Repository navigation
fix(core): keep exactly one tool result per tool call across message snapshots - #6294
Conversation
BenTaylorDev
left a comment
There was a problem hiding this comment.
This is close, and the substance is good — one thing needs changing before it lands.
What I verified in its favor
- The revocation race is real.
notifyAgentsChangedisprivate async(agent-registry.ts:748) andremoveAgent__unsafe_dev_onlyfires it withvoid, so it returns before the existingonAgentsChangedcleanup atcore.ts:518runs. A live observable can write tostateByRun/messageToRunfor a removed id in that window. The synchronousunsubscribeFromAgentcloses it. - I tried to break the new
onRunStartedEventguard and couldn't. My concern was thateffectiveRunIds.has(input)could be set by an earlier non-start event and cause a legitimateRUN_STARTEDto be dropped.@ag-ui/clientrejects that outright —AGUIError: First event must be 'RUN_STARTED', thrown before any subscriber callback — so the early-return can only fire on a duplicateRUN_STARTED, which is correct. - The
missing-ownerchange preserves existing behavior where it matters: the third call site passes"append", keepingmain's push-to-end fallback. - Tests are excellent — real
AbstractAgentsubclasses drivingcore.runAgent(), no mocks or spies anywhere, and they cover the edges I'd have asked for (ownerless placeholders, post-settle results, older-terminal-clearing-newer-run, post-revocation). Full suite passes: 60 files / 640 tests, and@copilotkit/core:buildsucceeds. Fork PRs don't get automatic CI here, so this is the first time any of it has run.
The blocker: stopPropagation starves other subscribers
onToolCallResultEvent returns { stopPropagation: true } whenever a tool message for that toolCallId already exists. The intent — stop @ag-ui/client inserting a duplicate — is right, but the flag does more than that. AgentStateMutation doesn't document its scope, so I tested it with two subscribers:
WITHOUT stopPropagation: { secondSubscriberSaw: true, toolMessageApplied: true }
WITH stopPropagation: { secondSubscriberSaw: false, toolMessageApplied: false }
It suppresses the default apply and every later subscriber. And there's a real consumer downstream — packages/web-inspector/src/index.ts:5361:
onToolCallResultEvent: ({ event }) => { this.recordAgentEvent(agentId, "TOOL_CALL_RESULT", event); }So: a frontend tool runs, run-handler inserts the result message, the runtime emits its canonical TOOL_CALL_RESULT, this code sees a message already present and suppresses — and the inspector's event timeline silently loses the entry. That flow is the one your own test "replaces a frontend placeholder with the canonical result event" exercises, so it's reachable in the normal path.
It's an observability gap rather than user-facing data loss, but it's the kind that's very hard to notice later. Returning the deduplicated { messages } as a mutation instead of stopPropagation should get you the same dedup without silencing the event — happy to look at whatever shape you prefer.
One thing to keep in mind (not blocking)
The existing lookup in insertToolResultMessage scans the whole array, so a toolCallId recycled from an earlier turn would skip insertion and suppress the follow-up, where main would have inserted a duplicate. I couldn't construct a reachable case — provider ids are unique and AG-UI's pairing already leans on that — so I'm not asking for a change, just flagging the assumption.
Sequencing
#6296 is approved and going in first; it touches the same runFinished && input.runId === subRunId heuristic you rewrite here, so this will need a rebase onto the new effectiveRunIds model. Worth doing that in the same pass as the stopPropagation change.
|
Revising my review here — I was wrong to block on this. The So: I'd like to land this. Two things:
For the record, what I verified while reviewing, so it isn't lost: the revocation race is real ( Approving as soon as it's rebased. |
5bbcfdd to
a5f7331
Compare
|
Rebased onto current The old The |
|
Picking this back up. The rebase did what I asked — 1. There's a conflict with
effectiveRunId = internalContinuation?.expectedRunId ?? input.runId;Note it's 2. const clearPendingResults = (input: RunAgentInput): void => {
pendingResults.delete(effectiveInput(input).runId);
};Both call sites ( The asymmetry at the same call site is what makes me read it as a slip rather than intent: |
a5f7331 to
3acf61e
Compare
|
Thanks for picking this back up and for spelling out both failure paths so precisely.
The |
|
Hey @rodboev, Thanks for sticking with this one — the diagnosis is right and the reconciliation fix is the correct shape. The second-turn test is a real one too: it drives a live agent through Two things to fix before this lands. The other one is On Last thing, and this one's on us to decide, not you: the run-isolation rework in here collides structurally with #6253, which keys runs off |
3acf61e to
254a59d
Compare
|
Thanks, I rebuilt this around the two production issues you called out. Snapshot recovery now happens through awaited terminal AG-UI messages mutations, so the apply pipeline owns the repaired history and the old in-place restore path is gone. Pre-start terminal callbacks use the failed input's identity and leave another active input alone. Result provenance is keyed by message ID and tool-call ID, normal result propagation stays active for later subscribers, and distinct results sharing a tool-call ID remain distinct. The generalized run-isolation and connect-replay identity work is split out for a separate PR aligned with #6253. The real two-turn reproduction and focused regressions pass locally. |
BenTaylorDev
left a comment
There was a problem hiding this comment.
Thanks for rebuilding this — the restructure did what Nathan and I asked for, and I checked each piece rather than taking it on faith.
What I verified in its favor
- The reconcile actually lands now. This was the whole point of Nathan's last note, so I traced it in
@ag-ui/clientrather than trusting the tests:onRunFinishedEvent/onRunErrorEventreturns go throughapplyMutation→emitUpdates()(apply/default.ts:830) and thenprocessApplyEventsassignsagent.messages. Subscribers also chain —runSubscribersWithMutation(agent/subscriber.ts:228) feeds each subscriber the previous one's mutated array, so a later subscriber can't clobber the repair. The dead in-place-splice path is gone. stopPropagationis gone, and your own test pins that a lateronToolCallResultEventsubscriber still fires. That closes my original blocker and the wider public-API concern Nathan raised.- The tests are the real pipeline. Every case drives
core.runAgent()against a realAbstractAgentsubclass — no hand-dispatched callbacks, no mocks. The second-turn reproduction is a genuine one. - Reconcile is idempotent.
RUN_ERRORreconciles atonRunErrorEventand again atonRunFailed; the second pass finds the exact match, sets nochanged, and returnsundefined. And the shallow-copy discipline is correct —applydeep-freezes messages in dev/test and nothing here mutates in place. - Scope and hygiene. Run isolation is genuinely split out; the diff is two files. No conflicts on the files you touch, no debris.
oxlintandoxfmtclean on both. Suite is 59/60 files — the 20core-inspector-metadatafailures reproduce identically onmainin my worktree, so they're not yours.
The blocker: this inserts a duplicate tool result on LangGraph
reconcilePendingResults decides "a real result already exists" by messageId. When a MESSAGES_SNAPSHOT carries the same toolCallId under a different message id with real content, it falls past both the exact-match and the placeholder branch and appends a second tool message.
That's the default LangGraph path, not an edge case:
integrations/langgraph/typescript/src/agent.ts:1093—TOOL_CALL_RESULTis dispatched withmessageId: randomUUID()integrations/langgraph/typescript/src/utils.ts:208— the snapshot's tool message usesid: message.id!, the checkpoint idintegrations/langgraph/typescript/src/agent.ts:721—getStateAndMessagesSnapshots()runs immediately beforeRUN_FINISHED, on every run
Python is the same shape (agent.py:1217 / :1268 vs utils.py:162). ADK middleware diverges too when emit_messages_snapshot=True (two independent UUIDs). By contrast AWS Strands and the Claude Agent SDK thread a single id through both events on purpose — Strands' ARCHITECTURE.md:77 gives "a duplicate tool message" as the reason.
Rather than hand-build the event stream, I instantiated the real @ag-ui/[email protected] LangGraphAgent against a stubbed LangGraph client (checkpoint state plus one on_tool_end chunk) and ran it through CopilotKitCore.runAgent(). The adapter emitted its own stream:
RUN_STARTED, STEP_STARTED, STATE_SNAPSHOT, RAW, TOOL_CALL_START,
TOOL_CALL_ARGS, TOOL_CALL_END, TOOL_CALL_RESULT, STEP_FINISHED,
STATE_SNAPSHOT, MESSAGES_SNAPSHOT, RUN_FINISHED
Same adapter, same stub, same stream — the only variable is state-manager.ts. On main the agent ends the turn with one tool message for that toolCallId; on this branch it ends with two:
[
{ "id": "lc-tool-1", "role": "tool", "toolCallId": "call_weather_1", "content": "72 and sunny" },
{ "id": "72192d78-8458-4e31-a03f-eddbcc88ed58", "role": "tool", "toolCallId": "call_weather_1", "content": "72 and sunny" }
]lc-tool-1 is LangGraph's checkpoint id, arriving via the snapshot; the UUID is the streamed TOOL_CALL_RESULT. Both go out on the next turn — prepareRunAgentInput only filters role === "activity", and there's no dedupe anywhere in packages/core.
For completeness on why main stays at one: apply/default.ts:551-590 treats MESSAGES_SNAPSHOT as a replace-by-id merge, so the streamed message is dropped and only the checkpoint one survives. This branch then re-adds the streamed one on top.
Two tool messages for one tool_call_id is the same malformed-history class this PR exists to fix, so I don't think we can ship it that way.
I can see this is deliberate — "preserves a real multi-part result beside a distinct canonical result" pins exactly this behavior, and the description says distinct results sharing a tool-call id stay distinct. I'd push back on the premise: two results for one tool_call_id isn't representable in OpenAI or Anthropic history anyway, so keeping both can't help the case it's protecting, while it provably breaks the common one. Treating "a non-placeholder tool message for this toolCallId already exists" as done — regardless of message id — gets you the #3884 repair and leaves LangGraph alone. The messageId identity still earns its keep for the placeholder-replacement branch.
Not blocking, but worth recording
1. I couldn't tie this to #3884. The event sequence in the issue has no MESSAGES_SNAPSHOT, and I confirmed that sequence already produces a correct turn-2 history on current main. I also pulled the reporter's exact pin, agent-framework-ag-ui==1.0.0b260311: it reuses one message_id across the result event and the snapshot entry (_run_common.py:243, :255), always includes tool results in the snapshot (_agent_run.py:575), and never clears FlowState mid-run. So their setup shouldn't reach this mechanism.
None of that makes the fix less real — snapshot-dropped results are a genuine bug and worth fixing on its own merits. But I'd rather we not auto-close #3884 on merge and instead ask the reporter for a raw event trace, so we don't leave them thinking it's handled.
2. Duplicated helper. normalizeToolResultContent and the "Forwarded to client" check are copied verbatim out of run-handler.ts:657-700. Two copies of one sentinel will drift — worth extracting to a shared helper both import.
3. Minor. hasStartedInput's second clause (!initializedInputs.has(input) && startedRunIds.has(input.runId)) can't be reached through runAgent/connectAgent, since onRunInitialized always runs first — it only serves hand-dispatched dispatchers. A comment saying so would save the next reader the trace. And the messages → _messages rename in handleMessagesSnapshot is unrelated to this fix; the parameter was already unused on main.
Happy to re-run my LangGraph repro against whatever you land on.
254a59d to
db40578
Compare
|
Thanks for the LangGraph reproduction. I rebuilt the rework around the provider obligation instead of the transport message ID.
I also removed the old tests that treated distinct message IDs for one |
|
This revision fixes the blocker. One thing left, and it's the rebase, not your logic. VerifiedI rebuilt the probe: real
I also ran the fix direction on the real adapter — checkpoint snapshot omits the tool message:
So the bug is real on current Blocker: a test of yours fails once merged with
|
Route canonical tool results through the AG-UI terminal messages mutation so subsequent runs retain results omitted by later snapshots.
Use the input fallback for pre-start terminals, preserve message associations, and match frontend placeholders by their normalized full content.
Leave AG-UI result propagation active and reconcile placeholders, duplicate identities, and pre-start lifecycle state without suppressing subscribers.
Exercise same-input finalization cleanup and a pre-start failure while an earlier input remains active.
Reconcile streamed tool results by call identity so divergent message IDs cannot append a second real result. Share placeholder normalization between state reconciliation and run-handler forwarding.
Track the started input through protocol errors so remapped run IDs clean up the active run without disturbing pre-start failures. Add lifecycle and multi-call reconciliation coverage.
db40578 to
d5fe120
Compare
|
Thanks, your merged-main probe pinned the remaining failure to the provenance expectation rather than the reconciliation logic.
The LangGraph and omitted-snapshot behavior remains covered while the test now matches current main's first-seen message provenance. |
@copilotkit/a2ui-renderer
@copilotkit/agentcore-runner
@copilotkit/angular
@copilotkit/channels
@copilotkit/channels-core
@copilotkit/channels-discord
@copilotkit/channels-intelligence
@copilotkit/channels-slack
@copilotkit/channels-teams
@copilotkit/channels-telegram
@copilotkit/channels-ui
@copilotkit/channels-whatsapp
@copilotkit/core
@copilotkit/react-core
@copilotkit/react-native
@copilotkit/react-textarea
@copilotkit/react-ui
@copilotkit/runtime
@copilotkit/runtime-client-gql
@copilotkit/sdk-js
@copilotkit/shared
@copilotkit/sqlite-runner
@copilotkit/voice
@copilotkit/vue
@copilotkit/web-components
@copilotkit/web-inspector
commit: |
BenTaylorDev
left a comment
There was a problem hiding this comment.
Thanks — this closes the blocker, and I verified it rather than taking the description on faith.
The LangGraph duplicate is gone
I re-ran the same repro I used last time: real @ag-ui/[email protected] LangGraphAgent against a stubbed LangGraph client, driven through CopilotKitCore.runAgent(). The adapter emits its own stream — TOOL_CALL_RESULT with randomUUID(), then MESSAGES_SNAPSHOT carrying the checkpoint id:
RUN_STARTED, STEP_STARTED, STATE_SNAPSHOT, RAW, TOOL_CALL_START, RAW,
TOOL_CALL_END, STEP_FINISHED, STEP_STARTED, STATE_SNAPSHOT, RAW,
TOOL_CALL_RESULT, STEP_FINISHED, STATE_SNAPSHOT, MESSAGES_SNAPSHOT, RUN_FINISHED
Same adapter, same stub — the only variable is state-manager.ts. On 254a59d44 (the commit I reviewed) the turn ends with two tool messages for call_weather_1 (lc-tool-1 plus a UUID). On this head it ends with one. Keying reconciliation by toolCallId was the right call.
The tests are load-bearing, not decorative
I broke each mechanism to confirm the suite actually pins it:
- remove the duplicate-removal loop in the
realIndexbranch → 4 tests fail - neuter the insert branch → 4 tests fail
- drop
clearPendingResultsfromonRunFinishedEvent→ the cross-server-run test fails
I tried to kill this and couldn't
A repaired result keeps its run association — AG-UI's apply created the message before the snapshot dropped it, so getRunIdForMessage still resolves to the originating run. I expected this to be a gap and checked; it isn't. Ownerless results are guarded. A regenerate-style snapshot drops the assistant owner too, so reconcile no-ops. The only behavior change I could construct is a subscriber returning stopPropagation on TOOL_CALL_RESULT — its result would now be re-inserted at RUN_FINISHED — and there is no such consumer here, nor a coherent history where that is desirable.
Verification
CI ran on this head. Green: the unit matrix 6/6 (Node 20/22/24 x React 18/19), build, check-types, bundle-size, compat-check, package-quality, oxlint, format, commitlint, check-binaries, check-config-files, and every integration test job.
The 22 Showcase: Build Check jobs show as cancelled. That is not this PR: each one burned exactly its timeout-minutes budget (15 for integrations, 10 for shell) after the Depot build stalled ~90s in, and a timed-out job reports as cancelled. They also could not have tested this change — the integration Docker contexts do not include packages/, and every showcase package pins published @copilotkit/* at 1.61.2. The one job in that workflow that does compile packages/core is build-angular, which passed.
Locally, on the branch merged into current main (it merges clean; main has touched nothing this PR touches): core suite 684 passed, with the one failing file (core-inspector-metadata) failing identically on main in the same worktree; oxlint and oxfmt clean; tsdown build succeeds; and the new helper stays internal — nothing in dist/index.d.mts.
Earlier notes
All addressed: the sentinel helper is extracted to one module, hasStartedInput is gone entirely, and the description no longer auto-closes #3884 — I will follow up there asking the reporter for a raw event trace.
One trivial leftover, not worth another round: the messages -> _messages rename in handleMessagesSnapshot is unrelated to this fix.
I bless the code with a glad heart.
fix(core): keep exactly one tool result per tool call across message snapshots
Summary
When an agent emits a MESSAGES_SNAPSHOT, AG-UI merges it by message id and can drop a tool message that TOOL_CALL_RESULT created. The next turn then sends an assistant tool call without its paired result, which providers reject.
This PR records observed tool results for the current input and repairs history through AG-UI's returned-messages mutation channel. It keeps one tool message per toolCallId and composes with current main's first-seen message provenance.
Root cause
@ag-ui/client applies events against its own cloned messages array. TOOL_CALL_RESULT creates a tool message and inserts it after its assistant owner. A later MESSAGES_SNAPSHOT is a replace-by-id merge, so a missing tool entry can remove that result. packages/core had no record of the result event, so there was nothing to restore it from.
What changed
The reconciliation rule
toolCallId is the decisive identity:
On the LangGraph duplicate
LangGraph can represent one result with different streamed and checkpoint message ids. The regression fixture keeps the streamed result before the snapshot and places both representations in the snapshot. The final history and next-turn input contain one result for that toolCallId.
Two tool messages for one toolCallId are one malformed history class. Keying reconciliation by toolCallId makes that duplicate unrepresentable while preserving normal event delivery.
What this does not do
Relationship to #3884
Related to #3884, but not marked as closing it. The event sequence in that issue has no MESSAGES_SNAPSHOT, and it already produces a correct turn-2 history on current main. Snapshot-dropped results are a real bug worth fixing independently, while the reporter's case still needs a raw event trace.
Test plan
All cases drive CopilotKitCore.runAgent() against real AbstractAgent subclasses.