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): darwin kernel-level leg, fired on escalations only

Brandon Bridgese0024cd56320
diff --git a/CLAUDE.md b/CLAUDE.md
index 63efdf5b0..2388337d3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6633,6 +6633,19 @@ detaching + an always-true pressure signal is why the symptom read as "my sessio
disappearing" rather than as an occasional cull. The `vm_stat` reader is what makes the pool safe
again; the grace window was never the thing that was wrong.
+**macOS memory pressure is the KERNEL's level, on its own leg, fired on escalations only.** The
+byte leg (`hostMemReader`) stays `null` on darwin and main's RSS never nears the 4 GB self leg, so
+until this leg the renderer's reclaim levers never ran on a visible Mac window — the safety net #179
+counted on was dead. `core/memory-pressure.ts` now samples `kern.memorystatus_vm_pressure_level`
+(1 normal / 2 warn / 4 critical; async `sysctl` per 30 s tick, last landed value) and calls
+`onKernelPressure` once per ESCALATION (normal→warn, →critical). Measured lever effect (dev, 12
+hidden warm terminals): GPU footprint 331 → 152 MB, IOSurface 235 → 91 MB, all 12 re-granted on
+pan-back. Three rules: never re-fire a HELD kernel level (the 60 s floor at a held WARN is #179's
+timed release and its pan-back flicker again); never feed the level through `hostMemReader` /
+`MemInfo` (`planReap` shares it — that would be a new reaper trigger); a kernel CRITICAL runs the
+levers only, no reaper sweep, until that step is measured on its own (#211). A failed read is no
+information: it neither fires nor resets the held level.
+
## Live links (Pro browser link to one terminal: watch, chat, or type)
A live link shows ONE node in a plain browser — read-only, or typeable on a Control link by a viewer
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6a4fcd4ab..adf7b9942 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1345,6 +1345,9 @@ bite most often:
- `handleNodesChange` must not call `onNodesChange` with an empty batch (it re-renders the canvas
every frame through React Flow's ResizeObserver).
- Work done per terminal on a project switch must be coalesced and on-screen-first.
+- macOS memory pressure comes from the kernel's level (`onKernelPressure` in
+ `core/memory-pressure.ts`), fired on escalations only. Never re-fire it on a held level, and
+ never route it through `hostMemReader`/`MemInfo`: the session reaper shares that reader.
**SSH projects on Windows** run over an in-process transport (`src/core/remote-ssh/native/`),
not the ssh binary. If you add an ssh call site, route it through `useNativeSsh()` like the
diff --git a/docs/session-memory.md b/docs/session-memory.md
index d1d613810..10a065fde 100644
--- a/docs/session-memory.md
+++ b/docs/session-memory.md
@@ -512,6 +512,11 @@ macOS (the ps path never runs on Linux)
AM's 19.00 GB of parts on a 24 GB machine (was 23.9/24.0 before the fix). Still open on
macOS: give the memory-PRESSURE monitor a real signal (`kern.memorystatus_vm_pressure_level`)
rather than a byte watermark — the same capture showed 82% used with AM's pressure graph GREEN.
+ **Code DONE 2026-10-19** — a separate darwin kernel-level leg in `core/memory-pressure.ts`
+ (`onKernelPressure`): renderer levers on escalations into warn/critical only, never on a held
+ level, never through `hostMemReader`, no reaper sweep on kernel CRITICAL yet (#211). Owed: a
+ firing log under induced pressure on a dev build (`memory_pressure -S -l warn`), plus the GPU
+ process `footprint` / IOSurface count before and 60 s after the lever run.
RE-VERIFIED independently 2026-08-12 (second session, shipping function imported via esbuild
bundle, vm_stat captured on the same tick as an AM screenshot): ours 18.87 GB used vs AM's
parts 7.23 + 2.99 + 8.66 = 18.88 GB — 0.05% off; AM's HEADLINE "Memory Used" was 19.70 GB,
diff --git a/src/core/memory-pressure.test.ts b/src/core/memory-pressure.test.ts
index b78ce8b43..9ab3be7b9 100644
--- a/src/core/memory-pressure.test.ts
+++ b/src/core/memory-pressure.test.ts
@@ -1,5 +1,13 @@
import { describe, it, expect, vi } from 'vitest'
-import { createMemoryPressureMonitor, hostMemReader } from './memory-pressure'
+import {
+ createMemoryPressureMonitor,
+ hostMemReader,
+ kernelPressureReader,
+ parseKernelPressureLevel,
+ RE_FIRE_FLOOR_MS,
+ type KernelLevelExec,
+ type KernelPressureLevel
+} from './memory-pressure'
import { readMemInfo } from './session-budget'
const mem = (availableMb: number, totalMb = 16000) => () => ({ availableMb, totalMb })
@@ -86,3 +94,209 @@ describe('memory pressure monitor', () => {
vi.useRealTimers()
})
})
+
+describe('memory pressure monitor: darwin kernel-level leg', () => {
+ /** A scripted kernel reader: each tick consumes the next level; the last one is held. */
+ const script = (levels: (KernelPressureLevel | null)[]) => {
+ let i = 0
+ return (): KernelPressureLevel | null => levels[Math.min(i++, levels.length - 1)]
+ }
+ // Host + self legs quiet, so every fire below is the kernel leg's.
+ const quiet = { readMem: () => null, selfRssMb: () => 100, intervalMs: 1000, log: () => {} }
+
+ it('parses the sysctl integers and nothing else', () => {
+ expect(parseKernelPressureLevel('1\n')).toBe('normal')
+ expect(parseKernelPressureLevel('2')).toBe('warn')
+ expect(parseKernelPressureLevel(' 4 \n')).toBe('critical')
+ for (const junk of ['0', '3', '', 'error', '12']) expect(parseKernelPressureLevel(junk)).toBeNull()
+ })
+
+ it('fires once per ESCALATION, never on a held or falling level', () => {
+ vi.useFakeTimers()
+ const onKernel = vi.fn()
+ const onPressure = vi.fn()
+ // The extra tick primed at start() consumes the first entry.
+ const m = createMemoryPressureMonitor({
+ ...quiet,
+ onPressure,
+ readKernelLevel: script(['normal', 'normal', 'warn', 'warn', 'critical', 'warn', 'normal', 'warn']),
+ onKernelPressure: onKernel
+ })
+ m.start()
+ vi.advanceTimersByTime(7000)
+ expect(onKernel.mock.calls).toEqual([['warning'], ['critical'], ['warning']])
+ expect(onPressure).not.toHaveBeenCalled()
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('a HELD warn stays one lever run past the 60 s re-fire floor (#179: no timed release)', () => {
+ vi.useFakeTimers()
+ const onKernel = vi.fn()
+ const m = createMemoryPressureMonitor({ ...quiet, onPressure: vi.fn(), readKernelLevel: () => 'warn', onKernelPressure: onKernel })
+ m.start()
+ vi.advanceTimersByTime(RE_FIRE_FLOOR_MS * 10)
+ expect(onKernel).toHaveBeenCalledTimes(1)
+ expect(m.kernelLevel()).toBe('warn')
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('a failed read neither fires nor resets the held level', () => {
+ vi.useFakeTimers()
+ const onKernel = vi.fn()
+ const m = createMemoryPressureMonitor({
+ ...quiet,
+ onPressure: vi.fn(),
+ readKernelLevel: script([null, 'warn', null, null, 'warn']),
+ onKernelPressure: onKernel
+ })
+ m.start()
+ vi.advanceTimersByTime(5000)
+ expect(onKernel).toHaveBeenCalledTimes(1)
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('a launch into an already-pressured machine fires on the first tick; a healthy one stays silent', () => {
+ vi.useFakeTimers()
+ const hot = vi.fn()
+ const cold = vi.fn()
+ const a = createMemoryPressureMonitor({ ...quiet, onPressure: vi.fn(), readKernelLevel: () => 'critical', onKernelPressure: hot })
+ const b = createMemoryPressureMonitor({ ...quiet, onPressure: vi.fn(), readKernelLevel: () => 'normal', onKernelPressure: cold })
+ a.start()
+ b.start()
+ vi.advanceTimersByTime(1000)
+ expect(hot.mock.calls).toEqual([['critical']])
+ vi.advanceTimersByTime(600_000)
+ expect(cold).not.toHaveBeenCalled()
+ a.stop()
+ b.stop()
+ vi.useRealTimers()
+ })
+
+ it('never reaches onPressure, so a kernel CRITICAL cannot trigger the shells\' reaper sweep', () => {
+ vi.useFakeTimers()
+ const onPressure = vi.fn()
+ const m = createMemoryPressureMonitor({ ...quiet, onPressure, readKernelLevel: () => 'critical', onKernelPressure: vi.fn() })
+ m.start()
+ vi.advanceTimersByTime(120_000)
+ expect(onPressure).not.toHaveBeenCalled()
+ // …and the byte/self classification is untouched by it.
+ expect(m.check()).toBeNull()
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('runs beside the watermark leg without either suppressing the other', () => {
+ vi.useFakeTimers()
+ const onPressure = vi.fn()
+ const onKernel = vi.fn()
+ const m = createMemoryPressureMonitor({
+ ...quiet,
+ selfRssMb: () => 9000,
+ onPressure,
+ readKernelLevel: () => 'warn',
+ onKernelPressure: onKernel
+ })
+ m.start()
+ vi.advanceTimersByTime(1000)
+ expect(onPressure.mock.calls).toEqual([['critical']])
+ expect(onKernel.mock.calls).toEqual([['warning']])
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('logs every transition (falls included) and every lever run', () => {
+ vi.useFakeTimers()
+ const log = vi.fn()
+ const m = createMemoryPressureMonitor({
+ ...quiet,
+ log,
+ onPressure: vi.fn(),
+ readKernelLevel: script(['normal', 'warn', 'normal']),
+ onKernelPressure: vi.fn()
+ })
+ m.start()
+ vi.advanceTimersByTime(3000)
+ expect(log.mock.calls.map((c) => c[0])).toEqual([
+ '[memory-pressure] kernel level normal -> warn',
+ '[memory-pressure] kernel warn: running reclaim levers (warning)',
+ '[memory-pressure] kernel level warn -> normal'
+ ])
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ it('a throwing kernel consumer does not break the monitor', () => {
+ vi.useFakeTimers()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ let calls = 0
+ const m = createMemoryPressureMonitor({
+ ...quiet,
+ onPressure: vi.fn(),
+ readKernelLevel: script(['normal', 'warn', 'normal', 'critical']),
+ onKernelPressure: () => {
+ calls++
+ throw new Error('destroyed window')
+ }
+ })
+ m.start()
+ expect(() => vi.advanceTimersByTime(3000)).not.toThrow()
+ expect(calls).toBe(2)
+ m.stop()
+ warn.mockRestore()
+ vi.useRealTimers()
+ })
+
+ it('the leg is off without an onKernelPressure consumer (the Server Edition passes none)', () => {
+ vi.useFakeTimers()
+ const read = vi.fn((): KernelPressureLevel => 'critical')
+ const m = createMemoryPressureMonitor({ ...quiet, onPressure: vi.fn(), readKernelLevel: read })
+ m.start()
+ vi.advanceTimersByTime(5000)
+ expect(read).not.toHaveBeenCalled()
+ m.stop()
+ vi.useRealTimers()
+ })
+
+ describe('kernelPressureReader', () => {
+ it('is absent off darwin', () => {
+ expect(kernelPressureReader('linux')).toBeNull()
+ expect(kernelPressureReader('win32')).toBeNull()
+ })
+ it('returns the last LANDED reading and keeps one read in flight at most', () => {
+ const pending: ((err: Error | null, out: string) => void)[] = []
+ const exec: KernelLevelExec = (cb) => void pending.push(cb)
+ const read = kernelPressureReader('darwin', exec)!
+ expect(read()).toBeNull() // nothing landed yet
+ expect(read()).toBeNull()
+ expect(pending).toHaveLength(1) // second call did not spawn a second sysctl
+ pending.shift()!(null, '2\n')
+ expect(read()).toBe('warn')
+ pending.shift()!(new Error('timeout'), '')
+ expect(read()).toBeNull() // a failed read is no information, not a level
+ })
+ it('a spawn that throws synchronously is a failed read', () => {
+ const read = kernelPressureReader('darwin', () => {
+ throw new Error('EAGAIN')
+ })!
+ expect(read()).toBeNull()
+ expect(read()).toBeNull()
+ })
+ // darwin only: kern.memorystatus_vm_pressure_level exists nowhere else.
+ it.skipIf(process.platform !== 'darwin')(
+ 'reads the real sysctl on macOS (read-only; asserts a parsed level, not which one)',
+ async () => {
+ const read = kernelPressureReader('darwin')!
+ let level = read()
+ for (let i = 0; i < 40 && level === null; i++) {
+ await new Promise((r) => setTimeout(r, 50))
+ level = read()
+ }
+ // Every supported macOS has this sysctl; null here means the parse or the argv is wrong.
+ expect(['normal', 'warn', 'critical']).toContain(level)
+ }
+ )
+ })
+})
diff --git a/src/core/memory-pressure.ts b/src/core/memory-pressure.ts
index 98fbb82c0..ad4794ce6 100644
--- a/src/core/memory-pressure.ts
+++ b/src/core/memory-pressure.ts
@@ -4,6 +4,23 @@
// own RSS, because the host signal alone can't tell you YOU are the problem.
// Consumers hang reclaim levers off onPressure; all levers must be idempotent — the monitor
// re-fires a held severity at most once per RE_FIRE_FLOOR_MS.
+//
+// A THIRD leg, darwin only: the kernel's own pressure level (`kern.memorystatus_vm_pressure_level`,
+// the number Activity Monitor's pressure graph colours). With the host leg silent there and main's
+// RSS at 63-200 MB against a 4096 MB threshold, the two legs above never fire on macOS, so the
+// renderer's reclaim levers (`releaseAllHiddenGrants` + the park drop) never ran while the window
+// was visible — #179 removed the timed hidden-context release on the promise that these would.
+// Measured (2026-10 GPU audit, dev build): the lever pair on 12 hidden warm terminals took the GPU
+// process footprint 331 → 152 MB and IOSurface 235 → 91 MB; panning back re-granted all 12.
+// This leg is deliberately NOT part of check()/onPressure:
+// - it fires on TRANSITIONS into warn/critical only, never on a held level. The 60 s re-fire
+// floor above at a held WARN (which a Mac can sit in for hours) would be #179's timed release
+// again, pan-back flicker included;
+// - it never goes through hostMemReader/MemInfo, which the reaper's planReap shares — a kernel
+// WARN must not become a byte watermark the reaper culls detached sessions on (#135/#136/#137);
+// - it reports through its own callback, so a shell decides separately whether a kernel CRITICAL
+// also sweeps the reaper. Neither shell does yet: that step is to be measured on its own (#211).
+import { execFile } from 'child_process'
import { hostMemReader, type MemInfo } from './session-budget'
export { hostMemReader }
@@ -15,12 +32,77 @@ export const RE_FIRE_FLOOR_MS = 60_000
export const SELF_RSS_WARN_MB = 4096
export const SELF_RSS_CRIT_MB = 8192
+/** macOS's own pressure level, as `kern.memorystatus_vm_pressure_level` reports it. */
+export type KernelPressureLevel = 'normal' | 'warn' | 'critical'
+
+/** sysctl's answer is a single integer: 1 normal, 2 warn, 4 critical (the kernel's
+ * `kVMPressure*` values). Anything else — 0, empty, junk — is "could not read", never a level. */
+export function parseKernelPressureLevel(stdout: string): KernelPressureLevel | null {
+ switch (stdout.trim()) {
+ case '1':
+ return 'normal'
+ case '2':
+ return 'warn'
+ case '4':
+ return 'critical'
+ default:
+ return null
+ }
+}
+
+const KERNEL_RANK: Record<KernelPressureLevel, number> = { normal: 0, warn: 1, critical: 2 }
+
+export type KernelLevelExec = (cb: (err: Error | null, stdout: string) => void) => void
+
+const sysctlPressureLevel: KernelLevelExec = (cb) => {
+ execFile('sysctl', ['-n', 'kern.memorystatus_vm_pressure_level'], { timeout: 5_000 }, (err, stdout) =>
+ cb(err, String(stdout))
+ )
+}
+
+/**
+ * The kernel-level reader: synchronous to its caller, asynchronous underneath, in the
+ * `pty-devices.ts` primePtyCeiling pattern — each call returns the last reading that LANDED and
+ * kicks one background `sysctl` (never two in flight). The monitor calls it once per 30 s tick, so
+ * that is one tiny subprocess per tick, the same cost class as the RAM pill's 30 s host read; a
+ * transition is therefore seen at most one tick late, which is fine for a lever that frees idle
+ * warmth. Closure state, not module state, so tests (and two monitors) never share a cache.
+ *
+ * Off darwin there is no such sysctl, so the reader is absent (`null`) and the leg does not exist.
+ * A failed or unparseable read lands as `null` — no information, never pressure.
+ */
+export function kernelPressureReader(
+ platform: NodeJS.Platform = process.platform,
+ exec: KernelLevelExec = sysctlPressureLevel
+): (() => KernelPressureLevel | null) | null {
+ if (platform !== 'darwin') return null
+ let last: KernelPressureLevel | null = null
+ let inFlight = false
+ return () => {
+ if (!inFlight) {
+ inFlight = true
+ try {
+ exec((err, stdout) => {
+ inFlight = false
+ last = err ? null : parseKernelPressureLevel(stdout)
+ })
+ } catch {
+ inFlight = false // a spawn that throws synchronously is a failed read, not a crash
+ last = null
+ }
+ }
+ return last
+ }
+}
+
export interface MemoryPressureMonitor {
start(): void
stop(): void
/** One classification pass; null = no pressure (including "could not read"). */
check(): PressureSeverity | null
+ /** The kernel leg's held level (darwin); `normal` until a reading says otherwise. */
+ kernelLevel(): KernelPressureLevel
}
export function createMemoryPressureMonitor(opts: {
@@ -28,13 +110,30 @@ export function createMemoryPressureMonitor(opts: {
selfRssMb?: () => number
intervalMs?: number
onPressure: (s: PressureSeverity) => void
+ /** The kernel-level reader; defaults to `kernelPressureReader()` (absent off darwin). `null`
+ * switches the leg off. */
+ readKernelLevel?: (() => KernelPressureLevel | null) | null
+ /** Fired once per ESCALATION of the kernel level (normal→warn, →critical), never on a held or
+ * falling level. No callback ⇒ the leg is not sampled at all. */
+ onKernelPressure?: (s: PressureSeverity) => void
+ log?: (m: string) => void
}): MemoryPressureMonitor {
const readMem = opts.readMem ?? hostMemReader()
+ const readKernel =
+ opts.onKernelPressure === undefined
+ ? null
+ : opts.readKernelLevel === undefined
+ ? kernelPressureReader()
+ : opts.readKernelLevel
+ const log = opts.log ?? ((m: string): void => console.log(m))
// `memoryUsage.rss()` reads just the one number; `memoryUsage()` builds the whole stats object
// (heap walk included) every 30 s for a field we throw away.
const selfRss = opts.selfRssMb ?? ((): number => Math.round(process.memoryUsage.rss() / 1048576))
let timer: ReturnType<typeof setInterval> | null = null
let lastFired = 0
+ // Starting at `normal` is what makes a healthy Mac silent (no transition to report) and what
+ // makes a launch INTO an already-pressured machine fire once.
+ let kernelHeld: KernelPressureLevel = 'normal'
const check = (): PressureSeverity | null => {
const rss = selfRss()
@@ -47,11 +146,36 @@ export function createMemoryPressureMonitor(opts: {
return null
}
+ const kernelTick = (): void => {
+ if (!readKernel || !opts.onKernelPressure) return
+ const level = readKernel()
+ // A failed read is no information: it neither fires nor resets the held level, so a
+ // warn → (failed read) → warn sequence is still ONE lever run.
+ if (level === null || level === kernelHeld) return
+ const from = kernelHeld
+ kernelHeld = level
+ log(`[memory-pressure] kernel level ${from} -> ${level}`)
+ // Escalations only. A falling level runs nothing: the levers already ran on the way up, and
+ // whatever has re-granted since is warmth the user just panned back to.
+ if (KERNEL_RANK[level] <= KERNEL_RANK[from]) return
+ const severity: PressureSeverity = level === 'critical' ? 'critical' : 'warning'
+ log(`[memory-pressure] kernel ${level}: running reclaim levers (${severity})`)
+ try {
+ opts.onKernelPressure(severity)
+ } catch (e) {
+ console.warn('[memory-pressure] onKernelPressure threw', e)
+ }
+ }
+
return {
check,
+ kernelLevel: () => kernelHeld,
start(): void {
if (timer) return
+ // Prime the reader so the first tick compares a real reading, not the empty cache.
+ readKernel?.()
timer = setInterval(() => {
+ kernelTick()
const s = check()
if (!s) return
const now = Date.now()
diff --git a/src/core/session-budget.ts b/src/core/session-budget.ts
index 6a62a8ca9..c4fcd32d1 100644
--- a/src/core/session-budget.ts
+++ b/src/core/session-budget.ts
@@ -408,8 +408,11 @@ export function parseSessionList(stdout: string): SessionInfo[] {
* critical one sweeps the reaper: we would cull sessions on a machine macOS says is fine. That is
* the same class of mistake as the bug this started with, reached from the other direction.
*
- * Follow-up (unchanged in shape, sharper in target): give this leg macOS's REAL pressure signal —
- * `kern.memorystatus_vm_pressure_level`, or the `memory_pressure` tool — rather than a byte count.
+ * That follow-up is now a SEPARATE leg, not this one: memory-pressure.ts reads macOS's real signal,
+ * `kern.memorystatus_vm_pressure_level`, through its own reader and its own callback, and fires the
+ * renderer's reclaim levers on escalations only. It deliberately does not come back through here:
+ * `planReap` shares this reader, so a kernel level fed in as a MemInfo would hand the reaper a new
+ * cull trigger. Keep this `null` on darwin.
*/
export function hostMemReader(platform: NodeJS.Platform = process.platform): () => MemInfo | null {
return platform === 'darwin' ? (): null => null : readMemInfo
diff --git a/src/main/index.ts b/src/main/index.ts
index d8348a63c..6a4214bd1 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3536,11 +3536,17 @@ app.whenReady().then(async () => {
// 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.
+ //
+ // The kernel leg (macOS only — absent elsewhere) is the one that actually fires there: the byte
+ // leg is silent on darwin and main's RSS never nears 4 GB. It runs the renderer levers ONLY, once
+ // per escalation of `kern.memorystatus_vm_pressure_level`; a kernel CRITICAL deliberately does
+ // NOT sweep the reaper yet — that is a separate, separately measured step (#211).
createMemoryPressureMonitor({
onPressure: (severity) => {
sendToMain(IPC.appMemoryPressure, severity)
if (severity === 'critical') void sessionReaper.sweep()
- }
+ },
+ onKernelPressure: (severity) => sendToMain(IPC.appMemoryPressure, severity)
}).start()
// Pty-device pressure (core/pty-pressure.ts): the OTHER way this machine runs out, and the one
// that actually happened. The memory monitor above could not see it — during the 2026-08-11