A coloured bar above the prompt showing what fills the context window, by category, and how much the last turn and its steps added.

A coloured bar in the band above the prompt showing what fills the context window, by category, and how much the last turn added.
████████████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒ 60k/200k (30%) · $1.30
System 20k MCP 4.0k Skills 2.0k Messages 22k Turn 13k Free 107k Buffer 33k
Last turn: 3 steps · context 40k → 52k (+13k) · 1.5k out · $0.30 · steps +1.0k +6.0k +5.0k
/context uses: system prompt and tools, MCP tools, custom agents, skills, memory files, then messages. After the content come the free space (shaded) and the autocompact buffer. Every category in use gets at least one cell, however small, where the bar has room.This turn) and the previous one after it ends (Last turn): how many model requests it made, the context it started from and reached, the tokens it generated, what it cost, and what each of its last eight steps added. When a compaction runs partway through a turn, the line shows where it left the context (context 166k → compacted 34k → 37k) and counts the turn's growth from there.The band yields to a survey, and can be collapsed and restored like any band above the prompt (ctrl+x ctrl+a, or the [-]/[+] at its right edge).
In the desktop app the band has a view of its own: the bar is laid out by the app from each segment's share of the window in solid theme colours, the free space filled rather than shaded, so it fills the band at any font size. The legend puts a swatch beside each name and wraps rather than dropping what does not fit, and the turn line wraps too.
/context-toolsOpens a pane, as wide as the terminal allows, with a table of the twenty largest tool results in the context, each by what its call set out to do:
Largest tool results in the context 20 of 54 results · ~31k of 101k in messages · ~9.2k in reminders · 4 characters a token
# Size Share Tool Call Detail
──────────────────────────────────────────────────────────────────────────────────────────────────────────
1 ~12k ██████████ Bash ▸ Run plugin tests and type-check claude plugin test plugins/context-bar
2 ~5.0k ████▏ Read ▾ register.tsx plugins/context-bar/hooks
file_path S:\repo\plugins\context-bar\hooks\register.tsx
Result
│ import { atom, read, update } from 'claude-code';
… 412 more lines
3 ~725 ▋ Grep ▸ "session.compact" in types *.ts
[ Close ]
Bash, Agent) goes by its description, its command in the detail. A file goes by its name, its folder relative to the project in the detail. A search goes by its pattern and where it looked, and a fetch by its address. The detail is dropped when the pane is too narrow for it, and a failed call's tool is drawn in the error colour.<system-reminder> blocks Claude Code attaches to whichever result comes next are left out of it and counted together in the header.q or Close dismisses it.The list is read from the context as it stands when drawn, so it holds what a compaction kept and nothing it dropped, and is drawn again after every response. Sizes are estimated from each result's text at about four characters a token, so images are not counted.
/context, measured against the compaction window and refreshed after every response. The system prompt, tools, MCP tools, agents, skills and memory files are counted with the token-count API, as /context counts them, and counted again only when the engine's local estimate of them changes (a tool or memory file loaded), so most responses send no requests. The messages are what the last response was answered over beyond those, so the total matches the status line's figure; before the first response, and after a /clear or a compaction, they are the local estimate./cost and the status line total it; a turn's cost is how much that total grew during it, so it includes its subagents' requests./clear resets everything and draws the fresh conversation's bar at once.hooks/register.tsx 423 lines1import { atom, read, update } from 'claude-code';
2import type { ContextCategory, EngineInterface, ModelUsage, Register, SessionContextBreakdown } from 'claude-code';
3
4import type { ContextBarBreakdown, ContextBarSlice, ContextBarStep, ContextBarTurn } from '../types';
5import { desktopBand } from './desktop';
6import type { BandSegment as Segment } from './desktop';
7import { formatTokens, registerTools } from './tools';
8
9// Kept in the session's state, so a reload of the module draws at once rather
10// than waiting for the next response.
11const breakdown = atom({ plugin: 'context-bar', key: 'breakdown' } as const, null);
12const measured = atom({ plugin: 'context-bar', key: 'measured' } as const, null);
13const cost = atom({ plugin: 'context-bar', key: 'cost' } as const, null);
14const turn = atom({ plugin: 'context-bar', key: 'turn' } as const, null);
15const counted = atom({ plugin: 'context-bar', key: 'counted' } as const, null);
16
17// The steps the turn line lists, newest last.
18const MAX_STEPS_SHOWN = 8;
19// The bar's narrowest, in cells; otherwise it fills the band beside its summary.
20const MIN_BAR_CELLS = 10;
21// What the last turn is drawn in: the first of these no other segment uses.
22const LAST_TURN_COLORS = ['warning', 'suggestion', 'success', 'permission'];
23// The colours /context draws the conversation and the free space in, for when
24// the breakdown leaves their rows out.
25const MESSAGES_COLOR = 'purple_FOR_SUBAGENTS_ONLY';
26const FREE_COLOR = 'promptBorder';
27// After a /clear, how often and how many times to look for the fresh
28// conversation before measuring whatever is there.
29const CLEAR_POLL_MS = 100;
30const CLEAR_POLLS = 10;
31
32// The short names for /context's rows, by the start of the row's name, in the
33// order the bar draws them. A row named otherwise goes by its first word, just
34// before the messages, which stay last so the last turn can be carved off them.
35const SHORT_NAMES: [prefix: string, name: string][] = [
36 ['System', 'System'],
37 ['MCP', 'MCP'],
38 ['Custom agents', 'Agents'],
39 ['Skills', 'Skills'],
40 ['Memory', 'Memory'],
41 ['Messages', 'Messages'],
42];
43
44// Measures the conversation a /clear started, once the engine has bound it
45// after the ending one's `session.end`: at once, then every CLEAR_POLL_MS
46// while the session still goes by the ended one's id, CLEAR_POLLS in all.
47function refreshAfterClear($: EngineInterface, endedId: string, polls = CLEAR_POLLS) {
48 $.clock.after(polls === CLEAR_POLLS ? 0 : CLEAR_POLL_MS, async () => {
49 try {
50 if ((await $.session.id()) === endedId && polls > 1) return refreshAfterClear($, endedId, polls - 1);
51 } catch {
52 // Measure what is there.
53 }
54 await refresh($);
55 });
56}
57
58function inputSide(usage: ModelUsage) {
59 return usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens;
60}
61
62// The rows that stay the same until the session's tools, skills or memory
63// change: everything in use but the conversation.
64function isFixed(category: ContextCategory) {
65 return category.kind === 'used' && !category.name.startsWith('Messages');
66}
67
68function slice({ name, tokens, color, kind }: ContextCategory): ContextBarSlice {
69 return { name, tokens, color, kind: kind as ContextBarSlice['kind'] };
70}
71
72// The fixed rows counted with the token-count API, as /context counts them.
73// The summary's local estimate of the tool schemas runs well over what they
74// really take, so it is only trusted to say when they changed.
75async function countFixed($: EngineInterface, estimated: ContextCategory[]) {
76 try {
77 const counted = (await $.session.usage({ breakdown: 'full' })).context.breakdown;
78 if (counted !== undefined) return counted.categories.filter(isFixed).map(slice);
79 } catch (error) {
80 $.ui.log(`context-bar: could not count the context: ${error instanceof Error ? error.message : String(error)}`);
81 }
82 return estimated.map(slice);
83}
84
85// The window by category: the fixed rows as last counted, counted again
86// whenever their estimate moves; the conversation as what the last response
87// was answered over beyond them (the summary's estimate before there is one,
88// in a fresh, cleared or just-compacted session); and the free space as what
89// is left of the window past both and the compaction buffer.
90async function measureWindow($: EngineInterface, rows: SessionContextBreakdown): Promise<ContextBarBreakdown> {
91 const estimated = rows.categories.filter(isFixed);
92 const basis = JSON.stringify(estimated.map(({ name, tokens }) => [name, tokens]));
93 let known = await read($, counted);
94 if (known?.basis !== basis) {
95 known = { basis, slices: await countFixed($, estimated) };
96 await update($, counted, () => known);
97 }
98 const window = rows.rawMaxTokens;
99 const fixed = known.slices.reduce((sum, each) => sum + each.tokens, 0);
100 const conversation = rows.categories.find(category => category.kind === 'used' && !isFixed(category));
101 const messages =
102 rows.apiUsage === null ? (conversation?.tokens ?? 0) : Math.max(inputSide(rows.apiUsage) - fixed, 0);
103 const used = fixed + messages;
104 const freeRow = rows.categories.find(category => category.kind === 'free');
105 const bufferRow = rows.categories.find(category => category.kind === 'buffer');
106 // The buffer is the window past the compaction threshold, so content that
107 // reaches into it leaves that much less of it.
108 const buffer = Math.min(bufferRow?.tokens ?? 0, Math.max(window - used, 0));
109 const slices: ContextBarSlice[] = [
110 ...known.slices,
111 { name: 'Messages', tokens: messages, color: conversation?.color ?? MESSAGES_COLOR, kind: 'used' },
112 { name: 'Free space', tokens: Math.max(window - used - buffer, 0), color: freeRow?.color ?? FREE_COLOR, kind: 'free' },
113 ];
114 if (bufferRow !== undefined) slices.push({ ...slice(bufferRow), tokens: buffer });
115 return { slices: slices.filter(each => each.tokens > 0), window };
116}
117
118// Re-measures the window by category. `summary` counts locally and sends no
119// request, so it is cheap enough to run after every response; the fixed rows
120// are counted again only when it says they changed.
121async function refresh($: EngineInterface) {
122 try {
123 const usage = await $.session.usage({ breakdown: 'summary' });
124 await update($, cost, () => usage.cost?.usd ?? null);
125 const rows = usage.context.breakdown;
126 if (rows === undefined) return;
127 const measuredWindow = await measureWindow($, rows);
128 await update($, breakdown, () => measuredWindow);
129 } catch (error) {
130 $.ui.log(`context-bar: could not break the context down: ${error instanceof Error ? error.message : String(error)}`);
131 }
132}
133
134// What the turn has added to the context so far, from where it started (or
135// where a compaction within it left the context) to its latest request, that
136// request's own output included, since the next one carries it.
137function turnGrowth(current: ContextBarTurn) {
138 const last = current.steps.at(-1);
139 const start = current.compactedAt === null ? current.contextBefore : current.steps[current.compactedAt]!.context;
140 if (last === undefined || start === null) return null;
141 return last.context + last.output - start;
142}
143
144// What each step added over the one before it (the first over the turn's
145// start): 'compacted' for the step a compaction shrank, null where there is
146// nothing to compare against.
147function stepGrowth(current: ContextBarTurn) {
148 return current.steps.map((step, index) => {
149 if (index === current.compactedAt) return 'compacted';
150 const before = index === 0 ? current.contextBefore : current.steps[index - 1]!.context;
151 return before === null ? null : step.context - before;
152 });
153}
154
155function signed(tokens: number) {
156 return `${tokens < 0 ? '-' : '+'}${formatTokens(Math.abs(tokens))}`;
157}
158
159function formatUsd(usd: number) {
160 return `$${usd.toFixed(2)}`;
161}
162
163// The line under the legend: the turn's requests, the context it went from
164// and to, what it generated and cost (from the session's cost `costNow`), and
165// what each of its last steps added.
166export function turnLine(current: ContextBarTurn, costNow: number | null) {
167 const last = current.steps.at(-1);
168 if (last === undefined) return null;
169 const growth = turnGrowth(current);
170 const context = [
171 current.contextBefore === null ? null : formatTokens(current.contextBefore),
172 current.compactedAt === null ? null : `compacted ${formatTokens(current.steps[current.compactedAt]!.context)}`,
173 formatTokens(last.context),
174 ].filter(point => point !== null);
175 const steps = stepGrowth(current);
176 const shown = steps
177 .slice(-MAX_STEPS_SHOWN)
178 .map(delta => (delta === null ? '?' : delta === 'compacted' ? delta : signed(delta)));
179 const count = current.steps.length;
180 return [
181 `${current.isRunning ? 'This turn' : 'Last turn'}: ${count} step${count === 1 ? '' : 's'}`,
182 `context ${context.join(' → ')}${growth === null ? '' : ` (${signed(growth)})`}`,
183 `${formatTokens(current.steps.reduce((sum, step) => sum + step.output, 0))} out`,
184 current.costBefore === null || costNow === null ? null : formatUsd(costNow - current.costBefore),
185 shown.length < 2 ? null : `steps ${steps.length > shown.length ? '… ' : ''}${shown.join(' ')}`,
186 ]
187 .filter(part => part !== null)
188 .join(' · ');
189}
190
191function isContent(segment: Segment) {
192 return segment.kind === 'used' || segment.kind === 'turn';
193}
194
195// How a segment's cells and its legend label are drawn: the free space dimmed.
196function style(segment: Segment) {
197 return segment.kind === 'free' ? { color: undefined, isDim: true } : { color: segment.color, isDim: false };
198}
199
200function knownIndex(slice: ContextBarSlice) {
201 return SHORT_NAMES.findIndex(([prefix]) => slice.name.startsWith(prefix));
202}
203
204function shortName(slice: ContextBarSlice) {
205 if (slice.kind === 'free') return 'Free';
206 if (slice.kind === 'buffer') return 'Buffer';
207 return SHORT_NAMES[knownIndex(slice)]?.[1] ?? slice.name.split(' ')[0] ?? slice.name;
208}
209
210// The bar's segments in order, each by its short name, neighbours of one name
211// (the system prompt and the system tools) drawn as one in the first one's
212// colour: the content in SHORT_NAMES' order with the last turn's growth carved
213// off its end, then the free space and the buffer.
214export function segments(rows: ContextBarBreakdown, growth: number | null): Segment[] {
215 const result: Segment[] = [];
216 const add = (slice: ContextBarSlice) => {
217 const name = shortName(slice);
218 const previous = result.at(-1);
219 if (previous?.name === name) previous.tokens += slice.tokens;
220 else result.push({ ...slice, name });
221 };
222 const rank = (slice: ContextBarSlice) => {
223 const index = knownIndex(slice);
224 return index < 0 ? SHORT_NAMES.length - 1.5 : index;
225 };
226 rows.slices
227 .filter(slice => slice.kind === 'used')
228 .sort((a, b) => rank(a) - rank(b))
229 .forEach(add);
230 const tail = result.at(-1);
231 if (tail?.name === 'Messages' && growth !== null && growth > 0) {
232 const carved = Math.min(growth, tail.tokens);
233 tail.tokens -= carved;
234 result.push({
235 name: 'Turn',
236 tokens: carved,
237 color: LAST_TURN_COLORS.find(color => result.every(each => each.color !== color)) ?? LAST_TURN_COLORS[0]!,
238 kind: 'turn',
239 });
240 }
241 rows.slices.filter(slice => slice.kind === 'free').forEach(add);
242 rows.slices.filter(slice => slice.kind === 'buffer').forEach(add);
243 return result.filter(segment => segment.tokens > 0);
244}
245
246// Splits `cells` among the weights in proportion, by largest remainder, then
247// gives a cell to each required weight that rounded to none, taken from the
248// largest, so every kind of content in the window shows.
249export function allocate(weights: number[], cells: number, isRequired: boolean[]) {
250 const total = weights.reduce((sum, weight) => sum + weight, 0);
251 if (total <= 0 || cells <= 0) return weights.map(() => 0);
252 const exact = weights.map(weight => (weight / total) * cells);
253 const counts = exact.map(Math.floor);
254 let left = cells - counts.reduce((sum, count) => sum + count, 0);
255 const byRemainder = exact.map((value, index) => ({ index, remainder: value - Math.floor(value) }));
256 byRemainder.sort((a, b) => b.remainder - a.remainder);
257 for (const { index } of byRemainder) {
258 if (left <= 0) break;
259 counts[index]!++;
260 left--;
261 }
262 for (const [index, required] of isRequired.entries()) {
263 if (!required || counts[index]! > 0) continue;
264 const largest = counts.indexOf(Math.max(...counts));
265 if (counts[largest]! <= 1) break;
266 counts[largest]!--;
267 counts[index] = 1;
268 }
269 return counts;
270}
271
272const GLYPH: Record<Segment['kind'], string> = { used: '█', turn: '█', free: '░', buffer: '▒' };
273
274type LegendItem = { segment: Segment; label: string };
275
276// The legend that fits on one line of `columns`, labels two spaces apart: every
277// segment with its tokens; then by name alone; then as many names as fit.
278export function legend(parts: Segment[], columns: number): LegendItem[] {
279 const width = (items: LegendItem[]) => items.reduce((sum, item) => sum + item.label.length + 2, -2);
280 const full = parts.map(segment => ({ segment, label: `${segment.name} ${formatTokens(segment.tokens)}` }));
281 if (width(full) <= columns) return full;
282 const names = parts.map(segment => ({ segment, label: segment.name }));
283 let used = -2;
284 const fitting: LegendItem[] = [];
285 for (const item of names) {
286 used += item.label.length + 2;
287 if (used > columns) break;
288 fitting.push(item);
289 }
290 return fitting;
291}
292
293export const register: Register = on => {
294 on('session.start', async ($, e, next) => {
295 await $.command.register({
296 name: 'context-tools',
297 description: 'Show the largest tool results in the context',
298 immediate: true,
299 });
300 const result = await next(e);
301 await refresh($);
302 return result;
303 });
304
305 // A /clear starts the conversation over, and no `session.start` follows it.
306 on('session.end', async ($, e, next) => {
307 if (e.reason === 'clear') {
308 await update($, breakdown, () => null);
309 await update($, measured, () => null);
310 await update($, cost, () => null);
311 await update($, turn, () => null);
312 await update($, counted, () => null);
313 }
314 const result = await next(e);
315 if (e.reason === 'clear') refreshAfterClear($, e.sessionId);
316 return result;
317 });
318
319 registerTools(on);
320
321 on('session.measure', async ($, e, next) => {
322 if (e.changed.includes('cost') && e.cost !== undefined) {
323 const usd = e.cost.usd;
324 await update($, cost, () => usd);
325 }
326 if (e.changed.includes('context')) {
327 await update($, measured, () => e.context.tokens ?? null);
328 await refresh($);
329 }
330 return next(e);
331 });
332
333 on('turn.start', async ($, e, next) => {
334 const [contextBefore, costBefore] = await Promise.all([read($, measured), read($, cost)]);
335 await update($, turn, () => ({ contextBefore, steps: [], compactedAt: null, costBefore, isRunning: true }));
336 return next(e);
337 });
338
339 on('turn.step', async function* ($, e, next) {
340 const result = yield* next(e);
341 if (e.agentId === undefined && result.usage !== null) {
342 const step: ContextBarStep = { context: inputSide(result.usage), output: result.usage.output_tokens };
343 await update($, turn, current => {
344 if (current === null) return current;
345 // The context only shrinks when a compaction runs mid-turn.
346 const previous = current.steps.at(-1)?.context ?? current.contextBefore;
347 const compactedAt = previous !== null && step.context < previous ? current.steps.length : current.compactedAt;
348 return { ...current, steps: [...current.steps, step], compactedAt };
349 });
350 }
351 return result;
352 });
353
354 on('turn.complete', async ($, e, next) => {
355 if (e.agentId === undefined) {
356 await update($, turn, current => (current === null ? current : { ...current, isRunning: false }));
357 }
358 return next(e);
359 });
360
361 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
362 const rows = await read($, breakdown);
363 if (e.props.hasSurvey || rows === null || rows.slices.length < 1) return next(e);
364 const [current, costNow] = await Promise.all([read($, turn), read($, cost)]);
365 const used = rows.slices.filter(slice => slice.kind === 'used').reduce((sum, slice) => sum + slice.tokens, 0);
366 const percent = Math.round((used / Math.max(rows.window, 1)) * 100);
367 const summary = [
368 `${formatTokens(used)}/${formatTokens(rows.window)} (${percent}%)`,
369 costNow === null ? null : formatUsd(costNow),
370 ]
371 .filter(part => part !== null)
372 .join(' · ');
373
374 const parts = segments(rows, current === null ? null : turnGrowth(current));
375 const line = current === null ? null : turnLine(current, costNow);
376 if (e.surface === 'desktop') return desktopBand($.ui.resolve(e), { parts, summary, line });
377
378 const { Box, Text } = $.ui.resolve(e);
379 // The bar fills the band beside its summary, down to a floor.
380 const cells = Math.max(e.props.bodyColumns - summary.length - 1, MIN_BAR_CELLS);
381 const counts = allocate(
382 parts.map(part => part.tokens),
383 cells,
384 parts.map(isContent),
385 );
386
387 return (
388 <Box flexDirection="column">
389 <Box flexDirection="row">
390 <Box key="bar" flexDirection="row">
391 {parts.map((part, index) => {
392 if (counts[index]! < 1) return null;
393 const { color, isDim } = style(part);
394 return (
395 <Text color={color} dimColor={isDim}>
396 {GLYPH[part.kind].repeat(counts[index]!)}
397 </Text>
398 );
399 })}
400 </Box>
401 <Text bold> {summary}</Text>
402 </Box>
403 <Box key="legend" flexDirection="row">
404 {legend(parts, e.props.bodyColumns).map(({ segment, label }, index) => {
405 const { color, isDim } = style(segment);
406 return (
407 <Text color={color} dimColor={isDim}>
408 {index === 0 ? '' : ' '}
409 {label}
410 </Text>
411 );
412 })}
413 </Box>
414 {line === null ? null : (
415 <Text dimColor wrap="truncate-end">
416 {line}
417 </Text>
418 )}
419 </Box>
420 );
421 });
422};
423hooks/desktop.tsx 69 lines1import type { ElementTable, ThemeKey } from 'claude-code';
2
3import type { ContextBarSlice } from '../types';
4import { formatTokens } from './tools';
5
6// What the band draws, worked out the same on every surface.
7export type BandSegment = { name: string; tokens: number; color: string; kind: ContextBarSlice['kind'] | 'turn' };
8export type Band = { parts: BandSegment[]; summary: string; line: string | null };
9
10// The colour the free space is filled with, in place of the terminal's shading.
11const FREE_COLOR = 'subtle';
12
13// The theme keys every surface knows. `/context` also colours some categories
14// with the terminal's subagent keys (`purple_FOR_SUBAGENTS_ONLY`), which the
15// desktop need not hold: those take the plain colour they are named for.
16const THEME_KEYS = new Set<string>([
17 'text', 'inverseText', 'inactive', 'subtle', 'suggestion', 'remember', 'success', 'error', 'warning', 'merged',
18 'claude', 'permission', 'planMode', 'autoAccept', 'promptBorder', 'bashBorder', 'ide', 'diffAdded', 'diffRemoved',
19 'diffAddedDimmed', 'diffRemovedDimmed', 'diffAddedWord', 'diffRemovedWord',
20] satisfies ThemeKey[]);
21
22export function fill(segment: Pick<BandSegment, 'color' | 'kind'>) {
23 if (segment.kind === 'free') return FREE_COLOR;
24 return THEME_KEYS.has(segment.color) ? segment.color : segment.color.replace(/_FOR_SUBAGENTS_ONLY$/, '');
25}
26
27// `tokens` as a percentage of `total`, to a hundredth.
28export function share(tokens: number, total: number) {
29 return Math.round((tokens / Math.max(total, 1)) * 10_000) / 100;
30}
31
32// The band on the desktop: the surface lays the bar out from each segment's
33// share, so it fills the band's width at any font size, in solid theme
34// colours; the legend wraps rather than dropping what does not fit, and so
35// does the turn line.
36export function desktopBand({ Box, Text }: ElementTable<'desktop'>, { parts, summary, line }: Band) {
37 const total = parts.reduce((sum, part) => sum + part.tokens, 0);
38 return (
39 <Box flexDirection="column">
40 <Box flexDirection="row" alignItems="center" gap={1}>
41 <Box key="bar" flexDirection="row" flexGrow={1} height={1}>
42 {parts.map(part => (
43 <Box
44 key={`segment-${part.name}`}
45 // Its percentage of the bar: the surface refuses a grow over 10,000.
46 flexGrow={share(part.tokens, total)}
47 // Every kind of content in use shows, however small.
48 minWidth={part.kind === 'used' || part.kind === 'turn' ? 1 : 0}
49 backgroundColor={fill(part)}
50 />
51 ))}
52 </Box>
53 <Text bold>{summary}</Text>
54 </Box>
55 <Box key="legend" flexDirection="row" flexWrap="wrap" columnGap={2}>
56 {parts.map(part => (
57 <Box key={`legend-${part.name}`} flexDirection="row" gap={1}>
58 <Box width={2} height={1} backgroundColor={fill(part)} />
59 <Text dimColor={part.kind === 'free'}>
60 {part.name} <Text dimColor>{formatTokens(part.tokens)}</Text>
61 </Text>
62 </Box>
63 ))}
64 </Box>
65 {line === null ? null : <Text dimColor>{line}</Text>}
66 </Box>
67 );
68}
69hooks/tools.tsx 397 lines1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, On } from 'claude-code';
3
4// The row expanded, by its call's id; the pane shows one at a time.
5const expanded = atom({ plugin: 'context-bar', key: 'expandedTool' } as const, null);
6// The window by category, which register.tsx keeps.
7const breakdown = atom({ plugin: 'context-bar', key: 'breakdown' } as const, null);
8
9// The command, and the pane it opens, listing the largest tool results.
10export const TOOLS_PANE = 'context-tools';
11const MAX_LISTED = 20;
12// A tool result's tokens, estimated from its text's length.
13const CHARS_PER_TOKEN = 4;
14// The width of a row's size bar, in cells, drawn in eighths.
15const BAR_CELLS = 10;
16const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉'];
17// What an expanded row shows of its result.
18const PREVIEW_LINES = 8;
19// The arguments that say what an unknown tool was called on, the first present.
20const TARGET_KEYS = ['path', 'command', 'pattern', 'url', 'query', 'skill', 'description', 'prompt'];
21
22// One tool result in the context: the call it answers and its estimated size.
23type ToolResult = {
24 id: string;
25 tool: string;
26 input: Record<string, unknown>;
27 text: string;
28 isError: boolean;
29 tokens: number;
30};
31
32type Block = { type: string; [field: string]: unknown };
33type Message = { role: string; content: Block[] };
34
35// What Claude Code attaches to a message, whichever tool's result it lands in.
36const REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
37
38function blockText(content: unknown) {
39 if (typeof content === 'string') return content;
40 if (!Array.isArray(content)) return '';
41 return (content as Block[])
42 .filter(block => block.type === 'text' && typeof block.text === 'string')
43 .map(block => block.text as string)
44 .join('\n');
45}
46
47// A result's own text: its reminders cut out, and the blank lines they left.
48function resultText(content: unknown) {
49 return blockText(content).replace(REMINDER, '').replace(/\n{3,}/g, '\n\n').trim();
50}
51
52// The reminders in `messages`, in tokens: in tool results or beside them.
53export function reminderTokens(messages: readonly Message[]) {
54 let chars = 0;
55 for (const message of messages) {
56 for (const block of message.content) {
57 const text = block.type === 'tool_result' ? blockText(block.content) : block.type === 'text' ? blockText([block]) : '';
58 for (const reminder of text.match(REMINDER) ?? []) chars += reminder.length;
59 }
60 }
61 return Math.ceil(chars / CHARS_PER_TOKEN);
62}
63
64// The tool results of `messages` (the context in API form), largest first,
65// each paired with the call it answers and sized by its own text.
66export function toolResults(messages: readonly Message[]): ToolResult[] {
67 const calls = new Map<string, Block>();
68 const results: ToolResult[] = [];
69 for (const message of messages) {
70 for (const block of message.content) {
71 if (block.type === 'tool_use' && typeof block.id === 'string') calls.set(block.id, block);
72 if (block.type !== 'tool_result' || typeof block.tool_use_id !== 'string') continue;
73 const call = calls.get(block.tool_use_id);
74 const text = resultText(block.content);
75 results.push({
76 id: block.tool_use_id,
77 tool: typeof call?.name === 'string' ? call.name : 'Tool',
78 input: (call?.input ?? {}) as Record<string, unknown>,
79 text,
80 isError: block.is_error === true,
81 tokens: Math.ceil(text.length / CHARS_PER_TOKEN),
82 });
83 }
84 }
85 return results.filter(result => result.tokens > 0).sort((a, b) => b.tokens - a.tokens);
86}
87
88function oneLine(value: unknown) {
89 return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
90}
91
92// `path` relative to `cwd` when it lies inside it.
93function relative(path: string, cwd: string) {
94 const norm = (each: string) => each.replace(/\\/g, '/').toLowerCase();
95 const root = norm(cwd).replace(/\/$/, '');
96 return norm(path).startsWith(`${root}/`) ? path.slice(root.length + 1) : path;
97}
98
99function splitPath(path: string) {
100 const cut = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
101 return cut < 0 ? { name: path, folder: '' } : { name: path.slice(cut + 1), folder: path.slice(0, cut) };
102}
103
104// The tool's name for a row: an MCP tool by its server and tool.
105function toolName(tool: string) {
106 const mcp = /^mcp__(.+?)__(.+)$/.exec(tool);
107 return mcp === null ? tool : `${mcp[1]} ${mcp[2]}`;
108}
109
110// What a call set out to do, in a row's words: `title` first, `detail` dim
111// after it. A description the model wrote leads; else the file, search or
112// address the call was on.
113export function describe(tool: string, input: Record<string, unknown>, cwd: string) {
114 const path = oneLine(input.file_path) || oneLine(input.notebook_path);
115 if (path) {
116 const { name, folder } = splitPath(relative(path, cwd));
117 return { title: name, detail: folder };
118 }
119 const where = oneLine(input.path) ? `in ${relative(oneLine(input.path), cwd)}` : '';
120 switch (tool) {
121 case 'Bash':
122 return oneLine(input.description)
123 ? { title: oneLine(input.description), detail: oneLine(input.command) }
124 : { title: oneLine(input.command), detail: '' };
125 case 'Agent':
126 case 'Task':
127 return { title: oneLine(input.description) || oneLine(input.prompt), detail: oneLine(input.subagent_type) };
128 case 'Grep':
129 return { title: `"${oneLine(input.pattern)}"`, detail: [where, oneLine(input.glob)].filter(Boolean).join(' ') };
130 case 'Glob':
131 return { title: oneLine(input.pattern), detail: where };
132 case 'WebFetch':
133 return { title: oneLine(input.url).replace(/^https?:\/\//, ''), detail: oneLine(input.prompt) };
134 }
135 const target = TARGET_KEYS.map(key => oneLine(input[key])).find(Boolean) ?? '';
136 return { title: target || toolName(tool), detail: '' };
137}
138
139// `text` in `width` cells, its middle cut where it is wider, so a path keeps
140// both its root and its file name.
141export function fitMiddle(text: string, width: number) {
142 if (text.length <= width) return text;
143 if (width < 2) return '…'.slice(0, Math.max(width, 0));
144 const head = Math.ceil((width - 1) / 2);
145 return `${text.slice(0, head)}…${text.slice(text.length - (width - 1 - head))}`;
146}
147
148// A bar of BAR_CELLS for `tokens` against the largest, in eighths of a cell,
149// never less than one eighth.
150export function sizeBar(tokens: number, largest: number) {
151 const eighths = Math.max(Math.round((tokens / Math.max(largest, 1)) * BAR_CELLS * 8), 1);
152 return `${'█'.repeat(Math.floor(eighths / 8))}${EIGHTHS[eighths % 8]}`.padEnd(BAR_CELLS);
153}
154
155// The desktop's share bar: `tokens` against the largest, as a percentage of
156// the column the surface lays out; never less than one eighth of a cell, as on
157// the terminal.
158export function sharePercent(tokens: number, largest: number) {
159 return Math.max(Math.round((tokens / Math.max(largest, 1)) * 1000) / 10, 100 / (BAR_CELLS * 8));
160}
161
162export function formatTokens(tokens: number) {
163 const size = Math.abs(tokens);
164 if (size < 1_000) return String(Math.round(tokens));
165 if (size < 10_000) return `${(tokens / 1_000).toFixed(1)}k`;
166 if (size < 1_000_000) return `${Math.round(tokens / 1_000)}k`;
167 return `${(tokens / 1_000_000).toFixed(1)}M`;
168}
169
170// A size estimated from characters.
171function estimate(tokens: number) {
172 return `~${formatTokens(tokens)}`;
173}
174
175// The arguments of a call, a key and its value each, as an expanded row lists them.
176function argumentRows(input: Record<string, unknown>): [key: string, value: string][] {
177 return Object.entries(input)
178 .filter(([, value]) => value !== undefined && value !== '')
179 .map(([key, value]) => [key, typeof value === 'string' ? oneLine(value) : JSON.stringify(value)]);
180}
181
182const GAP = 2;
183const MIN_DETAIL = 12;
184
185// The table's column widths in `columns` cells, a gap after each but the last:
186// the call takes what its titles need up to half the room the fixed columns
187// leave, the detail the rest, and is dropped when too narrow to read.
188export function tableColumns(columns: number, rows: { size: string; title: string; tool: string }[]) {
189 const rank = String(rows.length).length;
190 const size = Math.max(4, ...rows.map(row => row.size.length));
191 const tool = Math.max(4, ...rows.map(row => row.tool.length));
192 // What the call, a gap and the detail share, past the fixed columns and their gaps.
193 const room = columns - rank - size - BAR_CELLS - tool - 4 * GAP;
194 // A title follows its row's marker and a space.
195 const titles = Math.max(4, ...rows.map(row => row.title.length)) + 2;
196 let call = Math.min(titles, Math.max(Math.ceil(room / 2), 20));
197 let detail = room - call - GAP;
198 if (detail < MIN_DETAIL) {
199 call = Math.max(room - GAP, 4);
200 detail = 0;
201 }
202 return { rank, size, bar: BAR_CELLS, call, detail, tool };
203}
204
205// The first lines of a result, and how many more there are.
206function preview(text: string) {
207 const lines = text.replace(/\s+$/, '').split('\n');
208 return { lines: lines.slice(0, PREVIEW_LINES), more: Math.max(lines.length - PREVIEW_LINES, 0) };
209}
210
211// The messages' share of the window, as last estimated; null before one was.
212// Read while drawn, it draws the pane again after every response.
213async function messagesTokens($: EngineInterface) {
214 const rows = await read($, breakdown);
215 return rows?.slices.find(slice => slice.name.startsWith('Messages'))?.tokens ?? null;
216}
217
218export function registerTools(on: On) {
219 // The command's name written out, as register.tsx registers it, so the
220 // engine sees the hook answers only its own command.
221 on('command.run', { command: 'context-tools' }, async ($, e) => {
222 await $.ui.open({
223 id: TOOLS_PANE,
224 title: 'Largest tool results',
225 focus: true,
226 closeOnEscape: true,
227 // The rows, and the title, column header, rule, Close and the space between.
228 rows: MAX_LISTED + 6,
229 // A one-off look, so docked it asks for the whole width.
230 columns: e.presentation.columns,
231 });
232 return {};
233 });
234
235 on('ui.render', { component: 'Pane', requestId: TOOLS_PANE }, async ($, e) => {
236 const { Box, Button, Text } = $.ui.resolve(e);
237 const [messages, cwd, open, inMessages] = await Promise.all([
238 $.session.messages({ as: 'api' }),
239 $.session.cwd(),
240 read($, expanded),
241 messagesTokens($),
242 ]);
243 const all = toolResults(messages as Message[]);
244 const reminders = reminderTokens(messages as Message[]);
245 const listed = all.slice(0, MAX_LISTED);
246 const total = all.reduce((sum, each) => sum + each.tokens, 0);
247 const rows = listed.map(each => ({
248 result: each,
249 size: estimate(each.tokens),
250 tool: toolName(each.tool),
251 ...describe(each.tool, each.input, cwd),
252 }));
253 const widths = tableColumns(e.props.bodyColumns, rows);
254 // Where the call column starts, past its row's marker, as details indent to.
255 const indent = widths.rank + widths.size + widths.bar + widths.tool + 4 * GAP + 2;
256 const close = () => void $.ui.close({ id: TOOLS_PANE });
257 const toggle = async (id: string) => {
258 await update($, expanded, current => (current === id ? null : id));
259 $.ui.invalidate('ui.render');
260 };
261
262 const header = [
263 `${listed.length < all.length ? `${listed.length} of ` : ''}${all.length} result${all.length === 1 ? '' : 's'}`,
264 `${estimate(total)}${inMessages === null ? '' : ` of ${formatTokens(inMessages)} in messages`}`,
265 ...(reminders > 0 ? [`${estimate(reminders)} in reminders`] : []),
266 `${CHARS_PER_TOKEN} characters a token`,
267 ].join(' · ');
268
269 return (
270 <Box flexDirection="column">
271 <Box flexDirection="row" justifyContent="space-between">
272 <Text bold>Largest tool results in the context</Text>
273 <Text dimColor wrap="truncate-end">
274 {header}
275 </Text>
276 </Box>
277 {listed.length < 1 ? (
278 <Text dimColor>No tool results in the context.</Text>
279 ) : (
280 <Box flexDirection="column" marginTop={1}>
281 <Box flexDirection="row">
282 <Box width={widths.rank} marginRight={GAP} justifyContent="flex-end">
283 <Text dimColor bold>
284 #
285 </Text>
286 </Box>
287 <Box width={widths.size} marginRight={GAP} justifyContent="flex-end">
288 <Text dimColor bold>
289 Size
290 </Text>
291 </Box>
292 <Box width={widths.bar + GAP}>
293 <Text dimColor bold>
294 Share
295 </Text>
296 </Box>
297 <Box width={widths.tool + GAP}>
298 <Text dimColor bold>
299 Tool
300 </Text>
301 </Box>
302 <Box width={widths.call + GAP}>
303 <Text dimColor bold>
304 {' Call'}
305 </Text>
306 </Box>
307 {widths.detail > 0 ? (
308 <Text dimColor bold>
309 Detail
310 </Text>
311 ) : null}
312 </Box>
313 <Text dimColor wrap="truncate-end">
314 {'─'.repeat(Math.max(e.props.bodyColumns, 0))}
315 </Text>
316 </Box>
317 )}
318 {rows.map((row, index) => {
319 const each = row.result;
320 const isOpen = open === each.id;
321 return (
322 <Box key={`row-${each.id}`} flexDirection="column">
323 <Box flexDirection="row">
324 <Box width={widths.rank} marginRight={GAP} justifyContent="flex-end">
325 <Text dimColor>{String(index + 1)}</Text>
326 </Box>
327 <Box width={widths.size} marginRight={GAP} justifyContent="flex-end">
328 <Text>{row.size}</Text>
329 </Box>
330 <Box width={widths.bar} marginRight={GAP}>
331 {e.surface === 'desktop' ? (
332 <Box
333 key={`share-${each.id}`}
334 width={`${sharePercent(each.tokens, listed[0]!.tokens)}%`}
335 height={1}
336 backgroundColor="suggestion"
337 />
338 ) : (
339 <Text color="suggestion">{sizeBar(each.tokens, listed[0]!.tokens)}</Text>
340 )}
341 </Box>
342 <Box width={widths.tool + GAP}>
343 {each.isError ? <Text color="error">{row.tool}</Text> : <Text dimColor>{row.tool}</Text>}
344 </Box>
345 <Box width={widths.call + GAP}>
346 <Button
347 key={`tool-${each.id}`}
348 plain
349 label={`${isOpen ? '▾' : '▸'} ${fitMiddle(row.title, widths.call - 2)}`}
350 onPress={() => void toggle(each.id)}
351 />
352 </Box>
353 {widths.detail > 0 ? <Text dimColor>{fitMiddle(row.detail, widths.detail)}</Text> : null}
354 </Box>
355 {isOpen ? details(each, Math.max(e.props.bodyColumns - indent, 8)) : null}
356 </Box>
357 );
358 })}
359 <Box flexDirection="row" marginTop={1}>
360 <Button key="close" role="dismiss" hotkey="q" onPress={close}>
361 Close
362 </Button>
363 </Box>
364 </Box>
365 );
366
367 // An expanded row: the call's arguments and the start of its result.
368 function details(result: ToolResult, width: number) {
369 const { lines, more } = preview(result.text);
370 const args = argumentRows(result.input);
371 const keyWidth = Math.max(0, ...args.map(([key]) => key.length)) + GAP;
372 return (
373 <Box flexDirection="column" paddingLeft={indent} marginBottom={1}>
374 {args.map(([key, value]) => (
375 <Box key={`arg-${key}`} flexDirection="row">
376 <Box width={keyWidth}>
377 <Text dimColor>{key}</Text>
378 </Box>
379 <Text wrap="truncate-end">{fitMiddle(value, width - keyWidth)}</Text>
380 </Box>
381 ))}
382 <Text color={result.isError ? 'error' : 'suggestion'} bold>
383 {result.isError ? 'Error result' : 'Result'}
384 </Text>
385 {lines.map(line => (
386 <Text wrap="truncate-end">
387 <Text dimColor>│ </Text>
388 {line.slice(0, width - 2)}
389 </Text>
390 ))}
391 {more > 0 ? <Text dimColor>… {more} more lines</Text> : null}
392 </Box>
393 );
394 }
395 });
396}
397types/index.d.ts 57 lines1// One row of the context window as /context breaks it down: content in use,
2// the free space, or the compaction buffer.
3export type ContextBarSlice = {
4 name: string;
5 tokens: number;
6 // The theme colour /context draws the row in, by its key in the theme.
7 color: string;
8 kind: 'used' | 'free' | 'buffer';
9};
10
11// The window by category, as last estimated; on-demand tool schemas, which
12// sit outside the window, are left out.
13export type ContextBarBreakdown = {
14 slices: ContextBarSlice[];
15 // The window measured against: the model's, or a smaller compaction window.
16 window: number;
17};
18
19// The rows of the window that stay the same until the session's tools, skills
20// or memory change, as last counted with the token-count API, and the
21// summary's estimate of them then (`basis`), which says when to count again.
22export type ContextBarCounted = { basis: string; slices: ContextBarSlice[] };
23
24// One model request of the main conversation: the input side it was answered
25// over (uncached, cache-read and cache-written together) and what it generated.
26export type ContextBarStep = { context: number; output: number };
27
28// The main conversation's latest turn, kept until the next one starts.
29export type ContextBarTurn = {
30 // The context the turn started from: the last response's input side, or
31 // null when none was measured (a fresh or just-compacted session).
32 contextBefore: number | null;
33 steps: ContextBarStep[];
34 // The first step after a compaction within the turn, if one ran: the
35 // turn's growth is counted from there instead.
36 compactedAt: number | null;
37 // The session's cost when the turn started, in US dollars; null when unknown.
38 costBefore: number | null;
39 isRunning: boolean;
40};
41
42declare module 'claude-code' {
43 interface PluginState {
44 'context-bar': {
45 breakdown: ContextBarBreakdown | null;
46 // The input side of the last response, as the status line reports it.
47 measured: number | null;
48 // What the session has cost so far, in US dollars, as /cost totals it.
49 cost: number | null;
50 turn: ContextBarTurn | null;
51 counted: ContextBarCounted | null;
52 // The /context-tools row expanded, by its call's id.
53 expandedTool: string | null;
54 };
55 }
56}
57