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): control-mode client over pipes — zero pty devices
enese99343f25ceb
diff --git a/src/core/tmux-control-client.test.ts b/src/core/tmux-control-client.test.tsnew file mode 100644index 000000000..a6823a041--- /dev/null+++ b/src/core/tmux-control-client.test.ts@@ -0,0 +1,281 @@+import { describe, it, expect, vi } from 'vitest'+import { ControlModeClient, MAX_PENDING_BYTES, type ControlSpawn } from './tmux-control-client'++/**+ * The client is the only place that owns a tmux control-mode PROCESS, so everything worth asserting+ * here is a lifecycle promise: what gets spawned, that bytes arrive undamaged, that replies pair with+ * the right command, and that a dead or wedged peer never leaves a caller hanging forever.+ */++/** One fake child per spawn: tests drive stdout with `feed`, then read back what was written. */+interface FakeChild {+ writes: string[]+ killed: number+ exit(code: number | null): void+ feed(latin1: string): void+}++class FakeControlSpawn implements ControlSpawn {+ calls: Array<{ bin: string; args: string[] }> = []+ children: FakeChild[] = []+ spawn(bin: string, args: string[]) {+ this.calls.push({ bin, args })+ let onData: ((b: Buffer) => void) | undefined+ let onExit: ((code: number | null) => void) | undefined+ const child: FakeChild = {+ writes: [],+ killed: 0,+ exit: (code) => onExit?.(code),+ // Buffer.from(s, 'latin1') is the byte-exact transport the real spawner hands us.+ feed: (s) => onData?.(Buffer.from(s, 'latin1'))+ }+ this.children.push(child)+ return {+ stdin: {+ write: (s: string) => {+ child.writes.push(s)+ }+ },+ stdout: {+ on: (_ev: 'data', cb: (b: Buffer) => void) => {+ onData = cb+ }+ },+ on: (_ev: 'exit', cb: (code: number | null) => void) => {+ onExit = cb+ },+ kill: () => {+ child.killed+++ }+ }+ }+ get only(): FakeChild {+ return this.children[0]+ }+}++/** A started client plus its fake, wired with recording callbacks — the shape every test needs. */+function makeClient(over: Partial<{ onOutput: (d: string) => void; onExit: () => void }> = {}) {+ const spawner = new FakeControlSpawn()+ const out: string[] = []+ const exits: number[] = []+ const client = new ControlModeClient({+ tmuxBin: '/opt/homebrew/bin/tmux',+ socket: 'node-terminal',+ sessionName: 'nt-term-1',+ onOutput: over.onOutput ?? ((d) => out.push(d)),+ onExit: over.onExit ?? (() => exits.push(1)),+ spawner+ })+ client.start()+ return { client, spawner, out, exits, child: spawner.only }+}++/** tmux answers `%begin/%end`; ts and num must repeat in the terminator or the codec keeps the block open. */+function reply(num: number, body: string[] = [], ok = true): string {+ const term = ok ? '%end' : '%error'+ return [`%begin 1700 ${num} 0`, ...body, `${term} 1700 ${num} 0`, ''].join('\n')+}++describe('ControlModeClient.start', () => {+ it('spawns tmux in control mode on the session socket', () => {+ const { spawner } = makeClient()+ expect(spawner.calls).toEqual([+ {+ bin: '/opt/homebrew/bin/tmux',+ args: ['-L', 'node-terminal', '-C', 'attach-session', '-t', 'nt-term-1']+ }+ ])+ })+ it('is alive once started and not before', () => {+ const spawner = new FakeControlSpawn()+ const client = new ControlModeClient({+ tmuxBin: 'tmux',+ socket: 's',+ sessionName: 'nt-term-1',+ onOutput: () => {},+ onExit: () => {},+ spawner+ })+ expect(client.alive).toBe(false)+ client.start()+ expect(client.alive).toBe(true)+ })+})++describe('ControlModeClient output', () => {+ it('delivers %output payloads to onOutput with the octal escapes decoded', () => {+ const { child, out } = makeClient()+ child.feed('%output %1 hi\\015\\012')+ child.feed('there\\012\n')+ expect(out).toEqual(['hi\r\nthere\n'])+ })+ it('re-assembles a UTF-8 character split across two %output lines', () => {+ // The transport is latin1 (bytes >= 0x80 ride RAW and unescaped), so `ç` arrives as the two+ // chars \xc3 \xa7 — possibly in different lines. A per-byte utf8 decode would emit two U+FFFDs.+ const { child, out } = makeClient()+ child.feed('%output %1 \xc3\n')+ child.feed('%output %1 \xa7\n')+ expect(out.join('')).toBe('ç')+ })+ it('ignores notifications that are neither output nor replies', () => {+ const { child, out } = makeClient()+ child.feed('%session-changed $0 nt-term-1\n%window-add @2\n')+ expect(out).toEqual([])+ })+})++describe('ControlModeClient.sendKeys', () => {+ it('writes the hex send-keys line and resolves true on an ok reply', async () => {+ const { client, child } = makeClient()+ const p = client.sendKeys('ls\n')+ expect(child.writes).toEqual(['send-keys -t nt-term-1 -H 6c 73 0a\n'])+ child.feed(reply(1))+ await expect(p).resolves.toBe(true)+ })+ it('resolves false when tmux answers %error', async () => {+ const { client, child } = makeClient()+ const p = client.sendKeys('x')+ child.feed(reply(1, ["can't find pane"], false))+ await expect(p).resolves.toBe(false)+ })+ it('can target another session on the same server', async () => {+ const { client, child } = makeClient()+ const p = client.sendKeys('x', 'nt-term-9')+ expect(child.writes).toEqual(['send-keys -t nt-term-9 -H 78\n'])+ child.feed(reply(1))+ await expect(p).resolves.toBe(true)+ })+})++describe('ControlModeClient.command', () => {+ it('resolves with the reply body', async () => {+ const { client, child } = makeClient()+ const p = client.command('list-panes')+ expect(child.writes).toEqual(['list-panes\n'])+ child.feed(reply(1, ['%1: [80x24]']))+ await expect(p).resolves.toEqual({ ok: true, body: ['%1: [80x24]'] })+ })+ it('pairs overlapping commands with replies in FIFO arrival order', async () => {+ // Control mode answers in order and the reply carries no correlation to the command text, so+ // arrival order IS the correlation. Getting this wrong silently swaps two callers' answers.+ const { client, child } = makeClient()+ const first = client.command('display -p #{pane_width}')+ const second = client.command('display -p #{pane_height}')+ expect(child.writes).toEqual(['display -p #{pane_width}\n', 'display -p #{pane_height}\n'])+ child.feed(reply(1, ['80']))+ child.feed(reply(2, ['24']))+ expect(await first).toEqual({ ok: true, body: ['80'] })+ expect(await second).toEqual({ ok: true, body: ['24'] })+ })+ it('rejects instead of hanging when the client is not running', async () => {+ const spawner = new FakeControlSpawn()+ const client = new ControlModeClient({+ tmuxBin: 'tmux',+ socket: 's',+ sessionName: 'nt-term-1',+ onOutput: () => {},+ onExit: () => {},+ spawner+ })+ await expect(client.command('list-panes')).rejects.toThrow(/not running/)+ })+})++describe('ControlModeClient exit', () => {+ it('fires onExit once, rejects pending commands and stops being alive', async () => {+ const onExit = vi.fn()+ const { client, child } = makeClient({ onExit })+ const pending = client.command('list-panes')+ child.exit(0)+ child.exit(0) // a second exit event must not double-notify the owner+ expect(onExit).toHaveBeenCalledTimes(1)+ expect(client.alive).toBe(false)+ await expect(pending).rejects.toThrow(/exited/)+ })+ it('treats a %exit notification as the end of the client', async () => {+ const onExit = vi.fn()+ const { client, child } = makeClient({ onExit })+ const pending = client.command('list-panes')+ child.feed('%exit server exited\n')+ expect(onExit).toHaveBeenCalledTimes(1)+ expect(client.alive).toBe(false)+ expect(child.killed).toBe(1)+ await expect(pending).rejects.toThrow(/exited/)+ })+ it('kills a peer that floods the stream without ever completing an event', async () => {+ // The codec buffers an unterminated line and an unterminated %begin block FOREVER; a peer that+ // loses a terminator would grow the heap until the app dies. Past the cap we call it broken.+ const onExit = vi.fn()+ const { client, child } = makeClient({ onExit })+ const pending = client.command('list-panes')+ child.feed('%begin 1700 1 0\n')+ child.feed('x'.repeat(MAX_PENDING_BYTES + 1))+ expect(child.killed).toBe(1)+ expect(onExit).toHaveBeenCalledTimes(1)+ expect(client.alive).toBe(false)+ await expect(pending).rejects.toThrow(/wedged|exited/)+ })+ it('does not count healthy traffic towards the flood cap', () => {+ const { client, child } = makeClient()+ const line = `%output %1 ${'x'.repeat(1000)}\n`+ for (let i = 0; i < Math.ceil(MAX_PENDING_BYTES / line.length) + 10; i++) child.feed(line)+ expect(client.alive).toBe(true)+ expect(child.killed).toBe(0)+ })+})++describe('ControlModeClient with the real child_process spawner', () => {+ it('reports a tmux binary that cannot be spawned as an exit', async () => {+ // The default spawner is otherwise untested, and ENOENT is its nastiest path: Node emits 'error'+ // (which THROWS if unhandled) and may never emit 'exit', so a client without that wiring would+ // both crash the app and stay "alive" with every command hanging forever.+ let resolveExit: () => void+ const exited = new Promise<void>((r) => (resolveExit = r))+ const client = new ControlModeClient({+ tmuxBin: '/nonexistent/tmux-does-not-exist',+ socket: 'node-terminal',+ sessionName: 'nt-term-1',+ onOutput: () => {},+ onExit: () => resolveExit()+ })+ client.start()+ await exited+ expect(client.alive).toBe(false)+ await expect(client.command('list-panes')).rejects.toThrow(/not running/)+ })+})++describe('ControlModeClient.dispose', () => {+ it('detaches politely, then kills', () => {+ const { client, child } = makeClient()+ client.dispose()+ expect(child.writes).toEqual(['detach-client\n'])+ expect(child.killed).toBe(1)+ expect(client.alive).toBe(false)+ })+ it('is idempotent', () => {+ const { client, child } = makeClient()+ client.dispose()+ client.dispose()+ expect(child.writes).toEqual(['detach-client\n'])+ expect(child.killed).toBe(1)+ })+ it('rejects pending commands but does not report an unexpected exit', async () => {+ // A swap-out (Task 3) disposes the shadow on purpose; onExit means "the client died on us" and+ // firing it here would make the owner re-attach the very shadow it just retired.+ const onExit = vi.fn()+ const { client, child } = makeClient({ onExit })+ const pending = client.command('list-panes')+ client.dispose()+ child.exit(0)+ expect(onExit).not.toHaveBeenCalled()+ await expect(pending).rejects.toThrow(/disposed/)+ })+ it('stops delivering output after disposal', () => {+ const { client, child, out } = makeClient()+ client.dispose()+ child.feed('%output %1 late\n')+ expect(out).toEqual([])+ })+})diff --git a/src/core/tmux-control-client.ts b/src/core/tmux-control-client.tsnew file mode 100644index 000000000..820ca02fe--- /dev/null+++ b/src/core/tmux-control-client.ts@@ -0,0 +1,202 @@+// A tmux control-mode (`-C`) client over plain pipes: process lifecycle + command/reply correlation+// on top of the pure codec in tmux-control.ts. The point of the whole exercise is the pty device it+// does NOT hold — `tmux -C attach-session` streams a session's bytes and accepts `send-keys` while+// allocating zero pty devices, which is what lets an unwatched session stay observable for free.+//+// Electron-free by design (src/core is shared with the server edition): the only host dependency is+// `child_process.spawn`, and it sits behind the `ControlSpawn` seam so tests drive a fake instead.++import { spawn as nodeSpawn } from 'child_process'+import { StringDecoder } from 'string_decoder'+import { createControlDecoder, encodeSendKeysHex, type ControlEvent } from './tmux-control'++/**+ * The child-process seam. Deliberately the smallest surface the client needs — stdout is handed over+ * as raw Buffers (NEVER a utf8-decoded string; see the ENCODING note in tmux-control.ts) and stderr+ * is not part of the contract at all.+ */+export interface ControlSpawn {+ spawn(+ bin: string,+ args: string[]+ ): {+ stdin: { write(s: string): void }+ stdout: { on(ev: 'data', cb: (b: Buffer) => void): void }+ on(ev: 'exit', cb: (code: number | null) => void): void+ kill(): void+ }+}++/**+ * How much stream we accept without the codec completing a single event before we declare the peer+ * broken. The codec buffers a partial line, and an open `%begin` block's body, without bound — a+ * tmux that never sends the matching `%end` (or a wedged pipe that never sends a newline) would grow+ * the heap until the app dies. 8 MiB is orders of magnitude past any reply we issue, so hitting it+ * means "wedged", not "busy": we tear the client down exactly as if the process had exited.+ */+export const MAX_PENDING_BYTES = 8 * 1024 * 1024++/** Real `child_process` wiring. stderr is dropped: nothing reads it, and an unread pipe can block. */+const realSpawner: ControlSpawn = {+ spawn(bin, args) {+ const cp = nodeSpawn(bin, args, { stdio: ['pipe', 'pipe', 'ignore'] })+ // An unhandled 'error' on a child or its pipes THROWS. Both are reachable in normal operation —+ // a missing/unrunnable tmux binary (ENOENT), and an EPIPE from writing to a client that just+ // died — and neither may take the app down. The child's 'error' doubles as an exit report,+ // because Node does not promise an 'exit' event for a process that never spawned.+ cp.stdin?.on('error', () => {})+ cp.stdout?.on('error', () => {})+ return {+ // Commands are ASCII, but latin1 keeps the write path byte-exact for anything that is not.+ stdin: { write: (s: string) => void cp.stdin?.write(s, 'latin1') },+ stdout: { on: (_ev, cb) => void cp.stdout?.on('data', cb) },+ on: (_ev, cb) => {+ cp.on('exit', cb)+ cp.on('error', () => cb(null))+ },+ kill: () => void cp.kill()+ }+ }+}++interface Pending {+ resolve(r: { ok: boolean; body: string[] }): void+ reject(e: Error): void+}++export interface ControlModeClientOpts {+ tmuxBin: string+ socket: string+ sessionName: string+ /** Pane bytes, UTF-8 decoded and re-assembled across chunk/line boundaries. */+ onOutput(data: string): void+ /** The client died on its own (process exit, `%exit`, or wedged peer). Never fires after dispose. */+ onExit(): void+ spawner?: ControlSpawn+}++export class ControlModeClient {+ private readonly opts: ControlModeClientOpts+ private readonly spawner: ControlSpawn+ private readonly decoder = createControlDecoder()+ /** One UTF-8 decoder per pane: interleaving panes through a shared one would split characters. */+ private readonly utf8 = new Map<string, StringDecoder>()+ /** Control mode answers commands IN ORDER, so arrival order is the only correlation there is. */+ private readonly pending: Pending[] = []+ private proc: ReturnType<ControlSpawn['spawn']> | null = null+ private pendingBytes = 0+ private gone = false+ private disposed = false++ constructor(opts: ControlModeClientOpts) {+ this.opts = opts+ this.spawner = opts.spawner ?? realSpawner+ }++ /** True between `start()` and the client's death or disposal. */+ get alive(): boolean {+ return this.proc !== null && !this.gone && !this.disposed+ }++ /** Attach: `tmux -L <socket> -C attach-session -t <session>`. Calling twice is a no-op. */+ start(): void {+ if (this.proc || this.disposed) return+ const args = ['-L', this.opts.socket, '-C', 'attach-session', '-t', this.opts.sessionName]+ this.proc = this.spawner.spawn(this.opts.tmuxBin, args)+ this.proc.stdout.on('data', (b) => this.onChunk(b))+ this.proc.on('exit', () => this.die('control-mode client exited'))+ }++ /** Type `data` into `target` (default: our own session). Resolves false when tmux says `%error`. */+ async sendKeys(data: string, target = this.opts.sessionName): Promise<boolean> {+ const { ok } = await this.command(encodeSendKeysHex(target, data))+ return ok+ }++ /** Run one control-mode command line. Rejects if the client is not running or dies while waiting. */+ command(line: string): Promise<{ ok: boolean; body: string[] }> {+ if (!this.alive || !this.proc) {+ return Promise.reject(new Error('tmux control-mode client is not running'))+ }+ const proc = this.proc+ return new Promise((resolve, reject) => {+ // Write BEFORE queueing: a throwing write rejects this promise, and a resolver left in the+ // FIFO for a command tmux never saw would pair every later reply with the wrong caller.+ // (Safe ordering — the reply cannot arrive before this synchronous block ends.)+ proc.stdin.write(`${line}\n`)+ this.pending.push({ resolve, reject })+ })+ }++ /** Detach politely, then kill. Idempotent, and never reports an exit the caller asked for. */+ dispose(): void {+ if (this.disposed) return+ this.disposed = true+ const proc = this.proc+ if (proc && !this.gone) {+ // `detach-client` lets tmux drop the client cleanly; the kill is the backstop, not the plan.+ try {+ proc.stdin.write('detach-client\n')+ } catch {+ /* pipe already gone — the kill below is what matters */+ }+ try {+ proc.kill()+ } catch {+ /* already dead */+ }+ }+ this.rejectPending(new Error('tmux control-mode client was disposed'))+ }++ private onChunk(chunk: Buffer): void {+ if (!this.alive) return+ // latin1 is byte-exact: tmux escapes only bytes < 0x20 and the backslash, so anything >= 0x80+ // travels raw and a utf8 decode HERE would mangle it beyond recovery.+ const text = chunk.toString('latin1')+ this.pendingBytes += text.length+ if (this.pendingBytes > MAX_PENDING_BYTES) {+ this.die(`tmux control-mode client wedged (${MAX_PENDING_BYTES} bytes, no complete event)`)+ return+ }+ const events = this.decoder.push(text)+ if (events.length > 0) this.pendingBytes = 0+ for (const ev of events) {+ this.dispatch(ev)+ if (!this.alive) return+ }+ }++ private dispatch(ev: ControlEvent): void {+ if (ev.kind === 'output') {+ // The codec hands back one CHAR per byte; re-assemble to a Buffer and decode UTF-8 with a+ // streaming decoder so a character split across %output lines survives.+ let dec = this.utf8.get(ev.paneId)+ if (!dec) this.utf8.set(ev.paneId, (dec = new StringDecoder('utf8')))+ const text = dec.write(Buffer.from(ev.data, 'latin1'))+ if (text) this.opts.onOutput(text)+ } else if (ev.kind === 'reply') {+ this.pending.shift()?.resolve({ ok: ev.ok, body: ev.body })+ } else if (ev.kind === 'exited') {+ this.die('tmux control-mode client exited')+ }+ // 'other' notifications (%session-changed, %window-add, …) carry nothing this client acts on.+ }++ /** The client died on us: notify once, fail everyone waiting, and make sure the process is gone. */+ private die(why: string): void {+ if (this.gone || this.disposed) return+ this.gone = true+ try {+ this.proc?.kill()+ } catch {+ /* already dead */+ }+ this.rejectPending(new Error(why))+ this.opts.onExit()+ }++ private rejectPending(err: Error): void {+ while (this.pending.length > 0) this.pending.shift()?.reject(err)+ }+}