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): review fixes — real sweep allowance, safer fix handler, honest dismissal
enes003ccb6ca2d5
diff --git a/src/core/pty-pressure.ts b/src/core/pty-pressure.tsindex 5c54aa384..c03ef5ad1 100644--- a/src/core/pty-pressure.ts+++ b/src/core/pty-pressure.ts@@ -37,10 +37,15 @@ 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).+ * the user never sees — a re-announce here can re-raise a BANNER, so the interval is a nagging+ * budget, not just a refresh rate. A level CHANGE always fires immediately; `none` is never+ * re-announced (there is nothing to re-say — the banner is already gone).+ *+ * What a re-announce MEANS is the renderer's call, and the two bands answer differently+ * (PtyPressureBanner): a dismissed `elevated` stays dismissed through these — it is an early+ * warning and the user has been told — while a dismissed `critical` comes back on the next one,+ * because terminals are failing to open while it is up. So this constant is the reminder cadence+ * for the wall, and the freshness cadence for the warning.*/export const PTY_PRESSURE_RE_ANNOUNCE_MS = 300_000diff --git a/src/core/session-budget.test.ts b/src/core/session-budget.test.tsindex a869c1fc5..588506a81 100644--- a/src/core/session-budget.test.ts+++ b/src/core/session-budget.test.ts@@ -89,6 +89,26 @@ describe('planReap (pure policy)', () => {const plan = planReap(sessions, lowMem, NOW, cfg({ batchMax: 3 }))expect(plan).toHaveLength(3)})++ // The 2026-08-11 profile: plenty of RAM, well under the detached cap, and the machine still+ // could not open a terminal because it was out of pty DEVICES. Without an allowance of its own+ // that reading plans nothing at all — the sweep the shell fires on critical pty pressure would+ // be a no-op, which is exactly the bug this argument exists to close.+ it('an external pressure reason earns the same allowance low memory does', () => {+ const sessions = Array.from({ length: 20 }, (_, i) => idle(`nt-s${i}`, 100 + i))+ expect(planReap(sessions, okMem, NOW, cfg({ batchMax: 3 }))).toHaveLength(0)+ expect(planReap(sessions, okMem, NOW, cfg({ batchMax: 3 }), true)).toHaveLength(3)+ })++ it('external pressure widens NO safety gate: attached and in-grace sessions still live', () => {+ const sessions = [idle('nt-watched', 500, 1), idle('nt-fresh', 1), idle('user-shell', 500)]+ expect(planReap(sessions, okMem, NOW, cfg(), true)).toEqual([])+ })++ it('the kill switch still wins over an external pressure reason', () => {+ const plan = planReap([idle('nt-a', 500)], okMem, NOW, cfg({ disabled: true }), true)+ expect(plan).toEqual([])+ })})describe('parseSessionList', () => {@@ -239,4 +259,31 @@ describe('createSessionReaper (service)', () => {expect(await reaper.sweep()).toBe(0)expect(w.calls.filter((c) => c.args[2] === 'kill-session')).toHaveLength(0)})++ it('…but the same host sweeps under an explicit external pressure reason', async () => {+ const w = fakeWorld({ 'node-terminal': [`nt-x|0|${OLD}`] })+ const reaper = createSessionReaper({+ ...base,+ readMem: () => ({ availableMb: 30_000, totalMb: 64_000 }),+ tmuxBin: () => 'tmux',+ sockets: ['node-terminal'],+ exec: w.exec+ })+ expect(await reaper.sweep({ pressure: 'pty' })).toBe(1)+ })++ it('an external reason never overrides the attached/grace exemptions', async () => {+ const w = fakeWorld({+ 'node-terminal': [`nt-watched|1|${OLD}`, `nt-fresh|0|${NOW - 60}`]+ })+ const reaper = createSessionReaper({+ ...base,+ readMem: () => ({ availableMb: 30_000, totalMb: 64_000 }),+ tmuxBin: () => 'tmux',+ sockets: ['node-terminal'],+ exec: w.exec+ })+ expect(await reaper.sweep({ pressure: 'pty' })).toBe(0)+ expect(w.calls.filter((c) => c.args[2] === 'kill-session')).toHaveLength(0)+ })})diff --git a/src/core/session-budget.ts b/src/core/session-budget.tsindex dd55b5f3c..21814a152 100644--- a/src/core/session-budget.ts+++ b/src/core/session-budget.ts@@ -98,14 +98,24 @@ export function sessionBudgetConfig(env: NodeJS.ProcessEnv, totalMb: number): Se* Eligible = named `nt-*` AND detached AND idle past the grace window. Then:* - memory below the watermark → up to `batchMax` (a failed memory read — `mem === null` — is* NOT pressure: absence of evidence never triggers the primary path);+ * - `externalPressure` → the same allowance, for a resource this module cannot measure (today:+ * pty devices — see core/pty-pressure.ts). It exists because the 2026-08-11 host had HEALTHY+ * memory and sat well under `maxDetached` while being unable to open a single terminal, so+ * every term above was zero and the sweep the shell fired was a no-op;* - detached count over `maxDetached` → the excess, even with healthy memory;* combined take is bounded by `batchMax`.+ *+ * An allowance is not an exemption: `externalPressure` raises how MANY of the eligible may go, and+ * touches nothing about which sessions are eligible. Attached sessions and sessions inside the+ * grace window stay unkillable under it, exactly as under memory pressure — that is this module's+ * one hard rule and no caller gets to spend it.*/export function planReap(sessions: SessionInfo[],mem: MemInfo | null,nowSec: number,- cfg: SessionBudgetConfig+ cfg: SessionBudgetConfig,+ externalPressure = false): string[] {if (cfg.disabled) return []const nt = sessions.filter((s) => s.name.startsWith('nt-'))@@ -114,7 +124,8 @@ export function planReap(.filter((s) => nowSec - s.activitySec >= cfg.graceSec).sort((a, b) => a.activitySec - b.activitySec)- const pressure = mem !== null && mem.availableMb < cfg.minAvailableMb ? cfg.batchMax : 0+ const lowMem = mem !== null && mem.availableMb < cfg.minAvailableMb+ const pressure = lowMem || externalPressure ? cfg.batchMax : 0const overCap = Math.max(0, detached.length - cfg.maxDetached)const take = Math.min(cfg.batchMax, Math.max(pressure, overCap))return eligible.slice(0, take).map((s) => s.name)@@ -195,9 +206,20 @@ export interface SessionReaperOpts {log?: (msg: string) => void}+/**+ * A resource OUTSIDE this module's instruments that is exhausted right now, named by the shell+ * that measured it. Today only pty devices (`kern.tty.ptmx_max`, core/pty-pressure.ts).+ */+export type SweepPressure = 'pty'++export interface SweepOptions {+ /** Grant this sweep the same allowance low memory would. Omitted ⇒ ordinary budget semantics. */+ pressure?: SweepPressure+}+export interface SessionReaper {/** One sweep; resolves to the number of sessions killed. Never throws. */- sweep(): Promise<number>+ sweep(opts?: SweepOptions): Promise<number>start(): voidstop(): void}@@ -249,7 +271,7 @@ export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {}}- const sweep = async (): Promise<number> => {+ const sweep = async (sweepOpts?: SweepOptions): Promise<number> => {if (cfg.disabled) return 0const bin = opts.tmuxBin()if (!bin) return 0@@ -262,7 +284,7 @@ export function createSessionReaper(opts: SessionReaperOpts): SessionReaper {if (bySocket.size === 0) return 0const all = [...bySocket.entries()].flatMap(([, list]) => list)- const plan = new Set(planReap(all, readMem(), nowSec(), cfg))+ const plan = new Set(planReap(all, readMem(), nowSec(), cfg, sweepOpts?.pressure !== undefined))if (plan.size === 0) return 0let killed = 0diff --git a/src/main/index.ts b/src/main/index.tsindex 5598bef41..e479e36a1 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1556,10 +1556,15 @@ app.whenReady().then(async () => {// 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.+ //+ // The sweep is passed `pressure: 'pty'` because a bare `sweep()` here would plan NOTHING: the+ // budget's own triggers are memory and a detached-count cap, and the incident profile clears+ // both (healthy RAM, under the cap). The reason grants the same batch allowance low memory+ // would and widens no exemption — attached and in-grace sessions stay untouchable.const ptyPressure = createPtyPressureMonitor({onLevel: (reading) => {sendToMain(IPC.ptyPressure, reading)- if (reading.level === 'critical') void sessionReaper.sweep()+ if (reading.level === 'critical') void sessionReaper.sweep({ pressure: 'pty' })}})ptyPressure.start()diff --git a/src/main/ptmx-limit.test.ts b/src/main/ptmx-limit.test.tsindex 0a6ffb8a4..f5f74f99a 100644--- a/src/main/ptmx-limit.test.ts+++ b/src/main/ptmx-limit.test.ts@@ -1,7 +1,10 @@import { describe, it, expect } from 'vitest'+import fs from 'fs'+import path from 'path'import { IPC } from '@shared/ipc'import { fakePlatform } from '../core/platform-fake'import {+ OSASCRIPT_BIN,PTMX_DAEMON_LABEL,PTMX_MIN_TARGET,PTMX_PLIST_PATH,@@ -117,7 +120,11 @@ describe('the raise-limit IPC handler', () => {const runs: string[][] = []registerPtmxLimitHandler(p, {platform: over.platform ?? 'darwin',- read: () => ({ ceiling: over.ceiling ?? 511, inUse: over.inUse ?? 508 }),+ // `?? 511` would swallow the explicit `ceiling: null` case this suite has to cover.+ read: () => ({+ ceiling: 'ceiling' in over ? over.ceiling! : 511,+ inUse: over.inUse ?? 508+ }),run: async (args) => {runs.push(args)return over.run ? over.run(args) : { ok: true as const }@@ -185,6 +192,55 @@ describe('the raise-limit IPC handler', () => {const { runs } = setup()expect(runs).toEqual([])})++ // ptmxTarget(null) is the FLOOR, and the floor is a DOWNGRADE on a machine already at 4096 —+ // written into a LaunchDaemon, so the downgrade would survive every reboot. A ceiling we could+ // not read is the one input we must never compute a new limit from.+ it('refuses to write a limit computed from an unmeasured ceiling', async () => {+ const { call, runs, announced } = setup({ ceiling: null })+ const res: any = await call()+ expect(res.ok).toBe(false)+ expect(res.error).toMatch(/could not read/i)+ expect(runs).toEqual([])+ expect(announced).toEqual([])+ })++ // One password dialog is up and modal; a renderer reload or a second window must not stack a+ // second one behind it. The loser is silent — nothing failed, the user is already being asked.+ it('a second invoke while the dialog is still up is a silent no-op', async () => {+ let release: (() => void) | null = null+ const { call, runs } = setup({+ run: () =>+ new Promise((resolve) => {+ release = () => resolve({ ok: true as const })+ })+ })+ const first = call()+ const second: any = await call()+ expect(second).toEqual({ ok: false, busy: true, error: expect.any(String) })+ expect(runs).toHaveLength(1)+ release!()+ await expect(first).resolves.toEqual({ ok: true, ceiling: 2048 })+ // …and the guard clears with it, so a later click is not locked out for good.+ void call()+ expect(runs).toHaveLength(2)+ release!()+ })+})++describe('the binary this file runs', () => {+ it('is pinned to an absolute path', () => {+ expect(OSASCRIPT_BIN).toBe('/usr/bin/osascript')+ })++ it('is never resolved through PATH', () => {+ // A GUI launch inherits no shell environment (the DMG/Finder incidents), and this exec is the+ // one immediately preceding an administrator-password prompt: a PATH-resolved `osascript` is+ // both the likeliest to be missing and the worst one to let anything else answer to.+ const src = fs.readFileSync(path.join(__dirname, 'ptmx-limit.ts'), 'utf8')+ expect(src).not.toMatch(/execFile\(\s*['"]osascript['"]/)+ expect(src).toMatch(/execFile\(\s*OSASCRIPT_BIN/)+ })})describe('IPC channels for pty pressure', () => {diff --git a/src/main/ptmx-limit.ts b/src/main/ptmx-limit.tsindex a6bd7ab49..e5ab558a3 100644--- a/src/main/ptmx-limit.ts+++ b/src/main/ptmx-limit.ts@@ -132,9 +132,17 @@ export type OsascriptRunner = (args: string[]) => Promise<{ ok: true } | { ok: false; message: string }>+/**+ * Absolute, never PATH-resolved. A GUI launch inherits no shell environment — the DMG/Finder+ * incidents in this repo were exactly that — and of every binary the app runs, this is the one that+ * must not be answered by whatever a broken (or hostile) PATH happens to point at: the next thing+ * it does is ask the user for their administrator password.+ */+export const OSASCRIPT_BIN = '/usr/bin/osascript'+const defaultRunner: OsascriptRunner = (args) =>new Promise((resolve) => {- execFile('osascript', args, { timeout: 5 * 60_000 }, (err, _stdout, stderr) => {+ execFile(OSASCRIPT_BIN, 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 })@@ -161,6 +169,10 @@ export function registerPtmxLimitHandler(platform: CorePlatform, deps: PtmxLimitconst read = deps.read ?? readPtyDevicesconst run = deps.run ?? defaultRunnerconst os = deps.platform ?? process.platform+ // The password dialog is modal and there is one of it. A renderer reload mid-prompt, or a second+ // window, would otherwise queue a second osascript behind the first — two password prompts for+ // one click the user made once.+ let asking = falseplatform.handle(IPC.ptyRaiseDeviceLimit, async (): Promise<PtyLimitFixResult> => {if (os !== 'darwin') {@@ -169,9 +181,28 @@ export function registerPtmxLimitHandler(platform: CorePlatform, deps: PtmxLimiterror: 'Raising the pty-device limit is only supported on macOS.'}}+ if (asking) {+ // Silent for the caller: nothing failed and nothing is lost — the user is already being+ // asked, and the answer will re-announce to every window.+ return { ok: false, busy: true, error: 'Already asking for permission.' }+ }const before = read()+ // `ptmxTarget(null)` is the FLOOR, and on a machine already raised past it the floor is a+ // DOWNGRADE — one we would then pin across every reboot with the LaunchDaemon. A ceiling we+ // could not measure is the one input never worth guessing from; the read self-heals in a+ // moment (pty-devices re-primes in the background), so the honest answer is "not now".+ if (before.ceiling === null) {+ return {+ ok: false,+ error:+ 'Could not read this machine’s terminal limit (kern.tty.ptmx_max) — try again in a moment.'+ }+ }const target = ptmxTarget(before.ceiling)- const res = await run(osascriptArgs(target))+ asking = true+ const res = await run(osascriptArgs(target)).finally(() => {+ asking = false+ })if (!res.ok) {return isUserCancel(res.message)? {diff --git a/src/renderer/components/PtyPressureBanner.test.tsx b/src/renderer/components/PtyPressureBanner.test.tsxindex 55f944c4a..c5c837829 100644--- a/src/renderer/components/PtyPressureBanner.test.tsx+++ b/src/renderer/components/PtyPressureBanner.test.tsx@@ -107,13 +107,26 @@ describe('PtyPressureBanner', () => {expect(host.querySelector('.announce-banner')).toBeNull()})- it('the ✕ hides it, and a WORSENING level brings it back', () => {+ it('a dismissed ELEVATED banner stays down while the level holds, and returns when it worsens', () => {const { host } = mount()act(() => listener!(reading('elevated')))act(() => (host.querySelector('.announce-banner__close') as HTMLButtonElement).click())expect(host.querySelector('.announce-banner')).toBeNull()+ // A five-minute re-announce of the SAME early warning respects the dismissal — the user was+ // told, it is not urgent yet, and nagging is how a banner gets ignored for good.act(() => listener!(reading('elevated')))- expect(host.querySelector('.announce-banner')).toBeNull() // same level: stays dismissed+ expect(host.querySelector('.announce-banner')).toBeNull()+ act(() => listener!(reading('critical')))+ expect(host.querySelector('.announce-banner')).not.toBeNull()+ })++ it('a dismissed CRITICAL banner comes back on the next re-announce', () => {+ const { host } = mount()+ act(() => listener!(reading('critical')))+ act(() => (host.querySelector('.announce-banner__close') as HTMLButtonElement).click())+ expect(host.querySelector('.announce-banner')).toBeNull()+ // The shell re-announces a held critical every five minutes. Terminals are failing to open+ // right now: a dismissal buys quiet until the next reminder, never permanent silence.act(() => listener!(reading('critical')))expect(host.querySelector('.announce-banner')).not.toBeNull()})@@ -149,6 +162,19 @@ describe('PtyPressureBanner', () => {expect(host.querySelector('.announce-banner')).not.toBeNull() // banner stays})+ it('a busy answer is silent too — another window is already holding the dialog', async () => {+ fix = vi.fn(async () => ({ ok: false as const, busy: true, error: 'Already asking' }))+ 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()+ })+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()diff --git a/src/renderer/components/PtyPressureBanner.tsx b/src/renderer/components/PtyPressureBanner.tsxindex 5738918f6..88e395de7 100644--- a/src/renderer/components/PtyPressureBanner.tsx+++ b/src/renderer/components/PtyPressureBanner.tsx@@ -56,20 +56,38 @@ export function PtyPressureBanner({onError: (message: string) => voidisMac?: 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)+ // `seq` counts BROADCASTS, not levels: the shell sends one per band change and one per+ // five-minute re-announce, which is what lets a dismissal be scoped to a single reminder.+ const [state, setState] = useState<{ reading: PtyPressure; seq: number } | null>(null)+ const [dismissed, setDismissed] = useState<{ level: PtyPressure['level']; seq: number } | 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)+ const off = window.nodeTerminal.onPtyPressure?.((r) =>+ setState((prev) => ({ reading: r, seq: (prev?.seq ?? 0) + 1 }))+ )return () => off?.()}, [])+ const reading = state?.reading ?? nullconst copy = reading ? ptyPressureCopy(reading) : null- if (!reading || !copy || dismissed === reading.level) return null+ // Dismissal is never for the session, and the two bands are not dismissed on the same terms:+ // - ELEVATED sticks until the level changes. It is an early warning with runway left; the+ // user has been told, and a strip that comes back every five minutes on a machine that is+ // merely busy is how a banner teaches people to ignore it.+ // - CRITICAL expires with the broadcast it dismissed. Terminals are failing to open RIGHT NOW,+ // so ✕ buys quiet until the next reminder (five minutes, see PTY_PRESSURE_RE_ANNOUNCE_MS),+ // never permanent silence.+ // Either way a drop to `none` clears everything: there is nothing left to dismiss.+ const hidden =+ !!dismissed &&+ !!reading &&+ dismissed.level === reading.level &&+ (reading.level !== 'critical' || dismissed.seq === state!.seq)+ if (!reading || !copy || hidden) return nullconst fix = (): void => {if (busy) return@@ -81,7 +99,9 @@ export function PtyPressureBanner({void window.nodeTerminal.raisePtyDeviceLimit?.().then((res) => {- if (!res.ok && !res.canceled) onError(res.error)+ // `canceled` (the user said no) and `busy` (another window is already asking) are both+ // outcomes, not failures — neither may raise a toast.+ if (!res.ok && !res.canceled && !res.busy) onError(res.error)}).catch((e: unknown) => onError(String((e as Error)?.message ?? e))).finally(() => setBusy(false))@@ -107,7 +127,7 @@ export function PtyPressureBanner({<buttonclassName="announce-banner__close"title="Dismiss"- onClick={() => setDismissed(reading.level)}+ onClick={() => setDismissed({ level: reading.level, seq: state!.seq })}>✕</button>diff --git a/src/server/index.ts b/src/server/index.tsindex 648f17614..ad27af254 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -476,9 +476,13 @@ export async function startServer(// 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.+ //+ // `pressure: 'pty'` for the same reason as the desktop: without an explicit reason the budget's+ // own triggers (memory watermark, detached cap) are both clear on a pty-starved host and the+ // sweep plans nothing. It buys an allowance, not an exemption — see planReap.const ptyPressure = createPtyPressureMonitor({onLevel: (reading) => {- if (reading.level === 'critical') void sessionReaper.sweep()+ if (reading.level === 'critical') void sessionReaper.sweep({ pressure: 'pty' })}})ptyPressure.start()diff --git a/src/shared/types.ts b/src/shared/types.tsindex 53bf3c5e3..14a1aedae 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -537,8 +537,10 @@ export interface PtyPressure {/** 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 }+ /** `canceled` = the user dismissed macOS's own admin-password dialog. Not an error to retry.+ * `busy` = a password dialog from another window/reload is already up. Both are SILENT for the+ * renderer: nothing failed, so neither may raise an error toast. */+ | { ok: false; error: string; canceled?: boolean; busy?: boolean }export interface PtyApi {/** Starts a new PTY session; returns its sessionId and whether the session was freshly