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.

feat(server): immediate opens deliver through the echo-verified launcher

review8cd3907ac55a
diff --git a/CLAUDE.md b/CLAUDE.md
index 68338b707..d0ee087ea 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -3095,6 +3095,10 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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`.
+ Headless starts (`core/headless-launch.ts`, #925) and the Server Edition's immediate open deliver
+ through the SAME echo-verified writer (`@shared/command-delivery`, moved out of the renderer for
+ this): a tmux paste is not immune to zsh's rc-time tty flush (#556) or the canonical-line cap
+ (#706).
(5) UI `initialCommand` stays until submission; serialization converts unsubmitted UI intent
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
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index aa82a474e..80e42cb1b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -777,7 +777,10 @@ coordinate nodeterm, not external editors, so do not claim a filesystem-wide com
**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.
-Desktop launches (automatic and Run now) use the echo-verified command writer, not `sendText`.
+Every launch uses the echo-verified command writer (`@shared/command-delivery`), not `sendText`:
+desktop automatic and Run now, the desktop headless start (`core/headless-launch.ts`), and the
+Server Edition's immediate open. The Server Edition's deferred `--after` release (`refreshArmed`)
+is the one remaining `sendText` launch, pending a move that must never create a session.
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
diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.ts
index 428815e1d..c3320bbb4 100644
--- a/src/server/canvas-control.test.ts
+++ b/src/server/canvas-control.test.ts
@@ -27,6 +27,57 @@ import { IPC } from '../shared/ipc'
import { DEFAULT_SETTINGS, type Project, type Settings, type Workspace } from '../shared/types'
import { initServerCanvasControl, type ServerCanvasControl } from './canvas-control'
+type HeadlessShell = Pick<
+ PtyManager,
+ 'persistentSpawnAvailable' | 'writeHeadless' | 'onOutput' | 'releaseHeadless'
+> & { submitted: string[] }
+
+/**
+ * The headless taps of a fresh interactive shell, which an immediate open now types its launch
+ * into (#925): it prints its prompt once, echoes what it is typed, and records each line Enter
+ * submits. The prompt is what ends the launcher's settle after its quiet window; without it every
+ * open would wait out the full settle cap.
+ */
+function headlessShell(): HeadlessShell {
+ const taps = new Map<string, Set<(chunk: string) => void>>()
+ const lines = new Map<string, string>()
+ const prompted = new Set<string>()
+ const submitted: string[] = []
+ return {
+ submitted,
+ persistentSpawnAvailable: () => true,
+ onOutput: (key, cb) => {
+ let set = taps.get(key)
+ if (!set) taps.set(key, (set = new Set()))
+ set.add(cb)
+ if (!prompted.has(key)) {
+ prompted.add(key)
+ setTimeout(() => {
+ if (set!.has(cb)) cb('$ ')
+ }, 0)
+ }
+ return () => {
+ set!.delete(cb)
+ }
+ },
+ writeHeadless: (key, data) => {
+ if (data === '\r') {
+ submitted.push(lines.get(key) ?? '')
+ lines.set(key, '')
+ return true
+ }
+ if (data === '\x15' || data === '\x1b') {
+ lines.set(key, '')
+ return true
+ }
+ lines.set(key, (lines.get(key) ?? '') + data)
+ for (const cb of [...(taps.get(key) ?? [])]) cb(data)
+ return true
+ },
+ releaseHeadless: () => undefined
+ }
+}
+
describe('initServerCanvasControl', () => {
let dataDir = ''
let runtime: ServerCanvasControl | null = null
@@ -99,7 +150,9 @@ describe('initServerCanvasControl', () => {
const paneOwner = vi.fn(async () => null)
const sendEnvelope = vi.fn(async () => true)
const sendText = vi.fn(async (_nodeId: string, _text: string) => true)
+ const shell = headlessShell()
const pty = {
+ ...shell,
createHeadless: vi.fn(async () => ({ sessionId: 'unused', fresh: true })),
paneCommand: vi.fn(async () => 'bash'),
sendText,
@@ -146,9 +199,11 @@ describe('initServerCanvasControl', () => {
})
expect(opened).toMatchObject({ ok: true })
const openedId = (opened.result as { id: string }).id
- expect(sendText.mock.calls.at(-1)?.[1]).toBe(
+ // The launch is typed into the shell and submitted, never pasted blind (#925).
+ expect(shell.submitted).toEqual([
"nodeterm-codex 'identity proof' --ask-for-approval on-request"
- )
+ ])
+ expect(sendText).not.toHaveBeenCalled()
const unowned = await runtime.handler({
verb: 'send',
@@ -227,6 +282,7 @@ describe('initServerCanvasControl', () => {
let pasted = ''
const legacySendEnvelope = vi.fn(async () => true)
const pty = {
+ ...headlessShell(),
createHeadless: vi.fn(async () => ({ sessionId: 'unused', fresh: true })),
paneCommand: vi.fn(async () => 'bash'),
captureSession: vi.fn(async () =>
@@ -338,6 +394,7 @@ describe('initServerCanvasControl', () => {
capabilityProjectFor: () => ({ agentMessaging: false, capabilityAck: {} })
} as unknown as WorkspaceStore
const pty = {
+ ...headlessShell(),
createHeadless: vi.fn(async () => ({ sessionId: 'unused', fresh: true })),
paneCommand: vi.fn(async () => 'bash'),
sendText: vi.fn(async () => true),
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index fdbbd782f..3d18d4e35 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -34,6 +34,42 @@ class FakePty implements HeadlessPty {
}> = []
readonly live = new Set<string>()
readonly alreadyDead = new Set<string>()
+ readonly released: string[] = []
+ private readonly taps = new Map<string, Set<(c: string) => void>>()
+ private readonly lines = new Map<string, string>()
+
+ persistentSpawnAvailable(): boolean {
+ return true
+ }
+
+ onOutput(key: string, cb: (c: string) => void): () => void {
+ let set = this.taps.get(key)
+ if (!set) this.taps.set(key, (set = new Set()))
+ set.add(cb)
+ return () => set!.delete(cb)
+ }
+
+ // An interactive shell: echoes what it is typed; Enter submits the line (recorded in `sends`,
+ // so every pre-existing `pty.sends` assertion keeps its meaning); Ctrl-U / Esc clear it.
+ writeHeadless(key: string, data: string): boolean {
+ if (!this.live.has(key)) return false
+ if (data === '\r') {
+ this.sends.push({ nodeId: key, text: this.lines.get(key) ?? '' })
+ this.lines.set(key, '')
+ return true
+ }
+ if (data === '\x15' || data === '\x1b') {
+ this.lines.set(key, '')
+ return true
+ }
+ this.lines.set(key, (this.lines.get(key) ?? '') + data)
+ for (const cb of [...(this.taps.get(key) ?? [])]) cb(data)
+ return true
+ }
+
+ releaseHeadless(key: string): void {
+ this.released.push(key)
+ }
async createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult> {
this.creates.push(options)
@@ -170,6 +206,7 @@ describe('HeadlessNodeFactory', () => {
codexSharedIdentity: async () => codexSharedIdentity,
ownership,
stateOf: (id) => states[id],
+ launchTiming: { quietMs: 0, capMs: 0 },
publishNode: (_projectId, node) => published.push(node),
publishRemoval: (_projectId, nodeId) => removed.push(nodeId),
publishProject: (project) => publishedProjects.push(structuredClone(project))
@@ -1028,8 +1065,11 @@ describe('HeadlessNodeFactory', () => {
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)
+ else if (failure === 'throws') {
+ vi.spyOn(pty, 'writeHeadless').mockImplementation(() => {
+ throw new Error('disconnected')
+ })
+ } else vi.spyOn(pty, 'writeHeadless').mockReturnValue(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] } })
@@ -1051,16 +1091,21 @@ describe('HeadlessNodeFactory', () => {
it('saves manual recovery intent before sending, including a successful send whose clearing save fails', async () => {
const save = vi.spyOn(store, 'save')
- vi.spyOn(pty, 'sendText').mockImplementationOnce(async (id) => {
- const durable = await store.load({ sideline: false })
- expect(durable.projects[0].nodes.find((n) => n.id === id)?.pendingLaunch)
- .toMatchObject({ command: "claude 'brief'", manualOnly: true })
- save.mockRejectedValueOnce(new Error('disk unavailable after delivery'))
- pty.sends.push({ nodeId: id, text: 'brief' })
- return true
+ const typeInto = pty.writeHeadless.bind(pty)
+ // The headless write is synchronous, so the durable read starts at the first typed byte and is
+ // awaited afterwards. Nothing reaches the disk in between: the next save is the one failed here.
+ let firstWrite: { id: string; durable: ReturnType<WorkspaceStore['load']> } | undefined
+ vi.spyOn(pty, 'writeHeadless').mockImplementation((id, data) => {
+ firstWrite ??= { id, durable: store.load({ sideline: false }) }
+ if (data === '\r') save.mockRejectedValueOnce(new Error('disk unavailable after delivery'))
+ return typeInto(id, data)
})
await expect(factory.openAgent('term-source', { agent: 'claude', prompt: 'brief' }, true))
.rejects.toThrow('disk unavailable')
+ const durable = await firstWrite!.durable
+ expect(durable.projects[0].nodes.find((n) => n.id === firstWrite!.id)?.pendingLaunch)
+ .toMatchObject({ command: "claude 'brief'", manualOnly: true })
+ expect(pty.sends).toEqual([{ nodeId: firstWrite!.id, text: "claude 'brief'" }])
await factory.refreshArmed({ nodeId: 'term-upstream', state: 'done' })
expect(pty.sends).toHaveLength(1)
})
@@ -1082,7 +1127,13 @@ describe('HeadlessNodeFactory', () => {
})
it('reports a partial batch and never retries the retained launch on unrelated hooks', async () => {
- vi.spyOn(pty, 'sendText').mockResolvedValueOnce(true).mockResolvedValueOnce(false)
+ // The first node's writes land; every write into the second is refused.
+ const typeInto = pty.writeHeadless.bind(pty)
+ let firstId: string | undefined
+ vi.spyOn(pty, 'writeHeadless').mockImplementation((id, data) => {
+ firstId ??= id
+ return id === firstId ? typeInto(id, data) : 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: [] } })
@@ -1239,4 +1290,25 @@ describe('HeadlessNodeFactory', () => {
expect(reply).toMatchObject({ ok: false, error: expect.stringContaining('claude|codex|gemini') })
expect(pty.creates).toEqual([])
})
+
+ it('immediate delivery is echo-verified and keeps the server client attached (#925)', async () => {
+ // `sends` records the blind paste and the typed-then-Enter line identically, so the path taken
+ // is only visible here: the immediate open must never fall back to `sendText`.
+ const paste = vi.spyOn(pty, 'sendText')
+ const reply = await factory.openTerminal('term-source', { cwd: projectDir, cmd: 'printf hello' }, true)
+ const id = (reply.result as { id: string }).id
+ expect(pty.sends).toEqual([{ nodeId: id, text: 'printf hello' }])
+ expect(paste).not.toHaveBeenCalled()
+ expect(pty.released).toEqual([]) // release:false — the server keeps client 0, as it always has
+ })
+
+ it('a refused headless write retains the launch for Run now (#925)', async () => {
+ vi.spyOn(pty, 'writeHeadless').mockReturnValue(false)
+ const reply = await factory.openTerminal('term-source', { cwd: projectDir, cmd: 'printf hello' }, true)
+ expect(reply.ok).toBe(false)
+ expect(reply.error).toMatch(/^launch-failed:/)
+ const id = (reply.result as { id: string }).id
+ const node = (await store.load({ sideline: false })).projects[0].nodes.find((n) => n.id === id)
+ expect(node?.pendingLaunch).toMatchObject({ command: 'printf hello', manualOnly: true })
+ })
})
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index 1e121cd27..ee71a13c4 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -4,6 +4,7 @@ import { randomBytes, randomUUID } from 'node:crypto'
import path from 'node:path'
import { publishCanvasMutation } from '../core/canvas-sync'
+import { launchHeadless } from '../core/headless-launch'
import { gateProjectTarget, GRANT_CAP } from '../core/project-grants'
import {
LINK_ENDPOINT_NOT_FOUND,
@@ -18,6 +19,7 @@ import {
type NodeColor
} from '../shared/node-colors'
import { applyStickyWrite, parseStickyArgs, resolveStickyRef } from '../shared/sticky-write'
+import type { HeadlessLaunchResult } from '../shared/headless-launch'
import { localNodePtyOptions } from '../shared/node-pty-options'
import type { WorkspaceStore } from '../core/workspace-store'
import {
@@ -62,6 +64,10 @@ export interface HeadlessPty {
paneCommand(persistKey: string): Promise<string | null>
sessionExists(persistKey: string): Promise<boolean>
sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<TextDeliveryResult>
+ persistentSpawnAvailable(): boolean
+ writeHeadless(persistKey: string, data: string): boolean
+ onOutput(persistKey: string, cb: (chunk: string) => void): () => void
+ releaseHeadless(persistKey: string): void
destroySession(
clientId: number | null,
persistKey: string,
@@ -106,6 +112,8 @@ export interface HeadlessNodeFactoryDeps {
publishProject?: (project: Project) => void
/** Injectable only so tests can seed creator facts; production uses a fresh process-local ledger. */
ownership?: HeadlessNodeOwnership
+ /** Test seam for the launch settle; production uses core's SETTLE_* defaults. */
+ launchTiming?: { quietMs: number; capMs: number }
}
export interface HeadlessNodeOwner {
@@ -589,6 +597,29 @@ export class HeadlessNodeFactory {
return result
}
+ /**
+ * Spawn-or-attach `node` and deliver `command` through the shared echo-verified launcher (#925).
+ * - `release:false` keeps the server's synthetic client attached, as it always has.
+ * - `requirePersistent:false`, because that attached client is what keeps even a plain-shell
+ * session reachable here. (The desktop releases its client, so it refuses a plain shell instead.)
+ * - `createHeadless` goes through `attach()` so the `attached` ledger stays authoritative.
+ */
+ private launch(project: Project, node: CanvasNodeState, command: string): Promise<HeadlessLaunchResult> {
+ const pty = this.deps.ptyManager
+ return launchHeadless(
+ {
+ persistentSpawnAvailable: () => pty.persistentSpawnAvailable(),
+ createHeadless: () => this.attach(project, node),
+ paneCommand: (key) => pty.paneCommand(key),
+ writeHeadless: (key, data) => pty.writeHeadless(key, data),
+ onOutput: (key, cb) => pty.onOutput(key, cb),
+ releaseHeadless: (key) => pty.releaseHeadless(key),
+ timing: this.deps.launchTiming
+ },
+ { ptyOptions: ptyOptions(project, node), command, release: false, requirePersistent: false }
+ )
+ }
+
private resolveTarget(
workspace: Workspace,
source: { project: Project; node: CanvasNodeState },
@@ -1229,18 +1260,18 @@ export class HeadlessNodeFactory {
const failed: string[] = []
for (const node of created) {
try {
- const result = await this.attach(target, node)
- if (!result.sessionId) {
- failed.push(node.id)
- continue
- }
- if (verb === 'open-agent' && result.fresh) this.awaitingFirstWorking.add(node.id)
const command = commands.get(node.id)
- if (command) {
- if (isLaunchShell(await this.deps.ptyManager.paneCommand(node.id)) &&
- (await this.deps.ptyManager.sendText(node.id, command)) === true) node.pendingLaunch = undefined
- else failed.push(node.id)
+ if (!command) {
+ // Nothing to deliver now (a plain terminal, or a launch held for `--after`): spawn only.
+ const result = await this.attach(target, node)
+ if (!result.sessionId) failed.push(node.id)
+ else if (verb === 'open-agent' && result.fresh) this.awaitingFirstWorking.add(node.id)
+ continue
}
+ const launched = await this.launch(target, node, command)
+ if (verb === 'open-agent' && launched.fresh) this.awaitingFirstWorking.add(node.id)
+ if (launched.outcome === 'delivered') node.pendingLaunch = undefined
+ else failed.push(node.id)
} catch {
failed.push(node.id)
}