Flightdeck: a live agent dashboard for Claude Code. Main model vitals, an on-call architect, every permission check, subagent cards and swimlanes, a turn…

A Claude Code mod that puts a live agent dashboard in your terminal: context and cost, an advisor timeline, every permission check, and your subagents as cards or swimlanes. Every number comes from a real session event, and nothing leaves your machine.
<img src="docs/media/demo.gif" alt="Flightdeck during a live session: five audit subagents fan out as cards, switch to swimlanes and finish, while the permission gate fills with checks" width="520">
<a href="#install">Install</a> · <a href="#what-you-see">What you see</a> · <a href="#what-it-can-reach">What it can reach</a> · <a href="#configure">Configure</a> · <a href="#troubleshooting">Troubleshooting</a> · <a href="CHANGELOG.md">What's new</a>
Inside Claude Code (2.1.287 or later):
/plugin marketplace add scasella/claude-flightdeck
/plugin install flightdeck@claude-flightdeck
/reload-plugins
/flightdeck
claude plugin marketplace add scasella/claude-flightdeck
claude plugin install flightdeck@claude-flightdeck
Or load it straight from a clone, for one session:
git clone https://github.com/scasella/claude-flightdeck
claude --plugin-dir ./claude-flightdeck
The installer may say config options aren't set; the defaults are fine, and /config changes them.
Mods are an early-access Claude Code feature and their API can change between releases. If something breaks, see Troubleshooting.
https://github.com/user-attachments/assets/9ad0fcc3-c81c-427a-a743-f7b6c49f5885
<img src="docs/media/docked-session.png" alt="Claude Code in fullscreen with the Flightdeck pane docked beside the transcript" width="820">
| Docked beside the transcript | Inline above the prompt |
|---|---|
| <img src="docs/media/docked-pane.png" alt="The docked pane: main model vitals, architect timeline, permission gate, five agents as swimlanes, last-turn receipt and session log" width="380"> | <img src="docs/media/inline-mini.png" alt="The inline mini layout: the model, context gauge, session cost and architect consults; the permission gate strip and totals; the last turn's duration, agents, edits, errors and cost" width="420"><br><br>On the main screen, without fullscreen, the pane is a summary of at most 8 rows; up to 3 agents join it when the session has subagents. |
| Panel | Shows | From |
|---|---|---|
| main | model, effort, permission mode, request count; a context gauge with compactions (⟲), measured against the compaction window when the session compacts in a smaller one than the model's (autoCompactWindow, or Claude Code's own); cost and the first two rate-limit windows when your plan reports them, with the time to each reset (↻) from 56 columns; the last main-loop request's time to first token | turn.step, session.measure, session.compact, $.session.usage() (its local summary breakdown, once per model, for the compaction window) |
| architect | consults on a timeline, whether one is running, how long the last took; optionally the moment of each consult; the first line of a subagent architect's advice | a spawn of a matching agent type, or a matching server tool in the assistant's rows |
| gate | one cell per permission check: green allowed without asking, blue decided by the auto-mode classifier or you and then run, amber pending, red ✗ denied, dim if made inside a subagent. Totals, and a drill-down per tool family with credentials masked | tool.check, settled by the tool.call around it |
| agents | cards side by side while they fit: the task, type, live context and output tokens, steps, a running clock, max_tokens in red. Beyond that, swimlanes on one time axis | agent.spawn, turn.step, tool.call, turn.complete |
| loops | model loops that match no card: workflow agents, compactions, memory forks | turn.step ids no card claims |
| receipt | the running turn, or the last one: duration, agents, edits, errors, cost added | turn.start, turn.complete |
| log | prompts, spawns, completions, consults, edits, errors and denials; filtered to one agent while you view its transcript | all of the above |
Connectors animate only while work flows: a turn is running, an agent is running, or a consult is open. Panels with nothing to show take no room, so a session without subagents shows just the main box and the log.
| Command | Does | |||
|---|---|---|---|---|
/flightdeck | open the pane | |||
/flightdeck close | close it | |||
/flightdeck reset | clear agents, checks, consults, log and the turn (cost, rate limits and compactions stay) | |||
| `/flightdeck layout auto\ | compact\ | wide\ | mini` | override the layout for this session |
Focus the pane with ctrl+x tab, then:
| Key | Does |
|---|---|
1, 2, … | expand an agent card or lane: its full task, last 3 tool calls, start of its answer |
f s o | open the gate's file / shell / other drill-down: the last 5 checks and their verdicts |
/clear resets the pane along with the conversation.
With openOnStart, the pane opens by itself when a session starts, in terminals at least 144 columns wide; below that, /flightdeck opens it. Colours come from your Claude Code theme, so light, dark and colour-blind themes all read.
Flightdeck only watches. Every hook passes its event on unchanged: it never denies, rewrites or delays a tool call, a prompt or a subagent.
| It sees | Through |
|---|---|
| every tool call's name and input, and whether it failed | tool.call |
| every permission verdict | tool.check |
| subagent spawns, their model requests and token usage, and their final answers | agent.spawn, turn.step, turn.complete |
| your prompts' first 70 characters, for the log | turn.start |
| context, cost and rate-limit readings | session.measure, $.session.usage() |
the context breakdown /context shows (its categories, memory-file paths, MCP tools, agents and skills), estimated locally once per model; it keeps only the compaction window from it | $.session.usage({ breakdown: 'summary' }) |
| advisor tool calls in the assistant's responses (their content is encrypted) | session.append |
What it keeps: short summaries (a tool name plus a path or command, with credentials masked) in session state, which ends with the session. It makes no network requests, runs no processes, reads and writes no files, stores nothing across sessions, and calls no model. claude plugin validate . prints exactly what it hooks and calls.
(inferred); turn them off with moments: false.advisor, the pane counts and times the consult but cannot show what it said.ctx, not cost: the API has no per-agent cost.tokens/window and the status line's ctx N% measure against that window, so they read higher than Claude Code's own status-line percentage (and claude-hud's), which measure against the model's window. Auto-compaction runs a little before 100%, at its threshold inside that window.ttft is timed at Flightdeck's own turn.step hook, so it includes everything beneath it: other plugins' hooks, the engine, the network and any retry. When the model's thinking isn't streamed, the first piece arrives after it, so ttft includes the thinking. Measured, not inferred, but not the API's own figure. There is no output rate: the reported tokens include thinking, so a rate over the visible stream isn't a real speed.In /config, or under pluginConfigs[<id>].options in your user settings.json, where <id> is how Claude Code loaded the plugin: flightdeck@claude-flightdeck when installed from the marketplace, flightdeck (or flightdeck@inline) with --plugin-dir. An entry under another key, or in project settings (.claude/settings.json), is ignored without a warning. From a terminal, claude plugin configure flightdeck@claude-flightdeck lists the options and which are unset, and saves them with --values-stdin.
| Option | Default | Meaning | |
|---|---|---|---|
architectPattern | `advisor\ | architect` | case-insensitive regex for agent types and server tools that count as the architect |
matchDescriptions | false | also match agent descriptions, not just type names | |
architectLabel | ARCHITECT | the architect's name in the pane | |
gateLabel | GATE | the permission panel's name | |
panels | main,architect,gate,agents,loops,receipt,log | which panels show, in order | |
layout | auto | mini, compact, wide, or auto (mini inline, wide from 110 columns docked) | |
maxCards | 3 | cards side by side before swimlanes (1–6); fewer if the pane is too narrow | |
paneColumns | 66 | columns the docked pane asks for, 40 or more. Claude Code caps the dock at 45% of the terminal, and a width you dragged it to, in this session or an earlier one, wins. The wide layout starts at 110, so it needs a terminal of about 245 columns, or layout: wide | |
motion | while-active | off keeps connectors still | |
moments | true | show the inferred consult moments | |
palette | theme | pastel uses fixed colours tuned for dark terminals | |
openOnStart | true | ask to open the pane when a session starts | |
statusLine | true | context, running agents, consults and denials in the status line |
The pane doesn't appear.
claude --version is 2.1.287 or later, then run /reload-plugins and /flightdeck./flightdeck opens it at any width.flightdeck:. It names the hook that failed or the reason the pane was refused. Please open an issue with it.draw failed (…), its drawing hook threw; include that line in the issue too.Nothing shows in the VS Code extension. In one report its 2.1.296 build ran Flightdeck's hooks but showed no pane, and none for another mod either (#5). Run claude in VS Code's integrated terminal instead, then /flightdeck: an integrated terminal is usually narrower than the 144 columns the pane needs to open by itself.
Options seem ignored. Check the key in your user settings.json: pluginConfigs["flightdeck@claude-flightdeck"] when installed, pluginConfigs["flightdeck"] with --plugin-dir. See Configure.
Colours look wrong. Set palette to pastel in /config.
It's too much motion. Set motion to off.
Counters look stale after an update. Run /flightdeck reset.
| File | Holds |
|---|---|
hooks/register.tsx | the event hooks, state access, and one function per panel |
hooks/core.ts | every reducer, formatter and layout rule as pure functions, so behaviour is testable directly |
hooks/rail.tsx, hooks/elapsed.tsx | surface modules: animated connectors and live clocks that redraw only themselves, on the surface's own frame clock |
types/index.d.ts | the state contract |
tests/ | 50 tests: pure behaviour, plus drawings mounted on every surface at 24–120 columns, with every width from 24 to 40 checked for anything that spills past its box |
State lives in $.state atoms. Every read is merged over defaults, so a missing or older field never breaks the pane; an update that changes the state's shape may still reset its counters once. New to mods? Start with Claude Code mods and Getting started with Claude Code mods.
Flightdeck works alongside these, and owes ideas to them:
claude --plugin-dir . # load it; edits hot-reload
claude plugin validate .
claude plugin test .
npx -p typescript tsc -p . # after the first load, which writes .claude-plugin/types/
See CONTRIBUTING.md. Changes are listed in CHANGELOG.md.
hooks/register.tsx 1361 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { AgentCard, Architect, Bucket, Check, Gate, Layout, LogLine, Loop, Main, Roster, Turn, Usage, View } from '../types'
5import {
6 DEFAULT_ARCHITECT,
7 addCard,
8 resumeCard,
9 DEFAULT_GATE,
10 DEFAULT_MAIN,
11 DEFAULT_ROSTER,
12 DEFAULT_TURN,
13 DEFAULT_USAGE,
14 DEFAULT_VIEW,
15 EDIT_TOOLS,
16 SCHEMA_VERSION,
17 afterCall,
18 applyStep,
19 bucketOf,
20 cellWidth,
21 piecesThatFit,
22 cardTitle,
23 afterCompactRead,
24 claimCompactRead,
25 contextFill,
26 faultKey,
27 forgetCompactRead,
28 titleLines,
29 consultTimeline,
30 describeInput,
31 endConsult,
32 fitLegend,
33 fmtClock,
34 fmtDuration,
35 fmtTimer,
36 fmtUsd,
37 plural,
38 gateSummary,
39 gauge,
40 isAdvising,
41 isLoopActive,
42 kTokens,
43 lanes,
44 limitLabel,
45 limitOf,
46 fmtResetIn,
47 fmtSpeed,
48 listOf,
49 logRows,
50 marksIn,
51 momentOf,
52 normalize,
53 normalizeCard,
54 normalizeGate,
55 normalizeLog,
56 noteTool,
57 PALETTES,
58 SVG_COLORS,
59 parseConfig,
60 prettyModel,
61 promptLine,
62 handbackOf,
63 adviceLine,
64 receiptOf,
65 recordCheck,
66 settleCheck,
67 shorten,
68 startConsult,
69 stepSpeed,
70 stepLoop,
71} from './core'
72import type { Config, Panel } from './core'
73
74const PANE = 'flightdeck'
75const TITLE = 'Flightdeck'
76
77
78// ---------------------------------------------------------------- state
79
80const meta = atom({ plugin: 'flightdeck', key: 'meta' } as const, { schemaVersion: SCHEMA_VERSION })
81const main = atom({ plugin: 'flightdeck', key: 'main' } as const, DEFAULT_MAIN)
82const usage = atom({ plugin: 'flightdeck', key: 'usage' } as const, DEFAULT_USAGE)
83const architect = atom({ plugin: 'flightdeck', key: 'architect' } as const, DEFAULT_ARCHITECT)
84const gate = atom({ plugin: 'flightdeck', key: 'gate' } as const, DEFAULT_GATE)
85const agents = atom({ plugin: 'flightdeck', key: 'agents' } as const, [])
86const loops = atom({ plugin: 'flightdeck', key: 'loops' } as const, [])
87const log = atom({ plugin: 'flightdeck', key: 'log' } as const, [])
88const turn = atom({ plugin: 'flightdeck', key: 'turn' } as const, DEFAULT_TURN)
89const receipt = atom({ plugin: 'flightdeck', key: 'receipt' } as const, null)
90const view = atom({ plugin: 'flightdeck', key: 'view' } as const, DEFAULT_VIEW)
91const roster = atom({ plugin: 'flightdeck', key: 'roster' } as const, DEFAULT_ROSTER)
92
93type ServerBlock = { type: string; id?: string; name?: string; tool_use_id?: string }
94
95// Every read goes through these, so a value saved under an older shape still reads.
96async function getMain($: EngineInterface): Promise<Main> {
97 return normalize(DEFAULT_MAIN, await read($, main))
98}
99async function getUsage($: EngineInterface): Promise<Usage> {
100 return normalize(DEFAULT_USAGE, await read($, usage))
101}
102async function getArchitect($: EngineInterface): Promise<Architect> {
103 const a = normalize(DEFAULT_ARCHITECT, await read($, architect))
104 return { ...a, consults: listOf(a.consults), ids: listOf(a.ids), seen: listOf(a.seen) }
105}
106async function getGate($: EngineInterface): Promise<Gate> {
107 return normalizeGate(await read($, gate))
108}
109async function getCards($: EngineInterface): Promise<AgentCard[]> {
110 return listOf<unknown>(await read($, agents)).map(normalizeCard)
111}
112async function getLoops($: EngineInterface): Promise<Loop[]> {
113 return listOf<Loop>(await read($, loops))
114}
115async function getLog($: EngineInterface): Promise<LogLine[]> {
116 return normalizeLog(await read($, log))
117}
118async function getTurn($: EngineInterface): Promise<Turn> {
119 return normalize(DEFAULT_TURN, await read($, turn))
120}
121async function getView($: EngineInterface): Promise<View> {
122 return normalize(DEFAULT_VIEW, await read($, view))
123}
124async function getRoster($: EngineInterface): Promise<Roster> {
125 const r = normalize(DEFAULT_ROSTER, await read($, roster))
126 return { architectTypes: listOf(r.architectTypes) }
127}
128
129/** A stored shape older than this build's: drop what cannot be read, keep the rest. */
130async function migrate($: EngineInterface) {
131 const m = await read($, meta)
132 if ((m?.schemaVersion ?? 0) >= SCHEMA_VERSION) return
133 await update($, log, list => normalizeLog(list))
134 await update($, agents, list => listOf<unknown>(list).map(normalizeCard))
135 await update($, gate, g => normalizeGate(g))
136 await update($, meta, () => ({ schemaVersion: SCHEMA_VERSION }))
137}
138
139async function say($: EngineInterface, who: string, text: string, kind: LogLine['kind'] = 'info', agentId: string | null = null) {
140 const line: LogLine = { at: await $.clock.now(), who, text, kind, agentId }
141 await update($, log, list => [...normalizeLog(list), line].slice(-60))
142}
143
144async function refreshStatus($: EngineInterface, cfg: Config) {
145 if (!cfg.statusLine) return $.ui.status(undefined)
146 const [u, a, g, cards] = await Promise.all([getUsage($), getArchitect($), getGate($), getCards($)])
147 const running = cards.filter(c => c.status === 'running').length
148 const s = gateSummary(g)
149 const ctxFill = contextFill(u)
150 const parts = [
151 ctxFill.pct !== null ? `ctx ${Math.round(ctxFill.pct)}%` : null,
152 cards.length > 0 ? `agents ${running}/${cards.length}` : null,
153 a.consults.length > 0 || a.ids.length > 0 ? `${cfg.architectLabel.toLowerCase()} ${isAdvising(a) ? 'advising' : a.consults.length}` : null,
154 s.deny > 0 ? `denied ${s.deny}` : null,
155 ]
156 // Only fields with something to say; with none, no status entry at all.
157 const shown = parts.filter(Boolean)
158 $.ui.status(shown.length > 0 ? shown.join(' · ') : undefined)
159}
160
161async function whoIs($: EngineInterface, agentId: string | undefined) {
162 if (!agentId) return 'main'
163 const card = (await getCards($)).find(c => c.id === agentId)
164 return card ? shorten(cardTitle(card), 14) : 'agent'
165}
166
167async function consultStarted($: EngineInterface, cfg: Config, id: string, via: string) {
168 const t = await getTurn($)
169 const moment = momentOf(t)
170 const at = await $.clock.now()
171 await update($, architect, a => startConsult(normalize(DEFAULT_ARCHITECT, a), { id, at, moment, via }))
172 if (moment === 'before done') await update($, turn, x => ({ ...normalize(DEFAULT_TURN, x), isReviewing: true }))
173 await say($, cfg.architectLabel.toLowerCase(), cfg.moments ? `${moment} · ${via}` : `consulted · ${via}`, 'consult')
174 await refreshStatus($, cfg)
175}
176
177async function consultEnded($: EngineInterface, cfg: Config, advice: string | null, id?: string) {
178 const at = await $.clock.now()
179 const first = advice?.split('\n').find(l => l.trim()) ?? null
180 const text = first ? shorten(first.replace(/^[#>*\s-]+/, ''), 160) : null
181 await update($, architect, a => endConsult(normalize(DEFAULT_ARCHITECT, a), at, text, id))
182 await update($, turn, t => ({ ...normalize(DEFAULT_TURN, t), isReviewing: false }))
183 await say($, cfg.architectLabel.toLowerCase(), text ? `advice: ${shorten(text, 60)}` : 'advice returned', 'consult')
184 await refreshStatus($, cfg)
185}
186
187async function noteAdvice($: EngineInterface, cfg: Config, advice: string) {
188 await update($, architect, x => ({ ...normalize(DEFAULT_ARCHITECT, x), lastAdvice: advice }))
189 await say($, cfg.architectLabel.toLowerCase(), `advice: ${shorten(advice, 60)}`, 'consult')
190}
191
192async function isArchitectType($: EngineInterface, cfg: Config, type: string) {
193 return cfg.architect.test(type) || (await getRoster($)).architectTypes.includes(type)
194}
195
196async function openPane($: EngineInterface, cfg: Config) {
197 // columns apply when docked beside the transcript, rows when seated inline above the prompt.
198 return $.ui.open({ id: PANE, title: TITLE, columns: cfg.paneColumns, rows: 8 })
199}
200
201async function resetAll($: EngineInterface) {
202 await update($, main, m => ({ ...DEFAULT_MAIN, model: normalize(DEFAULT_MAIN, m).model, mode: normalize(DEFAULT_MAIN, m).mode }))
203 await update($, architect, () => DEFAULT_ARCHITECT)
204 await update($, gate, () => DEFAULT_GATE)
205 await update($, agents, () => [])
206 await update($, loops, () => [])
207 await update($, log, () => [])
208 await update($, turn, () => DEFAULT_TURN)
209 await update($, receipt, () => null)
210 await update($, view, () => DEFAULT_VIEW)
211 // The context gauge waits for the next measurement rather than showing the pre-clear fill.
212 await update($, usage, x => ({ ...normalize(DEFAULT_USAGE, x), pct: null, tokens: null }))
213}
214
215/**
216 * Stores the compaction window for the model window `window`. A `summary` breakdown estimates locally
217 * and sends no request; until the host gives one, the gauge stays on the model's window (afterCompactRead).
218 */
219async function readCompactWindow($: EngineInterface, window: number) {
220 const r = await $.session.usage({ breakdown: 'summary' }).catch(() => null)
221 await update($, usage, x => afterCompactRead(normalize(DEFAULT_USAGE, x), window, r?.context.breakdown))
222}
223
224/** The session's cost read fresh, not from the last measurement: the receipt subtracts two of these. */
225async function costNow($: EngineInterface): Promise<number | null> {
226 const u = await $.session.usage().catch(() => null)
227 return u?.cost?.usd ?? null
228}
229
230async function noteMode($: EngineInterface, mode: string | undefined) {
231 if (mode) await update($, main, m => (normalize(DEFAULT_MAIN, m).mode === mode ? normalize(DEFAULT_MAIN, m) : { ...normalize(DEFAULT_MAIN, m), mode }))
232}
233
234// ---------------------------------------------------------------- hooks
235
236export const register: Register = (on, options) => {
237 const cfg = parseConfig(options)
238 const C = PALETTES[cfg.palette]
239 // tool.check carries no loop id; the tool.call around it does, keyed by the call's id.
240 const callLoop = new Map<string, string | null>()
241
242 on('session.start', async ($, e, next) => {
243 await $.command.register({
244 name: 'flightdeck',
245 description: 'Flightdeck, the live agent dashboard: open, close, reset, or set the layout',
246 argumentHint: '[open|close|reset|layout auto|compact|wide|mini]',
247 })
248 await migrate($)
249 // A host without usage (headless, an SDK host, a session not yet bound) just starts without it.
250 const u = await $.session.usage().catch(() => null)
251 // A resumed session has a fill to draw already: its compaction window is read now, not at its first
252 // measurement. Any other start forgets the last reading (the setting may have changed) for that one to read.
253 const resumedWindow = u && u.context.tokens !== undefined && u.context.window > 0 ? u.context.window : 0
254 if (u) {
255 await update($, usage, x => ({
256 ...normalize(DEFAULT_USAGE, x),
257 pct: u.context.percent ?? null,
258 tokens: u.context.tokens ?? null,
259 window: u.context.window,
260 compactFor: resumedWindow,
261 compactMisses: 0,
262 costUsd: u.cost?.usd ?? null,
263 limits: u.rateLimits.map(limitOf),
264 }))
265 }
266 if (cfg.openOnStart) void openPane($, cfg).catch(() => undefined)
267 await refreshStatus($, cfg)
268 const done = await next(e)
269 if (resumedWindow > 0) {
270 await readCompactWindow($, resumedWindow)
271 await refreshStatus($, cfg)
272 }
273 return done
274 })
275
276 on('session.end', async ($, e, next) => {
277 if (e.reason === 'clear') {
278 await resetAll($)
279 await refreshStatus($, cfg)
280 }
281 return next(e)
282 })
283
284 on('command.run', { command: 'flightdeck' }, async ($, e) => {
285 const [verb = 'open', arg = ''] = e.args.trim().split(/\s+/)
286 if (verb === 'close') {
287 await $.ui.close({ id: PANE })
288 return { text: 'Flightdeck closed.' }
289 }
290 if (verb === 'reset') {
291 await resetAll($)
292 await refreshStatus($, cfg)
293 return { text: 'Flightdeck reset.' }
294 }
295 if (verb === 'layout') {
296 const layout: Layout | null = arg === 'compact' || arg === 'wide' || arg === 'auto' || arg === 'mini' ? arg : null
297 if (!layout) return { text: 'Usage: /flightdeck layout auto|compact|wide|mini' }
298 await update($, view, v => ({ ...normalize(DEFAULT_VIEW, v), layout }))
299 const opened = await openPane($, cfg)
300 return { text: opened.isPlaced ? `Flightdeck layout: ${layout}.` : `Layout set to ${layout}; the pane is not shown yet: ${opened.reason}` }
301 }
302 const opened = await openPane($, cfg)
303 if (!opened.isPlaced) return { text: `Flightdeck is not shown yet: ${opened.reason}` }
304 return { text: 'Flightdeck opened. Focus it with ctrl+x tab; 1-6 expand cards, f/s/o open the gate rows.' }
305 })
306
307 on('classic.UserPromptSubmit', async ($, e, next) => {
308 await noteMode($, e.permission_mode)
309 return next(e)
310 })
311
312 on('agent.offer', async ($, e, next) => {
313 const offered = await next(e)
314 if (cfg.architect.test(e.agent) || (cfg.matchDescriptions && cfg.architect.test(e.description))) {
315 await update($, roster, r => {
316 const x = normalize(DEFAULT_ROSTER, r)
317 return x.architectTypes.includes(e.agent) ? x : { architectTypes: [...listOf<string>(x.architectTypes), e.agent].slice(-20) }
318 })
319 }
320 return offered
321 })
322
323 on('turn.start', async ($, e, next) => {
324 // A subagent's turn (its spawn, or a resume by SendMessage) is its card's, not the main turn's.
325 if (e.agentId !== undefined) return next(e)
326 const [now, cost] = await Promise.all([$.clock.now(), costNow($)])
327 await update($, turn, () => ({ ...DEFAULT_TURN, startedAt: now, costAtStart: cost }))
328 await update($, main, m => ({ ...normalize(DEFAULT_MAIN, m), isRunning: true }))
329 // A background architect's report reaches the main loop as the text opening this turn. The
330 // SubagentHandback tool call (in tool.call) normally carries it first; this is the fallback.
331 const back = e.text ? handbackOf(e.text) : null
332 const a = back ? await getArchitect($) : null
333 if (back && a && a.ids.includes(back.from)) {
334 const advice = adviceLine(back.body)
335 if (advice && advice !== a.lastAdvice) await noteAdvice($, cfg, advice)
336 } else if (e.text) {
337 const p = promptLine(e.text)
338 await say($, p.who, p.text)
339 }
340 return next(e)
341 })
342
343 on('turn.step', async function* ($, e, next) {
344 // The main loop's model is known when its request starts; a long first request shouldn't read "—".
345 if (!e.agentId) {
346 let isNewModel = false
347 await update($, main, m => {
348 const x = normalize(DEFAULT_MAIN, m)
349 isNewModel = x.model !== '' && x.model !== e.model
350 return { ...x, model: e.model, effort: String(e.effort ?? x.effort), steps: x.steps + 1 }
351 })
352 if (isNewModel) await update($, usage, x => forgetCompactRead(normalize(DEFAULT_USAGE, x)))
353 // Time the response as it passes: its first piece that is neither the engine's envelope nor the
354 // stop. One clock read in the stream and nothing stored until it has ended.
355 const sentAt = await $.clock.now()
356 let firstAt: number | null = null
357 const s = next(e)
358 for await (const c of s) {
359 if (firstAt === null && c.kind !== 'engine' && c.kind !== 'stop') firstAt = await $.clock.now()
360 yield c
361 }
362 const result = await s.result
363 const speed = result.usage ? stepSpeed(sentAt, firstAt) : null
364 if (speed) await update($, main, m => ({ ...normalize(DEFAULT_MAIN, m), speed }))
365 return result
366 }
367 const id = e.agentId
368 // A step from an agent whose card finished means it was resumed (SendMessage): it runs again.
369 const before = (await getCards($)).find(c => c.id === id)
370 if (before && before.status !== 'running') {
371 // Flipped in the write: a resume its agent.spawn already logged is not logged again.
372 let isResumed = false
373 await update($, agents, list =>
374 listOf<unknown>(list)
375 .map(normalizeCard)
376 .map(c => {
377 if (c.id !== id || c.status === 'running') return c
378 isResumed = true
379 return resumeCard(c)
380 }),
381 )
382 if (isResumed) {
383 await say($, await whoIs($, id), 'resumed', 'info', id)
384 await refreshStatus($, cfg)
385 }
386 }
387 const result = yield* next(e)
388 const [cards, a] = await Promise.all([getCards($), getArchitect($)])
389 if (cards.some(c => c.id === id)) {
390 const step = { model: e.model, usage: result.usage, stopReason: result.stopReason }
391 await update($, agents, list => listOf<unknown>(list).map(normalizeCard).map(c => (c.id === id ? applyStep(c, step) : c)))
392 if (result.stopReason === 'max_tokens') await say($, await whoIs($, id), 'hit max_tokens', 'error', id)
393 } else if (!a.ids.includes(id)) {
394 const now = await $.clock.now()
395 await update($, loops, l => stepLoop(listOf<Loop>(l), id, now))
396 }
397 return result
398 })
399
400 on('session.measure', async ($, e, next) => {
401 // The compaction window is read once per model window, not on every measurement (a breakdown
402 // estimates every category each time): claimed here, in the same write, so no two reads overlap.
403 let isStale = false
404 await update($, usage, x => {
405 const claim = claimCompactRead(normalize(DEFAULT_USAGE, x), e.context.window)
406 isStale = claim.isClaimed
407 return {
408 ...claim.usage,
409 pct: e.context.percent ?? null,
410 tokens: e.context.tokens ?? null,
411 window: e.context.window,
412 costUsd: e.cost?.usd ?? null,
413 limits: e.rateLimits.map(limitOf),
414 }
415 })
416 if (e.changed.includes('context')) await refreshStatus($, cfg)
417 const done = await next(e)
418 if (isStale) {
419 await readCompactWindow($, e.context.window)
420 await refreshStatus($, cfg)
421 }
422 return done
423 })
424
425 on('session.compact', async ($, e, next) => {
426 const done = await next(e)
427 if (!e.agentId && e.trigger !== 'precompute') {
428 const now = await $.clock.now()
429 await update($, usage, x => {
430 const u = normalize(DEFAULT_USAGE, x)
431 return { ...u, compactions: u.compactions + 1, lastCompactAt: now }
432 })
433 await say($, 'main', `context compacted (${e.trigger})`)
434 }
435 return done
436 })
437
438 on('tool.check', async ($, e, next) => {
439 const verdict = await next(e)
440 if (e.tool_use_id) {
441 const check: Check = {
442 id: e.tool_use_id,
443 tool: e.tool,
444 bucket: bucketOf(e.tool),
445 verdict: verdict.decision === 'allow' ? 'rule' : verdict.decision,
446 inSubagent: Boolean(callLoop.get(e.tool_use_id)),
447 detail: shorten(describeInput(e.tool, e.input), 90),
448 at: await $.clock.now(),
449 }
450 await update($, gate, g => recordCheck(normalizeGate(g), check))
451 // The status line updates when the call settles; only a refusal ends here.
452 if (verdict.decision === 'deny') {
453 await say($, 'gate', `denied by rule · ${check.detail}`, 'error')
454 await refreshStatus($, cfg)
455 }
456 }
457 return verdict
458 })
459
460 on('tool.call', async ($, e, next) => {
461 callLoop.set(e.tool_use_id, e.agentId ?? null)
462 const ran = await next(e).finally(() => callLoop.delete(e.tool_use_id))
463 const didRun = ran.deny === undefined
464 // Settle this call's pending ask, if it had one; skip the write (and the redraw) otherwise.
465 const g0 = await getGate($)
466 const isSettled = settleCheck(g0, e.tool_use_id, didRun) !== g0
467 if (isSettled) await update($, gate, g => settleCheck(normalizeGate(g), e.tool_use_id, didRun))
468 // A background agent hands its report back through this tool; an architect's report is its advice.
469 if (String(e.tool) === 'SubagentHandback') {
470 const message = (e as unknown as { message?: unknown }).message
471 const a = e.agentId ? await getArchitect($) : null
472 if (a && e.agentId && a.ids.includes(e.agentId) && typeof message === 'string') {
473 const advice = adviceLine(message)
474 if (advice && advice !== a.lastAdvice) await noteAdvice($, cfg, advice)
475 }
476 return ran
477 }
478 if (e.tool === 'Agent') {
479 if (isSettled) await refreshStatus($, cfg)
480 return ran
481 }
482 const hasFailed = didRun && ran.isError === true
483 const isEdit = !hasFailed && didRun && EDIT_TOOLS.has(e.tool)
484 const t0 = await getTurn($)
485 if (isEdit || hasFailed || (!e.agentId && t0.errorStreak > 0)) {
486 await update($, turn, t => afterCall(normalize(DEFAULT_TURN, t), { inSubagent: Boolean(e.agentId), hasFailed, isEdit }))
487 }
488 const text = shorten(describeInput(e.tool, e), 64)
489 if (e.agentId) {
490 const id = e.agentId
491 await update($, agents, list =>
492 listOf<unknown>(list)
493 .map(normalizeCard)
494 .map(c => (c.id === id ? noteTool(c, { tool: e.tool, text, isError: hasFailed || ran.deny !== undefined }) : c)),
495 )
496 }
497 // The log keeps what is worth a glance: refusals, errors and edits; the rest is on the cards.
498 if (ran.deny !== undefined) await say($, await whoIs($, e.agentId), `${text} denied`, 'error', e.agentId ?? null)
499 else if (hasFailed) await say($, await whoIs($, e.agentId), `${text} ✗`, 'error', e.agentId ?? null)
500 else if (isEdit) await say($, await whoIs($, e.agentId), text, 'info', e.agentId ?? null)
501 if (isSettled || !didRun) await refreshStatus($, cfg)
502 return ran
503 })
504
505 // A server-side review tool never reaches tool.call: it shows only in the assistant's rows.
506 on('session.append', async ($, e, next) => {
507 if (!e.agentId && e.message.type === 'assistant') {
508 const a = await getArchitect($)
509 // Consults this row opened: their result may be in the same row, after the stale read above.
510 const opened = new Set<string>()
511 for (const block of e.message.content as unknown as readonly ServerBlock[]) {
512 if (block.type === 'server_tool_use' && block.name && block.id && cfg.architect.test(block.name)) {
513 if (a.seen.includes(block.id)) continue
514 const id = block.id
515 await update($, architect, x => {
516 const y = normalize(DEFAULT_ARCHITECT, x)
517 return { ...y, seen: [...listOf<string>(y.seen), id].slice(-60) }
518 })
519 opened.add(id)
520 await consultStarted($, cfg, id, `${block.name} tool`)
521 } else if (block.type.endsWith('_tool_result') && block.tool_use_id) {
522 const id = block.tool_use_id
523 const isOpen = opened.has(id) || (await getArchitect($)).consults.some(c => c.id === id && c.endAt === null)
524 if (isOpen) await consultEnded($, cfg, null, id)
525 }
526 }
527 }
528 return next(e)
529 })
530
531 on('agent.spawn', async ($, e, next) => {
532 const started = await next(e)
533 if (!e.parentAgentId) await noteMode($, e.permissionMode)
534 if (started.deny !== undefined || !started.agentId) return started
535 const id = started.agentId
536 if (await isArchitectType($, cfg, e.subagentType)) {
537 await update($, architect, a => {
538 const x = normalize(DEFAULT_ARCHITECT, a)
539 return { ...x, ids: [...listOf<string>(x.ids), id].slice(-40) }
540 })
541 await update($, loops, l => listOf<Loop>(l).filter(x => x.id !== id))
542 await consultStarted($, cfg, id, e.subagentType.split(':').pop() ?? 'agent')
543 return started
544 }
545 const card: AgentCard = {
546 ...normalizeCard({}),
547 id,
548 type: e.name ?? e.subagentType,
549 model: started.model,
550 description: e.description,
551 spawnedAt: await $.clock.now(),
552 }
553 // Decided in the write: a resume whose first step already put its card back to running is not logged again.
554 let isNew = true
555 let isResumed = false
556 await update($, agents, list => {
557 const cards = listOf<unknown>(list).map(normalizeCard)
558 const known = cards.find(c => c.id === id)
559 isNew = known === undefined
560 isResumed = known !== undefined && known.status !== 'running'
561 return addCard(cards, card)
562 })
563 await update($, loops, l => listOf<Loop>(l).filter(x => x.id !== id))
564 if (isNew || isResumed) await say($, shorten(cardTitle(card), 12), isNew ? `spawned · ${card.type}` : 'resumed', 'info', id)
565 await refreshStatus($, cfg)
566 return started
567 })
568
569 on('turn.complete', async ($, e, next) => {
570 const done = await next(e)
571 const id = e.agentId
572 const now = await $.clock.now()
573 if (!id) {
574 const [t, cards, cost] = await Promise.all([getTurn($), getCards($), costNow($)])
575 const r = receiptOf(t, {
576 durationMs: e.durationMs,
577 agentsSince: cards.filter(c => c.spawnedAt >= t.startedAt).length,
578 costNow: cost,
579 reason: e.reason,
580 })
581 await update($, receipt, () => r)
582 await update($, main, m => ({ ...normalize(DEFAULT_MAIN, m), isRunning: false }))
583 await refreshStatus($, cfg)
584 return done
585 }
586 if ((await getArchitect($)).ids.includes(id)) {
587 await consultEnded($, cfg, e.answer, id)
588 return done
589 }
590 const cards = await getCards($)
591 if (cards.some(c => c.id === id)) {
592 const status = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'stopped' : 'failed'
593 await update($, agents, list =>
594 listOf<unknown>(list)
595 .map(normalizeCard)
596 .map(c => (c.id === id ? { ...c, status, endedAt: now, answer: shorten(e.answer, 400) } : c)),
597 )
598 // This run's own length: a resumed agent's card clock also spans the idle time between runs.
599 const took = fmtDuration(e.durationMs)
600 await say($, await whoIs($, id), status === 'done' ? `done · ${took}` : status, status === 'done' ? 'done' : 'error', id)
601 } else {
602 await update($, loops, l => listOf<Loop>(l).map(x => (x.id === id ? { ...x, isDone: true, lastAt: now } : x)))
603 }
604 await refreshStatus($, cfg)
605 return done
606 })
607
608 // ---------------------------------------------------------------- drawing
609
610 // After a surface module faults on a surface, this load draws it there as plain text; the other
611 // module, and other surfaces, keep theirs. Keyed by faultKey: `desktop:rail.tsx`.
612 const faulted = new Set<string>()
613 on('ui.fault', async ($, e, next) => {
614 const key = faultKey(e.surface, e.module)
615 if (e.requestId === PANE && !faulted.has(key)) {
616 faulted.add(key)
617 $.ui.log(`flightdeck: ${e.module} faulted on ${e.surface} (${e.phase}: ${e.reason}); drawing it without animation`)
618 $.ui.invalidate('ui.render')
619 }
620 return next(e)
621 })
622
623 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
624 const els = $.ui.resolve(e)
625 const { Box, Text, Button } = els
626 const hasClient = 'Client' in els
627 const hasRail = hasClient && !faulted.has(faultKey(e.surface, 'rail.tsx'))
628 const hasClock = hasClient && !faulted.has(faultKey(e.surface, 'elapsed.tsx'))
629 const [m, u, a, g, cards, lp, lines, t, r, v, now] = await Promise.all([
630 getMain($),
631 getUsage($),
632 getArchitect($),
633 getGate($),
634 getCards($),
635 getLoops($),
636 getLog($),
637 getTurn($),
638 read($, receipt),
639 getView($),
640 $.clock.now(),
641 ])
642 // The body's own width, down to the narrowest dock Claude Code seats (24): a wider drawing is cut off at the frame.
643 const W = Math.max(24, e.props.bodyColumns)
644 const layout = v.layout ?? cfg.layout
645 const isWide = layout === 'wide' || (layout === 'auto' && W >= 110)
646 const colW = isWide ? Math.floor((W - 2) / 2) : W
647 const modelName = prettyModel(m.model)
648 const viewed = e.props.view?.agentId ?? null
649 const advising = isAdvising(a)
650 const running = cards.filter(c => c.status === 'running')
651 const showArchitect = a.consults.length > 0 || a.ids.length > 0
652 const motion = cfg.motion && hasRail
653 // A panel with nothing to show yet takes no room: most sessions never spawn an agent.
654 const isEmpty: Record<Panel, boolean> = {
655 main: false,
656 architect: !showArchitect,
657 gate: g.recent.length === 0 && gateSummary(g).total === 0,
658 agents: cards.length === 0,
659 loops: lp.length === 0,
660 receipt: !m.isRunning && !r,
661 log: false,
662 }
663 const panels = cfg.panels.filter(p => !isEmpty[p])
664 const decider = m.mode === 'auto' ? 'classifier' : 'you'
665
666 // A connector between panels: animated while its flow is live, a dim line otherwise.
667 const rail = (key: string, active: boolean, color: string, width: number, marks: number[] = [], isMerge = false) =>
668 motion ? (
669 <els.Client
670 key={key}
671 module="./rail.tsx"
672 width={width}
673 height={1}
674 props={{ active, width, color, dim: C.faint, marks, isMerge }}
675 />
676 ) : (
677 <Text color={C.faint} mono>
678 {'─'.repeat(Math.max(1, width))}
679 </Text>
680 )
681
682 // A start time of 0 is unknown (state saved before it was recorded): no clock, not decades.
683 const clock = (key: string, since: number, endAt: number | null, color: string) =>
684 since <= 0 ? (
685 <Text color={color}>—</Text>
686 ) : hasClock ? (
687 <els.Client key={key} module="./elapsed.tsx" props={{ since, now, endAt, color }} />
688 ) : (
689 <Text color={color}>{fmtTimer((endAt ?? now) - since)}</Text>
690 )
691
692 const isTerminal = e.surface === 'terminal'
693 // A row of marks (gate checks, loop dots), sized by `marksIn`. Should a surface draw them wider
694 // still, the row is cut at its box rather than running past it.
695 const markRow = (marks: RenderChildren, lead = 0) => (
696 <Box overflow="hidden" {...(lead ? { marginLeft: lead } : {})}>
697 <Text wrap="truncate-start">{marks}</Text>
698 </Box>
699 )
700 // A terminal's border row stands apart from the text above it; a graphical surface draws the
701 // border flush against it, so the legend keeps one row of air there.
702 const legendGap = isTerminal ? 0 : 1
703
704 // A line of coloured pieces, drawn as a row of boxes the way the log draws its lines. A Text nesting
705 // coloured Texts truncates as one line in a terminal, but the desktop app wraps each nested piece on its
706 // own, lays truncating ones out as blocks of their own, and collapses runs of spaces. So pieces sit `gap`
707 // cells apart (a piece's `lead` adds more), each keeps its width, and pieces that don't fit in `room` are
708 // left out from the end; or a piece marked `fill` (one span) truncates to what the others leave.
709 type Span = { text: string; color?: string; dim?: boolean; bold?: boolean }
710 type Piece = { spans: Span[]; lead?: number; fill?: boolean }
711 const styleOf = (s: Span) => ({ ...(s.color ? { color: s.color } : {}), ...(s.dim ? { dimColor: true } : {}), ...(s.bold ? { bold: true } : {}) })
712 const widthOf = (p: Piece) => p.spans.reduce((n, s) => n + cellWidth(s.text), 0)
713 const line = (pieces: (Piece | null)[], room: number, gap = 1, justify?: 'center') => {
714 const all = pieces.filter((p): p is Piece => p !== null)
715 const shown = all.some(p => p.fill) ? all : all.slice(0, piecesThatFit(all.map(p => ({ width: widthOf(p), lead: p.lead })), room, gap))
716 return (
717 <Box width={room} columnGap={gap} overflow="hidden" {...(justify ? { justifyContent: justify } : {})}>
718 {shown.map(p => {
719 const lead = p.lead ? { marginLeft: p.lead } : {}
720 if (p.fill && p.spans[0]) {
721 return (
722 <Text {...styleOf(p.spans[0])} wrap="truncate">
723 {p.spans[0].text}
724 </Text>
725 )
726 }
727 return (
728 <Box flexShrink={0} {...lead}>
729 {p.spans.length === 1 && p.spans[0] ? <Text {...styleOf(p.spans[0])}>{p.spans[0].text}</Text> : <Text>{p.spans.map(s => <Text {...styleOf(s)}>{s.text}</Text>)}</Text>}
730 </Box>
731 )
732 })}
733 </Box>
734 )
735 }
736
737 // ---- main
738 const effortN = { low: 1, medium: 2, high: 3, xhigh: 4, max: 4 }[m.effort] ?? 0
739 const ctxFill = contextFill(u)
740 const ctxGauge = ctxFill.pct !== null ? gauge(ctxFill.pct, 10) : null
741 const mainPanel = (w: number) => (
742 <Box flexDirection="column" borderStyle="round" borderColor={C.main} paddingX={1} width={w}>
743 <Box justifyContent="space-between">
744 <Text color={C.main} bold wrap="truncate">
745 {modelName} · main
746 </Text>
747 <Box flexShrink={0}>
748 <Text color={m.isRunning ? C.main : C.dim}>{m.isRunning ? '● working' : '○ idle'}</Text>
749 </Box>
750 </Box>
751 {line(
752 [
753 {
754 spans: [
755 { text: 'effort ', dim: true },
756 { text: `${'▮'.repeat(effortN) + '▯'.repeat(4 - effortN)} `, color: C.main },
757 { text: m.effort || '—', color: C.main, bold: true },
758 ],
759 },
760 m.mode ? { spans: [{ text: `mode ${m.mode}`, dim: true }] } : null,
761 { spans: [{ text: `${m.steps} req`, dim: true }] },
762 ],
763 w - 4,
764 3,
765 )}
766 {ctxGauge
767 ? line(
768 [
769 {
770 spans: [
771 { text: 'ctx ', dim: true },
772 { text: ctxGauge.on, color: ctxFill.pct !== null && ctxFill.pct >= 80 ? C.warn : C.main },
773 { text: ctxGauge.off, color: C.faint },
774 { text: ` ${Math.round(ctxFill.pct ?? 0)}%`, bold: true },
775 ],
776 },
777 u.tokens !== null ? { spans: [{ text: `${kTokens(u.tokens)}/${kTokens(ctxFill.window)}`, dim: true }] } : null,
778 u.compactions > 0 ? { spans: [{ text: `⟲${u.compactions}`, color: C.amber }], lead: 1 } : null,
779 ],
780 w - 4,
781 )
782 : null}
783 {u.costUsd !== null || u.limits.length > 0
784 ? line(
785 [
786 u.costUsd !== null ? { spans: [{ text: fmtUsd(u.costUsd), color: C.text }] } : null,
787 ...u.limits.slice(0, 2).map((l, i): Piece => {
788 const lg = gauge(l.pct, 5)
789 // The time to each reset where the line has room for it: both windows fit from 56 columns,
790 // so a wide pane's half column (59 at 120) has them; a window that doesn't fit is left out.
791 const resetIn = w >= 56 ? fmtResetIn(l.resetsAt, now) : ''
792 return {
793 lead: i > 0 ? 1 : u.costUsd !== null ? 2 : 0,
794 spans: [
795 { text: `${limitLabel(l.kind)} `, dim: true },
796 { text: lg.on, color: l.pct >= 80 ? C.warn : C.main },
797 { text: lg.off, color: C.faint },
798 { text: ` ${Math.round(l.pct)}%${resetIn ? ` ↻${resetIn}` : ''}`, dim: true },
799 ],
800 }
801 }),
802 ],
803 w - 4,
804 )
805 : null}
806 {m.speed ? <Text dimColor wrap="truncate">{`last req ${fmtSpeed(m.speed)}`}</Text> : null}
807 </Box>
808 )
809
810 // ---- architect
811 const lastConsult = a.consults[a.consults.length - 1]
812 const architectPanel = (w: number) => {
813 // Both ends are anchors (the first consult, now): should it run past its box, it asks to lose the middle.
814 const tl = consultTimeline(a, now, Math.max(8, w - 4))
815 return (
816 <Box flexDirection="column" borderStyle="round" borderColor={C.arch} paddingX={1} width={w}>
817 <Box justifyContent="space-between">
818 <Text color={C.arch} bold wrap="truncate">
819 {cfg.architectLabel} · {advising ? 'advising' : 'on call'}
820 </Text>
821 <Box flexShrink={0}>
822 <Text>
823 <Text dimColor>consults </Text>
824 <Text color={C.arch} bold>
825 {a.consults.length}
826 </Text>
827 </Text>
828 </Box>
829 </Box>
830 <Text color={C.arch} wrap="truncate-middle">
831 {tl}
832 </Text>
833 {lastConsult ? (
834 <Text dimColor wrap="truncate">
835 {advising
836 ? `consulting since ${fmtClock(lastConsult.at)}`
837 : `last ${fmtDuration(now - (lastConsult.endAt ?? lastConsult.at))} ago · took ${fmtDuration((lastConsult.endAt ?? now) - lastConsult.at)}`}
838 </Text>
839 ) : (
840 <Text dimColor>not consulted yet</Text>
841 )}
842 {cfg.moments ? (
843 <Box flexWrap="wrap" columnGap={2}>
844 {(['before a plan', 'error repeats', 'before done'] as const).map(mo => {
845 const isOn = lastConsult?.moment === mo
846 return (
847 <Text color={isOn ? C.arch : C.dim} bold={isOn}>
848 {isOn ? '◆' : '◇'} {mo}
849 </Text>
850 )
851 })}
852 <Text color={C.faint}>(inferred)</Text>
853 </Box>
854 ) : null}
855 {a.lastAdvice ? (
856 <Text color={C.arch} wrap="truncate">
857 » {a.lastAdvice}
858 </Text>
859 ) : null}
860 </Box>
861 )
862 }
863
864 // ---- gate
865 const s = gateSummary(g)
866 const verdictColor = (c: Check) =>
867 c.verdict === 'rule' ? C.gate : c.verdict === 'cleared' ? C.cleared : c.verdict === 'ask' ? C.amber : C.warn
868 const checkMark = (c: Check) => (
869 <Text color={verdictColor(c)} dimColor={c.inSubagent}>
870 {c.verdict === 'deny' ? '✗' : '■'}
871 </Text>
872 )
873 const gatePanel = (w: number) => {
874 const strip = g.recent.slice(-Math.max(8, marksIn(w - 4, isTerminal)))
875 const open = v.gateOpen
876 // The totals in words where they all fit, in numbers alone where they don't: the colours say which is which.
877 const totalsOf = (isShort: boolean): Piece[] => [
878 { spans: [{ text: '■', color: C.gate }, { text: isShort ? ` ${s.rule}` : ` ${s.rule} allowed`, dim: true }] },
879 { spans: [{ text: '■', color: C.cleared }, { text: isShort ? ` ${s.cleared}` : ` ${s.cleared} ${decider}`, dim: true }] },
880 ...(s.ask > 0 ? [{ spans: [{ text: isShort ? `■ ${s.ask}` : `■ ${s.ask} pending`, color: C.amber }] }] : []),
881 { spans: [{ text: isShort ? `✗ ${s.deny}` : `✗ ${s.deny} denied`, color: s.deny > 0 ? C.warn : C.dim }] },
882 ]
883 const words = totalsOf(false)
884 const isShort = piecesThatFit(words.map(p => ({ width: widthOf(p) })), w - 4, 2) < words.length
885 const totals = isShort ? totalsOf(true) : words
886 return (
887 <Box flexDirection="column" borderStyle="round" borderColor={C.gate} paddingX={1} width={w}>
888 <Box justifyContent="space-between">
889 <Text color={C.gate} bold wrap="truncate">
890 {cfg.gateLabel} · permissions
891 </Text>
892 <Box flexShrink={0}>
893 <Text dimColor>{`${s.total} checks`}</Text>
894 </Box>
895 </Box>
896 {strip.length === 0 ? <Text color={C.faint}>no checks yet</Text> : markRow(strip.map(checkMark))}
897 {line([...totals, !isShort && w >= 80 && g.recent.some(c => c.inSubagent) ? { spans: [{ text: 'dim: in subagents', color: C.faint }] } : null], w - 4, 2)}
898 {/* Below about 44 columns the three rows' buttons take two lines rather than run past the box. */}
899 <Box columnGap={2} flexWrap="wrap">
900 {(['file', 'shell', 'other'] as const).map((b: Bucket) => {
901 const tl = g.totals[b]
902 const n = tl.rule + tl.ask + tl.cleared + tl.deny
903 return (
904 <Button
905 key={`gate-${b}`}
906 plain
907 hotkey={b[0]}
908 label={`${b} ${n}${open === b ? ' ▾' : ''}`}
909 dimColor={n === 0}
910 onPress={() => update($, view, x => ({ ...normalize(DEFAULT_VIEW, x), gateOpen: normalize(DEFAULT_VIEW, x).gateOpen === b ? null : b }))}
911 />
912 )
913 })}
914 </Box>
915 {open
916 ? g.recent
917 .filter(c => c.bucket === open)
918 .slice(-5)
919 .map(c => (
920 // The verdict sits in a box of its own width, not padded with spaces, which a graphical surface collapses.
921 <Box width={w - 4} columnGap={1} overflow="hidden">
922 <Box width={12} flexShrink={0}>
923 <Text>
924 <Text color={verdictColor(c)}>{c.verdict === 'deny' ? '✗ ' : '■ '}</Text>
925 <Text color={C.dim}>{c.verdict === 'rule' ? 'allowed' : c.verdict === 'cleared' ? decider : c.verdict === 'ask' ? 'pending' : 'denied'}</Text>
926 </Text>
927 </Box>
928 <Text dimColor={c.inSubagent} wrap="truncate">
929 {shorten(c.detail, Math.max(10, w - 18))}
930 </Text>
931 </Box>
932 ))
933 : null}
934 </Box>
935 )
936 }
937
938 // ---- agents: cards up to the limit, swimlanes beyond it
939 const statusColor = (c: AgentCard) => (c.status === 'failed' ? C.warn : c.status === 'done' ? C.gate : C.agent)
940 const glyph = (c: AgentCard) => (c.status === 'running' ? '◐' : c.status === 'done' ? '✓' : c.status === 'failed' ? '✗' : '■')
941 const expandOnPress = (id: string) => () =>
942 update($, view, x => ({ ...normalize(DEFAULT_VIEW, x), expanded: normalize(DEFAULT_VIEW, x).expanded === id ? null : id }))
943
944 const agentsPanel = (w: number) => {
945 // Cards need 20 columns each; when the pane can't hold the limit, lanes take over.
946 const fit = Math.max(1, Math.min(cfg.maxCards, Math.floor((w + 1) / 21)))
947 const useLanes = cards.length > fit
948 const isNarrow = w < 40
949 const header = (
950 <Box justifyContent="space-between" width={w}>
951 <Text bold wrap="truncate">
952 {isNarrow ? `agents · ${running.length}/${cards.length}` : `agents · ${running.length} running · ${cards.length} total`}
953 </Text>
954 {cards.length > 0 ? (
955 <Box flexShrink={0}>
956 <Text color={C.faint}>{`1-${Math.min(cards.length, useLanes ? 6 : fit)}${isNarrow ? '' : ' expand'}`}</Text>
957 </Box>
958 ) : null}
959 </Box>
960 )
961 if (cards.length === 0) {
962 return (
963 <Box flexDirection="column" width={w}>
964 {header}
965 <Text color={C.faint}>no subagents yet</Text>
966 </Box>
967 )
968 }
969 if (useLanes) {
970 const shown = cards.slice(-6)
971 // A lane is its glyph, a label, the bar and a clock: below 34 columns the label narrows, below
972 // 36 the bar, so a 24-column pane still holds it. From 40 they are as they always were.
973 const labelW = Math.min(17, Math.max(7, w - 17))
974 const barW = Math.max(4, w - 11 - labelW)
975 const geo = lanes(shown, now, barW)
976 return (
977 <Box flexDirection="column" width={w}>
978 {header}
979 {cards.length > shown.length ? <Text color={C.faint}>{`+${cards.length - shown.length} earlier`}</Text> : null}
980 {shown.map((c, i) => {
981 const gm = geo[i]
982 const isViewed = viewed === c.id
983 return (
984 <Box columnGap={1}>
985 <Text color={statusColor(c)} bold={isViewed}>
986 {isViewed ? '▶' : glyph(c)}
987 </Text>
988 <Box width={labelW} flexShrink={0}>
989 <Button key={`card-${c.id}`} plain hotkey={String(i + 1)} label={shorten(cardTitle(c), labelW - 3)} onPress={expandOnPress(c.id)} />
990 </Box>
991 <Box flexShrink={0}>
992 <Text>
993 <Text color={C.faint}>{'·'.repeat(gm?.before ?? 0)}</Text>
994 <Text color={statusColor(c)}>{'━'.repeat(gm?.bar ?? 1)}</Text>
995 <Text color={C.faint}>{'·'.repeat(gm?.after ?? 0)}</Text>
996 </Text>
997 </Box>
998 {clock(`lane-clock-${c.id}`, c.spawnedAt, c.endedAt, C.dim)}
999 </Box>
1000 )
1001 })}
1002 </Box>
1003 )
1004 }
1005 const shown = cards.slice(-fit)
1006 const cardW = Math.max(20, Math.floor((w - (shown.length - 1)) / shown.length))
1007 const centers = shown.map((_, i) => i * (cardW + 1) + Math.floor(cardW / 2))
1008 return (
1009 <Box flexDirection="column" width={w}>
1010 {header}
1011 {rail('fan-out', running.length > 0, C.agent, w, centers)}
1012 <Box columnGap={1}>
1013 {shown.map((c, i) => {
1014 const isViewed = viewed === c.id
1015 const sameModel = !c.model || prettyModel(c.model) === modelName
1016 return (
1017 <Box
1018 flexDirection="column"
1019 borderStyle={isViewed ? 'double' : 'round'}
1020 borderColor={c.lastStop === 'max_tokens' ? C.warn : C.agent}
1021 borderDimColor={c.status !== 'running' && !isViewed}
1022 width={cardW}
1023 paddingX={1}
1024 >
1025 <Button key={`card-${c.id}`} plain hotkey={String(i + 1)} label={titleLines(cardTitle(c), cardW - 7, cardW - 4)[0]} onPress={expandOnPress(c.id)} />
1026 <Text bold wrap="truncate">
1027 {titleLines(cardTitle(c), cardW - 7, cardW - 4)[1]}
1028 </Text>
1029 <Text color={C.dim} wrap="truncate">
1030 {sameModel ? c.type : `${c.type} · ${prettyModel(c.model)}`}
1031 </Text>
1032 <Text dimColor wrap="truncate">
1033 {c.steps > 0 ? `ctx ${kTokens(c.ctx)} · out ${kTokens(c.out)} · ${c.steps} st` : 'starting…'}
1034 </Text>
1035 <Box columnGap={1}>
1036 <Text color={c.lastStop === 'max_tokens' ? C.warn : statusColor(c)}>
1037 {cardW >= 26 ? `${glyph(c)} ${c.lastStop === 'max_tokens' ? 'max_tokens' : c.status}` : glyph(c)}
1038 </Text>
1039 <Box flexShrink={0}>{clock(`card-clock-${c.id}`, c.spawnedAt, c.endedAt, C.dim)}</Box>
1040 </Box>
1041 </Box>
1042 )
1043 })}
1044 </Box>
1045 {rail('merge', running.length > 0, C.agent, w, centers, true)}
1046 </Box>
1047 )
1048 }
1049
1050 const expandedCard = cards.find(c => c.id === v.expanded)
1051 const expandedPanel = (w: number) =>
1052 expandedCard ? (
1053 <Box flexDirection="column" borderStyle="single" borderColor={C.agent} paddingX={1} width={w}>
1054 <Text bold wrap="wrap">
1055 {expandedCard.description || expandedCard.type}
1056 </Text>
1057 <Text dimColor wrap="truncate">{`${expandedCard.type} · ${prettyModel(expandedCard.model)} · ${expandedCard.status} · ${expandedCard.steps} steps`}</Text>
1058 {expandedCard.tools.length === 0 ? <Text color={C.faint}>no tool calls yet</Text> : null}
1059 {expandedCard.tools.map(n => (
1060 <Text color={n.isError ? C.warn : C.text} wrap="truncate">
1061 {`${n.isError ? '✗' : '·'} ${n.text}`}
1062 </Text>
1063 ))}
1064 {expandedCard.answer ? (
1065 <Text dimColor wrap="wrap">
1066 {`» ${shorten(expandedCard.answer, 240)}`}
1067 </Text>
1068 ) : null}
1069 </Box>
1070 ) : null
1071
1072 // ---- other loops (workflow agents, forks): ids that match no card
1073 const loopsPanel = (w: number) => {
1074 if (lp.length === 0) return null
1075 const active = lp.filter(l => isLoopActive(l, now)).length
1076 const dots = lp.slice(-Math.max(4, marksIn(w - 38, isTerminal)))
1077 const isNarrow = w < 40
1078 return (
1079 <Box width={w} columnGap={1}>
1080 <Text bold>{isNarrow ? 'loops' : 'other loops'}</Text>
1081 <Text dimColor>{isNarrow ? `${lp.length} · ${active} active` : `${lp.length} seen · ${active} active`}</Text>
1082 {markRow(
1083 dots.map(l => (
1084 <Text color={isLoopActive(l, now) ? C.agent : l.isDone ? C.dim : C.faint}>{isLoopActive(l, now) ? '●' : l.isDone ? '✓' : '○'}</Text>
1085 )),
1086 1,
1087 )}
1088 </Box>
1089 )
1090 }
1091
1092 // ---- receipt: the turn now, or the last one
1093 const receiptPanel = (w: number) => {
1094 const isReview = t.isReviewing
1095 return (
1096 <Box flexDirection="column" borderStyle="round" borderColor={C.main} borderDimColor={!m.isRunning && !isReview} paddingX={1} width={w}>
1097 {m.isRunning ? (
1098 <Box width={w - 4} columnGap={1} overflow="hidden">
1099 <Text color={C.main} wrap="truncate">{`◐ back to ${modelName.toLowerCase()} · turn`}</Text>
1100 <Box flexShrink={0}>{clock('turn-clock', t.startedAt, null, C.main)}</Box>
1101 {w >= 60 ? <Text dimColor wrap="truncate">{`· ${plural(t.edits, 'edit')} · ${plural(t.errors, 'error')}`}</Text> : null}
1102 </Box>
1103 ) : r ? (
1104 line(
1105 [
1106 { spans: [{ text: r.reason === 'answer' ? '✓' : '✗', color: r.reason === 'answer' ? C.gate : C.warn }] },
1107 {
1108 spans: [{ text: `last turn ${fmtDuration(r.durationMs)} · ${plural(r.agents, 'agent')} · ${plural(r.edits, 'edit')} · ${plural(r.errors, 'error')}` }],
1109 fill: true,
1110 },
1111 r.costDelta !== null ? { spans: [{ text: `· +${fmtUsd(r.costDelta)}`, color: C.main }] } : null,
1112 ],
1113 w - 4,
1114 )
1115 ) : (
1116 <Text color={C.faint}>no turn finished yet</Text>
1117 )}
1118 {isReview ? (
1119 <Text color={C.arch} wrap="wrap">
1120 {`${cfg.architectLabel.toLowerCase()} reviewing before done (inferred)`}
1121 </Text>
1122 ) : null}
1123 </Box>
1124 )
1125 }
1126
1127 // ---- log: whatever rows the other panels leave, 4 to 8
1128 // The main box's speed line, the legend's gap and the gap above the log are a row each.
1129 const used = 2 + legendGap + 5 + (m.speed ? 1 : 0) + 1 + (showArchitect ? 6 : 0) + 6 + (v.gateOpen ? 5 : 0) + (cards.length > cfg.maxCards ? 3 + Math.min(6, cards.length) : 8) + (expandedCard ? 8 : 0) + (lp.length ? 1 : 0) + 3
1130 const bodyRows = e.props.scroll?.bodyRows ?? e.viewport?.rows ?? 40
1131 const nLog = logRows(bodyRows, used)
1132 const shownLines = (viewed ? lines.filter(l => l.agentId === viewed) : lines).slice(-nLog)
1133 const colorOf = (l: LogLine) =>
1134 l.kind === 'error' ? C.warn : l.kind === 'consult' ? C.arch : l.who === 'main' ? C.main : l.who === 'gate' ? C.gate : l.who === 'you' ? C.text : C.agent
1135 // Below 40 columns a line keeps its minute, not its second, and a shorter name.
1136 const logPanel = (w: number) => (
1137 <Box flexDirection="column" borderStyle="round" borderColor={C.faint} paddingX={1} marginTop={1} width={w}>
1138 <Text dimColor wrap="truncate">
1139 {viewed ? 'session log · this agent' : 'session log'}
1140 </Text>
1141 {shownLines.length === 0 ? <Text color={C.faint}>nothing yet</Text> : null}
1142 {shownLines.map(l => (
1143 <Box>
1144 <Box width={w < 40 ? 6 : 9} flexShrink={0}>
1145 <Text color={C.faint}>{w < 40 ? fmtClock(l.at).slice(0, 5) : fmtClock(l.at)}</Text>
1146 </Box>
1147 <Box width={w < 40 ? 9 : 13} flexShrink={0}>
1148 <Text color={colorOf(l)} bold wrap="truncate">
1149 {l.who}
1150 </Text>
1151 </Box>
1152 <Text color={l.kind === 'error' ? C.warn : C.text} wrap="truncate">
1153 {l.text}
1154 </Text>
1155 </Box>
1156 ))}
1157 </Box>
1158 )
1159
1160 const draw = (p: Panel, w: number) =>
1161 p === 'main'
1162 ? mainPanel(w)
1163 : p === 'architect'
1164 ? architectPanel(w)
1165 : p === 'gate'
1166 ? gatePanel(w)
1167 : p === 'agents'
1168 ? agentsPanel(w)
1169 : p === 'loops'
1170 ? loopsPanel(w)
1171 : p === 'receipt'
1172 ? receiptPanel(w)
1173 : logPanel(w)
1174
1175 // Panels with the flow between them; the agents panel draws its own rails.
1176 const column = (ps: Panel[], w: number) => (
1177 <Box flexDirection="column" width={w}>
1178 {ps.map((p, i) => {
1179 const prev = ps[i - 1]
1180 const link =
1181 i === 0 || p === 'agents' || prev === 'agents' || p === 'log' || p === 'loops' || prev === 'loops'
1182 ? null
1183 : rail(`link-${p}`, p === 'architect' ? advising : m.isRunning, p === 'architect' ? C.arch : C.main, w)
1184 return (
1185 <Box flexDirection="column">
1186 {link}
1187 {draw(p, w)}
1188 {p === 'agents' ? expandedPanel(w) : null}
1189 </Box>
1190 )
1191 })}
1192 </Box>
1193 )
1194
1195 // Desktop draws the agents' time axis as SVG under the panels.
1196 const svgLanes =
1197 e.surface !== 'terminal' && cards.length > 0
1198 ? (() => {
1199 const { Svg } = $.ui.resolve(e)
1200 const rowH = 18hooks/core.ts 612 lines1// Pure data: defaults, reducers, formatting and layout math. Nothing here touches `$`, so every
2// behaviour is testable directly (the test kit cannot raise a subagent's tool call or a
3// permission check inside a call; these functions are what the hooks apply).
4import type {
5 AgentCard,
6 Architect,
7 Bucket,
8 Check,
9 Gate,
10 Layout,
11 LogLine,
12 Loop,
13 Main,
14 Moment,
15 Receipt,
16 Roster,
17 Tally,
18 ToolNote,
19 Turn,
20 Usage,
21 View,
22} from '../types'
23
24export const SCHEMA_VERSION = 2
25
26// ---------------------------------------------------------------- defaults
27
28export const DEFAULT_MAIN: Main = { model: '', effort: '', mode: '', steps: 0, isRunning: false, speed: null }
29export const DEFAULT_USAGE: Usage = {
30 pct: null,
31 tokens: null,
32 window: 0,
33 compactWindow: null,
34 compactFor: 0,
35 compactMisses: 0,
36 costUsd: null,
37 limits: [],
38 compactions: 0,
39 lastCompactAt: null,
40}
41export const DEFAULT_ARCHITECT: Architect = { consults: [], ids: [], seen: [], lastAdvice: '' }
42const ZERO: Tally = { rule: 0, ask: 0, cleared: 0, deny: 0 }
43export const DEFAULT_GATE: Gate = { recent: [], totals: { file: ZERO, shell: ZERO, other: ZERO } }
44export const DEFAULT_TURN: Turn = { edits: 0, errorStreak: 0, errors: 0, isReviewing: false, startedAt: 0, costAtStart: null }
45export const DEFAULT_VIEW: View = { expanded: null, gateOpen: null, layout: null }
46export const DEFAULT_ROSTER: Roster = { architectTypes: [] }
47
48const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
49
50/** A stored object merged over its defaults, so a value saved under an older shape still reads. */
51export const normalize = <T extends object>(def: T, stored: unknown): T =>
52 isObject(stored) ? ({ ...def, ...stored } as T) : def
53
54/** A stored list, or empty when what is stored is not a list. */
55export const listOf = <T>(stored: unknown): T[] => (Array.isArray(stored) ? (stored as T[]) : [])
56
57export const normalizeGate = (stored: unknown): Gate => {
58 const g = normalize(DEFAULT_GATE, stored)
59 const totals = normalize(DEFAULT_GATE.totals, g.totals)
60 return {
61 recent: listOf<Check>(g.recent),
62 totals: { file: normalize(ZERO, totals.file), shell: normalize(ZERO, totals.shell), other: normalize(ZERO, totals.other) },
63 }
64}
65
66export const normalizeCard = (stored: unknown): AgentCard =>
67 normalize<AgentCard>(
68 {
69 id: '',
70 type: 'agent',
71 model: '',
72 description: '',
73 status: 'running',
74 spawnedAt: 0,
75 endedAt: null,
76 ctx: 0,
77 out: 0,
78 steps: 0,
79 lastStop: null,
80 tools: [],
81 answer: '',
82 },
83 stored,
84 )
85
86export const normalizeLog = (stored: unknown): LogLine[] =>
87 listOf<Record<string, unknown>>(stored).map(l => ({
88 at: typeof l.at === 'number' ? l.at : 0,
89 who: String(l.who ?? ''),
90 text: String(l.text ?? ''),
91 agentId: typeof l.agentId === 'string' ? l.agentId : null,
92 kind: l.kind === 'error' || l.kind === 'consult' || l.kind === 'done' ? l.kind : 'info',
93 }))
94
95// ---------------------------------------------------------------- config
96
97export type Panel = 'main' | 'architect' | 'gate' | 'agents' | 'loops' | 'receipt' | 'log'
98const PANELS: readonly Panel[] = ['main', 'architect', 'gate', 'agents', 'loops', 'receipt', 'log']
99
100export type Config = {
101 architect: RegExp
102 architectLabel: string
103 gateLabel: string
104 panels: Panel[]
105 motion: boolean
106 moments: boolean
107 matchDescriptions: boolean
108 maxCards: number
109 paneColumns: number
110 layout: Layout
111 palette: Palette
112 openOnStart: boolean
113 statusLine: boolean
114}
115
116const safeRegExp = (source: string, fallback: string) => {
117 try {
118 return new RegExp(source || fallback, 'i')
119 } catch {
120 return new RegExp(fallback, 'i')
121 }
122}
123
124/** The plugin's `/config` values, read leniently: anything malformed falls back to the default. */
125export const parseConfig = (o: Readonly<Record<string, unknown>>): Config => {
126 const str = (k: string, d: string) => (typeof o[k] === 'string' && o[k] !== '' ? (o[k] as string) : d)
127 const bool = (k: string, d: boolean) => (typeof o[k] === 'boolean' ? (o[k] as boolean) : d)
128 const panels = str('panels', PANELS.join(','))
129 .split(',')
130 .map(s => s.trim())
131 .filter((p): p is Panel => (PANELS as readonly string[]).includes(p))
132 const layout = str('layout', 'auto')
133 const max = typeof o.maxCards === 'number' ? Math.round(o.maxCards) : 3
134 const cols = typeof o.paneColumns === 'number' && Number.isFinite(o.paneColumns) ? Math.round(o.paneColumns) : 66
135 return {
136 architect: safeRegExp(str('architectPattern', ''), 'advisor|architect'),
137 architectLabel: str('architectLabel', 'ARCHITECT'),
138 gateLabel: str('gateLabel', 'GATE'),
139 panels: panels.length > 0 ? [...new Set(panels)] : [...PANELS],
140 motion: str('motion', 'while-active') !== 'off',
141 moments: bool('moments', true),
142 matchDescriptions: bool('matchDescriptions', false),
143 maxCards: Math.min(6, Math.max(1, max)),
144 // The body clamps its drawing at 40 columns, so a narrower dock would only clip it.
145 paneColumns: Math.max(40, cols),
146 layout: layout === 'compact' || layout === 'wide' || layout === 'mini' ? layout : 'auto',
147 palette: str('palette', 'theme') === 'pastel' ? 'pastel' : 'theme',
148 openOnStart: bool('openOnStart', true),
149 statusLine: bool('statusLine', true),
150 }
151}
152
153// ---------------------------------------------------------------- palette
154
155export type Palette = 'theme' | 'pastel'
156export type Colors = Record<'main' | 'agent' | 'gate' | 'cleared' | 'arch' | 'amber' | 'warn' | 'dim' | 'faint' | 'text', string>
157
158/**
159 * `theme` names the person's own theme colours (they follow light, dark and colour-blind themes);
160 * `pastel` is fixed hex tuned for dark terminals.
161 */
162export const PALETTES: Record<Palette, Colors> = {
163 theme: {
164 main: 'claude',
165 agent: 'suggestion',
166 gate: 'success',
167 cleared: 'permission',
168 arch: 'merged',
169 amber: 'warning',
170 warn: 'error',
171 dim: 'inactive',
172 faint: 'subtle',
173 text: 'text',
174 },
175 pastel: {
176 main: '#7dd3fc',
177 agent: '#93c5fd',
178 gate: '#86efac',
179 cleared: '#5eead4',
180 arch: '#c4b5fd',
181 amber: '#fcd34d',
182 warn: '#fca5a5',
183 dim: '#6b7280',
184 faint: '#3f4654',
185 text: '#e5e7eb',
186 },
187}
188
189/** SVG cannot name theme keys: mid-tone colours that read on light and dark backgrounds. */
190export const SVG_COLORS = { running: '#3b82f6', done: '#16a34a', failed: '#dc2626', other: '#8b5cf6', label: '#6b7280' }
191
192// ---------------------------------------------------------------- formatting
193
194/** `claude-opus-5-5` → `Opus 5.5`; anything else is shown as given. */
195/**
196 * A model id as people say it, from any provider's spelling: `claude-opus-5-5[1m]` → `Opus 5.5 1M`,
197 * `us.anthropic.claude-sonnet-4-5-20250929-v1:0` → `Sonnet 4.5`, `claude-3-5-haiku-20241022` →
198 * `Haiku 3.5`. Anything else is shown as given, cut to 22 characters.
199 */
200export const prettyModel = (id: string) => {
201 if (!id) return '—'
202 const cap = (f: string) => f.charAt(0).toUpperCase() + f.slice(1)
203 const big = /\[1m\]|-1m\b/i.test(id) ? ' 1M' : ''
204 const now = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?![\d])/i.exec(id)
205 if (now?.[1] && !/^\d/.test(now[1])) return `${cap(now[1].toLowerCase())} ${now[2]}${now[3] ? `.${now[3]}` : ''}${big}`
206 const old = /claude-(\d+)(?:-(\d))?-([a-z]+)/i.exec(id)
207 if (old?.[3]) return `${cap(old[3].toLowerCase())} ${old[1]}${old[2] ? `.${old[2]}` : ''}${big}`
208 return shorten(id, 22)
209}
210
211export const shorten = (s: string, n: number) => {
212 const one = s.replace(/\s+/g, ' ').trim()
213 return n <= 0 ? '' : one.length > n ? `${one.slice(0, Math.max(0, n - 1)).trimEnd()}…` : one
214}
215
216export const kTokens = (n: number) =>
217 n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
218
219export const fmtDuration = (ms: number) => {
220 const s = Math.max(0, Math.round(ms / 1000))
221 if (s < 60) return `${s}s`
222 const m = Math.floor(s / 60)
223 return m < 60 ? `${m}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
224}
225
226/** A running clock as the live cards draw it: m:ss, or XhYY past an hour. */
227export const fmtTimer = (ms: number) => {
228 const s = Math.max(0, Math.floor(ms / 1000))
229 const m = Math.floor(s / 60)
230 return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
231}
232
233export const fmtClock = (ms: number) => (ms > 0 ? new Date(ms).toTimeString().slice(0, 8) : '--:--:--')
234
235/** `1 error`, `2 errors`. */
236export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
237
238export const fmtUsd = (n: number) => (n >= 100 ? `$${Math.round(n)}` : `$${n.toFixed(2)}`)
239
240/**
241 * How soon a request began to answer: from when it was sent to its first piece of response; null when
242 * none came. No output rate: the reported tokens include thinking, which may arrive unstreamed before
243 * that first piece, so tokens over the visible stream read in the thousands per second.
244 */
245export const stepSpeed = (sentAt: number, firstAt: number | null) => (firstAt === null ? null : { ttftMs: Math.max(0, firstAt - sentAt) })
246
247/** `ttft 0.8s`. */
248export const fmtSpeed = (s: { ttftMs: number }) => `ttft ${(s.ttftMs / 1000).toFixed(1)}s`
249
250/** The compaction window a context breakdown reports: its `rawMaxTokens` when auto-compaction is on and that is smaller than the model's `window`; else null. */
251export const compactWindowOf = (b: { rawMaxTokens: number; isAutoCompactEnabled: boolean } | null | undefined, window: number): number | null =>
252 b && b.isAutoCompactEnabled && b.rawMaxTokens > 0 && b.rawMaxTokens < window ? b.rawMaxTokens : null
253
254/**
255 * What the context gauge measures: the compaction window when one is set smaller than the model's,
256 * else the model's window, and the fill of it from the real `tokens` reading. No gauge (null) without one.
257 */
258export const contextFill = (u: Pick<Usage, 'tokens' | 'window' | 'compactWindow'>): { pct: number | null; window: number } => {
259 const window = u.compactWindow !== null && u.compactWindow > 0 && u.compactWindow < u.window ? u.compactWindow : u.window
260 return { window, pct: u.tokens !== null && window > 0 ? (u.tokens * 100) / window : null }
261}
262
263/** Reads of the compaction window that may miss (no session bound yet) before a model window stops asking. */
264export const COMPACT_TRIES = 3
265
266/**
267 * A measurement of model window `window`: whether it reads the compaction window (not read for this
268 * window yet, fewer than COMPACT_TRIES misses), and the usage with that read claimed. A new window
269 * starts its misses afresh.
270 */
271export const claimCompactRead = (u: Usage, window: number): { usage: Usage; isClaimed: boolean } => {
272 const misses = u.window === window ? u.compactMisses : 0
273 const isClaimed = window > 0 && u.compactFor !== window && misses < COMPACT_TRIES
274 return { usage: { ...u, compactFor: isClaimed ? window : u.compactFor, compactMisses: misses }, isClaimed }
275}
276
277/**
278 * The usage after a compaction-window read for model window `window`. Dropped when a newer claim took
279 * its place (a model switch); a read that failed or came back with no breakdown is a miss, asked
280 * again at the next measurement.
281 */
282export const afterCompactRead = (
283 u: Usage,
284 window: number,
285 b: { rawMaxTokens: number; isAutoCompactEnabled: boolean } | null | undefined,
286): Usage =>
287 u.compactFor !== window
288 ? u
289 : b
290 ? { ...u, compactWindow: compactWindowOf(b, window), compactMisses: 0 }
291 : { ...u, compactWindow: null, compactFor: 0, compactMisses: u.compactMisses + 1 }
292
293/** A new main-loop model may compact in another window (`modelSettings`): read afresh at the next measurement. */
294export const forgetCompactRead = (u: Usage): Usage => ({ ...u, compactWindow: null, compactFor: 0, compactMisses: 0 })
295
296/** A gauge of `width` cells: ▰ filled, ▱ empty. */
297export const gauge = (pct: number, width: number) => {
298 const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
299 return { on: '▰'.repeat(full), off: '▱'.repeat(width - full) }
300}
301
302/** A rate-limit reading as the pane keeps it, its ISO reset time turned into ms since the epoch. */
303export const limitOf = (r: { kind: string; percentUsed: number; resetsAt?: string }) => {
304 const at = r.resetsAt ? Date.parse(r.resetsAt) : NaN
305 return { kind: r.kind, pct: r.percentUsed, resetsAt: Number.isFinite(at) ? at : null }
306}
307
308/** Time left until a window resets, its two largest units: `25m`, `3h10m`, `4d2h`; empty when unknown or past. */
309export const fmtResetIn = (resetsAt: number | null | undefined, now: number) => {
310 if (resetsAt === null || resetsAt === undefined || resetsAt <= now) return ''
311 const m = Math.max(1, Math.floor((resetsAt - now) / 60_000))
312 const d = Math.floor(m / 1440)
313 const h = Math.floor((m % 1440) / 60)
314 if (d > 0) return `${d}d${h}h`
315 return h > 0 ? `${h}h${String(m % 60).padStart(2, '0')}m` : `${m}m`
316}
317
318/** A rate-limit window's short name: `five_hour` → `5h`, `seven_day_opus` → `7d opus`. */
319export const limitLabel = (kind: string) =>
320 kind
321 .replace(/five[_ -]?hours?/i, '5h')
322 .replace(/seven[_ -]?days?/i, '7d')
323 .replace(/[_-]+/g, ' ')
324 .trim()
325
326// ---------------------------------------------------------------- redaction
327
328const SECRETS: [RegExp, string][] = [
329 [/(authorization\s*[:=]\s*)(bearer\s+|basic\s+)?\S+/gi, '$1$2•••'],
330 [/\b(bearer)\s+[A-Za-z0-9._~+/-]{8,}=*/gi, '$1 •••'],
331 [/\b(sk|pk|rk|ghp|gho|ghs|github_pat|xox[abprs])[-_][A-Za-z0-9_-]{8,}/g, '•••'],
332 [/((?:api[_-]?key|access[_-]?token|token|secret|password|passwd|pwd)\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi, '$1•••'],
333 [/(--(?:token|password|api-key|secret)[= ])\S+/gi, '$1•••'],
334 [/(\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)=)\S+/g, '$1•••'],
335 [/(\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:)[^\s@]+@/gi, '$1•••@'],
336]
337
338/** What the gate drill-down may store: credentials masked before anything is written to state. */
339export const redact = (s: string) => SECRETS.reduce((t, [re, to]) => t.replace(re, to), s)
340
341// ---------------------------------------------------------------- tools and gate
342
343const FILE_TOOLS = new Set(['Read', 'Edit', 'Write', 'NotebookEdit', 'Glob', 'Grep'])
344const SHELL_TOOLS = new Set(['Bash', 'PowerShell'])
345export const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
346
347export const bucketOf = (tool: string): Bucket =>
348 FILE_TOOLS.has(tool) ? 'file' : SHELL_TOOLS.has(tool) ? 'shell' : 'other'
349
350/** One line saying what a call was about: its command, path or pattern; redacted. */
351export const describeInput = (tool: string, input: unknown) => {
352 const i = isObject(input) ? input : {}
353 const path = typeof i.file_path === 'string' ? i.file_path.split(/[\\/]/).slice(-2).join('/') : ''
354 const what =
355 typeof i.command === 'string'
356 ? i.command
357 : path || (typeof i.pattern === 'string' ? i.pattern : typeof i.url === 'string' ? i.url : typeof i.description === 'string' ? i.description : '')
358 return redact(what ? `${tool} → ${what}` : tool)
359}
360
361/** Keeps the last `max` checks, but never drops a pending ask: its settle must still find it. */
362export const trimRecent = (list: Check[], max: number): Check[] => {
363 let extra = list.length - max
364 if (extra <= 0) return list
365 const out: Check[] = []
366 for (const c of list) {
367 if (extra > 0 && c.verdict !== 'ask') {
368 extra -= 1
369 continue
370 }
371 out.push(c)
372 }
373 return out.slice(-max * 2)
374}
375
376export const recordCheck = (g: Gate, c: Check): Gate => {
377 const t = g.totals[c.bucket]
378 return {
379 recent: trimRecent([...g.recent, c], 80),
380 totals: { ...g.totals, [c.bucket]: { ...t, [c.verdict]: t[c.verdict] + 1 } },
381 }
382}
383
384/** An `ask` settled by the call that followed it: it ran (cleared) or was refused (deny). */
385export const settleCheck = (g: Gate, id: string, didRun: boolean): Gate => {
386 const c = g.recent.find(r => r.id === id && r.verdict === 'ask')
387 if (!c) return g
388 const verdict = didRun ? 'cleared' : 'deny'
389 const t = g.totals[c.bucket]
390 return {
391 recent: g.recent.map(r => (r === c ? { ...r, verdict } : r)),
392 totals: { ...g.totals, [c.bucket]: { ...t, ask: Math.max(0, t.ask - 1), [verdict]: t[verdict] + 1 } },
393 }
394}
395
396export const gateSummary = (g: Gate) => {
397 const all = (['file', 'shell', 'other'] as const).reduce(
398 (s, k) => ({
399 rule: s.rule + g.totals[k].rule,
400 ask: s.ask + g.totals[k].ask,
401 cleared: s.cleared + g.totals[k].cleared,
402 deny: s.deny + g.totals[k].deny,
403 }),
404 { ...ZERO },
405 )
406 return { ...all, total: all.rule + all.ask + all.cleared + all.deny }
407}
408
409// ---------------------------------------------------------------- turn and architect
410
411/**
412 * The turn after one tool call. Errors count in the main loop only (a subagent's failure is its
413 * own); edits count from every loop, so delegated work still reaches "before done".
414 */
415export const afterCall = (t: Turn, c: { inSubagent: boolean; hasFailed: boolean; isEdit: boolean }): Turn => ({
416 ...t,
417 errorStreak: c.inSubagent ? t.errorStreak : c.hasFailed ? t.errorStreak + 1 : 0,
418 errors: t.errors + (!c.inSubagent && c.hasFailed ? 1 : 0),
419 edits: t.edits + (c.isEdit ? 1 : 0),
420})
421
422/** Which of the architect's three moments a consult falls at: an inference over this turn so far. */
423export const momentOf = (t: Pick<Turn, 'edits' | 'errorStreak'>): Moment =>
424 t.errorStreak >= 2 ? 'error repeats' : t.edits === 0 ? 'before a plan' : 'before done'
425
426export const startConsult = (a: Architect, c: { id: string; at: number; moment: Moment; via: string }): Architect =>
427 a.consults.some(x => x.id === c.id) ? a : { ...a, consults: [...a.consults, { ...c, endAt: null }].slice(-40) }
428
429/** Ends the open consult (the latest without an end), or the one named. */
430export const endConsult = (a: Architect, at: number, advice: string | null, id?: string): Architect => {
431 const open = [...a.consults].reverse().find(c => c.endAt === null && (id === undefined || c.id === id))
432 return {
433 ...a,
434 consults: a.consults.map(c => (c === open ? { ...c, endAt: at } : c)),
435 lastAdvice: advice ?? a.lastAdvice,
436 }
437}
438
439export const isAdvising = (a: Architect) => a.consults.some(c => c.endAt === null)
440
441/** A one-row timeline of consults across `width` cells: ◆ a consult, ━ while it ran. */
442export const consultTimeline = (a: Architect, now: number, width: number) => {
443 if (a.consults.length === 0 || width < 4) return '─'.repeat(Math.max(0, width))
444 const first = a.consults[0]?.at ?? now
445 const span = Math.max(1, now - first)
446 const cells = Array.from({ length: width }, () => '─')
447 for (const c of a.consults) {
448 const from = Math.min(width - 1, Math.floor(((c.at - first) / span) * (width - 1)))
449 const to = Math.min(width - 1, Math.floor((((c.endAt ?? now) - first) / span) * (width - 1)))
450 for (let i = from + 1; i <= to; i += 1) cells[i] = '━'
451 cells[from] = '◆'
452 }
453 return cells.join('')
454}
455
456export const receiptOf = (t: Turn, o: { durationMs: number; agentsSince: number; costNow: number | null; reason: string }): Receipt => ({
457 durationMs: o.durationMs,
458 agents: o.agentsSince,
459 edits: t.edits,
460 errors: t.errors,
461 costDelta: o.costNow !== null && t.costAtStart !== null && o.costNow - t.costAtStart >= 0.005 ? o.costNow - t.costAtStart : null,
462 reason: o.reason,
463})
464
465// ---------------------------------------------------------------- agents and loops
466
467type StepUsage = { input_tokens?: number; cache_read_input_tokens?: number; cache_creation_input_tokens?: number; output_tokens?: number } | null
468
469/** A card after one of its model requests: its context is the latest step's whole input; output adds up. */
470export const applyStep = (c: AgentCard, s: { model: string; usage: StepUsage; stopReason: string | null }): AgentCard => {
471 const u = s.usage ?? {}
472 const ctx = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
473 return {
474 ...c,
475 model: c.model || s.model,
476 steps: c.steps + 1,
477 ctx: ctx > 0 ? ctx : c.ctx,
478 out: c.out + (u.output_tokens ?? 0),
479 lastStop: s.stopReason,
480 }
481}
482
483export const noteTool = (c: AgentCard, n: ToolNote): AgentCard => ({ ...c, tools: [...c.tools, n].slice(-3) })
484
485/** A surface module's fault key, `desktop:rail.tsx`, from `hooks/rail.tsx` or `hooks\rail.tsx` alike. */
486export const faultKey = (surface: string, module: string) => `${surface}:${module.split(/[\\/]/).pop()}`
487
488/** A card whose agent was resumed after it finished (SendMessage): running again, its clock from its first spawn. */
489export const resumeCard = (c: AgentCard): AgentCard => ({ ...c, status: 'running', endedAt: null })
490
491/**
492 * A spawned card joins the list. An id already there is that agent resumed: its card runs again
493 * where it stands, with its tallies and the new task and model, so no two cards share keys.
494 */
495export const addCard = (cards: AgentCard[], card: AgentCard): AgentCard[] =>
496 cards.some(c => c.id === card.id)
497 ? cards.map(c => (c.id === card.id ? resumeCard({ ...c, description: card.description || c.description, model: card.model || c.model }) : c))
498 : [...cards, card].slice(-24)
499
500export const stepLoop = (loops: Loop[], id: string, at: number): Loop[] => {
501 const found = loops.find(l => l.id === id)
502 const next = found
503 ? loops.map(l => (l === found ? { ...l, steps: l.steps + 1, lastAt: at } : l))
504 : [...loops, { id, steps: 1, firstAt: at, lastAt: at, isDone: false }]
505 return next.slice(-60)
506}
507
508export const LOOP_ACTIVE_MS = 15_000
509export const isLoopActive = (l: Loop, now: number) => !l.isDone && now - l.lastAt < LOOP_ACTIVE_MS
510
511/** Swimlane geometry: each agent's bar on one shared axis from the first spawn to now. */
512export const lanes = (cards: AgentCard[], now: number, width: number) => {
513 const start = Math.min(...cards.map(c => c.spawnedAt).filter(n => n > 0), now)
514 const span = Math.max(1, now - start)
515 return cards.map(c => {
516 const from = Math.floor(((Math.max(c.spawnedAt, start) - start) / span) * width)
517 const to = Math.max(from + 1, Math.ceil((((c.endedAt ?? now) - start) / span) * width))
518 return { id: c.id, before: Math.min(from, width), bar: Math.min(to, width) - Math.min(from, width), after: width - Math.min(to, width) }
519 })
520}
521
522// ---------------------------------------------------------------- layout
523
524/** How many log lines fit: what the other panels leave, never fewer than 4 nor more than 8. */
525export const logRows = (bodyRows: number, used: number) => Math.max(4, Math.min(8, bodyRows - used - 3))
526
527/** Legend items that fit on one row of `width` cells, in order; the rest are dropped. */
528export const fitLegend = <T extends { label: string }>(items: T[], width: number) => {
529 const out: T[] = []
530 let used = 0
531 for (const it of items) {
532 const w = it.label.length + 4
533 if (used + w > width) break
534 out.push(it)
535 used += w
536 }
537 return out
538}
539
540/** The cells a string takes in a terminal: one per character. */
541export const cellWidth = (s: string) => [...s].length
542
543/**
544 * How many pieces of a line fit in `room` cells, in order from the start: each piece is `lead` extra cells
545 * then `width`, and pieces sit `gap` cells apart. The rest are left out, as the legend's items are.
546 */
547export const piecesThatFit = (pieces: readonly { width: number; lead?: number }[], room: number, gap: number) => {
548 let used = 0
549 for (let i = 0; i < pieces.length; i += 1) {
550 const p = pieces[i]!
551 const next = used + (i > 0 ? gap : 0) + (p.lead ?? 0) + p.width
552 if (next > room) return i
553 used = next
554 }
555 return pieces.length
556}
557
558/**
559 * How many marks (■ ✗ ● ○ ✓) a row of `cells` columns holds. A terminal draws each mark in one
560 * cell; a graphical surface draws them wider (■ measured about 1.4 cells on the desktop app), so
561 * there a row holds fewer and its newest marks still show.
562 */
563export const marksIn = (cells: number, isTerminal: boolean) => (isTerminal ? cells : Math.floor(cells / 1.5))
564
565/** A card's title row: the task in the agent's own words, the type only when there is none. */
566export const cardTitle = (c: AgentCard) => c.description || c.type
567
568/** A title split over two rows at a word boundary: `first` cells on row one, `rest` on row two. */
569export const titleLines = (title: string, first: number, rest: number): [string, string] => {
570 const t = title.replace(/\s+/g, ' ').trim()
571 if (t.length <= first) return [t, '']
572 const cut = t.lastIndexOf(' ', first)
573 const at = cut > 0 ? cut : first
574 return [t.slice(0, at).trim(), shorten(t.slice(at), rest)]
575}
576
577/**
578 * What a turn's opening text was, for the log: the person's words, or for a turn the engine
579 * opened with a tagged message (a subagent's hand-back, a task notification), that message's kind.
580 */
581export const promptLine = (text: string): { who: string; text: string } => {
582 const tag = /^\s*<([a-z][\w-]*)/i.exec(text)?.[1]
583 if (!tag) return { who: 'you', text: shorten(text, 70) }
584 const from = /\bfrom="([^"]+)"/.exec(text)?.[1]
585 return { who: 'engine', text: shorten(`${tag.replace(/[-_]/g, ' ')}${from ? ` from ${from.slice(0, 8)}` : ''}`, 70) }
586}
587
588/**
589 * A subagent's hand-back message: who sent it and the first line of what it said. The report
590 * follows a framing header in the message; without one, the first line after the opening tag.
591 */
592export const handbackOf = (text: string): { from: string; body: string } | null => {
593 const from = /^\s*<agent-message\s+from="([^"]+)"/.exec(text)?.[1]
594 if (!from) return null
595 const afterHeader = text.split(/The report follows:\s*\n/)[1]
596 const rest = afterHeader ?? text.replace(/^\s*<agent-message[^>]*>/, '')
597 const body =
598 rest
599 .split('\n')
600 .map(l => l.trim())
601 .find(l => l && !l.startsWith('[') && !l.startsWith('<') && !l.startsWith('</')) ?? ''
602 return body ? { from, body } : null
603}
604
605/** The advice line a pane shows for a report: its first real line, markdown markers stripped, cut to 160. */
606export const adviceLine = (report: string) => {
607 const first = report.split('\n').map(l => l.trim()).find(l => l && !l.startsWith('[') && !l.startsWith('<')) ?? ''
608 return shorten(first.replace(/\*\*|__/g, '').replace(/^[#>*\s-]+/, ''), 160)
609}
610
611export const elapsedOf = (c: AgentCard, now: number) => (c.endedAt ?? now) - c.spawnedAt
612hooks/rail.tsx 85 lines1// A connector drawn on the surface's own frame clock: packets travel along it while `active`,
2// and it rests as a plain dim line otherwise. Only this region redraws; the pane does not.
3import type { ClientModule, RenderChildren } from 'claude-code'
4
5type Props = {
6 active: boolean
7 width: number
8 color: string
9 dim: string
10 /** Cells where a branch drops (┬); the rest of the line is ─. */
11 marks: number[]
12 /** Draw ┴ instead of ┬ at the marks: a merge into what is below. */
13 isMerge: boolean
14}
15
16type Ref = { phase: number; active: boolean }
17type State = { ref: Ref }
18
19const STEP_MS = 110
20/** Dashes drawn past the line's end and clipped by its box, so the right end is the box's edge. */
21const SPARE = 4
22
23const Rail: ClientModule<Props, State> = (props, surface) => {
24 const { Box, Text } = surface.elements
25 const ref = surface.state?.ref ?? { phase: 0, active: props.active }
26 ref.active = props.active
27 if (surface.state === undefined) {
28 surface.setState({ ref })
29 surface.every(STEP_MS, () => {
30 if (ref.active) {
31 ref.phase += 1
32 surface.setState({ ref })
33 }
34 })
35 }
36
37 const width = Math.max(1, surface.columns || props.width)
38 const cells = Array.from({ length: width + SPARE }, () => '─')
39 for (const m of props.marks) if (m >= 0 && m < width) cells[m] = props.isMerge ? '┴' : '┬'
40
41 // A graphical surface draws text in a proportional face, where ─ ● • and bold differ in width, so as
42 // the packets moved the line's length changed and its right end jittered. Drawn in the surface's
43 // monospaced face (whose advance is what a cell is there) each glyph is one cell, and the line sits in
44 // a box of its width that clips the spare dashes: its right end is that edge, every frame.
45 const line = (children: RenderChildren) => (
46 <Box width={width} overflow="hidden">
47 <Box flexShrink={0}>{children}</Box>
48 </Box>
49 )
50
51 if (!props.active) {
52 return line(
53 <Text color={props.dim} mono>
54 {cells.join('')}
55 </Text>,
56 )
57 }
58
59 // Two packets per 24 cells, a bright head and a trailing dot, moving left to right.
60 const lit = new Map<number, string>()
61 for (let base = 0; base < width + 24; base += 24) {
62 const head = (base + ref.phase) % (width + 24)
63 if (head < width) lit.set(head, '●')
64 if (head - 1 >= 0 && head - 1 < width) lit.set(head - 1, '•')
65 }
66 // Runs, not cells: consecutive cells of one kind share a Text, a handful of nodes per frame.
67 const runs: { text: string; isLit: boolean }[] = []
68 cells.forEach((ch, i) => {
69 const isLit = lit.has(i)
70 const last = runs[runs.length - 1]
71 const glyph = lit.get(i) ?? ch
72 if (last && last.isLit === isLit) last.text += glyph
73 else runs.push({ text: glyph, isLit })
74 })
75 return line(
76 runs.map(r => (
77 <Text color={r.isLit ? props.color : props.dim} bold={r.isLit} mono>
78 {r.text}
79 </Text>
80 )),
81 )
82}
83
84export default Rail
85hooks/elapsed.tsx 38 lines1// A running agent's clock, ticking on the surface's frame clock so the pane need not redraw.
2// `since` and `now` come from the hooks module's $.clock; between redraws it adds its own ticks.
3import type { ClientModule } from 'claude-code'
4
5type Props = { since: number; now: number; endAt: number | null; color: string }
6type Ref = { base: number; ticks: number; lastNow: number; isRunning: boolean }
7type State = { ref: Ref }
8
9const fmt = (ms: number) => {
10 const s = Math.max(0, Math.floor(ms / 1000))
11 const m = Math.floor(s / 60)
12 return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
13}
14
15const Elapsed: ClientModule<Props, State> = (props, surface) => {
16 const { Text } = surface.elements
17 const ref = surface.state?.ref ?? { base: 0, ticks: 0, lastNow: -1, isRunning: true }
18 if (props.now !== ref.lastNow) {
19 // A fresh reading from the hooks module: restart the local count from it.
20 ref.lastNow = props.now
21 ref.base = (props.endAt ?? props.now) - props.since
22 ref.ticks = 0
23 }
24 ref.isRunning = props.endAt === null
25 if (surface.state === undefined) {
26 surface.setState({ ref })
27 surface.every(1000, () => {
28 if (ref.isRunning) {
29 ref.ticks += 1
30 surface.setState({ ref })
31 }
32 })
33 }
34 return <Text color={props.color}>{fmt(ref.base + ref.ticks * 1000)}</Text>
35}
36
37export default Elapsed
38types/index.d.ts 129 lines1export type Moment = 'before a plan' | 'error repeats' | 'before done'
2
3export type Bucket = 'file' | 'shell' | 'other'
4
5/** rule: settings allowed it. ask: put to the decider, outcome pending. cleared: asked, then ran. deny: refused. */
6export type Verdict = 'rule' | 'ask' | 'cleared' | 'deny'
7
8export type Main = {
9 model: string
10 effort: string
11 mode: string
12 steps: number
13 isRunning: boolean
14 /** The main loop's last answered request: time to its first piece of response. Null until one is
15 * measured, absent in older state; a `tokPerS` kept by 0.5.0 and earlier is ignored. */
16 speed?: { ttftMs: number } | null
17}
18
19export type Usage = {
20 pct: number | null
21 tokens: number | null
22 window: number
23 /** The compaction window (`autoCompactWindow`, or the host's own) the host measures context against, when auto-compaction
24 * is on and the window is smaller than the model's; null when none is set or none could be read. */
25 compactWindow: number | null
26 /** The model window `compactWindow` was read for, so a model switch reads it again; 0 = not read yet. */
27 compactFor: number
28 /** Reads for this model window that came back with no breakdown or failed; it stops asking at 3. */
29 compactMisses: number
30 costUsd: number | null
31 /** `resetsAt`: when the window resets, in ms since the epoch; null when the API gave no time,
32 * absent in state saved before it was kept. */
33 limits: { kind: string; pct: number; resetsAt?: number | null }[]
34 compactions: number
35 lastCompactAt: number | null
36}
37
38export type Consult = { id: string; at: number; endAt: number | null; moment: Moment; via: string }
39
40export type Architect = { consults: Consult[]; ids: string[]; seen: string[]; lastAdvice: string }
41
42export type Check = {
43 id: string
44 tool: string
45 bucket: Bucket
46 verdict: Verdict
47 inSubagent: boolean
48 detail: string
49 at: number
50}
51
52export type Tally = { rule: number; ask: number; cleared: number; deny: number }
53
54export type Gate = { recent: Check[]; totals: Record<Bucket, Tally> }
55
56export type ToolNote = { tool: string; text: string; isError: boolean }
57
58export type AgentCard = {
59 id: string
60 type: string
61 model: string
62 description: string
63 status: string
64 spawnedAt: number
65 endedAt: number | null
66 /** The agent's context now: input + cache read + cache write of its latest step. */
67 ctx: number
68 /** Output tokens summed over its steps. */
69 out: number
70 steps: number
71 lastStop: string | null
72 tools: ToolNote[]
73 answer: string
74}
75
76/** A model loop whose id matches no card: a workflow agent, a compaction or a memory fork. */
77export type Loop = { id: string; steps: number; firstAt: number; lastAt: number; isDone: boolean }
78
79export type LogLine = {
80 at: number
81 who: string
82 text: string
83 agentId: string | null
84 kind: 'info' | 'error' | 'consult' | 'done'
85}
86
87export type Turn = {
88 edits: number
89 errorStreak: number
90 errors: number
91 isReviewing: boolean
92 startedAt: number
93 costAtStart: number | null
94}
95
96export type Receipt = {
97 durationMs: number
98 agents: number
99 edits: number
100 errors: number
101 costDelta: number | null
102 reason: string
103}
104
105export type Layout = 'auto' | 'compact' | 'wide' | 'mini'
106
107export type View = { expanded: string | null; gateOpen: Bucket | null; layout: Layout | null }
108
109export type Roster = { architectTypes: string[] }
110
111declare module 'claude-code' {
112 interface PluginState {
113 'flightdeck': {
114 meta: { schemaVersion: number }
115 main: Main
116 usage: Usage
117 architect: Architect
118 gate: Gate
119 agents: AgentCard[]
120 loops: Loop[]
121 log: LogLine[]
122 turn: Turn
123 receipt: Receipt | null
124 view: View
125 roster: Roster
126 }
127 }
128}
129