Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
fix(console): keep a session with running background subagents from parking (#642)
Louis Amaudruz36577334aa6c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 741148eda..d85e4834c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1357,6 +1357,18 @@ version of their own to them without also giving them a release of their own.### [Unreleased]+#### Fixed+- **A Claude Code session is no longer parked while its background subagents+ are still working.** The idle timer only looked at turns, so a session whose+ turn had ended with subagents still running in the background was stopped+ after the idle timeout, taking the subagents with it. Those subagents now+ count as activity, and the idle wait starts again when the last one stops.++#### Changed+- **An idle session now parks after a day rather than 30 minutes.** Set+ `SWITCH_SESSION_PARK_AFTER_MS` on the session host to choose another+ timeout, or `off` to never park.+### [0.38.1] - 2026-10-01#### Fixeddiff --git a/console/packages/agent-providers/src/adapter.ts b/console/packages/agent-providers/src/adapter.tsindex b5a8c373f..672335474 100644--- a/console/packages/agent-providers/src/adapter.ts+++ b/console/packages/agent-providers/src/adapter.ts@@ -148,6 +148,12 @@ export interface ProviderAdapter {stopSession(sessionId: string): Promise<void>;stopAll(): Promise<void>;hasSession(sessionId: string): boolean;+ /**+ * Whether the session is still at work outside any turn — subagents started+ * in the background that outlive the turn that started them. A session with+ * background work is not idle. Absent means the provider has none to report.+ */+ hasBackgroundWork?(sessionId: string): boolean;/** Events for every session this adapter drives. Returns the unsubscribe. */subscribe(listener: (event: ProviderRuntimeEvent) => void): () => void;diff --git a/console/packages/agent-providers/src/claude/claude-adapter.test.ts b/console/packages/agent-providers/src/claude/claude-adapter.test.tsindex a1bdca5c9..0a78e2bb3 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.test.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.test.ts@@ -1,4 +1,5 @@-import { describe, expect, it } from 'vitest';+import { randomUUID } from 'node:crypto';+import { describe, expect, it, vi } from 'vitest';import type { ProviderSessionStartInput, RuntimeMode } from '../adapter';import { ProviderConversationUnavailableError } from '../adapter';import { EventRecorder } from '../testing/event-recorder';@@ -1093,3 +1094,93 @@ describe('ClaudeAdapter model switching', () => {expect(sdk.options().effort).toBeUndefined();});});++describe('ClaudeAdapter background subagents', () => {+ function task(subtype: string, fields: Record<string, unknown>) {+ return { type: 'system', subtype, uuid: randomUUID(), session_id: 'native-1', ...fields };+ }++ it('reports background work while a subagent outlives its turn, until it settles', async () => {+ const { sdk, adapter, recorder } = await startSession();+ await adapter.sendTurn({ sessionId: SESSION, turnId: 'turn-1', text: 'fan out' });+ const query = sdk.latest();+ const [sent] = await query.waitForSent(1);+ query.emit(+ task('task_started', {+ task_id: 'agent-1',+ task_type: 'local_agent',+ subagent_type: 'Explore',+ description: 'Search',+ is_backgrounded: true,+ })+ );+ query.emit(+ task('task_started', {+ task_id: 'shell-1',+ task_type: 'local_bash',+ description: 'dev server',+ is_backgrounded: true,+ })+ );+ query.emit(resultMessage([sent!.uuid!]));+ await recorder.waitFor('turn.completed', () => true, 1_000);+ expect(adapter.hasBackgroundWork(SESSION)).toBe(true);++ query.emit(+ task('task_notification', {+ task_id: 'agent-1',+ status: 'completed',+ output_file: '',+ summary: 'done',+ })+ );+ await vi.waitFor(() => expect(adapter.hasBackgroundWork(SESSION)).toBe(false));+ await adapter.stopAll();+ });++ it('counts a foreground subagent only once it is moved to the background', async () => {+ const { sdk, adapter } = await startSession();+ await adapter.sendTurn({ sessionId: SESSION, turnId: 'turn-1', text: 'fan out' });+ const query = sdk.latest();+ query.emit(+ task('task_started', {+ task_id: 'agent-1',+ task_type: 'local_agent',+ description: 'Search',+ is_backgrounded: false,+ })+ );+ query.emit(task('task_updated', { task_id: 'agent-1', patch: { is_backgrounded: true } }));+ await vi.waitFor(() => expect(adapter.hasBackgroundWork(SESSION)).toBe(true));+ query.emit(task('task_updated', { task_id: 'agent-1', patch: { status: 'killed' } }));+ await vi.waitFor(() => expect(adapter.hasBackgroundWork(SESSION)).toBe(false));+ await adapter.stopAll();+ });++ it('takes the background task list as the truth, ignoring ambient tasks', async () => {+ const { sdk, adapter } = await startSession();+ const query = sdk.latest();+ query.emit(+ task('task_started', {+ task_id: 'stale',+ task_type: 'local_agent',+ description: 'x',+ is_backgrounded: true,+ })+ );+ await vi.waitFor(() => expect(adapter.hasBackgroundWork(SESSION)).toBe(true));+ query.emit(+ task('background_tasks_changed', {+ tasks: [{ task_id: 'watcher', task_type: 'local_agent', description: 'w', ambient: true }],+ })+ );+ await vi.waitFor(() => expect(adapter.hasBackgroundWork(SESSION)).toBe(false));+ query.emit(+ task('background_tasks_changed', {+ tasks: [{ task_id: 'agent-2', task_type: 'local_agent', description: 'y' }],+ })+ );+ await vi.waitFor(() => expect(adapter.hasBackgroundWork(SESSION)).toBe(true));+ await adapter.stopAll();+ });+});diff --git a/console/packages/agent-providers/src/claude/claude-adapter.ts b/console/packages/agent-providers/src/claude/claude-adapter.tsindex c15747c87..41ed7bb08 100644--- a/console/packages/agent-providers/src/claude/claude-adapter.ts+++ b/console/packages/agent-providers/src/claude/claude-adapter.ts@@ -218,6 +218,27 @@ interface SessionState {*/usage: CumulativeUsage;unreportedUsage: TokenUsage[];+ /**+ * Subagent tasks the CLI is running, by task id, and whether each runs in+ * the background. A background one outlives the turn that started it, so+ * the session is still at work after the turn ends.+ */+ subagentTasks: Map<string, { backgrounded: boolean }>;+}++/** Task types that are agents doing work, rather than shells or tool calls. */+const SUBAGENT_TASK_TYPES = new Set(['local_agent', 'remote_agent', 'local_workflow']);++function isSubagentTask(task: {+ task_type?: string;+ subagent_type?: string;+ ambient?: boolean;+ skip_transcript?: boolean;+}): boolean {+ if (task.ambient || task.skip_transcript) return false;+ return task.task_type !== undefined+ ? SUBAGENT_TASK_TYPES.has(task.task_type)+ : task.subagent_type !== undefined;}/** An async iterable the adapter pushes into for the life of the session. */@@ -351,6 +372,14 @@ export class ClaudeAdapter implements ProviderAdapter {return this.sessions.has(sessionId);}+ /** Whether subagents started in the background are still running. */+ hasBackgroundWork(sessionId: string): boolean {+ const session = this.sessions.get(sessionId);+ if (!session) return false;+ for (const task of session.subagentTasks.values()) if (task.backgrounded) return true;+ return false;+ }+/*** Start a Claude Code session.*@@ -438,6 +467,7 @@ export class ClaudeAdapter implements ProviderAdapter {exited: false,usage: new CumulativeUsage(),unreportedUsage: [],+ subagentTasks: new Map(),};this.sessions.set(input.sessionId, session);this.emit(session, { type: 'session.state.changed', status: 'starting' });@@ -684,6 +714,7 @@ export class ClaudeAdapter implements ProviderAdapter {private handleMessage(session: SessionState, message: SDKMessage): void {if (message.type === 'result') this.recordUsage(session, message);+ this.trackSubagentTasks(session, message);if (session.compaction) {if (message.type === 'system' && message.subtype === 'compact_boundary')session.compaction.boundary = true;@@ -732,6 +763,50 @@ export class ClaudeAdapter implements ProviderAdapter {}}+ /**+ * Follows the CLI's subagent tasks, which compaction does not pause. The+ * `background_tasks_changed` level replaces what the edges built up, so a+ * missed notification cannot leave a task counted forever.+ */+ private trackSubagentTasks(session: SessionState, message: SDKMessage): void {+ const tasks = session.subagentTasks;+ if (message.type === 'result') {+ // A foreground task blocks the turn it runs in, so none outlives it.+ for (const [taskId, task] of tasks) if (!task.backgrounded) tasks.delete(taskId);+ return;+ }+ if (message.type !== 'system') return;+ switch (message.subtype) {+ case 'task_started':+ if (isSubagentTask(message))+ tasks.set(message.task_id, { backgrounded: message.is_backgrounded !== false });+ return;+ case 'task_updated': {+ const task = tasks.get(message.task_id);+ if (!task) return;+ const status = message.patch.status;+ if (status === 'completed' || status === 'failed' || status === 'killed')+ tasks.delete(message.task_id);+ else if (message.patch.is_backgrounded !== undefined)+ task.backgrounded = message.patch.is_backgrounded;+ return;+ }+ case 'task_notification':+ tasks.delete(message.task_id);+ return;+ case 'background_tasks_changed': {+ const foreground = [...tasks].filter(([, task]) => !task.backgrounded);+ tasks.clear();+ for (const [taskId, task] of foreground) tasks.set(taskId, task);+ for (const task of message.tasks)+ if (isSubagentTask(task)) tasks.set(task.task_id, { backgrounded: true });+ return;+ }+ default:+ return;+ }+ }+private handleStreamEvent(session: SessionState,event: unknown,diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.tsindex c42b7f4a2..3179ea276 100644--- a/console/packages/agent-providers/src/host/session-host.ts+++ b/console/packages/agent-providers/src/host/session-host.ts@@ -461,6 +461,11 @@ export class HostedSession {return this.decisionPending;}+ /** Work the provider is doing outside any turn, such as background subagents. */+ get backgroundWorkRunning(): boolean {+ return this.adapter.hasBackgroundWork?.(this.config.session.sessionId) ?? false;+ }+snapshot(): Snapshot {return this.replica.snapshot();}diff --git a/console/packages/agent-providers/src/host/shared-host.test.ts b/console/packages/agent-providers/src/host/shared-host.test.tsindex 96766ecdb..c6d7e0e87 100644--- a/console/packages/agent-providers/src/host/shared-host.test.ts+++ b/console/packages/agent-providers/src/host/shared-host.test.ts@@ -13,7 +13,7 @@ import {import type { ProviderRuntimeEvent } from '../events';import { stubSwitchFetch } from '../testing/agent-sessions-server';import { connectParent } from './session-channel';-import { runSharedHost } from './shared-host';+import { parkAfterMs, runSharedHost } from './shared-host';import { hostParked } from './shared-state';const roots: string[] = [];@@ -99,6 +99,8 @@ async function start(rooms?: boolean;ask?: 'approval' | 'questions';parkAfterMs?: number;+ /** The provider reports work, such as subagents, still running outside any turn. */+ backgroundWork?: { running: boolean };resettable?: boolean;/** What the launcher recorded when it created this session's root, if it did. */owedStart?: string;@@ -196,6 +198,9 @@ async function start(}),stopAll: vi.fn(async () => {}),hasSession: () => live,+ ...(opts.backgroundWork+ ? { hasBackgroundWork: () => live && opts.backgroundWork!.running }+ : {}),subscribe: (fn) => {listener = fn;return () => {@@ -665,6 +670,16 @@ it('takes commands and room messages from its parent, and pushes what it records}});+it('parks after a day idle unless the environment says otherwise', () => {+ vi.stubEnv('SWITCH_SESSION_PARK_AFTER_MS', '');+ expect(parkAfterMs()).toBe(24 * 60 * 60 * 1000);+ vi.stubEnv('SWITCH_SESSION_PARK_AFTER_MS', '5000');+ expect(parkAfterMs()).toBe(5000);+ vi.stubEnv('SWITCH_SESSION_PARK_AFTER_MS', 'off');+ expect(parkAfterMs()).toBeNull();+ vi.unstubAllEnvs();+});+it('parks itself once it has sat idle, and says so for whoever would start it', async () => {const host = await start({ parkAfterMs: 300 });await vi.waitFor(async () => expect(await hostParked(host.root)).toBe(true), { timeout: 5000 });@@ -684,6 +699,33 @@ it('does not park while a turn waits on a person', async () => {}});+it('does not park while subagents the provider started are still running', async () => {+ const backgroundWork = { running: true };+ const host = await start({ rooms: true, backgroundWork, parkAfterMs: 500 });+ try {+ await host.parent.ask({ type: 'room', handoff: roomMessage(1, 'Fan out') });+ await vi.waitFor(() => expect(host.turns).toHaveLength(1), { timeout: 5000 });+ // The turn ends with its subagents still at work in the background.+ host.emit({+ type: 'turn.completed',+ turnId: host.turns[0]!.turnId,+ outcome: 'completed',+ usage: [],+ });+ await new Promise((resolve) => setTimeout(resolve, 1500));+ expect(await hostParked(host.root)).toBe(false);+ // Once they finish the session counts as idle from then, not from the turn.+ backgroundWork.running = false;+ await new Promise((resolve) => setTimeout(resolve, 250));+ expect(await hostParked(host.root)).toBe(false);+ await vi.waitFor(async () => expect(await hostParked(host.root)).toBe(true), {+ timeout: 5000,+ });+ } finally {+ await host.stop();+ }+});+it('keeps running room messages while Switch cannot take its reports', async () => {const host = await start({ rooms: true });try {diff --git a/console/packages/agent-providers/src/host/shared-host.ts b/console/packages/agent-providers/src/host/shared-host.tsindex 18b3ac1f9..9cf5cec2c 100644--- a/console/packages/agent-providers/src/host/shared-host.ts+++ b/console/packages/agent-providers/src/host/shared-host.ts@@ -58,11 +58,11 @@ export type SharedHostOptions = {};/** How long a session sits idle before its host parks, unless the environment says otherwise. */-const PARK_AFTER_MS = 30 * 60 * 1000;+const PARK_AFTER_MS = 24 * 60 * 60 * 1000;/*** The park timeout for this process: `SWITCH_SESSION_PARK_AFTER_MS` in- * milliseconds, `off` to never park, or 30 minutes when unset.+ * milliseconds, `off` to never park, or one day when unset.*/export function parkAfterMs(): number | null {const value = process.env.SWITCH_SESSION_PARK_AFTER_MS;@@ -614,9 +614,17 @@ export async function runSharedHost(host.onPublished((event) => parent.push(event));parent.ready();}- /** Nothing running, nothing waiting on a person, nothing handed over, for long enough. */+ /**+ * Nothing running, nothing waiting on a person, nothing handed over, for+ * long enough. Subagents still at work after their turn ended count as+ * running, and the wait starts again from when the last of them stops.+ */const idleEnough = (): boolean => {if (!parent || options.parkAfterMs === null) return false;+ if (host!.backgroundWorkRunning) {+ active();+ return false;+ }if (performance.now() - lastActive < options.parkAfterMs) return false;const snapshot = host!.snapshot();return (diff --git a/docs/session-activity-handoff.md b/docs/session-activity-handoff.mdindex 3958c1673..4304731e8 100644--- a/docs/session-activity-handoff.md+++ b/docs/session-activity-handoff.md@@ -225,7 +225,7 @@ Compatibility with deployed Consoles is waived (owner's call).raises: the data cannot be rebuilt.9. Idle sessions park. A host with a parent that has had nothing to do for- `SWITCH_SESSION_PARK_AFTER_MS` (30 minutes by default, `off` to disable)+ `SWITCH_SESSION_PARK_AFTER_MS` (one day by default, `off` to disable)records `parked` in `shared-state.jsonl` and exits. The idle check needsno turn running, no open request, no reset decision and no room messagequeued. It stops answering its parent first, so a request that arrives