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(session-memory): "nodeterm itself" in the panel, swap and kernel pressure in the RAM pill
Brandon Bridges1f4da8f32578
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2388337d3..f98b2dd0d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -6498,6 +6498,25 @@ about which machine they describe. Reading + parsing is `core/session-memory.ts`re-exports it. The reaper's watermark and the pill must never disagree about how much RAM is free,and a second copy is exactly the drift this file warns about elsewhere. `null` = could not read,never zero.+- **The pill's swap figure and kernel-pressure tint live in `MemInfo.display`, and nothing but the+ pill reads it** (audit roadmap #14). darwin: `sysctl vm.swapusage` and+ `kern.memorystatus_vm_pressure_level` (1/2/4 → normal/warn/critical), each a separate optional+ read inside `darwinMemInfo`; Linux: copied from the same `/proc/meminfo` text. **Never fill+ `swapTotalMb`/`swapFreeMb` on darwin** — `hostUnderMemoryPressure` reads them, and a Mac keeps+ its swap ~85% used while healthy (the audited one: 7.7 of 9 GB, level flapping 1↔2), so the+ reaper's swap term would fire all day. The level only RAISES the used-% tint, never lowers it;+ a failed read omits its field (no "0 GB swap"). Not an input to the reaper, the pressure monitor+ or any lever — that is a separate, measured change.+- **"nodeterm itself" is a separate group, never a session row and never in the header total**+ (`SessionMemoryReport.app`, audit roadmap #4). The GPU helper's footprint was 1557-1845 MB while+ `ps` rss said 96-153 MB, and no surface attributed it. The desktop shell injects+ `appProcesses` from `app.getAppMetrics()` for **pid, type and `cumulativeCPUUsage` only**: on+ macOS `memory.workingSetSize` is resident size (blind to IOSurfaces, like rss) and+ `privateBytes` is Windows-only, so memory comes from the sweep's OWN table — `top`'s footprint+ on darwin (`ProcEntry.footprint`; a pid `top` missed is "not measured", never its rss), VmRSS on+ Linux, working set on Windows. No second `top` (~0.5 s each). CPU is lifetime CPU TIME, not a+ rate: `percentCPUUsage` answers 0 on its first call. Local scope only; absent = not available+ (Server Edition, SSH, relay); `ok:false` = tried and could not, rendered as such.- **The local reader reads `/proc/<pid>/status`, never `statm`.** `status` carries `PPid` and `VmRSS`in one file, already in kB; `statm` reports RSS in **pages**, forcing a page-size assumption — ahard-coded 4096 under-reports **4×** on a 16 KiB-page arm64 kernel and **16×** on the 64 KiB-pagediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex adf7b9942..796c7c4dc 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1363,6 +1363,14 @@ on a file it has no loader for). No CI job builds the server bundle, but`src/server/server-build.test.ts` builds it in both views and goes red. The server runs from a`node_modules` tree, so an external is resolved at runtime.+**Session memory's display-only figures stay display-only.** The RAM pill's swap and kernel-pressure+tint live in `MemInfo.display`, which the reaper and the pressure monitor never read; never fill+`swapTotalMb`/`swapFreeMb` on darwin (a healthy Mac keeps swap ~85% used, so the reaper's swap term+would fire all day). The panel's "nodeterm itself" group takes pids/types/CPU time from+`app.getAppMetrics()` but memory from the sweep's own table (`top` footprint on macOS) — never+`workingSetSize`, which on macOS misses the GPU helper's IOSurfaces (≈1.6 GB footprint vs ≈120 MB+rss). It is local-only and never part of the session total. CLAUDE.md, Session memory.+## Testing**Run the suite with a scratch `HOME`, and know what else points at your real config.** The workerdiff --git a/docs/session-memory.md b/docs/session-memory.mdindex 10a065fde..810386818 100644--- a/docs/session-memory.md+++ b/docs/session-memory.md@@ -261,6 +261,47 @@ machine read **23.9 / 24.0 GB**.The test fixture remains composed from Apple's documented format; what is verified is the FORMULAagainst a real machine, not that fixture's specific numbers.+### Swap and kernel pressure in the pill (display only)++Added from the 2026-10-19 performance audit (roadmap #14). The pill said 86% "warn" while 8.5 GB+were swapped and the kernel sat at pressure level 2, and nothing on screen said either.++- **Where.** `MemInfo.display` — `swapUsedMb`, `swapTotalMb`, `pressureLevel`. darwin reads+ `sysctl vm.swapusage` (`total = 9216.00M used = 7853.62M free = 1362.38M (encrypted)`, parsed by+ `parseSwapUsage`; K/M/G only) and `kern.memorystatus_vm_pressure_level` (`parsePressureLevel`:+ 1 normal, 2 warn, 4 critical, anything else omitted). Each is its own optional read in+ `darwinMemInfo`; a failure omits that one field and leaves the `vm_stat` reading untouched. Linux+ copies its swap from the `/proc/meminfo` text already parsed. Linux has no kernel level; PSI is+ not mapped to one because no threshold has been measured.+- **Why a sub-object.** `hostUnderMemoryPressure` reads `swapTotalMb`/`swapFreeMb`. Filling those on+ darwin would turn a healthy Mac (16% swap free on the audited one) into permanent "pressure" for the+ reaper. The pill reads only `display`; nothing else does.+- **The tint.** `max(used-% threshold, kernel level)`: the level can raise the colour, never lower it.+- **No fake zero.** No `display` → no swap text. A measured 0 used is stated in the title only.+- **Owed.** Pill vs `sysctl vm.swapusage` and Activity Monitor's pressure colour over a day.++### "nodeterm itself" in the panel++Roadmap #4 of the same audit. The GPU helper's real footprint was 1557-1845 MB (window swap chain,+raster tiles, terminal WebGL buffers, driver memory) while `ps` rss said 96-153 MB; the pill counted+it in the host total, but the panel never attributed it.++- **Data.** The desktop shell injects `appProcesses` (`app.getAppMetrics()` → pid, type,+ `cumulativeCPUUsage`). Memory is looked up per pid in the sweep's own process table, so the group+ uses the rows' accounting with no second `top`: footprint on darwin (only for pids `top` covered,+ `ProcEntry.footprint`), VmRSS on Linux, working set on Windows. `getAppMetrics().memory` is not+ used: on macOS `workingSetSize` is resident size and `privateBytes` is Windows-only.+- **Groups.** Browser → main, Tab → renderer (the HUD is a second one), GPU → gpu, everything else+ → helpers. A group with an unmeasured pid has no MB; the group total exists only when every group+ has one.+- **States.** Absent = this surface cannot enumerate its processes (Server Edition, SSH, relay):+ nothing drawn. `ok:false` = it tried and could not: "Could not measure nodeterm's own processes."+ Never in the header total, never a row, local scope only.+- **CPU** is lifetime CPU time per group, not a percentage (`percentCPUUsage` returns 0 on its+ first call, and the sweep takes one sample).+- **Owed.** Panel GPU figure within 5% of `footprint <gpu pid>` and not equal to `ps rss`, on a+ real build.+## 6. The SSH legAn SSH project's sessions live on the host, so the sweep runs there: core generates ONE POSIX `sh`diff --git a/src/core/session-memory-service.test.ts b/src/core/session-memory-service.test.tsindex f543ea6bd..fcd4d3d75 100644--- a/src/core/session-memory-service.test.ts+++ b/src/core/session-memory-service.test.ts@@ -390,3 +390,77 @@ describe('mergeLocalLegs', () => {expect(mergeLocalLegs(r(true, []), r(true, []))).not.toHaveProperty('host')})})++describe('startSessionMemoryService — "nodeterm itself" (roadmap #4)', () => {+ const MEM = { availableMb: 8000, totalMb: 16000 }+ const listing = {+ running: true,+ names: ['nt-a'],+ sessions: [{ name: 'nt-a', pid: 100, subscribers: 0, lastOutputMs: 1, createdMs: 1, generation: 'gen-aaaaaaaa' }]+ }+ // pid 7 is the GPU helper; `footprint` so the darwin rule (top's figure only) is satisfied on a Mac+ // runner too — the Windows table this leg normally reads is working set on every platform.+ const table = async () => [+ { pid: 100, ppid: 1, rssKb: 2048 },+ { pid: 7, ppid: 1, rssKb: 1600 * 1024, footprint: true as const }+ ]+ const appProcesses = () => [{ pid: 7, type: 'GPU', cpuSeconds: 42 }]++ it('a local sweep carries the group, measured from the sweep\'s own table', async () => {+ startSessionMemoryService({+ tmuxBin: () => null,+ readMem: () => MEM,+ sessionHost: async () => listing,+ sessionHostTable: table,+ appProcesses+ })+ const r = await read({ projectId: 'p1' })+ expect(r.app).toEqual({ ok: true, groups: [{ kind: 'gpu', count: 1, mb: 1600, cpuSeconds: 42 }], totalMb: 1600 })+ // Never folded into a session row.+ expect(r.rows.map((x) => x.totalMb)).toEqual([2])+ })++ it('a path that read no table says NOT MEASURED rather than leaving the group out', async () => {+ startSessionMemoryService({+ tmuxBin: () => null,+ readMem: () => MEM,+ sessionHost: async () => ({ running: false, names: [], sessions: [] }),+ appProcesses+ })+ expect((await read({ projectId: 'p1' })).app).toEqual({ ok: false, groups: [] })+ })++ it('no reader injected (Server Edition) → no field: not available, not "could not measure"', async () => {+ startSessionMemoryService({ tmuxBin: () => null, readMem: () => MEM, sessionHost: async () => listing, sessionHostTable: table })+ expect(await read({ projectId: 'p1' })).not.toHaveProperty('app')+ })++ it('an SSH scope never carries this machine\'s processes, and never asks for them', async () => {+ const reader = vi.fn(appProcesses)+ startSessionMemoryService({+ tmuxBin: () => null,+ sessionHost: async () => listing,+ sessionHostTable: table,+ appProcesses: reader,+ remote: { run: async () => HOST_REPLY, isRemoteProject: (id) => id === 'ssh1' }+ })+ const r = await read({ projectId: 'ssh1' })+ expect(r.ok).toBe(true)+ expect(r).not.toHaveProperty('app')+ expect(reader).not.toHaveBeenCalled()+ })++ it('mergeLocalLegs prefers a measured group and never adopts one from a failed leg', () => {+ const measured = { ok: true, groups: [{ kind: 'gpu' as const, count: 1, mb: 5 }], totalMb: 5 }+ const notMeasured = { ok: false, groups: [] }+ const leg = (ok: boolean, app?: SessionMemoryReport['app']): SessionMemoryReport => ({+ ok,+ rows: [],+ mem: null,+ ...(app ? { app } : {})+ })+ expect(mergeLocalLegs(leg(true, notMeasured), leg(true, measured)).app).toEqual(measured)+ expect(mergeLocalLegs(leg(true, notMeasured), leg(true)).app).toEqual(notMeasured)+ expect(mergeLocalLegs(leg(true), leg(false, measured))).not.toHaveProperty('app')+ })+})diff --git a/src/core/session-memory-service.ts b/src/core/session-memory-service.tsindex eeace1a12..7ddd4d923 100644--- a/src/core/session-memory-service.ts+++ b/src/core/session-memory-service.ts@@ -7,7 +7,13 @@import { IPC } from '../shared/ipc'import { platform } from './platform'import type { MemInfo, SessionMemoryQuery, SessionMemoryReport } from '../shared/types'-import { collectSessionHostMemory, collectSessionMemory, readMemInfo, type ProcEntry } from './session-memory'+import {+ collectSessionHostMemory,+ collectSessionMemory,+ readMemInfo,+ type AppProcessReader,+ type ProcEntry+} from './session-memory'import type { SessionHostListing } from './session-host-client'import { fetchRemoteSessionMemory, type RemoteSessionMemoryRunner } from './session-memory-remote'@@ -27,6 +33,13 @@ export interface SessionMemoryServiceOptions {sessionHostTable?: () => Promise<ProcEntry[] | null>/** Host RAM reader, injectable for tests. Defaults to the real `/proc/meminfo` read. */readMem?: () => MemInfo | null+ /**+ * nodeterm's own processes, for the panel's "nodeterm itself" group (audit roadmap #4). Only the+ * desktop shell has them (`app.getAppMetrics()`); the Server Edition omits it, and its reports+ * then carry no `app` — "not available", which is not "could not measure". Consulted for LOCAL+ * sweeps only: an SSH host's report must never include this machine's processes.+ */+ appProcesses?: AppProcessReader/*** The two remote facts, in a deliberately ASYMMETRIC pair: knowing which projects are somebody* else's machine is required, being able to read them is not.@@ -95,6 +108,10 @@ export function mergeLocalLegs(a: SessionMemoryReport, b: SessionMemoryReport):// Only the session-host leg ever carries it; a failed leg's is never adopted.const host = answered.find((r) => r.host)?.hostif (host) out.host = host+ // Prefer a leg that measured it; either leg's table describes this same machine.+ const apps = answered.flatMap((r) => (r.app ? [r.app] : []))+ const app = apps.find((x) => x.ok) ?? apps[0]+ if (app) out.app = appreturn out}@@ -142,11 +159,12 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {const hostLeg = collectSessionHostMemory({list: () => listing,readMem: opts.readMem,- ...(opts.sessionHostTable ? { readTable: opts.sessionHostTable } : {})+ ...(opts.sessionHostTable ? { readTable: opts.sessionHostTable } : {}),+ ...(opts.appProcesses ? { appProcesses: opts.appProcesses } : {})})if (!opts.tmuxBin()) return hostLegconst [tmuxLeg, host] = await Promise.all([- collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem }),+ collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem, appProcesses: opts.appProcesses }),hostLeg])return mergeLocalLegs(tmuxLeg, host)@@ -166,7 +184,7 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {const hostListing = opts.sessionHost?.()const [report, unmeasured] = await Promise.all([hostListing === undefined- ? collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem })+ ? collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem, appProcesses: opts.appProcesses }): collectLocalWithSessionHost(hostListing),opts.unmeasuredSessions ? opts.unmeasuredSessions().catch(() => null) : Promise.resolve(0)])diff --git a/src/core/session-memory.test.ts b/src/core/session-memory.test.tsindex 309462daf..76fc3d797 100644--- a/src/core/session-memory.test.ts+++ b/src/core/session-memory.test.ts@@ -419,6 +419,36 @@ describe('collectSessionMemory on darwin', () => {expect((rows as { selfMb: number }[])[0].selfMb).toBe(Math.round(200000 / 1024))}))++ it(+ 'the "nodeterm itself" group reuses that SAME top read — footprint for a covered pid, nothing for a missed one',+ asDarwin(async () => {+ const calls: string[] = []+ const r = await collectSessionMemory({+ tmuxBin: () => '/usr/bin/tmux',+ sockets: ['s1'],+ exec: async (bin) => {+ calls.push(bin)+ if (bin.includes('tmux')) return 'nt-a|4242|claude\n'+ // 900 = the GPU helper: rss 120 MB. 901 = a renderer top did not list.+ if (bin === 'ps') return 'PID PPID RSS\n4242 1 100000\n900 1 122880\n901 1 307200\n'+ return 'PID MEM \n4242 200000K\n900 1600M\n'+ },+ readTable: undefined,+ readMem: () => null,+ appProcesses: () => [+ { pid: 900, type: 'GPU' },+ { pid: 901, type: 'Tab' }+ ]+ })+ // ONE top for the whole panel, sessions and app together (~0.5 s each, measured).+ expect(calls.filter((c) => c === 'top')).toHaveLength(1)+ expect(r.app?.groups).toEqual([+ { kind: 'gpu', count: 1, mb: 1600 },+ { kind: 'renderer', count: 1 }+ ])+ })+ )})import { parseMemInfoText, parsePsiMemory, readMemInfo } from './session-memory'@@ -445,7 +475,9 @@ describe('parseMemInfoText', () => {availableMb: 13481,totalMb: 64158,swapTotalMb: 8192,- swapFreeMb: 2141+ swapFreeMb: 2141,+ // The pill's copy of the same instant, in the display-only object the reaper never reads.+ display: { swapUsedMb: 8192 - 2141, swapTotalMb: 8192 }})})@@ -520,3 +552,158 @@ describe('readMemInfo on this Linux host (integration)', () => {if (m!.psiFullAvg60 !== undefined) expect(m!.psiFullAvg60).toBeGreaterThanOrEqual(0)})})++import {+ appProcessKind,+ appSelfMemory,+ parsePressureLevel,+ parseSwapUsage,+ type AppProcessSample+} from './session-memory'++/** Captured live on the audited Mac, 2026-10-19 (`sysctl vm.swapusage`). */+const SWAPUSAGE = 'vm.swapusage: total = 9216.00M used = 7853.62M free = 1362.38M (encrypted)\n'++describe('parseSwapUsage (darwin, roadmap #14)', () => {+ it('reads used and total from the live string, prefixed or not', () => {+ expect(parseSwapUsage(SWAPUSAGE)).toEqual({ swapUsedMb: 7854, swapTotalMb: 9216 })+ expect(parseSwapUsage(SWAPUSAGE.replace('vm.swapusage: ', ''))).toEqual({ swapUsedMb: 7854, swapTotalMb: 9216 })+ })++ it('accepts K and G, and passes a real zero through', () => {+ expect(parseSwapUsage('total = 2.00G used = 512.00K free = 1.99G')).toEqual({ swapUsedMb: 1, swapTotalMb: 2048 })+ expect(parseSwapUsage('total = 0.00M used = 0.00M free = 0.00M')).toEqual({ swapUsedMb: 0, swapTotalMb: 0 })+ })++ it('an unknown unit or a missing half yields NOTHING, never a guessed scale or a zero', () => {+ expect(parseSwapUsage('total = 9216.00T used = 1.00M free = 1.00M')).toEqual({})+ expect(parseSwapUsage('total = 9216.00M free = 1.00M')).toEqual({})+ expect(parseSwapUsage('')).toEqual({})+ })+})++describe('parsePressureLevel (darwin, roadmap #14)', () => {+ it('maps xnu levels 1/2/4 and nothing else', () => {+ expect(parsePressureLevel('1')).toBe('normal')+ expect(parsePressureLevel('kern.memorystatus_vm_pressure_level: 2\n')).toBe('warn')+ expect(parsePressureLevel('4')).toBe('critical')+ for (const junk of ['0', '3', '12', '', 'unknown oid', 'kern.memorystatus_vm_pressure_level: 21'])+ expect(parsePressureLevel(junk)).toBeUndefined()+ })+})++describe('darwinMemInfo display extras', () => {+ const sysctl = (answers: Record<string, string | Error>) => (name: string): string => {+ const a = answers[name]+ if (a === undefined || a instanceof Error) throw a ?? new Error(`unknown oid ${name}`)+ return a+ }++ it('adds swap and pressure under `display` and NEVER fills the reaper pair', () => {+ const m = darwinMemInfo(() => VM_STAT, TOTAL_BYTES, sysctl({+ 'vm.swapusage': SWAPUSAGE,+ 'kern.memorystatus_vm_pressure_level': 'kern.memorystatus_vm_pressure_level: 2'+ }))+ expect(m).toEqual({+ availableMb: 8951,+ totalMb: 24576,+ display: { swapUsedMb: 7854, swapTotalMb: 9216, pressureLevel: 'warn' }+ })+ // The reaper's Linux swap term reads these; on this Mac (16% free) it would fire all day.+ expect(m).not.toHaveProperty('swapTotalMb')+ expect(m).not.toHaveProperty('swapFreeMb')+ })++ it('a failed sysctl omits only its own field; both failing leaves the vm_stat reading untouched', () => {+ const swapOnly = darwinMemInfo(() => VM_STAT, TOTAL_BYTES, sysctl({ 'vm.swapusage': SWAPUSAGE }))+ expect(swapOnly?.display).toEqual({ swapUsedMb: 7854, swapTotalMb: 9216 })+ const none = darwinMemInfo(() => VM_STAT, TOTAL_BYTES, sysctl({}))+ expect(none).toEqual({ availableMb: 8951, totalMb: 24576 })+ // vm_stat failing still wins: no reading at all, never a display-only one.+ expect(darwinMemInfo(() => { throw new Error('no vm_stat') }, TOTAL_BYTES, sysctl({ 'vm.swapusage': SWAPUSAGE }))).toBeNull()+ })++ it.skipIf(process.platform !== 'darwin')('reads this Mac\'s real swap and pressure (darwin-only: sysctl oids)', () => {+ const m = readMemInfo()+ expect(m).not.toBeNull()+ expect(m).not.toHaveProperty('swapTotalMb')+ expect(typeof m?.display?.swapTotalMb).toBe('number')+ expect(['normal', 'warn', 'critical']).toContain(m?.display?.pressureLevel)+ })+})++describe('appSelfMemory — "nodeterm itself" (roadmap #4)', () => {+ const S = (pid: number, type: string, cpuSeconds?: number): AppProcessSample => ({+ pid,+ type,+ ...(cpuSeconds !== undefined ? { cpuSeconds } : {})+ })+ // The live shape: GPU footprint 1.6 GB while its rss was ~120 MB; two renderers (canvas + HUD).+ const SAMPLES = [S(10, 'Browser', 60), S(11, 'GPU', 3600), S(12, 'Tab', 900), S(13, 'Tab', 5), S(14, 'Utility', 2)]+ const FP = (pid: number, kb: number) => ({ pid, ppid: 1, rssKb: kb, footprint: true as const })+ const TABLE = [FP(10, 180 * 1024), FP(11, 1600 * 1024), FP(12, 300 * 1024), FP(13, 40 * 1024), FP(14, 20 * 1024)]++ it('folds Electron types into gpu / renderer / main / helper, GPU first', () => {+ expect(['Browser', 'Tab', 'GPU', 'Utility', 'Zygote'].map(appProcessKind)).toEqual(['main', 'renderer', 'gpu', 'helper', 'helper'])+ const r = appSelfMemory(SAMPLES, TABLE, 'darwin')+ expect(r).toEqual({+ ok: true,+ groups: [+ { kind: 'gpu', count: 1, mb: 1600, cpuSeconds: 3600 },+ { kind: 'renderer', count: 2, mb: 340, cpuSeconds: 905 },+ { kind: 'main', count: 1, mb: 180, cpuSeconds: 60 },+ { kind: 'helper', count: 1, mb: 20, cpuSeconds: 2 }+ ],+ totalMb: 2140+ })+ })++ it('darwin: a pid top did not cover keeps NO figure — its rss is the blind number this replaces', () => {+ const table = TABLE.map((e) => (e.pid === 11 ? { pid: 11, ppid: 1, rssKb: 120 * 1024 } : e))+ const r = appSelfMemory(SAMPLES, table, 'darwin')+ expect(r.ok).toBe(true)+ expect(r.groups.find((g) => g.kind === 'gpu')).toEqual({ kind: 'gpu', count: 1, cpuSeconds: 3600 })+ // No total over a missing GPU: it would understate by the very 1.5 GB at issue.+ expect(r).not.toHaveProperty('totalMb')+ // Linux / Windows read the table's own accounting (VmRSS / working set) — same as the rows.+ expect(appSelfMemory(SAMPLES, table, 'linux').groups[0]).toMatchObject({ kind: 'gpu', mb: 120 })+ })++ it('a group with one missing pid has no partial sum', () => {+ const r = appSelfMemory(SAMPLES, TABLE.filter((e) => e.pid !== 13), 'darwin')+ expect(r.groups.find((g) => g.kind === 'renderer')).toEqual({ kind: 'renderer', count: 2, cpuSeconds: 905 })+ })++ it('CPU time is omitted, not zeroed, when Electron did not report it', () => {+ const r = appSelfMemory([S(10, 'Browser'), S(11, 'GPU', 7)], TABLE, 'darwin')+ expect(r.groups).toEqual([+ { kind: 'gpu', count: 1, mb: 1600, cpuSeconds: 7 },+ { kind: 'main', count: 1, mb: 180 }+ ])+ })++ it('ok:false — never an empty ok group — when nothing could be measured', () => {+ expect(appSelfMemory(null, TABLE, 'darwin')).toEqual({ ok: false, groups: [] })+ expect(appSelfMemory([], TABLE, 'darwin')).toEqual({ ok: false, groups: [] })+ expect(appSelfMemory(SAMPLES, null, 'darwin')).toEqual({ ok: false, groups: [] })+ expect(appSelfMemory(SAMPLES, [], 'linux')).toEqual({ ok: false, groups: [] })+ })++ it('rides on the tmux sweep\'s own table, and a throwing reader is not-measured', async () => {+ const base = {+ tmuxBin: () => '/usr/bin/tmux',+ sockets: ['s1'],+ exec: async () => 'nt-a|100|claude\n',+ readTable: () => [P(100, 1, 40 * 1024), { pid: 7, ppid: 1, rssKb: 512 * 1024, footprint: true as const }],+ readMem: () => null+ }+ const ok = await collectSessionMemory({ ...base, appProcesses: () => [S(7, 'GPU')] })+ expect(ok.app).toEqual({ ok: true, groups: [{ kind: 'gpu', count: 1, mb: 512 }], totalMb: 512 })+ // The session rows are untouched by it.+ expect(ok.rows.map((r) => r.nodeId)).toEqual(['a'])+ const threw = await collectSessionMemory({ ...base, appProcesses: () => { throw new Error('gone') } })+ expect(threw.app).toEqual({ ok: false, groups: [] })+ // No reader injected (Server Edition) → no field at all: "not available", not "could not measure".+ expect(await collectSessionMemory(base)).not.toHaveProperty('app')+ })+})diff --git a/src/core/session-memory.ts b/src/core/session-memory.tsindex 70de95ab0..ab23ed20e 100644--- a/src/core/session-memory.ts+++ b/src/core/session-memory.ts@@ -12,7 +12,16 @@ import fs from 'fs'import os from 'os'import { execFile, execFileSync } from 'child_process'import { promisify } from 'util'-import type { MemInfo, SessionHostOverhead, SessionMemoryRow, SessionMemoryReport } from '../shared/types'+import type {+ AppProcessKind,+ AppSelfGroup,+ AppSelfMemory,+ MemDisplay,+ MemInfo,+ SessionHostOverhead,+ SessionMemoryRow,+ SessionMemoryReport+} from '../shared/types'import { TMUX_SOCKET } from './tmux-naming'import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'import type { SessionHostListing } from './session-host-client'@@ -30,6 +39,10 @@ export interface ProcEntry {rssKb: number/** Image name, when the reader has one (the Windows CIM table). Only `hostOverhead` reads it. */name?: string+ /** darwin: `rssKb` is `top`'s phys_footprint, not `ps` rss. Only `appSelfMemory` reads it — a+ * pid `top` missed keeps its rss, which is fine for a session row but is exactly the blind number+ * the "nodeterm itself" group exists to replace (GPU: rss 96-153 MB vs footprint 1557-1845 MB). */+ footprint?: true}/** Reads the whole process table at once; null when it could not run. */@@ -174,12 +187,75 @@ export function parseTopFootprint(stdout: string): Map<number, number> {* degrade correctly on null: `planReap` treats it as "no pressure" (absence of evidence never* triggers a kill) and the pill pulses instead of printing a number it has not earned.*/-export function darwinMemInfo(runVmStat: () => string, totalBytes: number): MemInfo | null {+export function darwinMemInfo(+ runVmStat: () => string,+ totalBytes: number,+ runSysctl?: (name: string) => string+): MemInfo | null {+ let base: MemInfo | nulltry {- return parseVmStat(runVmStat(), totalBytes)+ base = parseVmStat(runVmStat(), totalBytes)} catch {return null}+ if (!base || !runSysctl) return base+ // The pill's display extras (roadmap #14). Each is a SEPARATE optional read, the same shape as+ // PSI on Linux: a failed sysctl omits its one field and costs the vm_stat reading nothing. Never+ // `swapTotalMb`/`swapFreeMb` — see MemInfo.display for why darwin must not fill those.+ const display: MemDisplay = {}+ try {+ Object.assign(display, parseSwapUsage(runSysctl('vm.swapusage')))+ } catch {+ // no swap figure+ }+ try {+ const level = parsePressureLevel(runSysctl('kern.memorystatus_vm_pressure_level'))+ if (level) display.pressureLevel = level+ } catch {+ // no pressure tint+ }+ return Object.keys(display).length > 0 ? { ...base, display } : base+}++/**+ * Parse `sysctl vm.swapusage` (with or without the `vm.swapusage:` prefix). Live shape on the+ * audited Mac (2026-10-19):+ * vm.swapusage: total = 9216.00M used = 7853.62M free = 1362.38M (encrypted)+ * `K`/`M`/`G` are accepted; an unknown suffix or a missing half yields NOTHING rather than a guessed+ * scale. `total = 0.00M` is a real answer (no swap file yet) and passes through as 0.+ */+export function parseSwapUsage(text: string): Pick<MemDisplay, 'swapUsedMb' | 'swapTotalMb'> {+ const UNIT: Record<string, number> = { K: 1 / 1024, M: 1, G: 1024 }+ const mb = (label: string): number | undefined => {+ const m = new RegExp(`\\b${label}\\s*=\\s*(\\d+(?:\\.\\d+)?)([A-Za-z])`).exec(text)+ if (!m) return undefined+ const factor = UNIT[m[2].toUpperCase()]+ if (factor === undefined) return undefined+ const n = Number(m[1]) * factor+ return Number.isFinite(n) ? Math.round(n) : undefined+ }+ const total = mb('total')+ const used = mb('used')+ // Both or neither, like the Linux swap pair: "used" without a size cannot be read as a fraction.+ if (total === undefined || used === undefined) return {}+ return { swapUsedMb: used, swapTotalMb: total }+}++/** `kern.memorystatus_vm_pressure_level`: 1 NORMAL, 2 WARN, 4 CRITICAL (xnu's+ * kVMPressureNormal/Warning/Critical; 2 observed live while the audit's Mac had 7.5-8.7 GB+ * swapped). Anything else is undefined — never mapped to "normal". */+export function parsePressureLevel(text: string): MemDisplay['pressureLevel'] {+ const m = /(?:^|:\s*)(\d+)\s*$/.exec(text.trim())+ switch (m?.[1]) {+ case '1':+ return 'normal'+ case '2':+ return 'warn'+ case '4':+ return 'critical'+ default:+ return undefined+ }}/**@@ -255,6 +331,12 @@ export function parseMemInfoText(text: string): MemInfo | null {if (swapTotal !== null && swapFree !== null) {out.swapTotalMb = Math.round(swapTotal / 1024)out.swapFreeMb = Math.round(swapFree / 1024)+ // The pill's copy, from the same instant. The reaper keeps reading the pair above; the pill+ // reads only `display`, so darwin and Linux reach it through one shape.+ out.display = {+ swapUsedMb: Math.max(0, out.swapTotalMb - out.swapFreeMb),+ swapTotalMb: out.swapTotalMb+ }}return out}@@ -310,9 +392,12 @@ export function readMemInfo(): MemInfo | null {// (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') {+ // The two sysctls are sub-millisecond reads; they ride on every caller (the reaper too), which+ // only ever ignores `display`.return darwinMemInfo(() => execFileSync('vm_stat', { encoding: 'utf8', timeout: 5_000 }),- os.totalmem()+ os.totalmem(),+ (name) => execFileSync('sysctl', [name], { encoding: 'utf8', timeout: 5_000 }))}try {@@ -382,6 +467,8 @@ export interface SessionMemoryDeps {exec?: (bin: string, args: string[]) => Promise<string>readTable?: ProcessTableReaderreadMem?: () => MemInfo | null+ /** nodeterm's own processes (desktop only). Absent → the report carries no `app` at all. */+ appProcesses?: AppProcessReader}/**@@ -461,7 +548,10 @@ async function psProcessTable(const fp = parseTopFootprint(await exec('top', ['-l', '1', '-stats', 'pid,mem']))// A pid `top` did not list keeps its `rss`. The two snapshots are a moment apart, so a miss is// a process that came or went between them — not a reason to report nothing.- return rows.map((e) => ({ ...e, rssKb: fp.get(e.pid) ?? e.rssKb }))+ return rows.map((e) => {+ const f = fp.get(e.pid)+ return f === undefined ? e : { ...e, rssKb: f, footprint: true as const }+ })} catch {return null}@@ -557,6 +647,96 @@ export function hostOverhead(return { pid: hostPid, selfMb, consoleMb, consoleCount, totalMb: selfMb + consoleMb }}+/**+ * One of nodeterm's own processes, as the shell enumerates them. The desktop shell maps+ * `app.getAppMetrics()` onto this and nothing else reads Electron: `src/core` stays Electron-free.+ *+ * Memory is DELIBERATELY not taken from `getAppMetrics()`. On macOS neither field tracks+ * phys_footprint: `memory.workingSetSize` is resident size, as blind to IOSurfaces as `ps` rss+ * (audit tmux-2/obs-1 — the GPU helper's 1557-1845 MB footprint shows as 96-153 MB there), and+ * `memory.privateBytes` is Windows-only. The pid is looked up in the panel sweep's own process+ * table instead, so the group uses exactly the accounting the session rows use, with no extra+ * `top` (~0.5 s per call, measured).+ */+export interface AppProcessSample {+ pid: number+ /** Electron `ProcessMetric.type`: 'Browser' | 'Tab' | 'GPU' | 'Utility' | … */+ type: string+ /** Electron `cpu.cumulativeCPUUsage` — seconds since the process started; optional there too. */+ cpuSeconds?: number+}++/** Enumerates this app's processes; null (or a throw) = could not. */+export type AppProcessReader = () => AppProcessSample[] | null++export function appProcessKind(type: string): AppProcessKind {+ if (type === 'Browser') return 'main'+ if (type === 'Tab') return 'renderer'+ if (type === 'GPU') return 'gpu'+ return 'helper'+}++const APP_KIND_ORDER: readonly AppProcessKind[] = ['gpu', 'renderer', 'main', 'helper']++/**+ * Build the "nodeterm itself" group from the sweep's table. Rules (audit §5b invariants 2 and 3):+ * - a null process list or table → `ok:false`, never an empty-but-ok group;+ * - darwin: a pid counts as measured only if `top` gave its footprint (`ProcEntry.footprint`).+ * The rss fallback the session rows tolerate is the very number this group exists to replace;+ * - a group with ANY unmeasured pid has no `mb` (a partial sum understates), and the total exists+ * only when every group has one;+ * - not one pid measured → `ok:false`.+ */+export function appSelfMemory(+ samples: readonly AppProcessSample[] | null,+ table: readonly ProcEntry[] | null,+ platformName: NodeJS.Platform+): AppSelfMemory {+ if (!samples || samples.length === 0 || !table) return { ok: false, groups: [] }+ const byPid = new Map(table.map((e) => [e.pid, e]))+ /** `whole` / `cpuWhole`: every pid of the group contributed — false means no figure, not a sum. */+ type Acc = { count: number; kb: number; whole: boolean; cpu: number; cpuWhole: boolean }+ const acc = new Map<AppProcessKind, Acc>()+ let anyMeasured = false+ for (const s of samples) {+ const kind = appProcessKind(s.type)+ const g = acc.get(kind) ?? { count: 0, kb: 0, whole: true, cpu: 0, cpuWhole: true }+ g.count+++ const e = byPid.get(s.pid)+ if (e && (platformName !== 'darwin' || e.footprint)) {+ g.kb += e.rssKb+ anyMeasured = true+ } else {+ g.whole = false+ }+ if (typeof s.cpuSeconds === 'number' && Number.isFinite(s.cpuSeconds)) g.cpu += s.cpuSeconds+ else g.cpuWhole = false+ acc.set(kind, g)+ }+ if (!anyMeasured) return { ok: false, groups: [] }+ const groups: AppSelfGroup[] = APP_KIND_ORDER.filter((k) => acc.has(k)).map((kind) => {+ const g = acc.get(kind) as Acc+ return {+ kind,+ count: g.count,+ ...(g.whole ? { mb: kbToMb(g.kb) } : {}),+ ...(g.cpuWhole ? { cpuSeconds: Math.round(g.cpu) } : {})+ }+ })+ const out: AppSelfMemory = { ok: true, groups }+ if (groups.every((g) => g.mb !== undefined)) out.totalMb = groups.reduce((n, g) => n + (g.mb as number), 0)+ return out+}++/** Read the shell's process list without letting a throw escape into the sweep. */+function sampleApp(read: AppProcessReader): AppProcessSample[] | null {+ try {+ return read()+ } catch {+ return null+ }+}+export interface SessionHostMemoryDeps {/** The host's listing (`PtyManager.sessionHostListing()`); null = the read failed. */list: () => Promise<SessionHostListing | null>@@ -565,6 +745,8 @@ export interface SessionHostMemoryDeps {readMem?: () => MemInfo | nullexec?: (bin: string, args: string[]) => Promise<string>platformName?: NodeJS.Platform+ /** nodeterm's own processes (desktop only). Absent → the report carries no `app` at all. */+ appProcesses?: AppProcessReader}/**@@ -580,6 +762,13 @@ export interface SessionHostMemoryDeps {*/export async function collectSessionHostMemory(deps: SessionHostMemoryDeps): Promise<SessionMemoryReport> {const mem = (deps.readMem ?? readMemInfo)()+ const platformName = deps.platformName ?? process.platform+ // The "nodeterm itself" group rides on whatever table this sweep read. A path that reads none+ // reports it NOT MEASURED (ok:false) rather than leaving it out — absent means "not available".+ const withApp = (report: SessionMemoryReport, table: ProcEntry[] | null): SessionMemoryReport =>+ deps.appProcesses+ ? { ...report, app: appSelfMemory(sampleApp(deps.appProcesses), table, platformName) }+ : reportlet listing: SessionHostListing | nulltry {listing = await deps.list()@@ -587,7 +776,7 @@ export async function collectSessionHostMemory(deps: SessionHostMemoryDeps): Prolisting = null}if (!listing) return { ok: false, rows: [], mem }- if (!listing.running) return { ok: true, rows: [], mem }+ if (!listing.running) return withApp({ ok: true, rows: [], mem }, null)const ours = listing.names.filter((n) => n.startsWith('nt-'))const described = new Map((listing.sessions ?? []).map((row) => [row.name, row]))const panes: PaneRef[] = []@@ -603,9 +792,9 @@ export async function collectSessionHostMemory(deps: SessionHostMemoryDeps): Pro// table — but only when there is a host pid to measure. Without one there is nothing to look up,// and "no sessions" stays the no-table answer it always was.const hostPid = listing.hostPid- if (panes.length === 0 && hostPid === undefined) return withUnmeasured({ ok: true, rows: [], mem })+ if (panes.length === 0 && hostPid === undefined)+ return withApp(withUnmeasured({ ok: true, rows: [], mem }), null)- const platformName = deps.platformName ?? process.platformconst exec =deps.exec ??(async (b: string, args: string[]): Promise<string> => {@@ -631,10 +820,10 @@ export async function collectSessionHostMemory(deps: SessionHostMemoryDeps): Proif (table === null) {// No pane to describe: the table was read only for the host's own cost, and failing to read it// says nothing about sessions — the answer stays "none", with the host simply unmeasured.- if (panes.length === 0) return withUnmeasured({ ok: true, rows: [], mem })+ if (panes.length === 0) return withApp(withUnmeasured({ ok: true, rows: [], mem }), null)return { ok: false, rows: [], mem }}- const report = withUnmeasured(buildReport(panes, table, mem))+ const report = withApp(withUnmeasured(buildReport(panes, table, mem)), table)// A session the host named but did not describe has a shell among the host's children that no// row excludes, so its memory would be booked as host overhead. Report nothing rather than that.// The same holds for a session outside the `nt-` namespace (the host accepts any name, and the@@ -697,5 +886,9 @@ export async function collectSessionMemory(// Nobody answered: broken tmux, an unreadable socket dir, a timeout against a hung server. We did// not look, so we cannot claim there is nothing — that would print "no sessions" over 20 live ones.if (answered === 0) return { ok: false, rows: [], mem }- return buildReport([...bySession.values()], table, mem)+ const report = buildReport([...bySession.values()], table, mem)+ // Same table, no second read: on darwin it already carries `top`'s footprint for EVERY pid,+ // Electron's included (audit §5b: reuse the sweep, the pill never polls `top`).+ if (!deps.appProcesses) return report+ return { ...report, app: appSelfMemory(sampleApp(deps.appProcesses), table, process.platform) }}diff --git a/src/main/index.ts b/src/main/index.tsindex 6a4214bd1..c6be3a355 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3583,6 +3583,17 @@ app.whenReady().then(async () => {unmeasuredSessions: () => ptyManager.zellijSessionCount(),// Windows (no tmux): the session host's sessions; undefined where it is not the backend.sessionHost: () => ptyManager.sessionHostListing(),+ // The panel's "nodeterm itself" group (audit roadmap #4): pids, types and CPU time only. Memory+ // is NOT taken from here — on macOS `memory.workingSetSize` is resident size and misses the GPU+ // helper's IOSurfaces (footprint 1557-1845 MB vs 96-153 MB), and `privateBytes` is Windows-only;+ // core looks each pid up in the sweep's own footprint table instead. Called once per panel+ // sweep, never on a timer.+ appProcesses: () =>+ app.getAppMetrics().map((m) => ({+ pid: m.pid,+ type: m.type,+ ...(typeof m.cpu.cumulativeCPUUsage === 'number' ? { cpuSeconds: m.cpu.cumulativeCPUUsage } : {})+ })),remote: {// Identity, not liveness: a DISCONNECTED SSH project is still someone else's machine, and// `connectedHosts()` alone would answer "local" for it — exactly the window the service'sdiff --git a/src/renderer/components/SessionMemoryPanel.test.tsx b/src/renderer/components/SessionMemoryPanel.test.tsxindex 8370064f0..d45772880 100644--- a/src/renderer/components/SessionMemoryPanel.test.tsx+++ b/src/renderer/components/SessionMemoryPanel.test.tsx@@ -78,6 +78,7 @@ function mount(over: Partial<ReturnType<typeof useSessionMemory.getState>> = {})loadedScope: '',loading: false,host: undefined,+ app: undefined,refreshFull,startHostPoll,stopHostPoll,@@ -481,4 +482,61 @@ describe('SessionMemoryPanel', () => {expect(pauseOf(1)).toBeNull()})})++ describe('"nodeterm itself" (roadmap #4)', () => {+ const APP = {+ ok: true,+ groups: [+ { kind: 'gpu' as const, count: 1, mb: 1600, cpuSeconds: 3725 },+ { kind: 'renderer' as const, count: 2, mb: 340 },+ { kind: 'main' as const, count: 1 }+ ]+ }+ const appBlock = (): HTMLElement | null => host.querySelector('.sessmem-app')++ it('lists the app groups below the rows, OUT of the session total', () => {+ mount({ app: { ...APP, totalMb: 2000 } })+ const t = appBlock()?.textContent ?? ''+ expect(t).toContain('nodeterm itself')+ expect(t).toContain('GPU')+ expect(t).toContain('1.6 GB')+ expect(t).toContain('CPU 1h 02m')+ expect(t).toContain('Renderers ×2')+ // The main process was not measured: said so, never "0 B".+ expect(t).toContain('not measured')+ expect(t).not.toMatch(/\b0 B\b/)+ // The header is still the sessions' 1.5 GB, not 1.5 + 2.0.+ expect(host.querySelector('.sessmem-panel__total')?.textContent).toBe('1.5 GB')+ })++ it('a partial group set prints no app total rather than an understated one', () => {+ mount({ app: APP })+ expect(appBlock()?.querySelector('.sessmem-host__mb')?.textContent).toBe('—')+ })++ it('ok:false says it could not measure — never a zero', () => {+ mount({ app: { ok: false, groups: [] } })+ expect(appBlock()?.textContent).toMatch(/could not measure nodeterm/i)+ expect(appBlock()?.textContent).not.toMatch(/\d/)+ })++ it('absent (Server Edition) draws nothing', () => {+ mount()+ expect(appBlock()).toBeNull()+ })++ it('never appears on an SSH scope, even with a stale group in the store', () => {+ useProjects.setState({+ projects: [project({ id: 'ssh1', name: 'Box', ssh: { server: { host: 'box', user: 'enes', port: 22 } as never, remoteCwd: '/srv' } })],+ activeProjectId: 'ssh1'+ })+ mount({ loadedScope: 'enes@box', app: { ...APP, totalMb: 2000 } })+ expect(appBlock()).toBeNull()+ })++ it('waits for this scope\'s answer like every other figure', () => {+ mount({ loadedScope: null, app: { ...APP, totalMb: 2000 } })+ expect(appBlock()).toBeNull()+ })+ })})diff --git a/src/renderer/components/SessionMemoryPanel.tsx b/src/renderer/components/SessionMemoryPanel.tsxindex fe53e1043..2280b21d6 100644--- a/src/renderer/components/SessionMemoryPanel.tsx+++ b/src/renderer/components/SessionMemoryPanel.tsx@@ -16,7 +16,13 @@ import { formatBytes } from '@shared/fsLimits'import { useAgentStatus } from '../state/agentStatus'import { useProjects } from '../state/projects'import { useSessionMemory } from '../state/sessionMemory'-import { hostOverheadLabel, resolveSessionRows, totalMb } from '../lib/sessionMemoryRows'+import {+ appGroupLabel,+ formatCpuTime,+ hostOverheadLabel,+ resolveSessionRows,+ totalMb+} from '../lib/sessionMemoryRows'import { usageScopeKey } from '../lib/usageScope'import type { SessionPauseOffer } from '../lib/sessionPause'import { unmeasuredNote } from '../lib/sessionMemoryNote'@@ -81,6 +87,7 @@ export function SessionMemoryPanel({const unmeasured = useSessionMemory((s) => s.unmeasured)const unmeasuredBackend = useSessionMemory((s) => s.unmeasuredBackend)const hostCost = useSessionMemory((s) => s.host)+ const appSelf = useSessionMemory((s) => s.app)const loading = useSessionMemory((s) => s.loading)const loadedScope = useSessionMemory((s) => s.loadedScope)const refreshFull = useSessionMemory((s) => s.refreshFull)@@ -284,6 +291,40 @@ export function SessionMemoryPanel({nodeterm itself.</div>+ {/* nodeterm's OWN processes (audit roadmap #4), below the attribution line on purpose: they+ are not a session and are NOT in the header total. The GPU helper is the reason this+ exists — `ps` said 96-153 MB while its footprint was 1557-1845 MB, mostly IOSurfaces (the+ window's swap chain and raster tiles, and the terminals' WebGL buffers), and no surface+ attributed it. LOCAL scope only (`scopeKey === ''`): never beside an SSH host's numbers.+ Absent = this surface cannot enumerate its processes (Server Edition) → nothing drawn;+ `ok:false` = it tried and could not, which is said, never printed as 0 B. */}+ {measured && !relay && scopeKey === '' && appSelf && (+ <div+ className="sessmem-app"+ title="nodeterm's own processes, in the same accounting as the rows above (on macOS: physical footprint, which includes graphics memory that ps does not show). CPU is time used since each process started."+ >+ <div className="sessmem-host">+ <span className="sessmem-host__label">nodeterm itself</span>+ <span className="sessmem-host__mb">+ {appSelf.ok ? (appSelf.totalMb !== undefined ? formatMb(appSelf.totalMb) : '—') : ''}+ </span>+ </div>+ {appSelf.ok ? (+ appSelf.groups.map((g) => (+ <div key={g.kind} className="sessmem-row__kids sessmem-app__group">+ └ {appGroupLabel(g)}+ {g.cpuSeconds !== undefined && (+ <span className="sessmem-app__cpu"> · CPU {formatCpuTime(g.cpuSeconds)}</span>+ )}{' '}+ <span>{g.mb !== undefined ? formatMb(g.mb) : 'not measured'}</span>+ </div>+ ))+ ) : (+ <div className="sessmem-panel__note">Could not measure nodeterm's own processes.</div>+ )}+ </div>+ )}+<div className="sessmem-panel__foot"><span className="sessmem-panel__count">{measured ? `${views.length} session${views.length === 1 ? '' : 's'}` : ''}diff --git a/src/renderer/components/SystemResourcePill.test.tsx b/src/renderer/components/SystemResourcePill.test.tsxindex 69f9bc472..ad986bd5a 100644--- a/src/renderer/components/SystemResourcePill.test.tsx+++ b/src/renderer/components/SystemResourcePill.test.tsx@@ -229,4 +229,51 @@ describe('SystemResourcePill', () => {expect(panel).not.toBeNull()expect(panel?.classList.contains('sessmem-panel')).toBe(true)})++ describe('swap and kernel pressure (roadmap #14, display-only)', () => {+ const pillText = (): string => host.querySelector('.sysres-pill')?.textContent ?? ''+ const title = (): string => host.querySelector('.sysres-pill')?.getAttribute('title') ?? ''+ const icon = (): string => host.querySelector<HTMLElement>('.sysres-pill__icon')?.style.color ?? ''++ it('shows swap in use beside the RAM figure, and used-of-total in the title', () => {+ // The audited Mac: 7.7 GB of 9 GB swapped while the pill read only "86%".+ mount({ ...MEM, display: { swapUsedMb: 7854, swapTotalMb: 9216 } })+ expect(pillText()).toContain('7.7 GB swap')+ expect(title()).toContain('swap 7.7 GB of 9.0 GB used')+ })++ it('no swap figure at all when it was not measured — never "0 GB swap"', () => {+ mount(MEM)+ expect(pillText()).not.toMatch(/swap/i)+ expect(title()).not.toMatch(/swap/i)+ act(() => root.unmount())+ // Half a reading is no reading.+ mount({ ...MEM, display: { swapUsedMb: 100 } })+ expect(pillText()).not.toMatch(/swap/i)+ })++ it('a measured zero stays out of the pill and is only stated in the title', () => {+ mount({ ...MEM, display: { swapUsedMb: 0, swapTotalMb: 2048 } })+ expect(pillText()).not.toMatch(/swap/i)+ expect(title()).toContain('swap 0 B of 2.0 GB used')+ act(() => root.unmount())+ // No swap provisioned at all: nothing to describe, in the title either.+ mount({ ...MEM, display: { swapUsedMb: 0, swapTotalMb: 0 } })+ expect(title()).not.toMatch(/swap/i)+ })++ it('the kernel level RAISES the tint at 25% used…', () => {+ mount({ ...MEM, display: { pressureLevel: 'warn' } })+ expect(icon()).toBe('var(--warn)')+ expect(title()).toContain('memory pressure warn')+ act(() => root.unmount())+ mount({ ...MEM, display: { pressureLevel: 'critical' } })+ expect(icon()).toBe('var(--danger)')+ })++ it('…and never lowers it: "normal" does not calm a 98%-used machine', () => {+ mount({ totalMb: 64000, availableMb: 1000, display: { pressureLevel: 'normal' } })+ expect(icon()).toBe('var(--danger)')+ })+ })})diff --git a/src/renderer/components/SystemResourcePill.tsx b/src/renderer/components/SystemResourcePill.tsxindex 7ab94d293..32bd71524 100644--- a/src/renderer/components/SystemResourcePill.tsx+++ b/src/renderer/components/SystemResourcePill.tsx@@ -1,5 +1,6 @@import { useEffect, useRef, useState } from 'react'import { formatBytes } from '@shared/fsLimits'+import type { MemInfo } from '@shared/types'import { useProjects } from '../state/projects'import { useSshConn } from '../state/sshConn'import { useSessionMemory } from '../state/sessionMemory'@@ -15,6 +16,25 @@ const MB = 1024 * 1024const WARN_PERCENT = 75const DANGER_PERCENT = 90+/** 0 none, 1 warn, 2 danger. */+type Severity = 0 | 1 | 2+const TINT: Record<Severity, string | undefined> = { 0: undefined, 1: 'var(--warn)', 2: 'var(--danger)' }++function percentSeverity(usedPercent: number): Severity {+ return usedPercent >= DANGER_PERCENT ? 2 : usedPercent >= WARN_PERCENT ? 1 : 0+}++/**+ * The kernel's own verdict (darwin `kern.memorystatus_vm_pressure_level`, the colour Activity+ * Monitor's pressure graph uses). It may only RAISE the tint, never lower it: used-% is the only+ * signal on Linux and on an SSH host, and a "normal" level does not make 95% used comfortable.+ * Absent = not measured → contributes nothing.+ */+function pressureSeverity(mem: MemInfo): Severity {+ const level = mem.display?.pressureLevel+ return level === 'critical' ? 2 : level === 'warn' ? 1 : 0+}+export interface SystemResourcePillProps {overBoard?: boolean/** Handed straight to the panel. Required, not optional: an omitted callback would compile into@@ -101,6 +121,7 @@ export function SystemResourcePill({let body: JSX.Elementlet iconColor: string | undefined+ let swapTitle = ''// `null` = could not read — the normal answer on a non-Linux SSH host, and on any host whose// first read has not landed yet. Pulse, NEVER "0 GB": a confident zero is the one thing this pill// must never say, since the number is the whole reason anyone looks at it. A `totalMb` of zero is@@ -112,18 +133,32 @@ export function SystemResourcePill({const usedPercent = Math.min(100, (usedMb / mem.totalMb) * 100)// The ICON carries the pressure reading now that the bar is gone: it tints as memory is// consumed, so a glance still says "this machine is tight" without the pill claiming a row of- // the canvas. Same thresholds the bar used.- const color =- usedPercent >= DANGER_PERCENT- ? 'var(--danger)'- : usedPercent >= WARN_PERCENT- ? 'var(--warn)'- : undefined+ // the canvas. Same thresholds the bar used, raised (never lowered) by the kernel's pressure+ // level where the OS reports one (audit roadmap #14).+ const color = TINT[Math.max(percentSeverity(usedPercent), pressureSeverity(mem)) as Severity]+ const swap = mem.display+ // Swap is shown only when BOTH halves were measured (`display` is display-only: the reaper never+ // reads it). On the audited Mac the pill said 86% "warn" with 8.5 GB swapped and nothing on+ // screen said so (audit agent-trees-3). No figure when the read failed or the OS has none —+ // never "+0 GB"; a measured 0 with swap provisioned is a fact and only goes in the title.+ const swapShown =+ swap?.swapUsedMb !== undefined && swap.swapTotalMb !== undefined && swap.swapUsedMb > 0+ // `swapTotalMb > 0`: a Mac with no swap file yet (or a swapless Linux host) has nothing to+ // describe, and "swap 0 B of 0 B used" would read as a measurement of something.+ if (swap?.swapUsedMb !== undefined && swap.swapTotalMb !== undefined && swap.swapTotalMb > 0)+ swapTitle = ` · swap ${formatBytes(swap.swapUsedMb * MB)} of ${formatBytes(swap.swapTotalMb * MB)} used`+ if (swap?.pressureLevel) swapTitle += ` · memory pressure ${swap.pressureLevel}`body = (<span className="sysres-pill__detail sysres-pill__num" style={color ? { color } : undefined}>{formatBytes(usedMb * MB)}<span className="sysres-pill__sep"> / </span>{formatBytes(mem.totalMb * MB)}+ {swapShown && (+ <span className="sysres-pill__swap sysres-pill__dim">+ <span className="sysres-pill__sep"> · </span>+ {formatBytes((swap.swapUsedMb as number) * MB)} swap+ </span>+ )}</span>)iconColor = color@@ -149,7 +184,7 @@ export function SystemResourcePill({aria-controls="sessmem-panel"// The SSH pill is visually identical to the local one, so the title is what answers// "whose memory is this?" without opening the panel.- title={scopeKey ? `Memory on ${scopeKey}` : 'Memory on this machine'}+ title={(scopeKey ? `Memory on ${scopeKey}` : 'Memory on this machine') + swapTitle}><span className="sysres-pill__icon" style={iconColor ? { color: iconColor } : undefined}><IconResource />diff --git a/src/renderer/lib/sessionMemoryRows.test.ts b/src/renderer/lib/sessionMemoryRows.test.tsindex 891c4d57a..8ea640870 100644--- a/src/renderer/lib/sessionMemoryRows.test.ts+++ b/src/renderer/lib/sessionMemoryRows.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { hostOverheadLabel, resolveSessionRows, totalMb } from './sessionMemoryRows'+import { appGroupLabel, formatCpuTime, hostOverheadLabel, resolveSessionRows, totalMb } from './sessionMemoryRows'import type { SessionMemoryRow } from '@shared/types'const row = (nodeId: string, mb: number): SessionMemoryRow => ({@@ -86,3 +86,20 @@ describe('totalMb', () => {expect(hostOverheadLabel({ ...host, consoleCount: 1 })).toBe('nodeterm session host (1 console)')})})++describe('"nodeterm itself" labels (roadmap #4)', () => {+ it('names each group, with a count only when there is more than one', () => {+ expect(appGroupLabel({ kind: 'gpu', count: 1 })).toBe('GPU')+ expect(appGroupLabel({ kind: 'renderer', count: 2 })).toBe('Renderers ×2')+ expect(appGroupLabel({ kind: 'renderer', count: 1 })).toBe('Renderer')+ expect(appGroupLabel({ kind: 'main', count: 1 })).toBe('Main process')+ expect(appGroupLabel({ kind: 'helper', count: 3 })).toBe('Helpers ×3')+ })++ it('prints CPU TIME, not a rate', () => {+ expect(formatCpuTime(42.4)).toBe('42s')+ expect(formatCpuTime(720)).toBe('12m')+ expect(formatCpuTime(3725)).toBe('1h 02m')+ expect(formatCpuTime(-1)).toBe('0s')+ })+})diff --git a/src/renderer/lib/sessionMemoryRows.ts b/src/renderer/lib/sessionMemoryRows.tsindex 481ae4b5b..839b97ecd 100644--- a/src/renderer/lib/sessionMemoryRows.ts+++ b/src/renderer/lib/sessionMemoryRows.ts@@ -5,7 +5,7 @@// orphan/closed-project policy is unit-testable without mounting anything.import type { AgentState } from '@shared/agents/normalize'-import type { Project, SessionHostOverhead, SessionMemoryRow } from '@shared/types'+import type { AppSelfGroup, Project, SessionHostOverhead, SessionMemoryRow } from '@shared/types'export interface SessionMemoryView {row: SessionMemoryRow@@ -84,3 +84,31 @@ export function hostOverheadLabel(host: SessionHostOverhead): string {const n = host.consoleCountreturn `nodeterm session host (${n} console${n === 1 ? '' : 's'})`}++/** "nodeterm itself" sub-line label: `GPU`, `Renderers ×2`, `Main process`, `Helpers ×3`. */+export function appGroupLabel(g: AppSelfGroup): string {+ const n = g.count > 1 ? ` ×${g.count}` : ''+ switch (g.kind) {+ case 'gpu':+ return `GPU${n}`+ case 'renderer':+ return `Renderer${g.count > 1 ? 's' : ''}${n}`+ case 'main':+ return `Main process${n}`+ default:+ return `Helper${g.count > 1 ? 's' : ''}${n}`+ }+}++/**+ * CPU TIME, not a rate: `cumulativeCPUUsage` is seconds since each process started, and a+ * percentage would need a second sample the panel's one-shot sweep does not take (Electron's own+ * `percentCPUUsage` answers 0 on the first call — a fake zero). `42s`, `12m`, `3h 05m`.+ */+export function formatCpuTime(seconds: number): string {+ const s = Math.max(0, Math.round(seconds))+ if (s < 60) return `${s}s`+ const m = Math.floor(s / 60)+ if (m < 60) return `${m}m`+ return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`+}diff --git a/src/renderer/state/sessionMemory.test.ts b/src/renderer/state/sessionMemory.test.tsindex 36e8479b0..6ddad07dd 100644--- a/src/renderer/state/sessionMemory.test.ts+++ b/src/renderer/state/sessionMemory.test.ts@@ -153,3 +153,29 @@ describe('failure semantics', () => {expect(useSessionMemory.getState().loading).toBe(false)})})++describe('"nodeterm itself" group (roadmap #4)', () => {+ const APP = { ok: true, groups: [{ kind: 'gpu', count: 1, mb: 1600 }], totalMb: 1600 }++ it('carries the group from an answered sweep, and drops it when the sweep failed or the scope changed', async () => {+ read.mockResolvedValueOnce({ ok: true, rows: [], mem: null, app: APP })+ await useSessionMemory.getState().refreshFull('', 'p1')+ expect(useSessionMemory.getState().app).toEqual(APP)+ // ok:false: nothing from that report is adopted, the group included.+ read.mockResolvedValueOnce({ ok: false, rows: [], mem: null, app: APP })+ await useSessionMemory.getState().refreshFull('', 'p1')+ expect(useSessionMemory.getState().app).toBeUndefined()+ read.mockResolvedValueOnce({ ok: true, rows: [], mem: null, app: APP })+ await useSessionMemory.getState().refreshFull('', 'p1')+ // Leaving this machine for an SSH host must not keep this machine's processes on screen.+ useSessionMemory.getState().startHostPoll('user@host', 'ssh1')+ expect(useSessionMemory.getState().app).toBeUndefined()+ })++ it('a rejected call clears it too', async () => {+ useSessionMemory.setState({ app: APP as never })+ read.mockRejectedValueOnce(new Error('bridge down'))+ await useSessionMemory.getState().refreshFull('', 'p1')+ expect(useSessionMemory.getState().app).toBeUndefined()+ })+})diff --git a/src/renderer/state/sessionMemory.ts b/src/renderer/state/sessionMemory.tsindex 3a2fdc506..8eb117834 100644--- a/src/renderer/state/sessionMemory.ts+++ b/src/renderer/state/sessionMemory.ts@@ -11,6 +11,7 @@import { create } from 'zustand'import type {+ AppSelfMemory,MemInfo,SessionHostOverhead,SessionMemoryApi,@@ -31,6 +32,8 @@ interface SessionMemoryState {unmeasuredBackend?: 'session-host'/** The Windows session host's own cost (SessionMemoryReport.host); absent = none / unmeasured. */host?: SessionHostOverhead+ /** nodeterm's own processes (SessionMemoryReport.app); absent = not available on this surface. */+ app?: AppSelfMemorymem: MemInfo | nullloading: boolean/** Scope key the current rows belong to; null before the first successful load. */@@ -103,13 +106,14 @@ export const useSessionMemory = create<SessionMemoryState>((set, get) => ({unmeasured: r.unmeasured ?? 0,unmeasuredBackend: r.unmeasuredBackend,host: r.ok ? r.host : undefined,+ app: r.ok ? r.app : undefined,loadedScope: scopeKey})} catch {// A rejected call (dead WS bridge, no session yet) is the same fact as `ok:false` — the sweep// could not run. It is emphatically not "there are no sessions".if (scopeKey !== activeScope) return- set({ ok: false, rows: [], unmeasured: 0, unmeasuredBackend: undefined, host: undefined })+ set({ ok: false, rows: [], unmeasured: 0, unmeasuredBackend: undefined, host: undefined, app: undefined })} finally {// A response for a scope we have left owns nothing here — `enterScope` already cleared the// spinner when it switched.@@ -157,6 +161,7 @@ function enterScope(scopeKey: string, set: SetState): void {unmeasured: 0,unmeasuredBackend: undefined,host: undefined,+ app: undefined,mem: null,loading: false,loadedScope: nulldiff --git a/src/shared/types.ts b/src/shared/types.tsindex 6a610a2d6..64acacba9 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3157,6 +3157,28 @@ export interface MemInfo {psiSomeAvg60?: number/** `/proc/pressure/memory` `full avg60` — % of the last minute EVERY task was stalled. Thrash. */psiFullAvg60?: number+ /**+ * What the RAM pill SHOWS beyond used/total. **Display only: never an input to the reaper, the+ * memory-pressure monitor or a reclaim lever** (audit §5b invariant 1). It is a separate object,+ * rather than more top-level fields, so that rule is structural: `hostUnderMemoryPressure` reads+ * `swapTotalMb`/`swapFreeMb`, and filling THOSE on darwin would fire the reaper's swap term all+ * day on a Mac that keeps its swap ~85% used as a matter of course (audit agent-trees-2/3: 16%+ * swap free while healthy). Absent field = not measured, never zero.+ */+ display?: MemDisplay+}++/** See `MemInfo.display`. Every field is optional and independent: one failed read omits one fact. */+export interface MemDisplay {+ /** Swap in use, MB. darwin: `sysctl vm.swapusage`; Linux: `SwapTotal - SwapFree`. */+ swapUsedMb?: number+ /** Swap currently provisioned, MB. On darwin this GROWS on demand (dynamic swap files), so it is+ * a size, not a ceiling. */+ swapTotalMb?: number+ /** The kernel's own verdict (`kern.memorystatus_vm_pressure_level`: 1/2/4), darwin only — the+ * colour Activity Monitor's pressure graph shows. Linux has no equivalent level and PSI has no+ * measured threshold here, so it is never invented there. */+ pressureLevel?: 'normal' | 'warn' | 'critical'}/** One nt- session's memory, as the panel renders it. */@@ -3204,6 +3226,41 @@ export interface SessionMemoryReport {* could not be measured: never a fake zero. The tmux leg never sets it.*/host?: SessionHostOverhead+ /**+ * nodeterm's OWN processes (main, renderer(s), GPU, helpers) — the "nodeterm itself" group.+ * Display only, LOCAL scope only. Absent = this shell cannot enumerate its processes (Server+ * Edition, a relay stub, every SSH scope): not available. `ok:false` = it tried and could not+ * measure. Never part of the session total — see AppSelfMemory.+ */+ app?: AppSelfMemory+}++/** Which of nodeterm's own processes a group is (Electron `ProcessMetric.type`, folded). */+export type AppProcessKind = 'main' | 'renderer' | 'gpu' | 'helper'++/** One kind of nodeterm process, summed over every pid of that kind (the HUD is a 2nd renderer). */+export interface AppSelfGroup {+ kind: AppProcessKind+ count: number+ /** Summed memory in MB, in the SAME accounting as the session rows (darwin: phys_footprint from+ * the panel's own `top` read; Linux: VmRSS; Windows: working set). Absent when any pid of the+ * group was missing from the table: a partial sum would understate, which is a wrong number. */+ mb?: number+ /** Summed CPU time since each process started, seconds (Electron `cumulativeCPUUsage`). Absent =+ * not reported. A lifetime total, deliberately not a percentage. */+ cpuSeconds?: number+}++/**+ * The audit's roadmap #4: the GPU helper's real footprint (1557-1845 MB live, mostly IOSurfaces)+ * was invisible because `ps` RSS says 96-153 MB and nothing attributed it. `ok:false` (no groups)+ * when the process list or the table could not be read, or no pid of ours was in it.+ */+export interface AppSelfMemory {+ ok: boolean+ groups: AppSelfGroup[]+ /** Sum of every group, only when every group was measured. */+ totalMb?: number}/** See `SessionMemoryReport.host`. All MB figures are MEASURED working sets, not estimates. */