SLOPSHOPPER

overview

A session overview pane: context, cost, time, turns, tools, files, subagents, limits and git; cells in the terminal, charts in the desktop app

paneguardcommandtimeragents
v0.7.6MITupdated 2026-10-17satoramoto/awesome-claude/mods/overview
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · overview
› fix the failing auth test and add an audit log call ⏺ 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 › /overview ⎿ overview: Overview pane opened. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

awesome-claude

Mods for Claude Code. A mod is a Claude Code plugin that adds interface to Claude Code itself (a pane, a slash command) through the engine's hooks API. This repository holds our own mods, forks of others' (each kept under its own license, with a link back), and is a plugin marketplace that installs them.

The panes draw in the desktop app (as a side pane, with charts) and in the terminal (a simpler pane of text cells). Tested on Claude Code 2.1.296, the version CI pins.

The mods

ModWhat it showsOpens withNeeds
overviewthe current session at a glance: context, limits, activity, agents, the branches it started and their pull requests, coston its own when a session starts; /overview opens it againgit for Workspaces; gh signed in for pull requests
issuesthe open GitHub issues of the session's repository, newest change first, with actions on eachon its own when a session starts; /issues opens it againa GitHub repository; gh signed in
launcherthe project's dev servers from .claude/launch.json (the desktop app's preview list), each with its state, URL, Start, Stop and Restart, and its outputon its own when a session starts; /launcher (or /preview) opens it again; /launcher start <name>, /launcher stop <name>a .claude/launch.json; lsof to tell which ports answer
labfor mod authors: 77 experiments probing what the engine draws (SVG gradients and filters, animation, hover, Client modules, every element), with the engine's verdict on each surface in mods/lab/verdicts.jsonthe index on its own when a session starts; /lab, /lab <id>, /lab gallerynothing

Forked mods

Copies of other people's mods, changed here to fit these. Each keeps its original license and author; its README opens with where it came from, the upstream commit it was taken at, and what this fork changed.

ModWhat it doesOriginalLicense
filetreean IDE-style file tree of the session's folder: git status and lines changed per file, and a shimmer on what Claude reads, writes and commits. /filetree opens itdata-goblin/claude-code-filetree, by Kurt BuhlerMIT
blast-radiusholds a risky shell command (rm -rf, git reset --hard, git clean, force push, migrations) and shows what it would change, with Proceed and Cancelanthropics/claude-code-playground, by AnthropicApache-2.0

Requirements

  • Claude Code: tested on 2.1.296.
  • git, for overview's Workspaces section.
  • The GitHub CLI, signed in (gh auth login), for issues and for the pull requests in overview's Workspaces. Without it overview still draws everything else, and its Workspaces section shows a note in place of pull requests (gh not installed, or gh not authenticated (run gh auth login)); issues shows the same note in place of the list.
  • Bun, only to build from source (bun install, then bun build.ts). Installing from the marketplace needs nothing else.

What the panes do

/overview

Opens by itself when a session starts; /overview brings it back after you close it. Its sections, each folding open and shut:

  • Context: how full the context window is, by kind, and the room left before compaction.
  • Limits: your plan's usage limits and when they reset.
  • Activity: tool calls per turn, sliced by tool, with failures.
  • Agents: the session's subagents, each with its status, tokens and time.
  • Workspaces: the branches the session started, each with its pull request's state, checks and lines changed. Pull requests are read with gh every 30 seconds while any is open.
  • Accounting: the session's cost and model.

A footer shows the session's share of the machine's cpu, memory and network.

/issues

Opens by itself when a session starts; /issues brings it back. Lists the open issues of the session's repository (read with gh issue list).

  • Quick add creates an issue from a title alone, with an empty body (gh issue create).
  • Refine, Start and Sprint send a prompt to the session, as if you'd typed it, and the session does the work with gh:
  • Refine: the session reads the issue, asks you about what's unclear, rewrites its body and labels it refined.
  • Start: one subagent takes the issue in its own worktree and branch off the default branch, and reports back when it's pushed. An issue not yet labelled refined asks first whether to refine it.
  • Sprint (select several issues): one subagent per issue in parallel, each in its own worktree, integrated on one sprint/<date> branch, then one PR for your approval with auto-merge off.

These prompts encode an opinionated way of working (worktrees, a subagent per issue, an integration branch reviewed by you). Read mods/issues/hooks/register.tsx for their exact wording before you rely on them.

/launcher

The desktop app's preview launcher, in a pane that works in the terminal too. Opens by itself when a session starts; /launcher brings it back. It lists every configuration in the project's .claude/launch.json (the session's folder, or the nearest one above it up to the git root), one row each: its name, its state, its URL once the port answers, and Start, Stop and Restart.

  • States: stopped (grey); starting (blue: started here, its port not answering yet); running (green, with http://localhost:<port>); running elsewhere (green: something this session didn't start answers on the port, such as the desktop app or another session; it can't be started twice); failed (red: it exited with an error, and its row unfolds to show why).
  • Start runs runtimeExecutable runtimeArgs… in the configuration's cwd (the project root by default) with PORT set to its port and its env over that. With autoPort, a taken port moves it to the next free one.
  • Unfold a row for its command, its exit code, and the tail of its output (the last 200 lines are kept, colours stripped).
  • From the prompt: /launcher start <name>, /launcher stop <name>, /launcher restart <name>, /launcher list. Each answers in text, so they work without the pane. /preview does the same.
  • Which ports answer comes from lsof (an HTTP request to each port where lsof isn't installed), every 2 s while the pane is shown, and not at all while it isn't.
  • Stop frees the port: checked with npm run serve starting a node server, ending the spawn loop ends the grandchild node too, so its port was free at once.

The servers it starts are children of the mod: they end when the session ends, and when the mod reloads (/reload-plugins, or a rebuild with hot reloading on). Servers started elsewhere aren't touched; Stop is only for the ones this session started.

Install

From the marketplace

At the prompt of a Claude Code session in a terminal:

/plugin marketplace add satoramoto/awesome-claude
/plugin install overview@awesome-claude
/plugin install issues@awesome-claude

Pick a scope when asked (user scope loads the mod in every session). Each mod is active straight away. Or from a shell: claude plugin marketplace add satoramoto/awesome-claude, then claude plugin install overview@awesome-claude.

Run these from a terminal session; a mod installed at user scope then loads in the desktop app too.

Getting updates

An installed mod updates only when its version changes; every release of a mod raises it. To fetch the newest versions by hand, at the prompt:

/plugin marketplace update awesome-claude
/plugin update overview@awesome-claude

or from a shell: claude plugin marketplace update awesome-claude, then claude plugin update overview@awesome-claude (and the same for each mod you installed). The new version loads after a restart or /reload-plugins.

Auto-update is off by default for marketplaces other than Anthropic's. Turn it on in /plugin → Marketplaces → awesome-claude → Enable auto-update, or with "autoUpdate": true next to source in extraKnownMarketplaces in ~/.claude/settings.json:

"extraKnownMarketplaces": {
  "awesome-claude": {
    "source": { "source": "github", "repo": "satoramoto/awesome-claude" },
    "autoUpdate": true
  }
}

Loading from a clone (--plugin-dir or CLAUDE_CODE_PLUGIN_DIRS, below) gets no marketplace updates: git pull the clone instead. To pull at every session start, a SessionStart hook in ~/.claude/settings.json:

"hooks": {
  "SessionStart": [
    { "hooks": [{ "type": "command", "command": "git -C ~/Code/satoramoto/awesome-claude pull -q --ff-only" }] }
  ]
}

Try it from a clone, for one session

The compiled mods are committed, so a clone runs as is. A folder of plugins passed to --plugin-dir loads each one in it:

git clone https://github.com/satoramoto/awesome-claude ~/Code/satoramoto/awesome-claude
claude --plugin-dir ~/Code/satoramoto/awesome-claude/plugins

From source, while changing the mods

git clone https://github.com/satoramoto/awesome-claude ~/Code/satoramoto/awesome-claude
cd ~/Code/satoramoto/awesome-claude
bun install
bun build.ts

Then point every session at the compiled folder, in ~/.claude/settings.json, with the full path to your clone's plugins folder:

"env": {
  "CLAUDE_CODE_PLUGIN_DIRS": "/Users/you/Code/satoramoto/awesome-claude/plugins",
  "CLAUDE_CODE_PLUGIN_DIR_WATCH": "1"
}

With bun run watch running, a save under mods/ (or in zen's kit, with ZEN set) recompiles and the session reloads the mod. These two variables are what this setup uses on Claude Code 2.1.296; they may change in later versions. Don't also install the mods from the marketplace, or each loads twice.

Making a mod

AGENTS.md lists the commands and checks. The project's skills, which Claude Code loads when working in this repository, hold the how-to:

FolderWhat it is
mods/<name>/a mod's source: .claude-plugin/plugin.json, hooks/, types/. Imports the kit as @kit/…
zen's src/harness/claude-code/kit/the kit, from the pinned @satoramoto/zen dev dependency: components (ui.tsx), colors and glyphs (tokens.ts), number formatting (format.ts), icons (icons.ts), timing a mod's own work (perf.ts), skins (skin.ts, skins.ts)
zen.tswhere zen's kit and bench are: node_modules/@satoramoto/zen, or the zen checkout ZEN names
plugins/<name>/the compiled mods: what Claude Code loads and the marketplace installs. Generated by bun build.ts; don't edit
.claude-plugin/marketplace.jsonthe marketplace: each mod in plugins/, at its plugin.json version
playground/a browser page that draws every mod live with sample data, on each surface, through zen's bench; playground/fixtures/ holds the sample data
stories/Storybook stories: each mod's scenarios, the lab and the engine experiments

Each mod is versioned on its own in its plugin.json. A new mod also gets an entry in .claude-plugin/marketplace.json; CI fails if a mod is missing there or its version differs from its plugin.json. Any change to a mod's compiled output in plugins/<mod>/ (a new zen pin that changes the kit included) raises its version, in plugin.json and the marketplace, since installs only update when it changes; CI fails a pull request that changes a mod's output without raising its version.

The playground

bun run playground

At http://localhost:5173 (set PORT for another). Every mod's ui.render hooks, drawn with the scenarios in playground/fixtures/<mod>.ts, side by side in desktop light, desktop dark and terminal, at any pane width. On each save it also compiles and runs claude plugin validate plugins/<mod>, and shows the result in the bar.

Storybook

bun run storybook

At http://localhost:6006 (set PORT for another). Each mod scenario (stories/<mod>.stories.ts, from the playground's fixtures), drawn by zen's bench. The toolbar picks the surface (desktop or terminal), the theme, the frame and the pane width. The kit's own components and the skins have their stories in zen's Storybook, under Harness/Claude Code. Storybook is for how things look; the playground is for wiring up a whole mod with the engine's checks running.

Why a compiler

The engine reads a mod's source as it is and refuses any import from outside the mod's folder (symlinks included). build.ts copies zen's kit into each compiled mod and rewrites @kit/… to relative paths; nothing else changes, so the output is still readable source and passes claude plugin validate.

Drawing for the desktop

What the desktop accepts, found by probing the engine's validator (first on 2.1.293; the mods are tested on 2.1.296): whole percentages only (25.5% is refused); flexGrow up to 10000; fractional heights and margins; no Box hover. Borders: round draws rounded corners, and single, double, bold and classic draw; dashed doesn't. SVG is drawn as an image the page scales, so it blurs as the pane resizes: draw with boxes and text.

What it paints (measured on the real pane, 2.1.295): a horizontal unit is a column (~7.8px), height a row (~19px), but vertical margin, padding and row gap half a row (~9.5px); a transparent border colour draws in the text's colour; a Button draws its label alone, never its children. zen's docs/harness-claude-code.md ("What the engine and the desktop accept") has the details, and Storybook draws by the same rules.

License

MIT, except the forked mods, which keep their own licenses: mods/filetree is MIT, copyright Kurt Buhler (LICENSE), and mods/blast-radius is Apache-2.0, copyright Anthropic PBC (LICENSE).

Source 6 files
hooks/register.tsx 1074 lines
1import { atom, read, update } from 'claude-code'
2import type {
3  AgentInfo,
4  EngineInterface,
5  ModelUsage,
6  ProcessRunResult,
7  Register,
8  SessionContextBreakdown,
9  SessionRateLimit,
10  Timer,
11} from 'claude-code'
12
13import type {
14  Activity,
15  Agent,
16  AgentExtra,
17  BranchView,
18  Doing,
19  DoingKind,
20  GhInfo,
21  GitFile,
22  GitInfo,
23  GitNote,
24  GitPr,
25  Item,
26  Limit,
27  Segment,
28  Snapshot,
29  Tracked,
30  TreeRow,
31  TurnPoint,
32  WorkspacesGh,
33} from '../types'
34import { parseLeftRight, startedBy } from './branches'
35import { short } from '@kit/format'
36import { createPerf } from '@kit/perf'
37import { holdButtons } from '@kit/ui'
38
39import { renderDesktop } from './desktop'
40import type { AppElements, DesktopData, Helpers } from './desktop'
41import { renderTerminal } from './terminal'
42import type { TermElements, TermHelpers } from './terminal'
43import { NETTOP, NET_PER_PROCESS, resourcesSh, takeNettop, toResources } from './resources'
44
45const PANE = 'overview'
46const snapshot = atom({ plugin: 'overview', key: 'snapshot' } as const, null)
47const agents = atom({ plugin: 'overview', key: 'agents' } as const, [])
48const agentExtra = atom({ plugin: 'overview', key: 'agentExtra' } as const, {})
49const now = atom({ plugin: 'overview', key: 'now' } as const, 0)
50const resources = atom({ plugin: 'overview', key: 'resources' } as const, null)
51const TICK_MS = 1_000
52
53// One hue per used category, in the order /context lists them.
54export const PALETTE = ['#7aa2f7', '#bb9af7', '#7dcfff', '#9ece6a', '#e0af68', '#f7768e', '#ff9e64', '#2ac3de']
55const DETAIL_ITEMS = 5
56
57export const formatTokens = (n: number): string => {
58  if (n >= 999_500) return `${trim(n / 1_000_000)}M`
59  if (n >= 1_000) return `${trim(n / 1_000)}k`
60  return String(Math.round(n))
61}
62
63const trim = (n: number) => (n >= 100 ? String(Math.round(n)) : n.toFixed(1).replace(/\.0$/, ''))
64
65const basename = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path
66
67const top = (items: Item[]) => [...items].sort((a, b) => b.tokens - a.tokens).slice(0, DETAIL_ITEMS)
68
69/** The breakdown as the band keeps it: used rows first, then free space, then the compaction buffer. */
70export const toSnapshot = (b: SessionContextBreakdown): Snapshot => {
71  const rows = b.categories.filter(c => c.kind !== 'deferred')
72  const order = { used: 0, free: 1, buffer: 2, deferred: 3 }
73  const segments: Segment[] = rows
74    .map(c => ({ name: c.name, tokens: c.tokens, kind: c.kind }))
75    .sort((x, y) => order[x.kind] - order[y.kind])
76
77  const servers = new Map<string, number>()
78  for (const tool of b.mcpTools) {
79    if (tool.isLoaded) servers.set(tool.serverName, (servers.get(tool.serverName) ?? 0) + tool.tokens)
80  }
81
82  return {
83    model: b.model,
84    total: b.totalTokens,
85    max: b.rawMaxTokens,
86    percent: b.percentage,
87    ...(b.isAutoCompactEnabled && b.autoCompactThreshold ? { compactAt: b.autoCompactThreshold } : {}),
88    segments,
89    memory: top(b.memoryFiles.map(f => ({ label: `${basename(f.path)} (${f.type})`, tokens: f.tokens }))),
90    mcp: top([...servers].map(([label, tokens]) => ({ label, tokens }))),
91    skills: top((b.skills?.skillFrontmatter ?? []).map(s => ({ label: s.name, tokens: s.tokens }))),
92    agents: top(b.agents.map(a => ({ label: a.agentType, tokens: a.tokens }))),
93  }
94}
95
96export const colorOf = (segments: Segment[], i: number): string | undefined => {
97  const s = segments[i]
98  if (!s || s.kind !== 'used') return undefined
99  const used = segments.slice(0, i).filter(x => x.kind === 'used').length
100  return PALETTE[used % PALETTE.length]
101}
102
103/** `$.agent.list()`'s row as plain data, the fields the Agents tree draws. */
104export const toAgent = (info: AgentInfo): Agent => {
105  const agent: Agent = { id: info.id, description: info.description, type: info.type, status: info.status }
106  if (info.parentId) agent.parentId = info.parentId
107  return agent
108}
109
110const isActive = (status: string) => status === 'running' || status === 'pending' || status === 'idle'
111
112/**
113 * Every agent once, depth first, each under the agent that spawned it, in spawn order,
114 * with the connectors each row draws. A `folded` id keeps its row and hides its descendants.
115 */
116export const buildTree = (list: Agent[], folded: ReadonlySet<string> = new Set()): TreeRow[] => {
117  const ids = new Set(list.map(a => a.id))
118  const children = new Map<string, Agent[]>()
119  const roots: Agent[] = []
120  for (const agent of list) {
121    // A parent the list doesn't name puts the agent at the top rather than hiding it.
122    if (agent.parentId && agent.parentId !== agent.id && ids.has(agent.parentId)) {
123      children.set(agent.parentId, [...(children.get(agent.parentId) ?? []), agent])
124    } else {
125      roots.push(agent)
126    }
127  }
128  // Claim each agent once (it has one parent), so a parent cycle can't loop.
129  const kids = new Map<string, Agent[]>()
130  const claimed = new Set<string>()
131  const claim = (agent: Agent) => {
132    claimed.add(agent.id)
133    const mine = (children.get(agent.id) ?? []).filter(c => !claimed.has(c.id))
134    kids.set(agent.id, mine)
135    for (const c of mine) claim(c)
136  }
137  const tops: Agent[] = []
138  // Roots first; then a parent cycle, which has no root, still shows every agent.
139  for (const agent of [...roots, ...list]) {
140    if (claimed.has(agent.id)) continue
141    tops.push(agent)
142    claim(agent)
143  }
144
145  const counts = new Map<string, { descendants: number; running: number }>()
146  const count = (agent: Agent): { descendants: number; running: number } => {
147    let descendants = 0
148    let running = 0
149    for (const c of kids.get(agent.id) ?? []) {
150      const sub = count(c)
151      descendants += 1 + sub.descendants
152      running += (isActive(c.status) ? 1 : 0) + sub.running
153    }
154    const n = { descendants, running }
155    counts.set(agent.id, n)
156    return n
157  }
158  for (const t of tops) count(t)
159
160  const rows: TreeRow[] = []
161  const walk = (agent: Agent, depth: number, last: boolean, guides: boolean[]) => {
162    const n = counts.get(agent.id) ?? { descendants: 0, running: 0 }
163    const fold = folded.has(agent.id) && n.descendants > 0
164    rows.push({ agent, depth, last, guides, descendants: n.descendants, running: n.running, folded: fold })
165    if (fold) return
166    const mine = kids.get(agent.id) ?? []
167    // A root's children start the connectors; deeper ones carry a guide for this row's later siblings.
168    const next = depth === 0 ? [] : [...guides, !last]
169    mine.forEach((c, i) => walk(c, depth + 1, i === mine.length - 1, next))
170  }
171  tops.forEach((t, i) => walk(t, 0, i === tops.length - 1, []))
172  return rows
173}
174
175/**
176 * The tree cut to `budget` rows: finished subtrees fold into their parent first, the
177 * topmost (oldest) first, so running agents and their ancestors stay; the rest is cut.
178 */
179export const fitTree = (list: Agent[], budget: number): { rows: TreeRow[]; hidden: number } => {
180  const folded = new Set<string>()
181  let rows = buildTree(list)
182  while (rows.length > budget) {
183    // The topmost row whose whole subtree is finished and still shown.
184    const next = rows.find(r => r.descendants > 0 && r.running === 0 && !r.folded && !folded.has(r.agent.id))
185    if (!next) break
186    folded.add(next.agent.id)
187    rows = buildTree(list, folded)
188  }
189  if (rows.length <= budget) return { rows, hidden: 0 }
190  const shown = rows.slice(0, Math.max(0, budget - 1))
191  return { rows: shown, hidden: rows.length - shown.length }
192}
193
194/** The rolled-up children of a parent row, e.g. `3 sub · 1 running`. */
195export const subSummary = (row: TreeRow): string => {
196  if (row.descendants === 0) return ''
197  const parts = [`${row.descendants} sub`]
198  if (row.running > 0) parts.push(`${row.running} running`)
199  if (row.folded) parts.push('folded')
200  return parts.join(' · ')
201}
202
203const usageTokens = (u: ModelUsage) =>
204  u.input_tokens + u.output_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
205
206// ---- Git section ---------------------------------------------------------
207
208const git = atom({ plugin: 'overview', key: 'git' } as const, null)
209const gh = atom({ plugin: 'overview', key: 'gh' } as const, null)
210const GIT_FILES = 4
211
212type Parsed = Omit<GitInfo, 'ok' | 'root' | 'repo' | 'worktree' | 'insertions' | 'deletions'>
213
214const fileOf = (xy: string, path: string, renamed = false): GitFile => {
215  const x = xy[0] ?? '.'
216  const y = xy[1] ?? '.'
217  const kind: GitFile['kind'] = renamed
218    ? 'renamed'
219    : x === 'A'
220      ? 'added'
221      : x === 'D' || y === 'D'
222        ? 'deleted'
223        : 'modified'
224  return { path, kind, staged: x !== '.' && y === '.' }
225}
226
227/** `git status --porcelain=v2 --branch`, counted and listed. */
228export const parseStatus = (text: string): Parsed => {
229  const out: Parsed = {
230    branch: '',
231    detached: false,
232    ahead: 0,
233    behind: 0,
234    staged: 0,
235    modified: 0,
236    untracked: 0,
237    conflicted: 0,
238    files: [],
239    fileCount: 0,
240  }
241  let oid = ''
242  for (const line of text.split('\n')) {
243    if (!line) continue
244    const parts = line.split(' ')
245    if (line.startsWith('# branch.oid ')) oid = parts[2] ?? ''
246    else if (line.startsWith('# branch.head ')) out.branch = parts.slice(2).join(' ')
247    else if (line.startsWith('# branch.upstream ')) out.upstream = parts.slice(2).join(' ')
248    else if (line.startsWith('# branch.ab ')) {
249      out.ahead = Math.abs(Number(parts[2]) || 0)
250      out.behind = Math.abs(Number(parts[3]) || 0)
251    } else if (parts[0] === '1' || parts[0] === '2') {
252      const xy = parts[1] ?? '..'
253      if (xy[0] !== '.') out.staged++
254      if (xy[1] !== '.') out.modified++
255      const path = parts[0] === '1' ? parts.slice(8).join(' ') : (parts.slice(9).join(' ').split('\t')[0] ?? '')
256      out.files.push(fileOf(xy, path, parts[0] === '2'))
257    } else if (parts[0] === 'u') {
258      out.conflicted++
259      out.files.push({ path: parts.slice(10).join(' '), kind: 'conflict', staged: false })
260    } else if (parts[0] === '?') {
261      out.untracked++
262      out.files.push({ path: parts.slice(1).join(' '), kind: 'untracked', staged: false })
263    }
264  }
265  if (out.branch === '(detached)' || !out.branch) {
266    out.detached = true
267    out.branch = oid && oid !== '(initial)' ? oid.slice(0, 7) : 'detached'
268  }
269  // Conflicts first, then tracked changes, then untracked.
270  const rank = { conflict: 0, added: 1, deleted: 1, renamed: 1, modified: 1, untracked: 2 }
271  out.fileCount = out.files.length
272  out.files = [...out.files].sort((a, b) => rank[a.kind] - rank[b.kind]).slice(0, GIT_FILES)
273  return out
274}
275
276/** `git worktree list --porcelain`: each worktree's path, the main checkout first. */
277export const parseWorktrees = (text: string): string[] =>
278  text
279    .split(/\n\s*\n/)
280    .map(block => block.split('\n').find(l => l.startsWith('worktree '))?.slice('worktree '.length) ?? '')
281    .filter(Boolean)
282
283/** `git diff --shortstat`: insertions and deletions. */
284export const parseShortstat = (text: string) => ({
285  insertions: Number(/(\d+) insertion/.exec(text)?.[1] ?? 0),
286  deletions: Number(/(\d+) deletion/.exec(text)?.[1] ?? 0),
287})
288
289type RollupItem = { name?: string; context?: string; status?: string; conclusion?: string; state?: string }
290
291/** Check runs and commit statuses, counted as GitHub's PR page counts them. */
292export const summarizeChecks = (rollup: RollupItem[] | null | undefined) => {
293  const checks = { passed: 0, failed: 0, pending: 0 }
294  const failing: string[] = []
295  for (const c of rollup ?? []) {
296    const outcome = (c.conclusion || c.state || '').toUpperCase()
297    if (c.status !== undefined && c.status !== 'COMPLETED') checks.pending++
298    else if (['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(outcome)) checks.passed++
299    else if (['PENDING', 'EXPECTED', ''].includes(outcome)) checks.pending++
300    else {
301      checks.failed++
302      const name = c.name || c.context
303      if (name && !failing.includes(name)) failing.push(name)
304    }
305  }
306  return { checks, failing }
307}
308
309export const toGitPr = (json: any, branch: string): GitPr => ({
310  number: Number(json.number),
311  title: String(json.title ?? ''),
312  url: String(json.url ?? ''),
313  state: String(json.state ?? 'OPEN'),
314  isDraft: Boolean(json.isDraft),
315  review: String(json.reviewDecision ?? ''),
316  ...summarizeChecks(json.statusCheckRollup),
317  current: json.headRefName === branch,
318  conflicting: json.mergeable === 'CONFLICTING',
319})
320
321/** A one-line reason from gh's stderr. */
322export const ghNote = (stderr: string): string => {
323  if (/auth login|not logged|authenticat/i.test(stderr)) return 'gh not authenticated (run gh auth login)'
324  if (/no git remote|none of the git remotes|not a git/i.test(stderr)) return 'No GitHub remote for this repo'
325  return (stderr.trim().split('\n')[0] || 'gh failed').slice(0, 120)
326}
327
328const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
329
330/**
331 * A git read: the repo, or why there's none. `lasting`: the answer itself (not a
332 * repo), not a read that failed. `root`: the repo a failed read was for.
333 */
334type GitRead = GitInfo | (GitNote & { lasting?: boolean; root?: string })
335
336/** When git and gh were last read good: the age a failed refresh shows. */
337const goodAt = { git: 0, gh: 0, workspaces: 0 }
338
339/**
340 * What the git state becomes after a read: a good read as it is; a failed one
341 * keeps the last-good figures of the same repo, marked with why and since when;
342 * anything else is its note.
343 */
344const keepGit =(before: GitInfo | GitNote | null, fresh: GitRead, t: number): GitInfo | GitNote => {
345  if (fresh.ok) {
346    goodAt.git = t
347    return fresh
348  }
349  if (!fresh.lasting && before?.ok && (fresh.root === undefined || fresh.root === before.root)) {
350    return { ...before, failed: fresh.note, at: before.failed ? before.at : goodAt.git || undefined }
351  }
352  return { ok: false, note: fresh.note }
353}
354
355/** The same for gh: a failed read for the same repo keeps the last-good PRs. */
356const keepGh =(before: GhInfo | null, fresh: GhInfo): GhInfo => {
357  if (!fresh.note) {
358    goodAt.gh = fresh.at
359    return fresh
360  }
361  if (before && !before.note && before.root === fresh.root) {
362    return { ...before, failed: fresh.note, at: before.failed ? before.at : goodAt.gh || before.at }
363  }
364  return fresh
365}
366
367const loadGit = async ($: EngineInterface): Promise<GitRead> => {
368  const cwd = await $.session.cwd()
369  // --no-optional-locks: a read never rewrites the index.
370  const run = (args: string[]) => $.process.run(['git', '--no-optional-locks', ...args], { cwd, timeoutMs: 10_000 })
371  let top: ProcessRunResult
372  try {
373    top = await run(['rev-parse', '--show-toplevel'])
374  } catch {
375    return { ok: false, note: 'git not found' }
376  }
377  if (top.exitCode !== 0) return { ok: false, note: 'Not a git repository', lasting: true }
378  const root = top.stdout.trim()
379  const [status, wt, diff] = await Promise.all([
380    run(['status', '--porcelain=v2', '--branch']).catch(() => null),
381    run(['worktree', 'list', '--porcelain']).catch(() => null),
382    run(['diff', '--shortstat', 'HEAD']).catch(() => null),
383  ])
384  if (!status || status.exitCode !== 0) {
385    return { ok: false, note: (status?.stderr || 'git status failed').trim().split('\n')[0] || 'git status failed', root }
386  }
387  const trees = wt && wt.exitCode === 0 ? parseWorktrees(wt.stdout) : []
388  const main = trees[0] ?? root
389  return {
390    ok: true,
391    root,
392    repo: basename(main).replace(/\.git$/, ''),
393    ...parseStatus(status.stdout),
394    worktree: { name: basename(root), path: root, linked: trees.length > 0 && root !== main, count: trees.length },
395    ...(diff && diff.exitCode === 0 ? parseShortstat(diff.stdout) : { insertions: 0, deletions: 0 }),
396  }
397}
398
399const GH_FIELDS = 'number,title,state,isDraft,reviewDecision,statusCheckRollup,url,headRefName,mergeable'
400
401const loadGh = async ($: EngineInterface, info: GitInfo): Promise<GhInfo> => {
402  const at = Date.now()
403  const run = (args: string[]) => $.process.run(['gh', ...args], { cwd: info.root, timeoutMs: 20_000 })
404  let list: ProcessRunResult
405  let here: ProcessRunResult | null
406  try {
407    ;[list, here] = await Promise.all([
408      run(['pr', 'list', '--author', '@me', '--state', 'open', '--limit', '5', '--json', GH_FIELDS]),
409      // The current branch's PR, whoever opened it; exits 1 when there is none.
410      info.detached ? Promise.resolve(null) : run(['pr', 'view', '--json', GH_FIELDS]),
411    ])
412  } catch {
413    return { root: info.root, prs: [], note: 'gh not installed', at }
414  }
415  if (list.exitCode !== 0) return { root: info.root, prs: [], note: ghNote(list.stderr), at }
416  const prs: GitPr[] = []
417  try {
418    if (here && here.exitCode === 0) prs.push({ ...toGitPr(JSON.parse(here.stdout), info.branch), current: true })
419    for (const json of JSON.parse(list.stdout) as any[]) {
420      if (!prs.some(p => p.number === json.number)) prs.push(toGitPr(json, info.branch))
421    }
422  } catch {
423    return { root: info.root, prs: [], note: 'Could not read gh output', at }
424  }
425  prs.sort((a, b) => Number(b.current) - Number(a.current) || b.number - a.number)
426  return { root: info.root, prs, at }
427}
428
429let gitBusy = false
430let gitAgain = false
431let ghBusy = false
432
433/** Re-read git; a call made while one runs queues one more run after it. */
434const refreshGit = async ($: EngineInterface): Promise<void> => {
435  if (gitBusy) {
436    gitAgain = true
437    return
438  }
439  gitBusy = true
440  try {
441    do {
442      gitAgain = false
443      const before = await read($, git)
444      const fresh = keepGit(before, await loadGit($), Date.now())
445      if (!same(before, fresh)) await update($, git, () => fresh)
446      const cached = await read($, gh)
447      // A new repo (the session cd'd) shouldn't show the old repo's PRs.
448      if (fresh.ok && cached?.root !== fresh.root) stale.gh = true
449    } while (gitAgain)
450  } finally {
451    gitBusy = false
452  }
453}
454
455// ---- Branches the session works on ----------------------------------------------
456
457const tracked = atom({ plugin: 'overview', key: 'tracked' } as const, [])
458const hidden = atom({ plugin: 'overview', key: 'hidden' } as const, [])
459const branches = atom({ plugin: 'overview', key: 'branches' } as const, [])
460const creating = atom({ plugin: 'overview', key: 'creating' } as const, null)
461const workspacesGh = atom({ plugin: 'overview', key: 'workspacesGh' } as const, null)
462const MAX_BRANCHES = 6
463
464/** Adds a branch to the tracked list once; a path relative to `cwd` is resolved. */
465const track = async ($: EngineInterface, branch: string, path: string, cwd: string) => {
466  const full = path.startsWith('/') ? path : `${cwd.replace(/\/$/, '')}/${path.replace(/^\.\//, '')}`
467  await update($, tracked, list => (list.some(t => t.branch === branch) ? list : [...list, { branch, path: full, at: Date.now() }]))
468}
469
470/** One tracked branch's git state against the default branch. */
471const loadBranch = async ($: EngineInterface, t: Tracked, base: string, prs: Map<string, GitPr>, root: string): Promise<BranchView> => {
472  // A worktree removed after its PR merged leaves the branch in the repository:
473  // read it from the session's checkout then, rather than calling it deleted.
474  const probe = await $.process.run(['git', 'rev-parse', '--git-dir'], { cwd: t.path, timeoutMs: 10_000 }).catch(() => null)
475  const cwd = probe?.exitCode === 0 ? t.path : root
476  const run = (args: string[]) => $.process.run(['git', '--no-optional-locks', ...args], { cwd, timeoutMs: 10_000 }).catch(() => null)
477  const [head, exists, lr, committed, status, remote, top] = await Promise.all([
478    run(['rev-parse', '--abbrev-ref', 'HEAD']),
479    run(['rev-parse', '--verify', '--quiet', `refs/heads/${t.branch}`]),
480    run(['rev-list', '--left-right', '--count', `${base}...${t.branch}`]),
481    run(['diff', '--shortstat', `${base}...${t.branch}`]),
482    run(['status', '--porcelain=v2']),
483    run(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${t.branch}`]),
484    run(['rev-parse', '--show-toplevel', '--git-dir', '--git-common-dir']),
485  ])
486  const checkedOut = head?.exitCode === 0 && head.stdout.trim() === t.branch
487  const counts = checkedOut && status?.exitCode === 0 ? parseStatus(status.stdout) : null
488  // Uncommitted lines count too while the branch is checked out, as the app counts them.
489  const working = checkedOut ? await run(['diff', '--shortstat', 'HEAD']) : null
490  const lines = parseShortstat(committed?.exitCode === 0 ? committed.stdout : '')
491  const extra = parseShortstat(working?.exitCode === 0 ? working.stdout : '')
492  // A linked worktree's git dir differs from the repository's common one.
493  const [toplevel = t.path, gitDir = '.git', common = '.git'] = top?.exitCode === 0 ? top.stdout.trim().split('\n') : []
494  return {
495    branch: t.branch,
496    path: t.path,
497    place: basename(toplevel),
498    worktree: gitDir !== common,
499    exists: exists?.exitCode === 0,
500    checkedOut,
501    ...(lr?.exitCode === 0 ? parseLeftRight(lr.stdout) : { ahead: 0, behind: 0 }),
502    insertions: lines.insertions + extra.insertions,
503    deletions: lines.deletions + extra.deletions,
504    staged: counts?.staged ?? 0,
505    modified: counts?.modified ?? 0,
506    untracked: counts?.untracked ?? 0,
507    conflicted: counts?.conflicted ?? 0,
508    pushed: remote?.exitCode === 0,
509    pr: prs.get(t.branch) ?? null,
510  }
511}
512
513let branchesBusy = false
514
515/** PRs by head branch, from the last gh read; gh runs on its own slower cadence. */
516let prCache = new Map<string, GitPr>()
517let baseCache: string | null = null
518/** Whether a shown workspace has an open PR, as of the last read: gh is then read more often. */
519let openPrs = false
520
521/** Re-reads every shown tracked branch; with `withGh`, all their PRs too, in one gh call. */
522const refreshBranches = async ($: EngineInterface, withGh = false): Promise<void> => {
523  if (branchesBusy) {
524    // A gh read skipped now would otherwise wait out the whole interval: try again soon.
525    if (withGh) stale.gh = true
526    return
527  }
528  branchesBusy = true
529  try {
530    const info = await read($, git)
531    if (!info?.ok) return
532    const run = (cmd: string[]) => $.process.run(cmd, { cwd: info.root, timeoutMs: 20_000 }).catch(() => null)
533    if (baseCache === null) {
534      const ref = await run(['git', 'rev-parse', '--abbrev-ref', 'origin/HEAD'])
535      baseCache = ref?.exitCode === 0 ? ref.stdout.trim() : 'origin/main'
536    }
537    // The default branch is what the others merge into, not a workspace of its own
538    // (it would offer "Create PR" against itself), even when the session sits on it.
539    const base = baseCache.replace(/^origin\//, '')
540    // The session's own branch counts as started here.
541    if (!info.detached && info.branch !== base) await track($, info.branch, info.root, info.root)
542    const off = await read($, hidden)
543    const list = (await read($, tracked))
544      .filter(t => !off.includes(t.branch) && t.branch !== base)
545      .slice(-MAX_BRANCHES)
546      .reverse()
547    if (withGh) {
548      const prList = await run(['gh', 'pr', 'list', '--state', 'all', '--limit', '40', '--json', GH_FIELDS])
549      let failed: string | undefined = !prList ? 'gh not installed' : prList.exitCode !== 0 ? ghNote(prList.stderr) : undefined
550      if (prList?.exitCode === 0) {
551        try {
552          // Newest first from gh, so the first PR per branch is its latest.
553          const prs = new Map<string, GitPr>()
554          for (const json of JSON.parse(prList.stdout) as any[]) if (!prs.has(json.headRefName)) prs.set(json.headRefName, toGitPr(json, json.headRefName))
555          prCache = prs
556        } catch {
557          failed = 'Could not read gh output'
558        }
559      }
560      // A failed read keeps the last PRs (prCache), marked with why and since when.
561      const before = await read($, workspacesGh)
562      if (!failed) goodAt.workspaces = Date.now()
563      const next: WorkspacesGh = failed ? { failed, at: before?.failed ? before.at : goodAt.workspaces } : { at: goodAt.workspaces }
564      // A good read after a good read changes nothing drawn: no write, no redraw.
565      if (failed ? !same(before, next) : !before || before.failed) await update($, workspacesGh, () => next)
566    }
567    const loaded = await Promise.all(list.map(t => loadBranch($, t, baseCache!, prCache, info.root)))
568    // git and gh took a while: a branch hidden since `off` was read must not come
569    // back. `hiding` is checked again inside the write, which retries on a miss.
570    openPrs = loaded.some(b => b.pr?.state === 'OPEN')
571    const offNow = await read($, hidden)
572    const shown = () => loaded.filter(b => !offNow.includes(b.branch) && !hiding.has(b.branch))
573    if (!same(await read($, branches), shown())) await update($, branches, shown)
574  } finally {
575    branchesBusy = false
576  }
577}
578
579/**
580 * Branches hidden in this process, set before any await: a refresh already
581 * running read `hidden` before the press, and filters by this when it writes.
582 */
583const hiding = new Set<string>()
584
585/** The ✕ on a branch: stop showing it. */
586const hideBranch = async ($: EngineInterface, branch: string) => {
587  hiding.add(branch)
588  await update($, hidden, list => (list.includes(branch) ? list : [...list, branch]))
589  await update($, branches, list => list.filter(b => b.branch !== branch))
590}
591
592/**
593 * Create PR, as the desktop app's own button does it: hand it to the session as a
594 * prompt, so Claude writes the description, opens the PR and starts watching it
595 * (auto-merge and Auto-fix, per the person's instructions). Runs as a turn of its
596 * own once the session is idle.
597 */
598const createPr = async ($: EngineInterface, branch: string) => {
599  if (await read($, creating)) return
600  const view = (await read($, branches)).find(b => b.branch === branch)
601  if (!view) return
602  await update($, creating, () => branch)
603  try {
604    await $.prompt.submit({
605      text:
606        `Create a pull request for the \`${branch}\` branch (checked out at ${view.path}). ` +
607        'Push it if needed, write the title and body from its commits, open it, and start watching it.',
608      asUser: true,
609    })
610  } catch {
611    $.ui.toast('Create PR: could not send the request to the session')
612  } finally {
613    await update($, creating, () => null)
614  }
615}
616
617const refreshGh = async ($: EngineInterface): Promise<void> => {
618  if (ghBusy) return
619  const info = await read($, git)
620  if (!info?.ok) return
621  ghBusy = true
622  try {
623    const before = await read($, gh)
624    const fresh = keepGh(before, await loadGh($, info))
625    // Keep the old timestamp when nothing changed, so the pane doesn't redraw for nothing.
626    if (!before || !same({ ...before, at: 0 }, { ...fresh, at: 0 })) await update($, gh, () => fresh)
627  } finally {
628    ghBusy = false
629  }
630}
631
632const FILE_TOOLS = ['Bash', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit']
633
634// ---- Account limits --------------------------------------------------------
635
636const limits = atom({ plugin: 'overview', key: 'limits' } as const, null)
637
638const KNOWN_WINDOWS: Record<string, string> = { five_hour: '5-hour', seven_day: 'Weekly', spend_limit: 'Spend' }
639
640const prettify = (s: string) => {
641  const t = s.replace(/[_-]+/g, ' ').trim()
642  return t ? t[0]!.toUpperCase() + t.slice(1) : s
643}
644
645/** A window's name for people: `five_hour` -> 5-hour, `seven_day_opus` -> Weekly opus. */
646export const limitLabel = (kind: string): string => {
647  const known = KNOWN_WINDOWS[kind]
648  if (known) return known
649  for (const [prefix, label] of Object.entries(KNOWN_WINDOWS)) {
650    if (kind.startsWith(`${prefix}_`)) return `${label} ${kind.slice(prefix.length + 1).replace(/[_-]+/g, ' ')}`
651  }
652  return prettify(kind)
653}
654
655export const toLimits = (list: SessionRateLimit[]): Limit[] =>
656  list.map(l => ({ kind: l.kind, percent: l.percentUsed, ...(l.resetsAt ? { resetsAt: l.resetsAt } : {}) }))
657
658/** "resets in 2h 14m", "resets in 3d 4h", or "" when the time is unknown. */
659export const resetIn = (resetsAt: string | undefined, at: number): string => {
660  if (!resetsAt) return ''
661  const t = Date.parse(resetsAt)
662  if (Number.isNaN(t)) return ''
663  const m = Math.ceil((t - at) / 60_000)
664  if (m <= 0) return 'resets now'
665  const d = Math.floor(m / 1_440)
666  const h = Math.floor((m % 1_440) / 60)
667  if (d > 0) return `resets in ${d}d ${h}h`
668  if (h > 0) return `resets in ${h}h ${m % 60}m`
669  return `resets in ${m}m`
670}
671
672const storeLimits = async ($: EngineInterface, list: SessionRateLimit[]) => {
673  const fresh = toLimits(list)
674  if (!same(await read($, limits), fresh)) await update($, limits, () => fresh)
675}
676
677// The session's folder, read once, so an agent's paths can be drawn relative to it.
678let sessionCwd: string | undefined
679
680/** Keeps an agent's latest tool call in words, written only when it changed. */
681const noteDoing = async ($: EngineInterface, id: string, tool: string, args: Record<string, unknown>): Promise<void> => {
682  sessionCwd ??= await $.session.cwd().catch(() => undefined)
683  const doing = describeCall(tool, args, sessionCwd)
684  const old = (await read($, agentExtra))[id]?.doing
685  if (old && old.kind === doing.kind && old.text === doing.text && old.arg === doing.arg) return
686  await update($, agentExtra, all => ({ ...all, [id]: { ...all[id], doing } }))
687}
688
689// Ticks once a second while any agent runs, so elapsed times move; stopped when none do.
690let ticker: Timer | undefined
691/** The running agents' elapsed times as their cards last showed them (`elapsedShown`). */
692let lastElapsed = ''
693
694/** Each running agent's elapsed time as its card draws it (`short`, whole minutes) at `t`. */
695export const elapsedShown = (list: Agent[], extras: Record<string, AgentExtra>, t: number): string =>
696  list
697    .filter(a => a.status === 'running' && extras[a.id]?.startedAt !== undefined)
698    .map(a => `${a.id} ${short(t - extras[a.id]!.startedAt!)}`)
699    .join('\n')
700
701const refreshAgents = async ($: EngineInterface): Promise<void> => {
702  const extras = await read($, agentExtra)
703  const fresh = (await $.agent.list()).map(info => {
704    const agent = toAgent(info)
705    // The list should name the spawning agent; the spawn hook's parentAgentId backs it up.
706    const parentId = extras[agent.id]?.parentId
707    if (!agent.parentId && parentId) agent.parentId = parentId
708    return agent
709  })
710  const before = await read($, agents)
711  if (JSON.stringify(before) !== JSON.stringify(fresh)) await update($, agents, () => fresh)
712  const running = fresh.some(a => a.status === 'running' || a.status === 'pending')
713  if (running) {
714    // Elapsed times move only where someone can see them, and redraw only when one
715    // drawn would read differently (a card shows whole minutes).
716    const t = Date.now()
717    const elapsed = elapsedShown(fresh, extras, t)
718    if (elapsed !== lastElapsed && (await isShown($))) {
719      lastElapsed = elapsed
720      await update($, now, () => t)
721    }
722    ticker ??= $.clock.every(TICK_MS, () => void perf.time('agents', () => refreshAgents($)).catch(() => undefined))
723  } else if (ticker) {
724    ticker.cancel()
725    ticker = undefined
726  }
727}
728
729// ---- Session activity --------------------------------------------------------
730
731const activity = atom({ plugin: 'overview', key: 'activity' } as const, {
732  turns: 0,
733  tools: {},
734  files: [],
735  turnLog: [],
736  contextLog: [],
737})
738const TURN_LOG = 40
739const CONTEXT_LOG = 60
740const EDIT_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
741
742/** The path an editing tool's arguments name, if any. */
743export const editedPath = (tool: string, args: { file_path?: unknown; notebook_path?: unknown }): string | undefined => {
744  if (!EDIT_TOOLS.includes(tool)) return undefined
745  const path = args.file_path ?? args.notebook_path
746  return typeof path === 'string' && path ? path : undefined
747}
748
749/** `path` relative to the session's folder when it's inside it, else as given. */
750const relative = (path: string, cwd: string | undefined): string =>
751  cwd && path.startsWith(`${cwd.replace(/\/$/, '')}/`) ? path.slice(cwd.replace(/\/$/, '').length + 1) : path
752
753/** A string argument, its first line, trimmed; empty when it isn't one. */
754const arg = (v: unknown): string => (typeof v === 'string' ? (v.trim().split('\n')[0] ?? '').trim() : '')
755
756/**
757 * A tool call for an agent's "doing now" line: its kind, a name or verb and its
758 * argument (`Bash` `bun build.ts`, `Editing` `kit/ui.tsx`, `Searching` `TODO`).
759 * Paths are made relative to the session's folder.
760 */
761export const describeCall = (tool: string, args: Record<string, unknown>, cwd?: string): Doing => {
762  const doing = (kind: DoingKind, text: string, v: unknown, isPath = false): Doing => {
763    const a = arg(v)
764    return a ? { kind, text, arg: isPath ? relative(a, cwd) : a } : { kind, text }
765  }
766  switch (tool) {
767    case 'Bash':
768      return doing('bash', 'Bash', args.command)
769    case 'Edit':
770    case 'MultiEdit':
771    case 'NotebookEdit':
772      return doing('edit', 'Editing', args.file_path ?? args.notebook_path, true)
773    case 'Write':
774      return doing('edit', 'Writing', args.file_path, true)
775    case 'Read':
776      return doing('read', 'Reading', args.file_path, true)
777    case 'Grep':
778      return doing('search', 'Searching', args.pattern)
779    case 'Glob':
780      return doing('search', 'Finding', args.pattern)
781    case 'WebFetch':
782      return doing('web', 'Fetching', args.url)
783    case 'WebSearch':
784      return doing('web', 'Searching the web', args.query)
785    case 'Agent':
786    case 'Task':
787      return doing('agent', 'Starting agent', args.description)
788    default:
789      // An MCP tool by its own name, its server dim after it: `search_issues` `github`.
790      if (tool.startsWith('mcp__')) {
791        const [, server, ...name] = tool.split('__')
792        return name.length ? { kind: 'mcp', text: name.join('__'), arg: server } : { kind: 'mcp', text: tool }
793      }
794      return { kind: 'other', text: tool }
795  }
796}
797
798/** The activity with one more tool call. */
799export const countTool = (a: Activity, tool: string, isError: boolean, path?: string): Activity => {
800  const old = a.tools[tool] ?? { n: 0, err: 0 }
801  const tools = { ...a.tools, [tool]: { n: old.n + 1, err: old.err + (isError ? 1 : 0) } }
802  const files = path && !a.files.includes(path) ? [...a.files, path] : a.files
803  const turnTools = { ...a.turnTools, [tool]: (a.turnTools?.[tool] ?? 0) + 1 }
804  return { ...a, tools, files, callsThisTurn: (a.callsThisTurn ?? 0) + 1, turnTools }
805}
806
807/** The activity with one more main-loop turn, the log cut to its last TURN_LOG. */
808export const countTurn = (a: Activity, ms: number, usage: ModelUsage | undefined): Activity => {
809  const point: TurnPoint = {
810    ms,
811    input: usage?.input_tokens ?? 0,
812    output: usage?.output_tokens ?? 0,
813    cacheRead: usage?.cache_read_input_tokens ?? 0,
814    cacheWrite: usage?.cache_creation_input_tokens ?? 0,
815    calls: a.callsThisTurn ?? 0,
816    tools: a.turnTools ?? {},
817  }
818  return { ...a, turns: a.turns + 1, callsThisTurn: 0, turnTools: {}, turnLog: [...a.turnLog, point].slice(-TURN_LOG) }
819}
820
821export const refresh = async ($: EngineInterface) => {
822  const usage = await $.session.usage({ breakdown: 'summary' })
823  const b = usage.context.breakdown
824  if (b) {
825    const fresh = toSnapshot(b)
826    if (!same(await read($, snapshot), fresh)) await update($, snapshot, () => fresh)
827  }
828  await storeLimits($, usage.rateLimits ?? [])
829  const percent = b?.percentage ?? usage.context.percent
830  await update($, activity, a => {
831    const log =
832      percent === undefined || a.contextLog.at(-1) === percent ? a.contextLog : [...a.contextLog, percent].slice(-CONTEXT_LOG)
833    const next: Activity = { ...a, startedAt: usage.startedAt, contextLog: log }
834    if (usage.cost) next.cost = usage.cost.usd
835    return same(a, next) ? a : next
836  })
837}
838
839// ---- When to work ------------------------------------------------------------
840// Nothing runs while the pane isn't shown: events only mark what went stale,
841// and one timer reads it again, at most so often, while the pane is on screen.
842
843let shownAt = 0
844let shown = false
845
846/** Whether the overview pane is the one shown and placed; asked at most every 2 s. */
847const isShown = async ($: EngineInterface): Promise<boolean> => {
848  if (Date.now() - shownAt < 2_000) return shown
849  shownAt = Date.now()
850  try {
851    shown = (await $.ui.panes()).some(p => p.id === PANE && p.isShown && p.isPlaced)
852  } catch {
853    shown = false
854  }
855  return shown
856}
857
858const stale = { usage: true, git: true, gh: true }
859const last = { usage: 0, git: 0, gh: 0, clock: 0, resources: 0 }
860const RESOURCES_EVERY = 10_000
861let nettopBusy = false
862
863/** One sample of the session's share of the machine; see resources.ts. */
864const sampleResources = async ($: EngineInterface) => {
865  const run = await $.process.run(resourcesSh(), { timeoutMs: 5_000 })
866  if (run.exitCode !== 0) return null
867  if (NET_PER_PROCESS && !nettopBusy) {
868    nettopBusy = true
869    $.process
870      .run(NETTOP, { timeoutMs: 10_000 })
871      .then(r => (r.exitCode === 0 ? takeNettop(r.stdout, Date.now()) : undefined))
872      .catch(() => undefined)
873      .finally(() => (nettopBusy = false))
874  }
875  return toResources(run.stdout, Date.now())
876}
877// Even with nothing marked stale, read again this often while shown.
878const EVERY = { usage: 60_000, git: 60_000, gh: 180_000, clock: 60_000 }
879// And never more often than this, however much happens.
880const AT_MOST = { usage: 3_000, git: 3_000, gh: 20_000 }
881let worker: Timer | undefined
882
883// While a workspace has an open PR, GitHub moves it with nothing happening here
884// (checks finish, auto-merge lands), so gh is read this often instead.
885const GH_WHILE_OPEN = 30_000
886
887export const due = (kind: 'usage' | 'git' | 'gh', t: number) =>
888  t - last[kind] >= (stale[kind] ? AT_MOST[kind] : kind === 'gh' && openPrs ? GH_WHILE_OPEN : EVERY[kind])
889
890const tick = async ($: EngineInterface) => {
891  if (!(await isShown($))) return
892  const t = Date.now()
893  if (due('usage', t)) {
894    stale.usage = false
895    last.usage = t
896    await perf.time('usage', () => refresh($))
897  }
898  if (due('git', t)) {
899    stale.git = false
900    last.git = t
901    await perf.time('git', () => refreshGit($))
902    if (!due('gh', t)) await perf.time('branches', () => refreshBranches($))
903  }
904  if (due('gh', t)) {
905    stale.gh = false
906    last.gh = t
907    await perf.time('gh', () => refreshGh($))
908    await perf.time('branches', () => refreshBranches($, true))
909  }
910  // The session's share of the machine: a few shell commands, every 10 s while shown.
911  if (t - last.resources >= RESOURCES_EVERY) {
912    last.resources = t
913    const res = await perf.time('resources', () => sampleResources($)).catch(() => null)
914    if (res && !same(await read($, resources), res)) await update($, resources, () => res)
915  }
916  // The session's elapsed time moves even when nothing else does.
917  if (t - last.clock >= EVERY.clock) {
918    last.clock = t
919    await update($, now, () => t)
920  }
921}
922
923const HELPERS: Helpers = { colorOf, limitLabel, resetIn, buildTree }
924const TERM_HELPERS: TermHelpers = { limitLabel, resetIn, fitTree, subSummary }
925
926/** What this mod costs, drawn in the pane's debug footer. */
927export const perf = createPerf()
928
929/** The app mode's sections the person folded; kept for the session. */
930const collapsed = atom({ plugin: 'overview', key: 'collapsed' } as const, [])
931/** Whether a wide app pane flows its sections into columns; the footer's switch flips it. */
932const columns = atom({ plugin: 'overview', key: 'columns' } as const, true)
933
934export const register: Register = on => {
935  on('session.start', async ($, e, next) => {
936    await $.command.register({
937      name: 'overview',
938      description: 'Open the session overview pane: context, cost, turns, tools, agents, limits and git',
939    })
940    void refreshAgents($).catch(() => undefined)
941    worker?.cancel()
942    worker = $.clock.every(3_000, () => void perf.time('tick', () => tick($)).catch(() => undefined))
943    void $.ui.open({ id: PANE, title: 'Overview' })
944
945    return next(e)
946  })
947
948  // A tool that may have changed files (or pushed, or opened a PR) marks git stale;
949  // a gh or push command marks the PRs stale too. Nothing waits on the bookkeeping.
950  on('tool.call', async ($, e, next) => {
951    // A subagent's call, as it starts: what that agent is doing now.
952    const agentId = e.agentId
953    if (agentId) void noteDoing($, agentId, e.tool, e as unknown as Record<string, unknown>).catch(() => undefined)
954    const ran = await next(e)
955    if (!('deny' in ran && ran.deny)) {
956      const path = editedPath(e.tool, e as { file_path?: unknown; notebook_path?: unknown })
957      void perf.time('tool.call', () => update($, activity, a => countTool(a, e.tool, Boolean(ran.isError), path))).catch(() => undefined)
958    }
959    // A command that starts a branch or a worktree: track it.
960    if (e.tool === 'Bash') {
961      const started = startedBy(e.command)
962      if (started.length) {
963        void (async () => {
964          const cwd = await $.session.cwd()
965          for (const s of started) await track($, s.branch, s.path ?? cwd, cwd)
966          stale.gh = true
967        })().catch(() => undefined)
968      }
969    }
970    if (FILE_TOOLS.includes(e.tool)) {
971      stale.git = true
972      if (e.tool === 'Bash' && /\bgh pr\b|\bgit (push|commit|checkout|switch)\b/.test(e.command)) stale.gh = true
973    }
974    return ran
975  })
976
977  // The list has no start time; the spawn does, and the loop it happened in.
978  on('agent.spawn', async ($, e, next) => {
979    const started = await next(e)
980    const id = started.agentId
981    if (id) {
982      const parentId = e.parentAgentId
983      await update($, agentExtra, all => {
984        const x: AgentExtra = { ...all[id], startedAt: Date.now() }
985        if (parentId && parentId !== id) x.parentId = parentId
986        return { ...all, [id]: x }
987      })
988      await refreshAgents($).catch(() => undefined)
989    }
990    return started
991  })
992
993  // Each run of a subagent's loop is one turn; its end carries duration and usage.
994  on('turn.complete', async ($, e, next) => {
995    const done = await next(e)
996    stale.git = true
997    const id = e.agentId
998    if (id) {
999      await update($, agentExtra, all => {
1000        const old = all[id] ?? {}
1001        const x: AgentExtra = { ...old, durationMs: (old.durationMs ?? 0) + e.durationMs }
1002        if (e.usage) x.tokens = (old.tokens ?? 0) + usageTokens(e.usage)
1003        return { ...all, [id]: x }
1004      })
1005      void refreshAgents($).catch(() => undefined)
1006    } else {
1007      void update($, activity, a => countTurn(a, e.durationMs, e.usage)).catch(() => undefined)
1008    }
1009    return done
1010  })
1011
1012  on('command.run', { command: 'overview' }, async $ => {
1013    // Opened by the person: read everything now rather than on the next tick.
1014    shownAt = 0
1015    stale.usage = stale.git = stale.gh = true
1016    last.usage = last.git = last.gh = 0
1017    await refresh($)
1018    await $.ui.open({ id: PANE, title: 'Overview' })
1019
1020    return { text: 'Overview pane opened.' }
1021  })
1022
1023  on('session.measure', async ($, e, next) => {
1024    const result = await next(e)
1025    if (e.changed.includes('rateLimits')) await storeLimits($, e.rateLimits)
1026    // The breakdown is worked out on the next tick, if the pane is shown.
1027    stale.usage = true
1028
1029    return result
1030  })
1031
1032  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1033    // Read so the pane redraws as elapsed times move.
1034    await read($, now)
1035    const data: DesktopData = {
1036      snap: await read($, snapshot),
1037      limits: await read($, limits),
1038      agents: await read($, agents),
1039      extras: await read($, agentExtra),
1040      git: await read($, git),
1041      gh: await read($, gh),
1042      activity: await read($, activity),
1043      collapsed: await read($, collapsed),
1044      resources: await read($, resources),
1045      branches: await read($, branches),
1046      creating: await read($, creating),
1047      workspacesGh: await read($, workspacesGh),
1048      focused: e.props.isFocused,
1049      hideBranch: (branch: string) => void hideBranch($, branch).catch(err => $.ui.toast(`Hide ${branch}: ${err?.message ?? err}`)),
1050      // Merge, like Create PR: the session does it, and reports back.
1051      mergePr: (pr: GitPr) =>
1052        void $.prompt
1053          .submit({ text: `Merge PR #${pr.number} (${pr.url}) once its checks pass: turn on auto-merge, or merge it now if it's already green.`, asUser: true })
1054          .catch(() => $.ui.toast('Merge: could not send the request to the session')),
1055      createPr: (branch: string) => void createPr($, branch).catch(() => undefined),
1056      toggle: (id: string) =>
1057        void update($, collapsed, list => (list.includes(id) ? list.filter(x => x !== id) : [...list, id])).catch(() => undefined),
1058      columnsOn: await read($, columns),
1059      toggleColumns: () => void update($, columns, was => !was).catch(() => undefined),
1060      columns: e.props.bodyColumns,
1061      rows: e.props.scroll?.bodyRows,
1062      at: Date.now(),
1063      perf: perf.snapshot(),
1064    }
1065    // The terminal draws the same inspector in cells; the app surfaces as boxes.
1066    // Buttons keep their press handles across redraws, so a click made just before one still lands.
1067    const els = holdButtons($.ui.resolve(e), e)
1068    if (e.surface === 'terminal') {
1069      return perf.time('render', () => renderTerminal(els as TermElements, data, TERM_HELPERS))
1070    }
1071    return perf.time('render', () => renderDesktop(els as AppElements, data, HELPERS))
1072  })
1073}
1074
hooks/branches.ts 38 lines
1/*
2 * The branches a session works on, as the desktop app tracks them: each branch
3 * or worktree the session starts, with its git state and its PR. This file
4 * holds the parsing; register.tsx runs git and gh.
5 */
6
7/** Branches a Bash command starts, and where (relative to the command's directory when not absolute). */
8export const startedBy = (command: string): { branch: string; path?: string }[] => {
9  const found: { branch: string; path?: string }[] = []
10  for (const part of command.split(/&&|\|\||;|\n/)) {
11    const words = part.trim().split(/\s+/)
12    const at = words.indexOf('git')
13    if (at < 0) continue
14    const w = words.slice(at + 1).filter(x => x !== '-q' && x !== '--quiet')
15    const flag = (names: string[]) => {
16      const i = w.findIndex(x => names.includes(x))
17      return i >= 0 ? w[i + 1] : undefined
18    }
19    if (w[0] === 'checkout' || w[0] === 'switch') {
20      const branch = flag(['-b', '-B', '-c', '-C'])
21      if (branch) found.push({ branch })
22    } else if (w[0] === 'worktree' && w[1] === 'add') {
23      const rest = w.slice(2)
24      const branch = flag(['-b', '-B'])
25      const positional = rest.filter((x, i) => !x.startsWith('-') && !['-b', '-B', '--reason'].includes(rest[i - 1] ?? ''))
26      const path = positional[0]
27      if (path) found.push({ branch: branch ?? positional[1] ?? path.split('/').pop()!, path: path.replace(/^["']|["']$/g, '') })
28    }
29  }
30  return found
31}
32
33/** `git rev-list --left-right --count A...B`: behind, ahead. */
34export const parseLeftRight = (text: string) => {
35  const [behind = 0, ahead = 0] = text.trim().split(/\s+/).map(Number)
36  return { behind, ahead }
37}
38
hooks/desktop.tsx 541 lines
1import type { Elements, RenderElement } from 'claude-code'
2
3import { bytes, middle, money, short, tokens } from '@kit/format'
4import type { PerfSnapshot } from '@kit/perf'
5import { C, GLYPH, GRAY, INK, MUTED, RAMP, TRACK, levelColor } from '@kit/tokens'
6import { EDGE, SPACE, kit } from '@kit/ui'
7
8import type { Activity, Agent, AgentExtra, BranchView, Doing, GhInfo, GitInfo, GitNote, GitPr, Limit, Resources, Snapshot, WorkspacesGh } from '../types'
9
10/*
11 * The app mode: a properties inspector for the session, drawn as an instrument.
12 *
13 * The rules it keeps (kit/tokens.ts and kit/ui.tsx hold the values):
14 * - Colour: each hue one meaning (grey labels, slate quantity, blue live, amber
15 *   near a limit, red failed, green done well, purple merged). Icons are muted.
16 * - Type: values plain, labels and units dim, bold only for section titles and
17 *   the context %, uppercase only for captions and a branch's state word.
18 * - Spacing: the kit's SPACE scale and INSET; nothing else.
19 * - Each fact once: calls and time in the header, cost in Accounting.
20 */
21
22/** The elements the app mode draws with: the desktop and VS Code have these. */
23export type AppElements = Pick<Elements['desktop'], 'Box' | 'Text' | 'Link' | 'Button' | 'Svg'>
24
25export type DesktopData = {
26  snap: Snapshot | null
27  limits: Limit[] | null
28  agents: Agent[]
29  extras: Record<string, AgentExtra>
30  git: GitInfo | GitNote | null
31  gh: GhInfo | null
32  activity: Activity
33  /** Section ids the person folded. */
34  collapsed: string[]
35  /** Folds or unfolds a section. */
36  toggle: (id: string) => void
37  /** The column view's switch: on, a wide pane flows its sections into columns. */
38  columnsOn: boolean
39  /** Flips the column view. */
40  toggleColumns: () => void
41  /** The pane's width in cells. */
42  columns: number
43  /** The pane's height in rows, so the footer can sit on its bottom edge. */
44  rows?: number
45  /** The session's share of the machine, for the footer. */
46  resources: Resources | null
47  /** The branches the session started, newest first. */
48  branches: BranchView[]
49  /** The branch a PR is being created for, if any. */
50  creating: string | null
51  /** Hide a branch. */
52  hideBranch: (branch: string) => void
53  /** Create PR on a branch without one. */
54  createPr: (branch: string) => void
55  /** Merge on an open PR. */
56  mergePr: (pr: GitPr) => void
57  /** What the mod cost, for the debug footer. */
58  perf: PerfSnapshot
59  /** The clock elapsed times and resets are drawn against. */
60  at: number
61  /** The workspaces' last `gh pr list`: whether it failed, and when it last read good (the terminal shows it). */
62  workspacesGh?: WorkspacesGh | null
63  /** Whether the pane has the keyboard (`e.props.isFocused`); the terminal's kit takes it. */
64  focused?: boolean
65}
66
67/** What the app mode borrows from register.tsx, passed in so this file has no cycle back. */
68export type Helpers = {
69  colorOf: (segments: Snapshot['segments'], i: number) => string | undefined
70  limitLabel: (kind: string) => string
71  resetIn: (resetsAt: string | undefined, at: number) => string
72  buildTree: (list: Agent[]) => Array<{ agent: Agent; depth: number }>
73}
74
75/**
76 * A context category's short name and colour: the fixed overhead in shades of
77 * slate (it only says how much), messages in blue (the part that grows).
78 */
79// Grouped into four, so the legend is short: what the system brings, what MCP
80// brings, what the person's setup brings (memory, skills, agents), and the conversation.
81export const CATEGORY: Record<string, { name: string; color: string }> = {
82  'System prompt': { name: 'System', color: RAMP.slate[0] },
83  'System tools': { name: 'System', color: RAMP.slate[0] },
84  'MCP tools': { name: 'MCP', color: RAMP.slate[1] },
85  'MCP server instructions': { name: 'MCP', color: RAMP.slate[1] },
86  'Custom agents': { name: 'Memory', color: RAMP.slate[2] },
87  'Memory files': { name: 'Memory', color: RAMP.slate[2] },
88  Skills: { name: 'Memory', color: RAMP.slate[2] },
89  Messages: { name: 'Messages', color: C.blue },
90}
91
92/** Three letters for a context category: what the terminal layout's chips show. */
93export const tagOf = (name: string): string => {
94  const known: Record<string, string> = {
95    'System prompt': 'sys',
96    'System tools': 'tls',
97    'MCP tools': 'mcp',
98    'Custom agents': 'agt',
99    'Memory files': 'mem',
100    Skills: 'skl',
101    Messages: 'msg',
102  }
103  return known[name] ?? name.slice(0, 3).toLowerCase()
104}
105
106/** An agent's status as its icon's colour: running or queued blue, done green, failed red, else grey. */
107export const statusColor = (status: string): string =>
108  status === 'running' || status === 'pending' ? C.blue : status === 'completed' ? C.ok : status === 'failed' ? C.bad : MUTED
109
110/** A mark for each kind of thing: its icon on the app surfaces, its one-cell glyph on the terminal. */
111type Mark = { icon: string; glyph: string }
112
113/**
114 * Each kind of agent's mark: code for a lane lead, tools for a worker, a bolt for
115 * a quick fix, a checklist (◎ on the terminal, as ✓ means done) for a reviewer,
116 * a telescope to explore, a task list to plan, a robot for the general agent and
117 * a book for the guide; the agents sparkle for any other.
118 */
119const AGENT_MARK: Record<string, Mark> = {
120  developer: { icon: 'code', glyph: '◆' },
121  worker: { icon: 'tools', glyph: '◇' },
122  'quick-fix': { icon: 'zap', glyph: '↯' },
123  reviewer: { icon: 'checklist', glyph: '◎' },
124  explore: { icon: 'telescope', glyph: '⌕' },
125  plan: { icon: 'tasklist', glyph: '≡' },
126  'general-purpose': { icon: 'hubot', glyph: '○' },
127  'claude-code-guide': { icon: 'book', glyph: '?' },
128}
129export const agentMark = (type: string): Mark => AGENT_MARK[type.toLowerCase()] ?? { icon: GLYPH.agents, glyph: '✦' }
130
131/** Each kind of tool call's mark, for an agent's "doing now" line. */
132const DOING_MARK: Record<string, Mark> = {
133  bash: { icon: 'terminal', glyph: '$' },
134  edit: { icon: 'pencil', glyph: '✎' },
135  read: { icon: 'eye', glyph: '◇' },
136  search: { icon: 'search', glyph: '⌕' },
137  web: { icon: 'globe', glyph: '◎' },
138  agent: { icon: GLYPH.agents, glyph: '✦' },
139  mcp: { icon: 'plug', glyph: '⏚' },
140  other: { icon: 'dot-fill', glyph: '·' },
141}
142export const doingMark = (d: Doing): Mark => DOING_MARK[d.kind] ?? DOING_MARK.other!
143
144/**
145 * A "doing now" line's argument in what's left of `cells` after its name and a
146 * space, cut in the middle (`mods/…/register.tsx`) so its end stays in view.
147 */
148export const doingArg = (d: Doing, cells: number): string | undefined =>
149  d.arg ? middle(d.arg, Math.max(8, cells - [...d.text].length - 1)) : undefined
150
151/**
152 * A PR's state as one colour: merged purple; closed or draft grey; an open one green,
153 * red while it has conflicts (on GitHub or in the checkout), amber while CI fails.
154 */
155export const prColor = (pr: GitPr, conflicted: boolean) =>
156  pr.state === 'MERGED'
157    ? C.purple
158    : pr.state === 'CLOSED' || pr.isDraft
159      ? MUTED
160      : conflicted || pr.conflicting
161        ? C.bad
162        : pr.checks.failed
163          ? C.warn
164          : C.ok
165
166/** "2h18", "3d4h", from "resets in 2h 18m". */
167export const compact = (s: string) => s.replace('resets in ', '').replace(/ /g, '')
168
169/** The context bar's free room: a step brighter than the empty track. */
170const FREE = 'rgba(128,128,128,0.34)'
171/** The context bar's buffer past compaction: the compaction mark's amber, faint. */
172const BUFFER = 'rgba(227,163,59,0.32)'
173
174export const shortTool = (name: string) => (name.startsWith('mcp__') ? (name.split('__').pop() ?? name) : name)
175
176/**
177 * The footer's lead: the session's share of the machine, ours against the
178 * system's, under muted three-letter labels; ours turns amber or red when it's a big share.
179 */
180export const machine = (k: ReturnType<typeof kit>, r: Resources | null): RenderElement[] => {
181  if (!r) return []
182  const hot = (part: number, whole: number) => (whole > 0 && part / whole > 0.5 ? C.bad : whole > 0 && part / whole > 0.25 ? C.warn : undefined)
183  const pctOf = (n: number) => `${Math.round(n)}%`
184  return [
185    k.share('cpu', 'cpu', pctOf(r.cpu), pctOf(r.cpuAll), hot(r.cpu, r.cpuAll)),
186    k.share('mem', 'mem', bytes(r.mem), bytes(r.memAll), hot(r.mem, r.memAll)),
187    k.share('net', 'net', r.net === null ? '–' : bytes(r.net), bytes(r.netAll), r.net === null ? undefined : hot(r.net, r.netAll)),
188  ]
189}
190
191/** The context window's used segments summed into their groups, in the groups' order; the free room up to compaction; the buffer past it. */
192export const contextParts = (snap: Snapshot | null) => {
193  const parts: { value: number; color: string; label: string }[] = []
194  for (const s of snap?.segments ?? []) {
195    if (s.kind !== 'used' || s.tokens <= 0) continue
196    const c = CATEGORY[s.name] ?? { name: s.name, color: INK }
197    const at = parts.find(p => p.label === c.name)
198    if (at) at.value += s.tokens
199    else parts.push({ value: s.tokens, color: c.color, label: c.name })
200  }
201  const free = snap ? Math.max(0, (snap.compactAt ?? snap.max) - snap.total) : 0
202  const buffer = snap?.compactAt && snap.max > snap.compactAt ? snap.max - snap.compactAt : 0
203  return { parts, free, buffer }
204}
205
206/**
207 * The activity chart's data: tool calls per turn, each turn's column sliced by tool.
208 * The busiest tools take shades of blue (one series, parts told apart), the rest one slate slice.
209 */
210export const activityChart = (a: Activity) => {
211  const allTools = Object.entries(a.tools).sort((x, y) => y[1].n - x[1].n)
212  const named = allTools.slice(0, RAMP.blue.length).map(([name], i) => ({ name, color: RAMP.blue[i]! }))
213  const OTHER = RAMP.slate[1]
214  const SLOTS = 16
215  const log = a.turnLog.slice(-SLOTS)
216  const first = a.turns - log.length + 1
217  const sliced = log.map(p => {
218    const by = p.tools ?? {}
219    const other = Object.entries(by).reduce((n, [name, c]) => n + (named.some(t => t.name === name) ? 0 : c), 0)
220    // Stacked bottom up, the busiest tool at the base; a turn without calls keeps a sliver.
221    const stack = [...named.map(t => ({ value: by[t.name] ?? 0, color: t.color })), { value: other, color: OTHER }].reverse()
222    return stack.some(x => x.value > 0) ? stack : [{ value: 0.05, color: TRACK }]
223  })
224  const peak = Math.max(0, ...log.map(p => p.calls ?? 0))
225  const otherCount = allTools.slice(named.length).reduce((n, [, t]) => n + t.n, 0)
226  const cacheIn = a.turnLog.reduce((n, p) => n + p.cacheRead, 0)
227  const allIn = a.turnLog.reduce((n, p) => n + p.cacheRead + p.cacheWrite + p.input, 0)
228  // Turn numbers under the first, middle and last bar.
229  const ticks = log.length ? [0, Math.floor((log.length - 1) / 2), log.length - 1].filter((v, i, xs) => xs.indexOf(v) === i) : []
230  return { named, OTHER, SLOTS, log, first, sliced, peak, otherCount, cacheIn, allIn, ticks }
231}
232
233export const renderDesktop = (els: AppElements, d: DesktopData, fx: Helpers): RenderElement => {
234  const { Box, Text } = els
235  const k = kit(els, 'desktop', d.columns, { flow: { on: d.columnsOn, toggle: d.toggleColumns } })
236  // A section's width: the pane's, or a flow column's when the pane is wide (at most six sections share it).
237  const lane = k.flowColumns(6).width
238  const a = d.activity
239  const snap = d.snap
240  const fold = (id: string) => ({ collapsed: d.collapsed.includes(id), onToggle: () => d.toggle(id) })
241
242  const toolCalls = Object.values(a.tools).reduce((n, t) => n + t.n, 0)
243  const running = d.agents.filter(x => x.status === 'running' || x.status === 'pending').length
244
245  // ---- context: the instrument's main meter ----
246  const { parts, free, buffer } = contextParts(snap)
247  // What's left, as two more shades of the same bar: the free room up to compaction,
248  // then the buffer past it (amber, as the compaction mark is), with their own legend entries.
249  const room = [...parts]
250  if (snap) {
251    if (free > 0) room.push({ value: free, color: FREE, label: 'Free' })
252    if (buffer > 0) room.push({ value: buffer, color: BUFFER, label: 'Buffer' })
253  }
254  const context = k.section({
255    id: 'context',
256    icon: GLYPH.context,
257    title: 'Context',
258    right: snap ? (
259      <Text>
260        <Text bold color={levelColor(snap.percent)}>{`${snap.percent}%`}</Text>
261        <Text color={GRAY.mid}>{` of ${tokens(snap.max)}`}</Text>
262      </Text>
263    ) : (
264      <Text color={GRAY.mid}>measuring…</Text>
265    ),
266    ...fold('context'),
267    children: snap
268      ? [
269          <Box key="meter" flexDirection="column">
270            {k.bar(room, snap.max, { height: 0.5 })}
271            {/* No compaction mark: the buffer's shade starts where it falls. */}
272            {k.scale()}
273            {k.axis(
274              'ctx-axis',
275              [0, 0.25, 0.5, 0.75, 1].map(f => ({ at: f, text: f === 0 ? '0' : tokens(snap.max * f) })),
276            )}
277          </Box>,
278          <Box key="legend" marginTop={SPACE.block} width="100%">
279            {k.legend(
280              'ctx',
281              room.map(p => ({ label: p.label, color: p.color, figure: tokens(p.value) })),
282              2,
283            )}
284          </Box>,
285        ]
286      : null,
287  })
288
289  // ---- limits ----
290  const windows = d.limits ?? []
291  const limits = windows.length
292    ? k.section({
293        id: 'limits',
294        icon: GLYPH.limits,
295        title: 'Limits',
296        ...fold('limits'),
297        children: windows.map(w =>
298          k.reading(`limit-${w.kind}`, {
299            label: fx.limitLabel(w.kind),
300            value: Math.min(100, Math.max(0, w.percent)),
301            max: 100,
302            color: levelColor(w.percent),
303            figure: `${Math.round(w.percent)}%`,
304            unit: w.resetsAt ? compact(fx.resetIn(w.resetsAt, d.at)) : undefined,
305          }),
306        ),
307      })
308    : null
309
310  // ---- activity: tool calls per turn, each bar sliced by tool ----
311  const { named, OTHER, SLOTS, log, first, sliced, peak, otherCount, cacheIn, allIn, ticks } = activityChart(a)
312  const activity =
313    log.length || toolCalls
314      ? k.section({
315          id: 'activity',
316          icon: GLYPH.tools,
317          title: 'Activity',
318          right: k.summary([[String(peak), 'peak'], [`${allIn ? Math.round((cacheIn / allIn) * 100) : 0}%`, 'cached']]),
319          ...fold('activity'),
320          children: [
321            <Box key="chart" flexDirection="column">
322              {k.columns(sliced, { slots: SLOTS, height: 3.5 })}
323              {k.axis(
324                'act-axis',
325                ticks.map(i => ({ at: (i + 0.5) / SLOTS, text: String(first + i).padStart(2, '0') })),
326              )}
327            </Box>,
328            <Box key="legend" marginTop={SPACE.block} width="100%">
329              {k.legend('act', [
330                ...named.map(t => ({ label: shortTool(t.name), color: t.color, figure: String(a.tools[t.name]!.n) })),
331                ...(otherCount ? [{ label: 'Other', color: OTHER, figure: String(otherCount) }] : []),
332              ])}
333            </Box>,
334          ],
335        })
336      : null
337
338  // ---- agents ----
339  const agents = d.agents.length
340    ? k.section({
341        id: 'agents',
342        icon: GLYPH.agents,
343        title: 'Agents',
344        right: k.summary([[String(d.agents.length), 'started'], running ? [String(running), 'running', C.blue] : null]),
345        ...fold('agents'),
346        // A tile per agent, one line, and a second while it runs:
347        //   [type icon, status colour] description     12k  3m
348        //   [tool icon] Editing kit/ui.tsx
349        // The type and status are the icon's tooltip.
350        children: fx.buildTree(d.agents).map(({ agent, depth }, i) => {
351          const x = d.extras[agent.id]
352          const ms = agent.status === 'running' && x?.startedAt !== undefined ? d.at - x.startedAt : x?.durationMs
353          const color = statusColor(agent.status)
354          const who = `${agent.type} · ${agent.status.toLowerCase()}`
355          const doing = agent.status === 'running' ? x?.doing : undefined
356          const row = (key: string, l: (RenderElement | null)[], r: (RenderElement | null)[]) => (
357            <Box key={key} flexDirection="row" justifyContent="space-between" gap={SPACE.item} width="100%">
358              <Box flexDirection="row" alignItems="center" gap={SPACE.pair} flexShrink={1} minWidth={0} overflow="hidden">
359                {l}
360              </Box>
361              <Box flexDirection="row" alignItems="center" gap={SPACE.item} flexShrink={0}>
362                {r}
363              </Box>
364            </Box>
365          )
366          return (
367            // Indented by padding, inside the full width, so a nested tile ends at the same right edge.
368            <Box key={`agent-${agent.id}`} width="100%" paddingLeft={depth * 2} marginTop={i === 0 ? 0 : SPACE.block}>
369              {k.tile(`tile-${agent.id}`, [
370                row(
371                  'l1',
372                  [
373                    <Box key="i" flexShrink={0}>
374                      {k.icon(agentMark(agent.type).icon, color, undefined, { tooltip: who })}
375                    </Box>,
376                    <Text key="d" wrap="truncate">{agent.description || agent.type}</Text>,
377                  ],
378                  [
379                    x?.tokens !== undefined ? <Text key="t" color={GRAY.mid}>{tokens(x.tokens)}</Text> : null,
380                    ms !== undefined ? <Text key="ms" color={GRAY.dark}>{short(ms)}</Text> : null,
381                  ],
382                ),
383                // What it's doing now, while it runs: the tool's icon, its name, then its argument dim.
384                doing
385                  ? row(
386                      'l2',
387                      [
388                        <Box key="i" flexShrink={0}>
389                          {k.icon(doingMark(doing).icon, MUTED)}
390                        </Box>,
391                        <Text key="t" wrap="truncate">
392                          {doing.text}
393                          {doing.arg ? <Text color={GRAY.mid}>{` ${doingArg(doing, lane - depth * 2 - 6)}`}</Text> : null}
394                        </Text>,
395                      ],
396                      [],
397                    )
398                  : null,
399              ])}
400            </Box>
401          )
402        }),
403      })
404    : null
405
406  // ---- accounting: what the session cost, and on what ----
407  const accounting = k.section({
408    id: 'accounting',
409    icon: GLYPH.cost,
410    title: 'Accounting',
411    right: k.summary([[a.cost !== undefined ? money(a.cost) : '–']]),
412    ...fold('accounting'),
413    children: [snap ? k.prop('model', 'Model', snap.model) : k.prop('model', 'Model', '–')],
414  })
415
416  return k.pinned(
417    // In columns when the pane is wide; one stack at a sidebar's width.
418    k.flow('sections', [context, limits, activity, agents, ...renderBranches(els, k, d, fold), accounting]),
419    k.perf(d.perf, { lead: machine(k, d.resources) }),
420    d.rows,
421  )
422}
423
424/**
425 * Workspaces: the branches the session started, as the desktop app tracks them,
426 * each in its own tile: the PR's state as an icon and a word, the PR's title on a
427 * line of its own, then its number, where it lives, changes, CI and the actions.
428 */
429const renderBranches = (els: AppElements, k: ReturnType<typeof kit>, d: DesktopData, fold: (id: string) => { collapsed: boolean; onToggle: () => void }): RenderElement[] => {
430  const { Box, Text, Link, Button } = els
431  const entries = d.branches.map((b, i) => {
432    const pr = b.pr
433    const open = pr?.state === 'OPEN'
434    const color = pr ? prColor(pr, b.conflicted > 0) : MUTED
435    const ci: [string, string] | null = b.conflicted
436      ? [`${b.conflicted} conflict${b.conflicted === 1 ? '' : 's'}`, C.bad]
437      : !pr || !open
438        ? null
439        : pr.conflicting
440          ? ['conflicts', C.bad]
441          : pr.checks.failed
442          ? [`${pr.checks.failed} failing`, C.warn]
443          : pr.checks.pending
444            ? [`${pr.checks.pending} pending`, C.blue]
445            : pr.checks.passed
446              ? ['passing', C.ok]
447              : null
448    const action =
449      !Button || !b.exists
450        ? null
451        : d.creating === b.branch
452          ? <Text color={GRAY.mid}>creating PR…</Text>
453          : !pr
454            ? <Button key={`create-${b.branch}`} plain label="Create PR" onPress={() => d.createPr(b.branch)} />
455            : open && !pr.isDraft
456              ? <Button key={`merge-${pr.number}`} plain label="Merge" onPress={() => d.mergePr(pr)} />
457              : null
458    // A tile per branch, three lines:
459    //   [pr icon] branch                    hide
460    //   A neater inspector, the PR's title, the full width
461    //   #9  awesome-claude      +412 −96  1 failing  Merge
462    // The PR's state is the icon's glyph and colour, no word; a deleted branch's name is struck through.
463    const iconKey = !pr ? GLYPH.branch : pr.state === 'MERGED' ? 'pr-merged' : pr.state === 'CLOSED' ? 'pr-closed' : pr.isDraft ? 'pr-draft' : 'pr-open'
464    const where = b.worktree ? `${b.place} (worktree)` : b.place
465    const row = (key: string, l: RenderElement | (RenderElement | null)[], r: (RenderElement | null)[]) => (
466      <Box key={key} flexDirection="row" justifyContent="space-between" gap={SPACE.item} width="100%">
467        <Box flexDirection="row" alignItems="center" gap={SPACE.pair} flexShrink={1} minWidth={0} overflow="hidden">
468          {l}
469        </Box>
470        <Box flexDirection="row" alignItems="center" gap={SPACE.item} flexShrink={0}>
471          {r}
472        </Box>
473      </Box>
474    )
475    return (
476      <Box key={`branch-${b.branch}`} width="100%" marginTop={i === 0 ? 0 : SPACE.block}>
477        {k.tile(`tile-${b.branch}`, [
478          row(
479            'l1',
480            [
481              k.icon(iconKey, color),
482              <Text key="b" wrap="truncate" strikethrough={!b.exists} dimColor={!b.exists}>
483                {b.branch}
484              </Text>,
485            ],
486            [
487              Button ? (
488                // dimColor, not a grey child Text: the desktop draws a Button's label alone.
489                <Button key={`hide-${b.branch}`} plain dimColor label="hide" onPress={() => d.hideBranch(b.branch)} />
490              ) : null,
491            ],
492          ),
493          pr ? (
494            <Text key="title" wrap="truncate">
495              {pr.title}
496            </Text>
497          ) : null,
498          row(
499            'l3',
500            [
501              // The PR's number reads as a link by its blue alone, no underline.
502              pr ? (
503                <Link key="n" href={pr.url} label={`#${pr.number}`}>
504                  <Text color={C.blue}>{`#${pr.number}`}</Text>
505                </Link>
506              ) : null,
507              <Text key="p" color={GRAY.mid} wrap="truncate">
508                {where}
509              </Text>,
510            ],
511            [
512              b.insertions || b.deletions ? (
513                // Lines added green, removed red, as a diff colours them.
514                <Text key="d">
515                  <Text color={C.ok}>{`+${b.insertions}`}</Text>
516                  <Text color={C.bad}>{` −${b.deletions}`}</Text>
517                </Text>
518              ) : null,
519              ci ? <Text key="ci" color={ci[1]}>{ci[0]}</Text> : null,
520              action,
521            ],
522          ),
523        ])}
524      </Box>
525    )
526  })
527  if (!entries.length) return []
528  const merged = d.branches.filter(b => b.pr?.state === 'MERGED').length
529  const openPrs = d.branches.filter(b => b.pr?.state === 'OPEN').length
530  return [
531    k.section({
532      id: 'workspaces',
533      icon: GLYPH.branch,
534      title: 'Workspaces',
535      right: k.summary([openPrs ? [String(openPrs), 'open', C.blue] : null, merged ? [String(merged), 'merged', C.purple] : null]),
536      ...fold('workspaces'),
537      children: entries,
538    }),
539  ]
540}
541
hooks/terminal.tsx 449 lines
1import type { Elements, RenderElement } from 'claude-code'
2
3import { ago, basename, money, short, tokens } from '@kit/format'
4import { C, GLYPH, MUTED, TRACK, TREE, levelColor } from '@kit/tokens'
5import type { StatusKind } from '@kit/tokens'
6import { MEASURE, kit } from '@kit/ui'
7import type { Kit } from '@kit/ui'
8
9import type { Agent, BranchView, GitFile, GitInfo, GitPr, TreeRow } from '../types'
10import { activityChart, agentMark, compact, contextParts, doingArg, doingMark, machine, prColor, shortTool, statusColor } from './desktop'
11import type { DesktopData } from './desktop'
12
13/*
14 * The terminal mode: the same instrument inspector as the desktop, in cells.
15 * Same sections in the same order (Context, Limits, Activity, Agents,
16 * Workspaces, Accounting), plus the session's own checkout and its pull
17 * requests (Git), which the terminal has always shown. Every row is drawn
18 * with the kit's terminal primitives, sized from the pane's `bodyColumns`.
19 */
20
21/** The elements the terminal draws with. */
22export type TermElements = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
23
24/** What the terminal mode borrows from register.tsx, passed in so this file has no cycle back. */
25export type TermHelpers = {
26  limitLabel: (kind: string) => string
27  resetIn: (resetsAt: string | undefined, at: number) => string
28  fitTree: (list: Agent[], budget: number) => { rows: TreeRow[]; hidden: number }
29  subSummary: (row: TreeRow) => string
30}
31
32/** The most agent rows drawn; finished subtrees fold first, then the rest is counted. */
33const AGENT_ROWS = 12
34/** The most pull requests the Git section lists. */
35const GIT_PRS = 3
36
37
38/** A PR's icon key: its state, as GitHub draws it. */
39const prIcon = (pr: GitPr) => (pr.state === 'MERGED' ? 'pr-merged' : pr.state === 'CLOSED' ? 'pr-closed' : pr.isDraft ? 'pr-draft' : 'pr-open')
40
41/** A PR's checks as one status and word, or null when there's nothing to say. */
42const prChecks = (pr: GitPr, conflicted = 0): [StatusKind, string] | null => {
43  if (pr.state === 'MERGED') return ['merged', 'merged']
44  if (pr.state === 'CLOSED') return ['stopped', 'closed']
45  if (conflicted) return ['failed', `${conflicted} conflict${conflicted === 1 ? '' : 's'}`]
46  if (pr.conflicting) return ['failed', 'conflicts']
47  if (pr.checks.failed) return ['failed', `${pr.checks.failed} failing`]
48  if (pr.checks.pending) return ['pending', `${pr.checks.pending} pending`]
49  if (pr.checks.passed) return ['done', 'passing']
50  return null
51}
52
53/** A changed file's colour: conflicts and deletions red, additions and staged green, edits amber, untracked grey. */
54const fileColor = (f: GitFile) =>
55  f.kind === 'conflict' || f.kind === 'deleted' ? C.bad : f.kind === 'added' || f.staged ? C.ok : f.kind === 'untracked' ? MUTED : C.warn
56
57/** The folder a path sits in, or '' at the top. */
58const dirOf = (path: string) => path.split(/[\\/]/).slice(0, -1).join('/')
59
60/** How old last-good figures are, for a header's stale state: 40s, 5m, 3h; nothing when unknown. */
61const since = (at: number | undefined, now: number) => {
62  if (!at) return undefined
63  const ms = Math.max(0, now - at)
64  return ms < 60_000 ? `${Math.floor(ms / 1_000)}s` : ago(ms)
65}
66
67/** Tokens a turn added: its input, output and cache writes (cache reads restate the context, which Context shows). */
68const turnTokens = (p: { input: number; output: number; cacheWrite: number }) => p.input + p.output + p.cacheWrite
69
70export const renderTerminal = (els: TermElements, d: DesktopData, fx: TermHelpers): RenderElement => {
71  const { Box, Text } = els
72  // A dashboard of readings: drawn to the kit's measure, so a wide pane doesn't spread them apart.
73  const k = kit(els, 'terminal', d.columns, { focused: d.focused, measure: MEASURE })
74  const a = d.activity
75  const snap = d.snap
76  const fold = (id: string) => ({ collapsed: d.collapsed.includes(id), onToggle: () => d.toggle(id) })
77  const running = d.agents.filter(x => x.status === 'running' || x.status === 'pending').length
78
79  // ---- context: one row: the used groups as the heavy line, then the free room and the
80  // buffer past the compaction point as the light rail (dim, then amber); the legend under it ----
81  const { parts, free, buffer } = contextParts(snap)
82  const room = [
83    ...(free > 0 ? [{ value: free, color: TRACK, label: 'Free', room: true }] : []),
84    ...(buffer > 0 ? [{ value: buffer, color: C.warn, label: 'Buffer', room: true }] : []),
85  ]
86  const context = k.section({
87    id: 'context',
88    icon: GLYPH.context,
89    title: 'Context',
90    right: snap ? k.summary([[`${snap.percent}%`, `of ${tokens(snap.max)}`, levelColor(snap.percent)]]) : undefined,
91    loading: !snap,
92    ...fold('context'),
93    children: snap
94      ? [
95          <Box key="meter">{k.bar([...parts, ...room], snap.max)}</Box>,
96          // Keyed with the bar's own glyphs: ━ for what's used, ─ for the room.
97          k.legend(
98            'ctx',
99            [...parts, ...room].map(p => ({ label: p.label, color: p.color, figure: tokens(p.value), room: 'room' in p })),
100            undefined,
101            { bar: true },
102          ),
103        ]
104      : [k.note('ctx-reading', 'Reading context…', 'loading')],
105  })
106
107  // ---- limits ----
108  const windows = d.limits ?? []
109  // The header names the fullest window, so a folded section (or the narrow floor, which draws headers only) still says it.
110  const fullest = windows.reduce<(typeof windows)[number] | null>((m, w) => (!m || w.percent > m.percent ? w : m), null)
111  const limits = windows.length
112    ? k.section({
113        id: 'limits',
114        icon: GLYPH.limits,
115        title: 'Limits',
116        right: fullest ? k.summary([[`${Math.round(fullest.percent)}%`, fx.limitLabel(fullest.kind).toLowerCase(), levelColor(fullest.percent)]]) : undefined,
117        // The readings say it while the section is open.
118        restated: true,
119        ...fold('limits'),
120        children: windows.map(w =>
121          k.reading(`limit-${w.kind}`, {
122            label: fx.limitLabel(w.kind),
123            value: Math.min(100, Math.max(0, w.percent)),
124            max: 100,
125            color: levelColor(w.percent),
126            figure: `${Math.round(w.percent)}%`,
127            unit: w.resetsAt ? compact(fx.resetIn(w.resetsAt, d.at)) : undefined,
128          }),
129        ),
130      })
131    : null
132
133  // ---- activity: tool calls per turn ----
134  const chart = activityChart(a)
135  const toolCalls = Object.values(a.tools).reduce((n, t) => n + t.n, 0)
136  // The chart's own width (whole cells per slot), so the turn numbers sit under their columns.
137  const chartWidth = Math.max(1, Math.floor(k.width / chart.SLOTS)) * chart.SLOTS
138  const activity =
139    chart.log.length || toolCalls
140      ? k.section({
141          id: 'activity',
142          icon: GLYPH.tools,
143          title: 'Activity',
144          right: k.summary([
145            [String(chart.peak), 'peak'],
146            // Narrow, the cache share goes first: the header would be cut.
147            k.width >= 50 ? [`${chart.allIn ? Math.round((chart.cacheIn / chart.allIn) * 100) : 0}%`, 'cached'] : null,
148          ]),
149          ...fold('activity'),
150          children: [
151            <Box key="chart" flexDirection="column">
152              {k.columns(chart.sliced, { slots: chart.SLOTS, height: 3 })}
153              {k.axis(
154                'act-axis',
155                chart.ticks.map(i => ({ at: (i + 0.5) / chart.SLOTS, text: String(chart.first + i).padStart(2, '0') })),
156                chartWidth,
157              )}
158            </Box>,
159            // A chart taller than a row is its own block: its legend after one blank row.
160            <Box key="legend" marginTop={k.space.block}>
161              {k.legend('act', [
162                ...chart.named.map(t => ({ label: shortTool(t.name), color: t.color, figure: String(a.tools[t.name]!.n) })),
163                ...(chart.otherCount ? [{ label: 'Other', color: chart.OTHER, figure: String(chart.otherCount) }] : []),
164              ])}
165            </Box>,
166          ],
167        })
168      : null
169
170  // ---- agents: a tree, each row its status, description, type, tokens and time ----
171  const { rows: tree, hidden } = fx.fitTree(d.agents, AGENT_ROWS)
172  const agents = d.agents.length
173    ? k.section({
174        id: 'agents',
175        icon: GLYPH.agents,
176        title: 'Agents',
177        right: k.summary([[String(d.agents.length), 'started'], running ? [String(running), 'running', C.blue] : null]),
178        ...fold('agents'),
179        children: [
180          ...tree.flatMap(row => {
181            const { agent } = row
182            const x = d.extras[agent.id]
183            const ms = agent.status === 'running' && x?.startedAt !== undefined ? d.at - x.startedAt : x?.durationMs
184            const sub = fx.subSummary(row)
185            // While it runs, a line under it with its latest tool call, under its text: the tool's
186            // glyph dim, its name, its argument dim. The tree's guides carry on through it, and a
187            // pipe under the mark when its children follow.
188            const doing =
189              agent.status === 'running' && x?.doing
190                ? (() => {
191                    const d0 = x.doing
192                    const guides = row.depth ? row.guides.map(g => (g ? TREE.pipe : TREE.blank)).join('') + (row.last ? TREE.blank : TREE.pipe) : ''
193                    const prefix = guides + (row.descendants > 0 && !row.folded ? TREE.pipe : TREE.blank)
194                    // The row less its tree, the glyph's two cells and the note's two-cell gap.
195                    const note = doingArg(d0, k.width - [...prefix].length - 4)
196                    return k.item(`doing-${agent.id}`, { tree: prefix, lead: doingMark(d0).glyph, text: d0.text, note })
197                  })()
198                : null
199            // Its kind of agent as a glyph, coloured by its status.
200            const line = k.item(`agent-${agent.id}`, {
201              tree: row.depth ? k.tree(row.guides, row.last, row.depth) : undefined,
202              lead: agentMark(agent.type).glyph,
203              leadColor: statusColor(agent.status),
204              text: agent.description || agent.type,
205              note: [agent.description ? agent.type : '', sub].filter(Boolean).join(' · '),
206              // Narrow, the tokens go before the time.
207              right: [
208                x?.tokens !== undefined ? { part: tokens(x.tokens), drop: 2 } : null,
209                ms !== undefined ? { part: short(ms), drop: 1 } : null,
210              ],
211            })
212            return doing ? [line, doing] : [line]
213          }),
214          hidden > 0 ? k.note('agents-more', `… ${hidden} more`) : null,
215        ],
216      })
217    : null
218
219  // ---- accounting: the cost, the model, and the tokens each turn added as a sparkline ----
220  // A spark rather than columns: one series over time with no parts to stack, and Braille's two
221  // points a cell fit the whole turn log (40) in 20 cells, where columns show one turn a cell.
222  const perTurn = a.turnLog.map(turnTokens)
223  const SPARK_MIN = 4
224  const accounting = k.section({
225    id: 'accounting',
226    icon: GLYPH.cost,
227    title: 'Accounting',
228    right: k.summary([[a.cost !== undefined ? money(a.cost) : '–']]),
229    ...fold('accounting'),
230    children: [
231      k.prop('model', 'Model', snap ? snap.model : '–'),
232      // The last turn's figure, then the spark on the same row, scaled to the log's peak; with
233      // fewer than SPARK_MIN turns there's no shape to read, so the figure stands alone.
234      perTurn.length
235        ? k.prop(
236            'turn-tokens',
237            'Tokens',
238            perTurn.length < SPARK_MIN ? (
239              `${tokens(perTurn.at(-1)!)} last turn`
240            ) : (
241              <Box flexDirection="row" gap={k.space.group}>
242                <Text wrap="truncate">{`${tokens(perTurn.at(-1)!)} last turn`}</Text>
243                {k.spark(perTurn, { height: 1, width: Math.min(20, Math.ceil(perTurn.length / 2)) })}
244              </Box>
245            ),
246          )
247        : null,
248    ],
249  })
250
251  return k.pinned(
252    [context, limits, activity, agents, ...workspaces(els, k, d, fold), gitSection(els, k, d, fold), accounting],
253    k.perf(d.perf, { lead: machine(k, d.resources) }),
254    d.rows,
255  )
256}
257
258type Fold = (id: string) => { collapsed: boolean; onToggle: () => void }
259
260/**
261 * Workspaces: the branches the session started, two rows each: the PR's state as
262 * its icon, the branch and its actions; then the PR's number and title, the
263 * lines changed and CI.
264 */
265const workspaces = (els: TermElements, k: Kit, d: DesktopData, fold: Fold): RenderElement[] => {
266  const { Box, Text } = els
267  if (!d.branches.length) return []
268  const entries = d.branches.map((b: BranchView, i) => {
269    const pr = b.pr
270    const open = pr?.state === 'OPEN'
271    // A merged or closed PR's state is its icon (and the header's count): no word for it again.
272    const ci = pr ? (open ? prChecks(pr, b.conflicted) : null) : b.conflicted ? (['failed', `${b.conflicted} conflicts`] as [StatusKind, string]) : null
273    const main =
274      !b.exists
275        ? null
276        : d.creating === b.branch
277          ? null
278          : !pr
279            ? { key: `create-${b.branch}`, label: 'Create PR', onPress: () => d.createPr(b.branch) }
280            : open && !pr.isDraft
281              ? { key: `merge-${pr.number}`, label: 'Merge', onPress: () => d.mergePr(pr) }
282              : null
283    const where = b.worktree ? `${b.place} (worktree)` : b.place
284    return (
285      <Box key={`branch-${b.branch}`} flexDirection="column" marginTop={i === 0 ? 0 : k.space.block}>
286        {k.item(`branch-${b.branch}-head`, {
287          lead: pr ? prIcon(pr) : GLYPH.branch,
288          leadColor: pr ? prColor(pr, b.conflicted > 0) : MUTED,
289          text: b.branch,
290          note: pr ? `#${pr.number}` : undefined,
291          dim: !b.exists,
292          // The actions sit beside the branch they act on, not alone on the far edge.
293          after: k.actions(`branch-${b.branch}-actions`, [main, { key: `hide-${b.branch}`, label: 'hide', quiet: true, onPress: () => d.hideBranch(b.branch) }]),
294          right: [d.creating === b.branch ? { part: 'creating PR…', drop: 1 } : null],
295        })}
296        {k.item(`branch-${b.branch}-pr`, {
297          indent: k.edge.left,
298          text: pr ? pr.title : where,
299          dim: !pr,
300          // Narrow, the lines changed go before CI.
301          right: [
302            b.insertions || b.deletions
303              ? {
304                  part: (
305                    <Text key="diff">
306                      <Text {...k.ink(C.ok)}>{`+${b.insertions}`}</Text>
307                      <Text {...k.ink(C.bad)}>{` −${b.deletions}`}</Text>
308                    </Text>
309                  ),
310                  drop: 1,
311                }
312              : null,
313            ci ? k.status(ci[0], ci[1], 'ci') : null,
314          ],
315        })}
316      </Box>
317    )
318  })
319  const merged = d.branches.filter(b => b.pr?.state === 'MERGED').length
320  const openPrs = d.branches.filter(b => b.pr?.state === 'OPEN').length
321  return [
322    k.section({
323      id: 'workspaces',
324      icon: GLYPH.branch,
325      title: 'Workspaces',
326      // A failed gh read keeps the last PRs: the header says so, and how old they are.
327      right: k.summary([openPrs ? [String(openPrs), 'open', C.blue] : null, merged ? [String(merged), 'merged', C.purple] : null], {
328        failed: Boolean(d.workspacesGh?.failed),
329        age: d.workspacesGh?.failed ? since(d.workspacesGh.at, d.at) : undefined,
330      }),
331      ...fold('workspaces'),
332      children: entries,
333    }),
334  ]
335}
336
337/**
338 * Git: the session's own checkout (branch, upstream, worktree, what changed) and
339 * the open pull requests it has, each a list row with its status.
340 */
341const gitSection = (els: TermElements, k: Kit, d: DesktopData, fold: Fold): RenderElement => {
342  const { Box, Text } = els
343  const repo = d.git
344  const hub = d.gh
345  const head = (right: RenderElement | null, children: (RenderElement | null)[], loading = false) =>
346    k.section({ id: 'git', icon: GLYPH.branch, title: 'Git', right: right ?? undefined, loading, ...fold('git'), children })
347  if (repo === null) return head(null, [k.note('git-reading', 'Reading git…', 'loading')], true)
348  if (!repo.ok) return head(null, [k.note('git-note', repo.note)])
349  const g: GitInfo = repo
350  // A failed git or gh read keeps the last-good figures: the header says so, with the older one's age.
351  const ghHere = hub && hub.root === g.root ? hub : null
352  const failed = Boolean(g.failed || ghHere?.failed)
353  const failedAt = [g.failed ? g.at : undefined, ghHere?.failed ? ghHere.at : undefined].filter((x): x is number => Boolean(x))
354  const state = failed ? { failed, age: failedAt.length ? since(Math.min(...failedAt), d.at) : undefined } : {}
355
356  // The branch row: where the checkout is against its upstream.
357  const sync: (RenderElement | string | null)[] = g.detached
358    ? [k.status('warn', 'detached', 'sync')]
359    : !g.upstream
360      ? ['no upstream']
361      : g.ahead || g.behind
362        ? [
363            g.ahead ? <Text key="ahead">{`${GLYPH.up}${g.ahead}`}</Text> : null,
364            g.behind ? <Text key="behind" {...k.ink(C.warn)}>{`${GLYPH.down}${g.behind}`}</Text> : null,
365          ]
366        : [k.status('done', 'synced', 'sync')]
367
368  const changes =
369    g.conflicted || g.staged || g.modified || g.untracked || g.insertions || g.deletions
370      ? k.summary([
371          g.conflicted ? [String(g.conflicted), 'conflicted', C.bad] : null,
372          g.staged ? [String(g.staged), 'staged', C.ok] : null,
373          g.modified ? [String(g.modified), 'modified', C.warn] : null,
374          g.untracked ? [String(g.untracked), 'untracked'] : null,
375          g.insertions ? [`+${g.insertions}`, undefined, C.ok] : null,
376          g.deletions ? [`−${g.deletions}`, undefined, C.bad] : null,
377        ])
378      : k.status('done', 'working tree clean', 'clean')
379
380  const files = g.files.map(f =>
381    k.item(`file-${f.path}`, {
382      lead: 'file',
383      leadColor: fileColor(f),
384      text: basename(f.path),
385      note: dirOf(f.path) || undefined,
386      right: [f.kind === 'conflict' ? 'conflict' : f.kind],
387    }),
388  )
389
390  // ---- pull requests ----
391  const prs: (RenderElement | null)[] = []
392  if (hub === null || hub.root !== g.root) prs.push(k.note('prs-reading', 'Reading pull requests…', 'loading'))
393  else if (hub.note) prs.push(k.note('prs-note', hub.note))
394  else if (hub.prs.length === 0) prs.push(k.note('prs-none', 'No open pull requests'))
395  else {
396    // A PR Workspaces already lists isn't listed again here.
397    const listed = new Set(d.branches.map(b => b.pr?.number).filter((n): n is number => n !== undefined))
398    const rest = hub.prs.filter(pr => !listed.has(pr.number))
399    for (const pr of rest.slice(0, GIT_PRS)) {
400      const ci = prChecks(pr)
401      prs.push(
402        k.item(`pr-${pr.number}`, {
403          lead: prIcon(pr),
404          leadColor: prColor(pr, false),
405          text: pr.title,
406          bold: pr.current,
407          // Narrow, the number goes before CI: the title already says which PR it is.
408          right: [{ part: `#${pr.number}`, drop: 1 }, ci ? k.status(ci[0], ci[1], 'ci') : null],
409        }),
410      )
411      // What else the PR is waiting on, dim, under its title: the failing checks, the review, whether it's this branch's.
412      const more = [
413        pr.state === 'OPEN' && pr.failing.length ? pr.failing.slice(0, 3).join(', ') : '',
414        pr.state === 'OPEN' && pr.isDraft ? 'draft' : '',
415        pr.state === 'OPEN' && pr.review === 'APPROVED' ? 'approved' : '',
416        pr.state === 'OPEN' && pr.review === 'CHANGES_REQUESTED' ? 'changes requested' : '',
417        pr.state === 'OPEN' && pr.review === 'REVIEW_REQUIRED' ? 'review required' : '',
418        pr.current ? 'this branch' : '',
419      ].filter(Boolean)
420      if (more.length) {
421        prs.push(
422          <Box key={`pr-${pr.number}-more`} paddingLeft={k.edge.left} minWidth={0}>
423            <Text dimColor wrap="truncate">
424              {more.join(' · ')}
425            </Text>
426          </Box>,
427        )
428      }
429    }
430    if (rest.length > GIT_PRS) prs.push(k.note('prs-more', `… ${rest.length - GIT_PRS} more`))
431  }
432
433  return head(k.summary([[g.repo]], state), [
434    k.item('git-branch', { lead: GLYPH.branch, text: g.branch, right: sync }),
435    k.prop(
436      'git-worktree',
437      g.worktree.linked ? 'Worktree' : 'Checkout',
438      g.worktree.linked ? `${g.worktree.name}, linked (${g.worktree.count} total)` : g.worktree.count > 1 ? `main (+${g.worktree.count - 1} worktrees)` : 'main',
439    ),
440    <Box key="git-changes" minWidth={0}>
441      {changes}
442    </Box>,
443    ...files,
444    g.fileCount > g.files.length ? k.note('git-files-more', `… ${g.fileCount - g.files.length} more`) : null,
445    prs.length ? <Box key="git-gap" height={k.space.block} /> : null,
446    ...prs,
447  ])
448}
449
hooks/resources.ts 130 lines
1import type { Resources } from '../types'
2
3/*
4 * The session's share of the machine, from one cheap shell command (ps, sysctl,
5 * ioreg, netstat; a few milliseconds): the session's Claude Code process (the
6 * nearest ancestor named `claude`), its whole process tree's CPU and memory,
7 * and the system's CPU, memory, disk and network. The tree's own network comes
8 * from `nettop`, which always takes 5 s (but almost no CPU), on its own. Rates
9 * are deltas between samples. macOS only. register.tsx runs the commands; this
10 * file parses.
11 */
12
13/**
14 * The sample command. Measured CPU per run: ps 0.02 s (0.04 s with names, so
15 * names only on the first run, to find the session's process), iostat, netstat
16 * and sysctl a few ms each.
17 */
18export const resourcesSh = () => [
19  'sh',
20  '-c',
21  `echo $PPID; ps -A -o pid=,ppid=,%cpu=,rss=${root === null ? ',comm=' : ''}; echo @; sysctl -n hw.ncpu hw.memsize; echo @; ` +
22    'iostat -Id -c 1; echo @; netstat -ib',
23]
24
25/** The session's Claude Code process, found once. */
26let root: number | null = null
27
28/** The tree's network, one nettop sample: per process, bytes in and out so far. */
29export const NETTOP = ['nettop', '-P', '-L', '1', '-x', '-J', 'bytes_in,bytes_out']
30
31/** Whether to read the tree's own network with nettop (about 0.015 s of CPU a run). */
32export const NET_PER_PROCESS = true
33
34type Counters = { pids: number[]; cores: number; cpu: number; cpuAll: number; mem: number; memAll: number; diskAll: number; netAll: number }
35
36const parse = (out: string): Counters => {
37  const [head = '', sys = '', io = '', nets = ''] = out.split('\n@\n')
38  const lines = head.split('\n')
39  const self = Number(lines[0])
40  const rows = new Map<number, { ppid: number; cpu: number; rss: number; name: string }>()
41  for (const line of lines.slice(1)) {
42    const m = /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s*(.*)$/.exec(line)
43    if (m) rows.set(Number(m[1]), { ppid: Number(m[2]), cpu: Number(m[3]), rss: Number(m[4]), name: m[5]!.split('/').pop()! })
44  }
45  // The session's process: the nearest ancestor named `claude`, else the shell's parent.
46  if (root === null || !rows.has(root)) {
47    root = self
48    for (let pid = self; rows.has(pid); pid = rows.get(pid)!.ppid) {
49      if (rows.get(pid)!.name === 'claude') {
50        root = pid
51        break
52      }
53    }
54  }
55  const kids = new Map<number, number[]>()
56  for (const [pid, r] of rows) kids.set(r.ppid, [...(kids.get(r.ppid) ?? []), pid])
57  const pids: number[] = []
58  const todo = [root!]
59  while (todo.length) {
60    const pid = todo.pop()!
61    pids.push(pid)
62    todo.push(...(kids.get(pid) ?? []))
63  }
64  const [cores = 1, memAll = 0] = sys.trim().split('\n').map(Number)
65  let netAll = 0
66  const seen = new Set<string>()
67  for (const line of nets.split('\n').slice(1)) {
68    const p = line.trim().split(/\s+/)
69    if (p.length >= 10 && p[2]!.startsWith('<Link') && !p[0]!.startsWith('lo') && !seen.has(p[0]!)) {
70      seen.add(p[0]!)
71      netAll += Number(p[6]) + Number(p[9])
72    }
73  }
74  const sum = (f: (r: { cpu: number; rss: number }) => number, ids: Iterable<number>) => [...ids].reduce((n, id) => n + (rows.has(id) ? f(rows.get(id)!) : 0), 0)
75  return {
76    pids,
77    cores,
78    cpu: sum(r => r.cpu, pids),
79    cpuAll: sum(r => r.cpu, rows.keys()),
80    mem: sum(r => r.rss, pids) * 1024,
81    memAll,
82    // iostat -I: per disk, KB/t, transfers and MB so far; the MB is every third figure.
83    diskAll: (io.trim().split('\n').pop() ?? '')
84      .trim()
85      .split(/\s+/)
86      .filter((_, i) => i % 3 === 2)
87      .reduce((n, mb) => n + Number(mb) * 1024 * 1024, 0),
88    netAll,
89  }
90}
91
92let prev: { at: number; c: Counters } | null = null
93let netPrev: { at: number; bytes: number } | null = null
94let net: number | null = null
95let treePids: number[] = []
96
97/** Turns one sample into a Resources; null on the first. */
98export const toResources = (stdout: string, at: number): Resources | null => {
99  const c = parse(stdout)
100  treePids = c.pids
101  const before = prev
102  prev = { at, c }
103  if (!before) return null
104  const secs = Math.max(0.5, (at - before.at) / 1000)
105  const rate = (a: number, b: number) => Math.max(0, (a - b) / secs)
106  const allCores = c.cores * 100
107  return {
108    procs: c.pids.length,
109    cpu: (c.cpu / allCores) * 100,
110    cpuAll: Math.min(100, (c.cpuAll / allCores) * 100),
111    mem: c.mem,
112    memAll: c.memAll,
113    diskAll: rate(c.diskAll, before.c.diskAll),
114    net,
115    netAll: rate(c.netAll, before.c.netAll),
116  }
117}
118
119/** Folds one nettop sample into the tree's network rate. */
120export const takeNettop = (stdout: string, at: number) => {
121  const mine = new Set(treePids)
122  let bytes = 0
123  for (const line of stdout.split('\n')) {
124    const m = /\.(\d+),(\d+),(\d+),?$/.exec(line)
125    if (m && mine.has(Number(m[1]))) bytes += Number(m[2]) + Number(m[3])
126  }
127  if (netPrev) net = Math.max(0, (bytes - netPrev.bytes) / Math.max(0.5, (at - netPrev.at) / 1000))
128  netPrev = { at, bytes }
129}
130
types/index.d.ts 289 lines
1/** One category of the window, as /context lists it; `kind` as the engine stamps it. */
2export type Segment = { name: string; tokens: number; kind: 'used' | 'free' | 'buffer' | 'deferred' }
3
4/** One line item under a category (a memory file, an MCP server, a skill, an agent). */
5export type Item = { label: string; tokens: number }
6
7/** The breakdown, slimmed to what the band draws. */
8export type Snapshot = {
9  model: string
10  total: number
11  max: number
12  percent: number
13  compactAt?: number
14  segments: Segment[]
15  memory: Item[]
16  mcp: Item[]
17  skills: Item[]
18  agents: Item[]
19}
20
21/** One subagent as `$.agent.list()` gives it, kept as plain data. */
22export type Agent = {
23  id: string
24  description: string
25  /** The agent definition (`general-purpose`, `Explore`, ...). */
26  type: string
27  /** `running`, `completed`, `failed`, `killed`, or another engine task status. */
28  status: string
29  /** The subagent that spawned it; absent when the main loop did. */
30  parentId?: string
31}
32
33/** What the spawn and turn hooks saw of an agent beyond the list. */
34export type AgentExtra = {
35  /** When `agent.spawn` started it (ms since epoch). */
36  startedAt?: number
37  /** Summed `durationMs` of its finished turns. */
38  durationMs?: number
39  /** Summed tokens of its finished turns (input, output and cache). */
40  tokens?: number
41  /** `agent.spawn`'s `parentAgentId`: the loop that spawned it, for when the list leaves `parentId` out. */
42  parentId?: string
43  /** Its latest tool call, from its loop's `tool.call`: what it's doing now (drawn while it runs). */
44  doing?: Doing
45}
46
47/** The kind of tool a call is, for its icon (desktop) or glyph (terminal). */
48export type DoingKind = 'bash' | 'edit' | 'read' | 'search' | 'web' | 'agent' | 'mcp' | 'other'
49
50/** An agent's latest tool call: its kind, a name or verb (`Bash`, `Editing`) and its argument (`bun build.ts`, `kit/ui.tsx`). */
51export type Doing = {
52  kind: DoingKind
53  /** The tool's name or verb, drawn at normal weight. */
54  text: string
55  /** Its command, path, URL or pattern, drawn dim and cut in the middle where the line is too long. */
56  arg?: string
57}
58
59/** One drawn row of the Tasks tree. */
60export type TreeRow = {
61  agent: Agent
62  depth: number
63  /** Last among its siblings: drawn with `└─` rather than `├─`. */
64  last: boolean
65  /** Per ancestor level 1..depth-1, whether that ancestor has later siblings (draw a `│` guide). */
66  guides: boolean[]
67  /** All its descendants, folded ones included. */
68  descendants: number
69  /** Of those, the ones still running or pending. */
70  running: number
71  /** Its finished subtree is folded into this row. */
72  folded: boolean
73}
74
75/** One changed path from `git status --porcelain=v2`. */
76export type GitFile = {
77  path: string
78  kind: 'conflict' | 'untracked' | 'added' | 'deleted' | 'renamed' | 'modified'
79  /** Only the index has the change (nothing left unstaged). */
80  staged: boolean
81}
82
83/** The session's repo as the git section draws it. */
84export type GitInfo = {
85  ok: true
86  /** `git rev-parse --show-toplevel` of the session cwd. */
87  root: string
88  repo: string
89  /** Branch name, or the short commit when detached. */
90  branch: string
91  detached: boolean
92  upstream?: string
93  ahead: number
94  behind: number
95  worktree: { name: string; path: string; linked: boolean; count: number }
96  staged: number
97  modified: number
98  untracked: number
99  conflicted: number
100  insertions: number
101  deletions: number
102  /** The first few changed paths. */
103  files: GitFile[]
104  /** Changed paths in all, beyond `files` too. */
105  fileCount: number
106  /**
107   * Set when the last read failed and these are the last-good figures kept
108   * through it: why it failed. Absent after a good read.
109   */
110  failed?: string
111  /** With `failed`: when the figures were last read good (ms since epoch). */
112  at?: number
113}
114
115/** Why there is no git section: not a repo, git missing. */
116export type GitNote = { ok: false; note: string }
117
118/** One pull request for the git section. */
119export type GitPr = {
120  number: number
121  title: string
122  url: string
123  /** `OPEN`, `MERGED` or `CLOSED`. */
124  state: string
125  isDraft: boolean
126  /** `APPROVED`, `CHANGES_REQUESTED`, `REVIEW_REQUIRED` or empty. */
127  review: string
128  checks: { passed: number; failed: number; pending: number }
129  /** Names of the failing checks. */
130  failing: string[]
131  /** The PR's head is the current branch. */
132  current: boolean
133  /** GitHub can't merge it for conflicts with its base (`mergeable` is `CONFLICTING`). */
134  conflicting?: boolean
135}
136
137/** The cached `gh` result, refreshed on a slower timer. */
138export type GhInfo = {
139  /** The repo root it was fetched for. */
140  root: string
141  prs: GitPr[]
142  /** Why there are no PRs to show: gh missing, unauthenticated, no remote. */
143  note?: string
144  /**
145   * Set when the last read failed and `prs` are the last-good ones kept through
146   * it: why it failed. Absent after a good read.
147   */
148  failed?: string
149  /** When `prs` were read (ms since epoch); with `failed`, when they were last read good. */
150  at: number
151}
152
153/** The workspaces' shared `gh pr list` read: whether the last one failed, and when the PRs were last read good. */
154export type WorkspacesGh = { failed?: string; at: number }
155
156/** One account rate-limit window as the API last reported it. */
157export type Limit = {
158  /** `five_hour`, `seven_day`, a gateway's `spend_limit`, or another window the API names. */
159  kind: string
160  /** 0 to 100; past 100 on an exceeded spend limit. */
161  percent: number
162  /** ISO 8601 time the window resets. */
163  resetsAt?: string
164}
165
166/** One tool's calls this session, and how many of them errored. */
167export type ToolCount = { n: number; err: number }
168
169/** One main-loop turn: how long it took and its tokens. */
170/** One main-loop turn: its time, its tokens, and the tool calls made during it (absent on older points). */
171export type TurnPoint = {
172  ms: number
173  input: number
174  output: number
175  cacheRead: number
176  cacheWrite: number
177  calls?: number
178  /** The turn's tool calls by tool name (absent on older points). */
179  tools?: Record<string, number>
180}
181
182/** What the session has done, as the hooks saw it. */
183export type Activity = {
184  /** When the session's figures count from (ms since epoch); absent until the first usage read. */
185  startedAt?: number
186  /** US dollars so far; absent where the host keeps no cost ledger. */
187  cost?: number
188  /** Main-loop turns finished. */
189  turns: number
190  /** Tool calls since the last turn finished, for the next TurnPoint. */
191  callsThisTurn?: number
192  /** Those calls by tool name. */
193  turnTools?: Record<string, number>
194  /** Calls per tool name, subagents' included. */
195  tools: Record<string, ToolCount>
196  /** Paths Edit, Write, MultiEdit and NotebookEdit touched, each once. */
197  files: string[]
198  /** The last main-loop turns, oldest first. */
199  turnLog: TurnPoint[]
200  /** The context window's percent at each measurement, oldest first. */
201  contextLog: number[]
202}
203
204/** A branch the session started (or began on), and the checkout it lives in. */
205export type Tracked = { branch: string; path: string; at: number }
206
207/** One tracked branch's state against the repo's default branch, and its PR. */
208export type BranchView = {
209  branch: string
210  /** The checkout (main or a worktree) the branch was started in. */
211  path: string
212  /** That checkout's folder name, and whether it's a linked worktree. */
213  place: string
214  worktree: boolean
215  /** The branch still exists locally. */
216  exists: boolean
217  /** It's what that checkout has checked out now, so the uncommitted counts are its. */
218  checkedOut: boolean
219  /** Commits ahead of and behind the default branch. */
220  ahead: number
221  behind: number
222  /** Lines added and removed against the default branch, committed and not. */
223  insertions: number
224  deletions: number
225  staged: number
226  modified: number
227  untracked: number
228  conflicted: number
229  /** Pushed: the remote has the branch. */
230  pushed: boolean
231  /** Its most recent PR, if any. */
232  pr: GitPr | null
233}
234
235/** This session's process tree against the whole machine, from the last sample. */
236export type Resources = {
237  /** Processes in the session's tree. */
238  procs: number
239  /** CPU: the tree's and the system's busy share of all cores, 0 to 100. */
240  cpu: number
241  cpuAll: number
242  /** Memory: the tree's resident bytes, and the machine's RAM. */
243  mem: number
244  memAll: number
245  /** Disk: the system's bytes per second, read plus written (macOS has no cheap per-process figure). */
246  diskAll: number
247  /** Network: bytes per second in plus out; the tree's is null until nettop's first sample. */
248  net: number | null
249  netAll: number
250}
251
252declare module 'claude-code' {
253  interface PluginState {
254    overview: {
255      /** The account's rate-limit windows from the last usage read; null until the first. */
256      limits: Limit[] | null
257      /** The session cwd's git state; null until the first read. */
258      git: GitInfo | GitNote | null
259      /** The last `gh` read for that repo; null until the first. */
260      gh: GhInfo | null
261      snapshot: Snapshot | null
262      /** The session's subagents from the last `$.agent.list()`. */
263      agents: Agent[]
264      /** Per agent id, what the spawn and turn hooks recorded. */
265      agentExtra: Record<string, AgentExtra>
266      /** The clock running agents' elapsed time is drawn against (ms since epoch). */
267      now: number
268      /** Cost, time, turns, tool calls and files: the session's activity. */
269      activity: Activity
270      /** The app mode's section ids the person folded. */
271      collapsed: string[]
272      /** Whether a wide app pane flows its sections into columns (the footer's switch); on until flipped. */
273      columns: boolean
274      /** The session's share of the machine; null until two samples give rates. */
275      resources: Resources | null
276      /** Branches the session started or began on, oldest first. */
277      tracked: Tracked[]
278      /** Branches the person closed with ✕. */
279      hidden: string[]
280      /** Each shown tracked branch's state, newest first. */
281      branches: BranchView[]
282      /** The last `gh pr list` for the workspaces; null until the first. Their PRs are kept through a failed one. */
283      workspacesGh: WorkspacesGh | null
284      /** A branch a PR is being created for, while gh runs. */
285      creating: string | null
286    }
287  }
288}
289