SLOPSHOPPER

context-meter

Context-window meter for every running Claude Code session, with Compact now, auto-compact and options

panebandcommandprocesstimer
v0.2.0MITupdated 2026-10-20sp1e/context-meter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · context-meter
│ ┃ context-meter ✕ › fix the failing auth test and add an audit log call │ ┃ [Compact] visas från 50% │ ┃ ⏺ Read(src/auth.ts) │ ┃ Inga aktiva sessioner just nu. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /context-meter │ ⎿ context-meter: Context-panelen dold. │ │ Context – Jämför ▾ Compact Auto 50% ○ ⚙ × ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Context – Jämför ▾ Compact Auto 50% ○ ⚙ ×
Pane · context-meter
[Compact] visas från 50% Inga aktiva sessioner just nu.
README

context-meter

A Claude Code mod (function-hook plugin) that shows how full the context window is, for this session and for every other session that is actively working.

The UI text is in Swedish.

What it draws

A band above the prompt, per session:

  • Context 15% +: this session's fill, colored green, yellow or red. + opens the comparison pane, − closes it.
  • × hides the band in this session. /context-meter brings it back.
  • Compact now compacts this session at once with the structured instructions below.
  • ☐ Auto-compact 50% does the same by itself once the session reaches the threshold. Per session.
  • ⚙ Options opens the settings, shared by all sessions.
  • Prompt cache line: after 40 minutes without a turn the band counts down to the end of the one-hour prompt cache (Cachen går ut om 12 min). Once it has expired it warns that the next prompt writes the whole context into the cache again (Cachen har gått ut: nästa prompt skriver om ~180k tokens till cachen).

The comparison pane lists every session whose transcript was written recently, sorted by fill, with a bar, tokens / window and folder. A [Compact] button appears on a row at or above the threshold. Rows marked ≈ are sessions that do not run the mod. Their fill is estimated from the transcript.

Options

OptionDefault
Auto-compact at50 %
Auto-compact on in new sessionsNo
Compact when idle after55 min (av turns it off)
…if the context is at least150k tokens
[Compact] in the pane from50 %
Yellow from / red above50 % / 75 %
Show sessions active within10 min
Show sessions without the mod (≈)Yes
Open the comparison pane at startYes

How compaction works

A session can only compact itself, so a request goes through a file:

  1. The button writes ~/.claude/context-meter/requests/<session id>.json.
  2. The target session picks it up on its next tick (every 15 s) and compacts with the structured instructions below: one model call, the same as a bare /compact.
  3. A compaction refused while a turn runs is retried up to five times, then sent as the /compact command.

Idle compact

The API keeps the prompt cache for an hour. A prompt sent after a longer pause writes the whole context into the cache again, at twice the input price. A session that has had no turn for the idle time (55 min by default), with at least 150k tokens of context, therefore compacts itself through the same steps as Compact now. The compaction reads the context from a warm cache, and the return starts from the smaller compacted context. It runs once per idle stretch, only while the cache is still warm (under 60 minutes), and not after a session is resumed, since the cache is cold by then.

Every compaction gets structured instructions

Compact now, idle compact and every compaction that arrives without instructions of its own (the engine's auto-compact at its threshold, a bare /compact, a precompute) get a fixed outline. The summary then has the headings LÄGE, GJORT, BESLUT, FILER, FEL OCH LÖSNINGAR, NÄSTA STEG and FAST, with exact paths, ids, commands and numbers. The decisive line of each error is quoted verbatim, so the full tool output can be found again in the session transcript by searching for that line. A /compact typed with text keeps that text. Subagents' own compactions are left alone.

Every summary that stands is saved to compacts/<UTC time>_<session id>.md, with the session, folder, trigger and tokens before and after. Other sessions can search them there.

Files it writes

All under ~/.claude/context-meter/:

  • <session id>.json: one heartbeat per session, every 15 s.
  • requests/: compaction requests and their state.
  • compacts/: one Markdown file per compaction, the summary as it stands.
  • prefs.json: the options.

Install

Clone it anywhere and point Claude Code at the folder. For every session, set this in ~/.claude/settings.json:

{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "C:\\path\\to\\context-meter" } }

A session loads it at start. The estimated rows need python on PATH (scripts/scan.py).

.claude-plugin/types/ holds the Claude Code type definitions. Claude Code generates them locally and they are not committed.

claude plugin validate .

License

MIT, see LICENSE.

Source 3 files
hooks/register.tsx 824 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { CompactRequest, CompactState, ContextBeat, MeterPrefs } from '../types'
5import { cacheStatus, isIdleCompactDue } from './idle'
6
7const PANE = 'context-meter'
8const BEAT_MS = 15_000
9// A session whose heartbeat is older than this has quit or crashed.
10const STALE_MS = 90_000
11// The scan, the activity filter (prefs.activeMinutes), reruns this often.
12const SCAN_MS = 60_000
13
14const DEFAULT_PREFS: MeterPrefs = {
15  isHidden: false,
16  autoAt: 50,
17  buttonAt: 50,
18  yellowAt: 50,
19  redAt: 75,
20  activeMinutes: 10,
21  showEstimated: true,
22  autoInNewSessions: false,
23  idleMinutes: 55,
24  idleMinTokens: 150_000,
25}
26
27// What the options' pickers offer; a stored value outside them is added.
28const COMPACT_STEPS = [30, 40, 50, 60, 70, 80, 90]
29const YELLOW_STEPS = [30, 40, 50, 60, 70, 80]
30const RED_STEPS = [50, 60, 70, 75, 80, 90, 95]
31const MINUTE_STEPS = [5, 10, 30, 60, 240]
32const IDLE_STEPS = [0, 30, 45, 55]
33const TOKEN_STEPS = [100_000, 150_000, 200_000, 250_000]
34
35
36// Steers every compaction that arrives without instructions of its own: the
37// engine's auto-compact at its threshold, a bare /compact, and a precompute.
38const COMPACT_INSTRUCTIONS = [
39  'Skriv sammanfattningen så att en ny session kan fortsätta utan att fråga något. Skriv på samtalets språk.',
40  'Använd exakt dessa rubriker, i den här ordningen:',
41  'LÄGE: en mening om vad som pågår just nu och om något arbete är halvfärdigt.',
42  'GJORT: det som är klart och verifierat, med uppmätta tal och hur det verifierades.',
43  'BESLUT: vad användaren har bestämt, med användarens egna ord där de spelar roll, och vad som väntar på beslut.',
44  'FILER: fullständiga sökvägar till varje fil som skapats eller ändrats, säkerhetskopior, grenar, commits och PR-länkar.',
45  'FEL OCH LÖSNINGAR: fel som uppstod, orsaken och vad som löste dem, så att de inte upprepas. ' +
46    'Citera den avgörande felraden ordagrant inom backticks, så att hela utskriften kan sökas fram i transkriptet.',
47  'NÄSTA STEG: numrerade, i den ordning de ska göras.',
48  'FAST: regler och rättelser användaren gett i sessionen som ska gälla framåt.',
49  'Ta med exakta namn, id:n, kommandon och tal. Utelämna resonemang och mellansteg som inte påverkar fortsättningen.',
50].join('\n')
51
52const STATE_TEXT: Record<CompactState, string> = {
53  requested: 'compact begärd',
54  summarizing: 'skriver sammanfattning',
55  compacting: 'kompakterar',
56  done: 'kompakterad',
57  failed: 'compact misslyckades',
58}
59
60const beats = atom({ plugin: 'context-meter', key: 'beats' } as const, [])
61const scanned = atom({ plugin: 'context-meter', key: 'scanned' } as const, [])
62const selfId = atom({ plugin: 'context-meter', key: 'selfId' } as const, '')
63const requests = atom({ plugin: 'context-meter', key: 'requests' } as const, {})
64const isPaneOpen = atom({ plugin: 'context-meter', key: 'isPaneOpen' } as const, false)
65// Both per session: the band's close mark, and the auto-compact box.
66const isBandHidden = atom({ plugin: 'context-meter', key: 'isBandHidden' } as const, false)
67const isAutoCompact = atom({ plugin: 'context-meter', key: 'isAutoCompact' } as const, false)
68const isOptionsOpen = atom({ plugin: 'context-meter', key: 'isOptionsOpen' } as const, false)
69const prefs = atom({ plugin: 'context-meter', key: 'prefs' } as const, DEFAULT_PREFS)
70// When this session's last main turn ended (0: none since the session started), and whether one runs now.
71const lastTurnAt = atom({ plugin: 'context-meter', key: 'lastTurnAt' } as const, 0)
72const isTurnRunning = atom({ plugin: 'context-meter', key: 'isTurnRunning' } as const, false)
73// After a failed or finished compaction, auto-compact waits this long.
74const AUTO_PAUSE_MS = 10 * 60_000
75
76// The meter's palette: mint, sun and coral for the three zones, periwinkle for
77// auto-compact. Raw hex reads on both a dark and a light theme.
78const MINT = '#2EC4A0'
79const SUN = '#F5B83D'
80const CORAL = '#F26D6D'
81const PERIWINKLE = '#8B8FF7'
82const GAUGE_CELLS = 12
83
84// Mint below yellowAt, sun up to and including redAt, coral above.
85function colorFor(percent: number, p: MeterPrefs): string {
86  if (percent < p.yellowAt) return MINT
87  if (percent <= p.redAt) return SUN
88  return CORAL
89}
90
91type GaugeCell = { glyph: string; color?: string; isFilled: boolean }
92
93// The band's meter: filled cells take the colour of the zone they sit in, and a
94// tick marks where auto-compact fires while this session's box is ticked.
95function gauge(percent: number, p: MeterPrefs, autoAt?: number): GaugeCell[] {
96  const cells: GaugeCell[] = []
97  for (let i = 0; i < GAUGE_CELLS; i++) {
98    const at = ((i + 0.5) / GAUGE_CELLS) * 100
99    if (autoAt !== undefined && Math.round((autoAt / 100) * GAUGE_CELLS) === i) {
100      cells.push({ glyph: '┃', color: PERIWINKLE, isFilled: true })
101    }
102    const isFilled = percent >= at
103    cells.push({ glyph: isFilled ? '▰' : '▱', color: isFilled ? colorFor(at, p) : undefined, isFilled })
104  }
105  return cells
106}
107
108const numberOr = (value: unknown, fallback: number) =>
109  typeof value === 'number' && Number.isFinite(value) ? value : fallback
110
111const booleanOr = (value: unknown, fallback: boolean) => (typeof value === 'boolean' ? value : fallback)
112
113// A hand-edited or older prefs.json falls back field by field.
114function toPrefs(raw: unknown): MeterPrefs {
115  const p = (raw !== null && typeof raw === 'object' ? raw : {}) as Record<string, unknown>
116  const d = DEFAULT_PREFS
117  return {
118    isHidden: booleanOr(p.isHidden, d.isHidden),
119    autoAt: numberOr(p.autoAt, d.autoAt),
120    buttonAt: numberOr(p.buttonAt, d.buttonAt),
121    yellowAt: numberOr(p.yellowAt, d.yellowAt),
122    redAt: numberOr(p.redAt, d.redAt),
123    activeMinutes: numberOr(p.activeMinutes, d.activeMinutes),
124    showEstimated: booleanOr(p.showEstimated, d.showEstimated),
125    autoInNewSessions: booleanOr(p.autoInNewSessions, d.autoInNewSessions),
126    idleMinutes: numberOr(p.idleMinutes, d.idleMinutes),
127    idleMinTokens: numberOr(p.idleMinTokens, d.idleMinTokens),
128  }
129}
130
131// Yellow stays below red: the field just picked wins, the other gives way.
132function ordered(p: MeterPrefs, isRedPicked: boolean): MeterPrefs {
133  if (p.yellowAt < p.redAt) return p
134  return isRedPicked ? { ...p, yellowAt: p.redAt - 5 } : { ...p, redAt: p.yellowAt + 5 }
135}
136
137function percentOptions(steps: readonly number[], current: number, unit = '%') {
138  return [...new Set([...steps, current])]
139    .sort((a, b) => a - b)
140    .map(n => ({ value: String(n), label: `${n}${unit}` }))
141}
142
143const YES_NO = [
144  { value: 'yes', label: 'Ja' },
145  { value: 'no', label: 'Nej' },
146]
147const yesNo = (isOn: boolean) => (isOn ? 'yes' : 'no')
148
149function idleOptions(current: number) {
150  return [...new Set([...IDLE_STEPS, current])]
151    .sort((a, b) => a - b)
152    .map(n => ({ value: String(n), label: n === 0 ? 'av' : `${n} min` }))
153}
154
155function tokenOptions(current: number) {
156  return [...new Set([...TOKEN_STEPS, current])]
157    .sort((a, b) => a - b)
158    .map(n => ({ value: String(n), label: `${n / 1000}k` }))
159}
160
161const kilo = (n: number) =>
162  n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1000)}k`
163
164const folderName = (path: string) => path.split(/[\\/]/).filter(Boolean).pop() ?? path
165
166const isBusy = (r: CompactRequest | undefined) =>
167  r !== undefined && (r.state === 'requested' || r.state === 'compacting')
168
169async function homeDir($: EngineInterface): Promise<string> {
170  return (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '.'
171}
172
173async function heartbeatDir($: EngineInterface): Promise<string> {
174  return `${await homeDir($)}/.claude/context-meter`
175}
176
177// Module variables start over on a reload; the label is cheap to rebuild.
178let label = ''
179
180async function labelFor($: EngineInterface, cwd: string): Promise<string> {
181  if (label) return label
182  const messages = await $.session.messages()
183  const first = messages.find(m => m.role === 'user' && m.text.trim() !== '')
184  const prompt = first?.text.replace(/\s+/g, ' ').trim().slice(0, 48) ?? ''
185  if (prompt) label = prompt
186  return prompt || folderName(cwd)
187}
188
189async function beat($: EngineInterface, isEnded = false): Promise<void> {
190  const [id, cwd, model, usage, now] = await Promise.all([
191    $.session.id(),
192    $.session.cwd(),
193    $.session.model(),
194    $.session.usage(),
195    $.clock.now(),
196  ])
197  const entry: ContextBeat = {
198    id,
199    label: await labelFor($, cwd),
200    cwd,
201    model,
202    tokens: usage.context.tokens ?? 0,
203    window: usage.context.window,
204    percent: usage.context.percent ?? 0,
205    updatedAt: now,
206    isEnded,
207  }
208  await $.fs.write(`${await heartbeatDir($)}/${id}.json`, JSON.stringify(entry))
209}
210
211async function readJsonDir<T>($: EngineInterface, dir: string, maxAgeMs: number): Promise<Array<[string, T]>> {
212  const now = await $.clock.now()
213  const files = (await $.fs.list(dir).catch(() => [])).filter(
214    f => f.kind === 'file' && f.name.endsWith('.json') && now - f.mtimeMs < maxAgeMs,
215  )
216  const parsed = await Promise.all(
217    files.map(f =>
218      $.fs
219        .read(`${dir}/${f.name}`)
220        .then((text): [string, T] => [f.name.slice(0, -'.json'.length), JSON.parse(text) as T])
221        .catch(() => undefined),
222    ),
223  )
224  return parsed.filter((p): p is [string, T] => p !== undefined)
225}
226
227async function refresh($: EngineInterface): Promise<void> {
228  const dir = await heartbeatDir($)
229  const now = await $.clock.now()
230  const live = (await readJsonDir<ContextBeat>($, dir, STALE_MS))
231    .map(([, b]) => b)
232    .filter(b => !b.isEnded && now - b.updatedAt < STALE_MS)
233  await update($, beats, () => live)
234  const asked = await readJsonDir<CompactRequest>($, `${dir}/requests`, 24 * 3_600_000)
235  await update($, requests, () => Object.fromEntries(asked))
236}
237
238type ScanRow = { id: string; label: string; cwd: string; model: string; tokens: number; updatedAt: number }
239
240// A transcript does not say the model's window: take this session's own,
241// and 1M once a session is past 200k.
242async function scan($: EngineInterface): Promise<void> {
243  const home = await homeDir($)
244  const activeSeconds = (await read($, prefs)).activeMinutes * 60
245  const [run, usage] = await Promise.all([
246    $.process.run(
247      ['python', `${$.plugin.root}/scripts/scan.py`, `${home}/.claude/projects`, String(activeSeconds)],
248      { timeoutMs: 60_000 },
249    ),
250    $.session.usage(),
251  ])
252  if (run.exitCode !== 0) return
253  const rows = JSON.parse(run.stdout) as ScanRow[]
254  const estimated = rows.map((r): ContextBeat => {
255    const window = r.tokens > 200_000 ? Math.max(1_000_000, usage.context.window) : usage.context.window
256    return {
257      ...r,
258      window,
259      percent: Math.round((r.tokens / window) * 100),
260      isEnded: false,
261      isEstimated: true,
262    }
263  })
264  await update($, scanned, () => estimated)
265}
266
267// The scan is the activity filter: a session shows only while its transcript
268// was written within prefs.activeMinutes (this session always). Heartbeats are
269// exact and win; the transcript's title (the name the app shows) labels both.
270function merge(exact: ContextBeat[], estimated: ContextBeat[], self: string, showEstimated = true): ContextBeat[] {
271  const active = new Map(estimated.map(b => [b.id, b]))
272  const exactIds = new Set(exact.map(b => b.id))
273  const estimatedOnly = showEstimated
274    ? estimated.filter(b => !exactIds.has(b.id)).map(b => ({ ...b, label: b.label || folderName(b.cwd) }))
275    : []
276  return [
277    ...exact
278      .filter(b => b.id === self || active.has(b.id))
279      .map(b => ({ ...b, label: active.get(b.id)?.label || b.label })),
280    ...estimatedOnly,
281  ].sort((a, b) => b.percent - a.percent)
282}
283
284async function writeRequest($: EngineInterface, id: string, state: CompactState, note?: string): Promise<void> {
285  const request: CompactRequest = { state, at: await $.clock.now(), ...(note ? { note } : {}) }
286  await $.fs.write(`${await heartbeatDir($)}/requests/${id}.json`, JSON.stringify(request))
287  await update($, requests, all => ({ ...all, [id]: request }))
288}
289
290// The compaction's summary is the first message of the conversation it leaves.
291// Saved as compacts/<date>_<session id>.md, one file per compaction.
292async function archiveSummary(
293  $: EngineInterface,
294  id: string,
295  trigger: string,
296  result: { messages?: readonly { text: string }[]; tokensBefore?: number; tokensAfter?: number },
297): Promise<void> {
298  const summary = result.messages?.[0]?.text?.trim()
299  if (!summary) return
300  const at = new Date(await $.clock.now())
301  const stamp = at.toISOString().slice(0, 19).replace(/[:T]/g, '-')
302  const cwd = await $.session.cwd()
303  const tokens =
304    result.tokensBefore !== undefined
305      ? `${Math.round(result.tokensBefore / 1000)}k → ${Math.round((result.tokensAfter ?? 0) / 1000)}k tokens`
306      : ''
307  const header = [
308    `# Compact ${at.toISOString().slice(0, 16).replace('T', ' ')} UTC`,
309    '',
310    `- Session: ${label || folderName(cwd)} (\`${id}\`)`,
311    `- Mapp: \`${cwd}\``,
312    `- Utlöst av: ${trigger}${tokens ? `, ${tokens}` : ''}`,
313    '',
314  ].join('\n')
315  await $.fs.write(`${await heartbeatDir($)}/compacts/${stamp}_${id}.md`, `${header}\n${summary}\n`)
316}
317
318// In the target session: a requested compaction runs at once with the
319// structured instructions, one model call over the context.
320async function takeRequest($: EngineInterface): Promise<void> {
321  const id = await $.session.id()
322  const request = (await read($, requests))[id]
323  if (request?.state !== 'requested') return
324  await writeRequest($, id, 'compacting', request.note)
325  void compactWith($, COMPACT_INSTRUCTIONS, 1)
326}
327
328const errorText = (error: unknown) =>
329  (error instanceof Error ? error.message : String(error)).replace(/\s+/g, ' ').slice(0, 160)
330
331// Compaction is refused while
332// a turn runs, so it is retried a few times; the last try goes through the
333// /compact command instead, and a failure keeps the engine's own words.
334async function compactWith($: EngineInterface, instructions: string, attempt: number): Promise<void> {
335  const id = await $.session.id()
336  try {
337    const result = await $.session.compact({ instructions })
338    const isSkipped = 'skip' in result && result.skip !== undefined
339    await writeRequest($, id, isSkipped ? 'failed' : 'done', isSkipped ? 'avbruten av en hook' : undefined)
340    await beat($).catch(() => undefined)
341  } catch (error) {
342    if (attempt < 5) {
343      await writeRequest($, id, 'compacting', `försök ${attempt} avvisat: ${errorText(error)}`)
344      $.clock.after(10_000, () => void compactWith($, instructions, attempt + 1))
345      return
346    }
347    try {
348      await $.command.run({ command: 'compact', args: instructions })
349      await writeRequest($, id, 'done', 'via /compact-kommandot')
350      await beat($).catch(() => undefined)
351    } catch (fallback) {
352      // Last resort: paste `/compact <text>` as if typed; it runs once idle.
353      try {
354        await $.prompt.submit({ text: `/compact ${instructions}`, asUser: true })
355        await writeRequest($, id, 'compacting', 'inklistrat som /compact, körs när sessionen är ledig')
356      } catch (pasted) {
357        const notes = [errorText(error), `/compact: ${errorText(fallback)}`, `inklistring: ${errorText(pasted)}`]
358        await writeRequest($, id, 'failed', notes.join(' | '))
359      }
360    }
361  }
362}
363
364// Read on every tick, so a change made in one session reaches the others.
365async function loadPrefs($: EngineInterface): Promise<MeterPrefs> {
366  const text = await $.fs.read(`${await heartbeatDir($)}/prefs.json`).catch(() => '')
367  let raw: unknown = {}
368  try {
369    raw = JSON.parse(text)
370  } catch {
371    // Missing or broken: the defaults stand.
372  }
373  const loaded = toPrefs(raw)
374  await update($, prefs, () => loaded)
375  return loaded
376}
377
378async function savePrefs($: EngineInterface, patch: Partial<MeterPrefs>): Promise<void> {
379  // Re-read first: another session may have changed another option meanwhile.
380  const current = await loadPrefs($).catch(() => read($, prefs))
381  const next = ordered({ ...current, ...patch }, patch.redAt !== undefined)
382  await update($, prefs, () => next)
383  await $.fs.write(`${await heartbeatDir($)}/prefs.json`, JSON.stringify(next, null, 2)).catch(() => undefined)
384}
385
386// The last choice is also where the next session starts.
387async function setPane($: EngineInterface, isOpen: boolean): Promise<void> {
388  if (isOpen) {
389    await $.ui.open({ id: PANE, title: 'Context' })
390  } else {
391    await $.ui.close({ id: PANE })
392  }
393  await update($, isPaneOpen, () => isOpen)
394  await savePrefs($, { isHidden: !isOpen })
395}
396
397// Compact now: request this session's compaction and take it at once.
398async function compactSelf($: EngineInterface): Promise<void> {
399  const id = await $.session.id()
400  if (isBusy((await read($, requests))[id])) return
401  await writeRequest($, id, 'requested')
402  await takeRequest($)
403}
404
405// Auto-compact: a session past prefs.autoAt asks for its own compaction, once;
406// a failure or a fresh compaction pauses it for AUTO_PAUSE_MS.
407async function autoCompact($: EngineInterface): Promise<void> {
408  if (!(await read($, isAutoCompact))) return
409  const [id, usage, now, p] = await Promise.all([$.session.id(), $.session.usage(), $.clock.now(), read($, prefs)])
410  if ((usage.context.percent ?? 0) < p.autoAt) return
411  const request = (await read($, requests))[id]
412  if (isBusy(request)) return
413  if (request && (request.state === 'failed' || request.state === 'done') && now - request.at < AUTO_PAUSE_MS) return
414  await writeRequest($, id, 'requested', 'auto-compact')
415}
416
417// Idle compact: see idle.ts. Once per idle stretch: a request made after the last turn ends it.
418async function idleCompact($: EngineInterface): Promise<void> {
419  const [p, last, isRunning] = await Promise.all([read($, prefs), read($, lastTurnAt), read($, isTurnRunning)])
420  if (p.idleMinutes <= 0 || last === 0 || isRunning) return
421  const [id, usage, now] = await Promise.all([$.session.id(), $.session.usage(), $.clock.now()])
422  const request = (await read($, requests))[id]
423  const due = isIdleCompactDue({
424    idleMinutes: p.idleMinutes,
425    minTokens: p.idleMinTokens,
426    lastTurnAt: last,
427    now,
428    tokens: usage.context.tokens ?? 0,
429    lastRequestAt: request?.at,
430    isRequestBusy: isBusy(request),
431  })
432  if (due) await writeRequest($, id, 'requested', `inaktiv i ${Math.round((now - last) / 60_000)} min`)
433}
434
435async function tick($: EngineInterface): Promise<void> {
436  await loadPrefs($).catch(() => undefined)
437  await beat($).catch(() => undefined)
438  await refresh($).catch(() => undefined)
439  await autoCompact($).catch(() => undefined)
440  await idleCompact($).catch(() => undefined)
441  await takeRequest($).catch(() => undefined)
442}
443
444export const register: Register = on => {
445  on('session.start', async ($, e, next) => {
446    await update($, selfId, () => '')
447    await $.command.register({
448      name: 'context-meter',
449      description: 'Visa Context-raden igen, eller visa/dölj jämförelsepanelen',
450    })
451    void $.session.id().then(id => update($, selfId, () => id))
452    void tick($)
453    $.clock.every(BEAT_MS, () => void tick($))
454    void scan($).catch(() => undefined)
455    $.clock.every(SCAN_MS, () => void scan($).catch(() => undefined))
456    void loadPrefs($).then(async loaded => {
457      await update($, isAutoCompact, () => loaded.autoInNewSessions)
458      if (loaded.isHidden) return
459      await $.ui.open({ id: PANE, title: 'Context' })
460      await update($, isPaneOpen, () => true)
461    })
462
463    return next(e)
464  })
465
466  on('command.run', { command: 'context-meter' }, async $ => {
467    await tick($)
468    // Brings a closed band back; otherwise toggles the comparison pane.
469    if (await read($, isBandHidden)) {
470      await update($, isBandHidden, () => false)
471      return { text: 'Context-raden visas igen.' }
472    }
473    const isOpen = !(await read($, isPaneOpen))
474    await setPane($, isOpen)
475
476    return { text: isOpen ? 'Context-panelen visas.' : 'Context-panelen dold.' }
477  })
478
479  // The pane's own close mark counts as hiding it.
480  on('ui.close', async ($, e, next) => {
481    const result = await next(e)
482    if (e.id === PANE) {
483      await update($, isPaneOpen, () => false).catch(() => undefined)
484      if (e.origin.kind === 'person') await savePrefs($, { isHidden: true }).catch(() => undefined)
485    }
486
487    return result
488  })
489
490  // The band above the prompt: this session's fill, + for the comparison pane,
491  // a close mark, and the compaction controls.
492  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
493    if (e.props.hasSurvey || (await read($, isBandHidden))) return next(e)
494    const table = $.ui.resolve(e)
495    // The band is drawn on the terminal and desktop only, both with a Select.
496    if (!('Select' in table)) return next(e)
497    const { Box, Button, Select, Text } = table
498    const self = await read($, selfId)
499    const own = merge(await read($, beats), await read($, scanned), self).find(b => b.id === self)
500    const isOpen = await read($, isPaneOpen)
501    const isAuto = await read($, isAutoCompact)
502    const isOptions = await read($, isOptionsOpen)
503    const p = await read($, prefs)
504    const request = (await read($, requests))[self]
505    const cache = cacheStatus({
506      lastTurnAt: await read($, lastTurnAt),
507      now: await $.clock.now(),
508      tokens: own?.tokens ?? 0,
509      isRunning: await read($, isTurnRunning),
510    })
511
512    const percent = own?.percent
513    const cells = percent === undefined ? [] : gauge(percent, p, isAuto ? p.autoAt : undefined)
514
515    // Options in three short rows: compaction, colours, the comparison pane.
516    const optionsPanel = (
517      <Box flexDirection="column" marginTop={1}>
518        <Box flexDirection="row" flexWrap="wrap" columnGap={3}>
519          <Text size="caption" bold color={PERIWINKLE}>Compact</Text>
520          <Select
521            key="context-meter-opt-auto-at"
522            label="Custom autocomp. vid "
523            options={percentOptions(COMPACT_STEPS, p.autoAt)}
524            value={String(p.autoAt)}
525            onSelect={v => void savePrefs($, { autoAt: Number(v) })}
526          />
527          <Select
528            key="context-meter-opt-auto-new"
529            label="på i nya sessioner "
530            options={YES_NO}
531            value={yesNo(p.autoInNewSessions)}
532            onSelect={v => void savePrefs($, { autoInNewSessions: v === 'yes' })}
533          />
534          <Select
535            key="context-meter-opt-idle"
536            label="vid inaktivitet efter "
537            options={idleOptions(p.idleMinutes)}
538            value={String(p.idleMinutes)}
539            onSelect={v => void savePrefs($, { idleMinutes: Number(v) })}
540          />
541          <Select
542            key="context-meter-opt-idle-tokens"
543            label="om kontexten är minst "
544            options={tokenOptions(p.idleMinTokens)}
545            value={String(p.idleMinTokens)}
546            onSelect={v => void savePrefs($, { idleMinTokens: Number(v) })}
547          />
548        </Box>
549        <Box flexDirection="row" flexWrap="wrap" columnGap={3}>
550          <Text size="caption" bold color={SUN}>Färger</Text>
551          <Select
552            key="context-meter-opt-yellow"
553            label="gul från "
554            options={percentOptions(YELLOW_STEPS, p.yellowAt)}
555            value={String(p.yellowAt)}
556            onSelect={v => void savePrefs($, { yellowAt: Number(v) })}
557          />
558          <Select
559            key="context-meter-opt-red"
560            label="röd över "
561            options={percentOptions(RED_STEPS, p.redAt)}
562            value={String(p.redAt)}
563            onSelect={v => void savePrefs($, { redAt: Number(v) })}
564          />
565        </Box>
566        <Box flexDirection="row" flexWrap="wrap" columnGap={3}>
567          <Text size="caption" bold color={MINT}>Panelen</Text>
568          <Select
569            key="context-meter-opt-pane"
570            label="öppen vid start "
571            options={YES_NO}
572            value={yesNo(!p.isHidden)}
573            onSelect={v => void savePrefs($, { isHidden: v === 'no' })}
574          />
575          <Select
576            key="context-meter-opt-active"
577            label="sessioner aktiva senaste "
578            options={percentOptions(MINUTE_STEPS, p.activeMinutes, ' min')}
579            value={String(p.activeMinutes)}
580            onSelect={v => void savePrefs($, { activeMinutes: Number(v) }).then(() => scan($))}
581          />
582          <Select
583            key="context-meter-opt-button-at"
584            label="[Compact] från "
585            options={percentOptions(COMPACT_STEPS, p.buttonAt)}
586            value={String(p.buttonAt)}
587            onSelect={v => void savePrefs($, { buttonAt: Number(v) })}
588          />
589          <Select
590            key="context-meter-opt-estimated"
591            label="sessioner utan moddet (≈) "
592            options={YES_NO}
593            value={yesNo(p.showEstimated)}
594            onSelect={v => void savePrefs($, { showEstimated: v === 'yes' })}
595          />
596        </Box>
597        <Box flexDirection="row" alignItems="center" columnGap={2}>
598          <Text size="caption" dimColor>Gäller alla sessioner. Bocken gäller bara den här.</Text>
599          <Box flexGrow={1} />
600          <Button
601            key="context-meter-opt-reset"
602            plain
603            dimColor
604            label="Återställ standard"
605            onPress={() => savePrefs($, { ...DEFAULT_PREFS, isHidden: p.isHidden })}
606          />
607          <Button
608            key="context-meter-opt-done"
609            label="Klar"
610            onPress={() => update($, isOptionsOpen, () => false)}
611          />
612        </Box>
613      </Box>
614    )
615
616    return (
617      <Box flexDirection="column" paddingX={1}>
618        {/* One row in the smallest type the surface has. The desktop draws a
619            Button's label in its own type and drops Text children, so the
620            styled text sits beside the buttons and the notes run inline. The
621            content shrinks and clips; ⚙ and × never shrink, so a narrow
622            session window still shows the way to close the band. */}
623        <Box flexDirection="row" alignItems="center" columnGap={2}>
624          <Box
625            flexDirection="row"
626            alignItems="center"
627            columnGap={2}
628            flexGrow={1}
629            flexShrink={1}
630            minWidth={0}
631            overflow="hidden"
632          >
633            <Text size="caption" tabular>
634              <Text dimColor>Context </Text>
635              <Text bold color={percent === undefined ? undefined : colorFor(percent, p)}>
636                {percent === undefined ? '–' : `${percent}%`}
637              </Text>
638              <Text> </Text>
639              {cells.map(c => (
640                <Text color={c.color} dimColor={!c.isFilled}>
641                  {c.glyph}
642                </Text>
643              ))}
644            </Text>
645            <Button
646              key="context-meter-compare"
647              plain
648              dimColor={!isOpen}
649              label={isOpen ? 'Dölj ▴' : 'Jämför ▾'}
650              onPress={() => setPane($, !isOpen)}
651            />
652            <Button
653              key="context-meter-compact"
654              plain
655              label={request && isBusy(request) ? `${STATE_TEXT[request.state]} …` : 'Compact'}
656              onPress={() => compactSelf($)}
657            />
658            <Text size="caption" tabular>
659              <Text dimColor>Auto </Text>
660              <Text bold color={isAuto ? PERIWINKLE : undefined} dimColor={!isAuto}>
661                {p.autoAt}%
662              </Text>
663            </Text>
664            <Button
665              key="context-meter-auto"
666              plain
667              dimColor={!isAuto}
668              label={isAuto ? '◉' : '○'}
669              onPress={() => update($, isAutoCompact, was => !was)}
670            />
671            <Box flexGrow={1} flexShrink={1} minWidth={0}>
672              {cache.kind === 'cold' && (
673                <Text key="context-meter-cache" size="caption" color={SUN} wrap="truncate-end">
674                  ◷ Cachen har gått ut: nästa prompt skriver om ~{kilo(cache.tokens)} tokens
675                </Text>
676              )}
677              {cache.kind === 'expiring' && (
678                <Text key="context-meter-cache" size="caption" dimColor wrap="truncate-end">
679                  ◷ Cachen går ut om {cache.minutesLeft} min (~{kilo(cache.tokens)} tokens)
680                </Text>
681              )}
682              {cache.kind !== 'cold' && cache.kind !== 'expiring' && request && !isBusy(request) && (
683                <Text size="caption" wrap="truncate-end">
684                  <Text color={request.state === 'failed' ? CORAL : MINT}>
685                    {request.state === 'failed' ? '✕ ' : '✓ '}
686                  </Text>
687                  <Text dimColor>
688                    {STATE_TEXT[request.state]}
689                    {request.note ? ` – ${request.note}` : ''}
690                  </Text>
691                </Text>
692              )}
693            </Box>
694          </Box>
695          <Box flexDirection="row" alignItems="center" columnGap={1} flexShrink={0}>
696            <Button
697              key="context-meter-options"
698              plain
699              dimColor={!isOptions}
700              label="⚙"
701              onPress={() => update($, isOptionsOpen, was => !was)}
702            />
703            <Button
704              key="context-meter-close"
705              role="dismiss"
706              plain
707              dimColor
708              label="×"
709              onPress={() => update($, isBandHidden, () => true)}
710            />
711          </Box>
712        </Box>
713        {isOptions && optionsPanel}
714      </Box>
715    )
716  })
717
718  on('turn.start', async ($, e, next) => {
719    await update($, isTurnRunning, () => true)
720    return next(e)
721  })
722
723  on('turn.complete', async ($, e, next) => {
724    const result = await next(e)
725    if (e.agentId === undefined) {
726      const now = await $.clock.now()
727      await update($, isTurnRunning, () => false)
728      await update($, lastTurnAt, () => now)
729    }
730    await tick($)
731
732    return result
733  })
734
735  // However the compaction ran (call, command or pasted /compact), a request
736  // waiting on it is done once it stands.
737  // A compaction without instructions gets the structured ones, and every
738  // summary that stands is archived under compacts/ for later sessions.
739  on('session.compact', async ($, e, next) => {
740    const isMain = e.agentId === undefined
741    const steered = isMain && !e.instructions?.trim() ? { ...e, instructions: COMPACT_INSTRUCTIONS } : e
742    const result = await next(steered)
743    const isSkipped = 'skip' in result && result.skip !== undefined
744    const id = await $.session.id()
745    if (!isSkipped && isMain && e.trigger !== 'precompute') {
746      await archiveSummary($, id, e.trigger, result).catch(() => undefined)
747    }
748    const request = (await read($, requests))[id]
749    if (!isSkipped && request?.state === 'compacting') {
750      await writeRequest($, id, 'done').catch(() => undefined)
751      $.clock.after(2_000, () => void beat($).catch(() => undefined))
752    }
753
754    return result
755  })
756
757  on('session.end', async ($, e, next) => {
758    await beat($, true).catch(() => undefined)
759
760    return next(e)
761  })
762
763  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
764    const { Box, Button, Text } = $.ui.resolve(e)
765    const self = await read($, selfId)
766    const p = await read($, prefs)
767    const list = merge(await read($, beats), await read($, scanned), self, p.showEstimated)
768    const top = list[0]
769    const asked = await read($, requests)
770    const columns = e.props.bodyColumns ?? e.viewport?.columns ?? 40
771    // Narrower than the pane: a desktop draws wider glyphs than it reports.
772    const barWidth = Math.max(10, Math.min(60, columns - 12))
773
774    return (
775      <Box flexDirection="column">
776        <Box marginBottom={1}>
777          <Text dimColor wrap="truncate-end">
778            [Compact] visas från {p.buttonAt}%
779            {top ? ` · högst nu ${top.percent}%` : ''}
780          </Text>
781        </Box>
782        {list.length === 0 && <Text dimColor>Inga aktiva sessioner just nu.</Text>}
783        {list.map(b => {
784          const filled = Math.round((b.percent / 100) * barWidth)
785          const request = asked[b.id]
786          const canCompact = !b.isEstimated && b.percent >= p.buttonAt && !isBusy(request)
787          return (
788            <Box key={b.id} flexDirection="column" marginBottom={1}>
789              <Text bold={b.id === self} dimColor={b.isEstimated} wrap="truncate-end">
790                {b.id === self ? '● ' : '  '}
791                {b.label}
792              </Text>
793              <Text color={colorFor(b.percent, p)} wrap="truncate-end">
794                {'█'.repeat(filled)}
795                <Text dimColor>{'░'.repeat(barWidth - filled)}</Text>
796              </Text>
797              <Text dimColor wrap="truncate-end">
798                {b.isEstimated ? '≈' : ''}
799                {b.percent}% · {kilo(b.tokens)} / {kilo(b.window)} · {folderName(b.cwd)}
800              </Text>
801              {request && (
802                <Text dimColor wrap="truncate-end">
803                  {STATE_TEXT[request.state]}
804                  {request.note ? ` – ${request.note}` : ''}
805                </Text>
806              )}
807              {canCompact && (
808                <Button
809                  key={`compact-${b.id}`}
810                  label="Compact"
811                  onPress={() => writeRequest($, b.id, 'requested')}
812                />
813              )}
814              {b.isEstimated && b.percent >= p.buttonAt && (
815                <Text dimColor>starta om sessionen för compact</Text>
816              )}
817            </Box>
818          )
819        })}
820      </Box>
821    )
822  })
823}
824
hooks/idle.ts 50 lines
1// Pure code, no engine: decides whether an idle session should compact now.
2
3// The API keeps the prompt cache for an hour. A prompt after that writes the
4// whole context into the cache again, at twice the input price. Compacting
5// before the hour ends reads the context from a warm cache instead.
6export const CACHE_TTL_MS = 60 * 60_000
7
8export type IdleInput = {
9  /** Minutes without a turn before compacting; 0 turns it off. */
10  idleMinutes: number
11  /** Smaller contexts are left alone. */
12  minTokens: number
13  /** When the last main turn ended; 0 when none has run since the session started. */
14  lastTurnAt: number
15  now: number
16  tokens: number
17  /** When this session's latest compaction request was written, if any. */
18  lastRequestAt?: number
19  isRequestBusy: boolean
20}
21
22export function isIdleCompactDue(i: IdleInput): boolean {
23  if (i.idleMinutes <= 0 || i.lastTurnAt === 0 || i.isRequestBusy) return false
24  const idleMs = i.now - i.lastTurnAt
25  if (idleMs < i.idleMinutes * 60_000 || idleMs >= CACHE_TTL_MS) return false
26  if (i.tokens < i.minTokens) return false
27  // A request written after the last turn already covers this idle stretch.
28  return i.lastRequestAt === undefined || i.lastRequestAt <= i.lastTurnAt
29}
30
31// Cache Tax: what the band says about the prompt cache while the session waits.
32// From WARN_MS of idle it counts down; once the hour has passed, the next prompt
33// writes the whole context into the cache again.
34export const CACHE_WARN_MS = 40 * 60_000
35
36export type CacheStatus =
37  | { kind: 'warm' }
38  | { kind: 'expiring'; minutesLeft: number; tokens: number }
39  | { kind: 'cold'; tokens: number }
40
41export function cacheStatus(i: { lastTurnAt: number; now: number; tokens: number; isRunning: boolean }): CacheStatus {
42  if (i.lastTurnAt === 0 || i.isRunning || i.tokens <= 0) return { kind: 'warm' }
43  const idleMs = i.now - i.lastTurnAt
44  if (idleMs >= CACHE_TTL_MS) return { kind: 'cold', tokens: i.tokens }
45  if (idleMs >= CACHE_WARN_MS) {
46    return { kind: 'expiring', minutesLeft: Math.ceil((CACHE_TTL_MS - idleMs) / 60_000), tokens: i.tokens }
47  }
48  return { kind: 'warm' }
49}
50
types/index.d.ts 65 lines
1/** One session's context fill: from its own heartbeat, or estimated from its transcript. */
2export type ContextBeat = {
3  id: string
4  label: string
5  cwd: string
6  model: string
7  tokens: number
8  window: number
9  percent: number
10  updatedAt: number
11  isEnded: boolean
12  isEstimated?: boolean
13}
14
15/** Where a requested compaction of one session stands. */
16export type CompactState = 'requested' | 'summarizing' | 'compacting' | 'done' | 'failed'
17
18/** A compaction the pane asked for, kept in requests/<session id>.json. */
19export type CompactRequest = {
20  state: CompactState
21  at: number
22  note?: string
23}
24
25/** The options, shared by every session, in prefs.json. */
26export type MeterPrefs = {
27  /** The comparison pane starts closed. */
28  isHidden: boolean
29  /** Auto-compact fires at this fill. */
30  autoAt: number
31  /** The pane's per-session [Compact] shows from this fill. */
32  buttonAt: number
33  /** Below this fill green; up to and including redAt yellow; above, red. */
34  yellowAt: number
35  redAt: number
36  /** Sessions whose transcript was written within this window are listed. */
37  activeMinutes: number
38  /** List sessions that do not run the mod, estimated from their transcript. */
39  showEstimated: boolean
40  /** A new session starts with its auto-compact box ticked. */
41  autoInNewSessions: boolean
42  /** Idle compact: minutes without a turn before a large session compacts; 0 turns it off. */
43  idleMinutes: number
44  /** Idle compact only touches a session with at least this many context tokens. */
45  idleMinTokens: number
46}
47
48declare module 'claude-code' {
49  interface PluginState {
50    'context-meter': {
51      beats: ContextBeat[]
52      scanned: ContextBeat[]
53      selfId: string
54      requests: Record<string, CompactRequest>
55      isPaneOpen: boolean
56      isBandHidden: boolean
57      isAutoCompact: boolean
58      isOptionsOpen: boolean
59      prefs: MeterPrefs
60      lastTurnAt: number
61      isTurnRunning: boolean
62    }
63  }
64}
65