Skip to content

fix(sdk-python): restore frontend tool history faithfully in LangGraph middleware - #5308

Merged
BenTaylorDev merged 4 commits into
CopilotKit:mainfrom
mvanhorn:fix/4759-copilotkit-lg-middleware-fe-tool-history
Aug 17, 2026
Merged

BenTaylorDev merged 4 commits into
CopilotKit:mainfrom
mvanhorn:fix/4759-copilotkit-lg-middleware-fe-tool-history

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

Description

Fixes the LangGraph middleware "lying" to the agent about frontend tool execution (#4759). When a model turn calls a useFrontendTool handler, the middleware strips the FE tool calls so the backend ToolNode only runs calls it actually made, then rehydrates them afterward. Previously the rehydration could leave the restored AI message and its tool history inconsistent, so providers that require every tool call to have a matching result would break, and the agent saw an incorrect picture of what executed.

Changes

  • _restore_intercepted_tool_call_history rebuilds the intercepted FE tool calls with synthetic ToolMessage results only for the restored model history (so providers that require every tool_call to have a result stay valid), and preserves the original AI message's name, additional_kwargs, and response_metadata on restore.
  • Tracks original_tool_calls in the CopilotKit private state so the original call set is restored exactly.

Testing

uv run pytest tests/test_copilotkit_lg_middleware.py — 68 passed, including new cases asserting the restored AI message keeps its tool-call ids, name, additional_kwargs, and response_metadata, and that tool results line up with their calls.

Closes #4759

AI was used for assistance.

… execution

The middleware strips FE tool calls so the backend ToolNode only executes
its own calls, then restores them. Restoration now rebuilds the intercepted
calls with synthetic ToolMessage results scoped to the restored model
history (providers that require a result per tool_call stay valid) and
preserves the original AI message's name, additional_kwargs, and
response_metadata. Tracks original_tool_calls in private state so the
original call set is restored exactly.

Closes CopilotKit#4759

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@vercel

vercel Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
docs Ready Ready Preview, Comment Jun 7, 2026 4:05pm

Request Review

@vercel

vercel Bot commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

@mvanhorn is attempting to deploy a commit to the CopilotKit Team on Vercel.

A member of the Team first needs to authorize it.

BenTaylorDev added a commit that referenced this pull request Jul 23, 2026
## What does this PR do?

- Preserve non-tool `AIMessage` fields when frontend tool calls are
intercepted in `afterModel` and restored in `afterAgent`, including
`additional_kwargs`, `response_metadata`, `usage_metadata`,
`invalid_tool_calls`, `id`, and `name`.
- Use a shared rebuild helper with `tool_calls` as the source of truth.
For LangChain v1 content blocks, remove stale `tool_call` and
`tool_call_chunk` blocks before reconstructing the message.
- Add regression coverage for the `reasoning + backend/frontend tool
calls -> afterModel -> afterAgent` flow, including metadata preservation
and v1 content block synchronization.

## Related PRs and Issues

- Closes #6087
- Related to #4759 and #5308

## Checklist

- [x] I have read the [Contribution
Guide](https://github.com/copilotkit/copilotkit/blob/master/CONTRIBUTING.md)
- [x] Documentation is not required because this is an internal
middleware bug fix with no public API changes
- [x] "Allow edits by maintainers" is checked (lets us help iterate on
your PR directly — faster turnaround for everyone)

@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 this — the core diagnosis is right and the mid-loop restore half is a genuine fix: replaying the intercepted frontend calls into wrap/awrap so the model sees its full assistant turn addresses a real, still-present bug (#4759). Two concerns on the after_agent half before it can land:

  1. The synthetic forwarded_to_frontend ToolMessage collides with the existing orphan-handoff contract. On main, after_agent deliberately leaves the frontend tool call as an orphan (no result) — that's the slot the real frontend result fills, and _fix_messages_for_bedrock (copilotkit_lg_middleware.py:563) + langchain's patch_orphan_tool_calls reposition/dedup it by matching _INTERRUPTED_PAT (:585, the "…was interrupted before completion." placeholder). This PR persists a synthetic {"status":"forwarded_to_frontend"} result whose content doesn't match that pattern, so it's treated as a second real result and the reposition path is skipped — on the Bedrock path the real frontend result can end up non-adjacent and then get stripped as unanswered.
  2. Sync/async asymmetry. awrap_model_call runs _restore_intercepted_tool_call_history and _fix_messages_for_bedrock (:789, :793), but the sync wrap_model_call (:450) only runs the restore — so the synthetic messages it injects never go through the Bedrock dedup, risking a duplicate tool_call_id reaching the provider.

The tests hand-build message lists and never exercise the real round-trip (checkpoint persist → add_messages merge → patch_orphan_tool_calls → real FE result reintegration → dedup), so they don't catch either. Could you (a) confirm the real frontend-result round-trip still keeps the result adjacent given the synthetic no longer matches _INTERRUPTED_PAT — or better, avoid persisting a synthetic result and keep the orphan-handoff contract intact — and (b) run the sync path through _fix_messages_for_bedrock too? The mid-loop restore looks good on its own.

Addresses both review concerns on the after_agent half.

after_agent no longer synthesizes a forwarded_to_frontend ToolMessage. That
synthetic result did not match _INTERRUPTED_PAT, so _fix_messages_for_bedrock
and langchain's patch_orphan_tool_calls treated it as a real second result and
skipped the reposition path, which on the Bedrock path could leave the real
frontend result non-adjacent and then stripped as unanswered. The restore helper
now takes synthesize_frontend_tool_results, which after_agent sets to False so
the call stays an orphan for the real result to fill, and any synthetic result
already in history is dropped by id.

The sync wrap_model_call now also runs _fix_messages_for_bedrock, matching
awrap_model_call, so the messages it injects go through the same dedup instead
of risking a duplicate tool_call id on the sync path.
@mvanhorn

Copy link
Copy Markdown
Contributor Author

Both concerns addressed in 9f847a2.

  1. The synthetic forwarded_to_frontend result is gone from after_agent. You were right that it collided with the orphan-handoff contract: it did not match _INTERRUPTED_PAT, so _fix_messages_for_bedrock and patch_orphan_tool_calls read it as a real second result and skipped the reposition path. _restore_intercepted_tool_call_history now takes synthesize_frontend_tool_results, which after_agent passes as False, so the frontend call stays an orphan for the real result to fill. Any synthetic result already sitting in history is dropped by its copilotkit-fe-tool-result-<id> id, so a mid-loop restore followed by after_agent does not leave one behind.

  2. The sync/async asymmetry is closed: wrap_model_call now runs _fix_messages_for_bedrock after the restore, matching awrap_model_call.

The mid-loop restore path is unchanged, since that half was the part you said was a genuine fix.

Two tests changed with it: test_after_agent_restores_intercepted_tool_calls_on_original_message now asserts no ToolMessages survive, and the duplicate-history test asserts only the backend result remains.

Verification, with a caveat. tests/test_copilotkit_lg_middleware.py gives 61 passed, 7 failed. The 7 failures are all in TestAutoA2UI and are identical on clean HEAD, so they are not from this change; they come from a newer langchain_core rejecting a MagicMock in the tool decorator. The sdk is a Poetry project and I installed the deps into a plain venv rather than through Poetry, so that version skew is mine, not yours.

@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 the quick turnaround — concern (2) is fully addressed: wrap_model_call now runs _fix_messages_for_bedrock after the restore, and the restore-then-fix ordering is correct. The mid-loop half is confirmed working; against a real create_agent + AG-UI adapter run, the second model call now sees ai-1 with ['be-1','fe-1'] and both answered, where main shows only ['be-1']. That's a genuine fix for the intra-turn half of #4759.

Concern (1) isn't resolved yet, though. The synthetic result still lands in the persisted checkpoint — I see ToolMessage id='copilotkit-fe-tool-result-fe-1' content='{"status": "forwarded_to_frontend"}' in the checkpoint after turn 1. Two reasons: _restore_intercepted_tool_call_history mutates request.messages in place, and that list is the state channel's, so the synthetic is written into state; and after_agent removes it by omitting it from the returned list, which add_messages cannot honor — dropping a message needs a RemoveMessage. So synthesize_frontend_tool_results=False and the id-filter don't actually keep the FE call orphaned.

To be fair: at the currently-resolved versions this is not a live regression — turn 2 behaves identically to main — because the patch_orphan_tool_calls placeholder the adapter's repair path keys off (_ORPHAN_TOOL_MSG_RE) is no longer produced by langchain/langgraph at all. But persisting a synthetic tool result into user checkpoints is durable state we can't easily walk back, and it silently defeats that repair path wherever it is active.

The smallest fix is to keep the rehydration request-scoped rather than state-scoped — restore into a copy, e.g. request = request.override(messages=list(request.messages)) before the restore. I verified that shape keeps the mid-loop benefit (model still sees ['be-1','fe-1'], both answered) while leaving the checkpoint's FE call orphaned and synthetic-free. It also makes the synthesize_frontend_tool_results flag and the id-filter unnecessary.

Two notes: I'd soften "Closes #4759" to the intra-turn half — the cross-turn path is still broken, but that's pre-existing (_fix_messages_for_bedrock mutating in place permanently erases the FE tool call from persisted state across turns), and worth a separate issue. And your 7 failures were the plain-venv skew, not a real break: installing via poetry the way CI does, main is 210 passed / 11 skipped and this branch is 214 passed / 11 skipped, all green.

Implemented the remaining review fix:
- Sync and async model restoration now operate on copied message lists, preventing synthetic results from entering checkpoint state.
- Removed the obsolete synthesis flag and ineffective result-ID filter.
- `after_agent` restores the frontend call as an orphan.
- Added sync/async regression coverage for request-scoped restoration.
[Middleware changes](/Users/mvanhorn/.osc/workspaces/CopilotKit-CopilotKit-pr5308/sdk-python/copilotkit/copilotkit_lg_middleware.py:450)
[Regression tests](/Users/mvanhorn/.osc/workspaces/CopilotKit-CopilotKit-pr5308/sdk-python/tests/test_copilotkit_lg_middleware.py:618)
```text
@mvanhorn

Copy link
Copy Markdown
Contributor Author

Addressed the remaining review point. Sync and async model restoration now operate on copied message lists, so synthetic results no longer leak into checkpoint state. Dropped the obsolete synthesis flag and the result-ID filter that was not actually filtering, and after_agent now restores the frontend call as an orphan. Added sync and async regression coverage for request-scoped restoration.

ruff format --check and ruff check both pass. The focused pytest run could not collect locally because the Poetry/LangChain deps are not installed on my side.

…f contract

Adds tests that exercise the full checkpoint roundtrip path:
- test_checkpoint_roundtrip_placeholder_replaced_by_real_result: Verifies
  _fix_messages_for_bedrock correctly replaces patch_orphan_tool_calls
  placeholder with real FE result
- test_checkpoint_roundtrip_multiple_fe_calls_with_placeholders: Multiple
  FE calls with placeholders all correctly resolved
- test_after_agent_leaves_fe_call_orphaned_for_checkpoint: Confirms
  after_agent does not persist synthetic ToolMessages, leaving FE calls
  as orphans for the real result to fill

These tests address reviewer feedback requesting coverage for the checkpoint
persist → add_messages merge → patch_orphan_tool_calls → real FE result path.

Co-authored-by: Matt Van Horn <[email protected]>
@mvanhorn

Copy link
Copy Markdown
Contributor Author

Pushed tests for the checkpoint round-trip you asked about.

after_agent still restores tool_calls only and does not persist a synthetic forwarded_to_frontend result, so the real frontend result can fill the orphan. wrap/awrap copy messages before mid-loop restore so that synthetic result does not land in checkpoint state. New tests cover placeholder replacement after patch_orphan_tool_calls.

@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.

Re-reviewed at 49bf4535a. Concern (1) is resolved, and I verified it live rather than from the tests — a real create_agent + InMemorySaver two-turn run:

-- model call #2 (mid-loop restore) --  AI(ai-1) tool_calls=['be-1','fe-1']; TM(be-1); TM(fe-1 synthetic)
-- checkpoint after turn 1 --           AI(ai-1) tool_calls=['be-1','fe-1']; TM(be-1) only
   synthetic 'forwarded_to_frontend' in checkpoint?  False
   fe-1 left orphaned?                              True

request.override(messages=list(request.messages)) + model_copy keeps the rehydration request-scoped exactly as suggested, and after_agent persists tool_calls only — the orphan-handoff contract is intact and no synthetic result reaches durable state. Suite is 217 passed / 11 skipped on the merged tree vs 210 / 11 on main, and CI is green across the full 3.10–3.14 matrix. Nice work on the original_tool_calls tracking too — restoring the exact original call set is better than the append-order reconstruction it replaces.

Two follow-ups, neither blocking:

  1. The sync _fix_messages_for_bedrock(request.messages) I asked for in round 2 turns out to cost more than it buys. It mutates message objects in place (msg.tool_calls = … at copilotkit_lg_middleware.py:595), so the list copy doesn't shield state — on turn 2 the sync path now drops the real FE result from the request and permanently reduces ai-1 to ['be-1'] in the checkpoint, where main's sync path keeps both. That matches what the async path already does on main, so it's parity rather than a new class of bug, but the duplicate-tool_call_id risk that motivated my ask is gone now that nothing synthetic is persisted — so that one line can simply come out. My mistake for requesting it; sorry for the churn.
  2. Worth softening Closes #4759 to the intra-turn half. The cross-turn path is still broken by _fix_messages_for_bedrock corrupting persisted state, which is pre-existing and deserves its own issue.

Minor: request.state.get("copilotkit", {}) (:606, :950) are the only two request.state reads in the file without the or {} guard every other site uses.

I bless the code with a glad heart.

@BenTaylorDev
BenTaylorDev merged commit cd0d38a into CopilotKit:main Aug 17, 2026
34 checks passed
BenTaylorDev added a commit that referenced this pull request Aug 31, 2026
… actions wait for a response (#6524)

Two frontend-tool defects that share a shape: a tool that was registered
correctly still never reached the agent, or reached the render without
the ability to respond.

## `useFrontendTool` tools dropped when the runtime enables
`openGenerativeUI` (#4952)

Tools reached the core registry through two owners that shared one array
— the provider via `setTools()`, hooks via `addTool()` — and `setTools`
replaced the array wholesale. Any provider re-sync after mount therefore
wiped every hook-registered tool.

A runtime with `openGenerativeUI: true` made it reproduce on **every**
mount: `/info` flips the flag asynchronously, the provider re-derives
its tool list to add `generateSandboxedUi`, and the re-sync dropped the
app's own tools. The agent then received only `generateSandboxedUi`,
exactly as reported.

The fix splits the two owners into their own buckets, merged on read
with hook entries winning. This mirrors what `CopilotKitCoreReact`
already does for render tool calls (`react-core.ts`) — tools simply
never got the same treatment. Because the clobber lived in core rather
than in one provider, **Vue had the identical bug and is fixed by the
same change** — verified end to end, not by shape:
`CopilotKitProvider.vue:461` assigns `runtimeOpenGenerativeUIEnabled`
from the core, `:297` derives `openGenerativeUIActive`, `:328`/`:354`
add the built-in to `allTools`, and `:492` re-syncs it through
`setTools` behind the same `didMountRef` skip. Angular is unaffected: it
never calls `setTools`, passes `tools` only through the constructor
(`copilotkit.ts:152`), and registers just the *renderers* from
`config.tools` (`:224`) — no second registration.

`addTool` now shadows a provider tool of the same name instead of
refusing to register, and only warns when another imperative
registration already holds the name. It also no longer pushes onto the
array the provider passed in, and `initialize` copies that array like
`setTools` already did.

**One intentional behavior change worth a reviewer's eye:** `setTools`
now replaces provider-owned tools only, so `setTools([])` no longer
clears tools registered through `addTool`. That narrowing *is* the fix,
but anyone calling `setTools([])` as a "clear everything" would now need
`removeTool` per tool. Nothing in the repo does (core, react-core, vue,
angular suites all pass).

## Catch-all actions could not wait for a response (#1746)

`getActionConfig` short-circuited on `name === "*"` before checking for
a wait-render, so a catch-all declaring `renderAndWaitForResponse` was
silently downgraded to render-only — no `respond`, and in practice a
`render is not a function` throw, since the render-only path reads
`action.render`. Handling N human-in-the-loop tools required N hooks.

A catch-all with a wait-render now routes to the human-in-the-loop path.
Core already had the execution half
(`getWildcardTool`/`executeWildcardTool`), so this is routing, not new
machinery. Two supporting changes make it usable:

- The HITL render props now carry **the name of the tool actually being
called**. It equals the registration name for a normal action, but a
catch-all needs it to tell N tools apart, and `"*"` was being written
over it in both the v1 wrapper and the v2 hook.
- `CatchAllFrontendAction` accepts
`renderAndWaitForResponse`/`renderAndWait` alongside `render`, mutually
exclusive as on `FrontendAction`, with `CatchAllActionRenderPropsWait`
exported.

Also: a wildcard tool is no longer advertised to the agent. It is a
local catch-all handler for calls with no exact match, so offering the
model a tool literally named `*` was never meaningful. Latent before
this PR (nothing in React registered a wildcard *tool*); catch-all HITL
activates it.

## Synced with `main` (2026-08-31)

`main` moved react-core's v1 tree under `src/v1-deprecated/` while this
branch was open, so the merge had exactly two conflicts, both
relocations:

- `use-default-tool.ts`'s `DistributiveOmit` change re-applied on the
moved file, keeping main's deprecation banner.
- the catch-all HITL e2e test moved into
`src/v1-deprecated/hooks/__tests__/`, with its `../../v2/...` imports
re-rooted to `../../../v2/...` to match its sibling
`use-copilot-action.e2e.test.tsx`.

The defect is still live on current `main` —
`CopilotKitProvider.tsx:838` still calls `copilotkit.setTools(allTools)`
— and both regression tests still bite there. The suites, the
before/after checks, `tsc --noEmit`, `oxlint` and `oxfmt` below were all
re-run on the merged tree; the browser walkthrough under **Live
verification** is from the pre-merge branch and was not repeated.

## Testing

**New regression tests**

- `packages/core/src/core/__tests__/run-handler-tool-registry.test.ts` —
13 tests: `addTool` survives `setTools`, hook precedence, agent-scoped
vs global, `removeTool` across both buckets, remount re-registration,
capability toggles surviving a re-sync, provider ordering, caller-array
aliasing in both directions, wildcard never advertised.
-
`packages/react-core/src/v2/providers/__tests__/CopilotKitProvider.openGenerativeUIToolLoss.test.tsx`
— drives the **real** core over a stubbed `/info` that returns
`openGenerativeUIEnabled: true`, asserting the hook tool survives.
-
`packages/react-core/src/v1-deprecated/hooks/__tests__/use-copilot-action-catch-all-hitl.e2e.test.tsx`
— end-to-end through the real provider and core: catch-all gets the real
tool name and a live `respond`, the tool result lands on the original
`toolCallId`, the follow-up run fires, and `*` is absent from
`runInputs[0].tools`.

**Both new tests were confirmed to fail before the fix — re-confirmed
after syncing `main`,** by checking the touched sources out at
`origin/main` and rebuilding core's dist:

```
× keeps the hook tool once the runtime turns openGenerativeUI on
  → expected [ 'generateSandboxedUi' ] to include 'sayHello'
```

and before the routing fix, the catch-all test failed with the exact
defect from the issue:

```
× gives the catch-all render a live respond and the real tool name
  → TypeError: render is not a function
    ❯ render src/hooks/use-render-tool-call.ts:44:22
```

**Suites (all green)**

```
@copilotkit/core        67 files,  799 tests passed
@copilotkit/react-core 137 files, 1558 tests passed
@copilotkit/vue        101 files, 1092 tests passed
@copilotkit/angular     49 files,  317 tests passed (1 skipped)
```

`tsc --noEmit` clean for `core` and `react-core`; `oxlint` 0 errors on
the changed files (16 warnings, all pre-existing); `oxfmt` applied.

**Live verification** — `examples/v2/react/demo` in a browser against
built dists, with a temporary stub AG-UI agent (no LLM key) that echoes
the tool names it receives, a runtime configured `openGenerativeUI:
true`, no `openGenerativeUI` prop on the provider, one
`useCopilotAction` frontend tool and one `useCopilotAction({ name: "*",
renderAndWaitForResponse })`:

```
TOOLS_RECEIVED: ["generateSandboxedUi","sayHello"]     <- #4952: hook tool survived; no "*" leaked
catch-all handling: book_call   status: executing      <- #1746: real tool name, live respond
[click "Pick Tuesday"]
catch-all handling: book_call   status: complete
TOOL_RESULT_RECEIVED: "{"slot":"tuesday"}"             <- follow-up run received the result
```

0 console errors. The stub route and page were scratch and are not in
this branch.

## Notes for reviewers

- Community PR #4967 also targets #4952 by merging in the provider
instead. I took the core-layer fix because the clobber is in core's
registry and every framework provider hits it — patching one provider
leaves Vue broken. Happy to reconcile.
- Pre-existing and deliberately **not** changed here:
`useCopilotAction({ name: "*" })` render props do not infer, because the
hook's parameter is a union TypeScript cannot contextually type. This
already affected plain `render` before this PR (verified), so the new
tests and docs annotate props explicitly. Fixing it needs a
`useCopilotAction` overload — worth a follow-up.
- Deliberate small duplications, flagged rather than abstracted:
`WILDCARD_TOOL_NAME` is a one-line const in both core and react-core's
v2 HITL hook (sharing it would mean a new public export from core), and
the link between "a catch-all render receives `name`" and "the v1 HITL
wrapper supplies it" is a cast rather than a type — making it typed
means adding `name` to the public `ActionRenderPropsWait`, which is
wider than this fix.
- #4759 is left with contributor PR #5308, and #6101 needs its own
design pass since it introduces new public API.



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Added catch-all human-in-the-loop actions that can handle unregistered
tools and wait for user responses.
- Catch-all action renderers now receive the actual invoked tool name
and arguments.
  - Added support for wait-aware catch-all rendering types.

- **Bug Fixes**
  - Preserved frontend tools when provider tool lists are refreshed.
- Prevented duplicate tools and ensured registered tools take
precedence.
- Hidden wildcard tools from agent-advertised tool lists while keeping
them available for handling requests.


<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

🐛 Bug: LangGraph Middleware lies to agent about FE tools execution

3 participants