Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas-control): start QUEUED nodes on a PTY-ready signal, and never fail silently
enese285fb18721b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 674cbd21e..9464a77b9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1369,14 +1369,47 @@ else, and its context links must keep classifying across restarts).arming would hand delivery to the canvas effect, which races the node's PTY into existence.(4) Delivery is **exactly-once via `launchInFlight`** (an id stays in the set forever once`sendText` resolved true — clearing `pendingLaunch` is a state update that can lag a re-render),- and a **refused** `sendText` retries (`LAUNCH_DELIVERY_ATTEMPTS`) instead of vanishing.+ and a **refused** `sendText` retries (`launchRetryDelay`'s backoff) instead of vanishing.(5) `pendingLaunch` **is persisted** (unlike `initialCommand`), but agent state is not — so aftera restart nothing will ever report `done` and the node carries a manual ▶ **run-now** escape in- its QUEUED badge. (6) Canvas subscribes to `armedDepSig`, NOT `useAgentStatus(s => s.byId)` —+ its QUEUED badge (which disarms only on a delivery that LANDED — dropping it unconditionally+ threw the command away in exactly the state the button exists to rescue). (6) Canvas subscribes+ to `armedDepSig`, NOT `useAgentStatus(s => s.byId)` —the same discipline as `loopSig`; the full map re-renders the canvas on every hook event.Pure logic + refusal matrix in `renderer/lib/pendingLaunch.ts` (unit-tested); the dashed dep→nodeedges are **derived, never persisted** (a pending dependency is a state that ends when the launchfires — the durable relation is the context bridge `--after` also draws).+ **(7) Delivery waits for the node's PTY, and never fails silently** (issue #569 item 1, 2026-09).+ A satisfied dependency says nothing about whether there is a terminal to type into, and the+ original loop conflated the two: a flat 5 × 400 ms budget started when the CANVAS held the node+ and was spent on loading the canvas, mounting it and spawning tmux — so on a cold project switch+ the launch was abandoned before its session existed, in a `console.warn`, and the node read+ QUEUED forever with only the manual ▶ left. `TerminalNode` therefore publishes a **session-ready**+ signal (`isSessionReady` / `subscribeSessionReady`, module-level like `offscreenNodes`): true for+ an ADOPTED park (already typeable, and its create continuation ran on a previous mount) and, for+ a fresh spawn, at the SAME `whenShellSettled` moment `writeWhenShellReady` delivers an+ `initialCommand` — both write a CLI command line, and a line delivered across zsh's rc-file tty+ flush comes out mangled. A **park keeps it** (a parked tmux session is still addressable by name);+ only a real teardown clears it. The loop then WAITS instead of burning attempts, and the backoff+ (`launchRetryDelay`, ~12 s over five attempts) covers only the residual race after readiness.+ Because a wait with no end is the failure mode this replaces, both give-up states are **visible**+ in the transient `state/launchDelivery.ts` and rendered by the QUEUED badge's amber ⚠ + tooltip+ (`launchTooltip`, pure): `stalled` = gate open, no terminal yet, **still held** (raised by a+ `LAUNCH_STALL_MS` timer with a fire-time re-ask; the launch still fires whenever the session+ finally comes up — an SSH host reconnecting takes this path) and `failed` = the session came up+ and refused every attempt, so nothing will retry it. Neither is ever inferred from silence, and+ the tooltip names no cause it did not measure (the node's own overlay owns the diagnosis).+ The open verbs' replies carry the same fact for callers OUTSIDE the app: `result.queued` ++ `result.queuedIds` on `open-terminal`/`open-claude`/`open-agent`, always true for the+ `--project` cold-open branch — an orchestrator was previously told "opened" either way and+ routed work to a session that did not exist. Agent-facing copy is generated in+ `canvas-control-core.ts` and pinned in its test, per the sync rule above.+ **(8) An armed node must not cold-start its own agent** (found while fixing (7)). The mount-time+ cold-restore relaunch (`fresh && agentId && canResume(...)`) is now also gated on+ `!data.pendingLaunch`: a first open is `fresh` by definition, so every `--after` / `verify` node+ 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.**Review panel (`verify`, 2026-07):** `verify --node <id> [--lenses …] [--focus …] [--agent …][--synthesis off]` opens one reviewer per LENS, each armed behind the target (`--after`) andbridged to it, wrapped in a `Verify: <title>` group, plus a judge armed behind the whole panel.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 87822590a..9f1030f8a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -191,6 +191,18 @@ happened synchronously at your `console.log`, and wrapping that call in `try/cat(measured on node 22). If you write to a stream that can go away, attach an `'error'` listener andlatch the writer off — `installLogSink` (`src/core/log-sink.ts`) is the worked example. Issue #382.+**A retry budget must measure the thing it is waiting for, and running out must be VISIBLE.** The+armed-launch loop (canvas-control `--after`, and the cold open a `--project` node gets) delivered its+held command on a flat 5 × 400 ms budget started when the *canvas* held the node — so on a cold+project switch it was spent loading the canvas, mounting the node and spawning tmux, and the launch+was abandoned before the session it was for existed. Two rules came out of issue #569: wait on a+real signal (`isSessionReady`, published by the node when its shell settles) rather than on a+stopwatch aimed at the wrong start, and never let "we gave up" live only in a `console.warn` — the+node shows it (`state/launchDelivery.ts` → the QUEUED badge's ⚠ + tooltip) and the canvas-control+reply carries it (`queued` / `queuedIds`), because a user who cannot see the failure and an+orchestrator that is told "opened" both act on a session that is not there. If you add a bounded+retry anywhere, ask what the clock actually starts on and where its exhaustion becomes visible.+**Agent features attach to base harness capabilities, not frontend allowlists.** A custom agent caninherit a builtin harness, so add the capability and its one shared leaf (`src/shared/agents`) andlet every UI ask the helper. Repeating Claude/Codex/etc. cases in menus breaks that inheritance anddiff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex d3a36f9a8..9981a35a5 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -369,6 +369,23 @@ describe('parseControlRequest', () => {}})+ it('both agent-facing texts say the open reply reports `queued` (issue #569 item 1)', () => {+ for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {+ // The field itself, and the list that says WHICH ids — a caller that cannot name the queued+ // nodes cannot act on the answer.+ expect(body).toContain('queued')+ expect(body).toContain('queuedIds')+ // The consequence is the whole point of the field: an armed node has no process, so an+ // orchestrator must not route work to it. Without this sentence the flag reads as trivia.+ expect(body.toLowerCase()).toContain('no process')+ // And the three ways a node ends up armed must all be named, or a caller learns the third+ // one by reporting a --project session as started when it has not begun.+ expect(body).toContain('--after')+ expect(body).toContain('--project')+ expect(body.toLowerCase()).toMatch(/setup script/)+ }+ })+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.tsindex 206066ae2..6c4dfa978 100644--- a/src/main/canvas-control-core.ts+++ b/src/main/canvas-control-core.ts@@ -322,6 +322,13 @@ export function buildCanvasControlInstructions(shimPath: string): string {' included); or an id `open-project` returned to YOU in this session, which never switches the',' user\'s view. A session opened into a non-active project starts when the user next views that',' project — do not poll for it. `--group`/`--after` cannot be combined with `--project`.',+ ' The reply reports whether anything actually started: `queued` is true (and `queuedIds`',+ ' lists which) when a node was opened ARMED — waiting on `--after`, on a worktree\'s',+ ' setup script, or on a `--project` target the user has not viewed yet. A queued node',+ ' exists on the canvas but has no process behind it: do not route work to it, do not',+ ' `send` to it and do not report it as started. It launches itself when its wait ends,',+ ' then reports through the ordinary status hooks — there is nothing to poll.',+ ' `queued: false` means the session is running.',' `--prompt` arrives on ONE LINE: every run of whitespace in it, newlines included, is',' collapsed to a single space before the session starts (the prompt rides the launch command',' line typed into the pane). For a structured or multi-line brief use `--prompt-file <abs',@@ -709,6 +716,13 @@ Verbs:TARGET project's (its cwd, its default account and permission mode). A session opened into anon-active project starts when the user next views that project — do not poll for it; the replysays so. \`--group\`/\`--after\` cannot be combined with \`--project\`.+ **The reply tells you whether anything actually started.** \`queued\` is true — and+ \`queuedIds\` names which of the returned ids — whenever a node was opened **armed**: waiting on+ \`--after\`, on a worktree's setup script, or on a \`--project\` target the user has not viewed+ yet. A queued node exists on the canvas but has **no process behind it**, so do not route work+ to it, do not \`send\` to it and do not report it as started. It launches itself when its wait+ ends and then reports through the ordinary status hooks, so there is nothing to poll.+ \`queued: false\` means the session is running.\`--prompt\` arrives on ONE LINE. Every run of whitespace in it — newlines included — iscollapsed to a single space before the session starts, because the prompt is passed as anargument on the agent CLI's launch command line and that line is typed into the pane. Twodiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 93d83e322..261f405ce 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -32,7 +32,9 @@ import {isNodeWatched,setWatchedNode,setRemotelyViewedNodes,- wakeHibernatedNode+ wakeHibernatedNode,+ isSessionReady,+ subscribeSessionReady} from '../nodes/TerminalNode'import { solveFitPadding } from './fit-view'import { MacWheelGestureRouter, trackpadRoutingEnabled } from './wheel-gesture'@@ -310,6 +312,7 @@ import {} from '../lib/explorerPinHint'import { useProjects } from '../state/projects'import { useAgentStatus } from '../state/agentStatus'+import { useLaunchDelivery } from '../state/launchDelivery'import { useBrowserLease, drivingNodeIds } from '../state/browserLease'import { useTerminalFocus } from '../state/terminalFocus'import { useCodexIdentity, codexFallbackText } from '../state/codexIdentity'@@ -388,7 +391,14 @@ import {type RelayTab,} from '../session/relay-tab'import { buildBackgroundLinkMaps, buildContextLinkNote, buildLinkMap, buildNotePushMessage, classifyLink, hiddenLinkIds, linkIdsCoveredByRopes, pairKey, planBridges, type LinkEndpoint } from '../lib/noteLink'-import { dependencyEdges, launchesToFire, unmetDeps, type ArmedNode } from '../lib/pendingLaunch'+import {+ dependencyEdges,+ launchesToFire,+ launchRetryDelay,+ unmetDeps,+ LAUNCH_STALL_MS,+ type ArmedNode+} from '../lib/pendingLaunch'import { freeSpot } from '../lib/placement'import { pushSessionRename } from '../lib/sessionRename'import { useReopenHistory } from '../state/reopenHistory'@@ -639,11 +649,6 @@ const offsetFrom = (return { x: parent.position.x + off.x, y: parent.position.y + off.y }}-// Delivering an armed node's held launch (canvas-control `--after`) can lose the race against-// that node's own PTY coming up, and a dropped launch is exactly the thing its dependency was-// waiting for — so a refused delivery is retried a few times instead of vanishing.-const LAUNCH_DELIVERY_ATTEMPTS = 5-const LAUNCH_RETRY_MS = 400// A canvas-control request whose source node lives in another project switches that project in// first, and the active-project effect hydrates React Flow ASYNCHRONOUSLY — so the handler waits@@ -1536,13 +1541,44 @@ export function Canvas() {}return sig})- // Bumped to re-run the launch effect after a refused delivery (see LAUNCH_RETRY_MS).- const [launchRetry, setLaunchRetry] = useState(0)+ // Bumped to re-run the launch effect: after a refused delivery's backoff, and when a node+ // reports its session ready (`subscribeSessionReady` below).+ const [launchNudge, setLaunchNudge] = useState(0)// Ids whose held launch has been handed to the pty. An id stays here FOREVER once delivery// succeeded — clearing `pendingLaunch` is a state update that can lag a re-render, and this// action is irreversible, so the set (not the node data) is what guarantees exactly-once.const launchInFlight = useRef<Set<string>>(new Set())const launchAttempts = useRef<Map<string, number>>(new Map())+ // Per-node "the gate is open but nothing has come up to deliver into" timers — the source of the+ // visible `stalled` warning. One per armed node, armed once and cleared the moment the node+ // becomes ready, is delivered, or stops being armed.+ const launchStallTimers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map())+ const clearStallTimer = useCallback((nodeId: string) => {+ const t = launchStallTimers.current.get(nodeId)+ if (t === undefined) return+ clearTimeout(t)+ launchStallTimers.current.delete(nodeId)+ }, [])+ // A node whose session just came up is the ONE event the launch loop was missing. Filtered by+ // id on the way in: a canvas of forty terminals publishes forty times on load, and re-rendering+ // this component for each of them (for the sake of the one node that is armed) is exactly the+ // churn `armedDepSig` and `loopSig` exist to avoid.+ useEffect(+ () =>+ subscribeSessionReady((nodeId) => {+ if (nodesRef.current.some((n) => n.id === nodeId && n.data.pendingLaunch))+ setLaunchNudge((v) => v + 1)+ }),+ []+ )+ // Nothing must outlive the component: a pending stall timer would fire into an unmounted tree.+ useEffect(+ () => () => {+ for (const t of launchStallTimers.current.values()) clearTimeout(t)+ launchStallTimers.current.clear()+ },+ []+ )// Fire armed nodes whose upstream stations have all gone idle. This is the edge that makes// the canvas a graph rather than a fan-out: the dependent starts itself, with no orchestrator// sitting in a poll loop burning context.@@ -1554,7 +1590,50 @@ export function Canvas() {live,setupDoneForGroup).filter((f) => !launchInFlight.current.has(f.id))+ // Anything we were reporting on that is no longer an armed node — delivered, run by hand with+ // ▶, or deleted — stops being reported. Timers go with it: a stall warning for a node that has+ // already started is a lie with a countdown on it.+ const delivery = useLaunchDelivery.getState()+ for (const id of Object.keys(delivery.byId)) {+ if (!nodes.some((n) => n.id === id && n.data.pendingLaunch)) {+ delivery.clear(id)+ clearStallTimer(id)+ }+ }for (const f of ready) {+ // THE gate this whole loop turns on. Every dependency is satisfied, but that says nothing+ // about whether there is a terminal to deliver into: a cold project switch loads the canvas,+ // mounts the node, spawns tmux and settles a shell, and the old flat 2 s retry budget was+ // spent long before any of that finished — the launch was then abandoned in a console.warn+ // and the node sat on QUEUED until somebody clicked ▶ (#569 item 1).+ //+ // So we WAIT instead of burning attempts, and we say we are waiting. This is not a deadline:+ // a session that comes up ten minutes later (an SSH host reconnecting, a checkout behind a+ // slow setup script) still fires, because `subscribeSessionReady` brings us straight back.+ if (!isSessionReady(f.id)) {+ if (!launchStallTimers.current.has(f.id)) {+ launchStallTimers.current.set(+ f.id,+ setTimeout(() => {+ launchStallTimers.current.delete(f.id)+ // Re-ask at fire time: the plan is 45 s old and the node may have started, been+ // delivered or been deleted since.+ if (+ !isSessionReady(f.id) &&+ nodesRef.current.some((n) => n.id === f.id && n.data.pendingLaunch)+ )+ useLaunchDelivery.getState().markStalled(f.id)+ }, LAUNCH_STALL_MS)+ )+ }+ continue+ }+ clearStallTimer(f.id)+ // There IS a terminal now, so a standing "has not started yet" warning is out of date. A+ // `failed` record is not withdrawn here — that one is about this session refusing the+ // launch, and only a delivery that lands (or the manual ▶) retires it.+ if (useLaunchDelivery.getState().byId[f.id]?.kind === 'stalled')+ useLaunchDelivery.getState().clear(f.id)launchInFlight.current.add(f.id)const attempt = (launchAttempts.current.get(f.id) ?? 0) + 1launchAttempts.current.set(f.id, attempt)@@ -1563,21 +1642,29 @@ export function Canvas() {setNodes((ns) =>ns.map((n) => (n.id === f.id ? { ...n, data: { ...n.data, pendingLaunch: undefined } } : n)))+ useLaunchDelivery.getState().clear(f.id)markDirty()return}- // Refused: the node's tmux session is most likely still coming up. Let it back out of- // flight and re-run shortly — a launch that silently vanishes is worse than a late one.+ // Refused although the session reported ready — a narrow residual race now, not the+ // whole cold-start window. Let it back out of flight and re-run after the backoff; a+ // launch that silently vanishes is worse than a late one.launchInFlight.current.delete(f.id)- if (attempt < LAUNCH_DELIVERY_ATTEMPTS) {- setTimeout(() => setLaunchRetry((v) => v + 1), LAUNCH_RETRY_MS)- } else {- console.warn('[pending-launch] gave up delivering held launch for', f.id)+ const delay = launchRetryDelay(attempt)+ if (delay !== null) {+ setTimeout(() => setLaunchNudge((v) => v + 1), delay)+ return}+ // Out of attempts against a session that IS up. Nothing else will retry this, so it is+ // reported where the person looking at the node can see it — the QUEUED badge turns into+ // a warning pointing at the manual ▶. The log line stays for a bug report; it is no+ // longer the only place the failure exists.+ useLaunchDelivery.getState().markFailed(f.id, attempt)+ console.warn('[pending-launch] gave up delivering held launch for', f.id)})}- // eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/armedSetupSig/launchRetry are the triggers- }, [nodes, armedDepSig, armedSetupSig, launchRetry])+ // eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/armedSetupSig/launchNudge are the triggers+ }, [nodes, armedDepSig, armedSetupSig, launchNudge])// Selection state for ephemeral nodes (they live outside React Flow's managed nodes), owned by// the agent-nodes store so the cards themselves can set it — see `selectable: false` below.@@ -8233,7 +8320,8 @@ export function Canvas() {reply({ok: true,message: `opened ${tgCount} ${tgWhat} session(s) in "${target.name}" (${tgIds.join(', ')})`,- result: { ids: tgIds, id: tgIds[0], projectId: target.id }+ // The target is on screen, so these started normally — nothing is queued.+ result: { ids: tgIds, id: tgIds[0], projectId: target.id, queued: false, queuedIds: [] }})return}@@ -8254,8 +8342,17 @@ export function Canvas() {ok: true,message:`opened ${tgCount} ${tgWhat} session(s) in "${target.name}" (${tgIds.join(', ')}) — ` +- 'starts when that project is next viewed',- result: { ids: tgIds, id: tgIds[0], projectId: target.id }+ 'queued; starts when that project is next viewed',+ // Every node on this branch is armed by `armForColdOpen`, so the whole batch is+ // QUEUED. Said in the reply as a field, not only in the sentence, so an orchestrator+ // does not have to report a session as started when it is not (#569 item 1).+ result: {+ ids: tgIds,+ id: tgIds[0],+ projectId: target.id,+ queued: true,+ queuedIds: tgIds+ }})return}@@ -8662,8 +8759,15 @@ export function Canvas() {})return}- const make = (i: number): CanvasNode =>- armAfter(+ // Which of the nodes we are about to open are actually ARMED — i.e. QUEUED rather+ // than running. `armAfter` decides that per node (deps already satisfied leave the+ // command as an ordinary `initialCommand`), so the answer is recorded as it builds+ // them rather than inferred from the flags; `setNodes` has not landed by reply time,+ // so the canvas cannot be asked either. Reported so a caller can tell "started" from+ // "will start later" instead of assuming the first — see #569 item 1.+ const queuedIds: string[] = []+ const make = (i: number): CanvasNode => {+ const node = armAfter(createTerminalNode(nodesRef.current.length + i,termCwd,@@ -8675,6 +8779,9 @@ export function Canvas() {undefined,intoGroupId)+ if (node.data.pendingLaunch) queuedIds.push(node.id)+ return node+ }const ids = intoGroupId? addGrouped(intoGroupId, count, make): Array.from({ length: count }, (_, i) => addAndConnect(make(i)))@@ -8683,7 +8790,13 @@ export function Canvas() {message:`opened ${count} terminal(s): ${ids.join(', ')}` +(after?.length ? `\nwaiting for ${after.join(', ')} before running` : ''),- result: { ids, id: ids[0], after: after ?? [] }+ result: {+ ids,+ id: ids[0],+ after: after ?? [],+ queued: queuedIds.length > 0,+ queuedIds+ }})return}@@ -8779,8 +8892,11 @@ export function Canvas() {})return}- const make = (i: number): CanvasNode =>- armAfter(+ // See the same list in open-terminal: which of these nodes end up ARMED is+ // `armAfter`'s per-node decision, recorded as it builds them.+ const queuedIds: string[] = []+ const make = (i: number): CanvasNode => {+ const node = armAfter(createAgentNode(agentId,nodesRef.current.length + i,@@ -8803,6 +8919,9 @@ export function Canvas() {undefined,intoGroupId)+ if (node.data.pendingLaunch) queuedIds.push(node.id)+ return node+ }const ids = intoGroupId? addGrouped(intoGroupId, count, make): Array.from({ length: count }, (_, i) => addAndConnect(make(i)))@@ -8831,7 +8950,13 @@ export function Canvas() {? `\nwaiting for ${after.join(', ')} before running` +(depLinked.length ? ` (and linked to read them)` : ''): ''),- result: { ids, linked: bridged, after: after ?? [] }+ result: {+ ids,+ linked: bridged,+ after: after ?? [],+ queued: queuedIds.length > 0,+ queuedIds+ }})return}diff --git a/src/renderer/canvas/pending-launch-delivery.source.test.ts b/src/renderer/canvas/pending-launch-delivery.source.test.tsnew file mode 100644index 000000000..914dd22f6--- /dev/null+++ b/src/renderer/canvas/pending-launch-delivery.source.test.ts@@ -0,0 +1,110 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * STRUCTURAL pins for the armed-launch delivery loop (issue #569 item 1) — same class of test as+ * `control-open-project.source.test.ts`, and for the same reason: the loop is an effect inside a+ * 9000-line React component with no unit seam. The DECISIONS it makes are proven against real+ * primitives elsewhere (`pendingLaunch.test.ts` for the schedule and the tooltip,+ * `launchDelivery.test.ts` for the record); what only the source can state is which signals the+ * effect consults and what it does when it runs out of them.+ *+ * The bug: delivery was a flat 5 × 400 ms budget started when the CANVAS held the node, spent+ * while its terminal was still being spawned, and abandoned into a `console.warn`. A node opened+ * into a project the user was not looking at therefore said QUEUED forever, and neither the user+ * nor the orchestrator that opened it could tell that apart from a node still waiting on a+ * dependency.+ */+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8')++/** The launch effect: from the `launchesToFire(` call to the end of its dependency array. */+function launchEffect(): string {+ const start = src.indexOf('const ready = launchesToFire(')+ expect(start).toBeGreaterThan(-1)+ const rest = src.slice(start)+ const end = rest.indexOf('armedSetupSig, launchNudge])')+ expect(end).toBeGreaterThan(-1)+ return rest.slice(0, end)+}++describe('armed-launch delivery (source pins)', () => {+ it('gates delivery on the node reporting its session READY, not on a fixed attempt budget', () => {+ const body = launchEffect()+ expect(body).toContain('isSessionReady(f.id)')+ // The gate must SKIP, never deliver-and-hope: an attempt against a session that does not+ // exist is what burnt the old budget before the terminal was up.+ expect(body).toMatch(/if \(!isSessionReady\(f\.id\)\)[\s\S]{0,1400}?continue/)+ // And the flat constants must be gone — a grep for them is how a revert announces itself.+ expect(src).not.toContain('LAUNCH_RETRY_MS')+ expect(src).not.toMatch(/attempt < LAUNCH_DELIVERY_ATTEMPTS/)+ })++ it('subscribes to readiness so a session coming up re-runs the loop — no polling, no deadline', () => {+ // Without this the ready gate would be a WORSE bug than the budget: a node that becomes+ // typeable a second after the effect last ran would sit armed with nothing to wake it.+ expect(src).toContain('subscribeSessionReady(')+ expect(src).toContain('setLaunchNudge')+ // Filtered by id: forty terminals publishing on load must not re-render the canvas forty+ // times for the sake of one armed node.+ expect(src).toMatch(/subscribeSessionReady\(\(nodeId\) => \{[\s\S]{0,400}?n\.data\.pendingLaunch/)+ })++ it('retries a refused delivery on the shared backoff and gives up only when it is exhausted', () => {+ const body = launchEffect()+ expect(body).toContain('launchRetryDelay(attempt)')+ expect(body).toMatch(/delay !== null[\s\S]{0,200}?setTimeout/)+ })++ it('a give-up is REPORTED, not only logged — the console.warn is no longer the whole story', () => {+ const body = launchEffect()+ const warn = body.indexOf("console.warn('[pending-launch]")+ expect(warn).toBeGreaterThan(-1)+ // markFailed must accompany the log. This is the misleading-error rule: a failure the user+ // can only find in DevTools is a failure the user cannot find.+ expect(body).toContain('markFailed(f.id, attempt)')+ expect(body.slice(0, warn)).toContain('markFailed')+ })++ it('says so while it waits — a long stall raises the visible warning rather than staying mute', () => {+ const body = launchEffect()+ expect(body).toContain('LAUNCH_STALL_MS')+ expect(body).toContain('markStalled(f.id)')+ // Fire-time re-ask, same discipline as the hibernation sweep: the plan is 45 s old by then,+ // and the node may have started, been delivered or been deleted since.+ expect(body).toMatch(/setTimeout\(\(\) => \{[\s\S]{0,600}?!isSessionReady\(f\.id\)[\s\S]{0,300}?markStalled/)+ })++ it('keeps the exactly-once and dep-satisfaction invariants the feature already had', () => {+ const body = launchEffect()+ // Exactly-once: an id enters the in-flight set before the send and only LEAVES it on a+ // refusal (a successful delivery is irreversible and must never be re-attempted).+ expect(body).toContain('launchInFlight.current.add(f.id)')+ expect(body).toMatch(/if \(ok\)[\s\S]{0,400}?pendingLaunch: undefined/)+ expect(body).toMatch(/launchInFlight\.current\.delete\(f\.id\)/)+ // Satisfaction is still `launchesToFire`'s call — the ready gate is an ADDITIONAL condition,+ // never a replacement for the dependency matrix.+ expect(body).toContain('launchesToFire(')+ expect(body).toContain('setupDoneForGroup')+ })++ it('stops reporting on a node that is no longer armed — no stale warning on a running session', () => {+ const body = launchEffect()+ expect(body).toMatch(/delivery\.clear\(id\)[\s\S]{0,120}?clearStallTimer\(id\)/)+ })+})++describe('the open verbs report whether anything started (source pins)', () => {+ it('open-terminal and open-agent both answer with `queued` + `queuedIds`', () => {+ // Two separate reply sites, so both are pinned: an orchestrator that can only tell "opened"+ // from "opened but not started" for ONE of the verbs has learned nothing.+ expect(src.match(/queued: queuedIds\.length > 0/g)?.length).toBe(2)+ expect(src.match(/if \(node\.data\.pendingLaunch\) queuedIds\.push\(node\.id\)/g)?.length).toBe(2)+ })++ it('the cross-project cold open reports queued:true, and the in-view branch reports false', () => {+ // The whole `--project` branch is armed by `armForColdOpen`, and the active-target branch+ // beside it is not — the two literals are what keep that difference in the reply.+ expect(src).toContain('queued: true,')+ expect(src).toContain('queued: false, queuedIds: []')+ })+})diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.tsindex bdc20e1eb..57a20f249 100644--- a/src/renderer/lib/pendingLaunch.test.ts+++ b/src/renderer/lib/pendingLaunch.test.ts@@ -1,5 +1,15 @@import { describe, it, expect } from 'vitest'-import { dependencyEdges, launchesToFire, unmetDeps, type ArmedNode, type StatusById } from './pendingLaunch'+import {+ dependencyEdges,+ launchesToFire,+ launchRetryDelay,+ launchTooltip,+ unmetDeps,+ LAUNCH_DELIVERY_ATTEMPTS,+ LAUNCH_STALL_MS,+ type ArmedNode,+ type StatusById+} from './pendingLaunch'const armed = (id: string, after: string[], command = `echo ${id}`): ArmedNode => ({id,@@ -131,3 +141,79 @@ describe('dependencyEdges', () => {expect(dependencyEdges([plain('c')], new Set(['c']))).toEqual([])})})++/**+ * Issue #569 item 1 — the delivery policy behind an armed node's held launch.+ *+ * The bug these pin: delivery used to be a flat 5 × 400 ms = 2 s budget started when the CANVAS+ * decided a node was ready to launch, not when the node's terminal existed. A cold project switch+ * spends that budget on loading the canvas, mounting the node and spawning tmux, so the launch was+ * abandoned before there was anything to deliver into — and abandoned into a `console.warn`, which+ * left a node reading QUEUED forever with no way to tell it apart from one still waiting on a+ * dependency.+ */+describe('launch delivery policy (#569 item 1)', () => {+ it('the schedule backs off and is bounded — exhaustion is reachable, so "gave up" can be told', () => {+ const delays: number[] = []+ for (let attempt = 1; ; attempt++) {+ const d = launchRetryDelay(attempt)+ if (d === null) break+ delays.push(d)+ expect(attempt).toBeLessThan(20) // guard: a schedule that never ends is the bug, not a fix+ }+ expect(delays.length).toBe(LAUNCH_DELIVERY_ATTEMPTS)+ // Strictly increasing: a flat schedule is what made the old budget a fixed 2 s wall.+ for (let i = 1; i < delays.length; i++) expect(delays[i]).toBeGreaterThan(delays[i - 1])+ // And the whole window is comfortably wider than the old one, measured from READINESS.+ expect(delays.reduce((a, b) => a + b, 0)).toBeGreaterThan(10_000)+ })++ it('an attempt past the end has no delay — nothing silently retries forever', () => {+ expect(launchRetryDelay(LAUNCH_DELIVERY_ATTEMPTS)).not.toBeNull()+ expect(launchRetryDelay(LAUNCH_DELIVERY_ATTEMPTS + 1)).toBeNull()+ })++ it('the stall warning waits longer than a cold project switch could plausibly take', () => {+ expect(LAUNCH_STALL_MS).toBeGreaterThanOrEqual(30_000)+ })+})++describe('launchTooltip — the QUEUED badge never goes silent (#569 item 1)', () => {+ const cmd = 'claude "review the diff"'++ it('with nothing to report it names the dependencies, exactly as before', () => {+ const t = launchTooltip(undefined, 'Builder, Tests', cmd)+ expect(t).toContain('Waiting for Builder, Tests to finish')+ expect(t).toContain(cmd)+ expect(t).not.toContain('▶')+ })++ it('a stalled launch says it is still held, and does NOT claim a cause it never measured', () => {+ const t = launchTooltip({ kind: 'stalled', since: 1 }, 'Builder', cmd)+ expect(t).toContain('has not started yet')+ expect(t).toContain('still held')+ expect(t).toContain('▶')+ // We know the terminal is not up; we do not know why. Naming a cause here would be the+ // misleading-error failure this feature exists to avoid.+ expect(t.toLowerCase()).not.toMatch(/ssh|host is down|crash/)+ })++ it('a failed launch reports the attempt count and that nothing will retry it', () => {+ const t = launchTooltip({ kind: 'failed', attempts: 5, at: 1 }, 'Builder', cmd)+ expect(t).toContain('5 attempts')+ expect(t).toContain('nothing will retry it')+ expect(t).toContain('▶')+ expect(t).toContain(cmd)+ })++ it('singularises one attempt (the manual ▶ reports exactly one refusal)', () => {+ expect(launchTooltip({ kind: 'failed', attempts: 1, at: 1 }, 'Builder', cmd)).toContain(+ '1 attempt was refused'+ )+ })++ it('failed outranks the dependency sentence — the warning is never buried', () => {+ const t = launchTooltip({ kind: 'failed', attempts: 5, at: 1 }, 'Builder', cmd)+ expect(t).not.toContain('Waiting for Builder')+ })+})diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.tsindex 1bbd8de73..54eacf24d 100644--- a/src/renderer/lib/pendingLaunch.ts+++ b/src/renderer/lib/pendingLaunch.ts@@ -111,3 +111,79 @@ export function dependencyEdges(}return out}++/**+ * The backoff between delivery attempts, in milliseconds, indexed by the number of attempts+ * ALREADY made. `null` = the schedule is exhausted; the launch has failed for good.+ *+ * This replaces a flat 5 × 400 ms budget (2 s from the moment the canvas mounted the node) that+ * measured the wrong thing entirely: it started when the CANVAS decided the node was ready to+ * launch, and spent itself while the terminal was still being spawned. A cold project switch —+ * load the canvas, mount the node, spawn tmux, settle the shell — routinely costs more than two+ * seconds, so the launch was abandoned before the session it was meant for existed. That is+ * issue #569 item 1: a node that says QUEUED forever with no way to tell it apart from one that+ * is simply waiting on a dependency.+ *+ * The fix is mostly NOT here: delivery is now gated on the node reporting its session ready+ * (`isSessionReady`), so the schedule below only has to cover the residual race between "the+ * shell settled" and "tmux will accept a paste for this session". It is nevertheless generous+ * and bounded — roughly 12 s across five attempts — because the alternative to a bound is a+ * retry loop nobody can see the end of.+ */+const LAUNCH_RETRY_SCHEDULE_MS = [400, 800, 1600, 3200, 6400] as const++export function launchRetryDelay(attemptsMade: number): number | null {+ return LAUNCH_RETRY_SCHEDULE_MS[attemptsMade - 1] ?? null+}++/** Total attempts a refused delivery gets before it is reported as failed. */+export const LAUNCH_DELIVERY_ATTEMPTS = LAUNCH_RETRY_SCHEDULE_MS.length++/**+ * How long an armed node whose gate is OPEN may sit with no terminal to deliver into before the+ * badge says so. It is a WARNING, not a deadline: the launch is still held and still fires the+ * moment the session comes up (an SSH host that reconnects, a spawn behind a slow `npm ci`).+ *+ * Chosen well past a cold project switch on a loaded canvas, so an ordinary open never trips it.+ */+export const LAUNCH_STALL_MS = 45_000++/**+ * What the delivery loop has to say about ONE armed node's held launch — the visible half of the+ * two failure modes that used to be a `console.warn` nobody reads. Declared here rather than in+ * the store so the rendering below stays pure and testable; the store only holds it.+ */+export type LaunchDelivery =+ | { kind: 'stalled'; since: number }+ | { kind: 'failed'; attempts: number; at: number }++/**+ * The QUEUED badge's tooltip. One function for all three cases so the sentences cannot drift, and+ * so the two warnings are held to the same standard as the ordinary one: say what is true, name+ * what would fix it, and never claim a cause that was not measured.+ *+ * `stalled` is careful about that last point. We know the terminal has not come up; we do NOT know+ * why (a host that is down, a spawn that failed, a machine under load all look identical from+ * here), so the text says what we observed and leaves the diagnosis to the node's own overlay,+ * which does know.+ */+export function launchTooltip(+ delivery: LaunchDelivery | undefined,+ waitingOn: string,+ command: string+): string {+ const runs = `Runs:\n${command}`+ if (delivery?.kind === 'failed')+ return (+ `This session did not accept its launch — ${delivery.attempts} ` ++ `attempt${delivery.attempts === 1 ? ' was' : 's were'} refused, and nothing will retry it.\n` ++ `Press \u25b6 to run it now.\n${runs}`+ )+ if (delivery?.kind === 'stalled')+ return (+ 'Ready to run, but this terminal has not started yet — the launch is still held and ' ++ 'fires as soon as it does.\n' ++ `Press \u25b6 to try it now.\n${runs}`+ )+ return `Waiting for ${waitingOn} to finish, then runs:\n${command}`+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 93ee51531..0012d4496 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -138,6 +138,8 @@ import { renameCommand } from '../lib/sessionRename'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 type { AgentState } from '@shared/agents/normalize'import type { ClientId } from '@shared/presence'import { PresenceChips } from '../components/PresenceChips'@@ -829,6 +831,53 @@ const coSubs = new Map<string, (s: CoState) => void>()*/const restartSubs = new Map<string, () => void>()+/**+ * Nodes whose terminal is up and settled enough to be TYPED INTO — the signal Canvas's armed-launch+ * loop waits on before it delivers a held command (`pendingLaunch`).+ *+ * It exists because the loop used to wait on nothing at all: it fired `pty.sendText` the instant+ * the canvas held the node and spent a flat 2 s retry budget while the session was still being+ * spawned, then gave up in a `console.warn`. On a cold project switch that budget is gone before+ * tmux has a session to paste into, which is issue #569 item 1 — a node stuck on QUEUED that only+ * a manual click could start.+ *+ * "Ready" is deliberately the same moment `writeWhenShellReady` delivers an `initialCommand`: the+ * session resolved AND its shell has gone quiet. Both paths type into the same pane, and a launch+ * line written across zsh's rc-file tty flush is the mangled-command bug that helper exists for.+ *+ * ABSENT = not ready, which is the safe direction: it holds the launch (visibly — see+ * `useLaunchDelivery`) instead of burning it against a session that is not there. Published by the+ * node itself, since nothing else can see the spawn resolve. A PARKED session stays ready — it is+ * still a live tmux session addressable by name — and only a real teardown (respawn, offscreen+ * dispose, delete) clears it.+ */+const sessionReadyNodes = new Set<string>()+const sessionReadySubs = new Set<(nodeId: string) => void>()++/** Is this node's session up and typeable? Unknown answers false — see the note above. */+export function isSessionReady(nodeId: string): boolean {+ return sessionReadyNodes.has(nodeId)+}++/**+ * Watch for nodes becoming ready. The callback is handed the node id rather than being a bare+ * "something changed" ping: Canvas re-renders on it, and a canvas of forty terminals must not+ * re-render forty times on load for the sake of the one node that is armed.+ */+export function subscribeSessionReady(cb: (nodeId: string) => void): () => void {+ sessionReadySubs.add(cb)+ return () => {+ sessionReadySubs.delete(cb)+ }+}++function setSessionReady(nodeId: string, ready: boolean): void {+ if (sessionReadyNodes.has(nodeId) === ready) return+ if (ready) sessionReadyNodes.add(nodeId)+ else sessionReadyNodes.delete(nodeId)+ for (const cb of sessionReadySubs) cb(nodeId)+}+/*** Which mounted terminals are currently OUT of the viewport, published by the one visibility* observer each node already runs (Phase 2's) — never a second observer, and never a second@@ -1554,6 +1603,11 @@ export function TerminalNode({// it is armed, and by WHAT it is blocked — dep titles read straight off the live canvas, since// "waits for term-17" tells the user nothing.const pendingLaunch = data.pendingLaunch as PendingLaunch | undefined+ // What the delivery loop has to say about this node's held launch, if anything. Absent is the+ // ordinary case (still waiting on a dependency); the two states it can carry are the ones that+ // used to be invisible — see the store. Selected by id so an unarmed node never re-renders on+ // another node's delivery.+ const launchDelivery = useLaunchDelivery((s) => s.byId[id])const pendingWaitingOn = [...(pendingLaunch?.after ?? []).map((depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId@@ -1743,6 +1797,11 @@ export function TerminalNode({parkedTerminals.delete(termKey)parked.timer.cancel()}+ // An ADOPTED terminal is already typeable — the same live session, the same settled shell —+ // and its spawn continuation ran on a previous mount, so it will never reach the publish+ // below. A fresh one starts NOT ready: this effect also re-runs for a respawn and for an+ // offscreen revive, and both replace the session a stale `true` would describe.+ setSessionReady(id, !!parked)const s = useSettings.getState().settings// Appearance comes from ONE place, shared with the kanban card modal's viewer of this same@@ -3026,22 +3085,14 @@ export function TerminalNode({// `quote>` on Enter) instead of running. The settle wait below minimizes wasted// attempts; deliverCommand (echo-verify + retry, fail-open) guarantees a mangled// line is never submitted. See command-delivery.ts.- const writeWhenShellReady = (cmd: string): void => {+ const whenShellSettled = (run: () => void): void => {let done = falselet timer: ReturnType<typeof setTimeout>const fire = (): void => {if (done) returndone = trueunsub()- cleanups.push(- deliverCommand(- {- write: (d) => transport.write(sid, d),- onData: (cb) => transport.onData(sid, cb)- },- cmd- )- )+ run()}const unsub = transport.onData(sid, () => {if (done) return@@ -3055,6 +3106,26 @@ export function TerminalNode({unsub()})}+ const writeWhenShellReady = (cmd: string): void => {+ whenShellSettled(() => {+ cleanups.push(+ deliverCommand(+ {+ write: (d) => transport.write(sid, d),+ onData: (cb) => transport.onData(sid, cb)+ },+ cmd+ )+ )+ })+ }+ // Tell the canvas this node can be typed into — the gate its armed-launch loop waits on.+ // Through the SAME settle the two writers above use, and for the same reason: the held+ // launch is an agent CLI command line, and a line delivered across zsh's rc-file tty flush+ // comes out mangled. Published unconditionally (not only for an armed node): whether this+ // node is armed is Canvas's question, it can change after the spawn resolves, and the+ // subscribers filter by id anyway.+ whenShellSettled(() => setSessionReady(id, true))// Hibernation × cold restore. `hibernated` is PERSISTED, so it can outlive the very thing// it describes:// - `fresh` (the tmux session is GONE — a reboot, a reaped server, a first open): the CLI@@ -3074,11 +3145,20 @@ export function TerminalNode({if (data.initialCommand) {writeWhenShellReady(data.initialCommand)updateNodeData(id, { initialCommand: undefined })- } else if (fresh && agentId && canResume(agentId)) {+ } else if (fresh && agentId && canResume(agentId) && !data.pendingLaunch) {// Cold restart of an agent node: the live agent is gone, so re-launch it. Resume the// prior conversation by its session id when we have one; otherwise start the agent// fresh. Plain terminals get nothing here — just the restored shell.//+ // An ARMED node (`pendingLaunch`) is excluded, and that is the point of arming: its+ // launch — the very same agent CLI line, with the brief it was opened for — is being+ // HELD until its dependencies finish. Launching a bare CLI here starts the session the+ // hold exists to prevent, and Canvas's held launch then arrives as TEXT typed into the+ // running CLI rather than as the command it is. A first open is `fresh` by definition,+ // so this covered every `--after` / `verify` node; it was previously masked by the+ // delivery race (the held launch usually lost it and was retried), and gating delivery+ // on the shell settling would have made the collision deterministic.+ //// Two sources, in this order, and the order is the whole point:// 1. the LIVE id from hooks, which tracks `/clear` and `--fork-session` minting a new// one mid-conversation, so it is the only one that can be current;@@ -3756,6 +3836,10 @@ export function TerminalNode({// EARLIER effect (this terminal may have been adopted from a park) sees the session die here// and tears down instead of wiring listeners onto it; `killSession` keeps the kill single.life.dead = true+ // A real teardown (respawn, offscreen dispose, delete) ends the session this node published+ // as ready. A PARK does not, and returns above without reaching here — a parked session is+ // still a live tmux session addressable by name, so it stays typeable.+ setSessionReady(id, false)cleanups.forEach((fn) => fn())if (sessionId) killSession(sessionId)term.dispose()@@ -4623,18 +4707,30 @@ export function TerminalNode({"run now" an armed node left over from before the restart would be a dead end. */}{pendingLaunch && (<span- className="term-node__status term-node__status--queued nodrag"- title={`Waiting for ${pendingWaitingOn} to finish, then runs:\n${pendingLaunch.command}`}+ className={`term-node__status term-node__status--queued nodrag${+ launchDelivery ? ' term-node__status--queued-warn' : ''+ }`}+ title={launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command)}><span className="term-node__status-dot" />- QUEUED+ {launchDelivery ? '⚠ ' : ''}QUEUED<buttonclassName="term-node__queued-run"title="Run now without waiting"onClick={(e) => {e.stopPropagation()- void api.pty.sendText(id, pendingLaunch.command)- updateNodeData(id, { pendingLaunch: undefined })+ // Disarm only on a delivery that actually landed. Dropping `pendingLaunch`+ // unconditionally threw the command away whenever the session was not up yet —+ // and "not up yet" is precisely the state a user reaches for this button in, so+ // the one escape hatch could destroy the thing it exists to rescue.+ void api.pty.sendText(id, pendingLaunch.command).then((ok) => {+ if (ok) {+ useLaunchDelivery.getState().clear(id)+ updateNodeData(id, { pendingLaunch: undefined })+ } else {+ useLaunchDelivery.getState().markFailed(id, 1)+ }+ })}}>▶diff --git a/src/renderer/nodes/session-ready-signal.test.ts b/src/renderer/nodes/session-ready-signal.test.tsnew file mode 100644index 000000000..5c6b9ad8c--- /dev/null+++ b/src/renderer/nodes/session-ready-signal.test.ts@@ -0,0 +1,81 @@+// @vitest-environment jsdom+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { isSessionReady, subscribeSessionReady } from './TerminalNode'++/**+ * Issue #569 item 1 — the PTY-ready signal Canvas's armed-launch loop waits on.+ *+ * TerminalNode is impractical to mount in jsdom (xterm, a live PTY, dozens of stores), so the+ * exported CONTRACT is exercised directly and the publish/clear sites are pinned as source+ * tripwires — the same split `status-lifecycle.test.ts` uses.+ */+const src = readFileSync(join(__dirname, 'TerminalNode.tsx'), 'utf8')++describe('the session-ready registry contract', () => {+ it('an unknown node is NOT ready — the safe direction holds the launch instead of burning it', () => {+ expect(isSessionReady('term-never-seen')).toBe(false)+ })++ it('a subscriber can be added and removed without the module retaining it', () => {+ const seen: string[] = []+ const off = subscribeSessionReady((id) => seen.push(id))+ expect(typeof off).toBe('function')+ off()+ off() // idempotent: a double-unsubscribe on unmount must not throw+ expect(seen).toEqual([])+ })+})++describe('where readiness is published (source pins)', () => {+ it('an ADOPTED (parked) terminal is ready immediately; a fresh one starts not-ready', () => {+ // The park→remount path returns before `create()` and would otherwise never publish, leaving+ // an armed node waiting on a session that has been live the whole time.+ expect(src).toContain('setSessionReady(id, !!parked)')+ })++ it('a fresh session is published through the SAME shell settle the initialCommand writer uses', () => {+ // Both write an agent CLI command line into the pane. A line delivered across zsh's rc-file+ // tty flush comes out mangled, which is exactly what `whenShellSettled` exists to avoid — so+ // the armed launch must not be released on a bare create-resolve.+ expect(src).toContain('whenShellSettled(() => setSessionReady(id, true))')+ expect(src).toContain('const writeWhenShellReady = (cmd: string): void => {')+ expect(src).toMatch(/whenShellSettled\(\(\) => \{[\s\S]{0,400}?deliverCommand\(/)+ })++ it('only a REAL teardown clears it — a park keeps the session typeable by name', () => {+ // The park branch returns before this line; a parked tmux session is still addressable by+ // `sendText`, so clearing there would strand a launch that could have been delivered.+ expect(src).toMatch(/life\.dead = true[\s\S]{0,600}?setSessionReady\(id, false\)/)+ // Exactly three publish sites: mount (adopt-or-not), settle, teardown. A fourth means+ // somebody has taught another path to claim readiness it cannot vouch for.+ expect(src.match(/setSessionReady\(/g)?.length).toBe(4) // 3 call sites + the definition+ })+})++describe('an ARMED node does not cold-start its agent under the hold (source pins)', () => {+ it('the cold-restore relaunch is gated on there being no pendingLaunch', () => {+ // A first open is `fresh` by definition, so without this every `--after` / `verify` node+ // launched a bare CLI on mount — and Canvas's held launch then arrived as TEXT typed into+ // the session the hold existed to prevent.+ expect(src).toContain('fresh && agentId && canResume(agentId) && !data.pendingLaunch')+ })+})++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)')+ })++ it('the manual ▶ disarms only on a delivery that landed', () => {+ // Dropping `pendingLaunch` unconditionally threw the command away whenever the session was+ // not up — precisely the state a user reaches for this button in.+ expect(src).toMatch(+ /pty\.sendText\(id, pendingLaunch\.command\)\.then\(\(ok\) => \{[\s\S]{0,600}?if \(ok\)[\s\S]{0,300}?pendingLaunch: undefined/+ )+ expect(src).toMatch(/else \{[\s\S]{0,200}?markFailed\(id, 1\)/)+ })+})diff --git a/src/renderer/state/launchDelivery.test.ts b/src/renderer/state/launchDelivery.test.tsnew file mode 100644index 000000000..863871f82--- /dev/null+++ b/src/renderer/state/launchDelivery.test.ts@@ -0,0 +1,51 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useLaunchDelivery } from './launchDelivery'++/**+ * Issue #569 item 1 — the transient record behind the QUEUED badge's warning.+ *+ * The rule the whole store exists for: a launch that was abandoned must be VISIBLE. It used to be+ * a `console.warn` and nothing else, so a node that never started looked exactly like one still+ * waiting on a dependency — from the canvas and, more expensively, from an orchestrator driving+ * the canvas from outside.+ */+describe('useLaunchDelivery', () => {+ beforeEach(() => useLaunchDelivery.setState({ byId: {} }))++ it('reports nothing by default — absent is "waiting normally", not "fine"', () => {+ expect(useLaunchDelivery.getState().byId['term-1']).toBeUndefined()+ })++ it('markStalled is idempotent: the age does not restart on every re-render', () => {+ const s = useLaunchDelivery.getState()+ s.markStalled('term-1')+ const first = useLaunchDelivery.getState().byId['term-1']+ s.markStalled('term-1')+ expect(useLaunchDelivery.getState().byId['term-1']).toBe(first)+ })++ it('never downgrades a failure back to a stall', () => {+ const s = useLaunchDelivery.getState()+ s.markFailed('term-1', 5)+ s.markStalled('term-1')+ expect(useLaunchDelivery.getState().byId['term-1']?.kind).toBe('failed')+ })++ it('keeps the LARGER attempt count — the manual ▶ must not rewrite history', () => {+ const s = useLaunchDelivery.getState()+ s.markFailed('term-1', 5)+ s.markFailed('term-1', 1) // the ▶ button's single refusal+ const st = useLaunchDelivery.getState().byId['term-1']+ expect(st).toMatchObject({ kind: 'failed', attempts: 5 })+ })++ it('clear removes the entry, and clearing an unknown id changes nothing', () => {+ const s = useLaunchDelivery.getState()+ s.markFailed('term-1', 2)+ const before = useLaunchDelivery.getState().byId+ s.clear('term-nope')+ expect(useLaunchDelivery.getState().byId).toBe(before)+ s.clear('term-1')+ expect(useLaunchDelivery.getState().byId['term-1']).toBeUndefined()+ })+})diff --git a/src/renderer/state/launchDelivery.ts b/src/renderer/state/launchDelivery.tsnew file mode 100644index 000000000..9925a4fa8--- /dev/null+++ b/src/renderer/state/launchDelivery.ts@@ -0,0 +1,63 @@+import { create } from 'zustand'+import type { LaunchDelivery } from '../lib/pendingLaunch'++/**+ * What happened to an ARMED node's held launch (canvas-control `--after`, or the cold-open arming+ * a `--project` open leaves behind) — the visible half of the delivery loop that Canvas runs.+ *+ * TRANSIENT on purpose, like the live half of `agentStatus`. A delivery outcome describes THIS+ * app run's attempt to start a session: it is not a property of the canvas, it must not ride+ * `.nodeterm/project.json` to a teammate's machine, and a restart legitimately retries from+ * scratch. Nothing here is persisted.+ *+ * Absent = nothing to report: the node is simply waiting on its dependencies (which the QUEUED+ * badge already explains), or it has not been armed at all.+ *+ * The states, and why both exist:+ * - `stalled` — the gate is OPEN (every dependency is satisfied) but the node's terminal has not+ * come up, so there is nothing to deliver INTO yet. We keep waiting — an SSH host that comes+ * back, a slow spawn and a project the user just switched to all end here first — but we say+ * so, because "queued, indefinitely, with no reason given" is the exact complaint this whole+ * change answers (#569 item 1).+ * - `failed` — the terminal DID come up and refused the launch anyway, for every attempt in the+ * backoff schedule. That is a real dead end: nothing further will retry it, so the badge must+ * carry the warning and point at the manual ▶.+ *+ * Neither state is ever inferred from silence. `stalled` is raised by a timer that starts when+ * the gate opens, `failed` only after a delivery was actually attempted and refused.+ */+export type { LaunchDelivery }++interface LaunchDeliveryStore {+ byId: Record<string, LaunchDelivery | undefined>+ /** The gate opened but the node's session is not up yet — still waiting, and saying so. */+ markStalled: (nodeId: string) => void+ /** Every attempt in the schedule was refused. Terminal: only ▶ (or a respawn) revives it. */+ markFailed: (nodeId: string, attempts: number) => void+ /** Delivered, disarmed, or the node is gone — nothing left to report. */+ clear: (nodeId: string) => void+}++export const useLaunchDelivery = create<LaunchDeliveryStore>((set) => ({+ byId: {},+ markStalled: (nodeId) =>+ set((s) =>+ // Idempotent: the sweep can re-raise this on every re-render, and a fresh `since` on each+ // would make the badge's age tick backwards. `failed` is never downgraded to `stalled`.+ s.byId[nodeId] ? s : { byId: { ...s.byId, [nodeId]: { kind: 'stalled', since: Date.now() } } }+ ),+ markFailed: (nodeId, attempts) =>+ set((s) => {+ // Never let a later, smaller count shrink the record: the manual ▶ reports its own single+ // refusal, and it must not rewrite "5 attempts were refused" as "1 was".+ const prev = s.byId[nodeId]+ const total = Math.max(attempts, prev?.kind === 'failed' ? prev.attempts : 0)+ return { byId: { ...s.byId, [nodeId]: { kind: 'failed', attempts: total, at: Date.now() } } }+ }),+ clear: (nodeId) =>+ set((s) => {+ if (!s.byId[nodeId]) return s+ const { [nodeId]: _gone, ...rest } = s.byId+ return { byId: rest }+ })+}))diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 7859f558e..e953c23d9 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1576,6 +1576,14 @@ body,gap: 4px;}+/* …and the same chip once the delivery loop has something to report about that launch: it has been+ ready to run for a long time with no terminal to run in, or its delivery was refused for good.+ Amber rather than the NEEDS-YOU red: nothing is broken in the user's work, but the session they+ were told would start has not, and that must not be discoverable only in a console.warn. */+.term-node__status--queued-warn {+ color: #ffb340;+}+/* Copy receipt (1.6 s) — green like the base chip, and deliberately quieter than RUNNING /NEEDS YOU: this is a receipt, not an alert. */.term-node__queued-run {