Skip to content

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

fix(control): a station's report ends when new work REACHES its pane, not when the send answers

reviewc245dbe1ff9a
diff --git a/CLAUDE.md b/CLAUDE.md
index d311b6614..1070f6022 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3831,18 +3831,43 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
(`requiresVerified`) and a node reports only about ITSELF: `--node` naming another node is
refused (`report-outcome-not-self`), not ignored. The note is display text (`sanitizeOutcomeNote`:
`oneLine` + format chars stripped, 200 code points) and is never typed into a pane.
- - **When a report ends — the "new task" rule.** A later report supersedes. A `send` / `reply` /
- `write` / `run` that SUCCEEDS against a station withdraws its report (`clearOutcomesAfterControl`,
- run by each shell's control handler AFTER the answer). Without it, "hand a station its next task,
- then open a dependent `--after-success` it" released the dependent at once on the previous task's
- success — early, the direction nothing undoes; withdrawing errs toward holding, which the deadline
- and ▶ end. A new TURN does not clear it (a turn is not a task: a station may report mid-turn, and a
- person typing "thanks" starts a turn, not a task), and neither does a person typing in the pane or
- a board comment. Closing a station keeps its report (the deleted-station rule reads it).
- - **Both shells**: desktop main answers the verb before the forward and clears after it; the Server
- Edition answers it through the same `handleReportOutcome` (`onRecorded` re-runs `refreshArmed`),
- honours `--after-success` in the headless factory (`successFacts`: the mirror's `done` plus the
- fresh-spawn `awaitingFirstWorking` rule) and wraps its handler with the same clearing rule.
+ - **When a report ends — the "new task" rule, decided by when work REACHES THE PANE, never by
+ when a control answer comes back.** A later report supersedes. Otherwise, "hand a station its next
+ task, then open a dependent `--after-success` on it" releases the dependent on the PREVIOUS task's
+ success. The first version withdrew the report on the `send`'s ANSWER, which for a busy station is
+ `queued` (ok: true) long before the message lands — so the station's report for the task it was
+ still on counted, its turn ended, D fired, and the queue flushed the new task on the same idle edge
+ (review of #1034). Now:
+ - `send` / `reply`: the messaging layer emits `AgentMessagingDeps.onHandover` — `queued` (the
+ queue's own `onQueued`, synchronous at the push), `landed` (bytes reached the pane: `delivered`,
+ `stalled`, `deliveredToReplacedTarget`, on a first attempt or a flush, `at` = when that attempt
+ STARTED), `settled` (one per `queued`: flushed, refused on flush, or expired). The store
+ (`StationOutcomeStore.onHandover`) marks a queued station WORK PENDING — its reports publish with
+ `workPending` and do not count — withdraws reports older than a landing's start (so a report
+ about the new work survives a stalled or late answer), and on a settle that never landed
+ withdraws the report too (holding, not the old success; the orchestrator was told it expired).
+ Only `send` / `reply` count: a board comment is a person steering and a station notice is the app.
+ - `write` / `run`: their answer IS the landing (typed after the confirm; a held launch delivered),
+ so `clearOutcomesAfterControl` withdraws reports older than the answer, from each shell's
+ control handler (desktop `finishAnswer`, which runs on a late answer too).
+ - A new TURN clears nothing (a turn is not a task: a station may report mid-turn, and a person
+ typing "thanks" starts a turn), nor does typing in the pane. Closing a station keeps its report
+ (the deleted-station rule reads it). Every rule errs toward holding, which the deadline and ▶ end.
+ `main/station-outcome-handover.test.ts` replays the review's scenario through the REAL queue and
+ fails on the answer-time rule.
+ - **Both shells**: desktop main answers the verb before the forward; the Server Edition answers it
+ through the same `handleReportOutcome` (`onRecorded` re-runs `refreshArmed`) and honours
+ `--after-success` in the headless factory (`successFacts`: the mirror's `done`, the fresh-spawn
+ `awaitingFirstWorking` rule, and #521's errored turn from its own event stream, `lastTurnErrored`
+ — so a succeeded-then-errored station holds on both editions; the server's PLAIN `--after` still
+ does not apply #521, a pre-existing gap). Both wire `onHandover` into their messaging deps and run
+ `clearOutcomesAfterControl` on answers.
+ - **The badge's deadline tick is a memo input** (`lib/useSuccessWait.ts`): nothing in any store
+ changes when a deadline passes, and a timer whose tick the memo ignores re-rendered the node with
+ the cached "waiting" — the badge kept QUEUED while `list` said EXPIRED. `useSuccessWait.test.tsx`.
+ - Reports do not survive an app restart, so a station that reported success and was then CLOSED
+ reads BLOCKED afterwards ("closed without reporting success in this app run"); nothing can report
+ for it any more, so only ▶ / `run` start that dependent. Both agent bodies say so.
`station-outcome:list` is in `HOST_ONLY_CHANNELS` (unscoped: every project's notes); relay tabs
take the inert stub. Pinned at source level by `main/station-outcome-wiring.test.ts`. **Not
done:** a reported `failed` does not raise a station-failure notice to the opener (the opener
diff --git a/src/core/agents/agent-messaging.ts b/src/core/agents/agent-messaging.ts
index b1f02b6f5..7fe187697 100644
--- a/src/core/agents/agent-messaging.ts
+++ b/src/core/agents/agent-messaging.ts
@@ -187,8 +187,27 @@ export interface AgentMessagingDeps {
* `createDeliveryQueue` has run.
*/
onQueuedResult?(req: QueuedDeliveryRequest, outcome: AgentMessageOutcome): void
+ /**
+ * Where a message stands on its way INTO a target's pane — the facts a station's task-outcome
+ * report depends on (src/core/station-outcome-store.ts: new work handed to a station ends its
+ * previous report). Emitted for every verb; the listener picks the ones it counts:
+ * - `queued`: accepted into the target's queue (the bytes have NOT reached the pane);
+ * - `landed`: the bytes reached the pane (`delivered`, `stalled`, `deliveredToReplacedTarget`),
+ * on a first attempt or a flush. `at` is when that delivery attempt STARTED — a report made
+ * after it started was made about the new work, whenever the answer comes back;
+ * - `settled`: a queued entry ended (flushed, refused on flush, or expired), `landed` saying
+ * whether its bytes reached the pane. Exactly one per `queued`.
+ * Read at call time, so a shell may assign it after `createDeliveryQueue` has run.
+ */
+ onHandover?(event: MessageHandover): void
}
+/** See `AgentMessagingDeps.onHandover`. */
+export type MessageHandover =
+ | { phase: 'queued'; verb: string; targetNodeId: string }
+ | { phase: 'landed'; verb: string; targetNodeId: string; at: number }
+ | { phase: 'settled'; verb: string; targetNodeId: string; landed: boolean }
+
/**
* The production `messagingEnabled`: the per-project capability GRANT, one call, nothing else.
*
@@ -291,10 +310,12 @@ export function createDeliveryQueue(
}
void deps.appendBoardLog(projectId, entry)
}
+ const handover = (ev: MessageHandover): void => deps.onHandover?.(ev)
const queue: DeliveryQueue = new DeliveryQueue(
{
now,
deliver: async (qreq) => {
+ const startedAt = now()
const outcome = await runDelivery(
qreq.verb === 'board-comment'
? (qreq as unknown as BoardCommentMessage)
@@ -308,6 +329,8 @@ export function createDeliveryQueue(
},
deps
)
+ if (WROTE.has(outcome.kind))
+ handover({ phase: 'landed', verb: String(qreq.verb), targetNodeId: qreq.targetNodeId, at: startedAt })
// A board comment re-queued by the pair window waits on a CLOCK, not on the target's turn:
// re-offer it when the window ends (see `DeliveryQueue.retryAfter`).
if (qreq.verb === 'board-comment' && outcome.kind === 'rateLimited')
@@ -331,7 +354,10 @@ export function createDeliveryQueue(
now
}),
// The sender leg: a durable line where the sender's operator will see it.
+ onQueued: (req) =>
+ handover({ phase: 'queued', verb: String(req.verb), targetNodeId: req.targetNodeId }),
onExpired: (req, info) => {
+ handover({ phase: 'settled', verb: String(req.verb), targetNodeId: req.targetNodeId, landed: false })
senderBoardLog(req, 'expired')
deps.onQueuedResult?.(req, {
kind: 'expired',
@@ -340,6 +366,12 @@ export function createDeliveryQueue(
})
},
onFlushed: (req, outcome) => {
+ handover({
+ phase: 'settled',
+ verb: String(req.verb),
+ targetNodeId: req.targetNodeId,
+ landed: WROTE.has(outcome.kind)
+ })
senderBoardLog(req, outcome.kind)
deps.onQueuedResult?.(req, outcome)
},
@@ -795,7 +827,10 @@ async function deliverWithQueue(
outcome,
reply: renderMessageOutcome(outcome)
})
+ const startedAt = (deps.now ?? ((): number => Date.now()))()
const outcome = await runDelivery(req, deps)
+ if (WROTE.has(outcome.kind))
+ deps.onHandover?.({ phase: 'landed', verb: req.verb, targetNodeId: req.targetNodeId, at: startedAt })
const queue = deps.queue
if (queue) {
const ident = requestIdentity(req)
diff --git a/src/core/agents/delivery-queue.ts b/src/core/agents/delivery-queue.ts
index 85b0515be..0a520dd11 100644
--- a/src/core/agents/delivery-queue.ts
+++ b/src/core/agents/delivery-queue.ts
@@ -106,6 +106,10 @@ export interface DeliveryQueueDeps {
/** Tell the sender how a flush ended (delivered, or refused because the world changed under it).
* Same optionality reasoning as `onExpired`. */
onFlushed?(req: QueuedDeliveryRequest, outcome: AgentMessageOutcome): void
+ /** An entry was accepted into a target's queue — called synchronously, right as it is added, so a
+ * listener learns of it before any flush or expiry of that entry can run. Every entry that fires
+ * this later ends in exactly one `onFlushed` or `onExpired`. */
+ onQueued?(req: QueuedDeliveryRequest): void
/** Arm a one-shot timer, returning its cancel. Injected so tests drive TTL expiry deterministically
* instead of waiting real milliseconds; defaults to `setTimeout`/`clearTimeout`. */
schedule?(ms: number, fn: () => void): CancelTimer
@@ -195,6 +199,7 @@ export class DeliveryQueue {
}
list.push(entry)
this.queues.set(req.targetNodeId, list)
+ this.deps.onQueued?.(req)
// Kick the wake for a hibernated target so it starts its resume; the flush waits on the idle
// event, not on the wake. A busy (non-hibernated) target needs nothing — it will go idle on its
// own turn end.
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 904eed352..f2e6a6559 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -235,17 +235,22 @@ function afterSuccessDocLines(): string[] {
'- Only an agent session with canvas control can report, so only such a node may be named; a plain',
' terminal is refused (wait on it with `--after`). A station that is CLOSED counts only if it reported',
' success before it was closed; closed without one, it blocks.',
- '- A report stands until that station reports again, or until YOU hand it new work through canvas',
- ' control: a `send`, `reply`, `write` or `run` aimed at it withdraws its report. So to reuse a station,',
- ' hand it the next task FIRST, then open the dependent — opened first, the dependent would start at',
- ' once on the earlier success. A new turn does not withdraw a report, and neither does the user',
- " typing in the station's pane.",
+ '- A report stands until that station reports again, or until new work YOU hand it through canvas',
+ ' control reaches its session: a `send`, `reply`, `write` or `run` aimed at it withdraws the reports it',
+ ' made before that work arrived. A `send` / `reply` QUEUED for a busy station stops its report',
+ ' counting the moment it is queued — so the report it makes for the task it is still on releases',
+ ' nothing — and a queued message that expires unread withdraws the report too. So to reuse a',
+ ' station, hand it the next task FIRST, then open the dependent — opened first, the dependent would',
+ ' start at once on the earlier success. A new turn does not withdraw a report, and neither does the',
+ " user typing in the station's pane.",
`- \`--success-deadline <90m|12h|3d>\` bounds the wait (default ${hours}h, at most ${days}d). Past it the node`,
' never starts on its own: `list` marks it EXPIRED, and you start it with `run` (the user can press ▶).',
`- Name each station once, at most ${SUCCESS_WAIT_MAX}: an id in both \`--after\` and \`--after-success\` is refused, and so is`,
' a suffix on `--after` (`--after a1:ok`) — write `--after-success a1`. `--run-now` and `--project` cannot',
' be combined with it. Reports live in the running app: after an app restart no station has reported',
- ' yet, so a dependent still waiting then needs its stations to report again (or `run`). The Server',
+ ' yet, so a dependent still waiting then needs its stations to report again (or `run`) — and one whose',
+ ' station reported success and was then CLOSED reads BLOCKED ("closed without reporting success in',
+ ' this app run"): nothing can report for it any more, so only `run` (or ▶) starts it. The Server',
' Edition accepts both the flag and the verb.'
]
}
diff --git a/src/core/station-outcome-store.test.ts b/src/core/station-outcome-store.test.ts
index 525e40b2b..166dbc370 100644
--- a/src/core/station-outcome-store.test.ts
+++ b/src/core/station-outcome-store.test.ts
@@ -142,7 +142,7 @@ describe('StationOutcomeStore', () => {
})
})
-describe('clearOutcomesAfterControl — new work handed through canvas control withdraws a report', () => {
+describe('clearOutcomesAfterControl — a write / run landing in a station withdraws its OLDER report', () => {
const seeded = () => {
const s = new StationOutcomeStore()
s.record({ nodeId: 'st1', outcome: 'succeeded', at: 1 })
@@ -150,37 +150,107 @@ describe('clearOutcomesAfterControl — new work handed through canvas control w
return s
}
- it.each(['send', 'reply', 'write', 'run'])('a successful %s aimed at a station clears its report', (verb) => {
+ it.each(['write', 'run'])('a successful %s aimed at a station withdraws a report made before its answer', (verb) => {
const s = seeded()
- clearOutcomesAfterControl(s, verb, { node: 'st1', text: 'next task' }, { ok: true }, 'orch')
+ clearOutcomesAfterControl(s, verb, { node: 'st1', text: 'next task' }, { ok: true }, 'orch', 10)
expect(s.get('st1')).toBeUndefined()
expect(s.get('st2')).toBeDefined()
})
- it('a refused or failed request handed nothing, so nothing is cleared', () => {
+ it('a report made after the answer (about the new work) stands', () => {
const s = seeded()
- clearOutcomesAfterControl(s, 'send', { node: 'st1' }, { ok: false }, 'orch')
+ clearOutcomesAfterControl(s, 'write', { node: 'st1' }, { ok: true }, 'orch', 1)
expect(s.get('st1')).toBeDefined()
})
- it('notify types nothing into a pane, and other verbs hand no work', () => {
+ it('send / reply are NOT decided by their answer — a queued answer comes back before the pane gets it', () => {
const s = seeded()
+ for (const verb of ['send', 'reply']) clearOutcomesAfterControl(s, verb, { node: 'st1' }, { ok: true }, 'orch', 10)
+ expect(s.get('st1')).toBeDefined()
+ expect([...OUTCOME_CLEARING_VERBS].sort()).toEqual(['run', 'write'])
+ })
+
+ it('a refused request handed nothing, and other verbs hand no work', () => {
+ const s = seeded()
+ clearOutcomesAfterControl(s, 'write', { node: 'st1' }, { ok: false }, 'orch', 10)
for (const verb of ['notify', 'rename', 'list', 'close', 'color', 'assign']) {
- clearOutcomesAfterControl(s, verb, { node: 'st1' }, { ok: true }, 'orch')
+ clearOutcomesAfterControl(s, verb, { node: 'st1' }, { ok: true }, 'orch', 10)
}
expect(s.get('st1')).toBeDefined()
- expect([...OUTCOME_CLEARING_VERBS].sort()).toEqual(['reply', 'run', 'send', 'write'])
})
it('a node writing into its OWN pane is not handed work by anyone', () => {
const s = seeded()
- clearOutcomesAfterControl(s, 'write', { node: 'st1' }, { ok: true }, 'st1')
+ clearOutcomesAfterControl(s, 'write', { node: 'st1' }, { ok: true }, 'st1', 10)
expect(s.get('st1')).toBeDefined()
})
it('reads a comma list, and ignores an id it would not vouch for', () => {
const s = seeded()
- clearOutcomesAfterControl(s, 'send', { node: 'st1, st2, ../x' }, { ok: true }, 'orch')
+ clearOutcomesAfterControl(s, 'run', { node: 'st1, st2, ../x' }, { ok: true }, 'orch', 10)
expect(s.list()).toEqual([])
})
})
+
+describe('StationOutcomeStore.onHandover — decided by when the work reaches the pane', () => {
+ it('queued → every report stops counting (workPending), including one made after', () => {
+ const publish = vi.fn()
+ const s = new StationOutcomeStore(publish)
+ s.record({ nodeId: 'st', outcome: 'succeeded', at: 5 })
+ s.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st' })
+ expect(s.get('st')).toEqual({ nodeId: 'st', outcome: 'succeeded', at: 5, workPending: true })
+ s.record({ nodeId: 'st', outcome: 'succeeded', at: 7 })
+ expect(s.list()).toEqual([{ nodeId: 'st', outcome: 'succeeded', at: 7, workPending: true }])
+ expect(publish).toHaveBeenLastCalledWith([{ nodeId: 'st', outcome: 'succeeded', at: 7, workPending: true }])
+ })
+
+ it('landed withdraws only reports older than when the delivery started; settled drops the mark', () => {
+ const s = new StationOutcomeStore()
+ s.onHandover({ phase: 'queued', verb: 'reply', targetNodeId: 'st' })
+ s.record({ nodeId: 'st', outcome: 'succeeded', at: 5 })
+ s.onHandover({ phase: 'landed', verb: 'reply', targetNodeId: 'st', at: 10 })
+ expect(s.get('st')).toBeUndefined()
+ s.onHandover({ phase: 'settled', verb: 'reply', targetNodeId: 'st', landed: true })
+ s.record({ nodeId: 'st', outcome: 'failed', at: 12 })
+ expect(s.get('st')).toEqual({ nodeId: 'st', outcome: 'failed', at: 12 })
+ // A later landing whose delivery started BEFORE that report leaves it alone.
+ s.onHandover({ phase: 'landed', verb: 'send', targetNodeId: 'st', at: 11 })
+ expect(s.get('st')?.outcome).toBe('failed')
+ })
+
+ it('two queued messages keep the mark until BOTH have settled', () => {
+ const s = new StationOutcomeStore()
+ s.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st' })
+ s.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st' })
+ s.onHandover({ phase: 'landed', verb: 'send', targetNodeId: 'st', at: 1 })
+ s.onHandover({ phase: 'settled', verb: 'send', targetNodeId: 'st', landed: true })
+ s.record({ nodeId: 'st', outcome: 'succeeded', at: 2 })
+ expect(s.get('st')?.workPending).toBe(true)
+ s.onHandover({ phase: 'landed', verb: 'send', targetNodeId: 'st', at: 3 })
+ s.onHandover({ phase: 'settled', verb: 'send', targetNodeId: 'st', landed: true })
+ expect(s.get('st')).toBeUndefined()
+ s.record({ nodeId: 'st', outcome: 'succeeded', at: 4 })
+ expect(s.get('st')?.workPending).toBeUndefined()
+ })
+
+ it('a queued entry that ends without landing withdraws the report and drops the mark', () => {
+ const s = new StationOutcomeStore()
+ s.onHandover({ phase: 'queued', verb: 'send', targetNodeId: 'st' })
+ s.record({ nodeId: 'st', outcome: 'succeeded', at: 5 })
+ s.onHandover({ phase: 'settled', verb: 'send', targetNodeId: 'st', landed: false })
+ expect(s.get('st')).toBeUndefined()
+ s.record({ nodeId: 'st', outcome: 'succeeded', at: 6 })
+ expect(s.get('st')?.workPending).toBeUndefined()
+ })
+
+ it('only send / reply count — a board comment, a station notice or notify hand no task', () => {
+ const s = new StationOutcomeStore()
+ s.record({ nodeId: 'st', outcome: 'succeeded', at: 1 })
+ for (const verb of ['board-comment', 'station-notice', 'notify']) {
+ s.onHandover({ phase: 'queued', verb, targetNodeId: 'st' })
+ s.onHandover({ phase: 'landed', verb, targetNodeId: 'st', at: 10 })
+ s.onHandover({ phase: 'settled', verb, targetNodeId: 'st', landed: false })
+ }
+ expect(s.get('st')).toEqual({ nodeId: 'st', outcome: 'succeeded', at: 1 })
+ })
+})
diff --git a/src/core/station-outcome-store.ts b/src/core/station-outcome-store.ts
index 55d0ddcdf..1ddb727da 100644
--- a/src/core/station-outcome-store.ts
+++ b/src/core/station-outcome-store.ts
@@ -12,12 +12,23 @@
*
* WHEN A REPORT ENDS (the "new task" rule):
* - the station reports again — the later report supersedes;
- * - the station is handed new work THROUGH CANVAS CONTROL — a `send` / `reply` / `write` into its
- * pane, or a `run` of its held launch (`OUTCOME_CLEARING_VERBS`). Those are the moments nodeterm
- * itself sees new work arrive, and they are how an orchestrator reuses a station: without the
- * withdrawal, "hand the station its next task, then open a dependent `--after-success` it" would
- * release that dependent at once on the PREVIOUS task's success — early, the direction nothing
- * can undo. Withdrawing errs toward holding, which the deadline and ▶ / `run` can always end;
+ * - the station is handed new work THROUGH CANVAS CONTROL. That is how an orchestrator reuses a
+ * station, and without it "hand the station its next task, then open a dependent
+ * `--after-success` on it" would release that dependent at once on the PREVIOUS task's success —
+ * early, the direction nothing can undo. It is decided by WHEN THE WORK REACHES THE PANE, never
+ * by when a control answer comes back (the answer to a queued message comes back long before):
+ * · a `send` / `reply` that is QUEUED for a busy station marks it WORK PENDING
+ * (`onHandover` 'queued'): every report it makes stops counting — including the one it is
+ * about to make for the task it is still on — until the message lands;
+ * · when the bytes LAND (first attempt or flush), every report made before that delivery
+ * STARTED is withdrawn; a report made after it (about the new work) stands, however late
+ * the answer arrives;
+ * · a queued message that ends WITHOUT landing (expired, refused on flush) withdraws the
+ * report too. The orchestrator handed new work and was told it did not arrive; a dependent it
+ * armed after that hand-over must not start on the older task's word;
+ * · `write` / `run` (typed straight into the pane after its confirm, or a held launch started)
+ * withdraw every report older than their answer, which is when the bytes landed;
+ * Every one of these errs toward holding, which the deadline and ▶ / `run` can always end;
* - NOT a new turn. A turn is not a task: a station may report mid-turn and keep summarising, and
* a person typing "thanks" into its pane starts a turn without starting a task. nodeterm cannot
* tell a new task from a follow-up by looking at a turn, so a turn changes nothing here; the
@@ -36,6 +47,7 @@ import {
type StationOutcomeRecord
} from '../shared/station-outcome'
import type { CorePlatform } from './platform'
+import type { MessageHandover } from './agents/agent-messaging'
/** How many stations' reports one process keeps. Far past any canvas; evicts the oldest first. */
export const STATION_OUTCOME_MAX_RECORDS = 1000
@@ -47,6 +59,10 @@ export class StationOutcomeStore {
// Insertion order IS recency: a record is deleted and re-set on every write, so the first key is
// always the oldest and eviction is one `keys().next()`.
private readonly byId = new Map<string, StationOutcomeRecord>()
+ /** Stations with a `send`/`reply` still QUEUED for them, and how many. While a station is here its
+ * report does not count (`workPending` on the published record). Every entry is removed by the
+ * queue's own `settled` event — the queue guarantees one per `queued`. */
+ private readonly pending = new Map<string, number>()
/** `publish` gets the FULL list after every change (never a delta), like station notices. */
constructor(private readonly publish: (records: StationOutcomeRecord[]) => void = () => {}) {}
@@ -69,39 +85,82 @@ export class StationOutcomeStore {
return true
}
+ /** Withdraw a station's report if it was made BEFORE `at` — new work landed at `at`, so only a
+ * report made after it can be about that work. `true` when one was withdrawn. */
+ withdrawBefore(nodeId: string, at: number): boolean {
+ const rec = this.byId.get(nodeId)
+ if (!rec || rec.at >= at) return false
+ return this.clear(nodeId)
+ }
+
+ /**
+ * The messaging layer's hand-over events (`AgentMessagingDeps.onHandover`). Only `send` and
+ * `reply` count: a board comment is a person steering (like typing in the pane), and a station
+ * notice is the app telling an orchestrator something — neither is a task handed to a station.
+ */
+ onHandover(ev: MessageHandover): void {
+ if (!HANDOVER_VERBS.has(ev.verb) || !isSafeNodeId(ev.targetNodeId)) return
+ const id = ev.targetNodeId
+ if (ev.phase === 'queued') {
+ this.pending.set(id, (this.pending.get(id) ?? 0) + 1)
+ this.publish(this.list())
+ return
+ }
+ if (ev.phase === 'landed') {
+ this.withdrawBefore(id, ev.at)
+ return
+ }
+ // settled: the queued entry is gone. One that never landed withdraws the report as well (see
+ // the header); one that landed already withdrew the older reports on its `landed` event.
+ const left = (this.pending.get(id) ?? 1) - 1
+ if (left > 0) this.pending.set(id, left)
+ else this.pending.delete(id)
+ if (!ev.landed) this.byId.delete(id)
+ this.publish(this.list())
+ }
+
get(nodeId: string): StationOutcomeRecord | undefined {
- return this.byId.get(nodeId)
+ const rec = this.byId.get(nodeId)
+ return rec && this.pending.has(nodeId) ? { ...rec, workPending: true } : rec
}
- /** Every record, newest first. */
+ /** Every record, newest first, each flagged `workPending` while new work is still queued for it. */
list(): StationOutcomeRecord[] {
- return [...this.byId.values()].reverse()
+ return [...this.byId.values()]
+ .reverse()
+ .map((rec) => (this.pending.has(rec.nodeId) ? { ...rec, workPending: true as const } : rec))
}
}
+/** The messaging verbs whose delivery hands a station new work. */
+const HANDOVER_VERBS: ReadonlySet<string> = new Set(['send', 'reply'])
+
/**
- * Verbs that hand the node they name (`--node`) NEW WORK when they succeed, and so withdraw its
- * outcome report — see the header's "new task" rule. `notify` is not one: it raises an OS
- * notification and types nothing into the pane.
+ * The control verbs whose ANSWER marks new work landing in the node they name (`--node`): `write`
+ * types into the pane right before it answers (after its confirm), and `run` answers once a held
+ * launch was delivered. `send` / `reply` are NOT here — their answer can be `queued`, long before
+ * the bytes reach the pane — and are handled by the messaging layer's own hand-over events
+ * (`StationOutcomeStore.onHandover`). `notify` types nothing into the pane.
*/
-export const OUTCOME_CLEARING_VERBS: ReadonlySet<string> = new Set(['send', 'reply', 'write', 'run'])
+export const OUTCOME_CLEARING_VERBS: ReadonlySet<string> = new Set(['write', 'run'])
/**
- * Apply the "new task" rule to one finished control request. Run by each shell's control handler
- * AFTER the verb answered, and only on success: a refused or undelivered message handed nothing.
- * A caller naming ITSELF is not handed work by anyone (a station `write`-ing into its own pane is
- * still doing its own task).
+ * Apply the "new task" rule to one finished `write` / `run`. Run by each shell's control handler on
+ * the answer, and only on success: a refused write handed nothing. Withdraws only reports made
+ * BEFORE `now` — the answer is when the bytes landed. A caller naming ITSELF is not handed work by
+ * anyone (a station `write`-ing into its own pane is still doing its own task).
*/
export function clearOutcomesAfterControl(
- store: Pick<StationOutcomeStore, 'clear'>,
+ store: Pick<StationOutcomeStore, 'withdrawBefore'>,
verb: string,
args: Record<string, string | undefined>,
result: { ok: boolean },
- callerNodeId: string
+ callerNodeId: string,
+ now: number = Date.now()
): void {
if (!result.ok || !OUTCOME_CLEARING_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)) store.clear(id)
+ if (id && id !== callerNodeId && isSafeNodeId(id)) store.withdrawBefore(id, now)
}
}
@@ -178,8 +237,8 @@ export async function handleReportOutcome(
const message = [
`recorded: your task ${parsed.outcome}${parsed.note ? ` — "${parsed.note}"` : ''}.`,
RELEASE_TEXT[parsed.outcome],
- 'It stands until you report again, or until you are handed new work through canvas control ' +
- '(a send, reply, write or run aimed at you). A new turn does not change it.'
+ 'It stands until you report again, or until new work handed to you through canvas control (a ' +
+ 'send, reply, write or run aimed at you) reaches your session. A new turn does not change it.'
].join(' ')
return {
ok: true,
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 815b253a3..ff7d9a42a 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -1495,8 +1495,11 @@ describe('--after-success + report-outcome: a dependent that waits for a reporte
expect(flat).toContain('No report yet means waiting')
expect(flat).toContain('A station that is CLOSED counts only if it reported success before it was closed')
// The "new task" rule, as core implements it (OUTCOME_CLEARING_VERBS).
- expect(flat).toContain('a `send`, `reply`, `write` or `run` aimed at it withdraws its report')
+ expect(flat).toContain('a `send`, `reply`, `write` or `run` aimed at it withdraws the reports it made before that work arrived')
+ expect(flat).toContain('A `send` / `reply` QUEUED for a busy station stops its report counting the moment it is queued')
+ expect(flat).toContain('a queued message that expires unread withdraws the report too')
expect(flat).toContain('hand it the next task FIRST, then open the dependent')
+ expect(flat).toContain('only `run` (or ▶) starts it')
expect(flat).toContain('A new turn does not withdraw a report')
// Limits rendered from the modules that enforce them.
expect(flat).toContain('`--success-deadline <90m|12h|3d>` bounds the wait (default 24h, at most 14d)')
diff --git a/src/main/index.ts b/src/main/index.ts
index df1638118..593535bf0 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1960,6 +1960,10 @@ app.whenReady().then(async () => {
sendToMain(IPC.stationOutcomeChanged, records)
)
registerStationOutcomeIpc(corePlatform, () => stationOutcomes)
+ // 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)
ipcMain.handle(IPC.dialogSelectFolder, async () => {
const result = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'] })
@@ -3961,9 +3965,10 @@ app.whenReady().then(async () => {
return { ok: false, error: OPEN_PROJECT_GRANT_CAP, message: OPEN_PROJECT_GRANT_CAP }
}
}
- // New work handed to a station through canvas control withdraws its outcome report — the
+ // New work typed into a station by `write` / `run` withdraws its older outcome report — the
// "new task" rule in src/core/station-outcome-store.ts. On the answer (prompt or late), and
- // only on success.
+ // 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)
return answer
}
diff --git a/src/main/station-outcome-handover.test.ts b/src/main/station-outcome-handover.test.ts
new file mode 100644
index 000000000..b7556882b
--- /dev/null
+++ b/src/main/station-outcome-handover.test.ts
@@ -0,0 +1,214 @@
+/**
+ * The "new task" rule for `--after-success`, end to end through the REAL messaging service and the
+ * REAL delivery queue (`createDeliveryQueue`, the builder both shells use) — the path the review of
+ * #1034 found wrong. The report used to be withdrawn when the control ANSWER returned; for a busy
+ * station a `send` answers `queued` (ok: true) long before the message reaches the pane, so:
+ *
+ * 1. the orchestrator `send`s station S task B while S still works on A → queued, report withdrawn;
+ * 2. the orchestrator opens D `--after-success S`;
+ * 3. S finishes A and reports `succeeded`;
+ * 4. S's turn ends → D fires on A's word; on the same idle edge the queue flushes B.
+ *
+ * Each test below replays one ordering with the shell's own post-answer step
+ * (`clearOutcomesAfterControl`, which `finishAnswer` and the Server Edition's wrapper run), so it
+ * fails on the answer-time rule and passes on the landing-time one.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ createDeliveryQueue,
+ deliverFromControl,
+ onMessagingAgentEvent,
+ type AgentMessagingDeps
+} from '../core/agents/agent-messaging'
+import { resetMessageFlow } from '../core/agents/agent-message-flow'
+import { resetAgentMessageTraceForTests } from '../core/agents/agent-message-trace'
+import { MANAGED_SCRIPT_REVISION } from '../core/agents/hooks/managed-script'
+import type { MirrorEntry } from '../core/agent-status-mirror'
+import { StationOutcomeStore, clearOutcomesAfterControl } from '../core/station-outcome-store'
+import { successWaitSatisfied, type SuccessWaitHold } from '../shared/station-outcome'
+
+const entry = (state: 'working' | 'done'): MirrorEntry => ({
+ state,
+ updatedAt: 1,
+ stateVerified: true,
+ clientRevision: MANAGED_SCRIPT_REVISION
+})
+
+interface Harness {
+ deps: AgentMessagingDeps
+ store: StationOutcomeStore
+ setBusy(busy: boolean): void
+ tick(ms: number): number
+ sent: string[]
+ /** Runs inside the pane write — a station that reports WHILE the delivery is still in flight. */
+ duringWrite?: () => void
+}
+
+function harness(): Harness {
+ let busy = true
+ let clock = 1_000_000
+ const sent: string[] = []
+ const store = new StationOutcomeStore()
+ const h: Harness = {
+ store,
+ sent,
+ setBusy: (b) => {
+ busy = b
+ },
+ tick: (ms) => (clock += ms),
+ deps: undefined as unknown as AgentMessagingDeps
+ }
+ const projects = () => [
+ { id: 'p1', nodes: [{ id: 'orch', title: 'Orchestrator', agentId: 'claude' }, { id: 'st', title: 'Station', agentId: 'claude' }] }
+ ]
+ 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)
+ h.duringWrite?.()
+ return true
+ },
+ hasLiveSession: () => true,
+ mirrorEntry: () => entry(busy ? 'working' : 'done'),
+ projects,
+ isRemoteNode: () => false,
+ messagingEnabled: () => true,
+ paneOwnerProject: () => 'p1',
+ customAgents: () => undefined,
+ appendBoardLog: async () => false,
+ // Every write is confirmed by the station starting a verified turn → `delivered`.
+ 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.
+ onHandover: (ev) => store.onHandover(ev)
+ }
+ return h
+}
+
+const send = { verb: 'send', sourceNodeId: 'orch', targetNodeId: 'st', body: 'task B' } as never
+const sendArgs = { node: 'st', text: 'task B' }
+/** D's wait, armed right after the hand-over, per the skill text's own advice. */
+const hold: SuccessWaitHold = { deps: ['st'], deadlineAt: Number.MAX_SAFE_INTEGER }
+/** Would D fire now? The station's turn is over (the idle edge the queue flushes on). */
+const dFires = (store: StationOutcomeStore): boolean =>
+ successWaitSatisfied(hold, (id) => ({ exists: true, turnDone: true, outcome: store.get(id) }), 0)
+
+beforeEach(() => {
+ resetMessageFlow()
+ resetAgentMessageTraceForTests()
+})
+
+describe('a QUEUED send marks the station "work pending" — the reviewer\'s scenario', () => {
+ it('the report S makes for the task it is still on does NOT release D; only the report after B lands does', async () => {
+ const h = harness()
+ const queue = createDeliveryQueue(h.deps, { schedule: () => () => {} })
+ h.deps.queue = queue
+
+ // 1. hand-over while S is busy on A → queued. The shell runs its post-answer step.
+ const { outcome, reply } = await deliverFromControl(send, h.deps)
+ expect(outcome.kind).toBe('queued')
+ expect(reply.ok).toBe(true)
+ clearOutcomesAfterControl(h.store, 'send', sendArgs, reply, 'orch')
+
+ // 3. S finishes A and reports success — AFTER the hand-over, BEFORE B reached it.
+ h.tick(100)
+ h.store.record({ nodeId: 'st', outcome: 'succeeded', at: h.tick(0) })
+ expect(h.store.get('st')?.workPending).toBe(true)
+ // 4. S's turn ends: D must not fire on A's word.
+ expect(dFires(h.store)).toBe(false)
+
+ // The same idle edge flushes B into the pane.
+ h.tick(100)
+ h.setBusy(false)
+ onMessagingAgentEvent({ nodeId: 'st', state: 'done', verified: true, newTurn: false } as never, queue)
+ await vi.waitFor(() => expect(queue.depth('st')).toBe(0))
+ await vi.waitFor(() => expect(h.sent).toHaveLength(1))
+ // B landed: A's report is gone, the mark is dropped, and D still waits.
+ await vi.waitFor(() => expect(h.store.get('st')).toBeUndefined())
+ expect(dFires(h.store)).toBe(false)
+
+ // S works on B and reports: now — and only now — D is released.
+ h.tick(100)
+ h.store.record({ nodeId: 'st', outcome: 'succeeded', at: h.tick(0) })
+ expect(h.store.get('st')?.workPending).toBeUndefined()
+ expect(dFires(h.store)).toBe(true)
+ })
+
+ it('a queued message that EXPIRES unread withdraws the report too — D never starts on A', 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
+ const { reply } = await deliverFromControl(send, h.deps)
+ clearOutcomesAfterControl(h.store, 'send', sendArgs, reply, 'orch')
+ h.tick(50)
+ h.store.record({ nodeId: 'st', outcome: 'succeeded', at: h.tick(0) })
+ expect(dFires(h.store)).toBe(false)
+ expect(expire).toBeTruthy()
+ expire!()
+ await vi.waitFor(() => expect(h.store.get('st')).toBeUndefined())
+ expect(dFires(h.store)).toBe(false)
+ // Nothing is left pending: the station's next report counts at once.
+ h.store.record({ nodeId: 'st', outcome: 'succeeded', at: h.tick(10) })
+ expect(dFires(h.store)).toBe(true)
+ })
+})
+
+describe('a report about the NEW work survives however late the answer comes back', () => {
+ it('a direct delivery withdraws only reports older than the moment it STARTED', async () => {
+ const h = harness()
+ h.setBusy(false)
+ // An old report from task A.
+ h.store.record({ nodeId: 'st', outcome: 'failed', at: h.tick(0) - 10 })
+ // While the delivery of B is still in flight (the settle-and-submit wait), S already reports
+ // B — the "stalled / late answer" ordering.
+ h.duringWrite = () => {
+ h.store.record({ nodeId: 'st', outcome: 'succeeded', at: h.tick(50) })
+ }
+ const { outcome, reply } = await deliverFromControl(send, h.deps)
+ expect(outcome.kind).toBe('delivered')
+ // The shell's post-answer step, arriving after that report.
+ h.tick(1_000)
+ clearOutcomesAfterControl(h.store, 'send', sendArgs, reply, 'orch')
+ expect(h.store.get('st')?.outcome).toBe('succeeded')
+ expect(dFires(h.store)).toBe(true)
+ })
+
+ it('an old report is withdrawn when the delivery lands', async () => {
+ const h = harness()
+ h.setBusy(false)
+ h.store.record({ nodeId: 'st', outcome: 'succeeded', at: h.tick(0) - 10 })
+ await deliverFromControl(send, h.deps)
+ expect(h.store.get('st')).toBeUndefined()
+ expect(dFires(h.store)).toBe(false)
+ })
+})
+
+describe('only a task handed through canvas control counts', () => {
+ it('a board comment or a station notice reaching the pane does not withdraw a report', async () => {
+ const h = harness()
+ h.setBusy(false)
+ h.store.record({ nodeId: 'st', outcome: 'succeeded', at: h.tick(0) - 10 })
+ h.store.onHandover({ phase: 'landed', verb: 'board-comment', targetNodeId: 'st', at: h.tick(0) })
+ h.store.onHandover({ phase: 'queued', verb: 'station-notice', targetNodeId: 'st' })
+ expect(h.store.get('st')).toMatchObject({ outcome: 'succeeded' })
+ expect(h.store.get('st')?.workPending).toBeUndefined()
+ })
+})
diff --git a/src/main/station-outcome-wiring.test.ts b/src/main/station-outcome-wiring.test.ts
index dd839adec..8b3351415 100644
--- a/src/main/station-outcome-wiring.test.ts
+++ b/src/main/station-outcome-wiring.test.ts
@@ -45,6 +45,10 @@ describe('desktop main', () => {
expect(handler).toMatch(/finish: finishAnswer/)
})
+ 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)')
+ })
+
it('registers the read channel and pushes every change to the window', () => {
expect(main).toContain('registerStationOutcomeIpc(corePlatform, () => stationOutcomes)')
expect(main).toMatch(/new StationOutcomeStore\(\(records\) =>\s*sendToMain\(IPC\.stationOutcomeChanged, records\)/)
@@ -60,6 +64,10 @@ describe('Server Edition', () => {
expect(block).toContain('onRecorded: () => void factory.refreshArmed()')
})
+ it('wires the same hand-over events into its messaging deps', () => {
+ expect(serverControl).toContain('onHandover: (ev) => stationOutcomes.onHandover(ev)')
+ })
+
it('hands the factory the outcome store, so --after-success is honoured headlessly', () => {
expect(serverControl).toContain('outcomeOf: (nodeId) => stationOutcomes.get(nodeId)')
})
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index ff908a9f8..4acceec7b 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -2113,7 +2113,7 @@ export function Canvas() {
if (!hold || hold.invalid) continue
for (const d of hold.deps) {
const r = outcomeOf(s.byId, d)
- sig += `${d}:${r ? `${r.outcome}@${r.at}` : '-'},`
+ sig += `${d}:${r ? `${r.outcome}@${r.at}${r.workPending ? 'p' : ''}` : '-'},`
}
sig += '|'
}
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index 6dce40c2f..d2f651d95 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -540,6 +540,22 @@ it('lists every station’s own report, and where a success wait stands (--after
expect(controlListingText(after)).toContain('build [terminal] Builder — REPORTED SUCCESS')
})
+it('a report made before queued new work is listed as not counting, and the wait keeps waiting', () => {
+ const rows = storedNodeListing(
+ [
+ { id: 'build', title: 'Builder', agentId: 'claude' },
+ { id: 'rev', title: 'Reviewer', pendingLaunch: { command: 'claude', after: ['build'], afterSuccess: { deps: ['build'], deadlineAt: 99 } } }
+ ],
+ { build: { state: 'done' } },
+ {},
+ 10,
+ { build: { nodeId: 'build', outcome: 'succeeded', at: 1, workPending: true } }
+ )
+ const text = controlListingText(rows)
+ expect(text).toContain('build [terminal] Builder — REPORTED SUCCESS (before new work queued for it; not counted until it reports again)')
+ expect(text).toContain('rev [terminal] Reviewer — WAITING FOR SUCCESS — needs success from: build "Builder" (new work is queued for it; waiting for its next report)')
+})
+
it('a hostile success hold in a stored project neither throws nor reads as met', () => {
const rows = storedNodeListing(
[
diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.ts
index 8ed575505..9db4cf9f5 100644
--- a/src/renderer/lib/controlRouting.ts
+++ b/src/renderer/lib/controlRouting.ts
@@ -228,7 +228,13 @@ export function storedNodeListing(
...(launchState ? { launchState } : {}),
...(launchState === 'queued' && prHold && !prHold.invalid ? { prWait: formatPrWaits(prHold) } : {}),
...(successWait ? { successWait } : {}),
- ...(reported ? { outcome: reported.outcome, ...(reported.note ? { outcomeNote: reported.note } : {}) } : {})
+ ...(reported
+ ? {
+ outcome: reported.outcome,
+ ...(reported.note ? { outcomeNote: reported.note } : {}),
+ ...(reported.workPending ? { outcomeSuperseded: true } : {})
+ }
+ : {})
}
})
}
@@ -255,6 +261,7 @@ export function controlListingText(rows: ReturnType<typeof storedNodeListing>):
(n.prWait ? ` — waits on ${n.prWait}` : '') +
(n.successWait ? ` — needs success from: ${n.successWait}` : '') +
(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' : '')
).join('\n')
}
diff --git a/src/renderer/lib/useSuccessWait.test.tsx b/src/renderer/lib/useSuccessWait.test.tsx
new file mode 100644
index 000000000..bea57e6cb
--- /dev/null
+++ b/src/renderer/lib/useSuccessWait.test.tsx
@@ -0,0 +1,69 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { useAgentStatus } from '../state/agentStatus'
+import { useStationOutcomes } from '../state/stationOutcomes'
+import { useSuccessWait } from './useSuccessWait'
+
+// The badge's label is what a user reads; render the same decision the node renders.
+function Badge({ hold }: { hold: unknown }) {
+ const { tooltip } = useSuccessWait(hold, (id) => (id === 'build' ? 'Builder' : undefined))
+ const label = !tooltip ? 'none' : tooltip.status === 'expired' ? '⚠ EXPIRED' : tooltip.status === 'blocked' ? '⚠ BLOCKED' : 'QUEUED'
+ return <span data-testid="badge">{label}</span>
+}
+
+let root: Root
+let host: HTMLDivElement
+const label = (): string => host.querySelector('[data-testid="badge"]')?.textContent ?? ''
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(1_000_000)
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ useStationOutcomes.getState().setRecords([])
+ useAgentStatus.setState({ byId: { build: { state: 'done', unread: false } } } as never)
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ vi.useRealTimers()
+})
+
+it('flips to ⚠ EXPIRED on its own when the deadline passes — nothing in any store changes then', () => {
+ const hold = { deps: ['build'], deadlineAt: 1_000_000 + 60_000 }
+ act(() => root.render(<Badge hold={hold} />))
+ expect(label()).toBe('QUEUED')
+ act(() => {
+ vi.advanceTimersByTime(59_000)
+ })
+ expect(label()).toBe('QUEUED')
+ act(() => {
+ vi.advanceTimersByTime(2_000)
+ })
+ expect(label()).toBe('⚠ EXPIRED')
+})
+
+it('a blocked wait also turns EXPIRED at its deadline (expiry is what the badge says then)', () => {
+ useStationOutcomes.getState().setRecords([{ nodeId: 'build', outcome: 'failed', at: 1 }])
+ const hold = { deps: ['build'], deadlineAt: 1_000_000 + 1_000 }
+ act(() => root.render(<Badge hold={hold} />))
+ expect(label()).toBe('⚠ BLOCKED')
+ act(() => {
+ vi.advanceTimersByTime(1_100)
+ })
+ expect(label()).toBe('⚠ EXPIRED')
+})
+
+it('follows a report as it arrives, and treats a hostile hold as expired without throwing', () => {
+ const hold = { deps: ['build'], deadlineAt: 1_000_000 + 60_000 }
+ act(() => root.render(<Badge hold={hold} />))
+ act(() => useStationOutcomes.getState().setRecords([{ nodeId: 'build', outcome: 'failed', at: 2 }]))
+ expect(label()).toBe('⚠ BLOCKED')
+ act(() => root.render(<Badge hold={{ deps: 'build' }} />))
+ expect(label()).toBe('⚠ EXPIRED')
+})
diff --git a/src/renderer/lib/useSuccessWait.ts b/src/renderer/lib/useSuccessWait.ts
new file mode 100644
index 000000000..cbf8226b8
--- /dev/null
+++ b/src/renderer/lib/useSuccessWait.ts
@@ -0,0 +1,85 @@
+/**
+ * The QUEUED badge's view of a `--after-success` wait (@shared/station-outcome): where it stands —
+ * waiting, blocked by a failure, expired — the unmet stations, and the deadline, from the same facts
+ * the launch loop judges (the stations' reports, their turn state, whether they still exist).
+ *
+ * A hook of its own, beside the node that renders it, because its one moving part is easy to get
+ * wrong: NOTHING in any store changes when the deadline passes, so the hook arms a timer for it and
+ * the tick must be one of the memo's inputs. A timer whose tick the memo ignores re-renders the node
+ * and hands back the cached "waiting" — the badge then kept QUEUED with "until <a past date>" while
+ * `list` (computed fresh) said EXPIRED. `useSuccessWait.test.tsx` pins the flip.
+ *
+ * Subscriptions are PRIMITIVE signatures over the ids this node waits on, so no other node's report
+ * or hook event re-renders it (the `armedDepSig` discipline).
+ */
+import { useEffect, useMemo, useState } from 'react'
+import {
+ normalizeSuccessWaitHold,
+ successWaitExpired,
+ successWaitStatus,
+ successWaitSummary,
+ type SuccessWaitHold,
+ type SuccessWaitStatus
+} from '@shared/station-outcome'
+import { useAgentStatus } from '../state/agentStatus'
+import { useStationOutcomes } from '../state/stationOutcomes'
+import { successDepFacts } from './pendingLaunch'
+
+export interface SuccessWaitView {
+ /** The hold through the shape rule — a malformed one reads as unreadable and expired. */
+ hold: SuccessWaitHold | undefined
+ /** The station ids it waits on (empty for no hold or an unreadable one). */
+ depIds: readonly string[]
+ /** What the tooltip and the badge label read; undefined when the node has no success wait. */
+ tooltip: { status: SuccessWaitStatus; summary: string; deadline: string } | undefined
+}
+
+const NO_IDS: readonly string[] = []
+
+export function useSuccessWait(
+ rawHold: unknown,
+ /** A node's display title, if it is still on the canvas (`undefined` = gone). */
+ titleOf: (id: string) => string | undefined
+): SuccessWaitView {
+ const hold = useMemo(() => normalizeSuccessWaitHold(rawHold), [rawHold])
+ const depIds = hold && !hold.invalid ? hold.deps : NO_IDS
+ const outcomeSig = useStationOutcomes((s) =>
+ depIds
+ .map((d) => {
+ const r = Object.prototype.hasOwnProperty.call(s.byId, d) ? s.byId[d] : undefined
+ return r ? `${d}:${r.outcome}:${r.at}:${r.workPending ? 'p' : ''}` : `${d}:-`
+ })
+ .join('|')
+ )
+ const stateSig = useAgentStatus((s) =>
+ depIds.map((d) => `${d}:${s.byId[d]?.state ?? '-'}:${s.byId[d]?.lastTurnError ? 'e' : ''}`).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.
+ const [clock, setClock] = useState(0)
+ useEffect(() => {
+ if (!hold || successWaitExpired(hold, Date.now())) return
+ const t = setTimeout(
+ () => setClock((v) => v + 1),
+ Math.min(Math.max(0, hold.deadlineAt - Date.now()) + 50, 2 ** 31 - 1)
+ )
+ return () => clearTimeout(t)
+ }, [hold, clock])
+ const tooltip = useMemo(() => {
+ if (!hold) return undefined
+ const live = new Set(depIds.filter((d) => titleOf(d) !== undefined))
+ const facts = (d: string) =>
+ successDepFacts(d, useAgentStatus.getState().byId, live, useStationOutcomes.getState().byId)
+ const name = (d: string) => titleOf(d) || d
+ return {
+ status: successWaitStatus(hold, facts, Date.now()),
+ summary: hold.invalid ? 'a success wait that could not be read' : successWaitSummary(hold, facts, name),
+ deadline: hold.invalid
+ ? 'the project file holds an unreadable one'
+ : 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])
+ return { hold, depIds, tooltip }
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 07bb5dfd3..8e260e298 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -231,14 +231,8 @@ import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../sta
import { codexApprovalCaps } from '../state/codexCli'
import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'
import { useLaunchDelivery } from '../state/launchDelivery'
-import { erroredDeps, launchTooltip, successDepFacts } from '../lib/pendingLaunch'
-import {
- normalizeSuccessWaitHold,
- successWaitExpired,
- successWaitStatus,
- successWaitSummary
-} from '@shared/station-outcome'
-import { useStationOutcomes } from '../state/stationOutcomes'
+import { erroredDeps, launchTooltip } from '../lib/pendingLaunch'
+import { useSuccessWait } from '../lib/useSuccessWait'
import { StationFailedChip } from '../components/StationFailedChip'
import { prHoldExpired, prHoldSummary } from '../lib/prWait'
import { pullBoardFor, useGitHubIssues } from '../state/githubIssues'
@@ -2062,13 +2056,18 @@ export function TerminalNode({
!pendingLaunch?.awaitSetupGroup &&
!pendingLaunch?.afterPr &&
!pendingLaunch?.afterSuccess
- // Through the shape rule, memoized on the raw value: a malformed hold (a peer's mutation, a
- // hand-edited file) reads as an unreadable, expired hold rather than throwing during render.
- const rawSuccessHold = pendingLaunch?.afterSuccess
- const successHold = useMemo(() => normalizeSuccessWaitHold(rawSuccessHold), [rawSuccessHold])
+ // `--after-success`: where the wait stands (lib/useSuccessWait — the hold through the shape rule,
+ // its stations, and the tooltip, which flips to EXPIRED on its own deadline tick).
+ const successWait = useSuccessWait(
+ pendingLaunch?.afterSuccess,
+ (depId) => {
+ const n = getNode(depId) as CanvasNode | undefined
+ return n ? ((n.data.title as string) || '') : undefined
+ }
+ )
// The stations a `--after-success` wait names are ALSO in `after`; the tooltip speaks of them in
// the success sentence, so the plain list leaves them out rather than naming them twice.
- const successDepIds = successHold && !successHold.invalid ? successHold.deps : []
+ const successDepIds = successWait.depIds
const pendingWaitingOn = [
...(pendingLaunch?.after ?? []).filter((depId) => !successDepIds.includes(depId)).map(
(depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId
@@ -2111,45 +2110,7 @@ export function TerminalNode({
deadline: prHold.invalid ? 'the project file holds an unreadable one' : new Date(prHold.deadlineAt).toLocaleString()
}
: undefined
- // `--after-success`: where the wait stands, from the same facts the launch loop judges (the
- // stations' reports, their turn state, whether they still exist). A PRIMITIVE signature per store,
- // selected only for a node that has such a wait, so no other node re-renders on a report or a
- // hook event.
- const successOutcomeSig = useStationOutcomes((s) =>
- successDepIds.map((d) => {
- const r = Object.prototype.hasOwnProperty.call(s.byId, d) ? s.byId[d] : undefined
- return r ? `${d}:${r.outcome}:${r.at}` : `${d}:-`
- }).join('|')
- )
- const successStateSig = useAgentStatus((s) =>
- successDepIds.map((d) => `${d}:${s.byId[d]?.state ?? '-'}:${s.byId[d]?.lastTurnError ? 'e' : ''}`).join('|')
- )
- const [, setSuccessClock] = useState(0)
- useEffect(() => {
- if (!successHold || successWaitExpired(successHold, Date.now())) return
- const t = setTimeout(
- () => setSuccessClock((v) => v + 1),
- Math.min(successHold.deadlineAt - Date.now() + 50, 2 ** 31 - 1)
- )
- return () => clearTimeout(t)
- }, [successHold])
- const successTooltip = useMemo(() => {
- if (!successHold) return undefined
- const live = new Set(successDepIds.filter((d) => !!getNode(d)))
- const facts = (d: string) =>
- successDepFacts(d, useAgentStatus.getState().byId, live, useStationOutcomes.getState().byId)
- const name = (d: string) => ((getNode(d) as CanvasNode | undefined)?.data.title as string) || d
- return {
- status: successWaitStatus(successHold, facts, Date.now()),
- summary: successHold.invalid
- ? 'a success wait that could not be read'
- : successWaitSummary(successHold, facts, name),
- deadline: successHold.invalid
- ? 'the project file holds an unreadable one'
- : new Date(successHold.deadlineAt).toLocaleString()
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps -- the two signatures are the triggers
- }, [successHold, successOutcomeSig, successStateSig, getNode])
+ const successTooltip = successWait.tooltip
const successExpired = successTooltip?.status === 'expired'
const successBlocked = successTooltip?.status === 'blocked'
const pendingErroredOn = erroredDepIds
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
index ddced8243..6580d5393 100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@ -236,7 +236,10 @@ export async function initServerCanvasControl(
callerOwnsTarget: (sourceNodeId, targetNodeId) =>
factory.ownsSpawn(sourceNodeId, targetNodeId),
customAgents: () => deps.settings().customAgents,
- appendBoardLog: (projectId, entry) => deps.boardLog.append(projectId, entry)
+ 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)
}
const queue = createDeliveryQueue(messaging)
messaging.queue = queue
@@ -316,8 +319,9 @@ export async function initServerCanvasControl(
const baseHandler = createServerEditionControlHandler(actions)
return {
- // New work handed to a station (`send` / `reply` / `run` aimed at it) withdraws its outcome
- // report — the "new task" rule in core/station-outcome-store.ts, applied after the answer.
+ // New work typed into a station by `run` withdraws its older outcome report — the "new task"
+ // 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) => {
const reply = await baseHandler(req)
clearOutcomesAfterControl(stationOutcomes, req.verb, req.args, reply, req.nodeId)
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index 1bb19b16c..a7f18bc44 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -1258,6 +1258,20 @@ describe('HeadlessNodeFactory', () => {
expect(still?.pendingLaunch?.afterSuccess).toBeDefined()
})
+ it('holds when the station\'s last turn ERRORED after it reported success (#521, like the desktop)', async () => {
+ states['term-upstream'] = 'done'
+ const id = await openWaiting()
+ report('term-upstream', 'succeeded')
+ factory.onAgentEvent({ nodeId: 'term-upstream', state: 'done', errored: true })
+ await factory.refreshArmed()
+ expect(pty.sends).toEqual([])
+ // The next genuine new turn clears the verdict; a clean end of it releases.
+ factory.onAgentEvent({ nodeId: 'term-upstream', state: 'working', newTurn: true })
+ states['term-upstream'] = 'done'
+ factory.onAgentEvent({ nodeId: 'term-upstream', state: 'done' })
+ await vi.waitFor(() => expect(pty.sends).toEqual([{ nodeId: id, text: "claude 'ship it'" }]))
+ })
+
it('a reported success mid-turn waits for the turn to end', async () => {
states['term-upstream'] = 'working'
await openWaiting()
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index 2b92a747f..761811be9 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -582,6 +582,10 @@ export class HeadlessNodeFactory {
private ownership: HeadlessNodeOwnership
/** Fresh server-spawned agents that have not emitted their first real working turn yet. */
private awaitingFirstWorking = new Set<string>()
+ /** Stations whose LAST turn ended on an API/model error (#521, the `errored` flag on a `done`),
+ * from this edition's own event stream — the desktop's `lastTurnError`, kept here so a success
+ * wait holds on an errored turn on both editions. Cleared by the next genuine new turn. */
+ private lastTurnErrored = new Set<string>()
/**
* Server-local `open-project` grants. The browser shell's grant ledger is process-local too,
* but Server Edition has its own process and handler. A service restart deliberately clears
@@ -731,7 +735,8 @@ export class HeadlessNodeFactory {
}
/** 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), plus its report. */
+ * 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. */
private successFacts(
project: Project,
depId: string,
@@ -742,7 +747,11 @@ export class HeadlessNodeFactory {
const reported = this.deps.outcomeOf?.(depId)
return {
exists,
- turnDone: exists && !this.awaitingFirstWorking.has(depId) && state === 'done',
+ turnDone:
+ exists &&
+ !this.awaitingFirstWorking.has(depId) &&
+ !this.lastTurnErrored.has(depId) &&
+ state === 'done',
...(reported ? { outcome: reported } : {})
}
}
@@ -1667,8 +1676,10 @@ export class HeadlessNodeFactory {
return Promise.resolve()
}
- onAgentEvent(event: Pick<NormalizedAgentEvent, 'nodeId' | 'state'>): void {
+ onAgentEvent(event: Pick<NormalizedAgentEvent, 'nodeId' | 'state' | 'errored' | 'newTurn'>): void {
if (this.stopped || !event?.nodeId) return
+ if (event.state === 'done' && event.errored === true) this.lastTurnErrored.add(event.nodeId)
+ else if (event.newTurn === true) this.lastTurnErrored.delete(event.nodeId)
if (event.state === 'working') this.awaitingFirstWorking.delete(event.nodeId)
if (event.state === 'working' || event.state === 'done') void this.refreshArmed(event)
}
diff --git a/src/shared/station-outcome.test.ts b/src/shared/station-outcome.test.ts
index d7d268eec..820d61cb9 100644
--- a/src/shared/station-outcome.test.ts
+++ b/src/shared/station-outcome.test.ts
@@ -91,6 +91,14 @@ describe('sanitizeOutcomeRecords — the IPC/bridge boundary', () => {
{ nodeId: 'a1', outcome: 'succeeded', at: 1 },
{ nodeId: 'a2', outcome: 'failed', at: 2, note: 'x y' }
])
+ // The work-pending flag crosses the boundary only as a literal true.
+ expect(sanitizeOutcomeRecords([
+ { nodeId: 'a1', outcome: 'succeeded', at: 1, workPending: true },
+ { nodeId: 'a2', outcome: 'succeeded', at: 1, workPending: 'yes' }
+ ])).toEqual([
+ { nodeId: 'a1', outcome: 'succeeded', at: 1, workPending: true },
+ { nodeId: 'a2', outcome: 'succeeded', at: 1 }
+ ])
expect(sanitizeOutcomeRecords({ nodeId: 'a1' })).toEqual([])
})
})
@@ -229,10 +237,21 @@ describe('evaluateSuccessDep — the whole matrix', () => {
expect(at({ exists: true, turnDone: false })).toBe('waiting')
})
+ it('a report made before new work that is still QUEUED for the station does not count', () => {
+ expect(at({ exists: true, turnDone: true, outcome: { outcome: 'succeeded', workPending: true } })).toBe('waiting')
+ // Not even a failure blocks: it speaks for the task before, and the next one is on its way.
+ expect(at({ exists: true, turnDone: true, outcome: { outcome: 'failed', workPending: true } })).toBe('waiting')
+ expect(at({ exists: false, turnDone: false, outcome: { outcome: 'succeeded', workPending: true } })).toBe('blocked')
+ })
+
it('a CLOSED station counts only with a success reported before it went', () => {
expect(at({ exists: false, turnDone: false, outcome: { outcome: 'succeeded' } })).toBe('met')
expect(at({ exists: false, turnDone: false })).toBe('blocked')
expect(at({ exists: false, turnDone: false, outcome: { outcome: 'failed' } })).toBe('blocked')
+ // Reports do not survive a restart, and the text says so — only `run` / ▶ move it then.
+ expect(evaluateSuccessDep('a1', { exists: false, turnDone: false }).detail).toBe(
+ 'closed without reporting success in this app run'
+ )
})
})
diff --git a/src/shared/station-outcome.ts b/src/shared/station-outcome.ts
index 5941860f2..285e265f2 100644
--- a/src/shared/station-outcome.ts
+++ b/src/shared/station-outcome.ts
@@ -44,6 +44,10 @@ export interface StationOutcomeRecord {
* into a pane, never read as a gate. */
note?: string
at: number
+ /** New work (a `send` / `reply`) is QUEUED for this station and has not reached it yet: this
+ * report was made before that work, so it does not count — a success wait keeps waiting. Set by
+ * the core store on what it publishes; never persisted. */
+ workPending?: true
}
/** The verb a station runs about ITSELF. Named apart from `report-issue` on purpose: "report" alone
@@ -127,7 +131,13 @@ export function sanitizeOutcomeRecords(raw: unknown): StationOutcomeRecord[] {
if (!isStationOutcome(r.outcome)) continue
if (typeof r.at !== 'number' || !Number.isFinite(r.at)) continue
const note = sanitizeOutcomeNote(r.note)
- out.push({ nodeId: r.nodeId, outcome: r.outcome, at: r.at, ...(note ? { note } : {}) })
+ out.push({
+ nodeId: r.nodeId,
+ outcome: r.outcome,
+ at: r.at,
+ ...(note ? { note } : {}),
+ ...(r.workPending === true ? { workPending: true as const } : {})
+ })
}
return out
}
@@ -293,7 +303,7 @@ export interface SuccessDepFacts {
* counts as that (`depSatisfied` on the desktop, `stateOf === 'done'` on the Server Edition). */
turnDone: boolean
/** Its latest report in this app run, if any. */
- outcome?: Pick<StationOutcomeRecord, 'outcome' | 'note'>
+ outcome?: Pick<StationOutcomeRecord, 'outcome' | 'note' | 'workPending'>
}
export type SuccessDepState = 'met' | 'waiting' | 'blocked'
@@ -317,10 +327,18 @@ export interface SuccessDepReport {
* - a DELETED station: met only if it reported success before it went (a closed station can never
* report again, and closing one is exactly how an orchestrator abandons a failed attempt — reading
* the deletion as success, which is `--after`'s rule, would release dependents on a failure).
- * Closed without a success report ⇒ blocked, with the deadline and ▶ as the way out.
+ * Closed without a success report ⇒ blocked, with the deadline and ▶ as the way out. Reports do
+ * not survive an app restart, so a station closed before one reads this way afterwards too.
+ * - a report made before new work that is still QUEUED for the station (`workPending`) is no
+ * report: it speaks for the task before, and the station has not even received the next one.
*/
export function evaluateSuccessDep(id: string, facts: SuccessDepFacts): SuccessDepReport {
const r = (state: SuccessDepState, detail: string): SuccessDepReport => ({ id, state, detail })
+ if (facts.outcome?.workPending) {
+ return facts.exists
+ ? r('waiting', 'new work is queued for it; waiting for its next report')
+ : r('blocked', 'closed while new work was queued for it')
+ }
const reported = facts.outcome
if (reported?.outcome === 'failed') {
return r('blocked', `reported failure${reported.note ? `: "${reported.note}"` : ''}`)
@@ -329,7 +347,9 @@ export function evaluateSuccessDep(id: string, facts: SuccessDepFacts): SuccessD
if (facts.exists && !facts.turnDone) return r('waiting', 'reported success; waiting for its turn to end')
return r('met', 'reported success')
}
- return facts.exists ? r('waiting', 'no outcome reported yet') : r('blocked', 'closed without reporting success')
+ return facts.exists
+ ? r('waiting', 'no outcome reported yet')
+ : r('blocked', 'closed without reporting success in this app run')
}
export function successWaitReports(