Skip to content

Agent host (Claude): background subagents stay "running" after they finish ("4 subagents running" never clears) #348900

Description

Summary

In a Claude agent host session, subagents started with run_in_background: true keep showing as running after they finish. The chat footer stays at "4 subagents running", and each subagent's read-only chat tab still shows a live status (Working, Considering, Analyzing, Reasoning). This was still the case 30+ minutes after all four had finished.

On the Claude side the subagents ended normally:

  • each subagents/agent-<id>.meta.json has "finished": true;
  • each subagent transcript ends with its SubagentHandback tool call, the tool result {"success":true,"message":"Report delivered to your caller."}, then a successful SubagentStop hook;
  • the parent conversation received a <task-notification> with <status>completed</status> and the matching <tool-use-id> for each one, and continued.

Environment

  • VS Code 1.146.0 (69047191fc427f2f92828279aae1d90d8eeda7ab), macOS 27.2.1, arm64
  • Agent host Claude SDK @anthropic-ai/claude-agent-sdk 0.3.304 (bundled CLI 2.1.304), from agent-host/sdk-cache
  • Claude Code extension 2.1.326
  • Session in the Chat view's Claude tab, Auto Mode

Steps to reproduce

  1. In a Claude agent host session, have the agent launch several subagents with the Agent tool and run_in_background: true. In my case these were four feature-dev:code-reviewer / general-purpose agents that each ran 3–12 minutes and ended through SubagentHandback.
  2. Let them all finish. The parent gets a completion notification for each one.
  3. Optional, possibly a trigger: the session is later rebuilt. agenthost.log: rebinding before turn … for changed client customizations → rebuild isResume=true.

Expected: each subagent's tool part becomes inactive and the "N subagents running" footer clears.

Actual: the footer stays at "4 subagents running" and the four subagent tabs keep their in-progress status. Stopping the tasks from the parent fails with "No task found" because the CLI has already removed them.

What I found in the 1.146.0 code

  • The renderer counts a subagent as running when toolSpecificData.kind === "subagent" and toolSpecificData.isActive ?? !isComplete(part). _observeSubagentSession sets isActive = !!subagentChat.activeTurn.
  • For a background spawn, task_started sets spawn.background = true. The Agent tool's placeholder tool_result therefore doesn't complete it (S && !S.background && S.markCompleted()). The only path that emits subagent_completed is the system / task_notification handler. That handler returns [] if tool_use_id is missing, if the status isn't completed/failed/stopped, or if getSpawn(tool_use_id) is undefined or already marked completed. Each of these drops the event silently, so the subagent chat's activeTurn is never closed.
  • The bundled CLI 2.1.304 emits task_notification with tool_use_id: task.toolUseId, including the handback/handback_report path. So the id should be present, which suggests the spawn lookup fails or the event is lost (for example across a rebuild).
  • agenthost.log at info level records none of this: there's no log line when a task_notification is dropped.

Possibly relevant timing:

  • All four subagents finished between 13:08 and 13:19 local time.
  • The session was rebuilt (isResume=true) at 13:38:53.
  • The screenshot showing "4 subagents running" was taken at 13:39:24.

#347909 / #348078 (a rebuilt Claude session never delivers completion to the UI) may share a cause.

A fifth, trivial background subagent started later, after the rebuild, was followed 12 s after it finished by [ProtocolServer] Request 'subscribe' … failed Resource not found: ahp-chat:/<subagent chat>. That error handler is the other place that clears isActive. No such line exists for the four stuck subagents.

Suggestions

  • Log (at least at debug) when a task_notification doesn't map to a known spawn.
  • On resume or rebuild, reconcile restored subagent chats against the SDK's task state or meta.json (finished: true) instead of leaving activeTurn open.
  • Treat a subagent whose transcript ends with a SubagentHandback result followed by SubagentStop as complete.

Activity

  1. sohampatwardhan commented on Nov 17, 2026

    @sohampatwardhan
    Author

    Root cause, and a patch for the most likely path

    I traced this on main (fc08017c). The problem is before mapSubagentSystemMessage. In most background runs that function never sees the task_notification.

    ClaudeSdkPipeline._processMessages passes turnId = this._queue.peekParent()?.turnId to ClaudeSdkMessageRouter.handle. While the parent chat is idle the queue is empty, so turnId is undefined. handle then returns before mapping anything:

    if (turnId === undefined) {
    	return;
    }

    A background spawn usually finishes after the parent's turn has ended (launch, end the turn, wait for the notification), so its terminal system/task_notification arrives with no turn queued and is dropped. Nothing else emits subagent_completed for a background spawn, and the subagent chat's activeTurn stays open. That matches the report: the CLI completed and removed the tasks, the parent got <task-notification> and continued, the footer stayed at "4 subagents running", and nothing was logged. The existing router test handle with turnId=undefined produces no signals asserts this drop, but only for a stream event.

    SubagentSpawn does not depend on a turn. Background spawns survive drainForegroundSpawns() at turn end, and AgentSideEffects.completeSubagentSession closes the subagent's own turn without needing a parent turn. So the turn-less system message can just be routed.

    Patch

    1. claudeSdkMessageRouter.ts: when turnId === undefined and the message is type: 'system', run it through mapSubagentSystemMessage and fire the resulting signals. Everything else is still dropped while idle, as before.
    2. claudeSubagentSignals.ts: mapSubagentSystemMessage takes an optional ILogService. A terminal task_notification that closes nothing is now logged: info when the tool_use_id matches no open spawn (the rebuild case below), debug when the id is missing or the spawn was already completed. This is the first suggestion in the report.
    3. claudeMapSessionEvents.ts: passes its logService through.
    4. Tests:
      • claudeSdkMessageRouter.test.ts: an Agent spawn, task_started, and the "launched" tool_result, all on turn-1, then two task_notifications with turnId = undefined. Exactly one subagent_completed is expected. On unpatched main this test fails (no signal).
      • claudeSubagentSignals.test.ts: covers the new log lines.

    Verification, run locally on a partial checkout installed with pnpm install --ignore-scripts:

    • tsc -p src/tsconfig.json --noEmit gives the same error set as unmodified main. The remaining errors are all electron and excluded extensions/ paths.
    • The Claude agent-host suites pass under mocha, including claudeSdkMessageRouter (21), claudeSubagentSignals (12), claudeMapSessionEvents, claudeSubagentRegistry, claudeSdkPipeline (29), and claudeReplayMapper.
    • claudeAgent.test.ts would not load without the native vscode_fs addon, so I did not run it. One claudeSavedChatReader test and one claudeAgentSdkService test fail for environment reasons only (no native sqlite3, no test bootstrap for FileAccess).
    Diff against fc08017c
    diff --git a/src/vs/platform/agentHost/node/claude/claudeMapSessionEvents.ts b/src/vs/platform/agentHost/node/claude/claudeMapSessionEvents.ts
    index 671c0b34..7c4f0617 100644
    --- a/src/vs/platform/agentHost/node/claude/claudeMapSessionEvents.ts
    +++ b/src/vs/platform/agentHost/node/claude/claudeMapSessionEvents.ts
    @@ -292,7 +292,7 @@ export function mapSDKMessageToAgentSignals(
     		default:
     			// Phase 12 step 7 — system subtypes for subagent task discrimination.
     			if (message.type === 'system') {
    -				return mapSubagentSystemMessage(message, chat, registry);
    +				return mapSubagentSystemMessage(message, chat, registry, logService);
     			}
     			return [];
     	}
    diff --git a/src/vs/platform/agentHost/node/claude/claudeSdkMessageRouter.ts b/src/vs/platform/agentHost/node/claude/claudeSdkMessageRouter.ts
    index 5fcf9758..d7e88014 100644
    --- a/src/vs/platform/agentHost/node/claude/claudeSdkMessageRouter.ts
    +++ b/src/vs/platform/agentHost/node/claude/claudeSdkMessageRouter.ts
    @@ -16,6 +16,7 @@ import { subagentChatUri } from '../../common/agentHostChatMinting.js';
     import { ClaudeFileEditObserver } from './claudeFileEditObserver.js';
     import { ClaudeMapperState, mapSDKMessageToAgentSignals } from './claudeMapSessionEvents.js';
     import type { SubagentRegistry } from './claudeSubagentRegistry.js';
    +import { mapSubagentSystemMessage } from './claudeSubagentSignals.js';
     import { ClaudeTerminalOutputs } from './claudeTerminalOutput.js';
     import type { SessionClientToolsModel } from './clientTools/claudeSessionClientToolsModel.js';
     
    @@ -80,6 +81,13 @@ export class ClaudeSdkMessageRouter extends Disposable {
     			}
     		}
     		if (turnId === undefined) {
    +			// A background subagent usually finishes after the parent's turn
    +			// has ended, so its `task_started` / `task_notification` arrive
    +			// while no turn is queued. Those signals close the subagent chat
    +			// and need no turn id; dropping them leaves it running forever.
    +			if (message.type === 'system') {
    +				this._fireSystemSignals(message);
    +			}
     			return;
     		}
     		try {
    @@ -101,6 +109,16 @@ export class ClaudeSdkMessageRouter extends Disposable {
     		}
     	}
     
    +	private _fireSystemSignals(message: Extract<SDKMessage, { type: 'system' }>): void {
    +		try {
    +			for (const signal of mapSubagentSystemMessage(message, this._chatChannelUri, this._subagents, this._logService)) {
    +				this._onDidProduceSignal.fire(signal);
    +			}
    +		} catch (mapperErr) {
    +			this._logService.warn(`[ClaudeSdkMessageRouter] turn-less system message mapper threw, skipping: ${mapperErr}`);
    +		}
    +	}
    +
     	private _getEditChatUri(parentToolUseId: string | null): string {
     		return parentToolUseId
     			? subagentChatUri(this._owner.getSubagentChatUriFormat(), this._owner.get().toString(), this._chatChannelUri.toString(), parentToolUseId)
    diff --git a/src/vs/platform/agentHost/node/claude/claudeSubagentSignals.ts b/src/vs/platform/agentHost/node/claude/claudeSubagentSignals.ts
    index b226faf4..3c3d0901 100644
    --- a/src/vs/platform/agentHost/node/claude/claudeSubagentSignals.ts
    +++ b/src/vs/platform/agentHost/node/claude/claudeSubagentSignals.ts
    @@ -6,6 +6,7 @@
     import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk';
     import type { URI } from '../../../../base/common/uri.js';
     import type { Mutable } from '../../../../base/common/types.js';
    +import type { ILogService } from '../../../log/common/log.js';
     import { toToolCallMeta, type IToolCallMeta } from '../../common/meta/agentToolCallMeta.js';
     import type { AgentSignal, IAgentSubagentStartedSignal } from '../../common/agent.js';
     import { ActionType } from '../../common/state/sessionActions.js';
    @@ -97,11 +98,17 @@ export function tagWithParent(
      * All other system subtypes (`compact_boundary`, `task_progress`,
      * `task_updated`, hooks, etc.) fall through with `[]`; non-subagent
      * system handling stays in the mapper proper.
    + *
    + * Does not need a turn id: the router also calls it while the parent
    + * is idle, which is when most background subagents finish. A terminal
    + * `task_notification` that cannot be mapped to an open spawn is logged,
    + * because the subagent chat it was meant to close stays active.
      */
     export function mapSubagentSystemMessage(
     	message: Extract<SDKMessage, { type: 'system' }>,
     	chat: URI,
     	registry: SubagentRegistry,
    +	logService?: ILogService,
     ): AgentSignal[] {
     	const sub = (message as { subtype?: string }).subtype;
     	if (sub === 'task_started') {
    @@ -113,16 +120,22 @@ export function mapSubagentSystemMessage(
     		return [];
     	}
     	if (sub === 'task_notification') {
    -		const m = message as { tool_use_id?: string; status?: string };
    -		if (!m.tool_use_id) {
    -			return [];
    -		}
    +		const m = message as { task_id?: string; tool_use_id?: string; status?: string };
     		const status = m.status;
     		if (status !== 'completed' && status !== 'failed' && status !== 'stopped') {
     			return [];
     		}
    +		if (!m.tool_use_id) {
    +			logService?.debug(`[claudeSubagentSignals] task_notification status=${status} task_id=${m.task_id ?? '<none>'} has no tool_use_id; no subagent chat closed`);
    +			return [];
    +		}
     		const spawn = registry.getSpawn(m.tool_use_id);
    -		if (!spawn || !spawn.markCompleted()) {
    +		if (!spawn) {
    +			logService?.info(`[claudeSubagentSignals] task_notification status=${status} for tool_use_id=${m.tool_use_id} matches no open subagent spawn; no subagent chat closed`);
    +			return [];
    +		}
    +		if (!spawn.markCompleted()) {
    +			logService?.debug(`[claudeSubagentSignals] task_notification status=${status} for tool_use_id=${m.tool_use_id} ignored; spawn already completed`);
     			return [];
     		}
     		const toolUseId = m.tool_use_id;
    diff --git a/src/vs/platform/agentHost/test/node/claudeSdkMessageRouter.test.ts b/src/vs/platform/agentHost/test/node/claudeSdkMessageRouter.test.ts
    index d163f655..3baf33a2 100644
    --- a/src/vs/platform/agentHost/test/node/claudeSdkMessageRouter.test.ts
    +++ b/src/vs/platform/agentHost/test/node/claudeSdkMessageRouter.test.ts
    @@ -160,6 +160,25 @@ suite('ClaudeSdkMessageRouter', () => {
     		assert.deepStrictEqual(signals, []);
     	});
     
    +	test('background subagent task_notification that arrives while the parent is idle still completes the subagent', async () => {
    +		const { router, signals } = createRouter(disposables);
    +		await router.handle(assistantMessage([
    +			{ type: 'tool_use', id: 'toolu_bg', name: 'Agent', input: { description: 'bg', subagent_type: 'general-purpose', prompt: 'p', run_in_background: true } },
    +		]), 'turn-1');
    +		await router.handle({ type: 'system', subtype: 'task_started', task_id: 't1', tool_use_id: 'toolu_bg', description: 'bg' } as unknown as SDKMessage, 'turn-1');
    +		await router.handle(userMessage([
    +			{ type: 'tool_result', tool_use_id: 'toolu_bg', content: 'Async agent launched successfully.' },
    +		]), 'turn-1');
    +		// The parent's turn has ended; the subagent finishes later.
    +		await router.handle({ type: 'system', subtype: 'task_notification', task_id: 't1', tool_use_id: 'toolu_bg', status: 'completed', output_file: 'o', summary: 's' } as unknown as SDKMessage, undefined);
    +		await router.handle({ type: 'system', subtype: 'task_notification', task_id: 't1', tool_use_id: 'toolu_bg', status: 'completed', output_file: 'o', summary: 's' } as unknown as SDKMessage, undefined);
    +
    +		assert.deepStrictEqual(
    +			signals.flatMap(s => s.kind === 'subagent_completed' ? [{ chat: s.chat.toString(), toolCallId: s.toolCallId }] : []),
    +			[{ chat: buildDefaultChatUri('claude:/sess-1'), toolCallId: 'toolu_bg' }],
    +		);
    +	});
    +
     	test('handle with a turnId on a text content block produces ChatResponsePart + ChatDelta signals', async () => {
     		const { router, signals } = createRouter(disposables);
     		await router.handle(makeStreamEvent('sess-1', makeMessageStart()), 'turn-1');
    diff --git a/src/vs/platform/agentHost/test/node/claudeSubagentSignals.test.ts b/src/vs/platform/agentHost/test/node/claudeSubagentSignals.test.ts
    index d0b4584f..bf972d89 100644
    --- a/src/vs/platform/agentHost/test/node/claudeSubagentSignals.test.ts
    +++ b/src/vs/platform/agentHost/test/node/claudeSubagentSignals.test.ts
    @@ -446,5 +446,28 @@ suite('claudeSubagentSignals — Phase 12 emission', () => {
     		});
     	});
     
    +	test('mapSubagentSystemMessage logs a terminal task_notification that closes no subagent chat', () => {
    +		const registry = r();
    +		const messages: string[] = [];
    +		const log = new class extends NullLogService {
    +			override info(message: string): void { messages.push(`info ${message}`); }
    +			override debug(message: string): void { messages.push(`debug ${message}`); }
    +		}();
    +		registry.recordSpawn('toolu_known');
    +
    +		mapSubagentSystemMessage({ type: 'system', subtype: 'task_notification', task_id: 't', tool_use_id: 'toolu_known', status: 'in_progress' } as unknown as SDKMessage & { type: 'system' }, SESSION, registry, log);
    +		mapSubagentSystemMessage({ type: 'system', subtype: 'task_notification', task_id: 't', status: 'completed' } as unknown as SDKMessage & { type: 'system' }, SESSION, registry, log);
    +		mapSubagentSystemMessage({ type: 'system', subtype: 'task_notification', task_id: 't', tool_use_id: 'toolu_unknown', status: 'failed' } as unknown as SDKMessage & { type: 'system' }, SESSION, registry, log);
    +		const completed = mapSubagentSystemMessage({ type: 'system', subtype: 'task_notification', task_id: 't', tool_use_id: 'toolu_known', status: 'completed' } as unknown as SDKMessage & { type: 'system' }, SESSION, registry, log);
    +
    +		assert.deepStrictEqual({ completedKinds: completed.map(s => s.kind), messages }, {
    +			completedKinds: ['subagent_completed'],
    +			messages: [
    +				'debug [claudeSubagentSignals] task_notification status=completed task_id=t has no tool_use_id; no subagent chat closed',
    +				'info [claudeSubagentSignals] task_notification status=failed for tool_use_id=toolu_unknown matches no open subagent spawn; no subagent chat closed',
    +			],
    +		});
    +	});
    +
     	// #endregion
     });

    Not covered by this patch

    Workaround until a fix ships: keep the parent turn open until the background subagents report back, for example by having the agent wait on them in the same turn rather than ending it.

  2. jlgascon-hiberuscom commented on Nov 18, 2026

    @jlgascon-hiberuscom

    I can reproduce the same issue.

    The subagents finish successfully, but VS Code continues to display N subagents running indefinitely. The parent agent continues normally, so the displayed subagent state appears to remain stale after completion.

  3. jaibatrik commented on Nov 26, 2026

    @jaibatrik

    This issue is effectively preventing me from using VS Code as the agentic control panel.

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

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions