SLOPSHOPPER

proc-stats

Status line, task-manager pane and report of Claude Code's memory, CPU and uptime, and those of the processes it started

paneguardcommandtoaststatusprocess
★ 4v0.4.0no licenseupdated 2026-10-11DragosMocrii/proc-stats
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · proc-stats
│ ┃ Processes ✕ › fix the failing auth test and add an audit log call │ ┃ no engine pid in "" │ ┃ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /proc-stats │ ⎿ proc-stats: Processes pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ proc-stats: proc-stats: no engine pid in ""

Draws

Pane · Processes
no engine pid in ""
README

proc-stats

A Claude Code mod that pins a status line with the session's own resource use, and opens a task-manager pane of it on /proc-stats:

Claude starts a dev server, a test watcher and a detached tunnel; /proc-stats shows them in a tree with live charts, details, collapsing and sorting, and /proc-stats report summarizes the session

mem 484MB · peak 530MB · cpu 2.4% · up 12m 4s

While the session has processes running under it (Bash commands, watchers, test runs, local MCP servers), or ones it started that have since detached, their share is added after a +:

mem (484 + 215)MB · peak 530MB · cpu (2.4 + 98.7)% · up 12m 4s
  • mem: resident memory of Claude Code, plus every process below it and every detached process it started.
  • peak: Claude Code's highest resident memory. On macOS, where ps has no peak, it is the highest seen since the mod loaded.
  • cpu: share of one core since the last reading, as top shows it.
  • up: how long Claude Code has been running.

Processes pane

/proc-stats opens a task-manager pane and gives it the keyboard (Esc hands it back to the prompt; click the pane or press ctrl+x then tab to return):

  • History: two lines at the top chart the session's total memory and CPU (Claude Code and everything it started) over the history window (10 minutes by default; see Settings), each followed by the current value and the window's highest (max). Memory is scaled from the window's lowest to its highest point, and never to less than 64 MB or a tenth of its highest point (whichever is more), so a slow leak rises across the full height while small noise stays flat and a steady line sits mid-height; CPU is scaled from zero to one core, or to its highest point when that is more. Short spikes stay visible. Readings are drawn evenly spaced, so a gap (such as while the machine sleeps) does not show.
  • Rows: Claude Code's own row (with the main conversation's model and effort, dim, once it has made a request since the mod loaded, e.g. Claude Code opus-5-5 · high), then every process below it as a tree. A Bash command Claude ran shows as $ <command>; a $ … row also says what started it when it can tell — · Bash, · Monitor, · subagent: <type>, or · agent for one it cannot name — and the details name the subagent's task (commands started before the mod loaded show none); ▾/▸ marks a row with processes under it. Under the rows, Child processes sums every process below Claude Code, and Total adds the detached ones and Claude Code's own.
  • Subagents: under the rows, while any subagent is active (pending, running, waiting or idle) or an ended one still holds a process, each subagent with its task and status (followed by the model and effort of the agent's latest request, e.g. · running · sonnet-5-5 · high), nested under the subagent that started it, and the memory and CPU of the processes it started and theirs (— when it has none). A subagent that ended stays, dim, while a process it started still runs; so does one the listing does not name (a workflow's, or one the engine has dropped), as not listed. A subagent's own work runs inside Claude Code and is counted in Claude Code's row.
  • Detached: processes the session started that no longer run under Claude Code (nohup … &, setsid, daemons) follow the tree under a Detached heading, with their own subtotal. They count toward the totals, the history, the status-line marker and the toasts, and can be stopped like any other row. In a sorted view their parent reads detached. The mod finds them by a variable, PROC_STATS_SESSION, that it sets for every command the session starts; if it cannot set it, a line under the rows says detached processes are not tracked.
  • ↑ / ↓ move between rows; the row you land on is selected and its full command, pid, parent, start time, memory and CPU show under the table, with what started it and whether it is detached.
  • Enter or a click selects a row, and on a row with processes under it collapses or expands it (collapsed, it shows its subtree's totals).
  • s sorts by CPU, memory or runtime (highest first, each row followed by its parent), then back to the tree.
  • k stops the selected process and everything it started: it asks first (y Stop, n Cancel; Esc, leaving the pane, cancels too), sends SIGTERM (Windows: taskkill /T), and after 3 seconds offers f Force stop (SIGKILL) if anything is still running, even a process that left the tree when its parent ended. Once a stop is sent the footer offers n Dismiss. Claude Code's own row cannot be stopped.
  • Stopping a $ … row that Claude is still running ends that tool call.
  • A stop reaches only the first 500 listed processes.
  • On Windows a first stop may need f: taskkill without /F cannot end console processes.

TIME, then PID, give way on a narrow pane.

Report

/proc-stats report writes a summary of the session into the conversation, where Claude reads it too: the platform and how long Claude Code has run; the memory and CPU of Claude Code, its child processes, its detached processes and all of them together now; the highest memory and CPU of the history window and how long ago they were; the five processes using the most memory, with what started them; up to ten detached processes; the marker level; and the last five alerts.

Platforms

By default both views refresh every second on Linux, every 2 seconds on macOS and every 5 on Windows (configurable in Settings), and work on Linux (/proc and ps), macOS (ps) and Windows (PowerShell). Detached processes are found on Linux (/proc/<pid>/environ, read once per process) and macOS (ps eww, at most every 10 seconds, so a new one can take that long to show), and not on Windows.

Settings

In Claude Code's config menu (/config), under proc-stats:

SettingDefault
Refresh on Linux / macOS / Windows (ms)1000 / 2000 / 5000how often processes are read; 250-60000 on Linux and macOS, 1000-60000 on Windows
Memory warning / alert (MB)2048 / 4096🟡 / 🔴 on the status line (session total); a warning above its alert is lowered to the alert; limits are at least 1
CPU warning / alert (%)150 / 300the same for CPU, averaged over the last 10 s (two refreshes when the refresh is slower)
Busy process CPU (%) / time (s)90 / 60a toast for one process the session started
Large process memory (MB)1024a toast for one process the session started
History (minutes)10the pane's sparklines; 1-120 minutes
Child processes on the status lineonthe + part

A value out of range is ignored and its default used.

Alerts

  • Status line: 🟡 at the start of the line when the session (Claude Code and every process it started) uses more memory than the warning limit, or more CPU on average over the last 10 seconds (two refreshes when the refresh is slower); 🔴 above the alert limit. A marker clears only once its value is 10% below the limit, so it does not flicker.
  • Toasts: one when a process the session started (under Claude Code or detached) stays above the busy-process CPU limit for the set time (short dips are tolerated), and one when it grows past the large-process memory limit. Each fires once per process, and again only after the process has been 10 seconds below 90% of the limit. Several at once become one toast.

Install

At the prompt of a Claude Code terminal session:

/plugin install proc-stats --marketplace DragosMocrii/proc-stats

Answer y to add the marketplace, then choose a scope (user scope loads it in every session).

Limits

  • A detached process is found only if it keeps the environment it started with (a program that clears it, such as env -i, is not found), and only on Linux and macOS.
  • A program a command opens that outlives it, such as a browser or editor started by xdg-open or code ., carries the session's mark and is counted as a detached process.
  • A command that starts and ends between two readings is not counted.
  • + ? means the process table could not be read (for example no ps in a minimal container).
  • A subagent's totals cover the processes the pane lists (it caps its rows), so they can be lower than the processes it started; processes started before the mod loaded, or by tools other than Bash and Monitor, count toward no subagent.

FAQ

Does it add much overhead? Little. Each reading runs ps once. On Linux it also reads a few small /proc files for Claude Code and for each process under it, and reads a new process's environment once. A reading that is due while the last one is still running is skipped, so readings never pile up. With 36 processes running, one ps call takes about 5 ms. Windows costs more because every reading starts PowerShell, so it reads every 5 seconds by default. The mod only reads: it attaches to no process, does not slow any process down, and sends nothing over the network. It runs inside Claude Code, so its own memory and CPU show in Claude Code's row. It keeps at most 2,400 history points and 500 rows. For a lighter load, raise the refresh in Settings.

Is it configurable? Yes, in /config under proc-stats. You can set how often each platform is read, the memory and CPU limits for the 🟡 / 🔴 markers and the toasts, how far back the history goes, and whether the status line shows the + part for child processes. See Settings.

Can I resize the pane? Yes. Claude Code places the pane and sizes it, not the mod. In the fullscreen layout at 110 columns or more, it docks beside the conversation; otherwise it sits above the prompt. You can drag it to another size, and Claude Code keeps the size you set. When the pane is narrow, the TIME column is hidden first, then PID.

Why is CPU above 100%? CPU is a share of one core, as in top, so 250% means two and a half cores are busy.

Does it see my other sessions and terminals? No. It sees Claude Code, the processes under it, and detached processes that carry this session's mark. Each session gets its own mark, so another session's processes are not counted.

What is PROC_STATS_SESSION in my environment? It is this session's mark, a random ID that the mod sets for every command the session starts. The mod uses it to find processes that have detached. It holds nothing else.

Can it stop a process by mistake? No. It stops a process only when you press k on its row in the pane and then confirm with y. Claude Code's own row cannot be stopped.

Development

claude plugin validate .
claude plugin test .
claude --plugin-dir .

docs/demo.gif is recorded by docs/demo, a Go module that runs Claude Code with the mod in a pseudo-terminal, in a made-up project whose stand-in processes hold memory and CPU, and draws the screen to a GIF. It runs on Linux, logged in to Claude Code (its one prompt uses your account), in a home and config directory of its own; see the comment at the top of docs/demo/main.go for the fonts it needs. Re-record it after visible changes:

cd docs/demo
go run . -font DejaVuSansMono.ttf -bold DejaVuSansMono-Bold.ttf \
  -fallback DejaVuSans.ttf,NotoSansSymbols2-Regular.ttf,NotoSansSymbols.ttf -emoji noto-emoji/2D/png/72
Source 19 files
hooks/register.ts 738 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentEntry, AlertState, History, ModelUse, Origin, OriginCall, Origins, PaneState, Point, Reading, SessionMark, StopState } from '../types'
5import { toEntries } from './agents'
6import { historyCapacity, pointOf, pointSpacingMs, pushPoint, shouldRecord } from './history'
7import { EMPTY_ALERTS, markerFor, stepAlerts, worse } from './alerts'
8import { candidatesOf, environHasMark, macListedPids, macMarkedPids, oursOf, rememberMarks, startedFrom, unreadOf } from './detached'
9import type { MarkCache } from './detached'
10import { CALL_TTL_MS, EMPTY_ORIGINS, matchOrigins, UNNAMED_AGENT } from './origin'
11import { pruneModels, withModel } from './models'
12import { drawPane } from './pane'
13import type { PaneHandlers } from './pane'
14import { buildSnapshot, capRows } from './snapshot'
15import type { Timed } from './snapshot'
16import { reportText } from './report'
17import { readSettings } from './settings'
18import type { Settings } from './settings'
19import { statusLine } from './status'
20import {
21  aliveFrom,
22  isAlreadyEnded,
23  killArgv,
24  linuxObserved,
25  macLivenessArgv,
26  outcomeText,
27  parseMacLiveness,
28  parseWindowsLiveness,
29  startsOf,
30  STOP_CHECK_MS,
31  STOP_CHECK_TRIES,
32  stopTargets,
33  windowsLivenessScript,
34} from './stop'
35import type { Observed } from './stop'
36import { cycleSort, EMPTY_PANE, isSelected, labelOf, pruneState, toggleCollapsed } from './view'
37import { childPids, linuxEngine, linuxProc, macReading, windowsReading } from './sampler'
38import type { Gathered } from './sampler'
39import { isComplete, parseMacFields, parsePsTable, powerShellSample } from './stats'
40import type { Platform, Proc } from './stats'
41
42const PANE = 'proc-stats'
43const COMMAND = 'proc-stats'
44
45const READING = { plugin: 'proc-stats', key: 'reading' } as const
46const PANE_STATE = { plugin: 'proc-stats', key: 'pane' } as const
47const reading = atom(READING, {} as Reading)
48const pane = atom(PANE_STATE, EMPTY_PANE as PaneState)
49const IS_OPEN = { plugin: 'proc-stats', key: 'isOpen' } as const
50const isOpen = atom(IS_OPEN, false)
51const HISTORY = { plugin: 'proc-stats', key: 'history' } as const
52const ALERTS = { plugin: 'proc-stats', key: 'alerts' } as const
53const history = atom(HISTORY, { points: [] } as History)
54const alerts = atom(ALERTS, EMPTY_ALERTS as AlertState)
55const ORIGINS = { plugin: 'proc-stats', key: 'origins' } as const
56const origins = atom(ORIGINS, EMPTY_ORIGINS as Origins)
57const AGENTS = { plugin: 'proc-stats', key: 'agents' } as const
58const agents = atom(AGENTS, [] as AgentEntry[])
59const MODELS = { plugin: 'proc-stats', key: 'models' } as const
60const models = atom(MODELS, {} as Record<string, ModelUse>)
61const SESSION = { plugin: 'proc-stats', key: 'session' } as const
62const session = atom(SESSION, { id: '', startMs: 0 } as SessionMark)
63// macOS reads environments with one `ps eww` at most this often.
64const MAC_SCAN_MS = 10_000
65const DETACHED_OFF = 'Detached processes are not tracked: the session mark could not be set.'
66// Long enough to read a process name and its numbers.
67const TOAST_MS = 8000
68const OPEN = { id: PANE, title: 'Processes' }
69const USAGE = '/proc-stats opens the Processes pane; /proc-stats report summarizes the session here.'
70
71const detectPlatform = async ($: EngineInterface): Promise<Platform> => {
72  if ((await $.env.get('OS')) === 'Windows_NT') return 'windows'
73  const { stdout } = await $.process.run(['uname', '-s'])
74
75  return stdout.trim() === 'Darwin' ? 'mac' : 'linux'
76}
77
78// The engine starts each command itself, so a command's parent is the engine.
79const enginePid = async ($: EngineInterface, platform: Platform) => {
80  const { stdout } =
81    platform === 'windows'
82      ? await $.process.run([
83          'powershell',
84          '-NoProfile',
85          '-Command',
86          '(Get-CimInstance Win32_Process -Filter "ProcessId=$PID").ParentProcessId',
87        ])
88      : await $.process.run(['sh', '-c', 'echo $PPID'])
89  const pid = Number(stdout.trim())
90  if (!Number.isInteger(pid) || pid <= 0) throw new Error(`no engine pid in "${stdout.trim()}"`)
91
92  return pid
93}
94
95// `exec` gives ps the shell's pid, printed first, so it can leave itself out.
96const psTable = async ($: EngineInterface, columns: string) => {
97  const { stdout } = await $.process.run(['sh', '-c', `echo $$; exec ps -A -o ${columns}`])
98
99  return parsePsTable(stdout)
100}
101
102const readLinuxChild = async ($: EngineInterface, pid: number, uptime: string): Promise<Proc | undefined> => {
103  try {
104    const [status, stat, cmdline] = await Promise.all([
105      $.fs.read(`/proc/${pid}/status`),
106      $.fs.read(`/proc/${pid}/stat`),
107      // Its own failure only costs the arguments: the name from stat stands in.
108      $.fs.read(`/proc/${pid}/cmdline`).catch(() => ''),
109    ])
110
111    return linuxProc(pid, status, stat, cmdline, uptime)
112  } catch {
113    // Ended since the table was read.
114    return undefined
115  }
116}
117
118// What finding detached processes keeps between readings: the session's mark, what is known of
119// each pid's environment, and when macOS last read environments.
120type Finder = { mark: SessionMark; cache: MarkCache; scannedAt: number }
121
122// Linux: the environment of each candidate not read before, once; one that cannot be read is not ours.
123const linuxDetached = async ($: EngineInterface, finder: Finder, rows: string[][], excluded: Set<number>, wallMs: number) => {
124  const candidates = candidatesOf(startedFrom(rows, 2, wallMs), excluded, finder.mark.startMs)
125  const read = await Promise.all(
126    unreadOf(finder.cache, candidates).map(async each => {
127      try {
128        return { ...each, isOurs: environHasMark(await $.fs.read(`/proc/${each.pid}/environ`), finder.mark.id) }
129      } catch {
130        return { ...each, isOurs: false }
131      }
132    }),
133  )
134  finder.cache = rememberMarks(finder.cache, candidates, read)
135
136  return oursOf(finder.cache, candidates)
137}
138
139// macOS: one `ps eww` over the candidates not read before, at most every MAC_SCAN_MS; until it runs they are not shown.
140const macDetached = async ($: EngineInterface, finder: Finder, rows: string[][], excluded: Set<number>, wallMs: number) => {
141  const candidates = candidatesOf(startedFrom(rows, 4, wallMs), excluded, finder.mark.startMs)
142  const unread = unreadOf(finder.cache, candidates)
143  let read: { pid: number; startMs: number; isOurs: boolean }[] = []
144  if (unread.length > 0 && wallMs - finder.scannedAt >= MAC_SCAN_MS) {
145    finder.scannedAt = wallMs
146    try {
147      const { stdout, isStdoutTruncated } = await $.process.run(['ps', 'eww', '-o', 'pid=,command=', '-p', unread.map(each => each.pid).join(',')])
148      const marked = macMarkedPids(stdout, finder.mark.id)
149      const listed = macListedPids(stdout)
150      // A pid missing from the output stays unread (the command may have failed or been cut); with cut
151      // output only a pid found marked is certain.
152      read = unread
153        .filter(each => marked.has(each.pid) || (!isStdoutTruncated && listed.has(each.pid)))
154        .map(each => ({ ...each, isOurs: marked.has(each.pid) }))
155    } catch {
156      // Read again at the next scan.
157    }
158  }
159  finder.cache = rememberMarks(finder.cache, candidates, read)
160
161  return oursOf(finder.cache, candidates)
162}
163
164const readLinux = async ($: EngineInterface, pid: number, finder: Finder | null): Promise<Gathered> => {
165  const [status, stat, uptime] = await Promise.all([
166    $.fs.read(`/proc/${pid}/status`),
167    $.fs.read(`/proc/${pid}/stat`),
168    $.fs.read('/proc/uptime'),
169  ])
170  const engine = linuxEngine(status, stat, uptime)
171  try {
172    const table = await psTable($, 'pid=,ppid=,etime=')
173    const pids = childPids(table, pid)
174    const excluded = new Set([pid, table.selfPid, ...pids])
175    const ours = finder ? await linuxDetached($, finder, table.rows, excluded, await $.clock.now()) : []
176    const [procs, detached] = await Promise.all([
177      Promise.all(pids.map(child => readLinuxChild($, child, uptime))),
178      Promise.all(ours.map(each => readLinuxChild($, each, uptime))),
179    ])
180
181    return { engine, children: procs.filter(proc => proc !== undefined), detached: detached.filter(proc => proc !== undefined) }
182  } catch {
183    return { engine }
184  }
185}
186
187const readMac = async ($: EngineInterface, pid: number, peakSeenKb: number, finder: Finder | null): Promise<Gathered> => {
188  const table = await psTable($, 'pid=,ppid=,rss=,time=,etime=,command=')
189  const gathered = macReading(table, pid, peakSeenKb)
190  if (!finder) return gathered
191  const excluded = new Set([pid, table.selfPid, ...(gathered.children ?? []).map(child => child.pid)])
192  const ours = new Set(await macDetached($, finder, table.rows, excluded, await $.clock.now()))
193
194  return { ...gathered, detached: table.rows.filter(fields => ours.has(Number(fields[0]))).map(parseMacFields) }
195}
196
197const readWindows = async ($: EngineInterface, pid: number) => {
198  const { stdout } = await $.process.run(['powershell', '-NoProfile', '-Command', powerShellSample(pid)])
199
200  return windowsReading(stdout, pid)
201}
202
203const readProcesses = (
204  $: EngineInterface,
205  platform: Platform,
206  pid: number,
207  peakSeenKb: number,
208  finder: Finder | null,
209): Promise<Gathered> => {
210  switch (platform) {
211    case 'linux':
212      return readLinux($, pid, finder)
213    case 'mac':
214      return readMac($, pid, peakSeenKb, finder)
215    case 'windows':
216      return readWindows($, pid)
217  }
218}
219
220// Sends the signal; a failure is the first line of what the command said, else null. A process that
221// had already ended is no failure.
222const signal = async ($: EngineInterface, platform: string, pids: number[], isForce: boolean) => {
223  try {
224    const { exitCode, stderr } = await $.process.run(killArgv(platform, pids, isForce))
225    if (exitCode === 0 || isAlreadyEnded(stderr)) return null
226
227    return stderr.trim().split('\n')[0] || `exit ${exitCode}`
228  } catch (error) {
229    return error instanceof Error ? error.message : 'the command could not start'
230  }
231}
232
233const toast = ($: EngineInterface, text: string) => $.ui.toast(text, { timeoutMs: TOAST_MS })
234
235// The Linux start of one pid; null once it ended (its stat is gone, or it is a zombie).
236const linuxStart = async ($: EngineInterface, pid: number, uptime: string, wallMs: number) => {
237  try {
238    return linuxObserved(pid, await $.fs.read(`/proc/${pid}/stat`), uptime, wallMs)
239  } catch {
240    return null
241  }
242}
243
244// Which of a stop's targets still run, read per pid outside the tree, since one may have left it
245// (its parent ended); a pid now used by a process started later is not one of them. Null when the
246// liveness could not be read at all.
247const aliveTargets = async ($: EngineInterface, platform: string, stop: StopState): Promise<number[] | null> => {
248  const targets = stop.pids.map((pid, index) => ({ pid, startMs: stop.starts?.[index] ?? NaN }))
249  try {
250    let observed: Observed[]
251    if (platform === 'linux') {
252      const uptime = await $.fs.read('/proc/uptime')
253      const wallMs = await $.clock.now()
254      const starts = await Promise.all(stop.pids.map(pid => linuxStart($, pid, uptime, wallMs)))
255      observed = starts.filter(seen => seen !== null)
256    } else {
257      const { stdout } = await $.process.run(
258        platform === 'mac'
259          ? macLivenessArgv(stop.pids)
260          : ['powershell', '-NoProfile', '-Command', windowsLivenessScript(stop.pids)],
261      )
262      const wallMs = await $.clock.now()
263      observed = platform === 'mac' ? parseMacLiveness(stdout, wallMs) : parseWindowsLiveness(stdout, wallMs)
264    }
265
266    return aliveFrom(targets, observed)
267  } catch {
268    return null
269  }
270}
271
272const sameStop = (a: StopState | null | undefined, b: StopState) =>
273  a?.pid === b.pid && a.startMs === b.startMs && a.phase === b.phase
274
275// Replaces the stop only while it is still the one given, in the phase given: the person may have
276// dismissed it, or another press moved it on, meanwhile. True when it was replaced.
277const moveStop = async ($: EngineInterface, from: StopState, next: StopState | null) => {
278  let isMoved = false
279  await update($, pane, state => {
280    isMoved = sameStop(state.stop, from)
281
282    return isMoved ? { ...state, stop: next } : state
283  })
284
285  return isMoved
286}
287
288// STOP_CHECK_MS after a signal: done when none of the targets runs; else offer a force stop, or, after one,
289// report. Without a reading, or liveness, it tries again, up to STOP_CHECK_TRIES times, then offers force stop.
290const checkStop = async ($: EngineInterface) => {
291  const stop = (await $.state.get(PANE_STATE)).value?.stop
292  if (!stop || (stop.phase !== 'sent' && stop.phase !== 'forced')) return
293  const snapshot = (await $.state.get(READING)).value?.snapshot
294  const alive = snapshot ? await aliveTargets($, snapshot.platform, stop) : null
295  if (alive === null) {
296    // A stop saved by an earlier version has no count.
297    const checks = Number.isFinite(stop.checks) ? stop.checks : 0
298    if (checks >= STOP_CHECK_TRIES) {
299      await moveStop($, stop, { ...stop, phase: 'stuck' })
300      return
301    }
302    if (await moveStop($, stop, { ...stop, checks: checks + 1 })) $.clock.after(STOP_CHECK_MS, () => void checkStop($))
303    return
304  }
305  if (alive.length > 0 && stop.phase === 'sent') {
306    await moveStop($, stop, { ...stop, phase: 'stuck' })
307    return
308  }
309  if (await moveStop($, stop, null)) toast($, outcomeText(stop, alive))
310}
311
312// What the pane's presses do. Built here because they call $, which pane.tsx never receives.
313const paneHandlers = ($: EngineInterface): PaneHandlers => ({
314  onRow: target =>
315    void update($, pane, state => ({
316      ...state,
317      selected: { pid: target.pid, startMs: target.startMs },
318      collapsed: target.hasChildren ? toggleCollapsed(state.collapsed, target.pid) : state.collapsed,
319    })),
320  onSort: () => void update($, pane, state => ({ ...state, sort: cycleSort(state.sort) })),
321  // k: ask first. The targets are checked again at y, so a process that ended meanwhile is left alone.
322  onStop: () =>
323    void (async () => {
324      const state = (await $.state.get(PANE_STATE)).value ?? EMPTY_PANE
325      const snapshot = (await $.state.get(READING)).value?.snapshot
326      if (state.stop) return
327      const pids = snapshot && state.selected ? stopTargets(snapshot, state.selected) : null
328      const row = snapshot?.children?.find(each => isSelected(each, state.selected))
329      if (!pids || !row) {
330        $.ui.toast('proc-stats: that process is no longer listed')
331        return
332      }
333      const stop: StopState = {
334        pid: row.pid,
335        startMs: row.startMs,
336        label: labelOf(row.command),
337        pids,
338        starts: startsOf(snapshot!, pids),
339        checks: 0,
340        phase: 'confirm',
341      }
342      await update($, pane, state => (state.stop ? state : { ...state, stop }))
343    })(),
344  // y: the targets again from this reading, then confirm → sent as one compare-and-set, so a second
345  // press (or one racing it) signals nothing.
346  onConfirm: () =>
347    void (async () => {
348      const snapshot = (await $.state.get(READING)).value?.snapshot
349      if (!snapshot) return
350      let won: StopState | null = null
351      let isGone = false
352      await update($, pane, state => {
353        won = null
354        isGone = false
355        if (state.stop?.phase !== 'confirm') return state
356        const pids = stopTargets(snapshot, state.stop)
357        if (!pids) {
358          isGone = true
359          return { ...state, stop: null }
360        }
361        won = { ...state.stop, pids, starts: startsOf(snapshot, pids), checks: 0, phase: 'sent' }
362
363        return { ...state, stop: won }
364      })
365      if (isGone) toast($, 'proc-stats: that process is no longer listed')
366      const sent = won as StopState | null
367      if (!sent) return
368      const failure = await signal($, snapshot.platform, sent.pids, false)
369      if (failure) toast($, `proc-stats: ${failure}`)
370      $.clock.after(STOP_CHECK_MS, () => void checkStop($))
371    })(),
372  // f: stuck → forced as one compare-and-set, then SIGKILL to exactly the targets still running,
373  // wherever they run now; with none left, the outcome.
374  onForce: () =>
375    void (async () => {
376      const snapshot = (await $.state.get(READING)).value?.snapshot
377      if (!snapshot) {
378        toast($, 'proc-stats: no reading yet; try again')
379        return
380      }
381      let won: StopState | null = null
382      await update($, pane, state => {
383        won = null
384        if (state.stop?.phase !== 'stuck') return state
385        won = { ...state.stop, checks: 0, phase: 'forced' }
386
387        return { ...state, stop: won }
388      })
389      const forced = won as StopState | null
390      if (!forced) return
391      const alive = await aliveTargets($, snapshot.platform, forced)
392      if (alive === null) {
393        await moveStop($, forced, { ...forced, phase: 'stuck' })
394        toast($, 'proc-stats: could not check which processes still run; try again')
395        return
396      }
397      if (alive.length === 0) {
398        if (await moveStop($, forced, null)) toast($, outcomeText(forced, []))
399        return
400      }
401      const failure = await signal($, snapshot.platform, alive, true)
402      if (failure) toast($, `proc-stats: ${failure}`)
403      $.clock.after(STOP_CHECK_MS, () => void checkStop($))
404    })(),
405  onCancel: () => void update($, pane, state => ({ ...state, stop: null })),
406})
407
408// This session's mark: made once and kept across reloads, then set for every command started from now
409// on. Null when it could not be set: detached processes are then not tracked.
410const markSession = async ($: EngineInterface): Promise<SessionMark | null> => {
411  try {
412    const fresh = { id: crypto.randomUUID(), startMs: await $.clock.now() }
413    let mark = fresh
414    await update($, session, kept => (mark = kept.id ? kept : fresh))
415    await $.env.set('PROC_STATS_SESSION', mark.id)
416
417    return mark
418  } catch {
419    return null
420  }
421}
422
423// One loop feeds both views: the status line, and the reading the pane draws.
424const startSampling = async ($: EngineInterface, settings: Settings, mark: SessionMark | null) => {
425  const set = (next: Reading) => update($, reading, () => next)
426
427  try {
428    const platform = await detectPlatform($)
429    const pid = await enginePid($, platform)
430    const capacity = historyCapacity(settings.historyMinutes, settings.intervalMs[platform])
431    const windowMs = settings.historyMinutes * 60_000
432    const spacingMs = pointSpacingMs(settings.historyMinutes)
433    let before: Timed | undefined
434    let isBusy = false
435    // Windows finds no detached processes (documented); elsewhere only with the session marked.
436    const finder: Finder | null = mark && platform !== 'windows' ? { mark, cache: new Map(), scannedAt: -Infinity } : null
437    const detachedOff = mark === null && platform !== 'windows' ? { detachedOff: DETACHED_OFF } : {}
438
439    const sample = async () => {
440      if (isBusy) return
441      isBusy = true
442      try {
443        const sample = await readProcesses($, platform, pid, before?.engine.peakKb ?? 0, finder)
444        if (!isComplete(sample.engine)) throw new Error('unreadable sample')
445        const now = { ...sample, wallMs: await $.clock.now() }
446        const snapshot = { ...buildSnapshot(platform, pid, now, before), ...detachedOff }
447        await set({ snapshot: capRows(snapshot) })
448        try {
449          const kept = (await $.state.get(PANE_STATE)).value ?? EMPTY_PANE
450          const pruned = pruneState(kept, snapshot)
451          if (JSON.stringify(pruned) !== JSON.stringify(kept)) await update($, pane, state => pruneState(state, snapshot))
452        } catch {
453          // The pane keeps its state this reading.
454        }
455        try {
456          const kept = (await $.state.get(ORIGINS)).value ?? EMPTY_ORIGINS
457          const matched = matchOrigins(kept, snapshot, now.wallMs)
458          if (JSON.stringify(matched) !== JSON.stringify(kept)) {
459            await update($, origins, current => matchOrigins(current, snapshot, now.wallMs))
460          }
461        } catch {
462          // Origins catch up at the next reading.
463        }
464        // The pane's Subagents section, while the pane is open: the listing, written when it changed.
465        try {
466          if ((await $.state.get(IS_OPEN)).value) {
467            const listed = toEntries(await $.agent.list())
468            const kept = (await $.state.get(AGENTS)).value ?? []
469            if (JSON.stringify(listed) !== JSON.stringify(kept)) await update($, agents, () => listed)
470            // The models of agents the listing does not name are forgotten.
471            const ids = listed.map(each => each.id)
472            const known = (await $.state.get(MODELS)).value ?? {}
473            if (pruneModels(known, ids) !== known) await update($, models, current => pruneModels(current, ids))
474          }
475        } catch {
476          // The section keeps the last listing this reading.
477        }
478        // A get reads one moment, so the points for the alerts come from the update itself.
479        let points: Point[] = []
480        try {
481          points = (await $.state.get(HISTORY)).value?.points ?? []
482          const point = pointOf(snapshot, now.wallMs)
483          if (point) {
484            await update($, history, kept => {
485              const next = shouldRecord(kept, point, spacingMs)
486                ? pushPoint(kept, point, capacity, windowMs)
487                : kept
488              points = next.points
489
490              return next
491            })
492          }
493        } catch {
494          // The point is skipped; the reading above stands.
495        }
496        // Alerts after the history, which holds this reading's point; their failure costs the marker only.
497        let marker = ''
498        try {
499          const previous = (await $.state.get(ALERTS)).value ?? EMPTY_ALERTS
500          const step = stepAlerts(previous, snapshot, points, now.wallMs, settings, settings.intervalMs[platform])
501          // Written only when it changed: an idle session leaves the state alone.
502          if (JSON.stringify(step.state) !== JSON.stringify(previous)) await update($, alerts, () => step.state)
503          marker = markerFor(worse(step.state.levels.mem, step.state.levels.cpu))
504          if (step.toast) $.ui.toast(step.toast, { timeoutMs: TOAST_MS })
505        } catch {
506          // No marker or toast this reading; the status line still shows.
507        }
508        $.ui.status(`${marker}${statusLine(snapshot, settings.statusShowChildren)}`)
509        before = now
510      } catch {
511        const error = `cannot read process ${pid} on ${platform}`
512        $.ui.status(`proc-stats: ${error}`)
513        await set({ error })
514      } finally {
515        isBusy = false
516      }
517    }
518
519    $.clock.every(settings.intervalMs[platform], () => void sample())
520    await sample()
521  } catch (error) {
522    const text = error instanceof Error ? error.message : 'unavailable'
523    $.ui.status(`proc-stats: ${text}`)
524    await set({ error: text })
525  }
526}
527
528// The agent of a call: the listed subagent, an unnamed agent when the listing does not name it
529// (or cannot be read), or null for the main conversation.
530const agentOf = async ($: EngineInterface, agentId: string | undefined): Promise<Origin['agent']> => {
531  if (!agentId) return null
532  try {
533    const listed = (await $.agent.list()).find(agent => agent.id === agentId)
534    if (listed) return { id: agentId, type: listed.type, description: listed.description }
535  } catch {
536    // Unnamed below.
537  }
538
539  return { id: agentId, ...UNNAMED_AGENT }
540}
541
542// Records a Bash or Monitor call before it runs, with the agent whose call it is, and drops calls
543// past the TTL. Never throws: a failure here costs the origin only, never the call.
544const recordCall = async ($: EngineInterface, tool: string, e: { tool_use_id: string; command?: unknown; agentId?: string }) => {
545  if (typeof e.command !== 'string' || !e.command) return
546  try {
547    const at = await $.clock.now()
548    const call: OriginCall = { id: e.tool_use_id, tool, agent: await agentOf($, e.agentId), command: e.command, at, settledAt: null }
549    await update($, origins, kept => ({ ...kept, calls: [...kept.calls.filter(each => at - each.at <= CALL_TTL_MS), call] }))
550  } catch {
551    // The process will show without an origin.
552  }
553}
554
555// Marks a recorded call settled: the tool returned. Never throws.
556const settleCall = async ($: EngineInterface, id: string) => {
557  try {
558    const settledAt = await $.clock.now()
559    await update($, origins, kept =>
560      kept.calls.some(each => each.id === id)
561        ? { ...kept, calls: kept.calls.map(each => (each.id === id ? { ...each, settledAt } : each)) }
562        : kept,
563    )
564  } catch {
565    // The call stays running until its TTL.
566  }
567}
568
569// The command a recorded call runs, as the check sees it: after any PreToolUse rewrite. Never throws.
570const checkCall = async ($: EngineInterface, e: { tool_use_id?: string; input: unknown }) => {
571  const id = e.tool_use_id
572  const command = (e.input as { command?: unknown } | null)?.command
573  if (!id || typeof command !== 'string' || !command) return
574  try {
575    const kept = (await $.state.get(ORIGINS)).value ?? EMPTY_ORIGINS
576    if (!kept.calls.some(each => each.id === id && each.command !== command)) return
577    await update($, origins, current => ({
578      ...current,
579      calls: current.calls.map(each => (each.id === id ? { ...each, command } : each)),
580    }))
581  } catch {
582    // The call keeps the command it was recorded with.
583  }
584}
585
586// Runs a Bash or Monitor call: recorded before, settled after, the call and its answer unchanged.
587const traceCall = async <E extends { tool_use_id: string; command?: unknown; agentId?: string }, R>(
588  $: EngineInterface,
589  tool: string,
590  e: E,
591  next: (e: E) => Promise<R>,
592): Promise<R> => {
593  await recordCall($, tool, e)
594  try {
595    return await next(e)
596  } finally {
597    await settleCall($, e.tool_use_id)
598  }
599}
600
601// Records the model and effort of an agent's request (`''` for the main conversation) when they changed.
602// Never throws: a failure here costs the display only, never the request.
603const recordModel = async ($: EngineInterface, key: string, model: string, effort: ModelUse['effort']) => {
604  try {
605    const use: ModelUse = { model, effort }
606    const kept = (await $.state.get(MODELS)).value ?? {}
607    if (withModel(kept, key, use) !== kept) await update($, models, current => withModel(current, key, use))
608  } catch {
609    // The row shows the model it had.
610  }
611}
612
613// The report from current state, as the person and the model read it.
614const report = async ($: EngineInterface, historyMinutes: number) =>
615  reportText({
616    reading: await read($, reading),
617    points: (await read($, history)).points,
618    alerts: await read($, alerts),
619    origins: await read($, origins),
620    now: await $.clock.now(),
621    historyMinutes,
622  })
623
624// A settings change reloads the module, so they are read once per load.
625export const register: Register = (on, options) => {
626  const settings = readSettings(options)
627
628  on('session.start', async ($, e, next) => {
629    const started = await next(e)
630    await $.command.register({
631      name: COMMAND,
632      description: 'Show Claude Code and the processes it started in a task-manager pane, or a report',
633      argumentHint: '[report]',
634    })
635    void startSampling($, settings, await markSession($))
636    // A reload drops the check timer of a stop already signalled; schedule it again.
637    const phase = (await $.state.get(PANE_STATE)).value?.stop?.phase
638    if (phase === 'sent' || phase === 'forced') $.clock.after(STOP_CHECK_MS, () => void checkStop($))
639    // A reload closes the pane (an unload no hook hears); put it back if it was open.
640    if (await read($, isOpen)) void $.ui.open(OPEN).catch(() => undefined)
641
642    return started
643  })
644
645  // Where processes come from: each Bash and Monitor call is recorded before it runs.
646  on('tool.call', { tool: 'Bash' }, ($, e, next) => traceCall($, 'Bash', e, next)).catch(($, e, next) => next(e))
647
648  on('tool.call', { tool: 'Monitor' }, ($, e, next) => traceCall($, 'Monitor', e, next)).catch(($, e, next) => next(e))
649
650  // A PreToolUse hook may rewrite the command; the check sees it as it will run.
651  on('tool.check', { tool: 'Bash' }, async ($, e, next) => {
652    await checkCall($, e)
653
654    return next(e)
655  }).catch(($, e, next) => next(e))
656
657  on('tool.check', { tool: 'Monitor' }, async ($, e, next) => {
658    await checkCall($, e)
659
660    return next(e)
661  }).catch(($, e, next) => next(e))
662
663  // Which model and effort each request names, for the pane; recorded without waiting, the request passes untouched.
664  on('turn.step', async function* ($, e, next) {
665    void recordModel($, e.agentId ?? '', e.model, e.effort)
666
667    return yield* next(e)
668  }).catch(async function* ($, e, next) {
669    return yield* next(e)
670  })
671
672  // Bare: the pane. `report`: the report as the command's output. Anything else: how to use it.
673  on('command.run', { command: COMMAND }, async ($, e) => {
674    const typed = e.args.trim()
675    if (typed.toLowerCase() === 'report') {
676      try {
677        return { text: await report($, settings.historyMinutes) }
678      } catch {
679        return { text: 'the report could not be made; try again.' }
680      }
681    }
682    if (typed !== '') return { text: `unknown argument "${typed}". ${USAGE}` }
683    const opened = await $.ui.open({ ...OPEN, focus: true })
684    await update($, isOpen, () => true)
685    // The Subagents section from the first draw, not only from the next reading.
686    try {
687      const listed = toEntries(await $.agent.list())
688      await update($, agents, () => listed)
689    } catch {
690      // The next reading fills it.
691    }
692
693    return { text: opened.isPlaced ? 'Processes pane opened.' : 'Processes pane could not be placed.' }
694  }).catch(($, e, next) =>
695    next.called ? next(e) : { text: 'the Processes pane could not be opened.' },
696  )
697
698  // A close the person or the engine makes. A reload is no close: the pane comes back.
699  on('ui.close', { id: PANE }, async ($, e, next) => {
700    const closed = await next(e)
701    await update($, isOpen, () => false)
702    // A reopened pane shows no statuses from before.
703    await update($, agents, () => [])
704
705    return closed
706  }).catch(($, e, next) => next(e))
707
708  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) =>
709    drawPane(
710      $.ui.resolve(e),
711      await read($, reading),
712      await read($, pane),
713      (await read($, history)).points,
714      await read($, origins),
715      await read($, agents),
716      await read($, models),
717      e.props.bodyColumns,
718      paneHandlers($),
719    ),
720  )
721
722  // Arrow keys move the focus ring over the rows; the row it lands on is the selection.
723  on('ui.focus', { requestId: PANE }, async ($, e, next) => {
724    const moved = await next(e)
725    if (e.element === undefined) {
726      await update($, pane, state => (state.stop?.phase === 'confirm' ? { ...state, stop: null } : state))
727    }
728    const pid = e.element?.startsWith('pid:') ? Number(e.element.slice(4)) : null
729    if (pid !== null && !('deny' in moved)) {
730      const snapshot = (await $.state.get(READING)).value?.snapshot
731      const row = snapshot?.children?.find(each => each.pid === pid)
732      await update($, pane, state => ({ ...state, selected: { pid, startMs: row?.startMs ?? 0 } }))
733    }
734
735    return moved
736  }).catch(($, e, next) => next(e))
737}
738
hooks/agents.ts 122 lines
1// The Subagents section: the session's agents, each with the processes it started.
2
3import type { AgentEntry, AgentRow, Origins, Snapshot } from '../types'
4import { originOf } from './origin'
5
6export const ACTIVE_STATUSES: readonly string[] = ['pending', 'running', 'waiting', 'idle']
7
8// The status of an agent with processes that the listing does not name: not necessarily ended, as a
9// workflow's agents and the engine's own forks carry ids no listing names.
10export const UNLISTED = 'not listed'
11
12// What `$.agent.list()` answers, as far as the section reads it.
13export type ListedAgent = {
14  id: string
15  type: string
16  description: string
17  status: string
18  parentId?: string
19  name?: string
20  teammateId?: string
21}
22
23// The listing trimmed to what the section draws: a name only for a teammate (a background
24// subagent's engine-given name is not one to show).
25export const toEntries = (listed: readonly ListedAgent[]): AgentEntry[] =>
26  listed.map(({ id, type, description, status, parentId, name, teammateId }) => ({
27    id,
28    type,
29    description,
30    status,
31    ...(parentId !== undefined ? { parentId } : {}),
32    ...(teammateId !== undefined && name !== undefined ? { name } : {}),
33  }))
34
35export type Tally = { type: string; description: string; count: number; kb: number; cpuPercent: number | null }
36
37// Each agent's processes, by agent id: every row counts toward the nearest row at or above it, within
38// its group (the tree, then the detached group), whose origin names an agent by id.
39export const tallyByAgent = (snapshot: Snapshot, origins: Origins): Map<string, Tally> => {
40  const tallies = new Map<string, Tally>()
41  // The owning agent at each depth of the current branch.
42  let owners: (string | null)[] = []
43  let isDetached = false
44  for (const row of snapshot.children ?? []) {
45    if ((row.detached ?? false) !== isDetached) {
46      owners = []
47      isDetached = row.detached ?? false
48    }
49    const agent = originOf(origins, row)?.agent
50    const owner = agent?.id ?? (row.depth > 0 ? (owners[row.depth - 1] ?? null) : null)
51    owners = owners.slice(0, row.depth)
52    owners[row.depth] = owner
53    if (owner === null) continue
54    const kept = tallies.get(owner)
55    const type = kept?.type ?? agent?.type ?? 'agent'
56    const description = kept?.description ?? agent?.description ?? ''
57    // Null once any of its processes has no CPU yet.
58    const cpuPercent = !kept
59      ? row.cpuPercent
60      : kept.cpuPercent === null || row.cpuPercent === null
61        ? null
62        : kept.cpuPercent + row.cpuPercent
63    tallies.set(owner, { type, description, count: (kept?.count ?? 0) + 1, kb: (kept?.kb ?? 0) + row.rssKb, cpuPercent })
64  }
65
66  return tallies
67}
68
69const labelOf = (agent: AgentEntry) => {
70  const who = agent.name ?? agent.type
71
72  return agent.description ? `${who}: ${agent.description}` : who
73}
74
75// The section's rows: listed agents that are active or have processes, then agents with processes the
76// listing no longer names; each agent's children under it, in order. A parent not shown, or a cycle,
77// makes a root.
78export const agentRows = (agents: AgentEntry[], snapshot: Snapshot, origins: Origins): AgentRow[] => {
79  const tallies = tallyByAgent(snapshot, origins)
80  const listed = new Set(agents.map(agent => agent.id))
81  const kept: AgentEntry[] = [
82    ...agents.filter(agent => ACTIVE_STATUSES.includes(agent.status) || tallies.has(agent.id)),
83    ...[...tallies]
84      .filter(([id]) => !listed.has(id))
85      .map(([id, tally]) => ({ id, type: tally.type, description: tally.description, status: UNLISTED })),
86  ]
87  const shown = new Set(kept.map(agent => agent.id))
88  // An agent whose parent chain leaves the shown agents or loops is a root.
89  const parentOf = (agent: AgentEntry): string | undefined => {
90    const seen = new Set([agent.id])
91    let parent = agent.parentId
92    while (parent !== undefined && shown.has(parent)) {
93      if (seen.has(parent)) return undefined
94      seen.add(parent)
95      parent = kept.find(each => each.id === parent)?.parentId
96    }
97
98    return agent.parentId !== undefined && shown.has(agent.parentId) ? agent.parentId : undefined
99  }
100  const parents = new Map(kept.map(agent => [agent.id, parentOf(agent)]))
101  const rows: AgentRow[] = []
102  const visit = (parent: string | undefined, depth: number) => {
103    for (const agent of kept.filter(each => parents.get(each.id) === parent)) {
104      const tally = tallies.get(agent.id)
105      rows.push({
106        id: agent.id,
107        label: labelOf(agent),
108        status: agent.status,
109        isEnded: !ACTIVE_STATUSES.includes(agent.status),
110        depth,
111        processCount: tally?.count ?? 0,
112        rssKb: tally?.kb ?? 0,
113        cpuPercent: tally ? tally.cpuPercent : null,
114      })
115      visit(agent.id, depth + 1)
116    }
117  }
118  visit(undefined, 0)
119
120  return rows
121}
122
hooks/history.ts 50 lines
1// Session totals over time: what the alerts average and the sparklines draw.
2
3import type { History, Point, Snapshot } from '../types'
4
5// No more points than this, however long the window or short the interval.
6export const MAX_POINTS = 2400
7
8export const historyCapacity = (minutes: number, intervalMs: number) =>
9  Math.min(MAX_POINTS, Math.max(2, Math.ceil((minutes * 60_000) / intervalMs)))
10
11// How far apart points are kept so the window fits MAX_POINTS.
12export const pointSpacingMs = (minutes: number) => (minutes * 60_000) / MAX_POINTS
13
14// A point is kept when the history is empty or the spacing has passed since the last.
15export const shouldRecord = (history: History, point: Point, spacingMs: number) => {
16  const last = history.points.at(-1)
17
18  return last === undefined || point.t - last.t >= spacingMs
19}
20
21// Points within the window, the newest `capacity` of them (so a smaller capacity trims the oldest).
22export const pushPoint = (history: History, point: Point, capacity: number, windowMs: number): History => ({
23  points: [...history.points, point].filter(kept => kept.t >= point.t - windowMs).slice(-capacity),
24})
25
26// One value per bucket, its maximum, so a spike is never averaged away.
27export const downsample = (values: number[], width: number) => {
28  if (values.length <= width) return values
29  const n = values.length
30
31  return Array.from({ length: width }, (_, i) =>
32    Math.max(...values.slice(Math.floor((i * n) / width), Math.floor(((i + 1) * n) / width))),
33  )
34}
35
36// The mean of the points in the last `windowMs`, its start included; null with none to average.
37export const averageSince = (points: Point[], now: number, windowMs: number, pick: (point: Point) => number) => {
38  const recent = points.filter(point => point.t >= now - windowMs)
39
40  return recent.length === 0 ? null : recent.reduce((sum, point) => sum + pick(point), 0) / recent.length
41}
42
43// Null until CPU and the children can be measured, so the history holds whole points only.
44export const pointOf = (snapshot: Snapshot, t: number): Point | null => {
45  const { engine, childKb, childCpuPercent, children } = snapshot
46  if (engine.cpuPercent === null || children === null || childCpuPercent === null) return null
47
48  return { t, memKb: engine.rssKb + childKb, cpuPct: Math.round((engine.cpuPercent + childCpuPercent) * 10) / 10 }
49}
50
hooks/alerts.ts 161 lines
1// The status-line marker and the toasts for busy or large child processes.
2
3import type { AlertState, Level, Point, ProcRow, ProcTrack, Snapshot } from '../types'
4import { formatBytes, formatDuration } from './format'
5import { averageSince } from './history'
6import type { Settings } from './settings'
7
8// The CPU average the marker reads: the last 10 s, or two refreshes when the refresh is slower.
9// The points must cover half of it.
10export const CPU_WINDOW_MS = 10_000
11// A level, or a fired toast, clears only below this share of its limit.
12export const FALL_BACK = 0.9
13// How long a fired toast stays below FALL_BACK before it re-arms.
14export const COOL_MS = 10_000
15
16// How many sent toasts the alerts keep for the report.
17export const RECENT_TOASTS = 5
18
19export const EMPTY_ALERTS: AlertState = { levels: { mem: 'none', cpu: 'none' }, tracks: {} }
20
21const RANK: Record<Level, number> = { none: 0, warn: 1, alert: 2 }
22
23// Above a limit rises at once; falling waits until 10% below the limit held.
24export const levelFor = (value: number, warn: number, alert: number, previous: Level): Level => {
25  const raw: Level = value > alert ? 'alert' : value > warn ? 'warn' : 'none'
26  if (RANK[raw] >= RANK[previous]) return raw
27  if (previous === 'alert' && value > alert * FALL_BACK) return 'alert'
28
29  return value > warn * FALL_BACK ? 'warn' : 'none'
30}
31
32export const worse = (a: Level, b: Level): Level => (RANK[a] >= RANK[b] ? a : b)
33
34export const markerFor = (level: Level) => (level === 'alert' ? '🔴 ' : level === 'warn' ? '🟡 ' : '')
35
36// Null until the window holds two points spanning half of it, so one spike is no average.
37export const cpuAverage = (points: Point[], now: number, intervalMs: number): number | null => {
38  const window = Math.max(CPU_WINDOW_MS, 2 * intervalMs)
39  const recent = points.filter(point => point.t >= now - window)
40  const first = recent[0]
41  const last = recent[recent.length - 1]
42  if (!first || !last || recent.length < 2 || last.t - first.t < window / 2) return null
43
44  return averageSince(recent, now, window, point => point.cpuPct)
45}
46
47// Memory is the current total (Claude Code alone while the table is unreadable, which holds the level); CPU the average.
48export const sessionLevels = (
49  snapshot: Snapshot,
50  points: Point[],
51  now: number,
52  settings: Settings,
53  previous: AlertState['levels'],
54  intervalMs: number,
55): AlertState['levels'] => {
56  const memMb = (snapshot.engine.rssKb + snapshot.childKb) / 1024
57  const cpu = cpuAverage(points, now, intervalMs)
58  const mem = levelFor(memMb, settings.warnMemMb, settings.alertMemMb, previous.mem)
59
60  return {
61    // Without the process table the total is Claude Code alone: it may raise the level, never lower it.
62    mem: snapshot.children === null ? worse(previous.mem, mem) : mem,
63    cpu: cpu === null ? previous.cpu : levelFor(cpu, settings.warnCpuPct, settings.alertCpuPct, previous.cpu),
64  }
65}
66
67export type Fired = { kind: 'cpu' | 'mem'; pid: number; command: string; cpuPercent: number; seconds: number; limitKb: number; limitPct: number }
68
69const fresh = (startMs: number): ProcTrack => ({
70  startMs,
71  cpuSince: null,
72  cpuFired: false,
73  cpuCoolSince: null,
74  memFired: false,
75  memCoolSince: null,
76})
77
78// A fired toast re-arms after COOL_MS spent below FALL_BACK of its limit.
79const cool = (isFired: boolean, isBelow: boolean, since: number | null, now: number) => {
80  if (!isFired || !isBelow) return { isFired, since: null }
81  const start = since ?? now
82
83  return now - start >= COOL_MS ? { isFired: false, since: null } : { isFired, since: start }
84}
85
86// One reading of the listed processes (under Claude Code and detached): the trackers after it, and the toasts it fires.
87export const trackProcesses = (tracks: Record<string, ProcTrack>, rows: ProcRow[], now: number, settings: Settings) => {
88  const next: Record<string, ProcTrack> = {}
89  const fired: Fired[] = []
90  const cpuLimit = settings.toastCpuPct
91  const memLimitKb = settings.toastMemMb * 1024
92  for (const row of rows) {
93    const was = tracks[String(row.pid)]
94    const startMs = now - row.uptimeSeconds * 1000
95    // A start more than 2 s later than the tracked one is another process under a reused pid;
96    // a tracker without a start (an older shape) counts as another too. The tracked start stays.
97    const track: ProcTrack = was && typeof was.startMs === 'number' && startMs <= was.startMs + 2000 ? { ...was } : fresh(startMs)
98
99    if (row.cpuPercent !== null) {
100      const cpu = row.cpuPercent
101      const cooled = cool(track.cpuFired, cpu < cpuLimit * FALL_BACK, track.cpuCoolSince, now)
102      track.cpuFired = cooled.isFired
103      track.cpuCoolSince = cooled.since
104      track.cpuSince = cpu > cpuLimit ? (track.cpuSince ?? now) : cpu < cpuLimit * FALL_BACK ? null : track.cpuSince
105      if (!track.cpuFired && track.cpuSince !== null && now - track.cpuSince >= settings.toastCpuSeconds * 1000) {
106        track.cpuFired = true
107        fired.push({ kind: 'cpu', pid: row.pid, command: row.command, cpuPercent: cpu, seconds: (now - track.cpuSince) / 1000, limitKb: 0, limitPct: cpuLimit })
108      }
109    }
110
111    const cooled = cool(track.memFired, row.rssKb < memLimitKb * FALL_BACK, track.memCoolSince, now)
112    track.memFired = cooled.isFired
113    track.memCoolSince = cooled.since
114    if (!track.memFired && row.rssKb > memLimitKb) {
115      track.memFired = true
116      fired.push({ kind: 'mem', pid: row.pid, command: row.command, cpuPercent: 0, seconds: 0, limitKb: memLimitKb, limitPct: 0 })
117    }
118
119    next[String(row.pid)] = track
120  }
121
122  return { tracks: next, fired }
123}
124
125// One line, at most 40 code points.
126const short = (command: string) => {
127  const chars = Array.from(command.replace(/\s+/g, ' ').trim())
128
129  return chars.length > 40 ? `${chars.slice(0, 39).join('')}…` : chars.join('')
130}
131
132const describe = (fired: Fired) =>
133  fired.kind === 'cpu'
134    ? `${short(fired.command)} has used ~${Math.round(Math.max(fired.cpuPercent, fired.limitPct))}% CPU for ${formatDuration(fired.seconds)} · pid ${fired.pid}`
135    : `${short(fired.command)} grew past ${formatBytes(fired.limitKb)} · pid ${fired.pid}`
136
137// One toast per reading: each process's lines, or a count once several processes fire together.
138export const toastText = (fired: Fired[]) => {
139  if (fired.length === 0) return null
140  const pids = [...new Set(fired.map(entry => entry.pid))]
141  if (pids.length === 1) return `${fired.map(describe).join(' · ')} · /proc-stats`
142  const names = pids.map(pid => short(fired.find(entry => entry.pid === pid)!.command))
143
144  return `${pids.length} processes over limits: ${names.join(', ')} · /proc-stats`
145}
146
147// One reading: the next alert state and the toast, if any, which joins the recent toasts. The first
148// reading (no CPU yet) and an unreadable table move the levels only.
149export const stepAlerts = (state: AlertState, snapshot: Snapshot, points: Point[], now: number, settings: Settings, intervalMs: number) => {
150  const levels = sessionLevels(snapshot, points, now, settings, state.levels, intervalMs)
151  if (snapshot.engine.cpuPercent === null || snapshot.children === null) {
152    return { state: { ...state, levels }, toast: null }
153  }
154  const { tracks, fired } = trackProcesses(state.tracks, snapshot.children, now, settings)
155  const toast = toastText(fired)
156  // A toast sent joins the recent ones; without one they stay as they were (absent until the first).
157  const recent = toast ? { recent: [...(state.recent ?? []), { t: now, text: toast }].slice(-RECENT_TOASTS) } : {}
158
159  return { state: { ...state, levels, tracks, ...recent }, toast }
160}
161
hooks/detached.ts 73 lines
1// Detached processes: ones this session started that no longer run under Claude Code. Each command
2// the session starts carries PROC_STATS_SESSION=<id> in its environment, and keeps it when it detaches.
3
4import { parsePsTime } from './stats'
5import { START_TOLERANCE_MS } from './view'
6
7// What the environment holds for this session's processes.
8export const markOf = (id: string) => `PROC_STATS_SESSION=${id}`
9
10// A process seen in the table: its pid and when it started (ms since the epoch).
11export type Started = { pid: number; startMs: number }
12
13// What is known of a pid: its start, and whether its environment holds the mark.
14export type MarkCache = Map<number, { startMs: number; isOurs: boolean }>
15
16// Linux: /proc/<pid>/environ is NUL-separated `NAME=value` entries.
17export const environHasMark = (environ: string, id: string) => environ.split('\0').includes(markOf(id))
18
19// macOS: `ps eww -o pid=,command= -p …` prints each pid, its command and then its environment, space-separated.
20export const macMarkedPids = (stdout: string, id: string) => {
21  const mark = markOf(id)
22  const pids = new Set<number>()
23  for (const line of stdout.split(/\r?\n/)) {
24    const fields = line.trim().split(/\s+/)
25    if (fields.slice(1).includes(mark)) pids.add(Number(fields[0]))
26  }
27
28  return pids
29}
30
31// macOS: the pids that lead a line of that output, whether marked or not.
32export const macListedPids = (stdout: string) => {
33  const pids = new Set<number>()
34  for (const line of stdout.split(/\r?\n/)) {
35    const pid = Number(line.trim().split(/\s+/)[0])
36    if (Number.isInteger(pid) && pid > 0) pids.add(pid)
37  }
38
39  return pids
40}
41
42// The processes that could be ours: started since the session began (with two seconds' slack) and not
43// excluded (Claude Code, what runs under it, and the reader itself).
44export const candidatesOf = (started: Started[], excluded: Set<number>, sessionStartMs: number) =>
45  started.filter(each => !excluded.has(each.pid) && each.startMs >= sessionStartMs - START_TOLERANCE_MS)
46
47const isKnown = (cache: MarkCache, each: Started) => {
48  const known = cache.get(each.pid)
49
50  return known !== undefined && Math.abs(known.startMs - each.startMs) <= START_TOLERANCE_MS
51}
52
53// The candidates whose environment has not been read yet (a reused pid counts as unread).
54export const unreadOf = (cache: MarkCache, candidates: Started[]) => candidates.filter(each => !isKnown(cache, each))
55
56// The cache after a reading: what was just read, plus what is still known of the candidates; ended
57// processes and reused pids leave it.
58export const rememberMarks = (cache: MarkCache, candidates: Started[], read: (Started & { isOurs: boolean })[]): MarkCache => {
59  const next: MarkCache = new Map()
60  for (const each of candidates) if (isKnown(cache, each)) next.set(each.pid, cache.get(each.pid)!)
61  for (const each of read) next.set(each.pid, { startMs: each.startMs, isOurs: each.isOurs })
62
63  return next
64}
65
66// The candidates known to be ours.
67export const oursOf = (cache: MarkCache, candidates: Started[]) =>
68  candidates.filter(each => isKnown(cache, each) && cache.get(each.pid)!.isOurs).map(each => each.pid)
69
70// Each table row's pid and start, its elapsed time (`[[dd-]hh:]mm:ss`) in column `etimeColumn`, read at `wallMs`.
71export const startedFrom = (rows: string[][], etimeColumn: number, wallMs: number): Started[] =>
72  rows.map(fields => ({ pid: Number(fields[0]), startMs: wallMs - parsePsTime(fields[etimeColumn] ?? '') * 1000 }))
73
hooks/origin.ts 86 lines
1// Which tool call, and which agent, started each of Claude Code's Bash and Monitor processes.
2
3import type { Origin, OriginCall, Origins, ProcRow, Snapshot } from '../types'
4import { START_TOLERANCE_MS, unwrapCommand } from './view'
5
6export const EMPTY_ORIGINS: Origins = { calls: [], byPid: {} }
7
8// A call still running and unmatched is forgotten after this long.
9export const CALL_TTL_MS = 600_000
10
11// A call starts its process while it runs: from when it was recorded (it may wait on a permission
12// prompt first) until it settled, both within the start tolerance.
13const isEligible = (call: OriginCall, startMs: number) =>
14  call.at <= startMs + START_TOLERANCE_MS &&
15  (typeof call.settledAt !== 'number' || startMs <= call.settledAt + START_TOLERANCE_MS)
16
17// Each reading: keep origins whose process is still listed with the same start; give each unmatched
18// wrapper row, oldest first, the oldest eligible recorded call with its exact command; drop calls
19// matched, settled before this reading (beyond the tolerance, since the table was read just before
20// `now`), or still running past the TTL. An unreadable table changes nothing.
21// Identical commands started in the same instant by different agents cannot be told apart.
22export const matchOrigins = (origins: Origins, snapshot: Snapshot, now: number): Origins => {
23  const rows = snapshot.children
24  if (rows === null) return origins
25  const byPid: Origins['byPid'] = {}
26  for (const row of rows) {
27    const kept = origins.byPid[String(row.pid)]
28    if (kept && Math.abs(kept.startMs - row.startMs) <= START_TOLERANCE_MS) byPid[String(row.pid)] = kept
29  }
30  let calls = origins.calls.filter(each => typeof each.settledAt === 'number' || now - each.at <= CALL_TTL_MS)
31  const waiting = rows
32    .filter(row => byPid[String(row.pid)] === undefined)
33    .map(row => ({ row, inner: unwrapCommand(row.command) }))
34    .filter((each): each is { row: ProcRow; inner: string } => each.inner !== null)
35    .sort((a, b) => a.row.startMs - b.row.startMs)
36  for (const { row, inner } of waiting) {
37    let index = -1
38    calls.forEach((each, at) => {
39      const eligible = each.command === inner && isEligible(each, row.startMs)
40      if (eligible && (index < 0 || each.at < calls[index]!.at)) index = at
41    })
42    if (index < 0) continue
43    const { tool, agent } = calls[index]!
44    byPid[String(row.pid)] = { tool, agent, startMs: row.startMs }
45    calls = [...calls.slice(0, index), ...calls.slice(index + 1)]
46  }
47
48  // A settled call's process, if it had one, started before it settled: this reading had it.
49  calls = calls.filter(each => typeof each.settledAt !== 'number' || each.settledAt + START_TOLERANCE_MS >= now)
50
51  return { calls, byPid }
52}
53
54// The origin of a listed process, matched by pid and start; null when unknown.
55export const originOf = (origins: Origins, row: { pid: number; startMs: number }): Origin | null => {
56  const kept = origins.byPid[String(row.pid)]
57  if (!kept || Math.abs(kept.startMs - row.startMs) > START_TOLERANCE_MS) return null
58
59  return { tool: kept.tool, agent: kept.agent }
60}
61
62// The agent of a call whose agentId no listing names.
63export const UNNAMED_AGENT = { type: 'agent', description: '' }
64
65// Short, for the command cell: the tool, the subagent's type, or `agent` for an unnamed one.
66export const originLabel = (origin: Origin) => {
67  if (!origin.agent) return origin.tool
68
69  return origin.agent.type === UNNAMED_AGENT.type ? 'agent' : `subagent: ${origin.agent.type}`
70}
71
72// Long, for the details.
73export const originDetail = (origin: Origin) => {
74  if (!origin.agent) return `started by ${origin.tool} in the main conversation`
75  if (!origin.agent.description) return `started by ${origin.tool} in an agent`
76
77  return `started by ${origin.tool} in subagent ${origin.agent.type}: ${origin.agent.description}`
78}
79
80// The command cell's origin text for a listed process; undefined when unknown.
81export const originText = (origins: Origins, row: { pid: number; startMs: number }): string | undefined => {
82  const origin = originOf(origins, row)
83
84  return origin ? originLabel(origin) : undefined
85}
86
hooks/models.ts 40 lines
1// The model and effort of each agent's latest request, as the Subagents rows and Claude Code's row show them.
2
3import type { ModelUse } from '../types'
4
5// The model id as shown: after `claude-` (a provider prefix goes too), without a trailing `-YYYYMMDD` date; a `[…]` tag stays.
6export const modelName = (id: string): string => {
7  const at = id.indexOf('claude-')
8  if (at < 0) return id
9
10  return id.slice(at + 'claude-'.length).replace(/-\d{8}(?=\[|$)/, '')
11}
12
13// The map with `use` under `key`: `kept` itself when it holds that already.
14export const withModel = (kept: Record<string, ModelUse>, key: string, use: ModelUse): Record<string, ModelUse> => {
15  const had = kept[key]
16  if (had !== undefined && had.model === use.model && had.effort === use.effort) return kept
17
18  return { ...kept, [key]: use.effort === undefined ? { model: use.model } : { model: use.model, effort: use.effort } }
19}
20
21// The map without the agents the listing does not name; the main conversation (`''`) stays. `kept` itself when nothing drops.
22export const pruneModels = (kept: Record<string, ModelUse>, listedIds: readonly string[]): Record<string, ModelUse> => {
23  const keys = Object.keys(kept)
24  const stays = keys.filter(key => key === '' || listedIds.includes(key))
25  if (stays.length === keys.length) return kept
26
27  return Object.fromEntries(stays.map(key => [key, kept[key]!]))
28}
29
30// The model and effort as shown, joined by ` · `: `model` and `model · effort` when known, else nothing.
31export const modelParts = (use: ModelUse | undefined): string =>
32  use === undefined ? '' : `${modelName(use.model)}${use.effort === undefined ? '' : ` · ${use.effort}`}`
33
34// The dim text after a name or status: ` · model` and ` · effort` when known, else nothing.
35export const modelText = (use: ModelUse | undefined): string => {
36  const parts = modelParts(use)
37
38  return parts === '' ? '' : ` · ${parts}`
39}
40
hooks/pane.tsx 294 lines
1import type { Elements, RenderSurface } from 'claude-code'
2
3import type { AgentEntry, AgentRow, ModelUse, Origins, PaneState, Point, Reading } from '../types'
4import { agentRows } from './agents'
5import { modelParts, modelText } from './models'
6import { originText } from './origin'
7import { formatBytes, formatDuration, formatPercent } from './format'
8import { sparkLines } from './sparkline'
9import { confirmText } from './stop'
10import { detailLines, fit, isSelected, noteLine, totalLines, treePrefixes, viewRows } from './view'
11import type { ViewRow } from './view'
12
13const PID_WIDTH = 7
14const NUMBER_WIDTH = 7
15const TIME_WIDTH = 7
16const MIN_COMMAND = 12
17// Space around the pane's contents, in cells: each side, and below. Rows pad
18// their own sides too, so a stripe reaches past the text it holds.
19const PADDING_X = 1
20const ROW_PADDING_X = 1
21const PADDING_BOTTOM = 1
22// Theme keys, so both follow the person's light or dark theme.
23const HEADER_COLOR = 'claude'
24const HEADER_TEXT = 'inverseText'
25const STRIPE_COLOR = 'subtle'
26
27// The columns that fit: TIME goes first, then PID, the command keeping the rest.
28export const paneColumns = (bodyColumns: number) => {
29  const fixed = (showPid: boolean, showTime: boolean) =>
30    (showPid ? PID_WIDTH + 1 : 0) + (NUMBER_WIDTH + 1) * 2 + (showTime ? TIME_WIDTH + 1 : 0)
31  const showTime = bodyColumns - fixed(true, true) >= MIN_COMMAND
32  const showPid = bodyColumns - fixed(true, false) >= MIN_COMMAND || showTime
33
34  return {
35    showPid,
36    showTime,
37    commandWidth: Math.max(MIN_COMMAND, bodyColumns - fixed(showPid, showTime)),
38  }
39}
40
41export type RowTarget = { pid: number; startMs: number; hasChildren: boolean }
42
43// What the pane's presses do; register.ts builds them. Stop handlers are optional: without them no stop is offered.
44export type PaneHandlers = {
45  onRow: (target: RowTarget) => void
46  onSort: () => void
47  onStop?: () => void
48  onConfirm?: () => void
49  onCancel?: () => void
50  onForce?: () => void
51}
52
53const marker = (view: ViewRow) => (view.hasChildren ? (view.isCollapsed ? '▸ ' : '▾ ') : '')
54
55// The command cell: tree lines, the collapse marker and the label; then, dim, its origin and
56// (in sorted views) its parent, given at most a third of the width.
57export const commandCell = (view: ViewRow, width: number, origin?: string) => {
58  const main = `${view.prefix}${marker(view)}${view.label}`
59  const tail = `${origin ? ` · ${origin}` : ''}${view.parent !== null ? ` ← ${view.parent}` : ''}`
60  if (tail === '') return { main: fit(main, width), parent: '' }
61  const tailWidth = Math.min(Array.from(tail).length, Math.floor(width / 3))
62
63  return { main: fit(main, width - tailWidth), parent: fit(tail, tailWidth) }
64}
65
66// A command cell of exactly `width` cells: `head` cut to fit, then a dim tail of `status` and `extra`
67// that takes at most width - 1 cells. The status stays whole when it fits; `extra` is cut to what is left.
68const tailedCell = (head: string, status: string, extra: string, width: number) => {
69  const room = Math.max(0, width - 1)
70  const statusCells = Array.from(status).length
71  const left = room - statusCells
72  const shownStatus = left >= 0 ? status : fit(status, room)
73  const shownExtra = left <= 1 ? '' : Array.from(extra).length <= left ? extra : fit(extra, left)
74  const tail = `${shownStatus}${shownExtra}`
75
76  return { main: fit(head, width - Array.from(tail).length), tail }
77}
78
79// An agent row's command cell: tree lines and its label cut to fit, then its status and `extra`, which give way
80// (extra first) so the cell stays `width` cells.
81export const agentCell = (agent: AgentRow, prefix: string, width: number, extra = '') =>
82  tailedCell(`${prefix}${agent.label}`, ` · ${agent.status}`, extra, width)
83
84export const drawPane = (
85  { Box, Text, Button }: Elements[RenderSurface],
86  { snapshot, error }: Reading,
87  state: PaneState,
88  points: Point[],
89  origins: Origins,
90  agents: AgentEntry[],
91  models: Record<string, ModelUse>,
92  bodyColumns: number,
93  handlers: PaneHandlers,
94) => {
95  if (!snapshot) {
96    return (
97      <Box paddingX={PADDING_X} paddingBottom={PADDING_BOTTOM}>
98        <Text dimColor>{error ?? 'Reading…'}</Text>
99      </Box>
100    )
101  }
102  // The cells inside the pane's and each row's padding: what the rows and the charts lay out in.
103  const contentWidth = bodyColumns - (PADDING_X + ROW_PADDING_X) * 2
104  const { showPid, showTime, commandWidth } = paneColumns(contentWidth)
105  const views = viewRows(snapshot, state)
106  // The history's shape over the window, in the width the rows use.
107  const charts = sparkLines(points, contentWidth)
108  const numbers = (mem: string, cpu: string, time: string) =>
109    ` ${fit(mem, NUMBER_WIDTH, true)} ${fit(cpu, NUMBER_WIDTH, true)}${showTime ? ` ${fit(time, TIME_WIDTH, true)}` : ''}`
110  const pidCell = (pid: string) => (showPid ? `${fit(pid, PID_WIDTH)} ` : '')
111
112  // One row: a plain keyed Button of Text cells, striped by its Box; the selected row underlined.
113  const row = (
114    key: string,
115    target: RowTarget,
116    command: { main: string; parent: string },
117    figures: string,
118    pid: string,
119    isStriped: boolean,
120    isBold: boolean,
121  ) => {
122    const background = isStriped ? STRIPE_COLOR : undefined
123    const underline = isSelected(target, state.selected) || (target.pid === snapshot.pid && state.selected?.pid === snapshot.pid)
124    const cells =
125      command.parent === ''
126        ? [
127            <Text backgroundColor={background} bold={isBold} underline={underline}>{`${pidCell(pid)}${command.main}`}</Text>,
128            <Text backgroundColor={background} bold={isBold}>{figures}</Text>,
129          ]
130        : [
131            <Text backgroundColor={background} bold={isBold} underline={underline}>{`${pidCell(pid)}${command.main}`}</Text>,
132            <Text backgroundColor={background} dimColor>{command.parent}</Text>,
133            <Text backgroundColor={background} bold={isBold}>{figures}</Text>,
134          ]
135
136    return (
137      <Box paddingX={ROW_PADDING_X} backgroundColor={background}>
138        <Button key={key} plain onPress={() => handlers.onRow(target)}>
139          {cells}
140        </Button>
141      </Box>
142    )
143  }
144
145  const { engine } = snapshot
146  // Claude Code's row names the main conversation's model and effort, dim, once a request has told them; no separator, as it has no status.
147  const enginePartsText = modelParts(models[''])
148  const engineCell = tailedCell('Claude Code', '', enginePartsText === '' ? '' : `  ${enginePartsText}`, commandWidth)
149  const engineRow = row(
150    `pid:${snapshot.pid}`,
151    { pid: snapshot.pid, startMs: 0, hasChildren: false },
152    { main: engineCell.main, parent: engineCell.tail },
153    numbers(formatBytes(engine.rssKb), formatPercent(engine.cpuPercent), formatDuration(engine.uptimeSeconds)),
154    String(snapshot.pid),
155    false,
156    true,
157  )
158  // In the tree, the detached group follows a heading of its own.
159  const firstDetached = state.sort === 'tree' ? views.findIndex(view => view.row.detached) : -1
160  const detachedHeading = (
161    <Box key="detached-heading" paddingX={ROW_PADDING_X}>
162      <Text bold dimColor>{`${pidCell('')}Detached`}</Text>
163    </Box>
164  )
165  // Zebra rows count Claude Code's own as the first.
166  const childRows = views.flatMap((view, index) => [
167    ...(index === firstDetached ? [detachedHeading] : []),
168    row(
169      `pid:${view.row.pid}`,
170      { pid: view.row.pid, startMs: view.row.startMs, hasChildren: view.hasChildren && state.sort === 'tree' },
171      commandCell(view, commandWidth, originText(origins, view.row)),
172      numbers(formatBytes(view.rssKb), formatPercent(view.cpuPercent), formatDuration(view.row.uptimeSeconds)),
173      String(view.row.pid),
174      index % 2 === 0,
175      false,
176    ),
177  ])
178  const note = noteLine(snapshot)
179  // The Subagents section: one plain row each, in the table's columns, ended ones dim.
180  const agentList = agentRows(agents, snapshot, origins)
181  const agentPrefixes = treePrefixes(agentList)
182  const agentLines = agentList.map((agent, index) => {
183    const { main, tail } = agentCell(agent, agentPrefixes[index] ?? '', commandWidth, modelText(models[agent.id]))
184    const figures =
185      agent.processCount === 0 ? numbers('—', '—', '') : numbers(formatBytes(agent.rssKb), formatPercent(agent.cpuPercent), '')
186
187    return (
188      <Box key={`agent:${agent.id}`} flexDirection="row" paddingX={ROW_PADDING_X}>
189        <Text dimColor={agent.isEnded}>{`${pidCell('')}${main}`}</Text>
190        <Text dimColor>{tail}</Text>
191        <Text dimColor={agent.isEnded}>{figures}</Text>
192      </Box>
193    )
194  })
195  const totals = totalLines(snapshot)
196  const details = detailLines(snapshot, state.selected, origins)
197  const stop = state.stop
198  const canStop =
199    handlers.onStop !== undefined &&
200    state.selected !== null &&
201    state.selected.pid !== snapshot.pid &&
202    views.some(view => isSelected(view.row, state.selected))
203
204  return (
205    <Box flexDirection="column" paddingX={PADDING_X} paddingBottom={PADDING_BOTTOM}>
206      {charts !== null && (
207        <Box flexDirection="column" paddingX={ROW_PADDING_X}>
208          <Text>{charts[0]}</Text>
209          <Text>{charts[1]}</Text>
210        </Box>
211      )}
212      <Box marginBottom={1} paddingX={ROW_PADDING_X}>
213        <Text dimColor>
214          peak {formatBytes(engine.peakKb)} · {snapshot.platform}
215          {snapshot.platform === 'mac' ? ' (peak is the highest seen)' : ''}
216        </Text>
217      </Box>
218      <Box paddingX={ROW_PADDING_X} backgroundColor={HEADER_COLOR}>
219        <Text color={HEADER_TEXT} bold>
220          {`${pidCell('PID')}${fit(state.sort === 'tree' ? 'COMMAND' : `COMMAND (by ${state.sort})`, commandWidth)}${numbers('MEM', 'CPU', 'TIME')}`}
221        </Text>
222      </Box>
223      {engineRow}
224      {childRows}
225      {note !== null && (
226        <Box paddingX={ROW_PADDING_X}>
227          <Text dimColor>{`${pidCell('')}${note}`}</Text>
228        </Box>
229      )}
230      {snapshot.detachedOff !== undefined && (
231        <Box paddingX={ROW_PADDING_X}>
232          <Text dimColor>{`${pidCell('')}${snapshot.detachedOff}`}</Text>
233        </Box>
234      )}
235      {agentLines.length > 0 && (
236        <Box flexDirection="column" marginTop={1}>
237          <Box key="agents-heading" paddingX={ROW_PADDING_X}>
238            <Text bold dimColor>{`${pidCell('')}Subagents`}</Text>
239          </Box>
240          {agentLines}
241        </Box>
242      )}
243      {totals.length > 0 && (
244        <Box flexDirection="column" marginTop={1} paddingX={ROW_PADDING_X}>
245          {totals.map(total => (
246            <Text bold>{`${pidCell('')}${fit(total.label, commandWidth)}${numbers(total.mem, total.cpu, '')}`}</Text>
247          ))}
248        </Box>
249      )}
250      {details !== null && (
251        <Box flexDirection="column" marginTop={1} paddingX={ROW_PADDING_X}>
252          {details.map((line, index) => (
253            <Text dimColor={index > 0}>{line}</Text>
254          ))}
255        </Box>
256      )}
257      {stop?.phase === 'confirm' && (
258        <Box marginTop={1} paddingX={ROW_PADDING_X}>
259          <Text>{confirmText(stop)}</Text>
260        </Box>
261      )}
262      <Box flexDirection="row" columnGap={2} marginTop={stop?.phase === 'confirm' ? 0 : 1} paddingX={ROW_PADDING_X}>
263        {stop === null && (
264          <Button key="sort" plain hotkey="s" onPress={handlers.onSort}>
265            {`Sort: ${state.sort}`}
266          </Button>
267        )}
268        {stop === null && canStop && handlers.onStop && (
269          <Button key="stop" plain hotkey="k" onPress={handlers.onStop}>
270            Stop process
271          </Button>
272        )}
273        {stop?.phase === 'confirm' && handlers.onConfirm && (
274          <Button key="confirm" plain hotkey="y" onPress={handlers.onConfirm}>
275            Stop
276          </Button>
277        )}
278        {(stop?.phase === 'sent' || stop?.phase === 'forced') && <Text dimColor>Stopping…</Text>}
279        {stop?.phase === 'stuck' && <Text>Still running.</Text>}
280        {stop?.phase === 'stuck' && handlers.onForce && (
281          <Button key="force" plain hotkey="f" onPress={handlers.onForce}>
282            Force stop
283          </Button>
284        )}
285        {stop && handlers.onCancel && (
286          <Button key="cancel" plain hotkey="n" onPress={handlers.onCancel}>
287            {stop.phase === 'confirm' ? 'Cancel' : 'Dismiss'}
288          </Button>
289        )}
290      </Box>
291    </Box>
292  )
293}
294
hooks/snapshot.ts 123 lines
1// Two readings into what both views draw: per-process CPU, the tree, the totals.
2
3import type { ProcRow, Snapshot } from '../types'
4import type { Platform, Proc, Sample } from './stats'
5
6// A build can start hundreds of workers; the pane needs no more than this.
7export const MAX_ROWS = 500
8
9// The engine, the processes under it (undefined when the table cannot be read), and the detached
10// processes this session started (left out where they are not tracked).
11export type Timed = { engine: Sample; children?: Proc[]; detached?: Proc[]; wallMs: number }
12
13// CPU a process spent since the last reading, and as a share of one core. A pid
14// whose process is younger than the one seen before was reused: a new process.
15// One first seen (new, reused, or found late by a slow scan) shows its average over its
16// life; only the share of its CPU that falls in this reading's window counts as delta.
17export const procCpu = (now: Proc, was: Proc | undefined, elapsed: number) => {
18  const isSame = was !== undefined && now.uptimeSeconds >= was.uptimeSeconds - 1
19  if (isSame) {
20    const delta = Math.max(0, now.cpuSeconds - was.cpuSeconds)
21
22    return { delta, percent: (delta / elapsed) * 100 }
23  }
24  const window = Math.max(1, now.uptimeSeconds)
25
26  return { delta: now.cpuSeconds * Math.min(1, elapsed / window), percent: (now.cpuSeconds / window) * 100 }
27}
28
29// Depth-first from the engine, each level by pid.
30export const treeOrder = (procs: Proc[], root: number) => {
31  const byParent = new Map<number, Proc[]>()
32  for (const proc of procs) byParent.set(proc.ppid, [...(byParent.get(proc.ppid) ?? []), proc])
33  for (const list of byParent.values()) list.sort((a, b) => a.pid - b.pid)
34  const ordered: { proc: Proc; depth: number }[] = []
35  const seen = new Set<number>()
36  const visit = (pid: number, depth: number) => {
37    for (const proc of byParent.get(pid) ?? []) {
38      if (seen.has(proc.pid)) continue
39      seen.add(proc.pid)
40      ordered.push({ proc, depth })
41      visit(proc.pid, depth + 1)
42    }
43  }
44  visit(root, 0)
45  // A process whose parent ended between reads is kept, at the top level.
46  for (const proc of procs) if (!seen.has(proc.pid)) ordered.push({ proc, depth: 0 })
47
48  return ordered
49}
50
51// A parent no process has, for forestOrder's roots.
52const FOREST_ROOT = -1
53
54// Processes as a forest: each whose parent is not among them is a root, roots by pid.
55export const forestOrder = (procs: Proc[]) => {
56  const pids = new Set(procs.map(proc => proc.pid))
57  const byPid = new Map(procs.map(proc => [proc.pid, proc]))
58  const rooted = procs.map(proc => (pids.has(proc.ppid) ? proc : { ...proc, ppid: FOREST_ROOT }))
59
60  return treeOrder(rooted, FOREST_ROOT).map(({ proc, depth }) => ({ proc: byPid.get(proc.pid)!, depth }))
61}
62
63export const buildSnapshot = (
64  platform: Platform,
65  pid: number,
66  now: Timed,
67  before: Timed | undefined,
68): Snapshot => {
69  const elapsed = before ? (now.wallMs - before.wallMs) / 1000 : 0
70  const isMeasured = before !== undefined && elapsed > 0
71  const was = new Map([...(before?.children ?? []), ...(before?.detached ?? [])].map(proc => [proc.pid, proc]))
72  const canCompare = isMeasured && before?.children !== undefined && now.children !== undefined
73  let childDelta = 0
74  let detachedDelta = 0
75  const toRow = ({ proc, depth }: { proc: Proc; depth: number }, isDetached: boolean): ProcRow => {
76    const cpu = canCompare ? procCpu(proc, was.get(proc.pid), elapsed) : undefined
77    childDelta += cpu?.delta ?? 0
78    if (isDetached) detachedDelta += cpu?.delta ?? 0
79
80    return {
81      pid: proc.pid,
82      ppid: proc.ppid,
83      depth,
84      command: proc.command,
85      rssKb: proc.rssKb,
86      cpuPercent: cpu ? cpu.percent : null,
87      uptimeSeconds: proc.uptimeSeconds,
88      startMs: Math.round(now.wallMs - proc.uptimeSeconds * 1000),
89      ...(isDetached ? { detached: true as const } : {}),
90    }
91  }
92  // The tree under Claude Code, then the detached processes; the detached ones only with the tree.
93  const detachedRows = now.children ? forestOrder(now.detached ?? []).map(each => toRow(each, true)) : []
94  const rows = now.children ? [...treeOrder(now.children, pid).map(each => toRow(each, false)), ...detachedRows] : null
95
96  return {
97    platform,
98    pid,
99    engine: {
100      rssKb: now.engine.rssKb,
101      peakKb: now.engine.peakKb,
102      cpuPercent:
103        isMeasured && before
104          ? (Math.max(0, now.engine.cpuSeconds - before.engine.cpuSeconds) / elapsed) * 100
105          : null,
106      uptimeSeconds: now.engine.uptimeSeconds,
107    },
108    children: rows,
109    childCount: rows?.length ?? 0,
110    childKb: rows?.reduce((sum, row) => sum + row.rssKb, 0) ?? 0,
111    childCpuPercent: canCompare ? (childDelta / elapsed) * 100 : null,
112    detachedCount: detachedRows.length,
113    detachedKb: detachedRows.reduce((sum, row) => sum + row.rssKb, 0),
114    detachedCpuPercent: canCompare ? (detachedDelta / elapsed) * 100 : null,
115  }
116}
117
118// What the pane is handed: the totals over every process, the rows capped.
119export const capRows = (snapshot: Snapshot): Snapshot => ({
120  ...snapshot,
121  children: snapshot.children?.slice(0, MAX_ROWS) ?? null,
122})
123
hooks/report.ts 117 lines
1// The `/proc-stats report` text: what the person and the model read about the session, from current state.
2
3import type { AlertState, Origins, Point, ProcRow, Reading } from '../types'
4import { worse } from './alerts'
5import { formatBytes, formatDuration, formatPercent } from './format'
6import { originLabel, originOf } from './origin'
7import { labelOf, subtotals } from './view'
8
9// How many processes the report names, heaviest (most memory) first.
10export const HEAVIEST = 5
11// How many detached processes the report lists, heaviest first.
12export const DETACHED_LISTED = 10
13// A command is cut to this many code points.
14const COMMAND_MAX = 80
15
16export type ReportInput = {
17  reading: Reading
18  points: Point[]
19  alerts: AlertState
20  origins: Origins
21  // ms since the epoch
22  now: number
23  historyMinutes: number
24}
25
26const PLATFORMS: Record<string, string> = { linux: 'Linux', mac: 'macOS', windows: 'Windows' }
27
28const cut = (text: string) => {
29  const chars = Array.from(text)
30
31  return chars.length > COMMAND_MAX ? `${chars.slice(0, COMMAND_MAX - 1).join('')}…` : text
32}
33
34const ago = (now: number, t: number) => `${formatDuration((now - t) / 1000)} ago`
35
36const sum = (a: number | null, b: number | null) => (a === null || b === null ? null : a + b)
37
38// The first point holding the highest value: when the peak was reached.
39const peakOf = (points: Point[], pick: (point: Point) => number) =>
40  points.reduce<Point | null>((best, point) => (best === null || pick(point) > pick(best) ? point : best), null)
41
42// Most memory first, then most CPU, then the lower pid.
43const byWeight = (rows: ProcRow[]) =>
44  [...rows].sort((a, b) => b.rssKb - a.rssKb || (b.cpuPercent ?? 0) - (a.cpuPercent ?? 0) || a.pid - b.pid)
45
46// One listed process: its figures, command and origin, and (where asked) whether it is detached. Not
47// numbered: Claude Code shows the report as Markdown, where a numbered line starts a list that runs on.
48const processLine = (row: ProcRow, origins: Origins, isDetachedShown: boolean) => {
49  const origin = originOf(origins, row)
50  const from = origin ? ` · ${originLabel(origin)}` : ''
51  const detached = isDetachedShown && row.detached ? ' · detached' : ''
52
53  return `  ${formatBytes(row.rssKb)} · ${formatPercent(row.cpuPercent)} CPU · pid ${row.pid} · ${cut(labelOf(row.command))}${from}${detached}`
54}
55
56// A subtotal in words: `2 child processes 20MB, 1.0% CPU`.
57const subtotalText = (count: number, noun: string, kb: number, cpuPercent: number | null) =>
58  `${count} ${noun} ${formatBytes(kb)}, ${formatPercent(cpuPercent)} CPU`
59
60export const reportText = ({ reading, points, alerts, origins, now, historyMinutes }: ReportInput) => {
61  const snapshot = reading.snapshot
62  if (!snapshot) return `report: ${reading.error ?? 'no reading yet'}`
63  const { engine, children, childCount, childKb, childCpuPercent } = snapshot
64  const lines = [
65    `report · ${PLATFORMS[snapshot.platform] ?? snapshot.platform} · Claude Code pid ${snapshot.pid} · up ${formatDuration(engine.uptimeSeconds)}`,
66  ]
67
68  const own = `Claude Code ${formatBytes(engine.rssKb)}, ${formatPercent(engine.cpuPercent)} CPU`
69  const { under, detached } = subtotals(snapshot)
70  if (children === null) lines.push(`Now: ${own} · child processes unknown (the process table could not be read)`)
71  else if (childCount === 0) lines.push(`Now: ${own} · no child processes`)
72  else {
73    const parts = [
74      under.count === 0
75        ? 'no child processes'
76        : subtotalText(under.count, under.count === 1 ? 'child process' : 'child processes', under.kb, under.cpuPercent),
77      ...(detached.count > 0 ? [subtotalText(detached.count, 'detached', detached.kb, detached.cpuPercent)] : []),
78      `total ${formatBytes(engine.rssKb + childKb)}, ${formatPercent(sum(engine.cpuPercent, childCpuPercent))} CPU`,
79    ]
80    lines.push(`Now: ${own} · ${parts.join(' · ')}`)
81  }
82  if (snapshot.detachedOff !== undefined) lines.push(snapshot.detachedOff)
83
84  const memPeak = peakOf(points, point => point.memKb)
85  const cpuPeak = peakOf(points, point => point.cpuPct)
86  lines.push(
87    memPeak && cpuPeak
88      ? `Peaks in the last ${historyMinutes} min: memory ${formatBytes(memPeak.memKb)} ${ago(now, memPeak.t)} · CPU ${formatPercent(cpuPeak.cpuPct)} ${ago(now, cpuPeak.t)}`
89      : `Peaks in the last ${historyMinutes} min: no history yet`,
90  )
91
92  if (children && children.length > 0) {
93    lines.push('Heaviest processes:')
94    byWeight(children).slice(0, HEAVIEST).forEach(row => lines.push(processLine(row, origins, true)))
95    const detachedRows = children.filter(row => row.detached)
96    if (detachedRows.length > 0) {
97      lines.push(
98        detached.count > DETACHED_LISTED ? `Detached processes (${DETACHED_LISTED} of ${detached.count}):` : 'Detached processes:',
99      )
100      byWeight(detachedRows).slice(0, DETACHED_LISTED).forEach(row => lines.push(processLine(row, origins, false)))
101    }
102  }
103
104  const { mem, cpu } = alerts.levels
105  const level = worse(mem, cpu)
106  lines.push(level === 'none' ? 'Marker: none' : `Marker: ${level === 'alert' ? '🔴' : '🟡'} ${level} (memory ${mem}, CPU ${cpu})`)
107
108  const recent = alerts.recent ?? []
109  if (recent.length === 0) lines.push('Recent alerts: none')
110  else {
111    lines.push('Recent alerts:')
112    for (const toast of [...recent].reverse()) lines.push(`  ${ago(now, toast.t)} · ${toast.text}`)
113  }
114
115  return lines.join('\n')
116}
117
hooks/settings.ts 68 lines
1// The person's settings (plugin.json userConfig), read once per load. A value
2// that is missing, of the wrong type or out of range is its default.
3
4import type { PluginOptions } from 'claude-code'
5
6import type { Platform } from './stats'
7
8export type Settings = {
9  intervalMs: Record<Platform, number>
10  warnMemMb: number
11  alertMemMb: number
12  warnCpuPct: number
13  alertCpuPct: number
14  toastCpuPct: number
15  toastCpuSeconds: number
16  toastMemMb: number
17  historyMinutes: number
18  statusShowChildren: boolean
19}
20
21export const DEFAULTS: Settings = {
22  intervalMs: { linux: 1000, mac: 2000, windows: 5000 },
23  warnMemMb: 2048,
24  alertMemMb: 4096,
25  warnCpuPct: 150,
26  alertCpuPct: 300,
27  toastCpuPct: 90,
28  toastCpuSeconds: 60,
29  toastMemMb: 1024,
30  historyMinutes: 10,
31  statusShowChildren: true,
32}
33
34const number = (value: unknown, fallback: number, min: number, max: number) =>
35  typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max ? value : fallback
36
37// A warn limit above its alert limit could never show: it is lowered to the alert limit.
38const pair = (warn: number, alert: number): [number, number] => [Math.min(warn, alert), alert]
39
40export const readSettings = (options: PluginOptions): Settings => {
41  const [warnMemMb, alertMemMb] = pair(
42    number(options.warnMemMb, DEFAULTS.warnMemMb, 1, 1_000_000),
43    number(options.alertMemMb, DEFAULTS.alertMemMb, 1, 1_000_000),
44  )
45  const [warnCpuPct, alertCpuPct] = pair(
46    number(options.warnCpuPct, DEFAULTS.warnCpuPct, 1, 100_000),
47    number(options.alertCpuPct, DEFAULTS.alertCpuPct, 1, 100_000),
48  )
49
50  return {
51    intervalMs: {
52      linux: number(options.intervalLinuxMs, DEFAULTS.intervalMs.linux, 250, 60_000),
53      mac: number(options.intervalMacMs, DEFAULTS.intervalMs.mac, 250, 60_000),
54      windows: number(options.intervalWindowsMs, DEFAULTS.intervalMs.windows, 1000, 60_000),
55    },
56    warnMemMb,
57    alertMemMb,
58    warnCpuPct,
59    alertCpuPct,
60    toastCpuPct: number(options.toastCpuPct, DEFAULTS.toastCpuPct, 1, 100_000),
61    toastCpuSeconds: number(options.toastCpuSeconds, DEFAULTS.toastCpuSeconds, 1, 86_400),
62    toastMemMb: number(options.toastMemMb, DEFAULTS.toastMemMb, 1, 1_000_000),
63    historyMinutes: number(options.historyMinutes, DEFAULTS.historyMinutes, 1, 120),
64    statusShowChildren:
65      typeof options.statusShowChildren === 'boolean' ? options.statusShowChildren : DEFAULTS.statusShowChildren,
66  }
67}
68
hooks/status.ts 23 lines
1// The status line under the prompt.
2
3import type { Snapshot } from '../types'
4import { formatBytes, formatDuration, formatPair, formatPercent } from './format'
5
6// The share of the processes the session started (under Claude Code or detached) shows only while there
7// are any; `?` when the table could not be read.
8export const statusLine = (snapshot: Snapshot, showChildren = true) => {
9  const { engine, children, childCpuPercent } = snapshot
10  // Without them, or with none running, Claude Code's own figures alone.
11  const hasChildren = showChildren && (children === null || snapshot.childCount > 0)
12  let cpu = '…'
13  if (engine.cpuPercent !== null) {
14    const own = engine.cpuPercent.toFixed(1)
15    cpu = hasChildren
16      ? `(${own} + ${childCpuPercent === null ? '?' : childCpuPercent.toFixed(1)})%`
17      : formatPercent(engine.cpuPercent)
18  }
19  const childKb = children === null ? undefined : snapshot.childKb
20
21  return `mem ${formatPair(engine.rssKb, hasChildren ? childKb : 0)} · peak ${formatBytes(engine.peakKb)} · cpu ${cpu} · up ${formatDuration(engine.uptimeSeconds)}`
22}
23