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(renderer): final wave — one watched predicate, remote at plan time, hibernate before release
enes65a8c41eb85d
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 7d7e169e3..f774c7354 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -28,7 +28,9 @@ import {disposeTerminalOnUnmount,disposeParkedTerminal,disposeAllParkedTerminals,- isNodeOffscreen,+ isNodeRemote,+ isNodeWatched,+ setWatchedNode,wakeHibernatedNode} from '../nodes/TerminalNode'import { solveFitPadding } from './fit-view'@@ -5441,6 +5443,10 @@ export function Canvas() {// whole board on every Canvas render.const setKanbanModalNode = useCallback((id: string | null) => {kanbanModalNodeRef.current = id+ // The one place the "is anyone looking at this session" predicate learns about the modal —+ // every asker (the sweep's plan, the node's fire-time re-ask, the nudge) reads it through+ // `isNodeWatched`, so the modal clause cannot go missing from one of them.+ setWatchedNode(id)// Opening a card IS opening the session — the second way in, and the one the canvas// visibility observer says nothing about. A hibernated node reached this way resumes its// conversation just as it would on a pan-back, instead of showing the bare shell it was@@ -7115,16 +7121,14 @@ export function Canvas() {parentNodeId: v.parentNodeId,status: v.state})),- // The nodes' own visibility observers (Phase 2's) are the authority — never a second- // observer here, and "we have not heard" is never read as "nobody is looking".- //- // …with ONE override the observers structurally cannot know about: a kanban card modal- // co-attaches the same tmux session over a canvas nobody can see, so its node is- // off-screen by every measurement and yet is the one session the user is looking at.- // Quitting the CLI under an open modal is the same intrusion as quitting it under the- // node itself.- isOffscreen: (nodeId) =>- nodeId !== kanbanModalNodeRef.current && isNodeOffscreen(nodeId),+ // `isNodeWatched` is the ONE predicate for "the user is looking at this session" — the+ // nodes' own visibility observers (Phase 2's) plus the open card modal, which no+ // observer can see (it co-attaches the same tmux session over a canvas nobody is+ // looking at). The node's exit closure re-asks the SAME function at fire time.+ isOffscreen: (nodeId) => !isNodeWatched(nodeId),+ // Remote (SSH / relay) sessions are excluded in v1 — here rather than only at the exit,+ // or two of them could occupy both batch slots on every pass (see the policy).+ isRemote: isNodeRemote,// Wired = mounted with a live terminal that registered its hibernate pair. An// offscreen-DISPOSED node (Phase 2) has already given its buffer back and has no pane// to quit, so it drops out here.@@ -7149,9 +7153,7 @@ export function Canvas() {// EDGE has passed, so no wake trigger is left and the node would sit SLEEPING in// front of the user. Nudge it: the node re-reads the flag itself, so this is a// no-op wherever the user did not arrive.- if (!isNodeOffscreen(nodeId) || nodeId === kanbanModalNodeRef.current) {- wakeHibernatedNode(nodeId)- }+ if (isNodeWatched(nodeId)) wakeHibernatedNode(nodeId)}// 'exit-timeout' / 'not-eligible': the CLI is still running and NOTHING is recorded —// marking it hibernated would put a SLEEPING chip on a live session and suppress thediff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex 08177fd79..2777db04c 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -221,7 +221,7 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El<SearchableRow {...ROWS.hibernation}><FieldRowlabel="Hibernate idle agents"- description="Exit an agent CLI that has been idle and offscreen this long, freeing its memory; the conversation resumes automatically when you view the node. Scheduled, /loop and /cron agents — and sessions with subagents still running — are never touched."+ description="Exit an agent CLI that has been idle and offscreen this long, freeing its memory; the conversation resumes automatically when you view the node. While this is on, the terminal view of an offscreen agent is kept until the agent hibernates, so the bigger saving happens first. Scheduled, /loop and /cron agents — and sessions with subagents still running — are never touched."control={<div className="flex items-center gap-2"><Switchdiff --git a/src/renderer/lib/hibernationCandidates.test.ts b/src/renderer/lib/hibernationCandidates.test.tsindex 61920f0bb..49647bcea 100644--- a/src/renderer/lib/hibernationCandidates.test.ts+++ b/src/renderer/lib/hibernationCandidates.test.ts@@ -12,6 +12,7 @@ function inputs(over: Partial<HibernationCandidateInputs> = {}): HibernationCandsubagents: [],isOffscreen: () => true,isWired: () => true,+ isRemote: () => false,...over}}@@ -27,6 +28,7 @@ describe('buildHibernationCandidates', () => {wired: true,offscreen: true,hibernated: false,+ remote: false,recurring: false,liveSubagents: false,lastEventAt: IDLE@@ -82,6 +84,24 @@ describe('buildHibernationCandidates', () => {).toBe(true)})+ it('carries the REMOTE fact per node, so the plan can exclude it before the batch slice', () => {+ const rows = buildHibernationCandidates(+ inputs({+ nodes: [+ { id: 'a', agentId: 'claude' },+ { id: 'b', agentId: 'claude' }+ ],+ isRemote: (id) => id === 'a'+ })+ )+ expect(rows.map((r) => [r.id, r.remote])).toEqual([+ ['a', true],+ ['b', false]+ ])+ // A remote node is refused however idle it looks — the whole point of asking at plan time.+ expect(planHibernation([rows[0]], NOW, { enabled: true, idleMinutes: 30 })).toEqual([])+ })+it('carries wiring and visibility from the callbacks, per node', () => {const rows = buildHibernationCandidates(inputs({diff --git a/src/renderer/lib/hibernationCandidates.ts b/src/renderer/lib/hibernationCandidates.tsindex 33e9fecf7..223d96dd5 100644--- a/src/renderer/lib/hibernationCandidates.ts+++ b/src/renderer/lib/hibernationCandidates.ts@@ -55,6 +55,9 @@ export interface HibernationCandidateInputs {isOffscreen: (nodeId: string) => boolean/** Does this node have a live terminal with a registered hibernate pair? */isWired: (nodeId: string) => boolean+ /** Does this node's session run on another machine (SSH project / relay tab)? Excluded in v1 —+ * and excluded HERE, at plan time, for the batch-slot reason in the policy's `remote` field. */+ isRemote: (nodeId: string) => boolean}export function buildHibernationCandidates(@@ -75,6 +78,7 @@ export function buildHibernationCandidates(wired: inputs.isWired(n.id),offscreen: inputs.isOffscreen(n.id),hibernated: !!st?.hibernated,+ remote: inputs.isRemote(n.id),recurring: !!st?.loop,liveSubagents: liveParents.has(n.id),lastEventAt: st?.lastEventAtdiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 0ef5a3e7d..8a775637f 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -64,7 +64,10 @@ import {mayDisposeOffscreen,offscreenCoreIsRemote,offscreenDisposeMs,- planOffscreenVisibility+ planOffscreenVisibility,+ shouldDeferReleaseForEco,+ OFFSCREEN_DEFER_RETRY_MS,+ OFFSCREEN_DISPOSE_MS_DEFAULT} from '../terminal/offscreen-policy'import { attachGlyphGrid, type GlyphGridAttachment } from '../terminal/glyphgrid-attach'import type { GridHandle } from '../glyphgrid/engine'@@ -88,6 +91,7 @@ import {import { deliverCommand, KILL_LINE, type DeliveryIo } from '../terminal/command-delivery'import {agentHibernateFns,+ exitSequence,guardConcurrentRestart,isShellCommand,performExitPhase,@@ -651,6 +655,38 @@ const restartSubs = new Map<string, () => void>()*/const offscreenNodes = new Set<string>()+/**+ * Nodes whose session runs on ANOTHER machine (SSH project terminal, relay/remote-server tab).+ * Published by the node itself, because the answer is a union of two independent facts only it can+ * see (`offscreenRemoteRef`). Read by the hibernation sweep at PLAN time — see the policy's+ * `remote` field for why excluding these only at the exit was not enough.+ */+const remoteNodes = new Set<string>()++function setNodeRemote(nodeId: string, remote: boolean): void {+ if (remote) remoteNodes.add(nodeId)+ else remoteNodes.delete(nodeId)+}++/** Does this node's session live on another machine? Unknown answers `false` (a node that has not+ * reported is local until it says otherwise; the exit closure re-asks at fire time regardless). */+export function isNodeRemote(nodeId: string): boolean {+ return remoteNodes.has(nodeId)+}++/**+ * The open kanban card modal's node, if any — the ONE thing that makes a node "being looked at"+ * without the canvas observer knowing: the modal co-attaches the same tmux session over a canvas+ * nobody can see, so its node is off-screen by every measurement and is nevertheless the session+ * the user has open. Published by Canvas (which owns the modal), kept HERE so that the watched+ * question has exactly one answer for all of its askers.+ */+let watchedNodeId: string | null = null++export function setWatchedNode(nodeId: string | null): void {+ watchedNodeId = nodeId+}+/** How long a freshly mounted node waits before asking to be woken: the spawn its resume line is* written into is still in flight at mount (no session id, no pane). */const WAKE_MOUNT_DELAY_MS = 2000@@ -663,9 +699,20 @@ function setNodeOffscreen(nodeId: string, offscreen: boolean): void {else offscreenNodes.delete(nodeId)}-/** Is this node out of the viewport? Unknown answers `false` — see `offscreenNodes`. */-export function isNodeOffscreen(nodeId: string): boolean {- return offscreenNodes.has(nodeId)+/**+ * "Is the user looking at this session RIGHT NOW?" — the one predicate behind every hibernation+ * decision that turns on attention: the sweep's plan, the exit closure's fire-time re-ask, and the+ * post-mark nudge. It has to be ONE function: the first version of this feature asked the question+ * three times, and the fire-time copy was missing the modal clause — so a card modal opened+ * mid-batch could still have `/exit` typed into it.+ *+ * Two ways to be watched, and the second is not visible to any observer: the node is on screen, or+ * its kanban card modal is open (see `watchedNodeId`). Unknown answers WATCHED — a node whose+ * observer has not delivered yet must never be read as "nobody is looking", which is the direction+ * that quits a session out from under someone.+ */+export function isNodeWatched(nodeId: string): boolean {+ return !offscreenNodes.has(nodeId) || watchedNodeId === nodeId}/**@@ -910,6 +957,9 @@ export function TerminalNode({const [offscreenDown, setOffscreenDown] = useState(false)const offscreenDownRef = useRef(false)const offscreenTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ /** When the current offscreen stretch began (null = on screen). The Eco deferral's cap is+ * measured against it, so it is stamped once per stretch, not per observer callback. */+ const offscreenSinceRef = useRef<number | null>(null)const [offscreenEpoch, setOffscreenEpoch] = useState(0)/** The visibility observer's last verdict. Component-level (not per-lifecycle-run) because it* must survive an offscreen dispose and because a budget client registered by a later run needs@@ -999,6 +1049,12 @@ export function TerminalNode({// gemini names its own sessions but has no rename command, so it polls and never pushes.const canReadTitleNode = !!agentId && canReadTitle(agentId)const agentLabel = (agentId ? agentConfig(agentId) : undefined)?.label ?? 'Agent'+ // Could this node's CLI ever be hibernated — quit AND brought back? A durable property of the+ // agent, not of its current state: the offscreen release consults it to decide whether waiting+ // for Eco is even meaningful here (see `shouldDeferReleaseForEco`).+ const hibernationTarget = !!agentId && canResume(agentId) && !!exitSequence(agentId)+ const hibernationTargetRef = useRef(hibernationTarget)+ hibernationTargetRef.current = hibernationTarget// Keep the listener's mirrors current every render.titleAutoRef.current = data.titleAuto !== false@@ -1046,6 +1102,14 @@ export function TerminalNode({// project long after the lifecycle run that would otherwise have captured the answer.const offscreenRemoteRef = useRef(false)offscreenRemoteRef.current = remoteSession || offscreenCoreIsRemote(session.source)+ // …and published for the hibernation sweep, which needs the same answer at PLAN time (see the+ // policy's `remote` field: excluding these only at the exit let two remote nodes occupy both+ // batch slots forever). Re-published whenever it changes — a local project can become an SSH one.+ const nodeIsRemote = offscreenRemoteRef.current+ useEffect(() => {+ setNodeRemote(id, nodeIsRemote)+ return () => setNodeRemote(id, false)+ }, [id, nodeIsRemote])const canMoveIntoWorktree =!!parentWtPath &&!parentWtStale &&@@ -1113,7 +1177,7 @@ export function TerminalNode({const trigger = (): void => wakeRef.current()wakeSubs.set(id, trigger)const t = setTimeout(() => {- if (!isNodeOffscreen(id)) wakeRef.current()+ if (isNodeWatched(id)) wakeRef.current()}, WAKE_MOUNT_DELAY_MS)return () => {clearTimeout(t)@@ -2607,15 +2671,15 @@ export function TerminalNode({// (parked → remounted) terminal never reaches the spawn continuation.const unregisterHibernate = registerAgentHibernate(id, {exit: guardConcurrentRestart(id, async (): Promise<ExitPhaseOutcome> => {- // "Is this node STILL out of view?" — re-asked at FIRE time, never trusted from the plan,- // the same discipline as `mayDisposeOffscreen`. A sweep can spend ~12 s working through- // its batch, and the node whose turn comes last may be one the user panned back to and is- // now typing in: KILL_LINE + `/exit` would land in a pane they are watching, taking their- // half-written prompt with it. Worse, the visible EDGE has already passed by then, so no- // wake trigger is left and the node would sit SLEEPING on screen until clicked.- // (`isNodeOffscreen` and this node's own `wasVisibleRef` are the same observer's verdict;- // the map is used here so the sweep and the node cannot disagree.)- if (!isNodeOffscreen(id)) return 'not-eligible'+ // "Is the user looking at this session STILL?" — re-asked at FIRE time, never trusted from+ // the plan, the same discipline as `mayDisposeOffscreen`. A sweep can spend ~12 s working+ // through its batch, and the node whose turn comes last may be one the user panned back to+ // (or opened as a card modal) and is now typing in: KILL_LINE + `/exit` would land in a+ // pane they are watching, taking their half-written prompt with it. Worse, the visible+ // EDGE has already passed by then, so no wake trigger is left and the node would sit+ // SLEEPING on screen until clicked. Deliberately the SAME `isNodeWatched` the plan and the+ // nudge ask — a second copy of this question is how the modal clause went missing once.+ if (isNodeWatched(id)) return 'not-eligible'// SSH / relay sessions are excluded in v1, exactly as the offscreen dispose excludes them// (offscreen-policy.ts): the exit and its much later resume would race the ControlMaster /// relay lifecycle, and a wake that cannot reach the host leaves a dead conversation behind.@@ -2628,13 +2692,29 @@ export function TerminalNode({// permission prompt ANSWERS it).const gate = restartEligibility(agentId, st?.state, agentSessionId)if (!gate.ok || !agentId || !agentSessionId || !restartTarget()) return 'not-eligible'- return performExitPhase({+ const outcome = await performExitPhase({agentId,sessionId: agentSessionId,io: restartIo,paneCommand: () => api.pty.paneCommand(id),isLive: restartTarget})+ if (outcome === 'exited') {+ // Remember WHAT the pane settled to. The wake will only type into a pane it recognizes,+ // and its `isShellCommand` allowlist does not know `nu`, `xonsh` or `pwsh` — while the+ // exit half accepts those through its allowlist-free "the command stopped being the CLI"+ // signal. Without this record the wake is STRICTER than the exit that produced it, and+ // such a user is hibernated and then never woken: the chip refuses forever.+ // One extra poll rather than a value out of `performExitPhase`, whose behavior is pinned+ // byte-for-byte by Task 8's tests. `null` (a pane we could not read) FORGETS the old+ // value: a stale string must never stand in as permission to type into today's pane.+ const settled = await queryPaneWithin(+ () => api.pty.paneCommand(id),+ RESTART_EXIT_TIMEOUT_MS+ )+ useAgentStatus.getState().setHibernatedPane(id, settled)+ }+ return outcome}),resume: guardConcurrentRestart(id, async (): Promise<ResumePhaseOutcome> => {const st = useAgentStatus.getState().byId[id]@@ -2648,16 +2728,29 @@ export function TerminalNode({// mode is a property of how a session is LAUNCHED, so it is re-resolved now (a wake can be// hours after the exit, and days after the node was created).const base = resumeCommand(agentId, agentSessionId)- const command = base- ? withPermissionMode(base, agentId, await ensureActivePermissionMode(agentId))- : undefined+ // Refused BEFORE anything is written. `performResumePhase` gates on this same bare command+ // and would refuse too — but the KILL_LINE below is ours, so leaving this check to it+ // meant an unusable session id erased the pane's line (three times, once per wake trigger)+ // and then declined to resume.+ if (!base) return 'not-eligible'+ const command = withPermissionMode(+ base,+ agentId,+ await ensureActivePermissionMode(agentId)+ )// THE load-bearing gate of the wake half. Hours can pass between the exit and this// resume, and the pane is a REPL the user can type into: by now it may belong to vim, to// `top`, or to a claude the user launched by hand — and a launch line typed into a live// program is sent to that program, as a message or a mangled command. A pane we cannot// READ answers null and is refused for the same reason.+ //+ // Two ways to recognize it, mirroring the exit half's two: a KNOWN shell, or the exact+ // command this node's own exit measured the pane settling to (`hibernatedPane`). The+ // second is what keeps a `nu` / `xonsh` / `pwsh` user — whom the exit accepts through its+ // allowlist-free signal — from being hibernated and never woken.const pane = await queryPaneWithin(() => api.pty.paneCommand(id), RESTART_EXIT_TIMEOUT_MS)- if (!isShellCommand(pane)) return 'not-eligible'+ const settled = useAgentStatus.getState().byId[id]?.hibernatedPane+ if (!isShellCommand(pane) && !(pane !== null && pane === settled)) return 'not-eligible'// Clear the line before the launch line goes in. The shell above is the one WE exited to,// hours ago — nothing stops a passer-by (or a stray paste, or the user's own aborted// command) from having left a half-typed line at its prompt, and `deliverCommand`'s first@@ -3026,6 +3119,9 @@ export function TerminalNode({// conversation resumed before they can reach for the chip. No-op (one map lookup) for a// node that is not hibernated, which is every node in the default case.if (visible && !wasVisible) wakeRef.current()+ // A visible node is not in an offscreen stretch at all — the next hidden edge starts a+ // fresh clock for the Eco deferral's cap.+ if (visible) offscreenSinceRef.current = null// …and the offscreen-dispose state machine. Every decision is the pure// `planOffscreenVisibility`; this block only executes the plan.const disposeMs = offscreenDisposeMs(@@ -3047,7 +3143,11 @@ export function TerminalNode({setOffscreenEpoch((n) => n + 1) // re-run the lifecycle effect → fresh warm tmux attach}if (plan.armTimer && disposeMs !== null) {- offscreenTimerRef.current = setTimeout(() => {+ // When this offscreen stretch began — the clock the Eco deferral's cap is measured+ // against. Stamped only here, where a NEW timer is armed (the plan refuses to re-arm+ // while one is pending), so a pan that keeps reporting hidden cannot keep pushing it out.+ offscreenSinceRef.current = Date.now()+ const fireRelease = (): void => {offscreenTimerRef.current = null// Every input re-asked at FIRE time, never at arm time: ten minutes is long enough for// all of them to have changed. `wasVisibleRef` is the observer's own latest verdict.@@ -3059,16 +3159,43 @@ export function TerminalNode({}))return+ // The setting can also have been switched OFF while this timer counted down; a fire+ // that disposed anyway would take a buffer the user has just asked us to keep.+ const liveSettings = useSettings.getState().settings+ if (offscreenDisposeMs(liveSettings.offscreenTerminalMinutes) === null) return// 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+ // 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 the+ // shipped defaults it fires at 10 minutes against a 30-minute idle window, so the+ // canonical "finish a turn, pan away" session never hibernated at all. The viewer is+ // ~15 MB; the CLI is hundreds. So wait for the big prize, on the sweep's own cadence,+ // and only up to the capped total — a node that can never hibernate must not hold its+ // viewer forever.+ if (+ shouldDeferReleaseForEco({+ ecoEnabled: liveSettings.agentHibernationEnabled,+ resumableAgent: hibernationTargetRef.current,+ hibernated: !!useAgentStatus.getState().byId[id]?.hibernated,+ offscreenElapsedMs: Date.now() - (offscreenSinceRef.current ?? Date.now()),+ idleMinutes: liveSettings.agentHibernationIdleMinutes,+ offscreenMinutes:+ liveSettings.offscreenTerminalMinutes ?? OFFSCREEN_DISPOSE_MS_DEFAULT / 60_000+ })+ ) {+ offscreenTimerRef.current = setTimeout(fireRelease, OFFSCREEN_DEFER_RETRY_MS)+ return+ }offscreenDownRef.current = true// The cleanup must DISPOSE, not park: parking keeps the very buffer this feature exists// to give back. Set before the state flip, since that flip is what runs the cleanup.noParkIds.add(termKey)setOffscreenDown(true)setOffscreenEpoch((n) => n + 1)- }, disposeMs)+ }+ offscreenTimerRef.current = setTimeout(fireRelease, disposeMs)}},{ rootMargin: '256px' }diff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.tsindex 33c980fd3..f1ed167c1 100644--- a/src/renderer/state/agentStatus.persist.test.ts+++ b/src/renderer/state/agentStatus.persist.test.ts@@ -96,6 +96,56 @@ describe('loop persistence (cron/schedule survive an app restart)', () => {expect(Date.now() - st.lastEventAt!).toBeLessThan(5000) // hours-old clock replaced})+ it('persists `hibernatedPane` with the flag and drops it on wake', async () => {+ // What the pane settled to when the CLI let go: the wake's second way of recognizing a pane it+ // may type into, for shells the `isShellCommand` allowlist does not know (nu/xonsh/pwsh).+ // Kept past a wake it would be a standing permission to type into whatever that string names.+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setHibernatedPane('n15', 'nu')+ useAgentStatus.getState().setHibernated('n15', true)+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n15).toMatchObject({+ hibernated: true,+ hibernatedPane: 'nu'+ })+ useAgentStatus.getState().setHibernated('n15', false)+ expect(useAgentStatus.getState().byId['n15'].hibernatedPane).toBeUndefined()+ expect(JSON.parse(store.getItem('nodeterm.agentStatus')!).n15?.hibernatedPane).toBeUndefined()+ })++ it('forgets the recorded pane when the exit could not read one (null)', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setHibernatedPane('n16', 'nu')+ useAgentStatus.getState().setHibernatedPane('n16', null)+ // A stale string must never stand in as permission to type into TODAY's pane.+ expect(useAgentStatus.getState().byId['n16'].hibernatedPane).toBeUndefined()+ })++ it('drops `hibernatedPane` with the flag on the live-state self-heal', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setHibernatedPane('n17', 'nu')+ useAgentStatus.getState().setHibernated('n17', true)+ useAgentStatus.getState().setState('n17', 'working', 'claude')+ expect(useAgentStatus.getState().byId['n17'].hibernated).toBeUndefined()+ expect(useAgentStatus.getState().byId['n17'].hibernatedPane).toBeUndefined()+ })++ it('never restores a recorded pane without the flag it belongs to', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.agentStatus': JSON.stringify({+ n18: { unread: false, sessionId: 's', hibernatedPane: 'nu' }+ })+ })+ )+ const { useAgentStatus } = await import('./agentStatus')+ expect(useAgentStatus.getState().byId['n18'].hibernatedPane).toBeUndefined()+ })+it('setHibernated(false) on a node that is not hibernated changes NOTHING', async () => {// Load-bearing since Canvas calls it on every SessionStart (a fresh launch disproves the// flag): the bail must not create an entry, must not touch the idle clock — which would hidediff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex a111171d4..c3ae50575 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -59,6 +59,19 @@ export interface AgentNodeStatus {* holds a shell rather than a live CLI.*/hibernated?: boolean+ /**+ * What the pane's foreground command settled to once the CLI let go of it — recorded at the+ * moment of hibernation, persisted beside the flag, and dropped with it.+ *+ * The wake refuses to type a launch line into a pane it does not recognize as a shell, and its+ * allowlist (`isShellCommand`) knows zsh/bash/fish/… but not `nu`, `xonsh` or `pwsh`. The EXIT+ * half has a second, allowlist-free signal for exactly those users (the foreground command+ * stopped being the CLI, twice in a row) — so without this the wake is STRICTER than the exit,+ * and a `nu` user could be hibernated and then never woken: the chip would refuse forever.+ * Remembering what we exited TO closes that gap, and it is narrow by construction: it permits+ * one specific string, on one specific node, recorded by us.+ */+ hibernatedPane?: string/** Which agent this node is running (claude/codex/gemini/…), when known. */agentId?: AgentId/** A turn finished / needs attention while the user wasn't looking. */@@ -124,6 +137,9 @@ export interface AgentStatusStore {* Waking also restarts the idle clock (`lastEventAt`), so a quiet resumed session is not* re-hibernated on the next sweep. */setHibernated(id: string, on: boolean): void+ /** Record what the pane settled to when this node's CLI let go of it (`null` = forget: a stale+ * value must never permit a wake into a pane we did not measure). See `hibernatedPane`. */+ setHibernatedPane(id: string, pane: string | null): voidmarkUnread(id: string): void/*** Drop a node's unread flag. By default a clear of a FINISHED (done) node also ACKs the read@@ -219,6 +235,10 @@ export function createAgentStatusSession(// Only when set: an absent flag stays absent, so an entry saved before this field// existed hydrates byte-identically (and `hibernated: false` never grows in the file).if (v.hibernated) out[id].hibernated = true+ // Only alongside the flag: the pane we exited TO is meaningless (and, as a wake+ // permission, unwanted) once the node is not hibernated any more.+ if (v.hibernated && typeof v.hibernatedPane === 'string')+ out[id].hibernatedPane = v.hibernatedPane// A recurring job (cron/schedule — and tmux keeps in-session loops alive too) outlives// the app: restore its card. Minimal shape check so a corrupt entry can't break load.if (v.loop && typeof v.loop === 'object' && v.loop.kind) {@@ -253,7 +273,9 @@ export function createAgentStatusSession(sessionId: v.sessionId,agentId: v.agentId,loop: v.loop,- hibernated: v.hibernated+ hibernated: v.hibernated,+ // Never written without the flag it belongs to (see `hibernatedPane`).+ hibernatedPane: v.hibernated ? v.hibernatedPane : undefined}}}@@ -320,7 +342,10 @@ export function createAgentStatusSession(// `done` deliberately does NOT clear it — a hibernated node's last known state IS done,// and a late Stop POST arriving after the exit would undo the hibernation we just did.const alive = state === 'working' || state === 'blocked' || state === 'waiting'- if (alive && prev.hibernated) next.hibernated = undefined+ if (alive && prev.hibernated) {+ next.hibernated = undefined+ next.hibernatedPane = undefined // goes with the flag, always+ }const byId = { ...s.byId, [id]: next }// `state` itself is transient, so a plain transition writes nothing — but dropping a// PERSISTED flag has to reach disk, or a relaunch would restore a hibernated node that@@ -367,7 +392,15 @@ export function createAgentStatusSession(if (!!prev.hibernated === on) return s// Cleared by dropping the key, not by storing `false`: `save` skips entries that carry// nothing durable, so a woken node leaves no residue behind in localStorage.- const next = { ...prev, hibernated: on ? true : undefined }+ // The recorded pane belongs to THIS hibernation: it goes with the flag, in both+ // directions. Kept past a wake it would be a standing permission to type into whatever+ // that string names, long after we measured it.+ const next: AgentNodeStatus = {+ ...prev,+ hibernated: on ? true : undefined,+ // Hibernating KEEPS what the exit closure just recorded; waking drops it.+ hibernatedPane: on ? prev.hibernatedPane : undefined+ }// Waking RESTARTS the idle clock. Without this, a node whose conversation was resumed but// whose CLI then sits quiet (an agent that fires no hook until you talk to it) still// carries the `lastEventAt` from before it was hibernated — hours old — so the very next@@ -380,6 +413,16 @@ export function createAgentStatusSession(return { byId }}),+ setHibernatedPane: (id, pane) =>+ set((s) => {+ const prev = s.byId[id] ?? EMPTY+ const next = pane ?? undefined+ if (prev.hibernatedPane === next) return s+ const byId = { ...s.byId, [id]: { ...prev, hibernatedPane: next } }+ save(byId)+ return { byId }+ }),+markUnread: (id) =>set((s) => {const prev = s.byId[id] ?? EMPTYdiff --git a/src/renderer/terminal/hibernation-policy.test.ts b/src/renderer/terminal/hibernation-policy.test.tsindex 2d2103a53..96c60b132 100644--- a/src/renderer/terminal/hibernation-policy.test.ts+++ b/src/renderer/terminal/hibernation-policy.test.ts@@ -9,6 +9,7 @@ const base = (id: string, over: object = {}) => ({wired: true,offscreen: true,hibernated: false,+ remote: false,recurring: false,liveSubagents: false,lastEventAt: 0,@@ -93,6 +94,24 @@ describe('planHibernation', () => {expect(planHibernation([base('a', { hibernated: true })], NOW, cfg)).toEqual([])})+ it('excludes REMOTE sessions here, not only at the exit — the batch is a slice', () => {+ expect(planHibernation([base('a', { remote: true })], NOW, cfg)).toEqual([])+ // The reason it must be excluded at PLAN time: two remote nodes at the head of the oldest-idle+ // order would fill both slots on every pass, and the local node behind them would never be+ // reached — Eco silently doing nothing on the machine it was enabled for.+ expect(+ planHibernation(+ [+ base('r1', { remote: true, lastEventAt: 0 }),+ base('r2', { remote: true, lastEventAt: 1 }),+ base('local', { lastEventAt: 2 })+ ],+ NOW,+ cfg+ )+ ).toEqual(['local'])+ })+it('empty candidate list → empty', () => {expect(planHibernation([], NOW, cfg)).toEqual([])})diff --git a/src/renderer/terminal/hibernation-policy.ts b/src/renderer/terminal/hibernation-policy.tsindex 9465b0055..8cef575bd 100644--- a/src/renderer/terminal/hibernation-policy.ts+++ b/src/renderer/terminal/hibernation-policy.ts@@ -24,6 +24,10 @@* - **Unknown idle is NOT idle.** A candidate with no `lastEventAt` (no hook event has ever been* seen for it in this run) is never eligible — the same rule as pendingLaunch's "an unknown* dependency state is not satisfied". Guessing here costs the user a live session.+ * - **Never a REMOTE session** (SSH project / relay tab) in v1 — and excluded at PLAN time, not+ * only when the exit is attempted: the plan is a deterministic sort-and-slice, so two remote+ * nodes at the head of the oldest-idle order would occupy both batch slots on every pass and no+ * local node would ever hibernate.* - **`restartEligibility` is the shared gate.** Hibernation is exit + resume, so a node this* module picks must be one the restart machinery could actually bring back: a CLI we cannot* quit or resume, or a session with no provider session id, has nothing to resume INTO.@@ -52,6 +56,19 @@ export interface HibernationCandidate {offscreen: boolean/** Already hibernated — nothing left to reclaim. */hibernated: boolean+ /**+ * The session runs on ANOTHER MACHINE (an SSH project's terminal, or a relay/remote-server tab).+ * Excluded in v1, the same call the offscreen dispose makes: the exit and its much later resume+ * would race the ControlMaster / relay lifecycle, and a wake that cannot reach the host leaves a+ * dead conversation behind.+ *+ * Excluded HERE and not only at the moment of the exit, because this plan is a deterministic+ * sort-and-slice: two remote nodes sitting at the head of the oldest-idle order would fill both+ * batch slots on every pass, refuse at fire time, and no local node would ever be hibernated —+ * a feature that silently does nothing, which is the hardest kind of failure to notice. The+ * fire-time check stays as the freshness re-ask (a project can BECOME an SSH project).+ */+ remote: boolean/** Any `/loop`, `/schedule` or `/cron` indicator on this node (from `agentStatus.loop`). */recurring: boolean/** Any non-done subagent card whose parent is this node (from `state/agentNodes.ts`). */@@ -83,6 +100,7 @@ export function planHibernation(.filter((c) =>!c.hibernated &&+ !c.remote &&c.wired &&c.offscreen &&c.state === 'done' &&diff --git a/src/renderer/terminal/offscreen-policy.test.ts b/src/renderer/terminal/offscreen-policy.test.tsindex 06604327f..0836836d0 100644--- a/src/renderer/terminal/offscreen-policy.test.ts+++ b/src/renderer/terminal/offscreen-policy.test.ts@@ -4,7 +4,8 @@ import {offscreenDisposeMs,mayDisposeOffscreen,offscreenCoreIsRemote,- planOffscreenVisibility+ planOffscreenVisibility,+ shouldDeferReleaseForEco} from './offscreen-policy'describe('offscreen dispose policy', () => {@@ -98,3 +99,42 @@ describe('planOffscreenVisibility', () => {).toEqual({ cancelTimer: false, armTimer: false, revive: false })})})++describe('shouldDeferReleaseForEco — hibernate first, then release the viewer', () => {+ // Defaults: the release fires at 10 minutes, the idle window closes at 30. Without the deferral+ // the release wins, unwires the node, and "finish a turn and pan away" never hibernates at all.+ const base = {+ ecoEnabled: true,+ resumableAgent: true,+ hibernated: false,+ offscreenElapsedMs: 10 * 60_000,+ idleMinutes: 30,+ offscreenMinutes: 10+ }++ it('defers at the release deadline, so the bigger prize (the CLI) is still reachable', () => {+ expect(shouldDeferReleaseForEco(base)).toBe(true)+ })++ it('stops deferring once the node HAS hibernated — the pane is a plain shell now', () => {+ expect(shouldDeferReleaseForEco({ ...base, hibernated: true })).toBe(false)+ })++ it('never defers with Eco off, or for a CLI that can never be quit + resumed', () => {+ expect(shouldDeferReleaseForEco({ ...base, ecoEnabled: false })).toBe(false)+ expect(shouldDeferReleaseForEco({ ...base, resumableAgent: false })).toBe(false)+ })++ it('never defers on an unusable idle window (planHibernation refuses those outright)', () => {+ for (const idleMinutes of [0, -5, NaN])+ expect(shouldDeferReleaseForEco({ ...base, idleMinutes }), String(idleMinutes)).toBe(false)+ })++ it('caps the wait at idle + offscreen, so a node that can NEVER hibernate is not stranded', () => {+ // A /cron node, one with a live subagent, one whose session id never arrived: nothing here+ // knows that, and the cap is what makes not knowing safe.+ expect(shouldDeferReleaseForEco({ ...base, offscreenElapsedMs: 40 * 60_000 - 1 })).toBe(true)+ expect(shouldDeferReleaseForEco({ ...base, offscreenElapsedMs: 40 * 60_000 })).toBe(false)+ expect(shouldDeferReleaseForEco({ ...base, offscreenElapsedMs: 90 * 60_000 })).toBe(false)+ })+})diff --git a/src/renderer/terminal/offscreen-policy.ts b/src/renderer/terminal/offscreen-policy.tsindex 36da363ad..842115353 100644--- a/src/renderer/terminal/offscreen-policy.ts+++ b/src/renderer/terminal/offscreen-policy.ts@@ -43,6 +43,54 @@ export function mayDisposeOffscreen(i: {return !i.visible && !i.remote && !i.selected}+/** 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. */+export const OFFSCREEN_DEFER_RETRY_MS = 60_000++/**+ * PHASE 5 ORDERING: with Eco on, releasing an offscreen terminal's viewer WAITS for its agent to+ * hibernate first.+ *+ * The two features want the same node and they are not equal prizes. This release reclaims the+ * xterm buffer and the PTY client — roughly 15 MB at the top end. Hibernation reclaims the agent+ * CLI PROCESS, which is hundreds of MB. But the release UNWIRES the node (the lifecycle effect+ * tears down, so the hibernate pair is unregistered and `planHibernation` reads the node as+ * unwired), and at the shipped defaults it fires FIRST — 10 minutes offscreen against a 30-minute+ * idle window. The canonical case the whole feature exists for, "finish a turn and pan away",+ * therefore never hibernated at all: the small prize was taken in a way that forfeited the large+ * one. So the release defers, and the ordering becomes hibernate-then-release; once the CLI is+ * gone, the pane holds a plain shell and the viewer release is a pure win on top.+ *+ * The deferral is CAPPED, and the cap is why this cannot strand anything: a node that will never+ * hibernate — a `/cron` node, one with a live subagent, an agent with no session id yet — must not+ * hold its viewer forever waiting for something that is not coming. Past+ * `idleMinutes + offscreenMinutes` the release proceeds regardless, so the worst case is that a+ * non-hibernating node keeps its buffer for the sum of the two windows instead of one of them.+ *+ * Deliberately NOT gated on "this node is currently eligible": eligibility is a moving target+ * (a working node goes done, a session id arrives late), and asking for it here would re-implement+ * `planHibernation` in a second place. The question asked is the durable one — could this node's+ * CLI ever be quit and resumed at all — and the cap covers the rest.+ */+export function shouldDeferReleaseForEco(i: {+ ecoEnabled: boolean+ /** Is this an agent whose CLI this app can quit AND resume? (Anything else can never hibernate.) */+ resumableAgent: boolean+ /** Already hibernated — the CLI is gone, so the release is now a pure win and must proceed. */+ hibernated: boolean+ /** How long this node has been continuously out of view. */+ offscreenElapsedMs: number+ idleMinutes: number+ offscreenMinutes: number+}): boolean {+ if (!i.ecoEnabled || !i.resumableAgent || i.hibernated) return false+ // An unusable window means Eco is off in practice (`planHibernation` refuses a non-positive one),+ // so there is nothing to wait for — release on the ordinary schedule.+ if (!(i.idleMinutes > 0)) return false+ const cap = (i.idleMinutes + Math.max(0, i.offscreenMinutes)) * 60_000+ return i.offscreenElapsedMs < cap+}+/** What a visibility report owes the offscreen state machine. Pure so the node only has to run it. */export interface OffscreenPlan {/** Drop the pending dispose timer (it is armed and no longer wanted). */