Repository navigation
Agent Host: keep Claude background tasks alive across turns and match results to prompts - #345986
Conversation
…atch results to prompts Sending a message while a Claude session had background subagents made the pre-flight in ClaudeAgentSession.send() rebuild the SDK subprocess, which SIGKILLed the subagents mid-command (exit 137). The resumed CLI then ran its stopped-task notice as a turn of its own, and ClaudeSdkPipeline settled the user's queued prompt on that first `result`, so the protocol turn closed with no response and the real reply arrived with no owning turn (`result for sdkUuid=undefined`). - ClaudePromptQueue.settle() pops the yielded entry a `result` names via `user_message_uuid(s)`; a result for an SDK-initiated turn no longer consumes a pending user prompt. settleHead() remains the fallback for CLIs that predate the field. - ClaudeSdkPipeline tracks `system:background_tasks_changed` (non-ambient, replace semantics, reset on init and rebind) and exposes liveBackgroundTasks. - ClaudeAgentSession.send() splits rebuild reasons into required (resume anchor, transport switch, owner change) and deferrable (client tools, customizations, MCP enablement, additional directories), defers the deferrable ones while background tasks are live, and logs the reason whenever it rebuilds. Refs microsoft#339309
📬 CODENOTIFYThe following users are being notified based on files changed in this PR: TylerLeonhardtMatched files:
|
Design notes for reviewersA summary of what was considered while diagnosing and fixing this, so the shape of the change is easier to judge. How the problem was located
Alternatives considered and why they were not taken
Behaviour that changes and known limits
Verification
Related#333799, #332073 and #337904 describe adjacent symptoms. Open PRs #326270 and #336753 touch the same area and this change is intended to be compatible with both. |
There was a problem hiding this comment.
🟡 Changes recommended
Critical issues can leave prompts unresolved, terminate the wrong turn, and execute messages using the previous agent or disabled plugins.
4 open issues
What changed in this PR
Addresses Claude background-task termination and lost replies in the Agent Host by deferring eligible subprocess rebuilds and matching results to user prompts.
Changes:
- Matches SDK results to queued prompt UUIDs, retaining positional fallback for older CLIs.
- Tracks live non-ambient background tasks and defers selected rebuild reasons while they run.
- Adds rebuild diagnostics and regression tests for result matching and task tracking.
| File | Description |
|---|---|
src/vs/platform/agentHost/test/node/claudeSdkPipeline.test.ts |
Tests result ownership, legacy fallback, and background-task tracking. |
src/vs/platform/agentHost/test/node/claudePromptQueue.test.ts |
Tests non-head UUID settlement and unmatched results. |
src/vs/platform/agentHost/node/claude/claudeSdkPipeline.ts |
Matches results to prompts and tracks live background tasks. |
src/vs/platform/agentHost/node/claude/claudePromptQueue.ts |
Adds UUID-based prompt settlement. |
src/vs/platform/agentHost/node/claude/claudeAgentSession.ts |
Classifies rebuild reasons, defers eligible rebuilds, and logs decisions. |
Review effort: Balanced
| if (this.clientCustomizationsDiff.hasDifferenceFrom(this._desiredClientPluginPaths(this._owner.get()))) { | ||
| deferrable.push('client customizations'); |
| if (this.clientCustomizationsDiff.hasDifferenceFrom(this._desiredClientPluginPaths(this._owner.get()))) { | ||
| deferrable.push('client customizations'); |
| /** | ||
| * Pop the yielded entry whose `sdkUuid` is one of `sdkUuids` (the | ||
| * `user_message_uuid` / `user_message_uuids` a `result` message | ||
| * names). Same batching semantics as {@link settleHead}. Returns | ||
| * `undefined` and leaves the queue untouched when no yielded entry | ||
| * matches: the result then belongs to a turn the SDK started on its | ||
| * own (a stopped-task notice after a resume, a cross-session | ||
| * message) and must not consume a pending user prompt's slot. | ||
| */ | ||
| settle(sdkUuids: readonly string[]): IPendingSdkMessage | undefined { | ||
| const index = this._yielded.findIndex(entry => sdkUuids.includes(entry.sdkUuid)); | ||
| return index === -1 ? undefined : this._settleAt(index); | ||
| } |
| if (!completed && answered.length > 0 && !this._queue.isEmpty) { | ||
| this._logService.info(`[Claude:${this.sessionId}] result for SDK-initiated turn user_message_uuid=${answered.join(',')}; keeping the pending user turn open`); | ||
| continue; |
|
Martin Carapia (@martincarapia) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.
Contributor License AgreementContribution License AgreementThis Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
|

Fixes #339309
Sending a message while a Claude session had background subagents made the pre-flight in
ClaudeAgentSession.send()rebuild the SDK subprocess, which SIGKILLed the subagents mid-command (exit 137). The resumed CLI then ran its stopped-task notice as a turn of its own, andClaudeSdkPipelinesettled the user's queued prompt on that firstresult, so the protocol turn closed with no response and the real reply arrived with no owning turn (result for sdkUuid=undefined).Evidence
Reproduced on macOS on two machines, VS Code 1.144.1 (261c84c), Claude SDK 0.3.304 / Claude Code 2.1.304, Agents window, Claude harness, local connection. One occurrence from
agenthost.log:The parent transcript at 20:06:53 holds the CLI's
<task-notification>withstatus=stopped("it may have been running when the previous Claude Code process exited"). The subagent's transcript ends with a Bash result of exit code 137 five seconds after the nextrebuild isResume=trueline.hostProcessAgeMswas continuous throughout, so the agent host itself never restarted. The renderer log shows[AgentHostFirstResponse] … invocationKind="newTurn" outcome="success" … hasResponseText:falsefor the blank turn. In that session 5 of 6 turns rebuilt the session and no rebuild reason was logged.Changes (
src/vs/platform/agentHost/node/claude)ClaudePromptQueue.settle(uuids)pops the yielded entry aresultnames viauser_message_uuid/user_message_uuids. A result for an SDK-initiated turn no longer consumes a pending user prompt.settleHead()remains the fallback for CLIs that predate the field.ClaudeSdkPipelinetrackssystem:background_tasks_changed(non-ambient, replace semantics, reset onsystem:initand rebind) and exposes it asliveBackgroundTasks.ClaudeAgentSession.send()splits rebuild reasons into required (resume anchor, transport switch, owner change) and deferrable (client tools, client customizations, MCP launch enablement, additional directories). Deferrable rebuilds wait while background tasks are live, and every rebuild now logs its reason so the remaining cases are diagnosable fromagenthost.log.Tests
claudePromptQueue.test.ts: settle-by-uuid for a non-head entry; no-match leaves the pending user prompt in flight.claudeSdkPipeline.test.ts: result matching byuser_message_uuid(SDK-initiated turn keeps the user turn open), andliveBackgroundTaskstracking (replace semantics, ambient filtered, reset on init).pnpm run eslint,pnpm run typecheck-client, and./scripts/test.sh --glob "**/vs/platform/agentHost/test/**/*.test.js"(16880 passing) are clean.Not verified live
user_message_uuidis optional in the SDK types and the deferral only helps when the CLI emitsbackground_tasks_changed. SDK 0.3.304 declares both; on older CLIs both paths fall back to today's behavior.