Skip to content

Agent Host: keep Claude background tasks alive across turns and match results to prompts - #345986

Open
Martin Carapia (martincarapia) wants to merge 1 commit into
microsoft:mainfrom
martincarapia:fix/agent-host-claude-rebuild-subagents
Open

Martin Carapia (martincarapia) wants to merge 1 commit into
microsoft:mainfrom
martincarapia:fix/agent-host-claude-rebuild-subagents

Conversation

@martincarapia

@martincarapia Martin Carapia (martincarapia) commented Nov 4, 2026 •

Copy link
Copy Markdown

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, 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).

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:

20:02:05  parent spawns background Agent (toolu_016pJGZhJtRcdVDCKA6ZzHrb)
20:02:17  parent turn ends; subagent keeps working (tool calls through 20:06:09)
20:06:49  [Claude] session d113704d-…: rebuild isResume=true agent=(none)   <- user sent a follow-up
20:06:50  queue yielded sdkUuid=request_a40f7966-…
20:06:53  result for sdkUuid=request_a40f7966-…      <- 2.4 s later: the stopped-task notice turn
20:07:06  result for sdkUuid=undefined               <- the real reply, never rendered

The parent transcript at 20:06:53 holds the CLI's <task-notification> with status=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 next rebuild isResume=true line. hostProcessAgeMs was continuous throughout, so the agent host itself never restarted. The renderer log shows [AgentHostFirstResponse] … invocationKind="newTurn" outcome="success" … hasResponseText:false for 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 a result names via user_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.
  • ClaudeSdkPipeline tracks system:background_tasks_changed (non-ambient, replace semantics, reset on system:init and rebind) and exposes it as liveBackgroundTasks.
  • 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 from agenthost.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 by user_message_uuid (SDK-initiated turn keeps the user turn open), and liveBackgroundTasks tracking (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_uuid is optional in the SDK types and the deferral only helps when the CLI emits background_tasks_changed. SDK 0.3.304 declares both; on older CLIs both paths fall back to today's behavior.

…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
Copilot AI balanced review requested due to automatic review settings November 4, 2026 06:41
@martincarapia Martin Carapia (martincarapia) changed the title Agent Host: keep Claude background tasks alive across turns and match resultsto prompts Agent Host: keep Claude background tasks alive across turns and match results to prompts Nov 4, 2026
@vs-code-engineering

Copy link
Copy Markdown
Contributor

📬 CODENOTIFY

The following users are being notified based on files changed in this PR:

TylerLeonhardt

Matched files:

  • src/vs/platform/agentHost/node/claude/claudeAgentSession.ts
  • src/vs/platform/agentHost/node/claude/claudePromptQueue.ts
  • src/vs/platform/agentHost/node/claude/claudeSdkPipeline.ts

@martincarapia

Copy link
Copy Markdown
Author

Design notes for reviewers

A 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

  • The symptom (background subagents never "come back", follow-up messages render blank) first looked like a Claude Code extension or network issue. The logs ruled both out: agenthost.log showed entrypoint: sdk-ts, hostProcessAgeMs was continuous across every failure, and there were no abort or disconnect lines. The failures all sit inside the built-in Agent Host, hence a VS Code PR rather than an SDK or extension report.
  • The anchor was the pairing of rebuild isResume=true immediately followed by a result for the user's sdkUuid within ~2 s and then a second result for sdkUuid=undefined. The subagent transcripts ending in a Bash exit code 137 a few seconds after each rebuild line tied the SIGKILL to WarmQuery.close() on the old subprocess.
  • The send() pre-flight has seven independent conditions that trigger _rebindForSyncedState() and none were logged, so the log could not say which one fired on a given turn. That is why reason logging is part of this PR rather than a follow-up.

Alternatives considered and why they were not taken

Option Why not
Stop rebuilding between turns altogether Three triggers are correctness-critical: a pending resume anchor (set by truncateChat), a transport switch, and an owner change. Skipping those would resume the wrong conversation prefix or talk to the wrong process. They stay unconditional.
Only fix the dropped reply (identity-based settling) and leave the rebuild alone Would make the follow-up render, but the subagents would still be SIGKILLed and the stopped-task notice would still appear. The user-visible bug is the lost work, not only the blank turn.
Only defer the rebuild and leave positional settling alone Required rebuilds still happen, and the CLI still runs its stopped-task notice as a turn of its own after any resume. Any SDK-initiated turn would keep misattributing results to the user's prompt. Both halves are needed.
Drive deferral from the existing claudeSubagentRegistry (task_started / task_notification) Those are edge events for Agent tasks only. system:background_tasks_changed is a level signal with replace semantics and covers every task type the CLI considers live, so it is the authoritative source. The registry is unchanged.
Include ambient tasks in the live set Ambient tasks are long-lived by design and would defer the rebuild indefinitely. They are filtered out.
Persist or hand off background tasks across the rebuild The SDK exposes no API for transferring running tasks to a new process.
Keep positional settling and special-case the stopped-task notice by text Fragile, and SDKResultMessage.user_message_uuid / user_message_uuids already exist to express ownership. settleHead() is retained only as the fallback for CLIs that predate the field.

Behaviour that changes and known limits

  • While non-ambient background tasks are live, a turn that would have rebuilt for client-tool, customization, MCP-enablement or additional-directory changes instead runs against the existing process with the previous configuration. The next send() after the task set empties performs the deferred rebuild. The deferral is logged with the reasons it skipped.
  • A non-ambient task that never finishes defers those rebuilds until the user restarts the session. No timeout was added, to keep the change minimal and because the SDK already decides what counts as live. Happy to add one if preferred.
  • liveBackgroundTasks is reset on system:init and after a rebind, since the old process's tasks are dead at that point and stale state would otherwise block deferrals forever.
  • A result whose user_message_uuid matches nothing in the yielded queue is treated as an SDK-initiated turn and leaves the user's turn open. A result with no uuid falls back to settling the head, which is today's behaviour.

Verification

  • Unit tests cover settle-by-uuid for a non-head entry, a no-match result leaving the user prompt in flight, liveBackgroundTasks replace semantics with ambient filtering, and reset on init.
  • pnpm run eslint, pnpm run typecheck-client, and the full agentHost test glob (16880 passing) are clean.
  • Not verified against a live CLI: SDK 0.3.304 declares both user_message_uuid and background_tasks_changed, but I did not capture them on the wire. On older CLIs both paths degrade to current behaviour. The way to confirm is to repeat the repro and look for the new "deferring rebuild" and "result for SDK-initiated turn" lines in agenthost.log in place of result for sdkUuid=undefined.

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.

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.

🟡 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

Comment on lines +1115 to +1116
if (this.clientCustomizationsDiff.hasDifferenceFrom(this._desiredClientPluginPaths(this._owner.get()))) {
deferrable.push('client customizations');
Comment on lines +1115 to +1116
if (this.clientCustomizationsDiff.hasDifferenceFrom(this._desiredClientPluginPaths(this._owner.get()))) {
deferrable.push('client customizations');
Comment on lines +161 to +173
/**
* 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);
}
Comment on lines +740 to +742
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;
@microsoft-github-policy-service

Copy link
Copy Markdown
Contributor

Martin Carapia (@martincarapia) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

This branch has not been deployed

No deployments
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.

Claude agent host: between-turn 'resume rebuild' kills subagents and drops replies

3 participants