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(terminal): gate the offscreen release on live work too (#126)
enesc17875030ac1
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex c94856e04..895961f3f 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -74,6 +74,7 @@ import {planOffscreenVisibility,releaseStillEnabled,shouldDeferReleaseForEco,+ shouldDeferReleaseForLiveWork,OFFSCREEN_DEFER_RETRY_MS,OFFSCREEN_DISPOSE_MS_DEFAULT} from '../terminal/offscreen-policy'@@ -1017,6 +1018,13 @@ export function TerminalNode({/** Is there a live session here that could be given back? Published by the lifecycle run* (`restartTarget`), null between runs — the dispose timer refuses when it cannot ask. */const offscreenLiveRef = useRef<(() => boolean) | null>(null)+ /** Does the CURRENT session survive losing its client (tmux, local or remote)? Published by the+ * lifecycle run from `PtyCreateResult.persistent` — the offscreen release reads it to decide+ * whether disposing this terminal would end a running agent (`wouldKillLiveWork`). Read only+ * AFTER `offscreenLiveRef` has confirmed a live session, so a value left over from a torn-down+ * run is never acted on. Seeded `true`: the historical assumption, never a protection on a+ * guess. */+ const sessionPersistentRef = useRef(true)// Selection is a live veto (`mayDisposeOffscreen`): a selected node is one the user is working// with — it can be off-screen mid-drag or right after a ⌘K jump — so it is never taken down.const selectedRef = useRef(selected)@@ -1635,6 +1643,7 @@ export function TerminalNode({// (`PtyCreateResult.persistent` absent), behaves exactly as it always did rather than being// protected on a guess. See `canDisposePark`.let sessionPersistent = parked ? parked.tmuxBacked : true+ sessionPersistentRef.current = sessionPersistentlet 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)@@ -2331,6 +2340,8 @@ export function TerminalNode({sessionId = sid// `?? true`: an absent flag is an older core over the relay, not a plain shell.sessionPersistent = persistent ?? true+ // Published for the mount-stable observer effect, which cannot see this closure.+ sessionPersistentRef.current = sessionPersistentif (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).@@ -3232,6 +3243,22 @@ export function TerminalNode({// Nothing to give back (no session yet, or one that was closed/ended under us) ⇒ no// dispose. A null ref means no lifecycle run is live at all, which answers the same way.if (!offscreenLiveRef.current?.()) return+ // LIVE WORK ON A PLAIN SHELL (issue #126): this release is only "give the buffer back,+ // re-attach later" while tmux is underneath. Without it the pty is the shell, so+ // disposing an offscreen agent node kills the CLI mid-turn — panning away is not a+ // request to stop it. Defer on the same retry the Eco ordering uses, but with no cap:+ // what this waits for (the turn ending) always comes, and giving up would BE the bug.+ // Asked after `offscreenLiveRef`, so the persistence ref is only read for a session+ // this run actually has.+ if (+ shouldDeferReleaseForLiveWork({+ tmuxBacked: sessionPersistentRef.current,+ agentState: useAgentStatus.getState().byId[id]?.state+ })+ ) {+ offscreenTimerRef.current = setTimeout(fireRelease, OFFSCREEN_DEFER_RETRY_MS)+ return+ }// ECO ORDERING (see `shouldDeferReleaseForEco`): hibernate first, release second. This// release would UNWIRE the node — the lifecycle effect tears down, the hibernate pair// unregisters, and `planHibernation` then reads the node as unwired — and at thediff --git a/src/renderer/terminal/live-work.test.ts b/src/renderer/terminal/live-work.test.tsnew file mode 100644index 000000000..9b09a6b2e--- /dev/null+++ b/src/renderer/terminal/live-work.test.ts@@ -0,0 +1,20 @@+import { describe, it, expect } from 'vitest'+import { wouldKillLiveWork } from './live-work'++describe('wouldKillLiveWork', () => {+ it('is true only for a NON-tmux session whose agent is working/waiting/blocked', () => {+ for (const agentState of ['working', 'waiting', 'blocked'] as const) {+ expect(wouldKillLiveWork({ tmuxBacked: false, agentState })).toBe(true)+ }+ })+ it('is false for a tmux-backed session, whatever its agent is doing', () => {+ // The kill only detaches our client there — tmux, the pane and the CLI all keep running.+ for (const agentState of ['working', 'waiting', 'blocked', 'done', undefined] as const) {+ expect(wouldKillLiveWork({ tmuxBacked: true, agentState })).toBe(false)+ }+ })+ it('is false for a finished or unknown agent, and for a terminal with no agent at all', () => {+ expect(wouldKillLiveWork({ tmuxBacked: false, agentState: 'done' })).toBe(false)+ expect(wouldKillLiveWork({ tmuxBacked: false })).toBe(false)+ })+})diff --git a/src/renderer/terminal/live-work.ts b/src/renderer/terminal/live-work.tsnew file mode 100644index 000000000..26ac90e0c--- /dev/null+++ b/src/renderer/terminal/live-work.ts@@ -0,0 +1,52 @@+/**+ * THE ONE QUESTION EVERY MEMORY LEVER MUST ASK BEFORE IT KILLS A PTY CLIENT: would that kill end+ * work the user has running?+ *+ * The renderer reclaims terminal memory in four places, and all four are written as if dropping a+ * PTY client were free — "the tmux session keeps running and re-attach redraws". That sentence is+ * true only where tmux is actually underneath. On the plain-shell fallback (no tmux installed,+ * tmux switched off in settings, or an install path `findTmux` missed) the pty IS the shell, so+ * the identical call kills the shell and every process under it — an agent CLI mid-turn included.+ *+ * Reported as issue #126: switching projects terminated a working Claude agent, which then+ * auto-resumed from wherever the kill landed ("terminated mid action"). Three of the four levers+ * are the park's (window expiry, LRU cap, memory-pressure drop — see `park-budget.ts`); the fourth+ * is the offscreen viewer release (`offscreen-policy.ts`). They differ in everything except this+ * question, which is why it lives here on its own rather than in whichever module happened to+ * need it first.+ *+ * The predicate is deliberately the NARROWEST one that closes the bug: it takes both halves, and+ * either half alone leaves today's behavior untouched. A tmux-backed session is never protected+ * (the kill costs a redraw, and protecting it would forfeit real memory on the setups where+ * reclaiming it is free); a plain terminal, a finished agent and an unknown state are never+ * protected either (nothing is running to lose).+ */+import type { AgentState } from '@shared/agents/normalize'++/**+ * Agent states that mean the CLI is mid-task or holding something open for the user. The same set+ * hibernation refuses to `/exit` (`hibernation-policy.ts`) and for the same reasons: `working` is+ * a turn in flight, `waiting`/`blocked` is a question or a permission request the user is being+ * asked to come back for. `done` and unknown are not evidence of live work.+ */+const LIVE_AGENT_STATES: ReadonlySet<AgentState> = new Set<AgentState>([+ 'working',+ 'waiting',+ 'blocked'+])++export interface LiveWorkInput {+ /**+ * The session survives losing this client — a tmux session, local or remote+ * (`PtyCreateResult.persistent`). False = the plain-shell fallback, where the pty is the shell.+ */+ tmuxBacked: boolean+ /** The node's live agent state (`agentStatus.byId[nodeId].state`); absent = a plain terminal, or+ * no hook event seen for it yet. */+ agentState?: AgentState+}++/** Would tearing down this terminal's PTY client destroy work that is still running? */+export function wouldKillLiveWork(i: LiveWorkInput): boolean {+ return !i.tmuxBacked && !!i.agentState && LIVE_AGENT_STATES.has(i.agentState)+}diff --git a/src/renderer/terminal/offscreen-policy.test.ts b/src/renderer/terminal/offscreen-policy.test.tsindex e95e9e7a4..db1c2bd8c 100644--- a/src/renderer/terminal/offscreen-policy.test.ts+++ b/src/renderer/terminal/offscreen-policy.test.ts@@ -6,7 +6,8 @@ import {mayDisposeOffscreen,offscreenCoreIsRemote,planOffscreenVisibility,- shouldDeferReleaseForEco+ shouldDeferReleaseForEco,+ shouldDeferReleaseForLiveWork} from './offscreen-policy'describe('offscreen dispose policy', () => {@@ -150,6 +151,46 @@ describe('shouldDeferReleaseForEco — hibernate first, then release the viewer'})})+describe('shouldDeferReleaseForLiveWork — the fourth kill lever behind issue #126', () => {+ it('defers a PLAIN-SHELL terminal whose agent is mid-task, where the release would end it', () => {+ for (const agentState of ['working', 'waiting', 'blocked'] as const) {+ expect(shouldDeferReleaseForLiveWork({ tmuxBacked: false, agentState })).toBe(true)+ }+ })++ it('releases the same terminal once the agent goes idle — the deferral drains itself', () => {+ // The retry cadence re-asks, so "protected" is a state the node LEAVES; nothing has to+ // remember that it was ever deferred.+ expect(shouldDeferReleaseForLiveWork({ tmuxBacked: false, agentState: 'working' })).toBe(true)+ expect(shouldDeferReleaseForLiveWork({ tmuxBacked: false, agentState: 'done' })).toBe(false)+ })++ it('never defers a TMUX-BACKED terminal, even one mid-turn — that release is safe', () => {+ // The whole point of the distinction: with tmux the dispose detaches a client and the CLI+ // keeps working. Deferring here would forfeit the memory this feature exists to reclaim, on+ // the setups where reclaiming it is free.+ expect(shouldDeferReleaseForLiveWork({ tmuxBacked: true, agentState: 'working' })).toBe(false)+ expect(shouldDeferReleaseForLiveWork({ tmuxBacked: true, agentState: 'waiting' })).toBe(false)+ })++ it('never defers a plain terminal or an agent-less node', () => {+ expect(shouldDeferReleaseForLiveWork({ tmuxBacked: false })).toBe(false)+ })++ it('is UNCAPPED, unlike the Eco deferral — there is no elapsed time that makes the kill safe', () => {+ // shouldDeferReleaseForEco takes `offscreenElapsedMs` and gives up at the cap because it waits+ // for a hibernation that may never come. This one waits for the user's own turn to end, and+ // "give up and kill it anyway" is precisely the reported bug — so time is not an input at all.+ // Pinned structurally: the input carries no clock, so no caller can grow a cap by passing one.+ const input: Parameters<typeof shouldDeferReleaseForLiveWork>[0] = {+ tmuxBacked: false,+ agentState: 'working'+ }+ expect(Object.keys(input).sort()).toEqual(['agentState', 'tmuxBacked'])+ expect(shouldDeferReleaseForLiveWork(input)).toBe(true)+ })+})+describe('releaseStillEnabled — the fire-time re-ask of the setting itself', () => {it('refuses a release whose feature was switched off while the timer counted down', () => {// A timer armed ten minutes ago outlives the setting that armed it, and the Eco deferral makesdiff --git a/src/renderer/terminal/offscreen-policy.ts b/src/renderer/terminal/offscreen-policy.tsindex d0c142be4..9a754a875 100644--- a/src/renderer/terminal/offscreen-policy.ts+++ b/src/renderer/terminal/offscreen-policy.ts@@ -8,7 +8,12 @@* REMOTE (SSH) nodes are excluded in v1: their spawn path runs the requireRemote/offline* machinery and a re-spawn while the ControlMaster is down would surface the offline overlay for* a node the user never touched. Follow-up once demand exists.+ *+ * "The tmux session keeps running and re-attach redraws" is the load-bearing sentence, and it is+ * FALSE without tmux — where this release kills the shell and the agent CLI in it. See+ * `shouldDeferReleaseForLiveWork`.*/+import { wouldKillLiveWork, type LiveWorkInput } from './live-work'import type { SessionSource } from '../session/session'export const OFFSCREEN_DISPOSE_MS_DEFAULT = 10 * 60_000@@ -55,9 +60,38 @@ export function releaseStillEnabled(settingMinutes: number | undefined): boolean}/** How often a DEFERRED release re-asks. The hibernation sweep's own cadence, because that is- * exactly what the deferral is waiting for: one sweep after the node hibernates, the viewer goes. */+ * exactly what the deferral is waiting for: one sweep after the node hibernates, the viewer goes.+ * The live-work deferral below rides the same retry, and a minute suits it for the same kind of+ * reason — what it waits for is a human-scale event (an agent turn ending). */export const OFFSCREEN_DEFER_RETRY_MS = 60_000+/**+ * THE FOURTH KILL LEVER (issue #126). Defer this release — indefinitely — while disposing the+ * terminal would destroy work that is still running.+ *+ * This module's whole premise is that a release is cheap: the node stays mounted, the tmux session+ * keeps running, and the revive is a warm re-attach that redraws. Without tmux underneath none of+ * that holds — the pty IS the shell — so releasing an offscreen agent node on a plain-shell setup+ * terminates the CLI mid-turn and the node's restart machinery resumes it from wherever the kill+ * landed. Panning away from a working agent is not a request to stop it.+ *+ * Expressed as a DEFERRAL rather than a refusal because this fire path already has exactly that+ * shape and cadence (`shouldDeferReleaseForEco` → re-arm at `OFFSCREEN_DEFER_RETRY_MS`): every+ * input is re-asked a minute later, so "protected" is a state the node LEAVES on its own the+ * moment its agent goes idle, and the release then proceeds normally. No new timer, no new state,+ * nothing to remember.+ *+ * UNCAPPED, and that is the one place it deliberately differs from the Eco deferral above. That+ * one caps because it waits for a hibernation that may never come, and stranding a viewer forever+ * for an event that cannot happen would be worse than the memory it saves. This one waits for the+ * user's own turn to end — a thing that always ends — and "give up and release anyway" is+ * precisely the reported bug. So no clock is an input here at all. The exposure is bounded by+ * what it protects: only non-tmux sessions, only while an agent is actually mid-task.+ */+export function shouldDeferReleaseForLiveWork(i: LiveWorkInput): boolean {+ return wouldKillLiveWork(i)+}+/*** PHASE 5 ORDERING: with Eco on, releasing an offscreen terminal's viewer WAITS for its agent to* hibernate first.diff --git a/src/renderer/terminal/park-budget.ts b/src/renderer/terminal/park-budget.tsindex d20c9ff68..6c314f6a5 100644--- a/src/renderer/terminal/park-budget.ts+++ b/src/renderer/terminal/park-budget.ts@@ -1,4 +1,4 @@-import type { AgentState } from '@shared/agents/normalize'+import { wouldKillLiveWork, type LiveWorkInput } from './live-work'/*** Count cap for parked terminals (see TerminalNode's parkedTerminals). The park window@@ -26,52 +26,21 @@ export const PARK_MAX = 12*/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.+ * The park's name for the shared safety question (`wouldKillLiveWork`, see `live-work.ts`): its+ * dispose is "detach the client", which is exactly what a cache eviction should cost — but only+ * where tmux is underneath. On the plain-shell fallback the very same dispose is the whole+ * session, so a park holding a working agent there is protected (issue #126).** 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))+export function canDisposePark(p: LiveWorkInput): boolean {+ return !wouldKillLiveWork(p)}/** Keys to dispose so the park stays within `max`, oldest first. Caller passes keys in park