SLOPSHOPPER

usage-hud

Usage bar above the Claude Code prompt that expands into cards: plan limits with local reset times and pace, context breakdown, prompt cache, estimated cost

bandcommandstatus
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-hud
› 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 › /hud ⎿ usage-hud: Usage cards shown above the prompt. ╭───────────────────────────────────────────────╮ ╭───────────────────────────────────────────────╮ ╭─────────────── │ Limits resets · GMT │ │ 🎈 Context 97k / 200k │ │ 🧊 Cache · 1h │ │ │ │ │ │ 🌖 5-hour 31% │ │ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ │ │ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄ │ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ │ │ 49% full · 103k free │ │ known after th │ 69% left │ │ │ │ │ │ ╰───────────────────────────────────────────────╯ │ no turn yet th │ Weekly — │ ╰─────────────── │ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ │ │ no reading yet │ ╰───────────────────────────────────────────────╯ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
╭───────────────────────────────────────────────╮ ╭───────────────────────────────────────────────╮ │ Limits resets · GMT │ │ 🎈 Context 97k / 200k │ │ │ │ │ │ 🌖 5-hour 31% │ │ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ │ │ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ │ │ 49% full · 103k free │ │ 69% left │ │ │ │ │ ╰───────────────────────────────────────────────╯ │ Weekly — │ │ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ │ │ no reading yet │ ╰───────────────────────────────────────────────╯
README

Usage HUD for Claude Code

A small usage bar that sits above the Claude Code prompt and opens into a row of cards. You can see how much of your plan limits you have used, when they reset in your own time zone, whether you're using them faster than the clock refills them, what is filling your context window, whether the prompt cache is still warm, and roughly what the session would cost at API prices.

Free and MIT licensed. If it ever saved you from a surprise limit, ☕ tip dadTheeBuilder (pay what you want).

The usage bar above the Claude Code prompt

Click details › (or type /hud) and the bar opens into four cards above the prompt: Limits, Context, Cache and Session. They are drawn on your terminal's own background, so they fit light and dark terminals alike.

The usage cards: limits, context, cache and session

Install

You need Claude Code 2.1.289 or later (plugins written as hook modules). In a terminal:

claude plugin marketplace add rsvishalsingh93/claude-usage-hud
claude plugin install usage-hud@claude-usage-hud

Then restart Claude Code, or run /reload-plugins in a running session. The bar appears above the prompt once the session has usage to show.

Inside Claude Code you can do the same with /plugin marketplace add rsvishalsingh93/claude-usage-hud followed by /plugin install usage-hud@claude-usage-hud.

Update and remove

claude plugin marketplace update claude-usage-hud
claude plugin update usage-hud@claude-usage-hud

claude plugin uninstall usage-hud@claude-usage-hud
claude plugin marketplace remove claude-usage-hud

Use

details › or /hudopen the cards; ‹ hide or /hud again closes them. Clicking needs Claude Code's fullscreen layout (the terminal only reports clicks there); on the main screen the bar reads /hud for details, and ctrl+x tab then Enter works too
/hud calmstop the animations (icons and numbers stay); run it again to turn them back on

What you are looking at

The bars. The fill is how much of a limit is used, green, then amber, then red as it fills. If your current pace would use a limit up before it resets, the bar says when, in amber: runs out ~Thu 4:10 PM. When it doesn't, nothing extra is shown. In the cards, the bars ripple while Claude is spending tokens and stand still otherwise.

The icons change with the value beside them:

🌕 🌖 🌗 🌘 🌑5-hour limit: a moon waning as the limit drains
🌱 🌿 🌳 🍂 🥀weekly limit: a plant ageing through the week
💧 🎈 💥context: a bubble filling up; 💥 means automatic compaction is close
🔥 ⏳ 🧊prompt cache: warm, last five minutes (the time switches to a mm:ss countdown), cold
💰 💸cost: idle, spending
💳an organization's spend limit (enterprise gateways), shown in place of the plan windows

The cards.

  • Limits: each limit's bar, how much of its window has gone, where your pace takes you ("~72% by reset", or "runs out ~Tue 5:18 PM"), and the exact reset date and time in your computer's time zone.
  • Context: tokens in the window, a bar split by category (messages, tools, skills, system prompt, ...) with the autocompact reserve at the right end, and the largest categories listed.
  • Cache: how long the prompt cache stays warm (1 hour on a subscription, 5 minutes on an API key), the last request split into cached, written and new tokens, and its hit rate.
  • Session: estimated cost, model, turns, estimated burn per hour and the hit rate of recent turns.

What is exact and what is estimated

ShownWhere it comes from
5-hour and weekly %, reset timesAnthropic's servers, with each response: exact
Context tokens (193k / 1.0M)the last response's usage: exact
Cache warm or cold, cached/written/newthe last response's usage and the cache lifetime: exact counts, and the countdown assumes the standard lifetime
Context by categoryClaude Code's local estimate, the same as /context: estimated
Cost, burn per hourtoken counts priced at Claude Code's built-in API rates, the same as /cost: estimated. On a Pro or Max subscription you are not billed per token, so this is what the session would cost on the API, not a charge
Pace and projectionsyour usage over the last half hour once there is ten minutes of it, the window's average before that: projection

After you reopen or resume a session

The HUD only knows what this run of Claude Code has seen, so until the first reply comes back some values are missing or off:

  • Cache reads unknown and the bar leaves it out, even if the cache is still warm from before you closed the session. After the first reply it is exact again.
  • 5-hour and weekly limits and context appear with the first reply; before it the bar may be empty or show only part of itself.
  • Turns, hit rate and burn per hour count only this run, not the session's earlier history.
  • Cost is whatever Claude Code's own /cost reports for the session; if that starts over on resume, so does the HUD.

Tips

  • The colors follow your Claude Code theme. If the bars look washed out, set /theme to Auto (match terminal) so Claude Code matches your terminal's light or dark background.
  • The cards need about 12 rows. On a short terminal, the space above the prompt scrolls.
  • The bar redraws once a second to keep the countdowns live, and about three times a second while Claude is working. /hud calm keeps it to once a second.

What the plugin hooks, and what it doesn't touch

The plugin only reads. It never blocks, rewrites or answers anything that isn't its own: every hook below passes the event on unchanged with next(e), except /hud, which it owns.

HookWhat it does
session.startregisters the /hud command, reads the session's usage once and starts the clock that keeps the countdowns live
command.run (only /hud)opens or closes the cards; /hud calm turns the animations off and on. Other commands are not seen
session.measurere-reads usage when Claude Code measures the session
turn.start, turn.completenotes when Claude is working (for the animation), and after each turn records the last request's token counts (cached, written, new) for the Cache card
ui.render (the band above the prompt)draws the bar and the cards; it steps aside for Claude Code's own surveys there

It calls $.session.usage (the figures /cost, /context and the rate-limit headers already give Claude Code), $.clock, $.ui and $.state (its own snapshot, kept for the session). No network calls, no files, no processes, and nothing leaves your computer.

Develop

The plugin is one hooks module, plugins/usage-hud/hooks/register.tsx. To try a change without installing:

claude --plugin-dir ./plugins/usage-hud

Checks:

claude plugin validate ./plugins/usage-hud
claude plugin test ./plugins/usage-hud

More from the same maker

Usage HUD also lives at under5dollars.com/usage-hud, next to CCPrune, a Mac app that makes long Claude Code chats lighter before you resume them. Both are made by Jhilmil Labs.

Like them? ☕ Tip dadTheeBuilder, any amount, nothing to unlock, and follow @dadtheebuilder on 𝕏 for new tools.

License

MIT

Source 2 files
hooks/register.tsx 650 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import type { Limit, Part, Sample, Snap, Turn } from '../types'
4
5const TTL_API_MS = 5 * 60 * 1000
6const TTL_SUB_MS = 60 * 60 * 1000
7const TICK_MS = 1000
8const ANIM_MS = 300
9const REFRESH_MS = 10_000
10const WINDOW_MS: Record<string, number> = { five_hour: 5 * 3600_000, seven_day: 7 * 86400_000 }
11const CARD_MIN = 34
12const empty: Snap = { limits: [], ctx: null, usd: 0, model: '', ttl: TTL_SUB_MS, lastAt: 0, turns: [], now: 0, open: false, parts: [], buffer: 0, samples: {}, phase: 0, startedAt: 0, calm: false, working: false }
13
14let isOpen = false
15let isLooping = false
16
17// Every color is a theme key, so the HUD follows the light, dark, daltonized and ANSI themes alike.
18const C = {
19  text: 'text',
20  muted: 'inactive',
21  track: 'subtle',
22  ok: 'success',
23  warn: 'warning',
24  bad: 'error',
25  blue: 'permission',
26  accent: 'claude',
27} as const
28
29// A reading the host left out, or one a gateway or cloud provider sent as null or text, counts as nothing.
30export const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
31// Short counts: 950, 9.5k, 95k, 1.2M. The cut-offs sit where rounding would carry into the next unit.
32export const tok = (n: number) => {
33  const v = Math.max(0, num(n))
34  return v < 999.5 ? `${Math.round(v)}` : v < 9950 ? `${(v / 1e3).toFixed(1)}k` : v < 999_500 ? `${Math.round(v / 1e3)}k` : v < 9.95e6 ? `${(v / 1e6).toFixed(1)}M` : `${Math.round(v / 1e6)}M`
35}
36// Dollars: cents while small, whole dollars past $100, then k, so a long API session never runs to five digits.
37export const money = (usd: number) => {
38  const v = Math.max(0, num(usd))
39  return v < 99.995 ? `$${v.toFixed(2)}` : v < 999.5 ? `$${Math.round(v)}` : v < 9950 ? `$${(v / 1e3).toFixed(1)}k` : v < 999_500 ? `$${Math.round(v / 1e3)}k` : `$${(v / 1e6).toFixed(1)}M`
40}
41// Cells a string takes in the terminal: an emoji two, a variation selector or joiner none, the rest one.
42export const cells = (str: string) =>
43  [...str].reduce((n, ch) => {
44    const cp = ch.codePointAt(0)!
45    return n + (cp === 0xfe0f || cp === 0x200d ? 0 : cp >= 0x1f000 || cp === 0x23f3 ? 2 : 1)
46  }, 0)
47const clip = (str: string, w: number) => ([...str].length <= w ? str : `${[...str].slice(0, Math.max(0, w - 1)).join('')}…`)
48const clock = (ms: number) => `${Math.floor(ms / 60000)}:${String(Math.floor((ms % 60000) / 1000)).padStart(2, '0')}`
49const span = (ms: number) => {
50  if (ms <= 0) return 'now'
51  const m = Math.floor(ms / 60000)
52  const d = Math.floor(m / 1440)
53  const hrs = Math.floor((m % 1440) / 60)
54  return d > 0 ? `${d}d ${hrs}h` : hrs > 0 ? `${hrs}h ${String(m % 60).padStart(2, '0')}m` : `${m}m`
55}
56// Reset times in the computer's own time zone: the module's Date follows the host's, daylight saving included.
57const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
58const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
59export function localTime(at: number) {
60  const d = new Date(at)
61  const hour = d.getHours()
62  const time = `${hour % 12 || 12}:${String(d.getMinutes()).padStart(2, '0')} ${hour < 12 ? 'AM' : 'PM'}`
63  const day = DAYS[d.getDay()]!
64  return { time, day, date: `${day} ${d.getDate()} ${MONTHS[d.getMonth()]}` }
65}
66// The zone as an offset from GMT (getTimezoneOffset counts minutes the other way round): -330 is GMT+5:30.
67export function zoneLabel(offsetMin: number) {
68  if (offsetMin === 0) return 'GMT'
69  const m = Math.abs(offsetMin)
70  return `GMT${offsetMin < 0 ? '+' : '-'}${Math.floor(m / 60)}${m % 60 ? `:${String(m % 60).padStart(2, '0')}` : ''}`
71}
72
73// Usage: the more used, the worse. Hit rate: the reverse.
74export const usedTone = (pct: number) => (pct >= 85 ? C.bad : pct >= 60 ? C.warn : C.ok)
75const hitTone = (pct: number) => (pct >= 80 ? C.ok : pct >= 40 ? C.warn : C.bad)
76
77// A one-row meter: the filled run and the track, in whole and half cells of a heavy line.
78export function meter(frac: number, width: number) {
79  const halves = Math.round(Math.max(0, Math.min(1, frac)) * width * 2)
80  const full = Math.floor(halves / 2)
81  const half = halves % 2 === 1
82  return { fill: '━'.repeat(full) + (half ? '╸' : ''), track: '━'.repeat(Math.max(0, width - full - (half ? 1 : 0))) }
83}
84
85// The cards' meter: a solid half-height block, so it reads as a gauge and not as a divider line.
86export function block(frac: number, width: number) {
87  const full = Math.round(Math.max(0, Math.min(1, frac)) * width)
88  return { fill: '▄'.repeat(full), track: '▄'.repeat(width - full) }
89}
90
91// The context bar's cells: the used run split among the categories by their share, then free space,
92// then the autocompact reserve at the right end. Every cell is accounted for, and a category with tokens keeps one.
93export function segments(parts: Part[], usedFrac: number, bufferFrac: number, width: number) {
94  const used = Math.round(Math.max(0, Math.min(1, usedFrac)) * width)
95  const reserve = Math.min(width - used, Math.round(Math.max(0, bufferFrac) * width))
96  const total = parts.reduce((n, p) => n + p.tokens, 0)
97  // parts come largest first: the largest absorbs the rounding, so the smallest still shows.
98  const ws =
99    used < parts.length ? parts.map((_, i) => (i < used ? 1 : 0)) : parts.map(p => Math.max(1, Math.round((p.tokens / Math.max(1, total)) * used)))
100  if (ws.length && used >= parts.length) ws[0] = Math.max(1, ws[0]! + used - ws.reduce((n, w) => n + w, 0))
101  const out = parts.map((p, i) => ({ w: ws[i]!, color: p.color }))
102  const left = used - ws.reduce((n, w) => n + w, 0)
103  if (left > 0) out.push({ w: left, color: C.blue })
104  out.push({ w: width - used - reserve, color: C.track })
105  if (reserve > 0) out.push({ w: reserve, color: C.muted })
106  return out.filter(o => o.w > 0)
107}
108
109// The forecast: where a limit lands at its reset if the pace holds. The pace is the last half hour's when there is
110// at least ten minutes of it, else the window's average so far (usage over the time since the window opened).
111export function forecast(pct: number, resetAt: number, windowMs: number, now: number, samples: Sample[]) {
112  const left = resetAt - now
113  if (!resetAt || left <= 0) return null
114  let rate: number | null = null
115  const first = samples[0]
116  const last = samples[samples.length - 1]
117  if (first && last && last.t - first.t >= 10 * 60_000) rate = Math.max(0, (last.pct - first.pct) / (last.t - first.t))
118  else {
119    const elapsed = now - (resetAt - windowMs)
120    if (elapsed >= 5 * 60_000) rate = pct / elapsed
121  }
122  if (rate === null) return null
123  const projected = pct + rate * left
124  const outAt = rate > 0 && projected > 100 ? now + (100 - pct) / rate : null
125  return { projected, outAt }
126}
127
128// The pace bar: the fill is how much of a limit is used, the needle how far through its window the clock is.
129// Fill past the needle is usage running ahead of the clock. While Claude is spending tokens, gaps flow along
130// the fill toward its head; when nothing is being spent the bar stands still.
131export type Cell = { ch: string; role: 'fill' | 'ahead' | 'track' | 'needle' }
132export function paceCells(
133  usedFrac: number,
134  timeFrac: number | null,
135  width: number,
136  g: { fill: string; gap: string; track: string; needle: string },
137  phase: number,
138  flowing: boolean,
139) {
140  const clamp = (v: number) => Math.max(0, Math.min(1, v))
141  const used = Math.round(clamp(usedFrac) * width)
142  const needle = timeFrac === null ? -1 : Math.min(width - 1, Math.floor(clamp(timeFrac) * width))
143  const cells: Cell[] = []
144  for (let i = 0; i < width; i++) {
145    if (i === needle) cells.push({ ch: g.needle, role: 'needle' })
146    else if (i < used) cells.push({ ch: flowing && (((i - phase) % 4) + 4) % 4 === 0 ? g.gap : g.fill, role: needle >= 0 && i > needle ? 'ahead' : 'fill' })
147    else cells.push({ ch: g.track, role: 'track' })
148  }
149  return cells
150}
151// Runs of one role, so a bar is a handful of Text elements rather than one per cell.
152const runs = (cells: Cell[]) =>
153  cells.reduce<{ text: string; role: Cell['role'] }[]>((out, c) => {
154    const tail = out[out.length - 1]
155    if (tail && tail.role === c.role) tail.text += c.ch
156    else out.push({ text: c.ch, role: c.role })
157    return out
158  }, [])
159
160// How far through its window a limit's clock is, 0 to 1.
161const timeFrac = (kind: string, resetAt: number, now: number) => {
162  const w = WINDOW_MS[kind]
163  return w && resetAt ? Math.max(0, Math.min(1, (now - (resetAt - w)) / w)) : null
164}
165
166// Icons that change with the value beside them.
167// The 5-hour limit is a moon waning as it drains; the week a plant ageing through its season; the context a
168// bubble filling toward the pop of autocompact; the cache a fire that dies to ice; the cost a coin, flying while spent.
169export const moon = (used: number) => ['🌕', '🌖', '🌗', '🌘', '🌑'][Math.max(0, Math.min(4, Math.round(used / 25)))]!
170export const season = (used: number) => (used < 25 ? '🌱' : used < 50 ? '🌿' : used < 75 ? '🌳' : used < 95 ? '🍂' : '🥀')
171// Only emoji every terminal's width table knows: a newer one (🫧, 🪙) drawn one cell wide where the layout counts
172// two shifts the rest of the row, and the next redraw leaves stray letters behind ("cachre").
173export const bubble = (ctxPct: number) => (ctxPct < 40 ? '💧' : ctxPct < 80 ? '🎈' : '💥')
174export const ember = (warm: boolean, remain: number) => (!warm ? '🧊' : remain < 5 * 60_000 ? '⏳' : '🔥')
175export const coin = (spending: boolean) => (spending ? '💸' : '💰')
176const card = () => '💳'
177const LIMIT_ICON: Record<string, (used: number) => string> = { five_hour: moon, seven_day: season, spend_limit: card }
178const LIMIT_LABEL: Record<string, string> = { five_hour: '5h', seven_day: 'week', spend_limit: 'spend' }
179
180// The prompt cache as a pie that empties as its time runs out.
181const PIE = ['○', '◔', '◑', '◕', '●']
182export const pie = (frac: number) => PIE[frac <= 0 ? 0 : Math.max(1, Math.min(4, Math.round(frac * 4)))]!
183
184const SPARK = '▁▂▃▄▅▆▇█'
185const spark = (pct: number) => SPARK[Math.min(7, Math.floor((pct / 100) * 8))]
186
187// The session's snapshot. Reading it while drawing makes the drawing follow its writes.
188async function load($: EngineInterface): Promise<Snap> {
189  const { value } = await $.state.get({ plugin: 'usage-hud', key: 'snap' })
190  return { ...empty, ...value }
191}
192// Writes are version-checked and retried, so the clock and a turn's hooks never overwrite each other.
193// A write that keeps losing (it shouldn't) gives up rather than spin: the next tick writes again.
194async function save($: EngineInterface, change: (s: Snap) => Snap) {
195  for (let tries = 0; tries < 20; tries++) {
196    const { value, version } = await $.state.get({ plugin: 'usage-hud', key: 'snap' })
197    const { isSet } = await $.state.set({ plugin: 'usage-hud', key: 'snap' }, change({ ...empty, ...value }), { ifVersion: version })
198    if (isSet) return
199  }
200}
201
202async function refresh($: EngineInterface) {
203  // The per-category breakdown (local estimates, as /context's summary) is only read while the cards show it.
204  const u = await $.session.usage(isOpen ? { breakdown: 'summary' } : undefined)
205  const now = await $.clock.now()
206  const limits = (u.rateLimits ?? [])
207    .filter((r: any) => typeof r?.kind === 'string' && Number.isFinite(r.percentUsed))
208    .map((r: any) => ({ kind: r.kind, pct: Math.max(0, r.percentUsed), resetsAt: r.resetsAt && Number.isFinite(Date.parse(r.resetsAt)) ? r.resetsAt : undefined }))
209  const tokens = num(u.context?.tokens)
210  const window = num(u.context?.window)
211  const ctx = u.context?.tokens === undefined || window <= 0 ? null : { tokens, window, pct: Number.isFinite(u.context.percent) ? u.context.percent! : (tokens / window) * 100 }
212  const usd = num(u.cost?.usd)
213  // Subscription accounts report rate-limit windows and get the 1-hour prompt cache; API keys get 5 minutes.
214  const ttl = limits.some((l: any) => l.kind !== 'spend_limit') ? TTL_SUB_MS : TTL_API_MS
215  const b = u.context?.breakdown
216  const cats: any[] | undefined = Array.isArray(b?.categories) ? b.categories : undefined
217  const parts: Part[] | undefined = cats
218    ?.filter((c: any) => c.kind === 'used' && c.tokens > 0)
219    .sort((x: any, y: any) => y.tokens - x.tokens)
220    .map((c: any) => ({ name: String(c.name), tokens: num(c.tokens), color: c.color }))
221  const buffer = cats ? num(cats.find((c: any) => c.kind === 'buffer')?.tokens) : undefined
222  await save($, (s: Snap) => {
223    // Keep the last half hour of readings per limit; a drop means the window reset, so its history starts over.
224    const samples: Record<string, Sample[]> = {}
225    for (const l of limits as { kind: string; pct: number }[]) {
226      const prev = (s.samples ?? {})[l.kind] ?? []
227      const tail = prev[prev.length - 1]
228      const kept = tail && l.pct < tail.pct - 1 ? [] : prev.filter(x => now - x.t <= 30 * 60_000)
229      samples[l.kind] = !tail || now - tail.t >= 60_000 || l.pct !== tail.pct ? [...kept, { t: now, pct: l.pct }].slice(-40) : kept
230    }
231    return { ...s, limits, ctx, usd, now, ttl, parts: parts ?? s.parts, buffer: buffer ?? s.buffer, samples, startedAt: num(u.startedAt) || s.startedAt }
232  })
233}
234
235// The bars only move while tokens are being spent.
236const animating = (s: Snap) => !s.calm && s.working
237
238// The clock: a frame every 300ms while tokens flow, else once a second for the countdowns; usage every 10s.
239async function pulse($: EngineInterface) {
240  isLooping = true
241  let lastRead = 0
242  for (;;) {
243    const s = await load($)
244    await $.clock.sleep(animating(s) ? ANIM_MS : TICK_MS)
245    const now = await $.clock.now()
246    if (now - lastRead >= REFRESH_MS) {
247      lastRead = now
248      // One failed read (the host mid-reload, a gateway hiccup) must not stop the clock for the rest of the session.
249      await refresh($).catch(() => {})
250    }
251    await save($, (v: Snap) => ({ ...v, now, phase: v.phase + 1 }))
252  }
253}
254
255// The details live in the band itself, drawn on the terminal's own background: no docked pane, no slab of
256// theme colour beside the transcript, and the transcript keeps its full width.
257async function setOpen($: EngineInterface, open: boolean) {
258  isOpen = open
259  if (open) await refresh($)
260  await save($, (s: Snap) => ({ ...s, open }))
261}
262
263// The collapsed line as styled runs, at the most detail that fits `width` cells. Each step drops the least useful
264// part: reset notes, then the run-out forecast, then shorter bars, the cache, the context, the bars, the labels.
265export type Span = { text: string; color?: string; bold?: boolean }
266const LEVELS = [
267  { bar: 12, note: true, out: true, cache: true, ctx: true, label: true, sep: '  │  ' },
268  { bar: 12, note: false, out: true, cache: true, ctx: true, label: true, sep: '  │  ' },
269  { bar: 8, note: false, out: false, cache: true, ctx: true, label: true, sep: '  │  ' },
270  { bar: 6, note: false, out: false, cache: false, ctx: true, label: true, sep: ' │ ' },
271  { bar: 4, note: false, out: false, cache: false, ctx: false, label: true, sep: ' │ ' },
272  { bar: 0, note: false, out: false, cache: false, ctx: false, label: false, sep: ' │ ' },
273]
274export function bandLine(s: Snap, width: number): Span[] {
275  const resetAt = (l: Limit) => (l.resetsAt ? Date.parse(l.resetsAt) : 0)
276  const when = (t: number) => (localTime(t).date === localTime(s.now).date ? localTime(t).time : `${localTime(t).day} ${localTime(t).time}`)
277  const age = s.lastAt ? s.now - s.lastAt : s.ttl
278  const remain = Math.max(0, s.ttl - age)
279  const isWarm = s.lastAt > 0 && remain > 0
280  const shown = ['five_hour', 'seven_day', 'spend_limit'].map(k => s.limits.find(l => l.kind === k)).filter((l): l is Limit => !!l)
281  const build = (o: (typeof LEVELS)[number]) => {
282    const groups: Span[][] = shown.map(l => {
283      const out = forecast(l.pct, resetAt(l), WINDOW_MS[l.kind] ?? 0, s.now, s.samples[l.kind] ?? [])?.outAt
284      const m = meter(l.pct / 100, o.bar)
285      const note = !l.resetsAt ? '' : l.kind === 'five_hour' ? `${span(resetAt(l) - s.now)} · ${localTime(resetAt(l)).time}` : `${localTime(resetAt(l)).day} ${localTime(resetAt(l)).time}`
286      return [
287        { text: `${(LIMIT_ICON[l.kind] ?? moon)(l.pct)} ` },
288        ...(o.label ? [{ text: `${LIMIT_LABEL[l.kind] ?? l.kind} `, color: C.muted }] : []),
289        ...(o.bar ? [{ text: m.fill, color: usedTone(l.pct) }, { text: m.track, color: C.track }, { text: ' ' }] : []),
290        { text: `${Math.round(l.pct)}%`, color: usedTone(l.pct), bold: true },
291        ...(o.out && out ? [{ text: ` · runs out ~${when(out)}`, color: l.pct >= 85 ? C.bad : C.warn }] : []),
292        ...(o.note && note ? [{ text: ` · ${note}`, color: C.muted }] : []),
293      ]
294    })
295    if (o.ctx && s.ctx)
296      groups.push([
297        { text: `${bubble(s.ctx.pct)} ` },
298        ...(o.label ? [{ text: 'ctx ', color: C.muted }] : []),
299        { text: tok(s.ctx.tokens), bold: true },
300        { text: `/${tok(s.ctx.window)}`, color: C.muted },
301      ])
302    if (o.cache && s.lastAt > 0)
303      groups.push([
304        { text: `${ember(isWarm, remain)} ` },
305        ...(o.label ? [{ text: 'cache ', color: C.muted }] : []),
306        { text: isWarm ? (remain < 5 * 60_000 ? clock(remain) : span(remain)) : 'cold', color: !isWarm ? C.muted : remain < 5 * 60_000 ? C.warn : C.ok },
307      ])
308    groups.push([{ text: `${coin(s.working)} ` }, { text: money(s.usd), bold: true }, ...(o.label ? [{ text: ' est.', color: C.muted }] : [])])
309    return groups.flatMap((g, i) => (i ? [{ text: o.sep, color: C.track }, ...g] : g))
310  }
311  const fits = (line: Span[]) => line.reduce((n, sp) => n + cells(sp.text), 0) <= width
312  for (const o of LEVELS) {
313    const line = build(o)
314    if (fits(line)) return line
315  }
316  return build(LEVELS[LEVELS.length - 1]!)
317}
318
319// How many cards sit side by side in the band's width.
320export const perRow = (cols: number) => (cols >= 4 * CARD_MIN + 3 ? 4 : cols >= 2 * CARD_MIN + 1 ? 2 : 1)
321
322export const register: Register = on => {
323  on('session.start', async ($, e, next) => {
324    await $.command.register({ name: 'hud', description: 'Show or hide the usage cards; /hud calm turns the animations off and on' })
325    $.ui.status(undefined)
326    await save($, (s: Snap) => ({ ...s, open: false }))
327    await refresh($)
328    // The loop's pending sleep is aborted when the module unloads (a reload, the session's end): nothing to report.
329    if (!isLooping)
330      pulse($).catch(() => {
331        isLooping = false
332      })
333    return next(e)
334  })
335
336  on('command.run', { command: 'hud' }, async ($, e) => {
337    const arg = e.args.trim()
338    if (arg && arg !== 'calm') return { text: 'Usage: /hud shows or hides the usage cards; /hud calm turns the animations off and on.' }
339    if (arg === 'calm') {
340      const calm = !(await load($)).calm
341      await save($, (s: Snap) => ({ ...s, calm }))
342      return { text: calm ? 'Usage HUD animations off.' : 'Usage HUD animations on.' }
343    }
344    const open = !(await load($)).open
345    await setOpen($, open)
346    return { text: open ? 'Usage cards shown above the prompt.' : 'Usage cards hidden.' }
347  })
348
349  on('session.measure', async ($, e, next) => {
350    await refresh($)
351    return next(e)
352  })
353
354  on('turn.start', async ($, e, next) => {
355    await save($, (s: Snap) => ({ ...s, working: true }))
356    return next(e)
357  })
358
359  on('turn.complete', async ($, e, next) => {
360    await save($, (s: Snap) => ({ ...s, working: false }))
361    // turn.complete's usage sums every request of the turn, so a tool-heavy turn counts the whole prompt once per step.
362    // The window's last response is what the context bar measures: use that so both agree.
363    const win = (await $.session.usage({ breakdown: 'summary' })).context?.breakdown?.apiUsage
364    const u = win ?? e.usage
365    if (u) {
366      const at = await $.clock.now()
367      // Bedrock, Vertex and gateways may leave the cache fields out.
368      const read = num(u.cache_read_input_tokens)
369      const wrote = num(u.cache_creation_input_tokens)
370      const fresh = num(u.input_tokens)
371      const turn: Turn = { read, wrote, fresh, hit: Math.round((read / Math.max(1, read + wrote + fresh)) * 100) }
372      await save($, (s: Snap) => ({ ...s, model: e.usage?.model ?? s.model, lastAt: at, turns: [...s.turns, turn].slice(-12) }))
373    }
374    await refresh($)
375    return next(e)
376  })
377
378  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
379    const s = await load($)
380    const five = s.limits.find(l => l.kind === 'five_hour')
381    const week = s.limits.find(l => l.kind === 'seven_day')
382    const spend = s.limits.find(l => l.kind === 'spend_limit')
383    if (e.props.hasSurvey || (!s.limits.length && !s.ctx)) return next(e)
384
385    const { Box, Text, Button } = $.ui.resolve(e)
386    const cols = Math.max(20, num(e.props.bodyColumns) || 80)
387    const resetAt = (l?: { resetsAt?: string }) => (l?.resetsAt ? Date.parse(l.resetsAt) : 0)
388    const flowing = animating(s)
389    const roleColor = (role: Cell['role'], pct: number) =>
390      role === 'ahead' ? (pct >= 85 ? C.bad : C.warn) : role === 'fill' ? usedTone(pct) : role === 'track' ? C.track : undefined
391    const PaceBar = (p: { l: { kind: string; pct: number; resetsAt?: string }; width: number; g: { fill: string; gap: string; track: string; needle: string }; flow: boolean }) => (
392      <Text>
393        {runs(paceCells(p.l.pct / 100, null, p.width, p.g, s.phase, p.flow && flowing)).map((r, i) => (
394          <Text key={`r${i}`} color={roleColor(r.role, p.l.pct)} bold={r.role === 'needle'}>
395            {r.text}
396          </Text>
397        ))}
398      </Text>
399    )
400    const fc = (l: { kind: string; pct: number; resetsAt?: string }) => forecast(l.pct, resetAt(l), WINDOW_MS[l.kind] ?? 0, s.now, s.samples[l.kind] ?? [])
401    // A time today reads as the time alone; any other day gets its weekday.
402    const when = (t: number) => (localTime(t).date === localTime(s.now).date ? localTime(t).time : `${localTime(t).day} ${localTime(t).time}`)
403    // Cache
404    const age = s.lastAt ? s.now - s.lastAt : s.ttl
405    const remain = Math.max(0, s.ttl - age)
406    const isWarm = s.lastAt > 0 && remain > 0
407    const cacheTone = !isWarm ? C.muted : remain < 5 * 60_000 ? C.warn : C.ok
408
409    // Collapsed: one quiet line, cut down to the band's width so it never wraps (a wrapped row garbles on redraw
410    // and can push the button off the line).
411    if (!s.open) {
412      // The terminal reports clicks to Claude Code only in its fullscreen layout; on the main screen a click never
413      // arrives, so the button there names the command instead of looking clickable. Enter presses it either way
414      // once ctrl+x tab has focused the band.
415      const clickable = e.surface !== 'terminal' || e.viewport?.isFullscreen !== false
416      const label = clickable ? 'details ›' : '/hud for details'
417      const line = bandLine(s, cols - cells(label) - 2)
418      return (
419        <Box>
420          <Box flexShrink={1}>
421            <Text wrap="truncate">
422              {line.map((sp, i) => (
423                <Text key={`b${i}`} color={sp.color} bold={sp.bold}>
424                  {sp.text}
425                </Text>
426              ))}
427            </Text>
428          </Box>
429          <Box flexShrink={0} marginLeft={2}>
430            <Button key="open" label={label} plain dimColor onPress={() => setOpen($, true)} />
431          </Box>
432        </Box>
433      )
434    }
435
436    // Expanded: a row of cards, four across on a wide terminal, two by two on a narrower one.
437    const n = perRow(cols)
438    const cardW = Math.floor((cols - (n - 1)) / n)
439    const W = cardW - 4
440
441    const Bar = (p: { frac: number; color: string }) => {
442      const m = block(p.frac, W)
443      return (
444        <Text>
445          <Text color={p.color}>{m.fill}</Text>
446          <Text color={C.track}>{m.track}</Text>
447        </Text>
448      )
449    }
450    const Row = (p: { left: any; right: any }) => (
451      <Box justifyContent="space-between" width={W}>
452        {p.left}
453        {p.right}
454      </Box>
455    )
456    const Card = (p: { title: string; right?: any; children: any }) => (
457      <Box flexDirection="column" width={cardW} borderStyle="round" borderColor={C.track} paddingX={1}>
458        <Row left={<Text bold color={C.accent}>{p.title}</Text>} right={p.right ?? <Text> </Text>} />
459        {p.children}
460      </Box>
461    )
462    const CARD = { fill: '▄', gap: '▂', track: '▄', needle: '' }
463    // One line under a limit's bar: how far ahead of or behind the clock it is, and where the pace lands it.
464    const Pace = (p: { l: { kind: string; pct: number; resetsAt?: string } }) => {
465      const t = timeFrac(p.l.kind, resetAt(p.l), s.now)
466      const f = fc(p.l)
467      if (t === null) return null
468      return (
469        <Text color={C.muted} wrap="truncate">
470          {Math.round(t * 100)}% of window gone
471          {f ? (
472            f.outAt ? (
473              <Text color={p.l.pct >= 85 ? C.bad : C.warn} bold> · runs out ~{when(f.outAt)}</Text>
474            ) : (
475              ` · ~${Math.min(100, Math.round(f.projected))}% by reset`
476            )
477          ) : (
478            ''
479          )}
480        </Text>
481      )
482    }
483    const Limit = (p: { title: string; l?: { kind: string; pct: number; resetsAt?: string } }) => (
484      <Box flexDirection="column" marginTop={1}>
485        <Row
486          left={
487            <Text bold>
488              {p.l ? `${(LIMIT_ICON[p.l.kind] ?? moon)(p.l.pct)} ` : ''}
489              {p.title}
490            </Text>
491          }
492          right={p.l ? <Text bold color={usedTone(p.l.pct)}>{Math.round(p.l.pct)}%</Text> : <Text color={C.muted}>—</Text>}
493        />
494        {p.l ? <PaceBar l={p.l} width={W} g={CARD} flow /> : <Bar frac={0} color={C.track} />}
495        {p.l && <Pace l={p.l} />}
496        {p.l?.resetsAt ? (
497          <Text color={C.muted} wrap="truncate">
498            {localTime(resetAt(p.l)).date}, <Text bold>{localTime(resetAt(p.l)).time}</Text> · in {span(resetAt(p.l) - s.now)}
499          </Text>
500        ) : (
501          <Text color={C.muted}>{p.l ? `${Math.round(100 - p.l.pct)}% left` : 'no reading yet'}</Text>
502        )}
503      </Box>
504    )
505
506    const last = s.turns[s.turns.length - 1]
507    const prompt = last ? last.read + last.wrote + last.fresh : 0
508    const mix = last
509      ? segments(
510          [
511            { name: 'cached', tokens: last.read, color: C.ok },
512            { name: 'written', tokens: last.wrote, color: C.warn },
513            { name: 'new', tokens: last.fresh, color: C.blue },
514          ].filter(p => p.tokens > 0),
515          1,
516          0,
517          W,
518        )
519      : []
520    const legend = [...s.parts.slice(0, 4), ...(s.parts.length > 4 ? [{ name: 'Other', tokens: s.parts.slice(4).reduce((t, p) => t + p.tokens, 0), color: C.muted }] : [])]
521
522    return (
523      <Box flexDirection="column">
524        <Box flexWrap="wrap" columnGap={1}>
525          <Card title="Limits" right={<Text color={C.muted}>resets · {zoneLabel(new Date(s.now).getTimezoneOffset())}</Text>}>
526            {five || week ? <Limit title="5-hour" l={five} /> : null}
527            {five || week ? <Limit title="Weekly" l={week} /> : null}
528            {spend ? <Limit title="Spend limit" l={spend} /> : null}
529            {!five && !week && !spend ? (
530              <Box marginTop={1} flexDirection="column">
531                <Text color={C.muted} wrap="truncate">no plan limits on this account</Text>
532                <Text color={C.muted} wrap="truncate">(API key or cloud billing)</Text>
533              </Box>
534            ) : null}
535          </Card>
536
537          <Card
538            title={`${bubble(s.ctx?.pct ?? 0)} Context`}
539            right={
540              s.ctx ? (
541                <Text>
542                  <Text bold>{tok(s.ctx.tokens)}</Text>
543                  <Text color={C.muted}> / {tok(s.ctx.window)}</Text>
544                </Text>
545              ) : (
546                <Text color={C.muted}>—</Text>
547              )
548            }
549          >
550            <Box marginTop={1} flexDirection="column">
551              {s.ctx && s.parts.length ? (
552                <Text>
553                  {segments(s.parts, s.ctx.tokens / s.ctx.window, s.buffer / s.ctx.window, W).map((g, i) => (
554                    <Text key={`c${i}`} color={g.color}>{'▄'.repeat(g.w)}</Text>
555                  ))}
556                </Text>
557              ) : (
558                <Bar frac={s.ctx ? s.ctx.tokens / s.ctx.window : 0} color={C.blue} />
559              )}
560              <Text color={C.muted} wrap="truncate">
561                {s.ctx ? `${Math.round(s.ctx.pct)}% full · ${tok(Math.max(0, s.ctx.window - s.ctx.tokens))} free${s.buffer ? ` · ${tok(s.buffer)} reserve` : ''}` : 'no reading yet'}
562              </Text>
563            </Box>
564            <Box marginTop={1} flexDirection="column">
565              {legend.length > 0 && <Text color={C.muted}>by category (est.)</Text>}
566              {legend.map((p, i) => (
567                <Row
568                  key={`l${i}`}
569                  left={
570                    <Text wrap="truncate">
571                      <Text color={p.color}>●</Text>
572                      <Text color={C.muted}> {p.name}</Text>
573                    </Text>
574                  }
575                  right={<Text>{tok(p.tokens)}</Text>}
576                />
577              ))}
578            </Box>
579          </Card>
580
581          <Card
582            title={`${ember(isWarm, remain)} Cache · ${s.ttl === TTL_SUB_MS ? '1h' : '5m'}`}
583            right={
584              isWarm ? (
585                <Text>
586                  <Text bold color={cacheTone}>{pie(remain / s.ttl)} warm</Text>
587                  <Text color={C.muted}> {clock(remain)}</Text>
588                </Text>
589              ) : (
590                // No turn seen by this process (a fresh start, or a resumed session): the cache may well be warm.
591                <Text color={C.muted}>{s.lastAt ? '○ cold' : '— unknown'}</Text>
592              )
593            }
594          >
595            <Box marginTop={1} flexDirection="column">
596              <Bar frac={isWarm ? remain / s.ttl : 0} color={C.ok} />
597              <Text color={C.muted}>{isWarm ? 'time left before the cache expires' : s.lastAt ? 'next turn re-writes the prompt' : 'known after the first reply'}</Text>
598            </Box>
599            {last ? (
600              <Box marginTop={1} flexDirection="column">
601                <Row left={<Text bold>Last request</Text>} right={<Text bold color={hitTone(last.hit)}>{last.hit}% hit</Text>} />
602                <Text>
603                  {mix.map((g, i) => (
604                    <Text key={`m${i}`} color={g.color}>{'▄'.repeat(g.w)}</Text>
605                  ))}
606                </Text>
607                <Row left={<Text color={C.muted}><Text color={C.ok}>●</Text> cached</Text>} right={<Text>{tok(last.read)}</Text>} />
608                <Row left={<Text color={C.muted}><Text color={C.warn}>●</Text> written</Text>} right={<Text>{tok(last.wrote)}</Text>} />
609                <Row left={<Text color={C.muted}><Text color={C.blue}>●</Text> new</Text>} right={<Text>{tok(last.fresh)}</Text>} />
610              </Box>
611            ) : (
612              <Box marginTop={1}>
613                <Text color={C.muted}>no turn yet this session</Text>
614              </Box>
615            )}
616          </Card>
617
618          <Card title={`${coin(s.working)} Session`} right={<Text bold>≈ {money(s.usd)}</Text>}>
619            <Box marginTop={1} flexDirection="column">
620              <Text color={C.muted} wrap="truncate">{five || week ? 'est. at API prices, not a bill' : 'est. at API list prices'}</Text>
621              <Row left={<Text color={C.muted}>model</Text>} right={<Text>{clip(s.model || '—', W - 7)}</Text>} />
622              <Row left={<Text color={C.muted}>turns</Text>} right={<Text>{s.turns.length}</Text>} />
623              {/* Under ten minutes in, an hourly rate is mostly noise: one big turn reads as hundreds an hour. */}
624              {s.startedAt > 0 && s.now - s.startedAt >= 10 * 60_000 && (
625                <Row left={<Text color={C.muted}>burn (est.)</Text>} right={<Text>≈ {money(s.usd / ((s.now - s.startedAt) / 3_600_000))}/h</Text>} />
626              )}
627              {s.turns.length >= 3 && (
628                <Row
629                  left={<Text color={C.muted}>hit rate</Text>}
630                  right={
631                    <Text>
632                      {s.turns.map((t, i) => (
633                        <Text key={`s${i}`} color={hitTone(t.hit)}>{spark(t.hit)}</Text>
634                      ))}
635                    </Text>
636                  }
637                />
638              )}
639            </Box>
640            <Box marginTop={1}>
641              <Button key="close" label="‹ hide" plain dimColor onPress={() => setOpen($, false)} />
642              <Text color={C.muted}>  · /hud toggles</Text>
643            </Box>
644          </Card>
645        </Box>
646      </Box>
647    )
648  })
649}
650
types/index.d.ts 29 lines
1export type Limit = { kind: string; pct: number; resetsAt?: string }
2export type Turn = { read: number; wrote: number; fresh: number; hit: number }
3export type Part = { name: string; tokens: number; color: string }
4export type Sample = { t: number; pct: number }
5export type Snap = {
6  limits: Limit[]
7  ctx: { tokens: number; window: number; pct: number } | null
8  usd: number
9  model: string
10  ttl: number
11  lastAt: number
12  turns: Turn[]
13  now: number
14  open: boolean
15  parts: Part[]
16  buffer: number
17  samples: Record<string, Sample[]>
18  phase: number
19  startedAt: number
20  calm: boolean
21  working: boolean
22}
23
24declare module 'claude-code' {
25  interface PluginState {
26    'usage-hud': { snap: Snap }
27  }
28}
29