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(pty): headless taps — persistence probe, output tap, client-0 write/release
review3345bf95b834
diff --git a/src/core/pty-headless-taps.test.ts b/src/core/pty-headless-taps.test.tsnew file mode 100644index 000000000..59dfe7cf6--- /dev/null+++ b/src/core/pty-headless-taps.test.ts@@ -0,0 +1,150 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { IPC } from '../shared/ipc'++/**+ * The core-side io of the headless launcher (#925): an output tap per node, and a write/release+ * pair that acts AS the synthetic client 0 `createHeadless` subscribes. Harness copied from+ * pty-coattach.test.ts: no `init()`, so there is no tmux and every session is a plain shell (its+ * node id lives on `nodeId`, not `persistKey`).+ */++/** One fake pty per spawn, recorded so a test can push output and see what was written. */+interface FakePty {+ onDataCb?: (d: string) => void+ onExitCb?: (e: { exitCode: number }) => void+ writes: string[]+ resizes: Array<{ cols: number; rows: number }>+ paused: boolean+ killed: boolean+}+const spawned: FakePty[] = []++// Pin the persistence backend: `sessionHostSupported()` only asks whether+// out/session-host/host.cjs exists on disk, so whether this suite exercises the mocked+// `node-pty` spawn below or a real session-host shim depended on whether anyone had run+// `npm run build` (or `npm run host:build`). See src/core/__fixtures__/no-session-host.ts.+vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)++vi.mock('node-pty', () => ({+ spawn: (_file: string, _args: string[], _opts: unknown) => {+ const p: FakePty = { writes: [], resizes: [], paused: false, killed: false }+ spawned.push(p)+ return {+ onData: (cb: (d: string) => void) => {+ p.onDataCb = cb+ },+ onExit: (cb: (e: { exitCode: number }) => void) => {+ p.onExitCb = cb+ },+ write: (d: string) => p.writes.push(d),+ resize: (cols: number, rows: number) => p.resizes.push({ cols, rows }),+ pause: () => {+ p.paused = true+ },+ resume: () => {+ p.paused = false+ },+ kill: () => {+ p.killed = true+ },+ pid: 1234+ }+ }+}))++/**+ * A machine with pty devices to spare, always — otherwise the real `/dev` probe makes this suite+ * depend on how many terminals the developer running it has open (see pty-coattach.test.ts).+ */+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++describe('PtyManager headless taps (#925)', () => {+ let fake: FakePlatform++ beforeEach(() => {+ spawned.length = 0+ fake = fakePlatform()+ initPlatform(fake)+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ resetPlatformForTests()+ })++ async function manager() {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.registerIpc()+ return m+ }++ it('onOutput receives flushed output for the node, and unsubscribes cleanly', async () => {+ const m = await manager()+ const r = await m.createHeadless({ cols: 80, rows: 24, persistKey: 'n1' })+ expect(r.sessionId).toBeTruthy()+ const seen: string[] = []+ const off = m.onOutput('n1', (c) => seen.push(c))+ spawned[0].onDataCb?.('hello')+ vi.advanceTimersByTime(50) // past FLUSH_MS+ expect(seen.join('')).toBe('hello')+ off()+ spawned[0].onDataCb?.('again')+ vi.advanceTimersByTime(50)+ expect(seen.join('')).toBe('hello')+ })++ it('writeHeadless writes only when client 0 holds a live session for that node', async () => {+ const m = await manager()+ expect(m.writeHeadless('n1', 'x')).toBe(false) // nothing spawned yet+ await m.createHeadless({ cols: 80, rows: 24, persistKey: 'n1' })+ expect(m.writeHeadless('n1', 'abc')).toBe(true)+ expect(spawned[0].writes).toContain('abc')+ expect(m.writeHeadless('other', 'abc')).toBe(false)+ })++ it('writeHeadless refuses a live session that only a real client attached', async () => {+ const m = await manager()+ await fake.handlers[IPC.ptyCreate](1, { cols: 80, rows: 24, persistKey: 'n1' })+ expect(spawned).toHaveLength(1)+ expect(m.writeHeadless('n1', 'abc')).toBe(false) // client 0 never subscribed+ expect(spawned[0].writes).toEqual([])+ m.releaseHeadless('n1') // not client 0's to drop: the viewer's pty stays attached+ expect(spawned[0].killed).toBe(false)+ })++ it('releaseHeadless drops client 0, after which a headless write is refused', async () => {+ const m = await manager()+ await m.createHeadless({ cols: 80, rows: 24, persistKey: 'n1' })+ m.releaseHeadless('n1')+ // Client 0 was the only subscriber, so the pty client is released (a plain shell dies with it,+ // which is why the launcher gates on persistentSpawnAvailable) and the session is forgotten.+ expect(spawned[0].killed).toBe(true)+ expect(m.writeHeadless('n1', 'abc')).toBe(false)+ expect(spawned[0].writes).not.toContain('abc')+ m.releaseHeadless('n1') // idempotent: no live session, no throw+ })++ it('a throwing output tap does not break delivery to the others', async () => {+ const m = await manager()+ await m.createHeadless({ cols: 80, rows: 24, persistKey: 'n1' })+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const seen: string[] = []+ m.onOutput('n1', () => {+ throw new Error('boom')+ })+ m.onOutput('n1', (c) => seen.push(c))+ spawned[0].onDataCb?.('z')+ vi.advanceTimersByTime(50)+ expect(seen).toEqual(['z'])+ expect(warn).toHaveBeenCalledWith('[pty] output tap failed', 'boom')+ warn.mockRestore()+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 46922b011..a4d3aa438 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -520,6 +520,8 @@ export { findInLoginPath } from './exec-path'/** A UI client: an Electron webContents id or a ServerPlatform uiId. */type ClientId = number+/** The synthetic subscriber of a spawn no viewer initiated (see createHeadless). */+const HEADLESS_CLIENT: ClientId = 0/** A viewer id: which VIEW within one client. `PRIMARY_VIEWER` is the default view — the canvas* node, and every legacy call that omits a viewerId. A second view in the SAME renderer (the@@ -891,6 +893,8 @@ export class PtyManager {private unknownEnds = new Set<string>()/** Shell-owned cleanup runs after end processing and, for session host, its kill acknowledgement. */private sessionEndedListeners = new Set<(persistKey: string) => void>()+ /** Per-node output taps for core consumers (the headless launcher's settle + echo, #925). */+ private outputListeners = new Map<string, Set<(chunk: string) => void>>()/** persistKey (node id) → the co-viewers of a session that was RECYCLED (moved into a worktree),* waiting to be told to restart onto the replacement session. Held — not sent — until that* session is registered (`spawnSession`), so a co-viewer's restart can never win the race and@@ -1991,7 +1995,64 @@ export class PtyManager {* account scoping, project env and ownership recording still run through `create` unchanged.*/createHeadless(options: PtyCreateOptions): Promise<PtyCreateResult> {- return this.create(0, options)+ return this.create(HEADLESS_CLIENT, options)+ }++ /**+ * Would a spawn right now outlive its client? The same test `spawnNew` applies: tmux found and+ * enabled, or the session-host backend (Windows). The desktop headless launcher refuses without+ * it: it releases its client after delivery, and releasing a plain shell kills it (#925).+ */+ persistentSpawnAvailable(): boolean {+ if (this.tmuxPath && this.getSettings().tmuxEnabled) return true+ return this.hostBackendEligible()+ }++ /** Subscribe to a node's output as core sees it (after buffering, before fan-out). */+ onOutput(persistKey: string, cb: (chunk: string) => void): () => void {+ let set = this.outputListeners.get(persistKey)+ if (!set) {+ set = new Set()+ this.outputListeners.set(persistKey, set)+ }+ set.add(cb)+ return () => {+ const s = this.outputListeners.get(persistKey)+ if (!s) return+ s.delete(cb)+ if (!s.size) this.outputListeners.delete(persistKey)+ }+ }++ /** The live session a node id names: the persist index first, then any session spawned for it+ * (a plain shell carries the id only as `nodeId`). */+ private liveSessionForNode(persistKey: string): [string, Session] | undefined {+ const indexed = this.byPersistKey.get(persistKey)+ const hit = indexed ? this.sessions.get(indexed) : undefined+ if (indexed && hit) return [indexed, hit]+ for (const [id, s] of this.sessions) {+ if (s.persistKey === persistKey || s.nodeId === persistKey) return [id, s]+ }+ return undefined+ }++ /**+ * Type into a node's pane AS the headless client. False unless client 0 subscribes to a live+ * session for that node, so a launch can never type into a pty it did not attach. Writes the+ * process directly rather than through `write()`: the synthetic client is not a person, so it+ * must not light the team typing badge.+ */+ writeHeadless(persistKey: string, data: string): boolean {+ const live = this.liveSessionForNode(persistKey)+ if (!live || !this.subscribes(HEADLESS_CLIENT, live[0])) return false+ live[1].proc.write(data)+ return true+ }++ /** Drop the headless client. The tmux session keeps running, exactly as `kill()` always leaves it. */+ releaseHeadless(persistKey: string): void {+ const live = this.liveSessionForNode(persistKey)+ if (live) this.kill(HEADLESS_CLIENT, live[0])}private async create(clientId: ClientId, options: PtyCreateOptions): Promise<PtyCreateResult> {@@ -3822,6 +3883,17 @@ export class PtyManager {session.buf = []session.bufBytes = 0session.onData?.(data) // relay host sink (unchanged)+ const tapKey = session.persistKey ?? session.nodeId+ const taps = tapKey ? this.outputListeners.get(tapKey) : undefined+ if (taps) {+ for (const cb of [...taps]) {+ try {+ cb(data)+ } catch (error) {+ console.warn('[pty] output tap failed', error instanceof Error ? error.message : String(error))+ }+ }+ }const channel = IPC.ptyData(sessionId)// One send per distinct client — a client's views share the per-client `pty:data:<id>` channel.for (const client of this.clientsOf(session)) this.send(client, channel, data)diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.tsindex 46521ce70..1ec193f0d 100644--- a/src/core/pty-single-user.test.ts+++ b/src/core/pty-single-user.test.ts@@ -888,4 +888,21 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =expect(again.sessionId).not.toBe(sessionId)expect(again.fresh).toBe(true)})++ // ── persistentSpawnAvailable (#925) ────────────────────────────────────────────────────────+ // Nested here, not at top level: `tmuxManager()` and the platform/userData harness it needs are+ // scoped to this describe.+ describe('persistentSpawnAvailable (#925)', () => {+ it('is true with tmux found and enabled', async () => {+ const m = await tmuxManager()+ expect(m.persistentSpawnAvailable()).toBe(true)+ })+ it('is false when tmux persistence is switched off (and no session-host applies on this platform)', async () => {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.init(() => ({ ...DEFAULT_SETTINGS, tmuxEnabled: false }))+ m.registerIpc()+ expect(m.persistentSpawnAvailable()).toBe(false)+ })+ })})