Shows the context window as a stacked bar above the prompt, one colour per /context category; /context-bar toggles it

Shows the context window as a stacked bar above the prompt, one colour per /context category, so you see where the window goes without running /context.
32% · 317k / 1M · 650k to compact ███▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░▒
■ Messages 270k ■ System tools 37k ■ Skills 6.6k ■ System prompt 2.2k ■ Autocompact buffer 33k ■ Free space 650k
/plugin install context-bar@claude-mods
/context category in the colour /context draws it in: used space █, the autocompact buffer ▒, free space ░; deferred tool schemas are left out, as /context leaves them out of the gridpercent · used / window · left to compact: the tokens left before auto-compaction runs (absent when it is off). The start of the ▒ buffer segment is where it runs+N more for the rest)context 32% aloneThe numbers are the local estimate /context makes ($.session.usage({ breakdown: 'summary' })): no token-count requests. They refresh when the session starts, after every turn, after compaction and, during a long turn, after tool calls at most once per refreshSeconds.
/context-bar/context-bar toggles the band, /context-bar on and /context-bar off set it. The choice is remembered across sessions.
| Option | Default | |
|---|---|---|
legend | true | Show the legend row |
refreshSeconds | 5 | During a turn, re-measure after a tool call at most this often |
hooks/register.tsx 153 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { ContextSnapshot } from '../types'
5import { GLYPH, allocate, isNearEdge, legend, summary } from './layout'
6
7const snapshot = atom({ plugin: 'context-bar', key: 'snapshot' } as const, null)
8const isHidden = atom({ plugin: 'context-bar', key: 'isHidden' } as const, false)
9
10/** The person's /context-bar choice, kept across sessions. */
11const HIDDEN_KEY = 'isHidden'
12
13/** From this share of the window the summary is drawn bold. */
14const HIGH_PERCENT = 80
15
16/** Cells kept free at the right end, so the row never reaches the band edge and wraps. */
17const MARGIN = 2
18
19/** Below this many cells for the bar, the band shows the summary alone. */
20const MIN_BAR = 10
21
22let measuredAt = 0
23
24// The summary breakdown is estimated locally, the same rows /context lists,
25// without a token-count request.
26async function measure($: EngineInterface) {
27 const usage = await $.session.usage({ breakdown: 'summary' })
28 const breakdown = usage.context.breakdown
29 if (!breakdown) return
30
31 measuredAt = await $.clock.now()
32 const next: ContextSnapshot = {
33 categories: breakdown.categories.map(({ name, tokens, color, kind }) => ({ name, tokens, color, kind })),
34 usedTokens: breakdown.totalTokens,
35 maxTokens: breakdown.rawMaxTokens,
36 percent: breakdown.percentage,
37 ...(breakdown.isAutoCompactEnabled && breakdown.autoCompactThreshold !== undefined ? { compactAt: breakdown.autoCompactThreshold } : {}),
38 at: measuredAt,
39 }
40 await update($, snapshot, () => next)
41}
42
43async function measureIfStale($: EngineInterface, refreshMs: number) {
44 if ((await $.clock.now()) - measuredAt >= refreshMs) await measure($)
45}
46
47export const register: Register = (on, options) => {
48 const isLegendShown = options.legend !== false
49 const refreshMs = Math.max(1, Number(options.refreshSeconds ?? 5)) * 1000
50
51 on('session.start', async ($, e, next) => {
52 await $.command.register({
53 name: 'context-bar',
54 description: 'Show or hide the context window bar above the prompt',
55 argumentHint: '[on|off]',
56 })
57 const stored = await $.store.get(HIDDEN_KEY)
58 if (stored === true) await update($, isHidden, () => true)
59
60 const started = await next(e)
61 await measure($)
62
63 return started
64 })
65
66 on('turn.complete', async ($, e, next) => {
67 const done = await next(e)
68 await measure($)
69
70 return done
71 })
72
73 on('session.compact', async ($, e, next) => {
74 const compacted = await next(e)
75 await measure($)
76
77 return compacted
78 })
79
80 // Tool results are what grows a long turn: re-measure after them, at most
81 // once per refreshSeconds.
82 on('tool.call', async ($, e, next) => {
83 const ran = await next(e)
84 await measureIfStale($, refreshMs)
85
86 return ran
87 })
88
89 on('command.run', { command: 'context-bar' }, async ($, e) => {
90 const arg = e.args.trim().toLowerCase()
91 const wasHidden = await read($, isHidden)
92 const hide = arg === 'off' ? true : arg === 'on' ? false : arg === '' ? !wasHidden : undefined
93 if (hide === undefined) return { text: 'Usage: /context-bar [on|off]' }
94
95 await update($, isHidden, () => hide)
96 await $.store.set(HIDDEN_KEY, hide)
97 if (!hide) await measure($)
98
99 return { text: hide ? 'Hidden. /context-bar shows it again.' : 'Shown.' }
100 })
101
102 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
103 // The breakdown is the main conversation's: not over a subagent's transcript
104 if (e.props.hasSurvey || e.props.view.agentId !== undefined) return next(e)
105 if (await read($, isHidden)) return next(e)
106 const snap = await read($, snapshot)
107 if (snap === null) return next(e)
108
109 const { Box, Text } = $.ui.resolve(e)
110 const width = e.props.bodyColumns
111 const label = summary(snap)
112 const isHigh = isNearEdge(snap, HIGH_PERCENT)
113 const barWidth = width - label.length - 1 - MARGIN
114
115 if (barWidth < MIN_BAR) {
116 return (
117 <Box>
118 <Text dimColor={!isHigh} bold={isHigh}>
119 context {label}
120 </Text>
121 </Box>
122 )
123 }
124
125 const items = isLegendShown ? legend(snap, width) : []
126
127 return (
128 <Box flexDirection="column">
129 {/* The summary leads, so a squeezed row cuts the end of the bar, never the numbers */}
130 <Box>
131 <Text dimColor={!isHigh} bold={isHigh}>
132 {label}{' '}
133 </Text>
134 {allocate(snap, barWidth).map(segment => (
135 <Text color={segment.color} dimColor={segment.kind !== 'used'}>
136 {GLYPH[segment.kind].repeat(segment.cells)}
137 </Text>
138 ))}
139 </Box>
140 {items.length > 0 && (
141 <Box>
142 {items.flatMap((item, i) => [
143 ...(i > 0 ? [<Text>{' '}</Text>] : []),
144 ...(item.name === '' ? [] : [<Text color={item.color}>■ </Text>]),
145 <Text dimColor>{item.label}</Text>,
146 ])}
147 </Box>
148 )}
149 </Box>
150 )
151 })
152}
153hooks/layout.ts 123 lines1// The bar's layout as pure functions: no `$`, so tests call them directly.
2
3import type { ContextSnapshot, SnapshotCategory } from '../types'
4
5export type Segment = {
6 name: string
7 color: string
8 kind: SnapshotCategory['kind']
9 cells: number
10}
11
12export type LegendItem = { name: string; color: string; kind: SnapshotCategory['kind']; label: string }
13
14/** The glyph a segment is drawn with: used space solid, the buffer shaded, free space light. */
15export const GLYPH: Record<SnapshotCategory['kind'], string> = {
16 used: '█',
17 buffer: '▒',
18 free: '░',
19 deferred: '',
20}
21
22/** `950`, `12.3k`, `124k`, `1.2M`: short enough for a band. */
23export function formatTokens(tokens: number): string {
24 if (tokens < 1000) return String(Math.round(tokens))
25 if (tokens < 10_000) return `${(tokens / 1000).toFixed(1).replace(/\.0$/, '')}k`
26 if (tokens < 1_000_000) return `${Math.round(tokens / 1000)}k`
27 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
28}
29
30/** The categories the bar draws: deferred tool schemas are not in the window, empty rows take no room. */
31export const drawn = (snapshot: ContextSnapshot) =>
32 snapshot.categories.filter(category => category.kind !== 'deferred' && category.tokens > 0)
33
34/**
35 * Splits `width` cells between the categories in proportion to their tokens,
36 * by largest remainder so the cells add up to `width` exactly. Every used
37 * category keeps at least one cell while there is room, taken from the
38 * largest segment, so a small one does not vanish.
39 */
40export function allocate(snapshot: ContextSnapshot, width: number): Segment[] {
41 const categories = drawn(snapshot)
42 const total = categories.reduce((sum, category) => sum + category.tokens, 0)
43 if (width <= 0 || total <= 0) return []
44
45 const exact = categories.map(category => (category.tokens / total) * width)
46 const cells = exact.map(Math.floor)
47 let left = width - cells.reduce((sum, n) => sum + n, 0)
48 const byRemainder = exact.map((value, i) => ({ i, rest: value - Math.floor(value) })).sort((a, b) => b.rest - a.rest)
49 for (const { i } of byRemainder) {
50 if (left <= 0) break
51 cells[i]! += 1
52 left -= 1
53 }
54
55 categories.forEach((category, i) => {
56 if (category.kind !== 'used' || cells[i]! > 0) return
57 const largest = cells.indexOf(Math.max(...cells))
58 if (cells[largest]! > 1) {
59 cells[largest]! -= 1
60 cells[i] = 1
61 }
62 })
63
64 return categories
65 .map((category, i) => ({ name: category.name, color: category.color, kind: category.kind, cells: cells[i]! }))
66 .filter(segment => segment.cells > 0)
67}
68
69/** `62% · 124k / 200k` */
70export function summary(snapshot: ContextSnapshot): string {
71 const left = toCompact(snapshot)
72 const compact = left === undefined ? '' : ` · ${formatTokens(left)} to compact`
73 return `${snapshot.percent}% · ${formatTokens(snapshot.usedTokens)} / ${formatTokens(snapshot.maxTokens)}${compact}`
74}
75
76/** Tokens left before auto-compaction runs; undefined when it is off. */
77export const toCompact = (snapshot: ContextSnapshot) =>
78 snapshot.compactAt === undefined ? undefined : Math.max(0, snapshot.compactAt - snapshot.usedTokens)
79
80/** Close to the edge: 80% full, or less than a tenth of the window before compaction. */
81export function isNearEdge(snapshot: ContextSnapshot, highPercent = 80): boolean {
82 const left = toCompact(snapshot)
83 return snapshot.percent >= highPercent || (left !== undefined && left < snapshot.maxTokens / 10)
84}
85
86/** Legend order: what takes the space first, then the buffer, free space last. */
87const KIND_ORDER: Record<SnapshotCategory['kind'], number> = { used: 0, buffer: 1, free: 2, deferred: 3 }
88
89/**
90 * The legend's items, used categories largest first, then the buffer and free
91 * space, as many as fit in `width` cells (`■ name 12k` and two spaces between
92 * items); the rest are counted in a final `+N more` when that fits.
93 */
94export function legend(snapshot: ContextSnapshot, width: number): LegendItem[] {
95 const items = drawn(snapshot)
96 .slice()
97 .sort((a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || b.tokens - a.tokens)
98 .map(category => ({
99 name: category.name,
100 color: category.color,
101 kind: category.kind,
102 label: `${category.name} ${formatTokens(category.tokens)}`,
103 }))
104
105 const fitted: LegendItem[] = []
106 let used = 0
107 for (const [i, item] of items.entries()) {
108 const gap = fitted.length > 0 ? 2 : 0
109 const after = items.length - i - 1
110 const reserve = after > 0 ? 2 + `+${after} more`.length : 0
111 if (used + gap + 2 + item.label.length + reserve <= width) {
112 fitted.push(item)
113 used += gap + 2 + item.label.length
114 continue
115 }
116 const more = `+${items.length - i} more`
117 if (used + gap + more.length <= width) fitted.push({ name: '', color: '', kind: 'free', label: more })
118 break
119 }
120
121 return fitted
122}
123types/index.d.ts 32 lines1export type SnapshotCategory = {
2 /** The row's label as /context prints it. */
3 name: string
4 tokens: number
5 /** The theme colour /context draws the row in, by its key in the theme. */
6 color: string
7 kind: 'used' | 'free' | 'buffer' | 'deferred'
8}
9
10export type ContextSnapshot = {
11 categories: SnapshotCategory[]
12 /** Tokens in use, as /context counts them. */
13 usedTokens: number
14 /** The window measured against (the compaction window). */
15 maxTokens: number
16 /** usedTokens over maxTokens, 0 to 100. */
17 percent: number
18 /** The token count at which auto-compaction runs; absent when it is off. */
19 compactAt?: number
20 /** When it was measured, in ms since the epoch. */
21 at: number
22}
23
24declare module 'claude-code' {
25 interface PluginState {
26 'context-bar': {
27 snapshot: ContextSnapshot | null
28 isHidden: boolean
29 }
30 }
31}
32