A ring per active session above the prompt, filled by how much of its context window is used; newest activity first, hover for the name

A Claude Code mod that shows how full each of your sessions' context windows is, as a row of rings above the prompt. The session you were active in most recently comes first. Point at a ring to see the session's name and its cache, like Fix login bug · 1hr, 7m left; point at a subagent's dot to see its name and size.
/compact. The ring drops to the compacted size right away, before the next reply reports the real one.Explore codebase · 410K of 500K (82%).+N; point at it to see their names. This session's ring always shows.On the terminal the rings are drawn as ○ ◔ ◑ ◕ ●.
At the prompt of a terminal session:
/plugin install context-rings --marketplace nvsravank/context-rings
Each is a row in the mod's settings in /config.
| Setting | Default | Choices |
|---|---|---|
| Session context window | 1M | 100K to 1M |
| Session ring turns yellow at | 50% | 30% to 90% |
| Session ring turns red at | 80% | 50% to 95% |
| Context used on hover | Off | Off, Tokens, Tokens and %, Tokens, limit and % |
| Subagent limit | 500K | 100K to 1M |
| Subagent dot appears (yellow) at | 75% | 30% to 90% |
| Subagent dot turns red (and toasts) at | 90% | 50% to 95% |
| 1-hour cache: warn before it expires | 10m | Off, 5m to 30m |
| 5-minute cache: warn before it expires | 1m | Off, 30s to 2m |
| Cache warning only for sessions over | 500K | Any, 100K to 1M |
It sends nothing: no network calls. It does not read the conversation of the session it runs in through Claude Code's API. It reads Claude Code's own files about your sessions, on your machine, to find each session's name and context size.
What it reads, every 5 seconds and after each turn:
| What | Why |
|---|---|
~/.claude/sessions/*.json | Which sessions are running, their names, folders and whether they are working |
~/.claude/projects/**/*.jsonl (the last 1 MB of each changed in the last hour) | The context size the last reply or compaction reported, when the last message and reply came, and the prompt cache's lifetime |
~/.claude/projects/**/custom-title.json, subagents/*.meta.json | Session titles and subagent descriptions |
What it runs (read-only, no shell except the first):
| Command | Why |
|---|---|
sh -c 'printf %s "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"' | Once, to find Claude Code's folder |
ps -o pid= -p <pids> | Which session processes are still running |
find ~/.claude/projects … -exec stat -f '%m %N' | Which transcripts changed, and when |
tail -c 1000000 <transcripts> | The end of each changed transcript |
What it writes: only its own store in Claude Code's plugin data, holding recent session names (so a closed session keeps its title) and which subagents and cache warnings were already toasted. Its hooks pass every event through unchanged.
Uninstall with /plugin uninstall context-rings; nothing is left behind but that store.
MIT
hooks/register.tsx 424 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Ring, Sub } from '../types'
5import {
6 K,
7 baseName,
8 PULSE_MS,
9 cacheInfo,
10 cacheToast,
11 cacheWarning,
12 capRings,
13 fmt,
14 folderOrder,
15 glyph,
16 lastContextTokens,
17 lastMessageAt,
18 level,
19 moreLabel,
20 parsePct,
21 parseSize,
22 pctOf,
23 parseContextShow,
24 parseStat,
25 parseWait,
26 projectDir,
27 ringLabel,
28 ringsSvg,
29 subLabel,
30 splitTail,
31} from './parse'
32import type { CacheWarn, ContextShow, Scale, TranscriptFile } from './parse'
33
34type Engine = EngineInterface
35
36// How often every session's files are read again.
37const POLL_MS = 5000
38// A session shows this long after its last message, running or not: the prompt cache's hour.
39const RECENT_MS = 60 * 60 * 1000
40// A subagent whose transcript has not moved in this long is taken as finished.
41const SUB_ACTIVE_MS = 10 * 60 * 1000
42// How much of each transcript's end is read for its last response's usage.
43const TAIL_BYTES = 1000000
44// Files per tail call, so one call's output stays under process.run's 4 MiB.
45const TAIL_BATCH = 3
46const FOLDER_KEY = 'folder'
47
48const c = { ok: 'success', warn: 'warning', bad: 'error', chip: 'suggestion' } as const
49
50// --- preferences: a change reloads the module, so register sets them again ---
51let main: Scale = { limit: 1000 * K, yellow: 50, red: 80 }
52let sub: Scale = { limit: 500 * K, yellow: 75, red: 90 }
53let show: ContextShow = 'off'
54let warn: CacheWarn = { hour: 10 * 60 * 1000, fiveMin: 60 * 1000, minTokens: 500 * K }
55
56const rings = atom({ plugin: 'context-rings', key: 'rings' } as const, [])
57// The chip's view: '' is this session's folder (where it starts), ALL every folder, else a folder.
58const folder = atom({ plugin: 'context-rings', key: 'folder' } as const, '')
59const ALL = '*'
60// Flips each second while a ring pulses; only the terminal reads it (the SVG animates itself).
61const blink = atom({ plugin: 'context-rings', key: 'blink' } as const, false)
62
63type Live = { pid: number; sessionId: string; cwd: string; name?: string; status?: string; updatedAt: number }
64type Known = { name?: string; cwd?: string }
65
66let configDir = ''
67const tokensByPath = new Map<string, { mtime: number; tokens: number; msgAt?: number; cacheTtl?: number; cacheAt?: number; cwd?: string }>()
68const subNames = new Map<string, string>()
69
70async function findConfigDir($: Engine): Promise<string> {
71 if (configDir) return configDir
72 const { stdout } = await $.process.run(['/bin/sh', '-c', 'printf %s "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"'])
73 configDir = stdout.trim()
74 return configDir
75}
76
77async function readLive($: Engine, dir: string): Promise<Live[]> {
78 const entries = await $.fs.list(`${dir}/sessions`).catch(() => [])
79 const out: Live[] = []
80 for (const entry of entries) {
81 if (entry.kind !== 'file' || !/^\d+\.json$/.test(entry.name)) continue
82 try {
83 const j = JSON.parse(await $.fs.read(`${dir}/sessions/${entry.name}`))
84 if (typeof j.sessionId !== 'string' || typeof j.pid !== 'number') continue
85 out.push({
86 pid: j.pid,
87 sessionId: j.sessionId,
88 cwd: String(j.cwd ?? ''),
89 name: typeof j.name === 'string' ? j.name : undefined,
90 status: typeof j.status === 'string' ? j.status : undefined,
91 updatedAt: Number(j.statusUpdatedAt ?? j.updatedAt ?? 0),
92 })
93 } catch {
94 // A file being rewritten right now: next poll.
95 }
96 }
97 if (out.length === 0) return out
98 // A registry file can outlive a crashed process: keep only pids still running.
99 const ps = await $.process.run(['/bin/ps', '-o', 'pid=', '-p', out.map(l => l.pid).join(',')])
100 const alive = new Set(ps.stdout.split('\n').map(s => Number(s.trim())).filter(Boolean))
101 return out.filter(l => alive.has(l.pid))
102}
103
104async function statTranscripts($: Engine, dir: string, live: readonly Live[]): Promise<TranscriptFile[]> {
105 const names = live.flatMap(l => ['-o', '-name', `${l.sessionId}.jsonl`])
106 const minutes = String(Math.ceil(RECENT_MS / 60000))
107 const { stdout } = await $.process.run([
108 '/usr/bin/find', `${dir}/projects`, '-maxdepth', '4', '-name', '*.jsonl',
109 '(', '-mmin', `-${minutes}`, ...names, ')',
110 '-exec', '/usr/bin/stat', '-f', '%m %N', '{}', '+',
111 ])
112 return parseStat(stdout)
113}
114
115async function readTokens($: Engine, files: readonly TranscriptFile[]) {
116 const stale = files.filter(f => tokensByPath.get(f.path)?.mtime !== f.mtime)
117 for (let i = 0; i < stale.length; i += TAIL_BATCH) {
118 const batch = stale.slice(i, i + TAIL_BATCH)
119 const paths = batch.map(f => f.path)
120 const { stdout } = await $.process.run(['/usr/bin/tail', '-c', String(TAIL_BYTES), ...paths])
121 const texts = splitTail(stdout, paths)
122 for (const f of batch) {
123 const text = texts.get(f.path) ?? ''
124 const before = tokensByPath.get(f.path)
125 const cache = cacheInfo(text)
126 const cwd = /"cwd":"([^"]+)"/.exec(text)?.[1]
127 tokensByPath.set(f.path, {
128 mtime: f.mtime,
129 tokens: lastContextTokens(text) ?? before?.tokens ?? 0,
130 msgAt: lastMessageAt(text) ?? before?.msgAt,
131 cacheTtl: cache.ttl ?? before?.cacheTtl,
132 cacheAt: cache.at ?? before?.cacheAt,
133 cwd: cwd ?? before?.cwd,
134 })
135 }
136 }
137}
138
139async function subName($: Engine, path: string): Promise<string> {
140 const known = subNames.get(path)
141 if (known) return known
142 let name = 'subagent'
143 try {
144 const meta = JSON.parse(await $.fs.read(path.replace(/\.jsonl$/, '.meta.json')))
145 name = String(meta.description ?? meta.agentType ?? name)
146 } catch {
147 // No meta file: keep the plain name.
148 }
149 subNames.set(path, name)
150 return name
151}
152
153async function savedTitle($: Engine, mainPath: string, sessionId: string): Promise<string | undefined> {
154 try {
155 const j = JSON.parse(await $.fs.read(mainPath.replace(/\.jsonl$/, '') + '/custom-title.json'))
156 return typeof j.customTitle === 'string' ? j.customTitle : undefined
157 } catch {
158 return undefined
159 }
160}
161
162async function alertSubs($: Engine, subs: readonly { ring: Ring; sub: Sub; mtime: number }[], now: number) {
163 // A toast when a subagent's dot turns red.
164 const due = subs.filter(s => now - s.mtime < SUB_ACTIVE_MS && pctOf(s.sub.tokens, sub) >= sub.red)
165 await toastOnce(
166 $,
167 due.map(({ ring, sub: s }) => ({ key: s.id, text: `⚠ ${ring.name} › ${s.name}: ${fmt(s.tokens)} of its ${fmt(sub.limit)} limit` })),
168 now,
169 )
170}
171
172async function alertCaches($: Engine, all: readonly Ring[], now: number) {
173 // A toast when a session's cache warning starts: once per session per cache lifetime.
174 const due = all.filter(r => r.cache === 'warn')
175 await toastOnce($, due.map(r => ({ key: `cache:${r.id}:${r.cacheWarnAt}`, text: cacheToast(r, now) })), now)
176}
177
178async function toastOnce($: Engine, due: readonly { key: string; text: string }[], now: number) {
179 if (due.length === 0) return
180 // Every open session runs this: the shared store says what was already toasted.
181 const alerted = ((await $.store.get('alerted')) ?? {}) as Record<string, number>
182 let isChanged = false
183 for (const { key, text } of due) {
184 if (alerted[key]) continue
185 alerted[key] = now
186 isChanged = true
187 $.ui.toast(text, { timeoutMs: 8000 })
188 }
189 if (!isChanged) return
190 for (const [id, at] of Object.entries(alerted)) if (now - at > 24 * RECENT_MS) delete alerted[id]
191 await $.store.set('alerted', alerted)
192}
193
194async function refresh($: Engine) {
195 const dir = await findConfigDir($)
196 const now = await $.clock.now()
197 const currentId = await $.session.id()
198 const live = await readLive($, dir)
199 const files = await statTranscripts($, dir, live)
200 await readTokens($, files)
201
202 const known = ((await $.store.get('known')) ?? {}) as Record<string, Known>
203 const liveById = new Map(live.map(l => [l.sessionId, l]))
204 const mains = new Map(files.filter(f => f.kind === 'main').map(f => [f.sessionId, f]))
205 const ids = new Set([...liveById.keys(), ...mains.keys()])
206
207 const out: Ring[] = []
208 for (const id of ids) {
209 const l = liveById.get(id)
210 const f = mains.get(id)
211 const seen = f ? tokensByPath.get(f.path) : undefined
212 // The last message, not the file's time: opening a session writes to it and starts its process.
213 const lastAt = f ? (seen?.msgAt ?? 0) : (l?.updatedAt ?? 0)
214 const isCurrent = id === currentId
215 const isBusy = l?.status === 'busy'
216 if (!isCurrent && !isBusy && now - lastAt > RECENT_MS) continue
217 const cwd = l?.cwd || seen?.cwd || known[id]?.cwd || ''
218 const name =
219 l?.name || (f ? await savedTitle($, f.path, id) : undefined) || known[id]?.name || `${baseName(cwd) || 'session'} · ${id.slice(0, 8)}`
220 known[id] = { name, cwd }
221 const cacheTtl = seen?.cacheTtl ?? 0
222 const cacheAt = seen?.cacheAt ?? 0
223 out.push({
224 id, name, cwd, tokens: seen?.tokens ?? 0, isLive: !!l, isBusy, isCurrent, lastAt, subs: [],
225 cacheTtl, cacheAt, ...cacheFields(isBusy ? undefined : cacheWarning(cacheTtl, cacheAt, seen?.tokens ?? 0, warn, now)),
226 })
227 }
228
229 const byId = new Map(out.map(r => [r.id, r]))
230 const subRows: { ring: Ring; sub: Sub; mtime: number }[] = []
231 for (const f of files) {
232 if (f.kind !== 'sub') continue
233 const ring = byId.get(f.sessionId)
234 const tokens = tokensByPath.get(f.path)?.tokens ?? 0
235 // A subagent shows once its dot would be yellow, and only while active.
236 if (!ring || pctOf(tokens, sub) < sub.yellow || now - f.mtime > SUB_ACTIVE_MS) continue
237 const row = { id: f.agentId, name: await subName($, f.path), tokens }
238 ring.subs.push(row)
239 subRows.push({ ring, sub: row, mtime: f.mtime })
240 }
241
242 out.sort((a, b) => b.lastAt - a.lastAt)
243 await alertSubs($, subRows, now)
244 await alertCaches($, out, now)
245
246 // Keep names of sessions seen lately, so a closed one still has its title.
247 const keep = Object.fromEntries(Object.entries(known).filter(([id]) => ids.has(id)).slice(-200))
248 await $.store.set('known', keep)
249
250 const prev = await read($, rings)
251 if (JSON.stringify(prev) !== JSON.stringify(out)) await update($, rings, () => out)
252 if (out.some(r => isPulsing(r, now))) startBlink($)
253}
254
255function cacheFields(w: ReturnType<typeof cacheWarning> | undefined) {
256 // A working session's cache is being refreshed as it goes.
257 return w ? { cache: w.cache, cacheWarnAt: w.warnAt, cacheArc: w.arc } : { cache: 'warm' as const, cacheWarnAt: 0, cacheArc: 0 }
258}
259
260function isPulsing(r: Ring, now: number): boolean {
261 return r.cache === 'warn' && now - r.cacheWarnAt < PULSE_MS
262}
263
264let blinkTimer: { cancel: () => void } | null = null
265function startBlink($: Engine) {
266 if (blinkTimer) return
267 const tick = () => {
268 blinkTimer = $.clock.after(1000, () => {
269 void (async () => {
270 const now = await $.clock.now()
271 if (!(await read($, rings)).some(r => isPulsing(r, now))) {
272 blinkTimer = null
273 await update($, blink, () => false)
274 return
275 }
276 await update($, blink, isLit => !isLit)
277 tick()
278 })().catch(() => (blinkTimer = null))
279 })
280 }
281 tick()
282}
283
284let pollTimer: { cancel: () => void } | null = null
285function schedule($: Engine) {
286 if (pollTimer) pollTimer.cancel()
287 pollTimer = $.clock.after(POLL_MS, () => {
288 void refresh($)
289 .catch(() => undefined)
290 .then(() => schedule($))
291 })
292}
293
294let lastCycleAt = 0
295
296/** The folder the chip shows: this session's folder for '', or ALL. */
297function viewOf(picked: string, all: readonly Ring[]): string {
298 return picked || all.find(r => r.isCurrent)?.cwd || ALL
299}
300
301/** The chip cycles this session's folder → All → every other folder, A to Z → this folder. */
302async function cycleFolder($: Engine) {
303 const now = await $.clock.now()
304 if (now - lastCycleAt < 400) return
305 lastCycleAt = now
306 const all = await read($, rings)
307 const here = all.find(r => r.isCurrent)?.cwd ?? ''
308 const order = folderOrder(all, ALL)
309 await update($, folder, cur => {
310 const next = order[(order.indexOf(viewOf(cur, all)) + 1) % order.length]!
311 return next === here ? '' : next
312 })
313}
314
315export const register: Register = (on, options) => {
316 main = { limit: parseSize(options.contextWindow, 1000 * K), yellow: parsePct(options.mainYellow, 50), red: parsePct(options.mainRed, 80) }
317 sub = { limit: parseSize(options.subagentLimit, 500 * K), yellow: parsePct(options.subagentYellow, 75), red: parsePct(options.subagentRed, 90) }
318 show = parseContextShow(options.hoverContext)
319 warn = {
320 hour: parseWait(options.cacheWarnHour, 10 * 60 * 1000),
321 fiveMin: parseWait(options.cacheWarnFiveMin, 60 * 1000),
322 minTokens: options.cacheWarnMin === 'Any' ? 0 : parseSize(options.cacheWarnMin, 500 * K),
323 }
324
325 on('session.start', async ($, e, next) => {
326 void refresh($).catch(() => undefined)
327 schedule($)
328 return next(e)
329 })
330
331 on('turn.complete', async ($, e, next) => {
332 void refresh($).catch(() => undefined)
333 return next(e)
334 })
335
336 // Presses arrive by onPress, ui.press or both (desktop); either cycles the chip once.
337 on('ui.press', { component: 'AbovePrompt' }, async ($, e, next) => {
338 if (e.element !== FOLDER_KEY) return next(e)
339 await cycleFolder($)
340 return { element: e.element }
341 })
342
343 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
344 const all = await read($, rings)
345 if (e.props.hasSurvey || all.length === 0) return next(e)
346 const view = viewOf(await read($, folder), all)
347 const { shown, hidden } = capRings(view === ALL ? all : all.filter(r => r.cwd === view))
348 const now = await $.clock.now()
349 const ui = $.ui.resolve(e)
350 const { Box, Text, Button } = ui
351 const chip = <Button key={FOLDER_KEY} label={view === ALL ? 'All' : baseName(view)} onPress={() => void cycleFolder($)} />
352
353 // Desktop: one interactive SVG; pointing at a ring reveals its label inside it (CSS :hover).
354 if (e.surface !== 'terminal' && 'Svg' in ui) {
355 const { Svg } = ui
356 const svg = ringsSvg(shown, main, sub, now, hidden, show)
357 return (
358 <Box flexDirection="row" alignItems="center">
359 {chip}
360 <Box marginLeft={1}>
361 <Svg source={svg.source} width={svg.width} height={svg.height} isInteractive alt={`${shown.length + hidden.length} sessions' context`} />
362 </Box>
363 </Box>
364 )
365 }
366
367 // Terminal: glyphs; each is a hover group that reveals its label at the row's end.
368 const isBlinkOn = await read($, blink)
369 const scope = (r: Ring) => `ring-${r.id.slice(0, 20)}`
370 const subScope = (r: Ring, s: Sub) => `sub-${r.id.slice(0, 8)}-${s.id.slice(0, 20)}`
371 return (
372 <Box flexDirection="row" width={e.props.bodyColumns}>
373 {chip}
374 {shown.map(r => {
375 const pct = pctOf(r.tokens, main)
376 return (
377 <Box key={r.id} marginLeft={1} hover={{ scope: scope(r) }}>
378 <Text color={c[level(pct, main)]} dimColor={!r.isLive} bold={r.isCurrent} inverse={isPulsing(r, now) && isBlinkOn}>
379 {glyph(pct)}
380 {r.cache === 'warn' ? '⧗' : ''}
381 </Text>
382 {r.subs.map(s => (
383 <Box key={s.id} hover={{ scope: subScope(r, s) }}>
384 <Text color={c[level(pctOf(s.tokens, sub), sub)]} dimColor={!r.isLive}>
385 •
386 </Text>
387 </Box>
388 ))}
389 </Box>
390 )
391 })}
392 {hidden.length > 0 && (
393 <Box key="more" marginLeft={1} hover={{ scope: 'ring-more' }}>
394 <Text dimColor>+{hidden.length}</Text>
395 </Box>
396 )}
397 {hidden.length > 0 && (
398 <Box key="label-more" marginLeft={2} flexShrink={1} display="none" hover={{ scope: 'ring-more', display: 'flex' }}>
399 <Text dimColor wrap="truncate-end">
400 {moreLabel(hidden)}
401 </Text>
402 </Box>
403 )}
404 {shown.map(r => (
405 <Box key={`label-${r.id}`} marginLeft={2} flexShrink={1} display="none" hover={{ scope: scope(r), display: 'flex' }}>
406 <Text dimColor wrap="truncate-end">
407 {ringLabel(r, main, now, show)}
408 </Text>
409 </Box>
410 ))}
411 {shown.flatMap(r =>
412 r.subs.map(s => (
413 <Box key={`label-${r.id}-${s.id}`} marginLeft={2} flexShrink={1} display="none" hover={{ scope: subScope(r, s), display: 'flex' }}>
414 <Text dimColor wrap="truncate-end">
415 {subLabel(s, sub)}
416 </Text>
417 </Box>
418 )),
419 )}
420 </Box>
421 )
422 })
423}
424hooks/parse.ts 405 lines1// Pure helpers: no `$` here, so the validator only has to follow register.tsx.
2
3import type { Ring, Sub } from '../types'
4
5export const K = 1000
6
7/** "100K" → 100000, "1M" → 1000000; anything else → fallback. */
8export function parseSize(text: unknown, fallback: number): number {
9 if (typeof text !== 'string') return fallback
10 const m = /^(\d+)([KM])$/.exec(text)
11 if (!m) return fallback
12 return Number(m[1]) * (m[2] === 'M' ? 1000 * K : K)
13}
14
15/** 340000 → "340K", 1000000 → "1M". */
16export function fmt(tokens: number): string {
17 if (tokens >= 1000 * K) return `${+(tokens / (1000 * K)).toFixed(2)}M`
18 return `${Math.round(tokens / K)}K`
19}
20
21export function baseName(path: string): string {
22 const parts = path.split('/').filter(Boolean)
23 return parts[parts.length - 1] ?? path
24}
25
26/** The folder name Claude Code files a project's transcripts under. */
27export function projectDir(cwd: string): string {
28 return cwd.replace(/[^A-Za-z0-9]/g, '-')
29}
30
31export type TranscriptFile =
32 | { kind: 'main'; path: string; mtime: number; sessionId: string }
33 | { kind: 'sub'; path: string; mtime: number; sessionId: string; agentId: string }
34
35/** Lines of `stat -f '%m %N'`: seconds, a space, the path. */
36export function parseStat(stdout: string): TranscriptFile[] {
37 const out: TranscriptFile[] = []
38 for (const line of stdout.split('\n')) {
39 const i = line.indexOf(' ')
40 if (i <= 0) continue
41 const mtime = Number(line.slice(0, i)) * 1000
42 const path = line.slice(i + 1)
43 const sub = /\/([0-9a-f-]{36})\/subagents\/agent-([A-Za-z0-9_-]+)\.jsonl$/.exec(path)
44 if (sub) {
45 out.push({ kind: 'sub', path, mtime, sessionId: sub[1]!, agentId: sub[2]! })
46 continue
47 }
48 const main = /\/([0-9a-f-]{36})\.jsonl$/.exec(path)
49 if (main) out.push({ kind: 'main', path, mtime, sessionId: main[1]! })
50 }
51 return out
52}
53
54/**
55 * Splits the output of `tail -c N a b c` into each file's text. With more than
56 * one file tail heads each with `==> path <==`; with one it writes none.
57 */
58export function splitTail(stdout: string, paths: readonly string[]): Map<string, string> {
59 const map = new Map<string, string>()
60 if (paths.length === 1) {
61 map.set(paths[0]!, stdout)
62 return map
63 }
64 const re = /^==> (.*) <==$/gm
65 const heads: { path: string; start: number; end: number }[] = []
66 let m: RegExpExecArray | null
67 while ((m = re.exec(stdout))) heads.push({ path: m[1]!, start: m.index, end: re.lastIndex })
68 heads.forEach((h, i) => {
69 const stop = i + 1 < heads.length ? heads[i + 1]!.start : stdout.length
70 map.set(h.path, stdout.slice(h.end, stop))
71 })
72 return map
73}
74
75/**
76 * The context the last assistant response was answered over: uncached input,
77 * cache writes and cache reads together. A compaction after the last response
78 * counts as its `postTokens`, until the next response reports the real figure.
79 * Undefined when the tail holds neither.
80 */
81export function lastContextTokens(text: string): number | undefined {
82 const lines = text.split('\n')
83 for (let i = lines.length - 1; i >= 0; i--) {
84 const line = lines[i]!
85 const isCompact = line.includes('"compact_boundary"')
86 if (!isCompact && (!line.includes('"usage"') || !line.includes('"assistant"'))) continue
87 try {
88 const row = JSON.parse(line)
89 if (isCompact && row?.subtype === 'compact_boundary') {
90 const post = row?.compactMetadata?.postTokens
91 if (typeof post === 'number') return post
92 continue
93 }
94 const u = row?.message?.usage
95 if (!u || row?.message?.role !== 'assistant') continue
96 return (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0)
97 } catch {
98 // The tail's first line is usually cut mid-row.
99 }
100 }
101 return undefined
102}
103
104/**
105 * When the last message, yours or the model's, was written: the newest
106 * timestamped user or assistant row. Opening a session in the app appends
107 * rows of its own (mode, title) without timestamps, so they do not count.
108 * Undefined when the tail holds none.
109 */
110export function lastMessageAt(text: string): number | undefined {
111 const lines = text.split('\n')
112 for (let i = lines.length - 1; i >= 0; i--) {
113 const line = lines[i]!
114 if (!line.includes('"timestamp"') || !/"type":"(user|assistant)"/.test(line)) continue
115 try {
116 const row = JSON.parse(line)
117 if (row?.type !== 'user' && row?.type !== 'assistant') continue
118 const at = Date.parse(row.timestamp)
119 if (!Number.isNaN(at)) return at
120 } catch {
121 // The tail's first line is usually cut mid-row.
122 }
123 }
124 return undefined
125}
126
127/**
128 * The prompt cache the last replies wrote: its lifetime, from the newest reply
129 * that wrote any (1h or 5m), and when the last reply came, which restarts it.
130 * Each is undefined when the tail does not say.
131 */
132export function cacheInfo(text: string): { ttl?: number; at?: number } {
133 const out: { ttl?: number; at?: number } = {}
134 const lines = text.split('\n')
135 for (let i = lines.length - 1; i >= 0 && (out.ttl === undefined || out.at === undefined); i--) {
136 const line = lines[i]!
137 if (!line.includes('"usage"') || !line.includes('"assistant"')) continue
138 try {
139 const row = JSON.parse(line)
140 if (row?.message?.role !== 'assistant') continue
141 const at = Date.parse(row.timestamp)
142 if (out.at === undefined && !Number.isNaN(at)) out.at = at
143 const made = row.message.usage?.cache_creation
144 if (out.ttl === undefined && made) {
145 if (made.ephemeral_1h_input_tokens > 0) out.ttl = HOUR
146 else if (made.ephemeral_5m_input_tokens > 0) out.ttl = 5 * MINUTE
147 }
148 } catch {
149 // The tail's first line is usually cut mid-row.
150 }
151 }
152 return out
153}
154
155const MINUTE = 60 * 1000
156const HOUR = 60 * MINUTE
157
158/** "10m" → 600000, "30s" → 30000, "Off" → 0; anything else → fallback. */
159export function parseWait(text: unknown, fallback: number): number {
160 if (text === 'Off') return 0
161 const m = typeof text === 'string' ? /^(\d+)([sm])$/.exec(text) : null
162 return m ? Number(m[1]) * (m[2] === 'm' ? MINUTE : 1000) : fallback
163}
164
165/**
166 * How long before each cache lifetime runs out its warning starts (0 is off),
167 * and the smallest session it is worth warning about.
168 */
169export type CacheWarn = { hour: number; fiveMin: number; minTokens: number }
170
171// A ring pulses this long when its warning starts, then shows the arc alone.
172export const PULSE_MS = 10 * 1000
173// The arc's steps, so a redraw comes every 1/40th of the warning window, not every poll.
174const ARC_STEPS = 40
175
176/**
177 * The cache's state for one session: warm, in its warning window (only for a
178 * session of at least `minTokens`), expired, or not known. In the window,
179 * `warnAt` is when it began and `arc` the share of it left, in steps.
180 */
181export function cacheWarning(
182 ttl: number | undefined,
183 at: number | undefined,
184 tokens: number,
185 warn: CacheWarn,
186 now: number,
187): { cache: Ring['cache']; warnAt: number; arc: number } {
188 if (!ttl || !at) return { cache: 'none', warnAt: 0, arc: 0 }
189 const left = at + ttl - now
190 if (left <= 0) return { cache: 'cold', warnAt: 0, arc: 0 }
191 const lead = ttl >= HOUR ? warn.hour : warn.fiveMin
192 if (lead <= 0 || left > lead || tokens < warn.minTokens) return { cache: 'warm', warnAt: 0, arc: 0 }
193 return { cache: 'warn', warnAt: at + ttl - lead, arc: Math.ceil((left / lead) * ARC_STEPS) / ARC_STEPS }
194}
195
196/** The toast when a session's warning starts. */
197export function cacheToast(r: Ring, now: number): string {
198 const life = r.cacheTtl >= HOUR ? '1h' : '5m'
199 return `⏳ ${r.name} · ${baseName(r.cwd)}: its ${life} cache of ${fmt(r.tokens)} expires in ${until(r.cacheAt + r.cacheTtl - now)}. A message keeps it warm; /compact first to also shrink it.`
200}
201
202/** Five fill steps for the terminal, where there is no SVG. */
203export function glyph(pct: number): string {
204 if (pct < 12.5) return '○'
205 if (pct < 37.5) return '◔'
206 if (pct < 62.5) return '◑'
207 if (pct < 87.5) return '◕'
208 return '●'
209}
210
211/** A limit and the percentages of it where yellow and red begin. */
212export type Scale = { limit: number; yellow: number; red: number }
213
214export function pctOf(tokens: number, scale: Scale): number {
215 return Math.min(100, (tokens / scale.limit) * 100)
216}
217
218export function level(pct: number, scale: Scale): 'ok' | 'warn' | 'bad' {
219 return pct < scale.yellow ? 'ok' : pct < scale.red ? 'warn' : 'bad'
220}
221
222/** "65%" → 65; anything else → fallback. */
223export function parsePct(text: unknown, fallback: number): number {
224 const m = typeof text === 'string' ? /^(\d+)%$/.exec(text) : null
225 return m ? Number(m[1]) : fallback
226}
227
228const HEX = { ok: '#3fb950', warn: '#d29922', bad: '#f85149' } as const
229const ORANGE = '#f0883e'
230const RING = 24
231const DOT = 11
232const DOT_R = 4.5
233
234/** How much of a session's context its hover label shows. */
235export type ContextShow = 'off' | 'tokens' | 'pct' | 'full'
236
237/** The "Context used on hover" setting → what it shows; off unless set. */
238export function parseContextShow(text: unknown): ContextShow {
239 return text === 'Tokens' ? 'tokens' : text === 'Tokens and %' ? 'pct' : text === 'Tokens, limit and %' ? 'full' : 'off'
240}
241
242/** 620000 of 1M → "620K", "620K (62%)" or "620K of 1M (62%)". */
243function contextText(tokens: number, scale: Scale, show: ContextShow): string {
244 const pct = `(${Math.round(pctOf(tokens, scale))}%)`
245 if (show === 'tokens') return fmt(tokens)
246 if (show === 'pct') return `${fmt(tokens)} ${pct}`
247 if (show === 'full') return `${fmt(tokens)} of ${fmt(scale.limit)} ${pct}`
248 return ''
249}
250
251// Longest name a hover label shows before cutting it with "…".
252const NAME_MAX = 40
253
254export function shortName(name: string): string {
255 return name.length > NAME_MAX ? `${name.slice(0, NAME_MAX).trimEnd()}…` : name
256}
257
258/** What hovering a ring reveals: its name, the context if chosen, and its cache. */
259export function ringLabel(r: Ring, main: Scale, now: number, show: ContextShow = 'off'): string {
260 return [shortName(r.name), contextText(r.tokens, main, show), cacheText(r, now)].filter(Boolean).join(' · ')
261}
262
263/** What hovering a subagent's dot reveals: its name and size against the subagent limit. */
264export function subLabel(s: Sub, sub: Scale): string {
265 return `${shortName(s.name)} · ${contextText(s.tokens, sub, 'full')}`
266}
267
268function cacheText(r: Ring, now: number): string {
269 if (r.cache === 'none' || !r.cacheTtl) return ''
270 const left = r.cacheAt + r.cacheTtl - now
271 const life = r.cacheTtl >= HOUR ? '1hr' : '5min'
272 return left > 0 ? `${life}, ${until(left)} left` : `${life}, expired`
273}
274
275function until(ms: number): string {
276 const s = Math.max(0, Math.round(ms / 1000))
277 return s < 60 ? `${s}s` : `${Math.round(s / 60)}m`
278}
279
280/** One session's ring; its subagents' dots are drawn beside it by `ringsSvg`. */
281export function ringSvg(r: Ring, main: Scale, sub: Scale, now = 0): { source: string; width: number; height: number } {
282 const pct = pctOf(r.tokens, main)
283 const color = HEX[level(pct, main)]
284 const c = RING / 2
285 const rad = 9
286 const len = 2 * Math.PI * rad
287 const arcRad = 11.25
288 const arcLen = 2 * Math.PI * arcRad
289 // The pulse runs out by itself: it repeats only for what is left of its 10 seconds.
290 const pulses = r.cache === 'warn' ? Math.ceil((r.cacheWarnAt + PULSE_MS - now) / 1000) : 0
291 const parts = [
292 `<g opacity="${r.isLive ? 1 : 0.4}">`,
293 pulses > 0 ? `<animate attributeName="opacity" values="1;0.2;1" dur="1s" repeatCount="${pulses}"/>` : '',
294 `<circle cx="${c}" cy="${c}" r="${rad}" fill="none" stroke="#8b949e" stroke-opacity="0.3" stroke-width="3"/>`,
295 `<circle cx="${c}" cy="${c}" r="${rad}" fill="none" stroke="${color}" stroke-width="3" stroke-linecap="round"` +
296 ` stroke-dasharray="${((len * pct) / 100).toFixed(2)} ${len.toFixed(2)}" transform="rotate(-90 ${c} ${c})"/>`,
297 r.isCurrent ? `<circle cx="${c}" cy="${c}" r="2.5" fill="#8b949e"/>` : '',
298 r.isBusy
299 ? `<circle cx="${c}" cy="${c}" r="${rad}" fill="none" stroke="${color}" stroke-width="1" opacity="0.6">` +
300 `<animate attributeName="r" values="${rad};${rad + 2.5};${rad}" dur="1.6s" repeatCount="indefinite"/></circle>`
301 : '',
302 // The cache's countdown: an orange arc outside the ring, shrinking to nothing at expiry.
303 r.cache === 'warn'
304 ? `<circle cx="${c}" cy="${c}" r="${arcRad}" fill="none" stroke="${ORANGE}" stroke-width="1.5" stroke-linecap="round"` +
305 ` stroke-dasharray="${(arcLen * r.cacheArc).toFixed(2)} ${arcLen.toFixed(2)}" transform="rotate(-90 ${c} ${c})"/>`
306 : '',
307 `</g>`,
308 ]
309 const x = RING
310 return {
311 source: `<svg xmlns="http://www.w3.org/2000/svg" width="${x}" height="${RING}" viewBox="0 0 ${x} ${RING}">${parts.join('')}</svg>`,
312 width: x,
313 height: RING,
314 }
315}
316
317function esc(text: string): string {
318 return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
319}
320
321// Room for the hover label after the rings, in CSS pixels.
322const LABEL_W = 640
323
324// Most rings shown in the row; the rest fold into a "+N".
325export const MAX_RINGS = 10
326
327/**
328 * The first `max` rings (most recent first) and the rest. This session's ring
329 * always shows: when it is past the cap it takes the last place.
330 */
331export function capRings(rings: readonly Ring[], max = MAX_RINGS): { shown: Ring[]; hidden: Ring[] } {
332 if (rings.length <= max) return { shown: [...rings], hidden: [] }
333 const shown = rings.slice(0, max)
334 const current = rings.slice(max).find(r => r.isCurrent)
335 if (current) shown[max - 1] = current
336 return { shown, hidden: rings.filter(r => !shown.includes(r)) }
337}
338
339/** The chip's stops: this session's folder, then `all`, then every other folder by name. */
340export function folderOrder(rings: readonly Ring[], all: string): string[] {
341 const here = rings.find(r => r.isCurrent)?.cwd ?? ''
342 const others = [...new Set(rings.map(r => r.cwd).filter(cwd => cwd && cwd !== here))]
343 others.sort((a, b) => baseName(a).localeCompare(baseName(b)) || a.localeCompare(b))
344 return [...(here ? [here] : []), all, ...others]
345}
346
347/** What hovering the "+N" reveals: the names of the folded sessions. */
348export function moreLabel(hidden: readonly Ring[]): string {
349 return `${hidden.length} more: ${hidden.map(r => shortName(r.name)).join(', ')}`
350}
351
352/**
353 * Every ring in one interactive SVG. Pointing at a ring reveals its label,
354 * drawn in the same SVG after the last ring, by CSS :hover inside the frame.
355 */
356export function ringsSvg(
357 rings: readonly Ring[],
358 main: Scale,
359 sub: Scale,
360 now: number,
361 hidden: readonly Ring[] = [],
362 show: ContextShow = 'off',
363): { source: string; width: number; height: number } {
364 // Each ring and each subagent dot is its own hover target, with its own label.
365 const widthOf = (r: Ring) => RING + r.subs.length * DOT + 6
366 const moreW = hidden.length ? 8 * String(hidden.length).length + 16 : 0
367 const labelX = rings.reduce((w, r) => w + widthOf(r), 0) + moreW + 6
368 const label = (text: string) => `<text class="l" x="${labelX}" y="${RING / 2 + 4}">${esc(text)}</text>`
369 const groups: string[] = []
370 let x = 0
371 for (const r of rings) {
372 const inner = ringSvg(r, main, sub, now).source.replace(/^<svg[^>]*>/, '').replace(/<\/svg>$/, '')
373 groups.push(
374 `<g class="r"><rect x="${x}" y="0" width="${RING + (r.subs.length ? 0 : 6)}" height="${RING}" fill="transparent"/>` +
375 `<g transform="translate(${x} 0)">${inner}</g>${label(ringLabel(r, main, now, show))}</g>`,
376 )
377 let dx = x + RING
378 for (const s of r.subs) {
379 groups.push(
380 `<g class="r"><rect x="${dx}" y="0" width="${DOT}" height="${RING}" fill="transparent"/>` +
381 `<circle cx="${dx + DOT / 2}" cy="${RING / 2}" r="${DOT_R}" fill="${HEX[level(pctOf(s.tokens, sub), sub)]}" opacity="${r.isLive ? 1 : 0.4}"/>` +
382 `${label(subLabel(s, sub))}</g>`,
383 )
384 dx += DOT
385 }
386 x += widthOf(r)
387 }
388 if (hidden.length) {
389 groups.push(
390 `<g class="r"><rect x="${x}" y="0" width="${moreW}" height="${RING}" fill="transparent"/>` +
391 `<text class="m" x="${x}" y="${RING / 2 + 4}">+${hidden.length}</text>${label(moreLabel(hidden))}</g>`,
392 )
393 }
394 const width = labelX + LABEL_W
395 const style =
396 `<style>.l{visibility:hidden;font:12px -apple-system,system-ui,sans-serif;fill:#8b949e}` +
397 `.m{font:12px -apple-system,system-ui,sans-serif;fill:#8b949e}` +
398 `.r:hover .l{visibility:visible}.r{cursor:default}</style>`
399 return {
400 source: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${RING}" viewBox="0 0 ${width} ${RING}">${style}${groups.join('')}</svg>`,
401 width,
402 height: RING,
403 }
404}
405types/index.d.ts 27 lines1export type Sub = { id: string; name: string; tokens: number }
2
3export type Ring = {
4 id: string
5 name: string
6 cwd: string
7 tokens: number
8 isLive: boolean
9 isBusy: boolean
10 isCurrent: boolean
11 lastAt: number
12 subs: Sub[]
13 /** The prompt cache's lifetime in ms (0 unknown), when the last reply restarted it, and its state. */
14 cacheTtl: number
15 cacheAt: number
16 cache: 'warm' | 'warn' | 'cold' | 'none'
17 /** In the warning window: when it began, and the share of it left (the arc). */
18 cacheWarnAt: number
19 cacheArc: number
20}
21
22declare module 'claude-code' {
23 interface PluginState {
24 'context-rings': { rings: Ring[]; folder: string; blink: boolean }
25 }
26}
27