Docked pane showing the project, branch, upstream, worktrees, recent commits, the last turn's recap and the session's context fill.

A Claude Code mod (function-hooks plugin) that docks a pane beside the transcript with the facts a developer keeps checking by hand:
owner/name of originok when the upstream name is the branch's own, mismatch when it points elsewhere (the state that makes git push refuse under push.default=simple), gone when the remote branch was deleted, none when unsetOn the terminal the mod also draws one row above the prompt in the status line's look (~/.claude/statusline.sh): the same ■□ ten-cell bars, │ separators and colors, taken from BAND_PALETTES in hooks/palette.ts. Each rate-limit window shows its bar with a ▣ where the window's time has got to, the percentage and the reset as clock time (→ 2:19pm, with the weekday when it is more than a day away); the context shows its fill, tokens used and what the last response added; cost shows the session's cost so far (the /cost total), from three turns on a sparkline of the last twelve turns' costs (each bar scaled to the dearest of them), and 1h with what the turns of the last hour cost. A rate-limit bar steps teal, yellow, orange and red with its level as the status line's does, and a window used faster than it refills steps up early. The band takes the place of the usage-bar mod's band on the terminal (its /usage and /budget commands still work); band: false hands the row back to it.
The pane opens by itself when the terminal runs the fullscreen layout and is at least 144 columns wide. /dashboard opens or closes it at any width. r refreshes, h hides.
The desktop app's sidebar does not say which worktree a session runs in, so on every surface the pane leads with the worktree name (or the project name at the main checkout), its path with $HOME as ~, the project and the branch.
On the desktop app, VS Code and mobile the pane is drawn as SVG in the style of the usage-bar mod. One full-width card carries everything about where the session is, each fact once: the worktree (or project) name, its path, the project when in a worktree, the branch with the changed-file count beside it, and the upstream with its verdict and note. Below it come the other worktrees and the commits, then the context card and the turn recaps. A branch, upstream or path too long for a line wraps onto a second one, and a recap line onto up to three, breaking after a space, /, _, - or ., instead of being cut; Hangul and other East Asian glyphs are measured at a full em so a Korean line stays inside its card. Body text is 12 CSS pixels, values 13 and the name 22, close to the host's own pane text. The SVG restyles itself through prefers-color-scheme, and its tints are translucent over the host's own pane background, so the pane follows the app's light or dark appearance without reading a setting. Cards are sized from the pane's cell count at about 9.5 CSS pixels per cell (measured on the desktop app, less the 26 pixels its paddingX takes on each side) and wrap to one, two or three columns, so a pane wide enough for two columns gets two full ones and a narrower pane one full-width column.
In the terminal, where there is no SVG, colors follow Claude Code's theme setting, a custom theme counting as the preset it is based on: a light theme gets PhpStorm's Rider Melon tool-window gray with a keyword-blue accent, matching the light Ghostty theme; a dark theme takes the colors of the herdr sidebar beside it (~/.config/herdr/config.toml): the Catppuccin Mocha mantle, the wine-rose accent #cc6480, the rose-shifted grays and herdr's sage, yellow and red state colors. When one side's colors change, change the other's with it. The theme option forces one. Under the header a row of tinted chips carries the context fill, the branch and the upstream verdict; the sections below keep the label-and-value rows.
For a session started from a terminal, name the folder in CLAUDE_CODE_PLUGIN_DIRS:
export CLAUDE_CODE_PLUGIN_DIRS="$HOME/.claude/mods/dev-dashboard"
For sessions the desktop app starts, put the same key in the env block of ~/.claude/settings.json. Either way the mod is read once, when the session starts: a saved edit is not picked up until /reload-plugins is run in that session or a new session starts.
Options live under /config (or pluginConfigs.dev-dashboard in settings): banner, commits, autoOpen, band, pollSeconds, recapLines, theme.
art: flower draws a six-petal flower (14 by 14 pixels, two per cell with ▀) on the terminal surface, beside the banner and worktree name when the pane is wide enough for both and above them otherwise; its black surround takes the pane's background color. The pixels live in hooks/flower.ts, generated from a photo with pure-Python PNG decoding and box downsampling.
The banner is drawn with a built-in 3-row block font (letters, digits, -, .): 3 by 5 pixel glyphs, two cell columns per pixel so the stems are a full cell wide. Where that form does not fit, the glyphs fall back to one column per pixel; a text still wider than the pane is left out rather than cut.
claude plugin validate ~/.claude/mods/dev-dashboard
tsc -p ~/.claude/mods/dev-dashboard # after the engine has loaded it once
claude plugin test ~/.claude/mods/dev-dashboardhooks/register.tsx 581 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { GitSnapshot, RateLimit, SessionFacts, TurnCosts, TurnRecap, UpstreamStatus } from '../types'
5import { bandGroups, barRuns } from './band'
6import type { BandGroup } from './band'
7import { bannerWidth, renderBanner } from './banner'
8import { UPSTREAM_NOTE, changedText, chips, commitsCard, contextCard, fit, isInSync, placeCard, recapCard, recapSummary, shortAge, shortenHome, syncText, worktreesCard } from './cards'
9import type { Card, ChipPart, PaneFacts } from './cards'
10import { FLOWER } from './flower'
11import { readGitSnapshot } from './git'
12import { BAND_PALETTES, PALETTES, customThemeSlug, resolveTheme } from './palette'
13import type { ChipTone, Palette, ThemeName } from './palette'
14import { makeHalfBlockCells } from './raster'
15import { RECAP_ROOTS_KEY, makeRecap, recapKey, rememberRoot } from './recap'
16
17const PANE_ID = 'dev-dashboard'
18const PANE_TITLE = 'Dashboard'
19const PANE_COLUMNS = 46
20const GIT_TIMEOUT_MS = 10000
21const LABEL_WIDTH = 10
22
23// A remote pane reports its width in cells only. Measured on the desktop app
24// at two pane widths: a cell is about 9.5 CSS pixels, the pane body has no
25// padding of its own, and the Box's paddingX={1} takes about 26 pixels a side.
26// A few pixels are kept back so a card never crosses the pane's edge.
27const REMOTE_CELL_PX = 9.5
28const REMOTE_PAD_PX = 26
29const REMOTE_SAFETY_PX = 4
30const CARD_GAP_PX = 8
31const CARD_MIN_PX = 250
32const CARD_MAX_COLUMNS = 3
33const BAND_BAR_WIDTH = 10
34const BAND_WIDE_COLUMNS = 100
35const TURN_COSTS_KEPT = 48
36const SESSION_POLL_MS = 60_000
37
38const NO_COSTS: TurnCosts = { turns: [], startUsd: null }
39
40// Change a shape tag when that value's fields change: the tag declines what an
41// earlier version stored, which outlives a reload.
42const git = atom({ plugin: 'dev-dashboard', key: 'git' } as const, null, { shape: 'git-pane-1' })
43const lastTurn = atom({ plugin: 'dev-dashboard', key: 'lastTurn' } as const, null, { shape: 'recap-pane-1' })
44const previous = atom({ plugin: 'dev-dashboard', key: 'previous' } as const, null, { shape: 'recap-pane-1' })
45const session = atom({ plugin: 'dev-dashboard', key: 'session' } as const, null, { shape: 'session-band-1' })
46const isDismissed = atom({ plugin: 'dev-dashboard', key: 'isDismissed' } as const, false)
47const costs = atom({ plugin: 'dev-dashboard', key: 'costs' } as const, NO_COSTS)
48
49const gitRefresh: { pending: Promise<GitSnapshot> | null; isQueued: boolean } = { pending: null, isQueued: false }
50
51function toNumber(value: unknown, fallback: number): number {
52 const parsed = typeof value === 'number' ? value : Number(value)
53
54 return Number.isFinite(parsed) ? parsed : fallback
55}
56
57function upstreamColor(palette: Palette, status: UpstreamStatus): string {
58 if (status === 'ok') return palette.ok
59 if (status === 'mismatch') return palette.error
60 if (status === 'gone') return palette.warning
61
62 return palette.muted
63}
64
65function refreshGit($: EngineInterface, commitCount: number): Promise<GitSnapshot> {
66 if (gitRefresh.pending !== null) {
67 gitRefresh.isQueued = true
68
69 return gitRefresh.pending
70 }
71
72 gitRefresh.pending = (async () => {
73 const cwd = await $.session.cwd()
74 const run = async (args: readonly string[]) => {
75 const ran = await $.process.run(['git', ...args], { cwd, timeoutMs: GIT_TIMEOUT_MS })
76
77 return { exitCode: ran.exitCode, stdout: ran.stdout }
78 }
79 const snapshot = await readGitSnapshot(run, cwd, commitCount, await $.clock.now())
80 await update($, git, () => snapshot)
81
82 return snapshot
83 })().finally(() => {
84 gitRefresh.pending = null
85
86 if (gitRefresh.isQueued) {
87 gitRefresh.isQueued = false
88 void refreshGit($, commitCount)
89 }
90 })
91
92 return gitRefresh.pending
93}
94
95function toRateLimit(limit: { kind: string; percentUsed: number; resetsAt?: string }): RateLimit {
96 return { kind: limit.kind, percentUsed: limit.percentUsed, resetsAt: limit.resetsAt ?? null }
97}
98
99async function refreshSession($: EngineInterface): Promise<void> {
100 const [model, turns, usage] = await Promise.all([$.session.model(), $.session.turns(), $.session.usage()])
101 const facts: SessionFacts = {
102 model,
103 turns,
104 contextPercent: usage.context.percent ?? null,
105 contextTokens: usage.context.tokens ?? null,
106 contextWindow: usage.context.window,
107 contextDelta: null,
108 rateLimits: usage.rateLimits.map(toRateLimit),
109 costUsd: usage.cost?.usd ?? null,
110 startedAt: usage.startedAt,
111 }
112
113 await update($, session, earlier => ({ ...facts, contextDelta: earlier?.contextDelta ?? null }))
114}
115
116// A turn's cost is the session total at its end minus the total at its start,
117// so a subagent's spend counts toward the turn that ran it.
118async function recordTurnCost($: EngineInterface, endedAt: number): Promise<void> {
119 const facts = await read($, session)
120 const sessionUsd = facts?.costUsd ?? null
121
122 await update($, costs, ledger => {
123 if (sessionUsd === null || ledger.startUsd === null) return { ...ledger, startUsd: null }
124
125 return { turns: [...ledger.turns, { endedAt, usd: Math.max(0, sessionUsd - ledger.startUsd) }].slice(-TURN_COSTS_KEPT), startUsd: null }
126 })
127}
128
129async function loadPrevious($: EngineInterface, repoRoot: string | null): Promise<void> {
130 if (repoRoot === null) return
131
132 const stored = await $.store.get(recapKey(repoRoot))
133 const recap = stored !== undefined && stored !== null && typeof stored === 'object' ? (stored as TurnRecap) : null
134
135 await update($, previous, () => recap)
136}
137
138async function persistRecap($: EngineInterface, recap: TurnRecap): Promise<void> {
139 if (recap.repoRoot === null) return
140
141 const roots = await $.store.get(RECAP_ROOTS_KEY)
142 const known = Array.isArray(roots) ? roots.filter((root): root is string => typeof root === 'string') : []
143 const kept = rememberRoot(known, recap.repoRoot)
144
145 await Promise.all(known.filter(root => !kept.includes(root)).map(root => $.store.delete(recapKey(root))))
146 await $.store.set(recapKey(recap.repoRoot), recap)
147 await $.store.set(RECAP_ROOTS_KEY, kept)
148}
149
150async function customThemeBase($: EngineInterface, slug: string): Promise<unknown> {
151 try {
152 const home = await $.env.get('HOME')
153 const theme = JSON.parse(await $.fs.read(`${home}/.claude/themes/${slug}.json`)) as { base?: unknown }
154
155 return theme.base ?? 'dark'
156 } catch {
157 return 'dark'
158 }
159}
160
161async function readTheme($: EngineInterface, option: unknown): Promise<ThemeName> {
162 const settings = await $.settings.read()
163 const slug = customThemeSlug(settings.theme)
164
165 return resolveTheme(option, slug === null ? settings.theme : await customThemeBase($, slug))
166}
167
168function openPane($: EngineInterface) {
169 return $.ui.open({ id: PANE_ID, title: PANE_TITLE, columns: PANE_COLUMNS })
170}
171
172export const register: Register = (on, options) => {
173 const commitCount = Math.max(1, Math.floor(toNumber(options.commits, 8)))
174 const recapLines = Math.max(1, Math.floor(toNumber(options.recapLines, 4)))
175 const pollSeconds = Math.max(0, toNumber(options.pollSeconds, 30))
176 const autoOpen = options.autoOpen !== false
177 const isBandEnabled = options.band !== false
178 const bannerText = typeof options.banner === 'string' ? options.banner : ''
179 const wideBanner = renderBanner(bannerText, 2)
180 const narrowBanner = renderBanner(bannerText, 1)
181 const bannerFor = (columns: number) => [wideBanner, narrowBanner].find(rows => rows.length > 0 && bannerWidth(rows) <= columns) ?? null
182 const artwork = options.art === 'none' ? null : FLOWER
183
184 let theme: ThemeName = 'dark'
185 let home: string | null = null
186 let turnStartedAt = 0
187 let toolCalls = 0
188 let hasAutoOpened = false
189
190 on('session.start', async ($, e, next) => {
191 await $.command.register({ name: 'dashboard', description: 'Toggle the dev dashboard pane' })
192
193 theme = await readTheme($, options.theme)
194 home = (await $.env.get('HOME')) ?? null
195 const snapshot = await refreshGit($, commitCount)
196 await Promise.all([loadPrevious($, snapshot.mainRoot), refreshSession($)])
197
198 $.clock.every(SESSION_POLL_MS, () => void refreshSession($))
199
200 if (pollSeconds > 0) {
201 $.clock.every(pollSeconds * 1000, () => void refreshGit($, commitCount))
202 }
203
204 return next(e)
205 })
206
207 on('command.run', { command: 'dashboard' }, async $ => {
208 const isOpen = (await $.ui.panes()).some(pane => pane.id === PANE_ID)
209
210 if (isOpen) {
211 await $.ui.close({ id: PANE_ID })
212
213 return { text: 'Dashboard closed.' }
214 }
215
216 await update($, isDismissed, () => false)
217 const opened = await openPane($)
218
219 return { text: opened.isPlaced ? 'Dashboard opened.' : `Dashboard waits: ${opened.reason}` }
220 })
221
222 on('ui.close', async ($, e, next) => {
223 if (e.id === PANE_ID && e.origin.kind === 'person') {
224 await update($, isDismissed, () => true)
225 }
226
227 return next(e)
228 })
229
230 // Drawn without next(e) on the terminal, so a band of another plugin
231 // beneath (usage-bar) is left out there; `band: false` gives it back.
232 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
233 if (autoOpen && !hasAutoOpened && e.viewport?.isFullscreen === true && !(await read($, isDismissed))) {
234 hasAutoOpened = true
235 void openPane($)
236 }
237
238 if (!isBandEnabled || e.surface !== 'terminal' || e.props.hasSurvey) return next(e)
239
240 const [facts, ledger] = await Promise.all([read($, session), read($, costs)])
241 const groups = facts === null ? [] : bandGroups(facts, await $.clock.now(), e.props.bodyColumns >= BAND_WIDE_COLUMNS, ledger.turns)
242 if (groups.length === 0) return next(e)
243
244 const { Box, Text } = $.ui.resolve(e)
245 const colors = BAND_PALETTES[theme]
246 const valueColor = (group: BandGroup) => (group.tone === 'ok' ? colors.label : colors.bars[group.barColor])
247
248 return (
249 <Box flexDirection="row" flexWrap="wrap" paddingX={1}>
250 {groups.map((group, index) => (
251 <Box key={group.key} flexDirection="row" flexShrink={0}>
252 {index > 0 && <Text color={colors.separator}>{' │ '}</Text>}
253 <Text color={colors.label}>{`${group.label} `}</Text>
254 {group.percent !== null &&
255 barRuns(group.percent, group.elapsedShare, BAND_BAR_WIDTH).map(([run], runIndex) => (
256 <Text key={`${group.key}:${runIndex}`} color={colors.bars[group.barColor]} weight={group.barColor === 'context' ? undefined : 'bold'}>
257 {run}
258 </Text>
259 ))}
260 <Text color={group.percent === null ? colors.value : valueColor(group)} weight={group.percent === null || group.tone !== 'ok' ? 'bold' : undefined}>
261 {group.percent === null ? group.value : ` ${group.value}`}
262 </Text>
263 {group.spark !== null && <Text color={colors.spark}>{` ${group.spark}`}</Text>}
264 {group.asides.map(aside => (
265 <Text key={`${group.key}:${aside}`} color={colors.separator}>
266 {` ${aside}`}
267 </Text>
268 ))}
269 </Box>
270 ))}
271 </Box>
272 )
273 })
274
275 on('session.measure', async ($, e, next) => {
276 await update($, session, facts => {
277 if (facts === null) return null
278
279 const tokens = e.context.tokens ?? facts.contextTokens
280 const hasMoved = tokens !== null && facts.contextTokens !== null && tokens !== facts.contextTokens
281
282 return {
283 ...facts,
284 contextPercent: e.context.percent ?? facts.contextPercent,
285 contextTokens: tokens,
286 contextWindow: e.context.window,
287 contextDelta: hasMoved ? tokens - (facts.contextTokens ?? 0) : facts.contextDelta,
288 rateLimits: e.rateLimits.map(toRateLimit),
289 costUsd: e.cost?.usd ?? facts.costUsd,
290 }
291 })
292
293 return next(e)
294 })
295
296 on('prompt.submit', async ($, e, next) => {
297 turnStartedAt = await $.clock.now()
298 toolCalls = 0
299
300 return next(e)
301 })
302
303 on('turn.start', async ($, e, next) => {
304 if (e.agentId !== undefined) return next(e)
305
306 const usage = await $.session.usage()
307 await update($, costs, ledger => ({ ...ledger, startUsd: usage.cost?.usd ?? null }))
308
309 return next(e)
310 })
311
312 on('tool.call', async ($, e, next) => {
313 const isMainLoop = e.agentId === undefined
314 if (isMainLoop) toolCalls += 1
315
316 const ran = await next(e)
317
318 if (isMainLoop && ran.deny === undefined && ran.isReadOnly !== true) {
319 void refreshGit($, commitCount)
320 }
321
322 return ran
323 })
324
325 on('turn.complete', async ($, e, next) => {
326 if (e.agentId !== undefined) return next(e)
327
328 const endedAt = await $.clock.now()
329 const snapshot = await read($, git)
330 const recap = makeRecap({
331 answer: e.answer,
332 durationMs: turnStartedAt > 0 ? endedAt - turnStartedAt : e.durationMs,
333 toolCalls,
334 outputTokens: e.usage?.output_tokens ?? null,
335 reason: e.reason,
336 repoRoot: snapshot?.mainRoot ?? null,
337 endedAt,
338 lineCount: recapLines,
339 })
340
341 await update($, lastTurn, () => recap)
342 await Promise.all([persistRecap($, recap), refreshSession($), refreshGit($, commitCount)])
343 await recordTurnCost($, endedAt)
344
345 return next(e)
346 })
347
348 on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
349 const now = await $.clock.now()
350 const [snapshot, turn, prior, facts] = await Promise.all([read($, git), read($, lastTurn), read($, previous), read($, session)])
351 const showsPrior = prior !== null && (turn === null || prior.endedAt !== turn.endedAt)
352
353 if (e.surface !== 'terminal') {
354 const { Box, Button, Svg, Text } = $.ui.resolve(e)
355 const paneWidth = Math.max(CARD_MIN_PX, Math.floor(e.props.bodyColumns * REMOTE_CELL_PX) - 2 * REMOTE_PAD_PX - REMOTE_SAFETY_PX)
356 const columns = Math.max(1, Math.min(CARD_MAX_COLUMNS, Math.floor((paneWidth + CARD_GAP_PX) / (CARD_MIN_PX + CARD_GAP_PX))))
357 const cardWidth = Math.floor((paneWidth - CARD_GAP_PX * (columns - 1)) / columns)
358 const wideWidth = columns === 1 ? cardWidth : cardWidth * 2 + CARD_GAP_PX
359 const draw = (key: string, card: Card) => <Svg key={key} source={card.source} alt={card.alt} width={card.width} height={card.height} />
360
361 if (snapshot === null) {
362 return (
363 <Box paddingX={1}>
364 <Text dimColor>Reading the repository…</Text>
365 </Box>
366 )
367 }
368
369 const view: PaneFacts = { snapshot, turn, prior, facts, now, home }
370 const context = contextCard(view, cardWidth)
371 const worktrees = worktreesCard(view, cardWidth)
372
373 // Development facts first (where the session is, its other worktrees,
374 // the commits), the session's own facts after them.
375 return (
376 <Box flexDirection="column" width="100%" paddingX={1} rowGap={1}>
377 {draw('card:place', placeCard(view, wideWidth))}
378 <Box flexDirection="row" flexWrap="wrap" alignItems="flex-start" columnGap={1} rowGap={1}>
379 {worktrees !== null && draw('card:worktrees', worktrees)}
380 {snapshot.isRepo && draw('card:commits', commitsCard(view, wideWidth))}
381 {context !== null && draw('card:context', context)}
382 {turn !== null && draw('card:turn', recapCard('LAST TURN', turn, now, wideWidth, 'purple'))}
383 {showsPrior && draw('card:previous', recapCard('PREVIOUS SESSION', prior, now, wideWidth, null))}
384 {!snapshot.isRepo && <Text dimColor>not a git repository</Text>}
385 </Box>
386 <Box flexDirection="row" columnGap={1}>
387 <Button key="refresh" label="Refresh" hotkey="r" onPress={() => void refreshGit($, commitCount)} />
388 <Button key="hide" label="Hide" hotkey="h" role="dismiss" onPress={() => $.ui.close({ id: PANE_ID })} />
389 </Box>
390 </Box>
391 )
392 }
393
394 const { Box, Button, Text, Raster } = $.ui.resolve(e)
395 const palette = PALETTES[theme]
396 const width = Math.max(10, e.props.bodyColumns - 2)
397
398 const heading = (label: string) => (
399 <Box key={`h:${label}`} marginTop={1}>
400 <Text color={palette.accent} weight="bold">
401 {fit(label.toUpperCase(), width)}
402 </Text>
403 <Text color={palette.muted} dimColor>
404 {fit(` ${'─'.repeat(Math.max(0, width - label.length - 1))}`, Math.max(0, width - label.length))}
405 </Text>
406 </Box>
407 )
408 const row = (label: string, value: string, color: string = palette.text) => (
409 <Box key={`r:${label}`}>
410 <Text color={palette.muted}>{label.padEnd(LABEL_WIDTH)}</Text>
411 <Text color={color} wrap="truncate-end">
412 {fit(value, width - LABEL_WIDTH)}
413 </Text>
414 </Box>
415 )
416 const chip = (key: string, tone: ChipTone, parts: ChipPart[]) => {
417 const colors = palette.chips[tone]
418 const style: Record<ChipPart[1], { color: string; weight?: 'bold'; dimColor?: boolean }> = {
419 label: { color: colors.accent, weight: 'bold' },
420 value: { color: colors.text, weight: 'bold' },
421 aside: { color: colors.muted },
422 accent: { color: colors.accent },
423 off: { color: colors.muted, dimColor: true },
424 }
425 const last = parts.length - 1
426
427 return (
428 <Box key={`chip:${key}`} flexDirection="row" flexShrink={0}>
429 {parts.map(([text, kind], index) => (
430 <Text key={`${key}:${index}`} backgroundColor={colors.tint} {...style[kind]}>
431 {`${index === 0 ? ' ' : ''}${text}${index === last ? ' ' : ''}`}
432 </Text>
433 ))}
434 </Box>
435 )
436 }
437 const recapBlock = (label: string, recap: TurnRecap | null) => {
438 if (recap === null) return null
439
440 return (
441 <Box key={`recap:${label}`} flexDirection="column">
442 {heading(label)}
443 <Text color={palette.muted}>{fit(recapSummary(recap, now).join(' · '), width)}</Text>
444 {recap.lines.map((line, index) => (
445 <Text key={`${label}:${index}`} color={palette.text} wrap="wrap">
446 {line}
447 </Text>
448 ))}
449 </Box>
450 )
451 }
452
453 const artworkCells = artwork !== null && artwork.width <= width ? makeHalfBlockCells(artwork, palette.background) : null
454 const art = () => artworkCells === null ? null : <Raster key="flower" columns={artworkCells.columns} rows={artworkCells.rows} cells={artworkCells.cells} />
455 const title = (snapshot: GitSnapshot, titleWidth: number) => {
456 const banner = bannerFor(titleWidth)
457
458 return (
459 <Box flexDirection="column">
460 {banner !== null && (
461 <Box flexDirection="column" marginBottom={1}>
462 {banner.map((bannerRow, index) => (
463 <Text key={`banner:${index}`} color={palette.accent} weight="bold">
464 {bannerRow}
465 </Text>
466 ))}
467 </Box>
468 )}
469 <Text color={palette.accent} weight="bold">
470 {fit(snapshot.worktree ?? snapshot.projectName, titleWidth)}
471 </Text>
472 {snapshot.worktree !== null && <Text color={palette.text}>{fit(`project ${snapshot.projectName}`, titleWidth)}</Text>}
473 {snapshot.remoteName !== null && <Text color={palette.muted}>{fit(snapshot.remoteName, titleWidth)}</Text>}
474 <Text color={palette.muted} dimColor>
475 {fit(shortenHome(snapshot.root, home), titleWidth)}
476 </Text>
477 </Box>
478 )
479 }
480 const header = (snapshot: GitSnapshot) => {
481 const artColumns = artworkCells === null ? 0 : artworkCells.columns + 2
482 const isSideBySide = artworkCells !== null && artColumns + Math.max(bannerWidth(narrowBanner), (snapshot.worktree ?? snapshot.projectName).length) <= width
483
484 if (isSideBySide) {
485 return (
486 <Box alignItems="center">
487 <Box marginRight={2}>{art()}</Box>
488 {title(snapshot, width - artColumns)}
489 </Box>
490 )
491 }
492
493 return (
494 <Box flexDirection="column">
495 {artworkCells !== null && <Box marginBottom={1}>{art()}</Box>}
496 {title(snapshot, width)}
497 </Box>
498 )
499 }
500 const frame = (children: RenderChildren) => (
501 <Box flexDirection="column" width="100%" minHeight={Math.max(1, e.props.scroll.bodyRows)} paddingX={1} backgroundColor={palette.background}>
502 {children}
503 </Box>
504 )
505
506 if (snapshot === null) {
507 return frame(<Text color={palette.muted}>Reading the repository…</Text>)
508 }
509
510 const view: PaneFacts = { snapshot, turn, prior, facts, now, home }
511 const upstreamNote = UPSTREAM_NOTE[snapshot.upstreamStatus]
512 const otherWorktrees = snapshot.worktrees.filter(worktree => !worktree.isCurrent)
513
514 return frame(
515 <Box flexDirection="column">
516 {header(snapshot)}
517 <Box flexDirection="row" flexWrap="wrap" columnGap={1} marginTop={1}>
518 {chips(view).map(part => chip(part.key, part.tone, part.parts))}
519 </Box>
520 {!snapshot.isRepo && (
521 <Box marginTop={1}>
522 <Text color={palette.muted}>not a git repository</Text>
523 </Box>
524 )}
525 {snapshot.isRepo && (
526 <Box flexDirection="column">
527 {heading('Git')}
528 {row('branch', snapshot.branch ?? 'HEAD (detached)', snapshot.branch === null ? palette.warning : palette.text)}
529 {snapshot.worktree !== null && row('worktree', snapshot.worktree)}
530 {row('upstream', snapshot.upstream ?? 'none', upstreamColor(palette, snapshot.upstreamStatus))}
531 {upstreamNote !== null && (
532 <Text color={upstreamColor(palette, snapshot.upstreamStatus)} wrap="truncate-end">
533 {fit(` ! ${upstreamNote}`, width)}
534 </Text>
535 )}
536 {snapshot.pushTarget !== null && row('push', snapshot.pushTarget, palette.warning)}
537 {row('sync', `${syncText(snapshot)} ${changedText(snapshot)}`, isInSync(snapshot) ? palette.ok : palette.text)}
538 {otherWorktrees.length > 0 && (
539 <Box flexDirection="column">
540 {heading(`Worktrees (${otherWorktrees.length})`)}
541 {otherWorktrees.map(worktree => (
542 <Box key={`w:${worktree.path}`} flexDirection="column">
543 <Text color={palette.text} wrap="truncate-end">
544 {fit(`${worktree.name}${worktree.branch === null ? ' (detached)' : ''}${worktree.status === 'ok' ? '' : ` (${worktree.status})`}`, width)}
545 </Text>
546 <Text color={upstreamColor(palette, worktree.status)} wrap="truncate-end">
547 {fit(` → ${worktree.upstream ?? 'none'}`, width)}
548 </Text>
549 </Box>
550 ))}
551 </Box>
552 )}
553 </Box>
554 )}
555 {recapBlock('Last turn', turn)}
556 {showsPrior && recapBlock('Previous session', prior)}
557 {snapshot.isRepo && (
558 <Box flexDirection="column">
559 {heading('Commits')}
560 {snapshot.commits.length === 0 && <Text color={palette.muted}>no commits yet</Text>}
561 {snapshot.commits.map(commit => (
562 <Box key={`c:${commit.hash}`}>
563 <Text color={palette.hash}>{commit.hash.slice(0, 8)} </Text>
564 <Text color={palette.muted}>{shortAge(commit.age).padEnd(3)} </Text>
565 <Text color={palette.text} wrap="truncate-end">
566 {fit(commit.subject, width - 13)}
567 </Text>
568 </Box>
569 ))}
570 </Box>
571 )}
572 <Box marginTop={1}>
573 <Button key="refresh" label="Refresh" hotkey="r" onPress={() => void refreshGit($, commitCount)} />
574 <Text> </Text>
575 <Button key="hide" label="Hide" hotkey="h" role="dismiss" onPress={() => $.ui.close({ id: PANE_ID })} />
576 </Box>
577 </Box>,
578 )
579 })
580}
581hooks/band.ts 155 lines1import type { RateLimit, SessionFacts, TurnCost } from '../types'
2import { formatUsd, recentSpend, sparkline } from './cost'
3import { formatTokens } from './recap'
4
5export type BandTone = 'ok' | 'warn' | 'crit'
6export type BarCell = 'on' | 'off' | 'mark'
7
8// The status line's four steps for a rate-limit bar, plus the context bar's own color.
9export type BarColor = 'low' | 'mid' | 'high' | 'crit' | 'context'
10
11export type BandGroup = {
12 key: string
13 label: string
14 percent: number | null
15 elapsedShare: number | null
16 tone: BandTone
17 barColor: BarColor
18 value: string
19 spark: string | null
20 asides: string[]
21}
22
23const WINDOW_MS: Record<string, number> = { five_hour: 5 * 3_600_000, seven_day: 7 * 24 * 3_600_000 }
24const LIMIT_LABEL: Record<string, string> = { five_hour: '5h', seven_day: '7d', spend_limit: 'spend' }
25const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
26const DAY_MS = 24 * 3_600_000
27// Two bars compare nothing worth a glance and read as a broken glyph.
28export const SPARK_MIN_TURNS = 3
29const SPARK_TURNS = 12
30const BAR_GLYPH: Record<BarCell, string> = { on: '■', off: '□', mark: '▣' }
31
32export function clampPercent(percent: number): number {
33 return Math.max(0, Math.min(100, Math.round(percent)))
34}
35
36// Read the way the status line prints a reset: local clock time, with the
37// weekday once the reset is more than a day away.
38export function clockTime(at: number): string {
39 const date = new Date(at)
40 const hours = date.getHours()
41
42 return `${hours % 12 === 0 ? 12 : hours % 12}:${String(date.getMinutes()).padStart(2, '0')}${hours < 12 ? 'am' : 'pm'}`
43}
44
45export function resetClock(resetsAt: number, now: number): string {
46 const time = clockTime(resetsAt)
47
48 return resetsAt - now < DAY_MS ? time : `${WEEKDAYS[new Date(resetsAt).getDay()] ?? ''} ${time}`
49}
50
51export function shortTokens(count: number): string {
52 return count >= 1_000_000 ? `${+(count / 1_000_000).toFixed(1)}M` : formatTokens(count)
53}
54
55export function windowElapsed(limit: RateLimit, now: number): number | null {
56 const span = WINDOW_MS[limit.kind]
57 const resetsAt = limit.resetsAt === null ? Number.NaN : Date.parse(limit.resetsAt)
58 if (span === undefined || Number.isNaN(resetsAt)) return null
59
60 return Math.min(1, Math.max(0, 1 - Math.max(0, resetsAt - now) / span))
61}
62
63// A window is judged by its level and by its pace: 40% used a tenth into the
64// window runs out long before the reset.
65export function limitTone(limit: RateLimit, now: number): BandTone {
66 const percent = clampPercent(limit.percentUsed)
67 const elapsed = windowElapsed(limit, now)
68 const projected = elapsed === null || elapsed < 0.1 ? null : percent / elapsed
69
70 if (percent >= 90 || (projected !== null && projected >= 150 && percent >= 30)) return 'crit'
71 if (percent >= 70 || (projected !== null && projected >= 100 && percent >= 20)) return 'warn'
72
73 return 'ok'
74}
75
76// The status line steps by level alone; a fast pace lifts the step here too.
77export function limitBarColor(percent: number, tone: BandTone): BarColor {
78 if (percent >= 90 || tone === 'crit') return 'crit'
79 if (percent >= 70) return 'high'
80 if (percent >= 50 || tone === 'warn') return 'mid'
81
82 return 'low'
83}
84
85export function contextTone(percent: number): BandTone {
86 if (percent >= 85) return 'crit'
87 if (percent >= 70) return 'warn'
88
89 return 'ok'
90}
91
92export function barRuns(percent: number, elapsedShare: number | null, width: number): [text: string, cell: BarCell][] {
93 const filled = Math.round((percent / 100) * width)
94 const markAt = elapsedShare === null ? -1 : Math.min(width - 1, Math.floor(elapsedShare * width))
95 const runs: [string, BarCell][] = []
96
97 for (let index = 0; index < width; index += 1) {
98 const cell: BarCell = index === markAt ? 'mark' : index < filled ? 'on' : 'off'
99 const last = runs[runs.length - 1]
100
101 if (last !== undefined && last[1] === cell) last[0] += BAR_GLYPH[cell]
102 else runs.push([BAR_GLYPH[cell], cell])
103 }
104
105 return runs
106}
107
108export function bandGroups(facts: SessionFacts, now: number, isWide: boolean, turns: readonly TurnCost[]): BandGroup[] {
109 const groups: BandGroup[] = facts.rateLimits.map(limit => {
110 const percent = clampPercent(limit.percentUsed)
111 const tone = limitTone(limit, now)
112 const resetsAt = limit.resetsAt === null ? Number.NaN : Date.parse(limit.resetsAt)
113
114 return {
115 key: `limit:${limit.kind}`,
116 label: LIMIT_LABEL[limit.kind] ?? limit.kind,
117 percent,
118 elapsedShare: windowElapsed(limit, now),
119 tone,
120 barColor: limitBarColor(percent, tone),
121 value: `${percent}%`,
122 spark: null,
123 asides: Number.isNaN(resetsAt) || resetsAt <= now ? [] : [`→ ${resetClock(resetsAt, now)}`],
124 }
125 })
126
127 if (facts.contextPercent !== null) {
128 const percent = clampPercent(facts.contextPercent)
129 const asides = [
130 isWide && facts.contextTokens !== null && facts.contextWindow !== null ? `${shortTokens(facts.contextTokens)}/${shortTokens(facts.contextWindow)}` : null,
131 facts.contextDelta !== null && facts.contextDelta !== 0 ? `${facts.contextDelta > 0 ? '+' : '−'}${shortTokens(Math.abs(facts.contextDelta))}` : null,
132 ].filter((aside): aside is string => aside !== null)
133
134 groups.push({ key: 'context', label: 'ctx', percent, elapsedShare: null, tone: contextTone(percent), barColor: 'context', value: `${percent}%`, spark: null, asides })
135 }
136
137 if (facts.costUsd !== null) {
138 const lastHour = recentSpend(turns, now)
139
140 groups.push({
141 key: 'cost',
142 label: 'cost',
143 percent: null,
144 elapsedShare: null,
145 tone: 'ok',
146 barColor: 'low',
147 value: formatUsd(facts.costUsd),
148 spark: turns.length < SPARK_MIN_TURNS ? null : sparkline(turns.slice(-SPARK_TURNS).map(turn => turn.usd)),
149 asides: isWide && lastHour !== null ? [`1h ${formatUsd(lastHour)}`] : [],
150 })
151 }
152
153 return groups
154}
155hooks/banner.ts 91 lines1export const BANNER_ROWS = 3
2
3// Each glyph is 3 by 5 pixels ('#' is ink). Drawn two cell columns per pixel,
4// every stem is a full cell wide, which is what keeps the letters readable at
5// small font sizes; one column per pixel is the fallback for panes too narrow
6// for that. Pixel rows pair up into cells with the upper and lower half
7// blocks, which leaves one blank pixel row under the letters.
8const PIXEL_GLYPHS: Record<string, readonly string[]> = {
9 A: ['.#.', '#.#', '###', '#.#', '#.#'],
10 B: ['##.', '#.#', '##.', '#.#', '##.'],
11 C: ['.##', '#..', '#..', '#..', '.##'],
12 D: ['##.', '#.#', '#.#', '#.#', '##.'],
13 E: ['###', '#..', '##.', '#..', '###'],
14 F: ['###', '#..', '##.', '#..', '#..'],
15 G: ['.##', '#..', '#.#', '#.#', '.##'],
16 H: ['#.#', '#.#', '###', '#.#', '#.#'],
17 I: ['###', '.#.', '.#.', '.#.', '###'],
18 J: ['..#', '..#', '..#', '#.#', '.#.'],
19 K: ['#.#', '#.#', '##.', '#.#', '#.#'],
20 L: ['#..', '#..', '#..', '#..', '###'],
21 M: ['#.#', '###', '###', '#.#', '#.#'],
22 N: ['##.', '#.#', '#.#', '#.#', '#.#'],
23 O: ['.#.', '#.#', '#.#', '#.#', '.#.'],
24 P: ['##.', '#.#', '##.', '#..', '#..'],
25 Q: ['.#.', '#.#', '#.#', '.#.', '..#'],
26 R: ['##.', '#.#', '##.', '#.#', '#.#'],
27 S: ['.##', '#..', '.#.', '..#', '##.'],
28 T: ['###', '.#.', '.#.', '.#.', '.#.'],
29 U: ['#.#', '#.#', '#.#', '#.#', '###'],
30 V: ['#.#', '#.#', '#.#', '#.#', '.#.'],
31 W: ['#.#', '#.#', '###', '###', '#.#'],
32 X: ['#.#', '#.#', '.#.', '#.#', '#.#'],
33 Y: ['#.#', '#.#', '.#.', '.#.', '.#.'],
34 Z: ['###', '..#', '.#.', '#..', '###'],
35 '0': ['###', '#.#', '#.#', '#.#', '###'],
36 '1': ['.#.', '##.', '.#.', '.#.', '###'],
37 '2': ['##.', '..#', '.#.', '#..', '###'],
38 '3': ['###', '..#', '.##', '..#', '###'],
39 '4': ['#.#', '#.#', '###', '..#', '..#'],
40 '5': ['###', '#..', '##.', '..#', '##.'],
41 '6': ['.##', '#..', '###', '#.#', '###'],
42 '7': ['###', '..#', '.#.', '.#.', '.#.'],
43 '8': ['###', '#.#', '###', '#.#', '###'],
44 '9': ['###', '#.#', '###', '..#', '##.'],
45 '-': ['...', '...', '###', '...', '...'],
46 '.': ['...', '...', '...', '...', '.#.'],
47 ' ': ['..', '..', '..', '..', '..'],
48}
49
50export type ColumnsPerPixel = 1 | 2
51
52function glyphCells(pixelRows: readonly string[], columnsPerPixel: ColumnsPerPixel): string[] {
53 const width = (pixelRows[0]?.length ?? 0) * columnsPerPixel
54 const cells: string[] = []
55
56 for (let row = 0; row < BANNER_ROWS; row += 1) {
57 let line = ''
58
59 for (let column = 0; column < width; column += 1) {
60 const pixelColumn = Math.floor(column / columnsPerPixel)
61 const upper = pixelRows[row * 2]?.[pixelColumn] === '#'
62 const lower = pixelRows[row * 2 + 1]?.[pixelColumn] === '#'
63
64 line += upper && lower ? '█' : upper ? '▀' : lower ? '▄' : ' '
65 }
66
67 cells.push(line)
68 }
69
70 return cells
71}
72
73export function renderBanner(text: string, columnsPerPixel: ColumnsPerPixel = 2): string[] {
74 const rows: string[] = ['', '', '']
75
76 for (const char of text.toUpperCase()) {
77 const glyph = PIXEL_GLYPHS[char]
78 if (glyph === undefined) continue
79
80 glyphCells(glyph, columnsPerPixel).forEach((part, index) => {
81 rows[index] = rows[index] === '' ? part : `${rows[index]} ${part}`
82 })
83 }
84
85 return rows[0] === '' ? [] : rows
86}
87
88export function bannerWidth(rows: readonly string[]): number {
89 return rows.reduce((widest, row) => Math.max(widest, row.length), 0)
90}
91hooks/cards.ts 236 lines1import type { GitSnapshot, SessionFacts, TurnRecap, UpstreamStatus } from '../types'
2import type { ChipTone } from './palette'
3import { formatDuration, formatTokens, relativeAge } from './recap'
4import { SIZE, cardInnerWidth, contextTone, drawCard, textWidth } from './svg'
5import type { CardBlock, Cls, Drawing, TextSegment, Tone } from './svg'
6
7export type PaneFacts = {
8 snapshot: GitSnapshot
9 turn: TurnRecap | null
10 prior: TurnRecap | null
11 facts: SessionFacts | null
12 now: number
13 home: string | null
14}
15
16export type Card = Drawing & { alt: string }
17
18export type ChipPart = [text: string, kind: 'label' | 'value' | 'aside' | 'accent' | 'off']
19export type Chip = { key: string; tone: ChipTone; parts: ChipPart[] }
20
21const CHIP_BAR = 6
22const BIG_SIZES = [SIZE.big, 18, 15]
23
24export const UPSTREAM_NOTE: Record<UpstreamStatus, string | null> = {
25 ok: null,
26 mismatch: 'name differs, git push is refused',
27 gone: 'remote branch was deleted',
28 none: 'no upstream, first push sets it',
29}
30
31export const UPSTREAM_TONE: Record<UpstreamStatus, Tone | null> = {
32 ok: 'green',
33 mismatch: 'red',
34 gone: 'yellow',
35 none: null,
36}
37
38export function fit(text: string, width: number): string {
39 if (width <= 1) return ''
40
41 return text.length > width ? `${text.slice(0, width - 1)}…` : text
42}
43
44export function shortAge(age: string): string {
45 return age.replace(/ ago$/, '').replace(/ (\w)\w+$/, '$1')
46}
47
48export function syncText(snapshot: GitSnapshot): string {
49 return `↑${snapshot.ahead} ↓${snapshot.behind}`
50}
51
52export function isInSync(snapshot: GitSnapshot): boolean {
53 return snapshot.dirty === 0 && snapshot.ahead === 0 && snapshot.behind === 0
54}
55
56export function changedText(snapshot: GitSnapshot): string {
57 return snapshot.dirty === 0 ? 'clean' : `${snapshot.dirty} changed`
58}
59
60export function shortenHome(path: string, home: string | null): string {
61 if (home === null || home === '' || !(path === home || path.startsWith(`${home}/`))) return path
62
63 return `~${path.slice(home.length)}`
64}
65
66export function recapSummary(recap: TurnRecap, now: number): string[] {
67 return [
68 relativeAge(recap.endedAt, now),
69 formatDuration(recap.durationMs),
70 `${recap.toolCalls} tools`,
71 recap.outputTokens === null ? null : `${formatTokens(recap.outputTokens)} out`,
72 recap.reason === 'answer' ? null : recap.reason,
73 ].filter((fact): fact is string => fact !== null)
74}
75
76function label(text: string): TextSegment {
77 return { text, cls: 'lb', weight: 700, size: SIZE.label }
78}
79
80function bigSize(text: string, width: number): number {
81 return BIG_SIZES.find(size => textWidth(text, size) <= cardInnerWidth(width)) ?? BIG_SIZES[BIG_SIZES.length - 1] ?? SIZE.big
82}
83
84export function placeCard(view: PaneFacts, width: number): Card {
85 const { snapshot, home } = view
86 const status = snapshot.upstreamStatus
87 const statusTone = UPSTREAM_TONE[status]
88 const note = UPSTREAM_NOTE[status]
89 const isWorktree = snapshot.worktree !== null
90 const name = snapshot.worktree ?? snapshot.projectName
91 const path = shortenHome(snapshot.root, home)
92 const blocks: CardBlock[] = [
93 { kind: 'big', text: name, cls: isWorktree ? 'purple' : 'cyan', size: bigSize(name, width) },
94 { kind: 'wrap', text: path, cls: 'mu' },
95 ]
96
97 if (isWorktree) {
98 blocks.push({ kind: 'row', segments: [label('PROJECT'), { text: snapshot.projectName, cls: 'fg', weight: 650, size: SIZE.value }] })
99 }
100
101 if (snapshot.isRepo) {
102 const changedCls: Cls = snapshot.dirty === 0 ? 'green' : 'yellow'
103 const isOk = status === 'ok'
104 const syncCls: Cls = isOk ? (snapshot.ahead === 0 && snapshot.behind === 0 ? 'green' : 'mu') : statusTone ?? 'mu'
105
106 blocks.push(
107 { kind: 'gap', px: 6 },
108 { kind: 'row', segments: [label('BRANCH')], right: { text: changedText(snapshot), cls: changedCls, weight: 700, size: SIZE.value } },
109 { kind: 'wrap', text: snapshot.branch ?? 'HEAD (detached)', cls: snapshot.branch === null ? 'yellow' : 'fg', weight: 650, size: SIZE.value },
110 { kind: 'gap', px: 6 },
111 {
112 kind: 'row',
113 segments: [label('UPSTREAM')],
114 right: { text: isOk ? (snapshot.ahead === 0 && snapshot.behind === 0 ? 'in sync' : syncText(snapshot)) : status, cls: syncCls, weight: 650 },
115 },
116 { kind: 'wrap', text: snapshot.upstream ?? 'none', cls: statusTone ?? 'mu', weight: 600 },
117 )
118
119 if (note !== null) blocks.push({ kind: 'line', text: `! ${note}`, cls: statusTone ?? 'mu' })
120 if (snapshot.pushTarget !== null) blocks.push({ kind: 'line', text: `push → ${snapshot.pushTarget}`, cls: 'yellow' })
121 }
122
123 const drawing = drawCard({
124 width,
125 tone: isWorktree ? 'purple' : 'cyan',
126 title: isWorktree ? 'WORKTREE' : 'PROJECT',
127 titleRight: snapshot.remoteName === null ? undefined : { text: snapshot.remoteName },
128 blocks,
129 })
130 const gitAlt = snapshot.isRepo
131 ? `, branch ${snapshot.branch ?? 'detached'}, ${changedText(snapshot)}, ${syncText(snapshot)}, upstream ${snapshot.upstream ?? 'none'} ${status}`
132 : ''
133
134 return {
135 ...drawing,
136 alt: `${isWorktree ? 'worktree' : 'project'} ${name} at ${path}${isWorktree ? `, project ${snapshot.projectName}` : ''}${gitAlt}`,
137 }
138}
139
140export function contextCard(view: PaneFacts, width: number): Card | null {
141 const { facts } = view
142 if (facts === null) return null
143
144 const percent = facts.contextPercent === null ? null : Math.round(facts.contextPercent)
145 const tone = percent === null ? 'blue' : contextTone(percent)
146 const blocks: CardBlock[] = [
147 { kind: 'big', text: percent === null ? '—' : `${percent}%`, cls: tone, side: `${facts.turns} turns` },
148 { kind: 'bar', percent: percent ?? 0, tone },
149 { kind: 'line', text: facts.model },
150 ]
151 const tokens = facts.contextTokens !== null && facts.contextWindow !== null ? `${formatTokens(facts.contextTokens)}/${formatTokens(facts.contextWindow)}` : null
152 const drawing = drawCard({ width, tone: 'blue', title: 'CONTEXT', titleRight: tokens === null ? undefined : { text: tokens }, blocks })
153
154 return { ...drawing, alt: `context ${percent === null ? 'unknown' : `${percent}%`}, ${facts.model}, ${facts.turns} turns` }
155}
156
157export function recapCard(title: string, recap: TurnRecap, now: number, width: number, tone: Tone | null): Card {
158 const summary = recapSummary(recap, now)
159 const [age = ''] = summary
160 const blocks: CardBlock[] = [
161 { kind: 'big', text: formatDuration(recap.durationMs), cls: tone ?? 'fg', side: summary.slice(2).join(' · ') },
162 ...recap.lines.map((line): CardBlock => ({ kind: 'wrap', text: line, cls: 'fg', maxLines: 3 })),
163 ]
164 const drawing = drawCard({ width, tone, title, titleRight: { text: age }, blocks })
165
166 return { ...drawing, alt: `${title.toLowerCase()}: ${summary.join(', ')}. ${recap.lines.join(' ')}` }
167}
168
169export function worktreesCard(view: PaneFacts, width: number): Card | null {
170 const others = view.snapshot.worktrees.filter(worktree => !worktree.isCurrent)
171 if (others.length === 0) return null
172
173 const blocks: CardBlock[] = others.flatMap((worktree): CardBlock[] => [
174 {
175 kind: 'row',
176 segments: [{ dot: UPSTREAM_TONE[worktree.status] ?? 'purple' }, { text: worktree.name, cls: 'fg', weight: 650, size: SIZE.value }],
177 right: worktree.branch === null ? { text: 'detached', cls: 'yellow' } : worktree.status === 'ok' ? undefined : { text: worktree.status, cls: UPSTREAM_TONE[worktree.status] ?? 'mu' },
178 },
179 { kind: 'row', segments: [{ text: ' →', cls: 'lb' }, { text: worktree.upstream ?? 'none', cls: UPSTREAM_TONE[worktree.status] ?? 'mu' }] },
180 ])
181 const drawing = drawCard({ width, tone: 'cyan', title: 'WORKTREES', titleRight: { text: String(others.length) }, blocks })
182
183 return { ...drawing, alt: `worktrees: ${others.map(worktree => `${worktree.name} → ${worktree.upstream ?? 'none'} ${worktree.status}`).join(', ')}` }
184}
185
186export function commitsCard(view: PaneFacts, width: number): Card {
187 const { commits } = view.snapshot
188 const blocks: CardBlock[] = commits.length === 0
189 ? [{ kind: 'line', text: 'no commits yet', cls: 'lb' }]
190 : commits.map((commit): CardBlock => ({
191 kind: 'row',
192 segments: [
193 { text: commit.hash.slice(0, 7), cls: 'purple', weight: 650, size: 11 },
194 { text: shortAge(commit.age).padStart(3), cls: 'lb', size: 11 },
195 { text: commit.subject, cls: 'fg' },
196 ],
197 }))
198 const drawing = drawCard({ width, tone: 'yellow', title: 'COMMITS', titleRight: { text: String(commits.length) }, blocks })
199
200 return { ...drawing, alt: `commits: ${commits.map(commit => `${commit.hash.slice(0, 7)} ${commit.subject}`).join(', ')}` }
201}
202
203function chipBar(percent: number, width = CHIP_BAR): ChipPart[] {
204 const filled = Math.round((percent / 100) * width)
205 const parts: ChipPart[] = [
206 ['━'.repeat(filled), 'accent'],
207 ['━'.repeat(width - filled), 'off'],
208 ]
209
210 return parts.filter(part => part[0] !== '')
211}
212
213export function chips(view: PaneFacts): Chip[] {
214 const { snapshot, facts } = view
215 const list: Chip[] = []
216 const status = snapshot.upstreamStatus
217 const statusTone: ChipTone = UPSTREAM_TONE[status] ?? 'slate'
218
219 if (facts !== null && facts.contextPercent !== null) {
220 const percent = Math.round(facts.contextPercent)
221 list.push({ key: 'ctx', tone: contextTone(percent), parts: [['ctx ', 'label'], ...chipBar(percent), [` ${percent}%`, 'value']] })
222 }
223
224 if (snapshot.isRepo) {
225 const parts: ChipPart[] = [['git ', 'label'], [fit(snapshot.branch ?? 'detached', 24), 'value']]
226 if (snapshot.dirty > 0) parts.push([` ±${snapshot.dirty}`, 'accent'])
227 if (snapshot.ahead > 0 || snapshot.behind > 0) parts.push([` ${syncText(snapshot)}`, 'aside'])
228 list.push({ key: 'git', tone: 'cyan', parts })
229 list.push({ key: 'upstream', tone: statusTone, parts: [['up ', 'label'], [status, 'value']] })
230 }
231
232 if (facts !== null) list.push({ key: 'model', tone: 'slate', parts: [[`${facts.model} · ${facts.turns} turns`, 'aside']] })
233
234 return list
235}
236hooks/flower.ts 23 lines1import type { PixelArt } from './raster'
2
3export const FLOWER: PixelArt = {
4 width: 14,
5 height: 14,
6 pixels: [
7 '000000000000000000000000000000869898c8d3d398a3a26a7c7b000000000000000000000000000000',
8 '000000000000000000000000476060e4e7e7eae8e9c7c7c594a4a30000000000005c6f6f000000000000',
9 '00000093b4b6d9dbdbc6cac96a7d7ee1e7e8e7e6e6c8cac9c8d0cf7f8f90c6d1d2d1d3d2c0c8c9000000',
10 '738989b4bcbbdfdedde2e1e1c2c5c3c0cbcae0dfdec2c1beaeb3b1c6cccbeae9e9ecebebdee4e5608083',
11 '647c7ed8d8d8e4e3e3e7e6e6d4d3d1b1bab8bec6c6b9bbb9bab9b6a9b3b0e3e1e1e8e7e7d2d8d8000000',
12 '000000cbd6d7f0f0f0eeededd9d7d68aa3a44ca7b159aeb897b4b5b4bab8dedcdcd9d9d99aabac000000',
13 '0000005b7173a7bcbec5d2d3d3d9d85ea0a722c2da21c3db56aab4b9c7c6d4dfdfd6dedf808e90000000',
14 'b3c7c9cdd1d1cfcdcbcccbc9b2b9b74f8c921e9fb121b7cc519aa2c4c7c6e1e0dfe8e7e7dcdbda798484',
15 'bdced0dbd9d9e1e0dfe9e8e8e8e8e79bacad43828846888e90a8a8cbcac8d8d6d5dbd9d9dad9d8bbc7c7',
16 '7e9596cbcac9e2e1e1eeeeeecfdadb9ab6b8bfc0beb8b8b6b4bcbab8c8c8e0e0dfd8d6d5d1d0cfa5b1b1',
17 '607273a0a7a6d8d9d8c7cfcf87a1a4cbd3d4e4e3e3dad8d8d5d4d36d898bcfd6d6dbe0df9eadac678182',
18 '00000000000058686a000000000000cad9dbedecece1dfe0cfcfcd5d7a7c000000000000000000000000',
19 '00000000000000000000000000000086a0a3bcd4d7d4d4d39ba4a3246870000000000000000000000000',
20 '000000000000000000000000000000000000000000809597466f73000000000000000000000000000000',
21 ].join(''),
22}
23hooks/git.ts 170 lines1import type { Commit, GitSnapshot, UpstreamStatus, WorktreeRow } from '../types'
2
3export type GitRun = (args: readonly string[]) => Promise<{ exitCode: number; stdout: string }>
4
5type RefRow = {
6 branch: string
7 upstream: string | null
8 remoteRef: string
9 track: string
10 push: string | null
11}
12
13export function basename(path: string): string {
14 const trimmed = path.replace(/\/+$/, '')
15
16 return trimmed.slice(trimmed.lastIndexOf('/') + 1)
17}
18
19export function parseRemoteName(remoteUrl: string | null): string | null {
20 if (remoteUrl === null || remoteUrl === '') return null
21
22 const match = /([^/:]+\/[^/:]+?)(?:\.git)?\/?$/.exec(remoteUrl)
23
24 return match?.[1] ?? null
25}
26
27export function judgeUpstream(branch: string | null, remoteRef: string, track: string): UpstreamStatus {
28 if (branch === null || remoteRef === '') return 'none'
29 if (track.includes('gone')) return 'gone'
30
31 return remoteRef === `refs/heads/${branch}` ? 'ok' : 'mismatch'
32}
33
34export function parseTrack(track: string): { ahead: number; behind: number } {
35 const ahead = /ahead (\d+)/.exec(track)
36 const behind = /behind (\d+)/.exec(track)
37
38 return { ahead: Number(ahead?.[1] ?? 0), behind: Number(behind?.[1] ?? 0) }
39}
40
41export function parseCommits(stdout: string): Commit[] {
42 return stdout
43 .split('\n')
44 .filter(line => line !== '')
45 .map(line => {
46 const [hash = '', age = '', ...subject] = line.split('\t')
47
48 return { hash, age, subject: subject.join('\t') }
49 })
50}
51
52export function parseRefs(stdout: string): Map<string, RefRow> {
53 const rows = new Map<string, RefRow>()
54
55 for (const line of stdout.split('\n')) {
56 if (line === '') continue
57
58 const [branch = '', upstream = '', remoteRef = '', track = '', push = ''] = line.split('\t')
59
60 rows.set(branch, {
61 branch,
62 upstream: upstream === '' ? null : upstream,
63 remoteRef,
64 track,
65 push: push === '' ? null : push,
66 })
67 }
68
69 return rows
70}
71
72export function parseWorktrees(stdout: string, refs: Map<string, RefRow>, currentRoot: string | null): WorktreeRow[] {
73 const rows: WorktreeRow[] = []
74 let path: string | null = null
75 let branch: string | null = null
76
77 const flush = () => {
78 if (path === null) return
79
80 const ref = branch === null ? undefined : refs.get(branch)
81
82 rows.push({
83 path,
84 name: basename(path),
85 branch,
86 upstream: ref?.upstream ?? null,
87 status: judgeUpstream(branch, ref?.remoteRef ?? '', ref?.track ?? ''),
88 isCurrent: path === currentRoot,
89 })
90 path = null
91 branch = null
92 }
93
94 for (const line of stdout.split('\n')) {
95 if (line.startsWith('worktree ')) {
96 flush()
97 path = line.slice('worktree '.length)
98 } else if (line.startsWith('branch refs/heads/')) {
99 branch = line.slice('branch refs/heads/'.length)
100 } else if (line === '') {
101 flush()
102 }
103 }
104 flush()
105
106 return rows
107}
108
109export async function readGitSnapshot(run: GitRun, cwd: string, commitCount: number, readAt: number): Promise<GitSnapshot> {
110 const empty: GitSnapshot = {
111 isRepo: false,
112 cwd,
113 root: cwd,
114 mainRoot: null,
115 projectName: basename(cwd),
116 remoteName: null,
117 branch: null,
118 worktree: null,
119 upstream: null,
120 upstreamStatus: 'none',
121 pushTarget: null,
122 ahead: 0,
123 behind: 0,
124 dirty: 0,
125 commits: [],
126 worktrees: [],
127 readAt,
128 }
129
130 const layout = await run(['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir', '--abbrev-ref', 'HEAD'])
131 if (layout.exitCode !== 0) return empty
132
133 const [toplevel = '', commonDir = '', head = ''] = layout.stdout.split('\n')
134 const mainRoot = commonDir.endsWith('/.git') ? commonDir.slice(0, -'/.git'.length) : toplevel
135 const branch = head === '' || head === 'HEAD' ? null : head
136
137 const [remote, refs, status, log, worktrees] = await Promise.all([
138 run(['config', '--get', 'remote.origin.url']),
139 run(['for-each-ref', '--format=%(refname:short)%09%(upstream:short)%09%(upstream:remoteref)%09%(upstream:track)%09%(push:short)', 'refs/heads/']),
140 run(['status', '--porcelain']),
141 run(['log', `--format=%h%x09%ar%x09%s`, '-n', String(commitCount)]),
142 run(['worktree', 'list', '--porcelain']),
143 ])
144
145 const refRows = parseRefs(refs.stdout)
146 const current = branch === null ? undefined : refRows.get(branch)
147 const upstream = current?.upstream ?? null
148 const { ahead, behind } = parseTrack(current?.track ?? '')
149
150 return {
151 isRepo: true,
152 cwd,
153 root: toplevel,
154 mainRoot,
155 projectName: basename(mainRoot),
156 remoteName: remote.exitCode === 0 ? parseRemoteName(remote.stdout.trim()) : null,
157 branch,
158 worktree: toplevel === mainRoot ? null : basename(toplevel),
159 upstream,
160 upstreamStatus: judgeUpstream(branch, current?.remoteRef ?? '', current?.track ?? ''),
161 pushTarget: current?.push !== null && current?.push !== undefined && current.push !== upstream ? current.push : null,
162 ahead,
163 behind,
164 dirty: status.stdout.split('\n').filter(line => line !== '').length,
165 commits: log.exitCode === 0 ? parseCommits(log.stdout) : [],
166 worktrees: parseWorktrees(worktrees.stdout, refRows, toplevel),
167 readAt,
168 }
169}
170hooks/palette.ts 108 lines1export type ThemeName = 'light' | 'dark'
2
3export type ChipTone = 'green' | 'yellow' | 'red' | 'blue' | 'purple' | 'cyan' | 'slate'
4
5// tint is the chip's background; text, accent and muted are drawn on it
6export type Chip = {
7 tint: string
8 text: string
9 accent: string
10 muted: string
11}
12
13export type Palette = {
14 background: string
15 accent: string
16 text: string
17 muted: string
18 hash: string
19 ok: string
20 warning: string
21 error: string
22 chips: Record<ChipTone, Chip>
23}
24
25export const PALETTES: Record<ThemeName, Palette> = {
26 light: {
27 background: '#f7f7f7',
28 accent: '#0f54d6',
29 text: '#202020',
30 muted: '#606060',
31 hash: '#6b2fba',
32 ok: '#1b6600',
33 warning: '#826a00',
34 error: '#ad0f00',
35 chips: {
36 green: { tint: '#dcf1e4', text: '#123f28', accent: '#1b7f4b', muted: '#4f7d62' },
37 yellow: { tint: '#f6ebc4', text: '#4a3700', accent: '#9a6b00', muted: '#857449' },
38 red: { tint: '#f9dad6', text: '#5e160d', accent: '#c4402b', muted: '#9a6a65' },
39 blue: { tint: '#dbe5fb', text: '#17295e', accent: '#3563d1', muted: '#6775a3' },
40 purple: { tint: '#e5dffa', text: '#2a2064', accent: '#6a52cc', muted: '#7d76a6' },
41 cyan: { tint: '#d4ecf0', text: '#0d4148', accent: '#167f8c', muted: '#5b8b91' },
42 slate: { tint: '#e5e5e9', text: '#26262c', accent: '#5b5b66', muted: '#787884' },
43 },
44 },
45 dark: {
46 background: '#181825',
47 accent: '#cc6480',
48 text: '#cdd6f4',
49 muted: '#b4a5aa',
50 hash: '#fab387',
51 ok: '#a3c9a8',
52 warning: '#f9e2af',
53 error: '#e78284',
54 chips: {
55 green: { tint: '#1f3128', text: '#dcefe0', accent: '#a3c9a8', muted: '#88a58d' },
56 yellow: { tint: '#382f1c', text: '#faefd0', accent: '#f9e2af', muted: '#b3a47d' },
57 red: { tint: '#431f24', text: '#f8dcdc', accent: '#e78284', muted: '#b78c8f' },
58 blue: { tint: '#1f2a46', text: '#d9e3fa', accent: '#89b4fa', muted: '#8b9ac0' },
59 purple: { tint: '#4a1a2c', text: '#f5dbe3', accent: '#e48aa3', muted: '#b98e9b' },
60 cyan: { tint: '#16323a', text: '#d0eef2', accent: '#89dceb', muted: '#7eaab0' },
61 slate: { tint: '#2b2428', text: '#e6dade', accent: '#b4a5aa', muted: '#a0939a' },
62 },
63 },
64}
65
66// The status line's colors (~/.claude/statusline.sh), so the band above the
67// prompt reads as the same family as the lines under it. Change both together.
68export type BandPalette = {
69 separator: string
70 label: string
71 value: string
72 spark: string
73 bars: Record<'low' | 'mid' | 'high' | 'crit' | 'context', string>
74}
75
76export const BAND_PALETTES: Record<ThemeName, BandPalette> = {
77 light: {
78 separator: '#adadad',
79 label: '#606060',
80 value: '#202020',
81 spark: '#6b2fba',
82 bars: { low: '#005c43', mid: '#826a00', high: '#a14916', crit: '#ad0f00', context: '#ad0f00' },
83 },
84 dark: {
85 separator: '#7f849c',
86 label: '#bac2de',
87 value: '#cdd6f4',
88 spark: '#b4befe',
89 bars: { low: '#94e2d5', mid: '#f9e2af', high: '#fab387', crit: '#f38ba8', context: '#f38ba8' },
90 },
91}
92
93export function resolveTheme(option: unknown, settingsTheme: unknown): ThemeName {
94 if (option === 'light' || option === 'dark') return option
95
96 return typeof settingsTheme === 'string' && settingsTheme.startsWith('light') ? 'light' : 'dark'
97}
98
99// A custom theme is stored as custom:<slug> and is a preset plus overrides;
100// the slug names ~/.claude/themes/<slug>.json, whose "base" is that preset.
101export function customThemeSlug(settingsTheme: unknown): string | null {
102 if (typeof settingsTheme !== 'string' || !settingsTheme.startsWith('custom:')) return null
103
104 const slug = settingsTheme.slice('custom:'.length)
105
106 return /^[A-Za-z0-9_-]+$/.test(slug) ? slug : null
107}
108hooks/raster.ts 74 lines1export type PixelArt = {
2 width: number
3 height: number
4 pixels: string
5}
6
7export type RasterCells = {
8 columns: number
9 rows: number
10 cells: string
11}
12
13const UPPER_HALF_BLOCK = 0x2580
14const BACKGROUND_LUMA_LIMIT = 40
15const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
16
17export function parseHexColor(hex: string): number {
18 return Number.parseInt(hex.replace(/^#/, ''), 16)
19}
20
21function luma(color: number): number {
22 const red = (color >> 16) & 0xff
23 const green = (color >> 8) & 0xff
24 const blue = color & 0xff
25
26 return (red * 299 + green * 587 + blue * 114) / 1000
27}
28
29function pixelAt(art: PixelArt, x: number, y: number, background: number): number {
30 if (y >= art.height) return background
31
32 const offset = (y * art.width + x) * 6
33 const color = Number.parseInt(art.pixels.slice(offset, offset + 6), 16)
34
35 return luma(color) < BACKGROUND_LUMA_LIMIT ? background : color
36}
37
38export function encodeBase64(bytes: Uint8Array): string {
39 let out = ''
40
41 for (let index = 0; index < bytes.length; index += 3) {
42 const first = bytes[index] ?? 0
43 const second = bytes[index + 1]
44 const third = bytes[index + 2]
45 const triple = (first << 16) | ((second ?? 0) << 8) | (third ?? 0)
46
47 out += BASE64[(triple >> 18) & 63]
48 out += BASE64[(triple >> 12) & 63]
49 out += second === undefined ? '=' : BASE64[(triple >> 6) & 63]
50 out += third === undefined ? '=' : BASE64[triple & 63]
51 }
52
53 return out
54}
55
56export function makeHalfBlockCells(art: PixelArt, backgroundHex: string): RasterCells {
57 const background = parseHexColor(backgroundHex)
58 const columns = art.width
59 const rows = Math.ceil(art.height / 2)
60 const words = new Uint32Array(columns * rows * 3)
61
62 for (let row = 0; row < rows; row += 1) {
63 for (let column = 0; column < columns; column += 1) {
64 const cell = (row * columns + column) * 3
65
66 words[cell] = UPPER_HALF_BLOCK
67 words[cell + 1] = pixelAt(art, column, row * 2, background)
68 words[cell + 2] = pixelAt(art, column, row * 2 + 1, background)
69 }
70 }
71
72 return { columns, rows, cells: encodeBase64(new Uint8Array(words.buffer)) }
73}
74hooks/recap.ts 72 lines1import type { TurnRecap } from '../types'
2
3export const RECAP_ROOTS_KEY = 'recap-roots'
4export const RECAP_ROOTS_LIMIT = 20
5
6export function recapKey(repoRoot: string): string {
7 return `recap:${repoRoot}`
8}
9
10export function firstLines(answer: string, count: number): string[] {
11 return answer
12 .split('\n')
13 .map(line => line.replace(/^\s*(?:#{1,6}\s+|[-*]\s+|\d+\.\s+|>\s*)/, '').replace(/[`*]/g, '').trim())
14 .filter(line => line !== '' && !/^[-=]{3,}$/.test(line))
15 .slice(0, count)
16}
17
18export function formatDuration(ms: number): string {
19 const seconds = Math.round(ms / 1000)
20 if (seconds < 60) return `${seconds}s`
21
22 const minutes = Math.floor(seconds / 60)
23 if (minutes < 60) return `${minutes}m ${seconds % 60}s`
24
25 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
26}
27
28export function formatTokens(count: number): string {
29 if (count < 1000) return String(count)
30 if (count < 10000) return `${(count / 1000).toFixed(1)}k`
31
32 return `${Math.round(count / 1000)}k`
33}
34
35export function relativeAge(fromMs: number, nowMs: number): string {
36 const seconds = Math.max(0, Math.round((nowMs - fromMs) / 1000))
37 if (seconds < 60) return 'just now'
38
39 const minutes = Math.floor(seconds / 60)
40 if (minutes < 60) return `${minutes}m ago`
41
42 const hours = Math.floor(minutes / 60)
43 if (hours < 48) return `${hours}h ago`
44
45 return `${Math.floor(hours / 24)}d ago`
46}
47
48export function makeRecap(input: {
49 answer: string
50 durationMs: number
51 toolCalls: number
52 outputTokens: number | null
53 reason: string
54 repoRoot: string | null
55 endedAt: number
56 lineCount: number
57}): TurnRecap {
58 return {
59 repoRoot: input.repoRoot,
60 endedAt: input.endedAt,
61 durationMs: input.durationMs,
62 toolCalls: input.toolCalls,
63 outputTokens: input.outputTokens,
64 reason: input.reason,
65 lines: firstLines(input.answer, input.lineCount),
66 }
67}
68
69export function rememberRoot(roots: readonly string[], repoRoot: string): string[] {
70 return [repoRoot, ...roots.filter(root => root !== repoRoot)].slice(0, RECAP_ROOTS_LIMIT)
71}
72hooks/cost.ts 27 lines1import type { TurnCost } from '../types'
2
3export const RECENT_SPEND_MS = 3_600_000
4
5const SPARK = '▁▂▃▄▅▆▇█'
6
7// Each bar is scaled to the dearest turn shown, so the line compares turns
8// with each other, not against a fixed amount.
9export function sparkline(values: readonly number[]): string {
10 const top = Math.max(...values, 0)
11 if (top <= 0) return SPARK[0]?.repeat(values.length) ?? ''
12
13 return values.map(value => SPARK[Math.min(SPARK.length - 1, Math.round((Math.max(0, value) / top) * (SPARK.length - 1)))] ?? '').join('')
14}
15
16// What the turns that ended in the last hour cost. A session left open for a
17// day makes its lifetime average per hour meaningless; this stays current.
18export function recentSpend(turns: readonly TurnCost[], now: number): number | null {
19 const recent = turns.filter(turn => now - turn.endedAt <= RECENT_SPEND_MS)
20
21 return recent.length === 0 ? null : recent.reduce((sum, turn) => sum + turn.usd, 0)
22}
23
24export function formatUsd(usd: number): string {
25 return `$${usd.toFixed(2)}`
26}
27hooks/svg.ts 284 lines1// The desktop pane is drawn as SVG so it can follow the host's light or dark
2// appearance through prefers-color-scheme: the mods API exposes no appearance,
3// and an opaque Box background cannot follow it. Fills are translucent tints
4// over the host's own pane background, the way the usage-bar mod draws its band.
5
6export type Tone = 'green' | 'yellow' | 'red' | 'blue' | 'purple' | 'cyan'
7export type Cls = Tone | 'fg' | 'mu' | 'lb'
8
9export type TextSegment = { text: string; cls?: Cls; weight?: number; size?: number }
10export type Segment = TextSegment | { dot: Tone }
11
12export type CardBlock =
13 | { kind: 'big'; text: string; cls?: Cls; side?: string; sideCls?: Cls; size?: number }
14 | { kind: 'line'; text: string; cls?: Cls; size?: number }
15 | { kind: 'wrap'; text: string; cls?: Cls; size?: number; weight?: number; maxLines?: number }
16 | { kind: 'bar'; percent: number; tone: Tone }
17 | { kind: 'row'; segments: Segment[]; right?: TextSegment }
18 | { kind: 'gap'; px: number }
19
20export type Drawing = { source: string; width: number; height: number }
21
22const FONT = 'ui-monospace,SFMono-Regular,Menlo,Consolas,monospace'
23// A monospace glyph is about 0.62em wide; Hangul, kana, han and other
24// East Asian wide glyphs take a full em.
25const ADVANCE = 0.62
26const WIDE_GLYPH = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA960-\uA97F\uAC00-\uD7FF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/
27const TONES: readonly Tone[] = ['green', 'yellow', 'red', 'blue', 'purple', 'cyan']
28
29// [light, dark]
30const PALETTE: Record<Cls | 'track', readonly [string, string]> = {
31 fg: ['#1f1f24', '#ececf1'],
32 mu: ['#74747f', '#9b9ba8'],
33 lb: ['#8b8b96', '#7d7d8a'],
34 track: ['#0000001a', '#ffffff1f'],
35 green: ['#23875a', '#5fd19c'],
36 yellow: ['#a87708', '#e8bd3f'],
37 red: ['#c4402b', '#ff7b67'],
38 blue: ['#3563d1', '#86a6ff'],
39 purple: ['#6a52cc', '#a996ff'],
40 cyan: ['#167f8c', '#5cc9d6'],
41}
42
43// CSS pixels. The desktop host draws its own pane text at about 13px, so body
44// text sits just under that and the small-caps labels one step below it.
45export const SIZE = { label: 10, body: 12, value: 13, big: 22 }
46const LABEL_TRACKING = 0.8
47
48const CARD_PAD = 14
49const CARD_RADIUS = 11
50const TITLE_BASELINE = 21
51const BODY_TOP = 34
52const ROW_HEIGHT = 18
53const ROW_BASELINE = 13
54const BIG_HEIGHT = 30
55const BREAK_AFTER: readonly (readonly string[])[] = [[' '], ['/'], ['_', '-'], ['.']]
56
57export function escapeXml(text: string): string {
58 return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
59}
60
61function glyphWidth(glyph: string, size: number): number {
62 return size * (WIDE_GLYPH.test(glyph) ? 1 : ADVANCE)
63}
64
65export function textWidth(text: string, size: number, tracking = 0): number {
66 return [...text].reduce((width, glyph) => width + glyphWidth(glyph, size) + tracking, 0)
67}
68
69function fitCount(glyphs: readonly string[], size: number, room: number): number {
70 let width = 0
71 let count = 0
72
73 for (const glyph of glyphs) {
74 width += glyphWidth(glyph, size)
75 if (width > room + 0.001) break
76 count += 1
77 }
78
79 return count
80}
81
82export function cardInnerWidth(width: number): number {
83 return width - 2 * CARD_PAD
84}
85
86export function fitText(text: string, size: number, room: number): string {
87 const glyphs = [...text]
88
89 if (fitCount(glyphs, size, room) === glyphs.length) return text
90
91 const kept = fitCount(glyphs, size, room - glyphWidth('…', size))
92 if (kept === 0) return ''
93
94 return `${glyphs.slice(0, kept).join('')}…`
95}
96
97// Breaks after a separator in the back half of the line where there is one,
98// so `feature/NX-1_long-name` splits at a word, not mid-word. A space is
99// taken before a `/`, that before `_` or `-`, and those before a `.`, so prose
100// breaks at a word, a path at a folder and a branch outside a version number.
101function breakAt(glyphs: readonly string[], max: number): number {
102 for (const separators of BREAK_AFTER) {
103 for (let index = max; index > Math.floor(max / 2); index -= 1) {
104 if (separators.includes(glyphs[index - 1] ?? '')) return index
105 }
106 }
107
108 return max
109}
110
111export function wrapText(text: string, size: number, room: number, maxLines: number): string[] {
112 const glyphs = [...text]
113 const lines: string[] = []
114 let start = 0
115
116 if (glyphs.length === 0 || fitCount(glyphs.slice(0, 2), size, room) < 2) return lines
117
118 while (start < glyphs.length) {
119 const rest = glyphs.slice(start)
120 const max = fitCount(rest, size, room)
121
122 if (max === rest.length) {
123 lines.push(rest.join(''))
124 break
125 }
126
127 if (lines.length === maxLines - 1) {
128 lines.push(fitText(rest.join(''), size, room))
129 break
130 }
131
132 const cut = breakAt(rest, max)
133
134 lines.push(rest.slice(0, cut).join('').trimEnd())
135 start += cut
136 }
137
138 return lines
139}
140
141function styles(mode: 0 | 1): string {
142 const fills = (Object.keys(PALETTE) as (keyof typeof PALETTE)[]).map(name => `.${name}{fill:${PALETTE[name][mode]}}`).join('')
143 const cards = TONES.map(tone => `.card-${tone}{fill:${PALETTE[tone][mode]};fill-opacity:${mode ? 0.07 : 0.05};stroke:${PALETTE[tone][mode]};stroke-opacity:${mode ? 0.2 : 0.18}}`).join('')
144 const neutral = `.card-none{fill:${PALETTE.fg[mode]};fill-opacity:${mode ? 0.04 : 0.03};stroke:${PALETTE.fg[mode]};stroke-opacity:${mode ? 0.12 : 0.1}}`
145
146 return fills + cards + neutral
147}
148
149function document(width: number, height: number, body: string): string {
150 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" font-family="${FONT}">` +
151 `<style>${styles(0)}@media (prefers-color-scheme:dark){${styles(1)}}</style>${body}</svg>`
152}
153
154function text(x: number, baseline: number, content: string, options: { size: number; weight?: number; cls?: Cls; anchor?: 'end'; tracking?: number }): string {
155 const anchor = options.anchor === undefined ? '' : ` text-anchor="${options.anchor}"`
156 const tracking = options.tracking === undefined ? '' : ` letter-spacing="${options.tracking}"`
157
158 return `<text class="${options.cls ?? 'fg'}" x="${x.toFixed(1)}" y="${baseline.toFixed(1)}" font-size="${options.size}" font-weight="${options.weight ?? 500}"${anchor}${tracking}>${escapeXml(content)}</text>`
159}
160
161function segmentWidth(segment: Segment): number {
162 if ('dot' in segment) return 8
163
164 return textWidth(segment.text, segment.size ?? SIZE.body)
165}
166
167function segment(segment: Segment, x: number, baseline: number, room: number): string {
168 if ('dot' in segment) return `<circle class="${segment.dot}" cx="${x + 3.5}" cy="${baseline - 4}" r="3"/>`
169
170 const size = segment.size ?? SIZE.body
171
172 return text(x, baseline, fitText(segment.text, size, room), { size, weight: segment.weight, cls: segment.cls ?? 'mu' })
173}
174
175function wrapLines(block: Extract<CardBlock, { kind: 'wrap' }>, width: number): string[] {
176 return wrapText(block.text, block.size ?? SIZE.body, cardInnerWidth(width), block.maxLines ?? 2)
177}
178
179function blockHeight(block: CardBlock, width: number): number {
180 if (block.kind === 'big') return BIG_HEIGHT
181 if (block.kind === 'gap') return block.px
182 if (block.kind === 'wrap') return Math.max(1, wrapLines(block, width).length) * ROW_HEIGHT
183
184 return ROW_HEIGHT
185}
186
187function block(block: CardBlock, y: number, width: number): string {
188 const inner = cardInnerWidth(width)
189 const left = CARD_PAD
190
191 if (block.kind === 'gap') return ''
192
193 if (block.kind === 'big') {
194 const size = block.size ?? SIZE.big
195 const main = fitText(block.text, size, block.side === undefined ? inner : inner * 0.6)
196 let drawn = text(left, y + size, main, { size, weight: 700, cls: block.cls ?? 'fg' })
197
198 if (block.side !== undefined) {
199 const sideX = left + textWidth(main, size) + 8
200 drawn += text(sideX, y + size, fitText(block.side, SIZE.body, width - CARD_PAD - sideX), { size: SIZE.body, cls: block.sideCls ?? 'mu' })
201 }
202
203 return drawn
204 }
205
206 if (block.kind === 'line') {
207 const size = block.size ?? SIZE.body
208
209 return text(left, y + ROW_BASELINE, fitText(block.text, size, inner), { size, cls: block.cls ?? 'mu' })
210 }
211
212 if (block.kind === 'wrap') {
213 const size = block.size ?? SIZE.body
214
215 return wrapLines(block, width)
216 .map((line, index) => text(left, y + ROW_BASELINE + index * ROW_HEIGHT, line, { size, weight: block.weight, cls: block.cls ?? 'mu' }))
217 .join('')
218 }
219
220 if (block.kind === 'bar') {
221 const fill = block.percent > 0 ? Math.max(3, (block.percent / 100) * inner) : 0
222 const track = `<rect class="track" x="${left}" y="${y + 5}" width="${inner}" height="6" rx="3"/>`
223
224 return fill === 0 ? track : `${track}<rect class="${block.tone}" x="${left}" y="${y + 5}" width="${fill.toFixed(1)}" height="6" rx="3"/>`
225 }
226
227 const baseline = y + ROW_BASELINE
228 const rightWidth = block.right === undefined ? 0 : segmentWidth(block.right) + 8
229 let x = left
230 let drawn = ''
231
232 block.segments.forEach((part, index) => {
233 const isLast = index === block.segments.length - 1
234 const room = isLast ? width - CARD_PAD - rightWidth - x : segmentWidth(part)
235
236 if (room <= 0) return
237
238 drawn += segment(part, x, baseline, room)
239 x += ('dot' in part ? 8 : textWidth(fitText(part.text, part.size ?? SIZE.body, room), part.size ?? SIZE.body)) + 7
240 })
241
242 if (block.right !== undefined) {
243 const size = block.right.size ?? SIZE.body
244 drawn += text(width - CARD_PAD, baseline, block.right.text, { size, weight: block.right.weight, cls: block.right.cls ?? 'mu', anchor: 'end' })
245 }
246
247 return drawn
248}
249
250export function drawCard(options: {
251 width: number
252 tone: Tone | null
253 title: string
254 titleRight?: { text: string; cls?: Cls }
255 blocks: readonly CardBlock[]
256}): Drawing {
257 const { width } = options
258 let body = text(CARD_PAD, TITLE_BASELINE, options.title, { size: SIZE.label, weight: 700, cls: options.tone ?? 'lb', tracking: LABEL_TRACKING })
259
260 if (options.titleRight !== undefined) {
261 const room = cardInnerWidth(width) - textWidth(options.title, SIZE.label, LABEL_TRACKING) - 10
262 body += text(width - CARD_PAD, TITLE_BASELINE, fitText(options.titleRight.text, SIZE.body, room), { size: SIZE.body, cls: options.titleRight.cls ?? 'mu', anchor: 'end' })
263 }
264
265 let y = BODY_TOP
266
267 for (const part of options.blocks) {
268 body += block(part, y, width)
269 y += blockHeight(part, width)
270 }
271
272 const height = Math.max(y + 8, BODY_TOP + 12)
273 const frame = `<rect class="card-${options.tone ?? 'none'}" x=".5" y=".5" width="${width - 1}" height="${height - 1}" rx="${CARD_RADIUS}"/>`
274
275 return { source: document(width, height, frame + body), width, height }
276}
277
278export function contextTone(percent: number): Tone {
279 if (percent < 50) return 'blue'
280 if (percent < 75) return 'yellow'
281
282 return 'red'
283}
284types/index.d.ts 88 lines1export type UpstreamStatus = 'ok' | 'mismatch' | 'none' | 'gone'
2
3export type Commit = {
4 hash: string
5 age: string
6 subject: string
7}
8
9export type WorktreeRow = {
10 path: string
11 name: string
12 branch: string | null
13 upstream: string | null
14 status: UpstreamStatus
15 isCurrent: boolean
16}
17
18export type GitSnapshot = {
19 isRepo: boolean
20 cwd: string
21 root: string
22 mainRoot: string | null
23 projectName: string
24 remoteName: string | null
25 branch: string | null
26 worktree: string | null
27 upstream: string | null
28 upstreamStatus: UpstreamStatus
29 pushTarget: string | null
30 ahead: number
31 behind: number
32 dirty: number
33 commits: Commit[]
34 worktrees: WorktreeRow[]
35 readAt: number
36}
37
38export type TurnRecap = {
39 repoRoot: string | null
40 endedAt: number
41 durationMs: number
42 toolCalls: number
43 outputTokens: number | null
44 reason: string
45 lines: string[]
46}
47
48export type RateLimit = {
49 kind: string
50 percentUsed: number
51 resetsAt: string | null
52}
53
54export type SessionFacts = {
55 model: string
56 turns: number
57 contextPercent: number | null
58 contextTokens: number | null
59 contextWindow: number | null
60 contextDelta: number | null
61 rateLimits: RateLimit[]
62 costUsd: number | null
63 startedAt: number | null
64}
65
66export type TurnCost = {
67 endedAt: number
68 usd: number
69}
70
71export type TurnCosts = {
72 turns: TurnCost[]
73 startUsd: number | null
74}
75
76declare module 'claude-code' {
77 interface PluginState {
78 'dev-dashboard': {
79 git: Shaped<GitSnapshot | null>
80 lastTurn: Shaped<TurnRecap | null>
81 previous: Shaped<TurnRecap | null>
82 session: Shaped<SessionFacts | null>
83 isDismissed: boolean
84 costs: TurnCosts
85 }
86 }
87}
88