Load and save UI adapter conversations through a `ConversationStore` with `conversation_store`
- Part of #11031
Posted by Claude Code on Douwe's behalf.
Why
#11431 added manage_message_history='server', where the app loads the stored history, passes it as message_history and saves result.all_messages() in on_complete. #11031 asks the adapter to do the loading and saving itself, through the ConversationStore that shipped in v2.65.0 (#10658). An app with a store then doesn't hand-write that glue, and it gets what the store adds: append-only saves, branches for regenerate and edit, a revision check against concurrent writers, and the deferred tool requests a paused run is waiting on.
New public surface
UIAdapter.conversation_store: ConversationStore | None = None. Passing a store means the history is held on the server, andmanage_message_historyis ignored: the client's new turn follows the'server'rules whatever it says. Its'client'default is unchanged.UIAdapter.conversation_scope: str | None = None, passed to the store'sloadandsave.- Both are typed parameters on
from_request()anddispatch_request()ofUIAdapter,VercelAIAdapterandAGUIAdapter. - After a save, the stream sends the stored entry ids: a transient Vercel AI
data-conversation-savedpart, or an AG-UIpydantic_ai_conversation_savedcustom event, each{'conversation_id': ..., 'entry_ids': [...]}. The hook that builds them (_conversation_saved_events) is private for now.
Behavior
await VercelAIAdapter.dispatch_request(
request, agent=agent, conversation_store=store, conversation_scope=user_id,
)
- Load: the run method loads the conversation the request names (Vercel AI chat
id, AG-UIthreadId, orconversation_id=) with the scope. Passingmessage_historyorusagetoo, or having no conversation id, raises aUserErrorat the call site. - Scope: a conversation saved with another scope, or with any scope when the adapter has no
conversation_scope, is treated as not found. (The store's ownscope=Nonereaches every scope; the adapter doesn't, since the ID comes from the client.)dispatch_requestanswers404before running anything. The other run methods reject the request with aUserError("Conversation 'x' was not found."), which reaches the client as the protocol error event. A conversation the store doesn't have at all is created. A client naming the conversation'new'also gets the404fromdispatch_request, since no store can hold one with that name. - New turn: #11431's rules apply unchanged: only the client's messages after its last response are used, and they're sanitized.
- Regenerate and edit: a resubmitted user message replaces its turn at save time. The adapter saves the kept stored history, the turn as the run stamped it, and what the run added, so
savecompares that with the stored history and keeps the replaced turn as a branch. A capability that trims or rewrites what the model is sent doesn't change what's stored, as on an ordinary turn. A regenerate whose run fails leaves the stored conversation as it was. - Pending calls: the loaded
Conversation.deferred_tool_requestssays what each pending call is waiting for. An approval or denial has to answer a call inapprovals, and a client tool result a call incalls. A result for an approval-gated call is dropped with the existing warning. An approval that doesn't match is rejected with #12313's error. - Run and save: the agent runs with
conversation=. On the run's result, the adapter callsstore.save(result, scope=...), which appends only the run's new messages. It then sends the saved-entries event, before the user'son_completeruns. - Parts the run adds to the new turn (core fix in
run.py, also for a plainagent.run(conversation=...)with a message appended before the run): a system prompt reinjected into the client's turn, aModelSettingsDeltaPart, or any other part added around the turn's own parts no longer makes the save compare the whole history. The save appends the turn as the run sent it, so a trimmed history or an effort change no longer replaces or re-saves the stored conversation, and a resubmitted first message is stored with its system prompt and stamps. Reported by rscholz98. - Conflict: a
ConversationConflict(another request saved in between) becomes aUserErrorasking the client to reload, delivered as the protocol error event. Nothing is saved. - Store failure: any other exception from the store, on load or save, reaches the client as a fixed message, as the protocol error event, or as a
500fromdispatch_requestif it happens before the run. AUserErrorthe store raises itself is sent as is.
Choices made during review
These came out of review findings. They're easy to change, so please check them:
- Store failures on the server: the client only gets a fixed message, so the adapter raises a
UserWarningnaming the conversation and the exception's type and text, and records the exception on the current OpenTelemetry span if one is recording. The span gets the type only, throughrecord_exception(..., include_content=False), because a store's message can quote stored messages and the adapter doesn't know the agent'sinclude_content. A failure while reporting can't replace the fixed message, so under-W errorthe warning is dropped rather than sent to the client. 500before the run:dispatch_requestanswers a store failure at its 404 check with a500holding the generic message as JSON, through a newconversation_load_failed_response.usage=with a store is rejected with aUserErrorat the call site, sinceconversation=andusage=can't be combined on a run. A store therefore can't share a usage budget across runs; supporting that would be a separate feature.- A client-sent
'new'ID gets a404, rather than theUserErroran app passingconversation_id='new'still gets, because a client's input shouldn't cause an unhandled exception. deps.statekeeps its order: a request rejected while loading the conversation has already written the client's state todeps.state. The comment and docstring say so. Moving that setup into the stream would change when its warning fires on every path.
Not in this PR
- Scope-qualified store keys. A store keys conversations by ID alone, so a tenant who creates an ID first holds it and its owner gets a
404. No tenant can reach another's messages. The docs say multi-tenant apps need unguessable or per-scope IDs; keying by scope as well would change the store's key model. - Saving failed or stopped turns depends on #12324 (
AgentRunError.conversationandcapture_run_conversation()). Once that merges, the run gets wrapped incapture_run_conversation()and the captured conversation is saved on failure. Until then, a run that fails or is stopped isn't saved, as the docs say. - The unanswered-stored-request case from #11431 (keep every merged UI message id on a request) needs that failure saving first.
- Streamed assistant ids on stored responses, and AG-UI
runIdas the defaultrun_id(@rscholz98's ask on #11031).
Verification
tests/test_vercel_ai.py:test_conversation_store_loads_and_saves_each_turn: the model sees each turn once, the stored history is right, the entry ids matchload_entries, and the chunks arrive in order._regenerate_branches._resubmission_keeps_a_history_a_capability_rewrote(including a capability that changes messages in place) and_resubmission_stores_the_turn_a_capability_rewrote_as_sent, on regenerate and edit._failed_regenerate_keeps_the_stored_turn._failed_resubmission_save_keeps_the_stored_turn_for_a_retry: on regenerate and edit after a capability trimmed the history, a failed save warns, records the exception type on the span and leaves the stored record and entries as they were, and the retry stores the turn once with one branch._tool_approval: a result for the approval-gated call is dropped, the approval runs it, anddeferred_tool_requestsis cleared._conflict_asks_the_client_to_reload._scope: not found, nothing runs.test_dispatch_request_conversation_store_scope:200for the owning scope,404for another scope and for no scope.test_conversation_store_without_a_scope_reaches_only_unscoped_conversations.test_dispatch_request_conversation_store_needs_a_conversation_id.test_conversation_store_ignores_manage_message_history: the model sees each turn once with an explicit'client'or'server'._misuse:message_historyorusagewith a store is rejected.
tests/test_ag_ui.py:test_conversation_store_loads_saves_and_resumes: aresume[]-only request against the stored thread, and the custom event payload.test_conversation_store_rejects_a_resume_for_a_call_not_pending.
tests/test_ui.py:test_conversation_store_without_protocol_saved_events_still_saves.test_conversation_store_announces_only_a_run_it_saved.- The signature test now covers the new parameters.
tests/ui_roundtrip:test_conversation_store_round_tripdrives two turns and a regenerate through the realAbstractChatandAbstractAgent.- The docs example
conversation_store_ui.pyruns intests/test_examples.py.
Decided: keep the 404
Douwe decided to keep the 404. The difference reveals nothing beyond what save already does through ConversationConflict.
- Existence of a conversation id. To tell a conversation saved under another scope (404 / "not found") from one the store doesn't have yet (created), the adapter calls
store.read_record(conversation_id), which ignores scope, and compares itsscope. The store's docs say a conversation saved with another scope "is treated as one the store doesn't have, so a guessedconversation_iddoesn't reach it". That still holds, since nothing is read or written. But the 404-versus-created difference lets a caller learn whether a conversation id exists under some other scope. The store's ownsavealready reveals this throughConversationConflict("already exists"). The alternative is to make noread_recordcall and let the save conflict, which also costs a model run before the error. Is the 404 the intended trade-off?
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.
🤖 Generated with Claude Code