SLOPSHOPPER

context-cache

A panel above the prompt showing context usage, usage limits (session, weekly, Fable) and prompt-cache temperature, with Clear, Compact and Warm buttons, what…

panebandcommandtoastmodelnetwork
★ 2v0.1.11MITupdated 2026-10-26Christandoh/context-cache
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · context-cache
│ ┃ Context & cache ✕ › fix the failing auth test and add an audit log call │ ┃ ╭─────────────────────────────────────────── │ ┃ │ Context 97k / 200k (49%) ━━━━━━━━━━━━━━━━━ ⏺ Read(src/auth.ts) │ ┃ │ ● System 0 ● Tools 0 ● Files 0 ● ⎿ Read 6 lines │ ┃ │ Messages 0 Free 103k ⏺ Update(src/auth.ts) │ ┃ │ ◷ 31% ▦ — ✦ — ♨ Warm ⎿ Added 2 lines, removed 1 line │ ┃ │ Time 80% 100% warm ⏺ Bash(bun test) │ ┃ │ ● Cache warm: reuses 97k (≈$0.02). ⎿ 3 pass, 1 fail │ ┃ │ [ Clear ] [ Compact ] [ Warm ] │ ┃ ╰─────────────────────────────────────────── ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /cache │ ⎿ context-cache: Context & cache panel hidden. /cache shows it aga │ │ ● Context 49% · Cache warm, 60m left · Next message ≈$0.02 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
● Context 49% · Cache warm, 60m left · Next message ≈$0.02
Pane · Context & cache
╭──────────────────────────────────────────────────────────╮ │ Context 97k / 200k (49%) ━━━━━━━━━━━━━━━━━━━━━━━ 49% │ │ ● System 0 ● Tools 0 ● Files 0 ● Messages 0 Free │ │ 103k │ │ ◷ 31% ▦ — ✦ — ♨ Warm │ │ Time 80% 100% warm │ │ ● Cache warm: reuses 97k (≈$0.02). │ │ [ Clear ] [ Compact ] [ Warm ] │ ╰──────────────────────────────────────────────────────────╯
README

Context-cache

version installs stars license Claude Code plugin

A Claude Code mod that puts your context window, your usage limits and your prompt cache on one card above the prompt. It shows in the terminal, in the desktop app's Code tab and, as a pane, on the phone.

The panel in the desktop app, live data

That's a real session. 315k of a 1M context window, the session limit at 10% with 39% of its five hours gone, the weekly limit at 75% with 71% of its week gone, Fable at 22%, and a prompt cache that is fully warm with 60 minutes left and every token of the last reply read from it. The notice at the bottom says what the next message will cost you, with Clear, Compact and Warm beside it.

Why

Claude Code already tells you all of this, in three places. /context has the window, /usage has the limits, and the cache is in the usage figures if you know where to look. None of it is on screen while you work, and the one number that changes what you do next, whether your cache is about to expire, isn't anywhere.

The cache matters more than it looks. Every reply re-sends the whole conversation. With the cache warm, 98% of that is served from memory at a tenth of the input price on most models, and a twentieth on Opus 5.5. Let it go cold, by walking away for an hour, and the next message pays full price to re-read everything. The panel counts that down and tells you before it happens.

A limit's percentage alone can mislead. Being at 60% of your weekly allowance is fine on Saturday and a problem on Tuesday. So each limit bar carries two layers. The dark one is how much of the window's time has passed, the bright one is how much you've used, and a white tick marks where time is. If the bright bar is past the tick you're ahead of pace, and the bar turns amber. At 90% it turns red.

What's on the card

The top row is the context window. Tokens used out of the window, split into System, Tools, Files and Messages, with a legend under the bar and a tick where auto-compact will fire. The share of the window used is in bold.

The middle row is three limits and the cache. Current session is the 5-hour window, Weekly the 7-day one, and Fable the model-specific weekly window. Each has the double bar described above, the two percentages and the reset time. Then the cache. Warm, Cooling or Cold, a temperature bar, how warm it is as a percentage of its time-to-live, the last reply's cache hit rate, and minutes left.

The bottom row is a one-line notice about the cache with three buttons. Clear runs /clear. Compact compacts the conversation. The notice puts a price on the next message, for example "Cache cold: next message re-reads 452k for ≈$3.62". After a Clear or Compact it turns green and says what was taken out and what that saves, for example "Cleared 452k. Next message costs ≈$3.57 less, or ≈$0.09 less while the cache is warm." That message stays until the next reply lands. In a narrow terminal the notice takes the longest wording that fits its line, so it never cuts off.

Warm keeps the cache from going cold while you're away. 55 minutes after the last reply it sends a hidden one-line ping over the conversation. The ping pays the cache-read price and resets the cache's hour. Going cold would instead pay twice the input price to write the 1-hour cache again, so a ping costs a twentieth of that on Sonnet 5, a fortieth on Opus 5.5 and an eightieth on Fable 5.1. Pressing Warm says the figure for your session's model. Nothing is added to the chat. While it runs, the notice line says when the next ping is due and what the last one read. The button becomes Stop while it runs, and warming stops on its own when you send a message, after 8 hours, after /clear, a compaction or a model switch, or if a ping misses the cache. It only works with the 1-hour cache. With the 5-minute cache, pinging that often would cost more than letting it go cold.

Warm can also switch itself on. /cache-autowarm 300 turns it on by itself once you've been quiet for 55 minutes with more than 300k in the context, the size where going cold starts to hurt. It's off until you set it. Pressing Stop holds it off until the next reply.

If nothing will keep the 1-hour cache, you hear about it with 5 minutes left, as a notification through your terminal ("Cache cold in 5m, ≈$3.62 to rebuild"), once per reply. The desktop app has no notification channel for mods, so there it's a toast.

As a limit reaches 90%, a toast says so once per window, for example "Weekly at 90%, resets Sat 11:00 pm". When a bar turns amber or red it flashes lighter twice, so the change catches your eye.

Switching model throws the cache away, because each model keeps its own. When the cache is still warm, /model or the model picker asks first: "Switching model throws away the warm cache: the next message re-writes 452k for ≈$9.04. Switch anyway?" A switch Claude Code makes on its own, such as a fallback, gets a toast with the same figures afterwards. Claude Code itself supplies the price.

The row never hides, whatever the cache holds, so the buttons are always there. With nothing cached yet, in a fresh session or after /clear or a compaction, it says how much the next message will write to the cache.

900 px, nothing cached yet, drawn from the mod's layout code

Four widths

The card re-lays itself as the window changes. Columns down to about 500 px, rings below that, and the legend drops at about 360 px. Below the widest layout the notice switches to a shorter wording, so it stays on one line. The widest layout is the screenshot at the top. These are the other three, from the same live session.

About 620 px, columns

About 420 px, rings with the legend

About 320 px, rings without the legend

Install

claude plugin marketplace add Christandoh/context-cache
claude plugin install context-cache@chris-mods

Inside a session, /plugin marketplace add Christandoh/context-cache and then /plugin install context-cache@chris-mods do the same. Installed at the user scope, it loads in every Claude Code session, including the desktop app's Code tab. Start a new session and the card is there.

Installing puts a copy in your plugin cache. claude plugin update context-cache@chris-mods fetches a new release whenever version in plugin.json has changed.

Two limits of the platform worth knowing. The desktop app's ordinary chat has no plugin surface, so the card can't appear there. And the panel's figures for the weekly and Fable limits come from an endpoint Anthropic hasn't documented (/usage reads the same one). If that endpoint changes, the Fable column shows "No data" and everything else keeps working.

Commands

/cache hides or shows the card.

/cache-status prints a diagnostics report. It lists which apps are attached, what the mod has drawn, where each figure came from, whether warming is on, and how the last account usage request went, down to the HTTP status and which window matched Fable. It also totals what was saved, today and over the last 7 days: the tokens Clear and Compact took out, and the Warm pings that kept the cache, each with the cache re-write it spared at list price. While Warm is on it adds the run itself: when it started, when it ends, the time of each ping, and what one ping costs against the re-write it saves. A Prices line names the list prices the money comes from, or says your model is missing from the list in hooks/model.ts, which is why the panel would then show tokens without money. The full report also lands in context-cache-status.json in the session's working directory.

/cache-pane opens the card as a pane, on any device.

/cache-refresh re-reads usage now instead of waiting for the next poll.

/cache-scale sets how many CSS pixels the desktop draws per band cell. The default is 8. /cache-scale 8.5 sets a value; a bare /cache-scale steps it up by a half, from 7 round to 9.5. You only need it if the card comes out narrower or wider than the composer.

/cache-mini draws the card as one line, "Context 45% · Cache warm, 59m left · Next message ≈$0.09", shortened to fit the band. Run it again for the whole card. The choice carries over to new sessions.

/cache-autowarm sets the context size above which Warm switches itself on, in thousands of tokens. /cache-autowarm 300 sets 300k, /cache-autowarm 0 turns it off, and a bare /cache-autowarm steps through off, 200k, 300k and 500k.

These are seven separate commands rather than one with arguments because the desktop composer drops anything typed after a slash command's name. That's also why the two that take a number step through values when given none.

Where the numbers come from

Every figure has a named source. One is worked out rather than reported. Files is the share of the conversation that is Read output, by character count, because Claude Code folds file reads into Messages.

FigureSource
Context used, window, auto-compact point$.session.usage(), the same figures as the status line and /context
System / Tools / Messages splitthe /context breakdown, scaled to the real token count
Filesthe share of Messages that is Read output, by character count
Session and weekly limitsthe rate-limit headers of every reply, so they move with each message. The headers can trail the account endpoint by a point, so when both describe the same window the panel shows the higher of the two, which matches /usage
Fable, and any reset time a header lacksAnthropic's account usage endpoint (api.anthropic.com/api/oauth/usage), called through Claude Code with your session's own login, so the mod never sees the token. Asked at most once every 5 minutes across all your open sessions, and on /cache-refresh. The first session to ask leaves a note in the mod's store, and the others use the reading it saves rather than asking too. A 429 holds them all back for as long as the endpoint says. Each good reading is saved, so a reopened chat that has not had a reply yet, and whose request is turned away (the endpoint answers 429 when many sessions ask), shows the last saved figures instead of nothing; windows that have reset since are left out. Fable is the limits[] item whose scope names Fable, matched by name so a moved key still works
Time %worked out from each window's reset time and its length (5h or 7d)
Cache TTL (5m or 60m)read from the cache_creation usage of your last response in the transcript, or from Claude Code's own report when you switch model; remembered across sessions
Last cache writeeach reply in the main conversation as it arrives, mid-turn included (or, on resume, how long ago the last response was)
Prices (≈$)the session's model from Claude Code, priced from a list in hooks/model.ts: input and cache-read list prices, with a cache write at 2× input for the 1-hour cache and 1.25× for 5 minutes. On a subscription you don't pay per token, so read it as how much of your limits the tokens would use. An unknown model shows tokens only
What Clear or Compact savedthe context before, and again once Claude Code reports the new size
Hit %cache reads divided by (cache reads + cache writes + uncached input), for the last reply during a turn and for the whole turn once it ends

Warmth is remaining TTL divided by TTL. Warm above 25%, Cooling between 1 and 25%, Cold at 0%. A /clear, a compaction or a model switch empties the cache, and the card shows "Nothing cached yet" until the first reply of the next turn arrives.

Working on it

git clone https://github.com/Christandoh/context-cache
claude plugin marketplace add ./context-cache
claude plugin install context-cache@chris-mods

A warning from experience. claude plugin list will say the plugin is read from your folder, but the engine runs a copy under ~/.claude/plugins/cache/chris-mods/context-cache/<version> taken at install time. Edits to the folder never reach the running mod, and /reload-plugins only reloads the stale copy. After editing, refresh the copy:

claude plugin uninstall context-cache@chris-mods
claude plugin install context-cache@chris-mods

then /reload-plugins in an open session. Slash commands register when a session starts, so a brand-new command needs a new session. For a single terminal session, claude --plugin-dir ./context-cache skips the install.

Check it with:

claude plugin validate .

hooks/register.tsx holds the hooks: data collection, the commands and the band. hooks/model.ts is the maths, thresholds and copy, with no drawing in it. hooks/view.tsx draws the terminal version in cells and the desktop version as the SVG panel plus the host's buttons. hooks/panel-svg.ts lays the design out as SVG at its real pixel sizes, measuring text with the font widths in hooks/metrics.ts. types/index.d.ts is the mod's $.state contract.

Licence

MIT. See LICENSE.

Installs

The installs badge and the chart below count clones of this repo. Adding the marketplace clones it, so each install shows up as one. Reinstalls and updates clone it too, so the number runs a little high. Nothing is sent from your machine.

<img alt="Installs over time" src="https://raw.githubusercontent.com/Christandoh/context-cache/traffic/line-light.svg" width="100%">

Source 6 files
hooks/register.tsx 990 lines
1// context-cache: a panel above the prompt with context usage, usage limits
2// (session, weekly, Fable) and prompt-cache temperature, plus Clear / Compact / Warm.
3//
4// Where each number comes from (all real, nothing sampled):
5// - Context: $.session.usage() (the status line's figures) and its /context
6//   breakdown; Files is the share of Messages that is file contents read.
7// - Limits: the account usage endpoint (api.anthropic.com/api/oauth/usage),
8//   called with the session's own credential through the host; falls back to
9//   the rate-limit headers of the last response, then to the last good
10//   account reading any session saved (windows that have reset are dropped).
11// - Cache: the time of the last main-thread response, the TTL the responses
12//   were cached with (read from the transcript's usage, or the engine's own
13//   model-switch report), and the last turn's cache-read share.
14// - Prices: $.session.model(), priced from the list in model.ts. After a Clear
15//   or Compact the notice says what was taken out (context before and after).
16//
17// Also: auto-warm above a context size (/cache-autowarm), a notice when the
18// cache has 5 minutes left, a toast as a limit reaches 90%, a pulse when a bar
19// turns amber or red, and the band as one line (/cache-mini).
20
21import { atom, read, update } from 'claude-code'
22import type { EngineInterface, Register } from 'claude-code'
23
24import type { ContextCacheCache, ContextCacheLimit, ContextCacheSnapshot, ContextCacheWarming } from '../types'
25import {
26  buildContext,
27  buildView,
28  cacheView,
29  fmtClock,
30  fmtSpan,
31  fmtTokens,
32  fmtUsd,
33  priceOf,
34  noticeText,
35  pct,
36  sizeClassOf,
37  type ViewModel,
38  fileShareOf,
39  isPulseLit,
40  limitToast,
41  miniLine,
42  limitsFromResponse,
43  listPrice,
44  parseAccountUsage,
45  timePct,
46  toneOf,
47  TTL_1H,
48  TTL_5M,
49  usageWindowsOf,
50  warmNotice,
51} from './model'
52import { renderDesktop, renderMini, renderTerminal, type Actions } from './view'
53
54const snapshotAtom = atom({ plugin: 'context-cache', key: 'snapshot' } as const, null)
55const hiddenAtom = atom({ plugin: 'context-cache', key: 'isHidden' } as const, false)
56const nowAtom = atom({ plugin: 'context-cache', key: 'now' } as const, 0)
57// Desktop and mobile draw the design in CSS px, but the band is measured in
58// cells; this is the conversion. 8 fits the desktop app's default font;
59// /cache scale <px> adjusts it and the value is kept across sessions.
60const pxPerCellAtom = atom({ plugin: 'context-cache', key: 'pxPerCell' } as const, 8)
61const DEFAULT_PX_PER_CELL = 8
62const warmUntilAtom = atom({ plugin: 'context-cache', key: 'warmUntil' } as const, null)
63// /cache-mini: the band as one line; kept across sessions in the store.
64const miniAtom = atom({ plugin: 'context-cache', key: 'isMini' } as const, false)
65
66// Keep-warm: a cache read resets the 1h TTL for free, so one tool-less fork of
67// the main thread 55 min after the last reply keeps it alive at the cache-read
68// price (a tenth of input on most models, a twentieth on Opus 5.5) where a
69// cold re-write is 2x input. The fork never enters the transcript.
70const WARM_AFTER_MS = 55 * 60_000
71const WARM_FOR_MS = 8 * 60 * 60_000
72const WARM_PROMPT = 'Keep-alive ping for the prompt cache. Reply with only: ok'
73let warmInFlight = false
74/** The last successful ping of this warming run, for the notice line. */
75let lastPing: { at: number; read: number } | null = null
76/** This warming run for /cache-status, kept in the store so a reload keeps it. */
77type WarmRun = { startedAt: number; until: number; pings: { at: number; read: number }[] }
78
79async function startWarmRun($: EngineInterface, startedAt: number, until: number) {
80  lastPing = null
81  await $.store.set('warmRun', { startedAt, until, pings: [] } satisfies WarmRun)
82}
83
84const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
85// The account endpoint answers 429 to anyone who leans on it; the status-line
86// tools that use it hold to one request per 5 minutes, so this does too. The
87// 5h/7d figures still move every response through the rate-limit headers.
88const ACCOUNT_EVERY_MS = 5 * 60_000
89// Two reset times this close describe the same window (the sources round differently).
90const SAME_WINDOW_MS = 30 * 60_000
91const MAX_TRANSCRIPT_BYTES = 4 * 1024 * 1024 - 1024
92
93const emptyCache = (ttlMs: number, isTtlKnown: boolean): ContextCacheCache => ({
94  lastAt: null,
95  ttlMs,
96  isTtlKnown,
97  hitRate: null,
98})
99
100/** The TTL a response was cached with, from a transcript line's usage. */
101export function ttlFromTranscript(text: string): number | null {
102  const lines = text.split('\n')
103  for (let i = lines.length - 1, seen = 0; i >= 0 && seen < 400; i--, seen++) {
104    const line = lines[i]
105    if (!line || !line.includes('cache_creation')) continue
106    try {
107      const row = JSON.parse(line) as { message?: { usage?: { cache_creation?: Record<string, number> } } }
108      const cc = row.message?.usage?.cache_creation
109      if (!cc) continue
110      if ((cc['ephemeral_1h_input_tokens'] ?? 0) > 0) return TTL_1H
111      if ((cc['ephemeral_5m_input_tokens'] ?? 0) > 0) return TTL_5M
112    } catch {
113      // a partial line; keep looking
114    }
115  }
116  return null
117}
118
119// Module state: rebuilt on reload; what the drawing needs lives in $.state.
120let accountLimits: ContextCacheLimit[] | null = null
121let accountAt = 0
122let accountInFlight = false
123let refreshing: Promise<void> | null = null
124// Diagnostics for /cache status: what asked the mod to draw, and where, and
125// how the last account usage request went.
126const draws: Record<string, number> = {}
127const attached: string[] = []
128let cwd = ''
129const DIAG_FILE = 'context-cache-status.json' // written in the session's working directory
130type AccountDiag = {
131  at: number
132  authKind: string
133  status: number | null
134  ok: boolean | null
135  topLevelKeys: string[]
136  /** JSON paths of every node with a utilization figure, and which matched Fable. */
137  windows: string[]
138  fableMatched: string[]
139  bodyPreview: string
140  error: string | null
141}
142let lastAccount: AccountDiag | null = null
143
144function noteDraw(component: string, surface: string) {
145  const k = `${component}@${surface}`
146  draws[k] = (draws[k] ?? 0) + 1
147}
148
149async function statusReport($: EngineInterface): Promise<string> {
150  let surfaces: readonly string[] = []
151  try {
152    surfaces = await $.session.surfaces()
153  } catch {
154    surfaces = []
155  }
156  const [snap, hidden, pxPerCell, warmUntil] = await Promise.all([
157    read($, snapshotAtom),
158    read($, hiddenAtom),
159    read($, pxPerCellAtom),
160    read($, warmUntilAtom),
161  ])
162  const warming = snap ? await warmingOf($, snap) : null
163  const drawn = Object.entries(draws).map(([k, n]) => `${k} ×${n}`).join(', ') || 'nothing yet'
164  const a = lastAccount
165  const account = a
166    ? `auth ${a.authKind}, HTTP ${a.status ?? '—'}${a.ok === false ? ' (not ok)' : ''}` +
167      `${a.error ? `, error: ${a.error}` : ''}; keys: ${a.topLevelKeys.join(', ') || '—'}; ` +
168      `windows: ${a.windows.join(', ') || 'none'}; Fable matched: ${a.fableMatched.join(', ') || 'none'}`
169    : 'not attempted yet'
170  const lines = [
171    `Surfaces attached now: ${surfaces.length ? surfaces.join(', ') : 'none'}`,
172    `Clients that attached since load: ${attached.length ? attached.join(', ') : 'none seen'}`,
173    `Draw requests received: ${drawn}`,
174    `Panel hidden: ${hidden ? 'yes' : 'no'}; px per cell: ${pxPerCell} (/cache scale <px> changes it)`,
175    `Context: ${snap?.context ? `${snap.context.used} / ${snap.context.window}` : 'no reading'}`,
176    `Limits: ${snap?.limits.length ? snap.limits.map(l => `${l.kind} ${l.usage}%`).join(', ') : 'none'} (source: ${snap?.limitsSource ?? 'none'})`,
177    `Account usage request: ${account}`,
178    `Cache: last write ${snap?.cache.lastAt ? new Date(snap.cache.lastAt).toISOString() : 'none'}, TTL ${snap ? snap.cache.ttlMs / 60000 : '?'}m${snap?.cache.isTtlKnown ? '' : ' (default)'}`,
179    priceLine(snap?.model),
180    ...tallyLines(await readDays($)),
181    `Warming: ${warmUntil === null ? 'off' : `on until ${fmtClock(warmUntil)}; ${warming ? warmNotice(warming, snap!.context)[0] : 'no note'}`}`,
182    ...(warmUntil === null ? [] : warmRunLines((await $.store.get('warmRun')) as WarmRun | null | undefined, snap, warming, await $.clock.now())),
183    `Auto-warm: ${(await autoWarmAt($)) === 0 ? 'off (/cache-autowarm sets it)' : `when quiet with a context over ${fmtTokens(await autoWarmAt($))}${autoHeld ? '; held off until the next reply' : ''}`}`,
184    `Full report: ${cwd ? `${cwd}/` : ''}${DIAG_FILE}`,
185  ]
186  const text = lines.join('\n')
187  try {
188    await $.fs.write(
189      DIAG_FILE,
190      JSON.stringify({ at: await $.clock.now(), surfaces, attached, draws, hidden, pxPerCell, account: lastAccount, snap }, null, 2),
191    )
192  } catch {
193    // diagnostics only
194  }
195  return text
196}
197
198async function current($: EngineInterface): Promise<ContextCacheSnapshot> {
199  const snap = await read($, snapshotAtom)
200  if (snap) return snap
201  const stored = await $.store.get('ttlMs')
202  const ttl = stored === TTL_5M || stored === TTL_1H ? stored : TTL_1H
203  return {
204    context: null,
205    limits: [],
206    limitsSource: 'none',
207    cache: emptyCache(ttl, stored === TTL_5M || stored === TTL_1H),
208    updatedAt: await $.clock.now(),
209  }
210}
211
212async function patchCache($: EngineInterface, patch: Partial<ContextCacheCache>) {
213  const base = await current($)
214  await update($, snapshotAtom, prev => {
215    const s = prev ?? base
216    return { ...s, cache: { ...s.cache, ...patch } }
217  })
218}
219
220async function setTtl($: EngineInterface, ttlMs: number) {
221  await $.store.set('ttlMs', ttlMs)
222  await patchCache($, { ttlMs, isTtlKnown: true })
223}
224
225/** The last account reading any session saved, when it is newer than this session's own. */
226async function adoptShared($: EngineInterface) {
227  const saved = (await $.store.get('accountLimits')) as { at?: number; limits?: ContextCacheLimit[] } | undefined
228  if (saved?.limits?.length && typeof saved.at === 'number' && saved.at > accountAt) {
229    accountLimits = saved.limits
230    accountAt = saved.at
231  }
232}
233
234// Every open session shares one request: whoever asks first writes the time to
235// the store, and the others take the reading it saves instead of asking too.
236// ponytail: two sessions reading the claim in the same instant both ask; rare, and a 429 backs both off.
237async function fetchAccount($: EngineInterface, now: number, force: boolean) {
238  if (accountInFlight) return
239  if (!force) {
240    const asked = await $.store.get('accountAskedAt')
241    if (typeof asked === 'number' && now - asked < ACCOUNT_EVERY_MS) return adoptShared($)
242  }
243  await $.store.set('accountAskedAt', now)
244  accountInFlight = true
245  const diag: AccountDiag = { at: now, authKind: 'none', status: null, ok: null, topLevelKeys: [], windows: [], fableMatched: [], bodyPreview: '', error: null }
246  lastAccount = diag
247  try {
248    const auth = await $.session.authorize()
249    diag.authKind = auth ? auth.kind : 'none'
250    if (!auth || auth.kind !== 'bearer') return
251    const res = await $.http.fetch(USAGE_URL, {
252      auth: auth.handle,
253      headers: { 'anthropic-beta': 'oauth-2025-04-20', accept: 'application/json' },
254    })
255    diag.status = res.status
256    diag.ok = res.ok
257    diag.bodyPreview = res.text.slice(0, 2000)
258    if (res.status === 429) {
259      // Back off a whole interval (or what retry-after asks) before trying again.
260      // The claim moves on so that no session asks before then.
261      const retry = Number(res.headers['retry-after'])
262      await $.store.set('accountAskedAt', now + (Number.isFinite(retry) && retry > 0 ? Math.max(0, retry * 1000 - ACCOUNT_EVERY_MS) : 0))
263      return
264    }
265    if (!res.ok) return
266    const json: unknown = JSON.parse(res.text)
267    if (json && typeof json === 'object') diag.topLevelKeys = Object.keys(json as object)
268    const found = usageWindowsOf(json)
269    diag.windows = found.map(f => `${f.path}=${f.usage}%`)
270    diag.fableMatched = found.filter(f => f.isFable).map(f => f.path)
271    const limits = parseAccountUsage(json)
272    if (limits.length > 0) {
273      accountLimits = limits
274      accountAt = now
275      await $.store.set('accountLimits', { at: now, limits })
276    }
277  } catch (err) {
278    // keep the last good reading; the response headers cover the gap
279    diag.error = err instanceof Error ? err.message : String(err)
280  } finally {
281    accountInFlight = false
282  }
283}
284
285// The Files share of the conversation: reading the whole transcript is the
286// dear part of a refresh, so it is done once per turn and reused between.
287let fileShare = 0
288let fileShareTurn = -1
289let turnNo = 0
290
291async function doRefresh($: EngineInterface, forceAccount: boolean) {
292  const now = await $.clock.now()
293  const prev = await current($)
294
295  let context = prev.context
296  let responseLimits: ContextCacheLimit[] = []
297  try {
298    const usage = await $.session.usage({ breakdown: 'summary' })
299    responseLimits = limitsFromResponse(usage.rateLimits)
300    const b = usage.context.breakdown
301    if (fileShareTurn !== turnNo) {
302      try {
303        const msgs = await $.session.messages()
304        if (Array.isArray(msgs)) fileShare = fileShareOf(msgs)
305        fileShareTurn = turnNo
306      } catch {
307        // keep the last share
308      }
309    }
310    context = buildContext({
311      categories: b?.categories ?? [],
312      realTokens: usage.context.tokens ?? b?.totalTokens,
313      window: usage.context.window,
314      autoCompactAt: b?.autoCompactThreshold,
315      isAutoCompactEnabled: b?.isAutoCompactEnabled ?? false,
316      fileShare,
317    })
318  } catch {
319    // keep the last context reading
320  }
321
322  await fetchAccount($, now, forceAccount)
323  // A reload empties module memory but not the session's snapshot: a recent
324  // account reading there still stands, so Fable does not blink out meanwhile.
325  if (accountLimits === null && prev.limitsSource === 'account' && now - prev.updatedAt < 10 * ACCOUNT_EVERY_MS) {
326    accountLimits = prev.limits
327    accountAt = prev.updatedAt
328  }
329  const isAccountFresh = accountLimits !== null && now - accountAt < 10 * ACCOUNT_EVERY_MS
330  let limits: ContextCacheLimit[]
331  let limitsSource: ContextCacheSnapshot['limitsSource']
332  if (isAccountFresh && accountLimits) {
333    // The headers arrive with every reply and the account reading is up to 5
334    // minutes old, yet the headers can trail it (weekly 25% against the
335    // account's and /usage's 26%). Usage only climbs inside a window, so for
336    // the same window the higher reading is the newer one; across a reset the
337    // later window wins. The account adds what the headers lack (Fable).
338    limits = [
339      ...responseLimits.map(r => {
340        const a = accountLimits!.find(x => x.kind === r.kind)
341        if (!a) return r
342        const resetsAt = r.resetsAt ?? a.resetsAt
343        if (resetsAt !== null && a.resetsAt !== null && Math.abs(resetsAt - a.resetsAt) > SAME_WINDOW_MS) {
344          return a.resetsAt > resetsAt ? a : { ...r, resetsAt }
345        }
346        return { ...r, resetsAt, usage: Math.max(r.usage, a.usage) }
347      }),
348      ...accountLimits.filter(a => !responseLimits.some(r => r.kind === a.kind)),
349    ]
350    limitsSource = 'account'
351  } else if (responseLimits.length > 0) {
352    limits = responseLimits
353    limitsSource = 'response'
354  } else if (prev.limits.length > 0) {
355    limits = prev.limits
356    limitsSource = prev.limitsSource
357  } else {
358    // Nothing read in this session yet (a reopened old chat before its first
359    // reply): the last good account reading from any session, minus windows
360    // that have reset since. It is replaced by the next real reading.
361    const saved = (await $.store.get('accountLimits')) as { limits?: ContextCacheLimit[] } | undefined
362    limits = (saved?.limits ?? []).filter(l => l.resetsAt !== null && l.resetsAt > now)
363    limitsSource = limits.length > 0 ? 'account' : 'none'
364  }
365
366  let model = prev.model ?? null
367  try {
368    model = await $.session.model()
369  } catch {
370    // keep the last one read; without it the notice leaves out prices
371  }
372
373  // A bar that just turned amber or red pulses; one already so when the session opened does not.
374  const rank = { normal: 0, amber: 1, red: 2 } as const
375  const toneAt = (l: ContextCacheLimit) => rank[toneOf(l.usage, timePct(l, now))]
376  const pulse = { ...prev.pulse }
377  for (const l of limits) {
378    const was = prev.limits.find(p => p.kind === l.kind)
379    if (was && toneAt(l) > toneAt(was)) pulse[l.kind] = now
380  }
381  await warnLimits($, limits, now)
382
383  await update($, snapshotAtom, latest => {
384    const s = latest ?? prev
385    return { ...s, context, limits, limitsSource, model, pulse, updatedAt: now }
386  })
387  await update($, nowAtom, () => now)
388}
389
390/**
391 * One toast as a limit reaches 90%, once per window across every session: the
392 * windows already warned about are kept in the store until they reset.
393 */
394async function warnLimits($: EngineInterface, limits: ContextCacheLimit[], now: number) {
395  const due = limits.filter(l => l.usage >= 90 && l.resetsAt !== null && l.resetsAt > now)
396  if (due.length === 0) return
397  const warned = (((await $.store.get('limitWarned')) as string[] | undefined) ?? []).map(k => {
398    const [kind, at] = k.split('@')
399    return { kind, at: Number(at) }
400  })
401  // The sources round reset times differently: within SAME_WINDOW_MS is the same window.
402  const fresh = due.filter(l => !warned.some(w => w.kind === l.kind && Math.abs(w.at - l.resetsAt!) < SAME_WINDOW_MS))
403  if (fresh.length === 0) return
404  const keep = warned.filter(w => w.at > now).map(w => `${w.kind}@${w.at}`)
405  await $.store.set('limitWarned', [...keep, ...fresh.map(l => `${l.kind}@${l.resetsAt}`)])
406  for (const l of fresh) $.ui.toast(limitToast(l, now))
407}
408
409function refresh($: EngineInterface, forceAccount = false): Promise<void> {
410  if (refreshing) return refreshing
411  refreshing = doRefresh($, forceAccount)
412    .catch(() => undefined) // a refresh outliving its session, or a refused write: the next one retries
413    .finally(() => {
414    refreshing = null
415  })
416  return refreshing
417}
418
419/** After a Clear or Compact: re-read the context and keep what was taken out, for the notice. */
420async function noteSaved($: EngineInterface, kind: 'clear' | 'compact', before: number | null) {
421  // A refresh already in flight read the context from before; the second reads it after.
422  await refresh($)
423  await refresh($)
424  const after = (await current($)).context?.used ?? 0
425  if (before === null || before <= after) return
426  await update($, snapshotAtom, s => (s ? { ...s, saved: { kind, before, after } } : s))
427  const snap = await current($)
428  const price = priceOf(snap.model, snap.cache.ttlMs)
429  await addToTally($, { freed: before - after, freedUsd: price ? (before - after) * price.write : 0 })
430}
431
432// What Clear, Compact and Warm saved, per local day for the last 7, kept
433// across sessions for /cache-status. Money is the cache re-write each one
434// spared, at list price.
435type Totals = { freed: number; freedUsd: number; pings: number; pingUsd: number }
436type Days = Record<string, Totals>
437const NONE: Totals = { freed: 0, freedUsd: 0, pings: 0, pingUsd: 0 }
438const DAY_MS = 24 * 60 * 60_000
439
440/** "2026-10-13" in local time: keys that sort, unlike toDateString. */
441const dayKey = (at: number) => {
442  const d = new Date(at)
443  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
444}
445
446/** The last 7 days' totals, today among them; older days dropped. */
447async function readDays($: EngineInterface): Promise<{ today: string; days: Days }> {
448  const now = await $.clock.now()
449  const today = dayKey(now)
450  const oldest = dayKey(now - 6 * DAY_MS)
451  let days = ((await $.store.get('tallyDays')) as Days | undefined) ?? {}
452  // Before 0.1.10 only today was kept, under 'tally'.
453  const old = (await $.store.get('tally')) as (Totals & { day: string }) | undefined
454  if (old && old.day === new Date(now).toDateString() && !days[today]) {
455    const { day: _, ...t } = old
456    days = { ...days, [today]: t }
457  }
458  return { today, days: Object.fromEntries(Object.entries(days).filter(([k]) => k >= oldest && k <= today)) }
459}
460
461async function addToTally($: EngineInterface, add: Partial<Totals>) {
462  const { today, days } = await readDays($)
463  const t = days[today] ?? NONE
464  const sum = (k: keyof Totals) => t[k] + (add[k] ?? 0)
465  await $.store.set('tallyDays', { ...days, [today]: { freed: sum('freed'), freedUsd: sum('freedUsd'), pings: sum('pings'), pingUsd: sum('pingUsd') } })
466}
467
468function tallyLines({ today, days }: { today: string; days: Days }): string[] {
469  const t = days[today] ?? NONE
470  const w = Object.values(days).reduce<Totals>(
471    (a, d) => ({ freed: a.freed + d.freed, freedUsd: a.freedUsd + d.freedUsd, pings: a.pings + d.pings, pingUsd: a.pingUsd + d.pingUsd }),
472    NONE,
473  )
474  const money = (usd: number) => (usd > 0 ? ` (up to ${fmtUsd(usd)} of cache re-writes)` : '')
475  const pings = (n: number) => `${n} Warm ping${n === 1 ? '' : 's'}`
476  const week =
477    w.freed === 0 && w.pings === 0
478      ? 'nothing yet'
479      : [
480          w.freed > 0 ? `${fmtTokens(w.freed)} taken out by Clear and Compact${w.freedUsd > 0 ? ` (up to ${fmtUsd(w.freedUsd)})` : ''}` : 'nothing taken out by Clear or Compact',
481          w.pings > 0 ? `${pings(w.pings)}${w.pingUsd > 0 ? ` (${fmtUsd(w.pingUsd)} of re-writes avoided)` : ''}` : 'no Warm pings',
482        ].join(', ')
483  return [
484    `Saved today by Clear and Compact: ${t.freed > 0 ? `${fmtTokens(t.freed)} taken out of the context${money(t.freedUsd)}` : 'nothing yet'}`,
485    `Saved today by Warm: ${t.pings > 0 ? `${t.pings} ping${t.pings === 1 ? '' : 's'} kept the cache${t.pingUsd > 0 ? `, ${fmtUsd(t.pingUsd)} of re-writes avoided after paying for the pings` : ''}` : 'no pings yet'}`,
486    `Saved in the last 7 days: ${week}`,
487  ]
488}
489
490/** The current Warm run: when it started and ends, each ping, and what the pings spared (as addToTally counts it). */
491function warmRunLines(run: WarmRun | null | undefined, snap: ContextCacheSnapshot | null, warming: ContextCacheWarming | null, now: number): string[] {
492  if (!run) return []
493  const last = run.pings.at(-1)
494  const price = snap ? priceOf(snap.model, snap.cache.ttlMs) : null
495  const lines = [
496    `Warm run: on since ${fmtClock(run.startedAt)} (${fmtSpan(now - run.startedAt)}), ends ${fmtClock(run.until)} (${fmtSpan(run.until - now)} left)`,
497    `Pings: ${run.pings.length ? run.pings.map(p => fmtClock(p.at).replace(/ [ap]m$/, '')).join(', ') : 'none yet'}` +
498      `${warming ? ` · next ${fmtClock(warming.nextAt).replace(/ [ap]m$/, '')}` : ''}${last ? ` · ${fmtTokens(last.read)} kept cached each` : ''}`,
499  ]
500  // A ping is a fork: nothing enters the chat.
501  if (price && last)
502    lines.push(`Each ping: 0 tokens added to the chat · reads ${fmtTokens(last.read)} from cache · costs ${fmtUsd(last.read * price.read)} · saves ${fmtUsd(last.read * price.write)} (net ${fmtUsd(last.read * (price.write - price.read))})`)
503  if (price && run.pings.length) {
504    const read = run.pings.reduce((n, p) => n + p.read, 0)
505    lines.push(`This run: ${fmtUsd(read * (price.write - price.read))} of re-writes avoided (pings ${fmtUsd((read * price.read) / run.pings.length)} each)`)
506  }
507  return lines
508}
509
510/** Which list prices the money comes from, or that the model has none. */
511function priceLine(model: string | null | undefined): string {
512  if (!model) return 'Prices: the model is not known yet, so the panel shows tokens without money'
513  const p = listPrice(model)
514  return p
515    ? `Prices: ${model} at $${p.input} input, $${p.read} cache read per million tokens`
516    : `Prices: ${model} is not in the price list in hooks/model.ts, so the panel shows tokens without money`
517}
518
519async function learnTtl($: EngineInterface, transcriptPath: string) {
520  if (!transcriptPath) return
521  try {
522    const stat = await $.fs.stat(transcriptPath)
523    if (stat.size > MAX_TRANSCRIPT_BYTES) return
524    const text = await $.fs.read(transcriptPath)
525    const ttl = ttlFromTranscript(typeof text === 'string' ? text : '')
526    if (ttl !== null) await setTtl($, ttl)
527  } catch {
528    // unreadable: the stored TTL stands
529  }
530}
531
532const PANE = 'context-cache'
533
534const COMMANDS = [
535  { name: 'cache', description: 'Context & cache panel: show or hide it' },
536  { name: 'cache-status', description: 'Context & cache panel: where each figure comes from (surfaces, draws, the account usage request, Fable) and what was saved today' },
537  { name: 'cache-mini', description: 'Context & cache panel: one line (context %, cache, the next message\'s price) or the whole card' },
538  { name: 'cache-pane', description: 'Context & cache panel: open it as a pane (the way it shows on mobile)' },
539  { name: 'cache-refresh', description: 'Context & cache panel: re-read usage now' },
540  { name: 'cache-scale', description: 'Context & cache panel: px per cell the desktop draws at (default 8); a number sets it, none steps it', argumentHint: '[px]' },
541  {
542    name: 'cache-autowarm',
543    description: 'Context & cache panel: switch Warm on by itself when you go quiet with a context over this many thousand tokens; 0 is off, none steps off/200/300/500',
544    argumentHint: '[k tokens]',
545  },
546] as const
547
548async function hasMobile($: EngineInterface): Promise<boolean> {
549  try {
550    return (await $.session.surfaces()).includes('mobile')
551  } catch {
552    return false
553  }
554}
555
556/** The card's inner width in CSS px on a remote surface: the band's cells × px per cell, less the border. */
557async function widthPx($: EngineInterface, columns: number): Promise<number> {
558  return columns * (await read($, pxPerCellAtom)) - 2
559}
560
561/** The terminal notice's room: the card's border and padding, "● ", and beside the buttons ([Clear] [Compact] [Warm]) when wide. */
562function terminalNoticeChars(columns: number): number {
563  const wide = sizeClassOf(columns) === 'a' || sizeClassOf(columns) === 'b'
564  return columns - 6 - (wide ? 25 : 0)
565}
566
567/** The size classes are set in the design's cells (8px each): a px width as that many. */
568function designCells(px: number): number {
569  return px / DEFAULT_PX_PER_CELL
570}
571
572/** The view model for a drawing, or null while hidden or before any reading. */
573async function panelModel($: EngineInterface, columns: number, maxRows: number, fitChars?: number): Promise<ViewModel | null> {
574  const [snap, hidden, tick] = await Promise.all([read($, snapshotAtom), read($, hiddenAtom), read($, nowAtom)])
575  if (hidden || !snap) return null
576  return buildView({ ...snap, warming: await warmingOf($, snap) }, Math.max(tick, snap.updatedAt), columns, maxRows, fitChars)
577}
578
579/** While warming: the last ping and when the next is due, for the notice line. */
580async function warmingOf($: EngineInterface, { cache }: ContextCacheSnapshot): Promise<ContextCacheWarming | null> {
581  if ((await read($, warmUntilAtom)) === null || cache.lastAt === null) return null
582  return { lastPing, nextAt: cache.lastAt + WARM_AFTER_MS }
583}
584
585/** Why the cache can't be kept warm now, or null when it can. */
586function whyNoWarm(cache: ContextCacheCache, now: number): string | null {
587  if (cache.ttlMs !== TTL_1H) return '5-minute cache'
588  if (cache.lastAt === null) return 'nothing cached'
589  if (now - cache.lastAt >= cache.ttlMs) return 'cache already cold'
590  return null
591}
592
593async function stopWarm($: EngineInterface, why: string) {
594  autoHeld = true
595  await update($, warmUntilAtom, () => null)
596  await $.store.set('warmRun', null)
597  $.ui.toast(`Warm off, ${why}.`)
598}
599
600// Auto-warm: Warm switches itself on once you have been quiet 55 minutes with
601// a context over the size /cache-autowarm set (off until set). Stop, or warming
602// stopping by itself, holds it off until the next reply.
603const AUTO_STEPS = [0, 200_000, 300_000, 500_000]
604let autoHeld = false
605/** The reply (cache.lastAt) the 5-minutes-left notice was raised for. */
606let coldSoonFor: number | null = null
607
608async function autoWarmAt($: EngineInterface): Promise<number> {
609  const v = await $.store.get('autoWarmAt')
610  return typeof v === 'number' && v > 0 ? v : 0
611}
612
613/** 5 minutes left and nothing will keep the cache: a notification, or a toast where nothing can notify (the desktop). */
614async function coldSoon($: EngineInterface, snap: ContextCacheSnapshot, now: number) {
615  const { cache, context } = snap
616  if (cache.lastAt === null || coldSoonFor === cache.lastAt) return
617  coldSoonFor = cache.lastAt
618  const price = priceOf(snap.model, cache.ttlMs)
619  const text =
620    `Cache cold in ${fmtSpan(cache.lastAt + cache.ttlMs - now)}` +
621    (price && context ? `, ${fmtUsd(context.used * price.write)} to rebuild.` : '.')
622  const sent = await $.ui.notify(text, { title: 'Context & cache' }).catch(() => ({ isSent: false as const }))
623  if (!sent.isSent) $.ui.toast(text)
624}
625
626/** Checked every 15s: pings once the cache is 55 min old while warming; otherwise auto-warm or the 5-minutes-left notice. */
627async function warmTick($: EngineInterface) {
628  if (warmInFlight) return
629  let until = await read($, warmUntilAtom)
630  const now = await $.clock.now()
631  const snap = await current($)
632  const { cache } = snap
633  if (until === null) {
634    if (cache.lastAt === null || whyNoWarm(cache, now) || now - cache.lastAt < WARM_AFTER_MS) return
635    const at = await autoWarmAt($)
636    if (autoHeld || at === 0 || (snap.context?.used ?? 0) < at) return coldSoon($, snap, now)
637    until = now + WARM_FOR_MS
638    await startWarmRun($, now, until)
639    await update($, warmUntilAtom, () => until)
640    $.ui.toast(`Auto-warm on, context ${fmtTokens(snap.context!.used)}.`)
641  }
642  if (now >= until) return stopWarm($, 'ran 8h')
643  const why = whyNoWarm(cache, now)
644  if (why) return stopWarm($, why)
645  if (now - cache.lastAt! < WARM_AFTER_MS) return
646  warmInFlight = true
647  try {
648    const r = await $.model.fork({ prompt: WARM_PROMPT })
649    if (!r.isAnswered && r.reason === 'nothing-to-fork') return stopWarm($, 'nothing cached')
650    const u = 'usage' in r ? r.usage : undefined
651    if (u && u.cache_read_input_tokens > 0) {
652      const at = await $.clock.now()
653      lastPing = { at, read: u.cache_read_input_tokens }
654      const run = (await $.store.get('warmRun')) as WarmRun | null | undefined
655      if (run) await $.store.set('warmRun', { ...run, pings: [...run.pings, lastPing] })
656      await patchCache($, { lastAt: at })
657      // A ping pays a cache read and spares the re-write going cold would cost.
658      const price = priceOf((await current($)).model, cache.ttlMs)
659      await addToTally($, { pings: 1, pingUsd: price ? u.cache_read_input_tokens * (price.write - price.read) : 0 })
660    }
661    else if (u && u.cache_creation_input_tokens > 0) await stopWarm($, 'ping missed the cache')
662    // else an API error: the next tick retries while the cache is still warm
663  } finally {
664    warmInFlight = false
665  }
666}
667
668/** Clear, Compact and Warm/Stop. None hides the notice row: it stays on whatever the cache holds. */
669async function actionsFor($: EngineInterface, isWorking: boolean): Promise<Actions> {
670  const isWarming = (await read($, warmUntilAtom)) !== null
671  return {
672    isWarming,
673    warm: async () => {
674      if ((await read($, warmUntilAtom)) !== null) {
675        autoHeld = true
676        await update($, warmUntilAtom, () => null)
677        $.ui.toast('Warm off.')
678        return
679      }
680      const now = await $.clock.now()
681      const why = whyNoWarm((await current($)).cache, now)
682      if (why) {
683        $.ui.toast(`Can't warm, ${why}.`)
684        return
685      }
686      await startWarmRun($, now, now + WARM_FOR_MS)
687      await update($, warmUntilAtom, () => now + WARM_FOR_MS)
688      const snap = await current($)
689      const price = priceOf(snap.model, snap.cache.ttlMs)
690      const cost =
691        price && snap.context
692          ? ` ${fmtUsd(snap.context.used * price.read)} a ping, saves ${fmtUsd(snap.context.used * price.write)}.`
693          : ''
694      $.ui.toast(`Warm on for 8h.${cost}`)
695    },
696    clear: async () => {
697      if (isWorking) $.ui.toast('Clear after this turn.')
698      try {
699        await $.command.run({ command: 'clear' })
700      } catch {
701        $.ui.toast('/clear failed.')
702      }
703    },
704    // Queued like Clear: $.session.compact() rejects whenever the engine is not idle.
705    // Our session.compact hook resets the cache once it runs.
706    compact: async () => {
707      if (isWorking) $.ui.toast('Compact after this turn.')
708      try {
709        await $.command.run({ command: 'compact' })
710      } catch (err) {
711        $.ui.toast(`/compact failed: ${err instanceof Error ? err.message : String(err)}`)
712      }
713    },
714  }
715}
716
717export const register: Register = on => {
718  // ── Session lifecycle ──────────────────────────────────────────────────
719
720  on('session.start', async ($, e, next) => {
721    cwd = e.cwd
722    // One command each: the desktop composer drops anything typed after a slash command's name.
723    for (const c of COMMANDS) await $.command.register(c)
724    const storedPx = await $.store.get('pxPerCell')
725    if (typeof storedPx === 'number' && storedPx > 0) await update($, pxPerCellAtom, () => storedPx)
726    if ((await $.store.get('isMini')) === true) await update($, miniAtom, () => true)
727    const initial = await current($)
728    await update($, snapshotAtom, prev => prev ?? initial)
729    void refresh($)
730    // Started from the phone: the pane is how the panel shows there.
731    if (await hasMobile($)) void $.ui.open({ id: PANE, title: 'Context & cache' }).catch(() => undefined)
732    // The countdown: checked once a second, redrawn only when a figure the
733    // panel shows would change (a 60m TTL moves a whole percent every 36s; a
734    // 5m one shows seconds, so it redraws every second).
735    let lastShown = ''
736    $.clock.every(1000, () => {
737      void (async () => {
738        const [snap, hidden] = await Promise.all([read($, snapshotAtom), read($, hiddenAtom)])
739        if (hidden || !snap) return
740        const now = await $.clock.now()
741        const c = cacheView(snap.cache, now)
742        const lit = Object.values(snap.pulse ?? {}).map(at => (isPulseLit(at, now) ? 1 : 0)).join('')
743        const shown = `${c.state}|${pct(c.warmth * 100)}|${c.detail}|${c.state === 'cooling' ? noticeText(c, snap.context, snap.cache.ttlMs) : ''}|${lit}`
744        if (shown === lastShown) return
745        lastShown = shown
746        await update($, nowAtom, () => now)
747      })().catch(() => undefined)
748    })
749    $.clock.every(ACCOUNT_EVERY_MS, () => void refresh($, false))
750    $.clock.every(15_000, () => void warmTick($).catch(() => undefined))
751    return next(e)
752  })
753
754  // Resumed: the transcript says how long ago the last response was.
755  on('classic.SessionStart', async ($, e, next) => {
756    const now = await $.clock.now()
757    if ((e.source === 'resume' || e.source === 'fork') && typeof e.seconds_since_last_response === 'number') {
758      await patchCache($, { lastAt: now - e.seconds_since_last_response * 1000 })
759    } else if (e.source === 'clear' || e.source === 'compact') {
760      await patchCache($, { lastAt: null, hitRate: null })
761    }
762    void learnTtl($, e.transcript_path)
763    return next(e)
764  }).catch((_$, e, next) => next(e))
765
766  // Each main-thread response writes/reads the cache as it lands, so a long
767  // turn (or the first one after /clear) does not sit at "Empty" until it ends.
768  on('turn.step', async function* ($, e, next) {
769    const r = yield* next(e)
770    const u = r.usage
771    if (e.agentId === undefined && u) {
772      autoHeld = false // a reply: auto-warm may act again on the next quiet spell
773      const total = u.cache_read_input_tokens + u.cache_creation_input_tokens + u.input_tokens
774      void $.clock
775        .now()
776        .then(now => patchCache($, { lastAt: now, hitRate: total > 0 ? u.cache_read_input_tokens / total : null }))
777        .then(() => update($, snapshotAtom, s => (s?.saved ? { ...s, saved: null } : s)))
778        .catch(() => undefined)
779    }
780    return r
781  })
782
783  // A turn of the main conversation ended: its requests just wrote/read the cache.
784  on('turn.complete', async ($, e, next) => {
785    const result = await next(e)
786    if (e.agentId === undefined) {
787      turnNo += 1
788      const now = await $.clock.now()
789      const u = e.usage
790      const total = u ? u.cache_read_input_tokens + u.cache_creation_input_tokens + u.input_tokens : 0
791      await patchCache($, {
792        lastAt: u ? now : (await current($)).cache.lastAt,
793        hitRate: u && total > 0 ? u.cache_read_input_tokens / total : (await current($)).cache.hitRate,
794      })
795      void refresh($)
796    }
797    return result
798  })
799
800  // You're back: your own message keeps the cache warm from here, so warming stops.
801  // turn.start, not prompt.submit: the desktop app's messages skip prompt.submit.
802  on('turn.start', async ($, e, next) => {
803    if (!warmInFlight && (await read($, warmUntilAtom)) !== null) {
804      await update($, warmUntilAtom, () => null)
805      $.ui.toast('Welcome back. Warm off.')
806    }
807    return next(e)
808  }).catch((_$, e, next) => next(e))
809
810  // After each turn, read which TTL the responses were cached with.
811  on('classic.Stop', ($, e, next) => {
812    void learnTtl($, e.transcript_path)
813    return next(e)
814  }).catch((_$, e, next) => next(e))
815
816  // The engine reports the TTL itself on a model switch; a switch also forfeits the cache.
817  // Before a switch you asked for: a warm cache would be thrown away, so ask
818  // first, with what the next message pays to write it again.
819  on('classic.PreModelSwitch', async ($, e, next) => {
820    const result = await next(e)
821    if (!e.prompt_cache_warm || e.context_tokens <= 0 || result.permissionDecision) return result
822    const usd = e.pricing === 'default' ? '' : ` for ${fmtUsd(e.estimated_cache_write_usd)}`
823    return {
824      ...result,
825      permissionDecision: 'ask' as const,
826      permissionDecisionReason: `Switching model throws away the warm cache: the next message re-writes ${fmtTokens(e.context_tokens)}${usd}. Switch anyway?`,
827    }
828  }).catch((_$, e, next) => next(e))
829
830  on('classic.PostModelSwitch', async ($, e, next) => {
831    // A switch nobody was asked about (an automatic fallback) still throws a
832    // warm cache away: say what the next message pays to write it again.
833    if (e.prompt_cache_warm && e.context_tokens > 0 && e.source === 'auto') {
834      const usd = e.pricing === 'default' ? '' : ` Next message ${fmtUsd(e.estimated_cache_write_usd)}.`
835      $.ui.toast(`Model switched, cache lost.${usd}`)
836    }
837    await setTtl($, e.cache_ttl === '5m' ? TTL_5M : TTL_1H)
838    await patchCache($, { lastAt: null, hitRate: null })
839    void refresh($)
840    return next(e)
841  }).catch((_$, e, next) => next(e))
842
843  // Usage figures moved (context fill, a limit window).
844  on('session.measure', ($, e, next) => {
845    void refresh($)
846    return next(e)
847  })
848
849  // A compaction replaces the conversation: nothing of the new one is cached yet.
850  on('session.compact', async ($, e, next) => {
851    const before = (await current($)).context?.used ?? null
852    const result = await next(e)
853    if (e.trigger !== 'precompute' && !('skip' in result)) {
854      await patchCache($, { lastAt: null, hitRate: null })
855      await noteSaved($, 'compact', before)
856    }
857    return result
858  }).catch((_$, e, next) => next(e))
859
860  // /clear starts a fresh conversation in the same process.
861  on('session.end', async ($, e, next) => {
862    const before = (await current($)).context?.used ?? null
863    const result = await next(e)
864    if (e.reason === 'clear') {
865      await patchCache($, { lastAt: null, hitRate: null })
866      await noteSaved($, 'clear', before)
867    }
868    return result
869  })
870
871  // ── /cache, /cache-status, /cache-pane, /cache-refresh, /cache-scale ────
872
873  on('command.run', { command: 'cache-status' }, async $ => ({ text: await statusReport($) }))
874
875  on('command.run', { command: 'cache-refresh' }, async $ => {
876    await refresh($, true)
877    return { text: 'Context & cache panel refreshed.' }
878  })
879
880  on('command.run', { command: 'cache-scale' }, async ($, e) => {
881    const was = await read($, pxPerCellAtom)
882    const typed = Number(e.args.trim())
883    // No number typed (or none delivered): step through 7 … 9.5 and round.
884    const n = Number.isFinite(typed) && typed > 0 ? typed : was >= 9.5 ? 7 : Math.round((was + 0.5) * 2) / 2
885    await $.store.set('pxPerCell', n)
886    await update($, pxPerCellAtom, () => n)
887    return { text: `Desktop now draws at ${n} px per cell (was ${was}). Run it again to step up; /cache-scale <px> sets it outright.` }
888  })
889
890  on('command.run', { command: 'cache-mini' }, async $ => {
891    const isMini = !(await read($, miniAtom))
892    await $.store.set('isMini', isMini)
893    await update($, miniAtom, () => isMini)
894    return {
895      text: isMini
896        ? 'Context & cache panel: one line (context, cache, next message). /cache-mini again for the whole card.'
897        : 'Context & cache panel: the whole card again.',
898    }
899  })
900
901  on('command.run', { command: 'cache-autowarm' }, async ($, e) => {
902    const was = await autoWarmAt($)
903    const typed = e.args.trim() === '' ? NaN : Number(e.args.trim())
904    // No number typed (or none delivered): the next step after the current one.
905    const n = Number.isFinite(typed) && typed >= 0 ? Math.round(typed * 1000) : AUTO_STEPS[(AUTO_STEPS.indexOf(was) + 1) % AUTO_STEPS.length]!
906    await $.store.set('autoWarmAt', n)
907    const before = was === 0 ? 'off' : fmtTokens(was)
908    if (n === 0) return { text: `Auto-warm is off (was ${before}).` }
909    return {
910      text: `Auto-warm: Warm switches itself on when the context is over ${fmtTokens(n)} and you have been quiet ${WARM_AFTER_MS / 60_000} minutes (was ${before}). Each ping reads the cache; /cache-autowarm 0 turns it off.`,
911    }
912  })
913
914  on('command.run', { command: 'cache-pane' }, async $ => {
915    await update($, hiddenAtom, () => false)
916    void refresh($)
917    await $.ui.open({ id: PANE, title: 'Context & cache' })
918    return { text: 'Context & cache panel opened.' }
919  })
920
921  on('command.run', { command: 'cache' }, async $ => {
922    const isHidden = await read($, hiddenAtom)
923    await update($, hiddenAtom, () => !isHidden)
924    if (isHidden) {
925      void refresh($)
926      // Phones have no band above the prompt: show it there as a pane.
927      if (await hasMobile($)) await $.ui.open({ id: PANE, title: 'Context & cache' })
928      return { text: 'Context & cache panel shown.' }
929    }
930    await $.ui.close({ id: PANE }).catch(() => undefined)
931    return { text: 'Context & cache panel hidden. /cache shows it again.' }
932  })
933
934  // A phone joined the session: open the panel as a pane there.
935  on('session.attach', async ($, e, next) => {
936    const result = await next(e)
937    attached.push(e.surface)
938    if (e.surface === 'mobile' && !(await read($, hiddenAtom))) {
939      void $.ui.open({ id: PANE, title: 'Context & cache' }).catch(() => undefined)
940    }
941    return result
942  })
943
944  // ── The band above the prompt (terminal, desktop) ──────────────────────
945
946  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
947    noteDraw('AbovePrompt', e.surface)
948    if (e.props.hasSurvey) return next(e)
949    if (e.props.view.agentId !== undefined) return next(e)
950    const E = $.ui.resolve(e)
951    if (await read($, miniAtom)) {
952      const [snap, hidden, tick] = await Promise.all([read($, snapshotAtom), read($, hiddenAtom), read($, nowAtom)])
953      if (hidden || !snap) return next(e)
954      const now = Math.max(tick, snap.updatedAt)
955      // paddingX 1 each side
956      return renderMini(E, miniLine(snap, now, e.props.bodyColumns - 2), cacheView(snap.cache, now).color)
957    }
958    if (e.surface === 'terminal') {
959      const vm = await panelModel($, e.props.bodyColumns, e.props.maxRows, terminalNoticeChars(e.props.bodyColumns))
960      if (!vm) return next(e)
961      return renderTerminal(E as Parameters<typeof renderTerminal>[0], vm, e.props.bodyColumns, (await actionsFor($, e.props.isWorking)))
962    }
963    if (e.surface === 'desktop' || e.surface === 'vscode') {
964      const px = await widthPx($, e.props.bodyColumns)
965      const vm = await panelModel($, designCells(px), e.props.maxRows)
966      if (!vm) return next(e)
967      return renderDesktop(E as Parameters<typeof renderDesktop>[0], vm, px, (await actionsFor($, e.props.isWorking)))
968    }
969    return next(e)
970  })
971
972  // ── The same panel as a pane (every surface; the phone's way to see it) ─
973
974  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
975    noteDraw('Pane', e.surface)
976    const E = $.ui.resolve(e)
977    const { Text } = E
978    const rows = Math.max(e.props.scroll.bodyRows, 12)
979    if (e.surface === 'terminal') {
980      const vm = await panelModel($, e.props.bodyColumns, rows, terminalNoticeChars(e.props.bodyColumns))
981      if (!vm) return <Text dimColor>Reading usage…</Text>
982      return renderTerminal(E as Parameters<typeof renderTerminal>[0], vm, e.props.bodyColumns, (await actionsFor($, false)))
983    }
984    const px = await widthPx($, e.props.bodyColumns)
985    const vm = await panelModel($, designCells(px), rows)
986    if (!vm) return <Text dimColor>Reading usage…</Text>
987    return renderDesktop(E as Parameters<typeof renderDesktop>[0], vm, px, (await actionsFor($, false)))
988  })
989}
990
hooks/model.ts 708 lines
1// Pure maths and copy for the context-cache panel: no `$`, no drawing.
2// Everything here takes real figures in and returns what the panel shows.
3
4import type { ContextCategory, SessionMessage, SessionRateLimit } from 'claude-code'
5
6import type {
7  ContextCacheCache,
8  ContextCacheContext,
9  ContextCacheGroup,
10  ContextCacheLimit,
11  ContextCacheLimitKind,
12  ContextCacheSaved,
13  ContextCacheSnapshot,
14  ContextCacheWarming,
15} from '../types'
16
17// ── Design tokens ──────────────────────────────────────────────────────────
18
19export const TOKENS = {
20  card: '#222120',
21  border: '#34322e',
22  borderStrong: '#4a4741',
23  track: '#2f2d2a',
24  ringTrack: '#3a3835',
25  text: '#ece9e2',
26  text2: '#b9b5ab',
27  /** The notice line: text2 lifted 20%. */
28  notice: '#ded9cd',
29  /** The dot beside a notice that reports what Clear or Compact saved. */
30  saved: '#4fae6a',
31  text3: '#8a867d',
32  text4: '#7d7970',
33  tick: '#ece9e2',
34  buttonText: '#1b1a18',
35  /** The context percentage in "112k / 1M (11%)", bold. */
36  strong: '#ffffff',
37  /** The free-token count in the legend, a step lighter than its "Free" label. */
38  freeTokens: '#c7c1b3',
39} as const
40
41export const GROUP_COLORS: Record<ContextCacheGroup, string> = {
42  system: '#6f6b64',
43  tools: '#7050b8',
44  files: '#2f6bd6',
45  messages: '#c2562f',
46}
47
48export const GROUP_LABELS: Record<ContextCacheGroup, string> = {
49  system: 'System',
50  tools: 'Tools',
51  files: 'Files',
52  messages: 'Messages',
53}
54
55export const GROUPS: readonly ContextCacheGroup[] = ['system', 'tools', 'files', 'messages']
56
57export const LIMIT_COLORS: Record<ContextCacheLimitKind, { bright: string; dark: string }> = {
58  session: { bright: '#4fae6a', dark: '#2c5a3a' },
59  weekly: { bright: '#3b7be0', dark: '#2b4a80' },
60  fable: { bright: '#8a6fc0', dark: '#4a4160' },
61}
62export const AMBER = { bright: '#e0a84f', dark: '#6b5428' }
63export const RED = { bright: '#e5604f', dark: '#6b2f2a' }
64
65export const LIMIT_TITLES: Record<ContextCacheLimitKind, string> = {
66  session: 'Current session',
67  weekly: 'Weekly limits',
68  fable: 'Fable',
69}
70
71export const CACHE_COLORS = {
72  warm: '#e8833a',
73  cooling: '#e0a84f',
74  cold: '#4f9be8',
75  empty: '#7d7970',
76} as const
77
78export const HOUR = 3_600_000
79export const FIVE_HOURS = 5 * HOUR
80export const SEVEN_DAYS = 7 * 24 * HOUR
81export const TTL_5M = 5 * 60_000
82export const TTL_1H = HOUR
83
84// ── Formatting ─────────────────────────────────────────────────────────────
85
86/** 452000 → "452k", 1000000 → "1M", 1500000 → "1.5M", 640 → "640". */
87// ── Prices ─────────────────────────────────────────────────────────────────
88
89// ponytail: list prices copied by hand ($ per million tokens: input, cache
90// read), as of 2026-10-13; update when Anthropic changes them. Matched by
91// prefix, most specific first, so `claude-opus-5-5[1m]` finds Opus 5.5.
92const PRICES: [string, number, number][] = [
93  ['claude-fable-5-1', 10, 0.25],
94  ['claude-mythos-5-1', 10, 0.25],
95  ['claude-fable-5', 10, 1],
96  ['claude-mythos-5', 10, 1],
97  ['claude-opus-5-5', 4, 0.2],
98  ['claude-opus-5', 5, 0.5],
99  ['claude-opus-4', 5, 0.5],
100  ['claude-sonnet-5', 2, 0.2],
101  ['claude-sonnet-4', 3, 0.3],
102  ['claude-haiku-5-5', 0.1, 0.01],
103  ['claude-haiku-4', 1, 0.1],
104]
105
106/** $ per token to read the cache, and to write it (2× input for the 1-hour cache, 1.25× for 5 minutes); null for an unknown model. */
107export type Price = { read: number; write: number }
108
109/** The list prices in $ per million tokens, or null for a model missing from the list. */
110export function listPrice(model: string | null | undefined): { input: number; read: number } | null {
111  const row = model ? PRICES.find(([p]) => model.startsWith(p)) : undefined
112  return row ? { input: row[1], read: row[2] } : null
113}
114
115export function priceOf(model: string | null | undefined, ttlMs: number): Price | null {
116  const list = listPrice(model)
117  if (!list) return null
118  return { read: list.read / 1e6, write: (list.input * (ttlMs === TTL_5M ? 1.25 : 2)) / 1e6 }
119}
120
121/** "≈$3.61", "≈$0.09", "<$0.01". */
122export function fmtUsd(n: number): string {
123  if (n < 0.005) return '<$0.01'
124  return `≈$${n < 100 ? n.toFixed(2) : Math.round(n)}`
125}
126
127export function fmtTokens(n: number): string {
128  if (n >= 1_000_000) {
129    const m = n / 1_000_000
130    return `${Number.isInteger(m) ? m : m.toFixed(1).replace(/\.0$/, '')}M`
131  }
132  if (n >= 1000) return `${Math.round(n / 1000)}k`
133  return String(Math.max(0, Math.round(n)))
134}
135
136/** Whole percent, never NaN. */
137export function pct(n: number): number {
138  return Number.isFinite(n) ? Math.round(n) : 0
139}
140
141/** 7_920_000 → "2h 12m"; 200_000 → "3m 20s"; 45_000 → "45s"; days when ≥ 24h. */
142export function fmtSpan(ms: number, withSeconds = false): string {
143  const s = Math.max(0, Math.round(ms / 1000))
144  const d = Math.floor(s / 86400)
145  const h = Math.floor((s % 86400) / 3600)
146  const m = Math.floor((s % 3600) / 60)
147  const sec = s % 60
148  if (d > 0) return `${d}d ${h}h`
149  if (h > 0) return `${h}h ${m}m`
150  if (withSeconds) return m > 0 ? `${m}m ${sec}s` : `${sec}s`
151  return `${m}m`
152}
153
154const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
155
156/** "Resets in 2h 12m" inside a day, else "Resets Sun 11:00 pm" (local time). */
157export function fmtReset(resetsAt: number | null, now: number): string {
158  if (resetsAt === null) return 'Reset time not reported'
159  const left = resetsAt - now
160  if (left <= 0) return 'Resetting now'
161  if (left < 24 * HOUR) return `Resets in ${fmtSpan(left)}`
162  return `Resets ${DAYS[new Date(resetsAt).getDay()]} ${fmtClock(resetsAt)}`
163}
164
165/** "11:05 pm" (local time). */
166export function fmtClock(at: number): string {
167  const d = new Date(at)
168  const h24 = d.getHours()
169  const h12 = h24 % 12 === 0 ? 12 : h24 % 12
170  return `${h12}:${String(d.getMinutes()).padStart(2, '0')} ${h24 < 12 ? 'am' : 'pm'}`
171}
172
173// ── Context ────────────────────────────────────────────────────────────────
174
175/** Tools whose results are file contents, for the Files share of Messages. */
176const FILE_TOOLS = new Set(['Read', 'NotebookRead'])
177
178/**
179 * The share of the conversation's text that is file contents the model read,
180 * 0 to 1: the Files segment is that share of the Messages row's real tokens.
181 */
182export function fileShareOf(messages: readonly SessionMessage[]): number {
183  let total = 0
184  let files = 0
185  for (const m of messages) {
186    total += m.text.length
187    for (const use of m.toolUses) {
188      const len = (use.text ?? '').length + JSON.stringify(use.input ?? {}).length
189      total += len
190      if (FILE_TOOLS.has(use.tool)) files += (use.text ?? '').length
191    }
192  }
193  return total > 0 ? Math.min(1, files / total) : 0
194}
195
196/** Which of the four groups a /context row belongs to. */
197export function groupOf(name: string): ContextCacheGroup {
198  if (/message/i.test(name)) return 'messages'
199  if (/tool|mcp|agent|skill|command/i.test(name)) return 'tools'
200  return 'system'
201}
202
203/**
204 * The context row's figures: /context's categories grouped into four and
205 * scaled so they sum to the real token count the last response reported.
206 */
207export function buildContext(args: {
208  categories: readonly ContextCategory[]
209  realTokens: number | undefined
210  window: number
211  autoCompactAt: number | undefined
212  isAutoCompactEnabled: boolean
213  fileShare: number
214}): ContextCacheContext {
215  const raw: Record<ContextCacheGroup, number> = { system: 0, tools: 0, files: 0, messages: 0 }
216  for (const c of args.categories) {
217    if (c.kind !== 'used') continue
218    raw[groupOf(c.name)] += c.tokens
219  }
220  const fileTokens = Math.round(raw.messages * args.fileShare)
221  raw.files = fileTokens
222  raw.messages -= fileTokens
223  const estimate = GROUPS.reduce((s, g) => s + raw[g], 0)
224  const used = args.realTokens ?? estimate
225  const k = estimate > 0 ? used / estimate : 0
226  const parts = { system: 0, tools: 0, files: 0, messages: 0 } as Record<ContextCacheGroup, number>
227  for (const g of GROUPS) parts[g] = Math.round(raw[g] * k)
228  return {
229    used,
230    window: args.window,
231    autoCompactAt: args.isAutoCompactEnabled && args.autoCompactAt ? args.autoCompactAt : null,
232    parts,
233  }
234}
235
236// ── Limits ─────────────────────────────────────────────────────────────────
237
238type Found = { path: string[]; node: Record<string, unknown>; usage: number }
239
240function walk(node: unknown, path: string[], out: Found[]): void {
241  if (Array.isArray(node)) {
242    node.forEach((n, i) => walk(n, [...path, String(i)], out))
243    return
244  }
245  if (node === null || typeof node !== 'object') return
246  const obj = node as Record<string, unknown>
247  // five_hour / seven_day say `utilization`; the limits[] items (the per-model windows) say `percent`.
248  const u = obj['utilization'] ?? obj['percent'] ?? obj['percent_used'] ?? obj['used_percent']
249  if (typeof u === 'number') {
250    out.push({ path, node: obj, usage: u })
251    return
252  }
253  for (const [k, v] of Object.entries(obj)) walk(v, [...path, k], out)
254}
255
256const isFable = (f: Found) => /fable/i.test(f.path.join('.')) || /fable/i.test(JSON.stringify(f.node))
257
258/** Every window with a utilization figure in the account usage JSON, for /cache status. */
259export function usageWindowsOf(json: unknown): { path: string; usage: number; isFable: boolean }[] {
260  const found: Found[] = []
261  walk(json, [], found)
262  return found.map(f => ({ path: f.path.join('.'), usage: f.usage, isFable: isFable(f) }))
263}
264
265function toEpochMs(v: unknown): number | null {
266  if (typeof v === 'number') return v < 1e12 ? v * 1000 : v
267  if (typeof v === 'string') {
268    const t = Date.parse(v)
269    return Number.isNaN(t) ? null : t
270  }
271  return null
272}
273
274/**
275 * Reads the account usage endpoint's JSON (api.anthropic.com/api/oauth/usage),
276 * the same source /usage draws on: `five_hour` is the current session,
277 * `seven_day` the weekly limit, and Fable is the `limits[]` item of kind
278 * `weekly_scoped` whose `scope.model.display_name` is "Fable" (an item with
279 * `scope: null` repeats `seven_day`). Matching by name rather than a fixed
280 * key keeps it working if the key moves.
281 */
282export function parseAccountUsage(json: unknown): ContextCacheLimit[] {
283  const found: Found[] = []
284  walk(json, [], found)
285  const out: ContextCacheLimit[] = []
286  const take = (kind: ContextCacheLimitKind, f: Found | undefined, windowMs: number) => {
287    if (!f) return
288    out.push({
289      kind,
290      usage: Math.max(0, Math.min(100, f.usage)),
291      resetsAt: toEpochMs(f.node['resets_at'] ?? f.node['resetsAt']),
292      windowMs,
293    })
294  }
295  const keyOf = (f: Found) => f.path[f.path.length - 1] ?? ''
296  take('session', found.find(f => keyOf(f) === 'five_hour'), FIVE_HOURS)
297  take('weekly', found.find(f => keyOf(f) === 'seven_day'), SEVEN_DAYS)
298  const fable = found.filter(isFable).sort((a, b) => b.usage - a.usage)[0]
299  take('fable', fable, SEVEN_DAYS)
300  return out
301}
302
303/** The engine's own per-response rate-limit readings, as a fallback. */
304export function limitsFromResponse(rateLimits: readonly SessionRateLimit[]): ContextCacheLimit[] {
305  const out: ContextCacheLimit[] = []
306  for (const r of rateLimits) {
307    const kind: ContextCacheLimitKind | null =
308      r.kind === 'five_hour' ? 'session' : r.kind === 'seven_day' ? 'weekly' : /fable/i.test(r.kind) ? 'fable' : null
309    if (!kind) continue
310    out.push({
311      kind,
312      usage: Math.max(0, Math.min(100, r.percentUsed)),
313      resetsAt: r.resetsAt ? toEpochMs(r.resetsAt) : null,
314      windowMs: kind === 'session' ? FIVE_HOURS : SEVEN_DAYS,
315    })
316  }
317  return out
318}
319
320export type LimitTone = 'normal' | 'amber' | 'red'
321
322export type LimitView = {
323  kind: ContextCacheLimitKind
324  title: string
325  /** Null when this limit has no reading at all. */
326  usage: number | null
327  time: number | null
328  tone: LimitTone
329  bright: string
330  dark: string
331  reset: string
332}
333
334/** Percent of the window that has elapsed, from its reset time. */
335export function timePct(limit: ContextCacheLimit, now: number): number | null {
336  if (limit.resetsAt === null) return null
337  const elapsed = limit.windowMs - (limit.resetsAt - now)
338  return Math.max(0, Math.min(100, (elapsed / limit.windowMs) * 100))
339}
340
341/** Red at ≥ 90% used; amber when > 15 points and > 1.4× ahead of time. */
342export function toneOf(usage: number, time: number | null): LimitTone {
343  if (usage >= 90) return 'red'
344  const t = time ?? 0
345  if (usage - t > 15 && (t === 0 || usage / t > 1.4)) return 'amber'
346  return 'normal'
347}
348
349/** How long a bar pulses after turning amber or red: lit, off, lit, off, a second each. */
350export const PULSE_MS = 4000
351
352/** Whether a pulse that began at `at` is lit at `now`. */
353export function isPulseLit(at: number | undefined, now: number): boolean {
354  if (at === undefined) return false
355  const t = now - at
356  return t >= 0 && t < PULSE_MS && Math.floor(t / 1000) % 2 === 0
357}
358
359export function limitView(kind: ContextCacheLimitKind, limit: ContextCacheLimit | undefined, now: number, pulseAt?: number): LimitView {
360  if (!limit) {
361    const base = LIMIT_COLORS[kind]
362    return { kind, title: LIMIT_TITLES[kind], usage: null, time: null, tone: 'normal', ...base, reset: 'No reading yet' }
363  }
364  const time = timePct(limit, now)
365  const tone = toneOf(limit.usage, time)
366  const colors = tone === 'red' ? RED : tone === 'amber' ? AMBER : LIMIT_COLORS[kind]
367  return {
368    kind,
369    title: LIMIT_TITLES[kind],
370    usage: limit.usage,
371    time,
372    tone,
373    ...colors,
374    ...(isPulseLit(pulseAt, now) ? { bright: mix(colors.bright, '#ffffff', 0.5) } : {}),
375    reset: fmtReset(limit.resetsAt, now),
376  }
377}
378
379const SHORT_TITLES: Record<ContextCacheLimitKind, string> = { session: 'Session', weekly: 'Weekly', fable: 'Fable' }
380
381/** The one-time toast as a limit reaches 90%: "Weekly at 90%, resets Sat 11:00 pm." */
382export function limitToast(limit: ContextCacheLimit, now: number): string {
383  const reset = fmtReset(limit.resetsAt, now)
384  return `${SHORT_TITLES[limit.kind]} at ${pct(limit.usage)}%, ${reset.charAt(0).toLowerCase()}${reset.slice(1)}.`
385}
386
387// ── Cache ──────────────────────────────────────────────────────────────────
388
389export type CacheState = 'warm' | 'cooling' | 'cold' | 'empty'
390
391export type CacheView = {
392  state: CacheState
393  /** Remaining TTL ÷ TTL, 0 to 1. */
394  warmth: number
395  remainingMs: number
396  color: string
397  label: string
398  hit: number | null
399  detail: string
400}
401
402/** Warm > 25% of the TTL left, cooling 1–25%, cold at 0; empty with nothing cached. */
403export function cacheView(cache: ContextCacheCache, now: number): CacheView {
404  const ttl = cache.ttlMs
405  const hit = cache.hitRate === null ? null : cache.hitRate * 100
406  if (cache.lastAt === null) {
407    return {
408      state: 'empty',
409      warmth: 0,
410      remainingMs: 0,
411      color: CACHE_COLORS.empty,
412      label: 'Empty',
413      hit,
414      detail: 'Nothing cached yet',
415    }
416  }
417  // Capped at the TTL: a reply or ping stamps lastAt with a fresher clock than
418  // the drawing's `now`, which would otherwise read as 103% and "61m left of 60m".
419  const remainingMs = Math.max(0, Math.min(ttl, cache.lastAt + ttl - now))
420  const warmth = ttl > 0 ? remainingMs / ttl : 0
421  const state: CacheState = warmth <= 0 ? 'cold' : warmth > 0.25 ? 'warm' : 'cooling'
422  const short = ttl < 10 * 60_000
423  const ttlText = `${Math.round(ttl / 60_000)}m`
424  const detail =
425    state === 'cold'
426      ? (() => {
427          const ago = now - (cache.lastAt + ttl)
428          return ago < 60_000 ? 'Expired just now' : `Expired ${fmtSpan(ago)} ago`
429        })()
430      : short
431        ? `${fmtSpan(remainingMs, true)} left of ${ttlText}`
432        : `${Math.max(1, Math.round(remainingMs / 60_000))}m left of ${ttlText}`
433  return {
434    state,
435    warmth,
436    remainingMs,
437    color: CACHE_COLORS[state],
438    label: state === 'warm' ? 'Warm' : state === 'cooling' ? 'Cooling' : 'Cold',
439    hit,
440    detail,
441  }
442}
443
444/**
445 * The notice line's copy. Always a line: the row with Clear / Compact / Warm never hides.
446 * `short`: the wording for every layout below the widest, short enough to stay on one line.
447 */
448export function noticeText(cache: CacheView, context: ContextCacheContext | null, ttlMs: number, short = false, price: Price | null = null): string {
449  if (!context) return cache.state === 'empty' ? 'Cache empty: nothing cached yet.' : `Cache ${cache.label.toLowerCase()}: reading context size…`
450  const tokens = fmtTokens(context.used)
451  // With a known price: what reading the cache costs, and what writing it again costs.
452  const read = price ? fmtUsd(context.used * price.read) : ''
453  const write = price ? fmtUsd(context.used * price.write) : ''
454  const more = price ? fmtUsd(context.used * (price.write - price.read)) : ''
455  if (cache.state === 'empty') {
456    if (short) return price ? `Cache empty: writes ${tokens} (${write}).` : `Cache empty: writes ${tokens}.`
457    return price ? `Cache empty: next message writes ${tokens} to cache for ${write}.` : `Cache empty: next message writes ${tokens} to cache.`
458  }
459  if (cache.state === 'warm') {
460    const usedPct = (context.used / context.window) * 100
461    if (context.autoCompactAt !== null && usedPct >= 85) {
462      const away = Math.max(0, pct((context.autoCompactAt / context.window) * 100 - usedPct))
463      if (short) return `Warm: reuses ${tokens}. Compact ${away}% away.`
464      return price
465        ? `Cache warm: next message reuses ${tokens} for ${read}. Auto-compact is ${away}% away.`
466        : `Cache warm: next message reuses ${tokens}. Auto-compact is ${away}% away.`
467    }
468    if (short) return price ? `Cache warm: reuses ${tokens} (${read}).` : `Cache warm: reuses ${tokens}.`
469    return price
470      ? `Cache warm: next message reuses ${tokens} for ${read} (${write} if it goes cold).`
471      : `Cache warm: next message reuses ${tokens} from cache.`
472  }
473  if (cache.state === 'cooling') {
474    const within =
475      ttlMs < 10 * 60_000 ? fmtSpan(cache.remainingMs, true) : `${Math.max(1, Math.round(cache.remainingMs / 60_000))}m`
476    if (short) return price ? `Cooling: send within ${within} (${more}).` : `Cooling: send within ${within}.`
477    return price
478      ? `Cache cooling: send within ${within} to keep ${tokens} cached, or pay ${more} more.`
479      : `Cache cooling: send within ${within} to keep ${tokens} cached.`
480  }
481  if (short) return price ? `Cache cold: re-reads ${tokens} (${write}).` : `Cache cold: re-reads ${tokens}.`
482  return price ? `Cache cold: next message re-reads ${tokens} for ${write}. Clear is free.` : `Cache cold: next message re-reads ${tokens}. Clear is free.`
483}
484
485/**
486 * The notice after a Clear or Compact, until the next reply lands: a bold lead
487 * (what was taken out) and the rest (what each later message now costs less).
488 */
489export function savedNotice(saved: ContextCacheSaved, price: Price | null, short = false): { lead: string; rest: string } {
490  const freed = Math.max(0, saved.before - saved.after)
491  const lead =
492    saved.kind === 'clear' ? `Cleared ${fmtTokens(saved.before)}.` : `Compacted ${fmtTokens(saved.before)} → ${fmtTokens(saved.after)}.`
493  if (!price) return { lead, rest: short ? '' : ` Each message now sends ${fmtTokens(freed)} fewer tokens.` }
494  const warm = fmtUsd(freed * price.read)
495  const cold = fmtUsd(freed * price.write)
496  if (short) return { lead, rest: ` ${cold} less a message.` }
497  return saved.kind === 'clear'
498    ? { lead, rest: ` Next message costs ${cold} less, or ${warm} less while the cache is warm.` }
499    : { lead, rest: ` Each message sends ${fmtTokens(freed)} fewer: ${warm} less warm, ${cold} after a break.` }
500}
501
502/** While Warm runs, in place of the cache notice: the last ping and the next, long, short and tiny. */
503export function warmNotice(w: ContextCacheWarming, context: ContextCacheContext | null): string[] {
504  const next = fmtClock(w.nextAt)
505  const p = w.lastPing
506  return p
507    ? [`Kept warm at ${fmtClock(p.at)}, reuses ${fmtTokens(p.read)}. Next ${next}.`, `Warmed ${fmtClock(p.at)}, next ${next}.`, `Next ping ${next}.`]
508    : [
509        `Kept warm: next message reuses ${context ? fmtTokens(context.used) : 'the cache'}. Ping at ${next}.`,
510        `Kept warm: next ping ${next}.`,
511        `Next ping ${next}.`,
512      ]
513}
514
515/** The fewest words for a terminal line too narrow for any wording above. */
516export function tinyNotice(cache: CacheView, context: ContextCacheContext | null): string {
517  if (cache.state === 'cooling') return `Cooling: ${fmtSpan(cache.remainingMs)} left.`
518  if (cache.state === 'warm' && context?.autoCompactAt != null && context.used / context.window >= 0.85) {
519    return `Compact ${Math.max(0, pct(((context.autoCompactAt - context.used) / context.window) * 100))}% away.`
520  }
521  return `Cache ${cache.label.toLowerCase()}.`
522}
523
524/** Every layout below the widest takes the short notice wording: beside three buttons the full sentence wraps from about 620px down. */
525export function isShortNotice(size: SizeClass): boolean {
526  return size !== 'a'
527}
528
529// ── Layout ─────────────────────────────────────────────────────────────────
530
531/**
532 * The design's four widths, in the cells the band is laid out in (≈ 8px a
533 * cell): a ≈ 900px, b ≈ 620px (columns from ~500px), c ≈ 420px (rings),
534 * d ≈ 320px (rings, no legend or detail lines).
535 */
536export type SizeClass = 'a' | 'b' | 'c' | 'd'
537
538export function sizeClassOf(columns: number): SizeClass {
539  if (columns >= 100) return 'a'
540  if (columns >= 62) return 'b'
541  if (columns >= 45) return 'c'
542  return 'd'
543}
544
545/** Rows the terminal card takes in each class (border included). */
546export function rowsFor(size: SizeClass, hasNotice: boolean): number {
547  const body = size === 'a' || size === 'b' ? 1 + 1 + 4 + (hasNotice ? 1 : 0) : size === 'c' ? 1 + 1 + 2 + (hasNotice ? 2 : 0) : 1 + 1 + (hasNotice ? 2 : 0)
548  return body + 2
549}
550
551// ── The whole view ─────────────────────────────────────────────────────────
552
553export type ViewModel = {
554  size: SizeClass
555  context: {
556    used: number
557    window: number
558    usedLabel: string
559    compactPct: number | null
560    rightLabel: string
561    segments: { group: ContextCacheGroup; tokens: number; color: string; label: string }[]
562    free: number
563  } | null
564  limits: LimitView[]
565  cache: CacheView
566  notice: string
567  /** The bold start of the notice (part of `notice`), or empty. */
568  noticeLead: string
569  /** The notice dot's colour: the cache's, or green after a Clear or Compact. */
570  noticeDot: string
571  showLegend: boolean
572  showDetail: boolean
573}
574
575/**
576 * `fitChars`, the terminal's: the cells the notice has on its line. The
577 * longest wording that fits is taken, down to the tiny one, so it never cuts
578 * off. Without it (the desktop), the size class picks the wording.
579 */
580export function buildView(
581  snap: ContextCacheSnapshot,
582  now: number,
583  columns: number,
584  maxRows: number,
585  fitChars?: number,
586): ViewModel {
587  let size = sizeClassOf(columns)
588  const cache = cacheView(snap.cache, now)
589  // Fall back to a shorter layout when the band has fewer rows than it needs.
590  while (size !== 'd' && rowsFor(size, true) > maxRows) {
591    size = size === 'a' ? 'c' : size === 'b' ? 'c' : 'd'
592  }
593  const price = priceOf(snap.model, snap.cache.ttlMs)
594  const isShort = isShortNotice(size)
595  // Priced wordings first (long, then short), then the same without money;
596  // the desktop takes the one its size class names.
597  const options: { lead: string; rest: string }[] = snap.saved
598    ? [price, null].flatMap(p => [false, true].map(short => savedNotice(snap.saved!, p, short)))
599    : snap.warming
600      ? warmNotice(snap.warming, snap.context).map(rest => ({ lead: '', rest }))
601      : [price, null].flatMap(p => [false, true].map(short => ({ lead: '', rest: noticeText(cache, snap.context, snap.cache.ttlMs, short, p) })))
602  if (!snap.saved && !snap.warming) options.push({ lead: '', rest: tinyNotice(cache, snap.context) })
603  const chosen =
604    fitChars === undefined
605      ? options[isShort ? 1 : 0]!
606      : (options.find(o => (o.lead + o.rest).length <= fitChars) ?? options[options.length - 1]!)
607  const saved = snap.saved ? chosen : null
608  const notice = chosen.lead + chosen.rest
609
610  const ctx = snap.context
611  const context = ctx
612    ? (() => {
613        const compactPct = ctx.autoCompactAt === null ? null : pct((ctx.autoCompactAt / ctx.window) * 100)
614        const wide = size === 'a' || size === 'b'
615        const rightLabel =
616          compactPct === null
617            ? `${pct((ctx.used / ctx.window) * 100)}%`
618            : wide
619              ? `Compact at ${compactPct}%`
620              : `${compactPct}%`
621        return {
622          used: ctx.used,
623          window: ctx.window,
624          usedLabel: `${fmtTokens(ctx.used)} / ${fmtTokens(ctx.window)} (${pct((ctx.used / ctx.window) * 100)}%)`,
625          compactPct,
626          rightLabel,
627          segments: GROUPS.map(g => ({
628            group: g,
629            tokens: ctx.parts[g],
630            color: GROUP_COLORS[g],
631            label: GROUP_LABELS[g],
632          })),
633          free: Math.max(0, ctx.window - ctx.used),
634        }
635      })()
636    : null
637
638  const byKind = (k: ContextCacheLimitKind) => snap.limits.find(l => l.kind === k)
639  const limits = (['session', 'weekly', 'fable'] as const).map(k => limitView(k, byKind(k), now, snap.pulse?.[k]))
640
641  return {
642    size,
643    context,
644    limits,
645    cache,
646    notice,
647    noticeLead: saved ? saved.lead : '',
648    noticeDot: saved ? TOKENS.saved : cache.color,
649    showLegend: size !== 'd',
650    showDetail: size === 'a' || size === 'b',
651  }
652}
653
654// ── /cache-mini ────────────────────────────────────────────────────────────
655
656/**
657 * The panel as one line: context %, the cache and what the next message costs
658 * ("Context 45% · Cache warm, 59m left · Next message ≈$0.09"). The longest
659 * wording that fits `columns` less the dot is taken.
660 */
661export function miniLine(snap: ContextCacheSnapshot, now: number, columns: number): string {
662  const cache = cacheView(snap.cache, now)
663  const ctx = snap.context
664  const price = priceOf(snap.model, snap.cache.ttlMs)
665  const live = cache.state === 'warm' || cache.state === 'cooling'
666  const left = live
667    ? snap.cache.ttlMs < 10 * 60_000
668      ? fmtSpan(cache.remainingMs, true)
669      : `${Math.max(1, Math.round(cache.remainingMs / 60_000))}m`
670    : ''
671  const usd = ctx && price ? fmtUsd(ctx.used * (live ? price.read : price.write)) : ''
672  const p = ctx ? `${pct((ctx.used / ctx.window) * 100)}%` : ''
673  const join = (...parts: string[]) => parts.filter(Boolean).join(' · ')
674  const options = [
675    join(p && `Context ${p}`, `Cache ${cache.label.toLowerCase()}${left ? `, ${left} left` : ''}`, usd && `Next message ${usd}`),
676    join(p, `${cache.label}${left ? ` ${left}` : ''}`, usd),
677    join(p, `${cache.label}${left ? ` ${left}` : ''}`),
678    cache.label,
679  ]
680  const room = columns - 2
681  const fit = options.find(o => o.length <= room)
682  return fit ?? options[options.length - 1]!.slice(0, Math.max(0, room))
683}
684
685// ── Colour helpers ─────────────────────────────────────────────────────────
686
687function hexToRgb(hex: string): [number, number, number] {
688  const h = hex.replace('#', '')
689  return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)]
690}
691
692function rgbToHex([r, g, b]: [number, number, number]): string {
693  return `#${[r, g, b].map(v => Math.round(v).toString(16).padStart(2, '0')).join('')}`
694}
695
696/** Mixes `a` toward `b` by `t` (0 → a, 1 → b). */
697export function mix(a: string, b: string, t: number): string {
698  const x = hexToRgb(a)
699  const y = hexToRgb(b)
700  return rgbToHex([x[0] + (y[0] - x[0]) * t, x[1] + (y[1] - x[1]) * t, x[2] + (y[2] - x[2]) * t])
701}
702
703/** The temperature gradient: blue → amber (50%) → orange. */
704export function tempColorAt(x: number): string {
705  const t = Math.max(0, Math.min(1, x))
706  return t < 0.5 ? mix(CACHE_COLORS.cold, CACHE_COLORS.cooling, t / 0.5) : mix(CACHE_COLORS.cooling, CACHE_COLORS.warm, (t - 0.5) / 0.5)
707}
708
hooks/view.tsx 348 lines
1// Drawing for the context-cache panel: one view model, two renderers.
2// Terminal: block-character bars in the design's colours, text glyphs for rings.
3// Desktop (and the editor, the phone's pane): the design drawn as SVG, host buttons.
4
5import type { Elements } from 'claude-code'
6
7import { fmtTokens, pct, TOKENS, tempColorAt, mix, type CacheView, type LimitView, type ViewModel } from './model'
8import { panelSvg } from './panel-svg'
9
10export type Actions = {
11  clear: () => void | Promise<void>
12  compact: () => void | Promise<void>
13  /** Starts keep-warm, or stops it while on. */
14  warm: () => void | Promise<void>
15  isWarming: boolean
16}
17
18type TermEls = Elements['terminal']
19type DeskEls = Elements['desktop'] | Elements['vscode'] | Elements['mobile']
20
21const BAR = '━'
22const TICK = '┃'
23
24// ── Shared bits ────────────────────────────────────────────────────────────
25
26function usageLine(l: LimitView): { main: string; time: string } {
27  if (l.usage === null) return { main: 'No data', time: '' }
28  return { main: `Usage ${pct(l.usage)}%`, time: l.time === null ? '' : ` · Time ${pct(l.time)}%` }
29}
30
31function cacheLine(c: CacheView): { main: string; hit: string } {
32  if (c.state === 'empty') return { main: 'Warmth —', hit: c.hit === null ? '' : ` · Hit ${pct(c.hit)}%` }
33  return { main: `Warmth ${pct(c.warmth * 100)}%`, hit: ` · Hit ${c.hit === null ? '—' : `${pct(c.hit)}%`}` }
34}
35
36// ── Terminal ───────────────────────────────────────────────────────────────
37
38type Cell = { ch: string; color: string }
39
40/** Context bar: one cell run per group, the auto-compact tick over it. */
41export function contextCells(vm: NonNullable<ViewModel['context']>, n: number): Cell[] {
42  const cells: Cell[] = Array.from({ length: n }, () => ({ ch: BAR, color: TOKENS.track }))
43  let acc = 0
44  for (const s of vm.segments) {
45    const start = Math.round((acc / vm.window) * n)
46    acc += s.tokens
47    const end = Math.min(n, Math.round((acc / vm.window) * n))
48    for (let i = start; i < end; i++) cells[i] = { ch: BAR, color: s.color }
49  }
50  if (vm.compactPct !== null) {
51    const i = Math.min(n - 1, Math.floor((vm.compactPct / 100) * n))
52    cells[i] = { ch: TICK, color: TOKENS.tick }
53  }
54  return cells
55}
56
57/** Double bar: dark = time (to max of both), bright = usage, tick at time. */
58export function limitCells(l: LimitView, n: number): Cell[] {
59  const u = l.usage ?? 0
60  const t = l.time ?? 0
61  // Any usage at all shows as at least one cell.
62  const brightEnd = u > 0 ? Math.max(1, Math.round((u / 100) * n)) : 0
63  const darkEnd = Math.max(brightEnd, Math.round((Math.max(u, t) / 100) * n))
64  const cells: Cell[] = Array.from({ length: n }, (_, i) => ({
65    ch: BAR,
66    color: i < brightEnd ? l.bright : i < darkEnd ? l.dark : TOKENS.track,
67  }))
68  // The time tick; at the very start of a window it would hide the bar's first cell.
69  const tickAt = Math.min(n - 1, Math.round((t / 100) * n))
70  if (l.usage !== null && l.time !== null && tickAt >= 1) {
71    cells[tickAt] = { ch: TICK, color: TOKENS.tick }
72  }
73  return cells
74}
75
76/** Temperature bar: the gradient, covered right of the current warmth, a tick at it. */
77export function tempCells(c: CacheView, n: number): Cell[] {
78  const cells: Cell[] = Array.from({ length: n }, (_, i) => {
79    const x = (i + 0.5) / n
80    const color = tempColorAt(x)
81    return { ch: BAR, color: x > c.warmth ? mix(color, TOKENS.card, 0.74) : color }
82  })
83  if (c.state !== 'empty' && c.warmth > 0) {
84    cells[Math.min(n - 1, Math.floor(c.warmth * n))] = { ch: TICK, color: TOKENS.tick }
85  }
86  return cells
87}
88
89function runsOf(cells: Cell[]): { text: string; color: string }[] {
90  const runs: { text: string; color: string }[] = []
91  for (const c of cells) {
92    const last = runs[runs.length - 1]
93    if (last && last.color === c.color) last.text += c.ch
94    else runs.push({ text: c.ch, color: c.color })
95  }
96  return runs
97}
98
99const TERM_GLYPH = { session: '◷', weekly: '▦', fable: '✦' } as const
100function cacheGlyph(c: CacheView): string {
101  return c.state === 'cold' ? '❄' : c.state === 'empty' ? '○' : '♨'
102}
103
104export function renderTerminal(E: TermEls, vm: ViewModel, columns: number, actions: Actions) {
105  const { Box, Text, Button } = E
106  const inner = Math.max(20, columns - 4)
107  const wide = vm.size === 'a' || vm.size === 'b'
108
109  const bar = (cells: Cell[]) => (
110    <Text wrap="truncate">
111      {runsOf(cells).map(r => (
112        <Text color={r.color}>{r.text}</Text>
113      ))}
114    </Text>
115  )
116
117  // Row 1: context
118  const ctx = vm.context
119  // "112k / 1M (11%)": the percentage bold and white, as on the desktop.
120  const used = ctx?.usedLabel.match(/^(.*\()(\d+%)(\))$/)
121  const contextRow = ctx ? (
122    <Box flexDirection="row">
123      <Text bold color={TOKENS.text}>Context </Text>
124      {used ? (
125        <Text color={TOKENS.text3}>
126          {used[1]}
127          <Text bold color={TOKENS.strong}>{used[2]}</Text>
128          {`${used[3]} `}
129        </Text>
130      ) : (
131        <Text color={TOKENS.text3}>{ctx.usedLabel} </Text>
132      )}
133      {bar(contextCells(ctx, Math.max(6, inner - 8 - ctx.usedLabel.length - 1 - ctx.rightLabel.length - 1)))}
134      <Text color={TOKENS.text4}> {ctx.rightLabel}</Text>
135    </Box>
136  ) : (
137    <Text color={TOKENS.text4}>Context: waiting for the first reading</Text>
138  )
139
140  // Row 2: legend. Wide, it starts under the context bar ("Context " and the
141  // used label before it); narrow, one cell in. Only where it still fits on one line.
142  const legendLen = ctx ? ctx.segments.reduce((n, s) => n + `● ${s.label} ${fmtTokens(s.tokens)}  `.length, 0) + `Free ${fmtTokens(ctx.free)}`.length : 0
143  const indent = !ctx ? 0 : wide ? 8 + ctx.usedLabel.length + 1 : 1
144  const legend =
145    ctx && vm.showLegend ? (
146      <Box paddingLeft={indent + legendLen <= inner ? indent : 0}>
147        <Text wrap="wrap">
148          {ctx.segments.map(s => (
149            <Text>
150              <Text color={s.color}>● </Text>
151              <Text color={TOKENS.text2}>{`${s.label} ${fmtTokens(s.tokens)}  `}</Text>
152            </Text>
153          ))}
154          <Text color={TOKENS.text4}>Free </Text>
155          <Text color={TOKENS.freeTokens}>{fmtTokens(ctx.free)}</Text>
156        </Text>
157      </Box>
158    ) : null
159
160  // Row 3: limits + cache
161  let limitsRow
162  if (wide) {
163    const gap = vm.size === 'a' ? 3 : 2
164    const colW = Math.max(8, Math.floor((inner - 3 * gap) / 4))
165    const limitCol = (l: LimitView) => {
166      const line = usageLine(l)
167      return (
168        <Box key={`limit-${l.kind}`} flexDirection="column" width={colW}>
169          <Text bold wrap="truncate" color={l.usage === null ? TOKENS.text4 : TOKENS.text}>
170            {l.title}
171          </Text>
172          {bar(limitCells(l, colW))}
173          <Text wrap="truncate">
174            <Text color={TOKENS.text}>{line.main}</Text>
175            <Text color={TOKENS.text3}>{line.time}</Text>
176          </Text>
177          <Text wrap="truncate" color={TOKENS.text4}>
178            {l.reset}
179          </Text>
180        </Box>
181      )
182    }
183    const c = vm.cache
184    const cl = cacheLine(c)
185    limitsRow = (
186      <Box flexDirection="row" columnGap={gap}>
187        {vm.limits.map(limitCol)}
188        <Box key="cache" flexDirection="column" width={colW}>
189          <Text bold wrap="truncate">
190            <Text color={TOKENS.text}>Cache · </Text>
191            <Text color={c.color}>{c.label}</Text>
192          </Text>
193          {bar(tempCells(c, colW))}
194          <Text wrap="truncate">
195            <Text color={TOKENS.text}>{cl.main}</Text>
196            <Text color={TOKENS.text3}>{cl.hit}</Text>
197          </Text>
198          <Text wrap="truncate" color={TOKENS.text4}>
199            {c.detail}
200          </Text>
201        </Box>
202      </Box>
203    )
204  } else {
205    const showTime = vm.size === 'c'
206    const ring = (l: LimitView) => (
207      <Box key={`limit-${l.kind}`} flexDirection="column">
208        <Text>
209          <Text color={l.bright}>{TERM_GLYPH[l.kind]} </Text>
210          <Text bold color={l.usage === null ? TOKENS.text4 : TOKENS.text}>
211            {l.usage === null ? '—' : `${pct(l.usage)}%`}
212          </Text>
213        </Text>
214        {showTime && <Text color={TOKENS.text3}>{l.time === null ? ' ' : `Time ${pct(l.time)}%`}</Text>}
215      </Box>
216    )
217    const c = vm.cache
218    const cacheMain =
219      c.state === 'cold' || c.state === 'empty' ? (showTime ? c.label : c.label) : showTime ? c.label : `${pct(c.warmth * 100)}%`
220    limitsRow = (
221      <Box flexDirection="row" justifyContent="space-between">
222        {vm.limits.map(ring)}
223        <Box key="cache" flexDirection="column">
224          <Text>
225            <Text color={c.color}>{cacheGlyph(c)} </Text>
226            <Text bold color={TOKENS.text}>
227              {cacheMain}
228            </Text>
229          </Text>
230          {showTime && (
231            <Text color={TOKENS.text3}>
232              {c.state === 'warm' || c.state === 'cooling' ? `${pct(c.warmth * 100)}% warm` : c.detail}
233            </Text>
234          )}
235        </Box>
236      </Box>
237    )
238  }
239
240  // Row 4: notice + actions
241  const buttons = (
242    <Box flexDirection="row" columnGap={1}>
243      <Button key="clear" label="Clear" variant="primary" hotkey="c" onPress={actions.clear} />
244      <Button key="compact" label="Compact" hotkey="k" onPress={actions.compact} />
245      <Button key="warm" label={actions.isWarming ? 'Stop' : 'Warm'} hotkey="w" onPress={actions.warm} />
246    </Box>
247  )
248  // The dot, then the bold lead (after a Clear or Compact) and the rest.
249  const noticeText = [
250    <Text key="dot" color={vm.noticeDot}>● </Text>,
251    vm.noticeLead ? <Text key="lead" color={TOKENS.notice} bold>{vm.noticeLead}</Text> : null,
252    <Text key="rest" color={TOKENS.notice}>{vm.notice.slice(vm.noticeLead.length)}</Text>,
253  ]
254  const notice = vm.notice
255    ? wide ? (
256        <Box flexDirection="row" columnGap={1}>
257          <Box key="notice" flexGrow={1} flexShrink={1}>
258            <Text wrap="truncate">{noticeText}</Text>
259          </Box>
260          {buttons}
261        </Box>
262      ) : (
263        <Box flexDirection="column">
264          <Box key="notice">
265            <Text wrap="wrap">{noticeText}</Text>
266          </Box>
267          <Box flexDirection="row" justifyContent="flex-end">{buttons}</Box>
268        </Box>
269      )
270    : null
271
272  return (
273    <Box
274      key="context-cache"
275      flexDirection="column"
276      borderStyle="round"
277      borderColor={TOKENS.border}
278      paddingX={1}
279    >
280      {contextRow}
281      {legend}
282      {limitsRow}
283      {notice}
284    </Box>
285  )
286}
287
288/** /cache-mini: the whole panel as one line, a dot in the cache's colour first. */
289export function renderMini(E: TermEls | DeskEls, line: string, dot: string) {
290  const { Box, Text } = E
291  return (
292    <Box key="context-cache-mini" paddingX={1}>
293      <Text wrap="truncate">
294        <Text color={dot}>● </Text>
295        <Text color={TOKENS.text2}>{line}</Text>
296      </Text>
297    </Box>
298  )
299}
300
301// ── Desktop (and the editor, and the phone's pane) ─────────────────────────
302//
303// The design at its real pixel sizes: hooks/panel-svg.ts lays rows 1–3 (and a
304// narrow layout's notice) out as one SVG, the host draws the card around it
305// and its own buttons for Clear / Compact / Warm. The SVG is drawn at the
306// width the band is believed to be (cells × px per cell, see /cache scale);
307// where the slot is narrower the host scales it down to fit, so it always
308// fills the width whole and resizes without reflowing.
309
310export function renderDesktop(E: DeskEls, vm: ViewModel, widthPx: number, actions: Actions) {
311  const { Box, Button, Svg } = E
312  const p = panelSvg(vm, Math.max(240, widthPx))
313  const wide = p.size === 'a' || p.size === 'b'
314  const padX = p.size === 'd' ? 1 : 2
315  const button = (key: 'clear' | 'compact' | 'warm', label: string, hotkey: string, extra: Record<string, unknown>) => (
316    <Button key={key} label={label} hotkey={hotkey} onPress={actions[key]} {...extra} />
317  )
318  const buttons = (
319    <Box flexDirection="row" columnGap={1}>
320      {button('clear', 'Clear', 'c', { variant: 'primary' })}
321      {button('compact', 'Compact', 'k', {})}
322      {button('warm', actions.isWarming ? 'Stop' : 'Warm', 'w', {})}
323    </Box>
324  )
325  let actionsRow = null
326  if (vm.notice) {
327    actionsRow =
328      wide && p.notice ? (
329        <Box flexDirection="row" alignItems="center" columnGap={1} paddingRight={padX} paddingBottom={1}>
330          <Box key="notice" flexGrow={1} flexShrink={1} minWidth={0}>
331            <Svg source={p.notice.svg} alt={vm.notice} />
332          </Box>
333          {buttons}
334        </Box>
335      ) : (
336        // The notice is in the SVG above; the buttons sit together under it, at the right.
337        // (The design's equal-width buttons need stretchable controls, which the host's native buttons are not.)
338        <Box flexDirection="row" justifyContent="flex-end" paddingX={padX} paddingBottom={1}>{buttons}</Box>
339      )
340  }
341  return (
342    <Box key="context-cache" flexDirection="column" borderStyle="round" borderColor={TOKENS.border} backgroundColor={TOKENS.card}>
343      <Svg source={p.body.svg} alt={p.alt} />
344      {actionsRow}
345    </Box>
346  )
347}
348
hooks/panel-svg.ts 472 lines
1// The desktop/mobile panel drawn as SVG at the design's exact pixel sizes.
2//
3// The host's Text has no font size, so every line of the design (13px titles,
4// 12.5px labels, 11.5px detail, 10.5px ring captions) is laid out here with
5// the design's own font stack and Arial-compatible metrics, positioned the
6// way the browser positions the design's HTML (line-height normal, flex gaps,
7// ellipsis). The host draws the card, and its own buttons for the actions.
8
9import { ellipsize, textWidth } from './metrics'
10import { CACHE_COLORS, fmtTokens, pct, TOKENS, type CacheView, type LimitView, type ViewModel } from './model'
11
12const FONT = `'Helvetica Neue', Helvetica, Arial, sans-serif`
13// Arial / Helvetica vertical metrics per em. Chrome rounds each to whole
14// pixels before stacking them into a line box, so this does too.
15const ASC = 0.905
16const DESC = 0.212
17const GAP = 0.0327
18const A = (size: number) => Math.round(ASC * size)
19const D = (size: number) => Math.round(DESC * size)
20const TICK = 'rgba(236,233,226,.85)'
21const NS = 'http://www.w3.org/2000/svg'
22
23/** The design's four widths: a ≈ 900px, b ≈ 620px (columns from ~500px), c ≈ 420px (rings), d ≈ 320px (no legend). */
24export type DesignSize = ViewModel['size']
25
26const PAD: Record<DesignSize, { y: number; x: number }> = {
27  a: { y: 14, x: 18 },
28  b: { y: 11, x: 14 },
29  c: { y: 11, x: 14 },
30  d: { y: 10, x: 12 },
31}
32const ROW_GAP = 11
33/** The legend sits this much closer to the context row than ROW_GAP (Chris's preview, 2026-10-13); the rows below stay put. */
34const LEGEND_UP: Record<DesignSize, number> = { a: 4, b: 5, c: 1, d: 0 }
35/** Where the legend starts: under the context bar when wide, else this far in from the padding. */
36const LEGEND_IN_NARROW = 8
37/** The notice text starts this far after the dot's left edge: the 7px dot and a 5px gap. */
38const NOTICE_TEXT_X = 12
39/** The notice beside the buttons (wide) is a size up from the narrow one. */
40const noticeSize = (wide: boolean) => (wide ? 13.5 : 12.5)
41/** A design button: 12.5px text, 6px padding, a 1px border on Compact. */
42export const BUTTON_H = lhOf(12.5) + 12 + 2
43
44function lhOf(size: number): number {
45  return A(size) + D(size) + Math.round(GAP * size)
46}
47
48const lh = lhOf
49/** Baseline of a line box of height `box` (default: line-height normal) with its top at `top`. */
50const baseline = (top: number, size: number, box = lhOf(size)) => top + (box - A(size) - D(size)) / 2 + A(size)
51const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
52const r2 = (n: number) => Math.round(n * 100) / 100
53
54type Run = { text: string; color: string; bold?: boolean }
55
56/** One line of runs starting at x, its line box's top at `top`. */
57function line(x: number, top: number, size: number, runs: Run[], anchor: 'start' | 'end' = 'start', clipId?: string): string {
58  const y = r2(baseline(top, size))
59  const spans = runs
60    .map(r => `<tspan fill="${r.color}"${r.bold ? ' font-weight="700"' : ''}>${esc(r.text)}</tspan>`)
61    .join('')
62  const clip = clipId ? ` clip-path="url(#${clipId})"` : ''
63  return `<text x="${r2(x)}" y="${y}" font-size="${size}" text-anchor="${anchor}"${clip} xml:space="preserve">${spans}</text>`
64}
65
66function runsWidth(runs: Run[], size: number): number {
67  return runs.reduce((w, r) => w + textWidth(r.text, size, r.bold), 0)
68}
69
70/** Cuts a run list to `max` px with an ellipsis on the run that overflows. */
71function fitRuns(runs: Run[], size: number, max: number): Run[] {
72  if (runsWidth(runs, size) <= max) return runs
73  const out: Run[] = []
74  let used = 0
75  for (const r of runs) {
76    const w = textWidth(r.text, size, r.bold)
77    if (used + w <= max - textWidth('…', size, r.bold)) {
78      out.push(r)
79      used += w
80      continue
81    }
82    out.push({ ...r, text: ellipsize(r.text, size, max - used, r.bold) })
83    break
84  }
85  return out
86}
87
88/** The first wording that fits `max` px whole; the shortest, cut, when none does. */
89function fitFirst(options: Run[][], size: number, max: number): Run[] {
90  return options.find(o => runsWidth(o, size) <= max) ?? fitRuns(options[options.length - 1]!, size, max)
91}
92
93/** A rounded 8px bar track, clipped, with whatever is drawn inside. */
94function bar(id: string, x: number, y: number, w: number, inner: string, track: string = TOKENS.track): string {
95  return (
96    `<clipPath id="${id}"><rect x="${r2(x)}" y="${r2(y)}" width="${r2(Math.max(0, w))}" height="8" rx="4"/></clipPath>` +
97    `<g clip-path="url(#${id})"><rect x="${r2(x)}" y="${r2(y)}" width="${r2(Math.max(0, w))}" height="8" fill="${track}"/>${inner}</g>`
98  )
99}
100
101function tick(x: number, y: number): string {
102  return `<rect x="${r2(x)}" y="${r2(y)}" width="2" height="8" fill="${TICK}"/>`
103}
104
105/** Context: segments as flex children with 1px gaps; the auto-compact tick. */
106function contextBar(id: string, ctx: NonNullable<ViewModel['context']>, x: number, y: number, w: number): string {
107  let inner = ''
108  let at = x
109  for (const s of ctx.segments) {
110    const sw = (s.tokens / ctx.window) * w
111    if (s.tokens > 0) inner += `<rect x="${r2(at)}" y="${r2(y)}" width="${r2(sw)}" height="8" fill="${s.color}"/>`
112    at += sw + 1
113  }
114  if (ctx.compactPct !== null) inner += tick(x + (ctx.compactPct / 100) * w, y)
115  return bar(id, x, y, w, inner)
116}
117
118/** Limit: dark = time (to the larger of both), bright = usage, tick at time. */
119function limitBar(id: string, l: LimitView, x: number, y: number, w: number): string {
120  if (l.usage === null) return bar(id, x, y, w, '')
121  const u = l.usage
122  const t = l.time ?? 0
123  const darkW = (Math.max(u, t) / 100) * w
124  let inner = `<rect x="${r2(x)}" y="${r2(y)}" width="${r2(darkW)}" height="8" fill="${l.dark}"/>`
125  inner += `<rect x="${r2(x)}" y="${r2(y)}" width="${r2((u / 100) * w)}" height="8" fill="${l.bright}"/>`
126  if (l.time !== null) inner += tick(x + (t / 100) * w, y)
127  return bar(id, x, y, w, inner)
128}
129
130/** Cache: the temperature gradient, covered right of the warmth, tick at it. */
131function tempBar(id: string, c: CacheView, x: number, y: number, w: number): string {
132  const gid = `${id}g`
133  const wx = x + c.warmth * w
134  let inner =
135    `<linearGradient id="${gid}" gradientUnits="userSpaceOnUse" x1="${r2(x)}" x2="${r2(x + w)}" y1="0" y2="0">` +
136    `<stop offset="0" stop-color="${CACHE_COLORS.cold}"/><stop offset="0.5" stop-color="${CACHE_COLORS.cooling}"/>` +
137    `<stop offset="1" stop-color="${CACHE_COLORS.warm}"/></linearGradient>` +
138    `<rect x="${r2(x)}" y="${r2(y)}" width="${r2(w)}" height="8" fill="url(#${gid})"/>` +
139    `<rect x="${r2(wx)}" y="${r2(y)}" width="${r2(x + w - wx)}" height="8" fill="rgba(34,33,32,.74)"/>`
140  if (c.state !== 'empty') inner += tick(wx, y)
141  return bar(id, x, y, w, inner, 'transparent')
142}
143
144// ── Icons and rings ────────────────────────────────────────────────────────
145
146type IconName = 'clock' | 'calendar' | 'fable' | 'flame' | 'snow' | 'empty'
147
148/** 24-unit icons standing in for the design's text glyphs (5h, 7d, F, ◆). */
149function icon(name: IconName, color: string): string {
150  const s = `fill="none" stroke="${color}" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"`
151  switch (name) {
152    case 'clock':
153      return `<circle cx="12" cy="12" r="9" ${s}/><path d="M12 7v5l3.5 2" ${s}/>`
154    case 'calendar':
155      return `<rect x="3.5" y="5" width="17" height="15" rx="2.5" ${s}/><path d="M3.5 10h17M8.5 3v4M15.5 3v4" ${s}/>`
156    case 'fable':
157      return `<path d="M12 2.5l2.2 6.6 6.8 2.4-6.8 2.4L12 20.5l-2.2-6.6L3 11.5l6.8-2.4z" fill="${color}"/>`
158    case 'flame':
159      return `<path d="M12 2.5c.8 3.4 5 5.6 5 10.5a5 5 0 0 1-10 0c0-2.6 1.4-4 2.6-5.2.2 2 1 3.2 2.4 3.6-.6-3.2-.8-6.2 0-8.9z" fill="${color}"/>`
160    case 'snow':
161      return `<path d="M12 2.5v19M3.8 7.2l16.4 9.6M20.2 7.2L3.8 16.8" ${s}/>`
162    case 'empty':
163      return `<circle cx="12" cy="12" r="7" ${s}/>`
164  }
165}
166
167/** An arc of the 30px ring (centre radius 13, 4 wide) from deg a to deg b, clockwise from 12 o'clock. */
168function arc(cx: number, cy: number, a: number, b: number, color: string): string {
169  if (b - a <= 0) return ''
170  if (b - a >= 359.99) return `<circle cx="${cx}" cy="${cy}" r="13" fill="none" stroke="${color}" stroke-width="4"/>`
171  const p = (deg: number) => {
172    const rad = ((deg - 90) * Math.PI) / 180
173    return `${r2(cx + 13 * Math.cos(rad))} ${r2(cy + 13 * Math.sin(rad))}`
174  }
175  const large = b - a > 180 ? 1 : 0
176  return `<path d="M${p(a)} A13 13 0 ${large} 1 ${p(b)}" fill="none" stroke="${color}" stroke-width="4"/>`
177}
178
179/** The design's conic ring: bright = usage, dark to the larger of usage and time, a 4° notch at time. */
180function ring(x: number, y: number, a: { usage: number | null; time: number | null; bright: string; dark: string; icon: IconName; iconColor: string }): string {
181  const cx = x + 15
182  const cy = y + 15
183  let s = `<circle cx="${cx}" cy="${cy}" r="13" fill="none" stroke="${TOKENS.ringTrack}" stroke-width="4"/>`
184  if (a.usage !== null) {
185    const u = a.usage * 3.6
186    const t = (a.time ?? 0) * 3.6
187    s += arc(cx, cy, 0, Math.max(u, t), a.dark)
188    s += arc(cx, cy, 0, u, a.bright)
189    if (a.time !== null) s += arc(cx, cy, Math.max(0, t - 2), Math.min(360, t + 2), TICK)
190  }
191  s += `<circle cx="${cx}" cy="${cy}" r="11" fill="${TOKENS.card}"/>`
192  s += `<g transform="translate(${cx - 6} ${cy - 6}) scale(0.5)">${icon(a.icon, a.iconColor)}</g>`
193  return s
194}
195
196const LIMIT_ICON = { session: 'clock', weekly: 'calendar', fable: 'fable' } as const
197const cacheIcon = (c: CacheView): IconName => (c.state === 'cold' ? 'snow' : c.state === 'empty' ? 'empty' : 'flame')
198
199// ── The panel ──────────────────────────────────────────────────────────────
200
201export type PanelSvg = {
202  size: DesignSize
203  /** What the whole panel says, for a reader that cannot see it. */
204  alt: string
205  /** Everything above the buttons: rows 1–3 (and, narrow, the notice text), padded as the card. */
206  body: { svg: string; width: number; height: number }
207  /** Wide layouts: the notice line beside the buttons. */
208  notice: { svg: string; width: number; height: number } | null
209  /** The width the host's buttons take on wide layouts, right padding included. */
210  buttonsWidth: number
211  /** Wide, but the notice is too long to sit beside the buttons: they wrap below it, left-aligned. */
212  noticeWraps: boolean
213  pad: { x: number; y: number }
214}
215
216function svgDoc(width: number, height: number, body: string, alt: string): string {
217  return (
218    `<svg xmlns="${NS}" width="${r2(width)}" height="${r2(height)}" viewBox="0 0 ${r2(width)} ${r2(height)}" ` +
219    `font-family="${FONT}" role="img" aria-label="${esc(alt)}">${body}</svg>`
220  )
221}
222
223/** Width of the design's three buttons (Warm or Stop, whichever is wider) and their gaps. */
224function buttonsWidthOf(): number {
225  const b = (label: string, padX: number, border: number) => textWidth(label, 12.5) + padX * 2 + border * 2
226  return b('Clear', 12, 0) + b('Compact', 12, 1) + Math.max(b('Warm', 12, 1), b('Stop', 12, 1)) + 6 * 2
227}
228
229/**
230 * Lays the panel out at `width` px (the card's inner width, border excluded)
231 * in the view model's size class. Ids are prefixed so several panels can share a page.
232 */
233export function panelSvg(vm: ViewModel, width: number, idPrefix = 'cc'): PanelSvg {
234  const size = vm.size
235  const pad = PAD[size]
236  const W = width
237  const inner = W - pad.x * 2
238  const wide = size === 'a' || size === 'b'
239  let y = pad.y
240  let out = ''
241  let n = 0
242  const id = () => `${idPrefix}${n++}`
243
244  // Row 1: Context
245  const ctx = vm.context
246  const h1 = lh(13)
247  let barX = pad.x
248  if (ctx) {
249    const right = ctx.compactPct === null ? `${pct((ctx.used / ctx.window) * 100)}%` : wide ? `Compact at ${ctx.compactPct}%` : `${ctx.compactPct}%`
250    const cy = y + h1 / 2
251    let x = pad.x
252    out += line(x, cy - lh(13) / 2, 13, [{ text: 'Context', color: TOKENS.text, bold: true }])
253    x += textWidth('Context', 13, true) + 10
254    // "112k / 1M (11%)": the percentage stands out, bold and white.
255    const m = ctx.usedLabel.match(/^(.*\()(\d+%)(\))$/)
256    const used: Run[] = m
257      ? [{ text: m[1]!, color: TOKENS.text3 }, { text: m[2]!, color: TOKENS.strong, bold: true }, { text: m[3]!, color: TOKENS.text3 }]
258      : [{ text: ctx.usedLabel, color: TOKENS.text3 }]
259    out += line(x, cy - lh(12.5) / 2, 12.5, used)
260    x += runsWidth(used, 12.5) + 10
261    const rightX = W - pad.x
262    out += line(rightX, cy - lh(12.5) / 2, 12.5, [{ text: right, color: TOKENS.text4 }], 'end')
263    const barW = Math.max(40, rightX - textWidth(right, 12.5) - 10 - x)
264    out += contextBar(id(), ctx, x, cy - 4, barW)
265    barX = x
266  } else {
267    out += line(pad.x, y, 12.5, [{ text: 'Context: waiting for the first reading', color: TOKENS.text4 }])
268  }
269  y += h1 + ROW_GAP
270
271  // Row 2: legend (wraps; 12px between items, 4px between lines)
272  if (ctx && size !== 'd') {
273    const items: Run[][] = ctx.segments.map(s => [
274      { text: '●', color: s.color },
275      { text: ` ${s.label} ${fmtTokens(s.tokens)}`, color: TOKENS.text2 },
276    ])
277    items.push([
278      { text: 'Free ', color: TOKENS.text4 },
279      { text: fmtTokens(ctx.free), color: TOKENS.freeTokens },
280    ])
281    // Wide: the legend starts under the context bar, or back at the padding if it would not fit there.
282    const total = items.reduce((w, it, i) => w + runsWidth(it, 11.5) + (i ? 12 : 0), 0)
283    const startX = wide && barX + total <= pad.x + inner ? barX : wide ? pad.x : pad.x + LEGEND_IN_NARROW
284    // Lines decided with the metrics; within a line the font itself flows the runs.
285    const lines: Run[][][] = [[]]
286    let x = startX
287    for (const it of items) {
288      const w = runsWidth(it, 11.5)
289      if (x > startX && x + w > pad.x + inner) {
290        lines.push([])
291        x = startX
292      }
293      lines[lines.length - 1]!.push(it)
294      x += w + 12
295    }
296    let lineTop = y
297    const up = LEGEND_UP[size]
298    lines.forEach((ln, i) => {
299      if (i > 0) lineTop += lh(11.5) + 4
300      const base = r2(baseline(lineTop - up, 11.5))
301      const spans = ln
302        .map((it, j) =>
303          it
304            .map((r, k) => `<tspan${j > 0 && k === 0 ? ' dx="12"' : ''} fill="${r.color}">${esc(r.text)}</tspan>`)
305            .join(''),
306        )
307        .join('')
308      out += `<text x="${r2(startX)}" y="${base}" font-size="11.5" xml:space="preserve">${spans}</text>`
309    })
310    y = lineTop + lh(11.5) + ROW_GAP
311  }
312
313  // Row 3: limits + cache
314  const c = vm.cache
315  if (wide) {
316    const gap = size === 'a' ? 18 : 12
317    const colW = (inner - gap * 3) / 4
318    const ts = size === 'a' ? 13 : 12.5
319    const col = (i: number) => pad.x + i * (colW + gap)
320    vm.limits.forEach((l, i) => {
321      const x = col(i)
322      const clip = id()
323      out += `<clipPath id="${clip}"><rect x="${r2(x)}" y="${r2(y)}" width="${r2(colW)}" height="80"/></clipPath>`
324      let yy = y
325      out += line(x, yy, ts, fitRuns([{ text: l.title, color: l.usage === null ? TOKENS.text4 : TOKENS.text, bold: true }], ts, colW), 'start', clip)
326      yy += lh(ts) + 5
327      out += limitBar(id(), l, x, yy, colW)
328      yy += 8 + 5
329      // Narrow columns drop the words before the numbers rather than cut the time off.
330      const usage = (u: string, t: string): Run[] => [
331        { text: `${u}${pct(l.usage!)}% · `, color: TOKENS.text },
332        { text: l.time === null ? '' : `${t}${pct(l.time)}%`, color: TOKENS.text3 },
333      ]
334      const usageRuns =
335        l.usage === null
336          ? [{ text: 'No data', color: TOKENS.text4 }]
337          : fitFirst([usage('Usage ', 'Time '), usage('', 'Time '), usage('', 'T ')], 11.5, colW)
338      out += line(x, yy, 11.5, usageRuns, 'start', clip)
339      yy += lh(11.5) + 5
340      const reset = (t: string): Run[] => [{ text: t, color: TOKENS.text4 }]
341      out += line(x, yy, 11.5, fitFirst([reset(l.reset), reset(l.reset.replace(/^Resets (in )?/, ''))], 11.5, colW), 'start', clip)
342    })
343    {
344      const x = col(3)
345      const clip = id()
346      out += `<clipPath id="${clip}"><rect x="${r2(x)}" y="${r2(y)}" width="${r2(colW)}" height="80"/></clipPath>`
347      let yy = y
348      out += line(
349        x,
350        yy,
351        ts,
352        fitRuns(
353          [
354            { text: 'Cache · ', color: TOKENS.text, bold: true },
355            { text: c.label, color: c.color, bold: true },
356          ],
357          ts,
358          colW,
359        ),
360        'start',
361        clip,
362      )
363      yy += lh(ts) + 5
364      out += tempBar(id(), c, x, yy, colW)
365      yy += 8 + 5
366      const warm = (w: string, h: string): Run[] => [
367        { text: `${w}${c.state === 'empty' ? '—' : `${pct(c.warmth * 100)}%`} · `, color: TOKENS.text },
368        { text: `${h}${c.hit === null ? '—' : `${pct(c.hit)}%`}`, color: TOKENS.text3 },
369      ]
370      out += line(x, yy, 11.5, fitFirst([warm('Warmth ', 'Hit '), warm('', 'Hit ')], 11.5, colW), 'start', clip)
371      yy += lh(11.5) + 5
372      out += line(x, yy, 11.5, fitRuns([{ text: c.detail, color: TOKENS.text4 }], 11.5, colW), 'start', clip)
373    }
374    y += lh(ts) + 5 + 8 + 5 + lh(11.5) + 5 + lh(11.5) + ROW_GAP
375  } else {
376    // Rings: four items spread with space-between, each a 30px ring, 6px, then text.
377    const twoLines = size === 'c'
378    const items = [
379      ...vm.limits.map(l => ({
380        ring: { usage: l.usage, time: l.time, bright: l.bright, dark: l.dark, icon: LIMIT_ICON[l.kind], iconColor: l.bright },
381        main: { text: l.usage === null ? '—' : `${pct(l.usage)}%`, color: TOKENS.text },
382        sub: l.time === null ? '' : `Time ${pct(l.time)}%`,
383      })),
384      {
385        ring: {
386          usage: c.state === 'empty' ? null : c.warmth * 100,
387          time: null,
388          bright: c.color,
389          dark: c.color,
390          icon: cacheIcon(c),
391          iconColor: c.color,
392        },
393        main: {
394          text: twoLines || c.state === 'cold' || c.state === 'empty' ? c.label : `${pct(c.warmth * 100)}%`,
395          color: c.color,
396        },
397        sub: c.state === 'empty' ? 'Nothing cached' : `${pct(c.warmth * 100)}% warm`,
398      },
399    ]
400    const widths = items.map(it => 30 + 6 + Math.max(textWidth(it.main.text, 13, true), twoLines ? textWidth(it.sub, 10.5) : 0))
401    const free = Math.max(0, inner - widths.reduce((a, b) => a + b, 0))
402    const step = free / (items.length - 1)
403    const textH = twoLines ? 13 * 1.25 + 10.5 * 1.25 : 13 * 1.25
404    const rowH = Math.max(30, textH)
405    let x = pad.x
406    items.forEach((it, i) => {
407      out += ring(x, y + (rowH - 30) / 2, it.ring)
408      const tx = x + 36
409      const ty = y + (rowH - textH) / 2
410      // line-height 1.25: the 13px line is 16.25 tall, the 10.5px one 13.125
411      out += `<text x="${r2(tx)}" y="${r2(baseline(ty, 13, 16.25))}" font-size="13" font-weight="700" fill="${it.main.color}">${esc(it.main.text)}</text>`
412      if (twoLines) {
413        out += `<text x="${r2(tx)}" y="${r2(baseline(ty + 16.25, 10.5, 13.125))}" font-size="10.5" fill="${TOKENS.text3}">${esc(it.sub)}</text>`
414      }
415      x += (widths[i] ?? 0) + step
416    })
417    y += rowH + ROW_GAP
418  }
419
420  // Notice: beside the buttons when wide; above them, wrapped, when narrow.
421  let notice: PanelSvg['notice'] = null
422  let noticeWraps = false
423  const buttonsWidth = buttonsWidthOf() + pad.x
424  if (vm.notice) {
425    // The bold lead (after a Clear or Compact) and the rest, in the notice colour.
426    const lead = vm.noticeLead
427    const runsOf = (text: string): Run[] =>
428      lead && text.startsWith(lead)
429        ? [{ text: lead, color: TOKENS.notice, bold: true }, { text: text.slice(lead.length), color: TOKENS.notice }]
430        : [{ text, color: TOKENS.notice }]
431    const ns = noticeSize(wide)
432    noticeWraps = wide && NOTICE_TEXT_X + runsWidth(runsOf(vm.notice), ns) + 12 + buttonsWidthOf() > inner
433    if (wide && !noticeWraps) {
434      const nw = Math.max(80, W - buttonsWidth - 12)
435      const top = (BUTTON_H - lh(ns)) / 2
436      const body =
437        `<circle cx="${pad.x + 3.5}" cy="${r2(BUTTON_H / 2)}" r="3.5" fill="${vm.noticeDot}"/>` +
438        line(pad.x + NOTICE_TEXT_X, top, ns, fitRuns(runsOf(vm.notice), ns, nw - pad.x - NOTICE_TEXT_X))
439      notice = { svg: svgDoc(nw, BUTTON_H, body, vm.notice), width: nw, height: BUTTON_H }
440    } else {
441      const maxW = inner - NOTICE_TEXT_X // narrow, or wide with the buttons wrapped below
442      // Break where the browser would: after spaces, and after hyphens.
443      const words = vm.notice.match(/[^\s-]*-|[^\s-]+\s*|\s+/g) ?? [vm.notice]
444      const lines: string[] = []
445      let cur = ''
446      for (const w of words) {
447        const next = cur + w
448        if (cur && textWidth(next.trimEnd(), 12.5) > maxW) {
449          lines.push(cur.trimEnd())
450          cur = w.trimStart()
451        } else cur = next
452      }
453      if (cur.trim()) lines.push(cur.trimEnd())
454      const blockH = lines.length * lh(12.5)
455      out += `<circle cx="${pad.x + 3.5}" cy="${r2(y + blockH / 2)}" r="3.5" fill="${vm.noticeDot}"/>`
456      lines.forEach((t, i) => {
457        out += line(pad.x + NOTICE_TEXT_X, y + i * lh(12.5), 12.5, i === 0 ? runsOf(t) : [{ text: t, color: TOKENS.notice }])
458      })
459      y += blockH + (noticeWraps ? 12 : ROW_GAP)
460    }
461  }
462
463  const alt = [
464    ctx ? `Context ${ctx.usedLabel}` : 'Context: no reading',
465    ...vm.limits.map(l => `${l.title}: ${l.usage === null ? 'no data' : `${pct(l.usage)}% used, ${pct(l.time ?? 0)}% of time`}`),
466    `Cache ${c.label}, ${c.detail}`,
467  ].join('. ')
468  // The bottom gap belongs to the buttons row when there is one.
469  const height = vm.notice ? y : y - ROW_GAP + pad.y
470  return { size, alt, body: { svg: svgDoc(W, height, out, alt), width: W, height }, notice, buttonsWidth, noticeWraps, pad }
471}
472
hooks/metrics.ts 35 lines
1// Advance widths (per 1000 em) of Arial / Helvetica-compatible metrics
2// (Liberation Sans), for laying out SVG text the way the browser lays out
3// the design's "Helvetica Neue", Helvetica, Arial stack. Generated.
4
5const CHARS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~·●—…◆–'
6const REGULAR = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 333, 604, 1000, 1000, 600, 556]
7const BOLD = [278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 333, 604, 1000, 1000, 600, 556]
8
9const reg = new Map<string, number>()
10const bold = new Map<string, number>()
11for (let i = 0; i < CHARS.length; i++) {
12  reg.set(CHARS[i]!, REGULAR[i]!)
13  bold.set(CHARS[i]!, BOLD[i]!)
14}
15
16/** Width in px of `text` at `size` px, regular or bold. */
17export function textWidth(text: string, size: number, isBold = false): number {
18  const table = isBold ? bold : reg
19  let units = 0
20  for (const ch of text) units += table.get(ch) ?? 556
21  return (units / 1000) * size
22}
23
24/** `text` cut to fit `max` px, with an ellipsis, as CSS text-overflow does. */
25export function ellipsize(text: string, size: number, max: number, isBold = false): string {
26  if (textWidth(text, size, isBold) <= max) return text
27  const ell = '…'
28  let out = ''
29  for (const ch of text) {
30    if (textWidth(out + ch + ell, size, isBold) > max) break
31    out += ch
32  }
33  return out.replace(/\s+$/, '') + ell
34}
35
types/index.d.ts 90 lines
1// Contract for the context-cache mod: the values it keeps in $.state.
2
3/** The four groups the context bar is split into. */
4export type ContextCacheGroup = 'system' | 'tools' | 'files' | 'messages'
5
6/** The live context window, as measured after the last response. */
7export type ContextCacheContext = {
8  /** Tokens in the window now (the last response's input side, or the local estimate before one). */
9  used: number
10  /** The model's context window in tokens. */
11  window: number
12  /** Token count at which auto-compact runs; null when auto-compact is off. */
13  autoCompactAt: number | null
14  /** Tokens per group, scaled so they sum to `used`. */
15  parts: Record<ContextCacheGroup, number>
16}
17
18export type ContextCacheLimitKind = 'session' | 'weekly' | 'fable'
19
20/** One usage-limit window. */
21export type ContextCacheLimit = {
22  kind: ContextCacheLimitKind
23  /** Percent of the window used, 0 to 100. */
24  usage: number
25  /** When the window resets, epoch milliseconds; null when not reported. */
26  resetsAt: number | null
27  /** The window's length in milliseconds (5h or 7d). */
28  windowMs: number
29}
30
31/** What is known about the prompt cache. */
32export type ContextCacheCache = {
33  /** When the main conversation's cache was last written or read (end of the last turn); null when nothing is cached. */
34  lastAt: number | null
35  /** The cache's time to live in milliseconds (300000 or 3600000). */
36  ttlMs: number
37  /** True once the TTL was read from a real response or the engine. */
38  isTtlKnown: boolean
39  /** cache_read ÷ (cache_read + cache_creation + uncached input) of the last turn, 0 to 1. */
40  hitRate: number | null
41}
42
43export type ContextCacheSnapshot = {
44  context: ContextCacheContext | null
45  limits: ContextCacheLimit[]
46  /** Where the limits came from: the account usage endpoint, the last response's headers, or nowhere. */
47  limitsSource: 'account' | 'response' | 'none'
48  cache: ContextCacheCache
49  /** When this snapshot was taken, epoch milliseconds. */
50  updatedAt: number
51  /** The session's model id, to price tokens; absent or null when not read yet. */
52  model?: string | null
53  /** What the last Clear or Compact took out of the context; shown until the next reply lands. */
54  saved?: ContextCacheSaved | null
55  /** When each limit's bar last turned amber or red, epoch milliseconds: it pulses for a few seconds. */
56  pulse?: Partial<Record<ContextCacheLimitKind, number>>
57  /** While Warm runs: filled in when the panel is drawn, from the warming state. */
58  warming?: ContextCacheWarming | null
59}
60
61/** Keep-warm in progress: the last ping that read the cache (null before the first) and when the next is due. */
62export type ContextCacheWarming = {
63  lastPing: { at: number; read: number } | null
64  nextAt: number
65}
66
67/** A Clear or Compact: the context before and after it, in tokens. */
68export type ContextCacheSaved = {
69  kind: 'clear' | 'compact'
70  before: number
71  after: number
72}
73
74declare module 'claude-code' {
75  interface PluginState {
76    'context-cache': {
77      snapshot: ContextCacheSnapshot | null
78      isHidden: boolean
79      /** The clock, written once a second so the countdown redraws. */
80      now: number
81      /** Desktop/mobile: CSS px per host cell, to draw the design at its real px size (/cache scale). */
82      pxPerCell: number
83      /** Keep-warm: when it switches itself off, epoch milliseconds; null while off. */
84      warmUntil: number | null
85      /** /cache-mini: the band drawn as one line. */
86      isMini: boolean
87    }
88  }
89}
90