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(core): process-table reader and per-pane tree rollup
enese627a9e96c98
diff --git a/src/core/session-budget.ts b/src/core/session-budget.tsindex 80d5b838d..032199458 100644--- a/src/core/session-budget.ts+++ b/src/core/session-budget.ts@@ -21,15 +21,19 @@// Electron-free (src/core): all exec/mem/clock access is behind injectable seams (template:// ack-sweep.ts), so both shells boot it and tests drive it without touching tmux.-import fs from 'fs'import os from 'os'import { execFile } from 'child_process'import { promisify } from 'util'import { TMUX_SOCKET } from './tmux-naming'import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'+import { readMemInfo, type MemInfo } from './session-memory'const runAsync = promisify(execFile)+// One definition, two consumers (the reaper's watermark and the system-resource pill): a copied+// second reader would let them disagree about how much RAM is free.+export { readMemInfo, type MemInfo } from './session-memory'+/** One tmux session as reported by `list-sessions`. `activitySec` is epoch seconds. */export interface SessionInfo {name: string@@ -37,12 +41,6 @@ export interface SessionInfo {activitySec: number}-/** Host memory snapshot in MB. `null` from a reader means "could not read" — see planReap. */-export interface MemInfo {- availableMb: number- totalMb: number-}-export interface SessionBudgetConfig {/** Kill switch (`NODETERM_SESSION_REAP_DISABLED=1`): sweeps become no-ops. */disabled: boolean@@ -122,26 +120,6 @@ export function parseSessionList(stdout: string): SessionInfo[] {return out}-/** Linux `/proc/meminfo` (MemAvailable is the honest number); `os.freemem()` fallback elsewhere.- * Returns null when nothing readable — the policy treats that as "no pressure signal". */-export function readMemInfo(): MemInfo | null {- try {- const text = fs.readFileSync('/proc/meminfo', 'utf8')- const avail = /MemAvailable:\s+(\d+)\s*kB/.exec(text)- const total = /MemTotal:\s+(\d+)\s*kB/.exec(text)- if (avail && total) {- return { availableMb: Math.round(Number(avail[1]) / 1024), totalMb: Math.round(Number(total[1]) / 1024) }- }- } catch {- // fall through to the os fallback- }- try {- return { availableMb: Math.round(os.freemem() / 1048576), totalMb: Math.round(os.totalmem() / 1048576) }- } catch {- return null- }-}-export interface SessionReaperOpts {/** Lazy tmux binary resolver (PtyManager resolves after init; null = tmux unavailable → no-op). */tmuxBin: () => string | nulldiff --git a/src/core/session-memory.test.ts b/src/core/session-memory.test.tsnew file mode 100644index 000000000..5561b64da--- /dev/null+++ b/src/core/session-memory.test.ts@@ -0,0 +1,58 @@+import { describe, it, expect } from 'vitest'+import { indexProcesses, rollupTree, parseProcessTable, type ProcEntry } from './session-memory'++const P = (pid: number, ppid: number, rssKb: number): ProcEntry => ({ pid, ppid, rssKb })++describe('indexProcesses + rollupTree', () => {+ it('sums a pane pid and every descendant, splitting self from children', () => {+ // pane(100) -> claude(200) -> mcp(300), and claude also has mcp2(301)+ const { table, kids } = indexProcesses([+ P(100, 1, 1024),+ P(200, 100, 350 * 1024),+ P(300, 200, 30 * 1024),+ P(301, 200, 20 * 1024)+ ])+ const r = rollupTree(table, kids, 100)+ expect(r.selfMb).toBe(1)+ expect(r.childrenMb).toBe(400)+ expect(r.childCount).toBe(3)+ expect(r.totalMb).toBe(401)+ })++ it('returns zeros for a pid that is not in the table', () => {+ const { table, kids } = indexProcesses([P(100, 1, 1024)])+ expect(rollupTree(table, kids, 999)).toEqual({+ selfMb: 0,+ childrenMb: 0,+ childCount: 0,+ totalMb: 0+ })+ })++ 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)])+ const r = rollupTree(table, kids, 100)+ expect(r.totalMb).toBe(2)+ expect(r.childCount).toBe(1)+ })+})++describe('parseProcessTable', () => {+ it('parses ps output and skips the header and malformed lines', () => {+ const out = parseProcessTable(+ ' PID PPID RSS COMMAND\n' ++ ' 100 1 1024 tmux\n' ++ 'garbage line\n' ++ ' 200 100 358400 claude\n'+ )+ expect(out).toEqual([+ { pid: 100, ppid: 1, rssKb: 1024 },+ { pid: 200, ppid: 100, rssKb: 358400 }+ ])+ })++ it('returns an empty array for empty input rather than throwing', () => {+ expect(parseProcessTable('')).toEqual([])+ })+})diff --git a/src/core/session-memory.ts b/src/core/session-memory.tsnew file mode 100644index 000000000..eb34ab5eb--- /dev/null+++ b/src/core/session-memory.ts@@ -0,0 +1,121 @@+// Per-session memory accounting: which nt- tmux session is holding how much RSS, including the+// agent CLI's own children (MCP servers, headless browsers).+//+// The measurement a user actually asks about is the PROCESS TREE under a pane, not the pane's own+// process: a `claude` session is ~335 MB itself but routinely carries 30-200 MB of MCP children,+// and a report that named only the pane would understate it by a third.+//+// Electron-free (src/core): every fs/exec access is behind an injectable seam (template:+// session-budget.ts), so both shells boot it and tests drive it without touching /proc or tmux.++import fs from 'fs'+import os from 'os'+import type { MemInfo } from '../shared/types'++export type { MemInfo }++/** One process from the host's table. `rssKb` is resident set size in kB. Core-internal: it never+ * crosses the wire, so it does not belong in shared/types. */+export interface ProcEntry {+ pid: number+ ppid: number+ rssKb: number+}++/** Reads the whole process table at once; null when it could not run. */+export type ProcessTableReader = () => ProcEntry[] | null++const kbToMb = (kb: number): number => Math.round(kb / 1024)++/** Index a flat table into pid→entry plus ppid→children, so a tree walk is O(nodes). */+export function indexProcesses(entries: readonly ProcEntry[]): {+ table: Map<number, ProcEntry>+ kids: Map<number, number[]>+} {+ const table = new Map<number, ProcEntry>()+ const kids = new Map<number, number[]>()+ for (const e of entries) {+ table.set(e.pid, e)+ const list = kids.get(e.ppid)+ if (list) list.push(e.pid)+ else kids.set(e.ppid, [e.pid])+ }+ return { table, kids }+}++/**+ * Total RSS of `root` and every descendant, split into the pane's own process and everything+ * below it (which is what the panel's `└ +N MCP` sub-line reports).+ *+ * A `seen` set guards the walk: a process table captured while pids are being recycled can+ * present a cyclic ppid chain, and a sweep that hangs is worse than one that under-reports.+ */+export function rollupTree(+ table: ReadonlyMap<number, ProcEntry>,+ kids: ReadonlyMap<number, number[]>,+ root: number+): { selfMb: number; childrenMb: number; childCount: number; totalMb: number } {+ const self = table.get(root)+ if (!self) return { selfMb: 0, childrenMb: 0, childCount: 0, totalMb: 0 }+ let childrenKb = 0+ let childCount = 0+ const seen = new Set<number>([root])+ const stack = [...(kids.get(root) ?? [])]+ while (stack.length > 0) {+ const pid = stack.pop() as number+ if (seen.has(pid)) continue+ seen.add(pid)+ const e = table.get(pid)+ if (!e) continue+ childrenKb += e.rssKb+ childCount+++ for (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 }+}++/** Parse `ps -eo pid,ppid,rss` output. Tolerant: header and malformed lines are skipped. */+export function parseProcessTable(stdout: string): ProcEntry[] {+ const out: ProcEntry[] = []+ for (const line of stdout.split('\n')) {+ const parts = line.trim().split(/\s+/)+ if (parts.length < 3) continue+ const pid = Number(parts[0])+ 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 })+ }+ return out+}++/** Linux `/proc/meminfo` (MemAvailable is the honest number); `os.freemem()` fallback elsewhere.+ * Returns null when nothing is readable — callers treat that as "no signal", never as zero.+ *+ * Lives here rather than in session-budget.ts because two features now read it (the reaper's+ * watermark and the system-resource pill) and a second copy would drift. */+export function readMemInfo(): MemInfo | null {+ try {+ const text = fs.readFileSync('/proc/meminfo', 'utf8')+ const avail = /MemAvailable:\s+(\d+)\s*kB/.exec(text)+ const total = /MemTotal:\s+(\d+)\s*kB/.exec(text)+ if (avail && total) {+ return {+ availableMb: Math.round(Number(avail[1]) / 1024),+ totalMb: Math.round(Number(total[1]) / 1024)+ }+ }+ } catch {+ // fall through to the os fallback+ }+ try {+ return {+ availableMb: Math.round(os.freemem() / 1048576),+ totalMb: Math.round(os.totalmem() / 1048576)+ }+ } catch {+ return null+ }+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 45de0f1f8..f10599e86 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1451,6 +1451,14 @@ export interface ProviderUsage {status: 'unavailable' | 'fetching' | 'ok' | 'error'}+/** Host memory snapshot in MB. `null` from any reader means "could not read" — never "zero".+ * Shared because it crosses the wire for the system-resource pill; core reads it, the renderer+ * renders it. */+export interface MemInfo {+ availableMb: number+ totalMb: number+}+/** Claude Code subscription usage snapshot for the bottom-left indicator. */export interface ClaudeUsage {/**