Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(agents): Claude subagent labels never shift to the next child

reviewb2084d5a020f
diff --git a/CLAUDE.md b/CLAUDE.md
index dd2754c62..9a99078ad 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3050,13 +3050,20 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
child is drawn from its tool call and then REPLACED by its native card (`supersedes` — the
renderer store, the host replay and the notch HUD move the card; nothing can know at the tool
call that a native start is coming). Native cards are keyed by `agent_id`, so start/stop/resume
- follow the CLI exactly; only the label is paired, first-in-first-out by type and corrected
- exactly by the ack (also when the ack overtakes its start). A native stop for an id that never
- started is dropped (side-agents); a later start of a known id re-opens its card; the parent
- `Stop` inventory ends a native card it no longer lists (the killed child) and any tool card
- whose child never started; tool-path ends are re-keyed onto the native card (idempotent, and
- they bring the sync stats the native stop lacks — a late stats-bearing `finish()` fills them on
- a done card). Tails: the native start begins the child's tail in the RAW listener, which must run
+ follow the CLI exactly; only the label is paired, first-in-first-out by type, corrected exactly
+ by the ack (also when the ack overtakes its start — and a call an ack already named is never
+ handed to another child), and for a SYNC child by its end (`tool_response.agentId`), which
+ takes its call out of the queue and relabels a still-running sibling that guessed it. Every
+ turn-end `Stop`/`StopFailure` (never the `idle` rescue — an Agent call may be waiting on a
+ permission prompt) clears the queue of calls whose child never started, with or WITHOUT an
+ inventory: 2.0.43 had native hooks long before `background_tasks`, and a denied call's label
+ must not go to the next child. A native stop for an id that never started is dropped
+ (side-agents); a later start of a known id re-opens its card; the parent `Stop` inventory, when
+ present, ends a native card it no longer lists (the killed child); a tool card whose child
+ never started is ended at the turn end; a replaced tool card also gets a plain end AFTER the
+ replacing start (for a consumer too old for `supersedes`); tool-path ends are re-keyed onto the
+ native card (idempotent, and they bring the sync stats the native stop lacks — a late
+ stats-bearing `finish()` fills them on a done card). Tails: the native start begins the child's tail in the RAW listener, which must run
BEFORE the `ignoreQuestionHook` child-event gate (it ignores every `agent_id`-tagged payload);
the lifecycle's `onRelease` ends it (local + remote); a resumed child continues from its
remembered offset (`subagent-tail` / `remote-subagent-tail`) instead of re-streaming; a remote
@@ -3066,9 +3073,9 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
rule than before (it also covers a background shell a subagent launched). Both shells pinned by
`hook-verified-parity.test.ts`; the Server Edition also behaviorally over the fixture
(`server/agent-status.test.ts`). Cost: one extra managed-hook process + POST per interactive turn
- (the side-agent stop). Residuals, stated: a SYNC child has no ack until it ends, so two same-type
- sync children launched in one reordered burst could swap LABELS (never lifecycle); a killed
- child with no later parent `Stop` still waits for the decay. **Device checklist** (not runnable
+ (the side-agent stop). Residuals, stated: a SYNC child has no ack, so while it runs a reordered
+ same-type burst can show a sibling's LABEL (never lifecycle) until the first of them ends; a
+ killed child with no later parent `Stop` inventory still waits for the decay. **Device checklist** (not runnable
here): (a) macOS + Windows canvas, interactive: cards at start, right labels, live activity,
done at stop, nested card, resumed card re-opens; (b) SSH node: native tail over the
ControlMaster at the derived path; (c) a session started BEFORE the upgrade (old hook snapshot —
@@ -3076,7 +3083,10 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
with a background subagent paused on its own background shell: not hibernated, bulk restart
skips it; (e) a managed-account node gets native cards (installer writes the account dir); (f)
Windows: the derived path keeps the reported separator; (g) a pre-2.0.43 CLI tolerates the two
- new keys in settings.json (same class as `StopFailure`, which already shipped).
+ new keys in settings.json (same class as `StopFailure`, which already shipped); (h) the
+ hand-back turn (a background child reporting back wakes the parent for a turn, then the
+ `<task-notification>` wakes it again) may chime "finished" twice — #708's quiet rule is per
+ turn.
**Codex** (2026-08-24, `spawn_agent` collaboration — issue #401) joined via its **native
`SubagentStart`/`SubagentStop` hooks**, measured on codex-cli 0.146.0, keyed by `agent_id` (NOT
`tool_use_id` — nothing correlates the spawn tool call with the Start it launches; agent_id is
diff --git a/src/core/claude-subagent-lifecycle.test.ts b/src/core/claude-subagent-lifecycle.test.ts
index b4060e4f5..8ef127d51 100644
--- a/src/core/claude-subagent-lifecycle.test.ts
+++ b/src/core/claude-subagent-lifecycle.test.ts
@@ -176,7 +176,7 @@ describe('ClaudeSubagentLifecycle over captured sessions', () => {
const ev = events('print_sync')
const { stream } = run(ev)
const [id] = startedIds(ev)
- const toolEnd = stream.find((e) => e.kind === 'subagent-end' && e.subagentSignal === 'tool')!
+ const toolEnd = stream.find((e) => e.kind === 'subagent-end' && e.subagentSignal === 'tool' && e.toolUseId === id)!
expect(toolEnd).toMatchObject({ toolUseId: id, tokens: expect.any(Number), toolUses: 1 })
})
@@ -328,6 +328,75 @@ describe('ClaudeSubagentLifecycle — the rules, one at a time', () => {
expect(lc.apply(stop())).toHaveLength(1)
})
+ // Review of #1032, probe (a): a CLI with native hooks but no Stop inventory (2.0.43 up to the
+ // release that added `background_tasks`). "Every tool call of the turn has resolved by its Stop"
+ // does not depend on the inventory, so the waiting labels must be cleared by ANY turn-end Stop.
+ it('a denied tool call does not lend its label to a later child, even with no Stop inventory', () => {
+ const lc = new ClaudeSubagentLifecycle()
+ lc.apply(toolStart('t0'))
+ lc.apply(nativeStart('a0')) // latched
+ lc.apply(nativeEnd('a0'))
+ lc.apply(toolStart('t1')) // denied: its child never starts
+ lc.apply(stop()) // older CLI: no inventory
+ const labels: Record<string, string | undefined> = {}
+ for (const [t, a] of [['t2', 'a2'], ['t3', 'a3']]) {
+ lc.apply(toolStart(t))
+ const [start] = lc.apply(nativeStart(a))
+ labels[a] = start.taskLabel
+ lc.apply(nativeEnd(a))
+ }
+ expect(labels).toEqual({ a2: 'task t2', a3: 'task t3' })
+ })
+
+ it('the idle-prompt rescue is not a turn end: a tool call waiting for approval keeps its label', () => {
+ const lc = new ClaudeSubagentLifecycle()
+ lc.apply(nativeStart('a0'))
+ lc.apply(toolStart('t1')) // Agent call held on a permission prompt; the CLI sits idle
+ lc.apply({ ...stop(), interrupted: true, idle: true })
+ expect(lc.apply(nativeStart('a1'))[0].taskLabel).toBe('task t1')
+ })
+
+ // Probe (b): a SubagentStart POST that overtakes its own PreToolUse, for SYNC children (no ack).
+ it("a sync end names its child exactly: the child's tool call leaves the queue and a mislabelled sibling is corrected", () => {
+ const lc = new ClaudeSubagentLifecycle()
+ lc.apply(nativeStart('a0')) // latched
+ lc.apply(nativeEnd('a0'))
+ expect(lc.apply(nativeStart('a1'))[0].taskLabel).toBeUndefined() // overtook t1
+ lc.apply(toolStart('t1'))
+ lc.apply(toolStart('t2'))
+ expect(lc.apply(nativeStart('a2'))[0].taskLabel).toBe('task t1') // the FIFO guess, wrong
+ lc.apply(nativeEnd('a1'))
+ const out = lc.apply({ ...base, kind: 'subagent-end', toolUseId: 't1', subagentAgentId: 'a1', subagentSignal: 'tool', tokens: 5 })
+ expect(out[0]).toMatchObject({ kind: 'subagent-end', toolUseId: 'a1', tokens: 5 })
+ // a2 is still running: it gets its own label back at once, not at the next Stop.
+ expect(out.slice(1)).toEqual([expect.objectContaining({ kind: 'subagent-start', toolUseId: 'a2', taskLabel: 'task t2' })])
+ // …and nothing of this turn is left to mislabel the next child.
+ lc.apply(nativeEnd('a2'))
+ lc.apply({ ...base, kind: 'subagent-end', toolUseId: 't2', subagentAgentId: 'a2', subagentSignal: 'tool' })
+ lc.apply(toolStart('t3'))
+ expect(lc.apply(nativeStart('a3'))[0].taskLabel).toBe('task t3')
+ })
+
+ it('a waiting tool call an ack already reserved for another child is not handed out by FIFO', () => {
+ const lc = new ClaudeSubagentLifecycle()
+ lc.apply(nativeStart('a0'))
+ lc.apply(toolStart('t1'))
+ lc.apply(toolStart('t2'))
+ lc.apply({ ...base, kind: 'state', state: 'working', subagentLaunch: { toolUseId: 't1', agentId: 'a1' } })
+ expect(lc.apply(nativeStart('a2'))[0].taskLabel).toBe('task t2')
+ expect(lc.apply(nativeStart('a1'))[0].taskLabel).toBe('task t1')
+ })
+
+ it('a superseded tool card is also ENDED, after the start that replaces it (an older consumer ignores supersedes)', () => {
+ const lc = new ClaudeSubagentLifecycle()
+ lc.apply(toolStart('t1'))
+ const out = lc.apply(nativeStart('a1'))
+ expect(out.map((e) => [e.kind, e.toolUseId, e.supersedes])).toEqual([
+ ['subagent-start', 'a1', 't1'],
+ ['subagent-end', 't1', undefined]
+ ])
+ })
+
it('stays bounded however many tool calls never start', () => {
const lc = new ClaudeSubagentLifecycle()
lc.apply(nativeStart('a0'))
diff --git a/src/core/claude-subagent-lifecycle.ts b/src/core/claude-subagent-lifecycle.ts
index bcdac19cf..6c481c55d 100644
--- a/src/core/claude-subagent-lifecycle.ts
+++ b/src/core/claude-subagent-lifecycle.ts
@@ -31,19 +31,27 @@
// issues every `PreToolUse` first and then starts the children within 5 ms of each other, and a
// backgrounded hook POST can overtake another. The async launch ack names the exact pair
// (`tool_response.agentId`, measured ~1 ms after each start), so a wrong guess is corrected
-// before anything else happens, and an ack that overtakes its own start is remembered. A SYNC
-// child has no ack until it ends; its FIFO label then stands (see CLAUDE.md for why that pairing
-// is right in practice).
+// before anything else happens, and an ack that overtakes its own start is remembered (and the
+// call it names is not handed to another child meanwhile). A SYNC child has no ack; its end
+// names it exactly (`tool_response.agentId`), which takes its call out of the queue and gives a
+// still-running sibling that guessed it its own label back.
// - A native stop ends a card; a later native start of the SAME id re-opens it. Measured: a
// background agent that ends its turn while its own child still runs fires `SubagentStop`, and
// is resumed under the same `agent_id` when the child reports back.
// - A native stop for an id that never started is DROPPED: Claude fires stops for its internal
// side-agents (prompt suggestions, measured after nearly every interactive turn) with an empty
// `agent_type` and no start.
+// - Every turn end (`Stop`, `StopFailure` — never the idle-prompt rescue, which can fire while an
+// Agent call waits on a permission prompt) clears the queue of calls whose child never started:
+// every call of the turn has resolved by then, inventory or not, and a left-over label would go
+// to the next child for the rest of the session.
// - A killed child fires NO stop (measured, SDK interrupt). The parent's next `Stop` carries the
-// session's live background-task inventory, and a native card still working that it no longer
-// lists is over. Foreground children are never in that list, and none can be running when the
-// parent's turn ends; nested children of a background agent are listed (measured).
+// session's live background-task inventory (when the CLI is new enough to send one), and a
+// native card still working that it no longer lists is over. Foreground children are never in
+// that list, and none can be running when the parent's turn ends; nested children of a
+// background agent are listed (measured).
+// - A replaced tool card also gets a plain end, AFTER the replacing start, for a consumer too old
+// to know `supersedes`.
// - Tool-path ends (the sync `PostToolUse`, the `<task-notification>` sniff) still arrive in a
// native session; they are re-keyed onto the native card, which makes them idempotent — and they
// carry the sync stats (tokens, tool uses) the native stop lacks.
@@ -111,7 +119,9 @@ export class ClaudeSubagentLifecycle {
}
if (ev.kind === 'state') {
if (ev.subagentLaunch) return this.ack(ev, ev.subagentLaunch)
- if (ev.state === 'done' && ev.backgroundTaskIds) return this.reconcile(ev, ev.backgroundTaskIds)
+ // A turn end (Stop / StopFailure) — never the idle-prompt rescue, which can fire while an
+ // Agent call is still held on a permission prompt.
+ if (ev.state === 'done' && !ev.idle) return this.turnEnd(ev)
return [ev]
}
if (!ev.subagentSignal || !ev.toolUseId) return [ev]
@@ -184,7 +194,7 @@ export class ClaudeSubagentLifecycle {
const hinted = st.ackHints.get(agentId)
st.ackHints.delete(agentId)
const superseded = hinted ? this.bind(st, card, hinted, ev, out) : this.bindNext(st, card)
- out.unshift(this.startEvent(ev, card, superseded))
+ out.unshift(this.startEvent(ev, card, superseded), ...this.supersededEnd(ev, superseded, card.type))
return out
}
@@ -200,7 +210,12 @@ export class ClaudeSubagentLifecycle {
if (card.toolUseId === launch.toolUseId) return [ev]
const out: NormalizedAgentEvent[] = [ev]
const superseded = this.bind(st, card, launch.toolUseId, ev, out)
- if (card.working) out.splice(1, 0, this.startEvent(ev, card, superseded))
+ out.splice(
+ 1,
+ 0,
+ ...(card.working ? [this.startEvent(ev, card, superseded)] : []),
+ ...this.supersededEnd(ev, superseded, card.type)
+ )
return out
}
@@ -221,9 +236,18 @@ export class ClaudeSubagentLifecycle {
const exact = ev.subagentAgentId ? st.cards.get(ev.subagentAgentId) : undefined
const card = exact ?? [...st.cards.values()].find((c) => c.toolUseId === toolUseId)
if (card) {
+ const fixes: NormalizedAgentEvent[] = []
+ // The sync end names its child exactly (tool_response.agentId). If the pairing guessed
+ // otherwise — a SubagentStart POST that overtook its own PreToolUse, where no ack follows to
+ // correct it — settle it now: this call leaves the queue (it would label the NEXT child), and
+ // a still-running sibling that took it gets its own label back.
+ if (exact && card.toolUseId !== toolUseId) {
+ const superseded = this.bind(st, card, toolUseId, ev, fixes)
+ fixes.push(...this.supersededEnd(ev, superseded, card.type))
+ }
if (card.working) this.onRelease(card.agentId)
card.working = false
- return [{ ...ev, toolUseId: card.agentId }]
+ return [{ ...ev, toolUseId: card.agentId }, ...fixes]
}
const i = st.pending.findIndex((p) => p.toolUseId === toolUseId)
if (i >= 0) {
@@ -234,19 +258,24 @@ export class ClaudeSubagentLifecycle {
return [ev]
}
- private reconcile(ev: NormalizedAgentEvent, live: string[]): NormalizedAgentEvent[] {
+ private turnEnd(ev: NormalizedAgentEvent): NormalizedAgentEvent[] {
const st = this.nodes.get(ev.nodeId)
if (!st?.native || (ev.sessionId && st.sessionId !== ev.sessionId)) return [ev]
- const alive = new Set(live)
const out: NormalizedAgentEvent[] = [ev]
- for (const card of st.cards.values()) {
- if (!card.working || alive.has(card.agentId)) continue
- card.working = false
- this.onRelease(card.agentId)
- out.push(this.endEvent(ev, card.agentId, card.type))
+ // The inventory, when the CLI sends one, ends the native cards it no longer lists.
+ if (ev.backgroundTaskIds) {
+ const alive = new Set(ev.backgroundTaskIds)
+ for (const card of st.cards.values()) {
+ if (!card.working || alive.has(card.agentId)) continue
+ card.working = false
+ this.onRelease(card.agentId)
+ out.push(this.endEvent(ev, card.agentId, card.type))
+ }
}
- // Every tool call of the turn has resolved by its Stop, so a child that has not started by now
- // never will. A card drawn for one (only possible before the latch) is ended.
+ // Every tool call of the turn has resolved by its Stop — with or without an inventory (native
+ // hooks shipped in 2.0.43, the inventory much later) — so a child that has not started by now
+ // never will, and its waiting label must not go to the next child. A card drawn for one (only
+ // possible before the latch) is ended.
for (const p of st.pending) {
if (!p.shown) continue
this.onRelease(p.toolUseId)
@@ -261,10 +290,13 @@ export class ClaudeSubagentLifecycle {
/** First in, first out: the oldest waiting tool call of the same type, else one with no type
* on either side. Returns the id of a drawn tool card the new card replaces. */
private bindNext(st: NodeState, card: Card): string | undefined {
+ // A call an ack already named for another child that has not started yet is not up for grabs.
+ const reserved = new Set(st.ackHints.values())
+ const free = (p: Pending): boolean => !reserved.has(p.toolUseId)
const i = (() => {
- const same = st.pending.findIndex((p) => p.type !== undefined && p.type === card.type)
+ const same = st.pending.findIndex((p) => free(p) && p.type !== undefined && p.type === card.type)
if (same >= 0) return same
- return st.pending.findIndex((p) => p.type === undefined || card.type === undefined)
+ return st.pending.findIndex((p) => free(p) && (p.type === undefined || card.type === undefined))
})()
if (i < 0) return undefined
const [p] = st.pending.splice(i, 1)
@@ -306,6 +338,7 @@ export class ClaudeSubagentLifecycle {
if (owner) {
const ownerSuperseded = this.bindNext(st, owner)
if (owner.working) out.push(this.startEvent(ev, owner, ownerSuperseded))
+ out.push(...this.supersededEnd(ev, ownerSuperseded, owner.type))
}
return superseded
}
@@ -349,6 +382,17 @@ export class ClaudeSubagentLifecycle {
}
}
+ /**
+ * A plain end for a tool card a native card just replaced, AFTER the replacing start. A consumer
+ * that knows `supersedes` has already moved the card, so this is a no-op there; one that does not
+ * (an older relay guest's renderer) would otherwise keep the tool card working until the stale
+ * decay. Never before the start: with auto-hide on, an end first would drop the card the start
+ * is about to move.
+ */
+ private supersededEnd(ev: NormalizedAgentEvent, key: string | undefined, type: string | undefined): NormalizedAgentEvent[] {
+ return key ? [{ ...this.endEvent(ev, key, type), subagentSignal: 'tool' }] : []
+ }
+
private endEvent(ev: NormalizedAgentEvent, key: string, type: string | undefined): NormalizedAgentEvent {
return {
nodeId: ev.nodeId,