Add `manage_message_history` to UI adapters so a server-held history isn't sent to the model twice

Merged
DO
1mo ago
+2442-43

Posted by Claude Code on Douwe's behalf.

Closes #11372

Why we make these changes

The UI adapters run on [*message_history, *client_messages], but useChat and @ag-ui/client send the whole conversation on every request, so an app that keeps the history on the server, as the trust-model docs recommend, sends every earlier turn to the model twice. Following Douwe's decision, this adds an opt-in mode in which the server's history is the conversation and only the client's new turn is used, plus a warning for the default mode.

New public surface

  • UIAdapter.manage_message_history: Literal['client', 'server'] = 'client', also accepted by from_request() / dispatch_request() on UIAdapter, VercelAIAdapter and AGUIAdapter.

User-visible behavior

# useChat posts [hi, hello, and now?]; the server stored [hi, hello]
VercelAIAdapter(agent, run_input=body).run_stream(message_history=stored)
# before and with the default: model sees hi, hello, hi, hello, and now? (now with a UserWarning)
VercelAIAdapter(agent, run_input=body, manage_message_history='server').run_stream(message_history=stored)
# model sees hi, hello, and now?

Under 'server': a new turn starting with the UI id of a stored user message (regenerate, edit, retried submit) cuts the stored history before it, keeping any tool results stored with that message; an unknown id appends, except that a regenerate of a message the server doesn't hold is rejected; a client tool result is kept only for a call still unanswered at the end of the stored history (others dropped with a warning); approvals still come from the request; sanitization and compaction-part dropping apply to the new turn.

Rejected regenerates raise a UserError, which run_stream_native hands back on the stream as the protocol's error event (Vercel AI error chunk, AG-UI RUN_ERROR), so dispatch_request answers 200 with that event. That's the path the adapters already use for a request they reject once it runs (a malformed deferred_tool_results), and it's how ag-ui#2186 proposes HISTORY_UNAVAILABLE: a RUN_ERROR, not an HTTP status. No new exception class: no caller needs to tell this rejection apart yet, and AG-UI's error code isn't in the protocol yet. The same rejection hits the AI SDK's regenerate() retry of a run that failed or was stopped, as that turn isn't stored; the error and docs say so and point to resending the message, and #11031's store removes the case. Matching needs the UI message ids an adapter run stores, so the docs also say to pass the history an adapter run produced (result.all_messages() in on_complete): one persisted another way rejects every Vercel AI regenerate and appends edits.

THREAT_MODEL.md now describes the 'server' boundary: only the new turn crosses it, the client can only rewind to its own stored user prompts, and the application still authorizes the conversation it loads.

On AG-UI, a client that sends only its new messages can return a frontend tool's result without the call it answers; under 'server' it loads against the stored history's pending call (found in @rscholz98's production test).

Verification

  • tests/test_ui.py: test_client_message_history_* (warning, no false positive), test_server_message_history_* (new turn only, resubmission cut only at a user message, cut/append and the cut in the helper's result, stale regenerate rejected, stored tool results kept on a cut, first turn, stale tool results, sanitization), test_dispatch_request_forwards_manage_message_history
  • tests/test_vercel_ai.py: follow-up with full and last-only messages, regenerate and edit, a stale regenerate's error event through dispatch_request, frontend tool output, v6 approval approved and denied (tool runs once), dispatch forwarding
  • tests/test_ag_ui.py: frontend tool result and the turn after it, the same from a client that sends only its new turn, a result for no pending call, resume[] interrupt, dispatch forwarding
  • tests/ui_roundtrip/test_ui_roundtrip.py: new test_server_held_history_wire_request drives the real AI SDK and AG-UI JS clients, which send their whole history, and checks every provider request equals the server-only one; test_server_held_history_has_none_of_the_client_round_trip_gaps pins that the #11184 gaps (appended_instructions family, no_output_feedback, AG-UI activities) don't occur there, leaving only the earlier-run enqueued system prompt (enqueued_system_prompt), tracked on #11184
  • tests/test_history_append_only.py: ui:server_held_history_* runs the append-only check across turns through both adapters in 'server' mode (each request strictly extends the previous; the same cases fail in 'client' mode), and test_server_held_ui_history_keeps_openai_responses_chaining shows a later turn sending previous_response_id and only the new turn

What changes for existing users

Nothing, except a new UserWarning when client messages repeat UI message ids already in message_history. A history without those ids (built by hand or by agent.run()) can't be told apart, so that case is documented rather than warned about.

Open decisions

Settled since the first round (decisions, scope): cut only at user messages, reject stale regenerates, merge as the #11372 fix without a store.

  1. Store as an additive 'server'-only parameter (#11031): confirmed by @rscholz98 against production AG-UI data; nothing here needs renaming.
  2. Kept for #11031: a failed or stopped run isn't stored (documented); streamed assistant ids aren't stored on responses.
  3. Tracked on #11184: an earlier-run enqueued system prompt is replaced by ReinjectSystemPrompt(replace_existing=True) even in stored history.
  4. Stored history ending with an unanswered request (a failed run saved via on_cancel, or #11031's store): the client resends it merged with its new message, whose UI id hides the resubmission, so the model sees it twice. Settled as option 3 (decision): documented in the overview with workarounds and recorded as a known round-trip gap tracked on #11031; options in this comment.
  5. Saved records: saving all_messages() over the stored history lets a resubmission cut drop later turns; documented (@rscholz98's option 2), and #11031's store keeps the cut as a branch.
  6. Still open from the issue: 'server' as the default in v3.
PR decisions

2026-10-26 · resubmission matches any stored request by UI id · iter -

  • Decision: In 'server' mode the new turn's first message cuts the stored history at the first ModelRequest with the same UI message id, whether it carries a user prompt or not
  • Why: User-message ids are the ones that survive persistence; matching any request also turns a retried frontend-tool-output submit into a replacement instead of a dropped return
  • Source: https://github.com/pydantic/pydantic-ai/issues/11372

2026-10-26 · pending tool calls are the last stored response · iter -

  • Decision: A client tool result is kept only for an unanswered call of the stored history's last ModelResponse (reusing _dangling_tool_calls_by_response); a second result for the same call is dropped too
  • Why: Matches the issue rule (unanswered at the end of the stored history) and keeps duplicate tool_call_ids, which providers reject, off the wire
  • Source: https://github.com/pydantic/pydantic-ai/issues/11372

2026-10-26 · compaction parts dropped in 'server' mode even on the first turn · iter -

  • Decision: _drop_compaction_parts runs when message_history is non-empty or manage_message_history='server'
  • Why: In 'server' mode the client never owns the history, so a client compaction boundary is never honored
  • Source: https://github.com/pydantic/pydantic-ai/issues/11372

2026-10-26 · server-held round-trip property · iter -

  • Decision: Added test_server_held_history_wire_request to tests/ui_roundtrip (real JS clients, one provider); only enqueued_system_prompt has a recorded gap, caused by the adapter's ReinjectSystemPrompt(replace_existing=True), not by this change
  • Why: Strongest integration evidence that the model sees each turn exactly once with clients that send full history
  • Source: https://github.com/pydantic/pydantic-ai/issues/11372

2026-10-26 · pre-push review 1 of 3 at bed1a6936066e5f354736b101afd31281b8d64c8 · iter -

2026-10-26 · pre-push review 1 of 3 at bed1a6936066e5f354736b101afd31281b8d64c8 · iter -

2026-10-26 · pre-push review 2 of 3 at bed1a6936066e5f354736b101afd31281b8d64c8 · iter -

2026-10-26 · pre-push review 2 of 3 at bed1a6936066e5f354736b101afd31281b8d64c8 · iter -

2026-10-26 · carry-over of unstored client turns left to Douwe · iter -

  • Decision: Under 'server', a client user message after an incomplete (unstored) run is not carried over; documented instead of changing the settled rules
  • Why: Changing it goes beyond the rules in Douwe's decision comment; listed as an open decision in the PR
  • Source: https://github.com/pydantic/pydantic-ai/issues/11372

2026-10-26 · pre-push review 3 of 3 at be9b79b22546f5540ab34daca2a20ef66a0187bc · iter -

2026-10-26 · pre-push review 3 of 3 at be9b79b22546f5540ab34daca2a20ef66a0187bc · iter -

2026-10-26 · cut request keeps its tool results · iter -

  • Decision: When a resubmission cuts a stored request that also carries tool results (merged in at run start), those results stay as a request of their own; client copies of them are dropped without a warning, other unpending results still warn
  • Why: Reproduced Veria's finding: an edit let a client replace a server-recorded tool return (test_server_message_history_resubmission_keeps_the_stored_tool_results_it_cuts); pre-push budget exhausted, pushed after local checks at 2d9a139b34224a9ac8ecd12f5aab694655214dca
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431#discussion_r4382707388

2026-10-26 · resubmission cuts only at a stored user message · iter -

  • Decision: Under 'server' the stored history is cut only at a request that holds a UserPromptPart with the resubmitted UI id; any other id match is ignored
  • Why: Douwe's decision 1: edits and regenerates only target user messages, and a client must not cut the history at any request id it knows
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431#issuecomment-6428914530
  • Supersedes: resubmission matches any stored request by UI id

2026-10-26 · stale regenerate is a UserError on the stream · iter -

  • Decision: A regenerate (Vercel RegenerateMessage, via a private UIAdapter._regenerates hook) whose message isn't stored raises UserError, which run_stream_native hands back as the stream's protocol error event (Vercel error chunk, AG-UI RUN_ERROR) under HTTP 200; no new exception class
  • Why: Douwe's decision 2; reuses the established deferred_tool_results rejection path, and ag-ui#2186 surfaces HISTORY_UNAVAILABLE as a RUN_ERROR event, not an HTTP status; the RUN_ERROR code itself isn't in the protocol yet, so it isn't emitted
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431#issuecomment-6428914530

2026-10-26 · 'client' overlap without UI ids is documented, not detected · iter -

  • Decision: No content-based overlap detection; the field docstring and overview say a history without UI ids duplicates the client's full conversation silently
  • Why: Comparing content would warn falsely for a legitimate server-only preamble that matches client text; ids are the only proof of overlap
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431#issuecomment-6428914530

2026-10-26 · new-turn helper returns the cut · iter -

2026-10-26 · server-held round-trip gap is enqueued_system_prompt · iter -

  • Decision: The only server_wire known gap is the enqueued_system_prompt scenario (ReinjectSystemPrompt replacing an earlier-run enqueued system prompt), now citing #11184; enqueued_messages, appended_instructions family and no_output_feedback have no server_wire gap, pinned by test_server_held_history_has_none_of_the_client_round_trip_gaps
  • Why: The decision named enqueued_messages, but in these scenarios the earlier-run enqueued system prompt is the enqueued_system_prompt scenario; enqueued_messages passes in server mode
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431#issuecomment-6429044186

2026-10-26 · append-only and chaining checks run through the adapters · iter -

  • Decision: tests/append_only.py Scenario.ui_adapter runs each run through VercelAIAdapter/AGUIAdapter in 'server' mode with the client sending its whole dumped conversation; added as AGENT_FEATURES cases plus a Responses previous_response_id test
  • Why: Douwe's required tests 2 and 3; verified the append-only cases fail when switched to 'client'
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431#issuecomment-6429044186

2026-10-26 · push past the exhausted pre-push budget at c4f20dd9e5ab58110d54265fb694411ec17e9a4b · iter -

  • Decision: No fourth pre-push review: the budget (3 of 3) was used before this round; pushed after targeted local checks, with CI and a fresh douwebot verdict as the review
  • Why: pushing-commits-to-the-repo: after the third review, remediate, run local checks, do not dispatch a fourth review, continue with push, CI and hosted review
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431

2026-10-27 · THREAT_MODEL.md covers server-held history · iter -

  • Decision: Added one paragraph to 'UI history and server-state disclosure'; no failure-pattern row (that table lists published advisories) and no evaluation question (they're component-agnostic); system content is described as stripped unless manage_system_prompt='client', matching sanitize_messages
  • Why: Douwe's follow-up: the model's own 'Keeping this model current' rule covers a new input path; wording checked against _take_new_turn and _run_message_history
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431

2026-10-27 · push past the exhausted pre-push budget at 6665ed16734824f394d0684ccfce26c7cfc70aa8 · iter -

  • Decision: No pre-push review (budget 3 of 3 used); pushed after the classifier, docs and pre-commit checks, with CI, UI Security Review and a fresh douwebot verdict as review
  • Why: pushing-commits-to-the-repo rule after the third review
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431

2026-10-27 · stale-regenerate error covers retries of unstored runs · iter -

  • Decision: Kept the rejection (Douwe's decision 2) and reworded the UserError and the overview: the message may never have been stored (a failed or stopped run the AI SDK retries with regenerate()) or the tab is stale; advise sending the message again as a new one; whether to accept such retries instead is left to #11031, whose store saves failed and stopped runs
  • Why: douwebot finding on 6665ed16: without assistant ids the adapter can't tell the cases apart, and the old text blamed a stale tab and advised a reload that loses the retried message; pre-push budget exhausted, pushed at c6ee3f7a7340bb17594d43337650cdef54dff7bf after targeted checks
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431#discussion_r4384206551

2026-10-27 · douwebot round on c6ee3f7a · iter -

  • Decision: Moved the OpenAIResponsesModelSettings import to a module-level try_import (test-only, exempt delta); kept warning stacklevels as they are, matching the existing state warning in run_stream_native, which also points into the library for run_stream/dispatch_request callers
  • Why: Blocking finding fixed at 7baa8884ce80e5fa9c4323c4c2b69b737bf4fe48; the optional stacklevel note can't reach the user's frame for every entry point without threading a level through, which no other adapter warning does
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431

2026-10-27 · AG-UI new-turn-only tool results load against the stored call · iter -

  • Decision: Under 'server', AGUIAdapter fills a ToolMessage's missing AssistantMessage with the stored history's pending call (private _server_held_client_messages hook; pending_tool_calls/warn_dropped_tool_results shared with _take_new_turn); a result for a call that isn't pending is dropped with the usual warning instead of failing the load; 'client' mode unchanged
  • Why: Reproduced @rscholz98's production report and douwebot's finding (ValueError -> 500 for the documented middleware); dropping rather than a UserError keeps the settled 'drop other tool results with a warning' rule; pre-push budget exhausted, pushed at 81378f0e331c09ffa1cf0661dec2158ecd935fe2 after targeted checks
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431#issuecomment-6431810558

2026-10-27 · dropped tool-result ids computed once · iter -

2026-10-27 · harness log-limit test flake on 2b19e078 · iter -

2026-10-27 · shared server_history_agent test helper · iter -

2026-10-27 · resubmission matching needs adapter-produced history · iter -

2026-10-27 · flake on c31203d6 · iter -

2026-10-27 · resubmission cut overwrites a saved record · iter -

2026-10-27 · stored unanswered tail recorded as a server_wire gap · iter -

  • Decision: main's new withdrawn_settings_change scenario (stored history ends with an unanswered request) duplicates that request in 'server' mode: the client resends it merged with its new message, and the merged request keeps only the new message's UI id; recorded as a known gap and escalated to Douwe rather than changing the matching rules
  • Why: A fix needs the loaders to keep every merged UI message id, or a content match, both beyond the settled rules; test-only delta, pre-push budget exhausted, pushed at 0b6d85371887759ade19cc3fdf7f406a68ff3da6
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431

2026-10-27 · unanswered stored request documented, tracked on #11031 · iter -

2026-10-27 · flakes on 0f44a36d · iter -

2026-10-27 · regenerate bullet split · iter -

  • Decision: Per Douwe, split the overview bullet into 'Regenerating and editing' (cut rule, stale-regenerate rejection), 'Saving the stored record' and 'Histories without UI message ids'; reordered the THREAT_MODEL.md paragraph so the record clause follows the client's limits
  • Why: douwebot optional finding accepted by Douwe; docs-only, pre-push budget exhausted, pushed at 61a9bdc70b98263d90f00105dc7202d032b3ef0f after docs tests
  • Source: https://github.com/pydantic/pydantic-ai/pull/11431

2026-10-27 · prefix-moving gap marked for the FunctionModel prefix check · iter -

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.