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.

44.0 KB
Raw Blame
// 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 { execFile, execFileSync } from 'child_process'
import { promisify } from 'util'
import type {
  AppProcessKind,
  AppSelfGroup,
  AppSelfMemory,
  MemDisplay,
  MemInfo,
  SessionHostOverhead,
  SessionMemoryMetric,
  SessionMemoryRow,
  SessionMemoryReport
} from '../shared/types'
import { TMUX_SOCKET } from './tmux-naming'
import { LEGACY_RMT_TMUX_SOCKET } from './remote-ssh/control-master'
import type { SessionHostListing } from './session-host-client'
import { cimRows, powershellArgs, powershellExe } from './win32-powershell'

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. */
export interface ProcEntry {
  pid: number
  ppid: number
  rssKb: number
  /** 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
   *  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. */
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 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.
 */
export function rollupTree(
  table: ReadonlyMap<number, ProcEntry>,
  kids: ReadonlyMap<number, number[]>,
  root: 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, 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 = self
  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++
    if (e.rssKb > largest.rssKb) largest = e
    for (const k of kids.get(pid) ?? []) stack.push(k)
  }
  const selfMb = kbToMb(self.rssKb)
  const childrenMb = kbToMb(childrenKb)
  const largestName = processLabel(largest.name)
  return {
    selfMb,
    childrenMb,
    childCount,
    totalMb: selfMb + childrenMb,
    largestMb: kbToMb(largest.rssKb),
    ...(largestName ? { largestName } : {})
  }
}

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')) {
    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
    const name = parts.slice(3).join(' ')
    out.push({ pid, ppid, rssKb, ...(name ? { name } : {}) })
  }
  return out
}

/**
 * Parse `top -l 1 -stats pid,mem` into pid → **phys_footprint** in kB.
 *
 * On darwin this REPLACES `ps`'s `rss` as the panel's memory number, because the two measure
 * different things and `rss` is the wrong one here. Measured on a real Mac (2026-08-12, 8 claude
 * processes captured in the same tick against Apple's own `footprint` tool):
 *   - ACTIVE processes: footprint/rss ≈ 1, and one read **0.73×** — `rss` counts shared resident
 *     pages that footprint does not, so the two accountings diverge in BOTH directions.
 *   - IDLE processes: **1.84–2.20×**. macOS moves an idle process's pages into the compressor,
 *     which drops out of `rss` but stays in footprint.
 * That is the population this panel exists to describe: it asks what idle sessions cost, and macOS
 * compresses exactly those. `rss` therefore understated a six-hour-idle session by about half.
 *
 * `phys_footprint` is also what Activity Monitor's "Memory" column shows, which makes the panel
 * agree with the pill — the pill's `vm_stat` reading already counts compressor pages and was
 * verified against Activity Monitor to 0.05%. Two surfaces describing one machine must not use two
 * accountings.
 *
 * Format facts, all MEASURED on that host (980 data rows) rather than assumed:
 *   - ~10 header lines, a blank, then a `PID    MEM` column header; data follows. We locate that
 *     header rather than counting lines, because the header block's size is not a contract.
 *   - The MEM column is LEFT-aligned in five characters, so values carry TRAILING SPACES
 *     (`12M  `, `859M `, `1314M`). A naive `/M$/` misses two thirds of them.
 *   - Units seen: `K` (553 rows) and `M` (427). `G` was never observed — a 1314M process stayed in
 *     M — but `top`'s own header prints `PhysMem: 23G`, so `G` is accepted anyway.
 *   - `B` and any restricted-process rendering were NOT observed and are deliberately not guessed:
 *     an unrecognised suffix skips the row, the same tolerance the rest of this file uses.
 *   - `top` rounds the M column to whole megabytes (29M and 28M across two ticks); K rows keep kB
 *     precision. The panel renders MB, so the rounding is below what it shows.
 *   - pid 0 (`kernel_task`) appears and is accessible; column spacing varies with pid width.
 */
export function parseTopFootprint(stdout: string): Map<number, number> {
  const out = new Map<number, number>()
  const lines = stdout.split('\n')
  // Find the column header, not a line number: the header block above it is not a contract.
  const head = lines.findIndex((l) => /^\s*PID\s+MEM\s*$/.test(l))
  if (head < 0) return out
  const UNIT: Record<string, number> = { B: 1 / 1024, K: 1, M: 1024, G: 1024 * 1024 }
  for (const line of lines.slice(head + 1)) {
    // `\s*$` rather than an end-anchored unit: the value is left-aligned and padded.
    const m = /^\s*(\d+)\s+(\d+(?:\.\d+)?)([A-Za-z])\s*$/.exec(line)
    if (!m) continue
    const factor = UNIT[m[3].toUpperCase()]
    // An unrecognised suffix skips the row rather than guessing a scale — a wrong scale here is a
    // wrong number presented as a fact, which is the failure this whole feature exists to end.
    if (factor === undefined) continue
    const pid = Number(m[1])
    if (!Number.isFinite(pid)) continue
    out.set(pid, Number(m[2]) * factor)
  }
  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. */
/**
 * macOS reading, or `null`. **There is deliberately no fallback to `os.freemem()` here.**
 *
 * That fallback is the very number this function exists to replace: on macOS it sits near zero, and
 * the session reaper's watermark (10% of RAM) then reads as permanent memory pressure — which had a
 * Mac reaping idle detached sessions every 10 minutes regardless of how much memory was free. A
 * confirmed field symptom, reported as "my sessions keep disappearing".
 *
 * So a `vm_stat` we cannot run or cannot parse yields NO SIGNAL, not a wrong one. Both consumers
 * 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.
 */
/** The oids `darwinMemInfo` reads, in ONE `sysctl` run. Without `-n`, so each answer carries its
 *  own `name:` prefix and is matched by name rather than by line position. */
export const DARWIN_DISPLAY_SYSCTLS = ['vm.swapusage', 'kern.memorystatus_vm_pressure_level'] as const

export function darwinMemInfo(
  runVmStat: () => string,
  totalBytes: number,
  runSysctl?: (names: string[]) => string
): MemInfo | null {
  let base: MemInfo | null
  try {
    base = parseVmStat(runVmStat(), totalBytes)
  } catch {
    return null
  }
  if (!base || !runSysctl) return base
  // The pill's display extras. Both oids come from ONE `sysctl` run, and each field is still
  // optional on its own, the same shape as PSI on Linux: an oid with no line (or a line that does
  // not parse) omits its one field, and a run that fails outright costs the vm_stat reading
  // nothing. Never `swapTotalMb`/`swapFreeMb` — see MemInfo.display for why darwin must not fill
  // those.
  const display: MemDisplay = {}
  let out = ''
  try {
    out = runSysctl([...DARWIN_DISPLAY_SYSCTLS])
  } catch {
    // no swap figure, no pressure tint
  }
  for (const line of out.split('\n')) {
    if (line.startsWith('vm.swapusage:')) Object.assign(display, parseSwapUsage(line))
    else if (line.startsWith('kern.memorystatus_vm_pressure_level:')) {
      const level = parsePressureLevel(line)
      if (level) display.pressureLevel = level
    }
  }
  return Object.keys(display).length > 0 ? { ...base, display } : base
}

/**
 * One bounded `sysctl` run for `darwinMemInfo`, by absolute path (a GUI app's PATH is not the
 * shell's). An oid the kernel does not know makes sysctl exit non-zero while still printing the
 * others, so a failure hands over whatever stdout it has: each field stays optional on its own.
 * stderr is discarded rather than inherited into main's.
 */
function runDarwinSysctl(names: string[]): string {
  try {
    return execFileSync('/usr/sbin/sysctl', names, {
      encoding: 'utf8',
      timeout: 5_000,
      stdio: ['ignore', 'pipe', 'ignore']
    })
  } catch (e) {
    const partial = (e as { stdout?: unknown } | null)?.stdout
    if (typeof partial === 'string' && partial) return partial
    throw e
  }
}

/**
 * Parse `sysctl vm.swapusage` (with or without the `vm.swapusage:` prefix). Live shape on a
 * measured 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 a measured 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
  }
}

/**
 * Parse `vm_stat` into the same MemInfo shape, given the machine's total bytes.
 *
 * macOS deliberately keeps almost nothing "free": file-backed and purgeable pages are held until
 * something needs them, so libuv's `os.freemem()` — which counts only genuinely free pages —
 * reports near zero on a healthy Mac. `total - free` therefore renders every Mac as ~100% full,
 * which is both useless and alarming. (It also pinned the session reaper's watermark permanently
 * below its threshold, so a Mac reaped idle detached sessions on every sweep regardless of memory.)
 *
 * The number Activity Monitor calls "Memory Used" is app + wired + compressed, i.e.
 * `anonymous - purgeable + wired + compressor`; everything else is reclaimable and counts as
 * available. This is an approximation of Activity Monitor, not a reproduction of it — Apple does not
 * document the exact figure, and on Apple Silicon the parts are known not to sum to its total.
 *
 * The page size is READ FROM THE HEADER, never assumed: Apple Silicon uses 16 KiB pages, and
 * hard-coding 4096 is the identical bug this file already fixed on the Linux side.
 */
export function parseVmStat(text: string, totalBytes: number): MemInfo | null {
  const pageSize = Number(/page size of (\d+) bytes/.exec(text)?.[1])
  if (!Number.isFinite(pageSize) || pageSize <= 0 || !Number.isFinite(totalBytes) || totalBytes <= 0) {
    return null
  }
  const pages = (label: string): number | null => {
    const m = new RegExp(`^${label}:\\s+(\\d+)\\.`, 'm').exec(text)
    return m ? Number(m[1]) : null
  }
  const anonymous = pages('Anonymous pages')
  const wired = pages('Pages wired down')
  const compressor = pages('Pages occupied by compressor')
  // `Pages purgeable` is a SUBSET of anonymous — caches an app has volunteered as droppable.
  const purgeable = pages('Pages purgeable') ?? 0
  // A missing field means we are not looking at vm_stat output we understand. Report nothing rather
  // than a number built from a partial read — the pill pulses, which is the honest answer.
  if (anonymous === null || wired === null || compressor === null) return null

  const usedBytes = (Math.max(0, anonymous - purgeable) + wired + compressor) * pageSize
  const totalMb = Math.round(totalBytes / 1048576)
  // Clamp: the parts are an approximation and can exceed the total on a heavily compressed system.
  const availableMb = Math.max(0, totalMb - Math.round(usedBytes / 1048576))
  return { availableMb, totalMb }
}

/**
 * Parse `/proc/meminfo`. `MemAvailable`/`MemTotal` are REQUIRED (without them there is no reading
 * at all); swap is optional and reported only when BOTH halves are present.
 *
 * Swap is read from the meminfo text already in hand rather than from a second file: the watermark
 * and the swap term must describe the same instant, and two reads a syscall apart can disagree
 * about a host that is actively swapping — which is precisely the host this term exists for.
 *
 * `SwapTotal: 0` is a real answer (a host with swap disabled) and is passed through as `0`, where
 * every consumer's `swapTotalMb > 0` guard turns the term off. A MISSING SwapTotal is a different
 * fact — a /proc we do not understand — and yields `undefined`, i.e. no signal.
 */
export function parseMemInfoText(text: string): MemInfo | null {
  const kb = (label: string): number | null => {
    const m = new RegExp(`^${label}:\\s+(\\d+)\\s*kB`, 'm').exec(text)
    return m ? Number(m[1]) : null
  }
  const avail = kb('MemAvailable')
  const total = kb('MemTotal')
  if (avail === null || total === null) return null
  const swapTotal = kb('SwapTotal')
  const swapFree = kb('SwapFree')
  const out: MemInfo = {
    availableMb: Math.round(avail / 1024),
    totalMb: Math.round(total / 1024)
  }
  // Both or neither: a SwapFree without a SwapTotal cannot be turned into a ratio, and half a
  // reading is worse than none — it would be a number a consumer could divide by zero with.
  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
}

/**
 * Parse `/proc/pressure/memory` into the two `avg60` figures.
 *
 * Shape (Linux >= 4.20, PSI compiled in):
 *   some avg10=0.00 avg60=0.00 avg300=0.18 total=29288181130
 *   full avg10=0.00 avg60=0.00 avg300=0.15 total=25621111809
 *
 * `avg60` rather than `avg10` on purpose: the reaper sweeps every ten minutes, and a 10-second
 * window is noise at that cadence — a single compile spiking avg10 must not be read as a host in
 * trouble. `avg300` is the other direction: it stays elevated long after the host recovered, and
 * would keep reaping through the recovery.
 *
 * A line we cannot parse yields `undefined` for that figure, not 0 — a zero here means "measured,
 * no stall", which is the opposite of "did not measure".
 */
export function parsePsiMemory(text: string): { psiSomeAvg60?: number; psiFullAvg60?: number } {
  const avg60 = (kind: 'some' | 'full'): number | undefined => {
    const m = new RegExp(`^${kind}\\s[^\\n]*?\\bavg60=(\\d+(?:\\.\\d+)?)`, 'm').exec(text)
    if (!m) return undefined
    const n = Number(m[1])
    return Number.isFinite(n) ? n : undefined
  }
  const some = avg60('some')
  const full = avg60('full')
  return {
    ...(some !== undefined ? { psiSomeAvg60: some } : {}),
    ...(full !== undefined ? { psiFullAvg60: full } : {})
  }
}

export function readMemInfo(): MemInfo | null {
  try {
    const base = parseMemInfoText(fs.readFileSync('/proc/meminfo', 'utf8'))
    if (base) {
      // PSI is a SEPARATE, OPTIONAL read: it is absent on pre-4.20 kernels, on kernels built
      // without CONFIG_PSI, and inside some containers. Its absence must cost the caller nothing —
      // the memory reading it decorates is already complete and correct without it.
      try {
        return { ...base, ...parsePsiMemory(fs.readFileSync('/proc/pressure/memory', 'utf8')) }
      } catch {
        return base
      }
    }
  } catch {
    // fall through to the os fallback
  }
  // macOS: `os.freemem()` counts only genuinely free pages, which a healthy Mac keeps near zero —
  // see parseVmStat. Ask the kernel for the real breakdown instead. Sync on purpose: both callers
  // (the 30 s pill poll and the reaper's 10 min sweep) are far apart, and keeping ONE signature
  // means the reaper's watermark is fixed by the same change.
  if (process.platform === 'darwin') {
    // The display extras cost one more synchronous process per call (both oids in one `sysctl`),
    // a fork/exec on main beside `vm_stat`. Their caller is the 30 s pill read: on darwin the
    // reaper's `hostMemReader` is null, so it never reaches this.
    return darwinMemInfo(
      () => execFileSync('vm_stat', { encoding: 'utf8', timeout: 5_000 }),
      os.totalmem(),
      runDarwinSysctl
    )
  }
  try {
    return {
      availableMb: Math.round(os.freemem() / 1048576),
      totalMb: Math.round(os.totalmem() / 1048576)
    }
  } catch {
    return null
  }
}

/** One tmux pane as reported by `list-panes -a`. Core-internal. */
export interface PaneRef {
  session: string
  panePid: number
  command: string
}

/** The `-F` format `parsePaneList` reads. Exported so the SSH leg's generated shell asks for the
 *  exact same fields — a second copy of this string would drift from its own parser. */
export 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])
    // `> 0`, not just finite: an empty pid field parses as 0, which would produce a phantom row
    // rolled up from a pid that cannot exist.
    if (!parts[0] || !Number.isFinite(panePid) || panePid <= 0) 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
  /** nodeterm's own processes (desktop only). Absent → the report carries no `app` at all. */
  appProcesses?: AppProcessReader
}

/**
 * Reads the whole table from `/proc` on Linux, with no subprocess. Returns null on every other
 * platform (and when `/proc` itself is unreadable) — the caller falls back to one `ps` call.
 *
 * `/proc/<pid>/status` is deliberately read INSTEAD of `stat` + `statm`: it carries both facts we
 * need in ONE file, and its `VmRSS` is already in kB. `statm` reports RSS in PAGES, which would
 * force a page-size assumption — hard-coding 4096 under-reports 4× on a 16 KiB-page arm64 kernel
 * and 16× on the 64 KiB-page enterprise arm64 builds, i.e. it would print 40 MB for a 640 MB
 * session. Do not "optimise" this back to `statm`.
 */
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 status = fs.readFileSync(`/proc/${name}/status`, 'utf8')
          const ppid = Number(/^PPid:\s+(\d+)/m.exec(status)?.[1])
          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
          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.
        }
      }
      return out
    } catch {
      return null
    }
  }
  return null // non-Linux falls through to the ps path in collectSessionMemory
}

/**
 * Does a failed `list-panes` mean "there is no tmux server on that socket" — which is an ANSWER,
 * and the normal state of a socket nobody has used — rather than "the sweep could not run"?
 * tmux exits non-zero for both, so its message is the only signal we get.
 *
 * Deliberately narrow. A permission-denied socket directory ("error connecting to … (Permission
 * denied)") or a timeout against a hung server is a real failure, and laundering it into "no
 * sessions here" is exactly the mistake `ok:false` exists to prevent: it would print an empty
 * panel over 20 live sessions. Only the two phrasings that positively assert absence count.
 *
 * The second alternative is ANCHORED to tmux's own connect message rather than matching a bare
 * `no such file or directory`. `promisify(execFile)` folds stderr into `err.message`, so an
 * unanchored errno string matches any failure that merely contains it — a tmux client missing a
 * shared library exits 127 with "cannot open shared object file: No such file or directory" on
 * EVERY socket (same binary), which would report "no sessions" while the server started before the
 * breakage still runs live ones. The same string is how a dead ssh ControlMaster fails
 * ("Control socket connect(…): No such file or directory"), which matters the moment this sweep is
 * routed over one. tmux ships no gettext (its messages are C literals), so anchoring is safe.
 */
export function isNoServerError(message: string): boolean {
  return /no server running|error connecting to [^\n]*\(no such file or directory\)/i.test(message)
}

/**
 * Non-Linux (or an unreadable /proc): `ps` for the whole table, through the injectable exec seam —
 * nothing in this file may reach a subprocess around it. Null when it could not run.
 *
 * On darwin a SECOND call is merged in: `top` carries phys_footprint, which is what Activity
 * Monitor shows and what the pill's `vm_stat` reading already counts. `ps`'s own `rss` drops an
 * idle process's compressed pages and understated a six-hour-idle session by about half — exactly
 * the population this panel exists to describe. See parseTopFootprint.
 */
async function psProcessTable(
  exec: (bin: string, args: string[]) => Promise<string>,
  platformName: NodeJS.Platform
): Promise<ProcEntry[] | null> {
  try {
    const rows = parseProcessTable(await exec('ps', ['-eo', 'pid,ppid,rss,comm']))
    if (platformName !== 'darwin') return rows
    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) => {
      const f = fp.get(e.pid)
      return f === undefined ? e : { ...e, rssKb: f, footprint: true as const }
    })
  } catch {
    return null
  }
}

/** The PowerShell the Windows table comes from: one CIM query, compressed JSON on one line. */
export const WIN32_PROCESS_TABLE_SCRIPT =
  'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,Name | ConvertTo-Json -Compress'

/**
 * Parse `WIN32_PROCESS_TABLE_SCRIPT`'s output. `ConvertTo-Json` prints a bare OBJECT for a
 * one-element pipeline and an array otherwise; both are accepted. `WorkingSetSize` is BYTES — the
 * Windows counterpart of RSS (resident pages, shared ones included), and what Task Manager's
 * "Working set" column shows. Rows without a numeric pid/ppid are skipped; a missing working set
 * reads as 0 rather than dropping the process, so the tree walk still reaches its children.
 * Unparseable JSON, or a table with no process at all (a machine always has some), is null.
 */
export function parseWin32ProcessTable(json: string): ProcEntry[] | null {
  const rows = cimRows(json)
  if (rows === null) return null
  const out: ProcEntry[] = []
  for (const r of rows) {
    const pid = Number(r.ProcessId)
    const ppid = Number(r.ParentProcessId)
    if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(ppid)) continue
    const bytes = Number(r.WorkingSetSize)
    const entry: ProcEntry = { pid, ppid, rssKb: Number.isFinite(bytes) && bytes > 0 ? bytes / 1024 : 0 }
    if (typeof r.Name === 'string' && r.Name) entry.name = r.Name
    out.push(entry)
  }
  return out.length > 0 ? out : null
}

/** The Windows process table through the exec seam, or null when PowerShell could not answer. */
export async function win32ProcessTable(
  exec: (bin: string, args: string[]) => Promise<string>
): Promise<ProcEntry[] | null> {
  try {
    return parseWin32ProcessTable(await exec(powershellExe(), powershellArgs(WIN32_PROCESS_TABLE_SCRIPT)))
  } catch {
    return null
  }
}

/** The ConPTY console hosts: inbox `conhost.exe`, or node-pty's bundled `OpenConsole.exe`. */
const CONSOLE_HOST_IMAGE = /^(conhost|openconsole)(\.exe)?$/i

/**
 * The session host's own cost (`SessionMemoryReport.host`): the host process, plus every child of
 * it that is NOT a session's shell, with their subtrees. ConPTY's conhost/OpenConsole is created by
 * the host's `CreatePseudoConsole`, so it is the host's child and the shell's SIBLING — no row's
 * rollup reaches it, and without this it is counted nowhere.
 *
 * The shells' subtrees are excluded by pid (they are the rows), so nothing is counted twice; a pane
 * pid equal to the host pid (it never should be) is still only the host's own working set.
 * `consoleCount` counts direct children named as a console host — the table carries image names on
 * Windows; without names the count is 0 while the memory is still included. Undefined when the host
 * pid is unknown or not in the table: a host we did not find is "could not measure", never 0 MB.
 */
export function hostOverhead(
  entries: readonly ProcEntry[],
  hostPid: number | undefined,
  panePids: readonly number[]
): SessionHostOverhead | undefined {
  if (hostPid === undefined || !Number.isSafeInteger(hostPid) || hostPid <= 0) return undefined
  const { table, kids } = indexProcesses(entries)
  const self = table.get(hostPid)
  if (!self) return undefined
  const panes = new Set(panePids)
  // Pre-seed the walk with the host and every pane so neither a shell subtree nor a cyclic ppid
  // chain back to the host is ever entered.
  const seen = new Set<number>([hostPid, ...panes])
  let childKb = 0
  let consoleCount = 0
  const stack: number[] = []
  for (const k of kids.get(hostPid) ?? []) {
    if (panes.has(k)) continue
    const e = table.get(k)
    if (e?.name && CONSOLE_HOST_IMAGE.test(e.name)) consoleCount++
    stack.push(k)
  }
  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
    childKb += e.rssKb
    for (const k of kids.get(pid) ?? []) stack.push(k)
  }
  const selfMb = kbToMb(self.rssKb)
  const consoleMb = kbToMb(childKb)
  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
 * (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:
 *  - 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>
  /** Process-table override for tests. Default: by platform (CIM on Windows, /proc, else ps). */
  readTable?: () => Promise<ProcEntry[] | null>
  readMem?: () => MemInfo | null
  exec?: (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
}

/**
 * The session-host leg of the sweep: the host names each session and its pty's pid (the pane's
 * shell — `PaneRef.panePid`), and the same `buildReport`/`rollupTree` then do what they do for
 * tmux. Failure rules, mirroring the tmux leg:
 *  - a failed host read, or an unreadable process table → `ok: false`, no rows;
 *  - no host running → `ok: true` with no rows — an ANSWER (there are no sessions), not a failure,
 *    and no process table is read for it;
 *  - a session the host names but does not describe (a host older than `sessionDetails`, a row
 *    dropped as malformed) is counted in `unmeasured` — never silently dropped, so the panel cannot
 *    say "no sessions" over live ones.
 */
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) }
      : report
  let listing: SessionHostListing | null
  try {
    listing = await deps.list()
  } catch {
    listing = null
  }
  if (!listing) return { ok: false, 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[] = []
  let unmeasured = 0
  for (const name of ours) {
    const row = described.get(name)
    if (row) panes.push({ session: name, panePid: row.pid, command: '' })
    else unmeasured++
  }
  const withUnmeasured = (report: SessionMemoryReport): SessionMemoryReport =>
    unmeasured === 0 ? report : { ...report, unmeasured, unmeasuredBackend: 'session-host' }
  // An idle host still costs memory, so a running host with no described session still reads the
  // 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 withApp(withUnmeasured({ ok: true, rows: [], mem }), null)

  const exec =
    deps.exec ??
    (async (b: string, args: string[]): Promise<string> => {
      const { stdout } = await runAsync(b, args, {
        timeout: 15_000,
        maxBuffer: 16 * 1024 * 1024,
        windowsHide: true
      })
      return stdout
    })
  const readTable =
    deps.readTable ??
    (async (): Promise<ProcEntry[] | null> => {
      if (platformName === 'win32') return win32ProcessTable(exec)
      return defaultProcessTableReader() ?? (await psProcessTable(exec, platformName))
    })
  let table: ProcEntry[] | null
  try {
    table = await readTable()
  } catch {
    table = null
  }
  if (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 withApp(withUnmeasured({ ok: true, rows: [], mem }), null)
    return { ok: false, rows: [], mem }
  }
  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
  // rows only cover ours): every session the host NAMED must be described, and every described
  // shell — whatever its name — is excluded from the overhead walk.
  const allDescribed = listing.names.every((n) => described.has(n))
  const host =
    unmeasured === 0 && allDescribed
      ? hostOverhead(table, hostPid, (listing.sessions ?? []).map((row) => row.pid))
      : undefined
  return host ? { ...report, host } : report
}

/**
 * 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 with no tmux server contributes NO panes but is NOT a failure — "no server running"
 *    is the normal answer for a socket nobody has used yet (`isNoServerError`);
 *  - but if NO socket answered — every one of them failed for some OTHER reason — the sweep never
 *    ran → `ok: false`. "Every socket errored" and "we looked and found nothing" are different
 *    facts and must not render the same.
 */
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 ?? defaultProcessTableReader

  let table = readTable()
  if (table === null && !deps.readTable) table = await psProcessTable(exec, process.platform)
  if (table === null) return { ok: false, rows: [], mem }

  const sockets = deps.sockets ?? [TMUX_SOCKET, LEGACY_RMT_TMUX_SOCKET]
  const bySession = new Map<string, PaneRef>()
  let answered = 0
  for (const s of sockets) {
    try {
      const stdout = await exec(bin, ['-L', s, 'list-panes', '-a', '-F', PANE_FMT])
      answered++
      // 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 (err) {
      // "No server on this socket" is an empty ANSWER, so it still counts as having looked. Any
      // other failure yields neither panes nor an answer.
      if (isNoServerError(err instanceof Error ? err.message : String(err))) answered++
    }
  }
  // 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),
    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 report
  return { ...report, app: appSelfMemory(sampleApp(deps.appProcesses), table, process.platform) }
}