SLOPSHOPPER

usage-bars

Context, cache, 5-hour session and weekly usage meters above the prompt

bandtoastmodelprocesstimer
v0.4.1no licenseupdated 2026-10-23luismiggarcia/claude-usage-bars
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-bars
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ 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 C▣ client module ./hit.tsx ▕▕▣ client module ./hit.tsx 4 C▣ client module ./hit.tsx ▣ client module ./hit.tsx 60▣ c t 9 c m x % h ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
C▣ client module ./hit.tsx ▕▕▣ client module ./hit.tsx 4 C▣ client module ./hit.tsx ▣ client module t 9 c x % h
README

usage-bars

A Claude Code mod that shows four meters in one line right above the prompt box:

MeterWhat it measuresAlternative text
Ctxcontext of the current session in use; a yellow stretch from 50% to 75% marks the time to deal with its size (compact, hand over), and a grey tick where auto-compact runsused · total tokens
Cchtime left before the prompt cache expiresminutes left · what the next prompt costs for the context now → once the cache has expired (input-token equivalents: 0.1× read, 2× rewrite for a 1-hour cache, 1.25× for a 5-minute one)
Sesthe account's 5-hour usage windowtime to reset (-2h 30m) · reset time
Wkthe account's weekly limittime to reset · reset day and time
  • Each bar keeps its own colour. The value beside it follows a scale: yellow from 75%, orange bold from 85%, red bold from 95%. For the cache the scale reads the time already gone, so it turns yellow with 15 minutes left.
  • Hovering a bar shows its alternative text, in two lines. A click on the bar or its label pins it; another click unpins it. Hovering a pinned text shows it in full.
  • Hovering a label (Ctx, Cch, Ses, Wk) shows its full name in the graph's place.
  • In the red band a meter shows its alternative text by itself.
  • On the desktop the bars are thin SVG pills; in the terminal, blocks of colour.
  • Warnings, as a toast: the prompt cache about to expire while the session waits for a prompt (5 minutes before, or 1 minute for a 5-minute cache), and the session or week window crossing 85% and 95%. Each is given once (a window's once per reset, across sessions). The cache warning and the 95% one also go out as a system notification, where the session has a channel for it.

Session and week figures arrive with each API response. Every session with the mod writes its latest reading to ~/.claude/usage-bars/latest.json and, every 30 seconds, takes a fresher one another session wrote: an idle session shows what an active one saw, and the verbose text says how old the reading is. The file is written whole beside it and moved over it, so no session reads it half written, and an older reading never replaces a fresher one. Past its reset time a window shows 0% until a new reading arrives. Every response of the main conversation, in the middle of a turn too, restarts the cache countdown; the time of each session's last response is kept in the mod's store, so a resumed session picks up its countdown.

The cache lives 1 hour or 5 minutes (an account in overage, for example), and no response says which. The mod assumes 1 hour and deduces the lifetime from a response that comes after a pause of more than 5 minutes and less than an hour, with the same model: one that wrote most of its input to the cache again shows a 5-minute cache (it had expired); one that read most of it shows a 1-hour cache. What it learns is kept in the store and used by every session; the verbose text says 5m cache while it is in force. It learns only after the fact: the first expiry of a 5-minute cache goes unannounced.

Install

At the prompt of a terminal session:

/plugin install usage-bars --marketplace luismiggarcia/claude-usage-bars

From a shell:

claude plugin install usage-bars --marketplace luismiggarcia/claude-usage-bars

In the desktop app, where /plugin does not run: click + next to the prompt box, then Plugins, Add marketplace with luismiggarcia/claude-usage-bars, then Add plugin.

Installed at the user scope, it loads in every new session.

Develop

claude plugin validate .
claude plugin test .

Authorship

Sole author: Luis Garcia (LG-Systems). See AUTHORS.md for how the "Co-Authored-By" lines in the commit history should be read.


© LG-Systems

Source 2 files
hooks/register.tsx 804 lines
1import type { Register, SessionContextUsage, SessionRateLimit, TurnUsage } from 'claude-code'
2
3type Window = { percent: number; resetsAt?: string }
4
5type Usage = {
6  context: { percent?: number; tokens?: number; window: number }
7  fiveHour: Window | null
8  week: Window | null
9}
10
11type Key = 'ctx' | 'cch' | 'ses' | 'wk'
12
13// The account's windows as last read by any session with this mod, shared
14// through a file so an idle session shows what an active one saw.
15type Shared = { readAt: number; fiveHour: Window | null; week: Window | null }
16const SHARED_FILE = '.claude/usage-bars/latest.json'
17
18// When each session's main conversation last got a response, kept in the
19// plugin's store so a resumed session (or a hot reload) picks up the cache
20// countdown where it was. Entries past the cache lifetime are dropped.
21const LAST_RESPONSE_KEY = 'lastResponseAt'
22type LastResponses = Record<string, number>
23
24// One meter as drawn: the bar, the value beside it, and the two texts that
25// replace the bar: the alternative text (short) and its verbose form.
26type Meter = {
27  key: Key
28  label: string
29  // Drives the colour scale: share of the limit already used (for the cache,
30  // share of its lifetime already gone, so its scale reads the other way round).
31  level: number | undefined
32  fill: number
33  value: string
34  alt: [string, string]
35  verbose: [string, string]
36  // A tick on the bar, as a share of it (the context's auto-compact point).
37  mark?: number
38  // A stretch of the bar marked out, from and to, as shares of it (the
39  // context's: the time to compact or hand over).
40  zone?: readonly [number, number]
41  // Equal segments the bar is cut into, as a gauge for the pace of use (the
42  // session's: one per hour; the week's: one per day).
43  segments?: number
44  // The start of the bar shaded, up to this share of it, under the fill: it
45  // shows once the fill has shrunk into it (the cache's last minutes).
46  shade?: number
47  // The keep-alive the value turns into under the pointer (the cache's, while
48  // it lives): the text the graph shows meanwhile, and whether it is armed.
49  keepAlive?: [string, string]
50  isArmed?: boolean
51  // Where the window is now, as a share of the bar: how much of its time has
52  // gone, to read the use against.
53  now?: number
54}
55
56const pickWindow = (limits: readonly SessionRateLimit[], kind: string): Window | null => {
57  const found = limits.find(l => l.kind === kind)
58  return found ? { percent: found.percentUsed, resetsAt: found.resetsAt } : null
59}
60
61const toUsage = (context: SessionContextUsage, limits: readonly SessionRateLimit[]): Usage => ({
62  context: { percent: context.percent, tokens: context.tokens, window: context.window },
63  fiveHour: pickWindow(limits, 'five_hour'),
64  week: pickWindow(limits, 'seven_day'),
65})
66
67// One colour per meter, fixed on the bar. The value follows the scale near the
68// limit: 75% yellow, 85% orange bold, 95% red bold; in the red band the meter
69// shows its alternative text by itself.
70const HUES: Record<Key, string> = { ctx: '#4f8ff7', cch: '#e07bb5', ses: '#9b7bf0', wk: '#2cb5a0' }
71const SCALE = [
72  { from: 95, color: '#e5534b', isBold: true },
73  { from: 85, color: '#f0883e', isBold: true },
74  { from: 75, color: '#d4a72c', isBold: false },
75] as const
76const RED_BAND = 95
77const TRACK = 'rgba(140,140,140,0.16)'
78const levelFor = (level: number) => SCALE.find(l => level >= l.from)
79
80// The prompt cache lives 1 hour after the last response, or 5 minutes (an
81// account in overage, say). No response says which: the mod deduces it from
82// what a response after a pause read from the cache (deduceTtl), assumes 1
83// hour until it knows, and keeps what it learned in the store for every session.
84const TTL_1H = 60 * 60_000
85const TTL_5M = 5 * 60_000
86const TTL_KEY = 'cacheTtl'
87// The next prompt rereads the whole context: from a live cache at 0.1x a plain
88// input token, or, once the cache has expired, writing it again at 2x (1-hour
89// cache) or 1.25x (5-minute cache). (in hundredths, to keep the arithmetic exact)
90const CACHE_READ_HUNDREDTHS = 10
91const writeHundredths = (ttlMs: number) => (ttlMs === TTL_5M ? 125 : 200)
92
93// What a response after a pause says of the cache's lifetime. Past 5 minutes
94// and within the hour, a 5-minute cache has expired: the response writes most
95// of its input again; a 1-hour cache is still there: it reads most of it.
96// Only the same model counts (each model has its own cache), and a short
97// pause, a small prompt or a mixed reading say nothing.
98type Seen = { at: number; model: string }
99const deduceTtl = (prev: Seen | null, at: number, usage: TurnUsage): number | undefined => {
100  if (prev === null || prev.model !== usage.model) return undefined
101  const gap = at - prev.at
102  if (gap <= TTL_5M + 30_000 || gap >= TTL_1H) return undefined
103  const total = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
104  if (total < 4096) return undefined
105  if (usage.cache_read_input_tokens >= total * 0.8) return TTL_1H
106  if (usage.cache_creation_input_tokens >= total * 0.5) return TTL_5M
107  return undefined
108}
109
110// Warnings, each given once: the cache about to expire while the session
111// waits (per response), and the session or week window crossing 85% and 95%
112// (per reset and band, kept in the store so the other sessions do not repeat it).
113const WARNED_KEY = 'warned'
114type Warned = Record<string, number>
115const LIMIT_BANDS = [95, 85] as const
116const cacheWarnBefore = (ttlMs: number) => (ttlMs === TTL_5M ? 60_000 : 5 * 60_000)
117
118// The tick for the auto-compact point.
119const MARK = 'rgba(140,140,140,0.9)'
120// The context's zone, from half the window to three quarters: the time to deal
121// with its size (compact, hand over) before the model works on a crowded one.
122// A faint stretch of the track, ticked at both ends, in the scale's yellow.
123const CTX_ZONE = [50, 75] as const
124const ZONE_FILL = 'rgba(212,167,44,0.22)'
125const ZONE_TICK = 'rgba(212,167,44,0.85)'
126// The cache's last minutes, shaded as the context's zone: 10 of the hour, or
127// the last 1 of a 5-minute cache.
128const cacheShadeMs = (ttlMs: number) => (ttlMs === TTL_5M ? 60_000 : 10 * 60_000)
129// The keep-alive: one tool-less fork of the main conversation, which the API
130// serves from its cache and so renews it, its reply kept out of the transcript.
131// A click arms it; it runs once, this long before the cache would expire (the
132// last 2 minutes of the hour, the last 1 of a 5-minute cache), and disarms.
133const keepAliveLeadMs = (ttlMs: number) => (ttlMs === TTL_5M ? 60_000 : 2 * 60_000)
134const KEEP_ALIVE_PROMPT = 'Keep-alive ping for the prompt cache. Reply with just: ok'
135const KEEP_ALIVE_GLYPH = '↻'
136// The faint dividers between a bar's segments, over the fill as on the track.
137const DIVIDER = 'rgba(140,140,140,0.45)'
138// The share of the bar at each divider: 7 segments, 6 dividers.
139// The arrow for where the window is now: a small triangle under the bar,
140// pointing up at it.
141const NOW_TICK = 'rgba(110,110,110,0.95)'
142const FIVE_HOURS = 5 * 60 * 60_000
143const WEEK = 7 * 24 * 60 * 60_000
144const dividers = (segments: number | undefined) =>
145  segments === undefined ? [] : Array.from({ length: segments - 1 }, (_, i) => ((i + 1) / segments) * 100)
146
147// Desktop: one cell of the band is about 9.5 px (measured: 95 columns).
148const PX_PER_COLUMN = 9.5
149const BAR_HEIGHT = 8
150const FRAME_HEIGHT = 20
151const BAR_INSET = 3
152// Average advance of the 9 px face, to cut a text that would not fit.
153const PX_PER_CHAR = 5.2
154
155const clamp = (percent: number) => Math.min(Math.max(percent, 0), 100)
156
157const esc = (text: string) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
158
159const kTokens = (n: number) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1000)}k`)
160
161const duration = (ms: number) => {
162  const minutes = Math.max(0, Math.round(ms / 60_000))
163  const d = Math.floor(minutes / 1440)
164  const h = Math.floor((minutes % 1440) / 60)
165  const m = minutes % 60
166  return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : `${m}m`
167}
168
169const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
170const clockTime = (ms: number) => {
171  const at = new Date(ms)
172  return `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`
173}
174const dayTime = (ms: number) => `${DAYS[new Date(ms).getDay()]} ${clockTime(ms)}`
175
176// What a meter shows in place of its bar: the pill, its alternative text, or
177// the verbose form of that text.
178type Face = 'pill' | 'alt' | 'verbose' | 'name' | 'keep'
179
180// The label's tooltip: its name in full, drawn in the graph's place while the
181// pointer is on the label.
182const NAMES: Record<Key, [string, string]> = {
183  ctx: ['Context', 'context window'],
184  cch: ['Cache', 'prompt cache'],
185  ses: ['Session', '5-hour window'],
186  wk: ['Week', 'weekly limit'],
187}
188
189// The graph is a plain SVG image of one face: the pointer is read by the
190// invisible Client laid over it (hit.tsx), not by CSS, so a face can stay put.
191const meterSvg = (width: number, m: Meter, face: Face) => {
192  const color = HUES[m.key]
193  const barWidth = width - 2 * BAR_INSET
194  const r = BAR_HEIGHT / 2
195  const top = (FRAME_HEIGHT - BAR_HEIGHT) / 2
196  const xAt = (percent: number) => BAR_INSET + (clamp(percent) / 100) * barWidth
197  const fill = m.fill <= 0 ? 0 : Math.max(BAR_HEIGHT, (clamp(m.fill) / 100) * barWidth)
198  const room = Math.max(4, Math.floor((width - BAR_INSET) / PX_PER_CHAR))
199  const fit = (t: string) => (t.length > room ? `${t.slice(0, room - 1)}…` : t)
200  const lines = ([a, b]: [string, string]) =>
201    `<text x="${width / 2}" y="8" fill="${color}">${esc(fit(a))}</text>` +
202    `<text x="${width / 2}" y="18" fill="${color}" class="s">${esc(fit(b))}</text>`
203  const body =
204    face === 'pill'
205      ? `<rect x="${BAR_INSET}" y="${top}" width="${barWidth}" height="${BAR_HEIGHT}" rx="${r}" fill="${TRACK}"/>` +
206        // rounded at the start, as the track, and square at its end
207        (m.shade === undefined
208          ? ''
209          : `<path d="M${BAR_INSET + r} ${top}h${Math.max(0, xAt(m.shade) - BAR_INSET - r).toFixed(1)}v${BAR_HEIGHT}H${BAR_INSET + r}a${r} ${r} 0 0 1 0 -${BAR_HEIGHT}z" fill="${ZONE_FILL}" data-shade="${m.shade.toFixed(1)}"/>`) +
210        (m.zone === undefined
211          ? ''
212          : `<rect x="${xAt(m.zone[0]).toFixed(1)}" y="${top}" width="${(xAt(m.zone[1]) - xAt(m.zone[0])).toFixed(1)}" height="${BAR_HEIGHT}" fill="${ZONE_FILL}" data-zone="band"/>`) +
213        (fill ? `<rect x="${BAR_INSET}" y="${top}" width="${fill.toFixed(1)}" height="${BAR_HEIGHT}" rx="${r}" fill="${color}"/>` : '') +
214        (m.zone === undefined
215          ? ''
216          : m.zone
217              .map(at => `<rect x="${(xAt(at) - 0.5).toFixed(1)}" y="${top - 2}" width="1" height="${BAR_HEIGHT + 4}" fill="${ZONE_TICK}" data-zone="${at}"/>`)
218              .join('')) +
219        dividers(m.segments)
220          .map(at => `<rect x="${(xAt(at) - 0.5).toFixed(1)}" y="${top}" width="1" height="${BAR_HEIGHT}" fill="${DIVIDER}" data-divider="${at.toFixed(1)}"/>`)
221          .join('') +
222        (m.now === undefined
223          ? ''
224          : `<path d="M${xAt(m.now).toFixed(1)} ${top + BAR_HEIGHT + 1}l3 4.5h-6z" fill="${NOW_TICK}" data-now="${m.now.toFixed(1)}"/>`) +
225        (m.mark === undefined
226          ? ''
227          : `<rect x="${(BAR_INSET + (clamp(m.mark) / 100) * barWidth - 0.75).toFixed(1)}" y="${top - 3}" width="1.5" height="${BAR_HEIGHT + 6}" rx="0.75" fill="${MARK}" data-mark="compact"/>`)
228      : lines(face === 'alt' ? m.alt : face === 'name' ? NAMES[m.key] : face === 'keep' && m.keepAlive ? m.keepAlive : m.verbose)
229  return (
230    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${FRAME_HEIGHT}" viewBox="0 0 ${width} ${FRAME_HEIGHT}" data-face="${face}">` +
231    `<style>text{font:600 9px -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;text-anchor:middle}.s{font-weight:400;opacity:.8}</style>` +
232    body +
233    `</svg>`
234  )
235}
236
237// The shared file, read and written straight from the disk so each session sees
238// what the others wrote. A missing or broken file reads as nothing.
239// eslint-disable-next-line @typescript-eslint/no-explicit-any
240async function readShared($: any, path: string | null): Promise<Shared | null> {
241  if (path === null) return null
242  try {
243    const shared = JSON.parse(String(await $.fs.read(path))) as Shared
244    return typeof shared.readAt === 'number' ? shared : null
245  } catch {
246    return null
247  }
248}
249
250// Written whole to a file of this session's own, then moved over the shared one,
251// so a reader never meets it half written. Where the move cannot run (no `mv`,
252// no process on this host) it is written in place. A reading older than the
253// one already shared is not written: two sessions answering at once never
254// put the older one back.
255// eslint-disable-next-line @typescript-eslint/no-explicit-any
256async function writeShared($: any, path: string | null, tmp: string | null, shared: Shared | null): Promise<void> {
257  if (path === null || shared === null) return
258  const there = await readShared($, path)
259  if (there !== null && there.readAt > shared.readAt) return
260  const text = JSON.stringify(shared)
261  if (tmp !== null) {
262    const isMoved = await $.fs
263      .write(tmp, text)
264      .then(() => $.process.run(['mv', '-f', tmp, path]))
265      .then((r: { exitCode: number }) => r.exitCode === 0)
266      .catch(() => false)
267    if (isMoved) return
268  }
269  await $.fs.write(path, text).catch(() => undefined)
270}
271
272// eslint-disable-next-line @typescript-eslint/no-explicit-any
273async function readLastResponses($: any): Promise<LastResponses> {
274  const value = await $.store.get(LAST_RESPONSE_KEY).catch(() => undefined)
275  return value !== null && typeof value === 'object' ? (value as LastResponses) : {}
276}
277
278// eslint-disable-next-line @typescript-eslint/no-explicit-any
279async function saveLastResponse($: any, sessionId: string | null, at: number): Promise<void> {
280  if (sessionId === null) return
281  const kept: LastResponses = { [sessionId]: at }
282  for (const [id, t] of Object.entries(await readLastResponses($))) {
283    if (id !== sessionId && typeof t === 'number' && at - t < TTL_1H) kept[id] = t
284  }
285  await $.store.set(LAST_RESPONSE_KEY, kept).catch(() => undefined)
286}
287
288// The lifetime a session deduced, kept in the store for all of them.
289// eslint-disable-next-line @typescript-eslint/no-explicit-any
290async function readTtl($: any): Promise<number | undefined> {
291  const saved = await $.store.get(TTL_KEY).catch(() => undefined)
292  return saved === TTL_5M || saved === TTL_1H ? saved : undefined
293}
294
295// The token count at which the context is compacted; undefined when off.
296// eslint-disable-next-line @typescript-eslint/no-explicit-any
297async function readCompactAt($: any): Promise<number | undefined> {
298  const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => null)
299  const breakdown = usage?.context?.breakdown
300  return breakdown?.isAutoCompactEnabled ? breakdown.autoCompactThreshold : undefined
301}
302
303// The keep-alive's fork, and a toast of how it went: resolves to when the
304// cache was renewed, or null.
305// eslint-disable-next-line @typescript-eslint/no-explicit-any
306async function forkKeepAlive($: any, sessionId: string | null): Promise<number | null> {
307  try {
308    const r = await $.model.fork({ prompt: KEEP_ALIVE_PROMPT })
309    if (!r.isAnswered) {
310      warn($, `Keep-alive failed: ${r.reason}${r.reason === 'api-error' && r.status ? ` ${r.status}` : ''}`, false, 'Prompt cache')
311      return null
312    }
313    // Read from the cache or written to it afresh, the prefix is cached now.
314    const at: number = await $.clock.now()
315    await saveLastResponse($, sessionId, at)
316    const read = r.usage.cache_read_input_tokens
317    const total = r.usage.input_tokens + read + r.usage.cache_creation_input_tokens
318    warn(
319      $,
320      read >= total * 0.8 ? `Prompt cache kept alive: ${kTokens(read)} read from it` : `Prompt cache had lapsed: ${kTokens(total - read)} written again`,
321      false,
322      'Prompt cache',
323    )
324    return at
325  } catch {
326    warn($, 'Keep-alive failed', false, 'Prompt cache')
327    return null
328  }
329}
330
331// A toast; an urgent one also as a notification, for a person away from the window.
332// eslint-disable-next-line @typescript-eslint/no-explicit-any
333function warn($: any, text: string, isUrgent: boolean, title: string): void {
334  try {
335    $.ui.toast(text, { timeoutMs: 15_000 })
336  } catch {
337    // nowhere to show it
338  }
339  if (!isUrgent) return
340  try {
341    void Promise.resolve($.ui.notify(text, { title })).catch(() => undefined)
342  } catch {
343    // no notification channel here
344  }
345}
346
347// The session or week window past 85% or 95%: once per reset and band, for
348// every session (the store remembers it was given).
349// eslint-disable-next-line @typescript-eslint/no-explicit-any
350async function warnLimits($: any, usage: Usage | null, now: number): Promise<void> {
351  if (usage === null) return
352  const windows = [
353    ['ses', 'Session', usage.fiveHour, false],
354    ['wk', 'Week', usage.week, true],
355  ] as const
356  const due = windows.flatMap(([key, name, w, isWeek]) => {
357    const resetAt = w?.resetsAt ? Date.parse(w.resetsAt) : NaN
358    const band = w ? LIMIT_BANDS.find(b => w.percent >= b) : undefined
359    if (!w || band === undefined || !Number.isFinite(resetAt) || resetAt <= now) return []
360    const when = isWeek ? dayTime(resetAt) : `at ${clockTime(resetAt)}`
361    return [{ id: `${key}:${resetAt}:${band}`, resetAt, band, text: `${name} at ${Math.round(w.percent)}% · resets ${when}` }]
362  })
363  if (due.length === 0) return
364  const saved = await $.store.get(WARNED_KEY).catch(() => undefined)
365  const warned: Warned = {}
366  for (const [id, at] of Object.entries((saved ?? {}) as Warned)) if (typeof at === 'number' && at > now) warned[id] = at
367  const fresh = due.filter(d => warned[d.id] === undefined)
368  if (fresh.length === 0) return
369  for (const d of fresh) {
370    warned[d.id] = d.resetAt
371    warn($, d.text, d.band >= RED_BAND, 'Usage limit')
372  }
373  await $.store.set(WARNED_KEY, warned).catch(() => undefined)
374}
375
376export const register: Register = on => {
377  let current: Usage | null = null
378  // When the session and week figures in `current` were read, by whichever session.
379  let readAt: number | null = null
380  let sharedPath: string | null = null
381  // This session's own file for writing the shared one whole before the move.
382  let tmpPath: string | null = null
383  let sessionId: string | null = null
384  let lastResponseAt: number | null = null
385  // The last response's model, beside its time, to deduce the cache's lifetime.
386  let lastSeen: Seen | null = null
387  let ttl = TTL_1H
388  let isTurnRunning = false
389  // The response the cache warning was last given for.
390  let cacheWarnedFor: number | null = null
391  // The token count at which the context is compacted; undefined when off.
392  let compactAt: number | undefined
393  // Meters the person pinned to their alternative text with a click, and the
394  // one under the pointer.
395  const pinned = new Set<Key>()
396  let hovered: Key | null = null
397  let hoveredLabel: Key | null = null
398  let hoveredValue: Key | null = null
399  let isKeepingAlive = false
400  let isArmed = false
401  const isKey = (k: unknown): k is Key => k === 'ctx' || k === 'cch' || k === 'ses' || k === 'wk'
402  const toggle = (k: Key) => {
403    if (pinned.has(k)) pinned.delete(k)
404    else pinned.add(k)
405  }
406
407  // Stamps this session's fresh reading of the windows, as the others read it.
408  const stamp = (at: number): Shared | null => {
409    if (current === null) return null
410    readAt = at
411    return { readAt: at, fiveHour: current.fiveHour, week: current.week }
412  }
413
414  // Takes the shared reading when it is fresher than the one shown.
415  const adopt = (shared: Shared | null) => {
416    if (shared === null || current === null || (readAt !== null && shared.readAt <= readAt)) return
417    current = { ...current, fiveHour: shared.fiveHour, week: shared.week }
418    readAt = shared.readAt
419  }
420
421  // The cache about to expire while the session waits for a prompt: what to
422  // say, once per response, or null.
423  const cacheWarning = (now: number): string | null => {
424    if (isTurnRunning || isArmed || lastResponseAt === null || cacheWarnedFor === lastResponseAt) return null
425    const left = lastResponseAt + ttl - now
426    if (left <= 0 || left > cacheWarnBefore(ttl)) return null
427    cacheWarnedFor = lastResponseAt
428    const tokens = current?.context.tokens
429    const cost =
430      tokens === undefined
431        ? ''
432        : `: the next prompt costs ${kTokens((tokens * CACHE_READ_HUNDREDTHS) / 100)} now, ${kTokens((tokens * writeHundredths(ttl)) / 100)} after`
433    return `Prompt cache expires in ${duration(left)}${cost}`
434  }
435
436  // The keep-alive is offered while the cache lives, and armed by a click.
437  const isCacheAlive = (now: number) => lastResponseAt !== null && lastResponseAt + ttl > now
438  const keepAliveAt = () => (lastResponseAt === null ? null : lastResponseAt + ttl - keepAliveLeadMs(ttl))
439
440  // The invisible regions over the graphs report the pointer here.
441  on('ui.message', async ($, e, next) => {
442    const data = e.data as { meter?: unknown; part?: unknown; type?: unknown } | null
443    if (e.module.endsWith('hit.tsx') && data && isKey(data.meter)) {
444      const isLabel = data.part === 'label'
445      if (data.part === 'value') {
446        if (data.type === 'enter') hoveredValue = data.meter
447        else if (data.type === 'leave') hoveredValue = hoveredValue === data.meter ? null : hoveredValue
448        else if (data.type === 'click' && data.meter === 'cch' && !isArmed && !isKeepingAlive && isCacheAlive(await $.clock.now()))
449          isArmed = true
450      } else if (data.type === 'enter') {
451        if (isLabel) hoveredLabel = data.meter
452        else hovered = data.meter
453      } else if (data.type === 'leave') {
454        if (isLabel) hoveredLabel = hoveredLabel === data.meter ? null : hoveredLabel
455        else hovered = hovered === data.meter ? null : hovered
456      } else if (data.type === 'click') toggle(data.meter)
457      $.ui.invalidate('ui.render')
458      return {}
459    }
460    return next(e)
461  })
462
463  on('session.start', async ($, e, next) => {
464    const home = await $.env.get('HOME')
465    sharedPath = home ? `${home}/${SHARED_FILE}` : null
466    sessionId = await $.session.id().catch(() => null)
467    tmpPath = sharedPath === null ? null : `${sharedPath}.${sessionId ?? crypto.randomUUID()}.tmp`
468    // A resumed session (or a reload) takes up the cache countdown it had.
469    const saved = sessionId === null ? undefined : (await readLastResponses($))[sessionId]
470    if (typeof saved === 'number') lastResponseAt = saved
471    ttl = (await readTtl($)) ?? ttl
472    const { context, rateLimits } = await $.session.usage()
473    current = toUsage(context, rateLimits)
474    compactAt = await readCompactAt($)
475    adopt(await readShared($, sharedPath))
476    // Every 30 s: take a fresher reading and lifetime another session shared,
477    // warn what is due, and redraw (the cache countdown and the reset times
478    // move on their own).
479    void $.clock.every(30_000, async () => {
480      adopt(await readShared($, sharedPath))
481      ttl = (await readTtl($)) ?? ttl
482      const now = await $.clock.now()
483      // The armed keep-alive, due: run it once, then the button is back.
484      const dueAt = keepAliveAt()
485      if (isArmed && !isTurnRunning && dueAt !== null && now >= dueAt) {
486        isArmed = false
487        if (isCacheAlive(now)) {
488          isKeepingAlive = true
489          $.ui.invalidate('ui.render')
490          const at = await forkKeepAlive($, sessionId)
491          if (at !== null) lastResponseAt = at
492          isKeepingAlive = false
493        } else warn($, 'Keep-alive missed: the prompt cache had already expired', false, 'Prompt cache')
494      }
495      const cacheText = cacheWarning(now)
496      if (cacheText !== null) warn($, cacheText, true, 'Prompt cache')
497      await warnLimits($, current, now)
498      $.ui.invalidate('ui.render')
499    })
500    $.ui.invalidate('ui.render')
501    return next(e)
502  })
503
504  on('session.measure', async ($, e, next) => {
505    current = toUsage(e.context, e.rateLimits)
506    const now = await $.clock.now()
507    if (e.rateLimits.length > 0) await writeShared($, sharedPath, tmpPath, stamp(now))
508    await warnLimits($, current, now)
509    $.ui.invalidate('ui.render')
510    return next(e)
511  })
512
513  on('turn.start', async ($, e, next) => {
514    // A new prompt renews the cache itself: an armed keep-alive is not needed.
515    if (!e.agentId) {
516      isTurnRunning = true
517      isArmed = false
518    }
519    return next(e)
520  })
521
522  // Every response of the main conversation renews the cache, the ones in the
523  // middle of a long turn too (each tool call's round trip rereads it): the
524  // countdown starts again as each one arrives, not only when the turn ends.
525  on('turn.step', async function* ($, e, next) {
526    const result = yield* next(e)
527    if (!e.agentId && result.usage !== null) {
528      const at = await $.clock.now()
529      const learned = deduceTtl(lastSeen, at, result.usage)
530      if (learned !== undefined && learned !== ttl) {
531        ttl = learned
532        await $.store.set(TTL_KEY, ttl).catch(() => undefined)
533      }
534      lastSeen = { at, model: result.usage.model }
535      lastResponseAt = at
536      await saveLastResponse($, sessionId, lastResponseAt)
537      $.ui.invalidate('ui.render')
538    }
539    return result
540  })
541
542  // The main conversation's last response renews the cache, and brought the
543  // account's windows as they are now: share them.
544  on('turn.complete', async ($, e, next) => {
545    const result = await next(e)
546    if (!e.agentId) {
547      isTurnRunning = false
548      lastResponseAt = await $.clock.now()
549      await saveLastResponse($, sessionId, lastResponseAt)
550      const { context, rateLimits } = await $.session.usage()
551      if (rateLimits.length > 0) {
552        current = toUsage(context, rateLimits)
553        await writeShared($, sharedPath, tmpPath, stamp(lastResponseAt))
554        await warnLimits($, current, lastResponseAt)
555      }
556      compactAt = await readCompactAt($)
557      $.ui.invalidate('ui.render')
558    }
559    return result
560  })
561
562  const meters = (usage: Usage, now: number): Meter[] => {
563    const ctx = usage.context
564    const pct = (p: number | undefined) => (p === undefined ? '—' : `${Math.round(p)}%`)
565
566    const ctxUsed = ctx.tokens !== undefined ? kTokens(ctx.tokens) : '—'
567    const ctxMeter: Meter = {
568      key: 'ctx',
569      label: 'Ctx',
570      level: ctx.percent,
571      fill: ctx.percent ?? 0,
572      value: pct(ctx.percent),
573      alt: [ctxUsed, kTokens(ctx.window)],
574      verbose: [
575        `Used: ${ctxUsed} tokens`,
576        `Window: ${kTokens(ctx.window)}${compactAt !== undefined ? ` · compacts at ${kTokens(compactAt)}` : ''}`,
577      ],
578      zone: CTX_ZONE,
579      ...(compactAt !== undefined && compactAt < ctx.window ? { mark: (compactAt / ctx.window) * 100 } : {}),
580    }
581
582    const elapsed = lastResponseAt === null ? undefined : Math.max(0, now - lastResponseAt)
583    const left = elapsed === undefined ? undefined : ttl - elapsed
584    // What the next prompt costs for the context, in plain input-token
585    // equivalents: with the cache alive, and once it has expired.
586    const warm = ctx.tokens !== undefined ? (ctx.tokens * CACHE_READ_HUNDREDTHS) / 100 : undefined
587    const cold = ctx.tokens !== undefined ? (ctx.tokens * writeHundredths(ttl)) / 100 : undefined
588    // Said only when it is not the 1 hour assumed.
589    const ttlNote = ttl === TTL_5M ? ' · 5m cache' : ''
590    const cost = warm === undefined || cold === undefined ? '—' : `${kTokens(warm)} → ${kTokens(cold)}`
591    const costVerbose =
592      warm === undefined || cold === undefined ? 'Next prompt: n/a' : `${kTokens(warm)} now, ${kTokens(cold)} expired`
593    const cchMeter: Meter =
594      left === undefined || elapsed === undefined
595        ? { key: 'cch', label: 'Cch', level: undefined, fill: 0, value: '—', alt: ['—', cost], verbose: ['No response yet', costVerbose] }
596        : left <= 0
597          ? {
598              key: 'cch',
599              label: 'Cch',
600              level: 100,
601              fill: 0,
602              value: 'exp',
603              alt: ['expired', cold === undefined ? '—' : `→ ${kTokens(cold)}`],
604              verbose: [`Expired ${duration(-left)} ago${ttlNote}`, cold === undefined ? 'Next prompt: n/a' : `Next prompt: ${kTokens(cold)}`],
605            }
606          : {
607              key: 'cch',
608              label: 'Cch',
609              level: (elapsed / ttl) * 100,
610              fill: (left / ttl) * 100,
611              value: isKeepingAlive ? '…' : `${Math.ceil(left / 60_000)}m`,
612              alt: [`${Math.ceil(left / 60_000)} min`, cost],
613              verbose: [`Expires in ${duration(left)}${ttlNote}`, costVerbose],
614              shade: (cacheShadeMs(ttl) / ttl) * 100,
615              ...(isKeepingAlive
616                ? {}
617                : {
618                    keepAlive: (isArmed
619                      ? [`${KEEP_ALIVE_GLYPH} Keep-alive armed`, `runs at ${clockTime(now + left - keepAliveLeadMs(ttl))}`]
620                      : [`${KEEP_ALIVE_GLYPH} Keep alive`, warm === undefined ? `at ${duration(keepAliveLeadMs(ttl))} left` : `at ${duration(keepAliveLeadMs(ttl))} left · ~${kTokens(warm)}`]) as [string, string],
621                    isArmed,
622                  }),
623            }
624
625    const age = readAt === null ? '' : now - readAt < 60_000 ? 'now' : `${duration(now - readAt)} ago`
626    const resetMeter = (key: Key, label: string, w: Window | null, isWeek: boolean, segments?: number, spanMs?: number): Meter => {
627      const resetAt = w?.resetsAt ? Date.parse(w.resetsAt) : NaN
628      const when = (ms: number) => (isWeek ? dayTime(ms) : clockTime(ms))
629      // Past its reset time the window is back to zero, whatever was last read.
630      if (Number.isFinite(resetAt) && resetAt <= now) {
631        return {
632          key,
633          label,
634          level: undefined,
635          fill: 0,
636          value: '0%',
637          alt: ['reset', when(resetAt)],
638          verbose: [`Reset ${isWeek ? 'on' : 'at'} ${when(resetAt)}`, 'awaiting a new reading'],
639          ...(segments === undefined ? {} : { segments }),
640        }
641      }
642      const hasReset = Number.isFinite(resetAt)
643      const at = hasReset ? when(resetAt) : ''
644      const nowAt = hasReset && spanMs !== undefined ? clamp(100 - ((resetAt - now) / spanMs) * 100) : undefined
645      return {
646        key,
647        label,
648        level: w?.percent,
649        fill: w?.percent ?? 0,
650        value: pct(w?.percent),
651        alt: hasReset ? [`-${duration(resetAt - now)}`, at] : ['—', '—'],
652        verbose: hasReset
653          ? [`Resets in ${duration(resetAt - now)}`, `${isWeek ? 'on' : 'at'} ${at}${age ? ` · ${age}` : ''}`]
654          : ['No reading yet', ''],
655        ...(segments === undefined ? {} : { segments }),
656        ...(nowAt === undefined ? {} : { now: nowAt }),
657      }
658    }
659
660    return [
661      ctxMeter,
662      cchMeter,
663      resetMeter('ses', 'Ses', usage.fiveHour, false, 5, FIVE_HOURS),
664      resetMeter('wk', 'Wk', usage.week, true, 7, WEEK),
665    ]
666  }
667
668  // The elements come from each surface's table. Four columns of equal width:
669  // label, graph and value. Hovering the graph shows the next face; a click on
670  // the graph or on the label pins the alternative text, a second one unpins
671  // it; in the red band the alternative text shows by itself.
672  // eslint-disable-next-line @typescript-eslint/no-explicit-any
673  const usageLine = (Box: any, Text: any, Button: any, Svg: any, Client: any, list: Meter[], bodyColumns: number, onLabel: (k: Key) => void) => {
674    const isTerminal = Svg === undefined
675    // Per column: label (3) and value (4) hug the graph, which takes the rest;
676    // 2 cells between columns, one more kept spare.
677    const gap = 2
678    const columnCells = (bodyColumns - gap * (list.length - 1)) / list.length
679    const barPx = Math.round(Math.max(6, columnCells - 3 - 4 - 1) * PX_PER_COLUMN)
680
681    return (
682      <Box flexDirection="row" width="100%" columnGap={gap}>
683        {list.map(m => {
684          const level = m.level === undefined ? undefined : levelFor(m.level)
685          const valueColor = m.level === undefined ? 'inactive' : (level?.color ?? HUES[m.key])
686          const isPinned = pinned.has(m.key) || (m.level !== undefined && m.level >= RED_BAND)
687          const rest: Face = isPinned ? 'alt' : 'pill'
688          const isOffering = m.keepAlive !== undefined && hoveredValue === m.key
689          const valueText = m.isArmed ? `${KEEP_ALIVE_GLYPH}${m.value}` : m.value
690          const face: Face =
691            hoveredLabel === m.key
692              ? 'name'
693              : isOffering
694                ? 'keep'
695                : hovered === m.key
696                  ? rest === 'alt'
697                    ? 'verbose'
698                    : 'alt'
699                  : rest
700          const text = face === 'alt' ? m.alt : face === 'name' ? NAMES[m.key] : face === 'keep' && m.keepAlive ? m.keepAlive : m.verbose
701          const graph = isTerminal ? (
702            face === 'pill' ? (
703              <Box width="100%" height={1} backgroundColor="subtle" overflow="hidden" position="relative">
704                <Box width={`${Math.round(clamp(m.fill))}%`} height={1} backgroundColor={HUES[m.key]} />
705                {(m.zone ?? []).map(at => (
706                  <Box key={`zone-${m.key}-${at}`} position="absolute" top={0} left={0} width={`${at}%`} height={1} flexDirection="row" justifyContent="flex-end">
707                    <Text color={ZONE_TICK}>▕</Text>
708                  </Box>
709                ))}
710                {dividers(m.segments).map(at => (
711                  <Box key={`divider-${m.key}-${at}`} position="absolute" top={0} left={0} width={`${Math.round(at)}%`} height={1} flexDirection="row" justifyContent="flex-end">
712                    <Text color={DIVIDER}>│</Text>
713                  </Box>
714                ))}
715                {m.now === undefined ? null : (
716                  <Box key={`now-${m.key}`} position="absolute" top={0} left={0} width={`${Math.round(m.now)}%`} height={1} flexDirection="row" justifyContent="flex-end">
717                    <Text color={NOW_TICK}>┃</Text>
718                  </Box>
719                )}
720                {m.mark === undefined ? null : (
721                  <Box key={`mark-${m.key}`} position="absolute" top={0} left={0} width={`${Math.round(clamp(m.mark))}%`} height={1} flexDirection="row" justifyContent="flex-end">
722                    <Text color={MARK}>▕</Text>
723                  </Box>
724                )}
725              </Box>
726            ) : (
727              <Text color={HUES[m.key]} wrap="truncate-end">{` ${text[0]} · ${text[1]}`}</Text>
728            )
729          ) : (
730            <Svg source={meterSvg(barPx, m, face)} alt={`${m.verbose[0]}. ${m.verbose[1]}`} width={barPx} height={FRAME_HEIGHT} />
731          )
732          const bar = (
733            <Box {...(isTerminal ? { flexGrow: 1, width: 0 } : { flexShrink: 0 })} height={1} position="relative" alignItems="center" overflow="hidden">
734              {graph}
735              {Client ? (
736                <Box position="absolute" top={0} left={0} right={0} bottom={0}>
737                  <Client key={`hit-${m.key}`} module="./hit.tsx" props={{ meter: m.key }} width="100%" height={1} />
738                </Box>
739              ) : null}
740            </Box>
741          )
742          return (
743            <Box key={`usage-${m.key}`} flexGrow={1} width={0} flexDirection="row" alignItems="center">
744              {Client ? (
745                <Box position="relative" flexShrink={0}>
746                  <Text dimColor>{m.label}</Text>
747                  <Box position="absolute" top={0} left={0} right={0} bottom={0}>
748                    <Client key={`hit-label-${m.key}`} module="./hit.tsx" props={{ meter: m.key, part: 'label' }} width="100%" height={1} />
749                  </Box>
750                </Box>
751              ) : (
752                <Button key={`label-${m.key}`} label={m.label} plain dimColor onPress={() => onLabel(m.key)} />
753              )}
754              {bar}
755              {/* The keep-alive keeps the value's width: under a narrower glyph the
756                  pointer would leave it, bring the minutes back, and flicker. */}
757              <Box
758                flexShrink={0}
759                marginLeft={isTerminal ? 1 : 0}
760                position="relative"
761                {...(m.keepAlive === undefined ? {} : { width: valueText.length, justifyContent: 'center' })}
762              >
763                {isOffering ? (
764                  <Text color={HUES[m.key]} bold={!m.isArmed} dimColor={m.isArmed === true}>
765                    {KEEP_ALIVE_GLYPH}
766                  </Text>
767                ) : (
768                  <Text color={valueColor} bold={level?.isBold === true}>
769                    {valueText}
770                  </Text>
771                )}
772                {Client && m.key === 'cch' ? (
773                  <Box position="absolute" top={0} left={0} right={0} bottom={0}>
774                    <Client key={`hit-value-${m.key}`} module="./hit.tsx" props={{ meter: m.key, part: 'value' }} width="100%" height={1} />
775                  </Box>
776                ) : null}
777              </Box>
778            </Box>
779          )
780        })}
781      </Box>
782    )
783  }
784
785  // One line in the band right above the prompt box (terminal and desktop).
786  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
787    if (current === null || e.props.hasSurvey) return next(e)
788
789    const now = await $.clock.now()
790    const list = meters(current, now)
791    const onLabel = (k: Key) => {
792      toggle(k)
793      $.ui.invalidate('ui.render')
794    }
795    if (e.surface === 'terminal') {
796      const { Box, Text, Button, Client } = $.ui.resolve(e)
797      return usageLine(Box, Text, Button, undefined, Client, list, e.props.bodyColumns, onLabel)
798    }
799    const { Box, Text, Button, Svg } = $.ui.resolve(e)
800    const Client = e.surface === 'desktop' ? $.ui.resolve(e).Client : undefined
801    return usageLine(Box, Text, Button, Svg, Client, list, e.props.bodyColumns, onLabel)
802  })
803}
804
hooks/hit.tsx 22 lines
1import type { ClientModule } from 'claude-code'
2
3// An invisible region laid over one meter's graph, label or value: it reports the
4// pointer entering, leaving and clicking to the hooks module, which picks the
5// face the graph shows (pill, alternative, verbose or the label's full name)
6// and keeps the pins.
7type Props = { meter: string; part?: 'graph' | 'label' | 'value' }
8
9const Hit: ClientModule<Props, true> = (props, surface) => {
10  if (surface.state === undefined) {
11    surface.onPointer(e => {
12      if (e.type === 'enter' || e.type === 'leave') surface.post({ meter: props.meter, part: props.part ?? 'graph', type: e.type })
13      else if (e.type === 'down' && e.button === 'left') surface.post({ meter: props.meter, part: props.part ?? 'graph', type: 'click' })
14    })
15    surface.setState(true)
16  }
17  const { Box } = surface.elements
18  return <Box width="100%" height={1} />
19}
20
21export default Hit
22