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

paneguardcommandtoastprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · overview
│ ┃ Overview ✕ › fix the failing auth test and add an audit log call │ ┃ ◕ Context ◌ ─ │ ┃ ─ ⏺ 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

Draws

Pane · Overview
◕ Context ◌ ─ ▾ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ Reading context… ◔ Limits ─ ▾ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ 5-hour ━━━━━━━━━──────────────────── 31% ⌘ Activity 9 peak 93% cached ─ ▾ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ██ ██ ██ 01 ■ Bash 4 ■ Write 2 ■ Read 1 ■ Grep 1 ■ Other 1 ⎇ Git ◌ ─ ▾ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ Reading git… $ Accounting $0.42 ─ ▾ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ Model – Tokens 7.9k last turn ◷ 0m • 9/m
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 13 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
kit/format.ts 95 lines
1const trim = (n: number) => (n >= 100 ? String(Math.round(n)) : n.toFixed(1).replace(/\.0$/, ''))
2
3/** Token counts: 950, 1.2k, 84k, 1M. */
4export const tokens = (n: number): string => {
5  if (n >= 999_500) return `${trim(n / 1_000_000)}M`
6  if (n >= 1_000) return `${trim(n / 1_000)}k`
7  return String(Math.round(n))
8}
9
10/** A duration to the second: 12s, 3m 05s, 2h 05m. */
11export const duration = (ms: number): string => {
12  const s = Math.max(0, Math.floor(ms / 1_000))
13  if (s < 60) return `${s}s`
14  const m = Math.floor(s / 60)
15  if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`
16  return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
17}
18
19/** A duration at a glance: 47m, 2h05, 3d4h. */
20export const short = (ms: number): string => {
21  const m = Math.max(0, Math.floor(ms / 60_000))
22  if (m < 60) return `${m}m`
23  const h = Math.floor(m / 60)
24  if (h < 24) return `${h}h${String(m % 60).padStart(2, '0')}`
25  return `${Math.floor(h / 24)}d${h % 24}h`
26}
27
28/** How long ago, coarsely, as GitHub lists things: 5m, 3h, 2d, 3w, 4mo, 2y. */
29export const ago = (ms: number): string => {
30  const m = Math.max(0, Math.floor(ms / 60_000))
31  if (m < 60) return `${m}m`
32  const h = Math.floor(m / 60)
33  if (h < 24) return `${h}h`
34  const d = Math.floor(h / 24)
35  if (d < 14) return `${d}d`
36  if (d < 60) return `${Math.floor(d / 7)}w`
37  if (d < 365) return `${Math.floor(d / 30)}mo`
38  return `${Math.floor(d / 365)}y`
39}
40
41/** US dollars: $1.50, $123. */
42/** Bytes, short: 812, 41K, 3.2M, 16G. */
43export const bytes = (n: number): string => {
44  const units = ['', 'k', 'M', 'G', 'T']
45  let i = 0
46  while (n >= 1024 && i < units.length - 1) {
47    n /= 1024
48    i++
49  }
50  return `${n >= 10 || i === 0 ? Math.round(n) : n.toFixed(1)}${units[i]}`
51}
52
53export const money =(usd: number) => (usd >= 100 ? `$${Math.round(usd)}` : `$${usd.toFixed(2)}`)
54
55/** `value` as a whole percent of `max`, clamped: the desktop takes whole percentages only. */
56export const pct = (value: number, max: number) => `${Math.round(Math.max(0, Math.min(100, (value / Math.max(max, 1)) * 100)))}%`
57
58/**
59 * `text` cut in the middle to at most `cells` characters, the end kept: a path
60 * keeps its first segment and as many whole segments from its end as fit
61 * (`src/…/hooks/view.tsx`), then `…/view.tsx`, then the end of its name; other
62 * text keeps its start and end around `…`. Text that fits comes back as is.
63 */
64export const middle = (text: string, cells: number): string => {
65  const chars = [...text]
66  const n = Math.max(0, Math.floor(cells))
67  if (chars.length <= n) return text
68  if (n <= 1) return n === 1 ? '…' : ''
69  const parts = text.split('/')
70  if (parts.length >= 2) {
71    const len = (s: string) => [...s].length
72    const head = parts[0]!
73    const tail: string[] = [parts[parts.length - 1]!]
74    // As many whole segments from the end as fit after `head/…/`.
75    for (let i = parts.length - 2; i > 0; i--) {
76      const next = [parts[i]!, ...tail].join('/')
77      if (len(`${head}/…/${next}`) > n) break
78      tail.unshift(parts[i]!)
79    }
80    const kept = tail.join('/')
81    if (len(`${head}/…/${kept}`) <= n) return `${head}/…/${kept}`
82    if (len(`…/${kept}`) <= n) return `…/${kept}`
83    // Not even the name fits: the end of the name.
84    const name = [...kept]
85    return `…${name.slice(name.length - (n - 1)).join('')}`
86  }
87  // Plain text: a little more of the start than the end.
88  const front = Math.ceil((n - 1) / 2)
89  const back = n - 1 - front
90  return `${chars.slice(0, front).join('')}…${back ? chars.slice(chars.length - back).join('') : ''}`
91}
92
93/** The last path segment. */
94export const basename = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path
95
kit/perf.ts 101 lines
1/**
2 * What a mod costs: how often each named thing ran, how long it took, and how
3 * much of the last minute it spent. Each compiled mod gets its own copy of the
4 * kit, so these are that mod's numbers. Recording never redraws: the footer
5 * shows them as of the pane's latest draw, so measuring adds no load.
6 *
7 *   const done = perf.start('render'); …; done()
8 *   await perf.time('git', () => run(...))
9 *   perf.count('state write')
10 */
11
12const now = (): number => (globalThis as { performance?: { now(): number } }).performance?.now() ?? Date.now()
13
14const WINDOW = 60_000
15
16type Entry = { n: number; total: number; last: number; max: number; recent: Array<[at: number, ms: number]> }
17
18export type PerfRow = {
19  name: string
20  /** Runs since the mod loaded. */
21  n: number
22  /** Runs in the last minute. */
23  perMin: number
24  /** Milliseconds per run, on average; 0 for counts. */
25  avgMs: number
26  lastMs: number
27  maxMs: number
28  /** Milliseconds spent in the last minute. */
29  busyMs: number
30}
31
32export type PerfSnapshot = { sinceMs: number; rows: PerfRow[] }
33
34export const createPerf = () => {
35  const entries = new Map<string, Entry>()
36  const loadedAt = Date.now()
37
38  const record = (name: string, ms: number) => {
39    const e = entries.get(name) ?? { n: 0, total: 0, last: 0, max: 0, recent: [] }
40    const at = Date.now()
41    e.n++
42    e.total += ms
43    e.last = ms
44    e.max = Math.max(e.max, ms)
45    e.recent.push([at, ms])
46    // Keep only the window, so a long session doesn't grow this.
47    while (e.recent.length && at - e.recent[0]![0] > WINDOW) e.recent.shift()
48    entries.set(name, e)
49  }
50
51  /** Starts timing `name`; call what it returns when it's done. */
52  const start = (name: string) => {
53    const t0 = now()
54    return () => record(name, now() - t0)
55  }
56
57  /** Times `fn`, sync or async, under `name`. */
58  const time = <T>(name: string, fn: () => T): T => {
59    const done = start(name)
60    let out: T
61    try {
62      out = fn()
63    } catch (err) {
64      done()
65      throw err
66    }
67    if (out instanceof Promise) return out.finally(done) as T
68    done()
69    return out
70  }
71
72  /** Counts one occurrence of `name`, with no time. */
73  const count = (name: string) => record(name, 0)
74
75  const snapshot = (): PerfSnapshot => {
76    const at = Date.now()
77    const rows = [...entries].map(([name, e]) => {
78      const recent = e.recent.filter(([t]) => at - t <= WINDOW)
79      return {
80        name,
81        n: e.n,
82        perMin: recent.length,
83        avgMs: e.n ? e.total / e.n : 0,
84        lastMs: e.last,
85        maxMs: e.max,
86        busyMs: recent.reduce((s, [, ms]) => s + ms, 0),
87      }
88    })
89    // What cost the most in the last minute first, then what ran most.
90    rows.sort((a, b) => b.busyMs - a.busyMs || b.perMin - a.perMin)
91    return { sinceMs: at - loadedAt, rows }
92  }
93
94  return { start, time, count, snapshot }
95}
96
97export type Perf = ReturnType<typeof createPerf>
98
99/** Milliseconds, short: 0.4ms, 12ms, 1.2s. */
100export const ms = (v: number): string => (v >= 1_000 ? `${(v / 1_000).toFixed(1)}s` : v >= 10 ? `${Math.round(v)}ms` : `${v.toFixed(1)}ms`)
101
kit/ui.tsx 2426 lines
1import type { RenderElement, RenderSurface } from 'claude-code'
2
3import { middle, pct, short } from './format'
4import { ICON_PX, glyphOf, iconSvg } from './icons'
5import { ms } from './perf'
6import type { PerfRow, PerfSnapshot } from './perf'
7import { C, FILL, GLYPH, GRAY, INK, MUTED, STATUS, TRACK, isKitColor, termInk, tint, treePrefix } from './tokens'
8import type { Duo, StatusKind } from './tokens'
9
10/**
11 * The shared components. Each draws for the surface it is given: on the app
12 * surfaces (desktop, VS Code, mobile) as boxes laid out by flexbox, crisp at
13 * any width; in the terminal as cells, `columns` wide.
14 *
15 * What the desktop accepts (2.1.293): whole percentages only, `flexGrow` up to
16 * 10000, fractional heights and margins; no `hover`. Borders `round` (rounded
17 * corners), single, double, bold and classic draw; `dashed` doesn't. SVG is
18 * drawn as an image: crisp only at its exact pixel size, so it's kept to small
19 * fixed pieces like bar ends.
20 *
21 * Units on the desktop (measured on 2.1.295): a column (widths, paddingX, marginX,
22 * gaps between columns) is ~7.8px; a row of size (`height`, `minHeight`) is ~19px,
23 * one text line; but vertical spacing (marginTop/Bottom/Y, paddingTop/Bottom/Y,
24 * rowGap) is half that, ~9.5px a unit. A `transparent` border colour is drawn in
25 * the text's colour, so the kit draws no border to round a fill.
26 */
27
28/** The element constructors the kit draws with. `Button` is needed only for collapsible sections. */
29export type Els = {
30  Box: (props: any, ...children: any[]) => RenderElement
31  Text: (props: any, ...children: any[]) => RenderElement
32  Button?: (props: any, ...children: any[]) => RenderElement
33  /** Rounds the ends of bars where the surface has it. */
34  Svg?: (props: any, ...children: any[]) => RenderElement
35}
36
37/**
38 * The Buttons one pane drew last, per scope: each by its key, with the props and
39 * children it was drawn with, the element built for them, and the latest press.
40 */
41type HeldButton = { look: string; made: unknown; element: RenderElement; frame: number; press: (e: any) => void }
42const heldButtons = new Map<string, { frame: number; buttons: Map<string, HeldButton> }>()
43
44/**
45 * The element table `els` with a `Button` that keeps each button's press handle
46 * from one drawing to the next, for the drawing `scope` names (the render event
47 * itself: its component, requestId and surface). Call it once per render, as
48 * the drawing starts (after the render's awaits), and draw every Button of that
49 * render with the table it returns (the kit's own included: pass it to `kit`).
50 *
51 * Why: the engine's JSX gives every Button it builds a new handle, and frees the
52 * old one as soon as a drawing leaves it out; a press reaches its `onPress` by
53 * that handle alone. So a redraw between drawing and click (the click focusing
54 * the pane, a timer's write) left the press on a freed handle, and it did
55 * nothing. Here a Button whose key, props and children match the last render's
56 * is that same element, its handle unchanged, its press running the latest
57 * `onPress`. One that changed is built anew (a stale press on it misses, as it
58 * should); one absent from the last render is forgotten.
59 */
60export const holdButtons = <E extends { Button?: unknown }>(els: E, scope: string | { component: string; requestId: string; surface: string }): E => {
61  const Made = els.Button as ((props: any, ...children: any[]) => RenderElement) | undefined
62  if (!Made) return els
63  const id = typeof scope === 'string' ? scope : `${scope.component}\u0000${scope.requestId}\u0000${scope.surface}`
64  const pane = heldButtons.get(id) ?? { frame: 0, buttons: new Map<string, HeldButton>() }
65  heldButtons.set(id, pane)
66  // A new render: keep only what the last one drew.
67  for (const [key, b] of pane.buttons) if (b.frame < pane.frame) pane.buttons.delete(key)
68  pane.frame += 1
69  const frame = pane.frame
70  const Button = (props: any, ...rest: any[]): RenderElement => {
71    const { children: given, onPress, ...plain } = props ?? {}
72    const children: unknown[] = rest.length ? rest : given === undefined ? [] : Array.isArray(given) ? given : [given]
73    const key = plain.key ?? plain.label ?? (children.length === 1 && typeof children[0] === 'string' ? children[0] : undefined)
74    if (typeof key !== 'string' || typeof onPress !== 'function') {
75      return (
76        <Made {...plain} onPress={onPress}>
77          {children}
78        </Made>
79      )
80    }
81    const look = JSON.stringify([plain, children])
82    const was = pane.buttons.get(key)
83    // A second Button on one key in one render is built apart: one element can't hold two presses.
84    if (was?.frame === frame) {
85      return (
86        <Made {...plain} onPress={onPress}>
87          {children}
88        </Made>
89      )
90    }
91    // The same look from the same constructor (another plugin may restyle the table's).
92    if (was && was.look === look && was.made === Made) {
93      was.frame = frame
94      was.press = onPress
95      return was.element
96    }
97    const b: HeldButton = { look, made: Made, frame, press: onPress, element: null as unknown as RenderElement }
98    b.element = (
99      <Made {...plain} onPress={(e: any) => b.press(e)}>
100        {children}
101      </Made>
102    )
103    pane.buttons.set(key, b)
104    return b.element
105  }
106  // Everything else read through to the table as it was (whatever kind of object it is).
107  // Defined, not assigned: the engine's table is frozen, and its read-only Button would refuse an assignment.
108  return Object.create(els, { Button: { value: Button, enumerable: true } }) as E
109}
110
111/**
112 * A bar part: its value, its color, and the label its legend shows. `room: true`
113 * marks room rather than use (free space, a reserve): the terminal draws it as
114 * the bar's light rail in its colour, and a `bar: true` legend keys it with `─`.
115 */
116export type Part = { value: number; color: string; label?: string; room?: boolean }
117
118const BAR = 0.45
119
120/** One row's height in CSS pixels on the desktop, measured: a 0.45-row bar is 8.5px tall. */
121const ROW_PX = 8.5 / 0.45
122/** One column's width in CSS pixels on the desktop (as the playground calibrates it): what an SVG sized in cells is drawn at. */
123const COL_PX = 7.8
124
125/*
126 * The grid. Mods use these, never raw spacing numbers:
127 *
128 * - SPACE.pair between the two halves of a pair (glyph and figure, dot and label),
129 *   SPACE.item between items in a row, SPACE.group between groups of items;
130 *   SPACE.block between blocks inside a section body (rows in a list sit at 0).
131 * - INSET: a band's (header, footer) padding on both sides, and a body's on the right,
132 *   so header figures, body figures and the footer end on one line.
133 * - BODY_INDENT: a body's left edge, just past the header's fold arrow.
134 * - Reading columns: LABEL | gauge (grows) | FIG right-aligned | FIG2 right-aligned.
135 */
136export const SPACE = { pair: 0.75, item: 1.25, group: 2, block: 0.8 } as const
137const INSET = 1
138const BODY_INDENT = 1.6
139/**
140 * The content edges: everything that isn't a band (the header totals, section bodies)
141 * starts at `left` and ends at `right`. Alignment rules, for every row:
142 * - labels, names and titles start on the left edge;
143 * - the row's last figure or action ends on the right edge (rows are space-between);
144 * - figures are right-aligned; a row's right side is one cluster, never two.
145 */
146export const EDGE = { left: BODY_INDENT, right: INSET } as const
147const LABEL = 10
148const FIG = 5
149const FIG2 = 6
150/** The terminal's fold-arrow gutter. */
151const GUTTER = 2
152
153/*
154 * The terminal's grid. A terminal lays out in whole cells, so it has its own
155 * spacing (a fraction would round differently row to row) and draws to an exact
156 * width in cells. `k.space` and `k.edge` give the grid for the kit's surface.
157 *
158 * - CELLS: pair 1 (glyph and figure), item 1 (columns of a reading), group 2
159 *   (figures in a summary, actions in a row), block 1 (a blank row).
160 * - Indent: a section body starts GUTTER (2) in, under the header's icon column;
161 *   each tree level indents 2 more.
162 * - Reading columns: LABEL (10) | gauge (the rest) | FIG (5) | FIG2 (6), one cell
163 *   apart; under MIN_GAUGE cells of gauge the label narrows, then the gauge goes.
164 */
165export const CELLS = { pair: 1, item: 1, group: 2, block: 1 } as const
166/** The fewest cells a terminal gauge is drawn in; narrower, the reading drops it and keeps its figures. */
167const MIN_GAUGE = 6
168/** The narrowest a terminal reading's label gets before its gauge is dropped. */
169const MIN_LABEL = 6
170/** The cells of its text a terminal list item keeps (with its ellipsis) before its right cluster is cut. */
171const ITEM_KEEPS = 6
172/**
173 * The narrowest pane the terminal draws section bodies in. Narrower, each section
174 * draws its header and figures only (a floor, as bottom's basic mode), rather
175 * than every reading collapsing to an ellipsis.
176 */
177export const MIN_COLUMNS = 30
178
179/**
180 * The terminal's meter glyphs. A gauge and a bar are both a heavy line on a light
181 * one, to half a cell (╸): a bar's parts are runs of the heavy line, each in its
182 * own solid theme colour, and its room (free space, a reserve) the light rail in
183 * its colour. No shades or dithers: they render as a checkerboard in real fonts.
184 */
185export const METER = {
186  line: '━',
187  half: '╸',
188  rail: '─',
189  /** Lower eighths, 0 to 8: for columns that rise. */
190  rise: [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'],
191} as const
192
193/**
194 * The widest a dashboard's sections are drawn on the terminal, in cells, when a
195 * mod passes `measure: MEASURE` to `kit()`: past it, more width only spreads
196 * readings apart and sends the eye across the pane.
197 */
198export const MEASURE = 72
199/** The terminal's right margin: figures stop one cell short of the pane's edge. */
200const RIGHT = 1
201/** The cells a section title's column takes, so header figures start on one column. */
202const TITLE_COL = 10
203
204/** The terminal's fold arrows: the small triangles, a cell each. */
205export const FOLD = { open: '▾', closed: '▸' } as const
206
207/**
208 * The terminal's marks for lists and footers: a selected row's gutter mark (a
209 * left half block, in `suggestion`, Claude Code's own selection colour), the key
210 * hints' separator, and the ellipsis that ends anything cut.
211 */
212export const MARK = { selected: '▌', sep: ' · ', more: '…', stale: '↻' } as const
213
214/**
215 * Braille dots for a sparkline, filled from the bottom: a cell holds two points
216 * (its left and right dot columns), four levels each. `left[n]` is the left
217 * column's bottom n dots, `right[n]` the right column's; OR them onto U+2800.
218 */
219export const SPARK = {
220  base: 0x2800,
221  left: [0, 0x40, 0x44, 0x46, 0x47],
222  right: [0, 0x80, 0xa0, 0xb0, 0xb8],
223} as const
224/**
225 * A band's (a section header's, a footer's) height on the app surfaces, in rows of
226 * size: one text row and a little room. Fixed rather than padded, so every band is
227 * as tall as every other whatever it holds: a native Button, a Link or an icon in
228 * a row of the real desktop is taller or shorter than a line of text, and a padded
229 * band grew or shrank with it (the launcher's rows came out uneven).
230 */
231export const BAND_ROWS = 1.3
232
233/**
234 * A Braille blank (U+2800): drawn as nothing, as a space is, but never trimmed or
235 * collapsed. A Button labelled with them lies over what the desktop can't draw in a
236 * Button (an icon, a coloured word), which shows through; its key is its address.
237 */
238export const BLANK = '⠀'
239/** A tile's padding above and below its lines, and the room between its lines: enough to breathe. */
240const TILE_PAD_Y = 0.6
241const TILE_ROW_GAP = 0.2
242/** The bar under the active tab on the app surfaces, in rows of size (about 2px), and the hairline under the tabs (about 1px). */
243const TAB_MARK = 0.12
244const HAIRLINE = 0.06
245/**
246 * A container's corner radius on the app surfaces, in pixels (a section's band, a
247 * list's surface, a tile): the Claude Code pack's card radius (zen's `linear`
248 * materials, `radiusCard`).
249 */
250const RADIUS_PX = 6
251/** An accent's stripe along a container's top edge, in pixels: as thick as the active tab's bar. */
252const ACCENT_PX = 2
253
254/**
255 * The desktop's fold arrow: full-size triangles, since text can't be sized.
256 * U+FE0E keeps ▶ a text glyph; without it macOS can draw it as an emoji. Never
257 * on the terminal, which draws FOLD and never gets a variation selector.
258 */
259export const fold = (collapsed: boolean) => (collapsed ? '▶︎' : '▼')
260
261
262/**
263 * `text` split for two terminal lines `width` cells wide: the first holds as many
264 * whole words as fit (a word longer than the line is cut to it), the second the
265 * rest, which the caller truncates. The second is empty when it all fits on one.
266 */
267const breakLine = (text: string, width: number): [string, string] => {
268  const chars = [...text]
269  if (chars.length <= width) return [text, '']
270  // The last space at or before the line's end; none, a hard cut.
271  let cut = -1
272  for (let i = Math.min(width, chars.length - 1); i > 0; i--) {
273    if (chars[i] === ' ') {
274      cut = i
275      break
276    }
277  }
278  if (cut <= 0) return [chars.slice(0, width).join(''), chars.slice(width).join('').trimStart()]
279  return [chars.slice(0, cut).join('').trimEnd(), chars.slice(cut + 1).join('').trimStart()]
280}
281
282
283/** The debug footer's glyph for each job the mods time; all muted, a slow job's figure turns amber or red. */
284export const PERF_GLYPH: Readonly<Record<string, string>> ={ render: '▣', tick: '↻', resources: '◎', usage: '◕', git: '⎇', gh: '⇡' }
285
286/*
287 * The terminal's look ("rules", after lazygit and gh-dash, made quieter). A header
288 * is a dim arrow and icon, the title in bold default foreground, its figures on a
289 * shared column right after it (so the eye doesn't cross the pane), then a dim `─`
290 * rule out to the edge. Status colours keep their one meaning; nothing else is coloured.
291 *
292 * Two tones and one weight carry the hierarchy: dim for what a thing is (labels,
293 * units, notes), the default foreground for what it says (values, list text),
294 * bold for the title and the one figure that matters in each section (a header's
295 * first figure). No italics: real terminal fonts draw them oddly, and some not at
296 * all. Tune the look here, in one place:
297 * - title: a section's name: bold;
298 * - label: what a value is (a reading's, a prop's, a legend entry's label): dim;
299 * - value: the figure or word that answers (a reading's figure, a prop's value): plain;
300 * - strong: the one figure per section that matters (a header's first figure): bold;
301 * - secondary: text a reader still reads, after the main text (a list row's note): dim;
302 * - meta: what's scanned past (units, ages, counts in a list row): dim.
303 *
304 * The alternatives it was picked from (inspector, panel, ledger) are in commit ab3a37a.
305 */
306
307/** Text props a terminal role is drawn with. */
308type Role = { color?: string; dimColor?: boolean; bold?: boolean; italic?: boolean }
309
310export const TERM_ROLES: Readonly<Record<'title' | 'label' | 'value' | 'strong' | 'secondary' | 'meta', Role>> = {
311  title: { bold: true },
312  label: { dimColor: true },
313  value: {},
314  strong: { bold: true },
315  secondary: { dimColor: true },
316  meta: { dimColor: true },
317}
318
319/**
320 * The header icon's colour on the terminal: dim (MUTED), as the fold arrow, since
321 * grey is what icons mean. The title beside it is bold in the default foreground,
322 * so a header carries no hue that could be read as a status in the rows under
323 * it. Read when drawing, so a skin worn later is the one drawn.
324 */
325const termHeaderIcon = () => MUTED
326
327/** What the kit is told about the pane beyond its surface and width. */
328export type KitOptions = {
329  /**
330   * Whether the pane has the keyboard: pass `e.props.isFocused`. Key hints show
331   * only while it's true, and a selected list row is drawn dimmed while it's
332   * false. Left out, the pane counts as focused.
333   */
334  focused?: boolean
335  /**
336   * The widest the terminal draws sections, in cells (`MEASURE` for a dashboard
337   * of readings). Past it a section keeps this width and the rest of the pane
338   * stays empty. Left out, sections span the pane (a file tree wants every cell).
339   */
340  measure?: number
341  /**
342   * The column view's switch, as the mod holds it in its own state (key
343   * `columns`, default on): off, `flow` gives one stack at any width. With a
344   * `toggle`, a wide desktop pane's footer (`perf`, `footer`) draws the quiet
345   * action that flips it (see `flowToggle`).
346   */
347  flow?: FlowSwitch
348}
349
350/** The column view's switch: `on` as the mod's state holds it, `toggle` to flip it from a press. */
351export type FlowSwitch = { on: boolean; toggle?: () => void }
352
353/**
354 * A part of a list row's right cluster that says when it gives way: at narrow
355 * widths the part with the highest `drop` goes first (ties: the later one), then
356 * the next, until the row fits; parts without one (rank 0) are never dropped,
357 * only cut. `cells` is its width on the terminal when it's an element the kit
358 * can't measure (a string measures itself).
359 */
360export type RightPart = { part: RenderElement | string; drop?: number; cells?: number }
361
362/** One key hint: the key as the person types it, and what it does. */
363export type Hint = { key: string; label: string }
364
365/** One of a pane's tabs (`k.tabs`): its id (what `onSelect` is called with), its label, and an optional hotkey (a digit). */
366export type Tab = { id: string; label: string; hotkey?: string }
367
368const isRightPart = (x: RenderElement | string | RightPart): x is RightPart => typeof x === 'object' && x !== null && 'part' in x && !('type' in x)
369
370/**
371 * The cells a part draws in on the terminal, as far as the kit can tell: a
372 * string's characters; a Text's text; a row Box's children and gaps; a plain
373 * Button's label (and `1: ` before it with a hotkey). Undefined when it can't.
374 */
375const cellsOf = (x: unknown): number | undefined => {
376  if (x == null || x === false) return 0
377  if (typeof x === 'string' || typeof x === 'number') return [...String(x)].length
378  if (Array.isArray(x)) {
379    let n = 0
380    for (const c of x) {
381      const m = cellsOf(c)
382      if (m === undefined) return undefined
383      n += m
384    }
385    return n
386  }
387  if (typeof x !== 'object') return undefined
388  const el = x as { type?: string; props?: Record<string, any>; children?: unknown[] }
389  const p = el.props ?? {}
390  const kids = el.children ?? (p.children as unknown[] | undefined) ?? []
391  if (el.type === 'Text') return cellsOf(kids)
392  if (el.type === 'Button') {
393    const label = p.label === undefined ? cellsOf(kids) : [...String(p.label)].length
394    if (label === undefined) return undefined
395    return (p.plain ? label : label + 4) + (p.hotkey ? 3 : 0)
396  }
397  if (el.type === 'Box') {
398    const list = (Array.isArray(kids) ? kids : [kids]).flat(Infinity as 1).filter(c => c != null && c !== false)
399    const sizes = list.map(cellsOf)
400    if (sizes.some(s => s === undefined)) return undefined
401    const n = sizes as number[]
402    if (p.flexDirection === 'column') return Math.max(0, ...n)
403    const gap = Number(p.columnGap ?? p.gap ?? 0)
404    return n.reduce((a, b) => a + b, 0) + gap * Math.max(0, n.length - 1)
405  }
406  return undefined
407}
408
409/*
410 * Flow: a pane's sections in columns when the desktop gives it the width.
411 *
412 * The engine tells a render its pane's width (`e.props.bodyColumns`; on the desktop
413 * the pane's width over its code font's advance), and draws again when it changes.
414 * At a sidebar's width the sections stack as they always have; past two of
415 * FLOW_MIN (plus the gutter) they split into two columns, past three into three.
416 * The terminal always stacks: its panes dock beside the transcript and are narrow.
417 */
418
419/**
420 * The narrowest a flow column gets, in the pane's reported columns: about the
421 * widest a desktop sidebar is drawn (Storybook's 110), halved, so a section in a
422 * column reads as it does in a roomy sidebar. Two columns from 82 (about 640px), three from 124 (about 970px).
423 */
424export const FLOW_MIN = 40
425/** The most columns a flow splits into: more makes every section a sliver. */
426export const FLOW_MAX = 3
427/** The gutter between flow columns: a group's room, as between groups of items in a row. No rule or panel marks it. */
428const FLOW_GAP = SPACE.group
429
430/** How a flow is told to lay out; each defaults to the kit's FLOW_MIN, FLOW_MAX. */
431export type FlowOptions = {
432  /** The narrowest column, in reported columns. */
433  min?: number
434  /** The most columns. */
435  max?: number
436  /**
437   * Each block's height in rows, where the caller knows better than the kit's
438   * estimate (`undefined` entries are estimated). In the order the blocks are given.
439   */
440  rows?: (number | undefined)[]
441  /**
442   * The room between blocks in a column, in the desktop's vertical units, for
443   * blocks that space themselves apart in one stack (a list's tiles, each with a
444   * margin above all but the first): in columns they drop that margin and the
445   * column spaces them, so every column's first block starts on one line.
446   */
447  gap?: number
448  /** One stack at any width: the column view switched off (KitOptions' `flow`). */
449  single?: boolean
450}
451
452/** Whether a pane `columns` across on `surface` is wide enough to split into flow columns at all. */
453export const flowSplits = (surface: RenderSurface, columns: number, o: Pick<FlowOptions, 'min'> = {}) =>
454  surface !== 'terminal' && Math.floor((Math.floor(columns) + FLOW_GAP) / ((o.min ?? FLOW_MIN) + FLOW_GAP)) >= 2
455
456/**
457 * How many columns a flow of `blocks` blocks takes at `columns` across on
458 * `surface`, and each column's width in reported columns: 1 and the whole width
459 * on the terminal, at a sidebar's width, with fewer than two blocks, or `single`.
460 */
461export const flowColumns = (surface: RenderSurface, columns: number, blocks: number, o: FlowOptions = {}) => {
462  const min = o.min ?? FLOW_MIN
463  const max = o.max ?? FLOW_MAX
464  const fit = surface === 'terminal' || o.single ? 1 : Math.floor((Math.floor(columns) + FLOW_GAP) / (min + FLOW_GAP))
465  const count = Math.max(1, Math.min(fit, max, blocks))
466  return { count, width: count === 1 ? columns : Math.floor((columns - FLOW_GAP * (count - 1)) / count) }
467}
468
469/** A drawn element's own props and children, as the engine's JSX and Storybook's both build them. */
470const partsOf = (x: any): { type?: string; p: Record<string, any>; kids: unknown[] } => {
471  const p = (x?.props ?? {}) as Record<string, any>
472  const given = x?.children ?? p.children ?? []
473  return { type: x?.type, p, kids: (Array.isArray(given) ? given : [given]).flat(Infinity as 1).filter(c => c != null && c !== false) }
474}
475
476/**
477 * About how many rows tall an element draws on the desktop: a Text or a Button a
478 * row, a column Box its children stacked, a row Box its tallest child, a `height`
479 * as given; vertical margins, padding and gaps at half a row a unit, as the
480 * desktop draws them. Only good enough to balance columns, never to size them.
481 */
482export const rowsOf = (x: unknown): number => {
483  if (x == null || x === false) return 0
484  if (typeof x === 'string' || typeof x === 'number') return 1
485  if (Array.isArray(x)) return x.reduce((n: number, c) => n + rowsOf(c), 0)
486  if (typeof x !== 'object') return 0
487  const { type, p, kids } = partsOf(x)
488  if (p.display === 'none' || p.position === 'absolute') return 0
489  const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
490  // Vertical spacing in half rows (the desktop's unit for it), as rows.
491  const around =
492    (num(p.marginTop) + num(p.marginBottom) + 2 * num(p.marginY) + 2 * num(p.margin) + num(p.paddingTop) + num(p.paddingBottom) + 2 * num(p.paddingY) + 2 * num(p.padding)) / 2
493  let own: number
494  if (typeof p.height === 'number') own = p.height
495  else if (type === 'Box') {
496    const sizes = kids.map(rowsOf)
497    if (p.flexDirection === 'column') own = sizes.reduce((a, b) => a + b, 0) + (num(p.rowGap ?? p.gap) * Math.max(0, sizes.length - 1)) / 2
498    else own = Math.max(0, ...sizes)
499  } else own = 1
500  return Math.max(own, num(p.minHeight)) + around
501}
502
503/**
504 * Splits `heights` into `n` runs in order, so the tallest run is as short as it
505 * can be: blocks read top to bottom, then left to right, and the columns end
506 * about even. Returns each run's first index.
507 */
508const balance = (heights: number[], n: number): number[] => {
509  const m = heights.length
510  const sum = [0]
511  for (const h of heights) sum.push(sum[sum.length - 1]! + h)
512  // best[j][i]: the tallest column laying the first i blocks in j columns; cut[j][i] where the last column starts.
513  const best = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(Infinity))
514  const cut = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0))
515  best[0]![0] = 0
516  for (let j = 1; j <= n; j++) {
517    for (let i = j; i <= m; i++) {
518      // Every column holds at least one block.
519      for (let s = j - 1; s < i; s++) {
520        const tall = Math.max(best[j - 1]![s]!, sum[i]! - sum[s]!)
521        // Ties go to the later cut, so earlier columns take more and the last isn't the tall one.
522        if (tall <= best[j]![i]!) {
523          best[j]![i] = tall
524          cut[j]![i] = s
525        }
526      }
527    }
528  }
529  const starts: number[] = []
530  let i = m
531  for (let j = n; j >= 1; j--) {
532    starts.unshift(cut[j]![i]!)
533    i = cut[j]![i]!
534  }
535  return starts
536}
537
538/**
539 * Lays `blocks` (a pane's sections, a list's tiles) out in columns when the pane
540 * is wide enough (see `flowColumns`); otherwise gives them back as they were, so
541 * a narrow pane draws exactly what it drew before. Spread the result where the
542 * blocks went: `{flow(Box, e.surface, columns, 'sections', [a, b, c])}`.
543 *
544 * A block is never split across columns. They read top to bottom, then left to
545 * right, cut where the columns come out most even by `rowsOf`'s estimate (or the
546 * `rows` given). Each column is a plain column Box (key `<key>-col-<n>`), each
547 * block in it spanning the column's width; the gutter between is FLOW_GAP, with
548 * no rule, panel or outline.
549 */
550export const flow = (
551  Box: Els['Box'],
552  surface: RenderSurface,
553  columns: number,
554  key: string,
555  blocks: (RenderElement | null | false | undefined)[],
556  o: FlowOptions = {},
557): (RenderElement | null)[] => {
558  const shown = blocks.map((b, i) => ({ b, rows: o.rows?.[i] })).filter((x): x is { b: RenderElement; rows: number | undefined } => x.b != null && x.b !== false)
559  const { count } = flowColumns(surface, columns, shown.length, o)
560  if (count < 2) return blocks.map(b => b || null)
561  const starts = balance(
562    shown.map(x => x.rows ?? rowsOf(x.b)),
563    count,
564  )
565  const runs = starts.map((s, c) => shown.slice(s, starts[c + 1] ?? shown.length))
566  return [
567    <Box key={key} flexDirection="row" width="100%" columnGap={FLOW_GAP} alignItems="flex-start">
568      {runs.map((run, c) => (
569        // Columns share the row equally, growing from no width, as a legend's do (the desktop doesn't stretch a nested box).
570        <Box key={`${key}-col-${c}`} flexDirection="column" flexGrow={1} flexShrink={1} width={0} minWidth={0} {...(o.gap ? { rowGap: o.gap } : {})}>
571          {run.map((x, i) => (
572            <Box key={`${key}-${c}-${i}`} flexDirection="column" width="100%" minWidth={0}>
573              {x.b}
574            </Box>
575          ))}
576        </Box>
577      ))}
578    </Box>,
579  ]
580}
581
582export const kit = (els: Els, surface: RenderSurface, columns = 40, opts: KitOptions = {}) => {
583  const { Box, Text, Button, Svg } = els
584  const terminal = surface === 'terminal'
585  /** Whether the pane has the keyboard; unknown counts as yes. */
586  const paneFocused = opts.focused !== false
587  /** A flow's options with the column view's switch applied: off, one stack. */
588  const flowOpts = (o: FlowOptions = {}): FlowOptions => (opts.flow?.on === false ? { ...o, single: true } : o)
589  /** Under MIN_COLUMNS the terminal draws section headers only. */
590  const floor = terminal && Math.floor(columns) < MIN_COLUMNS
591  /** A text role's props on the terminal (see TERM_ROLES). */
592  const R = TERM_ROLES
593  /** Text a step below the main text: one of the three greys on the app surfaces; plain dim in the terminal, whose greys are its own. */
594  const tone = (level: keyof typeof GRAY) => (terminal ? { dimColor: true } : { color: GRAY[level] })
595  /** A token colour as Text props for this surface: on the terminal a status's theme key, a grey as dim. */
596  const ink = (color?: string): { color?: string; dimColor?: boolean } => (terminal ? termInk(color) : color ? { color } : {})
597  /** The grid for this surface: CELLS on the terminal, SPACE elsewhere. */
598  const space = terminal ? CELLS : SPACE
599  const edge = terminal ? { left: GUTTER, right: RIGHT } : EDGE
600  /** A section's width in terminal cells: the pane's, up to the measure. */
601  const span = Math.max(1, Math.min(Math.floor(columns), opts.measure ?? Infinity))
602  /** A section body's width in terminal cells: the section's less the gutter and the right margin. */
603  const body = Math.max(1, span - GUTTER - RIGHT)
604  const clamp01 = (x: number) => (Number.isFinite(x) ? Math.max(0, Math.min(1, x)) : 0)
605
606  /** A run of one glyph in one colour, as one Text. */
607  const run = (key: string, glyph: string, n: number, props: Record<string, unknown>) =>
608    n > 0 ? <Text key={key} {...props}>{glyph.repeat(n)}</Text> : null
609
610  /**
611   * A terminal gauge `width` cells wide: a heavy line to the half cell over a
612   * dim light rail. Anything above zero shows at least half a cell.
613   */
614  const lineMeter = (fraction: number, color: string, width: number): RenderElement => {
615    const w = Math.max(1, Math.floor(width))
616    let halves = Math.round(clamp01(fraction) * w * 2)
617    if (fraction > 0 && halves === 0) halves = 1
618    const full = Math.floor(halves / 2)
619    const half = halves % 2
620    return (
621      <Text>
622        {run('fill', METER.line, full, ink(color))}
623        {half ? <Text key="half" {...ink(color)}>{METER.half}</Text> : null}
624        {run('rail', METER.rail, w - full - half, { dimColor: true })}
625      </Text>
626    )
627  }
628
629  /**
630   * A terminal bar `width` cells wide, one row: each part a run of the heavy line
631   * (`━`) in its own solid colour, to the half cell; a `room` part the light rail
632   * (`─`) in its colour; what's left the dim rail. Anything above zero shows at
633   * least half a cell. A cell shared by two parts takes the first one's colour.
634   */
635  const lineBar = (parts: Part[], total: number, width: number): RenderElement => {
636    const w = Math.max(1, Math.floor(width))
637    const halves = w * 2
638    const ends: { end: number; color: string; room: boolean }[] = []
639    let at = 0
640    for (const p of parts) {
641      if (!(p.value > 0) || at >= halves) continue
642      at = Math.min(halves, at + Math.max(1, Math.round((p.value / total) * halves)))
643      ends.push({ end: at, color: p.color, room: Boolean(p.room) })
644    }
645    const partAt = (h: number) => ends.find(x => h < x.end)
646    const rail = { glyph: METER.rail, props: { dimColor: true } as Record<string, unknown> }
647    const cells: { glyph: string; props: Record<string, unknown> }[] = []
648    for (let c = 0; c < w; c++) {
649      const left = partAt(2 * c)
650      const right = partAt(2 * c + 1)
651      if (!left) cells.push(rail)
652      else if (left.room) cells.push({ glyph: METER.rail, props: ink(left.color) })
653      // A used part ending at the half: the half line, then nothing (a room part, or the rail, starts next cell).
654      else if (!right || right.room) cells.push({ glyph: METER.half, props: ink(left.color) })
655      else cells.push({ glyph: METER.line, props: ink(left.color) })
656    }
657    // Runs of the same glyph and colour, as one Text each.
658    const runs: RenderElement[] = []
659    let i = 0
660    while (i < cells.length) {
661      let j = i + 1
662      while (j < cells.length && cells[j]!.glyph === cells[i]!.glyph && JSON.stringify(cells[j]!.props) === JSON.stringify(cells[i]!.props)) j++
663      runs.push(<Text key={`r${i}`} {...cells[i]!.props}>{cells[i]!.glyph.repeat(j - i)}</Text>)
664      i = j
665    }
666    return <Text>{runs}</Text>
667  }
668
669  /*
670   * Rounding on the desktop. Boxes have no corner radius; what rounds is:
671   *
672   * - `capped`: anything thin (bars, gauges). SVG end caps drawn at an exact pixel
673   *   size, so they stay crisp; the middle takes no height and stretches to the caps.
674   * - `card`: containers (a section's band, a list's surface, a tile). Their fill is
675   *   a ground placed behind the content (`position: absolute`, all four offsets 0):
676   *   an edge row of two SVG quarter discs (RADIUS_PX square) and a stretched middle
677   *   at the top and at the bottom, a plain fill between. An accent is the top edge's
678   *   first ACCENT_PX, the corners' share of it drawn in the same SVGs.
679   * - Nothing else: `rounded` boxes (pills) are square-cornered fills.
680   *
681   * What doesn't work, so nobody tries again: a `round` border in `transparent` to
682   * round a fill (the desktop doesn't know `transparent` as a border colour and draws
683   * the border in the text's colour: every band and tile became an outlined bubble),
684   * a border in a see-through fill's own colour (paints twice and draws a ring),
685   * borders on thin bars (empty, or blobs),
686   * glyph ends (◖━◗, ╺━╸ don't draw), SVG slivers a few pixels wide (don't draw), an
687   * SVG stretched to fit (blurs), a circle drawn over a rect in one SVG (a translucent
688   * colour doubles where they overlap).
689   */
690
691  /**
692   * An icon at the kit's one size (ICON_PX square): the SVG drawing where the
693   * surface has SVG and the kit has one for `key`, else its glyph as text
694   * (`glyphOf`: the terminal glyph for a named icon, never the name itself).
695   *
696   * `color` may be a file type's `Duo` (`FILE_TYPE`): light and dark values on the
697   * app surfaces, dim on the terminal, which draws file types monochrome.
698   * `alt` names the drawing for a reader that can't see it (the desktop's
699   * accessible name); `tooltip` also shows it under the pointer, drawing the SVG
700   * interactive (a sandboxed frame), so keep it to an icon that says something
701   * on its own (a branch's upstream), never one under a Button.
702   */
703  const icon = (key: string, color: string | Duo, px = ICON_PX, opts: { alt?: string; tooltip?: string } = {}): RenderElement => {
704    const source = Svg && !terminal ? iconSvg(key, color, px, opts.tooltip) : null
705    if (!Svg || !source) return <Text {...ink(typeof color === 'string' ? color : MUTED)}>{glyphOf(key)}</Text>
706    const alt = opts.alt ?? opts.tooltip ?? 'icon'
707    return opts.tooltip ? <Svg source={source} alt={alt} width={px} height={px} isInteractive /> : <Svg source={source} alt={alt} width={px} height={px} />
708  }
709
710  /**
711   * One rounded end:a square `px` tall, a half circle on the outside and a filled
712   * strip on the inside, as one shape.
713   */
714  const cap = (px: number, color: string, side: 'left' | 'right'): RenderElement | null => {
715    if (!Svg) return null
716    const r = px / 2
717    const d = side === 'left' ? `M${r} 0H${px}V${px}H${r}A${r} ${r} 0 0 1 ${r} 0Z` : `M0 0H${r}A${r} ${r} 0 0 1 ${r} ${px}H0Z`
718    // Over the track, as the bar's middle paints its parts: a see-through part's end
719    // then comes out the same shade as the rest of it.
720    const under = color === TRACK ? '' : `<path d="${d}" fill="${TRACK}"/>`
721    const source =
722      `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${px} ${px}">` +
723      `${under}<path d="${d}" fill="${color}"/></svg>`
724    return (
725      <Box flexShrink={0}>
726        <Svg source={source} alt="rounded end" width={px} height={px} />
727      </Box>
728    )
729  }
730
731  /**
732   * Rounds the ends of something thin: `middle` between a `left` and a `right` cap,
733   * `height` rows tall. Give `middle` no height of its own; it stretches to the caps,
734   * whose pixel size it can't drift from. Where the surface has no SVG, `middle` alone
735   * at `height`.
736   */
737  const capped = (height: number, left: string, right: string, middle: (height: number | undefined) => RenderElement): RenderElement => {
738    if (terminal || !Svg) return middle(height)
739    const px = Math.max(4, Math.round(height * ROW_PX))
740    return (
741      <Box flexDirection="row" flexGrow={1} alignItems="stretch">
742        {cap(px, left, 'left')}
743        {middle(undefined)}
744        {cap(px, right, 'right')}
745      </Box>
746    )
747  }
748
749  /**
750   * One corner of a card's ground, RADIUS_PX square: a quarter disc in `fill`, and
751   * on a top corner with an `accent`, the disc's top ACCENT_PX in the accent. The
752   * two parts meet without overlapping, so a see-through fill isn't painted twice.
753   */
754  const corner = (fill: string, at: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right', accent?: string): RenderElement | null => {
755    if (!Svg) return null
756    const r = RADIUS_PX
757    const s = Math.min(ACCENT_PX, r)
758    // Drawn as the top-left (centre r,r), then mirrored into place.
759    const x = r - Math.sqrt(r * r - (r - s) * (r - s))
760    const top = at.startsWith('top') && accent
761    const paths = top
762      ? `<path d="M0 ${r}A${r} ${r} 0 0 1 ${x} ${s}H${r}V${r}Z" fill="${fill}"/><path d="M${x} ${s}A${r} ${r} 0 0 1 ${r} 0V${s}Z" fill="${accent}"/>`
763      : `<path d="M0 ${r}A${r} ${r} 0 0 1 ${r} 0V${r}Z" fill="${fill}"/>`
764    const flip = `scale(${at.endsWith('right') ? -1 : 1} ${at.startsWith('bottom') ? -1 : 1})`
765    const move = `translate(${at.endsWith('right') ? r : 0} ${at.startsWith('bottom') ? r : 0})`
766    const source =
767      `<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${r}" viewBox="0 0 ${r} ${r}">` +
768      `<g transform="${move} ${flip}">${paths}</g></svg>`
769    return (
770      <Box flexShrink={0}>
771        <Svg source={source} alt="rounded corner" width={r} height={r} />
772      </Box>
773    )
774  }
775
776  /** A card's top or bottom edge, RADIUS_PX tall: a corner, the stretched middle (the accent's stripe over the fill, on top), a corner. */
777  const cardEdge = (key: string, fill: string, side: 'top' | 'bottom', accent?: string): RenderElement => (
778    <Box key={key} flexDirection="row" height={RADIUS_PX / ROW_PX} flexShrink={0} alignItems="stretch">
779      {corner(fill, `${side}-left`, accent)}
780      <Box flexGrow={1} flexDirection="column">
781        {side === 'top' && accent ? <Box key="accent" height={ACCENT_PX / ROW_PX} flexShrink={0} backgroundColor={accent} /> : null}
782        <Box key="fill" flexGrow={1} backgroundColor={fill} />
783      </Box>
784      {corner(fill, `${side}-right`, accent)}
785    </Box>
786  )
787
788  /**
789   * A container with rounded corners on the app surfaces: `props` and `children`
790   * laid out as a Box, over a ground in `fill` whose corners are rounded
791   * (RADIUS_PX), with an optional `accent` (one of ACCENT) as a thin stripe along
792   * its top edge. The ground sits behind the content, so the content keeps its
793   * own size, padding and centring. In the terminal, the box without fill or
794   * accent. See "Rounding on the desktop" above.
795   */
796  const card = (fill: string, accent: string | undefined, props: Record<string, unknown>, children: RenderElement | (RenderElement | null)[] | null) =>
797    terminal ? (
798      <Box {...props}>{children}</Box>
799    ) : (
800      <Box {...props}>
801        <Box key="card-ground" position="absolute" top={0} left={0} right={0} bottom={0} flexDirection="column">
802          {cardEdge('card-top', fill, 'top', accent)}
803          <Box key="card-fill" flexGrow={1} backgroundColor={fill} />
804          {cardEdge('card-bottom', fill, 'bottom')}
805        </Box>
806        {children}
807      </Box>
808    )
809
810  /**
811   * A filled box with square corners and no border: a pill's chip. Containers
812   * (bands, lists, tiles) are `card`s, rounded. In the terminal, the box
813   * without fill.
814   */
815  const rounded = (color: string, props: Record<string, unknown>, children: RenderElement | (RenderElement | null)[] | null) =>
816    terminal ? (
817      <Box {...props}>{children}</Box>
818    ) : (
819      <Box {...props} backgroundColor={color}>
820        {children}
821      </Box>
822    )
823
824  /**
825   * A tile: one item of a list that has several lines (a branch and its PR), in its
826   * own fill a step lighter than the pane, its corners rounded (`card`), so items read as units. A
827   * `selected` tile takes a blue-tinted fill: picked, without an outline; half
828   * as tinted while the pane isn't `focused` (the kit's `focused` by default).
829   * On the terminal, a blank row above and no fill, selected or not: a terminal
830   * list that selects draws its rows with `item`, which has a selection mark.
831   */
832  const tile = (key: string, children: (RenderElement | null)[], opts: { selected?: boolean; focused?: boolean } = {}) =>
833    terminal ? (
834      <Box key={key} flexDirection="column" marginTop={1}>
835        {children}
836      </Box>
837    ) : (
838      card(
839        opts.selected ? ((opts.focused ?? paneFocused) ? FILL.selected : FILL.selectedBlurred) : FILL.tile,
840        undefined,
841        { key, flexDirection: 'column', paddingX: SPACE.item, paddingY: TILE_PAD_Y, rowGap: TILE_ROW_GAP, width: '100%' },
842        children,
843      )
844    )
845
846  /**
847   * A list item: one item of a `collapsibleList`, read in two lines, as an
848   * app's PR or thread list draws them:
849   *
850   *   [lead]  title ……………………………… right  [fold]
851   *   [mark]  subtitle  meta…  [end mark]
852   *           what the fold holds, while `open`
853   *
854   * - `lead`: a status kind, an icon key (in `leadColor`, muted by default) or an
855   *   element (a short text badge such as `P1`). It sits in a slot of fixed width
856   *   and height, centred on the title's line, so an SVG icon and a glyph or
857   *   badge take the same room and every item's title starts on one column,
858   *   whether it has a lead or not.
859   * - `title`: one line, cut with an ellipsis; `bold` for the one that leads, `dim`
860   *   for one waiting its turn.
861   * - `right`: figures (strings, dim) and controls (a ⋮ Button) on the title's
862   *   line, centred on it, at the right edge.
863   * - `subtitle`: the second line, dim; `subtitleWrap` lets it wrap on the
864   *   desktop rather than cut (the terminal breaks it between words into two
865   *   lines, the second cut). `subtitleLead` takes the lead's slot on that line (a ✓ before a
866   *   decision); `strong` draws the subtitle in the text's own colour, bold where
867   *   the surface has it (a decision called out rather than a detail).
868   *   `meta` follows it on the line (strings dim, elements such as a Link as
869   *   they are), `mark` ends it in a fixed slot centred on the line (a CI mark).
870   * - `children`: lines under the subtitle, starting under the title, shown while
871   *   `open` (or always, without `onToggle`). `onToggle` draws the fold arrow
872   *   last on the title's line, as a section's header does.
873   *
874   * No box, fill, padding or rule of its own: the `collapsibleList` it sits in
875   * pads it and draws the hairline between items.
876   * On the terminal: the lead in a 2-cell column, the title and right cluster as
877   * an `item`, the subtitle and children each a line under the title.
878   */
879  const listItem = (
880    key: string,
881    e: {
882      title: string
883      lead?: StatusKind | string | RenderElement | null
884      leadColor?: string
885      bold?: boolean
886      dim?: boolean
887      right?: (RenderElement | string | null | false)[]
888      subtitle?: string
889      subtitleWrap?: boolean
890      subtitleLead?: StatusKind | string | RenderElement | null
891      strong?: boolean
892      meta?: (RenderElement | string | null | false)[]
893      mark?: StatusKind | RenderElement | null
894      open?: boolean
895      onToggle?: () => void
896      children?: (RenderElement | null)[]
897    },
898  ): RenderElement => {
899    const glyph = (x: StatusKind | string | RenderElement | null | undefined, color?: string) =>
900      x == null ? null : typeof x === 'string' ? (x in STATUS ? status(x as StatusKind) : icon(x, color ?? MUTED)) : x
901    const shown = !e.onToggle || Boolean(e.open)
902    const kids = shown ? (e.children ?? []).filter((c): c is RenderElement => c != null) : []
903    const arrow = e.onToggle
904      ? Button
905        ? <Button key={`${key}-fold`} plain dimColor label={terminal ? (e.open ? FOLD.open : FOLD.closed) : fold(!e.open)} onPress={() => e.onToggle?.()} />
906        : <Text key={`${key}-fold`} dimColor>{terminal ? (e.open ? FOLD.open : FOLD.closed) : fold(!e.open)}</Text>
907      : null
908    const right = [...(e.right ?? []).filter((x): x is RenderElement | string => Boolean(x)), ...(arrow ? [arrow] : [])]
909    const meta = (e.meta ?? []).filter((x): x is RenderElement | string => Boolean(x))
910    const mark = e.mark == null ? null : typeof e.mark === 'string' ? status(e.mark as StatusKind) : e.mark
911    const subLook = e.strong ? { bold: true } : tone('mid')
912    if (terminal) {
913      const under = (k2: string, el: RenderElement) => (
914        <Box key={k2} paddingLeft={GUTTER} flexDirection="row" minWidth={0}>
915          {el}
916        </Box>
917      )
918      const subLead = glyph(e.subtitleLead)
919      const lead = glyph(e.lead, e.leadColor)
920      // Terminal text never wraps: a wrapping subtitle breaks between words into two lines (as `note({ lines: 2 })`), the second cut.
921      const subRoom = Math.max(1, Math.floor(body) - GUTTER - (subLead ? 1 + CELLS.pair : 0))
922      const [first, rest] = e.subtitle && e.subtitleWrap ? breakLine(e.subtitle, subRoom) : [e.subtitle ?? '', '']
923      return (
924        <Box key={key} flexDirection="column" minWidth={0}>
925          {/* Without a lead, the title takes the lead column's indent, so it lines up with the subtitle under it. */}
926          {item(`${key}-title`, { lead: lead ?? undefined, text: e.title, bold: e.bold, dim: e.dim, right, ...(lead ? {} : { indent: GUTTER }) })}
927          {e.subtitle || meta.length || mark
928            ? under(
929                `${key}-sub`,
930                <Box flexDirection="row" gap={CELLS.pair} minWidth={0}>
931                  {subLead ? <Box flexShrink={0}>{subLead}</Box> : null}
932                  {first ? (
933                    <Box flexShrink={1} minWidth={0}>
934                      <Text wrap="truncate" {...subLook}>
935                        {first}
936                      </Text>
937                    </Box>
938                  ) : null}
939                  {meta.map((m, i) => (typeof m === 'string' ? <Text key={`m${i}`} {...tone('mid')}>{m}</Text> : m))}
940                  {mark}
941                </Box>,
942              )
943            : null}
944          {rest
945            ? under(
946                `${key}-sub2`,
947                <Box flexShrink={1} minWidth={0} paddingLeft={subLead ? 1 + CELLS.pair : 0}>
948                  <Text wrap="truncate" {...subLook}>
949                    {rest}
950                  </Text>
951                </Box>,
952              )
953            : null}
954          {kids.map((c, i) => under(`${key}-more-${i}`, c))}
955        </Box>
956      )
957    }
958    // The lead's slot: a fixed width (a two-letter badge and its room) and one text line tall; each
959    // line is its own row, centred, so a slot's centre is its line's whatever that line's height.
960    const SLOT = 2 + SPACE.pair
961    const slot = (k2: string, x: RenderElement | null) => (
962      <Box key={k2} width={SLOT} height={1} flexShrink={0} flexDirection="row" alignItems="center">
963        {x}
964      </Box>
965    )
966    return (
967      <Box key={key} flexDirection="column" width="100%" minWidth={0} rowGap={TILE_ROW_GAP * 2}>
968        <Box key="title" flexDirection="row" alignItems="center" width="100%" minWidth={0} gap={0}>
969          {slot('lead', glyph(e.lead, e.leadColor))}
970          <Box flexShrink={1} flexGrow={1} width={0} minWidth={0}>
971            <Text wrap="truncate" bold={e.bold} {...(e.dim ? tone('mid') : {})}>
972              {e.title}
973            </Text>
974          </Box>
975          {right.length ? (
976            <Box flexDirection="row" alignItems="center" gap={space.item} flexShrink={0} marginLeft={space.item}>
977              {right.map((x, i) => (typeof x === 'string' ? <Text key={`r${i}`} {...tone('mid')}>{x}</Text> : x))}
978            </Box>
979          ) : null}
980        </Box>
981        {e.subtitle || meta.length || mark ? (
982          <Box key="sub" flexDirection="row" alignItems={e.subtitleWrap ? 'flex-start' : 'center'} width="100%" minWidth={0}>
983            {slot('sub-lead', glyph(e.subtitleLead))}
984            <Box flexDirection="row" alignItems="center" gap={SPACE.pair} flexShrink={1} flexGrow={1} width={0} minWidth={0}>
985              {e.subtitle ? (
986                <Box flexShrink={1} minWidth={0}>
987                  <Text wrap={e.subtitleWrap ? 'wrap' : 'truncate'} {...subLook}>
988                    {e.subtitle}
989                  </Text>
990                </Box>
991              ) : null}
992              {meta.map((m, i) =>
993                typeof m === 'string' ? (
994                  <Text key={`m${i}`} {...tone('mid')}>
995                    {m}
996                  </Text>
997                ) : (
998                  m
999                ),
1000              )}
1001              {mark ? (
1002                <Box key="mark" width={2} height={1} flexShrink={0} flexDirection="row" alignItems="center">
1003                  {mark}
1004                </Box>
1005              ) : null}
1006            </Box>
1007          </Box>
1008        ) : null}
1009        {kids.length ? (
1010          <Box key="more" flexDirection="column" paddingLeft={SLOT} minWidth={0} rowGap={TILE_ROW_GAP * 2}>
1011            {kids}
1012          </Box>
1013        ) : null}
1014      </Box>
1015    )
1016  }
1017
1018  /**
1019   * A collapsible list: a section whose body is a list of items (`listItem`s, or a
1020   * `note` when there are none), drawn as one surface. The header (icon, title,
1021   * figures, the fold arrow last) and the items share one quiet fill (FILL.tile),
1022   * a hairline (TRACK, HAIRLINE tall, as the tabs' rule) under the header and
1023   * between items, each item padded alike. No band on the pane with tiles under
1024   * it: one thing, one fill. On the app surfaces the surface's corners are rounded
1025   * (`card`), its title one step up the type scale (`heading`), and an `accent`
1026   * draws a thin stripe along its top edge.
1027   *
1028   * Folded, only the header shows. `section` stays for bodies that aren't a list
1029   * (readings, bars, props); this is a list's section.
1030   * On the terminal it's a `section` with the items stacked under it, no rules:
1031   * the two-line rhythm and the indent separate them.
1032   */
1033  const collapsibleList = (s: {
1034    id: string
1035    title: string
1036    icon?: string
1037    right?: RenderElement | null
1038    collapsed?: boolean
1039    onToggle?: () => void
1040    loading?: boolean
1041    /** A colour from ACCENT, drawn as a thin stripe along the surface's top edge on the app surfaces; the terminal draws none. */
1042    accent?: string
1043    items: (RenderElement | null | false)[]
1044  }) => {
1045    const items = s.items.filter((x): x is RenderElement => Boolean(x))
1046    if (terminal) {
1047      return section({ id: s.id, title: s.title, icon: s.icon, right: s.right, collapsed: s.collapsed, onToggle: s.onToggle, loading: s.loading, children: items })
1048    }
1049    const right = s.right ?? (s.loading ? summary([], { loading: true }) : null)
1050    const arrow = fold(Boolean(s.collapsed))
1051    const toggle =
1052      s.onToggle && Button ? (
1053        <Button key={`toggle-${s.id}`} plain dimColor label={arrow} onPress={() => s.onToggle?.()} />
1054      ) : (
1055        <Text dimColor>{arrow}</Text>
1056      )
1057    const rule = (key: string) => <Box key={key} height={HAIRLINE} flexShrink={0} backgroundColor={TRACK} />
1058    const header = (
1059      <Box key="head" flexDirection="row" justifyContent="space-between" alignItems="center" gap={SPACE.item} paddingX={INSET} height={BAND_ROWS} flexShrink={0} overflow="hidden">
1060        <Box flexDirection="row" alignItems="center" flexShrink={0}>
1061          {s.icon ? (
1062            <Box width={2} flexShrink={0} flexDirection="row" alignItems="center">
1063              {icon(s.icon, MUTED)}
1064            </Box>
1065          ) : null}
1066          <Text wrap="truncate" bold size="heading">
1067            {s.title}
1068          </Text>
1069        </Box>
1070        <Box flexDirection="row" alignItems="center" justifyContent="flex-end" gap={SPACE.item} minWidth={0} flexShrink={1}>
1071          {right ? (
1072            <Box flexDirection="row" minWidth={0} flexShrink={1} overflow="hidden">
1073              {right}
1074            </Box>
1075          ) : null}
1076          <Box minWidth={1.6} flexShrink={0} flexDirection="row" justifyContent="flex-end">
1077            {toggle}
1078          </Box>
1079        </Box>
1080      </Box>
1081    )
1082    const body = s.collapsed
1083      ? []
1084      : items.flatMap((x, i) => [
1085          rule(`rule-${i}`),
1086          <Box key={`item-${i}`} flexDirection="column" width="100%" minWidth={0} paddingX={INSET} paddingY={TILE_PAD_Y}>
1087            {x}
1088          </Box>,
1089        ])
1090    return (
1091      <Box key={`list-${s.id}`} flexDirection="column" marginTop={1}>
1092        {card(FILL.tile, s.accent, { flexDirection: 'column', width: '100%', minWidth: 0 }, [header, ...body])}
1093      </Box>
1094    )
1095  }
1096
1097  /**
1098   * A thin bar: parts left to right out of `max`, the rest as track. On the
1099   * terminal one row `width` cells wide (a section body's width by default): the
1100   * gauge's heavy line, each part in its own colour, `room` parts and the rest
1101   * as the light rail (see `lineBar`).
1102   */
1103  const bar = (parts: Part[], max: number, opts: { height?: number; width?: number } = {}): RenderElement => {
1104    const total = Math.max(max, parts.reduce((n, p) => n + Math.max(0, p.value), 0), 1)
1105    if (terminal) {
1106      const w = opts.width ?? body
1107      return lineBar(parts, total, w)
1108    }
1109    // Grow factors out of 1000 (the desktop caps them at 10000): finer than a pixel at any width.
1110    // Rounded by SVG end caps around a flat middle. Borders can't round it: on the desktop a
1111    // border takes room inside the box, so a thin bordered track draws empty and bordered fills
1112    // draw as blobs; glyph bars (◖━◗, ╺━╸) don't draw at all.
1113    const height = opts.height ?? BAR
1114    const shown = parts.filter(p => p.value > 0).map(p => ({ ...p, grow: (p.value / total) * 1000 }))
1115    const rest = Math.max(0, 1000 - shown.reduce((n, p) => n + p.grow, 0))
1116    // Not `h`: that's the JSX factory.
1117    const flat = (rows: number | undefined) => (
1118      <Box flexDirection="row" flexGrow={1} height={rows} backgroundColor={TRACK} overflow="hidden">
1119        {/* An explicit full height: the desktop doesn't stretch a child to its parent's height. */}
1120        {shown.map(p => (
1121          <Box flexGrow={p.grow} flexShrink={0} width={0} height="100%" backgroundColor={p.color} />
1122        ))}
1123        {rest > 0 ? <Box flexGrow={rest} width={0} /> : null}
1124      </Box>
1125    )
1126    // The caps sit inside the bar's width, so a scale under it still lines up with its ends.
1127    const first = shown[0]?.color ?? TRACK
1128    const last = rest > 0 ? TRACK : (shown[shown.length - 1]?.color ?? TRACK)
1129    return capped(height, first, last, flat)
1130  }
1131
1132  /**
1133   * A label as GitHub draws one: a rounded chip filled with the label's colour,
1134   * faint and see-through (FILL.pill), and its name in the theme's foreground, which
1135   * reads on the light desktop theme and the dark one whatever the label's colour
1136   * (a label without a hex colour gets the track's grey). On the
1137   * terminal, a `■` swatch and the name in the default foreground: a label's
1138   * colour is data (GitHub's hex) that may not read on the person's theme, so it
1139   * only ever tints the one-cell swatch, never the text. A status colour (a kit
1140   * token) draws as its theme key, as everywhere.
1141   */
1142  const pill = (key: string, text: string, color: string) => {
1143    if (terminal) {
1144      return (
1145        <Text key={key}>
1146          <Text {...(isKitColor(color) ? ink(color) : { color })}>■</Text>
1147          {` ${text}`}
1148        </Text>
1149      )
1150    }
1151    return rounded(tint(color, FILL.pill) ?? TRACK, { key, flexDirection: 'row', paddingX: 0.6, flexShrink: 0 }, [<Text key="t">{text}</Text>])
1152  }
1153
1154  /**
1155   * A small mark of colour, a legend's key: a dot on the app surfaces, a square
1156   * `■` on the terminal. `line: true` keys a line bar's part (`k.bar`) on the
1157   * terminal with its own glyph: `━` for a part, `─` for a `room` one.
1158   */
1159  const swatch = (color: string, o: { line?: boolean; room?: boolean } = {}) => (
1160    <Text {...ink(color)}>{terminal ? (o.line ? (o.room ? METER.rail : METER.line) : '■') : '●'}</Text>
1161  )
1162
1163  /**
1164   * A legend: each entry a key, a dim label and its figure. `note` is an optional
1165   * coloured figure after it (a failure count). With `bar: true` (a legend that
1166   * keys a `bar`, its items in the bar's order, `room` ones included) the
1167   * terminal's keys are the bar's own glyphs, `━` and `─`.
1168   *
1169   * On the terminal it's a compact grid, filled row by row in the items' order:
1170   * as many columns as fit with labels up to 10 cells (`maxCols`, 3 at most),
1171   * 3 cells apart; then each column takes its share of the row, up to what its
1172   * longest label, figure and note need, so labels widen into spare room and are
1173   * cut with … only when it runs out, and a label stays close to its figure. The app surfaces
1174   * share the row out in up to three columns.
1175   */
1176  const legend = (
1177    key: string,
1178    items: { label: string; color: string; figure: string; note?: string; noteColor?: string; room?: boolean }[],
1179    maxCols?: number,
1180    opts: { bar?: boolean } = {},
1181  ) => {
1182    if (terminal) {
1183      const len = (s: string) => [...s].length
1184      const longest = Math.max(1, ...items.map(t => len(t.label)))
1185      const figW = Math.max(1, ...items.map(t => len(t.figure)))
1186      const noteW = Math.max(0, ...items.map(t => (t.note ? len(t.note) + 1 : 0)))
1187      const fixed = 2 + 1 + figW + noteW
1188      const gap = 3
1189      // How many columns fit is decided at the compact width (labels up to LABEL cells)...
1190      const compact = fixed + Math.min(LABEL, longest)
1191      const fit = Math.max(1, Math.floor((body + gap) / (compact + gap)))
1192      const cols = Math.max(1, Math.min(maxCols ?? 3, fit, items.length))
1193      const rows = Array.from({ length: Math.ceil(items.length / cols) }, (_, r) => items.slice(r * cols, r * cols + cols))
1194      // ...then each column takes its share of the row, up to what its longest label needs,
1195      // and the label has what's left after the key, figure and note.
1196      const share = Math.floor((body - gap * (cols - 1)) / cols)
1197      const width = Math.max(1, Math.min(fixed + longest, share))
1198      const labelRoom = Math.max(1, width - fixed)
1199      const fitLabel = (s: string) => (len(s) <= labelRoom ? s : [...s].slice(0, Math.max(0, labelRoom - 1)).join('') + MARK.more)
1200      return (
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
kit/icons.ts 202 lines
1import { GLYPH } from './tokens'
2import type { Duo } from './tokens'
3
4/*
5 * The kit's icons: stroked drawings on a 16×16 grid, drawn as SVG at one exact
6 * pixel size so every icon is the same height and width and stays crisp (an SVG
7 * the page has to scale blurs). Keyed by the glyph each one stands in for, so a
8 * component given a GLYPH draws the icon where the surface has SVG, the glyph
9 * where it doesn't (the terminal).
10 */
11
12/** The icons' drawn size in CSS pixels. */
13export const ICON_PX = 13
14
15const PATHS: Record<string, string> = {
16  // A pie a quarter cut: how full.
17  [GLYPH.context]: '<circle cx="8" cy="8" r="6"/><path d="M8 2v6h6"/>',
18  [GLYPH.time]: '<circle cx="8" cy="8" r="6"/><path d="M8 4.5V8l2.5 1.5"/>',
19  [GLYPH.turns]: '<path d="M13 8a5 5 0 1 1-1.6-3.7"/><path d="M13 2.5v3.2H9.8"/>',
20  [GLYPH.tools]: '<path d="M10.5 2.5a3 3 0 0 0-3.3 4.1L2.6 11.2l2.2 2.2 4.6-4.6a3 3 0 0 0 4.1-3.3l-1.9 1.9-1.9-.4-.4-1.9z"/>',
21  [GLYPH.files]: '<path d="M3 13l.9-3.4L10.8 2.7l2.5 2.5-6.9 6.9z"/>',
22  [GLYPH.agents]: '<path d="M8 2l1.4 4.6L14 8l-4.6 1.4L8 14l-1.4-4.6L2 8l4.6-1.4z"/>',
23  // A gauge: a dial three-quarters round, open at the bottom, centred like the
24  // other icons (a half dial sat low in its square and read as cut off), and a needle.
25  [GLYPH.limits]: '<path d="M3.76 12.24a6 6 0 1 1 8.48 0"/><path d="M8 8l2.6-2.6"/>',
26  [GLYPH.cost]: '<circle cx="8" cy="8" r="6"/><path d="M10 6.2c-.4-.8-1.2-1.2-2-1.2-1.1 0-2 .6-2 1.5S6.9 7.8 8 8s2 .6 2 1.5-.9 1.5-2 1.5c-.8 0-1.6-.4-2-1.2M8 4v1M8 11v1"/>',
27  // Events: a bolt.
28  events: '<path d="M9 1.5L3.5 9H8l-1 5.5L12.5 7H8z"/>',
29}
30
31/**
32 * GitHub's own icons for branches and pull requests: Octicons (`@primer/octicons`
33 * 19.15.0, `*-16.svg`, MIT, © GitHub Inc.), copied unchanged. Filled shapes, not
34 * strokes, so they're drawn filled in the icon's colour.
35 */
36const FILLED: Record<string, string> = {
37  [GLYPH.branch]:
38    'M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z',
39  'pr-open':
40    'M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z',
41  'pr-merged':
42    'M5.45 5.154A4.25 4.25 0 0 0 9.25 7.5h1.378a2.251 2.251 0 1 1 0 1.5H9.25A5.734 5.734 0 0 1 5 7.123v3.505a2.25 2.25 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.95-.218ZM4.25 13.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm8.5-4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5ZM5 3.25a.75.75 0 1 0 0 .005V3.25Z',
43  'pr-closed':
44    'M3.25 1A2.25 2.25 0 0 1 4 5.372v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.251 2.251 0 0 1 3.25 1Zm9.5 5.5a.75.75 0 0 1 .75.75v3.378a2.251 2.251 0 1 1-1.5 0V7.25a.75.75 0 0 1 .75-.75Zm-2.03-5.273a.75.75 0 0 1 1.06 0l.97.97.97-.97a.748.748 0 0 1 1.265.332.75.75 0 0 1-.205.729l-.97.97.97.97a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-.97-.97-.97.97a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l.97-.97-.97-.97a.75.75 0 0 1 0-1.06ZM2.5 3.25a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0ZM3.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm9.5 0a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z',
45  'issue-opened': 'M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z',
46  comment:
47    'M1 2.75C1 1.784 1.784 1 2.75 1h10.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 13.25 12H9.06l-2.573 2.573A1.458 1.458 0 0 1 4 13.543V12H2.75A1.75 1.75 0 0 1 1 10.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h4.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z',
48  'pr-draft':
49    'M3.25 1A2.25 2.25 0 0 1 4 5.372v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.251 2.251 0 0 1 3.25 1Zm9.5 14a2.25 2.25 0 1 1 0-4.5 2.25 2.25 0 0 1 0 4.5ZM2.5 3.25a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0ZM3.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm9.5 0a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM14 7.5a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Zm0-4.25a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Z',
50  // Files and folders, for trees of them.
51  file: 'M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z',
52  'file-code':
53    'M4 1.75C4 .784 4.784 0 5.75 0h5.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v8.586A1.75 1.75 0 0 1 14.25 15h-9a.75.75 0 0 1 0-1.5h9a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 10 4.25V1.5H5.75a.25.25 0 0 0-.25.25v2.5a.75.75 0 0 1-1.5 0Zm1.72 4.97a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l1.47-1.47-1.47-1.47a.75.75 0 0 1 0-1.06ZM3.28 7.78 1.81 9.25l1.47 1.47a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-2-2a.75.75 0 0 1 0-1.06l2-2a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Zm8.22-6.218V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z',
54  folder: 'M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z',
55  'folder-open':
56    'M.513 1.513A1.75 1.75 0 0 1 1.75 1h3.5c.55 0 1.07.26 1.4.7l.9 1.2a.25.25 0 0 0 .2.1H13a1 1 0 0 1 1 1v.5H2.75a.75.75 0 0 0 0 1.5h11.978a1 1 0 0 1 .994 1.117L15 13.25A1.75 1.75 0 0 1 13.25 15H1.75A1.75 1.75 0 0 1 0 13.25V2.75c0-.464.184-.91.513-1.237Z',
57  // Git and the actions on a tree or a command.
58  'git-commit': 'M11.93 8.5a4.002 4.002 0 0 1-7.86 0H.75a.75.75 0 0 1 0-1.5h3.32a4.002 4.002 0 0 1 7.86 0h3.32a.75.75 0 0 1 0 1.5Zm-1.43-.75a2.5 2.5 0 1 0-5 0 2.5 2.5 0 0 0 5 0Z',
59  'repo-push':
60    'M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0V1.5h-8a1 1 0 0 0-1 1v6.708A2.493 2.493 0 0 1 4.5 9h2.25a.75.75 0 0 1 0 1.5H4.5a1 1 0 0 0 0 2h4.75a.75.75 0 0 1 0 1.5H4.5A2.5 2.5 0 0 1 2 11.5Zm12.23 7.79h-.001l-1.224-1.224v6.184a.75.75 0 0 1-1.5 0V9.066L10.28 10.29a.75.75 0 0 1-1.06-1.061l2.505-2.504a.75.75 0 0 1 1.06 0L15.29 9.23a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018Z',
61  alert:
62    'M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z',
63  trash:
64    'M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z',
65  search:
66    'M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z',
67  sync: 'M1.705 8.005a.75.75 0 0 1 .834.656 5.5 5.5 0 0 0 9.592 2.97l-1.204-1.204a.25.25 0 0 1 .177-.427h3.646a.25.25 0 0 1 .25.25v3.646a.25.25 0 0 1-.427.177l-1.38-1.38A7.002 7.002 0 0 1 1.05 8.84a.75.75 0 0 1 .656-.834ZM8 2.5a5.487 5.487 0 0 0-4.131 1.869l1.204 1.204A.25.25 0 0 1 4.896 6H1.25A.25.25 0 0 1 1 5.75V2.104a.25.25 0 0 1 .427-.177l1.38 1.38A7.002 7.002 0 0 1 14.95 7.16a.75.75 0 0 1-1.49.178A5.5 5.5 0 0 0 8 2.5Z',
68  'arrow-up':
69    'M3.47 7.78a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0l4.25 4.25a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018L9 4.81v7.44a.75.75 0 0 1-1.5 0V4.81L4.53 7.78a.75.75 0 0 1-1.06 0Z',
70  home: 'M6.906.664a1.749 1.749 0 0 1 2.187 0l5.25 4.2c.415.332.657.835.657 1.367v7.019A1.75 1.75 0 0 1 13.25 15h-3.5a.75.75 0 0 1-.75-.75V9H7v5.25a.75.75 0 0 1-.75.75h-3.5A1.75 1.75 0 0 1 1 13.25V6.23c0-.531.242-1.034.657-1.366l5.25-4.2Zm1.25 1.171a.25.25 0 0 0-.312 0l-5.25 4.2a.25.25 0 0 0-.094.196v7.019c0 .138.112.25.25.25H5.5V8.25a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 .75.75v5.25h2.75a.25.25 0 0 0 .25-.25V6.23a.25.25 0 0 0-.094-.195Z',
71  eye: 'M8 2c1.981 0 3.671.992 4.933 2.078 1.27 1.091 2.187 2.345 2.637 3.023a1.62 1.62 0 0 1 0 1.798c-.45.678-1.367 1.932-2.637 3.023C11.67 13.008 9.981 14 8 14c-1.981 0-3.671-.992-4.933-2.078C1.797 10.83.88 9.576.43 8.898a1.62 1.62 0 0 1 0-1.798c.45-.677 1.367-1.931 2.637-3.022C4.33 2.992 6.019 2 8 2ZM1.679 7.932a.12.12 0 0 0 0 .136c.411.622 1.241 1.75 2.366 2.717C5.176 11.758 6.527 12.5 8 12.5c1.473 0 2.825-.742 3.955-1.715 1.124-.967 1.954-2.096 2.366-2.717a.12.12 0 0 0 0-.136c-.412-.621-1.242-1.75-2.366-2.717C10.824 4.242 9.473 3.5 8 3.5c-1.473 0-2.825.742-3.955 1.715-1.124.967-1.954 2.096-2.366 2.717ZM8 10a2 2 0 1 1-.001-3.999A2 2 0 0 1 8 10Z',
72  // What an agent's tool call is doing: a command, an edit, the web, an MCP server, anything else.
73  terminal:
74    'M0 2.75C0 1.784.784 1 1.75 1h12.5c.966 0 1.75.784 1.75 1.75v10.5A1.75 1.75 0 0 1 14.25 15H1.75A1.75 1.75 0 0 1 0 13.25Zm1.75-.25a.25.25 0 0 0-.25.25v10.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V2.75a.25.25 0 0 0-.25-.25ZM7.25 8a.749.749 0 0 1-.22.53l-2.25 2.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L5.44 8 3.72 6.28a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l2.25 2.25c.141.14.22.331.22.53Zm1.5 1.5h3a.75.75 0 0 1 0 1.5h-3a.75.75 0 0 1 0-1.5Z',
75  pencil:
76    'M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z',
77  globe:
78    'M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM5.78 8.75a9.64 9.64 0 0 0 1.363 4.177c.255.426.542.832.857 1.215.245-.296.551-.705.857-1.215A9.64 9.64 0 0 0 10.22 8.75Zm4.44-1.5a9.64 9.64 0 0 0-1.363-4.177c-.307-.51-.612-.919-.857-1.215a9.927 9.927 0 0 0-.857 1.215A9.64 9.64 0 0 0 5.78 7.25Zm-5.944 1.5H1.543a6.507 6.507 0 0 0 4.666 5.5c-.123-.181-.24-.365-.352-.552-.715-1.192-1.437-2.874-1.581-4.948Zm-2.733-1.5h2.733c.144-2.074.866-3.756 1.58-4.948.12-.197.237-.381.353-.552a6.507 6.507 0 0 0-4.666 5.5Zm10.181 1.5c-.144 2.074-.866 3.756-1.58 4.948-.12.197-.237.381-.353.552a6.507 6.507 0 0 0 4.666-5.5Zm2.733-1.5a6.507 6.507 0 0 0-4.666-5.5c.123.181.24.365.353.552.714 1.192 1.436 2.874 1.58 4.948Z',
79  plug: 'M4 8H2.5a1 1 0 0 0-1 1v5.25a.75.75 0 0 1-1.5 0V9a2.5 2.5 0 0 1 2.5-2.5H4V5.133a1.75 1.75 0 0 1 1.533-1.737l2.831-.353.76-.913c.332-.4.825-.63 1.344-.63h.782c.966 0 1.75.784 1.75 1.75V4h2.25a.75.75 0 0 1 0 1.5H13v4h2.25a.75.75 0 0 1 0 1.5H13v.75a1.75 1.75 0 0 1-1.75 1.75h-.782c-.519 0-1.012-.23-1.344-.63l-.761-.912-2.83-.354A1.75 1.75 0 0 1 4 9.867Zm6.276-4.91-.95 1.14a.753.753 0 0 1-.483.265l-3.124.39a.25.25 0 0 0-.219.248v4.734c0 .126.094.233.219.249l3.124.39a.752.752 0 0 1 .483.264l.95 1.14a.25.25 0 0 0 .192.09h.782a.25.25 0 0 0 .25-.25v-8.5a.25.25 0 0 0-.25-.25h-.782a.25.25 0 0 0-.192.09Z',
80  'dot-fill': 'M8 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Z',
81  // Kinds of agent: one that writes code, a worker, a quick fix, a reviewer, an explorer,
82  // a planner, a general one, a guide.
83  code: 'm11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z',
84  tools:
85    'M5.433 2.304A4.492 4.492 0 0 0 3.5 6c0 1.598.832 3.002 2.09 3.802.518.328.929.923.902 1.64v.008l-.164 3.337a.75.75 0 1 1-1.498-.073l.163-3.33c.002-.085-.05-.216-.207-.316A5.996 5.996 0 0 1 2 6a5.993 5.993 0 0 1 2.567-4.92 1.482 1.482 0 0 1 1.673-.04c.462.296.76.827.76 1.423v2.82c0 .082.041.16.11.206l.75.51a.25.25 0 0 0 .28 0l.75-.51A.249.249 0 0 0 9 5.282V2.463c0-.596.298-1.127.76-1.423a1.482 1.482 0 0 1 1.673.04A5.993 5.993 0 0 1 14 6a5.996 5.996 0 0 1-2.786 5.068c-.157.1-.209.23-.207.315l.163 3.33a.752.752 0 0 1-1.094.714.75.75 0 0 1-.404-.64l-.164-3.345c-.027-.717.384-1.312.902-1.64A4.495 4.495 0 0 0 12.5 6a4.492 4.492 0 0 0-1.933-3.696c-.024.017-.067.067-.067.16v2.818a1.75 1.75 0 0 1-.767 1.448l-.75.51a1.75 1.75 0 0 1-1.966 0l-.75-.51A1.75 1.75 0 0 1 5.5 5.282V2.463c0-.092-.043-.142-.067-.159Z',
86  zap: 'M9.504.43a1.516 1.516 0 0 1 2.437 1.713L10.415 5.5h2.123c1.57 0 2.346 1.909 1.22 3.004l-7.34 7.142a1.249 1.249 0 0 1-.871.354h-.302a1.25 1.25 0 0 1-1.157-1.723L5.633 10.5H3.462c-1.57 0-2.346-1.909-1.22-3.004L9.503.429Zm1.047 1.074L3.286 8.571A.25.25 0 0 0 3.462 9H6.75a.75.75 0 0 1 .694 1.034l-1.713 4.188 6.982-6.793A.25.25 0 0 0 12.538 7H9.25a.75.75 0 0 1-.683-1.06l2.008-4.418.003-.006a.036.036 0 0 0-.004-.009l-.006-.006-.008-.001c-.003 0-.006.002-.009.004Z',
87  checklist:
88    'M2.5 1.75v11.5c0 .138.112.25.25.25h3.17a.75.75 0 0 1 0 1.5H2.75A1.75 1.75 0 0 1 1 13.25V1.75C1 .784 1.784 0 2.75 0h8.5C12.216 0 13 .784 13 1.75v7.736a.75.75 0 0 1-1.5 0V1.75a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13.274 9.537v-.001l-4.557 4.45a.75.75 0 0 1-1.055-.008l-1.943-1.95a.75.75 0 0 1 1.062-1.058l1.419 1.425 4.026-3.932a.75.75 0 1 1 1.048 1.074ZM4.75 4h4.5a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1 0-1.5ZM4 7.75A.75.75 0 0 1 4.75 7h2a.75.75 0 0 1 0 1.5h-2A.75.75 0 0 1 4 7.75Z',
89  telescope:
90    'M14.184 1.143v-.001l1.422 2.464a1.75 1.75 0 0 1-.757 2.451L3.104 11.713a1.75 1.75 0 0 1-2.275-.702l-.447-.775a1.75 1.75 0 0 1 .53-2.32L11.682.573a1.748 1.748 0 0 1 2.502.57Zm-4.709 9.32h-.001l2.644 3.863a.75.75 0 1 1-1.238.848l-1.881-2.75v2.826a.75.75 0 0 1-1.5 0v-2.826l-1.881 2.75a.75.75 0 1 1-1.238-.848l2.049-2.992a.746.746 0 0 1 .293-.253l1.809-.87a.749.749 0 0 1 .944.252ZM9.436 3.92h-.001l-4.97 3.39.942 1.63 5.42-2.61Zm3.091-2.108h.001l-1.85 1.26 1.505 2.605 2.016-.97a.247.247 0 0 0 .13-.151.247.247 0 0 0-.022-.199l-1.422-2.464a.253.253 0 0 0-.161-.119.254.254 0 0 0-.197.038ZM1.756 9.157a.25.25 0 0 0-.075.33l.447.775a.25.25 0 0 0 .325.1l1.598-.769-.83-1.436-1.465 1Z',
91  tasklist:
92    'M2 2h4a1 1 0 0 1 1 1v4a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Zm4.655 8.595a.75.75 0 0 1 0 1.06L4.03 14.28a.75.75 0 0 1-1.06 0l-1.5-1.5a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l.97.97 2.095-2.095a.75.75 0 0 1 1.06 0ZM9.75 2.5h5.5a.75.75 0 0 1 0 1.5h-5.5a.75.75 0 0 1 0-1.5Zm0 5h5.5a.75.75 0 0 1 0 1.5h-5.5a.75.75 0 0 1 0-1.5Zm0 5h5.5a.75.75 0 0 1 0 1.5h-5.5a.75.75 0 0 1 0-1.5Zm-7.25-9v3h3v-3Z',
93  hubot:
94    'M0 8a8 8 0 0 1 16 0v5.25a.75.75 0 0 1-1.5 0V8a6.5 6.5 0 1 0-13 0v5.25a.75.75 0 0 1-1.5 0Zm3-1.25C3 5.784 3.784 5 4.75 5h6.5c.966 0 1.75.784 1.75 1.75v1.5A1.75 1.75 0 0 1 11.25 10h-6.5A1.75 1.75 0 0 1 3 8.25Zm1.47-.53a.75.75 0 0 0 0 1.06l1.5 1.5a.75.75 0 0 0 1.06 0L8 7.81l.97.97a.75.75 0 0 0 1.06 0l1.5-1.5a.749.749 0 0 0-.326-1.275.749.749 0 0 0-.734.215l-.97.97-.97-.97a.75.75 0 0 0-1.06 0l-.97.97-.97-.97a.75.75 0 0 0-1.06 0Zm1.03 6.03a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75Z',
95  book: 'M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z',
96  fold: 'M10.896 2H8.75V.75a.75.75 0 0 0-1.5 0V2H5.104a.25.25 0 0 0-.177.427l2.896 2.896a.25.25 0 0 0 .354 0l2.896-2.896A.25.25 0 0 0 10.896 2ZM8.75 15.25a.75.75 0 0 1-1.5 0V14H5.104a.25.25 0 0 1-.177-.427l2.896-2.896a.25.25 0 0 1 .354 0l2.896 2.896a.25.25 0 0 1-.177.427H8.75v1.25Zm-6.5-6.5a.75.75 0 0 0 0-1.5h-.5a.75.75 0 0 0 0 1.5h.5ZM6 8a.75.75 0 0 1-.75.75h-.5a.75.75 0 0 1 0-1.5h.5A.75.75 0 0 1 6 8Zm2.25.75a.75.75 0 0 0 0-1.5h-.5a.75.75 0 0 0 0 1.5h.5ZM12 8a.75.75 0 0 1-.75.75h-.5a.75.75 0 0 1 0-1.5h.5A.75.75 0 0 1 12 8Zm2.25.75a.75.75 0 0 0 0-1.5h-.5a.75.75 0 0 0 0 1.5h.5Z',
97}
98
99/**
100 * Where a branch's upstream lives, by the remote's host: GitHub's mark and a
101 * generic remote (a cloud) are Octicons (`@primer/octicons`, `mark-github-16.svg`
102 * and `cloud-16.svg`, MIT, © GitHub Inc.); GitLab's and Forgejo's marks are from
103 * Simple Icons (`icons/gitlab.svg`, `icons/forgejo.svg`, CC0 1.0), on their
104 * 24×24 grid. All copied unchanged, drawn filled in the icon's colour.
105 */
106const HOSTS: Record<string, { d: string; grid: number }> = {
107  'mark-github': {
108    grid: 16,
109    d: 'M6.766 11.328c-2.063-.25-3.516-1.734-3.516-3.656 0-.781.281-1.625.75-2.188-.203-.515-.172-1.609.063-2.062.625-.078 1.468.25 1.968.703.594-.187 1.219-.281 1.985-.281.765 0 1.39.094 1.953.265.484-.437 1.344-.765 1.969-.687.218.422.25 1.515.046 2.047.5.593.766 1.39.766 2.203 0 1.922-1.453 3.375-3.547 3.64.531.344.89 1.094.89 1.954v1.625c0 .468.391.734.86.547C13.781 14.359 16 11.53 16 8.03 16 3.61 12.406 0 7.984 0 3.563 0 0 3.61 0 8.031a7.88 7.88 0 0 0 5.172 7.422c.422.156.828-.125.828-.547v-1.25c-.219.094-.5.156-.75.156-1.031 0-1.64-.562-2.078-1.609-.172-.422-.36-.672-.719-.719-.187-.015-.25-.093-.25-.187 0-.188.313-.328.625-.328.453 0 .844.281 1.25.86.313.452.64.655 1.031.655s.641-.14 1-.5c.266-.265.47-.5.657-.656',
110  },
111  cloud: {
112    grid: 16,
113    d: 'M2 7.25A5.225 5.225 0 0 1 7.25 2a5.222 5.222 0 0 1 4.767 3.029A4.472 4.472 0 0 1 16 9.5c0 2.505-1.995 4.5-4.5 4.5h-8A3.474 3.474 0 0 1 0 10.5c0-1.41.809-2.614 2.001-3.17Zm1.54.482a.75.75 0 0 1-.556.832c-.86.22-1.484.987-1.484 1.936 0 1.124.876 2 2 2h8c1.676 0 3-1.324 3-3s-1.324-3-3-3a.75.75 0 0 1-.709-.504A3.72 3.72 0 0 0 7.25 3.5C5.16 3.5 3.5 5.16 3.5 7.25c.002.146.014.292.035.436l.004.036.001.008Z',
114  },
115  gitlab: {
116    grid: 24,
117    d: 'm23.6004 9.5927-.0337-.0862L20.3.9814a.851.851 0 0 0-.3362-.405.8748.8748 0 0 0-.9997.0539.8748.8748 0 0 0-.29.4399l-2.2055 6.748H7.5375l-2.2057-6.748a.8573.8573 0 0 0-.29-.4412.8748.8748 0 0 0-.9997-.0537.8585.8585 0 0 0-.3362.4049L.4332 9.5015l-.0325.0862a6.0657 6.0657 0 0 0 2.0119 7.0105l.0113.0087.03.0213 4.976 3.7264 2.462 1.8633 1.4995 1.1321a1.0085 1.0085 0 0 0 1.2197 0l1.4995-1.1321 2.4619-1.8633 5.006-3.7489.0125-.01a6.0682 6.0682 0 0 0 2.0094-7.003z',
118  },
119  forgejo: {
120    grid: 24,
121    d: 'M16.7773 0c1.6018 0 2.9004 1.2986 2.9004 2.9005s-1.2986 2.9004-2.9004 2.9004c-1.0854 0-2.0315-.596-2.5288-1.4787H12.91c-2.3322 0-4.2272 1.8718-4.2649 4.195l-.0007 2.1175a7.0759 7.0759 0 0 1 4.148-1.4205l.1176-.001 1.3385.0002c.4973-.8827 1.4434-1.4788 2.5288-1.4788 1.6018 0 2.9004 1.2986 2.9004 2.9005s-1.2986 2.9004-2.9004 2.9004c-1.0854 0-2.0315-.596-2.5288-1.4787H12.91c-2.3322 0-4.2272 1.8718-4.2649 4.195l-.0007 2.319c.8827.4973 1.4788 1.4434 1.4788 2.5287 0 1.602-1.2986 2.9005-2.9005 2.9005-1.6018 0-2.9004-1.2986-2.9004-2.9005 0-1.0853.596-2.0314 1.4788-2.5287l-.0002-9.9831c0-3.887 3.1195-7.0453 6.9915-7.108l.1176-.001h1.3385C14.7458.5962 15.692 0 16.7773 0ZM7.2227 19.9052c-.6596 0-1.1943.5347-1.1943 1.1943s.5347 1.1943 1.1943 1.1943 1.1944-.5347 1.1944-1.1943-.5348-1.1943-1.1944-1.1943Zm9.5546-10.4644c-.6596 0-1.1944.5347-1.1944 1.1943s.5348 1.1943 1.1944 1.1943c.6596 0 1.1943-.5347 1.1943-1.1943s-.5347-1.1943-1.1943-1.1943Zm0-7.7346c-.6596 0-1.1944.5347-1.1944 1.1943s.5348 1.1943 1.1944 1.1943c.6596 0 1.1943-.5347 1.1943-1.1943s-.5347-1.1943-1.1943-1.1943Z',
122  },
123}
124
125/**
126 * Each named icon's glyph on the terminal: one cell wide, from Unicode blocks
127 * monospace fonts carry (geometric shapes, arrows, box drawing, a few dingbats),
128 * never one with an emoji presentation (⚠ ⚡ ◼ draw as emoji in some terminals).
129 * A GLYPH key is its own glyph.
130 */
131export const TERM_GLYPH: Readonly<Record<string, string>> = {
132  events: '↯',
133  'issue-opened': '◉',
134  comment: '≡',
135  'pr-open': GLYPH.pr,
136  'pr-merged': '◆',
137  'pr-closed': GLYPH.failed,
138  'pr-draft': GLYPH.pending,
139  file: '□',
140  'file-code': '□',
141  // A tree shows a folder by its fold: closed points right, open points down.
142  folder: '▸',
143  'folder-open': '▾',
144  'git-commit': '○',
145  'repo-push': GLYPH.up,
146  alert: '▲',
147  trash: '⌫',
148  search: '⌕',
149  sync: GLYPH.turns,
150  'arrow-up': GLYPH.up,
151  home: '⌂',
152  eye: '◎',
153  // ⇕, not ↕: ↕ has an emoji presentation.
154  fold: '⇕',
155  terminal: '$',
156  pencil: '✎',
157  globe: '◎',
158  plug: '⏚',
159  'dot-fill': '·',
160  code: '◆',
161  tools: '◇',
162  // ↯, not ⚡: ⚡ has an emoji presentation; ✓, not ✔, for the same reason.
163  zap: '↯',
164  checklist: '✓',
165  telescope: '⌕',
166  tasklist: '≡',
167  hubot: '○',
168  book: '?',
169}
170
171/**
172 * The glyph an icon draws as where there's no SVG: its terminal glyph, a
173 * one-character key as itself, else a dot (never the icon's name as text).
174 */
175export const glyphOf = (key: string): string => TERM_GLYPH[key] ?? ([...key].length === 1 ? key : '•')
176
177/** An XML text node's escapes, for a tooltip's `<title>`. */
178const xml = (text: string) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
179
180/**
181 * The SVG for an icon (a GLYPH or a name), drawn in `color`; null when the kit has none.
182 *
183 * A `Duo` colour (a file type's, `FILE_TYPE` in kit/tokens.ts) draws the dark value
184 * and switches to the light one by the page's colour scheme, in a style inside the
185 * SVG: the engine tells a render hook no desktop theme. `title` is a tooltip,
186 * shown where the SVG is drawn interactive.
187 */
188export const iconSvg = (key: string, color: string | Duo, px = ICON_PX, title?: string): string | null => {
189  const host = HOSTS[key]
190  const filled = host?.d ?? FILLED[key]
191  const body = PATHS[key]
192  if (!filled && !body) return null
193  const grid = host?.grid ?? 16
194  const base = typeof color === 'string' ? color : color.dark
195  const paint = filled ? 'fill' : 'stroke'
196  const scheme = typeof color === 'string' ? '' : `<style>@media (prefers-color-scheme: light){svg{${paint}:${color.light}}}</style>`
197  const tip = title ? `<title>${xml(title)}</title>` : ''
198  const open = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${grid} ${grid}" `
199  if (filled) return `${open}fill="${base}">${scheme}${tip}<path d="${filled}"/></svg>`
200  return `${open}fill="none" stroke="${base}" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">${scheme}${tip}${body}</svg>`
201}
202
kit/tokens.ts 330 lines
1import type { Skin } from './skin'
2import { DEFAULT_SKIN, SKINS } from './skins'
3import type { SkinId } from './skins'
4
5/**
6 * The instrument's colours. Each hue means one thing, everywhere:
7 *
8 * - grey (MUTED): labels, icons, git marks, ordinary values
9 * - slate (INK): "how much" — bars and gauges that only measure
10 * - blue: live or in progress — running, pending, the activity series
11 * - amber: getting close to a limit — 75% and up, the compaction mark
12 * - red: failed, conflicted, 90% and up
13 * - green: finished well — checks passed, an agent done
14 * - purple: merged
15 *
16 * Cyan and orchid aren't statuses: they only tint parts within one chart. The
17 * accents (ACCENT) aren't either: they only tell sections apart.
18 *
19 * The values come from the skin the kit wears (kit/skin.ts): a zen theme pack's
20 * palette, mapped to what the app surfaces draw. The kit starts in the
21 * `claude-code` skin; `wear()` puts on another. Read them when drawing, never
22 * into a module-level constant, so a skin worn later reaches every drawing.
23 */
24export const C = {
25  ok: '',
26  warn: '',
27  bad: '',
28  blue: '',
29  purple: '',
30  cyan: '',
31  slate: '',
32  orchid: '',
33}
34
35/** Quantity ink: what a bar or gauge is drawn in when it only says how much. */
36export let INK = ''
37
38/** Shades within one chart: parts of one thing, told apart without new meanings. */
39export const RAMP = {
40  blue: ['', '', '', ''] as [string, string, string, string],
41  slate: ['', '', '', ''] as [string, string, string, string],
42}
43
44/** A bar's empty part and other quiet fills: a grey that reads on light and dark. */
45export const TRACK = 'rgba(128,128,128,0.18)'
46
47/**
48 * `color` (#rgb or #rrggbb) at `alpha` (0 to 1), as rgba(): a tint that lets the
49 * pane show through, so it reads on the light desktop theme and the dark one.
50 * Undefined for anything that isn't a hex colour.
51 */
52export const tint = (color: string, alpha: number): string | undefined => {
53  const hex = color.replace(/^#/, '')
54  const full = hex.length === 3 ? [...hex].map(x => x + x).join('') : hex
55  if (!/^[0-9a-f]{6}$/i.test(full)) return undefined
56  const [r, g, b] = [0, 2, 4].map(i => parseInt(full.slice(i, i + 2), 16))
57  return `rgba(${r},${g},${b},${alpha})`
58}
59
60/**
61 * The app surfaces' fills, behind text. The engine gives render hooks no desktop
62 * theme to read and no theme key for a fill, so each is a see-through tint over
63 * the pane: a neutral grey darkens the light pane and lightens the dark one by
64 * about the same step, and the text over it keeps the theme's own foreground.
65 * Never on the terminal, which draws no fills.
66 *
67 * - head: a section header's band, the step that marks where a section starts;
68 * - tile: one item of a list of several-line items, a step quieter than a band;
69 * - selected: the picked tile or row, tinted towards the blue that means live;
70 * - selectedBlurred: the same while the pane doesn't have the keyboard, half as strong;
71 * - pill: how strongly a label's own colour fills its chip.
72 */
73export const FILL = {
74  head: 'rgba(128,128,128,0.09)',
75  tile: 'rgba(128,128,128,0.05)',
76  selected: '',
77  selectedBlurred: '',
78  pill: 0.22,
79}
80
81/** Text, icons and marks that should recede. */
82export let MUTED = ''
83
84/**
85 * Three greys for text below the main text, each a step quieter, so a row can say
86 * what matters most without colour (tuned for the desktop's dark pane; mid and
87 * dark also read on the light one):
88 * - light: secondary text a reader still reads (a linked PR's title, a byline);
89 * - mid: metadata scanned past (ages, counts, secondary actions);
90 * - dark: the quietest marks (an icon beside a count, a heading over a list).
91 */
92export const GRAY = { light: '', mid: '', dark: '' }
93
94/**
95 * Accents: seven colours that only tell groups apart, such as the stripe along
96 * the top of a section or a list (`accent` on `section` and `collapsibleList`).
97 * They're the skin's palette's five categorical hue slots, then its two role
98 * hues. An accent is never a status or a quantity, and only the app surfaces
99 * draw one: the terminal has no theme key that means "this group", so it draws
100 * no accent.
101 */
102export const ACCENT: string[] = []
103
104/** A colour with one value for the light desktop theme and one for the dark. */
105export type Duo = { readonly light: string; readonly dark: string }
106
107/**
108 * File-type icon colours. One meaning: this file's type. Only a file tree's icons
109 * take them, never text, a header or a control (those stay grey), and only on the
110 * app surfaces: the terminal draws file icons monochrome (dim), as a file type is
111 * no state a theme key means.
112 *
113 * The values are IntelliJ's New UI ("expui") icon colours, each from the fill or
114 * stroke of the icon named beside it: intellij-community
115 * `platform/icons/src/expui/fileTypes/<name>.svg` (light) and `<name>_dark.svg`
116 * (dark), and `platform/icons/src/expui/nodes/` for the folders. Apache 2.0,
117 * © JetBrains s.r.o. and contributors (each SVG's header).
118 *
119 * An icon drawn in a Duo carries both values and picks one by the page's colour
120 * scheme (`iconSvg` in kit/icons.ts); where that can't be read it takes the dark.
121 */
122export const FILE_TYPE = {
123  /** typeScript.svg */
124  typescript: { light: '#3574F0', dark: '#548AF7' },
125  /** javaScript.svg */
126  javascript: { light: '#FFAF0F', dark: '#F2C55C' },
127  /** json.svg */
128  json: { light: '#834DF0', dark: '#B589EC' },
129  /** markdown.svg */
130  markdown: { light: '#3574F0', dark: '#548AF7' },
131  /** config.svg (its accent), toml.svg, docker.svg */
132  config: { light: '#3574F0', dark: '#548AF7' },
133  /** yaml.svg */
134  yaml: { light: '#DB3B4B', dark: '#DB5C5C' },
135  /** css.svg */
136  style: { light: '#4682FA', dark: '#548AF7' },
137  /** html.svg */
138  html: { light: '#369650', dark: '#57965C' },
139  /** xml.svg */
140  xml: { light: '#E66D17', dark: '#C77D55' },
141  /** csv.svg */
142  data: { light: '#208A3C', dark: '#57965C' },
143  /** sql.svg */
144  sql: { light: '#834DF0', dark: '#B589EC' },
145  /** image.svg */
146  image: { light: '#3574F0', dark: '#548AF7' },
147  /** archive.svg */
148  archive: { light: '#3574F0', dark: '#548AF7' },
149  /** text.svg, shell.svg, unknown.svg, font.svg: any other file, lockfiles included */
150  text: { light: '#6C707E', dark: '#CED0D6' },
151  /** nodes/folder.svg, nodes/folderGithub.svg */
152  folder: { light: '#6C707E', dark: '#CED0D6' },
153  /** nodes/excludeRoot.svg: a folder git ignores (node_modules, build output) */
154  excluded: { light: '#F28C35', dark: '#C77D55' },
155} as const satisfies Record<string, Duo>
156
157export type FileType = keyof typeof FILE_TYPE
158
159/** Slate under 75%, amber from 75%, red from 90%: colour only once it matters. */
160export const levelColor = (percent: number): string => (percent >= 90 ? C.bad : percent >= 75 ? C.warn : INK)
161
162/*
163 * The terminal's colours. The terminal draws each status in the engine theme key
164 * that means the same thing, so it follows the person's terminal theme (dark,
165 * light, colour-blind, ANSI-only) instead of a fixed hex that may not read on it:
166 *
167 * - green  C.ok     → 'success'
168 * - red    C.bad    → 'error'
169 * - amber  C.warn   → 'warning'
170 * - blue   C.blue   → 'suggestion'
171 * - purple C.purple → 'merged'
172 * - the greys (MUTED, GRAY, TRACK) → the terminal's own dim, never a grey hex
173 * - quantity (INK, slate) → the terminal's default foreground
174 * - the shades within one chart (RAMP, cyan, orchid) → plain and dim in turn
175 *   (TERM_TINT), the blue ramp as `suggestion` and dimmed `suggestion`
176 * - any other hex → the default foreground: no fixed hex reaches the terminal,
177 *   where it can vanish on a light, an ANSI-only or a colour-blind theme.
178 */
179const themeKey: Record<string, string> = {}
180export const THEME_KEY: Readonly<Record<string, string>> = themeKey
181
182const QUIET = new Set<string>()
183
184/** Text props on the terminal: a theme key, the terminal's dim, or neither (the default foreground). */
185export type TermInk = { color?: string; dimColor?: boolean }
186
187/**
188 * The chart shades on the terminal, which has no colours to spare for them: the
189 * slate ramp (quantity) is the default foreground and dim in turn, the blue ramp
190 * `suggestion` and dimmed `suggestion` in turn, cyan plain and orchid dim. A
191 * bar's parts are all runs of the same heavy line (METER), told apart by these
192 * inks alone: no shade or dither glyphs, which render as a checkerboard.
193 */
194const termTint: Record<string, TermInk> = {}
195export const TERM_TINT: Readonly<Record<string, TermInk>> = termTint
196
197/** Whether `color` is one of the kit's tokens (a status, a grey, a chart shade), not data such as a GitHub label's hex. */
198export const isKitColor = (color: string): boolean => QUIET.has(color) || color in THEME_KEY || color in TERM_TINT
199
200/** A raw colour (hex, rgb(), hsl()) rather than a theme key's name. */
201const RAW = /^(#|rgba?\(|hsla?\()/i
202
203/**
204 * A colour's Text props on the terminal: a status as its theme key, a grey as
205 * `dimColor`, a chart shade as TERM_TINT says, a theme key's name as itself, and
206 * any other raw colour as nothing (the default foreground). Nothing for no colour.
207 */
208export const termInk = (color?: string): TermInk => {
209  if (!color) return {}
210  if (QUIET.has(color)) return { dimColor: true }
211  const key = THEME_KEY[color]
212  if (key) return { color: key }
213  const tint = TERM_TINT[color]
214  if (tint) return { ...tint }
215  return RAW.test(color) ? {} : { color }
216}
217
218/**
219 * One glyph per idea, shared so mods read alike (the SVG icons are keyed by these).
220 * Each is what the terminal draws: one cell, and never a character with an emoji
221 * presentation (Unicode's Emoji property: ⚒ ⚠ ⚡ ⏱ ↕ ◼ draw as emoji in some
222 * terminals and take two cells).
223 */
224export const GLYPH = {
225  context: '◕',
226  cost: '$',
227  time: '◷',
228  turns: '↻',
229  // The place-of-interest sign, as on a Command key: what the tools are called with.
230  tools: '⌘',
231  files: '✎',
232  agents: '✦',
233  limits: '◔',
234  layers: '▤',
235  branch: '⎇',
236  pr: '⇡',
237  running: '◐',
238  done: '✓',
239  failed: '✕',
240  stopped: '■',
241  pending: '◌',
242  up: '↑',
243  down: '↓',
244} as const
245
246/**
247 * A status's mark: one glyph and the colour that means it, the same on every
248 * surface. Draw it with `k.status(kind)`, never by hand, so a running task, a
249 * running server and a pending check all read alike.
250 */
251export const STATUS = {
252  running: { glyph: GLYPH.running, color: '' },
253  pending: { glyph: GLYPH.pending, color: '' },
254  done: { glyph: GLYPH.done, color: '' },
255  failed: { glyph: GLYPH.failed, color: '' },
256  warn: { glyph: '▲', color: '' },
257  merged: { glyph: '◆', color: '' },
258  stopped: { glyph: GLYPH.stopped, color: '' },
259  idle: { glyph: '○', color: '' },
260}
261
262export type StatusKind = keyof typeof STATUS
263
264/** The skin the kit wears now: a key of SKINS, or `custom` for a skin passed in whole. */
265export let SKIN: SkinId | 'custom' = DEFAULT_SKIN
266
267/**
268 * Puts on a skin: a zen theme pack's (a key of SKINS, kit/skins.ts) or one made
269 * in full. Every colour above takes the skin's value, and the terminal's mapping
270 * follows, so each meaning keeps its theme key. Wear one before the first
271 * drawing (at the top of the hooks module); the kit starts in DEFAULT_SKIN.
272 */
273export const wear = (skin: SkinId | Skin): void => {
274  const s = typeof skin === 'string' ? SKINS[skin] : skin
275  if (!s) throw new Error(`no skin '${String(skin)}'`)
276  SKIN = typeof skin === 'string' ? skin : 'custom'
277  Object.assign(C, { ok: s.ok, warn: s.warn, bad: s.bad, blue: s.blue, purple: s.purple, cyan: s.cyan, slate: s.slate, orchid: s.orchid })
278  INK = s.slate
279  RAMP.blue.splice(0, 4, ...s.ramp.blue)
280  RAMP.slate.splice(0, 4, ...s.ramp.slate)
281  FILL.selected = tint(s.blue, 0.13)!
282  FILL.selectedBlurred = tint(s.blue, 0.065)!
283  MUTED = s.muted
284  Object.assign(GRAY, s.gray)
285  ACCENT.splice(0, ACCENT.length, ...s.hues, ...s.roles)
286  const status: Record<StatusKind, string> = {
287    running: s.blue,
288    pending: s.blue,
289    done: s.ok,
290    failed: s.bad,
291    warn: s.warn,
292    merged: s.purple,
293    stopped: s.muted,
294    idle: s.muted,
295  }
296  for (const kind of Object.keys(status) as StatusKind[]) STATUS[kind].color = status[kind]
297  for (const key of Object.keys(themeKey)) delete themeKey[key]
298  Object.assign(themeKey, { [s.ok]: 'success', [s.bad]: 'error', [s.warn]: 'warning', [s.blue]: 'suggestion', [s.purple]: 'merged' })
299  QUIET.clear()
300  for (const grey of [s.muted, s.gray.light, s.gray.mid, s.gray.dark, TRACK]) QUIET.add(grey)
301  for (const key of Object.keys(termTint)) delete termTint[key]
302  Object.assign(termTint, {
303    [s.ramp.slate[0]]: {},
304    [s.ramp.slate[1]]: { dimColor: true },
305    [s.ramp.slate[2]]: {},
306    [s.ramp.slate[3]]: { dimColor: true },
307    [s.ramp.blue[1]]: { color: 'suggestion', dimColor: true },
308    [s.ramp.blue[2]]: { color: 'suggestion' },
309    [s.ramp.blue[3]]: { color: 'suggestion', dimColor: true },
310    [s.cyan]: {},
311    [s.orchid]: { dimColor: true },
312  })
313}
314
315wear(DEFAULT_SKIN)
316
317/**
318 * Tree connectors for nested rows (agents under the agent that spawned them,
319 * files under folders), each two cells wide so levels indent on the grid.
320 */
321export const TREE = { tee: '├─', last: '└─', pipe: '│ ', blank: '  ' } as const
322
323/**
324 * A nested row's connector: for each level above it, a pipe where that level has
325 * more rows below, else blank; then a tee, or an elbow for the last child.
326 * Empty at the top level.
327 */
328export const treePrefix = (guides: boolean[], last: boolean, depth = guides.length + 1): string =>
329  depth === 0 ? '' : `${guides.map(g => (g ? TREE.pipe : TREE.blank)).join('')}${last ? TREE.last : TREE.tee}`
330
kit/skin.ts 45 lines
1/**
2 * A skin: the colours the kit draws with on the app surfaces (desktop, VS Code, mobile), one per
3 * meaning (see kit/tokens.ts). Each zen theme pack gives one (kit/skins.ts, made from the pack's
4 * palette by zen's `src/harness/claude-code/skins.ts`); a mod wears one with `wear()`.
5 *
6 * The terminal never draws these values: it draws each meaning in the terminal theme key that
7 * means the same thing (THEME_KEY, TERM_TINT in kit/tokens.ts), whatever the skin, so a mod
8 * follows the person's terminal theme.
9 *
10 * Every value is #rrggbb, and every value is its meaning's own: no two meanings share a value,
11 * as the terminal finds a meaning by its value. Greys may share one another's. The accents
12 * (`hues`, `roles`) stand outside that rule: only the app surfaces draw them, and nothing looks
13 * a meaning up by them.
14 */
15export type Skin = {
16  /** The pack's name, as zen's toolbar shows it. */
17  readonly label: string
18  /** Finished well: checks passed, an agent done. */
19  readonly ok: string
20  /** Getting close to a limit: 75% and up, the compaction mark. */
21  readonly warn: string
22  /** Failed, conflicted, 90% and up. */
23  readonly bad: string
24  /** Live or in progress: running, pending, the activity series. */
25  readonly blue: string
26  /** Merged. */
27  readonly purple: string
28  /** A tint for parts within one chart, never a status. */
29  readonly cyan: string
30  /** Quantity ink: what a bar or gauge is drawn in when it only says how much. */
31  readonly slate: string
32  /** A tint for parts within one chart, never a status. */
33  readonly orchid: string
34  /** Shades within one chart: the live colour and the quantity ink, each base first, then darker, lighter, darkest. */
35  readonly ramp: { readonly blue: readonly [string, string, string, string]; readonly slate: readonly [string, string, string, string] }
36  /** Text, icons and marks that should recede. */
37  readonly muted: string
38  /** Text below the main text, each a step quieter. */
39  readonly gray: { readonly light: string; readonly mid: string; readonly dark: string }
40  /** The palette's five categorical hue slots: accents that tell groups apart (ACCENT), never a status. */
41  readonly hues: readonly [string, string, string, string, string]
42  /** The palette's two role hues: the accents after the five. */
43  readonly roles: readonly [string, string]
44}
45
kit/skins.ts 349 lines
1// Every zen theme pack's skin for the Claude Code kit, by pack id: made from the pack's palette by
2// zen's src/harness/claude-code/skins.ts. Generated; don't edit it, run `npx tsx scripts/harness-skins.ts` in zen.
3import type { Skin } from './skin'
4
5export const SKINS = {
6  "yahaha-elektron": {
7    label: "yahaha × Elektron",
8    ok: "#5fdc4a",
9    warn: "#ffd60a",
10    bad: "#e5534b",
11    blue: "#3b8eff",
12    purple: "#a58cff",
13    cyan: "#3ff4ff",
14    slate: "#afc4e0",
15    orchid: "#f57aff",
16    ramp: {
17      blue: [
18        "#3b8eff",
19        "#2c6bbf",
20        "#80b6ff",
21        "#204e8c"
22      ],
23      slate: [
24        "#afc4e0",
25        "#8393a8",
26        "#cbd9eb",
27        "#606c7b"
28      ]
29    },
30    muted: "#8c8c8c",
31    gray: {
32      light: "#d6d6d6",
33      mid: "#8c8c8c",
34      dark: "#4d4d4d"
35    },
36    hues: [
37      "#3b8eff",
38      "#ff4f9e",
39      "#ff9a2e",
40      "#16c7a6",
41      "#bd39ec"
42    ],
43    roles: [
44      "#f57aff",
45      "#3ff4ff"
46    ]
47  },
48  "yahaha-classic": {
49    label: "yahaha classic",
50    ok: "#02c31e",
51    warn: "#ffeb44",
52    bad: "#fe4e66",
53    blue: "#4cc2ff",
54    purple: "#b98cff",
55    cyan: "#08b7aa",
56    slate: "#87aac2",
57    orchid: "#ff6bd0",
58    ramp: {
59      blue: [
60        "#4cc2ff",
61        "#3992bf",
62        "#8bd7ff",
63        "#2a6b8c"
64      ],
65      slate: [
66        "#87aac2",
67        "#658092",
68        "#b1c8d7",
69        "#4a5e6b"
70      ]
71    },
72    muted: "#8a929d",
73    gray: {
74      light: "#9aa2ad",
75      mid: "#8a929d",
76      dark: "#555c66"
77    },
78    hues: [
79      "#4cc2ff",
80      "#b98cff",
81      "#5fdc92",
82      "#fd7d00",
83      "#4b8efe"
84    ],
85    roles: [
86      "#ff6bd0",
87      "#08b7aa"
88    ]
89  },
90  "yahaha-push": {
91    label: "yahaha Push (as designed)",
92    ok: "#5fdc4a",
93    warn: "#ffd60a",
94    bad: "#e5534b",
95    blue: "#3b8eff",
96    purple: "#a58cff",
97    cyan: "#3ff4ff",
98    slate: "#afc4e0",
99    orchid: "#f57aff",
100    ramp: {
101      blue: [
102        "#3b8eff",
103        "#2c6bbf",
104        "#80b6ff",
105        "#204e8c"
106      ],
107      slate: [
108        "#afc4e0",
109        "#8393a8",
110        "#cbd9eb",
111        "#606c7b"
112      ]
113    },
114    muted: "#8c8c8c",
115    gray: {
116      light: "#d6d6d6",
117      mid: "#8c8c8c",
118      dark: "#4d4d4d"
119    },
120    hues: [
121      "#3b8eff",
122      "#ff4f9e",
123      "#ff9a2e",
124      "#16c7a6",
125      "#bd39ec"
126    ],
127    roles: [
128      "#f57aff",
129      "#3ff4ff"
130    ]
131  },
132  visuals: {
133    label: "visual[flow] (glass)",
134    ok: "#51cd85",
135    warn: "#f0b23c",
136    bad: "#e0483f",
137    blue: "#7c86ff",
138    purple: "#c86ef0",
139    cyan: "#3ff4ff",
140    slate: "#a8abce",
141    orchid: "#f2659f",
142    ramp: {
143      blue: [
144        "#7c86ff",
145        "#5d65bf",
146        "#aab0ff",
147        "#444a8c"
148      ],
149      slate: [
150        "#a8abce",
151        "#7e809b",
152        "#c6c8df",
153        "#5c5e71"
154      ]
155    },
156    muted: "#a4a4ac",
157    gray: {
158      light: "#b7b7be",
159      mid: "#a4a4ac",
160      dark: "#5e5e66"
161    },
162    hues: [
163      "#36b8ec",
164      "#7c86ff",
165      "#c86ef0",
166      "#f2659f",
167      "#d900af"
168    ],
169    roles: [
170      "#c6e34a",
171      "#3ff4ff"
172    ]
173  },
174  elektron: {
175    label: "Elektron",
176    ok: "#3ddc84",
177    warn: "#ff8c1a",
178    bad: "#ff4d4d",
179    blue: "#3d6bff",
180    purple: "#b48cff",
181    cyan: "#00d1ff",
182    slate: "#c2cdf5",
183    orchid: "#ff3dbb",
184    ramp: {
185      blue: [
186        "#3d6bff",
187        "#2e50bf",
188        "#819fff",
189        "#223b8c"
190      ],
191      slate: [
192        "#c2cdf5",
193        "#929ab8",
194        "#d7dff9",
195        "#6b7187"
196      ]
197    },
198    muted: "#b4b4b8",
199    gray: {
200      light: "#eeeef2",
201      mid: "#b4b4b8",
202      dark: "#6a6a6a"
203    },
204    hues: [
205      "#00d1ff",
206      "#3d6bff",
207      "#ff3dbb",
208      "#aaff1b",
209      "#c645f7"
210    ],
211    roles: [
212      "#b48cff",
213      "#0a9e9e"
214    ]
215  },
216  ableton: {
217    label: "Ableton",
218    ok: "#36b958",
219    warn: "#ffe630",
220    bad: "#ff3254",
221    blue: "#4d4dff",
222    purple: "#8a8aff",
223    cyan: "#018fd2",
224    slate: "#d3d3ff",
225    orchid: "#db77ff",
226    ramp: {
227      blue: [
228        "#4d4dff",
229        "#3a3abf",
230        "#8b8bff",
231        "#2a2a8c"
232      ],
233      slate: [
234        "#d3d3ff",
235        "#9e9ebf",
236        "#e2e2ff",
237        "#74748c"
238      ]
239    },
240    muted: "#aaaaaa",
241    gray: {
242      light: "#ffffff",
243      mid: "#aaaaaa",
244      dark: "#666666"
245    },
246    hues: [
247      "#ff8389",
248      "#00d2be",
249      "#8a8aff",
250      "#ffb347",
251      "#f529b5"
252    ],
253    roles: [
254      "#db77ff",
255      "#018fd2"
256    ]
257  },
258  linear: {
259    label: "Linear",
260    ok: "#86e08a",
261    warn: "#f4c430",
262    bad: "#eb5757",
263    blue: "#5e6ad2",
264    purple: "#bb87fc",
265    cyan: "#02b8cc",
266    slate: "#b4bbdd",
267    orchid: "#ff7ad9",
268    ramp: {
269      blue: [
270        "#5e6ad2",
271        "#47509e",
272        "#969ee2",
273        "#343a74"
274      ],
275      slate: [
276        "#b4bbdd",
277        "#878ca6",
278        "#ced3e9",
279        "#63677a"
280      ]
281    },
282    muted: "#8a8f98",
283    gray: {
284      light: "#d0d6e0",
285      mid: "#8a8f98",
286      dark: "#62666d"
287    },
288    hues: [
289      "#99bfff",
290      "#27a644",
291      "#02b8cc",
292      "#bb87fc",
293      "#d427cd"
294    ],
295    roles: [
296      "#ff7ad9",
297      "#ff8a3d"
298    ]
299  },
300  "claude-code": {
301    label: "Claude Code",
302    ok: "#5bc08a",
303    warn: "#e3a33b",
304    bad: "#e5636f",
305    blue: "#6c8ef5",
306    purple: "#9d85e8",
307    cyan: "#4fb3c8",
308    slate: "#8c9bb5",
309    orchid: "#c58ad6",
310    ramp: {
311      blue: [
312        "#6c8ef5",
313        "#4c68c9",
314        "#a9bbf9",
315        "#38509e"
316      ],
317      slate: [
318        "#8c9bb5",
319        "#6f7c93",
320        "#a7b2c6",
321        "#5b667a"
322      ]
323    },
324    muted: "#8e8e93",
325    gray: {
326      light: "#b9b9b6",
327      mid: "#8a8a87",
328      dark: "#62625f"
329    },
330    hues: [
331      "#c58ad6",
332      "#2fd0f0",
333      "#d6d65c",
334      "#b0613a",
335      "#ee2dc1"
336    ],
337    roles: [
338      "#a35ff0",
339      "#3a5fd0"
340    ]
341  }
342} as const satisfies Record<string, Skin>
343
344/** A pack's id: the skins a mod can wear. */
345export type SkinId = keyof typeof SKINS
346
347/** The skin the kit starts in: awesome-claude's look. */
348export const DEFAULT_SKIN: SkinId = 'claude-code'
349