Skip to content

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.

fix(pty): run the device pre-flight before the shadow swap-out, and pin its tests

enesfe1a456a017c
diff --git a/src/core/pty-background-write.test.ts b/src/core/pty-background-write.test.ts
index ddd11d3e1..0c617e1a4 100644
--- a/src/core/pty-background-write.test.ts
+++ b/src/core/pty-background-write.test.ts
@@ -148,6 +148,21 @@ const BOB = 2
/** `ls\n` as the wire sees it: hex bytes, because a control-mode command is one text line. */
const LS_KEYS = (target: string): string => `send-keys -t ${target} -H 6c 73 0a\n`
+/**
+ * A machine with pty devices to spare, always.
+ *
+ * Without this the real probe runs a `readdir('/dev')` against the DEVELOPER's host, and
+ * `spawnSession`'s pre-flight refuses every create once that host is within `PTY_DEVICE_HEADROOM`
+ * of its own `kern.tty.ptmx_max` — which a machine running this app all day genuinely reaches (511
+ * on macOS; this one sits in the 480s). Nothing below is about device pressure, so it is pinned
+ * healthy rather than left to depend on who is running the suite and how many terminals they have
+ * open. The pressure behaviour itself is tested in pty-spawn-preflight.test.ts.
+ */
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
describe('background writes into released sessions', () => {
let fake: FakePlatform
let userDataDir: string
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.ts
index b85ca515e..b6128f09d 100644
--- a/src/core/pty-coattach.test.ts
+++ b/src/core/pty-coattach.test.ts
@@ -52,6 +52,21 @@ const ALICE = 1
const BOB = 2
const CAROL = 3
+/**
+ * A machine with pty devices to spare, always.
+ *
+ * Without this the real probe runs a `readdir('/dev')` against the DEVELOPER's host, and
+ * `spawnSession`'s pre-flight refuses every create once that host is within `PTY_DEVICE_HEADROOM`
+ * of its own `kern.tty.ptmx_max` — which a machine running this app all day genuinely reaches (511
+ * on macOS; this one sits in the 480s). Nothing below is about device pressure, so it is pinned
+ * healthy rather than left to depend on who is running the suite and how many terminals they have
+ * open. The pressure behaviour itself is tested in pty-spawn-preflight.test.ts.
+ */
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
describe('terminal co-attach: one PTY, N subscribers', () => {
let fake: FakePlatform
diff --git a/src/core/pty-devices.ts b/src/core/pty-devices.ts
index e82640f72..842259314 100644
--- a/src/core/pty-devices.ts
+++ b/src/core/pty-devices.ts
@@ -31,6 +31,20 @@ export interface PtyDevices {
* 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.
+ *
+ * TWO CONSUMERS NOW, and the slack means something different to each:
+ * - the post-mortem hint above — the reading is a snapshot taken after the fact, so the slack
+ * absorbs devices returned between the failure and the count;
+ * - `PtyManager.spawnSession`'s pre-flight, where it is not slack at all but a PRE-EMPTIVE band:
+ * a refusal starts at `ceiling - 4` (507 of 511), while the machine still has four devices.
+ *
+ * The band is deliberate, and it is the same arithmetic read forwards. A tmux-backed spawn wants
+ * two devices, so a create begun at 508 lands ON the wall rather than under it — and a spawn that
+ * reaches the wall does not merely fail, it LEAKS two devices doing so (node-pty; see the
+ * pre-flight's comment). Refusing inside the band trades at most four devices of capacity, on a
+ * machine already at 99% of a system limit, for the guarantee that no failure-with-leak is ever
+ * started. Those four are the cheapest possible price for closing the spiral, and the user is told
+ * the true numbers either way.
*/
export const PTY_DEVICE_HEADROOM = 4
@@ -82,8 +96,13 @@ function ptyCeiling(): number | null {
*
* 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.
+ * out. `/dev/ttys*` is the macOS naming (`ttys000`, `ttys001`, …): entries are created on demand
+ * and RECLAIMED when the pty is closed — measured on this host going 492 → 500 → 492 across a batch
+ * of terminals opening and closing. Nothing is cached, so every call is a fresh readdir, which is
+ * what lets a machine that just freed some devices spawn again immediately instead of staying
+ * refused until a restart. (It is also why a LEAKED master is so costly: a device whose master fd
+ * is never closed is never reclaimed either, so it counts against the ceiling until the process
+ * that leaked it exits.)
*/
function countPtyDevices(): number | null {
if (os.platform() !== 'darwin') return null
diff --git a/src/core/pty-idle-reap.test.ts b/src/core/pty-idle-reap.test.ts
index 0b97148a3..8d6505775 100644
--- a/src/core/pty-idle-reap.test.ts
+++ b/src/core/pty-idle-reap.test.ts
@@ -83,6 +83,21 @@ vi.mock('child_process', () => {
const ALICE = 1
+/**
+ * A machine with pty devices to spare, always.
+ *
+ * Without this the real probe runs a `readdir('/dev')` against the DEVELOPER's host, and
+ * `spawnSession`'s pre-flight refuses every create once that host is within `PTY_DEVICE_HEADROOM`
+ * of its own `kern.tty.ptmx_max` — which a machine running this app all day genuinely reaches (511
+ * on macOS; this one sits in the 480s). Nothing below is about device pressure, so it is pinned
+ * healthy rather than left to depend on who is running the suite and how many terminals they have
+ * open. The pressure behaviour itself is tested in pty-spawn-preflight.test.ts.
+ */
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
describe('idle reap of unwatched client PTYs', () => {
let fake: FakePlatform
let userDataDir: string
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 6bda4c16f..26c9e0e74 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1693,6 +1693,59 @@ export class PtyManager {
clientId: ClientId | null,
sinks: DetachedSinks | undefined
): string {
+ // PRE-FLIGHT — refuse before node-pty is touched, not after it fails.
+ //
+ // node-pty's darwin spawn path LEAKS the pty it opened when `posix_spawn` fails:
+ // `pty_posix_spawn` (node_modules/node-pty/src/unix/pty.cc) opens the master with
+ // `posix_openpt` and the slave with `open()`, and the error branch in `PtyFork` throws without
+ // closing either — measured at 2 `/dev/ptmx` fds + 1 `/dev/ttys*` fd, i.e. 2 pty DEVICES, per
+ // failed spawn (there is a third, smaller leak of one device per SUCCESSFUL spawn from the
+ // `low_fds` cleanup loop's off-by-one). That makes exhaustion self-amplifying: at the ceiling
+ // every spawn fails, every failure eats two more devices, and each retry pushes the ceiling
+ // further away — a 31-minute-old main held 479 masters against 28 tmux panes and dozens of
+ // consecutive failed creates. The leak is node-pty's to fix; ours is to stop feeding it.
+ //
+ // FIRST STATEMENT IN THE FUNCTION, ahead of the swap-out below, because a refusal must leave
+ // the node exactly as it found it. Retiring the shadow first would trade a live background
+ // client for nothing at all: the painter it was making way for never arrives, and nothing
+ // re-attaches a shadow (`shadowAttach` is driven by release/reap, not by a failed create), so
+ // a node nobody is watching would go quietly dark on a machine that is merely full. Nothing
+ // between here and `pty.spawn` is needed to decide this — the reading is machine-wide.
+ //
+ // FAIL-OPEN is the rule here: `ptyDevicesExhausted` is false for anything unmeasured
+ // (non-darwin, a `sysctl` that failed, or a ceiling whose async prime — kicked in `init` — has
+ // not landed yet), so an unknown machine spawns exactly as it always did. Refusing a terminal
+ // on a machine that had room would be a worse bug than the leak this avoids.
+ //
+ // AND THAT IS THE WHOLE FIX — no backoff, no circuit breaker, deliberately. The bursts of
+ // consecutive failed creates in the field log are not a retry storm: NOTHING re-attempts a
+ // create that failed. The renderer's create rejection lands in one `.catch` that only records
+ // `spawnError` for the node's overlay (TerminalNode.tsx) — no timer, no respawn bump, and no
+ // `reportSshDrop`, so a failure cannot even feed the SSH reconnect coordinator (whose own loop
+ // is bounded anyway: 1→2→4→8→15s, then parked until a `connected` event, plus a 10s re-drop
+ // refusal). A burst is therefore N DISTINCT nodes each trying exactly once, fanned out by one
+ // moment — app boot, a project tab switch past the park window, an agent's bulk
+ // `open-terminal --count N`, or one reconnect flush. Rate-limiting that would only stagger
+ // failures the user asked for. What made it look like a storm was the amplification: 40
+ // one-shot creates used to cost 80 devices, and now cost none.
+ const devices = readPtyDevices()
+ if (ptyDevicesExhausted(devices)) {
+ // The REQUESTED program and cwd, not the resolved ones — resolution happens further down and
+ // deliberately has not run. Nothing was chosen, so nothing is claimed to have been.
+ //
+ // `archNote` is deliberately not consulted: it outranks the device note in
+ // `spawnFailureHint`, and no helper was exec'd here, so its architecture cannot be the
+ // reason. Saying "rebuild node-pty" to a machine that is simply full is the 2026-08-06
+ // mistake with a new cause.
+ throw this.spawnFailureError(
+ 'not attempted',
+ options.shell ?? '(default shell)',
+ options.cwd ?? os.homedir(),
+ null,
+ devices
+ )
+ }
+
// SWAP-OUT, before anything at all is spawned: a painter pty client is arriving for this node,
// and a session never has both. The painter attaches with `-D` and would kick the shadow off by
// itself — but only once tmux has processed both attaches, leaving a window where two clients
@@ -1702,7 +1755,8 @@ export class PtyManager {
//
// Here rather than in `create()` so EVERY path to a painter is covered — the warm reattach, the
// relay host's `attachDetached`, and whatever spawns next — and so the ordering is provable:
- // it is the first statement before `pty.spawn` in the same synchronous function.
+ // nothing between here and `pty.spawn` can fail, in the same synchronous function. (The
+ // pre-flight above is the one thing that CAN, which is exactly why it runs before this.)
// The shared background-write client goes too, for the same reason, when it is this node's
// session it happens to be attached to.
if (options.persistKey) {
@@ -1934,43 +1988,6 @@ export class PtyManager {
args = program ? programArgs : []
}
- // PRE-FLIGHT — refuse before node-pty is touched, not after it fails.
- //
- // node-pty's darwin spawn path LEAKS the pty it opened when `posix_spawn` fails:
- // `pty_posix_spawn` (node_modules/node-pty/src/unix/pty.cc) opens the master with
- // `posix_openpt` and the slave with `open()`, and the error branch in `PtyFork` throws without
- // closing either — measured at 2 `/dev/ptmx` fds + 1 `/dev/ttys*` fd, i.e. 2 pty DEVICES, per
- // failed spawn (there is a third, smaller leak of one device per SUCCESSFUL spawn from the
- // `low_fds` cleanup loop's off-by-one). That makes exhaustion self-amplifying: at the ceiling
- // every spawn fails, every failure eats two more devices, and each retry pushes the ceiling
- // further away — a 31-minute-old main held 479 masters against 28 tmux panes and dozens of
- // consecutive failed creates. The leak is node-pty's to fix; ours is to stop feeding it.
- //
- // FAIL-OPEN is the rule here: `ptyDevicesExhausted` is false for anything unmeasured
- // (non-darwin, a `sysctl` that failed, or a ceiling whose async prime — kicked in `init` — has
- // not landed yet), so an unknown machine spawns exactly as it always did. Refusing a terminal
- // on a machine that had room would be a worse bug than the leak this avoids.
- //
- // AND THAT IS THE WHOLE FIX — no backoff, no circuit breaker, deliberately. The bursts of
- // consecutive failed creates in the field log are not a retry storm: NOTHING re-attempts a
- // create that failed. The renderer's create rejection lands in one `.catch` that only records
- // `spawnError` for the node's overlay (TerminalNode.tsx) — no timer, no respawn bump, and no
- // `reportSshDrop`, so a failure cannot even feed the SSH reconnect coordinator (whose own loop
- // is bounded anyway: 1→2→4→8→15s, then parked until a `connected` event, plus a 10s re-drop
- // refusal). A burst is therefore N DISTINCT nodes each trying exactly once, fanned out by one
- // moment — app boot, a project tab switch past the park window, an agent's bulk
- // `open-terminal --count N`, or one reconnect flush. Rate-limiting that would only stagger
- // failures the user asked for. What made it look like a storm was the amplification: 40
- // one-shot creates used to cost 80 devices, and now cost none.
- const devices = readPtyDevices()
- if (ptyDevicesExhausted(devices)) {
- // `archNote` is deliberately not consulted: it outranks the device note in
- // `spawnFailureHint`, and no helper was exec'd here, so its architecture cannot be the
- // reason. Saying "rebuild node-pty" to a machine that is simply full is the 2026-08-06
- // mistake with a new cause.
- throw this.spawnFailureError('not attempted', file, cwd, null, devices)
- }
-
let proc: pty.IPty
try {
proc = pty.spawn(file, args, {
diff --git a/src/core/pty-require-remote.test.ts b/src/core/pty-require-remote.test.ts
index 85428d439..fadd033c9 100644
--- a/src/core/pty-require-remote.test.ts
+++ b/src/core/pty-require-remote.test.ts
@@ -34,6 +34,21 @@ vi.mock('node-pty', () => ({
const ALICE = 1
const BOB = 2
+/**
+ * A machine with pty devices to spare, always.
+ *
+ * Without this the real probe runs a `readdir('/dev')` against the DEVELOPER's host, and
+ * `spawnSession`'s pre-flight refuses every create once that host is within `PTY_DEVICE_HEADROOM`
+ * of its own `kern.tty.ptmx_max` — which a machine running this app all day genuinely reaches (511
+ * on macOS; this one sits in the 480s). Nothing below is about device pressure, so it is pinned
+ * healthy rather than left to depend on who is running the suite and how many terminals they have
+ * open. The pressure behaviour itself is tested in pty-spawn-preflight.test.ts.
+ */
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
describe('pty create: requireRemote never falls back to a local shell', () => {
let fake: FakePlatform
diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.ts
index e9808c8be..6e9446741 100644
--- a/src/core/pty-shadow.test.ts
+++ b/src/core/pty-shadow.test.ts
@@ -9,6 +9,7 @@ import { DEFAULT_SETTINGS } from '../shared/types'
import { TMUX_SOCKET, sessionName } from './tmux-naming'
import { REAP_IDLE_MS, REAP_SWEEP_MS } from './pty-reap'
import type { ControlSpawn } from './tmux-control-client'
+import type { PtyDevices } from './pty-devices'
/**
* SHADOW CLIENTS: a tmux control-mode (`-C`) client over plain pipes, attached to the tmux session
@@ -146,6 +147,21 @@ class FakeControlSpawn implements ControlSpawn {
}
}
+/**
+ * A machine with pty devices to spare by default.
+ *
+ * Without this the real probe runs a `readdir('/dev')` against the DEVELOPER's host, and
+ * `spawnSession`'s pre-flight refuses every create once that host is within `PTY_DEVICE_HEADROOM`
+ * of its own `kern.tty.ptmx_max` — which a machine running this app all day genuinely reaches (511
+ * on macOS; this one sits in the 480s). Settable, because one test below is about what a REFUSED
+ * create does to a shadow.
+ */
+const devices = vi.hoisted(() => ({ current: { ceiling: 511, inUse: 8 } as PtyDevices }))
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => devices.current
+}))
+
const ALICE = 1
const BOB = 2
@@ -157,6 +173,7 @@ describe('control-mode shadow clients for released sessions', () => {
beforeEach(() => {
spawned.length = 0
log.length = 0
+ devices.current = { ceiling: 511, inUse: 8 }
liveTmuxSessions.clear()
control = new FakeControlSpawn()
userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-shadow-'))
@@ -236,6 +253,27 @@ describe('control-mode shadow clients for released sessions', () => {
expect(control.calls).toHaveLength(0)
})
+ it('leaves the shadow ALIVE when the create is refused for want of pty devices', async () => {
+ // The swap-out below retires the shadow to make way for an arriving painter. If a create that
+ // never spawns anything still ran it, a machine at its pty ceiling would silently kill the
+ // background client of every node it refused — and nothing re-attaches one (`shadowAttach` is
+ // driven by release/reap, not by a failed create), so the node would go dark until the user
+ // reopened it. Hence the pre-flight runs BEFORE the swap-out, not next to `pty.spawn`.
+ const m = await tmuxManager()
+ const { sessionId } = await create(ALICE)
+ kill(ALICE, sessionId)
+ const shadow = await m.shadowAttach('node-1')
+ expect(shadow).not.toBeNull()
+
+ devices.current = { ceiling: 511, inUse: 515 } // the machine fills up
+ await expect(create(ALICE)).rejects.toThrow(/out of pty devices/)
+
+ expect(control.only.killed).toBe(0) // not retired…
+ expect(await m.shadowAttach('node-1')).toBe(shadow) // …and still the live one, re-used
+ expect(control.calls).toHaveLength(1) // no second control client either
+ expect(spawned).toHaveLength(1) // and, of course, no second pty
+ })
+
it('re-uses a live shadow instead of spawning a second control client', async () => {
const m = await tmuxManager()
const { sessionId } = await create(ALICE)
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index b9fb4392d..661f82e67 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -107,6 +107,21 @@ vi.mock('child_process', () => {
const SOLO = 42
+/**
+ * A machine with pty devices to spare, always.
+ *
+ * Without this the real probe runs a `readdir('/dev')` against the DEVELOPER's host, and
+ * `spawnSession`'s pre-flight refuses every create once that host is within `PTY_DEVICE_HEADROOM`
+ * of its own `kern.tty.ptmx_max` — which a machine running this app all day genuinely reaches (511
+ * on macOS; this one sits in the 480s). Nothing below is about device pressure, so it is pinned
+ * healthy rather than left to depend on who is running the suite and how many terminals they have
+ * open. The pressure behaviour itself is tested in pty-spawn-preflight.test.ts.
+ */
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () => {
let fake: FakePlatform
let userDataDir: string
diff --git a/src/core/pty-spawn-diagnosis.test.ts b/src/core/pty-spawn-diagnosis.test.ts
index 990c9c234..892016146 100644
--- a/src/core/pty-spawn-diagnosis.test.ts
+++ b/src/core/pty-spawn-diagnosis.test.ts
@@ -5,29 +5,50 @@ import { IPC } from '../shared/ipc'
import type { PtyDevices } from './pty-devices'
/**
- * WHAT THE SPAWN FAILURE SAYS.
+ * WHAT THE SPAWN FAILURE SAYS — the CATCH path, i.e. a spawn node-pty actually attempted and lost.
*
* 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).
+ *
+ * The device numbers below therefore describe the machine AS MEASURED AFTER THE FAILURE. The other
+ * way to be told the machine is full — the pre-flight refusing before node-pty is called at all —
+ * is a different code path and lives in pty-spawn-preflight.test.ts. Keeping them apart matters:
+ * once the pre-flight existed, a fixture that simply reads "exhausted" would be refused up front
+ * and these tests would silently stop exercising the catch at all.
*/
-/** Every spawn in this file fails: the message is the whole subject. */
+/**
+ * Every spawn in this file fails: the message is the whole subject. Counted, because "node-pty was
+ * reached at all" is the one thing that distinguishes this file's path from the pre-flight's — and
+ * a fixture drift that quietly routed these tests through the refusal instead would otherwise
+ * still produce a passing, and identical, message.
+ */
+const attempts = vi.hoisted(() => ({ n: 0 }))
vi.mock('node-pty', () => ({
spawn: () => {
+ attempts.n++
throw new Error('posix_spawnp failed.')
}
}))
-/** What the (real) device probe would have measured — set per test. */
+/** A machine with devices to spare — what the pre-flight must see so the spawn is attempted. */
+const HEALTHY: PtyDevices = { ceiling: 511, inUse: 8 }
+
+/** What the (real) device probe would have measured AFTER the failure — set per test. */
const devices = vi.hoisted(() => ({
- current: { ceiling: null, inUse: null } as PtyDevices
+ current: { ceiling: null, inUse: null } as PtyDevices,
+ calls: 0
}))
vi.mock('./pty-devices', async (importOriginal) => ({
...(await importOriginal<typeof import('./pty-devices')>()),
- readPtyDevices: () => devices.current
+ // `spawnSession` reads the devices exactly twice per failing create: once for the pre-flight,
+ // before node-pty, and once in the catch, after the failure. These tests are about the SECOND
+ // read, so the first always answers "healthy" — otherwise an exhausted fixture would be refused
+ // up front and node-pty would never be reached.
+ readPtyDevices: () => (devices.calls++ % 2 === 0 ? HEALTHY : devices.current)
}))
const ALICE = 1
@@ -37,10 +58,16 @@ describe('spawn failure diagnosis', () => {
beforeEach(() => {
devices.current = { ceiling: null, inUse: null }
+ devices.calls = 0
+ attempts.n = 0
fake = fakePlatform()
initPlatform(fake)
})
- afterEach(() => resetPlatformForTests())
+ afterEach(() => {
+ // Every test here is about what a FAILED spawn says, so every test must have spawned.
+ expect(attempts.n).toBeGreaterThan(0)
+ resetPlatformForTests()
+ })
async function manager() {
const { PtyManager } = await import('./pty-manager')
@@ -53,6 +80,17 @@ describe('spawn failure diagnosis', () => {
unknown
>
+ it('still diagnoses a machine that only filled up DURING the spawn', async () => {
+ await manager()
+ // The pre-flight saw room (HEALTHY, above) and let the spawn through; by the time it failed,
+ // the machine was at the wall. That is not a contrived ordering — it is the race the leak
+ // creates, and the reason the catch keeps its own measurement instead of trusting the
+ // pre-flight's. If the catch ever reused the earlier reading, this is the test that fails.
+ devices.current = { ceiling: 511, inUse: 511 }
+
+ await expect(create()).rejects.toThrow(/out of pty devices \(511 of 511/)
+ })
+
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 }
diff --git a/src/core/pty-spawn-preflight.test.ts b/src/core/pty-spawn-preflight.test.ts
index 8e3535f6d..7fc6f8dc3 100644
--- a/src/core/pty-spawn-preflight.test.ts
+++ b/src/core/pty-spawn-preflight.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import os from 'os'
import { initPlatform, resetPlatformForTests } from './platform'
import { fakePlatform, type FakePlatform } from './platform-fake'
import { IPC } from '../shared/ipc'
@@ -22,11 +23,17 @@ import type { PtyCreateResult } from '../shared/types'
* would refuse terminals on a healthy machine — so anything unmeasured spawns as it always did.
*/
-/** Every node-pty call is recorded, because "was it called" is the whole subject here. */
+/**
+ * Every node-pty call is recorded, because "was it called" is the whole subject here. It can also
+ * be told to fail, so the one test that needs the CATCH path (proving the arch mock below is real)
+ * can have it without a second file.
+ */
const spawned: Array<{ file: string }> = []
+const nodePty = vi.hoisted(() => ({ throws: false }))
vi.mock('node-pty', () => ({
spawn: (file: string) => {
spawned.push({ file })
+ if (nodePty.throws) throw new Error('posix_spawnp failed.')
return {
onData: () => {},
onExit: () => {},
@@ -49,6 +56,20 @@ vi.mock('./pty-devices', async (importOriginal) => ({
readPtyDevices: () => devices.current
}))
+/**
+ * Force `spawnHelperArchMismatch` to find a cross-arch spawn-helper.
+ *
+ * The arch note OUTRANKS the device note in `spawnFailureHint`, so on an ordinary matching-arch
+ * host "the refusal does not mention the architecture" is true no matter what the refusal does —
+ * the note is null either way. This makes the note non-null, so the assertion has something to
+ * catch. `spawnHelperArchMismatch` is module-private; `./macho-arch` is the seam underneath it.
+ */
+vi.mock('./macho-arch', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./macho-arch')>()),
+ machOArch: () => 'x64' as const,
+ archMismatch: () => true
+}))
+
const ALICE = 1
describe('pty create: pre-flight device check', () => {
@@ -56,6 +77,7 @@ describe('pty create: pre-flight device check', () => {
beforeEach(async () => {
spawned.length = 0
+ nodePty.throws = false
devices.current = { ceiling: null, inUse: null }
fake = fakePlatform()
initPlatform(fake)
@@ -87,14 +109,36 @@ describe('pty create: pre-flight device check', () => {
await expect(create()).rejects.toThrow(/kern\.tty\.ptmx_max/)
})
- it('never blames the architecture for a refusal it decided itself', async () => {
+ // Both of these need `spawnHelperArchMismatch` to actually produce a note, which it only does on
+ // darwin (it is a macOS-only diagnostic and returns null everywhere else). Skipped together, so
+ // a non-darwin run cannot pass the suppression test vacuously while silently losing its guard.
+ const onDarwin = os.platform() === 'darwin'
+
+ it.skipIf(!onDarwin)(
+ 'proves the arch mock is live: a spawn that DID fail still gets the arch note',
+ async () => {
+ // The control for the test below. Without it, "the refusal omits the arch note" could pass
+ // simply because the mock never took effect and there was no note to omit.
+ nodePty.throws = true
+ devices.current = { ceiling: 511, inUse: 62 } // healthy: the spawn is attempted, and fails
+
+ await expect(create()).rejects.toThrow(/npm run rebuild/)
+ expect(spawned).toHaveLength(1)
+ }
+ )
+
+ it.skipIf(!onDarwin)('never blames the architecture for a refusal it decided itself', async () => {
+ nodePty.throws = true // would fail if it were reached — it must not be
devices.current = { ceiling: 511, inUse: 515 }
- // `spawnHelperArchMismatch` outranks the device note in `spawnFailureHint`, so a machine that
- // ALSO has a mismatched helper would be told to rebuild node-pty — advice that cannot help,
- // for a helper this path never exec'd.
+ // Same mismatched helper as the control above, but this spawn is refused before node-pty. The
+ // arch note outranks the device note in `spawnFailureHint`, so consulting it here would tell a
+ // merely-full machine to rebuild node-pty — advice that cannot help, about a helper this path
+ // never exec'd.
+ await expect(create()).rejects.toThrow(/out of pty devices/)
await expect(create()).rejects.not.toThrow(/npm run rebuild/)
await expect(create()).rejects.not.toThrow(/architecture/)
+ expect(spawned).toHaveLength(0)
})
it('spawns normally on a machine with devices to spare', async () => {
diff --git a/src/core/pty-typing.test.ts b/src/core/pty-typing.test.ts
index 825359a85..f6b8852e2 100644
--- a/src/core/pty-typing.test.ts
+++ b/src/core/pty-typing.test.ts
@@ -29,6 +29,21 @@ vi.mock('node-pty', () => ({
const ALICE = 7
const BOB = 9
+/**
+ * A machine with pty devices to spare, always.
+ *
+ * Without this the real probe runs a `readdir('/dev')` against the DEVELOPER's host, and
+ * `spawnSession`'s pre-flight refuses every create once that host is within `PTY_DEVICE_HEADROOM`
+ * of its own `kern.tty.ptmx_max` — which a machine running this app all day genuinely reaches (511
+ * on macOS; this one sits in the 480s). Nothing below is about device pressure, so it is pinned
+ * healthy rather than left to depend on who is running the suite and how many terminals they have
+ * open. The pressure behaviour itself is tested in pty-spawn-preflight.test.ts.
+ */
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
describe('typing attribution', () => {
let fake: FakePlatform
beforeEach(() => {