Context window breakdown and plan usage, in the band above the prompt.

Two mods for Claude Code for people who run many sessions at once: one line above the prompt that tells you what this session is costing, and one pane beside the chat that tells you what every other session is doing.
<img src="docs/demo-light.gif" alt="A walkthrough: click the bar to see the context breakdown, click PRs to open the sessions pane, open a session, ask about it, ask about everything in flight, ask about the done ones while Claude is still replying, unfold them.">
Unofficial. Not affiliated with Anthropic.
context-card: one line above the prompt<img src="docs/card-light.png" alt="The context card with its breakdown open.">
| On the line | Meaning |
|---|---|
27% 272.3k / 1M | How full the context window is. Turns amber at 60%, red at 80%. |
● ◐ ○ | The prompt cache: fresh, past half its life, expired. Sending a message on an expired cache re-reads the whole context at full price. |
| The thin bar | The same percentage, colored by what is using it. |
weekly 20% ↻ 4d 21h | Your plan's weekly usage and when it resets, read live from your account. |
PRs | Opens the sessions pane. A number beside it counts sessions waiting on you. |
Click anywhere on the line to open the breakdown (messages, tools, MCP, skills, system, memory), the cache's minutes left, and where auto-compact will run. Click again to close it.
pr-pane: the sessions pane<img src="docs/sessions-light.png" alt="The sessions pane docked beside the chat.">
Every session in the same sidebar group, sorted by what it needs from you:
| Section | What is in it |
|---|---|
| Needs you | CI failing, conflicts, changes requested, ready to merge, or idle with nothing to show. |
| Working | Sessions running right now. |
| Done | Merged or closed. Folded until you click the heading; its Ask works either way. |
| Loose worktrees | Worktrees no session holds, and whether they have uncommitted changes. |
Each row has one time, on the right: how long it has been in the state its status names (working for 47m, merged 2h ago).
| Control | What it does |
|---|---|
| Click a session | Shows its worktree, branch, PR and activity. |
| Ask here | Asks, in the session you are in, for that session's status. Claude reads the other session's transcript and checks its PR; the other session is not messaged or interrupted. |
| Ask N working | The same, for every session that is running; with none running, Ask N open asks about every unfinished one. |
| Ask on the Done heading | Asks what the finished sessions changed, how they ended, and what they left to follow up. |
#45, PR ↗ | Opens the pull request on GitHub. |
↻ | Refreshes now. The pane also refreshes itself every 15 seconds. |
| A section heading | Folds or unfolds the section. |
An Ask pressed while Claude is still replying in your session waits on a line under the header, After this turn: ask about …, with Cancel, and is sent when the reply ends. One waits at a time: pressing Ask again replaces it.
Outside any project, the pane shows every project's sessions as one overview.
Both mods together, from this repository:
/plugin marketplace add Nongfsq/frank-claude-cockpit
/plugin install context-card@frank-claude-cockpit
/plugin install pr-pane@frank-claude-cockpit
Or copy the two folders into ~/.claude/skills/ and start a new session:
git clone https://github.com/Nongfsq/frank-claude-cockpit
cp -R frank-claude-cockpit/context-card frank-claude-cockpit/pr-pane ~/.claude/skills/
Install both: the PRs button lives in context-card and appears only when pr-pane is present.
ui.render, $.state); they were built and tested on 2.1.286.context-card's weekly usage needs a Claude subscription login. With an API key the card still shows context, without the weekly figure.pr-pane needs the Claude desktop app, which is where the session list comes from; in a plain terminal it says the list is unavailable. PR and CI state come from the gh CLI, logged in.context-card asks api.anthropic.com for your own plan usage with the login Claude Code already holds, at most once every two minutes however many sessions are open: one session asks and the rest read its answer from ~/.claude/cache/context-card-usage.json. That request uses no tokens.pr-pane runs git and gh locally, in the project's folder.Nothing else is sent anywhere.
claude plugin validate context-card
claude plugin test context-card
claude plugin test pr-pane
Types for an editor: run /plugin-types inside a mod's folder.
The demo above is a scripted page, docs/demo/index.html; open it in a browser to watch it loop, or add ?theme=light. To re-record it, both themes, as GIF and MP4, with the sessions screenshot cropped from the last frame:
cd docs/demo && npm i puppeteer-core
for theme in dark light; do
rm -rf frames && node record.mjs frames $theme 15
ffmpeg -y -framerate 15 -i frames/f%04d.png -vf "scale=1200:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=128:stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle" ../demo-$theme.gif
ffmpeg -y -framerate 15 -i frames/f%04d.png -vf "scale=1800:-2:flags=lanczos" -c:v libx264 -pix_fmt yuv420p -crf 23 -movflags +faststart ../demo-$theme.mp4
ffmpeg -y -i frames/$(ls frames | tail -1) -vf "crop=2280:1240:60:36" ../sessions-$theme.png
done
rm -rf frames
If this project is useful to you, you can buy me a coffee.
<a href="https://buymeacoffee.com/frankmenger"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee" height="44"></a>
hooks/register.tsx 570 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit } from 'claude-code'
3
4import type { Card, Limit, Slice } from '../types'
5
6const card = atom({ plugin: 'context-card', key: 'card' } as const, null)
7// Sessions that need the user, as the sessions pane counts them.
8const attention = atom({ plugin: 'pr-pane', key: 'attention' } as const, 0)
9
10// Presses of the PRs button. The sessions pane hooks this write and toggles itself, which works mid-turn,
11// where running its command would wait for the turn to end.
12const paneAsk = atom({ plugin: 'context-card', key: 'paneAsk' } as const, 0)
13
14const LINE_CELLS = 14
15// Whether the breakdown is open: a click on the line toggles it.
16const isOpen = atom({ plugin: 'context-card', key: 'isOpen' } as const, false)
17
18const LOCAL_MS = 15_000
19const HOUR = 3_600_000
20
21const FIVE_MINUTES = 300_000
22const TAIL_BYTES = 400_000
23
24// The prompt cache: when the last response came back, and how long the cache lives. An hour until the
25// session's own record says otherwise: five minutes with an API key or once usage credits are being drawn.
26const cache = atom({ plugin: 'context-card', key: 'cache' } as const, { lastReplyAt: 0, ttlMs: HOUR })
27
28const markReply = async ($: EngineInterface) => {
29 const now = await $.clock.now()
30 await update($, cache, was => ({ ...was, lastReplyAt: now }))
31}
32
33// Each response is recorded with what it wrote to the cache at each lifetime; the newest one that wrote any
34// tells which lifetime this session's cache has. Null when the end of the record names neither.
35const writtenTtl = (tail: string) => {
36 for (const line of tail.split('\n').reverse()) {
37 try {
38 const wrote = (JSON.parse(line) as { message?: { usage?: { cache_creation?: Record<string, unknown> } } }).message?.usage
39 ?.cache_creation
40
41 if (Number(wrote?.ephemeral_1h_input_tokens) > 0) {
42 return HOUR
43 }
44
45 if (Number(wrote?.ephemeral_5m_input_tokens) > 0) {
46 return FIVE_MINUTES
47 }
48 } catch {
49 // The first line is cut where the tail starts, and not every line is a response.
50 }
51 }
52
53 return null
54}
55
56const measureTtl = async ($: EngineInterface, transcriptPath: string) => {
57 if (transcriptPath === '') {
58 return
59 }
60
61 const tail = await $.process.run(['tail', '-c', String(TAIL_BYTES), transcriptPath]).catch(() => null)
62 const ttlMs = tail === null || tail.exitCode !== 0 ? null : writtenTtl(tail.stdout)
63
64 if (ttlMs !== null) {
65 await update($, cache, was => ({ ...was, ttlMs }))
66 }
67}
68
69// Full while the cache is fresh, half once most of its life is gone, an empty ring once it has expired. Only
70// these three: the quarter pies come from another font on desktop, smaller and off the line's centre.
71const cacheGlyph = (left: number, ttl: number) => (left <= 0 ? '○' : left > ttl * 0.5 ? '●' : '◐')
72
73const minutesLeft = (left: number) => (left >= 60_000 ? `${Math.ceil(left / 60_000)}m` : `${Math.max(1, Math.ceil(left / 1000))}s`)
74
75// Opening the breakdown also refreshes it, so what opens is current; neither call spends tokens.
76const toggleOpen = async ($: EngineInterface) => {
77 const opening = !(await read($, isOpen))
78 await update($, isOpen, () => opening)
79
80 if (opening) {
81 await Promise.all([refresh($), poll($).catch(() => {})])
82 }
83}
84
85// Labels per /context row, matched on a lowercase fragment of its name. Colors come from the row itself:
86// /context's own theme keys, so the bar matches /context and follows the light and dark themes.
87const ROWS: { match: string; label: string }[] = [
88 { match: 'system prompt', label: 'system' },
89 { match: 'mcp', label: 'mcp' },
90 { match: 'tool', label: 'tools' },
91 { match: 'agent', label: 'agents' },
92 { match: 'memory', label: 'memory' },
93 { match: 'skill', label: 'skills' },
94 { match: 'message', label: 'messages' },
95 { match: 'slash', label: 'commands' },
96]
97
98const LIMIT_LABELS: Record<string, string> = { seven_day: 'weekly', five_hour: '5h', spend_limit: 'spend' }
99const LIMIT_ORDER = ['seven_day']
100
101const compact = (tokens: number) => {
102 if (tokens < 1000) {
103 return String(tokens)
104 }
105
106 const [value, unit] = tokens < 999_950 ? [tokens / 1000, 'k'] : [tokens / 1_000_000, 'M']
107
108 return `${value.toFixed(1).replace(/\.0$/, '')}${unit}`
109}
110
111// Each figure has its own theme hue, so the two percentages never read alike; near a cap the hue gives way to
112// warning or error. Theme keys resolve per theme: claude is terracotta and suggestion is blue in light, dark and
113// ANSI themes alike, each legible on its background.
114const fillColor = (percent: number) => (percent >= 80 ? 'error' : percent >= 60 ? 'warning' : 'claude')
115const limitColor = (percent: number) => (percent >= 90 ? 'error' : percent >= 75 ? 'warning' : 'suggestion')
116
117const resetsIn = (resetsAt: string | undefined, now: number) => {
118 if (resetsAt === undefined) {
119 return ''
120 }
121
122 const minutes = Math.max(0, Math.round((Date.parse(resetsAt) - now) / 60_000))
123
124 if (minutes >= 1440) {
125 return `${Math.floor(minutes / 1440)}d ${Math.floor((minutes % 1440) / 60)}h`
126 }
127
128 return minutes >= 60 ? `${Math.floor(minutes / 60)}h ${minutes % 60}m` : `${minutes}m`
129}
130
131const age = (ms: number) => {
132 const minutes = Math.max(1, Math.round(ms / 60_000))
133
134 return minutes >= 1440 ? `${Math.floor(minutes / 1440)}d` : minutes >= 60 ? `${Math.floor(minutes / 60)}h` : `${minutes}m`
135}
136
137const toLimits = (limits: SessionRateLimit[]): Limit[] =>
138 limits
139 .filter(({ kind }) => LIMIT_ORDER.includes(kind))
140 .map(({ kind, percentUsed, resetsAt }) => ({ kind, percentUsed, resetsAt }))
141 .sort((a, b) => LIMIT_ORDER.indexOf(a.kind) - LIMIT_ORDER.indexOf(b.kind))
142
143const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
144const POLL_MS = 60_000
145
146// The newest weekly reading any session has, kept in one file every session reads, so they all show the same
147// figure. A reading comes from a session's own API responses, free, or failing those from asking the account, once
148// for all sessions. `status` is the refusal since the account last answered, if any.
149type Shared = { at: number; triedAt: number; retryAt: number; status: number | null; limits: Limit[] }
150
151// The account is asked only when no session has brought a reading for this long: weekly moves slowly.
152const SHARE_MS = 600_000
153const BACKOFF_MS = 300_000
154const CLAIM_MS = 20_000
155// Past this the account-wide figure gives way to the session's own reading, and is drawn dim if nothing newer exists.
156const STALE_MS = 900_000
157
158const EMPTY: Shared = { at: 0, triedAt: 0, retryAt: 0, status: null, limits: [] }
159
160// The last shared file this session read or wrote.
161let lastShared: Shared = EMPTY
162
163const pickLimits = () => ({ limits: lastShared.limits, limitsAt: lastShared.at, refusedStatus: lastShared.status })
164
165const showLimits = async ($: EngineInterface) => {
166 await update($, card, was => (was === null ? was : { ...was, ...pickLimits() }))
167}
168
169const sharedPath = async ($: EngineInterface) => {
170 const home = await $.env.get('HOME').catch(() => undefined)
171
172 return typeof home === 'string' && home !== '' ? `${home}/.claude/cache/context-card-usage.json` : null
173}
174
175const readShared = async ($: EngineInterface, path: string | null): Promise<Shared | null> => {
176 if (path === null) {
177 return null
178 }
179
180 try {
181 const found = JSON.parse(await $.fs.read(path)) as Partial<Shared>
182
183 return {
184 at: Number(found.at) || 0,
185 triedAt: Number(found.triedAt) || 0,
186 retryAt: Number(found.retryAt) || 0,
187 status: typeof found.status === 'number' ? found.status : null,
188 limits: Array.isArray(found.limits) ? found.limits : [],
189 }
190 } catch {
191 return null
192 }
193}
194
195const writeShared = async ($: EngineInterface, path: string | null, value: Shared) => {
196 lastShared = value
197
198 if (path !== null) {
199 await $.fs.write(path, JSON.stringify(value)).catch(() => undefined)
200 }
201}
202
203// How long a refusal asks to be left alone: Retry-After in seconds or as a date, never less than the backoff.
204const waitFor = (retryAfter: string | undefined, now: number) => {
205 const seconds = Number(retryAfter)
206 const asked = Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - now
207
208 return Math.max(BACKOFF_MS, Number.isFinite(asked) ? asked : 0)
209}
210
211// Account-wide plan usage, as the app's usage card reads it; covers every session, not just this one.
212// Each session calls this on its own timer, but only one of them sends the request: the rest read its result.
213const poll = async ($: EngineInterface) => {
214 const path = await sharedPath($)
215 const now = await $.clock.now()
216 const shared = (await readShared($, path)) ?? lastShared
217
218 lastShared = shared
219 await showLimits($)
220
221 // Fresh enough, told to wait after a refusal, or another session is asking right now.
222 if (now - shared.at < SHARE_MS || now < shared.retryAt || now - shared.triedAt < CLAIM_MS) {
223 return
224 }
225
226 const auth = await $.session.authorize()
227
228 if (auth === null) {
229 return
230 }
231
232 await writeShared($, path, { ...shared, triedAt: now })
233 const response = await $.http.fetch(USAGE_URL, {
234 headers: { 'anthropic-beta': 'oauth-2025-04-20' },
235 auth: auth.handle,
236 })
237
238 if (!response.ok) {
239 // Refused (rate limited, usually): every session waits as long as it was asked before any of them asks again.
240 // Read again first, so a reading another session wrote while this one waited is kept.
241 await writeShared($, path, {
242 ...((await readShared($, path)) ?? shared),
243 triedAt: now,
244 retryAt: now + waitFor(response.headers?.['retry-after'], now),
245 status: response.status,
246 })
247 await showLimits($)
248
249 return
250 }
251
252 const body = JSON.parse(response.text) as Record<string, { utilization?: unknown; resets_at?: unknown } | null>
253 const limits: Limit[] = LIMIT_ORDER.flatMap(kind => {
254 const window = body[kind]
255
256 return window && typeof window.utilization === 'number'
257 ? [{ kind, percentUsed: window.utilization, resetsAt: typeof window.resets_at === 'string' ? window.resets_at : undefined }]
258 : []
259 })
260
261 if (limits.length === 0) {
262 return
263 }
264
265 await writeShared($, path, { at: now, triedAt: now, retryAt: 0, status: null, limits })
266 await showLimits($)
267}
268
269// Puts the windows a response just reported into the shared file, for every session to show. Only one that just
270// came back: a session's first look holds whatever its last response said, which a resumed session may have had
271// for a day, and stamping that as now would pass it off as fresh.
272const shareHeaders = async ($: EngineInterface, rateLimits: SessionRateLimit[]) => {
273 const limits = toLimits(rateLimits)
274
275 if (limits.length === 0) {
276 return
277 }
278
279 const path = await sharedPath($)
280 const now = await $.clock.now()
281 const shared = (await readShared($, path)) ?? lastShared
282
283 await writeShared($, path, { ...shared, at: now, limits })
284}
285
286const refresh = async ($: EngineInterface, afterReply = false) => {
287 const { context, rateLimits } = await $.session.usage({ breakdown: 'summary' })
288 const breakdown = context.breakdown
289
290 if (afterReply) {
291 await shareHeaders($, rateLimits)
292 }
293
294 if (breakdown === undefined) {
295 return
296 }
297
298 const window = breakdown.rawMaxTokens
299
300 const slices: Slice[] = breakdown.categories
301 .filter(row => row.kind === 'used' || row.kind === 'free')
302 .filter(row => row.tokens > 0)
303 .map(row => {
304 const isFree = row.kind === 'free'
305 const known = ROWS.find(r => row.name.toLowerCase().includes(r.match))
306
307 return {
308 name: isFree ? 'free' : (known?.label ?? row.name.toLowerCase()),
309 tokens: row.tokens,
310 percent: Math.round((row.tokens / window) * 100),
311 color: row.color,
312 isFree,
313 }
314 })
315 // Categories that share a label (loaded and deferred MCP tools) are one row.
316 .reduce<Slice[]>((merged, slice) => {
317 const same = merged.find(one => one.name === slice.name)
318
319 if (same === undefined) {
320 return [...merged, slice]
321 }
322
323 const tokens = same.tokens + slice.tokens
324
325 return merged.map(one => (one === same ? { ...one, tokens, percent: Math.round((tokens / window) * 100) } : one))
326 }, [])
327
328 const tokens = context.tokens ?? breakdown.totalTokens
329
330 await update($, card, () => ({
331 tokens,
332 window: context.window,
333 percent: context.percent ?? breakdown.percentage,
334 compactsAt: breakdown.isAutoCompactEnabled ? (breakdown.autoCompactThreshold ?? null) : null,
335 slices,
336 ...pickLimits(),
337 }))
338}
339
340export const register: Register = on => {
341 let ticker: { cancel: () => void } | null = null
342 let localTicker: { cancel: () => void } | null = null
343
344 on('session.start', async ($, e, next) => {
345 await refresh($)
346 await poll($).catch(() => {})
347 ticker?.cancel()
348 ticker = $.clock.every(POLL_MS, () => poll($).catch(() => {}))
349 // The breakdown is a local estimate: refreshing it sends no request.
350 localTicker?.cancel()
351 localTicker = $.clock.every(LOCAL_MS, () => void refresh($))
352
353 return next(e)
354 })
355
356 on('session.end', ($, e, next) => {
357 ticker?.cancel()
358 localTicker?.cancel()
359 ticker = null
360 localTicker = null
361
362 return next(e)
363 })
364
365 on('turn.complete', async ($, e, next) => {
366 if (e.agentId === undefined) {
367 await markReply($)
368 await refresh($, true)
369 await poll($).catch(() => {})
370 }
371
372 return next(e)
373 })
374
375 // A resumed session's record already says which lifetime it has; after that, each finished turn's does.
376 on('classic.SessionStart', async ($, e, next) => {
377 await measureTtl($, e.transcript_path)
378
379 return next(e)
380 })
381
382 on('classic.Stop', async ($, e, next) => {
383 await measureTtl($, e.transcript_path)
384
385 return next(e)
386 })
387
388 on('session.compact', async ($, e, next) => {
389 const result = await next(e)
390 await refresh($)
391
392 return result
393 })
394
395 on('session.measure', async ($, e, next) => {
396 // The fill moves mid-turn: follow it at once, keeping the last breakdown until the next refresh.
397 const { tokens, window } = e.context
398
399 if (e.changed.includes('context') && tokens !== undefined) {
400 await markReply($)
401 const percent = e.context.percent ?? Math.round((tokens / window) * 100)
402 await update($, card, was => (was === null ? was : { ...was, tokens, window, percent }))
403 }
404
405 if (e.changed.includes('rateLimits')) {
406 await shareHeaders($, e.rateLimits)
407 await showLimits($)
408 }
409
410 return next(e)
411 })
412
413 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
414 const now = await read($, card)
415
416 if (e.props.hasSurvey || now === null) {
417 return next(e)
418 }
419
420 const { Box, Button, Text } = $.ui.resolve(e)
421 const clock = await $.clock.now()
422 const open = await read($, isOpen)
423 const isDesktop = e.surface === 'desktop'
424 const isNarrow = (e.props.bodyColumns ?? 100) < 64
425 const weekly = now.limits.find(limit => limit.kind === 'seven_day')
426 // Nothing newer has come in for a while: the figure is drawn dim, and the breakdown says how old it is and why.
427 const isWeeklyStale = now.limitsAt > 0 && clock - now.limitsAt > STALE_MS
428 const used = now.slices.filter(slice => !slice.isFree).sort((a, b) => b.tokens - a.tokens)
429 // Checked while drawing, so the button appears whichever mod finished loading first.
430 const hasSessions = (await $.command.list().catch(() => [])).some(command => command.name === 'sessions')
431 const waiting = hasSessions ? await read($, attention) : 0
432 const pctColor = fillColor(now.percent)
433 const cached = await read($, cache)
434 const cacheLeft = cached.lastReplyAt === 0 ? null : cached.ttlMs - (clock - cached.lastReplyAt)
435
436 // The line's bar in whole cells: each category its share of the filled cells, the rest dim.
437 const filled = Math.min(LINE_CELLS, Math.round((now.percent / 100) * LINE_CELLS))
438 const cells = used.map(slice => ({ slice, n: Math.round((slice.tokens / Math.max(now.tokens, 1)) * filled) }))
439 const drawn = cells.reduce((sum, cell) => sum + cell.n, 0)
440
441 const breakdown = (
442 <Box flexDirection="column" rowGap={1} paddingX={2} paddingY={1} marginBottom={1} borderStyle="round" borderDimColor>
443 <Box flexDirection="row" justifyContent="space-between" columnGap={2}>
444 <Text>
445 <Text bold color={pctColor}>{`${now.percent}%`}</Text>
446 <Text dimColor> of the context window</Text>
447 </Text>
448 <Box flexDirection="row" columnGap={2}>
449 {cacheLeft === null ? null : cacheLeft > 0 ? (
450 <Text dimColor>{`${cacheGlyph(cacheLeft, cached.ttlMs)} ${minutesLeft(cacheLeft)}`}</Text>
451 ) : (
452 <Text color="warning">○ cache cold</Text>
453 )}
454 {now.compactsAt === null ? null : <Text dimColor>{`auto-compact at ${compact(now.compactsAt)}`}</Text>}
455 </Box>
456 </Box>
457 {weekly !== undefined && isWeeklyStale ? (
458 <Text dimColor>
459 {`weekly ${Math.round(weekly.percentUsed)}% was read ${age(clock - now.limitsAt)} ago`}
460 {now.refusedStatus === null ? '' : ` · the usage request is refused (${now.refusedStatus})`}
461 </Text>
462 ) : null}
463 <Box flexDirection="row" overflow="hidden">
464 {used.map(slice => (
465 <Box key={`bar-${slice.name}`} width={`${Math.max(slice.percent, 1)}%`} flexShrink={0} overflow="hidden">
466 {/* Wider than any bar, so the parent clips it and no ellipsis is drawn at the cut. */}
467 <Box width={900} flexShrink={0}>
468 <Text color={slice.color}>{'━'.repeat(300)}</Text>
469 </Box>
470 </Box>
471 ))}
472 <Box key="bar-free" flexGrow={1} flexShrink={1} overflow="hidden">
473 <Box width={900} flexShrink={0}>
474 <Text dimColor>{'─'.repeat(300)}</Text>
475 </Box>
476 </Box>
477 </Box>
478 <Box flexDirection="row" flexWrap="wrap">
479 {used.map(slice => (
480 <Box key={`row-${slice.name}`} width={isNarrow ? '50%' : '33%'} paddingRight={3}>
481 <Box flexDirection="row" justifyContent="space-between" flexGrow={1}>
482 <Text wrap="truncate-end">
483 <Text color={slice.color}>● </Text>
484 <Text dimColor>{slice.name}</Text>
485 </Text>
486 <Text>{compact(slice.tokens)}</Text>
487 </Box>
488 </Box>
489 ))}
490 </Box>
491 </Box>
492 )
493
494 return (
495 <Box flexDirection="column">
496 {open ? breakdown : null}
497 <Box flexDirection="row" alignItems="center" columnGap={2}>
498 <Box key="line" flexDirection="row" alignItems="center" columnGap={2} flexGrow={1} position="relative">
499 {isDesktop ? (
500 <Text bold color={pctColor}>{`${now.percent}%`}</Text>
501 ) : (
502 <Button key="toggle" plain label={`${now.percent}%`} onPress={() => void toggleOpen($)} />
503 )}
504 {isNarrow ? null : (
505 <Text dimColor hover={{ dimColor: false }}>
506 {`${compact(now.tokens)} / ${compact(now.window)}`}
507 </Text>
508 )}
509 {cacheLeft === null ? null : cacheLeft > 0 ? (
510 <Text dimColor>{cacheGlyph(cacheLeft, cached.ttlMs)}</Text>
511 ) : (
512 <Text color="warning">○</Text>
513 )}
514 <Text wrap="truncate">
515 {cells.map(cell => (
516 <Text key={`cell-${cell.slice.name}`} color={cell.slice.color}>
517 {'━'.repeat(cell.n)}
518 </Text>
519 ))}
520 <Text dimColor hover={{ dimColor: false }}>
521 {'─'.repeat(Math.max(0, LINE_CELLS - drawn))}
522 </Text>
523 </Text>
524 {now.percent >= 60 && now.compactsAt !== null ? (
525 <Text color={pctColor}>{`compacts at ${compact(now.compactsAt)}`}</Text>
526 ) : null}
527 <Box flexGrow={1} />
528 {weekly === undefined ? null : (
529 <Box flexDirection="row" columnGap={1} flexShrink={0}>
530 {isNarrow ? null : <Text dimColor>weekly</Text>}
531 {isWeeklyStale ? (
532 <Text dimColor>{`${Math.round(weekly.percentUsed)}%`}</Text>
533 ) : (
534 <Text bold color={limitColor(weekly.percentUsed)}>{`${Math.round(weekly.percentUsed)}%`}</Text>
535 )}
536 {weekly.resetsAt === undefined ? null : <Text dimColor>{`↻ ${resetsIn(weekly.resetsAt, clock)}`}</Text>}
537 </Box>
538 )}
539 {/* Desktop: a label-less control laid over the whole line, so a click anywhere on it toggles the breakdown. */}
540 {isDesktop ? (
541 <Box position="absolute" top={0} left={0} right={0} bottom={0} overflow="hidden">
542 {/* The control is wider than any line, so the overlay clips it and its label is never cut with an ellipsis. */}
543 <Box width={1200} flexShrink={0}>
544 <Button
545 key="toggle"
546 plain
547 label={'\u00A0'.repeat(600)}
548 hover={{ backgroundColor: '#00000000' }}
549 onPress={() => void toggleOpen($)}
550 />
551 </Box>
552 </Box>
553 ) : null}
554 </Box>
555 {hasSessions ? (
556 <Box flexDirection="row" columnGap={1} flexShrink={0}>
557 <Button key="sessions" label="PRs" onPress={() => void update($, paneAsk, count => count + 1)} />
558 {waiting > 0 ? (
559 <Text bold color="warning">
560 {waiting}
561 </Text>
562 ) : null}
563 </Box>
564 ) : null}
565 </Box>
566 </Box>
567 )
568 })
569}
570types/index.d.ts 40 lines1export type Slice = {
2 /** Row label as /context prints it. */
3 name: string
4 tokens: number
5 /** 0 to 100, against the measured window. */
6 percent: number
7 color: string
8 isFree: boolean
9}
10
11export type Limit = {
12 /** `five_hour`, `seven_day`, or a gateway's `spend_limit`. */
13 kind: string
14 percentUsed: number
15 resetsAt?: string
16}
17
18export type Card = {
19 /** Tokens in use. */
20 tokens: number
21 /** The window measured against. */
22 window: number
23 percent: number
24 /** Token count where auto-compaction runs; null when off. */
25 compactsAt: number | null
26 slices: Slice[]
27 limits: Limit[]
28 /** When `limits` was read, epoch ms; 0 when unknown. */
29 limitsAt: number
30 /** The status the account's usage endpoint last refused with, until it answers again; null when it has not. */
31 refusedStatus: number | null
32}
33
34declare module 'claude-code' {
35 interface PluginState {
36 'context-card': { card: Card | null; isOpen: boolean; cache: { lastReplyAt: number; ttlMs: number }; paneAsk: number }
37 'pr-pane': { attention: number }
38 }
39}
40