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.

Merge origin/fix/after-stale-done (#1052 rework)

review682603001a88
diff --cc CLAUDE.md
index c0823de41,b923234ed..853b8932e
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -3856,26 -3862,31 +3866,32 @@@ command-bearing opens; this does not ad
`--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.
+ open the dependent"). DURABLE across a restart (`HANDOVER_FACT`, see **Durable orchestration
+ state**): the holding stations are stored, `queued` is rebuilt from the durable queue.
Relay tabs take the inert stub; the list channel is HOST_ONLY
(unscoped: every project's stations). Mobile: N/A (the phone never sees `pendingLaunch`).
Tests: `core/station-handover.test.ts`, `test/acceptance/after-handover.test.ts` (the REAL
diff --cc src/core/station-handover.persist.test.ts
index 6260eed6d,000000000..1426f2b00
mode 100644,000000..100644
--- a/src/core/station-handover.persist.test.ts
+++ b/src/core/station-handover.persist.test.ts
@@@ -1,108 -1,0 +1,108 @@@
+import { describe, it, expect } from 'vitest'
+import {
+ HANDOVER_FACT,
+ StationHandoverTracker,
+ sanitizePersistedHandover,
+ type PersistedHandover
+} from './station-handover'
+import { DurableFactFile } from './durable-state'
+import { testTmpDir } from './test-tmp'
+
+/**
+ * The plain-`--after` hand-over hold across an app restart: write through one tracker, read
+ * through a new one. Without it a restart released every dependent on the first `done` it saw.
+ */
+
+function disk() {
+ let saved: PersistedHandover[] = []
+ return {
+ durable: {
+ load: () => JSON.parse(JSON.stringify(saved)).map(sanitizePersistedHandover).filter(Boolean),
+ save: (r: PersistedHandover[]) => (saved = r)
+ },
+ saved: () => saved
+ }
+}
+
+describe('station hand-over holds across a restart', () => {
+ it('a hold survives, and only a turn that started after the hand-over ends it', () => {
+ let now = 1000
+ const d = disk()
+ const a = new StationHandoverTracker(() => {}, () => now, d.durable)
+ a.onAgentEvent({ nodeId: 'st1', state: 'done' })
+ a.noteControlAnswer('write', { node: 'st1' }, { ok: true }, 'orch', 1000)
+ expect(a.isHandedOver('st1')).toBe(true)
+ expect(d.saved()).toEqual([{ nodeId: 'st1', handedAt: 1000, state: 'done' }])
+
+ now = 5000
+ const b = new StationHandoverTracker(() => {}, () => now, d.durable)
+ expect(b.isHandedOver('st1')).toBe(false) // nothing until loadFromDisk
+ b.loadFromDisk()
+ expect(b.isHandedOver('st1')).toBe(true)
+ // The first `done` after the restart is the PREVIOUS task's: it releases nothing.
+ b.onAgentEvent({ nodeId: 'st1', state: 'done' })
+ expect(b.isHandedOver('st1')).toBe(true)
+ b.onAgentEvent({ nodeId: 'st1', state: 'working' })
+ b.onAgentEvent({ nodeId: 'st1', state: 'done' })
+ expect(b.isHandedOver('st1')).toBe(false)
+ expect(d.saved()).toEqual([])
+ })
+
+ it('a turn that started after the hand-over and was still running at the restart ends the hold on its done', () => {
+ let now = 1000
+ const d = disk()
+ const a = new StationHandoverTracker(() => {}, () => now, d.durable)
+ a.markHandedOver('st1', 1000)
+ now = 2000
+ a.onAgentEvent({ nodeId: 'st1', state: 'working' })
+ expect(d.saved()[0]).toMatchObject({ turnStartedAt: 2000, state: 'working' })
+ const b = new StationHandoverTracker(() => {}, () => 9000, d.durable)
+ b.loadFromDisk()
+ b.onAgentEvent({ nodeId: 'st1', state: 'done' })
+ expect(b.isHandedOver('st1')).toBe(false)
+ })
+
+ it('background work survives too, and a present empty inventory clears it', () => {
+ const d = disk()
+ const a = new StationHandoverTracker(() => {}, () => 1, d.durable)
- a.onAgentEvent({ nodeId: 'st1', state: 'done', backgroundTaskIds: ['b1'] })
++ a.onAgentEvent({ nodeId: 'st1', state: 'done', backgroundSubagentIds: ['b1'] })
+ const b = new StationHandoverTracker(() => {}, () => 2, d.durable)
+ b.loadFromDisk()
+ expect(b.isHandedOver('st1')).toBe(true)
- b.onAgentEvent({ nodeId: 'st1', state: 'done', backgroundTaskIds: [] })
++ b.onAgentEvent({ nodeId: 'st1', state: 'done', backgroundSubagentIds: [] })
+ expect(b.isHandedOver('st1')).toBe(false)
+ })
+
+ it('queued is not stored: the restored queue replays it', () => {
+ const d = disk()
+ const a = new StationHandoverTracker(() => {}, () => 1, d.durable)
+ a.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st1' })
+ expect(d.saved()).toEqual([])
+ const b = new StationHandoverTracker(() => {}, () => 2, d.durable)
+ b.loadFromDisk()
+ b.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st1' })
+ expect(b.list()).toEqual([{ nodeId: 'st1', queued: true }])
+ // …and a message that lapsed while the app was down still holds the station.
+ b.onHandover({ phase: 'settled', verb: 'send', targetNodeId: 'st1', landed: false })
+ expect(b.isHandedOver('st1')).toBe(true)
+ })
+
+ it('sanitizes hand-edited entries; one that holds nothing is dropped', () => {
+ expect(sanitizePersistedHandover({ nodeId: 'st1', handedAt: 1 })).toEqual({ nodeId: 'st1', handedAt: 1 })
+ expect(sanitizePersistedHandover({ nodeId: 'st1' })).toBeNull()
+ expect(sanitizePersistedHandover({ nodeId: '../x', handedAt: 1 })).toBeNull()
+ expect(sanitizePersistedHandover({ nodeId: 'st1', handedAt: 'x' })).toBeNull()
+ expect(sanitizePersistedHandover({ nodeId: 'st1', handedAt: 1, state: 'idle' })).toBeNull()
+ })
+
+ it('end to end through the file', async () => {
+ const dir = testTmpDir('nt-handover-')
+ const f = new DurableFactFile(HANDOVER_FACT, { userDataDir: dir, debounceMs: 1 })
+ const a = new StationHandoverTracker(() => {}, () => 1, f)
+ a.markHandedOver('st1', 1)
+ await f.flush()
+ const b = new StationHandoverTracker(() => {}, () => 2, new DurableFactFile(HANDOVER_FACT, { userDataDir: dir }))
+ b.loadFromDisk()
+ expect(b.isHandedOver('st1')).toBe(true)
+ })
+})
diff --cc src/core/station-handover.ts
index 3f62cd3e6,f21741ba8..52407c8cb
--- a/src/core/station-handover.ts
+++ b/src/core/station-handover.ts
@@@ -48,24 -60,9 +60,27 @@@
* 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.
*
- * Bounded (the oldest station with nothing handed over is evicted first) and DURABLE ACROSS A
- * 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.
++ * 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) and DURABLE ACROSS A
+ * RESTART (`HANDOVER_FACT`, `<userData>/orchestration-state/station-handovers.json`, through
+ * core/durable-state.ts). Without it an app restart forgot every hold, and a dependent armed on a
+ * station that had just been handed its next task fired on the first `done` after the restart —
+ * the previous task's, or a turn in flight before the work landed. What a restart means here:
+ * - the HOLDING stations are stored — `handedAt`, the current turn's start and state, the
+ * background flag — so a hold ends after the restart exactly as it would have without one: on
+ * a `done` for a turn that started at or after the hand-over (wall-clock times, so a turn that
+ * began before the restart still counts if it began after the hand-over);
+ * - `queued` is NOT stored: it is rebuilt from the durable delivery queue, whose restore replays
+ * a `queued` hand-over per waiting message (and a `settled` one, never landed, for each message
+ * that lapsed while the app was down — which is still a hand-over, see above);
+ * - hook events are lost while the app is down (the hook POSTs have nowhere to go), so a turn
+ * that ENDED during the downtime is not seen: the hold lasts until the station's next turn end.
+ * The holding direction, with ▶ / `run` as the way out, like every other uncertainty here;
+ * - a hold is not bound to a session: a station respawned into a new session still owes the work
+ * it was handed, and its next completed turn ends the hold as usual.
+ * Loaded by each shell after the station reports and before the delivery queue.
++ * The recent state `history` (what a confirm-delayed `write` answers) is NOT stored: it spans one
++ * confirm dialog, and after a restart the request it described is gone.
*/
import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'
import { IPC } from '../shared/ipc'
@@@ -243,19 -194,23 +283,26 @@@ 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)) {
- const started = !t.state || !ACTIVE.has(t.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()
++ const started = !t.state || !ACTIVE.has(t.state) || event.newTurn === true
+ if (started) t.turnStartedAt = this.now()
- t.state = state
+ this.setState(t, state)
+ // A held station's turn start is what ends its hold: it must survive a restart too.
+ if (started && holds(t)) this.persist()
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()
}
diff --cc src/server/canvas-control.ts
index 87cda6549,d15afa7a0..16e9ebd1f
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@@ -207,15 -192,14 +207,22 @@@ export async function initServerCanvasC
)
// 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.
- // Durable like the reports; loaded in the same order as the desktop (reports, hand-overs, queue).
+ // 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.
++ // below, before any event can reach the tracker. Durable like the reports; loaded in the same
++ // order as the desktop (reports, hand-overs, queue).
+ let factoryRef: HeadlessNodeFactory | undefined
- const stationHandovers = new StationHandoverTracker((records) => {
- platform().broadcast(IPC.stationHandoverChanged, records)
- void factoryRef?.refreshArmed()
- })
+ const handoversFile = new DurableFactFile(HANDOVER_FACT, { userDataDir: platform().userDataDir })
+ const stationHandovers = new StationHandoverTracker(
- (records) => platform().broadcast(IPC.stationHandoverChanged, records),
++ (records) => {
++ platform().broadcast(IPC.stationHandoverChanged, records)
++ void factoryRef?.refreshArmed()
++ },
+ Date.now,
+ handoversFile
+ )
+ stationOutcomes.loadFromDisk()
+ stationHandovers.loadFromDisk()
const factory = new HeadlessNodeFactory({
workspaceStore: deps.workspaceStore,
ptyManager: deps.ptyManager,