SLOPSHOPPER

usage-panel

Live Usage pane and a band above the prompt: when your tokens reload, calls, cost, context and rate limits; each prompt's tokens, models and subagents; and…

panebandrowscommandtimeragents
★ 1v0.9.1MITupdated 2026-10-26jamesnguyen1309/claude-usage
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-panel
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /usage-panel ⎿ usage-panel: Usage pane closed. ✓ — │ 0 tokens (0 out) │ 0s · ≈$0.000 Usage ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
✓ — │ 0 tokens (0 out) │ 0s · ≈$0.000 Usage ⟨Claude Code's own drawing⟩
README

📊 claude-usage

See what every prompt costs you in Claude Code: tokens, models and subagents, live.

usage-panel is a Claude Code mod: a live Usage pane beside the conversation and a one-line band above the prompt input.

version Claude Code surfaces license pulls unique pulls in the last 14 days


⚡ Install

On each device, in any shell:

gh api repos/jamesnguyen1309/claude-usage/contents/install.sh -H "Accept: application/vnd.github.raw" | bash

Then start a new Claude Code session: the Usage pane opens on its own.

Two commands, no script:

claude plugin marketplace add jamesnguyen1309/claude-usage
claude plugin install usage-panel@claude-usage --scope user

From inside a terminal claude session:

/plugin install usage-panel --marketplace jamesnguyen1309/claude-usage

Answer y to add the marketplace, then pick the user scope.

Only for one project: run the script with SCOPE=project (shared through the project's .claude/settings.json) or SCOPE=local (just you).

✨ What you get

Above the prompt input

One line for the prompt in progress (or the last one):

Modelthe main model as a chip, with its full id (claude-opus-5-5), plus a chip for each other model its subagents used
Tokensthe prompt's total across the main conversation and every subagent, and how many were output
Time · costhow long it has run, and what it cost
Usagea button that shows or hides the pane

The Usage pane

SectionShows
Statisticswhen your tokens next reload (a countdown to the soonest rate-limit reset, and which window it is), model calls and tool calls across the conversation (main and subagents), prompts sent, session cost, context window fill, and the 5-hour and 7-day limits with when each resets; meters turn amber at 70% and red at 90%
This prompttotal tokens, then figures for input, output, cache reads, cache writes, the cache hit rate and tokens per call; each model that worked on it: name, id, calls, tokens, its share of the prompt's tokens, and whether it ran the main conversation or subagents
Subagentseach subagent the prompt started, nested under the one that started it, with live status, model, time, calls, tools and tokens
Burn ratefor the 5-hour and 7-day limits: how fast each is being used (% per hour, % per day), and where that pace leads: Hits 100% at 14:52, 1h 22m before it reloads in red, or On pace for 71% when it reloads otherwise. A small chart shows the window so far, solid, and the pace carried on to the reload, dashed. Readings are kept across sessions, since the limits are your account's.
ContextExport context writes the conversation, as the context window holds it, to a Markdown file in ~/.claude/context-exports/<project>/: every message, and each tool call with its input and result (a tool's input or result over 8,000 characters is cut). The newest exports are listed with an Import button, which adds that export to this session's context as a note Claude reads with your next prompt. An import takes at most 60% of the free context window; a bigger one keeps its newest part.

While Claude works, a little animated Claude (the orange pixel crab, stepping and waving) marks what is running: the prompt card, each subagent and the band. The desktop app draws cards, bars and chips; a terminal gets the same figures as text. /usage-panel shows or hides the pane.

🔄 Update · remove

# after a new version is pushed (the install script does this too)
claude plugin marketplace update claude-usage && claude plugin update usage-panel@claude-usage

# remove
claude plugin uninstall usage-panel@claude-usage

Start a new session afterwards for the change to load.

📐 How the figures are counted

  • Tokens come from each model call's usage as the API reports it, main conversation and subagents together. Cache reads usually dominate: each call re-reads the conversation from cache, at a fraction of the price of fresh input.
  • Cost is Claude Code's own ledger, the one /cost totals. A prompt's cost is how much the session's total grew while it ran, subagents included; subagents show tokens, not dollars.
  • Per session: each session shows only its own prompts. Nothing leaves your machine.
  • Prompts sent before the mod loaded are listed once the conversation has drawn them, without figures.
  • The list doesn't jump to a prompt in the conversation: the desktop app doesn't let mods scroll its conversation (Claude Code answers transcript not scrollable here).

🛠 Develop

claude plugin validate .   # manifest, marketplace and hooks module
claude plugin test .       # behaviour tests, terminal and desktop
claude --plugin-dir .      # run a session with this working copy
FileRole
hooks/register.tsxthe hooks: bookkeeping, the pane, the band, the terminal views
hooks/draw.tsthe desktop drawings (SVG)
types/index.d.tsthe state contract
tests/usage-panel.test.tsbehaviour tests
install.shinstalls or updates the mod on a device
.claude-plugin/the mod's manifest and the marketplace that lists it

To release: bump version in both .claude-plugin/plugin.json and .claude-plugin/marketplace.json, push, then update on each device.

Source 5 files
hooks/register.tsx 748 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionUsage, TurnUsage } from 'claude-code'
3
4import { addSamples, burnOf } from './burn'
5import { estTokens, exportDir, exportName, formatExport, importNote } from './context'
6import type { AgentRun, BurnSample, ContextExport, ConversationTotals, ModelUse, PromptRow, PromptRun, RunStatus, SessionFigures, Tokens } from '../types'
7import {
8  agentRow,
9  bandRow,
10  burnCard,
11  cacheHit,
12  fmtResetAt,
13  fmtTime,
14  fmtTokens,
15  fmtUntil,
16  fmtUsd,
17  limitName,
18  mainModelOf,
19  modelName,
20  nextReset,
21  PARTS,
22  modelColor,
23  promptCard,
24  sessionTiles,
25  total,
26  whereOf,
27} from './draw'
28
29const PANE = 'usage-panel'
30const TITLE = 'Usage'
31const KEEP = 50
32
33const prompts = atom({ plugin: 'usage-panel', key: 'prompts' } as const, [])
34const session = atom({ plugin: 'usage-panel', key: 'session' } as const, {
35  costUsd: 0,
36  contextWindow: 0,
37  rateLimits: [],
38})
39const rows = atom({ plugin: 'usage-panel', key: 'rows' } as const, [])
40const totals = atom({ plugin: 'usage-panel', key: 'totals' } as const, null as ConversationTotals | null)
41
42// Rate-limit readings, in the store: the limits are the account's, so their history spans sessions.
43const SAMPLES = 'burn-samples'
44const readSamples = async ($: EngineInterface): Promise<BurnSample[]> => ((await $.store.get(SAMPLES)) as BurnSample[] | undefined) ?? []
45
46const now = atom({ plugin: 'usage-panel', key: 'now' } as const, 0)
47const exportsList = atom({ plugin: 'usage-panel', key: 'exports' } as const, [] as ContextExport[])
48const contextNote = atom({ plugin: 'usage-panel', key: 'contextNote' } as const, '')
49
50// ---- bookkeeping ------------------------------------------------------------------
51
52const zero = (): Tokens => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
53
54const add = (t: Tokens, u: TurnUsage): Tokens => ({
55  input: t.input + (u.input_tokens || 0),
56  output: t.output + (u.output_tokens || 0),
57  cacheRead: t.cacheRead + (u.cache_read_input_tokens || 0),
58  cacheWrite: t.cacheWrite + (u.cache_creation_input_tokens || 0),
59})
60
61const sum = (a: Tokens, b: Tokens): Tokens => ({
62  input: a.input + b.input,
63  output: a.output + b.output,
64  cacheRead: a.cacheRead + b.cacheRead,
65  cacheWrite: a.cacheWrite + b.cacheWrite,
66})
67
68/** The prompt's tokens: its main loop and every subagent. */
69const promptTokens = (p: PromptRun): Tokens => p.agents.reduce((t, a) => sum(t, a.tokens), p.tokens)
70
71// The conversation's totals before this mod counted them itself: what its prompts hold.
72const seedTotals = (list: PromptRun[]): ConversationTotals => ({
73  modelCalls: list.reduce((n, p) => n + p.calls + p.agents.reduce((m, a) => m + a.calls, 0), 0),
74  toolCalls: list.reduce((n, p) => n + p.tools + p.agents.reduce((m, a) => m + a.tools, 0), 0),
75  tokens: list.reduce((t, p) => sum(t, promptTokens(p)), zero()),
76})
77
78// Credits one model call to its model in the prompt's breakdown.
79const useModel = (models: ModelUse[], model: string, usage: TurnUsage | null, agentId?: string): ModelUse[] => {
80  if (!model) return models
81  const one = models.find(m => m.model === model) ?? { model, mainCalls: 0, agentCalls: 0, agentIds: [], tokens: zero() }
82  const next: ModelUse = {
83    ...one,
84    mainCalls: one.mainCalls + (agentId ? 0 : 1),
85    agentCalls: one.agentCalls + (agentId ? 1 : 0),
86    agentIds: agentId && !one.agentIds.includes(agentId) ? [...one.agentIds, agentId] : one.agentIds,
87    tokens: usage ? add(one.tokens, usage) : one.tokens,
88  }
89  return models.some(m => m.model === model) ? models.map(m => (m.model === model ? next : m)) : [...models, next]
90}
91
92const figures = (u: Pick<SessionUsage, 'context' | 'rateLimits' | 'cost'>): SessionFigures => ({
93  costUsd: u.cost?.usd ?? 0,
94  contextTokens: u.context.tokens,
95  contextWindow: u.context.window,
96  contextPercent: u.context.percent,
97  rateLimits: u.rateLimits.map(r => ({ kind: r.kind, percentUsed: r.percentUsed, resetsAt: r.resetsAt })),
98})
99
100// Subagents are filed under the prompt that was running when they started.
101const withCurrent = (list: PromptRun[], fn: (p: PromptRun) => PromptRun): PromptRun[] => {
102  const i = list.findLastIndex(p => p.status === 'running')
103  return i < 0 ? list : list.map((p, j) => (j === i ? fn(p) : p))
104}
105
106const withAgent = (list: PromptRun[], id: string, fn: (a: AgentRun) => AgentRun): PromptRun[] =>
107  list.map(p => (p.agents.some(a => a.id === id) ? { ...p, agents: p.agents.map(a => (a.id === id ? fn(a) : a)) } : p))
108
109const statusOf = (reason: string): RunStatus => (reason === 'answer' ? 'done' : reason === 'aborted' ? 'aborted' : 'failed')
110
111// Prompts kept by an earlier version of this mod may lack newer fields.
112const normalize = (p: PromptRun): PromptRun => ({ ...p, models: p.models ?? [] })
113
114const norm = (s: string): string => s.replace(/\s+/g, ' ').trim()
115
116// Your own prompts: typed here or sent from the Remote Control bridge.
117const isPersons = (origin: { kind: string } | undefined): boolean => origin?.kind === 'composer' || origin?.kind === 'bridge'
118
119// Records a prompt row once, by its id or, for a row first seen drawn, by its text.
120const addRow = (list: PromptRow[], row: { id: string; text: string; isDrawn: boolean; sentAt?: number }): PromptRow[] => {
121  const text = norm(row.text)
122  if (!text || list.some(r => r.id === row.id || r.renderId === row.id)) return list
123  if (row.isDrawn) {
124    // The row was appended earlier under its uuid: remember the id it is drawn under.
125    const i = list.findIndex(r => !r.renderId && r.text === text)
126    if (i >= 0) return list.map((r, j) => (j === i ? { ...r, renderId: row.id } : r))
127  }
128  if (!row.isDrawn) return [...list, { id: row.id, text, sentAt: row.sentAt }]
129  // Known only from its drawn row: sent before this mod was watching, so older than every
130  // appended row; it goes after the other rows like it, in the order they are drawn.
131  const at = list.findIndex(r => r.renderId !== r.id)
132  const drawnRow = { id: row.id, renderId: row.id, text }
133  return at < 0 ? [...list, drawnRow] : [...list.slice(0, at), drawnRow, ...list.slice(at)]
134}
135
136const oneLine = (s: string, max: number): string => {
137  const flat = norm(s)
138  return flat.length > max ? flat.slice(0, Math.max(1, max - 1)) + '…' : flat
139}
140
141const GLYPH: Record<RunStatus, string> = { running: '●', done: '✓', aborted: '◼', failed: '✗' }
142const COLOR: Record<RunStatus, string> = { running: 'cyan', done: 'green', aborted: 'yellow', failed: 'red' }
143
144const pctColor = (pct: number): string => (pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'green')
145
146const bar = (pct: number, width: number): string => {
147  const filled = Math.round((Math.min(100, Math.max(0, pct)) / 100) * width)
148  return '█'.repeat(filled) + '░'.repeat(width - filled)
149}
150
151const LIMIT_NAME: Record<string, string> = { five_hour: '5-hour', seven_day: '7-day', spend_limit: 'spend' }
152
153// ---- context export and import ----------------------------------------------------------
154
155/** Exports listed in the pane, newest first. */
156const EXPORTS_SHOWN = 4
157/** An import takes at most this share of the free context window, leaving room to work. */
158const IMPORT_SHARE = 0.6
159
160const contextFolder = async ($: EngineInterface): Promise<string> => {
161  const root = await $.session.root()
162  const home = await $.env.get('HOME')
163  return home ? exportDir(home, root) : `${root}/.claude/context-exports`
164}
165
166async function refreshExports($: EngineInterface): Promise<void> {
167  const dir = await contextFolder($)
168  const found = (await $.fs.exists(dir)) ? await $.fs.list(dir) : []
169  const list = found
170    .filter(f => f.kind === 'file' && f.name.endsWith('.md'))
171    .sort((a, b) => b.mtimeMs - a.mtimeMs)
172    .slice(0, EXPORTS_SHOWN)
173    .map(f => ({ name: f.name, path: `${dir}/${f.name}`, size: f.size, mtimeMs: f.mtimeMs }))
174  await update($, exportsList, () => list)
175}
176
177/** Writes the conversation, as the context window holds it, to a Markdown file. */
178async function exportContext($: EngineInterface): Promise<void> {
179  try {
180    const at = await $.clock.now()
181    const messages = await $.session.messages()
182    const text = formatExport(messages, { at, project: await $.session.root(), sessionId: await $.session.id(), model: await $.session.model() })
183    const path = `${await contextFolder($)}/${exportName(at)}`
184    await $.fs.write(path, text)
185    await update($, contextNote, () => `Exported ${messages.length} messages, ≈${fmtTokens(estTokens(text))} tokens, to ${path}`)
186    await refreshExports($)
187  } catch (err) {
188    await update($, contextNote, () => `Export failed: ${err instanceof Error ? err.message : String(err)}`)
189  }
190}
191
192/** Reads an export back into the context window: a note the model reads with the next prompt. */
193async function importContext($: EngineInterface, x: ContextExport): Promise<void> {
194  try {
195    const { context } = await $.session.usage()
196    const free = Math.max(0, context.window - (context.tokens ?? 0))
197    const budget = Math.floor(free * IMPORT_SHARE)
198    if (budget < 2000) {
199      await update($, contextNote, () => 'Not enough room in the context window to import: run /compact or /clear first.')
200      return
201    }
202    const note = importNote(await $.fs.read(x.path), x.name, budget)
203    const added = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: note.text }] } })
204    await update($, contextNote, () =>
205      added.deny !== undefined
206        ? `Import refused: ${added.deny}`
207        : `Imported ${x.name}, ≈${fmtTokens(note.tokens)} tokens${note.isCut ? ' (the oldest part left out to fit)' : ''}. Claude reads it with your next prompt.`,
208    )
209  } catch (err) {
210    await update($, contextNote, () => `Import failed: ${err instanceof Error ? err.message : String(err)}`)
211  }
212}
213
214// 18 Oct, 09:41
215const fmtStamp = (ms: number): string =>
216  new Date(ms).toLocaleString([], { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', hour12: false })
217
218async function togglePane($: EngineInterface): Promise<boolean> {
219  if ((await $.ui.panes()).some(p => p.id === PANE)) {
220    await $.ui.close({ id: PANE })
221    return false
222  }
223  await $.ui.open({ id: PANE, title: TITLE })
224  return true
225}
226
227// Prompt rows seen drawn, waiting to be saved: a render hook may not write state, so the
228// next event or the ticker saves them (within a second). Module scope: a reload redraws.
229let drawn: { id: string; text: string }[] = []
230
231async function saveDrawn($: EngineInterface): Promise<void> {
232  if (!drawn.length) return
233  const batch = drawn
234  drawn = []
235  await update($, rows, list => batch.reduce((l, r) => addRow(l, { ...r, isDrawn: true }), list))
236}
237
238export const register: Register = on => {
239  on('session.start', async ($, e, next) => {
240    const started = await next(e)
241    await $.command.register({
242      name: 'usage-panel',
243      description: 'Show or hide the live Usage pane: statistics, this prompt, burn rate, and context export and import',
244    })
245    try {
246      const usage = await $.session.usage()
247      await update($, session, () => figures(usage))
248      const at = await $.clock.now()
249      await update($, now, () => at)
250      if (usage.rateLimits.length) await $.store.set(SAMPLES, addSamples(await readSamples($), figures(usage).rateLimits, at))
251    } catch {
252      // No figures yet: the first session.measure fills them.
253    }
254    // Once a second: saves rows seen drawn, and ticks running clocks; when nothing runs, once a
255    // minute, for the reload countdown.
256    $.clock.every(1000, () => {
257      void (async () => {
258        await saveDrawn($)
259        const at = await $.clock.now()
260        const isRunning = (await read($, prompts)).some(p => p.status === 'running' || p.agents.some(a => a.status === 'running'))
261        if (!isRunning && Math.floor(at / 60_000) === Math.floor((await read($, now)) / 60_000)) return
262        await update($, now, () => at)
263      })()
264    })
265    void refreshExports($).catch(() => undefined)
266    void $.ui.open({ id: PANE, title: TITLE })
267    return started
268  })
269
270  on('command.run', { command: 'usage-panel' }, async $ => ({
271    text: (await togglePane($)) ? 'Usage pane opened.' : 'Usage pane closed.',
272  }))
273
274  // /clear starts the session over.
275  on('session.end', async ($, e, next) => {
276    if (e.reason === 'clear') {
277      await update($, prompts, () => [])
278      await update($, rows, () => [])
279      await update($, totals, () => null)
280      await update($, session, s => ({ ...s, costUsd: 0 }))
281    }
282    return next(e)
283  })
284
285  // Cost, context and rate limits, as the status line and /cost see them.
286  on('session.measure', async ($, e, next) => {
287    const result = await next(e)
288    await update($, session, () => figures(e))
289    if (e.rateLimits.length) {
290      const at = await $.clock.now()
291      const kept = await readSamples($)
292      const moved = addSamples(kept, figures(e).rateLimits, at)
293      if (JSON.stringify(moved) !== JSON.stringify(kept)) await $.store.set(SAMPLES, moved)
294    }
295    return result
296  })
297
298  // Your prompts as the conversation keeps them, by row id: the prompt list.
299  on('session.append', { door: 'prompt' }, async ($, e, next) => {
300    const result = await next(e)
301    await saveDrawn($)
302    if (!e.agentId && isPersons(e.origin)) {
303      const text = e.message.content.map(b => (b.type === 'text' ? b.text : '')).join('\n')
304      const sentAt = await $.clock.now()
305      await update($, rows, list => addRow(list, { id: e.uuid, text, isDrawn: false, sentAt }))
306    }
307    return result
308  })
309
310  // Your prompts' rows in the conversation, as drawn: prompts sent before this mod loaded,
311  // and the id each is drawn under (so it is listed once). The drawing is the engine's.
312  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
313    if (isPersons(e.props.origin)) {
314      const id = e.requestId
315      const known = await read($, rows)
316      if (!known.some(r => r.id === id || r.renderId === id) && !drawn.some(r => r.id === id)) {
317        drawn.push({ id, text: e.props.text })
318      }
319    }
320    return next(e)
321  })
322
323  // A main-loop turn: one per prompt (a subagent's run raises none).
324  on('turn.start', async ($, e, next) => {
325    const result = await next(e)
326    await saveDrawn($)
327    const at = await $.clock.now()
328    const { costUsd } = await read($, session)
329    const run: PromptRun = {
330      turnId: result.turnId ?? e.turnId,
331      text: e.text,
332      status: 'running',
333      startedAt: at,
334      model: '',
335      calls: 0,
336      tools: 0,
337      tokens: zero(),
338      costAtStart: costUsd,
339      agents: [],
340      models: [],
341    }
342    // A turn that never completed (the session was killed mid-turn) is closed here.
343    await update($, prompts, list =>
344      [...list.map(p => (p.status === 'running' ? { ...p, status: 'aborted' as const, endedAt: p.endedAt ?? at } : p)), run].slice(-KEEP),
345    )
346    await update($, now, () => at)
347    return result
348  })
349
350  // Every model call, main loop or subagent: tokens, model and the tools it asked for.
351  on('turn.step', async function* ($, e, next) {
352    const result = yield* next(e)
353    const usage = result.usage
354    const tools = result.toolUses.length
355    const model = usage?.model || e.model
356    // The conversation's running totals: every call, main loop and subagents alike.
357    const held = await read($, prompts)
358    await update($, totals, c => {
359      const base = c ?? seedTotals(held.map(normalize))
360      return { modelCalls: base.modelCalls + 1, toolCalls: base.toolCalls + tools, tokens: usage ? add(base.tokens, usage) : base.tokens }
361    })
362    if (e.agentId) {
363      const id = e.agentId
364      await update($, prompts, list =>
365        withAgent(list, id, a => ({
366          ...a,
367          model: model || a.model,
368          calls: a.calls + 1,
369          tools: a.tools + tools,
370          tokens: usage ? add(a.tokens, usage) : a.tokens,
371        })).map(p => (p.agents.some(a => a.id === id) ? { ...p, models: useModel(p.models ?? [], model, usage, id) } : p)),
372      )
373    } else {
374      await update($, prompts, list =>
375        list.map(p =>
376          p.turnId !== e.turnId
377            ? p
378            : {
379                ...p,
380                model: p.model || model,
381                calls: p.calls + 1,
382                tools: p.tools + tools,
383                tokens: usage ? add(p.tokens, usage) : p.tokens,
384                models: useModel(p.models ?? [], model, usage),
385              },
386        ),
387      )
388    }
389    return result
390  })
391
392  // A subagent started: filed under the running prompt, nested under its parent.
393  on('agent.spawn', async ($, e, next) => {
394    const started = await next(e)
395    if (started.deny !== undefined) return started
396    const at = await $.clock.now()
397    const run: AgentRun = {
398      id: started.agentId ?? e.tool_use_id,
399      parentId: e.parentAgentId,
400      type: e.subagentType,
401      description: e.description,
402      model: started.model,
403      status: 'running',
404      startedAt: at,
405      calls: 0,
406      tools: 0,
407      tokens: zero(),
408    }
409    await update($, prompts, list => withCurrent(list, p => ({ ...p, agents: [...p.agents.filter(a => a.id !== run.id), run] })))
410    await update($, now, () => at)
411    return started
412  }).catch(($, e, next) => next(e)) // bookkeeping only: never stand in a spawn's way
413
414  on('turn.complete', async ($, e, next) => {
415    const result = await next(e)
416    const at = await $.clock.now()
417    const status = statusOf(e.reason)
418    if (e.agentId) {
419      const id = e.agentId
420      await update($, prompts, list => withAgent(list, id, a => ({ ...a, status, endedAt: at })))
421    } else {
422      const { costUsd } = await read($, session)
423      await update($, prompts, list =>
424        list.map(p => (p.turnId === e.turnId ? { ...p, status, endedAt: at, costAtEnd: costUsd } : p)),
425      )
426    }
427    await update($, now, () => at)
428    return result
429  })
430
431  // ---- the pane -------------------------------------------------------------------
432
433  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
434    const ui = $.ui.resolve(e)
435    const { Box, Text, Button } = ui
436    const list = (await read($, prompts)).map(normalize)
437    const s = await read($, session)
438    const promptRows = await read($, rows)
439    const samples = await readSamples($)
440    const convo = (await read($, totals)) ?? seedTotals(list)
441    // `now` subscribes the pane to the ticker; the clock itself is what the burn rate reads against.
442    const at = Math.max(await read($, now), await $.clock.now(), ...list.map(p => p.startedAt), 0)
443
444    const costOf = (p: PromptRun): number =>
445      Math.max(0, (p.costAtEnd ?? (p.status === 'running' ? s.costUsd : p.costAtStart)) - p.costAtStart)
446    const elapsed = (r: { startedAt: number; endedAt?: number }) => (r.endedAt ?? at) - r.startedAt
447    const calls = (p: PromptRun) => p.calls + p.agents.reduce((n, a) => n + a.calls, 0)
448    const tools = (p: PromptRun) => p.tools + p.agents.reduce((n, a) => n + a.tools, 0)
449
450    // Agents in spawn order, each child right under its parent.
451    const ordered = (agents: AgentRun[]): { a: AgentRun; depth: number }[] => {
452      const ids = new Set(agents.map(a => a.id))
453      const out: { a: AgentRun; depth: number }[] = []
454      const walk = (parent: string | undefined, depth: number) => {
455        for (const a of agents) {
456          const isChild = parent === undefined ? !a.parentId || !ids.has(a.parentId) : a.parentId === parent
457          if (isChild) {
458            out.push({ a, depth })
459            walk(a.id, depth + 1)
460          }
461        }
462      }
463      walk(undefined, 0)
464      return out
465    }
466
467    const exportsShown = await read($, exportsList)
468    const ctxNote = await read($, contextNote)
469
470    // Context: export the conversation to a file, or read an export back in. The same on every surface.
471    const contextSection = (
472      <Box key="context" flexDirection="column" marginTop={1}>
473        <Box key="context-head" flexDirection="row" justifyContent="space-between" alignItems="center">
474          <Text bold>Context</Text>
475          <Button key="context-export" label="Export context" onPress={() => void exportContext($)} />
476        </Box>
477        {ctxNote ? (
478          <Text key="context-note" dimColor wrap="wrap">
479            {ctxNote}
480          </Text>
481        ) : null}
482        {exportsShown.length ? (
483          exportsShown.map(x => (
484            <Box key={`export:${x.name}`} flexDirection="row" justifyContent="space-between" alignItems="center" gap={1}>
485              <Text wrap="truncate-end">
486                {fmtStamp(x.mtimeMs)}
487                <Text dimColor> · ≈{fmtTokens(x.size / 4)} tokens</Text>
488              </Text>
489              <Button key={`import:${x.name}`} label="Import" onPress={() => void importContext($, x)} />
490            </Box>
491          ))
492        ) : (
493          <Text key="context-none" dimColor>
494            No exports yet: export this conversation to save it whole, then import it here or in another session.
495          </Text>
496        )}
497      </Box>
498    )
499
500    const latest = list.at(-1)
501    // The prompt card and subagents show the latest prompt.
502    const focus = latest
503    const agents = focus ? ordered(focus.agents) : []
504
505    if (e.surface !== 'terminal' && 'Svg' in ui) {
506      const { Svg } = ui
507      const W = Math.max(260, Math.min(900, (e.props.bodyColumns || 48) * 8 - 8))
508      const tiles = sessionTiles(W, s, { now: at, prompts: promptRows.length, calls: convo })
509      const card = focus
510        ? promptCard(W, focus, promptTokens(focus), {
511            costUsd: costOf(focus),
512            elapsedMs: elapsed(focus),
513            calls: calls(focus),
514            tools: tools(focus),
515          })
516        : null
517      return (
518        <Box flexDirection="column" gap={1}>
519          <Svg key="tiles" source={tiles.source} alt={tiles.alt} width={W} height={tiles.height} />
520          {card ? (
521            <Svg key="prompt" source={card.source} alt={card.alt} width={W} height={card.height} />
522          ) : (
523            <Text dimColor>Send a prompt to see its tokens, models and subagents.</Text>
524          )}
525          {agents.length > 0 && (
526            <Box flexDirection="column">
527              <Text bold>
528                Subagents · {agents.length}
529                {focus && focus.agents.some(a => a.status === 'running') ? ` (${focus.agents.filter(a => a.status === 'running').length} running)` : ''}
530              </Text>
531              {agents.map(({ a, depth }) => {
532                const r = agentRow(W, a, depth, elapsed(a))
533                return (
534                  <Svg
535                    key={`agent:${a.id}`}
536                    source={r.source}
537                    alt={`${a.description || a.type}: ${a.type}, ${modelName(a.model)}, ${a.status}, ${fmtTokens(total(a.tokens))} tokens`}
538                    width={W}
539                    height={r.height}
540                  />
541                )
542              })}
543            </Box>
544          )}
545          {s.rateLimits.length > 0 && (
546            <Box flexDirection="column" gap={1}>
547              <Text bold>Burn rate</Text>
548              {s.rateLimits.map(r => {
549                const c = burnCard(W, burnOf(r, samples, at), at)
550                return <Svg key={`burn:${r.kind}`} source={c.source} alt={c.alt} width={W} height={c.height} />
551              })}
552            </Box>
553          )}
554          {contextSection}
555        </Box>
556      )
557    }
558
559    // Terminal (and the editor and phone): the same content as text.
560    const cols = Math.max(30, e.props.bodyColumns || 60)
561    const barW = Math.max(8, Math.min(24, cols - 30))
562    const ctxPct = s.contextPercent ?? (s.contextTokens && s.contextWindow ? (s.contextTokens / s.contextWindow) * 100 : undefined)
563    const t = focus ? promptTokens(focus) : zero()
564    const reload = nextReset(s, at)
565    const resetOf = (iso?: string) => {
566      const ms = iso ? Date.parse(iso) : NaN
567      return Number.isFinite(ms) ? ` · resets ${fmtResetAt(ms, at)}` : ''
568    }
569    const hit = cacheHit(t)
570
571    return (
572      <Box flexDirection="column">
573        <Text bold>Statistics</Text>
574        {reload && (
575          <Text wrap="truncate-end">
576            {'  '}Tokens reload in <Text bold color="claude">{fmtUntil(reload.at - at)}</Text>
577            <Text dimColor>
578              {' '}
579              · {limitName(reload.kind)} · {fmtResetAt(reload.at, at)}
580            </Text>
581          </Text>
582        )}
583        <Text wrap="truncate-end">
584          {'  '}
585          <Text bold>{convo.modelCalls}</Text> model calls · <Text bold>{convo.toolCalls}</Text> tool calls ·{' '}
586          <Text bold>{promptRows.length}</Text> prompts
587        </Text>
588        <Text>
589          {'  '}Cost <Text bold>{fmtUsd(s.costUsd)}</Text>
590        </Text>
591        {ctxPct !== undefined && (
592          <Text wrap="truncate-end">
593            {'  '}Context <Text color={pctColor(ctxPct)}>{bar(ctxPct, barW)}</Text> {Math.round(ctxPct)}%
594            <Text dimColor>{s.contextTokens !== undefined ? ` · ${fmtTokens(s.contextTokens)} / ${fmtTokens(s.contextWindow)}` : ''}</Text>
595          </Text>
596        )}
597        {s.rateLimits.map(r => (
598          <Text key={r.kind} wrap="truncate-end">
599            {'  '}
600            {(LIMIT_NAME[r.kind] ?? r.kind).padEnd(7)} <Text color={pctColor(r.percentUsed)}>{bar(r.percentUsed, barW)}</Text> {Math.round(r.percentUsed)}%
601            <Text dimColor>{resetOf(r.resetsAt)}</Text>
602          </Text>
603        ))}
604
605        <Box marginTop={1} flexDirection="column">
606          <Text bold>This prompt</Text>
607          {focus ? (
608            <Box flexDirection="column">
609              <Text wrap="truncate-end">
610                <Text color={COLOR[focus.status]}>{GLYPH[focus.status]}</Text> “{oneLine(focus.text, cols - 6) || '(no text)'}”
611              </Text>
612              <Text dimColor wrap="truncate-end">
613                {'  '}≈{fmtUsd(costOf(focus))} · {fmtTime(elapsed(focus))} · {calls(focus)} calls · {tools(focus)} tools
614              </Text>
615              <Text wrap="truncate-end">
616                {'  '}Tokens <Text bold>{fmtTokens(total(t))}</Text>
617                <Text dimColor> · {PARTS.map(p => `${p.label} ${fmtTokens(t[p.key])}`).join(' · ')}</Text>
618              </Text>
619              <Text dimColor wrap="truncate-end">
620                {'  '}cache hit {hit === undefined ? '—' : `${Math.round(hit)}%`} · {calls(focus) ? fmtTokens(total(t) / calls(focus)) : '—'} per call
621              </Text>
622              <Text>{'  '}Models</Text>
623              {focus.models.length ? (
624                focus.models.map(m => (
625                  <Text key={m.model} wrap="truncate-end">
626                    {'    '}
627                    <Text bold>{modelName(m.model)}</Text>
628                    <Text dimColor>
629                      {' '}
630                      {m.model} · {whereOf(m)} · {m.mainCalls + m.agentCalls} calls · {fmtTokens(total(m.tokens))} tok
631                    </Text>
632                  </Text>
633                ))
634              ) : (
635                <Text dimColor>{'    '}waiting for the first model call…</Text>
636              )}
637              {agents.length > 0 && <Text>{'  '}Subagents · {agents.length}</Text>}
638              {agents.map(({ a, depth }) => (
639                <Box key={a.id} flexDirection="column">
640                  <Text wrap="truncate-end">
641                    {'    '}
642                    {'  '.repeat(depth)}
643                    <Text color={COLOR[a.status]}>{GLYPH[a.status]}</Text> <Text bold>{a.description || a.type}</Text>
644                    <Text dimColor> · {a.type}</Text>
645                  </Text>
646                  <Text dimColor wrap="truncate-end">
647                    {'      '}
648                    {'  '.repeat(depth)}
649                    {modelName(a.model)} · {fmtTime(elapsed(a))} · {a.calls} calls · {a.tools} tools · {fmtTokens(total(a.tokens))} tok
650                  </Text>
651                </Box>
652              ))}
653            </Box>
654          ) : (
655            <Text dimColor>{'  '}Send a prompt to see its tokens, models and subagents.</Text>
656          )}
657        </Box>
658        {s.rateLimits.length > 0 && (
659          <Box marginTop={1} flexDirection="column">
660            <Text bold>Burn rate</Text>
661            {s.rateLimits.map(r => {
662              const b = burnOf(r, samples, at)
663              const f = b.forecast
664              const pace = b.rate === undefined ? 'measuring…' : `${b.rate >= 10 ? Math.round(b.rate) : b.rate.toFixed(1)}%/${b.perLabel}`
665              const reset = b.resetAt !== undefined ? fmtResetAt(b.resetAt, at) : ''
666              const [line, color] =
667                f.kind === 'measuring'
668                  ? ['shows once the window has moved', undefined]
669                  : f.kind === 'idle'
670                    ? [`no use lately, stays at ${Math.round(b.pct)}%`, 'green']
671                    : f.kind === 'hits'
672                      ? [`hits 100% at ${fmtResetAt(f.at, at)}${b.resetAt !== undefined ? `, ${fmtUntil(b.resetAt - f.at)} before reload` : ''}`, 'red']
673                      : [`on pace for ${Math.round(f.atReset)}% at reload ${reset}`.trim(), pctColor(f.atReset)]
674              return (
675                <Text key={`burn:${r.kind}`} wrap="truncate-end">
676                  {'  '}
677                  {(LIMIT_NAME[r.kind] ?? r.kind).padEnd(7)} <Text bold>{pace}</Text> · <Text color={color}>{line}</Text>
678                </Text>
679              )
680            })}
681          </Box>
682        )}
683        {contextSection}
684      </Box>
685    )
686  })
687
688  // ---- the band above the prompt: this prompt's tokens and model ------------------------
689
690  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
691    const list = await read($, prompts)
692    const last = list.at(-1)
693    if (!last || e.props.hasSurvey) return next(e)
694    // The band is shared: what the plugins beneath draw there stays, below this row.
695    const below = await next(e)
696    const p = normalize(last)
697    const s = await read($, session)
698    const at = Math.max(await read($, now), p.startedAt)
699    const t = promptTokens(p)
700    const elapsedMs = (p.endedAt ?? at) - p.startedAt
701    const cost = Math.max(0, (p.costAtEnd ?? (p.status === 'running' ? s.costUsd : p.costAtStart)) - p.costAtStart)
702    const mainModel = mainModelOf(p)
703    const others = p.models.filter(m => m.model !== mainModel).map(m => modelName(m.model))
704    const alt = `${mainModel || 'no model yet'}${others.length ? ` + ${others.join(', ')}` : ''}: ${fmtTokens(total(t))} tokens (${fmtTokens(t.output)} out), ${fmtTime(elapsedMs)}, ≈${fmtUsd(cost)}`
705
706    const ui = $.ui.resolve(e)
707    const { Box, Text, Button } = ui
708    const open = <Button key="usage-open" label="Usage" plain onPress={() => void togglePane($)} />
709
710    if (e.surface !== 'terminal' && 'Svg' in ui) {
711      const { Svg } = ui
712      const W = Math.max(220, Math.min(1400, (e.props.bodyColumns || 100) * 8 - 72))
713      const row = bandRow(W, p, t, elapsedMs, cost)
714      return (
715        <Box flexDirection="column">
716          <Box flexDirection="row" alignItems="center" gap={1}>
717            <Svg key="usage-band" source={row.source} alt={alt} width={W} height={row.height} />
718            {open}
719          </Box>
720          {below}
721        </Box>
722      )
723    }
724
725    return (
726      <Box flexDirection="column">
727        <Box flexDirection="row" gap={1}>
728          <Text color={COLOR[p.status]}>{GLYPH[p.status]}</Text>
729          <Text bold>{mainModel ? modelName(mainModel) : '—'}</Text>
730          <Text dimColor wrap="truncate-end">
731            {mainModel}
732            {others.length ? ` +${others.join(', +')}` : ''}
733          </Text>
734          <Text>│</Text>
735          <Text bold>{fmtTokens(total(t))} tokens</Text>
736          <Text dimColor>({fmtTokens(t.output)} out)</Text>
737          <Text>│</Text>
738          <Text dimColor>
739            {fmtTime(elapsedMs)} · ≈{fmtUsd(cost)}
740          </Text>
741          {open}
742        </Box>
743        {below}
744      </Box>
745    )
746  })
747}
748
hooks/burn.ts 78 lines
1// Burn rate: how fast each rate-limit window is being used, and where that pace leads before
2// it reloads. Pure functions over the readings kept in the store (account-wide, so they span
3// sessions); the drawing is in draw.ts.
4import type { BurnSample, RateLimit } from '../types'
5
6const MIN = 60_000
7const HOUR = 60 * MIN
8
9/** How long each window runs, and how far back its pace is read. */
10const WINDOW: Record<string, { length: number; lookback: number; per: number; perLabel: string }> = {
11  five_hour: { length: 5 * HOUR, lookback: HOUR, per: HOUR, perLabel: 'hour' },
12  seven_day: { length: 7 * 24 * HOUR, lookback: 24 * HOUR, per: 24 * HOUR, perLabel: 'day' },
13}
14const DEFAULT_WINDOW = { length: 5 * HOUR, lookback: HOUR, per: HOUR, perLabel: 'hour' }
15export const windowOf = (kind: string) => WINDOW[kind] ?? DEFAULT_WINDOW
16
17/** Readings older than this are dropped: past the longest window. */
18const KEEP_MS = 8 * 24 * HOUR
19const KEEP_COUNT = 3000
20/** A pace read over less than this is too coarse to forecast from (the limits move a point at a time). */
21const MIN_SPAN = 10 * MIN
22
23/** Adds the readings that moved since the last one of their kind; drops the stale. */
24export const addSamples = (list: BurnSample[], limits: RateLimit[], at: number): BurnSample[] => {
25  let out = list.filter(s => at - s.at < KEEP_MS)
26  for (const r of limits) {
27    const last = out.findLast(s => s.kind === r.kind)
28    if (last && last.pct === r.percentUsed && last.resetsAt === r.resetsAt) continue
29    out = [...out, { at, kind: r.kind, pct: r.percentUsed, resetsAt: r.resetsAt }]
30  }
31  return out.slice(-KEEP_COUNT)
32}
33
34export type Forecast =
35  | { kind: 'measuring' }
36  | { kind: 'idle' }
37  | { kind: 'hits'; at: number }
38  | { kind: 'makes'; atReset: number }
39
40export type Burn = {
41  kind: string
42  pct: number
43  resetAt?: number
44  /** Points of the window per `per` ms, over the lookback; undefined while measuring. */
45  rate?: number
46  per: number
47  perLabel: string
48  /** This window's readings, oldest first, the last at now. */
49  series: { at: number; pct: number }[]
50  start: number
51  forecast: Forecast
52}
53
54export function burnOf(limit: RateLimit, samples: BurnSample[], now: number): Burn {
55  const w = windowOf(limit.kind)
56  const resetAt = limit.resetsAt ? Date.parse(limit.resetsAt) : NaN
57  const hasReset = Number.isFinite(resetAt)
58  // This window's readings: same reset time, and after the last drop (a reset seen early).
59  let mine = samples.filter(s => s.kind === limit.kind && s.resetsAt === limit.resetsAt && s.at <= now)
60  const drop = mine.findLastIndex((s, i) => i > 0 && s.pct < (mine[i - 1]?.pct ?? 0))
61  if (drop > 0) mine = mine.slice(drop)
62  const series = [...mine.map(s => ({ at: s.at, pct: s.pct })), { at: now, pct: limit.percentUsed }]
63  const start = hasReset ? resetAt - w.length : (series[0]?.at ?? now)
64  const base = { kind: limit.kind, pct: limit.percentUsed, resetAt: hasReset ? resetAt : undefined, per: w.per, perLabel: w.perLabel, series, start }
65
66  // The pace: from the last reading at or before the lookback (else the first), to now. Idle
67  // time counts, so a quiet stretch slows it.
68  const from = mine.findLast(s => s.at <= now - w.lookback) ?? mine[0]
69  if (!from || now - from.at < MIN_SPAN) return { ...base, forecast: { kind: 'measuring' } }
70  const perMs = Math.max(0, limit.percentUsed - from.pct) / (now - from.at)
71  const rate = perMs * w.per
72  // Flat: idle only once flat for the whole lookback; before that, a point may just not have ticked.
73  if (perMs <= 0) return now - from.at >= w.lookback ? { ...base, rate, forecast: { kind: 'idle' } } : { ...base, forecast: { kind: 'measuring' } }
74  const fullAt = now + Math.max(0, 100 - limit.percentUsed) / perMs
75  if (hasReset && fullAt >= resetAt) return { ...base, rate, forecast: { kind: 'makes', atReset: limit.percentUsed + perMs * (resetAt - now) } }
76  return { ...base, rate, forecast: { kind: 'hits', at: fullAt } }
77}
78
hooks/context.ts 72 lines
1// Context export and import: the conversation as Markdown, written beside your other exports,
2// and an export read back into the context window as a note the model reads. Pure functions;
3// the files and the session are register.tsx's.
4import type { SessionMessage } from 'claude-code'
5
6/** A tool's input or result longer than this is cut, so one huge output doesn't swamp the file. */
7const TOOL_TEXT_MAX = 8_000
8
9/** Rough tokens in a text: about four characters each. */
10export const estTokens = (s: string): number => Math.ceil(s.length / 4)
11
12const cut = (s: string, max = TOOL_TEXT_MAX): string =>
13  s.length > max ? `${s.slice(0, max)}\n[… ${s.length - max} more characters cut]` : s
14
15const fence = (s: string): string => {
16  const ticks = '`'.repeat(Math.max(3, ...[...s.matchAll(/`+/g)].map(m => m[0].length + 1)))
17  return `${ticks}\n${s}\n${ticks}`
18}
19
20/** The file name of an export made at `ms`: sortable, safe on every system. */
21export const exportName = (ms: number): string => `context-${new Date(ms).toISOString().replace(/[:.]/g, '-').replace(/-\d{3}Z$/, 'Z')}.md`
22
23/** The folder exports go to: one per project, under ~/.claude, out of the repository. */
24export const exportDir = (home: string, root: string): string =>
25  `${home}/.claude/context-exports/${root.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'session'}`
26
27/** The conversation as Markdown: each message in order, tool calls with their input and result. */
28export function formatExport(messages: readonly SessionMessage[], meta: { at: number; project: string; sessionId: string; model: string }): string {
29  const out: string[] = [
30    '# Context export',
31    '',
32    `- Project: \`${meta.project}\``,
33    `- Session: \`${meta.sessionId}\``,
34    `- Model: \`${meta.model}\``,
35    `- Exported: ${new Date(meta.at).toISOString()}`,
36    `- Messages: ${messages.length}`,
37    '',
38  ]
39  for (const m of messages) {
40    // A user row that only carries tool results belongs to the call above it.
41    if (m.role === 'user' && !m.text.trim()) continue
42    out.push(`## ${m.role === 'user' ? 'User' : 'Claude'}`, '')
43    if (m.text.trim()) out.push(m.text.trim(), '')
44    for (const u of m.toolUses) {
45      out.push(`**Tool: ${u.tool}**${u.isError ? ' (error)' : ''}`, '', fence(cut(JSON.stringify(u.input, null, 2))), '')
46      if (u.text !== undefined) out.push('Result:', '', fence(cut(u.text)), '')
47    }
48  }
49  return out.join('\n')
50}
51
52/**
53 * The note an import appends: the export, framed so the model reads it as earlier context.
54 * Over `budget` tokens, the newest part that fits is kept, cut at a message heading.
55 */
56export function importNote(file: string, name: string, budget: number): { text: string; tokens: number; isCut: boolean } {
57  let body = file
58  let isCut = false
59  if (estTokens(body) > budget) {
60    isCut = true
61    const tail = body.slice(body.length - budget * 4)
62    const at = tail.search(/^## (User|Claude)$/m)
63    body = at >= 0 ? tail.slice(at) : tail
64  }
65  const text =
66    `<imported-context source="${name}"${isCut ? ' truncated="oldest part left out to fit the context window"' : ''}>\n` +
67    'The person imported this record of an earlier conversation so you can continue from it. ' +
68    'Treat it as background on what was said and done; it is not a new request.\n\n' +
69    `${body.trim()}\n</imported-context>`
70  return { text, tokens: estTokens(text), isCut }
71}
72
hooks/draw.ts 541 lines
1// SVG drawings for the desktop: the pane's cards and rows, and the band above the prompt.
2// Pure functions of the mod's state; each returns markup and its height in CSS pixels.
3import type { Burn } from './burn'
4import type { AgentRun, ConversationTotals, ModelUse, PromptRun, RunStatus, SessionFigures, Tokens } from '../types'
5
6// ---- shared ---------------------------------------------------------------------
7
8export const FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
9const MONO = "ui-monospace,'SF Mono',Menlo,Consolas,monospace"
10
11// Theme tokens: light by default, dark under the system's dark scheme.
12const CSS = `<style>
13.fg{fill:#1c1c1b}.mu{fill:#6b6a66}.su{fill:#9a9994}.card{fill:#f7f6f3;stroke:#e7e5e0}.track{fill:#ebe9e4}.ln{stroke:#e7e5e0}
14@media (prefers-color-scheme: dark){.fg{fill:#ededeb}.mu{fill:#a9a8a3}.su{fill:#7c7b77}.card{fill:#222221;stroke:#343432}.track{fill:#30302e}.ln{stroke:#343432}}
15.live{animation:pulse 1.6s ease-in-out infinite}@keyframes pulse{50%{opacity:.3}}
16.crab .la{animation:step .5s steps(1) infinite}.crab .lb{animation:step .5s steps(1) infinite -.25s}
17.crab .bd{animation:bob .5s steps(1) infinite -.125s}.crab .cl{animation:wave 1s steps(1) infinite}.crab .cr{animation:wave 1s steps(1) infinite -.5s}
18@keyframes step{50%{transform:translateY(-1px)}}@keyframes bob{50%{transform:translateY(1px)}}@keyframes wave{50%{transform:translateY(-2px)}}
19@media (prefers-reduced-motion: reduce){.live,.crab *{animation:none!important}}
20</style>`
21
22const svg = (W: number, H: number, body: string): string =>
23  `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">${CSS}${body}</svg>`
24
25const xml = (s: string): string =>
26  s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c] ?? c)
27
28// Rough advance of system UI text, in em: enough to decide what fits. Digits are drawn
29// tabular (every digit as wide as a 0), bold runs a little wider. Text that sits beside
30// other text is never placed by this estimate: it shares one <text> (see spans).
31const charEm = (ch: string): number =>
32  /\d/.test(ch) ? 0.62 : /[\s.,:;'|!il()[\]]/.test(ch) ? 0.3 : /[A-ZMW@%mw]/.test(ch) ? 0.76 : 0.57
33
34export const textWidth = (s: string, size: number, isMono = false, isBold = false): number =>
35  isMono ? s.length * size * 0.6 : [...s].reduce((w, ch) => w + charEm(ch) * size, 0) * (isBold ? 1.07 : 1)
36
37export const fitText = (s: string, size: number, maxW: number, isMono = false): string => {
38  const flat = s.replace(/\s+/g, ' ').trim()
39  if (textWidth(flat, size, isMono) <= maxW) return flat
40  let out = ''
41  for (const ch of flat) {
42    if (textWidth(out + ch + '…', size, isMono) > maxW) break
43    out += ch
44  }
45  return out + '…'
46}
47
48type TextOpts = { size?: number; cls?: string; weight?: number; anchor?: 'start' | 'end' | 'middle'; fill?: string; isMono?: boolean }
49
50const text = (x: number, y: number, s: string, o: TextOpts = {}): string =>
51  `<text x="${x}" y="${y}"${o.fill ? ` fill="${o.fill}"` : ` class="${o.cls ?? 'fg'}"`} font-family="${o.isMono ? MONO : FONT}" font-size="${o.size ?? 12}"${o.weight ? ` font-weight="${o.weight}"` : ''}${o.anchor && o.anchor !== 'start' ? ` text-anchor="${o.anchor}"` : ''} font-variant-numeric="tabular-nums">${xml(s)}</text>`
52
53type Span = { s: string; size?: number; cls?: string; weight?: number; fill?: string; isMono?: boolean; gap?: number }
54
55/**
56 * Several styled runs as one <text>: the renderer lays them out end to end, so a label
57 * never overlaps the number before it however wide that number draws. `gap` is the space
58 * before a run, in pixels.
59 */
60const spans = (x: number, y: number, runs: Span[], anchor: 'start' | 'end' = 'start'): string =>
61  `<text x="${x}" y="${y}" font-family="${FONT}" font-variant-numeric="tabular-nums"${anchor === 'end' ? ' text-anchor="end"' : ''}>` +
62  runs
63    .map(
64      r =>
65        `<tspan${r.gap ? ` dx="${r.gap}"` : ''}${r.fill ? ` fill="${r.fill}"` : ` class="${r.cls ?? 'fg'}"`} font-size="${r.size ?? 12}"` +
66        `${r.weight ? ` font-weight="${r.weight}"` : ''}${r.isMono ? ` font-family="${MONO}"` : ''}>${xml(r.s)}</tspan>`,
67    )
68    .join('') +
69  '</text>'
70
71// ---- formatting -----------------------------------------------------------------
72
73export const total = (t: Tokens): number => t.input + t.output + t.cacheRead + t.cacheWrite
74
75export const fmtTokens = (n: number): string =>
76  n >= 1e6 ? `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${Math.round(n)}`
77
78export const fmtUsd = (usd: number): string => `$${usd < 1 ? usd.toFixed(3) : usd.toFixed(2)}`
79
80export const fmtTime = (ms: number): string => {
81  const s = Math.max(0, Math.round(ms / 1000))
82  const m = Math.floor(s / 60)
83  return m ? `${m}m ${String(s % 60).padStart(2, '0')}s` : `${s}s`
84}
85
86export const modelName = (id: string): string => {
87  const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
88  if (!m) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '') || '—'
89  const [, family = '', major = '', minor] = m
90  return `${family.charAt(0).toUpperCase()}${family.slice(1).toLowerCase()} ${major}${minor ? '.' + minor : ''}`
91}
92
93const FAMILY_COLOR: [RegExp, string][] = [
94  [/fable|mythos/i, '#C98A2B'],
95  [/opus/i, '#7F77DD'],
96  [/sonnet/i, '#378ADD'],
97  [/haiku/i, '#1D9E75'],
98]
99export const modelColor = (id: string): string => FAMILY_COLOR.find(([re]) => re.test(id))?.[1] ?? '#888780'
100
101export const STATUS_COLOR: Record<RunStatus, string> = { running: '#3B82F6', done: '#3B9C5F', aborted: '#C9A227', failed: '#D0453F' }
102
103// The four kinds of token, in the order the stacked bar draws them.
104export const PARTS: { key: keyof Tokens; label: string; color: string }[] = [
105  { key: 'input', label: 'in', color: '#3B82F6' },
106  { key: 'output', label: 'out', color: '#F97316' },
107  { key: 'cacheRead', label: 'cache read', color: '#14B8A6' },
108  { key: 'cacheWrite', label: 'cache write', color: '#A855F7' },
109]
110
111const pctColor = (pct: number): string => (pct >= 90 ? '#D0453F' : pct >= 70 ? '#C9A227' : '#3B9C5F')
112
113const LIMIT_NAME: Record<string, string> = { five_hour: '5-hour limit', seven_day: '7-day limit', spend_limit: 'Spend limit' }
114
115// Claude at work: the pixel crab, 24×16 on its grid, scaled to `w` and centred on (cx, cy).
116// Its legs step, its body bobs and its claws wave (CSS, so no redraws).
117const CLAY = '#D97757'
118const INK = '#1F1E1D'
119export const crab = (cx: number, cy: number, w = 16): string => {
120  const k = w / 24
121  const px = (x: number, y: number, pw: number, ph: number, fill: string, cls = '') =>
122    `<rect${cls ? ` class="${cls}"` : ''} x="${x}" y="${y}" width="${pw}" height="${ph}" fill="${fill}"/>`
123  return (
124    `<g transform="translate(${cx - w / 2},${cy - 8 * k}) scale(${k})" shape-rendering="crispEdges"><g class="crab">` +
125    `<g class="bd">${px(4, 0, 16, 12, CLAY)}${px(6, 3, 2, 2, INK)}${px(16, 3, 2, 2, INK)}</g>` +
126    px(0, 4, 4, 4, CLAY, 'cl') +
127    px(20, 4, 4, 4, CLAY, 'cr') +
128    px(4, 12, 2, 4, CLAY, 'la') +
129    px(14, 12, 2, 4, CLAY, 'la') +
130    px(8, 12, 2, 4, CLAY, 'lb') +
131    px(18, 12, 2, 4, CLAY, 'lb') +
132    '</g></g>'
133  )
134}
135
136// Claude, done: the crab standing still with both claws raised, cheering. 24×20 on
137// its grid, scaled to `w` and centred on (cx, cy).
138export const crabDone = (cx: number, cy: number, w = 16): string => {
139  const k = w / 24
140  const px = (x: number, y: number, pw: number, ph: number, fill = CLAY) => `<rect x="${x}" y="${y}" width="${pw}" height="${ph}" fill="${fill}"/>`
141  return (
142    `<g transform="translate(${cx - w / 2},${cy - 10 * k}) scale(${k})" shape-rendering="crispEdges">` +
143    // claws up, on arms reaching from the body's sides
144    px(0, 0, 4, 4) + px(1, 4, 2, 4) + px(20, 0, 4, 4) + px(21, 4, 2, 4) +
145    px(3, 7, 1, 2) + px(20, 7, 1, 2) +
146    px(4, 4, 16, 12) + px(6, 7, 2, 2, INK) + px(16, 7, 2, 2, INK) +
147    px(4, 16, 2, 4) + px(8, 16, 2, 4) + px(14, 16, 2, 4) + px(18, 16, 2, 4) +
148    '</g>'
149  )
150}
151
152const statusMark = (x: number, y: number, status: RunStatus): string => {
153  const c = STATUS_COLOR[status]
154  if (status === 'running') return crab(x, y, 16)
155  if (status === 'done') return `<path d="M${x - 4.5} ${y}l3 3 6-6.5" fill="none" stroke="${c}" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>`
156  if (status === 'aborted') return `<rect x="${x - 3.5}" y="${y - 3.5}" width="7" height="7" rx="1.5" fill="${c}"/>`
157  return `<path d="M${x - 3.5} ${y - 3.5}l7 7M${x + 3.5} ${y - 3.5}l-7 7" stroke="${c}" stroke-width="1.8" stroke-linecap="round"/>`
158}
159
160// A track with a fill, rounded.
161const meter = (x: number, y: number, w: number, h: number, frac: number, color: string): string =>
162  `<rect class="track" x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}"/>` +
163  (frac > 0 ? `<rect x="${x}" y="${y}" width="${Math.max(h, Math.round(w * Math.min(1, frac)))}" height="${h}" rx="${h / 2}" fill="${color}"/>` : '')
164
165// A rounded pill with centred white text; returns markup and width.
166const pill = (x: number, y: number, label: string, color: string, size = 11): { markup: string; w: number } => {
167  const w = Math.round(textWidth(label, size, false, true) + 14)
168  const h = size + 7
169  return {
170    markup: `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}" fill="${color}"/>${text(x + w / 2, y + h / 2 + size * 0.36, label, { size, weight: 600, anchor: 'middle', fill: '#ffffff' })}`,
171    w,
172  }
173}
174
175// ---- pane: session tiles ------------------------------------------------------------
176
177// How long until a moment: 45m, 2h 14m, 3d 4h; "now" once it has passed.
178export const fmtUntil = (ms: number): string => {
179  const m = Math.ceil(ms / 60_000)
180  if (m <= 0) return 'now'
181  if (m < 60) return `${m}m`
182  const h = Math.floor(m / 60)
183  if (h < 24) return `${h}h ${String(m % 60).padStart(2, '0')}m`
184  return `${Math.floor(h / 24)}d ${h % 24}h`
185}
186
187// When a window resets: 16:30 today, Thu 09:00 on another day.
188export const fmtResetAt = (ms: number, now: number): string => {
189  const d = new Date(ms)
190  const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
191  return d.toDateString() === new Date(now).toDateString() ? time : `${d.toLocaleDateString([], { weekday: 'short' })} ${time}`
192}
193
194/** The rate-limit window that resets soonest, still ahead of `now`. */
195export const nextReset = (s: SessionFigures, now: number): { kind: string; at: number } | undefined =>
196  s.rateLimits
197    .map(r => ({ kind: r.kind, at: r.resetsAt ? Date.parse(r.resetsAt) : NaN }))
198    .filter(r => Number.isFinite(r.at) && r.at > now)
199    .sort((a, b) => a.at - b.at)[0]
200
201export const limitName = (kind: string): string => LIMIT_NAME[kind] ?? kind
202
203/**
204 * The statistics: when tokens next reload, the conversation's model and tool calls and prompts,
205 * then cost, context and each rate limit with its own reset.
206 */
207export function sessionTiles(
208  W: number,
209  s: SessionFigures,
210  o: { now: number; prompts: number; calls: ConversationTotals },
211): { source: string; height: number; alt: string } {
212  type Tile = { label: string; value: string; sub?: string; pct?: number; accent?: string }
213  const ctxPct = s.contextPercent ?? (s.contextTokens && s.contextWindow ? (s.contextTokens / s.contextWindow) * 100 : undefined)
214  const tiles: Tile[] = []
215  const next = nextReset(s, o.now)
216  if (next) {
217    tiles.push({
218      label: 'Tokens reload in',
219      value: fmtUntil(next.at - o.now),
220      sub: `${limitName(next.kind).replace(/ limit$/, '')} · ${fmtResetAt(next.at, o.now)}`,
221      accent: CLAY,
222    })
223  }
224  tiles.push(
225    { label: 'Model calls', value: String(o.calls.modelCalls) },
226    { label: 'Tool calls', value: String(o.calls.toolCalls) },
227    { label: 'Prompts sent', value: String(o.prompts) },
228    { label: 'Session cost', value: fmtUsd(s.costUsd) },
229  )
230  if (ctxPct !== undefined) {
231    tiles.push({
232      label: 'Context',
233      value: `${Math.round(ctxPct)}%`,
234      sub: s.contextTokens !== undefined ? `${fmtTokens(s.contextTokens)} / ${fmtTokens(s.contextWindow)}` : undefined,
235      pct: ctxPct,
236    })
237  }
238  for (const r of s.rateLimits) {
239    const at = r.resetsAt ? Date.parse(r.resetsAt) : NaN
240    const sub = Number.isFinite(at) ? `resets ${fmtResetAt(at, o.now)}` : undefined
241    tiles.push({ label: limitName(r.kind), value: `${Math.round(r.percentUsed)}%`, sub, pct: r.percentUsed })
242  }
243
244  const gap = 8
245  const cols = Math.min(tiles.length, W >= 560 ? 4 : 2)
246  const tw = (W - gap * (cols - 1)) / cols
247  const th = 64
248  const rows = Math.ceil(tiles.length / cols)
249  const body = tiles
250    .map((t, i) => {
251      const x = (i % cols) * (tw + gap)
252      const y = Math.floor(i / cols) * (th + gap)
253      return (
254        `<rect class="card" x="${x + 0.5}" y="${y + 0.5}" width="${tw - 1}" height="${th - 1}" rx="10"/>` +
255        text(x + 12, y + 20, t.label, { size: 11, cls: 'mu' }) +
256        text(x + 12, y + 42, t.value, { size: 19, weight: 650, fill: t.accent }) +
257        // Without a meter, the note takes the meter's line, so a wide value never crowds it.
258        (t.sub && t.pct === undefined ? text(x + 12, y + th - 8, fitText(t.sub, 10.5, tw - 24), { size: 10.5, cls: 'su' }) : '') +
259        (t.sub && t.pct !== undefined ? text(x + tw - 12, y + 42, fitText(t.sub, 10.5, tw - 36 - textWidth(t.value, 19, false, true)), { size: 10.5, cls: 'su', anchor: 'end' }) : '') +
260        (t.pct !== undefined ? meter(x + 12, y + th - 14, tw - 24, 4, t.pct / 100, pctColor(t.pct)) : '')
261      )
262    })
263    .join('')
264  const height = rows * th + (rows - 1) * gap
265  return { source: svg(W, height, body), height, alt: tiles.map(t => `${t.label} ${t.value}${t.sub ? ` (${t.sub})` : ''}`).join(', ') }
266}
267
268// ---- pane: the current prompt -----------------------------------------------------
269
270export function promptCard(
271  W: number,
272  p: PromptRun,
273  t: Tokens,
274  extra: { costUsd: number; elapsedMs: number; calls: number; tools: number; title?: string },
275): { source: string; height: number; alt: string } {
276  const pad = 14
277  const inner = W - pad * 2
278  const sum = total(t)
279  let y = 0
280  const out: string[] = []
281
282  // Status, elapsed and cost.
283  y += 22
284  out.push(statusMark(pad + 4, y - 4, p.status))
285  const title = extra.title ?? (p.status === 'running' ? 'Working on your prompt' : 'Last prompt')
286  out.push(text(pad + 16, y, title, { size: 11, cls: 'mu', weight: 500 }))
287  out.push(text(W - pad, y, `${fmtTime(extra.elapsedMs)}  ·  ≈${fmtUsd(extra.costUsd)}`, { size: 11, cls: 'mu', anchor: 'end' }))
288
289  // The prompt itself.
290  y += 21
291  out.push(text(pad, y, fitText(`“${p.text || '(no text)'}”`, 13, inner), { size: 13, weight: 500 }))
292
293  // Big token count, calls and tools.
294  y += 38
295  const big = fmtTokens(sum)
296  out.push(spans(pad, y, [{ s: big, size: 26, weight: 700 }, { s: 'tokens', size: 12, cls: 'mu', gap: 7 }]))
297  out.push(text(W - pad, y, `${extra.calls} model calls  ·  ${extra.tools} tool calls`, { size: 11, cls: 'mu', anchor: 'end' }))
298
299  // The tokens as figures: each kind, how much of the input came from the cache, and the
300  // average a model call cost in tokens.
301  y += 12
302  y = tokenFigures(out, pad, y, inner, t, extra.calls)
303
304  // Models.
305  y += 16
306  out.push(`<line class="ln" x1="${pad}" y1="${y}" x2="${W - pad}" y2="${y}"/>`)
307  y += 22
308  out.push(text(pad, y, 'Models', { size: 11, cls: 'mu', weight: 600 }))
309  if (p.models.length === 0) {
310    y += 22
311    out.push(text(pad, y, 'Waiting for the first model call…', { size: 12, cls: 'su' }))
312  }
313  for (const m of p.models) {
314    y += 12
315    out.push(modelRow(pad, y, inner, m, sum))
316    y += 34
317  }
318  y += 14
319
320  const height = y
321  const card = `<rect class="card" x="0.5" y="0.5" width="${W - 1}" height="${height - 1}" rx="12"/>`
322  const alt =
323    `${extra.title ?? (p.status === 'running' ? 'Working on' : 'Last prompt')}: ${p.text}. ${fmtTokens(sum)} tokens ` +
324    `(${PARTS.map(part => `${part.label} ${fmtTokens(t[part.key])}`).join(', ')}). ` +
325    `Models: ${p.models.map(m => `${modelName(m.model)} (${m.model}) ${whereOf(m)} ${fmtTokens(total(m.tokens))}`).join('; ') || 'none yet'}.`
326  return { source: svg(W, height, card + out.join('')), height, alt }
327}
328
329/** Of the input the model read, the share served from the cache, 0 to 100; undefined with no input. */
330export const cacheHit = (t: Tokens): number | undefined => {
331  const read = t.input + t.cacheRead + t.cacheWrite
332  return read > 0 ? (t.cacheRead / read) * 100 : undefined
333}
334
335// Small figure cells in rows, top-left at (x, y): each kind of token, the cache hit rate and
336// tokens per call. Returns the y below them.
337const tokenFigures = (out: string[], x: number, y: number, w: number, t: Tokens, calls: number): number => {
338  const hit = cacheHit(t)
339  const cells: { label: string; value: string; color: string }[] = [
340    ...PARTS.map(part => ({ label: part.label.replace(/^in$/, 'input').replace(/^out$/, 'output'), value: fmtTokens(t[part.key]), color: part.color })),
341    { label: 'cache hit', value: hit === undefined ? '—' : `${Math.round(hit)}%`, color: '#14B8A6' },
342    { label: 'per call', value: calls ? fmtTokens(total(t) / calls) : '—', color: '#888780' },
343  ]
344  const gap = 6
345  const cols = w >= 540 ? 6 : w >= 270 ? 3 : 2
346  const cw = (w - gap * (cols - 1)) / cols
347  const ch = 40
348  cells.forEach((c, i) => {
349    const cx = x + (i % cols) * (cw + gap)
350    const cy = y + Math.floor(i / cols) * (ch + gap)
351    out.push(`<rect class="track" x="${cx}" y="${cy}" width="${cw}" height="${ch}" rx="7" opacity="0.55"/>`)
352    out.push(`<rect x="${cx + 9}" y="${cy + 9}" width="7" height="7" rx="2" fill="${c.color}"/>`)
353    out.push(text(cx + 21, cy + 16, fitText(c.label, 10.5, cw - 28), { size: 10.5, cls: 'mu' }))
354    out.push(text(cx + 9, cy + 33, c.value, { size: 14, weight: 700 }))
355  })
356  return y + Math.ceil(cells.length / cols) * (ch + gap) + 6
357}
358
359/**
360 * The model the prompt's main conversation ran on: the one with the most main-loop calls (the
361 * first used, on a tie). Not the last call's model: the engine makes small side calls inside a
362 * turn (on Haiku, say) that would win that. Never a subagent's model: falls back to the model
363 * the turn named, else none.
364 */
365export const mainModelOf = (p: PromptRun): string => {
366  const best = p.models.reduce<ModelUse | undefined>((top, m) => (m.mainCalls > (top?.mainCalls ?? 0) ? m : top), undefined)
367  return best?.model ?? p.model ?? ''
368}
369
370export const whereOf = (m: ModelUse): string => {
371  const n = m.agentIds.length
372  return [m.mainCalls ? 'main' : '', n ? `${n} subagent${n === 1 ? '' : 's'}` : ''].filter(Boolean).join(' + ')
373}
374
375// One model: colour chip, name, id, where it ran, its share of the prompt's tokens.
376const modelRow = (x: number, y: number, w: number, m: ModelUse, promptTotal: number): string => {
377  const color = modelColor(m.model)
378  const tokens = total(m.tokens)
379  const name = modelName(m.model)
380  const right = `${fmtTokens(tokens)}  ·  ${m.mainCalls + m.agentCalls} calls`
381  const nameW = textWidth(name, 12.5, false, true) + 8
382  const rightW = textWidth(right, 11) + 16
383  return (
384    `<rect x="${x}" y="${y + 1}" width="10" height="10" rx="3" fill="${color}"/>` +
385    spans(x + 16, y + 10.5, [
386      { s: name, size: 12.5, weight: 600 },
387      { s: fitText(m.model, 10.5, w - 16 - nameW - rightW, true), size: 10.5, cls: 'su', isMono: true, gap: 8 },
388    ]) +
389    text(x + w, y + 10.5, right, { size: 11, cls: 'mu', anchor: 'end' }) +
390    text(
391      x + 16,
392      y + 25,
393      fitText(`${promptTotal ? Math.round((tokens / promptTotal) * 100) : 0}% of the prompt's tokens  ·  ${whereOf(m)}`, 10.5, w - 16),
394      { size: 10.5, cls: 'su' },
395    )
396  )
397}
398
399// ---- pane: subagent and history rows ------------------------------------------------
400
401export function agentRow(W: number, a: AgentRun, depth: number, elapsedMs: number): { source: string; height: number } {
402  const H = 46
403  const x0 = 6 + depth * 16
404  const tokens = fmtTokens(total(a.tokens))
405  const right = textWidth(tokens, 13) + 8
406  const color = modelColor(a.model)
407  const body =
408    (depth ? `<path class="ln" d="M${x0 - 10} 6v14h6" fill="none" stroke-width="1.2"/>` : '') +
409    statusMark(x0 + 4, 17, a.status) +
410    text(x0 + 16, 21, fitText(a.description || a.type, 13, W - x0 - 16 - right), { size: 13, weight: 600 }) +
411    text(W - 4, 21, tokens, { size: 13, weight: 650, anchor: 'end' }) +
412    `<rect x="${x0 + 16}" y="${29}" width="7" height="7" rx="2" fill="${color}"/>` +
413    text(
414      x0 + 28,
415      36,
416      fitText(`${a.type}  ·  ${modelName(a.model)}  ·  ${fmtTime(elapsedMs)}  ·  ${a.calls} calls  ·  ${a.tools} tools`, 11, W - x0 - 32),
417      { size: 11, cls: 'mu' },
418    ) +
419    `<line class="ln" x1="${x0 + 16}" y1="${H - 0.5}" x2="${W}" y2="${H - 0.5}"/>`
420  return { source: svg(W, H, body), height: H }
421}
422
423// ---- band above the prompt ------------------------------------------------------------
424
425/**
426 * One line: status, the main model's id (and other models as chips), the prompt's tokens
427 * with output beside them, elapsed time and cost; trimmed from the right as space runs out.
428 */
429export function bandRow(W: number, p: PromptRun, t: Tokens, elapsedMs: number, costUsd: number): { source: string; height: number } {
430  const H = 24
431  const mid = H / 2
432  const parts: string[] = [statusMark(9, mid, p.status)]
433  let x = 22
434
435  const mainModel = mainModelOf(p)
436  if (mainModel) {
437    const chip = pill(x, mid - 9, modelName(mainModel), modelColor(mainModel))
438    parts.push(chip.markup)
439    x += chip.w + 6
440    const id = fitText(mainModel, 11, Math.max(0, W * 0.32), true)
441    parts.push(text(x, mid + 4, id, { size: 11, cls: 'mu', isMono: true }))
442    x += textWidth(id, 11, true) + 10
443  }
444
445  // Right side, one <text> anchored at the right edge: tokens, then output, time and cost
446  // while they fit. Decided by estimate; laid out by the renderer, so nothing overlaps.
447  const tokens = fmtTokens(total(t))
448  const right: Span[] = [
449    { s: tokens, size: 14, weight: 700 },
450    { s: 'tokens', size: 11, cls: 'mu', gap: 5 },
451  ]
452  let rightW = textWidth(tokens, 14, false, true) + 5 + textWidth('tokens', 11)
453  for (const extra of [`·  ${fmtTokens(t.output)} out`, `·  ${fmtTime(elapsedMs)}`, `·  ≈${fmtUsd(costUsd)}`]) {
454    const w = 10 + textWidth(extra, 11)
455    if (x + rightW + w + 24 > W) break
456    right.push({ s: extra, size: 11, cls: 'su', gap: 10 })
457    rightW += w
458  }
459
460  // Subagents' models, as small chips, while there is room before the right side.
461  for (const m of p.models.filter(one => one.model !== mainModel)) {
462    const label = `+ ${modelName(m.model)}`
463    const w = textWidth(label, 10, false, true) + 14
464    if (x + w + 24 > W - rightW) break
465    const chip = pill(x, mid - 8, label, modelColor(m.model), 10)
466    parts.push(chip.markup)
467    x += chip.w + 4
468  }
469  parts.push(spans(W - 2, mid + 5, right, 'end'))
470
471  return { source: svg(W, H, parts.join('')), height: H }
472}
473
474// ---- pane: burn rate ----------------------------------------------------------------------
475
476/**
477 * One rate-limit window: its pace, where that pace leads before it reloads, and a small chart
478 * of the window so far (solid) and the pace carried on to the reload or to 100% (dashed).
479 */
480export function burnCard(W: number, b: Burn, now: number): { source: string; height: number; alt: string } {
481  const pad = 14
482  const inner = W - pad * 2
483  const out: string[] = []
484  const name = limitName(b.kind)
485  const reset = b.resetAt !== undefined ? fmtResetAt(b.resetAt, now) : undefined
486  const rate = b.rate === undefined ? 'measuring…' : `${b.rate >= 10 ? Math.round(b.rate) : b.rate.toFixed(1)}% / ${b.perLabel}`
487
488  let y = 22
489  out.push(spans(pad, y, [{ s: name, size: 12, weight: 600 }, { s: `${Math.round(b.pct)}% used`, size: 11, cls: 'mu', gap: 8 }]))
490  out.push(text(W - pad, y, rate, { size: 12, weight: 650, anchor: 'end' }))
491
492  // The forecast, coloured by how it ends.
493  const f = b.forecast
494  const [line, color] =
495    f.kind === 'measuring'
496      ? ['Measuring the pace: it shows once the window has moved', undefined]
497      : f.kind === 'idle'
498        ? [`No use lately: stays at ${Math.round(b.pct)}%${reset ? ` until it reloads ${reset}` : ''}`, '#3B9C5F']
499        : f.kind === 'hits'
500          ? [`Hits 100% at ${fmtResetAt(f.at, now)}${b.resetAt !== undefined ? `, ${fmtUntil(b.resetAt - f.at)} before it reloads` : ''}`, '#D0453F']
501          : [`On pace for ${Math.round(f.atReset)}% when it reloads ${reset ?? ''}`.trim(), pctColor(f.atReset)]
502  y += 19
503  out.push(text(pad, y, fitText(line, 11.5, inner), { size: 11.5, weight: 500, ...(color ? { fill: color } : { cls: 'mu' }) }))
504
505  // The chart: the window from its start to its reload, 0 to 100%.
506  y += 12
507  const ch = 54
508  const x0 = b.start
509  const x1 = b.resetAt ?? Math.max(now + 1, ...b.series.map(p => p.at))
510  const fx = (t: number) => pad + ((Math.min(x1, Math.max(x0, t)) - x0) / Math.max(1, x1 - x0)) * inner
511  const fy = (pct: number) => y + ch - (Math.min(100, Math.max(0, pct)) / 100) * ch
512  out.push(`<rect class="track" x="${pad}" y="${y}" width="${inner}" height="${ch}" rx="6" opacity="0.45"/>`)
513  out.push(`<line class="ln" x1="${pad}" y1="${fy(70)}" x2="${W - pad}" y2="${fy(70)}" stroke-dasharray="2 3"/>`)
514  // Actual: a step line, each reading held until the next.
515  const pts = b.series.filter(p => p.at >= x0)
516  const first = b.series.findLast(p => p.at < x0)
517  const steps = first ? [{ at: x0, pct: first.pct }, ...pts] : pts
518  if (steps.length) {
519    let d = `M${fx(steps[0]!.at)} ${fy(steps[0]!.pct)}`
520    for (let i = 1; i < steps.length; i++) d += `H${fx(steps[i]!.at)}V${fy(steps[i]!.pct)}`
521    out.push(`<path d="${d}" fill="none" stroke="${pctColor(b.pct)}" stroke-width="2" stroke-linejoin="round"/>`)
522  }
523  // Projected: the pace carried on.
524  if (f.kind === 'hits' || f.kind === 'makes' || f.kind === 'idle') {
525    const endAt = f.kind === 'hits' ? f.at : x1
526    const endPct = f.kind === 'hits' ? 100 : f.kind === 'makes' ? f.atReset : b.pct
527    out.push(`<path d="M${fx(now)} ${fy(b.pct)}L${fx(endAt)} ${fy(endPct)}" fill="none" stroke="${color ?? '#888780'}" stroke-width="1.6" stroke-dasharray="4 3"/>`)
528    if (f.kind === 'hits') out.push(`<circle cx="${fx(endAt)}" cy="${fy(100)}" r="3" fill="${color}"/>`)
529  }
530  out.push(`<circle cx="${fx(now)}" cy="${fy(b.pct)}" r="3.2" fill="${pctColor(b.pct)}"/>`)
531  y += ch + 15
532  out.push(text(pad, y, 'window start', { size: 10, cls: 'su' }))
533  out.push(text(fx(now), y, 'now', { size: 10, cls: 'su', anchor: fx(now) > W - pad - 40 ? 'end' : fx(now) < pad + 70 ? 'start' : 'middle' }))
534  if (reset) out.push(text(W - pad, y, `reloads ${reset}`, { size: 10, cls: 'su', anchor: 'end' }))
535  y += 12
536
537  const height = y
538  const card = `<rect class="card" x="0.5" y="0.5" width="${W - 1}" height="${height - 1}" rx="12"/>`
539  return { source: svg(W, height, card + out.join('')), height, alt: `${name}: ${Math.round(b.pct)}% used, ${rate}. ${line}` }
540}
541
types/index.d.ts 105 lines
1export type RunStatus = 'running' | 'done' | 'aborted' | 'failed'
2
3/** Token counts summed over a loop's model calls. */
4export type Tokens = {
5  input: number
6  output: number
7  cacheRead: number
8  cacheWrite: number
9}
10
11export type AgentRun = {
12  id: string
13  parentId?: string
14  type: string
15  description: string
16  model: string
17  status: RunStatus
18  startedAt: number
19  endedAt?: number
20  calls: number
21  tools: number
22  tokens: Tokens
23}
24
25/** One model's share of a prompt: main loop and subagents together. */
26export type ModelUse = {
27  model: string
28  /** Model calls made on the main loop and inside subagents. */
29  mainCalls: number
30  agentCalls: number
31  /** The subagents that called it. */
32  agentIds: string[]
33  tokens: Tokens
34}
35
36/** One prompt: the main turn it started and every subagent spawned during it. */
37export type PromptRun = {
38  turnId: string
39  text: string
40  status: RunStatus
41  startedAt: number
42  endedAt?: number
43  model: string
44  calls: number
45  tools: number
46  tokens: Tokens
47  /** The session's cost (USD) when the prompt started and when it ended. */
48  costAtStart: number
49  costAtEnd?: number
50  agents: AgentRun[]
51  /** Every model that worked on the prompt, first used first. */
52  models: ModelUse[]
53}
54
55/** One of your prompts as the conversation keeps it: an entry of the prompt list. */
56export type PromptRow = {
57  /** The transcript row's id (session.append's uuid, or the drawn row's requestId). */
58  id: string
59  /** The id the conversation draws the row under, once seen drawn. */
60  renderId?: string
61  text: string
62  /** When you sent it ($.clock.now() ms); absent for a prompt sent before the mod loaded. */
63  sentAt?: number
64}
65
66/** The whole conversation's usage since the panel started watching: every model call, main and subagents. */
67export type ConversationTotals = {
68  modelCalls: number
69  toolCalls: number
70  tokens: Tokens
71}
72
73/** A context export on disk, as the pane lists it. */
74export type ContextExport = { name: string; path: string; size: number; mtimeMs: number }
75
76/** One reading of a rate-limit window, kept (in the store, across sessions) when it moved. */
77export type BurnSample = { at: number; kind: string; pct: number; resetsAt?: string }
78
79export type RateLimit = { kind: string; percentUsed: number; resetsAt?: string }
80
81export type SessionFigures = {
82  costUsd: number
83  contextTokens?: number
84  contextWindow: number
85  contextPercent?: number
86  rateLimits: RateLimit[]
87}
88
89declare module 'claude-code' {
90  interface PluginState {
91    'usage-panel': {
92      prompts: PromptRun[]
93      session: SessionFigures
94      rows: PromptRow[]
95      /** Null until the first model call this mod sees: then seeded from the prompts it holds. */
96      totals: ConversationTotals | null
97      now: number
98      /** The newest context exports, newest first. */
99      exports: ContextExport[]
100      /** What the last export or import did, shown under the Context heading. */
101      contextNote: string
102    }
103  }
104}
105