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
fix(session-memory): say what a row's number is, how it splits and when it was read
enes210d972bfcba
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8cdce8258..85a035727 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -6870,11 +6870,30 @@ about which machine they describe. Reading + parsing is `core/session-memory.ts`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-pageenterprise arm64 builds (40 MB printed for a 640 MB session). **Do not optimise this back to- `statm`.** Non-Linux falls through to one `ps -eo pid,ppid,rss` call, through the same injectable+ `statm`.** Non-Linux falls through to one `ps -eo pid,ppid,rss,comm` call, through the same injectableseam as tmux.-- **`childCount` counts ALL descendants**, the agent CLI included: `pane_pid` is the pane's SHELL, so- a claude session with two MCP servers reports **3**. The UI therefore says "**child processes**",- never "MCP" — a plain `npm run dev` has children too.+- **A row's number is the WHOLE TREE, and the line under it says how it splits.** `pane_pid` is the+ pane's SHELL, so `childCount` counts the agent CLI too (claude with two MCP servers: **3**), and+ `childrenMb` is the total minus a few MB of shell. The panel printed that, so "claude 1.7 GB" sat+ over "+14 child processes 1.7 GB" and read as two sizes (field report, 2026-11-04). The line is now+ `largestName largestMb · N other processes <the rest>`: two parts that add up to the row. It names+ the LARGEST process, never "the agent": a tree carries no marker for which that is, a guess fails+ on Windows' `cmd → node` shims, and the largest is what a reader wants when a total looks high. Say+ "processes", never "MCP": a plain `npm run dev` has them too. A name is untrusted text (a process+ can retitle itself, on an SSH host it may be another user's): `processLabel` cleans it, and cuts+ only an ABSOLUTE path to its file name, because `npm exec @playwright/mcp@latest` is a title.+- **The report says which measure it is in** (`SessionMemoryReport.metric`: `footprint` / `rss` /+ `working-set`), and the panel prints it, because the three disagree enormously for one process.+ MEASURED on a Mac: one Claude session of 7 processes is 751 MB in the panel, 751 MB in Apple's+ `footprint -p … ` run over all seven ("Summary Footprint", shared memory counted once; 620 MB of it+ compressed or swapped), and 148 MB as a `ps` rss sum; one idle MCP `node` is 242 MB of footprint and+ 4 MB of rss. So comparing a row with `ps`, or with `footprint <claude pid>` alone, reads as the+ panel over-reporting by 2.7× when it is not. An SSH host is always `rss`, a macOS host included+ (no `top` there), which is why the metric is reported rather than derived from the viewer's platform.+- **A reading says when it was taken.** The sweep runs on open and on ⟳ only (the cadence rule below),+ so an open panel ages. `measuredAt` is stamped on arrival by this machine's clock; the foot reads+ "Measured 3m ago", and "Measuring…" while the old rows wait for a new reading. Its 15 s tick+ re-renders that line and reads nothing.- **The cadence split follows the cost.** A **local** scope polls the pill's number every 30 s(`HOST_POLL_MS`, one file read, free). An **SSH** scope is **never polled**: one read on scopeentry, one when that project's ControlMaster comes up (an SSH project is opened before its masterdiff --git a/docs/session-memory.md b/docs/session-memory.mdindex e338baeb2..79ac6bfe6 100644--- a/docs/session-memory.md+++ b/docs/session-memory.md@@ -177,14 +177,35 @@ assumption — a hard-coded 4096 under-reports **4×** on a 16 KiB-page arm64 ke64 KiB-page enterprise arm64 builds (it would print 40 MB for a 640 MB session). Do not "optimise"this back to `statm`.-Non-Linux (and an unreadable `/proc`) falls through to one `ps -eo pid,ppid,rss` call, through the-same injectable seam as tmux — nothing in `session-memory.ts` reaches a subprocess around it.+Non-Linux (and an unreadable `/proc`) falls through to one `ps -eo pid,ppid,rss,comm` call, through+the same injectable seam as tmux — nothing in `session-memory.ts` reaches a subprocess around it.`rollupTree` walks each pane pid's descendants with a `seen` guard (a table captured while pids arerecycling can present a cyclic ppid chain, and a sweep that hangs is worse than one thatunder-reports). **`childCount` counts EVERY descendant**, the agent CLI included: `pane_pid` is the-pane's *shell*, so a claude session with two MCP servers reports **3**. The panel therefore says-"child processes", never "MCP" — a plain `npm run dev` has children too.+pane's *shell*, so a claude session with two MCP servers reports **3**.++A row's number is that whole tree. The line under it is how the tree splits: `claude 538 MB · 14+other processes 1.2 GB`, two parts that add up to the row. It names the LARGEST process in the tree,+which is usually the agent CLI and is what a reader wants either way when a total looks high. It says+"processes", never "MCP": a plain `npm run dev` has them too.++### Comparing the panel with other tools++The panel reports its measure (`metric`) and the time of the reading. A row is a tree SUM, so compare+it with a sum in the same measure, on the same processes:++| Session of 7 processes, measured on a Mac | |+|---|---|+| The panel | 751 MB |+| `footprint -p <pid> -p <pid> …` for all seven, "Summary Footprint" | 751 MB, 620 MB of it compressed or swapped |+| `footprint <claude pid>` alone | 232 MB |+| `ps` rss, summed | 148 MB |++`rss` leaves compressed pages out, and an idle process is mostly compressed: one idle MCP `node`+measured 242 MB of footprint and 4 MB of rss. A panel figure far above `ps` is therefore normal on+macOS. An SSH host is the exception: it is read with `ps`, so its rows are rss on a macOS host too,+and the panel says so.`list-panes -a` emits one line per **pane**, so the first pane of a session wins in both legs (samekey, same order) — one session is one row.@@ -598,9 +619,10 @@ Layout and theming (argued from CSS only)18. fitView / goToNode must no longer tuck nodes under the pill.Rows, travel and the panel itself-19. A `claude` node with 2 MCP servers must read `+3 child processes`, not +2: `pane_pid` is the- pane's SHELL, so the count includes the agent CLI itself. This is the ONLY item that can- falsify the "reports 3" claim made twice above; everything else about the sub-line is arithmetic.+19. A `claude` node with 2 MCP servers must read `claude … · 3 other processes …`: `pane_pid` is the+ pane's SHELL, so the tree is 4 processes and the 3 others are the shell and both servers. This is+ the ONLY item that can falsify the "reports 3" claim above; the rest of the sub-line is arithmetic.+ The two sizes on it must add up to the row's number, give or take rounding.20. Travel to a row whose node lives in a CLOSED project: the tab must REOPEN and the camera land onthe node. This is the likeliest thing on the list to be wrong — the load and the focus happen inthe same tick, and `travelToNode` (not `focusNodeById`) is what handles it.diff --git a/src/core/session-memory-remote.test.ts b/src/core/session-memory-remote.test.tsindex 62febfe7c..9115f3130 100644--- a/src/core/session-memory-remote.test.ts+++ b/src/core/session-memory-remote.test.ts@@ -226,6 +226,10 @@ describe('remoteSessionMemoryCommand under /bin/sh', () => {// The pane pid was resolved against the REAL process table: a live shell plus its children.// A 0 here would mean the rollup never found the pid, which is the failure worth catching.expect(r.rows[0].totalMb).toBeGreaterThan(0)+ // The name column comes back through the real `ps`, on whatever this host's ps prints.+ expect(r.rows[0].largestName).toBeTruthy()+ // An SSH host is read with `ps` whatever it runs, so the panel must not say footprint.+ expect(r.metric).toBe('rss')// Never assert `mem` unconditionally: this repo is maintained from macOS, which has no// /proc/meminfo, so a bare `not.toBeNull()` turns `npm test` red there — and contradicts the// sibling test below, which asserts that exact absence is fine.diff --git a/src/core/session-memory-remote.ts b/src/core/session-memory-remote.tsindex 0a3b176cb..95ce55d42 100644--- a/src/core/session-memory-remote.ts+++ b/src/core/session-memory-remote.ts@@ -52,8 +52,10 @@ const SWEEP_SOCKETS: readonly string[] = [TMUX_SOCKET, RMT_TMUX_SOCKET]* `echo`, so the command still exits 0 for the shell's exit-code gate.* - The socket names and the `-F` format come from the shared constants, so the remote sweep can* never look at a different socket, or ask for different fields, than the local one.- * - `ps -eo pid,ppid,rss` is used even on Linux hosts: it is one process instead of thousands of- * /proc reads over a link we do not control, and its output is what we already parse.+ * - `ps -eo pid,ppid,rss,comm` is used even on Linux hosts: it is one process instead of thousands+ * of /proc reads over a link we do not control, and its output is what we already parse. So an+ * SSH host's numbers are always rss, on a macOS host too (no `top` footprint here), and the+ * report says so (`metric`).*/export function remoteSessionMemoryCommand(): string {const listPanes = (socket: string): string => fencedListPanesCommand(socket)@@ -67,7 +69,7 @@ export function remoteSessionMemoryCommand(): string {`echo '${PANES}'`,...SWEEP_SOCKETS.map(listPanes),`echo '${PROCS}'`,- `ps -eo pid,ppid,rss 2>/dev/null || true`+ `ps -eo pid,ppid,rss,comm 2>/dev/null || true`].join('\n')}@@ -186,7 +188,7 @@ export function parseRemoteSessionMemory(stdout: string): SessionMemoryReport {// session is one row, exactly as the local leg's `bySession` map guarantees.const bySession = new Map<string, PaneRef>()for (const p of panes) if (!bySession.has(p.session)) bySession.set(p.session, p)- return buildReport([...bySession.values()], table, mem)+ return { ...buildReport([...bySession.values()], table, mem), metric: 'rss' }}/** Runs a POSIX sh command on the project's host; resolves stdout, or null if it could not run. */diff --git a/src/core/session-memory-service.test.ts b/src/core/session-memory-service.test.tsindex 05b3ffd86..310f095ca 100644--- a/src/core/session-memory-service.test.ts+++ b/src/core/session-memory-service.test.ts@@ -366,7 +366,8 @@ describe('mergeLocalLegs', () => {selfMb: t,childrenMb: 0,childCount: 0,- totalMb: t+ totalMb: t,+ largestMb: t})),mem: null,...extradiff --git a/src/core/session-memory-session-host.test.ts b/src/core/session-memory-session-host.test.tsindex 72a7c0338..834d94906 100644--- a/src/core/session-memory-session-host.test.ts+++ b/src/core/session-memory-session-host.test.ts@@ -253,11 +253,18 @@ describe('collectSessionHostMemory: the host\'s own cost', () => {it('an idle host (no sessions) is still measured', async () => {const r = await collectSessionHostMemory({+ platformName: 'win32',list: async () => listing({ names: [], sessions: [] }),readTable: async () => table.filter((e) => e.pid === 900 || e.pid === 901),readMem: () => MEM})- expect(r).toEqual({ ok: true, rows: [], mem: MEM, host: { pid: 900, selfMb: 60, consoleMb: 8, consoleCount: 1, totalMb: 68 } })+ expect(r).toEqual({+ ok: true,+ rows: [],+ mem: MEM,+ metric: 'working-set',+ host: { pid: 900, selfMb: 60, consoleMb: 8, consoleCount: 1, totalMb: 68 }+ })})it('with no session to describe, an unreadable table is still the "no sessions" answer', async () => {diff --git a/src/core/session-memory.test.ts b/src/core/session-memory.test.tsindex d3b525f2e..769b534b0 100644--- a/src/core/session-memory.test.ts+++ b/src/core/session-memory.test.ts@@ -6,10 +6,15 @@ import {parseProcessTable,parsePaneList,buildReport,+ collectSessionHostMemory,collectSessionMemory,+ defaultProcessTableReader,isNoServerError,- type ProcEntry+ processLabel,+ type ProcEntry,+ type SessionMemoryReport} from './session-memory'+import type { SessionHostListing } from './session-host-client'const P = (pid: number, ppid: number, rssKb: number): ProcEntry => ({ pid, ppid, rssKb })@@ -35,10 +40,40 @@ describe('indexProcesses + rollupTree', () => {selfMb: 0,childrenMb: 0,childCount: 0,- totalMb: 0+ totalMb: 0,+ largestMb: 0})})+ it('names the largest process wherever it sits in the tree, without taking it out of the total', () => {+ // The row's number is the whole tree, and the shell at its root is a few MB. What a reader+ // needs next is which process holds it: here a grandchild, not the pane's direct child.+ const { table, kids } = indexProcesses([+ { ...P(100, 1, 4 * 1024), name: '-zsh' },+ { ...P(200, 100, 500 * 1024), name: 'claude' },+ { ...P(300, 200, 900 * 1024), name: 'dart' }+ ])+ const r = rollupTree(table, kids, 100)+ expect(r.largestName).toBe('dart')+ expect(r.largestMb).toBe(900)+ expect(r.totalMb).toBe(1404)+ })++ it('can name the pane root itself: a pane started directly on the agent has no bigger child', () => {+ const { table, kids } = indexProcesses([+ { ...P(100, 1, 300 * 1024), name: 'claude' },+ { ...P(200, 100, 20 * 1024), name: 'node' }+ ])+ expect(rollupTree(table, kids, 100)).toMatchObject({ largestName: 'claude', largestMb: 300 })+ })++ it('reports the largest size with no name when the reader has none', () => {+ const { table, kids } = indexProcesses([P(100, 1, 1024), P(200, 100, 2048)])+ const r = rollupTree(table, kids, 100)+ expect(r.largestMb).toBe(2)+ expect(r.largestName).toBeUndefined()+ })+it('does not loop forever on a cyclic ppid chain', () => {// A pid whose parent chain points back at it must not hang the sweep.const { table, kids } = indexProcesses([P(100, 200, 1024), P(200, 100, 1024)])@@ -48,7 +83,53 @@ describe('indexProcesses + rollupTree', () => {})})+describe('processLabel', () => {+ it('reads an absolute path by its file name, spaces included', () => {+ expect(processLabel('/bin/zsh')).toBe('zsh')+ expect(processLabel('/Applications/Wow Keywords.app/Contents/MacOS/Wow Keywords')).toBe('Wow Keywords')+ })++ it('leaves a process title alone even when it holds a slash', () => {+ // macOS `ps` prints a retitled process verbatim. A basename here would print `mcp@latest`.+ expect(processLabel('npm exec @playwright/mcp@latest')).toBe('npm exec @playwright/mcp@latest')+ })++ it('drops the leading dash of a login shell', () => {+ expect(processLabel('-zsh')).toBe('zsh')+ })++ it('strips control and format characters: a process title is whatever the process set', () => {+ expect(processLabel('cla\u0007ude\u202e')).toBe('claude')+ })++ it('caps a long title', () => {+ const label = processLabel('x'.repeat(200)) as string+ expect(Array.from(label)).toHaveLength(40)+ expect(label.endsWith('…')).toBe(true)+ })++ it('answers nothing when there is nothing left to show', () => {+ expect(processLabel(undefined)).toBeUndefined()+ expect(processLabel('')).toBeUndefined()+ expect(processLabel('\u0007')).toBeUndefined()+ })+})+describe('parseProcessTable', () => {+ it('keeps the name column, spaces included', () => {+ const out = parseProcessTable(+ ' PID PPID RSS COMM\n 100 1 1024 /Applications/Wow Keywords.app/Contents/MacOS/Wow Keywords\n 200 100 2048 claude\n'+ )+ expect(out.map((e) => e.name)).toEqual([+ '/Applications/Wow Keywords.app/Contents/MacOS/Wow Keywords',+ 'claude'+ ])+ })++ it('still reads a three-column table, with no name', () => {+ expect(parseProcessTable('100 1 1024\n')[0].name).toBeUndefined()+ })+it('parses ps output and skips the header and malformed lines', () => {const out = parseProcessTable(' PID PPID RSS COMMAND\n' +@@ -57,8 +138,8 @@ describe('parseProcessTable', () => {' 200 100 358400 claude\n')expect(out).toEqual([- { pid: 100, ppid: 1, rssKb: 1024 },- { pid: 200, ppid: 100, rssKb: 358400 }+ { pid: 100, ppid: 1, rssKb: 1024, name: 'tmux' },+ { pid: 200, ppid: 100, rssKb: 358400, name: 'claude' }])})@@ -420,6 +501,30 @@ describe('collectSessionMemory on darwin', () => {}))+ it(+ 'asks ps for the process name, and says the rows are physical footprint',+ asDarwin(async () => {+ let psArgs: string[] = []+ const r = await collectSessionMemory({+ tmuxBin: () => '/usr/bin/tmux',+ sockets: ['s1'],+ exec: async (bin, args) => {+ if (bin.includes('tmux')) return 'nt-a|4242|claude\n'+ if (bin === 'ps') {+ psArgs = args+ return 'PID PPID RSS COMM\n4242 1 100000 -zsh\n'+ }+ return 'PID MEM \n4242 200000K'+ },+ readTable: undefined,+ readMem: () => null+ })+ expect(psArgs).toEqual(['-eo', 'pid,ppid,rss,comm'])+ expect(r.metric).toBe('footprint')+ expect(r.rows[0].largestName).toBe('zsh')+ })+ )+it('the "nodeterm itself" group reuses that SAME top read — footprint for a covered pid, nothing for a missed one',asDarwin(async () => {@@ -734,3 +839,42 @@ describe('appSelfMemory — "nodeterm itself"', () => {expect(await collectSessionMemory(base)).not.toHaveProperty('app')})})++describe('which memory measure the rows are in', () => {+ const report = (table: ProcEntry[]): Promise<SessionMemoryReport> =>+ collectSessionMemory({+ tmuxBin: () => '/usr/bin/tmux',+ sockets: ['s1'],+ exec: async () => 'nt-a|100|claude\n',+ readTable: () => table,+ readMem: () => null+ })++ it('says rss (working set on Windows) when the table carries no footprint', async () => {+ expect((await report([P(100, 1, 1024)])).metric).toBe(+ process.platform === 'win32' ? 'working-set' : 'rss'+ )+ })++ it('says footprint when it does', async () => {+ expect((await report([{ ...P(100, 1, 1024), footprint: true }])).metric).toBe('footprint')+ })++ it('says working set for a Windows session host', async () => {+ const r = await collectSessionHostMemory({+ platformName: 'win32',+ list: async () => ({ running: true, names: ['nt-a'], sessions: [{ name: 'nt-a', pid: 100 }] }) as SessionHostListing,+ readTable: async () => [{ ...P(100, 1, 1024), name: 'pwsh.exe' }],+ readMem: () => null+ })+ expect(r.metric).toBe('working-set')+ expect(r.rows[0].largestName).toBe('pwsh.exe')+ })+})++describe.skipIf(process.platform !== 'linux')('the Linux /proc reader', () => {+ it('carries each process name', () => {+ const me = defaultProcessTableReader()?.find((e) => e.pid === process.pid)+ expect(me?.name).toBeTruthy()+ })+})diff --git a/src/core/session-memory.ts b/src/core/session-memory.tsindex 95db5389d..6a5b92487 100644--- a/src/core/session-memory.ts+++ b/src/core/session-memory.ts@@ -19,6 +19,7 @@ import type {MemDisplay,MemInfo,SessionHostOverhead,+ SessionMemoryMetric,SessionMemoryRow,SessionMemoryReport} from '../shared/types'@@ -37,7 +38,8 @@ export interface ProcEntry {pid: numberppid: numberrssKb: number- /** Image name, when the reader has one (the Windows CIM table). Only `hostOverhead` reads it. */+ /** Raw process name, when the reader has one. `hostOverhead` matches Windows image names on it;+ * `rollupTree` shows it, through `processLabel`. */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@@ -80,9 +82,20 @@ export function rollupTree(table: ReadonlyMap<number, ProcEntry>,kids: ReadonlyMap<number, number[]>,root: number-): { selfMb: number; childrenMb: number; childCount: number; totalMb: number } {+): {+ selfMb: number+ childrenMb: number+ childCount: number+ totalMb: number+ largestMb: number+ largestName?: string+} {const self = table.get(root)- if (!self) return { selfMb: 0, childrenMb: 0, childCount: 0, totalMb: 0 }+ if (!self) return { selfMb: 0, childrenMb: 0, childCount: 0, totalMb: 0, largestMb: 0 }+ // The largest process, not "the agent": a pane's tree has no marker for which process that is, and+ // a guess fails on `cmd → node` shims on Windows. The largest one is true of any tree, and it names+ // what a reader is looking for when a total looks high, which is not always the agent.+ let largest = selflet childrenKb = 0let childCount = 0const seen = new Set<number>([root])@@ -95,14 +108,50 @@ export function rollupTree(if (!e) continuechildrenKb += e.rssKbchildCount+++ if (e.rssKb > largest.rssKb) largest = efor (const k of kids.get(pid) ?? []) stack.push(k)}const selfMb = kbToMb(self.rssKb)const childrenMb = kbToMb(childrenKb)- return { selfMb, childrenMb, childCount, totalMb: selfMb + childrenMb }+ const largestName = processLabel(largest.name)+ return {+ selfMb,+ childrenMb,+ childCount,+ totalMb: selfMb + childrenMb,+ largestMb: kbToMb(largest.rssKb),+ ...(largestName ? { largestName } : {})+ }}-/** Parse `ps -eo pid,ppid,rss` output. Tolerant: header and malformed lines are skipped. */+const PROCESS_LABEL_MAX = 40++/**+ * A process name as the panel prints it. It is untrusted text (a process can retitle itself, and on+ * an SSH host it may be another user's), so control and format characters go and the length is+ * capped. Only an ABSOLUTE path is cut to its file name: macOS `ps` prints a retitled process+ * verbatim, and `npm exec @playwright/mcp@latest` is a title with a slash in it, not a path.+ */+export function processLabel(raw: string | undefined): string | undefined {+ if (!raw) return undefined+ const clean = raw.replace(/[\p{Cc}\p{Cf}]/gu, '').trim()+ const base = clean.startsWith('/') ? clean.slice(clean.lastIndexOf('/') + 1) : clean+ // A login shell is `-zsh`.+ const points = Array.from(base.replace(/^-/, ''))+ if (points.length === 0) return undefined+ return points.length > PROCESS_LABEL_MAX+ ? `${points.slice(0, PROCESS_LABEL_MAX - 1).join('')}…`+ : points.join('')+}++/** The measure a table's numbers are in. `top` having covered any pid is what makes it footprint. */+function tableMetric(table: readonly ProcEntry[], platformName: NodeJS.Platform): SessionMemoryMetric {+ if (table.some((e) => e.footprint)) return 'footprint'+ return platformName === 'win32' ? 'working-set' : 'rss'+}++/** Parse `ps -eo pid,ppid,rss,comm` output. Tolerant: header and malformed lines are skipped, and+ * the name column is optional. A name may hold spaces, so it is everything after the third field. */export function parseProcessTable(stdout: string): ProcEntry[] {const out: ProcEntry[] = []for (const line of stdout.split('\n')) {@@ -112,7 +161,8 @@ export function parseProcessTable(stdout: string): ProcEntry[] {const ppid = Number(parts[1])const rssKb = Number(parts[2])if (!Number.isFinite(pid) || !Number.isFinite(ppid) || !Number.isFinite(rssKb)) continue- out.push({ pid, ppid, rssKb })+ const name = parts.slice(3).join(' ')+ out.push({ pid, ppid, rssKb, ...(name ? { name } : {}) })}return out}@@ -522,7 +572,8 @@ export function defaultProcessTableReader(): ProcEntry[] | null {const rssKb = Number(/^VmRSS:\s+(\d+)/m.exec(status)?.[1])// Kernel threads have no VmRSS and are dropped here — they are never pane descendants.if (!Number.isFinite(ppid) || !Number.isFinite(rssKb)) continue- out.push({ pid: Number(name), ppid, rssKb })+ const comm = /^Name:\s+(.+)$/m.exec(status)?.[1]+ out.push({ pid: Number(name), ppid, rssKb, ...(comm ? { name: comm } : {}) })} catch {// The process exited between readdir and read — skip it, never fail the sweep.}@@ -572,7 +623,7 @@ async function psProcessTable(platformName: NodeJS.Platform): Promise<ProcEntry[] | null> {try {- const rows = parseProcessTable(await exec('ps', ['-eo', 'pid,ppid,rss']))+ const rows = parseProcessTable(await exec('ps', ['-eo', 'pid,ppid,rss,comm']))if (platformName !== 'darwin') return rowsconst 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@@ -852,7 +903,10 @@ export async function collectSessionHostMemory(deps: SessionHostMemoryDeps): Proif (panes.length === 0) return withApp(withUnmeasured({ ok: true, rows: [], mem }), null)return { ok: false, rows: [], mem }}- const report = withApp(withUnmeasured(buildReport(panes, table, mem)), table)+ const report = withApp(+ withUnmeasured({ ...buildReport(panes, table, mem), metric: tableMetric(table, platformName) }),+ 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@@ -915,7 +969,10 @@ 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 }- const report = buildReport([...bySession.values()], table, mem)+ const report = {+ ...buildReport([...bySession.values()], table, mem),+ metric: tableMetric(table, process.platform)+ }// Same table, no second read: on darwin it already carries `top`'s footprint for EVERY pid,// Electron's included (reuse the sweep; the pill never polls `top`).if (!deps.appProcesses) return reportdiff --git a/src/renderer/components/SessionMemoryPanel.test.tsx b/src/renderer/components/SessionMemoryPanel.test.tsxindex deece9003..02d5963ac 100644--- a/src/renderer/components/SessionMemoryPanel.test.tsx+++ b/src/renderer/components/SessionMemoryPanel.test.tsx@@ -30,6 +30,7 @@ const row = (over: Partial<SessionMemoryRow> & { nodeId: string }): SessionMemorchildrenMb: 0,childCount: 0,totalMb: 0,+ largestMb: over.totalMb ?? 0,command: 'bash',...over})@@ -46,7 +47,16 @@ const row = (over: Partial<SessionMemoryRow> & { nodeId: string }): SessionMemor* - `ghost` has no node anywhere — the actual orphan.*/const ROWS: SessionMemoryRow[] = [- row({ nodeId: 't1', selfMb: 600, childrenMb: 300, childCount: 2, totalMb: 900, command: 'claude' }),+ row({+ nodeId: 't1',+ selfMb: 600,+ childrenMb: 300,+ childCount: 2,+ totalMb: 900,+ largestMb: 600,+ largestName: 'claude',+ command: 'claude'+ }),row({ nodeId: 't3', selfMb: 500, totalMb: 500, command: 'codex' }),row({ nodeId: 't2', selfMb: 120, totalMb: 120, command: 'bash' }),row({ nodeId: 'ghost', selfMb: 40, totalMb: 40, command: 'zsh' })@@ -256,13 +266,15 @@ describe('SessionMemoryPanel', () => {expect(onGoToNode).not.toHaveBeenCalled()})- it('names the extra processes as CHILD processes, not as MCP servers', () => {+ it('splits a row into its largest process and the rest, so the two add up to the row', () => {mount()- // `childCount` counts every descendant of the pane — the agent CLI itself plus whatever it- // spawned — because `pane_pid` is the pane's SHELL. Calling them MCP servers would miscount- // (claude + 2 MCP servers reads as 3) and mislabel a plain `npm run dev`.+ // The row's own number is the whole tree. The line under it used to print `childrenMb`, which+ // is that same tree minus a few MB of shell, so "claude 1.7 GB" sat on top of "+14 child+ // processes 1.7 GB" and read as two separate sizes (field report, 2026-11-04).const kids = rowsOf()[0].querySelector('.sessmem-row__kids')?.textContent ?? ''- expect(kids).toContain('2 child processes')+ expect(kids).toContain('claude')+ expect(kids).toContain('600.0 MB')+ expect(kids).toContain('2 other processes')expect(kids).toContain('300.0 MB')expect(text()).not.toContain('MCP')// Only the row that has children gets the sub-line.@@ -548,4 +560,65 @@ describe('SessionMemoryPanel', () => {expect(appBlock()).toBeNull()})})++ it('says "1 other process" in the singular', () => {+ mount({ rows: [row({ nodeId: 't1', childCount: 1, totalMb: 300, largestMb: 296, largestName: 'claude' })] })+ expect(rowsOf()[0].querySelector('.sessmem-row__kids')?.textContent).toContain('1 other process ')+ })++ it('falls back to a generic label when the process table carried no name', () => {+ mount({ rows: [row({ nodeId: 't1', childCount: 3, totalMb: 300, largestMb: 200 })] })+ expect(rowsOf()[0].querySelector('.sessmem-row__kids')?.textContent).toContain('Largest process')+ })++ it('titles the row total as the whole tree, not the command printed beside it', () => {+ mount()+ expect(rowsOf()[0].querySelector('.sessmem-row__mb')?.getAttribute('title')).toContain('whole session')+ })++ it.each([+ ['footprint', 'Activity Monitor'],+ ['rss', 'resident memory'],+ ['working-set', 'Task Manager']+ ] as const)('names the measure the rows are in: %s', (metric, phrase) => {+ mount({ metric })+ expect(host.querySelector('.sessmem-panel__attrib')?.textContent).toContain(phrase)+ })++ it('claims no measure when the report named none', () => {+ mount({ metric: undefined })+ expect(host.querySelector('.sessmem-panel__attrib')?.textContent).not.toContain('process tree')+ })++ describe('when the numbers were measured', () => {+ const when = (): string | null | undefined =>+ host.querySelector('.sessmem-panel__when')?.textContent++ it('says how old they are', () => {+ mount({ measuredAt: Date.now() - 5 * 60_000 })+ expect(when()).toBe('Measured 5m ago')+ })++ it('keeps counting while the panel stays open: nothing re-measures on its own', () => {+ vi.useFakeTimers()+ try {+ mount({ measuredAt: Date.now() })+ expect(when()).toBe('Measured just now')+ act(() => vi.advanceTimersByTime(3 * 60_000))+ expect(when()).toBe('Measured 3m ago')+ } finally {+ vi.useRealTimers()+ }+ })++ it('says a new reading is on its way while the old rows are still on screen', () => {+ mount({ measuredAt: Date.now() - 5 * 60_000, loading: true })+ expect(when()).toBe('Measuring…')+ })++ it('stays silent before anything was measured', () => {+ mount({ ok: false, rows: [], measuredAt: null })+ expect(when()).toBeFalsy()+ })+ })})diff --git a/src/renderer/components/SessionMemoryPanel.tsx b/src/renderer/components/SessionMemoryPanel.tsxindex c422267aa..77db20aab 100644--- a/src/renderer/components/SessionMemoryPanel.tsx+++ b/src/renderer/components/SessionMemoryPanel.tsx@@ -25,7 +25,8 @@ import {} from '../lib/sessionMemoryRows'import { usageScopeKey } from '../lib/usageScope'import type { SessionPauseOffer } from '../lib/sessionPause'-import { unmeasuredNote } from '../lib/sessionMemoryNote'+import { metricNote, unmeasuredNote } from '../lib/sessionMemoryNote'+import { formatTimeAgo } from '../lib/usageFormat'export interface SessionMemoryPanelProps {/** Travel to the node behind a row. Canvas passes `travelToNode`, so a CLOSED project's tab is@@ -50,6 +51,9 @@ export interface SessionMemoryPanelProps {onClose: () => void}+/** The "Measured … ago" line reads in minutes, so this only has to keep up with those. */+const AGE_TICK_MS = 15_000+/** Every number in this feature is MB; `formatBytes` speaks bytes. One formatter, so the panel's* units read like the rest of the app. */function formatMb(mb: number): string {@@ -90,6 +94,8 @@ export function SessionMemoryPanel({const appSelf = useSessionMemory((s) => s.app)const loading = useSessionMemory((s) => s.loading)const loadedScope = useSessionMemory((s) => s.loadedScope)+ const metric = useSessionMemory((s) => s.metric)+ const measuredAt = useSessionMemory((s) => s.measuredAt)const refreshFull = useSessionMemory((s) => s.refreshFull)// EVERY project, closed ones included: `closeProject` keeps the project and its nodes on disk@@ -135,6 +141,14 @@ export function SessionMemoryPanel({}, [relay, scopeKey, activeProjectId, refreshFull])useEffect(() => sweep(), [sweep])+ // Re-renders the "Measured … ago" line, nothing else: no reading happens here. The panel is+ // unmounted while closed, so this only runs while someone is looking at it.+ const [, setAgeTick] = useState(0)+ useEffect(() => {+ const t = setInterval(() => setAgeTick((n) => n + 1), AGE_TICK_MS)+ return () => clearInterval(t)+ }, [])+// Have we got an answer for THIS machine yet? A `loadedScope` from the machine we just left says// nothing about this one, so it is compared, not merely checked for existence.const measured = ok && loadedScope === scopeKey@@ -188,7 +202,13 @@ export function SessionMemoryPanel({))}<span className="sessmem-row__cmd">{v.row.command}</span>- <span className="sessmem-row__mb">{formatMb(v.row.totalMb)}</span>+ {/* Beside the command name this reads as that process's size, and it is not. */}+ <span+ className="sessmem-row__mb"+ title="The whole session: the shell, the agent and every process it started"+ >+ {formatMb(v.row.totalMb)}+ </span></button>{/* The NON-destructive reclaim, deliberately to the LEFT of the `×`: on the host thiswas measured against, exiting the CLI returns 98.3% of a session's memory while the@@ -232,11 +252,14 @@ export function SessionMemoryPanel({<IconClose /></button>{v.row.childCount > 0 && (- // "child processes", NOT "MCP servers": `pane_pid` is the pane's SHELL, so the count- // is the agent CLI itself plus everything it spawned. A claude session with two MCP- // servers reads as 3, and a plain `npm run dev` has children too.+ // How the row's total splits, and the two parts add up to it. Not `childrenMb`: that+ // is the total minus a few MB of shell, so it printed the same number twice and read+ // as a second size. "processes", NOT "MCP servers": a plain `npm run dev` has them too.<div className="sessmem-row__kids">- └ +{v.row.childCount} child processes <span>{formatMb(v.row.childrenMb)}</span>+ └ {v.row.largestName ?? 'Largest process'} <span>{formatMb(v.row.largestMb)}</span>+ {' · '}+ {v.row.childCount} other {v.row.childCount === 1 ? 'process' : 'processes'}{' '}+ <span>{formatMb(Math.max(0, v.row.totalMb - v.row.largestMb))}</span></div>)}</li>@@ -290,7 +313,7 @@ export function SessionMemoryPanel({and quoting one here would age into a lie (docs/session-memory.md §1 has them). */}<div className="sessmem-panel__attrib">Memory held by each session's own processes — the agent CLI and what it spawned, not- nodeterm itself.+ nodeterm itself. {measured && metricNote(metric)}</div>{/* nodeterm's OWN processes, below the attribution line on purpose: they@@ -331,18 +354,27 @@ export function SessionMemoryPanel({<span className="sessmem-panel__count">{measured ? `${views.length} session${views.length === 1 ? '' : 's'}` : ''}</span>- {/* A relay tab has nothing to retry — the answer is a stub, not a failure. */}- {!relay && (- <button- className={`sessmem-panel__refresh${loading ? ' spin' : ''}`}- title="Re-measure"- aria-label="Re-measure"- disabled={loading}- onClick={sweep}- >- <IconReload />- </button>- )}+ <span className="sessmem-panel__foot-end">+ {/* The sweep runs on open and on ⟳ only, so an open panel ages. `loading` wins: the old+ rows stay on screen until the new reading lands. */}+ {measured && (loading || measuredAt !== null) && (+ <span className="sessmem-panel__when">+ {loading ? 'Measuring…' : `Measured ${formatTimeAgo(measuredAt as number)}`}+ </span>+ )}+ {/* A relay tab has nothing to retry — the answer is a stub, not a failure. */}+ {!relay && (+ <button+ className={`sessmem-panel__refresh${loading ? ' spin' : ''}`}+ title="Re-measure"+ aria-label="Re-measure"+ disabled={loading}+ onClick={sweep}+ >+ <IconReload />+ </button>+ )}+ </span></div></div>)diff --git a/src/renderer/lib/sessionMemoryNote.ts b/src/renderer/lib/sessionMemoryNote.tsindex 7d9adf9a1..c081f1833 100644--- a/src/renderer/lib/sessionMemoryNote.ts+++ b/src/renderer/lib/sessionMemoryNote.ts@@ -1,3 +1,20 @@+import type { SessionMemoryMetric } from '@shared/types'++/**+ * What the numbers are, per measure. It has to be said: a user comparing a row against `ps` or a+ * single process in `footprint` gets a smaller number and reads the panel as wrong (field report,+ * 2026-11-04: 1.7 GB here, 538 MB for claude alone, 635 MB of tree rss).+ */+export function metricNote(metric: SessionMemoryMetric | undefined): string {+ if (metric === 'footprint')+ return 'Each row adds up its whole process tree, by physical footprint as in Activity Monitor. That includes compressed memory, so ps shows less.'+ if (metric === 'working-set')+ return 'Each row adds up its whole process tree, by working set as in Task Manager. Memory that was paged out is not counted.'+ if (metric === 'rss')+ return 'Each row adds up its whole process tree, by resident memory (RSS). Memory that was compressed or swapped out is not counted.'+ return ''+}+/** The sentence for live sessions the sweep could not measure: Zellij-backed ones (the sweep reads* tmux), or — `backend: 'session-host'` — sessions of a running session host older than this app,* which can name its sessions but not describe their processes. */diff --git a/src/renderer/lib/sessionMemoryRows.test.ts b/src/renderer/lib/sessionMemoryRows.test.tsindex dd22252f9..d54b8bd9d 100644--- a/src/renderer/lib/sessionMemoryRows.test.ts+++ b/src/renderer/lib/sessionMemoryRows.test.ts@@ -10,6 +10,7 @@ const row = (nodeId: string, mb: number): SessionMemoryRow => ({childrenMb: 0,childCount: 0,totalMb: mb,+ largestMb: mb,command: 'claude'})diff --git a/src/renderer/state/sessionMemory.test.ts b/src/renderer/state/sessionMemory.test.tsindex b6fc282d0..28347dbb9 100644--- a/src/renderer/state/sessionMemory.test.ts+++ b/src/renderer/state/sessionMemory.test.ts@@ -179,3 +179,39 @@ describe('"nodeterm itself" group', () => {expect(useSessionMemory.getState().app).toBeUndefined()})})++describe('what a full sweep records about itself', () => {+ it('stamps when it landed and which measure it is in', async () => {+ vi.setSystemTime(5_000_000)+ read.mockResolvedValue({ ok: true, rows: [], mem: null, metric: 'footprint' })+ await useSessionMemory.getState().refreshFull('', 'p1')+ expect(useSessionMemory.getState().measuredAt).toBe(5_000_000)+ expect(useSessionMemory.getState().metric).toBe('footprint')+ })++ it('keeps no stamp from a sweep that could not run', async () => {+ read.mockResolvedValue({ ok: true, rows: [], mem: null, metric: 'rss' })+ await useSessionMemory.getState().refreshFull('', 'p1')+ read.mockResolvedValue({ ok: false, rows: [], mem: null })+ await useSessionMemory.getState().refreshFull('', 'p1')+ expect(useSessionMemory.getState().measuredAt).toBeNull()+ expect(useSessionMemory.getState().metric).toBeUndefined()+ })++ it('keeps no stamp from a rejected call', async () => {+ read.mockResolvedValue({ ok: true, rows: [], mem: null, metric: 'rss' })+ await useSessionMemory.getState().refreshFull('', 'p1')+ read.mockRejectedValue(new Error('bridge down'))+ await useSessionMemory.getState().refreshFull('', 'p1')+ expect(useSessionMemory.getState().measuredAt).toBeNull()+ })++ it("drops another machine's stamp when the scope changes", async () => {+ read.mockResolvedValue({ ok: true, rows: [], mem: null, metric: 'footprint' })+ await useSessionMemory.getState().refreshFull('', 'p1')+ useSessionMemory.getState().startHostPoll('user@host', 'p2')+ await flush()+ expect(useSessionMemory.getState().measuredAt).toBeNull()+ expect(useSessionMemory.getState().metric).toBeUndefined()+ })+})diff --git a/src/renderer/state/sessionMemory.ts b/src/renderer/state/sessionMemory.tsindex 8eb117834..c25098ccf 100644--- a/src/renderer/state/sessionMemory.ts+++ b/src/renderer/state/sessionMemory.ts@@ -15,6 +15,7 @@ import type {MemInfo,SessionHostOverhead,SessionMemoryApi,+ SessionMemoryMetric,SessionMemoryQuery,SessionMemoryRow} from '@shared/types'@@ -35,6 +36,11 @@ interface SessionMemoryState {/** nodeterm's own processes (SessionMemoryReport.app); absent = not available on this surface. */app?: AppSelfMemorymem: MemInfo | null+ /** The measure `rows` are in (SessionMemoryReport.metric). */+ metric?: SessionMemoryMetric+ /** When the rows on screen were measured; null when nothing has been. This machine's clock, set+ * on arrival, so a host's clock never enters it. */+ measuredAt: number | nullloading: boolean/** Scope key the current rows belong to; null before the first successful load. */loadedScope: string | null@@ -76,6 +82,7 @@ export const useSessionMemory = create<SessionMemoryState>((set, get) => ({rows: [],unmeasured: 0,mem: null,+ measuredAt: null,loading: false,loadedScope: null,@@ -103,6 +110,8 @@ export const useSessionMemory = create<SessionMemoryState>((set, get) => ({ok: r.ok,rows: r.rows,mem: r.mem,+ metric: r.ok ? r.metric : undefined,+ measuredAt: r.ok ? Date.now() : null,unmeasured: r.unmeasured ?? 0,unmeasuredBackend: r.unmeasuredBackend,host: r.ok ? r.host : undefined,@@ -113,7 +122,16 @@ export const useSessionMemory = create<SessionMemoryState>((set, get) => ({// 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, app: undefined })+ set({+ ok: false,+ rows: [],+ metric: undefined,+ measuredAt: null,+ 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.@@ -163,6 +181,8 @@ function enterScope(scopeKey: string, set: SetState): void {host: undefined,app: undefined,mem: null,+ metric: undefined,+ measuredAt: null,loading: false,loadedScope: null})diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 3f5bb6498..ec8da53d7 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -9573,6 +9573,11 @@ button.group-node__setup:disabled {font-size: 11px;color: rgba(var(--tint-rgb), 0.5);}+.sessmem-panel__foot-end {+ display: inline-flex;+ align-items: center;+ gap: 8px;+}.sessmem-panel__refresh {display: inline-flex;align-items: center;diff --git a/src/session-host/process-tree.ts b/src/session-host/process-tree.tsindex d8116b547..f4a626511 100644--- a/src/session-host/process-tree.ts+++ b/src/session-host/process-tree.ts@@ -9,10 +9,10 @@ import { getWindowsProbeWorker, type WindowsProbeWorker } from './windows-probe-* WALKS THE DESCENDANTS of the pty's own child pid and reports the deepest live one.** This is a deliberately small, standalone reader rather than a reuse of- * `src/core/session-memory.ts`'s process-table reader: that module queries `pid,ppid,rss` (for- * memory accounting) and has no Windows branch at all yet, so there is nothing here to actually- * reuse without querying a THIRD column (`comm`/`Name`) it does not fetch — this is the "cannot,- * so wrote a second (much smaller) one" case CLAUDE.md's guidance for this task allows for.+ * `src/core/session-memory.ts`'s process-table reader: that module reads a whole table for memory+ * accounting (rss, plus `top` on macOS), which costs more than this one question needs — this is+ * the "cannot, so wrote a second (much smaller) one" case CLAUDE.md's guidance for this task allows+ * for.** The in-place agent restart feature (CLAUDE.md, "Restart agent (resume)") only cares about ONE* distinction — "is a SHELL back in charge of this pane, or is something else still running" — sodiff --git a/src/shared/types.ts b/src/shared/types.tsindex 913aa98cb..60e957b08 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3292,11 +3292,25 @@ export interface SessionMemoryRow {/** Everything below it (MCP servers, headless browsers, …). */childrenMb: numberchildCount: number+ /** The whole tree: the pane's own process plus everything below it. */totalMb: number+ /** The biggest single process in the tree, pane process included. Part of `totalMb`. */+ largestMb: number+ /** Its name, cleaned for display (`processLabel`). Absent when the table carried no name. */+ largestName?: string/** `#{pane_current_command}` — the agent/shell label. */command: string}+/**+ * What a sweep's numbers are, because the three measures answer differently for the same process:+ * on a Mac an idle MCP server measured 242 MB of footprint and 4 MB of rss (most of it compressed).+ * - `footprint`: macOS phys_footprint, Activity Monitor's "Memory" column;+ * - `rss`: resident memory: Linux, and every SSH host, which is read with `ps` whatever it runs;+ * - `working-set`: Windows, Task Manager's "Working set" column.+ */+export type SessionMemoryMetric = 'footprint' | 'rss' | 'working-set'+/*** `ok: false` means the sweep could not run (no tmux binary, unreadable process table). It is NOT* the same as an empty `rows` with `ok: true`, which means "we looked and there are no sessions".@@ -3307,6 +3321,8 @@ export interface SessionMemoryReport {ok: booleanrows: SessionMemoryRow[]mem: MemInfo | null+ /** The measure `rows` are in. Absent when the sweep read no process table. */+ metric?: SessionMemoryMetric/*** Live nodeterm sessions on this machine that the sweep could NOT measure — today, Zellij-backed* ones (the sweep reads tmux). Absent/0 = none. `null` = could not tell. Local scope only. The