Shows the git branch, context, 5-hour and weekly limits, token usage and cost right above the prompt

A bordered band right above the Claude Code prompt.

/context lists them, estimated locally)./cost totals it.Bars and percentages turn yellow from 70% used and red from 90%.
| Setting | Default | |
|---|---|---|
timezone | system | IANA timezone for reset times, e.g. Asia/Dhaka. |
showBranch | true | Show the branch row. |
showContext | true | Show the context row. |
showLimits | true | Show 5h / Week / On-demand. |
showTokenBreakdown | true | Show Read/Write and Cache R/W. |
showTokens | true | Show total tokens. |
showCost | true | Show cost. |
Change them under /config. With every section off, the band is hidden.
claude plugin validate mods/cockpit
claude plugin test mods/cockpithooks/register.tsx 480 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { EngineInterface } from 'claude-code'
5
6import type { Category, Context, Limit, Tokens } from '../types'
7
8const limits = atom({ plugin: 'cockpit', key: 'limits' } as const, [])
9const costUsd = atom({ plugin: 'cockpit', key: 'costUsd' } as const, null)
10const minute = atom({ plugin: 'cockpit', key: 'minute' } as const, 0)
11const tokens = atom({ plugin: 'cockpit', key: 'tokens' } as const, null)
12const context = atom({ plugin: 'cockpit', key: 'context' } as const, null)
13const branch = atom({ plugin: 'cockpit', key: 'branch' } as const, null)
14
15const LABELS: Record<string, string> = {
16 five_hour: '5h',
17 seven_day: 'Week',
18 spend_limit: 'On-demand',
19}
20const ORDER = ['five_hour', 'seven_day', 'spend_limit']
21const BAR_WIDTH = 10
22const DAY = 24 * 60 * 60 * 1000
23const BORDER = '#b5664a'
24const ZERO = { read: 0, write: 0, cacheRead: 0, cacheWrite: 0 }
25
26export const label = (kind: string) => LABELS[kind] ?? kind.replace(/_/g, ' ')
27
28// The used part and the rest of a thin line bar, drawn in two colours.
29export const bar = (percent: number) => {
30 const filled = Math.min(BAR_WIDTH, Math.max(0, Math.round((percent / 100) * BAR_WIDTH)))
31
32 // Both centred on the text's midline: a thick bar over a thin track.
33 return { used: '▬'.repeat(filled), rest: '─'.repeat(BAR_WIDTH - filled) }
34}
35
36// A valid IANA name, or undefined for the system's own timezone.
37export const zone = (setting: unknown) => {
38 if (typeof setting !== 'string' || setting.trim() === '' || setting.trim().toLowerCase() === 'system') {
39 return undefined
40 }
41 try {
42 new Intl.DateTimeFormat('en-US', { timeZone: setting.trim() })
43
44 return setting.trim()
45 } catch {
46 return undefined
47 }
48}
49
50// 8 -> "8", 3_000 -> "3k", 3_240 -> "3.2k", 1_250_000 -> "1.3M"
51export const count = (n: number) => {
52 const short = (v: number, unit: string) => `${Number(v.toFixed(1))}${unit}`
53
54 return n >= 1e6 ? short(n / 1e6, 'M') : n >= 1e3 ? short(n / 1e3, 'k') : `${n}`
55}
56
57// Pads each text on the left to the widest one's length.
58export const pad = (...texts: string[]) => {
59 const width = Math.max(...texts.map(t => t.length))
60
61 return texts.map(t => t.padStart(width))
62}
63
64export const usd = (amount: number) => `$${amount.toFixed(2)}`
65
66export const color = (percent: number) => (percent >= 90 ? 'red' : percent >= 70 ? 'yellow' : 'green')
67
68export const countdown = (at: number, now: number) => {
69 const minutes = Math.max(0, Math.round((at - now) / 60000))
70 const days = Math.floor(minutes / 1440)
71 const hours = Math.floor((minutes % 1440) / 60)
72 const mins = minutes % 60
73 return days > 0 ? `${days}d ${hours}h` : hours > 0 ? `${hours}h ${mins}m` : `${mins}m`
74}
75
76// "⏳ 03:31 PM (2h 30m)"; a reset more than a day out leads with its weekday.
77export const resetLabel = (resetsAt: string | undefined, now: number, timeZone?: string) => {
78 const at = resetsAt ? Date.parse(resetsAt) : NaN
79 if (Number.isNaN(at)) {
80 return ''
81 }
82 const time = new Intl.DateTimeFormat('en-US', {
83 timeZone,
84 weekday: at - now > DAY ? 'short' : undefined,
85 hour: '2-digit',
86 minute: '2-digit',
87 hour12: true,
88 }).format(at)
89
90 return `⏳ ${time} (${countdown(at, now)})`
91}
92
93const TOP = 4
94
95// The biggest rows that occupy the window, largest first.
96export const topCategories = (rows: readonly { name: string; tokens: number; color: string; kind: string }[]): Category[] =>
97 rows
98 .filter(r => r.kind === 'used' && r.tokens > 0)
99 .sort((a, b) => b.tokens - a.tokens)
100 .slice(0, TOP)
101 .map(r => ({ name: r.name, tokens: r.tokens, color: r.color }))
102
103// The window's fill and, as /context counts it (the local estimate, no requests), its biggest rows.
104const measureContext = async ($: EngineInterface): Promise<Context> => {
105 const { context: c } = await $.session.usage({ breakdown: 'summary' })
106
107 return { window: c.window, tokens: c.tokens, percent: c.percent, top: topCategories(c.breakdown?.categories ?? []) }
108}
109
110type Counts = typeof ZERO
111
112// Sums the usage of every reply in a transcript (JSONL). A reply is written
113// once per content block, each line repeating its usage, so each message id counts once.
114export const sumTranscript = (text: string): Counts => {
115 const replies = new Map<string, Counts>()
116 for (const line of text.split('\n')) {
117 if (!line.includes('"usage"')) {
118 continue
119 }
120 try {
121 const entry = JSON.parse(line)
122 const u = entry?.message?.usage
123 if (entry?.type !== 'assistant' || !u) {
124 continue
125 }
126 replies.set(entry.message.id ?? entry.uuid, {
127 read: u.input_tokens ?? 0,
128 write: u.output_tokens ?? 0,
129 cacheRead: u.cache_read_input_tokens ?? 0,
130 cacheWrite: u.cache_creation_input_tokens ?? 0,
131 })
132 } catch {
133 // A line cut short while being written: skip it.
134 }
135 }
136 const sum = { ...ZERO }
137 for (const r of replies.values()) {
138 sum.read += r.read
139 sum.write += r.write
140 sum.cacheRead += r.cacheRead
141 sum.cacheWrite += r.cacheWrite
142 }
143
144 return sum
145}
146
147// The conversation's transcript, and its subagents', counted; null when it cannot be read.
148const countTranscript = async ($: EngineInterface, cwd: string): Promise<Counts | null> => {
149 try {
150 const id = await $.session.id()
151 const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
152 const config = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`
153 const dir = `${config}/projects/${cwd.replace(/[^a-zA-Z0-9]/g, '-')}`
154 const sum = sumTranscript(await $.fs.read(`${dir}/${id}.jsonl`))
155 try {
156 for (const f of await $.fs.list(`${dir}/${id}/subagents`)) {
157 if (f.name.endsWith('.jsonl')) {
158 const sub = sumTranscript(await $.fs.read(`${dir}/${id}/subagents/${f.name}`))
159 sum.read += sub.read
160 sum.write += sub.write
161 sum.cacheRead += sub.cacheRead
162 sum.cacheWrite += sub.cacheWrite
163 }
164 }
165 } catch {
166 // No subagents ran.
167 }
168
169 return sum
170 } catch {
171 return null
172 }
173}
174
175// The session's branch, the short sha when detached, null outside a repo.
176const currentBranch = async ($: EngineInterface) => {
177 try {
178 const cwd = await $.session.cwd()
179 const git = (...args: string[]) => $.process.run(['git', ...args], { cwd, timeoutMs: 5000 })
180 const name = await git('branch', '--show-current')
181 if (name.exitCode !== 0) {
182 return null
183 }
184 if (name.stdout.trim()) {
185 return name.stdout.trim()
186 }
187 const sha = await git('rev-parse', '--short', 'HEAD')
188
189 return sha.exitCode === 0 && sha.stdout.trim() ? sha.stdout.trim() : null
190 } catch {
191 return null
192 }
193}
194
195const refreshBranch = async ($: EngineInterface) => {
196 const name = await currentBranch($)
197 await update($, branch, () => name)
198}
199
200// Which sections the band draws; each on unless its setting is off.
201export const shown = (options: Record<string, unknown>) => {
202 const on = (key: string) => options[key] !== false
203
204 return {
205 branch: on('showBranch'),
206 context: on('showContext'),
207 limits: on('showLimits'),
208 breakdown: on('showTokenBreakdown'),
209 tokens: on('showTokens'),
210 cost: on('showCost'),
211 }
212}
213
214const sorted = (list: readonly Limit[]) =>
215 [...list].sort((a, b) => {
216 const ia = ORDER.indexOf(a.kind)
217 const ib = ORDER.indexOf(b.kind)
218
219 return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib)
220 })
221
222export const register: Register = (on, options) => {
223 const timeZone = zone(options.timezone)
224 const show = shown(options)
225
226 on('session.start', async ($, e, next) => {
227 const result = await next(e)
228 const usage = await $.session.usage()
229 await update($, limits, () => usage.rateLimits.map(l => ({ ...l })))
230 await update($, costUsd, () => usage.cost?.usd ?? null)
231 const measured = await measureContext($)
232 await update($, context, () => measured)
233 if (show.branch) {
234 await refreshBranch($)
235 }
236 // A reload keeps the running totals; a new session (or /clear) counts its
237 // transcript once, then each turn adds to that.
238 const current = await read($, tokens)
239 if (!(current?.startedAt === usage.startedAt && current.isFull)) {
240 const counted = await countTranscript($, e.cwd)
241 await update($, tokens, () =>
242 counted
243 ? { startedAt: usage.startedAt, isFull: true, ...counted }
244 : { startedAt: usage.startedAt, isFull: false, ...ZERO },
245 )
246 }
247 // One cheap redraw a minute keeps the reset countdowns current.
248 $.clock.every(60000, () => update($, minute, n => n + 1))
249
250 return result
251 })
252
253 on('session.measure', async ($, e, next) => {
254 if (e.changed.includes('rateLimits')) {
255 await update($, limits, () => e.rateLimits.map(l => ({ ...l })))
256 }
257 if (e.changed.includes('cost')) {
258 await update($, costUsd, () => e.cost?.usd ?? null)
259 }
260 if (e.changed.includes('context')) {
261 const measured = await measureContext($)
262 await update($, context, () => measured)
263 }
264
265 return next(e)
266 })
267
268 // Read: uncached input; Write: generated output; Cache Read / Cache Write:
269 // input served from and written to the prompt cache. Nested tasks' turns count too.
270 on('turn.complete', async ($, e, next) => {
271 const u = e.usage
272 if (u) {
273 // Self-heals from a `tokens` session.start never managed to set: starts
274 // counting from this turn rather than staying stuck at nothing forever.
275 // A failed lookup must not block the write below, or the heal never happens.
276 const startedAt = (await read($, tokens))?.startedAt ?? (await $.session.usage().catch(() => null))?.startedAt ?? Date.now()
277 await update($, tokens, t => {
278 const base = t ?? { startedAt, isFull: false, ...ZERO }
279
280 return {
281 ...base,
282 read: base.read + u.input_tokens,
283 write: base.write + u.output_tokens,
284 cacheRead: base.cacheRead + u.cache_read_input_tokens,
285 cacheWrite: base.cacheWrite + u.cache_creation_input_tokens,
286 }
287 })
288 }
289 if (show.branch) {
290 await refreshBranch($)
291 }
292
293 return next(e)
294 })
295
296 // A git switch or checkout moves the branch mid-turn.
297 if (show.branch) {
298 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
299 const result = await next(e)
300 refreshBranch($).catch(() => {})
301
302 return result
303 })
304 }
305
306 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
307 if (e.props.hasSurvey || !Object.values(show).some(Boolean)) {
308 return next(e)
309 }
310
311 const list = sorted(await read($, limits))
312 const cost = await read($, costUsd)
313 const used = await read($, tokens)
314 const ctx = await read($, context)
315 const branchName = await read($, branch)
316 await read($, minute)
317 const now = await $.clock.now()
318 const { Box, Text } = $.ui.resolve(e)
319
320 const total = used ? used.read + used.write + used.cacheRead + used.cacheWrite : 0
321
322 if (list.length === 0 && cost === null && total === 0 && ctx === null && branchName === null) {
323 return (
324 <Box>
325 <Text dimColor>Usage: waiting for the first reply to report limits…</Text>
326 </Box>
327 )
328 }
329
330 const divider = (key: string) => (
331 <Box key={key} flexDirection="column" marginX={2}>
332 <Text color={BORDER}>│</Text>
333 <Text color={BORDER}>│</Text>
334 </Box>
335 )
336
337 const sections = (show.limits ? list : []).map(l => {
338 const left = Math.max(0, 100 - Math.round(l.percentUsed))
339 const name = label(l.kind)
340 const tone = color(l.percentUsed)
341 const { used, rest } = bar(l.percentUsed)
342 const reset = resetLabel(l.resetsAt, now, timeZone)
343
344 // Two rows: the bar, then the reset time under it, both left-aligned.
345 return (
346 <Box key={l.kind} flexDirection="column">
347 <Box key="bar">
348 <Text dimColor>{name} </Text>
349 <Text color={tone}>{used}</Text>
350 <Text color="#3a3a3a">
351 {rest}
352 </Text>
353 <Text color={tone} bold>
354 {' '}
355 {left}%
356 </Text>
357 <Text dimColor> left</Text>
358 </Box>
359 <Box key="reset">
360 <Text color="#777777">{reset}</Text>
361 </Box>
362 </Box>
363 )
364 })
365
366 if (used !== null && show.breakdown) {
367 // "Read/Write 8/3.2k" over "Cache R/W 3k/5k", the pairs right-aligned.
368 const [io, cache] = pad(
369 `${count(used.read)}/${count(used.write)}`,
370 `${count(used.cacheRead)}/${count(used.cacheWrite)}`,
371 )
372
373 sections.push(
374 <Box key="breakdown" flexDirection="column">
375 <Box key="io">
376 <Text dimColor>Read/Write </Text>
377 <Text bold>{io}</Text>
378 </Box>
379 <Box key="cache">
380 <Text dimColor>Cache R/W </Text>
381 <Text bold>{cache}</Text>
382 </Box>
383 </Box>,
384 )
385 }
386
387 if ((used !== null || cost !== null) && (show.tokens || show.cost)) {
388 // Pad the shown rows to one width so the numbers line up on the right.
389 const rows = [
390 ...(show.tokens ? [{ key: 'tokens', name: 'Tokens ', value: count(total) }] : []),
391 ...(show.cost ? [{ key: 'cost', name: 'Cost ', value: cost === null ? '—' : usd(cost) }] : []),
392 ]
393 const values = pad(...rows.map(r => r.value))
394
395 sections.push(
396 <Box key="totals" flexDirection="column">
397 {rows.map((r, i) => (
398 <Box key={r.key}>
399 <Text dimColor>{r.name}</Text>
400 <Text bold>{values[i]}</Text>
401 </Box>
402 ))}
403 </Box>,
404 )
405 }
406
407 const usageRow =
408 sections.length === 0 ? null : (
409 <Box key="usage" flexDirection="row" flexWrap="wrap">
410 {sections.flatMap((section, i) => (i === 0 ? [section] : [divider(`divider-${i}`), section]))}
411 </Box>
412 )
413
414 const branchRow =
415 branchName === null || !show.branch ? null : (
416 <Box key="branch">
417 <Text dimColor>Branch </Text>
418 <Text color={BORDER}>⎇ </Text>
419 <Text bold>{branchName}</Text>
420 </Box>
421 )
422
423 // One bordered box: the branch and context window on top, a rule, then the usage sections.
424 const contextRow = (() => {
425 if (ctx === null || !show.context) {
426 return null
427 }
428 const percent = ctx.percent ?? (ctx.tokens === undefined ? undefined : (ctx.tokens / ctx.window) * 100)
429 const { used: filled, rest } = bar(percent ?? 0)
430 const tone = color(percent ?? 0)
431
432 return (
433 <Box key="context" flexWrap="wrap">
434 <Text dimColor>Context </Text>
435 <Text color={tone}>{filled}</Text>
436 <Text color="#3a3a3a">{rest}</Text>
437 <Text color={tone} bold>
438 {' '}
439 {percent === undefined ? '—' : `${Math.round(percent)}%`}
440 </Text>
441 <Text dimColor> used </Text>
442 <Text bold>{ctx.tokens === undefined ? '—' : count(ctx.tokens)}</Text>
443 <Text dimColor>/{count(ctx.window)}</Text>
444 {ctx.top.length === 0 ? null : (
445 // Hungry frogs, eating what fills the context.
446 <Box key="top-divider" marginX={2}>
447 <Text>🐸🐸🐸</Text>
448 </Box>
449 )}
450 {ctx.top.map((c, i) => (
451 <Box key={`top-${c.name}`} marginLeft={i === 0 ? 0 : 3}>
452 <Text color={c.color}>■ </Text>
453 <Text color="#777777">{c.name} </Text>
454 <Text color="#aaaaaa">{count(c.tokens)}</Text>
455 </Box>
456 ))}
457 </Box>
458 )
459 })()
460
461 // The band's width less the border and padding on each side.
462 const ruleWidth = Math.max(1, e.props.bodyColumns - 4)
463
464 if (branchRow === null && contextRow === null && usageRow === null) {
465 return next(e)
466 }
467
468 return (
469 <Box flexDirection="column" borderStyle="round" borderColor={BORDER} paddingX={1}>
470 {branchRow}
471 {contextRow}
472 {(branchRow === null && contextRow === null) || usageRow === null ? null : (
473 <Text color={BORDER}>{'─'.repeat(ruleWidth)}</Text>
474 )}
475 {usageRow}
476 </Box>
477 )
478 })
479}
480types/index.d.ts 30 lines1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2
3/**
4 * Tokens summed over the whole conversation; `startedAt` is the session they
5 * belong to, `isFull` whether the transcript's earlier replies were counted in.
6 */
7export type Tokens = {
8 startedAt: number
9 isFull: boolean
10 read: number
11 write: number
12 cacheRead: number
13 cacheWrite: number
14}
15
16/** The live context window: its size, and its fill once a reply reported one. */
17export type Context = { window: number; tokens?: number; percent?: number; top: Category[] }
18
19/** One of the biggest rows /context lists (Messages, System tools, MCP tools...). */
20export type Category = { name: string; tokens: number; color: string }
21
22declare module 'claude-code' {
23 interface PluginState {
24 'cockpit': {
25 limits: Limit[]; costUsd: number | null; minute: number; tokens: Tokens | null
26 context: Context | null; branch: string | null
27 }
28 }
29}
30