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): close the master fd on detach + raise the fd soft limit
enes42ac552b7a2c
diff --git a/src/main/index.ts b/src/main/index.tsindex 215be3c3a..32d2933b7 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -126,6 +126,18 @@ if (!gotSingleInstanceLock) {// The actual request handler is installed post-ready via initMediaProtocol().registerMediaScheme()+// Raise the soft file-descriptor limit (macOS/Linux; no-op elsewhere). macOS launches GUI apps+// with a soft limit of 256, which a canvas full of terminals genuinely needs to exceed: every+// attached PTY holds a master fd here, plus hook-server sockets and transcript tails. 256 was+// hit in the field (posix_spawnp failures with ~34 terminals in one project).+if (process.platform !== 'win32' && typeof process.setFdLimit === 'function') {+ try {+ process.setFdLimit(8192)+ } catch (e) {+ console.warn('[main] could not raise fd limit', e)+ }+}+function createWindow(): BrowserWindow {const win = new BrowserWindow({width: 1400,diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex 27536845b..f9b003bb7 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -21,6 +21,7 @@ import {remoteCapturePaneArgs} from './remote-ssh/control-master'import { TMUX_SOCKET, sessionName } from './tmux-naming'+import { releasePty, type ReleasablePty } from './pty-release'import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'// How often we snapshot a live tmux session's scrollback to disk, so a machine reboot (which@@ -564,17 +565,18 @@ export class PtyManager {})} catch (err) {// node-pty surfaces the underlying failure as a bare "posix_spawnp failed." with no errno,- // so we can't tell EAGAIN/ENFILE apart here. The dominant cause is running out of PTYs/fds- // (macOS caps system-wide PTYs at kern.tty.ptmx_max, and this app keeps tmux sessions — and- // thus their PTYs — alive across restarts, so they accumulate). Re-throw with the resolved- // program + cwd + open-PTY count so the renderer surfaces an actionable message instead of- // an opaque stack, and the caller (create) rejects cleanly rather than leaving a blank node.+ // so we can't tell EMFILE/EAGAIN/ENOMEM apart here. In practice the dominant cause is THIS+ // process running out of file descriptors (macOS gives GUI apps a soft limit of only 256;+ // a field incident showed 253 fds used while the system PTY cap sat at 149/511). Re-throw+ // with the resolved program + cwd + live-PTY count so the renderer surfaces an actionable+ // message, and the caller (create) rejects cleanly rather than leaving a blank node.const openPtys = this.sessions.sizeconst reason = err instanceof Error ? err.message : String(err)throw new Error(`Failed to spawn terminal (${reason}). Program: ${file}, cwd: ${cwd}, live PTYs: ${openPtys}. ` +- `On macOS the system PTY limit (kern.tty.ptmx_max) may be exhausted — close unused ` +- `terminals or run \`tmux -L ${TMUX_SOCKET} kill-server\` to reclaim leaked sessions.`+ `The app process is likely out of file descriptors — restart the app to reclaim them ` ++ `(tmux sessions survive an app restart). If it recurs, reduce the number of open ` ++ `terminals in the active project.`)}@@ -688,7 +690,9 @@ export class PtyManager {// 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)- session.proc.kill()+ // 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.sessions.delete(sessionId)}@@ -832,7 +836,7 @@ export class PtyManager {// no output since the last periodic capture (unchanged pane content).if (session.persistKey && session.outputSinceSnapshot)finals.push(this.snapshotScrollback(session.persistKey, session.sshRemote))- session.proc.kill()+ releasePty(session.proc as ReleasablePty)}this.sessions.clear()return Promise.all(finals).then(() => undefined)diff --git a/src/main/pty-release.test.ts b/src/main/pty-release.test.tsnew file mode 100644index 000000000..f4628c81e--- /dev/null+++ b/src/main/pty-release.test.ts@@ -0,0 +1,60 @@+import { describe, it, expect } from 'vitest'+import { releasePty, type ReleasablePty } from './pty-release'++// Contract test with a stub: real node-pty is compiled against Electron's ABI and cannot load+// under vitest's node runtime, but the fd-leak fix is entirely about WHICH methods run in WHICH+// order — resume first (unblock a paused socket), then destroy (deterministic fd close) with a+// kill() fallback where destroy doesn't exist.+function stub(overrides: Partial<Record<'resume' | 'destroy' | 'kill', () => void>> = {}) {+ const calls: string[] = []+ const proc: ReleasablePty = {+ resume: overrides.resume ?? (() => calls.push('resume')),+ kill: overrides.kill ?? (() => calls.push('kill')),+ ...(overrides.destroy !== undefined || 'destroy' in overrides+ ? { destroy: overrides.destroy }+ : {})+ }+ return { proc, calls }+}++describe('releasePty', () => {+ it('resumes first, then prefers destroy (deterministic fd close) over kill', () => {+ const calls: string[] = []+ const proc: ReleasablePty = {+ resume: () => calls.push('resume'),+ kill: () => calls.push('kill'),+ destroy: () => calls.push('destroy')+ }+ releasePty(proc)+ expect(calls).toEqual(['resume', 'destroy'])+ })++ it('falls back to kill() when destroy is unavailable (winpty)', () => {+ const { proc, calls } = stub()+ releasePty(proc)+ expect(calls).toEqual(['resume', 'kill'])+ })++ it('a throwing resume() does not prevent the fd release', () => {+ const calls: string[] = []+ const proc: ReleasablePty = {+ resume: () => {+ throw new Error('socket closed')+ },+ kill: () => calls.push('kill'),+ destroy: () => calls.push('destroy')+ }+ expect(() => releasePty(proc)).not.toThrow()+ expect(calls).toEqual(['destroy'])+ })++ it('a throwing destroy/kill never propagates (process already dead)', () => {+ const proc: ReleasablePty = {+ resume: () => {},+ kill: () => {+ throw new Error('ESRCH')+ }+ }+ expect(() => releasePty(proc)).not.toThrow()+ })+})diff --git a/src/main/pty-release.ts b/src/main/pty-release.tsnew file mode 100644index 000000000..ff84fbc53--- /dev/null+++ b/src/main/pty-release.ts@@ -0,0 +1,31 @@+import type { IPty } from 'node-pty'++/** The subset of a node-pty terminal `releasePty` touches (destroy exists on UnixTerminal only). */+export type ReleasablePty = Pick<IPty, 'kill' | 'resume'> & { destroy?: () => void }++/**+ * Release a PTY client so its master fd is actually CLOSED, not just signalled.+ *+ * node-pty's `kill()` only sends SIGHUP to the child; the master fd is closed later, when the+ * socket reads EOF and emits 'close'. That never happens while the pty is `pause()`d — and our+ * xterm flow control pauses busy ptys — so a detach (`kill()`) of a paused session leaked one+ * /dev/ptmx fd per cycle until the main process hit its fd limit and every new spawn failed+ * with `posix_spawnp failed.`.+ *+ * `UnixTerminal.destroy()` closes the fd deterministically (and SIGHUPs the child once the+ * stream is down), so prefer it. `resume()` first so any already-pending EOF/'close' can flow;+ * fall back to `kill()` where destroy doesn't exist (e.g. the winpty backend).+ */+export function releasePty(proc: ReleasablePty): void {+ try {+ proc.resume()+ } catch {+ /* socket may already be closed */+ }+ try {+ if (typeof proc.destroy === 'function') proc.destroy()+ else proc.kill()+ } catch {+ /* process already dead (ESRCH) — nothing to release */+ }+}