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(canvas): headless start planners + orchestrator (#925)
reviewd2cacd70a66a
diff --git a/src/renderer/lib/headlessRun.test.ts b/src/renderer/lib/headlessRun.test.tsnew file mode 100644index 000000000..50983a455--- /dev/null+++ b/src/renderer/lib/headlessRun.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it, vi } from 'vitest'+import type { CanvasNodeState, PendingLaunch } from '@shared/types'+import type { HeadlessLaunchResult } from '@shared/headless-launch'+import { coldOpenMessage } from './coldOpen'+import {+ claimForHeadless,+ headlessStartNoticeText,+ mergeRunNow,+ planRunVerb,+ savePendingAnywhere,+ startHeadless,+ type HeadlessStartDeps,+ type PendingStoreEnv+} from './headlessRun'++const pending: PendingLaunch = { after: [], command: "claude 'go'", attempted: false }+const node = (over: Partial<CanvasNodeState> = {}): CanvasNodeState =>+ ({ id: 'n1', kind: 'terminal', agentId: 'claude', pendingLaunch: pending, ...over }) as CanvasNodeState+const project = { id: 'p2', cwd: '/repo' }++function deps(result: HeadlessLaunchResult | (() => Promise<HeadlessLaunchResult>), save = true) {+ const saved: Array<PendingLaunch | undefined> = []+ const d: HeadlessStartDeps = {+ launch: vi.fn(typeof result === 'function' ? result : async () => result),+ savePending: vi.fn(async (_id, p) => {+ saved.push(p)+ return save+ }),+ markStarting: vi.fn(),+ markFailed: vi.fn(),+ clearDelivery: vi.fn(),+ inFlight: new Set()+ }+ return { d, saved }+}++describe('planRunVerb', () => {+ it('covers every branch', () => {+ const base = { pending, inFlight: false, projectActive: false, hasWriter: false }+ expect(planRunVerb({ ...base, pending: undefined })).toBe('nothing-queued')+ expect(planRunVerb({ ...base, inFlight: true })).toBe('already-starting')+ expect(planRunVerb({ ...base, projectActive: true, hasWriter: true })).toBe('mounted')+ expect(planRunVerb({ ...base, projectActive: true })).toBe('wait-for-mount')+ expect(planRunVerb(base)).toBe('headless')+ })+})++describe('claimForHeadless', () => {+ it('marks the launch attempted, manual-only and core-executed', () => {+ expect(claimForHeadless(pending)).toEqual({ ...pending, attempted: true, manualOnly: true, executor: 'core' })+ })+})++describe('startHeadless', () => {+ it('delivered: claim saved BEFORE the launch, cleared after, notice-worthy', async () => {+ const order: string[] = []+ const { d, saved } = deps({ outcome: 'delivered', fresh: true })+ ;(d.savePending as ReturnType<typeof vi.fn>).mockImplementation(async (_id: string, p: PendingLaunch | undefined) => {+ order.push(p ? 'save-claim' : 'save-clear')+ saved.push(p)+ return true+ })+ ;(d.launch as ReturnType<typeof vi.fn>).mockImplementation(async () => {+ order.push('launch')+ return { outcome: 'delivered', fresh: true }+ })+ expect(await startHeadless(d, { project, node: node() })).toEqual({ id: 'n1', started: true })+ expect(order).toEqual(['save-claim', 'launch', 'save-clear'])+ expect(saved[0]).toMatchObject({ manualOnly: true, attempted: true, executor: 'core' })+ expect(d.markStarting).toHaveBeenCalledWith('n1')+ expect(d.clearDelivery).toHaveBeenCalledWith('n1')+ expect(d.launch).toHaveBeenCalledWith({+ ptyOptions: expect.objectContaining({ persistKey: 'n1', cwd: '/repo', ownerProjectId: 'p2', agentId: 'claude' }),+ command: "claude 'go'"+ })+ })++ it('not-persistent: the ORIGINAL pending launch is restored, so the node starts on view', async () => {+ const { d, saved } = deps({ outcome: 'failed', reason: 'not-persistent' })+ expect(await startHeadless(d, { project, node: node() })).toEqual({ id: 'n1', started: false, reason: 'not-persistent' })+ expect(saved[saved.length - 1]).toEqual(pending)+ expect(d.markFailed).not.toHaveBeenCalled()+ })++ it('a run on an already-attempted node restores THAT state on not-persistent, never attempted:false', async () => {+ const amber: PendingLaunch = { ...pending, attempted: true, manualOnly: true }+ const { d, saved } = deps({ outcome: 'failed', reason: 'not-persistent' })+ await startHeadless(d, { project, node: node({ pendingLaunch: amber }) })+ expect(saved[saved.length - 1]).toEqual(amber)+ })++ it('other failures keep the claim and mark the node failed', async () => {+ const { d, saved } = deps({ outcome: 'failed', reason: 'no-shell', fresh: true })+ expect(await startHeadless(d, { project, node: node() })).toEqual({ id: 'n1', started: false, reason: 'no-shell' })+ expect(saved).toHaveLength(1) // only the claim+ expect(d.markFailed).toHaveBeenCalledWith('n1')+ })++ it('a rejected launch IPC counts as spawn-failed', async () => {+ const { d } = deps(async () => {+ throw new Error('ipc')+ })+ expect(await startHeadless(d, { project, node: node() })).toMatchObject({ started: false, reason: 'spawn-failed' })+ })++ // Review Focus 5+ it('a claim that cannot be saved spawns nothing and restores the original', async () => {+ const { d, saved } = deps({ outcome: 'delivered', fresh: true }, false)+ expect(await startHeadless(d, { project, node: node() })).toEqual({ id: 'n1', started: false, reason: 'claim-not-saved' })+ expect(d.launch).not.toHaveBeenCalled()+ expect(saved[saved.length - 1]).toEqual(pending)+ })++ // Review Focus 4+ it('two starts of one node: one launch, the second answered already-starting', async () => {+ let release!: (r: HeadlessLaunchResult) => void+ const { d } = deps(() => new Promise<HeadlessLaunchResult>((r) => (release = r)))+ const first = startHeadless(d, { project, node: node() })+ await Promise.resolve()+ await Promise.resolve()+ expect(await startHeadless(d, { project, node: node() })).toEqual({ id: 'n1', started: false, reason: 'already-starting' })+ release({ outcome: 'delivered', fresh: true })+ expect(await first).toEqual({ id: 'n1', started: true })+ expect(d.launch).toHaveBeenCalledTimes(1)+ expect(d.inFlight.size).toBe(0)+ })++ it('a node with nothing queued is not started', async () => {+ const { d } = deps({ outcome: 'delivered', fresh: true })+ expect(await startHeadless(d, { project, node: node({ pendingLaunch: undefined }) })).toEqual({+ id: 'n1',+ started: false,+ reason: 'nothing-queued'+ })+ })+})++describe('savePendingAnywhere', () => {+ // Review Focus 1: the user switched to the project mid-start. The outcome must patch the LIVE+ // node (React Flow is the truth for the active project), not the stale store copy.+ it('follows the node to wherever it lives at the moment of the write', async () => {+ let active = 'p1'+ const env: PendingStoreEnv = {+ activeProjectId: () => active,+ patchLive: vi.fn(() => true),+ patchStored: vi.fn(() => true),+ writeDisk: vi.fn(async () => true),+ markDirty: vi.fn()+ }+ expect(await savePendingAnywhere(env, 'p2', 'n1', pending)).toBe(true)+ expect(env.patchStored).toHaveBeenCalledWith('p2', 'n1', pending)+ expect(env.writeDisk).toHaveBeenCalledTimes(1)+ active = 'p2'+ expect(await savePendingAnywhere(env, 'p2', 'n1', undefined)).toBe(true)+ expect(env.patchLive).toHaveBeenCalledWith('n1', undefined)+ expect(env.markDirty).toHaveBeenCalledTimes(1)+ })+ it('reports a missing node or a failed disk write as not saved', async () => {+ const env: PendingStoreEnv = {+ activeProjectId: () => 'p1',+ patchLive: () => false,+ patchStored: () => true,+ writeDisk: async () => false,+ markDirty: () => {}+ }+ expect(await savePendingAnywhere(env, 'p2', 'n1', pending)).toBe(false)+ expect(await savePendingAnywhere({ ...env, activeProjectId: () => 'p2' }, 'p2', 'n1', pending)).toBe(false)+ })+})++describe('mergeRunNow + notice', () => {+ it('rewrites the cold-open reply: no "starts when viewed", no welcome-screen hint, started ids listed', () => {+ const base = {+ ok: true as const,+ message: coldOpenMessage(2, 'claude', 'Repo', ['a', 'b'], { closed: true }),+ result: { ids: ['a', 'b'], id: 'a', projectId: 'p2', queued: true, queuedIds: ['a', 'b'] }+ }+ const r = mergeRunNow(base, [+ { id: 'a', started: true },+ { id: 'b', started: false, reason: 'no-shell' }+ ])+ expect(r.message).not.toMatch(/starts when that project is next viewed/)+ expect(r.message).not.toMatch(/welcome screen/)+ expect(r.message).toMatch(/started: a/)+ expect(r.message).toMatch(/queued \(no-shell\): b/)+ expect(r.result).toMatchObject({ started: true, startedIds: ['a'], queued: true, queuedIds: ['b'], reason: 'no-shell' })+ })+ it('names the project and the count', () => {+ expect(headlessStartNoticeText('Repo', 1)).toBe('An agent started a session in "Repo". That project is not on screen.')+ expect(headlessStartNoticeText('Repo', 3)).toBe('An agent started 3 sessions in "Repo". That project is not on screen.')+ })+})diff --git a/src/renderer/lib/headlessRun.ts b/src/renderer/lib/headlessRun.tsnew file mode 100644index 000000000..c308d72d7--- /dev/null+++ b/src/renderer/lib/headlessRun.ts@@ -0,0 +1,157 @@+// Canvas-control headless start (#925): `open-* --run-now` and `run --node`. Pure planners plus+// one orchestrator with injected effects, so Canvas.tsx only wires. See the spec (§4) for the flow:+// write-ahead claim → launch through main → patch the node wherever it lives NOW.+import type { CanvasNodeState, PendingLaunch, Project, PtyCreateOptions } from '@shared/types'+import type { HeadlessLaunchFailure, HeadlessLaunchResult } from '@shared/headless-launch'+import { HEADLESS_COLS, HEADLESS_ROWS, localNodePtyOptions } from '@shared/node-pty-options'++export const RUN_NOW_AFTER_REFUSAL =+ 'run-now-after-unsupported: --run-now cannot be combined with --after'++export type RunVerbPlan = 'nothing-queued' | 'already-starting' | 'mounted' | 'wait-for-mount' | 'headless'++/** What `run --node` does. A project on screen never starts headless: its node either has a+ * mounted writer (the ▶ path) or starts through the ordinary path when its terminal next mounts. */+export function planRunVerb(input: {+ pending?: PendingLaunch+ inFlight: boolean+ projectActive: boolean+ hasWriter: boolean+}): RunVerbPlan {+ if (!input.pending?.command) return 'nothing-queued'+ if (input.inFlight) return 'already-starting'+ if (input.projectActive) return input.hasWriter ? 'mounted' : 'wait-for-mount'+ return 'headless'+}++/** The write-ahead claim, saved before any spawn: a crash mid-start can never auto-start twice+ * (`launchesToFire` skips manualOnly, on every build). */+export function claimForHeadless(p: PendingLaunch): PendingLaunch {+ return { ...p, executor: 'core', attempted: true, manualOnly: true }+}++export function headlessStartNoticeText(projectName: string, count: number): string {+ const what = count === 1 ? 'a session' : `${count} sessions`+ return `An agent started ${what} in "${projectName}". That project is not on screen.`+}++export type HeadlessStartOutcome =+ | { id: string; started: true }+ | {+ id: string+ started: false+ reason: HeadlessLaunchFailure | 'already-starting' | 'claim-not-saved' | 'nothing-queued'+ }++export interface HeadlessStartDeps {+ launch(req: { ptyOptions: PtyCreateOptions; command: string }): Promise<HeadlessLaunchResult>+ /** Persist `pending` (undefined = cleared) on the node wherever it lives NOW; true = on disk. */+ savePending(nodeId: string, pending: PendingLaunch | undefined): Promise<boolean>+ markStarting(nodeId: string): void+ markFailed(nodeId: string): void+ clearDelivery(nodeId: string): void+ /** Shared across calls: one start per node at a time. */+ inFlight: Set<string>+}++export async function startHeadless(+ deps: HeadlessStartDeps,+ input: { project: Pick<Project, 'id' | 'cwd'>; node: CanvasNodeState }+): Promise<HeadlessStartOutcome> {+ const { node, project } = input+ const id = node.id+ const original = node.pendingLaunch+ if (!original?.command) return { id, started: false, reason: 'nothing-queued' }+ if (deps.inFlight.has(id)) return { id, started: false, reason: 'already-starting' }+ deps.inFlight.add(id)+ try {+ if (!(await deps.savePending(id, claimForHeadless(original)))) {+ // Never spawn on an unsaved claim: a crash would re-deliver on the next view.+ await deps.savePending(id, original)+ return { id, started: false, reason: 'claim-not-saved' }+ }+ deps.markStarting(id)+ let result: HeadlessLaunchResult+ try {+ result = await deps.launch({+ ptyOptions: localNodePtyOptions(project, node, { cols: HEADLESS_COLS, rows: HEADLESS_ROWS }),+ command: original.command+ })+ } catch {+ result = { outcome: 'failed', reason: 'spawn-failed' }+ }+ if (result.outcome === 'delivered') {+ deps.clearDelivery(id)+ await deps.savePending(id, undefined)+ return { id, started: true }+ }+ if (result.reason === 'not-persistent') {+ // Nothing was spawned. Hand the node back exactly as it was, so a cold open starts on view+ // and an already-attempted node keeps its manual Run now.+ deps.clearDelivery(id)+ await deps.savePending(id, original)+ } else {+ deps.markFailed(id)+ }+ return { id, started: false, reason: result.reason }+ } finally {+ deps.inFlight.delete(id)+ }+}++export interface PendingStoreEnv {+ activeProjectId(): string+ patchLive(nodeId: string, pending: PendingLaunch | undefined): boolean+ patchStored(projectId: string, nodeId: string, pending: PendingLaunch | undefined): boolean+ writeDisk(): Promise<boolean>+ markDirty(): void+}++/** React Flow is the truth for the ACTIVE project, the store for every other one. Decided at the+ * moment of each write, because the user may switch projects while a start is in flight. */+export async function savePendingAnywhere(+ env: PendingStoreEnv,+ projectId: string,+ nodeId: string,+ pending: PendingLaunch | undefined+): Promise<boolean> {+ if (env.activeProjectId() === projectId) {+ if (!env.patchLive(nodeId, pending)) return false+ env.markDirty()+ return true+ }+ if (!env.patchStored(projectId, nodeId, pending)) return false+ return env.writeDisk()+}++const STARTS_ON_VIEW = / — queued; starts when that project is next viewed/+const CLOSED_HINT = / \(that project is closed — reopen it from the welcome screen\)/++/** Turn a cold-open reply (`coldOpenMessage` + result) into the `--run-now` reply. */+export function mergeRunNow<T extends { ok: true; message: string; result: Record<string, unknown> }>(+ base: T,+ outcomes: HeadlessStartOutcome[]+): T {+ const startedIds = outcomes.filter((o) => o.started).map((o) => o.id)+ const failed = outcomes.filter(+ (o): o is Extract<HeadlessStartOutcome, { started: false }> => !o.started+ )+ const queuedIds = failed.map((o) => o.id)+ const reason = failed[0]?.reason+ const message =+ base.message.replace(STARTS_ON_VIEW, '').replace(CLOSED_HINT, '') ++ (startedIds.length ? ` — started: ${startedIds.join(', ')}` : '') ++ (queuedIds.length ? ` — queued (${reason}): ${queuedIds.join(', ')}` : '')+ return {+ ...base,+ message,+ result: {+ ...base.result,+ started: startedIds.length > 0,+ startedIds,+ queued: queuedIds.length > 0,+ queuedIds,+ ...(reason ? { reason } : {})+ }+ }+}diff --git a/src/renderer/terminal/launch-command.test.ts b/src/renderer/terminal/launch-command.test.tsindex 3a689e946..351b020cf 100644--- a/src/renderer/terminal/launch-command.test.ts+++ b/src/renderer/terminal/launch-command.test.ts@@ -1,7 +1,7 @@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 { createLaunchWriter, deliverInitialLaunch, hasLaunchWriter, launchCommand, registerLaunchWriter } from './launch-command'import { trustsFreshShell } from '@shared/launch-trust'import { KILL_LINE, WINDOWS_KILL_LINE, VERIFY_TIMEOUT_MS, DELIVERY_ATTEMPTS } from '@shared/command-delivery'@@ -131,6 +131,15 @@ describe('durable launch delivery', () => {second()expect(await launchCommand('node', 'cmd', true)).toBe('cancelled')})+ it('hasLaunchWriter reports a registered writer, per scope, and forgets it on unregister', () => {+ const scope = {}+ expect(hasLaunchWriter('probe')).toBe(false)+ const off = registerLaunchWriter('probe', async () => 'submitted')+ expect(hasLaunchWriter('probe')).toBe(true)+ expect(hasLaunchWriter('probe', scope)).toBe(false)+ off()+ expect(hasLaunchWriter('probe')).toBe(false)+ })})describe('UI initial-command lifecycle', () => {diff --git a/src/renderer/terminal/launch-command.ts b/src/renderer/terminal/launch-command.tsindex ff17c5203..8b91f96dc 100644--- a/src/renderer/terminal/launch-command.ts+++ b/src/renderer/terminal/launch-command.ts@@ -23,6 +23,10 @@ export function registerLaunchWriter(id: string, writer: Writer, scope: object =export function launchCommand(id: string, command: string, manual = false, scope: object = defaultScope): Promise<LaunchOutcome> {return writersFor(scope).get(id)?.(command, manual) ?? Promise.resolve('cancelled')}+/** Is a writer registered for `id` (its PTY is mounted, or parked with the writer alive)? */+export function hasLaunchWriter(id: string, scope: object = defaultScope): boolean {+ return writersFor(scope).has(id)+}export function createLaunchWriter(opts: {claimAttempt(manual: boolean, command: string): Promise<LaunchClaim>diff --git a/src/shared/types.ts b/src/shared/types.tsindex e958ec87a..895b15dc7 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -393,9 +393,10 @@ export interface PendingLaunch {/*** Which core process owns delivery. Absent is the historical renderer-owned path. Server* Edition headless opens stamp `server`, so a connected browser can render the armed state and- * dependency edges without racing the server to type the command into the same pane.+ * dependency edges without racing the server to type the command into the same pane. The+ * desktop's headless start (#925) stamps `core` on its manualOnly write-ahead claim.*/- executor?: 'server'+ executor?: 'server' | 'core'/*** Server-owned dependencies whose first real turn has not been observed yet. A freshly spawned* agent can briefly report `done` while its argv prompt is still booting; that idle blip must not