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(relay): preserve fresh UI launch without workspace persistence

review99f36117bc5d
diff --git a/CLAUDE.md b/CLAUDE.md
index 31f3e39fc..f78031809 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2574,9 +2574,12 @@ 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. Relay launch delivery, including Run now, is refused until a scoped durable
+ across parked views. Relay queued/restored delivery, including Run now, is refused until a scoped durable
claim API exists: a relay workspace load can be project-scoped, while save replaces the host
- index. Never use that load/save pair for a launch. A parked-project deferral before any input
+ index. Never use that load/save pair for a launch. A new relay UI initialCommand may instead
+ use the verified writer once on a fresh PTY without creating pendingLaunch or writing workspace
+ data. Its transient claim is consumed before settle and survives view remounts; relay snapshots
+ omit that initial command rather than converting it to durable intent. A parked-project deferral before any input
retains never-attempted intent and can proceed on activation without a retry timer.
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
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 174032d3c..ac203f4e4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -663,7 +663,10 @@ Desktop and Server save `attempted:true` before input. Never-attempted warm `--a
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.
-Relay-owned launches (automatic and Run now) are refused until a scoped durable claim API exists.
+Relay queued/restored launches and Run now are refused until a scoped durable claim API exists.
+A new relay UI initialCommand may run once on a fresh PTY through the verified writer, without
+workspace writes or pendingLaunch creation. Consume its transient attempt before shell settle;
+never retry it on remount or serialize it as durable intent.
Never round-trip a relay workspace load into save: the load can contain only one shared project,
while save replaces the entire host index. A pre-input parked-project deferral keeps intent
never-attempted; it must not poison the writer or trigger a retry timer.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index a52eba429..fd4be2c72 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -2598,7 +2598,7 @@ export function Canvas() {
// keeps mirroring the previous project until the host's next edit. Gated like the effect:
// without phone access on, the serialize itself is the waste (main would drop the payload).
if (useSettings.getState().settings.phoneAccessEnabled) {
- window.nodeTerminal.remoteHost.sendCanvasState({ nodes: flowToNodeStates(nodesRef.current) })
+ window.nodeTerminal.remoteHost.sendCanvasState({ nodes: flowToNodeStates(nodesRef.current, sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay') })
}
// Offer the resume card once per project per app run — and only when the user opted in
// (settings.showResumeCard, default off): while disabled the one-shot slot is NOT spent,
@@ -2728,7 +2728,8 @@ export function Canvas() {
// ephemeral-id set: it is read from a live store, so it is captured here, as of this call.
const publishableLater = useCallback((flow: CanvasNode[]): (() => CanvasNodeState[]) => {
const ephIds = new Set(Object.keys(useAgentNodes.getState().byId))
- return () => publishableStates(flowToNodeStates(flow), ephIds)
+ const retainInitial = sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay'
+ return () => publishableStates(flowToNodeStates(flow, retainInitial), ephIds)
}, [])
// ---- persistence helpers ----
@@ -2743,7 +2744,7 @@ export function Canvas() {
.getState()
.commitCanvas(
id,
- flowToNodeStates(nodesRef.current),
+ flowToNodeStates(nodesRef.current, sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay'),
viewportRef.current,
linkEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target })),
controlEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target }))
@@ -3099,7 +3100,7 @@ export function Canvas() {
useEffect(() => {
if (!phoneHosting || loadingRef.current) return
const t = setTimeout(() => {
- window.nodeTerminal.remoteHost.sendCanvasState({ nodes: flowToNodeStates(nodesRef.current) })
+ window.nodeTerminal.remoteHost.sendCanvasState({ nodes: flowToNodeStates(nodesRef.current, sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay') })
}, 120)
return () => clearTimeout(t)
}, [nodes, phoneHosting])
@@ -3113,7 +3114,7 @@ export function Canvas() {
useEffect(() => {
return window.nodeTerminal.remoteHost.onApplyMutation((mutation) => {
setNodes((ns) => {
- const next = applyCanvasMutation(flowToNodeStates(ns), mutation)
+ const next = applyCanvasMutation(flowToNodeStates(ns, sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay'), mutation)
return nodeStatesToFlow(next)
})
markDirty()
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index cda41612c..0f888c021 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -1,3 +1,4 @@
+import { deliverRelayInitialLaunch } from '../terminal/relay-initial-launch'
import { commitLaunch } from '../terminal/launch-attempt'
import { isLaunchShell } from '@shared/agents/pane'
import { createLaunchWriter, deliverInitialLaunch, launchCommand, registerLaunchWriter } from '../terminal/launch-command'
@@ -3434,14 +3435,16 @@ export function TerminalNode({
unsub()
})
}
- const launchWriter = createLaunchWriter({
- claimAttempt: (manual, command) => commitLaunch(api, id, command, manual),
- io: { write: (d) => transport.write(sid, d), onData: (cb) => transport.onData(sid, cb) },
+ const launchWriterOptions = {
+ io: { write: (d: string) => transport.write(sid, d), onData: (cb: (data: string) => void) => transport.onData(sid, cb) },
// A fresh shell is known at spawn; subsequent/manual deliveries must recheck the pane.
- shellReady: async (manual) =>
+ shellReady: async (manual: boolean) =>
(!manual && fresh && !sessionPersistent) || isLaunchShell(await queryPaneWithin(() => api.pty.paneCommand(id), RESTART_EXIT_TIMEOUT_MS)),
killLine: getTerminalKillLine(),
- cleanup: (cancel) => cleanups.push(cancel)
+ cleanup: (cancel: () => void) => { cleanups.push(cancel) }
+ }
+ const launchWriter = createLaunchWriter({ ...launchWriterOptions,
+ claimAttempt: (manual, command) => commitLaunch(api, id, command, manual)
})
const writeWhenShellReady = (cmd: string): void => {
whenShellSettled(() => {
@@ -3493,7 +3496,7 @@ export function TerminalNode({
// resume, not armed, not paused. A plain terminal has no conversation to lose, and paying
// a probe to tell it so would be the channel pressure this whole area exists to reduce.
const canColdRestore =
- !!agentId && canResume(agentId) && !data.pendingLaunch && shouldColdResume(pausedNow)
+ session.source !== 'relay' && !!agentId && canResume(agentId) && !data.pendingLaunch && shouldColdResume(pausedNow)
let coldStart = fresh
if (!fresh && freshUnverified && !data.initialCommand && canColdRestore) {
// After the shell has settled, not at this instant: the attach is a network round trip
@@ -3546,7 +3549,16 @@ export function TerminalNode({
// forget it.
if (data.initialCommand) {
const command = data.initialCommand
- deliverInitialLaunch(command, {
+ if (session.source === 'relay') {
+ deliverRelayInitialLaunch({ scope: api, id, fresh, pending: data.pendingLaunch, command,
+ consume: () => updateNodeData(id, { initialCommand: undefined }),
+ whenReady: whenShellSettled, writer: launchWriterOptions,
+ onFailure: (outcome) => {
+ useLaunchDelivery.getState().markFailed(id, 1)
+ if (outcome === 'line-too-long') setCo(termKey, { launchTooLongBytes: lineBytes(command) })
+ }
+ })
+ } else deliverInitialLaunch(command, {
pending: data.pendingLaunch,
whenReady: whenShellSettled,
write: launchWriter,
diff --git a/src/renderer/nodes/session-ready-signal.test.ts b/src/renderer/nodes/session-ready-signal.test.ts
index ba1b9deca..1cf324f1d 100644
--- a/src/renderer/nodes/session-ready-signal.test.ts
+++ b/src/renderer/nodes/session-ready-signal.test.ts
@@ -77,7 +77,7 @@ describe('an ARMED node does not cold-start its agent under the hold (source pin
// predicate's contents rather than the branch's old inline shape. `!data.pendingLaunch` and
// `shouldColdResume` are independent refusals and must both survive a reformat.
expect(src).toMatch(
- /const canColdRestore =\s*\n?\s*!!agentId && canResume\(agentId\) && !data\.pendingLaunch && shouldColdResume\(pausedNow\)/
+ /const canColdRestore =\s*\n?\s*session\.source !== 'relay' && !!agentId && canResume\(agentId\) && !data\.pendingLaunch && shouldColdResume\(pausedNow\)/
)
// …and the relaunch branch is the one that reads it.
expect(src).toContain('} else if (coldStart && canColdRestore) {')
@@ -97,9 +97,10 @@ describe('the QUEUED badge carries the delivery state (source pins)', () => {
expect(src).toContain("useLaunchDelivery((s) => s.byId[id])")
expect(src).toContain('term-node__status--queued-warn')
// `pendingErroredOn` is the fourth argument since #521 — an errored upstream is idle, so
- // without it the tooltip would promise a wait that never ends.
+ // without it the tooltip would promise a wait that never ends. The relay flag also
+ // keeps unsupported queued delivery from promising a working Run now action.
expect(src).toContain(
- 'launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn)'
+ "launchTooltip(launchDelivery, pendingWaitingOn, pendingLaunch.command, pendingErroredOn, session.source === 'relay')"
)
})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 507ed4d56..eb9643011 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -1966,7 +1966,7 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
}
/** Serializes live React Flow nodes back into persisted node states. */
-export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {
+export function flowToNodeStates(nodes: CanvasNode[], retainInitialCommand = true): CanvasNodeState[] {
const sizeFor = (kind: NodeKind) =>
kind === 'sticky'
? STICKY_SIZE
@@ -2033,9 +2033,9 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {
agentModel: n.data.agentModel,
accountId: n.data.accountId,
agentSessionId: n.data.agentSessionId,
- // 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
+ // Owning-core UI intent is durable. Relay snapshots opt out: their new UI command
+ // uses a transient one-shot writer, never a whole-workspace persistence claim.
+ pendingLaunch: n.data.pendingLaunch ?? (retainInitialCommand && n.data.initialCommand
? { after: [], command: n.data.initialCommand, attempted: false }
: undefined),
ssh: n.data.ssh,
diff --git a/src/renderer/terminal/relay-initial-launch.test.ts b/src/renderer/terminal/relay-initial-launch.test.ts
new file mode 100644
index 000000000..eb220063d
--- /dev/null
+++ b/src/renderer/terminal/relay-initial-launch.test.ts
@@ -0,0 +1,89 @@
+import { expect, it, vi } from 'vitest'
+import { deliverRelayInitialLaunch } from './relay-initial-launch'
+import { flowToNodeStates, createTerminalNode } from '../state/workspace'
+import type { PendingLaunch } from '@shared/types'
+
+async function tick() { for (let i = 0; i < 12; i++) await Promise.resolve() }
+function fixture() {
+ const scope = { workspace: { load: vi.fn(), save: vi.fn() } }
+ const node = createTerminalNode(0)
+ node.data.initialCommand = 'claude brief'
+ const cleanups: Array<() => void> = []
+ let ready!: () => void, echo!: (text: string) => void
+ const input = vi.fn(), failure = vi.fn(), shellReady = vi.fn(async () => true)
+ const launch = (fresh = true, pending?: PendingLaunch) => deliverRelayInitialLaunch({
+ scope, id: node.id, command: 'claude brief', fresh, pending,
+ consume: () => { node.data.initialCommand = undefined },
+ whenReady: (run) => { ready = run }, onFailure: failure,
+ writer: { shellReady, killLine: '\x15', cleanup: (fn) => { cleanups.push(fn) },
+ io: { write: input, onData: (cb) => { echo = cb; return () => {} } } }
+ })
+ return { scope, node, launch, input, failure, shellReady,
+ ready: () => ready?.(), echo: (s: string) => echo?.(s), dispose: () => cleanups.forEach((fn) => fn()) }
+}
+it('new relay UI initial command uses verified delivery once without durable intent or workspace calls', async () => {
+ const f = fixture()
+ // A pre-mount peer publication must not manufacture a pending launch on the host.
+ expect(flowToNodeStates([f.node], false)[0].pendingLaunch).toBeUndefined()
+ f.launch()
+ expect(f.node.data.initialCommand).toBeUndefined()
+ expect(f.node.data.pendingLaunch).toBeUndefined()
+ f.ready()
+ await tick()
+ expect(f.input.mock.calls).toEqual([['claude brief']])
+ f.echo('claude brief')
+ await tick()
+ f.ready()
+ f.launch() // stale alias/remount cannot obtain another transient attempt
+ f.ready()
+ await tick()
+ expect(f.input.mock.calls).toEqual([['claude brief'], ['\r']])
+ expect(f.scope.workspace.load).not.toHaveBeenCalled()
+ expect(f.scope.workspace.save).not.toHaveBeenCalled()
+ expect(flowToNodeStates([f.node], false)[0].pendingLaunch).toBeUndefined()
+})
+it('a failed shell check cannot be retried or replayed on remount', async () => {
+ const f = fixture()
+ f.shellReady.mockResolvedValueOnce(false)
+ f.launch(); f.ready(); await tick()
+ f.ready(); f.launch(); f.ready(); await tick()
+ expect(f.input).not.toHaveBeenCalled()
+ expect(f.failure).toHaveBeenCalledTimes(1)
+})
+it('teardown before settle consumes the attempt without replaying after remount', async () => {
+ const f = fixture()
+ f.launch(); f.dispose(); f.ready(); await tick()
+ f.launch(); f.ready(); await tick()
+ expect(f.input).not.toHaveBeenCalled()
+})
+it.each([undefined, { after: [], command: 'claude brief', attempted: false },
+ { after: [], command: 'claude brief', attempted: true }])('never grants a warm/restored initial command a transient attempt (%j)', async (pending) => {
+ const f = fixture()
+ f.launch(false, pending); f.ready(); await tick()
+ f.launch(true); f.ready(); await tick()
+ expect(f.input).not.toHaveBeenCalled()
+ expect(f.scope.workspace.save).not.toHaveBeenCalled()
+})
+it('a fresh PTY does not bypass a restored or queued durable launch', async () => {
+ const f = fixture()
+ f.launch(true, { after: [], command: 'claude brief', attempted: false })
+ f.ready(); await tick()
+ expect(f.input).not.toHaveBeenCalled()
+})
+it('local serialization keeps durable UI intent while relay serialization preserves only existing queued intent', () => {
+ const f = fixture()
+ expect(flowToNodeStates([f.node])[0].pendingLaunch).toEqual({ after: [], command: 'claude brief', attempted: false })
+ f.node.data.pendingLaunch = { after: ['upstream'], command: 'other', attempted: false }
+ expect(flowToNodeStates([f.node], false)[0].pendingLaunch).toEqual(f.node.data.pendingLaunch)
+})
+
+it('uncertain delivery after input never pastes again on remount', async () => {
+ const f = fixture()
+ f.launch(); f.ready(); await tick()
+ expect(f.input.mock.calls).toEqual([['claude brief']])
+ f.dispose(); await tick()
+ f.launch(); f.ready(); await tick()
+ expect(f.input.mock.calls).toEqual([['claude brief']])
+ expect(f.failure).toHaveBeenCalledWith('cancelled')
+ expect(f.scope.workspace.save).not.toHaveBeenCalled()
+})
diff --git a/src/renderer/terminal/relay-initial-launch.ts b/src/renderer/terminal/relay-initial-launch.ts
new file mode 100644
index 000000000..c8a9e6209
--- /dev/null
+++ b/src/renderer/terminal/relay-initial-launch.ts
@@ -0,0 +1,36 @@
+import type { PendingLaunch } from '@shared/types'
+import { createLaunchWriter } from './launch-command'
+import type { DeliveryOutcome } from './command-delivery'
+
+// Transient proof is scoped to this connection, never restored from workspace data. Consume
+// before settle so a parked/remounted view cannot retry even if no bytes ultimately arrived.
+const consumed = new WeakMap<object, Set<string>>()
+export function deliverRelayInitialLaunch(opts: {
+ scope: object
+ id: string
+ fresh: boolean
+ pending?: PendingLaunch
+ command: string
+ consume(): void
+ whenReady(run: () => void): void
+ writer: Omit<Parameters<typeof createLaunchWriter>[0], 'claimAttempt'>
+ onFailure(outcome: DeliveryOutcome): void
+}): void {
+ let ids = consumed.get(opts.scope)
+ if (!ids) { ids = new Set(); consumed.set(opts.scope, ids) }
+ opts.consume()
+ const seen = ids.has(opts.id)
+ ids.add(opts.id)
+ if (seen || !opts.fresh || opts.pending) return
+ // This writer is private to the new UI initial command. It is NOT registered for queued
+ // launches/Run now, and has no workspace or pendingLaunch mutation capability.
+ const write = createLaunchWriter({ ...opts.writer, claimAttempt: async () => true })
+ let fired = false
+ opts.whenReady(() => {
+ if (fired) return
+ fired = true
+ void write(opts.command, false).then((outcome) => {
+ if (outcome !== 'submitted' && outcome !== 'deferred') opts.onFailure(outcome)
+ })
+ })
+}