Draws the context window as a stacked bar above the prompt, one color per /context category; toggle with /context-bar

A Claude Code mod that draws your context window as a stacked bar above the prompt, one colour per /context category, so you can see usage without running /context.

◆ context 212k of 1M · compacts at 950k 21% · 5h 5% ↻ 19:39 · week 37% ↻ Sat 14:59 $0.92
████▉███████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│░░▒▒▒
▌ system prompt 3.4k 0.3% ▌ messages 186k 19% ▌ skills 2.2k 0.2%
/context's theme colours░ free space, ▒ autocompact buffer, │ where auto-compaction kicks in5h and week: how much of your plan's current 5-hour session and weekly limit you have used, the same two figures /usage shows, each followed by ↻ and the local time it resets (the weekly one with its day). Each percentage turns yellow at 50% and red at 80%. Claude Code reports them after the first response of the session, and only when the account has these limits; until then, or when it doesn't report one, it shows ?/cost totals it, at the far right. Claude Code only reports cost in US dollars, so it is always shown in $It refreshes at session start, after each tool call, after each turn and after compaction, using the local summary estimate (no token-count API requests), so figures can differ slightly from /context.
In a Claude Code terminal session:
/plugin install context-bar --marketplace fredrikbonde/claude-context-bar
Answer y to add the marketplace, then pick the user scope. The bar shows straight away and in every session after.
Mods are an early-access Claude Code feature; this was built on Claude Code 2.1.294.
/context-bar hides or shows the bar for the current session.
The [-] at the right of the header is Claude Code's own control for hiding the bar; the plugin doesn't draw it.
claude plugin update context-bar
then /reload-plugins in a running session.
claude plugin validate .
claude plugin test .hooks/register.tsx 279 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit } from 'claude-code'
3
4import type { ContextBarCategory, ContextBarSnapshot, UsageWindow } from '../types'
5
6const COMMAND = 'context-bar'
7const isShown = atom({ plugin: 'context-bar', key: 'isShown' } as const, true)
8const snapshot = atom({ plugin: 'context-bar', key: 'snapshot' } as const, null)
9
10const CELL_CHAR: Record<ContextBarCategory['kind'], string> = {
11 used: '█',
12 free: '░',
13 buffer: '▒',
14}
15
16// 'summary' estimates locally; 'full' would send a token-count request per tool and memory file on every refresh.
17async function refresh($: EngineInterface): Promise<void> {
18 const { context, cost, rateLimits } = await $.session.usage({ breakdown: 'summary' })
19 const breakdown = context.breakdown
20 if (!breakdown) {
21 return
22 }
23
24 const categories: ContextBarCategory[] = []
25 for (const c of breakdown.categories) {
26 if (c.kind !== 'deferred') {
27 categories.push({ name: c.name, tokens: c.tokens, color: c.color, kind: c.kind })
28 }
29 }
30
31 const next: ContextBarSnapshot = {
32 categories,
33 totalTokens: breakdown.totalTokens,
34 maxTokens: breakdown.rawMaxTokens,
35 percentage: breakdown.percentage,
36 autoCompactThreshold:
37 breakdown.isAutoCompactEnabled && breakdown.autoCompactThreshold !== undefined
38 ? breakdown.autoCompactThreshold
39 : null,
40 costUsd: cost?.usd ?? null,
41 fiveHour: usageWindow($, rateLimits, 'five_hour'),
42 week: usageWindow($, rateLimits, 'seven_day'),
43 }
44 await update($, snapshot, () => next)
45}
46
47function usageWindow($: EngineInterface, limits: SessionRateLimit[], kind: string): UsageWindow | null {
48 const limit = limits.find(l => l.kind === kind)
49 if (!limit) {
50 return null
51 }
52 if (limit.resetsAt === undefined) {
53 return { percentUsed: limit.percentUsed, resetsAt: null }
54 }
55 const resetsAt = Date.parse(limit.resetsAt)
56 if (Number.isNaN(resetsAt)) {
57 $.ui.log(`context-bar: ${kind} resetsAt is not a timestamp: ${limit.resetsAt}`)
58 return { percentUsed: limit.percentUsed, resetsAt: null }
59 }
60 return { percentUsed: limit.percentUsed, resetsAt }
61}
62
63// Background refreshes run after the engine's own work: a failed measurement must not fail the tool call, turn or
64// compaction it rides on, so it is reported in the transcript and the band keeps its last reading.
65async function refreshAfter($: EngineInterface, where: string): Promise<void> {
66 try {
67 await refresh($)
68 } catch (error) {
69 $.ui.log(`context-bar: refresh after ${where} failed: ${error instanceof Error ? error.message : String(error)}`)
70 }
71}
72
73export function formatTokens(tokens: number): string {
74 if (tokens >= 1_000_000) {
75 return `${trimZero((tokens / 1_000_000).toFixed(1))}M`
76 }
77 if (tokens >= 10_000) {
78 return `${Math.round(tokens / 1000)}k`
79 }
80 if (tokens >= 1000) {
81 return `${trimZero((tokens / 1000).toFixed(1))}k`
82 }
83 return `${tokens}`
84}
85
86// The engine's cost ledger is in US dollars only; there is no account currency to convert to.
87export function formatCost(usd: number): string {
88 return `$${usd.toFixed(2)}`
89}
90
91const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
92
93// Local wall-clock time rather than a countdown: the band only redraws on refresh, so "in 2h13m" would go stale
94// while the session sits idle, and a clock time stays true.
95export function formatReset(resetsAt: number, withWeekday: boolean): string {
96 const at = new Date(resetsAt)
97 const time = `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`
98 return withWeekday ? `${WEEKDAYS[at.getDay()]} ${time}` : time
99}
100
101function trimZero(text: string): string {
102 return text.endsWith('.0') ? text.slice(0, -2) : text
103}
104
105function formatShare(tokens: number, max: number): string {
106 const share = (tokens / max) * 100
107 return share < 1 ? `${share.toFixed(1)}%` : `${Math.round(share)}%`
108}
109
110export type BarRun = { color: string; text: string }
111
112// Largest-remainder rounding so the runs fill exactly `width` cells, and any non-empty category keeps at least one.
113export function layoutBar(s: ContextBarSnapshot, width: number): BarRun[] {
114 const visible = s.categories.filter(c => c.tokens > 0)
115 const exact = visible.map(c => (c.tokens / s.maxTokens) * width)
116 const cells = exact.map(x => Math.max(1, Math.floor(x)))
117 let spare = width - cells.reduce((a, b) => a + b, 0)
118 const order = exact
119 .map((x, i) => ({ i, rest: x - Math.floor(x) }))
120 .sort((a, b) => b.rest - a.rest)
121 for (let k = 0; spare > 0 && order.length > 0; k = (k + 1) % order.length) {
122 cells[order[k]!.i]! += 1
123 spare -= 1
124 }
125 // Over the window, or many 1-cell minimums: take the excess from the widest runs.
126 while (spare < 0) {
127 const widest = cells.indexOf(Math.max(...cells))
128 cells[widest]! -= 1
129 spare += 1
130 }
131
132 const glyphs: { color: string; char: string }[] = []
133 visible.forEach((c, i) => {
134 for (let n = 0; n < cells[i]!; n++) {
135 glyphs.push({ color: c.color, char: CELL_CHAR[c.kind] })
136 }
137 })
138
139 if (s.autoCompactThreshold !== null && s.autoCompactThreshold < s.maxTokens) {
140 const at = Math.min(width - 1, Math.floor((s.autoCompactThreshold / s.maxTokens) * width))
141 if (glyphs[at]) {
142 glyphs[at] = { color: 'warning', char: '│' }
143 }
144 }
145
146 const runs: BarRun[] = []
147 for (const g of glyphs) {
148 const last = runs[runs.length - 1]
149 if (last && last.color === g.color) {
150 last.text += g.char
151 } else {
152 runs.push({ color: g.color, text: g.char })
153 }
154 }
155 return runs
156}
157
158function percentColor(percentage: number): string {
159 if (percentage >= 80) return 'error'
160 if (percentage >= 50) return 'warning'
161 return 'success'
162}
163
164export const register: Register = on => {
165 on('session.start', async ($, e, next) => {
166 await $.command.register({
167 name: COMMAND,
168 description: 'Toggle the context window bar above the prompt',
169 })
170 const result = await next(e)
171 await refreshAfter($, 'session start')
172
173 return result
174 })
175
176 on('command.run', { command: COMMAND }, async $ => {
177 const shown = !(await read($, isShown))
178 await update($, isShown, () => shown)
179 if (shown) {
180 await refresh($)
181 }
182
183 return { text: shown ? 'Context bar shown.' : 'Context bar hidden.' }
184 })
185
186 on('tool.call', async ($, e, next) => {
187 const result = await next(e)
188 if (await read($, isShown)) {
189 await refreshAfter($, e.tool)
190 }
191
192 return result
193 })
194
195 on('turn.complete', async ($, e, next) => {
196 const result = await next(e)
197 await refreshAfter($, 'turn')
198
199 return result
200 })
201
202 on('session.compact', async ($, e, next) => {
203 const result = await next(e)
204 await refreshAfter($, 'compaction')
205
206 return result
207 })
208
209 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
210 if (e.props.hasSurvey || !(await read($, isShown))) {
211 return next(e)
212 }
213
214 const { Box, Text } = $.ui.resolve(e)
215 const s = await read($, snapshot)
216 if (s === null) {
217 return <Text dimColor>◆ context · measuring…</Text>
218 }
219
220 const width = Math.max(10, e.props.bodyColumns)
221 const runs = layoutBar(s, width)
222 const legend = s.categories.filter(c => c.kind === 'used' && c.tokens > 0)
223
224 return (
225 <Box flexDirection="column" width={width}>
226 <Box justifyContent="space-between">
227 <Text color="claude">◆ context</Text>
228 <Text>
229 <Text bold>{formatTokens(s.totalTokens)}</Text>
230 <Text dimColor> of {formatTokens(s.maxTokens)}</Text>
231 {s.autoCompactThreshold !== null && (
232 <Text dimColor> · compacts at {formatTokens(s.autoCompactThreshold)}</Text>
233 )}{' '}
234 <Text inverse color={percentColor(s.percentage)}>
235 {' '}
236 {Math.round(s.percentage)}%{' '}
237 </Text>
238 {/* Always drawn, so a session without limits reads as "not reported" rather than as an older version. */}
239 <Text>
240 <Text dimColor> · 5h </Text>
241 {s.fiveHour === null && <Text dimColor>?</Text>}
242 {s.fiveHour !== null && (
243 <Text color={percentColor(s.fiveHour.percentUsed)}>{`${Math.round(s.fiveHour.percentUsed)}%`}</Text>
244 )}
245 {s.fiveHour !== null && s.fiveHour.resetsAt !== null && (
246 <Text dimColor> ↻ {formatReset(s.fiveHour.resetsAt, false)}</Text>
247 )}
248 </Text>
249 <Text>
250 <Text dimColor> · week </Text>
251 {s.week === null && <Text dimColor>?</Text>}
252 {s.week !== null && (
253 <Text color={percentColor(s.week.percentUsed)}>{`${Math.round(s.week.percentUsed)}%`}</Text>
254 )}
255 {s.week !== null && s.week.resetsAt !== null && (
256 <Text dimColor> ↻ {formatReset(s.week.resetsAt, true)}</Text>
257 )}
258 </Text>
259 {s.costUsd !== null && <Text bold> {formatCost(s.costUsd)}</Text>}
260 </Text>
261 </Box>
262 <Box>
263 {runs.map(r => (
264 <Text color={r.color}>{r.text}</Text>
265 ))}
266 </Box>
267 <Box flexWrap="wrap" columnGap={3}>
268 {legend.map(c => (
269 <Text>
270 <Text color={c.color}>▌</Text> {c.name.toLowerCase()} {formatTokens(c.tokens)}{' '}
271 <Text dimColor>{formatShare(c.tokens, s.maxTokens)}</Text>
272 </Text>
273 ))}
274 </Box>
275 </Box>
276 )
277 })
278}
279types/index.d.ts 33 lines1export type ContextBarCategory = {
2 name: string
3 tokens: number
4 color: string
5 kind: 'used' | 'free' | 'buffer'
6}
7
8export type UsageWindow = {
9 percentUsed: number
10 // Epoch milliseconds; null when the response did not say when the window resets.
11 resetsAt: number | null
12}
13
14export type ContextBarSnapshot = {
15 categories: ContextBarCategory[]
16 totalTokens: number
17 maxTokens: number
18 percentage: number
19 autoCompactThreshold: number | null
20 // Null where the host keeps no cost ledger, so the bar shows nothing rather than $0.00.
21 costUsd: number | null
22 // The plan's usage windows as /usage shows them; null (drawn as "?") when the account has no such limit or no API
23 // response has reported one yet.
24 fiveHour: UsageWindow | null
25 week: UsageWindow | null
26}
27
28declare module 'claude-code' {
29 interface PluginState {
30 'context-bar': { isShown: boolean; snapshot: ContextBarSnapshot | null }
31 }
32}
33