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
feat(pty): idle-reap the client PTYs of sessions nobody is attached to
enescbaeb4329753
diff --git a/src/core/pty-idle-reap.test.ts b/src/core/pty-idle-reap.test.tsnew file mode 100644index 000000000..0b97148a3--- /dev/null+++ b/src/core/pty-idle-reap.test.ts@@ -0,0 +1,212 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { IPC } from '../shared/ipc'+import { DEFAULT_SETTINGS } from '../shared/types'+import { sessionName } from './tmux-naming'+import { REAP_IDLE_MS, REAP_SWEEP_MS } from './pty-reap'++/**+ * IDLE REAP (2026-08-11: the machine hit `kern.tty.ptmx_max` with 62 live PTYs in this manager).+ *+ * The sweep exists to return pty devices held by sessions NOBODY is attached to any more — the+ * residue of a release hook that was never wired or never ran (a destroyed window, a vanished relay+ * peer). What it must never do is take a device back at the cost of somebody's work, so each+ * refusal below is as much the subject as the reap itself.+ */++/** One fake pty per spawn. `killed` is what a released client pty looks like from here. */+interface FakePty {+ onDataCb?: (d: string) => void+ onExitCb?: (e: { exitCode: number }) => void+ killed: boolean+ paused: boolean+}+const spawned: FakePty[] = []+const spawnArgs: Array<{ file: string; args: string[] }> = []++vi.mock('node-pty', () => ({+ spawn: (file: string, args: string[]) => {+ const p: FakePty = { killed: false, paused: false }+ spawned.push(p)+ spawnArgs.push({ file, args })+ return {+ onData: (cb: (d: string) => void) => {+ p.onDataCb = cb+ },+ onExit: (cb: (e: { exitCode: number }) => void) => {+ p.onExitCb = cb+ },+ write: () => {},+ resize: () => {},+ pause: () => {+ p.paused = true+ },+ resume: () => {+ p.paused = false+ },+ kill: () => {+ p.killed = true+ },+ pid: 1+ }+ }+}))++/** Every tmux side-call goes through child_process, so this both answers `has-session` and lets a+ * test PROVE the reap never issues `kill-session` (the tmux session is the work). */+const execCalls: Array<{ file: string; args: string[] }> = []+const liveTmuxSessions = new Set<string>()++vi.mock('child_process', () => {+ type Cb = (err: Error | null, res?: { stdout: string; stderr: string }) => void+ const execFile = (file: string, args: string[], a?: unknown, b?: unknown): unknown => {+ const cb = (typeof a === 'function' ? a : b) as Cb | undefined+ execCalls.push({ file, args })+ const ok = (stdout: string): void => cb?.(null, { stdout, stderr: '' })+ if (args.includes('has-session')) {+ const target = args[args.indexOf('-t') + 1]+ if (liveTmuxSessions.has(target)) ok('')+ else cb?.(Object.assign(new Error('no such session'), { code: 1 }))+ } else if (args[0] === '-ilc') {+ ok('__NT_PATH_START__/usr/bin:/bin__NT_PATH_END__')+ } else {+ ok('')+ }+ return {}+ }+ return { execFile, execFileSync: (): string => '' }+})++const ALICE = 1++describe('idle reap of unwatched client PTYs', () => {+ let fake: FakePlatform+ let userDataDir: string++ beforeEach(() => {+ spawned.length = 0+ spawnArgs.length = 0+ execCalls.length = 0+ liveTmuxSessions.clear()+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-reap-'))+ fake = fakePlatform({ userDataDir })+ initPlatform(fake)+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+ resetPlatformForTests()+ // Best effort, exactly as in pty-single-user.test.ts: a fired-and-forgotten scrollback snapshot+ // can still be landing here, and a cleanup that fails the suite is worse than a leftover dir.+ try {+ fs.rmSync(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 })+ } catch {+ /* a temp dir we could not remove is not a test result */+ }+ })++ /** A manager WITH init(): tmux-backed, which is what a real user always gets. */+ async function tmuxManager() {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.init(() => DEFAULT_SETTINGS)+ m.registerIpc()+ return m+ }+ /** A manager WITHOUT init(): no tmux, so a session's work lives ONLY in its pty client. */+ async function plainManager() {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.registerIpc()+ return m+ }+ const create = (clientId: number, persistKey = 'node-1') =>+ fake.handlers[IPC.ptyCreate](clientId, { cols: 80, rows: 24, persistKey }) as Promise<{+ sessionId: string+ fresh: boolean+ }>+ /** Run the sweep past the idle threshold (it only decides on its own ticks). */+ const idle = (ms = REAP_IDLE_MS + REAP_SWEEP_MS) => vi.advanceTimersByTime(ms)++ it('releases the client pty of a tmux-backed session nobody is attached to any more', async () => {+ await tmuxManager()+ await create(ALICE) // …and Alice's window is then destroyed without a pty:kill ever arriving++ idle()++ expect(spawned[0].killed).toBe(true)+ // The tmux session is the WORK. Detaching its client is the whole point; killing it is the one+ // thing this sweep may never do.+ expect(execCalls.some((c) => c.args.includes('kill-session'))).toBe(false)+ })++ it('never reaps a session whose subscriber is still attached', async () => {+ fake.clients.push(ALICE) // her window is alive, terminal open (or parked, still subscribed)+ await tmuxManager()+ await create(ALICE)++ idle(REAP_IDLE_MS * 10)++ expect(spawned[0].killed).toBe(false)+ })++ it('never reaps before the threshold — it must not race the renderer 5-minute park', async () => {+ await tmuxManager()+ await create(ALICE)++ idle(6 * 60 * 1000) // one minute past TERM_PARK_MS++ expect(spawned[0].killed).toBe(false)+ })++ it('never reaps a session with no tmux underneath (an ssh-direct terminal dies with its client)', async () => {+ await plainManager()+ await create(ALICE)++ idle(REAP_IDLE_MS * 10)++ expect(spawned[0].killed).toBe(false)+ })++ it('never reaps a relay-served (detached) pty — its sink IS the watcher', async () => {+ const m = await tmuxManager()+ m.attachDetached('node-1', { onData: () => {}, onExit: () => {} })++ idle(REAP_IDLE_MS * 10)++ expect(spawned[0].killed).toBe(false)+ })++ it('reattaches transparently after a reap: the node reopens onto its live tmux session', async () => {+ await tmuxManager()+ const first = await create(ALICE)+ liveTmuxSessions.add(sessionName('node-1')) // tmux kept it running, as it does across a detach++ idle()+ expect(spawned[0].killed).toBe(true)++ const again = await create(ALICE)+ expect(again.sessionId).not.toBe(first.sessionId)+ expect(spawned).toHaveLength(2)+ // A WARM reattach: `fresh:false` is what suppresses the cold-restore scrollback replay, i.e.+ // the user gets the session that kept running, not a new shell.+ expect(again.fresh).toBe(false)+ expect(spawnArgs[1].args).toContain('new-session')+ expect(spawnArgs[1].args.slice(-2)).toEqual(['-s', sessionName('node-1')])+ })++ it('sweeps the same way off darwin — the pty ceiling is macOS, running out of them is not', async () => {+ vi.spyOn(os, 'platform').mockReturnValue('linux')+ await tmuxManager()+ await create(ALICE)++ idle()++ expect(spawned[0].killed).toBe(true)+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex ed846e9d6..dbed0cf4a 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -32,6 +32,7 @@ import {import { parsePaneCursor } from './pane-cursor'import { readSpawnResources, spawnResourceNote } from './spawn-resources'import { primePtyCeiling, readPtyDevices, spawnFailureHint } from './pty-devices'+import { REAP_SWEEP_MS, shouldReap } from './pty-reap'import { TMUX_SOCKET, sessionName } from './tmux-naming'import { bracketedInjection } from './paste-injection'import { releasePty, type ReleasablePty } from './pty-release'@@ -361,6 +362,14 @@ interface Session {sshRemote?: NonNullable<PtyCreateOptions['sshRemote']>/** Output arrived since the last scrollback snapshot — idle sessions skip the capture. */outputSinceSnapshot: boolean+ /** A tmux session (local `nt-<id>`, or the remote one an SSH project attaches to) is holding this+ * session's work, so the pty client here is expendable: detaching it loses nothing and the next+ * create re-attaches with `new-session -A`. It is the precondition for the idle reap — see+ * pty-reap.ts — and it is exactly the condition `persisted` is computed from at spawn. */+ tmuxBacked: boolean+ /** When the reap sweep first saw this session with nobody attached (no live subscriber, no relay+ * sink); `null` while somebody is. See `reapTick`. */+ unwatchedSince: number | null/*** The (client, owner) pairs that currently OWE us a resume — a ledger of FLOW TICKETS* (`flowTicket`), not of clients. The pty is paused while this set is non-empty and resumes only@@ -525,6 +534,9 @@ export class PtyManager {/** ONE shared snapshot interval for all persisted sessions — a per-session interval spawned* one tmux/ssh capture subprocess per session per tick, forever, even for idle terminals. */private snapshotTimer: ReturnType<typeof setInterval> | null = null+ /** ONE shared sweep for the idle reap (see `reapTick` / pty-reap.ts), armed by the first+ * tmux-backed session and cleared once no session is left. */+ private reapTimer: ReturnType<typeof setInterval> | null = nullprivate ensureSnapshotTimer(): void {if (this.snapshotTimer) return@@ -550,6 +562,66 @@ export class PtyManager {}}+ private ensureReapTimer(): void {+ if (this.reapTimer) return+ this.reapTimer = setInterval(() => this.reapTick(), REAP_SWEEP_MS)+ // Node keeps the process alive for a pending interval, and this one would otherwise outlive the+ // work it sweeps (the snapshot timer clears itself the same way, in its own tick).+ this.reapTimer.unref?.()+ }++ /**+ * Release the client pty of every tmux-backed session nobody has been attached to for+ * `REAP_IDLE_MS` — the safety net under the normal release paths. The tmux session, its processes+ * and its scrollback are untouched: this is the SAME detach the last subscriber's departure does,+ * and the next `pty:create` re-attaches to it. Read pty-reap.ts before changing any of it.+ *+ * "Attached" is decided against `platform().clientIds()`, not against the subscriber set: the+ * whole point is the subscriber whose window/tab/peer is GONE and which therefore can never send+ * the `pty:kill` that would release the pty. A client id is never reused (Electron webContents+ * ids and the server's `nextUiId` both only go up), so a client that comes back comes back as a+ * new id and creates its sessions afresh — there is no returning client to strand.+ */+ private reapTick(): void {+ const live = new Set(platform().clientIds())+ const now = Date.now()+ for (const [sessionId, session] of [...this.sessions]) {+ // A relay sink is a watcher (somebody's phone is mirroring this session); a parked terminal+ // is still a subscriber, and its client is still attached.+ const watched =+ !!session.onData || [...session.subscribers].some((sub) => live.has(subClient(sub)))+ if (watched) session.unwatchedSince = null+ else session.unwatchedSince ??= now+ const reap = shouldReap(+ { tmuxBacked: session.tmuxBacked, watched, unwatchedSince: session.unwatchedSince },+ now+ )+ if (reap) this.releaseClient(sessionId, session)+ }+ if (this.sessions.size === 0 && this.reapTimer) {+ clearInterval(this.reapTimer)+ this.reapTimer = null+ }+ }++ /**+ * Detach this process's pty CLIENT from a session and forget it: the final scrollback snapshot,+ * `releasePty` (never a bare `proc.kill()` — a paused pty never reads EOF, so kill alone leaks+ * the master fd; see pty-release.ts), and the index cleanup. Shared by the last subscriber's+ * departure and the idle reap, which differ only in what made the session unwatched. A tmux+ * session is NOT killed here, in either case — that is `destroySession`.+ */+ private releaseClient(sessionId: string, session: Session): void {+ if (session.flushTimer) clearTimeout(session.flushTimer)+ // Final snapshot on detach (node unmount / app quit) so the very latest scrollback survives+ // a reboot. The tmux session itself keeps running, so this only races a same-instant capture.+ // Skipped when nothing arrived since the last periodic capture (pane content is unchanged).+ if (session.persistKey && session.outputSinceSnapshot)+ void this.snapshotScrollback(session.persistKey, session.sshRemote)+ releasePty(session.proc as ReleasablePty)+ this.forget(sessionId, session)+ }+/** Must run after app is ready (needs userData path). */init(getSettings: () => Settings): void {this.getSettings = getSettings@@ -1381,10 +1453,21 @@ export class PtyManager {persistKey: persisted ? options.persistKey : undefined,sshRemote: remote,outputSinceSnapshot: true, // capture the initial screen on the first tick+ // `persisted` IS "a tmux session (local or remote) is holding this work" — the same condition+ // that gates the scrollback snapshots. Recorded under its own name because the reap decision+ // asks a different question of it: not "is it worth snapshotting" but "would releasing this+ // pty client destroy anything" (pty-reap.ts).+ tmuxBacked: persisted,+ unwatchedSince: null,pausedBy: new Set<string>(),accountFallback}- if (persisted) this.ensureSnapshotTimer()+ // Both shared timers are armed by the first session that needs them: the scrollback snapshots+ // and the idle reap are both about tmux-backed sessions and nothing else.+ if (persisted) {+ this.ensureSnapshotTimer()+ this.ensureReapTimer()+ }this.sessions.set(sessionId, session)// Index by node id even when the session is NOT tmux-persisted (`persisted` only governs// scrollback snapshots): co-attach must work for a plain-shell session too. Detached@@ -1769,16 +1852,9 @@ export class PtyManager {this.applySize(sessionId, session)return}- if (session.flushTimer) clearTimeout(session.flushTimer)- // Final snapshot on detach (node unmount / app quit) so the very latest scrollback survives- // a reboot. The tmux session itself keeps running, so this only races a same-instant capture.- // Skipped when nothing arrived since the last periodic capture (pane content is unchanged).- if (session.persistKey && session.outputSinceSnapshot)- void this.snapshotScrollback(session.persistKey, session.sshRemote)- // releasePty (not proc.kill()): a paused pty never reads EOF, so kill() alone leaks the- // master fd on every detach until the process runs out of descriptors (see pty-release.ts).- releasePty(session.proc as ReleasablePty)- this.forget(sessionId, session)+ // Nobody is left: detach this process's pty client (the tmux session keeps running, as always).+ // Shared with the idle reap — see `releaseClient`.+ this.releaseClient(sessionId, session)}/**@@ -2268,6 +2344,10 @@ export class PtyManager {clearInterval(this.snapshotTimer)this.snapshotTimer = null}+ if (this.reapTimer) {+ clearInterval(this.reapTimer)+ this.reapTimer = null+ }const finals: Promise<unknown>[] = []for (const session of this.sessions.values()) {if (session.flushTimer) clearTimeout(session.flushTimer)diff --git a/src/core/pty-reap.test.ts b/src/core/pty-reap.test.tsnew file mode 100644index 000000000..380a16d6e--- /dev/null+++ b/src/core/pty-reap.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest'+import { REAP_IDLE_MS, shouldReap, type ReapCandidate } from './pty-reap'++/**+ * The reap decision, in one place, so the three things it must never do can be pinned without a+ * PtyManager: never touch a session somebody is attached to, never touch a session whose work+ * would die with the pty client (no tmux underneath), and never fire before the idle threshold.+ */+const candidate = (over: Partial<ReapCandidate> = {}): ReapCandidate => ({+ tmuxBacked: true,+ watched: false,+ unwatchedSince: 0,+ ...over+})++describe('shouldReap', () => {+ it('reaps a tmux-backed session nobody has been attached to past the threshold', () => {+ expect(shouldReap(candidate(), REAP_IDLE_MS)).toBe(true)+ })++ it('never reaps a session somebody is attached to', () => {+ // The one non-negotiable: a reap detaches the tmux client, which repaints the terminal of+ // whoever is watching it — and for a relay-served pty (a sink is a watcher too) it would+ // simply cut the phone off.+ expect(shouldReap(candidate({ watched: true }), REAP_IDLE_MS * 100)).toBe(false)+ })++ it('never reaps a session with no tmux underneath', () => {+ // An ssh-direct terminal (SSH project without tmux, or a plain shell with tmux off) has NO+ // server-side copy: releasing the client pty ends the remote shell and everything in it.+ expect(shouldReap(candidate({ tmuxBacked: false }), REAP_IDLE_MS * 100)).toBe(false)+ })++ it('waits out the full threshold', () => {+ expect(shouldReap(candidate(), REAP_IDLE_MS - 1)).toBe(false)+ expect(shouldReap(candidate(), REAP_IDLE_MS)).toBe(true)+ })++ it('never reaps a session that has not yet been seen unwatched', () => {+ // `null` = the sweep has never seen it without a watcher, so there is no clock to measure.+ expect(shouldReap(candidate({ unwatchedSince: null }), REAP_IDLE_MS * 100)).toBe(false)+ })++ it('leaves comfortable room above the renderer park window', () => {+ // TerminalNode parks an unmounted terminal (with its PTY subscription intact) for 5 minutes+ // before detaching it. A parked terminal is still a SUBSCRIBER, so the sweep would skip it+ // anyway — but the threshold must never be close enough for that to be the only reason.+ const TERM_PARK_MS = 5 * 60 * 1000+ expect(REAP_IDLE_MS).toBeGreaterThanOrEqual(2 * TERM_PARK_MS)+ })+})diff --git a/src/core/pty-reap.ts b/src/core/pty-reap.tsnew file mode 100644index 000000000..2f0984cdf--- /dev/null+++ b/src/core/pty-reap.ts@@ -0,0 +1,64 @@+/**+ * IDLE REAP: give pty devices back to the OS without killing anybody's work.+ *+ * macOS caps pty devices system-wide (`kern.tty.ptmx_max`, 511 by default) and on 2026-08-11 this+ * app was a large part of a machine that hit it: 62 live PTYs in PtyManager, 18 tmux sessions, ~19+ * ssh children. Every terminal after that spawned black (see pty-devices.ts, which now says so).+ *+ * The normal release paths — the last subscriber's `pty:kill`, `dropClient` when a window/tab+ * vanishes, the renderer's 5-minute park expiry — already return the pty client for anything the+ * user actually closed. This sweep is the SAFETY NET underneath them: every one of those paths is a+ * hook that has to be wired (window 'closed', 'render-process-gone', the relay's socket teardown,+ * the peer registry's gone-hook), and a hook that is missed leaves a session subscribed to a client+ * that no longer exists — holding a pty device, a tmux client and an ssh child, for the life of the+ * process, with nothing left that could ever detach it.+ *+ * WHAT IT MAY TOUCH, and why each half of the rule is load-bearing:+ * - TMUX-BACKED only (local `nt-<id>` or the remote tmux an SSH project attaches to). The tmux+ * session, its processes and its scrollback all live SERVER-side and survive the client+ * detaching; the next `pty:create` re-attaches with `new-session -A` and the user sees their+ * work redrawn. A session with no tmux underneath — an ssh-direct terminal, or any shell spawned+ * with tmux off — has no such copy: releasing its pty client ends the shell and everything in+ * it. That is data loss, so it is never reaped.+ * - UNWATCHED only: no subscriber whose client is still attached, and no relay sink. A sink is a+ * watcher (somebody's phone is mirroring the session), and a parked terminal is still a+ * subscriber — the renderer holds its subscription for the whole park window precisely so a+ * remount is instant.+ * And it NEVER kills a tmux session. Sessions in closed projects run forever by design; the reclaim+ * path for those is the user's own "Recently closed → delete", not a timer.+ */++/**+ * How long a session must have been unwatched before its client pty is released.+ *+ * Comfortably longer than the renderer's park window (`TERM_PARK_MS`, 5 minutes in+ * renderer/nodes/TerminalNode.tsx), and deliberately not just longer: a parked terminal keeps its+ * subscription, so the sweep already skips it on the `watched` test — the margin is so that the two+ * mechanisms cannot come to depend on each other's timing. Ten minutes with nobody attached is also+ * far past any human "I'll be right back": the cost of reaping is one tmux redraw on return, the+ * cost of not reaping is a pty device held forever.+ */+export const REAP_IDLE_MS = 10 * 60 * 1000++/**+ * How often the sweep runs. A minute is fine granularity against a ten-minute threshold and costs a+ * walk of a map with tens of entries — nothing is spawned, and a session that IS watched is decided+ * by a set lookup.+ */+export const REAP_SWEEP_MS = 60_000++/** One session as the reap decision sees it. */+export interface ReapCandidate {+ /** A tmux session (local or remote) is holding this work, so the client pty is expendable. */+ tmuxBacked: boolean+ /** Any subscriber whose client is still attached, or a relay sink. */+ watched: boolean+ /** When the sweep first saw it with no watcher; `null` = never (it has always had one). */+ unwatchedSince: number | null+}++/** Pure: may this session's client pty be released now? */+export function shouldReap(c: ReapCandidate, now: number, idleMs = REAP_IDLE_MS): boolean {+ if (!c.tmuxBacked || c.watched || c.unwatchedSince === null) return false+ return now - c.unwatchedSince >= idleMs+}