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): name the machine pty-device limit in the spawn failure
enesd17a3474b724
diff --git a/src/core/pty-devices.test.ts b/src/core/pty-devices.test.tsnew file mode 100644index 000000000..e03ce7619--- /dev/null+++ b/src/core/pty-devices.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest'+import os from 'os'+import {+ PTY_DEVICE_HEADROOM,+ ptyDevicesExhausted,+ readPtyDevices,+ spawnFailureHint+} from './pty-devices'++/**+ * The 2026-08-11 report: every new terminal spawned black with `posix_spawnp failed.` while the+ * spawn-helper's architecture was fine and the process was nowhere near its descriptor limit. What+ * was actually full was the MACHINE: `kern.tty.ptmx_max` is 511 and there were 515 `/dev/ttys*`+ * devices. The message named the architecture anyway — the one hint that could not be the cause —+ * and the user rebuilt node-pty for the third time.+ *+ * What is pinned here is the ORDER of the hints and the fact that the pty-device hint is only+ * spoken when the two numbers say so.+ */+const GENERIC = 'If this persists, restart the app.'++describe('ptyDevicesExhausted', () => {+ it('is true when the device count has reached the ceiling', () => {+ expect(ptyDevicesExhausted({ ceiling: 511, inUse: 515 })).toBe(true)+ expect(ptyDevicesExhausted({ ceiling: 511, inUse: 511 })).toBe(true)+ })++ it('counts "a handful below the ceiling" as full', () => {+ // A terminal needs a device to spare; the failure lands before the count is literally equal.+ expect(ptyDevicesExhausted({ ceiling: 511, inUse: 511 - PTY_DEVICE_HEADROOM })).toBe(true)+ expect(ptyDevicesExhausted({ ceiling: 511, inUse: 511 - PTY_DEVICE_HEADROOM - 1 })).toBe(false)+ })++ it('is false on a machine with room, and on one it could not measure', () => {+ expect(ptyDevicesExhausted({ ceiling: 511, inUse: 62 })).toBe(false)+ expect(ptyDevicesExhausted({ ceiling: null, inUse: 515 })).toBe(false)+ expect(ptyDevicesExhausted({ ceiling: 511, inUse: null })).toBe(false)+ expect(ptyDevicesExhausted({ ceiling: null, inUse: null })).toBe(false)+ })+})++describe('spawnFailureHint', () => {+ it('names the pty-device limit — with both numbers — when the machine is out of devices', () => {+ const hint = spawnFailureHint(null, { ceiling: 511, inUse: 515 }, GENERIC)+ expect(hint).toContain('511')+ expect(hint).toContain('515')+ expect(hint).toContain('kern.tty.ptmx_max')+ expect(hint).toContain('close some terminals')+ // INSTEAD of, not in addition to: the generic advice is what sent the last report chasing a+ // rebuild, and it is exactly as wrong here as the architecture hint would be.+ expect(hint).not.toContain(GENERIC)+ })++ it('lets the architecture mismatch win — it is the one thing we MEASURED about this build', () => {+ const arch = "node-pty's spawn-helper is x86_64 but this app is arm64"+ const hint = spawnFailureHint(arch, { ceiling: 511, inUse: 515 }, GENERIC)+ expect(hint).toBe(arch)+ })++ it('falls back to the generic text when neither check fires', () => {+ expect(spawnFailureHint(null, { ceiling: 511, inUse: 62 }, GENERIC)).toBe(GENERIC)+ expect(spawnFailureHint(null, { ceiling: null, inUse: null }, GENERIC)).toBe(GENERIC)+ })+})++describe('readPtyDevices', () => {+ it('measures this machine without throwing', () => {+ // It runs INSIDE an error path: a diagnostic that throws replaces a bad error message with no+ // error message at all. The numbers are the machine's, so only their shape is asserted.+ const d = readPtyDevices()+ expect(d.inUse === null || d.inUse > 0).toBe(true)+ expect(d.ceiling === null || d.ceiling > 0).toBe(true)+ // Off darwin there is no `kern.tty.ptmx_max` and no `/dev/ttys*` convention to count: the+ // diagnostic says nothing rather than counting the wrong thing.+ if (os.platform() !== 'darwin') expect(d).toEqual({ ceiling: null, inUse: null })+ })+})diff --git a/src/core/pty-devices.ts b/src/core/pty-devices.tsnew file mode 100644index 000000000..73f05c606--- /dev/null+++ b/src/core/pty-devices.ts@@ -0,0 +1,139 @@+import fs from 'fs'+import os from 'os'+import { execFile } from 'child_process'++/**+ * How many pty DEVICES this machine can hand out, and how many exist right now.+ *+ * The limit that bit on 2026-08-11 was neither the app's descriptors nor node-pty's architecture:+ * macOS caps pty devices system-wide at `kern.tty.ptmx_max` (511 by default), and with 62 live app+ * PTYs, 18 tmux sessions and ~19 ssh children there were 515 `/dev/ttys*` entries. Every spawn from+ * then on failed with a bare `posix_spawnp failed.` — the SAME opaque error a cross-arch+ * spawn-helper produces, which is why the old message sent the report chasing an architecture that+ * was fine.+ *+ * `null` means "could not be measured", which is a different statement from zero and is rendered as+ * silence rather than as a number (same rule as `SpawnResources`).+ */+export interface PtyDevices {+ /** `kern.tty.ptmx_max` — the system-wide ceiling. */+ ceiling: number | null+ /** `/dev/ttys*` entries in existence right now. */+ inUse: number | null+}++/**+ * How close to the ceiling counts as "at" it.+ *+ * Opening a terminal takes a device, and a tmux-backed one takes two in quick succession (the app's+ * client plus, on a cold start, the pane) — so the spawn fails a hair before the count is literally+ * equal, and the count itself is a snapshot taken after the failure, by which time a device or two+ * may already have been returned. Small, because unlike the descriptor check this one names a+ * SYSTEM limit: claiming the machine is full when it has room would be a worse sentence than saying+ * nothing.+ */+export const PTY_DEVICE_HEADROOM = 4++/**+ * How long a read of `kern.tty.ptmx_max` is trusted.+ *+ * The value effectively never changes — but a user who follows the advice below and raises it with+ * `sysctl -w` must not be told the same wrong thing for the rest of the session, so it expires.+ */+const CEILING_TTL_MS = 60_000++let ceiling: { value: number | null; at: number } | null = null+let refreshing = false++/**+ * Kick an async read of the ceiling (darwin only). Fire-and-forget by design: `execFile` cannot be+ * awaited from the synchronous spawn path this diagnostic serves, so the value is read AHEAD of the+ * failure (PtyManager.init primes it) and re-read in the background when it goes stale. A read that+ * has not landed yet leaves `ceiling: null`, i.e. the hint stays silent rather than guessing.+ */+export function primePtyCeiling(): void {+ if (os.platform() !== 'darwin' || refreshing) return+ refreshing = true+ try {+ execFile('sysctl', ['-n', 'kern.tty.ptmx_max'], { timeout: 5_000 }, (err, stdout) => {+ refreshing = false+ // A failed/odd read is recorded as `null` WITH a timestamp: on a machine where sysctl is+ // unavailable this stops us re-spawning it on every subsequent spawn failure.+ const parsed = err ? NaN : Number.parseInt(String(stdout).trim(), 10)+ ceiling = { value: Number.isFinite(parsed) && parsed > 0 ? parsed : null, at: Date.now() }+ })+ } catch {+ refreshing = false // diagnostics only — never mask the real spawn error+ }+}++/** The cached ceiling, refreshing in the background once it is stale. */+function ptyCeiling(): number | null {+ if (os.platform() !== 'darwin') return null+ if (!ceiling || Date.now() - ceiling.at >= CEILING_TTL_MS) primePtyCeiling()+ // The stale value is still the best answer we have while the refresh is in flight — it is only+ // stale in the sense of "read a minute ago", and a sysctl that changed since is exactly the case+ // the refresh above is for.+ return ceiling?.value ?? null+}++/**+ * Count the pty devices that exist right now.+ *+ * A directory listing, not a subprocess: this runs inside an error path that is already one failed+ * spawn deep, and shelling out to `ls` to count files would need the very resource that just ran+ * out. `/dev/ttys*` is the macOS naming (`ttys000`, `ttys001`, …); the entries are created on demand+ * and stay until reboot, which is what makes the count meaningful.+ */+function countPtyDevices(): number | null {+ if (os.platform() !== 'darwin') return null+ try {+ return fs.readdirSync('/dev').filter((name) => name.startsWith('ttys')).length+ } catch {+ return null+ }+}++/** Both numbers, measured now. Fail-open in every direction (see `readSpawnResources`). */+export function readPtyDevices(): PtyDevices {+ return { ceiling: ptyCeiling(), inUse: countPtyDevices() }+}++/** True when the machine has no pty device left to hand out. Unmeasured ⇒ false (stay silent). */+export function ptyDevicesExhausted(d: PtyDevices): boolean {+ if (d.ceiling === null || d.inUse === null) return false+ return d.inUse >= d.ceiling - PTY_DEVICE_HEADROOM+}++/**+ * The ONE sentence a spawn failure ends with, chosen from what was actually measured. Pure, so the+ * wording and the precedence can be pinned.+ *+ * The order matters as much as the wording:+ * 1. `archNote` — the only hint derived from reading THIS build's spawn-helper. When the helper+ * cannot be exec'd at all, nothing else can be the cause.+ * 2. pty devices — the machine is out of them, so no process can open a terminal until some are+ * returned. Stated INSTEAD of the generic advice, never alongside it: "rebuild node-pty" is+ * precisely as wrong here as it was in the 2026-08-06 report.+ * 3. the caller's generic text, which is what it has always been — a guess of last resort.+ */+export function spawnFailureHint(+ archNote: string | null,+ devices: PtyDevices,+ generic: string+): string {+ if (archNote) return archNote+ if (!ptyDevicesExhausted(devices)) return generic+ return (+ `This MACHINE is out of pty devices (${devices.inUse} of ${devices.ceiling} allowed by ` ++ `\`kern.tty.ptmx_max\`), so no process can open a terminal until some are returned — close ` ++ `some terminals (a tmux session's pane holds one too), or raise the limit with ` ++ `\`sudo sysctl -w kern.tty.ptmx_max=<bigger>\`. Rebuilding node-pty will not help.`+ )+}++/** Test seam: forget the cached ceiling so a test can pin the read itself. */+export function resetPtyDevicesCacheForTests(): void {+ ceiling = null+ refreshing = false+}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex dd5367dda..ed846e9d6 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -31,6 +31,7 @@ import {} from './remote-ssh/control-master'import { parsePaneCursor } from './pane-cursor'import { readSpawnResources, spawnResourceNote } from './spawn-resources'+import { primePtyCeiling, readPtyDevices, spawnFailureHint } from './pty-devices'import { TMUX_SOCKET, sessionName } from './tmux-naming'import { bracketedInjection } from './paste-injection'import { releasePty, type ReleasablePty } from './pty-release'@@ -557,6 +558,11 @@ export class PtyManager {// own, so a tmux living only on the user's shell PATH is invisible until this resolves.void resolveShellPath().then(() => this.ensureTmux())this.ensureTmux()+ // Read the system pty-device ceiling now, while nothing is wrong. The spawn path that needs it+ // is synchronous and already one failed spawn deep — it cannot await a `sysctl` there, and a+ // machine at its device limit is exactly a machine where spawning one more process is a bad+ // idea. See pty-devices.ts.+ primePtyCeiling()}/** Probe tmux and write/push the generated config. Idempotent and safe to re-run: a later@@ -1308,9 +1314,10 @@ export class PtyManager {})} catch (err) {// node-pty surfaces the underlying failure as a bare "posix_spawnp failed." with no errno.- // The recurring field cause is a cross-arch `electron-builder --x64` run clobbering- // node-pty's spawn-helper in node_modules (arm64 app can't exec an x86_64 helper), so- // check the helper's Mach-O arch first and name the exact remedy when it mismatches.+ // Two different field causes wear that same message, so BOTH are measured before anything is+ // said: a cross-arch `electron-builder --x64` run clobbering node-pty's spawn-helper (arm64+ // app can't exec an x86_64 helper), and the machine being out of pty DEVICES+ // (`kern.tty.ptmx_max`, 2026-08-11 — 515 `/dev/ttys*` against a ceiling of 511).const openPtys = this.sessions.sizeconst reason = err instanceof Error ? err.message : String(err)const archNote = spawnHelperArchMismatch()@@ -1320,12 +1327,17 @@ export class PtyManager {// (2026-08-06) chasing an architecture that was fine. `spawnResourceNote` states what it// actually counted and only names a remedy the numbers support.const resources = spawnResourceNote(readSpawnResources(), openPtys)+ // ONE closing hint, picked by what was measured (`spawnFailureHint`): arch, else the system+ // pty-device limit, else the generic guess of last resort.+ const hint = spawnFailureHint(+ archNote,+ readPtyDevices(),+ `If this persists, restart the app (tmux sessions survive a restart) or run ` ++ `\`npm run rebuild\` in the repo — a release build may have rebuilt node-pty ` ++ `for the wrong architecture.`+ )throw new Error(- `Failed to spawn terminal (${reason}). Program: ${file}, cwd: ${cwd}, ${resources} ` +- (archNote ??- `If this persists, restart the app (tmux sessions survive a restart) or run ` +- `\`npm run rebuild\` in the repo — a release build may have rebuilt node-pty ` +- `for the wrong architecture.`)+ `Failed to spawn terminal (${reason}). Program: ${file}, cwd: ${cwd}, ${resources} ${hint}`)}diff --git a/src/core/pty-spawn-diagnosis.test.ts b/src/core/pty-spawn-diagnosis.test.tsnew file mode 100644index 000000000..990c9c234--- /dev/null+++ b/src/core/pty-spawn-diagnosis.test.ts@@ -0,0 +1,85 @@+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'+import type { PtyDevices } from './pty-devices'++/**+ * WHAT THE SPAWN FAILURE SAYS.+ *+ * node-pty reports every failure as a bare `posix_spawnp failed.` with the errno discarded, so the+ * error message is assembled from measurements taken after the fact. This pins the wiring: the+ * pty-DEVICE measurement actually reaches the message, and it replaces the generic+ * restart/rebuild advice rather than being appended to it (2026-08-11 — the machine was at+ * `kern.tty.ptmx_max`, and the message talked about architecture).+ */++/** Every spawn in this file fails: the message is the whole subject. */+vi.mock('node-pty', () => ({+ spawn: () => {+ throw new Error('posix_spawnp failed.')+ }+}))++/** What the (real) device probe would have measured — set per test. */+const devices = vi.hoisted(() => ({+ current: { ceiling: null, inUse: null } as PtyDevices+}))+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => devices.current+}))++const ALICE = 1++describe('spawn failure diagnosis', () => {+ let fake: FakePlatform++ beforeEach(() => {+ devices.current = { ceiling: null, inUse: null }+ fake = fakePlatform()+ initPlatform(fake)+ })+ afterEach(() => resetPlatformForTests())++ async function manager() {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.registerIpc()+ return m+ }+ const create = (): Promise<unknown> =>+ fake.handlers[IPC.ptyCreate](ALICE, { cols: 80, rows: 24, persistKey: 'node-1' }) as Promise<+ unknown+ >++ it('names the machine pty-device limit — with both numbers — when that is what is full', async () => {+ await manager()+ devices.current = { ceiling: 511, inUse: 515 }++ await expect(create()).rejects.toThrow(/out of pty devices \(515 of 511/)+ })++ it('says the pty limit INSTEAD of the rebuild advice, not alongside it', async () => {+ await manager()+ devices.current = { ceiling: 511, inUse: 515 }++ await expect(create()).rejects.toThrow(/kern\.tty\.ptmx_max/)+ await expect(create()).rejects.not.toThrow(/npm run rebuild/)+ })++ it('keeps the live-PTY / open-files context either way', async () => {+ await manager()+ devices.current = { ceiling: 511, inUse: 515 }++ await expect(create()).rejects.toThrow(/live PTYs: 0/)+ })++ it('falls back to the unchanged generic advice on a machine with pty devices to spare', async () => {+ await manager()+ devices.current = { ceiling: 511, inUse: 62 }++ await expect(create()).rejects.toThrow(/npm run rebuild/)+ await expect(create()).rejects.not.toThrow(/pty devices/)+ })+})