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): never park-kill a working agent on a plain shell (#126)

enes64e2b97f774b
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 321006a19..9bde21371 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -16,7 +16,7 @@ import {
type Settings,
type TmuxStatus
} from '../shared/types'
-import { findCommand, tmuxInstall } from './tmux-hint'
+import { findCommand, findFixedTmux, tmuxInstall } from './tmux-hint'
import { hookServer, PERM_WAIT_SECS_DEFAULT } from './agents/hook-server'
import {
probeSaysAbsent,
@@ -156,20 +156,32 @@ bind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X
`
}
-/** Resolve an absolute tmux path (GUI apps don't inherit the shell PATH). Subprocess-free:
- * the old fallback here was a SYNC login-shell `command -v tmux` — sourcing the profile
- * (nvm/conda: 100-800ms) on the main thread, re-triggered every 3s by the tmux-missing
- * banner's install poll, freezing all windows and IPC each time. Now it walks the cached
- * login-shell PATH instead; before that async probe settles a nonstandard location can be
- * missed, which init()'s post-probe ensureTmux() re-run and tmuxStatus()'s re-probe cover. */
+/**
+ * Resolve an absolute tmux path (GUI apps don't inherit the shell PATH). Subprocess-free: the old
+ * fallback here was a SYNC login-shell `command -v tmux` — sourcing the profile (nvm/conda:
+ * 100-800ms) on the main thread, re-triggered every 3s by the tmux-missing banner's install poll,
+ * freezing all windows and IPC each time. Now it walks a fixed candidate list
+ * (`tmuxCandidatePaths` — Homebrew, MacPorts, Nix, Linuxbrew, the distro paths) and then the
+ * cached login-shell PATH.
+ *
+ * BEFORE THAT ASYNC PATH PROBE SETTLES, a tmux living ONLY on the user's shell PATH is still
+ * invisible, and a session spawned in that window silently becomes a plain shell with no
+ * persistence — the window this candidate list narrows, and the reason issue #126 could bite a
+ * machine that has tmux installed. Two things close it after the fact: init()'s post-probe
+ * `ensureTmux()` re-run and `tmuxStatus()`'s re-probe, both of which upgrade NEW sessions without
+ * a restart. A session already spawned plain is NOT migrated (there is no way to move a running
+ * process into a tmux pane); its recovery is the node's own Refresh/respawn, which re-creates it
+ * through the now-resolved tmux.
+ */
function findTmux(): string | null {
- for (const c of ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux', '/bin/tmux']) {
- try {
- if (fs.existsSync(c)) return c
- } catch {
- // ignore
- }
+ let user: string | null = null
+ try {
+ user = os.userInfo().username
+ } catch {
+ // no passwd entry (some containers) — findFixedTmux falls back to the home basename
}
+ const fixed = findFixedTmux((p) => fs.existsSync(p), os.homedir(), user)
+ if (fixed) return fixed
return findInPathString('tmux', shellPathNow() ?? process.env.PATH)
}
@@ -1122,9 +1134,13 @@ export class PtyManager {
}
/** Probe tmux and write/push the generated config. Idempotent and safe to re-run: a later
- * successful probe (e.g. right after the banner's install command finishes) brings tmux
- * up for NEW sessions without an app restart — existing plain-shell sessions are left
- * alone. No-op while tmux is already resolved or before init() provided settings. */
+ * successful probe (the banner's install command finishing, or init()'s post-PATH-probe re-run
+ * finding a tmux only the login shell knew about) brings tmux up for NEW sessions without an
+ * app restart — existing plain-shell sessions are left alone. There is deliberately no
+ * migration: a process already running under a bare pty cannot be moved into a tmux pane, so
+ * the recovery for one of those is the node's own refresh/respawn, which re-creates the session
+ * through the now-resolved tmux (at the cost of that shell's state, as any respawn is).
+ * No-op while tmux is already resolved or before init() provided settings. */
ensureTmux(): void {
if (this.tmuxPath || !this.getSettings) return
const found = findTmux()
@@ -1470,9 +1486,12 @@ export class PtyManager {
// our tmux always runs `mouse on`, so enabling these unconditionally matches its client state.
// Rides `base` so it reaches the renderer on BOTH the resized and screen-painted branches.
const coAttachMouse = existing.persistKey ? true : undefined
+ // Same source, different question (and different consumer): a joiner needs to know whether the
+ // session it landed on survives losing a client, because its own unmount may park it.
+ const persistent = !!existing.persistKey
const base: PtyCreateResult = existing.accountFallback
- ? { sessionId: existingId, fresh: false, accountFallback: true, coAttachMouse }
- : { sessionId: existingId, fresh: false, coAttachMouse }
+ ? { sessionId: existingId, fresh: false, accountFallback: true, coAttachMouse, persistent }
+ : { sessionId: existingId, fresh: false, coAttachMouse, persistent }
if (resized) return Promise.resolve(base) // tmux is redrawing this client — do not paint twice
// An empty capture (plain shell — no tmux to capture; a tmux/ssh blip) is OMITTED, never sent
// as '': the renderer must not reset a terminal for nothing. A plain-shell joiner therefore
@@ -1530,9 +1549,16 @@ export class PtyManager {
// so the session env below picks it up — awaiting keeps the event loop free either way.
await resolveShellPath()
const sessionId = this.spawnSession(options, clientId, undefined)
+ const spawned = this.sessions.get(sessionId)
// Surface a missing-account-dir fallback so the renderer can flag the node's account chip.
- const accountFallback = this.sessions.get(sessionId)?.accountFallback
- return accountFallback ? { sessionId, fresh, accountFallback } : { sessionId, fresh }
+ const accountFallback = spawned?.accountFallback
+ // The session's `persistKey` is set iff the spawn actually landed on a tmux, local or remote
+ // (`persisted` in spawnSession) — i.e. exactly "this session survives losing its client",
+ // which is what the renderer's cache-dispose levers must not assume. See PtyCreateResult.
+ const persistent = !!spawned?.persistKey
+ return accountFallback
+ ? { sessionId, fresh, accountFallback, persistent }
+ : { sessionId, fresh, persistent }
}
/** Does the node's remote tmux session exist (over the project's ControlMaster)? Async so the
diff --git a/src/core/pty-tmux-late-probe.test.ts b/src/core/pty-tmux-late-probe.test.ts
new file mode 100644
index 000000000..4e845c00e
--- /dev/null
+++ b/src/core/pty-tmux-late-probe.test.ts
@@ -0,0 +1,70 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import fs from 'fs'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+
+/**
+ * THE SILENT PLAIN-SHELL WINDOW.
+ *
+ * `findTmux` is subprocess-free by design (a sync login shell on the main thread froze every
+ * window for 100-800ms per lookup), so it knows two things: a FIXED list of install locations, and
+ * the login-shell PATH — which is resolved ASYNCHRONOUSLY and is simply not available for the
+ * first moments of a run. A tmux that lives in neither is invisible, and a session spawned in that
+ * window becomes a plain shell with NO PERSISTENCE and no banner: the app never says so, and the
+ * park/offscreen disposes that are merely "detach a tmux client" everywhere else become "kill the
+ * shell and the agent CLI in it" (issue #126).
+ *
+ * The fixed list closing as much of that window as it cheaply can is one half (tmux-hint.test.ts);
+ * this is the other half — the guarantee that the window CLOSES: `init()` re-runs `ensureTmux()`
+ * when the PATH probe lands, so a nonstandard tmux is picked up for NEW sessions with no restart.
+ * Sessions already spawned plain are not migrated (a running process cannot be moved into a tmux
+ * pane); their recovery is the node's own refresh/respawn.
+ */
+
+const probe = vi.hoisted(() => ({ shellPath: undefined as string | undefined }))
+vi.mock('./exec-path', () => ({
+ resolveShellPath: () => Promise.resolve(probe.shellPath ?? null),
+ shellPathNow: () => probe.shellPath,
+ findInPathString: (bin: string, pathStr: string | null | undefined) =>
+ pathStr === '/opt/weird/bin' ? `/opt/weird/bin/${bin}` : null,
+ findExecutableSync: () => null
+}))
+vi.mock('node-pty', () => ({ spawn: () => ({ onData: () => {}, onExit: () => {}, kill: () => {} }) }))
+
+describe('tmux discovery after the login-shell PATH probe settles', () => {
+ beforeEach(() => {
+ probe.shellPath = undefined
+ initPlatform(fakePlatform())
+ // No tmux in ANY fixed location — the whole point is a tmux only the shell PATH knows about.
+ vi.spyOn(fs, 'existsSync').mockReturnValue(false)
+ // ensureTmux writes the generated tmux.conf into userDataDir; the fake's dir does not exist.
+ vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
+ })
+ afterEach(() => {
+ vi.restoreAllMocks()
+ resetPlatformForTests()
+ })
+
+ it('upgrades new sessions once the probe lands, without a restart', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager()
+ mgr.init(() => ({ tmuxEnabled: true, tmuxScrollback: 10_000 }) as never)
+ // The probe has not settled: the nonstandard install is invisible and this run would spawn
+ // plain shells. This is the window the fixed candidate list narrows but cannot delete.
+ expect(mgr.getTmuxBin()).toBeNull()
+
+ probe.shellPath = '/opt/weird/bin'
+ await Promise.resolve() // let init()'s `resolveShellPath().then(() => ensureTmux())` run
+ await Promise.resolve()
+ expect(mgr.getTmuxBin()).toBe('/opt/weird/bin/tmux')
+ })
+
+ it('tmuxStatus() re-probes too, so the banner clears itself', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager()
+ mgr.init(() => ({ tmuxEnabled: true, tmuxScrollback: 10_000 }) as never)
+ expect(mgr.tmuxStatus().available).toBe(false)
+ probe.shellPath = '/opt/weird/bin'
+ expect(mgr.tmuxStatus().available).toBe(true)
+ })
+})
diff --git a/src/core/tmux-hint.test.ts b/src/core/tmux-hint.test.ts
index 4871eefbe..5ad018160 100644
--- a/src/core/tmux-hint.test.ts
+++ b/src/core/tmux-hint.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { findCommand, tmuxInstall } from './tmux-hint'
+import { findCommand, findFixedTmux, tmuxCandidatePaths, tmuxInstall } from './tmux-hint'
describe('tmuxInstall', () => {
it('darwin with brew: one-click brew install', () => {
@@ -50,3 +50,47 @@ describe('findCommand', () => {
expect(findCommand('brew', {}, (p) => p === '/usr/local/bin/brew')).toBe(true)
})
})
+
+describe('tmuxCandidatePaths / findFixedTmux', () => {
+ it('keeps the four historical paths first, in their historical order', () => {
+ expect(tmuxCandidatePaths('/Users/dev', 'dev').slice(0, 4)).toEqual([
+ '/opt/homebrew/bin/tmux',
+ '/usr/local/bin/tmux',
+ '/usr/bin/tmux',
+ '/bin/tmux'
+ ])
+ })
+
+ it('covers the package managers the four fixed paths missed (silent plain-shell fallback)', () => {
+ const paths = tmuxCandidatePaths('/Users/dev', 'dev')
+ expect(paths).toContain('/opt/local/bin/tmux') // MacPorts
+ expect(paths).toContain('/run/current-system/sw/bin/tmux') // NixOS system profile
+ expect(paths).toContain('/Users/dev/.nix-profile/bin/tmux') // nix single-user profile
+ expect(paths).toContain('/etc/profiles/per-user/dev/bin/tmux') // home-manager / nix-darwin
+ expect(paths).toContain('/home/linuxbrew/.linuxbrew/bin/tmux') // Linuxbrew
+ })
+
+ it('falls back to the home directory basename when no user name is known', () => {
+ expect(tmuxCandidatePaths('/home/ada')).toContain('/etc/profiles/per-user/ada/bin/tmux')
+ // No home at all (an odd/locked-down environment): the home-derived paths are simply absent,
+ // never emitted as `undefined/...`.
+ expect(tmuxCandidatePaths(null).some((p) => p.includes('undefined'))).toBe(false)
+ expect(tmuxCandidatePaths(null).some((p) => p.includes('.nix-profile'))).toBe(false)
+ })
+
+ it('returns the FIRST candidate that exists', () => {
+ const seen: string[] = []
+ const exists = (p: string): boolean => (seen.push(p), p === '/opt/local/bin/tmux')
+ expect(findFixedTmux(exists, '/Users/dev', 'dev')).toBe('/opt/local/bin/tmux')
+ expect(seen[0]).toBe('/opt/homebrew/bin/tmux') // ordered walk, homebrew still wins first
+ expect(findFixedTmux(() => false, '/Users/dev', 'dev')).toBeNull()
+ })
+
+ it('treats a throwing existsSync as "not here" rather than failing the whole probe', () => {
+ const exists = (p: string): boolean => {
+ if (p === '/opt/homebrew/bin/tmux') throw new Error('EPERM')
+ return p === '/usr/bin/tmux'
+ }
+ expect(findFixedTmux(exists, '/Users/dev', 'dev')).toBe('/usr/bin/tmux')
+ })
+})
diff --git a/src/core/tmux-hint.ts b/src/core/tmux-hint.ts
index 487893c7f..014535458 100644
--- a/src/core/tmux-hint.ts
+++ b/src/core/tmux-hint.ts
@@ -54,6 +54,59 @@ export function tmuxInstall(
* findTmux in pty-manager. Checked after the process PATH. */
const COMMON_BIN_DIRS = ['/opt/homebrew/bin', '/usr/local/bin', '/opt/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin']
+/**
+ * Absolute places a tmux binary is routinely installed, walked in order by `findFixedTmux` — the
+ * subprocess-free half of pty-manager's `findTmux` (the other half walks the login-shell PATH,
+ * which is only accurate once the async probe has settled).
+ *
+ * The list is FIXED on purpose: this runs on the spawn path, and a shell-out to find tmux is the
+ * exact thing `exec-path.ts` exists to have removed (a sync login shell on the main thread cost
+ * 100-800ms per lookup). Missing an install location is not cosmetic — it silently drops the app
+ * into the plain-shell fallback, where a park/offscreen dispose kills the shell AND whatever agent
+ * CLI is running in it (issue #126) instead of merely detaching a tmux client.
+ *
+ * The first four are the historical list and keep their historical order (Homebrew arm64, then
+ * Homebrew Intel / manual `/usr/local`, then the distro paths); the rest are the package managers
+ * that were falling through: MacPorts, Nix (system profile, per-user profile, home-manager /
+ * nix-darwin) and Linuxbrew. `home`/`user` come from the caller (`os.homedir()` /
+ * `os.userInfo().username`); an unknown home simply omits the paths derived from it.
+ */
+export function tmuxCandidatePaths(home?: string | null, user?: string | null): string[] {
+ const paths = [
+ '/opt/homebrew/bin/tmux',
+ '/usr/local/bin/tmux',
+ '/usr/bin/tmux',
+ '/bin/tmux',
+ '/opt/local/bin/tmux',
+ '/run/current-system/sw/bin/tmux',
+ '/home/linuxbrew/.linuxbrew/bin/tmux'
+ ]
+ if (home) paths.push(`${home}/.nix-profile/bin/tmux`)
+ // The per-user nix profile is keyed by USER NAME, not by home path; the home basename is the
+ // fallback because that is what it is on every platform this list targets.
+ const name = user || (home ? home.slice(home.lastIndexOf('/') + 1) : '')
+ if (name) paths.push(`/etc/profiles/per-user/${name}/bin/tmux`)
+ return paths
+}
+
+/** First `tmuxCandidatePaths` entry that exists, or null. `exists` is injected (fs.existsSync in
+ * production) so the walk stays pure and testable; a throwing `exists` reads as "not here", never
+ * as a failed probe — one unreadable directory must not hide a tmux two entries later. */
+export function findFixedTmux(
+ exists: (path: string) => boolean,
+ home?: string | null,
+ user?: string | null
+): string | null {
+ for (const candidate of tmuxCandidatePaths(home, user)) {
+ try {
+ if (exists(candidate)) return candidate
+ } catch {
+ // unreadable — keep looking
+ }
+ }
+ return null
+}
+
/** Is `name` on the process PATH or in the common bin dirs? `exists` is injected (fs.existsSync
* in production) so the lookup stays pure and testable. */
export function findCommand(
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index e0cacb51e..c94856e04 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -59,7 +59,14 @@ import {
} from '../terminal/terminal-config'
import { useXtermVisualSettings } from '../terminal/useXtermVisualSettings'
import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'
-import { PARK_MAX, planParkEviction } from '../terminal/park-budget'
+import {
+ PARK_MAX,
+ armParkExpiry,
+ canDisposePark,
+ disposableParks,
+ planParkEviction,
+ type ParkTimer
+} from '../terminal/park-budget'
import {
mayDisposeOffscreen,
offscreenCoreIsRemote,
@@ -265,6 +272,12 @@ export function setSshRetryHandler(
* COUNT as well as time — beyond `PARK_MAX` the oldest entries are evicted early (see
* `terminal/park-budget.ts`), so a remount past the cap is the same warm reattach as one past the
* window.
+ *
+ * "The PTY client detaches; the session keeps running" is true ONLY with tmux underneath. On the
+ * plain-shell fallback the pty IS the shell, so the same dispose kills the shell and whatever runs
+ * in it — which is how a project switch could terminate a working agent mid-task (issue #126).
+ * Every dispose driven purely by the BUDGET (window expiry, LRU cap, memory-pressure lever) is
+ * therefore gated on `canDisposePark`; a deliberate dispose (delete, respawn, dead session) is not.
*/
interface ParkedTerminal {
term: Terminal
@@ -272,6 +285,12 @@ interface ParkedTerminal {
search: SearchAddon
transport: TerminalTransport
sessionId: string
+ /** The node this park belongs to — the key into `agentStatus.byId` the protection reads. (The
+ * map's own key is session-scoped, `terminalKey(sessionId, nodeId)`, so it is not the node id.) */
+ nodeId: string
+ /** `PtyCreateResult.persistent`: the session survives a client kill (tmux, local or remote).
+ * False = plain shell, where disposing this park ends the session for real. */
+ tmuxBacked: boolean
/** Session-scoped teardown (transport/xterm listeners) — run only at final dispose. */
cleanups: Array<() => void>
/**
@@ -281,13 +300,31 @@ interface ParkedTerminal {
* cleanup and the park dispose all race for it.
*/
life: SessionLife & { killed: boolean }
- timer: ReturnType<typeof setTimeout>
+ /** The park window, which RE-ARMS while the entry is protected (see `armParkExpiry`). */
+ timer: ParkTimer
}
const parkedTerminals = new Map<string, ParkedTerminal>()
const TERM_PARK_MS = 5 * 60 * 1000
+/** May the BUDGET levers dispose this park? Reads the node's live agent state the way the
+ * hibernation sweep does (the same store, non-reactively) and pairs it with the session's
+ * tmux-backedness. An unknown key is disposable — there is nothing there to protect.
+ *
+ * `useAgentStatus` is the DEFAULT (local-core) store, like every other status read in this file.
+ * A relay tab's status lives in its own session-scoped store, so a remote node reads as "no
+ * agent" here — which changes nothing: a remote session is tmux-backed on the remote host, so it
+ * is disposable either way. */
+function parkDisposable(key: string): boolean {
+ const p = parkedTerminals.get(key)
+ if (!p) return true
+ return canDisposePark({
+ tmuxBacked: p.tmuxBacked,
+ agentState: useAgentStatus.getState().byId[p.nodeId]?.state
+ })
+}
+
function disposeParked(p: ParkedTerminal): void {
- clearTimeout(p.timer)
+ p.timer.cancel()
// Mark the session dead BEFORE tearing it down: a spawn continuation still awaiting its history
// seed reads this to see that the session it handed off no longer exists (→ teardown, not
// continue-parked), instead of wiring listeners onto a killed session.
@@ -313,9 +350,16 @@ export function disposeParkedTerminal(key: string): void {
/** Memory-pressure lever: drop EVERY parked terminal now, without waiting out `TERM_PARK_MS`. The
* park is a cache, not state — each dropped entry costs only its warm re-adopt, and the node
* re-mounts as an ordinary warm reattach (tmux redraws; the session and its scrollback are
- * untouched). Idempotent; iterates a copy because `disposeParkedTerminal` mutates the map. */
+ * untouched). Idempotent; iterates a copy because `disposeParkedTerminal` mutates the map.
+ *
+ * EXCEPT the protected ones (`canDisposePark`): for a plain-shell session the sentence above is
+ * false — the dispose is not a re-adopt cost, it is the end of the session — so a park holding a
+ * working agent on a non-tmux shell is left alone and released by its own expiry re-check.
+ * Everything else still goes, which is the whole point of the lever. */
export function disposeAllParkedTerminals(): void {
- for (const key of [...parkedTerminals.keys()]) disposeParkedTerminal(key)
+ for (const key of disposableParks([...parkedTerminals.keys()], parkDisposable)) {
+ disposeParkedTerminal(key)
+ }
}
/** Session-scoped keys (`terminalKey`) whose next unmount must dispose (not park) — set on permanent
@@ -1359,7 +1403,7 @@ export function TerminalNode({
const parked = parkedTerminals.get(termKey)
if (parked) {
parkedTerminals.delete(termKey)
- clearTimeout(parked.timer)
+ parked.timer.cancel()
}
const s = useSettings.getState().settings
@@ -1585,6 +1629,12 @@ export function TerminalNode({
}
let sessionId: string | null = parked ? parked.sessionId : null
+ // Does this session survive losing its client (tmux, local or remote)? Read off the create
+ // result below, carried over when adopting a park. Seeded `true` — the historical assumption —
+ // so a session whose create has not answered yet, or a core too old to say
+ // (`PtyCreateResult.persistent` absent), behaves exactly as it always did rather than being
+ // protected on a guess. See `canDisposePark`.
+ let sessionPersistent = parked ? parked.tmuxBacked : true
let disposed = false
// Last cols/rows REPORTED to the pty (seeded at create): a resize IPC makes tmux redraw the
// whole pane, so a same-size fit (e.g. the ResizeObserver's initial tick right after mount)
@@ -2240,6 +2290,7 @@ export function TerminalNode({
screen,
cursor,
coAttachMouse,
+ persistent,
unavailable
}) => {
// REFUSED: `requireRemote` and core could not spawn remotely (the master died inside our
@@ -2278,6 +2329,8 @@ export function TerminalNode({
let offData: (() => void) | undefined
if (onDisposed()) return
sessionId = sid
+ // `?? true`: an absent flag is an older core over the relay, not a plain shell.
+ sessionPersistent = persistent ?? true
if (fellBack) setAccountFallback(true)
// Catch up a size change that landed while the spawn was in flight (applyFit skips the
// IPC until sessionId is set, and the observer won't re-fire without another change).
@@ -3023,26 +3076,38 @@ export function TerminalNode({
search: searchAddon,
transport,
sessionId,
+ nodeId: id,
+ tmuxBacked: sessionPersistent,
cleanups,
life,
- timer: setTimeout(() => {
- if (parkedTerminals.get(termKey) === entry) {
- parkedTerminals.delete(termKey)
- disposeParked(entry)
- }
- }, TERM_PARK_MS)
+ // The window RE-ARMS (PARK_RECHECK_MS) while this park is protected, instead of killing a
+ // plain shell that is still running the user's agent — and instead of leaking the park,
+ // which is what a plain "skip the dispose" would do.
+ timer: armParkExpiry(
+ () => parkDisposable(termKey),
+ () => {
+ if (parkedTerminals.get(termKey) === entry) {
+ parkedTerminals.delete(termKey)
+ disposeParked(entry)
+ }
+ },
+ TERM_PARK_MS
+ )
}
disposeParkedTerminal(termKey) // defensive: never stack two entries for one node
parkedTerminals.set(termKey, entry)
// Enforce the park count cap: evict the OLDEST parks (their next remount becomes a warm
- // tmux reattach — the post-window behavior, just earlier). Never the entry just parked.
+ // tmux reattach — the post-window behavior, just earlier). Never the entry just parked,
+ // and never a PROTECTED one — the plan skips those and takes the next-oldest disposable
+ // park instead, and the cap is simply exceeded when every park is protected (see
+ // planParkEviction: a bounded cache overrun beats killing live work).
// Eviction MUST observe the POST-ADOPTION map: a project switch flushes every outgoing
// node's cleanup (parking each) BEFORE any incoming node's mount effect adopts its own
// park, so evicting inline would dispose the parks the incoming project is about to
// re-adopt. A microtask is what defers past the whole synchronous passive-effect flush
// (cleanups AND mounts); adoption has removed its entries from the map by then.
queueMicrotask(() => {
- for (const k of planParkEviction([...parkedTerminals.keys()], PARK_MAX)) {
+ for (const k of planParkEviction([...parkedTerminals.keys()], PARK_MAX, parkDisposable)) {
if (k !== termKey) disposeParkedTerminal(k)
}
})
diff --git a/src/renderer/terminal/park-budget.test.ts b/src/renderer/terminal/park-budget.test.ts
index 0eebc5b16..7289b5d00 100644
--- a/src/renderer/terminal/park-budget.test.ts
+++ b/src/renderer/terminal/park-budget.test.ts
@@ -1,5 +1,12 @@
import { describe, it, expect } from 'vitest'
-import { PARK_MAX, planParkEviction } from './park-budget'
+import {
+ PARK_MAX,
+ PARK_RECHECK_MS,
+ armParkExpiry,
+ canDisposePark,
+ disposableParks,
+ planParkEviction
+} from './park-budget'
describe('planParkEviction', () => {
it('returns nothing at or under the cap', () => {
@@ -14,4 +21,98 @@ describe('planParkEviction', () => {
const keys = Array.from({ length: 13 }, (_, i) => `k${i}`)
expect(planParkEviction(keys, PARK_MAX)).toEqual(['k0'])
})
+ it('skips protected parks and takes the next disposable one instead', () => {
+ // 'a' is protected → the cap is still met, by evicting the next-oldest disposable park.
+ expect(planParkEviction(['a', 'b', 'c', 'd'], 2, (k) => k !== 'a')).toEqual(['b', 'c'])
+ })
+ it('lets the cap be exceeded rather than kill protected parks', () => {
+ // Nothing disposable left: the plan is empty and the park runs over PARK_MAX. Documented
+ // tradeoff — a cache overrun costs RAM, killing a plain shell costs the user's running work.
+ expect(planParkEviction(['a', 'b', 'c', 'd'], 2, () => false)).toEqual([])
+ expect(planParkEviction(['a', 'b', 'c', 'd'], 2, (k) => k === 'd')).toEqual(['d'])
+ })
+})
+
+describe('canDisposePark', () => {
+ it('protects a NON-tmux park whose agent is working/waiting/blocked', () => {
+ for (const agentState of ['working', 'waiting', 'blocked'] as const) {
+ expect(canDisposePark({ tmuxBacked: false, agentState })).toBe(false)
+ }
+ })
+ it('disposes a non-tmux park whose agent is done', () => {
+ expect(canDisposePark({ tmuxBacked: false, agentState: 'done' })).toBe(true)
+ })
+ it('disposes a non-tmux park with no agent at all (a plain terminal)', () => {
+ expect(canDisposePark({ tmuxBacked: false })).toBe(true)
+ })
+ it('disposes a TMUX-backed park even while its agent works — the kill only detaches a client', () => {
+ expect(canDisposePark({ tmuxBacked: true, agentState: 'working' })).toBe(true)
+ expect(canDisposePark({ tmuxBacked: true, agentState: 'waiting' })).toBe(true)
+ })
+})
+
+describe('disposableParks', () => {
+ it('drops everything except the protected parks', () => {
+ expect(disposableParks(['a', 'b', 'c'], (k) => k !== 'b')).toEqual(['a', 'c'])
+ expect(disposableParks(['a', 'b'], () => true)).toEqual(['a', 'b'])
+ expect(disposableParks(['a', 'b'], () => false)).toEqual([])
+ })
+})
+
+describe('armParkExpiry', () => {
+ /** Minimal injectable timer pair: fire(n) runs the nth armed callback. */
+ function fakeTimers(): {
+ timers: { set: (fn: () => void, ms: number) => number; clear: (h: number) => void }
+ armed: Array<{ fn: () => void; ms: number; cleared: boolean }>
+ } {
+ const armed: Array<{ fn: () => void; ms: number; cleared: boolean }> = []
+ return {
+ armed,
+ timers: {
+ set: (fn, ms) => armed.push({ fn, ms, cleared: false }) - 1,
+ clear: (h) => {
+ armed[h].cleared = true
+ }
+ }
+ }
+ }
+
+ it('disposes when the window expires and the park is disposable', () => {
+ const { timers, armed } = fakeTimers()
+ let disposed = 0
+ armParkExpiry(() => true, () => disposed++, 5000, timers)
+ expect(armed[0].ms).toBe(5000)
+ armed[0].fn()
+ expect(disposed).toBe(1)
+ expect(armed).toHaveLength(1) // nothing re-armed
+ })
+
+ it('re-arms at PARK_RECHECK_MS instead of disposing while the park is protected', () => {
+ const { timers, armed } = fakeTimers()
+ let disposable = false
+ let disposed = 0
+ armParkExpiry(() => disposable, () => disposed++, 5000, timers)
+ armed[0].fn()
+ expect(disposed).toBe(0)
+ expect(armed).toHaveLength(2)
+ expect(armed[1].ms).toBe(PARK_RECHECK_MS)
+ // Still protected → still re-checking, never leaked into a permanent park.
+ armed[1].fn()
+ expect(disposed).toBe(0)
+ expect(armed[2].ms).toBe(PARK_RECHECK_MS)
+ // The agent finished: the next re-check disposes for real.
+ disposable = true
+ armed[2].fn()
+ expect(disposed).toBe(1)
+ expect(armed).toHaveLength(3)
+ })
+
+ it('cancel() clears the timer currently armed, re-armed or not', () => {
+ const { timers, armed } = fakeTimers()
+ const t = armParkExpiry(() => false, () => {}, 5000, timers)
+ armed[0].fn() // re-arm
+ t.cancel()
+ expect(armed[0].cleared).toBe(false) // already fired; the live one is the re-armed timer
+ expect(armed[1].cleared).toBe(true)
+ })
})
diff --git a/src/renderer/terminal/park-budget.ts b/src/renderer/terminal/park-budget.ts
index 1d8a0c34f..d20c9ff68 100644
--- a/src/renderer/terminal/park-budget.ts
+++ b/src/renderer/terminal/park-budget.ts
@@ -1,3 +1,5 @@
+import type { AgentState } from '@shared/agents/normalize'
+
/**
* Count cap for parked terminals (see TerminalNode's parkedTerminals). The park window
* (TERM_PARK_MS) bounds each entry in TIME but nothing bounded the COUNT: switching through N
@@ -10,9 +12,135 @@
*/
export const PARK_MAX = 12
+/**
+ * How long a PROTECTED park (see `canDisposePark`) waits before asking again whether it may be
+ * disposed. A protection must never turn a park into a permanent leak, so an expiry it blocks
+ * RE-ARMS rather than being cancelled — the park is disposed the first re-check after the agent
+ * stops working.
+ *
+ * A minute, matching the hibernation sweep's cadence (HIBERNATE_SWEEP_MS) and for the same
+ * reason: the re-check is a Map lookup plus a store read, but what it waits for is a human-scale
+ * event (an agent turn ending), so a faster poll would only pay for an answer that cannot have
+ * changed. The cost of the coarseness is bounded and small — one already-parked xterm held at
+ * most a minute past the moment it became disposable.
+ */
+export const PARK_RECHECK_MS = 60_000
+
+/** Agent states that mean the CLI is mid-task or holding a question open for the user. Same set
+ * hibernation refuses to `/exit` (`hibernation-policy.ts`), for the same reason: `working` is a
+ * turn in flight, `waiting`/`blocked` is a question the user is being asked to come back to. */
+const LIVE_AGENT_STATES: ReadonlySet<AgentState> = new Set<AgentState>([
+ 'working',
+ 'waiting',
+ 'blocked'
+])
+
+export interface ParkProtectionInput {
+ /**
+ * The session survives losing this client — a tmux session, local or remote
+ * (`PtyCreateResult.persistent`). With tmux, disposing a park KILLS ONLY OUR CLIENT: the tmux
+ * session, its pane and everything running in it keep going, and the next mount is a warm
+ * reattach. Without it (the plain-shell fallback — no tmux installed, tmux switched off, or a
+ * tmux whose install path `findTmux` missed) the pty IS the shell, and the same dispose kills
+ * the shell and every process under it.
+ */
+ tmuxBacked: boolean
+ /** The node's live agent state (`agentStatus.byId[nodeId].state`); absent = plain terminal or
+ * no hook event seen yet. */
+ agentState?: AgentState
+}
+
+/**
+ * May this parked terminal be disposed by a BUDGET lever — the park window expiring, the LRU cap
+ * evicting, or the memory-pressure "drop every park" lever?
+ *
+ * Reported (issue #126): switching projects killed a Claude agent mid-task and it came back
+ * "terminated mid action", auto-resuming on return. The park is a CACHE and its dispose is
+ * "detach the client", which is exactly what it costs — but only where tmux is underneath. On the
+ * plain-shell fallback the very same dispose is the whole session: the shell dies, the agent CLI
+ * dies with it, and the node's restart machinery resumes the conversation from wherever the kill
+ * landed. Three levers reached that kill and none of them looked at what was running.
+ *
+ * So the protection is the narrowest one that closes it: BOTH no tmux underneath AND live agent
+ * work on the node. A plain terminal, a `done`/unknown agent, and every tmux-backed session keep
+ * today's behavior bit for bit.
+ *
+ * This is only about the budget levers. A deliberate dispose — node deleted, session closed by
+ * another client, respawn into a worktree, a dead pty — goes through `disposeParkedTerminal` and
+ * is never gated: there the session is already gone or is meant to be.
+ */
+export function canDisposePark(p: ParkProtectionInput): boolean {
+ if (p.tmuxBacked) return true
+ return !(p.agentState && LIVE_AGENT_STATES.has(p.agentState))
+}
+
/** Keys to dispose so the park stays within `max`, oldest first. Caller passes keys in park
- * order (Map insertion order — TerminalNode always deletes before re-inserting on re-park). */
-export function planParkEviction(keysInParkOrder: string[], max: number): string[] {
- if (keysInParkOrder.length <= max) return []
- return keysInParkOrder.slice(0, keysInParkOrder.length - max)
+ * order (Map insertion order — TerminalNode always deletes before re-inserting on re-park).
+ *
+ * `canDispose` (default: everything) is the live-work protection above. A protected park is
+ * SKIPPED, not counted out: the plan takes the next-oldest disposable park instead, so the cap
+ * still holds whenever anything may be dropped at all. When it cannot — every park protected —
+ * THE CAP YIELDS: the plan comes back short and the park runs over `max`. That is the same value
+ * judgment hibernation's exclusions make (a bounded cache overrun costs RAM; killing a plain
+ * shell costs the user's running work), and it is self-limiting: each protected park is released
+ * by its own expiry re-check (PARK_RECHECK_MS) as soon as its agent stops. */
+export function planParkEviction(
+ keysInParkOrder: string[],
+ max: number,
+ canDispose: (key: string) => boolean = () => true
+): string[] {
+ const overflow = keysInParkOrder.length - max
+ if (overflow <= 0) return []
+ const plan: string[] = []
+ for (const key of keysInParkOrder) {
+ if (plan.length >= overflow) break
+ if (canDispose(key)) plan.push(key)
+ }
+ return plan
+}
+
+/** The parks the memory-pressure lever may drop: everything except the protected ones. */
+export function disposableParks(keys: string[], canDispose: (key: string) => boolean): string[] {
+ return keys.filter(canDispose)
+}
+
+/** A park's expiry timer. Opaque because it RE-ARMS (see `armParkExpiry`), so the handle the
+ * caller must eventually clear is not the one it started with. */
+export interface ParkTimer {
+ cancel(): void
+}
+
+interface ParkTimers<H> {
+ set(fn: () => void, ms: number): H
+ clear(handle: H): void
+}
+
+/**
+ * Arm the park window, RE-ARMING at `PARK_RECHECK_MS` for as long as `canDispose` says no.
+ *
+ * The re-arm is the whole point: a protection that merely skipped the dispose would leak the
+ * park forever (no other timer would ever look at it again), and one that cancelled itself would
+ * hold a live agent's xterm until the app closed. Instead an expiry that finds live work
+ * postpones itself, and the park is disposed on the first re-check after the agent goes idle.
+ *
+ * `timers` is injectable so the re-arm is testable without real time; production passes none.
+ */
+export function armParkExpiry<H>(
+ canDispose: () => boolean,
+ dispose: () => void,
+ windowMs: number,
+ timers: ParkTimers<H> = {
+ set: (fn, ms) => setTimeout(fn, ms) as unknown as H,
+ clear: (h) => clearTimeout(h as unknown as ReturnType<typeof setTimeout>)
+ }
+): ParkTimer {
+ const tick = (): void => {
+ if (canDispose()) {
+ dispose()
+ return
+ }
+ handle = timers.set(tick, PARK_RECHECK_MS)
+ }
+ let handle = timers.set(tick, windowMs)
+ return { cancel: () => timers.clear(handle) }
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 69ef6d140..1af23fcf2 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -126,6 +126,21 @@ export interface PtyCreateResult {
* Absent for a plain-shell join (no tmux ⇒ no tmux mouse) and for the solo spawn path.
*/
coAttachMouse?: boolean
+ /**
+ * This session is TMUX-BACKED (local or remote) — it survives losing this client, so killing our
+ * pty client only detaches us and everything running in the session keeps going.
+ *
+ * False = the plain-shell fallback (no tmux installed, tmux switched off, or a node with no
+ * persistKey): the pty IS the shell, and killing it kills the shell and every process under it —
+ * an agent CLI mid-task included. The renderer needs the difference because several of its
+ * levers dispose a terminal purely as a CACHE (the park window, the park LRU cap, the
+ * memory-pressure drop), a call that is only cheap when tmux is underneath. See
+ * `renderer/terminal/park-budget.ts` (`canDisposePark`) and issue #126.
+ *
+ * Absent = unknown (a core older than this field, over the relay): the renderer must then assume
+ * the historical behavior (persistent), never protect on a guess.
+ */
+ persistent?: boolean
/**
* REFUSED: this node's session was permanently destroyed by ANOTHER client, so nothing was
* spawned (`sessionId` is empty) — the terminal shows the "closed by <name>" state instead.