SLOPSHOPPER

usage-footer

Footer beside the model name: prompt cache countdown and the API-equivalent cost of your 5-hour and weekly limit windows, colored by whether the limit will…

bandspinnercommandprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-footer
› 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-footer ⎿ usage-footer: No usage data yet. API equivalent cache 60 min left × 5-hour window $0.00 No requests Weekly window $0.00 No requests Scan error: JSON Parse error: Unexpected identifier "dev" At API list prices · all sessions and subagents included ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ▾ cache 60m — 5h … — 7d … auto-accept edits

Draws

Band
API equivalent cache 60 min left × 5-hour window $0.00 No requests Weekly window $0.00 No requests Scan error: JSON Parse error: Unexpected identifier "dev" At API list prices · all sessions and subagents included
README

usage-footer

A Claude Code mod that puts your usage where you look anyway: beside the model name under the prompt.

usage-footer in the terminal: the footer under the prompt and the card above it

▾ ◷42 — 5h $82 — 7d $115
  • ◷42: minutes left before this session's prompt cache expires. Green while fresh, sliding through yellow to red as it runs out.
  • 5h $82: what the requests in your current 5-hour limit window would cost at API list prices.
  • 7d $115: the same for your current weekly limit window. While the session runs Fable, this slot shows Fable's own weekly window (F $…).

The 5h and 7d values are colored by pace: red if, at the pace so far, the limit fills before the window resets; yellow if it ends the window at 85–100%; green otherwise.

Click ▾ (or run /usage-footer) for a card above the prompt with, per window:

  • when the limit fills at the current pace, or where it ends the window
  • the total cost and the cache hit rate
  • the total tokens of the window
  • one row per model: requests, input, cache read, cache write, output, total tokens, hit rate, cost

How it works

  • The windows are your account's own: each starts its length (5 hours, 7 days) before the reset time Claude Code reports for that limit, not a rolling "last 5 hours".
  • Costs come from your local transcripts (~/.claude/projects, including subagents), across every session on this machine, deduplicated per request and priced at API list prices. It is not what a subscription charges.
  • A small Node.js script scans the transcripts incrementally at the end of each turn and every 5 minutes; a scan takes tens of milliseconds. Nothing runs inside the model's request stream.

Requirements

  • Claude Code v2.1.287 or later (mods), in the terminal or the Code tab of the Desktop app.
  • Node.js on the machine. The mod looks for node on PATH, then in the usual install locations on macOS (Homebrew), Linux and Windows.
  • Works on macOS, Windows and Linux.

Install

claude plugin marketplace add omeraltinova/claude-usage-footer
claude plugin install usage-footer@claude-usage-footer

Then start a new session, or run /reload-plugins in an open one.

Update

claude plugin marketplace update claude-usage-footer
claude plugin update usage-footer@claude-usage-footer

Then start a new session, or run /reload-plugins in an open one.

Uninstall

claude plugin uninstall usage-footer@claude-usage-footer

Notes

  • Prices are built in (plugins/usage-footer/scripts/usage-scan.mjs, PRICES) and need updating when Anthropic's prices change.
  • Usage on claude.ai (web, mobile) is not in the local transcripts, so it is not counted in the dollar figures; the limit percentages come from your account and do include it.
  • The Desktop app cuts the footer at a fixed width, so the footer stays short; the card has the details.

License

MIT

Source 2 files
hooks/register.tsx 522 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { UsageLimit, UsagePeriod, UsageScan } from '../types'
5
6const MINUTE = 60e3
7const HOUR = 60 * MINUTE
8const DAY = 24 * HOUR
9
10const DANGER = '#e05050'
11const GOOD = '#3fb950'
12const TIGHT = '#d29922'
13const OVER = '#f85149'
14
15// Where the limit lands at the window's end if use keeps its pace so far:
16// past 100% red, 85-100% yellow, below green. Uncolored without a reading.
17function paceColor(limit: UsageLimit | undefined, lengthMs: number, now: number): string | undefined {
18  const resetMs = limit?.resetsAt ? Date.parse(limit.resetsAt) : NaN
19  if (!limit || !Number.isFinite(resetMs)) return undefined
20  if (limit.percentUsed >= 100) return OVER
21  // Early in a window the pace swings wildly: count at least a tenth of it as elapsed.
22  const elapsed = Math.max(lengthMs / 10, Math.min(lengthMs, lengthMs - (resetMs - now)))
23  const projected = (limit.percentUsed * lengthMs) / elapsed
24  return projected >= 100 ? OVER : projected >= 85 ? TIGHT : GOOD
25}
26
27// Green with the cache fresh, through yellow, to red as it runs out.
28function cacheColor(leftMs: number | undefined, ttlMin: number): string | undefined {
29  if (leftMs === undefined) return undefined
30  if (leftMs <= 0) return OVER
31  const fraction = Math.min(1, leftMs / (ttlMin * MINUTE))
32  const hue = Math.round(fraction * 120)
33  return hslToHex(hue, 70, 50)
34}
35
36// When the limit fills at the pace so far, or where it ends the window if it does not.
37function forecast(limit: UsageLimit | undefined, lengthMs: number, now: number, tzOffsetMin: number): string | undefined {
38  const resetMs = limit?.resetsAt ? Date.parse(limit.resetsAt) : NaN
39  if (!limit || !Number.isFinite(resetMs)) return undefined
40  if (limit.percentUsed >= 100) return `Limit reached · resets ${clock(resetMs, tzOffsetMin, lengthMs > DAY)}`
41  const elapsed = Math.max(lengthMs / 10, Math.min(lengthMs, lengthMs - (resetMs - now)))
42  const perMs = limit.percentUsed / elapsed
43  if (perMs <= 0) return `On pace: won't fill · now ${limit.percentUsed}%`
44  const fillAt = now + (100 - limit.percentUsed) / perMs
45  if (fillAt < resetMs) {
46    return `On pace: fills ~${clock(fillAt, tzOffsetMin, lengthMs > DAY)} (in ${span(fillAt - now)}) · now ${limit.percentUsed}%`
47  }
48  const endPercent = Math.round(limit.percentUsed + perMs * (resetMs - now))
49  return `On pace: won't fill · ~${endPercent}% at window end · now ${limit.percentUsed}%`
50}
51
52const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
53
54function clock(ms: number, tzOffsetMin: number, withDay: boolean): string {
55  const local = new Date(ms + tzOffsetMin * MINUTE)
56  const time = `${String(local.getUTCHours()).padStart(2, '0')}:${String(local.getUTCMinutes()).padStart(2, '0')}`
57  return withDay ? `${DAYS[local.getUTCDay()]} ${time}` : time
58}
59
60function span(ms: number): string {
61  if (ms >= DAY) return `${Math.floor(ms / DAY)}d ${Math.floor((ms % DAY) / HOUR)}h`
62  if (ms >= HOUR) return `${Math.floor(ms / HOUR)}h ${Math.floor((ms % HOUR) / MINUTE)}m`
63  return `${Math.max(1, Math.ceil(ms / MINUTE))}m`
64}
65
66function hslToHex(hue: number, saturation: number, lightness: number): string {
67  const s = saturation / 100
68  const l = lightness / 100
69  const k = (n: number) => (n + hue / 30) % 12
70  const a = s * Math.min(l, 1 - l)
71  const channel = (n: number) =>
72    Math.round(255 * (l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))))
73      .toString(16)
74      .padStart(2, '0')
75  return `#${channel(0)}${channel(8)}${channel(4)}`
76}
77const FAMILY_COLORS: Record<string, string> = {
78  opus: '#d97757',
79  sonnet: '#6a9bcc',
80  haiku: '#629987',
81  fable: '#a78bfa',
82  mythos: '#a78bfa',
83}
84
85const scan = atom({ plugin: 'usage-footer', key: 'scan' } as const, null)
86const limits = atom({ plugin: 'usage-footer', key: 'limits' } as const, [])
87const lastCall = atom({ plugin: 'usage-footer', key: 'lastCall' } as const, 0)
88const error = atom({ plugin: 'usage-footer', key: 'error' } as const, null)
89const isOpen = atom({ plugin: 'usage-footer', key: 'isOpen' } as const, false)
90const isWorking = atom({ plugin: 'usage-footer', key: 'isWorking' } as const, false)
91const model = atom({ plugin: 'usage-footer', key: 'model' } as const, '')
92
93// claude-opus-5-5 -> Opus 5.5, claude-haiku-4-5-20251001 -> Haiku 4.5
94function modelName(id: string): string {
95  const [family = id, ...version] = id.replace(/^claude-/, '').replace(/-\d{8}$/, '').split('-')
96  return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${version.join('.')}`.trim()
97}
98
99function modelColor(id: string): string {
100  const family = id.replace(/^claude-/, '').split('-')[0] ?? ''
101  return FAMILY_COLORS[family] ?? '#8a8a8a'
102}
103
104function usd(value: number): string {
105  return value >= 1000 ? `$${value.toFixed(0)}` : `$${value.toFixed(2)}`
106}
107
108// The desktop cuts the footer at a fixed width: whole dollars there, cents in the card.
109function usdShort(value: number): string {
110  return `$${Math.round(value)}`
111}
112
113// Short enough for a column at any size: 1.23B, 512.8M, 453k, 74
114function tokens(value: number): string {
115  // Rounding 999.7M would print 1000M: values that round up to the next unit move to it.
116  if (value >= 999.5e6) return `${(value / 1e9).toFixed(value >= 1e11 ? 0 : value >= 1e10 ? 1 : 2)}B`
117  if (value >= 999.5e3) return `${(value / 1e6).toFixed(value >= 1e8 ? 0 : 1)}M`
118  if (value >= 1e3) return `${(value / 1e3).toFixed(value >= 1e5 ? 0 : 1)}k`
119  return String(value)
120}
121
122// Share of the prompt the cache served: read over everything sent (uncached + written + read).
123function hitRate(row: { input: number; cacheRead: number; cacheWrite: number }): string {
124  const sent = row.input + row.cacheRead + row.cacheWrite
125  return sent > 0 ? `${((row.cacheRead / sent) * 100).toFixed(1)}%` : '—'
126}
127
128function startOf(list: UsageLimit[], kind: string, lengthMs: number): number | undefined {
129  const resetsAt = list.find(limit => limit.kind === kind)?.resetsAt
130  const resetMs = resetsAt ? Date.parse(resetsAt) : NaN
131  return Number.isFinite(resetMs) ? resetMs - lengthMs : undefined
132}
133
134function weekLimit(list: UsageLimit[]): UsageLimit | undefined {
135  return list.find(limit => limit.kind === 'seven_day') ?? list.find(limit => limit.kind.startsWith('seven_day') && !isFableKind(limit.kind))
136}
137
138function isFableKind(kind: string): boolean {
139  return /fable|mythos/.test(kind)
140}
141
142function fableLimit(list: UsageLimit[]): UsageLimit | undefined {
143  return list.find(limit => isFableKind(limit.kind))
144}
145
146function isFable(id: string): boolean {
147  return /fable|mythos/.test(id)
148}
149
150function cacheLeftMs(data: UsageScan | null, last: number, now: number): number | undefined {
151  const lastTs = Math.max(last, data?.cache?.lastTs ?? 0)
152  if (lastTs === 0) return undefined
153  return lastTs + (data?.cache?.ttlMin ?? 60) * MINUTE - now
154}
155
156// Apps started from the macOS Dock (and some Windows shortcuts) do not get the shell's PATH:
157// after PATH, try where Node usually lives on macOS, Linux and Windows.
158const NODE_CANDIDATES = [
159  'node',
160  '/opt/homebrew/bin/node',
161  '/usr/local/bin/node',
162  '/usr/bin/node',
163  'C:/Program Files/nodejs/node.exe',
164]
165let nodePath: string | undefined
166
167async function runNode($: EngineInterface, args: string[]) {
168  for (const candidate of nodePath ? [nodePath] : NODE_CANDIDATES) {
169    try {
170      const ran = await $.process.run([candidate, ...args], { timeoutMs: 120e3 })
171      nodePath = candidate
172      return ran
173    } catch {
174      // not there: try the next one
175    }
176  }
177  throw new Error('Node.js not found (install it, or put node on PATH)')
178}
179
180// The card's table: the model, then right-aligned figures. `drop` is the order columns
181// leave a narrow table in (highest first); 0 stays at any width.
182type CardColumn = {
183  key: 'reqs' | 'input' | 'read' | 'write' | 'output' | 'total' | 'hit' | 'cost'
184  label: string
185  width: number
186  drop: number
187}
188const CARD_COLUMNS: CardColumn[] = [
189  { key: 'reqs', label: 'Reqs', width: 6, drop: 0 },
190  { key: 'input', label: 'Input', width: 8, drop: 4 },
191  { key: 'read', label: 'Cache read', width: 12, drop: 0 },
192  { key: 'write', label: 'Cache write', width: 13, drop: 3 },
193  { key: 'output', label: 'Output', width: 9, drop: 1 },
194  { key: 'total', label: 'Total', width: 9, drop: 0 },
195  { key: 'hit', label: 'Hit', width: 8, drop: 2 },
196  { key: 'cost', label: 'Cost', width: 10, drop: 0 },
197]
198const MODEL_WIDTH = 14
199// The least a window takes beside another: the table with every droppable column gone, and some air.
200const SIDE_MIN = 70
201
202// The columns that fit `room` cells, each widened by an even share of what is left (up to `maxGrow`).
203function fitColumns(room: number, maxGrow: number): { columns: Array<CardColumn & { size: number }>; width: number } {
204  let columns = [...CARD_COLUMNS]
205  const used = () => MODEL_WIDTH + columns.reduce((sum, column) => sum + column.width, 0)
206  while (used() > room && columns.some(column => column.drop > 0)) {
207    const next = Math.max(...columns.map(column => column.drop))
208    columns = columns.filter(column => column.drop !== next)
209  }
210  const grow = Math.max(0, Math.min(maxGrow, Math.floor((room - used()) / columns.length)))
211  const sized = columns.map(column => ({ ...column, size: column.width + grow }))
212  return { columns: sized, width: MODEL_WIDTH + sized.reduce((sum, column) => sum + column.size, 0) }
213}
214
215let isScanning = false
216let isScanQueued = false
217
218async function rescan($: EngineInterface): Promise<void> {
219  if (isScanning) {
220    isScanQueued = true
221    return
222  }
223  isScanning = true
224  try {
225    const argv = ['node', `${$.plugin.root}/scripts/usage-scan.mjs`, '--session', await $.session.id()]
226    const list = await read($, limits)
227    // The account's own limit windows: each one started its length before it resets.
228    const windowStart = startOf(list, 'five_hour', 5 * HOUR)
229    const weekStart = startOf(list, weekLimit(list)?.kind ?? 'seven_day', 7 * DAY)
230    if (windowStart !== undefined) argv.push('--window-start', String(windowStart))
231    if (weekStart !== undefined) argv.push('--week-start', String(weekStart))
232    const fable = fableLimit(list)
233    const fableStart = fable ? startOf(list, fable.kind, 7 * DAY) : undefined
234    if (fableStart !== undefined) argv.push('--fable-week-start', String(fableStart))
235
236    const ran = await runNode($, argv.slice(1))
237    if (ran.exitCode !== 0) throw new Error(ran.stderr.trim().split('\n').pop() || `exit ${ran.exitCode}`)
238    const data = JSON.parse(ran.stdout) as UsageScan
239    await update($, scan, () => data)
240    await update($, error, () => null)
241  } catch (failure) {
242    const message = failure instanceof Error ? failure.message : String(failure)
243    await update($, error, () => message.slice(0, 300))
244  } finally {
245    isScanning = false
246    if (isScanQueued) {
247      isScanQueued = false
248      void rescan($)
249    }
250  }
251}
252
253function summaryText(data: UsageScan | null): string {
254  if (!data) return 'No usage data yet.'
255  const line = (title: string, period: UsagePeriod | null) =>
256    period
257      ? `${title}: ${usd(period.usd)} (${period.models.map(row => `${modelName(row.model)} ${usd(row.usd)}`).join(', ') || 'no requests'})`
258      : `${title}: no requests`
259  return [line('5-hour window', data.window), line('Weekly window', data.week), line('Weekly · Fable', data.fableWeek ?? null)].join('\n')
260}
261
262export const register: Register = on => {
263  on('session.start', async ($, e, next) => {
264    await $.command.register({
265      name: 'usage-footer',
266      description: 'Toggle the card with the API-equivalent cost of the 5-hour and weekly windows, per model',
267    })
268
269    const usage = await $.session.usage()
270    if (usage.rateLimits.length > 0) await update($, limits, () => [...usage.rateLimits])
271
272    const current = await $.session.model().catch(() => '')
273    await update($, model, () => current)
274    void rescan($)
275    // Each turn's end scans (session.measure); this catches other sessions' use meanwhile.
276    $.clock.every(5 * MINUTE, () => void rescan($))
277    // The cache countdown moves by the minute: redraw, nothing more.
278    $.clock.every(MINUTE, () => $.ui.invalidate('ui.render'))
279
280    return next(e)
281  })
282
283  // While a turn runs its requests keep the prompt cache warm; its end restarts the TTL.
284  on('turn.start', async ($, e, next) => {
285    await update($, isWorking, () => true)
286
287    return next(e)
288  })
289
290  on('turn.complete', async ($, e, next) => {
291    if (e.agentId === undefined) {
292      const now = await $.clock.now()
293      await update($, isWorking, () => false)
294      await update($, lastCall, () => now)
295      if (e.usage?.model) await update($, model, () => e.usage?.model ?? '')
296    }
297
298    return next(e)
299  })
300
301  on('session.measure', async ($, e, next) => {
302    if (e.rateLimits.length > 0) await update($, limits, () => [...e.rateLimits])
303    void rescan($)
304
305    return next(e)
306  })
307
308  on('command.run', { command: 'usage-footer' }, async $ => {
309    await update($, isOpen, open => !open)
310    await rescan($)
311
312    return { text: summaryText(await read($, scan)) }
313  })
314
315  // The footer: colored values beside the model name, kept short so the desktop does
316  // not cut them, and a ▾ that toggles the card.
317  on('ui.render', { component: 'SessionMode' }, async ($, e) => {
318    const { Box, Text, Button } = $.ui.resolve(e)
319    const data = await read($, scan)
320    const list = await read($, limits)
321    const now = await $.clock.now()
322    const isLive = await read($, isWorking)
323    const leftMs = isLive ? (data?.cache?.ttlMin ?? 60) * MINUTE : cacheLeftMs(data, await read($, lastCall), now)
324    const usesFable = isFable(await read($, model))
325    const toggle = () => void update($, isOpen, open => !open)
326
327    // The terminal has room and no ◷ in many fonts: full words and cents there;
328    // the desktop cuts its footer at a fixed width: a glyph and whole dollars.
329    const isTerminal = e.surface === 'terminal'
330    const money = isTerminal ? usd : usdShort
331    const minutes = leftMs === undefined ? undefined : Math.max(0, Math.ceil(leftMs / MINUTE))
332    const cache = isTerminal
333      ? `cache ${minutes === undefined ? '—' : `${minutes}m`}`
334      : `◷${minutes === undefined ? '—' : minutes}`
335    const window = `5h ${data?.window ? money(data.window.usd) : data ? '$0' : '…'}`
336    const week = `7d ${data ? money(data.week.usd) : '…'}`
337    const fable = `${isTerminal ? '7d Fable' : 'F'} ${data?.fableWeek ? money(data.fableWeek.usd) : '…'}`
338
339    return (
340      <Box flexDirection="row" gap={1}>
341        <Button key="toggle" plain label="▾" onPress={toggle} />
342        <Text bold color={cacheColor(leftMs, data?.cache?.ttlMin ?? 60)}>
343          {cache}
344        </Text>
345        <Text dimColor>—</Text>
346        <Text bold color={paceColor(list.find(limit => limit.kind === 'five_hour'), 5 * HOUR, now)}>
347          {window}
348        </Text>
349        <Text dimColor>—</Text>
350        {usesFable ? (
351          <Text bold color={paceColor(fableLimit(list), 7 * DAY, now)}>
352            {fable}
353          </Text>
354        ) : (
355          <Text bold color={paceColor(weekLimit(list), 7 * DAY, now)}>
356            {week}
357          </Text>
358        )}
359        {e.props.modes.length > 0 && <Text dimColor>{e.props.modes.join(' & ')}</Text>}
360      </Box>
361    )
362  })
363
364  // The card: drawn in the band right above the prompt while open.
365  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
366    if (e.props.hasSurvey || !(await read($, isOpen))) return next(e)
367
368    const { Box, Text, Button } = $.ui.resolve(e)
369    const data = await read($, scan)
370    const failure = await read($, error)
371    const list = await read($, limits)
372    const now = await $.clock.now()
373    const leftMs = (await read($, isWorking)) ? (data?.cache?.ttlMin ?? 60) * MINUTE : cacheLeftMs(data, await read($, lastCall), now)
374    const full = Math.max(32, e.props.bodyColumns - 2)
375    // The terminal band has few rows: no blank line above each table there.
376    const isTerminal = e.surface === 'terminal'
377    // The desktop keeps its fixed card; the terminal's fills the width it has.
378    const width = isTerminal ? full : Math.min(full, 100)
379
380    const row = (left: unknown, right: unknown, rowWidth = width) => (
381      <Box flexDirection="row" justifyContent="space-between" width={rowWidth}>
382        {left}
383        {right}
384      </Box>
385    )
386    // A header row (values null) or a model's row, in the columns that fit.
387    const cells = (columns: Array<CardColumn & { size: number }>, values: Record<CardColumn['key'], string> | null) =>
388      columns.map(column => (
389        <Box width={column.size} justifyContent="flex-end">
390          <Text dimColor={values === null} bold={values !== null && column.key === 'cost'}>
391            {values === null ? column.label : values[column.key]}
392          </Text>
393        </Box>
394      ))
395    const section = (title: string, period: UsagePeriod | null, color?: string, note?: string, room = width) => {
396      const table = fitColumns(room, isTerminal ? 6 : 0)
397      const sectionWidth = table.width
398      const models = period?.models ?? []
399      const total = models.reduce(
400        (sum, one) => ({
401          input: sum.input + one.input,
402          cacheRead: sum.cacheRead + one.cacheRead,
403          cacheWrite: sum.cacheWrite + one.cacheWrite,
404          output: sum.output + one.output,
405        }),
406        { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
407      )
408      const allTokens = total.input + total.cacheRead + total.cacheWrite + total.output
409      return (
410        <Box flexDirection="column" width={sectionWidth}>
411          {row(
412            <Text>
413              <Text bold>{title}</Text>
414              <Text dimColor>
415                {period ? `  ${period.startLabel} – ${period.endLabel}${period.isGuessed ? ' (estimated)' : ''}` : ''}
416              </Text>
417            </Text>,
418            <Text>
419              <Text dimColor>{models.length > 0 ? `${tokens(allTokens)} tokens · cache hit ${hitRate(total)}   ` : ''}</Text>
420              <Text bold color={color}>
421                {usd(period?.usd ?? 0)}
422              </Text>
423            </Text>,
424            sectionWidth,
425          )}
426          {note && <Text color={color}>{note}</Text>}
427          {models.length === 0 ? (
428            <Text dimColor>No requests</Text>
429          ) : (
430            <Box flexDirection="column" marginTop={isTerminal ? 0 : 1}>
431              <Box flexDirection="row">
432                <Box width={MODEL_WIDTH}>
433                  <Text dimColor>Model</Text>
434                </Box>
435                {cells(table.columns, null)}
436              </Box>
437              {models.map(model => (
438                <Box flexDirection="row">
439                  <Box width={MODEL_WIDTH} flexDirection="row" gap={1}>
440                    <Text color={modelColor(model.model)}>●</Text>
441                    <Text>{modelName(model.model)}</Text>
442                  </Box>
443                  {cells(table.columns, {
444                    reqs: String(model.reqs),
445                    input: tokens(model.input),
446                    read: tokens(model.cacheRead),
447                    write: tokens(model.cacheWrite),
448                    output: tokens(model.output),
449                    total: tokens(model.input + model.cacheRead + model.cacheWrite + model.output),
450                    hit: hitRate(model),
451                    cost: model.isPriced ? usd(model.usd) : 'n/a',
452                  })}
453                </Box>
454              ))}
455            </Box>
456          )}
457        </Box>
458      )
459    }
460
461    const five = list.find(limit => limit.kind === 'five_hour')
462    const tz = data?.tzOffsetMin ?? 0
463    const windows: Array<[string, UsagePeriod | null, UsageLimit | undefined, number]> = [
464      ['5-hour window', data?.window ?? null, five, 5 * HOUR],
465      ['Weekly window', data?.week ?? null, weekLimit(list), 7 * DAY],
466    ]
467    if (fableLimit(list) || (data?.fableWeek?.usd ?? 0) > 0) {
468      windows.push(['Weekly · Fable', data?.fableWeek ?? null, fableLimit(list), 7 * DAY])
469    }
470    // The terminal puts as many windows side by side as get SIDE_MIN columns each,
471    // the rest wrapping to the next row; one per row below that, at the full width.
472    const GAP = 4
473    let perRow = 1
474    if (isTerminal) {
475      for (let count = windows.length; count > 1; count -= 1) {
476        if (Math.floor((full - GAP * (count - 1)) / count) >= SIDE_MIN) {
477          perRow = count
478          break
479        }
480      }
481    }
482    const room = perRow > 1 ? Math.floor((full - GAP * (perRow - 1)) / perRow) : width
483    const sections = windows.map(([title, period, limit, lengthMs]) =>
484      section(title, period, paceColor(limit, lengthMs, now), forecast(limit, lengthMs, now, tz), room),
485    )
486    const rows: unknown[][] = []
487    for (let at = 0; at < sections.length; at += perRow) rows.push(sections.slice(at, at + perRow))
488
489    return (
490      <Box flexDirection="column" gap={1} paddingX={1}>
491        {row(
492          <Text>
493            <Text bold>API equivalent</Text>
494            <Text dimColor>
495              {'  '}cache {leftMs === undefined ? '—' : leftMs > 0 ? `${Math.ceil(leftMs / MINUTE)} min left` : 'expired'}
496            </Text>
497          </Text>,
498          <Button
499            key="close"
500            plain
501            dimColor
502            // ✕ is ambiguous-width: terminals draw it two cells wide and the hit area covers one.
503            label={isTerminal ? '×' : '✕'}
504            onPress={() => void update($, isOpen, () => false)}
505          />,
506          // Keep clear of the band's own [-] mark in the top right corner of a wide terminal.
507          isTerminal ? full - 6 : width,
508        )}
509        {perRow > 1
510          ? rows.map(group => (
511              <Box flexDirection="row" gap={GAP}>
512                {group}
513              </Box>
514            ))
515          : sections}
516        {failure && <Text color={DANGER}>Scan error: {failure}</Text>}
517        <Text dimColor>At API list prices · all sessions and subagents included</Text>
518      </Box>
519    )
520  })
521}
522
types/index.d.ts 47 lines
1export type UsageModelRow = {
2  model: string
3  usd: number
4  reqs: number
5  input: number
6  output: number
7  cacheRead: number
8  cacheWrite: number
9  isPriced: boolean
10}
11
12export type UsagePeriod = {
13  start: number
14  end: number
15  startLabel: string
16  endLabel: string
17  usd: number
18  models: UsageModelRow[]
19  isGuessed?: boolean
20}
21
22export type UsageScan = {
23  now: number
24  window: UsagePeriod | null
25  week: UsagePeriod
26  fableWeek?: UsagePeriod
27  cache: { lastTs: number; ttlMin: number } | null
28  tzOffsetMin?: number
29  scannedMs: number
30}
31
32export type UsageLimit = { kind: string; percentUsed: number; resetsAt?: string }
33
34declare module 'claude-code' {
35  interface PluginState {
36    'usage-footer': {
37      scan: UsageScan | null
38      limits: UsageLimit[]
39      lastCall: number
40      isWorking: boolean
41      model: string
42      error: string | null
43      isOpen: boolean
44    }
45  }
46}
47