Live session dashboard in one side pane (/cockpit). Mods: agents-progress (/agents-info), cache-keeper (/keepwarm, /cache-tax), context-health (/ctx-handoff…

Live session dashboard in one side pane. Needs Claude Code 2.1.287+.
/plugin marketplace add bharath-gp/ai-harness
/plugin install cockpit@ai-harness
/cockpit opens the pane: docked beside the transcript in fullscreen, an 8-row summary above the prompt otherwise. Focus it with ctrl+x tab; every key is also a button.
| Command | Does | |||
|---|---|---|---|---|
/cockpit | open the pane | |||
/cockpit close | close it | |||
/cockpit reset | clear agents, consults, checks, loops, log and the receipt (/clear does the same) | |||
| `/cockpit layout auto\ | compact\ | wide\ | mini` | override the layout for this session |
| Mod | What it shows | Commands |
|---|---|---|
agents-progress | Main activity and task progress, subagents as cards or swimlanes, background shells, monitors and wakeups | /agents-info |
cache-keeper | Cache countdown, a band when it is about to go cold, cold-send dialog with cost estimate | /keepwarm, /cache-tax |
context-health | Context gauge with compactions and a warning band | /ctx-handoff, /autohandoff |
token-meter | Session tokens and cost, project total, models | none |
usage-limits | 5h and 7d plan limits with reset countdown; a band from 70% | none |
filetree | File tree with git status and highlights for files Claude reads and writes | /filetree |
next-steps | Three suggested prompts after each turn | none |
architect | Consult timeline with advice from the on-call architect | none |
permission-gate | One cell per permission check, credentials masked | none |
loops | Model loops no agent claims (workflow agents, compactions, forks) | none |
turn-receipt | The running or last turn: clock, agents, edits, errors, cost | none |
session-log | Prompts, spawns, completions, consults, edits, errors, denials | none |
Every mod is on by default. Turn one off in the plugin config menu: agentsProgress, cacheKeeper, contextHealth, tokenMeter, usageLimits, filetree, nextSteps, architect, permissionGate, loops, turnReceipt, sessionLog. The plugin reloads.
| Option | Default | Meaning | |
|---|---|---|---|
palette | theme | theme follows your Claude Code theme; pastel uses fixed colours for dark terminals | |
motion | while-active | off keeps connectors still | |
layout | auto | mini, compact, wide or auto | |
openOnStart | true | open the pane when a session starts (terminals 144+ columns) | |
paneColumns | 66 | columns the docked pane asks for (40+) | |
maxCards | 3 | agent cards side by side before swimlanes (1-6) | |
architectPattern | `advisor\ | architect` | regex for agent types and server tools that count as the architect |
matchDescriptions | false | also match agent descriptions | |
moments | true | show each consult's inferred moment | |
architectLabel, gateLabel | ARCHITECT, GATE | panel names |
Mods are not sandboxed: read hooks/register.tsx first.
hooks/register.tsx 2288 lines1import type { Register } from 'claude-code'
2import { band, beginPass, box, gaugeSpans, line, quiet, quietLine, type BandSpec, type Piece } from './band'
3import { fileBadge, pill, sectionLabel } from './kit'
4import { C, DECK, MONO, P, SVG_COLORS, below, esc, fmtClock, fmtCost, fmtDur, fmtSize, fmtTimer, fmtTok, gauge, isRich, parsePorcelain, plural, prettyModel, shorten, usePalette, zoneTone } from './ui'
5
6// ===== shared drawing =====
7// The look and the pane follow claude-flightdeck (MIT, see THIRD_PARTY_NOTICES.md).
8// After a surface module faults on a surface, it is drawn there without animation; other surfaces keep theirs.
9const faulted = new Set<string>()
10
11// A connector carrying packets while `active`, a still faint line otherwise or where the surface cannot run a surface
12// module. `marks` are cells where a branch drops (┬) or merges (┴). The module path must be a literal in this file.
13export function rail(ui: any, e: any, key: string, active: boolean, color: string, width: number, marks: number[] = [], isMerge = false) {
14 const { Text } = ui
15 if (!DECK.motion || !('Client' in ui) || faulted.has(`${e.surface}:rail.tsx`)) {
16 const cells = Array.from({ length: Math.max(1, width) }, () => '─')
17 for (const m of marks) if (m >= 0 && m < cells.length) cells[m] = isMerge ? '┴' : '┬'
18 return <Text key={key} color={C.faint} mono>{cells.join('')}</Text>
19 }
20 return <ui.Client key={key} module="./rail.tsx" width={width} height={1} props={{ active, width, color, dim: C.faint, marks, isMerge }} />
21}
22
23// A running clock that ticks on the surface's own frame clock, so the pane does not redraw every second.
24export function liveClock(ui: any, e: any, key: string, since: number, now: number, endAt: number | null, color: string) {
25 const { Text } = ui
26 if (since <= 0) return <Text color={color}>—</Text>
27 if (!('Client' in ui) || faulted.has(`${e.surface}:elapsed.tsx`)) return <Text color={color}>{fmtTimer((endAt ?? now) - since)}</Text>
28 return <ui.Client key={key} module="./elapsed.tsx" props={{ since, now, endAt, color }} />
29}
30
31// Passes a turn.step stream through, calling `see` on each chunk, and returns its result to the hooks above.
32async function* tap(stream: any, see: (chunk: any) => unknown) {
33 const it = stream[Symbol.asyncIterator]()
34 for (let r = await it.next(); ; r = await it.next()) {
35 if (r.done) return r.value
36 await see(r.value)
37 yield r.value
38 }
39}
40
41// ===== cockpit pane =====
42// The shell every mod draws into: one docked pane (inline as an 8-row summary on the terminal's main screen), its
43// header, the main model's vitals and the turn the architect and receipt read. Not a mod: it has no toggle.
44const PANE = 'cockpit'
45let cockpitCfg = { layout: 'auto', maxCards: 3, paneColumns: 66, openOnStart: true }
46let deckModel = ''
47let deckEffort = ''
48let deckMode = ''
49let deckSteps = 0
50let deckRunning = false
51let deckTtft: number | null = null
52let deckLayout: string | null = null // /cockpit layout override, for this session
53// The main turn so far: edits from every loop, errors from the main loop only (a subagent's failure is its own).
54let deckTurn = { edits: 0, errors: 0, errorStreak: 0, startedAt: 0, costAtStart: null as number | null, isReviewing: false }
55
56function cockpitOpen($: any) {
57 // columns apply when docked beside the transcript, rows when seated inline above the prompt.
58 return $.ui.open({ id: PANE, title: 'Cockpit', columns: cockpitCfg.paneColumns, rows: 8 })
59}
60
61async function paneIsOpen($: any, id: string) {
62 try {
63 return (await $.ui.panes()).some((p: any) => p.id === id)
64 } catch {
65 return false
66 }
67}
68
69export async function cockpitSessionStart($: any, e: any, next: any) {
70 await $.command.register({ name: 'cockpit', description: 'Cockpit pane: open, close, reset, or set the layout', argumentHint: '[open|close|reset|layout auto|compact|wide|mini]' })
71 deckModel = await Promise.resolve($.session.model()).catch(() => '') // until the first request names it
72 if (cockpitCfg.openOnStart) void Promise.resolve(cockpitOpen($)).catch(() => undefined)
73 return next(e)
74}
75
76export async function cockpitCommandRun($: any, e: any) {
77 const [verb = 'open', arg = ''] = (e.args ?? '').trim().split(/\s+/)
78 if (verb === 'close') {
79 await $.ui.close({ id: PANE })
80 return { text: 'Cockpit closed.' }
81 }
82 if (verb === 'reset') {
83 cockpitReset()
84 $.ui.invalidate('ui.render')
85 return { text: 'Cockpit reset.' }
86 }
87 if (verb === 'layout') {
88 if (!['auto', 'compact', 'wide', 'mini'].includes(arg)) return { text: 'Usage: /cockpit layout auto|compact|wide|mini' }
89 deckLayout = arg
90 const opened = await cockpitOpen($)
91 return { text: opened.isPlaced ? `Cockpit layout: ${arg}.` : `Layout set to ${arg}; the pane is not shown yet: ${opened.reason}` }
92 }
93 const opened = await cockpitOpen($)
94 if (!opened.isPlaced) return { text: `Cockpit is not shown yet: ${opened.reason}` }
95 return { text: 'Cockpit opened. Focus it with ctrl+x tab: 1-6 expand agents, f/s/o open the gate rows, h hands off, k keeps the cache warm, t shows token details.' }
96}
97
98// Clears what the panels collected this session (agents, consults, checks, loops, log, receipt); cost and limits stay.
99function cockpitReset() {
100 agents = []
101 subTools = 0
102 bgTasks = []
103 mainTool = ''
104 archConsults = []
105 archIds = []
106 archAdvice = ''
107 gateRecent = []
108 gateTotals = gateZero()
109 loopsList = []
110 logLines = []
111 receiptLast = null
112 deckTurn = { ...deckTurn, edits: 0, errors: 0, errorStreak: 0, isReviewing: false }
113}
114
115export async function cockpitSessionEnd($: any, e: any, next: any) {
116 if (e.reason === 'clear') cockpitReset()
117 return next(e)
118}
119
120export function cockpitUserPromptSubmit(_$: any, e: any, next: any) {
121 if (e.permission_mode) deckMode = e.permission_mode
122 return next(e)
123}
124
125export async function cockpitTurnStart($: any, e: any, next: any) {
126 if (e.agentId === undefined) {
127 deckRunning = true
128 deckTurn = { edits: 0, errors: 0, errorStreak: 0, startedAt: await $.clock.now(), costAtStart: (await $.session.usage().catch(() => null))?.cost?.usd ?? null, isReviewing: false }
129 $.ui.invalidate('ui.render')
130 }
131 return next(e)
132}
133
134// The main loop's model is known when its request starts; its time to first token is timed as the stream passes.
135export async function* cockpitTurnStep($: any, e: any, next: any) {
136 if (e.agentId !== undefined) return yield* next(e)
137 deckModel = e.model
138 deckEffort = String(e.effort ?? deckEffort)
139 deckSteps += 1
140 const sentAt = await $.clock.now()
141 let firstAt: number | null = null
142 const result = yield* tap(next(e), async (c: any) => {
143 if (firstAt === null && c.kind !== 'engine' && c.kind !== 'stop') firstAt = await $.clock.now()
144 })
145 if (firstAt !== null) deckTtft = Math.max(0, firstAt - sentAt)
146 return result
147}
148
149export async function cockpitToolCall($: any, e: any, next: any) {
150 const ran = await next(e)
151 const didRun = ran.deny === undefined
152 const hasFailed = didRun && ran.isError === true
153 const isEdit = didRun && !hasFailed && ['Edit', 'Write', 'NotebookEdit'].includes(String(e.tool))
154 const inSub = e.agentId !== undefined
155 deckTurn = {
156 ...deckTurn,
157 errorStreak: inSub ? deckTurn.errorStreak : hasFailed ? deckTurn.errorStreak + 1 : 0,
158 errors: deckTurn.errors + (!inSub && hasFailed ? 1 : 0),
159 edits: deckTurn.edits + (isEdit ? 1 : 0),
160 }
161 return ran
162}
163
164export async function cockpitTurnComplete($: any, e: any, next: any) {
165 const done = await next(e)
166 if (e.agentId === undefined) {
167 deckRunning = false
168 $.ui.invalidate('ui.render')
169 }
170 return done
171}
172
173// The main box: model, effort, mode, requests, then each enabled mod's rows, then the last request's ttft.
174function cockpitMainPanel($: any, ui: any, e: any, w: number, now: number, options: any) {
175 const { Box, Text } = ui
176 const effortN = ({ low: 1, medium: 2, high: 3, xhigh: 4, max: 4 } as Record<string, number>)[deckEffort] ?? 0
177 return box(ui, {
178 key: 'main',
179 color: C.main,
180 title: `${prettyModel(deckModel)} · main`,
181 right: deckRunning ? '● working' : '○ idle',
182 w,
183 children: (
184 <Box flexDirection="column">
185 {line(ui, [
186 { spans: [{ text: 'effort ', dim: true }, { text: `${'▮'.repeat(effortN)}${'▯'.repeat(4 - effortN)} `, color: C.main }, { text: deckEffort || '—', color: C.main, bold: true }] },
187 deckMode ? { spans: [{ text: `mode ${deckMode}`, dim: true }] } : null,
188 { spans: [{ text: `${deckSteps} req`, dim: true }] },
189 ], w - 4, 3)}
190 {options.contextHealth !== false ? contextHealthPaneRow($, ui, w) : null}
191 {options.usageLimits !== false ? usageLimitsPaneRow(ui, w, now) : null}
192 {options.cacheKeeper !== false ? cacheKeeperPaneRow($, ui, w, now) : null}
193 {options.tokenMeter !== false ? tokenMeterPaneRows($, ui, w) : null}
194 {deckTtft !== null ? <Text dimColor wrap="truncate">{`last req ttft ${(deckTtft / 1000).toFixed(1)}s`}</Text> : null}
195 </Box>
196 ),
197 })
198}
199
200// Inline above the prompt (the terminal's main screen): a summary of at most 8 rows.
201function cockpitMini($: any, ui: any, e: any, W: number, now: number, options: any) {
202 const { Box, Text } = ui
203 const on = (k: string) => options[k] !== false
204 const ctx = on('contextHealth') && percent > 0 ? gauge(percent, 6) : null
205 const shown = on('agentsProgress') ? [...running(), ...[...finished()].reverse()].slice(0, 3) : []
206 const s = gateSummary()
207 return (
208 <Box flexDirection="column" width={W}>
209 {line(ui, [
210 { spans: [{ text: prettyModel(deckModel), color: C.main, bold: true }, { text: deckRunning ? ' ● working' : ' ○ idle', color: deckRunning ? C.main : C.dim }] },
211 ctx ? { spans: [{ text: '· ctx ', dim: true }, { text: ctx.on, color: percent >= 80 ? C.warn : C.main }, { text: ctx.off, color: C.faint }, { text: ` ${percent}%` }, ...(compactions ? [{ text: ` ⟲${compactions}`, color: C.amber }] : [])] } : null,
212 on('tokenMeter') ? { spans: [{ text: `· ${fmtTok(tmSum(tmSession))} tok`, dim: true }] } : null,
213 on('architect') && archShown() ? { spans: [{ text: `· ${archLabel.toLowerCase()} ${archAdvising() ? 'advising' : archConsults.length}`, color: C.arch }] } : null,
214 ], W)}
215 {line(ui, [
216 ...(on('usageLimits') ? usageLimitRates.map((r, i): Piece => ({ key: `u${i}`, spans: [{ text: `${i ? '· ' : ''}${LIMIT_SHORT[r.kind]} ${Math.round(r.percentUsed)}%`, color: r.percentUsed >= 70 ? P[zoneTone(r.percentUsed, 70, 90)] : undefined, dim: r.percentUsed < 70 }] })) : []),
217 on('cacheKeeper') && lastTouch ? { spans: [{ text: `· cache ${TTL - (now - lastTouch) > 0 ? mins(TTL - (now - lastTouch)) : 'cold'}`, dim: true }] } : null,
218 on('agentsProgress') && todos.length ? { spans: [{ text: `· tasks ${todos.filter(t => t.status === 'completed').length}/${todos.length}`, dim: true }] } : null,
219 on('agentsProgress') && bgLive(now).length ? { spans: [{ text: `· bg ${bgLive(now).length}`, dim: true }] } : null,
220 ], W)}
221 {on('permissionGate') && s.total > 0 ? (
222 <Box columnGap={1}>
223 <Text dimColor>{gateLabel.toLowerCase()}</Text>
224 <Box overflow="hidden" flexShrink={1}><Text wrap="truncate-start">{gateMarks(ui, gateRecent.slice(-Math.max(4, W - 50)))}</Text></Box>
225 <Box flexShrink={0}><Text color={s.deny ? C.warn : s.ask ? C.amber : C.dim}>{`${s.rule} allowed · ${s.cleared} ${gateDecider()} · ${s.deny} denied`}</Text></Box>
226 </Box>
227 ) : null}
228 {shown.map(a => (
229 <Box key={`m-${a.id}`} columnGap={1}>
230 <Text color={agentColor(a)}>{agentGlyph(a)}</Text>
231 <Box flexGrow={1} flexShrink={1}><Text wrap="truncate">{a.desc || a.type}</Text></Box>
232 {a.steps ? <Text dimColor>{`ctx ${fmtTok(a.ctx)}`}</Text> : null}
233 {liveClock(ui, e, `mini-clock-${a.id}`, a.startedAt, now, a.endedAt ?? null, C.dim)}
234 </Box>
235 ))}
236 {agents.length > shown.length && on('agentsProgress') ? <Text color={C.faint} wrap="truncate">{`+${agents.length - shown.length} more agents · /cockpit layout compact for all`}</Text> : null}
237 {on('loops') && loopsList.length ? <Text dimColor wrap="truncate">{`other loops ${loopsList.length} · ${loopsList.filter(l => loopActive(l, now)).length} active`}</Text> : null}
238 {on('turnReceipt') && !deckRunning && receiptLast ? <Text dimColor wrap="truncate">{receiptText(receiptLast)}</Text> : null}
239 </Box>
240 )
241}
242
243export async function cockpitUiRenderPane($: any, e: any, options: any) {
244 const ui = $.ui.resolve(e)
245 const { Box, Text } = ui
246 const now = await $.clock.now()
247 const W = Math.max(24, e.props.bodyColumns ?? 66)
248 const layout = deckLayout ?? cockpitCfg.layout
249 const on = (k: string) => options[k] !== false
250 if (layout === 'mini' || (layout === 'auto' && e.props.placement === 'inline')) return cockpitMini($, ui, e, W, now, options)
251 const isWide = layout === 'wide' || (layout === 'auto' && W >= 110)
252 const colW = isWide ? Math.floor((W - 2) / 2) : W
253 const showArch = on('architect') && archShown()
254 // A panel with nothing to show yet takes no room; the agents panel always shows, its main row runs every turn.
255 type Panel = { id: string; draw: (w: number) => unknown; flow?: { active: boolean; color: string } }
256 const panels: Panel[] = [
257 { id: 'main', draw: w => cockpitMainPanel($, ui, e, w, now, options) },
258 ...(showArch ? [{ id: 'architect', draw: (w: number) => architectPanel(ui, w, now), flow: { active: archAdvising(), color: C.arch } }] : []),
259 ...(on('permissionGate') && gateRecent.length ? [{ id: 'gate', draw: (w: number) => gatePanel($, ui, e, w), flow: { active: deckRunning, color: C.gate } }] : []),
260 ...(on('agentsProgress') ? [{ id: 'agents', draw: (w: number) => agentsProgressPanel($, ui, e, w, now) }] : []),
261 ...(on('loops') && loopsList.length ? [{ id: 'loops', draw: (w: number) => loopsPanel(ui, e, w, now) }] : []),
262 ...(on('turnReceipt') && (deckRunning || receiptLast) ? [{ id: 'receipt', draw: (w: number) => receiptPanel(ui, e, w, now), flow: { active: deckRunning, color: C.main } }] : []),
263 ]
264 // Panels with the flow between them: a rail that runs while a turn (or a consult) does.
265 const column = (ps: Panel[], w: number) => (
266 <Box flexDirection="column" width={w}>
267 {ps.map((p, i) => (
268 <Box key={p.id} flexDirection="column">
269 {i > 0 && p.flow && ps[i - 1].id !== 'agents' ? rail(ui, e, `link-${p.id}`, p.flow.active, p.flow.color, w) : null}
270 {p.draw(w)}
271 </Box>
272 ))}
273 </Box>
274 )
275 const left = panels.filter(p => ['main', 'architect', 'gate'].includes(p.id))
276 const right = panels.filter(p => !['main', 'architect', 'gate'].includes(p.id))
277 const legend = [
278 { label: 'main', color: C.main },
279 ...(on('agentsProgress') ? [{ label: 'agents', color: C.agent }] : []),
280 ...(on('permissionGate') ? [{ label: gateLabel.toLowerCase(), color: C.gate }] : []),
281 ...(showArch ? [{ label: archLabel.toLowerCase(), color: C.arch }] : []),
282 ]
283 return (
284 <Box flexDirection="column" width={W}>
285 {line(ui, [
286 W >= 40 ? { spans: [{ text: 'COCKPIT', bold: true }, { text: ' ·', color: C.dim, bold: true }] } : null,
287 { spans: [{ text: prettyModel(deckModel).toUpperCase(), color: C.main, bold: true }, { text: deckRunning ? ' WORKS' : ' IDLE', bold: true }] },
288 showArch ? { spans: [{ text: '· ', color: C.dim, bold: true }, { text: archLabel, color: C.arch, bold: true }, { text: archAdvising() ? ' ADVISING' : ' ON CALL', bold: true }] } : null,
289 ], W, 1, 'center')}
290 {line(ui, legend.map((l, i): Piece => ({ key: `l${i}`, spans: [{ text: '■', color: l.color }, { text: ` ${l.label}`, dim: true }] })), W, 2, 'center')}
291 {isWide ? (
292 <Box columnGap={2}>
293 {column(left, colW)}
294 {column(right, colW)}
295 </Box>
296 ) : (
297 column(panels, W)
298 )}
299 {on('sessionLog') ? logPanel(ui, e, W) : null}
300 {on('agentsProgress') ? agentsSvgLanes(ui, e, now) : null}
301 {!panels.length && !on('sessionLog') ? <Text dimColor>Every cockpit mod is off.</Text> : null}
302 </Box>
303 )
304}
305
306// ===== agents-progress =====
307type Agent = {
308 id: string
309 agentId?: string
310 type: string
311 desc: string
312 model?: string
313 startedAt: number
314 endedAt?: number
315 failed?: boolean
316 steps: number
317 ctx: number
318 out: number
319 lastStop?: string | null
320 tools: { text: string; isError: boolean }[]
321 answer?: string
322 bg?: boolean // run_in_background
323 wf?: boolean // started by a workflow script's agent()
324}
325// Background work of the main loop or a subagent: shells, monitors, and wakeups (CronCreate, ScheduleWakeup, /loop).
326type BgTask = { id: string; kind: 'shell' | 'monitor' | 'wakeup'; text: string; who: string; startedAt: number; endedAt?: number; isStopped?: boolean; fireAt?: number; recurring?: boolean }
327
328let agents: Agent[] = []
329let subTools = 0 // tool calls made inside subagents
330let cost = 0
331let ctxTokens = 0
332let showFinished = true
333let agentsExpanded: string | null = null // a card opened with 1-6
334type Todo = { id?: string; content: string; status: string; activeForm?: string }
335let todos: Todo[] = [] // main session's TodoWrite list, or its TaskCreate/TaskUpdate tasks (keyed by id)
336// A subagent's turn.complete can come before its agent.spawn returns: kept here until the card learns its agentId.
337const agentDone = new Map<string, { at: number; failed: boolean; answer: string }>()
338let bgTasks: BgTask[] = []
339let mainTool = '' // the main loop's latest tool call while it runs
340let mainEndedAt: number | null = null
341
342function agentsProgressRedraw($: any) { return $.ui.invalidate('ui.render') }
343const running = () => agents.filter(a => a.endedAt === undefined)
344const finished = () => agents.filter(a => a.endedAt !== undefined)
345const pctDone = () => (agents.length ? (finished().length / agents.length) * 100 : 0)
346const agentColor = (a: Agent) => (a.endedAt === undefined ? C.agent : a.failed ? C.warn : C.gate)
347const agentGlyph = (a: Agent) => (a.endedAt === undefined ? '◐' : a.failed ? '✗' : '✓')
348// A one-shot wakeup is over once its time passes; a recurring cron stays until deleted.
349const bgLive = (now: number) => bgTasks.filter(t => t.endedAt === undefined && (t.kind !== 'wakeup' || t.recurring || (t.fireAt ?? 0) > now))
350const bgShown = (now: number) => [...bgLive(now), ...bgTasks.filter(t => t.endedAt !== undefined).slice(-3).reverse()]
351const agentName = (agentId: string | undefined) => {
352 if (!agentId) return 'main'
353 const a = agents.find(x => x.agentId === agentId)
354 return a ? shorten(a.desc || a.type, 14) : 'agent'
355}
356
357async function agentsProgressSync($: any) {
358 const u = await $.session.usage()
359 cost = u.cost?.usd ?? cost
360 ctxTokens = u.context.tokens ?? ctxTokens
361 agentsProgressRedraw($)
362}
363
364export async function agentsProgressSessionStart($: any, e: any, next: any) {
365 await $.command.register({ name: 'agents-info', description: 'Show the subagents in the cockpit pane' })
366 $.clock.every(1000, () => (running().length || bgTasks.some(t => t.endedAt === undefined)) && agentsProgressRedraw($)) // elapsed-time tick where clocks cannot run
367 $.clock.every(8000, () => running().length && void agentsProgressSync($))
368 return next(e)
369}
370
371export async function agentsProgressCommandRunAgentsInfo($: any) {
372 showFinished = true
373 await cockpitOpen($)
374 return { text: 'Agents panel opened.' }
375}
376
377export async function agentsProgressAgentSpawn($: any, e: any, next: any) {
378 const a: Agent = { id: e.tool_use_id, type: e.subagentType, desc: e.description, startedAt: await $.clock.now(), steps: 0, ctx: 0, out: 0, tools: [], bg: e.background === true, wf: e.workflow !== undefined }
379 agents = [...agents, a].slice(-50)
380 agentsProgressRedraw($)
381 const r = await next(e)
382 a.model = r.model
383 if (r.deny !== undefined || !r.agentId) {
384 // Refused, or a remote workflow agent with no local loop: nothing more will arrive for it.
385 a.endedAt = await $.clock.now()
386 a.failed = r.deny !== undefined
387 } else {
388 a.agentId = r.agentId
389 const d = agentDone.get(r.agentId)
390 if (d) Object.assign(a, { endedAt: d.at, failed: d.failed, answer: d.answer })
391 agentDone.delete(r.agentId)
392 }
393 void agentsProgressSync($)
394 return r
395}
396
397// A subagent's model requests: its context is the latest step's whole input; output adds up.
398export async function* agentsProgressTurnStep($: any, e: any, next: any) {
399 if (e.agentId === undefined) return yield* next(e)
400 const result = yield* next(e)
401 const a = agents.find(x => x.agentId === e.agentId)
402 if (a) {
403 const u = result?.usage ?? {}
404 const ctx = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
405 Object.assign(a, { model: a.model || e.model, steps: a.steps + 1, ctx: ctx > 0 ? ctx : a.ctx, out: a.out + (u.output_tokens ?? 0), lastStop: result?.stopReason ?? null })
406 if (a.endedAt !== undefined) a.endedAt = undefined // a step after its end: resumed (SendMessage)
407 agentsProgressRedraw($)
408 }
409 return result
410}
411
412export async function agentsProgressTurnComplete($: any, e: any, next: any) {
413 const done = await next(e)
414 if (e.agentId === undefined) {
415 mainTool = ''
416 mainEndedAt = await $.clock.now()
417 } else {
418 const at = await $.clock.now()
419 const failed = e.reason !== 'answer'
420 const answer = shorten(e.answer ?? '', 400)
421 const a = agents.find(x => x.agentId === e.agentId)
422 if (a) Object.assign(a, { endedAt: at, failed, answer })
423 else agentDone.set(e.agentId, { at, failed, answer })
424 agentsProgressRedraw($)
425 }
426 return done
427}
428
429// The tool shows as the loop's current one while it runs; todos, tasks and background work are read from its result.
430export async function agentsProgressToolCall($: any, e: any, next: any) {
431 const tool = String(e.tool)
432 const isMain = e.agentId === undefined
433 const step = { text: describeInput(tool, e), isError: false }
434 const a = isMain ? undefined : agents.find(x => x.agentId === e.agentId)
435 if (!isMain) subTools += 1
436 if (a) a.tools = [...a.tools, step].slice(-3)
437 if (isMain) mainTool = step.text
438 if (isMain && tool === 'TodoWrite' && Array.isArray(e.todos)) todos = e.todos
439 agentsProgressRedraw($)
440 const r = await next(e)
441 step.isError = r.deny !== undefined || r.isError === true
442 if (isMain && mainTool === step.text) mainTool = ''
443 if (isMain && !step.isError && tool === 'TaskCreate' && r.result?.task?.id !== undefined) {
444 todos = [...todos, { id: String(r.result.task.id), content: e.subject, status: 'pending', activeForm: e.activeForm }]
445 } else if (isMain && !step.isError && tool === 'TaskUpdate') {
446 todos = (e.status === 'deleted'
447 ? todos.filter(t => t.id !== e.taskId)
448 : todos.map(t => (t.id === e.taskId ? { ...t, content: e.subject ?? t.content, status: e.status ?? t.status, activeForm: e.activeForm ?? t.activeForm } : t)))
449 }
450 if (!step.isError) await agentsProgressBackground($, e, r.result ?? {})
451 agentsProgressRedraw($)
452 return r
453}
454
455async function agentsProgressBackground($: any, e: any, res: any) {
456 const at = await $.clock.now()
457 const who = agentName(e.agentId)
458 const add = (t: BgTask) => { bgTasks = [...bgTasks.filter(x => x.id !== t.id), t].slice(-20) }
459 if (e.tool === 'Bash' && res.backgroundTaskId) add({ id: String(res.backgroundTaskId), kind: 'shell', text: e.description || e.command || 'shell', who, startedAt: at })
460 else if (e.tool === 'Monitor' && res.taskId) add({ id: String(res.taskId), kind: 'monitor', text: e.description || e.command || 'monitor', who, startedAt: at })
461 else if (e.tool === 'CronCreate' && res.id) add({ id: `cron:${res.id}`, kind: 'wakeup', text: `${res.humanSchedule ?? e.cron} · ${e.prompt ?? ''}`, who, startedAt: at, fireAt: res.nextFireAt, recurring: res.recurring === true })
462 else if (e.tool === 'CronDelete') bgTasks = bgTasks.filter(t => t.id !== `cron:${e.id}`)
463 else if (e.tool === 'ScheduleWakeup') {
464 bgTasks = bgTasks.filter(t => t.id !== 'wakeup') // one dynamic /loop wakeup at a time
465 if (!e.stop && res.scheduledFor) add({ id: 'wakeup', kind: 'wakeup', text: e.reason || e.prompt || 'wakeup', who, startedAt: at, fireAt: res.scheduledFor })
466 } else if (e.tool === 'TaskStop') {
467 const id = String(e.task_id ?? e.shell_id ?? '')
468 bgTasks = bgTasks.map(t => (t.id === id && t.endedAt === undefined ? { ...t, endedAt: at, isStopped: true } : t))
469 }
470}
471
472// Stop lists the background work still in flight: a shell or monitor missing from it has ended, a cron was deleted.
473// shortcut: an ended task shows as done whether it passed or failed; read the task-notification status if that matters.
474export async function agentsProgressStop($: any, e: any, next: any) {
475 const at = await $.clock.now()
476 if (Array.isArray(e.background_tasks)) {
477 const live = new Set(e.background_tasks.map((t: any) => String(t.id)))
478 bgTasks = bgTasks.map(t => (t.kind !== 'wakeup' && t.endedAt === undefined && !live.has(t.id) ? { ...t, endedAt: at } : t))
479 }
480 if (Array.isArray(e.session_crons)) {
481 const crons = new Set(e.session_crons.map((c: any) => `cron:${c.id}`))
482 bgTasks = bgTasks.filter(t => !t.id.startsWith('cron:') || crons.has(t.id))
483 }
484 agentsProgressRedraw($)
485 return next(e)
486}
487
488const todoTitle = () => {
489 const cur = todos.find(t => t.status === 'in_progress')
490 return { cur, title: cur ? cur.activeForm || cur.content : 'Next: ' + (todos.find(t => t.status !== 'completed')?.content ?? '') }
491}
492
493export async function agentsProgressUiRenderAbovePrompt($: any, e: any, next: any) {
494 if (e.props.hasSurvey) return next(e)
495 const live = running()
496 const nested = await below(next, e)
497 if (live.length) {
498 const open = () => cockpitOpen($)
499 quiet({
500 key: 'agents',
501 text: `${live.length} agent${live.length > 1 ? 's' : ''} running`,
502 onPress: open,
503 spec: { title: 'Agents', tone: 'info', busy: true, pct: pctDone(), pctLabel: `${live.length} running · ${finished().length}/${agents.length}` },
504 })
505 }
506 const bg = bgLive(await $.clock.now()).length
507 if (bg) quiet({ key: 'bg', text: `${bg} background`, onPress: () => cockpitOpen($) })
508 const done = todos.filter(t => t.status === 'completed').length
509 if (todos.length > 0 && done < todos.length) {
510 const { title } = todoTitle()
511 quiet({ key: 'todos', text: `${title.length > 40 ? `${title.slice(0, 39)}…` : title} ${done}/${todos.length}` })
512 }
513 return nested
514}
515
516// The main loop's row: working or idle, the tool it runs now, its requests and the turn's clock.
517function agentsProgressMainRow(ui: any, e: any, w: number, now: number) {
518 const { Box, Text } = ui
519 return (
520 <Box columnGap={1} width={w}>
521 <Text color={C.main}>{deckRunning ? '◐' : '○'}</Text>
522 <Text color={C.main} bold>main</Text>
523 <Box flexGrow={1} flexShrink={1}><Text dimColor={!deckRunning} wrap="truncate">{deckRunning ? mainTool || 'thinking' : 'idle'}</Text></Box>
524 <Box flexShrink={0}><Text dimColor>{`${deckSteps} req`}</Text></Box>
525 {deckTurn.startedAt ? <Box flexShrink={0}>{liveClock(ui, e, 'main-clock', deckTurn.startedAt, now, deckRunning ? null : mainEndedAt, C.dim)}</Box> : null}
526 </Box>
527 )
528}
529
530// Background shells, monitors and wakeups: the live ones, then the last three that ended.
531function agentsProgressBgRows(ui: any, e: any, w: number, now: number) {
532 const { Box, Text } = ui
533 const shown = bgShown(now)
534 return (
535 <Box flexDirection="column" width={w} marginTop={1}>
536 <Text bold wrap="truncate">{`background · ${bgLive(now).length} running`}</Text>
537 {shown.length ? null : <Text color={C.faint}>no background tasks</Text>}
538 {shown.map(t => (
539 <Box key={`bg-${t.id}`} columnGap={1}>
540 <Text color={t.endedAt === undefined ? C.agent : t.isStopped ? C.warn : C.gate}>{t.endedAt === undefined ? '◐' : t.isStopped ? '✗' : '✓'}</Text>
541 {w >= 40 ? <Box width={7} flexShrink={0}><Text color={C.dim}>{t.kind}</Text></Box> : null}
542 <Box flexGrow={1} flexShrink={1}><Text dimColor={t.endedAt !== undefined} wrap="truncate">{t.who === 'main' ? t.text : `${t.text} · ${t.who}`}</Text></Box>
543 <Box flexShrink={0}>
544 {t.kind !== 'wakeup' ? liveClock(ui, e, `bg-clock-${t.id}`, t.startedAt, now, t.endedAt ?? null, C.dim)
545 : <Text dimColor>{t.fireAt && t.fireAt > now ? `in ${fmtTimer(t.fireAt - now)}` : t.recurring ? 'recurring' : ''}</Text>}
546 </Box>
547 </Box>
548 ))}
549 </Box>
550 )
551}
552
553const agentTag = (a: Agent) => `${a.type}${a.wf ? ' · wf' : a.bg ? ' · bg' : ''}`
554const agentNow = (a: Agent) => (a.tools.length ? `· ${a.tools[a.tools.length - 1].text}` : '')
555
556// Cards side by side while they fit (maxCards, 20 columns each), swimlanes on one time axis beyond that.
557function agentsProgressPanel($: any, ui: any, e: any, w: number, now: number) {
558 const { Box, Text, Button } = ui
559 const live = running()
560 const list = showFinished ? agents : live
561 const fit = Math.max(1, Math.min(cockpitCfg.maxCards, Math.floor((w + 1) / 21)))
562 const useLanes = list.length > fit
563 const expand = (id: string) => () => { agentsExpanded = agentsExpanded === id ? null : id; agentsProgressRedraw($) }
564 const first = agents.length ? Math.min(...agents.map(a => a.startedAt)) : now
565 const last = live.length ? now : Math.max(first, ...agents.map(a => a.endedAt ?? 0))
566 const done = todos.filter(t => t.status === 'completed').length
567 const { cur, title } = todoTitle()
568 const header = (
569 <Box justifyContent="space-between" width={w}>
570 <Text bold wrap="truncate">{w < 40 ? `agents · ${live.length}/${agents.length}` : `agents · ${live.length} running · ${agents.length} total`}</Text>
571 {list.length ? <Box flexShrink={0}><Text color={C.faint}>{`1-${Math.min(list.length, 6)}${w < 40 ? '' : ' expand'}`}</Text></Box> : null}
572 </Box>
573 )
574 const shown = useLanes ? list.slice(-6) : list.slice(-fit)
575 let body: unknown
576 if (!list.length) body = <Text color={C.faint}>{agents.length ? 'all finished · a shows them' : 'no subagents yet'}</Text>
577 else if (useLanes) {
578 const labelW = Math.min(17, Math.max(7, w - 17))
579 const barW = Math.max(4, w - 11 - labelW)
580 const start = Math.min(...shown.map(a => a.startedAt), now)
581 const span = Math.max(1, now - start)
582 body = (
583 <Box flexDirection="column">
584 {list.length > shown.length ? <Text color={C.faint}>{`+${list.length - shown.length} earlier`}</Text> : null}
585 {shown.map((a, i) => {
586 const from = Math.min(barW, Math.floor(((a.startedAt - start) / span) * barW))
587 const to = Math.min(barW, Math.max(from + 1, Math.ceil((((a.endedAt ?? now) - start) / span) * barW)))
588 return (
589 <Box key={`lane-${a.id}`} flexDirection="column">
590 <Box columnGap={1}>
591 <Text color={agentColor(a)}>{agentGlyph(a)}</Text>
592 <Box width={labelW} flexShrink={0}><Button key={`card-${a.id}`} plain hotkey={String(i + 1)} label={shorten(a.desc || a.type, labelW - 3)} onPress={expand(a.id)} /></Box>
593 <Box flexShrink={0}>
594 <Text>
595 <Text color={C.faint}>{'·'.repeat(from)}</Text>
596 <Text color={agentColor(a)}>{'━'.repeat(to - from)}</Text>
597 <Text color={C.faint}>{'·'.repeat(barW - to)}</Text>
598 </Text>
599 </Box>
600 {liveClock(ui, e, `lane-clock-${a.id}`, a.startedAt, now, a.endedAt ?? null, C.dim)}
601 </Box>
602 {a.endedAt === undefined && agentNow(a) && w >= 40 ? <Box paddingLeft={2}><Text color={C.faint} wrap="truncate">{agentNow(a)}</Text></Box> : null}
603 </Box>
604 )
605 })}
606 </Box>
607 )
608 } else {
609 const cardW = Math.max(20, Math.floor((w - (shown.length - 1)) / shown.length))
610 const centers = shown.map((_, i) => i * (cardW + 1) + Math.floor(cardW / 2))
611 body = (
612 <Box flexDirection="column">
613 {rail(ui, e, 'fan-out', live.length > 0, C.agent, w, centers)}
614 <Box columnGap={1}>
615 {shown.map((a, i) => (
616 <Box key={`c-${a.id}`} flexDirection="column" borderStyle={agentsExpanded === a.id ? 'double' : 'round'} borderColor={a.lastStop === 'max_tokens' ? C.warn : C.agent} borderDimColor={a.endedAt !== undefined} width={cardW} paddingX={1}>
617 <Button key={`card-${a.id}`} plain hotkey={String(i + 1)} label={shorten(a.desc || a.type, cardW - 7)} onPress={expand(a.id)} />
618 <Text color={C.dim} wrap="truncate">{a.model ? `${agentTag(a)} · ${prettyModel(a.model)}` : agentTag(a)}</Text>
619 <Text dimColor wrap="truncate">{a.steps > 0 ? `ctx ${fmtTok(a.ctx)} · out ${fmtTok(a.out)} · ${a.steps} st` : 'starting…'}</Text>
620 <Text color={C.faint} wrap="truncate">{agentNow(a) || '·'}</Text>
621 <Box columnGap={1}>
622 <Text color={a.lastStop === 'max_tokens' ? C.warn : agentColor(a)}>{cardW >= 26 ? `${agentGlyph(a)} ${a.lastStop === 'max_tokens' ? 'max_tokens' : a.endedAt === undefined ? 'working' : a.failed ? 'failed' : 'done'}` : agentGlyph(a)}</Text>
623 <Box flexShrink={0}>{liveClock(ui, e, `card-clock-${a.id}`, a.startedAt, now, a.endedAt ?? null, C.dim)}</Box>
624 </Box>
625 </Box>
626 ))}
627 </Box>
628 {rail(ui, e, 'merge', live.length > 0, C.agent, w, centers, true)}
629 </Box>
630 )
631 }
632 const x = agents.find(a => a.id === agentsExpanded)
633 return (
634 <Box flexDirection="column" width={w}>
635 {agentsProgressMainRow(ui, e, w, now)}
636 {todos.length && done < todos.length ? line(ui, [{ spans: [{ text: cur ? '◐ ' : '○ ', color: C.agent }, { text: title }], fill: true }, { spans: gaugeSpans((done / todos.length) * 100, 6, C.agent, `${done}/${todos.length}`) }], w, 2) : null}
637 <Box marginTop={1}>{header}</Box>
638 {body}
639 {x ? (
640 <Box flexDirection="column" borderStyle="single" borderColor={C.agent} paddingX={1} width={w}>
641 <Text bold wrap="wrap">{x.desc || x.type}</Text>
642 <Text dimColor wrap="truncate">{`${x.type} · ${prettyModel(x.model ?? '')} · ${x.endedAt === undefined ? 'working' : x.failed ? 'failed' : 'done'} · ${x.steps} steps`}</Text>
643 {x.tools.length === 0 ? <Text color={C.faint}>no tool calls yet</Text> : null}
644 {x.tools.map((n, i) => <Box key={`t${i}`}><Text color={n.isError ? C.warn : undefined} wrap="truncate">{`${n.isError ? '✗' : '·'} ${n.text}`}</Text></Box>)}
645 {x.answer ? <Text dimColor wrap="wrap">{`» ${shorten(x.answer, 240)}`}</Text> : null}
646 </Box>
647 ) : null}
648 {line(ui, [
649 { spans: [{ text: 'cost ', dim: true }, { text: `≈${fmtCost(cost)}`, bold: true }] },
650 { spans: [{ text: 'ctx ', dim: true }, { text: fmtTok(ctxTokens), bold: true }] },
651 { spans: [{ text: 'time ', dim: true }, { text: fmtTimer(last - first), bold: true }] },
652 subTools ? { spans: [{ text: `${subTools} tool calls in subagents`, dim: true }] } : null,
653 ], w, 2)}
654 {finished().length ? <Button key="fin" plain hotkey="a" label={`${showFinished ? '▾' : '▸'} finished · ${finished().length}`} onPress={() => { showFinished = !showFinished; agentsProgressRedraw($) }} /> : null}
655 {agentsProgressBgRows(ui, e, w, now)}
656 </Box>
657 )
658}
659
660// The desktop and mobile also draw the agents on an SVG time axis under the panels.
661function agentsSvgLanes(ui: any, e: any, now: number) {
662 if (!isRich(ui, e) || !agents.length) return null
663 const shown = agents.slice(-10)
664 const rowH = 18
665 const pxW = 520
666 const start = Math.min(...shown.map(a => a.startedAt), now)
667 const span = Math.max(1, now - start)
668 const rects = shown
669 .map((a, i) => {
670 const x = 150 + ((a.startedAt - start) / span) * (pxW - 160)
671 const wpx = Math.max(3, (((a.endedAt ?? now) - a.startedAt) / span) * (pxW - 160))
672 const fill = a.endedAt === undefined ? SVG_COLORS.running : a.failed ? SVG_COLORS.failed : SVG_COLORS.done
673 return `<text x="4" y="${i * rowH + 13}" font-family="${MONO}" font-size="11" fill="${SVG_COLORS.label}">${esc(shorten(a.desc || a.type, 22))}</text><rect x="${x}" y="${i * rowH + 4}" width="${wpx}" height="10" rx="3" fill="${fill}"/>`
674 })
675 .join('')
676 const svgH = shown.length * rowH + 4
677 // No width or height on the element: it takes the markup's own width up to the pane's and scales down to fit.
678 return <ui.Svg key="lanes" source={`<svg xmlns="http://www.w3.org/2000/svg" width="${pxW}" height="${svgH}" viewBox="0 0 ${pxW} ${svgH}">${rects}</svg>`} alt={`${agents.length} agents on a time axis`} />
679}
680
681// ===== cache-keeper =====
682const TTL = 60 * 60_000 // main cache lifetime; ponytail: 1h only, read promptCacheTtl if 5m billing matters
683const PING_AFTER = 50 * 60_000
684const WARN_BEFORE = 5 * 60_000
685const MIN_GUARD_TOKENS = 50_000
686const DEFAULT_WINDOW = 6 * 3_600_000
687
688// $/MTok: [1h cache write, cache read]. ponytail: two rows, extend the table per model.
689const price = (model: string) => (/fable/i.test(model) ? [20, 0.25] : [4, 0.2])
690
691const parseDuration = (s: string) => {
692 const m = /^(?:(\d+)h)?(?:(\d+)m)?$/.exec(s.trim())
693 return m && (m[1] || m[2]) ? (Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0)) * 60_000 : undefined
694}
695
696const mins = (ms: number) => `${Math.max(0, Math.round(ms / 60_000))}m`
697
698let lastTouch = 0 // last time the cache was written or read
699let warnedCold = false
700let warnedSoon = false
701let warmUntil = 0
702let lastPing = ''
703let cacheKeeperTokens = 0
704let cacheKeeperRates = [4, 0.2]
705
706// Cost in dollars of sending the whole context at a $/MTok rate: [0] cold (cache write), [1] warm (cache read).
707const cacheCost = (i: 0 | 1) => fmtCost((cacheKeeperTokens * cacheKeeperRates[i]) / 1e6)
708
709async function cacheKeeperSync($: any) {
710 const { context } = await $.session.usage()
711 cacheKeeperTokens = context.tokens ?? cacheKeeperTokens
712 cacheKeeperRates = price(await $.session.model())
713 $.ui.invalidate('ui.render')
714}
715
716async function cacheKeeperTouch($: any) {
717 lastTouch = await $.clock.now()
718 warnedCold = false
719 warnedSoon = false
720 await cacheKeeperSync($)
721}
722
723export async function cacheKeeperSessionStart($: any, e: any, next: any) {
724 await $.command.register({ name: 'keepwarm', description: 'Keep the prompt cache warm: /keepwarm [90m|2h|off|status]' })
725 await $.command.register({ name: 'cache-tax', description: 'Show prompt cache state and rewrite cost' })
726 lastTouch = await $.clock.now()
727 void cacheKeeperSync($)
728
729 $.clock.every(30_000, async () => {
730 const now = await $.clock.now()
731 const idle = now - lastTouch
732 if (lastTouch && TTL - idle < WARN_BEFORE && TTL - idle > 0 && !warnedSoon && warmUntil < now) {
733 warnedSoon = true
734 $.ui.toast('Cache goes cold in under 5 minutes. /keepwarm to hold it.')
735 }
736 if (warmUntil > now && idle >= PING_AFTER && idle < TTL) {
737 const r = await $.model.fork({ prompt: 'Reply with the single word: ok' })
738 if (r.isAnswered) {
739 lastTouch = now
740 lastPing = `read ${fmtTok(r.usage.cache_read_input_tokens)}`
741 if (r.usage.cache_read_input_tokens === 0) {
742 warmUntil = 0 // ping wrote instead of read: cache was already cold, stop paying
743 lastPing += ', cold: stopped'
744 }
745 } else if (r.reason !== 'nothing-to-fork') {
746 lastPing = `ping failed: ${r.reason}`
747 }
748 }
749 $.ui.invalidate('ui.render')
750 })
751 return next(e)
752}
753
754export async function cacheKeeperCommandRunKeepwarm($: any, e: any) {
755 try {
756 const now = await $.clock.now()
757 const arg = (e.args ?? "").trim()
758 if (arg === 'off') {
759 warmUntil = 0
760 $.ui.invalidate('ui.render')
761 return { text: 'keepwarm off.' }
762 }
763 if (arg === 'status') {
764 return { text: warmUntil > now ? `keepwarm armed ${mins(warmUntil - now)} more. Last ping: ${lastPing || 'none'}` : 'keepwarm off.' }
765 }
766 const window = arg === '' ? DEFAULT_WINDOW : parseDuration(arg)
767 if (window === undefined) return { text: 'Usage: /keepwarm [90m|2h30m|off|status]' }
768 warmUntil = now + window
769 $.ui.invalidate('ui.render')
770 return { text: `keepwarm armed for ${mins(window)}. Pings are cheap cache reads, but they do cost tokens.` }
771 } catch (err) {
772 return { text: `keepwarm failed: ${(err as Error).message}` }
773 }
774}
775
776export async function cacheKeeperCommandRunCacheTax($: any) {
777 await cacheKeeperSync($)
778 const now = await $.clock.now()
779 const left = TTL - (now - lastTouch)
780 return {
781 text: `cache ${left > 0 ? `warm ${mins(left)} left` : 'cold'} | context ${cacheKeeperTokens} tok | cold send ≈ ${cacheCost(0)} vs warm ${cacheCost(1)}`,
782 }
783}
784
785export async function cacheKeeperPromptSubmit($: any, e: any, next: any) {
786 const now = await $.clock.now()
787 const isSlash = e.text.trimStart().startsWith('/')
788 const isCold = lastTouch > 0 && now - lastTouch >= TTL
789 if (isCold && !warnedCold && !isSlash && e.origin.kind !== 'plugin') {
790 await cacheKeeperSync($)
791 if (cacheKeeperTokens >= MIN_GUARD_TOKENS) {
792 warnedCold = true
793 let choice = ''
794 try {
795 choice = await $.ui.ask(`The cache went cold ${mins(now - lastTouch - TTL)} ago. Sending rewrites up to ${fmtTok(cacheKeeperTokens)} tokens ≈ ${cacheCost(0)} (warm: ${cacheCost(1)}). Continue here or start a new session?`, {
796 header: 'Cache cold',
797 options: ['Continue here', 'New session'],
798 })
799 } catch {
800 return { drop: 'cache-keeper: cache is cold, prompt not sent. Send again to continue here.' }
801 }
802 if (choice === 'New session') {
803 // command.run from inside prompt.submit would wait on this very turn: clear once the hook has returned
804 $.clock.after(0, () => $.command.run({ command: 'clear', args: '' }))
805 return { drop: 'cache-keeper: started a new session. Send your prompt again.' }
806 }
807 }
808 }
809 return next(e)
810}
811
812export async function cacheKeeperTurnComplete($: any, e: any, next: any) {
813 if (e.agentId === undefined) await cacheKeeperTouch($)
814 return next(e)
815}
816
817function cacheKeeperToggle($: any, keeping: boolean) {
818 return $.command.run({ command: 'keepwarm', args: keeping ? 'off' : '' })
819}
820
821export async function cacheKeeperUiRenderAbovePrompt($: any, e: any, next: any) {
822 if (e.props.hasSurvey || lastTouch === 0) return next(e)
823 const now = await $.clock.now()
824 const left = TTL - (now - lastTouch)
825 const warm = left > 0
826 const calm = left >= WARN_BEFORE // the band shows only when the cache is about to go cold, or already is
827 const keeping = warmUntil > now
828 const spec: BandSpec = {
829 title: warm ? `Cache warm · ${mins(left)} left` : 'Cache cold',
830 tone: calm ? 'ok' : !warm ? 'err' : 'warn',
831 pct: warm ? Math.max(0, (left / TTL) * 100) : 100,
832 busy: !warm,
833 detail: warm ? `${fmtTok(cacheKeeperTokens)} ctx · next send ${cacheCost(1)}` : `${fmtTok(cacheKeeperTokens)} ctx · next send rewrites it ${cacheCost(0)} (warm ${cacheCost(1)})`,
834 chips: keeping ? [`keepwarm ${mins(warmUntil - now)}`] : [],
835 right: keeping ? lastPing || 'no ping yet' : undefined,
836 buttons: [{ key: 'kw', label: keeping ? 'Stop keepwarm' : 'Keep warm', onPress: () => void cacheKeeperToggle($, keeping) }],
837 }
838 const nested = await below(next, e)
839 if (!calm) return band($.ui.resolve(e), e, nested, spec)
840 quiet({ key: 'cache', text: `Cache ${mins(left)}` })
841 return nested
842}
843
844function cacheKeeperPaneRow($: any, ui: any, w: number, now: number) {
845 if (lastTouch === 0) return null
846 const { Box, Button } = ui
847 const left = TTL - (now - lastTouch)
848 const keeping = warmUntil > now
849 const color = left >= WARN_BEFORE ? C.gate : left > 0 ? C.amber : C.warn
850 return (
851 <Box key="cache" columnGap={1}>
852 <Box flexGrow={1} flexShrink={1}>
853 {line(ui, [
854 { spans: left > 0 ? gaugeSpans((left / TTL) * 100, 5, color, 'cache') : [{ text: 'cache ', dim: true }, { text: 'cold', color: C.warn, bold: true }] },
855 { spans: [{ text: left > 0 ? `${mins(left)} · next ${cacheCost(1)}` : `next send ${cacheCost(0)} (warm ${cacheCost(1)})`, dim: true }] },
856 keeping ? { spans: [{ text: `keepwarm ${mins(warmUntil - now)}${lastPing ? ` · ${lastPing}` : ''}`, color: C.cleared }] } : null,
857 ], w - 18, 2)}
858 </Box>
859 <Button key="kw" plain hotkey="k" label={keeping ? 'stop warm' : 'keep warm'} onPress={() => void cacheKeeperToggle($, keeping)} />
860 </Box>
861 )
862}
863
864// ===== context-health =====
865const HANDOFF_FILE = '.claude/handoff.md'
866const HANDOFF_PROMPT = `Write a handoff brief to ${HANDOFF_FILE} so a fresh session can continue this work: goal, decisions made, files touched, current state, exact next steps. Keep it under 60 lines. Reply "handoff written" when done.`
867
868let percent = 0
869let contextHealthTokens = 0
870let windowSize = 0
871let contextHealthRates: { kind: string; percentUsed: number }[] = []
872let threshold = 50 // ponytail: stored per session; persist via $.store if wanted across sessions
873let auto = false
874let handingOff = false
875let compactions = 0 // the main conversation's compactions this session (⟲)
876
877let lastRefresh = 0
878let turnNo = 0
879let speed = 0 // last measured output tok/s of the main session
880let costNow = 0
881let costAtStart = 0
882let bandHidden = false // closed with ×, for the rest of the session
883
884async function refresh($: any, force = false) {
885 const now = await $.clock.now()
886 if (!force && now - lastRefresh < 2000) return
887 lastRefresh = now
888 const { context, rateLimits, cost } = await $.session.usage()
889 costNow = cost?.usd ?? costNow
890 percent = Math.round(context.percent ?? 0)
891 contextHealthTokens = context.tokens ?? 0
892 windowSize = context.window ?? 0
893 contextHealthRates = rateLimits ?? []
894 $.ui.invalidate('ui.render')
895}
896
897function startHandoff($: any) {
898 handingOff = true
899 // the host refuses a submit made from inside the /ctx-handoff command turn: send it from a later tick
900 $.clock.after(0, () => $.prompt.submit({ text: HANDOFF_PROMPT }))
901}
902
903export async function contextHealthSessionStart($: any, e: any, next: any) {
904 await $.command.register({ name: 'ctx-handoff', description: 'Write a handoff brief, clear, and continue in a fresh context' })
905 await $.command.register({ name: 'autohandoff', description: 'Auto handoff at a context %: /autohandoff [percent|off]' })
906 return next(e)
907}
908
909export async function contextHealthTurnStart($: any, e: any, next: any) {
910 if (e.agentId === undefined) {
911 turnNo += 1
912 costAtStart = (await $.session.usage()).cost?.usd ?? costNow
913 costNow = costAtStart
914 }
915 return next(e)
916}
917
918// Times each main-session response from its first chunk to its stop usage; stubs and instant bursts are dropped.
919export async function* contextHealthTurnStep($: any, e: any, next: any) {
920 if (e.agentId !== undefined) return yield* next(e)
921 let startedAt: number | null = null
922 return yield* tap(next(e), async (chunk: any) => {
923 if (startedAt === null) startedAt = await $.clock.now()
924 if (chunk.kind === 'stop' && chunk.usage) {
925 const secs = ((await $.clock.now()) - startedAt) / 1000
926 const rate = chunk.usage.output_tokens / secs
927 if (chunk.usage.output_tokens >= 50 && secs >= 1 && rate <= 400) speed = Math.round(rate)
928 }
929 })
930}
931
932export async function contextHealthCommandRunHandoff($: any) {
933 startHandoff($)
934 return { text: 'Writing handoff…' }
935}
936
937export async function contextHealthCommandRunAutohandoff(_$: any, e: any) {
938 const n = Number((e.args ?? "").trim())
939 if ((e.args ?? "").trim() === 'off') auto = false
940 else {
941 auto = true
942 if (n >= 10 && n <= 95) threshold = n
943 }
944 return { text: auto ? `Auto handoff at ${threshold}% context.` : 'Auto handoff off.' }
945}
946
947// Keep the band live while context grows (tool results) or shrinks (compact/clear).
948export async function contextHealthToolCall($: any, e: any, next: any) {
949 const done = await next(e)
950 if (e.agentId === undefined) await refresh($)
951 return done
952}
953
954export async function contextHealthPromptSubmit($: any, e: any, next: any) {
955 const done = await next(e)
956 await refresh($)
957 return done
958}
959
960export async function contextHealthSessionCompact($: any, e: any, next: any) {
961 const done = await next(e)
962 if (e.agentId === undefined && e.trigger !== 'precompute') compactions += 1
963 return done
964}
965
966export async function contextHealthTurnComplete($: any, e: any, next: any) {
967 if (e.agentId !== undefined) return next(e)
968 const done = await next(e)
969 if (handingOff) {
970 handingOff = false
971 // Clear only when the handoff turn finished and wrote its file: otherwise the context would be lost for nothing.
972 if (e.reason !== 'answer' || !(await $.fs.exists(`${await $.session.cwd()}/${HANDOFF_FILE}`))) {
973 $.ui.toast('Handoff did not finish: context kept.')
974 return done
975 }
976 await $.command.run({ command: 'clear', args: '' })
977 await refresh($, true)
978 await $.prompt.fill({ text: `Read ${HANDOFF_FILE} and continue from there.` })
979 $.ui.toast('Handoff ready: press Enter to continue in the fresh session.')
980 } else {
981 await refresh($, true)
982 if (auto && percent >= threshold) startHandoff($)
983 }
984 return done
985}
986
987const ctxChips = () => [
988 ...(turnNo ? [`turn ${turnNo}`] : []),
989 ...(speed ? [`${speed} tok/s`] : []),
990 ...(costNow ? [`${fmtCost(Math.max(0, costNow - costAtStart))} · ${fmtCost(costNow)}`] : []),
991 ...(auto ? [`auto @${threshold}%`] : []),
992]
993
994export async function contextHealthUiRenderAbovePrompt($: any, e: any, next: any) {
995 if (e.props.hasSurvey || percent === 0 || bandHidden) return next(e)
996 const high = percent >= threshold
997 const limits = contextHealthRates.map(r => `${r.kind.replace('five_hour', '5h').replace('seven_day', '7d')} ${Math.round(r.percentUsed)}%`).join(' · ')
998 const ctxTone = zoneTone(percent, threshold - 10, threshold)
999 const spec: BandSpec = {
1000 title: `Context ${percent}%`,
1001 tone: ctxTone,
1002 pct: percent,
1003 detail: high ? 'quality may drop: hand off or start fresh' : `${fmtTok(contextHealthTokens)} of ${fmtTok(windowSize)} tokens`,
1004 right: limits || undefined,
1005 chips: ctxChips(),
1006 buttons: [
1007 ...(high
1008 ? [
1009 { key: 'h', label: 'Handoff', hotkey: 'h', onPress: () => startHandoff($) },
1010 { key: 'f', label: 'Fresh', hotkey: 'f', plain: true, onPress: () => void $.command.run({ command: 'clear', args: '' }) },
1011 ]
1012 : []),
1013 { key: 'x', label: '×', plain: true, onPress: () => { bandHidden = true; void $.ui.invalidate('ui.render') } },
1014 ],
1015 }
1016 const nested = await below(next, e)
1017 if (ctxTone !== 'ok') return band($.ui.resolve(e), e, nested, spec)
1018 quiet({ key: 'context', text: `Context ${percent}%` })
1019 return nested
1020}
1021
1022function contextHealthPaneRow($: any, ui: any, w: number) {
1023 if (percent === 0) return null
1024 const { Box, Button } = ui
1025 const high = percent >= threshold
1026 const color = percent >= threshold ? C.warn : percent >= threshold - 10 ? C.amber : C.main
1027 return (
1028 <Box key="ctx" flexDirection="column">
1029 {line(ui, [
1030 { spans: gaugeSpans(percent, 10, color, 'ctx') },
1031 { spans: [{ text: `${fmtTok(contextHealthTokens)}/${fmtTok(windowSize)}`, dim: true }] },
1032 compactions ? { spans: [{ text: `⟲${compactions}`, color: C.amber }], lead: 1 } : null,
1033 ], w - 4)}
1034 {ctxChips().length ? line(ui, ctxChips().map((c, i): Piece => ({ key: `k${i}`, spans: [{ text: i ? `· ${c}` : c, dim: true }] })), w - 4) : null}
1035 {high ? (
1036 <Box columnGap={1}>
1037 <Box flexGrow={1}>{line(ui, [{ spans: [{ text: 'quality may drop: hand off or start fresh', color: C.warn }], fill: true }], w - 26)}</Box>
1038 <Button key="ho" plain hotkey="h" label="handoff" onPress={() => startHandoff($)} />
1039 <Button key="fr" plain label="fresh" onPress={() => void $.command.run({ command: 'clear', args: '' })} />
1040 </Box>
1041 ) : null}
1042 </Box>
1043 )
1044}
1045
1046// ===== filetree =====
1047type State = 'reading' | 'opened' | 'editing' | 'edited' | 'committed'
1048type Row = { path: string; name: string; depth: number; isDir: boolean; size: number; mtime: number }
1049type Change = { st: string; add: number; del: number }
1050type Activity = { state: State; label: string; target: string; running: boolean; at: number; failed?: boolean }
1051type Touch = { state: State; at: number }
1052
1053const HIDE = new Set(['node_modules', '.DS_Store', '.next', 'dist', '__pycache__', '.venv'])
1054const GLOW_MS = 9_000
1055const MAX_ROWS = 300
1056// One colour per kind of activity: reads in the architect's colour, edits in Claude's, commits in the gate's.
1057const famColor = (s: State) => (s === 'reading' || s === 'opened' ? C.arch : s === 'committed' ? C.gate : C.main)
1058const FAMILY_LABEL: Record<State, string> = { reading: 'Reading', opened: 'Opened', editing: 'Editing', edited: 'Edited', committed: 'Committed' }
1059const gitColor = (st: string) => (({ M: C.amber, T: C.amber, A: C.gate, '?': C.gate, R: C.agent, C: C.agent, D: C.warn, U: C.warn }) as Record<string, string>)[st]
1060const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
1061
1062const open = new Set<string>() // expanded dirs (absolute)
1063const touched = new Map<string, Touch>()
1064let cwd = ''
1065let root = ''
1066let selected = ''
1067let query = ''
1068let showSize = false
1069let showHidden = true
1070let changes = new Map<string, Change>() // absolute path -> change
1071let branch = ''
1072let upstream = ''
1073let ahead = 0
1074let behind = 0
1075let list: Row[] = []
1076let allFiles: Row[] | undefined // flat index for search, built on first use
1077let activity: Activity | undefined
1078let phase = 0
1079let ticking = false
1080let committedSet = new Set<string>() // files in commits not pushed yet (or the last commit)
1081const seen = new Set<string>() // changed files already auto-expanded once
1082
1083function filetreeRedraw($: any) { return $.ui.invalidate('ui.render') }
1084const rel = (p: string) => (p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p)
1085const dirOf = (p: string) => p.slice(0, p.lastIndexOf('/'))
1086const base = (p: string) => p.slice(p.lastIndexOf('/') + 1)
1087const ago = (ms: number) => {
1088 const m = Math.floor(ms / 60_000)
1089 return m < 1 ? 'just now' : m < 60 ? `${m}m ago` : m < 1440 ? `${Math.floor(m / 60)}h ago` : `${Math.floor(m / 1440)}d ago`
1090}
1091// Git state in words, not letters: "new", "modified", "deleted".
1092const WORD: Record<string, string> = { '?': 'new', A: 'new', M: 'modified', T: 'modified', D: 'deleted', R: 'renamed', C: 'copied', U: 'conflict' }
1093
1094async function refreshGit($: any) {
1095 const st = await $.process.run(['git', 'status', '-sb', '--porcelain', '-z'], { cwd: root, timeoutMs: 5000 }).catch(() => undefined)
1096 changes = new Map()
1097 branch = upstream = ''
1098 ahead = behind = 0
1099 if (st?.exitCode === 0) {
1100 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { cwd: root }).catch(() => undefined)
1101 const b = top?.exitCode === 0 ? top.stdout.trim() : root
1102 const [header = '', ...rest] = st.stdout.split('\0') as string[]
1103 const head = /^## (\S+?)(?:\.\.\.(\S+))?(?: \[(.+)\])?$/.exec(header)
1104 branch = head?.[1] ?? ''
1105 upstream = head?.[2] ?? ''
1106 ahead = Number(/ahead (\d+)/.exec(head?.[3] ?? '')?.[1] ?? 0)
1107 behind = Number(/behind (\d+)/.exec(head?.[3] ?? '')?.[1] ?? 0)
1108 for (const r of parsePorcelain(rest.join('\0'))) changes.set(`${b}/${r.path}`, { st: r.st.trim()[0] ?? '?', add: 0, del: 0 })
1109 const ns = await $.process.run(['git', 'diff', '--numstat', 'HEAD'], { cwd: root, timeoutMs: 5000 }).catch(() => undefined)
1110 for (const l of (ns?.stdout ?? '').split('\n')) {
1111 const [a, d, p] = l.split('\t')
1112 const c = p && changes.get(`${b}/${p}`)
1113 if (c) Object.assign(c, { add: Number(a) || 0, del: Number(d) || 0 })
1114 }
1115 }
1116 // Committed but not pushed: what the branch has that its upstream has not (else just the last commit).
1117 committedSet = new Set()
1118 if (branch) {
1119 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { cwd: root }).catch(() => undefined)
1120 const b = top?.exitCode === 0 ? top.stdout.trim() : root
1121 const range = upstream ? [`${upstream}..HEAD`] : ['HEAD~1', 'HEAD']
1122 const cm = await $.process.run(['git', 'diff', '--name-only', ...range], { cwd: root, timeoutMs: 5000 }).catch(() => undefined)
1123 for (const f of (cm?.exitCode === 0 ? cm.stdout : '').split('\n').filter(Boolean)) if (!changes.has(`${b}/${f}`)) committedSet.add(`${b}/${f}`)
1124 }
1125 await expandRecent($)
1126 filetreeRedraw($)
1127}
1128
1129// Open the folders of the files that changed most recently, so nested changes are visible without hunting.
1130// Each file is expanded once: a folder you collapse yourself stays collapsed until something new changes.
1131async function expandRecent($: any) {
1132 const fresh = [...changes.keys(), ...committedSet].filter(f => !seen.has(f) && f.startsWith(`${root}/`))
1133 for (const f of fresh) seen.add(f)
1134 const dated = await Promise.all(fresh.map(async f => ({ f, t: (await $.fs.stat(f).catch(() => undefined))?.mtimeMs ?? 0 })))
1135 for (const { f } of dated.sort((a, b) => b.t - a.t).slice(0, 12)) for (let d = dirOf(f); d.length > root.length; d = dirOf(d)) open.add(d)
1136 await rebuild($)
1137}
1138
1139async function walk($: any, dir: string, depth: number, out: Row[], expand: (p: string) => boolean) {
1140 const entries = (await $.fs.list(dir).catch(() => [])).filter((x: any) => !HIDE.has(x.name) && (showHidden ? x.name !== '.DS_Store' : !x.name.startsWith('.')))
1141 entries.sort((a: any, b: any) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'dir' ? -1 : 1))
1142 for (const x of entries) {
1143 if (out.length >= 2500) return
1144 const path = `${dir}/${x.name}`
1145 out.push({ path, name: x.name, depth, isDir: x.kind === 'dir', size: x.size, mtime: x.mtimeMs })
1146 if (x.kind === 'dir' && expand(path) && x.name !== '.git') await walk($, path, depth + 1, out, expand)
1147 }
1148}
1149
1150async function rebuild($: any) {
1151 if (query) {
1152 allFiles ??= await (async () => {
1153 const out: Row[] = []
1154 await walk($, root, 0, out, () => true)
1155 return out.filter(r => !r.isDir)
1156 })()
1157 const q = query.toLowerCase()
1158 list = allFiles.filter(r => r.path.toLowerCase().includes(q)).slice(0, MAX_ROWS)
1159 } else {
1160 const out: Row[] = []
1161 await walk($, root, 0, out, p => open.has(p))
1162 list = out
1163 }
1164 filetreeRedraw($)
1165}
1166
1167function startTick($: any) {
1168 if (ticking) return
1169 ticking = true
1170 const loop = () => {
1171 const live = activity?.running || [...touched.values()].some(m => Date.now() - m.at < GLOW_MS)
1172 phase += 1
1173 filetreeRedraw($)
1174 if (live) $.clock.after(130, loop)
1175 else ticking = false
1176 }
1177 $.clock.after(130, loop)
1178}
1179
1180function filetreeTouch($: any, path: string | undefined, state: State) {
1181 if (!path) return
1182 const abs = path.startsWith('/') ? path : `${root}/${path}`
1183 touched.set(abs, { state, at: Date.now() })
1184 for (let d = dirOf(abs); d.length > root.length; d = dirOf(d)) open.add(d)
1185 if (state === 'edited' || state === 'editing') allFiles = undefined
1186 void rebuild($)
1187 startTick($)
1188}
1189
1190function say($: any, a: Activity) {
1191 activity = a
1192 startTick($)
1193 filetreeRedraw($)
1194}
1195
1196// Per-character shimmer: a bright band sweeping along the name, the rest of it dim.
1197const isHot = (i: number, len: number) => Math.abs(i - (((phase * 1.4) % (len + 8)) - 4)) < 1.8
1198
1199const counts = (dir: string) => {
1200 let n = 0hooks/band.tsx 194 lines1// Shared band and pane pieces, so every mod looks the same: claude-flightdeck's look (MIT, see THIRD_PARTY_NOTICES.md).
2// Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/band.tsx. `$` never crosses an import, so every
3// piece takes `ui` (= $.ui.resolve(e)) and `e`. Animated pieces (rails, clocks) are drawn in each register.tsx:
4// a surface module's path must be a literal in the hooks module itself.
5import { C, P, gauge, type Tone } from './ui'
6
7export type Btn = { key: string; label: string; onPress: () => unknown; hotkey?: string; plain?: boolean }
8export type RowBtn = { key: string; label: string; hint?: string; hotkey?: string; onPress: () => unknown }
9export type BandSpec = {
10 title: string
11 tone: Tone
12 detail?: string
13 pct?: number // 0-100: a ▰▱ gauge
14 bars?: { pct: number; label: string; tone?: Tone }[] // several gauges in one band, instead of pct
15 pctLabel?: string // text before the gauge, e.g. "Review 3/4"
16 ring?: boolean // kept for callers: drawn as the same gauge
17 busy?: boolean // ◐ instead of ● while live
18 chips?: string[]
19 right?: string
20 buttons?: Btn[]
21 rows?: RowBtn[] // one clickable line each, under the band
22 maxW?: number
23}
24
25// ---- lines of coloured pieces (flightdeck's `line`)
26// A Text nesting coloured Texts truncates as one line in a terminal, but the desktop app wraps each nested piece on its
27// own and collapses runs of spaces. So pieces sit `gap` cells apart, each keeps its width, and pieces that don't fit in
28// `room` are left out from the end; a piece marked `fill` truncates to what the others leave.
29export type Span = { text: string; color?: string; dim?: boolean; bold?: boolean }
30export type Piece = { spans: Span[]; lead?: number; fill?: boolean; key?: string }
31const styleOf = (s: Span) => ({ ...(s.color ? { color: s.color } : {}), ...(s.dim ? { dimColor: true } : {}), ...(s.bold ? { bold: true } : {}) })
32const widthOf = (p: Piece) => p.spans.reduce((n, s) => n + [...s.text].length, 0)
33export const fits = (pieces: Piece[], room: number, gap: number) => {
34 let used = 0
35 for (let i = 0; i < pieces.length; i += 1) {
36 const next = used + (i > 0 ? gap : 0) + (pieces[i].lead ?? 0) + widthOf(pieces[i])
37 if (next > room) return i
38 used = next
39 }
40 return pieces.length
41}
42export const line = (ui: any, pieces: (Piece | null | false | undefined)[], room: number, gap = 1, justify?: 'center' | 'space-between') => {
43 const { Box, Text } = ui
44 const all = pieces.filter((p): p is Piece => Boolean(p))
45 const shown = all.some(p => p.fill) ? all : all.slice(0, Math.max(1, fits(all, room, gap)))
46 return (
47 <Box width={Math.max(1, room)} columnGap={gap} overflow="hidden" {...(justify ? { justifyContent: justify } : {})}>
48 {shown.map((p, i) => {
49 if (p.fill) return <Box key={p.key ?? `p${i}`} flexShrink={1}>{p.spans.length === 1 ? <Text {...styleOf(p.spans[0])} wrap="truncate">{p.spans[0].text}</Text> : <Text wrap="truncate">{p.spans.map(s => <Text {...styleOf(s)}>{s.text}</Text>)}</Text>}</Box>
50 return (
51 <Box key={p.key ?? `p${i}`} flexShrink={0} {...(p.lead ? { marginLeft: p.lead } : {})}>
52 {p.spans.length === 1 ? <Text {...styleOf(p.spans[0])}>{p.spans[0].text}</Text> : <Text>{p.spans.map(s => <Text {...styleOf(s)}>{s.text}</Text>)}</Text>}
53 </Box>
54 )
55 })}
56 </Box>
57 )
58}
59
60// A ▰▱ gauge as spans: coloured fill, faint track, then the percent.
61export const gaugeSpans = (pct: number, width: number, color: string, label = ''): Span[] => {
62 const g = gauge(pct, width)
63 return [...(label ? [{ text: `${label} `, dim: true }] : []), { text: g.on, color }, { text: g.off, color: C.faint }, { text: ` ${Math.round(pct)}%`, bold: true }]
64}
65
66// ---- boxes
67// A flightdeck panel: rounded border in the role's colour, a "TITLE · state" row with a dim right side, then the body.
68export const box = (ui: any, o: { key?: string; color: string; title: string; state?: string; right?: string; w?: number; dim?: boolean; children?: unknown }) => {
69 const { Box, Text } = ui
70 return (
71 <Box key={o.key} flexDirection="column" borderStyle="round" borderColor={o.color} borderDimColor={o.dim} paddingX={1} {...(o.w ? { width: o.w } : {})}>
72 <Box justifyContent="space-between">
73 <Text color={o.color} bold wrap="truncate">{o.state ? `${o.title} · ${o.state}` : o.title}</Text>
74 {o.right ? <Box flexShrink={0}><Text dimColor>{o.right}</Text></Box> : null}
75 </Box>
76 {o.children}
77 </Box>
78 )
79}
80
81const width = (e: any, maxW?: number) => Math.max(24, Math.min(maxW ?? 400, (e?.props?.bodyColumns ?? e?.viewport?.columns ?? 80) - 1))
82
83// ---- bands above the prompt
84// A mod that needs attention: one flightdeck box, same anatomy in every mod. `nested` is `await below(next, e)` (the bands
85// beneath), `ui` is `$.ui.resolve(e)`: `$` never crosses an import, so the mod passes both in.
86export const band = (ui: any, e: any, nested: unknown, s: BandSpec) => {
87 const { Box, Text, Button } = ui
88 const color = P[s.tone]
89 const W = width(e, s.maxW)
90 const bars = s.bars ?? (s.pct !== undefined ? [{ pct: s.pct, label: s.pctLabel ?? '', tone: undefined }] : [])
91 const meter = bars.length || s.chips?.length || s.right
92 return (
93 <Box flexDirection="column">
94 <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1} width={W}>
95 <Box flexDirection="row" alignItems="center" columnGap={1}>
96 <Box flexShrink={1} flexGrow={1}>
97 {line(ui, [{ spans: [{ text: `${s.busy ? '◐' : '●'} ${s.title}`, color, bold: true }] }, s.detail ? { spans: [{ text: `· ${s.detail}`, dim: true }], fill: true } : null], W - 4 - (s.buttons?.length ?? 0) * 12)}
98 </Box>
99 {(s.buttons ?? []).map(b => <Button key={b.key} label={b.label} hotkey={b.hotkey} plain={b.plain} onPress={b.onPress} />)}
100 </Box>
101 {meter
102 ? line(
103 ui,
104 [
105 ...bars.map((b, i): Piece => ({ key: `b${i}`, spans: gaugeSpans(b.pct, 10, b.tone ? P[b.tone] : color, b.label) })),
106 ...(s.chips ?? []).map((c, i): Piece => ({ key: `c${i}`, spans: [{ text: `· ${c}`, dim: true }] })),
107 s.right ? { key: 'r', spans: [{ text: s.right, dim: true }], lead: 1 } : null,
108 ],
109 W - 4,
110 2,
111 )
112 : null}
113 {(s.rows ?? []).map(r => (
114 <Button key={r.key} plain hotkey={r.hotkey} onPress={r.onPress}>
115 <Text color={color}>{r.hotkey ? '' : '› '}</Text>
116 <Text>{r.label}</Text>
117 <Text dimColor>{r.hint ? ` ${r.hint}` : ''}</Text>
118 </Button>
119 ))}
120 </Box>
121 {nested}
122 </Box>
123 )
124}
125
126// Calm state: a mod adds a short segment to one shared summary line instead of drawing its own band.
127export type Seg = { key: string; text: string; tone?: Tone; spec?: BandSpec; more?: BandSpec[]; onPress?: () => unknown }
128let segs: Seg[] = []
129export const beginPass = () => {
130 segs = []
131}
132// Bands are drawn inner-first, so a new segment goes to the front to keep the outermost mod on the left.
133export const quiet = (s: Seg) => {
134 segs.unshift(s)
135}
136export const quietSegs = () => segs
137
138// The one summary line above the prompt, flightdeck's inline "mini" look: NAME · every calm segment · an Open button.
139// `nested` is what the bands beneath drew.
140export const quietLine = (ui: any, e: any, nested: unknown, o: { name: string; open?: () => unknown; label?: string }) => {
141 if (!segs.length) return nested
142 const { Box, Text, Button } = ui
143 return (
144 <Box flexDirection="column">
145 <Box flexDirection="row" alignItems="center" columnGap={1} width={width(e)}>
146 <Text bold color={C.main}>{o.name}</Text>
147 {segs.map(s => {
148 const label = <Text color={s.tone ? P[s.tone] : undefined} dimColor={!s.tone}>{`· ${s.text}`}</Text>
149 return s.onPress ? <Button key={s.key} plain onPress={s.onPress}>{label}</Button> : <Box key={s.key} flexShrink={0}>{label}</Box>
150 })}
151 <Box flexGrow={1} />
152 {o.open ? <Button key="open" plain label={o.label ?? 'Open'} onPress={o.open} /> : null}
153 </Box>
154 {nested}
155 </Box>
156 )
157}
158
159// ---- panes
160// A pane's header, flightdeck's: "TITLE · state" in the tone's colour, a dim right side or a gauge.
161export const paneHeader = (ui: any, e: any, o: { title: string; sub?: string; pct?: number; tone?: Tone; right?: string }) => {
162 const color = P[o.tone ?? 'accent']
163 const W = width(e)
164 return line(
165 ui,
166 [
167 { spans: [{ text: o.title.toUpperCase(), color, bold: true }] },
168 o.sub ? { spans: [{ text: `· ${o.sub}`, bold: true }], fill: true } : null,
169 o.pct !== undefined ? { spans: gaugeSpans(o.pct, 8, color), lead: 1 } : null,
170 o.right ? { spans: [{ text: o.right, dim: true }], lead: 1 } : null,
171 ],
172 W,
173 )
174}
175
176const GLYPH: Record<Tone, string> = { accent: '◐', ok: '✓', warn: '◐', err: '✗', info: '●', purple: '●' }
177
178// One row in a pane list: status glyph, title, a dim chip and a right-hand meta; an optional dim line under it.
179export const item = (ui: any, e: any, o: { key: string; tone: Tone; title: string; sub?: string; chip?: string; meta?: string; glyph?: string }) => {
180 const { Box, Text } = ui
181 const color = P[o.tone]
182 return (
183 <Box key={o.key} flexDirection="column">
184 <Box columnGap={1}>
185 <Text color={color}>{o.glyph ?? GLYPH[o.tone]}</Text>
186 <Box flexShrink={1} flexGrow={1}><Text wrap="truncate">{o.title}</Text></Box>
187 {o.chip ? <Box flexShrink={0}><Text color={color}>{o.chip}</Text></Box> : null}
188 {o.meta ? <Box flexShrink={0}><Text dimColor>{o.meta}</Text></Box> : null}
189 </Box>
190 {o.sub ? <Text dimColor wrap="truncate">{` ${o.sub}`}</Text> : null}
191 </Box>
192 )
193}
194hooks/kit.tsx 67 lines1// Card pieces shared by the pane mods: pills, file badges, folder marks, stat tiles, section labels, text cards.
2// Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/kit.tsx. Mono text in theme colours on every surface,
3// as claude-flightdeck draws (MIT, see THIRD_PARTY_NOTICES.md). Every piece takes `ui` (= $.ui.resolve(e)) and `e`.
4import { C, P } from './ui'
5
6const EXT: Record<string, [string, keyof typeof P]> = {
7 js: ['JS', 'warn'], jsx: ['JSX', 'warn'], mjs: ['JS', 'warn'], ts: ['TS', 'info'], tsx: ['TSX', 'info'],
8 json: ['JSON', 'warn'], md: ['MD', 'muted'], pdf: ['PDF', 'err'], csv: ['CSV', 'ok'], py: ['PY', 'ok'],
9 sh: ['SH', 'accent'], html: ['HTML', 'err'], css: ['CSS', 'purple'], yml: ['YML', 'purple'], yaml: ['YML', 'purple'],
10 go: ['GO', 'teal'], rs: ['RS', 'accent'], txt: ['TXT', 'muted'], png: ['PNG', 'teal'], jpg: ['JPG', 'teal'],
11 svg: ['SVG', 'teal'], map: ['MAP', 'muted'], lock: ['LOCK', 'muted'], toml: ['TOML', 'accent'],
12}
13
14// "client.test.js" -> ["JS", colour]; no extension -> a plain file mark.
15export const extBadge = (name: string): [string, string] => {
16 const dot = name.lastIndexOf('.')
17 const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : name.startsWith('.') ? name.slice(1).toLowerCase() : ''
18 const hit = EXT[ext]
19 return hit ? [hit[0], P[hit[1]]] : [ext ? ext.slice(0, 4).toUpperCase() : 'FILE', P.muted]
20}
21
22export const fileBadge = (ui: any, _e: any, name: string) => {
23 const [label, color] = extBadge(name)
24 return <ui.Text color={color}>{`${label.padEnd(4)} `}</ui.Text>
25}
26
27export const folderIcon = (ui: any, _e: any, color: string = P.info) => <ui.Text color={color}>{'■ '}</ui.Text>
28
29// A small bracketed tag: "reading", "edited", "committed".
30export const pill = (ui: any, _e: any, label: string, color: string) => <ui.Text color={color} bold>{`[${label}]`}</ui.Text>
31
32// A glyph mark, the "RIGHT NOW" / trash icon.
33export const iconTile = (ui: any, _e: any, glyph: string, color: string) => <ui.Text color={color} bold>{`${glyph} `}</ui.Text>
34
35// Stat tile: a dim label and a bold value (Cost, Tokens, Time).
36export const tile = (ui: any, _e: any, label: string, value: string) => (
37 <ui.Text>
38 <ui.Text dimColor>{`${label} `}</ui.Text>
39 <ui.Text bold>{value}</ui.Text>
40 </ui.Text>
41)
42
43// "CLAUDE TOUCHED 1 FILE": dim caps label left, dim count right.
44export const sectionLabel = (ui: any, left: string, right?: string) => (
45 <ui.Box flexDirection="row">
46 <ui.Text bold dimColor>{left.toUpperCase()}</ui.Text>
47 <ui.Box flexGrow={1} />
48 <ui.Text dimColor>{right ? right.toUpperCase() : ''}</ui.Text>
49 </ui.Box>
50)
51
52// Rounded bordered panel in the faint colour, or the one given.
53export const panel = (ui: any, children: unknown, o: { color?: string } = {}) => (
54 <ui.Box flexDirection="column" borderStyle="round" borderColor={o.color ?? C.faint} paddingX={1}>
55 {children}
56 </ui.Box>
57)
58
59// A card whose text wraps in full (no truncation): a rounded border in the card's colour, text, an optional dim line and actions.
60export const textCard = (ui: any, o: { key: string; color: string; text: string; sub?: string; children?: unknown }) => (
61 <ui.Box key={o.key} flexDirection="column" borderStyle="round" borderColor={o.color} paddingX={1}>
62 <ui.Text wrap="wrap">{o.text}</ui.Text>
63 {o.sub ? <ui.Text wrap="wrap" dimColor>{o.sub}</ui.Text> : null}
64 {o.children}
65 </ui.Box>
66)
67hooks/ui.ts 114 lines1// Shared drawing kit. Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/ui.ts.
2// The look follows claude-flightdeck (MIT, see THIRD_PARTY_NOTICES.md): mono text in rounded, role-coloured boxes,
3// ▰▱ gauges, colours named after the person's Claude Code theme so light, dark and colour-blind themes all read.
4
5// Roles, as flightdeck names them: main (Claude's own), agent, gate, cleared, arch(itect), amber, warn, dim, faint, text.
6type Role = 'main' | 'agent' | 'gate' | 'cleared' | 'arch' | 'amber' | 'warn' | 'dim' | 'faint' | 'text'
7const THEME: Record<Role, string> = {
8 main: 'claude', agent: 'suggestion', gate: 'success', cleared: 'permission', arch: 'merged',
9 amber: 'warning', warn: 'error', dim: 'inactive', faint: 'subtle', text: 'text',
10}
11// Fixed hex tuned for dark terminals: the `palette: pastel` option.
12const PASTEL: Record<Role, string> = {
13 main: '#7dd3fc', agent: '#93c5fd', gate: '#86efac', cleared: '#5eead4', arch: '#c4b5fd',
14 amber: '#fcd34d', warn: '#fca5a5', dim: '#6b7280', faint: '#3f4654', text: '#e5e7eb',
15}
16
17// The live palette every mod reads. `usePalette` swaps it in place at register time, so imports stay valid.
18export const C: Record<Role, string> = { ...THEME }
19export type Tone = 'accent' | 'ok' | 'warn' | 'err' | 'info' | 'purple'
20// A mod's tone, as a role colour: accent is Claude's own, info an agent's, purple the architect's.
21export const P: Record<Tone | 'teal' | 'muted' | 'faint' | 'text', string> = { ...toneColors() }
22// Motion and palette options, set once per load by the bundle's register.
23export const DECK = { motion: true, palette: 'theme' as 'theme' | 'pastel' }
24
25function toneColors() {
26 return { accent: C.main, ok: C.gate, warn: C.amber, err: C.warn, info: C.agent, purple: C.arch, teal: C.cleared, muted: C.dim, faint: C.faint, text: C.text }
27}
28
29export const usePalette = (palette: unknown, motion: unknown) => {
30 DECK.palette = palette === 'pastel' ? 'pastel' : 'theme'
31 DECK.motion = motion !== 'off'
32 Object.assign(C, DECK.palette === 'pastel' ? PASTEL : THEME)
33 Object.assign(P, toneColors())
34}
35
36// SVG cannot name theme keys: mid-tone colours that read on light and dark backgrounds (the desktop time axis).
37export const SVG_COLORS = { running: '#3b82f6', done: '#16a34a', failed: '#dc2626', other: '#8b5cf6', label: '#6b7280' }
38export const MONO = "ui-monospace, 'SF Mono', Menlo, Consolas, monospace"
39
40export const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] as string)
41
42export const fmtTok = (n: number) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${n}`)
43export const fmtSize = (n: number) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB` : `${(n / 1048576).toFixed(1)} MB`)
44
45// `git status --porcelain -z` output (no header) -> rows. A rename or copy carries its old path as an extra field: skipped.
46export const parsePorcelain = (out: string) => {
47 const parts = out.split('\0')
48 const rows: { st: string; path: string }[] = []
49 for (let i = 0; i < parts.length; i++) {
50 const l = parts[i]
51 if (l.length < 4) continue
52 rows.push({ st: l.slice(0, 2), path: l.slice(3) })
53 if (/[RC]/.test(l.slice(0, 2))) i++
54 }
55 return rows
56}
57
58export const fmtCost = (usd: number) => (usd < 0.01 ? '<$0.01' : usd < 10 ? `$${usd.toFixed(2)}` : `$${Math.round(usd)}`)
59export const fmtDur = (ms: number) => {
60 const s = Math.max(0, Math.round(ms / 1000))
61 return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
62}
63// A running clock as flightdeck's cards draw it: m:ss, or XhYY past an hour.
64export const fmtTimer = (ms: number) => {
65 const s = Math.max(0, Math.floor(ms / 1000))
66 const m = Math.floor(s / 60)
67 return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
68}
69export const fmtClock = (ms: number) => (ms > 0 ? new Date(ms).toTimeString().slice(0, 8) : '--:--:--')
70export const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
71export const shorten = (s: string, n: number) => {
72 const one = s.replace(/\s+/g, ' ').trim()
73 return n <= 0 ? '' : one.length > n ? `${one.slice(0, Math.max(0, n - 1)).trimEnd()}…` : one
74}
75
76// Green below `warnAt`, amber below `errAt`, red above (percent scales).
77export const zone = (pct: number, warnAt = 60, errAt = 85) => (pct >= errAt ? C.warn : pct >= warnAt ? C.amber : C.gate)
78export const zoneTone = (pct: number, warnAt = 60, errAt = 85): Tone => (pct >= errAt ? 'err' : pct >= warnAt ? 'warn' : 'ok')
79
80// A gauge of `width` cells: ▰ filled, ▱ empty.
81export const gauge = (pct: number, width: number) => {
82 const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
83 return { on: '▰'.repeat(full), off: '▱'.repeat(width - full) }
84}
85
86// "claude-opus-5-5[1m]" -> "Opus 5.5 1M"; anything else as given, cut to 22.
87export const prettyModel = (id: string) => {
88 if (!id) return '—'
89 const cap = (f: string) => f.charAt(0).toUpperCase() + f.slice(1)
90 const big = /\[1m\]|-1m\b/i.test(id) ? ' 1M' : ''
91 const now = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?![\d])/i.exec(id)
92 if (now?.[1] && !/^\d/.test(now[1])) return `${cap(now[1].toLowerCase())} ${now[2]}${now[3] ? `.${now[3]}` : ''}${big}`
93 const old = /claude-(\d+)(?:-(\d))?-([a-z]+)/i.exec(id)
94 if (old?.[3]) return `${cap(old[3].toLowerCase())} ${old[1]}${old[2] ? `.${old[2]}` : ''}${big}`
95 return shorten(id, 22)
96}
97
98// The desktop and mobile draw Svg; the terminal's element table carries a stub that draws nothing: test the surface too.
99export const isRich = (ui: object, e: { surface: string }) => e.surface !== 'terminal' && 'Svg' in ui
100
101// AbovePrompt is one strip shared by every mod: a hook that returns a tree hides the mods beneath it
102// unless it nests what `next(e)` drew. Call this first, put the result in your column. Claude Code's
103// own placeholder ({ type: 'engine' }) is never nested: the desktop drops a band that nests it.
104export const below = async (next: (e: any) => unknown, e: unknown) => {
105 const drawn = await Promise.resolve(next(e)).catch(() => null)
106 return drawn && typeof drawn === 'object' && (drawn as { type?: string }).type !== 'engine' ? drawn : null
107}
108
109// Age in a few characters, as the filetree draws it: now, 12m, 3h, 5d.
110export const age = (ms: number) => {
111 const m = Math.floor(ms / 60_000)
112 return m < 1 ? 'now' : m < 60 ? `${m}m` : m < 1440 ? `${Math.floor(m / 60)}h` : `${Math.floor(m / 1440)}d`
113}
114hooks/rail.tsx 87 lines1// From claude-flightdeck (https://github.com/scasella/claude-flightdeck, commit f9c3c52), MIT, Copyright (c) 2026
2// Stephen Casella; see THIRD_PARTY_NOTICES.md. Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/rail.tsx.
3// A connector drawn on the surface's own frame clock: packets travel along it while `active`,
4// and it rests as a plain dim line otherwise. Only this region redraws; the pane does not.
5import type { ClientModule, RenderChildren } from 'claude-code'
6
7type Props = {
8 active: boolean
9 width: number
10 color: string
11 dim: string
12 /** Cells where a branch drops (┬); the rest of the line is ─. */
13 marks: number[]
14 /** Draw ┴ instead of ┬ at the marks: a merge into what is below. */
15 isMerge: boolean
16}
17
18type Ref = { phase: number; active: boolean }
19type State = { ref: Ref }
20
21const STEP_MS = 110
22/** Dashes drawn past the line's end and clipped by its box, so the right end is the box's edge. */
23const SPARE = 4
24
25const Rail: ClientModule<Props, State> = (props, surface) => {
26 const { Box, Text } = surface.elements
27 const ref = surface.state?.ref ?? { phase: 0, active: props.active }
28 ref.active = props.active
29 if (surface.state === undefined) {
30 surface.setState({ ref })
31 surface.every(STEP_MS, () => {
32 if (ref.active) {
33 ref.phase += 1
34 surface.setState({ ref })
35 }
36 })
37 }
38
39 const width = Math.max(1, surface.columns || props.width)
40 const cells = Array.from({ length: width + SPARE }, () => '─')
41 for (const m of props.marks) if (m >= 0 && m < width) cells[m] = props.isMerge ? '┴' : '┬'
42
43 // A graphical surface draws text in a proportional face, where ─ ● • and bold differ in width, so as
44 // the packets moved the line's length changed and its right end jittered. Drawn in the surface's
45 // monospaced face (whose advance is what a cell is there) each glyph is one cell, and the line sits in
46 // a box of its width that clips the spare dashes: its right end is that edge, every frame.
47 const line = (children: RenderChildren) => (
48 <Box width={width} overflow="hidden">
49 <Box flexShrink={0}>{children}</Box>
50 </Box>
51 )
52
53 if (!props.active) {
54 return line(
55 <Text color={props.dim} mono>
56 {cells.join('')}
57 </Text>,
58 )
59 }
60
61 // Two packets per 24 cells, a bright head and a trailing dot, moving left to right.
62 const lit = new Map<number, string>()
63 for (let base = 0; base < width + 24; base += 24) {
64 const head = (base + ref.phase) % (width + 24)
65 if (head < width) lit.set(head, '●')
66 if (head - 1 >= 0 && head - 1 < width) lit.set(head - 1, '•')
67 }
68 // Runs, not cells: consecutive cells of one kind share a Text, a handful of nodes per frame.
69 const runs: { text: string; isLit: boolean }[] = []
70 cells.forEach((ch, i) => {
71 const isLit = lit.has(i)
72 const last = runs[runs.length - 1]
73 const glyph = lit.get(i) ?? ch
74 if (last && last.isLit === isLit) last.text += glyph
75 else runs.push({ text: glyph, isLit })
76 })
77 return line(
78 runs.map(r => (
79 <Text color={r.isLit ? props.color : props.dim} bold={r.isLit} mono>
80 {r.text}
81 </Text>
82 )),
83 )
84}
85
86export default Rail
87hooks/elapsed.tsx 40 lines1// From claude-flightdeck (https://github.com/scasella/claude-flightdeck, commit f9c3c52), MIT, Copyright (c) 2026
2// Stephen Casella; see THIRD_PARTY_NOTICES.md. Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/elapsed.tsx.
3// A running agent's clock, ticking on the surface's frame clock so the pane need not redraw.
4// `since` and `now` come from the hooks module's $.clock; between redraws it adds its own ticks.
5import type { ClientModule } from 'claude-code'
6
7type Props = { since: number; now: number; endAt: number | null; color: string }
8type Ref = { base: number; ticks: number; lastNow: number; isRunning: boolean }
9type State = { ref: Ref }
10
11const fmt = (ms: number) => {
12 const s = Math.max(0, Math.floor(ms / 1000))
13 const m = Math.floor(s / 60)
14 return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
15}
16
17const Elapsed: ClientModule<Props, State> = (props, surface) => {
18 const { Text } = surface.elements
19 const ref = surface.state?.ref ?? { base: 0, ticks: 0, lastNow: -1, isRunning: true }
20 if (props.now !== ref.lastNow) {
21 // A fresh reading from the hooks module: restart the local count from it.
22 ref.lastNow = props.now
23 ref.base = (props.endAt ?? props.now) - props.since
24 ref.ticks = 0
25 }
26 ref.isRunning = props.endAt === null
27 if (surface.state === undefined) {
28 surface.setState({ ref })
29 surface.every(1000, () => {
30 if (ref.isRunning) {
31 ref.ticks += 1
32 surface.setState({ ref })
33 }
34 })
35 }
36 return <Text color={props.color}>{fmt(ref.base + ref.ticks * 1000)}</Text>
37}
38
39export default Elapsed
40