Skip to content

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

fix(launch): persist attempt proof for safe warm orchestration

review783d166d6826
diff --git a/CLAUDE.md b/CLAUDE.md
index 24a7af2c9..0987bea10 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2574,13 +2574,20 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
(4) Desktop automatic and manual launch delivery share `terminal/launch-command.ts`, which
uses `deliverCommand`: echo verification, bounded Ctrl-U repair, platform kill-line and overlong
line refusal. The PTY-lifetime writer coalesces concurrent requests and remembers submission
- across parked views. A warm attach never automatically replays a retained launch: its clearing
- autosave may have been lost after Enter. Explicit Run now rechecks the foreground shell and
+ across parked views. New intent has `attempted:false`; the writer awaits a workspace save of
+ `attempted:true, manualOnly:true` before input, then rechecks the shell after that save. A warm
+ attach may automatically deliver never-attempted intent, preserving long-running `--after`
+ graphs through project switches/park expiry. Attempted/legacy-unknown intent stays manual: its
+ clearing autosave may have been lost after Enter. Explicit Run now rechecks the foreground shell and
clears any incomplete line; a refused/throwing/cancelled launch stays held, `manualOnly`.
(5) UI `initialCommand` stays until submission; serialization converts unsubmitted UI intent
- into a manual-only `pendingLaunch`, including a project switch during shell settle. Server
- saves `manualOnly` BEFORE sending and only clears the command after acknowledgment. Failed
+ into a never-attempted `pendingLaunch`, including a project switch during shell settle. A live
+ initialCommand alias on remount cannot reset an attempted marker. Server saves
+ `attempted:true, manualOnly:true` BEFORE sending and only clears the command after acknowledgment. Failed
independent/dependent launches are never retried by unrelated hooks. Boot remains inert.
+ Server deferred delivery is deliberately one-shot: a transient probe/send failure needs Run now.
+ Desktop keeps the attached echo-verification transport even for offscreen held nodes; a large
+ long-waiting fan-out therefore keeps those xterm instances in memory until delivery/recovery.
(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);
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4e1248e68..6d21fdad5 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -658,10 +658,13 @@ coordinate nodeterm, not external editors, so do not claim a filesystem-wide com
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.
Desktop launches (automatic and Run now) use the echo-verified command writer, not `sendText`.
-Keep unsubmitted UI intent durable through shell settle/unmount. Warm attachments never auto-replay
-retained launch intent; Run now checks the shell and only confirmed submission clears it. Server
-marks attempts manual-only on disk before input, so failed delivery cannot retry on unrelated hooks.
-Held Desktop launches retain their attached transport, including when offscreen with tmux.
+Keep unsubmitted UI intent durable through shell settle/unmount. New intent carries `attempted:false`;
+Desktop and Server save `attempted:true` before input. Never-attempted warm `--after` launches may
+proceed after shell verification; attempted/legacy-unknown intent requires Run now. Only confirmed
+submission clears intent. Desktop open replies use `createControlOpenBatch` for queued accounting;
+protect that contract and concurrent submission with behavior tests, never source-text pins.
+Held Desktop launches retain their attached transport even offscreen with tmux (large fan-outs cost
+memory). Server deferred delivery is one-shot: a failed probe/send needs explicit recovery.
## Testing
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 66ad4a76e..b060eea42 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -1,3 +1,5 @@
+import { createControlOpenBatch } from '../lib/controlOpenBatch'
+import { commitLaunchAttempt, registerLaunchCommit } from '../terminal/launch-attempt'
import { launchCommand } from '../terminal/launch-command'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useShallow } from 'zustand/react/shallow'
@@ -1941,7 +1943,7 @@ export function Canvas() {
launchInFlight.current.add(f.id)
const attempt = (launchAttempts.current.get(f.id) ?? 0) + 1
launchAttempts.current.set(f.id, attempt)
- void launchCommand(f.id, f.command).then((outcome) => {
+ void launchCommand(f.id, f.command, false, activeSession.api).then((outcome) => {
if (outcome === 'submitted') {
setNodes((ns) =>
ns.map((n) => (n.id === f.id ? { ...n, data: { ...n.data, pendingLaunch: undefined } } : n))
@@ -1953,7 +1955,7 @@ export function Canvas() {
// The verified writer already exhausted its bounded echo repair. A failed launch
// needs an explicit retry; unrelated hooks and remounts must never inject it later.
setNodes((ns) => ns.map((n) => n.id === f.id && n.data.pendingLaunch
- ? { ...n, data: { ...n.data, pendingLaunch: { ...n.data.pendingLaunch, manualOnly: true } } }
+ ? { ...n, data: { ...n.data, pendingLaunch: { ...n.data.pendingLaunch, attempted: true, manualOnly: true } } }
: n))
markDirty()
useLaunchDelivery.getState().markFailed(f.id, attempt)
@@ -2777,6 +2779,42 @@ export function Canvas() {
await writeDisk()
}, [commitActiveToStore, writeDisk])
+ // Persist the attempt before a writer can send even its first byte. React Flow remains the
+ // live source: update its ref synchronously before serializing, not after an async setNodes.
+ useEffect(() => registerLaunchCommit(activeSession.api, async (nodeId, command, manual) => {
+ const projectId = useProjects.getState().activeProjectId
+ if (!canCommitCanvas(nodesProjectIdRef.current, projectId)) return false
+ const node = nodesRef.current.find((n) => n.id === nodeId)
+ if (!node) return false
+ return commitLaunchAttempt({
+ pending: node.data.pendingLaunch,
+ command,
+ manual,
+ update: (pendingLaunch) => {
+ const next = nodesRef.current.map((n) => n.id === nodeId
+ ? { ...n, data: { ...n.data, pendingLaunch } } : n)
+ nodesRef.current = next
+ setNodes(next)
+ markDirty()
+ commitActiveToStore()
+ },
+ save: async () => {
+ if (activeSession.api === api) {
+ await api.workspace.save(useProjects.getState().toWorkspace())
+ } else {
+ // Relay projects are intentionally absent from the local workspace serializer.
+ // Save on the owning core, preserving its other projects and the node's full content.
+ const workspace = await activeSession.api.workspace.load()
+ const matches = workspace.projects.flatMap((p) => p.nodes).filter((n) => n.id === nodeId)
+ if (matches.length !== 1 || matches[0].pendingLaunch?.command !== command)
+ throw new Error('launch intent changed before persistence')
+ matches[0].pendingLaunch = { ...matches[0].pendingLaunch!, attempted: true, manualOnly: true }
+ await activeSession.api.workspace.save(workspace)
+ }
+ }
+ })
+ }), [activeSession.api, api, commitActiveToStore, markDirty, setNodes])
+
// Global kanban reads ALL lanes from serialized `p.nodes`, but the active project's
// live React Flow nodes may have uncommitted edits (title rename, new node). Commit
// before the board mounts so the active lane matches the canvas — the other lanes are
@@ -10896,7 +10934,7 @@ export function Canvas() {
return
}
// Every command is held until delivery, including a visible node with no deps.
- const queuedIds: string[] = []
+ const openBatch = createControlOpenBatch()
const make = (i: number): CanvasNode => {
const node = armAfter(
createTerminalNode(
@@ -10909,26 +10947,21 @@ export function Canvas() {
after ?? [],
intoGroupId
)
- if (node.data.pendingLaunch) queuedIds.push(node.id)
- return node
+ return openBatch.add(node)
}
const ids = intoGroupId
? addGrouped(intoGroupId, count, make)
: Array.from({ length: count }, (_, i) => addAndConnect(make(i)))
ropeDeps(ids, after)
+ const openResult = openBatch.result(after ?? [])
+ const { queuedIds } = openResult
reply({
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,
- id: ids[0],
- after: after ?? [],
- queued: queuedIds.length > 0,
- queuedIds
- }
+ result: openResult
})
return
}
@@ -11026,7 +11059,7 @@ export function Canvas() {
}
// 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 openBatch = createControlOpenBatch()
// A `--prompt` over the typed-line budget is spilled to a file and delivered through
// the same `"$(cat …)"` substitution `--prompt-file` uses (#706). An explicit
// `--prompt-file` already took that route and is passed through untouched.
@@ -11054,13 +11087,14 @@ export function Canvas() {
after ?? [],
intoGroupId
)
- if (node.data.pendingLaunch) queuedIds.push(node.id)
- return node
+ return openBatch.add(node)
}
const ids = intoGroupId
? addGrouped(intoGroupId, count, make)
: Array.from({ length: count }, (_, i) => addAndConnect(make(i)))
ropeDeps(ids, after)
+ const openResult = openBatch.result(after ?? [])
+ const { queuedIds } = openResult
// Context-link the new session(s) back to the opener (same rationale as spawn-team:
// the fan-out needs a fan-in). The nodes were added via setNodes in this tick, so
// resolve their endpoints from `agentId` rather than the not-yet-updated canvas.
@@ -11090,11 +11124,8 @@ export function Canvas() {
(depLinked.length ? ` (and linked to read them)` : '')
: ''),
result: {
- ids,
- linked: bridged,
- after: after ?? [],
- queued: queuedIds.length > 0,
- queuedIds
+ ...openResult,
+ linked: bridged
}
})
return
diff --git a/src/renderer/lib/controlOpenBatch.test.ts b/src/renderer/lib/controlOpenBatch.test.ts
new file mode 100644
index 000000000..13de160aa
--- /dev/null
+++ b/src/renderer/lib/controlOpenBatch.test.ts
@@ -0,0 +1,22 @@
+import { expect, it } from 'vitest'
+import { createControlOpenBatch } from './controlOpenBatch'
+import { launchesToFire } from './pendingLaunch'
+
+it.each(['open-terminal', 'open-agent', 'open-claude'])('%s on the visible Desktop reports queued before a terminal exists', (verb) => {
+ const batch = createControlOpenBatch()
+ const nodes = ['one', 'two'].map((id) => batch.add({ id, data: {
+ initialCommand: verb === 'open-terminal' ? 'echo brief' : 'claude complete-brief'
+ } }))
+ expect(batch.result()).toEqual({ ids: ['one', 'two'], id: 'one', after: [], queued: true, queuedIds: ['one', 'two'] })
+ expect(nodes.every((n) => !n.data.initialCommand)).toBe(true)
+ expect(launchesToFire(nodes, {}, new Set(['one', 'two']))).toHaveLength(2)
+})
+it('keeps plain shells unqueued while accounting for every command-bearing node in a mixed batch', () => {
+ const batch = createControlOpenBatch()
+ batch.add({ id: 'shell', data: {} })
+ batch.add({ id: 'agent', data: { initialCommand: 'codex brief' } })
+ expect(batch.result(['upstream'])).toEqual({ ids: ['shell', 'agent'], id: 'shell', after: ['upstream'], queued: true, queuedIds: ['agent'] })
+ const shell = createControlOpenBatch()
+ shell.add({ id: 'plain', data: {} })
+ expect(shell.result()).toMatchObject({ queued: false, queuedIds: [] })
+})
diff --git a/src/renderer/lib/controlOpenBatch.ts b/src/renderer/lib/controlOpenBatch.ts
new file mode 100644
index 000000000..43f1f80ac
--- /dev/null
+++ b/src/renderer/lib/controlOpenBatch.ts
@@ -0,0 +1,20 @@
+import type { PendingLaunch } from '@shared/types'
+import { queueControlLaunch } from './pendingLaunch'
+
+/** The visible Desktop open handlers share creation-time delivery accounting. Mounting and
+ * asynchronous delivery happen later; neither can turn an open response into a startup claim. */
+export function createControlOpenBatch() {
+ const opened: Array<{ id: string; queued: boolean }> = []
+ return {
+ add<T extends { id: string; data: { initialCommand?: string; pendingLaunch?: PendingLaunch } }>(node: T) {
+ const held = queueControlLaunch(node)
+ opened.push({ id: held.id, queued: !!held.data.pendingLaunch })
+ return held
+ },
+ result(after: string[] = []) {
+ const ids = opened.map((n) => n.id)
+ const queuedIds = opened.filter((n) => n.queued).map((n) => n.id)
+ return { ids, id: ids[0], after, queued: queuedIds.length > 0, queuedIds }
+ }
+ }
+}
diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.ts
index d89283a22..b318f9b29 100644
--- a/src/renderer/lib/pendingLaunch.test.ts
+++ b/src/renderer/lib/pendingLaunch.test.ts
@@ -225,7 +225,7 @@ describe('control opens retain an unacknowledged launch (#827/#811)', () => {
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(node.data.pendingLaunch).toEqual({ after: [], command: `${agent} brief`, attempted: false })
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))
diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.ts
index 5e4cbf2ed..e9f346ee3 100644
--- a/src/renderer/lib/pendingLaunch.ts
+++ b/src/renderer/lib/pendingLaunch.ts
@@ -37,7 +37,7 @@ export function queueControlLaunch<T extends { data: { initialCommand?: string;
data: {
...node.data,
initialCommand: undefined,
- pendingLaunch: { after, command, ...(awaitSetupGroup ? { awaitSetupGroup } : {}) }
+ pendingLaunch: { after, command, attempted: false, ...(awaitSetupGroup ? { awaitSetupGroup } : {}) }
}
}
}
diff --git a/src/renderer/lib/projectOpen.test.ts b/src/renderer/lib/projectOpen.test.ts
index 9e71124e6..da8d9a535 100644
--- a/src/renderer/lib/projectOpen.test.ts
+++ b/src/renderer/lib/projectOpen.test.ts
@@ -205,7 +205,7 @@ describe('armForColdOpen — the launch moves (never copies) into pendingLaunch
it('moves initialCommand into pendingLaunch { after: [], command }', () => {
const armed = armForColdOpen(like('claude "go"'))
- expect(armed.data.pendingLaunch).toEqual({ after: [], command: 'claude "go"' })
+ expect(armed.data.pendingLaunch).toEqual({ after: [], command: 'claude "go"', attempted: false })
// MOVED, not copied: initialCommand is deliberately never serialized (workspace.ts), so a
// copy left behind is dead weight and a command left ONLY there is silently dropped — the
// node would never start. The serialization round-trip pin lives in
diff --git a/src/renderer/lib/projectOpen.ts b/src/renderer/lib/projectOpen.ts
index 828e07fa2..2f186c150 100644
--- a/src/renderer/lib/projectOpen.ts
+++ b/src/renderer/lib/projectOpen.ts
@@ -185,7 +185,7 @@ export function openProjectReply(
/**
* Re-arm a freshly-built node for a COLD open (spec §2.2): its composed launch command is MOVED —
- * never copied — from `initialCommand` into `pendingLaunch: { after: [], command }`.
+ * never copied — from `initialCommand` into `pendingLaunch: { after: [], command, attempted: false }`.
* `initialCommand` is deliberately never serialized (workspace.ts), while `pendingLaunch` is: a
* command left in `initialCommand` on the store path would be silently dropped by serialization
* and the node would never start; a copy left behind would double-deliver if that ever changed.
@@ -199,7 +199,7 @@ export function armForColdOpen<
if (!command) return node
return {
...node,
- data: { ...node.data, initialCommand: undefined, pendingLaunch: { after: [], command } }
+ data: { ...node.data, initialCommand: undefined, pendingLaunch: { after: [], command, attempted: false } }
}
}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 786ac6ccb..330184b49 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -1,3 +1,4 @@
+import { commitLaunch } from '../terminal/launch-attempt'
import { isLaunchShell } from '@shared/agents/pane'
import { createLaunchWriter, deliverInitialLaunch, launchCommand, registerLaunchWriter } from '../terminal/launch-command'
import { Suspense, lazy, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
@@ -3434,7 +3435,7 @@ export function TerminalNode({
})
}
const launchWriter = createLaunchWriter({
- fresh: fresh && !freshUnverified,
+ claimAttempt: (manual, command) => commitLaunch(api, id, command, manual),
io: { write: (d) => transport.write(sid, d), onData: (cb) => transport.onData(sid, cb) },
// A fresh shell is known at spawn; subsequent/manual deliveries must recheck the pane.
shellReady: async (manual) =>
@@ -3471,7 +3472,7 @@ export function TerminalNode({
// node is armed is Canvas's question, it can change after the spawn resolves, and the
// subscribers filter by id anyway.
whenShellSettled(() => {
- cleanups.push(registerLaunchWriter(id, launchWriter))
+ cleanups.push(registerLaunchWriter(id, launchWriter, api))
setSessionReady(id, true)
})
// Paused (see agentStatus.paused) is the ONE exception to the "a cold start always resumes"
@@ -3546,6 +3547,7 @@ export function TerminalNode({
if (data.initialCommand) {
const command = data.initialCommand
deliverInitialLaunch(command, {
+ pending: data.pendingLaunch,
whenReady: whenShellSettled,
write: launchWriter,
update: (patch) => updateNodeData(id, patch),
@@ -5544,7 +5546,7 @@ export function TerminalNode({
// 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 launchCommand(id, pendingLaunch.command, true).then((outcome) => {
+ void launchCommand(id, pendingLaunch.command, true, api).then((outcome) => {
if (outcome === 'submitted') {
useLaunchDelivery.getState().clear(id)
updateNodeData(id, { initialCommand: undefined, pendingLaunch: undefined })
diff --git a/src/renderer/state/workspace.cold-open.test.ts b/src/renderer/state/workspace.cold-open.test.ts
index 30e79f521..69d9292bf 100644
--- a/src/renderer/state/workspace.cold-open.test.ts
+++ b/src/renderer/state/workspace.cold-open.test.ts
@@ -77,13 +77,13 @@ describe('cold-open pin (b): an empty `after` is vacuously ready', () => {
})
})
-it('retains an unsubmitted UI command across a project switch without automatically replaying it', () => {
+it('retains a never-attempted UI command across a project switch', () => {
const live = nodeStatesToFlow([armedState])[0]
live.data.pendingLaunch = undefined
live.data.initialCommand = 'claude "complete original brief"'
const restored = nodeStatesToFlow(flowToNodeStates([live]))[0]
expect(restored.data.pendingLaunch).toEqual({
- after: [], command: 'claude "complete original brief"', manualOnly: true
+ after: [], command: 'claude "complete original brief"', attempted: false
})
- expect(launchesToFire([restored], {}, new Set([restored.id]))).toEqual([])
+ expect(launchesToFire([restored], {}, new Set([restored.id]))).toEqual([{ id: restored.id, command: 'claude "complete original brief"' }])
})
diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.ts
index b93184ed1..ae8b3d2ff 100644
--- a/src/renderer/state/workspace.test.ts
+++ b/src/renderer/state/workspace.test.ts
@@ -867,13 +867,13 @@ describe('pendingLaunch round-trip', () => {
})
})
- it('retains an ordinary node’s unsubmitted command for explicit recovery', () => {
+ it('retains an ordinary node’s never-attempted command', () => {
const node = {
id: 'term-4', type: 'terminal', position: { x: 0, y: 0 }, width: 1, height: 1,
data: { title: 'T', color: '#888', group: null, initialCommand: 'claude' }
} as unknown as CanvasNode
const states = flowToNodeStates([node])
- expect(states[0].pendingLaunch).toEqual({ after: [], command: 'claude', manualOnly: true })
+ expect(states[0].pendingLaunch).toEqual({ after: [], command: 'claude', attempted: false })
// The command is persisted as recoverable intent, never as a second initialCommand.
expect((states[0] as { initialCommand?: string }).initialCommand).toBeUndefined()
})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index ca6cec5e5..507ed4d56 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -2036,7 +2036,7 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {
// A not-yet-submitted UI command is durable too. Recover it explicitly on reload:
// the old PTY may have accepted it before the clearing save landed.
pendingLaunch: n.data.pendingLaunch ?? (n.data.initialCommand
- ? { after: [], command: n.data.initialCommand, manualOnly: true }
+ ? { after: [], command: n.data.initialCommand, attempted: false }
: undefined),
ssh: n.data.ssh,
sshRemoteTmux: n.data.sshRemoteTmux,
diff --git a/src/renderer/terminal/launch-attempt.test.ts b/src/renderer/terminal/launch-attempt.test.ts
new file mode 100644
index 000000000..4933888ff
--- /dev/null
+++ b/src/renderer/terminal/launch-attempt.test.ts
@@ -0,0 +1,69 @@
+import { expect, it, vi } from 'vitest'
+import type { PendingLaunch } from '@shared/types'
+import { commitLaunch, commitLaunchAttempt, registerLaunchCommit } from './launch-attempt'
+import { createLaunchWriter } from './launch-command'
+import { queueControlLaunch, launchesToFire } from '../lib/pendingLaunch'
+
+it.each([true, undefined])('refuses automatic replay of an attempted/legacy launch (%s)', async (attempted) => {
+ const update = vi.fn(), save = vi.fn(async () => {})
+ expect(await commitLaunchAttempt({ pending: { after: [], command: 'cmd', attempted }, command: 'cmd', manual: false, update, save })).toBe(false)
+ expect(update).not.toHaveBeenCalled()
+ expect(save).not.toHaveBeenCalled()
+})
+it('concurrent claimers read the synchronous attempted mark, and no acknowledgment precedes disk', async () => {
+ let pending: PendingLaunch = { after: [], command: 'cmd', attempted: false }
+ let saved!: () => void
+ const save = vi.fn(() => new Promise<void>((resolve) => { saved = resolve }))
+ const claim = () => commitLaunchAttempt({ pending, command: 'cmd', manual: false,
+ update: (next) => { pending = next }, save })
+ const first = claim()
+ expect(pending).toMatchObject({ attempted: true, manualOnly: true })
+ expect(await claim()).toBe(false)
+ expect(save).toHaveBeenCalledTimes(1)
+ saved()
+ expect(await first).toBe(true)
+})
+it('scope registration fails closed after unmount and never resolves through another core', async () => {
+ const core = {}, other = {}
+ const commit = vi.fn(async () => true)
+ const off = registerLaunchCommit(core, commit)
+ expect(await commitLaunch(other, 'node', 'cmd', false)).toBe(false)
+ expect(await commitLaunch(core, 'node', 'cmd', false)).toBe(true)
+ off()
+ expect(await commitLaunch(core, 'node', 'cmd', true)).toBe(false)
+ expect(commit).toHaveBeenCalledTimes(1)
+})
+it('a saved --after launch survives park expiry, runs once on warm shell, and never replays a lost clearing save', async () => {
+ const opened = queueControlLaunch({ id: 'downstream', data: { initialCommand: 'claude consume-result' } }, ['upstream'])
+ const live = new Set(['upstream', 'downstream'])
+ expect(launchesToFire([opened], { upstream: { state: 'working' } }, live)).toEqual([])
+ // Only durable data survives a project switch + expired park. No fresh-mount proof is needed.
+ const warm = JSON.parse(JSON.stringify(opened)) as typeof opened
+ const [ready] = launchesToFire([warm], { upstream: { state: 'done' } }, live)
+ expect(ready.command).toBe('claude consume-result')
+ let disk = JSON.stringify(warm)
+ let echo!: (text: string) => void
+ const write = vi.fn()
+ const writer = createLaunchWriter({
+ shellReady: async () => true, killLine: '\x15', cleanup: () => {},
+ io: { write, onData: (cb) => { echo = cb; return () => {} } },
+ claimAttempt: (manual, command) => commitLaunchAttempt({
+ pending: warm.data.pendingLaunch, command, manual,
+ update: (pending) => { warm.data.pendingLaunch = pending },
+ save: async () => { disk = JSON.stringify(warm) }
+ })
+ })
+ const delivery = writer(ready.command, false)
+ const concurrent = writer(ready.command, true)
+ expect(concurrent).toBe(delivery)
+ for (let i = 0; i < 12; i++) await Promise.resolve()
+ expect(JSON.parse(disk).data.pendingLaunch).toMatchObject({ attempted: true, manualOnly: true })
+ expect(write.mock.calls).toEqual([[ready.command]])
+ echo(ready.command)
+ expect(await delivery).toBe('submitted')
+ // Simulate crash before clearing intent reached disk, then warm reattach + unrelated hooks.
+ const resumed = JSON.parse(disk)
+ expect(launchesToFire([resumed], { upstream: { state: 'done' } }, live)).toEqual([])
+ expect(await writer(ready.command, false)).toBe('submitted')
+ expect(write.mock.calls).toEqual([[ready.command], ['\r']])
+})
diff --git a/src/renderer/terminal/launch-attempt.ts b/src/renderer/terminal/launch-attempt.ts
new file mode 100644
index 000000000..322dc4e08
--- /dev/null
+++ b/src/renderer/terminal/launch-attempt.ts
@@ -0,0 +1,31 @@
+import type { PendingLaunch } from '@shared/types'
+
+type Commit = (id: string, command: string, manual: boolean) => Promise<boolean>
+const commits = new WeakMap<object, Commit>()
+export function registerLaunchCommit(scope: object, commit: Commit): () => void {
+ commits.set(scope, commit)
+ return () => { if (commits.get(scope) === commit) commits.delete(scope) }
+}
+export function commitLaunch(scope: object, id: string, command: string, manual: boolean): Promise<boolean> {
+ return commits.get(scope)?.(id, command, manual) ?? Promise.resolve(false)
+}
+
+/** Write-ahead barrier: an absent legacy marker is uncertain, never proof of no previous input. */
+export async function commitLaunchAttempt(opts: {
+ pending: PendingLaunch | undefined
+ command: string
+ manual: boolean
+ update(pending: PendingLaunch): void
+ save(): Promise<void>
+}): Promise<boolean> {
+ if (!opts.pending || opts.pending.command !== opts.command) return false
+ if (!opts.manual && opts.pending.attempted !== false) return false
+ opts.update({ ...opts.pending, attempted: true, manualOnly: true })
+ try {
+ await opts.save()
+ return true
+ } catch {
+ // Keep the in-memory hold too: a failed save is not permission to type or retry silently.
+ return false
+ }
+}
diff --git a/src/renderer/terminal/launch-command.test.ts b/src/renderer/terminal/launch-command.test.ts
index 9cd3abd0a..e57e7a3ca 100644
--- a/src/renderer/terminal/launch-command.test.ts
+++ b/src/renderer/terminal/launch-command.test.ts
@@ -1,18 +1,26 @@
+import { commitLaunchAttempt } from './launch-attempt'
+import type { PendingLaunch } from '@shared/types'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createLaunchWriter, deliverInitialLaunch, launchCommand, registerLaunchWriter } from './launch-command'
import { KILL_LINE, WINDOWS_KILL_LINE, VERIFY_TIMEOUT_MS, DELIVERY_ATTEMPTS } from './command-delivery'
-function fixture(fresh = true, killLine = KILL_LINE) {
+function fixture(attempted = false, killLine = KILL_LINE) {
const cleanups: Array<() => void> = []
let output: ((text: string) => void) | undefined
const write = vi.fn()
const shellReady = vi.fn(async () => true)
- const writer = createLaunchWriter({ fresh, io: {
+ let durable: PendingLaunch = { after: [], command: '', attempted }
+ const save = vi.fn(async () => {})
+ const writer = createLaunchWriter({ claimAttempt: (manual, command) => commitLaunchAttempt({
+ pending: { ...durable, command }, command, manual,
+ update: (next) => { durable = next }, save
+ }), io: {
write, onData: (cb) => { output = cb; return () => { output = undefined } }
}, shellReady, killLine, cleanup: (cancel) => cleanups.push(cancel) })
- return { writer, write, shellReady, echo: (text: string) => output?.(text),
+ return { writer, write, shellReady, save, snapshot: () => JSON.parse(JSON.stringify(durable)) as PendingLaunch, echo: (text: string) => output?.(text),
dispose: () => cleanups.forEach((fn) => fn()) }
}
+async function tick() { for (let i = 0; i < 12; i++) await Promise.resolve() }
afterEach(() => vi.useRealTimers())
describe('durable launch delivery', () => {
it('acknowledges only after echoed command and Enter; stale UI and concurrent clicks never paste twice', async () => {
@@ -20,7 +28,7 @@ describe('durable launch delivery', () => {
const command = 'claude complete-brief'
const first = f.writer(command, false)
expect(f.writer(command, true)).toBe(first)
- await Promise.resolve()
+ await tick()
expect(f.write.mock.calls).toEqual([[command]])
f.echo(command)
expect(await first).toBe('submitted')
@@ -32,7 +40,7 @@ describe('durable launch delivery', () => {
const f = fixture()
const command = 'claude complete-brief'
const result = f.writer(command, false)
- await Promise.resolve()
+ await tick()
f.echo('complete-brief')
await vi.advanceTimersByTimeAsync(VERIFY_TIMEOUT_MS)
expect(f.write.mock.calls).toEqual([[command], [KILL_LINE], [command]])
@@ -51,12 +59,12 @@ describe('durable launch delivery', () => {
expect(await f.writer(command, false)).toBe('cancelled')
expect(f.write).toHaveBeenCalledTimes(calls)
const retry = f.writer(command, true)
- await Promise.resolve()
+ await tick()
f.echo(command)
expect(await retry).toBe('submitted')
})
it('does not replay a durable command on warm resume even if its successful clear was never saved', async () => {
- const f = fixture(false)
+ const f = fixture(true)
expect(await f.writer('codex brief', false)).toBe('cancelled')
expect(f.write).not.toHaveBeenCalled()
f.shellReady.mockResolvedValue(false) // running agent/editor: manual retry also refuses
@@ -64,14 +72,14 @@ describe('durable launch delivery', () => {
expect(f.write).not.toHaveBeenCalled()
f.shellReady.mockResolvedValue(true)
const retry = f.writer('codex brief', true)
- await Promise.resolve()
+ await tick()
f.echo('codex brief')
expect(await retry).toBe('submitted')
})
it('manual Windows recovery clears a partial line with Escape and submits Enter separately after echo', async () => {
- const f = fixture(false, WINDOWS_KILL_LINE)
+ const f = fixture(true, WINDOWS_KILL_LINE)
const result = f.writer('codex brief', true)
- await Promise.resolve()
+ await tick()
expect(f.write.mock.calls).toEqual([[WINDOWS_KILL_LINE], ['codex brief']])
f.echo('codex brief')
expect(await result).toBe('submitted')
@@ -92,7 +100,7 @@ describe('durable launch delivery', () => {
vi.useFakeTimers()
const f = fixture()
const result = f.writer('codex brief', false)
- await Promise.resolve()
+ await tick()
f.dispose()
expect(await result).toBe('cancelled')
await vi.runAllTimersAsync()
@@ -105,12 +113,12 @@ describe('durable launch delivery', () => {
if (failure === 'command' || text === '\r') throw new Error('offline')
})
const result = f.writer('claude brief', false)
- await Promise.resolve()
+ await tick()
f.echo('claude brief')
expect(await result).toBe('cancelled')
f.write.mockReset()
const retry = f.writer('claude brief', true)
- await Promise.resolve()
+ await tick()
f.echo('claude brief')
expect(await retry).toBe('submitted')
})
@@ -138,12 +146,12 @@ describe('UI initial-command lifecycle', () => {
// Teardown/park before ready cannot lose the brief: both live and durable intent remain.
expect(write).not.toHaveBeenCalled()
expect(state.initialCommand).toBe('claude original-brief')
- expect(state.pendingLaunch).toEqual({ after: [], command: 'claude original-brief', manualOnly: true })
+ expect(state.pendingLaunch).toEqual({ after: [], command: 'claude original-brief', attempted: false })
ready()
expect(write).toHaveBeenCalledWith('claude original-brief', false)
expect(state.initialCommand).toBe('claude original-brief')
settle(outcome)
- await Promise.resolve()
+ await tick()
expect(state.initialCommand).toBeUndefined()
if (outcome === 'submitted') {
expect(state.pendingLaunch).toBeUndefined()
@@ -154,3 +162,53 @@ describe('UI initial-command lifecycle', () => {
}
})
})
+
+describe('warm launch recovery after the park expires', () => {
+ it('automatically runs a never-attempted saved launch after a new writer attaches to its shell', async () => {
+ const original = fixture()
+ const snapshot = original.snapshot()
+ original.dispose() // park expiry destroys the view, not the saved intent or tmux shell
+ const warm = fixture(snapshot.attempted)
+ const delivery = warm.writer('claude upstream-result', false)
+ await tick()
+ expect(warm.save).toHaveBeenCalledTimes(1)
+ expect(warm.snapshot().attempted).toBe(true)
+ warm.echo('claude upstream-result')
+ expect(await delivery).toBe('submitted')
+ expect(warm.write.mock.calls).toEqual([['claude upstream-result'], ['\r']])
+ })
+ it('will not write before the durable attempt save resolves, and refuses a failed save', async () => {
+ const f = fixture()
+ let reject!: (e: Error) => void
+ f.save.mockImplementationOnce(() => new Promise((_, fail) => { reject = fail }))
+ const result = f.writer('claude brief', false)
+ await tick()
+ expect(f.snapshot().attempted).toBe(true)
+ expect(f.write).not.toHaveBeenCalled()
+ reject(new Error('disk offline'))
+ expect(await result).toBe('cancelled')
+ expect(f.write).not.toHaveBeenCalled()
+ })
+ it('rechecks shell ownership after persistence before writing', async () => {
+ const f = fixture()
+ f.shellReady.mockResolvedValueOnce(true).mockResolvedValueOnce(false)
+ expect(await f.writer('claude brief', false)).toBe('cancelled')
+ expect(f.save).toHaveBeenCalledTimes(1)
+ expect(f.write).not.toHaveBeenCalled()
+ const warm = fixture(f.snapshot().attempted)
+ expect(await warm.writer('claude brief', false)).toBe('cancelled')
+ expect(warm.write).not.toHaveBeenCalled()
+ })
+})
+
+it.each([true, undefined])('a retained initialCommand alias cannot reset attempted=%s', (attempted) => {
+ const state = { initialCommand: 'cmd' as string | undefined,
+ pendingLaunch: { after: [], command: 'cmd', attempted, manualOnly: true } }
+ const write = vi.fn(), whenReady = vi.fn(), onFailure = vi.fn()
+ deliverInitialLaunch('cmd', { pending: state.pendingLaunch, write, whenReady, onFailure,
+ update: (patch) => Object.assign(state, patch) })
+ expect(state.initialCommand).toBeUndefined()
+ expect(state.pendingLaunch).toMatchObject({ attempted, manualOnly: true, command: 'cmd' })
+ expect(whenReady).not.toHaveBeenCalled()
+ expect(write).not.toHaveBeenCalled()
+})
diff --git a/src/renderer/terminal/launch-command.ts b/src/renderer/terminal/launch-command.ts
index 62eea5482..2110c8b65 100644
--- a/src/renderer/terminal/launch-command.ts
+++ b/src/renderer/terminal/launch-command.ts
@@ -1,20 +1,28 @@
+import type { PendingLaunch } from '@shared/types'
import { deliverCommand, type DeliveryIo, type DeliveryOutcome } from './command-delivery'
// A writer belongs to the PTY lifetime (including a parked view), not a Canvas render.
-// Warm attachments never replay durable launch intent: a previous submission may have landed
-// just before its clearing autosave. The retained command is available for explicit recovery.
+// A durable write-ahead claim distinguishes a never-attempted warm launch from an uncertain
+// earlier submission whose clearing autosave may have been lost.
type Writer = (command: string, manual: boolean) => Promise<DeliveryOutcome>
-const writers = new Map<string, Writer>()
-export function registerLaunchWriter(id: string, writer: Writer): () => void {
+const defaultScope = {}
+const scopedWriters = new WeakMap<object, Map<string, Writer>>()
+function writersFor(scope: object): Map<string, Writer> {
+ let writers = scopedWriters.get(scope)
+ if (!writers) { writers = new Map(); scopedWriters.set(scope, writers) }
+ return writers
+}
+export function registerLaunchWriter(id: string, writer: Writer, scope: object = defaultScope): () => void {
+ const writers = writersFor(scope)
writers.set(id, writer)
return () => { if (writers.get(id) === writer) writers.delete(id) }
}
-export function launchCommand(id: string, command: string, manual = false): Promise<DeliveryOutcome> {
- return writers.get(id)?.(command, manual) ?? Promise.resolve('cancelled')
+export function launchCommand(id: string, command: string, manual = false, scope: object = defaultScope): Promise<DeliveryOutcome> {
+ return writersFor(scope).get(id)?.(command, manual) ?? Promise.resolve('cancelled')
}
export function createLaunchWriter(opts: {
- fresh: boolean
+ claimAttempt(manual: boolean, command: string): Promise<boolean>
io: DeliveryIo
shellReady(manual: boolean): Promise<boolean>
killLine: string
@@ -28,9 +36,12 @@ export function createLaunchWriter(opts: {
return (command, manual) => {
if (submitted) return Promise.resolve('submitted') // stale UI/save; never paste twice
if (inFlight) return inFlight
- if (disposed || (!manual && (!opts.fresh || attempted))) return Promise.resolve('cancelled')
+ if (disposed || (!manual && attempted)) return Promise.resolve('cancelled')
attempted = true
inFlight = (async () => {
+ if (!(await opts.shellReady(manual)) || disposed) return 'cancelled' as const
+ if (!(await opts.claimAttempt(manual, command)) || disposed) return 'cancelled' as const
+ // Saving can take a remote round trip. Recheck after the barrier, before any input.
if (!(await opts.shellReady(manual)) || disposed) return 'cancelled' as const
return new Promise<DeliveryOutcome>((resolve) => {
try {
@@ -50,22 +61,30 @@ export function createLaunchWriter(opts: {
/** Keep UI launch intent through the asynchronous shell settle and submission boundary. */
export function deliverInitialLaunch(command: string, opts: {
+ pending?: PendingLaunch
whenReady(run: () => void): void
write: Writer
update(patch: {
initialCommand?: undefined
- pendingLaunch?: { after: string[]; command: string; manualOnly: true }
+ pendingLaunch?: { after: string[]; command: string; attempted: boolean; manualOnly?: boolean }
}): void
onFailure(outcome: DeliveryOutcome): void
}): void {
- const pendingLaunch = { after: [], command, manualOnly: true as const }
+ if (opts.pending && opts.pending.attempted !== false) {
+ // A park/remount can retain the live initialCommand alias while its first submission is
+ // still settling. Never let that alias reset the durable attempted mark.
+ opts.update({ initialCommand: undefined })
+ opts.onFailure('cancelled')
+ return
+ }
+ const pendingLaunch = { after: [], command, attempted: false }
// Do not discard the live initialCommand before settle. The durable pending record also
- // prevents the Canvas loop from racing this writer and survives a project switch.
+ // survives a project switch. Canvas and this callback share the same in-flight writer.
opts.update({ pendingLaunch })
opts.whenReady(() => {
void opts.write(command, false).then((outcome) => {
opts.update({ initialCommand: undefined,
- pendingLaunch: outcome === 'submitted' ? undefined : pendingLaunch })
+ pendingLaunch: outcome === 'submitted' ? undefined : { ...pendingLaunch, attempted: true, manualOnly: true } })
if (outcome !== 'submitted') opts.onFailure(outcome)
})
})
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index b0dd36d1c..bcfcf3bab 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -1113,6 +1113,7 @@ describe('HeadlessNodeFactory', () => {
expect(workspace.projects[0].nodes.find((node) => node.id === id)?.pendingLaunch).toEqual({
after: ['term-upstream'],
command: "claude 'consume result'",
+ attempted: false,
executor: 'server'
})
expect(workspace.projects[0].bridges).toEqual(
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index b0261ac03..a25821ea7 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -1176,6 +1176,7 @@ export class HeadlessNodeFactory {
after,
command,
executor: 'server' as const,
+ attempted: !mustWait,
...(!mustWait ? { manualOnly: true } : {}),
...(awaitWorking.length ? { awaitWorking: [...awaitWorking] } : {})
}
@@ -1413,6 +1414,7 @@ export class HeadlessNodeFactory {
// Persist the attempt BEFORE input. A failed/uncertain send (or a crash before its
// acknowledgement save) must never be replayed by an unrelated hook.
pending.manualOnly = true
+ pending.attempted = true
await this.deps.workspaceStore.save(workspace)
markChanged()
if (!isLaunchShell(await this.deps.ptyManager.paneCommand(node.id).catch(() => null))) continue
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 8734ffc94..2f3a5f8e8 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -337,6 +337,8 @@ export type NodeKind = 'terminal' | 'sticky' | 'group' | 'editor' | 'diff' | 'vi
* a stalled station must never be a dead end.
*/
export interface PendingLaunch {
+ /** false proves no input attempt; true/absent require explicit recovery after reload. */
+ attempted?: boolean
/** An attempted/uncertain delivery requires explicit Run now; never replay on hooks. */
manualOnly?: boolean
/**