Skip to content

fix(core): keep exactly one tool result per tool call across message snapshots - #6294

Merged
BenTaylorDev merged 9 commits into
CopilotKit:mainfrom
rodboev:fix/3884-tool-result-history
Aug 24, 2026
Merged

BenTaylorDev merged 9 commits into
CopilotKit:mainfrom
rodboev:fix/3884-tool-result-history

Conversation

@rodboev

@rodboev rodboev commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

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

  • StateManager records one ToolCallResultEvent per toolCallId on the current RunAgentInput. Events keep flowing through AG-UI's normal path.
  • At RUN_FINISHED, RUN_ERROR, and onRunFailed, reconciliation returns a fresh message array only when a repair is needed. AG-UI applies it through its normal mutation chain.
  • Pending results are released at each finished server-run boundary and at finalization, so a later server run under one input cannot resurrect a result removed by its snapshot.
  • The "Forwarded to client" sentinel classifier now lives in one internal module used by StateManager and run-handler.ts.

The reconciliation rule

toolCallId is the decisive identity:

  • No assistant owner for the call: do nothing.
  • A real tool message already exists for the call under any message id: keep one result and remove duplicate same-call representations.
  • Only placeholders exist: promote one to the canonical result and drop the rest.
  • Nothing exists: insert the result after its assistant owner and its contiguous tool messages.

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

  • No direct agent.messages mutation, setMessages from a subscriber, or stopPropagation. AG-UI remains the owner of message application, ordering, and publication.
  • Reconciliation does not infer or rewrite run identity. Current main's event-derived run identity and first-seen snapshot provenance remain intact.
  • No message-to-run association is performed inside reconciliation.
  • No public API change, export, version bump, or changeset.

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.

  • Two-turn reproduction: a snapshot omits the result, and the next turn receives exactly one result.
  • LangGraph shape: differing message ids under one toolCallId produce one surviving tool message in real event-before-snapshot order.
  • Repeated server runs under one input do not resurrect a result removed by a later snapshot.
  • Terminal mutation, normal result propagation, duplicate results, placeholders, ownerless results, ordering, RUN_ERROR, local failure, and run ownership remain covered.
  • The focused core tests pass 32/32. Core typecheck, build, formatting, lint, and diff checks pass. CI checkboxes remain for GitHub.

@BenTaylorDev BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. notifyAgentsChanged is private async (agent-registry.ts:748) and removeAgent__unsafe_dev_only fires it with void, so it returns before the existing onAgentsChanged cleanup at core.ts:518 runs. A live observable can write to stateByRun/messageToRun for a removed id in that window. The synchronous unsubscribeFromAgent closes it.
  • I tried to break the new onRunStartedEvent guard and couldn't. My concern was that effectiveRunIds.has(input) could be set by an earlier non-start event and cause a legitimate RUN_STARTED to be dropped. @ag-ui/client rejects that outright — AGUIError: First event must be 'RUN_STARTED', thrown before any subscriber callback — so the early-return can only fire on a duplicate RUN_STARTED, which is correct.
  • The missing-owner change preserves existing behavior where it matters: the third call site passes "append", keeping main's push-to-end fallback.
  • Tests are excellent — real AbstractAgent subclasses driving core.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:build succeeds. 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.

@BenTaylorDev

Copy link
Copy Markdown
Contributor

Revising my review here — I was wrong to block on this.

The stopPropagation finding stands technically: it does suppress later subscribers, and web-inspector/src/index.ts:5361 does lose its TOOL_CALL_RESULT timeline entry when a result message already exists. But weighing it again, that's a dev-tool observability gap, and this PR fixes tool results disappearing from history — which produces invalid provider requests and breaks conversations. Holding a user-facing fix for a devtools entry is the wrong trade, and I made it.

So: I'd like to land this. Two things:

  1. Rebase onto current main. fix(react-core): preserve logical run identity across HITL resolve #6296 merged (7e502dd4a4), and it replaced the runFinished && input.runId === subRunId heuristic that this PR rewrites. That's a real design merge rather than a mechanical conflict resolution — your effectiveRunIds model needs to absorb its continuation-marker intent. Shout if you'd rather talk through the shape before doing it.
  2. stopPropagation becomes a follow-up, not a condition of merge. Returning the deduplicated { messages } as a mutation instead would get the same dedup without silencing the event, whenever you or someone else picks it up.

For the record, what I verified while reviewing, so it isn't lost: the revocation race is real (notifyAgentsChanged is async, and removeAgent__unsafe_dev_only fires it with void); I tried to break the new onRunStartedEvent guard and couldn't, because @ag-ui/client rejects any run whose first event isn't RUN_STARTED; the missing-owner change preserves the push-to-end fallback at the third call site; and the full @copilotkit/core suite passes at 60 files / 640 tests with core:build clean. Fork PRs get no automatic CI here, so that was the first run of any of it.

Approving as soon as it's rebased.

@rodboev

rodboev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and refolded the continuation-marker intent from the merged #6296 into the effective-run-id model.

The old runFinished && input.runId === subRunId heuristic that #6296 replaced has been absorbed into the captureEffectiveRunId decision: a new ordinary same-ID run after a settled run gets a fresh isolated run ID, while an internal continuation handoff (markNextRunAsContinuation) and an explicit resume (input.resume or forwardedProps.command.resume) preserve their logical run identity. The effectiveRunIds WeakMap that distinguishes late callbacks from an older pipeline is kept alongside the scalar continuation guard.

The stopPropagation return in onToolCallResultEvent stays as left for a follow-up. The full @copilotkit/core suite passes at 60 files / 650 tests, including the #6296 continuation regressions (state-manager.test.ts "Multiple Runs" section) and the react-core HITL follow-up tests.

@BenTaylorDev

Copy link
Copy Markdown
Contributor

Picking this back up. The rebase did what I asked — captureEffectiveRunId absorbs #6296's continuation-marker intent cleanly, and I confirmed the continuation regressions in state-manager.test.ts "Multiple Runs" still pass under it. Two things, both small.

1. There's a conflict with main again — sorry, that one's on us. You rebased the same day and it went stale while waiting on me to come back to it; that's our review latency, not anything you did.

696c44244b ("stop HITL continuations reusing the originating run id on the wire") landed after your rebase and rewrites the same subRunId derivation this PR replaces. It's the only conflict and the resolution is one line — in captureEffectiveRunId's else-branch:

effectiveRunId = internalContinuation?.expectedRunId ?? input.runId;

Note it's effectiveRunId, not subRunId as the raw conflict hunk reads — subRunId is assigned from it two lines down. run-handler.ts and core.ts auto-merge, and pinRunIdOnWire survives intact. I resolved it locally and the full @copilotkit/core suite is green at 61 files / 652 tests.

2. clearPendingResults re-derives the run id and clears the wrong run. state-manager.ts:202

const clearPendingResults = (input: RunAgentInput): void => {
  pendingResults.delete(effectiveInput(input).runId);
};

Both call sites (onRunFailed, onRunFinalized) pass an already-effective input — a fresh spread, so it isn't in the effectiveRunIds WeakMap. effectiveInput() re-derives it as subRunId ?? input.runId and hands back the current run's id rather than the settling run's. When an older run's onRunFinalized lands while a newer run is in flight, it deletes the newer run's buffered results, nothing reconciles at that run's finish, and #3884 comes back — on precisely the path the run-isolation model exists to protect.

The asymmetry at the same call site is what makes me read it as a slip rather than intent: clearActiveRun(effective) reads effective.runId directly and is correct.

@rodboev
rodboev force-pushed the fix/3884-tool-result-history branch from a5f7331 to 3acf61e Compare August 12, 2026 15:43
@rodboev

rodboev commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for picking this back up and for spelling out both failure paths so precisely.

  1. I rebased onto current main and resolved the captureEffectiveRunId overlap in packages/core/src/core/state-manager.ts with internalContinuation?.expectedRunId ?? input.runId. That keeps the continuation's logical identity while preserving pinRunIdOnWire in packages/core/src/core/run-handler.ts, so the follow-up still gets a distinct wire ID.
  2. I changed clearPendingResults to treat its argument as already effective and delete by that captured runId directly. Both onRunFailed and onRunFinalized now reuse one captured effective input for terminal cleanup; onRunFinalized also uses it for reconciliation, so a late callback from an older run can't clear a newer run's buffered tool results.
  3. The regressions in packages/core/src/__tests__/state-manager-tool-result-history.test.ts cover both terminal callbacks with a newer run in flight and verify that the newer run still reconciles its result exactly once under its own run ID.

The stopPropagation follow-up remains separate, as discussed.

@NathanTarbert

Copy link
Copy Markdown
Contributor

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 runAgent() so the actual apply pipeline runs, which is exactly the kind of test this area has been missing.

Two things to fix before this lands. restorePendingPlaceholders doesn't actually do anything in the real pipeline — defaultApplyEvents clones history at the start (apply/default.ts:98) and then assigns agent.messages from its own clone after subscribers run, so the in-place splice at state-manager.ts:270 gets overwritten right after. Behavior still comes out correct because reconcilePendingResults re-applies at RUN_FINISHED, but that means the restore path is dead code, and the test at :676 only looks like it covers it because that harness hand-dispatches callbacks with no pipeline behind them. Either return { messages } as a mutation from onMessagesSnapshotEvent, or drop the path and let reconcile own it — and if you keep it, cover it through core.runAgent().

The other one is settleRun on a run that fails before RUN_STARTED. subRunId is only assigned on RUN_STARTED, so an HTTP 4xx or auth failure clears pendingResults and activeRun under the previous run's id. That's a common path for the folks hitting this issue. Falling back to input.runId in the terminal callbacks when there's no captured effective id should do it.

On stopPropagation — agreed with Ben that it shouldn't block this, but worth noting it's wider than the inspector: agent.subscribe({ onToolCallResultEvent }) is public API and is the workaround people were told to use for this exact bug, so app subscribers registered after StateManager go quiet too. Returning the deduplicated { messages } mutation instead would cover it whenever you get to it.

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 event.runId because one connect replay can carry several server runs under a single input.runId — your WeakMap-per-input model collapses those into one. We'll sort out the ordering on our side, but if you're up for splitting the run-isolation piece into its own PR, the tool-result fix could land on its own much faster.

@rodboev
rodboev force-pushed the fix/3884-tool-result-history branch from 3acf61e to 254a59d Compare August 14, 2026 19:01
@rodboev

rodboev commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

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 BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/client rather than trusting the tests: onRunFinishedEvent / onRunErrorEvent returns go through applyMutation → emitUpdates() (apply/default.ts:830) and then processApplyEvents assigns agent.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.
  • stopPropagation is gone, and your own test pins that a later onToolCallResultEvent subscriber 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 real AbstractAgent subclass — no hand-dispatched callbacks, no mocks. The second-turn reproduction is a genuine one.
  • Reconcile is idempotent. RUN_ERROR reconciles at onRunErrorEvent and again at onRunFailed; the second pass finds the exact match, sets no changed, and returns undefined. And the shallow-copy discipline is correct — apply deep-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. oxlint and oxfmt clean on both. Suite is 59/60 files — the 20 core-inspector-metadata failures reproduce identically on main in 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_RESULT is dispatched with messageId: randomUUID()
  • integrations/langgraph/typescript/src/utils.ts:208 — the snapshot's tool message uses id: message.id!, the checkpoint id
  • integrations/langgraph/typescript/src/agent.ts:721 — getStateAndMessagesSnapshots() runs immediately before RUN_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.

@rodboev
rodboev force-pushed the fix/3884-tool-result-history branch from 254a59d to db40578 Compare August 17, 2026 00:43
@rodboev rodboev changed the title fix(core): preserve tool results in subsequent-turn history fix(core): keep exactly one tool result per tool call across message snapshots Aug 17, 2026
@rodboev

rodboev commented Aug 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the LangGraph reproduction. I rebuilt the rework around the provider obligation instead of the transport message ID.

  1. Pending result provenance is now one event per toolCallId on each input. Terminal reconciliation keeps the first real result for that call, removes same-call duplicate representations, promotes only exact frontend placeholders, and inserts a missing result only when an assistant owner exists.

  2. The repair still returns AG-UI messages mutations, so normal result propagation and later public subscribers remain active. The target-specific lifecycle and association machinery is removed, and run isolation stays with the separate follow-up aligned with PR fix(core): preserve run IDs across SSE connect replay #6253.

  3. The duplicated Forwarded to client classifier is extracted into one internal helper used by both StateManager and run-handler.ts. The LangGraph-shaped regression asserts one checkpoint-authoritative result in final history and in turn two.

I also removed the old tests that treated distinct message IDs for one toolCallId as separate real results. The issue's literal trace does not include this snapshot boundary, so I left #3884 as a reference rather than a closing link and asked the reporter for a raw event trace.

@BenTaylorDev

Copy link
Copy Markdown
Contributor

This revision fixes the blocker. One thing left, and it's the rebase, not your logic.

Verified

I rebuilt the probe: real @ag-ui/[email protected] against a stubbed LangGraph client, through CopilotKitCore.runAgent(). Same adapter, same emitted stream; only state-manager.ts varies.

tool messages for call_weather_1
main 1
previous revision (254a59d44) 2
this revision 1

I also ran the fix direction on the real adapter — checkpoint snapshot omits the tool message:

result
main [] — result lost, assistant tool call left unpaired
this revision exactly 1, ordered [user, assistant, tool]

So the bug is real on current main through a real adapter, and this repairs it without touching the healthy LangGraph/ADK divergent-id path. Also confirmed: 10 of your 13 tests fail against main, so the coverage is genuine; and onRunFailed returning { messages } really is applied (agent/agent.ts:459-475), with catchError (:229) ahead of finalize (:237) so onRunFinalized can't clear provenance first. The helper extraction closes my earlier note.

Blocker: a test of yours fails once merged with main

The branch is stale, and #6253 landed meanwhile — handleMessagesSnapshot now only stamps a run id onto snapshot messages that don't already have one.

FAIL  keeps one checkpoint result when LangGraph uses divergent message ids
AssertionError: expected 'b5247723-…' to be '133ca399-…'
  state-manager-tool-result-history.test.ts:248

Turn 2's snapshot re-carries lc-tool-1, which turn 1 created, so keeping turn 1's run id is the intended new behaviour — the assertion is what's stale. inputs[1] → inputs[0] is enough; I ran it, back to 13/13 merged. Note nothing but CodeRabbit has run on this PR, so no CI would have told you.

Minor

  • removes a placeholder beside an existing real result no longer describes its case — the fixture holds only a placeholder, so it exercises promotion. Leftover name from the multi-part revision.
  • The provenance map keeps the last result event for a call, while the repair keeps the first existing message. Contrived to hit; just noting "authoritative" means two things across the two halves.
  • The react-native comment edit is in scope since the helper moved, but naming normalizeToolResultContent in core/tool-result-content.ts would keep it greppable.
  • Thanks for splitting AG-UI: tool result messages missing from conversation history on subsequent turns (causes LLM 400) #3884 off rather than auto-closing it.

Rebase and fix that assertion and I'll re-run both the merged suite and the probes.

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.
@rodboev
rodboev force-pushed the fix/3884-tool-result-history branch from db40578 to d5fe120 Compare August 21, 2026 01:08
@rodboev

rodboev commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, your merged-main probe pinned the remaining failure to the provenance expectation rather than the reconciliation logic.

  1. Commit d5fe12043c rebases the existing branch onto current main and resolves the state-manager.ts conflict while retaining the existing result-reconciliation behavior.
  2. In keeps one result when LangGraph uses divergent message ids (state-manager-tool-result-history.test.ts:205-257), I changed the checkpoint provenance assertion from agent.inputs[1]?.runId to agent.inputs[0]?.runId. The separate second-turn history assertion remains unchanged, and the fixture keeps the streamed result before the snapshot.
  3. StateManager now clears pending results after each finished server run (state-manager.ts:284-300), so a replay with multiple server runs under one input cannot resurrect a result removed by a later snapshot. The regression is covered at state-manager-tool-result-history.test.ts:260-283.
  4. I left the nonblocking naming, terminology, and comment notes unchanged.

The LangGraph and omitted-snapshot behavior remains covered while the test now matches current main's first-seen message provenance.

@pkg-pr-new

pkg-pr-new Bot commented Aug 24, 2026

Copy link
Copy Markdown

Open in StackBlitz

@copilotkit/a2ui-renderer

pnpm add https://pkg.pr.new/@copilotkit/a2ui-renderer@6294

@copilotkit/agentcore-runner

pnpm add https://pkg.pr.new/@copilotkit/agentcore-runner@6294

@copilotkit/angular

pnpm add https://pkg.pr.new/@copilotkit/angular@6294

@copilotkit/channels

pnpm add https://pkg.pr.new/@copilotkit/channels@6294

@copilotkit/channels-core

pnpm add https://pkg.pr.new/@copilotkit/channels-core@6294

@copilotkit/channels-discord

pnpm add https://pkg.pr.new/@copilotkit/channels-discord@6294

@copilotkit/channels-intelligence

pnpm add https://pkg.pr.new/@copilotkit/channels-intelligence@6294

@copilotkit/channels-slack

pnpm add https://pkg.pr.new/@copilotkit/channels-slack@6294

@copilotkit/channels-teams

pnpm add https://pkg.pr.new/@copilotkit/channels-teams@6294

@copilotkit/channels-telegram

pnpm add https://pkg.pr.new/@copilotkit/channels-telegram@6294

@copilotkit/channels-ui

pnpm add https://pkg.pr.new/@copilotkit/channels-ui@6294

@copilotkit/channels-whatsapp

pnpm add https://pkg.pr.new/@copilotkit/channels-whatsapp@6294

@copilotkit/core

pnpm add https://pkg.pr.new/@copilotkit/core@6294

@copilotkit/react-core

pnpm add https://pkg.pr.new/@copilotkit/react-core@6294

@copilotkit/react-native

pnpm add https://pkg.pr.new/@copilotkit/react-native@6294

@copilotkit/react-textarea

pnpm add https://pkg.pr.new/@copilotkit/react-textarea@6294

@copilotkit/react-ui

pnpm add https://pkg.pr.new/@copilotkit/react-ui@6294

@copilotkit/runtime

pnpm add https://pkg.pr.new/@copilotkit/runtime@6294

@copilotkit/runtime-client-gql

pnpm add https://pkg.pr.new/@copilotkit/runtime-client-gql@6294

@copilotkit/sdk-js

pnpm add https://pkg.pr.new/@copilotkit/sdk-js@6294

@copilotkit/shared

pnpm add https://pkg.pr.new/@copilotkit/shared@6294

@copilotkit/sqlite-runner

pnpm add https://pkg.pr.new/@copilotkit/sqlite-runner@6294

@copilotkit/voice

pnpm add https://pkg.pr.new/@copilotkit/voice@6294

@copilotkit/vue

pnpm add https://pkg.pr.new/@copilotkit/vue@6294

@copilotkit/web-components

pnpm add https://pkg.pr.new/@copilotkit/web-components@6294

@copilotkit/web-inspector

pnpm add https://pkg.pr.new/@copilotkit/web-inspector@6294

commit: d5fe120

@BenTaylorDev BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 realIndex branch → 4 tests fail
  • neuter the insert branch → 4 tests fail
  • drop clearPendingResults from onRunFinishedEvent → 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.

@BenTaylorDev
BenTaylorDev merged commit 105ac3c into CopilotKit:main Aug 24, 2026
40 of 62 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants