Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 41 additions & 6 deletions src/handlers/background-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,20 @@ interface TrackedTask {
*/
sourceToolCallId?: string;
/**
* Backend task kind from the first `session.updated` sighting
* Backend task kind as last seen on a `session.updated` for this task
* (`taskKind`), verbatim: "subagent" (Agent/Task runs — the held-prompt
* chain waits on these), "workflow", "bash", … Undefined on entries
* created before the field existed.
* chain waits on these), "workflow", "bash", … Undefined until a sighting
* carries it: a subagent's SPAWN event names no kind (only the task event
* that follows it does), so a task tracked from its spawn event starts out
* kindless and is classified through `isSubagentTask` meanwhile.
*/
taskKind?: string;
/**
* The child session a subagent runs in, as last named on a sighting. The
* spawn event is the one carrier that reaches the wire before any taskKind
* does (the child is ready before the Agent call returns).
*/
childSessionId?: string;
/**
* True when acpCallId === sourceToolCallId (background Bash reusing the
* launch terminal card). Drives the terminal_exit + terminalSentData cleanup
Expand Down Expand Up @@ -151,6 +159,19 @@ function cardTitle(description: string | undefined): string {
return messages().backgroundTaskTitle((description ?? "").trim());
}

/**
* True when a tracked task is a subagent run (the kind the held-prompt chain
* waits on). Read on every check, never frozen at first sight: on 4.0 the
* first event for a subagent is its SPAWN (`SubagentSpawned`, a generic
* `session.updated` carrying `childSessionId` and NO `taskKind` — the child
* is ready before the Agent call returns), and `taskKind: "subagent"` only
* rides the task event that follows. The V2 face classifies the same way
* (`kindOf`, v2/background.ts); a taskKind that IS present always wins.
*/
function isSubagentTask(task: TrackedTask): boolean {
return task.taskKind === "subagent" || (!task.taskKind && !!task.childSessionId);
}

/**
* How long a rewind claim stays claimable. The replacement turn follows its
* admission within seconds (upstream command FIFO); anything starting later
Expand Down Expand Up @@ -266,7 +287,7 @@ export class BackgroundTaskListener implements EventListener {
*/
subagentWorkOutstanding(): boolean {
for (const task of this.tasks.values()) {
if (task.taskKind !== "subagent") continue;
if (!isSubagentTask(task)) continue;
if (task.lastStatus !== "completed" && task.lastStatus !== "failed") return true;
}
return false;
Expand All @@ -277,7 +298,7 @@ export class BackgroundTaskListener implements EventListener {
outstandingSubagentCallIds(): string[] {
const ids: string[] = [];
for (const task of this.tasks.values()) {
if (task.taskKind !== "subagent") continue;
if (!isSubagentTask(task)) continue;
if (task.lastStatus === "completed" || task.lastStatus === "failed") continue;
ids.push(task.acpCallId);
}
Expand All @@ -296,7 +317,7 @@ export class BackgroundTaskListener implements EventListener {
markOutstandingSubagentsTerminal(): number {
let flipped = 0;
for (const task of this.tasks.values()) {
if (task.taskKind !== "subagent") continue;
if (!isSubagentTask(task)) continue;
if (task.lastStatus === "completed" || task.lastStatus === "failed") continue;
task.lastStatus = "failed";
flipped++;
Expand Down Expand Up @@ -691,6 +712,17 @@ export class BackgroundTaskListener implements EventListener {
const taskId = p.taskId;
const status = p.status ?? "running";
const acpStatus = toAcpStatus(status);
// Keep the classification inputs current on EVERY sighting, before any
// path returns: a task tracked from its spawn event (no taskKind) learns
// its kind from the task event that follows, and a task event that is the
// first sighting still has to remember the child session.
const tracked = this.tasks.get(taskId);
if (tracked) {
if (p.taskKind && !tracked.taskKind) tracked.taskKind = p.taskKind;
if (p.childSessionId && !tracked.childSessionId) {
tracked.childSessionId = p.childSessionId;
}
}
// Dynamic-workflow run (taskKind "workflow"; taskId ≡ runId upstream).
// The fold-vs-fallback decision is made ONCE at first sight and stored on
// the tracked task — never re-evaluated against dispatchedToolCalls on
Expand Down Expand Up @@ -719,6 +751,7 @@ export class BackgroundTaskListener implements EventListener {
description: p.description ?? "",
lastStatus: "",
taskKind: p.taskKind,
childSessionId: p.childSessionId,
});
if (acpStatus !== "in_progress") stopWorkflowRunPoller(taskId);
else {
Expand Down Expand Up @@ -758,6 +791,7 @@ export class BackgroundTaskListener implements EventListener {
description: p.description ?? "",
lastStatus: "",
taskKind: p.taskKind,
childSessionId: p.childSessionId,
};
this.tasks.set(taskId, task);
// The launch card already exists (dispatch created it in the main
Expand All @@ -776,6 +810,7 @@ export class BackgroundTaskListener implements EventListener {
description: p.description ?? "",
lastStatus: "",
taskKind: p.taskKind,
childSessionId: p.childSessionId,
};
this.tasks.set(taskId, task);
const meta: Record<string, unknown> = {
Expand Down
124 changes: 124 additions & 0 deletions tests/background-tasks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,3 +397,127 @@ describe("BackgroundTaskListener foreign turn running state", () => {
expect(server.turnStates.map((t) => t.running)).toEqual([false, false]);
});
});

/**
* Subagent classification on the 4.0 event order (review 2026-12-01, #453).
*
* A subagent's first event is its SPAWN — a generic `session.updated` with
* `childSessionId` and NO `taskKind` (the child is ready before the Agent call
* returns; `subagent/runner.ts` emitSubagentEvent SubagentSpawned). The kind
* only rides the task event that follows. The listener used to freeze the kind
* at first sight, so every real subagent task stayed kindless for good: the
* held-prompt chain read "nothing outstanding" and `session/prompt` returned
* while the agent was still running (live 2026-12-01: prompt resolved at
* t+9.3s, the agent's card completed at t+15s).
*/
describe("BackgroundTaskListener subagent classification (4.0 spawn-first order)", () => {
/** Flush the async card emission. */
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));

/** The spawn event as 4.0 writes it (runner.ts:353-369). */
const spawnEvent = (taskId: string) =>
zcodeEvent("session.updated", {
taskId,
childSessionId: `sess_child_${taskId}`,
description: "alpha",
status: "running",
background: true,
});
/** The task event that follows, with the kind. */
const taskEvent = (taskId: string, status: string) =>
zcodeEvent("session.updated", {
taskId,
taskKind: "subagent",
toolName: "Agent",
description: "alpha",
status,
});

it("counts a kindless spawn as outstanding, and keeps counting it after the task event", async () => {
const server = makeServer();
const l = new BackgroundTaskListener(server as unknown as ZcodeAcpServer, "sess_test");
l.handleEvent(spawnEvent("agent_1"));
await flush();
// Spawn only: already outstanding — the Agent call has not even returned.
expect(l.subagentWorkOutstanding()).toBe(true);
expect(l.outstandingSubagentCallIds()).toHaveLength(1);
l.handleEvent(taskEvent("agent_1", "running"));
await flush();
expect(l.subagentWorkOutstanding()).toBe(true);
expect(l.outstandingSubagentCallIds()).toHaveLength(1);
// One card for the whole life — the task event never mints a second.
const cards = server.calls.filter((c) => c.update["sessionUpdate"] === "tool_call");
expect(cards).toHaveLength(1);
});

it("settles when the spawn-tracked task reaches a terminal status", async () => {
const server = makeServer();
const l = new BackgroundTaskListener(server as unknown as ZcodeAcpServer, "sess_test");
l.handleEvent(spawnEvent("agent_1"));
await flush();
l.handleEvent(taskEvent("agent_1", "completed"));
await flush();
expect(l.subagentWorkOutstanding()).toBe(false);
expect(l.outstandingSubagentCallIds()).toEqual([]);
});

it("a task-kind-first sighting still classifies (the kind wins as before)", async () => {
const server = makeServer();
const l = new BackgroundTaskListener(server as unknown as ZcodeAcpServer, "sess_test");
l.handleEvent(taskEvent("agent_1", "running"));
await flush();
expect(l.subagentWorkOutstanding()).toBe(true);
});

it("a kindless task with no child session is NOT a subagent", async () => {
const server = makeServer();
const l = new BackgroundTaskListener(server as unknown as ZcodeAcpServer, "sess_test");
// A plain background shell that carries neither field (older shape).
l.handleEvent(zcodeEvent("session.updated", { taskId: "exec_1", status: "running" }));
await flush();
expect(l.subagentWorkOutstanding()).toBe(false);
expect(l.outstandingSubagentCallIds()).toEqual([]);
});

it("a present taskKind other than subagent wins over a child session id", async () => {
const server = makeServer();
const l = new BackgroundTaskListener(server as unknown as ZcodeAcpServer, "sess_test");
// A background shell that happens to name a child session: the explicit
// kind rules, the child id is only the fallback for a KINDLESS task.
l.handleEvent(
zcodeEvent("session.updated", {
taskId: "exec_1",
taskKind: "bash",
childSessionId: "sess_child_x",
status: "running",
}),
);
await flush();
expect(l.subagentWorkOutstanding()).toBe(false);
});

it("the safety net flips a spawn-tracked task too", async () => {
const server = makeServer();
const l = new BackgroundTaskListener(server as unknown as ZcodeAcpServer, "sess_test");
l.handleEvent(spawnEvent("agent_1"));
await flush();
expect(l.markOutstandingSubagentsTerminal()).toBe(1);
expect(l.subagentWorkOutstanding()).toBe(false);
});

it("a task first seen without any kind becomes a subagent once a later sighting names it", async () => {
const server = makeServer();
const l = new BackgroundTaskListener(server as unknown as ZcodeAcpServer, "sess_test");
// Listener attached mid-run: the first sighting carries neither field
// (an older shape, or a spawn whose child id was dropped).
l.handleEvent(zcodeEvent("session.updated", { taskId: "agent_1", status: "running" }));
await flush();
expect(l.subagentWorkOutstanding()).toBe(false);
// The next event names the kind → the SAME tracked task is re-classified,
// and the outstanding verdict follows.
l.handleEvent(taskEvent("agent_1", "running"));
await flush();
expect(l.subagentWorkOutstanding()).toBe(true);
expect(l.outstandingSubagentCallIds()).toHaveLength(1);
});
});
Loading