SLOPSHOPPER

token-range-monitor

Projects what will be left of your weekly and 5-hour Claude limits at reset, from your recent usage rate

panebandguardcommandprocessnetwork
v1.4.8MITupdated 2026-10-16micke-dahlgren/token-range-monitor
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · token-range-monitor
│ ┃ Token Range Monitor 1.4.8 ✕ › fix the failing auth test and add an audit log call │ ┃ No weekly limit reported. │ ┃ ╭─────────────────────────────────────────── ⏺ Read(src/auth.ts) │ ┃ │ 5-hour window Lasts to the reset ⎿ Read 6 lines │ ┃ │ 31% ░░░░░░░░░░░░░░░░░░░░░░░░░░ ⏺ Update(src/auth.ts) │ ┃ │ resets NaN:NaN ⎿ Added 2 lines, removed 1 line │ ┃ ╰─────────────────────────────────────────── ⏺ Bash(bun test) │ ┃ ╭─────────────────────────────────────────── ⎿ 3 pass, 1 fail │ ┃ │ Models [ 5h ] [ Week ] │ ┃ │ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ Not recorded 31% │ ┃ │ Details ✻ Worked for 42s · done 4:20 PM │ ┃ ╰─────────────────────────────────────────── │ ┃ › /token-range │ ┃ Click here to enable sync between devices ⎿ token-range-monitor: Token Range Monitor opened. │ │ 5h ~NaN% left at NaN:NaN [ Details ↗ ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
5h ~NaN% left at NaN:NaN [ Details ↗ ]
Pane · Token Range Monitor 1.4.8
No weekly limit reported. ╭──────────────────────────────────────────────────────────╮ │ 5-hour window Lasts to the reset │ │ 31% ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │ │ resets NaN:NaN │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ Models [ 5h ] [ Week ] │ │ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │ │ Not recorded 31% │ │ Details │ ╰──────────────────────────────────────────────────────────╯ Click here to enable sync between devices
Pane · token-range-monitor-sync
Sync across devices Your usage history, shared between the computers you sign in on. Usage figures only: never prompts or code. Sync across devices · [ Sign in ]
README

Token Range Monitor

Like an electric car's range display, for your Claude limits: will your current pace carry you to the next reset?

  • Watches the weekly and 5-hour limits of a Claude Pro or Max subscription.
  • Projects what will be left of each when it resets, at the pace you've been going.

<img src="docs/pane.png" alt="The Token Range Monitor pane: this week's projection and its days, today against its budget, the 5-hour window, and where usage went by model" width="460">

Install

Claude Code CLI

Inside claude in a terminal, run:

/plugin install token-range-monitor --marketplace micke-dahlgren/token-range-monitor
  • Answer y, then pick the user scope so it runs in every session.
  • It's active right away.

Claude desktop app (Code tab)

/plugin install isn't available in the app. Run these in any terminal instead:

claude plugin marketplace add micke-dahlgren/token-range-monitor
claude plugin install token-range-monitor@token-range-monitor
  • Then run /reload-plugins in your Code tab session, or start a new one.
  • This installs for your user, so it also runs in the CLI.

Update

claude plugin update token-range-monitor

Then /reload-plugins, or start a new session.

What it shows

Above the prompt

<img src="docs/band.png" alt="The line above the prompt: Week ~25% left at reset, in 2d 20h · 5h ~76% left at 17:30 · Details" width="600">

  • Week: what's projected to be left at the reset, in green: ~6% left at reset. A forecast, not what's left now.
  • Won't make it? In orange, when you'd run out: runs out Wed ~12:45, 22h early.
  • ±N shows when the projection has typically missed by more than 5 points.
  • early shows until a whole day is on record.
  • 5h: cut off ~00:09 in orange, or ~55% left at 15:40 in green.
  • Narrow terminal: shortens to Week ~6% @reset 4d 13h · 5h out 00:09.
  • Details opens the pane.

The pane

Open it with /token-range, or Details above the prompt.

  • This week: what's left at the reset, the week as one bar, and your usage day by day against a daily budget.
  • Today: whether you'll stay within today's budget at this pace.
  • 5-hour window: when you'd be cut off, or that you'll last to the reset.
  • Models: your usage split by model and effort level, with each model's token cost.

How the estimate works

  • Each response reports every limit's % and reset time; the mod records them.
  • Pace = the average of your last 7 whole days.
  • Left at reset = 100% − (used now + the rest of today + your pace for each day left).
  • Your weekly rhythm: after 14 days the mod looks at the usual use on that weekday to make better predictions.
  • Daily budget = what was left at the start of today ÷ the days left.
  • Just installed: until a whole day is on record, a simpler hourly estimate is used, tagged early.
  • 5-hour cut-off = now + what's left ÷ your rate since the window opened.

Model costs

  • Each response reports its model, effort and tokens.
  • Every limit rise is shared among the responses behind it, weighed by token cost.
  • Each model starts at its published list price and learns from your use over the last 14 days.

Sync across devices

Off until you sign in. Without it, each computer only sees its own usage; the rest shows up as "used while away".

Sign in

  1. At the bottom of the pane, press Click here to enable sync between devices.
  2. Open the link shown and type the code from the pane (e.g. ABCD-EFGH).
  3. Choose Continue with Google or Continue with GitHub.
  4. Repeat on each device with the same account.

Only type a code your own Claude Code showed you, never one someone sent you.

What's sent

  • Limit percentages and reset times.
  • When your sessions were active.
  • Per response: time, model, effort and token counts.
  • This computer's name, to list your devices.
  • Never prompts, replies, code, file names or project names.
  • Account and organization ids are stored only as a keyed hash.

Where and how long

  • A small Cloudflare server: privacy policy.
  • Each day's data is deleted 15 days after its last update.
  • A device unused for 90 days is signed out and removed.

Manage it in ⚙ Settings:

  • See your linked devices; Remove one you don't recognize.
  • Sign out unlinks this device.
  • Delete synced data removes everything on the server.
  • CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC turns sync off.

Host your own: see server/, then set the plugin's Sync server option.

Good to know

  • Pro and Max only. API-key usage has no subscription limits.
  • History starts at install, recorded while a Claude Code session is open.
  • Usage elsewhere (claude.ai, other devices) shows as a jump, unless you sync.
  • Kept: the last 15 days, and daily totals for 8 weeks.
  • One history per Claude account.
  • Local only unless you sync.
  • Early-access mod API: a Claude Code update may break it until the mod is updated.

Development

Run it from this folder without installing:

claude --plugin-dir .

Check and test it:

claude plugin validate .
claude plugin test .

License

MIT

Source 9 files
hooks/register.tsx 1161 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit } from 'claude-code'
3
4import type { RangeCheck, RangeDay, RangeReading, RangeSettings, RangeStep, RangeSync, RangeWatch } from '../types'
5import {
6  DEFAULT_SETTINGS, KEEP, MIN, heartbeat, MIN_RECORDED_H, UNIT_MAX, UNIT_MIN, averageName, clampWindow, averageNote, chosenAverage,
7  drawingHeight, emptyChartSvg, emptyChartText, fit, fiveChart, LAST_INFO, LAST_LABEL, lastIsShort, lastWindow, lastWindowNote, lastWindowText, merge, parseWindow, project, rateText, recordedHours, resetsIn,
8  C, dur, HOUR, isShort, leftText, paceText, rangeTrack, rateShort, refine, runsOut, weekChart, windowHours, isStale, ofKind, DAY,
9} from './range'
10import type { Average, LastWindow, Model, TrackSeg, TrackTone } from './range'
11import { DEFAULT_PALETTES, historyPalettes, palettesFor, resolveTheme } from './theme'
12import { dailyTotals, selfCheck, typicalMiss, weekPlan } from './pace'
13import type { WeekPlan } from './pace'
14import {
15  cutOff, DAYS_MIN, dayEndText, daysHeight, overBudgetAt, dayName, daysText, dayTime, hm, fiveCardSvg, fiveHead, fivePart, mastheadSvg, oldFigures, one, partsWidth, pastDays,
16  showsToday, toCome, todaySvg, todayText, weekBarLabels, weekCardSvg, weekHead, weekHeadline, weekLegendSvg, weekPart,
17} from './cards'
18import type { Run } from './ui'
19import { baselineOf, costRows, learn, mergeSteps, MODELS_INFO, modelsHead, modelsUsage, shortNames, shownEffort, splitText, units, usageSplit } from './models'
20import type { UsageSplit } from './models'
21import {
22  agoText, cancelSignIn, cleanName, configureSync, DEVICE_KEY, DEVICES_FRESH, deleteSynced, deviceLabel, downloadedFor, endSync, GENERIC_NAMES, isDeviceId,
23  NAME_KEY, platformOf, refreshDevices, removeDevice, signIn, signOut, startSync, syncTick,
24} from './sync'
25import type { Lists, Platform, SyncIO } from './sync'
26
27const PANE = 'token-range-monitor'
28/** The mod's version, shown in the pane's title: keep it in step with `.claude-plugin/plugin.json`. */
29const VERSION = '1.4.8'
30const TITLE = `Token Range Monitor ${VERSION}`
31const readings = atom({ plugin: 'token-range-monitor', key: 'readings' } as const, [])
32const settings = atom({ plugin: 'token-range-monitor', key: 'settings' } as const, DEFAULT_SETTINGS)
33const tick = atom({ plugin: 'token-range-monitor', key: 'tick' } as const, 0)
34const seen = atom({ plugin: 'token-range-monitor', key: 'seen' } as const, [])
35const palettes = atom({ plugin: 'token-range-monitor', key: 'palettes' } as const, DEFAULT_PALETTES)
36const steps = atom({ plugin: 'token-range-monitor', key: 'steps' } as const, [])
37/** Each whole day's use, kept 8 weeks, and the weekly projection's self-check (see ./pace). */
38const days = atom({ plugin: 'token-range-monitor', key: 'days' } as const, [] as RangeDay[])
39const check = atom({ plugin: 'token-range-monitor', key: 'check' } as const, [] as RangeCheck[])
40/**
41 * How much larger the drawings are shown than they're laid out: 1, so their type is the design's own sizes
42 * (28, 16 and 13 px) at the card's width.
43 */
44const ZOOM = 1
45/** The strip under a card, and what its Details opens: a shade darker than the card, whatever colour the app gives it. */
46const INSET = '#00000017'
47/**
48 * A drawing as a plain image: the drawings are made for a frame (a wide canvas, filled to the frame's width), so as
49 * an image each gets a viewBox the width it was laid out for, `layout`, shown ZOOM times larger; it scales evenly to
50 * whatever width it's shown at.
51 */
52const asImage = (svg: string, layout: number) =>
53  svg.replace(/^<svg ([^>]*?)width="\d+" height="(\d+)">/, (_, attrs: string, h: string) =>
54    `<svg ${attrs}width="${Math.round(layout * ZOOM)}" height="${Math.round(Number(h) * ZOOM)}" viewBox="0 0 ${Math.round(layout)} ${h}" preserveAspectRatio="xMidYMin meet">`)
55/**
56 * The desktop's sizes for fitting the cards to the pane, measured in the app: a row of the pane's reported
57 * `bodyRows` in px, a row of the cards' own padding, margins and gaps in px (drawn smaller than a text row), and
58 * px kept spare under the cards so a small miss in the estimate doesn't scroll.
59 */
60const FIT_PX = { row: 21, native: 13, spare: 8 }
61/** Which cards' Details blocks are open: `week`, `five`, `models`. */
62const details = atom({ plugin: 'token-range-monitor', key: 'details' } as const, [] as string[])
63/** What the pane's sync row shows; sync itself (./sync) keeps it through syncIO. */
64const syncView = atom({ plugin: 'token-range-monitor', key: 'sync' } as const, { status: 'signedOut' } as RangeSync)
65
66/**
67 * Usage limits are the account's, so the record is too: everything is stored
68 * under the signed-in account (`<account>/`), and signing in to another
69 * account starts from that account's own record. Within it each session
70 * writes its readings under its own key (`r:`), and the spans it was watching
71 * under the twin key (`w:`), so sessions never overwrite each other, and every
72 * session reads them all. The responses it saw, each one's model and tokens,
73 * go under a third (`u:`).
74 */
75let account = ''
76const OWN = 'r:'
77const SEEN = 'w:'
78const STEPS = 'u:'
79const ownPrefix = () => `${account}/${OWN}`
80const seenKeyOf = (key: string) => key.replace(`/${OWN}`, `/${SEEN}`)
81const stepsKeyOf = (key: string) => key.replace(`/${OWN}`, `/${STEPS}`)
82const newOwnKey = (now: number) => `${ownPrefix()}${now.toString(36)}-${Math.floor(Math.random() * 1e6).toString(36)}`
83/** A stored list's key: whose (none for a record kept before accounts), and which kind. */
84const parseKey = (key: string) => /^(?:(.+)\/)?([rwu]):/.exec(key)
85
86let ownKey = ''
87let own: RangeReading[] = []
88let ownSeen: RangeWatch[] = []
89let othersSeen: RangeWatch[] = []
90let ownSteps: RangeStep[] = []
91let othersSteps: RangeStep[] = []
92
93/** The home folder: HOME, or on Windows, where the desktop app often leaves HOME unset, USERPROFILE. */
94async function homeOf($: EngineInterface): Promise<string> {
95  return (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
96}
97
98/**
99 * The signed-in account and organisation, from Claude Code's own config:
100 * the limits belong to both. `none` off a subscription, which has no limits.
101 */
102let accountRead: { mtime: number; account: string } | undefined
103async function accountOf($: EngineInterface): Promise<string | null> {
104  try {
105    const dir = await $.env.get('CLAUDE_CONFIG_DIR')
106    const file = dir ? `${dir}/.claude.json` : `${await homeOf($)}/.claude.json`
107    // the file is read again only once it changed
108    const { mtimeMs } = await $.fs.stat(file)
109    if (accountRead?.mtime === mtimeMs) return accountRead.account
110    const o = (JSON.parse(await $.fs.read(file)) as { oauthAccount?: { accountUuid?: string; organizationUuid?: string } }).oauthAccount
111    const a = o?.accountUuid ? `${o.accountUuid}.${o.organizationUuid ?? ''}` : 'none'
112    accountRead = { mtime: mtimeMs, account: a }
113    return a
114  } catch {
115    // unreadable (mid-write, say): no answer, which is no sign-in elsewhere
116    return null
117  }
118}
119
120/** Follows a sign-in to another account: this session starts a fresh list under it. True when it moved. */
121async function followAccount($: EngineInterface): Promise<boolean> {
122  const now = await $.clock.now()
123  const a = (await accountOf($)) ?? (account || 'none')
124  if (a === account) return false
125  account = a
126  ownKey = newOwnKey(now)
127  own = []
128  ownSeen = []
129  ownSteps = []
130  return true
131}
132
133/**
134 * Claude Code keeps a store per copy of a plugin: one installed from the
135 * marketplace and one run from a folder don't share. Every copy's store sits
136 * in the same folder, so each copy also reads the others' (never writes them),
137 * and sessions running different copies still see each other's usage.
138 */
139async function otherCopies($: EngineInterface): Promise<Array<[string, unknown]>> {
140  try {
141    const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${await homeOf($)}/.claude`
142    const stores = `${dir}/plugins/store`
143    const out: Array<[string, unknown]> = []
144    for (const f of await $.fs.list(stores)) {
145      if (!/^token-range-monitor_.*\.json$/.test(f.name)) continue
146      // a file being written as it's read is skipped this time, the others still count
147      try {
148        out.push(...Object.entries(JSON.parse(await $.fs.read(`${stores}/${f.name}`)) as Record<string, unknown>))
149      } catch { /* next minute */ }
150    }
151    return out
152  } catch {
153    return []
154  }
155}
156
157/**
158 * Every list recorded on this computer for the signed-in account: this
159 * session's, the other sessions', the other copies'. Lists other devices
160 * synced are not among them (they are kept under `sync:` keys).
161 */
162async function localLists($: EngineInterface, now: number) {
163  const lists: RangeReading[][] = [own]
164  const spans: RangeWatch[] = []
165  const stepLists: RangeStep[][] = []
166  // the other copies' lists, read as they stand; this copy's own file is among them, and merging drops the repeats
167  for (const [key, value] of await otherCopies($)) {
168    const k = parseKey(key)
169    // a record kept under none was this account's too (see below)
170    if (!k || !Array.isArray(value) || (k[1] !== undefined && k[1] !== account && !(k[1] === 'none' && account !== 'none'))) continue
171    if (k[2] === 'w') spans.push(...(value as RangeWatch[]))
172    else if (k[2] === 'u') stepLists.push(value as RangeStep[])
173    else lists.push(value as RangeReading[])
174  }
175  for (const key of await $.store.keys()) {
176    const k = parseKey(key)
177    if (!k || key === ownKey || key === seenKeyOf(ownKey) || key === stepsKeyOf(ownKey)) continue
178    const [, whose, kind] = k
179    const list = ((await $.store.get(key)) ?? []) as Array<RangeReading | RangeWatch | RangeStep>
180    // drop lists once everything in them has aged out, whichever account's
181    const end = (x: RangeReading | RangeWatch | RangeStep) => (kind === 'w' ? (x as RangeWatch)[1] : x[0])
182    if (list.every(x => end(x) < now - KEEP)) { await $.store.delete(key); continue }
183    if (whose === undefined) {
184      // a record kept before accounts: it was this account's, so it moves under it
185      await $.store.set(`${account}/${key}`, list)
186      await $.store.delete(key)
187    } else if (whose === 'none' && account && account !== 'none') {
188      // kept while the account couldn't be read (HOME unset, as on Windows): only a subscription reports
189      // limits, so the record was this account's all along, and it moves under it
190      await $.store.set(`${account}/${key.slice('none/'.length)}`, list)
191      await $.store.delete(key)
192    } else if (whose !== account) continue
193    if (kind === 'w') spans.push(...(list as RangeWatch[]))
194    else if (kind === 'u') stepLists.push(list as RangeStep[])
195    else lists.push(list as RangeReading[])
196  }
197  return { lists, spans, stepLists }
198}
199
200/** What this computer recorded, this session's unsaved part included: what sync uploads. */
201async function collectLocal($: EngineInterface): Promise<Lists> {
202  const { lists, spans, stepLists } = await localLists($, await $.clock.now())
203  return { readings: lists, spans: [...spans, ...ownSeen], steps: [...stepLists, ownSteps] }
204}
205
206/** A device id another copy's store already holds, so every copy on this computer syncs as one device. */
207async function peekDevice($: EngineInterface): Promise<string | undefined> {
208  for (const [key, value] of await otherCopies($)) if (key === DEVICE_KEY && isDeviceId(value)) return value
209  return undefined
210}
211
212/**
213 * The computer's own name, for the server's device list: the environment's
214 * (COMPUTERNAME on Windows, HOSTNAME where the shell exports it), else a host
215 * command's where one can run (`scutil --get ComputerName` on macOS, `hostname`
216 * elsewhere; CLI only, kept in the store for sessions that can't run one),
217 * else a generic name for the platform ("Mac", "Windows PC", "Linux computer").
218 */
219async function hostName($: EngineInterface): Promise<string> {
220  const fromEnv = cleanName(await $.env.get('COMPUTERNAME').catch(() => undefined)) ?? cleanName(await $.env.get('HOSTNAME').catch(() => undefined))
221  if (fromEnv) return fromEnv
222  const platform = platformOf({
223    os: await $.env.get('OS').catch(() => undefined),
224    cfEncoding: await $.env.get('__CF_USER_TEXT_ENCODING').catch(() => undefined),
225    home: await $.env.get('HOME').catch(() => undefined),
226  })
227  const found = await commandName($, platform)
228  if (found) {
229    await $.store.set(NAME_KEY, found).catch(() => undefined)
230    return found
231  }
232  return cleanName(await $.store.get(NAME_KEY).catch(() => undefined)) ?? GENERIC_NAMES[platform]
233}
234
235/** The name a host command prints, or null: no command runs here (the desktop), it failed, or it took over 3 s. */
236async function commandName($: EngineInterface, platform: Platform): Promise<string | null> {
237  if (platform === 'windows') return null
238  try {
239    const r = await $.process.run(platform === 'mac' ? ['scutil', '--get', 'ComputerName'] : ['hostname'], { timeoutMs: 3_000 })
240    return r.exitCode === 0 ? cleanName(r.stdout.split('\n')[0]) : null
241  } catch {
242    return null
243  }
244}
245
246/** The sync pane's own: what sync is doing, sign out, delete, and the linked devices, each removable. */
247const SYNC_PANE = 'token-range-monitor-sync'
248const SYNC_TITLE = 'Sync settings'
249
250/** Opens the sync settings, and asks for the device list if it wasn't asked for just now. */
251async function openSyncPane($: EngineInterface) {
252  await $.ui.open({ id: SYNC_PANE, title: SYNC_TITLE })
253  void refreshDevices(syncIO($), DEVICES_FRESH).catch(() => undefined)
254}
255
256type Els = ReturnType<EngineInterface['ui']['resolve']>
257
258/** Every sync control: the settings pane draws it, and the main pane while a sign-in waits. */
259function syncPanel($: EngineInterface, els: Els, v: RangeSync, clockNow: number) {
260  const { Box, Text, Button, Link } = els
261    return (
262      <Box key="sync" flexDirection="column" gap={1} marginTop={1}>
263        {/* the row's parts as one flat list: a fragment here is drawn as a column of its own on the desktop */}
264        <Box flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={1} rowGap={1}>
265          {v.status === 'signedIn'
266            ? [
267                <Text key="who" color="inactive">{`Synced as ${v.email || 'you'} · last sync ${agoText(v.last, clockNow)} ·`}</Text>,
268                <Button key="sync-signout" label="Sign out" dimColor={!!v.busy} onPress={() => void signOut(syncIO($))} />,
269                <Button key="sync-delete" label={v.confirmDelete ? 'Press again to delete all synced data' : 'Delete synced data'}
270                  variant={v.confirmDelete ? 'primary' : 'secondary'} dimColor={!!v.busy} onPress={() => void deleteSynced(syncIO($))} />,
271              ]
272            : v.status === 'waiting'
273              ? [
274                  <Text key="waiting" color="inactive">{`Waiting for sign-in… code ${v.code ?? ''} ·`}</Text>,
275                  <Button key="sync-cancel" label="Cancel" onPress={() => void cancelSignIn(syncIO($))} />,
276                ]
277              : [
278                  <Text key="title" color="inactive">{v.status === 'off' ? 'Sync across devices · off' : 'Sync across devices ·'}</Text>,
279                  ...(v.status === 'off' ? [] : [<Button key="sync-signin" label="Sign in" dimColor={!!v.busy} onPress={() => void signIn(syncIO($))} />]),
280                ]}
281        </Box>
282        {/* the devices signed in to this account, this one first: any other one can be removed */}
283        {v.status === 'signedIn' && v.devices && v.devices.length > 0 && (
284          <Box key="devices" flexDirection="column">
285            <Text key="devices-title" color="inactive">Linked devices</Text>
286            {v.devices.map(d => (
287              <Box key={`device-${d.id}`} flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={1}>
288                {d.current
289                  ? [<Text key="name">{`${deviceLabel(d)} · this device`}</Text>]
290                  : [
291                      <Text key="name">{`${deviceLabel(d)} · last seen ${d.lastSeenAt === undefined ? 'never' : agoText(d.lastSeenAt, clockNow)} ·`}</Text>,
292                      <Button key={`sync-remove-${d.id}`}
293                        label={v.confirmRemove === d.id ? `Press again to remove ${deviceLabel(d)} and its synced data` : 'Remove'}
294                        variant={v.confirmRemove === d.id ? 'primary' : 'secondary'} dimColor={!!v.busy}
295                        onPress={() => void removeDevice(syncIO($), d.id)} />,
296                    ]}
297              </Box>
298            ))}
299          </Box>
300        )}
301        {/* the page to sign in on, where the code is typed: as a link, and as text to copy */}
302        {v.status === 'waiting' && v.url && (
303          <Box flexDirection="column">
304            {/* the link inside a Text, as the inline element it is; the address again as plain text to copy */}
305            <Text>Open <Link href={v.url} label="the sign-in page" /> and enter the code {v.code ?? 'shown above'}.</Text>
306            <Text dimColor>{v.url}</Text>
307          </Box>
308        )}
309        {v.note && <Text dimColor>{v.note}</Text>}
310      </Box>
311    )
312}
313
314/**
315 * The main pane's sync line: one quiet line, the rest in the settings pane. Signed out, a text button to turn
316 * sync on; signing in, the code and the page (it's needed right there); signed in, when it last synced and a cog.
317 */
318function syncLine($: EngineInterface, els: Els, v: RangeSync, clockNow: number) {
319  const { Box, Text, Button } = els
320  if (v.status === 'off') return null
321  if (v.status === 'waiting') return syncPanel($, els, v, clockNow)
322  return (
323    <Box key="sync" flexDirection="column" marginTop={1}>
324      <Box flexDirection="row" flexWrap="wrap" justifyContent="space-between" alignItems="center" columnGap={1}>
325        {v.status === 'signedIn'
326          ? [
327              <Box key="who" flexDirection="row" flexWrap="wrap" columnGap={1}>
328                <Text color="claude">•</Text>
329                <Text color="inactive">{`Synced across devices · last sync ${agoText(v.last, clockNow)}`}</Text>
330              </Box>,
331              <Button key="sync-settings" plain dimColor label="⚙ Settings" onPress={() => void openSyncPane($)} />,
332            ]
333          : [<Button key="sync-enable" plain label="Click here to enable sync between devices" dimColor
334              onPress={() => void signIn(syncIO($))} />]}
335      </Box>
336      {v.note && <Text dimColor>{v.note}</Text>}
337    </Box>
338  )
339}
340
341/** Opens the pane, and asks for the device list if it wasn't asked for just now. */
342async function openPane($: EngineInterface) {
343  await $.ui.open({ id: PANE, title: TITLE })
344  void refreshDevices(syncIO($), DEVICES_FRESH).catch(() => undefined)
345}
346
347/** What sync reaches through the engine: every call on `$` spelled here, in the hooks module. */
348function syncIO($: EngineInterface): SyncIO {
349  return {
350    now: () => $.clock.now(),
351    fetch: (url, init) => $.http.fetch(url, init),
352    get: key => $.store.get(key),
353    set: (key, value) => $.store.set(key, value),
354    del: key => $.store.delete(key),
355    keys: () => $.store.keys(),
356    trafficOff: () => $.env.get('CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'),
357    hostName: () => hostName($),
358    every: (ms, fn) => $.clock.every(ms, fn),
359    after: (ms, fn) => $.clock.after(ms, fn),
360    log: (text, options) => $.ui.log(text, options),
361    view: () => read($, syncView),
362    setView: async change => { await update($, syncView, change) },
363    account: () => account,
364    collect: () => collectLocal($),
365    reload: () => loadAll($),
366    peekDevice: () => peekDevice($),
367  }
368}
369
370async function loadAll($: EngineInterface) {
371  const now = await $.clock.now()
372  const { lists, spans, stepLists } = await localLists($, now)
373  // the other devices' lists, as synced: read beside this computer's, merging drops the repeats
374  const far = await downloadedFor(syncIO($), account)
375  lists.push(...(far.readings as RangeReading[][]))
376  spans.push(...far.spans)
377  stepLists.push(...(far.steps as RangeStep[][]))
378  othersSeen = spans
379  othersSteps = mergeSteps(stepLists, now)
380  await update($, steps, () => mergeSteps([othersSteps, ownSteps], now))
381  await update($, readings, () => merge(lists, now))
382  await update($, seen, () => [...othersSeen, ...ownSeen])
383}
384
385/**
386 * Notes that this session just got fresh figures (a response arrived), for telling
387 * usage seen here from usage made elsewhere. Saved at most every 30 seconds.
388 */
389let seenSavedAt = 0
390let seenShownAt = 0
391async function watch($: EngineInterface) {
392  const now = await $.clock.now()
393  if (!ownKey) ownKey = newOwnKey(now)
394  const before = ownSeen.length
395  ownSeen = heartbeat(ownSeen, now)
396  if (ownSeen.length !== before || now - seenSavedAt > 30_000) {
397    seenSavedAt = now
398    await $.store.set(seenKeyOf(ownKey), ownSeen)
399  }
400  // a redraw for a new span, else at most every 30 seconds: each response would redraw the pane otherwise
401  if (ownSeen.length !== before || now - seenShownAt >= 30_000) {
402    seenShownAt = now
403    await update($, seen, () => [...othersSeen, ...ownSeen])
404  }
405}
406
407/** Notes one response: its model, effort and weighted tokens. Saved at most every 30 seconds. */
408let stepsSavedAt = 0
409let stepsShownAt = 0
410let stepsUnsaved = false
411async function record($: EngineInterface, step: RangeStep) {
412  const now = step[0]
413  if (!ownKey) ownKey = newOwnKey(now)
414  ownSteps = [...ownSteps.filter(s => s[0] >= now - KEEP), step]
415  stepsUnsaved = true
416  if (now - stepsSavedAt > 30_000) await saveSteps($, now)
417  // the models card follows at most every 30 seconds, not on every response: the minute's loadAll catches up the rest
418  if (now - stepsShownAt >= 30_000) {
419    stepsShownAt = now
420    await update($, steps, () => mergeSteps([othersSteps, ownSteps], now))
421  }
422}
423async function saveSteps($: EngineInterface, now: number) {
424  if (!stepsUnsaved || !ownKey) return
425  stepsSavedAt = now
426  stepsUnsaved = false
427  await $.store.set(stepsKeyOf(ownKey), ownSteps)
428}
429
430/**
431 * Keeps the daily totals and the self-check under the account (`<account>/days`, `<account>/check`): the
432 * readings are kept 15 days, so the weekday profile's 8 weeks and the last 4 windows' self-check are kept
433 * here, each built from the merged readings, the other devices' included. Saved only when they change.
434 */
435const daysKey = () => `${account}/days`
436const checkKey = () => `${account}/check`
437async function keepDays($: EngineInterface) {
438  const now = await $.clock.now()
439  const list = await read($, readings), watched = await read($, seen)
440  const totals = dailyTotals(list, watched, now, ((await $.store.get(daysKey())) ?? []) as RangeDay[])
441  const before = ((await $.store.get(checkKey())) ?? []) as RangeCheck[]
442  const next = selfCheck(before, list, watched, totals, now)
443  if (JSON.stringify(totals) !== JSON.stringify(await read($, days))) {
444    await $.store.set(daysKey(), totals)
445    await update($, days, () => totals)
446  }
447  if (JSON.stringify(next) !== JSON.stringify(before)) await $.store.set(checkKey(), next)
448  if (JSON.stringify(next) !== JSON.stringify(await read($, check))) await update($, check, () => next)
449}
450
451async function capture($: EngineInterface, limits: readonly SessionRateLimit[]) {
452  // figures from another account mean a sign-in since: read that account's record first
453  if (await followAccount($)) await loadAll($)
454  const now = await $.clock.now()
455  const known = await read($, readings)
456  const fresh: RangeReading[] = []
457  for (const rl of limits) {
458    const kind = rl.kind === 'five_hour' ? 0 : rl.kind === 'seven_day' ? 1 : -1
459    if (kind === -1 || !rl.resetsAt) continue
460    const resetsAt = Date.parse(rl.resetsAt)
461    const r: RangeReading = [now, kind, rl.percentUsed, resetsAt]
462    // this session's figures may be older than another's: only a new one is recorded
463    const last = ofKind(known, kind === 0 ? 'five' : 'week').at(-1)
464    if (!isStale(r, last) && (!last || last[2] !== r[2] || Math.abs(last[3] - r[3]) > 5 * MIN)) fresh.push(r)
465  }
466  if (fresh.length === 0) return
467  if (!ownKey) ownKey = newOwnKey(now)
468  own = merge([own, fresh], now)
469  await $.store.set(ownKey, own)
470  await update($, readings, list => merge([list, fresh], now))
471}
472
473/**
474 * Reads the person's theme and derives the card's palettes from it. A custom
475 * theme (`custom:<slug>`) is the person's own file or one a plugin ships.
476 */
477let themeFile: { slug: string; path: string } | undefined
478async function loadTheme($: EngineInterface) {
479  const setting = ((await $.settings.read()) as { theme?: unknown }).theme
480  const dir = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${await homeOf($)}/.claude`
481  const theme = await resolveTheme(setting, async slug => {
482    // found once, then read where it was; searched again only if it's gone
483    if (themeFile?.slug === slug && await $.fs.exists(themeFile.path)) return await $.fs.read(themeFile.path)
484    const own = `${dir}/themes/${slug}.json`
485    if (await $.fs.exists(own)) { themeFile = { slug, path: own }; return await $.fs.read(own) }
486    // plugins are cached as cache/<marketplace>/<plugin>/<version>/
487    const cache = `${dir}/plugins/cache`
488    for (const m of await $.fs.list(cache).catch(() => [])) {
489      for (const pl of await $.fs.list(`${cache}/${m.name}`).catch(() => [])) {
490        for (const ver of await $.fs.list(`${cache}/${m.name}/${pl.name}`).catch(() => [])) {
491          const file = `${cache}/${m.name}/${pl.name}/${ver.name}/themes/${slug}.json`
492          if (await $.fs.exists(file)) { themeFile = { slug, path: file }; return await $.fs.read(file) }
493        }
494      }
495    }
496    return undefined
497  })
498  const next = palettesFor(theme)
499  if (JSON.stringify(next) !== JSON.stringify(await read($, palettes))) await update($, palettes, () => next)
500}
501
502async function models($: EngineInterface) {
503  const list = await read($, readings)
504  const watched = await read($, seen)
505  const s = await read($, settings)
506  const pal = await read($, palettes)
507  await read($, tick)
508  // the drawings' time, up to the next whole minute: a redraw with nothing new (a scroll, a response, the minute's tick)
509  // then draws the very same drawings, which the surface keeps instead of loading them again (that flashed)
510  const now = Math.ceil((await $.clock.now()) / MIN) * MIN
511  const weekRecorded = recordedHours(list, 'week', now)
512  const weekAvg = chosenAverage(s)
513  // the 5-hour average runs from the window's opening: Anthropic's own figure, and the chart shows the whole window
514  const fiveAvg: Average = { type: 'reset' }
515  const stepList = await read($, steps)
516  const learned = learn(list, stepList, watched, now)
517  const projected = project(list, 'week', now, weekAvg, watched)
518  // the bars follow the responses behind each rise, each weighed by its model's cost where that's known
519  const shown = learned.models.filter(m => m.shown)
520  const usual = shown.length ? shown.reduce((a, m) => a + m.w, 0) / shown.length : 1
521  const weightOf = new Map(learned.models.map(m => [m.id, m.shown ? m.w : usual]))
522  const work = stepList.map(st => [st[0], st[3] * (weightOf.get(st[1]) ?? usual)] as const)
523  const shaped = (m: Model | null) => (m ? { ...m, increments: refine(m.increments, work) } : null)
524  const week = shaped(projected)
525  // 1.4's weekly projection: the last 7 whole days, today at no less than its expected use
526  const totals = dailyTotals(list, watched, now, await read($, days))
527  const plan = weekPlan(list, watched, totals, now, typicalMiss(await read($, check)))
528  const five = shaped(project(list, 'five', now, fiveAvg, watched))
529  // each limit's window by model and effort, each response weighed as the bars weigh it
530  const weigh = (id: string) => weightOf.get(id) ?? usual
531  const splits = {
532    five: five ? usageSplit(five, list, stepList, watched, weigh, now) : null,
533    week: projected ? usageSplit(projected, list, stepList, watched, weigh, now) : null,
534  }
535  return {
536    now, s, weekRecorded, pal, week, plan, totals, five, splits,
537    // how each limit's previous window ended, where the record can tell
538    lastWeek: lastWindow(list, 'week', now, watched),
539    lastFive: lastWindow(list, 'five', now, watched),
540    learned,
541    steps: stepList,
542  }
543}
544
545async function choose($: EngineInterface, change: Partial<RangeSettings>) {
546  await update($, settings, s => ({ ...s, ...change }))
547  await $.store.set('settings', await read($, settings))
548}
549
550/** Sets the weekly window: any length, one that can't give an estimate yet saying so in the chart's place. */
551async function setWindow($: EngineInterface, n: number, unit: 'h' | 'd') {
552  await choose($, { mode: 'window', n: clampWindow(n, unit), unit })
553}
554
555export const register: Register = (on, options) => {
556  configureSync(options.syncServer)
557
558  on('session.start', async ($, e, next) => {
559    account = ''
560    await followAccount($)
561    const saved = (await $.store.get('settings')) as RangeSettings | undefined
562    // a saved "everything recorded" (now retired) becomes the custom window it sat beside
563    if (saved) await update($, settings, () => ({ ...DEFAULT_SETTINGS, ...saved, mode: saved.mode === 'reset' ? 'reset' : 'window' }))
564    await $.command.register({
565      name: 'token-range',
566      description: 'Token Range Monitor: open the pane, or set what the weekly average covers (/token-range 2d, /token-range 6h, /token-range reset)',
567      argumentHint: '[window | reset]',
568    })
569    await startSync(syncIO($))
570    await loadAll($)
571    // a theme that can't be read leaves the card's default colours, never the rest of the start
572    await loadTheme($).catch(() => undefined)
573    await capture($, (await $.session.usage()).rateLimits)
574    await keepDays($).catch(() => undefined)
575    // the first sync waits for the session to be under way: nothing on the network holds up its start
576    $.clock.after(1_000, () => void syncTick(syncIO($), true))
577    // once a minute: pick up other sessions' readings and move "now" along; sync when it's due
578    $.clock.every(60_000, async () => {
579      await saveSteps($, await $.clock.now())
580      const moved = await followAccount($)
581      await loadAll($)
582      await loadTheme($).catch(() => undefined)   // picks up a theme file edited in place
583      await capture($, (await $.session.usage()).rateLimits)
584      await keepDays($).catch(() => undefined)
585      await update($, tick, n => n + 1)
586      // another account's record syncs at once
587      await syncTick(syncIO($), moved)
588    })
589    return next(e)
590  })
591
592  // at the end, the responses not yet saved are, and sync uploads once more
593  on('session.end', async ($, e, next) => {
594    try {
595      await saveSteps($, await $.clock.now())
596      await endSync(syncIO($))
597    } catch { /* never in the way of the exit */ }
598    return next(e)
599  })
600
601  // a turn's end and each tool call both follow a response, so the figures are fresh then;
602  // the once-a-minute check above only re-reads the last response's figures, so it isn't watching
603  on('session.measure', async ($, e, next) => {
604    if (e.changed.includes('rateLimits')) await capture($, e.rateLimits)
605    await watch($)
606    return next(e)
607  })
608
609  // a theme switched from /theme, the menu or another plugin redraws the card at once
610  on('config.set', { key: 'theme' }, async ($, e, next) => {
611    const result = await next(e)
612    await loadTheme($)
613    return result
614  }).catch(($, e, next) => next(e))   // never stands in the way of the theme change itself
615
616  // every model response, main and subagents': its model, effort and tokens, for learning what each model costs
617  on('turn.step', async function* ($, e, next) {
618    const r = yield* next(e)
619    try {
620      if (r?.usage) await record($, [await $.clock.now(), r.usage.model || e.model, e.effort === undefined ? '' : String(e.effort), units(r.usage), e.agentId ? 1 : 0])
621    } catch { /* never in the way of the response */ }
622    return r
623  })
624
625  on('tool.call', async ($, e, next) => {
626    await watch($)
627    return next(e)
628  })
629
630  on('command.run', { command: 'token-range' }, async ($, e) => {
631    const arg = e.args.trim().toLowerCase()
632    await openPane($)
633    if (!arg) return { text: 'Token Range Monitor opened.' }
634    if (arg === 'reset' || arg === 'since reset') {
635      await choose($, { mode: 'reset' })
636      return { text: 'Weekly average now covers the time since the reset.' }
637    }
638    const w = parseWindow(arg)
639    if (!w) return { text: `Couldn't read "${arg}". Use a window like 6h or 2d (at most 7d), or "reset".` }
640    await setWindow($, w.unit === 'h' ? w.n : w.n * (w.unit === 'w' ? 7 : 1), w.unit === 'h' ? 'h' : 'd')
641    // held to what's on offer: under 6 hours becomes 6
642    const avg: Average = { type: 'hours', hours: windowHours(await read($, settings)) }
643    return { text: `Weekly average now uses the last ${averageName(avg)}.` }
644  })
645
646  // C: one line above the prompt
647  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
648    if (e.props.hasSurvey) return next(e)
649    const { plan, five, now } = await models($)
650    if (!plan && !five) return next(e)
651    const { Box, Text, Button } = $.ui.resolve(e)
652    const partsOf = (short: boolean) => [
653      ...(plan ? [{ key: 'week', part: weekPart(plan, short) }] : []),
654      ...(five ? [{ key: 'five', part: fivePart(five, now, short) }] : []),
655    ]
656    // the full line where it fits, else the short one, so the band stays one line in a narrow column
657    const short = partsWidth(partsOf(false).map(x => x.part)) > e.props.bodyColumns
658    return (
659      <Box flexDirection="row" flexWrap="wrap" columnGap={1} alignItems="center">
660        {partsOf(short).flatMap(({ key, part: p }, i) => {
661          return [
662            ...(i ? [<Text key={`sep-${key}`} dimColor>·</Text>] : []),
663            <Box key={`band-${key}`} flexDirection="row">
664              <Text dimColor>{p.label} </Text>
665              <Text bold dimColor={p.dim} color={p.dim ? undefined : p.spare ? 'success' : 'claude'}>{p.value}</Text>
666              {p.rest && <Text dimColor>{p.rest}</Text>}
667              {p.tag && <Text key={`tag-${key}`} dimColor>{` ${p.tag}`}</Text>}
668            </Box>,
669          ]
670        })}
671        <Button key="details" label="Details ↗" onPress={() => void openPane($)} />
672      </Box>
673    )
674  })
675
676  // the sync settings: their own pane, opened from the main pane's cog
677  on('ui.render', { component: 'Pane', requestId: SYNC_PANE }, async ($, e) => {
678    const els = $.ui.resolve(e)
679    const { Box, Text } = els
680    const v = await read($, syncView)
681    return (
682      <Box flexDirection="column" gap={1}>
683        <Text bold>Sync across devices</Text>
684        <Text dimColor>Your usage history, shared between the computers you sign in on. Usage figures only: never prompts or code.</Text>
685        {syncPanel($, els, v, await $.clock.now())}
686      </Box>
687    )
688  })
689
690  // B: the side pane
691  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
692    const { now, s, week, five, pal, lastWeek, lastFive, weekRecorded, learned, plan, totals, splits } = await models($)
693    const els = $.ui.resolve(e)
694    const { Box, Text, Button } = els
695    const sync = await read($, syncView)
696    // the real time for the sync row's texts: `now` is the drawings', rounded up to the minute
697    const clockNow = await $.clock.now()
698    // the terminal draws no Svg: there the cards are text
699    const Svg = e.surface !== 'terminal' && 'Svg' in els ? els.Svg : null
700    // the drawings are laid out at the card's inner width; the 1.3 charts' heights follow it
701    const size = fit(e.props.bodyColumns)
702    const W = size.width
703    const lastOf = (m: Model) => (m.kind === 'week' ? lastWeek : lastFive)
704    const open = await read($, details)
705    const toggle = (key: string) => void update($, details, l => (l.includes(key) ? l.filter(k => k !== key) : [...l, key]))
706    // the head's figures in words, for a drawing's alt text
707    const figuresText = (m: Model) =>
708      `At reset ${leftText(m)}, your pace ${m.noData ? 'no data' : rateText(m, m.rate)}, safe pace ${rateText(m, m.limit)}.${paceText(m) ? ` ${paceText(m)}` : ''}`
709    const lastAlt = (last: LastWindow | null) => (last ? `${LAST_LABEL} ${lastWindowText(last)}. ${lastWindowNote(last)} ` : '')
710    const gap = Svg ? 1 : 0
711
712    // every drawing a plain image, never interactive: the surface loads an interactive drawing (a sandboxed frame)
713    // again on every redraw, a scroll's too, and that flashed. A plain function, not a component, each drawing keyed;
714    // its height left out, so it follows the drawing's proportions at whatever width it's shown
715    const draw = (key: string, svg: string, alt: string, layout = W) =>
716      Svg ? <Svg key={key} source={asImage(svg, layout)} alt={alt} /> : null
717
718    // the window selector: native widgets, so hover, focus and clicks are the surface's own
719    const unit = s.unit === 'h' ? 'h' : 'd'
720    const n = clampWindow(s.n, unit)
721    const isCustom = s.mode === 'window'
722    const seg = (key: string, label: string, isOn: boolean, onPress: () => void, off = false) => (
723      <Button key={key} label={label} variant={isOn && !off ? 'primary' : 'secondary'} dimColor={!isOn || off} onPress={() => { if (!off) onPress() }} />
724    )
725    // until there's enough recorded for a weekly average, there's nothing to choose between: the choices dim and do nothing
726    const choicesOff = weekRecorded < MIN_RECORDED_H.week
727    const modeButtons = (
728      <Box key="mode" flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={1} rowGap={gap}>
729        {seg('mode-reset', 'Since reset', s.mode === 'reset', () => void choose($, { mode: 'reset' }), choicesOff)}
730        {seg('mode-custom', 'Custom', isCustom, () => void setWindow($, n, unit), choicesOff)}
731      </Box>
732    )
733    const windowRow = isCustom && !choicesOff ? (
734      <Box key="window" flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={1} rowGap={gap}>
735        <Text color="inactive">Last</Text>
736        <Button key="win-dec" label="−" dimColor={n <= UNIT_MIN[unit]} onPress={() => void setWindow($, n - 1, unit)} />
737        <Text bold color="text">{` ${n} `}</Text>
738        <Button key="win-inc" label="+" dimColor={n >= UNIT_MAX[unit]} onPress={() => void setWindow($, n + 1, unit)} />
739        {seg('unit-h', 'hours', unit === 'h', () => void setWindow($, n, 'h'))}
740        {seg('unit-d', 'days', unit === 'd', () => void setWindow($, n, 'd'))}
741      </Box>
742    ) : null
743
744    // the models card: where this window's use went, by model and effort, for the limit that's tighter unless one is picked
745    const base = baselineOf(learned, s.baseline)
746    const shown = learned.models.filter(m => m.shown)
747    const names = shortNames(shown)
748    const tightness = (k: 'five' | 'week') => k === 'five'
749      ? (five ? (five.over ? -1 : five.arrive) : Infinity)
750      : (plan ? (plan.pct >= 100 || plan.runsOutAt !== null ? -1 : plan.left) : Infinity)
751    const picked = open.includes('models-period:five') ? 'five' : open.includes('models-period:week') ? 'week' : null
752    const period: 'five' | 'week' = picked ?? (tightness('five') < tightness('week') ? 'five' : 'week')
753    const split: UsageSplit | null = splits[period] ?? splits[period === 'five' ? 'week' : 'five']
754    const pickPeriod = (k: 'five' | 'week') => void update($, details, l => [...l.filter(x => !x.startsWith('models-period:')), `models-period:${k}`])
755    const periodButtons = (
756      <Box key="models-period" flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={1} rowGap={gap}>
757        {seg('period-five', '5h', split?.kind === 'five', () => pickPeriod('five'), !splits.five)}
758        {seg('period-week', 'Week', split?.kind === 'week', () => pickPeriod('week'), !splits.week)}
759      </Box>
760    )
761    const modelsOpen = open.includes('models')
762    const modelsSummary = !split ? 'No limit reported yet.'
763      : split.models.length ? split.models.slice(0, 3).map(m => `${names.get(m.id) ?? m.name} ${one(m.pct)}%`).join(' · ')
764      : 'Nothing used yet this window.'
765    // what the card counts, three plain lines, each point first
766    const modelsInfo = (
767      <Box key="models-info" flexDirection="column">
768        {MODELS_INFO.map(([point, rest], i) => (
769          <Box key={`info-${i}`} flexDirection="row" flexWrap="wrap" columnGap={1}>
770            <Text bold dimColor>{point}</Text>
771            <Text dimColor>{rest}</Text>
772          </Box>
773        ))}
774      </Box>
775    )
776    // the costs as a small table: name, figure, where the figure comes from
777    const rowsOfCost = costRows(learned, base)
778    const costTable = (
779      <Box key="models-costs" flexDirection="column">
780        <Text dimColor>{rowsOfCost.length ? 'Token cost, per token' : 'Costs compare once two models have been used.'}</Text>
781        {rowsOfCost.map(r => (
782          <Box key={`cost-${r.id}`} flexDirection="row" columnGap={2}>
783            <Box width={12} flexShrink={0}><Text>{r.name}</Text></Box>
784            <Box width={7} flexShrink={0}><Text bold>{r.x}</Text></Box>
785            <Text dimColor>{r.note}</Text>
786          </Box>
787        ))}
788      </Box>
789    )
790    const compareRow = base && (
791      <Box key="compare" flexDirection="row" flexWrap="wrap" justifyContent="flex-end" alignItems="center" columnGap={1} rowGap={gap}>
792        <Text color="inactive">Compare with</Text>
793        {shown.map(m => seg(`base-${m.id}`, names.get(m.id) ?? m.name, m === base, () => void choose($, { baseline: m.id })))}
794      </Box>
795    )
796
797    // sync: one quiet line here; everything else is in its own pane, opened from the cog
798    const syncRow = (v: RangeSync) => syncLine($, els, v, clockNow)
799
800    if (!week && !five) {
801      return (
802        <Box flexDirection="column" gap={1}>
803          <Text>No usage limits reported yet.</Text>
804          <Text dimColor>They arrive with Claude's next response, on a Pro or Max subscription.</Text>
805          {syncRow(sync)}
806        </Box>
807      )
808    }
809
810
811    if (Svg) {
812      // ---- the desktop: the design's cards, each a drawing with the pane's own controls in it ----
813      const runsText = (key: string, runs: Run[]) => (
814        <Box key={key} flexDirection="row" flexWrap="wrap" flexShrink={1}>
815          {runs.map((r, i) => (
816            <Text key={`${key}-${i}`} color={r.fill === C.bad ? 'claude' : r.fill === C.good ? 'success' : 'inactive'}>{r.s}</Text>
817          ))}
818        </Box>
819      )
820      /**
821       * One card: its drawing and controls on the card, then the strip under it (what it says while closed, and
822       * Details), then what Details opens, on the strip's tone.
823       */
824      const card = (key: string, body: Array<JSX.Element | null | false | undefined>, strip?: { summary: JSX.Element; detailsKey: string; inner: () => Array<JSX.Element | null | false | undefined> }) => {
825        const isOpen = !!strip && open.includes(strip.detailsKey)
826        return (
827          <Box key={`block-${key}`} flexDirection="column" marginBottom={1} borderStyle="round" borderColor="userMessageBackground" backgroundColor="userMessageBackground">
828            <Box key={`inner-${key}`} flexDirection="column" paddingX={2} paddingY={1} gap={1}>{body}</Box>
829            {strip && (
830              <Box key={`strip-${key}`} flexDirection="row" flexWrap="wrap" justifyContent="space-between" alignItems="center" columnGap={2} paddingX={2} paddingY={1} backgroundColor={INSET}>
831                {strip.summary}
832                <Button key={`details-btn-${strip.detailsKey}`} plain dimColor={!isOpen} label={isOpen ? 'Hide details ▴' : 'Details ▾'} onPress={() => toggle(strip.detailsKey)} />
833              </Box>
834            )}
835            {strip && isOpen && (
836              <Box key={`details-${key}`} flexDirection="column" paddingX={2} paddingBottom={1} gap={1} backgroundColor={INSET}>{strip.inner()}</Box>
837            )}
838          </Box>
839        )
840      }
841      // 1.3's card for a limit, behind its Details: its figures, its chart, what the average covers, Last window
842      const oldInner = (m: Model, title: string, controls: JSX.Element | null, extra: JSX.Element | null) => {
843        const last = lastOf(m)
844        const empty = emptyChartText(m, now)
845        const chart = empty ? emptyChartSvg(m, now, W, historyPalettes(pal))
846          : m.kind === 'week' ? weekChart(m, now, W, historyPalettes(pal), size.weekHeight) : fiveChart(m, now, W, historyPalettes(pal), size.fiveHeight)
847        return [
848          draw(`head-${m.kind}`, oldFigures(m, last, W, pal),
849            `${title}. ${resetsIn(m)}. ${isShort(m) ? `${runsOut(m)}. ` : ''}${figuresText(m)} ${lastAlt(last)}`),
850          draw(`chart-${m.kind}`, chart, empty ? empty.join('. ') : `${averageNote(m)} Your pace ${rateText(m, m.rate)}, safe pace ${rateText(m, m.limit)}.`),
851          <Box key={`old-foot-${m.kind}`} flexDirection="row" flexWrap="wrap" justifyContent="space-between" alignItems="center" columnGap={2} rowGap={gap}>
852            <Text key={`note-${m.kind}`} color="inactive">{empty || m.kind === 'five' ? '' : averageNote(m)}</Text>
853            {controls}
854          </Box>,
855          extra,
856          ...(last ? [LAST_INFO, lastWindowNote(last)] : []).map((para, i) => <Text key={`details-${m.kind}-${i}`} dimColor>{para}</Text>),
857        ]
858      }
859
860      /**
861       * How tightly the cards are drawn, so they all fit the pane's height where they can: 0 as designed, 1 without
862       * the masthead (the pane's title names it), 2 with the cards' headers and headlines smaller too. At each level
863       * the weekly card's day columns give up what the rest overruns, down to DAYS_MIN, so the cards fill the
864       * pane rather than leave a step's worth empty under them. Each level's drawings are measured; the native parts
865       * (padding, gaps, strips, the sync line) are counted in rows, at FIT_PX's sizes: an estimate, so a little may
866       * still scroll, and a pane too short even for the densest scrolls.
867       */
868      const showsWeek = !!(plan && week), showsTodayCard = !!(plan && week && showsToday(plan))
869      const weekSvg = (dense: boolean, shrink = 0) => weekCardSvg(plan!, pastDays(plan!), W, pal, dense, shrink)
870      const todayDrawing = (dense: boolean) => todaySvg(plan!, W, pal, dense)
871      const fiveSvg = (dense: boolean) => fiveCardSvg(five!, now, W, pal, dense)
872      const headOfModels = (dense: boolean) => modelsHead(split, W, pal, dense)
873      const usageSvg = split ? modelsUsage(split, W, pal) : null
874      const legendShown = showsWeek && !plan!.noData && plan!.pct < 100
875      const heightAt = (level: number) => {
876        const dense = level >= 2
877        const drawn = [
878          level === 0 ? mastheadSvg(W, pal) : null,
879          showsWeek ? weekSvg(dense) : null,
880          legendShown ? weekLegendSvg(plan!.basis === 'early', pal).svg : null,
881          showsTodayCard ? todayDrawing(dense) : null,
882          five ? fiveSvg(dense) : null,
883          headOfModels(dense),
884          usageSvg,
885        ].reduce((a, svg) => a + (svg ? drawingHeight(svg) : 0), 0)
886        // a card: its padding, the gaps between what's in it, its margin; a strip under it adds its padding and button
887        const cardRows = (items: number, strip: boolean) => 2 + Math.max(0, items - 1) + 1 + (strip ? 3 : 0)
888        const rows = (level === 0 ? 1 : 0)
889          + (showsWeek ? cardRows(legendShown ? 2 : 1, true) : 1)
890          + (showsTodayCard ? cardRows(1, false) : 0)
891          + (five ? cardRows(1, true) : 1)
892          + cardRows(split ? 3 : 2, true)
893          + 2
894          // an open Details: its text and drawings, roughly
895          + ['week', 'five', 'models'].filter(k => open.includes(k)).length * 18
896        return drawn + rows * FIT_PX.native
897      }
898      const room = Math.max(0, (e.props.scroll?.bodyRows ?? 0) * FIT_PX.row - FIT_PX.spare)
899      // what the day columns give up at a level, past which that level doesn't fit
900      const giveUp = (l: number) => Math.max(0, heightAt(l) - room)
901      const slack = legendShown ? daysHeight(W) - DAYS_MIN : 0
902      const level = !room ? 0 : [0, 1].find(l => giveUp(l) <= slack) ?? 2
903      const dense = level >= 2
904      const shrink = room && legendShown ? giveUp(level) : 0
905
906      const weekCard = plan && week ? (() => {
907        const past = pastDays(plan), hd = weekHead(plan), L = weekBarLabels(plan)
908        const alt = `This week, 100% = your weekly limit. ${hd.head}. ${hd.sub} ${plan.noData ? '' : `${[L.used, L.add].filter(Boolean).join(', ')}. ${daysText(plan, past)}.`}`
909        const chart = !plan.noData && plan.pct < 100
910        const legend = weekLegendSvg(plan.basis === 'early', pal)
911        return card('week', [
912          draw('week-card', weekSvg(dense, shrink), alt),
913          chart && (
914            <Box key="week-legend-row" flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={2}>
915              {draw('week-legend', legend.svg, plan.basis === 'early' ? 'Solid: used. Outlined: not known yet.' : 'Solid: used. Striped: expected at your pace.', legend.width)}
916            </Box>
917          ),
918        ], {
919          detailsKey: 'week',
920          summary: <Box key="summary-week" />,
921          inner: () => oldInner(week, 'This week', modeButtons, windowRow),
922        })
923      })() : <Text key="no-week" dimColor>No weekly limit reported.</Text>
924
925      // today, in today's budget: a card of its own under the week's
926      const todayCard = plan && week && showsToday(plan)
927        ? card('today', [draw('today-card', todayDrawing(dense), (() => { const d = todayText(plan); return `Today, 100% = today's budget. ${d.predicted}. ${d.note}` })())])
928        : null
929
930      const fiveCard = five ? card('five', [
931        draw('five-card', fiveSvg(dense), (() => { const hd = fiveHead(five, now); return `5-hour window, 100% = your 5-hour limit. ${hd.head}. ${hd.sub}` })()),
932      ], {
933        detailsKey: 'five',
934        summary: <Box key="summary-five" />,
935        inner: () => oldInner(five, '5-hour window', null, null),
936      }) : <Text key="no-five" dimColor>No current 5-hour window seen: it shows after your next response.</Text>
937
938      const modelsCard = card('models', [
939        draw('models-head', headOfModels(dense), `Models: where your usage went. ${modelsSummary}`),
940        periodButtons,
941        split && usageSvg ? draw('models-usage', usageSvg, splitText(split)) : null,
942      ], {
943        detailsKey: 'models',
944        summary: <Box key="summary-models" />,
945        inner: () => [
946          costTable,
947          compareRow,
948          modelsInfo,
949        ],
950      })
951
952      return (
953        <Box key="cards" flexDirection="column" gap={1}>
954          {level === 0 && draw('masthead', mastheadSvg(W, pal), 'Token Range Monitor. Track your usage, limits, and the time you have left.')}
955          <Box key="pane" flexDirection="column">
956            {weekCard}
957            {todayCard}
958            {fiveCard}
959            {modelsCard}
960            {syncRow(sync)}
961          </Box>
962        </Box>
963      )
964    }
965
966    // ---- the terminal: the same cards as text, each with its bars ----
967    const cardBox = { gap: 0, marginBottom: 0, paddingX: 1 }
968    // the card's inner width: the pane's, less the border and a column of padding each side
969    const inner = Math.max(20, e.props.bodyColumns - 4)
970    /**
971     * A bar on a card's scale, 100% at its right end: what's used solid with its figure in it, shaded to where this
972     * pace ends up with that total in it (in red past 100%), the rest faint. A figure its part can't hold is left out
973     * of the bar and comes back, so the line under it can say it.
974     */
975    const hbar = (key: string, used: number, total: number | null) => {
976      const n = inner, clamp = (v: number) => Math.max(0, Math.min(1, v / 100))
977      const u = Math.round(n * clamp(used)), t = total === null ? u : Math.max(u, Math.round(n * clamp(total)))
978      const over = (total ?? 0) > 100
979      // a label centred in a run of `w` cells, padded with `fill`; null when it doesn't fit with a cell either side
980      const centred = (label: string, w: number, fill: string) => {
981        if (w < label.length + 2) return null
982        const l = Math.floor((w - label.length) / 2)
983        return fill.repeat(l) + label + fill.repeat(w - l - label.length)
984      }
985      const usedLabel = `${one(used)}%`, totalLabel = total === null ? null : `~${one(total)}%`
986      const solid = centred(usedLabel, u, ' ')
987      const shade = totalLabel === null ? '▒'.repeat(t - u) : centred(` ${totalLabel} `, t - u, '▒')
988      const missing = [...(solid === null ? [`${usedLabel} used`] : []), ...(totalLabel !== null && shade === null ? [`${totalLabel} by the reset`] : [])]
989      return {
990        bar: (
991          <Box key={key} flexDirection="row">
992            <Text color="inverseText" backgroundColor="claude" bold>{solid ?? ' '.repeat(u)}</Text>
993            <Text color={over ? 'error' : 'claude'} bold={over}>{shade ?? '▒'.repeat(t - u)}</Text>
994            <Text color="subtle">{'░'.repeat(n - t)}</Text>
995          </Box>
996        ),
997        missing,
998      }
999    }
1000    /** The line under a bar: what the bar couldn't hold on the left, when it resets on the right. */
1001    const barFoot = (key: string, missing: string[], right: string) => (
1002      <Box key={key} flexDirection="row" flexWrap="wrap" justifyContent="space-between" columnGap={2}>
1003        <Text dimColor>{missing.join(' · ')}</Text>
1004        <Text dimColor>{right}</Text>
1005      </Box>
1006    )
1007    /** A card's title, and its headline on the right: only the figure in it (a %, or a time) in colour. */
1008    const titleRow = (key: string, title: string, head: string, tone: 'good' | 'bad' | 'dim') => (
1009      <Box key={key} flexDirection="row" flexWrap="wrap" justifyContent="space-between" columnGap={2}>
1010        <Text bold>{title}</Text>
1011        <Box flexDirection="row">
1012          {head.split(/(~?\d+(?:\.\d+)?%|~\d\d:\d\d)/).filter(Boolean).map((part, i) => (
1013            <Text key={`h${i}`} bold dimColor={tone === 'dim'} color={tone !== 'dim' && /^~?\d/.test(part) ? (tone === 'bad' ? 'error' : 'claude') : undefined}>{part}</Text>
1014          ))}
1015        </Box>
1016      </Box>
1017    )
1018    /**
1019     * The days of this window as columns, in % of the weekly limit: each day's figure over its column and its
1020     * name under it, past days and today solid, the days to come dim at this pace.
1021     */
1022    const dayColumns = (p: WeekPlan, rows: number) => {
1023      const early = p.basis === 'early'
1024      const days = [
1025        ...pastDays(p).map((v, i) => ({ name: dayName(p.days[i]!.start), v, label: `${one(v)}%`, later: false, today: false })),
1026        { name: dayName(p.dayStart), v: p.usedToday, label: `${one(p.usedToday)}%`, later: false, today: true },
1027        ...p.later.map(d => ({ name: dayName(d.start), v: early ? 0 : d.amount, label: early ? '?' : `~${one(d.amount)}%`, later: true, today: false })),
1028      ]
1029      const colW = Math.max(6, Math.min(9, Math.floor(inner / days.length)))
1030      const top = Math.max(1, ...days.map(d => d.v))
1031      const glyph = (v: number, row: number) => {
1032        const eighths = Math.round(v / top * rows * 8) - row * 8
1033        return eighths >= 8 ? '█' : eighths <= 0 ? ' ' : ' ▁▂▃▄▅▆▇'[eighths]!
1034      }
1035      const cell = (k: string, text: string, props: Record<string, unknown>) => (
1036        <Box key={k} width={colW} flexShrink={0}><Text {...props}>{text}</Text></Box>
1037      )
1038      return (
1039        <Box key="week-days" flexDirection="column">
1040          <Box flexDirection="row">{days.map((d, i) => cell(`v${i}`, d.label, { dimColor: true }))}</Box>
1041          {Array.from({ length: rows }, (_, r) => rows - 1 - r).map(row => (
1042            <Box key={`r${row}`} flexDirection="row">
1043              {days.map((d, i) => cell(`b${row}-${i}`, glyph(d.v, row).repeat(Math.min(4, colW - 2)), { color: 'claude', dimColor: d.later }))}
1044            </Box>
1045          ))}
1046          <Box flexDirection="row">{days.map((d, i) => cell(`n${i}`, d.today ? `${d.name}•` : d.name, d.today ? { color: 'claude', bold: true } : { dimColor: true }))}</Box>
1047        </Box>
1048      )
1049    }
1050    const termCard = (key: string, children: Array<JSX.Element | null | false>) => (
1051      <Box key={`block-${key}`} flexDirection="column" {...cardBox} borderStyle="round" borderColor="userMessageBackground" backgroundColor="userMessageBackground">{children}</Box>
1052    )
1053    /**
1054     * The days' columns' rows of bars, so the cards fit the pane's rows where they can: 3, or 1 in a short pane, or
1055     * none (0) in one shorter still. The rest is counted: each card's border, its lines, the sync line.
1056     */
1057    const dayRows = (() => {
1058      const room = e.props.scroll?.bodyRows ?? 0
1059      if (!room) return 3
1060      const weekRows = plan ? 2 + 1 + (plan.noData ? 0 : 2) : 1
1061      const todayRows = plan && showsToday(plan) ? 4 : 0
1062      const fiveRows = five ? 2 + 1 + (five.noData ? 0 : 2) : 1
1063      const modelsRows = 2 + 2 + (split ? 1 + split.models.length + (split.notRecorded >= 0.05 ? 1 : 0) : 0) + (modelsOpen ? 3 + rowsOfCost.length + MODELS_INFO.length + 2 : 0)
1064      const rest = weekRows + todayRows + fiveRows + modelsRows + 2
1065      const columns = plan && !plan.noData && plan.pct < 100
1066      if (!columns) return 3
1067      return [3, 1].find(r => rest + 2 + r <= room) ?? 0
1068    })()
1069    // the weekly card: its headline, the week as a bar, its days as columns
1070    const weekCardTerm = (p: WeekPlan) => {
1071      const hd = weekHeadline(p), L = weekBarLabels(p)
1072      const bar = p.noData ? null : hbar('week-bar', p.pct, L.add === null ? null : p.pct + toCome(p))
1073      return termCard('week', [
1074        titleRow('week-title', 'This week', hd.badge ? `${hd.head} ${hd.badge}` : hd.head, hd.tone),
1075        bar && bar.bar,
1076        bar && barFoot('week-foot', bar.missing, `resets ${dayTime(p.resetsAt)}`),
1077        !p.noData && p.pct < 100 && dayRows > 0 && dayColumns(p, dayRows),
1078      ])
1079    }
1080    // today against its budget, laid out as the 5-hour card
1081    const todayCardTerm = (p: WeekPlan) => {
1082      const at = overBudgetAt(p)
1083      const head = at === null ? 'Within budget' : at <= p.now ? 'Over budget' : `Over budget ~${hm(at)}`
1084      const bar = hbar('today-bar', p.usedOfBudget, p.predicted > p.usedOfBudget + 0.05 ? p.predicted : null)
1085      return termCard('today', [
1086        titleRow('today-title', 'Today', head, at === null ? 'good' : 'bad'),
1087        bar.bar,
1088        bar.missing.length ? barFoot('today-foot', bar.missing, '') : null,
1089      ])
1090    }
1091    // the 5-hour card: its headline, then the window's use as a bar
1092    const fiveCardTerm = (m: Model) => {
1093      const hd = fiveHead(m, now), proj = 100 - m.arrive, cut = m.noData ? null : cutOff(m, now)
1094      const bar = m.noData ? null : hbar('five-bar', m.pct, proj > m.pct ? proj : null)
1095      // the short headline: the reset's time is under the bar
1096      const head = m.noData || m.pct >= 100 ? hd.head : cut !== null ? `Cut off ~${hm(cut)}` : 'Lasts to the reset'
1097      return termCard('five', [
1098        titleRow('five-title', '5-hour window', head, hd.tone),
1099        bar && bar.bar,
1100        bar && barFoot('five-foot', bar.missing, `resets ${hm(m.resetsAt)}`),
1101      ])
1102    }
1103    const detailsButton = (key: string) => (
1104      <Button key={`details-btn-${key}`} plain dimColor label={open.includes(key) ? 'Hide details' : 'Details'} onPress={() => toggle(key)} />
1105    )
1106    // the models card: the split as one bar of each model's share, a line per model under it, the costs behind Details
1107    const modelBar = (sp: UsageSplit) => {
1108      const n = inner, colour = (f: string) => (f === 'fable' ? 'claude' : f === 'opus' ? 'claude' : f === 'sonnet' ? 'suggestion' : 'inactive')
1109      let used = 0
1110      const segsOf = sp.models.map((m, i) => {
1111        const c = Math.round(n * m.pct / 100)
1112        used += c
1113        return <Text key={`mb-${i}`} color={colour(m.family)} dimColor={i % 2 === 1}>{(i % 2 ? '▓' : '█').repeat(c)}</Text>
1114      })
1115      const nr = Math.min(n - used, Math.round(n * sp.notRecorded / 100))
1116      return (
1117        <Box key="models-bar" flexDirection="row">
1118          {segsOf}
1119          <Text color="subtle">{'▒'.repeat(Math.max(0, nr))}</Text>
1120          <Text color="subtle">{'░'.repeat(Math.max(0, n - used - nr))}</Text>
1121        </Box>
1122      )
1123    }
1124    const modelsCard = (
1125      <Box key="block-models" flexDirection="column" {...cardBox} borderStyle="round" borderColor="userMessageBackground" backgroundColor="userMessageBackground">
1126        <Box key="models-title" flexDirection="row" flexWrap="wrap" justifyContent="space-between" columnGap={2}>
1127          <Text bold>Models</Text>
1128          {periodButtons}
1129        </Box>
1130        {split && modelBar(split)}
1131        {split && split.models.map(m => (
1132          <Box key={`ml-${m.id}`} flexDirection="row" justifyContent="space-between" columnGap={2}>
1133            <Text>{(() => { const ef = shownEffort(m); return `${m.name}${ef.length > 1 || (ef[0] && ef[0][0] !== 'default') ? `  ${ef.map(([e, v]) => `${e} ${one(v)}%`).join(' · ')}` : ''}` })()}</Text>
1134            <Text bold>{`${one(m.pct)}%`}</Text>
1135          </Box>
1136        ))}
1137        {split && split.notRecorded >= 0.05 && (
1138          <Box key="ml-nr" flexDirection="row" justifyContent="space-between" columnGap={2}>
1139            <Text dimColor>Not recorded</Text>
1140            <Text dimColor>{`${one(split.notRecorded)}%`}</Text>
1141          </Box>
1142        )}
1143        <Box key="models-foot" flexDirection="row" justifyContent="flex-end">{detailsButton('models')}</Box>
1144        {modelsOpen && costTable}
1145        {modelsOpen && modelsInfo}
1146        {modelsOpen && compareRow}
1147      </Box>
1148    )
1149
1150    return (
1151      <Box key="cards" flexDirection="column">
1152        {plan ? weekCardTerm(plan) : <Text dimColor>No weekly limit reported.</Text>}
1153        {plan && showsToday(plan) && todayCardTerm(plan)}
1154        {five ? fiveCardTerm(five) : <Text dimColor>No current 5-hour window seen: it shows after your next response.</Text>}
1155        {modelsCard}
1156        {syncRow(sync)}
1157      </Box>
1158    )
1159  })
1160}
1161
hooks/range.ts 1022 lines
1import type { Palettes, RangeReading, RangeSettings } from '../types'
2import { DEFAULT_PALETTES, paletteStyle, v } from './theme'
3import type { PaletteKey } from './theme'
4
5export const MIN = 60_000
6export const HOUR = 60 * MIN
7export const DAY = 24 * HOUR
8
9export type Kind = 'five' | 'week'
10const KIND = { five: 0, week: 1 } as const
11const SPAN = { five: 5 * HOUR, week: 7 * DAY }
12/** How far back one reading's increase is spread when readings are far apart. */
13const SPREAD = 10 * MIN
14/**
15 * Readings older than this are dropped: the models learn from the last 14 days, plus a day of slack.
16 * The sync server keeps a day's list as long, so a device sees the same span of every other device.
17 */
18export const KEEP = 15 * DAY
19
20export const DEFAULT_SETTINGS: RangeSettings = { mode: 'reset', n: 1, unit: 'd', fine: false }
21export const UNIT_HOURS = { h: 1, d: 24, w: 168 } as const
22/** The longest window on offer per unit: a day in hours, the week's own length in days. */
23export const UNIT_MAX = { h: 24, d: 7 } as const
24
25export const windowHours = (s: Pick<RangeSettings, 'n' | 'unit'>) => Math.min(s.n * UNIT_HOURS[s.unit], KEEP / HOUR - 24)
26export const windowName = (s: Pick<RangeSettings, 'n' | 'unit'>) => `${s.n}${s.unit}`
27
28/** What an average covers: the last `hours`, or the time since the reset. */
29export type Average = { type: 'hours'; hours: number } | { type: 'reset' }
30
31/**
32 * Least data behind any average before it is an estimate. The weekly figure moves
33 * in coarse steps, so under six hours one step reads as a huge rate.
34 */
35export const MIN_RECORDED_H = { week: 6, five: 5 / 60 }
36/** The shortest window on offer per unit: in hours the weekly least, since anything shorter can't give an estimate. */
37export const UNIT_MIN = { h: MIN_RECORDED_H.week, d: 1 } as const
38/** `n` held to what the unit offers. */
39export const clampWindow = (n: number, unit: 'h' | 'd') => Math.min(UNIT_MAX[unit], Math.max(UNIT_MIN[unit], Math.round(n)))
40/** Least time since the reset before its average is an estimate: just after a reset a few % projects wildly. */
41export const MIN_SINCE_RESET_H = { week: 6, five: 0.25 }
42
43export const chosenAverage = (s: RangeSettings): Average =>
44  s.mode === 'window' ? { type: 'hours', hours: windowHours(s) } : { type: s.mode }
45
46/** Hours of usage on record for this limit: from its first reading to now. */
47export function recordedHours(readings: readonly RangeReading[], kind: Kind, now: number): number {
48  const first = ofKind(readings, kind)[0]
49  return first ? Math.max(0, (now - first[0]) / HOUR) : 0
50}
51
52/** Parses `2d`, `6h`, `1w`, `3 days`; null when it is none of those. */
53export function parseWindow(text: string): Pick<RangeSettings, 'n' | 'unit'> | null {
54  const m = /^\s*(\d{1,3})\s*(h|hours?|d|days?|w|weeks?)\s*$/i.exec(text)
55  if (!m) return null
56  const n = Number(m[1] ?? 0)
57  const unit = (m[2] ?? '').charAt(0).toLowerCase() as RangeSettings['unit']
58  if (n < 1 || n * UNIT_HOURS[unit] > 168) return null
59  return { n, unit }
60}
61
62const sameWindow = (a: RangeReading, b: RangeReading) => Math.abs(a[3] - b[3]) < 5 * MIN
63const sameWindowAs = (r: RangeReading, resetsAt: number) => Math.abs(r[3] - resetsAt) < 5 * MIN
64
65/**
66 * Whether reading `r` is an old figure come back with a later time, after `last`, the latest one kept.
67 * A session that has had no response for a while still holds the figures of its last one, and
68 * a version before 1.3.3 recorded them again each minute, taking turns with a busier session
69 * (8, 7, 8, 7…). A limit only rises within its window, so a lower figure in the same window, a
70 * figure naming an earlier window, or one taken after its own reset is stale.
71 */
72export const isStale = (r: RangeReading, last: RangeReading | undefined) =>
73  r[0] >= r[3] || (!!last && (r[3] < last[3] - 5 * MIN || (sameWindow(last, r) && r[2] < last[2])))
74
75/** One limit's readings in time order, stale ones left out. */
76export function ofKind(readings: readonly RangeReading[], kind: Kind): RangeReading[] {
77  const out: RangeReading[] = []
78  for (const r of readings.filter(r => r[1] === KIND[kind]).sort((a, b) => a[0] - b[0])) {
79    if (!isStale(r, out[out.length - 1])) out.push(r)
80  }
81  return out
82}
83
84/** Merges reading lists, dropping duplicates and anything older than KEEP. */
85export function merge(lists: ReadonlyArray<readonly RangeReading[]>, now: number): RangeReading[] {
86  const seen = new Set<string>()
87  const out: RangeReading[] = []
88  for (const list of lists) {
89    for (const r of list) {
90      const id = `${r[0]}:${r[1]}:${r[2]}`
91      if (r[0] < now - KEEP || seen.has(id)) continue
92      seen.add(id)
93      out.push(r)
94    }
95  }
96  return out.sort((a, b) => a[0] - b[0])
97}
98
99/**
100 * A stretch of time some session on this computer was getting fresh figures:
101 * its turns were getting responses from Claude, each carrying the account's
102 * current usage. An open but idle session gets none, so it isn't watching.
103 * [from, to] in ms.
104 */
105export type Watch = [number, number]
106
107/**
108 * Two fresh figures further apart than this leave a hole: nothing here was
109 * watching in between. Long enough to span a pause while you read or type,
110 * short enough that an idle hour counts as away.
111 */
112export const WATCH_GAP = 15 * MIN
113
114/** Whether [a, b] lies wholly inside the watched spans. */
115export function isWatched(seen: readonly Watch[], a: number, b: number): boolean {
116  let t = a
117  for (const [s, e] of [...seen].sort((x, y) => x[0] - y[0])) {
118    if (s > t + WATCH_GAP) break
119    t = Math.max(t, e)
120    if (t >= b - WATCH_GAP) return true
121  }
122  return t >= b - WATCH_GAP
123}
124
125/** Adds a heartbeat at `now`: extends the last span when it is recent, else starts one. */
126export function heartbeat(seen: readonly Watch[], now: number): Watch[] {
127  const last = seen[seen.length - 1]
128  const kept = seen.filter(w => w[1] >= now - KEEP)
129  if (last && now - last[1] <= WATCH_GAP) return [...kept.slice(0, -1), [last[0], now]]
130  return [...kept, [now, now]]
131}
132
133export type Increment = {
134  start: number
135  end: number
136  amount: number
137  /** Set when the rise came over a gap this computer didn't watch: the gap's start and where the rise was placed. Drawn as the gap's block. */
138  hole?: [number, number]
139  /** For a rise seen while watching: when the reading before it was taken, so the rise came somewhere after. */
140  from?: number
141}
142
143/**
144 * Usage gained between readings. Within one window only rises past the highest
145 * reading so far count, so rounding wobble isn't counted twice; across a reset,
146 * the new window's whole reading counts.
147 *
148 * Where it goes in time: while this computer was watching, a rise sits in the
149 * minutes before the reading that saw it. A rise over a gap the computer
150 * wasn't watching came from elsewhere (another computer, claude.ai): it goes
151 * into the account's current 5-hour window when that opened inside the gap,
152 * since a 5-hour window opens with the first message of a stretch of work;
153 * with no such clue it is spread evenly over the gap.
154 */
155export function increments(readings: readonly RangeReading[], kind: Kind, seen: readonly Watch[] = []): Increment[] {
156  const rs = ofKind(readings, kind)
157  const fives = ofKind(readings, 'five')
158  const out: Increment[] = []
159  let high = rs[0]?.[2] ?? 0
160  let reached = rs[0]?.[0] ?? 0
161  for (let i = 1; i < rs.length; i++) {
162    const a = rs[i - 1]!, b = rs[i]!
163    let amount: number
164    let start: number
165    let hole: [number, number] | undefined
166    if (b[0] - a[0] <= SPREAD || isWatched(seen, a[0], b[0])) {
167      start = b[0] - Math.min(b[0] - a[0], SPREAD)
168    } else {
169      let five: RangeReading | undefined
170      for (const f of fives) if (f[0] <= b[0] + MIN) five = f
171      const fiveStart = five && five[3] > b[0] ? five[3] - SPAN.five : undefined
172      start = fiveStart !== undefined && fiveStart > a[0] ? fiveStart : a[0]
173      hole = [a[0], start > a[0] ? start : b[0]]
174    }
175    // the rise came after the figure first reached its last point: readings repeat while it stays put
176    let from = reached
177    if (sameWindow(a, b)) {
178      amount = b[2] - high
179      high = Math.max(high, b[2])
180    } else {
181      amount = b[2]
182      high = b[2]
183      start = Math.max(start, b[3] - SPAN[kind])
184      from = Math.max(a[0], b[3] - SPAN[kind])
185    }
186    if (amount > 0) {
187      out.push({ start: Math.min(start, b[0] - 1), end: b[0], amount, ...(hole ? { hole } : { from }) })
188      reached = b[0]
189    }
190  }
191  return out
192}
193
194/**
195 * Rises placed where the work behind them happened. A limit is read in whole
196 * points, so on its own a rise only says which reading saw it: every bar of
197 * one point would be the same height. Each rise seen while watching is shared
198 * among the responses made since the figure reached its previous point, by their weight
199 * (`points`: when, and how much work), so the total stays Anthropic's and the
200 * shape is the work's. A rise with no responses behind it, or over a gap,
201 * stays as it was.
202 */
203export function refine(incs: readonly Increment[], points: ReadonlyArray<readonly [number, number]>): Increment[] {
204  const pts = [...points].sort((a, b) => a[0] - b[0])
205  const out: Increment[] = []
206  let k = 0
207  for (const inc of [...incs].sort((a, b) => a.end - b.end)) {
208    if (inc.hole || inc.from === undefined) { out.push(inc); continue }
209    while (k < pts.length && pts[k]![0] <= inc.from) k++
210    let j = k, total = 0
211    while (j < pts.length && pts[j]![0] <= inc.end) total += pts[j++]![1]
212    if (total <= 0) { out.push(inc); continue }
213    for (let i = k; i < j; i++) {
214      const [t, w] = pts[i]!
215      if (w > 0) out.push({ start: t - MIN, end: t, amount: inc.amount * w / total })
216    }
217  }
218  return out
219}
220
221export function usedBetween(incs: readonly Increment[], from: number, to: number): number {
222  let sum = 0
223  for (const inc of incs) {
224    const overlap = Math.min(inc.end, to) - Math.max(inc.start, from)
225    if (overlap > 0) sum += inc.amount * overlap / (inc.end - inc.start)
226  }
227  return sum
228}
229
230export type Model = {
231  kind: Kind
232  /** % used now, and when the window resets (ms). */
233  pct: number
234  resetsAt: number
235  /** Hours until the reset. */
236  left: number
237  /** Average and limit, in % per hour. */
238  rate: number
239  limit: number
240  /** % projected to be left at the reset; negative means short by that much. */
241  arrive: number
242  over: boolean
243  /** Hours until 100% at this rate (Infinity at rate 0), and how long before the reset that is. */
244  runsOutIn: number
245  early: number
246  /** What the average covers, from when (ms), and for how many hours. */
247  average: Average
248  from: number
249  winH: number
250  /** When recording of this limit began (ms): before it the chart has no bars. */
251  recordedFrom: number
252  /**
253   * Usage since the reset from before recording began, when the average runs
254   * from the reset and the record begins inside this window: % used by the
255   * first reading, and when that was (ms). Drawn as one block up to then.
256   */
257  before: { pct: number; until: number } | null
258  /** Why there is no estimate, when there isn't enough behind the average; then the rate and what follows from it mean nothing. */
259  noData: string | null
260  increments: Increment[]
261}
262
263/**
264 * The projection for one limit at `now`, from the latest reading and the
265 * average `avg`. With too little behind that average (a window longer than
266 * the record, or just after a reset) there is no estimate: `noData` says why.
267 */
268export function project(readings: readonly RangeReading[], kind: Kind, now: number, avg: Average, seen: readonly Watch[] = []): Model | null {
269  const rs = ofKind(readings, kind)
270  const last = rs[rs.length - 1]
271  if (!last) return null
272  let pct = last[2], resetsAt = last[3]
273  if (resetsAt <= now) {
274    if (kind === 'five') return null            // no active 5-hour window
275    while (resetsAt <= now) resetsAt += SPAN.week
276    pct = 0
277  }
278  const incs = increments(readings, kind, seen)
279  const recordedFrom = rs[0]![0]
280  const from = avg.type === 'reset' ? resetsAt - SPAN[kind] : now - avg.hours * HOUR
281  const winH = Math.max((now - from) / HOUR, 1 / 60)
282  // since the reset, Anthropic's own figure is exact; otherwise add up what was recorded
283  const recordedH = (now - recordedFrom) / HOUR
284  const sinceResetH = (now - (resetsAt - SPAN[kind])) / HOUR
285  const noData = avg.type === 'reset'
286    ? sinceResetH < MIN_SINCE_RESET_H[kind] ? `No estimate this soon after ${kind === 'five' ? 'the 5-hour window opened' : 'the reset'}. About ${dur(MIN_SINCE_RESET_H[kind] - sinceResetH)} to go.` : null
287    : avg.hours < MIN_RECORDED_H[kind] ? tooShort(kind) : avg.hours > recordedH ? needsMore(avg, recordedH) : null
288  const rate = noData ? 0 : (avg.type === 'reset' ? pct : usedBetween(incs, from, now)) / winH
289  const left = (resetsAt - now) / HOUR
290  const remaining = 100 - pct
291  const proj = pct + rate * left
292  const runsOutIn = rate > 0 ? remaining / rate : Infinity
293  // the window's first reading, when nothing was recorded before it, holds all usage up to then
294  const first = rs[0]!
295  const before = avg.type === 'reset' && sameWindowAs(first, resetsAt) && first[0] > from ? { pct: first[2], until: first[0] } : null
296  return {
297    kind, pct, resetsAt, left, rate, limit: remaining / left, arrive: 100 - proj, over: proj > 100,
298    runsOutIn, early: Math.max(0, left - runsOutIn), average: avg, from, winH, recordedFrom, before, noData, increments: incs,
299  }
300}
301
302/** Bar size in minutes so the window holds at most 48 bars. */
303export const bucketMinutes = (winMin: number) =>
304  [1, 5, 10, 15, 30, 60, 120, 180, 240, 360, 480, 720, 1440].find(b => winMin / b <= 48) ?? 1440
305
306/**
307 * Usage rate per bar from the average's start to now, in % per `perHours`
308 * hours: about `bucketMin` minutes a bar, the bars filling the span exactly.
309 */
310export function bars(m: Model, now: number, bucketMin: number, perHours: number): number[] {
311  const n = Math.max(1, Math.round(m.winH * 60 / bucketMin)), width = (now - m.from) / n, out: number[] = []
312  // usage seen as it happened; what came in over a gap is drawn as that gap's block instead
313  const seen = m.increments.filter(i => !i.hole)
314  for (let i = 0; i < n; i++) {
315    const s = m.from + i * width
316    out.push(usedBetween(seen, s, s + width) / (width / HOUR) * perHours)
317  }
318  return out
319}
320
321// ---- the last window ----
322
323/**
324 * How near its reset a window's last reading must be for its final figure to
325 * be trusted, as a share of the window: its last 10%, so 30 minutes of a
326 * 5-hour window and about 17 hours of a week. A window this computer watched
327 * to its end counts too. The same holds for the stretch in which a window ran
328 * out: from the last reading under 100% to the first at it.
329 */
330export const LAST_TAIL = 0.1
331
332export type LastWindow = {
333  kind: Kind
334  /** When the window reset (ms). */
335  resetsAt: number
336  /** % used by its last reading before the reset (100 once it ran out). */
337  pct: number
338  /**
339   * What was left of the limit at the reset, in %. Negative when it ran out:
340   * how much more the locked-out time would have needed at the rate the
341   * window was used until it ran out, as the card's left-at-reset reads.
342   */
343  left: number
344  /** When it ran out (ms), or null when it didn't; hours used before that, and locked out after. */
345  ranOutAt: number | null
346  usedH: number
347  lockedH: number
348}
349
350/**
351 * The previous window of a limit, as it ended: the latest window whose reset
352 * has passed. Didn't run out: 100 − its last %. Ran out: −(100% ÷ hours from
353 * the window's opening to running out × hours from then to the reset), the
354 * since-the-reset average the card projects with, kept up over the time
355 * locked out. Null when the record can't say: no readings in it, a last
356 * reading too long before the reset, or no telling when it ran out.
357 */
358export function lastWindow(readings: readonly RangeReading[], kind: Kind, now: number, seen: readonly Watch[] = []): LastWindow | null {
359  const rs = ofKind(readings, kind)
360  let resetsAt = -Infinity
361  for (const r of rs) if (r[3] <= now && r[3] > resetsAt) resetsAt = r[3]
362  if (resetsAt === -Infinity) return null
363  const span = SPAN[kind], opened = resetsAt - span, tail = LAST_TAIL * span
364  // that window's readings taken before it reset: one taken after, still naming that reset, is stale
365  const win = rs.filter(r => sameWindowAs(r, resetsAt) && r[0] < resetsAt)
366  const out = win.findIndex(r => r[2] >= 100)
367  if (out >= 0) {
368    const hit = win[out]!, before = win[out - 1]
369    // already out at its first reading, or a long unwatched gap before running out: when isn't known
370    if (!before || (hit[0] - before[0] > tail && !isWatched(seen, before[0], hit[0]))) return null
371    const usedH = Math.max(hit[0] - opened, MIN) / HOUR, lockedH = (resetsAt - hit[0]) / HOUR
372    return { kind, resetsAt, pct: 100, left: -100 / usedH * lockedH, ranOutAt: hit[0], usedH, lockedH }
373  }
374  const last = win[win.length - 1]
375  if (!last || (resetsAt - last[0] > tail && !isWatched(seen, last[0], resetsAt))) return null
376  return { kind, resetsAt, pct: last[2], left: 100 - last[2], ranOutAt: null, usedH: span / HOUR, lockedH: 0 }
377}
378
379/** The caption of the last window's figure. */
380export const LAST_LABEL = 'Last window'
381export const lastWindowText = (l: LastWindow) => spare(l.left)
382/** Whether it reads as short: by the rounded figure, so the colour matches the sign shown. */
383export const lastIsShort = (l: LastWindow) => Math.round(l.left) < 0
384/** What Last window means: the info circle's tooltip. */
385export const LAST_INFO = 'Last window is what was left of this limit when its previous window reset. Short means it ran out early: how much more you would have needed for the rest of that window, at the pace you used it until then.'
386/** How this one ended, in words. */
387export function lastWindowNote(l: LastWindow): string {
388  if (l.ranOutAt === null) return `It ended at ${Math.round(l.pct)}% used.`
389  return `It ran out ${dur(l.lockedH)} before its reset, after ${dur(l.usedH)} of use.`
390}
391
392// ---- words ----
393
394export const signed = (x: number) => (Math.round(x) >= 0 ? '+' : '−') + Math.abs(Math.round(x)) + '%'
395/** What's left of a limit, in words: "21% to spare", or "23% short" where it runs out. */
396export const spare = (x: number) => `${Math.abs(Math.round(x))}% ${Math.round(x) >= 0 ? 'to spare' : 'short'}`
397export const fx = (v: number, d = 1) => v.toFixed(d)
398
399export function dur(h: number): string {
400  if (!isFinite(h)) return '—'
401  if (h >= 24) return Math.round(h % 24) % 24 === 0 ? `${Math.round(h / 24)}d` : `${Math.floor(h / 24)}d ${Math.round(h % 24)}h`
402  if (h >= 1) {
403    const m = Math.round(h % 1 * 60)
404    // a whole number of hours reads plainly: "8h", not "8h 00m"
405    return m === 0 || m === 60 ? `${Math.round(h)}h` : `${Math.floor(h)}h ${String(m).padStart(2, '0')}m`
406  }
407  return `${Math.max(0, Math.round(h * 60))}m`
408}
409
410/** "Resets in 3d 17h", "Resets in 2h 24m", "Resets in 38m": exact at any distance, so no unit to pick. */
411export const resetsIn = (m: Model) => `Resets in ${dur(m.left)}`
412
413/** The name of an average, as its button shows it. */
414export const averageName = (avg: Average) =>
415  avg.type === 'reset' ? 'Since reset' : avg.hours < 1 ? `${Math.round(avg.hours * 60)}m` : windowName(hoursToWindow(avg.hours))
416
417const hoursToWindow = (h: number): Pick<RangeSettings, 'n' | 'unit'> =>
418  h % 24 === 0 ? { n: h / 24, unit: 'd' } : { n: h, unit: 'h' }
419
420/** One line on what the average covers. */
421export function averageNote(m: Model): string {
422  if (m.noData) return m.noData
423  if (m.average.type === 'reset') {
424    const since = m.kind === 'five' ? `the 5-hour window opened` : `the reset`
425    return m.recordedFrom > m.from
426      ? `Average since ${since} ${dur(m.winH)} ago, from Anthropic's figure.`
427      : `Average since ${since} ${dur(m.winH)} ago.`
428  }
429  return `Average over the last ${averageName(m.average)}.`
430}
431
432/** Why an average can't be picked yet, and when it can. */
433export const needsMore = (avg: { type: 'hours'; hours: number }, recordedH: number) =>
434  `${averageName(avg)} needs ${dur(avg.hours)} of recorded usage. ${dur(recordedH)} recorded so far, about ${dur(avg.hours - recordedH)} to go.`
435
436/** For a window shorter than a limit's least data: no estimate, whatever is on record. */
437const tooShort = (kind: Kind) =>
438  `${kind === 'week' ? 'Weekly' : '5-hour'} estimates need at least ${dur(MIN_RECORDED_H[kind])} of data. Set the window to ${dur(MIN_RECORDED_H[kind])} or more.`
439
440export const runsOut = (m: Model) => `Runs out in ${dur(m.runsOutIn)}, ${dur(m.early)} early`
441
442/** What's projected to be left at the reset, "21% to spare" or "23% short", or "No data" without an estimate. */
443export const leftText = (m: Model) => (m.noData ? 'No data' : spare(m.arrive))
444export const isShort = (m: Model) => m.over && !m.noData
445
446/** One limit's part of the band: its name, the figure in its state's colour, and what follows it. */
447export type BandPart = { label: string; value: string; rest: string }
448/**
449 * Over: when it runs out, from now ("runs out in 2d 9h, 1d 7h early"). Else
450 * what's left at the reset and when that is. `short` is the narrow form:
451 * "out in 2d 9h", or "+21% 2h 24m".
452 */
453export function bandPart(m: Model, short: boolean): BandPart {
454  const label = m.kind === 'week' ? 'Week' : '5h'
455  if (isShort(m)) return short
456    ? { label, value: `out in ${dur(m.runsOutIn)}`, rest: '' }
457    : { label, value: `runs out in ${dur(m.runsOutIn)}`, rest: `, ${dur(m.early)} early` }
458  return short
459    ? { label, value: m.noData ? 'No data' : signed(m.arrive), rest: ` ${dur(m.left)}` }
460    : { label, value: leftText(m), rest: `, resets in ${dur(m.left)}` }
461}
462/** About how many cells the band takes: the parts, the " · " between them, and the Details button. */
463export const bandWidth = (limits: Model[], short: boolean) =>
464  limits.reduce((w, m) => { const p = bandPart(m, short); return w + p.label.length + 1 + p.value.length + p.rest.length }, 0)
465  + Math.max(0, limits.length - 1) * 3 + 1 + 11
466
467export const rateText = (m: Model, perHour: number) =>
468  m.kind === 'week' ? `${fx(perHour * 24)}% a day` : `${fx(perHour)}% an hour`
469
470/** A rate in short: "15.9%/day", "8.6%/h". */
471export const rateShort = (m: Model, perHour: number) =>
472  m.kind === 'week' ? `${fx(perHour * 24)}%/day` : `${fx(perHour)}%/h`
473
474/** The terminal's range track: a piece of text and how it's coloured. */
475export type TrackTone = 'text' | 'dim' | 'faint' | 'short' | 'ok' | 'unused' | 'unusedBold'
476export type TrackSeg = { text: string; tone: TrackTone }
477export type Track = {
478  line: TrackSeg[]
479  /** Short: how early, its end under the ╳ (`indent` columns in). */
480  early?: { indent: number; text: string }
481  /** Lasting: what's left unused, and how far past the reset the pace carries. */
482  unused?: { left: TrackSeg[]; right: TrackSeg }
483}
484/** The width of the track's label column: "At your pace", "Left unused 57%". */
485export const TRACK_LABEL = 16
486
487/**
488 * The window as a line at your pace, for the terminal, `width` columns in all. Its first 70% runs to the
489 * reset (┤), at the same column on every card. Short, the line stops at ╳ where it runs out, the rest of the
490 * window dotted; lasting, it runs on past the reset in the unused colour as far as the pace carries,
491 * cut short with ▸ where that's beyond the pane. Null without an estimate.
492 */
493export function rangeTrack(m: Model, width: number): Track | null {
494  if (m.noData || !(m.left > 0)) return null
495  const T = Math.max(12, width - TRACK_LABEL - 1), R = Math.round(T * 0.7), O = T - R - 1
496  const label: TrackSeg = { text: 'At your pace'.padEnd(TRACK_LABEL), tone: 'dim' }
497  const reset: TrackSeg = { text: '┤', tone: 'dim' }
498  if (isShort(m)) {
499    const r = Math.max(1, Math.min(R - 1, Math.round(m.runsOutIn / m.left * R)))
500    const text = `${dur(m.early)} early`
501    return {
502      line: [label, { text: '━'.repeat(r - 1), tone: 'text' }, { text: '╳', tone: 'short' }, { text: '┄'.repeat(R - r), tone: 'faint' }, reset],
503      early: { indent: Math.max(0, TRACK_LABEL + r - text.length), text },
504    }
505  }
506  // at rate 0 it never runs out: the line runs on to the pane's edge
507  const past = m.runsOutIn - m.left
508  const want = isFinite(past) ? Math.max(0, Math.round(past / m.left * R)) : Infinity
509  const cut = want > O
510  const ext = cut ? O - 1 : want
511  return {
512    line: [label, { text: '━'.repeat(R), tone: 'ok' }, reset, { text: '━'.repeat(ext), tone: 'unused' }, ...(cut ? [{ text: '▸', tone: 'unused' } as TrackSeg] : [])],
513    unused: {
514      left: [{ text: 'Left unused ', tone: 'unused' }, { text: `${Math.round(m.arrive)}%`, tone: 'unusedBold' }],
515      right: { text: isFinite(past) ? `${dur(past)} past the reset` : 'lasts past the reset', tone: 'unused' },
516    },
517  }
518}
519
520/** Your pace against the safe pace, in words: what the chart's two lines show, for where there's no chart. */
521export function paceText(m: Model): string | null {
522  if (m.noData || !(m.limit > 0) || !(m.rate > 0)) return null
523  const x = m.rate / m.limit
524  return `Your pace is ${x >= 10 ? Math.round(x) : fx(x)}× the safe pace.`
525}
526
527// ---- drawing ----
528
529/** The card's colours, as CSS variables a chart's <style> sets from the person's theme (see theme.ts). */
530export const C = Object.fromEntries(
531  (['card', 'veil', 'fg', 'dim', 'off', 'barTop', 'barBottom', 'limit', 'over', 'under', 'bad', 'good', 'fable', 'opus', 'sonnet', 'haiku',
532    'surface', 'raised', 'inset', 'panel', 'line', 'muted', 'faint', 'accent', 'accentBg', 'badBg', 'solid'] as const).map(k => [k, v(k)]),
533) as Record<PaletteKey, string>
534/** The system's own sans, as the pane's design sets it; figures in it line up (tabular numbers, see `drawing`). */
535export const FONT = "Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
536export const MONO = FONT
537
538/**
539 * Every text style in the drawings, by role: size in rem (1rem = 16px), weight,
540 * and colour as a palette key, so it follows the theme. Change one here and
541 * the layout around it follows. A colour that carries state (the green or red
542 * figure, the limit line's label) stays that state's colour.
543 */
544export const TEXT: Record<Role, { rem: number; weight: number; color: PaletteKey; mono?: boolean }> = {
545  /** The card's title, "This week". */
546  title: { rem: 1.2, weight: 500, color: 'fg' },
547  /** The run-out warning under the title. */
548  warning: { rem: 0.85, weight: 400, color: 'over' },
549  /** A figure's caption: "Your pace", small and mono. */
550  caption: { rem: 0.6875, weight: 500, color: 'dim', mono: true },
551  /** A figure: "19.4% a day". */
552  figure: { rem: 0.9375, weight: 500, color: 'fg', mono: true },
553  /** The axes, the unit line and notes inside the plot. */
554  axis: { rem: 0.7, weight: 400, color: 'dim', mono: true },
555  /** The labels on the your-pace and safe-pace lines. */
556  line: { rem: 0.8125, weight: 500, color: 'fg', mono: true },
557  /** The reset countdown beside the title: "Resets in 6d 2h". */
558  countdown: { rem: 0.75, weight: 400, color: 'dim' },
559  /** The note under a card: "Average since the reset 23h ago, ...". */
560  note: { rem: 0.78, weight: 400, color: 'dim' },
561  /** A quiet figure beside the others, smaller and lighter: "Last window 28% to spare". */
562  aside: { rem: 0.8125, weight: 400, color: 'dim', mono: true },
563}
564type Role = 'title' | 'warning' | 'caption' | 'figure' | 'axis' | 'line' | 'countdown' | 'note' | 'aside'
565const px = (role: Role) => TEXT[role].rem * 16
566/** About how wide a text runs, for laying out around it: mono is 0.6em a character. */
567const textWidth = (str: string, role: Role) =>
568  str.length * px(role) * (TEXT[role].mono ? 0.6 : TEXT[role].weight >= 600 ? 0.62 : 0.58)
569export const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;')
570/**
571 * The width a drawing tells the app it has. The app shows each drawing in a
572 * frame as wide as its slot, up to this; inside, the drawing fills the frame
573 * (`:root{width:100%}`) and is laid out in percentages and pixels, never a
574 * viewBox, so it stretches to any width while its text stays the size set.
575 */
576const FRAME_W = 2000
577/** A drawing of `content`, `height` pixels tall, filling whatever width its frame has. */
578export function drawing(content: string, height: number, pal: Palettes = DEFAULT_PALETTES): string {
579  return `<svg xmlns="http://www.w3.org/2000/svg" width="${FRAME_W}" height="${Math.ceil(height)}"><style>:root{width:100%;height:100%;overflow:hidden}text{font-variant-numeric:tabular-nums}</style>${paletteStyle(pal)}${content}</svg>`
580}
581/** A drawing's height: what its frame is given. */
582export const drawingHeight = (svg: string) => Number(/^<svg [^>]* height="(\d+)">/.exec(svg)![1])
583/** A share of the width, as a length. */
584export const pct = (f: number) => `${(f * 100).toFixed(3)}%`
585/** Content placed with its origin at a share of the width (1: the right edge); it draws at negative x to sit left of it. */
586export const at = (f: number, content: string) => `<svg x="${pct(f)}" y="0" width="1" height="1" overflow="visible">${content}</svg>`
587
588/** A text in its role's style; `fill` and `weight` only where state sets them. */
589const text = (x: number | string, y: number, s: string, o: { role?: Role; fill?: string; anchor?: string; weight?: number; opacity?: number } = {}) => {
590  const t = TEXT[o.role ?? 'axis']
591  return `<text x="${typeof x === 'number' ? x.toFixed(1) : x}" y="${y.toFixed(1)}" text-anchor="${o.anchor ?? 'start'}" style="fill:${o.fill ?? C[t.color]}"${o.opacity !== undefined ? ` fill-opacity="${o.opacity}"` : ''} font-family="${t.mono ? MONO : FONT}" font-size="${t.rem}rem" font-weight="${o.weight ?? t.weight}">${esc(s)}</text>`
592}
593
594/**
595 * The card's head: the title, the run-out line when the projection goes over,
596 * and the three figures; given the last window, a quiet fourth one after them.
597 */
598/** Where the head's lines sit: the title, the warning, the captions and the figures, and its height. */
599function headLayout(m: Model, width: number, last?: LastWindow | null) {
600  const isOver = m.over && !m.noData
601  const title = px('title')
602  const warning = isOver ? title + px('warning') * 1.6 : title
603  const stats: Array<{ label: string; value: string; fill?: string; info: boolean; role: Role; opacity?: number; w: number; x: number; row: number }> = []
604  const add = (label: string, value: string, fill: string | undefined, o: { info?: boolean; role?: Role; opacity?: number } = {}) => {
605    const role = o.role ?? 'figure', info = !!o.info
606    stats.push({
607      label, value, ...(fill ? { fill } : {}), info, role, ...(o.opacity !== undefined ? { opacity: o.opacity } : {}),
608      w: Math.max(textWidth(label, 'caption') + (info ? px('caption') + 6 : 0), textWidth(value, role)), x: 0, row: 0,
609    })
610  }
611  // the left-at-reset figure is coloured by its state; the others take the figure role's colour
612  add(m.kind === 'week' ? 'At week reset' : 'At 5h reset', leftText(m), m.noData ? C.dim : m.over ? C.bad : C.good)
613  add('Your pace', m.noData ? 'No data' : rateText(m, m.rate), m.noData ? C.dim : undefined)
614  add('Safe pace', rateText(m, m.limit), undefined)
615  // the last window: smaller and lighter, in left-at-reset's colours but muted, its caption ending in an info circle
616  if (last) add(LAST_LABEL, lastWindowText(last), lastIsShort(last) ? C.bad : C.good, { info: true, role: 'aside', opacity: 0.7 })
617  // the figures flow left to right, onto another row where the card is too narrow for the next
618  const gap = px('figure') * 1.5
619  let x = 0, row = 0
620  for (const st of stats) {
621    if (x > 0 && x + st.w > width) { x = 0; row++ }
622    st.x = x; st.row = row
623    x += st.w + gap
624  }
625  const step = px('caption') * 1.6 + px('figure') * 1.5 + 6
626  const caption = (r: number) => warning + px('caption') * 2 + r * step
627  const figure = (r: number) => caption(r) + px('figure') * 1.5
628  return { isOver, title, warning, stats, caption, figure, height: Math.ceil(figure(row) + px('figure') * 0.4) }
629}
630
631/** Where the head's info circle sits, in drawn pixels: what the drawing around it places the tooltip by. */
632export type InfoSpot = { cx: number; cy: number; r: number }
633
634/**
635 * The head: title, warning, the figures, and the countdown. Given the last
636 * window, a quiet fourth figure "Last window" whose caption ends in an info
637 * circle; the circle itself is drawn by `withInfo`, which can open its
638 * tooltip over the chart.
639 */
640export function headerDraw(m: Model, title: string, width: number, pal: Palettes = DEFAULT_PALETTES, countdown = '', last?: LastWindow | null): { svg: string; height: number; info?: InfoSpot } {
641  const L = headLayout(m, width, last)
642  let s = text(0, L.title, title, { role: 'title' })
643  if (L.isOver) s += text(0, L.warning, runsOut(m), { role: 'warning' })
644  // the countdown sits at the right on the title's line
645  if (countdown) s += text('100%', L.title, countdown, { role: 'countdown', anchor: 'end' })
646  let spot: InfoSpot | undefined
647  for (const st of L.stats) {
648    s += text(st.x, L.caption(st.row), st.label, { role: 'caption' })
649    s += text(st.x, L.figure(st.row), st.value, { role: st.role, ...(st.fill ? { fill: st.fill } : {}), ...(st.opacity !== undefined ? { opacity: st.opacity } : {}) })
650    if (st.info) {
651      // the circle after the caption
652      const r = px('caption') * 0.5
653      spot = { cx: st.x + textWidth(st.label, 'caption') + 6 + r, cy: L.caption(st.row) - px('caption') * 0.35, r }
654    }
655  }
656  return { svg: drawing(s, L.height, pal), height: L.height, ...(spot ? { info: spot } : {}) }
657}
658export const headerSvg = (m: Model, title: string, width: number, pal: Palettes = DEFAULT_PALETTES, countdown = '', last?: LastWindow | null) =>
659  headerDraw(m, title, width, pal, countdown, last).svg
660
661/**
662 * Moves labels apart so none overlap: each sits as near its own line as it can.
663 * Labels that would collide are grouped and centred on their lines' average,
664 * then the whole stack is kept between `lo` and `hi`. `ys` are the lines'
665 * heights; the result is in the same order.
666 */
667export function spreadLabels(ys: readonly number[], gap: number, lo: number, hi: number): number[] {
668  const order = ys.map((y, i) => ({ y, i })).sort((a, b) => a.y - b.y)
669  // clusters of labels that share space, each centred on its members' lines
670  let groups = order.map(o => ({ members: [o], top: o.y }))
671  const place = (g: { members: { y: number }[] }) =>
672    g.members.reduce((a, m) => a + m.y, 0) / g.members.length - (g.members.length - 1) * gap / 2
673  for (let changed = true; changed;) {
674    changed = false
675    for (let k = 1; k < groups.length; k++) {
676      const a = groups[k - 1]!, b = groups[k]!
677      if (a.top + a.members.length * gap > b.top) {
678        const merged = { members: [...a.members, ...b.members], top: 0 }
679        merged.top = place(merged)
680        groups.splice(k - 1, 2, merged)
681        changed = true
682        break
683      }
684    }
685  }
686  const out = new Array<number>(ys.length)
687  const flat: { i: number; y: number }[] = []
688  for (const g of groups) g.members.forEach((m, j) => flat.push({ i: (m as { i: number }).i, y: g.top + j * gap }))
689  // keep the stack inside the plot, pushing neighbours along
690  for (let k = 0; k < flat.length; k++) flat[k]!.y = Math.max(flat[k]!.y, lo + k * gap)
691  for (let k = flat.length - 1; k >= 0; k--) flat[k]!.y = Math.min(flat[k]!.y, hi - (flat.length - 1 - k) * gap)
692  for (const f of flat) out[f.i] = f.y
693  return out
694}
695
696export type ChartSpec = {
697  width: number
698  height: number
699  bars: number[]
700  /** The average, or null with no estimate: then no dotted line. */
701  avg: number | null
702  limit: number
703  xTicks: Array<{ f: number; label: string }>
704  marks: Array<{ f: number; label: string }>
705  /** The share of the chart, from the left, before recording began with nothing known of it: lightly tinted. */
706  unrecorded: number
707  /**
708   * Stretches whose usage is known only as a total (before recording began,
709   * or while this computer wasn't watching): each one low block at the rate
710   * that total comes to, labelled with it. Shares of the chart, the rate per
711   * bar unit, and a long and a short label.
712   */
713  blocks: Array<{ f0: number; f1: number; rate: number; label: string; short: string }>
714  /** The theme's palettes; absent, the default dark theme's. */
715  palettes?: Palettes
716}
717
718/**
719 * Bars from the average's start to Now in a framed plot, scaled to the tallest
720 * bar, with the average (dotted) and limit (solid) lines across all of them.
721 * Recorded slices with no usage show as a dashed baseline. A limit above the
722 * tallest bar sits on the top edge, its label marked ▲.
723 */
724export function chartSvg(c: ChartSpec): string {
725  const est = c.width, Hh = c.height
726  const ax = px('axis')
727  const padT = Math.ceil(ax * 0.8 + 6), padB = Math.ceil(ax * 1.5 + 12)
728  const peak = Math.max(...c.bars, c.avg ?? 0, ...c.blocks.map(b => b.rate), 0.0001) * 1.04
729  const top = peak >= 10 ? Math.ceil(peak / 2) * 2 : peak
730  const Y = (v: number) => Hh - padB - Math.min(v, top) / top * (Hh - padT - padB)
731  const base = Y(0)
732  const num = (v: number) => (top >= 10 ? String(Math.round(v)) : fx(v))
733  const veil = (x: number, y: number, w: number, h: number, r = 5) =>
734    `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${w.toFixed(1)}" height="${h.toFixed(1)}" rx="${r}" style="fill:${C.veil}" fill-opacity="0.6"/>`
735  let s = `<defs>
736    <linearGradient id="bar" x1="0" y1="0" x2="0" y2="1"><stop offset="0" style="stop-color:${C.barTop}"/><stop offset="1" style="stop-color:${C.barBottom}"/></linearGradient>
737    <linearGradient id="plot" x1="0" y1="1" x2="0" y2="0"><stop offset="0" style="stop-color:${C.dim}" stop-opacity="0"/><stop offset="1" style="stop-color:${C.dim}" stop-opacity="0.07"/></linearGradient>
738  </defs>`
739  s += `<rect x="0" y="${padT}" width="100%" height="${base - padT}" rx="6" fill="url(#plot)"/>`
740  for (const g of [top / 4, top / 2, top * 3 / 4]) {
741    s += `<line x1="0" x2="100%" y1="${Y(g)}" y2="${Y(g)}" style="stroke:${C.dim}" stroke-opacity="0.18"/>`
742  }
743  for (const tk of c.xTicks) {
744    if (tk.f > 0 && tk.f < 1) s += `<line x1="${pct(tk.f)}" x2="${pct(tk.f)}" y1="${padT}" y2="${base}" style="stroke:${C.dim}" stroke-opacity="0.18" stroke-dasharray="4 4"/>`
745    const isNow = tk.f >= 1
746    s += text(pct(tk.f), Hh - ax * 0.6, tk.label, { anchor: isNow ? 'end' : tk.f <= 0 ? 'start' : 'middle', ...(isNow ? { fill: C.fg, weight: 600 } : {}) })
747  }
748  if (c.unrecorded > 0) {
749    s += `<rect x="0" y="${padT}" width="${pct(c.unrecorded)}" height="${base - padT}" style="fill:${C.dim}" fill-opacity="0.06"/>`
750    if (c.unrecorded * est > textWidth('not recorded', 'axis') + 16) s += text(pct(c.unrecorded / 2), base - ax * 0.6, 'not recorded', { anchor: 'middle' })
751  }
752  let late = ''   // labels drawn last, over the bars and lines
753  // each stretch known only as a total: one low block at the rate it comes to, its line on top, and what's known as its label
754  for (const b of c.blocks) {
755    const y = Y(b.rate), room = (b.f1 - b.f0) * est
756    s += `<rect x="${pct(b.f0)}" y="${y.toFixed(1)}" width="${pct(b.f1 - b.f0)}" height="${(base - y).toFixed(1)}" style="fill:${C.barBottom}" fill-opacity="0.22"/>`
757    s += `<line x1="${pct(b.f0)}" x2="${pct(b.f1)}" y1="${y.toFixed(1)}" y2="${y.toFixed(1)}" style="stroke:${C.barBottom}" stroke-width="1.5"/>`
758    // above the line, or just inside it when the line is near the top
759    const ly = y - 6 - ax < padT ? y + ax + 4 : y - 6
760    const fits = (l: string) => textWidth(l, 'axis') + 8 <= room
761    const label = fits(b.label) ? b.label : fits(b.short) ? b.short : null
762    // on a backing, so a line crossing it doesn't run through the words
763    const tag = (x: number, l: string, anchor: 'middle' | 'start') => {
764      const w = textWidth(l, 'axis') + 10, bx = anchor === 'middle' ? x - w / 2 : x - 5
765      return `<rect x="${bx.toFixed(1)}" y="${(ly - ax).toFixed(1)}" width="${w.toFixed(1)}" height="${(ax + 5).toFixed(1)}" rx="4" style="fill:${C.veil}" fill-opacity="0.6"/>` + text(x, ly, l, { anchor, fill: C.fg })
766    }
767    if (label) late += at((b.f0 + b.f1) / 2, tag(0, label, 'middle'))
768    // too narrow to hold even the short one: it starts at the block and runs right, where there's room
769    else if (textWidth(b.short, 'axis') + 8 <= (1 - b.f0) * est) late += at(b.f0, tag(9, b.short, 'start'))
770  }
771  for (const mk of c.marks) {
772    s += `<line x1="${pct(mk.f)}" x2="${pct(mk.f)}" y1="${padT}" y2="${base}" style="stroke:${C.dim}" stroke-dasharray="3 3"/>`
773    const w = textWidth(`↺ ${mk.label}`, 'axis') + 12, h = ax + 6
774    // near the right edge the label goes on the left of its line, clear of the line labels
775    const rx = mk.f * est + 3 + w > est - 190 ? -3 - w : 3
776    late += at(mk.f, veil(rx, padT + 4, w, h) + text(rx + 6, padT + 4 + h / 2 + ax * 0.35, `↺ ${mk.label}`, { fill: C.fg }))
777  }
778  // the scale, inside the plot at its left, on a backing so bars don't run through it
779  for (const g of [top / 2, top]) {
780    const y = Y(g) + ax + 4, label = num(g)
781    late += veil(4, y - ax - 1, textWidth(label, 'axis') + 8, ax + 6, 4) + text(8, y, label)
782  }
783  const n = Math.max(1, c.bars.length)
784  // a recorded slice with no usage shows a dashed baseline; one inside a block or before recording doesn't
785  const covered = (f: number) => f < c.unrecorded || c.blocks.some(b => f >= b.f0 && f <= b.f1)
786  const bar = (i: number, v: number) => {
787    const y = Y(v)
788    return `<rect x="${pct((i + 0.25) / n)}" y="${y.toFixed(1)}" width="${pct(0.5 / n)}" height="${Math.max(0, base - y).toFixed(1)}" rx="1.5" fill="url(#bar)"/>`
789  }
790  c.bars.forEach((v, i) => {
791    if (v > 0) s += bar(i, v)
792    else if (!covered((i + 0.5) / n)) {
793      s += `<line x1="${pct(i / n)}" x2="${pct((i + 1) / n)}" y1="${base - 1}" y2="${base - 1}" style="stroke:${C.barBottom}" stroke-width="1.5" stroke-dasharray="5 4"/>`
794    }
795  })
796  const limitOff = c.limit > top
797  const yl = limitOff ? Y(top) : Y(c.limit)
798  const ya = c.avg !== null ? Y(c.avg) : null
799  s += `<line x1="0" x2="100%" y1="${yl}" y2="${yl}" style="stroke:${C.limit}" stroke-width="2.5"/>`
800  if (ya !== null) s += `<line x1="0" x2="100%" y1="${ya}" y2="${ya}" style="stroke:${C.fg}" stroke-width="3" stroke-dasharray="3 5" stroke-linecap="round"/>`
801  // the labels sit on their lines at the right edge, each on a backing so bars and lines behind don't show through
802  const label = (y: number, s2: string, fill?: string) => {
803    const w = textWidth(s2, 'line') + 16, h = px('line') + 8
804    return at(1, veil(-4 - w, y - h / 2, w, h, 6) + text(-12, y + px('line') * 0.35, s2, { role: 'line', anchor: 'end', ...(fill ? { fill } : {}) }))
805  }
806  // keep the labels clear of each other and inside the plot
807  const [lY, aY] = spreadLabels(ya === null ? [yl] : [yl, ya], px('line') + 12, padT + px('line') / 2 + 6, base - px('line') / 2 - 6)
808  s += late
809  s += label(lY!, `safe pace ${fx(c.limit)}${limitOff ? ' ▲' : ''}`, C.limit)
810  if (aY !== undefined && c.avg !== null) s += label(aY, `your pace ${fx(c.avg)}`)
811  return drawing(s, Hh, c.palettes ?? DEFAULT_PALETTES)
812}
813/** The weekly chart for model `m` at `now`. */
814export function weekChart(m: Model, now: number, width: number, pal: Palettes = DEFAULT_PALETTES, height = 400): string {
815  return timeChart(m, now, width, height, pal)
816}
817
818/** The 5-hour chart: the window since it opened. */
819export function fiveChart(m: Model, now: number, width: number, pal: Palettes = DEFAULT_PALETTES, height = 300): string {
820  return timeChart(m, now, width, height, pal)
821}
822
823/**
824 * Recorded usage a chart needs before its bars mean anything: the weekly
825 * figure moves in steps of about a point, so it needs hours to show a shape;
826 * the 5-hour one, half an hour.
827 */
828export const CHART_NEEDS_H = { week: 6, five: 0.5 }
829
830/** Hours until the chart has enough recorded behind it; 0 once it has. */
831export const chartWait = (m: Model, now: number) => Math.max(0, CHART_NEEDS_H[m.kind] - (now - m.recordedFrom) / HOUR)
832
833
834/**
835 * What the empty state says in the chart's place, or null when there is a
836 * chart to draw: an average that can't be worked out yet (a window shorter
837 * than the least, or longer than the record; too soon after the reset), or a
838 * record too short for the bars to show a shape.
839 */
840export function emptyChartText(m: Model, now: number): [string, string] | null {
841  const name = m.kind === 'week' ? 'Weekly' : '5-hour'
842  const recordedH = (now - m.recordedFrom) / HOUR
843  const avg = m.average
844  if (avg.type === 'hours' && avg.hours < MIN_RECORDED_H[m.kind]) {
845    return [`${name} averages need at least ${dur(MIN_RECORDED_H[m.kind])}`, `Pick a window of ${dur(MIN_RECORDED_H[m.kind])} or more, or Since reset.`]
846  }
847  if (avg.type === 'hours' && avg.hours > recordedH) {
848    return [`Needs ${dur(avg.hours)} of recorded usage`, `About ${dur(avg.hours - recordedH)} to go. ${dur(recordedH)} recorded so far.`]
849  }
850  if (m.noData) return ['No estimate yet', m.noData]
851  const wait = chartWait(m, now)
852  if (wait > 0) return [`Chart in about ${dur(wait)}`, `It shows once ${dur(CHART_NEEDS_H[m.kind])} of usage is recorded. The figures above already count.`]
853  return null
854}
855
856/** In the chart's place until it has enough behind it: what it waits for, and how long that takes. */
857function emptyLayout(m: Model, now: number, width: number) {
858  const [head, sub] = emptyChartText(m, now) ?? ['', '']
859  const lines = wrap(sub, Math.max(160, width - 32), 'note')
860  const top = 24 + px('caption')
861  return { head, lines, top, height: Math.ceil(top + 10 + linesHeight(lines.length, 'note') + 18) }
862}
863
864
865export function emptyChartSvg(m: Model, now: number, width: number, pal: Palettes = DEFAULT_PALETTES): string {
866  const L = emptyLayout(m, now, width), H = L.height
867  // a dashed box edge to edge: its right side drawn from the right edge in
868  const dash = `style="stroke:${C.dim}" stroke-opacity="0.35" stroke-dasharray="4 5"`
869  const s = `<line x1="1" x2="100%" y1="1" y2="1" ${dash}/><line x1="1" x2="100%" y1="${H - 1}" y2="${H - 1}" ${dash}/>`
870    + `<line x1="1" x2="1" y1="1" y2="${H - 1}" ${dash}/>` + at(1, `<line x1="-1" x2="-1" y1="1" y2="${H - 1}" ${dash}/>`)
871    + text('50%', L.top, L.head, { role: 'caption', anchor: 'middle', fill: C.fg })
872    + L.lines.map((l, i) => text('50%', L.top + 10 + baseline(i, 'note'), l, { role: 'note', anchor: 'middle' })).join('')
873  return drawing(s, H, pal)
874}
875/** Text broken into lines that fit `width` in a role's style; paragraphs split on newlines. */
876function wrap(note: string, width: number, role: Role): string[] {
877  const lines: string[] = []
878  for (const para of note.split('\n')) {
879    let first = true
880    for (const word of para.split(' ')) {
881      const last = lines[lines.length - 1]
882      if (!first && last !== undefined && textWidth(`${last} ${word}`, role) <= width) lines[lines.length - 1] = `${last} ${word}`
883      else lines.push(word)
884      first = false
885    }
886  }
887  return lines
888}
889/** A wrapped line's baseline, and the height `n` lines take. */
890const baseline = (i: number, role: Role) => (i + 1) * px(role) * 1.4 - px(role) * 0.3
891const linesHeight = (n: number, role: Role) => Math.ceil(n * px(role) * 1.4 + px(role) * 0.3)
892
893/** Text in a role's style, wrapped to `width`. `fill` where state sets the colour. */
894export function noteSvg(note: string, width: number, pal: Palettes = DEFAULT_PALETTES, role: Role = 'note', fill?: string): string {
895  const lines = wrap(note, width, role), H = linesHeight(lines.length, role)
896  return drawing(lines.map((l, i) => text(0, baseline(i, role), l, { role, ...(fill ? { fill } : {}) })).join(''), H, pal)
897}
898
899/**
900 * The head and the chart (or its empty state) as one drawing, so the head's
901 * info circle can open its tooltip over the chart. A click or the pointer on
902 * the circle opens it, a click elsewhere closes it: no script, the circle
903 * takes focus on a click and CSS shows the box while it has focus or the
904 * pointer. Drawn interactive for that.
905 */
906export function withInfo(head: { svg: string; height: number; info?: InfoSpot }, chart: string, tip: string, width: number, pal: Palettes = DEFAULT_PALETTES, label = 'What is this?'): string {
907  const inner = (svg: string) => /^<svg [^>]*>([\s\S]*)<\/svg>$/.exec(svg)![1]!
908  const hH = drawingHeight(head.svg), cH = drawingHeight(chart), gap = 10
909  const nest = (svg: string, y: number, h: number) => `<svg x="0" y="${y}" width="100%" height="${h}" overflow="visible">${inner(svg)}</svg>`
910  let H = hH + gap + cH, over = ''
911  if (head.info) {
912    const { cx, cy, r } = head.info
913    const boxW = Math.min(width, 440), pad = 12
914    const lines = wrap(tip, boxW - pad * 2, 'note')
915    const boxH = linesHeight(lines.length, 'note') + pad * 2 - px('note') * 0.3
916    // the box opens just under the circle and ends at it, so it stays inside the card whatever its real width
917    const bx = Math.max(0, cx + r + 4 - boxW), by = cy + r + 8
918    H = Math.max(H, Math.ceil(by + boxH + 2))
919    const info = `<g class="info" tabindex="0" role="button" aria-label="${esc(label)}">`
920      + `<circle cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${(r + 4).toFixed(1)}" fill="transparent"/>`
921      + `<circle cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r.toFixed(1)}" fill="transparent" style="stroke:${C.dim}" stroke-width="1.2"/>`
922      + `<text x="${cx.toFixed(1)}" y="${(cy + r * 0.55).toFixed(1)}" text-anchor="middle" style="fill:${C.dim}" font-family="${FONT}" font-size="${(r * 1.5).toFixed(1)}" font-weight="600">i</text></g>`
923    const box = `<g class="tip"><rect x="${bx.toFixed(1)}" y="${by.toFixed(1)}" width="${boxW}" height="${boxH.toFixed(1)}" rx="8" style="fill:${C.veil};stroke:${C.dim}" fill-opacity="0.94" stroke-opacity="0.4"/>`
924      + lines.map((l, i) => text(bx + pad, by + pad + baseline(i, 'note') - px('note') * 0.15, l, { role: 'note', fill: C.fg })).join('') + `</g>`
925    const css = `<style>.info{cursor:pointer;outline:none}.info:hover circle+circle,.info:focus circle+circle{stroke:var(--fg)}.info:hover text,.info:focus text{fill:var(--fg)}`
926      + `.tip{display:none}.info:hover~.tip,.info:focus~.tip{display:inline}</style>`
927    over = css + info + box
928  }
929  return drawing(nest(head.svg, 0, hH) + nest(chart, hH + gap, cH) + over, H, pal)
930}
931
932// ---- fitting the pane ----
933
934/**
935 * A cell of the desktop's code font in CSS pixels, as measured in the Code
936 * tab: the pane reports its width in these cells, the drawings are in pixels.
937 */
938export const CELL_PX = { w: 9.5, h: 19 }
939
940export type Fit = { width: number; weekHeight: number; fiveHeight: number }
941
942/** Chart heights: a share of the card's width, within bounds. */
943const CHART_H = { week: { ratio: 0.55, min: 260, max: 440 }, five: { ratio: 0.42, min: 200, max: 340 } }
944
945/**
946 * Sizes the drawings for a pane `columns` wide: the card's inner width, for
947 * what wraps, and each chart's height, which follows that width.
948 */
949export function fit(columns: number): Fit {
950  // the card's inner width: the pane less the card's padding and edge. Drawings fill whatever width they get;
951  // this is for laying out what wraps (figures, notes) and for the charts' heights
952  const width = Math.max(240, Math.floor((columns - 6) * CELL_PX.w))
953  // the pane's reported rows don't follow its real height in the desktop app, so the charts' heights
954  // follow the card's width instead: a wider card, a taller chart, within bounds
955  const tall = (k: 'week' | 'five') => Math.round(Math.min(CHART_H[k].max, Math.max(CHART_H[k].min, width * CHART_H[k].ratio)))
956  return { width, weekHeight: tall('week'), fiveHeight: tall('five') }
957}
958
959/** The least a chart is drawn at to fit the pane's height: below this it stops being readable, and the pane scrolls. */
960const CHART_MIN_FIT = { week: 200, five: 160 }
961
962/**
963 * The charts' heights fitted to the pane's height: `budget` pixels are what's
964 * left for the two charts once everything else is placed. They share it in
965 * their width-based proportions, growing into spare room up to CHART_H's
966 * max, shrinking in a short pane down to CHART_MIN_FIT, below which it scrolls.
967 */
968export function fitHeight(f: Fit, budget: number): Fit {
969  const total = f.weekHeight + f.fiveHeight
970  const share = (k: 'week' | 'five', h: number) => Math.round(Math.min(CHART_H[k].max, Math.max(CHART_MIN_FIT[k], (budget * h) / total)))
971  return { ...f, weekHeight: share('week', f.weekHeight), fiveHeight: share('five', f.fiveHeight) }
972}
973const pctText = (v: number) => (v > 0 && v < 1 ? '<1%' : `${Math.round(v)}%`)
974
975/**
976 * The chart's stretches known only as a total: before recording began (the
977 * first reading's figure, since the reset), and each gap this computer wasn't
978 * watching. A weekly gap's rise could have come anywhere in it, so its block
979 * spans the gap; a 5-hour one belongs to the window it was seen in, so its
980 * block starts no earlier than the window opened.
981 */
982function knownBlocks(m: Model, now: number, perHours: number): ChartSpec['blocks'] {
983  const span = now - m.from, out: ChartSpec['blocks'] = []
984  const add = (a: number, b: number, amount: number, what: (p: string, h: string) => [string, string]) => {
985    const v0 = Math.max(a, m.from), v1 = Math.min(b, now)
986    if (v1 <= v0 || amount <= 0) return
987    const shown = amount * (v1 - v0) / (b - a), hours = (v1 - v0) / HOUR
988    const [label, short] = what(pctText(shown), dur(hours))
989    out.push({ f0: (v0 - m.from) / span, f1: (v1 - m.from) / span, rate: shown / hours * perHours, label, short })
990  }
991  if (m.before) add(m.from, m.before.until, m.before.pct, p => [`${p} before tracking`, p])
992  for (const inc of m.increments) {
993    if (!inc.hole) continue
994    add(m.kind === 'week' ? inc.hole[0] : inc.start, inc.end, inc.amount, (p, h) => [`${p} used while away, ${h}`, `${p} · ${h}`])
995  }
996  return out
997}
998
999function timeChart(m: Model, now: number, width: number, height: number, palettes: Palettes): string {
1000  const isWeek = m.kind === 'week'
1001  const values = bars(m, now, bucketMinutes(m.winH * 60), isWeek ? 24 : 1)
1002  const ago = (h: number) => h >= 48 ? `−${Math.round(h / 24)}d` : h >= 2 ? `−${Math.round(h)}h` : `−${Math.round(h * 60)}m`
1003  // the axis keeps one unit across, picked by the window's length
1004  const tick = (h: number) => m.winH >= 48 ? `−${fx(h / 24, h / 24 < 10 && h % 24 ? 1 : 0)}d`
1005    : m.winH >= 2 ? `−${Math.round(h * 10) % 10 && h < 5 ? fx(h) : Math.round(h)}h`
1006    : `−${Math.round(h * 60)}m`
1007  const perHours = isWeek ? 24 : 1
1008  const marks: ChartSpec['marks'] = []
1009  for (let k = 0; isWeek && k < 4; k++) {
1010    const at = m.resetsAt - (k + 1) * SPAN.week
1011    if (at > m.from && at < now) marks.push({ f: (at - m.from) / (now - m.from), label: `reset ${ago((now - at) / HOUR)}` })
1012  }
1013  return chartSvg({
1014    width, height, bars: values, avg: m.noData ? null : m.rate * (isWeek ? 24 : 1), limit: m.limit * (isWeek ? 24 : 1),
1015    xTicks: [0, 0.25, 0.5, 0.75].map(f => ({ f, label: tick(m.winH * (1 - f)) })).concat({ f: 1, label: 'Now' }),
1016    marks,
1017    unrecorded: m.before ? 0 : Math.min(1, Math.max(0, (m.recordedFrom - m.from) / (now - m.from))),
1018    blocks: knownBlocks(m, now, perHours),
1019    palettes,
1020  })
1021}
1022
hooks/theme.ts 246 lines
1/**
2 * The card's colours, derived from the person's Claude Code theme rather than
3 * fixed: the theme's own tokens (text, inactive, claude, success, ...) set the
4 * palette, so a custom theme, or a mod that ships one, carries over to the charts.
5 *
6 * The charts are SVG images, which can't name theme keys the way a Text can,
7 * so each chart carries the palette as CSS variables: one set for a dark
8 * appearance and one for a light, chosen by `prefers-color-scheme`.
9 */
10import type { Palette, Palettes } from '../types'
11
12/** The theme tokens the palette is made from. */
13export type Tokens = {
14  text: string; inverseText: string; inactive: string; subtle: string; userMessageBackground: string
15  claude: string; success: string; error: string; warning: string; suggestion: string
16}
17const TOKEN_KEYS = ['text', 'inverseText', 'inactive', 'subtle', 'userMessageBackground', 'claude', 'success', 'error', 'warning', 'suggestion'] as const
18/** Tokens a theme gives its own hue: kept in the other appearance too. */
19const ACCENTS = ['claude', 'success', 'error', 'warning', 'suggestion'] as const
20
21/** Claude Code's built-in presets, as far as the palette needs them. */
22const DARK: Tokens = {
23  text: 'rgb(255,255,255)', inverseText: 'rgb(0,0,0)', inactive: 'rgb(153,153,153)', subtle: 'rgb(80,80,80)', userMessageBackground: 'rgb(55,55,55)',
24  claude: 'rgb(215,119,87)', success: 'rgb(78,186,101)', error: 'rgb(255,107,128)', warning: 'rgb(255,193,7)', suggestion: 'rgb(177,185,249)',
25}
26const LIGHT: Tokens = {
27  text: 'rgb(0,0,0)', inverseText: 'rgb(255,255,255)', inactive: 'rgb(102,102,102)', subtle: 'rgb(175,175,175)', userMessageBackground: 'rgb(240,240,240)',
28  claude: 'rgb(215,119,87)', success: 'rgb(44,122,57)', error: 'rgb(171,43,63)', warning: 'rgb(150,108,30)', suggestion: 'rgb(87,105,247)',
29}
30export const PRESETS: Record<string, Tokens> = {
31  dark: DARK,
32  light: LIGHT,
33  'dark-daltonized': { ...DARK, success: 'rgb(51,153,255)', error: 'rgb(255,102,102)', warning: 'rgb(255,204,0)' },
34  'light-daltonized': { ...LIGHT, success: 'rgb(0,102,153)', error: 'rgb(204,0,0)', warning: 'rgb(255,153,51)' },
35  'dark-ansi': { ...DARK, text: 'ansi:whiteBright', inactive: 'ansi:white', subtle: 'ansi:blackBright', claude: 'ansi:redBright', success: 'ansi:greenBright', error: 'ansi:redBright', warning: 'ansi:yellowBright', suggestion: 'ansi:blueBright' },
36  'light-ansi': { ...LIGHT, text: 'ansi:black', inactive: 'ansi:blackBright', subtle: 'ansi:white', claude: 'ansi:red', success: 'ansi:green', error: 'ansi:red', warning: 'ansi:yellow', suggestion: 'ansi:blue' },
37}
38
39/** A theme as the setting and its file describe it: which preset it builds on, and what it changes. */
40export type Theme = { base: string; overrides: Partial<Tokens> }
41
42const isDark = (base: string) => !base.startsWith('light')
43/** The preset of the other appearance, of the same kind (plain, daltonized, ansi). */
44const counterpart = (base: string) => (isDark(base) ? base.replace(/^dark/, 'light') : base.replace(/^light/, 'dark'))
45
46/** Reads a theme file's `{ base, overrides }`, keeping only tokens the palette uses and colours that parse. */
47export function parseThemeFile(json: unknown): Theme {
48  const o = (json ?? {}) as { base?: unknown; overrides?: Record<string, unknown> }
49  const base = typeof o.base === 'string' && PRESETS[o.base] ? o.base : 'dark'
50  const overrides: Partial<Tokens> = {}
51  for (const k of TOKEN_KEYS) {
52    const v = o.overrides?.[k]
53    if (typeof v === 'string' && parseColor(v)) overrides[k] = v
54  }
55  return { base, overrides }
56}
57
58/**
59 * The tokens for each appearance. The theme's own appearance takes the theme
60 * whole; the other takes its counterpart preset with the theme's accents, so
61 * the hues it chose carry over while text and background suit that appearance.
62 * `auto` has no appearance of its own: each takes its plain preset.
63 */
64export function tokensFor(theme: Theme | 'auto'): { dark: Tokens; light: Tokens } {
65  if (theme === 'auto') return { dark: DARK, light: LIGHT }
66  const own = { ...PRESETS[theme.base] ?? DARK, ...theme.overrides }
67  const accents: Partial<Tokens> = {}
68  for (const k of ACCENTS) if (theme.overrides[k]) accents[k] = theme.overrides[k]
69  const other = { ...PRESETS[counterpart(theme.base)] ?? LIGHT, ...accents }
70  return isDark(theme.base) ? { dark: own, light: other } : { dark: other, light: own }
71}
72
73// ---- colours ----
74
75type RGB = [number, number, number]
76
77const ANSI: Record<string, RGB> = {
78  black: [0, 0, 0], red: [205, 49, 49], green: [13, 188, 121], yellow: [229, 229, 16], blue: [36, 114, 200], magenta: [188, 63, 188], cyan: [17, 168, 205], white: [229, 229, 229],
79  blackBright: [102, 102, 102], redBright: [241, 76, 76], greenBright: [35, 209, 139], yellowBright: [245, 245, 67], blueBright: [59, 142, 234], magentaBright: [214, 112, 214], cyanBright: [41, 184, 219], whiteBright: [255, 255, 255],
80}
81const ANSI_ORDER = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] as const
82
83/** Parses the colours a theme file takes: `#rrggbb`, `#rgb`, `rgb(r,g,b)`, `ansi256(n)`, `ansi:<name>`. */
84export function parseColor(s: string): RGB | null {
85  const t = s.trim()
86  let m = /^#([0-9a-f]{6})$/i.exec(t)
87  if (m) { const n = parseInt(m[1]!, 16); return [n >> 16, (n >> 8) & 255, n & 255] }
88  m = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(t)
89  if (m) return [m[1]!, m[2]!, m[3]!].map(h => parseInt(h + h, 16)) as RGB
90  m = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i.exec(t)
91  if (m) return [m[1]!, m[2]!, m[3]!].map(v => Math.min(255, Number(v))) as RGB
92  m = /^ansi256\(\s*(\d{1,3})\s*\)$/i.exec(t)
93  if (m) return ansi256(Number(m[1]))
94  m = /^ansi:(\w+)$/i.exec(t)
95  if (m) return ANSI[m[1]!] ?? null
96  return null
97}
98
99function ansi256(n: number): RGB | null {
100  if (n < 0 || n > 255) return null
101  if (n < 16) return ANSI[(n < 8 ? ANSI_ORDER[n] : `${ANSI_ORDER[n - 8]}Bright`)!] ?? null
102  if (n >= 232) { const v = 8 + (n - 232) * 10; return [v, v, v] }
103  const i = n - 16, step = (c: number) => (c === 0 ? 0 : 55 + c * 40)
104  return [step(Math.floor(i / 36)), step(Math.floor(i / 6) % 6), step(i % 6)]
105}
106
107const hex = (c: RGB) => '#' + c.map(v => Math.round(v).toString(16).padStart(2, '0')).join('')
108/** `a` moved toward `b` by `t` (0 = a, 1 = b). */
109const mix = (a: RGB, b: RGB, t: number): RGB => [0, 1, 2].map(i => a[i]! + (b[i]! - a[i]!) * t) as RGB
110
111const luminance = (c: RGB) => {
112  const ch = (v: number) => { const s = v / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4 }
113  return 0.2126 * ch(c[0]) + 0.7152 * ch(c[1]) + 0.0722 * ch(c[2])
114}
115export const contrast = (a: RGB, b: RGB) => {
116  const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p)
117  return (x! + 0.05) / (y! + 0.05)
118}
119/** `c` as it is, or moved toward `toward` just enough to reach `min` contrast on `bg`. */
120function legible(c: RGB, bg: RGB, toward: RGB, min: number): RGB {
121  for (let t = 0; t <= 1; t += 0.05) {
122    const x = mix(c, toward, t)
123    if (contrast(x, bg) >= min) return x
124  }
125  return toward
126}
127
128// ---- the palette ----
129
130export type PaletteKey = keyof Palette
131
132/** The design's inks for each appearance: what the built-in presets draw with. */
133type Inks = Pick<Palette, 'fg' | 'muted' | 'faint' | 'accent' | 'good' | 'solid' | 'fable' | 'opus' | 'sonnet' | 'haiku'>
134const DESIGN: { dark: Inks; light: Inks } = {
135  dark: { fg: '#f2efeb', muted: '#aaa7a3', faint: '#8e8a85', accent: '#df9a7c', good: '#86c294', solid: '#a9a5a0', fable: '#cdb39c', opus: '#df9a7c', sonnet: '#b9ada1', haiku: '#999590' },
136  light: { fg: '#302e2b', muted: '#716b64', faint: '#807970', accent: '#a85f42', good: '#3f7d4c', solid: '#aaa197', fable: '#8f6a52', opus: '#a85f42', sonnet: '#827365', haiku: '#8d8780' },
137}
138/**
139 * The design's tones within a card, as overlays on whatever the card is: a raised chip, the panel inside a
140 * card, the inset strip under it, a hairline. Overlays, so they sit right on the app's own card colour.
141 */
142const TONES = {
143  dark: { raised: '#ffffff14', panel: '#ffffff0b', inset: '#0000002e', line: '#ffffff1c' },
144  light: { raised: '#0000000f', panel: '#00000008', inset: '#00000009', line: '#0000001a' },
145}
146
147const same = (a: RGB, b: RGB) => a.every((v, i) => Math.abs(v - b[i]!) < 1)
148
149/**
150 * The card's palette from one appearance's tokens. The card is the theme's message background and the
151 * veil behind a label its inverse text colour; the built-in presets' inks are the design's own warm ones,
152 * and a theme that sets its own colours carries them over: its text, its Claude colour as the accent and
153 * for what's short, its success colour for what lasts. Every colour that carries meaning is nudged toward the text colour until
154 * it reads on the card. The older keys (dim, off, barTop, ...) name the same colours for the 1.3 charts.
155 */
156export function derivePalette(t: Tokens): Palette {
157  const c = (s: string, fallback: string) => parseColor(s) ?? parseColor(fallback)!
158  const fallback = luminance(c(t.inverseText, '#000')) < 0.5 ? DARK : LIGHT
159  const k = Object.fromEntries(TOKEN_KEYS.map(key => [key, c(t[key], fallback[key])])) as Record<keyof Tokens, RGB>
160  const card = k.userMessageBackground
161  const look = luminance(card) < 0.5 ? 'dark' : 'light'
162  const d = DESIGN[look], preset = look === 'dark' ? DARK : LIGHT
163  // a token the theme left as its preset has takes the design's ink; one it set is its own
164  const ink = (key: keyof Tokens, design: string, own: RGB = k[key]) => (same(k[key], parseColor(preset[key])!) ? parseColor(design)! : own)
165  const text = ink('text', d.fg)
166  const on = (x: RGB, min: number) => hex(legible(x, card, text, min))
167  const accent = on(ink('claude', d.accent), 3)
168  // what's short reads in the accent's amber; green is only for a figure "… to spare"
169  const bad = accent
170  const good = on(ink('success', d.good), 3)
171  const muted = on(ink('inactive', d.muted), 4.5)
172  const tones = TONES[look]
173  return {
174    card: hex(card),
175    veil: hex(k.inverseText),
176    fg: on(text, 7),
177    dim: muted,
178    off: on(ink('subtle', d.faint), 2.5),
179    barTop: accent,
180    barBottom: accent,
181    limit: on(ink('claude', d.sonnet, mix(k.claude, k.inactive, 0.7)), 3),
182    over: accent,
183    under: accent,
184    bad,
185    good,
186    surface: hex(card),
187    ...tones,
188    muted,
189    faint: on(ink('subtle', d.faint), 2.5),
190    accent,
191    accentBg: `${accent}2e`,
192    badBg: `${bad}33`,
193    solid: on(ink('inactive', d.solid), 2.5),
194    fable: on(ink('claude', d.fable, mix(k.claude, k.suggestion, 0.5)), 3),
195    opus: accent,
196    sonnet: on(ink('claude', d.sonnet, mix(k.claude, k.inactive, 0.7)), 3),
197    haiku: on(ink('inactive', d.haiku), 3),
198  }
199}
200
201/**
202 * The 1.3 chart's colours inside a card's Details, as the design restyles it: its your-pace line in the solid grey, the safe pace in the second model colour, the bars in the accent.
203 */
204export function historyPalettes(p: Palettes): Palettes {
205  const h = (x: Palette): Palette => ({ ...x, fg: x.solid, dim: x.muted, off: x.faint, limit: x.sonnet })
206  return { ...p, dark: h(p.dark), light: h(p.light) }
207}
208
209export function palettesFor(theme: Theme | 'auto'): Palettes {
210  const t = tokensFor(theme)
211  return { dark: derivePalette(t.dark), light: derivePalette(t.light), own: theme === 'auto' || isDark(theme.base) ? 'dark' : 'light' }
212}
213
214export const DEFAULT_PALETTES = palettesFor({ base: 'dark', overrides: {} })
215
216/** A colour by name, for a style: `style="fill:${v('fg')}"`. */
217export const v = (key: PaletteKey) => `var(--${key})`
218
219/**
220 * The `<style>` a chart carries: its theme's own appearance as the default,
221 * the other one under `prefers-color-scheme`, so the chart follows the app's
222 * appearance where the surface passes it on, and the theme where it doesn't.
223 */
224export function paletteStyle(p: Palettes): string {
225  const vars = (pal: Palette) => Object.entries(pal).map(([key, val]) => `--${key}:${val}`).join(';')
226  const other = p.own === 'dark' ? 'light' : 'dark'
227  // shown in a frame, a drawing is a page of its own: one that doesn't say it can be dark gets an opaque
228  // white backdrop in a dark app, so each says it suits both, and stays see-through
229  return `<style>:root{color-scheme:light dark;background:transparent}svg{${vars(p[p.own])}}@media (prefers-color-scheme:${other}){svg{${vars(p[other])}}}</style>`
230}
231
232/** The theme a `theme` setting names: a preset, `auto`, or `custom:<slug>`, read by `readFile`. */
233export async function resolveTheme(setting: unknown, readFile: (slug: string) => Promise<string | undefined>): Promise<Theme | 'auto'> {
234  const name = typeof setting === 'string' ? setting : 'dark'
235  if (name === 'auto') return 'auto'
236  if (PRESETS[name]) return { base: name, overrides: {} }
237  const slug = /^custom:(.+)$/.exec(name)?.[1]
238  if (slug) {
239    const text = await readFile(slug).catch(() => undefined)
240    if (text) {
241      try { return parseThemeFile(JSON.parse(text)) } catch { /* fall through to the default */ }
242    }
243  }
244  return { base: 'dark', overrides: {} }
245}
246
hooks/pace.ts 269 lines
1import type { RangeCheck, RangeDay, RangeReading } from '../types'
2import { DAY, HOUR, MIN, increments, lastWindow, ofKind, project, usedBetween } from './range'
3import type { Watch } from './range'
4
5const WEEK = 7 * DAY
6/** Daily totals are kept 8 weeks. */
7export const KEEP_DAYS = 56
8/** The range (±miss) shows only when the projection has typically missed by more than this many points. */
9export const RANGE_OVER = 5
10/** Days on record before each weekday counts at its own usual use. */
11const PROFILE_DAYS = 14
12/** Two resets this close are the same one. */
13const sameReset = (a: number, b: number) => Math.abs(a - b) < 5 * MIN
14
15const sum = (xs: readonly number[]) => xs.reduce((a, x) => a + x, 0)
16const median = (xs: readonly number[]) => {
17  const s = [...xs].sort((a, b) => a - b), m = s.length >> 1
18  return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2
19}
20
21/**
22 * The current weekly window: % used and when it resets, from the latest weekly reading.
23 * A reset that has passed rolls a week on with nothing used, as `project` does. Null with no weekly reading.
24 */
25export function currentReset(readings: readonly RangeReading[], now: number): { pct: number; resetsAt: number } | null {
26  const rs = ofKind(readings, 'week'), last = rs[rs.length - 1]
27  if (!last) return null
28  let pct = last[2], resetsAt = last[3]
29  while (resetsAt <= now) { resetsAt += WEEK; pct = 0 }
30  return { pct, resetsAt }
31}
32
33/** Local midnight at or before `t`. */
34export const midnightOf = (t: number) => { const d = new Date(t); d.setHours(0, 0, 0, 0); return d.getTime() }
35/** The local midnight after `t`: a calendar day is 23 or 25 hours where the clocks change. */
36export const nextMidnight = (t: number) => { const d = new Date(midnightOf(t)); d.setDate(d.getDate() + 1); return d.getTime() }
37
38/** A day of the window: a calendar day, or the part of one the window covers; `share` is that part (1 for the whole day). */
39export type WindowDay = { start: number; end: number; share: number }
40
41/**
42 * The days of the window resetting at `resetsAt`: calendar days, local midnight to midnight, the first from
43 * when the window opened and the last to its reset. With a reset mid-day those two are part days, so a
44 * window has 8 days; with a reset at midnight, 7 whole ones.
45 */
46export function windowDays(resetsAt: number): WindowDay[] {
47  const out: WindowDay[] = []
48  for (let start = resetsAt - WEEK; start < resetsAt;) {
49    const m = midnightOf(start), next = nextMidnight(start), end = Math.min(next, resetsAt)
50    out.push({ start, end, share: (end - start) / (next - m) })
51    start = end
52  }
53  return out
54}
55
56/** Days that have ended by `now`, oldest first. */
57const wholeDays = (totals: readonly RangeDay[], now: number) =>
58  totals.filter(d => d[0] + DAY <= now).sort((a, b) => a[0] - b[0])
59
60/**
61 * Whole calendar days on record, oldest first, each with how far the weekly figure rose in it: rises over a gap
62 * nothing here watched count too, since that was real use elsewhere. A day is on record once recording
63 * had begun at its start. Days the readings cover are always worked out afresh, since a gap's rise can
64 * arrive later and change them; older days come from `stored`, where none overlaps those. Kept KEEP_DAYS.
65 */
66export function dailyTotals(readings: readonly RangeReading[], seen: readonly Watch[], now: number, stored: readonly RangeDay[] = []): RangeDay[] {
67  const cur = currentReset(readings, now)
68  const first = ofKind(readings, 'week')[0]
69  const fresh: RangeDay[] = []
70  let from = now
71  if (cur && first) {
72    const incs = increments(readings, 'week', seen)
73    // calendar days, from the first midnight recording had begun by
74    from = midnightOf(first[0])
75    if (from < first[0]) from = nextMidnight(first[0])
76    for (let s = from; nextMidnight(s) <= now; s = nextMidnight(s)) fresh.push([s, usedBetween(incs, s, nextMidnight(s))])
77  }
78  const older: RangeDay[] = []
79  for (const d of wholeDays(stored, from)) {
80    const prev = older[older.length - 1]
81    if (!prev || d[0] >= prev[0] + DAY) older.push(d)
82  }
83  const keepFrom = midnightOf(now) - KEEP_DAYS * DAY
84  return [...older, ...fresh].filter(d => d[0] >= keepFrom)
85}
86
87/** The average of the last (up to) 7 whole days, across resets, and how many there were; null with none. */
88export function pace(totals: readonly RangeDay[], now: number): { perDay: number; days: number } | null {
89  // the days that ended within the last week
90  const days = wholeDays(totals, now).filter(d => d[0] + 8 * DAY > now).slice(-7)
91  return days.length ? { perDay: sum(days.map(d => d[1])) / days.length, days: days.length } : null
92}
93
94/** What makes a day active: ¼ of the median day with any use; 0 when no day had use. */
95export function activeThreshold(totals: readonly RangeDay[]): number {
96  const used = totals.map(d => d[1]).filter(x => x > 0)
97  return used.length ? median(used) / 4 : 0
98}
99
100/**
101 * What's usually used on each local weekday (index: `new Date(dayStart).getDay()`, 0 = Sunday): the median
102 * of that weekday's days on record, 0 for a weekday never active. A weekday with no day on record counts at
103 * the median of all days. Null under 14 whole days on record.
104 */
105export function weekdayProfile(totals: readonly RangeDay[], now: number): number[] | null {
106  const days = wholeDays(totals, now)
107  if (days.length < PROFILE_DAYS) return null
108  const active = activeThreshold(days), all = median(days.map(d => d[1]))
109  return [0, 1, 2, 3, 4, 5, 6].map(w => {
110    const vs = days.filter(d => new Date(d[0]).getDay() === w).map(d => d[1])
111    if (!vs.length) return all
112    return vs.some(x => x > 0 && x >= active) ? median(vs) : 0
113  })
114}
115
116export type WeekPlan = {
117  now: number
118  /** % of the weekly limit used, and when the window resets (ms). */
119  pct: number
120  resetsAt: number
121  /** The window's calendar days (see `windowDays`), which of them is today, and when today began and ends (ms). */
122  days: WindowDay[]
123  k: number
124  dayStart: number
125  dayEnd: number
126  /** % of the weekly limit used on each day before today. */
127  past: number[]
128  /** % of the weekly limit used since today began. */
129  usedToday: number
130  /** What a whole today is expected to use: the pace, or what's usual on this weekday (in proportion, for a part day). */
131  expectedToday: number
132  /** Today as it's predicted: what's used so far, and the expected use for the hours left in it. */
133  today: number
134  /** The days after today, each at the pace or its weekday's usual use (in proportion, for the window's last part day). */
135  later: Array<{ start: number; end: number; amount: number }>
136  /** What the days are counted at: the 7-day pace, the weekday profile, or 1.3's hourly figure while no whole day is on record. */
137  basis: 'pace' | 'profile' | 'early'
138  /** The 7-day pace in % a day and how many days are behind it (early: 1.3's rate × 24, and 0). */
139  pacePerDay: number
140  paceDays: number
141  /** % of the weekly limit left at the reset; negative means short by that much. */
142  left: number
143  /** When it runs out (ms), whether that's today, and how many hours before the reset; null and 0 when it lasts. */
144  runsOutAt: number | null
145  runsOutToday: boolean
146  early: number
147  /** Today's budget, in % of the weekly limit: what was left at the start of today spread over the time left, and that for a whole day. */
148  budget: number
149  budgetPerDay: number
150  /** Today's expected and actual use, in % of today's budget. */
151  predicted: number
152  usedOfBudget: number
153  /** How far the projection typically misses, in points, when that's over RANGE_OVER; else null. */
154  miss: number | null
155  /** Why there's no estimate yet (early basis only): then the figures mean nothing. */
156  noData: string | null
157}
158
159/**
160 * The weekly projection at `now`: what's used, the rest of today at the expected use for the hours left in it,
161 * and each day left at the 7-day pace (or its weekday's usual use once 14 days are on record). With no whole
162 * day on record it falls back to 1.3's figure.
163 * Null with no weekly reading.
164 */
165export function weekPlan(readings: readonly RangeReading[], seen: readonly Watch[], totals: readonly RangeDay[], now: number, miss: number | null = null): WeekPlan | null {
166  const cur = currentReset(readings, now)
167  if (!cur) return null
168  const { pct, resetsAt } = cur
169  const days = windowDays(resetsAt)
170  const k = Math.max(0, days.findIndex(d => now < d.end)), { start: dayStart, end: dayEnd } = days[k]!
171  const incs = increments(readings, 'week', seen)
172  const usedToday = Math.min(pct, usedBetween(incs, dayStart, now))
173  const past = days.slice(0, k).map(d => usedBetween(incs, d.start, d.end))
174  const p = pace(totals, now)
175  const profile = p ? weekdayProfile(totals, now) : null
176  // with no whole day on record, 1.3's figure since the reset
177  const m = p ? null : project(readings, 'week', now, { type: 'reset' }, seen)
178  const pacePerDay = p ? p.perDay : (m?.rate ?? 0) * 24
179  // a day at the pace or its weekday's usual use, in proportion to how much of it the window covers
180  const on = (d: WindowDay) => (profile ? profile[new Date(d.start).getDay()]! : pacePerDay) * d.share
181  const expectedToday = on(days[k]!)
182  // what's used today so far, and the day's expected use spread evenly over the hours still to come
183  const rest = expectedToday * (dayEnd - now) / (dayEnd - dayStart), today = usedToday + rest
184  const later: WeekPlan['later'] = days.slice(k + 1).map(d => ({ start: d.start, end: d.end, amount: on(d) }))
185
186  let left: number, runsOutAt: number | null = null
187  if (m) {
188    left = m.arrive
189    if (pct >= 100) runsOutAt = now
190    else if (m.over) runsOutAt = now + m.runsOutIn * HOUR
191  } else {
192    left = 100 - (pct + rest + sum(later.map(d => d.amount)))
193    if (pct >= 100) runsOutAt = now
194    // today's expected use still to come, spread evenly to the day's end
195    else if (pct + rest > 100) runsOutAt = now + (100 - pct) / rest * (dayEnd - now)
196    else {
197      // each later day spread evenly over its hours
198      let cum = pct + rest
199      for (const d of later) {
200        if (cum + d.amount > 100) { runsOutAt = d.start + (100 - cum) / d.amount * (d.end - d.start); break }
201        cum += d.amount
202      }
203    }
204  }
205  // what was left at the start of today, spread evenly over the time to the reset
206  const budgetPerDay = (100 - (pct - usedToday)) * DAY / (resetsAt - dayStart)
207  const budget = budgetPerDay * (dayEnd - dayStart) / DAY
208  const ofBudget = (x: number) => (budget > 0 ? x / budget * 100 : x > 0 ? Infinity : 0)
209  return {
210    now, pct, resetsAt, days, k, dayStart, dayEnd, past, usedToday, expectedToday, today, later,
211    basis: m ? 'early' : profile ? 'profile' : 'pace',
212    pacePerDay, paceDays: p ? p.days : 0,
213    left, runsOutAt, runsOutToday: runsOutAt !== null && runsOutAt < dayEnd,
214    early: runsOutAt === null ? 0 : Math.max(0, (resetsAt - runsOutAt) / HOUR),
215    budget, budgetPerDay, predicted: ofBudget(today), usedOfBudget: ofBudget(usedToday),
216    miss: miss !== null && miss > RANGE_OVER ? Math.round(miss * 10) / 10 : null,
217    noData: m ? m.noData : null,
218  }
219}
220
221/** Watched spans as they stood at `t`. */
222const seenAt = (seen: readonly Watch[], t: number): Watch[] => seen.filter(w => w[0] <= t).map(w => [w[0], Math.min(w[1], t)])
223
224/**
225 * The self-check: for the current window and the one just ended, what the projection said was left at
226 * the start of each of its days, worked out from the record as it stood then where it's missing. Once a window has
227 * reset, what was actually left (Last window's figure); a window whose outcome can't be trusted is
228 * dropped. Keeps the last 4 completed windows and the current one.
229 */
230export function selfCheck(check: readonly RangeCheck[], readings: readonly RangeReading[], seen: readonly Watch[], totals: readonly RangeDay[], now: number): RangeCheck[] {
231  const out: RangeCheck[] = check.map(c => ({ ...c, at: [...c.at] }))
232  const find = (resetsAt: number) => out.find(c => sameReset(c.resetsAt, resetsAt))
233  const cur = currentReset(readings, now)
234  const first = ofKind(readings, 'week')[0]
235  const last = lastWindow(readings, 'week', now, seen)
236  if (cur && first) {
237    // the window just ended is filled only when its outcome is known
238    const wins = [cur.resetsAt, ...(last && sameReset(last.resetsAt, cur.resetsAt - WEEK) ? [last.resetsAt] : [])]
239    for (const resetsAt of wins) {
240      let c = find(resetsAt)
241      if (c?.actual !== undefined) continue
242      if (!c) { c = { resetsAt, at: [] }; out.push(c) }
243      for (const { start: b } of windowDays(c.resetsAt)) {
244        if (b > now || b < first[0] || c.at.some(a => Math.abs(a[0] - b) < 5 * MIN)) continue
245        const plan = weekPlan(readings.filter(r => r[0] <= b), seenAt(seen, b), totals.filter(d => d[0] + DAY <= b), b)
246        if (plan && !plan.noData && sameReset(plan.resetsAt, c.resetsAt)) c.at.push([b, plan.left])
247      }
248      c.at.sort((x, y) => x[0] - y[0])
249    }
250  }
251  const done: RangeCheck[] = [], open: RangeCheck[] = []
252  for (const c of out.sort((a, b) => a.resetsAt - b.resetsAt)) {
253    if (!c.at.length) continue
254    if (c.resetsAt > now) { open.push(c); continue }
255    if (c.actual === undefined) {
256      if (!last || !sameReset(last.resetsAt, c.resetsAt)) continue
257      c.actual = last.left
258    }
259    done.push(c)
260  }
261  return [...done.slice(-4), ...open.slice(-1)]
262}
263
264/** How far the projection typically misses: the median of |said − actual| over every snapshot of the completed windows; null when none has completed. */
265export function typicalMiss(check: readonly RangeCheck[]): number | null {
266  const errs = check.flatMap(c => (c.actual === undefined ? [] : c.at.map(a => Math.abs(a[1] - c.actual!))))
267  return errs.length ? median(errs) : null
268}
269
hooks/cards.ts 457 lines
1import type { Palettes, RangeDay } from '../types'
2import { C, DAY, HOUR, LAST_LABEL, drawing, dur, isShort, lastIsShort, lastWindowText, rateText, spare } from './range'
3import type { BandPart, LastWindow, Model } from './range'
4import type { WeekPlan } from './pace'
5import { DEFAULT_PALETTES } from './theme'
6import { NARROW, SIZE, cardHeader, metricGrid, rect, rich, stripes, t, topRounded, track, trackLabels, tw } from './ui'
7import type { Run } from './ui'
8
9/**
10 * 1.4's cards: the weekly card in two frames (the week, 100% = the weekly
11 * limit; today, 100% = today's budget), the 5-hour card,
12 * and the line above the prompt. Every % names its 100%, and no figure mixes
13 * the two frames: one sentence gives today's budget in week terms.
14 */
15
16// ---- clock words ----
17
18const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
19const FULL_DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
20const pad = (n: number) => String(n).padStart(2, '0')
21/** Local clock time: "00:09". */
22export const hm = (t: number) => { const d = new Date(t); return `${pad(d.getHours())}:${pad(d.getMinutes())}` }
23/** The local weekday, short: "Wed". */
24export const dayName = (t: number) => DAYS[new Date(t).getDay()]!
25/** A day and time: "Thu 11:00". */
26export const dayTime = (t: number) => `${dayName(t)} ${hm(t)}`
27/** A day, its date and the time: "Thu · Oct 08 · 11:00". */
28export const dayDateTime = (t: number) => `${dayName(t)} · ${dateName(t)} · ${hm(t)}`
29/** About when, to the quarter hour: "Wed ~12:45". */
30export const around = (t: number) => { const q = Math.round(t / (15 * 60_000)) * 15 * 60_000; return `${dayName(q)} ~${hm(q)}` }
31/** One decimal, a whole number without it: "13.5", "39". */
32export const one = (n: number) => (Math.round(n * 10) / 10).toFixed(1).replace(/\.0$/, '')
33
34// ---- the line above the prompt ----
35
36/** One limit's part of the line: as 1.3's, plus whether it reads as short or as what's left at the reset, and a tag ("early"). */
37export type Part = BandPart & { bad: boolean; dim: boolean; spare?: boolean; tag?: string }
38
39/**
40 * The week's part. Lasting: "~6% left at reset ±12, in 4d 13h" (narrow "~6% @reset 4d 13h"). Short: "runs out
41 * Wed ~12:45, 22h early" (narrow "out Wed 12:45"). Before a whole day is on record, 1.3's hourly figure
42 * with the tag "early".
43 */
44export function weekPart(p: WeekPlan, short: boolean): Part {
45  const label = 'Week', leftH = (p.resetsAt - p.now) / HOUR
46  if (p.noData) return { label, value: 'No data', rest: '', bad: false, dim: true }
47  const tag = p.basis === 'early' ? { tag: 'early' } : {}
48  if (p.pct >= 100) return { label, value: short ? `out to ${hm(p.resetsAt)}` : `out until ${dayTime(p.resetsAt)}`, rest: '', bad: true, dim: false }
49  if (p.runsOutAt !== null) {
50    if (p.basis === 'early') return short
51      ? { label, value: `out in ${dur((p.runsOutAt - p.now) / HOUR)}`, rest: '', bad: true, dim: false, ...tag }
52      : { label, value: `runs out in ${dur((p.runsOutAt - p.now) / HOUR)}`, rest: `, ${dur(p.early)} early`, bad: true, dim: false, ...tag }
53    const when = p.runsOutToday ? 'later today' : around(p.runsOutAt)
54    return short
55      ? { label, value: `out ${p.runsOutToday ? 'today' : when.replace('~', '')}`, rest: '', bad: true, dim: false }
56      : { label, value: `runs out ${when}`, rest: `, ${dur(p.early)} early`, bad: true, dim: false }
57  }
58  const miss = p.miss ? ` ±${one(p.miss)}` : ''
59  return short
60    ? { label, value: `~${Math.max(0, Math.round(p.left))}% @reset${miss}`, rest: ` ${dur(leftH)}`, bad: false, dim: false, spare: true, ...tag }
61    : { label, value: `~${Math.max(0, Math.round(p.left))}% left at reset${miss}`, rest: `, in ${dur(leftH)}`, bad: false, dim: false, spare: true, ...tag }
62}
63
64/** When the 5-hour limit runs out at this pace (ms), or null when it lasts to the reset. */
65export const cutOff = (m: Model, now: number) => (m.over && !m.noData ? Math.round((now + m.runsOutIn * HOUR) / 60_000) * 60_000 : null)
66
67/** The 5-hour part, in clock times: "cut off ~00:09, resets 00:40" or "~55% left at 15:40" (narrow "out 00:09", "~55% @15:40"). */
68export function fivePart(m: Model, now: number, short: boolean): Part {
69  const label = '5h'
70  if (m.noData) return { label, value: 'No data', rest: '', bad: false, dim: true }
71  if (m.pct >= 100) return { label, value: short ? `out to ${hm(m.resetsAt)}` : `out until ${hm(m.resetsAt)}`, rest: '', bad: true, dim: false }
72  const cut = cutOff(m, now)
73  if (cut !== null) return short
74    ? { label, value: `out ${hm(cut)}`, rest: '', bad: true, dim: false }
75    : { label, value: `cut off ~${hm(cut)}`, rest: `, resets ${hm(m.resetsAt)}`, bad: true, dim: false }
76  return short
77    ? { label, value: `~${Math.max(0, Math.round(m.arrive))}% @${hm(m.resetsAt)}`, rest: '', bad: false, dim: false, spare: true }
78    : { label, value: `~${Math.max(0, Math.round(m.arrive))}% left at ${hm(m.resetsAt)}`, rest: '', bad: false, dim: false, spare: true }
79}
80
81/** About how many cells the line takes: the parts, their tags, the " · " between them, and the Details button. */
82export const partsWidth = (parts: Part[]) =>
83  parts.reduce((w, p) => w + p.label.length + 1 + p.value.length + p.rest.length + (p.tag ? p.tag.length + 1 : 0), 0)
84  + Math.max(0, parts.length - 1) * 3 + 1 + 11
85
86// ---- the weekly card's words ----
87
88/** The days of this window so far, each in % of the weekly limit (0 for a day not on record). */
89export const pastDays = (p: WeekPlan): number[] => p.past
90
91/** When today ends: at midnight, or at the reset when that comes first. */
92export const dayEndText = (p: WeekPlan) => (p.dayEnd === p.resetsAt ? `week resets ${hm(p.dayEnd)}` : 'day ends at midnight')
93
94/** How the projection was made, for the line under the head. */
95export function basisText(p: WeekPlan): string {
96  if (p.basis === 'profile') return 'At what you usually use on each of the days left.'
97  if (p.basis === 'early') return 'Early estimate: no whole day is on record yet, so this is 1.3’s hourly figure.'
98  return `At your pace over the last ${p.paceDays === 1 ? 'whole day' : `${p.paceDays} whole days`}: ${one(p.pacePerDay)}% a day.`
99}
100
101/** The week's head and the line under it: what's left at the reset, or when it runs out, and what that's based on. */
102export function weekHead(p: WeekPlan): { head: string; tone: 'good' | 'bad' | 'dim'; sub: string } {
103  if (p.noData) return { head: 'No estimate yet', tone: 'dim', sub: p.noData }
104  if (p.pct >= 100) return { head: `Out until ${dayTime(p.resetsAt)}`, tone: 'bad', sub: 'The weekly limit is reached.' }
105  if (p.runsOutAt !== null) {
106    const when = p.basis === 'early' ? `in ${dur((p.runsOutAt - p.now) / HOUR)}` : p.runsOutToday ? 'later today' : around(p.runsOutAt)
107    return { head: `Runs out ${when}, ${dur(p.early)} before the reset`, tone: 'bad', sub: basisText(p) }
108  }
109  const left = Math.max(0, Math.round(p.left))
110  let sub = basisText(p)
111  if (p.miss) {
112    const lo = left - p.miss, hi = left + p.miss
113    sub += ` Your projections have typically been off by ${one(p.miss)} points, so read it as ${lo < 0 ? `between ${one(-lo)}% short and ${one(hi)}% to spare` : `${one(lo)}–${one(hi)}% to spare`}.`
114  }
115  return { head: `About ${left}% left at the reset${p.miss ? ` ±${one(p.miss)}` : ''}`, tone: 'good', sub }
116}
117
118/** What's projected on top of what's used, to the reset: today's rest and the later days. */
119export const toCome = (p: WeekPlan) => p.today - p.usedToday + p.later.reduce((a, d) => a + d.amount, 0)
120
121/** The week bar's labels: used, what the pace adds, and the end. */
122export function weekBarLabels(p: WeekPlan): { used: string; add: string | null; addBad: boolean; end: string } {
123  const add = p.basis === 'early' ? null : toCome(p), total = p.pct + (add ?? 0)
124  return {
125    used: `${one(p.pct)}% used`,
126    add: add === null ? null : total > 100 ? `+${one(add)}% at this pace, ${one(total - 100)}% more than the limit` : `+${one(add)}% at this pace`,
127    addBad: total > 100,
128    end: `Resets ${dayDateTime(p.resetsAt)}`,
129  }
130}
131
132/** Whether the today frame shows: once there's a pace, and while the limit isn't reached. */
133export const showsToday = (p: WeekPlan) => !p.noData && p.basis !== 'early' && p.pct < 100
134
135/** Today, in today's frame: the predicted line and the sentence under the bar. */
136export function todayText(p: WeekPlan): { predicted: string; bad: boolean; used: string; pred: string | null; end: string; note: string } {
137  const how = p.basis === 'profile' ? `your usual ${FULL_DAYS[new Date(p.dayStart).getDay()]}` : 'your pace'
138  return {
139    predicted: `Predicted use today: ${one(p.predicted)}% of daily budget`,
140    bad: p.predicted > 100,
141    used: `${one(p.usedOfBudget)}% used`,
142    pred: p.predicted > p.usedOfBudget + 0.05 ? `${one(p.predicted)}% predicted` : null,
143    end: `100% · ${dayEndText(p)}`,
144    note: `Predicted: what’s used so far, and the rest of the day at ${how}. Today’s budget is what’s left of the week spread over the time to the reset: ${one(p.budget)}% of your weekly limit.`,
145  }
146}
147
148/** The days in words, for the terminal and alt text: "Thu 20% · Fri 7% · Sat 12% now · Sun ~13.5% …". */
149export function daysText(p: WeekPlan, past: readonly number[]): string {
150  const early = p.basis === 'early'
151  const out: string[] = past.map((v, i) => `${dayName(p.days[i]!.start)} ${one(v)}%`)
152  out.push(`${dayName(p.dayStart)} ${one(p.usedToday)}% now`)
153  for (const d of p.later) out.push(`${dayName(d.start)} ${early ? '?' : d.amount > 0 ? `~${one(d.amount)}%` : '0%'}`)
154  return out.join(' · ')
155}
156
157// ---- the desktop's words, in runs: what's in the text colour or a state's, the rest muted ----
158
159const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
160/** A day's date: "Oct 08". */
161export const dateName = (t: number) => { const d = new Date(t); return `${MONTHS[d.getMonth()]} ${pad(d.getDate())}` }
162const strong = (s: string, fill: string = C.fg, weight = 600): Run => ({ s, fill, weight })
163
164/** The weekly headline as the card shows it: the figure, its tone, and the range as a badge of its own ("±12 pts"). */
165export function weekHeadline(p: WeekPlan): { head: string; tone: 'good' | 'bad' | 'dim'; badge: string | null } {
166  const h = weekHead(p)
167  if (h.tone !== 'good') return { head: h.head, tone: h.tone, badge: null }
168  return { head: `About ${Math.max(0, Math.round(p.left))}% left at the reset`, tone: 'good', badge: p.miss ? `±${one(p.miss)} pts` : null }
169}
170
171
172/** How far off the projection typically is, and the range that makes, under the basis. */
173export function missRuns(p: WeekPlan): Run[] | null {
174  if (!p.miss || weekHead(p).tone !== 'good') return null
175  const left = Math.max(0, Math.round(p.left)), lo = left - p.miss, hi = left + p.miss
176  return [{ s: `Typical forecast miss: ${one(p.miss)} points. Read this as ` }, strong(lo < 0 ? `between ${one(-lo)}% short and ${one(hi)}% to spare.` : `${one(lo)}–${one(hi)}% to spare.`)]
177}
178
179
180
181// ---- drawing ----
182
183const TONE = { good: C.accent, bad: C.bad, dim: C.muted }
184
185/**
186 * A limit's use as one bar, `width` wide from `y`, on 0–100% of the limit: solid to what's used (`pct`), striped to
187 * where the pace ends up by the reset (`total`, or null with no projection), a mark at 100%. Each figure is centred
188 * in its own part, the total on a chip over the stripes and in red past 100%, so there's nothing to add up. Under the
189 * bar, at its ends, when the window opened (`start`) and when it resets (`end`); a figure whose part is too narrow for
190 * it goes between them. The y under it all comes back.
191 */
192function limitBar(y: number, width: number, pct: number, total: number | null, stripe: string, start: string, end: string): { svg: string; y: number } {
193  const BW = width - 2, BH = 24, used = Math.min(100, pct), to = total === null ? used : Math.min(100, total), over = (total ?? 0) > 100
194  let s = track(0, y, BW, BH, used / 100, to / 100, 1, { stripe })
195  const ty = y + BH / 2 + SIZE.meta * 0.36
196  const inBar = (label: string, x0: number, x1: number, chip: boolean, fill: string) => {
197    const w = tw(label, SIZE.meta, 600), cx = (x0 + x1) / 2
198    if (x1 - x0 < w + (chip ? 16 : 10)) return false
199    if (chip) s += rect(cx - w / 2 - 6, y + 3, w + 12, BH - 6, `fill:${C.card}`, ' rx="4"')
200    s += t(cx, ty, label, { size: SIZE.meta, weight: 600, fill, anchor: 'middle' })
201    return true
202  }
203  const usedX = BW * used / 100, toX = BW * to / 100
204  const usedIn = inBar(`${one(pct)}%`, 0, usedX, false, C.card)
205  const totalIn = total === null || inBar(`~${one(total)}%`, usedX, toX, true, over ? C.bad : C.fg)
206  const between: Run[] = [
207    ...(usedIn ? [] : [strong(`${one(pct)}%`, C.fg, 500), { s: ' used' }]),
208    ...(totalIn ? [] : [{ s: usedIn ? '' : ' · ' }, strong(`~${one(total!)}%`, over ? C.bad : C.fg, 500), { s: ' by the reset' }]),
209  ]
210  const row = trackLabels([[{ s: start }], between.length ? between : null, [{ s: end }]], y + BH + 8 + SIZE.meta * 1.15, width)
211  return { svg: s + row.svg, y: row.y + SIZE.meta * 0.6 }
212}
213
214/** A card's headline size: the design's title size, smaller on a narrow card or a dense one. */
215const headSize = (width: number, dense: boolean) => (dense ? 20 : width < NARROW ? 24 : SIZE.title)
216
217/** The pane's masthead: the mark and the name. */
218export function mastheadSvg(width: number, pal: Palettes = DEFAULT_PALETTES): string {
219  const narrow = width < NARROW
220  const m = narrow ? 0 : 48, gap = narrow ? 0 : 15
221  let s = ''
222  if (!narrow) {
223    s += rect(0, 0, 48, 48, `fill:${C.raised}`, ' rx="12"')
224    // the mark: three bars, as the plugin's icon
225    s += `<g transform="translate(9 9) scale(0.9375)" style="fill:${C.accent}"><rect x="3" y="17" width="6" height="12" rx="2"/><rect x="13" y="3" width="6" height="26" rx="2"/><rect x="23" y="11" width="6" height="18" rx="2"/></g>`
226  }
227  const ts = narrow ? 24 : SIZE.title
228  s += t(m + gap, narrow ? 24 : 34, 'Token Range Monitor', { size: ts, weight: 650 })
229  return drawing(s, narrow ? 30 : 48, pal)
230}
231
232/** The days' columns' height in px as designed, at a card `width` wide, and the least they're drawn at to fit a short pane. */
233export const daysHeight = (width: number) => (width < NARROW ? 110 : 136)
234export const DAYS_MIN = 72
235
236/** A nice top for the days' scale: a little over the tallest, in whole even points. */
237function scaleTop(max: number): number {
238  const v = Math.max(max, 1) * 1.1
239  return v >= 10 ? Math.ceil(v / 2) * 2 : Math.ceil(v)
240}
241
242/**
243 * The weekly card, `width` wide, down to the days' dates: its header; the week's frame (the headline and
244 * its range, the whole week as one bar); the days of this window as seven columns on one
245 * scale (calendar days; the first and last part days where the reset falls mid-day), past days solid, today solid with its expected rest striped, later days striped, today's and later
246 * days' daily budget outlined. The legend and today's frame are drawn apart (`weekLegendSvg`, `todaySvg`). `dense`, for
247 * a pane too short for the cards, draws the header and headline smaller; `shrink`, px the days' columns are drawn
248 * shorter than the design's so the cards fit the pane's height, down to DAYS_MIN.
249 */
250export function weekCardSvg(p: WeekPlan, past: readonly number[], width: number, pal: Palettes = DEFAULT_PALETTES, dense = false, shrink = 0): string {
251  const W = width
252  let s = `<defs>${stripes('wk', C.raised)}${stripes('wkd', C.inset)}</defs>`
253  const head = cardHeader('calendar', 'This week', [], W, dense)
254  s += head.svg
255  let y = head.y
256
257  // ---- the headline, its range, what it's based on ----
258  const h = weekHeadline(p)
259  const hs = headSize(W, dense)
260  const badgeW = h.badge ? tw(h.badge, SIZE.meta, 500) + 14 : 0
261  const fitsOne = tw(h.head, hs, 600) + (h.badge ? 12 + badgeW : 0) <= W
262  // only the figure carries the tone (a %, or a time); the rest of the headline is in the text colour
263  const headRuns: Run[] = h.head.split(/(~?\d+(?:\.\d+)?%|~\d\d:\d\d)/).filter(Boolean)
264    .map((part, i) => ({ s: part, fill: i % 2 || /^~?\d/.test(part) ? TONE[h.tone] : C.fg, weight: 600 }))
265  const hl = rich(headRuns, 0, y + hs * 0.95, W, hs, 1.3)
266  s += hl.svg
267  y = hl.y
268  if (h.badge) {
269    const bx = fitsOne ? tw(h.head, hs, 600) + 12 : 0, by = fitsOne ? y - hs * 0.72 : y + 12
270    s += rect(bx, by, badgeW, 23, `fill:${C.raised}`, ' rx="5"') + t(bx + 7, by + 16, h.badge, { size: SIZE.meta, weight: 500, fill: C.muted })
271    if (!fitsOne) y += 30
272  }
273  y += hs * 0.3
274  const miss = missRuns(p)
275  if (miss) {
276    const r = rich(miss, 0, y + 5 + SIZE.meta * 1.2, W, SIZE.meta, 1.7)
277    s += r.svg
278    y = r.y + SIZE.meta * 0.5
279  }
280
281  // ---- the whole week as one bar ----
282  if (!p.noData) {
283    y += 17
284    const L = weekBarLabels(p), bar = limitBar(y, W, p.pct, L.add === null ? null : p.pct + toCome(p), 'wk', `Started ${dayDateTime(p.resetsAt - 7 * DAY)}`, L.end)
285    s += bar.svg
286    y = bar.y
287  }
288
289  // ---- the days of this window, one scale ----
290  if (!p.noData && p.pct < 100) {
291    const early = p.basis === 'early', narrow = W < NARROW, n = p.days.length
292    const vals = [...past, early ? p.usedToday : p.today, ...(early ? [] : p.later.map(d => d.amount)), early ? 0 : p.budgetPerDay]
293    const top = scaleTop(Math.max(...vals))
294    const axisW = narrow ? 32 : 36, gap = narrow ? 7 : W < 760 ? 12 : 16
295    const colW = (W - axisW - 4 - gap * (n - 1)) / n
296    const tall = Math.max(DAYS_MIN, daysHeight(W) - shrink)
297    y += 22
298    const vy = y + 13, base = y + 30 + tall
299    const hOf = (v: number) => Math.max(0, Math.min(v, top)) / top * tall
300    // the scale: the top and middle as dashed lines, their figures at the left
301    for (const [f, label] of [[1, top], [0.5, top / 2], [0, 0]] as const) {
302      const ly = base - f * tall
303      if (f > 0) s += `<line x1="${axisW}" x2="${W}" y1="${ly.toFixed(1)}" y2="${ly.toFixed(1)}" style="stroke:${C.line}" stroke-dasharray="3 3"/>`
304      s += t(axisW - (narrow ? 6 : 9), ly + SIZE.meta * 0.36, `${one(label)}%`, { size: SIZE.meta, fill: C.muted, anchor: 'end' })
305    }
306    for (let i = 0; i < n; i++) {
307      const day = p.days[i]!, x = axisW + i * (colW + gap), cx = x + colW / 2, isToday = i === p.k
308      let v = '', vFill: string = C.muted
309      if (i < p.k) {
310        const hv = hOf(past[i] ?? 0)
311        if (hv > 0) s += `<path d="${topRounded(x + 0.5, base - hv, colW - 1, hv, 4)}Z" style="fill:${C.accent};stroke:${C.accent}"/>`
312        v = `${one(past[i] ?? 0)}%`
313      } else if (isToday) {
314        const over = !early && p.usedToday > p.budget
315        const hu = hOf(p.usedToday), hr = early ? 0 : hOf(p.today) - hu
316        if (hr > 0.5) s += `<path d="${topRounded(x + 0.5, base - hu - hr, colW - 1, hr, 3)}Z" style="fill:url(#wkd)"/>`
317        if (hu > 0) s += `<path d="${hr > 0.5 ? `M${(x + 0.5).toFixed(1)} ${base.toFixed(1)}V${(base - hu).toFixed(1)}H${(x + colW - 0.5).toFixed(1)}V${base.toFixed(1)}` : topRounded(x + 0.5, base - hu, colW - 1, hu, 4)}Z" style="fill:${over ? C.bad : C.accent};stroke:${over ? C.bad : C.accent}"/>`
318        v = `${one(p.usedToday)}%`; vFill = over ? C.bad : C.accent
319      } else if (early) {
320        s += `<path d="${topRounded(x + 0.5, base - tall * 0.4, colW - 1, tall * 0.4, 4)}" fill="none" style="stroke:${C.faint}" stroke-dasharray="4 3"/>`
321        v = '?'
322      } else {
323        const d = p.later[i - p.k - 1]!, hd = hOf(d.amount)
324        if (hd > 0) s += `<path d="${topRounded(x + 0.5, base - hd, colW - 1, hd, 4)}Z" style="fill:url(#wkd);stroke:${C.accent}"/>`
325        v = d.amount > 0 ? `~${one(d.amount)}%` : '0%'
326      }
327      // the daily budget, outlined over today and the days after it (a part day's in proportion)
328      if (!early && i >= p.k) {
329        const hb = hOf(isToday ? p.budget : p.budgetPerDay * day.share)
330        s += `<path d="${topRounded(x - 3, base - hb, colW + 6, hb, 4)}" fill="none" style="stroke:${C.muted}"/>`
331      }
332      const vs = tw(v, SIZE.meta) > colW + gap - 2 ? v.replace('%', '').replace('~', '') : v
333      s += t(cx, vy, vs, { size: SIZE.meta, fill: vFill, anchor: 'middle' })
334      const name = dayName(day.start), date = dateName(day.start)
335      s += t(cx, base + 9 + SIZE.meta * 1.15, name, { size: SIZE.meta, fill: isToday ? C.accent : C.fg, anchor: 'middle' })
336      if (isToday) s += `<circle cx="${(cx + tw(name, SIZE.meta) / 2 + 6).toFixed(1)}" cy="${(base + 9 + SIZE.meta * 0.78).toFixed(1)}" r="2" style="fill:${C.accent}"/>`
337      // under the name: the date; the window's part days say where they start or stop; today says it's now
338      const part = day.share < 1 ? (i === 0 ? `from ${hm(day.start)}` : i === n - 1 ? `to ${hm(day.end)}` : null) : null
339      const fits = (l: string) => colW + gap > tw(l, SIZE.meta) + 2
340      const dl = isToday ? (fits(`${date} · now`) ? `${date} · now` : 'now')
341        : part ? (fits(part) ? part : part.replace(/^\S+ /, '')) : fits(date) ? date : date.slice(4)
342      s += t(cx, base + 9 + SIZE.meta * 2.65, dl, { size: SIZE.meta, fill: isToday ? C.accent : C.muted, anchor: 'middle' })
343    }
344    s += `<line x1="${axisW}" x2="${W}" y1="${(base + 0.5).toFixed(1)}" y2="${(base + 0.5).toFixed(1)}" style="stroke:${C.line}"/>`
345    y = base + 9 + SIZE.meta * 2.65
346  }
347  return drawing(s, Math.ceil(y + 4), pal)
348}
349
350/** The days' legend: used, and what the pace adds (or that the days to come aren't known yet). */
351export function weekLegendSvg(early: boolean, pal: Palettes = DEFAULT_PALETTES): { svg: string; width: number } {
352  const second = early ? 'Not known yet' : 'Expected at your pace'
353  const w = 13 + 7 + tw('Used', SIZE.meta) + 20 + 13 + 7 + tw(second, SIZE.meta) + 4
354  let s = `<defs>${stripes('lg', 'none', 4, 2)}</defs>`
355  s += rect(0, 5, 13, 12, `fill:${C.accent}`, ' rx="3"') + t(20, 15.5, 'Used', { size: SIZE.meta, fill: C.muted })
356  const x = 20 + tw('Used', SIZE.meta) + 20
357  s += rect(x + 0.5, 5.5, 12, 11, `fill:url(#lg);stroke:${C.accent}`, ' rx="3"') + t(x + 20, 15.5, second, { size: SIZE.meta, fill: C.muted })
358  return { svg: drawing(s, 22, pal), width: Math.ceil(w) }
359}
360
361/** When today passes its budget at this pace (ms): now when it already has, null when it stays within it. */
362export function overBudgetAt(p: WeekPlan): number | null {
363  if (p.usedOfBudget >= 100) return p.now
364  if (p.predicted <= 100) return null
365  // the rest of today's expected use runs evenly to the day's end
366  const rest = p.today - p.usedToday
367  return Math.round((p.now + (p.budget - p.usedToday) / rest * (p.dayEnd - p.now)) / 60_000) * 60_000
368}
369
370/**
371 * The today card, `width` wide, laid out as the 5-hour card is: its header; when today passes its budget at
372 * this pace (its time in red) or that it stays within it; and today's use as one bar on 0–100% of today's
373 * budget (`limitBar`): solid for what's used, striped to the prediction, the day's start and end under it.
374 */
375export function todaySvg(p: WeekPlan, width: number, pal: Palettes = DEFAULT_PALETTES, dense = false): string {
376  const W = width
377  let s = `<defs>${stripes('td', C.raised)}</defs>`
378  const head = cardHeader('bars', 'Today', [], W, dense)
379  s += head.svg
380  let y = head.y
381  const hs = headSize(W, dense), over = overBudgetAt(p)
382  const title: Run[] = over === null
383    ? [{ s: 'Within today’s budget', fill: C.fg }, { s: ' at this pace', fill: C.fg }]
384    : over <= p.now
385      ? [{ s: 'Over today’s budget', fill: C.bad }]
386      : [{ s: 'Over budget ', fill: C.fg }, { s: `~${hm(over)}`, fill: C.bad }, { s: ' at this pace', fill: C.fg }]
387  const hl = rich(title, 0, y + hs * 1.0, W, hs, 1.35, { weight: 600 })
388  s += hl.svg
389  y = hl.y + hs * 0.35 + (dense ? 14 : 27)
390  const end = p.dayEnd === p.resetsAt ? `Week resets ${hm(p.dayEnd)}` : 'Ends at midnight'
391  const bar = limitBar(y, W, p.usedOfBudget, p.predicted > p.usedOfBudget + 0.05 ? p.predicted : null, 'td', `Started ${hm(p.dayStart)}`, end)
392  s += bar.svg
393  return drawing(s, Math.ceil(bar.y + 4), pal)
394}
395
396// ---- the 5-hour card ----
397
398/** The 5-hour head and the line under it. */
399export function fiveHead(m: Model, now: number): { head: string; tone: 'good' | 'bad' | 'dim'; sub: string } {
400  const opened = m.resetsAt - 5 * HOUR
401  if (m.noData) return { head: 'No estimate yet', tone: 'dim', sub: m.noData }
402  if (m.pct >= 100) return { head: `Out until ${hm(m.resetsAt)}`, tone: 'bad', sub: `The 5-hour limit is reached. It resets at ${hm(m.resetsAt)}.` }
403  const used = `${Math.round(m.pct)}% used since ${hm(opened)}, ${one(m.rate)}% an hour.`
404  const cut = cutOff(m, now)
405  if (cut !== null) return { head: `Cut off ~${hm(cut)} at this pace`, tone: 'bad', sub: `${used} It resets at ${hm(m.resetsAt)}, ${dur((m.resetsAt - cut) / HOUR)} after the cut-off.` }
406  return { head: `Lasts to the reset at ${hm(m.resetsAt)}`, tone: 'good', sub: `${used.slice(0, -1)} · about ${Math.round(m.arrive)}% to spare.` }
407}
408
409
410/** What the 5-hour card's Details strip says while closed, in runs: when it runs out at 1.3's pace, or what's left. */
411export function fiveSummary(m: Model): Run[] {
412  if (m.noData) return [{ s: m.noData }]
413  if (isShort(m)) return [{ s: 'Runs out in ' }, { s: dur(m.runsOutIn), fill: C.bad }, { s: ` · ${dur(m.early)} early` }]
414  return [{ s: 'At the reset ' }, { s: spare(m.arrive), fill: C.good }, { s: ` · resets in ${dur(m.left)}` }]
415}
416
417/**
418 * The 5-hour card, `width` wide: its header; the cut-off (its time in red) or the reset it lasts to; and the window's
419 * use as one bar on that scale (`limitBar`): solid for what's used, striped to where this pace ends up by the reset.
420 */
421export function fiveCardSvg(m: Model, now: number, width: number, pal: Palettes = DEFAULT_PALETTES, dense = false): string {
422  const W = width, opened = m.resetsAt - 5 * HOUR
423  let s = `<defs>${stripes('fv', C.raised)}</defs>`
424  const head = cardHeader('clock', '5-hour window', [], W, dense)
425  s += head.svg
426  let y = head.y
427  const h = fiveHead(m, now), cut = m.noData ? null : cutOff(m, now)
428  const hs = headSize(W, dense)
429  const title: Run[] = cut !== null && m.pct < 100
430    ? [{ s: 'Cut off ', fill: C.fg }, { s: `~${hm(cut)}`, fill: C.bad }, { s: ' at this pace', fill: C.fg }]
431    : h.tone === 'good'
432      ? [{ s: 'Lasts to the reset at ', fill: C.fg }, { s: hm(m.resetsAt), fill: C.accent }]
433      : [{ s: h.head, fill: TONE[h.tone] }]
434  const hl = rich(title, 0, y + hs * 1.0, W, hs, 1.35, { weight: 600 })
435  s += hl.svg
436  y = hl.y + hs * 0.35
437  if (m.noData) return drawing(s, Math.ceil(y + 8), pal)
438
439  // ---- the window's use as one bar, on the card's scale: used, then where this pace ends up by the reset ----
440  y += dense ? 14 : 27
441  const proj = 100 - m.arrive, bar = limitBar(y, W, m.pct, proj > m.pct ? proj : null, 'fv', `Started ${hm(opened)}`, `Resets ${hm(m.resetsAt)}`)
442  s += bar.svg
443  y = bar.y
444  return drawing(s, Math.ceil(y + 4), pal)
445}
446
447/** A 1.3 head's figures, as the Details' grid shows them: the two paces, the last window. */
448export function oldFigures(m: Model, last: LastWindow | null, width: number, pal: Palettes = DEFAULT_PALETTES): string {
449  const items = [
450    { label: 'Your pace', value: m.noData ? 'No data' : rateText(m, m.rate) },
451    { label: 'Safe pace', value: rateText(m, m.limit) },
452    ...(last ? [{ label: LAST_LABEL, value: lastWindowText(last), fill: lastIsShort(last) ? C.bad : C.good }] : []),
453  ]
454  const g = metricGrid(items, width)
455  return drawing(g.svg, Math.ceil(g.y), pal)
456}
457
hooks/ui.ts 189 lines
1import { C, FONT, esc } from './range'
2
3/**
4 * The drawing kit the cards share: text and runs of text that wrap, rectangles, the icons, the striped
5 * projection pattern and each card's header. Sizes follow the design's three steps, 28 / 16 / 13 px.
6 */
7
8export const SIZE = { title: 28, body: 16, meta: 13 } as const
9
10export type Txt = { size: number; weight?: number; fill?: string; anchor?: 'start' | 'middle' | 'end'; opacity?: number }
11export const t = (x: number | string, y: number, s: string, o: Txt) =>
12  `<text x="${typeof x === 'number' ? x.toFixed(1) : x}" y="${y.toFixed(1)}" text-anchor="${o.anchor ?? 'start'}" style="fill:${o.fill ?? C.fg}"${o.opacity !== undefined ? ` fill-opacity="${o.opacity}"` : ''} font-family="${FONT}" font-size="${o.size}px" font-weight="${o.weight ?? 400}">${esc(s)}</text>`
13/** About how wide a text runs. */
14export const tw = (s: string, size: number, weight = 400) => s.length * size * (weight >= 600 ? 0.57 : weight >= 500 ? 0.545 : 0.53)
15
16export const rect = (x: number, y: number, w: number, h: number, style: string, extra = '') =>
17  `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${Math.max(0, w).toFixed(1)}" height="${Math.max(0, h).toFixed(1)}" style="${style}"${extra}/>`
18/** A box with only its top corners rounded, as a path. */
19export const topRounded = (x: number, y: number, w: number, h: number, r: number) => {
20  r = Math.max(0, Math.min(r, w / 2, h))
21  return `M${x.toFixed(1)} ${(y + h).toFixed(1)}V${(y + r).toFixed(1)}Q${x.toFixed(1)} ${y.toFixed(1)} ${(x + r).toFixed(1)} ${y.toFixed(1)}H${(x + w - r).toFixed(1)}Q${(x + w).toFixed(1)} ${y.toFixed(1)} ${(x + w).toFixed(1)} ${(y + r).toFixed(1)}V${(y + h).toFixed(1)}`
22}
23/** A box with only its left corners rounded, or only its right ones. */
24export const sideRounded = (x: number, y: number, w: number, h: number, r: number, side: 'left' | 'right') => {
25  r = Math.max(0, Math.min(r, w, h / 2))
26  return side === 'left'
27    ? `M${(x + w).toFixed(1)} ${y.toFixed(1)}H${(x + r).toFixed(1)}Q${x.toFixed(1)} ${y.toFixed(1)} ${x.toFixed(1)} ${(y + r).toFixed(1)}V${(y + h - r).toFixed(1)}Q${x.toFixed(1)} ${(y + h).toFixed(1)} ${(x + r).toFixed(1)} ${(y + h).toFixed(1)}H${(x + w).toFixed(1)}Z`
28    : `M${x.toFixed(1)} ${y.toFixed(1)}H${(x + w - r).toFixed(1)}Q${(x + w).toFixed(1)} ${y.toFixed(1)} ${(x + w).toFixed(1)} ${(y + r).toFixed(1)}V${(y + h - r).toFixed(1)}Q${(x + w).toFixed(1)} ${(y + h).toFixed(1)} ${(x + w - r).toFixed(1)} ${(y + h).toFixed(1)}H${x.toFixed(1)}Z`
29}
30
31/**
32 * The projection's stripes, in the accent on the track's colour, as the design's
33 * `repeating-linear-gradient(125deg, transparent 4px, accent 2px)`: `id` names it, `bg` is what shows between.
34 */
35export const stripes = (id: string, bg: string, period = 6, line = 2, ink: string = C.accent) =>
36  `<pattern id="${id}" width="${period}" height="${period}" patternUnits="userSpaceOnUse" patternTransform="rotate(35)"><rect width="${period}" height="${period}" style="fill:${bg}"/><rect width="${line}" height="${period}" style="fill:${ink}"/></pattern>`
37
38// ---- runs of text that wrap ----
39
40/** A piece of a sentence and how it looks: muted, or in the text colour and bolder, or in a state's colour. */
41export type Run = { s: string; fill?: string; weight?: number }
42
43/**
44 * Runs laid out as one paragraph, `width` wide, from the first baseline `y`; words break onto new lines as
45 * they need to, each keeping its run's look. The y of the last baseline comes back.
46 */
47export function rich(runs: Run[], x: number, y: number, width: number, size: number, lh = 1.6, base: Omit<Run, 's'> = {}): { svg: string; y: number; lines: number } {
48  // words, each knowing whether a space came before it (a run may end or begin with one)
49  type Word = { s: string; fill: string; weight: number; space: boolean }
50  const words: Word[] = []
51  let pending = false
52  for (const r of runs) {
53    for (const p of r.s.split(/(\s+)/)) {
54      if (p === '') continue
55      if (/^\s+$/.test(p)) { pending = true; continue }
56      words.push({ s: p, fill: r.fill ?? base.fill ?? C.muted, weight: r.weight ?? base.weight ?? 400, space: pending })
57      pending = false
58    }
59  }
60  const lines: Word[][] = [[]]
61  let cx = 0
62  for (const w of words) {
63    const line = lines[lines.length - 1]!
64    const gap = line.length && w.space ? size * 0.28 : 0
65    const ww = tw(w.s, size, w.weight)
66    if (line.length && cx + gap + ww > width) { lines.push([{ ...w, space: false }]); cx = ww; continue }
67    line.push(w)
68    cx += gap + ww
69  }
70  let svg = ''
71  lines.forEach((line, i) => {
72    if (!line.length) return
73    const ly = y + i * size * lh
74    svg += `<text x="${x.toFixed(1)}" y="${ly.toFixed(1)}" font-family="${FONT}" font-size="${size}px" xml:space="preserve">`
75    // consecutive words of the same look in one tspan, so the spacing is the font's own
76    let cur: { fill: string; weight: number; s: string } | null = null
77    const flush = () => { if (cur) svg += `<tspan style="fill:${cur.fill}" font-weight="${cur.weight}">${esc(cur.s)}</tspan>` }
78    for (const w of line) {
79      const sp = w.space ? ' ' : ''
80      if (cur && cur.fill === w.fill && cur.weight === w.weight) cur.s += sp + w.s
81      else { if (cur) cur.s += sp; flush(); cur = { fill: w.fill, weight: w.weight, s: w.s } }
82    }
83    flush()
84    svg += '</text>'
85  })
86  return { svg, y: y + (lines.length - 1) * size * lh, lines: lines.length }
87}
88
89// ---- icons ----
90
91/** The design's line icons, 24 units square. */
92export const ICONS = {
93  bars: '<path d="M5 20v-6m7 6V4m7 16V9" stroke-width="4"/>',
94  calendar: '<rect x="3" y="5" width="18" height="16" rx="3"/><path d="M7 3v4m10-4v4M3 11h18m-13 5h3m3 0h2"/>',
95  folder: '<path d="M3 7a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/>',
96  clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
97  model: '<path d="m12 3 9 5-9 5-9-5Zm-9 9 9 5 9-5m-18 5 9 5 9-5"/>',
98  lock: '<rect x="5" y="10" width="14" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3m-4 5v2"/>',
99  caretDown: '<path d="m6 9 6 6 6-6"/>',
100  caretRight: '<path d="m9 6 6 6-6 6"/>',
101  settings: '<circle cx="12" cy="12" r="3"/><path d="M12 2v3m0 14v3M2 12h3m14 0h3M4.9 4.9l2.1 2.1m10 10 2.1 2.1M4.9 19.1 7 17M17 7l2.1-2.1"/>',
102} as const
103export type Icon = keyof typeof ICONS
104
105/** An icon `size` px square at (x, y), stroked in `stroke`. */
106export const icon = (name: Icon, x: number, y: number, size: number, stroke: string, width = 1.6) =>
107  `<g transform="translate(${x.toFixed(1)} ${y.toFixed(1)}) scale(${(size / 24).toFixed(4)})" fill="none" style="stroke:${stroke}" stroke-width="${(width * 24 / size).toFixed(2)}" stroke-linecap="round" stroke-linejoin="round">${ICONS[name]}</g>`
108/** The icon on its rounded tile, as each card's header shows it. */
109export const tile = (name: Icon, x: number, y: number, size: number, ink: string = C.fg) =>
110  rect(x, y, size, size, `fill:${C.raised}`, ` rx="${(size * 0.21).toFixed(1)}"`) + icon(name, x + size * 0.25, y + size * 0.25, size * 0.5, ink, name === 'bars' ? 1.6 : 1.6)
111
112// ---- the card's header ----
113
114/** Below this the header's right-hand line goes under the title, as the design's phone layout does. */
115export const NARROW = 560
116
117/**
118 * A card's header, `width` wide: its icon on a tile, the title beside it, and at the right a figure line
119 * (under the title where the card is narrow). The y where the card's body starts comes back. `dense`, for a pane
120 * too short for the cards, draws it smaller and closer to the body.
121 */
122export function cardHeader(name: Icon, title: string, meta: Run[], width: number, dense = false): { svg: string; y: number } {
123  const narrow = width < NARROW
124  const ts = dense ? 20 : narrow ? 24 : SIZE.title, tileS = dense ? 32 : narrow ? 39 : 48, gap = dense ? 10 : narrow ? 11 : 15
125  const below = dense ? 14 : 22
126  const blockH = ts * 1.25
127  const top = Math.max(0, (tileS - blockH) / 2)
128  let svg = tile(name, 0, 0, tileS)
129  const tx = tileS + gap
130  svg += t(tx, top + ts * 1.02, title, { size: ts, weight: 650 })
131  const h = Math.max(blockH, tileS)
132  const metaW = meta.reduce((a, r) => a + tw(r.s, SIZE.meta, r.weight), 0)
133  if (!meta.length) return { svg, y: h + below }
134  if (!narrow && tx + tw(title, ts, 650) + 24 + metaW <= width) {
135    svg += rich(meta, width - metaW, h / 2 + SIZE.meta * 0.36, metaW + 40, SIZE.meta, 1.6, { fill: C.muted }).svg
136    return { svg, y: h + below }
137  }
138  const m = rich(meta, 0, h + 12 + SIZE.meta, width, SIZE.meta, 1.6, { fill: C.muted })
139  return { svg: svg + m.svg, y: m.y + below }
140}
141
142/**
143 * A bar on a track, the design's `usage-track`: solid to `used`, striped to `to`, a mark at `limit`; each a
144 * share (0–1) of the track. A tinted track's stripes sit on the accent's own tint (the today panel's).
145 */
146export function track(x: number, y: number, w: number, h: number, used: number, to: number, limit: number | null, o: { usedFill?: string; stripe: string; r?: number }): string {
147  const r = o.r ?? 5, ux = w * Math.max(0, Math.min(1, used)), px = w * Math.max(0, Math.min(1, to))
148  let s = rect(x, y, w, h, `fill:${C.raised}`, ` rx="${r}"`)
149  if (px > ux) s += rect(x + ux, y, px - ux, h, `fill:url(#${o.stripe})`)
150  if (ux > 0) s += `<path d="${sideRounded(x, y, ux, h, r, 'left')}" style="fill:${o.usedFill ?? C.accent}"/>`
151  if (limit !== null) s += rect(x + w * limit - (limit >= 1 ? 2 : 1), y - 4, 2, h + 8, `fill:${C.fg}`, ' rx="1"')
152  return s
153}
154
155/** Three labels under a track: left, centred and right, each a run of text. Onto more lines where they don't fit. */
156export function trackLabels(cols: Array<Run[] | null>, y: number, width: number, size = SIZE.meta): { svg: string; y: number } {
157  const ws = cols.map(c => (c ? c.reduce((a, r) => a + tw(r.s, size, r.weight ?? 400), 0) : 0))
158  const third = width / 3
159  if (ws.every(w => w <= third - 6)) {
160    let svg = ''
161    cols.forEach((c, i) => {
162      if (!c) return
163      const x = i === 0 ? 0 : i === 1 ? width / 2 - ws[1]! / 2 : width - ws[2]!
164      svg += rich(c, x, y, ws[i]! + 40, size, 1.6, { fill: C.muted }).svg
165    })
166    return { svg, y }
167  }
168  let svg = '', ly = y
169  cols.filter((c): c is Run[] => !!c).forEach((c, i) => {
170    const r = rich(c, 0, ly + (i ? size * 1.6 : 0), width, size, 1.6, { fill: C.muted })
171    svg += r.svg
172    ly = r.y
173  })
174  return { svg, y: ly }
175}
176
177/** A row of figures with a caption over each, the design's `metric-grid`: four across, two where it's narrow. */
178export function metricGrid(items: Array<{ label: string; value: string; fill?: string }>, width: number): { svg: string; y: number } {
179  const cols = width < NARROW ? 2 : 4, cw = (width - (cols - 1) * 12) / cols
180  let svg = '', y = 0
181  items.forEach((it, i) => {
182    const c = i % cols, r = Math.floor(i / cols), x = c * (cw + 12)
183    y = 13 + r * 54
184    svg += t(x, 13 + 13 + r * 54, it.label, { size: SIZE.meta, fill: C.muted })
185    svg += t(x, 13 + 13 + 5 + 19 + r * 54, it.value, { size: SIZE.meta, weight: 500, fill: it.fill ?? C.fg })
186  })
187  return { svg, y: y + 13 + 5 + 19 + 21 }
188}
189
hooks/models.ts 413 lines
1import type { Palettes, RangeReading, RangeStep } from '../types'
2import { C, DAY, FONT, HOUR, KEEP, drawing, esc, increments, isWatched, ofKind, usedBetween } from './range'
3import type { Model, Watch } from './range'
4import { DEFAULT_PALETTES } from './theme'
5import { SIZE, cardHeader, rect, t, tw } from './ui'
6
7/**
8 * What each model costs, learned from this account's own history.
9 *
10 * Every response reports its model and tokens. Between two readings of the
11 * 5-hour limit the plugin knows how far the limit rose and which models did
12 * the work then, so over many such stretches it can solve for each model's
13 * weight: rise ≈ Σ w·T. The 5-hour figure moves several times faster than the
14 * weekly one, so it gives several times the stretches; how models compare
15 * comes out the same from either limit, and the week's points are the 5-hour
16 * ones exchanged at the account's own rate (5-hour points per weekly point). Within a
17 * model, its token kinds are combined at that model's published price ratios
18 * (UNITS), so only the weight across models is learned. Each weight starts at
19 * the model's list price (LIST_PRICE), scaled to the account by one fitted
20 * number, and the stretches pull it from there as they add up: every model has
21 * a weight from its first response.
22 */
23
24/** A response's tokens, weighted as a model's price list weighs them: input 1, output 5, cache writes 1.25, cache reads 0.1. */
25export const units = (u: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }) =>
26  u.input_tokens + 5 * u.output_tokens + 1.25 * u.cache_creation_input_tokens + 0.1 * u.cache_read_input_tokens
27
28/** How far back the costs are learned from. */
29export const LEARN_SPAN = 14 * DAY
30/** Under this many stretches with the model in them, its weight is mostly its list price. */
31const MIN_STRETCHES = 5
32/** z for a 90% range. */
33const Z90 = 1.645
34/** The list price counts as this many typical stretches of the model: the data outweighs it once it has more. */
35const PRIOR_STRETCHES = 10
36
37/**
38 * Published API prices per million input tokens, by family and version (output is 5× input for every one, as
39 * UNITS weighs it). Only their ratios matter: they are each model's starting weight. A version not listed takes
40 * its family's newest price.
41 */
42export const LIST_PRICE: Record<string, number> = {
43  'fable 5.1': 10, 'fable 5': 10,
44  'opus 5.5': 4, 'opus 5': 5, 'opus 4.8': 5, 'opus 4.7': 5, 'opus 4.6': 5,
45  'sonnet 5.5': 2, 'sonnet 5': 2, 'sonnet 4.6': 3,
46  'haiku 5.5': 0.1, 'haiku 4.5': 1,
47}
48const NEWEST: Record<string, number> = { fable: 10, opus: 4, sonnet: 2, haiku: 0.1 }
49
50/** A model's list price per million input tokens, or null for a model of no known family. */
51export function listPrice(id: string): number | null {
52  const m = modelName(id)
53  if (m.family === 'other') return null
54  return LIST_PRICE[`${m.family} ${m.version.join('.')}`] ?? NEWEST[m.family]!
55}
56
57const FAMILIES = ['fable', 'opus', 'sonnet', 'haiku'] as const
58export type Family = (typeof FAMILIES)[number] | 'other'
59
60/** A model's name and family from its id: `claude-opus-5-5` is Opus 5.5, `claude-3-5-sonnet-20241022` Sonnet 3.5. */
61export function modelName(id: string): { name: string; family: Family; version: number[] } {
62  const parts = id.toLowerCase().replace(/\[.*\]$/, '').replace(/^claude-/, '').split('-').filter(p => !/^\d{8}$/.test(p) && p !== 'latest')
63  const family = (FAMILIES as readonly string[]).find(f => parts.includes(f)) as Family | undefined
64  const version = parts.filter(p => /^\d{1,2}$/.test(p)).map(Number)
65  if (!family) return { name: id, family: 'other', version }
66  const title = family[0]!.toUpperCase() + family.slice(1)
67  return { name: version.length ? `${title} ${version.join('.')}` : title, family, version }
68}
69
70/** Fable, Opus, Sonnet, Haiku, then the rest; newest version first within a family. */
71function byRank(a: string, b: string) {
72  const A = modelName(a), B = modelName(b)
73  const rank = (f: Family) => (f === 'other' ? 9 : FAMILIES.indexOf(f))
74  if (rank(A.family) !== rank(B.family)) return rank(A.family) - rank(B.family)
75  for (let i = 0; i < Math.max(A.version.length, B.version.length); i++) {
76    const d = (B.version[i] ?? 0) - (A.version[i] ?? 0)
77    if (d) return d
78  }
79  return a.localeCompare(b)
80}
81
82export type ModelCost = {
83  id: string
84  name: string
85  family: Family
86  /** 5-hour points per million weighted tokens (in list-price units until a stretch is watched); 0 when unknown. */
87  w: number
88  /** The 90% range as a share of `w`: Infinity while nothing is known. */
89  rel: number
90  /** Whether it has a weight at all: a list price, or a fit. */
91  shown: boolean
92  /** Whether that weight is still mostly the list price: too few stretches had the model in them. */
93  prior: boolean
94  /** Responses in the learning span, and how many of them subagents made. */
95  responses: number
96  sub: number
97}
98
99export type Learned = {
100  models: ModelCost[]
101  /** When the first stretch learned from began (ms), or null with none yet. */
102  since: number | null
103  /** 5-hour points per weekly point over the same span, or null until the weekly figure has moved enough to tell. */
104  perWeek: number | null
105}
106
107/** Solves the normal equations A·x = b (A symmetric, small) and gives A's inverse too; null when A is singular. */
108function solve(A: number[][], b: number[]): { x: number[]; inv: number[][] } | null {
109  const n = b.length
110  const M = A.map((row, i) => [...row, ...Array.from({ length: n }, (_, j) => (i === j ? 1 : 0)), b[i]!])
111  for (let c = 0; c < n; c++) {
112    let p = c
113    for (let r = c + 1; r < n; r++) if (Math.abs(M[r]![c]!) > Math.abs(M[p]![c]!)) p = r
114    if (Math.abs(M[p]![c]!) < 1e-12) return null
115    ;[M[c], M[p]] = [M[p]!, M[c]!]
116    const d = M[c]![c]!
117    for (let k = 0; k <= 2 * n; k++) M[c]![k]! /= d
118    for (let r = 0; r < n; r++) {
119      if (r === c) continue
120      const f = M[r]![c]!
121      if (f) for (let k = 0; k <= 2 * n; k++) M[r]![k]! -= f * M[c]![k]!
122    }
123  }
124  return { x: M.map(r => r[2 * n]!), inv: M.map(r => r.slice(n, 2 * n)) }
125}
126
127/**
128 * Each model's weight from the stretches between weekly readings that this
129 * computer watched whole, and how sure that weight is. Weights can't go
130 * below zero: a model whose best fit is negative is left out and refitted.
131 */
132export function learn(readings: readonly RangeReading[], steps: readonly RangeStep[], seen: readonly Watch[], now: number): Learned {
133  const from = now - LEARN_SPAN
134  const recent = steps.filter(s => s[0] >= from && s[0] <= now)
135  const ids = [...new Set(recent.map(s => s[1]))].sort(byRank)
136  // each point where it was first reached: a repeat of it (another session, another device) would split a
137  // stretch in two, the work before the repeat seeming to have cost nothing
138  const fives = ofKind(readings, 'five').filter((r, i, all) => r[0] >= from && !(i > 0 && all[i - 1]![2] === r[2] && Math.abs(all[i - 1]![3] - r[3]) <= 5 * 60_000))
139  const sorted = [...recent].sort((a, b) => a[0] - b[0])
140
141  // the stretches: how far the limit rose, and each model's tokens (in millions) meanwhile
142  const rows: Array<{ y: number; x: number[]; n: number }> = []
143  let since: number | null = null
144  for (let i = 1; i < fives.length; i++) {
145    const a = fives[i - 1]!, b = fives[i]!
146    // a reset in between, or a gap nobody here watched: usage from elsewhere would count against these models
147    if (Math.abs(a[3] - b[3]) > 5 * 60_000 || !isWatched(seen, a[0], b[0])) continue
148    const y = b[2] - a[2]
149    if (y < 0) continue
150    const x = ids.map(() => 0)
151    let n = 0
152    for (const s of sorted) if (s[0] > a[0] && s[0] <= b[0]) { x[ids.indexOf(s[1])]! += s[3] / 1e6; n++ }
153    if (n === 0) continue
154    rows.push({ y, x, n })
155    since ??= a[0]
156  }
157
158  // each model's starting weight: its list price, scaled to this account's points by one number fitted to every stretch
159  const price = ids.map(listPrice)
160  const z = rows.map(r => r.x.reduce((t, v, i) => t + v * (price[i] ?? 0), 0))
161  const zz = z.reduce((t, v) => t + v * v, 0)
162  const scale = zz > 0 ? rows.reduce((t, r, k) => t + r.y * z[k]!, 0) / zz : 1
163  const w0 = price.map(p => (p === null ? 0 : p * scale))
164  // how much the start counts: PRIOR_STRETCHES of the model's typical stretch
165  const lam = ids.map((_, i) => {
166    if (price[i] === null) return 0
167    const xs = rows.map(r => r.x[i]!).filter(v => v > 0)
168    return xs.length ? PRIOR_STRETCHES * xs.reduce((t, v) => t + v * v, 0) / xs.length : 0
169  })
170
171  // least squares over the models still in, pulled toward their start, dropping the most negative until none is
172  let active = ids.map((_, i) => i).filter(i => rows.some(r => r.x[i]! > 0))
173  let fit: { x: number[]; inv: number[][] } | null = null
174  while (active.length) {
175    const A = active.map(i => active.map(j => rows.reduce((t, r) => t + r.x[i]! * r.x[j]!, 0) + (i === j ? lam[i]! : 0)))
176    const b = active.map(i => rows.reduce((t, r) => t + r.x[i]! * r.y, 0) + lam[i]! * w0[i]!)
177    fit = solve(A, b)
178    if (!fit) break
179    const worst = fit.x.reduce((k, v, j) => (v < (fit!.x[k] ?? 0) ? j : k), 0)
180    if (fit.x[worst]! >= 0) break
181    active = active.filter((_, j) => j !== worst)
182    fit = null
183  }
184  // a model no watched stretch had, or one the fit dropped as negative, keeps its start
185  const w = ids.map((_, i) => w0[i]!), rel = ids.map(() => Infinity)
186  const fitted = fit && (rows.length > active.length || active.every(i => lam[i]! > 0))
187  if (fit && fitted) {
188    active.forEach((i, j) => { w[i] = fit!.x[j]! })
189    const rss = rows.reduce((t, r) => t + (r.y - r.x.reduce((u, v, i) => u + v * w[i]!, 0)) ** 2, 0)
190    // the limit is read at whole points, so each end of a stretch is off by part of the response that crossed
191    // the point, evenly anywhere in it: never trust a fit closer than that (two ends, each size²/12)
192    const perResponse = rows.reduce((t, r) => t + r.y, 0) / rows.reduce((t, r) => t + r.n, 0)
193    const s2 = Math.max(rss / Math.max(1, rows.length - active.length), perResponse ** 2 / 6)
194    active.forEach((i, j) => {
195      if (w[i]! > 0) rel[i] = Z90 * Math.sqrt(s2 * fit!.inv[j]![j]!) / w[i]!
196    })
197  }
198
199  // the exchange rate to weekly points, from what both limits rose by while watched
200  const weekPts = usedBetween(increments(readings, 'week', seen).filter(x => !x.hole), from, now)
201  const fivePts = usedBetween(increments(readings, 'five', seen).filter(x => !x.hole), from, now)
202
203  return {
204    since,
205    perWeek: weekPts >= 3 && fivePts > 0 ? fivePts / weekPts : null,
206    models: ids.map((id, i) => {
207      const mine = recent.filter(s => s[1] === id)
208      const stretches = rows.filter(r => r.x[i]! > 0).length
209      return { id, ...modelName(id), w: w[i]!, rel: rel[i]!, shown: w[i]! > 0, prior: stretches < MIN_STRETCHES, responses: mine.length, sub: mine.filter(s => s[4]).length }
210    }),
211  }
212}
213
214/** The model the others compare to: the one picked, else the one known most precisely from your use, else the most used. Null under two shown. */
215export function baselineOf(l: Learned, picked: string | undefined): ModelCost | null {
216  const shown = l.models.filter(m => m.shown)
217  if (shown.length < 2) return null
218  return shown.find(m => m.id === picked)
219    ?? [...shown].filter(m => !m.prior && isFinite(m.rel)).sort((a, b) => a.rel - b.rel)[0]
220    ?? [...shown].sort((a, b) => b.responses - a.responses)[0]!
221}
222
223/** The names the baseline buttons show: the family alone, unless two versions of it are shown. */
224export function shortNames(models: readonly ModelCost[]): Map<string, string> {
225  const count = (f: Family) => models.filter(m => m.family === f).length
226  return new Map(models.map(m => [m.id, m.family !== 'other' && count(m.family) === 1 ? m.name.replace(/ [\d.]+$/, '') : m.name]))
227}
228
229export type UsageSplit = {
230  kind: 'five' | 'week'
231  /** % of the limit used this window. */
232  used: number
233  /** Each model's % of the limit, largest first, split by effort (largest first). */
234  models: Array<{ id: string; name: string; family: Family; pct: number; effort: Array<[string, number]> }>
235  /** Used with no responses seen here behind it: another device, the phone, claude.ai, or a gap nobody watched. */
236  notRecorded: number
237  /** 100 − used, never below 0. */
238  unused: number
239}
240
241/**
242 * This window's use of a limit by model and effort. Each rise of the limit seen while watching is shared among
243 * the responses made since the reading before it, by their weighted tokens × their model's weight; a rise with
244 * no responses behind it, or over a gap, is not recorded. Rises adding up to more than the figure are scaled
245 * down to it; to less, the rest is not recorded. models + notRecorded + unused = 100.
246 */
247export function usageSplit(m: Model, readings: readonly RangeReading[], steps: readonly RangeStep[], seen: readonly Watch[], weightOf: (id: string) => number, now: number): UsageSplit {
248  const kind = m.kind as 'five' | 'week', from = m.resetsAt - (kind === 'five' ? 5 * HOUR : 7 * DAY), used = Math.min(100, m.pct)
249  const sorted = [...steps].sort((a, b) => a[0] - b[0])
250  const by = new Map<string, Map<string, number>>()
251  let total = 0, away = 0
252  for (const inc of increments(readings, kind, seen)) {
253    const overlap = Math.min(inc.end, now) - Math.max(inc.start, from)
254    if (overlap <= 0) continue
255    const amount = inc.amount * Math.min(1, overlap / Math.max(1, inc.end - inc.start))
256    total += amount
257    if (inc.hole || inc.from === undefined) { away += amount; continue }
258    // the responses in (inc.from, inc.end]
259    let lo = 0, hi = sorted.length
260    while (lo < hi) { const k = (lo + hi) >> 1; if (sorted[k]![0] <= inc.from) lo = k + 1; else hi = k }
261    const shares: Array<[string, string, number]> = []
262    let weight = 0
263    for (let i = lo; i < sorted.length && sorted[i]![0] <= inc.end; i++) {
264      const st = sorted[i]!, wt = st[3] * weightOf(st[1])
265      if (!(wt > 0)) continue
266      shares.push([st[1], st[2] || 'default', wt])
267      weight += wt
268    }
269    if (weight <= 0) { away += amount; continue }
270    for (const [id, effort, wt] of shares) {
271      const e = by.get(id) ?? new Map<string, number>()
272      e.set(effort, (e.get(effort) ?? 0) + amount * wt / weight)
273      by.set(id, e)
274    }
275  }
276  // the record may cover more or less than the figure: scale down to it, or the rest is not recorded
277  const scale = total > used && total > 0 ? used / total : 1
278  const models = [...by].map(([id, e]) => {
279    const effort = [...e].map(([k, v]): [string, number] => [k, v * scale]).sort((a, b) => b[1] - a[1])
280    return { id, ...modelName(id), pct: effort.reduce((t, x) => t + x[1], 0), effort }
281  }).filter(x => x.pct > 0).sort((a, b) => b.pct - a.pct || byRank(a.id, b.id))
282  return { kind, used, models, notRecorded: away * scale + Math.max(0, used - total), unused: Math.max(0, 100 - used) }
283}
284
285// ---- words ----
286
287const times = (x: number) => (x >= 1 ? x.toFixed(1) : x.toFixed(2)) + '×'
288const one = (n: number) => n.toFixed(1).replace(/\.0$/, '')
289/** A share of the weekly limit: "41.2%". */
290const pc = (n: number) => `${one(n)}%`
291
292/** A model's cost against the baseline, and its likely range. */
293export function ratio(m: ModelCost, b: ModelCost): { x: string; range: string } {
294  // only what was measured counts toward the range: a list price is taken as given
295  const x = m.w / b.w, err = Math.hypot(isFinite(m.rel) ? m.rel : 0, isFinite(b.rel) ? b.rel : 0)
296  return { x: times(x), range: `${times(Math.max(0, x * (1 - err)))}–${times(x * (1 + err))}` }
297}
298
299/** What the card counts, under its Details. */
300export const MODELS_INFO: Array<[string, string]> = [
301  ['The bar shows which models used up your limit.', 'A bigger piece means that model used more.'],
302  ['Some models cost more than others.', 'We start with a guess and get better the more you use Claude.'],
303  ['Grey stripes are use we couldn’t see,', 'like on your phone or the website.'],
304]
305
306/** A model's efforts worth naming: a sliver under 0.05% would read as 0%. */
307export const shownEffort = (m: UsageSplit['models'][number]) => m.effort.filter(([, v]) => v >= 0.05)
308
309/** The frame a split is in: what its 100% is. */
310export const splitFrame = (sp: UsageSplit) => (sp.kind === 'five' ? 'This 5-hour window · 100% = your 5-hour limit' : 'This week · 100% = your weekly limit')
311
312/** The split in words, for a reader that can't see the bar and for the terminal. */
313export function splitText(sp: UsageSplit): string {
314  const parts = [
315    ...sp.models.map(m => { const ef = shownEffort(m); return `${m.name} ${pc(m.pct)}${ef.length > 1 ? ` (${ef.map(([e, v]) => `${e} ${pc(v)}`).join(', ')})` : ''}` }),
316    ...(sp.notRecorded >= 0.05 ? [`not recorded ${pc(sp.notRecorded)}`] : []),
317    `unused ${pc(sp.unused)}`,
318  ]
319  return `${splitFrame(sp)}: ${parts.join(', ')}.`
320}
321
322/**
323 * Each model's token cost against the baseline, a row per model from the most to the least costly: its figure, and where
324 * the figure comes from (its list price, your use with its likely range, or a rough fit that needs more use).
325 */
326export function costRows(l: Learned, b: ModelCost | null): Array<{ id: string; name: string; x: string; note: string }> {
327  if (!b) return []
328  const others = l.models.filter(m => m.shown && m !== b)
329  if (!others.length) return []
330  return [b, ...others].sort((p, q) => q.w - p.w).map(m => {
331    if (m === b) return { id: m.id, name: m.name, x: '1×', note: 'baseline' }
332    const r = ratio(m, b)
333    const note = m.prior ? 'list price' : isFinite(m.rel) && m.rel <= 0.5 ? `likely ${r.range}` : 'rough, needs more use'
334    return { id: m.id, name: m.name, x: r.x, note }
335  })
336}
337
338// ---- drawing ----
339
340/** A model's colour for its cost figure: Opus the accent, then the second and third tones. */
341const colorOf = (f: Family) => (f === 'other' ? C.muted : C[f])
342
343/** The models card's head, `width` wide: its header, with the frame of the split under it on the right. */
344export function modelsHead(sp: UsageSplit | null, width: number, pal: Palettes = DEFAULT_PALETTES, dense = false): string {
345  const head = cardHeader('model', 'Models', sp ? [{ s: sp.kind === 'five' ? 'This 5-hour window' : 'This week' }] : [], width, dense)
346  return drawing(head.svg, Math.ceil(head.y + 4), pal)
347}
348
349/**
350 * The split, `width` wide: one stacked bar on the limit's scale (each model in its colour, what wasn't
351 * recorded hatched, what's unused faint), then a row per model with its figure and a chip per effort, and the
352 * not-recorded row.
353 */
354export function modelsUsage(sp: UsageSplit, width: number, pal: Palettes = DEFAULT_PALETTES): string {
355  let s = `<defs><pattern id="nr" width="5" height="5" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="5" height="5" style="fill:${C.raised}"/><rect width="2" height="5" style="fill:${C.faint}"/></pattern></defs>`
356  let y = 4
357  // the bar: models, then not recorded, then unused, 2px apart
358  const parts = [...sp.models.map(m => ({ v: m.pct, fill: colorOf(m.family) })), { v: sp.notRecorded, fill: 'url(#nr)' }].filter(x => x.v >= 0.05)
359  const H = 14
360  s += rect(0, y, width, H, `fill:${C.raised}`, ' rx="4"')
361  let x = 0
362  for (const p of parts) {
363    const w = Math.max(2, p.v / 100 * width)
364    s += rect(x, y, Math.min(w, width - x), H, `fill:${p.fill}`, x === 0 ? ' rx="4"' : '')
365    x += w + 2
366    if (x >= width) break
367  }
368  y += H + 8
369  const row = (name: string, v: number, dot: string, quiet: boolean) => {
370    const hy = y + 12 + SIZE.body * 1.05
371    s += rect(0, hy - 10, 8, 8, `fill:${dot}`, ' rx="2"')
372    s += t(15, hy, name, { size: SIZE.body, fill: quiet ? C.muted : C.fg }) + t(width, hy, pc(v), { size: SIZE.body, fill: quiet ? C.muted : C.fg, anchor: 'end' })
373    return hy
374  }
375  for (const m of sp.models) {
376    const hy = row(m.name, m.pct, colorOf(m.family), false)
377    y = hy + 4
378    const ef = shownEffort(m)
379    if (ef.length > 1 || (ef[0] && ef[0][0] !== 'default')) {
380      // a chip per effort: its name, and its share of the limit
381      let cx = 15, cy = hy + 6
382      for (const [e, v] of ef) {
383        const a = pc(v), w = 6 + tw(`${e} `, SIZE.meta) + tw(a, SIZE.meta) + 6
384        if (cx > 15 && cx + w > width) { cx = 15; cy += 27 }
385        s += rect(cx, cy, w, 22, `fill:${C.raised}`, ' rx="3"')
386        s += `<text x="${(cx + 6).toFixed(1)}" y="${(cy + 15.5).toFixed(1)}" font-family="${FONT}" font-size="${SIZE.meta}px" xml:space="preserve"><tspan style="fill:${C.muted}">${esc(`${e} `)}</tspan><tspan style="fill:${C.faint}">${esc(a)}</tspan></text>`
387        cx += w + 7
388      }
389      y = cy + 22
390    }
391  }
392  if (sp.notRecorded >= 0.05) y = row('Not recorded', sp.notRecorded, C.faint, true) + 4
393  if (!sp.models.length && sp.notRecorded < 0.05) {
394    y += 12 + SIZE.meta * 1.2
395    s += t(0, y, 'Nothing used yet this window.', { size: SIZE.meta, fill: C.muted })
396  }
397  return drawing(s, Math.ceil(y + 8), pal)
398}
399
400/** Steps older than the readings are kept are dropped, and repeats merged. */
401export function mergeSteps(lists: ReadonlyArray<readonly RangeStep[]>, now: number): RangeStep[] {
402  const seen = new Set<string>(), out: RangeStep[] = []
403  for (const list of lists) {
404    for (const s of list) {
405      const id = `${s[0]}:${s[1]}:${s[3]}`
406      if (s[0] < now - KEEP || seen.has(id)) continue
407      seen.add(id)
408      out.push(s)
409    }
410  }
411  return out.sort((a, b) => a[0] - b[0])
412}
413
hooks/sync.ts 967 lines
1import type { HttpInit, HttpResponse } from 'claude-code'
2
3import type { RangeDevice, RangeReading, RangeStep, RangeSync, RangeWatch } from '../types'
4import { DAY, HOUR, KEEP, MIN } from './range'
5
6/**
7 * Sync across devices: each device uploads what this computer recorded for the
8 * signed-in Claude account, one list per UTC day (`d:<device>-<YYYYMMDD>`,
9 * `[readings, watched spans, steps]`), and downloads the other devices' lists,
10 * which are read beside the local ones. Off until the person signs in.
11 *
12 * Every session on this computer uploads the union of all the lists recorded
13 * here (its own, the other sessions', the other copies' stores), never what it
14 * downloaded: sessions share the device's day keys, so each upload is the whole
15 * day and none overwrites another's part of it.
16 */
17
18export const DEFAULT_SERVER = 'https://token-range-monitor.micke-dahlgren.workers.dev'
19/** How often a signed-in session syncs. */
20export const SYNC_EVERY = 10 * MIN
21/** The first retry after a failure; each further failure doubles it, up to BACKOFF_MAX. */
22export const BACKOFF_BASE = 2 * MIN
23export const BACKOFF_MAX = HOUR
24/** How long a sign-in code is waited for at most. */
25export const LINK_TTL = 10 * MIN
26/** How long "Delete synced data" and a device's "Remove" wait for their confirming press. */
27export const CONFIRM_FOR = 10_000
28/** Opening the pane asks the server for the device list at most this often (each sync asks anyway). */
29export const DEVICES_FRESH = 30_000
30
31/** The server's limits, with some room left. */
32export const MAX_LIST_BYTES = 128 * 1024 - 1024
33export const MAX_LISTS_PER_PUT = 50
34export const MAX_BODY_BYTES = 256 * 1024 - 8 * 1024
35
36/** Store keys: none matches the record's `[<account>/](r|w|u):` keys, so the record's cleanup never touches them. */
37export const DEVICE_KEY = 'sync:device'
38export const AUTH_KEY = 'sync:auth'
39export const LINK_KEY = 'sync:link'
40/** This computer's name as a command on the host found it, for sessions that can't run one (the desktop). */
41export const NAME_KEY = 'sync:name'
42/** Per Claude account: the download cursor, the fingerprint of each day list last uploaded, when it last synced. */
43export const acctKey = (account: string) => `sync:acct:${account}`
44/** A downloaded list, kept so a restart shows it offline. */
45export const cacheKey = (account: string, key: string) => `sync:dl:${account}:${key}`
46const CACHE_PREFIX = 'sync:dl:'
47
48/** One day's list: `[readings, watched spans, steps]`. */
49export type DayData = [RangeReading[], RangeWatch[], RangeStep[]]
50/** Lists as the record holds them: reading lists, watched spans, step lists. */
51export type Lists = { readings: Array<readonly RangeReading[]>; spans: RangeWatch[]; steps: Array<readonly RangeStep[]> }
52export type Outgoing = { key: string; data: DayData; fp: string }
53
54// ---------------------------------------------------------------- pure parts
55
56const pad = (n: number) => String(n).padStart(2, '0')
57/** The UTC day `t` falls in, as `YYYYMMDD`. */
58export function dayOf(t: number): string {
59  const d = new Date(t)
60  return `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}`
61}
62/** When a `YYYYMMDD` UTC day starts, in ms. */
63export const dayStart = (day: string) => Date.UTC(Number(day.slice(0, 4)), Number(day.slice(4, 6)) - 1, Number(day.slice(6, 8)))
64
65/** A day list's key; a day too big for one list goes on in parts `.1`, `.2`, ... */
66export const listKey = (device: string, day: string, part = 0) => `d:${device}-${day}${part ? `.${part}` : ''}`
67export function parseListKey(key: string): { device: string; day: string; part: number } | null {
68  const m = /^d:([A-Za-z0-9._-]+)-(\d{8})(?:\.(\d+))?$/.exec(key)
69  return m ? { device: m[1]!, day: m[2]!, part: Number(m[3] ?? 0) } : null
70}
71
72/** A short random id for this device: letters and digits, safe in a key and a URL. */
73export function newDeviceId(now: number, random: () => number = Math.random): string {
74  let s = now.toString(36)
75  while (s.length < 16) s += Math.floor(random() * 36).toString(36)
76  return s
77}
78export const isDeviceId = (v: unknown): v is string => typeof v === 'string' && /^[A-Za-z0-9]{6,40}$/.test(v)
79
80/**
81 * A watched span split at each UTC midnight it crosses, so every day's list
82 * holds only that day and stops changing once the day is over:
83 * `[23:50, 00:10]` becomes `[23:50, 23:59:59.999]` and `[00:00, 00:10]`.
84 */
85export function splitSpan([a, b]: readonly [number, number]): RangeWatch[] {
86  if (!(b >= a)) return []
87  const out: RangeWatch[] = []
88  let s = a
89  for (let end = dayStart(dayOf(s)) + DAY; end <= b; end += DAY) {
90    out.push([s, end - 1])
91    s = end
92  }
93  out.push([s, b])
94  return out
95}
96
97/** Overlapping spans joined: several sessions watching at once is one stretch watched. */
98export function joinSpans(spans: readonly RangeWatch[]): RangeWatch[] {
99  const out: RangeWatch[] = []
100  for (const [a, b] of [...spans].filter(w => w[1] >= w[0]).sort((x, y) => x[0] - y[0] || x[1] - y[1])) {
101    const last = out[out.length - 1]
102    if (last && a <= last[1]) last[1] = Math.max(last[1], b)
103    else out.push([a, b])
104  }
105  return out
106}
107
108/**
109 * The record's lists packed into one list per UTC day, repeats dropped:
110 * readings and steps by their time, watched spans split at midnight. Only the
111 * days wholly inside KEEP, so a day's list never shrinks as its start ages out.
112 * Steps go as their first 5 elements: a project name 1.4.0 recorded never leaves the computer.
113 */
114export function packDays(lists: Lists, now: number): Map<string, DayData> {
115  const days = new Map<string, DayData>()
116  const from = now - KEEP
117  const dayFor = (t: number): DayData | null => {
118    const day = dayOf(t)
119    if (dayStart(day) < from || t > now + HOUR) return null
120    let d = days.get(day)
121    if (!d) days.set(day, (d = [[], [], []]))
122    return d
123  }
124  const seenR = new Set<string>()
125  for (const list of lists.readings) {
126    for (const r of list) {
127      const id = `${r[0]}:${r[1]}:${r[2]}`
128      if (seenR.has(id)) continue
129      seenR.add(id)
130      dayFor(r[0])?.[0].push(r)
131    }
132  }
133  for (const span of joinSpans(lists.spans)) for (const piece of splitSpan(span)) dayFor(piece[0])?.[1].push(piece)
134  const seenS = new Set<string>()
135  for (const list of lists.steps) {
136    for (const s of list) {
137      const id = `${s[0]}:${s[1]}:${s[3]}`
138      if (seenS.has(id)) continue
139      seenS.add(id)
140      // project names stay on this computer
141      dayFor(s[0])?.[2].push(s.slice(0, 5) as RangeStep)
142    }
143  }
144  for (const [, d] of days) {
145    d[0].sort((a, b) => a[0] - b[0] || a[1] - b[1])
146    d[1].sort((a, b) => a[0] - b[0])
147    d[2].sort((a, b) => a[0] - b[0])
148  }
149  return new Map([...days].sort(([a], [b]) => (a < b ? -1 : 1)))
150}
151
152/** The UTF-8 length of a string, as the server counts it. */
153export function utf8Bytes(s: string): number {
154  let n = 0
155  for (let i = 0; i < s.length; i++) {
156    const c = s.charCodeAt(i)
157    if (c < 0x80) n += 1
158    else if (c < 0x800) n += 2
159    else if (c >= 0xd800 && c < 0xdc00) { n += 4; i++ }
160    else n += 3
161  }
162  return n
163}
164const sizeOf = (v: unknown) => utf8Bytes(JSON.stringify(v))
165
166/**
167 * The days as the lists this device uploads. A day bigger than one list allows
168 * (a very busy day of responses) carries its steps on in parts `.1`, `.2`, ...
169 */
170export function packLists(device: string, days: ReadonlyMap<string, DayData>, max = MAX_LIST_BYTES): Array<{ key: string; data: DayData }> {
171  const out: Array<{ key: string; data: DayData }> = []
172  for (const [day, data] of days) {
173    if (sizeOf(data) <= max) { out.push({ key: listKey(device, day), data }); continue }
174    let part: DayData = [data[0], data[1], []]
175    let size = sizeOf(part)
176    let n = 0
177    for (const s of data[2]) {
178      const add = sizeOf(s) + 1
179      if (size + add > max && part[2].length > 0) {
180        out.push({ key: listKey(device, day, n++), data: part })
181        part = [[], [], []]
182        size = sizeOf(part)
183      }
184      part[2].push(s)
185      size += add
186    }
187    out.push({ key: listKey(device, day, n), data: part })
188  }
189  return out
190}
191
192/** A short fingerprint of a list's content: FNV-1a over its JSON, and its length. */
193export function fingerprint(data: unknown): string {
194  const s = JSON.stringify(data)
195  let h = 0x811c9dc5
196  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193)
197  return `${(h >>> 0).toString(36)}.${s.length.toString(36)}`
198}
199
200/** The lists whose content changed since they were last uploaded. */
201export function changedLists(lists: ReadonlyArray<{ key: string; data: DayData }>, sent: Readonly<Record<string, string>>): Outgoing[] {
202  return lists.map(l => ({ ...l, fp: fingerprint(l.data) })).filter(l => sent[l.key] !== l.fp)
203}
204
205/** Lists grouped into requests the server takes: at most 50 lists and 256 KB each. */
206export function batches<L extends { key: string; data: unknown }>(lists: readonly L[], maxLists = MAX_LISTS_PER_PUT, maxBytes = MAX_BODY_BYTES): L[][] {
207  const out: L[][] = []
208  let cur: L[] = []
209  let size = 0
210  for (const l of lists) {
211    const add = sizeOf({ key: l.key, data: l.data }) + 1
212    if (cur.length && (cur.length >= maxLists || size + add > maxBytes)) { out.push(cur); cur = []; size = 0 }
213    cur.push(l)
214    size += add
215  }
216  if (cur.length) out.push(cur)
217  return out
218}
219
220/** When to try again after `failures` failures in a row: doubling from BACKOFF_BASE up to BACKOFF_MAX, never sooner than the server asked. */
221export function backoffMs(failures: number, retryAfterMs = 0): number {
222  return Math.max(retryAfterMs, Math.min(BACKOFF_MAX, BACKOFF_BASE * 2 ** Math.max(0, failures - 1)))
223}
224
225const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
226/**
227 * A downloaded list's data, its items checked one by one (another device may run another version); null when it is no day list.
228 * Steps are cut to their first 5 elements, so another device's list never brings anything more in.
229 */
230export function unpack(data: unknown): DayData | null {
231  if (!Array.isArray(data) || data.length < 3 || !data.slice(0, 3).every(Array.isArray)) return null
232  const [r, w, s] = data as unknown[][]
233  return [
234    r!.filter((x): x is RangeReading => Array.isArray(x) && isNum(x[0]) && (x[1] === 0 || x[1] === 1) && isNum(x[2]) && isNum(x[3])),
235    w!.filter((x): x is RangeWatch => Array.isArray(x) && isNum(x[0]) && isNum(x[1])),
236    s!.filter((x): x is RangeStep => Array.isArray(x) && isNum(x[0]) && typeof x[1] === 'string' && typeof x[2] === 'string' && isNum(x[3]) && (x[4] === 0 || x[4] === 1))
237      .map(x => x.slice(0, 5) as RangeStep),
238  ]
239}
240
241/** Downloaded day lists as the record's lists. */
242export function unpacked(lists: Iterable<DayData>): Lists {
243  const out: Lists = { readings: [], spans: [], steps: [] }
244  for (const [r, w, s] of lists) {
245    out.readings.push(r)
246    out.spans.push(...w)
247    out.steps.push(s)
248  }
249  return out
250}
251
252/** "just now", "3 min ago", "2 h ago", "4 days ago". */
253export function agoText(t: number | undefined, now: number): string {
254  if (t === undefined) return 'not synced yet'
255  const d = Math.max(0, now - t)
256  if (d < MIN) return 'just now'
257  if (d < HOUR) return `${Math.floor(d / MIN)} min ago`
258  if (d < DAY) return `${Math.floor(d / HOUR)} h ago`
259  const n = Math.floor(d / DAY)
260  return `${n} day${n === 1 ? '' : 's'} ago`
261}
262
263/** The server's base URL from the plugin's option: an http(s) URL, no trailing slash; the default otherwise. */
264export function serverFrom(option: unknown): string {
265  const s = typeof option === 'string' ? option.trim().replace(/\/+$/, '') : ''
266  return /^https?:\/\/[^\s/]+/.test(s) ? s : DEFAULT_SERVER
267}
268
269const minutes = (ms: number) => `${Math.max(1, Math.round(ms / MIN))} min`
270
271// ---------------------------------------------------------------- the network
272
273export class SyncError extends Error {
274  constructor(
275    /** `auth`: drop the token; `retry`: back off and try again; `cursor`: start over; `rejected`: the server refused what was sent. */
276    readonly kind: 'auth' | 'retry' | 'cursor' | 'rejected',
277    readonly status: number,
278    readonly code: string,
279    readonly detail?: string,
280    readonly retryAfterMs = 0,
281  ) {
282    super(code)
283  }
284}
285
286type Json = Record<string, unknown>
287async function call(io: SyncIO, method: string, path: string, body?: unknown, token?: string): Promise<Json> {
288  const headers: Record<string, string> = { accept: 'application/json' }
289  if (body !== undefined) headers['content-type'] = 'application/json'
290  if (token) headers.authorization = `Bearer ${token}`
291  let res
292  try {
293    res = await io.fetch(`${state.server}${path}`, body === undefined ? { method, headers } : { method, headers, body: JSON.stringify(body) })
294  } catch {
295    throw new SyncError('retry', 0, 'network')
296  }
297  let json: Json = {}
298  try {
299    const v = JSON.parse(res.text) as unknown
300    if (v && typeof v === 'object' && !Array.isArray(v)) json = v as Json
301  } catch { /* not JSON */ }
302  if (res.ok) return json
303  const code = typeof json.error === 'string' ? json.error : `http_${res.status}`
304  const detail = typeof json.message === 'string' ? json.message : undefined
305  const retryAfter = Number(res.headers['retry-after'] ?? 0) * 1000 || 0
306  const kind = res.status === 401 ? 'auth'
307    : res.status === 400 && code === 'invalid_cursor' ? 'cursor'
308    : res.status === 429 || res.status >= 500 ? 'retry'
309    : 'rejected'
310  throw new SyncError(kind, res.status, code, detail, retryAfter)
311}
312
313/** What a computer is called when nothing better is known, by its platform. */
314export const GENERIC_NAMES = { mac: 'Mac', windows: 'Windows PC', linux: 'Linux computer', other: 'Computer' } as const
315export type Platform = keyof typeof GENERIC_NAMES
316const isGeneric = (name: string) => (Object.values(GENERIC_NAMES) as string[]).includes(name)
317
318/** A name as the server takes it: control characters out, trimmed, at most 64 characters; null when nothing is left. */
319export function cleanName(v: unknown): string | null {
320  if (typeof v !== 'string') return null
321  const s = [...v.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()].slice(0, 64).join('').trim()
322  return s || null
323}
324
325/** The platform as the environment gives it away: Windows sets OS, macOS sets __CF_USER_TEXT_ENCODING and keeps homes under /Users. */
326export function platformOf(env: { os?: string; cfEncoding?: string; home?: string }): Platform {
327  if (env.os === 'Windows_NT') return 'windows'
328  if (env.cfEncoding || env.home?.startsWith('/Users/')) return 'mac'
329  if (env.home?.startsWith('/home/') || env.home === '/root') return 'linux'
330  return 'other'
331}
332
333/** The server's device list, as far as it can be read. */
334export function parseDevices(v: unknown): RangeDevice[] {
335  if (!Array.isArray(v)) return []
336  const out: RangeDevice[] = []
337  for (const d of v as Array<Record<string, unknown>>) {
338    if (!d || typeof d.id !== 'string' || !d.id) continue
339    out.push({
340      id: d.id,
341      name: typeof d.name === 'string' && d.name ? d.name : null,
342      ...(isNum(d.lastSeenAt) ? { lastSeenAt: d.lastSeenAt } : {}),
343      current: d.current === true,
344    })
345  }
346  // this device first, the others as the server lists them (oldest link first)
347  return [...out.filter(d => d.current), ...out.filter(d => !d.current)]
348}
349
350export const deviceLabel = (d: { name: string | null }) => d.name ?? 'Unnamed device'
351
352// ---------------------------------------------------------------- state
353
354type Auth = { token: string; email: string; server: string }
355type Link = { pollToken: string; code: string; url: string; interval: number; expiresAt: number; server: string }
356type AcctState = { cursor?: string; sent: Record<string, string>; last?: number }
357
358/**
359 * What sync reaches outside itself, handed in by the hooks module (which alone
360 * calls the engine): the clock, the network, the store, the environment, the
361 * pane's view, and the record itself.
362 */
363export type SyncIO = {
364  now: () => Promise<number>
365  fetch: (url: string, init: HttpInit) => Promise<HttpResponse>
366  get: (key: string) => Promise<unknown>
367  set: (key: string, value: unknown) => Promise<void>
368  del: (key: string) => Promise<void>
369  keys: () => Promise<string[]>
370  /** `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, as set. */
371  trafficOff: () => Promise<string | undefined>
372  /**
373   * The computer's name, for the server's list of devices: its own name when
374   * one can be found, else a generic one for its platform ("Mac", "Windows PC").
375   */
376  hostName: () => Promise<string | undefined>
377  every: (ms: number, fn: () => void) => { cancel: () => void }
378  after: (ms: number, fn: () => void) => { cancel: () => void }
379  log: (text: string, options?: { to: 'debug' }) => void
380  view: () => Promise<RangeSync>
381  setView: (change: (v: RangeSync) => RangeSync) => Promise<void>
382  /** The Claude account the record is under now (`<accountUuid>.<orgUuid>`, `none`, or '' before it's known). */
383  account: () => string
384  /** Every list recorded on this computer for the current account (never the downloaded ones). */
385  collect: () => Promise<Lists>
386  /** Re-reads the record (downloaded lists included) and redraws. */
387  reload: () => Promise<void>
388  /** A device id another copy of the plugin on this computer already chose, if any. */
389  peekDevice: () => Promise<string | undefined>
390}
391
392const state = {
393  server: DEFAULT_SERVER,
394  /** The session's own reach, from its start: timers begun from a press run on it, not on the press's. */
395  home: null as SyncIO | null,
396  started: false,
397  disabled: false,
398  device: '',
399  auth: null as Auth | null,
400  failures: 0,
401  nextAt: 0,
402  uploadPausedUntil: 0,
403  uploadNote: undefined as string | undefined,
404  rejectLogged: false,
405  running: false,
406  poll: null as { cancel: () => void } | null,
407  polling: false,
408  confirm: null as { cancel: () => void } | null,
409  /** Downloaded lists per account, by list key. */
410  far: new Map<string, Map<string, DayData>>(),
411  /** The signed-in user's devices, as the server last listed them; when they were asked for. */
412  devices: undefined as RangeDevice[] | undefined,
413  devicesAt: 0,
414  /** The device a "Remove" is waiting on its confirming press for, and the timer that gives up on it. */
415  confirmRemove: undefined as string | undefined,
416  confirmRm: null as { cancel: () => void } | null,
417  /** Whether this session compared the server's name for this device with its own yet (once a session, and once after a sign-in). */
418  nameChecked: false,
419}
420
421/** Called as the module loads: a fresh load starts from nothing (its timers went with the old one). */
422export function configureSync(server: unknown) {
423  Object.assign(state, {
424    home: null, started: false, disabled: false, device: '', auth: null, failures: 0, nextAt: 0, uploadPausedUntil: 0,
425    uploadNote: undefined, rejectLogged: false, running: false, poll: null, polling: false, confirm: null, far: new Map(),
426    devices: undefined, devicesAt: 0, confirmRemove: undefined, confirmRm: null, nameChecked: false,
427  })
428  state.server = serverFrom(server)
429}
430
431const usable = (account: string) => !!account && account !== 'none'
432const isAuth = (v: unknown): v is Auth => !!v && typeof (v as Auth).token === 'string' && !!(v as Auth).token && typeof (v as Auth).server === 'string'
433const isLink = (v: unknown): v is Link => !!v && typeof (v as Link).pollToken === 'string' && typeof (v as Link).code === 'string' && typeof (v as Link).url === 'string' && isNum((v as Link).expiresAt)
434
435async function setView(io: SyncIO, next: RangeSync | ((v: RangeSync) => RangeSync)) {
436  await io.setView(v => (typeof next === 'function' ? next(v ?? { status: 'signedOut' }) : next))
437}
438
439/** The view for a signed-in device, with its account's last sync. */
440async function signedInView(io: SyncIO, note?: string): Promise<RangeSync> {
441  const account = io.account()
442  const last = usable(account) ? (await readAcct(io, account)).last : undefined
443  const n = note ?? state.uploadNote ?? (usable(account) ? undefined : 'Syncs once Claude Code is signed in to a Pro or Max subscription.')
444  return {
445    status: 'signedIn', email: state.auth?.email ?? '', ...(last !== undefined ? { last } : {}), ...(n ? { note: n } : {}),
446    ...(state.devices ? { devices: state.devices } : {}),
447    ...(state.confirmRemove ? { confirmRemove: state.confirmRemove } : {}),
448  }
449}
450
451async function readAcct(io: SyncIO, account: string): Promise<AcctState> {
452  const v = (await io.get(acctKey(account))) as Partial<AcctState> | undefined
453  return { sent: v?.sent && typeof v.sent === 'object' ? v.sent : {}, ...(typeof v?.cursor === 'string' ? { cursor: v.cursor } : {}), ...(isNum(v?.last) ? { last: v.last } : {}) }
454}
455/** Read, changed and written back at once, so sessions sharing the store lose as little of each other's as can be. */
456async function patchAcct(io: SyncIO, account: string, change: (s: AcctState) => void) {
457  const s = await readAcct(io, account)
458  change(s)
459  await io.set(acctKey(account), s)
460}
461
462const isSet = (v: string | undefined) => !!v && v !== '0' && v.toLowerCase() !== 'false'
463
464/**
465 * Starts sync for this session: off when nonessential traffic is; the device id
466 * found or made; the sign-in kept from before; a sign-in waiting in the browser
467 * picked up again.
468 */
469export async function startSync(io: SyncIO) {
470  state.started = true
471  state.home = io
472  state.disabled = isSet(await io.trafficOff().catch(() => undefined))
473  if (state.disabled) {
474    state.auth = null
475    await setView(io, { status: 'off', note: 'Off: CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC is set.' })
476    return
477  }
478  const now = await io.now()
479  const saved = await io.get(DEVICE_KEY)
480  if (isDeviceId(saved)) state.device = saved
481  else {
482    const peeked = await io.peekDevice().catch(() => undefined)
483    state.device = isDeviceId(peeked) ? peeked : newDeviceId(now)
484    await io.set(DEVICE_KEY, state.device)
485  }
486  await refresh(io)
487  // a view left from before a reload says what's so now
488  if (!state.auth && !state.poll && (await io.view()).status !== 'signedOut') await setView(io, { status: 'signedOut' })
489}
490
491/** Picks up a sign-in, sign-out or sign-in in progress another session on this computer made. */
492async function refresh(io: SyncIO) {
493  if (state.disabled) return
494  const stored = await io.get(AUTH_KEY)
495  const auth = isAuth(stored) && stored.server === state.server ? stored : null
496  if (auth?.token !== state.auth?.token) {
497    state.auth = auth
498    state.far.clear()
499    state.failures = 0
500    state.nextAt = 0
501    if (auth) {
502      stopPolling()
503      await setView(io, await signedInView(io))
504    } else if ((await io.view()).status === 'signedIn') {
505      await setView(io, { status: 'signedOut' })
506    }
507  }
508  if (state.auth) return
509  const link = await io.get(LINK_KEY)
510  const now = await io.now()
511  if (isLink(link) && link.server === state.server && now < link.expiresAt) {
512    if (!state.poll) {
513      await setView(io, { status: 'waiting', code: link.code, url: link.url })
514      startPolling(io, link)
515    }
516  } else if (state.poll) {
517    // cancelled in another session
518    stopPolling()
519    await setView(io, { status: 'signedOut' })
520  }
521}
522
523/** The lists downloaded for this account, while signed in: read from the store once, then kept as they come. */
524export async function downloadedFor(io: SyncIO, account: string): Promise<Lists> {
525  if (state.disabled || !state.auth || !usable(account)) return { readings: [], spans: [], steps: [] }
526  let lists = state.far.get(account)
527  if (!lists) {
528    lists = new Map()
529    state.far.set(account, lists)
530    const prefix = cacheKey(account, '')
531    for (const key of await io.keys()) {
532      if (!key.startsWith(prefix)) continue
533      const data = unpack(await io.get(key))
534      if (data) lists.set(key.slice(prefix.length), data)
535    }
536  }
537  return unpacked(lists.values())
538}
539
540/**
541 * Once a minute: picks up what other sessions changed, and syncs when it's due
542 * (every 10 minutes, later after failures). `force` syncs now.
543 */
544export async function syncTick(io: SyncIO, force = false) {
545  if (!state.started || state.disabled) return
546  await refresh(io)
547  const now = await io.now()
548  // ticks come a minute apart: one due within the next half minute is due now
549  if (!state.auth || (!force && now + 30_000 < state.nextAt)) return
550  await syncNow(io)
551}
552
553/** Uploads what changed, then downloads what's new; a failure backs off and the record carries on locally. */
554export async function syncNow(io: SyncIO) {
555  const account = io.account()
556  const auth = state.auth
557  if (state.running || state.disabled || !auth) return
558  if (!usable(account)) {
559    await setView(io, await signedInView(io))
560    return
561  }
562  state.running = true
563  try {
564    const now = await io.now()
565    try {
566      await upload(io, account, auth.token, now)
567    } catch (err) {
568      if (!(err instanceof SyncError) || err.kind !== 'rejected') throw err
569      // too big or over the quota: said once, and not tried again for an hour; downloads go on
570      state.uploadPausedUntil = now + HOUR
571      state.uploadNote = `Couldn't upload: ${err.detail ?? err.code}.`
572      if (!state.rejectLogged) {
573        state.rejectLogged = true
574        io.log(`Token Range Monitor sync: the server refused an upload (${err.status} ${err.code}${err.detail ? `: ${err.detail}` : ''}). Retrying in an hour.`, { to: 'debug' })
575      }
576    }
577    // signed out meanwhile: nothing more is kept
578    if (state.auth !== auth) return
579    const got = await download(io, account, auth.token, now)
580    if (state.auth !== auth) return
581    state.failures = 0
582    state.nextAt = now + SYNC_EVERY
583    if (now >= state.uploadPausedUntil) state.uploadNote = undefined
584    await patchAcct(io, account, s => { s.last = now })
585    await setView(io, await signedInView(io))
586    if (got) await io.reload()
587    await refreshDevices(io)
588  } catch (err) {
589    if (state.auth === auth) await failed(io, err)
590  } finally {
591    state.running = false
592  }
593}
594
595async function failed(io: SyncIO, err: unknown) {
596  const now = await io.now()
597  const e = err instanceof SyncError ? err : new SyncError('retry', 0, 'error')
598  if (e.kind === 'auth') {
599    await forget(io)
600    await setView(io, {
601      status: 'signedOut',
602      note: e.code === 'device_expired'
603        ? 'This device was signed out after 90 days unused. Sign in again to sync.'
604        : 'This device is no longer signed in to sync. Sign in again to sync.',
605    })
606    await io.reload()
607    return
608  }
609  state.failures++
610  const wait = backoffMs(state.failures, e.retryAfterMs)
611  state.nextAt = now + wait
612  const why = e.status === 0 ? "Couldn't reach the sync server"
613    : e.status === 429 ? 'The sync server asked to slow down'
614    : e.code === 'not_configured' ? "The sync server isn't set up"
615    : e.status === 503 ? 'The sync server is over its free daily limit'
616    : `The sync server answered ${e.status}`
617  await setView(io, await signedInView(io, `${why}; trying again in ${minutes(wait)}.`))
618}
619
620async function upload(io: SyncIO, account: string, token: string, now: number) {
621  if (now < state.uploadPausedUntil) return
622  const lists = packLists(state.device, packDays(await io.collect(), now))
623  const todo = changedLists(lists, (await readAcct(io, account)).sent)
624  for (const batch of batches(todo)) {
625    await call(io, 'PUT', '/v1/lists', { account, lists: batch.map(l => ({ key: l.key, data: l.data })) }, token)
626    await patchAcct(io, account, s => { for (const l of batch) s.sent[l.key] = l.fp })
627  }
628  // fingerprints of days gone from the record are dropped
629  await patchAcct(io, account, s => {
630    for (const key of Object.keys(s.sent)) {
631      const k = parseListKey(key)
632      if (!k || dayStart(k.day) < now - KEEP) delete s.sent[key]
633    }
634  })
635}
636
637/** Follows the cursor through every page; returns how many lists came. Repeats are harmless: the record merges them. */
638async function download(io: SyncIO, account: string, token: string, now: number): Promise<number> {
639  let cursor = (await readAcct(io, account)).cursor
640  let lists = state.far.get(account)
641  if (!lists) await downloadedFor(io, account)
642  lists = state.far.get(account) ?? new Map<string, DayData>()
643  state.far.set(account, lists)
644  let got = 0
645  let restarted = false
646  for (let page = 0; page < 50; page++) {
647    let r: Json
648    try {
649      r = await call(io, 'GET', `/v1/lists?account=${encodeURIComponent(account)}${cursor ? `&since=${encodeURIComponent(cursor)}` : ''}`, undefined, token)
650    } catch (err) {
651      // a cursor the server can't read: everything again, once
652      if (err instanceof SyncError && err.kind === 'cursor' && !restarted) { restarted = true; cursor = undefined; continue }
653      throw err
654    }
655    for (const l of Array.isArray(r.lists) ? r.lists as Array<{ key?: unknown; data?: unknown }> : []) {
656      const k = typeof l?.key === 'string' ? parseListKey(l.key) : null
657      // this device's own lists are already here
658      if (!k || k.device === state.device || dayStart(k.day) + DAY < now - KEEP) continue
659      const data = unpack(l.data)
660      if (!data) continue
661      lists.set(l.key as string, data)
662      got++
663      // kept for a restart; a store that is full keeps it for this session only
664      try { await io.set(cacheKey(account, l.key as string), data) } catch { /* in memory */ }
665    }
666    if (typeof r.cursor === 'string') cursor = r.cursor
667    if (r.more !== true) break
668  }
669  await patchAcct(io, account, s => { if (cursor) s.cursor = cursor; else delete s.cursor })
670  // days aged out of the record leave the cache
671  const prefix = cacheKey(account, '')
672  for (const key of await io.keys()) {
673    if (!key.startsWith(prefix)) continue
674    const k = parseListKey(key.slice(prefix.length))
675    if (!k || dayStart(k.day) + DAY < now - KEEP) await io.del(key)
676  }
677  for (const key of [...lists.keys()]) {
678    const k = parseListKey(key)
679    if (!k || dayStart(k.day) + DAY < now - KEEP) lists.delete(key)
680  }
681  return got
682}
683
684/** At the session's end: one last upload, so what this session saw since the last sync isn't left behind. */
685export async function endSync(io: SyncIO) {
686  const account = io.account()
687  if (state.disabled || !state.auth || !usable(account) || state.running) return
688  try {
689    await upload(io, account, state.auth.token, await io.now())
690  } catch { /* next session */ }
691}
692
693/** Drops the sign-in and everything downloaded with it: the record goes back to this computer's own lists. */
694async function forget(io: SyncIO) {
695  state.auth = null
696  state.far.clear()
697  state.failures = 0
698  state.nextAt = 0
699  state.uploadPausedUntil = 0
700  state.uploadNote = undefined
701  stopPolling()
702  state.confirm?.cancel()
703  state.confirm = null
704  state.confirmRm?.cancel()
705  state.confirmRm = null
706  state.confirmRemove = undefined
707  state.devices = undefined
708  state.devicesAt = 0
709  await io.del(AUTH_KEY)
710  for (const key of await io.keys()) {
711    if (key.startsWith(CACHE_PREFIX) || key.startsWith('sync:acct:')) await io.del(key)
712  }
713}
714
715// ---------------------------------------------------------------- signing in and out
716
717/** Starts the device link: the server hands out a code and a page to sign in on, then is asked until it says yes. */
718export async function signIn(io: SyncIO) {
719  if (state.disabled || state.auth || state.poll || (await io.view()).busy) return
720  await setView(io, v => ({ ...v, status: 'signedOut', busy: true }))
721  try {
722    const name = cleanName(await io.hostName().catch(() => undefined))
723    const r = await call(io, 'POST', '/v1/link/start', name ? { deviceName: name } : {})
724    const now = await io.now()
725    if (typeof r.code !== 'string' || typeof r.url !== 'string' || !/^https?:\/\//.test(r.url) || typeof r.pollToken !== 'string') {
726      throw new SyncError('rejected', 200, 'bad_answer')
727    }
728    const ttl = isNum(r.expiresIn) ? Math.min(r.expiresIn * 1000, LINK_TTL) : LINK_TTL
729    const link: Link = {
730      pollToken: r.pollToken, code: r.code, url: r.url,
731      interval: isNum(r.interval) ? Math.min(60, Math.max(1, r.interval)) : 3,
732      expiresAt: now + ttl, server: state.server,
733    }
734    await io.set(LINK_KEY, link)
735    await setView(io, { status: 'waiting', code: link.code, url: link.url })
736    startPolling(io, link)
737  } catch (err) {
738    const e = err instanceof SyncError ? err : null
739    await setView(io, {
740      status: 'signedOut',
741      note: e?.status === 429 ? 'Too many sign-in attempts; try again in a few minutes.'
742        : e?.status === 0 || !e ? "Couldn't reach the sync server."
743        : `The sync server answered ${e.status}${e.detail ? `: ${e.detail}` : ''}.`,
744    })
745  }
746}
747
748function startPolling(io: SyncIO, link: Link) {
749  stopPolling()
750  const home = state.home ?? io
751  state.poll = home.every(link.interval * 1000, () => void pollOnce(home, link))
752}
753function stopPolling() {
754  state.poll?.cancel()
755  state.poll = null
756}
757
758async function pollOnce(io: SyncIO, link: Link) {
759  if (state.polling || state.poll === null) return
760  state.polling = true
761  try {
762    // another session may have finished it
763    await refresh(io)
764    if (state.auth || !state.poll) return
765    const now = await io.now()
766    if (now >= link.expiresAt) return await expired(io)
767    let r: Json
768    try {
769      r = await call(io, 'POST', '/v1/link/poll', { pollToken: link.pollToken })
770    } catch (err) {
771      // the network or a busy server: asked again next time; anything else ends it
772      if (err instanceof SyncError && err.kind === 'retry') return
773      return await expired(io)
774    }
775    if (r.status === 'ok' && typeof r.deviceToken === 'string' && r.deviceToken) {
776      const auth: Auth = { token: r.deviceToken, email: typeof r.email === 'string' ? r.email : '', server: state.server }
777      stopPolling()
778      await io.set(AUTH_KEY, auth)
779      await io.del(LINK_KEY)
780      state.auth = auth
781      state.far.clear()
782      state.failures = 0
783      state.nextAt = 0
784      state.devices = undefined
785      // a fresh sign-in checks this device's name again
786      state.nameChecked = false
787      await setView(io, await signedInView(io))
788      await syncNow(io)
789      await io.reload()
790    } else if (r.status === 'expired') {
791      await expired(io)
792    }
793  } finally {
794    state.polling = false
795  }
796}
797
798async function expired(io: SyncIO) {
799  stopPolling()
800  await io.del(LINK_KEY)
801  // the one-time answer may have gone to another session on this computer
802  await refresh(io)
803  if (!state.auth) await setView(io, { status: 'signedOut', note: 'The sign-in code expired. Press Sign in to try again.' })
804}
805
806export async function cancelSignIn(io: SyncIO) {
807  stopPolling()
808  await io.del(LINK_KEY)
809  await setView(io, { status: 'signedOut' })
810}
811
812/** Unlinks this device on the server, then forgets the sign-in and the downloaded lists here. */
813export async function signOut(io: SyncIO) {
814  const auth = state.auth
815  if (!auth) return
816  await setView(io, v => ({ ...v, busy: true }))
817  let note: string | undefined
818  try {
819    await call(io, 'DELETE', '/v1/device', undefined, auth.token)
820  } catch (err) {
821    if (!(err instanceof SyncError && err.kind === 'auth')) note = "Signed out here; the server couldn't be reached, so it lists this device until it goes unused for 90 days."
822  }
823  await forget(io)
824  await setView(io, note ? { status: 'signedOut', note } : { status: 'signedOut' })
825  await io.reload()
826}
827
828/** The first press asks for a second; the second deletes the account and every synced list on the server. */
829export async function deleteSynced(io: SyncIO) {
830  const auth = state.auth
831  if (!auth) return
832  const v = await io.view()
833  if (v.busy) return
834  if (!v.confirmDelete) {
835    await setView(io, { ...v, confirmDelete: true })
836    state.confirm?.cancel()
837    const home = state.home ?? io
838    state.confirm = home.after(CONFIRM_FOR, () => void setView(home, x => {
839      const { confirmDelete: _, ...rest } = x
840      return rest
841    }))
842    return
843  }
844  state.confirm?.cancel()
845  state.confirm = null
846  await setView(io, { ...v, confirmDelete: false, busy: true })
847  try {
848    await call(io, 'DELETE', '/v1/me', undefined, auth.token)
849  } catch (err) {
850    if (!(err instanceof SyncError && err.kind === 'auth')) {
851      await setView(io, await signedInView(io, `Couldn't delete the synced data: ${err instanceof SyncError && err.status ? `the server answered ${err.status}` : "the server couldn't be reached"}.`))
852      return
853    }
854  }
855  await forget(io)
856  await setView(io, { status: 'signedOut', note: 'Deleted all synced data and signed out.' })
857  await io.reload()
858}
859
860// ---------------------------------------------------------------- the devices signed in
861
862/**
863 * Asks the server for the signed-in user's devices (GET /v1/me) and shows them.
864 * After each sync, and when the pane opens (`fresherThan`: not if asked that
865 * recently). The first time in a session, and after a sign-in, it also puts
866 * this computer's name right on the server when it has none or another one.
867 */
868export async function refreshDevices(io: SyncIO, fresherThan = 0) {
869  const auth = state.auth
870  if (state.disabled || !auth) return
871  const now = await io.now()
872  if (fresherThan && now - state.devicesAt < fresherThan) return
873  state.devicesAt = now
874  let r: Json
875  try {
876    r = await call(io, 'GET', '/v1/me', undefined, auth.token)
877  } catch (err) {
878    // a token gone is the next sync's to notice; anything else keeps the last list
879    return
880  }
881  if (state.auth !== auth) return
882  const devices = parseDevices(r.devices)
883  state.devices = devices
884  if (!state.nameChecked) {
885    state.nameChecked = true
886    const me = devices.find(d => d.current)
887    const want = cleanName(await io.hostName().catch(() => undefined))
888    // a generic name ("Mac") only fills a missing one: it never replaces a real name another session found
889    if (me && want && me.name !== want && (me.name === null || !isGeneric(want))) {
890      try {
891        const x = await call(io, 'PUT', '/v1/device', { name: want }, auth.token)
892        me.name = typeof x.name === 'string' ? x.name : want
893      } catch { /* tried again next session */ }
894    }
895  }
896  if (state.auth !== auth) return
897  await setView(io, v => (v.status === 'signedIn' ? { ...v, devices: state.devices ?? [] } : v))
898}
899
900/** Every downloaded list dropped and downloaded again: what a removed device uploaded leaves this record too. */
901async function downloadAgain(io: SyncIO) {
902  state.far.clear()
903  for (const key of await io.keys()) {
904    if (key.startsWith(CACHE_PREFIX)) await io.del(key)
905    else if (key.startsWith('sync:acct:')) {
906      const v = (await io.get(key)) as Partial<AcctState> | undefined
907      if (v && typeof v === 'object') {
908        const { cursor: _, ...rest } = v
909        await io.set(key, rest)
910      }
911    }
912  }
913}
914
915/**
916 * Removes another device of this account: the first press asks for a second,
917 * the second removes it on the server (its token stops working, its lists are
918 * deleted) and downloads the rest again, so its lists leave this record too.
919 */
920export async function removeDevice(io: SyncIO, id: string) {
921  const auth = state.auth
922  if (!auth) return
923  const v = await io.view()
924  if (v.busy) return
925  const device = state.devices?.find(d => d.id === id && !d.current)
926  if (!device) return
927  if (state.confirmRemove !== id) {
928    state.confirmRemove = id
929    await setView(io, { ...v, confirmRemove: id })
930    state.confirmRm?.cancel()
931    const home = state.home ?? io
932    state.confirmRm = home.after(CONFIRM_FOR, () => {
933      if (state.confirmRemove !== id) return
934      state.confirmRemove = undefined
935      void setView(home, x => {
936        const { confirmRemove: _, ...rest } = x
937        return rest
938      })
939    })
940    return
941  }
942  state.confirmRm?.cancel()
943  state.confirmRm = null
944  state.confirmRemove = undefined
945  const { confirmRemove: _, ...rest } = v
946  await setView(io, { ...rest, busy: true })
947  let note: string | undefined
948  try {
949    await call(io, 'DELETE', `/v1/devices/${encodeURIComponent(id)}`, undefined, auth.token)
950  } catch (err) {
951    const e = err instanceof SyncError ? err : null
952    if (e?.kind === 'auth') return void (await failed(io, e))
953    // 404: gone already, which is what was asked
954    if (e?.status !== 404) note = `Couldn't remove ${deviceLabel(device)}: ${e?.status ? `the server answered ${e.status}` : "the server couldn't be reached"}.`
955  }
956  if (state.auth !== auth) return
957  if (!note) {
958    state.devices = state.devices?.filter(d => d.id !== id)
959    await downloadAgain(io)
960  }
961  await setView(io, await signedInView(io, note))
962  if (note) return void (await refreshDevices(io))
963  // the sync asks for the device list again once it's through
964  await syncNow(io)
965  await io.reload()
966}
967
types/index.d.ts 73 lines
1/** One rate-limit reading: when, which window (0 = 5-hour, 1 = weekly), % used, reset time (ms). */
2export type RangeReading = [t: number, kind: 0 | 1, pct: number, resetsAt: number]
3
4/** A stretch of time a session on this computer was open and taking readings: [from, to] in ms. */
5export type RangeWatch = [from: number, to: number]
6
7/** One day's use, a day being 24 hours from the weekly reset's time of day: when it began (ms), and how far the weekly figure rose in it, in % of the weekly limit. */
8export type RangeDay = [dayStart: number, pct: number]
9
10/** One weekly window's self-check: when it resets (ms), what the projection said was left at each day boundary in it, and what was actually left once it reset. */
11export type RangeCheck = { resetsAt: number; at: Array<[t: number, left: number]>; actual?: number }
12
13/**
14 * One model response seen here, subagents' included: when, the model's id, the effort it was asked for
15 * ('' for none), its tokens weighted by that model's price ratios, and 1 when a subagent made it. Responses recorded
16 * by 1.4.0 also carry the project they were made in (that release's projects card, since removed): it is never synced.
17 */
18export type RangeStep = [t: number, model: string, effort: string, units: number, sub: 0 | 1, project?: string]
19
20/**
21 * What the weekly average covers (a window of n units, or since the reset), whether reset countdowns show
22 * the finer unit, the model the others' costs compare to (a model id; absent, the default), and whether the
23 * weekly card's daily budget outlines are hidden.
24 */
25export type RangeSettings = { mode: 'window' | 'reset'; n: number; unit: 'h' | 'd' | 'w'; fine: boolean; baseline?: string }
26
27/** The colours the card draws with, as hex. */
28export type Palette = {
29  card: string; veil: string; fg: string; dim: string; off: string
30  barTop: string; barBottom: string; limit: string; over: string; under: string; bad: string
31  /** A figure "… to spare": the only place green is used. */
32  good: string
33  /** A colour per model family. */
34  fable: string; opus: string; sonnet: string; haiku: string
35  /** The card's surfaces, as the pane's design names them: the card, a raised chip, the inset strip, the panel within. */
36  surface: string; raised: string; inset: string; panel: string; line: string
37  /** Its inks: muted and faint text, the accent and its tint, what's short and its tint, the neutral solid grey. */
38  muted: string; faint: string; accent: string; accentBg: string; badBg: string; solid: string
39}
40
41/** The card's palettes for a dark and a light appearance, derived from the theme, and which one the theme itself is. */
42export type Palettes = { dark: Palette; light: Palette; own: 'dark' | 'light' }
43
44/**
45 * What the pane's "Sync across devices" row shows: off (the person turned nonessential traffic off), signed out,
46 * waiting for a sign-in in the browser (its code and page), or signed in (as whom, when it last synced);
47 * a quiet note for what went wrong, whether a delete is waiting for its confirming press, and the devices signed in
48 * (with the one a "Remove" waits on).
49 */
50export type RangeSync = {
51  status: 'off' | 'signedOut' | 'waiting' | 'signedIn'
52  email?: string
53  last?: number
54  code?: string
55  url?: string
56  note?: string
57  confirmDelete?: boolean
58  busy?: boolean
59  /** The signed-in account's devices, as the server last listed them (this device first). */
60  devices?: RangeDevice[]
61  /** The device a "Remove" is waiting on its confirming press for. */
62  confirmRemove?: string
63}
64
65/** A device signed in to sync, as the pane lists it: the server's id, its name (null: none given), when it was last seen, whether it is this one. */
66export type RangeDevice = { id: string; name: string | null; lastSeenAt?: number; current: boolean }
67
68declare module 'claude-code' {
69  interface PluginState {
70    'token-range-monitor': { readings: RangeReading[]; seen: RangeWatch[]; steps: RangeStep[]; days: RangeDay[]; check: RangeCheck[]; settings: RangeSettings; tick: number; palettes: Palettes; sync: RangeSync; details: string[] }
71  }
72}
73