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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(control): plain --after no longer fires on a done from before new work was handed over
review4d793151c6c8
diff --git a/CLAUDE.md b/CLAUDE.mdindex 11a32ad80..1d84e48d2 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3817,6 +3817,51 @@ command-bearing opens; this does not add a human-confirm dialog or change mobileso reporting it as "the error" would be a confident wrong fact. Reading the text, and the*failed-to-start* watchdog (a station that never emits ANY hook event — the opposite failure,which hangs dependents honestly rather than firing them wrongly), stay open.+ **(10) A `done` from BEFORE new work was handed over does not release anything**+ (`core/station-handover.ts`, `@shared/station-handover`, 2026-09-30). A station is reused: an+ orchestrator hands it task B (`send` → `queued` because it is busy, or delivered to an idle pane+ it has not started on yet, or a `write` / `run`) and then opens D `--after <station>`. Until the+ station STARTS B its state is still task A's `done`, so D fired at once — on A's output, and a+ launched dependent cannot un-launch. #1042 closed the same hole for `--after-success` (reports);+ this is the plain-turn half. Rules a refactor must not undo:+ - **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).+ - **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+ 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.+ - **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+ source level by `main/station-handover-wiring.test.ts`.+ - **The renderer reads it through a derived primitive signature** (`armedHandoverSig`, only the+ armed nodes' deps — the `armedDepSig` rule), and `launchesToFire` / `depSatisfied` take it as a+ trailing argument: a handed-over station is never a satisfied dep, a DELETED one still is.+ `successDepFacts.turnDone` applies it too, so a success wait never releases where plain+ `--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.+ - **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+ 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+ (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+ queue → tracker → the renderer's real `launchesToFire`, red on the old code) and the server+ factory's own cases.**Pull request waits (`--after-pr`, 2026-09-29).** `open-terminal --cmd …` / `open-claude` /`open-agent` take `--after-pr <N:checks|N:merged>[,…]` (N may be `#N` or `owner/repo#N`) and`--pr-deadline <90m|12h|3d>`: the held launch ALSO waits for pull requests of the project'sdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex d12f15adc..505e19f6d 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -349,6 +349,13 @@ anything else. Board-level fields survive every transform — `pullLinks` is oneruns only on time. Do not move the ledger into one shell's handler: the other shell silently losesit.+- **A new way to hand a station work must feed `src/core/station-handover.ts`.** Plain `--after`+ would otherwise release a dependent on the station's `done` from its PREVIOUS task. Today the+ hand-overs are `send` / `reply` (through the messaging layer's `onHandover`) and `write` / `run`+ (`noteControlAnswer` in each shell's control handler — desktop main's `finishAnswer` and the+ Server Edition wrapper). A new verb that types a task into another node's pane joins that set in+ the same PR, on BOTH shells; `src/main/station-handover-wiring.test.ts` pins the sites that exist.+- **A new canvas-control open path must record who opened the node.** When a station stops, theagent that opened it is told (`src/core/agents/station-notice.ts`) — and a rope alone cannot saywho that is, because an `--after` node is roped to the stations it waited on too, with the same iddiff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex cd6e07a38..9adbb2a3b 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -255,6 +255,25 @@ function afterSuccessDocLines(): string[] {]}+/**+ * The plain `--after` "new work" rule — core/station-handover.ts. Both agent-facing bodies share+ * these lines; `canvas-control-core.test.ts` pins them against both.+ */+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.',+ '- 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."+ ]+}+function reportOutcomeDocLines(): string[] {return [`- \`${REPORT_OUTCOME_VERB} --outcome succeeded|failed [--note "<one line>"]\` — say how YOUR task went.`,@@ -833,6 +852,7 @@ export function buildCanvasControlInstructions(shimPath: string): string {' agent does not recognise fails inside the session, not at open time — name a model you know.',...issueBindingDocLines(),...afterPrDocLines(),+ ...afterHandoverDocLines(),...afterSuccessDocLines(),...reportOutcomeDocLines(),'- `open-project --cwd </abs/path> [--name N] [--color C]` — register (or find) the project for a',@@ -1399,6 +1419,8 @@ Verbs:open time, so name a model you know that CLI accepts rather than guessing.${issueBindingDocLines().join('\n')}${afterPrDocLines().join('\n')}+${afterHandoverDocLines().join('\n')}+${afterSuccessDocLines().join('\n')}${reportOutcomeDocLines().join('\n')}- \`open-project --cwd </abs/path> [--name N] [--color C]\` — register (or find) the project for adiff --git a/src/core/station-handover.test.ts b/src/core/station-handover.test.tsnew file mode 100644index 000000000..f2f1feadc--- /dev/null+++ b/src/core/station-handover.test.ts@@ -0,0 +1,145 @@+import { describe, expect, it } from 'vitest'+import { StationHandoverTracker, STATION_HANDOVER_MAX_TRACKED } from './station-handover'++function tracker() {+ let clock = 1_000+ const pushes: string[][] = []+ const t = new StationHandoverTracker(+ (records) => pushes.push(records.map((r) => r.nodeId)),+ () => clock+ )+ return {+ t,+ pushes,+ at: (ms: number) => {+ clock = ms+ return ms+ },+ ev: (state: 'working' | 'waiting' | 'blocked' | 'done', ms?: number) => {+ if (ms !== undefined) clock = ms+ t.onAgentEvent({ nodeId: 'st', state })+ }+ }+}++describe('StationHandoverTracker — when a station counts as finished for plain --after', () => {+ it('a QUEUED send holds the station from the moment it is queued, whatever it reads', () => {+ const h = tracker()+ h.ev('working', 100)+ h.t.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st' })+ expect(h.t.isHandedOver('st')).toBe(true)+ // The station finishes its OLD task: still held (the message has not even landed).+ h.ev('done', 200)+ expect(h.t.isHandedOver('st')).toBe(true)+ // The queue flushes on that idle edge.+ h.t.onHandover({ phase: 'landed', verb: 'send', targetNodeId: 'st', at: h.at(210) })+ h.t.onHandover({ phase: 'settled', verb: 'send', targetNodeId: 'st', landed: true })+ expect(h.t.isHandedOver('st')).toBe(true)+ // The new task's turn starts and ends: released.+ h.ev('working', 220)+ expect(h.t.isHandedOver('st')).toBe(true)+ h.ev('done', 300)+ expect(h.t.isHandedOver('st')).toBe(false)+ expect(h.t.list()).toEqual([])+ })++ it('landed on an idle station but not started yet: the old done does not count', () => {+ const h = tracker()+ h.ev('working', 100)+ h.ev('done', 200)+ h.t.onHandover({ phase: 'landed', verb: 'reply', targetNodeId: 'st', at: 300 })+ expect(h.t.isHandedOver('st')).toBe(true)+ expect(h.t.list()).toEqual([{ nodeId: 'st', since: 300 }])+ // An idle-prompt style `done` with no turn in between releases nothing.+ h.ev('done', 350)+ expect(h.t.isHandedOver('st')).toBe(true)+ h.ev('working', 400)+ h.ev('done', 500)+ expect(h.t.isHandedOver('st')).toBe(false)+ })++ it('a turn that started and ENDED before the delivery reported back already answers it', () => {+ const h = tracker()+ h.ev('done', 100)+ // The delivery attempt started at 200; the prompt's turn ran 210–260; `landed` is emitted at 270.+ h.ev('working', 210)+ h.ev('done', 260)+ h.at(270)+ h.t.onHandover({ phase: 'landed', verb: 'send', targetNodeId: 'st', at: 200 })+ expect(h.t.isHandedOver('st')).toBe(false)+ })++ it('work landing in a turn ALREADY in progress waits for a turn that starts after it', () => {+ const h = tracker()+ h.ev('working', 100)+ h.t.noteControlAnswer('write', { node: 'st', text: 'x' }, { ok: true }, 'orch', 150)+ expect(h.t.isHandedOver('st')).toBe(true)+ h.ev('blocked', 160) // still the same turn+ h.ev('working', 170)+ h.ev('done', 200) // the OLD turn ends+ expect(h.t.isHandedOver('st')).toBe(true)+ h.ev('working', 210)+ h.ev('done', 300)+ expect(h.t.isHandedOver('st')).toBe(false)+ })++ it('write / run count from when the request ARRIVED, only on success, never for the caller itself', () => {+ const h = tracker()+ h.ev('done', 100)+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: false }, 'orch', 150)+ h.t.noteControlAnswer('close', { node: 'st' }, { ok: true }, 'orch', 150)+ h.t.noteControlAnswer('write', { node: 'st' }, { ok: true }, 'st', 150)+ expect(h.t.isHandedOver('st')).toBe(false)+ // run: the turn the launch starts (at 160) happened before main heard the answer (at 400).+ h.ev('working', 160)+ h.ev('done', 390)+ h.at(400)+ h.t.noteControlAnswer('run', { node: 'st' }, { ok: true }, 'orch', 150)+ expect(h.t.isHandedOver('st')).toBe(false)+ // A comma list marks each named node.+ h.t.noteControlAnswer('write', { node: 'st, other' }, { ok: true }, 'orch', 500)+ expect(h.t.isHandedOver('st')).toBe(true)+ expect(h.t.isHandedOver('other')).toBe(true)+ })++ it('a queued message that never lands still holds, until the station finishes a later turn', () => {+ const h = tracker()+ h.ev('working', 100)+ h.t.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st' })+ h.ev('done', 200)+ h.at(250)+ h.t.onHandover({ phase: 'settled', verb: 'send', targetNodeId: 'st', landed: false })+ expect(h.t.isHandedOver('st')).toBe(true)+ h.ev('working', 300)+ h.ev('done', 400)+ expect(h.t.isHandedOver('st')).toBe(false)+ })++ it('board comments and station notices are not a hand-over (#1042 counts the same set)', () => {+ const h = tracker()+ h.t.onHandover({ phase: 'queued', verb: 'board-comment', targetNodeId: 'st' })+ h.t.onHandover({ phase: 'landed', verb: 'station-notice', targetNodeId: 'st', at: 5 })+ expect(h.t.isHandedOver('st')).toBe(false)+ expect(h.pushes).toEqual([])+ })++ it('pushes the whole list only when it changes, and bounds what it tracks', () => {+ const h = tracker()+ h.t.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st' })+ h.ev('working', 10)+ h.ev('done', 20)+ expect(h.pushes).toEqual([['st']])+ for (let i = 0; i < STATION_HANDOVER_MAX_TRACKED + 5; i++) h.t.onAgentEvent({ nodeId: `n${i}`, state: 'done' })+ // The oldest station is the held one, and it is NOT the one evicted: dropping it would release+ // its dependents. The overflow comes out of the stations with nothing handed over.+ expect(h.t.isHandedOver('st')).toBe(true)+ expect(h.t.list().map((r) => r.nodeId)).toEqual(['st'])+ })++ it('ignores unsafe ids and stateless events', () => {+ const h = tracker()+ h.t.markHandedOver('../x', 5)+ h.t.onAgentEvent({ nodeId: 'st', state: undefined })+ expect(h.t.list()).toEqual([])+ })+})diff --git a/src/core/station-handover.ts b/src/core/station-handover.tsnew file mode 100644index 000000000..dd0efc715--- /dev/null+++ b/src/core/station-handover.ts@@ -0,0 +1,210 @@+/**+ * Which stations have been HANDED NEW WORK they have not finished — the fact plain `--after` needs+ * (@shared/station-handover has the why). ONE module for both shells: desktop main feeds it and+ * pushes its list to the renderer, whose launch loop (`launchesToFire`) reads it; the Server+ * Edition's headless factory asks it directly. So the two editions cannot come to disagree about+ * when a dependent starts.+ *+ * WHAT COUNTS AS A HAND-OVER — the same moments #1042's report rule uses+ * (src/core/station-outcome-store.ts), fed by the same events:+ * - a `send` / `reply` QUEUED for a busy station (`onHandover` 'queued'): the station is handed+ * over from that moment — its current `done` is the PREVIOUS task's — until the message lands+ * and a turn after it ends;+ * - the bytes LANDING in the pane (`onHandover` 'landed', first attempt or flush) at `at`, which+ * 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.+ *+ * 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).+ *+ * 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.+ */+import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'+import { IPC } from '../shared/ipc'+import { isSafeNodeId } from '../shared/safe-id'+import type { StationHandoverRecord } from '../shared/station-handover'+import type { MessageHandover } from './agents/agent-messaging'+import type { CorePlatform } from './platform'++/** How many stations' activity one process tracks. Far past any canvas; evicts the oldest first. */+export const STATION_HANDOVER_MAX_TRACKED = 2000++/** The messaging verbs whose delivery hands a station new work (#1042's set). */+const HANDOVER_VERBS: ReadonlySet<string> = new Set(['send', 'reply'])++/** The control verbs whose successful ANSWER means new work reached the node they name. */+export const HANDOVER_CONTROL_VERBS: ReadonlySet<string> = new Set(['write', 'run'])++const ACTIVE: ReadonlySet<AgentState> = new Set<AgentState>(['working', 'waiting', 'blocked'])++interface StationTrack {+ /** The last state seen. `undefined` until the first event. */+ state?: AgentState+ /** 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. */+ queued: number+ /** The newest hand-over that no finished turn has answered yet. */+ handedAt?: number+}++export class StationHandoverTracker {+ // Insertion order IS recency (re-set on every touch), so eviction is one `keys().next()`.+ private readonly byId = new Map<string, StationTrack>()+ private lastSig = ''++ constructor(+ private readonly publish: (records: StationHandoverRecord[]) => void = () => {},+ private readonly now: () => number = Date.now+ ) {}++ private touch(nodeId: string): StationTrack {+ const cur = this.byId.get(nodeId) ?? { queued: 0 }+ this.byId.delete(nodeId)+ this.byId.set(nodeId, cur)+ // Evict the oldest station with NOTHING handed over: dropping a held one would release its+ // dependents — the direction nothing can undo. Only a map full of held stations drops one.+ while (this.byId.size > STATION_HANDOVER_MAX_TRACKED) {+ let victim: string | undefined+ for (const [id, t] of this.byId) {+ if (id !== nodeId && t.queued <= 0 && t.handedAt === undefined) {+ victim = id+ break+ }+ }+ victim ??= this.byId.keys().next().value+ if (victim === undefined) break+ this.byId.delete(victim)+ }+ return cur+ }++ /** Has the turn answering the hand-over already ended? */+ private settle(t: StationTrack): void {+ if (+ t.handedAt !== undefined &&+ t.state === 'done' &&+ t.turnStartedAt !== undefined &&+ t.turnStartedAt >= t.handedAt+ )+ t.handedAt = undefined+ }++ private changed(): void {+ const list = this.list()+ const sig = list.map((r) => `${r.nodeId}:${r.since ?? ''}:${r.queued ? 1 : 0}`).join('|')+ if (sig === this.lastSig) return+ this.lastSig = sig+ this.publish(list)+ }++ /** Every agent event of every node, fed BEFORE anything that acts on it (the Server Edition's+ * `refreshArmed`, the messaging queue's flush on `done`). Events without a state are ignored. */+ onAgentEvent(event: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): void {+ const state = event?.state+ if (!event?.nodeId || !isSafeNodeId(event.nodeId) || typeof state !== 'string') 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+ return+ }+ t.state = state+ if (state === 'done') {+ this.settle(t)+ this.changed()+ }+ }++ /** New work landed in the station's pane at `at` (this process's clock). */+ markHandedOver(nodeId: string, at: number): void {+ if (!isSafeNodeId(nodeId) || !Number.isFinite(at)) return+ const t = this.touch(nodeId)+ t.handedAt = Math.max(t.handedAt ?? at, at)+ // A delivered prompt can start AND finish its turn before the delivery reports back.+ this.settle(t)+ this.changed()+ }++ /** The messaging layer's hand-over events (`AgentMessagingDeps.onHandover`). */+ onHandover(ev: MessageHandover): void {+ if (!HANDOVER_VERBS.has(ev.verb) || !isSafeNodeId(ev.targetNodeId)) return+ const id = ev.targetNodeId+ if (ev.phase === 'queued') {+ this.touch(id).queued+++ this.changed()+ return+ }+ if (ev.phase === 'landed') {+ this.markHandedOver(id, ev.at)+ return+ }+ const t = this.touch(id)+ t.queued = Math.max(0, t.queued - 1)+ // A queued message that never landed still counts as handed over (see the header).+ if (!ev.landed) t.handedAt = Math.max(t.handedAt ?? 0, this.now())+ this.changed()+ }++ /**+ * 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.+ */+ noteControlAnswer(+ verb: string,+ args: Record<string, string | undefined>,+ result: { ok: boolean },+ callerNodeId: string,+ requestAt: number+ ): void {+ if (!result.ok || !HANDOVER_CONTROL_VERBS.has(verb) || typeof args.node !== 'string') return+ for (const id of args.node.split(',').map((s) => s.trim())) {+ if (id && id !== callerNodeId && isSafeNodeId(id)) this.markHandedOver(id, requestAt)+ }+ }++ /** Is `--after` on this station held by unfinished handed-over work? */+ isHandedOver(nodeId: string): boolean {+ const t = this.byId.get(nodeId)+ return !!t && (t.queued > 0 || t.handedAt !== undefined)+ }++ /** Every station with unfinished handed-over work, newest first. */+ list(): StationHandoverRecord[] {+ const out: StationHandoverRecord[] = []+ for (const [nodeId, t] of [...this.byId.entries()].reverse()) {+ if (t.queued <= 0 && t.handedAt === undefined) continue+ out.push({+ nodeId,+ ...(t.handedAt !== undefined ? { since: t.handedAt } : {}),+ ...(t.queued > 0 ? { queued: true as const } : {})+ })+ }+ return out+ }+}++/** The read channel, registered by BOTH shells. `tracker` is a thunk: a shell may build it after+ * the platform handlers. */+export function registerStationHandoverIpc(+ platform: Pick<CorePlatform, 'handle'>,+ tracker: () => StationHandoverTracker | null+): void {+ platform.handle(IPC.stationHandoverList, () => tracker()?.list() ?? [])+}diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex 62712f8a9..e00289168 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -1518,6 +1518,22 @@ describe('--after-success + report-outcome: a dependent that waits for a reporteexpect(flat).toContain('The Server Edition accepts both the flag and the verb')})+ // Plain `--after` and new work (core/station-handover.ts): the rule an orchestrator reusing a+ // station must know, in both bodies, in the words core implements.+ it.each(bodies)('%s states that new work resets a plain --after wait, and how to reuse a station', (_name, body) => {+ 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'+ )+ 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('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")+ })+it.each(bodies)('%s teaches stations to report, honestly, about themselves only', (_name, body) => {const flat = body.replace(/\s+/g, ' ')expect(flat).toContain(`\`${REPORT_OUTCOME_VERB} --outcome succeeded|failed [--note "<one line>"]\``)diff --git a/src/main/index.ts b/src/main/index.tsindex efe14f8a9..603c655c6 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -86,6 +86,10 @@ import {handleReportOutcome,registerStationOutcomeIpc} from '../core/station-outcome-store'+import {+ StationHandoverTracker,+ registerStationHandoverIpc+} from '../core/station-handover'import { afterSuccessFlagRefusal } from '../shared/station-outcome'import { stationRecipient } from '../shared/station-notice'import type { RemoteLogExec } from '../core/board-log'@@ -1961,7 +1965,17 @@ app.whenReady().then(async () => {// A `send` / `reply` hands a station new work — decided by when the message REACHES its pane (a// queued one marks the station "work pending" until it lands), never by when the control answer// comes back. The messaging service reports those moments; the store applies the rule.- messagingDeps.onHandover = (ev) => stationOutcomes.onHandover(ev)+ // The same hand-over moments also hold plain `--after` (src/core/station-handover.ts): a station+ // handed new work is not "done" until a turn that started after the hand-over has ended. Pushed+ // whole to the window, whose launch loop reads it.+ const stationHandovers = new StationHandoverTracker((records) =>+ sendToMain(IPC.stationHandoverChanged, records)+ )+ registerStationHandoverIpc(corePlatform, () => stationHandovers)+ messagingDeps.onHandover = (ev) => {+ stationOutcomes.onHandover(ev)+ stationHandovers.onHandover(ev)+ }ipcMain.handle(IPC.dialogSelectFolder, async () => {const result = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'] })@@ -2899,6 +2913,9 @@ app.whenReady().then(async () => {// event ENRICHED for a needs-you edge (a question strips its pendingId), so the canvas keys off// the same single source of truth as the mirror/phone. Then broadcast the enriched event.const enriched = recordAgentEvent(out) ?? out+ // The hand-over tracker FIRST: it stamps when a station's turn starts and ends, and the+ // messaging queue below may flush new work into the station on this very `done`.+ stationHandovers.onAgentEvent(enriched)sendToMain(IPC.agentStatus, enriched)// Feed the macOS Notch HUD its prompt (ev.task on newTurn) + subagent grouping (no-op off/non-darwin).notchHudOnAgentEvent(enriched)@@ -3844,6 +3861,9 @@ app.whenReady().then(async () => {)}hookServer.setControlHandler(async ({ verb, nodeId, args, verified, onLateAnswer }) => {+ // When the request ARRIVED — before a `write` / `run` typed anything. The hand-over tracker+ // stamps the new work with it, so a turn the typed text starts is always later.+ const requestAt = Date.now()// `--dry-run` (issue #532) is honoured by the spawn verbs only, and this gate runs FIRST —// before the browser intercept, the open-project gates and the renderer forward — because a// verb that cannot dry-run must REFUSE rather than silently perform: a `close --dry-run`@@ -3972,6 +3992,8 @@ app.whenReady().then(async () => {// only on success. `send` / `reply` go through `messagingDeps.onHandover` instead: their// answer can be `queued`, long before the message reaches the pane.clearOutcomesAfterControl(stationOutcomes, verb, args, answer, nodeId)+ // …and holds plain `--after` on that station until a turn after it ends.+ stationHandovers.noteControlAnswer(verb, args, answer, nodeId, requestAt)return answer}// The timeout is NAMED, and what it says depends on the verb and on whether the request ledgerdiff --git a/src/main/station-handover-wiring.test.ts b/src/main/station-handover-wiring.test.tsnew file mode 100644index 000000000..7c2fc1083--- /dev/null+++ b/src/main/station-handover-wiring.test.ts@@ -0,0 +1,69 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * SOURCE-LEVEL pins for the plain `--after` hand-over rule (src/core/station-handover.ts). Every+ * piece is well-typed whether or not it is wired — an optional `handedOver` dep left out, a tracker+ * never fed agent events, a `launchesToFire` call without its trailing argument — so the rule could+ * be plumbed end to end and ship INERT on one shell. The behaviour is proven against real code in+ * `core/station-handover.test.ts`, `test/acceptance/after-handover.test.ts` and+ * `server/headless-node-factory.test.ts`.+ */+const read = (rel: string): string =>+ readFileSync(new URL(rel, import.meta.url), 'utf8').replace(/\r\n/g, '\n')+const main = read('./index.ts')+const serverControl = read('../server/canvas-control.ts')+const serverIndex = read('../server/index.ts')+const canvas = read('../renderer/canvas/Canvas.tsx')++describe('desktop main', () => {+ it('feeds the messaging layer\'s hand-over events to the tracker', () => {+ expect(main).toMatch(/messagingDeps\.onHandover = \(ev\) => \{[^}]*stationHandovers\.onHandover\(ev\)/)+ })++ it('feeds every agent event to the tracker BEFORE the messaging queue can flush on it', () => {+ const emit = main.slice(main.indexOf('const emitAgentStatus = ('))+ const tracker = emit.indexOf('stationHandovers.onAgentEvent(enriched)')+ expect(tracker).toBeGreaterThan(-1)+ expect(tracker).toBeLessThan(emit.indexOf('onMessagingAgentEvent(enriched)'))+ })++ it('marks write / run in the finishing step both answers take, from when the request arrived', () => {+ const handler = main.slice(main.indexOf('hookServer.setControlHandler('))+ expect(handler.slice(0, 400)).toContain('const requestAt = Date.now()')+ const finish = handler.slice(handler.indexOf('const finishAnswer = ('))+ const body = finish.slice(0, finish.indexOf('\n }\n'))+ expect(body).toContain('stationHandovers.noteControlAnswer(verb, args, answer, nodeId, requestAt)')+ })++ it('registers the read channel and pushes every change to the window', () => {+ expect(main).toContain('registerStationHandoverIpc(corePlatform, () => stationHandovers)')+ expect(main).toMatch(/new StationHandoverTracker\(\(records\) =>\s*sendToMain\(IPC\.stationHandoverChanged, records\)/)+ })+})++describe('Server Edition', () => {+ it('gives the headless factory the tracker and feeds it the same events', () => {+ expect(serverControl).toContain('handedOver: (nodeId) => stationHandovers.isHandedOver(nodeId)')+ expect(serverControl).toMatch(/onHandover: \(ev\) => \{[^}]*stationHandovers\.onHandover\(ev\)/)+ const on = serverControl.slice(serverControl.indexOf('onAgentEvent: (event) => {'))+ const tracker = on.indexOf('stationHandovers.onAgentEvent(event)')+ expect(tracker).toBeGreaterThan(-1)+ expect(tracker).toBeLessThan(on.indexOf('onMessagingAgentEvent(event, queue)'))+ expect(tracker).toBeLessThan(on.indexOf('factory.onAgentEvent(event)'))+ expect(serverControl).toContain(+ 'stationHandovers.noteControlAnswer(req.verb, req.args, reply, req.nodeId, requestAt)'+ )+ expect(serverIndex).toContain('registerStationHandoverIpc(platform, () => canvasControl?.stationHandovers ?? null)')+ })+})++describe('renderer', () => {+ it('installs the mirror and passes it to the launch loop and to list', () => {+ expect(canvas).toContain('installStationHandoverWiring(window.nodeTerminal)')+ const call = canvas.slice(canvas.indexOf('const ready = launchesToFire('))+ expect(call.slice(0, call.indexOf('.filter('))).toContain('useStationHandovers.getState().byId')+ expect(canvas).toContain('armedHandoverSig')+ expect(canvas.match(/useStationOutcomes\.getState\(\)\.byId, useStationHandovers\.getState\(\)\.byId\)/g)).toHaveLength(2)+ })+})diff --git a/src/main/station-outcome-wiring.test.ts b/src/main/station-outcome-wiring.test.tsindex 8b3351415..8f883a2bf 100644--- a/src/main/station-outcome-wiring.test.ts+++ b/src/main/station-outcome-wiring.test.ts@@ -46,7 +46,7 @@ describe('desktop main', () => {})it('wires the messaging layer\'s hand-over events — send / reply are decided by when they LAND', () => {- expect(main).toContain('messagingDeps.onHandover = (ev) => stationOutcomes.onHandover(ev)')+ expect(main).toMatch(/messagingDeps\.onHandover = \(ev\) => \{\s*stationOutcomes\.onHandover\(ev\)/)})it('registers the read channel and pushes every change to the window', () => {@@ -65,7 +65,7 @@ describe('Server Edition', () => {})it('wires the same hand-over events into its messaging deps', () => {- expect(serverControl).toContain('onHandover: (ev) => stationOutcomes.onHandover(ev)')+ expect(serverControl).toMatch(/onHandover: \(ev\) => \{\s*stationOutcomes\.onHandover\(ev\)/)})it('hands the factory the outcome store, so --after-success is honoured headlessly', () => {@@ -124,7 +124,7 @@ describe('the desktop renderer', () => {})it('list reads the outcomes on both the live and the stored path', () => {- const hits = canvas.split('useStationOutcomes.getState().byId)').length - 1+ const hits = canvas.split('useStationOutcomes.getState().byId, useStationHandovers.getState().byId)').length - 1expect(hits).toBeGreaterThanOrEqual(2)})})diff --git a/src/preload/index.ts b/src/preload/index.tsindex c9becea18..7c8ae216f 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -877,6 +877,14 @@ const api: NodeTerminalApi = {ipcRenderer.on(IPC.stationOutcomeChanged, handler)return () => ipcRenderer.removeListener(IPC.stationOutcomeChanged, handler)}+ },+ stationHandover: {+ list: () => ipcRenderer.invoke(IPC.stationHandoverList),+ onChanged: (cb) => {+ const handler = (_e: unknown, records: Parameters<typeof cb>[0]) => cb(records)+ ipcRenderer.on(IPC.stationHandoverChanged, handler)+ return () => ipcRenderer.removeListener(IPC.stationHandoverChanged, handler)+ }}}diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.tsindex 882daeeff..7100856a0 100644--- a/src/renderer/bridge/relay-api.ts+++ b/src/renderer/bridge/relay-api.ts@@ -194,6 +194,7 @@ export function buildRelayApi(// tab's nodes live in the host's core, whose notices are the host's renderer's to draw.stationNotice: stub.stationNotice,stationOutcome: stub.stationOutcome,+ stationHandover: stub.stationHandover,// The mirror identity seed is a deliberate no-op here: a relay tab's nodes belong to the HOST's// core, whose mirror is seeded by the host's own renderer from its own localStorage. This// machine's localStorage holds no identity for them, and `...local` would plant this machine'sdiff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 79a0978be..e6b8c601d 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -594,6 +594,11 @@ export function buildStubApi(): Omit<stationOutcome: {list: async () => [],onChanged: noopUnsub+ },+ // Same split again: the Server Edition overrides it (`buildStationHandoverApi`).+ stationHandover: {+ list: async () => [],+ onChanged: noopUnsub}} satisfies Omit<NodeTerminalApi,diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 46946072e..3df73ebe4 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -72,6 +72,7 @@ import type { PaneOwner } from '../../shared/agents/pane-owner-predicate'import { buildStubApi, unsupported } from './stubs'import { sanitizeStationNotices } from '@shared/station-notice'import { sanitizeOutcomeRecords } from '@shared/station-outcome'+import { sanitizeHandoverRecords } from '@shared/station-handover'import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'import { encodePcmForWire } from './speech-encode'import { type FrameTransport, WebSocketFrameTransport } from './frame-transport'@@ -698,7 +699,24 @@ export function buildStationNoticeApi(client: RpcClient): Pick<NodeTerminalApi,* The Server Edition's station task outcomes — REAL, for the same reason as station notices: the* server's canvas-control runtime records `report-outcome` and honours `--after-success` headlessly,* and a browser tab's QUEUED badge and `list` must say what the server knows. Kept out of- * `buildAgentApi`, which relay tabs share.+ * `buildAgentApi`, which relay tabs share. The hand-over list (src/core/station-handover.ts) is real+ * for the same reason: the server's headless factory honours plain `--after` with it, and `list`+ * names it.+ */+export function buildStationHandoverApi(client: RpcClient): Pick<NodeTerminalApi, 'stationHandover'> {+ return {+ stationHandover: {+ list: () =>+ (client.request(IPC.stationHandoverList) as Promise<unknown>).then(sanitizeHandoverRecords, () => []),+ onChanged: (cb) =>+ client.subscribe(IPC.stationHandoverChanged, ((records: unknown) =>+ cb(sanitizeHandoverRecords(records))) as Listener)+ }+ }+}++/**+ * The Server Edition's station task outcomes — the real bridge, see `buildStationHandoverApi`'s note.*/export function buildStationOutcomeApi(client: RpcClient): Pick<NodeTerminalApi, 'stationOutcome'> {return {@@ -1234,6 +1252,7 @@ export async function installWsBridge(): Promise<boolean> {...buildAgentApi(client),...buildStationNoticeApi(client),...buildStationOutcomeApi(client),+ ...buildStationHandoverApi(client),...buildCanvasApi(client),...buildPresenceApi(client),...buildSpeechApi(client),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex e2152bd09..dc1aff573 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -551,6 +551,8 @@ import {} from '@shared/station-outcome'import { useStationOutcomes } from '../state/stationOutcomes'import { installStationOutcomeWiring } from '../lib/stationOutcomeWiring'+import { useStationHandovers } from '../state/stationHandovers'+import { installStationHandoverWiring } from '../lib/stationHandoverWiring'import { lookupPullRequests, pullBoardFor, useGitHubIssues } from '../state/githubIssues'import { usePullChase } from '../components/kanban/usePullAutoMove'import {@@ -2040,6 +2042,21 @@ export function Canvas() {}return sig})+ // ---- work handed to the stations an armed node waits on (plain `--after`) ----+ // A station handed new work it has not finished (core/station-handover.ts) is never a satisfied+ // dep, whatever its state reads. A PRIMITIVE signature over the armed nodes' deps only — the+ // `armedDepSig` discipline — so the launch effect re-runs when one of THOSE stations finishes its+ // new work, and nothing re-renders on another station's hand-over.+ const armedHandoverSig = useStationHandovers((s) => {+ let sig = ''+ for (const n of nodesRef.current) {+ const p = n.data.pendingLaunch+ if (!p) continue+ for (const d of p.after) if (s.byId[d]) sig += `${d},`+ sig += '|'+ }+ return sig+ })// ---- the setup gate an armed node waits on ----// The runs are launched from the worktree-lifecycle block far below; the gate itself lives up// here, beside the launch effect that reads it.@@ -2251,7 +2268,9 @@ export function Canvas() {// The `--after-pr` gate: this canvas's pull request status and the clock its deadlines are on.{ board: pullBoardFor(useGitHubIssues.getState(), nodesProjectIdRef.current ?? ''), now: Date.now() },// The `--after-success` gate: every station's latest task report (core's store, mirrored).- { outcomes: useStationOutcomes.getState().byId, now: Date.now() }+ { outcomes: useStationOutcomes.getState().byId, now: Date.now() },+ // Stations handed new work they have not finished: their `done` is the previous task's.+ useStationHandovers.getState().byId).filter((f) => !launchInFlight.current.has(f.id))// Anything we were reporting on that is no longer an armed node — delivered, run by hand with// ▶, or deleted — stops being reported. Timers go with it: a stall warning for a node that has@@ -2342,8 +2361,8 @@ export function Canvas() {return deliverHeld()})}- // eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/armedSetupSig/armedPrSig/armedSuccessSig/launchNudge are the triggers- }, [nodes, armedDepSig, armedSetupSig, armedPrSig, armedSuccessSig, launchNudge])+ // eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/armedHandoverSig/armedSetupSig/armedPrSig/armedSuccessSig/launchNudge are the triggers+ }, [nodes, armedDepSig, armedHandoverSig, armedSetupSig, armedPrSig, armedSuccessSig, launchNudge])// Selection state for ephemeral nodes (they live outside React Flow's managed nodes), owned by// the agent-nodes store so the cards themselves can set it — see `selectable: false` below.@@ -10279,6 +10298,7 @@ export function Canvas() {useEffect(() => installStationNoticeWiring(window.nodeTerminal), [])// Station task outcomes (`report-outcome`): core's store mirrored for the `--after-success` gate.useEffect(() => installStationOutcomeWiring(window.nodeTerminal), [])+ useEffect(() => installStationHandoverWiring(window.nodeTerminal), [])// Session board cards are derived LIVE from the canvas nodes; the board stores only assignments.// Only while the board is OPEN: `nodes` gets a fresh identity on every drag frame, so a closed@@ -11962,7 +11982,7 @@ export function Canvas() {return}if (!needsLiveCanvas(verb)) {- const rows = storedNodeListing(projects.find((p) => p.id === route.projectId)?.nodes ?? [], useAgentStatus.getState().byId, useLaunchDelivery.getState().byId, Date.now(), useStationOutcomes.getState().byId)+ const rows = storedNodeListing(projects.find((p) => p.id === route.projectId)?.nodes ?? [], useAgentStatus.getState().byId, useLaunchDelivery.getState().byId, Date.now(), useStationOutcomes.getState().byId, useStationHandovers.getState().byId)reply({ok: true,result: rows,@@ -12675,7 +12695,7 @@ export function Canvas() {id: n.id, kind: n.type, title: n.data.title as string,pendingLaunch: n.data.pendingLaunch, agentId: n.data.agentId as string | undefined,issueRef: n.data.issueRef- })), st, useLaunchDelivery.getState().byId, Date.now(), useStationOutcomes.getState().byId)+ })), st, useLaunchDelivery.getState().byId, Date.now(), useStationOutcomes.getState().byId, useStationHandovers.getState().byId)reply({ ok: true, result: list, message: controlListingText(list) })return}diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.tsindex 076aadfa1..50d31e912 100644--- a/src/renderer/lib/controlRouting.test.ts+++ b/src/renderer/lib/controlRouting.test.ts@@ -353,6 +353,27 @@ describe('storedNodeListing', () => {})})+describe('storedNodeListing — a dependent held by work handed to its station (core/station-handover.ts)', () => {+ it('names the station whose `done` is from before the work just handed to it', () => {+ const nodes = [+ { id: 'st', kind: 'terminal', title: 'Builder', agentId: 'claude' },+ { id: 'd', kind: 'terminal', title: 'Reviewer', agentId: 'claude', pendingLaunch: { after: ['st'], command: 'claude go' } },+ // Hostile shapes are read, never thrown on.+ { id: 'bad', kind: 'terminal', title: 'Bad', pendingLaunch: { after: 'st', command: 'x' } }+ ]+ const statuses = { st: { state: 'done' as const }, d: {}, bad: {} }+ const handovers = { st: { nodeId: 'st', since: 5 } }+ const rows = storedNodeListing(nodes, statuses, {}, 0, {}, handovers)+ expect(rows[1]).toMatchObject({ launchState: 'queued', handoverWait: 'st "Builder"' })+ expect(rows[2]).not.toHaveProperty('handoverWait')+ expect(controlListingText(rows).split('\n')[1]).toBe(+ 'd [terminal] Reviewer — QUEUED — waiting for st "Builder" to finish the work handed to it'+ )+ // Nothing handed over: the row is what it always was.+ expect(storedNodeListing(nodes, statuses, {}, 0, {}, {})[1]).not.toHaveProperty('handoverWait')+ })+})+describe('the off-screen disposition table (the verbs that used to travel)', () => {it('the verbs that act on existing nodes are answered from the store, not by travelling', () => {// The field report: the user was typing in another project, a background agent issued adiff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.tsindex 9db4cf9f5..dcc1d1c0d 100644--- a/src/renderer/lib/controlRouting.ts+++ b/src/renderer/lib/controlRouting.ts@@ -24,7 +24,14 @@ import {type StationOutcomeRecord} from '@shared/station-outcome'import { prHoldExpired } from './prWait'-import { controlLaunchState, successDepFacts, type LaunchDelivery, type StatusById } from './pendingLaunch'+import {+ controlLaunchState,+ handedOverDeps,+ successDepFacts,+ type HandoverById,+ type LaunchDelivery,+ type StatusById+} from './pendingLaunch'import { projectTravel } from './presenceTravel'import {projectCapabilityGrantedFor,@@ -187,7 +194,9 @@ export function storedNodeListing(deliveries: Record<string, LaunchDelivery | undefined> = {},now: number = Date.now(),/** Every station's latest task report (`report-outcome`, core's store mirrored). */- outcomes: Readonly<Record<string, StationOutcomeRecord>> = {}+ outcomes: Readonly<Record<string, StationOutcomeRecord>> = {},+ /** Stations with unfinished handed-over work (core/station-handover.ts, mirrored). */+ handovers: HandoverById = {}) {const live = new Set(nodes.map((n) => n.id))const titleOf = (id: string): string => {@@ -207,7 +216,7 @@ export function storedNodeListing((n.pendingLaunch as { afterSuccess?: unknown } | undefined)?.afterSuccess)const successFacts = (d: string) =>- successDepFacts(d, statuses, live, outcomes)+ successDepFacts(d, statuses, live, outcomes, handovers)const successState = successHold ? successWaitStatus(successHold, successFacts, now) : undefinedconst launchState = controlLaunchState(!!n.pendingLaunch, deliveries[n.id] ?? ((n.pendingLaunch as { manualOnly?: boolean } | undefined)?.manualOnly ? { kind: 'failed', attempts: 1, at: 0 } : undefined), status, prExpired, successState) ??(n.agentId && !status?.state ? 'unconfirmed' as const : undefined)@@ -221,6 +230,25 @@ export function storedNodeListing(successHold && !successHold.invalid && successState !== 'met'? successWaitSummary(successHold, successFacts, titleOf): undefined+ // Plain `--after` deps whose `done` is from BEFORE the work just handed to them: named, so an+ // orchestrator reading QUEUED next to a station that reads idle knows what it is waiting for.+ // (`pendingLaunch` is unvalidated here: only a list of strings is read.)+ const rawAfter = (n.pendingLaunch as { after?: unknown } | undefined)?.after+ const handedOver = Array.isArray(rawAfter)+ ? handedOverDeps(+ {+ id: n.id,+ data: {+ pendingLaunch: {+ after: rawAfter.filter((d): d is string => typeof d === 'string'),+ command: ''+ }+ }+ },+ live,+ handovers+ )+ : []return {id: n.id, kind: n.kind ?? 'terminal', title: n.title ?? '',...(issue ? { issue } : {}),@@ -228,6 +256,7 @@ export function storedNodeListing(...(launchState ? { launchState } : {}),...(launchState === 'queued' && prHold && !prHold.invalid ? { prWait: formatPrWaits(prHold) } : {}),...(successWait ? { successWait } : {}),+ ...(handedOver.length ? { handoverWait: handedOver.map(titleOf).join(', ') } : {}),...(reported? {outcome: reported.outcome,@@ -260,6 +289,7 @@ export function controlListingText(rows: ReturnType<typeof storedNodeListing>):(n.launchState ? ` — ${launchLabels[n.launchState]}` : '') +(n.prWait ? ` — waits on ${n.prWait}` : '') +(n.successWait ? ` — needs success from: ${n.successWait}` : '') ++ (n.handoverWait ? ` — waiting for ${n.handoverWait} to finish the work handed to it` : '') +(n.outcome ? ` — REPORTED ${n.outcome === 'succeeded' ? 'SUCCESS' : 'FAILURE'}${n.outcomeNote ? ` ("${n.outcomeNote}")` : ''}` : '') +(n.outcomeSuperseded ? ' (before new work queued for it; not counted until it reports again)' : '') +(n.lastTurnErrored ? ' — LAST TURN ERRORED' : '')diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.tsindex 159a956ae..896ba4b9b 100644--- a/src/renderer/lib/pendingLaunch.test.ts+++ b/src/renderer/lib/pendingLaunch.test.ts@@ -13,6 +13,7 @@ import {successDepFacts,withLaunchBrief,launchBriefPresent,+ handedOverDeps,type ArmedNode,type StatusById} from './pendingLaunch'@@ -554,6 +555,52 @@ describe('--after-success: a success wait is a fourth gate — the turn ending i})})+describe('plain --after on a station handed new work (core/station-handover.ts)', () => {+ const live = new Set(['a', 'b', 'c'])+ const status: StatusById = { a: { state: 'done' }, b: { state: 'done' } }+ const handovers = { a: { nodeId: 'a', since: 10 } }++ it('a handed-over station is never a satisfied dep, whatever its state reads', () => {+ expect(launchesToFire([armed('c', ['a', 'b'])], status, live, undefined, undefined, undefined, undefined, handovers)).toEqual([])+ expect(unmetDeps(armed('c', ['a', 'b']), status, live, handovers)).toEqual(['a'])+ expect(handedOverDeps(armed('c', ['a', 'b']), live, handovers)).toEqual(['a'])+ })++ it('without a hand-over the same state fires as before', () => {+ expect(launchesToFire([armed('c', ['a', 'b'])], status, live, undefined, undefined, undefined, undefined, {})).toEqual([+ { id: 'c', command: 'echo c' }+ ])+ })++ it('a deleted station still counts as satisfied, hand-over or not', () => {+ expect(launchesToFire([armed('c', ['a'])], {}, new Set(['c']), undefined, undefined, undefined, undefined, handovers)).toEqual([+ { id: 'c', command: 'echo c' }+ ])+ expect(handedOverDeps(armed('c', ['a']), new Set(['c']), handovers)).toEqual([])+ })++ it('a success wait on a handed-over station holds: its turn is not over', () => {+ expect(successDepFacts('a', status, live, {}, handovers).turnDone).toBe(false)+ expect(successDepFacts('a', status, live, {}).turnDone).toBe(true)+ })++ it('a prototype key is not a hand-over', () => {+ const bare = Object.create(null) as Record<string, undefined>+ expect(handedOverDeps(armed('c', ['constructor', '__proto__']), new Set(['constructor', '__proto__']), bare)).toEqual([])+ expect(handedOverDeps(armed('c', ['constructor']), new Set(['constructor']), {})).toEqual([])+ })++ it('the tooltip says what the wait is for, not "waiting for X to finish" about an idle X', () => {+ const text = launchTooltip(undefined, 'Builder, Tester', 'claude go', undefined, false, undefined, undefined, 'Builder')+ expect(text).toBe(+ 'Waiting for Builder to finish the work just handed to it — its earlier turn does not count ' ++ '(all waits: Builder, Tester), then runs:\nclaude go'+ )+ // An errored upstream is still named first: it will not end on its own.+ expect(launchTooltip(undefined, 'Builder', 'claude go', 'Tester', false, undefined, undefined, 'Builder')).toMatch(/^Tester ended/)+ })+})+describe('withSuccessHold — the sibling of withPrHold', () => {const hold = { deps: ['a'], deadlineAt: 9 }it('adds the hold to a node that already holds its launch, and only then', () => {diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.tsindex 21bdc1862..a5801f1e8 100644--- a/src/renderer/lib/pendingLaunch.ts+++ b/src/renderer/lib/pendingLaunch.ts@@ -15,6 +15,7 @@ import {type SuccessWaitHold} from '@shared/station-outcome'import type { PendingLaunch } from '@shared/types'+import type { StationHandoverRecord } from '@shared/station-handover'import { prHoldSatisfied } from './prWait'/** The subset of a canvas node this module reads. */@@ -57,6 +58,17 @@ export interface PrGateContext {now: number}+/**+ * Stations with unfinished HANDED-OVER work (core/station-handover.ts, mirrored): a station here is+ * never a satisfied `--after` dep, whatever its state reads — its `done` is from before the work it+ * was just handed. Absent = nothing handed over.+ */+export type HandoverById = Readonly<Record<string, StationHandoverRecord | undefined>>++function handedOver(handovers: HandoverById | undefined, depId: string): boolean {+ return !!handovers && Object.prototype.hasOwnProperty.call(handovers, depId) && !!handovers[depId]+}+/** What `launchesToFire` needs to judge a `--after-success` wait: every station's latest task* report in this app run (core's store, mirrored) and the clock deadlines are on. */export interface SuccessGateContext {@@ -73,13 +85,14 @@ export function successDepFacts(depId: string,status: StatusById,live: ReadonlySet<string>,- outcomes: Readonly<Record<string, StationOutcomeRecord>>+ outcomes: Readonly<Record<string, StationOutcomeRecord>>,+ handovers?: HandoverById): SuccessDepFacts {const exists = live.has(depId)const reported = outcomeOf(outcomes, depId)return {exists,- turnDone: exists && depSatisfied(depId, status, live),+ turnDone: exists && depSatisfied(depId, status, live, handovers),...(reported ? { outcome: reported } : {})}}@@ -212,13 +225,36 @@ export function controlLaunchState(** The refusal ends by itself: `lastTurnError` is cleared by the upstream's next genuine new turn,* so a station that is nudged and answers successfully satisfies its dependents on that turn.+ *+ * A dep that has been HANDED NEW WORK it has not finished (`handovers`, core/station-handover.ts)+ * is refused too. A station is reused: an orchestrator hands it its next task and then arms a+ * dependent on it, and until the station starts that task its state is still the PREVIOUS task's+ * `done` — the dependent would start at once, on the old output. Core decides when the hand-over+ * is answered (a turn that started after it has ended); here it is only a membership test, so the+ * renderer and the Server Edition's factory cannot disagree.*/-function depSatisfied(depId: string, status: StatusById, live: ReadonlySet<string>): boolean {+function depSatisfied(+ depId: string,+ status: StatusById,+ live: ReadonlySet<string>,+ handovers?: HandoverById+): boolean {if (!live.has(depId)) return true+ if (handedOver(handovers, depId)) return falseconst st = status[depId]return st?.state === 'done' && !st.lastTurnError}+/** Of the deps this node is still waiting on, which are held because they were handed new work+ * they have not finished — what the QUEUED tooltip and `list` name. */+export function handedOverDeps(+ node: ArmedNode,+ live: ReadonlySet<string>,+ handovers: HandoverById | undefined+): string[] {+ return (node.data.pendingLaunch?.after ?? []).filter((d) => live.has(d) && handedOver(handovers, d))+}+/** Of the deps this node is still waiting on, which are held because they ERRORED rather than* because they have not finished? What the QUEUED tooltip names (issue #521). */export function erroredDeps(@@ -254,7 +290,9 @@ export function launchesToFire(setupDone?: (groupId: string) => boolean,deliveries?: Record<string, LaunchDelivery | undefined>,pr?: PrGateContext,- success?: SuccessGateContext+ success?: SuccessGateContext,+ /** Stations with unfinished handed-over work — never a satisfied dep (see `depSatisfied`). */+ handovers?: HandoverById): LaunchToFire[] {const out: LaunchToFire[] = []for (const n of nodes) {@@ -281,13 +319,13 @@ export function launchesToFire(success &&successWaitSatisfied(successHold,- (d) => successDepFacts(d, status, live, success.outcomes),+ (d) => successDepFacts(d, status, live, success.outcomes, handovers),success.now)))continue- if (p.after.every((d) => depSatisfied(d, status, live))) {+ if (p.after.every((d) => depSatisfied(d, status, live, handovers))) {out.push({ id: n.id, command: p.command, ...(p.promptFile ? { briefFile: p.promptFile } : {}) })}}@@ -298,11 +336,12 @@ export function launchesToFire(export function unmetDeps(node: ArmedNode,status: StatusById,- live: ReadonlySet<string>+ live: ReadonlySet<string>,+ handovers?: HandoverById): string[] {const p = node.data.pendingLaunchif (!p) return []- return p.after.filter((d) => !depSatisfied(d, status, live))+ return p.after.filter((d) => !depSatisfied(d, status, live, handovers))}/**@@ -367,7 +406,9 @@ export function launchTooltip(pr?: { expired: boolean; summary: string; deadline: string },/** The node's `--after-success` wait: where it stands (`successWaitStatus`), the unmet stations* (`successWaitSummary`), and its deadline as the caller formats it. */- success?: { status: 'met' | 'waiting' | 'blocked' | 'expired'; summary: string; deadline: string }+ success?: { status: 'met' | 'waiting' | 'blocked' | 'expired'; summary: string; deadline: string },+ /** The deps that were handed new work they have not finished (core/station-handover.ts), named. */+ handedOverOn?: string): string {if (delivery?.kind === 'starting') return 'Starting in the background — an agent asked for this session to run now.'const runs = `Runs:\n${command}`@@ -422,6 +463,13 @@ export function launchTooltip('fires as soon as it does.\n' +`Press \u25b6 to try it now.\n${runs}`)+ // A station that just got new work still reads `done` from its previous task; saying "waiting for+ // X to finish" alone would read as a wait that should already be over.+ if (handedOverOn)+ return (+ `Waiting for ${handedOverOn} to finish the work just handed to it — its earlier turn does not ` ++ `count${waitingOn ? ` (all waits: ${waitingOn})` : ''}, then runs:\n${command}`+ )if (success?.status === 'waiting') {// `waitingOn` here is the caller's list of the OTHER stations (plain `--after`), if any.const stations = waitingOn ? `${waitingOn} to finish and for ` : ''diff --git a/src/renderer/lib/stationHandoverWiring.ts b/src/renderer/lib/stationHandoverWiring.tsnew file mode 100644index 000000000..65229d75f--- /dev/null+++ b/src/renderer/lib/stationHandoverWiring.ts@@ -0,0 +1,32 @@+/**+ * Mirror core's hand-over tracker (src/core/station-handover.ts) into `useStationHandovers`: the+ * initial pull (a push that fired before this renderer loaded is otherwise lost) and every later+ * push. Nothing flows the other way — a hand-over is observed by core, never declared here.+ *+ * Installed once, on the app's own api (`window.nodeTerminal`), like the station-outcome wiring.+ */+import type { NodeTerminalApi } from '@shared/types'+import { sanitizeHandoverRecords } from '@shared/station-handover'+import { useStationHandovers } from '../state/stationHandovers'++export function installStationHandoverWiring(api: Pick<NodeTerminalApi, 'stationHandover'>): () => void {+ const set = (raw: unknown): void =>+ useStationHandovers.getState().setRecords(sanitizeHandoverRecords(raw))+ let live = true+ // A push is always newer than the initial pull; a pull that resolves after one must not undo it.+ let pushed = false+ void api.stationHandover+ .list()+ .then((records) => {+ if (live && !pushed) set(records)+ })+ .catch(() => undefined)+ const off = api.stationHandover.onChanged((records) => {+ pushed = true+ set(records)+ })+ return () => {+ live = false+ off()+ }+}diff --git a/src/renderer/lib/useSuccessWait.ts b/src/renderer/lib/useSuccessWait.tsindex cbf8226b8..4fca8986b 100644--- a/src/renderer/lib/useSuccessWait.ts+++ b/src/renderer/lib/useSuccessWait.ts@@ -23,6 +23,7 @@ import {} from '@shared/station-outcome'import { useAgentStatus } from '../state/agentStatus'import { useStationOutcomes } from '../state/stationOutcomes'+import { useStationHandovers } from '../state/stationHandovers'import { successDepFacts } from './pendingLaunch'export interface SuccessWaitView {@@ -54,6 +55,8 @@ export function useSuccessWait(const stateSig = useAgentStatus((s) =>depIds.map((d) => `${d}:${s.byId[d]?.state ?? '-'}:${s.byId[d]?.lastTurnError ? 'e' : ''}`).join('|'))+ // Handed-over work holds a station's turn open (core/station-handover.ts), like the launch loop.+ const handoverSig = useStationHandovers((s) => depIds.map((d) => (s.byId[d] ? '1' : '0')).join(''))// Which stations are still on the canvas, read each render: a closed station changes the verdict.const existSig = depIds.map((d) => (titleOf(d) !== undefined ? '1' : '0')).join('')// The deadline tick. Its VALUE is a memo input — see the header.@@ -70,7 +73,13 @@ export function useSuccessWait(if (!hold) return undefinedconst live = new Set(depIds.filter((d) => titleOf(d) !== undefined))const facts = (d: string) =>- successDepFacts(d, useAgentStatus.getState().byId, live, useStationOutcomes.getState().byId)+ successDepFacts(+ d,+ useAgentStatus.getState().byId,+ live,+ useStationOutcomes.getState().byId,+ useStationHandovers.getState().byId+ )const name = (d: string) => titleOf(d) || dreturn {status: successWaitStatus(hold, facts, Date.now()),@@ -80,6 +89,6 @@ export function useSuccessWait(: new Date(hold.deadlineAt).toLocaleString()}// eslint-disable-next-line react-hooks/exhaustive-deps -- the signatures and the clock are the triggers- }, [hold, outcomeSig, stateSig, existSig, clock])+ }, [hold, outcomeSig, stateSig, handoverSig, existSig, clock])return { hold, depIds, tooltip }}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 2f3bb3dd6..9f9364f0f 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -234,7 +234,8 @@ import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../staimport { codexApprovalCaps } from '../state/codexCli'import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'import { useLaunchDelivery } from '../state/launchDelivery'-import { erroredDeps, launchTooltip } from '../lib/pendingLaunch'+import { erroredDeps, handedOverDeps, launchTooltip } from '../lib/pendingLaunch'+import { useStationHandovers } from '../state/stationHandovers'import { useSuccessWait } from '../lib/useSuccessWait'import { StationFailedChip } from '../components/StationFailedChip'import { prHoldExpired, prHoldSummary } from '../lib/prWait'@@ -2122,6 +2123,20 @@ export function TerminalNode({const successTooltip = successWait.tooltipconst successExpired = successTooltip?.status === 'expired'const successBlocked = successTooltip?.status === 'blocked'+ // Which deps were handed new work they have not finished (core/station-handover.ts): their `done`+ // is from before it, so the tooltip says what the wait is really for. A primitive, like above.+ const handedOverDepIds = useStationHandovers((s) => {+ const after = pendingLaunch?.after ?? []+ if (!after.length) return ''+ const live = new Set(after.filter((d) => !!getNode(d)))+ return handedOverDeps({ id, data: { pendingLaunch } }, live, s.byId).join(',')+ })+ const pendingHandedOverOn = handedOverDepIds+ ? handedOverDepIds+ .split(',')+ .map((depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId)+ .join(', ')+ : undefinedconst pendingErroredOn = erroredDepIds? erroredDepIds.split(',')@@ -6009,7 +6024,7 @@ export function TerminalNode({? ' term-node__status--queued-warn': ''}`}- title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip, successTooltip)}+ title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay', prTooltip, successTooltip, pendingHandedOverOn)}><span className="term-node__status-dot" />{startingNowdiff --git a/src/renderer/state/stationHandovers.ts b/src/renderer/state/stationHandovers.tsnew file mode 100644index 000000000..e86f22e77--- /dev/null+++ b/src/renderer/state/stationHandovers.ts@@ -0,0 +1,27 @@+/**+ * Which stations have unfinished HANDED-OVER work — a MIRROR of core's tracker+ * (src/core/station-handover.ts), replaced whole on every push, never edited here. Core decides what+ * a hand-over is and when it ends; the renderer reads it for the plain `--after` gate+ * (`launchesToFire`), the QUEUED tooltip and `list`.+ *+ * Transient: core re-sends the list on request after a reload, and after an app restart there is+ * nothing to send — no work has been handed over in this run.+ */+import { create } from 'zustand'+import type { StationHandoverRecord } from '@shared/station-handover'+export { isHandedOver } from '@shared/station-handover'++interface StationHandoversStore {+ byId: Record<string, StationHandoverRecord>+ setRecords(records: readonly StationHandoverRecord[]): void+}++export const useStationHandovers = create<StationHandoversStore>((set) => ({+ byId: Object.create(null) as Record<string, StationHandoverRecord>,+ setRecords: (records) => {+ // No prototype: `__proto__` passes the node-id charset.+ const byId = Object.create(null) as Record<string, StationHandoverRecord>+ for (const r of records) byId[r.nodeId] = r+ set({ byId })+ }+}))diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.tsindex 6580d5393..2cebcbf7b 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -17,6 +17,7 @@ import {clearOutcomesAfterControl,handleReportOutcome} from '../core/station-outcome-store'+import { StationHandoverTracker } from '../core/station-handover'import { stationRecipientFromOwner } from '../shared/station-notice'import {mirrorEntry,@@ -95,6 +96,8 @@ export interface ServerCanvasControl {stationNotices: StationNoticeMonitor/** What each station reported about its own task in THIS server run (`report-outcome`). */stationOutcomes: StationOutcomeStore+ /** Stations with unfinished handed-over work in THIS server run (plain `--after` holds on them). */+ stationHandovers: StationHandoverTrackerinstallSkillInto(configDir: string): voidstop(): void}@@ -187,6 +190,11 @@ export async function initServerCanvasControl(const stationOutcomes = new StationOutcomeStore((records) =>platform().broadcast(IPC.stationOutcomeChanged, records))+ // 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) =>+ platform().broadcast(IPC.stationHandoverChanged, records)+ )const factory = new HeadlessNodeFactory({workspaceStore: deps.workspaceStore,ptyManager: deps.ptyManager,@@ -203,6 +211,7 @@ export async function initServerCanvasControl(stateOf: nodeState,agentIdOf: (nodeId) => mirrorEntry(nodeId)?.agentId,outcomeOf: (nodeId) => stationOutcomes.get(nodeId),+ handedOver: (nodeId) => stationHandovers.isHandedOver(nodeId),// NOT `workspaceExternalChange`. That channel means "somebody else wrote this file" and the// renderer answers it with `decideExternalChange`, which compares the whole project shell —// and `ropes` is part of it, so every headless spawn (one appended `ctrl-…` rope) read as a@@ -239,7 +248,10 @@ export async function initServerCanvasControl(appendBoardLog: (projectId, entry) => deps.boardLog.append(projectId, entry),// A `send` / `reply` hands a station new work when it REACHES the pane (queued ⇒ "work pending"// until it lands) — the same rule, and the same store method, as the desktop.- onHandover: (ev) => stationOutcomes.onHandover(ev)+ onHandover: (ev) => {+ stationOutcomes.onHandover(ev)+ stationHandovers.onHandover(ev)+ }}const queue = createDeliveryQueue(messaging)messaging.queue = queue@@ -323,17 +335,24 @@ export async function initServerCanvasControl(// rule in core/station-outcome-store.ts, applied on the answer. (`send` / `reply` go through// `messaging.onHandover` above, which knows when a queued message actually lands.)handler: async (req) => {+ // When the request arrived — before `run` typed anything (see core/station-handover.ts).+ const requestAt = Date.now()const reply = await baseHandler(req)clearOutcomesAfterControl(stationOutcomes, req.verb, req.args, reply, req.nodeId)+ stationHandovers.noteControlAnswer(req.verb, req.args, reply, req.nodeId, requestAt)return reply},onAgentEvent: (event) => {+ // The hand-over tracker FIRST: it stamps turn starts and ends, and both the queue flush and+ // the factory's `refreshArmed` below act on this very event.+ stationHandovers.onAgentEvent(event)onMessagingAgentEvent(event, queue)factory.onAgentEvent(event)stationNotices.onAgentEvent(event)},stationNotices,stationOutcomes,+ stationHandovers,installSkillInto,stop: () => {factory.stop()diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.tsindex a7f18bc44..2a9f3a446 100644--- a/src/server/headless-node-factory.test.ts+++ b/src/server/headless-node-factory.test.ts@@ -165,6 +165,8 @@ describe('HeadlessNodeFactory', () => {let codexSharedIdentity: booleanlet codexApprovalValues: { approvalValues: string[] | null }let outcomes: Record<string, StationOutcomeRecord>+ /** Stations with unfinished handed-over work (core/station-handover.ts), as the tracker answers. */+ let handedOver: Set<string>const settings = (): Settings => ({...DEFAULT_SETTINGS,@@ -182,6 +184,7 @@ describe('HeadlessNodeFactory', () => {pty = new FakePty()states = {}outcomes = {}+ handedOver = new Set()published = []removed = []publishedProjects = []@@ -239,6 +242,7 @@ describe('HeadlessNodeFactory', () => {ownership,stateOf: (id) => states[id],outcomeOf: (id) => outcomes[id],+ handedOver: (id) => handedOver.has(id),launchTiming: { quietMs: 0, capMs: 0 },publishNode: (_projectId, node) => published.push(node),publishRemoval: (_projectId, nodeId) => removed.push(nodeId),@@ -1215,6 +1219,64 @@ describe('HeadlessNodeFactory', () => {expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toBeUndefined()})+ describe('plain --after on a station handed new work (core/station-handover.ts)', () => {+ it('does NOT take the creation shortcut on a done from before the hand-over', async () => {+ // The station reads `done` — from its PREVIOUS task — and was just handed the next one.+ states['term-upstream'] = 'done'+ handedOver.add('term-upstream')+ const reply = await factory.openAgent(+ 'term-source',+ { agent: 'claude', prompt: 'consume result', after: 'term-upstream' },+ true+ )+ expect(reply.ok).toBe(true)+ const id = (reply.result as { id: string }).id+ expect(pty.sends).toEqual([])+ expect(reply.result).toMatchObject({ queued: true, queuedIds: [id] })+ // refreshArmed on the same old `done` still holds.+ await factory.refreshArmed()+ expect(pty.sends).toEqual([])+ // The new work's turn ends: the tracker drops the station, and the next done releases D once.+ handedOver.delete('term-upstream')+ factory.onAgentEvent({ nodeId: 'term-upstream', state: 'done' })+ await factory.refreshArmed()+ await factory.refreshArmed()+ expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'consume result'" }])+ })++ it('an already-armed dependent is held by a hand-over that arrives before the station idles', async () => {+ states['term-upstream'] = 'working'+ const reply = await factory.openAgent(+ 'term-source',+ { agent: 'claude', prompt: 'consume result', after: 'term-upstream' },+ true+ )+ const id = (reply.result as { id: string }).id+ handedOver.add('term-upstream')+ states['term-upstream'] = 'done'+ factory.onAgentEvent({ nodeId: 'term-upstream', state: 'done' })+ await factory.refreshArmed()+ expect(pty.sends).toEqual([])+ handedOver.delete('term-upstream')+ await factory.refreshArmed()+ expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'consume result'" }])+ })++ it('a success wait holds too: its turn is not over while handed-over work is unfinished', async () => {+ states['term-upstream'] = 'done'+ outcomes['term-upstream'] = { nodeId: 'term-upstream', outcome: 'succeeded', at: Date.now() }+ handedOver.add('term-upstream')+ const reply = await factory.openAgent(+ 'term-source',+ { agent: 'claude', prompt: 'ship it', 'after-success': 'term-upstream' },+ true+ )+ expect(reply.ok).toBe(true)+ await factory.refreshArmed()+ expect(pty.sends).toEqual([])+ })+ })+describe('--after-success: the dependent waits for a REPORTED success, not a turn ending', () => {const report = (nodeId: string, outcome: 'succeeded' | 'failed', note?: string) => {outcomes[nodeId] = { nodeId, outcome, at: Date.now(), ...(note ? { note } : {}) }diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.tsindex 761811be9..35ef5d994 100644--- a/src/server/headless-node-factory.ts+++ b/src/server/headless-node-factory.ts@@ -124,6 +124,11 @@ export interface HeadlessNodeFactoryDeps {/** A station's latest task report (`report-outcome`, core's store) — what `--after-success` waits* on. Absent = no report is ever known, so a success wait never releases on its own. */outcomeOf?(nodeId: string): StationOutcomeRecord | undefined+ /** Has this station been handed new work (a `send` / `reply` queued or landed, a `run`) that no+ * turn since has finished? core/station-handover.ts — while it has, plain `--after` on it is not+ * satisfied, whatever its state reads: its `done` is the PREVIOUS task's. Absent = nothing is+ * ever handed over (the pre-tracker behaviour). */+ handedOver?(nodeId: string): booleanenv?: Record<string, string | undefined>now?: () => numberpublishNode?: (projectId: string, node: CanvasNodeState) => void@@ -734,6 +739,10 @@ export class HeadlessNodeFactory {return this.deps.now?.() ?? Date.now()}+ private handedOver(depId: string): boolean {+ return this.deps.handedOver?.(depId) === true+ }+/** What a success wait knows about one station, from the same facts this edition's `--after`* reads (the mirror's `done`, the `awaitWorking` fresh-spawn rule), the errored-turn rule (#521,* `lastTurnErrored`, which this edition's plain `--after` does not apply), and its report. */@@ -751,6 +760,7 @@ export class HeadlessNodeFactory {exists &&!this.awaitingFirstWorking.has(depId) &&!this.lastTurnErrored.has(depId) &&+ !this.handedOver(depId) &&state === 'done',...(reported ? { outcome: reported } : {})}@@ -1407,7 +1417,9 @@ export class HeadlessNodeFactory {if (state === 'working') this.awaitingFirstWorking.delete(depId)}const mustWait =- after.some((depId) => afterStates.get(depId) !== 'done') ||+ // A `done` from before new work was handed over is not this wait's `done`+ // (core/station-handover.ts): the creation shortcut must not start the node on it.+ after.some((depId) => afterStates.get(depId) !== 'done' || this.handedOver(depId)) ||(!!successHold &&!successWaitSatisfied(successHold, (d) => this.successFacts(target, d), this.now()))const awaitWorking = after.filter((depId) =>@@ -1717,6 +1729,7 @@ export class HeadlessNodeFactory {const stillExists = project.nodes.some((candidate) => candidate.id === depId)if (!stillExists) return trueif (pending.awaitWorking?.includes(depId)) return false+ if (this.handedOver(depId)) return falsereturn observed?.nodeId === depId? observed.state === 'done': this.deps.stateOf(depId) === 'done'diff --git a/src/server/index.ts b/src/server/index.tsindex 75fdd47b1..6ffd40921 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -53,6 +53,7 @@ import { serverEditionControlHandler } from './control-unsupported'import { initServerCanvasControl, type ServerCanvasControl } from './canvas-control'import { registerStationNoticeIpc } from '../core/agents/station-notice'import { registerStationOutcomeIpc } from '../core/station-outcome-store'+import { registerStationHandoverIpc } from '../core/station-handover'import { refreshNodeTokens } from '../core/agents/node-token-service'import { armServerNodeIdentity } from './node-identity-arm'import { wireServerCodexSharedIdentity } from './codex-shared-identity'@@ -497,6 +498,7 @@ export async function startServer(// Station task outcomes: registered for the same reason — a browser tab's `list` gets "none"// rather than an unknown channel when canvas control is off.registerStationOutcomeIpc(platform, () => canvasControl?.stationOutcomes ?? null)+ registerStationHandoverIpc(platform, () => canvasControl?.stationHandovers ?? null)const { contextTail, geminiContextTail, codexContextTail } = wireAgentStatus(platform, {onEvent: (event) => canvasControl?.onAgentEvent(event)})diff --git a/src/shared/host-control.ts b/src/shared/host-control.tsindex 25ada496c..3d63e05bc 100644--- a/src/shared/host-control.ts+++ b/src/shared/host-control.ts@@ -77,6 +77,8 @@ export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([// Unscoped: every project's station outcomes and their notes. A relay guest bound to one project// must not read another's, and a relay tab's launch loop is refused anyway (its stub is inert).IPC.stationOutcomeList,+ // Same class: which of the host's stations (any project) have work handed to them.+ IPC.stationHandoverList,// The host's settings. `settings:save` is the dangerous half: `modelGateway.baseUrl` is the TRUST// ANCHOR `agent:discover-models` uses to decide whether it may resolve the stored// `${secret:model-gateway-api-key}` (core/agent-env-ipc.ts), so a peer that could save settingsdiff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex aefc0de6d..6af59af90 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -248,6 +248,12 @@ export const IPC = {stationOutcomeList: 'station-outcome:list',/** core → every renderer: the FULL current record list on each change, never a delta. */stationOutcomeChanged: 'station-outcome:changed',+ /** Stations with unfinished HANDED-OVER work (src/core/station-handover.ts): what plain `--after`+ * reads so a `done` from before new work arrived does not release a dependent. invoke: the+ * current list (StationHandoverRecord[]), for a renderer that booted after a push. */+ stationHandoverList: 'station-handover:list',+ /** core → every renderer: the FULL current list on each change, never a delta. */+ stationHandoverChanged: 'station-handover:changed',/** Canvas sync: a client casts its local node mutations here; the core reflector* (src/core/canvas-sync.ts) stamps each with the total order (`seq`) and sends it back out on the* SAME channel to EVERY attached client — the sender included, whose copy is its ack (seediff --git a/src/shared/station-handover.ts b/src/shared/station-handover.tsnew file mode 100644index 000000000..0d43b4aa0--- /dev/null+++ b/src/shared/station-handover.ts@@ -0,0 +1,60 @@+// A station that has been HANDED NEW WORK it has not finished yet — the fact plain `--after` needs+// so it does not release a dependent on a `done` from BEFORE that work arrived.+//+// WHY. `--after <station>` releases a node when the station's turn is over (`done`). A station is+// reused: an orchestrator hands it its next task (`send` / `reply`, `write`, `run`) and then opens a+// dependent `--after <station>` to consume that task's output. Until the station STARTS the new+// task its state is still `done` — from the previous task — so the dependent fired at once, on the+// old output, and a launched dependent cannot un-launch. #1042 closed the same hole for+// `--after-success` (a report stops counting once new work is handed over); this is the plain-turn+// half.+//+// THE RULE (decided in core, `core/station-handover.ts`; this module is only the wire shape): a+// station is "handed over" from the moment new work is queued for it, or lands in its pane, until a+// turn that STARTED at or after that hand-over has ENDED. While it is, `--after` on it is not+// satisfied, whatever its state reads. Everything here errs toward holding — the QUEUED badge's ▶+// and the `run` verb always end a hold by hand.+//+// Core publishes the WHOLE list after every change (never a delta), like station outcomes; the+// renderer mirrors it (`state/stationHandovers.ts`) and the Server Edition's headless factory asks+// the tracker directly. TRANSIENT: after a restart no work has been handed over in this run.++import { isSafeNodeId } from './safe-id'++/** One station with unfinished handed-over work. */+export interface StationHandoverRecord {+ nodeId: string+ /** When the newest hand-over landed (the recording process's clock); absent while the only work+ * handed over is still QUEUED and has not reached the pane. */+ since?: number+ /** A `send` / `reply` is still waiting in the station's queue. */+ queued?: true+}++/** Parse a pushed / pulled list defensively: it crosses a process boundary (and, in the Server+ * Edition, a network one). A malformed entry is dropped, never half-kept. */+export function sanitizeHandoverRecords(raw: unknown): StationHandoverRecord[] {+ if (!Array.isArray(raw)) return []+ const out: StationHandoverRecord[] = []+ for (const e of raw as unknown[]) {+ if (!e || typeof e !== 'object') continue+ const r = e as Record<string, unknown>+ if (typeof r.nodeId !== 'string' || !isSafeNodeId(r.nodeId)) continue+ const since = typeof r.since === 'number' && Number.isFinite(r.since) ? r.since : undefined+ out.push({+ nodeId: r.nodeId,+ ...(since !== undefined ? { since } : {}),+ ...(r.queued === true ? { queued: true as const } : {})+ })+ }+ return out+}++/** Is this station holding unfinished handed-over work? `byId` has no prototype (a node id can be+ * `__proto__`), so an own-property read is all it takes. */+export function isHandedOver(+ byId: Readonly<Record<string, StationHandoverRecord>> | undefined,+ nodeId: string+): boolean {+ return !!byId && Object.prototype.hasOwnProperty.call(byId, nodeId)+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 9eb729bc7..19d629328 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -4141,4 +4141,12 @@ export interface NodeTerminalApi {list(): Promise<import('./station-outcome').StationOutcomeRecord[]>onChanged(cb: (records: import('./station-outcome').StationOutcomeRecord[]) => void): () => void}+ /** Stations with unfinished HANDED-OVER work (src/core/station-handover.ts) — what plain+ * `--after` reads so it never releases on a `done` from before that work arrived. Desktop and+ * Server Edition are real; a relay tab's stations belong to the host's core, so there it is+ * inert (and its launch delivery is refused anyway). */+ stationHandover: {+ list(): Promise<import('./station-handover').StationHandoverRecord[]>+ onChanged(cb: (records: import('./station-handover').StationHandoverRecord[]) => void): () => void+ }}diff --git a/test/acceptance/after-handover.test.ts b/test/acceptance/after-handover.test.tsnew file mode 100644index 000000000..b3c67b86d--- /dev/null+++ b/test/acceptance/after-handover.test.ts@@ -0,0 +1,228 @@+/**+ * Plain `--after` must not fire on a `done` from BEFORE new work was handed over — end to end, across+ * the layers that decide it: the REAL messaging service and delivery queue (`createDeliveryQueue`,+ * which both shells build) emit the hand-over events, core's tracker (src/core/station-handover.ts)+ * turns them and the station's agent events into "handed over", and the RENDERER's real launch+ * decision (`launchesToFire`) reads that list, exactly as Canvas passes it.+ *+ * The orchestrator's scenario: station S is reused. It hands S its next task B, then opens D+ * `--after S`. S still reads `done` from task A (or is still working on A and is about to go+ * `done`), so before this change D fired at once — on A's output, irreversibly.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'+import {+ createDeliveryQueue,+ deliverFromControl,+ onMessagingAgentEvent,+ type AgentMessagingDeps+} from '../../src/core/agents/agent-messaging'+import { resetMessageFlow } from '../../src/core/agents/agent-message-flow'+import { resetAgentMessageTraceForTests } from '../../src/core/agents/agent-message-trace'+import { MANAGED_SCRIPT_REVISION } from '../../src/core/agents/hooks/managed-script'+import type { MirrorEntry } from '../../src/core/agent-status-mirror'+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'++interface Harness {+ deps: AgentMessagingDeps+ tracker: StationHandoverTracker+ /** What the renderer's mirror holds (`useStationHandovers.byId`), fed by the tracker's pushes. */+ mirror: () => Record<string, StationHandoverRecord>+ state: Record<string, AgentState | undefined>+ tick(ms: number): number+ sent: string[]+ /** An agent event, fed the way both shells do: tracker FIRST, then the messaging queue. */+ event(state: AgentState): void+}++function harness(): Harness {+ let clock = 1_000_000+ const sent: string[] = []+ let byId: Record<string, StationHandoverRecord> = Object.create(null)+ const tracker = new StationHandoverTracker(+ (records) => {+ byId = Object.create(null)+ for (const r of records) byId[r.nodeId] = r+ },+ () => clock+ )+ const state: Record<string, AgentState | undefined> = { st: 'working' }+ const h: Harness = {+ tracker,+ mirror: () => byId,+ state,+ sent,+ tick: (ms) => (clock += ms),+ event: () => undefined,+ deps: undefined as unknown as AgentMessagingDeps+ }+ const entry = (): MirrorEntry => ({+ state: state.st === 'done' ? 'done' : 'working',+ updatedAt: 1,+ stateVerified: true,+ clientRevision: MANAGED_SCRIPT_REVISION+ })+ h.deps = {+ paneOwner: async () => ({+ tty: '/dev/pts/9',+ panePid: 100,+ paneId: '%1',+ command: 'claude',+ argv: ['claude'],+ pids: [200]+ }),+ sendEnvelope: async (_nodeId, payload) => {+ sent.push(payload)+ return true+ },+ hasLiveSession: () => true,+ mirrorEntry: () => entry(),+ projects: () => [+ {+ id: 'p1',+ nodes: [+ { id: 'orch', title: 'Orchestrator', agentId: 'claude' },+ { id: 'st', title: 'Station', agentId: 'claude' }+ ]+ }+ ],+ isRemoteNode: () => false,+ messagingEnabled: () => true,+ paneOwnerProject: () => 'p1',+ customAgents: () => undefined,+ appendBoardLog: async () => false,+ subscribeReceipts: (cb) => {+ const t = setTimeout(() => cb({ nodeId: 'st', newTurn: true, verified: true }), 1)+ return () => clearTimeout(t)+ },+ now: () => clock,+ // THE WIRING UNDER TEST — exactly what both shells assign (beside the outcome store).+ onHandover: (ev) => tracker.onHandover(ev)+ }+ h.event = (s) => {+ h.tick(10)+ state.st = s+ tracker.onAgentEvent({ nodeId: 'st', state: s })+ if (h.deps.queue)+ onMessagingAgentEvent({ nodeId: 'st', state: s, verified: true, newTurn: false } as never, h.deps.queue)+ }+ return h+}++const send = { verb: 'send', sourceNodeId: 'orch', targetNodeId: 'st', body: 'task B' } as never+/** D: `open-claude --after st`, held (as every control open is) in `pendingLaunch`. */+const d: ArmedNode = { id: 'd', data: { pendingLaunch: { after: ['st'], command: 'claude go' } } }+const live = new Set(['orch', 'st', 'd'])++/** Would the renderer's launch loop start D right now? */+function dFires(h: Harness): boolean {+ const status = { st: { state: h.state.st } }+ return launchesToFire([d], status, live, undefined, undefined, undefined, undefined, h.mirror()).length > 0+}++beforeEach(() => {+ resetMessageFlow()+ resetAgentMessageTraceForTests()+})++describe('plain --after after a QUEUED hand-over — the scenario that fired on the old task', () => {+ it('D does not fire when S finishes the OLD task; it fires only after the new task\'s turn ends', async () => {+ const h = harness()+ const queue = createDeliveryQueue(h.deps, { schedule: () => () => {} })+ h.deps.queue = queue+ h.event('working') // S is busy on task A++ // 1. The orchestrator hands S task B → queued (S is busy).+ const { outcome } = await deliverFromControl(send, h.deps)+ expect(outcome.kind).toBe('queued')+ // 2. …and opens D `--after S`.+ expect(dFires(h)).toBe(false)++ // 3. S finishes task A. Its state is `done` — the OLD task's. The queue flushes B on this edge.+ h.event('done')+ expect(dFires(h)).toBe(false)+ await vi.waitFor(() => expect(queue.depth('st')).toBe(0))+ await vi.waitFor(() => expect(h.sent).toHaveLength(1))+ expect(dFires(h)).toBe(false)++ // 4. S starts B, then ends that turn: now — and only now — D starts.+ h.event('working')+ expect(dFires(h)).toBe(false)+ h.event('done')+ expect(dFires(h)).toBe(true)+ })++ it('a queued hand-over that EXPIRES unread holds D until S finishes a later turn', async () => {+ const h = harness()+ let expire: (() => void) | null = null+ const queue = createDeliveryQueue(h.deps, {+ schedule: (_ms, fn) => {+ expire = fn+ return () => {+ expire = null+ }+ }+ })+ h.deps.queue = queue+ h.event('working')+ await deliverFromControl(send, h.deps)+ expect(expire).toBeTruthy()+ h.tick(10)+ expire!()+ // The queue settles the entry after its trace write.+ await vi.waitFor(() => expect(h.tracker.list()).toEqual([{ nodeId: 'st', since: expect.any(Number) }]))+ // S is idle on task A's `done` — which is not what the orchestrator armed D for.+ h.state.st = 'done'+ h.tracker.onAgentEvent({ nodeId: 'st', state: 'done' })+ expect(dFires(h)).toBe(false)+ h.event('working')+ h.event('done')+ expect(dFires(h)).toBe(true)+ })+})++describe('plain --after after a hand-over that LANDED on an idle station', () => {+ it('D waits while S has not started the new work yet, then fires after that turn', async () => {+ const h = harness()+ h.event('done') // idle after task A+ const { outcome } = await deliverFromControl(send, h.deps)+ expect(outcome.kind).toBe('delivered')+ // Landed, but S has not emitted `working` yet: its `done` is task A's.+ expect(dFires(h)).toBe(false)+ h.event('working')+ h.event('done')+ expect(dFires(h)).toBe(true)+ })+})++describe('plain --after after a write / run', () => {+ it('the answer marks the station from when the request arrived', () => {+ const h = harness()+ h.event('done')+ const requestAt = h.tick(5)+ h.tracker.noteControlAnswer('write', { node: 'st', text: 'task B' }, { ok: true }, 'orch', requestAt)+ expect(dFires(h)).toBe(false)+ h.event('working')+ h.event('done')+ expect(dFires(h)).toBe(true)+ })++ it('a refused write hands nothing over', () => {+ const h = harness()+ h.event('done')+ h.tracker.noteControlAnswer('write', { node: 'st' }, { ok: false }, 'orch', h.tick(5))+ expect(dFires(h)).toBe(true)+ })+})++describe('the ordinary case is unchanged', () => {+ it('a station nobody handed anything fires D on its done, as before', () => {+ const h = harness()+ h.event('working')+ expect(dFires(h)).toBe(false)+ h.event('done')+ expect(dFires(h)).toBe(true)+ })+})