Plan usage, the context window and the prompt cache countdown as a banner above the Claude Code prompt, with burn rates, alerts and an opt-in keep-warm. TW…

Plan usage, context window and prompt cache countdown, right above the Claude Code prompt.
Token Watch is a Claude Code mod that draws a small banner above the prompt. It shows:
Right-click the banner to cycle three views. TW Settings chooses what the banner shows, sets alerts, keep-warm and burn rates, and can override them per session. TW Monitor lists every Claude Code session on your machine with its context and cache. Where the banner can't be drawn, /token-watch answers as text, and Token Watch for VS Code puts the same reading in the status bar.
Quick start (Claude Code 2.1.308 or later):
claude plugin marketplace add nevermemo/token-watch
claude plugin install token-watch@token-watch
Then start a new session, or type /reload-plugins in an open one. More ways to install are under Install.
In these sketches [ … ] marks a button; the real banner draws it as a filled chip whose colour is its state. Each bar is filled in proportion and coloured: a fill on a grey track for usage, one colour per category for the context.
Expanded:
╭───────────────────────────────────────────────────────────────────────────────╮
│ 5H ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ 62% 2h 14m 28%/h 1h 20m │ [≡]
│ WK ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ 31% 3d 4h 0.4%/h Safe │ [#]
│ CTX ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ 21% 212k / 1M │
│ ▄ messages 186k ▄ tools 12k ▄ memory 4.9k ▄ skills 3k │
│ TTL 52:50 / 60:00 [ Remind Me ] │
╰───────────────────────────────────────────────────────────────────────────────╯
Beside the expanded banner, [≡] (☰ on the desktop) opens TW Settings and [#] (⊞ on the desktop) opens TW Monitor. After a usage window's reset countdown come its burn rate and when it would fill at that rate: a red time, Safe in green when it resets first, or Full.
Collapsed (one line with bars):
5H ▄▄▄▄▄▄▄▄▄▄ 62% WK ▄▄▄▄▄▄▄▄▄▄ 31% CTX ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ 21% 212k / 1M [ 47:12 ]
Minimal (one line without bars):
5H 62% WK 31% CTX 21% 212k / 1M [ 47:12 ]
Requirements: Claude Code 2.1.308 or later (claude --version); tested on 2.1.310. Token Watch draws in the terminal and in the Code tab of the Claude desktop app. Token Watch for VS Code needs Token Watch 1.1.0 or later.
This repository is its own plugin marketplace: the quick start above adds it as a marketplace and installs Token Watch from it. Inside a session, /plugin marketplace add nevermemo/token-watch does the same as the first command.
claude plugin marketplace update token-watch
claude plugin update token-watch@token-watch
Upgrading from 1.3.0: /context-bar is now /token-watch, and keep-warm now reminds you by default instead of pinging. See the changelog.
Clone it, then, from the same folder, load it for one session:
git clone https://github.com/nevermemo/token-watch
claude --plugin-dir ./token-watch
To list Token Watch in a marketplace you already run, add an entry to its plugins array that points at this repository:
{
"name": "token-watch",
"source": { "source": "github", "repo": "nevermemo/token-watch" },
"description": "Plan usage, the context window and a prompt cache countdown above the Claude Code prompt."
}
To pin a release, add "ref": "v1.4.0" to the source object. Administrators can also require the marketplace or the plugin on every machine through managed settings. See Manage mods for your organization.
claude plugin uninstall token-watch@token-watch
| Row | Meaning | On the right |
|---|---|---|
5H | Your rolling 5-hour usage window | Time until it resets (2h 14m), then its burn rate and when it fills |
WK | Your weekly usage window | The same, e.g. 3d 4h 0.4%/h Safe |
FB, OP, SN, HK | A model's own allowance, if Claude Code reports one (Fable, Opus, Sonnet, Haiku) | The same |
$$ | Your organisation's spend limit, when Claude Code runs through a Claude gateway | The same |
CTX | The context window, broken down the way /context breaks it down | Tokens in use, e.g. 212k / 1M |
TTL | The prompt cache's time to live: how long until the API forgets this conversation's cached prefix, counted from the end of Claude's last response | The time left over the whole TTL, e.g. 52:50 / 60:00, then the keep-warm button. While pings are on: their caps (Pings: 0/8 Time: 00:26 / 8:00:00) and a Refresh Caps button, and for a minute after a ping, a reminder or a stop, a dim note. The caps and the note need a banner 90 columns or wider |
slack 8.2k · github 6.1k), the memory files by name (CLAUDE.md 3.4k), and the skills and agents (12 of 40, 10k · agents 3, 67). They're off by default; turn them on in TW Settings under Context → Details.Safe in green when it resets first, and Full in red once full. By default both show in the expanded view only.47:12) to turn keep-warm on, and again to turn it off. By default it reminds you before the cache expires; it can ping instead. See The prompt cache and keep-warm.Refresh Caps (expanded view, 90 columns or wider, pings on) to start keep-warm's caps over.| Colour | Keep-warm button | Collapsed timer | Meaning |
|---|---|---|---|
| Grey | Remind Me (Notify) or Keep Warm (Pings, Both) | 47:12 | The cache is warm; keep-warm is off |
| Green | Reminding or Let Chill | 47:12 | Keep-warm is on |
| Red | Cache Lost | --:-- | The countdown ran out; the cache is cold |
| Red | No Data | --:-- | No response yet, so nothing is cached |
Clicking Cache Lost or No Data does not start keep-warm. In the expanded view, 90 columns or wider, a short note says why. In a terminal the keep-warm button keeps one width whatever it says, so the caps after it stay put. Refresh Caps is always grey.
[≡] (☰ on the desktop) opens TW Settings; [#] (⊞) opens TW Monitor. Both sit beside the expanded banner. [≡] also stays beside a collapsed line that shows nothing, as the way back, and, marked [≡●], beside any view that hides the TTL while keep-warm runs, so keep-warm is never out of sight./token-watch hides or shows the banner. Hiding it turns keep-warm off in Pings and Both, so nothing spends out of sight; in Notify, keep-warm stays on. Where the banner can't be drawn (the VS Code extension's chat panel, claude -p), /token-watch answers with the reading as one line instead: 5H 62% (2h 14m) · WK 31% (3d 4h) · CTX 21% (212k / 1M) · TTL 47:12 (1h · subscription). The TTL part reads TTL lost once the countdown runs out./token-watch text answers with that line anywhere. /token-watch file says where the usage snapshot is and when it was last written. /token-watch settings and /token-watch monitor open the two panels.212k / 1M detail, in that order. The percentages and the timer stay. The expanded table drops its burn-rate columns below 70 columns and its reset and token column below 50.TW Settings docks beside the transcript in the terminal's fullscreen layout and beside the chat on the desktop; on the terminal's main screen it opens inline. Open it with [≡] or /token-watch settings. Every change applies at once and is saved.
At the top, choose which settings it shows:
[Reset], and [Reset to global] at the bottom clears them all.overridden in Session. [Reset to defaults] at the bottom puts them back.Each section and row opens and closes with [▸] / [▾]. On the desktop, checkboxes are ☑ / ☐ and choices ◉ / ○; in a terminal both are ● / ○.
● Session ○ Global ○ Monitor
[▾] Usage
[▾] 5H
[▸] Show on banner
[▸] Burn rate
[▸] Burn forecast
[▸] WK
[▸] OTH
[▸] Context
[▸] Cache time
[Reset to global]
[Enable] sets 99%, and [-] / [+] step from 50% to 95% in fives, then 99%, then off. Off by default. A usage alert is every session's (set in Global), and only one session sends it each window period.%/h or %/min for 5H, %/h or %/day for the others).| TTL | Default | Pings | Hours |
|---|---|---|---|
| One hour | 8 pings or 8 hours | 1 to 24 | 1 to 24 |
| Five minutes | 30 pings or 2 hours | 5 to 100, in steps of 5 | 1 to 6 |
A running keep-warm already past a new cap stops at once, saying why. Caps apply to pings, not reminders.
/config.A session's own settings are kept for 30 days after it was last seen, and saved again once a day while it stays open.
TW Monitor lists every Claude Code session running on your machine, from the small files each session writes (see Session files). Open it with [#] (⊞ on the desktop) or /token-watch monitor. It reads the other sessions every 30 seconds while it is open; [↻] (↻ on the desktop) at its top right reads them now.
[▾] Usage [↻]
5H ▄▄▄▄▄▄▄▄▄▄ 62% 2h 14m 28%/h
WK ▄▄▄▄▄▄▄▄▄▄ 31% 3d 4h 0.4%/h
──────────────────────────────────────────────────
[▾] Sessions
[ ] [▾] › token-watch [×]
CTX ▄▄▄▄▄▄▄▄▄▄ 48% 477k / 1M
TTL ▄▄▄▄▄▄▄▄▄▄ 49m (Ping)
[*] [▸] GUST working TTL 1h 00m [×]
[ ] [▸] scratch TTL Cold [×]
[▸] Hidden 0
›, then the others by name. Each opens to its context and its cache's countdown; closed, it keeps a one-line summary. The countdown is green while keep-warm is on, grey while it is off, and red with Cold or No data; keep-warm's mode follows it, (Ping), (Notify) or (Ping + Notify). working marks a session running a turn.[ ] / [*] before a session (⚐ / ⚑ on the desktop) pins it above the others.[×] (× on the desktop) at a session's right moves it to Hidden, closed at first; [↺] (↺) there brings it back. Hiding this session hides it from the other sessions' monitors; while Current session is On top, it stays in its own.In TW Settings' Monitor view:
[Reset to default], [Unpin all sessions] and [Unhide all sessions] sit at the bottom.Claude Code keeps a session's title in its transcript, ~/.claude/projects/<project>/<session id>.jsonl. Token Watch reads it only while Name is Title or Folder / title:
It never reads a transcript on a timer otherwise. Only the title is kept, in Token Watch's storage, and the titles are deleted when you choose Folder again. A transcript over 4 MiB, more than the mod API reads at once, is searched with git grep, run without a shell, which prints only the title lines; without git, that session goes by its folder. The transcript format is Claude Code's own, not a documented interface, so a future Claude Code could stop titles from being found; the session then shows its folder.
Claude Code sends your whole conversation with every request. The API caches that prefix and bills a re-read at the cached rate, for one TTL after the last request:
FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting, ENABLE_PROMPT_CACHING_1H.TTL row shows the TTL as its timer's denominator, 52:50 / 60:00. /token-watch text and the snapshot's cache.ttlSource say why: 1h · subscription, 5m · FORCE_PROMPT_CACHING_5M, or 1h · confirmed once a keep-warm ping has proved the hour.The countdown is an estimate: see Good to know.
Keep-warm is off by default and never saved. Turn it on with the keep-warm button (on the collapsed lines, the timer) while the cache is warm. What it does depends on its mode, set in TW Settings under Cache time → Keep-warm:
$.model.fork: the same prefix plus "Reply with the single word: ok") 8 minutes before the hour would run out, or 75 seconds before five minutes would, and again before each renewed window. Only one is ever out at a time. The API serves it from the cache and renews the entries it read for another TTL.While pings are on, the row shows their caps, Pings: 0/8 Time: 00:26 / 8:00:00, and a Refresh Caps button. Refresh Caps starts the caps over: pings back to 0, time back to 00:00, a ping's failures forgotten and the note cleared, with keep-warm still on. It does not send a ping or move the schedule, so the next ping goes out when it was going to.
Measured first (headless sessions, October 2026, Opus 5.5): with the TTL forced to five minutes, a message eight minutes after the last response read nothing from the cache; with one ping at four minutes it read 47k tokens. On the hour, a message at 65 minutes read nothing; with one ping at 55 minutes it read the 33k tokens the ping had read. A ping reads about 70% of the prompt (its request differs from yours in its tail), and your next message writes the rest again, as it would after any turn.
Notify costs nothing. Every ping is a real request, counted against your plan usage like any other. Per ping, with r_in your model's input price and r_out its output price:
cache_read × r_in × 0.1 (0.05 on Opus 5.5, 0.025 on Fable 5.1), about 70% of your prompt;cache_creation × r_in × 1.25 (the fork's own tail, about 14k tokens in the measurements, written at the five-minute rate);r_out.The multipliers are the API's published ones (prompt caching pricing). The row shows each ping's actual counts for a minute (ping read 33k · wrote 14k, 90 columns or wider), and /token-watch text keeps the last ping's.
When it stops:
/token-watch hides the banner (Pings and Both), or no view shows the TTL row;/clear, a resume, a logout or exit.On the one-hour TTL, Claude Code can compact a conversation of 200k tokens or more (the default threshold) about 54 minutes into an idle hour (idleCompaction, on by default). Compaction replaces your conversation and stops keep-warm, so on large conversations the two work against each other. To keep warm instead of compacting, set "idleCompaction": false (or the Idle compaction row in /config). The setting needs Claude Code 2.1.290 or later, the /config row 2.1.302.
| Where you run Claude Code | Token Watch |
|---|---|
claude in a terminal (including editor terminals and JetBrains) | Shown |
| The Code tab of the Claude desktop app | Shown |
| The VS Code extension's chat panel | Loads, but there is no banner above the prompt to draw in, so /token-watch answers with the reading as text. Token Watch for VS Code shows it in the status bar. |
claude -p, the Agent SDK | Loads and answers /token-watch as text; writes no snapshot or session file, since nobody is at the prompt |
| Cloud sessions | Not drawn: cloud sessions don't load plugins installed on your machine, and don't show mod drawings |
The VS Code extension's chat panel has no banner above the prompt, so Token Watch has a companion: Token Watch for VS Code puts 5H ████▉░ 82% · 41m WK ██▏░░░ 35% CTX █▌░░░░ 26% in the status bar, with the reset countdowns and the context breakdown in a tooltip and a panel that draws the same bars. It reads the usage snapshot below and nothing else.
To install it, download token-watch-0.1.0.vsix from the releases page, then run code --install-extension token-watch-0.1.0.vsix, or use Extensions → ⋯ → Install from VSIX…. It is not yet published to the VS Code Marketplace or Open VSX. Keep Token Watch 1.1.0 or later installed, and open any Claude Code session: the terminal, the desktop app or the chat panel.
After each reading, Token Watch writes one small JSON file, ~/.claude/token-watch/usage.json (~ is USERPROFILE on Windows and HOME elsewhere), and writes it again every 30 seconds while the session is alive. With several sessions open, the most recently active one keeps the file; another takes over once that snapshot is more than 120 seconds old. Token Watch for VS Code treats a snapshot older than 150 seconds as a session that has ended.
Off: turn off Usage snapshot files in /config, or in /plugin → token-watch → Configure options. That also turns off the session files, and TW Monitor then lists this session
hooks/register.tsx 2901 lines1// Token Watch: plan usage (the 5-hour and weekly windows, and any other
2// window Claude Code reports), the context window and the prompt cache's
3// countdown as thin bars above the prompt. A right click cycles the band's
4// three views, the cache timer and the keep-warm button turn keep-warm on and
5// off, and /token-watch shows or hides it.
6//
7// session.start: register /token-watch, restore the saved view (or the one
8// the 1.1 keys meant), the settings (the global ones and this session's
9// own, its id's settings kept 30 days) and the last usage windows seen (a new session has none until its first
10// response), read the TTL controls once (three environment variables and
11// the promptCacheTtl setting), take a reading, and tick a clock every 30s
12// so the countdowns stay current and the usage snapshot says the session
13// is alive.
14// session.measure: after each main-thread turn, or when a usage window moves,
15// take a reading.
16// turn.start / turn.complete (main loop): no ping while a turn runs; when a
17// response ends the countdown restarts, since its request refreshed the
18// cache. Neither hook reads the text.
19// prompt.submit: a prompt from the person turns keep-warm off (in Notify
20// mode it stays on: a reminder costs nothing); a background delivery does
21// not. Only the origin is read, and the prompt passes on.
22// session.compact (main loop, not a precompute): keep-warm off, the countdown
23// restarts.
24// session.end: keep-warm off; where the process goes on under another session
25// (/clear, a resume, a logout), the cache is forgotten too.
26// command.run (token-watch): show or hide the band where it draws; where it
27// cannot be drawn (the VS Code extension's chat panel, a headless run),
28// answer with the reading as one line of text. `text` asks for that line
29// anywhere, `file` for the snapshot's path, `settings` opens the settings
30// panel, `monitor` TW Monitor.
31// ui.render (AbovePrompt): the band, drawn by the Client in ./band.tsx, which
32// lays itself out to the room it is given and reports clicks; beside it, the
33// settings button ([≡] in a terminal, ☰ on the desktop), a Button of this
34// module's own, so its press is the person's, and under it in the expanded
35// view the sessions button ([#] in a terminal, ⊞ on the desktop).
36// ui.message: the band was clicked: { action: 'cycle' } (right click) moves
37// to the next view, { action: 'keep-warm' } (the timer or the keep-warm
38// button) toggles keep-warm, { action: 'refresh-caps' } starts its caps over.
39// ui.render (Pane, the settings panel): in collapsible sections, what each
40// part shows in each view, each usage window's pace (in which views, over
41// which window, in which unit) and keep-warm's caps for this session's TTL,
42// for this session or for every session: a session's own setting overrides
43// the global one, leaf by leaf (./settings.ts). While no view shows the
44// cache keep-warm stays off, so nothing spends out of sight. Every 30 s the
45// global settings are read again, so a change another session made reaches
46// this one.
47// ui.render (Pane, TW Monitor): every live session on this device,
48// from the sessions' files: its folder, its context and its cache's
49// countdown.
50//
51// Burn rates: each reading's usage windows are kept in the store where they
52// moved (./burn.ts), shared by every session since the windows are the
53// account's; the band shows each window's pace and when it fills.
54//
55// A reading is $.session.usage({ breakdown: 'summary' }): the /context rows,
56// estimated locally, so it costs no token-count request, and the plan's
57// rate-limit windows as the status line has them (none off a subscription).
58// Each reading is also written to ~/.claude/token-watch/usage.json, the
59// snapshot a companion (Token Watch for VS Code) reads, and to this session's
60// own file in ~/.claude/token-watch/sessions/, which TW Monitor of
61// every session on the device reads; the plugin's `snapshot` option turns
62// both off.
63//
64// Keep-warm's mode (the settings): Pings, as below; Notify, no pings, one
65// notification ($.ui.notify) a lead time before each countdown runs out,
66// staying on across prompts; Both, pings, and one notification a lead time
67// before the first ping of each idle spell. Alerts: a notification when a
68// usage window (once per window period, shared through the store so one
69// session says it) or this session's context crosses the level set for it.
70//
71// Keep-warm: a ping is $.model.fork with a one-word prompt, which repeats the
72// main thread's last request so the API serves it from the cache and
73// refreshes the entry. Pings go out a lead time before the believed expiry,
74// never during a turn, never two at once and never while the TTL row is
75// hidden, and stop at the caps, when the person types, after two failures in
76// a row, when a ping finds the cache cold, at compaction and when the session
77// ends. The rules are in ./cache.ts.
78
79import { atom, read, update } from 'claude-code'
80import type { EngineInterface, ModelForkResult, Register, Timer } from 'claude-code'
81
82import type {
83 BandProps,
84 Cap,
85 ContextDetails,
86 MonitorCurrent,
87 MonitorFilter,
88 MonitorName,
89 MonitorCtxPiece,
90 MonitorTtlPiece,
91 MonitorUsagePiece,
92 MonitorSort,
93 KeepWarm,
94 Limit,
95 Pace,
96 Reading,
97 Scope,
98 SessionSnapshot,
99 SettingsOverride,
100 SettingsTree,
101 Slice,
102 Snapshot,
103 TtlInputs,
104 UsagePart,
105 View,
106 WarmMode,
107} from '../types'
108import {
109 BACKGROUND_ORIGINS,
110 CAP_LIMITS,
111 COLD_READ_SHARE,
112 DEFAULT_CAPS,
113 KEEP_WARM_OFF,
114 MAX_FAILURES,
115 MIN_WARM_READ,
116 NO_CACHE,
117 NO_INPUTS,
118 PING_LOST_MS,
119 PING_PROMPT,
120 RETRY_MS,
121 SESSION_SETTINGS_KEEP_MS,
122 TTL_MS,
123 caps,
124 isTtl,
125 leadMs,
126 nextView,
127 refreshMs,
128 resolveTtl,
129} from './cache'
130import {
131 DEFAULT_SETTINGS,
132 MONITOR_CURRENT,
133 MONITOR_FILTERS,
134 MONITOR_NAMES,
135 MONITOR_CTX_PIECES,
136 MONITOR_TTL_PIECES,
137 MONITOR_USAGE_PIECES,
138 MONITOR_SORTS,
139 MONITOR_STATES,
140 NOTIFY_LEADS,
141 PACE_UNITS,
142 PACE_WINDOWS,
143 RECENT_STEPS,
144 USAGE_PARTS,
145 VIEWS,
146 VIEW_NAMES,
147 WARM_MODES,
148 dropAt,
149 forecastHiddenIn,
150 fromLegacy,
151 getAt,
152 hiddenIn,
153 isCacheHidden,
154 isGlobalOnly,
155 isEmptyOverride,
156 merge,
157 overridesUnder,
158 paceHiddenIn,
159 readOverride,
160 readSettings,
161 recentText,
162 setAt,
163 stepAlert,
164 stepIn,
165 windowText,
166} from './settings'
167import type { Path } from './settings'
168import { DROP_RESET, addReadings, fullAt, isEarlier, isSameReset, ratePerHour, rateText, readHistory } from './burn'
169import { countdown, duration, hmmss, label, levelColor, partOf, readingLine, short, sorted } from './format'
170
171const reading = atom({ plugin: 'token-watch', key: 'reading' } as const, null)
172const isShown = atom({ plugin: 'token-watch', key: 'isShown' } as const, true)
173const view = atom({ plugin: 'token-watch', key: 'view' } as const, 'expanded')
174const limits = atom({ plugin: 'token-watch', key: 'limits' } as const, [])
175const limitsAt = atom({ plugin: 'token-watch', key: 'limitsAt' } as const, 0)
176const nowMs = atom({ plugin: 'token-watch', key: 'nowMs' } as const, 0)
177const working = atom({ plugin: 'token-watch', key: 'working' } as const, false)
178const ttlInputs = atom({ plugin: 'token-watch', key: 'ttlInputs' } as const, NO_INPUTS)
179const cache = atom({ plugin: 'token-watch', key: 'cache' } as const, NO_CACHE)
180const keepWarm = atom({ plugin: 'token-watch', key: 'keepWarm' } as const, KEEP_WARM_OFF)
181const pingingSince = atom({ plugin: 'token-watch', key: 'pingingSince' } as const, null)
182const settings = atom({ plugin: 'token-watch', key: 'settings' } as const, DEFAULT_SETTINGS)
183const globalSettings = atom({ plugin: 'token-watch', key: 'globalSettings' } as const, DEFAULT_SETTINGS)
184const override = atom({ plugin: 'token-watch', key: 'override' } as const, {})
185const scope = atom({ plugin: 'token-watch', key: 'scope' } as const, 'session')
186const openSections = atom({ plugin: 'token-watch', key: 'openSections' } as const, [])
187const ctxAlerted = atom({ plugin: 'token-watch', key: 'ctxAlerted' } as const, [])
188const history = atom({ plugin: 'token-watch', key: 'history' } as const, {})
189const sessions = atom({ plugin: 'token-watch', key: 'sessions' } as const, [])
190const sessionsClosed = atom({ plugin: 'token-watch', key: 'sessionsClosed' } as const, [])
191const pinned = atom({ plugin: 'token-watch', key: 'pinned' } as const, {})
192const titles = atom({ plugin: 'token-watch', key: 'titles' } as const, {})
193const clearPresses = atom({ plugin: 'token-watch', key: 'clearPresses' } as const, { count: 0, since: 0 })
194const hiddenSessions = atom({ plugin: 'token-watch', key: 'hiddenSessions' } as const, {})
195
196// The context's details lines, as the panel names them.
197const DETAILS: ['mcp' | 'memory' | 'skills', string][] = [
198 ['mcp', 'MCP servers'],
199 ['memory', 'Memory files'],
200 ['skills', 'Skills & agents'],
201]
202
203// TW Monitor's settings as the panel names and explains them.
204const USAGE_NAMES: Record<UsagePart, string> = { '5H': '5H', WK: 'WK', other: 'OTH' }
205const MONITOR_USAGE_NAMES: Record<MonitorUsagePiece, string> = { bar: 'Bar', percent: 'Percentage', reset: 'Reset timer', rate: 'Burn rate' }
206const MONITOR_CTX_NAMES: Record<MonitorCtxPiece, string> = { bar: 'Bar', percent: 'Percentage', tokens: 'Tokens' }
207const MONITOR_TTL_NAMES: Record<MonitorTtlPiece, string> = { bar: 'Bar', timer: 'Timer', warm: 'Keep-warm' }
208const MONITOR_NAME_NAMES: Record<MonitorName, string> = { folder: 'Folder', title: 'Title', both: 'Folder / title' }
209const MONITOR_SORT_NAMES: Record<MonitorSort, string> = { name: 'Name', context: 'Context', expiry: 'Cache expiry', activity: 'Last activity' }
210const MONITOR_FILTER_NAMES: Record<MonitorFilter, string> = { all: 'All', warm: 'Warm cache', recent: 'Recent' }
211const MONITOR_FILTER_NOTES: Record<MonitorFilter, string> = {
212 all: 'Every session running on this device.',
213 warm: 'Sessions whose prompt cache is warm, or working.',
214 recent: 'Sessions that answered within this time, or are running a turn.',
215}
216const MONITOR_CURRENT_NAMES: Record<MonitorCurrent, string> = { default: 'Default', top: 'On top' }
217const MONITOR_CURRENT_NOTES: Record<MonitorCurrent, string> = {
218 default: 'Pins, Hidden and Sort apply to it like any other session; Show never leaves it out.',
219 top: 'Always listed first, and never hidden here.',
220}
221
222// Keep-warm's mode as TW Monitor notes it after a session's countdown, while
223// keep-warm is on.
224const MONITOR_WARM_NOTES: Record<WarmMode, string> = { pings: '(Ping)', notify: '(Notify)', both: '(Ping + Notify)' }
225
226// Keep-warm's modes as the panel names and explains them.
227const WARM_MODE_NAMES: Record<WarmMode, string> = { pings: 'Pings', notify: 'Notify', both: 'Both' }
228const WARM_MODE_NOTES: Record<WarmMode, string> = {
229 pings: 'Pings keep the cache warm while you are away; each ping uses tokens.',
230 notify: 'No pings: a free notification before the cache expires. Stays on when you type.',
231 both: 'Pings, and a notification before the first ping each time you go idle.',
232}
233
234// The settings panel's pane id, and its width when docked beside the transcript.
235const SETTINGS = 'token-watch-settings'
236const SETTINGS_TITLE = 'TW Settings'
237const SETTINGS_COLUMNS = 52
238
239// TW Monitor's pane id and width; its meters' cells and colours (the
240// band's), and its lines' label, value and note columns.
241const SESSIONS = 'token-watch-monitor'
242const SESSIONS_TITLE = 'TW Monitor'
243const SESSIONS_COLUMNS = 52
244const SESSION_METER = 10
245const SESSION_GLYPH = '\u2584'
246const SESSION_TRACK = '#3d4250'
247const SESSION_WARM = '#8fd18f'
248const SESSION_COLD = '#e06c6c'
249// A warm countdown's fill with keep-warm off: grey, lighter than the track.
250const SESSION_IDLE = '#8a8f99'
251const SESSION_LABEL_WIDTH = 3
252// A heading's notes give way this many times faster than its title when the
253// row is short.
254const NOTES_SHRINK = 100
255
256// TW Monitor's mark for this session, before its name: one cell everywhere,
257// where ▶ may draw as an emoji.
258const THIS_SESSION = '›'
259
260// TW Monitor's marks on sessions and their store keys: pinned, and hidden
261// (`hidden` is 1.3.0's parts, still read by the settings' migration).
262const MARKS = { pinned: 'pinned', hidden: 'hiddenSessions' } as const
263type Mark = keyof typeof MARKS
264
265// "Clear all data": how many presses it takes, and within how long of the
266// first.
267const CLEAR_PRESSES = 10
268const CLEAR_WINDOW_MS = 5_000
269const NO_PRESSES = { count: 0, since: 0 }
270
271// TW Monitor's sections that start closed.
272const CLOSED_FIRST = new Set(['hidden'])
273
274// The pin's column before a session's heading, at least: [ ] in a terminal;
275// two cells on the desktop, a minimum the flag's Button widens as it needs
276// (a fixed two clipped it).
277const PIN_WIDTH_TERMINAL = 3
278const PIN_WIDTH_DESKTOP = 2
279
280// A piece of a closed section's summary: text in its colour (dim without
281// one), or a short meter filled to a share.
282type SummaryPart = { text: string; color?: string } | { meter: number; color: string }
283
284// A closed session's meters, shorter than its lines'.
285const SUMMARY_METER = 5
286
287const SESSION_VALUE_WIDTH = 'No data'.length + 1
288const SESSION_NOTE_WIDTH = '23h 59m'.length + 1
289
290// The sessions button's label: a squared plus on the desktop; in a terminal
291// "#", which every monospace font centres in its cell, as it does not \u229e.
292const SESSIONS_MARK = '\u229e'
293const SESSIONS_MARK_TERMINAL = '#'
294
295// The settings button's label, a "menu" glyph: U+2630 on the desktop; in a
296// terminal U+2261, since recent Unicode makes the trigram U+2630 two cells
297// wide while fonts draw it in one, which leaves a gap before the bracket.
298const MENU = '\u2630'
299const MENU_TERMINAL = '\u2261'
300
301// /context's row names, shortened for the legend.
302const LABELS: Record<string, string> = {
303 'system tools': 'tools',
304 'custom agents': 'agents',
305 'free space': 'free',
306 'autocompact buffer': 'buffer',
307}
308
309const COLORS: Record<string, string> = {
310 'system prompt': '#7b9cd8',
311 tools: '#7ecfc4',
312 'mcp tools': '#a78bfa',
313 agents: '#8fd18f',
314 'memory files': '#e8c66a',
315 skills: '#e89bb8',
316 messages: '#d97757',
317}
318
319// The usage snapshot: where it goes under the home directory, how often it
320// is written again while the session is alive, and how long another
321// session's snapshot stays its own before this session takes the file over.
322const SNAPSHOT_PARTS = ['.claude', 'token-watch', 'usage.json']
323// Each session's own file, for TW Monitor: a numbered slot in this
324// folder, which a later session reuses once the one before it has ended or
325// gone stale (no file is ever deleted), so the folder holds as many files as
326// sessions ever ran at once.
327const SESSIONS_PARTS = ['.claude', 'token-watch', 'sessions']
328// Where Claude Code keeps the transcripts, read for sessions' titles; the
329// most $.fs.read takes; and, for a larger transcript, git grep's pattern for
330// a title (a JSON string, escapes and all) and how long it may take.
331const PROJECTS_PARTS = ['.claude', 'projects']
332const FS_READ_MAX = 4 * 1024 * 1024
333const TITLE_PATTERN = '"type":"custom-title","customTitle":"(\\\\.|[^"])*"'
334const GREP_TIMEOUT_MS = 10_000
335// How soon a session whose transcript was not found is looked for again.
336const TITLE_RETRY_MS = 2 * 60_000
337const SLOT_NAME = /^session-(\d+)\.json$/
338const HEARTBEAT_MS = 30_000
339const SNAPSHOT_FRESH_MS = 120_000
340
341// A session's end after which the process goes on under another session.
342const CONTINUES = new Set<string>(['clear', 'resume', 'logout'])
343
344// How often a session's own settings are saved again, so a session open for
345// weeks is never pruned.
346const TOUCH_EVERY_MS = 24 * 60 * 60_000
347
348// The least a ping waits once armed.
349const MIN_PING_WAIT_MS = 1_000
350
351// Snapshot bookkeeping, the armed ping, and the ping this module has out
352// (numbered, so a ping given up on can tell another has taken its place).
353// Module variables: a hot reload loses them, which costs one extra write, and
354// the heartbeat arms the ping again; `pingingSince` in $.state keeps a reload
355// from sending a second ping while the first is out.
356let snapshotOn = true
357let snapshotPath: string | null = null
358let lastWriteMs = 0
359let lastKey = ''
360// The sessions folder, this session's slot in it (found again after a
361// reload by the id in it), the id it last wrote there, and that write.
362let sessionsDir: string | null = null
363let slotPath: string | null = null
364let slotId: string | null = null
365let lastSlotMs = 0
366let lastSlotKey = ''
367// Whether a person is at the prompt (a `claude -p` or SDK run writes no
368// files), whether this session has ended (its file says so, and stays so),
369// when its own settings were last saved again, and when a session's
370// transcript was last looked for and not found.
371let isInteractive = true
372let hasEnded = false
373let lastTouchMs = 0
374const titleMisses = new Map<string, number>()
375let pingTimer: Timer | null = null
376let notifyTimer: Timer | null = null
377let pingOut: { seq: number; sentAt: number } | null = null
378let pingSeq = 0
379
380export const register: Register = (on, options) => {
381 // The plugin's `snapshot` option (/config): on unless set to false.
382 snapshotOn = options.snapshot !== false
383
384 on('session.start', async ($, e, next) => {
385 const result = await next(e)
386 isInteractive = e.isInteractive
387 hasEnded = false
388 // The clock first, so a step below that fails cannot leave the session
389 // without its countdowns, its file and its settings' updates.
390 $.clock.every(HEARTBEAT_MS, () => void tick($).then(() => heartbeat($)).catch(() => {}))
391 await $.command.register({
392 name: 'token-watch',
393 description:
394 'Show or hide the Token Watch banner above the prompt. "text" prints the reading, "file" the snapshot\'s path, "settings" opens TW Settings, "monitor" opens TW Monitor.',
395 argumentHint: '[text|file|settings|monitor]',
396 })
397 const shown = await $.store.get('isShown')
398 await update($, isShown, () => shown !== false)
399 const restored = await restoreView($)
400 await update($, view, () => restored)
401 await tick($)
402 await pruneSessionSettings($)
403 await loadSettings($, true)
404 lastTouchMs = await $.clock.now()
405 await setMarks($, 'pinned', readMarks(await $.store.get(MARKS.pinned)))
406 await setMarks($, 'hidden', readMarks(await $.store.get(MARKS.hidden)))
407 await setTitles($, readTitleStore(await $.store.get('titles')))
408 const keptHistory = readHistory(await $.store.get('history'))
409 await update($, history, () => keptHistory)
410 // A new session has no usage windows until its first response, so start
411 // from the last ones seen; any whose reset time has passed is drawn at 0%,
412 // and the first response replaces them.
413 const saved = readLimits(await $.store.get('limits'))
414 if (saved !== null) {
415 await update($, limits, () => saved)
416 const savedAt = await $.store.get('limitsAt')
417 if (typeof savedAt === 'number') await update($, limitsAt, () => savedAt)
418 }
419 await resolvePaths($)
420 const inputs = await readTtlInputs($)
421 await update($, ttlInputs, () => inputs)
422 await settleTtl($)
423 // A start's reading counts as fresh only while no session has stamped
424 // one (a new store, or 1.3.0's): it never puts older figures over newer.
425 await takeReading($, (await read($, limitsAt)) === 0)
426 // The ping timer is a module variable a hot reload drops, while
427 // keep-warm's state lives in $.state: arm it again. Unless the TTL row is
428 // now hidden (another session, sharing the store, hid it): then off.
429 if ((await read($, keepWarm)).on) {
430 if (isCacheHidden(await read($, settings))) {
431 await stopKeepWarm($, null)
432 await writeSnapshot($)
433 } else {
434 await schedule($)
435 }
436 }
437
438 return result
439 })
440
441 on('session.measure', async ($, e, next) => {
442 const result = await next(e)
443 // A reading after every measurement, banner shown or not (the context's
444 // alert and the snapshot need it). A reading here follows a response, so
445 // its windows are fresh: the store gets them too, where they are newer.
446 await tick($)
447 await takeReading($, true)
448
449 return result
450 })
451
452 on('turn.start', async ($, e, next) => {
453 const result = await next(e)
454 // A subagent's or teammate's turn is not the main thread's, and its
455 // turn.complete is not followed either.
456 if (e.agentId) return result
457 stopPingTimer()
458 // A turn refreshes the cache: no reminder while it runs; its end arms
459 // the next.
460 stopNotifyTimer()
461 await update($, working, () => true)
462 return result
463 })
464
465 on('turn.complete', async ($, e, next) => {
466 const result = await next(e)
467 if (e.agentId) return result
468 await tick($)
469 await update($, working, () => false)
470 // A response came back, so its request was served: the cache was
471 // refreshed at that moment. An interrupted or failed turn without one
472 // leaves the countdown as it was.
473 if (e.usage) await rebase($)
474 await schedule($)
475 await writeSnapshot($)
476 return result
477 })
478
479 on('prompt.submit', async ($, e, next) => {
480 // The person is back: keep-warm has done its job. A delivery from a
481 // notification, a schedule, a peer or a plugin is not the person.
482 // A reminder costs nothing and stays on: it is for the next idle spell.
483 const isReminder = (await read($, settings)).warm.mode === 'notify'
484 if (!BACKGROUND_ORIGINS.has(e.origin.kind) && !isReminder && (await read($, keepWarm)).on) {
485 await stopKeepWarm($, null)
486 await writeSnapshot($)
487 }
488 return next(e)
489 })
490
491 on('session.compact', async ($, e, next) => {
492 const result = await next(e)
493 // The conversation layer is replaced; the summarizer's request read the
494 // prefix, so the layers that stay are warm from now. A precompute
495 // replaces nothing: it only prepares the next compaction.
496 if (!e.agentId && e.trigger !== 'precompute' && result.skip === undefined) {
497 await tick($)
498 if ((await read($, keepWarm)).on) await stopKeepWarm($, 'stopped: compaction')
499 if ((await read($, cache)).lastResponseAt !== null) await rebase($)
500 }
501 return result
502 })
503
504 on('session.end', async ($, e, next) => {
505 const result = await next(e)
506 // Keep-warm belongs to the conversation that ended. After /clear, a resume
507 // or a logout the process goes on under another session, whose cache this
508 // one's countdown says nothing about.
509 stopPingTimer()
510 await update($, keepWarm, () => KEEP_WARM_OFF)
511 if (CONTINUES.has(e.reason)) {
512 await update($, cache, c => ({
513 ...c,
514 lastResponseAt: null,
515 warmUntil: null,
516 windowMs: TTL_MS[c.ttl],
517 prefixTokens: null,
518 confirmed: false,
519 }))
520 await settleTtl($)
521 // Another session's id: its own settings, if it has any; and its
522 // context, so the banner and the files stop showing the last one's.
523 await loadSettings($, true)
524 await takeReading($)
525 } else {
526 // The session is over (the process goes on only under another one,
527 // which keeps the slot): its file says so first, within the hook's
528 // budget, and stays so; the slot is free for the next.
529 hasEnded = true
530 await writeSessionFile($, true, true)
531 }
532 await writeSnapshot($)
533 return result
534 })
535
536 on('command.run', { command: 'token-watch' }, async ($, e) => {
537 const arg = e.args.trim().toLowerCase()
538 if (arg === 'file') {
539 return { text: await snapshotStatus($) }
540 }
541 if (arg === 'settings' || arg === 'monitor') {
542 const id = arg === 'settings' ? SETTINGS : SESSIONS
543 const title = arg === 'settings' ? SETTINGS_TITLE : SESSIONS_TITLE
544 const opened = arg === 'settings' ? await openSettings($) : await openSessions($)
545 if (opened.isPlaced) return { text: `${title} opened.` }
546 // Not placed: close it rather than leave it waiting, undrawn, for a
547 // surface that would show it later unasked.
548 await $.ui.close({ id }).catch(() => {})
549 return { text: `${title}: the panel can't be shown here (${opened.reason}).` }
550 }
551 if (arg !== '' && arg !== 'text') {
552 return { text: 'Usage: /token-watch [text|file|settings|monitor]' }
553 }
554 // The band draws on the terminal and the desktop app alone. Elsewhere
555 // (the VS Code extension's chat panel, a headless run) a bare
556 // /token-watch answers with the reading as one line instead of toggling
557 // a band nobody would see.
558 const surfaces = await $.session.surfaces().catch(() => ['terminal'] as const)
559 const draws = surfaces.some(s => s === 'terminal' || s === 'desktop')
560 if (arg === 'text' || !draws) {
561 await tick($)
562 await takeReading($)
563 const now = await read($, nowMs)
564 const text = readingLine(await read($, reading), current(await read($, limits), now), now, {
565 cache: await read($, cache),
566 keepWarm: await read($, keepWarm),
567 isWorking: await read($, working),
568 cap: await currentCap($),
569 warmMode: (await read($, settings)).warm.mode,
570 })
571 return { text: text || 'Token Watch: no reading yet.' }
572 }
573
574 const shown = !(await read($, isShown))
575 await update($, isShown, () => shown)
576 await $.store.set('isShown', shown)
577 if (shown) {
578 await takeReading($)
579 } else if ((await read($, keepWarm)).on && (await read($, settings)).warm.mode !== 'notify') {
580 // Nothing spends out of sight: pings stop with the banner (a
581 // reminder costs nothing, and stays).
582 await stopKeepWarm($, 'stopped: banner hidden')
583 }
584
585 return { text: shown ? 'Token Watch banner shown.' : 'Token Watch banner hidden.' }
586 })
587
588 on('ui.message', async ($, e, next) => {
589 const action = (e.data as { action?: string } | null)?.action
590 if (action === 'cycle') {
591 const moved = nextView(await read($, view))
592 await update($, view, () => moved)
593 await $.store.set('view', moved)
594 return {}
595 }
596 if (action === 'keep-warm') {
597 await toggleKeepWarm($)
598 return {}
599 }
600 if (action === 'refresh-caps') {
601 await refreshCaps($)
602 return {}
603 }
604
605 return next(e)
606 })
607
608 // The settings panel. At the top, which settings it edits: this session's
609 // own, which override the global ones leaf by leaf, or every session's.
610 // Then collapsible sections: Usage (a section per window: in which views it
611 // shows, and its pace's views, window and unit), Context, and Cache (its
612 // views and keep-warm's caps for this session's TTL). A checkbox's or a
613 // radio button's Button holds its mark and its label. A row this session
614 // overrides has a reset in this session's scope, and a note in every
615 // session's. A docked pane, so it stays beside the transcript while
616 // the band changes under it.
617 on('ui.render', { component: 'Pane', requestId: SETTINGS }, async ($, e) => {
618 const { Box, Text, Button } = $.ui.resolve(e)
619 // Every Button is plain on both surfaces (no native frame on the
620 // desktop). A checkbox or a radio button is its mark and its label in one
621 // Button, so a press on either toggles or picks it: ☑ / ☐ and ◉ / ○ on
622 // the desktop, ● / ○ for both in a terminal (☑ may draw there as a wide
623 // emoji). The rest are bracketed with no spaces: [▸] / [▾] for a section,
624 // [-] / [+] for a stepper, [Enable], [reset]. The desktop's font is
625 // proportional: its label columns keep a cell of slack.
626 const isTerminal = e.surface === 'terminal'
627 const wrap = (glyph: string) => `[${glyph}]`
628 const mark = (isOn: boolean) => (isTerminal ? (isOn ? '\u25cf' : '\u25cb') : isOn ? '\u2611' : '\u2610')
629 const choice = (isOn: boolean) => (isOn ? (isTerminal ? '\u25cf' : '\u25c9') : '\u25cb')
630 const pick = (key: string, glyph: string, label: string, onPress: () => void) => (
631 <Box key={key} flexShrink={0}>
632 <Button key={key} plain onPress={onPress}>
633 {`${glyph} ${label}`}
634 </Button>
635 </Box>
636 )
637 const checkbox = (key: string, label: string, isOn: boolean, onPress: () => void) => pick(key, mark(isOn), label, onPress)
638 const radio = (key: string, label: string, isOn: boolean, onPress: () => void) => pick(key, choice(isOn), label, onPress)
639 const isGlobal = await editsGlobal($)
640 const isMonitor = (await read($, scope)) === 'monitor'
641 const hasSession = (await sessionKey($)) !== null
642 const pressed = await read($, clearPresses)
643 const presses = (await read($, nowMs)) - pressed.since < CLEAR_WINDOW_MS ? pressed.count : 0
644 const pinsNow = await read($, pinned)
645 const hiddenNow = await read($, hiddenSessions)
646 const own = await read($, override)
647 // What each leaf reads in the scope shown.
648 const shown = isGlobal ? await read($, globalSettings) : await read($, settings)
649 const open = await read($, openSections)
650 const ttl = (await read($, cache)).ttl
651 const paceWidth = 'Window:'.length + (isTerminal ? 0 : 1)
652
653 // A row's override marker: a reset in this session's scope, a note in
654 // every session's.
655 const marker = (path: Path) =>
656 !overridesUnder(own, path) ? null : isGlobal ? (
657 <Text key={`over-${path.join('-')}`} dimColor wrap="truncate">
658 overridden in Session
659 </Text>
660 ) : (
661 <Button key={`reset-${path.join('-')}`} plain dimColor onPress={() => void resetSetting($, path)}>
662 {wrap('Reset')}
663 </Button>
664 )
665 // A section's heading, which opens and closes it, and its body indented.
666 // The heading is a plain Button on both surfaces (no native frame on the
667 // desktop), [▾] / [▸] and the title, so a press anywhere on it toggles,
668 // as in TW Monitor. A sub-section's title is not bold, and its
669 // row's override marker follows the Button, so an override shows with
670 // the section closed.
671 const section = (id: string, title: string, body: () => unknown, options: { isSub?: true; extra?: unknown } = {}) => {
672 const isOpen = open.includes(id)
673 return (
674 <Box key={id} flexDirection="column">
675 <Box flexDirection="row" columnGap={1}>
676 <Button key={`section-${id}`} plain onPress={() => void toggleSection($, id)}>
677 {`[${isOpen ? '\u25be' : '\u25b8'}] `}
678 <Text bold={!options.isSub || undefined}>{title}</Text>
679 </Button>
680 {(options.extra ?? null) as never}
681 </Box>
682 {isOpen && (
683 <Box flexDirection="column" paddingLeft={2}>
684 {body() as never}
685 </Box>
686 )}
687 </Box>
688 )
689 }
690 // The three views, each toggled on its own.
691 const viewChoices = (path: Path, key: string) => (
692 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
693 {VIEWS.map(v => {
694 const isOn = getAt(shown, [...path, v]) === true
695 return checkbox(`${key}-${v}`, VIEW_NAMES[v], isOn, () => void setSetting($, [...path, v], !isOn))
696 })}
697 </Box>
698 )
699 const views = (id: string, title: string, path: Path, key: string) =>
700 section(id, title, () => viewChoices(path, key), { isSub: true, extra: marker(path) })
701 // A part's alert level: [-]80%[+], 50% to 95% in steps of 5, then 99%,
702 // then Off; off, the [-] becomes Enable (to 99%) and there is no [+].
703 // A usage window's alert is every session's (the window is the account's),
704 // so only every session's scope shows it.
705 const alerts = (id: string, part: keyof typeof shown.alert) => {
706 const isShared = isGlobalOnly(['alert', part])
707 if (isShared && !isGlobal) return null
708 const level = shown.alert[part]
709 const step = (by: 1 | -1) => void setSetting($, ['alert', part], stepAlert(level, by))
710 return section(
711 id,
712 'Alerts',
713 () => (
714 <Box flexDirection="row">
715 {level === null ? (
716 <Button key={`alert-${part}-enable`} plain onPress={() => step(-1)}>
717 {wrap('Enable')}
718 </Button>
719 ) : (
720 <Button key={`alert-${part}-down`} plain dimColor={level <= 50} onPress={() => step(-1)}>
721 [-]
722 </Button>
723 )}
724 <Text>{level === null ? 'Off' : `${level}%`}</Text>
725 {level !== null && (
726 <Button key={`alert-${part}-up`} plain onPress={() => step(1)}>
727 [+]
728 </Button>
729 )}
730 </Box>
731 ),
732 { isSub: true, extra: isShared ? null : marker(['alert', part]) },
733 )
734 }
735 // A stepper: label, [-], value, [+], dimmed at the ends.
736 const stepper = (key: string, title: string, width: number, value: string, atMin: boolean, atMax: boolean, by: (d: 1 | -1) => void, over: Path) => (
737 <Box key={key} flexDirection="row" columnGap={1}>
738 <Box width={width} flexShrink={0}>
739 <Text>{title}</Text>
740 </Box>
741 <Button key={`${key}-down`} plain dimColor={atMin} onPress={() => by(-1)}>
742 [-]
743 </Button>
744 <Text>{value}</Text>
745 <Button key={`${key}-up`} plain dimColor={atMax} onPress={() => by(1)}>
746 [+]
747 </Button>
748 {marker(over)}
749 </Box>
750 )
751 const usage = (part: UsagePart, name: string) => {
752 const pace = shown.pace[part]
753 const windows = PACE_WINDOWS[part]
754 const id = `usage-${part}`
755 return section(id, name, () => (
756 <Box flexDirection="column">
757 {views(`${id}-show`, 'Show on banner', ['show', part], `show-${part}`)}
758 {alerts(`${id}-alert`, part)}
759 {section(
760 `${id}-pace`,
761 'Burn rate',
762 () => (
763 <Box flexDirection="column">
764 {viewChoices(['pace', part, 'show'], `pace-${part}`)}
765 {stepper(
766 `window-${part}`,
767 'Window:',
768 paceWidth,
769 windowText(pace.windowMin),
770 pace.windowMin <= windows[0]!,
771 pace.windowMin >= windows[windows.length - 1]!,
772 by => void setSetting($, ['pace', part, 'windowMin'], stepIn(windows, pace.windowMin, by)),
773 ['pace', part, 'windowMin'],
774 )}
775 <Box flexDirection="row" columnGap={1}>
776 <Box width={paceWidth} flexShrink={0}>
777 <Text>Unit:</Text>
778 </Box>
779 {PACE_UNITS[part].map(unit =>
780 radio(`unit-${part}-${unit}`, `%/${unit}`, pace.unit === unit, () => void setSetting($, ['pace', part, 'unit'], unit)),
781 )}
782 {marker(['pace', part, 'unit'])}
783 </Box>
784 </Box>
785 ),
786 { isSub: true, extra: marker(['pace', part, 'show']) },
787 )}
788 {views(`${id}-forecast`, 'Burn forecast', ['pace', part, 'forecast'], `forecast-${part}`)}
789 </Box>
790 ))
791 }
792 // The Monitor view: TW Monitor's settings, the same in every session (no
793 // session has its own), in collapsible rows; then the pins' and hidden
794 // sessions' resets.
795 const mon = shown.monitor
796 const groupWidth = 'TTL:'.length + (isTerminal ? 0 : 1)
797 const choices = <T extends string>(key: string, list: T[], names: Record<T, string>, at: T, pick: (value: T) => void) => (
798 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
799 {list.map(value => radio(`${key}-${value}`, names[value], at === value, () => pick(value)))}
800 </Box>
801 )
802 const note = (text: string) => (
803 <Text dimColor wrap="wrap">
804 {text}
805 </Text>
806 )
807 // A group's pieces as checkboxes, after its label where it has one.
808 const pieces = <T extends string>(key: string, label: string | null, list: T[], names: Record<T, string>, values: Record<T, boolean>, path: Path) => (
809 <Box key={key} flexDirection="row" columnGap={1}>
810 {label !== null && (
811 <Box width={groupWidth} flexShrink={0}>
812 <Text>{label}</Text>
813 </Box>
814 )}
815 <Box flexDirection="row" columnGap={1} flexWrap="wrap" flexShrink={1} minWidth={0}>
816 {list.map(piece => checkbox(`${key}-${piece}`, names[piece], values[piece], () => void setSetting($, [...path, piece], !values[piece])))}
817 </Box>
818 </Box>
819 )
820 const monitorView = () => (
821 <Box flexDirection="column" rowGap={1}>
822 {section('monitor-usage', 'Usage', () => (
823 <Box flexDirection="column">
824 {USAGE_PARTS.map(part =>
825 section(
826 `monitor-usage-${part}`,
827 USAGE_NAMES[part],
828 () => pieces(`monitor-usage-${part}`, null, MONITOR_USAGE_PIECES, MONITOR_USAGE_NAMES, mon.usage[part], ['monitor', 'usage', part]),
829 { isSub: true },
830 ),
831 )}
832 {note('A window with nothing ticked is left out, and Usage too when every window is.')}
833 </Box>
834 ))}
835 {section('monitor-lines', 'Session lines', () => (
836 <Box flexDirection="column">
837 {MONITOR_STATES.map(state =>
838 section(
839 `monitor-lines-${state}`,
840 state === 'expanded' ? 'Expanded' : 'Collapsed',
841 () => (
842 <Box flexDirection="column">
843 {pieces(`monitor-lines-${state}-ctx`, 'CTX:', MONITOR_CTX_PIECES, MONITOR_CTX_NAMES, mon.lines[state].ctx, ['monitor', 'lines', state, 'ctx'])}
844 {pieces(`monitor-lines-${state}-ttl`, 'TTL:', MONITOR_TTL_PIECES, MONITOR_TTL_NAMES, mon.lines[state].ttl, ['monitor', 'lines', state, 'ttl'])}
845 </Box>
846 ),
847 { isSub: true },
848 ),
849 )}
850 {note('A line with nothing on is left out.')}
851 </Box>
852 ))}
853 {section('monitor-name', 'Name', () => (
854 <Box flexDirection="column">
855 {choices('monitor-name', MONITOR_NAMES, MONITOR_NAME_NAMES, mon.name, value =>
856 void setSetting($, ['monitor', 'name'], value).then(() => (value === 'folder' ? forgetTitles($) : rereadTitles($))),
857 )}
858 {note('A title is read from its session\'s transcript when the session is listed, and again for every session when Title or Folder / title is pressed. A session without one shows its folder.')}
859 </Box>
860 ))}
861 {section('monitor-sort', 'Sort', () => (
862 <Box flexDirection="column">
863 {choices('monitor-sort', MONITOR_SORTS, MONITOR_SORT_NAMES, mon.sort, value => void setSetting($, ['monitor', 'sort'], value))}
864 {note('Pinned sessions always come first.')}
865 </Box>
866 ))}
867 {section('monitor-filter', 'Show', () => (
868 <Box flexDirection="column">
869 {choices('monitor-filter', MONITOR_FILTERS, MONITOR_FILTER_NAMES, mon.filter, value => void setSetting($, ['monitor', 'filter'], value))}
870 {mon.filter === 'recent' &&
871 stepper(
872 'recent',
873 'Within:',
874 paceWidth,
875 recentText(mon.recentMin),
876 mon.recentMin <= RECENT_STEPS[0]!,
877 mon.recentMin >= RECENT_STEPS[RECENT_STEPS.length - 1]!,
878 by => void setSetting($, ['monitor', 'recentMin'], stepIn(RECENT_STEPS, mon.recentMin, by)),
879 ['monitor', 'recentMin'],
880 )}
881 {note(MONITOR_FILTER_NOTES[mon.filter])}
882 </Box>
883 ))}
884 {section('monitor-current', 'Current session', () => (
885 <Box flexDirection="column">
886 {choices('monitor-current', MONITOR_CURRENT, MONITOR_CURRENT_NAMES, mon.current, value => void setSetting($, ['monitor', 'current'], value))}
887 {note(MONITOR_CURRENT_NOTES[mon.current])}
888 </Box>
889 ))}
890 </Box>
891 )
892 // Under the settings, each dim with nothing to undo: in this session's
893 // view, its own settings back to the global ones; in the global view,
894 // those back to the defaults; in the Monitor view, TW Monitor's back to
895 // the defaults, and every pin and hidden session undone.
896 const resets = () => (
897 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
898 {isMonitor ? (
899 <Button key="reset-monitor" plain dimColor={JSON.stringify(mon) === JSON.stringify(DEFAULT_SETTINGS.monitor) || undefined} onPress={() => void resetMonitor($)}>
900 {wrap('Reset to default')}
901 </Button>
902 ) : isGlobal ? (
903 <Button key="reset-defaults" plain dimColor={isDefault(shown) || undefined} onPress={() => void resetDefaults($)}>
904 {wrap('Reset to defaults')}
905 </Button>
906 ) : (
907 <Button key="reset-session" plain dimColor={isEmptyOverride(own) || undefined} onPress={() => void resetSession($)}>
908 {wrap('Reset to global')}
909 </Button>
910 )}
911 {isMonitor && (
912 <Button key="unpin-all" plain dimColor={Object.keys(pinsNow).length === 0 || undefined} onPress={() => void clearMarks($, 'pinned')}>
913 {wrap('Unpin all sessions')}
914 </Button>
915 )}
916 {isMonitor && (
917 <Button key="restore-all" plain dimColor={Object.keys(hiddenNow).length === 0 || undefined} onPress={() => void clearMarks($, 'hidden')}>
918 {wrap('Unhide all sessions')}
919 </Button>
920 )}
921 </Box>
922 )
923 // Below everything in the global view: Clear all data, which takes
924 // CLEAR_PRESSES presses within CLEAR_WINDOW_MS, counting them down, so
925 // one press by mistake clears nothing. The note under it says so (no
926 // tooltips for a Button).
927 const left = CLEAR_PRESSES - presses
928 const clear = () => (
929 <Box flexDirection="column">
930 <Box flexDirection="row">
931 <Button key="clear-all" plain onPress={() => void pressClear($)}>
932 {presses === 0 ? wrap('Clear all data') : <Text color={SESSION_COLD}>{wrap(`Clear all data: ${left} more`)}</Text>}
933 </Button>
934 </Box>
935 <Text dimColor wrap="wrap">
936 {`Press ${CLEAR_PRESSES} times within ${CLEAR_WINDOW_MS / 1000} seconds to delete everything Token Watch has stored: settings, pins, hidden sessions, titles and usage history. Its files in ~/.claude/token-watch stay; turn them off with Usage snapshot files in /config.`}
937 </Text>
938 </Box>
939 )
940 return (
941 <Box flexDirection="column" rowGap={1} paddingX={1}>
942 {/* Which settings the panel shows: this session's own (where it has
943 a session), every session's, or TW Monitor's. */}
944 <Box flexDirection="column">
945 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
946 {hasSession && radio('scope-session', 'Session', !isGlobal && !isMonitor, () => void setScope($, 'session'))}
947 {radio('scope-global', 'Global', isGlobal && !isMonitor, () => void setScope($, 'global'))}
948 {radio('scope-monitor', 'Monitor', isMonitor, () => void setScope($, 'monitor'))}
949 </Box>
950 <Text dimColor wrap="wrap">
951 {isMonitor
952 ? 'Changes apply to TW Monitor in every session.'
953 : isGlobal
954 ? 'Changes apply to every session, except where one has its own setting.'
955 : 'Changes apply to this session only, over Global. Usage alerts are set in Global.'}
956 </Text>
957 </Box>
958 {isMonitor && monitorView()}
959 {!isMonitor && section('usage', 'Usage', () => (
960 <Box flexDirection="column">
961 {usage('5H', '5H')}
962 {usage('WK', 'WK')}
963 {usage('other', 'OTH')}
964 </Box>
965 ))}
966 {!isMonitor && section('context', 'Context', () => (
967 <Box flexDirection="column">
968 {views('context-show', 'Show on banner', ['show', 'CTX'], 'show-CTX')}
969 {alerts('context-alert', 'CTX')}
970 {section(
971 'context-details',
972 'Details',
973 () => (
974 <Box flexDirection="column">
975 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
976 {DETAILS.map(([which, name]) => {
977 const isOn = shown.details[which]
978 return checkbox(`details-${which}`, name, isOn, () => void setSetting($, ['details', which], !isOn))
979 })}
980 </Box>
981 <Text dimColor wrap="wrap">
982 Shown under the legend in the Expanded view.
983 </Text>
984 </Box>
985 ),
986 { isSub: true, extra: marker(['details']) },
987 )}
988 </Box>
989 ))}
990 {!isMonitor && section('cache', 'Cache time', () => (
991 <Box flexDirection="column">
992 {section(
993 'cache-show',
994 'Show on banner',
995 () => (
996 <Box flexDirection="column">
997 {viewChoices(['show', 'TTL'], 'show-TTL')}
998 <Text dimColor wrap="wrap">
999 Hiding it in every view turns keep-warm off.
1000 </Text>
1001 </Box>
1002 ),
1003 { isSub: true, extra: marker(['show', 'TTL']) },
1004 )}
1005 {section(
1006 'cache-warm',
1007 'Keep-warm',
1008 () => (
1009 <Box flexDirection="column">
1010 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
1011 {WARM_MODES.map(mode =>
1012 radio(`warm-${mode}`, WARM_MODE_NAMES[mode], shown.warm.mode === mode, () => void setSetting($, ['warm', 'mode'], mode)),
1013 )}
1014 </Box>
1015 <Text dimColor wrap="wrap">
1016 {WARM_MODE_NOTES[shown.warm.mode]}
1017 </Text>
1018 {shown.warm.mode !== 'pings' &&
1019 stepper(
1020 'lead',
1021 'Remind:',
1022 paceWidth,
1023 `${shown.warm.lead[ttl]} min before`,
1024 shown.warm.lead[ttl] <= NOTIFY_LEADS[ttl][0]!,
1025 shown.warm.lead[ttl] >= NOTIFY_LEADS[ttl][NOTIFY_LEADS[ttl].length - 1]!,
1026 by => void setSetting($, ['warm', 'lead', ttl], stepIn(NOTIFY_LEADS[ttl], shown.warm.lead[ttl], by)),
1027 ['warm', 'lead', ttl],
1028 )}
1029 </Box>
1030 ),
1031 { isSub: true, extra: marker(['warm']) },
1032 )}
1033 {section(
1034 'cache-limits',
1035 `Limits (${ttl} TTL)`,
1036 () => (
1037 <Box flexDirection="column">
1038 {(['pings', 'hours'] as const).map(which => {
1039 const value = shown.caps[ttl][which]
1040 const { min, max, step } = CAP_LIMITS[ttl][which]
1041 return stepper(
1042 which,
1043 which === 'pings' ? 'Pings:' : 'Hours:',
1044 paceWidth,
1045 String(value),
1046 value <= min,
1047 value >= max,
1048 by => void setSetting($, ['caps', ttl, which], Math.min(max, Math.max(min, value + by * step))),
1049 ['caps', ttl, which],
1050 )
1051 })}
1052 <Text dimColor wrap="wrap">
1053 {`Defaults: ${DEFAULT_CAPS[ttl].pings} pings or ${DEFAULT_CAPS[ttl].hours} hours. Caps apply to pings, not reminders; a running keep-warm past a new cap stops.`}
1054 </Text>
1055 </Box>
1056 ),
1057 { isSub: true, extra: marker(['caps', ttl]) },
1058 )}
1059 </Box>
1060 ))}
1061 {resets()}
1062 <Text dimColor wrap="wrap">
1063 {isMonitor
1064 ? '/token-watch monitor opens TW Monitor; /token-watch settings opens this panel again.'
1065 : 'A burn rate is averaged over its window once that holds 5 minutes of readings. /token-watch settings opens this panel again.'}
1066 </Text>
1067 {isGlobal && !isMonitor && clear()}
1068 </Box>
1069 )
1070 })
1071
1072 // TW Monitor: the usage windows on top, then every live session on this
1073 // device (its file written in the last two minutes, and not ended), this
1074 // one with its own figures as they stand (first, by the Current session
1075 // setting), each with its name, its context and its prompt cache's
1076 // countdown, as the Monitor settings pick. The others' files are read when
1077 // the panel opens, every 30 s while it is open, and on its refresh.
1078 on('ui.render', { component: 'Pane', requestId: SESSIONS }, async ($, e) => {
1079 const { Box, Button, Text } = $.ui.resolve(e)
1080 const isTerminal = e.surface === 'terminal'
1081 const closed = await read($, sessionsClosed)
1082 // A section: its heading, which opens and closes it, and its body
1083 // indented under it. The heading is a plain Button (no native frame on
1084 // the desktop either), [▾] / [▸] and the title, so a press anywhere on it
1085 // toggles; what is said about it (this session, working) follows, dim.
1086 // Closed, the heading keeps a summary of what it holds: its figures in
1087 // their colours, as the band shows them, the rest dim. Options: `lead`
1088 // before the heading (a session's pin), `actions` at the row's right edge
1089 // (its hide), and the body's `indent`.
1090 const fold = (
1091 id: string,
1092 title: string,
1093 notes: string[],
1094 summary: SummaryPart[],
1095 body: () => unknown,
1096 options: { lead?: unknown; actions?: unknown; indent?: number } = {},
1097 ) => {
1098 const { lead = null, actions = null, indent = 2 } = options
1099 // A section is open until toggled, Hidden closed until toggled.
1100 const isOpen = closed.includes(id) === CLOSED_FIRST.has(id)
1101 const glyph = isOpen ? '\u25be' : '\u25b8'
1102 return (
1103 <Box key={id} flexDirection="column">
1104 <Box flexDirection="row" columnGap={1}>
1105 {/* The lead against the heading on the desktop, where the flag's
1106 Button brings its own room; a cell between in a terminal. */}
1107 <Box flexDirection="row" columnGap={isTerminal ? 1 : 0} flexShrink={1} minWidth={0}>
1108 {lead as never}
1109 {/* The glyph bracketed on both surfaces, so it reads as a button
1110 at rest too. */}
1111 <Box flexShrink={1} minWidth={0}>
1112 <Button key={`fold-${id}`} plain onPress={() => void toggleFold($, id)}>
1113 {`[${glyph}] `}
1114 <Text bold>{title}</Text>
1115 </Button>
1116 </Box>
1117 </Box>
1118 {/* One line, cut at the edge, and cut before the title is. */}
1119 {notes.length > 0 && (
1120 <Box flexShrink={NOTES_SHRINK} minWidth={0}>
1121 <Text dimColor wrap="truncate">
1122 {notes.join(' · ')}
1123 </Text>
1124 </Box>
1125 )}
1126 {!isOpen &&
1127 (summary.some(part => 'meter' in part) ? (
1128 <Box flexDirection="row" flexShrink={1} minWidth={0}>
1129 {summary.map((part, n) =>
1130 'meter' in part ? (
1131 <Box key={String(n)} flexShrink={0}>
1132 {meter(part.meter, part.color, SUMMARY_METER)}
1133 </Box>
1134 ) : (
1135 <Text key={String(n)} color={part.color} dimColor={part.color === undefined || undefined} wrap="truncate">
1136 {part.text}
1137 </Text>
1138 ),
1139 )}
1140 </Box>
1141 ) : (
1142 <Box flexShrink={1} minWidth={0}>
1143 <Text wrap="truncate">
1144 {summary.map((part, n) =>
1145 'meter' in part ? null : (
1146 <Text key={String(n)} color={part.color} dimColor={part.color === undefined || undefined}>
1147 {part.text}
1148 </Text>
1149 ),
1150 )}
1151 </Text>
1152 </Box>
1153 ))}
1154 {/* No fragment: the engine lays a fragment's children out as a
1155 column. */}
1156 {actions !== null && <Box flexGrow={1} />}
1157 {actions as never}
1158 </Box>
1159 {isOpen && (
1160 <Box flexDirection="column" paddingLeft={indent}>
1161 {body() as never}
1162 </Box>
1163 )}
1164 </Box>
1165 )
1166 }
1167 // The line between the usage and the sessions: a run of box-drawing
1168 // lines in a terminal, a hairline on the desktop.
1169 const rule = () =>
1170 isTerminal ? (
1171 <Text key="rule" color={SESSION_TRACK} wrap="truncate">
1172 {'\u2500'.repeat(Math.max(1, e.props.bodyColumns - 2))}
1173 </Text>
1174 ) : (
1175 <Box key="rule" flexDirection="row" height={1} alignItems="center">
1176 <Box flexGrow={1} height="10%" backgroundColor={SESSION_TRACK} />
1177 </Box>
1178 )
1179 const now = await read($, nowMs)
1180 const m = (await read($, settings)).monitor
1181 const own = await sessionSnapshotOf($, now, null)
1182 const names = await read($, titles)
1183 const pins = await read($, pinned)
1184 const hides = await read($, hiddenSessions)
1185 const isPinned = (s: SessionSnapshot) => s.session.id !== null && s.session.id in pins
1186 const isHidden = (s: SessionSnapshot) => s.session.id !== null && s.session.id in hides
1187 // A session's name by the Name setting: its folder, its title (else its
1188 // folder), or both.
1189 const nameOf = (s: SessionSnapshot) => {
1190 const folder = folderOf(projectOf(s))
1191 const title = s.session.id === null ? null : (names[s.session.id] ?? null)
1192 if (m.name === 'title') return title ?? folder
1193 if (m.name === 'both' && title !== null) return `${folder} / ${title}`
1194 return folder
1195 }
1196 // When a session's cache expires: the whole TTL on while a turn runs;
1197 // null when cold or unknown.
1198 const expiresOf = (s: SessionSnapshot) => {
1199 if (s.isWorking) return now + TTL_MS[s.cache.ttl]
1200 const at = s.cache.expiresAt === null ? NaN : Date.parse(s.cache.expiresAt)hooks/cache.ts 170 lines1// The prompt cache's rules and keep-warm's policy in one place: the two TTLs,
2// how Token Watch decides which one the main conversation gets, when a ping
3// goes out and when keep-warm stops. Constants and pure functions; the hooks
4// module (./register.tsx) applies them and the band (./band.tsx) reads the
5// constants it shows.
6
7import type { PromptOrigin } from 'claude-code'
8
9import type { Cap, CacheState, CapSetting, CapSettings, KeepWarm, Limit, Ttl, TtlInputs, TtlSource, View } from '../types'
10
11export const MINUTE = 60_000
12
13export const TTL_MS: Record<Ttl, number> = { '5m': 5 * MINUTE, '1h': 60 * MINUTE }
14
15// How long a keep-warm ping keeps the cache warm, counted from the ping: the
16// main conversation's own TTL.
17//
18// Measured in the spike. Five-minute TTL (forced): a check eight minutes after
19// a response read nothing from the cache (run A0), and read 47k tokens when
20// one fork had pinged at four minutes (run A1). One-hour TTL: a check at 65
21// minutes read nothing (run B0), and read the 33k tokens a fork had read at
22// 55 minutes (run B1), ten minutes after that ping: a fork's read renews the
23// entries it hits for their original TTL, not for the fork's own five
24// minutes.
25export function refreshMs(ttl: Ttl) {
26 return TTL_MS[ttl]
27}
28
29// How long before the believed expiry a ping is sent, by the window it
30// extends: 75 s on a five-minute window, 8 min on an hour. Generous, because
31// the API counts a TTL from the start of the last request while the band
32// counts from the end of its response, and because idle compaction can run
33// about 54 minutes into an idle hour.
34export function leadMs(windowMs: number) {
35 return windowMs >= TTL_MS['1h'] ? 8 * MINUTE : 75_000
36}
37
38// Keep-warm's caps by TTL, until the settings panel changes them: on the
39// hour 8 pings or eight hours, on five minutes 30 pings or two hours.
40export const DEFAULT_CAPS: CapSettings = { '1h': { pings: 8, hours: 8 }, '5m': { pings: 30, hours: 2 } }
41
42// What the settings panel's steppers allow, by TTL: the least, the most and
43// the step. On the hour a ping goes out about every 52 minutes, so 24 pings
44// is about a day; on five minutes every 3:45, so 100 pings is about six hours.
45export const CAP_LIMITS: Record<Ttl, Record<keyof CapSetting, { min: number; max: number; step: number }>> = {
46 '1h': { pings: { min: 1, max: 24, step: 1 }, hours: { min: 1, max: 24, step: 1 } },
47 '5m': { pings: { min: 5, max: 100, step: 5 }, hours: { min: 1, max: 6, step: 1 } },
48}
49
50// The caps in force for a TTL.
51export function caps(ttl: Ttl, settings: CapSettings): Cap {
52 const cap = settings[ttl]
53 return { pings: cap.pings, ms: cap.hours * 60 * MINUTE }
54}
55
56// Whether a value is one a cap's stepper can reach: a whole number on its
57// grid within its bounds.
58export function isCapValue(ttl: Ttl, which: keyof CapSetting, value: unknown): value is number {
59 const { min, max, step } = CAP_LIMITS[ttl][which]
60 return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max && (value - min) % step === 0
61}
62
63// The cap a stored value names, by TTL and field, if it names one.
64function capOf(saved: unknown, ttl: Ttl, which: keyof CapSetting): unknown {
65 return (saved as Partial<Record<Ttl, Partial<CapSetting>>> | null)?.[ttl]?.[which]
66}
67
68// Caps read back from the store: each value one its stepper can reach, else
69// the default. Anything else is the defaults.
70export function readCaps(saved: unknown): CapSettings {
71 const read = (ttl: Ttl, which: keyof CapSetting) => {
72 const value = capOf(saved, ttl, which)
73 return isCapValue(ttl, which, value) ? value : DEFAULT_CAPS[ttl][which]
74 }
75 return {
76 '1h': { pings: read('1h', 'pings'), hours: read('1h', 'hours') },
77 '5m': { pings: read('5m', 'pings'), hours: read('5m', 'hours') },
78 }
79}
80
81// How long a session's own settings are kept after it last saved them.
82export const SESSION_SETTINGS_KEEP_MS = 30 * 24 * 60 * MINUTE
83
84// The one user message a ping appends; the reply is a few tokens.
85export const PING_PROMPT = 'Reply with the single word: ok'
86
87// Keep-warm stops after this many failed pings in a row, and retries a
88// failed one after RETRY_MS.
89export const MAX_FAILURES = 2
90export const RETRY_MS = 30_000
91
92// A ping still unanswered after this long is taken as lost (a reload dropped
93// the module that sent it), so the next one may go out.
94export const PING_LOST_MS = 2 * MINUTE
95
96// A ping that reads less than this share of the last response's prompt found
97// the cache cold (a warm fork read about 70% of it in the spike, since its
98// request differs from the main thread's in its tail). Before the first
99// breakdown, below MIN_WARM_READ tokens.
100export const COLD_READ_SHARE = 0.5
101export const MIN_WARM_READ = 1024
102
103// How long the band shows a ping's counts or a stop reason.
104export const NOTE_MS = 60_000
105
106// Prompt origins that are not the person typing (PromptOrigin in the API's
107// declarations): a prompt from any other origin turns keep-warm off.
108export const BACKGROUND_ORIGINS: ReadonlySet<PromptOrigin['kind']> = new Set<PromptOrigin['kind']>([
109 'task-notification',
110 'scheduled-trigger',
111 'peer',
112 'peer-send-message',
113 'projects-relay',
114 'channel',
115 'coordinator',
116 'observer',
117 'observer-activity',
118 'auto-continuation',
119 'plugin',
120])
121
122export function isTtl(value: unknown): value is Ttl {
123 return value === '5m' || value === '1h'
124}
125
126export const NO_INPUTS: TtlInputs = { force5m: false, envTtl: null, settingTtl: null, enable1h: false }
127
128export const NO_CACHE: CacheState = {
129 ttl: '5m',
130 ttlSource: 'API key or cloud',
131 lastResponseAt: null,
132 warmUntil: null,
133 windowMs: TTL_MS['5m'],
134 prefixTokens: null,
135 confirmed: false,
136}
137
138export const KEEP_WARM_OFF: KeepWarm = {
139 on: false,
140 startedAt: null,
141 pings: 0,
142 failures: 0,
143 lastPing: null,
144 note: null,
145 notifiedFor: null,
146}
147
148// The TTL the main conversation gets, in Claude Code's order of precedence
149// (docs: prompt caching, "Choose the TTL yourself"): FORCE_PROMPT_CACHING_5M,
150// then CLAUDE_CODE_PROMPT_CACHE_TTL, then the promptCacheTtl setting, then
151// ENABLE_PROMPT_CACHING_1H, then the default: an hour on a subscription
152// within its plan usage (a usage window past 100% means usage credits, so
153// five minutes), five minutes with an API key or a cloud provider. A ping
154// that found the cache warm more than five minutes after the last response
155// has proved the hour, which outranks the default alone.
156export function resolveTtl(inputs: TtlInputs, limits: Limit[], confirmed: boolean): { ttl: Ttl; ttlSource: TtlSource } {
157 if (inputs.force5m) return { ttl: '5m', ttlSource: 'FORCE_PROMPT_CACHING_5M' }
158 if (inputs.envTtl !== null) return { ttl: inputs.envTtl, ttlSource: 'CLAUDE_CODE_PROMPT_CACHE_TTL' }
159 if (inputs.settingTtl !== null) return { ttl: inputs.settingTtl, ttlSource: 'promptCacheTtl' }
160 if (inputs.enable1h) return { ttl: '1h', ttlSource: 'ENABLE_PROMPT_CACHING_1H' }
161 if (limits.some(w => w.percentUsed >= 100)) return { ttl: '5m', ttlSource: 'over plan limit' }
162 if (confirmed) return { ttl: '1h', ttlSource: 'confirmed' }
163 if (limits.length === 0) return { ttl: '5m', ttlSource: 'API key or cloud' }
164 return { ttl: '1h', ttlSource: 'subscription' }
165}
166
167// The view a right click moves to.
168export function nextView(view: View): View {
169 return view === 'expanded' ? 'bars' : view === 'bars' ? 'plain' : 'expanded'
170}hooks/settings.ts 278 lines1// The settings, as one tree: what each part of the banner shows in each
2// view, each usage window's pace (shown in which views, its averaging window
3// and its unit), keep-warm's caps, mode and reminder, the alerts, the
4// context's details lines, and TW Monitor's settings. Every setting is a
5// leaf with a check of its own. The global settings are the whole tree; a session's own
6// are a sparse copy of it, holding only the leaves the session set; the
7// settings in force take the session's leaf where there is one, else the
8// global. Pure functions; the hooks module keeps and saves the trees.
9
10import type {
11 AlertPart,
12 BurnUnit,
13 CapSetting,
14 MonitorCurrent,
15 MonitorFilter,
16 MonitorCtxPiece,
17 MonitorName,
18 MonitorSort,
19 MonitorState,
20 MonitorTtlPiece,
21 MonitorUsagePiece,
22 Part,
23 SettingsOverride,
24 SettingsTree,
25 Ttl,
26 UsagePart,
27 View,
28 WarmMode,
29} from '../types'
30import { DEFAULT_CAPS, isCapValue, readCaps } from './cache'
31
32// The band's views, in the order the panel lists them, and the panel's names
33// for them: the collapsed line without bars, with bars, and the table.
34export const VIEWS: View[] = ['plain', 'bars', 'expanded']
35export const VIEW_NAMES: Record<View, string> = { plain: 'Minimal', bars: 'Collapsed', expanded: 'Expanded' }
36
37export const ALL_PARTS: Part[] = ['5H', 'WK', 'other', 'CTX', 'TTL']
38
39// The parts that are usage windows, which have a pace.
40export const USAGE_PARTS: UsagePart[] = ['5H', 'WK', 'other']
41
42// Each usage part's averaging windows (minutes) and units. The 5-hour window
43// moves within the hour; the weekly ones (WK, and the model allowances most
44// other windows are) over hours or days.
45export const PACE_WINDOWS: Record<UsagePart, number[]> = {
46 '5H': [15, 30, 60, 120],
47 WK: [120, 360, 720, 1440],
48 other: [120, 360, 720, 1440],
49}
50export const PACE_UNITS: Record<UsagePart, BurnUnit[]> = { '5H': ['h', 'min'], WK: ['h', 'day'], other: ['h', 'day'] }
51
52// Keep-warm's modes, and how many minutes before the cache expires (Notify)
53// or before the first ping (Both) the reminder comes, by TTL.
54export const WARM_MODES: WarmMode[] = ['pings', 'notify', 'both']
55export const NOTIFY_LEADS: Record<Ttl, number[]> = { '1h': [2, 5, 10, 15], '5m': [1, 2, 3] }
56
57// The parts that can alert, and the levels an alert's stepper goes through:
58// 50% to 95% in steps of 5, then 99%, then off (null).
59export const ALERT_PARTS: AlertPart[] = ['5H', 'WK', 'other', 'CTX']
60export const ALERT_STEPS: (number | null)[] = [50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 99, null]
61
62// The next alert level up (+1, towards off) or down (-1), held at the ends.
63export function stepAlert(level: number | null, by: 1 | -1) {
64 const i = ALERT_STEPS.indexOf(level)
65 return ALERT_STEPS[Math.min(ALERT_STEPS.length - 1, Math.max(0, i + by))] ?? null
66}
67
68// TW Monitor's choices, in the order the panel lists them: what a usage
69// window's line shows; what a session's context and cache show, in which
70// state; the name; the order; which sessions; and how far back "recent"
71// reaches (minutes, 5 minutes to 7 days).
72export const MONITOR_USAGE_PIECES: MonitorUsagePiece[] = ['bar', 'percent', 'reset', 'rate']
73export const MONITOR_CTX_PIECES: MonitorCtxPiece[] = ['bar', 'percent', 'tokens']
74export const MONITOR_TTL_PIECES: MonitorTtlPiece[] = ['bar', 'timer', 'warm']
75export const MONITOR_STATES: MonitorState[] = ['expanded', 'collapsed']
76export const MONITOR_NAMES: MonitorName[] = ['folder', 'title', 'both']
77export const MONITOR_SORTS: MonitorSort[] = ['name', 'context', 'expiry', 'activity']
78export const MONITOR_FILTERS: MonitorFilter[] = ['all', 'warm', 'recent']
79export const RECENT_STEPS = [5, 10, 15, 30, 60, 120, 240, 480, 720, 1440, 4320, 10080]
80export const MONITOR_CURRENT: MonitorCurrent[] = ['default', 'top']
81
82export type Path = readonly string[]
83
84const everyView = (): Record<View, boolean> => ({ plain: true, bars: true, expanded: true })
85const everyPiece = (): Record<MonitorUsagePiece, boolean> => ({ bar: true, percent: true, reset: true, rate: true })
86// The pace and its forecast, by default, only in the table, where they have
87// columns of their own.
88const expandedOnly = (): Record<View, boolean> => ({ plain: false, bars: false, expanded: true })
89
90export const DEFAULT_SETTINGS: SettingsTree = {
91 show: { '5H': everyView(), WK: everyView(), other: everyView(), CTX: everyView(), TTL: everyView() },
92 pace: {
93 '5H': { show: expandedOnly(), forecast: expandedOnly(), windowMin: 30, unit: 'h' },
94 WK: { show: expandedOnly(), forecast: expandedOnly(), windowMin: 360, unit: 'h' },
95 other: { show: expandedOnly(), forecast: expandedOnly(), windowMin: 360, unit: 'h' },
96 },
97 caps: DEFAULT_CAPS,
98 // Keep-warm reminds, free, unless pings are chosen.
99 warm: { mode: 'notify', lead: { '1h': 5, '5m': 1 } },
100 alert: { '5H': null, WK: null, other: null, CTX: null },
101 details: { mcp: false, memory: false, skills: false },
102 // 5H and WK in full, no other windows; a session open in full, closed its
103 // countdown and keep-warm alone.
104 monitor: {
105 usage: { '5H': everyPiece(), WK: everyPiece(), other: { bar: false, percent: false, reset: false, rate: false } },
106 lines: {
107 expanded: { ctx: { bar: true, percent: true, tokens: true }, ttl: { bar: true, timer: true, warm: true } },
108 collapsed: { ctx: { bar: false, percent: false, tokens: false }, ttl: { bar: false, timer: true, warm: true } },
109 },
110 name: 'folder',
111 sort: 'name',
112 filter: 'all',
113 recentMin: 1440,
114 current: 'top',
115 },
116}
117
118const TTLS: Ttl[] = ['1h', '5m']
119const CAP_FIELDS: (keyof CapSetting)[] = ['pings', 'hours']
120
121const isBool = (value: unknown) => typeof value === 'boolean'
122
123// Every leaf of the tree with its check. A leaf `isGlobalOnly` has no
124// session's own value: the usage windows' alerts, the windows being the
125// account's, alert the same in every session.
126const LEAVES: { path: Path; isValid: (value: unknown) => boolean; isGlobalOnly?: true }[] = [
127 ...ALL_PARTS.flatMap(part => VIEWS.map(v => ({ path: ['show', part, v], isValid: isBool }))),
128 ...USAGE_PARTS.flatMap(part => [
129 ...VIEWS.map(v => ({ path: ['pace', part, 'show', v], isValid: isBool })),
130 ...VIEWS.map(v => ({ path: ['pace', part, 'forecast', v], isValid: isBool })),
131 { path: ['pace', part, 'windowMin'], isValid: (value: unknown) => PACE_WINDOWS[part].includes(value as number) },
132 { path: ['pace', part, 'unit'], isValid: (value: unknown) => PACE_UNITS[part].includes(value as BurnUnit) },
133 ]),
134 ...TTLS.flatMap(ttl =>
135 CAP_FIELDS.map(which => ({ path: ['caps', ttl, which], isValid: (value: unknown) => isCapValue(ttl, which, value) })),
136 ),
137 { path: ['warm', 'mode'], isValid: (value: unknown) => WARM_MODES.includes(value as WarmMode) },
138 ...TTLS.map(ttl => ({ path: ['warm', 'lead', ttl], isValid: (value: unknown) => NOTIFY_LEADS[ttl].includes(value as number) })),
139 ...(['mcp', 'memory', 'skills'] as const).map(which => ({ path: ['details', which], isValid: isBool })),
140 // TW Monitor's, the same in every session: the settings panel's Monitor
141 // view edits them, with no session's own.
142 ...[
143 ...USAGE_PARTS.flatMap(part => MONITOR_USAGE_PIECES.map(piece => ({ path: ['monitor', 'usage', part, piece], isValid: isBool }))),
144 ...MONITOR_STATES.flatMap(state => [
145 ...MONITOR_CTX_PIECES.map(piece => ({ path: ['monitor', 'lines', state, 'ctx', piece], isValid: isBool })),
146 ...MONITOR_TTL_PIECES.map(piece => ({ path: ['monitor', 'lines', state, 'ttl', piece], isValid: isBool })),
147 ]),
148 { path: ['monitor', 'name'], isValid: (value: unknown) => MONITOR_NAMES.includes(value as MonitorName) },
149 { path: ['monitor', 'sort'], isValid: (value: unknown) => MONITOR_SORTS.includes(value as MonitorSort) },
150 { path: ['monitor', 'filter'], isValid: (value: unknown) => MONITOR_FILTERS.includes(value as MonitorFilter) },
151 { path: ['monitor', 'recentMin'], isValid: (value: unknown) => RECENT_STEPS.includes(value as number) },
152 { path: ['monitor', 'current'], isValid: (value: unknown) => MONITOR_CURRENT.includes(value as MonitorCurrent) },
153 ].map(leaf => ({ ...leaf, isGlobalOnly: true as const })),
154 ...ALERT_PARTS.map(part => ({
155 path: ['alert', part],
156 isValid: (value: unknown) => ALERT_STEPS.includes(value as number | null),
157 ...(part === 'CTX' ? {} : { isGlobalOnly: true as const }),
158 })),
159]
160
161export function getAt(tree: unknown, path: Path): unknown {
162 let node = tree
163 for (const key of path) {
164 if (typeof node !== 'object' || node === null) return undefined
165 node = (node as Record<string, unknown>)[key]
166 }
167 return node
168}
169
170// The tree with one leaf set, copied along its path.
171export function setAt<T>(tree: T, path: Path, value: unknown): T {
172 const [key, ...rest] = path
173 if (key === undefined) return value as T
174 const node = (typeof tree === 'object' && tree !== null ? tree : {}) as Record<string, unknown>
175 return { ...node, [key]: setAt(node[key], rest, value) } as T
176}
177
178// The tree with one leaf removed, and any branch left empty with it.
179export function dropAt<T>(tree: T, path: Path): T {
180 const [key, ...rest] = path
181 if (key === undefined || typeof tree !== 'object' || tree === null) return tree
182 const node = tree as Record<string, unknown>
183 if (!(key in node)) return tree
184 const { [key]: child, ...others } = node
185 if (rest.length === 0) return others as T
186 const pruned = dropAt(child, rest)
187 const isEmpty = typeof pruned === 'object' && pruned !== null && Object.keys(pruned).length === 0
188 return (isEmpty ? others : { ...others, [key]: pruned }) as T
189}
190
191// The global settings read back from the store: each leaf that passes its
192// check, else the default.
193export function readSettings(saved: unknown): SettingsTree {
194 return LEAVES.reduce((tree, leaf) => {
195 const value = getAt(saved, leaf.path)
196 return leaf.isValid(value) ? setAt(tree, leaf.path, value) : tree
197 }, DEFAULT_SETTINGS)
198}
199
200// A session's own settings read back: only the leaves a session may set that
201// pass their check.
202export function readOverride(saved: unknown): SettingsOverride {
203 return LEAVES.reduce<SettingsOverride>((tree, leaf) => {
204 const value = getAt(saved, leaf.path)
205 return !leaf.isGlobalOnly && leaf.isValid(value) ? setAt(tree, leaf.path, value) : tree
206 }, {})
207}
208
209// Whether a path names a leaf only the global settings hold.
210export function isGlobalOnly(path: Path) {
211 return LEAVES.some(leaf => leaf.isGlobalOnly && leaf.path.length === path.length && leaf.path.every((k, i) => k === path[i]))
212}
213
214// 1.3.0's settings, the parts it hid (hidden in every view) and its caps, as
215// a tree.
216export function fromLegacy(hidden: unknown, caps: unknown): SettingsTree {
217 const parts = Array.isArray(hidden) ? hidden.filter((p): p is Part => ALL_PARTS.includes(p as Part)) : []
218 const show = parts.reduce(
219 (tree, part) => ({ ...tree, [part]: { plain: false, bars: false, expanded: false } }),
220 DEFAULT_SETTINGS.show,
221 )
222 return { ...DEFAULT_SETTINGS, show, caps: readCaps(caps) }
223}
224
225// The settings in force: the session's leaf where it set one, else the global.
226export function merge(global: SettingsTree, override: SettingsOverride): SettingsTree {
227 return LEAVES.reduce((tree, leaf) => {
228 const value = getAt(override, leaf.path)
229 return value === undefined ? tree : setAt(tree, leaf.path, value)
230 }, global)
231}
232
233export function isEmptyOverride(override: SettingsOverride) {
234 return LEAVES.every(leaf => getAt(override, leaf.path) === undefined)
235}
236
237// Whether the override sets any leaf under a path (a row of the panel).
238export function overridesUnder(override: SettingsOverride, path: Path) {
239 return LEAVES.some(leaf => path.every((key, i) => leaf.path[i] === key) && getAt(override, leaf.path) !== undefined)
240}
241
242// The next value of a list up (+1) or down (-1), held at the ends.
243export function stepIn(list: number[], value: number, by: 1 | -1) {
244 const i = list.indexOf(value)
245 return list[Math.min(list.length - 1, Math.max(0, i + by))] ?? value
246}
247
248// The parts a view hides, and the usage parts whose pace it hides.
249export function hiddenIn(settings: SettingsTree, view: View): Part[] {
250 return ALL_PARTS.filter(part => !settings.show[part][view])
251}
252
253export function paceHiddenIn(settings: SettingsTree, view: View): Part[] {
254 return USAGE_PARTS.filter(part => !settings.pace[part].show[view])
255}
256
257export function forecastHiddenIn(settings: SettingsTree, view: View): Part[] {
258 return USAGE_PARTS.filter(part => !settings.pace[part].forecast[view])
259}
260
261// Whether no view shows the cache, which keeps keep-warm off.
262export function isCacheHidden(settings: SettingsTree) {
263 return VIEWS.every(v => !settings.show.TTL[v])
264}
265
266// How far back "recent" reaches, as the panel prints it: "15 min", "4 h",
267// "3 d".
268export function recentText(minutes: number) {
269 if (minutes < 60) return `${minutes} min`
270 if (minutes < 1440) return `${minutes / 60} h`
271 return `${minutes / 1440} d`
272}
273
274// An averaging window as the panel prints it: "30 min", "6 h".
275export function windowText(minutes: number) {
276 return minutes < 60 ? `${minutes} min` : `${minutes / 60} h`
277}
278hooks/burn.ts 149 lines1// Burn rates: how fast each usage window fills, from the readings Token
2// Watch already takes, averaged over a window the settings panel sets. Pure
3// functions; the hooks module keeps the readings and the band draws the
4// results.
5//
6// A window's percentage is kept only when it moves, so it is a step function:
7// its value at any moment is the newest sample at or before that moment. The
8// pace over the window is the step from the window's start to now, over the
9// time between them. The 5-hour and weekly windows are the account's, so the
10// samples are shared by every session through the store.
11
12import type { BurnUnit, History, Limit, Sample } from '../types'
13import { MINUTE } from './cache'
14
15const HOUR = 60 * MINUTE
16
17// The least time a rate is worked out over: less, and a single step of one
18// reading would read as a pace.
19export const MIN_SPAN_MS = 5 * MINUTE
20
21// How long samples are kept: the longest averaging window the panel offers,
22// plus the newest older sample, which says where that window started.
23export const KEEP_MS = 24 * 60 * MINUTE
24
25// A fall in the same period this many points or more is a reset (a plan
26// change, a correction), not a reading that arrived out of order.
27export const DROP_RESET = 5
28
29// Reset times this close are the same one, however each was spelled.
30const RESET_TOLERANCE_MS = 60_000
31
32// Whether two reset times are the same period's.
33export function isSameReset(a: string | null | undefined, b: string | null | undefined) {
34 if (!a || !b) return !a && !b
35 const at = Date.parse(a)
36 const bt = Date.parse(b)
37 return Number.isNaN(at) || Number.isNaN(bt) ? a === b : Math.abs(at - bt) < RESET_TOLERANCE_MS
38}
39
40// Whether a reset time is an earlier period's than another.
41export function isEarlier(a: string | null | undefined, b: string | null | undefined) {
42 if (!a || !b) return false
43 const at = Date.parse(a)
44 const bt = Date.parse(b)
45 return !Number.isNaN(at) && !Number.isNaN(bt) && at < bt - RESET_TOLERANCE_MS
46}
47
48// Samples kept: those newer than KEEP_MS, and the newest older one.
49function trim<T extends { at: number }>(samples: T[], now: number): T[] {
50 const cut = samples.findIndex(s => s.at > now - KEEP_MS)
51 if (cut === -1) return samples.slice(-1)
52 return samples.slice(Math.max(0, cut - 1))
53}
54
55// A reading's windows added to the history: a sample where a window's
56// percentage moved. A window whose reset time moved on has reset, and starts
57// over; a reading from an earlier period arrived late, and is left out. In
58// the same period, a small fall is a reading that arrived out of order (two
59// sessions' responses crossing), left out too; a fall of DROP_RESET points
60// or more (a plan change, a correction), or any fall in a window with no
61// reset time to tell by, starts over. Unchanged, the history comes back as
62// it was.
63export function addReadings(history: History, limits: Limit[], at: number): History {
64 let next = history
65 for (const limit of limits) {
66 const resetsAt = limit.resetsAt ?? null
67 const kept = history[limit.kind]
68 const last = kept?.samples[kept.samples.length - 1]
69 if (kept && isEarlier(resetsAt, kept.resetsAt)) continue
70 const fall = last === undefined ? 0 : last.percent - limit.percentUsed
71 const isSamePeriod = kept !== undefined && isSameReset(kept.resetsAt, resetsAt)
72 const hasReset = !isSamePeriod || (fall > 0 && (resetsAt === null || fall >= DROP_RESET))
73 if (!hasReset && (fall > 0 || last?.percent === limit.percentUsed)) continue
74 const sample: Sample = { at, percent: limit.percentUsed }
75 const samples = hasReset || !kept ? [sample] : trim([...kept.samples, sample], at)
76 next = { ...next, [limit.kind]: { resetsAt, samples } }
77 }
78 return next
79}
80
81// A history read back from the store: each window's samples in time order,
82// anything that does not read as one left out.
83export function readHistory(saved: unknown): History {
84 const history: History = {}
85 if (typeof saved !== 'object' || saved === null) return history
86 for (const [kind, value] of Object.entries(saved as Record<string, unknown>)) {
87 const v = value as { resetsAt?: unknown; samples?: unknown } | null
88 if (!v || !Array.isArray(v.samples)) continue
89 const samples = v.samples.filter(
90 (s): s is Sample => typeof s?.at === 'number' && typeof s?.percent === 'number',
91 )
92 if (samples.length === 0) continue
93 samples.sort((a, b) => a.at - b.at)
94 history[kind] = { resetsAt: typeof v.resetsAt === 'string' ? v.resetsAt : null, samples }
95 }
96 return history
97}
98
99// The change from the window's start to now: the value at the start and the
100// newest value, with the time between. The value at the start lies on the
101// line between the samples either side of it, so a gap between readings
102// (usage elsewhere, on another device) is spread over the gap rather than
103// booked at its end; with tracking begun later, the start is the oldest
104// sample.
105function stepOver(samples: Sample[], now: number, windowMs: number) {
106 const last = samples[samples.length - 1]
107 const first = samples[0]
108 if (last === undefined || first === undefined) return null
109 const start = now - windowMs
110 if (first.at >= start) return { base: first.percent, last: last.percent, span: now - first.at }
111 const after = samples.findIndex(s => s.at > start)
112 if (after === -1) return { base: last.percent, last: last.percent, span: windowMs }
113 const a = samples[after - 1]!
114 const b = samples[after]!
115 const base = a.percent + ((b.percent - a.percent) * (start - a.at)) / (b.at - a.at)
116 return { base, last: last.percent, span: windowMs }
117}
118
119// Percentage points an hour over the window, or null with less than
120// MIN_SPAN_MS of readings in it.
121export function ratePerHour(samples: Sample[], now: number, windowMs: number): number | null {
122 const step = stepOver(samples, now, windowMs)
123 if (step === null || step.span < MIN_SPAN_MS) return null
124 return Math.max(0, (step.last - step.base) / (step.span / HOUR))
125}
126
127// When a window fills at this pace: now when it is full already; null at no
128// pace, or when it would reset first.
129export function fullAt(percent: number, perHour: number | null, now: number, resetsAt: string | undefined): number | null {
130 if (perHour === null) return null
131 if (percent >= 100) return now
132 if (perHour <= 0) return null
133 const at = now + ((100 - percent) / perHour) * HOUR
134 const reset = resetsAt ? Date.parse(resetsAt) : NaN
135 return !Number.isNaN(reset) && at >= reset ? null : at
136}
137
138// A rate as the band prints it: "12%/h", "3.2%/h", "0.20%/min", "14%/day".
139export function rateText(perHour: number, unit: BurnUnit) {
140 // The precision chosen by the value as printed: 9.96 is "10%/h", not
141 // "10.0%/h".
142 if (unit === 'min') {
143 const perMin = perHour / 60
144 return `${Number(perMin.toFixed(2)) >= 1 ? perMin.toFixed(1) : perMin.toFixed(2)}%/min`
145 }
146 const value = unit === 'day' ? perHour * 24 : perHour
147 return `${Number(value.toFixed(1)) >= 10 ? Math.round(value) : value.toFixed(1)}%/${unit}`
148}
149hooks/format.ts 168 lines1// Shared by the hooks module and the band: how Token Watch names, orders and
2// spells its figures, so the band, the /token-watch reading and the usage
3// snapshot all say the same thing.
4
5import type { Cap, CacheState, KeepWarm, Limit, Reading, UsagePart, WarmMode } from '../types'
6import { TTL_MS } from './cache'
7
8// Usage windows by kind, in the order they are shown; any other window the
9// API sends comes after them.
10const WINDOWS: Record<string, string> = {
11 five_hour: '5H',
12 seven_day: 'WK',
13 spend_limit: '$$',
14}
15const ORDER = Object.keys(WINDOWS)
16
17// Windows Claude Code does not list today but the API may send, such as a
18// model's own allowance: named by the model when the kind mentions one.
19const MODELS: [RegExp, string][] = [
20 [/fable/i, 'FB'],
21 [/opus/i, 'OP'],
22 [/sonnet/i, 'SN'],
23 [/haiku/i, 'HK'],
24]
25
26export function sorted(list: Limit[]) {
27 const rank = (kind: string) => (ORDER.includes(kind) ? ORDER.indexOf(kind) : ORDER.length)
28 return [...list].sort((a, b) => rank(a.kind) - rank(b.kind))
29}
30
31// The part of the band a usage window belongs to, for the settings panel.
32export function partOf(limit: Limit): UsagePart {
33 return limit.kind === 'five_hour' ? '5H' : limit.kind === 'seven_day' ? 'WK' : 'other'
34}
35
36export function label(limit: Limit) {
37 return WINDOWS[limit.kind] ?? MODELS.find(([pattern]) => pattern.test(limit.kind))?.[1] ?? limit.kind
38}
39
40// Time left until a window resets: "3d 4h", "2h 14m", "9m".
41export function countdown(resetsAt: string | undefined, nowMs: number) {
42 if (!resetsAt || !nowMs) return ''
43 const ms = Date.parse(resetsAt) - nowMs
44 if (Number.isNaN(ms)) return ''
45 if (ms <= 0) return 'now'
46 return duration(ms)
47}
48
49// A span of time, rounded down to the minute: "3d 4h", "2h 14m", "9m".
50export function duration(ms: number) {
51 const minutes = Math.floor(ms / 60_000)
52 const days = Math.floor(minutes / 1_440)
53 const hours = Math.floor((minutes % 1_440) / 60)
54 if (days > 0) return `${days}d ${hours}h`
55 if (hours > 0) return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`
56 return `${Math.max(1, minutes)}m`
57}
58
59export function short(n: number) {
60 // From 999,500 a count rounds to a thousand thousands: "1M", not "1000k".
61 if (n >= 999_500) return `${+(n / 1_000_000).toFixed(1)}M`
62 if (n >= 10_000) return `${Math.round(n / 1_000)}k`
63 if (n >= 1_000) return `${+(n / 1_000).toFixed(1)}k`
64 return String(n)
65}
66
67// The level colour of a percentage: green below 50%, yellow from 50%, red
68// from 80%.
69export function levelColor(percent: number) {
70 if (percent < 50) return '#8fd18f'
71 if (percent < 80) return '#e8c66a'
72 return '#e06c6c'
73}
74
75// A countdown as minutes and seconds, rounded up: "47:12", "4:05", "0:59".
76export function mmss(ms: number) {
77 const seconds = Math.max(0, Math.ceil(ms / 1000))
78 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
79}
80
81// The cache timer's label: the whole TTL while a turn runs (its requests
82// refresh the cache), "--:--" before the first response, "lost" once the
83// countdown has run out, else the time left.
84export function cacheLabel(cache: CacheState, nowMs: number, isWorking: boolean) {
85 if (isWorking) return mmss(TTL_MS[cache.ttl])
86 if (cache.warmUntil === null) return '--:--'
87 if (nowMs >= cache.warmUntil) return 'lost'
88 return mmss(cache.warmUntil - nowMs)
89}
90
91// The TTL and where it comes from: "1h · subscription".
92export function ttlText(cache: CacheState) {
93 return `${cache.ttl} · ${cache.ttlSource}`
94}
95
96// A span as hours, minutes and seconds: "8:00:00", "0:42:05".
97export function hmmss(ms: number) {
98 const seconds = Math.max(0, Math.floor(ms / 1000))
99 const h = Math.floor(seconds / 3600)
100 const m = Math.floor((seconds % 3600) / 60)
101 return `${h}:${String(m).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`
102}
103
104// A span as minutes and seconds under the hour, "00:26", "42:05", and as
105// hours, minutes and seconds from there, "1:02:03".
106export function clockText(ms: number) {
107 const seconds = Math.max(0, Math.floor(ms / 1000))
108 if (seconds >= 3600) return hmmss(ms)
109 return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`
110}
111
112// The band's timer: the time left, "47:12"; the whole TTL while a turn runs;
113// "--:--" when there is no warm cache, before the first response or once the
114// countdown has run out (the band colours both red). The text reply says
115// "lost" for the second (cacheLabel).
116export function bandTimerLabel(cache: CacheState, nowMs: number, isWorking: boolean) {
117 if (isWorking) return mmss(TTL_MS[cache.ttl])
118 if (cache.warmUntil === null || nowMs >= cache.warmUntil) return '--:--'
119 return mmss(cache.warmUntil - nowMs)
120}
121
122// The expanded TTL row's timer: the time left over the whole TTL, "52:50 /
123// 60:00", "--:-- / 60:00" with no warm cache.
124export function timerText(cache: CacheState, nowMs: number, isWorking: boolean) {
125 return `${bandTimerLabel(cache, nowMs, isWorking)} / ${mmss(TTL_MS[cache.ttl])}`
126}
127
128// Keep-warm's caps on the expanded TTL row: "Pings: 0/8 Time: 00:26 / 8:00:00".
129export function capsLine(keepWarm: KeepWarm, cap: Cap, nowMs: number) {
130 const elapsed = keepWarm.startedAt === null ? 0 : nowMs - keepWarm.startedAt
131 return `Pings: ${keepWarm.pings}/${cap.pings} Time: ${clockText(elapsed)} / ${hmmss(cap.ms)}`
132}
133
134// Keep-warm's caps for the text reply, spelled as the band spells them:
135// "pings 3/30 · 42:05 / 2:00:00".
136export function capsText(keepWarm: KeepWarm, cap: Cap, nowMs: number) {
137 const elapsed = keepWarm.startedAt === null ? 0 : nowMs - keepWarm.startedAt
138 return `pings ${keepWarm.pings}/${cap.pings} · ${clockText(elapsed)} / ${hmmss(cap.ms)}`
139}
140
141// What the text reply knows of the cache beside the reading.
142export type CacheLine = { cache: CacheState; keepWarm: KeepWarm; isWorking: boolean; cap: Cap; warmMode?: WarmMode }
143
144// The reading as one line of text, for where the band cannot be drawn:
145// "5H 62% (2h 14m) · WK 31% (3d 4h) · CTX 21% (212k / 1M)", then once there
146// is a countdown, "· TTL 47:12 (1h · subscription)", with keep-warm's caps
147// and the last ping's counts while they apply. Empty before the first reading.
148export function readingLine(reading: Reading | null, limits: Limit[], nowMs: number, cacheLine?: CacheLine) {
149 const parts = sorted(limits).map(limit => {
150 const left = countdown(limit.resetsAt, nowMs)
151 return `${label(limit)} ${Math.round(limit.percentUsed)}%${left ? ` (${left})` : ''}`
152 })
153 if (reading !== null) {
154 const percent = Math.round((reading.total / reading.window) * 100)
155 parts.push(`CTX ${percent}% (${short(reading.total)} / ${short(reading.window)})`)
156 }
157 if (cacheLine && (cacheLine.cache.warmUntil !== null || cacheLine.keepWarm.on)) {
158 const { cache, keepWarm, isWorking, cap, warmMode } = cacheLine
159 const extras = [ttlText(cache)]
160 // A reminder has no caps.
161 if (keepWarm.on) extras.push(warmMode === 'notify' ? 'keep-warm reminder' : `keep-warm ${capsText(keepWarm, cap, nowMs)}`)
162 if (keepWarm.lastPing !== null) {
163 extras.push(`last ping read ${short(keepWarm.lastPing.read)} wrote ${short(keepWarm.lastPing.wrote)}`)
164 }
165 parts.push(`TTL ${cacheLabel(cache, nowMs, isWorking)} (${extras.join(', ')})`)
166 }
167 return parts.join(' · ')
168}hooks/band.tsx 652 lines1// The band itself, drawn as a Client so the whole thing is one pointer target
2// and its two Buttons are its own.
3//
4// Every bar is a row of Boxes that grow in proportion to what they measure, so
5// the layout engine fits it to whatever width the band has, on the terminal
6// and the desktop alike, instead of the module counting characters.
7//
8// One layout and one palette on every surface; only the leaf that paints a
9// coloured piece depends on the surface (see `pieces`). The desktop paints a
10// Box background gaplessly, where any run of glyphs would leave a sliver of
11// remainder per piece in its proportional font, so there each piece is an
12// empty Box 60% as tall as its line. A terminal can only shade whole cells,
13// and only a glyph shape gives it less than a cell of height, so there each
14// piece is a run of lower blocks clipped to its Box. Either way the bars are
15// thinner than their line and stacked bars keep a gap between them.
16//
17// Expanded: one aligned table in a rounded box. A row per usage window (5H, WK
18// and any other window the API sends, such as a model's own allowance), then
19// CTX, each as label, bar, percentage and a dim detail (the time to reset,
20// or the tokens of the window). Every bar starts and ends in the same
21// columns, over a track in one quiet colour for what is still available.
22// On the context bar the reserve past the auto-compact point is a darker
23// shade than the free space before it. Pieces are pure proportion, with no
24// one-cell minimum, so a bar's fill matches the printed percentage. Under
25// CTX, the legend, largest category first, with 2-cell swatches, wrapping
26// onto more lines when it does not fit. Then the TTL row: the prompt
27// cache's time left over its whole TTL, "52:50 / 60:00", and the keep-warm
28// Button, which says what pressing it would do or why it cannot ("Keep
29// Warm", "Let Chill", "Cache Lost", "No Data"; "Remind Me" and "Reminding"
30// in Notify mode); while pings are on, their caps, "Pings: 0/8 Time:
31// 00:26 / 8:00:00", and a Refresh Caps Button (a reminder has no caps); for
32// a minute after a ping or a stop, a dim note. The caps and the note go
33// below 90 columns, and cut at the edge above it.
34// Collapsed with bars ('bars'): one line in the table's language. Each usage
35// window as label, a meter (10 cells, narrower where the line is short)
36// and percentage; then CTX as label, the context bar filling the rest,
37// percentage and "212k / 1M"; then the timer.
38// Counted in cells against the width (see `fit`): the detail, each
39// window's pace and forecast, then the meters, each while the context bar
40// keeps 8 cells; below that the bar takes what is left, so the line never
41// wraps.
42// Collapsed without bars ('plain'): the line's labels, percentages, detail
43// and timer alone.
44//
45// Burn rates (props.pace): in the table, after a window's reset countdown,
46// its pace ("12%/h") and its forecast: how long until it fills, in red
47// ("1h 20m"), or "Safe" in green when it would not fill before it resets; in
48// two more fixed columns so the bars still line up. On a collapsed line, the
49// pace and the forecast after the window's percentage.
50// Each shows in the views the settings panel picks (props.paceHidden,
51// props.forecastHidden).
52//
53// The settings panel can hide parts (props.hidden): the 5H and WK windows,
54// any other window, CTX (with its legend) and TTL (with the timer and
55// keep-warm's buttons). A hidden part is left out of every view; with
56// everything hidden the table says so and the collapsed line is empty, the
57// settings button the hooks module draws beside the band being the way back.
58//
59// The collapsed views' timer: the countdown as a Button, "47:12", whose chip
60// is its own indicator (grey with keep-warm off, green on, red with no warm
61// cache). It reads the whole TTL while a turn runs, and "--:--" before the
62// first response or once the countdown has run out. Pressing it, or the
63// expanded row's button, posts { action: 'keep-warm' }. Between the hooks
64// module's clock readings (every 30 s) the countdown ticks on the Client's
65// frame clock.
66//
67// Every Button is a chip: a Box filled with the indicator's colour around a
68// plain Button, the same on both surfaces.
69//
70// The pointer: a right click posts { action: 'cycle' }, which moves to the
71// next view; a left click does nothing but press a Button; hover brightens
72// the labels.
73
74import type { ClientElements, ClientModule, RenderElement } from 'claude-code'
75
76import type { BandProps, ContextDetails, DetailsSetting, Limit, Part, Reading } from '../types'
77import { NOTE_MS } from './cache'
78import { rateText } from './burn'
79import { bandTimerLabel, capsLine, countdown, duration, label, levelColor, partOf, short, sorted, timerText } from './format'
80
81// Local state: whether the pointer is over the band; the frame clock's
82// milliseconds since the instance started (what the countdown ticks on); and
83// the anchor, the hooks module's clock reading the frame clock was last
84// lined up with and the frame clock then. The display clock is that reading
85// plus the frames since. Kept in the instance's state, so a band drawn again
86// (hidden and shown, or after a survey) starts from its own frame clock.
87type Local = { isHovered: boolean; frameMs: number; anchorNowMs: number; anchorFrameMs: number }
88const INITIAL: Local = { isHovered: false, frameMs: 0, anchorNowMs: 0, anchorFrameMs: 0 }
89
90// The latest props, for the ticker, whose callback outlives the call that
91// started it. A module variable: nothing here needs to survive a reload.
92let latest: BandProps | null = null
93
94// The display clock: the hooks module's reading, plus the frames since the
95// anchor while the anchor is that reading. A new reading counts from itself
96// until the ticker lines the anchor up with it.
97function displayNow(props: BandProps, state: Local) {
98 return props.nowMs + (state.anchorNowMs === props.nowMs ? state.frameMs - state.anchorFrameMs : 0)
99}
100
101// A row of the table, keyed by its window's kind (two kinds may share a label).
102type Row = { key: string; label: string; bar: RenderElement[]; percent: number; detail: string; rate: string; forecast: string }
103
104// A forecast's colour: "Safe" calm, a time until full a warning.
105const forecastColor = (forecast: string) => (forecast === 'Safe' ? SAFE : FORECAST)
106
107// One palette for both views and both surfaces: what is still available (the
108// usage tracks, the context's free space), and the reserve past the
109// auto-compact point a step darker.
110const TRACK = '#3d4250'
111
112// The button chips: grey, green while keep-warm is on, and red for
113// the timer once the cache has gone cold.
114const CHIP_OFF = '#4a5060'
115const CHIP_ON = '#2f7a4f'
116const CHIP_COLD = '#a8433f'
117
118// A chip's margin, inside its Button's label so the whole chip is clickable.
119// The desktop draws a proportional font, where an ordinary space is a few
120// pixels wide, so there an en space (U+2002), about the width of the cell of
121// padding a chip would otherwise have; a terminal cell takes a non-breaking
122// space. Neither is trimmed the way an ordinary space may be.
123const PAD_DESKTOP = ' '
124const PAD_TERMINAL = ' '
125
126// The cells of the expanded row's longest button label, "Cache Lost".
127const WARM_CELLS = 10
128
129// A terminal label centred in so many cells with non-breaking spaces, any odd
130// one on the right.
131function centred(text: string, cells: number) {
132 const gap = Math.max(0, cells - text.length)
133 const left = Math.floor(gap / 2)
134 return PAD_TERMINAL.repeat(left) + text + PAD_TERMINAL.repeat(gap - left)
135}
136
137// The reserve past the auto-compact point, a step darker than the track.
138const RESERVE = '#2e3139'
139
140// What a terminal draws a piece with: the lower half block, shorter than its
141// cell, and one every console font has (the finer ▆ is missing from Consolas
142// and Lucida Console, so the classic Windows console drew boxes).
143const GLYPH = '▄'
144
145// The legend's shorter names for the longer category labels.
146const LEGEND: Record<string, string> = {
147 'system prompt': 'system',
148 'memory files': 'memory',
149 'mcp tools': 'mcp',
150}
151
152// Below this many columns the expanded table leaves out the detail column.
153const DETAIL_MIN_COLUMNS = 50
154
155// The details lines' label column: "Memory" and a cell (and the desktop's
156// slack).
157const DETAIL_LABEL_WIDTH = 7
158
159// Below this many columns the table leaves out the burn rates and forecasts.
160const RATE_MIN_COLUMNS = 70
161
162// A forecast that a window fills before it resets, in the warning colour,
163// and one that it would not, in the calm one.
164const FORECAST = '#e06c6c'
165const SAFE = '#8fd18f'
166
167// Below this many columns the TTL row leaves out keep-warm's caps and notes;
168// short of room above it, the note gives way this many times faster than
169// the caps.
170const CAPS_MIN_COLUMNS = 90
171const NOTE_SHRINK = 100
172
173// Cells of slack in each fixed column: the desktop draws text in a
174// proportional font, where "CTX" or "100%" can be wider than its characters.
175const SLACK = 2
176
177// The percentage column: "100%" and its slack.
178const PERCENT_WIDTH = 6
179
180// The collapsed line: the gap between its cells, the width of a usage
181// window's meter, and the room the context bar keeps before the line gives
182// up its extras.
183const CELL_GAP = 3
184// A usage window's meter: 10 cells, or 6 or 4 where the line is short.
185const METER_WIDTHS = [10, 6, 4]
186const BAR_MIN = 8
187
188// The timer on the collapsed line: its gap and its chip, "47:12" between a
189// cell of margin each side.
190const TIMER_CELLS = CELL_GAP + 1 + 5 + 1
191
192const Band: ClientModule<BandProps, Local> = (props, surface) => {
193 const { Box, Text, Button } = surface.elements
194 latest = props
195 if (surface.state === undefined) {
196 surface.setState(INITIAL)
197 // One ticker per instance, started on the first call: a redraw a second
198 // while there is a countdown to move, none once it has run out.
199 surface.every(1000, () => {
200 const s = surface.state ?? INITIAL
201 if (latest === null || latest.cache.warmUntil === null || latest.isWorking) return
202 if (displayNow(latest, s) >= latest.cache.warmUntil) return
203 const anchored = s.anchorNowMs === latest.nowMs ? s : { ...s, anchorNowMs: latest.nowMs, anchorFrameMs: s.frameMs }
204 surface.setState({ ...anchored, frameMs: anchored.frameMs + 1000 })
205 })
206 }
207 const state = surface.state ?? INITIAL
208 const now = displayNow(props, state)
209 const { reading: current, view, isWorking, cache, keepWarm } = props
210 // The parts the settings panel leaves shown.
211 const shows = (part: Part) => !props.hidden.includes(part)
212 const limits = sorted(props.limits).filter(limit => shows(partOf(limit)))
213 const showCtx = shows('CTX')
214 const showTtl = shows('TTL')
215 const isHovered = state.isHovered
216
217 surface.onPointer(event => {
218 if (event.type === 'up' && event.button === 'right') {
219 surface.post({ action: 'cycle' })
220 } else if (event.type === 'enter' || event.type === 'leave') {
221 // Read the state as it is now: an enter and a leave can both arrive
222 // before the next frame.
223 const hovered = event.type === 'enter'
224 const s = surface.state ?? INITIAL
225 if (s.isHovered !== hovered) surface.setState({ ...s, isHovered: hovered })
226 }
227 })
228
229 const percent = Math.round((current.total / current.window) * 100)
230
231 const draw = pieces(Box, Text, props.surface, surface.columns)
232
233 // A Button inside a Client draws as plain text on the desktop app (measured),
234 // so every Button sits on a filled chip to read as a button, the chip's
235 // colour saying its state. The terminal gets the same chip, its Button
236 // drawn plain (the label alone, without "[ ]"), so both surfaces look alike.
237 // The chip's margins are spaces inside the label, not padding, so the whole
238 // chip is the Button and a click anywhere on it presses it.
239 const pad = props.surface === 'desktop' ? PAD_DESKTOP : PAD_TERMINAL
240 const chip = (key: string, text: string, fill: string, action: string) => (
241 <Box key={`${key}-chip`} flexShrink={0} backgroundColor={fill}>
242 <Button key={key} plain onPress={() => surface.post({ action })}>
243 {`${pad}${text}${pad}`}
244 </Button>
245 </Box>
246 )
247
248 // The buttons are the indicators: the collapsed views' timer is grey with
249 // keep-warm off, green with it on, red with no warm cache (before the first
250 // response, or once the countdown has run out, when the timer reads "--:--").
251 const isUnknown = !isWorking && cache.warmUntil === null
252 const isCold = isUnknown || (!isWorking && now >= cache.warmUntil!)
253 const timerFill = isCold ? CHIP_COLD : keepWarm.on ? CHIP_ON : CHIP_OFF
254
255 // The expanded row's button, in the timer's colour, says what pressing it
256 // would do, or why it cannot: "No Data" before the first response, "Cache
257 // Lost" once the cache has gone cold, "Let Chill" while keep-warm is on,
258 // else "Keep Warm"; in Notify mode "Reminding" and "Remind Me". The terminal centres it in the longest label's cells so
259 // the caps after it stay put; the desktop's proportional font cannot.
260 const isReminder = props.warmMode === 'notify'
261 const warmText = isUnknown
262 ? 'No Data'
263 : isCold
264 ? 'Cache Lost'
265 : keepWarm.on
266 ? isReminder
267 ? 'Reminding'
268 : 'Let Chill'
269 : isReminder
270 ? 'Remind Me'
271 : 'Keep Warm'
272 const warmLabel = props.surface === 'desktop' ? warmText : centred(warmText, WARM_CELLS)
273 const timer = chip('cache-timer', bandTimerLabel(cache, now, isWorking), timerFill, 'keep-warm')
274
275 // A window's pace, and its forecast (how long until it fills, or "Safe" if
276 // it would not before it resets), as the band prints them; empty without a
277 // pace or where the settings hide them.
278 const rateOf = (limit: Limit) => {
279 const p = props.pace.windows[limit.kind]
280 return p && !props.paceHidden.includes(partOf(limit)) ? rateText(p.perHour, p.unit) : ''
281 }
282 const forecastOf = (limit: Limit) => {
283 if (props.forecastHidden.includes(partOf(limit))) return ''
284 const p = props.pace.windows[limit.kind]
285 if (!p) return ''
286 return p.fullAt === null ? 'Safe' : p.fullAt <= props.nowMs ? 'Full' : duration(p.fullAt - props.nowMs)
287 }
288
289 if (view !== 'expanded') {
290 const showBars = view === 'bars'
291 const detail = `${short(current.total)} / ${short(current.window)}`
292 const cells = (text: string) => (text ? text.length + 1 : 0)
293 const ratesCells = limits.reduce((n, limit) => n + cells(rateOf(limit)), 0)
294 const forecastCells = limits.reduce((n, limit) => n + cells(forecastOf(limit)), 0)
295 const { showDetail, meterWidth, showRates, showForecasts } = fit(
296 surface.columns,
297 limits,
298 percent,
299 detail,
300 showBars,
301 showCtx,
302 showTtl,
303 ratesCells,
304 forecastCells,
305 )
306 // With every part hidden the line is empty; the settings button beside
307 // the band (drawn by the hooks module) is the way back.
308 if (limits.length === 0 && !showCtx && !showTtl) return <Box height={1} />
309 return (
310 <Box flexDirection="row" alignItems="center" columnGap={CELL_GAP} paddingX={1}>
311 {limits.map(limit => (
312 <Box key={limit.kind} flexDirection="row" alignItems="center" columnGap={1} flexShrink={0}>
313 <Text dimColor={!isHovered} wrap="truncate">
314 {label(limit)}
315 </Text>
316 {meterWidth > 0 && (
317 <Box width={meterWidth} height={1} flexDirection="row" alignItems="center" flexShrink={0}>
318 {meter(draw, limit.percentUsed)}
319 </Box>
320 )}
321 <Text wrap="truncate" {...warning(limit.percentUsed)}>{`${Math.round(limit.percentUsed)}%`}</Text>
322 {showRates && rateOf(limit) !== '' && (
323 <Text dimColor wrap="truncate">
324 {rateOf(limit)}
325 </Text>
326 )}
327 {showForecasts && forecastOf(limit) !== '' && (
328 <Text wrap="truncate" color={forecastColor(forecastOf(limit))}>
329 {forecastOf(limit)}
330 </Text>
331 )}
332 </Box>
333 ))}
334 {/* With bars the context bar fills the line and the timer ends it;
335 without, the texts follow one another and the timer comes last. */}
336 {showCtx && (
337 <Box flexDirection="row" alignItems="center" columnGap={1} flexGrow={showBars ? 1 : 0}>
338 {/* The label and percentage keep their width; the bar gives way. */}
339 <Box flexShrink={0}>
340 <Text dimColor={!isHovered} wrap="truncate">
341 CTX
342 </Text>
343 </Box>
344 {showBars && (
345 <Box flexDirection="row" flexGrow={1} minWidth={4} height={1} alignItems="center">
346 {bar(draw, current, TRACK, RESERVE)}
347 </Box>
348 )}
349 <Box flexShrink={0}>
350 <Text wrap="truncate" {...warning(percent)}>{`${percent}%`}</Text>
351 </Box>
352 {showDetail && (
353 <Box marginLeft={1} flexShrink={0}>
354 <Text dimColor wrap="truncate">
355 {detail}
356 </Text>
357 </Box>
358 )}
359 </Box>
360 )}
361 {showTtl && timer}
362 </Box>
363 )
364 }
365
366 const rows: Row[] = [
367 ...limits.map(limit => ({
368 key: limit.kind,
369 label: label(limit),
370 bar: meter(draw, limit.percentUsed),
371 percent: limit.percentUsed,
372 // The reset countdowns move by the minute, so they follow the hooks
373 // module's 30-second readings rather than the frame clock.
374 detail: countdown(limit.resetsAt, props.nowMs),
375 rate: rateOf(limit),
376 forecast: forecastOf(limit),
377 })),
378 ...(showCtx
379 ? [
380 {
381 key: 'CTX',
382 label: 'CTX',
383 bar: bar(draw, current, TRACK, RESERVE),
384 percent,
385 detail: `${short(current.total)} / ${short(current.window)}`,
386 rate: '',
387 forecast: '',
388 },
389 ]
390 : []),
391 ]
392 const labelWidth = Math.max(3, ...rows.map(row => row.label.length)) + SLACK
393 const showDetail = surface.columns >= DETAIL_MIN_COLUMNS
394 const detailWidth = Math.max(0, ...rows.map(row => row.detail.length)) + SLACK
395 // The pace and forecast columns, each as wide as its longest entry, so the
396 // bars end in the same column on every row; none without either.
397 const showRates = showDetail && surface.columns >= RATE_MIN_COLUMNS
398 const rateWidth = Math.max(0, ...rows.map(row => row.rate.length))
399 const forecastWidth = Math.max(0, ...rows.map(row => row.forecast.length))
400 const legend = current.slices.filter(s => s.kind === 'used').sort((a, b) => b.tokens - a.tokens)
401 // A legend swatch: a 2-cell bar, drawn the way the bars are.
402 const swatch = (color: string) => (
403 <Box width={2} height={1} flexDirection="row" alignItems="center" flexShrink={0}>
404 {draw(color, { grow: 1 })}
405 </Box>
406 )
407 // While keep-warm is on, its caps follow, then a minute's note (a ping's
408 // counts, why it stopped) when there is one. Both go below CAPS_MIN_COLUMNS.
409 // Caps are the pings': a reminder has none.
410 const showCaps = keepWarm.on && !isReminder && surface.columns >= CAPS_MIN_COLUMNS
411 const note =
412 surface.columns >= CAPS_MIN_COLUMNS && keepWarm.note !== null && now - keepWarm.note.at < NOTE_MS ? keepWarm.note.text : ''
413
414 return (
415 <Box flexDirection="column" borderStyle="round" borderDimColor={!isHovered} paddingX={1}>
416 {rows.length === 0 && !showTtl && (
417 <Text dimColor>
418 {props.limits.length === 0
419 ? 'CTX and TTL are hidden, and there is no plan usage to show. TW Settings shows them again.'
420 : 'All parts are hidden. TW Settings shows them again.'}
421 </Text>
422 )}
423 {rows.map(row => (
424 <Box key={row.key} flexDirection="row" alignItems="center" columnGap={2}>
425 <Box width={labelWidth} flexShrink={0}>
426 <Text dimColor wrap="truncate">
427 {row.label}
428 </Text>
429 </Box>
430 <Box flexDirection="row" flexGrow={1} minWidth={4} height={1} alignItems="center">
431 {row.bar}
432 </Box>
433 <Box width={PERCENT_WIDTH} flexShrink={0} justifyContent="flex-end">
434 <Text wrap="truncate" {...warning(row.percent)}>{`${Math.round(row.percent)}%`}</Text>
435 </Box>
436 {showDetail && (
437 <Box width={detailWidth} flexShrink={0}>
438 <Text dimColor wrap="truncate">
439 {row.detail}
440 </Text>
441 </Box>
442 )}
443 {showRates && rateWidth > 0 && (
444 <Box width={rateWidth + SLACK} flexShrink={0}>
445 <Text dimColor wrap="truncate">
446 {row.rate}
447 </Text>
448 </Box>
449 )}
450 {showRates && forecastWidth > 0 && (
451 <Box width={forecastWidth + SLACK} flexShrink={0}>
452 <Text wrap="truncate" color={forecastColor(row.forecast)}>
453 {row.forecast}
454 </Text>
455 </Box>
456 )}
457 </Box>
458 ))}
459 {showCtx && (
460 <Box flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={3} paddingLeft={labelWidth + 2}>
461 {legend.map(slice => (
462 <Box key={slice.label} flexDirection="row" alignItems="center" columnGap={1} flexShrink={0}>
463 {swatch(slice.color)}
464 <Text dimColor>{`${LEGEND[slice.label] ?? slice.label} ${short(slice.tokens)}`}</Text>
465 </Box>
466 ))}
467 </Box>
468 )}
469 {showCtx &&
470 detailLines(current.details, props.details).map(([title, text]) => (
471 <Box key={title} flexDirection="row" columnGap={1} paddingLeft={labelWidth + 2}>
472 <Box width={DETAIL_LABEL_WIDTH + (props.surface === 'terminal' ? 0 : SLACK)} flexShrink={0}>
473 <Text dimColor>{title}</Text>
474 </Box>
475 <Box flexShrink={1} minWidth={0}>
476 <Text dimColor wrap="truncate">
477 {text}
478 </Text>
479 </Box>
480 </Box>
481 ))}
482 {showTtl && (
483 <Box flexDirection="row" alignItems="center" columnGap={2}>
484 <Box width={labelWidth} flexShrink={0}>
485 <Text dimColor wrap="truncate">
486 TTL
487 </Text>
488 </Box>
489 <Box flexShrink={0}>
490 <Text>{timerText(cache, now, isWorking)}</Text>
491 </Box>
492 {chip('keep-warm', warmLabel, timerFill, 'keep-warm')}
493 {/* The caps cut at the edge, rather than push the row past it. */}
494 {showCaps && (
495 <Box flexShrink={1} minWidth={0} marginLeft={1}>
496 <Text dimColor wrap="truncate">
497 {capsLine(keepWarm, props.cap, now)}
498 </Text>
499 </Box>
500 )}
501 {showCaps && chip('refresh-caps', 'Refresh Caps', CHIP_OFF, 'refresh-caps')}
502 {/* The note gives way first, the caps after it. */}
503 {note !== '' && (
504 <Box flexShrink={NOTE_SHRINK} minWidth={0}>
505 <Text dimColor wrap="truncate">
506 {note}
507 </Text>
508 </Box>
509 )}
510 </Box>
511 )}
512 </Box>
513 )
514}
515
516export default Band
517
518// How a bar draws one piece: a colour over a share of the bar (`grow`) or a
519// fixed number of cells (`width`). No minimum size: the share is exact, so a
520// bar's fill matches the percentage printed beside it.
521type Size = { grow?: number; width?: number }
522type Draw = (color: string, size: Size) => RenderElement
523
524const box = (size: Size) => ({
525 width: size.width ?? 0,
526 flexGrow: size.grow ?? 0,
527 flexShrink: size.width ? 0 : 1,
528 minWidth: 0,
529})
530
531// A piece shorter than its line, for both views. The surface chooses
532// the leaf, and only here: on the desktop an empty Box 60% as tall as its row
533// with a background, which is gapless; in a terminal a Box one cell tall
534// holding a run of GLYPH, which wraps exactly at the Box's width and whose
535// overflow is clipped. (The run is longer than any piece can be, so it fills
536// the Box whatever share it has.)
537function pieces(
538 Box: ClientElements['Box'],
539 Text: ClientElements['Text'],
540 surface: BandProps['surface'],
541 columns: number,
542): Draw {
543 if (surface === 'desktop') {
544 return (color, size) => <Box {...box(size)} height="60%" backgroundColor={color} />
545 }
546
547 return (color, size) => (
548 <Box {...box(size)} height={1} overflow="hidden">
549 <Text color={color} wrap="wrap">
550 {GLYPH.repeat(size.width ?? Math.max(columns, 80) + 2)}
551 </Text>
552 </Box>
553 )
554}
555
556// The context bar: a piece per category, each growing by its tokens from a
557// zero base, so the widths stay proportional at any size. Free space is drawn
558// in `free`, the reserve past the auto-compact point in `reserveColor`.
559function bar(draw: Draw, now: Reading, free: string, reserveColor: string) {
560 // Largest category first, as the legend lists them, then the free space.
561 const used = now.slices.filter(s => s.kind === 'used').sort((a, b) => b.tokens - a.tokens)
562 const segments = [...used, ...now.slices.filter(s => s.kind === 'free')].map(s =>
563 draw(s.kind === 'free' ? free : s.color, { grow: grow(s.tokens, now.window) }),
564 )
565 const reserve = now.compactsAt !== null ? Math.max(0, now.window - now.compactsAt) : 0
566 if (reserve > 0) {
567 segments.push(draw(reserveColor, { grow: grow(reserve, now.window) }))
568 }
569
570 return segments
571}
572
573// A usage window's meter: the used share in its level colour and what is
574// still available as track, both growing from a zero base like the context
575// bar.
576function meter(draw: Draw, percentUsed: number) {
577 const used = Math.max(0, Math.min(100, percentUsed))
578 return [draw(levelColor(used), { grow: used * 100 }), draw(TRACK, { grow: (100 - used) * 100 })]
579}
580
581// Which of the collapsed line's extras fit, kept in this order: the detail,
582// the paces (`ratesCells`, each with its gap), the forecasts
583// (`forecastCells`), then the usage meters, which narrow (10, 6, 4 cells)
584// before they go, the first to, since they only repeat the percentage beside
585// them. Counted in cells, the bar's room being
586// what is left after the padding, labels, percentages, gaps and the timer;
587// the desktop's proportional text measures a little wider, which the bar
588// absorbs. Without the context there is no bar to keep room for: the extras
589// need only fit.
590function fit(
591 columns: number,
592 limits: Limit[],
593 percent: number,
594 detail: string,
595 showBars: boolean,
596 showCtx: boolean,
597 showTtl: boolean,
598 ratesCells: number,
599 forecastCells: number,
600) {
601 const usage = limits.reduce(
602 (n, limit) => n + label(limit).length + 1 + `${Math.round(limit.percentUsed)}%`.length + CELL_GAP,
603 0,
604 )
605 const base = 2 + usage + (showTtl ? TIMER_CELLS : 0)
606 const withCtx = showCtx ? base + 'CTX'.length + 1 + 1 + `${percent}%`.length : base
607 // The room the context bar keeps; none without bars or without the context.
608 const keep = showCtx && showBars ? BAR_MIN : 0
609 const showDetail = showCtx && columns - (withCtx + 2 + detail.length) >= keep
610 let used = showDetail ? withCtx + 2 + detail.length : withCtx
611 const showRates = ratesCells > 0 && columns - used - ratesCells >= keep
612 if (showRates) used += ratesCells
613 // Forecasts only after the paces (when there are paces), in that order.
614 const showForecasts = forecastCells > 0 && (ratesCells === 0 || showRates) && columns - used - forecastCells >= keep
615 if (showForecasts) used += forecastCells
616 // The widest meters that leave the context bar its room; none if even the
617 // narrowest do not.
618 const meterWidth = !showBars
619 ? 0
620 : (METER_WIDTHS.find(width => columns - used - limits.length * (width + 1) >= keep) ?? 0)
621 return { showDetail, meterWidth, showRates, showForecasts }
622}
623
624// The context's details lines the settings turn on and the reading has
625// something for: "MCP slack 8.2k · github 6.1k", "Memory CLAUDE.md 1.2k",
626// "Skills 12 of 40, 10k · agents 3, 67". Each is one line, cut at the band's
627// edge.
628function detailLines(details: ContextDetails | undefined, on: DetailsSetting): [string, string][] {
629 // A reading kept from before a reload may have no details yet.
630 if (details === undefined) return []
631 const list = (items: { name: string; tokens: number }[]) => items.map(i => `${i.name} ${short(i.tokens)}`).join(' \u00b7 ')
632 const lines: [string, string][] = []
633 if (on.mcp && details.mcp.length > 0) lines.push(['MCP', list(details.mcp)])
634 if (on.memory && details.memory.length > 0) lines.push(['Memory', list(details.memory)])
635 if (on.skills && (details.skills !== null || details.agents.count > 0)) {
636 const parts = []
637 if (details.skills !== null) parts.push(`${details.skills.included} of ${details.skills.total}, ${short(details.skills.tokens)}`)
638 if (details.agents.count > 0) parts.push(`agents ${details.agents.count}, ${short(details.agents.tokens)}`)
639 lines.push(['Skills', parts.join(' \u00b7 ')])
640 }
641 return lines
642}
643
644// A share of the window in parts per 10,000, the most flexGrow takes.
645function grow(tokens: number, window: number) {
646 return Math.min(10_000, Math.round((tokens / window) * 10_000 * 100) / 100)
647}
648
649// The percentages in both views: plain text, yellow from 50%, red from 80%.
650function warning(percent: number) {
651 return percent < 50 ? {} : { color: levelColor(percent) }
652}types/index.d.ts 359 lines1// One category of the context window, as the bar and the legend draw it.
2export type Slice = {
3 label: string
4 tokens: number
5 color: string
6 kind: 'used' | 'free' | 'buffer'
7}
8
9// The last reading of the window, broken down the way /context breaks it down.
10export type Reading = {
11 slices: Slice[]
12 total: number
13 window: number
14 compactsAt: number | null
15 // What the context's details lines show: the loaded MCP tools' tokens by
16 // server, the memory files' by name, largest first; the skills included of
17 // all, with their tokens; and the agents, with theirs.
18 details: ContextDetails
19}
20
21export type ContextDetails = {
22 mcp: { name: string; tokens: number }[]
23 memory: { name: string; tokens: number }[]
24 skills: { included: number; total: number; tokens: number } | null
25 agents: { count: number; tokens: number }
26}
27
28// Which of the context's details lines the expanded view shows.
29export type DetailsSetting = { mcp: boolean; memory: boolean; skills: boolean }
30
31// TW Monitor's settings: what each usage window's line shows; what a
32// session shows open (its lines) and closed (its heading's summary), for its
33// context and its cache; the name it goes by; the order of the unpinned;
34// which sessions it lists (all, those with a warm cache, or those that
35// answered within `recentMin` minutes); and whether this session stays on top
36// or follows the pins and Hidden like the rest. A group with all of its
37// pieces off is left out: a usage window, its section, a session's line.
38export type MonitorUsagePiece = 'bar' | 'percent' | 'reset' | 'rate'
39export type MonitorCtxPiece = 'bar' | 'percent' | 'tokens'
40export type MonitorTtlPiece = 'bar' | 'timer' | 'warm'
41export type MonitorState = 'expanded' | 'collapsed'
42export type MonitorLines = { ctx: Record<MonitorCtxPiece, boolean>; ttl: Record<MonitorTtlPiece, boolean> }
43export type MonitorName = 'folder' | 'title' | 'both'
44export type MonitorSort = 'name' | 'context' | 'expiry' | 'activity'
45export type MonitorFilter = 'all' | 'warm' | 'recent'
46export type MonitorCurrent = 'default' | 'top'
47export type MonitorSetting = {
48 usage: Record<UsagePart, Record<MonitorUsagePiece, boolean>>
49 lines: Record<MonitorState, MonitorLines>
50 name: MonitorName
51 sort: MonitorSort
52 filter: MonitorFilter
53 recentMin: number
54 current: MonitorCurrent
55}
56
57// One plan usage window (five_hour, seven_day), as the status line has it.
58export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
59
60// One usage window as the snapshot lists it: the band's label beside the kind.
61export type SnapshotWindow = {
62 kind: string
63 label: string
64 percentUsed: number
65 resetsAt: string | null
66 // The pace over the burn-rate window, in percentage points an hour, and
67 // when the window fills at it (before it resets); null without either.
68 // Added in 1.4.0.
69 ratePerHour: number | null
70 fullAt: string | null
71}
72
73// The band's three views, in the order a right click cycles them: the table,
74// the collapsed line with its bars, the collapsed line without them.
75export type View = 'expanded' | 'bars' | 'plain'
76
77// A part of the band the settings panel can hide: the 5-hour and weekly
78// windows, any other window (a model's allowance, a spend limit), the context
79// and the prompt cache's TTL row.
80export type Part = '5H' | 'WK' | 'other' | 'CTX' | 'TTL'
81
82// The parts that are usage windows, which have a pace.
83export type UsagePart = '5H' | 'WK' | 'other'
84
85// Keep-warm's caps for one TTL as the settings panel sets them: the most
86// pings, and the most hours on.
87export type CapSetting = { pings: number; hours: number }
88
89// The caps by the TTL they apply to; saved across sessions.
90export type CapSettings = Record<Ttl, CapSetting>
91
92// The caps in force: the most pings, and the most time on in milliseconds.
93export type Cap = { pings: number; ms: number }
94
95// The unit a pace is printed in: percentage points an hour, a minute or a day.
96export type BurnUnit = 'h' | 'min' | 'day'
97
98// A usage window's percentage, kept when it moved, and the windows' samples
99// by kind with the reset time they belong to.
100export type Sample = { at: number; percent: number }
101export type History = Record<string, { resetsAt: string | null; samples: Sample[] }>
102
103// One part's pace settings: in which views the pace and its forecast show,
104// the window it is averaged over (minutes) and its unit.
105export type PaceSetting = { show: Record<View, boolean>; forecast: Record<View, boolean>; windowMin: number; unit: BurnUnit }
106
107// What keep-warm does once on: ping, only remind with a notification before
108// the cache expires, or both (remind before the first ping of an idle spell).
109export type WarmMode = 'pings' | 'notify' | 'both'
110
111// The parts that can raise an alert: the usage windows and the context.
112export type AlertPart = UsagePart | 'CTX'
113
114// The settings, as one tree (../hooks/settings.ts): what each part shows in
115// each view, each usage part's pace, keep-warm's caps, mode and reminder,
116// the alerts, the context's details lines, and TW Monitor's settings.
117export type SettingsTree = {
118 show: Record<Part, Record<View, boolean>>
119 pace: Record<UsagePart, PaceSetting>
120 caps: CapSettings
121 // Keep-warm's mode, and how many minutes before it the reminder comes, by TTL.
122 warm: { mode: WarmMode; lead: Record<Ttl, number> }
123 // The level a part alerts at when it crosses it (50 to 95 in steps of 5,
124 // or 99), or null for no alert.
125 alert: Record<AlertPart, number | null>
126 // The context's details lines in the expanded view.
127 details: DetailsSetting
128 monitor: MonitorSetting
129}
130
131// A session's own settings: any leaf of the tree a session may set, set or
132// not. The usage windows' alerts and TW Monitor's settings are every
133// session's alone.
134export type SettingsOverride = {
135 show?: Partial<Record<Part, Partial<Record<View, boolean>>>>
136 pace?: Partial<
137 Record<
138 UsagePart,
139 { show?: Partial<Record<View, boolean>>; forecast?: Partial<Record<View, boolean>>; windowMin?: number; unit?: BurnUnit }
140 >
141 >
142 caps?: Partial<Record<Ttl, Partial<CapSetting>>>
143 warm?: { mode?: WarmMode; lead?: Partial<Record<Ttl, number>> }
144 alert?: { CTX?: number | null }
145 details?: Partial<DetailsSetting>
146}
147
148// What the band shows of the pace: per window kind, its rate, when it fills
149// and the unit its part prints it in.
150export type Pace = {
151 windows: Record<string, { perHour: number; fullAt: number | null; unit: BurnUnit }>
152}
153
154// Which settings the panel shows: this session's own, every session's, or
155// TW Monitor's.
156export type Scope = 'session' | 'global' | 'monitor'
157
158// The prompt cache's time to live, as Claude Code requests it.
159export type Ttl = '5m' | '1h'
160
161// Where the band's TTL comes from: one of Claude Code's controls, in their
162// order of precedence; the plan's default bucket; or a keep-warm ping that
163// found the cache warm more than five minutes after the last response.
164export type TtlSource =
165 | 'FORCE_PROMPT_CACHING_5M'
166 | 'CLAUDE_CODE_PROMPT_CACHE_TTL'
167 | 'promptCacheTtl'
168 | 'ENABLE_PROMPT_CACHING_1H'
169 | 'over plan limit'
170 | 'confirmed'
171 | 'API key or cloud'
172 | 'subscription'
173
174// The TTL controls, read once at session start: three environment variables
175// and the promptCacheTtl setting.
176export type TtlInputs = {
177 force5m: boolean
178 envTtl: Ttl | null
179 settingTtl: Ttl | null
180 enable1h: boolean
181}
182
183// What the band knows of the main conversation's prompt cache.
184export type CacheState = {
185 ttl: Ttl
186 ttlSource: TtlSource
187 // When the last main-thread response ended, in ms since the epoch: the
188 // countdown counts from here. Null before the first response and after
189 // /clear.
190 lastResponseAt: number | null
191 // Until when the cache is believed warm: the last response plus the TTL, or
192 // later after a keep-warm ping. Null with lastResponseAt.
193 warmUntil: number | null
194 // The length of the window that set warmUntil (the TTL, or what a ping
195 // refreshes): what the next ping's lead time is read from.
196 windowMs: number
197 // The last response's prompt in tokens (input, cache read and cache written
198 // together), from the context breakdown: what a warm ping reads most of.
199 // Null before the first breakdown.
200 prefixTokens: number | null
201 // True once a ping read the cache more than five minutes after the last
202 // response: the hour TTL is confirmed.
203 confirmed: boolean
204}
205
206// Keep-warm: on or off for this session (never saved), and what its pings did.
207export type KeepWarm = {
208 on: boolean
209 startedAt: number | null
210 pings: number
211 failures: number
212 lastPing: { at: number; read: number; wrote: number } | null
213 // A line the band shows for a minute: the last ping's counts, a failure, or
214 // why keep-warm stopped.
215 note: { at: number; text: string } | null
216 // What the last reminder was for: in Notify mode the expiry it warned of,
217 // in Both the response the idle spell began with; null before one.
218 notifiedFor: number | null
219}
220
221// The cache as the snapshot lists it.
222export type SnapshotCache = {
223 ttl: Ttl
224 ttlSource: TtlSource
225 expiresAt: string | null
226 warm: boolean
227 keepWarm: {
228 on: boolean
229 // Added in 1.4.0.
230 mode: WarmMode
231 pings: number
232 maxPings: number
233 startedAt: string | null
234 maxMs: number
235 lastPing: { at: string; read: number; wrote: number } | null
236 }
237}
238
239// The usage snapshot written to ~/.claude/token-watch/usage.json after each
240// reading, for Token Watch for VS Code or any other local reader. A window
241// whose resetsAt has passed has started over: show it at 0%. A snapshot
242// whose writtenAt is more than a few minutes old was left by a session that
243// has ended. `cache` was added in 1.2.0; schema 1 only gains fields.
244export type Snapshot = {
245 schema: 1
246 writtenAt: string
247 session: { id: string | null; cwd: string | null }
248 windows: SnapshotWindow[]
249 context: {
250 total: number
251 window: number
252 percent: number
253 compactsAt: number | null
254 categories: Slice[]
255 } | null
256 cache: SnapshotCache
257}
258
259// One session's file under ~/.claude/token-watch/sessions/, which every
260// session's TW Monitor reads: where the session runs (its project root,
261// which names it, and the directory it is in now, which a shell `cd` moves),
262// its context and its prompt cache. A session ended (not cleared or resumed)
263// says when.
264export type SessionSnapshot = {
265 schema: 1
266 writtenAt: string
267 endedAt: string | null
268 session: { id: string | null; cwd: string | null; root: string | null }
269 isWorking: boolean
270 // When its last response ended, for the "recent" filter and the order by
271 // last activity; null before its first.
272 lastActiveAt?: string | null
273 context: { total: number; window: number; percent: number } | null
274 cache: {
275 ttl: Ttl
276 expiresAt: string | null
277 warm: boolean
278 keepWarm: { on: boolean; mode: WarmMode }
279 }
280}
281
282// What the hooks module hands the band's Client.
283export type BandProps = {
284 reading: Reading
285 limits: Limit[]
286 nowMs: number
287 view: View
288 // True while a model turn runs: its requests refresh the cache, so the
289 // countdown shows the whole TTL.
290 isWorking: boolean
291 cache: CacheState
292 keepWarm: KeepWarm
293 surface: 'terminal' | 'desktop' | 'mobile' | 'vscode'
294 // The parts the settings panel hides in this view, and the usage parts
295 // whose pace, and whose forecast, it hides.
296 hidden: Part[]
297 paceHidden: Part[]
298 forecastHidden: Part[]
299 // Keep-warm's caps in force for this session's TTL, and its mode.
300 cap: Cap
301 warmMode: WarmMode
302 // The context's details lines the settings turn on.
303 details: DetailsSetting
304 // The burn rates and forecasts.
305 pace: Pace
306}
307
308declare module 'claude-code' {
309 interface PluginState {
310 'token-watch': {
311 reading: Reading | null
312 limits: Limit[]
313 // When the windows in `limits` were reported after a response, this
314 // session's or another's (through the store); 0 until one was.
315 limitsAt: number
316 nowMs: number
317 isShown: boolean
318 view: View
319 working: boolean
320 ttlInputs: TtlInputs
321 cache: CacheState
322 keepWarm: KeepWarm
323 // When the ping now out was sent, or null with none out: a second ping
324 // waits for it, across a reload too.
325 pingingSince: number | null
326 // The settings in force in this session (../hooks/settings.ts): its
327 // own over the global ones, leaf by leaf; the global settings (saved,
328 // shared by every session); and this session's own (saved under its id).
329 settings: SettingsTree
330 globalSettings: SettingsTree
331 override: SettingsOverride
332 // The usage windows' samples, shared through the store, for the burn
333 // rates.
334 history: History
335 // Which settings the settings panel shows, and its open sections.
336 scope: Scope
337 openSections: string[]
338 // The alert levels this session's context has crossed, and not fallen
339 // back under since.
340 ctxAlerted: number[]
341 // The other live sessions on this device, as TW Monitor last read
342 // their files; and its sections toggled from how they start (open,
343 // save Hidden, which starts closed).
344 sessions: SessionSnapshot[]
345 sessionsClosed: string[]
346 // The sessions' titles from their transcripts, by id (null for one with
347 // none), read while TW Monitor's Name setting uses them.
348 titles: Record<string, string | null>
349 // "Clear all data": how many times it has been pressed since the first
350 // press of its window, and when that was.
351 clearPresses: { count: number; since: number }
352 // The sessions pinned in TW Monitor, and those moved to its Hidden
353 // section, by id, with when each was: shared through the store, so
354 // every session's TW Monitor has them.
355 pinned: Record<string, number>
356 hiddenSessions: Record<string, number>
357 }
358 }
359}