Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat: memory-pressure responder chain (webgl + parks + early reaper sweep)

enes868d5c3092ec
diff --git a/src/core/memory-pressure.test.ts b/src/core/memory-pressure.test.ts
index c3ddd1570..ffd5c34bc 100644
--- a/src/core/memory-pressure.test.ts
+++ b/src/core/memory-pressure.test.ts
@@ -15,13 +15,17 @@ describe('memory pressure monitor', () => {
const m = createMemoryPressureMonitor({ readMem: () => null, selfRssMb: () => 500, onPressure: vi.fn() })
expect(m.check()).toBeNull()
})
+ it('self-RSS still counts when the host read fails', () => {
+ const m = createMemoryPressureMonitor({ readMem: () => null, selfRssMb: () => 9000, onPressure: vi.fn() })
+ expect(m.check()).toBe('critical')
+ })
it('self-RSS thresholds fire independently of host memory', () => {
const m = createMemoryPressureMonitor({ readMem: mem(8000), selfRssMb: () => 5000, onPressure: vi.fn() })
expect(m.check()).toBe('warning')
const c = createMemoryPressureMonitor({ readMem: mem(8000), selfRssMb: () => 9000, onPressure: vi.fn() })
expect(c.check()).toBe('critical')
})
- it('re-fires a severity at most once per 60s (edge-trigger + floor)', () => {
+ it('re-fires a severity at most once per 60s (floor)', () => {
vi.useFakeTimers()
const on = vi.fn()
const m = createMemoryPressureMonitor({ readMem: mem(1500), selfRssMb: () => 0, intervalMs: 1000, onPressure: on })
@@ -33,4 +37,37 @@ describe('memory pressure monitor', () => {
m.stop()
vi.useRealTimers()
})
+ it('stop() ends the sweeps for good', () => {
+ vi.useFakeTimers()
+ const on = vi.fn()
+ const m = createMemoryPressureMonitor({ readMem: mem(700), selfRssMb: () => 0, intervalMs: 1000, onPressure: on })
+ m.start()
+ vi.advanceTimersByTime(1000)
+ expect(on).toHaveBeenCalledTimes(1)
+ m.stop()
+ vi.advanceTimersByTime(600_000)
+ expect(on).toHaveBeenCalledTimes(1)
+ vi.useRealTimers()
+ })
+ it('a throwing consumer does not break the monitor', () => {
+ vi.useFakeTimers()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ let calls = 0
+ const m = createMemoryPressureMonitor({
+ readMem: mem(700),
+ selfRssMb: () => 0,
+ intervalMs: 1000,
+ onPressure: () => {
+ calls++
+ throw new Error('destroyed window')
+ }
+ })
+ m.start()
+ expect(() => vi.advanceTimersByTime(1000)).not.toThrow()
+ vi.advanceTimersByTime(61_000)
+ expect(calls).toBe(2) // still firing after the throw
+ m.stop()
+ warn.mockRestore()
+ vi.useRealTimers()
+ })
})
diff --git a/src/core/memory-pressure.ts b/src/core/memory-pressure.ts
index 722b5b667..953e45ec4 100644
--- a/src/core/memory-pressure.ts
+++ b/src/core/memory-pressure.ts
@@ -51,7 +51,14 @@ export function createMemoryPressureMonitor(opts: {
const now = Date.now()
if (now - lastFired < RE_FIRE_FLOOR_MS) return
lastFired = now
- opts.onPressure(s)
+ // A consumer throw must never take the shell down with it — the responders run in a
+ // shell (`webContents.send` on a destroyed window, a reaper sweep) and this timer is the
+ // only thing on the stack. Log and keep the monitor alive, like session-budget's sweep.
+ try {
+ opts.onPressure(s)
+ } catch (e) {
+ console.warn('[memory-pressure] onPressure threw', e)
+ }
}, opts.intervalMs ?? PRESSURE_INTERVAL_MS)
timer.unref?.()
},
diff --git a/src/main/index.ts b/src/main/index.ts
index d580cf065..36492cc4a 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -69,6 +69,7 @@ import { createGrantsAccessor, type PushGrant } from '../core/push-grants'
import { createRemoteGrantsCache } from '../core/remote-push-grants'
import { createAckSweeper } from '../core/ack-sweep'
import { createSessionReaper } from '../core/session-budget'
+import { createMemoryPressureMonitor } from '../core/memory-pressure'
import { getDeviceId } from '../core/device-id'
import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
import { initCanvasSync } from '../core/canvas-sync'
@@ -1525,7 +1526,21 @@ app.whenReady().then(async () => {
// budget). Attached sessions are never touched; a reaped node cold-restores on next open.
// Local sockets only — a remote SSH host's sessions are reaped by that host's own
// nodeterm-server, never across the wire. Timer is unref'd; no explicit stop needed.
- createSessionReaper({ tmuxBin: () => ptyManager.getTmuxBin() }).start()
+ const sessionReaper = createSessionReaper({ tmuxBin: () => ptyManager.getTmuxBin() })
+ sessionReaper.start()
+ // Memory pressure (core/memory-pressure.ts): the reaper's own 10-minute timer is the steady
+ // state; this is the fast path. On a watermark crossing the renderer runs its reclaim levers
+ // (hidden WebGL contexts, parked terminals) and a CRITICAL reading also sweeps the reaper NOW
+ // rather than waiting out its timer. Both levers are idempotent and the monitor re-fires at most
+ // once a minute. The send goes through `sendToMain`, which resolves the window AT SEND TIME and
+ // no-ops while it is closed (macOS keeps the app alive without one) — the monitor's own
+ // try/catch is the backstop, not the primary.
+ createMemoryPressureMonitor({
+ onPressure: (severity) => {
+ sendToMain(IPC.appMemoryPressure, severity)
+ if (severity === 'critical') void sessionReaper.sweep()
+ }
+ }).start()
const ackSweeper = createAckSweeper({
handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }
})
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b4db052c6..cd2b9fdf1 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -550,6 +550,11 @@ const api: NodeTerminalApi = {
ipcRenderer.on(IPC.appFocusNode, handler)
return () => ipcRenderer.removeListener(IPC.appFocusNode, handler)
},
+ onMemoryPressure: (listener) => {
+ const handler = (_e: unknown, severity: 'warning' | 'critical') => listener(severity)
+ ipcRenderer.on(IPC.appMemoryPressure, handler)
+ return () => ipcRenderer.removeListener(IPC.appMemoryPressure, handler)
+ },
answerPermission: (payload) => ipcRenderer.invoke(IPC.agentAnswerPermission, payload),
ackDone: (nodeId) => {
void ipcRenderer.invoke(IPC.agentAckDone, nodeId)
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 0e3baee2b..55b260318 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -335,6 +335,12 @@ export function buildStubApi(): Omit<
},
openNotificationSettings: pnoop,
onFocusNode: noopUnsub,
+ // Server Edition v1: the memory-pressure levers run HOST-side only (the session reaper, driven
+ // by the same core monitor in src/server/index.ts). A browser tab's own memory — its WebGL
+ // contexts and parked terminals — belongs to the browser, which already discards and reclaims
+ // on its own terms; pushing our levers over the wire would fight it, not help it. Deliberate
+ // no-op, not an oversight.
+ onMemoryPressure: noopUnsub,
onAgentControl: noopUnsub,
sendAgentControlResult: noop
} satisfies Omit<
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 2acd89ab8..4faedd7de 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -26,7 +26,8 @@ import {
setSshDropHandler,
setSshRetryHandler,
disposeTerminalOnUnmount,
- disposeParkedTerminal
+ disposeParkedTerminal,
+ disposeAllParkedTerminals
} from '../nodes/TerminalNode'
import { solveFitPadding } from './fit-view'
import {
@@ -44,7 +45,12 @@ import {
} from './SharedGlyphLayer'
import { SshReconnector } from '../lib/sshReconnect'
import { terminalKey } from '../terminal/terminal-config'
-import { setWebglGesture, setWebglZoom, WEBGL_GESTURE_SETTLE_MS } from '../terminal/webgl-budget'
+import {
+ setWebglGesture,
+ setWebglZoom,
+ releaseAllHiddenGrants,
+ WEBGL_GESTURE_SETTLE_MS
+} from '../terminal/webgl-budget'
import { StickyNode } from '../nodes/StickyNode'
import { GroupNode, setWorktreeActionHandler } from '../nodes/GroupNode'
import { LazyEditorNode, LazyDiffNode } from '../nodes/lazyMonacoNodes'
@@ -7394,6 +7400,21 @@ export function Canvas() {
// travelToNode, not focusNodeById, so a closed project's tab is reopened first).
useEffect(() => window.nodeTerminal.onFocusNode(travelToNode), [travelToNode])
+ // Memory pressure (core/memory-pressure.ts, pushed by the shell): run the renderer's reclaim
+ // levers. Both are idempotent and cost only warmth — a reclaimed hidden context re-grants on its
+ // next visibility transition, a dropped park re-mounts as an ordinary warm reattach — and the
+ // shell re-fires at most once a minute, so this never runs hot. Severity is not branched on
+ // (yet): the levers are cheap enough to run on 'warning', and the extra CRITICAL step (an early
+ // 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()
+ })
+ return () => off?.()
+ }, [])
+
// 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.tsx
index 9877c261d..dfc002339 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -296,6 +296,14 @@ export function disposeParkedTerminal(key: string): void {
disposeParked(p)
}
+/** Memory-pressure lever: drop EVERY parked terminal now, without waiting out `TERM_PARK_MS`. The
+ * park is a cache, not state — each dropped entry costs only its warm re-adopt, and the node
+ * re-mounts as an ordinary warm reattach (tmux redraws; the session and its scrollback are
+ * untouched). Idempotent; iterates a copy because `disposeParkedTerminal` mutates the map. */
+export function disposeAllParkedTerminals(): void {
+ for (const key of [...parkedTerminals.keys()]) disposeParkedTerminal(key)
+}
+
/** Session-scoped keys (`terminalKey`) whose next unmount must dispose (not park) — set on permanent
* deletion, where the unmount runs AFTER the session was already destroyed, so parking would keep a
* dead xterm. */
diff --git a/src/renderer/terminal/webgl-budget.ts b/src/renderer/terminal/webgl-budget.ts
index 3fd5267ee..b1d7c9d7e 100644
--- a/src/renderer/terminal/webgl-budget.ts
+++ b/src/renderer/terminal/webgl-budget.ts
@@ -344,6 +344,20 @@ function reclaim(c: Client): void {
c.granted = false
}
+/**
+ * Memory-pressure lever: reclaim EVERY hidden holder's context now, bypassing the release delay.
+ * Visible holders are untouched — the same invariant `lruHiddenHolder` applies, and for the same
+ * reason: taking a context off a terminal the user is looking at trades memory for a visible
+ * downgrade. Idempotent (a client that holds nothing is skipped), and each reclaimed client
+ * re-grants through the normal budget-gated path on its next visibility transition.
+ */
+export function releaseAllHiddenGrants(): void {
+ for (const c of clients.values()) {
+ if (!c.granted || c.visible) continue
+ reclaim(c)
+ }
+}
+
/** The least-recently-visible HIDDEN holder, or null if every holder is currently visible. */
function lruHiddenHolder(): Client | null {
let best: Client | null = null
diff --git a/src/server/index.ts b/src/server/index.ts
index 9652a5468..122de6500 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -50,6 +50,7 @@ import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { createGrantsAccessor } from '../core/push-grants'
import { createAckSweeper } from '../core/ack-sweep'
import { createSessionReaper } from '../core/session-budget'
+import { createMemoryPressureMonitor } from '../core/memory-pressure'
import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
import { claudeConfigDirFor } from '../core/claude-config-dir'
import { presenceHub } from '../core/presence/hub'
@@ -442,6 +443,19 @@ export async function startServer(
// open. Kill switch + tuning via NODETERM_SESSION_* env (core/session-budget.ts).
const sessionReaper = createSessionReaper({ tmuxBin: () => ptyManager.getTmuxBin() })
sessionReaper.start()
+ // Memory pressure (core/memory-pressure.ts): only the reaper leg on this shell. A CRITICAL
+ // reading sweeps NOW instead of waiting out the reaper's 10-minute timer — that is the whole
+ // responder chain here. The renderer levers the desktop also runs (hidden WebGL contexts,
+ // parked terminals) are deliberately NOT pushed to attached browsers: a tab's own memory is the
+ // browser's to manage, and it already discards on its own terms (see the documented no-op in
+ // renderer/bridge/stubs.ts). Stopped on close beside the reaper — the timer is unref'd, but a
+ // test that starts and closes several servers must not leave sweepers behind.
+ const pressure = createMemoryPressureMonitor({
+ onPressure: (severity) => {
+ if (severity === 'critical') void sessionReaper.sweep()
+ }
+ })
+ pressure.start()
// Headless notification host: every core service above (incl. the loopback hook server, which
// is its own listener and MUST run) is booted, but we bind NO public HTTP/WS listener — no
@@ -454,6 +468,7 @@ export async function startServer(
async close() {
// Detach PTY clients — tmux sessions keep running (Phase 1 contract).
sessionReaper.stop()
+ pressure.stop()
await contextLink.stop()
await ptyManager.killAll()
// Same native hazard as the desktop app: a whisper transcribe still running when the
@@ -500,6 +515,7 @@ export async function startServer(
async close() {
// Detach PTY clients — tmux sessions keep running (Phase 1 contract; never kill the server).
sessionReaper.stop()
+ pressure.stop()
await contextLink.stop()
await ptyManager.killAll()
// Same native hazard as the desktop app: a whisper transcribe still running when the node
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index f1e83aaed..915433266 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -41,6 +41,10 @@ export const IPC = {
appOpenNotificationSettings: 'app:open-notification-settings',
appFocusNode: 'app:focus-node',
appSetBadge: 'app:set-badge',
+ /** Main → renderer: the host (or this process's own RSS) crossed a memory-pressure watermark,
+ * so the renderer should run its reclaim levers now (hidden WebGL contexts, parked terminals).
+ * Payload: `'warning' | 'critical'`. Re-fired at most once a minute — see core/memory-pressure. */
+ appMemoryPressure: 'app:memory-pressure',
agentStatus: 'agent:status',
/** Renderer → main/server: answer a held Claude permission hook (deterministic approvals).
* Payload: `{ nodeId, pendingId, decision: 'allow'|'deny' }`; resolves boolean. See
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 6d516e00b..7206ce1cd 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2011,6 +2011,12 @@ export interface NodeTerminalApi {
openNotificationSettings(): Promise<void>
/** Fires when a notification is clicked, asking the renderer to focus a node. Returns unsubscribe. */
onFocusNode(listener: (nodeId: string) => void): () => void
+ /** Fires when the shell's memory-pressure monitor (core/memory-pressure.ts) sees the host — or
+ * this process's own RSS — cross a watermark: the renderer answers by running its reclaim
+ * levers (hidden WebGL contexts, parked terminals). At most one fire a minute, so the levers
+ * need only be idempotent, not cheap. Returns unsubscribe. Server Edition: never fires (the
+ * pressure levers run host-side there; a browser tab's memory belongs to the browser). */
+ onMemoryPressure(listener: (severity: 'warning' | 'critical') => void): () => void
/** Answer a Claude permission request via the deterministic hook-reply channel (spec:
* docs/hook-reply-approvals.md). Writes the one-line answer file the held hook is polling
* (`~/.nodeterm/pending/<pendingId>.answer`) on the host the agent runs on — the LOCAL fs for a