Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(control): retain unacknowledged agent launches and report delivery honestly
enesa4c9fb42f049
diff --git a/CLAUDE.md b/CLAUDE.mdindex 148e8508b..71f5bd9a8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2571,9 +2571,10 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilelive **`lastTurnError`** is NOT (issue #521, below). (2) Only `hasHooks` agents may bewaited on — a plain terminal never reports done, so `resolveAfter` **refuses** it rather thanletting `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- `initialCommand` so the node's own mount path delivers it through `writeWhenShellReady` —- arming would hand delivery to the canvas effect, which races the node's PTY into existence.+ (3) **Control opens always retain the command in `pendingLaunch` until delivery lands**+ (#827/#811). Even a visible node with no deps has not mounted its PTY when the open reply is+ sent. `queueControlLaunch` moves the command out of `initialCommand`; the PTY-ready gate below+ makes this safe. The open reply says `queued`, and project serialization retains the brief.(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 (`launchRetryDelay`'s backoff) instead of vanishing.@@ -2627,6 +2628,11 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile`--project` cold-open branch — an orchestrator was previously told "opened" either way androuted 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.+ `queued:false` is NOT proof of a running CLI: Server's `deliveredIds` acknowledges terminal+ delivery only. Its initial commands are persisted before attach/send and retained on failure;+ only acknowledged sends clear them. Boot ownership remains fail-closed. Desktop `list` (live+ and stored projects) names QUEUED / LAUNCH FAILED / DROPPED / AGENT STATUS UNCONFIRMED rather+ than treating absence of a hook as success. Server v1 still explicitly refuses `list`.**(8) An armed node must not cold-start its own agent** (found while fixing (7)). The mount-timecold-restore relaunch (`fresh && agentId && canResume(...)`) carries a second, independentrefusal beside the `paused` one (`shouldColdResume`): `!data.pendingLaunch`. A first open isdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 2fc26fff9..8f7aceaf6 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -654,6 +654,9 @@ the link; recheck resolution before publishing. SSH uses plain readlink and cd -and refuses dangling/cyclic links and newline paths. A conflicting/stale lock skips installationwith a diagnostic naming the lock and safe manual recovery; do not steal it from another process. These lockscoordinate nodeterm, not external editors, so do not claim a filesystem-wide compare-and-swap.+**Creating an agent node is not proof it started.** Control opens retain their launch command+until delivery is acknowledged, and report `queued` while it is held. A successful terminal send+proves delivery only; never describe it as a healthy/running agent without agent evidence.## Testingdiff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 021206733..e1545772f 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -448,14 +448,16 @@ export function buildCanvasControlInstructions(shimPath: string): string {' returned to YOU in this session. 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',+ ' The reply reports delivery: `queued` is true (and `queuedIds`',+ ' lists which) while launch delivery is pending, including a visible node waiting for its PTY,',+ ' or one waiting on `--after`, on a worktree\'s',' setup script, or on a project the user has not viewed yet (a `--project` target, or your',' own project while they are looking elsewhere). A queued node',- ' exists on the canvas but has no process behind it: do not route work to it, do not',+ ' exists on the canvas but its agent launch has not been delivered: 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.',+ ' `queued: false` is not proof the agent is running. `deliveredIds` confirms command delivery only.',+ ' `list` names QUEUED, LAUNCH FAILED, DROPPED and AGENT STATUS UNCONFIRMED where observed.',' `--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',@@ -909,14 +911,15 @@ Verbs:**closed**, the node is still saved into it and the reply says so; the tab is not reopened foryou. So: opening a station is safe to do at any time, but a station you opened while the user waselsewhere is not running yet — read \`queued\` before you route work to it.- **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+ **The reply reports launch delivery, not agent health.** \`queued\` is true — and+ \`queuedIds\` names which of the returned ids — while launch delivery is pending: waiting for its PTY, or on\`--after\`, on a worktree's setup script, or on a project the user has not viewed yet (a\`--project\` target, or your own project while they are looking elsewhere).- A queued node exists on the canvas but has **no process behind it**, so do not route work+ A queued node exists on the canvas but its **agent launch has not been delivered**, so do not route workto it, do not \`send\` to it and do not report it as started. It launches itself when its waitends and then reports through the ordinary status hooks, so there is nothing to poll.- \`queued: false\` means the session is running.+ \`queued: false\` does not prove the agent is running. \`deliveredIds\` confirms command delivery only.+ \`list\` names QUEUED, LAUNCH FAILED, DROPPED and AGENT STATUS UNCONFIRMED where observed.\`--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/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex ab352d29c..409512313 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -412,9 +412,10 @@ describe('parseControlRequest', () => {// 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+ // The consequence is the whole point of the field: an armed node has no delivered agent launch, so an// orchestrator must not route work to it. Without this sentence the flag reads as trivia.- expect(body.toLowerCase()).toContain('no process')+ expect(body.toLowerCase()).toContain('launch has not been delivered')+ expect(body).toContain('deliveredIds')// 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')diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 2326fef99..b0e40af68 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -266,6 +266,7 @@ import {offScreenRefusal,sourceIsControlCapable,storedNodeListing,+ controlListingText,answerBrowserResolve,type BrowserResolveProject} from '../lib/controlRouting'@@ -462,7 +463,7 @@ import { buildBackgroundLinkMaps, buildContextLinkNote, buildLinkMap, buildNotePimport {launchesToFire,launchRetryDelay,- unmetDeps,+ queueControlLaunch,LAUNCH_STALL_MS,type ArmedNode} from '../lib/pendingLaunch'@@ -1890,7 +1891,8 @@ export function Canvas() {nodes as unknown as ArmedNode[],useAgentStatus.getState().byId,live,- setupDoneForGroup+ setupDoneForGroup,+ useLaunchDelivery.getState().byId).filter((f) => !launchInFlight.current.has(f.id))// Anything we were reporting on that is no longer an armed node — delivered, run by hand with// ▶, or deleted — stops being reported. Timers go with it: a stall warning for a node that has@@ -1939,7 +1941,7 @@ export function Canvas() {launchInFlight.current.add(f.id)const attempt = (launchAttempts.current.get(f.id) ?? 0) + 1launchAttempts.current.set(f.id, attempt)- void api.pty.sendText(f.id, f.command).then((ok) => {+ void api.pty.sendText(f.id, f.command).catch(() => false).then((ok) => {if (ok) {setNodes((ns) =>ns.map((n) => (n.id === f.id ? { ...n, data: { ...n.data, pendingLaunch: undefined } } : n))@@ -10075,14 +10077,16 @@ export function Canvas() {// The skill text names the workaround (open a reader agent inside the target project).if (tgActive) {// The human is looking at the target (the caller is a background orchestrator):- // live-canvas insertion, normal initialCommand — the session starts immediately.- setNodes((ns) => [...ns, ...tgMade])+ // live insertion still precedes PTY readiness: keep the launch queued.+ const tgQueuedIds = tgMade.filter((n) => !!n.data.initialCommand).map((n) => n.id)+ setNodes((ns) => [...ns, ...tgMade.map((node) => queueControlLaunch(node))])markDirty()reply({ok: true,- message: `opened ${tgCount} ${tgWhat} session(s) in "${target.name}" (${tgIds.join(', ')})`,- // The target is on screen, so these started normally — nothing is queued.- result: { ids: tgIds, id: tgIds[0], projectId: target.id, queued: false, queuedIds: [] }+ message: `opened ${tgCount} ${tgWhat} session(s) in "${target.name}" (${tgIds.join(', ')})` ++ (tgQueuedIds.length ? ' — queued; awaiting launch delivery' : ''),+ // Being on screen is not proof of launch delivery.+ result: { ids: tgIds, id: tgIds[0], projectId: target.id, queued: tgQueuedIds.length > 0, queuedIds: tgQueuedIds }})return}@@ -10229,11 +10233,11 @@ export function Canvas() {return}if (!needsLiveCanvas(verb)) {- const rows = storedNodeListing(projects.find((p) => p.id === route.projectId)?.nodes ?? [])+ const rows = storedNodeListing(projects.find((p) => p.id === route.projectId)?.nodes ?? [], useAgentStatus.getState().byId, useLaunchDelivery.getState().byId)reply({ok: true,result: rows,- message: rows.map((n) => `${n.id} [${n.kind}] ${n.title}`).join('\n')+ message: controlListingText(rows)})return}@@ -10792,16 +10796,12 @@ export function Canvas() {// Hold a freshly-built node's launch instead of running it on open. The factories already// composed the exact command (agent CLI + permission-mode flag + prompt, or --cmd), so it// is MOVED rather than rebuilt — a second construction site is how the two drift apart.- // `extraLive` names nodes being created in this same tick — `verify` arms its judge on- // reviewers that are not on the canvas yet, and without this they would look DELETED,- // which counts as satisfied, and the judge would fire before a single review existed.// `intoGroup` adds the SECOND reason to hold a launch: the node is being opened into a// worktree frame whose project setup script is still preparing the checkout (and said// `waitForSetup`). Same mechanism, same escape hatch on the node — see `awaitSetupGroup`.const armAfter = (node: CanvasNode,after: string[],- extraLive?: Iterable<string>,intoGroup?: string | null): CanvasNode => {const command = node.data.initialCommand as string | undefined@@ -10815,27 +10815,9 @@ export function Canvas() {setupWaitGroupsRef.current.has(intoGroup)) &&!setupDoneForGroup(intoGroup)const awaitSetupGroup = holdsForSetup ? intoGroup ?? undefined : undefined- if (!after.length && !awaitSetupGroup) return node- // If the wait is ALREADY over, don't arm at all — leave the command as the node's- // `initialCommand` so its own mount path delivers it through `writeWhenShellReady`- // (which waits for the shell prompt and echo-verifies). Arming would instead hand- // delivery to the canvas effect, which would race the node's PTY into existence and- // could fire into a session that does not exist yet.- const live = new Set([...nodesRef.current.map((nd) => nd.id), ...(extraLive ?? [])])- const unmet = unmetDeps(- { id: node.id, data: { pendingLaunch: { after, command } } },- useAgentStatus.getState().byId,- live- )- if (!unmet.length && !awaitSetupGroup) return node- return {- ...node,- data: {- ...node.data,- initialCommand: undefined,- pendingLaunch: { after, command, ...(awaitSetupGroup ? { awaitSetupGroup } : {}) }- }- }+ // Always retain the command until the PTY-ready delivery loop acknowledges it.+ // Node creation (even on screen) is not command delivery.+ return queueControlLaunch(node, after, awaitSetupGroup)}// Open `count` nodes INTO a group frame: grow the frame FIRST (extent:'parent' would// clamp children landing outside it), then drop each node into the next grid slot@@ -10882,23 +10864,11 @@ export function Canvas() {// 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,- ...(st[n.id]?.lastTurnError ? { lastTurnErrored: true } : {})- }))- reply({- ok: true,- result: list,- message: list- .map(- (n) =>- `${n.id} [${n.kind}] ${n.title}` +- (n.lastTurnErrored ? ' — LAST TURN ERRORED' : '')- )- .join('\n')- })+ const list = storedNodeListing(nodesRef.current.map((n) => ({+ id: n.id, kind: n.type, title: n.data.title as string,+ pendingLaunch: n.data.pendingLaunch, agentId: n.data.agentId as string | undefined+ })), st, useLaunchDelivery.getState().byId)+ reply({ ok: true, result: list, message: controlListingText(list) })return}case 'open-terminal': {@@ -10932,12 +10902,7 @@ export function Canvas() {})return}- // 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.+ // Every command is held until delivery, including a visible node with no deps.const queuedIds: string[] = []const make = (i: number): CanvasNode => {const node = armAfter(@@ -10949,7 +10914,6 @@ export function Canvas() {sshFor(termCwd)),after ?? [],- undefined,intoGroupId)if (node.data.pendingLaunch) queuedIds.push(node.id)@@ -10963,6 +10927,7 @@ export function Canvas() {ok: true,message:`opened ${count} terminal(s): ${ids.join(', ')}` ++ (queuedIds.length ? '\nqueued; awaiting launch delivery' : '') +(after?.length ? `\nwaiting for ${after.join(', ')} before running` : ''),result: {ids,@@ -11094,7 +11059,6 @@ export function Canvas() {promptFile ?? promptLaunch.promptFile),after ?? [],- undefined,intoGroupId)if (node.data.pendingLaunch) queuedIds.push(node.id)@@ -11126,6 +11090,7 @@ export function Canvas() {ok: true,message:`opened ${count} ${agentId} session(s): ${ids.join(', ')}` ++ (queuedIds.length ? '\nqueued; awaiting launch delivery' : '') +(bridged.length ? `\ncontext-linked to you: ${bridged.join(', ')}` : '') +(after?.length? `\nwaiting for ${after.join(', ')} before running` +@@ -11517,8 +11482,7 @@ export function Canvas() {)return { ...j, data: { ...j.data, title: 'Verify: verdict', titleAuto: false } }})(),- reviewerIds,- reviewerIds // the reviewers exist only in this tick — see armAfter+ reviewerIds): nullconst panelIds = [...reviewerIds, ...(judge ? [judge.id] : [])]diff --git a/src/renderer/canvas/pending-launch-delivery.source.test.ts b/src/renderer/canvas/pending-launch-delivery.source.test.tsindex 914dd22f6..d4ad3ff1c 100644--- a/src/renderer/canvas/pending-launch-delivery.source.test.ts+++ b/src/renderer/canvas/pending-launch-delivery.source.test.ts@@ -92,19 +92,3 @@ describe('armed-launch delivery (source pins)', () => {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/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.tsindex eca5390ab..7f06ec1c9 100644--- a/src/renderer/lib/controlRouting.test.ts+++ b/src/renderer/lib/controlRouting.test.ts@@ -10,6 +10,7 @@ import {controlVerbSetsForTests,sourceIsControlCapable,storedNodeListing,+ controlListingText,answerBrowserResolve,type ControlProject,type BrowserResolveProject@@ -419,3 +420,32 @@ describe('the off-screen disposition table (the verbs that used to travel)', ()for (const v of storeAnswered) expect(needsLiveCanvas(v), v).toBe(false)})})+++it('lists held, failed and unconfirmed launches without claiming an agent is healthy', () => {+ const nodes = [+ { id: 'queued', pendingLaunch: { command: 'claude' } },+ { id: 'failed', pendingLaunch: { command: 'codex' } },+ { id: 'stalled', pendingLaunch: { command: 'claude' } },+ { id: 'dead', agentId: 'claude' },+ { id: 'unknown', agentId: 'codex' },+ { id: 'errored', agentId: 'claude' },+ { id: 'shell' }+ ]+ const rows = storedNodeListing(nodes, {+ dead: { dropped: true, state: 'done' },+ errored: { state: 'done', lastTurnError: { at: 1 } }+ }, {+ failed: { kind: 'failed', attempts: 5, at: 1 },+ stalled: { kind: 'stalled', since: 1 }+ })+ expect(rows.map((r) => r.launchState)).toEqual(['queued', 'failed', 'stalled', 'dropped', 'unconfirmed', undefined, undefined])+ const text = controlListingText(rows)+ expect(text).toContain('queued [terminal] — QUEUED')+ expect(text).toContain('failed [terminal] — LAUNCH FAILED')+ expect(text).toContain('stalled [terminal] — QUEUED (terminal not ready)')+ expect(text).toContain('dead [terminal] — DROPPED')+ expect(text).toContain('unknown [terminal] — AGENT STATUS UNCONFIRMED')+ expect(text).toContain('errored [terminal] — LAST TURN ERRORED')+ expect(text).not.toContain('RUNNING')+})diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.tsindex 539a6195d..94b3d65c4 100644--- a/src/renderer/lib/controlRouting.ts+++ b/src/renderer/lib/controlRouting.ts@@ -14,6 +14,7 @@// that reads and changes nothing, answer straight out of its serialized nodes).import { canControlCanvas, type AgentId } from '@shared/agents/config'+import { controlLaunchState, type LaunchDelivery, type StatusById } from './pendingLaunch'import { projectTravel } from './presenceTravel'import {projectCapabilityGrantedFor,@@ -33,6 +34,8 @@ export interface StoredNode {id: stringkind?: stringtitle?: string+ pendingLaunch?: unknown+ agentId?: string}/**@@ -167,7 +170,34 @@ export function answerBrowserResolve(/** `list`'s rows, built from serialized nodes — the same shape the live canvas answers with* (`n.type` is the persisted `kind`, `n.data.title` the persisted `title`). */export function storedNodeListing(- nodes: readonly StoredNode[]-): { id: string; kind: string; title: string }[] {- return nodes.map((n) => ({ id: n.id, kind: n.kind ?? 'terminal', title: n.title ?? '' }))+ nodes: readonly StoredNode[],+ statuses: StatusById & Record<string, { dropped?: boolean } | undefined> = {},+ deliveries: Record<string, LaunchDelivery | undefined> = {}+) {+ return nodes.map((n) => {+ const status = statuses[n.id]+ const launchState = controlLaunchState(!!n.pendingLaunch, deliveries[n.id], status) ??+ (n.agentId && !status?.state ? 'unconfirmed' as const : undefined)+ return {+ id: n.id, kind: n.kind ?? 'terminal', title: n.title ?? '',+ ...(status?.lastTurnError ? { lastTurnErrored: true } : {}),+ ...(launchState ? { launchState } : {})+ }+ })+}++const launchLabels = {+ queued: 'QUEUED',+ failed: 'LAUNCH FAILED',+ stalled: 'QUEUED (terminal not ready)',+ dropped: 'DROPPED',+ working: 'WORKING',+ unconfirmed: 'AGENT STATUS UNCONFIRMED'+} as const++export function controlListingText(rows: ReturnType<typeof storedNodeListing>): string {+ return rows.map((n) => `${n.id} [${n.kind}] ${n.title}` ++ (n.launchState ? ` — ${launchLabels[n.launchState]}` : '') ++ (n.lastTurnErrored ? ' — LAST TURN ERRORED' : '')+ ).join('\n')}diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.tsindex 5a75a50fa..9104e8505 100644--- a/src/renderer/lib/pendingLaunch.test.ts+++ b/src/renderer/lib/pendingLaunch.test.ts@@ -1,6 +1,8 @@import { describe, it, expect } from 'vitest'import {launchesToFire,+ queueControlLaunch,+ controlLaunchState,launchRetryDelay,launchTooltip,unmetDeps,@@ -238,3 +240,56 @@ describe('launchTooltip — the QUEUED badge never goes silent (#569 item 1)', (expect(t).not.toContain('Waiting for Builder')})})+++describe('control opens retain an unacknowledged launch (#827/#811)', () => {+ it.each(['claude', 'codex'])('queues %s even on a visible canvas with no dependencies', (agent) => {+ const original = { id: 'new', data: { initialCommand: `${agent} brief`, pendingLaunch: undefined } }+ const node = queueControlLaunch(original)+ expect(node.data.initialCommand).toBeUndefined()+ expect(node.data.pendingLaunch).toEqual({ after: [], command: `${agent} brief` })+ expect(controlLaunchState(!!node.data.pendingLaunch, undefined)).toBe('queued')+ // Simulate a project save/view: only durable data survives; the command must still fire.+ const restored = JSON.parse(JSON.stringify(node))+ expect(launchesToFire([restored], {}, new Set(['new']))).toEqual([{ id: 'new', command: `${agent} brief` }])+ expect(original.data.initialCommand).toBe(`${agent} brief`)+ })++ it('preserves dependency and setup gates until delivery, including already-done dependencies', () => {+ const node = queueControlLaunch({ id: 'new', data: { initialCommand: 'claude brief' } }, ['upstream'], 'setup')+ const live = new Set(['new', 'upstream'])+ expect(launchesToFire([node], {}, live, () => true)).toEqual([])+ expect(launchesToFire([node], { upstream: { state: 'done' } }, live, () => false)).toEqual([])+ expect(launchesToFire([node], { upstream: { state: 'done' } }, live, () => true)).toEqual([{ id: 'new', command: 'claude brief' }])+ })++ it('does not invent a launch for a plain shell or overwrite an existing hold', () => {+ const node = armed('held', ['upstream'])+ expect(queueControlLaunch(node)).toBe(node)+ const shell = { data: {} }+ expect(queueControlLaunch(shell)).toBe(shell)+ })++ it('does not infer running from delivery, idle, or absence of errors', () => {+ expect(controlLaunchState(false, undefined)).toBeUndefined()+ expect(controlLaunchState(false, undefined, { state: 'done' })).toBeUndefined()+ expect(controlLaunchState(false, undefined, { state: 'working' })).toBe('working')+ expect(controlLaunchState(false, undefined, { state: 'working', dropped: true })).toBe('dropped')+ expect(controlLaunchState(true, { kind: 'failed', attempts: 5, at: 1 })).toBe('failed')+ expect(controlLaunchState(true, { kind: 'stalled', since: 1 })).toBe('stalled')+ })+})+++it('a dependency-free launch tooltip names delivery rather than an empty dependency', () => {+ expect(launchTooltip(undefined, '', 'codex')).toBe('Queued; waiting for launch delivery.\nRuns:\ncodex')+})+++it('an exhausted delivery stays held on rerender; a stalled terminal may still become ready', () => {+ const node = armed('new', [])+ const live = new Set(['new'])+ expect(launchesToFire([node], {}, live, undefined, { new: { kind: 'failed', attempts: 5, at: 1 } })).toEqual([])+ expect(node.data.pendingLaunch?.command).toBe('echo new')+ expect(launchesToFire([node], {}, live, undefined, { new: { kind: 'stalled', since: 1 } })).toEqual([{ id: 'new', command: 'echo new' }])+})diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.tsindex f31cbd614..351119a9a 100644--- a/src/renderer/lib/pendingLaunch.ts+++ b/src/renderer/lib/pendingLaunch.ts@@ -23,6 +23,37 @@ export interface LaunchToFire {command: string}+/** Control opens reply before the PTY exists. Keep their command durable until delivery lands,+ * even with no dependencies (or dependencies that are already done). */+export function queueControlLaunch<T extends { data: { initialCommand?: string; pendingLaunch?: PendingLaunch } }>(+ node: T,+ after: string[] = [],+ awaitSetupGroup?: string+): T & { data: { pendingLaunch?: PendingLaunch } } {+ const command = node.data.initialCommand+ if (!command) return node+ return {+ ...node,+ data: {+ ...node.data,+ initialCommand: undefined,+ pendingLaunch: { after, command, ...(awaitSetupGroup ? { awaitSetupGroup } : {}) }+ }+ }+}++/** A list row states only observed facts; absence of a launch error is not proof of a live CLI. */+export function controlLaunchState(+ pending: boolean,+ delivery: LaunchDelivery | undefined,+ status?: { dropped?: boolean; state?: AgentState }+): 'queued' | 'stalled' | 'failed' | 'dropped' | 'working' | undefined {+ if (pending) return delivery?.kind ?? 'queued'+ if (status?.dropped) return 'dropped'+ if (status?.state === 'working') return 'working'+ return undefined+}+/*** Is one dependency satisfied?*@@ -87,12 +118,14 @@ export function launchesToFire(nodes: readonly ArmedNode[],status: StatusById,live: ReadonlySet<string>,- setupDone?: (groupId: string) => boolean+ setupDone?: (groupId: string) => boolean,+ deliveries?: Record<string, LaunchDelivery | undefined>): LaunchToFire[] {const out: LaunchToFire[] = []for (const n of nodes) {const p = n.data.pendingLaunchif (!p || !p.command || p.executor === 'server') continue+ if (deliveries?.[n.id]?.kind === 'failed') continueif (p.awaitSetupGroup && !(setupDone?.(p.awaitSetupGroup) ?? true)) continueif (p.after.every((d) => depSatisfied(d, status, live))) out.push({ id: n.id, command: p.command })}@@ -193,5 +226,7 @@ export function launchTooltip('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}`+ return waitingOn+ ? `Waiting for ${waitingOn} to finish, then runs:\n${command}`+ : `Queued; waiting for launch delivery.\n${runs}`}diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.tsindex 55768d6bf..d29a91509 100644--- a/src/server/headless-node-factory.test.ts+++ b/src/server/headless-node-factory.test.ts@@ -199,7 +199,8 @@ describe('HeadlessNodeFactory', () => {})])expect(pty.sends).toEqual([{ nodeId: id, text: 'printf hello' }])- expect(published.map((node) => node.id)).toEqual([id])+ // The persisted hold is published first, then its acknowledged delivery.+ expect(published.map((node) => node.id)).toEqual([id, id])expect(fs.existsSync(path.join(dataDir, 'workspace.json'))).toBe(true)const projectFile = path.join(projectDir, '.nodeterm', 'project.json')@@ -1014,6 +1015,43 @@ describe('HeadlessNodeFactory', () => {})})+ it.each(['claude', 'codex'])('reports delivered, not running, for %s', async (agent) => {+ const reply = await factory.openAgent('term-source', { agent, prompt: 'work' }, true)+ const id = (reply.result as { id: string }).id+ expect(reply).toMatchObject({ ok: true, result: { queued: false, queuedIds: [], deliveredIds: [id], failed: [] } })+ expect(reply.message).toContain('agent startup is not confirmed')+ const workspace = await store.load({ sideline: false })+ expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toBeUndefined()+ })++ it.each(['refused', 'throws', 'no-pty'])('retains the exact initial command after %s', async (failure) => {+ if (failure === 'no-pty') vi.spyOn(pty, 'createHeadless').mockRejectedValueOnce(new Error('unavailable'))+ else if (failure === 'throws') vi.spyOn(pty, 'sendText').mockRejectedValueOnce(new Error('disconnected'))+ else vi.spyOn(pty, 'sendText').mockResolvedValueOnce(false)+ const reply = await factory.openAgent('term-source', { agent: 'claude', prompt: 'keep this brief' }, true)+ const id = (reply.result as { id: string }).id+ expect(reply).toMatchObject({ ok: false, result: { deliveredIds: [], failed: [id] } })+ expect(reply.error).toContain('do not repeat the open request')+ const workspace = await store.load({ sideline: false })+ expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toMatchObject({+ after: [], command: "claude 'keep this brief'", executor: 'server'+ })+ })++ it('reports a partial batch and recovers only the retained launch', async () => {+ vi.spyOn(pty, 'sendText').mockResolvedValueOnce(true).mockResolvedValueOnce(false)+ const reply = await factory.openAgent('term-source', { agent: 'codex', prompt: 'work', count: '2' }, true)+ const [delivered, failed] = (reply.result as { ids: string[] }).ids+ expect(reply).toMatchObject({ ok: false, result: { deliveredIds: [delivered], failed: [failed], queuedIds: [] } })+ const workspace = await store.load({ sideline: false })+ expect(workspace.projects[0].nodes.find((node) => node.id === failed)?.pendingLaunch?.command)+ .toContain("codex 'work'")+ pty.sends.length = 0+ await factory.refreshArmed()+ await factory.refreshArmed()+ expect(pty.sends.map((send) => send.nodeId)).toEqual([failed])+ })+it('persists --after without launching, then flushes exactly once on the idle state', async () => {states['term-upstream'] = 'working'const reply = await factory.openAgent(@@ -1024,6 +1062,8 @@ describe('HeadlessNodeFactory', () => {expect(reply.ok).toBe(true)const id = (reply.result as { id: string }).idexpect(pty.sends).toEqual([])+ expect(reply.result).toMatchObject({ queued: true, queuedIds: [id], deliveredIds: [] })+ expect(reply.message).toContain('queued:')let workspace = await store.load({ sideline: false })expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toEqual({diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.tsindex 8bfb8454c..bec60bb74 100644--- a/src/server/headless-node-factory.ts+++ b/src/server/headless-node-factory.ts@@ -1177,9 +1177,9 @@ export class HeadlessNodeFactory {}const id = nextId('term')- // Match the desktop's `armAfter`: if every dependency is already done, launch now rather- // than persisting a wait that has no future edge left to wake it.- const pendingLaunch = command && mustWait+ // Persist before attempting delivery, including launches whose gates are already open.+ // A failed attach/send must leave the command available to the user's Run now action.+ const pendingLaunch = command? {after,command,@@ -1208,7 +1208,7 @@ export class HeadlessNodeFactory {...(pendingLaunch ? { pendingLaunch } : {})}created.push(node)- if (command && !pendingLaunch) commands.set(id, command)+ if (command && !mustWait) commands.set(id, command)addEdge(ropes, source.node.id, id, 'ctrl')if (verb === 'open-agent') {@@ -1244,20 +1244,34 @@ export class HeadlessNodeFactory {}if (verb === 'open-agent' && result.fresh) this.awaitingFirstWorking.add(node.id)const command = commands.get(node.id)- if (command && !(await this.deps.ptyManager.sendText(node.id, command))) failed.push(node.id)+ if (command) {+ if (await this.deps.ptyManager.sendText(node.id, command)) node.pendingLaunch = undefined+ else failed.push(node.id)+ }} catch {failed.push(node.id)}}+ // Creation and delivery are separate transactions. A refused/throwing send retains the+ // exact command for the user's Run now action; boot still cannot adopt persisted nodes.+ await this.deps.workspaceStore.save(workspace)+ this.publish(target, created)const ids = created.map((node) => node.id)+ const queuedIds = created+ .filter((node) => node.pendingLaunch && !failed.includes(node.id))+ .map((node) => node.id)+ const deliveredIds = created+ .filter((node) => commands.has(node.id) && !node.pendingLaunch && !failed.includes(node.id))+ .map((node) => node.id)+ const launchResult = { queued: queuedIds.length > 0, queuedIds, deliveredIds, failed }if (failed.length) {return {ok: false,error:`launch-failed: node(s) ${failed.join(', ')} were persisted but their PTY or initial ` +- 'command could not be started; do not repeat the open request',- result: { ids, id: ids[0], after, failed }+ 'command could not be delivered; launch retained for Run now in the node; do not repeat the open request',+ result: { ids, id: ids[0], after, ...launchResult }}}return {@@ -1265,8 +1279,9 @@ export class HeadlessNodeFactory {message:`opened ${count} ${verb === 'open-agent' ? `${agentId} session` : 'terminal'}(s): ` +ids.join(', ') +- (after.length ? `; waiting for ${after.join(', ')} before running` : ''),- result: { ids, id: ids[0], after }+ (queuedIds.length ? `; queued: ${queuedIds.join(', ')}` : '') ++ (deliveredIds.length ? '; launch delivered; agent startup is not confirmed' : ''),+ result: { ids, id: ids[0], after, ...launchResult }}})}@@ -1398,7 +1413,7 @@ export class HeadlessNodeFactory {const live = this.attached.has(node.id) ||await this.deps.ptyManager.sessionExists(node.id).catch(() => false)if (!live) continue- if (!(await this.deps.ptyManager.sendText(node.id, pending.command))) {+ if (!(await this.deps.ptyManager.sendText(node.id, pending.command).catch(() => false))) {this.scheduleRetry(node.id)continue}