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): a hidden window lets terminals count as offscreen
review2513e722f752
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex fd61ff8d3..7e832c48e 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -105,6 +105,11 @@ import {releaseAllHiddenGrants,WEBGL_GESTURE_SETTLE_MS} from '../terminal/webgl-budget'+import {+ BACKGROUND_RELEASE_DWELL_MS,+ isWindowBackgrounded,+ setWindowBackgrounded+} from '../terminal/window-backgrounded'import { StickyNode } from '../nodes/StickyNode'import { GroupNode, setWorktreeActionHandler } from '../nodes/GroupNode'import { LazyEditorNode, LazyDiffNode } from '../nodes/lazyMonacoNodes'@@ -1320,6 +1325,18 @@ function setupApi(): typeof window.nodeTerminal.projectSetup {return window.nodeTerminal.projectSetup}+/**+ * The renderer's bulk reclaim pair, shared by memory pressure and a window put away for the+ * background dwell. Both halves are idempotent and cost only warmth: a reclaimed HIDDEN context+ * re-grants on its next visibility transition (a visible holder is never touched — see+ * `releaseAllHiddenGrants`), and a dropped park re-mounts as an ordinary warm reattach unless it+ * holds live work (`disposeAllParkedTerminals` asks the live-work gate).+ */+function runReclaimLevers(): void {+ releaseAllHiddenGrants()+ disposeAllParkedTerminals()+}+export function Canvas() {// This canvas's core api (a context read — stable for the session, no store subscription).// For the local session it IS window.nodeTerminal, so every call resolves identically.@@ -17711,13 +17728,42 @@ export function Canvas() {// session-reaper sweep) belongs to the shell, not here. Optional-called because the Server// Edition's bridge declares this a documented no-op.useEffect(() => {- const off = window.nodeTerminal.onMemoryPressure?.(() => {- releaseAllHiddenGrants()- disposeAllParkedTerminals()- })+ const off = window.nodeTerminal.onMemoryPressure?.(() => runReclaimLevers())return () => off?.()}, [])+ // Window put away (close-to-tray — the Windows default —, macOS hide-on-close, minimize): flip+ // the backgrounded flag, which makes every terminal report itself offscreen so the offscreen+ // release runs on its (dwell-shortened) timer behind all of its gates, live-work included. Then,+ // once the window has stayed hidden for the dwell, run the same reclaim pair memory pressure runs:+ // by then every terminal reads hidden, so `releaseAllHiddenGrants` frees the contexts the+ // on-screen terminals held too, and the parks go (`disposeAllParkedTerminals` keeps a park that+ // holds live work). A quick close/reopen cancels the dwell and nothing is released. On show the+ // observers' real verdicts flow again: released nodes warm-reattach, contexts re-grant through+ // the budget. Server Edition: the bridge declares the signal a no-op (see stubs.ts).+ useEffect(() => {+ let dwell: ReturnType<typeof setTimeout> | null = null+ const clearDwell = (): void => {+ if (dwell) clearTimeout(dwell)+ dwell = null+ }+ const off = window.nodeTerminal.onWindowVisibility?.((state) => {+ const hidden = state === 'hidden'+ setWindowBackgrounded(hidden)+ if (!hidden) return clearDwell()+ if (dwell) return+ dwell = setTimeout(() => {+ dwell = null+ if (isWindowBackgrounded()) runReclaimLevers()+ }, BACKGROUND_RELEASE_DWELL_MS)+ })+ return () => {+ off?.()+ clearDwell()+ setWindowBackgrounded(false)+ }+ }, [])+// Permanently remove a project (from the "Recently closed" list): end every terminal's tmux// session, drop persisted agent status, tear down any SSH master, then delete it from disk.const deleteProject = useCallback(diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 7e66a30be..f1f118967 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -118,6 +118,12 @@ import {} from '../terminal/terminal-font-zoom'import { ensureProjectLaunchInfo } from '../state/projectLaunchInfo'import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from '../terminal/webgl-budget'+import {+ backgroundReleaseMs,+ effectiveVisible,+ isWindowBackgrounded,+ subscribeWindowBackgrounded+} from '../terminal/window-backgrounded'import { quantizeCharSize } from '../terminal/char-size-quantize'import { resyncDomRendererSpacing } from '../terminal/dom-renderer-spacing'import {@@ -5280,159 +5286,182 @@ export function TerminalNode({useEffect(() => {const container = bodyRef.currentif (!container || typeof IntersectionObserver === 'undefined') return- const io = new IntersectionObserver(- (entries) => {- const visible = entries[entries.length - 1]?.isIntersecting ?? false- // The renderer half first: it reads `wasVisibleRef` as the PREVIOUS verdict for its- // hidden→visible edge test, so the write below must come after it.- visibilityReportRef.current?.(visible)- const wasVisible = wasVisibleRef.current- wasVisibleRef.current = visible- // Publish the same verdict for the hibernation sweep, which runs in Canvas and cannot see- // this node's box. One observer, two consumers — a second observer would be a second- // opinion about the same rectangle.- setNodeOffscreen(id, !visible)- // …and the wake edge: a hibernated node the user has just panned back to gets its- // 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. A `paused` node is- // excluded — see the mount-timer trigger above for why (`shouldAutoWake`).- const stVisible = useAgentStatus.getState().byId[id]- if (visible && !wasVisible && shouldAutoWake(stVisible?.hibernated, stVisible?.paused))- wakeRef.current()- // …and the liveness check, for the same reason and on the same edge: a node whose CLI died- // while nobody was looking should say so by the time the user has finished panning to it,- // not on the interval's next tick. Cheap — the asker's own gate returns before any I/O for- // a node that is not a parked agent.- if (visible && !wasVisible) void livenessAskRef.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(- useSettings.getState().settings.offscreenTerminalMinutes- )- const plan = planOffscreenVisibility({- visible,- down: offscreenDownRef.current,- timerArmed: !!offscreenTimerRef.current,- disposeMs- })- if (plan.cancelTimer && offscreenTimerRef.current) {- clearTimeout(offscreenTimerRef.current)+ // The observer's own latest verdict, kept so a window-backgrounded EDGE (which the observer+ // never sees — a hidden window still has a viewport) can be re-stated through the same path.+ let intersecting = false+ let observed = false+ // One verdict, whoever produced it: the observer, or the window being put away / brought back.+ // `visible` is already the EFFECTIVE value (`effectiveVisible`) — while the window is+ // backgrounded every node reports itself offscreen, so every consumer below (WebGL budget,+ // hibernation sweep, liveness poll, offscreen release) sees "nobody is looking", and every+ // fire-time gate of the release still applies unchanged.+ const onVerdict = (visible: boolean): void => {+ // The renderer half first: it reads `wasVisibleRef` as the PREVIOUS verdict for its+ // hidden→visible edge test, so the write below must come after it.+ visibilityReportRef.current?.(visible)+ const wasVisible = wasVisibleRef.current+ wasVisibleRef.current = visible+ // Publish the same verdict for the hibernation sweep, which runs in Canvas and cannot see+ // this node's box. One observer, two consumers — a second observer would be a second+ // opinion about the same rectangle.+ setNodeOffscreen(id, !visible)+ // …and the wake edge: a hibernated node the user has just panned back to gets its+ // 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. A `paused` node is+ // excluded — see the mount-timer trigger above for why (`shouldAutoWake`).+ const stVisible = useAgentStatus.getState().byId[id]+ if (visible && !wasVisible && shouldAutoWake(stVisible?.hibernated, stVisible?.paused))+ wakeRef.current()+ // …and the liveness check, for the same reason and on the same edge: a node whose CLI died+ // while nobody was looking should say so by the time the user has finished panning to it,+ // not on the interval's next tick. Cheap — the asker's own gate returns before any I/O for+ // a node that is not a parked agent.+ if (visible && !wasVisible) void livenessAskRef.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.+ // Backgrounded: the shorter of the user's window and the background dwell (`0 = never`+ // still wins). Only a NEW timer picks this up — one already armed by an earlier pan keeps+ // its own deadline, which is at most the ordinary offscreen window.+ const disposeMs = backgroundReleaseMs(+ offscreenDisposeMs(useSettings.getState().settings.offscreenTerminalMinutes),+ isWindowBackgrounded()+ )+ const plan = planOffscreenVisibility({+ visible,+ down: offscreenDownRef.current,+ timerArmed: !!offscreenTimerRef.current,+ disposeMs+ })+ if (plan.cancelTimer && offscreenTimerRef.current) {+ clearTimeout(offscreenTimerRef.current)+ offscreenTimerRef.current = null+ }+ if (plan.revive) {+ offscreenDownRef.current = false+ setOffscreenDown(false)+ setOffscreenEpoch((n) => n + 1) // re-run the lifecycle effect → fresh warm tmux attach+ }+ if (plan.armTimer && disposeMs !== null) {+ // 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- }- if (plan.revive) {- offscreenDownRef.current = false- setOffscreenDown(false)- setOffscreenEpoch((n) => n + 1) // re-run the lifecycle effect → fresh warm tmux attach- }- if (plan.armTimer && disposeMs !== null) {- // 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.- if (- !mayDisposeOffscreen({- visible: wasVisibleRef.current,- remote: offscreenRemoteRef.current,- selected: selectedRef.current- })- )- 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 (!releaseStillEnabled(liveSettings.offscreenTerminalMinutes)) 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- // 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: readAgentStateRef.current(),- agentProcess: readAgentProcessRef.current()- })- ) {- // Re-stamp the offscreen clock: this node is not RELEASABLE yet, and the Eco- // deferral's cap is measured from the start of the releasable stretch. Without this- // a long live-work wait would blow that cap outright, so the release that finally- // runs would skip the hibernate-first ordering and forfeit the CLI's hundreds of MB- // at the exact moment they became reclaimable. The stretch effectively begins when- // the work ends.- offscreenSinceRef.current = Date.now()- offscreenTimerRef.current = setTimeout(fireRelease, OFFSCREEN_DEFER_RETRY_MS)- return- }- // A HELD LAUNCH ON A PLAIN SHELL (the fifth lever): the `--after` launch this node holds- // is typed into the pane by session name, and without tmux the release destroys that- // pane. Nothing brings a released node back but the camera, so the launch would sit- // QUEUED until the user happened to pan over it. Same cadence, same drain: the hold- // ends when the launch fires. (Tmux-backed: released as normal — see the teardown,- // which keeps such a session READY because it stays typeable by name.)- if (- shouldDeferReleaseForHeldLaunch({- tmuxBacked: sessionPersistentRef.current,- armed: armedRef.current- })- ) {- offscreenSinceRef.current = Date.now()- 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 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.- const ecoStatus = useAgentStatus.getState().byId[id]- if (- shouldDeferReleaseForEco({- ecoEnabled: liveSettings.agentHibernationEnabled,- resumableAgent: hibernationTargetRef.current,- hibernated: !!ecoStatus?.hibernated,- // Same "unknown idle is not idle" rule the policy applies: with no hook event seen- // in this run there is no idle clock, `planHibernation` refuses this node outright,- // and waiting for a hibernation that cannot come would hold every warm node's- // viewer for the full cap after each app restart.- idleKnown: ecoStatus?.lastEventAt !== undefined,- 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)+ // 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.+ if (+ !mayDisposeOffscreen({+ visible: wasVisibleRef.current,+ remote: offscreenRemoteRef.current,+ selected: selectedRef.current+ })+ )+ 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 (!releaseStillEnabled(liveSettings.offscreenTerminalMinutes)) 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+ // 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: readAgentStateRef.current(),+ agentProcess: readAgentProcessRef.current()+ })+ ) {+ // Re-stamp the offscreen clock: this node is not RELEASABLE yet, and the Eco+ // deferral's cap is measured from the start of the releasable stretch. Without this+ // a long live-work wait would blow that cap outright, so the release that finally+ // runs would skip the hibernate-first ordering and forfeit the CLI's hundreds of MB+ // at the exact moment they became reclaimable. The stretch effectively begins when+ // the work ends.+ offscreenSinceRef.current = Date.now()+ offscreenTimerRef.current = setTimeout(fireRelease, OFFSCREEN_DEFER_RETRY_MS)+ return+ }+ // A HELD LAUNCH ON A PLAIN SHELL (the fifth lever): the `--after` launch this node holds+ // is typed into the pane by session name, and without tmux the release destroys that+ // pane. Nothing brings a released node back but the camera, so the launch would sit+ // QUEUED until the user happened to pan over it. Same cadence, same drain: the hold+ // ends when the launch fires. (Tmux-backed: released as normal — see the teardown,+ // which keeps such a session READY because it stays typeable by name.)+ if (+ shouldDeferReleaseForHeldLaunch({+ tmuxBacked: sessionPersistentRef.current,+ armed: armedRef.current+ })+ ) {+ offscreenSinceRef.current = Date.now()+ offscreenTimerRef.current = setTimeout(fireRelease, OFFSCREEN_DEFER_RETRY_MS)+ return}- offscreenTimerRef.current = setTimeout(fireRelease, disposeMs)+ // 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.+ const ecoStatus = useAgentStatus.getState().byId[id]+ if (+ shouldDeferReleaseForEco({+ ecoEnabled: liveSettings.agentHibernationEnabled,+ resumableAgent: hibernationTargetRef.current,+ hibernated: !!ecoStatus?.hibernated,+ // Same "unknown idle is not idle" rule the policy applies: with no hook event seen+ // in this run there is no idle clock, `planHibernation` refuses this node outright,+ // and waiting for a hibernation that cannot come would hold every warm node's+ // viewer for the full cap after each app restart.+ idleKnown: ecoStatus?.lastEventAt !== undefined,+ 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)}+ offscreenTimerRef.current = setTimeout(fireRelease, disposeMs)+ }+ }+ const io = new IntersectionObserver(+ (entries) => {+ intersecting = entries[entries.length - 1]?.isIntersecting ?? false+ observed = true+ onVerdict(effectiveVisible(intersecting, isWindowBackgrounded()))},{ rootMargin: '256px' })io.observe(container)+ // Before the observer's first delivery there is no verdict to re-state; that first delivery+ // reads the flag itself.+ const offBackgrounded = subscribeWindowBackgrounded((bg) => {+ if (observed) onVerdict(effectiveVisible(intersecting, bg))+ })return () => {+ offBackgrounded()io.disconnect()if (offscreenTimerRef.current) {clearTimeout(offscreenTimerRef.current)diff --git a/src/renderer/terminal/window-backgrounded.test.ts b/src/renderer/terminal/window-backgrounded.test.tsnew file mode 100644index 000000000..8a838db8a--- /dev/null+++ b/src/renderer/terminal/window-backgrounded.test.ts@@ -0,0 +1,132 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ BACKGROUND_RELEASE_DWELL_MS,+ backgroundReleaseMs,+ effectiveVisible,+ isWindowBackgrounded,+ resetWindowBackgroundedForTests,+ setWindowBackgrounded,+ subscribeWindowBackgrounded+} from './window-backgrounded'+import {+ mayDisposeOffscreen,+ offscreenDisposeMs,+ planOffscreenVisibility,+ shouldDeferReleaseForLiveWork+} from './offscreen-policy'++afterEach(() => resetWindowBackgroundedForTests())++describe('effectiveVisible', () => {+ it('is the observer verdict unless the window is backgrounded', () => {+ expect(effectiveVisible(true, false)).toBe(true)+ expect(effectiveVisible(false, false)).toBe(false)+ expect(effectiveVisible(true, true)).toBe(false)+ expect(effectiveVisible(false, true)).toBe(false)+ })+})++describe('backgroundReleaseMs', () => {+ it('shortens the offscreen window to the background dwell only while backgrounded', () => {+ expect(backgroundReleaseMs(10 * 60_000, true)).toBe(BACKGROUND_RELEASE_DWELL_MS)+ expect(backgroundReleaseMs(10 * 60_000, false)).toBe(10 * 60_000)+ })++ it('keeps a shorter user setting', () => {+ expect(backgroundReleaseMs(60_000, true)).toBe(60_000)+ })++ it('never overrides the setting\'s "never" (0 = off)', () => {+ expect(backgroundReleaseMs(offscreenDisposeMs(0), true)).toBeNull()+ expect(backgroundReleaseMs(null, false)).toBeNull()+ })+})++describe('the backgrounded flag', () => {+ it('defaults to not backgrounded (the keep-everything direction)', () => {+ expect(isWindowBackgrounded()).toBe(false)+ })++ it('notifies on changes only', () => {+ const seen: boolean[] = []+ subscribeWindowBackgrounded((b) => seen.push(b))+ setWindowBackgrounded(false)+ setWindowBackgrounded(true)+ setWindowBackgrounded(true)+ setWindowBackgrounded(false)+ expect(seen).toEqual([true, false])+ })++ it('keeps notifying the rest when one listener throws', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const second = vi.fn()+ subscribeWindowBackgrounded(() => {+ throw new Error('boom')+ })+ subscribeWindowBackgrounded(second)+ setWindowBackgrounded(true)+ expect(second).toHaveBeenCalledWith(true)+ warn.mockRestore()+ })++ it('unsubscribes', () => {+ const l = vi.fn()+ const off = subscribeWindowBackgrounded(l)+ off()+ setWindowBackgrounded(true)+ expect(l).not.toHaveBeenCalled()+ })+})++describe('a backgrounded on-screen node rides the ordinary offscreen machine', () => {+ it('arms the release at the dwell, and revives on show', () => {+ vi.useFakeTimers()+ try {+ const disposeMs = offscreenDisposeMs(undefined)+ const ms = backgroundReleaseMs(disposeMs, true)+ const plan = planOffscreenVisibility({+ visible: effectiveVisible(true, true),+ down: false,+ timerArmed: false,+ disposeMs: ms+ })+ expect(plan.armTimer).toBe(true)+ const fire = vi.fn()+ setTimeout(fire, ms!)+ vi.advanceTimersByTime(BACKGROUND_RELEASE_DWELL_MS - 1)+ expect(fire).not.toHaveBeenCalled()+ vi.advanceTimersByTime(1)+ expect(fire).toHaveBeenCalledTimes(1)+ // Shown again: the observer's real verdict (intersecting) revives the released node.+ expect(+ planOffscreenVisibility({+ visible: effectiveVisible(true, false),+ down: true,+ timerArmed: false,+ disposeMs+ }).revive+ ).toBe(true)+ } finally {+ vi.useRealTimers()+ }+ })+})++describe('backgrounding changes visibility, never the fire-time gates', () => {+ const visible = effectiveVisible(true, true)++ it('releases a backgrounded tmux-backed node', () => {+ expect(mayDisposeOffscreen({ visible, remote: false, selected: false })).toBe(true)+ expect(shouldDeferReleaseForLiveWork({ tmuxBacked: true, agentState: 'working' })).toBe(false)+ })++ it('still defers a working agent on the plain-shell fallback (issue #126)', () => {+ expect(mayDisposeOffscreen({ visible, remote: false, selected: false })).toBe(true)+ expect(shouldDeferReleaseForLiveWork({ tmuxBacked: false, agentState: 'working' })).toBe(true)+ })++ it('still refuses a remote-core node and the selected node', () => {+ expect(mayDisposeOffscreen({ visible, remote: true, selected: false })).toBe(false)+ expect(mayDisposeOffscreen({ visible, remote: false, selected: true })).toBe(false)+ })+})diff --git a/src/renderer/terminal/window-backgrounded.ts b/src/renderer/terminal/window-backgrounded.tsnew file mode 100644index 000000000..e269fe0cc--- /dev/null+++ b/src/renderer/terminal/window-backgrounded.ts@@ -0,0 +1,78 @@+/**+ * "The window is put away" — one module-level flag the terminal levers read beside viewport+ * visibility.+ *+ * Every renderer reclaim lever (offscreen release, the WebGL budget, the hibernation sweep's+ * "is anybody watching") takes visibility from a per-node IntersectionObserver, and that observer+ * measures against the PAGE's viewport — which a hidden BrowserWindow still has. So a window closed+ * to the tray (the Windows default), hidden on close (macOS) or minimized kept every on-screen+ * terminal, its WebGL context and its PTY client resident for as long as it stayed hidden.+ *+ * The fix is one more INPUT, not a parallel release path: while backgrounded, every node reports+ * itself offscreen (`effectiveVisible`), so the existing state machine runs with all of its gates+ * intact — the live-work deferral (a plain-shell agent mid-turn is never killed), the held-launch+ * and Eco deferrals, the remote/SSH exclusion, the selected-node refusal and the setting's+ * `0 = never`. On show the observer's real verdict flows again and released nodes revive through+ * the ordinary warm re-attach.+ *+ * Fed ONLY by the desktop shell's explicit signal (`onWindowVisibility`), never by+ * `document.visibilityState`: an occluded window must not release, and the Server Edition's tab+ * switches must not either (its bridge declares the signal a no-op). Fail-safe direction: `false`+ * (not backgrounded = keep everything), which is what a fresh page or a missed event resolves to.+ */++/** How long the window must stay hidden before the levers run. A quick close/reopen (or a minimize+ * to glance at something) stays warm; a window put away for longer gives memory back. */+export const BACKGROUND_RELEASE_DWELL_MS = 2 * 60_000++let backgrounded = false+const listeners = new Set<(backgrounded: boolean) => void>()++export function isWindowBackgrounded(): boolean {+ return backgrounded+}++/** Set the flag; listeners hear CHANGES only (a repeated `'shown'` is a no-op). */+export function setWindowBackgrounded(next: boolean): void {+ if (next === backgrounded) return+ backgrounded = next+ for (const l of [...listeners]) {+ // One node's failure must not stop the rest of the canvas hearing the edge.+ try {+ l(next)+ } catch (err) {+ console.warn('[window-backgrounded] listener failed (continuing)', err)+ }+ }+}++export function subscribeWindowBackgrounded(listener: (backgrounded: boolean) => void): () => void {+ listeners.add(listener)+ return () => {+ listeners.delete(listener)+ }+}++/** What a node reports to the levers: the observer's verdict, unless the window is put away. */+export function effectiveVisible(intersecting: boolean, windowBackgrounded: boolean): boolean {+ return intersecting && !windowBackgrounded+}++/**+ * The offscreen-release delay for a node that goes offscreen BECAUSE the window was put away: the+ * shorter of the user's offscreen window and the background dwell. `null` (the setting's+ * "never") stays `null` — backgrounding never overrides an explicit opt-out.+ */+export function backgroundReleaseMs(+ disposeMs: number | null,+ windowBackgrounded: boolean+): number | null {+ if (disposeMs === null || !windowBackgrounded) return disposeMs+ return Math.min(disposeMs, BACKGROUND_RELEASE_DWELL_MS)+}++/** Test seam: reset module state between tests. */+export function resetWindowBackgroundedForTests(): void {+ backgrounded = false+ listeners.clear()+}diff --git a/src/renderer/terminal/window-backgrounded.wiring.test.ts b/src/renderer/terminal/window-backgrounded.wiring.test.tsnew file mode 100644index 000000000..54b3a3911--- /dev/null+++ b/src/renderer/terminal/window-backgrounded.wiring.test.ts@@ -0,0 +1,43 @@+// The hidden-window reclaim is three files of wiring around one pure module, and every link is a+// way it could compile and do nothing: main never sends, Canvas never sets the flag, or the node's+// observer never re-states its verdict on the edge. Neither main/index.ts nor Canvas/TerminalNode+// can be mounted here, so the wiring is pinned at source level; the decisions are behaviour-tested+// in window-backgrounded.test.ts and main/window-visibility.test.ts.+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++const read = (rel: string): string =>+ readFileSync(join(__dirname, rel), 'utf8').replace(/\r\n/g, '\n')++describe('hidden-window reclaim wiring', () => {+ it('main sends the signal for every window visibility event', () => {+ const main = read('../../main/index.ts')+ expect(main).toMatch(/for \(const ev of WINDOW_VISIBILITY_EVENTS\)/)+ expect(main).toContain('win.webContents.send(IPC.appWindowVisibility, windowVisibilitySignal(ev))')+ })++ it('the preload forwards it and the Server Edition declares it a no-op', () => {+ expect(read('../../preload/index.ts')).toContain('ipcRenderer.on(IPC.appWindowVisibility, handler)')+ expect(read('../bridge/stubs.ts')).toMatch(/onWindowVisibility: noopUnsub/)+ })++ it('Canvas sets the flag and runs the shared reclaim pair after the dwell', () => {+ const canvas = read('../canvas/Canvas.tsx')+ const at = canvas.indexOf('window.nodeTerminal.onWindowVisibility?.(')+ expect(at).toBeGreaterThan(-1)+ const effect = canvas.slice(at, canvas.indexOf('}, [])', at))+ expect(effect).toContain('setWindowBackgrounded(hidden)')+ expect(effect).toContain('BACKGROUND_RELEASE_DWELL_MS')+ expect(effect).toContain('runReclaimLevers()')+ // Memory pressure shares the same pair rather than a second copy of it.+ expect(canvas).toContain('onMemoryPressure?.(() => runReclaimLevers())')+ })++ it('the node re-states its effective verdict on the backgrounded edge, through the one path', () => {+ const node = read('../nodes/TerminalNode.tsx')+ expect(node).toContain('onVerdict(effectiveVisible(intersecting, isWindowBackgrounded()))')+ expect(node).toContain('if (observed) onVerdict(effectiveVisible(intersecting, bg))')+ expect(node).toMatch(/backgroundReleaseMs\(\s*offscreenDisposeMs\(/)+ })+})