See what fills Claude Code's context window, how many turns until auto-compact, and compact with a focus. Live band above the prompt, breakdown pane, optional…


<a href="LICENSE"><img src="https://img.shields.io/github/license/AweGuider/Claude-Context-Control" alt="License"></a> <img src="https://img.shields.io/badge/Claude%20Code-mod-4f7cc4" alt="Claude Code mod"> <img src="https://img.shields.io/badge/mod%20API-early%20access-c98c2e" alt="Mod API: early access">
<a href="#install">Install</a> · <a href="#what-it-does">What it does</a> · <a href="#comparison">Comparison</a> · <a href="#settings">Settings</a> · <a href="#what-it-reads-sends-and-writes">Privacy</a> · <a href="#faq">FAQ</a> · <a href="CHANGELOG.md">Changelog</a>
Context Control is a Claude Code mod that keeps your context window in view. A band above the prompt shows your context usage as you work: how full the window is, how many tokens each turn adds, what fills it, and how many turns are left until auto-compact. When you want to compact, a Compact button takes a focus, so the summary keeps what matters. It works in the Claude desktop app's Code tab and in the terminal.
Unofficial community mod. Not affiliated with or endorsed by Anthropic.
/compact does. While Claude is working it waits for the turn to end./context-control): context over the session with compaction markers, what fills it, what is loaded on every turn (MCP servers, memory files, skill listing, agents) and compaction history.The bars animate as the numbers change: fill grows, the session chart draws in, the band breathes at the alert level and shimmers while compacting.

<sub>Illustrative mockup of the band's states, with sample figures.</sub>
What Claude Code shows on its own, and what Context Control adds.
| Claude Code built in | Context Control | |
|---|---|---|
| Context usage always in view | Depends on the app version; some desktop builds show no context indicator, and the terminal needs a custom status line | A band above the prompt |
| What fills the context window | /context, on demand | Live, by category, plus what is loaded on every turn |
| Turns until auto-compact | Not shown | Estimated from recent growth |
| Warning before auto-compact | A notice near the limit | Amber, then red, and one toast |
| Compact with a focus | Type /compact <instructions> | A Compact button with a focus field that waits for the turn to end |
| Snapshot before compaction | Write your own PreCompact hook | Built in, optional |
| Context over the session and compaction history | Not shown | Side pane |
In a terminal Claude Code session:
/plugin install context-control --marketplace AweGuider/Claude-Context-Control
Answer y to add the marketplace, then pick the user scope. Or, from your shell:
claude plugin install context-control --marketplace AweGuider/Claude-Context-Control
Installed at user scope, it loads in every new session, including the Claude desktop app's Code tab. In a session that is already running, type /reload-plugins.
Update: claude plugin update context-control@awedev, then /reload-plugins, or press Update on the plugin's page in the desktop app. Uninstall: claude plugin uninstall context-control@awedev.
Built against Claude Code 2.1.295. The mod API is early access and can change between releases.
In the pane's Settings tab; saved across sessions.
| Setting | Default |
|---|---|
| Band above the prompt | On |
| Band starts | Collapsed |
| Open the pane when a session starts | Off |
| Name the band's ↗ and ▲ icons on hover | On |
| Warn at / Alert at | 70% / 85% of auto-compact |
| Toast once when crossing Alert | On |
| Average over (for turns left) | 5 turns |
| Exact counts | Off |
| Pre-compact snapshot | Off |
| Keep snapshots out of git | On |
When on, each compaction first writes .claude/context-snapshots/<date>_<time>.md in the session's working directory (normally the project root) with the trigger, model, context size, the focus you gave, your last 10 prompts, files edited and read, and open tasks. The folder is fixed. With Keep snapshots out of git on, the mod also writes .claude/context-snapshots/.gitignore containing *, a file git reads to ignore the snapshots; your project's own .gitignore is not touched. Old snapshots are not deleted.
/context does, to the Anthropic API your session already uses..claude/context-snapshots/ under the working directory: the snapshot Markdown files and, with Keep snapshots out of git on, a .gitignore that tells git to ignore that folder. It writes no other file.session.compact) only to save the snapshot first and to record the compaction in its history. It passes every compaction on unchanged and never delays, edits or blocks it./context-control, which opens the mod's pane and does nothing else./compact <focus>, as if you typed it, only when you press Compact. It runs no other command.The full policy is in PRIVACY.md.
Install Context Control. The band above the prompt shows the context window's fill as a bar and a percentage, the tokens used out of the window, and how much the last turn added. Click it for the breakdown, or run /context-control for the pane.
Some versions of the desktop app don't show a context indicator or a Compact button above the prompt. Context Control adds both back as a mod, with more detail: what fills the context and how many turns are left until auto-compact.
The band shows it, estimated from the average growth of your last five turns (adjustable in Settings) against the auto-compact threshold. The expanded band and the pane mark that threshold on the bar.
The breakdown splits the context into messages, system prompt, system tools, MCP tools, skills, agents and memory files. The pane's Always loaded list ranks what you pay for on every turn, such as MCP servers and CLAUDE.md files, so you can see what to disconnect or trim.
Press Compact and write what the summary must keep, such as "the plan and the open bugs". It runs the same compaction as /compact <instructions>. Turn on the pre-compact snapshot to also keep a Markdown handoff on disk.
The band appears in the Claude desktop app's Code tab and in the terminal. The pane opens on every surface Claude Code draws on; VS Code is untested.
No. It makes no network requests and no model calls. The optional Exact counts setting uses the same token-count requests as /context; it's off by default.
Only its settings and recent sessions' context sizes (both in Claude Code's plugin storage), and snapshots if you turn them on. Snapshots go to .claude/context-snapshots/ in your project, with a .gitignore there that keeps them out of git.
See Install. Updates arrive when the version changes; press Update on the plugin's page or run claude plugin update context-control@awedev.
No. Context Control is an unofficial community mod by AweDev, not affiliated with or endorsed by Anthropic.
~. The same applies to the average per turn of a session with no history yet: it is estimated from message tokens over prompts sent, and reads low after an earlier compaction.— after the mod missed turns (installed or updated mid-session), until the next reply.claude plugin validate .
claude plugin test .
claude --plugin-dir .
hooks/register.tsx holds the hooks and drawings, hooks/model.ts the figures, hooks/svg.ts the bars and chart, hooks/snapshot.ts the snapshot writer, types/index.d.ts the state contract and tests/control.test.ts the tests.
MIT © 2026 Alan Safonov (AweDev)
hooks/register.tsx 1037 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, SessionCompactResult, SessionContextUsage, SessionMessage, Timer } from 'claude-code'
3
4import { DEFAULTS, TEXT_TONE, TONE, clampPercent, estimatedAvg, fmt, fmtDelta, fmtWindow, growth, levelOf, limitOf, toBreakdown, turnsLeft } from './model'
5import type { Level } from './model'
6import { snapshotStamp, snapshotText } from './snapshot'
7import { compositionBar, rankBar, sparkline, windowBar } from './svg'
8import type { Breakdown, Compaction, Point, Reading, ControlSettings } from '../types'
9
10const PANE = 'context-control'
11
12const reading = atom({ plugin: 'context-control', key: 'reading' } as const, null)
13const history = atom({ plugin: 'context-control', key: 'history' } as const, [])
14const breakdown = atom({ plugin: 'context-control', key: 'breakdown' } as const, null)
15const compactions = atom({ plugin: 'context-control', key: 'compactions' } as const, [])
16const phase = atom({ plugin: 'context-control', key: 'phase' } as const, 'idle')
17const expanded = atom({ plugin: 'context-control', key: 'expanded' } as const, false)
18const composing = atom({ plugin: 'context-control', key: 'composing' } as const, false)
19const draft = atom({ plugin: 'context-control', key: 'draft' } as const, '')
20const tab = atom({ plugin: 'context-control', key: 'tab' } as const, 'overview')
21const settings = atom({ plugin: 'context-control', key: 'settings' } as const, DEFAULTS)
22const shownFill = atom({ plugin: 'context-control', key: 'shownFill' } as const, 0)
23const changedAt = atom({ plugin: 'context-control', key: 'changedAt' } as const, 0)
24const breakdownAt = atom({ plugin: 'context-control', key: 'breakdownAt' } as const, 0)
25const toggledAt = atom({ plugin: 'context-control', key: 'toggledAt' } as const, 0)
26const revealFrame = atom({ plugin: 'context-control', key: 'revealFrame' } as const, 0)
27const turnCount = atom({ plugin: 'context-control', key: 'turnCount' } as const, null)
28const isAlerted = atom({ plugin: 'context-control', key: 'isAlerted' } as const, false)
29const error = atom({ plugin: 'context-control', key: 'error' } as const, '')
30
31// Not `$`: the engine and the directory read that name as the capability object.
32type Engine = EngineInterface
33type Els = Elements[keyof Elements]
34
35const message = (err: unknown) => (err instanceof Error ? err.message : String(err))
36
37const HISTORY_KEY = 'history:'
38const KEEP_HISTORIES = 20
39/** Longer than the bar's grow and the composition's fade, so only a draw this soon after a change animates. */
40const ANIMATE_MS = 1500
41const DELTA_COLOR = '#7fa7e0'
42/** The breakdown opens in up to four stages: one every STAGE_MS, closing a little faster. */
43const STAGE_MS = 55
44const CLOSE_STAGE_MS = 40
45const STAGES = 4
46/** Columns at the strip's right end the click area leaves bare, so Compact and the icons take their own clicks. */
47const CLICK_CLEAR_RIGHT = 20
48
49/** Everything a drawing needs, derived once per draw. */
50type View = {
51 r: Reading
52 tokens?: number
53 /** `tokens` is the breakdown's estimate: Claude Code has reported no count yet. */
54 isEstimate: boolean
55 pct?: number
56 limit: number
57 limitPct?: number
58 level: Level
59 last?: number
60 avg?: number
61 isAvgEstimate: boolean
62 turns?: number
63 b: Breakdown | null
64 s: ControlSettings
65 /** Where the bar's fill grows from: the last reading's, or `to` once that change has been drawn. */
66 from: number
67 fadeComposition: boolean
68}
69
70async function viewOf($: Engine): Promise<View | null> {
71 const r = await read($, reading)
72 if (r === null) return null
73 const [b, s, points, shown, prompts, readingAt, compositionAt, now] = await Promise.all([
74 read($, breakdown),
75 read($, settings),
76 read($, history),
77 read($, shownFill),
78 read($, turnCount),
79 read($, changedAt),
80 read($, breakdownAt),
81 $.clock.now(),
82 ])
83 const limit = limitOf(r, b)
84 const isEstimate = r.tokens === undefined && b !== null
85 const tokens = r.tokens ?? b?.estimate
86 const fill = tokens === undefined ? 0 : (tokens / r.window) * 100
87 const pct = tokens === undefined ? undefined : isEstimate ? Math.round((tokens / r.window) * 100) : (r.percent ?? Math.round((tokens / r.window) * 100))
88 const measured = growth(points, s.averageOver)
89 const avg = measured.avg ?? estimatedAvg(b, prompts)
90 return {
91 r,
92 tokens,
93 isEstimate,
94 pct,
95 limit,
96 limitPct: b?.threshold !== undefined ? (b.threshold / r.window) * 100 : undefined,
97 level: tokens === undefined ? 'calm' : levelOf(tokens, limit, s),
98 last: measured.last,
99 avg,
100 isAvgEstimate: measured.avg === undefined && avg !== undefined,
101 turns: tokens === undefined ? undefined : turnsLeft(tokens, limit, avg),
102 b,
103 s,
104 from: now - readingAt < ANIMATE_MS ? shown : fill,
105 fadeComposition: now - compositionAt < ANIMATE_MS,
106 }
107}
108
109/** The session's history as last saved, so a resume or restart keeps Last turn and Avg. */
110async function loadHistory($: Engine): Promise<Point[]> {
111 const saved = (await $.store.get(HISTORY_KEY + (await $.session.id()))) as { points?: Point[] } | undefined
112 return Array.isArray(saved?.points) ? saved.points : []
113}
114
115async function saveHistory($: Engine, points: Point[]) {
116 await $.store.set(HISTORY_KEY + (await $.session.id()), { at: await $.clock.now(), points })
117}
118
119/** Keeps the newest KEEP_HISTORIES sessions' histories; the store is one file for every session. */
120async function pruneHistories($: Engine) {
121 const keys = (await $.store.keys()).filter(k => k.startsWith(HISTORY_KEY))
122 if (keys.length <= KEEP_HISTORIES) return
123 const dated = await Promise.all(keys.map(async k => ({ k, at: Number(((await $.store.get(k)) as { at?: number } | undefined)?.at ?? 0) })))
124 dated.sort((a, b) => b.at - a.at)
125 for (const { k } of dated.slice(KEEP_HISTORIES)) await $.store.delete(k)
126}
127
128/** `isSeed`: the first reading after the mod started watching; turns before it went unseen. */
129async function ingest($: Engine, ctx: SessionContextUsage, isSeed = false) {
130 const [before, b] = await Promise.all([read($, reading), read($, breakdown)])
131 const next: Reading = { tokens: ctx.tokens, window: ctx.window, percent: ctx.percent }
132 const shown = before?.tokens ?? b?.estimate
133 await update($, shownFill, () => (shown !== undefined && before ? (shown / before.window) * 100 : 0))
134 await update($, reading, () => next)
135 if (next.tokens !== before?.tokens) {
136 const now = await $.clock.now()
137 await update($, changedAt, () => now)
138 }
139 if (next.tokens === undefined) return
140 const tokens = next.tokens
141
142 const wasCompacted = (await read($, phase)) === 'compacted'
143 if (wasCompacted) await update($, phase, () => 'idle')
144 const list = await read($, history)
145 const lastPoint = list.at(-1)
146 if (!wasCompacted && lastPoint?.tokens === tokens) return
147 const point: Point = wasCompacted ? { tokens, isCompaction: true } : isSeed && lastPoint ? { tokens, isGap: true } : { tokens }
148 const points = await update($, history, () => [...list, point].slice(-300))
149 await saveHistory($, points)
150}
151
152async function checkAlert($: Engine) {
153 const [r, s, b, points] = await Promise.all([read($, reading), read($, settings), read($, breakdown), read($, history)])
154 const tokens = r?.tokens
155 if (r === null || tokens === undefined) return
156 const limit = limitOf(r, b)
157 const level = levelOf(tokens, limit, s)
158 if (level === 'alert' && !(await read($, isAlerted))) {
159 await update($, isAlerted, () => true)
160 if (s.toastOnAlert) {
161 const turns = turnsLeft(tokens, limit, growth(points, s.averageOver).avg)
162 const pct = r.percent ?? Math.round((tokens / r.window) * 100)
163 $.ui.toast(`Context at ${pct}%${turns !== undefined ? ` — auto-compact in ~${turns} ${turns === 1 ? 'turn' : 'turns'}` : ''}`, { timeoutMs: 6000 })
164 }
165 } else if (level === 'calm') {
166 await update($, isAlerted, () => false)
167 }
168}
169
170/** Stores the breakdown, and when what it shows changed, the time, so that change animates once. */
171async function storeBreakdown($: Engine, next: Breakdown) {
172 const [prev, r] = await Promise.all([read($, breakdown), read($, reading)])
173 await update($, breakdown, () => next)
174 const isNew = JSON.stringify(prev?.used) !== JSON.stringify(next.used)
175 const isNewEstimate = r?.tokens === undefined && prev?.estimate !== next.estimate
176 if (!isNew && !isNewEstimate) return
177 const now = await $.clock.now()
178 if (isNew) await update($, breakdownAt, () => now)
179 if (isNewEstimate && r) {
180 await update($, shownFill, () => (prev ? (prev.estimate / r.window) * 100 : 0))
181 await update($, changedAt, () => now)
182 }
183}
184
185/**
186 * The plain usage call is free and quick, so the band draws from it first;
187 * the breakdown (the slow part) and the prompt count follow.
188 */
189async function refresh($: Engine, ctx?: SessionContextUsage, isSeed = false) {
190 try {
191 await ingest($, ctx ?? (await $.session.usage()).context, isSeed)
192 const s = await read($, settings)
193 const found = (await $.session.usage({ breakdown: s.exactCounts ? 'full' : 'summary' })).context.breakdown
194 if (found) await storeBreakdown($, toBreakdown(found, s.exactCounts))
195 await checkAlert($)
196 const prompts = await $.session.turns()
197 await update($, turnCount, () => prompts)
198 await update($, error, () => '')
199 } catch (err) {
200 await update($, error, () => message(err))
201 }
202}
203
204async function startWatching($: Engine) {
205 try {
206 const saved = await loadHistory($)
207 await update($, history, () => saved)
208 } catch (err) {
209 await update($, error, () => message(err))
210 }
211 await refresh($, undefined, true)
212 await pruneHistories($).catch(() => {})
213}
214
215async function saveSettings($: Engine, patch: Partial<ControlSettings>) {
216 const next = await update($, settings, s => ({ ...s, ...patch }))
217 await $.store.set('settings', next)
218 if (patch.exactCounts !== undefined || patch.warnAt !== undefined || patch.alertAt !== undefined) void refresh($)
219}
220
221/**
222 * Writes the snapshot; the engine follows `$` only into functions of this file,
223 * so the I/O lives here and snapshot.ts only builds the text.
224 */
225async function writeSnapshot(
226 $: Engine,
227 o: { messages: readonly SessionMessage[]; trigger: string; focus?: string; reading: Reading | null; settings: ControlSettings },
228): Promise<string> {
229 const stamp = snapshotStamp(await $.clock.now())
230 const sessionId = await $.session.id()
231 const model = await $.session.model()
232 const text = snapshotText({ stamp, trigger: o.trigger, sessionId, model, reading: o.reading, focus: o.focus, messages: o.messages })
233 // Fixed paths, relative to the working directory, so the plugin directory can read what is written.
234 await $.fs.write(`.claude/context-snapshots/${stamp}.md`, text)
235 if (o.settings.snapshotGitignore && !(await $.fs.exists('.claude/context-snapshots/.gitignore'))) {
236 await $.fs.write('.claude/context-snapshots/.gitignore', '*\n')
237 }
238 return `.claude/context-snapshots/${stamp}.md`
239}
240
241/** The Compact button's run while its `/compact` is in flight: its snapshot, and whether the hook recorded it. */
242type ButtonCompact = { snapshot?: string; isRecorded: boolean }
243let buttonCompact: ButtonCompact | undefined
244
245/**
246 * Snapshot first (when on), run the compaction, record it: the session.compact hook's work.
247 * `own`: the button already wrote the snapshot, so this uses it and marks the run recorded.
248 */
249async function aroundCompact(
250 $: Engine,
251 o: { trigger: string; focus?: string; messages: readonly SessionMessage[]; own?: ButtonCompact },
252 run: () => Promise<SessionCompactResult>,
253): Promise<SessionCompactResult> {
254 const s = await read($, settings)
255 const before = await read($, reading)
256 await update($, phase, () => 'compacting')
257 try {
258 let snapshot: string | undefined = o.own?.snapshot
259 if (s.snapshot && !o.own) {
260 try {
261 snapshot = await writeSnapshot($, { messages: o.messages, trigger: o.trigger, focus: o.focus, reading: before, settings: s })
262 } catch (err) {
263 $.ui.toast(`Snapshot not saved: ${message(err)}`)
264 }
265 }
266 const result = await run()
267 if (result.skip !== undefined) {
268 await update($, phase, () => 'idle')
269 return result
270 }
271 const record: Compaction = {
272 at: await $.clock.now(),
273 trigger: o.trigger,
274 before: result.tokensBefore ?? before?.tokens,
275 after: result.tokensAfter,
276 focus: o.focus,
277 snapshot,
278 }
279 await update($, compactions, list => [...list, record].slice(-50))
280 await update($, phase, () => 'compacted')
281 await update($, isAlerted, () => false)
282 if (o.own) o.own.isRecorded = true
283 return result
284 } catch (err) {
285 await update($, phase, () => 'idle')
286 throw err
287 }
288}
289
290const asMessages = (found: unknown): readonly SessionMessage[] => (Array.isArray(found) ? found : [])
291
292/**
293 * Runs `/compact <focus>` as the person would: `$.session.compact` is refused in an SDK session,
294 * which every desktop session is, and a prompt may not start with `/`. The engine may run this
295 * plugin's own session.compact hook for it or skip it as the caller's, so the button writes the
296 * snapshot first and records the compaction itself unless the hook did.
297 */
298async function compactNow($: Engine, focus: string) {
299 await update($, composing, () => false)
300 await update($, draft, () => '')
301 const text = focus.trim()
302 const [s, before] = await Promise.all([read($, settings), read($, reading)])
303 await update($, phase, () => 'compacting')
304 const own: ButtonCompact = { isRecorded: false }
305 if (s.snapshot) {
306 try {
307 let messages: readonly SessionMessage[] = []
308 try {
309 messages = asMessages(await $.session.messages())
310 } catch {
311 messages = []
312 }
313 own.snapshot = await writeSnapshot($, { messages, trigger: 'manual', focus: text || undefined, reading: before, settings: s })
314 } catch (err) {
315 $.ui.toast(`Snapshot not saved: ${message(err)}`)
316 }
317 }
318 buttonCompact = own
319 try {
320 await $.command.run({ command: 'compact', args: text })
321 if (!own.isRecorded) {
322 const record: Compaction = { at: await $.clock.now(), trigger: 'manual', before: before?.tokens, focus: text || undefined, snapshot: own.snapshot }
323 await update($, compactions, list => [...list, record].slice(-50))
324 await update($, phase, () => 'compacted')
325 await update($, isAlerted, () => false)
326 }
327 } catch (err) {
328 await update($, phase, () => 'idle')
329 $.ui.toast(`Couldn't compact: ${message(err)}`)
330 } finally {
331 if (buttonCompact === own) buttonCompact = undefined
332 }
333}
334
335/** `focus` when the person asked for it, so the pane's first click presses a tab instead of only focusing the pane. */
336function openPane($: Engine, focus = false) {
337 return $.ui.open(focus ? { id: PANE, title: 'Context', focus: true } : { id: PANE, title: 'Context' })
338}
339
340const textBar = (pct: number, cells: number) => {
341 const filled = Math.round((clampPercent(pct) / 100) * cells)
342 return '█'.repeat(filled) + '░'.repeat(cells - filled)
343}
344
345const share = (part: number, whole: number) => {
346 const p = whole > 0 ? (part / whole) * 100 : 0
347 return p > 0 && p < 1 ? '<1%' : `${Math.round(p)}%`
348}
349
350const approx = (isEstimate: boolean) => (isEstimate ? '~' : '')
351
352function windowSvg(els: Els, v: View, o: { width?: number; height: number; compacting: boolean }) {
353 const to = v.tokens === undefined ? 0 : (v.tokens / v.r.window) * 100
354 if (!('Svg' in els)) {
355 const { Text } = els
356 return <Text color={TEXT_TONE[v.level]}>{textBar(to, o.width ? Math.max(6, Math.round(o.width / 8)) : 40)}</Text>
357 }
358 const { Svg } = els
359 const source = windowBar({
360 from: v.from,
361 to,
362 tick: v.limitPct,
363 tone: TONE[v.level],
364 pulse: v.level === 'alert' && !o.compacting,
365 shimmer: o.compacting,
366 width: o.width,
367 height: o.height,
368 })
369 const alt = `${v.isEstimate ? 'About ' : ''}${v.pct ?? 0}% of the context window used${v.b?.threshold !== undefined ? `; auto-compact at ${fmt(v.b.threshold)}` : ''}`
370 return o.width !== undefined ? <Svg source={source} alt={alt} width={o.width} height={o.height} /> : <Svg source={source} alt={alt} height={o.height} />
371}
372
373function compositionSvg(els: Els, b: Breakdown, fade: boolean) {
374 const total = b.used.reduce((a, c) => a + c.tokens, 0)
375 if (!('Svg' in els)) {
376 const { Box, Text } = els
377 return (
378 <Box flexDirection="row">
379 {b.used.map(c => (
380 <Text color={c.color}>{'█'.repeat(Math.max(1, Math.round((c.tokens / total) * 40)))}</Text>
381 ))}
382 </Box>
383 )
384 }
385 const { Svg } = els
386 return <Svg source={compositionBar(b.used, fade)} alt={`Used context by category: ${b.used.map(c => `${c.name} ${fmt(c.tokens)}`).join(', ')}`} height={8} />
387}
388
389function legend(els: Els, b: Breakdown, columns: 1 | 2) {
390 const { Box, Text } = els
391 const total = b.used.reduce((a, c) => a + c.tokens, 0)
392 return (
393 <Box flexDirection="row" flexWrap="wrap">
394 {b.used.map(c => (
395 <Box flexDirection="row" width={columns === 2 ? '50%' : '100%'} paddingRight={columns === 2 ? 3 : 0}>
396 <Text color={c.color}>■ </Text>
397 <Box flexGrow={1}>
398 <Text wrap="truncate-end">{c.name}</Text>
399 </Box>
400 <Text>{fmt(c.tokens)}</Text>
401 <Box width={6} justifyContent="flex-end">
402 <Text dimColor>{share(c.tokens, total)}</Text>
403 </Box>
404 </Box>
405 ))}
406 </Box>
407 )
408}
409
410/** The legend as rows of one or two categories, so the breakdown can reveal it row by row. */
411function legendRows(els: Els, b: Breakdown, columns: 1 | 2 | 3) {
412 const { Box, Text } = els
413 const total = b.used.reduce((a, c) => a + c.tokens, 0)
414 const rows = []
415 for (let i = 0; i < b.used.length; i += columns) {
416 rows.push(
417 <Box flexDirection="row">
418 {b.used.slice(i, i + columns).map(c => (
419 <Box flexDirection="row" width={columns === 3 ? '33%' : columns === 2 ? '50%' : '100%'} paddingRight={columns > 1 ? 3 : 0}>
420 <Text color={c.color}>■ </Text>
421 <Box flexGrow={1}>
422 <Text wrap="truncate-end">{c.name}</Text>
423 </Box>
424 <Text>{fmt(c.tokens)}</Text>
425 <Box width={6} justifyContent="flex-end">
426 <Text dimColor>{share(c.tokens, total)}</Text>
427 </Box>
428 </Box>
429 ))}
430 </Box>,
431 )
432 }
433 return rows
434}
435
436let revealTimer: Timer | undefined
437
438/** Opens or closes the breakdown; with `animate`, redraws once per stage until every stage has shown. */
439async function toggleDetails($: Engine, animate: boolean) {
440 const isOpen = await update($, expanded, x => !x)
441 if (!animate) return
442 const start = await $.clock.now()
443 const step = isOpen ? STAGE_MS : CLOSE_STAGE_MS
444 await update($, toggledAt, () => start)
445 revealTimer?.cancel()
446 revealTimer = undefined
447 const timer = $.clock.every(step, () => {
448 void (async () => {
449 await update($, revealFrame, n => n + 1)
450 if ((await $.clock.now()) - start >= step * STAGES) {
451 timer.cancel()
452 if (revealTimer === timer) revealTimer = undefined
453 }
454 })()
455 })
456 revealTimer = timer
457}
458
459function composeOf($: Engine, els: Els, v: View, s: ControlSettings, text: string, show: boolean) {
460 if (!show) return null
461 const { Box, Text, Button } = els
462 return (
463 <Box flexDirection="column" rowGap={1} paddingBottom={1}>
464 <Text>
465 <Text bold>Compact conversation</Text>
466 <Text dimColor>{v.tokens !== undefined ? ` · ${approx(v.isEstimate)}${fmt(v.tokens)} now; older messages become a summary, recent ones stay` : ''}</Text>
467 </Text>
468 {'Input' in els ? (
469 <els.Input
470 key="focus"
471 label="Focus (optional)"
472 placeholder="What the summary must keep"
473 value={text}
474 autoFocus
475 submitLabel="Compact"
476 onInput={value => void update($, draft, () => value)}
477 onSubmit={value => void compactNow($, value)}
478 />
479 ) : null}
480 <Box flexDirection="row" columnGap={2} alignItems="center">
481 <Text dimColor>{s.snapshot ? 'Snapshot first → .claude/context-snapshots/' : 'No snapshot · turn it on in the pane’s Settings'}</Text>
482 <Box flexGrow={1} />
483 <Button key="cancel" label="Cancel" onPress={() => update($, composing, () => false)} />
484 {/* The field's own submit is the Compact button; a surface without fields gets this one. */}
485 {'Input' in els ? null : <Button key="go" label="Compact" variant="primary" onPress={() => compactNow($, '')} />}
486 </Box>
487 </Box>
488 )
489}
490
491export const register: Register = on => {
492 on('session.start', async ($, e, next) => {
493 const stored = (await $.store.get('settings')) as Partial<ControlSettings> | undefined
494 const s: ControlSettings = { ...DEFAULTS, ...(stored ?? {}) }
495 await update($, settings, () => s)
496 await update($, expanded, () => s.startExpanded)
497 await $.command.register({
498 name: 'context-control',
499 description: 'Open the Context Control pane: breakdown, history, compactions and settings',
500 })
501 void startWatching($)
502 if (s.openPaneOnStart) void openPane($)
503 return next(e)
504 })
505
506 on('session.end', async ($, e, next) => {
507 if (e.reason === 'clear') {
508 await update($, reading, () => null)
509 await update($, history, () => [])
510 await update($, compactions, () => [])
511 await update($, phase, () => 'idle')
512 await update($, isAlerted, () => false)
513 }
514 return next(e)
515 })
516
517 on('session.measure', async ($, e, next) => {
518 const out = await next(e)
519 if (e.changed.includes('context')) await refresh($, e.context)
520 return out
521 })
522
523 on('session.compact', ($, e, next) => {
524 if (e.agentId !== undefined || e.trigger === 'precompute') return next(e)
525 const own = e.trigger === 'manual' ? buttonCompact : undefined
526 return aroundCompact($, { trigger: e.trigger, focus: e.instructions, messages: e.messages, own }, () => next(e))
527 }).catch(($, e, next) => next(e))
528
529 on('ui.message', async ($, e, next) => {
530 if (!e.element.startsWith('click-')) return next(e)
531 if ((e.data as { type?: unknown } | null)?.type === 'toggle') await toggleDetails($, true)
532 return {}
533 })
534
535 on('command.run', { command: 'context-control' }, async $ => {
536 await openPane($, true)
537 return { text: 'Opened the Context Control pane.' }
538 })
539
540 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
541 const s = await read($, settings)
542 if (!s.showBand || e.props.hasSurvey) return next(e)
543 const v = await viewOf($)
544 if (v === null) return next(e)
545 const [ph, isOpen, isComposing, text, compacts, toggled, now] = await Promise.all([
546 read($, phase),
547 read($, expanded),
548 read($, composing),
549 read($, draft),
550 read($, compactions),
551 read($, toggledAt),
552 $.clock.now(),
553 // Read only so each frame of a reveal draws again.
554 read($, revealFrame),
555 ])
556 const els = $.ui.resolve(e)
557 const { Box, Text, Button } = els
558 const tone = TEXT_TONE[v.level]
559 const win = fmtWindow(v.r.window)
560 const toggle = () => toggleDetails($, 'Client' in els)
561 const lastCompaction = compacts.at(-1)
562
563 let summary
564 if (ph === 'compacting') {
565 summary = (
566 <Text>
567 <Text bold color="claude">Compacting…</Text>
568 <Text dimColor>{v.tokens !== undefined ? ` summarising ${fmt(v.tokens)}` : ''}{s.snapshot ? ' · snapshot first' : ''}</Text>
569 </Text>
570 )
571 } else if (ph === 'compacted' || v.tokens === undefined) {
572 const wasCompacted = ph === 'compacted' && lastCompaction !== undefined
573 summary = wasCompacted ? (
574 <Text>
575 <Text bold color="success">Compacted</Text>
576 <Text dimColor>
577 {` ${lastCompaction.before !== undefined ? fmt(lastCompaction.before) : '?'} → ${lastCompaction.after !== undefined ? fmt(lastCompaction.after) : 'summary'}`}
578 {lastCompaction.snapshot ? ' · snapshot saved' : ''}
579 {' · new size after the next reply'}
580 </Text>
581 </Text>
582 ) : (
583 <Text>
584 <Text bold dimColor>Context</Text>
585 <Text dimColor> measuring — figures appear after the next reply</Text>
586 </Text>
587 )
588 }
589
590 // Narrower bands drop words first, then whole figures, so Compact and the arrow always fit.
591 const isNarrow = e.props.bodyColumns < 90
592 const isTiny = e.props.bodyColumns < 60
593 const canToggle = v.tokens !== undefined && ph === 'idle'
594 const toggleLabel = isOpen ? 'Hide details' : 'Show details'
595 const a = approx(v.isEstimate)
596 const turnsWord = v.turns === 1 ? 'turn' : 'turns'
597
598 const right =
599 !canToggle || isTiny
600 ? ''
601 : v.b?.threshold === undefined
602 ? v.b && !v.b.isAutoCompactEnabled
603 ? 'auto-compact off'
604 : ''
605 : v.turns !== undefined
606 ? isNarrow
607 ? `~${v.turns} ${turnsWord} left`
608 : `auto-compact in ~${v.turns} ${turnsWord}`
609 : isNarrow
610 ? ''
611 : `auto-compact at ${fmt(v.b.threshold)}`
612
613 let compactControl
614 if (ph === 'compacting') compactControl = null
615 else if (e.props.isWorking) compactControl = <Text dimColor>Compact after this turn</Text>
616 else if (isComposing) compactControl = null
617 else
618 compactControl = (
619 <Button key="compact" label="Compact" variant={v.level === 'alert' ? 'primary' : undefined} onPress={() => update($, composing, () => true)} />
620 )
621
622 // An icon Button that names itself in a small dim line beside it while hovered.
623 const icon = (key: string, glyph: string, name: string, onPress: () => unknown) => (
624 <Box key={`${key}-box`} flexDirection="row" alignItems="center" columnGap={1}>
625 {s.arrowTooltip ? (
626 <Box display="none" hover={{ display: 'flex' }}>
627 <Text size="footnote" dimColor>
628 {name}
629 </Text>
630 </Box>
631 ) : null}
632 <Button key={key} plain dimColor hover={{ dimColor: false }} onPress={onPress}>
633 {glyph}
634 </Button>
635 </Box>
636 )
637 const paneIcon = icon('open-pane', '↗', 'Open pane', () => openPane($, true))
638 const chevron = icon('chevron', isOpen ? '▼' : '▲', toggleLabel, toggle)
639
640 // A Box can't be pressed and a Button holds only text, so each text piece is its own toggle.
641 const strip = canToggle ? (
642 <Box key="strip" flexDirection="row" alignItems="center" columnGap={2}>
643 <Box flexDirection="row" alignItems="center" columnGap={1}>
644 {windowSvg(els, v, { width: 72, height: 10, compacting: false })}
645 <Button key="toggle" plain onPress={toggle}>
646 <Text bold color={tone}>{`${a}${v.pct}%`}</Text>
647 </Button>
648 </Box>
649 <Button key="toggle-tokens" plain onPress={toggle}>
650 <Text>{`${a}${fmt(v.tokens!)}${isNarrow ? '' : ` / ${win}`}`}</Text>
651 </Button>
652 {v.last !== undefined && !isTiny ? (
653 <Button key="toggle-last" plain onPress={toggle}>
654 <Text bold color={DELTA_COLOR}>{fmtDelta(v.last)}</Text>
655 {isNarrow ? null : <Text dimColor> last turn</Text>}
656 </Button>
657 ) : null}
658 <Box flexGrow={1} />
659 {right ? (
660 <Button key="toggle-right" plain onPress={toggle}>
661 <Text color={v.level === 'calm' ? undefined : tone} dimColor={v.level === 'calm'}>
662 {right}
663 </Text>
664 </Button>
665 ) : null}
666 {compactControl}
667 {paneIcon}
668 {chevron}
669 </Box>
670 ) : (
671 <Box flexDirection="row" alignItems="center" columnGap={2}>
672 {windowSvg(els, v, { width: 72, height: 10, compacting: ph === 'compacting' })}
673 {summary}
674 <Box flexGrow={1} />
675 {compactControl}
676 {paneIcon}
677 </Box>
678 )
679
680 const hasClickArea = canToggle && !isComposing && 'Client' in els
681 // No local binding named `Client`: the plugin directory reads it only as an element with a fixed module.
682 const clickLayer = (key: string) => {
683 if (!('Client' in els)) return null
684 return <els.Client key={key} module="./click-area.tsx" width="100%" height="100%" />
685 }
686 // One click layer per row: a single layer stretched over the panel reached only its top row on desktop.
687 const clickable = (node: unknown, key: string) =>
688 hasClickArea ? (
689 <Box flexDirection="column" position="relative">
690 {node}
691 <Box position="absolute" top={0} bottom={0} left={0} width="100%">
692 {clickLayer(key)}
693 </Box>
694 </Box>
695 ) : (
696 node
697 )
698
699 // `gap`: 'inner' sits within a section, 'section' between sections; inner spacing is given up first.
700 type Row = { node: unknown; gap?: 'inner' | 'section'; isLegend?: true }
701 const gap = (kind: 'inner' | 'section' = 'section'): Row => ({ node: <Box height={1} />, gap: kind })
702 const legendColumns = e.props.bodyColumns >= 100 ? 3 : e.props.bodyColumns >= 70 ? 2 : 1
703 const threshold = v.b?.threshold !== undefined ? `auto-compact at ${fmt(v.b.threshold)}` : v.b && !v.b.isAutoCompactEnabled ? 'auto-compact off' : ''
704 // Stages, bottom first: revealed one at a time, nearest the strip first.
705 const stages: Row[][] = canToggle
706 ? [
707 [
708 {
709 node: (
710 <Box flexDirection="row" columnGap={4} flexWrap="wrap">
711 <Button key="close-last" plain onPress={toggle}>
712 <Text dimColor>Last turn </Text>
713 <Text bold>{fmtDelta(v.last)}</Text>
714 </Button>
715 <Button key="close-avg" plain onPress={toggle}>
716 <Text dimColor>Avg / turn </Text>
717 <Text bold>{v.avg !== undefined ? `${approx(v.isAvgEstimate)}${fmt(v.avg)}` : '—'}</Text>
718 </Button>
719 <Button key="close-turns" plain onPress={toggle}>
720 <Text dimColor>Auto-compact in </Text>
721 <Text bold color={tone}>{v.turns !== undefined ? `~${v.turns} ${turnsWord}` : '—'}</Text>
722 </Button>
723 <Box flexGrow={1} />
724 </Box>
725 ),
726 },
727 gap(),
728 ],
729 v.b && v.b.used.length > 0 ? [...legendRows(els, v.b, legendColumns).map(node => ({ node, isLegend: true as const })), gap()] : [],
730 v.b && v.b.used.length > 0
731 ? [
732 {
733 node: (
734 <Box flexDirection="row" justifyContent="space-between">
735 <Button key="close-fills" plain onPress={toggle}>
736 <Text dimColor>What fills it</Text>
737 </Button>
738 <Button key="close-accuracy" plain onPress={toggle}>
739 <Text dimColor>{v.b.isExact ? 'exact counts' : 'local estimate'}</Text>
740 </Button>
741 </Box>
742 ),
743 },
744 gap('inner'),
745 { node: compositionSvg(els, v.b, v.fadeComposition) },
746 gap('inner'),
747 ]
748 : [],
749 [
750 {
751 node: (
752 <Box flexDirection="row" justifyContent="space-between">
753 <Button key="close-head" plain onPress={toggle}>
754 <Text bold color={tone}>{`${a}${v.pct}%`}</Text>
755 <Text dimColor>{` of ${win} · ${a}${fmt(v.tokens!)} tokens`}</Text>
756 </Button>
757 {threshold ? (
758 <Button key="close-threshold" plain onPress={toggle}>
759 <Text dimColor>{threshold}</Text>
760 </Button>
761 ) : null}
762 </Box>
763 ),
764 },
765 gap('inner'),
766 { node: windowSvg(els, v, { height: 12, compacting: false }) },
767 gap(),
768 ],
769 ].filter(stage => stage.length > 0)
770 : []
771
772 // The band scrolls past maxRows: the open panel gives up inner spacing, then lower legend rows, then section spacing.
773 const budget = Math.max(0, e.props.maxRows - 1)
774 const count = () => stages.reduce((n, stage) => n + stage.length, 0)
775 const dropGaps = (kind: 'inner' | 'section') => {
776 for (const stage of stages) if (count() > budget) stage.splice(0, stage.length, ...stage.filter(r => r.gap !== kind))
777 }
778 const trimLegend = (minKeep: number) => {
779 const legendStage = stages.find(stage => stage.some(r => r.isLegend))
780 if (!legendStage || count() <= budget) return
781 const legend = legendStage.filter(r => r.isLegend)
782 const rest = legendStage.filter(r => !r.isLegend)
783 const keep = legend.length - (count() - budget) - 1
784 if (keep >= minKeep && keep < legend.length) {
785 const more = v.b!.used.length - keep * legendColumns
786 legendStage.splice(0, legendStage.length, ...legend.slice(0, keep), { node: <Text dimColor>{`+${more} more · /context-control for all`}</Text> }, ...rest)
787 } else if (minKeep === 0) {
788 legendStage.splice(0, legendStage.length, ...rest)
789 }
790 }
791 if (count() > budget) dropGaps('inner')
792 trimLegend(1)
793 if (count() > budget) dropGaps('section')
794 trimLegend(0)
795
796 const shownStages = !('Client' in els) || toggled === 0
797 ? isOpen ? stages.length : 0
798 : isOpen
799 ? Math.min(stages.length, 1 + Math.floor((now - toggled) / STAGE_MS))
800 : Math.max(0, stages.length - 1 - Math.floor((now - toggled) / CLOSE_STAGE_MS))
801 const visible = stages.slice(0, shownStages).reverse().flat().slice(-budget || stages.length)
802 const details = visible.length > 0 ? <Box flexDirection="column">{visible.map((r, i) => clickable(r.node, `click-row-${i}`))}</Box> : null
803
804 const compose = composeOf($, els, v, s, text, isComposing && ph === 'idle' && !e.props.isWorking)
805
806 if (hasClickArea) {
807 return (
808 <Box flexDirection="column">
809 {details}
810 <Box flexDirection="column" position="relative">
811 {strip}
812 {/* The strip's right end stays bare so Compact and the arrow take their own clicks. */}
813 <Box position="absolute" top={0} bottom={0} left={0} width={Math.max(1, e.props.bodyColumns - CLICK_CLEAR_RIGHT)}>
814 {clickLayer('click-strip')}
815 </Box>
816 </Box>
817 </Box>
818 )
819 }
820
821 return (
822 <Box flexDirection="column">
823 {compose}
824 {details}
825 {strip}
826 </Box>
827 )
828 })
829
830 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
831 const els = $.ui.resolve(e)
832 const { Box, Text, Button } = els
833 const [current, v, points, compacts, err] = await Promise.all([read($, tab), viewOf($), read($, history), read($, compactions), read($, error)])
834 const tabs = (
835 <Box flexDirection="row" columnGap={2} paddingBottom={1}>
836 <Button key="tab-overview" plain onPress={() => update($, tab, () => 'overview')}>
837 <Text bold={current === 'overview'} dimColor={current !== 'overview'}>Overview</Text>
838 </Button>
839 <Button key="tab-settings" plain onPress={() => update($, tab, () => 'settings')}>
840 <Text bold={current === 'settings'} dimColor={current !== 'settings'}>Settings</Text>
841 </Button>
842 </Box>
843 )
844
845 if (current === 'settings') {
846 const s = await read($, settings)
847 const cwd = await $.session.cwd()
848 const toggleRow = (key: keyof ControlSettings & string, label: string, value: boolean, hint?: string) => (
849 <Box flexDirection="column">
850 <Box flexDirection="row" alignItems="center" columnGap={2}>
851 <Box flexGrow={1}>
852 <Text>{label}</Text>
853 </Box>
854 <Button key={`set-${key}`} label={value ? 'On' : 'Off'} variant={value ? 'primary' : undefined} onPress={() => saveSettings($, { [key]: !value })} />
855 </Box>
856 {hint ? <Text dimColor>{hint}</Text> : null}
857 </Box>
858 )
859 const numberRow = (key: 'warnAt' | 'alertAt' | 'averageOver', label: string, suffix: string, min: number, max: number) =>
860 'Input' in els ? (
861 // The Input draws its own label before the field; wrapping keeps the suffix off it in a narrow pane.
862 <Box flexDirection="row" alignItems="center" columnGap={2} flexWrap="wrap">
863 <els.Input
864 key={`set-${key}`}
865 label={label}
866 value={String(s[key])}
867 submitLabel="Set"
868 onSubmit={value => {
869 const n = Math.round(Number(value))
870 if (Number.isFinite(n) && n >= min && n <= max) void saveSettings($, { [key]: n })
871 else $.ui.toast(`${label}: enter ${min}–${max}`)
872 }}
873 />
874 <Text dimColor>{suffix}</Text>
875 </Box>
876 ) : (
877 <Text>{`${label}: ${s[key]} ${suffix}`}</Text>
878 )
879 const heading = (t: string) => <Text bold dimColor>{t.toUpperCase()}</Text>
880
881 return (
882 <Box flexDirection="column" rowGap={1}>
883 {tabs}
884 {heading('Display')}
885 {toggleRow('showBand', 'Band above the prompt', s.showBand)}
886 {'Select' in els ? (
887 <Box flexDirection="row" alignItems="center" columnGap={2}>
888 <Box flexGrow={1}>
889 <Text>Band starts</Text>
890 </Box>
891 <els.Select
892 key="set-startExpanded"
893 options={[{ value: 'collapsed', label: 'Collapsed' }, { value: 'expanded', label: 'Expanded' }]}
894 value={s.startExpanded ? 'expanded' : 'collapsed'}
895 onSelect={value => void saveSettings($, { startExpanded: value === 'expanded' })}
896 />
897 </Box>
898 ) : null}
899 {toggleRow('openPaneOnStart', 'Open this pane when a session starts', s.openPaneOnStart)}
900 {toggleRow('arrowTooltip', 'Name the band’s ↗ and ▲ icons on hover', s.arrowTooltip)}
901 {heading('Alerts')}
902 {numberRow('warnAt', 'Warn at', '% of auto-compact', 1, 100)}
903 {numberRow('alertAt', 'Alert at', '% of auto-compact', 1, 100)}
904 {toggleRow('toastOnAlert', 'Toast once when crossing Alert', s.toastOnAlert)}
905 {numberRow('averageOver', 'Average over', 'turns for turns left', 1, 50)}
906 {heading('Breakdown accuracy')}
907 {toggleRow(
908 'exactCounts',
909 'Exact counts',
910 s.exactCounts,
911 s.exactCounts
912 ? 'Calls the token-count API per category after each turn, with your account. Not a model call, but not free of requests.'
913 : 'Off: local estimate from the last reply’s usage. No API calls.',
914 )}
915 {heading('Pre-compact snapshot')}
916 {toggleRow('snapshot', 'Save a snapshot before each compaction', s.snapshot, 'A Markdown handoff built from the transcript (recent prompts, files touched, open tasks). No model calls.')}
917 <Text dimColor>{`Folder: .claude/context-snapshots/ in ${cwd}`}</Text>
918 {toggleRow('snapshotGitignore', 'Keep snapshots out of git', s.snapshotGitignore, 'Writes a one-line .gitignore inside the snapshot folder; the project’s own .gitignore is untouched.')}
919 </Box>
920 )
921 }
922
923 if (v === null || v.tokens === undefined) {
924 return (
925 <Box flexDirection="column" rowGap={1}>
926 {tabs}
927 <Text dimColor>{err ? `Couldn’t read usage: ${err}` : 'Measuring — figures appear after the next reply.'}</Text>
928 </Box>
929 )
930 }
931
932 const tone = TEXT_TONE[v.level]
933 const used = v.b?.used ?? []
934 const usedTotal = used.reduce((a, c) => a + c.tokens, 0)
935 const fixed = v.b?.fixed ?? []
936 const maxFixed = fixed[0]?.tokens ?? 1
937 const hasSvg = 'Svg' in els
938 const section = (title: string, aside?: string) => (
939 <Box flexDirection="row" justifyContent="space-between">
940 <Text bold>{title}</Text>
941 {aside ? <Text dimColor>{aside}</Text> : null}
942 </Box>
943 )
944
945 return (
946 <Box flexDirection="column" rowGap={1}>
947 {tabs}
948 <Text dimColor>{`Context window · ${await $.session.model()}`}</Text>
949 <Text>
950 <Text bold color={tone}>{`${approx(v.isEstimate)}${v.pct}%`}</Text>
951 <Text dimColor>{` ${approx(v.isEstimate)}${fmt(v.tokens)} of ${fmtWindow(v.r.window)} tokens`}</Text>
952 </Text>
953 {windowSvg(els, v, { height: 12, compacting: false })}
954 <Text dimColor>{v.b?.threshold !== undefined ? `auto-compact at ${fmt(v.b.threshold)}` : 'auto-compact off'}</Text>
955 <Box flexDirection="row" columnGap={3} flexWrap="wrap">
956 <Text dimColor>
957 Last turn <Text bold>{fmtDelta(v.last)}</Text>
958 </Text>
959 <Text dimColor>
960 Avg <Text bold>{v.avg !== undefined ? `${approx(v.isAvgEstimate)}${fmt(v.avg)}` : '—'}</Text>
961 </Text>
962 <Text dimColor>
963 Auto-compact in <Text bold color={tone}>{v.turns !== undefined ? `~${v.turns} ${v.turns === 1 ? 'turn' : 'turns'}` : '—'}</Text>
964 </Text>
965 </Box>
966
967 {points.length >= 2 && hasSvg && 'Svg' in els ? (
968 <Box flexDirection="column" rowGap={1} paddingTop={1}>
969 {section('This session', `${points.length} readings`)}
970 <els.Svg
971 source={sparkline(points, v.r.window, v.b?.threshold)}
972 alt={`Context over the session, now ${fmt(v.tokens)}${compacts.length ? `, ${compacts.length} compaction${compacts.length === 1 ? '' : 's'}` : ''}`}
973 />
974 <Text dimColor>- - auto-compact ● compaction ○ now</Text>
975 </Box>
976 ) : null}
977
978 {used.length > 0 && v.b ? (
979 <Box flexDirection="column" rowGap={1} paddingTop={1}>
980 {section('What fills it', v.b.isExact ? 'exact counts' : 'local estimate')}
981 {compositionSvg(els, v.b, v.fadeComposition)}
982 {legend(els, v.b, 1)}
983 <Text dimColor>{`${fmt(usedTotal)} counted by category`}</Text>
984 </Box>
985 ) : null}
986
987 {fixed.length > 0 ? (
988 <Box flexDirection="column" rowGap={1} paddingTop={1}>
989 {section('Always loaded')}
990 <Text dimColor>Paid on every turn. Trim these to buy headroom.</Text>
991 {fixed.map(f => (
992 <Box flexDirection="column">
993 <Box flexDirection="row" columnGap={1}>
994 <Box width={9}>
995 <Text dimColor>{f.kind}</Text>
996 </Box>
997 <Box flexGrow={1}>
998 <Text wrap="truncate-end">{f.name}</Text>
999 </Box>
1000 <Text>{fmt(f.tokens)}</Text>
1001 </Box>
1002 {'Svg' in els ? <els.Svg source={rankBar(f.tokens / maxFixed, f.color)} alt={`${f.name}: ${fmt(f.tokens)}`} height={4} /> : null}
1003 </Box>
1004 ))}
1005 </Box>
1006 ) : null}
1007
1008 <Box flexDirection="column" rowGap={1} paddingTop={1}>
1009 {section('Compactions', `${compacts.length} this session`)}
1010 {compacts.length === 0 ? <Text dimColor>None yet.</Text> : null}
1011 {[...compacts]
1012 .reverse()
1013 .slice(0, 6)
1014 .map(c => {
1015 const at = new Date(c.at)
1016 const time = `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`
1017 return (
1018 <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
1019 <Box flexDirection="row" justifyContent="space-between">
1020 <Text bold>{`${time} · ${c.trigger}`}</Text>
1021 <Text>{`${c.before !== undefined ? fmt(c.before) : '?'} → ${c.after !== undefined ? fmt(c.after) : 'summary'}`}</Text>
1022 </Box>
1023 {c.focus ? <Text dimColor>{`Focus: “${c.focus}”`}</Text> : null}
1024 {c.snapshot ? <Text dimColor wrap="truncate-start">{c.snapshot}</Text> : null}
1025 </Box>
1026 )
1027 })}
1028 </Box>
1029
1030 <Box paddingTop={1}>
1031 <Button key="pane-compact" label="Compact…" onPress={() => update($, composing, () => true)} />
1032 </Box>
1033 </Box>
1034 )
1035 })
1036}
1037hooks/model.ts 136 lines1import type { SessionContextBreakdown } from 'claude-code'
2
3import type { Breakdown, Category, FixedCost, Point, Reading, ControlSettings } from '../types'
4
5export const DEFAULTS: ControlSettings = {
6 showBand: true,
7 startExpanded: false,
8 openPaneOnStart: false,
9 warnAt: 70,
10 alertAt: 85,
11 toastOnAlert: true,
12 averageOver: 5,
13 exactCounts: false,
14 snapshot: false,
15 snapshotGitignore: true,
16 arrowTooltip: true,
17}
18
19export type Level = 'calm' | 'warn' | 'alert'
20
21export const TONE: Record<Level, string> = { calm: '#9a968c', warn: '#d99a3a', alert: '#e0624a' }
22
23export const TEXT_TONE: Record<Level, string | undefined> = { calm: undefined, warn: 'warning', alert: 'error' }
24
25const CATEGORY_COLORS: Record<string, string> = {
26 Messages: '#6f9be0',
27 'MCP tools': '#3f9a96',
28 'System tools': '#8a99a8',
29 'System prompt': '#77736b',
30 Skills: '#9a86c9',
31 'Custom agents': '#b48ad6',
32 'Memory files': '#c9a24f',
33}
34
35const FALLBACK_COLORS = ['#c77b9b', '#7fb37a', '#d08a5a', '#5aa9c9']
36
37const baseName = (path: string) => path.split(/[\\/]/).pop() ?? path
38
39export function toBreakdown(b: SessionContextBreakdown, isExact: boolean): Breakdown {
40 const used: Category[] = b.categories
41 .filter(c => c.kind === 'used' && c.tokens > 0)
42 .map((c, i) => ({
43 name: c.name,
44 tokens: c.tokens,
45 color: CATEGORY_COLORS[c.name] ?? FALLBACK_COLORS[i % FALLBACK_COLORS.length] ?? '#9a968c',
46 }))
47 .sort((x, y) => y.tokens - x.tokens)
48
49 const fixed: FixedCost[] = []
50 const servers = new Map<string, number>()
51 for (const tool of b.mcpTools) {
52 if (tool.isLoaded) servers.set(tool.serverName, (servers.get(tool.serverName) ?? 0) + tool.tokens)
53 }
54 for (const [name, tokens] of servers) fixed.push({ kind: 'MCP', name, tokens, color: CATEGORY_COLORS['MCP tools']! })
55 for (const file of b.memoryFiles) {
56 fixed.push({ kind: 'Memory', name: `${baseName(file.path)} · ${file.type}`, tokens: file.tokens, color: CATEGORY_COLORS['Memory files']! })
57 }
58 if (b.skills && b.skills.tokens > 0) {
59 fixed.push({ kind: 'Skills', name: `Skill listing · ${b.skills.includedSkills} skills`, tokens: b.skills.tokens, color: CATEGORY_COLORS.Skills! })
60 }
61 const agentTokens = b.agents.reduce((sum, a) => sum + a.tokens, 0)
62 if (agentTokens > 0) {
63 fixed.push({ kind: 'Agents', name: `Custom agents · ${b.agents.length}`, tokens: agentTokens, color: CATEGORY_COLORS['Custom agents']! })
64 }
65 if (b.slashCommands && b.slashCommands.tokens > 0) {
66 fixed.push({ kind: 'Commands', name: `Command listing · ${b.slashCommands.includedCommands}`, tokens: b.slashCommands.tokens, color: '#8a99a8' })
67 }
68 fixed.sort((x, y) => y.tokens - x.tokens)
69
70 return {
71 used,
72 threshold: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined,
73 isAutoCompactEnabled: b.isAutoCompactEnabled,
74 fixed: fixed.slice(0, 8),
75 isExact,
76 estimate: b.totalTokens,
77 messages: used.find(c => c.name === 'Messages')?.tokens,
78 }
79}
80
81export function fmt(n: number): string {
82 if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`
83 if (n >= 1000) return `${(n / 1000).toFixed(1)}k`
84 return String(Math.round(n))
85}
86
87export function fmtWindow(n: number): string {
88 if (n % 1_000_000 === 0) return `${n / 1_000_000}M`
89 if (n % 1000 === 0) return `${n / 1000}k`
90 return fmt(n)
91}
92
93export function fmtDelta(n: number | undefined): string {
94 if (n === undefined) return '—'
95 return `${n >= 0 ? '+' : '−'}${fmt(Math.abs(n))}`
96}
97
98export const limitOf = (reading: Reading, breakdown: Breakdown | null) => breakdown?.threshold ?? reading.window
99
100export function levelOf(tokens: number, limit: number, s: ControlSettings): Level {
101 const ratio = (tokens / limit) * 100
102 if (ratio >= s.alertAt) return 'alert'
103 if (ratio >= s.warnAt) return 'warn'
104 return 'calm'
105}
106
107/** Growth per turn since the last compaction: the newest delta and the mean of the last `over`. */
108export function growth(history: readonly Point[], over: number): { last?: number; avg?: number } {
109 const start = history.findLastIndex(p => p.isCompaction === true)
110 const run = history.slice(Math.max(0, start))
111 const deltas: number[] = []
112 for (let i = 1; i < run.length; i++) if (!run[i]!.isGap) deltas.push(run[i]!.tokens - run[i - 1]!.tokens)
113 if (deltas.length === 0) return {}
114 const recent = deltas.slice(-Math.max(1, over)).filter(d => d > 0)
115 const avg = recent.length > 0 ? recent.reduce((a, b) => a + b, 0) / recent.length : undefined
116 return { last: run.at(-1)?.isGap ? undefined : deltas.at(-1), avg }
117}
118
119/**
120 * Growth per turn guessed from the conversation so far: message tokens over prompts sent.
121 * Counts every prompt since the session began, so after a compaction it reads low.
122 */
123export function estimatedAvg(b: Breakdown | null, turns: number | null): number | undefined {
124 if (b?.messages === undefined || !turns || turns <= 0) return undefined
125 return b.messages / turns
126}
127
128export function turnsLeft(tokens: number, limit: number, avg: number | undefined): number | undefined {
129 if (avg === undefined || avg <= 0) return undefined
130 return Math.max(0, Math.ceil((limit - tokens) / avg))
131}
132
133export function clampPercent(n: number): number {
134 return Math.max(0, Math.min(100, n))
135}
136hooks/snapshot.ts 94 lines1import type { SessionMessage } from 'claude-code'
2
3import { fmt } from './model'
4import type { Reading } from '../types'
5
6const EDITS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
7const TASK_TOOLS = new Set(['TodoWrite', 'mcp__ccd_turn__update_plan'])
8
9const pad = (n: number) => String(n).padStart(2, '0')
10
11const clean = (text: string) =>
12 text
13 .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')
14 .replace(/<[a-z-]+-context[^>]*>[\s\S]*?<\/[a-z-]+-context>/g, '')
15 .trim()
16
17function promptsOf(messages: readonly SessionMessage[], count: number): string[] {
18 return messages
19 .filter(m => m.role === 'user' && (m.toolResults?.length ?? 0) === 0)
20 .map(m => clean(m.text))
21 .filter(t => t.length > 0)
22 .slice(-count)
23}
24
25function filesOf(messages: readonly SessionMessage[]): { edited: string[]; read: string[] } {
26 const edited = new Set<string>()
27 const read = new Set<string>()
28 for (const m of messages) {
29 for (const use of m.toolUses) {
30 const path = use.input.file_path ?? use.input.notebook_path
31 if (typeof path !== 'string') continue
32 if (EDITS.has(use.tool)) edited.add(path)
33 else if (use.tool === 'Read') read.add(path)
34 }
35 }
36 for (const p of edited) read.delete(p)
37 return { edited: [...edited], read: [...read] }
38}
39
40function tasksOf(messages: readonly SessionMessage[]): string[] {
41 for (let i = messages.length - 1; i >= 0; i--) {
42 const use = [...messages[i]!.toolUses].reverse().find(u => TASK_TOOLS.has(u.tool) && Array.isArray(u.input.todos ?? u.input.items))
43 if (!use) continue
44 const list = (use.input.todos ?? use.input.items) as { content?: unknown; status?: unknown }[]
45 return list
46 .filter(t => t.status !== 'completed')
47 .map(t => `- [${t.status === 'in_progress' ? '~' : ' '}] ${String(t.content ?? '')}`)
48 }
49 return []
50}
51
52/** The snapshot's file name stamp for a time: `2026-10-15_164705`. */
53export function snapshotStamp(nowMs: number): string {
54 const now = new Date(nowMs)
55 return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`
56}
57
58/** The Markdown handoff of the conversation about to be compacted. */
59export function snapshotText(o: {
60 stamp: string
61 trigger: string
62 sessionId: string
63 model: string
64 reading: Reading | null
65 focus?: string
66 messages: readonly SessionMessage[]
67}): string {
68 const r = o.reading
69 const size = r?.tokens !== undefined ? `${fmt(r.tokens)} of ${fmt(r.window)} (${r.percent ?? Math.round((r.tokens / r.window) * 100)}%)` : 'unknown'
70 const files = filesOf(o.messages)
71 const tasks = tasksOf(o.messages)
72 const prompts = promptsOf(o.messages, 10)
73
74 return [
75 `# Context snapshot — ${o.stamp.replace('_', ' ')}`,
76 '',
77 `- Trigger: ${o.trigger}`,
78 `- Session: ${o.sessionId}`,
79 `- Model: ${o.model}`,
80 `- Context before compaction: ${size}`,
81 ...(o.focus ? [`- Focus: ${o.focus}`] : []),
82 '',
83 `## Recent prompts (${prompts.length})`,
84 '',
85 ...prompts.flatMap(p => [p.slice(0, 1200).replace(/^/gm, '> '), '']),
86 '## Files touched',
87 '',
88 ...(files.edited.length ? ['Edited:', ...files.edited.map(f => `- ${f}`), ''] : []),
89 ...(files.read.length ? ['Read:', ...files.read.slice(-40).map(f => `- ${f}`), ''] : []),
90 ...(files.edited.length + files.read.length === 0 ? ['None recorded.', ''] : []),
91 ...(tasks.length ? ['## Open tasks', '', ...tasks, ''] : []),
92 ].join('\n')
93}
94hooks/svg.ts 111 lines1import type { Category, Point } from '../types'
2
3const TRACK = 'rgba(128,128,128,0.22)'
4const TICK = '#b8b4aa'
5const EASE = 'calcMode="spline" keyTimes="0;1" keySplines="0.2 0.8 0.2 1"'
6
7const svg = (w: number, h: number, body: string) =>
8 `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none">${body}</svg>`
9
10/**
11 * The window as one bar: fill grows from `from` to `to` (percent of the window),
12 * the hatch past `tick` is the auto-compact reserve, `pulse` breathes the fill,
13 * `shimmer` sweeps it while compacting.
14 */
15export function windowBar(o: {
16 from: number
17 to: number
18 tick?: number
19 tone: string
20 pulse?: boolean
21 shimmer?: boolean
22 width?: number
23 height?: number
24}): string {
25 const W = o.width ?? 1600
26 const H = o.height ?? 12
27 const bh = Math.min(6, H - 4)
28 const y = (H - bh) / 2
29 const x = (p: number) => (Math.max(0, Math.min(100, p)) / 100) * W
30 const to = x(o.to)
31 const from = x(o.from)
32 const parts: string[] = [
33 `<defs><pattern id="h" width="5" height="5" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="2" height="5" fill="rgba(128,128,128,0.5)"/></pattern>`,
34 `<clipPath id="c"><rect x="0" y="${y}" width="${to}" height="${bh}" rx="${bh / 2}">${from === to ? '' : `<animate attributeName="width" from="${from}" to="${to}" dur="0.7s" fill="freeze" ${EASE}/>`}</rect></clipPath>`,
35 `<linearGradient id="s" x1="0" x2="1"><stop offset="0" stop-color="#fff" stop-opacity="0"/><stop offset="0.5" stop-color="#fff" stop-opacity="0.45"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient></defs>`,
36 `<rect x="0" y="${y}" width="${W}" height="${bh}" rx="${bh / 2}" fill="${TRACK}"/>`,
37 ]
38 if (o.tick !== undefined && o.tick < 100) {
39 parts.push(`<rect x="${x(o.tick)}" y="${y}" width="${W - x(o.tick)}" height="${bh}" fill="url(#h)"/>`)
40 }
41 const pulse = o.pulse ? `<animate attributeName="opacity" values="1;0.55;1" dur="2.4s" repeatCount="indefinite"/>` : ''
42 parts.push(`<rect x="0" y="${y}" width="${W}" height="${bh}" fill="${o.tone}" clip-path="url(#c)">${pulse}</rect>`)
43 if (o.shimmer) {
44 const sw = Math.max(40, W * 0.15)
45 parts.push(
46 `<rect x="${-sw}" y="${y}" width="${sw}" height="${bh}" fill="url(#s)" clip-path="url(#c)"><animate attributeName="x" from="${-sw}" to="${Math.max(to, sw)}" dur="1.3s" repeatCount="indefinite"/></rect>`,
47 )
48 }
49 if (o.tick !== undefined && o.tick < 100) {
50 parts.push(`<rect x="${x(o.tick) - 1}" y="0" width="2" height="${H}" rx="1" fill="${TICK}"/>`)
51 }
52 return svg(W, H, parts.join(''))
53}
54
55/** What fills the used part, as one stacked bar; with `fade`, segments fade in left to right. */
56export function compositionBar(cats: readonly Category[], fade: boolean, width = 1600, height = 8): string {
57 const total = cats.reduce((a, c) => a + c.tokens, 0)
58 if (total <= 0) return svg(width, height, '')
59 const gap = 6
60 const minW = 8
61 const room = width - gap * Math.max(0, cats.length - 1)
62 let x = 0
63 const parts = cats.map((c, i) => {
64 const w = Math.max(minW, (c.tokens / total) * room)
65 const at = Math.min(0.9, i * 0.08).toFixed(2)
66 const anim = fade ? `<animate attributeName="opacity" values="0;0;1" keyTimes="0;${at};1" dur="${(0.5 + Number(at)).toFixed(2)}s" fill="freeze"/>` : ''
67 const rect = `<rect x="${x.toFixed(1)}" y="0" width="${w.toFixed(1)}" height="${height}" rx="2" fill="${c.color}">${anim}</rect>`
68 x += w + gap
69 return rect
70 })
71 return svg(Math.max(width, Math.ceil(x - gap)), height, parts.join(''))
72}
73
74/** Context over the session: area, line drawn in, compaction markers, the auto-compact line. */
75export function sparkline(points: readonly Point[], window: number, limit: number | undefined, width = 360, height = 96): string {
76 if (points.length < 2) return svg(width, height, '')
77 const pad = 4
78 const x = (i: number) => (i / (points.length - 1)) * (width - pad * 2) + pad
79 const y = (t: number) => height - pad - (Math.min(t, window) / window) * (height - pad * 2)
80 const line = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(p.tokens).toFixed(1)}`).join(' ')
81 const area = `${line} L${x(points.length - 1).toFixed(1)},${height - pad} L${pad},${height - pad} Z`
82 const parts: string[] = []
83 if (limit !== undefined) {
84 parts.push(`<line x1="0" x2="${width}" y1="${y(limit).toFixed(1)}" y2="${y(limit).toFixed(1)}" stroke="#a3a097" stroke-width="1" stroke-dasharray="3 3"/>`)
85 }
86 parts.push(`<path d="${area}" fill="#6f9be0" fill-opacity="0.14"><animate attributeName="fill-opacity" values="0;0.14" dur="0.9s" fill="freeze"/></path>`)
87 parts.push(
88 `<path d="${line}" fill="none" stroke="#6f9be0" stroke-width="1.8" stroke-linejoin="round" pathLength="1" stroke-dasharray="1" stroke-dashoffset="0"><animate attributeName="stroke-dashoffset" from="1" to="0" dur="0.9s" fill="freeze" ${EASE}/></path>`,
89 )
90 points.forEach((p, i) => {
91 if (!p.isCompaction || i === 0) return
92 const prev = points[i - 1]!
93 parts.push(`<line x1="${x(i).toFixed(1)}" x2="${x(i).toFixed(1)}" y1="${y(prev.tokens).toFixed(1)}" y2="${height - pad}" stroke="#d97757" stroke-width="1" stroke-dasharray="2 3"/>`)
94 parts.push(`<circle cx="${x(i - 1).toFixed(1)}" cy="${y(prev.tokens).toFixed(1)}" r="3.5" fill="#d97757"/>`)
95 })
96 const last = points[points.length - 1]!
97 parts.push(`<circle cx="${x(points.length - 1).toFixed(1)}" cy="${y(last.tokens).toFixed(1)}" r="3.5" fill="#e8e6dc" stroke="#6f9be0" stroke-width="1.5"/>`)
98 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${parts.join('')}</svg>`
99}
100
101/** A small filled bar for a ranked row: `share` of the row's width. */
102export function rankBar(share: number, color: string, width = 600, height = 4): string {
103 const w = Math.max(4, Math.min(1, share) * width)
104 return svg(
105 width,
106 height,
107 `<rect x="0" y="0" width="${width}" height="${height}" rx="2" fill="${TRACK}"/><rect x="0" y="0" width="${w.toFixed(1)}" height="${height}" rx="2" fill="${color}"><animate attributeName="width" from="0" to="${w.toFixed(1)}" dur="0.6s" fill="freeze" ${EASE}/></rect>`,
108 )
109}
110
111hooks/click-area.tsx 16 lines1import type { ClientModule, JsonValue } from 'claude-code'
2
3/**
4 * An empty region laid over the band: a click anywhere on it asks the hooks module
5 * to open or close the breakdown. What shows through is drawn by the band itself.
6 */
7const ClickArea: ClientModule<JsonValue> = (_props, surface) => {
8 surface.onPointer(e => {
9 if (e.type === 'down' && e.button !== 'right' && e.button !== 'middle') surface.post({ type: 'toggle' })
10 })
11 const { Box } = surface.elements
12 return <Box flexGrow={1} />
13}
14
15export default ClickArea
16types/index.d.ts 72 lines1export type Reading = { tokens?: number; window: number; percent?: number }
2
3/** `isGap`: the turns before it went unwatched, so no growth is read across it. */
4export type Point = { tokens: number; isCompaction?: true; isGap?: true }
5
6export type Category = { name: string; tokens: number; color: string }
7
8export type FixedCost = { kind: string; name: string; tokens: number; color: string }
9
10export type Breakdown = {
11 used: Category[]
12 threshold?: number
13 isAutoCompactEnabled: boolean
14 fixed: FixedCost[]
15 isExact: boolean
16 /** The breakdown's own total: shown, marked "~", while Claude Code reports no token count. */
17 estimate: number
18 messages?: number
19}
20
21export type Compaction = {
22 at: number
23 trigger: string
24 before?: number
25 after?: number
26 focus?: string
27 snapshot?: string
28}
29
30export type Phase = 'idle' | 'compacting' | 'compacted'
31
32export type Tab = 'overview' | 'settings'
33
34export type ControlSettings = {
35 showBand: boolean
36 startExpanded: boolean
37 openPaneOnStart: boolean
38 warnAt: number
39 alertAt: number
40 toastOnAlert: boolean
41 averageOver: number
42 exactCounts: boolean
43 snapshot: boolean
44 snapshotGitignore: boolean
45 arrowTooltip: boolean
46}
47
48declare module 'claude-code' {
49 interface PluginState {
50 'context-control': {
51 reading: Reading | null
52 history: Point[]
53 breakdown: Breakdown | null
54 compactions: Compaction[]
55 phase: Phase
56 expanded: boolean
57 composing: boolean
58 draft: string
59 tab: Tab
60 settings: ControlSettings
61 shownFill: number
62 changedAt: number
63 breakdownAt: number
64 toggledAt: number
65 revealFrame: number
66 turnCount: number | null
67 isAlerted: boolean
68 error: string
69 }
70 }
71}
72