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
feat(core): launchHeadless — settle, shell probe, echo-verified delivery (#925)
reviewf72010c87173
diff --git a/src/core/headless-launch.test.ts b/src/core/headless-launch.test.tsnew file mode 100644index 000000000..4216e8250--- /dev/null+++ b/src/core/headless-launch.test.ts@@ -0,0 +1,202 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { DELIVERY_ATTEMPTS, KILL_LINE, VERIFY_TIMEOUT_MS } from '@shared/command-delivery'+import type { HeadlessLaunchRequest } from '@shared/headless-launch'+import { launchHeadless, SETTLE_CAP_MS, SETTLE_QUIET_MS, type HeadlessLaunchDeps } from './headless-launch'+import type { PtyManager } from './pty-manager'++const CMD = "claude 'fix the flaky test in the worker pool'"++function harness(opts: { echoFrom?: number; fresh?: boolean; pane?: string | null } = {}) {+ const writes: string[] = []+ const listeners = new Set<(c: string) => void>()+ let cmdWrites = 0+ const deps: HeadlessLaunchDeps = {+ persistentSpawnAvailable: vi.fn(() => true),+ createHeadless: vi.fn(async () => ({ sessionId: 's1', fresh: opts.fresh ?? true, persistent: true })),+ paneCommand: vi.fn(async () => (opts.pane === undefined ? 'zsh' : opts.pane)),+ writeHeadless: vi.fn((_k: string, d: string) => {+ writes.push(d)+ if (d === '\r' || d === KILL_LINE || d === '\x1b') return true+ cmdWrites += 1+ // The shell echoes what it was typed, from the `echoFrom`-th command write on (1 = at once).+ if (cmdWrites >= (opts.echoFrom ?? 1)) for (const l of [...listeners]) l(d)+ return true+ }),+ onOutput: vi.fn((_k: string, cb: (c: string) => void) => {+ listeners.add(cb)+ return () => listeners.delete(cb)+ }),+ releaseHeadless: vi.fn()+ }+ const emit = (c: string): void => { for (const l of [...listeners]) l(c) }+ return { deps, writes, emit, listeners }+}++const req = (over: Partial<HeadlessLaunchRequest> = {}): HeadlessLaunchRequest => ({+ ptyOptions: { cols: 120, rows: 36, persistKey: 'n1', cwd: '/repo', shell: '/bin/zsh' },+ command: CMD,+ release: true,+ requirePersistent: true,+ ...over+})++beforeEach(() => vi.useFakeTimers())+afterEach(() => vi.useRealTimers())++describe('launchHeadless (#925)', () => {+ it('a PtyManager is the deps as-is (checked by npm run typecheck)', () => {+ const structural: PtyManager extends HeadlessLaunchDeps ? true : false = true+ expect(structural).toBe(true)+ })++ it('refuses before spawning when no persistent backend exists', async () => {+ const { deps } = harness()+ ;(deps.persistentSpawnAvailable as ReturnType<typeof vi.fn>).mockReturnValue(false)+ expect(await launchHeadless(deps, req())).toEqual({ outcome: 'failed', reason: 'not-persistent' })+ expect(deps.createHeadless).not.toHaveBeenCalled()+ expect(deps.releaseHeadless).not.toHaveBeenCalled()+ })++ it('does not ask about persistence when the caller keeps its client (Server Edition)', async () => {+ const { deps } = harness()+ ;(deps.persistentSpawnAvailable as ReturnType<typeof vi.fn>).mockReturnValue(false)+ const p = launchHeadless(deps, req({ release: false, requirePersistent: false }))+ await vi.advanceTimersByTimeAsync(SETTLE_CAP_MS)+ expect(await p).toEqual({ outcome: 'delivered', fresh: true })+ expect(deps.persistentSpawnAvailable).not.toHaveBeenCalled()+ })++ // The pre-spawn probe races a settings change: tmux switched off in between yields a plain+ // shell, and releasing a plain shell kills it. Typing a launch into it would kill that launch too.+ it('refuses a spawn that came back non-persistent, without typing, and still releases', async () => {+ const { deps, writes } = harness()+ ;(deps.createHeadless as ReturnType<typeof vi.fn>).mockResolvedValue({ sessionId: 's1', fresh: true, persistent: false })+ expect(await launchHeadless(deps, req())).toEqual({ outcome: 'failed', reason: 'not-persistent', fresh: true })+ expect(writes).toEqual([])+ expect(deps.paneCommand).not.toHaveBeenCalled()+ expect(deps.releaseHeadless).toHaveBeenCalledWith('n1')+ })++ it('delivers into a non-persistent spawn when the caller does not require persistence', async () => {+ const { deps, writes } = harness()+ ;(deps.createHeadless as ReturnType<typeof vi.fn>).mockResolvedValue({ sessionId: 's1', fresh: true, persistent: false })+ const p = launchHeadless(deps, req({ requirePersistent: false }))+ await vi.advanceTimersByTimeAsync(SETTLE_CAP_MS)+ expect(await p).toEqual({ outcome: 'delivered', fresh: true })+ expect(writes).toEqual([CMD, '\r'])+ })++ it('an older core that omits `persistent` counts as persistent', async () => {+ const { deps } = harness()+ ;(deps.createHeadless as ReturnType<typeof vi.fn>).mockResolvedValue({ sessionId: 's1', fresh: true })+ const p = launchHeadless(deps, req())+ await vi.advanceTimersByTimeAsync(SETTLE_CAP_MS)+ expect(await p).toEqual({ outcome: 'delivered', fresh: true })+ })++ it('waits for a fresh shell to settle before the pane probe (cap with no output)', async () => {+ const { deps, writes, listeners } = harness()+ const p = launchHeadless(deps, req())+ await vi.advanceTimersByTimeAsync(SETTLE_CAP_MS - 1)+ expect(deps.paneCommand).not.toHaveBeenCalled()+ expect(writes).toEqual([])+ await vi.advanceTimersByTimeAsync(1)+ expect(await p).toEqual({ outcome: 'delivered', fresh: true })+ expect(writes).toEqual([CMD, '\r'])+ expect(deps.releaseHeadless).toHaveBeenCalledWith('n1')+ // Both output taps (the settle's and the delivery's) are gone once the launch is over.+ expect(listeners.size).toBe(0)+ })++ it('output restarts the quiet window', async () => {+ const { deps, emit } = harness()+ const p = launchHeadless(deps, req())+ await vi.advanceTimersByTimeAsync(10)+ emit('prompt% ')+ await vi.advanceTimersByTimeAsync(SETTLE_QUIET_MS - 1)+ expect(deps.paneCommand).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(await p).toMatchObject({ outcome: 'delivered' })+ })++ it('an existing session skips the settle and clears any pending input first', async () => {+ const { deps, writes } = harness({ fresh: false })+ expect(await launchHeadless(deps, req())).toEqual({ outcome: 'delivered', fresh: false })+ expect(writes).toEqual([KILL_LINE, CMD, '\r'])+ })++ it('types nothing when no shell owns the pane (a running agent, an unreadable probe)', async () => {+ for (const pane of ['vim', null]) {+ const { deps, writes } = harness({ fresh: false, pane })+ expect(await launchHeadless(deps, req())).toEqual({ outcome: 'failed', reason: 'no-shell', fresh: false })+ expect(writes).toEqual([])+ expect(deps.releaseHeadless).toHaveBeenCalledWith('n1')+ }+ })++ it('treats a throwing probe as no shell', async () => {+ const { deps, writes } = harness({ fresh: false })+ ;(deps.paneCommand as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('tmux gone'))+ expect(await launchHeadless(deps, req())).toMatchObject({ outcome: 'failed', reason: 'no-shell' })+ expect(writes).toEqual([])+ })++ // Review Focus 2: rc work swallowed the first attempt — kill the line and retype, never submit it.+ it('a first attempt whose echo never arrives is killed and retried, not submitted', async () => {+ const { deps, writes } = harness({ fresh: false, echoFrom: 2 })+ const p = launchHeadless(deps, req())+ await vi.advanceTimersByTimeAsync(VERIFY_TIMEOUT_MS)+ expect(await p).toEqual({ outcome: 'delivered', fresh: false })+ expect(writes).toEqual([KILL_LINE, CMD, KILL_LINE, CMD, '\r'])+ })++ // Review Focus 3: a line the tty cannot hold is refused, never submitted truncated (#706).+ it('an over-long command that never echoes ends line-too-long with no Enter', async () => {+ const long = `claude '${'x'.repeat(5000)}'`+ const { deps, writes } = harness({ fresh: false, echoFrom: Number.POSITIVE_INFINITY })+ const p = launchHeadless(deps, req({ command: long }))+ await vi.advanceTimersByTimeAsync(VERIFY_TIMEOUT_MS * DELIVERY_ATTEMPTS)+ expect(await p).toEqual({ outcome: 'failed', reason: 'line-too-long', fresh: false })+ expect(writes).not.toContain('\r')+ expect(writes[writes.length - 1]).toBe(KILL_LINE)+ })++ it('a refused headless write ends the delivery as cancelled', async () => {+ const { deps } = harness({ fresh: false })+ ;(deps.writeHeadless as ReturnType<typeof vi.fn>).mockReturnValue(false)+ expect(await launchHeadless(deps, req())).toMatchObject({ outcome: 'failed', reason: 'cancelled' })+ })++ it('spawn failures: a throw, no session, or an unavailable answer', async () => {+ for (const impl of [+ async () => { throw new Error('spawn') },+ async () => ({ sessionId: '', fresh: true }),+ async () => ({ sessionId: 's1', fresh: true, unavailable: 'ssh' as const })+ ]) {+ const { deps } = harness()+ ;(deps.createHeadless as ReturnType<typeof vi.fn>).mockImplementation(impl)+ expect(await launchHeadless(deps, req())).toMatchObject({ outcome: 'failed', reason: 'spawn-failed' })+ }+ })++ it('never releases when nothing was spawned', async () => {+ for (const impl of [async () => { throw new Error('spawn') }, async () => ({ sessionId: '', fresh: true })]) {+ const { deps } = harness()+ ;(deps.createHeadless as ReturnType<typeof vi.fn>).mockImplementation(impl)+ await launchHeadless(deps, req())+ expect(deps.releaseHeadless).not.toHaveBeenCalled()+ }+ })++ it('keeps the client when asked to (release:false)', async () => {+ const { deps } = harness({ fresh: false })+ await launchHeadless(deps, req({ release: false }))+ expect(deps.releaseHeadless).not.toHaveBeenCalled()+ })++ it('uses the Windows line-clear for a PowerShell pane', async () => {+ const { deps, writes } = harness({ fresh: false, pane: 'pwsh' })+ await launchHeadless(deps, req({ ptyOptions: { cols: 1, rows: 1, persistKey: 'n1', shell: 'pwsh.exe' } }))+ expect(writes[0]).toBe('\x1b')+ })+})diff --git a/src/core/headless-launch.ts b/src/core/headless-launch.tsnew file mode 100644index 000000000..49362148d--- /dev/null+++ b/src/core/headless-launch.ts@@ -0,0 +1,122 @@+// The headless launcher (#925): start a node's session with no viewer and deliver its launch+// command exactly the way a mounted terminal does — settle, prove a shell owns the pane, then the+// echo-verified writer (@shared/command-delivery). The desktop runs it for canvas-control+// `--run-now` / `run`; the Server Edition runs it for every immediate open.+//+// Never a blind paste: zsh's rc/ZLE setup FLUSHES the tty (#556) and a canonical-mode line is cut+// at the tty's cap (#706). A tmux paste is not immune to either, which is why the desktop rule+// "launches use the echo-verified writer, not sendText" now covers this path too.+import { deliverCommand, type DeliveryIo, type DeliveryOutcome } from '../shared/command-delivery'+import { isLaunchShell } from '../shared/agents/pane'+import type { HeadlessLaunchRequest, HeadlessLaunchResult } from '../shared/headless-launch'+import { shellKillLineSequence } from '../shared/shell-kill-line'+import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'++/** Same numbers as TerminalNode's `whenShellSettled`: 200 ms of quiet after output = prompt is up;+ * 1500 ms of total silence = write anyway. */+export const SETTLE_QUIET_MS = 200+export const SETTLE_CAP_MS = 1500++export interface HeadlessLaunchDeps {+ persistentSpawnAvailable(): boolean+ createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult>+ paneCommand(persistKey: string): Promise<string | null>+ writeHeadless(persistKey: string, data: string): boolean+ onOutput(persistKey: string, cb: (chunk: string) => void): () => void+ releaseHeadless(persistKey: string): void+ /** Test seam; production uses SETTLE_QUIET_MS / SETTLE_CAP_MS. */+ timing?: { quietMs: number; capMs: number }+}++export async function launchHeadless(+ deps: HeadlessLaunchDeps,+ req: HeadlessLaunchRequest+): Promise<HeadlessLaunchResult> {+ const key = req.ptyOptions.persistKey+ if (!key) return { outcome: 'failed', reason: 'spawn-failed' }+ if (req.requirePersistent && !deps.persistentSpawnAvailable()) {+ return { outcome: 'failed', reason: 'not-persistent' }+ }+ let created: PtyCreateResult+ try {+ created = await deps.createHeadless(req.ptyOptions)+ } catch {+ return { outcome: 'failed', reason: 'spawn-failed' }+ }+ if (!created.sessionId) return { outcome: 'failed', reason: 'spawn-failed' }+ const fresh = created.fresh+ try {+ if (created.unavailable) return { outcome: 'failed', reason: 'spawn-failed', fresh }+ // The probe above can be stale by the time the spawn lands (tmux switched off in between), and+ // a plain shell dies with the client this launcher is about to release — typing a launch into+ // it would start an agent only to kill it. `persistent` absent = an older core, persistent by+ // the field's own contract (`PtyCreateResult.persistent`, and `trustsFreshShell` reads it so).+ if (req.requirePersistent && created.persistent === false) {+ return { outcome: 'failed', reason: 'not-persistent', fresh }+ }+ if (fresh) await settle(deps, key)+ let pane: string | null+ try {+ pane = await deps.paneCommand(key)+ } catch {+ pane = null+ }+ // Unknown is not a shell: an un-typed launch is recoverable (Run now), a spliced one is not.+ if (!isLaunchShell(pane)) return { outcome: 'failed', reason: 'no-shell', fresh }+ const killLine = shellKillLineSequence(undefined, req.ptyOptions.shell)+ const outcome = await deliver(deps, key, req.command, killLine, !fresh)+ return outcome === 'submitted'+ ? { outcome: 'delivered', fresh }+ : { outcome: 'failed', reason: outcome, fresh }+ } finally {+ if (req.release) deps.releaseHeadless(key)+ }+}++function settle(deps: HeadlessLaunchDeps, key: string): Promise<void> {+ const quietMs = deps.timing?.quietMs ?? SETTLE_QUIET_MS+ const capMs = deps.timing?.capMs ?? SETTLE_CAP_MS+ return new Promise((resolve) => {+ let done = false+ let unsub: (() => void) | undefined+ const finish = (): void => {+ if (done) return+ done = true+ clearTimeout(timer)+ unsub?.()+ resolve()+ }+ let timer = setTimeout(finish, capMs)+ unsub = deps.onOutput(key, () => {+ if (done) return+ clearTimeout(timer)+ timer = setTimeout(finish, quietMs)+ })+ })+}++function deliver(+ deps: HeadlessLaunchDeps,+ key: string,+ command: string,+ killLine: string,+ clearFirst: boolean+): Promise<DeliveryOutcome> {+ return new Promise((resolve) => {+ const io: DeliveryIo = {+ write: (data) => {+ // A refused write means client 0 no longer holds the session: end the delivery (cancelled)+ // rather than keep typing into nothing.+ if (!deps.writeHeadless(key, data)) throw new Error('headless write refused')+ },+ onData: (cb) => deps.onOutput(key, cb)+ }+ try {+ // A live session may hold a half-typed line; start clean, as the manual Run now path does.+ if (clearFirst) io.write(killLine)+ deliverCommand(io, command, resolve, { killLine })+ } catch {+ resolve('cancelled')+ }+ })+}diff --git a/src/shared/headless-launch.ts b/src/shared/headless-launch.tsnew file mode 100644index 000000000..e5cde0d85--- /dev/null+++ b/src/shared/headless-launch.ts@@ -0,0 +1,16 @@+// Wire types of the headless launcher (#925): core/headless-launch.ts implements it, desktop main+// exposes it as `pty.launchHeadless`, the renderer's `--run-now` / `run` consume the result.+import type { PtyCreateOptions } from './types'++export type HeadlessLaunchFailure = 'not-persistent' | 'spawn-failed' | 'no-shell' | 'line-too-long' | 'cancelled'+export type HeadlessLaunchResult =+ | { outcome: 'delivered'; fresh: boolean }+ | { outcome: 'failed'; reason: HeadlessLaunchFailure; fresh?: boolean }+export interface HeadlessLaunchRequest {+ ptyOptions: PtyCreateOptions+ command: string+ /** Release the synthetic client afterwards (desktop: true; Server Edition: false). */+ release: boolean+ /** Refuse without a persistent backend (desktop: true — it releases; Server Edition: false). */+ requirePersistent: boolean+}