A band above the prompt showing session usage: cost, prompts, rate limits and context fill.

A Claude Code mod: a band above the prompt showing session usage: the cost, prompt count and rate limits on the left, the context gauge on the right. Based on the token-weather sample in anthropics/claude-code-playground. Needs Claude Code 2.1.287 or later.

/cost totals it (an estimate at API prices), where Claude Code reports one.On desktop the rate-limit pills are rounded, with a slightly darker, recessed background; the rest is plain text.
The band never wraps: when it does not fit its width it drops the reset countdowns first, then the prompt count.
The band reads usage as soon as the session starts, showing an animated placeholder until the first figures arrive (it gives up after 30 seconds without any). It refreshes when a turn finishes and steps aside while a survey is shown.
/plugin marketplace add QuantiCZ/claude-code-mods
/plugin install usage-band@quanti-mods
claude plugin validate plugins/usage-band
claude plugin test plugins/usage-bandhooks/register.tsx 336 lines1import type {
2 EngineInterface,
3 Register,
4 SessionContextUsage,
5 SessionCost,
6 SessionRateLimit,
7 Timer,
8} from 'claude-code'
9
10import {
11 BAR_CELLS,
12 METER_PX,
13 PILL_DIM_HEX,
14 bar,
15 colorFor,
16 dots,
17 limitLabel,
18 limitText,
19 meterSvg,
20 pillSvg,
21 planBand,
22 resetIn,
23 severityHex,
24 shimmerSvg,
25 short,
26 skeletonSvg,
27 sortLimits,
28 spinner,
29 sweep,
30} from './format'
31
32type Limit = { kind: string; percent: number; resetsAt?: number }
33
34type Reading = {
35 percent: number
36 tokens: number
37 window: number
38 usd?: number
39 limits: Limit[]
40 prompts?: number
41}
42
43// One loading frame every FRAME_MS; a fresh reading is tried every
44// RETRY_FRAMES frames, and the band gives up after GIVE_UP_FRAMES.
45const FRAME_MS = 100
46const RETRY_FRAMES = 3
47const GIVE_UP_FRAMES = 300
48// The reset countdowns move on once a minute.
49const CLOCK_MS = 60_000
50
51let reading: Reading | null = null
52let now = 0
53let frame = 0
54let ticker: Timer | null = null
55let clockTicker: Timer | null = null
56let isRetrying = false
57// Only the terminal's placeholder needs a redraw per frame; the desktop's
58// animates inside its SVG and would restart if redrawn.
59let animatesTerminal = false
60
61function toLimit(limit: SessionRateLimit): Limit {
62 const resetsAt = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt)
63 return {
64 kind: limit.kind,
65 percent: Math.round(limit.percentUsed),
66 resetsAt: Number.isNaN(resetsAt) ? undefined : resetsAt,
67 }
68}
69
70// Folds the usage figures into the reading; false when they have no window yet.
71function applyUsage(
72 context: SessionContextUsage | undefined,
73 cost: SessionCost | undefined,
74 rateLimits: readonly SessionRateLimit[] | undefined,
75): boolean {
76 if (!context || !context.window) {
77 return false
78 }
79 const tokens = context.tokens ?? 0
80 const percent = Math.round(context.percent ?? (tokens / context.window) * 100)
81 reading = {
82 percent,
83 tokens,
84 window: context.window,
85 usd: cost?.usd,
86 limits: sortLimits(rateLimits ?? []).map(toLimit),
87 prompts: reading?.prompts,
88 }
89 return true
90}
91
92async function takeReading($: EngineInterface): Promise<void> {
93 try {
94 const [usage, prompts, at] = await Promise.all([
95 $.session.usage(),
96 $.session.turns().catch(() => undefined),
97 $.clock.now().catch(() => now),
98 ])
99 now = at
100 if (!applyUsage(usage.context, usage.cost, usage.rateLimits)) {
101 return
102 }
103 if (reading !== null && prompts !== undefined) {
104 reading.prompts = prompts
105 }
106 stopLoading()
107 $.ui.invalidate('ui.render')
108 } catch {
109 // Keep the last reading.
110 }
111}
112
113function stopLoading(): void {
114 ticker?.cancel()
115 ticker = null
116}
117
118function startLoading($: EngineInterface): void {
119 if (ticker !== null) {
120 return
121 }
122 frame = 0
123 ticker = $.clock.every(FRAME_MS, () => {
124 frame += 1
125 if (frame > GIVE_UP_FRAMES) {
126 stopLoading()
127 $.ui.invalidate('ui.render')
128 return
129 }
130 if (frame % RETRY_FRAMES === 0 && !isRetrying) {
131 isRetrying = true
132 void takeReading($).finally(() => {
133 isRetrying = false
134 })
135 }
136 if (animatesTerminal) {
137 $.ui.invalidate('ui.render')
138 }
139 })
140}
141
142function startClock($: EngineInterface): void {
143 if (clockTicker !== null) {
144 return
145 }
146 clockTicker = $.clock.every(CLOCK_MS, () => {
147 void $.clock
148 .now()
149 .then(at => {
150 now = at
151 if (reading?.limits.some(limit => limit.resetsAt !== undefined)) {
152 $.ui.invalidate('ui.render')
153 }
154 })
155 .catch(() => {})
156 })
157}
158
159export const register: Register = on => {
160 on('session.start', async ($, e, next) => {
161 reading = null
162 animatesTerminal = false
163 startLoading($)
164 startClock($)
165 // Read right away rather than after the session has finished starting;
166 // a reading that is not ready yet is retried by the loading ticker.
167 void takeReading($)
168 const result = await next(e)
169 await takeReading($)
170
171 return result
172 })
173
174 on('turn.complete', async ($, e, next) => {
175 const result = await next(e)
176 await takeReading($)
177
178 return result
179 })
180
181 // Pushed when a figure moves, a rate-limit window among them.
182 on('session.measure', async ($, e, next) => {
183 const result = await next(e)
184 if (applyUsage(e.context, e.cost, e.rateLimits)) {
185 stopLoading()
186 $.ui.invalidate('ui.render')
187 }
188
189 return result
190 })
191
192 on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
193 if (e.props.hasSurvey) {
194 return next(e)
195 }
196
197 const { Box, Text } = $.ui.resolve(e)
198 const current = reading
199
200 if (current === null) {
201 if (ticker === null) {
202 return next(e)
203 }
204 let spend
205 let figures
206 let meter
207 if (e.surface === 'desktop') {
208 const { Svg } = $.ui.resolve(e)
209 spend = <Svg source={skeletonSvg(36, 8)} alt="Loading cost" width={36} height={8} isInteractive />
210 figures = <Svg source={skeletonSvg(56, 8)} alt="Loading context" width={56} height={8} isInteractive />
211 meter = <Svg source={shimmerSvg()} alt="Loading context meter" width={METER_PX} height={6} isInteractive />
212 } else {
213 animatesTerminal = true
214 const { before, glow, after } = sweep(frame)
215 spend = <Text dimColor>{spinner(frame)}</Text>
216 figures = <Text dimColor>{dots(frame)}</Text>
217 meter = (
218 <Box key="meter" flexDirection="row">
219 <Text color="inactive">{before}</Text>
220 <Text color="subtle">{glow}</Text>
221 <Text color="inactive">{after}</Text>
222 </Box>
223 )
224 }
225
226 return (
227 <Box key="loading" flexDirection="row" justifyContent="space-between" alignItems="center" width="100%" paddingX={1}>
228 <Box key="spend" flexDirection="row">
229 {spend}
230 </Box>
231 <Box key="gauge" flexDirection="row" alignItems="center" gap={1}>
232 {figures}
233 {meter}
234 </Box>
235 </Box>
236 )
237 }
238
239 const { usd, prompts, limits } = current
240 const costText = usd !== undefined ? `$${usd.toFixed(2)}` : ''
241 const promptsText = prompts !== undefined ? `${prompts} ${prompts === 1 ? 'prompt' : 'prompts'}` : ''
242 const contextText = `${short(current.tokens)} / ${short(current.window)}`
243 const percentText = `${current.percent}%`
244 const resetOf = (limit: Limit) => (limit.resetsAt === undefined ? undefined : resetIn(limit.resetsAt - now))
245
246 // Fit the band to its width rather than let a figure wrap: drop the reset
247 // countdowns first, then the prompt count.
248 const { showsResets, showsPrompts } = planBand(e.props.bodyColumns ?? 80, {
249 cost: costText.length,
250 prompts: promptsText.length,
251 limits: limits.map(limit => ({
252 full: limitText(limitLabel(limit.kind), limit.percent, resetOf(limit)).length,
253 compact: limitText(limitLabel(limit.kind), limit.percent).length,
254 })),
255 gauge: contextText.length + 1 + percentText.length + 1 + BAR_CELLS,
256 })
257 const severity = colorFor(current.percent)
258
259 // A rate limit's pill. On desktop an SVG, for its rounded ends; in the
260 // terminal plain runs of text on the band.
261 const pillOf = (limit: Limit) => {
262 const label = limitLabel(limit.kind)
263 const reset = showsResets ? resetOf(limit) : undefined
264 if (e.surface === 'desktop') {
265 const { Svg } = $.ui.resolve(e)
266 const runs = [
267 { text: `${label} `, color: PILL_DIM_HEX },
268 { text: `${limit.percent}%`, color: severityHex(limit.percent) },
269 ...(reset === undefined ? [] : [{ text: ` ↻ ${reset}`, color: PILL_DIM_HEX }]),
270 ]
271 const pill = pillSvg(runs)
272 return <Svg source={pill.source} alt={limitText(label, limit.percent, reset)} width={pill.width} height={pill.height} />
273 }
274 return (
275 <Box flexDirection="row" gap={1}>
276 <Text dimColor>{label}</Text>
277 <Text color={colorFor(limit.percent)}>{`${limit.percent}%`}</Text>
278 {reset !== undefined ? <Text dimColor>{`↻ ${reset}`}</Text> : null}
279 </Box>
280 )
281 }
282
283 const meter =
284 e.surface === 'desktop'
285 ? (() => {
286 const { Svg } = $.ui.resolve(e)
287 return <Svg source={meterSvg(current.percent)} alt={`Context ${current.percent}% full`} width={METER_PX} height={6} />
288 })()
289 : (() => {
290 const { fill, track } = bar(current.percent)
291 return (
292 <Box key="meter" flexDirection="row" flexShrink={0}>
293 <Text color={severity}>{fill}</Text>
294 <Text color="inactive">{track}</Text>
295 </Box>
296 )
297 })()
298
299 // Cost, prompts and the rate-limit pills on the left; the context gauge on
300 // the right. Nothing shrinks, so no figure wraps onto a second row.
301 return (
302 <Box flexDirection="row" justifyContent="space-between" alignItems="center" width="100%" paddingX={1}>
303 <Box key="left" flexDirection="row" alignItems="center" gap={2} flexShrink={0}>
304 {usd !== undefined ? (
305 <Box key="spend" flexDirection="row" flexShrink={0}>
306 <Text wrap="truncate-end">{costText}</Text>
307 </Box>
308 ) : null}
309 {showsPrompts && prompts !== undefined ? (
310 <Box key="prompts" flexDirection="row" flexShrink={0}>
311 <Text dimColor wrap="truncate-end">{promptsText}</Text>
312 </Box>
313 ) : null}
314 {limits.length > 0 ? (
315 <Box key="limits" flexDirection="row" alignItems="center" gap={1} flexShrink={0}>
316 {limits.map(limit => (
317 <Box key={`limit-${limit.kind}`} flexDirection="row" flexShrink={0}>
318 {pillOf(limit)}
319 </Box>
320 ))}
321 </Box>
322 ) : null}
323 </Box>
324 <Box key="gauge" flexDirection="row" alignItems="center" gap={1} flexShrink={0}>
325 <Box key="context" flexDirection="row" flexShrink={0}>
326 <Text>{short(current.tokens)}</Text>
327 <Text dimColor>{` / ${short(current.window)}`}</Text>
328 </Box>
329 <Text bold color={severity}>{percentText}</Text>
330 {meter}
331 </Box>
332 </Box>
333 )
334 })
335}
336hooks/format.ts 226 lines1// The context meter: cells in the terminal, CSS pixels on desktop.
2export const BAR_CELLS = 5
3export const METER_PX = 36
4
5export type Severity = 'success' | 'warning' | 'claude' | 'error'
6
7// The theme's own hues, for the SVG meter, which cannot read theme keys.
8const SEVERITY_HEX: Record<Severity, string> = {
9 success: '#4eba65',
10 warning: '#e8b339',
11 claude: '#d77757',
12 error: '#ef5a6f',
13}
14
15function oneDecimal(n: number): string {
16 return n.toFixed(1).replace(/\.0$/, '')
17}
18
19function clampPercent(percent: number): number {
20 return Math.max(0, Math.min(100, percent))
21}
22
23export function short(n: number): string {
24 if (n >= 1_000_000) {
25 return `${oneDecimal(n / 1_000_000)}M`
26 }
27 if (n >= 1_000) {
28 return `${oneDecimal(n / 1_000)}k`
29 }
30 return String(n)
31}
32
33export function colorFor(percent: number): Severity {
34 if (percent >= 90) {
35 return 'error'
36 }
37 if (percent >= 75) {
38 return 'claude'
39 }
40 if (percent >= 50) {
41 return 'warning'
42 }
43 return 'success'
44}
45
46// The terminal meter: a heavy line for the fill over a light line for the track,
47// at least one cell filled once anything is used, as the desktop meter's dot.
48export function bar(percent: number, cells = BAR_CELLS): { fill: string; track: string } {
49 const p = clampPercent(percent)
50 const filled = p === 0 ? 0 : Math.max(1, Math.round((p / 100) * cells))
51 return { fill: '━'.repeat(filled), track: '─'.repeat(cells - filled) }
52}
53
54const LIMIT_LABELS: Record<string, string> = {
55 five_hour: '5h',
56 seven_day: 'week',
57 spend_limit: 'spend',
58}
59const LIMIT_ORDER = ['five_hour', 'seven_day', 'spend_limit']
60
61// A rate-limit window's short name: `five_hour` is "5h", an unknown kind is spelled out.
62export function limitLabel(kind: string): string {
63 return LIMIT_LABELS[kind] ?? kind.replace(/_/g, ' ')
64}
65
66// The 5-hour window first, then the weekly one, then any other.
67export function sortLimits<T extends { kind: string }>(limits: readonly T[]): T[] {
68 const rank = (kind: string) => {
69 const at = LIMIT_ORDER.indexOf(kind)
70 return at === -1 ? LIMIT_ORDER.length : at
71 }
72 return [...limits].sort((a, b) => rank(a.kind) - rank(b.kind))
73}
74
75// How long until a window resets: "37m", "4h 27m", "2d 5h"; "now" once it is due.
76export function resetIn(ms: number): string {
77 if (!(ms > 0)) {
78 return 'now'
79 }
80 const minutes = Math.ceil(ms / 60_000)
81 if (minutes < 60) {
82 return `${minutes}m`
83 }
84 const hours = Math.floor(minutes / 60)
85 if (hours < 24) {
86 return `${hours}h ${minutes % 60}m`
87 }
88 return `${Math.floor(hours / 24)}d ${hours % 24}h`
89}
90
91const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
92const DOTS = ['· ', '·· ', '···', ' ··', ' ·', ' ']
93export const GLOW_CELLS = 2
94
95export function spinner(frame: number): string {
96 return SPINNER[frame % SPINNER.length] ?? ''
97}
98
99export function dots(frame: number): string {
100 return DOTS[Math.floor(frame / 2) % DOTS.length] ?? ''
101}
102
103// The terminal loading meter: a short heavy segment sweeping back and forth
104// over the light track.
105export function sweep(frame: number): { before: string; glow: string; after: string } {
106 const span = BAR_CELLS - GLOW_CELLS
107 const step = frame % (2 * span)
108 const at = step <= span ? step : 2 * span - step
109 return {
110 before: '─'.repeat(at),
111 glow: '━'.repeat(GLOW_CELLS),
112 after: '─'.repeat(span - at),
113 }
114}
115
116// A placeholder for a figure still loading: a grey pill that pulses.
117export function skeletonSvg(width: number, height: number): string {
118 const r = height / 2
119 return (
120 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
121 `<rect width="${width}" height="${height}" rx="${r}" fill="#808080" fill-opacity="0.2">` +
122 `<animate attributeName="fill-opacity" values="0.12;0.34;0.12" dur="1.4s" repeatCount="indefinite"/>` +
123 `</rect></svg>`
124 )
125}
126
127// The desktop meter while loading: the empty track with a highlight gliding across.
128export function shimmerSvg(width = METER_PX, height = 6): string {
129 const r = height / 2
130 const glow = Math.round(width / 3)
131 return (
132 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
133 `<defs><clipPath id="t"><rect width="${width}" height="${height}" rx="${r}"/></clipPath>` +
134 `<linearGradient id="g"><stop offset="0" stop-color="#b0b0b0" stop-opacity="0"/>` +
135 `<stop offset="0.5" stop-color="#b0b0b0" stop-opacity="0.75"/>` +
136 `<stop offset="1" stop-color="#b0b0b0" stop-opacity="0"/></linearGradient></defs>` +
137 `<rect width="${width}" height="${height}" rx="${r}" fill="#80808047"/>` +
138 `<g clip-path="url(#t)"><rect x="${-glow}" width="${glow}" height="${height}" fill="url(#g)">` +
139 `<animate attributeName="x" from="${-glow}" to="${width}" dur="1.2s" repeatCount="indefinite"/>` +
140 `</rect></g></svg>`
141 )
142}
143
144// The desktop meter: a rounded pill, its fill never thinner than its height
145// once anything is used, so 1% still shows as a dot.
146export function meterSvg(percent: number, width = METER_PX, height = 6): string {
147 const p = clampPercent(percent)
148 const r = height / 2
149 const fillWidth = p === 0 ? 0 : Math.max(height, Math.round((p / 100) * width))
150 const fill =
151 fillWidth > 0
152 ? `<rect width="${fillWidth}" height="${height}" rx="${r}" fill="${SEVERITY_HEX[colorFor(p)]}"/>`
153 : ''
154 return (
155 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
156 `<rect width="${width}" height="${height}" rx="${r}" fill="#80808047"/>` +
157 fill +
158 `</svg>`
159 )
160}
161
162// A rate limit's pill text: "5h 9% ↻ 4h 27m", or "5h 9%" without the reset.
163export function limitText(label: string, percent: number, reset?: string): string {
164 return reset === undefined ? `${label} ${percent}%` : `${label} ${percent}% ↻ ${reset}`
165}
166
167// The desktop pill: rounded ends, monospace text in coloured runs. Drawn as an
168// SVG since a Box has no rounded corners, and an SVG never wraps or shrinks.
169const PILL_FONT_PX = 12
170const PILL_CHAR_PX = 7.2
171const PILL_PAD_PX = 8
172const PILL_HEIGHT_PX = 20
173// Grey that reads on light and dark themes alike, for the pill's dim runs.
174export const PILL_DIM_HEX = '#8e8e8e'
175
176export type PillRun = { text: string; color: string }
177
178export function severityHex(percent: number): string {
179 return SEVERITY_HEX[colorFor(percent)]
180}
181
182function escapeXml(text: string): string {
183 return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
184}
185
186export function pillSvg(runs: readonly PillRun[]): { source: string; width: number; height: number } {
187 const chars = runs.reduce((n, run) => n + [...run.text].length, 0)
188 const width = Math.ceil(chars * PILL_CHAR_PX + 2 * PILL_PAD_PX)
189 const height = PILL_HEIGHT_PX
190 const spans = runs.map(run => `<tspan fill="${run.color}">${escapeXml(run.text)}</tspan>`).join('')
191 const source =
192 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
193 `<rect width="${width}" height="${height}" rx="${height / 2}" fill="#000000" fill-opacity="0.18"/>` +
194 `<text x="${PILL_PAD_PX}" y="${height / 2}" dominant-baseline="central" xml:space="preserve" ` +
195 `font-family="ui-monospace, 'Cascadia Mono', Consolas, Menlo, monospace" font-size="${PILL_FONT_PX}">` +
196 spans +
197 `</text></svg>`
198 return { source, width, height }
199}
200
201// What the band would hold, in cells, to decide what fits.
202export type BandSizes = {
203 cost: number
204 prompts: number
205 limits: readonly { full: number; compact: number }[]
206 gauge: number
207}
208
209// Fits the band to its width: the full band if it fits, else without the reset
210// countdowns, else without the prompt count as well.
211export function planBand(columns: number, sizes: BandSizes): { showsResets: boolean; showsPrompts: boolean } {
212 const widthOf = (showsResets: boolean, showsPrompts: boolean) => {
213 const pills = sizes.limits.map(limit => (showsResets ? limit.full : limit.compact) + 2)
214 const pillsWidth = pills.length > 0 ? pills.reduce((a, b) => a + b, 0) + pills.length - 1 : 0
215 const left = [sizes.cost, showsPrompts ? sizes.prompts : 0, pillsWidth].filter(w => w > 0)
216 const leftWidth = left.reduce((a, b) => a + b, 0) + 2 * Math.max(0, left.length - 1)
217 return 2 + leftWidth + 2 + sizes.gauge
218 }
219 const plans = [
220 { showsResets: true, showsPrompts: true },
221 { showsResets: false, showsPrompts: true },
222 { showsResets: false, showsPrompts: false },
223 ]
224 return plans.find(plan => widthOf(plan.showsResets, plan.showsPrompts) <= columns) ?? plans[2]!
225}
226