Live agent, tool, review, context, and activity views for Claude Code.

Cockpit is a Claude Code plugin that adds five read-only views and a band above the prompt. It does not change the status line, prompts, tool results, or permission dialogs.
The plugin needs Claude Code 2.1.292 or later for the early-access function-hook API. A later engine release can change this API.
| View | Content | Data source |
|---|---|---|
| Agents | Session summary, plan, agent tree, and a detail card for the selected agent with its status, tokens, models, tool mix, todos, recent tools, and last answer | Native agent, turn, and tool events |
| Tools | Totals with approval counts, running calls, the call log with actor filters, a detail card, time per tool, background tasks, and crons | Native tool, permission, task notification, and turn events |
| Changes | Branch and totals, file groups by Git state with diffstat bars, the selected diff, checks, review findings, and Git activity | Native edit and shell results, and requested Git reads |
| Context | Fill gauge with the auto-compact mark, headroom and trend, category estimates, a token table, cost and rate limits, largest consumers, and compactions | Local summary and native measurements |
| Activity | Bongo Cat, activity counts and history, a timeline per actor, and a summary of where the time went | Observed tool, agent, and turn activity |
The band shows up to two rows above the prompt. A ◉ button before the rows opens the pane. The pane opens only from this button or a /cockpit command.
The first row shows what runs now. It shows only while work runs, while agents are live, or after a failure. It has these parts, in priority order:
+N for each other running call. While a turn runs with no running tool, the status is "thinking".After a turn stops on an API error, the status shows "stopped: API error" in red until the next turn starts. The pane header also shows the error message from the transcript. After another failed turn, the status shows ✗ last turn failed.
The second row shows where the work stands. It has these parts, in priority order:
1/3 Writing tests. A finished plan stays only while a turn runs.✗ npm test 2/42 failed. An edit after the check dims the result and adds (stale).⟳ ~4 replies to compact. It shows only near the auto-compact threshold: yellow from 10 points before the threshold, and red at the threshold.When a row is too narrow, the parts that have a short form use it. Then the parts with the lowest priority drop out. When the space above the prompt has fewer rows, the band keeps its first rows.
The band does not show the model, the context fill, the cost, or the turn time. The claude-statusline script and the engine show them.
When you open the transcript of a subagent, the band follows that agent. The first row starts with the name of the agent, then its lead tool or its status. The second row shows the plan of that agent.
The spinner turns four times a second while work runs. When the animation setting is off, the status shows a static ▸.
The pane header shows the model, the session status, a context meter, the cost, the number of turns, and the session time.
Below the header, each view tab shows a count:
▸ while agents run.▸ while calls run.An accent mark under the active tab shows the selected view. In a narrow pane, the tabs drop their counts first. Then the tabs wrap onto more than one row, in order.
The session summary shows the current status, the turn count, and the average turn time. It also shows failed tool calls, token totals with the cache hit rate, and live agents.
The plan comes from the last TodoWrite result of the main thread and from the task tools (TaskCreate, TaskUpdate, TaskList). The plan list shows the items near the item in progress. The plan of a subagent appears in the detail card of that agent.
A completed Agent call reports run totals: tokens, tool uses, duration, changed lines, and models. The detail card shows the last answer of the agent as Markdown. An agent without run totals shows the usage of its last turn. "Show its tools" opens the Tools view, filtered to that agent.
When the transcript in view changes to a subagent, the pane selects that agent. A selection that you make stays until the transcript in view changes again.
The summary shows the total tool time and the number of approval prompts. "Running now" lists the running calls, newest first. A call that waits for a permission answer shows a ? mark.
The time of a call starts when the engine starts the call and stops when the call returns. This time includes the permission dialog and hooks. The detail card of a call that asked for permission shows "Approval asked".
"By tool" ranks the tools by total time, with call and failure counts. Agent calls are counted but get no bar, because their time is the time of the subagent.
Background tasks come from Bash calls with run_in_background, Agent calls with run_in_background, and Monitor calls. The task notification in the transcript gives the end status, such as completed, failed, or killed. A TaskStop call marks a task as stopped. The end of the last turn of a background agent also marks the agent as ended.
Crons appear below the background tasks. They come from CronCreate, CronDelete, and ScheduleWakeup calls. A one-shot cron leaves the list when its prompt fires. A /loop wakeup shows the time until it fires.
The view groups files as staged, changed, untracked, and edited but not yet read from Git. Each row shows the Git state, the path, the number of observed edits, the number of findings, a diffstat bar, and the line counts. The diff heading names the agent that made the last edit.
Git activity comes from shell results that the engine marks as commits, pushes, branch changes, or pull requests. A pull request with an https URL shows a link.
The gauge scales the category estimates to the live fill and marks the auto-compact threshold. The headroom line shows the tokens left before auto-compact.
The engine measures the fill after each model response. The trend line shows the average growth of the last five measurements that grew. It also estimates the number of responses left before auto-compact.
The Compactions section shows the number of recorded compactions. It lists the last five with their trigger, token counts, and reduction.
Cost per turn is the difference between consecutive cost measurements of the main thread.
The Activity view shows the phase, the number of running tools and agents, the activity history, and a pause control. It also has these parts:
The cat is braille line art based on the original Bongo Cat. The table edge falls to the right, the face tilts with it, and the two bongos stand in front. A raised paw shows its toe beans, and a hit shows impact lines. The cat is 40 columns wide, or 34 or fewer in a narrow pane. It uses theme colors.
The selected view, the band setting, the animation setting, and the timeline zoom persist across sessions in plugin storage. A saved reactor view opens the Activity view. reactor is the name of the view that Activity replaced. Storage errors go to the debug log and do not block the commands.
The pane does not paint a background. In the terminal dock, the engine fills the pane with the composerSidebarBackground color of the Claude Code theme. A plugin cannot paint the default terminal background over this fill.
All text and border colors are Claude Code theme keys, such as suggestion, success, and inactive. An ANSI theme, such as dark-ansi, draws these keys with the terminal palette.
A hex value or a color name is a fixed RGB value. In tmux, Claude Code limits output to 256 colors unless CLAUDE_CODE_TMUX_TRUECOLOR is set. With 256 colors, a hex value changes to the nearest xterm color.
This configuration makes the dock match the terminal background:
~/.claude/themes/stylix.json. The theme extends the ANSI theme for the Stylix polarity and sets composerSidebarBackground to Stylix base00.settings.json selects custom:stylix and sets CLAUDE_CODE_TMUX_TRUECOLOR to 1. Without truecolor, tmux sessions round base00 to a gray xterm color./cockpit
/cockpit agents
/cockpit tools
/cockpit changes
/cockpit context
/cockpit activity
/cockpit band off
/cockpit band on
/cockpit close
/cockpit help
The command can run during a model turn. /cockpit reactor is an alias for /cockpit activity.
/cockpit to open the pane.Ctrl+X Tab to focus the pane.1 through 5 to select a view.Tab to move between controls.Ctrl+X ← to widen it or Ctrl+X → to narrow it.Ctrl+X ↑ to make it taller or Ctrl+X ↓ to make it shorter.Esc to close the pane.While the pane has focus, the views also have letter keys:
| Key | Agents | Tools | Changes | Context | Activity |
|---|---|---|---|---|---|
r | Refresh agents | Read Git | Estimate categories | ||
j / k | Next or previous agent | Older or newer call | Next or previous file | ||
t | Show its tools | ||||
p | Copy the file path | Pause or wake the cat | |||
c / q | Copy or quote the patch | ||||
z | Change the timeline zoom |
The pane uses native scrolling and resizing. The pane asks for 58 columns in the dock and 24 rows above the prompt. A size that you set has priority over this request. The footer shows the resize keys for the current placement. Every view fits its layout to the new size.
History starts when the plugin loads and stays in session memory. Hot reload keeps this memory, and /clear removes it.
Session memory holds at most these items:
Agent status comes from the engine roster. An external teammate can keep an old status after its terminal closes. An agent that is missing from the roster shows an unknown status. This status does not prove that the agent stopped.
Tool durations measure the call, not the full life of a background process. Server-side tools appear only after the response that used them. Passive tool hooks do not give general live stdout.
No event reports when you answer a permission dialog. As a result, the approval mark stays until the tool finishes, and the band does not show it. The time of a call that asked for permission includes the time that the dialog waited for you.
The plugin uses no classic hook events (classic.*). On a machine with managed settings, and for Team and Enterprise organizations, the built-in cc-plugin-sec-default plugin runs first and sends each classic event past installed plugins. As a result, the plugin cannot get these data:
PostToolUse).Stop).rate_limit (StopFailure).A shell or monitor task ends in the view only when the transcript draws its notification. In a session without a surface that draws the transcript, the task stays running.
Crons change only from tool calls. A recurring cron that expires after 7 days stays in the list. A one-shot cron stays in the list if its fired prompt differs from the prompt that scheduled it.
Check summaries read the known output formats of Jest, Vitest, pytest, cargo, and Go. For unknown output, the check shows a completed call and does not invent a pass count. A background check keeps its last reported state.
The context summary estimates the categories locally. It makes no token-count API request. Live input counts come from the last response. They are unknown before the first response and after a compaction.
The cost figure comes from the engine ledger. It is not a statement of account billing. Category estimates can differ from the live input count.
The Activity view shows relative observed activity, not an exact running token rate. The activity history records each change in the number of running tools, running agents, and main turns, also while the pane is closed. The cat animates only while the Activity view is visible. The pause control changes the animation setting, so it stops the cat and the band spinner.
The timeline knows the start and end of each tool call and main turn. Model time is the part of a turn without a running tool. An agent lane starts when the plugin first observes the agent.
While work runs, elapsed times redraw once a second, also while the pane is closed. A running tool, a main turn, and a running agent are work. The band spinner redraws only the band.
The plugin observes existing work. It does not automatically start builds, reviews, browser capture, model requests, or HTTP requests.
The plugin reads Git only when you select the Changes view or press its refresh control. The Git commands use argument vectors, disable external diff drivers and text conversion, and disable filesystem monitor commands.
The plugin does not keep raw prompts, shell command arguments, or shell output, with one exception. A recognized check keeps a short label: the executable and its check subcommand or script, such as cargo test or npm run test:unit. Other Bash calls show only the executable name. A background shell task shows its description or its executable name, not its command. A cron shows its schedule, not its prompt.
Patches, finding summaries, todo text, and the last answer of each agent stay in bounded session memory. The plugin does not write them to disk. Plugin storage holds only the view, band, animation, and zoom preferences.
"Copy path" puts the path of the selected file on the clipboard. The path is relative to the repository root, as the file list shows it. For a file outside the repository, the full path is copied. "Copy patch" puts the patch on the clipboard. "Quote patch" adds the patch to the end of the draft. It does not submit the draft or replace existing text.
Observation errors go to the debug log. They do not change tool arguments, results, permission decisions, or streamed chunks. Existing shell hooks stay active.
The tracked source is dotfiles/claude/.claude/plugins/cockpit/. Home Manager links the complete plugin root directly through home.file.".claude/skills/cockpit".source, with an out-of-store symlink.
Claude Code loads each folder in ~/.claude/skills/ that has a .claude-plugin/plugin.json file as a user plugin. No --plugin-dir flag or enabledPlugins entry is necessary. claude plugin list shows the plugin as cockpit@skills-dir. An interactive session watches the folder and reloads the hooks module after a file changes.
The generic managed-plugin wrapper can cache a manifest-only entry for an out-of-store source. The direct link keeps the original manifest, type contract, and hook modules.
The nono profile grants read access to the tracked target. The generated SDK declarations are optional at runtime. A sandbox can refuse to write the declarations next to the source, and the plugin does not need write access to the whole source.
Nothing in the plugin activates Home Manager or rebuilds NixOS. The link appears after the usual configuration activation.
The skills folder link already loads the tracked source in each session. Use --plugin-dir only where the link does not exist:
claude --plugin-dir "$HOME/.nix-config/dotfiles/claude/.claude/plugins/cockpit"
An interactive session hot-reloads a development path. A session development mod needs a separate hot-reload approval from the person.
claude plugin validate --strict "$HOME/.nix-config/dotfiles/claude/.claude/plugins/cockpit"
claude plugin test "$HOME/.nix-config/dotfiles/claude/.claude/plugins/cockpit"
tsc -p "$HOME/.nix-config/dotfiles/claude/.claude/plugins/cockpit"
The engine generates .claude-plugin/types/ after a normal plugin load. The generated declarations describe the current engine and the connected tools. Git ignores this directory.
The tests use the native test engine, explicit surfaces, and mocked host operations. They cover descriptions and interactions, not the actual paint of the renderer.
hooks/register.tsx holds hooks, host operations, literal state references, the band, and the pane header.hooks/state.ts holds initial state factories. It also fills the fields that state from an earlier version does not have.hooks/data.ts holds bounded parsers and observation helpers.hooks/summary.ts derives the status, totals, plan, context fill, activity history, and band rows from state.hooks/layout.tsx holds shared drawing blocks: lines, headings, fields, cards, actions, and tabs.hooks/agents.tsx, hooks/tools.tsx, hooks/changes.tsx, hooks/context.tsx, and hooks/activity.tsx draw one view each.hooks/theme.ts holds shared theme-key colors and text formatting.types/index.d.ts declares the self-contained state contract.tests/ holds parser, summary, view, lifecycle, and safety tests. tests/kit.tsx holds the shared fixtures.The native source analyzer follows host capabilities only through top-level functions in the hooks module. It does not follow $ across imported helpers.
hooks/register.tsx 936 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderSurface, Timer } from 'claude-code'
3import type {
4 CockpitActions, CockpitActivity, CockpitAgent, CockpitChange, CockpitCompaction, CockpitContext, CockpitFinding,
5 CockpitMascot, CockpitPreferences, CockpitPulse, CockpitReview, CockpitSpan, CockpitStopFailure, CockpitTool, CockpitView,
6 CockpitViewProps,
7} from '../types'
8import { renderActivity, SPAN_ORDER } from './activity'
9import { renderAgents } from './agents'
10import { renderChanges } from './changes'
11import { renderContext } from './context'
12import {
13 agentResult, answerText, applyCronResult, applyTaskResult, backgroundLaunch, changeState, detectCheck, endBackground,
14 endedStatus, firedCrons, gitOperationOf, mergeAgents, normalizeObservedChanges, parseGitDiff, parseGitStatus,
15 summarizeCheck, todosOf, toolTarget, withSample,
16} from './data'
17import { line, paneFooter, tabMark, tabRows } from './layout'
18import { activityOf, contextOf, initialActivity, initialContext, initialReview, reviewOf } from './state'
19import type { Segment } from './summary'
20import {
21 bandRows, changeTotals, contextColor, contextFill, isLive, mainTurns, runningTools, sessionStart, sessionStatus,
22} from './summary'
23import { brief, clip, colors, humanize, meter, percent, shortModel, usd } from './theme'
24import { renderTools } from './tools'
25
26const PANE = 'cockpit'
27const STORE_KEY = 'preferences'
28const VIEWS: CockpitView[] = ['agents', 'tools', 'changes', 'context', 'activity']
29
30const activity = atom({ plugin: 'cockpit', key: 'activity' } as const, initialActivity())
31const review = atom({ plugin: 'cockpit', key: 'review' } as const, initialReview())
32const context = atom({ plugin: 'cockpit', key: 'context' } as const, initialContext())
33const preferences = atom({ plugin: 'cockpit', key: 'preferences' } as const, {
34 view: 'agents', band: true, animation: true, span: 'fit', paneOpen: false,
35} satisfies CockpitPreferences)
36const mascot = atom({ plugin: 'cockpit', key: 'mascot' } as const, {
37 frame: 0, phase: 'idle',
38} satisfies CockpitMascot)
39const pulse = atom({ plugin: 'cockpit', key: 'pulse' } as const, { frame: 0 } satisfies CockpitPulse)
40
41// Session memory can hold an earlier version's shape. Every update reads it
42// filled in, and an updater that returns its input writes nothing.
43const normalized = <T,>(fill: (value: T) => T, change: (previous: T) => T) => (previous: T): T => {
44 const current = fill(previous)
45 const next = change(current)
46 return next === current ? previous : next
47}
48const updateActivity = async ($: EngineInterface, change: (previous: CockpitActivity) => CockpitActivity): Promise<void> => {
49 await update($, activity, normalized(activityOf, change))
50}
51const updateReview = async ($: EngineInterface, change: (previous: CockpitReview) => CockpitReview): Promise<void> => {
52 await update($, review, normalized(reviewOf, change))
53}
54const updateContext = async ($: EngineInterface, change: (previous: CockpitContext) => CockpitContext): Promise<void> => {
55 await update($, context, normalized(contextOf, change))
56}
57
58const errorText = (error: unknown): string =>
59 clip(error instanceof Error ? error.message : 'The operation could not complete.', 240)
60
61// The engine follows host capabilities only through functions in this module.
62const observe = async ($: EngineInterface, work: () => Promise<unknown>): Promise<void> => {
63 try {
64 await work()
65 } catch (error) {
66 // Never replay or change the operation when its observation fails.
67 $.ui.log(`cockpit: ${errorText(error)}`, { to: 'debug' })
68 }
69}
70
71let initializing: Promise<string> | undefined
72
73const ensureSession = async ($: EngineInterface): Promise<string> => {
74 if (initializing !== undefined) {
75 await initializing
76 return ensureSession($)
77 }
78 const initialize = async (): Promise<string> => {
79 const id = await $.session.id()
80 const previous = await read($, activity)
81 if (previous.sessionId === id) return id
82 const model = await $.session.model()
83 await update($, activity, (value): CockpitActivity => ({ ...initialActivity(), sessionId: id, model }))
84 await update($, review, (value): CockpitReview => ({ ...initialReview(), sessionId: id }))
85 await update($, context, (value): CockpitContext => ({ ...initialContext(), sessionId: id }))
86 await update($, mascot, (): CockpitMascot => ({ frame: 0, phase: 'idle' }))
87 return id
88 }
89 const pending = initialize()
90 initializing = pending
91 try {
92 return await pending
93 } finally {
94 if (initializing === pending) initializing = undefined
95 }
96}
97
98const resetSession = async ($: EngineInterface): Promise<void> => {
99 await update($, activity, initialActivity)
100 await update($, review, initialReview)
101 await update($, context, initialContext)
102 await update($, mascot, (): CockpitMascot => ({ frame: 0, phase: 'idle' }))
103}
104
105// Changes to tools, agents or the working flag also record the activity level.
106const changeActivity = async (
107 $: EngineInterface, sessionId: string, now: number,
108 change: (previous: CockpitActivity) => CockpitActivity,
109): Promise<void> => {
110 await updateActivity($, (previous): CockpitActivity => {
111 if (previous.sessionId !== sessionId) return previous
112 const next = change(previous)
113 return next === previous ? previous : withSample(next, now)
114 })
115}
116
117const refreshAgents = async ($: EngineInterface): Promise<void> => {
118 const id = await ensureSession($)
119 try {
120 const [incoming, now] = await Promise.all([$.agent.list(), $.clock.now()])
121 await changeActivity($, id, now, previous => {
122 const merged = mergeAgents(previous.agents, incoming, now)
123 const identity = (list: typeof merged) => list.map(agent => ({ ...agent, lastSeenAt: 0 }))
124 if (JSON.stringify(identity(previous.agents)) === JSON.stringify(identity(merged))) return previous
125 return { ...previous, agents: merged, updatedAt: now, error: null }
126 })
127 } catch (error) {
128 await updateActivity($, (previous): CockpitActivity =>
129 previous.sessionId === id ? { ...previous, error: errorText(error) } : previous,
130 )
131 }
132}
133
134const refreshContext = async ($: EngineInterface): Promise<void> => {
135 const id = await ensureSession($)
136 await updateContext($, previous => ({ ...previous, loading: true, error: null }))
137 try {
138 const usage = await $.session.usage({ breakdown: 'summary', columns: 80 })
139 const now = await $.clock.now()
140 await updateContext($, (previous): CockpitContext => previous.sessionId === id
141 ? { ...previous, usage, refreshedAt: now, loading: false, error: null } : previous)
142 } catch (error) {
143 await updateContext($, previous => previous.sessionId === id
144 ? { ...previous, loading: false, error: errorText(error) } : previous)
145 }
146}
147
148const relativePath = (root: string, path: string): string => {
149 const prefix = `${root.replace(/\/$/, '')}/`
150 return path.startsWith(prefix) ? path.slice(prefix.length) : path
151}
152
153const refreshChanges = async ($: EngineInterface): Promise<void> => {
154 const id = await ensureSession($)
155 await updateReview($, previous => ({ ...previous, loading: true, error: null }))
156 try {
157 const repo = await $.session.repo()
158 if (repo === null) throw new Error('This session is not inside a Git repository.')
159 const init = { cwd: repo.root, timeoutMs: 5000, env: { GIT_OPTIONAL_LOCKS: '0' } }
160 const git = ['git', '--no-pager', '-c', 'color.ui=false', '-c', 'core.fsmonitor=false']
161 const diff = ['diff', '--no-ext-diff', '--no-textconv', '--no-renames']
162 const [status, branch, unstaged, staged] = await Promise.all([
163 $.process.run([...git, 'status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=normal'], init),
164 $.process.run([...git, 'symbolic-ref', '--quiet', '--short', 'HEAD'], init),
165 $.process.run([...git, ...diff], init),
166 $.process.run([...git, ...diff, '--cached'], init),
167 ])
168 if (status.exitCode !== 0 || unstaged.exitCode !== 0 || staged.exitCode !== 0) {
169 throw new Error('Git could not read the working tree. Check repository access.')
170 }
171 const now = await $.clock.now()
172 const entries = parseGitStatus(status.stdout)
173 const patches = [...parseGitDiff(unstaged.stdout, now), ...parseGitDiff(staged.stdout, now, true)]
174 const truncated = unstaged.isStdoutTruncated || staged.isStdoutTruncated
175 let remaining = 200000
176 const changes: CockpitChange[] = entries.slice(0, 100).map(entry => {
177 const matching = patches.filter(change => change.path === entry.path)
178 const full = matching.map(change => change.patch).join('\n')
179 const patch = full.slice(0, Math.max(0, Math.min(24000, remaining)))
180 remaining -= patch.length
181 return {
182 path: entry.path, source: 'git', updatedAt: now, staged: entry.staged,
183 untracked: entry.untracked, patch, state: changeState(entry.status),
184 additions: matching.reduce((total, change) => total + change.additions, 0),
185 deletions: matching.reduce((total, change) => total + change.deletions, 0),
186 truncated: Boolean(truncated || full.length > patch.length || matching.some(change => change.truncated)),
187 }
188 })
189 await updateReview($, (previous): CockpitReview => {
190 if (previous.sessionId !== id) return previous
191 const selected = previous.selectedPath === null ? null : relativePath(repo.root, previous.selectedPath)
192 // Git knows the state. The session knows who edited the file and how often.
193 const history = new Map(previous.changes.map(change => [relativePath(repo.root, change.path), change]))
194 return {
195 ...previous,
196 changes: changes.map(change => {
197 const prior = history.get(change.path)
198 return prior ? { ...change, edits: prior.edits, agentId: prior.agentId } : change
199 }),
200 selectedPath: changes.some(change => change.path === selected) ? selected : changes[0]?.path ?? null,
201 branch: branch.exitCode === 0 ? branch.stdout.trim() : 'detached HEAD',
202 root: repo.root, refreshedAt: now, loading: false,
203 error: status.isStdoutTruncated || truncated ? 'Git output was truncated. Some changes are not shown.' : null,
204 }
205 })
206 } catch (error) {
207 await updateReview($, previous => previous.sessionId === id
208 ? { ...previous, loading: false, error: errorText(error) } : previous)
209 }
210}
211
212const rememberChange = async ($: EngineInterface, change: CockpitChange, sessionId: string): Promise<void> => {
213 await updateReview($, (previous): CockpitReview => {
214 if (previous.sessionId !== sessionId) return previous
215 const path = previous.root === null ? change.path : relativePath(previous.root, change.path)
216 const prior = previous.changes.find(item => item.path === path)
217 const next = {
218 ...change, path, patch: change.patch.slice(0, 24000),
219 edits: (prior?.edits ?? 0) + 1, agentId: change.agentId,
220 ...(prior?.state === undefined ? {} : { state: prior.state, staged: prior.staged }),
221 }
222 const changes = [...previous.changes.filter(item => item.path !== path), next].slice(-100)
223 let remaining = 200000
224 const bounded = changes.reverse().map(item => {
225 const patch = item.patch.slice(0, Math.max(0, remaining))
226 remaining -= patch.length
227 return { ...item, patch, truncated: item.truncated || patch.length !== item.patch.length }
228 }).reverse()
229 return { ...previous, changes: bounded, selectedPath: previous.selectedPath ?? path }
230 })
231}
232
233const record = (value: unknown): Record<string, unknown> | null =>
234 value !== null && typeof value === 'object' && !Array.isArray(value)
235 ? value as Record<string, unknown>
236 : null
237
238const loadPreferences = async ($: EngineInterface): Promise<void> => {
239 const saved = record(await $.store.get(STORE_KEY))
240 if (saved === null) return
241 // The activity view replaced the reactor; a saved reactor choice opens it.
242 const view = saved.view === 'reactor' ? 'activity' : saved.view
243 await update($, preferences, previous => ({
244 ...previous,
245 view: VIEWS.includes(view as CockpitView) ? view as CockpitView : previous.view,
246 band: typeof saved.band === 'boolean' ? saved.band : previous.band,
247 animation: typeof saved.animation === 'boolean' ? saved.animation : previous.animation,
248 span: SPAN_ORDER.includes(saved.span as CockpitSpan) ? saved.span as CockpitSpan : previous.span,
249 }))
250}
251
252// $.state lasts one session. The store keeps the person's choices for the next.
253const savePreferences = ($: EngineInterface): Promise<void> => observe($, async () => {
254 const { view, band, animation, span } = await read($, preferences)
255 await $.store.set(STORE_KEY, { view, band, animation, span })
256})
257
258const recordTaskEnd = async ($: EngineInterface, id: string, status: string): Promise<void> => {
259 const [sessionId, now] = await Promise.all([$.session.id(), $.clock.now()])
260 await updateActivity($, (previous): CockpitActivity => {
261 if (previous.sessionId !== sessionId) return previous
262 const background = endBackground(previous.background, id, status, now)
263 return background === previous.background ? previous : { ...previous, background }
264 })
265}
266
267// Only the classic StopFailure hook names the kind of API error, and a managed
268// security plugin keeps classic hooks from installed plugins. The transcript
269// ends with the engine's message for the error.
270const turnFailure = async ($: EngineInterface, now: number): Promise<CockpitStopFailure> => {
271 const last = (await $.session.messages().catch(() => [])).at(-1)
272 const details = last?.role === 'assistant' ? last.text.trim() : ''
273 return { error: 'API error', details: details === '' ? undefined : clip(details, 240), at: now }
274}
275
276const selectView = async ($: EngineInterface, view: CockpitView): Promise<void> => {
277 await ensureSession($)
278 await update($, preferences, previous => ({ ...previous, view }))
279 await savePreferences($)
280 if (view === 'agents' || view === 'tools') await refreshAgents($)
281 if (view === 'changes') await refreshChanges($)
282 if (view === 'context') await refreshContext($)
283}
284
285const openCockpit = async ($: EngineInterface, view?: CockpitView): Promise<void> => {
286 await ensureSession($)
287 if (view !== undefined) await selectView($, view)
288 const opened = await $.ui.open({ id: PANE, title: 'Cockpit', focus: true, closeOnEscape: true, rows: 24, columns: 58 })
289 if (!opened.isPlaced) $.ui.toast('Cockpit is waiting for a surface with enough room.')
290 await update($, preferences, previous => ({ ...previous, paneOpen: true }))
291}
292
293const actionsFor = ($: EngineInterface, surface: RenderSurface, viewedAgent: string | null): CockpitActions => {
294 const patchFor = async (path: string): Promise<string | null> => {
295 const state = await read($, review)
296 const patch = state.changes.find(change => change.path === path)?.patch
297 if (!patch) { $.ui.toast('No patch is available for this file.'); return null }
298 return patch
299 }
300 return {
301 selectView: view => selectView($, view),
302 refreshAgents: () => refreshAgents($),
303 selectAgent: async id => {
304 await updateActivity($, previous => ({ ...previous, selectedAgent: id, selectedFor: viewedAgent }))
305 },
306 selectTool: async id => { await updateActivity($, previous => ({ ...previous, selectedTool: id })) },
307 refreshChanges: () => refreshChanges($),
308 selectChange: async path => { await updateReview($, previous => ({ ...previous, selectedPath: path })) },
309 copyPath: async path => {
310 if (path === '') return
311 // An edit seen before the first Git read keeps the absolute path the tool reported.
312 const root = (await read($, review)).root ?? (await $.session.repo())?.root ?? null
313 const relative = root === null ? path : relativePath(root, path)
314 const copied = await $.ui.copy({ text: relative, surface })
315 if (!copied.isCopied) $.ui.toast('Clipboard access is not available on this surface.')
316 else $.ui.toast(relative.startsWith('/') ? 'The file is outside the repository. Its full path was copied.' : `Copied ${clip(relative, 60)}.`)
317 },
318 copyPatch: async path => {
319 const patch = await patchFor(path)
320 if (patch !== null) {
321 const copied = await $.ui.copy({ text: patch, surface })
322 $.ui.toast(copied.isCopied ? 'Patch copied.' : 'Clipboard access is not available on this surface.')
323 }
324 },
325 quotePatch: async path => {
326 const patch = await patchFor(path)
327 if (patch !== null) {
328 const longest = Math.max(2, ...(patch.match(/`+/g) ?? []).map(run => run.length))
329 const fence = '`'.repeat(longest + 1)
330 const filled = await $.prompt.fill({ text: `\n${fence}diff\n${patch}\n${fence}\n`, mode: 'append' })
331 $.ui.toast(filled.isFilled ? 'Patch added to the draft. Nothing was submitted.' : 'The prompt cannot accept a draft right now.')
332 }
333 },
334 refreshContext: () => refreshContext($),
335 toggleAnimation: async () => {
336 await update($, preferences, previous => ({ ...previous, animation: !previous.animation }))
337 await savePreferences($)
338 },
339 cycleSpan: async () => {
340 await update($, preferences, previous => ({
341 ...previous, span: SPAN_ORDER[(SPAN_ORDER.indexOf(previous.span) + 1) % SPAN_ORDER.length] ?? 'fit',
342 }))
343 await savePreferences($)
344 },
345 }
346}
347
348const viewLabels: Record<CockpitView, string> = {
349 agents: 'Agents',
350 tools: 'Tools',
351 changes: 'Changes',
352 context: 'Context',
353 activity: 'Activity',
354}
355
356let timer: Timer | undefined
357let ticking = false
358let tick = 0
359let lastAgentRefresh = 0
360
361/** What the cat acts out: tools first, then a working turn or a live agent. */
362const mascotPhase = (state: CockpitActivity): CockpitActivity['phase'] =>
363 state.tools.some(tool => tool.outcome === 'running') ? 'tools'
364 : state.working || state.agents.some(agent => agent.status === 'running') ? 'thinking'
365 : state.phase
366
367// Four ticks a second: the cat's frames while the activity view shows, and the
368// band spinner while work runs. Elapsed times redraw once a second while work
369// runs, in the band as well as the pane.
370const startTimer = ($: EngineInterface) => {
371 if (timer !== undefined) return
372 timer = $.clock.every(250, async () => {
373 if (ticking) return
374 ticking = true
375 tick = (tick + 1) % 1000000
376 try {
377 const prefs = await read($, preferences)
378 const pane = prefs.paneOpen ? (await $.ui.panes()).find(item => item.id === PANE) : undefined
379 const shown = pane?.isPlaced === true && pane.isShown
380 const state = await read($, activity)
381 const busy = state.working || state.tools.some(tool => tool.outcome === 'running')
382 || state.agents.some(agent => agent.status === 'running')
383 const spinning = busy && prefs.band && prefs.animation
384 if (!shown && !spinning && tick % 4 !== 0) return
385 if (spinning) await update($, pulse, (previous): CockpitPulse => ({ frame: ((previous?.frame ?? 0) + 1) % 1000000 }))
386 if (shown) {
387 await ensureSession($)
388 const now = await $.clock.now()
389 if (now - lastAgentRefresh >= 2000) {
390 lastAgentRefresh = now
391 await refreshAgents($)
392 }
393 }
394 if (shown && prefs.view === 'activity' && prefs.animation) {
395 await update($, mascot, (previous): CockpitMascot => ({ frame: (previous.frame + 1) % 1000000, phase: mascotPhase(state) }))
396 }
397 if (busy && tick % 4 === 0) $.ui.invalidate('ui.render')
398 } catch (error) {
399 $.ui.log(`cockpit timer: ${errorText(error)}`, { to: 'debug' })
400 } finally {
401 ticking = false
402 }
403 })
404}
405
406export const register: Register = on => {
407 on('session.start', async ($, e, next) => {
408 const result = await next(e)
409 // A store that cannot be read leaves the defaults and skips nothing else.
410 await observe($, () => loadPreferences($))
411 await observe($, async () => {
412 await ensureSession($)
413 await $.command.register({
414 name: 'cockpit',
415 description: 'Open agent, tool, change, context, or activity views.',
416 argumentHint: '[agents|tools|changes|context|activity|band|close]',
417 immediate: true,
418 })
419 await refreshAgents($)
420 const id = await $.session.id()
421 const usage = await $.session.usage()
422 await updateContext($, (previous): CockpitContext => previous.sessionId === id ? { ...previous, usage } : previous)
423 if (e.isInteractive) startTimer($)
424 })
425 return result
426 }).catch(($, e, next) => next(e))
427
428 on('session.end', async ($, e, next) => {
429 const result = await next(e)
430 await observe($, async () => {
431 await resetSession($)
432 if (e.reason !== 'clear' && e.reason !== 'resume') {
433 timer?.cancel()
434 timer = undefined
435 await update($, preferences, previous => ({ ...previous, paneOpen: false }))
436 }
437 })
438 return result
439 }).catch(($, e, next) => next(e))
440
441 on('command.run', { command: 'cockpit' }, async ($, e) => {
442 try {
443 const args = e.args.trim()
444 const cut = args.search(/\s/)
445 const command = cut < 0 ? args : args.slice(0, cut)
446 const tail = cut < 0 ? '' : args.slice(cut).trim()
447 if (command === 'help') {
448 return { text: [
449 '/cockpit [agents|tools|changes|context|activity]', '/cockpit band [on|off]', '/cockpit close', '',
450 'Ctrl+X Tab focuses the pane. Then Ctrl+X ← or → resizes a docked pane, and Ctrl+X ↑ or ↓ a pane above the prompt.',
451 ].join('\n') }
452 }
453 if (command === 'close') {
454 await $.ui.close({ id: PANE })
455 await update($, preferences, previous => ({ ...previous, paneOpen: false }))
456 return { text: 'Cockpit closed.' }
457 }
458 if (command === 'band') {
459 if (tail !== '' && tail !== 'on' && tail !== 'off') {
460 return { text: 'Use /cockpit band [on|off].', exitCode: 1 }
461 }
462 await update($, preferences, previous => ({
463 ...previous,
464 band: tail === '' ? !previous.band : tail === 'on',
465 }))
466 await savePreferences($)
467 const prefs = await read($, preferences)
468 return { text: `Cockpit band ${prefs.band ? 'enabled' : 'hidden'}.` }
469 }
470 const view = command === 'reactor' ? 'activity' : command
471 if (view !== '' && !VIEWS.includes(view as CockpitView)) {
472 return { text: 'Unknown cockpit view. Use /cockpit help.', exitCode: 1 }
473 }
474 if (tail !== '') {
475 return { text: 'Cockpit views take no arguments. Use /cockpit help.', exitCode: 1 }
476 }
477 await openCockpit($, view === '' ? undefined : view as CockpitView)
478 startTimer($)
479 return { text: 'Cockpit opened. Use the view buttons or /cockpit help.' }
480 } catch (error) {
481 return { text: `Cockpit: ${errorText(error)}`, exitCode: 1 }
482 }
483 })
484
485 on('ui.close', async ($, e, next) => {
486 const result = await next(e)
487 if (e.id === PANE && !('deny' in result)) {
488 await observe($, () => update($, preferences, previous => ({ ...previous, paneOpen: false })))
489 }
490 return result
491 }).catch(($, e, next) => next(e))
492
493 on('turn.start', async ($, e, next) => {
494 await observe($, async () => {
495 const id = await ensureSession($)
496 const now = await $.clock.now()
497 await changeActivity($, id, now, previous => ({
498 ...previous, working: true, turnStartedAt: now, phase: 'thinking', stopFailure: null, updatedAt: now,
499 }))
500 })
501 return next(e)
502 }).catch(($, e, next) => next(e))
503
504 on('turn.step', async function* ($, e, next) {
505 let sessionId: string | undefined
506 await observe($, async () => {
507 sessionId = await ensureSession($)
508 if (e.agentId === undefined) {
509 await updateActivity($, (previous): CockpitActivity => ({ ...previous, model: e.model, phase: 'thinking' }))
510 }
511 })
512 const result = yield* next(e)
513 await observe($, async () => {
514 if (sessionId === undefined || await $.session.id() !== sessionId) return
515 const now = await $.clock.now()
516 const retrospective: CockpitTool[] = (result.serverToolUses ?? []).map(tool => ({
517 id: tool.id,
518 tool: tool.name,
519 agentId: e.agentId,
520 startedAt: tool.startedAt,
521 finishedAt: tool.endedAt ?? now,
522 outcome: tool.endedAt === undefined ? 'interrupted' : 'success',
523 retrospective: true,
524 }))
525 if (retrospective.length > 0) {
526 await updateActivity($, (previous): CockpitActivity => ({
527 ...previous,
528 tools: [...previous.tools.filter(tool => !retrospective.some(server => server.id === tool.id)), ...retrospective].slice(-200),
529 updatedAt: now,
530 }))
531 }
532 })
533 return result
534 }).catch(async function* ($, e, next) { return yield* next(e) })
535
536 on('agent.spawn', async ($, e, next) => {
537 const result = await next(e)
538 await observe($, () => refreshAgents($))
539 return result
540 }).catch(($, e, next) => next(e))
541
542 on('session.receive', async ($, e, next) => {
543 const result = await next(e)
544 await observe($, () => refreshAgents($))
545 return result
546 }).catch(($, e, next) => next(e))
547
548 on('tool.check', async ($, e, next) => {
549 const result = await next(e)
550 const id = e.tool_use_id
551 // A query from $.tool.check has no call id and decides nothing that runs.
552 if (result.decision === 'ask' && id !== undefined) {
553 await observe($, () => updateActivity($, (previous): CockpitActivity => ({
554 ...previous,
555 tools: previous.tools.map(tool => tool.id === id ? { ...tool, approval: 'asked' } : tool),
556 })))
557 }
558 return result
559 }).catch(($, e, next) => next(e))
560
561 on('tool.call', async ($, e, next) => {
562 let sessionId: string | undefined
563 let startedAt = 0
564 const checkLabel = e.tool === 'Bash' && typeof e.command === 'string' ? detectCheck(e.command) : undefined
565 await observe($, async () => {
566 sessionId = await ensureSession($)
567 startedAt = await $.clock.now()
568 const tool: CockpitTool = {
569 id: e.tool_use_id,
570 tool: e.tool,
571 agentId: e.agentId,
572 target: toolTarget(e.tool, e),
573 startedAt,
574 outcome: 'running',
575 }
576 await changeActivity($, sessionId, startedAt, previous => ({
577 ...previous,
578 tools: [...previous.tools.filter(item => item.id !== tool.id), tool].slice(-200),
579 phase: 'tools',
580 updatedAt: startedAt,
581 }))
582 if (checkLabel !== undefined) {
583 await updateReview($, (previous): CockpitReview => ({
584 ...previous,
585 checks: [...previous.checks.filter(check => check.id !== tool.id), { id: tool.id, label: checkLabel, status: 'running' as const }].slice(-40),
586 }))
587 }
588 })
589 try {
590 const result = await next(e)
591 await observe($, async () => {
592 if (sessionId === undefined || await $.session.id() !== sessionId) return
593 const id = sessionId
594 const now = await $.clock.now()
595 const output = record(result.result)
596 const outcome: CockpitTool['outcome'] = result.deny ? 'denied' : result.isError ? 'error' : output?.interrupted === true ? 'interrupted' : 'success'
597 const succeeded = !result.isError && !result.deny
598 const todos = succeeded && e.tool === 'TodoWrite' ? todosOf(result) : undefined
599 const launch = succeeded ? backgroundLaunch(e.tool, e, result, now) : undefined
600 const stopped = succeeded && e.tool === 'TaskStop' && typeof output?.task_id === 'string' ? output.task_id : undefined
601 const finished = succeeded && e.tool === 'Agent' ? agentResult(result) : undefined
602 const spawned: CockpitAgent | undefined = finished && e.tool === 'Agent' ? {
603 id: finished.agentId,
604 name: typeof e.name === 'string' ? clip(e.name, 80) : undefined,
605 description: clip(e.description, 240),
606 type: clip(e.subagent_type ?? 'general-purpose', 80),
607 status: 'completed',
608 startedAt,
609 lastSeenAt: now,
610 completedAt: now,
611 } : undefined
612 await changeActivity($, id, now, previous => {
613 const tools = previous.tools.map(tool => tool.id === e.tool_use_id ? { ...tool, outcome, finishedAt: now } : tool)
614 const phase = tools.some(tool => tool.outcome === 'running') ? 'tools' : previous.working ? 'thinking' : outcome === 'error' ? 'error' : 'idle'
615 const tasks = succeeded ? applyTaskResult(previous.tasks, e.tool, e, result) : undefined
616 const crons = succeeded ? applyCronResult(previous.crons, e.tool, e, result) : undefined
617 let background = launch ? [...previous.background.filter(task => task.id !== launch.id), launch].slice(-40) : previous.background
618 if (stopped !== undefined) background = endBackground(background, stopped, 'stopped', now)
619 // An agent can leave the roster before a refresh lists it. Keep its report anyway.
620 const agents = finished === undefined ? previous.agents
621 : previous.agents.some(agent => agent.id === finished.agentId)
622 ? previous.agents.map(agent => agent.id === finished.agentId
623 ? { ...agent, totals: finished.totals, answer: finished.answer ?? agent.answer } : agent)
624 : spawned ? [...previous.agents, { ...spawned, totals: finished.totals, answer: finished.answer }].slice(-100) : previous.agents
625 return {
626 ...previous, tools, phase, agents, background,
627 tasks: tasks ?? previous.tasks,
628 crons: crons ?? previous.crons,
629 todos: todos === undefined ? previous.todos : [
630 ...previous.todos.filter(list => list.agentId !== e.agentId),
631 { agentId: e.agentId, items: todos, updatedAt: now },
632 ].slice(-20),
633 updatedAt: now,
634 }
635 })
636 if (checkLabel !== undefined) {
637 const check = summarizeCheck(e.tool_use_id, checkLabel, result, { error: result.isError, denied: result.deny !== undefined }, Math.max(0, now - startedAt))
638 await updateReview($, (previous): CockpitReview => previous.sessionId === id ? {
639 ...previous,
640 checks: [...previous.checks.filter(item => item.id !== check.id), { ...check, finishedAt: now }].slice(-40),
641 } : previous)
642 }
643 if (succeeded) {
644 const changes = normalizeObservedChanges(e.tool, e, result, now)
645 if ((e.tool === 'Edit' || e.tool === 'Write') && changes.length === 0
646 && typeof output?.filePath === 'string' && output.staged !== true) {
647 changes.push({ path: output.filePath, patch: '', additions: 0, deletions: 0, source: 'observed', updatedAt: now })
648 }
649 for (const change of changes) await rememberChange($, { ...change, agentId: e.agentId }, id)
650 }
651 const gitOp = succeeded && e.tool === 'Bash' ? gitOperationOf(e.tool_use_id, result, now) : undefined
652 if (gitOp !== undefined) {
653 await updateReview($, (previous): CockpitReview => previous.sessionId === id
654 ? { ...previous, gitOps: [...previous.gitOps.filter(item => item.id !== gitOp.id), gitOp].slice(-30) } : previous)
655 }
656 if (succeeded && e.tool === 'ReportFindings' && Array.isArray(e.findings)) {
657 const findings: CockpitFinding[] = e.findings.flatMap((value, index) => {
658 const finding = record(value)
659 if (finding === null || typeof finding.file !== 'string' || typeof finding.summary !== 'string') return []
660 return [{
661 id: `${e.tool_use_id}:${index}`,
662 path: finding.file,
663 summary: clip(finding.summary, 1000),
664 line: typeof finding.line === 'number' && finding.line > 0 ? finding.line : undefined,
665 category: typeof finding.category === 'string' ? clip(finding.category, 40) : undefined,
666 verdict: typeof finding.verdict === 'string' ? clip(finding.verdict, 40) : undefined,
667 outcome: typeof finding.outcome === 'string' ? clip(finding.outcome, 40) : undefined,
668 }]
669 })
670 await updateReview($, (previous): CockpitReview => previous.sessionId === id
671 ? { ...previous, findings: [...previous.findings, ...findings].slice(-100) } : previous)
672 }
673 if (e.tool === 'Agent' || e.agentId !== undefined) await refreshAgents($)
674 })
675 return result
676 } catch (error) {
677 await observe($, async () => {
678 if (sessionId === undefined) return
679 const now = await $.clock.now()
680 await changeActivity($, sessionId, now, previous => ({
681 ...previous,
682 tools: previous.tools.map(tool => tool.id === e.tool_use_id ? { ...tool, outcome: 'error', finishedAt: now } : tool),
683 phase: 'error',
684 updatedAt: now,
685 }))
686 })
687 throw error
688 }
689 }).catch(($, e, next) => next(e))
690
691 on('turn.complete', async ($, e, next) => {
692 let id: string | undefined
693 await observe($, async () => { id = await ensureSession($) })
694 const result = await next(e)
695 await observe($, async () => {
696 if (id === undefined || await $.session.id() !== id) return
697 const now = await $.clock.now()
698 // A subagent's failure reaches its spawner as a tool error.
699 const failure = e.agentId === undefined && e.reason === 'error' ? await turnFailure($, now) : null
700 const ended = e.reason === 'answer' ? 'completed' : e.reason === 'aborted' ? 'killed' : 'failed'
701 await changeActivity($, id, now, previous => ({
702 ...previous,
703 turns: [...previous.turns.filter(turn => turn.id !== e.turnId), {
704 id: e.turnId,
705 agentId: e.agentId,
706 durationMs: e.durationMs,
707 reason: e.reason,
708 finishedAt: now,
709 usage: e.usage,
710 }].slice(-100),
711 working: e.agentId === undefined ? false : previous.working,
712 turnStartedAt: e.agentId === undefined ? null : previous.turnStartedAt,
713 phase: e.agentId === undefined ? e.reason === 'error' ? 'error' : 'idle' : previous.phase,
714 stopFailure: failure ?? previous.stopFailure,
715 background: e.agentId === undefined ? previous.background : endBackground(previous.background, e.agentId, ended, now),
716 agents: previous.agents.map(agent => agent.id === e.agentId ? {
717 ...agent,
718 completedAt: now,
719 durationMs: e.durationMs,
720 usage: e.usage,
721 answer: answerText(e.answer) ?? agent.answer,
722 } : agent),
723 updatedAt: now,
724 }))
725 await refreshAgents($)
726 })
727 return result
728 }).catch(($, e, next) => next(e))
729
730 // A firing does not name its cron. A one-shot cron is known by its prompt.
731 on('prompt.submit', async ($, e, next) => {
732 if (e.origin.kind === 'scheduled-trigger') {
733 await observe($, async () => {
734 const id = await ensureSession($)
735 const now = await $.clock.now()
736 await updateActivity($, (previous): CockpitActivity => {
737 if (previous.sessionId !== id) return previous
738 const crons = firedCrons(previous.crons, e.text, now)
739 return crons === previous.crons ? previous : { ...previous, crons }
740 })
741 })
742 }
743 return next(e)
744 }).catch(($, e, next) => next(e))
745
746 // Outside the classic Stop hook, the notification row is the only report of
747 // how a background task ended. A drawing never writes, so a timer records it,
748 // and the hook reads no state, so later writes do not redraw the row.
749 on('ui.render', { component: 'UserMessage', props: { origin: { kind: 'task-notification' } } }, async ($, e, next) => {
750 const id = e.props.task?.id
751 const status = endedStatus(e.props.task?.status)
752 if (id !== undefined && status !== undefined) $.clock.after(0, () => { void observe($, () => recordTaskEnd($, id, status)) })
753 return next(e)
754 }).catch(($, e, next) => next(e))
755
756 on('session.compact', async ($, e, next) => {
757 const result = await next(e)
758 // A precompute installs nothing. Its result waits for a later compaction.
759 if (e.trigger !== 'precompute') {
760 await observe($, async () => {
761 const id = await ensureSession($)
762 const now = await $.clock.now()
763 const entry: CockpitCompaction = result.skip !== undefined
764 ? { at: now, trigger: e.trigger, agentId: e.agentId, skipped: clip(result.skip, 240) }
765 : { at: now, trigger: e.trigger, agentId: e.agentId, tokensBefore: result.tokensBefore, tokensAfter: result.tokensAfter }
766 await updateContext($, (previous): CockpitContext => previous.sessionId === id
767 ? { ...previous, compactions: [...previous.compactions, entry].slice(-20) } : previous)
768 })
769 }
770 return result
771 }).catch(($, e, next) => next(e))
772
773 on('session.measure', async ($, e, next) => {
774 const result = await next(e)
775 await observe($, async () => {
776 const id = await ensureSession($)
777 const now = await $.clock.now()
778 const usd = e.cost?.usd
779 const fill = e.context.tokens
780 await updateContext($, (previous): CockpitContext => previous.sessionId === id ? {
781 ...previous,
782 usage: {
783 startedAt: previous.usage?.startedAt ?? now,
784 context: { ...e.context, breakdown: previous.usage?.context.breakdown },
785 rateLimits: e.rateLimits,
786 cost: e.cost,
787 },
788 costs: usd !== undefined && Number.isFinite(usd) && previous.costs.at(-1)?.usd !== usd
789 ? [...previous.costs, { at: now, usd }].slice(-100) : previous.costs,
790 fills: fill !== undefined && Number.isFinite(fill) && previous.fills.at(-1)?.tokens !== fill
791 ? [...previous.fills, { at: now, tokens: fill }].slice(-100) : previous.fills,
792 } : previous)
793 })
794 return result
795 }).catch(($, e, next) => next(e))
796
797 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
798 const prefs = await read($, preferences)
799 if (e.props.hasSurvey || !prefs.band || e.props.maxRows < 1) return next(e)
800 const [stored, r, c, beat, now] = await Promise.all([
801 read($, activity), read($, review), read($, context), read($, pulse), $.clock.now(),
802 ])
803 const ui = $.ui.resolve(e)
804 const { Box, Button } = ui
805 const frame = beat?.frame
806 // The plain one-glyph button and the gap after it take two columns.
807 const rows = bandRows(activityOf(stored), reviewOf(r), contextOf(c), {
808 isWorking: e.props.isWorking, columns: e.props.bodyColumns - 2, now, agentId: e.props.view.agentId,
809 frame: prefs.animation && typeof frame === 'number' && Number.isFinite(frame) ? frame : undefined,
810 }).slice(0, e.props.maxRows)
811 const base = await next(e)
812 return (
813 <Box flexDirection="column">
814 {base}
815 <Box flexDirection="row" columnGap={1}>
816 <Button key="cockpit-open" plain label="◉" onPress={() => { void observe($, () => openCockpit($)) }} />
817 <Box flexDirection="column" flexGrow={1} flexShrink={1} minWidth={0}>
818 {rows.map((row, index) => (
819 <Box key={`cockpit-band:${index}`} flexDirection="row" justifyContent="space-between">
820 {line(ui, `cockpit-band:${index}:start`, row.start)}
821 {row.end.length > 0 ? line(ui, `cockpit-band:${index}:end`, row.end) : null}
822 </Box>
823 ))}
824 </Box>
825 </Box>
826 </Box>
827 )
828 })
829
830 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
831 const [stored, r, c, storedPrefs, frame, now] = await Promise.all([
832 read($, activity), read($, review), read($, context), read($, preferences),
833 read($, mascot), $.clock.now(),
834 ])
835 // Hot reload keeps session memory, which an earlier version can have shaped.
836 const a = activityOf(stored)
837 const prefs: CockpitPreferences = {
838 ...storedPrefs,
839 view: VIEWS.includes(storedPrefs.view) ? storedPrefs.view : 'agents',
840 span: SPAN_ORDER.includes(storedPrefs.span) ? storedPrefs.span : 'fit',
841 }
842 const viewedAgent = e.props.view.agentId ?? null
843 // Follow the transcript in view until the person chooses while viewing it.
844 const selectedAgent = viewedAgent !== null && viewedAgent !== a.selectedFor ? viewedAgent : a.selectedAgent
845 const ui = $.ui.resolve(e)
846 const { Box, Button, Text } = ui
847 const props: CockpitViewProps = {
848 activity: { ...a, selectedAgent },
849 review: reviewOf(r),
850 context: contextOf(c),
851 preferences: prefs,
852 mascot: { frame: Number.isFinite(frame?.frame) ? frame.frame : 0, phase: mascotPhase(a) },
853 actions: actionsFor($, e.surface, viewedAgent),
854 viewedAgent,
855 columns: Math.max(12, e.props.bodyColumns),
856 rows: Math.max(6, e.props.scroll.bodyRows - 5),
857 now,
858 }
859 const content = prefs.view === 'agents' ? renderAgents(ui, props)
860 : prefs.view === 'tools' ? renderTools(ui, props)
861 : prefs.view === 'changes' ? renderChanges(ui, props)
862 : prefs.view === 'context' ? renderContext(ui, props)
863 : renderActivity(ui, props)
864 const width = Math.max(12, props.columns - 1)
865 const status = sessionStatus(props.activity, a.working)
866 const fill = contextFill(props.context)
867 const cost = props.context.usage?.cost?.usd
868 const started = sessionStart(props.activity, props.context)
869 const turns = mainTurns(props.activity).length
870 const since = status.since === undefined ? '' : ` ${brief(now - status.since)}`
871 const statusLine: Segment[] = [
872 { text: 'COCKPIT', color: colors.accent, bold: true },
873 { text: a.model ? ` ${shortModel(a.model)}` : '', color: colors.muted },
874 { text: ' · ', color: colors.muted },
875 { text: clip(`${status.glyph} ${status.label}${since}`, Math.max(8, width - 12 - shortModel(a.model).length)), color: status.color, bold: status.color !== colors.muted },
876 ]
877 const ctxColor = contextColor(fill)
878 const meterLine: Segment[] = [
879 { text: 'ctx ', color: colors.muted },
880 { text: meter(fill.percent ?? 0, Math.max(6, Math.min(16, width - 40))), color: ctxColor === colors.muted ? colors.accent : ctxColor },
881 { text: ` ${percent(fill.percent)}`, color: ctxColor === colors.muted ? undefined : ctxColor },
882 { text: cost !== undefined && Number.isFinite(cost) ? ` · ${usd(cost)}` : '', color: colors.muted },
883 { text: ` · ${turns} ${turns === 1 ? 'turn' : 'turns'}`, color: colors.muted },
884 { text: started === undefined ? '' : ` · ${brief(now - started)} session`, color: colors.muted },
885 ]
886 const live = props.activity.agents.filter(isLive).length
887 const running = runningTools(props.activity).length
888 const files = changeTotals(props.review).files
889 const ctxBadge = fill.percent !== undefined && Number.isFinite(fill.percent) ? percent(fill.percent) : ''
890 const badges: Record<CockpitView, Segment> = {
891 agents: live > 0 ? { text: `${live}▸`, color: colors.accent } : { text: props.activity.agents.length > 0 ? `${props.activity.agents.length}` : '', color: colors.muted },
892 tools: running > 0 ? { text: `${running}▸`, color: colors.accent } : { text: props.activity.tools.length > 0 ? `${props.activity.tools.length}` : '', color: colors.muted },
893 changes: { text: files > 0 ? `${files}` : '', color: colors.muted },
894 context: { text: ctxBadge, color: ctxColor },
895 activity: { text: '' },
896 }
897 const tabs = VIEWS.map(view => ({ label: viewLabels[view], badge: badges[view].text || undefined }))
898 const tabLayout = tabRows(tabs, width)
899 const activeTab = VIEWS.indexOf(prefs.view)
900 // Each plain tab reads `1: Label`; the active one is at full strength over
901 // an accent mark, the rest dim.
902 const tabBar = tabLayout.rows.flatMap((row, number) => [
903 <Box key={`cockpit:tabs:${number}`} flexDirection="row" columnGap={tabLayout.gap}>
904 {row.map(index => {
905 const view = VIEWS[index] ?? 'agents'
906 const badge = badges[view]
907 return (
908 <Box key={`cockpit:tab:${view}`} flexDirection="row">
909 <Button key={`view-${view}`} plain dimColor={prefs.view !== view} label={viewLabels[view]}
910 hotkey={String(index + 1) as '1' | '2' | '3' | '4' | '5'}
911 onPress={() => props.actions.selectView(view)} />
912 {tabLayout.badges && badge.text !== '' && <Text color={badge.color} dimColor={prefs.view !== view && badge.color === colors.muted}>{` ${badge.text}`}</Text>}
913 </Box>
914 )
915 })}
916 </Box>,
917 ...[tabMark(tabs, row, activeTab, tabLayout.badges, tabLayout.gap)].flatMap(mark => mark ? [line(ui, `cockpit:tabs:${number}:mark`, mark)] : []),
918 ])
919 const failure = a.stopFailure
920 // No backgroundColor: the dock paints its own theme fill, and a plugin cannot
921 // paint the terminal's default background over it.
922 return (
923 <Box flexDirection="column" gap={1}>
924 <Box flexDirection="column">
925 {line(ui, 'cockpit:status', statusLine)}
926 {line(ui, 'cockpit:meter', meterLine)}
927 {tabBar}
928 {failure && <Text color={colors.red} wrap="wrap">{clip(`✗ Last turn stopped: ${humanize(failure.error)}${failure.details ? ` · ${failure.details}` : ''}`, 320)}</Text>}
929 </Box>
930 {content}
931 <Text dimColor>{paneFooter(e.surface, e.props.placement, props.columns)}</Text>
932 </Box>
933 )
934 })
935}
936hooks/activity.tsx 544 lines1import type { RenderElement, ThemeKey } from 'claude-code'
2import type { CockpitActivity, CockpitContext, CockpitMascot, CockpitSample, CockpitSpan, CockpitViewProps } from '../types'
3import { agentName } from './agents'
4import { actions, field, heading, line, muted, section, viewWidth } from './layout'
5import type { Segment } from './summary'
6import {
7 activityHistory, agentElapsed, approvalCount, HISTORY_BUCKET_MS, isLive, leadTool, mainTurns, runningTools, sessionStart,
8 sessionStatus, toolDuration, toolLabel, toolStats,
9} from './summary'
10import type { CockpitElements } from './theme'
11import { brief, clip, colors, duration, humanize, padEnd, percent, plural, sparkline } from './theme'
12
13const finite = (value: number | undefined | null): value is number =>
14 typeof value === 'number' && Number.isFinite(value)
15
16// ---------------------------------------------------------------- Bongo Cat
17
18export type Pose = 'up' | 'left' | 'right' | 'both' | 'rest'
19
20/** Running tools and live agents: how hard the cat drums. */
21export const activityLoad = (activity: CockpitActivity): number =>
22 runningTools(activity).length + activity.agents.filter(agent => agent.status === 'running').length
23
24/**
25 * The cat acts out the phase: asleep on the drums when idle, a slow tap while
26 * the model thinks, both paws while tools run (faster with more at once), and
27 * paws up after an error. A paused animation holds frame 0.
28 */
29export const catPose = (phase: CockpitMascot['phase'], frame: number, load: number): Pose => {
30 if (phase === 'error') return 'up'
31 if (phase === 'idle') return 'rest'
32 if (phase === 'thinking') return frame % 4 === 0 ? 'right' : 'up'
33 if (load >= 3) return frame % 2 === 0 ? 'both' : 'up'
34 if (load === 2) return frame % 2 === 0 ? 'left' : 'right'
35 return (['left', 'up', 'right', 'up'] as const)[frame % 4] ?? 'up'
36}
37
38type Eyes = 'open' | 'closed' | 'squint' | 'crossed'
39
40const eyesFor = (phase: CockpitMascot['phase'], pose: Pose, frame: number): Eyes => {
41 if (phase === 'error') return 'crossed'
42 if (phase === 'idle') return 'closed'
43 if (pose === 'both') return 'squint'
44 return pose === 'up' && frame % 8 === 7 ? 'closed' : 'open'
45}
46
47type Glyph = { char: string; color?: ThemeKey }
48type Point = readonly [number, number]
49type Layer = 'table' | 'drum' | 'cat' | 'eyes' | 'bean' | 'hit'
50
51// The drawing follows the original Bongo Cat, in the 612 × 354 space of the
52// overlay art: the table edge falls to the right, the face tilts with it, and
53// the bongos stand in front. A raised paw is an arch with toe beans; a paw
54// that hits curls onto its drum, with impact lines under it.
55const spline = (points: readonly Point[], steps = 40): Point[] => {
56 const out: Point[] = []
57 const at = (index: number): Point => points[Math.max(0, Math.min(points.length - 1, index))] ?? [0, 0]
58 for (let index = 0; index < points.length - 1; index += 1) {
59 const [p0, p1, p2, p3] = [at(index - 1), at(index), at(index + 1), at(index + 2)]
60 for (let step = 0; step < steps; step += 1) {
61 const t = step / steps
62 const curve = (a: number, b: number, c: number, d: number): number =>
63 0.5 * (2 * b + (c - a) * t + (2 * a - 5 * b + 4 * c - d) * t * t + (3 * b - a - 3 * c + d) * t * t * t)
64 out.push([curve(p0[0], p1[0], p2[0], p3[0]), curve(p0[1], p1[1], p2[1], p3[1])])
65 }
66 }
67 out.push(at(points.length - 1))
68 return out
69}
70
71const segment = (from: Point, to: Point, steps = 30): Point[] =>
72 Array.from({ length: steps + 1 }, (_, step): Point => [from[0] + (to[0] - from[0]) * step / steps, from[1] + (to[1] - from[1]) * step / steps])
73
74const oval = (cx: number, cy: number, rx: number, ry: number, from = 0, to = 360, steps = 120): Point[] =>
75 Array.from({ length: steps + 1 }, (_, step): Point => {
76 const angle = (from + (to - from) * step / steps) * Math.PI / 180
77 return [cx + rx * Math.cos(angle), cy + ry * Math.sin(angle)]
78 })
79
80const blob = (cx: number, cy: number, rx: number, ry: number): Point[] => {
81 const out: Point[] = []
82 for (let x = -10; x <= 10; x += 1) {
83 for (let y = -10; y <= 10; y += 1) if (x * x + y * y <= 100) out.push([cx + rx * x / 10, cy + ry * y / 10])
84 }
85 return out
86}
87
88type Drum = { cx: number; cy: number; rx: number; ry: number; bottom: number }
89
90const DRUMS: readonly Drum[] = [
91 { cx: 196, cy: 214, rx: 62, ry: 20, bottom: 262 },
92 { cx: 332, cy: 236, rx: 58, ry: 19, bottom: 280 },
93]
94
95const insideDrum = (drum: Drum, x: number, y: number): boolean => {
96 if (y < drum.cy) return ((x - drum.cx) / drum.rx) ** 2 + ((y - drum.cy) / drum.ry) ** 2 <= 1
97 if (y <= drum.bottom) return Math.abs(x - drum.cx) <= drum.rx - 8 * (y - drum.cy) / (drum.bottom - drum.cy)
98 return ((x - drum.cx) / (drum.rx - 8)) ** 2 + ((y - drum.bottom) / drum.ry) ** 2 <= 1
99}
100
101const drumLines = (drum: Drum): Point[] => [
102 ...oval(drum.cx, drum.cy, drum.rx, drum.ry),
103 ...segment([drum.cx - drum.rx, drum.cy], [drum.cx - drum.rx + 8, drum.bottom], 60),
104 ...segment([drum.cx + drum.rx, drum.cy], [drum.cx + drum.rx - 8, drum.bottom], 60),
105 ...oval(drum.cx, drum.bottom, drum.rx - 8, drum.ry, 0, 180),
106]
107
108const CAT_PARTS = {
109 body: spline([[172, 106], [205, 90], [240, 72], [268, 52], [290, 26], [297, 20], [306, 30], [318, 50], [360, 55], [405, 72],
110 [440, 104], [462, 92], [481, 87], [487, 125], [476, 150], [482, 192], [497, 226], [503, 240]]),
111 table: segment([0, 150], [612, 252], 200),
112 smile: spline([[264, 138], [270, 152], [281, 155], [288, 146], [294, 155], [305, 156], [312, 146]], 12),
113 gasp: oval(288, 149, 8, 7),
114 open: [...blob(241, 131, 7, 7), ...blob(357, 166, 7, 7)],
115 closed: [...segment([231, 129], [251, 133]), ...segment([347, 164], [367, 168])],
116 squint: [...segment([232, 123], [246, 131]), ...segment([246, 131], [232, 139]), ...segment([366, 158], [352, 166]), ...segment([352, 166], [366, 174])],
117 crossed: [...segment([233, 123], [249, 139]), ...segment([249, 123], [233, 139]), ...segment([349, 158], [365, 174]), ...segment([365, 158], [349, 174])],
118 leftUp: spline([[138, 172], [133, 122], [145, 93], [165, 88], [190, 100], [207, 145]]),
119 leftBeans: [...blob(150, 135, 5, 6), ...blob(162, 118, 5, 6), ...blob(178, 133, 5, 6), ...blob(168, 153, 9, 12)],
120 leftDown: spline([[172, 108], [158, 140], [160, 190], [180, 218], [200, 224], [216, 213], [221, 196], [219, 180]]),
121 leftHit: [...segment([184, 234], [180, 252]), ...segment([207, 236], [214, 249]), ...segment([232, 221], [254, 228])],
122 rightUp: spline([[386, 215], [381, 166], [392, 136], [412, 132], [437, 146], [455, 188]]),
123 rightBeans: [...blob(398, 180, 5, 6), ...blob(409, 162, 5, 6), ...blob(425, 177, 5, 6), ...blob(416, 198, 9, 12)],
124 rightDown: spline([[425, 170], [380, 190], [342, 213], [328, 232], [350, 246], [400, 246], [450, 237], [488, 225]]),
125 rightHit: [...segment([268, 229], [298, 228]), ...segment([291, 258], [305, 245])],
126} satisfies Record<string, Point[]>
127
128type CatPart = keyof typeof CAT_PARTS
129
130/** The part of the art the cat shows: from the left table edge to past the cat, ears to drums. */
131const CAT_VIEW = { left: 40, top: 12, width: 530, height: 290 }
132/** Where the bubble's tail points (the top of the head) and the right ear, in art space. */
133const CAT_HEAD_X = 360
134const CAT_EAR_X = 481
135
136type CatSheet = { columns: number; rows: number; scale: number; base: (Layer | undefined)[]; parts: Record<CatPart, number[]> }
137
138const sheets = new Map<number, CatSheet>()
139
140// Braille cells hold 2 × 4 dots, close to square on a terminal, so one scale
141// serves both axes. Each size is traced once and kept.
142const catSheet = (columns: number): CatSheet => {
143 const cached = sheets.get(columns)
144 if (cached) return cached
145 const scale = CAT_VIEW.width / (columns * 2)
146 const rows = Math.ceil(CAT_VIEW.height / scale / 4)
147 const width = columns * 2
148 const height = rows * 4
149 const dotsOf = (points: readonly Point[]): number[] => {
150 const dots = new Set<number>()
151 for (const [x, y] of points) {
152 const dx = Math.floor((x - CAT_VIEW.left) / scale)
153 const dy = Math.floor((y - CAT_VIEW.top) / scale)
154 if (dx >= 0 && dx < width && dy >= 0 && dy < height) dots.add(dy * width + dx)
155 }
156 return [...dots]
157 }
158 const base: (Layer | undefined)[] = Array.from({ length: width * height }, () => undefined)
159 for (const dot of dotsOf(CAT_PARTS.body)) base[dot] = 'cat'
160 for (const dot of dotsOf(CAT_PARTS.table)) base[dot] = 'table'
161 // The bongos stand in front: they hide the table edge and the cat behind them.
162 for (const drum of DRUMS) {
163 for (let dot = 0; dot < base.length; dot += 1) {
164 const x = CAT_VIEW.left + (dot % width + 0.5) * scale
165 const y = CAT_VIEW.top + (Math.floor(dot / width) + 0.5) * scale
166 if (insideDrum(drum, x, y)) base[dot] = undefined
167 }
168 for (const dot of dotsOf(drumLines(drum))) base[dot] = 'drum'
169 }
170 const parts = Object.fromEntries(Object.entries(CAT_PARTS).map(([name, points]) => [name, dotsOf(points)])) as Record<CatPart, number[]>
171 const sheet = { columns, rows, scale, base, parts }
172 sheets.set(columns, sheet)
173 return sheet
174}
175
176/** The widest cat that fits: 40 columns, then 34, then down to 20. */
177export const catColumns = (width: number): number =>
178 width >= 44 ? 40 : width >= 36 ? 34 : Math.max(20, Math.min(28, Math.floor(Number.isFinite(width) ? width : 28)))
179
180/** The column of the top of the cat's head in a cat `columns` wide. */
181export const catHead = (columns: number): number => Math.floor((CAT_HEAD_X - CAT_VIEW.left) / catSheet(columns).scale / 2)
182
183const LAYER_ORDER: readonly Layer[] = ['table', 'drum', 'cat', 'eyes', 'bean', 'hit']
184const BRAILLE_BITS = [[0x01, 0x08], [0x02, 0x10], [0x04, 0x20], [0x40, 0x80]] as const
185
186/**
187 * The cat as rows of colored braille glyphs, `columns` wide. Each cell takes
188 * the color of its strongest layer: impact lines, toe beans, eyes, the cat,
189 * the drums, then the table edge.
190 */
191export const bongoCat = (phase: CockpitMascot['phase'], frame: number, load: number, columns = 40): Glyph[][] => {
192 const safeFrame = Number.isFinite(frame) ? Math.max(0, Math.floor(frame)) : 0
193 const pose = catPose(phase, safeFrame, load)
194 const sheet = catSheet(Math.max(20, Math.min(40, Math.floor(Number.isFinite(columns) ? columns : 40))))
195 const dots = sheet.base.slice()
196 const draw = (part: CatPart, layer: Layer): void => { for (const dot of sheet.parts[part]) dots[dot] = layer }
197 const leftDown = pose === 'left' || pose === 'both' || pose === 'rest'
198 const rightDown = pose === 'right' || pose === 'both' || pose === 'rest'
199 const hit = pose !== 'rest'
200 draw(phase === 'error' ? 'gasp' : 'smile', 'cat')
201 draw(eyesFor(phase, pose, safeFrame), 'eyes')
202 if (leftDown) { draw('leftDown', 'cat'); if (hit) draw('leftHit', 'hit') } else { draw('leftUp', 'cat'); draw('leftBeans', 'bean') }
203 if (rightDown) { draw('rightDown', 'cat'); if (hit) draw('rightHit', 'hit') } else { draw('rightUp', 'cat'); draw('rightBeans', 'bean') }
204 const colorOf: Record<Layer, ThemeKey | undefined> = {
205 table: colors.muted, drum: colors.yellow, cat: undefined, eyes: phase === 'error' ? colors.red : undefined, bean: colors.magenta, hit: colors.accent,
206 }
207 const width = sheet.columns * 2
208 const grid: Glyph[][] = Array.from({ length: sheet.rows }, (_, row) => Array.from({ length: sheet.columns }, (_, column): Glyph => {
209 let bits = 0
210 let strongest = -1
211 for (let dy = 0; dy < 4; dy += 1) {
212 for (let dx = 0; dx < 2; dx += 1) {
213 const layer = dots[(row * 4 + dy) * width + column * 2 + dx]
214 if (layer === undefined) continue
215 bits |= BRAILLE_BITS[dy]?.[dx] ?? 0
216 strongest = Math.max(strongest, LAYER_ORDER.indexOf(layer))
217 }
218 }
219 // An empty cell is a space: some fonts draw the blank braille pattern.
220 if (bits === 0) return { char: ' ' }
221 const layer = LAYER_ORDER[strongest]
222 return { char: String.fromCharCode(0x2800 + bits), color: layer === undefined ? undefined : colorOf[layer] }
223 }))
224 const ear = Math.floor((CAT_EAR_X - CAT_VIEW.left) / sheet.scale / 2)
225 const put = (row: number, column: number, char: string, color: ThemeKey): void => {
226 const cell = grid[row]?.[Math.min(sheet.columns - 1, column)]
227 if (cell) { cell.char = char; cell.color = color }
228 }
229 if (phase === 'idle') {
230 const drift = safeFrame % 4 < 2 ? 0 : 1
231 put(1, ear + 2 + drift, 'z', colors.muted)
232 put(0, ear + 4 + drift, 'Z', colors.muted)
233 }
234 if (phase === 'error') put(0, ear + 3, '!', colors.red)
235 if (phase === 'thinking' && safeFrame % 8 >= 4) put(0, ear + 3, '?', colors.cyan)
236 return grid
237}
238
239/** What the cat says: the tool it drums for, the thought, the error, or sleep. */
240export const catSays = (activity: CockpitActivity, now: number): { text: string; color: ThemeKey } => {
241 const status = sessionStatus(activity, activity.working)
242 if (activity.stopFailure && !activity.working) return { text: `stopped: ${humanize(activity.stopFailure.error)}`, color: colors.red }
243 const running = runningTools(activity)
244 const lead = leadTool(running)
245 if (lead) {
246 const more = running.length > 1 ? ` +${running.length - 1}` : ''
247 return { text: `${toolLabel(lead)} · ${brief(now - lead.startedAt)}${more}`, color: colors.cyan }
248 }
249 if (activity.working) {
250 return { text: activity.turnStartedAt === null ? 'thinking' : `thinking · ${brief(now - activity.turnStartedAt)}`, color: colors.cyan }
251 }
252 if (status.label === 'last turn failed') return { text: 'last turn failed', color: colors.red }
253 const last = mainTurns(activity).at(-1)
254 return { text: last ? `zzz · idle ${brief(now - last.finishedAt)}` : 'zzz', color: colors.muted }
255}
256
257const toSegments = (row: readonly Glyph[]): Segment[] => {
258 const segments: Segment[] = []
259 for (const glyph of row) {
260 const last = segments[segments.length - 1]
261 if (last && last.color === glyph.color) last.text += glyph.char
262 else segments.push({ text: glyph.char, color: glyph.color })
263 }
264 return segments
265}
266
267const catBlock = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement => {
268 const { Box } = ui
269 const load = activityLoad(props.activity)
270 const frame = props.preferences.animation ? props.mascot.frame : 0
271 const columns = catColumns(width)
272 const grid = bongoCat(props.mascot.phase, frame, load, columns)
273 const says = catSays(props.activity, props.now)
274 const text = clip(says.text, Math.max(8, width - 6))
275 const inner = [...text].length + 2
276 const blockWidth = Math.max(columns, inner + 2)
277 // Center the bubble and the cat in one block, the tail over the cat's head.
278 const bubbleAt = Math.floor((blockWidth - inner - 2) / 2)
279 const catAt = Math.floor((blockWidth - columns) / 2)
280 const tail = Math.max(bubbleAt + 1, Math.min(bubbleAt + inner, catAt + catHead(columns)))
281 const border = colors.muted
282 const pad = (segments: Segment[], used: number): Segment[] => [...segments, { text: ' '.repeat(Math.max(0, blockWidth - used)) }]
283 const rows: Segment[][] = [
284 pad([{ text: `${' '.repeat(bubbleAt)}╭${'─'.repeat(inner)}╮`, color: border }], bubbleAt + inner + 2),
285 pad([{ text: `${' '.repeat(bubbleAt)}│ `, color: border }, { text, color: says.color, bold: true }, { text: ' │', color: border }], bubbleAt + inner + 2),
286 pad([{ text: `${' '.repeat(bubbleAt)}╰${'─'.repeat(tail - bubbleAt - 1)}┬${'─'.repeat(bubbleAt + inner - tail)}╯`, color: border }], bubbleAt + inner + 2),
287 pad([{ text: `${' '.repeat(tail)}│`, color: border }], tail + 1),
288 ...grid.map(row => pad([{ text: ' '.repeat(catAt) }, ...toSegments(row)], catAt + columns)),
289 ]
290 return (
291 <Box key="activity:cat" flexDirection="column" alignItems="center" width="100%">
292 {rows.map((segments, index) => line(ui, `activity:cat:${index}`, segments))}
293 </Box>
294 )
295}
296
297// ---------------------------------------------------------------- timeline
298
299/** Cell states, in the order one overrides another within a cell. */
300export const LANE = { absent: -1, idle: 0, model: 1, agent: 2, tool: 3, error: 4 } as const
301type LaneState = typeof LANE[keyof typeof LANE]
302
303const laneGlyph: Record<LaneState, Glyph> = {
304 [-1]: { char: ' ' },
305 0: { char: '·', color: colors.muted },
306 1: { char: '▒', color: colors.accent },
307 2: { char: '▓', color: colors.magenta },
308 3: { char: '█', color: colors.cyan },
309 4: { char: '█', color: colors.red },
310}
311
312const SPANS: Record<Exclude<CockpitSpan, 'fit'>, number> = { '5m': 300000, '15m': 900000, '60m': 3600000 }
313const NICE_CELLS = [1, 2, 3, 5, 10, 15, 20, 30, 45, 60, 90, 120, 180, 300, 600, 900, 1200, 1800, 3600].map(seconds => seconds * 1000)
314
315export const SPAN_ORDER: CockpitSpan[] = ['fit', '5m', '15m', '60m']
316
317/** The cell size and start: a fixed span, or since the first event for `fit`. */
318export const timelineScale = (span: CockpitSpan, first: number | undefined, now: number, cells: number): { cellMs: number; start: number } => {
319 const columns = Math.max(1, Math.floor(cells))
320 const wanted = span === 'fit' ? Math.max(60000, now - (first ?? now)) : SPANS[span]
321 const cellMs = NICE_CELLS.find(size => size * columns >= wanted) ?? NICE_CELLS[NICE_CELLS.length - 1] ?? 3600000
322 return { cellMs, start: now - cellMs * columns }
323}
324
325type Interval = { from: number; to: number; state: LaneState }
326export type Lane = { id?: string; label: string; cells: LaneState[] }
327
328const laneIntervals = (activity: CockpitActivity, id: string | undefined, now: number): { intervals: Interval[]; from?: number; to?: number } => {
329 const intervals: Interval[] = []
330 for (const turn of activity.turns.filter(item => item.agentId === id)) {
331 intervals.push({ from: turn.finishedAt - turn.durationMs, to: turn.finishedAt, state: LANE.model })
332 }
333 let from: number | undefined
334 let to: number | undefined
335 if (id === undefined) {
336 if (activity.working && activity.turnStartedAt !== null) intervals.push({ from: activity.turnStartedAt, to: now, state: LANE.model })
337 } else {
338 const agent = activity.agents.find(item => item.id === id)
339 if (agent?.startedAt !== undefined) {
340 from = agent.startedAt
341 to = isLive(agent) ? now : agent.completedAt ?? agent.lastSeenAt
342 intervals.push({ from, to, state: LANE.model })
343 }
344 }
345 for (const tool of activity.tools.filter(item => item.agentId === id)) {
346 const end = tool.finishedAt ?? (tool.outcome === 'running' ? now : tool.startedAt)
347 intervals.push({ from: tool.startedAt, to: end, state: tool.tool === 'Agent' ? LANE.agent : LANE.tool })
348 if (tool.outcome === 'error' || tool.outcome === 'denied') intervals.push({ from: end, to: end, state: LANE.error })
349 from = from === undefined ? tool.startedAt : Math.min(from, tool.startedAt)
350 to = to === undefined ? end : Math.max(to, end)
351 }
352 return { intervals, from, to }
353}
354
355export const timelineLanes = (
356 activity: CockpitActivity, now: number, start: number, cellMs: number, cells: number, maxLanes = 6, sessionFrom?: number,
357): Lane[] => {
358 const windowEnd = start + cellMs * cells
359 const agents = activity.agents
360 .filter(agent => agent.startedAt !== undefined || activity.tools.some(tool => tool.agentId === agent.id))
361 .map(agent => ({ agent, span: laneIntervals(activity, agent.id, now) }))
362 .filter(entry => (entry.span.to ?? 0) >= start)
363 .sort((left, right) => (left.span.from ?? 0) - (right.span.from ?? 0))
364 .slice(-Math.max(0, maxLanes - 1))
365 const main = laneIntervals(activity, undefined, now)
366 const lanes = [
367 { id: undefined, label: 'main', span: { ...main, from: sessionFrom ?? main.from, to: now }, bounded: sessionFrom !== undefined },
368 ...agents.map(entry => ({ id: entry.agent.id, label: agentName(entry.agent), span: entry.span, bounded: true })),
369 ]
370 return lanes.map(lane => {
371 const states: LaneState[] = []
372 for (let index = 0; index < cells; index += 1) {
373 const from = start + index * cellMs
374 const to = Math.min(windowEnd, from + cellMs)
375 let state: LaneState = lane.bounded && (lane.span.from === undefined || to <= lane.span.from || from >= (lane.span.to ?? now)) ? LANE.absent : LANE.idle
376 if (from >= now) state = LANE.absent
377 for (const interval of lane.span.intervals) {
378 const overlaps = interval.from === interval.to ? interval.from >= from && interval.from < to : interval.from < to && interval.to > from
379 if (overlaps && interval.state > state) state = interval.state
380 }
381 states.push(state)
382 }
383 return { id: lane.id, label: lane.label, cells: states }
384 })
385}
386
387const laneSegments = (cells: readonly LaneState[]): Segment[] => toSegments(cells.map(state => laneGlyph[state]))
388
389export type TimeBudget = {
390 sessionMs?: number
391 busyMs: number
392 toolMs: number
393 topTools: { tool: string; ms: number }[]
394 agentMs: number
395 agents: number
396 approvals: number
397 peak: number
398 average?: number
399 calls: number
400 failures: number
401}
402
403/** Where the session's time went: the main turn, tools, agents, and approval prompts. */
404export const timeBudget = (activity: CockpitActivity, context: CockpitContext, now: number): TimeBudget => {
405 const started = sessionStart(activity, context)
406 const turns = mainTurns(activity)
407 const busy = turns.reduce((total, turn) => total + turn.durationMs, 0)
408 + (activity.working && activity.turnStartedAt !== null ? Math.max(0, now - activity.turnStartedAt) : 0)
409 const tools = activity.tools.filter(tool => tool.tool !== 'Agent')
410 const sorted = activity.samples.filter(sample => finite(sample.at) && finite(sample.level)).slice().sort((left, right) => left.at - right.at)
411 let weighted = 0
412 let active = 0
413 sorted.forEach((sample, index) => {
414 const end = sorted[index + 1]?.at ?? now
415 if (sample.level > 0) { weighted += sample.level * (end - sample.at); active += end - sample.at }
416 })
417 return {
418 sessionMs: finite(started) ? Math.max(0, now - started) : undefined,
419 busyMs: busy,
420 toolMs: tools.reduce((total, tool) => total + (toolDuration(tool, now) ?? 0), 0),
421 topTools: toolStats(tools, now).slice(0, 3).map(stat => ({ tool: stat.tool, ms: stat.totalMs })),
422 agentMs: activity.agents.reduce((total, agent) => total + (agentElapsed(agent, now) ?? 0), 0),
423 agents: activity.agents.length,
424 approvals: approvalCount(activity.tools),
425 peak: Math.max(0, ...sorted.map(sample => sample.level)),
426 average: active > 0 ? weighted / active : undefined,
427 calls: activity.tools.length,
428 failures: activity.tools.filter(tool => tool.outcome === 'error' || tool.outcome === 'denied').length,
429 }
430}
431
432const timelineSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement => {
433 const { Box } = ui
434 const labelWidth = Math.min(10, Math.max(6, Math.floor(width / 6)))
435 const cells = Math.max(10, width - labelWidth - 1)
436 const first = sessionStart(props.activity, props.context)
437 const { cellMs, start } = timelineScale(props.preferences.span, first, props.now, cells)
438 const lanes = timelineLanes(props.activity, props.now, start, cellMs, cells, 6, first)
439 const left = `-${brief(props.now - start)}`
440 const middle = `-${brief((props.now - start) / 2)}`
441 const axisGap = Math.max(1, Math.floor((cells - left.length - middle.length - 3) / 2))
442 const legend: Segment[] = [
443 { text: '█', color: colors.cyan }, { text: ' tool ', color: colors.muted },
444 { text: '▒', color: colors.accent }, { text: ' model ', color: colors.muted },
445 { text: '▓', color: colors.magenta }, { text: ' agent ', color: colors.muted },
446 { text: '█', color: colors.red }, { text: ' error', color: colors.muted },
447 ]
448 return (
449 <Box key="activity:timeline" flexDirection="column" width="100%">
450 {heading(ui, 'activity:timeline:title', 'Timeline', [
451 { text: `${brief(cellMs * cells)} · 1 cell ${brief(cellMs)}`, color: colors.muted },
452 ], width)}
453 {lanes.map(lane => line(ui, `activity:lane:${lane.id ?? 'main'}`, [
454 { text: `${padEnd(clip(lane.label, labelWidth - 1), labelWidth - 1)} `, color: lane.id === undefined ? colors.accent : colors.magenta },
455 ...laneSegments(lane.cells),
456 ]))}
457 {line(ui, 'activity:axis', [{ text: `${' '.repeat(labelWidth)}${left}${' '.repeat(axisGap)}${middle}${' '.repeat(axisGap)}now`, color: colors.muted }])}
458 {line(ui, 'activity:legend', legend, true)}
459 {actions(ui, 'activity:timeline:actions', [
460 { key: 'activity:span', label: `Zoom: ${props.preferences.span === 'fit' ? 'session' : `last ${props.preferences.span}`}`, hotkey: 'z', onPress: props.actions.cycleSpan },
461 { key: 'activity:animation', label: props.preferences.animation ? 'Pause cat' : 'Wake cat', hotkey: 'p', onPress: props.actions.toggleAnimation },
462 ])}
463 </Box>
464 )
465}
466
467const budgetSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement => {
468 const budget = timeBudget(props.activity, props.context, props.now)
469 const share = finite(budget.sessionMs) && budget.sessionMs > 0 ? ` (${percent(budget.busyMs / budget.sessionMs * 100)})` : ''
470 const busyMinutes = budget.busyMs / 60000
471 return section(ui, 'activity:budget', [
472 heading(ui, 'activity:budget:title', 'Where time went', [], width),
473 field(ui, 'activity:budget:session', 'Session', [
474 { text: finite(budget.sessionMs) ? duration(budget.sessionMs) : 'unknown' },
475 { text: ' · main busy ', color: colors.muted }, { text: `${duration(budget.busyMs)}${share}` },
476 ], 10),
477 field(ui, 'activity:budget:tools', 'Tools', [
478 { text: duration(budget.toolMs) },
479 ...budget.topTools.flatMap(tool => [{ text: ' · ', color: colors.muted }, { text: tool.tool }, { text: ` ${brief(tool.ms)}`, color: colors.muted }]),
480 ], 10),
481 budget.agents > 0 ? field(ui, 'activity:budget:agents', 'Agents', [
482 { text: plural(budget.agents, 'agent') }, { text: ` · ${duration(budget.agentMs)} total`, color: colors.muted },
483 ], 10) : null,
484 field(ui, 'activity:budget:approval', 'Approval', budget.approvals === 0 ? [{ text: 'none asked', color: colors.muted }] : [
485 { text: plural(budget.approvals, 'prompt'), color: colors.yellow },
486 ], 10),
487 field(ui, 'activity:budget:parallel', 'Parallel', [
488 { text: `peak ${budget.peak}` },
489 { text: budget.average === undefined ? '' : ` · avg ${budget.average.toFixed(1)} while active`, color: colors.muted },
490 ], 10),
491 field(ui, 'activity:budget:pace', 'Pace', [
492 { text: plural(budget.calls, 'call') },
493 { text: busyMinutes >= 0.5 ? ` · ${(budget.calls / busyMinutes).toFixed(1)}/min busy` : '', color: colors.muted },
494 { text: budget.failures > 0 ? ` · ${budget.failures} failed` : '', color: colors.red },
495 ], 10),
496 ])
497}
498
499const phaseLabel: Record<CockpitMascot['phase'], string> = {
500 idle: 'idle', thinking: 'thinking', tools: 'running tools', error: 'error',
501}
502
503export const renderActivity = (ui: CockpitElements, props: CockpitViewProps): RenderElement => {
504 const { Box } = ui
505 const width = viewWidth(props)
506 const status = sessionStatus(props.activity, props.activity.working)
507 const tools = runningTools(props.activity).length
508 const agents = props.activity.agents.filter(agent => agent.status === 'running').length
509 const history = activityHistory(props.activity.samples, props.now, width)
510 const wide = width >= 100
511 const left = wide ? Math.floor((width - 2) / 2) : width
512 const right = wide ? width - left - 2 : width
513 const top = [
514 heading(ui, 'activity:title', 'Activity', [
515 { text: phaseLabel[props.mascot.phase], color: status.color },
516 { text: props.preferences.animation ? '' : ' · paused', color: colors.muted },
517 ], width),
518 catBlock(ui, props, width),
519 line(ui, 'activity:counts', [
520 { text: plural(tools, 'tool'), color: tools > 0 ? colors.cyan : colors.muted },
521 { text: ' · ', color: colors.muted },
522 { text: plural(agents, 'agent'), color: agents > 0 ? colors.magenta : colors.muted },
523 { text: props.activity.working && props.activity.turnStartedAt !== null ? ` · turn ${brief(props.now - props.activity.turnStartedAt)}` : '', color: colors.muted },
524 ]),
525 history.length > 0 ? line(ui, 'activity:history', [{ text: sparkline(history, width), color: colors.cyan }]) : null,
526 history.length > 0 ? muted(ui, 'activity:history:legend', `Concurrency, last ${brief(history.length * HISTORY_BUCKET_MS)}: tools, agents, and the main turn`) : null,
527 ].filter((child): child is RenderElement => Boolean(child))
528 const timeline = timelineSection(ui, props, left)
529 const budget = budgetSection(ui, props, right)
530 return (
531 <Box flexDirection="column" gap={1} width="100%">
532 <Box key="activity:top" flexDirection="column" width="100%">{top}</Box>
533 {wide ? (
534 <Box key="activity:bottom" flexDirection="row" gap={2} width="100%" alignItems="flex-start">
535 <Box flexDirection="column" width={left} flexShrink={0}>{timeline}</Box>
536 <Box flexDirection="column" width={right} flexShrink={0}>{budget}</Box>
537 </Box>
538 ) : (
539 <Box key="activity:bottom" flexDirection="column" gap={1} width="100%">{timeline}{budget}</Box>
540 )}
541 </Box>
542 )
543}
544hooks/agents.tsx 285 lines1import type { RenderElement, ThemeKey } from 'claude-code'
2import type { CockpitAgent, CockpitTodo, CockpitViewProps } from '../types'
3import { actions, card, field, heading, line, listLimit, muted, neighboringIndex, section, spread, viewWidth, visibleWindow } from './layout'
4import type { Segment } from './summary'
5import {
6 agentElapsed, agentTokens, cacheHit, isLive, mainTurns, runningTools, sessionStatus, tokenTotals, toolDuration,
7 toolLabel, toolStats,
8} from './summary'
9import type { CockpitElements } from './theme'
10import {
11 ago, brief, cleanText, clip, colors, compact, count, duration, meter, padStart, percent, plural, shortModel, statusColor,
12 statusGlyph,
13} from './theme'
14
15export const agentStatusLabel = (agent: CockpitAgent): string => {
16 if (agent.status === 'missing') return 'unknown (not listed)'
17 return agent.teammateId ? `last reported: ${agent.status}` : agent.status
18}
19
20export type AgentRow = { agent: CockpitAgent; depth: number; last: boolean }
21
22export const agentHierarchy = (agents: readonly CockpitAgent[]): AgentRow[] => {
23 const bounded = agents.slice(0, 100)
24 const ids = new Set(bounded.map(agent => agent.id))
25 const children = new Map<string | undefined, CockpitAgent[]>()
26 for (const agent of bounded) {
27 const parent = agent.parentId && ids.has(agent.parentId) ? agent.parentId : undefined
28 const siblings = children.get(parent) ?? []
29 siblings.push(agent)
30 children.set(parent, siblings)
31 }
32 const rows: AgentRow[] = []
33 const visited = new Set<string>()
34 const visit = (agent: CockpitAgent, depth: number, last: boolean): void => {
35 if (visited.has(agent.id)) return
36 visited.add(agent.id)
37 rows.push({ agent, depth, last })
38 const kids = (children.get(agent.id) ?? []).filter(child => !visited.has(child.id))
39 kids.forEach((child, index) => visit(child, depth + 1, index === kids.length - 1))
40 }
41 const roots = children.get(undefined) ?? []
42 roots.forEach((agent, index) => visit(agent, 0, index === roots.length - 1))
43 // Cycles have no root. Keep those agents visible without walking the cycle twice.
44 for (const agent of bounded) visit(agent, 0, true)
45 return rows
46}
47
48export const agentName = (agent: CockpitAgent): string => cleanText(agent.name || agent.description || agent.id)
49
50export const actorName = (props: CockpitViewProps, id: string | undefined): string => {
51 if (!id) return 'main'
52 const agent = props.activity.agents.find(item => item.id === id)
53 return agent ? agentName(agent) : `agent ${cleanText(id)}`
54}
55
56// Stored answers are already cleaned. `clip` would also turn their newlines into spaces.
57const excerpt = (value: string, limit: number): string =>
58 value.length <= limit ? value : `${value.slice(0, limit - 1)}…`
59
60const todoMark: Record<CockpitTodo['status'], string> = { completed: '✓', in_progress: '▸', pending: '○' }
61const todoColor: Record<CockpitTodo['status'], ThemeKey> = { completed: colors.green, in_progress: colors.cyan, pending: colors.muted }
62
63/** The plan in its own order, windowed around the item in progress. */
64const checklist = (
65 ui: CockpitElements, key: string, items: readonly { status: CockpitTodo['status']; text: string }[], columns: number, limit = 8,
66): RenderElement[] => {
67 const current = Math.max(0, items.findIndex(item => item.status === 'in_progress'))
68 const shown = visibleWindow(items, current, limit)
69 const start = items.indexOf(shown[0] as typeof items[number])
70 const rows = shown.map((item, index) =>
71 line(ui, `${key}:${start + index}`, [
72 { text: `${todoMark[item.status]} `, color: todoColor[item.status] },
73 { text: clip(item.text, columns - 2), color: item.status === 'completed' ? colors.muted : undefined, bold: item.status === 'in_progress' },
74 ]))
75 if (start > 0) rows.unshift(muted(ui, `${key}:before`, ` ${start} done above`))
76 const after = items.length - start - shown.length
77 if (after > 0) rows.push(muted(ui, `${key}:after`, ` ${after} more`))
78 return rows
79}
80
81const progressDetail = (done: number, total: number, columns: number): Segment[] => [
82 { text: `${done}/${total} `, color: done === total ? colors.green : colors.accent },
83 { text: meter(total === 0 ? 0 : done / total * 100, Math.max(6, Math.min(16, columns))), color: done === total ? colors.green : colors.cyan },
84]
85
86const planSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
87 const todos = props.activity.todos.find(list => list.agentId === undefined)?.items ?? []
88 const tasks = props.activity.tasks
89 if (todos.length === 0 && tasks.length === 0) return null
90 const items = todos.length > 0
91 ? todos.map(todo => ({ status: todo.status, text: todo.status === 'in_progress' ? todo.activeForm : todo.content }))
92 : tasks.map(task => ({ status: task.status, text: `#${task.id} ${task.subject}${task.owner ? ` · ${task.owner}` : ''}` }))
93 const done = items.filter(item => item.status === 'completed').length
94 return section(ui, 'agents:plan', [
95 heading(ui, 'agents:plan:title', todos.length > 0 ? 'Plan' : 'Tasks', progressDetail(done, items.length, width - 20), width),
96 ...checklist(ui, 'agents:plan:item', items, width),
97 todos.length > 0 && tasks.length > 0 ? muted(ui, 'agents:plan:tasks', `Tasks ${tasks.filter(task => task.status === 'completed').length}/${tasks.length} done`) : null,
98 ])
99}
100
101const sessionSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement => {
102 const { activity } = props
103 const status = sessionStatus(activity, activity.working)
104 const turns = mainTurns(activity)
105 const totals = tokenTotals(turns.map(turn => turn.usage))
106 const hit = cacheHit(totals)
107 const failures = activity.tools.filter(tool => tool.outcome === 'error' || tool.outcome === 'denied').length
108 const agents = activity.agents
109 const agentTotal = agents.reduce((total, agent) => total + (agentTokens(agent) ?? 0), 0)
110 const average = turns.length > 0 ? turns.reduce((total, turn) => total + turn.durationMs, 0) / turns.length : undefined
111 const since = status.since === undefined ? '' : ` · ${brief(props.now - status.since)}`
112 const turnClock = activity.working && activity.turnStartedAt !== null && status.label !== 'thinking'
113 ? ` · turn ${brief(props.now - activity.turnStartedAt)}` : ''
114 return section(ui, 'agents:session', [
115 heading(ui, 'agents:session:title', 'Session', [{ text: shortModel(activity.model || 'model unknown'), color: colors.muted }], width),
116 line(ui, 'agents:session:status', [
117 { text: `${status.glyph} `, color: status.color },
118 { text: clip(`${status.label}${since}${turnClock}`, width - 2), color: status.color, bold: true },
119 ]),
120 line(ui, 'agents:session:turns', [
121 { text: plural(turns.length, 'turn') },
122 { text: average === undefined ? '' : ` · avg ${duration(average)}`, color: colors.muted },
123 { text: ` · ${plural(activity.tools.length, 'tool call')}` },
124 { text: failures > 0 ? ` · ${failures} failed` : '', color: colors.red },
125 ]),
126 totals.input + totals.output + totals.cacheRead > 0 ? line(ui, 'agents:session:tokens', [
127 { text: 'in ', color: colors.muted }, { text: compact(totals.input) },
128 { text: ' · out ', color: colors.muted }, { text: compact(totals.output) },
129 { text: ' · cache ', color: colors.muted }, { text: compact(totals.cacheRead + totals.cacheWrite) },
130 { text: hit === undefined ? '' : ` · ${percent(hit)} hit`, color: hit !== undefined && hit < 50 ? colors.yellow : colors.green },
131 ]) : null,
132 agents.length > 0 ? line(ui, 'agents:session:agents', [
133 { text: plural(agents.length, 'agent') },
134 { text: ` · ${agents.filter(isLive).length} live`, color: colors.cyan },
135 { text: agentTotal > 0 ? ` · ${compact(agentTotal)} tokens` : '', color: colors.muted },
136 ]) : null,
137 ])
138}
139
140const rowDetail = (props: CockpitViewProps, agent: CockpitAgent): Segment[] => {
141 const elapsed = agentElapsed(agent, props.now)
142 const time = elapsed === undefined ? '' : brief(elapsed)
143 if (isLive(agent)) {
144 const current = runningTools(props.activity).find(tool => tool.agentId === agent.id)
145 return [
146 { text: current ? `▸ ${clip(current.tool, 12)} ` : `${agent.status} `, color: colors.cyan },
147 { text: padStart(time, 5), color: colors.muted },
148 ]
149 }
150 const tokens = agentTokens(agent)
151 return [
152 { text: tokens === undefined ? `${agent.status} ` : `${compact(tokens)} `, color: tokens === undefined ? statusColor(agent.status) : colors.muted },
153 { text: padStart(time, 5), color: colors.muted },
154 ]
155}
156
157const agentList = (ui: CockpitElements, props: CockpitViewProps, width: number, selected: CockpitAgent | undefined): RenderElement => {
158 const { Box, Button, Text } = ui
159 const rows = agentHierarchy(props.activity.agents)
160 const selectedIndex = Math.max(0, rows.findIndex(row => row.agent.id === selected?.id))
161 const visible = visibleWindow(rows, selectedIndex, listLimit(props))
162 const live = props.activity.agents.filter(isLive).length
163 const done = props.activity.agents.filter(agent => agent.status === 'completed').length
164 const failed = props.activity.agents.filter(agent => agent.status === 'failed' || agent.status === 'killed').length
165 const chooseNeighbor = (direction: number): Promise<void> => {
166 const next = rows[neighboringIndex(rows.length, selectedIndex, direction)]?.agent
167 return next ? props.actions.selectAgent(next.id) : Promise.resolve()
168 }
169 return section(ui, 'agents:list', [
170 heading(ui, 'agents:list:title', 'Agents', [
171 { text: `${live} live`, color: live > 0 ? colors.cyan : colors.muted },
172 { text: ` · ${done} done`, color: colors.muted },
173 { text: failed > 0 ? ` · ${failed} failed` : '', color: colors.red },
174 ], width),
175 rows.length === 0 ? muted(ui, 'agents:list:empty', 'No subagents yet. They appear here when the session starts one.') : null,
176 ...visible.map(({ agent, depth, last }) => {
177 const indent = depth === 0 ? '' : `${' '.repeat(Math.min(3, depth - 1))}${last ? '└ ' : '├ '}`
178 const marker = agent.id === selected?.id ? '›' : ' '
179 const viewing = agent.id === props.viewedAgent ? ' ◉' : ''
180 const detail = rowDetail(props, agent)
181 const detailWidth = detail.reduce((total, segment) => total + [...segment.text].length, 0)
182 const nameWidth = Math.max(6, width - detailWidth - [...indent].length - 5 - viewing.length)
183 return spread(ui, `agents:row:${agent.id}`, (
184 <Box flexDirection="row">
185 <Text color={agent.id === selected?.id ? colors.accent : colors.muted}>{marker} {indent}</Text>
186 <Text color={statusColor(agent.status)}>{statusGlyph(agent.status)} </Text>
187 <Button key={`agents:select:${agent.id}`} plain label={`${clip(agentName(agent), nameWidth)}${viewing}`} onPress={() => props.actions.selectAgent(agent.id)} />
188 </Box>
189 ), detail)
190 }),
191 rows.length > visible.length ? muted(ui, 'agents:list:more', `Showing ${visible.length} of ${rows.length}.`) : null,
192 actions(ui, 'agents:list:actions', [
193 { key: 'agents:refresh', label: 'Refresh', hotkey: 'r', onPress: props.actions.refreshAgents },
194 { key: 'agents:prev', label: 'Previous', hotkey: 'k', onPress: () => chooseNeighbor(-1), hidden: rows.length < 2 },
195 { key: 'agents:next', label: 'Next', hotkey: 'j', onPress: () => chooseNeighbor(1), hidden: rows.length < 2 },
196 ]),
197 ])
198}
199
200const agentDetail = (ui: CockpitElements, props: CockpitViewProps, agent: CockpitAgent, width: number): RenderElement => {
201 const { Markdown } = ui
202 const inner = width - 4
203 const tools = props.activity.tools.filter(tool => tool.agentId === agent.id)
204 const recent = tools.slice().sort((left, right) => right.startedAt - left.startedAt).slice(0, 4)
205 const mix = toolStats(tools, props.now).sort((left, right) => right.calls - left.calls).slice(0, 4)
206 const todos = props.activity.todos.find(list => list.agentId === agent.id)?.items ?? []
207 const elapsed = agentElapsed(agent, props.now)
208 const tokens = agentTokens(agent)
209 const usage = agent.usage
210 const totals = agent.totals
211 const timing = isLive(agent)
212 ? `${elapsed === undefined ? 'running' : `running ${duration(elapsed)}`}`
213 : `${agentStatusLabel(agent)}${agent.completedAt === undefined ? '' : ` ${ago(props.now, agent.completedAt)}`}${elapsed === undefined ? '' : ` · ran ${duration(elapsed)}`}`
214 return card(ui, `agents:detail:${agent.id}`, [
215 spread(ui, 'agents:detail:title', line(ui, 'agents:detail:name', [
216 { text: `${statusGlyph(agent.status)} `, color: statusColor(agent.status) },
217 { text: clip(agentName(agent), inner - 18), bold: true },
218 ]), [{ text: clip(agent.type, 16), color: colors.magenta }]),
219 agent.name && agent.description && agent.description !== agent.name ? muted(ui, 'agents:detail:description', clip(agent.description, inner * 2)) : null,
220 field(ui, 'agents:detail:status', 'Status', [{ text: timing, color: statusColor(agent.status) }]),
221 field(ui, 'agents:detail:parent', 'Parent', [{ text: actorName(props, agent.parentId) }, { text: agent.id === props.viewedAgent ? ' · in view' : '', color: colors.accent }]),
222 tokens !== undefined ? field(ui, 'agents:detail:tokens', 'Tokens', [
223 { text: count(tokens) },
224 { text: totals ? ` · ${plural(totals.toolUses, 'tool use')}` : usage ? ` · in ${compact(usage.input_tokens)} out ${compact(usage.output_tokens)}` : '', color: colors.muted },
225 ]) : null,
226 totals && (totals.linesAdded !== undefined || totals.linesRemoved !== undefined) ? field(ui, 'agents:detail:lines', 'Lines', [
227 { text: `+${count(totals.linesAdded ?? 0)}`, color: colors.green }, { text: ' ' }, { text: `−${count(totals.linesRemoved ?? 0)}`, color: colors.red },
228 ]) : null,
229 totals && totals.models.length > 0 ? field(ui, 'agents:detail:models', 'Models', [{ text: totals.models.map(shortModel).join(', '), color: colors.muted }])
230 : usage ? field(ui, 'agents:detail:model', 'Model', [{ text: shortModel(usage.model), color: colors.muted }]) : null,
231 mix.length > 0 ? field(ui, 'agents:detail:mix', 'Tools', mix.flatMap((stat, index) => [
232 { text: index > 0 ? ' · ' : '', color: colors.muted }, { text: stat.tool }, { text: ` ${stat.calls}`, color: colors.muted },
233 ])) : null,
234 agent.teammateId ? muted(ui, 'agents:detail:teammate', 'A teammate status is its last report.') : null,
235 agent.status === 'missing' ? muted(ui, 'agents:detail:missing', 'Not listed on the last refresh.') : null,
236 todos.length > 0 ? heading(ui, 'agents:detail:todos', 'Todos', progressDetail(todos.filter(todo => todo.status === 'completed').length, todos.length, 10), inner) : null,
237 ...(todos.length > 0 ? checklist(ui, `agents:detail:todo:${agent.id}`, todos.map(todo => ({ status: todo.status, text: todo.status === 'in_progress' ? todo.activeForm : todo.content })), inner, 5) : []),
238 recent.length > 0 ? heading(ui, 'agents:detail:recent', 'Recent', [{ text: `${tools.length} calls`, color: colors.muted }], inner) : null,
239 ...recent.map(tool => {
240 const elapsed = toolDuration(tool, props.now)
241 return spread(ui, `agents:detail:tool:${tool.id}`, line(ui, `agents:detail:tool:${tool.id}:label`, [
242 { text: `${statusGlyph(tool.outcome)} `, color: statusColor(tool.outcome) },
243 { text: clip(toolLabel(tool), inner - 10) },
244 ]), [{ text: elapsed === undefined ? '' : brief(elapsed), color: colors.muted }])
245 }),
246 agent.answer ? heading(ui, 'agents:detail:answer', 'Answer', [], inner) : null,
247 agent.answer ? <Markdown key={`agents:answer:${agent.id}`} text={excerpt(agent.answer, 1200)} /> : null,
248 tools.length > 0 ? actions(ui, 'agents:detail:actions', [{ key: 'agents:show-tools', label: 'Show its tools', hotkey: 't', onPress: async () => {
249 await props.actions.selectAgent(agent.id)
250 await props.actions.selectTool(null)
251 await props.actions.selectView('tools')
252 } }]) : null,
253 ])
254}
255
256
257export const renderAgents = (ui: CockpitElements, props: CockpitViewProps): RenderElement => {
258 const { Box } = ui
259 const width = viewWidth(props)
260 const wide = width >= 100
261 const left = wide ? Math.floor((width - 2) / 2) : width
262 const right = wide ? width - left - 2 : width
263 const rows = agentHierarchy(props.activity.agents)
264 const selected = rows.find(row => row.agent.id === props.activity.selectedAgent)?.agent ?? rows[0]?.agent
265 const error = props.activity.error
266 const main = [
267 sessionSection(ui, props, left),
268 planSection(ui, props, left),
269 agentList(ui, props, left, selected),
270 error ? line(ui, 'agents:error', [{ text: clip(error, 280), color: colors.red }], true) : null,
271 ].filter((child): child is RenderElement => Boolean(child))
272 const detail = selected ? agentDetail(ui, props, selected, right) : null
273 return wide ? (
274 <Box flexDirection="row" gap={2} width="100%" alignItems="flex-start">
275 <Box flexDirection="column" gap={1} width={left} flexShrink={0}>{main}</Box>
276 <Box flexDirection="column" width={right} flexShrink={0}>{detail ?? muted(ui, 'agents:detail:none', 'Select an agent to see its run.')}</Box>
277 </Box>
278 ) : (
279 <Box flexDirection="column" gap={1} width="100%">
280 {main}
281 {detail}
282 </Box>
283 )
284}
285hooks/changes.tsx 278 lines1import type { RenderElement, ThemeKey } from 'claude-code'
2import type { CockpitChange, CockpitChangeState, CockpitCheck, CockpitGitOperation, CockpitViewProps } from '../types'
3import { actorName } from './agents'
4import { actions, card, heading, line, listLimit, muted, neighboringIndex, section, spread, viewWidth, visibleWindow } from './layout'
5import type { Segment } from './summary'
6import { changeTotals, checkResult } from './summary'
7import type { CockpitElements } from './theme'
8import { ago, brief, cleanText, clip, clipStart, colors, compact, humanize, padStart, statusColor, statusGlyph } from './theme'
9
10export const patchPreview = (patch: string, maxChars = 24000): { source: string; truncated: boolean } => {
11 const source = patch.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, ' ')
12 const limit = Math.max(0, Math.min(24000, Math.floor(maxChars)))
13 if (source.length <= limit) return { source, truncated: false }
14 // Code needs complete hunks. Do not turn a partial hunk into an apparent complete diff.
15 const starts = [...source.matchAll(/^@@ /gm)].map(match => match.index)
16 const boundary = starts.filter(index => index <= limit).at(-1)
17 return { source: boundary === undefined || boundary === starts[0] ? '' : source.slice(0, boundary), truncated: true }
18}
19
20export const gitOperationLines = (operation: CockpitGitOperation): string[] => [
21 operation.commit && `${humanize(operation.commit.kind)} ${operation.commit.sha.slice(0, 8)}${operation.commit.branch ? ` on ${operation.commit.branch}` : ''}`,
22 operation.push && `pushed ${operation.push.branch}`,
23 operation.branch && `${humanize(operation.branch.action)} ${operation.branch.ref}`,
24 operation.pr && `PR #${operation.pr.number} ${humanize(operation.pr.action)}`,
25].filter((entry): entry is string => Boolean(entry)).map(entry => cleanText(entry))
26
27const stateLetter: Record<CockpitChangeState, string> = {
28 modified: 'M', added: 'A', deleted: 'D', renamed: 'R', untracked: '?', conflict: 'U',
29}
30const stateColor: Record<CockpitChangeState, ThemeKey> = {
31 modified: colors.yellow, added: colors.green, deleted: colors.red, renamed: colors.cyan, untracked: colors.muted, conflict: colors.red,
32}
33
34type Group = { key: string; title: string; changes: CockpitChange[] }
35
36/** Staged, then changed, untracked, and edits that no Git read has placed yet. */
37export const changeGroups = (changes: readonly CockpitChange[]): Group[] => [
38 { key: 'staged', title: 'Staged', changes: changes.filter(change => change.source === 'git' && change.staged) },
39 { key: 'changed', title: 'Changed', changes: changes.filter(change => change.source === 'git' && !change.staged && !change.untracked) },
40 { key: 'untracked', title: 'Untracked', changes: changes.filter(change => change.source === 'git' && !change.staged && change.untracked) },
41 { key: 'edited', title: 'Edited, not yet read from Git', changes: changes.filter(change => change.source === 'observed') },
42].filter(group => group.changes.length > 0)
43
44/** A git-style `+++--` bar scaled to the largest change in view. */
45const diffstat = (change: CockpitChange, largest: number, cells: number): Segment[] => {
46 const total = change.additions + change.deletions
47 if (total === 0 || cells <= 0) return []
48 const width = Math.max(1, Math.round(total / Math.max(1, largest) * cells))
49 const plus = Math.round(change.additions / total * width)
50 return [{ text: '+'.repeat(plus), color: colors.green }, { text: '-'.repeat(width - plus), color: colors.red }]
51}
52
53const fileList = (
54 ui: CockpitElements, props: CockpitViewProps, selected: CockpitChange | undefined, width: number,
55): RenderElement => {
56 const { Box, Button, Text } = ui
57 const ordered = changeGroups(props.review.changes)
58 const flat = ordered.flatMap(group => group.changes)
59 const selectedIndex = Math.max(0, flat.findIndex(change => change.path === selected?.path))
60 const visible = new Set(visibleWindow(flat, selectedIndex, listLimit(props)))
61 const largest = Math.max(1, ...flat.map(change => change.additions + change.deletions))
62 const findingCounts = new Map<string, number>()
63 for (const finding of props.review.findings) findingCounts.set(finding.path, (findingCounts.get(finding.path) ?? 0) + 1)
64 const statWidth = 10
65 const rows: RenderElement[] = []
66 for (const group of ordered) {
67 const shown = group.changes.filter(change => visible.has(change))
68 if (shown.length === 0) continue
69 rows.push(line(ui, `changes:group:${group.key}`, [
70 { text: group.title, color: colors.magenta }, { text: ` ${group.changes.length}`, color: colors.muted },
71 ]))
72 for (const change of shown) {
73 const state = change.state ?? (change.untracked ? 'untracked' : 'modified')
74 const findings = findingCounts.get(change.path) ?? 0
75 const counts = change.additions + change.deletions > 0 || change.patch.length > 0
76 ? `+${compact(change.additions)} −${compact(change.deletions)}` : ''
77 const marks = `${change.edits && change.edits > 1 ? ` ✎${change.edits}` : ''}${findings > 0 ? ` ⚑${findings}` : ''}`
78 const stat = diffstat(change, largest, statWidth)
79 const statLength = stat.reduce((total, segment) => total + segment.text.length, 0)
80 // The bar pads to its width, so the counts line up at the right edge.
81 const right: Segment[] = [
82 { text: marks ? `${marks} ` : '', color: colors.yellow },
83 ...stat,
84 { text: ' '.repeat(Math.max(0, statWidth - statLength)) },
85 { text: padStart(counts, 10), color: colors.muted },
86 ]
87 const rightWidth = right.reduce((total, segment) => total + [...segment.text].length, 0)
88 rows.push(spread(ui, `changes:row:${change.path}`, (
89 <Box flexDirection="row">
90 <Text color={change.path === selected?.path ? colors.accent : colors.muted}>{change.path === selected?.path ? '› ' : ' '}</Text>
91 <Text color={stateColor[state]} bold>{stateLetter[state]} </Text>
92 <Button key={`changes:select:${change.path}`} plain label={clipStart(change.path, Math.max(8, width - rightWidth - 6))} onPress={() => props.actions.selectChange(change.path)} />
93 </Box>
94 ), right))
95 }
96 }
97 return section(ui, 'changes:files', [
98 ...rows,
99 flat.length > visible.size ? muted(ui, 'changes:files:more', `Showing ${visible.size} of ${flat.length}.`) : null,
100 ])
101}
102
103const checkLine = (check: CockpitCheck, now: number): Segment[] => {
104 const failed = check.status === 'failed' || (check.failed ?? 0) > 0
105 const color = check.status === 'running' ? colors.cyan : failed ? colors.red : statusColor(check.status)
106 return [
107 { text: `${check.status === 'running' ? '◌' : statusGlyph(failed ? 'failed' : check.status)} `, color },
108 { text: clip(check.label, 24) },
109 { text: ` ${checkResult(check)}`, color },
110 { text: check.durationMs === undefined ? '' : ` · ${brief(check.durationMs)}`, color: colors.muted },
111 { text: check.finishedAt === undefined ? '' : ` · ${ago(now, check.finishedAt)}`, color: colors.muted },
112 ]
113}
114
115/** The newest result of each check label, running ones included. */
116const latestChecks = (checks: readonly CockpitCheck[]): CockpitCheck[] => {
117 const latest = new Map<string, CockpitCheck>()
118 for (const check of checks) latest.set(check.label, check)
119 return [...latest.values()]
120}
121
122const summary = (ui: CockpitElements, props: CockpitViewProps, selected: CockpitChange | undefined, width: number): RenderElement => {
123 const totals = changeTotals(props.review)
124 const checks = latestChecks(props.review.checks)
125 const confirmed = props.review.findings.filter(finding => /confirm/i.test(finding.verdict ?? '')).length
126 const git = props.review.gitOps.at(-1)
127 const changes = props.review.changes
128 const chooseNeighbor = (direction: number): Promise<void> => {
129 const ordered = changeGroups(changes).flatMap(group => group.changes)
130 const index = Math.max(0, ordered.findIndex(change => change.path === props.review.selectedPath))
131 const next = ordered[neighboringIndex(ordered.length, index, direction)]
132 return next ? props.actions.selectChange(next.path) : Promise.resolve()
133 }
134 return section(ui, 'changes:summary', [
135 heading(ui, 'changes:title', 'Changes', [
136 { text: '⎇ ', color: colors.muted },
137 { text: clip(props.review.branch ?? 'branch unknown', Math.max(8, width - 16)), color: colors.magenta },
138 ], width),
139 line(ui, 'changes:totals', [
140 { text: `${totals.files} ${totals.files === 1 ? 'file' : 'files'} ` },
141 { text: `+${compact(totals.additions)}`, color: colors.green }, { text: ' ' },
142 { text: `−${compact(totals.deletions)}`, color: colors.red },
143 { text: totals.staged > 0 ? ` · ${totals.staged} staged` : '', color: colors.muted },
144 { text: totals.untracked > 0 ? ` · ${totals.untracked} untracked` : '', color: colors.muted },
145 { text: ` · git ${props.review.refreshedAt === null ? 'not read' : ago(props.now, props.review.refreshedAt)}`, color: colors.muted },
146 ], true),
147 checks.length > 0 ? line(ui, 'changes:checks-summary', checks.slice(-3).flatMap((check, index) => {
148 const failed = check.status === 'failed' || (check.failed ?? 0) > 0
149 const color = check.status === 'running' ? colors.cyan : failed ? colors.red : statusColor(check.status)
150 return [
151 { text: index > 0 ? ' · ' : 'Checks ', color: colors.muted },
152 { text: `${check.status === 'running' ? '◌' : statusGlyph(failed ? 'failed' : check.status)} ${clip(check.label, 16)}`, color },
153 ]
154 }), true) : null,
155 props.review.findings.length > 0 ? line(ui, 'changes:findings-summary', [
156 { text: 'Review ', color: colors.muted },
157 { text: `⚑ ${props.review.findings.length} ${props.review.findings.length === 1 ? 'finding' : 'findings'}`, color: colors.yellow },
158 { text: confirmed > 0 ? ` · ${confirmed} confirmed` : '', color: colors.red },
159 ]) : null,
160 git ? line(ui, 'changes:git-summary', [
161 { text: 'Git ', color: colors.muted },
162 { text: clip(gitOperationLines(git).join(' · '), width - 16) },
163 { text: ` · ${ago(props.now, git.at)}`, color: colors.muted },
164 ]) : null,
165 props.review.error ? line(ui, 'changes:error', [{ text: clip(props.review.error, 320), color: colors.red }], true) : null,
166 actions(ui, 'changes:actions', [
167 { key: 'changes:refresh', label: props.review.loading ? 'Reading git…' : 'Read git', hotkey: 'r', onPress: props.actions.refreshChanges },
168 { key: 'changes:prev', label: 'Previous', hotkey: 'k', onPress: () => chooseNeighbor(-1), hidden: changes.length < 2 },
169 { key: 'changes:next', label: 'Next', hotkey: 'j', onPress: () => chooseNeighbor(1), hidden: changes.length < 2 },
170 { key: 'changes:copy-path', label: 'Copy path', hotkey: 'p', onPress: () => props.actions.copyPath(selected?.path ?? ''), hidden: !selected },
171 { key: 'changes:copy', label: 'Copy patch', hotkey: 'c', onPress: () => props.actions.copyPatch(selected?.path ?? ''), hidden: !selected?.patch },
172 { key: 'changes:quote', label: 'Quote patch', hotkey: 'q', onPress: () => props.actions.quotePatch(selected?.path ?? ''), hidden: !selected?.patch },
173 ]),
174 ])
175}
176
177const diffSection = (ui: CockpitElements, props: CockpitViewProps, change: CockpitChange, width: number): RenderElement => {
178 const { Code } = ui
179 const preview = patchPreview(change.patch)
180 const findings = props.review.findings.filter(finding => finding.path === change.path)
181 const by = change.agentId !== undefined || change.edits ? [
182 { text: change.edits ? ` · edited ${change.edits}×` : '', color: colors.muted },
183 { text: change.agentId !== undefined ? ` by ${clip(actorName(props, change.agentId), 14)}` : '', color: colors.magenta },
184 ] : []
185 return section(ui, 'changes:diff', [
186 heading(ui, 'changes:diff:title', clipStart(change.path, Math.max(12, width - 30)), [
187 { text: `+${compact(change.additions)}`, color: colors.green }, { text: ' ' },
188 { text: `−${compact(change.deletions)}`, color: colors.red },
189 ...by,
190 ], width),
191 ...findings.slice(0, 4).map(finding => line(ui, `changes:diff:finding:${finding.id}`, [
192 { text: '⚑ ', color: colors.yellow },
193 { text: finding.line === undefined ? '' : `L${finding.line} `, color: colors.muted },
194 { text: clip(finding.summary, width * 2) },
195 { text: finding.verdict ? ` · ${finding.verdict}` : '', color: /confirm/i.test(finding.verdict ?? '') ? colors.red : colors.yellow },
196 ], true)),
197 change.truncated || preview.truncated ? muted(ui, 'changes:diff:truncated', 'Truncated patch.') : null,
198 preview.source
199 ? <Code key="changes:diff:code" source={preview.source} path={change.path} format="diff" wrap="wrap" />
200 : muted(ui, 'changes:diff:none', preview.truncated
201 ? 'No complete hunk fits the preview limit. Copy or quote the captured patch to inspect it.'
202 : change.truncated ? 'Patch omitted: no complete hunk fits the capture limit.'
203 : change.untracked ? 'Untracked file: Git shows no patch until it is added.' : 'No text patch captured. Read git to load it.'),
204 ])
205}
206
207const checksSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
208 const checks = props.review.checks.slice(-6).reverse()
209 if (checks.length === 0) return null
210 const passed = props.review.checks.filter(check => check.status === 'passed').length
211 const failed = props.review.checks.filter(check => check.status === 'failed').length
212 return section(ui, 'changes:checks', [
213 heading(ui, 'changes:checks:title', 'Checks', [
214 { text: `${passed} passed`, color: passed > 0 ? colors.green : colors.muted },
215 { text: ' · ', color: colors.muted },
216 { text: `${failed} failed`, color: failed > 0 ? colors.red : colors.muted },
217 ], width),
218 ...checks.map(check => line(ui, `changes:check:${check.id}`, checkLine(check, props.now))),
219 props.review.checks.length > checks.length ? muted(ui, 'changes:checks:more', `Showing the latest ${checks.length} of ${props.review.checks.length}.`) : null,
220 ])
221}
222
223const findingsSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
224 const findings = props.review.findings.slice(-8).reverse()
225 if (findings.length === 0) return null
226 return section(ui, 'changes:findings', [
227 heading(ui, 'changes:findings:title', 'Findings', [{ text: `${props.review.findings.length}`, color: colors.yellow }], width),
228 ...findings.flatMap(finding => [
229 line(ui, `changes:finding:${finding.id}:where`, [
230 { text: '⚑ ', color: /confirm/i.test(finding.verdict ?? '') ? colors.red : colors.yellow },
231 { text: clipStart(`${finding.path}${finding.line === undefined ? '' : `:${finding.line}`}`, Math.max(12, width - 30)) },
232 { text: [finding.category, finding.verdict, finding.outcome].filter(Boolean).map(value => ` · ${value}`).join(''), color: colors.muted },
233 ]),
234 line(ui, `changes:finding:${finding.id}:summary`, [{ text: ` ${clip(finding.summary, 360)}` }], true),
235 ]),
236 ])
237}
238
239const gitSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
240 const { Link } = ui
241 const operations = props.review.gitOps.slice(-6).reverse()
242 if (operations.length === 0) return null
243 return section(ui, 'changes:git', [
244 heading(ui, 'changes:git:title', 'Git activity', [{ text: `${props.review.gitOps.length}`, color: colors.muted }], width),
245 ...operations.flatMap(operation => [
246 spread(ui, `changes:git:${operation.id}`, line(ui, `changes:git:${operation.id}:text`, [
247 { text: operation.pr ? '⇡ ' : operation.push ? '↑ ' : '● ', color: colors.magenta },
248 { text: clip(gitOperationLines(operation).join(' · '), width - 12) },
249 ]), [{ text: ago(props.now, operation.at), color: colors.muted }]),
250 operation.pr?.url ? <Link key={`changes:git:pr:${operation.id}`} href={operation.pr.url} label={` ${clip(operation.pr.url, width - 2)}`} /> : null,
251 ].filter((child): child is RenderElement => Boolean(child))),
252 ])
253}
254
255export const renderChanges = (ui: CockpitElements, props: CockpitViewProps): RenderElement => {
256 const { Box } = ui
257 const width = viewWidth(props)
258 const wide = width >= 100
259 const left = wide ? Math.min(60, Math.floor((width - 2) * 0.45)) : width
260 const right = wide ? width - left - 2 : width
261 const selected = props.review.changes.find(change => change.path === props.review.selectedPath) ?? changeGroups(props.review.changes)[0]?.changes[0]
262 const keep = (items: (RenderElement | null)[]) => items.filter((item): item is RenderElement => Boolean(item))
263 const files = props.review.changes.length > 0 ? fileList(ui, props, selected, left)
264 : muted(ui, 'changes:empty', 'No changes yet. Edits appear as the session makes them; Read git loads the working tree.')
265 const diff = selected ? diffSection(ui, props, selected, right) : null
266 const extras = [checksSection(ui, props, left), findingsSection(ui, props, left), gitSection(ui, props, left)]
267 return wide ? (
268 <Box flexDirection="row" gap={2} width="100%" alignItems="flex-start">
269 <Box flexDirection="column" gap={1} width={left} flexShrink={0}>{keep([summary(ui, props, selected, left), files, ...extras])}</Box>
270 <Box flexDirection="column" width={right} flexShrink={0}>{diff ? card(ui, 'changes:diff:card', [diff]) : muted(ui, 'changes:diff:empty', 'Select a file to see its patch.')}</Box>
271 </Box>
272 ) : (
273 <Box flexDirection="column" gap={1} width="100%">
274 {keep([summary(ui, props, selected, width), files, diff, ...extras])}
275 </Box>
276 )
277}
278hooks/context.tsx 300 lines1import type { ContextCategory, RenderElement, SessionContextBreakdown, ThemeKey } from 'claude-code'
2import type { CockpitCompaction, CockpitCostSample, CockpitViewProps } from '../types'
3import { actions, field, heading, line, muted, section, viewWidth } from './layout'
4import type { Segment } from './summary'
5import { cacheHit, contextColor, contextFill, mainTurns, sessionStart, tokenTotals } from './summary'
6import type { CockpitElements } from './theme'
7import { ago, bar, brief, cleanText, clip, colors, compact, count, humanize, meter, padEnd, padStart, percent, shortModel, sparkline, usd } from './theme'
8
9const palette: ThemeKey[] = [colors.accent, colors.cyan, colors.green, colors.magenta, colors.yellow, colors.red]
10
11const finite = (value: number | undefined): value is number => value !== undefined && Number.isFinite(value)
12
13export const categoryColor = (category: Pick<ContextCategory, 'kind'>, index: number): ThemeKey => {
14 if (category.kind === 'free') return colors.muted
15 if (category.kind === 'buffer') return colors.yellow
16 if (category.kind === 'deferred') return colors.magenta
17 return palette[index % palette.length] ?? colors.accent
18}
19
20export type RankedEstimate = { label: string; tokens: number; detail?: string }
21
22export const rankedEstimates = (breakdown: SessionContextBreakdown): {
23 memory: RankedEstimate[]
24 mcp: RankedEstimate[]
25 skills: RankedEstimate[]
26} => {
27 const servers = new Map<string, { tokens: number; loaded: number; total: number; deferred: number }>()
28 for (const tool of breakdown.mcpTools) {
29 const server = servers.get(tool.serverName) ?? { tokens: 0, loaded: 0, total: 0, deferred: 0 }
30 const tokens = Number.isFinite(tool.tokens) ? Math.max(0, tool.tokens) : 0
31 server.tokens += tokens
32 server.total += 1
33 if (tool.isLoaded) server.loaded += 1
34 else server.deferred += tokens
35 servers.set(tool.serverName, server)
36 }
37 const descending = (a: RankedEstimate, b: RankedEstimate): number => b.tokens - a.tokens
38 return {
39 memory: breakdown.memoryFiles
40 .map(file => ({ label: file.path, tokens: file.tokens, detail: file.type }))
41 .sort(descending),
42 mcp: Array.from(servers, ([label, server]) => ({
43 label,
44 tokens: server.tokens,
45 detail: `${server.loaded}/${server.total} loaded; ${count(server.deferred)} deferred`,
46 })).sort(descending),
47 skills: (breakdown.skills?.skillFrontmatter ?? [])
48 .map(skill => ({ label: skill.name, tokens: skill.tokens, detail: skill.pluginName ?? skill.source }))
49 .sort(descending),
50 }
51}
52
53// Each cost sample is the session total after a main turn grew it. The first
54// sample can hold earlier turns, so only differences between samples count.
55export const costPerTurn = (costs: readonly CockpitCostSample[]): number[] =>
56 costs.slice(1).map((sample, index) => Math.max(0, sample.usd - (costs[index]?.usd ?? sample.usd)))
57
58export const compactionLine = (entry: CockpitCompaction, now: number): string => {
59 const who = `${humanize(entry.trigger)}${entry.agentId ? ' (agent)' : ''}`
60 if (entry.skipped !== undefined) return `${who} · skipped: ${entry.skipped} · ${ago(now, entry.at)}`
61 const saved = finite(entry.tokensBefore) && finite(entry.tokensAfter) && entry.tokensBefore > 0
62 ? ` (−${Math.round((1 - entry.tokensAfter / entry.tokensBefore) * 100)}%)` : ''
63 return `${who} · ${compact(entry.tokensBefore)} → ${compact(entry.tokensAfter)}${saved} · ${ago(now, entry.at)}`
64}
65
66type Cell = { glyph: string; color: ThemeKey }
67
68/**
69 * One line across the window: each used category in its color, free space up
70 * to the auto-compaction threshold, the threshold mark, and the reserve after it.
71 */
72export const contextGauge = (
73 breakdown: SessionContextBreakdown | undefined, tokens: number | undefined, window: number | undefined,
74 threshold: number | undefined, columns: number,
75): Cell[] => {
76 const cells = Math.max(8, Math.floor(columns))
77 const size = finite(window) && window > 0 ? window : breakdown?.rawMaxTokens
78 if (!finite(size) || size <= 0) return []
79 const used = breakdown?.categories.filter(category => category.kind === 'used' || category.kind === 'deferred') ?? []
80 const estimate = used.reduce((total, category) => total + Math.max(0, category.tokens), 0)
81 // Scale the estimate to the live fill, which the last response measured.
82 const scale = finite(tokens) && estimate > 0 ? tokens / estimate : 1
83 const result: Cell[] = []
84 if (used.length > 0) {
85 let carried = 0
86 used.forEach((category, index) => {
87 const exact = Math.max(0, category.tokens) * scale / size * cells + carried
88 // The epsilon keeps float error in the carried fractions from losing a cell.
89 const whole = Math.floor(exact + 1e-9)
90 carried = exact - whole
91 const colorIndex = breakdown?.categories.indexOf(category) ?? index
92 for (let cell = 0; cell < whole && result.length < cells; cell += 1) result.push({ glyph: '█', color: categoryColor(category, colorIndex) })
93 })
94 } else if (finite(tokens)) {
95 for (let cell = 0; cell < Math.round(tokens / size * cells) && result.length < cells; cell += 1) result.push({ glyph: '█', color: colors.accent })
96 }
97 const mark = finite(threshold) ? Math.min(cells - 1, Math.round(threshold / size * cells)) : undefined
98 while (result.length < cells) {
99 const index = result.length
100 if (mark !== undefined && index === mark) result.push({ glyph: '┃', color: colors.yellow })
101 else if (mark !== undefined && index > mark) result.push({ glyph: '░', color: colors.muted })
102 else result.push({ glyph: '─', color: colors.muted })
103 }
104 if (mark !== undefined && result[mark]?.glyph === '█') result[mark] = { glyph: '┃', color: colors.red }
105 return result
106}
107
108const runs = (cells: readonly Cell[]): Segment[] => {
109 const merged: Segment[] = []
110 for (const cell of cells) {
111 const last = merged[merged.length - 1]
112 if (last && last.color === cell.color) last.text += cell.glyph
113 else merged.push({ text: cell.glyph, color: cell.color })
114 }
115 return merged
116}
117
118const resetText = (value: string | undefined, now: number): string => {
119 if (!value) return 'reset unknown'
120 const at = Date.parse(value)
121 return Number.isFinite(at) ? `resets in ${brief(Math.max(0, at - now))}` : `resets ${cleanText(value)}`
122}
123
124const fillSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement => {
125 const { Box } = ui
126 const usage = props.context.usage
127 const breakdown = usage?.context.breakdown
128 const fill = contextFill(props.context)
129 const gauge = contextGauge(breakdown, fill.tokens, fill.window, fill.threshold, width)
130 const trend = props.context.fills.map(sample => sample.tokens)
131 const color = contextColor(fill)
132 return (
133 <Box key="context:fill" flexDirection="column" width="100%">
134 {heading(ui, 'context:title', 'Context', [
135 { text: shortModel(breakdown?.model ?? props.activity.model ?? ''), color: colors.muted },
136 { text: finite(fill.window) ? ` · ${compact(fill.window)} window` : '', color: colors.muted },
137 ], width)}
138 {line(ui, 'context:headline', [
139 { text: finite(fill.tokens) ? count(fill.tokens) : 'Not measured yet', bold: true },
140 { text: finite(fill.tokens) ? ' tokens' : '', color: colors.muted },
141 { text: finite(fill.percent) ? ` · ${percent(fill.percent)}` : '', color: color === colors.muted ? colors.accent : color, bold: true },
142 { text: finite(fill.window) ? ` of ${compact(fill.window)}` : '', color: colors.muted },
143 ])}
144 {gauge.length > 0 && line(ui, 'context:gauge', runs(gauge))}
145 {finite(fill.threshold) ? line(ui, 'context:headroom', [
146 { text: `${compact(fill.headroom)} left`, color: color === colors.muted ? colors.green : color, bold: true },
147 { text: ` before auto-compact at ${compact(fill.threshold)}`, color: colors.muted },
148 ], true) : breakdown && !breakdown.isAutoCompactEnabled ? muted(ui, 'context:no-compact', 'Auto-compact is off.') : null}
149 {trend.length > 1 && line(ui, 'context:trend', [
150 { text: 'Trend ', color: colors.muted },
151 { text: sparkline(trend, Math.min(12, trend.length)), color: colors.cyan },
152 { text: finite(fill.growth) ? ` +${compact(fill.growth)} per response` : '' },
153 { text: finite(fill.responsesLeft) ? ` · ~${fill.responsesLeft < 10 ? fill.responsesLeft.toFixed(1) : Math.round(fill.responsesLeft)} responses to compact` : '', color: color === colors.muted ? colors.muted : color },
154 ], true)}
155 {props.context.error && line(ui, 'context:error', [{ text: clip(props.context.error, 280), color: colors.red }], true)}
156 {actions(ui, 'context:actions', [
157 { key: 'context:refresh', label: props.context.loading ? 'Estimating…' : 'Estimate categories', hotkey: 'r', onPress: props.actions.refreshContext },
158 ])}
159 </Box>
160 )
161}
162
163const breakdownSection = (ui: CockpitElements, props: CockpitViewProps, breakdown: SessionContextBreakdown, width: number): RenderElement => {
164 const nameWidth = Math.min(18, Math.max(10, ...breakdown.categories.map(category => category.name.length)))
165 const barWidth = Math.max(0, width - nameWidth - 7 - 5 - 2)
166 const size = Math.max(1, breakdown.rawMaxTokens)
167 const largest = Math.max(1, ...breakdown.categories.filter(category => category.kind === 'used' || category.kind === 'deferred').map(category => category.tokens))
168 return section(ui, 'context:breakdown', [
169 heading(ui, 'context:breakdown:title', 'Breakdown', [
170 { text: `estimated ${props.context.refreshedAt === null ? '' : ago(props.now, props.context.refreshedAt)}`, color: colors.muted },
171 ], width),
172 ...breakdown.categories.slice(0, 14).map((category, index) => {
173 const reserved = category.kind === 'free' || category.kind === 'buffer'
174 return line(ui, `context:category:${index}`, [
175 { text: '■ ', color: categoryColor(category, index) },
176 { text: padEnd(clip(`${category.name}${category.kind === 'deferred' ? '*' : ''}`, nameWidth), nameWidth), color: reserved ? colors.muted : undefined },
177 { text: padStart(compact(category.tokens), 7), color: reserved ? colors.muted : undefined },
178 { text: padStart(percent(category.tokens / size * 100), 5), color: colors.muted },
179 { text: reserved || barWidth === 0 ? '' : ` ${bar(category.tokens / largest, barWidth)}`, color: categoryColor(category, index) },
180 ])
181 }),
182 breakdown.categories.some(category => category.kind === 'deferred') ? muted(ui, 'context:deferred', '* deferred: loaded only when used.') : null,
183 ])
184}
185
186const consumers = (ui: CockpitElements, breakdown: SessionContextBreakdown, width: number): RenderElement | null => {
187 const ranked = rankedEstimates(breakdown)
188 const list = (entries: { label: string; tokens: number }[], limit: number): Segment[] =>
189 entries.slice(0, limit).flatMap((entry, index) => [
190 { text: index > 0 ? ' · ' : '', color: colors.muted },
191 { text: clip(entry.label.replace(/^.*\/(?=[^/]+\/[^/]+$)/, ''), 24) },
192 { text: ` ${compact(entry.tokens)}`, color: colors.cyan },
193 ])
194 const rows = [
195 ranked.memory.length > 0 ? field(ui, 'context:consumers:memory', 'Memory', list(ranked.memory, 3)) : null,
196 ranked.mcp.length > 0 ? field(ui, 'context:consumers:mcp', 'MCP', list(ranked.mcp, 3)) : null,
197 breakdown.skills ? field(ui, 'context:consumers:skills', 'Skills', [
198 { text: `${count(breakdown.skills.includedSkills)}/${count(breakdown.skills.totalSkills)} listed`, color: colors.muted },
199 { text: ranked.skills.length > 0 ? ' · ' : '', color: colors.muted },
200 ...list(ranked.skills, 2),
201 ]) : null,
202 ]
203 if (rows.every(row => row === null)) return null
204 return section(ui, 'context:consumers', [heading(ui, 'context:consumers:title', 'Largest', [{ text: 'estimated', color: colors.muted }], width), ...rows])
205}
206
207const usageSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
208 const turns = mainTurns(props.activity)
209 const last = turns.filter(turn => turn.usage).at(-1)?.usage
210 if (!last) return null
211 const lastTotals = tokenTotals([last])
212 const session = tokenTotals(turns.map(turn => turn.usage))
213 const lastHit = cacheHit(lastTotals)
214 const sessionHit = cacheHit(session)
215 const column = 7
216 const row = (key: string, label: string, totals: typeof session, hit: number | undefined): RenderElement => line(ui, key, [
217 { text: padEnd(label, 10), color: colors.muted },
218 ...[totals.input, totals.output, totals.cacheRead, totals.cacheWrite].map(value => ({ text: padStart(compact(value), column) })),
219 { text: padStart(percent(hit), column), color: hit !== undefined && hit < 50 ? colors.yellow : colors.green },
220 ])
221 return section(ui, 'context:usage', [
222 heading(ui, 'context:usage:title', 'Tokens', [{ text: 'main session', color: colors.muted }], width),
223 line(ui, 'context:usage:columns', [{ text: `${padEnd('', 10)}${['input', 'output', 'read', 'write', 'hit'].map(name => padStart(name, column)).join('')}`, color: colors.muted }]),
224 row('context:usage:last', 'Last turn', lastTotals, lastHit),
225 row('context:usage:session', `${turns.length} ${turns.length === 1 ? 'turn' : 'turns'}`, session, sessionHit),
226 ])
227}
228
229const costSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement => {
230 const usage = props.context.usage
231 const total = usage?.cost?.usd
232 const perTurn = costPerTurn(props.context.costs)
233 const last = perTurn.at(-1)
234 const average = perTurn.length > 0 ? perTurn.reduce((sum, value) => sum + value, 0) / perTurn.length : undefined
235 const started = sessionStart(props.activity, props.context)
236 const hours = finite(started) ? (props.now - started) / 3600000 : undefined
237 const rate = finite(total) && finite(hours) && hours > 0.05 ? total / hours : undefined
238 const limits = usage?.rateLimits ?? []
239 return section(ui, 'context:cost', [
240 heading(ui, 'context:cost:title', 'Cost', [{ text: finite(total) ? usd(total) : 'not reported', color: finite(total) ? colors.accent : colors.muted, bold: true }], width),
241 last !== undefined ? line(ui, 'context:cost:turns', [
242 { text: 'Last turn ', color: colors.muted }, { text: usd(last) },
243 { text: ' · avg ', color: colors.muted }, { text: average === undefined ? '?' : usd(average) },
244 { text: rate === undefined ? '' : ' · ', color: colors.muted }, { text: rate === undefined ? '' : `${usd(rate)}/h` },
245 { text: perTurn.length > 1 ? ` ${sparkline(perTurn, Math.min(20, width - 44))}` : '', color: colors.cyan },
246 ]) : null,
247 ...limits.slice(0, 6).map((limit, index) => {
248 const used = limit.percentUsed
249 const color = used >= 90 ? colors.red : used >= 75 ? colors.yellow : colors.cyan
250 return line(ui, `context:limit:${index}`, [
251 { text: padEnd(clip(humanize(limit.kind), 10), 10), color: colors.muted },
252 { text: padStart(percent(used), 5), color },
253 { text: ` ${meter(used, Math.max(6, Math.min(20, width - 36)))} `, color },
254 { text: resetText(limit.resetsAt, props.now), color: colors.muted },
255 ])
256 }),
257 limits.length === 0 ? muted(ui, 'context:limits:none', 'Rate limits not reported.') : null,
258 ])
259}
260
261const compactionSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
262 const entries = props.context.compactions
263 if (entries.length === 0) return null
264 return section(ui, 'context:compactions', [
265 heading(ui, 'context:compactions:title', 'Compactions', [{ text: `${entries.length}`, color: colors.muted }], width),
266 ...entries.slice(-5).reverse().map((entry, index) => line(ui, `context:compaction:${index}`, [
267 { text: entry.skipped === undefined ? '⇣ ' : '· ', color: entry.skipped === undefined ? colors.cyan : colors.yellow },
268 { text: clip(compactionLine(entry, props.now), width - 2), color: entry.skipped === undefined ? undefined : colors.yellow },
269 ])),
270 ])
271}
272
273export const renderContext = (ui: CockpitElements, props: CockpitViewProps): RenderElement => {
274 const { Box } = ui
275 const width = viewWidth(props)
276 const wide = width >= 100
277 const left = wide ? Math.floor((width - 2) / 2) : width
278 const right = wide ? width - left - 2 : width
279 const breakdown = props.context.usage?.context.breakdown
280 const keep = (items: (RenderElement | null)[]) => items.filter((item): item is RenderElement => Boolean(item))
281 const first = keep([
282 fillSection(ui, props, left),
283 breakdown ? breakdownSection(ui, props, breakdown, left) : muted(ui, 'context:breakdown:none', 'Estimate categories to see what fills the window.'),
284 ])
285 const second = keep([
286 usageSection(ui, props, right),
287 costSection(ui, props, right),
288 breakdown ? consumers(ui, breakdown, right) : null,
289 compactionSection(ui, props, right),
290 ])
291 return wide ? (
292 <Box flexDirection="row" gap={2} width="100%" alignItems="flex-start">
293 <Box flexDirection="column" gap={1} width={left} flexShrink={0}>{first}</Box>
294 <Box flexDirection="column" gap={1} width={right} flexShrink={0}>{second}</Box>
295 </Box>
296 ) : (
297 <Box flexDirection="column" gap={1} width="100%">{[...first, ...second]}</Box>
298 )
299}
300hooks/data.ts 744 lines1import type { AgentInfo } from 'claude-code'
2import type {
3 CockpitActivity, CockpitAgent, CockpitAgentTotals, CockpitBackgroundTask, CockpitChange, CockpitChangeState,
4 CockpitCheck, CockpitCron, CockpitGitOperation, CockpitTask, CockpitTodo,
5} from '../types'
6import { cleanText } from './theme'
7
8const MAX_ITEMS = 100
9const MAX_PATH = 4096
10const MAX_INPUT = 2 * 1024 * 1024
11const MAX_PATCH = 24000
12const MAX_PATCH_TOTAL = 200000
13const MAX_COUNT = 1_000_000
14
15const record = (value: unknown): Record<string, unknown> | undefined =>
16 typeof value === 'object' && value !== null && !Array.isArray(value)
17 ? value as Record<string, unknown>
18 : undefined
19
20const label = (value: string, limit = 240): string => cleanText(value.slice(0, limit))
21const finite = (value: unknown, limit = MAX_COUNT): number | undefined =>
22 typeof value === 'number' && Number.isFinite(value) && value >= 0
23 ? Math.min(limit, Math.floor(value))
24 : undefined
25const hunkNumber = (value: unknown): number | undefined =>
26 typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= MAX_COUNT
27 ? value
28 : undefined
29const pathValue = (value: unknown): string | undefined =>
30 typeof value === 'string' && value.length > 0 && value.length <= MAX_PATH && !value.includes('\0')
31 ? value
32 : undefined
33const terminal = (status: CockpitAgent['status']): boolean =>
34 status === 'completed' || status === 'failed' || status === 'killed'
35
36export const mergeAgents = (
37 previous: CockpitAgent[], incoming: AgentInfo[], now: number,
38): CockpitAgent[] => {
39 const seenAt = finite(now, Number.MAX_SAFE_INTEGER) ?? 0
40 const old = new Map(previous.slice(0, MAX_ITEMS).map(agent => [agent.id, agent]))
41 const merged: CockpitAgent[] = []
42 const seen = new Set<string>()
43 for (const agent of incoming.slice(0, MAX_ITEMS)) {
44 if (seen.has(agent.id)) continue
45 seen.add(agent.id)
46 const prior = old.get(agent.id)
47 merged.push({
48 id: agent.id,
49 name: agent.name === undefined ? undefined : label(agent.name, 80),
50 description: label(agent.description),
51 type: label(agent.type, 80),
52 status: agent.status,
53 parentId: agent.parentId,
54 teammateId: agent.teammateId,
55 spawnedBy: agent.spawnedBy,
56 startedAt: prior?.startedAt ?? seenAt,
57 lastSeenAt: seenAt,
58 completedAt: terminal(agent.status) ? prior?.completedAt ?? seenAt : undefined,
59 durationMs: prior?.durationMs,
60 usage: prior?.usage,
61 totals: prior?.totals,
62 answer: prior?.answer,
63 })
64 }
65 for (const agent of previous.slice(0, MAX_ITEMS)) {
66 if (seen.has(agent.id)) continue
67 seen.add(agent.id)
68 merged.push({ ...agent, status: terminal(agent.status) ? agent.status : 'missing' })
69 }
70 return merged.slice(0, MAX_ITEMS)
71}
72
73// Parse only enough shell syntax to identify commands. Never retain arguments.
74const commandSegments = (command: string): string[][] => {
75 const segments: string[][] = []
76 let words: string[] = []
77 let word = ''
78 let quote = ''
79 let escaped = false
80 let comment = false
81 const pushWord = (): void => {
82 if (word) words.push(word)
83 word = ''
84 }
85 const pushSegment = (): void => {
86 pushWord()
87 if (words.length) segments.push(words)
88 words = []
89 }
90 if (command.length > 8192 || command.includes('<<')) return []
91 for (const char of command) {
92 if (segments.length >= 16 || words.length >= 100) break
93 if (comment) {
94 if (char === '\n') { comment = false; pushSegment() }
95 continue
96 }
97 if (escaped) { word += char; escaped = false; continue }
98 if (char === '\\' && quote !== "'") { escaped = true; continue }
99 if (quote) {
100 if (char === quote) quote = ''
101 else word += char
102 continue
103 }
104 if (char === '"' || char === "'") { quote = char; continue }
105 if (char === '#' && !word) { comment = true; continue }
106 if (';&|\n'.includes(char)) { pushSegment(); continue }
107 if (/\s/.test(char)) { pushWord(); continue }
108 word += char
109 }
110 if (!quote && !escaped) pushSegment()
111 return segments
112}
113
114const commandWords = (words: string[]): string[] => {
115 let index = words[0] === 'env' ? 1 : 0
116 while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[index] ?? '')) index++
117 return words.slice(index)
118}
119const executable = (word: string | undefined): string | undefined => {
120 if (!word) return undefined
121 const name = word.slice(word.lastIndexOf('/') + 1)
122 return /^[A-Za-z0-9_.+-]{1,80}$/.test(name) ? name : undefined
123}
124
125export const toolTarget = (tool: string, input: unknown): string | undefined => {
126 const value = record(input)
127 if (!value) return undefined
128 if (['Read', 'Edit', 'Write', 'Glob', 'Grep', 'NotebookEdit'].includes(tool)) {
129 const path = pathValue(value.file_path ?? value.notebook_path ?? value.path)
130 return path === undefined ? undefined : label(path, 240)
131 }
132 if (tool === 'Bash' && typeof value.command === 'string') {
133 return executable(commandWords(commandSegments(value.command)[0] ?? [])[0])
134 }
135 if (tool === 'Agent' && typeof value.description === 'string') return label(value.description)
136 return undefined
137}
138
139const checkWords = (words: string[]): string | undefined => {
140 const exe = executable(words[0])
141 const args = words.slice(1)
142 if (!exe) return undefined
143 if (['npm', 'pnpm', 'yarn'].includes(exe)) {
144 const script = args[0] === 'run' ? args[1] : args[0]
145 if (script && /^(test|lint|typecheck|type-check|check|format|fmt)(?::[A-Za-z0-9_-]{1,40})?$/.test(script)) {
146 return `${exe}${args[0] === 'run' ? ' run' : ''} ${script}`
147 }
148 if (args[0] === 'exec') {
149 const nested = checkWords(args.slice(1))
150 if (nested) return label(`${exe} exec ${nested}`)
151 }
152 }
153 if (['npx', 'bunx'].includes(exe)) {
154 const nested = checkWords(args.filter((arg, index) => index > 0 || !['--yes', '-y', '--no-install'].includes(arg)))
155 if (nested) return label(`${exe} ${nested}`)
156 }
157 if (['pytest', 'py.test', 'jest', 'vitest'].includes(exe)) return exe
158 if (/^python(?:3(?:\.\d+)?)?$/.test(exe) && args[0] === '-m' && args[1] === 'pytest') return 'pytest'
159 if (exe === 'cargo' && ['test', 'check', 'clippy', 'fmt'].includes(args[0] ?? '')) return `cargo ${args[0]}`
160 if (exe === 'go' && ['test', 'vet', 'fmt'].includes(args[0] ?? '')) return `go ${args[0]}`
161 if (exe === 'nix') {
162 const nixArgs = [...args]
163 while (nixArgs[0]?.startsWith('--')) {
164 const flag = nixArgs.shift()
165 if (['--extra-experimental-features', '--experimental-features', '--option'].includes(flag ?? '')) {
166 nixArgs.shift()
167 if (flag === '--option') nixArgs.shift()
168 } else break
169 }
170 if (nixArgs[0] === 'flake' && nixArgs[1] === 'check') return 'nix flake check'
171 if (['eval', 'build', 'check'].includes(nixArgs[0] ?? '')) return `nix ${nixArgs[0]}`
172 }
173 if (['tsc', 'eslint', 'prettier', 'mypy', 'black', 'isort', 'rustfmt', 'nixfmt', 'nixpkgs-fmt', 'alejandra'].includes(exe)) return exe
174 if (['ruff', 'biome'].includes(exe) && ['check', 'format'].includes(args[0] ?? '')) return `${exe} ${args[0]}`
175 return undefined
176}
177
178export const detectCheck = (command: string): string | undefined => {
179 for (const segment of commandSegments(command)) {
180 const detected = checkWords(commandWords(segment))
181 if (detected) return detected
182 }
183 return undefined
184}
185
186export type CheckFlags = { error?: boolean; denied?: boolean; interrupted?: boolean }
187
188export const summarizeCheck = (
189 id: string, checkLabel: string, result: unknown, flags: CheckFlags = {}, durationMs?: number,
190): CockpitCheck => {
191 const wrapper = record(result)
192 const value = record(wrapper?.result) ?? wrapper
193 const check: CockpitCheck = { id, label: label(checkLabel), status: 'completed' }
194 const duration = finite(durationMs, Number.MAX_SAFE_INTEGER)
195 if (duration !== undefined) check.durationMs = duration
196 if (flags.denied || typeof wrapper?.deny === 'string') return { ...check, status: 'denied' }
197 if (flags.interrupted || value?.interrupted === true) return { ...check, status: 'interrupted' }
198 const nativeError = flags.error || wrapper?.isError === true
199 // Summaries usually appear at the end. Output is transient, never returned.
200 const output = typeof result === 'string' ? result.slice(-65536) : [
201 typeof value?.stdout === 'string' ? value.stdout.slice(-65536) : '',
202 typeof value?.stderr === 'string' ? value.stderr.slice(-65536) : '',
203 ].join('\n')
204 const text = output.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '')
205 let recognizedPass = false
206 let recognizedFail = false
207 let passed: number | undefined
208 let failed: number | undefined
209 const counts = (summary: string): void => {
210 for (const match of summary.matchAll(/(\d+)\s+(passed|failed)\b/g)) {
211 const count = Math.min(MAX_COUNT, Number(match[1]))
212 if (match[2] === 'passed') passed = count
213 else failed = count
214 }
215 if ((passed ?? 0) > 0) recognizedPass = true
216 if ((failed ?? 0) > 0) recognizedFail = true
217 }
218 const cargo = [...text.matchAll(/^test result: (ok|FAILED)\.\s*(\d+) passed;\s*(\d+) failed;/gm)]
219 if (cargo.length) {
220 passed = 0
221 failed = 0
222 for (const match of cargo) {
223 passed = Math.min(MAX_COUNT, passed + Number(match[2]))
224 failed = Math.min(MAX_COUNT, failed + Number(match[3]))
225 recognizedPass ||= match[1] === 'ok'
226 recognizedFail ||= match[1] === 'FAILED'
227 }
228 } else {
229 const summaries = [...text.matchAll(/^\s*Tests\s*:?\s+(.*)$/gm)]
230 const testSummary = summaries.at(-1)?.[1]
231 if (testSummary !== undefined) counts(testSummary)
232 else {
233 const pytest = [...text.matchAll(/^\s*(?:=+\s*)?(\d+ (?:passed|failed|skipped|error|errors|xfailed|xpassed).*?\bin \d+(?:\.\d+)?(?:s| seconds).*?)(?:\s*=+)?\s*$/gm)]
234 const summary = pytest.at(-1)?.[1]
235 if (summary !== undefined) {
236 counts(summary)
237 if (/\b[1-9]\d* errors?\b/.test(summary)) recognizedFail = true
238 }
239 }
240 }
241 if (/^ok[ \t]+\S+[ \t]+(?:\d+(?:\.\d+)?s|\(cached\))(?:[ \t]|$)/m.test(text)) recognizedPass = true
242 if (/^(?:FAIL(?:\s|$)|--- FAIL:)/m.test(text)) recognizedFail = true
243 if (passed !== undefined) check.passed = passed
244 if (failed !== undefined) check.failed = failed
245 if (nativeError || recognizedFail) check.status = 'failed'
246 else if (typeof value?.backgroundTaskId === 'string') check.status = 'running'
247 else if (recognizedPass) check.status = 'passed'
248 return check
249}
250
251export type GitStatusEntry = {
252 path: string
253 status: string
254 staged: boolean
255 untracked: boolean
256 originalPath?: string
257}
258
259// Porcelain v1 XY codes: X is the index, Y the work tree.
260export const changeState = (status: string): CockpitChangeState => {
261 if (status === '??') return 'untracked'
262 if (status.includes('U') || status === 'AA' || status === 'DD') return 'conflict'
263 if (/[RC]/.test(status)) return 'renamed'
264 if (status.charAt(0) === 'A') return 'added'
265 if (status.includes('D')) return 'deleted'
266 return 'modified'
267}
268
269export const parseGitStatus = (porcelain: string): GitStatusEntry[] => {
270 const entries: GitStatusEntry[] = []
271 const end = Math.min(porcelain.length, MAX_INPUT)
272 let offset = 0
273 const next = (): string | undefined => {
274 const nul = porcelain.indexOf('\0', offset)
275 if (nul < 0 || nul >= end) return undefined
276 const item = porcelain.slice(offset, nul)
277 offset = nul + 1
278 return item
279 }
280 while (offset < end && entries.length < MAX_ITEMS) {
281 const entry = next()
282 if (entry === undefined) break
283 const status = entry.slice(0, 2)
284 if (!/^[ MADRCUT?!]{2}$/.test(status) || entry[2] !== ' ') continue
285 const originalPath = /[RC]/.test(status) ? next() : undefined
286 const path = pathValue(entry.slice(3))
287 if (!path || status === '!!') continue
288 if (/[RC]/.test(status) && !pathValue(originalPath)) continue
289 entries.push({
290 path, status, staged: ![' ', '?', '!'].includes(status.charAt(0)), untracked: status === '??',
291 ...(originalPath === undefined ? {} : { originalPath }),
292 })
293 }
294 return entries
295}
296
297const decodeGitPath = (value: string): string | undefined => {
298 let decoded = value
299 if (value.startsWith('"')) {
300 const match = /^"((?:\\.|[^"\\])*)"/.exec(value)
301 if (!match) return undefined
302 decoded = (match[1] ?? '').replace(/(?:\\[0-7]{3})+|\\([abtnvfr\\"])/g, (escaped, named: string | undefined) => {
303 if (named) {
304 const escapes: Record<string, string> = { a: '\x07', b: '\b', t: '\t', n: '\n', v: '\v', f: '\f', r: '\r', '\\': '\\', '"': '"' }
305 return escapes[named] ?? named
306 }
307 const octets = escaped.match(/\\([0-7]{3})/g) ?? []
308 return new TextDecoder().decode(new Uint8Array(octets.map((octet: string) => parseInt(octet.slice(1), 8))))
309 })
310 }
311 return pathValue(decoded)
312}
313const markerPath = (value: string): string | undefined => {
314 const path = decodeGitPath(value.startsWith('"') ? value : value.split('\t')[0] ?? '')
315 if (!path || path === '/dev/null') return undefined
316 return path.replace(/^[ab]\//, '')
317}
318const headerPath = (line: string): string | undefined => {
319 const value = line.slice('diff --git '.length)
320 const boundary = Math.max(value.lastIndexOf(' b/'), value.lastIndexOf(' "b/'))
321 return boundary < 0 ? undefined : markerPath(value.slice(boundary + 1))
322}
323const safePatch = (patch: string): string =>
324 patch.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '')
325
326// A native diff view needs complete hunks. Omit a large first hunk instead of
327// presenting a cut hunk as a valid patch. Counts still describe observed data.
328const completePatch = (patch: string, wasTruncated = false): { patch: string; truncated: boolean } => {
329 const text = patch.slice(0, MAX_PATCH)
330 const cut = wasTruncated || patch.length > MAX_PATCH
331 let offset = 0
332 let boundary = 0
333 let oldRemaining = 0
334 let newRemaining = 0
335 let inHunk = false
336 let sawHunk = false
337 for (const line of text.split('\n')) {
338 const end = offset + line.length
339 const terminated = end < text.length
340 if (!terminated && cut) break
341 const next = end + (terminated ? 1 : 0)
342 const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line)
343 if (hunk) {
344 oldRemaining = Number(hunk[1] ?? 1)
345 newRemaining = Number(hunk[2] ?? 1)
346 inHunk = oldRemaining + newRemaining > 0
347 sawHunk = true
348 if (!inHunk) boundary = next
349 } else if (inHunk) {
350 if (line.startsWith('+') && newRemaining > 0) newRemaining--
351 else if (line.startsWith('-') && oldRemaining > 0) oldRemaining--
352 else if (line.startsWith(' ') && oldRemaining > 0 && newRemaining > 0) { oldRemaining--; newRemaining-- }
353 else if (line !== '\\ No newline at end of file') break
354 if (oldRemaining === 0 && newRemaining === 0) { inHunk = false; boundary = next }
355 } else if (line === '\\ No newline at end of file' && boundary === offset) boundary = next
356 offset = next
357 }
358 if (!sawHunk) return { patch: cut ? '' : text, truncated: cut }
359 const value = text.slice(0, boundary)
360 return { patch: value, truncated: cut || value.length < text.trimEnd().length }
361}
362
363export const parseGitDiff = (diff: string, now: number, staged = false): CockpitChange[] => {
364 const changes: CockpitChange[] = []
365 const input = diff.slice(0, MAX_INPUT)
366 const lines = input.split('\n')
367 let current: CockpitChange | undefined
368 let chunks: string[] = []
369 let size = 0
370 let total = 0
371 let inHunk = false
372 let hadHunk = false
373 let oldRemaining = 0
374 let newRemaining = 0
375 const finish = (): void => {
376 if (!current) return
377 if (current.path) {
378 const bounded = completePatch(chunks.join(''), current.truncated)
379 current.patch = bounded.patch
380 current.truncated = bounded.truncated
381 total += current.patch.length
382 changes.push(current)
383 }
384 current = undefined
385 chunks = []
386 size = 0
387 inHunk = false
388 hadHunk = false
389 oldRemaining = 0
390 newRemaining = 0
391 }
392 const start = (path: string | undefined): void => {
393 current = { path: path ?? '', patch: '', additions: 0, deletions: 0, source: 'git', staged, updatedAt: now }
394 }
395 for (let index = 0; index < lines.length; index++) {
396 const line = lines[index] ?? ''
397 if (line.startsWith('diff --git ')) {
398 finish()
399 if (changes.length >= MAX_ITEMS || total >= MAX_PATCH_TOTAL) break
400 start(headerPath(line))
401 } else if (!inHunk && line.startsWith('--- ') && (!current || hadHunk)) {
402 finish()
403 if (changes.length >= MAX_ITEMS || total >= MAX_PATCH_TOTAL) break
404 start(markerPath(line.slice(4)))
405 }
406 if (!current) continue
407 if (!inHunk && line.startsWith('--- ')) current.path = markerPath(line.slice(4)) ?? current.path
408 if (!inHunk && line.startsWith('+++ ')) current.path = markerPath(line.slice(4)) ?? current.path
409 if (!inHunk && line.startsWith('rename to ')) current.path = decodeGitPath(line.slice(10)) ?? current.path
410 const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line)
411 if (hunk) {
412 oldRemaining = Number(hunk[1] ?? 1)
413 newRemaining = Number(hunk[2] ?? 1)
414 inHunk = oldRemaining + newRemaining > 0
415 hadHunk = true
416 } else if (inHunk) {
417 if (line.startsWith('+')) {
418 current.additions = Math.min(MAX_COUNT, current.additions + 1)
419 newRemaining--
420 } else if (line.startsWith('-')) {
421 current.deletions = Math.min(MAX_COUNT, current.deletions + 1)
422 oldRemaining--
423 } else if (line.startsWith(' ')) {
424 oldRemaining--
425 newRemaining--
426 }
427 if (oldRemaining <= 0 && newRemaining <= 0) inHunk = false
428 }
429 const chunk = safePatch(line) + (index < lines.length - 1 ? '\n' : '')
430 const available = Math.min(MAX_PATCH - size, MAX_PATCH_TOTAL - total - size)
431 if (chunk.length > available) current.truncated = true
432 if (available > 0) { chunks.push(chunk.slice(0, available)); size += Math.min(chunk.length, available) }
433 }
434 finish()
435 const last = changes.at(-1)
436 if (last && diff.length > MAX_INPUT) last.truncated = true
437 return changes
438}
439
440export const normalizeObservedChanges = (
441 tool: string, input: unknown, result: unknown, now: number,
442): CockpitChange[] => {
443 if (tool === 'Bash') {
444 const wrapper = record(result)
445 if (typeof wrapper?.deny === 'string') return []
446 const value = record(wrapper?.result) ?? wrapper
447 const files = record(value?.bashEditDiff)?.files
448 if (!Array.isArray(files)) return []
449 const changes: CockpitChange[] = []
450 let total = 0
451 for (const file of files.slice(0, MAX_ITEMS)) {
452 const item = record(file)
453 if (!item) continue
454 const change = normalizeObservedChanges('Edit', {}, { filePath: item.filePath, structuredPatch: item.hunks }, now)[0]
455 if (!change) continue
456 const remaining = Math.max(0, MAX_PATCH_TOTAL - total)
457 if (change.patch.length > remaining) {
458 const bounded = completePatch(change.patch.slice(0, remaining), true)
459 change.patch = bounded.patch
460 change.truncated = true
461 }
462 total += change.patch.length
463 changes.push(change)
464 }
465 return changes
466 }
467 if (tool !== 'Edit' && tool !== 'Write') return []
468 const wrapper = record(result)
469 if (wrapper?.isError === true || typeof wrapper?.deny === 'string') return []
470 const value = record(wrapper?.result) ?? wrapper
471 if (!value || value.staged === true) return []
472 const path = pathValue(value.filePath) ?? pathValue(record(input)?.file_path)
473 if (!path) return []
474 const change: CockpitChange = { path, patch: '', additions: 0, deletions: 0, source: 'observed', updatedAt: now }
475 const gitDiff = record(value.gitDiff)
476 if (typeof gitDiff?.patch === 'string' && /^(?:diff --git |--- |\+\+\+ |@@ -|Binary files )/m.test(gitDiff.patch.slice(0, MAX_INPUT))) {
477 const patch = safePatch(gitDiff.patch.slice(0, MAX_INPUT))
478 const bounded = completePatch(patch, gitDiff.patch.length > MAX_INPUT)
479 change.patch = bounded.patch
480 change.truncated = bounded.truncated
481 const parsed = parseGitDiff(patch, now)[0]
482 change.additions = finite(gitDiff.additions) ?? parsed?.additions ?? 0
483 change.deletions = finite(gitDiff.deletions) ?? parsed?.deletions ?? 0
484 return [change]
485 }
486 if (!Array.isArray(value.structuredPatch) || value.structuredPatch.length === 0) return []
487 const chunks = [`--- ${JSON.stringify(`a/${path}`)}\n+++ ${JSON.stringify(`b/${path}`)}\n`]
488 let size = chunks[0]?.length ?? 0
489 let accepted = 0
490 let lineCount = 0
491 const append = (text: string): void => {
492 const chunk = safePatch(text.slice(0, MAX_PATCH + 1))
493 const available = Math.max(0, MAX_PATCH - size)
494 if (text.length > MAX_PATCH || chunk.length > available) change.truncated = true
495 if (available) { chunks.push(chunk.slice(0, available)); size += Math.min(chunk.length, available) }
496 }
497 for (const hunk of value.structuredPatch.slice(0, 1000)) {
498 const item = record(hunk)
499 if (!item || !Array.isArray(item.lines)) continue
500 const oldStart = hunkNumber(item.oldStart)
501 const oldLines = hunkNumber(item.oldLines)
502 const newStart = hunkNumber(item.newStart)
503 const newLines = hunkNumber(item.newLines)
504 if ([oldStart, oldLines, newStart, newLines].some(number => number === undefined)) continue
505 const body = item.lines.slice(0, 10001)
506 if (!body.length || body.some(line => typeof line !== 'string' || line.includes('\n') || !line.length || (!' +-'.includes(line.charAt(0)) && line !== '\\ No newline at end of file'))) continue
507 accepted++
508 append(`@@ -${oldStart},${oldLines} +${newStart},${newLines} @@\n`)
509 for (const line of body) {
510 if (++lineCount > 10000) { change.truncated = true; break }
511 if (typeof line !== 'string') continue
512 if (line.startsWith('+')) change.additions++
513 if (line.startsWith('-')) change.deletions++
514 append(`${line}\n`)
515 }
516 if (lineCount > 10000) break
517 }
518 if (!accepted) return []
519 if (value.structuredPatch.length > 1000) change.truncated = true
520 const bounded = completePatch(chunks.join(''), change.truncated)
521 change.patch = bounded.patch
522 change.truncated = bounded.truncated
523 return [change]
524}
525
526const MAX_SAMPLES = 240
527const MAX_TODOS = 50
528const MAX_TASKS = 100
529const MAX_ANSWER = 4000
530
531const text = (value: unknown, limit = 240): string | undefined =>
532 typeof value === 'string' && value.length > 0 ? label(value, limit) : undefined
533const array = (value: unknown, limit: number): unknown[] =>
534 Array.isArray(value) ? value.slice(0, limit) : []
535const resultOf = (result: unknown): Record<string, unknown> | undefined => {
536 const wrapper = record(result)
537 return record(wrapper?.result) ?? wrapper
538}
539const workStatus = (value: unknown): CockpitTodo['status'] | undefined =>
540 value === 'pending' || value === 'in_progress' || value === 'completed' ? value : undefined
541
542export const activityLevel = (activity: Pick<CockpitActivity, 'tools' | 'agents' | 'working'>): number =>
543 activity.tools.filter(tool => tool.outcome === 'running').length
544 + activity.agents.filter(agent => agent.status === 'running').length
545 + (activity.working ? 1 : 0)
546
547// Record the level only where it changes. The level holds between samples, so
548// a history needs no timer and has no gaps while the pane is closed.
549export const withSample = (activity: CockpitActivity, now: number): CockpitActivity => {
550 const level = activityLevel(activity)
551 const samples = Array.isArray(activity.samples) ? activity.samples : []
552 if (samples.at(-1)?.level === level) return activity
553 return { ...activity, samples: [...samples, { at: now, level }].slice(-MAX_SAMPLES) }
554}
555
556// Answers keep newlines and tabs for Markdown, and lose other control characters.
557export const answerText = (value: unknown): string | undefined => {
558 if (typeof value !== 'string') return undefined
559 return safePatch(value.slice(0, MAX_ANSWER)).trim() || undefined
560}
561
562export const agentResult = (result: unknown): { agentId: string; totals: CockpitAgentTotals; answer?: string } | undefined => {
563 const value = resultOf(result)
564 const agentId = text(value?.agentId, 200)
565 if (!value || !agentId || value.status !== 'completed') return undefined
566 const stats = record(value.toolStats)
567 const models = array(value.modelsUsed, 8).flatMap(model => text(model, 80) ?? [])
568 const resolved = text(value.resolvedModel, 80)
569 const answer = answerText(array(value.content, 50).flatMap(block => {
570 const blockText = record(block)?.text
571 return typeof blockText === 'string' ? [blockText] : []
572 }).join('\n'))
573 return {
574 agentId,
575 totals: {
576 tokens: finite(value.totalTokens, Number.MAX_SAFE_INTEGER) ?? 0,
577 toolUses: finite(value.totalToolUseCount) ?? 0,
578 durationMs: finite(value.totalDurationMs, Number.MAX_SAFE_INTEGER) ?? 0,
579 linesAdded: finite(stats?.linesAdded),
580 linesRemoved: finite(stats?.linesRemoved),
581 models: models.length > 0 ? models : resolved ? [resolved] : [],
582 },
583 answer,
584 }
585}
586
587export const todosOf = (result: unknown): CockpitTodo[] | undefined => {
588 const value = resultOf(result)
589 if (!Array.isArray(value?.newTodos)) return undefined
590 return value.newTodos.slice(0, MAX_TODOS).flatMap(item => {
591 const todo = record(item)
592 const status = workStatus(todo?.status)
593 const content = text(todo?.content)
594 if (!status || !content) return []
595 return [{ content, status, activeForm: text(todo?.activeForm) ?? content }]
596 })
597}
598
599// TaskList is authoritative. Create, Get and Update change one entry.
600export const applyTaskResult = (
601 tasks: CockpitTask[], tool: string, input: unknown, result: unknown,
602): CockpitTask[] | undefined => {
603 const value = resultOf(result)
604 const args = record(input)
605 if (!value) return undefined
606 const task = (item: unknown): CockpitTask | undefined => {
607 const entry = record(item)
608 const id = text(entry?.id, 80)
609 const subject = text(entry?.subject)
610 if (!id || !subject) return undefined
611 return { id, subject, status: workStatus(entry?.status) ?? 'pending', owner: text(entry?.owner, 80) }
612 }
613 const upsert = (next: CockpitTask): CockpitTask[] =>
614 [...tasks.filter(item => item.id !== next.id), next].slice(-MAX_TASKS)
615 if (tool === 'TaskList' && Array.isArray(value.tasks)) {
616 return value.tasks.slice(0, MAX_TASKS).flatMap(item => task(item) ?? [])
617 }
618 if (tool === 'TaskCreate' || tool === 'TaskGet') {
619 const next = task(value.task)
620 return next ? upsert({ ...tasks.find(item => item.id === next.id), ...next }) : undefined
621 }
622 if (tool === 'TaskUpdate' && value.success === true) {
623 const id = text(value.taskId, 80)
624 const existing = tasks.find(item => item.id === id)
625 if (!id) return undefined
626 if (args?.status === 'deleted') return tasks.filter(item => item.id !== id)
627 const status = workStatus(record(value.statusChange)?.to) ?? workStatus(args?.status)
628 const subject = text(args?.subject) ?? existing?.subject
629 if (!subject) return undefined
630 return upsert({
631 id, subject, status: status ?? existing?.status ?? 'pending',
632 owner: text(args?.owner, 80) ?? existing?.owner,
633 })
634 }
635 return undefined
636}
637
638export const gitOperationOf = (id: string, result: unknown, now: number): CockpitGitOperation | undefined => {
639 const operation = record(resultOf(result)?.gitOperation)
640 if (!operation) return undefined
641 const commit = record(operation.commit)
642 const push = record(operation.push)
643 const branch = record(operation.branch)
644 const pr = record(operation.pr)
645 const found: CockpitGitOperation = { id, at: now }
646 const sha = text(commit?.sha, 64)
647 if (sha) found.commit = { sha, kind: text(commit?.kind, 40) ?? 'committed', branch: text(commit?.branch, 200) }
648 const pushed = text(push?.branch, 200)
649 if (pushed) found.push = { branch: pushed }
650 const ref = text(branch?.ref, 200)
651 if (ref) found.branch = { ref, action: text(branch?.action, 40) ?? 'changed' }
652 const number = finite(pr?.number)
653 const url = text(pr?.url, 2048)
654 if (number !== undefined) {
655 found.pr = { number, action: text(pr?.action, 40) ?? 'changed', url: url?.startsWith('https://') ? url : undefined }
656 }
657 return found.commit || found.push || found.branch || found.pr ? found : undefined
658}
659
660// A launch is known from the tool result, and its end from the task
661// notification. A shell command line is never kept: only its description.
662export const backgroundLaunch = (
663 tool: string, input: unknown, result: unknown, now: number,
664): CockpitBackgroundTask | undefined => {
665 const value = resultOf(result)
666 const args = record(input)
667 const launched = (id: string | undefined, type: string, description: string | undefined): CockpitBackgroundTask | undefined =>
668 id ? { id, type, status: 'running', description: description ?? type, startedAt: now, updatedAt: now } : undefined
669 if (tool === 'Bash') {
670 const command = typeof args?.command === 'string' ? toolTarget('Bash', args) : undefined
671 return launched(text(value?.backgroundTaskId, 80), 'shell', text(args?.description) ?? command)
672 }
673 if (tool === 'Agent' && value?.status === 'async_launched') {
674 return launched(text(value.agentId, 200), 'subagent', text(value.description) ?? text(args?.description))
675 }
676 if (tool === 'Monitor') return launched(text(value?.taskId, 80), 'monitor', text(args?.description))
677 return undefined
678}
679
680// A redrawn notification ends nothing new, so it returns the same list.
681export const endBackground = (
682 previous: CockpitBackgroundTask[], id: string, status: string, now: number,
683): CockpitBackgroundTask[] =>
684 previous.some(task => task.id === id && task.endedAt === undefined)
685 ? previous.map(task => task.id === id && task.endedAt === undefined ? { ...task, status, endedAt: now, updatedAt: now } : task)
686 : previous
687
688/** The status of a task notification that reports an end. A progress notification has no status, or a live one. */
689export const endedStatus = (status: unknown): string | undefined => {
690 const value = text(status, 40)
691 return value === undefined || value === 'running' || value === 'pending' ? undefined : value
692}
693
694const MAX_CRONS = 20
695const WAKEUP = 'wakeup'
696
697// FNV-1a. A firing names a one-shot cron only by its prompt, and session
698// memory keeps no prompt.
699const promptKey = (prompt: string): string => {
700 let hash = 0x811c9dc5
701 const value = prompt.trim()
702 for (let index = 0; index < value.length; index += 1) {
703 hash = Math.imul(hash ^ value.charCodeAt(index), 0x01000193) >>> 0
704 }
705 return hash.toString(16)
706}
707
708// No plugin event lists the session's crons. The tools that schedule and
709// cancel them report each change.
710export const applyCronResult = (
711 crons: CockpitCron[], tool: string, input: unknown, result: unknown,
712): CockpitCron[] | undefined => {
713 const value = resultOf(result)
714 const args = record(input)
715 if (!value) return undefined
716 if (tool === 'CronCreate') {
717 const id = text(value.id, 80)
718 const schedule = text(value.humanSchedule, 80) ?? text(args?.cron, 80)
719 if (!id || !schedule) return undefined
720 const recurring = typeof value.recurring === 'boolean' ? value.recurring : args?.recurring !== false
721 const prompt = typeof args?.prompt === 'string' && !recurring ? promptKey(args.prompt) : undefined
722 return [...crons.filter(cron => cron.id !== id), { id, schedule, recurring, ...(prompt === undefined ? {} : { promptKey: prompt }) }].slice(-MAX_CRONS)
723 }
724 if (tool === 'CronDelete') {
725 const id = text(value.id, 80) ?? text(args?.id, 80)
726 return id ? crons.filter(cron => cron.id !== id) : undefined
727 }
728 if (tool === 'ScheduleWakeup') {
729 // A dynamic /loop holds one pending wakeup. The next call replaces it.
730 const rest = crons.filter(cron => cron.id !== WAKEUP)
731 if (value.stopped === true) return rest
732 const dueAt = finite(value.scheduledFor, Number.MAX_SAFE_INTEGER)
733 return dueAt === undefined ? undefined : [...rest, { id: WAKEUP, schedule: '/loop wakeup', recurring: false, dueAt }].slice(-MAX_CRONS)
734 }
735 return undefined
736}
737
738/** A scheduled prompt fired: the one-shot cron with that prompt deletes itself, and a due wakeup has fired. */
739export const firedCrons = (crons: CockpitCron[], prompt: string, now: number): CockpitCron[] => {
740 const key = promptKey(prompt)
741 const left = crons.filter(cron => cron.promptKey !== key && (cron.dueAt === undefined || cron.dueAt > now))
742 return left.length === crons.length ? crons : left
743}
744hooks/layout.tsx 176 lines1import type { RenderElement } from 'claude-code'
2import type { CockpitViewProps } from '../types'
3import type { Segment } from './summary'
4import type { CockpitElements } from './theme'
5import { clip, colors, padEnd, rule } from './theme'
6
7const width = (segments: readonly Segment[]): number =>
8 segments.reduce((total, segment) => total + [...segment.text].length, 0)
9
10/** Columns a view can fill: the pane body less one, so a full line never wraps. */
11export const viewWidth = (props: CockpitViewProps): number => Math.max(24, Math.floor(props.columns) - 1)
12
13/** Rows a list can take before it windows around the selection. */
14export const listLimit = (props: CockpitViewProps): number => Math.max(6, Math.min(20, Math.floor(props.rows) - 12))
15
16export const line = (ui: CockpitElements, key: string, segments: readonly Segment[], wrap = false): RenderElement => {
17 const { Text } = ui
18 return (
19 <Text key={key} wrap={wrap ? 'wrap' : 'truncate-end'}>
20 {segments.map(segment => <Text color={segment.color} backgroundColor={segment.backgroundColor} bold={segment.bold}>{segment.text}</Text>)}
21 </Text>
22 )
23}
24
25/** `Title ───────── detail`: the rule fills the line between them. */
26export const heading = (
27 ui: CockpitElements, key: string, title: string, detail: readonly Segment[], columns: number,
28): RenderElement => {
29 const detailWidth = width(detail)
30 const fill = columns - [...title].length - detailWidth - (detailWidth > 0 ? 2 : 1)
31 return line(ui, key, [
32 { text: title, color: colors.accent, bold: true },
33 { text: fill >= 2 ? ` ${rule(fill)}${detailWidth > 0 ? ' ' : ''}` : ' ', color: colors.muted },
34 ...detail,
35 ])
36}
37
38export type Action = { key: string; label: string; hotkey?: string; onPress: () => Promise<void> | void; hidden?: boolean }
39
40/** Plain buttons that read `r: Refresh`, as the view tabs do. */
41export const actions = (ui: CockpitElements, key: string, items: readonly Action[]): RenderElement => {
42 const { Box, Button } = ui
43 return (
44 <Box key={key} flexDirection="row" flexWrap="wrap" columnGap={2}>
45 {items.filter(item => !item.hidden).map(item => (
46 <Button key={item.key} plain label={item.label} hotkey={item.hotkey} onPress={item.onPress} />
47 ))}
48 </Box>
49 )
50}
51
52/** A muted label column and a value that wraps under itself. */
53export const field = (
54 ui: CockpitElements, key: string, label: string, value: readonly Segment[], labelWidth = 9,
55): RenderElement => {
56 const { Box, Text } = ui
57 return (
58 <Box key={key} flexDirection="row">
59 <Box width={labelWidth} flexShrink={0}><Text color={colors.muted}>{padEnd(label, labelWidth)}</Text></Box>
60 <Box flexGrow={1} flexShrink={1} minWidth={0}>{line(ui, `${key}:value`, value, true)}</Box>
61 </Box>
62 )
63}
64
65/** A row with content at the left edge and a detail at the right edge. */
66export const spread = (
67 ui: CockpitElements, key: string, left: RenderElement, right: readonly Segment[],
68): RenderElement => {
69 const { Box } = ui
70 return (
71 <Box key={key} flexDirection="row" justifyContent="space-between" gap={1}>
72 <Box flexShrink={1} minWidth={0}>{left}</Box>
73 <Box flexShrink={0}>{line(ui, `${key}:right`, right)}</Box>
74 </Box>
75 )
76}
77
78export const card = (ui: CockpitElements, key: string, children: (RenderElement | null | false | undefined)[]): RenderElement => {
79 const { Box } = ui
80 return (
81 <Box key={key} flexDirection="column" borderStyle="round" borderColor={colors.muted} paddingX={1} width="100%">
82 {children.filter((child): child is RenderElement => Boolean(child))}
83 </Box>
84 )
85}
86
87export const section = (ui: CockpitElements, key: string, children: (RenderElement | null | false | undefined)[]): RenderElement => {
88 const { Box } = ui
89 return (
90 <Box key={key} flexDirection="column" width="100%">
91 {children.filter((child): child is RenderElement => Boolean(child))}
92 </Box>
93 )
94}
95
96export const muted = (ui: CockpitElements, key: string, text: string): RenderElement => {
97 const { Text } = ui
98 return <Text key={key} color={colors.muted} wrap="wrap">{text}</Text>
99}
100
101export const visibleWindow = <T,>(items: readonly T[], selected: number, limit: number): readonly T[] => {
102 const size = Math.max(1, Math.floor(limit))
103 const anchor = Math.max(0, Math.min(items.length - 1, selected))
104 const start = Math.max(0, Math.min(items.length - size, anchor - Math.floor(size / 2)))
105 return items.slice(start, start + size)
106}
107
108export const neighboringIndex = (length: number, selected: number, direction: number): number =>
109 length > 0 ? (Math.max(0, selected) + direction + length) % length : 0
110
111export type Tab = { label: string; badge?: string }
112
113/** Columns of a plain tab: the Button's `1: Label`, then its badge after a space. */
114export const tabWidth = (tabs: readonly Tab[], index: number, badges: boolean): number => {
115 const tab = tabs[index]
116 if (tab === undefined) return 0
117 return [...`${index + 1}: ${tab.label}`].length + (badges && tab.badge ? 1 + [...tab.badge].length : 0)
118}
119
120/**
121 * How the tabs fit `columns`: one row three columns apart, then without badges,
122 * then two apart; else rows packed in order, with badges when they add no row.
123 */
124export const tabRows = (tabs: readonly Tab[], columns: number): { rows: number[][]; badges: boolean; gap: number } => {
125 const all = tabs.map((_, index) => index)
126 const total = (row: readonly number[], badges: boolean, gap: number): number =>
127 row.reduce((sum, index) => sum + tabWidth(tabs, index, badges), 0) + gap * Math.max(0, row.length - 1)
128 for (const [badges, gap] of [[true, 3], [false, 3], [false, 2]] as const) {
129 if (total(all, badges, gap) <= columns) return { rows: [all], badges, gap }
130 }
131 const pack = (badges: boolean): number[][] => {
132 const rows: number[][] = []
133 for (const index of all) {
134 const row = rows[rows.length - 1]
135 if (row && total([...row, index], badges, 3) <= columns) row.push(index)
136 else rows.push([index])
137 }
138 return rows
139 }
140 const badged = pack(true)
141 const plain = pack(false)
142 return badged.length <= plain.length ? { rows: badged, badges: true, gap: 3 } : { rows: plain, badges: false, gap: 3 }
143}
144
145/** The mark under the row that holds the active tab: a thin accent bar under it. */
146export const tabMark = (
147 tabs: readonly Tab[], row: readonly number[], active: number, badges: boolean, gap: number,
148): Segment[] | undefined => {
149 let used = 0
150 for (const [position, index] of row.entries()) {
151 if (position > 0) used += gap
152 const size = tabWidth(tabs, index, badges)
153 if (index === active) return [{ text: ' '.repeat(used) }, { text: '▔'.repeat(size), color: colors.accent }]
154 used += size
155 }
156 return undefined
157}
158
159/**
160 * The pane footer: the keys that work in this pane, in reading order. When it
161 * does not fit, the least needed part drops first: read-only, close, views.
162 */
163export const paneFooter = (surface: string, placement: 'dock' | 'inline', columns: number): string => {
164 if (surface !== 'terminal') return 'Read-only'
165 const parts = [
166 { text: 'Read-only', need: 4 },
167 { text: '1–5 views', need: 2 },
168 { text: 'Ctrl+X Tab focus', need: 0 },
169 { text: placement === 'dock' ? 'Ctrl+X ←/→ resize' : 'Ctrl+X ↑/↓ resize', need: 1 },
170 { text: 'Esc close', need: 3 },
171 ]
172 const text = (limit: number): string => parts.filter(part => part.need <= limit).map(part => part.text).join(' · ')
173 for (let limit = 4; limit > 0; limit -= 1) if ([...text(limit)].length <= columns) return text(limit)
174 return clip(text(0), columns)
175}
176hooks/state.ts 75 lines1import type {
2 CockpitActivity,
3 CockpitContext,
4 CockpitReview,
5} from '../types'
6
7export const initialActivity = (): CockpitActivity => ({
8 sessionId: null,
9 model: '',
10 working: false,
11 turnStartedAt: null,
12 phase: 'idle',
13 tools: [],
14 agents: [],
15 turns: [],
16 samples: [],
17 todos: [],
18 tasks: [],
19 background: [],
20 crons: [],
21 stopFailure: null,
22 selectedAgent: null,
23 selectedFor: null,
24 selectedTool: null,
25 updatedAt: 0,
26 error: null,
27})
28
29export const initialReview = (): CockpitReview => ({
30 sessionId: null,
31 changes: [],
32 findings: [],
33 checks: [],
34 gitOps: [],
35 selectedPath: null,
36 branch: null,
37 root: null,
38 refreshedAt: null,
39 loading: false,
40 error: null,
41})
42
43export const initialContext = (): CockpitContext => ({
44 sessionId: null,
45 usage: null,
46 compactions: [],
47 costs: [],
48 fills: [],
49 refreshedAt: null,
50 loading: false,
51 error: null,
52})
53
54// Hot reload keeps session memory in the shape an earlier version wrote. Fill
55// the fields it lacks, and drop activity samples from before they were records.
56// A complete value comes back as the same object, so an unchanged update stays one.
57const complete = <T extends object>(value: T, initial: T): boolean =>
58 Object.keys(initial).every(key => (value as Record<string, unknown>)[key] !== undefined)
59
60const filled = <T extends object>(value: T, initial: T): T =>
61 ({ ...initial, ...Object.fromEntries(Object.entries(value).filter(([, field]) => field !== undefined)) })
62
63export const activityOf = (value: CockpitActivity): CockpitActivity => {
64 const samples = Array.isArray(value.samples) ? value.samples : []
65 const records = samples.every(sample => typeof sample === 'object' && sample !== null)
66 if (complete(value, initialActivity()) && records && samples === value.samples) return value
67 return { ...filled(value, initialActivity()), samples: samples.filter(sample => typeof sample === 'object' && sample !== null) }
68}
69
70export const reviewOf = (value: CockpitReview): CockpitReview =>
71 complete(value, initialReview()) ? value : filled(value, initialReview())
72
73export const contextOf = (value: CockpitContext): CockpitContext =>
74 complete(value, initialContext()) ? value : filled(value, initialContext())
75hooks/summary.ts 486 lines1import type { ThemeKey } from 'claude-code'
2import type {
3 CockpitActivity, CockpitAgent, CockpitCheck, CockpitContext, CockpitReview, CockpitSample, CockpitTodo,
4 CockpitTokenUsage, CockpitTool, CockpitTurn,
5} from '../types'
6import { bar, brief, cells, clip, colors, compact, humanize, sparkline, statusColor, statusGlyph, stopwatch } from './theme'
7
8export type Segment = { text: string; color?: ThemeKey; backgroundColor?: ThemeKey; bold?: boolean }
9
10const finite = (value: number | undefined | null): value is number =>
11 typeof value === 'number' && Number.isFinite(value)
12
13// The time includes any permission prompt and hook time. Execution time alone
14// comes only from the classic PostToolUse hook, which a managed security plugin
15// keeps from installed plugins.
16export const toolDuration = (tool: CockpitTool, now: number): number | undefined => {
17 const end = tool.finishedAt ?? (tool.outcome === 'running' ? now : undefined)
18 if (end === undefined || !Number.isFinite(end) || !Number.isFinite(tool.startedAt)) return undefined
19 return Math.max(0, end - tool.startedAt)
20}
21
22export const runningTools = (activity: CockpitActivity): CockpitTool[] =>
23 activity.tools.filter(tool => tool.outcome === 'running').sort((left, right) => right.startedAt - left.startedAt)
24
25export const isLive = (agent: CockpitAgent): boolean =>
26 agent.status === 'running' || agent.status === 'pending' || agent.status === 'waiting'
27
28export const mainTurns = (activity: CockpitActivity): CockpitTurn[] =>
29 activity.turns.filter(turn => turn.agentId === undefined)
30
31export type TokenTotals = { input: number; output: number; cacheRead: number; cacheWrite: number }
32
33export const tokenTotals = (usages: readonly (CockpitTokenUsage | undefined)[]): TokenTotals =>
34 usages.reduce<TokenTotals>((total, usage) => usage ? {
35 input: total.input + (usage.input_tokens || 0),
36 output: total.output + (usage.output_tokens || 0),
37 cacheRead: total.cacheRead + (usage.cache_read_input_tokens || 0),
38 cacheWrite: total.cacheWrite + (usage.cache_creation_input_tokens || 0),
39 } : total, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
40
41/** The share of prompt tokens read from the cache; undefined before any prompt. */
42export const cacheHit = (totals: TokenTotals): number | undefined => {
43 const prompt = totals.input + totals.cacheRead + totals.cacheWrite
44 return prompt > 0 ? totals.cacheRead / prompt * 100 : undefined
45}
46
47export const agentTokens = (agent: CockpitAgent): number | undefined => {
48 if (agent.totals) return agent.totals.tokens
49 if (!agent.usage) return undefined
50 const totals = tokenTotals([agent.usage])
51 return totals.input + totals.output + totals.cacheRead + totals.cacheWrite
52}
53
54/** How long an agent ran: its reported duration, or the time since it was first seen. */
55export const agentElapsed = (agent: CockpitAgent, now: number): number | undefined => {
56 if (agent.totals) return agent.totals.durationMs
57 if (agent.durationMs !== undefined) return agent.durationMs
58 if (agent.startedAt === undefined) return undefined
59 return Math.max(0, (agent.completedAt ?? now) - agent.startedAt)
60}
61
62export const mainTodos = (activity: CockpitActivity): CockpitTodo[] =>
63 activity.todos.find(list => list.agentId === undefined)?.items ?? []
64
65export type PlanState = { done: number; total: number; current?: string; noun: 'todos' | 'tasks' }
66
67/** The plan of the main session, or of one agent: its todos. Tasks belong to the main session. */
68export const planState = (activity: Pick<CockpitActivity, 'todos' | 'tasks'>, agentId?: string): PlanState | undefined => {
69 const todos = activity.todos.find(list => list.agentId === agentId)?.items ?? []
70 if (todos.length > 0) {
71 const current = todos.find(todo => todo.status === 'in_progress')
72 return { done: todos.filter(todo => todo.status === 'completed').length, total: todos.length, current: current?.activeForm, noun: 'todos' }
73 }
74 if (agentId !== undefined || activity.tasks.length === 0) return undefined
75 const current = activity.tasks.find(task => task.status === 'in_progress')
76 return { done: activity.tasks.filter(task => task.status === 'completed').length, total: activity.tasks.length, current: current?.subject, noun: 'tasks' }
77}
78
79export const planProgress = (activity: Pick<CockpitActivity, 'todos' | 'tasks'>): string | undefined => {
80 const plan = planState(activity)
81 return plan ? `${plan.done}/${plan.total} ${plan.noun}` : undefined
82}
83
84export type ChangeTotals = { files: number; additions: number; deletions: number; staged: number; untracked: number }
85
86export const changeTotals = (review: CockpitReview): ChangeTotals => ({
87 files: review.changes.length,
88 additions: review.changes.reduce((total, change) => total + change.additions, 0),
89 deletions: review.changes.reduce((total, change) => total + change.deletions, 0),
90 staged: review.changes.filter(change => change.staged).length,
91 untracked: review.changes.filter(change => change.untracked).length,
92})
93
94/** A running check first; otherwise the one that finished last. */
95export const latestCheck = (review: CockpitReview): CockpitCheck | undefined =>
96 review.checks.filter(check => check.status === 'running').at(-1)
97 ?? review.checks.filter(check => check.status !== 'running').slice().sort((left, right) => (left.finishedAt ?? 0) - (right.finishedAt ?? 0)).at(-1)
98
99export const checkResult = (check: CockpitCheck): string => {
100 if (check.status === 'running') return 'running'
101 if (check.failed !== undefined && check.failed > 0) return `${compact(check.failed)} failed`
102 if (check.passed !== undefined) return `${compact(check.passed)} passed`
103 return check.status
104}
105
106export type ContextFill = {
107 tokens?: number
108 window?: number
109 percent?: number
110 threshold?: number
111 headroom?: number
112 /** Average growth per measurement, after compactions are left out. */
113 growth?: number
114 responsesLeft?: number
115}
116
117export const contextFill = (context: CockpitContext): ContextFill => {
118 const live = context.usage?.context
119 const breakdown = live?.breakdown
120 const threshold = breakdown?.isAutoCompactEnabled ? breakdown.autoCompactThreshold : undefined
121 const tokens = live?.tokens
122 const deltas = context.fills.slice(1).map((sample, index) => sample.tokens - (context.fills[index]?.tokens ?? sample.tokens))
123 .filter(delta => delta > 0).slice(-5)
124 const growth = deltas.length > 0 ? deltas.reduce((total, delta) => total + delta, 0) / deltas.length : undefined
125 const headroom = finite(threshold) && finite(tokens) ? Math.max(0, threshold - tokens) : undefined
126 return {
127 tokens, window: live?.window, percent: live?.percent, threshold, headroom, growth,
128 responsesLeft: finite(headroom) && finite(growth) && growth > 0 ? headroom / growth : undefined,
129 }
130}
131
132/** The context share at which the band and header warn: near auto-compaction, or 80% without a threshold. */
133export const contextColor = (fill: ContextFill): ThemeKey => {
134 if (!finite(fill.percent)) return colors.muted
135 const limit = finite(fill.threshold) && finite(fill.window) && fill.window > 0 ? fill.threshold / fill.window * 100 : 80
136 if (fill.percent >= limit) return colors.red
137 if (fill.percent >= limit - 10) return colors.yellow
138 return colors.muted
139}
140
141export type ToolStat = { tool: string; calls: number; failures: number; totalMs: number; maxMs: number }
142
143export const toolStats = (tools: readonly CockpitTool[], now: number): ToolStat[] => {
144 const stats = new Map<string, ToolStat>()
145 for (const tool of tools) {
146 const stat = stats.get(tool.tool) ?? { tool: tool.tool, calls: 0, failures: 0, totalMs: 0, maxMs: 0 }
147 const elapsed = toolDuration(tool, now) ?? 0
148 stat.calls += 1
149 if (tool.outcome === 'error' || tool.outcome === 'denied') stat.failures += 1
150 stat.totalMs += elapsed
151 stat.maxMs = Math.max(stat.maxMs, elapsed)
152 stats.set(tool.tool, stat)
153 }
154 return [...stats.values()].sort((left, right) => right.totalMs - left.totalMs || right.calls - left.calls)
155}
156
157export const approvalCount = (tools: readonly CockpitTool[]): number =>
158 tools.filter(tool => tool.approval === 'asked').length
159
160export const sessionStart = (activity: CockpitActivity, context: CockpitContext): number | undefined => {
161 const started = context.usage?.startedAt
162 if (finite(started)) return started
163 const times = [
164 ...activity.tools.map(tool => tool.startedAt),
165 ...activity.turns.map(turn => turn.finishedAt - turn.durationMs),
166 ...activity.samples.map(sample => sample.at),
167 ].filter(finite)
168 return times.length > 0 ? Math.min(...times) : undefined
169}
170
171export const toolLabel = (tool: CockpitTool): string => tool.target ? `${tool.tool} ${tool.target}` : tool.tool
172
173/** The main thread's own call first, then a subagent it waits on, then any running call. */
174export const leadTool = (running: readonly CockpitTool[]): CockpitTool | undefined =>
175 running.find(tool => tool.agentId === undefined && tool.tool !== 'Agent')
176 ?? running.find(tool => tool.agentId === undefined)
177 ?? running[0]
178
179export type StatusSummary = { glyph: string; label: string; color: ThemeKey; since?: number }
180
181/** What the main session is doing now, for the band and the pane header. */
182export const sessionStatus = (activity: CockpitActivity, isWorking: boolean): StatusSummary => {
183 const failure = isWorking ? null : activity.stopFailure
184 if (failure) return { glyph: '✗', label: `stopped: ${humanize(failure.error)}`, color: colors.red }
185 const running = runningTools(activity)
186 const lead = leadTool(running)
187 if (lead) {
188 const more = running.length > 1 ? ` +${running.length - 1}` : ''
189 return { glyph: '▸', label: `${toolLabel(lead)}${more}`, color: colors.cyan, since: lead.startedAt }
190 }
191 if (isWorking) return { glyph: '▸', label: 'thinking', color: colors.cyan, since: activity.turnStartedAt ?? undefined }
192 if (activity.phase === 'error') return { glyph: '✗', label: 'last turn failed', color: colors.red }
193 return { glyph: '○', label: 'idle', color: colors.muted }
194}
195
196// Activity history: one level per bucket, for the band and the Activity view.
197export const HISTORY_BUCKET_MS = 5000
198
199// The level per bucket for the newest buckets up to `now`: the highest level
200// reached in the bucket, or the level carried from the sample before it.
201export const activityHistory = (
202 samples: readonly CockpitSample[], now: number, columns: number, bucketMs = HISTORY_BUCKET_MS,
203): number[] => {
204 const sorted = samples.filter(sample => finite(sample?.at) && finite(sample?.level)).slice().sort((left, right) => left.at - right.at)
205 const first = sorted[0]
206 if (first === undefined || !finite(now)) return []
207 const width = Math.max(1, Math.min(120, Math.floor(Number.isFinite(columns) ? columns : 40)))
208 const end = Math.floor(now / bucketMs)
209 const begin = Math.max(end - width + 1, Math.floor(first.at / bucketMs))
210 let carried = 0
211 let cursor = 0
212 while (cursor < sorted.length && Math.floor((sorted[cursor]?.at ?? 0) / bucketMs) < begin) {
213 carried = sorted[cursor]?.level ?? carried
214 cursor += 1
215 }
216 const levels: number[] = []
217 for (let bucket = begin; bucket <= end; bucket += 1) {
218 let peak = carried
219 while (cursor < sorted.length && Math.floor((sorted[cursor]?.at ?? 0) / bucketMs) === bucket) {
220 carried = sorted[cursor]?.level ?? carried
221 peak = Math.max(peak, carried)
222 cursor += 1
223 }
224 levels.push(peak)
225 }
226 return levels
227}
228
229// ---------------------------------------------------------------- band
230
231export type BandRow = { start: Segment[]; end: Segment[] }
232
233export type BandOptions = {
234 isWorking: boolean
235 columns: number
236 now: number
237 /** The agent whose transcript is on screen; absent for the main conversation. */
238 agentId?: string
239 /** The spinner frame; absent while animation is off. */
240 frame?: number
241}
242
243const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
244const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
245const GAP = 2
246const SPARK_BUCKETS = 10
247const SPARK_BUCKET_MS = 30000
248
249const width = (segments: readonly Segment[]): number =>
250 segments.reduce((total, segment) => total + cells(segment.text), 0)
251
252const spin = (frame: number | undefined): string =>
253 frame === undefined || !finite(frame) ? '▸' : SPINNER[Math.abs(Math.floor(frame)) % SPINNER.length] ?? '▸'
254
255// Seconds while they change, then minutes, so that a chip keeps its width.
256const age = (ms: number): string => ms < 60000 ? stopwatch(ms) : brief(ms)
257
258const agentLabel = (agent: CockpitAgent): string => agent.name ?? agent.type
259
260/** Edits that finished after a check can have changed its result. */
261export const isStale = (check: CockpitCheck, tools: readonly CockpitTool[]): boolean => {
262 const finished = check.finishedAt
263 if (check.status === 'running' || !finite(finished)) return false
264 return tools.some(tool => EDIT_TOOLS.has(tool.tool) && tool.outcome === 'success'
265 && (tool.finishedAt ?? tool.startedAt) > finished)
266}
267
268/** A bar in eighths of a cell over a muted track. */
269const gauge = (fraction: number, columns: number, color: ThemeKey): Segment[] => {
270 const filled = bar(fraction, columns)
271 const whole = filled.replace(/[^█]/g, '')
272 const segments: Segment[] = [
273 { text: whole, color },
274 { text: filled.slice(whole.length), color, backgroundColor: colors.muted },
275 { text: ' '.repeat(Math.max(0, columns - [...filled].length)), backgroundColor: colors.muted },
276 ]
277 return segments.filter(segment => segment.text !== '')
278}
279
280/** Five cells split between additions and deletions, as `git diff --stat` splits its bar. */
281const diffstat = (additions: number, deletions: number): Segment[] => {
282 const total = additions + deletions
283 if (!(total > 0)) return []
284 const added = deletions === 0 ? 5 : additions === 0 ? 0 : Math.min(4, Math.max(1, Math.round(additions / total * 5)))
285 const segments: Segment[] = [{ text: '▮'.repeat(added), color: colors.green }, { text: '▮'.repeat(5 - added), color: colors.red }]
286 return segments.filter(segment => segment.text !== '')
287}
288
289const checkCounts = (check: CockpitCheck): string => {
290 if (check.failed !== undefined && check.failed > 0) {
291 return check.passed === undefined ? `${compact(check.failed)} failed` : `${compact(check.failed)}/${compact(check.failed + check.passed)} failed`
292 }
293 if (check.passed !== undefined) return `${compact(check.passed)} passed`
294 return check.status
295}
296
297type Part = { priority: number; full: Segment[]; short?: Segment[]; end?: true }
298
299const clipSegments = (segments: readonly Segment[], columns: number): Segment[] => {
300 const clipped: Segment[] = []
301 let left = columns
302 for (const segment of segments) {
303 const size = cells(segment.text)
304 if (size <= left) {
305 clipped.push(segment)
306 left -= size
307 continue
308 }
309 let text = ''
310 for (const char of segment.text) {
311 if (cells(text + char) > left - 1) break
312 text += char
313 }
314 if (left >= 1) clipped.push({ ...segment, text: `${text}…` })
315 break
316 }
317 return clipped
318}
319
320/**
321 * One band row. When the row is too wide, every part takes its short form, the
322 * lowest priorities drop, and the highest regain their full form while it fits.
323 */
324const fitRow = (parts: readonly Part[], columns: number): BandRow | undefined => {
325 if (parts.length === 0) return undefined
326 const full = new Set<Part>(parts)
327 const form = (part: Part): Segment[] => full.has(part) ? part.full : part.short ?? part.full
328 const measure = (kept: readonly Part[]) =>
329 kept.reduce((total, part) => total + width(form(part)), 0) + GAP * Math.max(0, kept.length - 1)
330 let kept = [...parts]
331 if (measure(kept) > columns) {
332 full.clear()
333 while (kept.length > 1 && measure(kept) > columns) {
334 const lowest = Math.max(...kept.map(part => part.priority))
335 kept = kept.filter(part => part.priority !== lowest)
336 }
337 for (const part of kept) {
338 full.add(part)
339 if (measure(kept) > columns) full.delete(part)
340 }
341 }
342 const join = (side: readonly Part[]): Segment[] =>
343 side.flatMap((part, index) => index > 0 ? [{ text: ' '.repeat(GAP) }, ...form(part)] : form(part))
344 const start = join(kept.filter(part => !part.end))
345 const end = join(kept.filter(part => part.end))
346 // A part left alone can still be too wide.
347 if (measure(kept) > columns) return { start: clipSegments([...start, ...end], columns), end: [] }
348 return { start, end }
349}
350
351/** What the main session runs now, or why it stopped; nothing while idle. */
352const mainStatus = (activity: CockpitActivity, isWorking: boolean, glyph: string, now: number): Part | undefined => {
353 const failure = isWorking ? null : activity.stopFailure
354 if (failure) return { priority: 0, full: [{ text: `✗ stopped: ${humanize(failure.error)}`, color: colors.red }] }
355 const running = runningTools(activity)
356 const lead = leadTool(running)
357 if (lead) {
358 const tail = ` ${stopwatch(now - lead.startedAt)}${running.length > 1 ? ` +${running.length - 1}` : ''}`
359 return {
360 priority: 0,
361 full: [{ text: `${glyph} ${clip(toolLabel(lead), 40)}${tail}`, color: colors.cyan }],
362 short: [{ text: `${glyph} ${clip(lead.tool, 16)}${tail}`, color: colors.cyan }],
363 }
364 }
365 if (isWorking) return { priority: 0, full: [{ text: `${glyph} thinking`, color: colors.cyan }] }
366 if (activity.phase === 'error') return { priority: 0, full: [{ text: '✗ last turn failed', color: colors.red }] }
367 return undefined
368}
369
370/** What the agent in view runs now, or its status, after its name. */
371const agentStatus = (activity: CockpitActivity, agentId: string, glyph: string, now: number): Part => {
372 const agent = activity.agents.find(item => item.id === agentId)
373 const name: Segment = { text: `${clip(agent ? agentLabel(agent) : 'agent', 16)} › `, color: colors.magenta }
374 const own = runningTools(activity).filter(tool => tool.agentId === agentId)
375 const lead = own.find(tool => tool.tool !== 'Agent') ?? own[0]
376 if (lead) {
377 const tail = ` ${stopwatch(now - lead.startedAt)}${own.length > 1 ? ` +${own.length - 1}` : ''}`
378 return {
379 priority: 0,
380 full: [name, { text: `${glyph} ${clip(toolLabel(lead), 40)}${tail}`, color: colors.cyan }],
381 short: [name, { text: `${glyph} ${clip(lead.tool, 16)}${tail}`, color: colors.cyan }],
382 }
383 }
384 if (agent && isLive(agent)) return { priority: 0, full: [name, { text: `${glyph} thinking`, color: colors.cyan }] }
385 const status = agent?.status ?? 'missing'
386 const elapsed = agent ? agentElapsed(agent, now) : undefined
387 return {
388 priority: 0,
389 full: [name, { text: `${statusGlyph(status)} ${status}${elapsed === undefined ? '' : ` ${age(elapsed)}`}`, color: statusColor(status) }],
390 }
391}
392
393/**
394 * The band: what runs now, then where the work stands. The first row shows
395 * while anything runs, and drops while the session is idle. The status line
396 * shows the model, context fill, and cost, and the engine shows the turn time,
397 * so the band leaves them out.
398 */
399export const bandRows = (
400 activity: CockpitActivity, review: CockpitReview, context: CockpitContext, options: BandOptions,
401): BandRow[] => {
402 const { agentId, now } = options
403 const columns = Math.max(8, Math.floor(options.columns))
404 const glyph = spin(options.frame)
405
406 const running: Part[] = []
407 const status = agentId === undefined
408 ? mainStatus(activity, options.isWorking, glyph, now)
409 : agentStatus(activity, agentId, glyph, now)
410 if (status) running.push(status)
411 const live = activity.agents.filter(agent => isLive(agent) && agent.id !== agentId)
412 .sort((left, right) => (left.startedAt ?? 0) - (right.startedAt ?? 0))
413 if (live.length > 0) {
414 const chips = live.map((agent): Segment[] => {
415 const elapsed = agentElapsed(agent, now)
416 return [{
417 text: `${agent.status === 'pending' ? '○' : '◐'} ${clip(agentLabel(agent), 16)}${elapsed === undefined ? '' : ` ${age(elapsed)}`}`,
418 color: agent.status === 'waiting' ? colors.yellow : colors.magenta,
419 }]
420 })
421 running.push({
422 priority: 1,
423 full: chips.flatMap((chip, index) => index > 0 ? [{ text: ' '.repeat(GAP) }, ...chip] : chip),
424 short: [{ text: `◐ ${live.length} ${live.length === 1 ? 'agent' : 'agents'}`, color: colors.magenta }],
425 })
426 }
427 if (running.length > 0) {
428 const history = activityHistory(activity.samples, now, SPARK_BUCKETS, SPARK_BUCKET_MS)
429 if (history.length > 1) running.push({ priority: 2, end: true, full: [{ text: sparkline(history, SPARK_BUCKETS), color: colors.cyan }] })
430 }
431
432 const state: Part[] = []
433 const viewed = agentId === undefined ? undefined : activity.agents.find(agent => agent.id === agentId)
434 const plan = planState(activity, agentId)
435 // A finished plan stays only while its work runs.
436 if (plan && (plan.done < plan.total || (viewed ? isLive(viewed) : options.isWorking))) {
437 const progress = gauge(plan.total > 0 ? plan.done / plan.total : 0, 6, colors.accent)
438 state.push({
439 priority: 0,
440 full: [...progress, { text: ` ${plan.done}/${plan.total}${plan.current ? ` ${clip(plan.current, 32)}` : ` ${plan.noun}`}`, color: colors.accent }],
441 short: [...progress, { text: ` ${plan.done}/${plan.total}`, color: colors.accent }],
442 })
443 }
444 const check = latestCheck(review)
445 if (check) {
446 const failed = check.status === 'failed' || (check.failed ?? 0) > 0
447 const stale = isStale(check, activity.tools)
448 const mark = check.status === 'running' ? glyph : statusGlyph(failed ? 'failed' : check.status)
449 const color = stale ? colors.muted : check.status === 'running' ? colors.cyan : failed ? colors.red : statusColor(check.status)
450 const result = check.status === 'running' ? '' : ` ${checkCounts(check)}${stale ? ' (stale)' : ''}`
451 state.push({
452 priority: 1,
453 full: [{ text: `${mark} ${clip(check.label, 24)}${result}`, color }],
454 short: [{ text: `${mark} ${clip(check.label, 12)}`, color }],
455 })
456 }
457 const changes = changeTotals(review)
458 if (changes.files > 0) {
459 const counts: Segment[] = [
460 { text: `+${compact(changes.additions)}`, color: colors.green }, { text: ' ' },
461 { text: `−${compact(changes.deletions)}`, color: colors.red },
462 ]
463 const stat = diffstat(changes.additions, changes.deletions)
464 state.push({
465 priority: 2,
466 full: [{ text: `${changes.files} ${changes.files === 1 ? 'file' : 'files'} ` }, ...counts, ...(stat.length > 0 ? [{ text: ' ' }, ...stat] : [])],
467 short: counts,
468 })
469 }
470 const fill = contextFill(context)
471 const warning = contextColor(fill)
472 // Only near auto-compaction: the status line shows the fill, not the threshold.
473 if (finite(fill.threshold) && warning !== colors.muted) {
474 const replies = finite(fill.responsesLeft) ? Math.floor(fill.responsesLeft) : undefined
475 const full = replies === undefined
476 ? finite(fill.headroom) && fill.headroom > 0 ? `${compact(fill.headroom)} to compact` : 'compaction due'
477 : replies < 1 ? 'compaction next' : `~${replies} ${replies === 1 ? 'reply' : 'replies'} to compact`
478 const short = replies === undefined
479 ? finite(fill.headroom) && fill.headroom > 0 ? compact(fill.headroom) : 'due'
480 : replies < 1 ? 'next' : `~${replies}`
481 state.push({ priority: 3, full: [{ text: `⟳ ${full}`, color: warning }], short: [{ text: `⟳ ${short}`, color: warning }] })
482 }
483
484 return [fitRow(running, columns), fitRow(state, columns)].filter((row): row is BandRow => row !== undefined)
485}
486hooks/theme.ts 148 lines1import type { Elements, RenderSurface, ThemeKey } from 'claude-code'
2
3export type CockpitElements = Elements[RenderSurface]
4
5// Theme keys follow the person's theme. An ANSI theme draws them with the
6// terminal's own palette. Raw hex and color names are fixed RGB values, which
7// a 256-color terminal (any tmux session) rounds to the nearest xterm color.
8export const colors = {
9 accent: 'suggestion',
10 cyan: 'planMode',
11 green: 'success',
12 yellow: 'warning',
13 red: 'error',
14 magenta: 'merged',
15 muted: 'inactive',
16} as const satisfies Record<string, ThemeKey>
17
18export const cleanText = (text: string): string =>
19 text.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
20
21const length = (text: string): number => [...text].length
22
23// East Asian wide letters and emoji take two terminal cells, combining marks none.
24const WIDE = /[\u{1100}-\u{115f}\u{2e80}-\u{303e}\u{3041}-\u{33ff}\u{3400}-\u{4dbf}\u{4e00}-\u{9fff}\u{a000}-\u{a4cf}\u{ac00}-\u{d7a3}\u{f900}-\u{faff}\u{fe30}-\u{fe4f}\u{ff00}-\u{ff60}\u{ffe0}-\u{ffe6}\u{20000}-\u{3fffd}]|\p{Emoji_Presentation}/u
25const ZERO = /[\p{Mn}\p{Me}\u{200b}-\u{200f}\u{fe00}-\u{fe0f}]/u
26
27/** The terminal cells a text takes. */
28export const cells = (text: string): number =>
29 [...text].reduce((total, char) => total + (ZERO.test(char) ? 0 : WIDE.test(char) ? 2 : 1), 0)
30
31export const clip = (text: string, columns: number): string => {
32 const value = cleanText(text)
33 const limit = Math.max(1, Math.floor(columns))
34 return length(value) <= limit ? value : `${[...value].slice(0, Math.max(0, limit - 1)).join('')}…`
35}
36
37// Paths keep their file name: the end says more than the start.
38export const clipStart = (text: string, columns: number): string => {
39 const value = cleanText(text)
40 const limit = Math.max(1, Math.floor(columns))
41 return length(value) <= limit ? value : `…${[...value].slice(length(value) - limit + 1).join('')}`
42}
43
44export const padEnd = (text: string, columns: number): string =>
45 `${text}${' '.repeat(Math.max(0, Math.floor(columns) - length(text)))}`
46
47export const padStart = (text: string, columns: number): string =>
48 `${' '.repeat(Math.max(0, Math.floor(columns) - length(text)))}${text}`
49
50export const duration = (ms: number): string => {
51 const safe = Math.max(0, Number.isFinite(ms) ? ms : 0)
52 if (safe < 1000) return `${Math.round(safe)}ms`
53 if (safe < 60000) return `${(safe / 1000).toFixed(1)}s`
54 if (safe < 3600000) return `${Math.floor(safe / 60000)}m ${Math.floor((safe % 60000) / 1000)}s`
55 return `${Math.floor(safe / 3600000)}h ${Math.floor((safe % 3600000) / 60000)}m`
56}
57
58/** One unit, for columns and ages: 45s, 9m, 2h, 3d. */
59export const brief = (ms: number): string => {
60 const safe = Math.max(0, Number.isFinite(ms) ? ms : 0)
61 if (safe < 10000) return `${(safe / 1000).toFixed(1)}s`
62 if (safe < 60000) return `${Math.floor(safe / 1000)}s`
63 if (safe < 3600000) return `${Math.floor(safe / 60000)}m`
64 if (safe < 86400000) return `${Math.floor(safe / 3600000)}h`
65 return `${Math.floor(safe / 86400000)}d`
66}
67
68/** Whole seconds, for a clock that redraws once a second: 9s, 1m05s, 2h04m. */
69export const stopwatch = (ms: number): string => {
70 const seconds = Math.floor(Math.max(0, Number.isFinite(ms) ? ms : 0) / 1000)
71 if (seconds < 60) return `${seconds}s`
72 if (seconds < 3600) return `${Math.floor(seconds / 60)}m${String(seconds % 60).padStart(2, '0')}s`
73 return `${Math.floor(seconds / 3600)}h${String(Math.floor((seconds % 3600) / 60)).padStart(2, '0')}m`
74}
75
76export const ago = (now: number, at: number | null | undefined): string =>
77 at === null || at === undefined || !Number.isFinite(at) || !Number.isFinite(now) ? 'never' : `${brief(now - at)} ago`
78
79export const count = (value: number | undefined): string => {
80 if (value === undefined || !Number.isFinite(value)) return 'unknown'
81 return Math.round(Math.max(0, value)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
82}
83
84/** 950, 1.2k, 61k, 1.4M. */
85export const compact = (value: number | undefined): string => {
86 if (value === undefined || !Number.isFinite(value)) return '?'
87 const safe = Math.max(0, value)
88 if (safe < 1000) return `${Math.round(safe)}`
89 if (safe < 10000) return `${(safe / 1000).toFixed(1)}k`
90 if (safe < 1000000) return `${Math.round(safe / 1000)}k`
91 return `${(safe / 1000000).toFixed(1)}M`
92}
93
94export const usd = (value: number): string =>
95 !Number.isFinite(value) ? '$?' : value >= 0.995 || value === 0 ? `$${value.toFixed(2)}` : `$${value.toFixed(value >= 0.01 ? 2 : 4)}`
96
97export const percent = (value: number | undefined): string =>
98 value === undefined || !Number.isFinite(value) ? '?' : `${Math.round(value)}%`
99
100export const humanize = (code: string): string => cleanText(code).replace(/_/g, ' ')
101
102export const plural = (value: number, noun: string): string =>
103 `${count(value)} ${value === 1 ? noun : `${noun}s`}`
104
105export const shortModel = (model: string): string =>
106 cleanText(model).replace(/^claude-/, '').replace(/-\d{8}$/, '').replace(/\[1m\]$/, '')
107
108export const meter = (value: number, width = 16): string => {
109 const cells = Math.max(1, Math.min(120, Math.floor(width)))
110 const filled = Math.round((Math.max(0, Math.min(100, Number.isFinite(value) ? value : 0)) / 100) * cells)
111 return `${'━'.repeat(filled)}${'─'.repeat(cells - filled)}`
112}
113
114const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
115
116/** A left-aligned bar in eighths of a cell, for one row of a ranking. */
117export const bar = (fraction: number, width: number): string => {
118 const cells = Math.max(0, Math.floor(width))
119 const eighths = Math.round(Math.max(0, Math.min(1, Number.isFinite(fraction) ? fraction : 0)) * cells * 8)
120 return `${'█'.repeat(Math.floor(eighths / 8))}${EIGHTHS[eighths % 8] ?? ''}`
121}
122
123export const sparkline = (values: readonly number[], columns: number): string => {
124 const shown = values.slice(-Math.max(1, Math.min(120, Math.floor(Number.isFinite(columns) ? columns : 40))))
125 if (shown.length === 0) return ''
126 const maximum = Math.max(1e-9, ...shown.filter(Number.isFinite))
127 const glyphs = '▁▂▃▄▅▆▇█'
128 return shown.map(value => glyphs[Math.max(0, Math.min(7, Math.round((Number.isFinite(value) ? Math.max(0, value) : 0) / maximum * 7)))] ?? '▁').join('')
129}
130
131export const rule = (width: number): string => '─'.repeat(Math.max(0, Math.floor(width)))
132
133export const statusColor = (status: string): ThemeKey => {
134 if (['failed', 'error', 'denied', 'killed', 'interrupted'].includes(status)) return colors.red
135 if (['running', 'thinking', 'tools', 'pending'].includes(status)) return colors.cyan
136 if (['waiting', 'missing'].includes(status)) return colors.yellow
137 if (['completed', 'success', 'passed'].includes(status)) return colors.green
138 return colors.muted
139}
140
141const glyphs: Record<string, string> = {
142 running: '▸', thinking: '▸', tools: '▸', pending: '○', waiting: '◐', idle: '○',
143 success: '✓', completed: '✓', passed: '✓',
144 error: '✗', failed: '✗', denied: '⊘', killed: '■', interrupted: '■', missing: '?',
145}
146
147export const statusGlyph = (status: string): string => glyphs[status] ?? '·'
148hooks/tools.tsx 236 lines1import type { RenderElement } from 'claude-code'
2import type { CockpitBackgroundTask, CockpitTool, CockpitViewProps } from '../types'
3import { actorName, agentName } from './agents'
4import { actions, card, field, heading, line, listLimit, muted, neighboringIndex, section, spread, viewWidth, visibleWindow } from './layout'
5import type { Segment } from './summary'
6import { approvalCount, runningTools, toolDuration, toolLabel, toolStats } from './summary'
7import type { CockpitElements } from './theme'
8import { ago, bar, brief, clip, colors, duration, padEnd, padStart, plural, statusColor, statusGlyph } from './theme'
9
10const outcomeColor = (tool: CockpitTool) =>
11 tool.outcome === 'running' && tool.approval === 'asked' ? colors.yellow : statusColor(tool.outcome)
12
13const failed = (tool: CockpitTool): boolean => tool.outcome === 'error' || tool.outcome === 'denied'
14
15const summary = (ui: CockpitElements, props: CockpitViewProps, tools: readonly CockpitTool[], width: number): RenderElement => {
16 const running = tools.filter(tool => tool.outcome === 'running').length
17 const failures = tools.filter(failed).length
18 const ran = tools.filter(tool => tool.tool !== 'Agent').reduce((total, tool) => total + (toolDuration(tool, props.now) ?? 0), 0)
19 const asked = approvalCount(tools)
20 return section(ui, 'tools:summary', [
21 heading(ui, 'tools:title', 'Tools', [
22 { text: plural(tools.length, 'call'), color: colors.muted },
23 { text: running > 0 ? ` · ${running} running` : '', color: colors.cyan },
24 { text: failures > 0 ? ` · ${failures} failed` : '', color: colors.red },
25 ], width),
26 line(ui, 'tools:time', [
27 { text: 'Tool time ', color: colors.muted }, { text: duration(ran) },
28 ...(asked > 0 ? [
29 { text: ' · ', color: colors.muted },
30 { text: plural(asked, 'approval'), color: colors.yellow },
31 ] : []),
32 ], true),
33 ])
34}
35
36const runningSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
37 const running = runningTools(props.activity)
38 if (running.length === 0) return null
39 return section(ui, 'tools:running', [
40 heading(ui, 'tools:running:title', 'Running now', [{ text: `${running.length}`, color: colors.cyan }], width),
41 ...running.slice(0, 6).map(tool => {
42 const actor = clip(actorName(props, tool.agentId), 14)
43 const elapsed = brief(props.now - tool.startedAt)
44 return spread(ui, `tools:running:${tool.id}`, line(ui, `tools:running:${tool.id}:label`, [
45 { text: tool.approval === 'asked' ? '? ' : '▸ ', color: outcomeColor(tool) },
46 { text: clip(toolLabel(tool), width - actor.length - elapsed.length - 6), bold: true },
47 ]), [
48 { text: `${actor} `, color: colors.magenta },
49 { text: elapsed, color: tool.approval === 'asked' ? colors.yellow : colors.cyan },
50 ])
51 }),
52 running.some(tool => tool.approval === 'asked') ? muted(ui, 'tools:running:approval', '? asked for approval: the time includes the prompt.') : null,
53 ])
54}
55
56const statsSection = (ui: CockpitElements, props: CockpitViewProps, tools: readonly CockpitTool[], width: number): RenderElement | null => {
57 const stats = toolStats(tools, props.now)
58 if (stats.length === 0) return null
59 const nameWidth = Math.min(16, Math.max(8, ...stats.map(stat => stat.tool.length)))
60 const fixed = nameWidth + 6 + 5 + 7
61 const barWidth = Math.max(0, width - fixed - 1)
62 // A subagent's run would dwarf every tool, so Agent calls get no bar.
63 const longest = Math.max(1, ...stats.filter(stat => stat.tool !== 'Agent').map(stat => stat.totalMs))
64 return section(ui, 'tools:stats', [
65 heading(ui, 'tools:stats:title', 'By tool', [{ text: 'where the time goes', color: colors.muted }], width),
66 line(ui, 'tools:stats:columns', [{ text: `${padEnd('', nameWidth)}${padStart('calls', 6)}${padStart('fail', 5)}${padStart('time', 7)}`, color: colors.muted }]),
67 ...stats.slice(0, 8).map(stat => line(ui, `tools:stat:${stat.tool}`, [
68 { text: padEnd(clip(stat.tool, nameWidth), nameWidth), color: stat.tool === 'Agent' ? colors.magenta : undefined },
69 { text: padStart(`${stat.calls}`, 6), color: colors.muted },
70 { text: padStart(stat.failures > 0 ? `${stat.failures}` : '·', 5), color: stat.failures > 0 ? colors.red : colors.muted },
71 { text: padStart(brief(stat.totalMs), 7) },
72 { text: barWidth > 0 && stat.tool !== 'Agent' ? ` ${bar(Math.min(1, stat.totalMs / longest), barWidth)}` : '', color: colors.cyan },
73 ])),
74 stats.length > 8 ? muted(ui, 'tools:stats:more', `${stats.length - 8} more tools`) : null,
75 ])
76}
77
78const filterRow = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
79 const { Box, Button } = ui
80 const agents = props.activity.agents
81 if (agents.length === 0) return null
82 const setFilter = async (id: string | null): Promise<void> => {
83 await props.actions.selectAgent(id)
84 await props.actions.selectTool(null)
85 }
86 const index = agents.findIndex(agent => agent.id === props.activity.selectedAgent)
87 const shown = visibleWindow(agents, index, 3)
88 return (
89 <Box key="tools:filters" flexDirection="row" flexWrap="wrap" columnGap={2}>
90 <Button key="tools:filter:all" plain dimColor={props.activity.selectedAgent !== null} label={`${props.activity.selectedAgent === null ? '● ' : ''}All`} onPress={() => setFilter(null)} />
91 {shown.map(agent => (
92 <Button key={`tools:filter:${agent.id}`} plain dimColor={agent.id !== props.activity.selectedAgent}
93 label={`${agent.id === props.activity.selectedAgent ? '● ' : ''}${clip(agentName(agent), Math.min(18, width - 8))}`}
94 onPress={() => setFilter(agent.id)} />
95 ))}
96 {agents.length > shown.length && <Button key="tools:filter:next" plain dimColor label="more ›" onPress={() => {
97 const next = agents[index < 0 ? 0 : neighboringIndex(agents.length, index, 1)]
98 return next ? setFilter(next.id) : Promise.resolve()
99 }} />}
100 </Box>
101 )
102}
103
104const recentSection = (
105 ui: CockpitElements, props: CockpitViewProps, filtered: readonly CockpitTool[], selected: CockpitTool | undefined, width: number,
106): RenderElement => {
107 const { Box, Button, Text } = ui
108 const selectedIndex = Math.max(0, filtered.findIndex(tool => tool.id === selected?.id))
109 const visible = visibleWindow(filtered, selectedIndex, Math.min(12, listLimit(props)))
110 const showActor = props.activity.selectedAgent === null
111 const chooseNeighbor = (direction: number): Promise<void> => {
112 const next = filtered[neighboringIndex(filtered.length, selectedIndex, direction)]
113 return next ? props.actions.selectTool(next.id) : Promise.resolve()
114 }
115 return section(ui, 'tools:recent', [
116 heading(ui, 'tools:recent:title', 'Calls', [
117 { text: props.activity.selectedAgent === null ? 'all actors' : clip(actorName(props, props.activity.selectedAgent), 24), color: colors.magenta },
118 { text: ' · newest first', color: colors.muted },
119 ], width),
120 filterRow(ui, props, width),
121 filtered.length === 0 ? muted(ui, 'tools:recent:empty', 'No tool calls for this filter yet.') : null,
122 ...visible.map(tool => {
123 const elapsed = toolDuration(tool, props.now)
124 const actor = showActor && tool.agentId ? clip(actorName(props, tool.agentId), 10) : ''
125 const right: Segment[] = [
126 { text: actor ? `${actor} ` : '', color: colors.magenta },
127 { text: padStart(elapsed === undefined ? '?' : brief(elapsed), 5), color: tool.outcome === 'running' ? colors.cyan : colors.muted },
128 { text: padStart(tool.outcome === 'running' ? '' : ago(props.now, tool.startedAt).replace(' ago', ''), 5), color: colors.muted },
129 ]
130 const rightWidth = right.reduce((total, segment) => total + [...segment.text].length, 0)
131 return spread(ui, `tools:row:${tool.id}`, (
132 <Box flexDirection="row">
133 <Text color={tool.id === selected?.id ? colors.accent : colors.muted}>{tool.id === selected?.id ? '› ' : ' '}</Text>
134 <Text color={outcomeColor(tool)}>{statusGlyph(tool.outcome)} </Text>
135 <Text color={colors.yellow}>{tool.approval === 'asked' ? '? ' : ''}</Text>
136 <Button key={`tools:select:${tool.id}`} plain label={clip(toolLabel(tool), Math.max(8, width - rightWidth - 6))} onPress={() => props.actions.selectTool(tool.id)} />
137 </Box>
138 ), right)
139 }),
140 filtered.length > visible.length ? muted(ui, 'tools:recent:more', `Showing ${visible.length} of ${filtered.length}.`) : null,
141 filtered.length > 1 ? actions(ui, 'tools:recent:actions', [
142 { key: 'tools:prev', label: 'Newer', hotkey: 'k', onPress: () => chooseNeighbor(-1) },
143 { key: 'tools:next', label: 'Older', hotkey: 'j', onPress: () => chooseNeighbor(1) },
144 ]) : null,
145 ])
146}
147
148const toolDetail = (ui: CockpitElements, props: CockpitViewProps, tool: CockpitTool, width: number): RenderElement => {
149 const elapsed = toolDuration(tool, props.now)
150 const inner = width - 4
151 return card(ui, `tools:detail:${tool.id}`, [
152 spread(ui, 'tools:detail:title', line(ui, 'tools:detail:name', [
153 { text: `${statusGlyph(tool.outcome)} `, color: outcomeColor(tool) },
154 { text: clip(tool.tool, inner - 14), bold: true },
155 ]), [{ text: tool.outcome, color: outcomeColor(tool) }]),
156 field(ui, 'tools:detail:actor', 'Actor', [{ text: actorName(props, tool.agentId), color: tool.agentId ? colors.magenta : undefined }]),
157 tool.target ? field(ui, 'tools:detail:target', 'Target', [{ text: clip(tool.target, 240) }]) : null,
158 field(ui, 'tools:detail:started', 'Started', [{ text: ago(props.now, tool.startedAt) }]),
159 field(ui, 'tools:detail:time', tool.outcome === 'running' ? 'Elapsed' : 'Took', [
160 { text: elapsed === undefined ? 'unknown' : duration(elapsed) },
161 ]),
162 tool.approval === 'asked' ? field(ui, 'tools:detail:asked', 'Approval', [
163 { text: 'asked', color: colors.yellow }, { text: ' · the time includes the prompt', color: colors.muted },
164 ]) : null,
165 tool.retrospective ? muted(ui, 'tools:detail:server', 'Server tool, reported after the response.') : null,
166 ])
167}
168
169const backgroundColor = (task: CockpitBackgroundTask) =>
170 task.endedAt !== undefined ? colors.muted : statusColor(task.status === 'pending' ? 'pending' : 'running')
171
172const backgroundSection = (ui: CockpitElements, props: CockpitViewProps, width: number): RenderElement | null => {
173 const tasks = props.activity.background
174 const crons = props.activity.crons
175 if (tasks.length === 0 && crons.length === 0) return null
176 const live = tasks.filter(task => task.endedAt === undefined)
177 // In-flight work first, then the most recently ended.
178 const shown = [...live, ...tasks.filter(task => task.endedAt !== undefined).reverse()].slice(0, 6)
179 return section(ui, 'tools:background', [
180 heading(ui, 'tools:background:title', 'Background', [
181 { text: `${live.length} running`, color: live.length > 0 ? colors.cyan : colors.muted },
182 ], width),
183 ...shown.map(task => {
184 const time = task.startedAt === undefined ? '' : brief((task.endedAt ?? props.now) - task.startedAt)
185 const right: Segment[] = [
186 { text: `${clip(task.type.replace(/^local_/, ''), 10)} `, color: colors.muted },
187 { text: padStart(time, 4), color: colors.muted },
188 ]
189 return spread(ui, `tools:background:${task.id}`, line(ui, `tools:background:${task.id}:label`, [
190 { text: task.endedAt === undefined ? '● ' : '○ ', color: backgroundColor(task) },
191 { text: clip(task.description, width - 20), color: task.endedAt === undefined ? undefined : colors.muted },
192 { text: task.endedAt === undefined ? '' : ` · ${task.status}`, color: colors.muted },
193 ]), right)
194 }),
195 tasks.length > shown.length ? muted(ui, 'tools:background:more', `${tasks.length - shown.length} more`) : null,
196 ...crons.slice(0, 4).map(cron => line(ui, `tools:cron:${cron.id}`, [
197 { text: '⏲ ', color: colors.accent }, { text: cron.schedule },
198 { text: cron.dueAt !== undefined ? ` · ${cron.dueAt > props.now ? `in ${brief(cron.dueAt - props.now)}` : 'due'}` : cron.recurring ? ' · recurring' : ' · once', color: colors.muted },
199 ])),
200 ])
201}
202
203export const renderTools = (ui: CockpitElements, props: CockpitViewProps): RenderElement => {
204 const { Box } = ui
205 const width = viewWidth(props)
206 const wide = width >= 100
207 const left = wide ? Math.floor((width - 2) * 0.55) : width
208 const right = wide ? width - left - 2 : width
209 const all = props.activity.tools.slice().sort((a, b) => b.startedAt - a.startedAt)
210 const filtered = props.activity.selectedAgent === null ? all : all.filter(tool => tool.agentId === props.activity.selectedAgent)
211 const selected = filtered.find(tool => tool.id === props.activity.selectedTool) ?? filtered[0]
212 const scope = props.activity.selectedAgent === null ? all : filtered
213 const main = [
214 summary(ui, props, scope, left),
215 runningSection(ui, props, left),
216 recentSection(ui, props, filtered, selected, left),
217 ]
218 const side = [
219 selected ? toolDetail(ui, props, selected, right) : null,
220 statsSection(ui, props, scope, right),
221 backgroundSection(ui, props, right),
222 ]
223 const keep = (items: (RenderElement | null)[]) => items.filter((item): item is RenderElement => Boolean(item))
224 return wide ? (
225 <Box flexDirection="row" gap={2} width="100%" alignItems="flex-start">
226 <Box flexDirection="column" gap={1} width={left} flexShrink={0}>{keep(main)}</Box>
227 <Box flexDirection="column" gap={1} width={right} flexShrink={0}>{keep(side)}</Box>
228 </Box>
229 ) : (
230 <Box flexDirection="column" gap={1} width="100%">
231 {keep([...main, ...side])}
232 </Box>
233 )
234}
235
236types/index.d.ts 341 lines1export type CockpitView = 'agents' | 'tools' | 'changes' | 'context' | 'activity'
2
3/** How much time the activity timeline spans: from the first event, or a fixed window. */
4export type CockpitSpan = 'fit' | '5m' | '15m' | '60m'
5
6export type CockpitTokenUsage = {
7 input_tokens: number
8 output_tokens: number
9 cache_read_input_tokens: number
10 cache_creation_input_tokens: number
11}
12
13export type CockpitTurnUsage = CockpitTokenUsage & { model: string }
14
15export type CockpitBreakdown = {
16 categories: {
17 name: string
18 tokens: number
19 color: string
20 isDeferred: boolean
21 kind: 'used' | 'free' | 'buffer' | 'deferred'
22 }[]
23 totalTokens: number
24 maxTokens: number
25 rawMaxTokens: number
26 autocompactSource: 'env' | 'settings' | 'clientdata' | 'experiment' | 'model-default' | 'unknown-model' | 'auto'
27 percentage: number
28 gridRows: {
29 color: string
30 isFilled: boolean
31 categoryName: string
32 tokens: number
33 percentage: number
34 squareFullness: number
35 }[][]
36 model: string
37 memoryFiles: { path: string; type: string; tokens: number }[]
38 mcpTools: { name: string; serverName: string; tokens: number; isLoaded: boolean }[]
39 agents: { agentType: string; source: string; tokens: number }[]
40 slashCommands?: { totalCommands: number; includedCommands: number; tokens: number }
41 skills?: {
42 totalSkills: number
43 includedSkills: number
44 tokens: number
45 skillFrontmatter: { name: string; source: string; pluginName?: string; tokens: number }[]
46 }
47 autoCompactThreshold?: number
48 isAutoCompactEnabled: boolean
49 apiUsage: CockpitTokenUsage | null
50}
51
52export type CockpitUsage = {
53 startedAt: number
54 context: { window: number; tokens?: number; percent?: number; breakdown?: CockpitBreakdown }
55 rateLimits: { kind: string; percentUsed: number; resetsAt?: string }[]
56 cost?: { usd: number }
57}
58
59export type CockpitTool = {
60 id: string
61 tool: string
62 agentId?: string
63 target?: string
64 startedAt: number
65 finishedAt?: number
66 outcome: 'running' | 'success' | 'error' | 'denied' | 'interrupted'
67 retrospective?: boolean
68 /** The permission check put the call to the mode's decider (a dialog, a classifier). */
69 approval?: 'asked'
70}
71
72export type CockpitAgentTotals = {
73 tokens: number
74 toolUses: number
75 durationMs: number
76 linesAdded?: number
77 linesRemoved?: number
78 models: string[]
79}
80
81export type CockpitAgent = {
82 id: string
83 name?: string
84 description: string
85 type: string
86 status: 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed' | 'missing'
87 parentId?: string
88 teammateId?: string
89 spawnedBy?: string
90 /** When the roster or a tool result first reported the agent. */
91 startedAt?: number
92 lastSeenAt: number
93 completedAt?: number
94 durationMs?: number
95 usage?: CockpitTurnUsage
96 totals?: CockpitAgentTotals
97 answer?: string
98}
99
100export type CockpitTodo = {
101 content: string
102 status: 'pending' | 'in_progress' | 'completed'
103 activeForm: string
104}
105
106/** One loop's TodoWrite list; `agentId` is absent for the main session. */
107export type CockpitTodoList = {
108 agentId?: string
109 items: CockpitTodo[]
110 updatedAt: number
111}
112
113export type CockpitTask = {
114 id: string
115 subject: string
116 status: 'pending' | 'in_progress' | 'completed'
117 owner?: string
118}
119
120export type CockpitBackgroundTask = {
121 id: string
122 type: string
123 status: string
124 description: string
125 startedAt?: number
126 endedAt?: number
127 updatedAt: number
128}
129
130export type CockpitCron = {
131 id: string
132 schedule: string
133 recurring: boolean
134 /** A hash of a one-shot cron's prompt. Its firing names the cron by this prompt alone. */
135 promptKey?: string
136 /** When a /loop wakeup fires. */
137 dueAt?: number
138}
139
140/** A change in the activity level: running tools + running agents + main turn. */
141export type CockpitSample = {
142 at: number
143 level: number
144}
145
146export type CockpitStopFailure = {
147 error: string
148 details?: string
149 at: number
150}
151
152export type CockpitTurn = {
153 id: string
154 agentId?: string
155 durationMs: number
156 reason: string
157 finishedAt: number
158 usage?: CockpitTurnUsage
159}
160
161export type CockpitActivity = {
162 sessionId: string | null
163 model: string
164 working: boolean
165 /** When the main turn in progress started; null between turns. */
166 turnStartedAt: number | null
167 phase: 'idle' | 'thinking' | 'tools' | 'error'
168 tools: CockpitTool[]
169 agents: CockpitAgent[]
170 turns: CockpitTurn[]
171 samples: CockpitSample[]
172 todos: CockpitTodoList[]
173 tasks: CockpitTask[]
174 background: CockpitBackgroundTask[]
175 crons: CockpitCron[]
176 stopFailure: CockpitStopFailure | null
177 selectedAgent: string | null
178 /** The agent in view when the person last chose; a later view change is followed. */
179 selectedFor: string | null
180 selectedTool: string | null
181 updatedAt: number
182 error: string | null
183}
184
185export type CockpitChangeState = 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'conflict'
186
187export type CockpitChange = {
188 path: string
189 patch: string
190 additions: number
191 deletions: number
192 source: 'observed' | 'git'
193 /** The Git status of the file; absent for an edit before the next Git read. */
194 state?: CockpitChangeState
195 staged?: boolean
196 untracked?: boolean
197 /** How many observed edits changed the file, and which agent made the last one. */
198 edits?: number
199 agentId?: string
200 updatedAt: number
201 truncated?: boolean
202}
203
204export type CockpitFinding = {
205 id: string
206 path: string
207 line?: number
208 summary: string
209 category?: string
210 verdict?: string
211 outcome?: string
212}
213
214export type CockpitCheck = {
215 id: string
216 label: string
217 status: 'running' | 'completed' | 'passed' | 'failed' | 'interrupted' | 'denied'
218 passed?: number
219 failed?: number
220 durationMs?: number
221 finishedAt?: number
222}
223
224/** A Bash call's `gitOperation`: what the engine detected the command did. */
225export type CockpitGitOperation = {
226 id: string
227 at: number
228 commit?: { sha: string; kind: string; branch?: string }
229 push?: { branch: string }
230 branch?: { ref: string; action: string }
231 pr?: { number: number; url?: string; action: string }
232}
233
234export type CockpitReview = {
235 sessionId: string | null
236 changes: CockpitChange[]
237 findings: CockpitFinding[]
238 checks: CockpitCheck[]
239 gitOps: CockpitGitOperation[]
240 selectedPath: string | null
241 branch: string | null
242 root: string | null
243 refreshedAt: number | null
244 loading: boolean
245 error: string | null
246}
247
248export type CockpitCompaction = {
249 at: number
250 trigger: string
251 agentId?: string
252 tokensBefore?: number
253 tokensAfter?: number
254 skipped?: string
255}
256
257/** The session cost total each time it grew, about once per main turn. */
258export type CockpitCostSample = {
259 at: number
260 usd: number
261}
262
263/** The live context fill each time a measurement moved it. */
264export type CockpitFillSample = {
265 at: number
266 tokens: number
267}
268
269export type CockpitContext = {
270 sessionId: string | null
271 usage: CockpitUsage | null
272 compactions: CockpitCompaction[]
273 costs: CockpitCostSample[]
274 fills: CockpitFillSample[]
275 refreshedAt: number | null
276 loading: boolean
277 error: string | null
278}
279
280export type CockpitPreferences = {
281 view: CockpitView
282 band: boolean
283 animation: boolean
284 span: CockpitSpan
285 paneOpen: boolean
286}
287
288/** The Bongo Cat's animation frame and the phase it acts out. */
289export type CockpitMascot = {
290 frame: number
291 phase: CockpitActivity['phase']
292}
293
294/** The band spinner's frame. Only the band reads it, so a new frame redraws only the band. */
295export type CockpitPulse = {
296 frame: number
297}
298
299export type CockpitActions = {
300 selectView: (view: CockpitView) => Promise<void>
301 refreshAgents: () => Promise<void>
302 selectAgent: (id: string | null) => Promise<void>
303 selectTool: (id: string | null) => Promise<void>
304 refreshChanges: () => Promise<void>
305 selectChange: (path: string) => Promise<void>
306 /** Copies the path relative to the repository root, as the file list shows it. */
307 copyPath: (path: string) => Promise<void>
308 copyPatch: (path: string) => Promise<void>
309 quotePatch: (path: string) => Promise<void>
310 refreshContext: () => Promise<void>
311 toggleAnimation: () => Promise<void>
312 cycleSpan: () => Promise<void>
313}
314
315export type CockpitViewProps = {
316 activity: CockpitActivity
317 review: CockpitReview
318 context: CockpitContext
319 preferences: CockpitPreferences
320 mascot: CockpitMascot
321 actions: CockpitActions
322 /** The agent whose transcript is beside the pane; null for the main session. */
323 viewedAgent: string | null
324 columns: number
325 rows: number
326 now: number
327}
328
329declare module 'claude-code' {
330 interface PluginState {
331 cockpit: {
332 activity: CockpitActivity
333 review: CockpitReview
334 context: CockpitContext
335 preferences: CockpitPreferences
336 mascot: CockpitMascot
337 pulse: CockpitPulse
338 }
339 }
340}
341