From 451bc04ae022ef02473bdd92740cf19d8ceb5f3c Mon Sep 17 00:00:00 2001 From: Mikhail Rodionov <39830104+volveezz@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:52:59 +0100 Subject: [PATCH] fix: keep a workflow agent's tool call out of the turn's unfinished tools (#1638) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Problem With workflows on (`CLAUDE_CODE_WORKFLOWS=1`), the prompt fails when a workflow agent asks for permission while the main agent's turn is open: ```text RequestError: Internal error: Claude ended the turn without returning results for tool calls: toolu_… data: { errorKind: "incomplete_tool_call" } ``` Seen in a client running workflows in default mode: the main agent starts a background workflow and keeps working, a workflow agent runs a quick Bash command after the user allows it, and the main agent's turn then ends with this error. The workflow itself finishes fine. ## Cause Claude Code calls `canUseTool` for a workflow agent with an `agentID` that no `task_started` announces. The workflow's own `task_started` names the Workflow call, and the agent's tool_use and tool_result never stream on the root query. `toolUseOwner` finds no parent (the adapter logs "No parent tool_use recorded for subagent a…; sending the Bash permission request unattributed"), so `ensureToolCallEmitted` sees no `parentToolUseId` and the root session id, and records the call as the turn's foreground work: ```ts if (!parentToolUseId && notificationSessionId === sessionId && toolName !== "SandboxNetworkAccess") { recordForegroundToolCall(session, toolCallId); } ``` The call is still open when the turn's result arrives. The permission path also recorded it as dispatched, so `settleActive` counts it as stuck and fails the prompt. A command that runs a few seconds gets a `task_started`, and `registerLiveTask` forgets the call, so only quick commands hit this. ## Fix `ensureToolCallEmitted` takes `canUseTool`'s `agentID`, and a call with an `agentID` is not recorded as foreground work: ```ts if (!agentID && toolName !== "SandboxNetworkAccess") { recordForegroundToolCall(session, toolCallId); } ``` `toolUseOwner` finds a parent or a child session only for a set `agentID`, so the two dropped conditions are implied by `!agentID`, and the result changes only for a subagent with neither. That is a workflow agent, or a Task subagent whose request beats its `task_started`; the latter's call was already unlisted by its streamed frame. `foregroundToolCallIds` feeds only the end-of-turn check. Both callers, the permission request and the AskUserQuestion elicitation, pass `agentID`. v2 is not affected: it never fails a turn for an open tool call, and it emits a permission's tool call early only for SandboxNetworkAccess. ## Tests - `v1/incomplete-tools.test.ts`: "does not claim a workflow agent's permission tool as a foreground tool". The stream is what the CLI sends: a Workflow tool_use, its `local_workflow` `task_started` and launch result, then the agent's `canUseTool` with an `agentID` no `task_started` announced, then the result. It fails without the fix with "Claude ended the turn without returning results for tool calls: unfinished-bash". - `npm run check`, `npm run build` and `tsc --noEmit` pass. `npm run test:run`: 4179 passed, 36 skipped, 1 failed. The failure is `acp-scenarios.test.ts` "replaces only the version of this adapter and the path of this Node binary", which fails the same way on `main` on my machine. - Real repro: an ACP client spawning the adapter with Claude Code 2.1.325, default mode, permissions allowed after 1.5s. The main agent starts a workflow whose one agent runs `date > stamp.txt; cat stamp.txt`, then goes on with its own work: | Build | Main turn ends | Result | | --- | --- | --- | | `main` (7d9e1f6) | ~27s after the workflow's command | failed 2/2 | | this branch | ~27s after the workflow's command | clean 4/4 | | `main` (7d9e1f6) | ~1s after the command is allowed | failed 3/3 | | this branch | ~1s after the command is allowed | clean 3/3 | 0.101.1 fails the same way (2/2), and this change alone makes it clean (2/2). ## Not covered - The workflow agent's tool call still never closes in the client: nothing streams its result on the root query. That was already the case when the main turn ended before the request. A probe shows the adapter's PostToolUse hook does fire for it, with the call's `tool_use_id`, its `agent_id` and `agent_type: "workflow-subagent"`, so a follow-up could close it from there. - The "No parent tool_use recorded" log now fires on every workflow agent's request, not only on a lost race with `task_started`. Its comment says so; it is still only `logger.log`. - `npm run test:integration` was not run. Related: #1501 hits the same check through the same eager permission call, for a root `confirm_` question with no `agentID`. This PR does not change it. Co-authored-by: Ben Brandt --- src/tests/v1/incomplete-tools.test.ts | 44 +++++++++++++++++++++++++++ src/v1/acp-agent.ts | 23 +++++++++----- 2 files changed, 60 insertions(+), 7 deletions(-) diff --git a/src/tests/v1/incomplete-tools.test.ts b/src/tests/v1/incomplete-tools.test.ts index 86d23e29..6143b1d2 100644 --- a/src/tests/v1/incomplete-tools.test.ts +++ b/src/tests/v1/incomplete-tools.test.ts @@ -267,6 +267,12 @@ describe("incomplete foreground tools", () => { await expect(prompt()).resolves.toMatchObject({ stopReason: "end_turn" }); }); + it("does not claim a workflow agent's permission tool as a foreground tool", async () => { + const { prompt } = createTestSession(workflowAgentPermissionMessages); + + await expect(prompt()).resolves.toMatchObject({ stopReason: "end_turn" }); + }); + it("does not treat a request to run in the background as a confirmed handoff", async () => { const { prompt } = createTestSession(unconfirmedBackgroundToolMessages); @@ -1442,6 +1448,44 @@ async function* permissionOnlyToolMessages(input: Pushable, agent: ClaudeAc yield successfulResultMessage(); } +/** A workflow agent asks for permission while the turn runs. The workflow's + * task_started names the Workflow call, not the agent, and the agent's + * tool_use and tool_result never stream on the root query. */ +async function* workflowAgentPermissionMessages(input: Pushable, agent: ClaudeAcpAgent) { + yield* echoNextPrompt(input); + yield toolStart("workflow", null, "Workflow"); + yield toolUse("workflow", null, "Workflow", { script: "await agent('Stamp the date')" }); + yield { + type: "system", + subtype: "task_started", + session_id: sessionId, + task_id: "wzr1bosoo", + tool_use_id: "workflow", + description: "Stamp the date", + task_type: "local_workflow", + }; + yield { + ...toolResult("workflow"), + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "workflow", + content: "Workflow launched in background. Task ID: wzr1bosoo", + }, + ], + }, + }; + await agent.canUseTool(sessionId)("Bash", { command: "date > stamp.txt; cat stamp.txt" }, { + toolUseID: toolCallId, + agentID: "a2a57f1ad0803996a", + signal: new AbortController().signal, + suggestions: [], + } as any); + yield successfulResultMessage(); +} + async function* completedToolMessages(input: Pushable) { yield* echoNextPrompt(input); yield toolStart(); diff --git a/src/v1/acp-agent.ts b/src/v1/acp-agent.ts index 9628e13f..a78da842 100644 --- a/src/v1/acp-agent.ts +++ b/src/v1/acp-agent.ts @@ -8686,6 +8686,7 @@ export class ClaudeAcpAgent { params.toolCall.toolCallId, toolInput, parentToolUseId, + agentID, signal, params.sessionId, previewContent, @@ -8780,13 +8781,17 @@ export class ClaudeAcpAgent { * always resolve. Since the streamed path never completes those calls, they * are resolved at tool_result time instead (see `toAcpNotifications`). * `parentToolUseId` attributes a subagent's tool call to the Agent/Task call - * that spawned it, matching the streamed path's `_meta`. */ + * that spawned it, matching the streamed path's `_meta`. `agentID` is + * `canUseTool`'s, set for every subagent's tool call, including a workflow + * agent's, which has no `parentToolUseId`. Such a call is not recorded as + * the turn's foreground work. */ private async ensureToolCallEmitted( sessionId: string, toolName: string, toolCallId: string, toolInput: unknown, parentToolUseId?: string, + agentID?: string, signal?: AbortSignal, notificationSessionId: string = sessionId, previewContent?: ToolCallContent[], @@ -8810,11 +8815,12 @@ export class ClaudeAcpAgent { } session.emittedToolCalls.add(toolCallId); if (parentToolUseId) recordToolCallParent(session, toolCallId, parentToolUseId); - // SandboxNetworkAccess is a permission-only callback, not an executing - // tool: the SDK does not send a tool_result for its synthetic id. + // A subagent's tool call is not the turn's foreground work, even when no + // parent was found for it: a workflow agent's tool_result never streams on + // the root query. SandboxNetworkAccess is a permission-only callback, not + // an executing tool: the SDK does not send a tool_result for its synthetic id. if ( - !parentToolUseId && - notificationSessionId === sessionId && + !agentID && toolName !== "SandboxNetworkAccess" && // Neither does it send one for a question that Claude Code asks on its own. !isConfirmQuestion(toolCallId) @@ -8853,7 +8859,8 @@ export class ClaudeAcpAgent { * emitted tool call and of its requests: the subagent's child session once * it is announced, else the root session. In the rare SDK ordering where * the callback beats the spawning Agent/Task frame, the root keeps it; the - * later frame announces the child with its correct nested lineage. + * later frame announces the child with its correct nested lineage. A + * workflow agent gets no task_started, so the root always keeps its tool use. */ private toolUseOwner( session: Session, @@ -8968,7 +8975,8 @@ export class ClaudeAcpAgent { // defines a subagent's `agent_id` as its task id). Should the consumer // lose the race with task_started, the lookup misses and the request // goes out unattributed; log it so the miss is observable rather than - // silent. + // silent. A workflow agent's request always misses: it has no + // task_started. this.logger.log( `[claude-agent-acp] No parent tool_use recorded for subagent ${agentID}; ` + `sending the ${toolName} permission request unattributed`, @@ -8988,6 +8996,7 @@ export class ClaudeAcpAgent { toolUseID, toolInput, parentToolUseId, + agentID, signal, permissionSessionId, );