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(terminal): configurable park window + cap, remote parks evicted last (#886)
review30fbd95e2ca7
diff --git a/CLAUDE.md b/CLAUDE.mdindex f13633712..67b63627b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -579,11 +579,22 @@ Lifecycle, by intent:look at it" was this.- **Node unmount (project switch)** → the RENDERER **parks** the terminal (`TerminalNode.tsx``parkedTerminals`): the xterm instance + its attached PTY stay alive with the `.xterm` element- detached from the DOM, so a remount within `TERM_PARK_MS` (5 min) re-adopts them — instant, and+ detached from the DOM, so a remount within the park window re-adopts them — instant, andexact (the tmux client never detaches, so mouse-tracking/alternate-screen modes and scrollbackcarry over; do NOT "optimize" this into a respawn+redraw — a fresh xterm on a reused clientmisses the attach-time mode sequences and breaks scrolling). The park timer then runs the real- teardown: `kill()` detaches the PTY client; the tmux session keeps running. WebGL contexts are+ teardown: `kill()` detaches the PTY client; the tmux session keeps running. **Window and cap+ are settings (issue #886)**: `settings.terminalParkMinutes` (default 5; **0 = until app quit** —+ `parkWindowMs` returns `null` and NO timer is armed, never `Infinity`, which `setTimeout` clamps+ to ~1 ms and would dispose every park at once) and `settings.terminalParkMax` (default 12), both+ re-validated at park time. The LRU cap evicts **local parks before remote ones**+ (`planParkEviction`'s `isRemote`): a local re-adopt miss is a warm reattach in ms, an SSH one is+ a new client per terminal paced 4-per-master, plus a login if the master idled out+ (`ControlPersist`) — and a live parked client is also what keeps that master from idling out.+ Parking does not raise sshd `MaxSessions` pressure: masters are per project, so a parked SSH+ project holds exactly the channels it held while in view. Measured (headless xterm, 200×50): a+ parked tmux-backed terminal ≈ **2 MB** (alternate screen, empty normal buffer — tmux owns the+ history); a plain shell with a full 10k scrollback ≈ **27 MB**. WebGL contexts are**viewport-scoped and budgeted** (browsers cap ~16 live contexts, and a canvas holds far moreterminals). A per-terminal `IntersectionObserver` (`rootMargin` pre-announces approach) onlyREPORTS visibility to a **module-level budget coordinator** (`terminal/webgl-budget.ts`) that ownsdiff --git a/src/renderer/components/settings/sections/TmuxSection.tsx b/src/renderer/components/settings/sections/TmuxSection.tsxindex 1e7cdbacf..2c5569149 100644--- a/src/renderer/components/settings/sections/TmuxSection.tsx+++ b/src/renderer/components/settings/sections/TmuxSection.tsx@@ -10,6 +10,12 @@ import {LEAD_PANE_WIDTH_MAX,LEAD_PANE_WIDTH_MIN} from '@shared/tmux-lead-pane'+import {+ PARK_MAX,+ PARK_MAX_LIMIT,+ PARK_MINUTES_DEFAULT,+ PARK_MINUTES_MAX+} from '@renderer/terminal/park-budget'const ROWS = {enabled: {@@ -21,6 +27,14 @@ const ROWS = {title: 'Keep lead pane wide (agent teams)',keywords: ['lead', 'pane', 'width', 'agent', 'team', 'teammates', 'split', 'claude', 'resize']},+ parkMinutes: {+ title: 'Keep switched-away terminals attached',+ keywords: ['park', 'switch', 'project', 'ssh', 'fast', 'instant', 'reattach', 'minutes', 'memory']+ },+ parkMax: {+ title: 'Max attached terminals in other projects',+ keywords: ['park', 'cap', 'limit', 'switch', 'project', 'ssh', 'reattach', 'memory', 'ram']+ },offscreen: {title: 'Release offscreen terminals',keywords: ['offscreen', 'memory', 'ram', 'release', 'reattach', 'idle', 'minutes']@@ -100,6 +114,54 @@ export function TmuxSection({ isActive }: { isActive: boolean }): React.JSX.Elem}/></SearchableRow>+ <SearchableRow {...ROWS.parkMinutes}>+ <FieldRow+ label="Keep switched-away terminals attached"+ description={+ 'Minutes a project’s terminals stay attached after you switch to another project, so switching back is instant. ' ++ 'After that they reattach on return — seconds per project over SSH. 0 = until the app quits. ' ++ `Default ${PARK_MINUTES_DEFAULT}. Applies from the next switch.`+ }+ control={+ <NumberField+ value={settings.terminalParkMinutes}+ min={0}+ max={PARK_MINUTES_MAX}+ step={1}+ ariaLabel="Park window (minutes)"+ // A cleared field reads back as the DEFAULT, not 0: 0 means "keep forever", the+ // memory-expensive end, and must only ever be typed on purpose.+ onChange={(v) =>+ update({+ terminalParkMinutes: Number.isFinite(v) ? Math.max(0, v) : PARK_MINUTES_DEFAULT+ })+ }+ />+ }+ />+ </SearchableRow>+ <SearchableRow {...ROWS.parkMax}>+ <FieldRow+ label="Max attached terminals in other projects"+ description={+ 'How many switched-away terminals stay attached in total. Beyond this the oldest are released early — local ones before SSH ones, which are slower to reattach. ' ++ 'Each costs about 2 MB with tmux (more without tmux: its scrollback lives in the app) and, over SSH, one local ssh client on the project’s connection. ' ++ `Default ${PARK_MAX}.`+ }+ control={+ <NumberField+ value={settings.terminalParkMax}+ min={1}+ max={PARK_MAX_LIMIT}+ step={1}+ ariaLabel="Max parked terminals"+ onChange={(v) =>+ update({ terminalParkMax: Number.isFinite(v) && v >= 1 ? Math.floor(v) : PARK_MAX })+ }+ />+ }+ />+ </SearchableRow><SearchableRow {...ROWS.offscreen}><FieldRowlabel="Release offscreen terminals"diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 2158070be..118db4fb5 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -68,7 +68,8 @@ import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from 'import { quantizeCharSize } from '../terminal/char-size-quantize'import { resyncDomRendererSpacing } from '../terminal/dom-renderer-spacing'import {- PARK_MAX,+ parkCap,+ parkWindowMs,armParkExpiry,canDisposeParkedEntry,disposableParks,@@ -456,13 +457,13 @@ export function setSshRetryHandler(/*** Parked terminals: when a node unmounts (project switch), its xterm instance and live PTY* session are kept — the `.xterm` element is detached from the DOM and held here — so a remount- * within TERM_PARK_MS re-adopts them instead of respawning. This makes switching back to a- * project instant AND exact: the tmux client never detaches, so the full terminal state+ * within the park window (`settings.terminalParkMinutes`) re-adopts them instead of respawning.+ * This makes switching back to a project instant AND exact: the tmux client never detaches, so the full terminal state* (alternate screen, mouse-tracking modes, scrollback, cursor) carries over with no redraw and* no mode re-negotiation to get wrong. After the window the entry is disposed for real (the* PTY client detaches; the tmux session itself keeps running, as always). The park is bounded in- * 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+ * COUNT as well as time — beyond `settings.terminalParkMax` the oldest entries are evicted early,+ * local before remote (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@@ -502,9 +503,15 @@ interface ParkedTerminal {life: SessionLife & { killed: boolean }/** The park window, which RE-ARMS while the entry is protected (see `armParkExpiry`). */timer: ParkTimer+ /** Rebuilding this session costs a network round trip — an SSH-project node (remote tmux over+ * the ControlMaster) or a relay tab. The LRU cap evicts these LAST (`planParkEviction`). */+ remote: boolean}const parkedTerminals = new Map<string, ParkedTerminal>()-const TERM_PARK_MS = 5 * 60 * 1000+// The park window is `settings.terminalParkMinutes` (default 5 = the historical TERM_PARK_MS; 0 =+// until the app quits) and the count cap `settings.terminalParkMax` (default PARK_MAX = 12), both+// read at PARK time through their validators (`parkWindowMs` / `parkCap`), so a change applies to+// the next switch-away without touching entries already parked. Issue #886./** May the BUDGET levers dispose this park? The entry carries both halves of the answer: the* session's tmux-backedness, and a live read of the node's OWN agent-status store with the@@ -545,7 +552,7 @@ export function disposeParkedTerminal(key: string): void {disposeParked(p)}-/** Memory-pressure lever: drop EVERY parked terminal now, without waiting out `TERM_PARK_MS`. The+/** Memory-pressure lever: drop EVERY parked terminal now, without waiting out the park window. 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.@@ -1078,7 +1085,7 @@ export function wakeHibernatedNode(nodeId: string): void {/*** The mounted instance publishes its copy-feedback sink here, for the same reason as* `restartSubs`: the OSC 52 handler is registered ONCE per xterm instance and that instance- * SURVIVES A PARK (project switch → remount within TERM_PARK_MS), so a handler holding this+ * SURVIVES A PARK (project switch → remount within the park window), so a handler holding this* component's `setState` would be feeding a component that unmounted two projects ago. Looked up* at call time instead. No entry = nobody is mounted = nothing to show.*/@@ -2076,7 +2083,7 @@ export function TerminalNode({agentId ? binariesFor(agentId, useSettings.getState().settings.customAgents) : null- // Adopt-or-create: a parked terminal (this node unmounted less than TERM_PARK_MS ago) is+ // Adopt-or-create: a parked terminal (this node unmounted within the park window) is// re-adopted with its live PTY session and full xterm state intact; otherwise a fresh// xterm + session are built. `myNonce` vs the render-updated ref tells the cleanup below// whether it runs for a respawn (worktree move — must NOT park) or a plain unmount.@@ -4450,7 +4457,7 @@ export function TerminalNode({const co = getCo(termKey)if (sessionId && !isRespawn && !co.closed && !co.ended && !noParkIds.delete(termKey)) {// Park = "subscribed, but not viewing": report no size at all, so this window's (possibly- // small) grid stops clamping every other subscriber's terminal for the next five minutes.+ // small) grid stops clamping every other subscriber's terminal for as long as it stays parked.// The subscription itself stays — output keeps streaming into the parked xterm — and the// adopting mount re-reports its size (sentCols/sentRows are NOT carried over; see above).transport.resize(sessionId, null, null)@@ -4480,8 +4487,9 @@ export function TerminalNode({disposeParked(entry)}},- TERM_PARK_MS- )+ parkWindowMs(useSettings.getState().settings.terminalParkMinutes)+ ),+ remote: sshRemoteTmux || session.source === 'relay'}disposeParkedTerminal(termKey) // defensive: never stack two entries for one nodeparkedTerminals.set(termKey, entry)@@ -4496,7 +4504,14 @@ export function TerminalNode({// 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, parkDisposable)) {+ const cap = parkCap(useSettings.getState().settings.terminalParkMax)+ const remoteKey = (k: string): boolean => parkedTerminals.get(k)?.remote ?? false+ for (const k of planParkEviction(+ [...parkedTerminals.keys()],+ cap,+ parkDisposable,+ remoteKey+ )) {if (k !== termKey) disposeParkedTerminal(k)}})diff --git a/src/renderer/terminal/park-budget.test.ts b/src/renderer/terminal/park-budget.test.tsindex 87c4cefb8..2476ad680 100644--- a/src/renderer/terminal/park-budget.test.ts+++ b/src/renderer/terminal/park-budget.test.ts@@ -1,8 +1,13 @@-import { describe, it, expect, beforeEach } from 'vitest'+import { describe, it, expect, beforeEach, vi } from 'vitest'import { WORKING_STALE_MS } from '@shared/agents/stale'import {PARK_MAX,+ PARK_MAX_LIMIT,+ PARK_MINUTES_DEFAULT,+ PARK_MINUTES_MAX,PARK_RECHECK_MS,+ parkCap,+ parkWindowMs,armParkExpiry,canDisposePark,canDisposeParkedEntry,@@ -239,3 +244,68 @@ describe('armParkExpiry', () => {expect(armed[1].cleared).toBe(true)})})++describe('planParkEviction — remote parks go last (issue #886)', () => {+ const remote = new Set(['r0', 'r1'])+ const isRemote = (k: string): boolean => remote.has(k)+ it('evicts a newer LOCAL park before an older REMOTE one', () => {+ expect(planParkEviction(['r0', 'l0', 'r1', 'l1'], 3, undefined, isRemote)).toEqual(['l0'])+ expect(planParkEviction(['r0', 'l0', 'r1', 'l1'], 2, undefined, isRemote)).toEqual(['l0', 'l1'])+ })+ it('falls through to remote parks, oldest first, once the local ones are gone', () => {+ expect(planParkEviction(['r0', 'l0', 'r1', 'l1'], 1, undefined, isRemote)).toEqual([+ 'l0',+ 'l1',+ 'r0'+ ])+ })+ it('still never evicts a protected park, local or remote', () => {+ expect(planParkEviction(['r0', 'l0', 'r1'], 1, (k) => k !== 'l0', isRemote)).toEqual([+ 'r0',+ 'r1'+ ])+ })+ it('without isRemote the plan is the historical oldest-first one', () => {+ expect(planParkEviction(['r0', 'l0', 'r1', 'l1'], 2)).toEqual(['r0', 'l0'])+ })+})++describe('parkWindowMs', () => {+ it('defaults to the historical 5 minutes', () => {+ expect(parkWindowMs(PARK_MINUTES_DEFAULT)).toBe(5 * 60_000)+ expect(parkWindowMs(undefined)).toBe(5 * 60_000)+ })+ it('0 = no window at all (null), never Infinity', () => {+ // setTimeout clamps a delay above 2^31-1 ms to ~1 ms: an Infinity window would dispose at once.+ expect(parkWindowMs(0)).toBeNull()+ })+ it('a broken hand-edit falls back to the default, never to "keep forever"', () => {+ for (const bad of [NaN, -1, Infinity, '30', null]) expect(parkWindowMs(bad)).toBe(5 * 60_000)+ })+ it('clamps to the ceiling, which stays under the setTimeout overflow', () => {+ expect(parkWindowMs(1e9)).toBe(PARK_MINUTES_MAX * 60_000)+ expect(PARK_MINUTES_MAX * 60_000).toBeLessThan(2 ** 31 - 1)+ })+})++describe('parkCap', () => {+ it('defaults to PARK_MAX and floors/clamps hand-edits', () => {+ expect(parkCap(undefined)).toBe(PARK_MAX)+ expect(parkCap(0)).toBe(PARK_MAX)+ expect(parkCap(-3)).toBe(PARK_MAX)+ expect(parkCap(NaN)).toBe(PARK_MAX)+ expect(parkCap(40.7)).toBe(40)+ expect(parkCap(1e6)).toBe(PARK_MAX_LIMIT)+ })+})++describe('armParkExpiry with no window', () => {+ it('arms nothing and never disposes', () => {+ const set = vi.fn()+ const dispose = vi.fn()+ const t = armParkExpiry(() => true, dispose, null, { set, clear: vi.fn() })+ expect(set).not.toHaveBeenCalled()+ expect(dispose).not.toHaveBeenCalled()+ t.cancel() // must not throw with no handle+ })+})diff --git a/src/renderer/terminal/park-budget.ts b/src/renderer/terminal/park-budget.tsindex c3b79c8aa..70a143851 100644--- a/src/renderer/terminal/park-budget.ts+++ b/src/renderer/terminal/park-budget.ts@@ -18,6 +18,41 @@ import type { AgentState } from '@shared/agents/normalize'*/export const PARK_MAX = 12+/** Default park window in minutes (`settings.terminalParkMinutes`) — the historical+ * `TERM_PARK_MS` of 5 minutes, unchanged for everyone who never touches the setting. */+export const PARK_MINUTES_DEFAULT = 5+/** Settings UI ceilings. The window's `0` means "until the app quits", so the ceiling only+ * bounds a typed number; the cap's is a sanity bound for a hand-edited settings.json. */+export const PARK_MINUTES_MAX = 24 * 60+export const PARK_MAX_LIMIT = 500++/**+ * The park window in ms for `settings.terminalParkMinutes`, or `null` = never expire (the+ * "keep terminals attached while the app is open" choice, issue #886). The value is+ * hand-editable, so it is re-validated HERE rather than trusted by type:+ * - absent / non-finite / negative ⇒ the default (5 min) — a broken value must never silently+ * become "keep forever", which is the memory-expensive end;+ * - `0` ⇒ `null`, and the caller arms NO timer. Not `Infinity`: `setTimeout` clamps any delay+ * above 2^31-1 ms to 1 ms, so an "infinite" window would dispose every park immediately.+ * - above the ceiling ⇒ the ceiling (24 h, far under that 2^31 ms ≈ 24.8 day overflow).+ */+export function parkWindowMs(minutes: unknown): number | null {+ if (typeof minutes !== 'number' || !Number.isFinite(minutes) || minutes < 0) {+ return PARK_MINUTES_DEFAULT * 60_000+ }+ if (minutes === 0) return null+ return Math.min(minutes, PARK_MINUTES_MAX) * 60_000+}++/** The park count cap for `settings.terminalParkMax`: an integer in [1, PARK_MAX_LIMIT], with any+ * invalid hand-edit falling back to `PARK_MAX`. The floor is 1, not 0 — "never park" would make+ * every project switch a full reattach, which nobody asked for and the window already expresses+ * better as a short time. */+export function parkCap(max: unknown): number {+ if (typeof max !== 'number' || !Number.isFinite(max) || max < 1) return PARK_MAX+ return Math.min(Math.floor(max), PARK_MAX_LIMIT)+}+/*** 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@@ -92,18 +127,31 @@ export function canDisposeParkedEntry(e: ParkedEntryState, now: number = Date.no* 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. */+ * by its own expiry re-check (PARK_RECHECK_MS) as soon as its agent stops — or, with the window+ * switched off (`parkWindowMs(0)`), by the next park's eviction pass after it becomes disposable.+ *+ * `isRemote` (default: nothing) orders the victims: every disposable LOCAL park goes before any+ * REMOTE one, oldest first within each — see the loop for why. */export function planParkEviction(keysInParkOrder: string[],max: number,- canDispose: (key: string) => boolean = () => true+ canDispose: (key: string) => boolean = () => true,+ isRemote: (key: string) => boolean = () => false): string[] {const overflow = keysInParkOrder.length - maxif (overflow <= 0) return []const plan: string[] = []- for (const key of keysInParkOrder) {- if (plan.length >= overflow) break- if (canDispose(key)) plan.push(key)+ // Two passes: LOCAL parks go first, oldest first, and only then REMOTE ones (issue #886). The+ // cap is the same either way — what differs is what the user pays on the way back. A local+ // re-adopt miss is a warm reattach on this machine (tens of ms); a remote one is a new PTY+ // client over the ControlMaster, paced 4-per-master by the spawn gate, plus a full login when+ // the master has idled out (`ControlPersist`) — seconds, per project. So when something must+ // go, it should be the park that is cheap to rebuild.+ for (const pass of [false, true]) {+ for (const key of keysInParkOrder) {+ if (plan.length >= overflow) return plan+ if (isRemote(key) === pass && canDispose(key)) plan.push(key)+ }}return plan}@@ -137,7 +185,7 @@ interface ParkTimers<H> {export function armParkExpiry<H>(canDispose: () => boolean,dispose: () => void,- windowMs: number,+ windowMs: number | null,timers: ParkTimers<H> = {set: (fn, ms) => setTimeout(fn, ms) as unknown as H,clear: (h) => clearTimeout(h as unknown as ReturnType<typeof setTimeout>)@@ -153,7 +201,9 @@ export function armParkExpiry<H>(}handle = timers.set(tick, PARK_RECHECK_MS)}- handle = timers.set(tick, windowMs)+ // `null` = no window at all (`parkWindowMs(0)`): the park lives until a deliberate dispose, the+ // LRU cap or the memory-pressure lever takes it. No timer, so nothing to re-arm either.+ if (windowMs !== null) handle = timers.set(tick, windowMs)return {cancel: () => {if (handle !== undefined) timers.clear(handle)diff --git a/src/shared/types.ts b/src/shared/types.tsindex 31d96a0fc..8fe1fae24 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1605,6 +1605,13 @@ export interface Settings {/** Minutes a terminal may sit fully offscreen before its xterm+PTY client is torn down in* place (tmux keeps the session; re-approach reattaches and redraws). 0 = never. */offscreenTerminalMinutes: number+ /** Minutes a terminal stays PARKED after its project is switched away — xterm + PTY client kept+ * alive off-DOM so switching back is instant and exact (no reattach). 0 = until the app quits.+ * Default 5. Hand-editable; re-validated at the use site (`parkWindowMs`). Issue #886. */+ terminalParkMinutes: number+ /** Max parked terminals across all projects before the oldest (local first, then remote) are+ * released early. Default 12. Re-validated at the use site (`parkCap`). Issue #886. */+ terminalParkMax: number/** AI commit message agent: a local coding-agent CLI run read-only. */commitAgent: 'claude' | 'codex' | 'custom'/** For commitAgent='custom': command template; {prompt} placeholder optional (else stdin). */@@ -1878,6 +1885,8 @@ export const DEFAULT_SETTINGS: Settings = {tmuxScrollback: 50000,tmuxLeadPaneWidth: 0,offscreenTerminalMinutes: 10,+ terminalParkMinutes: 5,+ terminalParkMax: 12,commitAgent: 'claude',commitAgentCommand: '',commitExtraPrompt: '',