Skip to content

Do not run a client tool twice when a tool call is readied twice - #330683

Closed
Ryan Ewen (RyanEwen) wants to merge 1 commit into
microsoft:mainfrom
RyanEwen:fix/duplicate-client-tool-invocation
Closed

Ryan Ewen (RyanEwen) wants to merge 1 commit into
microsoft:mainfrom
RyanEwen:fix/duplicate-client-tool-invocation

Conversation

@RyanEwen

@RyanEwen Ryan Ewen (RyanEwen) commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A client tool call can receive two ChatToolCallReady actions: one from the permission flow (carrying confirmation options, preApproved unset) and one from the agent's stream mapper on content_block_stop (confirmed: not-needed, pre-approved). _executeClientTool is driven once per ready, so the tool runs twice.

The existing startedClientToolCalls guard cannot prevent this. It is armed from markInvocationStarted, which _executeClientTool only calls after awaiting resolveToolInput, so both readies pass the started check before either arms it. The two requests also differ (only in preApproved), so the equals(observedRequest, request) check treats the second as a new request rather than a duplicate.

Symptom

The turn hangs indefinitely. The tool visibly succeeds and chat/toolCallComplete is reported, but only one of the two invocations is tracked, so the turn is never closed and nothing is logged.

User-visible variants of the same double dispatch: a browser page opening before the approval prompt is answered, and answering it then opening a second one.

Evidence

Captured by logging a stack at LanguageModelToolsService#invokeTool in a dev container window:

11:20:23.064  callId=toolu_01VfWfPn…  preApproved=undefined    at WX._executeClientTool
11:20:23.064  callId=toolu_01VfWfPn…  preApproved={"type":1}   at WX._executeClientTool

Same call id, same call site, same millisecond, differing only in approval state.

Fix

Arm a separate in-flight set synchronously when execution starts, and clear it when the execution settles. A second ready for a call that is already running is ignored, while genuine retries still work because the set is cleared on completion.

Verification

With the change applied, each tool call is invoked exactly once and turns complete:

open_browser_page   invoked 1x
type_in_page        invoked 1x
navigate_page       invoked 1x

Reproduced originally in a compose dev container on Windows (VS Code 1.133.0). Local windows were unaffected.

AI disclosure: this description and the code it proposes were written with the assistance of AI.

Public patches and patcher scripts

Source patch and installed-bundle workaround mapping. The public collection includes the maintained patchers, rollback instructions, regression scripts, and historical snapshots. Build restrictions and exact installer coverage are documented there.

Copilot AI balanced review requested due to automatic review settings August 13, 2026 16:35

Copilot AI 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.

Pull request overview

Prevents duplicate client-tool execution when concurrent ready actions arrive.

Changes:

  • Tracks in-flight client-tool calls synchronously.
  • Suppresses execution while the call remains active.
  • Clears tracking after execution settles.
Suppressed comments (2)

src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts:2333

  • This call-wide guard also suppresses legitimate superseding attempts while resolveToolInput is still pending. The existing supersedes a hung referenced input read when the request changes test updates the same call from a never-resolving input URI to a second URI; the first attempt adds this key, so the update now returns here and the second input is never read or invoked. Track the active request/attempt and coalesce only duplicate ready variants (for example, equivalent execution payloads ignoring approval metadata) instead of blocking every request sharing the call key.
					if (startedClientToolCalls.has(key) || inFlightClientToolCalls.has(key)) {

src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts:2356

  • Add a regression test for the pre-markInvocationStarted race: keep referenced input resolution pending, deliver the two ready variants with different approval metadata, and assert exactly one invocation while preserving a genuine retry after settlement. The existing tests do not exercise this timing window.
						inFlightClientToolCalls.add(key);

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@RyanEwen

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

@RyanEwen

Ryan Ewen (RyanEwen) commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Related: these three share a root cause. Noting it so they can be triaged together rather than as three unrelated patches.

The workbench executes a client tool off the stream-mapper chat/toolCallReady (emitted at content_block_stop with confirmed: "not-needed"), independently of whether the SDK has invoked that tool through its in-process MCP server. Three defects fall out of that one seam:

If client tools executed only on the SDK-driven invocation, with the stream-mapper ready used for rendering only, all three would be structurally impossible: one authoritative trigger, never without real input, and registration ordered before execution.

I have not proposed that as a PR because I do not know whether the stream-mapper ready is deliberately actionable. Starting the tool as soon as its arguments finish streaming, instead of waiting for the SDK round trip, is a plausible latency win, and the permission flow may already depend on the current ordering. That is a call for whoever owns the design.

Each of the three fixes a reproducible bug on its own and carries a test that fails without it, so they are safe to land in the meantime. If the structural fix is preferred, #330683 and #330684 can reasonably be closed in its favour; #330730 is worth keeping either way, since buffering a result that arrives before its handler is the same defensive behaviour CopilotAgentSession already has on this path.

AI disclosure: this comment was written with the assistance of AI.

@RyanEwen

Ryan Ewen (RyanEwen) commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Root cause filed as #330899, per the request on #330684. This PR still stands on its own, with a test that fails without it.

AI disclosure: this comment was written with the assistance of AI.

@RyanEwen

Copy link
Copy Markdown
Contributor Author

Two findings in the review body were collapsed as suppressed comments, so they never opened threads. Addressing both here.

On the guard suppressing legitimate superseding attempts (agentHostSessionHandler.ts, the call-wide key): this does not reproduce. Rebased onto current main and ran the suite the finding names:

54 passing
  ✔ supersedes a hung referenced input read when the request changes
  ✔ does not re-execute when the request changes after invocation starts

The cited scenario is exactly what that first test does: it parks the first attempt on a never-resolving session-db:/tool-input-1, then delivers a second ready for the same tool-call-1 with session-db:/tool-input-2, and asserts both URIs are read and the invocation carries the second input. It passes. Execution is tracked per attempt via activeAttempts rather than being blocked per call key, which is the coalescing the finding asks for.

For the record on test hygiene: three earlier runs of mine reported 53 passing against a stale out/, because npm run compile fails in my environment during extension media typechecking and I had emitted to the wrong outDir. The 53 to 54 difference is this branch's own added test, so the count is the tell that the run above used current code.

On the missing regression test for the pre-markInvocationStarted race: that one is fair. The suite covers re-entry after invocation starts, but not two ready variants differing only in approval metadata arriving while referenced input resolution is still pending. Happy to add it if you would like it in this PR.

AI disclosure: this comment and the related code were written with the assistance of AI.

@RyanEwen

Copy link
Copy Markdown
Contributor Author

Following up on the second suppressed finding, the one asking for a regression test in the pre-markInvocationStarted window. Writing it surfaced a real defect, so this PR now carries a fix as well.

Two guards on the execution path judged sameness differently:

  • The coalescing check compares executionSignature(request), which is [toolName, toolInput]. Approval metadata is deliberately excluded, so a ready differing only in approval is judged already in flight and declines to start a second attempt.
  • The attempt it defers to validated itself with equals(request$.read(undefined), request), a full comparison that the same approval change makes unequal, so it abandoned itself as superseded.

Between them the call was stranded. Three-way control, each run with the rest of the suite green:

Scenario Result before
single ready invokes
two readies, identical approval invokes once
two readies, differing approval 1 read, 0 invocations, 0 completions

No confirmation timer fires either, so the call sits unresolved for the life of the session rather than failing visibly.

The fix judges staleness by the same signature the coalescing check uses, so an approval-only change no longer invalidates the attempt it declined to replace. The new test pins all three rows above. 1110 passing across the agentSessions browser suites, and the previously cited supersedes a hung referenced input read when the request changes still passes, so genuine superseding on a changed input is unaffected.

AI disclosure: this comment and the related code were written with the assistance of AI.

@RyanEwen

Copy link
Copy Markdown
Contributor Author

Correcting the attribution in my previous comment, since it could be read as describing a pre-existing upstream defect. It is not.

The equals-based validity predicate is pre-existing (agentHostSessionHandler.ts:2393 on main). The signature-based coalescing early return is added by this PR and does not exist on main or at the merge base. So the inconsistency between the two, and the stranding it caused, were introduced here rather than found in existing code.

That makes the original review comment right about this PR specifically: the new call-wide guard did interfere with an attempt it should not have. It was wrong only about which scenario broke. The named test, supersedes a hung referenced input read when the request changes, passes both before and after, because a changed tool input produces a different signature and supersedes normally. The case that broke is the one the second comment asked for a test for: a ready differing only in approval, while referenced input is still resolving.

Both are now covered.

AI disclosure: this comment and the related code were written with the assistance of AI.

@Giuspepe Giuseppe Cianci (Giuspepe) added bug Issue identified by VS Code Team member as probable bug agent-host Issues for the agent-host implementation (not the protocol) and removed triage-needed labels Aug 25, 2026
@RyanEwen
Ryan Ewen (RyanEwen) force-pushed the fix/duplicate-client-tool-invocation branch from 9d0bb55 to 731cca6 Compare August 28, 2026 16:27
@RyanEwen

Copy link
Copy Markdown
Contributor Author

Superseded by #330933. Running twice is one symptom of there being no single admission point for a client tool: a display signal derived from the stream is used as the dispatch signal. Deduplicating at this layer suppresses the second of two events that should never have been two. #330933 addresses that directly, so this guard becomes redundant. See #333174.

AI disclosure: this comment and the related code were written with the assistance of AI.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

agent-host Issues for the agent-host implementation (not the protocol) bug Issue identified by VS Code Team member as probable bug

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants