Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(core): assemble the local session-memory report

enes4aaee63a1f12
diff --git a/src/core/session-memory.test.ts b/src/core/session-memory.test.ts
index 5561b64da..62efaefa1 100644
--- a/src/core/session-memory.test.ts
+++ b/src/core/session-memory.test.ts
@@ -1,5 +1,13 @@
import { describe, it, expect } from 'vitest'
-import { indexProcesses, rollupTree, parseProcessTable, type ProcEntry } from './session-memory'
+import {
+ indexProcesses,
+ rollupTree,
+ parseProcessTable,
+ parsePaneList,
+ buildReport,
+ collectSessionMemory,
+ type ProcEntry
+} from './session-memory'
const P = (pid: number, ppid: number, rssKb: number): ProcEntry => ({ pid, ppid, rssKb })
@@ -56,3 +64,98 @@ describe('parseProcessTable', () => {
expect(parseProcessTable('')).toEqual([])
})
})
+
+describe('parsePaneList', () => {
+ it('parses the pipe-delimited pane list and skips malformed lines', () => {
+ expect(
+ parsePaneList('nt-term-a|100|claude\nbroken\nnt-term-b|200|zsh\n|300|x\n')
+ ).toEqual([
+ { session: 'nt-term-a', panePid: 100, command: 'claude' },
+ { session: 'nt-term-b', panePid: 200, command: 'zsh' }
+ ])
+ })
+})
+
+describe('buildReport', () => {
+ it('rolls up each nt- session and sorts by total descending', () => {
+ const r = buildReport(
+ [
+ { session: 'nt-small', panePid: 100, command: 'zsh' },
+ { session: 'nt-big', panePid: 200, command: 'claude' }
+ ],
+ [
+ P(100, 1, 40 * 1024),
+ P(200, 1, 350 * 1024),
+ P(201, 200, 50 * 1024)
+ ],
+ { availableMb: 1000, totalMb: 64000 }
+ )
+ expect(r.ok).toBe(true)
+ expect(r.rows.map((x) => x.session)).toEqual(['nt-big', 'nt-small'])
+ expect(r.rows[0]).toMatchObject({
+ nodeId: 'big',
+ totalMb: 400,
+ selfMb: 350,
+ childrenMb: 50,
+ childCount: 1,
+ command: 'claude'
+ })
+ })
+
+ it('ignores sessions that are not nt- prefixed', () => {
+ const r = buildReport(
+ [{ session: 'my-own-tmux', panePid: 100, command: 'zsh' }],
+ [P(100, 1, 40 * 1024)],
+ null
+ )
+ expect(r.rows).toEqual([])
+ })
+})
+
+describe('collectSessionMemory', () => {
+ const table = [P(100, 1, 40 * 1024), P(200, 1, 350 * 1024)]
+
+ it('reports ok:false with no rows when the process table cannot be read', async () => {
+ const r = await collectSessionMemory({
+ tmuxBin: () => '/usr/bin/tmux',
+ sockets: ['s1'],
+ exec: async () => 'nt-a|100|claude\n',
+ readTable: () => null,
+ readMem: () => ({ availableMb: 1, totalMb: 2 })
+ })
+ // "could not look" must never render as "uses nothing".
+ expect(r.ok).toBe(false)
+ expect(r.rows).toEqual([])
+ })
+
+ it('reports ok:true with no rows when tmux has no server (a real answer)', async () => {
+ const r = await collectSessionMemory({
+ tmuxBin: () => '/usr/bin/tmux',
+ sockets: ['s1'],
+ exec: async () => {
+ throw new Error('no server running')
+ },
+ readTable: () => table,
+ readMem: () => null
+ })
+ expect(r.ok).toBe(true)
+ expect(r.rows).toEqual([])
+ })
+
+ it('reports ok:false when tmux is unavailable entirely', async () => {
+ const r = await collectSessionMemory({ tmuxBin: () => null, readTable: () => table })
+ expect(r.ok).toBe(false)
+ })
+
+ it('merges panes from every socket and dedupes by session name', async () => {
+ const r = await collectSessionMemory({
+ tmuxBin: () => '/usr/bin/tmux',
+ sockets: ['s1', 's2'],
+ exec: async (_bin, args) =>
+ args[1] === 's1' ? 'nt-a|100|zsh\n' : 'nt-b|200|claude\nnt-a|100|zsh\n',
+ readTable: () => table,
+ readMem: () => null
+ })
+ expect(r.rows.map((x) => x.session).sort()).toEqual(['nt-a', 'nt-b'])
+ })
+})
diff --git a/src/core/session-memory.ts b/src/core/session-memory.ts
index eb34ab5eb..2be81177e 100644
--- a/src/core/session-memory.ts
+++ b/src/core/session-memory.ts
@@ -10,9 +10,15 @@
import fs from 'fs'
import os from 'os'
-import type { MemInfo } from '../shared/types'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import type { MemInfo, SessionMemoryRow, SessionMemoryReport } from '../shared/types'
+import { TMUX_SOCKET } from './tmux-naming'
+import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'
-export type { MemInfo }
+export type { MemInfo, SessionMemoryRow, SessionMemoryReport }
+
+const runAsync = promisify(execFile)
/** 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. */
@@ -45,7 +51,10 @@ export function indexProcesses(entries: readonly ProcEntry[]): {
/**
* 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).
+ * below it (which is what the panel's `└ +N child processes` sub-line reports).
+ *
+ * `childCount` counts EVERY descendant, the agent CLI included: `root` is the pane's SHELL, so a
+ * claude session with two MCP servers reports 3, not 2. Labelling it `+N MCP` would be a lie.
*
* 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.
@@ -119,3 +128,143 @@ export function readMemInfo(): MemInfo | null {
return null
}
}
+
+/** One tmux pane as reported by `list-panes -a`. Core-internal. */
+export interface PaneRef {
+ session: string
+ panePid: number
+ command: string
+}
+
+const PANE_FMT = '#{session_name}|#{pane_pid}|#{pane_current_command}'
+
+/** Parse `list-panes -a -F '<PANE_FMT>'`. Tolerant: malformed lines are skipped. */
+export function parsePaneList(stdout: string): PaneRef[] {
+ const out: PaneRef[] = []
+ for (const line of stdout.split('\n')) {
+ const parts = line.trim().split('|')
+ if (parts.length < 3) continue
+ const panePid = Number(parts[1])
+ if (!parts[0] || !Number.isFinite(panePid)) continue
+ out.push({ session: parts[0], panePid, command: parts[2] })
+ }
+ return out
+}
+
+/** Pure assembly: panes + a process table → sorted rows. Only `nt-` sessions are ours. */
+export function buildReport(
+ panes: readonly PaneRef[],
+ table: readonly ProcEntry[],
+ mem: MemInfo | null
+): SessionMemoryReport {
+ const { table: byPid, kids } = indexProcesses(table)
+ const rows: SessionMemoryRow[] = []
+ for (const p of panes) {
+ if (!p.session.startsWith('nt-')) continue
+ const t = rollupTree(byPid, kids, p.panePid)
+ rows.push({
+ session: p.session,
+ nodeId: p.session.slice('nt-'.length),
+ panePid: p.panePid,
+ command: p.command,
+ ...t
+ })
+ }
+ rows.sort((a, b) => b.totalMb - a.totalMb)
+ return { ok: true, rows, mem }
+}
+
+export interface SessionMemoryDeps {
+ /** Lazy tmux resolver (PtyManager resolves after init; null = tmux unavailable). */
+ tmuxBin: () => string | null
+ /** Sockets to sweep. Default: the local socket + the SSH-remote socket. */
+ sockets?: string[]
+ exec?: (bin: string, args: string[]) => Promise<string>
+ readTable?: ProcessTableReader
+ readMem?: () => MemInfo | null
+}
+
+/** Default reader: /proc on Linux (no subprocess), one `ps` call everywhere else. */
+export function defaultProcessTableReader(): ProcEntry[] | null {
+ if (process.platform === 'linux') {
+ try {
+ const out: ProcEntry[] = []
+ for (const name of fs.readdirSync('/proc')) {
+ if (!/^\d+$/.test(name)) continue
+ try {
+ const stat = fs.readFileSync(`/proc/${name}/stat`, 'utf8')
+ // The comm field is parenthesized and may contain spaces: split AFTER the last ')'.
+ const after = stat.slice(stat.lastIndexOf(')') + 2).split(' ')
+ const ppid = Number(after[1])
+ const statm = fs.readFileSync(`/proc/${name}/statm`, 'utf8').split(' ')
+ const rssPages = Number(statm[1])
+ if (!Number.isFinite(ppid) || !Number.isFinite(rssPages)) continue
+ out.push({ pid: Number(name), ppid, rssKb: (rssPages * 4096) / 1024 })
+ } catch {
+ // The process exited between readdir and read — skip it, never fail the sweep.
+ }
+ }
+ return out
+ } catch {
+ return null
+ }
+ }
+ return null // non-Linux falls through to the ps path in collectSessionMemory
+}
+
+/**
+ * One sweep. Failure rules (CLAUDE.md: a failed read is never evidence of absence):
+ * - no tmux binary, or an unreadable process table → `ok: false`, no rows;
+ * - a socket whose `list-panes` fails contributes NO panes but is NOT a failure — "no server
+ * running" is the normal answer for a socket nobody has used yet.
+ */
+export async function collectSessionMemory(
+ deps: SessionMemoryDeps
+): Promise<SessionMemoryReport> {
+ const readMem = deps.readMem ?? readMemInfo
+ const mem = readMem()
+ const bin = deps.tmuxBin()
+ if (!bin) return { ok: false, rows: [], mem }
+
+ const exec =
+ deps.exec ??
+ (async (b: string, args: string[]): Promise<string> => {
+ const { stdout } = await runAsync(b, args, { timeout: 15_000 })
+ return stdout
+ })
+
+ const readTable =
+ deps.readTable ??
+ ((): ProcEntry[] | null => {
+ const viaProc = defaultProcessTableReader()
+ if (viaProc) return viaProc
+ return null
+ })
+
+ let table = readTable()
+ if (table === null && !deps.readTable) {
+ // Non-Linux (or an unreadable /proc): one `ps` call for the whole table.
+ try {
+ const { stdout } = await runAsync('ps', ['-eo', 'pid,ppid,rss'], { timeout: 15_000 })
+ table = parseProcessTable(stdout)
+ } catch {
+ table = null
+ }
+ }
+ if (table === null) return { ok: false, rows: [], mem }
+
+ const sockets = deps.sockets ?? [TMUX_SOCKET, RMT_TMUX_SOCKET]
+ const bySession = new Map<string, PaneRef>()
+ for (const s of sockets) {
+ try {
+ const stdout = await exec(bin, ['-L', s, 'list-panes', '-a', '-F', PANE_FMT])
+ // First pane of a session wins: a session with several panes is still one row.
+ for (const p of parsePaneList(stdout))
+ if (!bySession.has(p.session)) bySession.set(p.session, p)
+ } catch {
+ // "no server running" and a real failure both land here; neither yields panes, and neither
+ // makes the whole sweep a failure — the other socket may well have answered.
+ }
+ }
+ return buildReport([...bySession.values()], table, mem)
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index f10599e86..d9034d55e 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1459,6 +1459,35 @@ export interface MemInfo {
totalMb: number
}
+/** One nt- session's memory, as the panel renders it. */
+export interface SessionMemoryRow {
+ /** tmux session name, `nt-<nodeId>`. */
+ session: string
+ /** The canvas node id — the session name minus the `nt-` prefix. */
+ nodeId: string
+ panePid: number
+ /** The pane's own process. */
+ selfMb: number
+ /** Everything below it (MCP servers, headless browsers, …). */
+ childrenMb: number
+ childCount: number
+ totalMb: number
+ /** `#{pane_current_command}` — the agent/shell label. */
+ command: string
+}
+
+/**
+ * `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".
+ * Collapsing the two would make the panel report "nothing is using memory" at exactly the moment
+ * it failed to measure.
+ */
+export interface SessionMemoryReport {
+ ok: boolean
+ rows: SessionMemoryRow[]
+ mem: MemInfo | null
+}
+
/** Claude Code subscription usage snapshot for the bottom-left indicator. */
export interface ClaudeUsage {
/**