Shows context, 5h / 7d usage limits with reset countdowns, and output tok/s above the prompt

Personal Claude Code mods, published as a local plugin marketplace.
claude plugin marketplace add ~/Desktop/Github/claude-mods
claude plugin install usage-limit@claude-mods
hooks/register.tsx 360 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Limit } from '../types'
5
6const limits = atom({ plugin: 'usage-limit', key: 'limits' } as const, [])
7const contextPercent = atom({ plugin: 'usage-limit', key: 'contextPercent' } as const, null)
8// output tokens per second of the main conversation's last finished response
9const speed = atom({ plugin: 'usage-limit', key: 'speed' } as const, null)
10
11const HOUR = 3_600_000
12const WINDOWS: Record<string, { label: string; ms?: number; showsClock?: boolean }> = {
13 five_hour: { label: '5h', ms: 5 * HOUR, showsClock: true },
14 seven_day: { label: '7d', ms: 7 * 24 * HOUR },
15 spend_limit: { label: '$' },
16}
17const WARN_AT = [80, 90]
18// refreshes countdowns and the elapsed marker between measurements
19const TICK_MS = 60_000
20// reset clock times are shown in UTC+8
21const CLOCK_OFFSET = 8 * HOUR
22// responses shorter than this are too brief to time cleanly
23const MIN_SPEED_MS = 1000
24const MIN_SPEED_TOKENS = 20
25
26// Layout
27const BAR_CELLS = 10
28const METER_GAP = 3
29const SVG_COLORS: Record<string, string> = {
30 green: '#4caf50',
31 yellow: '#e0a526',
32 red: '#e5534b',
33 track: 'rgba(128,128,128,0.3)',
34}
35
36// value is the percentage; reset (countdown) and clock (reset time of day) are drawn in their own colors
37type Meter = {
38 key: string
39 label: string
40 used: number
41 elapsed: number | null
42 tone: string
43 value: string
44 reset: string | null
45 clock: string | null
46 // a plain figure (tok/s) draws no bar
47 noBar?: boolean
48}
49
50let ticker: { cancel: () => void } | null = null
51
52function clamp(p: number) {
53 return Math.min(100, Math.max(0, p))
54}
55
56// Pace: how far usage runs ahead of the share of the window already gone
57function toneOf(used: number, elapsed: number | null) {
58 if (used >= 90) return 'red'
59 if (elapsed === null) return used >= 80 ? 'red' : used >= 50 ? 'yellow' : 'green'
60 const margin = elapsed - used
61 if (margin < -15) return 'red'
62 if (margin < 10 && used >= 10) return 'yellow'
63 return 'green'
64}
65
66function duration(ms: number) {
67 const minutes = Math.max(0, Math.ceil(ms / 60_000))
68 const d = Math.floor(minutes / 1440)
69 const h = Math.floor((minutes % 1440) / 60)
70 const m = minutes % 60
71 return d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`
72}
73
74function clock(ms: number) {
75 const t = new Date(ms + CLOCK_OFFSET)
76 return `${String(t.getUTCHours()).padStart(2, '0')}:${String(t.getUTCMinutes()).padStart(2, '0')}`
77}
78
79function limitMeter(limit: Limit, now: number): Meter {
80 const win = WINDOWS[limit.kind]
81 const label = win?.label ?? limit.kind
82 const resetsAt = limit.resetsAt ? Date.parse(limit.resetsAt) : null
83 // the window has reset since the last reading: it starts again from zero
84 if (resetsAt !== null && resetsAt <= now) {
85 return { key: limit.kind, label, used: 0, elapsed: win?.ms ? 0 : null, tone: 'green', value: '0%', reset: null, clock: null }
86 }
87 const resetIn = resetsAt === null ? null : resetsAt - now
88 const elapsed = win?.ms && resetIn !== null ? clamp(100 - (resetIn / win.ms) * 100) : null
89 const value = `${Math.round(limit.percentUsed)}%`
90 const reset = resetIn === null ? null : duration(resetIn)
91 const at = resetsAt !== null && win?.showsClock ? `(${clock(resetsAt)})` : null
92 return { key: limit.kind, label, used: limit.percentUsed, elapsed, tone: toneOf(limit.percentUsed, elapsed), value, reset, clock: at }
93}
94
95// Desktop chips: one SVG per meter (the band's Box has no rounded backgrounds), each a tinted
96// pill with an icon, label, thin bar, bold percentage and, after a divider, the reset countdown.
97// Light and dark come from prefers-color-scheme inside the SVG. Icons are Lucide paths (ISC).
98const CHIP_H = 20
99const CHIP_PAD = 9
100const ICON = 11
101const GAP = 7
102const LETTER = 0.6
103const BAR_H = 3
104const FONT = 11
105const BAR_W = 36
106const CHIP_THEMES: Record<string, { tint: string; accent: string; accentDark: string; icon: string }> = {
107 ctx: { tint: 'rgba(70,130,240,0.16)', accent: '#3d72d6', accentDark: '#7aa5f5', icon: 'layers' },
108 five_hour: { tint: 'rgba(76,175,80,0.16)', accent: '#3f8f43', accentDark: '#6cc070', icon: 'gauge' },
109 seven_day: { tint: 'rgba(124,92,230,0.16)', accent: '#6d4fd6', accentDark: '#a48cf5', icon: 'calendar' },
110 speed: { tint: 'rgba(224,165,38,0.18)', accent: '#b07d10', accentDark: '#f0c050', icon: 'zap' },
111}
112const ICONS: Record<string, string> = {
113 gauge: '<path d="m12 14 4-4"/><path d="M3.34 19a10 10 0 1 1 17.32 0"/>',
114 calendar: '<rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/>',
115 layers:
116 '<path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/><path d="m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65"/><path d="m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65"/>',
117 history: '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>',
118 zap: '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',
119}
120
121// Monospace advance: ASCII is 0.6em, anything wider (⚠, CJK) taken as a full em, plus letter-spacing
122function textWidth(text: string, size = FONT) {
123 return [...text].reduce((w, ch) => w + (ch.charCodeAt(0) < 128 ? 0.6 : 1) * size + LETTER, 0)
124}
125
126function esc(text: string) {
127 return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
128}
129
130function icon(name: string, x: number, cls: string) {
131 const y = (CHIP_H - ICON) / 2
132 return `<g class="${cls}" transform="translate(${x} ${y}) scale(${ICON / 24})" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${ICONS[name]}</g>`
133}
134
135function chipSvg(m: Meter) {
136 const theme = CHIP_THEMES[m.key] ?? CHIP_THEMES.ctx
137 const mid = CHIP_H / 2
138 const base = mid + FONT * 0.35
139 const parts: string[] = []
140 let x = CHIP_PAD
141
142 parts.push(icon(theme.icon, x, 'accent'))
143 x += ICON + 5
144 parts.push(`<text x="${x}" y="${base}" class="muted">${esc(m.label)}</text>`)
145 x += textWidth(m.label) + GAP
146
147 if (!m.noBar) {
148 const barY = mid - BAR_H / 2
149 const fill = Math.round((clamp(m.used) / 100) * BAR_W)
150 parts.push(`<clipPath id="b"><rect x="${x}" y="${barY}" width="${BAR_W}" height="${BAR_H}" rx="${BAR_H / 2}"/></clipPath>`)
151 parts.push(`<g clip-path="url(#b)"><rect x="${x}" y="${barY}" width="${BAR_W}" height="${BAR_H}" fill="${SVG_COLORS.track}"/>`)
152 if (fill > 0) parts.push(`<rect x="${x}" y="${barY}" width="${fill}" height="${BAR_H}" fill="${SVG_COLORS[m.tone]}"/>`)
153 parts.push('</g>')
154 if (m.elapsed !== null) {
155 const mx = x + Math.min(BAR_W - 2, Math.max(0, Math.round((m.elapsed / 100) * BAR_W) - 1))
156 parts.push(`<rect x="${mx}" y="${mid - 4}" width="1.5" height="8" rx="1" class="ink-fill"/>`)
157 }
158 x += BAR_W + GAP
159 }
160
161 // the percentage stays in ink while on pace, and takes the warning color once it isn't
162 const pctClass = m.tone === 'green' ? 'ink' : ''
163 const pctFill = m.tone === 'green' ? '' : ` fill="${SVG_COLORS[m.tone]}"`
164 parts.push(`<text x="${x}" y="${base}" font-weight="700" class="${pctClass}"${pctFill}>${esc(m.value)}</text>`)
165 x += textWidth(m.value)
166
167 if (m.reset) {
168 x += GAP
169 parts.push(`<rect x="${x}" y="${mid - 5}" width="1" height="10" class="divider"/>`)
170 x += 1 + GAP
171 parts.push(icon('history', x, 'accent'))
172 x += ICON + 5
173 parts.push(`<text x="${x}" y="${base}" class="accent-fill">${esc(m.reset)}</text>`)
174 x += textWidth(m.reset)
175 }
176 if (m.clock) {
177 x += 5
178 parts.push(`<text x="${x}" y="${base}" class="muted">${esc(m.clock)}</text>`)
179 x += textWidth(m.clock)
180 }
181 const width = Math.ceil(x + CHIP_PAD)
182
183 const style =
184 `text{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:${FONT}px;letter-spacing:${LETTER}px}` +
185 `.ink{fill:#2b2b2b}.ink-fill{fill:#2b2b2b}.muted{fill:#6b6b6b}.divider{fill:rgba(0,0,0,0.15)}` +
186 `.accent{stroke:${theme.accent}}.accent-fill{fill:${theme.accent}}` +
187 `@media (prefers-color-scheme: dark){.ink,.ink-fill{fill:#ececec}.muted{fill:#a3a3a3}` +
188 `.divider{fill:rgba(255,255,255,0.18)}.accent{stroke:${theme.accentDark}}.accent-fill{fill:${theme.accentDark}}}`
189 return {
190 width,
191 source:
192 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${CHIP_H}" viewBox="0 0 ${width} ${CHIP_H}">` +
193 `<style>${style}</style><rect width="${width}" height="${CHIP_H}" rx="${CHIP_H / 2}" fill="${theme.tint}"/>` +
194 parts.join('') +
195 '</svg>',
196 }
197}
198
199// The terminal's bar as runs of cells: used in the tone color, the rest dim, the elapsed marker cyan
200function textBarRuns(used: number, elapsed: number | null) {
201 const filled = Math.round((clamp(used) / 100) * BAR_CELLS)
202 const marker = elapsed === null ? -1 : Math.min(BAR_CELLS - 1, Math.floor((elapsed / 100) * BAR_CELLS))
203 const runs: { kind: 'used' | 'rest' | 'marker'; text: string }[] = []
204 for (let i = 0; i < BAR_CELLS; i++) {
205 const kind = i === marker ? 'marker' : i < filled ? 'used' : 'rest'
206 const char = kind === 'marker' ? '┃' : kind === 'used' ? '█' : '░'
207 const last = runs[runs.length - 1]
208 if (last && last.kind === kind) last.text += char
209 else runs.push({ kind, text: char })
210 }
211 return runs
212}
213
214// Whether every meter fits on one line with its text bar
215function barsFit(meters: Meter[], columns: number) {
216 const width = meters.reduce(
217 (sum, m) => sum + m.label.length + 1 + (m.noBar ? 0 : BAR_CELLS + 1) + m.value.length + (m.reset ? m.reset.length + 3 : 0) + (m.clock ? m.clock.length + 1 : 0),
218 0,
219 )
220 return width + METER_GAP * (meters.length - 1) <= columns - 2
221}
222
223// Whether a render tree draws anything: text, or an element other than a bare Box or Text
224function hasContent(node: unknown): boolean {
225 if (node == null || node === false) return false
226 if (typeof node === 'string') return node.trim() !== ''
227 if (typeof node === 'number') return true
228 if (Array.isArray(node)) return node.some(hasContent)
229 const el = node as { type?: string; children?: unknown }
230 if (el.type !== 'Box' && el.type !== 'Text') return true
231 return hasContent(el.children)
232}
233
234export const register: Register = on => {
235 on('session.start', async ($, e, next) => {
236 const usage = await $.session.usage()
237 await update($, limits, () => usage.rateLimits)
238 await update($, contextPercent, () => usage.context.percent ?? null)
239 ticker?.cancel()
240 ticker = $.clock.every(TICK_MS, () => $.ui.invalidate('ui.render'))
241 return next(e)
242 })
243
244 on('session.measure', async ($, e, next) => {
245 if (e.changed.includes('context')) {
246 await update($, contextPercent, () => e.context.percent ?? null)
247 }
248 if (e.changed.includes('rateLimits')) {
249 const before = await read($, limits)
250 for (const limit of e.rateLimits) {
251 const old = before.find(l => l.kind === limit.kind)?.percentUsed ?? 0
252 const crossed = WARN_AT.filter(t => old < t && limit.percentUsed >= t).pop()
253 if (crossed) {
254 $.ui.toast(`${WINDOWS[limit.kind]?.label ?? limit.kind} usage limit passed ${crossed}%`)
255 }
256 }
257 await update($, limits, () => e.rateLimits)
258 }
259 return next(e)
260 })
261
262 // Times the main conversation's responses: output_tokens over the time from the first piece to the stop.
263 // Subagents run in parallel on their own models, so they are left out.
264 on('turn.step', async function* ($, e, next) {
265 if (e.agentId) return yield* next(e)
266 const stream = next(e)
267 let first: number | null = null
268 for await (const c of stream) {
269 const t = performance.now()
270 if (first === null) first = t
271 if (c.kind === 'stop' && c.usage) {
272 const ms = t - first
273 const tokens = c.usage.output_tokens
274 if (ms >= MIN_SPEED_MS && tokens >= MIN_SPEED_TOKENS) {
275 await update($, speed, () => tokens / (ms / 1000))
276 }
277 }
278 yield c
279 }
280 return await stream.result
281 })
282
283 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
284 const current: Limit[] = await read($, limits)
285 const ctx = await read($, contextPercent)
286 const rate = await read($, speed)
287 if (e.props.hasSurvey || (current.length === 0 && ctx === null && rate === null)) {
288 return next(e)
289 }
290
291 const now = await $.clock.now()
292 const meters: Meter[] = []
293 if (ctx !== null) {
294 meters.push({ key: 'ctx', label: 'ctx', used: ctx, elapsed: null, tone: toneOf(ctx, null), value: `${ctx}%`, reset: null, clock: null })
295 }
296 for (const limit of current) meters.push(limitMeter(limit, now))
297 if (rate !== null) {
298 const value = rate < 10 ? rate.toFixed(1) : String(Math.round(rate))
299 meters.push({ key: 'speed', label: 'tok/s', used: 0, elapsed: null, tone: 'green', value, reset: null, clock: null, noBar: true })
300 }
301
302 const elements = $.ui.resolve(e)
303 const { Box, Text } = elements
304 const Svg = 'Svg' in elements ? elements.Svg : null
305 const gauge = barsFit(meters, e.props.bodyColumns) ? 'text' : 'none'
306
307 const line = Svg ? (
308 <Box flexDirection="row" flexWrap="wrap" columnGap={1} rowGap={1}>
309 {meters.map(m => {
310 const chip = chipSvg(m)
311 return (
312 <Svg
313 key={`chip-${m.key}`}
314 source={chip.source}
315 alt={`${m.label} ${m.value}${m.reset ? `, resets in ${m.reset}` : ''}${m.elapsed === null ? '' : `, ${Math.round(m.elapsed)}% of the window gone`}`}
316 width={chip.width}
317 height={CHIP_H}
318 />
319 )
320 })}
321 </Box>
322 ) : (
323 <Box flexDirection="row" columnGap={METER_GAP}>
324 {meters.map(m => (
325 <Box key={`meter-${m.key}`} flexDirection="row" columnGap={1} alignItems="center">
326 <Text>{m.label}</Text>
327 {gauge === 'text' && !m.noBar ? (
328 <Text>
329 {textBarRuns(m.used, m.elapsed).map((run, i) =>
330 run.kind === 'marker' ? (
331 <Text key={i} color="cyan" bold>{run.text}</Text>
332 ) : run.kind === 'used' ? (
333 <Text key={i} color={m.tone}>{run.text}</Text>
334 ) : (
335 <Text key={i} dimColor>{run.text}</Text>
336 ),
337 )}
338 </Text>
339 ) : null}
340 <Text color={m.tone}>{m.value}</Text>
341 {m.reset ? <Text color="cyan">↻ {m.reset}</Text> : null}
342 {m.clock ? <Text dimColor>{m.clock}</Text> : null}
343 </Box>
344 ))}
345 </Box>
346 )
347
348 // keep what later mods draw in the band
349 const rest = await next(e)
350 // an empty tree from below would still take the row gap, leaving a blank row under the meters
351 if (!hasContent(rest)) return line
352 return (
353 <Box flexDirection="column" rowGap={e.surface === 'desktop' ? 1 : 0}>
354 {line}
355 {rest}
356 </Box>
357 )
358 })
359}
360types/index.d.ts 8 lines1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2
3declare module 'claude-code' {
4 interface PluginState {
5 'usage-limit': { limits: Limit[]; contextPercent: number | null; speed: number | null }
6 }
7}
8