Band above the prompt: ctx %, cache countdown (1h TTL) and hit rate, 5h/7d quota used with pace, colored by level; press ctx to compact, ♨ to keep the cache…

Band above the prompt: ctx %, cache countdown (1h TTL) and hit rate, 5h/7d quota used with pace, colored by level (quota green <50%, yellow <80%, red after; cache green >20m, yellow ≤20m, red cold)
claude plugin marketplace add Hsiang-LinC/usage-band
claude plugin install usage@usage-band
Private repo: needs gh auth login (or any git credential for github.com) on the machine.
Test: claude plugin test .
5h and 7d compare the share used with the share of the window that has passed (from resetsAt) and show it as a sign (5h puts its reset time after it; 7d shows the sign only):
| sign | burn, against an even one |
|---|---|
▾ (green) | more than 5 points under the elapsed share |
⋅ (yellow) | within 5 points |
▴ (red) | more than 5 points over |
5h 50% ▴ 2h10m reads: half used, burning faster than even, 2h10m to reset. The pace counts from the start of the window. The ♨ is red while the cache is hot, light blue once it has gone cold, and plain before the first request.
Press (or click, where the terminal reports clicks) a figure that offers an action:
ctx 55%: from 50% context (the yellow threshold, so yellow and red alike), while no request is running, the figure itself is the button. It runs /compact; a refused or vetoed compact is shown as a toast. The cache then starts over (cache --), since the prefix has changed.cache 52m ♨ hit 90%: the hot-spring sign is always there, in the place of the dot, so the band does not shift. Plain and inert while the cache has 30 minutes or more left; with less, it turns red and can be pressed. Pressed, it sends one tiny request over the session's own prefix ($.model.fork), which reads the cached prefix and restarts the 1h TTL; a toast says how many tokens the cache served. It stays plain while a request runs, for 30s after a failed press, before the first request and once the cache is cold (that request would write the whole prefix again). It is a real request: on a subscription it counts against the quota. The cache segment turns yellow with 20 minutes left and red when cold.Click where the terminal reports clicks (not with CLAUDE_CODE_DISABLE_MOUSE_CLICKS), or press ctrl+x then Tab to focus the band, move with the arrows and press Enter.
The band uses a Wada-inspired green / ochre / vermilion palette, with light/dark text colours and no background fill, so the terminal background shows through. Labels keep the terminal's normal monospace font; percentages and countdowns are bold. Separators use a neutral colour. The working star cycles ochre → blue-grey → vermilion: a shape changes every 200ms, and each colour holds for 1.2s, without opacity blinking.
Built-in light/dark variants follow Claude Code's selected theme. For auto and custom themes, this version follows macOS system appearance, checked at most once every 5 seconds; it does not infer a custom theme's background. Automatic appearance detection currently requires macOS. Use an explicit built-in light/dark theme on other hosts.
hooks/register.tsx 309 lines1import type { EngineInterface, Register, Timer } from 'claude-code'
2
3import { formatSegments, PACE_EVEN, PACE_FAST, PACE_SLOW, type Level, type LineInput } from './format'
4
5type CacheUsage = NonNullable<NonNullable<LineInput['cache']>['usage']>
6// newest main-thread request whose response reported usage
7let answered: { sentAt: number; usage: CacheUsage } | undefined
8// main-thread requests in flight, by identity (two may share a millisecond);
9// the icon grows only while this is non-empty
10const pending = new Set<{ sentAt: number }>()
11// when the newest keep-warm request was sent: like any request, it restarts
12// the cache's TTL
13let warmedAt: number | undefined
14let warming = false
15let lastWarm: number | undefined
16let contextPercent: number | undefined
17let rateLimits: LineInput['rateLimits'] = []
18let tick: Timer | undefined
19let poll: Timer | undefined
20let frame = 0
21let anim: Timer | undefined
22
23const POLL_MS = 5_000
24// a keep-warm press is ignored this long after the last one
25const WARM_COOLDOWN_MS = 30_000
26const ANIM_MS = 200
27const STARS = ['✶', '✴', '✷', '✦', '✧', '✦']
28// One full shape cycle (1.2s) per colour; no opacity blinking.
29const FRAME_COUNT = STARS.length * 3
30const PALETTES = {
31 light: {
32 neutral: '#61675F',
33 cool: '#4A8DB7',
34 colors: { ok: '#286044', warn: '#755812', bad: '#983E32', none: '#61675F' },
35 stars: ['#755812', '#416579', '#983E32'],
36 },
37 dark: {
38 neutral: '#A2A99F',
39 cool: '#8EC5E8',
40 colors: { ok: '#82B58B', warn: '#C5A35B', bad: '#DC9180', none: '#A2A99F' },
41 stars: ['#C5A35B', '#8BAABD', '#DC9180'],
42 },
43} satisfies Record<'light' | 'dark', {
44 neutral: string; cool: string; colors: Record<Level, string>; stars: string[]
45}>
46
47// The mod API exposes the selected theme, not auto's resolved appearance.
48// On macOS, auto/custom themes follow system appearance, cached for 5s.
49let systemAppearance: Promise<'light' | 'dark'> | undefined
50let appearanceExpires = 0
51async function palette($: EngineInterface) {
52 const theme = (await $.config.list()).find(row => row.key === 'theme')?.value
53 if (typeof theme !== 'string') throw new Error('usage-band: missing theme config')
54 if (/^light(?:-|$)/.test(theme)) return PALETTES.light
55 if (/^dark(?:-|$)/.test(theme)) return PALETTES.dark
56 if (theme !== 'auto' && !theme.startsWith('custom:')) {
57 throw new Error('usage-band: unsupported theme selection')
58 }
59 const now = await $.clock.now()
60 if (!systemAppearance || now >= appearanceExpires) {
61 appearanceExpires = now + POLL_MS
62 systemAppearance = $.process.run(
63 ['/usr/bin/defaults', 'read', '-g', 'AppleInterfaceStyle'],
64 { timeoutMs: 1000 },
65 ).then(result => {
66 if (result.exitCode === 0 && result.stdout.trim() === 'Dark') return 'dark'
67 if (result.exitCode === 1 && /AppleInterfaceStyle.*does not exist/.test(result.stderr)) return 'light'
68 throw new Error('usage-band: cannot read macOS system appearance')
69 })
70 }
71 return PALETTES[await systemAppearance]
72}
73
74const redraw = ($: EngineInterface) => $.ui.invalidate('ui.render')
75
76function press($: EngineInterface, kind: 'compact' | 'warm') {
77 return kind === 'compact' ? compact($) : warm($)
78}
79
80// The same call /compact makes. It is refused while a request runs (the band
81// offers it only when idle, but the press can land just after one starts);
82// either way the person is told, and nothing is retried.
83async function compact($: EngineInterface) {
84 try {
85 const r = await $.session.compact()
86 if (r.skip !== undefined) return void $.ui.toast(`compact skipped: ${r.skip}`)
87 } catch (error) {
88 return void $.ui.toast(`compact failed: ${error instanceof Error ? error.message : String(error)}`)
89 }
90 // the compacted transcript is a new prefix: what was cached no longer
91 // matches, so the next request starts the countdown afresh
92 answered = undefined
93 warmedAt = undefined
94 tick?.cancel()
95 tick = undefined
96 redraw($)
97}
98
99// A minimal request over the session's own prefix: it reads the cached
100// prefix, which restarts the TTL, and answers one word. Not retried; a
101// failure or a cut-off request is toasted and leaves the countdown alone.
102async function warm($: EngineInterface) {
103 warming = true
104 redraw($)
105 const sentAt = await $.clock.now()
106 try {
107 const r = await $.model.fork({ prompt: 'Reply with the single word: ok' })
108 if (!r.isAnswered) return void $.ui.toast(`keep-warm failed: ${r.reason}`)
109 warmedAt = sentAt
110 phaseTicker($, await $.clock.now())
111 const { cache_read_input_tokens: read, cache_creation_input_tokens: written } = r.usage
112 $.ui.toast(read >= written
113 ? `cache kept warm (${read} tokens read)`
114 : `cache had lapsed: ${written} tokens written again`)
115 } catch (error) {
116 $.ui.toast(`keep-warm failed: ${error instanceof Error ? error.message : String(error)}`)
117 } finally {
118 warming = false
119 lastWarm = await $.clock.now()
120 // the button comes back once the cooldown is over
121 $.clock.after(WARM_COOLDOWN_MS, () => redraw($))
122 redraw($)
123 }
124}
125
126// The countdown runs from the newest request sent, answered or still in
127// flight; the hit rate is the newest answered one's.
128function cacheState(): LineInput['cache'] {
129 let sentAt = answered?.sentAt
130 for (const request of pending) {
131 if (sentAt === undefined || request.sentAt > sentAt) sentAt = request.sentAt
132 }
133 if (warmedAt !== undefined && (sentAt === undefined || warmedAt > sentAt)) sentAt = warmedAt
134 return sentAt === undefined ? undefined : { sentAt, usage: answered?.usage }
135}
136
137// A minute ticker phased on the countdown's start, so the band redraws
138// exactly when a whole minute crosses.
139function phaseTicker($: EngineInterface, now: number) {
140 tick?.cancel()
141 tick = undefined
142 const cache = cacheState()
143 if (cache === undefined) return
144 tick = $.clock.after(60_000 - ((now - cache.sentAt) % 60_000), () => {
145 redraw($)
146 tick = $.clock.every(60_000, () => redraw($))
147 })
148}
149
150// Redraws only when something shown can have changed: the figures, or the
151// minute (the countdowns tick in minutes). The 5s poll would otherwise redraw
152// an idle band twelve times a minute.
153let drawnMinute: number | undefined
154async function refreshUsage($: EngineInterface) {
155 const u = await $.session.usage()
156 const minute = Math.floor((await $.clock.now()) / 60_000)
157 const isChanged =
158 u.context.percent !== contextPercent ||
159 JSON.stringify(u.rateLimits) !== JSON.stringify(rateLimits) ||
160 minute !== drawnMinute
161 contextPercent = u.context.percent
162 rateLimits = u.rateLimits
163 drawnMinute = minute
164 if (isChanged) redraw($)
165}
166
167export const register: Register = on => {
168 on('session.start', async ($, e, next) => {
169 await refreshUsage($)
170 // keeps 5h/7d fresh in idle sessions, where no measure event fires
171 poll?.cancel()
172 poll = $.clock.every(POLL_MS, () => refreshUsage($))
173 return next(e)
174 })
175
176 on('session.measure', ($, e, next) => {
177 contextPercent = e.context.percent
178 rateLimits = e.rateLimits
179 redraw($)
180 return next(e)
181 })
182
183 // per request, not per turn: a turn's usage sums every request of its tool
184 // loop, and only the latest request says how warm the cache is now
185 on('turn.step', async function* ($, e, next) {
186 // sub-agents send other prefixes; they neither read nor refresh this cache
187 if (e.agentId !== undefined) return yield* next(e)
188 const request = { sentAt: await $.clock.now() }
189 // the TTL restarts as the request is sent, so count down from now at once,
190 // keeping the last answered hit rate until this response reports its own
191 pending.add(request)
192 phaseTicker($, request.sentAt)
193 if (pending.size === 1) {
194 frame = 0
195 anim = $.clock.every(ANIM_MS, () => {
196 frame = (frame + 1) % FRAME_COUNT
197 redraw($)
198 })
199 }
200 redraw($)
201 try {
202 const r = yield* next(e)
203 if (r.usage) {
204 const usage = {
205 input: r.usage.input_tokens,
206 cacheRead: r.usage.cache_read_input_tokens,
207 cacheWrite: r.usage.cache_creation_input_tokens,
208 }
209 if (answered === undefined || request.sentAt >= answered.sentAt) {
210 answered = { sentAt: request.sentAt, usage }
211 }
212 }
213 return r
214 } finally {
215 // a request that failed or was cut off without usage confirms nothing
216 // about the cache: dropping it rolls the countdown back
217 pending.delete(request)
218 if (pending.size === 0) {
219 anim?.cancel()
220 anim = undefined
221 frame = 0
222 }
223 phaseTicker($, await $.clock.now())
224 redraw($)
225 }
226 })
227
228 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
229 if (e.props.hasSurvey) return next(e)
230 const now = await $.clock.now()
231 const segments = formatSegments({
232 contextPercent,
233 rateLimits,
234 cache: cacheState(),
235 canCompact: pending.size === 0,
236 canWarm: pending.size === 0 && !warming && (lastWarm === undefined || now - lastWarm >= WARM_COOLDOWN_MS),
237 now,
238 })
239 if (segments.length === 0) return next(e)
240
241 // other mods share the band (vault-jot adds its row), so draw on top of
242 // what lies beneath rather than in its place
243 const beneath = await next(e)
244 const { Box, Button, Text } = $.ui.resolve(e)
245 const theme = await palette($)
246 // label dim-free, values bold: "5h 20% ▾ 2h13m" bolds 20% and 2h13m;
247 // the pace sign has its own colour: fast red, slow green, even yellow
248 const paceColor: Record<string, string | undefined> = { [PACE_FAST]: theme.colors.bad, [PACE_SLOW]: theme.colors.ok, [PACE_EVEN]: theme.colors.warn }
249 const body = (s: (typeof segments)[number]) => (
250 <Text color={theme.colors[s.level]}>
251 <Text>{s.text.slice(0, s.text.indexOf(' ') + 1)}</Text>
252 {s.text.slice(s.text.indexOf(' ') + 1).split(/(<?\d+(?:[dh]\d+)?[dhm%]|[▴▾⋅])/).filter(text => text !== '').map((text, j) =>
253 text in paceColor ? (
254 <Text key={String(j)} color={paceColor[text]}>{text}</Text>
255 ) : (
256 <Text key={String(j)} bold={/^(<?\d+(?:[dh]\d+)?[dhm%])$/.test(text)}>{text}</Text>
257 ),
258 )}
259 </Text>
260 )
261 const warmColor = (tone: 'hot' | 'cold' | 'none' | undefined) =>
262 tone === 'hot' ? theme.colors.bad : tone === 'cold' ? theme.cool : undefined
263 return (
264 <Box flexDirection="column">
265 <Box paddingX={1}>
266 {/* the frames' glyphs differ in width where the font falls back (desktop), so a fixed cell keeps the text after still */}
267 <Box width={2} flexShrink={0}>
268 <Text color={theme.stars[Math.floor(frame / STARS.length)]}>{STARS[frame % STARS.length]}</Text>
269 </Box>
270 {/* A Button cannot sit inside an inline Text, so the segments are flex
271 items. The desktop trims whitespace at each item's edges: the gaps
272 between items come from `gap`, never from spaces in the separators. */}
273 <Box gap={1} flexWrap="wrap">
274 {segments.flatMap((s, i) => [
275 // the always-drawn warm sign already separates cache from what follows
276 ...(i > 0 && !(segments[i - 1].action?.kind === 'warm' && segments[i - 1].group === s.group)
277 ? [<Text key={`sep-${i}`} color={theme.neutral}>{segments[i - 1].group === 'session' && s.group === 'session' ? '·' : '│'}</Text>]
278 : []),
279 <Box key={`seg-${i}`} gap={1}>
280 {s.action?.kind === 'compact' && s.action.isEnabled ? (
281 // the segment is the button
282 <Button key="compact" plain onPress={() => press($, 'compact')}>{body(s)}</Button>
283 ) : (
284 body(s)
285 )}
286 {s.action === undefined || s.action.kind === 'compact' ? null : s.action.kind === 'warm' ? (
287 s.action.isEnabled ? (
288 // sized by the Button itself: it adds its own padding, which a
289 // fixed 2-cell box clipped to half the sign
290 <Button key="warm" plain onPress={() => press($, 'warm')}>
291 <Text color={warmColor(s.action.tone)}>{s.action.label}</Text>
292 </Button>
293 ) : (
294 // a fixed cell: the sign is a different width where the font falls back
295 <Box width={2} flexShrink={0}>
296 <Text color={warmColor(s.action.tone)}>{s.action.label}</Text>
297 </Box>
298 )
299 ) : null}
300 </Box>,
301 ])}
302 </Box>
303 </Box>
304 {beneath}
305 </Box>
306 )
307 })
308}
309hooks/format.ts 157 lines1export const CACHE_TTL_MS = 60 * 60 * 1000
2
3export type Level = 'ok' | 'warn' | 'bad' | 'none'
4// session: ctx and cache; quota: 5h and 7d. The band separates the two groups.
5// `action` is a button drawn after the segment (a Button cannot carry the
6// segment's colours). A disabled action keeps its place, drawn dim and inert,
7// so the band does not shift when the action comes and goes.
8// The warm sign's colour: red while the cache is hot, cool blue once it has
9// gone cold, plain before any request has started it.
10export type WarmTone = 'hot' | 'cold' | 'none'
11export type Segment = {
12 text: string
13 level: Level
14 group: 'session' | 'quota'
15 action?: { kind: 'compact' | 'warm'; label: string; isEnabled: boolean; tone?: WarmTone }
16}
17
18// Usage turns yellow at WARN_AT and red at BAD_AT; ctx is pressable (compact)
19// from the first colour change on.
20const WARN_AT = 50
21const BAD_AT = 80
22export const COMPACT_FROM = WARN_AT
23// The Japanese hot-spring sign (U+2668). It is also an emoji, which some
24// terminals draw two cells wide: the band gives it a fixed two-cell box.
25export const WARM_SIGN = '♨'
26// The cache segment turns yellow with this long left: a simple threshold, so
27// nothing needs drawing at the moment it is crossed beyond the minute tick.
28export const CACHE_WARN_MS = 20 * 60_000
29// The warm sign is pressable with less than this left; before that it is the
30// same sign, inert.
31export const WARM_FROM_MS = 30 * 60_000
32
33type Usage = { input: number; cacheRead: number; cacheWrite: number }
34
35export type LineInput = {
36 contextPercent?: number
37 rateLimits: { kind: string; percentUsed: number; resetsAt?: string }[]
38 // Absent until a main-thread request has been sent.
39 // Whether /compact can run now: it is refused while a request is in flight.
40 canCompact?: boolean
41 // Whether a keep-warm request can go now: nothing in flight, none just sent.
42 canWarm?: boolean
43 cache?: {
44 // When the newest counted request was sent (ms): the TTL restarts when a
45 // request reads or writes the cache, not when its response ends.
46 sentAt: number
47 // Figures of the newest request that answered; absent while none has.
48 usage?: Usage
49 }
50 now: number
51}
52
53// Green <50, yellow <80, red after; shared by ctx and quota.
54const byUsed = (pct: number): Level => (pct >= BAD_AT ? 'bad' : pct >= WARN_AT ? 'warn' : 'ok')
55
56// "3d04h" / "2h13m" / "45m"
57function duration(ms: number): string {
58 const mins = Math.max(1, Math.floor(ms / 60_000))
59 if (mins >= 1440) return `${Math.floor(mins / 1440)}d${String(Math.floor((mins % 1440) / 60)).padStart(2, '0')}h`
60 return mins >= 60 ? `${Math.floor(mins / 60)}h${String(mins % 60).padStart(2, '0')}m` : `${mins}m`
61}
62
63// Time until the window resets; undefined once it already has.
64function untilReset(resetsAt: string | undefined, now: number): string | undefined {
65 if (resetsAt === undefined) return undefined
66 const ms = Date.parse(resetsAt) - now
67 return ms > 0 ? duration(ms) : undefined
68}
69
70const hitPercent = (u: Usage | undefined): number | undefined => {
71 const total = u ? u.input + u.cacheRead + u.cacheWrite : 0
72 return u && total > 0 ? Math.floor((u.cacheRead / total) * 100) : undefined
73}
74
75const WINDOW_MS = { five_hour: 5 * 3_600_000, seven_day: 7 * 86_400_000 } as const
76// The pace signs; the band colours ▴ red and ▾ green. The dot is the smaller
77// U+22C5, so it does not outweigh the triangles.
78export const PACE_FAST = '▴'
79export const PACE_SLOW = '▾'
80export const PACE_EVEN = '⋅'
81// Used share within this many points of the elapsed share counts as even. Points
82// rather than a ratio: a ratio is unstable at the start of a window.
83const EVEN_BAND = 5
84const paceSign = (diff: number) => (diff > EVEN_BAND ? PACE_FAST : diff < -EVEN_BAND ? PACE_SLOW : PACE_EVEN)
85
86// Used share minus elapsed share of the window, in points: 0 is an even burn.
87function pace(kind: keyof typeof WINDOW_MS, percentUsed: number, resetsAt: string | undefined, now: number): number | undefined {
88 if (resetsAt === undefined) return undefined
89 const length = WINDOW_MS[kind]
90 const left = Date.parse(resetsAt) - now
91 if (!(left > 0)) return undefined
92 return percentUsed - ((length - left) / length) * 100
93}
94
95export function formatSegments(i: LineInput): Segment[] {
96 const parts: Segment[] = []
97
98 if (i.contextPercent !== undefined) {
99 const pct = Math.floor(i.contextPercent)
100 const level = byUsed(pct)
101 // the segment itself is the button; the band draws it pressable
102 const action = i.canCompact && pct >= COMPACT_FROM ? { kind: 'compact' as const, label: 'compact', isEnabled: true } : undefined
103 parts.push({ text: `ctx ${pct}%`, level, group: 'session', ...(action && { action }) })
104 }
105
106 const c = i.cache
107 // always drawn: live only for a warm cache under 30 minutes, with an idle session
108 const warm = (isEnabled: boolean, tone: WarmTone) => ({ kind: 'warm' as const, label: WARM_SIGN, isEnabled, tone })
109 if (c === undefined) {
110 parts.push({ text: 'cache --', level: 'none', group: 'session', action: warm(false, 'none') })
111 } else {
112 const remaining = c.sentAt + CACHE_TTL_MS - i.now
113 if (remaining <= 0) {
114 parts.push({ text: 'cache cold', level: 'bad', group: 'session', action: warm(false, 'cold') })
115 } else {
116 const text =
117 remaining < 60_000 ? 'cache <1m' : `cache ${Math.floor(remaining / 60_000)}m`
118 const level: Level = remaining > CACHE_WARN_MS ? 'ok' : 'warn'
119 parts.push({
120 text,
121 level,
122 group: 'session',
123 action: warm(i.canWarm === true && remaining < WARM_FROM_MS, 'hot'),
124 })
125 const hit = hitPercent(c.usage)
126 if (hit !== undefined) parts.push({ text: `hit ${hit}%`, level, group: 'session' })
127 }
128 }
129
130 for (const [kind, label] of [
131 ['five_hour', '5h'],
132 ['seven_day', '7d'],
133 ] as const) {
134 const w = i.rateLimits.find(r => r.kind === kind)
135 if (w) {
136 const pct = Math.floor(w.percentUsed)
137 const reset = untilReset(w.resetsAt, i.now)
138 const p = pace(kind, w.percentUsed, w.resetsAt, i.now)
139 // the sign says how fast the window is being used; 7d shows no reset time
140 const sign = p !== undefined ? paceSign(p) : ''
141 parts.push({
142 text: [`${label} ${pct}%`, sign, kind === 'five_hour' ? reset : undefined].filter(part => part !== undefined && part !== '').join(' '),
143 level: byUsed(pct),
144 group: 'quota',
145 })
146 }
147 }
148
149 return parts
150}
151
152export function formatLine(i: LineInput): string {
153 return formatSegments(i)
154 .map(s => s.text)
155 .join(' · ')
156}
157