Context, prompt-cache countdown and plan usage above the prompt: four SVG rings on desktop, fill glyphs in the terminal, with expiry toasts. Modified from…

提示框上方一條 context 用量天氣列,加上 prompt cache 倒數與過期提醒。
A context-window weather band above the prompt, plus a prompt-cache countdown with expiry toasts.
改自 Anthropic 官方範例 token-weather:原本右側的「最近 12 輪長條圖」換成快取倒數,桌面版再改畫成四個圓環。非官方版本。
桌面版(以及其他能畫 SVG 的介面):一排四個圓環。
| 圓環 | 中間 | 旁邊 |
|---|---|---|
| ctx | 用量 %,顏色跟天氣(☀ ☁ ☂ ☇ ↯) | 68k/200k |
| cache | 剩餘時間,圓環隨倒數排空 | TTL(1h 快取);過期顯示「過期」和要重寫的 token 數 |
| 5h / 7d | 方案額度已用 %(75% 起黃、90% 起紅) | reset 2h13m:多久後重置。沒有訂閱額度就不畫 |
終端機:一行填充符號(○ ◔ ◑ ◕ ●)。
◔ ctx 34% 68k/200k · ◕ cache 42m · ○ 5h 20% · ◕ 7d 80%
| 區塊 | 意思 |
|---|---|
ctx | context 用量,顏色依天氣:<25% Clear、<50% Cloudy、<75% Showers、<90% Storm、以上 Compact soon |
68k/200k | 已用 token / 模型的 context window(和 status line 同一組數字) |
cache 42m | 距離 prompt cache 過期還剩多久。綠 → 剩不到 40% 壽命轉黃 → 剩 5 分鐘轉紅(5m 快取則剩 1 分鐘);最後一分鐘改成 0:30 秒數 |
cache expired: next message rewrites 62.5k | 已過期:下一則訊息要重寫這麼多 token |
5h 7d | 方案額度已用 %,數字來自同一次用量讀取,不另外發請求 |
$.store),重開後不必等下一則訊息。已經過了的 toast 時間點不會重跳;已重置的額度視窗不會顯示舊數字。FORCE_PROMPT_CACHING_5M → CLAUDE_CODE_PROMPT_CACHE_TTL → 設定 promptCacheTtl → ENABLE_PROMPT_CACHING_1H → 帳號(訂閱且額度內 1h,否則 5m)。
hooks: session.start, session.end, turn.step, turn.complete, ui.render{component=AbovePrompt}
calls: $.clock.after, $.clock.now, $.env.get, $.session.id, $.session.usage, $.settings.read, $.store.get, $.store.set, $.ui.invalidate, $.ui.resolve, $.ui.toast
只讀用量和設定、畫一行 UI、跳 toast,並用 $.store 記住快取時間與額度(Claude Code 設定資料夾下 mod 自己的一個 JSON 檔,只存時間戳、token 數與百分比)。不連網、不執行程式、不送模型請求。
需要 Claude Code v2.1.287 以上。
claude plugin marketplace add youllook/ClaudeMods
claude plugin install token-weather-cache@claude-mods
和官方 token-weather 或其他畫
AbovePrompt的 mod(例如 cache-countdown)會搶同一條位置,擇一安裝。
node tests/token-weather.test.mjs
用假的 $ 模擬一小時:檢查顏色變化、toast 時機與過期顯示,終端機文字版與 SVG 圓環版各驗一次。
Apache-2.0(見 LICENSE),原作 Copyright 2026 Anthropic PBC。 快取倒數邏輯改自 jmac122/cache-countdown(MIT),聲明見 THIRD_PARTY_NOTICES.md。 圓環版面的構想參考 BatuhanCakmakk/wavy-usage(只借設計,沒有使用其程式碼)。
hooks/token-weather.mjs 369 lines1// Copyright 2026 Anthropic PBC
2// SPDX-License-Identifier: Apache-2.0
3//
4// Modified 2026-10-06 by youllook: replaced the per-turn chart with a prompt-cache
5// countdown (turn.step, session.end, timer, toasts). Original: token-weather in
6// anthropics/claude-code-playground. See THIRD_PARTY_NOTICES.md for the MIT notice
7// covering the adapted cache-countdown logic.
8// Modified 2026-10-18 by youllook: remote surfaces draw four SVG rings (context,
9// cache, 5h, 7d), the terminal one line of fill glyphs; ring layout inspired by
10// BatuhanCakmakk/wavy-usage (design only, no code taken).
11//
12// Token Weather: a live forecast of the context window, above the prompt.
13//
14// turn.complete: after each main-loop turn, read the context window's fill
15// from $.session.usage() (the same figures the status line shows).
16// session.start: take a first reading, so the band shows before any turn.
17// turn.step: time each main-loop request and note whether it touched the
18// prompt cache, for the cache countdown.
19// ui.render (AbovePrompt): one line: icon, forecast word, percent, tokens
20// used of the window, and the time left before the prompt cache expires.
21//
22// Cache countdown: TTL rules and the timer pacing are adapted from
23// jmac122/cache-countdown (MIT), itself from davila7/claude-code-templates
24// prompt-cache-control (MIT). The lifetime counts from the start of the last
25// request that read or wrote the cache; any message refreshes it.
26//
27// The host reads on(...) and $.noun.method(...) from source, so they are
28// spelled literally, and helpers that take $ are top-level functions.
29
30// Forecast bands, by percent of the window used.
31const FORECAST = [
32// Single-width text symbols, not emoji: they line up in every terminal font.
33 { upTo: 25, icon: "☀", word: "Clear", color: "yellow" },
34 { upTo: 50, icon: "☁", word: "Cloudy", color: "cyan" },
35 { upTo: 75, icon: "☂", word: "Showers", color: "blue" },
36 { upTo: 90, icon: "☇", word: "Storm", color: "magenta" },
37 { upTo: Infinity, icon: "↯", word: "Compact soon", color: "red" },
38];
39
40const TTL_MS = { "5m": 300_000, "1h": 3_600_000 };
41// Toasts at these seconds left; marks longer than the TTL are skipped.
42const TOAST_AT = [300, 60];
43// Inside this window the countdown shows m:ss and ticks each second.
44const FINAL_MS = 60_000;
45
46// Latest reading: { tokens, window, percent }.
47let reading = null;
48// Last main-loop request that touched the cache: { startedAt, tokens }.
49let lastCache = null;
50let ttl = "5m";
51let timer;
52// Lowest toast mark already shown for the current cache entry.
53let toastLevel = Infinity;
54// Clock time of the last tick or request; ui.render draws from it.
55let nowMs = 0;
56// Plan windows from the last reading: [{ kind, percentUsed, resetsAt }], empty off a subscription.
57let limits = [];
58
59export function register(on) {
60 on("session.start", async ($, e, next) => {
61 const result = await next(e);
62 reading = null;
63 lastCache = null;
64 await decideTtl($);
65 await takeReading($);
66 await restore($);
67 return result;
68 });
69
70 on("session.end", async ($, e, next) => {
71 stopTimer();
72 if (e.reason === "clear") {
73 lastCache = null;
74 }
75 return next(e);
76 });
77
78 on("turn.step", async function* ($, e, next) {
79 if (e.agentId) {
80 return yield* next(e);
81 }
82 const startedAt = await $.clock.now();
83 const r = yield* next(e);
84 const u = r?.usage;
85 if (u) {
86 const read = u.cache_read_input_tokens ?? 0;
87 const write = u.cache_creation_input_tokens ?? 0;
88 if (read + write > 0) {
89 lastCache = { startedAt, tokens: read + write + (u.input_tokens ?? 0) };
90 nowMs = startedAt;
91 toastLevel = Infinity;
92 schedule($, 0);
93 await saveCache($);
94 }
95 }
96 return r;
97 });
98
99 on("turn.complete", async ($, e, next) => {
100 const result = await next(e);
101 if (e.agentId) {
102 return result;
103 }
104 await takeReading($);
105 return result;
106 });
107
108 on("ui.render", { component: "AbovePrompt" }, ($, e, next) => {
109 if (e.hasSurvey || !reading) {
110 return next(e);
111 }
112 const { Box, Text, Svg } = $.ui.resolve(e);
113 // Svg is every remote surface's (desktop, mobile, editor); the terminal gets glyphs.
114 return Svg ? rings(Box, Svg, nowMs) : band(Box, Text, nowMs);
115 });
116}
117
118async function takeReading($) {
119 try {
120 const { context, rateLimits } = await $.session.usage();
121 if (!context || !context.window) {
122 return;
123 }
124 const tokens = context.tokens ?? 0;
125 const percent = Math.round(context.percent ?? (tokens / context.window) * 100);
126 // The session.start reading is 0 before any response; keep the last real one.
127 if (tokens > 0 || !reading) {
128 reading = { tokens, window: context.window, percent };
129 }
130 if (rateLimits?.length) {
131 limits = rateLimits.filter((w) => w.kind === "five_hour" || w.kind === "seven_day");
132 // Account-wide, so any session may show the last known windows until its first response.
133 await $.store.set("limits", limits).catch(() => {});
134 }
135 // No windows before the first response: keep the TTL the restored windows gave.
136 if (ttlByAccount && rateLimits?.length) {
137 ttl = accountTtl(rateLimits);
138 }
139 $.ui.invalidate("ui.render");
140 } catch {
141 // No reading this turn; the band keeps the last one.
142 }
143}
144
145// The countdown and plan windows live in module variables, which a restart or a
146// reload loses: keep the last cache entry per session, and the account's last
147// windows, in $.store, so a resumed session counts on at once.
148async function saveCache($) {
149 try {
150 const id = await $.session.id();
151 const all = (await $.store.get("cache")) ?? {};
152 const cutoff = lastCache.startedAt - TTL_MS["1h"];
153 const kept = Object.fromEntries(Object.entries(all).filter(([, c]) => c.startedAt > cutoff));
154 await $.store.set("cache", { ...kept, [id]: lastCache });
155 } catch {
156 // The countdown still runs; only a restart will lose it.
157 }
158}
159
160async function restore($) {
161 try {
162 nowMs = await $.clock.now();
163 if (!limits.length) {
164 const saved = (await $.store.get("limits")) ?? [];
165 limits = saved.filter((w) => !w.resetsAt || Date.parse(w.resetsAt) > nowMs);
166 }
167 if (ttlByAccount && limits.length) {
168 ttl = accountTtl(limits);
169 }
170 const saved = ((await $.store.get("cache")) ?? {})[await $.session.id()];
171 if (saved && saved.startedAt + TTL_MS[ttl] > nowMs - TTL_MS[ttl]) {
172 lastCache = saved;
173 // Marks already passed count as shown, so a restart raises no stale toast.
174 const left = leftMs(nowMs);
175 toastLevel = Math.min(Infinity, ...TOAST_AT.filter((m) => m * 1000 >= left));
176 schedule($, 0);
177 }
178 $.ui.invalidate("ui.render");
179 } catch {
180 // Nothing kept: the band waits for the next request, as before.
181 }
182}
183
184// The TTL Claude Code asks for, first match wins: FORCE_PROMPT_CACHING_5M,
185// CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting,
186// ENABLE_PROMPT_CACHING_1H, then the account (1h on a subscription within
187// plan usage, 5m otherwise).
188let ttlByAccount = true;
189async function decideTtl($) {
190 const none = () => null;
191 const isOn = (v) => v === "1" || v?.toLowerCase() === "true";
192 const asTtl = (v) => (v === "5m" || v === "1h" ? v : undefined);
193 const force5m = await $.env.get("FORCE_PROMPT_CACHING_5M").catch(none);
194 const ttlVar = await $.env.get("CLAUDE_CODE_PROMPT_CACHE_TTL").catch(none);
195 const enable1h = await $.env.get("ENABLE_PROMPT_CACHING_1H").catch(none);
196 const setting = (await $.settings.read().catch(() => ({}))).promptCacheTtl;
197 const pinned = isOn(force5m) ? "5m" : asTtl(ttlVar) ?? asTtl(setting) ?? (isOn(enable1h) ? "1h" : undefined);
198 ttlByAccount = !pinned;
199 ttl = pinned ?? "5m";
200}
201
202function accountTtl(windows) {
203 const plan = windows.filter((w) => w.kind === "five_hour" || w.kind === "seven_day");
204 if (plan.length === 0) return "5m";
205 return plan.some((w) => w.percentUsed >= 100) ? "5m" : "1h";
206}
207
208function leftMs(now) {
209 return lastCache ? Math.max(0, lastCache.startedAt + TTL_MS[ttl] - now) : 0;
210}
211
212function stopTimer() {
213 timer?.cancel();
214 timer = undefined;
215}
216
217function schedule($, delay) {
218 timer?.cancel();
219 // A tick that fails (module unloading) stops the timer rather than retrying.
220 timer = $.clock.after(delay, () => void tick($).catch(stopTimer));
221}
222
223// Wakes only when the countdown text changes or a toast is due.
224async function tick($) {
225 nowMs = await $.clock.now();
226 const left = leftMs(nowMs);
227 const secs = Math.ceil(left / 1000);
228 const due = TOAST_AT.filter((m) => m * 1000 < TTL_MS[ttl] && secs <= m && m < toastLevel);
229 if (due.length && left > 0) {
230 toastLevel = Math.min(...due);
231 $.ui.toast(`Prompt cache expires in ${clock(left)}: send any message to keep it warm`);
232 }
233 $.ui.invalidate("ui.render");
234 if (left > 0) {
235 schedule($, nextDelay(left));
236 } else {
237 timer = undefined;
238 }
239}
240
241function nextDelay(left) {
242 const period = left > FINAL_MS ? 60_000 : 1_000;
243 let d = ((left - 1) % period) + 1;
244 if (left > FINAL_MS) d = Math.min(d, left - FINAL_MS);
245 for (const m of TOAST_AT) {
246 if (m * 1000 < left) d = Math.min(d, left - m * 1000);
247 }
248 return Math.max(d, 20);
249}
250
251// Terminal: one line of fill glyphs, "◕ ctx 67% 134k/200k · ◕ cache 42m · ◔ 5h 34% · ○ 7d 12%".
252function band(Box, Text, now) {
253 const f = forecastFor(reading.percent);
254 const sep = () => Text({ dimColor: true, children: " · " });
255 const parts = [
256 Text({ color: f.color, bold: true, children: `${pie(reading.percent / 100)} ctx ${reading.percent}%` }),
257 Text({ dimColor: true, children: ` ${short(reading.tokens)}/${short(reading.window)}` }),
258 ];
259 if (lastCache) {
260 const left = leftMs(now);
261 parts.push(sep());
262 if (left > 0) {
263 parts.push(Text({ color: cacheColor(left), bold: left <= FINAL_MS, children: `${pie(left / TTL_MS[ttl])} cache ${countdown(left)}` }));
264 } else {
265 parts.push(Text({ color: "red", children: `○ cache expired: next message rewrites ${short(lastCache.tokens)}` }));
266 }
267 }
268 for (const w of limits) {
269 parts.push(sep());
270 parts.push(Text({ color: limitColor(w.percentUsed), children: `${pie(w.percentUsed / 100)} ${LIMIT_LABEL[w.kind]} ${Math.round(w.percentUsed)}%` }));
271 }
272 return Box({ flexDirection: "row", paddingX: 1, children: parts });
273}
274
275// Fill glyph for 0..1: ○ ◔ ◑ ◕ ●.
276function pie(f) {
277 return "○◔◑◕●"[Math.min(4, Math.max(0, Math.round(f * 4)))];
278}
279
280// Remote surfaces: four rings, each with a label and a sub-line beside it. The cache ring drains as it counts down.
281// Drawn as an image, so the colors are mid-tones that read on light and dark alike.
282const HEX = { yellow: "#D9A13B", cyan: "#3FA7B5", blue: "#4A8FD6", magenta: "#B05FC2", red: "#D9534F", green: "#5D9668" };
283const LIMIT_LABEL = { five_hour: "5h", seven_day: "7d" };
284const SVG_FONT = "system-ui, 'Segoe UI', 'Microsoft JhengHei', sans-serif";
285const RING_W = 118;
286const RING_H = 44;
287
288function rings(Box, Svg, now) {
289 const f = forecastFor(reading.percent);
290 const items = [{ fill: reading.percent / 100, color: HEX[f.color], center: `${reading.percent}%`, label: "ctx", sub: `${short(reading.tokens)}/${short(reading.window)}` }];
291 const alt = [`context ${reading.percent}% (${short(reading.tokens)} of ${short(reading.window)})`];
292 if (lastCache) {
293 const left = leftMs(now);
294 if (left > 0) {
295 items.push({ fill: left / TTL_MS[ttl], color: HEX[cacheColor(left)], center: countdown(left), label: "cache", sub: `${ttl} 快取` });
296 alt.push(`cache ${countdown(left)} left of ${ttl}`);
297 } else {
298 items.push({ fill: 0, color: HEX.red, center: "過期", label: "cache", sub: `重寫 ${short(lastCache.tokens)}` });
299 alt.push(`cache expired, next message rewrites ${short(lastCache.tokens)}`);
300 }
301 }
302 for (const w of limits) {
303 const reset = w.resetsAt ? Date.parse(w.resetsAt) - now : NaN;
304 items.push({
305 fill: w.percentUsed / 100,
306 color: HEX[limitColor(w.percentUsed)],
307 center: `${Math.round(w.percentUsed)}%`,
308 label: LIMIT_LABEL[w.kind],
309 sub: reset > 0 ? `reset ${span(reset)}` : "",
310 });
311 alt.push(`${LIMIT_LABEL[w.kind]} plan ${Math.round(w.percentUsed)}% used`);
312 }
313 const width = RING_W * items.length;
314 const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${RING_H}" viewBox="0 0 ${width} ${RING_H}" font-family="${SVG_FONT}">${items.map((it, i) => ring(it, i * RING_W)).join("")}</svg>`;
315 return Box({ flexDirection: "row", paddingX: 1, children: [Svg({ source, alt: alt.join(", "), width, height: RING_H })] });
316}
317
318function ring({ fill, color, center, label, sub }, x) {
319 const r = 17;
320 const cx = x + 22;
321 const cy = RING_H / 2;
322 const c = 2 * Math.PI * r;
323 const arc = Math.min(1, Math.max(0, fill)) * c;
324 return (
325 `<circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="#8A847E40" stroke-width="4"/>` +
326 (arc > 0 ? `<circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${color}" stroke-width="4" stroke-linecap="round" stroke-dasharray="${arc.toFixed(1)} ${c.toFixed(1)}" transform="rotate(-90 ${cx} ${cy})"/>` : "") +
327 `<text x="${cx}" y="${cy + 4}" text-anchor="middle" font-size="${center.length > 4 ? 10 : 11}" font-weight="700" fill="${color}">${center}</text>` +
328 `<text x="${cx + 26}" y="${cy - 2}" font-size="12" font-weight="600" fill="#8A847E">${label}</text>` +
329 `<text x="${cx + 26}" y="${cy + 13}" font-size="10" fill="#8A847E">${sub}</text>`
330 );
331}
332
333function limitColor(pct) {
334 if (pct >= 90) return "red";
335 return pct >= 75 ? "yellow" : "blue";
336}
337
338function span(ms) {
339 const m = Math.round(ms / 60_000);
340 if (m >= 1440) return `${Math.floor(m / 1440)}d${Math.floor((m % 1440) / 60)}h`;
341 if (m >= 60) return `${Math.floor(m / 60)}h${m % 60}m`;
342 return `${m}m`;
343}
344
345// Green while plenty, yellow below 40% of the lifetime, red from 5 minutes (1 minute on a 5m cache).
346function cacheColor(left) {
347 if (left <= Math.min(300_000, TTL_MS[ttl] * 0.2)) return "red";
348 return left / TTL_MS[ttl] <= 0.4 ? "yellow" : "green";
349}
350
351function countdown(left) {
352 return left > FINAL_MS ? `${Math.ceil(left / 60_000)}m` : clock(left);
353}
354
355function clock(ms) {
356 const total = Math.max(0, Math.ceil(ms / 1000));
357 return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
358}
359
360function forecastFor(percent) {
361 return FORECAST.find((band) => percent < band.upTo) ?? FORECAST[FORECAST.length - 1];
362}
363
364function short(n) {
365 if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1)}M`;
366 if (n >= 1_000) return `${(n / 1_000).toFixed(n % 1_000 === 0 ? 0 : 1)}k`;
367 return String(n);
368}
369