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.

fix(core): read macOS memory from vm_stat — os.freemem() reads ~0 there

enes306788951086
diff --git a/docs/session-memory.md b/docs/session-memory.md
index bfbdcec9d..d6a347dc3 100644
--- a/docs/session-memory.md
+++ b/docs/session-memory.md
@@ -126,6 +126,31 @@ pane's *shell*, so a claude session with two MCP servers reports **3**. The pane
`list-panes -a` emits one line per **pane**, so the first pane of a session wins in both legs (same
key, same order) — one session is one row.
+### macOS reads `vm_stat`, not `os.freemem()`
+
+libuv's `os.freemem()` counts only genuinely FREE pages, and a healthy Mac keeps that near zero on
+purpose — file-backed and purgeable pages are held until something needs them. So `total - free`
+renders every Mac at ~100% used. Observed in the field: a 24 GB Mac reporting **23.9 / 24.0 GB**
+while the panel's sessions summed to 2.8 GB.
+
+`parseVmStat` computes what Activity Monitor calls Memory Used —
+`anonymous - purgeable + wired + compressor` — and treats the rest as available. It is an
+**approximation of Activity Monitor, not a reproduction**: Apple documents no exact figure, and on
+Apple Silicon the parts are known not to sum to its total.
+
+**The page size is read from `vm_stat`'s own header, never assumed.** Apple Silicon uses 16 KiB
+pages; hard-coding 4096 would report a quarter of real usage — the identical mistake this file
+already fixed on the Linux side, where `statm` tempted the same constant.
+
+**This also fixed the reaper, which is why the change lives in `readMemInfo` rather than in the
+pill.** `sessionBudgetConfig`'s watermark defaults to 10% of RAM (2457 MB on a 24 GB machine), and
+`os.freemem()` sat permanently below it — so `planReap` saw memory pressure on EVERY sweep and a Mac
+reaped idle detached sessions every 10 minutes regardless of how much memory was actually free. One
+reader, two consumers: that is the reason they share a definition.
+
+**Unverified:** the fixture in `session-memory.test.ts` is composed from Apple's documented format,
+not captured from a real machine. Device checklist item 6 is what closes it.
+
## 6. The SSH leg
An SSH project's sessions live on the host, so the sweep runs there: core generates ONE POSIX `sh`
@@ -364,7 +389,8 @@ macOS (the ps path never runs on Linux)
5. Open the panel on a Mac: `defaultProcessTableReader` returns null there, so the whole table
comes from `ps -eo pid,ppid,rss`. Rows must populate, and the totals must be plausible — BSD ps
reports rss in kB, but confirm one known process against Activity Monitor before trusting it.
- 6. macOS pill numbers: `os.freemem()` reports FREE, not AVAILABLE, memory. Confirm used/total reads
+ 6. macOS: capture real `vm_stat` output and check `parseVmStat` against Activity Monitor's Memory
+ Used (the fixture is COMPOSED, not captured). Confirm the pill's used/total reads
plausibly rather than alarmingly (a Mac with a big page cache will look fuller than it is).
The SSH leg
diff --git a/src/core/session-memory.test.ts b/src/core/session-memory.test.ts
index 357174f57..af54ffd9b 100644
--- a/src/core/session-memory.test.ts
+++ b/src/core/session-memory.test.ts
@@ -236,3 +236,59 @@ describe('collectSessionMemory', () => {
}
})
})
+
+import { parseVmStat } from './session-memory'
+
+/** Shaped from Apple's documented `vm_stat` format, at a 16 KiB page (Apple Silicon). COMPOSED, not
+ * captured — nobody in this loop has a Mac. Numbers chosen so the arithmetic is checkable by hand:
+ * anonymous 800k - purgeable 50k + wired 150k + compressor 100k = 1,000,000 pages.
+ * 1,000,000 x 16384 B = 15625 MiB used of a 24576 MiB machine, i.e. 8951 MiB available. */
+const VM_STAT = [
+ 'Mach Virtual Memory Statistics: (page size of 16384 bytes)',
+ 'Pages free: 50000.',
+ 'Pages active: 600000.',
+ 'Pages inactive: 400000.',
+ 'Pages speculative: 30000.',
+ 'Pages throttled: 0.',
+ 'Pages wired down: 150000.',
+ 'Pages purgeable: 50000.',
+ '"Translation faults": 987654321.',
+ 'Pages occupied by compressor: 100000.',
+ 'File-backed pages: 700000.',
+ 'Anonymous pages: 800000.'
+].join('\n')
+
+const TOTAL_BYTES = 24576 * 1048576
+
+describe('parseVmStat', () => {
+ it('reports app+wired+compressed as used, not the near-zero free page count', () => {
+ // The bug this exists for: `Pages free` is 50000 (≈781 MiB) on a machine with 8.4 GiB genuinely
+ // available, because macOS holds the rest as reclaimable cache.
+ expect(parseVmStat(VM_STAT, TOTAL_BYTES)).toEqual({ availableMb: 8951, totalMb: 24576 })
+ })
+
+ it('reads the page size from the header rather than assuming 4096', () => {
+ // Same class as the Linux statm bug: a hard-coded 4096 would report a QUARTER of the real usage
+ // on Apple Silicon, i.e. an alarmingly empty machine.
+ const fourK = parseVmStat(VM_STAT.replace('16384 bytes', '4096 bytes'), TOTAL_BYTES)
+ // 1,000,000 x 4096 B = 3906 MiB, so the machine would read 5044 MiB emptier than it is.
+ expect(fourK).toEqual({ availableMb: 20670, totalMb: 24576 })
+ })
+
+ it('subtracts purgeable pages from anonymous — they are droppable cache, not app memory', () => {
+ const noPurge = parseVmStat(VM_STAT.replace(/Pages purgeable:.*\n/, ''), TOTAL_BYTES)
+ // Without the subtraction the machine reads 50000 pages (781 MiB) fuller than it is.
+ expect(noPurge?.availableMb).toBe(8951 - 781)
+ })
+
+ it('returns null when a field it needs is missing, rather than a partial number', () => {
+ expect(parseVmStat(VM_STAT.replace(/Pages wired down:.*\n/, ''), TOTAL_BYTES)).toBeNull()
+ expect(parseVmStat('not vm_stat output', TOTAL_BYTES)).toBeNull()
+ expect(parseVmStat(VM_STAT, 0)).toBeNull()
+ })
+
+ it('never reports negative availability on a heavily compressed machine', () => {
+ const tiny = parseVmStat(VM_STAT, 1024 * 1048576)
+ expect(tiny?.availableMb).toBe(0)
+ })
+})
diff --git a/src/core/session-memory.ts b/src/core/session-memory.ts
index 3213626db..fd1dc91a6 100644
--- a/src/core/session-memory.ts
+++ b/src/core/session-memory.ts
@@ -10,7 +10,7 @@
import fs from 'fs'
import os from 'os'
-import { execFile } from 'child_process'
+import { execFile, execFileSync } from 'child_process'
import { promisify } from 'util'
import type { MemInfo, SessionMemoryRow, SessionMemoryReport } from '../shared/types'
import { TMUX_SOCKET } from './tmux-naming'
@@ -105,6 +105,48 @@ export function parseProcessTable(stdout: string): ProcEntry[] {
*
* Lives here rather than in session-budget.ts because two features now read it (the reaper's
* watermark and the system-resource pill) and a second copy would drift. */
+/**
+ * Parse `vm_stat` into the same MemInfo shape, given the machine's total bytes.
+ *
+ * macOS deliberately keeps almost nothing "free": file-backed and purgeable pages are held until
+ * something needs them, so libuv's `os.freemem()` — which counts only genuinely free pages —
+ * reports near zero on a healthy Mac. `total - free` therefore renders every Mac as ~100% full,
+ * which is both useless and alarming. (It also pinned the session reaper's watermark permanently
+ * below its threshold, so a Mac reaped idle detached sessions on every sweep regardless of memory.)
+ *
+ * The number Activity Monitor calls "Memory Used" is app + wired + compressed, i.e.
+ * `anonymous - purgeable + wired + compressor`; everything else is reclaimable and counts as
+ * available. This is an approximation of Activity Monitor, not a reproduction of it — Apple does not
+ * document the exact figure, and on Apple Silicon the parts are known not to sum to its total.
+ *
+ * The page size is READ FROM THE HEADER, never assumed: Apple Silicon uses 16 KiB pages, and
+ * hard-coding 4096 is the identical bug this file already fixed on the Linux side.
+ */
+export function parseVmStat(text: string, totalBytes: number): MemInfo | null {
+ const pageSize = Number(/page size of (\d+) bytes/.exec(text)?.[1])
+ if (!Number.isFinite(pageSize) || pageSize <= 0 || !Number.isFinite(totalBytes) || totalBytes <= 0) {
+ return null
+ }
+ const pages = (label: string): number | null => {
+ const m = new RegExp(`^${label}:\\s+(\\d+)\\.`, 'm').exec(text)
+ return m ? Number(m[1]) : null
+ }
+ const anonymous = pages('Anonymous pages')
+ const wired = pages('Pages wired down')
+ const compressor = pages('Pages occupied by compressor')
+ // `Pages purgeable` is a SUBSET of anonymous — caches an app has volunteered as droppable.
+ const purgeable = pages('Pages purgeable') ?? 0
+ // A missing field means we are not looking at vm_stat output we understand. Report nothing rather
+ // than a number built from a partial read — the pill pulses, which is the honest answer.
+ if (anonymous === null || wired === null || compressor === null) return null
+
+ const usedBytes = (Math.max(0, anonymous - purgeable) + wired + compressor) * pageSize
+ const totalMb = Math.round(totalBytes / 1048576)
+ // Clamp: the parts are an approximation and can exceed the total on a heavily compressed system.
+ const availableMb = Math.max(0, totalMb - Math.round(usedBytes / 1048576))
+ return { availableMb, totalMb }
+}
+
export function readMemInfo(): MemInfo | null {
try {
const text = fs.readFileSync('/proc/meminfo', 'utf8')
@@ -119,6 +161,20 @@ export function readMemInfo(): MemInfo | null {
} catch {
// fall through to the os fallback
}
+ // macOS: `os.freemem()` counts only genuinely free pages, which a healthy Mac keeps near zero —
+ // see parseVmStat. Ask the kernel for the real breakdown instead. Sync on purpose: both callers
+ // (the 30 s pill poll and the reaper's 10 min sweep) are far apart, and keeping ONE signature
+ // means the reaper's watermark is fixed by the same change.
+ if (process.platform === 'darwin') {
+ try {
+ const out = execFileSync('vm_stat', { encoding: 'utf8', timeout: 5_000 })
+ const parsed = parseVmStat(out, os.totalmem())
+ if (parsed) return parsed
+ } catch {
+ // vm_stat missing or unreadable — fall through to the generic reader below, which is wrong on
+ // macOS but is still better than reporting nothing at all.
+ }
+ }
try {
return {
availableMb: Math.round(os.freemem() / 1048576),