Skip to content

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

fix(agents): an errored turn is distinguishable, and does not release --after

enesee608ea702c9
diff --git a/CLAUDE.md b/CLAUDE.md
index 588ebeaec..abf98bb7a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1513,7 +1513,8 @@ else, and its context links must keep classifying across restarts).
every dep reports `done`. This is what makes the canvas a DAG instead of a fan-out. Load-bearing
details: (1) **an unknown agent state is NOT "satisfied"** — right after a fan-out no upstream has
emitted a hook event yet, and reading "no news" as "finished" would fire every dependent
- instantly; a **deleted** dep IS satisfied (it can never report). (2) Only `hasHooks` agents may be
+ instantly; a **deleted** dep IS satisfied (it can never report); and a dep that is `done` with a
+ live **`lastTurnError`** is NOT (issue #521, below). (2) Only `hasHooks` agents may be
waited on — a plain terminal never reports done, so `resolveAfter` **refuses** it rather than
letting `launchesToFire` (which cannot tell "never will" from "not yet") hang the node forever.
(3) If the deps are **already satisfied at creation**, the node is NOT armed: the command stays
@@ -1563,6 +1564,34 @@ else, and its context links must keep classifying across restarts).
was launching a bare CLI on mount — the session the hold exists to prevent — and the held launch
then arrived as TEXT typed into it rather than as the command it is. The delivery race used to
mask it; gating delivery on the shell settling would have made it deterministic.
+ **(9) An ERRORED upstream does not release its dependents** (issue #521, 2026-09).
+ `--after` fires on idle, and a station whose turn dies on an API/model error reaches idle
+ **immediately** — so a malformed-prompt station looked healthy from every surface an
+ orchestrator can read, and the whole chain armed behind it launched on what it had not
+ produced. The signal was already there and was being thrown away: claude and grok both fire
+ **`StopFailure`** instead of `Stop` on an errored turn (already in `CLAUDE_HOOK_EVENTS` /
+ `GROK_HOOK_EVENTS` — without the subscription the badge sticks on RUNNING), and both
+ normalizers collapsed it to a plain `done`. It now carries **`errored`** on
+ `NormalizedAgentEvent`, which `agentStatus` keeps as **`lastTurnError: {at}`**.
+ Three things about the shape, each deliberate: (a) it is an **annotation, not a fifth
+ `AgentState`** — an errored station IS idle, the two facts coexist, and a fifth state would
+ ripple through both raw listeners, the parity test and the mobile mirror for a fact that is
+ not a state; (b) it is set in `src/shared`'s normalizers, so **both shells change by
+ construction** — there is nothing to keep in parity; (c) it is **TRANSIENT** like `state`,
+ because after a relaunch nothing armed can fire anyway and a restored verdict would describe
+ another app run's turn. It is **cleared by the next genuine new turn** — not by any
+ intermediate transition, which says nothing about whether that turn produced something — so
+ the refusal ends by itself when the station answers successfully. Firing with a WARNING was
+ considered and dropped: a dependent that has launched cannot un-launch. Surfaces: a
+ **TURN FAILED** chip on the node (red, no pulse — a verdict on a turn that is over, not
+ something being waited for), the QUEUED tooltip naming the errored upstream instead of
+ promising a wait, and a **`LAST TURN ERRORED` marker on the `list` rows** — on the ROW
+ because a seven-station fan-out should cost one call to learn this, not seven. **No error
+ TEXT is claimed**: whether the hook payload carries the failure message has not been
+ measured, and `last_assistant_message` is the previous assistant turn rather than the error,
+ so 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.
**Review panel (`verify`, 2026-07):** `verify --node <id> [--lenses …] [--focus …] [--agent …]
[--synthesis off]` opens one reviewer per LENS, each armed behind the target (`--after`) and
bridged to it, wrapped in a `Verify: <title>` group, plus a judge armed behind the whole panel.
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 14d0707c8..015d981c0 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -386,6 +386,18 @@ describe('parseControlRequest', () => {
}
})
+ it('both agent-facing texts say an ERRORED station does not release its dependents (#521)', () => {
+ for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {
+ // The contract changed under `--after`: "gone idle" no longer releases a dependent, because
+ // a station whose turn died on an API error reaches idle IMMEDIATELY. A text still promising
+ // the old rule tells an orchestrator its chain launched on something that produced nothing.
+ expect(body.toLowerCase()).toContain('successfully')
+ expect(body).toContain('LAST TURN ERRORED')
+ // And a way out, or the orchestrator is told it is stuck without being told what to do.
+ expect(body.toLowerCase()).toMatch(/nudge|retry/)
+ }
+ })
+
it('both agent-facing texts document the sticky verb', () => {
for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {
expect(body).toContain('`sticky --node')
diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.ts
index d49832aa2..3d3bc5dfd 100644
--- a/src/main/canvas-control-core.ts
+++ b/src/main/canvas-control-core.ts
@@ -313,8 +313,11 @@ export function buildCanvasControlInstructions(shimPath: string): string {
`- \`open-agent --agent ${agentChoices} [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--project <id>]\` — open`,
' any agent CLI. `--group` parents the node(s) into a group frame; a worktree-bound group also',
' hands its worktree path down as the cwd. `--after <id,id>` opens the node ARMED: it does not',
- ' start until every listed station has gone idle, and is context-linked to them so it can read',
- ' their work when it wakes — use it for "B needs what A produced" instead of polling. Only',
+ ' start until every listed station has finished a turn SUCCESSFULLY, and is context-linked to',
+ ' them so it can read their work when it wakes — use it for "B needs what A produced" instead',
+ ' of polling. A station whose turn ended on an API error does NOT release its dependents even',
+ ' though it is idle (`list` marks it LAST TURN ERRORED); nudge or retry it, or run the armed',
+ ' node yourself. Only',
` status-reporting agent nodes (${statusAgents}, or custom agents based on them) may be waited on; a plain terminal never`,
' reports finishing, so waiting on one is refused. `--project <id>` opens the node(s) in another',
' project instead of yours. It accepts exactly two things — any other id is refused: your OWN',
@@ -696,6 +699,10 @@ ${dryRunDocLines().join('\n')}
Verbs:
- \`list\` — list current nodes (id, kind, title). Start here when you need a node id.
+ A row ending **LAST TURN ERRORED** is a station whose last turn died on an API/model error:
+ it is idle, but it produced nothing, so do not read its output or build on it. The marker
+ is on the row on purpose — a fan-out of seven stations should cost one call to learn this,
+ not seven. It clears itself the moment that station completes another turn.
- \`help\` — print the verb list. The shim answers this itself, without reaching the app, so it
is also what to run when you are unsure whether the control endpoint is alive.
- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--project <id>]\` — open N plain terminals (default 1).
@@ -704,13 +711,17 @@ Verbs:
\`--group\` parents the node(s) into an existing group frame; a worktree-bound group also
hands its worktree path down as the cwd.
\`--after <id,id>\` opens the node **armed**: it does NOT start yet, and launches itself once
- every listed station has gone idle — that is how you express "B needs what A produces" without
+ every listed station has finished a turn successfully — that is how you express "B needs what A produces" without
sitting in a poll loop. The armed node is also context-linked to each station it waits on, so
it can read their work the moment it wakes. Only agent nodes that report status
(${statusAgents}, or custom agents based on them) can be waited on — waiting on a plain terminal is refused, because a
plain terminal never reports finishing and the node would hang forever. Note the semantics:
"idle" is the end of a station's TURN, not proof its whole job is done — right for a station
given one self-contained prompt, wrong if you expect a long conversation first.
+ A station whose turn ended on an API/model ERROR does NOT release its dependents, even
+ though it is idle: it reached idle immediately and produced nothing, so firing would start
+ the chain on bad ground. \`list\` marks it LAST TURN ERRORED. Nudge or retry that station —
+ one successful turn releases everything armed behind it — or run the armed node yourself.
\`--project <id>\` opens the node(s) in another project instead of yours. It accepts exactly
two things — any other id is refused: your OWN project id, which behaves exactly as if the flag
were omitted (a normal open, view switch included); or an id \`open-project\` returned to YOU
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index e438ba49a..489004d28 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -9254,15 +9254,27 @@ export function Canvas() {
try {
switch (verb) {
case 'list': {
+ // The error marker rides the LIST rows (issue #521), not a per-node read: an
+ // orchestrator running seven stations already calls `list`, and asking each one
+ // separately would be seven round trips to learn the one thing that changes what it
+ // does next.
+ const st = useAgentStatus.getState().byId
const list = nodesRef.current.map((n) => ({
id: n.id,
kind: n.type,
- title: n.data.title as string
+ title: n.data.title as string,
+ ...(st[n.id]?.lastTurnError ? { lastTurnErrored: true } : {})
}))
reply({
ok: true,
result: list,
- message: list.map((n) => `${n.id} [${n.kind}] ${n.title}`).join('\n')
+ message: list
+ .map(
+ (n) =>
+ `${n.id} [${n.kind}] ${n.title}` +
+ (n.lastTurnErrored ? ' — LAST TURN ERRORED' : '')
+ )
+ .join('\n')
})
return
}
@@ -11035,7 +11047,15 @@ export function Canvas() {
// `e.verified` is the identity evidence for this very transition (hook-server labels it);
// it was in scope here and dropped on the floor before the store had a field for it.
if (e.state && !stuckRescueSkip)
- cs.setState(e.nodeId, e.state, e.agentId, e.newTurn, e.pendingId, e.verified)
+ cs.setState(
+ e.nodeId,
+ e.state,
+ e.agentId,
+ e.newTurn,
+ e.pendingId,
+ e.verified,
+ e.errored
+ )
if (e.newTurn) an.clearForParent(e.nodeId) // genuine new turn → drop the previous fan-out
if (e.newTurn && e.task) {
// Prompt-prefix fallback for /loop|/schedule|/cron when the natural-language
diff --git a/src/renderer/lib/erroredTurn.test.ts b/src/renderer/lib/erroredTurn.test.ts
new file mode 100644
index 000000000..c039f07d3
--- /dev/null
+++ b/src/renderer/lib/erroredTurn.test.ts
@@ -0,0 +1,173 @@
+// Issue #521 — a station whose first turn dies must not look like one that finished.
+//
+// Observed in a seven-station run: two stations were launched with a malformed prompt, errored
+// immediately, and looked healthy from every surface an orchestrator can read. The damage is not
+// the missing badge — `--after` fires on idle, and an errored station reaches idle IMMEDIATELY, so
+// every downstream station armed behind it launched against an upstream that had produced nothing.
+//
+// The three legs of the fix, end to end: the hook says it (`normalizeClaude`/`normalizeGrok` on
+// `StopFailure`, which both agents fire INSTEAD of `Stop`), the store keeps it as an annotation
+// beside the state rather than as a fifth `AgentState` (an errored station IS idle — the two facts
+// coexist), and `depSatisfied` refuses it.
+import { beforeEach, describe, expect, it } from 'vitest'
+import { normalizeClaude, normalizeGrok } from '@shared/agents/normalize'
+import { useAgentStatus } from '../state/agentStatus'
+import { erroredDeps, launchesToFire, launchTooltip, unmetDeps } from './pendingLaunch'
+import type { StatusById } from './pendingLaunch'
+
+const LIVE = new Set(['up'])
+const armed = (after: string[]) => ({ id: 'down', data: { pendingLaunch: { after, command: 'go' } } })
+
+describe('the hook says it (normalize)', () => {
+ const env = (payload: Record<string, unknown>) => ({
+ nodeId: 'n1',
+ agentId: 'claude' as const,
+ payload
+ })
+
+ it('claude StopFailure carries `errored` beside its `done`', () => {
+ const e = normalizeClaude(env({ hook_event_name: 'StopFailure' }))
+ expect(e).toMatchObject({ kind: 'state', state: 'done', errored: true })
+ })
+
+ it('an ordinary claude Stop does NOT', () => {
+ // The whole point: the two must stop being byte-identical.
+ const e = normalizeClaude(env({ hook_event_name: 'Stop' }))
+ expect(e).toMatchObject({ state: 'done' })
+ expect(e?.errored).toBeFalsy()
+ })
+
+ it('an INTERRUPTED turn is not an errored one', () => {
+ // The user pressed Esc. Nothing failed, and the station should still release its dependents.
+ const e = normalizeClaude(env({ hook_event_name: 'Stop', is_interrupt: true }))
+ expect(e).toMatchObject({ state: 'done', interrupted: true })
+ expect(e?.errored).toBeFalsy()
+ })
+
+ it('grok reports it the same way — same field, one definition, both shells', () => {
+ const e = normalizeGrok({
+ nodeId: 'n1',
+ agentId: 'grok',
+ payload: { hookEventName: 'stop_failure', sessionId: 's1' }
+ })
+ expect(e).toMatchObject({ state: 'done', errored: true })
+ })
+})
+
+describe('the store keeps it as an annotation, not a state', () => {
+ let n = 0
+ const nid = () => `n${++n}`
+ beforeEach(() => useAgentStatus.setState({ byId: {} }))
+
+ it('records the error without displacing `done`', () => {
+ const id = nid()
+ useAgentStatus.getState().setState(id, 'done', 'claude', false, undefined, false, true)
+ const e = useAgentStatus.getState().byId[id]
+ expect(e.state).toBe('done')
+ expect(e.lastTurnError?.at).toBeGreaterThan(0)
+ })
+
+ it('an ordinary done leaves it unset', () => {
+ const id = nid()
+ useAgentStatus.getState().setState(id, 'done', 'claude')
+ expect(useAgentStatus.getState().byId[id].lastTurnError).toBeUndefined()
+ })
+
+ it('the next genuine new turn retires the verdict', () => {
+ const id = nid()
+ const s = useAgentStatus.getState()
+ s.setState(id, 'done', 'claude', false, undefined, false, true)
+ s.setState(id, 'working', 'claude', true)
+ expect(useAgentStatus.getState().byId[id].lastTurnError).toBeUndefined()
+ })
+
+ it('an intermediate transition that is NOT a new turn leaves it standing', () => {
+ // Between the failure and the next prompt a station still emits tool/notification events. None
+ // of them says anything about whether that turn produced something.
+ const id = nid()
+ const s = useAgentStatus.getState()
+ s.setState(id, 'done', 'claude', false, undefined, false, true)
+ s.setState(id, 'blocked', 'claude')
+ expect(useAgentStatus.getState().byId[id].lastTurnError).toBeDefined()
+ })
+
+ it('a StopFailure re-asserting the SAME state still lands', () => {
+ // The same-state path refreshes freshness IN PLACE to avoid a re-render — which is exactly what
+ // a badge appearing needs, so an event that moves the verdict must not take that path.
+ const id = nid()
+ const s = useAgentStatus.getState()
+ s.setState(id, 'done', 'claude')
+ s.setState(id, 'done', 'claude', false, undefined, false, true)
+ expect(useAgentStatus.getState().byId[id].lastTurnError).toBeDefined()
+ })
+
+ it('is transient — never reaches the persisted whitelist', async () => {
+ // Same rule as `state` and `lastEventAt`: after a relaunch no hook has spoken, nothing armed
+ // can fire anyway, and a restored verdict would describe a turn from another app run.
+ const { vi } = await import('vitest')
+ const mem = new Map<string, string>()
+ vi.stubGlobal('localStorage', {
+ getItem: (k: string) => mem.get(k) ?? null,
+ setItem: (k: string, v: string) => void mem.set(k, v),
+ removeItem: (k: string) => void mem.delete(k)
+ })
+ const id = nid()
+ const s = useAgentStatus.getState()
+ s.setState(id, 'done', 'claude', false, undefined, false, true)
+ s.setHibernated(id, true) // a write that DOES reach disk, so there is something to inspect
+ expect(mem.get('nodeterm.agentStatus') ?? '').not.toContain('lastTurnError')
+ expect(mem.get('nodeterm.agentStatus') ?? '').toContain('hibernated')
+ vi.unstubAllGlobals()
+ })
+})
+
+describe('depSatisfied refuses an errored upstream (the arming bug)', () => {
+ const done: StatusById = { up: { state: 'done' } }
+ const erroredDone: StatusById = { up: { state: 'done', lastTurnError: { at: 1 } } }
+
+ it('fires on a clean done', () => {
+ expect(launchesToFire([armed(['up'])], done, LIVE)).toEqual([{ id: 'down', command: 'go' }])
+ })
+
+ it('does NOT fire on a done that errored', () => {
+ // The seven-station run: this is the launch that started a chain on bad ground.
+ expect(launchesToFire([armed(['up'])], erroredDone, LIVE)).toEqual([])
+ })
+
+ it('reports the upstream as still unmet, and says WHY', () => {
+ expect(unmetDeps(armed(['up']), erroredDone, LIVE)).toEqual(['up'])
+ expect(erroredDeps(armed(['up']), erroredDone, LIVE)).toEqual(['up'])
+ })
+
+ it('distinguishes "errored" from "has not finished" — only one of them is named', () => {
+ const working: StatusById = { up: { state: 'working' } }
+ expect(unmetDeps(armed(['up']), working, LIVE)).toEqual(['up'])
+ expect(erroredDeps(armed(['up']), working, LIVE)).toEqual([])
+ })
+
+ it('a DELETED errored dep is still satisfied — it can never report again', () => {
+ // The existing rule, unchanged: treating it as pending would strand the dependent forever.
+ expect(launchesToFire([armed(['up'])], erroredDone, new Set())).toEqual([
+ { id: 'down', command: 'go' }
+ ])
+ expect(erroredDeps(armed(['up']), erroredDone, new Set())).toEqual([])
+ })
+
+ it('the refusal ends by itself once the station completes a turn', () => {
+ // No manual clearing, no flag to unset: the next genuine new turn retires the verdict in the
+ // store, and the very next sweep of `launchesToFire` releases everything armed behind it.
+ expect(launchesToFire([armed(['up'])], done, LIVE)).toHaveLength(1)
+ })
+
+ it('the QUEUED tooltip names the errored upstream instead of promising a wait', () => {
+ const t = launchTooltip(undefined, 'Contract station', 'go', 'Contract station')
+ expect(t).toContain('ended its last turn on an error')
+ expect(t).not.toContain('Waiting for')
+ // The manual escape must still be offered — a dependent held on a dead upstream needs a way out.
+ expect(t).toContain('▶')
+ })
+
+ it('an ordinary hold still reads as an ordinary hold', () => {
+ expect(launchTooltip(undefined, 'Contract station', 'go')).toContain('Waiting for')
+ })
+})
diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.ts
index 54eacf24d..6a5c667a7 100644
--- a/src/renderer/lib/pendingLaunch.ts
+++ b/src/renderer/lib/pendingLaunch.ts
@@ -13,7 +13,10 @@ export interface ArmedNode {
}
/** The subset of the agentStatus store this module reads. */
-export type StatusById = Record<string, { state?: AgentState } | undefined>
+export type StatusById = Record<
+ string,
+ { state?: AgentState; lastTurnError?: { at: number } } | undefined
+>
export interface LaunchToFire {
id: string
@@ -35,10 +38,33 @@ export interface LaunchToFire {
* exists but has reported nothing yet) is deliberately NOT satisfied: right after a fan-out the
* upstream stations have not emitted a hook event yet, and reading "no news" as "finished"
* would fire every dependent immediately — the exact bug that makes a dependency edge useless.
+ *
+ * A dep that is `done` **with a live `lastTurnError`** is refused (issue #521). An errored station
+ * reaches idle IMMEDIATELY and looked healthy from every surface an orchestrator can read, so a
+ * whole dependency chain launched against an upstream that had produced nothing. Firing with a
+ * warning instead was considered and dropped: a dependent that has already launched cannot
+ * un-launch, so the warning would arrive after the damage. The armed node keeps its manual ▶
+ * run-now escape, so the human — or the orchestrator, after a retry — is never stuck.
+ *
+ * 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.
*/
function depSatisfied(depId: string, status: StatusById, live: ReadonlySet<string>): boolean {
if (!live.has(depId)) return true
- return status[depId]?.state === 'done'
+ const st = status[depId]
+ return st?.state === 'done' && !st.lastTurnError
+}
+
+/** 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(
+ node: ArmedNode,
+ status: StatusById,
+ live: ReadonlySet<string>
+): string[] {
+ return (node.data.pendingLaunch?.after ?? []).filter(
+ (d) => live.has(d) && status[d]?.state === 'done' && !!status[d]?.lastTurnError
+ )
}
/**
@@ -170,9 +196,19 @@ export type LaunchDelivery =
export function launchTooltip(
delivery: LaunchDelivery | undefined,
waitingOn: string,
- command: string
+ command: string,
+ erroredOn?: string
): string {
const runs = `Runs:\n${command}`
+ // Issue #521: an errored upstream is idle, so without this the tooltip would say "waiting for X
+ // to finish" about a station that finished twenty minutes ago. Named first, because it is the
+ // one case where waiting will not end on its own.
+ if (erroredOn)
+ return (
+ `${erroredOn} ended its last turn on an error, so this is held rather than started on ` +
+ 'what it did not produce.\n' +
+ `Retry or nudge it — a successful turn releases this — or press ▶ to run it now.\n${runs}`
+ )
if (delivery?.kind === 'failed')
return (
`This session did not accept its launch — ${delivery.attempts} ` +
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 3349b4228..908a46033 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -143,7 +143,7 @@ import { useSettings } from '../state/settings'
import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../state/codexIdentity'
import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'
import { useLaunchDelivery } from '../state/launchDelivery'
-import { launchTooltip } from '../lib/pendingLaunch'
+import { erroredDeps, launchTooltip } from '../lib/pendingLaunch'
import type { AgentState } from '@shared/agents/normalize'
import type { ClientId } from '@shared/presence'
import { PresenceChips } from '../components/PresenceChips'
@@ -1634,6 +1634,24 @@ export function TerminalNode({
// tooltip on a setup-only hold would read "Waiting for to finish".
...(pendingLaunch?.awaitSetupGroup ? ['the project setup script'] : [])
].join(', ')
+ // Which of those deps are held because their last turn ERRORED (issue #521) — an errored station
+ // is idle, so without naming them the tooltip would promise a wait that will never end on its
+ // own. Selected as a joined string so the selector returns a primitive and an unarmed node never
+ // re-renders on another node's status.
+ const erroredDepIds = useAgentStatus((s) => {
+ const after = pendingLaunch?.after ?? []
+ if (!after.length) return ''
+ // Same liveness rule `depSatisfied` uses: a dep that is gone counts as satisfied, so it is
+ // not something this node is held on and must not be named as one.
+ const live = new Set(after.filter((d) => !!getNode(d)))
+ return erroredDeps({ id, data: { pendingLaunch } }, s.byId, live).join(',')
+ })
+ const pendingErroredOn = erroredDepIds
+ ? erroredDepIds
+ .split(',')
+ .map((depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId)
+ .join(', ')
+ : ''
// Use the chat panel only for a chat-capable agent with a known session; otherwise the
// markdown-of-output view (computed in the capture effect below) is shown as a fallback.
const useChat = mdMode && showChat && !!status?.sessionId
@@ -4861,7 +4879,7 @@ export function TerminalNode({
className={`term-node__status term-node__status--queued nodrag${
launchDelivery ? ' term-node__status--queued-warn' : ''
}`}
- title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command)}
+ title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn)}
>
<span className="term-node__status-dot" />
{launchDelivery ? '⚠ ' : ''}QUEUED
@@ -4888,6 +4906,20 @@ export function TerminalNode({
</button>
</span>
)}
+ {/* Issue #521: the last turn ended on an API/model error (the agent's own `StopFailure`
+ hook). NOT a state — the station is idle, and the two facts coexist; this is the only
+ thing on any surface that tells an errored station apart from one that finished. It
+ clears itself on the next genuine turn. Shown beside a `done`/unknown state only: a
+ live RUNNING/NEEDS YOU is about the CURRENT turn and speaks for itself. */}
+ {status?.lastTurnError && status?.state !== 'working' && (
+ <span
+ className="term-node__status term-node__status--errored"
+ title={`${agentLabel} ended its last turn on an error \u2014 it produced nothing this turn. Anything armed to wait on this node is held until a turn succeeds.`}
+ >
+ <span className="term-node__status-dot" />
+ TURN FAILED
+ </span>
+ )}
{(status?.state === 'waiting' || status?.state === 'blocked') && (
<span
className="term-node__status term-node__status--attention"
diff --git a/src/renderer/nodes/session-ready-signal.test.ts b/src/renderer/nodes/session-ready-signal.test.ts
index 84afa1abb..e47c98425 100644
--- a/src/renderer/nodes/session-ready-signal.test.ts
+++ b/src/renderer/nodes/session-ready-signal.test.ts
@@ -70,7 +70,11 @@ describe('the QUEUED badge carries the delivery state (source pins)', () => {
it('the badge reads the store and renders the warning variant plus the shared tooltip', () => {
expect(src).toContain("useLaunchDelivery((s) => s.byId[id])")
expect(src).toContain('term-node__status--queued-warn')
- expect(src).toContain('launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command)')
+ // `pendingErroredOn` is the fourth argument since #521 — an errored upstream is idle, so
+ // without it the tooltip would promise a wait that never ends.
+ expect(src).toContain(
+ 'launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn)'
+ )
})
it('the manual ▶ disarms only on a delivery that landed', () => {
diff --git a/src/renderer/state/agentStatus.test.ts b/src/renderer/state/agentStatus.test.ts
index c75deba79..31eeabe6c 100644
--- a/src/renderer/state/agentStatus.test.ts
+++ b/src/renderer/state/agentStatus.test.ts
@@ -271,7 +271,7 @@ describe('the verified evidence for a transition', () => {
// argument list: nothing else in the suite would notice if the last argument disappeared.
const src = readFileSync(resolve(__dirname, '../../..', 'src/renderer/canvas/Canvas.tsx'), 'utf8')
expect(src).toMatch(
- /cs\.setState\(\s*e\.nodeId,\s*e\.state,\s*e\.agentId,\s*e\.newTurn,\s*e\.pendingId,\s*e\.verified\s*\)/
+ /cs\.setState\(\s*e\.nodeId,\s*e\.state,\s*e\.agentId,\s*e\.newTurn,\s*e\.pendingId,\s*e\.verified,\s*e\.errored\s*\)/
)
})
diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.ts
index 779e51d62..fe9d84868 100644
--- a/src/renderer/state/agentStatus.ts
+++ b/src/renderer/state/agentStatus.ts
@@ -118,6 +118,25 @@ export interface AgentNodeStatus {
* leaves `blocked` (so the buttons vanish once the decision lands). Absent = legacy prompt path.
*/
pendingId?: string
+ /**
+ * The station's LAST turn ended on an API/model error (issue #521) — set from the agent's own
+ * `StopFailure` hook, cleared by the next genuine new turn.
+ *
+ * An annotation beside `state`, never a fifth `AgentState`: an errored station **is** idle, so
+ * the two facts coexist. Before it existed, a station whose first turn died was byte-identical
+ * to one that had finished — the orchestrator's `--after` dependents fired on an upstream that
+ * had produced nothing, and started a whole dependency chain on bad ground. That is what
+ * `depSatisfied` now refuses (`renderer/lib/pendingLaunch.ts`).
+ *
+ * TRANSIENT, like `state` itself, and for the same reason `lastEventAt` is: after a relaunch no
+ * hook has spoken, nothing armed can fire anyway, and a verdict restored from disk would
+ * describe a turn from another app run.
+ *
+ * `at` only. Whether the hook payload carries the failure text has not been measured, and
+ * `last_assistant_message` is the previous assistant turn rather than the error — see
+ * `NormalizedAgentEvent.errored`. Reading the error itself is still owed.
+ */
+ lastTurnError?: { at: number }
/** Set when running /loop, /schedule or /cron (heuristic); shown as a connected node. */
loop?: {
count: number
@@ -154,14 +173,17 @@ export interface AgentStatusStore {
* `pendingId` (deterministic approvals) is retained only while `state === 'blocked'`; any other
* state clears it, so the header's Approve/Deny buttons disappear as soon as the node moves on.
* `verified` is the identity evidence for THIS transition (see `stateVerified`); a caller that
- * omits it asserts nothing, which is why it is trailing and optional. */
+ * omits it asserts nothing, which is why it is trailing and optional.
+ * `errored` says this `done` came from the agent's `StopFailure` hook (see `lastTurnError`);
+ * `newTurn` retires the previous turn's verdict, so the two are read on the same edge. */
setState(
id: string,
state: AgentState | undefined,
agentId?: AgentId,
newTurn?: boolean,
pendingId?: string,
- verified?: boolean
+ verified?: boolean,
+ errored?: boolean
): void
/** Clear `working` entries whose last event is older than `staleMs` (lost-Stop safety net). */
sweepStaleWorking(staleMs?: number): void
@@ -345,10 +367,15 @@ export function createAgentStatusSession(
return s.activeId === id ? { activeId: null } : s
}),
- setState: (id, state, agentId, newTurn, pendingId, verified) =>
+ setState: (id, state, agentId, newTurn, pendingId, verified, errored) =>
set((s) => {
const prev = s.byId[id] ?? EMPTY
const now = Date.now()
+ // Does this event change the last-turn verdict (issue #521)? Read up front because the
+ // same-state fast path below mutates IN PLACE to avoid a re-render — which is exactly what
+ // a badge appearing or disappearing needs, so an event that moves this must not take it.
+ const turnErrorMoves =
+ errored === true || (newTurn === true && prev.lastTurnError !== undefined)
// Done-holdoff: a late working event (parallel hook curls arrive out of order, or a
// tool POST that was in flight when the user interrupted) must not resurrect a turn
// that just finished. Only a genuine new turn (UserPromptSubmit) may.
@@ -368,7 +395,8 @@ export function createAgentStatusSession(
if (
prev.state === state &&
(agentId === undefined || prev.agentId === agentId) &&
- samePendingWhileBlocked
+ samePendingWhileBlocked &&
+ !turnErrorMoves
) {
// Same-state event: refresh freshness in place — stateAt is never rendered, and a
// new object here would re-render every node header on each tool event.
@@ -391,6 +419,12 @@ export function createAgentStatusSession(
if (agentId !== undefined) next.agentId = agentId
// Retain the approval ticket only while blocked; any other state clears it (transient).
next.pendingId = state === 'blocked' ? (pendingId ?? prev.pendingId) : undefined
+ // The last-turn verdict (issue #521). A genuine new turn retires it — the station is being
+ // asked something else, and the old failure no longer describes what it is doing. Anything
+ // else LEAVES IT STANDING (it rides the spread): the intermediate transitions between the
+ // error and the next prompt say nothing about whether that turn produced anything.
+ if (newTurn) next.lastTurnError = undefined
+ else if (errored) next.lastTurnError = { at: now }
// A LIVE state is proof the CLI is running, so the hibernated flag is simply wrong and is
// dropped here — the one self-heal this flag has. It is set by a controller that watched
// the CLI let go of the pane, but the world moves on without us: the user relaunches the
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 03ee692ba..1ba03c7b4 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -1604,6 +1604,13 @@ body,
color: var(--danger);
}
+/* TURN FAILED: the last turn ended on an API/model error (issue #521). Red like NEEDS YOU —
+ something did go wrong — but the dot does NOT pulse: nothing is happening and nothing is being
+ waited for, it is a verdict on a turn that is already over. */
+.term-node__status--errored {
+ color: var(--danger);
+}
+
.term-node__status--loop {
color: #bf7af0;
}
diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.ts
index db8b3325d..74e774615 100644
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@ -12,6 +12,30 @@ export interface NormalizedAgentEvent {
// done only: the turn ended because the user interrupted (Esc/Ctrl-C) — the renderer
// skips the completion alert/unread for these (the user was right there).
interrupted?: boolean
+ /**
+ * done only: this turn ended on an API/model ERROR rather than by finishing (issue #521).
+ *
+ * An annotation, not a fifth `AgentState`, and the reason is not only that a new state would
+ * ripple through both raw listeners and the mobile mirror: **errored is a fact about the last
+ * turn, not a mutually exclusive live state.** A station whose turn 1 errored IS idle — the two
+ * facts coexist, and only one of them is the station's state.
+ *
+ * It is set from the agent's own `StopFailure` hook, which claude and grok both fire INSTEAD of
+ * `Stop` when the turn dies (`CLAUDE_HOOK_EVENTS`/`GROK_HOOK_EVENTS` already subscribe to it —
+ * without the subscription the badge would stick on RUNNING). So the source is a real hook, not
+ * a heuristic: a `Stop` whose turn produced no assistant message was considered and refused on
+ * the closed-set rule — interrupted and tool-only turns look identical to it, and a false
+ * attention signal has no later hook to clear it.
+ *
+ * Carried on the event so both shells change together by construction: `normalizeClaude` /
+ * `normalizeGrok` live in `src/shared` and both raw listeners forward what they return.
+ *
+ * NO ERROR TEXT accompanies it. Whether claude's `StopFailure` payload carries the failure
+ * message has not been measured, and `last_assistant_message` is the previous assistant turn
+ * rather than the error — reporting that as "the error" would be a wrong fact stated
+ * confidently. The flag says only what the hook said.
+ */
+ errored?: boolean
// done only: this `done` was inferred from the CLI going IDLE at its prompt (Claude's
// `idle_prompt` notification), not from a turn-end hook. It is a RESCUE signal: it may only
// move a node that is still `working` (see reduceEntry / the Canvas listener), because a
@@ -239,9 +263,18 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nu
}
}
// The turn died on an API/model error — Claude Code skips the normal Stop hook here,
- // so without this the node would sit on "working" forever.
+ // so without this the node would sit on "working" forever. `errored` is what keeps this
+ // distinguishable from an ordinary finish afterwards (issue #521): the station is idle either
+ // way, and before the flag existed a `--after` dependent fired on a station that produced
+ // nothing.
if (ev === 'StopFailure') {
- return { ...base, kind: 'state', state: 'done', lastMessage: p.last_assistant_message }
+ return {
+ ...base,
+ kind: 'state',
+ state: 'done',
+ errored: true,
+ lastMessage: p.last_assistant_message
+ }
}
// The dedicated permission hook (more direct than Notification's permission_prompt).
if (ev === 'PermissionRequest') {
@@ -645,7 +678,8 @@ export function normalizeGrok(env: RawHookEnvelope): NormalizedAgentEvent | null
: { ...base, kind: 'state', state: 'done', interrupted: true }
}
// The turn died on an API error — grok skips Stop entirely here, exactly as Claude does.
- if (ev === 'stopfailure') return { ...base, kind: 'state', state: 'done', lastMessage }
+ if (ev === 'stopfailure')
+ return { ...base, kind: 'state', state: 'done', errored: true, lastMessage }
if (ev === 'notification') {
// grok's Notification is the one event whose vocabulary we could not measure, and the three
// sources that describe it do not agree, so this mapping is deliberately safe in BOTH