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.

feat(pty): warn before kern.tty.ptmx_max, and offer to raise it

enes353486abdaca
diff --git a/src/core/pty-devices.test.ts b/src/core/pty-devices.test.ts
index e03ce7619..023cec2cc 100644
--- a/src/core/pty-devices.test.ts
+++ b/src/core/pty-devices.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import os from 'os'
import {
PTY_DEVICE_HEADROOM,
+ invalidatePtyCeiling,
ptyDevicesExhausted,
readPtyDevices,
spawnFailureHint
@@ -74,4 +75,12 @@ describe('readPtyDevices', () => {
// diagnostic says nothing rather than counting the wrong thing.
if (os.platform() !== 'darwin') expect(d).toEqual({ ceiling: null, inUse: null })
})
+
+ it('invalidatePtyCeiling makes the next read re-measure instead of trusting the cache', () => {
+ // The "Fix automatically…" button changes `kern.tty.ptmx_max` under us; the cached value would
+ // otherwise keep the banner up for another minute after the machine was already fixed.
+ expect(() => invalidatePtyCeiling()).not.toThrow()
+ const d = readPtyDevices()
+ expect(d.ceiling === null || d.ceiling > 0).toBe(true)
+ })
})
diff --git a/src/core/pty-devices.ts b/src/core/pty-devices.ts
index 73f05c606..e82640f72 100644
--- a/src/core/pty-devices.ts
+++ b/src/core/pty-devices.ts
@@ -132,6 +132,15 @@ export function spawnFailureHint(
)
}
+/**
+ * Forget the cached ceiling because something just CHANGED it (the "Fix automatically…" button's
+ * `sysctl -w`). Without this the TTL would keep serving the pre-fix number for up to a minute — and
+ * the pressure banner it feeds would keep saying the machine is full after it was emptied.
+ */
+export function invalidatePtyCeiling(): void {
+ ceiling = null
+}
+
/** Test seam: forget the cached ceiling so a test can pin the read itself. */
export function resetPtyDevicesCacheForTests(): void {
ceiling = null
diff --git a/src/core/pty-pressure.test.ts b/src/core/pty-pressure.test.ts
new file mode 100644
index 000000000..f8ec6358a
--- /dev/null
+++ b/src/core/pty-pressure.test.ts
@@ -0,0 +1,209 @@
+import { describe, it, expect, vi } from 'vitest'
+import {
+ classifyPtyPressure,
+ createPtyPressureMonitor,
+ readPtyPressure,
+ PTY_PRESSURE_ELEVATED_RATIO,
+ PTY_PRESSURE_INTERVAL_MS,
+ PTY_PRESSURE_RE_ANNOUNCE_MS
+} from './pty-pressure'
+import { PTY_DEVICE_HEADROOM } from './pty-devices'
+
+const devices = (inUse: number | null, ceiling: number | null = 500) => ({
+ ceiling,
+ inUse
+})
+
+describe('pty pressure classification', () => {
+ it('is none well below the ceiling', () => {
+ expect(classifyPtyPressure(devices(100))).toBe('none')
+ expect(classifyPtyPressure(devices(399))).toBe('none')
+ })
+
+ it('turns elevated exactly at the documented ratio of the ceiling', () => {
+ expect(PTY_PRESSURE_ELEVATED_RATIO).toBe(0.8)
+ expect(classifyPtyPressure(devices(400))).toBe('elevated') // 0.8 × 500
+ expect(classifyPtyPressure(devices(401))).toBe('elevated')
+ })
+
+ it('turns critical at the SAME line the spawn diagnosis calls exhausted', () => {
+ expect(classifyPtyPressure(devices(500 - PTY_DEVICE_HEADROOM))).toBe('critical')
+ expect(classifyPtyPressure(devices(500 - PTY_DEVICE_HEADROOM - 1))).toBe('elevated')
+ expect(classifyPtyPressure(devices(600))).toBe('critical') // already past it
+ })
+
+ it('critical wins on a ceiling so small the two bands overlap', () => {
+ // ceiling 10: elevated line is 8, critical line is 6 — 8 is BOTH, and the worse one must win.
+ expect(classifyPtyPressure(devices(8, 10))).toBe('critical')
+ })
+
+ it('an unmeasured ceiling or count is none, never a guess', () => {
+ expect(classifyPtyPressure(devices(400, null))).toBe('none')
+ expect(classifyPtyPressure(devices(null, 500))).toBe('none')
+ expect(classifyPtyPressure(devices(null, null))).toBe('none')
+ })
+
+ it('readPtyPressure carries the numbers the banner prints alongside the level', () => {
+ expect(readPtyPressure(() => devices(450))).toEqual({
+ level: 'elevated',
+ usage: 450,
+ ceiling: 500
+ })
+ expect(readPtyPressure(() => devices(null, null))).toEqual({
+ level: 'none',
+ usage: null,
+ ceiling: null
+ })
+ })
+})
+
+describe('pty pressure monitor', () => {
+ const monitor = (readings: Array<ReturnType<typeof devices>>, onLevel: (p: any) => void) => {
+ let i = 0
+ return createPtyPressureMonitor({
+ read: () => readings[Math.min(i++, readings.length - 1)],
+ intervalMs: 1000,
+ onLevel
+ })
+ }
+
+ it('says nothing while the machine is healthy', () => {
+ vi.useFakeTimers()
+ const on = vi.fn()
+ const m = monitor([devices(100)], on)
+ m.start()
+ vi.advanceTimersByTime(10_000)
+ expect(on).not.toHaveBeenCalled()
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('broadcasts on the transition into a level, then stays quiet while it holds', () => {
+ vi.useFakeTimers()
+ const on = vi.fn()
+ const m = monitor([devices(450)], on)
+ m.start()
+ vi.advanceTimersByTime(5000)
+ expect(on).toHaveBeenCalledTimes(1)
+ expect(on).toHaveBeenCalledWith({
+ level: 'elevated',
+ usage: 450,
+ ceiling: 500
+ })
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('re-announces a held level at most once per re-announce window', () => {
+ vi.useFakeTimers()
+ const on = vi.fn()
+ const m = monitor([devices(450)], on)
+ m.start()
+ vi.advanceTimersByTime(1000)
+ expect(on).toHaveBeenCalledTimes(1)
+ vi.advanceTimersByTime(PTY_PRESSURE_RE_ANNOUNCE_MS - 2000)
+ expect(on).toHaveBeenCalledTimes(1)
+ vi.advanceTimersByTime(2000)
+ expect(on).toHaveBeenCalledTimes(2)
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('a worsening level is reported immediately, not held for the window', () => {
+ vi.useFakeTimers()
+ const on = vi.fn()
+ const m = monitor([devices(450), devices(497)], on)
+ m.start()
+ vi.advanceTimersByTime(1000)
+ vi.advanceTimersByTime(1000)
+ expect(on).toHaveBeenCalledTimes(2)
+ expect(on).toHaveBeenLastCalledWith({
+ level: 'critical',
+ usage: 497,
+ ceiling: 500
+ })
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('reports the drop back to none ONCE so the banner clears, then holds its tongue', () => {
+ vi.useFakeTimers()
+ const on = vi.fn()
+ const m = monitor([devices(497), devices(100)], on)
+ m.start()
+ vi.advanceTimersByTime(1000)
+ vi.advanceTimersByTime(1000)
+ expect(on).toHaveBeenCalledTimes(2)
+ expect(on).toHaveBeenLastCalledWith({
+ level: 'none',
+ usage: 100,
+ ceiling: 500
+ })
+ vi.advanceTimersByTime(PTY_PRESSURE_RE_ANNOUNCE_MS * 2)
+ expect(on).toHaveBeenCalledTimes(2) // "none" is never re-announced
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('announce() force-fires a reading and takes over the dedupe state', () => {
+ vi.useFakeTimers()
+ const on = vi.fn()
+ const m = monitor([devices(497)], on)
+ m.start()
+ vi.advanceTimersByTime(1000)
+ expect(on).toHaveBeenCalledTimes(1)
+ // The fix handler re-broadcasts through the SAME funnel, so the next tick must not repeat it.
+ m.announce({ level: 'none', usage: 497, ceiling: 4096 })
+ expect(on).toHaveBeenCalledTimes(2)
+ expect(on).toHaveBeenLastCalledWith({
+ level: 'none',
+ usage: 497,
+ ceiling: 4096
+ })
+ vi.advanceTimersByTime(1000)
+ // The reader still says critical, which is now a CHANGE from the adopted 'none' → one fire.
+ expect(on).toHaveBeenCalledTimes(3)
+ vi.advanceTimersByTime(1000)
+ expect(on).toHaveBeenCalledTimes(3) // …and then it holds again
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('a throwing consumer does not break the monitor', () => {
+ vi.useFakeTimers()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ let calls = 0
+ const m = createPtyPressureMonitor({
+ read: () => devices(497),
+ intervalMs: 1000,
+ onLevel: () => {
+ calls++
+ throw new Error('destroyed window')
+ }
+ })
+ m.start()
+ expect(() => vi.advanceTimersByTime(1000)).not.toThrow()
+ vi.advanceTimersByTime(PTY_PRESSURE_RE_ANNOUNCE_MS)
+ expect(calls).toBe(2) // still firing after the throw
+ m.stop()
+ warn.mockRestore()
+ vi.useRealTimers()
+ })
+
+ it('stop() ends the checks for good', () => {
+ vi.useFakeTimers()
+ const on = vi.fn()
+ const m = monitor([devices(497)], on)
+ m.start()
+ vi.advanceTimersByTime(1000)
+ m.stop()
+ vi.advanceTimersByTime(600_000)
+ expect(on).toHaveBeenCalledTimes(1)
+ vi.useRealTimers()
+ })
+
+ it('defaults to a one-minute cadence', () => {
+ expect(PTY_PRESSURE_INTERVAL_MS).toBe(60_000)
+ expect(PTY_PRESSURE_RE_ANNOUNCE_MS).toBe(300_000)
+ })
+})
diff --git a/src/core/pty-pressure.ts b/src/core/pty-pressure.ts
new file mode 100644
index 000000000..5c54aa384
--- /dev/null
+++ b/src/core/pty-pressure.ts
@@ -0,0 +1,128 @@
+// Pty-device pressure: the WARNING that was missing when the 2026-08-11 field incident hit.
+//
+// We already diagnose the wall correctly once it is hit (pty-devices.ts writes the real sentence
+// into the spawn failure), and we already have a session reaper — but the reaper only woke on
+// MEMORY pressure, and during the incident RAM was plentiful while `/dev/ttys*` was full. So the
+// machine walked into a hard stop with nothing said and nothing reclaimed.
+//
+// This module is the missing signal, and only the signal: pure classification plus a timer that
+// reports LEVEL CHANGES. What each shell does with a level (banner, reaper sweep) is the shell's
+// business — same split as memory-pressure.ts, whose cadence/dedupe design this deliberately
+// copies rather than reinventing.
+
+import { readPtyDevices, ptyDevicesExhausted, type PtyDevices } from './pty-devices'
+import type { PtyPressure, PtyPressureLevel } from '@shared/types'
+
+/**
+ * Where "getting full" starts: 80% of the ceiling.
+ *
+ * A default macOS ceiling is 511 devices, so this is ~409 — a number no ordinary session reaches
+ * (the incident host sat at 515 with 62 app PTYs, 18 tmux sessions and ~19 ssh children). It buys
+ * roughly a hundred devices of runway, which is many terminals' worth of time to act, while
+ * staying far enough from normal use that the banner is not wallpaper.
+ */
+export const PTY_PRESSURE_ELEVATED_RATIO = 0.8
+
+/**
+ * How often the level is re-measured.
+ *
+ * One `readdir('/dev')` (the ceiling is already cached in pty-devices), so the cost is nil — but
+ * the condition it watches builds over minutes to hours, never in a second, and the memory monitor
+ * beside it is already the fast lane at 30s. A minute is the slowest cadence that still puts the
+ * banner up while there is runway left to use.
+ */
+export const PTY_PRESSURE_INTERVAL_MS = 60_000
+
+/**
+ * How long a HELD level stays quiet before it is said again.
+ *
+ * Five minutes, not one: unlike memory pressure — whose re-fire drives idempotent reclaim levers
+ * the user never sees — a re-announce here re-raises a BANNER the user may have just dismissed.
+ * Long enough that dismissing means something, short enough that a user who dismissed it and then
+ * left the machine climbing is reminded before the wall. A level CHANGE always fires immediately;
+ * `none` is never re-announced (there is nothing to re-say — the banner is already gone).
+ */
+export const PTY_PRESSURE_RE_ANNOUNCE_MS = 300_000
+
+/**
+ * Which band a device count falls in. Pure, so the boundaries can be pinned.
+ *
+ * `critical` reuses `ptyDevicesExhausted` rather than a second threshold of its own: the banner
+ * must turn red at exactly the line the spawn error calls "out of pty devices", or the two would
+ * contradict each other on the same machine at the same moment. It is checked FIRST because on a
+ * small ceiling the two bands overlap and the worse reading is the true one.
+ *
+ * Unmeasured (non-darwin, or a sysctl/readdir that failed) ⇒ `none`: a guess must degrade to
+ * silence, never to an alarm — same rule as the spawn hint.
+ */
+export function classifyPtyPressure(d: PtyDevices): PtyPressureLevel {
+ if (d.ceiling === null || d.inUse === null) return 'none'
+ if (ptyDevicesExhausted(d)) return 'critical'
+ return d.inUse >= d.ceiling * PTY_PRESSURE_ELEVATED_RATIO ? 'elevated' : 'none'
+}
+
+/** One reading: the level plus the two numbers the banner prints ("N of M pty devices"). */
+export function readPtyPressure(read: () => PtyDevices = readPtyDevices): PtyPressure {
+ const d = read()
+ return { level: classifyPtyPressure(d), usage: d.inUse, ceiling: d.ceiling }
+}
+
+export interface PtyPressureMonitor {
+ start(): void
+ stop(): void
+ /** The current reading, without touching the dedupe state. */
+ check(): PtyPressure
+ /**
+ * Report a reading through the same funnel a tick uses, unconditionally, and adopt it as the
+ * held level. The "Fix automatically…" handler uses this so the banner clears the instant the
+ * limit is raised, without the next tick then repeating what it just said.
+ */
+ announce(p: PtyPressure): void
+}
+
+export function createPtyPressureMonitor(opts: {
+ read?: () => PtyDevices
+ intervalMs?: number
+ reAnnounceMs?: number
+ onLevel: (p: PtyPressure) => void
+}): PtyPressureMonitor {
+ const read = opts.read ?? readPtyDevices
+ const reAnnounceMs = opts.reAnnounceMs ?? PTY_PRESSURE_RE_ANNOUNCE_MS
+ let timer: ReturnType<typeof setInterval> | null = null
+ // Starting at 'none' is what makes a healthy machine silent: there is no transition to report.
+ let held: PtyPressureLevel = 'none'
+ let heldAt = 0
+
+ const fire = (p: PtyPressure): void => {
+ held = p.level
+ heldAt = Date.now()
+ // A consumer throw must never take the timer down with it (the responders send to a possibly
+ // destroyed window and sweep the reaper) — same backstop as memory-pressure's onPressure.
+ try {
+ opts.onLevel(p)
+ } catch (e) {
+ console.warn('[pty-pressure] onLevel threw', e)
+ }
+ }
+
+ const tick = (): void => {
+ const p = readPtyPressure(read)
+ if (p.level !== held) return fire(p)
+ if (p.level === 'none') return
+ if (Date.now() - heldAt >= reAnnounceMs) fire(p)
+ }
+
+ return {
+ check: () => readPtyPressure(read),
+ announce: fire,
+ start(): void {
+ if (timer) return
+ timer = setInterval(tick, opts.intervalMs ?? PTY_PRESSURE_INTERVAL_MS)
+ timer.unref?.()
+ },
+ stop(): void {
+ if (timer) clearInterval(timer)
+ timer = null
+ }
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index c0f08bbeb..5598bef41 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -70,6 +70,8 @@ import { createRemoteGrantsCache } from '../core/remote-push-grants'
import { createAckSweeper } from '../core/ack-sweep'
import { createSessionReaper } from '../core/session-budget'
import { createMemoryPressureMonitor } from '../core/memory-pressure'
+import { createPtyPressureMonitor } from '../core/pty-pressure'
+import { registerPtmxLimitHandler } from './ptmx-limit'
import { getDeviceId } from '../core/device-id'
import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
import { initCanvasSync } from '../core/canvas-sync'
@@ -1547,6 +1549,24 @@ app.whenReady().then(async () => {
if (severity === 'critical') void sessionReaper.sweep()
}
}).start()
+ // Pty-device pressure (core/pty-pressure.ts): the OTHER way this machine runs out, and the one
+ // that actually happened. The memory monitor above could not see it — during the 2026-08-11
+ // incident RAM was plentiful while `/dev/ttys*` was full, so the reaper never woke and the user
+ // got no warning at all, just terminals that stopped opening. Same shape as the memory leg: tell
+ // the renderer (which raises a banner) on every band change, and sweep the reaper NOW on
+ // critical — a reaped detached session returns its pty device, which is exactly the resource in
+ // short supply. Transitions only, re-announced at most every five minutes.
+ const ptyPressure = createPtyPressureMonitor({
+ onLevel: (reading) => {
+ sendToMain(IPC.ptyPressure, reading)
+ if (reading.level === 'critical') void sessionReaper.sweep()
+ }
+ })
+ ptyPressure.start()
+ // The banner's "Fix automatically…" button. Registered, never called on our own initiative: it
+ // raises `kern.tty.ptmx_max` behind macOS's own admin-password dialog. Its success re-announces
+ // through the monitor's funnel, so the banner clears without waiting out the next tick.
+ registerPtmxLimitHandler(corePlatform, { announce: (reading) => ptyPressure.announce(reading) })
const ackSweeper = createAckSweeper({
handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }
})
diff --git a/src/main/ptmx-limit.test.ts b/src/main/ptmx-limit.test.ts
new file mode 100644
index 000000000..0a6ffb8a4
--- /dev/null
+++ b/src/main/ptmx-limit.test.ts
@@ -0,0 +1,195 @@
+import { describe, it, expect } from 'vitest'
+import { IPC } from '@shared/ipc'
+import { fakePlatform } from '../core/platform-fake'
+import {
+ PTMX_DAEMON_LABEL,
+ PTMX_MIN_TARGET,
+ PTMX_PLIST_PATH,
+ appleScriptQuote,
+ isUserCancel,
+ osascriptArgs,
+ ptmxPlist,
+ ptmxTarget,
+ raiseLimitScript,
+ registerPtmxLimitHandler
+} from './ptmx-limit'
+
+describe('ptmx target', () => {
+ it('doubles the current ceiling but never asks for less than the floor', () => {
+ expect(PTMX_MIN_TARGET).toBe(2048)
+ expect(ptmxTarget(511)).toBe(2048) // the macOS default: floor wins
+ expect(ptmxTarget(2048)).toBe(4096)
+ expect(ptmxTarget(4096)).toBe(8192)
+ })
+ it('an unmeasured ceiling still yields the floor', () => {
+ expect(ptmxTarget(null)).toBe(2048)
+ expect(ptmxTarget(0)).toBe(2048)
+ })
+})
+
+describe('LaunchDaemon plist', () => {
+ const plist = ptmxPlist(4096)
+ it('is a well-formed plist naming this app and the sysctl to re-apply', () => {
+ expect(plist.startsWith('<?xml version="1.0" encoding="UTF-8"?>')).toBe(true)
+ expect(plist).toContain('<key>Label</key>')
+ expect(plist).toContain(`<string>${PTMX_DAEMON_LABEL}</string>`)
+ expect(plist).toContain('<string>/usr/sbin/sysctl</string>')
+ expect(plist).toContain('<string>kern.tty.ptmx_max=4096</string>')
+ expect(plist).toContain('<key>RunAtLoad</key>')
+ expect(plist.trimEnd().endsWith('</plist>')).toBe(true)
+ })
+ it('carries no line that could close the heredoc it travels in', () => {
+ expect(plist.split('\n').some((l) => l.trim() === 'NODETERM_PTMX_PLIST')).toBe(false)
+ })
+ it('carries no tab, so the AppleScript literal needs no tab escape', () => {
+ expect(plist).not.toContain('\t')
+ })
+})
+
+describe('AppleScript string escaping', () => {
+ it('escapes backslashes before quotes, and never emits a raw newline', () => {
+ expect(appleScriptQuote('a"b')).toBe('"a\\"b"')
+ expect(appleScriptQuote('a\\b')).toBe('"a\\\\b"')
+ // A backslash followed by a quote must not turn into an escaped quote's escape.
+ expect(appleScriptQuote('a\\"b')).toBe('"a\\\\\\"b"')
+ expect(appleScriptQuote('a\nb')).toBe('"a\\nb"')
+ expect(appleScriptQuote('a\r\nb')).toBe('"a\\r\\nb"')
+ expect(appleScriptQuote('x')).not.toMatch(/\n/)
+ })
+})
+
+describe('the privileged shell script', () => {
+ const script = raiseLimitScript(4096)
+ it('sets the limit NOW and installs the LaunchDaemon that re-applies it at boot', () => {
+ expect(script).toContain('/usr/sbin/sysctl -w kern.tty.ptmx_max=4096')
+ expect(script).toContain(`> ${PTMX_PLIST_PATH} <<'NODETERM_PTMX_PLIST'`)
+ expect(script).toContain(ptmxPlist(4096))
+ expect(script).toContain(`/bin/launchctl load -w ${PTMX_PLIST_PATH}`)
+ })
+ it('is re-runnable: root-owns the plist and unloads any previous copy first', () => {
+ expect(script).toContain(`/usr/sbin/chown root:wheel ${PTMX_PLIST_PATH}`)
+ expect(script).toContain(`/bin/chmod 644 ${PTMX_PLIST_PATH}`)
+ expect(script.indexOf('launchctl unload')).toBeLessThan(script.indexOf('launchctl load'))
+ expect(script).toMatch(/launchctl unload .*\|\| true/)
+ })
+ it('aborts on the first failing step rather than half-installing', () => {
+ expect(script.split('\n')[0]).toBe('set -e')
+ })
+})
+
+describe('osascript invocation', () => {
+ const args = osascriptArgs(4096)
+ it('is ONE -e script that runs the shell script with administrator privileges', () => {
+ expect(args[0]).toBe('-e')
+ expect(args).toHaveLength(2)
+ expect(args[1].startsWith('do shell script "')).toBe(true)
+ expect(args[1].endsWith('" with administrator privileges')).toBe(true)
+ // The whole thing must stay on one line: `osascript -e` takes a line of AppleScript.
+ expect(args[1]).not.toMatch(/\n/)
+ })
+ it('carries the script through the escape, not raw', () => {
+ expect(args[1]).toContain(appleScriptQuote(raiseLimitScript(4096)).slice(1, -1))
+ })
+})
+
+describe('user cancel detection', () => {
+ it('recognises the dismissed password dialog', () => {
+ expect(isUserCancel('execution error: User canceled. (-128)')).toBe(true)
+ expect(isUserCancel('User cancelled.')).toBe(true)
+ })
+ it('does not swallow real failures', () => {
+ expect(isUserCancel('osascript: command not found')).toBe(false)
+ expect(isUserCancel('')).toBe(false)
+ })
+})
+
+describe('the raise-limit IPC handler', () => {
+ const setup = (
+ over: {
+ run?: (args: string[]) => Promise<{ ok: true } | { ok: false; message: string }>
+ platform?: NodeJS.Platform
+ inUse?: number | null
+ ceiling?: number | null
+ } = {}
+ ) => {
+ const p = fakePlatform()
+ const announced: any[] = []
+ const runs: string[][] = []
+ registerPtmxLimitHandler(p, {
+ platform: over.platform ?? 'darwin',
+ read: () => ({ ceiling: over.ceiling ?? 511, inUse: over.inUse ?? 508 }),
+ run: async (args) => {
+ runs.push(args)
+ return over.run ? over.run(args) : { ok: true as const }
+ },
+ announce: (r) => announced.push(r)
+ })
+ return {
+ p,
+ announced,
+ runs,
+ call: () => p.handlers[IPC.ptyRaiseDeviceLimit]()
+ }
+ }
+
+ it('registers on the documented channel', () => {
+ const { p } = setup()
+ expect(typeof p.handlers[IPC.ptyRaiseDeviceLimit]).toBe('function')
+ })
+
+ it('runs exactly one osascript for the doubled-or-floor target', async () => {
+ const { call, runs } = setup({ ceiling: 4096 })
+ await call()
+ expect(runs).toHaveLength(1)
+ expect(runs[0]).toEqual(osascriptArgs(8192))
+ })
+
+ it('re-announces the level from the ceiling it just set, so the banner clears itself', async () => {
+ const { call, announced } = setup()
+ await expect(call()).resolves.toEqual({ ok: true, ceiling: 2048 })
+ expect(announced).toEqual([{ level: 'none', usage: 508, ceiling: 2048 }])
+ })
+
+ it('a cancelled password prompt is a graceful, non-retrying error and says nothing new', async () => {
+ const { call, announced } = setup({
+ run: async () => ({
+ ok: false,
+ message: 'execution error: User canceled. (-128)'
+ })
+ })
+ const res: any = await call()
+ expect(res.ok).toBe(false)
+ expect(res.canceled).toBe(true)
+ expect(announced).toEqual([]) // the banner stays exactly as it was
+ })
+
+ it('a real failure comes back as an error the renderer can show', async () => {
+ const { call, announced } = setup({
+ run: async () => ({ ok: false, message: 'sysctl: no such' })
+ })
+ const res: any = await call()
+ expect(res.ok).toBe(false)
+ expect(res.canceled).toBeUndefined()
+ expect(res.error).toContain('sysctl: no such')
+ expect(announced).toEqual([])
+ })
+
+ it('never runs anything off macOS', async () => {
+ const { call, runs } = setup({ platform: 'linux' })
+ const res: any = await call()
+ expect(res.ok).toBe(false)
+ expect(runs).toEqual([])
+ })
+
+ it('never spawns osascript on its own — only the explicit invoke does', () => {
+ const { runs } = setup()
+ expect(runs).toEqual([])
+ })
+})
+
+describe('IPC channels for pty pressure', () => {
+ it('live in the pty namespace', () => {
+ expect(IPC.ptyPressure).toBe('pty:pressure')
+ expect(IPC.ptyRaiseDeviceLimit).toBe('pty:raise-device-limit')
+ })
+})
diff --git a/src/main/ptmx-limit.ts b/src/main/ptmx-limit.ts
new file mode 100644
index 000000000..a6bd7ab49
--- /dev/null
+++ b/src/main/ptmx-limit.ts
@@ -0,0 +1,199 @@
+// "Fix automatically…": raise this Mac's pty-device ceiling without opening a terminal.
+//
+// The 2026-08-11 field incident ended at `kern.tty.ptmx_max` (511 by default). The spawn error now
+// says so and names the `sudo sysctl -w` cure — but a cure phrased as a shell command is not a cure
+// for the users this app is for, and a bare `sysctl -w` is forgotten at the next reboot anyway. So:
+// ONE privileged step that both raises the limit NOW and installs a LaunchDaemon that re-applies it
+// at every boot.
+//
+// Rules this file exists to keep:
+// - the privileged step runs ONLY from the explicit button click. Nothing here is scheduled,
+// retried or run on boot — an app that asks for an admin password unprompted has already lost
+// the user's trust, however good its reason.
+// - the password dialog is macOS's own (`with administrator privileges`). We never see, prompt
+// for, or store the password, and a dismissed dialog is an ordinary, non-retrying outcome.
+// - the command is BUILT by pure functions and pinned by tests. It runs as root; "probably
+// escaped right" is not a standard that survives contact with a plist full of XML quotes.
+
+import { execFile } from 'child_process'
+import { IPC } from '@shared/ipc'
+import type { PtyLimitFixResult, PtyPressure } from '@shared/types'
+import type { CorePlatform } from '../core/platform'
+import { classifyPtyPressure } from '../core/pty-pressure'
+import { invalidatePtyCeiling, readPtyDevices, type PtyDevices } from '../core/pty-devices'
+
+export const PTMX_DAEMON_LABEL = 'com.nodeterm.ptmx-max'
+export const PTMX_PLIST_PATH = `/Library/LaunchDaemons/${PTMX_DAEMON_LABEL}.plist`
+
+/**
+ * The smallest ceiling worth asking for an admin password over.
+ *
+ * 2048 is four times the macOS default and several times the worst real usage we have measured
+ * (515 devices across 62 app PTYs, 18 tmux sessions and their ssh children). A pty device costs a
+ * few kilobytes of kernel memory only once it is actually opened, so a high ceiling is not a
+ * reservation — it is permission to keep working.
+ */
+export const PTMX_MIN_TARGET = 2048
+
+/** Where to move the ceiling to: double what this machine has, floored at PTMX_MIN_TARGET. */
+export function ptmxTarget(ceiling: number | null): number {
+ return Math.max(PTMX_MIN_TARGET, (ceiling ?? 0) * 2)
+}
+
+/** Heredoc delimiter the plist travels in — see raiseLimitScript. */
+const PLIST_HEREDOC = 'NODETERM_PTMX_PLIST'
+
+/**
+ * The LaunchDaemon that re-applies the sysctl at every boot. `sysctl -w` alone dies with the
+ * machine, and a user who paid an admin password once must not have to pay it again after a
+ * restart. RunAtLoad + a one-shot program: it sets the value and exits (no KeepAlive — a daemon
+ * relaunching a finished sysctl forever would be a bug, not persistence).
+ *
+ * Two-space indentation, deliberately: this string is escaped into an AppleScript literal, and
+ * keeping tabs out of it keeps the escape to quotes, backslashes and newlines.
+ */
+export function ptmxPlist(target: number): string {
+ return `<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>${PTMX_DAEMON_LABEL}</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>/usr/sbin/sysctl</string>
+ <string>kern.tty.ptmx_max=${target}</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+</dict>
+</plist>
+`
+}
+
+/**
+ * The /bin/sh script `do shell script` runs as root.
+ *
+ * The plist reaches disk through a QUOTED heredoc rather than as XML inline in the osascript
+ * string: the XML is full of double quotes, and nesting it inside an AppleScript literal inside a
+ * shell command line is exactly the kind of three-layer quoting that works until someone changes
+ * one character. Quoted (`<<'…'`) so the shell expands nothing inside it.
+ *
+ * Re-runnable on purpose — a user may click the button again after raising the limit once:
+ * `chown`/`chmod` restate ownership launchd requires, and the unload-then-load pair replaces an
+ * already-installed daemon instead of failing on it.
+ */
+export function raiseLimitScript(target: number): string {
+ return [
+ 'set -e', // never leave a half-installed daemon behind
+ `/usr/sbin/sysctl -w kern.tty.ptmx_max=${target}`,
+ `/bin/cat > ${PTMX_PLIST_PATH} <<'${PLIST_HEREDOC}'`,
+ ptmxPlist(target).trimEnd(),
+ PLIST_HEREDOC,
+ `/usr/sbin/chown root:wheel ${PTMX_PLIST_PATH}`,
+ `/bin/chmod 644 ${PTMX_PLIST_PATH}`,
+ `/bin/launchctl unload ${PTMX_PLIST_PATH} 2>/dev/null || true`,
+ `/bin/launchctl load -w ${PTMX_PLIST_PATH}`,
+ ''
+ ].join('\n')
+}
+
+/**
+ * Quote a string as an AppleScript literal. Backslash FIRST (escaping it after the quotes would
+ * re-escape the escapes we just added), then quotes, then the line breaks — `osascript -e` takes
+ * one LINE of AppleScript, so a raw newline would truncate the script rather than run it.
+ */
+export function appleScriptQuote(s: string): string {
+ const body = s
+ .replace(/\\/g, '\\\\')
+ .replace(/"/g, '\\"')
+ .replace(/\r/g, '\\r')
+ .replace(/\n/g, '\\n')
+ return `"${body}"`
+}
+
+/** The full `osascript` argv. One `-e`, one statement, one password prompt. */
+export function osascriptArgs(target: number): string[] {
+ return [
+ '-e',
+ `do shell script ${appleScriptQuote(raiseLimitScript(target))} with administrator privileges`
+ ]
+}
+
+/**
+ * Did the user dismiss macOS's password dialog? osascript reports that as error -128
+ * ("User canceled."), which is a DECISION, not a failure: no error toast, no retry, banner stays.
+ */
+export function isUserCancel(message: string): boolean {
+ return /-128\b/.test(message) || /user cancel(l)?ed/i.test(message)
+}
+
+export type OsascriptRunner = (
+ args: string[]
+) => Promise<{ ok: true } | { ok: false; message: string }>
+
+const defaultRunner: OsascriptRunner = (args) =>
+ new Promise((resolve) => {
+ execFile('osascript', args, { timeout: 5 * 60_000 }, (err, _stdout, stderr) => {
+ // The password dialog has no timeout of its own; the cap above is a backstop for a wedged
+ // osascript, generous enough that a user hunting for their password never trips it.
+ if (!err) return resolve({ ok: true })
+ resolve({
+ ok: false,
+ message: String(stderr || err.message || err).trim()
+ })
+ })
+ })
+
+export interface PtmxLimitDeps {
+ /** Re-broadcast a reading through the pressure monitor's funnel (so the banner clears). */
+ announce: (p: PtyPressure) => void
+ read?: () => PtyDevices
+ run?: OsascriptRunner
+ platform?: NodeJS.Platform
+}
+
+/**
+ * Register the button's handler. Invoke-only: the privileged command exists nowhere else in the
+ * app, and this function starts no timer.
+ */
+export function registerPtmxLimitHandler(platform: CorePlatform, deps: PtmxLimitDeps): void {
+ const read = deps.read ?? readPtyDevices
+ const run = deps.run ?? defaultRunner
+ const os = deps.platform ?? process.platform
+
+ platform.handle(IPC.ptyRaiseDeviceLimit, async (): Promise<PtyLimitFixResult> => {
+ if (os !== 'darwin') {
+ return {
+ ok: false,
+ error: 'Raising the pty-device limit is only supported on macOS.'
+ }
+ }
+ const before = read()
+ const target = ptmxTarget(before.ceiling)
+ const res = await run(osascriptArgs(target))
+ if (!res.ok) {
+ return isUserCancel(res.message)
+ ? {
+ ok: false,
+ canceled: true,
+ error: 'Cancelled — the terminal limit was not changed.'
+ }
+ : {
+ ok: false,
+ error: `Could not raise the terminal limit: ${res.message}`
+ }
+ }
+ // The sysctl succeeded, so `target` IS the new ceiling — more current than anything we could
+ // read back, since pty-devices caches the ceiling for a minute. Announce from it directly, and
+ // drop that cache so the monitor's next tick measures the machine rather than its own memory.
+ invalidatePtyCeiling()
+ const after: PtyDevices = { ceiling: target, inUse: before.inUse }
+ deps.announce({
+ level: classifyPtyPressure(after),
+ usage: after.inUse,
+ ceiling: target
+ })
+ return { ok: true, ceiling: target }
+ })
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index cd2b9fdf1..b97307da6 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -6,6 +6,7 @@ import type {
NodeTerminalApi,
Project,
PtyCreateOptions,
+ PtyPressure,
RecycledInfo,
RelayPeerPending,
RemoteUsageQuery,
@@ -555,6 +556,12 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.appMemoryPressure, handler)
return () => ipcRenderer.removeListener(IPC.appMemoryPressure, handler)
},
+ onPtyPressure: (listener) => {
+ const handler = (_e: unknown, reading: PtyPressure) => listener(reading)
+ ipcRenderer.on(IPC.ptyPressure, handler)
+ return () => ipcRenderer.removeListener(IPC.ptyPressure, handler)
+ },
+ raisePtyDeviceLimit: () => ipcRenderer.invoke(IPC.ptyRaiseDeviceLimit),
answerPermission: (payload) => ipcRenderer.invoke(IPC.agentAnswerPermission, payload),
ackDone: (nodeId) => {
void ipcRenderer.invoke(IPC.agentAckDone, nodeId)
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 55b260318..2a1960a40 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -341,6 +341,16 @@ export function buildStubApi(): Omit<
// on its own terms; pushing our levers over the wire would fight it, not help it. Deliberate
// no-op, not an oversight.
onMemoryPressure: noopUnsub,
+ // Same asymmetry, one step further: the desktop's pty-pressure banner exists to offer "Fix
+ // automatically…", which ends in macOS's admin-password dialog on the HOST's physical display.
+ // A browser tab cannot answer that prompt, so the host keeps the reaper leg and says nothing
+ // here (see the note beside createPtyPressureMonitor in src/server/index.ts). The fix itself
+ // rejects rather than pretending, so a stray call can never look like it worked.
+ onPtyPressure: noopUnsub,
+ raisePtyDeviceLimit: async () => ({
+ ok: false as const,
+ error: 'Raising the terminal limit must be done on the machine running the server.'
+ }),
onAgentControl: noopUnsub,
sendAgentControlResult: noop
} satisfies Omit<
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index f774c7354..a904446d6 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -125,6 +125,7 @@ import { isSpaceRelease, spacePanKeydown } from '../lib/spacePan'
import { UpdateCard } from '../components/UpdateCard'
import { AnnouncementBanner } from '../components/AnnouncementBanner'
import { TmuxBanner } from '../components/TmuxBanner'
+import { PtyPressureBanner } from '../components/PtyPressureBanner'
import { ConflictBar } from '../components/ConflictBar'
import { ConfirmDialog } from '../components/ConfirmDialog'
import { ConsentNotice } from '../remote/ConsentNotice'
@@ -7808,6 +7809,9 @@ export function Canvas() {
<div className="top-banners">
<AnnouncementBanner />
<TmuxBanner onInstall={runInTerminal} />
+ {/* This MACHINE is running out of pty devices — subscribes for itself; a failed
+ "Fix automatically…" lands in the same notice strip as every other async op. */}
+ <PtyPressureBanner onError={(text) => setNotice({ kind: 'error', text })} />
{migrationNote && (
<div className="announce-banner announce-banner--info">
<span className="announce-banner__dot" />
diff --git a/src/renderer/components/PtyPressureBanner.test.tsx b/src/renderer/components/PtyPressureBanner.test.tsx
new file mode 100644
index 000000000..55f944c4a
--- /dev/null
+++ b/src/renderer/components/PtyPressureBanner.test.tsx
@@ -0,0 +1,164 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { describe, expect, it, vi, beforeEach } from 'vitest'
+import type { PtyPressure, PtyLimitFixResult } from '@shared/types'
+import { PtyPressureBanner, ptyPressureCopy } from './PtyPressureBanner'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+describe('ptyPressureCopy', () => {
+ it('names the two numbers and the way back, without shell instructions', () => {
+ const copy = ptyPressureCopy({
+ level: 'elevated',
+ usage: 420,
+ ceiling: 511
+ })!
+ expect(copy.body).toBe(
+ 'This machine is close to its terminal limit (420 of 511 pty devices). ' +
+ 'Deleting sessions from Recently closed returns them.'
+ )
+ expect(copy.body).not.toContain('sysctl')
+ })
+
+ it('says the terminals have ALREADY stopped opening once it is critical', () => {
+ const copy = ptyPressureCopy({
+ level: 'critical',
+ usage: 509,
+ ceiling: 511
+ })!
+ expect(copy.body).toContain('has run out of terminal capacity (509 of 511 pty devices)')
+ expect(copy.body).toContain('New terminals will fail to open')
+ expect(copy.body).toContain('Deleting sessions from Recently closed returns them.')
+ })
+
+ it('escalates the strip styling with the band', () => {
+ expect(ptyPressureCopy({ level: 'elevated', usage: 420, ceiling: 511 })!.tone).toBe('warning')
+ expect(ptyPressureCopy({ level: 'critical', usage: 509, ceiling: 511 })!.tone).toBe('danger')
+ })
+
+ it('has nothing to say at none, or when the numbers were never measured', () => {
+ expect(ptyPressureCopy({ level: 'none', usage: 10, ceiling: 511 })).toBeNull()
+ expect(ptyPressureCopy({ level: 'critical', usage: null, ceiling: null })).toBeNull()
+ })
+})
+
+describe('PtyPressureBanner', () => {
+ const reading = (level: PtyPressure['level']): PtyPressure => ({
+ level,
+ usage: 509,
+ ceiling: 511
+ })
+
+ let listener: ((r: PtyPressure) => void) | null = null
+ let fix: () => Promise<PtyLimitFixResult>
+
+ beforeEach(() => {
+ listener = null
+ fix = vi.fn(async () => ({ ok: true as const, ceiling: 2048 }))
+ ;(window as any).nodeTerminal = {
+ onPtyPressure: (l: (r: PtyPressure) => void) => {
+ listener = l
+ return () => {
+ listener = null
+ }
+ },
+ raisePtyDeviceLimit: () => fix()
+ }
+ })
+
+ const mount = (onError = vi.fn()) => {
+ const host = document.createElement('div')
+ const root = createRoot(host)
+ act(() => root.render(<PtyPressureBanner isMac onError={onError} />))
+ return { host, root, onError }
+ }
+
+ it('shows nothing until the shell reports pressure', () => {
+ const { host } = mount()
+ expect(host.querySelector('.announce-banner')).toBeNull()
+ })
+
+ it('raises a warning banner with the fix button on macOS', () => {
+ const { host } = mount()
+ act(() => listener!(reading('elevated')))
+ expect(host.textContent).toContain('509 of 511')
+ expect([...host.querySelectorAll('button')].map((b) => b.textContent)).toContain(
+ 'Fix automatically…'
+ )
+ })
+
+ it('offers no fix button off macOS — only the informational text', () => {
+ const host = document.createElement('div')
+ const root = createRoot(host)
+ act(() => root.render(<PtyPressureBanner isMac={false} onError={vi.fn()} />))
+ act(() => listener!(reading('critical')))
+ expect(host.textContent).toContain('pty devices')
+ expect([...host.querySelectorAll('button')].map((b) => b.textContent)).not.toContain(
+ 'Fix automatically…'
+ )
+ })
+
+ it('a level that falls back to none takes the banner down, dismissal or not', () => {
+ const { host } = mount()
+ act(() => listener!(reading('critical')))
+ expect(host.querySelector('.announce-banner')).not.toBeNull()
+ act(() => listener!({ level: 'none', usage: 40, ceiling: 2048 }))
+ expect(host.querySelector('.announce-banner')).toBeNull()
+ })
+
+ it('the ✕ hides it, and a WORSENING level brings it back', () => {
+ const { host } = mount()
+ act(() => listener!(reading('elevated')))
+ act(() => (host.querySelector('.announce-banner__close') as HTMLButtonElement).click())
+ expect(host.querySelector('.announce-banner')).toBeNull()
+ act(() => listener!(reading('elevated')))
+ expect(host.querySelector('.announce-banner')).toBeNull() // same level: stays dismissed
+ act(() => listener!(reading('critical')))
+ expect(host.querySelector('.announce-banner')).not.toBeNull()
+ })
+
+ it('the fix button invokes ONCE and reports nothing on success (the re-broadcast clears it)', async () => {
+ const { host, onError } = mount()
+ act(() => listener!(reading('critical')))
+ const btn = [...host.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Fix automatically…'
+ ) as HTMLButtonElement
+ await act(async () => {
+ btn.click()
+ })
+ expect(fix).toHaveBeenCalledTimes(1)
+ expect(onError).not.toHaveBeenCalled()
+ })
+
+ it('a cancelled password dialog is silent — no toast, no retry loop', async () => {
+ fix = vi.fn(async () => ({
+ ok: false as const,
+ canceled: true,
+ error: 'Cancelled'
+ }))
+ const { host, onError } = mount()
+ act(() => listener!(reading('critical')))
+ const btn = [...host.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Fix automatically…'
+ ) as HTMLButtonElement
+ await act(async () => {
+ btn.click()
+ })
+ expect(onError).not.toHaveBeenCalled()
+ expect(host.querySelector('.announce-banner')).not.toBeNull() // banner stays
+ })
+
+ it('a real failure goes to the caller error surface', async () => {
+ fix = vi.fn(async () => ({ ok: false as const, error: 'sysctl exploded' }))
+ const { host, onError } = mount()
+ act(() => listener!(reading('critical')))
+ const btn = [...host.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Fix automatically…'
+ ) as HTMLButtonElement
+ await act(async () => {
+ btn.click()
+ })
+ expect(onError).toHaveBeenCalledWith('sysctl exploded')
+ })
+})
diff --git a/src/renderer/components/PtyPressureBanner.tsx b/src/renderer/components/PtyPressureBanner.tsx
new file mode 100644
index 000000000..5738918f6
--- /dev/null
+++ b/src/renderer/components/PtyPressureBanner.tsx
@@ -0,0 +1,116 @@
+import { useEffect, useState } from 'react'
+import type { PtyPressure } from '@shared/types'
+import { isMacPlatform } from '../../shared/platform-utils'
+
+// The warning that was missing on 2026-08-11: the machine filled up its pty devices
+// (`kern.tty.ptmx_max`) and the first thing anyone learned about it was terminals refusing to
+// open. The shell now measures the pressure (core/pty-pressure.ts) and this strip says so while
+// there is still room to act — in the user's terms (terminals, sessions), not the kernel's.
+//
+// Its own component, subscribing for itself, for the same reason TmuxBanner is: Canvas.tsx is a
+// hot file that every other branch touches, and a banner is not canvas logic. The one thing it
+// cannot own is the error surface — failures belong in the same toast strip as every other async
+// canvas op — so that comes in as a prop.
+
+export interface PtyPressureCopy {
+ title: string
+ body: string
+ /** Drives the banner's severity styling (`announce-banner--<tone>`). */
+ tone: 'warning' | 'danger'
+}
+
+/**
+ * What the strip says, or `null` for "say nothing".
+ *
+ * Both bands end on the SAME sentence about Recently closed, because that is the one lever the
+ * user has that costs nothing and always works: a deleted session's tmux session ends, and its
+ * pty devices go back to the machine. What neither band says is `sysctl` — the button below is
+ * that sentence's replacement, and a user who can read a shell command already got it from the
+ * spawn error.
+ */
+export function ptyPressureCopy(p: PtyPressure): PtyPressureCopy | null {
+ if (p.level === 'none' || p.usage === null || p.ceiling === null) return null
+ const counts = `(${p.usage} of ${p.ceiling} pty devices)`
+ const recover = 'Deleting sessions from Recently closed returns them.'
+ if (p.level === 'critical') {
+ return {
+ tone: 'danger',
+ title: 'Out of terminal capacity',
+ body:
+ `This machine has run out of terminal capacity ${counts}. New terminals will fail to ` +
+ `open until some are returned. ${recover}`
+ }
+ }
+ return {
+ tone: 'warning',
+ title: 'Close to this machine’s terminal limit',
+ body: `This machine is close to its terminal limit ${counts}. ${recover}`
+ }
+}
+
+export function PtyPressureBanner({
+ onError,
+ isMac = isMacPlatform()
+}: {
+ /** Surface a FAILED fix the way the canvas surfaces every other async failure. */
+ onError: (message: string) => void
+ isMac?: boolean
+}): JSX.Element | null {
+ const [reading, setReading] = useState<PtyPressure | null>(null)
+ // Dismissal is per-LEVEL, not for the session: a user who waved away "close to the limit" has
+ // not agreed to hear nothing when the machine actually fills up.
+ const [dismissed, setDismissed] = useState<PtyPressure['level'] | null>(null)
+ const [busy, setBusy] = useState(false)
+
+ useEffect(() => {
+ // Optional-called: the Server Edition bridge declares this a documented no-op.
+ const off = window.nodeTerminal.onPtyPressure?.(setReading)
+ return () => off?.()
+ }, [])
+
+ const copy = reading ? ptyPressureCopy(reading) : null
+ if (!reading || !copy || dismissed === reading.level) return null
+
+ const fix = (): void => {
+ if (busy) return
+ setBusy(true)
+ // No optimistic clear: the banner comes down when the SHELL says the level dropped (the
+ // handler re-announces from the ceiling it just set), so what the user sees is the machine's
+ // state, never our hope for it. A cancelled password dialog is a decision, not a failure —
+ // it leaves the banner exactly as it was and nothing is retried.
+ void window.nodeTerminal
+ .raisePtyDeviceLimit?.()
+ .then((res) => {
+ if (!res.ok && !res.canceled) onError(res.error)
+ })
+ .catch((e: unknown) => onError(String((e as Error)?.message ?? e)))
+ .finally(() => setBusy(false))
+ }
+
+ return (
+ <div className={`announce-banner announce-banner--${copy.tone}`}>
+ <span className="announce-banner__dot" />
+ <div className="announce-banner__content">
+ <span className="announce-banner__title">{copy.title}</span>
+ <span className="announce-banner__body">{copy.body}</span>
+ </div>
+ {isMac && (
+ <button
+ className="announce-banner__btn"
+ title="Raises this Mac’s pty-device limit (kern.tty.ptmx_max) now and after every restart. macOS will ask for your password."
+ disabled={busy}
+ onClick={fix}
+ >
+ {busy ? 'Fixing…' : 'Fix automatically…'}
+ </button>
+ )}
+ <button
+ className="announce-banner__close"
+ title="Dismiss"
+ onClick={() => setDismissed(reading.level)}
+ >
+ ✕
+ </button>
+ </div>
+ )
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index cc37bbd76..ed5098565 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3187,6 +3187,12 @@ body,
border-left-color: var(--warn);
}
+/* One step past --warning, for a strip whose condition is already breaking things (the machine is
+ out of pty devices, so new terminals fail) rather than about to. */
+.announce-banner--danger {
+ border-left-color: var(--danger);
+}
+
.announce-banner__dot {
width: 8px;
height: 8px;
@@ -3203,6 +3209,10 @@ body,
background: var(--warn);
}
+.announce-banner--danger .announce-banner__dot {
+ background: var(--danger);
+}
+
.announce-banner__content {
display: flex;
flex-direction: column;
diff --git a/src/server/index.ts b/src/server/index.ts
index 1358948f8..648f17614 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -51,6 +51,7 @@ import { createGrantsAccessor } from '../core/push-grants'
import { createAckSweeper } from '../core/ack-sweep'
import { createSessionReaper } from '../core/session-budget'
import { createMemoryPressureMonitor } from '../core/memory-pressure'
+import { createPtyPressureMonitor } from '../core/pty-pressure'
import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
import { claudeConfigDirFor } from '../core/claude-config-dir'
import { presenceHub } from '../core/presence/hub'
@@ -462,6 +463,25 @@ export async function startServer(
}
})
pressure.start()
+ // Pty-device pressure (core/pty-pressure.ts): the reaper leg ONLY, and deliberately so.
+ //
+ // A standing host is exactly where the ceiling is reached first — it accumulates the sessions
+ // (field report: 95) whose panes and ssh children hold the devices — so the sweep matters more
+ // here than on the desktop. What is missing is the OTHER half: the desktop also raises a banner
+ // whose one useful affordance is "Fix automatically…", and that button ends in macOS's own
+ // admin-password dialog on the HOST's physical display. A browser tab (possibly on another
+ // machine, possibly on a Linux host with no such limit at all) cannot answer that prompt, so a
+ // banner there would name a problem it gives the reader no way to act on. The channel exists —
+ // platform.broadcast reaches attached tabs — this is a choice, not a gap, and the same one
+ // already documented for the memory-pressure levers in renderer/bridge/stubs.ts. Server hosts
+ // hitting the wall are told by the spawn error (core/pty-devices.ts), which is the surface a
+ // headless host actually has. Stopped on close beside the memory monitor.
+ const ptyPressure = createPtyPressureMonitor({
+ onLevel: (reading) => {
+ if (reading.level === 'critical') void sessionReaper.sweep()
+ }
+ })
+ ptyPressure.start()
// Headless notification host: every core service above (incl. the loopback hook server, which
// is its own listener and MUST run) is booted, but we bind NO public HTTP/WS listener — no
@@ -475,6 +495,7 @@ export async function startServer(
// Detach PTY clients — tmux sessions keep running (Phase 1 contract).
sessionReaper.stop()
pressure.stop()
+ ptyPressure.stop()
await contextLink.stop()
await ptyManager.killAll()
// Same native hazard as the desktop app: a whisper transcribe still running when the
@@ -522,6 +543,7 @@ export async function startServer(
// Detach PTY clients — tmux sessions keep running (Phase 1 contract; never kill the server).
sessionReaper.stop()
pressure.stop()
+ ptyPressure.stop()
await contextLink.stop()
await ptyManager.killAll()
// Same native hazard as the desktop app: a whisper transcribe still running when the node
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 915433266..f95617ad2 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -22,6 +22,16 @@ export const IPC = {
* agent restart sees that the CLI has exited and a shell owns the pane again. */
ptyPaneCommand: 'pty:pane-command',
ptyReadSessionName: 'pty:read-session-name',
+ /** Shell → renderer: this MACHINE's pty-device pressure band changed (core/pty-pressure.ts).
+ * Payload: `PtyPressure` — `{ level, usage, ceiling }`. Sent on band CHANGES only, and re-sent
+ * for a held band at most once every five minutes; `level: 'none'` is what clears the banner.
+ * Desktop only — see the Server Edition note beside the monitor in src/server/index.ts. */
+ ptyPressure: 'pty:pressure',
+ /** Renderer → main: the user clicked "Fix automatically…" on the pty-pressure banner. Raises
+ * `kern.tty.ptmx_max` now AND installs a LaunchDaemon so it survives reboot, via ONE
+ * administrator-privileges osascript (macOS's own password dialog). Resolves
+ * `PtyLimitFixResult`. NEVER invoked on the app's own initiative — see main/ptmx-limit.ts. */
+ ptyRaiseDeviceLimit: 'pty:raise-device-limit',
claudeReadTranscript: 'claude:read-transcript',
chatReadTranscript: 'chat:read-transcript',
claudeAccountsAdd: 'claude-accounts:add',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index aa5e123c3..53bf3c5e3 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -518,6 +518,28 @@ export interface TmuxStatus {
platform: string
}
+/**
+ * How close THIS MACHINE is to `kern.tty.ptmx_max`, the system-wide pty-device ceiling that took
+ * the whole app down in the 2026-08-11 field report (every spawn failing with a bare
+ * `posix_spawnp failed.`). See core/pty-pressure.ts for the bands.
+ */
+export type PtyPressureLevel = 'none' | 'elevated' | 'critical'
+
+/** A pty-pressure reading, as broadcast on `IPC.ptyPressure`. `null` = could not be measured. */
+export interface PtyPressure {
+ level: PtyPressureLevel
+ /** `/dev/ttys*` entries in existence right now. */
+ usage: number | null
+ /** `kern.tty.ptmx_max`. */
+ ceiling: number | null
+}
+
+/** Outcome of the banner's "Fix automatically…" button (macOS only) — see main/ptmx-limit.ts. */
+export type PtyLimitFixResult =
+ | { ok: true; ceiling: number }
+ /** `canceled` = the user dismissed macOS's own admin-password dialog. Not an error to retry. */
+ | { ok: false; error: string; canceled?: boolean }
+
export interface PtyApi {
/** Starts a new PTY session; returns its sessionId and whether the session was freshly
* created (cold start) vs reattached to a still-running tmux session (warm). */
@@ -2044,6 +2066,17 @@ export interface NodeTerminalApi {
* need only be idempotent, not cheap. Returns unsubscribe. Server Edition: never fires (the
* pressure levers run host-side there; a browser tab's memory belongs to the browser). */
onMemoryPressure(listener: (severity: 'warning' | 'critical') => void): () => void
+ /** Fires when THIS MACHINE's pty-device pressure band changes (core/pty-pressure.ts): the
+ * renderer raises/lowers the banner that warns before `kern.tty.ptmx_max` stops every new
+ * terminal from opening. Band changes only, re-sent for a held band at most once every five
+ * minutes; `level: 'none'` means the banner should come down. Returns unsubscribe.
+ * Server Edition: never fires — the reaper leg runs host-side only (see src/server/index.ts). */
+ onPtyPressure(listener: (reading: PtyPressure) => void): () => void
+ /** Raise this Mac's pty-device ceiling (`kern.tty.ptmx_max`) now AND across reboots, behind
+ * macOS's own administrator-password dialog. Called ONLY from the banner's explicit
+ * "Fix automatically…" click — never on the app's initiative. macOS only; a dismissed password
+ * dialog resolves `{ ok: false, canceled: true }`, which is not an error to report or retry. */
+ raisePtyDeviceLimit(): Promise<PtyLimitFixResult>
/** Answer a Claude permission request via the deterministic hook-reply channel (spec:
* docs/hook-reply-approvals.md). Writes the one-line answer file the held hook is polling
* (`~/.nodeterm/pending/<pendingId>.answer`) on the host the agent runs on — the LOCAL fs for a