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
fix(pty): bound the boot-path synchronous tmux calls
Brandon Bridgese6a97055c875
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2487903a9..dfd213f40 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -603,6 +603,18 @@ interferes; status bar off, **mouse on**, 50k history, `set-clipboard on` + `tersessions survive when no client is attached. `src/shared/ssh.ts`'s `remoteTmuxConf` is the sameconfig for an SSH project's remote tmux.+**Every synchronous tmux call on main is bounded (`TMUX_BOOT_CMD_TIMEOUT_MS`, 2 s, via+`PtyManager.runTmuxSync`).** `ensureTmux`'s `source-file` runs before the first window exists, and+`ensureUpdateEnvKeys`' `show-options` / `set-option` run on a spawn; unbounded, a server that accepts+the connection and never answers held main for the wedge's whole lifetime (audit main-5: 4.05 s in+the repro, i.e. forever against a server that never recovers). The bound kills only our short-lived+client (SIGKILL, so one that ignores SIGTERM cannot keep `execFileSync` waiting), never the server.+A timeout is `console.warn`ed and fails open (tmux stays resolved; the spawn goes ahead); "no server+yet" stays silent, as it always was. A timeout also ends the rest of that call's tmux work — the+next `set-option` would only wait out the same wedge. Proven against a real client in+`pty-tmux-wedged.realtmux.test.ts`. A new sync tmux call goes through `runTmuxSync`, not a bare+`execFileSync`.+**Every REMOTE tmux invocation starts with `remoteTmuxPathPrologue()`** (`shared/ssh.ts` — PATH**append**: `/opt/homebrew/bin`, `/usr/local/bin`, `/opt/local/bin`, `$HOME/.local/bin`): an sshexec channel gets a non-login shell, and on a macOS host Homebrew's `shellenv` lives indiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 8d810e3f9..5c7dc80ed 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -963,6 +963,11 @@ shipped: managed-account `CLAUDE_CONFIG_DIR` leaked into system-account sessionsenv either joins `ACCOUNT_SCOPE_UPDATE_ENV` / the gateway list, or rides `-e` — and gets areal-tmux test (`account-env.realtmux.test.ts` is the pattern).+**A synchronous tmux call on main always has a timeout.** Use `PtyManager.runTmuxSync` (2 s,+`TMUX_BOOT_CMD_TIMEOUT_MS`), never a bare `execFileSync` on the tmux socket: one runs before the+first window exists, and a wedged server held an unbounded call for as long as it stayed wedged+(4.05 s in the audit repro, main-5). Warn on a timeout and fail open; keep "no server yet" silent.+**The same goes for the CWD: a tmux client never runs in the node's directory.** The server keepsthe cwd of the client that started it, and from tmux 3.7 a new pane's `-c` is silently dropped oncethat directory is deleted — every new terminal then opens in the deleted dir (issue #1131, measureddiff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex f3bb53afc..be5c66902 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -302,6 +302,22 @@ const PROJECT_OVERRIDES_TIMEOUT_MS = 2_000*/const PROBE_TIMEOUT_MS = 6_000+/**+ * Ceiling for the SYNCHRONOUS tmux calls on the boot/spawn path (`ensureTmux`'s `source-file`,+ * `ensureUpdateEnvKeys`' `show-options` / `set-option`). They block the main thread, and one runs+ * before `createWindow`: against a tmux server that accepts the connection but never answers+ * (stuck on a blocked client write, or SIGSTOPped) an unbounded call froze main with no window+ * and no error — the 2026-10 audit (main-5) reproduced a client held 4.05 s, exactly the wedged+ * listener's lifetime, i.e. forever against a server that never recovers. A healthy server+ * answers these in milliseconds, so 2 s only ever fires on a wedge. `vm_stat` already has 5 s.+ */+export const TMUX_BOOT_CMD_TIMEOUT_MS = 2_000++/** Outcome of one bounded synchronous tmux call. `timeout` is a wedged server and is LOGGED;+ * `failed` is the ordinary "no server running yet" exit and stays silent, as it always was.+ * Callers fail open on both — neither is `ok: true` with empty output. */+type TmuxSyncResult = { ok: true; stdout: string } | { ok: false; reason: 'timeout' | 'failed' }+/*** `execFile`, bounded. Wrapped HERE rather than at the call sites so a new one cannot forget: the* bug this exists for was one unbounded call out of twenty, and the next unbounded call would be@@ -2030,12 +2046,39 @@ export class PtyManager {// The tmux server outlives the app, so it won't re-read `-f` on relaunch. Push the// (possibly updated) config into a running server now so new bindings apply immediately;// a no-op error when no server exists yet (the next session loads it fresh via `-f`).+ // Bounded: this runs before the first window exists (audit main-5). A timeout keeps tmux+ // resolved — only the config push is skipped, and runTmuxSync has already logged it.+ this.runTmuxSync(['source-file', this.confPath], false)+ }++ /** Per-instance so a test can prove the bound in milliseconds; production never changes it. */+ tmuxBootCmdTimeoutMs = TMUX_BOOT_CMD_TIMEOUT_MS++ /**+ * One synchronous tmux call on our socket, bounded by `tmuxBootCmdTimeoutMs`. SIGKILL, not the+ * default SIGTERM: a wedged client that ignores or never services SIGTERM would keep+ * `execFileSync` waiting on its exit, which is the very hang this bound exists to end. The+ * signal goes to the short-lived tmux CLIENT we just spawned — never to the server, which holds+ * every session and is not touched.+ */+ private runTmuxSync(args: string[], capture: boolean): TmuxSyncResult {+ if (!this.tmuxPath) return { ok: false, reason: 'failed' }try {- execFileSync(this.tmuxPath, ['-L', TMUX_SOCKET, 'source-file', this.confPath], {- stdio: 'ignore'+ const out = execFileSync(this.tmuxPath, ['-L', TMUX_SOCKET, ...args], {+ stdio: capture ? ['ignore', 'pipe', 'ignore'] : 'ignore',+ timeout: this.tmuxBootCmdTimeoutMs,+ killSignal: 'SIGKILL'})- } catch {- // no server running yet — ignore+ return { ok: true, stdout: out ? out.toString() : '' }+ } catch (error) {+ if ((error as { code?: unknown } | null)?.code === 'ETIMEDOUT') {+ console.warn(+ `[pty] tmux ${args[0]} on -L ${TMUX_SOCKET} timed out after ${this.tmuxBootCmdTimeoutMs}ms` ++ ' — the tmux server is not answering; continuing without it'+ )+ return { ok: false, reason: 'timeout' }+ }+ return { ok: false, reason: 'failed' }}}@@ -2062,32 +2105,26 @@ export class PtyManager {)if (!wanted.length) returnif (!this.updateEnvKeys) {+ const shown = this.runTmuxSync(['show-options', '-g', 'update-environment'], true)+ // A wedged server: stop here. Every `set-option` below would wait out the same bound — one+ // stall per new name on the spawn path (audit main-5) — and leaving the cache unset lets a+ // later spawn probe a recovered server properly. The spawn itself goes ahead.+ if (!shown.ok && shown.reason === 'timeout') returnthis.updateEnvKeys = new Set(MODEL_GATEWAY_ENV_KEYS)- try {- const out = execFileSync(- this.tmuxPath,- ['-L', TMUX_SOCKET, 'show-options', '-g', 'update-environment'],- { stdio: ['ignore', 'pipe', 'ignore'] }- ).toString()- for (const m of out.matchAll(/update-environment\[\d+\]\s+(\S+)/g)) {+ // `failed` is "no server yet" — the conf list is what a fresh server will have.+ if (shown.ok) {+ for (const m of shown.stdout.matchAll(/update-environment\[\d+\]\s+(\S+)/g)) {this.updateEnvKeys.add(m[1])}- } catch {- /* no server yet — the conf list is what a fresh server will have */}}for (const name of wanted) {if (this.updateEnvKeys.has(name)) continue- try {- execFileSync(- this.tmuxPath,- ['-L', TMUX_SOCKET, 'set-option', '-ga', 'update-environment', name],- { stdio: 'ignore' }- )- this.updateEnvKeys.add(name)- } catch {- /* no server yet — fresh-server sessions inherit the client env directly */- }+ const set = this.runTmuxSync(['set-option', '-ga', 'update-environment', name], false)+ if (set.ok) this.updateEnvKeys.add(name)+ // One timeout per call, not per name: the rest would only wait out the same wedge.+ else if (set.reason === 'timeout') break+ /* `failed`: no server yet — fresh-server sessions inherit the client env directly */}}diff --git a/src/core/pty-tmux-boot-timeout.test.ts b/src/core/pty-tmux-boot-timeout.test.tsnew file mode 100644index 000000000..ef1974e55--- /dev/null+++ b/src/core/pty-tmux-boot-timeout.test.ts@@ -0,0 +1,138 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import fs from 'fs'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'++/**+ * THE BOOT-PATH tmux CALLS ARE BOUNDED (audit main-5).+ *+ * `ensureTmux`'s `source-file` runs on the main thread before the first window exists, and+ * `ensureUpdateEnvKeys`' `show-options` / `set-option` run on a spawn. All three were+ * `execFileSync` with no timeout, so a tmux server that accepts the connection and never answers+ * held main for as long as it stayed wedged (4.05 s in the audit's repro — the listener's whole+ * lifetime). These pin the contract with an injected `execFileSync`: every call carries the bound,+ * a timeout is WARNED and fails open, and the ordinary "no server yet" failure stays as silent as+ * it always was. The real-tmux proof is `pty-tmux-wedged.realtmux.test.ts`.+ */++type ExecCall = { args: string[]; opts: { timeout?: number; killSignal?: string } }+const execState = vi.hoisted(() => ({+ calls: [] as ExecCall[],+ /** Per-subcommand behaviour: a string is stdout, an object is thrown. */+ reply: new Map<string, string | object>()+}))+vi.mock('child_process', async (importOriginal) => {+ const actual = await importOriginal<typeof import('child_process')>()+ const execFileSync = (_file: string, args: string[], opts: ExecCall['opts']): Buffer => {+ execState.calls.push({ args, opts })+ const r = execState.reply.get(args[2])+ if (r !== undefined && typeof r !== 'string') throw r+ return Buffer.from(r ?? '')+ }+ return { ...actual, default: { ...actual, execFileSync }, execFileSync }+})+vi.mock('./exec-path', () => ({+ resolveShellPath: () => Promise.resolve(null),+ shellPathNow: () => undefined,+ findInPathString: () => null,+ findExecutableSync: () => null+}))+vi.mock('node-pty', () => ({ spawn: () => ({ onData: () => {}, onExit: () => {}, kill: () => {} }) }))+// Hermetic resolution (see pty-single-user.test.ts, issue #160): tmux is "installed", nothing real runs.+vi.mock('./tmux-hint', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./tmux-hint')>()),+ findFixedTmux: () => '/usr/bin/tmux'+}))++/** The shape Node gives `execFileSync` when `timeout` fires (measured: code ETIMEDOUT, status null). */+const TIMED_OUT = Object.assign(new Error('spawnSync /usr/bin/tmux ETIMEDOUT'), {+ code: 'ETIMEDOUT',+ signal: 'SIGKILL',+ status: null+})+/** The shape of "no server running on this socket": a plain non-zero exit. */+const NO_SERVER = Object.assign(new Error('Command failed'), { status: 1, signal: null })++const callsFor = (verb: string): ExecCall[] => execState.calls.filter((c) => c.args[2] === verb)++async function boot() {+ const { PtyManager, TMUX_BOOT_CMD_TIMEOUT_MS } = await import('./pty-manager')+ const mgr = new PtyManager()+ mgr.init(() => ({ tmuxEnabled: true, tmuxScrollback: 10_000 }) as never)+ const ensureUpdateEnvKeys = (names: string[]): void =>+ (mgr as unknown as { ensureUpdateEnvKeys: (n: string[]) => void }).ensureUpdateEnvKeys(names)+ return { mgr, ensureUpdateEnvKeys, TMUX_BOOT_CMD_TIMEOUT_MS }+}++describe('boot-path tmux calls under a wedged server', () => {+ let warn: ReturnType<typeof vi.spyOn>+ beforeEach(() => {+ execState.calls.length = 0+ execState.reply.clear()+ initPlatform(fakePlatform())+ // ensureTmux writes the generated tmux.conf into userDataDir; the fake's dir does not exist.+ vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ })+ afterEach(() => {+ vi.restoreAllMocks()+ resetPlatformForTests()+ })++ it('source-file carries the bound and a SIGKILL, and a healthy server is unchanged', async () => {+ const { mgr, TMUX_BOOT_CMD_TIMEOUT_MS } = await boot()+ const [push] = callsFor('source-file')+ expect(push.args.slice(0, 3)).toEqual(['-L', 'node-terminal', 'source-file'])+ expect(push.opts.timeout).toBe(TMUX_BOOT_CMD_TIMEOUT_MS)+ expect(push.opts.killSignal).toBe('SIGKILL')+ expect(mgr.getTmuxBin()).toBe('/usr/bin/tmux')+ expect(warn).not.toHaveBeenCalled()+ })++ it('a source-file timeout is logged and tmux stays resolved (fail open)', async () => {+ execState.reply.set('source-file', TIMED_OUT)+ const { mgr } = await boot()+ expect(mgr.getTmuxBin()).toBe('/usr/bin/tmux')+ expect(warn).toHaveBeenCalledTimes(1)+ expect(String(warn.mock.calls[0][0])).toMatch(/tmux source-file .*timed out after 2000ms/)+ })++ it('"no server yet" stays silent, exactly as before', async () => {+ execState.reply.set('source-file', NO_SERVER)+ execState.reply.set('show-options', NO_SERVER)+ execState.reply.set('set-option', NO_SERVER)+ const { mgr, ensureUpdateEnvKeys } = await boot()+ ensureUpdateEnvKeys(['MY_KEY'])+ expect(mgr.getTmuxBin()).toBe('/usr/bin/tmux')+ expect(callsFor('set-option')).toHaveLength(1)+ expect(warn).not.toHaveBeenCalled()+ })++ it('a show-options timeout skips every set-option and re-probes on the next spawn', async () => {+ const { ensureUpdateEnvKeys } = await boot()+ execState.reply.set('show-options', TIMED_OUT)+ ensureUpdateEnvKeys(['KEY_A', 'KEY_B', 'KEY_C'])+ // One stall, not 1 + 3: the set-options would only wait out the same wedge.+ expect(callsFor('show-options')).toHaveLength(1)+ expect(callsFor('set-option')).toHaveLength(0)+ expect(warn).toHaveBeenCalledTimes(1)++ // The server recovers: the cache was left unset, so the next spawn probes it properly.+ execState.reply.set('show-options', 'update-environment[0] KEY_A\n')+ ensureUpdateEnvKeys(['KEY_A', 'KEY_B'])+ expect(callsFor('show-options')).toHaveLength(2)+ expect(callsFor('set-option').map((c) => c.args[5])).toEqual(['KEY_B'])+ })++ it('a set-option timeout stops the loop after the first name', async () => {+ const { ensureUpdateEnvKeys } = await boot()+ execState.reply.set('set-option', TIMED_OUT)+ ensureUpdateEnvKeys(['KEY_A', 'KEY_B', 'KEY_C'])+ expect(callsFor('set-option')).toHaveLength(1)+ for (const c of [...callsFor('show-options'), ...callsFor('set-option')]) {+ expect(c.opts.timeout).toBe(2000)+ expect(c.opts.killSignal).toBe('SIGKILL')+ }+ expect(warn).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/core/pty-tmux-wedged.realtmux.test.ts b/src/core/pty-tmux-wedged.realtmux.test.tsnew file mode 100644index 000000000..e249a22df--- /dev/null+++ b/src/core/pty-tmux-wedged.realtmux.test.ts@@ -0,0 +1,101 @@+// A WEDGED tmux SERVER NO LONGER HOLDS BOOT (audit main-5), PROVEN AGAINST A REAL tmux CLIENT.+//+// The unit suite (`pty-tmux-boot-timeout.test.ts`) pins that every boot-path call carries the+// bound; whether the bound actually ends a real client stuck on a server that never answers is a+// property of tmux and the kernel, so it is measured here. The "server" is a unix listener bound+// where `-L node-terminal` resolves that accepts and then says nothing — the audit's repro, which+// held an unbounded client 4.05 s (the listener's whole lifetime). It works with main blocked in+// `execFileSync`: the kernel completes the connect from the listen backlog, no JS has to run.+//+// Private `TMUX_TMPDIR`, never the run-wide sandbox: other suites bind `node-terminal` inside that+// sandbox (`host-destroy-tmux.test.ts`), and planting a dead socket there would wedge them.+import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import net from 'net'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { makeTmuxTmpdir, tmuxSocketPath } from './tmux-test-socket'+import { TMUX_SOCKET } from './tmux-naming'++// Only the login-shell probe is stubbed (it would spawn a shell); tmux itself is found for real,+// from the fixed install paths or this process's PATH.+vi.mock('./exec-path', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./exec-path')>()),+ resolveShellPath: () => Promise.resolve(null),+ shellPathNow: () => undefined+}))+vi.mock('node-pty', () => ({ spawn: () => ({ onData: () => {}, onExit: () => {}, kill: () => {} }) }))++let tmp: string+let tmuxOk = false+let listener: net.Server | null = null+const accepted: net.Socket[] = []+const savedTmpdir = process.env.TMUX_TMPDIR++beforeAll(async () => {+ if (process.platform === 'win32') return // no tmux on Windows — the session host owns that world+ try {+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })+ tmuxOk = true+ } catch {+ return // no tmux on this host — the test below self-skips+ }+ tmp = makeTmuxTmpdir('ntwdg-', TMUX_SOCKET)+ const sock = tmuxSocketPath(tmp, process.getuid?.() ?? 0, TMUX_SOCKET)+ // tmux refuses a socket directory that is not private to the user.+ fs.mkdirSync(path.dirname(sock), { recursive: true, mode: 0o700 })+ listener = net.createServer((c) => {+ accepted.push(c) // hold it open, never write: a server that took the client and went silent+ })+ await new Promise<void>((resolve) => listener!.listen(sock, resolve))+ process.env.TMUX_TMPDIR = tmp+})++afterEach(() => {+ vi.restoreAllMocks()+ resetPlatformForTests()+})++afterAll(async () => {+ if (savedTmpdir === undefined) delete process.env.TMUX_TMPDIR+ else process.env.TMUX_TMPDIR = savedTmpdir+ for (const c of accepted) c.destroy()+ if (listener) await new Promise<void>((resolve) => listener!.close(() => resolve()))+ if (tmp) fs.rmSync(tmp, { recursive: true, force: true })+})++describe('boot against a tmux server that never answers', () => {+ it.skipIf(process.platform === 'win32')(+ 'ensureTmux returns within the bound, logs it, and keeps tmux resolved (needs a real tmux)',+ async () => {+ if (!tmuxOk) return // no tmux binary on this host: nothing real to measure+ initPlatform(fakePlatform())+ // ensureTmux writes the generated tmux.conf into userDataDir; the fake's dir does not exist.+ vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { PtyManager } = await import('./pty-manager')+ const mgr = new PtyManager()+ mgr.tmuxBootCmdTimeoutMs = 300 // production is 2 s; the property is what is under test++ const started = Date.now()+ mgr.init(() => ({ tmuxEnabled: true, tmuxScrollback: 10_000 }) as never)+ const elapsed = Date.now() - started++ expect(mgr.getTmuxBin()).not.toBeNull()+ // The client really was wedged (it waited out the bound) and really was ended by it.+ expect(elapsed).toBeGreaterThanOrEqual(300)+ expect(elapsed).toBeLessThan(2_000)+ // The listener's accept callback could not run while main was blocked; let it drain, then+ // confirm the client did reach OUR dead socket (not some other server, not a connect error).+ for (let i = 0; i < 50 && accepted.length === 0; i++) {+ await new Promise((resolve) => setTimeout(resolve, 20))+ }+ expect(accepted.length).toBeGreaterThan(0)+ expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toMatch(+ /tmux source-file .*timed out after 300ms/+ )+ }+ )+})