Load and save UI adapter conversations through a `ConversationStore` with `conversation_store`

Merged
DO
24d ago
+1649-79

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, and manage_message_history is 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's load and save.
  • Both are typed parameters on from_request() and dispatch_request() of UIAdapter, VercelAIAdapter and AGUIAdapter.
  • After a save, the stream sends the stored entry ids: a transient Vercel AI data-conversation-saved part, or an AG-UI pydantic_ai_conversation_saved custom 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-UI threadId, or conversation_id=) with the scope. Passing message_history or usage too, or having no conversation id, raises a UserError at 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 own scope=None reaches every scope; the adapter doesn't, since the ID comes from the client.) dispatch_request answers 404 before running anything. The other run methods reject the request with a UserError ("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 the 404 from dispatch_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 save compares 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_requests says what each pending call is waiting for. An approval or denial has to answer a call in approvals, and a client tool result a call in calls. 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 calls store.save(result, scope=...), which appends only the run's new messages. It then sends the saved-entries event, before the user's on_complete runs.
  • Parts the run adds to the new turn (core fix in run.py, also for a plain agent.run(conversation=...) with a message appended before the run): a system prompt reinjected into the client's turn, a ModelSettingsDeltaPart, 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 a UserError asking 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 500 from dispatch_request if it happens before the run. A UserError the 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 UserWarning naming 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, through record_exception(..., include_content=False), because a store's message can quote stored messages and the adapter doesn't know the agent's include_content. A failure while reporting can't replace the fixed message, so under -W error the warning is dropped rather than sent to the client.
  • 500 before the run: dispatch_request answers a store failure at its 404 check with a 500 holding the generic message as JSON, through a new conversation_load_failed_response.
  • usage= with a store is rejected with a UserError at the call site, since conversation= and usage= 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 a 404, rather than the UserError an app passing conversation_id='new' still gets, because a client's input shouldn't cause an unhandled exception.
  • deps.state keeps its order: a request rejected while loading the conversation has already written the client's state to deps.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.conversation and capture_run_conversation()). Once that merges, the run gets wrapped in capture_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 runId as the default run_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 match load_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, and deferred_tool_requests is cleared.
    • _conflict_asks_the_client_to_reload.
    • _scope: not found, nothing runs.
    • test_dispatch_request_conversation_store_scope: 200 for the owning scope, 404 for 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_history or usage with a store is rejected.
  • tests/test_ag_ui.py:
    • test_conversation_store_loads_saves_and_resumes: a resume[]-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_trip drives two turns and a regenerate through the real AbstractChat and AbstractAgent.
  • The docs example conversation_store_ui.py runs in tests/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 its scope. The store's docs say a conversation saved with another scope "is treated as one the store doesn't have, so a guessed conversation_id doesn'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 own save already reveals this through ConversationConflict ("already exists"). The alternative is to make no read_record call 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