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(control): review of #1052 — only background subagents hold, and five hold/release edges

reviewbac9befc77af
diff --git a/CLAUDE.md b/CLAUDE.md
index b64dcbd2a..b923234ed 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3827,20 +3827,30 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
- **The fact is core's, per station, fed by the SAME hand-over moments #1042 uses**: the
messaging layer's `onHandover` (`queued` = held from that instant; `landed` at the time the
delivery attempt STARTED; a queued entry that `settled` without landing holds too, from the
- settle — the orchestrator armed D believing the task was handed), and each shell's control
- answer for `write` / `run` (`noteControlAnswer`, on success only, never the caller naming itself,
- stamped with the time the REQUEST ARRIVED — before any byte was typed). Board comments, station
- notices and a person typing are not hand-overs (the #1042 set).
+ settle — the orchestrator armed D believing the task was handed; the turn running at the expiry
+ does not end it, only a turn started after it does, and nothing starts one unless the station is
+ given work again, so ▶ / `run` are the usual way out), and each shell's control answer
+ (`noteControlAnswer`, on success only, never the caller naming itself) for `write` — stamped with
+ the renderer's `typedAt`, when it STARTED TYPING after the human's confirm, never the request
+ time: a turn that began while the dialog was open (a background child's task-notification) must
+ not answer text not yet typed — and for `run` (starts the named node's held launch; no confirm,
+ stamped at request arrival). A `write` into a station that was BLOCKED or WAITING at request time
+ (read from the tracker's short state history) is NOT a hand-over: it answers the prompt and the
+ same turn continues, so no new turn would ever start to end it. Board comments, station notices
+ and a person typing are not hand-overs (the #1042 set).
- **It ends with a turn that STARTED at or after the newest hand-over and has ENDED, with nothing
still queued.** The tracker stamps turn starts itself (first working/waiting/blocked after an
- idle state, on its own clock) for EVERY station, because a delivered prompt can start — and
+ idle state, or any genuine `newTurn` — after an Esc interrupt core may never see the idle the
+ renderer infers — on its own clock) for EVERY station, because a delivered prompt can start — and
even finish — its turn before the delivery's `landed` event is emitted; a hand-over that finds
its answering turn already over clears at once. Timestamps never cross a process: the renderer
only reads a membership list, so the Server Edition browser's clock never enters it. A turn
already running when the work landed does not end it (the typed text is answered by a LATER
turn); if a CLI folds typed input into the running turn instead, the hold lasts until its next
- turn — the holding direction, with ▶ / `run` as the way out. An idle-prompt `done` with no turn
- in between ends nothing.
+ turn — the holding direction, with ▶ / `run` as the way out. The idle-prompt rescue (`idle: true`)
+ counts only for a station still `working` (the reduceEntry rule): it also fires under an open
+ permission prompt, and taking it as idle there let the approval's `working` stamp a fake turn
+ start inside the same turn (review of #1052, reproduced).
- **The tracker is fed every agent event BEFORE the messaging queue** (desktop `emitAgentStatus`,
the Server Edition's `onAgentEvent`): the queue flushes new work on the very `done` the tracker
must stamp, and the server's `refreshArmed` reads the tracker on that same event. Pinned at
@@ -3852,23 +3862,29 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`--after` would hold. The Server Edition's factory asks `handedOver` in `refreshArmed` AND in the
creation shortcut (`mustWait`): "already satisfied at creation" must mean satisfied under this
rule, or the node is launched immediately by the shortcut.
- - **Background tasks hold the same way** (same module, same list; `background: true` on the
- record). MEASURED live 2026-09-30: an agent's turn ended while its full test suite still ran in
- a background shell, and the node armed `--after` it fired before anything was pushed — the same
- bug class, from background work instead of a hand-over. Claude's `Stop` carries
- `background_tasks` (see **Claude's native subagent hooks**, fact 6), normalized to
- `backgroundTaskIds`. A `done` whose inventory lists a live task holds the station; only a later
- `done` whose inventory is PRESENT and EMPTY releases it, or `SessionEnd` (the CLI took its tasks
- with it and will never report them). An ABSENT inventory is unknown and changes NOTHING: a CLI
- too old to send the field keeps today's behaviour exactly (it never sets the hold — holding on
- "unknown" would strand every such station forever), and a `done` without one (the idle-prompt
- rescue, `StopFailure`, other agents) neither sets nor clears it. A turn STARTING does not clear
- it (the task may outlive that turn). A task that finishes without waking the station for another
- turn leaves the hold until the station's next turn end — holding, with ▶ / `run` as the way out.
- The agent bodies tell a station not to end its turn with background work a dependent needs.
- - **Eviction never drops a held station** (the bound is 2000 tracked stations; the oldest with
- nothing handed over goes first) — dropping one would release its dependents.
- - Surfaces: `list` says `waiting for <station> to finish the work handed to it`; the QUEUED tooltip
+ - **Background SUBAGENTS hold the same way; background SHELLS do not** (same module, same list;
+ `background: true` on the record). MEASURED live 2026-09-30: an agent's turn ended while its
+ work went on in the background, and the node armed `--after` it fired before anything was
+ pushed. Claude's `Stop` carries `background_tasks` (see **Claude's native subagent hooks**, fact
+ 6); `liveBackgroundSubagentIds` keeps only `type: 'subagent'` entries
+ (`NormalizedAgentEvent.backgroundSubagentIds`). A `done` listing a live subagent holds the
+ station; only a later `done` whose inventory is PRESENT with no subagent left releases it, or
+ `SessionEnd`. Why only subagents: a child ENDS, and its task-notification wakes the parent into
+ another turn, so that later `Stop` reliably comes; a background shell (a dev server, a watcher,
+ `tail -f`) may never end and does not reliably wake the station — holding on shells held a
+ dependent FOREVER ("S starts the dev server, T `--after` S runs e2e" never fired; review of
+ #1052). Unknown `type`s are treated like shells. An ABSENT inventory is unknown and changes
+ NOTHING (a CLI too old to send it keeps today's behaviour exactly; the idle rescue and
+ `StopFailure` carry none). The agent bodies tell a station to wait for a background shell's
+ result itself before ending its turn when a dependent needs it.
+ - **Eviction prefers stations with nothing held** (the bound is 2000 tracked stations; the oldest
+ with nothing held goes first) — dropping a held one would release its dependents. Only when
+ every tracked station holds is the oldest held one dropped.
+ - **The Server Edition re-runs `refreshArmed` on every tracker change**, not only on
+ working/done events: a hold can end on an event the factory is not otherwise run for (a
+ `SessionEnd` clearing a subagent hold).
+ - Surfaces: `list` says `waiting for <station> to finish the work handed to it` (or `…the tasks
+ still running in its background`); the QUEUED tooltip
names it; both agent bodies render `afterHandoverDocLines` ("hand it the next task FIRST, then
open the dependent"). TRANSIENT: after a restart nothing has been handed over in this run.
Relay tabs take the inert stub; the list channel is HOST_ONLY
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index d098227b6..abb02b68b 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -263,20 +263,25 @@ function afterHandoverDocLines(): string[] {
return [
'Reusing a station with `--after` (new work resets the wait):',
'- A station handed new work through canvas control — a `send` / `reply` aimed at it (queued or',
- ' delivered), or a `write` / `run` into it — does not count as finished for `--after` until a turn',
- ' that STARTED after that work arrived has ended. Its earlier `done` (the previous task) releases',
- ' nothing, and while a `send` / `reply` is still QUEUED for it nothing releases at all. A queued',
- ' message that expires unread still holds: the next turn the station finishes ends it.',
+ ' delivered), a `write` into it, or a `run` starting its held launch — does not count as finished',
+ ' for `--after` until a turn that STARTED after that work arrived has ended. Its earlier `done` (the',
+ ' previous task) releases nothing, and while a `send` / `reply` is still QUEUED for it nothing',
+ ' releases at all. A `write` that only answers the station\'s open prompt (a permission or a',
+ ' question) is not new work. A queued message that EXPIRES unread still holds, and the turn the',
+ ' station was on when it expired does not end that: only a turn started AFTER the expiry does, and',
+ ' nothing starts one unless the station is given work again — send the task again, or start the',
+ ' dependent yourself with `run`.',
'- So to reuse a station, hand it the next task FIRST, then open the dependent `--after` it — opened',
' first, the dependent would start at once on the previous task\'s output. `list` marks such a',
' dependent "waiting for <station> to finish the work handed to it". A person typing in the',
" station's pane is not a hand-over. `run` (or the user's ▶) always starts a held node anyway.",
- '- A turn that ENDS with background tasks still running (a background shell, an async subagent —',
- ' Claude reports them when its turn ends) has not finished either: `--after` on that station waits',
- ' for a later turn end that reports none (`list`: "waiting for <station> to finish the tasks still',
- ' running in its background"). If YOU are the station, do not end your turn with background work',
- ' whose result a dependent needs; wait for it, then finish. Agents that do not report background',
- ' tasks release on their turn end as before.'
+ '- A turn that ENDS with a background SUBAGENT still running (Claude reports them when its turn',
+ ' ends) has not finished either: `--after` on that station waits for a later turn end that reports',
+ ' none left — the subagent\'s result wakes the station for that turn (`list`: "waiting for',
+ ' <station> to finish the tasks still running in its background"). A background SHELL (a dev',
+ ' server, a watcher, a long test run) does NOT hold: it may never end. So if YOU are the station and',
+ ' a dependent needs a background shell\'s result, wait for it before you end your turn. Agents that',
+ ' do not report background tasks release on their turn end as before.'
]
}
diff --git a/src/core/station-handover.test.ts b/src/core/station-handover.test.ts
index f3e4ba934..86621497d 100644
--- a/src/core/station-handover.test.ts
+++ b/src/core/station-handover.test.ts
@@ -136,17 +136,17 @@ describe('StationHandoverTracker — when a station counts as finished for plain
expect(h.t.list().map((r) => r.nodeId)).toEqual(['st'])
})
- describe('background tasks left running at a turn end (Claude `Stop.background_tasks`)', () => {
- const stop = (t: StationHandoverTracker, ids?: string[]) =>
- t.onAgentEvent({ nodeId: 'st', state: 'done', ...(ids ? { backgroundTaskIds: ids } : {}) })
+ describe('background SUBAGENTS left running at a turn end (Claude `Stop.background_tasks`)', () => {
+ const stop = (t: StationHandoverTracker, subagents?: string[]) =>
+ t.onAgentEvent({ nodeId: 'st', state: 'done', ...(subagents ? { backgroundSubagentIds: subagents } : {}) })
- it('a done that still lists a running task holds; a later done with an EMPTY inventory releases', () => {
+ it('a done that still lists a running subagent holds; a later done with none releases', () => {
const h = tracker()
h.ev('working', 100)
- stop(h.t, ['bash_1'])
+ stop(h.t, ['agent_1'])
expect(h.t.isHandedOver('st')).toBe(true)
expect(h.t.list()).toEqual([{ nodeId: 'st', background: true }])
- // A turn starting does not end it: the task may outlive that turn.
+ // The child's task-notification wakes the parent: a turn starting does not end the hold.
h.ev('working', 200)
expect(h.t.isHandedOver('st')).toBe(true)
stop(h.t, [])
@@ -159,14 +159,14 @@ describe('StationHandoverTracker — when a station counts as finished for plain
stop(h.t) // a CLI too old to send the field: today's behaviour
expect(h.t.isHandedOver('st')).toBe(false)
stop(h.t, ['agent_1'])
- h.ev('done', 300) // the idle-prompt rescue / StopFailure carry no inventory
+ h.t.onAgentEvent({ nodeId: 'st', state: 'done', errored: true } as never) // StopFailure: no inventory
expect(h.t.isHandedOver('st')).toBe(true)
})
- it('SessionEnd ends it: the CLI took its tasks with it and will never report them', () => {
+ it('SessionEnd ends it: the CLI took its subagents with it and will never report them', () => {
const h = tracker()
h.ev('working', 100)
- stop(h.t, ['bash_1'])
+ stop(h.t, ['agent_1'])
h.t.onAgentEvent({ nodeId: 'st', state: undefined, sessionPhase: 'end' })
expect(h.t.isHandedOver('st')).toBe(false)
})
@@ -174,10 +174,11 @@ describe('StationHandoverTracker — when a station counts as finished for plain
it('background work and a hand-over hold independently', () => {
const h = tracker()
h.ev('working', 100)
- stop(h.t, ['bash_1'])
- h.t.noteControlAnswer('write', { node: 'st' }, { ok: true }, 'orch', h.at(150))
+ stop(h.t, ['agent_1'])
+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true, result: { typedAt: 150 } }, 'orch', 140)
+ h.at(155)
h.ev('working', 160)
- stop(h.t, ['bash_1']) // the new work's turn ended, the background task still runs
+ stop(h.t, ['agent_1']) // the new work's turn ended, the subagent still runs
expect(h.t.list()).toEqual([{ nodeId: 'st', background: true }])
h.ev('working', 200)
stop(h.t, [])
@@ -185,6 +186,93 @@ describe('StationHandoverTracker — when a station counts as finished for plain
})
})
+ describe('review of #1052: prompts, interrupts, the idle rescue and the confirm dialog', () => {
+ it('a write that ANSWERS a blocked / waiting station is not a hand-over (the same turn continues)', () => {
+ for (const prompt of ['blocked', 'waiting'] as const) {
+ const h = tracker()
+ h.ev('working', 100)
+ h.ev(prompt, 110)
+ h.at(130)
+ h.t.noteControlAnswer('write', { node: 'st', text: 'y' }, { ok: true, result: { typedAt: 125 } }, 'orch', 120)
+ expect(h.t.isHandedOver('st')).toBe(false)
+ }
+ })
+
+ it('the state at REQUEST time decides, not at the answer (the prompt was answered by then)', () => {
+ const h = tracker()
+ h.ev('working', 100)
+ h.ev('blocked', 110)
+ // The confirm dialog is open; meanwhile the user answers the prompt in the pane themselves.
+ h.ev('working', 200)
+ h.at(300)
+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true, result: { typedAt: 290 } }, 'orch', 150)
+ expect(h.t.isHandedOver('st')).toBe(false)
+ })
+
+ it('a genuine new turn (newTurn) starts one even when core never saw the previous idle (Esc)', () => {
+ const h = tracker()
+ h.ev('working', 100) // interrupted with Esc: no Stop, core still reads `working`
+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true, result: { typedAt: 150 } }, 'orch', 150)
+ h.at(160)
+ h.t.onAgentEvent({ nodeId: 'st', state: 'working', newTurn: true })
+ h.ev('done', 200)
+ expect(h.t.isHandedOver('st')).toBe(false)
+ })
+
+ it('the idle-prompt rescue counts only for a WORKING station — never under a prompt', () => {
+ // The reviewer's ordering: a write lands mid-turn A → A asks permission → idle-prompt fires
+ // under the prompt → the approval → A's Stop. Task B never started, so D must still wait.
+ const h = tracker()
+ h.ev('working', 100)
+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true, result: { typedAt: 150 } }, 'orch', 150)
+ h.at(160)
+ h.ev('blocked', 170)
+ h.at(180)
+ h.t.onAgentEvent({ nodeId: 'st', state: 'done', idle: true, interrupted: true } as never)
+ h.ev('working', 190) // the approval
+ h.ev('done', 200) // A's Stop
+ expect(h.t.isHandedOver('st')).toBe(true)
+ h.ev('working', 210)
+ h.ev('done', 300)
+ expect(h.t.isHandedOver('st')).toBe(false)
+ })
+
+ it('the idle-prompt rescue still ends a WORKING station\'s turn (the Esc-during-a-tool case)', () => {
+ const h = tracker()
+ h.ev('done', 50)
+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true, result: { typedAt: 90 } }, 'orch', 90)
+ h.ev('working', 100)
+ h.at(150)
+ h.t.onAgentEvent({ nodeId: 'st', state: 'done', idle: true, interrupted: true } as never)
+ expect(h.t.isHandedOver('st')).toBe(false)
+ })
+
+ it('a turn that started while the confirm dialog was open does not answer the write', () => {
+ const h = tracker()
+ h.ev('done', 50)
+ // Request at 100; the dialog is open; a task-notification turn runs 120–180.
+ h.ev('working', 120)
+ h.ev('done', 180)
+ h.at(200)
+ // Confirmed and typed at 195; the answer arrives at 200.
+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true, result: { typedAt: 195 } }, 'orch', 100)
+ expect(h.t.isHandedOver('st')).toBe(true)
+ h.ev('working', 210)
+ h.ev('done', 300)
+ expect(h.t.isHandedOver('st')).toBe(false)
+ })
+
+ it('a write whose typedAt is missing or implausible is stamped at the answer (holding)', () => {
+ const h = tracker()
+ h.ev('done', 50)
+ h.ev('working', 120)
+ h.ev('done', 180)
+ h.at(200)
+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true, result: { typedAt: 10 } }, 'orch', 100)
+ expect(h.t.list()).toEqual([{ nodeId: 'st', since: 200 }])
+ })
+ })
+
it('ignores unsafe ids and stateless events', () => {
const h = tracker()
h.t.markHandedOver('../x', 5)
diff --git a/src/core/station-handover.ts b/src/core/station-handover.ts
index ae4062c98..f21741ba8 100644
--- a/src/core/station-handover.ts
+++ b/src/core/station-handover.ts
@@ -14,42 +14,55 @@
* is when that delivery attempt STARTED;
* - a queued message that ends WITHOUT landing (expired, refused on flush): still a hand-over,
* at the moment it settled. The orchestrator handed new work and armed a dependent believing it
- * would be done; releasing that dependent on the older task's `done` is the bug this closes. It
- * ends with the station's next completed turn (a person may paste the task by hand), or by ▶;
- * - `write` / `run` succeeding (`noteControlAnswer`), at the time the REQUEST arrived — before any
- * byte was typed, so a turn the typed text starts is always later.
+ * would be done; releasing that dependent on the older task's `done` is the bug this closes. The
+ * turn the station was on at the expiry does not end it — only a turn STARTED after it does, and
+ * nothing starts one unless the station is given work again (a resend, a person typing the task
+ * by hand). ▶ / `run` start the dependent anyway;
+ * - `write` succeeding (`noteControlAnswer`), stamped when the renderer STARTED TYPING
+ * (`typedAt` in its answer) — never at the request, which waits on a human confirm first: a turn
+ * that started while the dialog was open (a background child's task-notification) is not an
+ * answer to text not typed yet. A write into a station that was BLOCKED or WAITING when the
+ * request arrived is not a hand-over at all: it answers the prompt, and the same turn goes on;
+ * - `run` succeeding: it starts the named node's held launch, stamped when the request arrived
+ * (no confirm), before anything was typed.
*
* WHEN IT ENDS: a `done` for a turn that STARTED at or after the newest hand-over, with nothing
* still queued. "Started" is the first active state (working / waiting / blocked) after the
- * station was last idle, stamped by this module's own clock as events arrive — tracked for every
- * station, handed over or not, because a delivered prompt can start (and even finish) its turn
- * before the delivery's `landed` event is emitted. A turn already in progress when the work landed
- * does not end it: the typed text is answered by a LATER turn (if the CLI folds it into the
- * current turn instead, the hold lasts until the next turn — the holding direction, with ▶ and
- * `run` as the way out).
+ * station was last idle, or any genuine new turn (`newTurn`: after an Esc interrupt core may never
+ * see the idle the renderer infers) — stamped by this module's own clock as events arrive, for
+ * every station, handed over or not, because a delivered prompt can start (and even finish) its
+ * turn before the delivery's `landed` event is emitted. The idle-prompt rescue (`idle: true`) is a
+ * turn end only for a station still `working` (the reduceEntry rule): it also fires under an open
+ * permission prompt, and taking it as idle there would let the approval's `working` stamp a fake
+ * turn start inside the SAME turn. A turn already in progress when the work landed does not end
+ * it: the typed text is answered by a LATER turn (if the CLI folds it into the current turn
+ * instead, the hold lasts until the next turn — the holding direction, with ▶ and `run` as the way
+ * out).
*
- * BACKGROUND WORK is the second kind of unfinished work, and it holds the same way. Claude's `Stop`
- * carries `background_tasks` — every background task of the session still running at that turn end
- * (background shells, async subagents; `NormalizedAgentEvent.backgroundTaskIds`). A turn that ends
- * with such a task running has not finished the station's work: the output the dependent is armed
- * to read is still being produced (measured live, 2026-09-30: an agent's turn ended while its test
- * suite ran in a background shell, and the node armed `--after` it fired before anything was
- * pushed). So a `done` whose inventory lists a live task holds the station, and only a later
- * `done` whose inventory is PRESENT and EMPTY releases it. Three decisions:
+ * BACKGROUND SUBAGENTS are the second kind of unfinished work. Claude's `Stop` carries
+ * `background_tasks` — every background task still running at that turn end — and a turn that ends
+ * with one running has not finished what a dependent is armed to read (measured live, 2026-09-30:
+ * an agent's turn ended while its work went on in the background, and the node armed `--after` it
+ * fired before anything was pushed). Only async SUBAGENTS hold
+ * (`NormalizedAgentEvent.backgroundSubagentIds`, `type: 'subagent'`): a child ENDS, and its
+ * task-notification wakes the parent into another turn, so a later `Stop` with it gone reliably
+ * comes. A background SHELL does not hold — a dev server, a file watcher, `tail -f` may never end
+ * and do not reliably wake the station, so holding on one held the dependent forever (the review
+ * of #1052 measured three turns ending with the same dev server listed). A station whose
+ * dependent needs a shell's result is told to wait for it before ending its turn. Rules:
* - an ABSENT inventory is "unknown", never "none" — and it changes nothing: a CLI too old to send
* the field never sets the hold (today's behaviour, exactly), and a `done` without one (the
* idle-prompt rescue, a `StopFailure`, another agent) neither sets nor clears it;
- * - the hold is not cleared by a turn STARTING (the tasks may well outlive it) — only by a turn
- * end that says they are gone, or by `SessionEnd` (the CLI exited, taking its tasks with it;
- * waiting on a session that will never report again would strand the dependent);
- * - a background task that finishes WITHOUT waking the station for another turn leaves the hold
- * up until the station's next turn end. That is the holding direction, and ▶ / `run` end it.
- *
+ * - the hold is not cleared by a turn STARTING (the child may well outlive it) — only by a turn
+ * end that says no subagent is left, or by `SessionEnd` (the CLI exited, taking its children
+ * with it; waiting on a session that will never report again would strand the dependent).
+
* NOT a hand-over: a board comment (a person steering), a station notice (the app telling an
* orchestrator something), a person typing in the pane. Deliberately the same set #1042 counts.
*
- * TRANSIENT, bounded (the oldest station with nothing handed over is evicted first): after a
- * restart nothing has been handed over in this run.
+ * TRANSIENT, bounded: past STATION_HANDOVER_MAX_TRACKED the oldest station with nothing held is
+ * evicted; only when EVERY tracked station holds is the oldest held one dropped. After a restart
+ * nothing has been handed over in this run.
*/
import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'
import { IPC } from '../shared/ipc'
@@ -69,9 +82,15 @@ export const HANDOVER_CONTROL_VERBS: ReadonlySet<string> = new Set(['write', 'ru
const ACTIVE: ReadonlySet<AgentState> = new Set<AgentState>(['working', 'waiting', 'blocked'])
+/** How many recent state changes a station keeps, to answer "what was it doing when that request
+ * arrived?" across a confirm dialog. A handful covers a prompt answered and re-asked. */
+const STATE_HISTORY = 8
+
interface StationTrack {
/** The last state seen. `undefined` until the first event. */
state?: AgentState
+ /** Recent state changes, oldest first: what `stateAt` reads. */
+ history?: Array<{ state: AgentState; at: number }>
/** When the current (or last) turn started: the first active state after an idle one. */
turnStartedAt?: number
/** `send` / `reply` entries still queued for this station. */
@@ -117,6 +136,25 @@ export class StationHandoverTracker {
return cur
}
+ private setState(t: StationTrack, state: AgentState): void {
+ if (t.state !== state) {
+ const h = (t.history ??= [])
+ h.push({ state, at: this.now() })
+ if (h.length > STATE_HISTORY) h.shift()
+ }
+ t.state = state
+ }
+
+ /** The station's state at `at`, from its recent history; unknown when older than the history. */
+ private stateAt(t: StationTrack, at: number): AgentState | undefined {
+ let out: AgentState | undefined
+ for (const e of t.history ?? []) {
+ if (e.at > at) break
+ out = e.state
+ }
+ return out
+ }
+
/** Has the turn answering the hand-over already ended? */
private settle(t: StationTrack): void {
if (
@@ -142,7 +180,7 @@ export class StationHandoverTracker {
* `refreshArmed`, the messaging queue's flush on `done`). Events without a state are ignored. */
onAgentEvent(
event: Pick<NormalizedAgentEvent, 'nodeId' | 'state'> &
- Partial<Pick<NormalizedAgentEvent, 'backgroundTaskIds' | 'sessionPhase'>>
+ Partial<Pick<NormalizedAgentEvent, 'backgroundSubagentIds' | 'sessionPhase' | 'newTurn' | 'idle'>>
): void {
if (!event?.nodeId || !isSafeNodeId(event.nodeId)) return
// The CLI exited: its background tasks died with it, and it will never report them finished.
@@ -156,16 +194,23 @@ export class StationHandoverTracker {
}
const state = event.state
if (typeof state !== 'string') return
+ // The idle-prompt rescue (`idle: true`) is a turn end ONLY for a station still `working` — the
+ // reduceEntry rule. It also fires while a permission prompt is up, and taking it there as
+ // idle would let the approval's `working` stamp a turn start in the middle of the SAME turn.
+ if (event.idle === true && this.byId.get(event.nodeId)?.state !== 'working') return
const t = this.touch(event.nodeId)
if (ACTIVE.has(state)) {
- if (!t.state || !ACTIVE.has(t.state)) t.turnStartedAt = this.now()
- t.state = state
+ // A genuine new turn (`newTurn`) starts one whatever came before: after an Esc interrupt the
+ // renderer infers the idle, but core may never see one, and the next real turn must count.
+ if (!t.state || !ACTIVE.has(t.state) || event.newTurn === true) t.turnStartedAt = this.now()
+ this.setState(t, state)
return
}
- t.state = state
+ this.setState(t, state)
if (state === 'done') {
- // Only a PRESENT inventory speaks about background work; an absent one is unknown.
- if (Array.isArray(event.backgroundTaskIds)) t.background = event.backgroundTaskIds.length > 0
+ // Only a PRESENT inventory speaks about background work; an absent one is unknown. Only
+ // background SUBAGENTS hold (see liveBackgroundSubagentIds and the header).
+ if (Array.isArray(event.backgroundSubagentIds)) t.background = event.backgroundSubagentIds.length > 0
this.settle(t)
this.changed()
}
@@ -203,19 +248,42 @@ export class StationHandoverTracker {
/**
* One finished `write` / `run`. Run by each shell's control handler on the answer (prompt or
- * late), and only on success: a refused write handed nothing. `requestAt` is when the request
- * ARRIVED, before any byte was typed. A caller naming itself is not handed work by anyone.
+ * late), and only on success: a refused write handed nothing. A caller naming itself is not
+ * handed work by anyone.
+ *
+ * WHEN the work landed:
+ * - `run` (no confirm): `requestAt`, when the request ARRIVED — before its held launch was typed.
+ * - `write`: when the renderer STARTED TYPING (`result.result.typedAt`), not the request time. A
+ * write waits on a human confirm first, and a turn that started while the dialog was open (a
+ * background child's task-notification, say) is not an answer to text not yet typed. A
+ * `typedAt` outside [requestAt, now] is not believed, and the answer time stands in: later
+ * errs toward holding.
+ * A station that was BLOCKED or WAITING when the request arrived is not handed work: the text
+ * answers its prompt, and the same turn simply continues (no new turn will ever start for it).
*/
noteControlAnswer(
verb: string,
args: Record<string, string | undefined>,
- result: { ok: boolean },
+ result: { ok: boolean; result?: unknown },
callerNodeId: string,
requestAt: number
): void {
if (!result.ok || !HANDOVER_CONTROL_VERBS.has(verb) || typeof args.node !== 'string') return
+ const now = this.now()
+ let at = requestAt
+ if (verb === 'write') {
+ const typedAt = (result.result as { typedAt?: unknown } | undefined)?.typedAt
+ at =
+ typeof typedAt === 'number' && typedAt >= requestAt && typedAt <= now
+ ? typedAt
+ : Math.max(requestAt, now)
+ }
for (const id of args.node.split(',').map((s) => s.trim())) {
- if (id && id !== callerNodeId && isSafeNodeId(id)) this.markHandedOver(id, requestAt)
+ if (!id || id === callerNodeId || !isSafeNodeId(id)) continue
+ const t = this.byId.get(id)
+ const was = t ? this.stateAt(t, requestAt) : undefined
+ if (was === 'blocked' || was === 'waiting') continue
+ this.markHandedOver(id, at)
}
}
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 97c6a8319..8fef6ed38 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -1524,16 +1524,19 @@ describe('--after-success + report-outcome: a dependent that waits for a reporte
const flat = body.replace(/\s+/g, ' ')
expect(flat).toContain('Reusing a station with `--after` (new work resets the wait)')
expect(flat).toContain(
- 'a `send` / `reply` aimed at it (queued or delivered), or a `write` / `run` into it — does not count as finished for `--after` until a turn that STARTED after that work arrived has ended'
+ 'a `send` / `reply` aimed at it (queued or delivered), a `write` into it, or a `run` starting its held launch — does not count as finished for `--after` until a turn that STARTED after that work arrived has ended'
)
expect(flat).toContain("Its earlier `done` (the previous task) releases nothing")
expect(flat).toContain('while a `send` / `reply` is still QUEUED for it nothing releases at all')
- expect(flat).toContain('A queued message that expires unread still holds')
+ expect(flat).toContain('A queued message that EXPIRES unread still holds')
+ expect(flat).toContain('only a turn started AFTER the expiry does')
+ expect(flat).toContain("A `write` that only answers the station's open prompt")
expect(flat).toContain('hand it the next task FIRST, then open the dependent `--after` it')
expect(flat).toContain('"waiting for <station> to finish the work handed to it"')
expect(flat).toContain("A person typing in the station's pane is not a hand-over")
- expect(flat).toContain('A turn that ENDS with background tasks still running')
- expect(flat).toContain('waits for a later turn end that reports none')
+ expect(flat).toContain('A turn that ENDS with a background SUBAGENT still running')
+ expect(flat).toContain('waits for a later turn end that reports none left')
+ expect(flat).toContain('A background SHELL (a dev server, a watcher, a long test run) does NOT hold')
expect(flat).toContain('"waiting for <station> to finish the tasks still running in its background"')
})
diff --git a/src/main/station-handover-wiring.test.ts b/src/main/station-handover-wiring.test.ts
index 7c2fc1083..7931f8b4a 100644
--- a/src/main/station-handover-wiring.test.ts
+++ b/src/main/station-handover-wiring.test.ts
@@ -56,6 +56,13 @@ describe('Server Edition', () => {
)
expect(serverIndex).toContain('registerStationHandoverIpc(platform, () => canvasControl?.stationHandovers ?? null)')
})
+
+ it('re-evaluates the factory\'s arms on EVERY tracker change (a SessionEnd clears a hold too)', () => {
+ const at = serverControl.indexOf('const stationHandovers = new StationHandoverTracker(')
+ const publish = serverControl.slice(at, serverControl.indexOf('})', at))
+ expect(publish).toContain('void factoryRef?.refreshArmed()')
+ expect(serverControl).toContain('factoryRef = factory')
+ })
})
describe('renderer', () => {
@@ -64,6 +71,12 @@ describe('renderer', () => {
const call = canvas.slice(canvas.indexOf('const ready = launchesToFire('))
expect(call.slice(0, call.indexOf('.filter('))).toContain('useStationHandovers.getState().byId')
expect(canvas).toContain('armedHandoverSig')
+ // A `write` is stamped when the renderer STARTED TYPING, after the human's confirm.
+ const write = canvas.slice(canvas.indexOf('const runWrite = async (): Promise<void> => {'))
+ const body = write.slice(0, write.indexOf('\n }\n'))
+ expect(body.indexOf('typedAt = Date.now()')).toBeGreaterThan(-1)
+ expect(body.indexOf('typedAt = Date.now()')).toBeLessThan(body.indexOf('api.pty.sendText('))
+ expect(body).toContain('result: { typedAt }')
expect(canvas.match(/useStationOutcomes\.getState\(\)\.byId, useStationHandovers\.getState\(\)\.byId\)/g)).toHaveLength(2)
})
})
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index dc1aff573..233ad7849 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -13936,8 +13936,13 @@ export function Canvas() {
// still waiting on its verification (command-delivery.ts). The dialog makes that
// rare, not impossible — the human confirms on their own clock, not the pane's.
let thrown: string | null = null
+ // When the text STARTED going into the pane — after the human's confirm. Core's
+ // hand-over tracker stamps the new work with it (core/station-handover.ts): a turn
+ // that began while the dialog was open is not an answer to this text.
+ let typedAt: number | undefined
const outcome = await guardConcurrentRestart(args.node, async () => {
try {
+ typedAt = Date.now()
const ok = await api.pty.sendText(args.node, args.text ?? '')
if (ok === 'pasted-not-submitted') thrown = TEXT_NOT_SUBMITTED
return ok === true ? ('sent' as const) : ('failed' as const)
@@ -13956,7 +13961,8 @@ export function Canvas() {
reply({
ok: outcome === 'sent',
message: outcome === 'sent' ? 'sent' : 'failed',
- error: outcome === 'sent' ? undefined : (thrown ?? 'sendText failed')
+ error: outcome === 'sent' ? undefined : (thrown ?? 'sendText failed'),
+ ...(typedAt !== undefined ? { result: { typedAt } } : {})
})
}
// Has the user waived this verb's dialog (this app run / permanently / while their own
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
index 2cebcbf7b..d15afa7a0 100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@ -192,9 +192,14 @@ export async function initServerCanvasControl(
)
// Stations with unfinished handed-over work (core/station-handover.ts): built before the factory,
// whose plain `--after` holds on them — the same tracker, fed the same events, as the desktop.
- const stationHandovers = new StationHandoverTracker((records) =>
+ // Every change re-evaluates the factory's arms: a hold can end on an event `refreshArmed` is not
+ // otherwise run for (a SessionEnd clearing a background-subagent hold). `factory` is assigned
+ // below, before any event can reach the tracker.
+ let factoryRef: HeadlessNodeFactory | undefined
+ const stationHandovers = new StationHandoverTracker((records) => {
platform().broadcast(IPC.stationHandoverChanged, records)
- )
+ void factoryRef?.refreshArmed()
+ })
const factory = new HeadlessNodeFactory({
workspaceStore: deps.workspaceStore,
ptyManager: deps.ptyManager,
@@ -225,6 +230,8 @@ export async function initServerCanvasControl(
appendBoardLog: (projectId, entry) => deps.boardLog.append(projectId, entry)
})
+ factoryRef = factory
+
const messaging: AgentMessagingDeps = {
paneOwner: (nodeId) => deps.ptyManager.paneOwner(nodeId),
// Server delivery has no renderer/xterm echo stream. Capture the headless pane instead and
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index 64b06dd1c..a79d218d4 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -1263,11 +1263,11 @@ describe('HeadlessNodeFactory', () => {
expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'consume result'" }])
})
- it('with a REAL tracker, a done still listing background tasks holds; an empty one releases', async () => {
+ it('with a REAL tracker, a done still listing a background subagent holds; none left releases', async () => {
// Wired as canvas-control.ts wires it: the tracker is fed every event BEFORE the factory.
const tracker = new StationHandoverTracker()
handedOver = { has: (id: string) => tracker.isHandedOver(id) } as unknown as Set<string>
- const feed = (ev: { nodeId: string; state: 'working' | 'done'; backgroundTaskIds?: string[] }) => {
+ const feed = (ev: { nodeId: string; state: 'working' | 'done'; backgroundSubagentIds?: string[] }) => {
states[ev.nodeId] = ev.state
tracker.onAgentEvent(ev)
factory.onAgentEvent(ev)
@@ -1279,11 +1279,11 @@ describe('HeadlessNodeFactory', () => {
true
)
const id = (reply.result as { id: string }).id
- feed({ nodeId: 'term-upstream', state: 'done', backgroundTaskIds: ['bash_suite'] })
+ feed({ nodeId: 'term-upstream', state: 'done', backgroundSubagentIds: ['a1b2c3'] })
await factory.refreshArmed()
expect(pty.sends).toEqual([])
feed({ nodeId: 'term-upstream', state: 'working' })
- feed({ nodeId: 'term-upstream', state: 'done', backgroundTaskIds: [] })
+ feed({ nodeId: 'term-upstream', state: 'done', backgroundSubagentIds: [] })
await factory.refreshArmed()
await factory.refreshArmed()
expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'consume result'" }])
diff --git a/src/shared/agents/claude-subagents.ts b/src/shared/agents/claude-subagents.ts
index fd6af83ae..45f9dd881 100644
--- a/src/shared/agents/claude-subagents.ts
+++ b/src/shared/agents/claude-subagents.ts
@@ -68,6 +68,29 @@ export function liveBackgroundTaskIds(value: unknown): string[] | undefined {
return out
}
+/**
+ * The subset of `liveBackgroundTaskIds` that are background SUBAGENTS (`type: 'subagent'`, the
+ * value every measured async child carries in the fixtures), or `undefined` with no inventory.
+ *
+ * Why a subset: plain `--after` holds a station whose turn ended with background work still
+ * running (core/station-handover.ts), and only a subagent is safe to hold on. An async subagent
+ * ENDS, and its `<task-notification>` wakes the parent into another turn, so a later `Stop` with
+ * it gone reliably comes. A background SHELL may never end (a dev server, a file watcher,
+ * `tail -f`) and does not reliably wake the station, so holding on one could hold a dependent
+ * forever. Any other or unknown `type` is treated like a shell: not held on.
+ */
+export function liveBackgroundSubagentIds(value: unknown): string[] | undefined {
+ if (!Array.isArray(value)) return undefined
+ const live = new Set(liveBackgroundTaskIds(value))
+ const out: string[] = []
+ for (const t of value) {
+ if (!t || typeof t !== 'object') continue
+ const { id, type } = t as { id?: unknown; type?: unknown }
+ if (type === 'subagent' && typeof id === 'string' && live.has(id) && !out.includes(id)) out.push(id)
+ }
+ return out
+}
+
/**
* The prompt Claude injects into the PARENT when a background subagent hands its result back
* (measured, 2.1.284, via the child's `SubagentHandback` tool): `<agent-message from="<agent id>">
diff --git a/src/shared/agents/normalize.claude.subagent-capture.test.ts b/src/shared/agents/normalize.claude.subagent-capture.test.ts
index e3739493a..69b930475 100644
--- a/src/shared/agents/normalize.claude.subagent-capture.test.ts
+++ b/src/shared/agents/normalize.claude.subagent-capture.test.ts
@@ -202,6 +202,30 @@ describe('normalizeClaude over the captured native subagent hooks', () => {
expect(e?.backgroundTaskIds).toEqual(['odd1', 'run1'])
})
+ it('backgroundSubagentIds is the SUBAGENT subset — the only background work plain --after holds on', () => {
+ // The measured fixture: every running entry is an async child (`type: 'subagent'`).
+ const [first, last] = named('print_async', 'Stop')
+ const e1 = normalizeClaude(env(first))
+ expect(e1?.backgroundSubagentIds).toEqual(e1?.backgroundTaskIds)
+ expect(normalizeClaude(env(last))?.backgroundSubagentIds).toEqual([])
+ // A background shell, an unknown type and a finished child do not count; no inventory = absent.
+ const mixed = normalizeClaude(
+ env({
+ ...first,
+ background_tasks: [
+ { id: 'bash_devserver', type: 'local_bash', status: 'running' },
+ { id: 'odd', type: 'something-new', status: 'running' },
+ { id: 'done1', type: 'subagent', status: 'completed' },
+ { id: 'run1', type: 'subagent', status: 'running' }
+ ]
+ })
+ )
+ expect(mixed?.backgroundTaskIds).toEqual(['bash_devserver', 'odd', 'run1'])
+ expect(mixed?.backgroundSubagentIds).toEqual(['run1'])
+ const { background_tasks: _drop, ...older } = first
+ expect(normalizeClaude(env(older))?.backgroundSubagentIds).toBeUndefined()
+ })
+
it('the subagent hand-back prompt is not a genuine user turn (same rule as <task-notification>)', () => {
const handback = events('interactive_background_then_esc').find(
(e) => e.hook_event_name === 'UserPromptSubmit' && String(e.prompt).startsWith('<agent-message')
diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.ts
index f1a34c549..e0a01a6c8 100644
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@ -1,7 +1,12 @@
import type { AgentId } from './config'
import type { ObservedClaudeAccount } from '../types'
import { ASK_USER_QUESTION_TOOL, isSafeToolName, readQuestions, type HeldPermission } from './permission-answer'
-import { isClaudeAgentId, isInjectedSubagentPrompt, liveBackgroundTaskIds } from './claude-subagents'
+import {
+ isClaudeAgentId,
+ isInjectedSubagentPrompt,
+ liveBackgroundSubagentIds,
+ liveBackgroundTaskIds
+} from './claude-subagents'
export type AgentState = 'working' | 'waiting' | 'blocked' | 'done'
@@ -114,6 +119,9 @@ export interface NormalizedAgentEvent {
* `liveBackgroundTaskIds`.
*/
backgroundTaskIds?: string[]
+ /** The async SUBAGENTS among `backgroundTaskIds` (`liveBackgroundSubagentIds`) — the only
+ * background work plain `--after` holds on. Present exactly when `backgroundTaskIds` is. */
+ backgroundSubagentIds?: string[]
/** Host-observed start time for display-only renderer reload replay. */
subagentStartedAt?: number
// grok StopCancelled only: normalized state-less so the mirror can make the session-aware badge
@@ -378,13 +386,15 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nu
}
if (ev === 'Stop') {
const backgroundTaskIds = liveBackgroundTaskIds(p.background_tasks)
+ const backgroundSubagentIds = liveBackgroundSubagentIds(p.background_tasks)
return {
...base,
kind: 'state',
state: 'done',
interrupted: p.is_interrupt === true,
lastMessage: p.last_assistant_message,
- ...(backgroundTaskIds ? { backgroundTaskIds } : {})
+ ...(backgroundTaskIds ? { backgroundTaskIds } : {}),
+ ...(backgroundSubagentIds ? { backgroundSubagentIds } : {})
}
}
// The turn died on an API/model error — Claude Code skips the normal Stop hook here,
diff --git a/test/acceptance/after-handover.test.ts b/test/acceptance/after-handover.test.ts
index 530895fd0..19a204a70 100644
--- a/test/acceptance/after-handover.test.ts
+++ b/test/acceptance/after-handover.test.ts
@@ -24,6 +24,7 @@ import { StationHandoverTracker } from '../../src/core/station-handover'
import type { AgentState } from '../../src/shared/agents/normalize'
import type { StationHandoverRecord } from '../../src/shared/station-handover'
import { launchesToFire, type ArmedNode } from '../../src/renderer/lib/pendingLaunch'
+import { normalizeClaude } from '../../src/shared/agents/normalize'
interface Harness {
deps: AgentMessagingDeps
@@ -217,24 +218,47 @@ describe('plain --after after a write / run', () => {
})
})
-describe('plain --after on a station whose turn ended with BACKGROUND tasks still running', () => {
- // Measured live (2026-09-30): an agent's turn ended while its test suite still ran in a
- // background shell, and the node armed `--after` it fired before anything had been pushed.
- const stop = (h: Harness, ids: string[] | undefined) => {
+describe('plain --after on a station whose turn ended with background work still running', () => {
+ // Measured live (2026-09-30): an agent's turn ended while its work went on in the background, and
+ // the node armed `--after` it fired before anything had been pushed. Only background SUBAGENTS
+ // hold: an async child ends and its task-notification wakes the parent into another turn, while a
+ // background SHELL (a dev server, a watcher) may never end — holding on it would hold forever.
+ // Fed through the REAL Claude normalizer, so the `type` split is the one production applies.
+ const stop = (h: Harness, tasks: Array<{ id: string; type: string; status: string }> | undefined) => {
h.tick(10)
h.state.st = 'done'
- h.tracker.onAgentEvent({ nodeId: 'st', state: 'done', ...(ids ? { backgroundTaskIds: ids } : {}) })
+ const ev = normalizeClaude({
+ nodeId: 'st',
+ agentId: 'claude',
+ payload: {
+ hook_event_name: 'Stop',
+ session_id: 's1',
+ ...(tasks ? { background_tasks: tasks } : {})
+ }
+ })!
+ h.tracker.onAgentEvent(ev)
}
- it('a done listing a running task does not release D; a later done with an empty inventory does', () => {
+ it('an async SUBAGENT still running holds D until a later turn end with none left', () => {
const h = harness()
h.event('working')
- stop(h, ['bash_suite'])
+ stop(h, [{ id: 'a1b2c3', type: 'subagent', status: 'running' }])
expect(dFires(h)).toBe(false)
- // The suite finishes and wakes the station (or the next prompt does); that turn's end is empty.
+ // The child's task-notification wakes the station; that turn ends with the child gone.
h.event('working')
expect(dFires(h)).toBe(false)
- stop(h, [])
+ stop(h, [{ id: 'a1b2c3', type: 'subagent', status: 'completed' }])
+ expect(dFires(h)).toBe(true)
+ })
+
+ it('a background SHELL that never ends (a dev server) does NOT hold D — before and after this PR', () => {
+ const h = harness()
+ h.event('working')
+ stop(h, [{ id: 'bash_devserver', type: 'local_bash', status: 'running' }])
+ expect(dFires(h)).toBe(true)
+ // …and it keeps not holding on every later turn that still lists it.
+ h.event('working')
+ stop(h, [{ id: 'bash_devserver', type: 'local_bash', status: 'running' }])
expect(dFires(h)).toBe(true)
})