Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(terminal): a terminal that failed to SPAWN says so instead of sitting black

enesab111e1ed557
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index a03d2feba..d4876a43d 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -30,6 +30,7 @@ import {
remotePaneCursorArgs
} from './remote-ssh/control-master'
import { parsePaneCursor } from './pane-cursor'
+import { readSpawnResources, spawnResourceNote } from './spawn-resources'
import { TMUX_SOCKET, sessionName } from './tmux-naming'
import { bracketedInjection } from './paste-injection'
import { releasePty, type ReleasablePty } from './pty-release'
@@ -1269,8 +1270,14 @@ export class PtyManager {
const openPtys = this.sessions.size
const reason = err instanceof Error ? err.message : String(err)
const archNote = spawnHelperArchMismatch()
+ // MEASURED, not guessed. node-pty discards the errno, so the old message ended every failure
+ // with the same advice — restart, or rebuild node-pty for the wrong architecture. Both are
+ // real causes and both are rare, and reading as authoritative sent at least one field report
+ // (2026-08-06) chasing an architecture that was fine. `spawnResourceNote` states what it
+ // actually counted and only names a remedy the numbers support.
+ const resources = spawnResourceNote(readSpawnResources(), openPtys)
throw new Error(
- `Failed to spawn terminal (${reason}). Program: ${file}, cwd: ${cwd}, live PTYs: ${openPtys}. ` +
+ `Failed to spawn terminal (${reason}). Program: ${file}, cwd: ${cwd}, ${resources} ` +
(archNote ??
`If this persists, restart the app (tmux sessions survive a restart) or run ` +
`\`npm run rebuild\` in the repo — a release build may have rebuilt node-pty ` +
diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.ts
index a27b23de1..7222d4d67 100644
--- a/src/core/pty-single-user.test.ts
+++ b/src/core/pty-single-user.test.ts
@@ -124,7 +124,13 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =
afterEach(() => {
vi.useRealTimers()
resetPlatformForTests()
- fs.rmSync(userDataDir, { recursive: true, force: true })
+ // RETRIED, because this races a write it cannot wait for. The scrollback snapshot is fired and
+ // forgotten by design — `snapshotScrollback` is best-effort and nothing awaits it — so a test
+ // that triggered one can reach here while the file is still landing, and the rmdir then fails
+ // with ENOTEMPTY. Measured at roughly one full-suite run in six before this, always in this
+ // hook and never in an assertion; the name of the test it failed under ("still snapshots the
+ // scrollback") is the tell. `maxRetries` covers exactly this errno.
+ fs.rmSync(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 })
})
/** A manager WITHOUT init(): no tmux (plain-shell fallback), as the co-attach suite runs it. */
diff --git a/src/core/spawn-resources.test.ts b/src/core/spawn-resources.test.ts
new file mode 100644
index 000000000..3d1cf732a
--- /dev/null
+++ b/src/core/spawn-resources.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest'
+import { readSpawnResources, spawnResourceNote } from './spawn-resources'
+
+/**
+ * The 2026-08-06 report: terminals failing with `posix_spawnp failed.` and 33 live PTYs, on a
+ * message that advised restarting the app or rebuilding node-pty for the wrong architecture. Both
+ * are real causes, both are rare, and the message said it every time — so the diagnosis went to the
+ * architecture, which was fine.
+ *
+ * node-pty discards the errno, so the numbers below are the closest thing to one. What is pinned
+ * here is that a remedy is only named when the measurement supports it.
+ */
+describe('spawnResourceNote', () => {
+ it('states what it counted', () => {
+ const note = spawnResourceNote({ openFds: 120, fdSoft: 256, procSoft: 2000 }, 33)
+ expect(note).toContain('live PTYs: 33')
+ expect(note).toContain('open files: 120/256')
+ })
+
+ it('names the file-descriptor limit ONLY when the process is against it', () => {
+ const healthy = spawnResourceNote({ openFds: 120, fdSoft: 256, procSoft: null }, 33)
+ expect(healthy).not.toContain('FILE DESCRIPTOR')
+
+ const exhausted = spawnResourceNote({ openFds: 254, fdSoft: 256, procSoft: null }, 33)
+ expect(exhausted).toContain('FILE DESCRIPTOR')
+ // …and the remedy has to follow from the number, not from habit: a restart frees the
+ // descriptors and they fill again, so it is the wrong advice even though it "works".
+ expect(exhausted).toContain('close some terminals')
+ })
+
+ it('counts "a handful below the ceiling" as against it', () => {
+ // A spawn needs several descriptors at once, so the failure lands before the count is equal.
+ expect(spawnResourceNote({ openFds: 245, fdSoft: 256, procSoft: null }, 1)).toContain(
+ 'FILE DESCRIPTOR'
+ )
+ })
+
+ it('says nothing it could not measure, rather than inventing a figure', () => {
+ const note = spawnResourceNote({ openFds: null, fdSoft: null, procSoft: null }, 7)
+ expect(note).toBe('live PTYs: 7')
+ expect(note).not.toContain('FILE DESCRIPTOR')
+ })
+
+ it('reports a known limit even with no count to compare it against', () => {
+ expect(spawnResourceNote({ openFds: null, fdSoft: 256, procSoft: null }, 7)).toContain(
+ 'file limit: 256'
+ )
+ })
+})
+
+describe('readSpawnResources', () => {
+ it('measures this process without throwing', () => {
+ // It runs INSIDE an error path: a diagnostic that throws replaces a bad error message with no
+ // error message. The values themselves are the machine's, so only their shape is asserted.
+ const r = readSpawnResources()
+ expect(r.openFds === null || r.openFds > 0).toBe(true)
+ expect(r.fdSoft === null || r.fdSoft > 0).toBe(true)
+ expect(r.procSoft === null || r.procSoft > 0).toBe(true)
+ })
+})
diff --git a/src/core/spawn-resources.ts b/src/core/spawn-resources.ts
new file mode 100644
index 000000000..14b422c9e
--- /dev/null
+++ b/src/core/spawn-resources.ts
@@ -0,0 +1,99 @@
+import fs from 'fs'
+
+/**
+ * What the process had left when a spawn failed.
+ *
+ * `null` anywhere means "could not be measured", which is a different statement from zero and is
+ * rendered as silence rather than as a number — a diagnostic that invents a figure is worse than
+ * one that admits it does not know.
+ */
+export interface SpawnResources {
+ /** Open file descriptors right now. */
+ openFds: number | null
+ /** The process's own RLIMIT_NOFILE, soft — the one that actually bites. */
+ fdSoft: number | null
+ /** RLIMIT_NPROC, soft. */
+ procSoft: number | null
+}
+
+/**
+ * How close to a limit counts as "at" it.
+ *
+ * A spawn needs several descriptors at once (the pty master, the slave, the helper's pipes), so a
+ * process sitting a handful below its ceiling is already the cause even though the number is not
+ * literally equal. Deliberately generous in the direction of NAMING the limit: the cost of saying
+ * "you are out of file descriptors" when the true cause was something else is a wrong sentence in
+ * an error message; the cost of staying silent is the user re-running `npm run rebuild` for the
+ * third time, which is exactly what the old message told them to do.
+ */
+const NEAR_LIMIT = 16
+
+/**
+ * Measure what a failed spawn ran out of.
+ *
+ * node-pty reports every failure as a bare `posix_spawnp failed.` with the errno discarded, so the
+ * one thing that would answer this immediately — EMFILE vs EAGAIN vs ENOENT — never reaches us.
+ * These two numbers are the closest thing available, and they are cheap: a directory listing and a
+ * field already inside Node's own report.
+ *
+ * `/dev/fd` is the descriptor list on macOS AND on Linux (where it is a symlink to
+ * `/proc/self/fd`), which is why it is read directly rather than branched on platform. Note the
+ * listing itself holds a descriptor while it runs, so the count is honest to within one.
+ *
+ * Fail-open in every direction: this runs INSIDE an error path, and a diagnostic that throws would
+ * replace a bad error message with no error message at all.
+ */
+export function readSpawnResources(): SpawnResources {
+ let openFds: number | null = null
+ try {
+ openFds = fs.readdirSync('/dev/fd').length
+ } catch {
+ openFds = null
+ }
+ let fdSoft: number | null = null
+ let procSoft: number | null = null
+ try {
+ const limits = (
+ process.report?.getReport() as {
+ userLimits?: Record<string, { soft?: number | string }>
+ }
+ )?.userLimits
+ const soft = (key: string): number | null => {
+ const v = limits?.[key]?.soft
+ return typeof v === 'number' && Number.isFinite(v) ? v : null
+ }
+ fdSoft = soft('open_files')
+ procSoft = soft('max_user_processes')
+ } catch {
+ /* diagnostics only */
+ }
+ return { openFds, fdSoft, procSoft }
+}
+
+/**
+ * The sentence to append to a spawn failure — the measurement, and a remedy that FOLLOWS from it.
+ *
+ * Pure, so the wording can be pinned. What it must never do is repeat the old message's mistake:
+ * that one always advised restarting the app or rebuilding node-pty for the wrong architecture,
+ * which is a real cause but a rare one, and it read as authoritative. When the numbers say the
+ * process is out of file descriptors, say THAT; when they say nothing, say nothing and leave the
+ * generic advice as what it is — a guess of last resort.
+ */
+export function spawnResourceNote(r: SpawnResources, livePtys: number): string {
+ const parts: string[] = [`live PTYs: ${livePtys}`]
+ if (r.openFds !== null) {
+ parts.push(`open files: ${r.openFds}${r.fdSoft !== null ? `/${r.fdSoft}` : ''}`)
+ } else if (r.fdSoft !== null) {
+ parts.push(`file limit: ${r.fdSoft}`)
+ }
+ const outOfFds = r.openFds !== null && r.fdSoft !== null && r.openFds >= r.fdSoft - NEAR_LIMIT
+ const measured = parts.join(', ')
+ if (outOfFds) {
+ return (
+ `${measured}. This process is at its FILE DESCRIPTOR limit, which is what stopped the ` +
+ `spawn — close some terminals (or raise the limit) rather than restarting; a restart frees ` +
+ `them but they fill up again.`
+ )
+ }
+ return measured
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 0a06cc165..c62a87aa7 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -501,8 +501,29 @@ interface CoState {
* that coordinator the moment it lands here, so an idle canvas heals itself.
*/
offline: boolean
+ /**
+ * The spawn REJECTED — core could not start a process at all (node-pty's `posix_spawnp failed`,
+ * a missing program, a resource limit).
+ *
+ * Before this existed the create promise had no rejection handler: the failure surfaced as an
+ * unhandled rejection in the main process log and the node sat there as an EMPTY xterm — a black
+ * rectangle with no explanation and no way back short of deleting the node. That is the
+ * 2026-08-06 report ("some terminals are black after coming back to the app"), and the black is
+ * not a rendering fault at all; it is a terminal that was never started.
+ *
+ * Holds core's own message, which names the program, the cwd and what it measured — the user is
+ * the one who can act on "out of file descriptors" or "host unreachable", and hiding it helps
+ * nobody.
+ */
+ spawnError: string | null
+}
+const NO_CO: CoState = {
+ letterbox: false,
+ closed: null,
+ ended: false,
+ offline: false,
+ spawnError: null
}
-const NO_CO: CoState = { letterbox: false, closed: null, ended: false, offline: false }
const coStates = new Map<string, CoState>()
const coSubs = new Map<string, (s: CoState) => void>()
@@ -865,6 +886,17 @@ export function TerminalNode({
}))
}
+ // A spawn that FAILED (CoState.spawnError): nothing was started, so there is nothing to detach
+ // from — just clear the message and re-run the lifecycle effect. Whether it works depends on
+ // whatever core reported (a freed file descriptor, a host that came back), which is exactly why
+ // the message is on screen rather than in a log.
+ const retrySpawn = (): void => {
+ setCo(termKey, { spawnError: null })
+ updateNodeData(id, (n) => ({
+ respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1
+ }))
+ }
+
// "Not connected" (CoState.offline): the host was unreachable, so this node has no session
// anywhere. Ask the coordinator to re-establish the project's master NOW — it flushes the
// pending nodes (this one included) on success, which is what respawns them. We do NOT bump
@@ -2122,6 +2154,20 @@ export function TerminalNode({
if (cmd) writeWhenShellReady(cmd) // same shell-startup race as initialCommand
}
})
+ .catch((err: unknown) => {
+ // THE missing handler, and the answer to "some terminals are black" (2026-08-06).
+ //
+ // A rejected create means core started NOTHING: no session to tear down, no data gate to
+ // open, nothing to unwire. The only thing owed is telling the user — and until now nobody
+ // did. The rejection went nowhere, the node kept the empty xterm it had mounted with, and
+ // the result was a black rectangle with no message and no way back short of deleting the
+ // node. The failure was in the main-process log the whole time.
+ //
+ // `life.dead` first: a node unmounted while its spawn was in flight has no state worth
+ // writing, and `setCo` would publish into a key the next mount reads.
+ if (life.dead) return
+ setCo(termKey, { spawnError: err instanceof Error ? err.message : String(err) })
+ })
})()
// In-place agent restart (Canvas node menu / bulk palette): ask the CLI to quit, wait until a
@@ -3208,7 +3254,15 @@ export function TerminalNode({
</button>
</div>
)}
- {!co.closed && !co.ended && co.offline && (
+ {!co.closed && !co.ended && co.spawnError && (
+ <div className="term-node__closed nodrag">
+ <span>This terminal could not be started. {co.spawnError}</span>
+ <button className="term-node__reopen" onClick={retrySpawn}>
+ Try again
+ </button>
+ </div>
+ )}
+ {!co.closed && !co.ended && !co.spawnError && co.offline && (
<div className="term-node__closed nodrag">
<span>
Not connected to {data.ssh ? `${(data.ssh as SshConnection).user}@${(data.ssh as SshConnection).host}` : 'the host'} — this session was not started