claude-code-cost 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,10 @@ npx claude-code-cost --open
18
18
 
19
19
  That's it — no hooks, no config. The dashboard reads the JSONL session logs Claude Code already writes to `~/.claude/projects/` and aggregates them server-side. Completely read-only; nothing leaves your machine.
20
20
 
21
+ ### Install as a desktop app
22
+
23
+ The dashboard is a PWA. With the server running, open it in Chrome or Edge and click **Install** in the top bar (or the install icon in the address bar). Safari on macOS: **File → Add to Dock**. The app opens in its own window with a Start menu / Dock entry and right-click shortcuts to Overview and Insights. The server still has to be running; the installed app is a window onto `http://localhost:3543`.
24
+
21
25
  ## Features
22
26
 
23
27
  - **Top-down drill-down** — total → project → session → message; every number is one click from its breakdown
@@ -44,7 +48,7 @@ That's it — no hooks, no config. The dashboard reads the JSONL session logs Cl
44
48
  --open Open browser on start
45
49
  ```
46
50
 
47
- The config dir can also be set via the `CLAUDE_CONFIG_DIR` environment variable.
51
+ The config dir can also be set via the `CLAUDE_CONFIG_DIR` environment variable. With a custom dir only `<dir>/projects` is scanned; the default profile also picks up `~/.config/claude/projects`.
48
52
 
49
53
  ## License
50
54
 
@@ -0,0 +1,184 @@
1
+ 'use strict';
2
+
3
+ // Plan rate limits live behind a control request, not on disk: the statusline payload the cck
4
+ // plugin spies only ever carries five_hour/seven_day/spend_limit, so per-model windows (the
5
+ // "weekly_scoped" rows) are invisible to a file reader. `claude -p` speaks the stream-json control
6
+ // protocol, and its get_usage subtype answers with the same data /usage renders.
7
+ //
8
+ // The call runs no model turn, and total_cost_usd comes back 0. It still spawns a full CLI process
9
+ // and fires that config dir's SessionStart hooks, so callers must cache rather than poll.
10
+
11
+ const { spawn } = require('child_process');
12
+
13
+ // The answer is one HTTPS call plus a scan of every transcript touched in the last seven days.
14
+ const PROBE_TIMEOUT_MS = 60000;
15
+
16
+ function resolveBin() {
17
+ return process.env.CLAUDE_BIN || (process.platform === 'win32' ? 'claude.exe' : 'claude');
18
+ }
19
+
20
+ function probeUsage({ claudeDir } = {}) {
21
+ return new Promise((resolve, reject) => {
22
+ const child = spawn(
23
+ resolveBin(),
24
+ ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose'],
25
+ {
26
+ stdio: ['pipe', 'pipe', 'pipe'],
27
+ windowsHide: true,
28
+ env: {
29
+ ...process.env,
30
+ ...(claudeDir ? { CLAUDE_CONFIG_DIR: claudeDir } : {}),
31
+ },
32
+ },
33
+ );
34
+
35
+ let settled = false;
36
+ let buf = '';
37
+ let stderr = '';
38
+
39
+ const finish = (err, value) => {
40
+ if (settled) return;
41
+ settled = true;
42
+ clearTimeout(timer);
43
+ child.kill();
44
+ if (err) reject(err);
45
+ else resolve(value);
46
+ };
47
+
48
+ const timer = setTimeout(() => finish(new Error('get_usage timed out')), PROBE_TIMEOUT_MS);
49
+
50
+ child.on('error', (err) => finish(err));
51
+ child.stderr.on('data', (d) => {
52
+ stderr = (stderr + d.toString()).slice(-2000);
53
+ });
54
+
55
+ child.stdout.on('data', (d) => {
56
+ buf += d.toString();
57
+ let nl;
58
+ while ((nl = buf.indexOf('\n')) >= 0) {
59
+ const line = buf.slice(0, nl).trim();
60
+ buf = buf.slice(nl + 1);
61
+ if (!line) continue;
62
+ let msg;
63
+ try {
64
+ msg = JSON.parse(line);
65
+ } catch {
66
+ continue;
67
+ }
68
+ if (msg.type !== 'control_response') continue;
69
+ const r = msg.response;
70
+ if (r?.subtype === 'error') {
71
+ finish(new Error(r.error || 'get_usage failed'));
72
+ return;
73
+ }
74
+ finish(null, r?.response ?? null);
75
+ return;
76
+ }
77
+ });
78
+
79
+ child.on('exit', (code) => {
80
+ finish(new Error(`claude exited ${code} before answering${stderr ? `: ${stderr.trim()}` : ''}`));
81
+ });
82
+
83
+ child.stdin.write(
84
+ `${JSON.stringify({
85
+ type: 'control_request',
86
+ request_id: 'cost_usage_1',
87
+ request: { subtype: 'get_usage' },
88
+ })}\n`,
89
+ );
90
+ child.stdin.end();
91
+ });
92
+ }
93
+
94
+ // The response shape is explicitly experimental, so normalize to what the dashboard draws and
95
+ // keep every window the CLI reports rather than naming the buckets this build happens to know.
96
+ //
97
+ // The order here is the render order: the per-model week, which is usually the binding one, then
98
+ // the all-models roll-up, then the session. Sorting by percent instead would reshuffle the rows
99
+ // between reads, so the one you were reading moves as you look.
100
+ const KINDS = [
101
+ ['weekly_scoped', 'Week'],
102
+ ['weekly_all', 'Week · all models'],
103
+ ['weekly_oauth_apps', 'Week · apps'],
104
+ ['session', 'Session'],
105
+ ];
106
+ const KIND_LABELS = Object.fromEntries(KINDS);
107
+ const KIND_RANK = Object.fromEntries(KINDS.map(([kind], i) => [kind, i]));
108
+
109
+ // The CLI reports 'normal' right up to the cap, so a window only ever looks urgent if we say so.
110
+ // The returned names are the dashboard's own pace vocabulary, so the renderer writes `pace-${sev}`
111
+ // with nothing to translate.
112
+ function severityOf(reported, percent) {
113
+ if (percent >= 90 || reported === 'critical') return 'hot';
114
+ if (percent >= 70 || (reported && reported !== 'normal')) return 'warn';
115
+ return 'ok';
116
+ }
117
+
118
+ function usageRow(label, percent, { severity, resetsAt, binding, rank } = {}) {
119
+ return {
120
+ label,
121
+ percent,
122
+ severity: severityOf(severity, percent),
123
+ resetsAt: resetsAt || null,
124
+ binding: binding === true,
125
+ rank: rank ?? KINDS.length,
126
+ };
127
+ }
128
+
129
+ function normalizeUsage(raw) {
130
+ if (!raw) return null;
131
+ const rl = raw.rate_limits;
132
+ const rows = [];
133
+
134
+ if (Array.isArray(rl?.limits)) {
135
+ for (const l of rl.limits) {
136
+ if (typeof l?.percent !== 'number') continue;
137
+ const model = l.scope?.model?.display_name || null;
138
+ const base = KIND_LABELS[l.kind] || l.kind;
139
+ rows.push(
140
+ usageRow(model ? `${base} · ${model}` : base, l.percent, {
141
+ severity: l.severity,
142
+ resetsAt: l.resets_at,
143
+ binding: l.is_active,
144
+ rank: KIND_RANK[l.kind],
145
+ }),
146
+ );
147
+ }
148
+ }
149
+
150
+ // Older builds answer with the named windows only.
151
+ if (!rows.length && rl) {
152
+ for (const [key, label, rank] of [
153
+ ['seven_day_opus', 'Week · Opus', KIND_RANK.weekly_scoped],
154
+ ['seven_day_sonnet', 'Week · Sonnet', KIND_RANK.weekly_scoped],
155
+ ['seven_day', 'Week · all models', KIND_RANK.weekly_all],
156
+ ['five_hour', 'Session', KIND_RANK.session],
157
+ ]) {
158
+ const w = rl[key];
159
+ if (typeof w?.utilization !== 'number') continue;
160
+ rows.push(usageRow(label, w.utilization, { resetsAt: w.resets_at, rank }));
161
+ }
162
+ }
163
+
164
+ const spend = rl?.spend
165
+ ? {
166
+ enabled: rl.spend.enabled === true,
167
+ percent: typeof rl.spend.percent === 'number' ? rl.spend.percent : null,
168
+ severity: severityOf(rl.spend.severity, rl.spend.percent || 0),
169
+ disabledReason: rl.spend.disabled_reason || null,
170
+ }
171
+ : null;
172
+
173
+ return {
174
+ subscription: raw.subscription_type || null,
175
+ windows: rows
176
+ .sort((a, b) => a.rank - b.rank || b.percent - a.percent)
177
+ .map(({ rank, ...row }) => row),
178
+ spend,
179
+ behaviors: raw.behaviors || null,
180
+ fetchedAt: new Date().toISOString(),
181
+ };
182
+ }
183
+
184
+ module.exports = { probeUsage, normalizeUsage };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/app.js CHANGED
@@ -98,6 +98,7 @@ function meter(pct, { label = '', cls = '', ariaLabel = '' } = {}) {
98
98
  function formatDuration(minutes) {
99
99
  if (!minutes || minutes < 1) return '<1m';
100
100
  if (minutes < 60) return `${minutes}m`;
101
+ if (minutes >= 1440) return `${Math.floor(minutes / 1440)}d ${Math.floor((minutes % 1440) / 60)}h`;
101
102
  const h = Math.floor(minutes / 60);
102
103
  const m = minutes % 60;
103
104
  return m > 0 ? `${h}h ${m}m` : `${h}h`;
@@ -284,7 +285,7 @@ function migrateStoredPreset(value) {
284
285
  }
285
286
 
286
287
  // Reads the JSON tagged union and the legacy bare "3" / "today" scalar that predates it: the key is
287
- // a preference, so clearLocalCache() never evicts it and old values outlive any cache clear.
288
+ // a preference, so purgeLegacyLocalCache() never evicts it and old values outlive any cache clear.
288
289
  // Anything unrecognized returns null, which lands on the default preset.
289
290
  function parseStoredRange(raw) {
290
291
  if (!raw) return null;
@@ -444,61 +445,41 @@ function updateUrl() {
444
445
  // #region FETCH
445
446
 
446
447
  const BROWSER_CACHE_TTL = 5 * 60 * 1000; // 5 min
447
- const CACHE_VERSION = 6;
448
+ const MAX_CACHE_ENTRIES = 20;
448
449
  let forceRefresh = false;
449
450
  // Age of the data on screen, for the auto-refresh staleness check. A cache hit carries its own
450
- // timestamp forward, so a reload with a warm cache doesn't look freshly fetched.
451
+ // timestamp forward, so a re-render from cache doesn't look freshly fetched.
451
452
  let dataFetchedAt = 0;
452
453
 
454
+ // In memory on purpose: the server can be restarted against another CLAUDE_CONFIG_DIR (the hub does
455
+ // this on a config-dir switch and reloads the page), and a cache that outlives the page would keep
456
+ // showing the previous dir's data. The server's own 30 s cache absorbs the reload cost.
457
+ const dataCache = new Map();
458
+
453
459
  function getCached(key) {
454
460
  if (forceRefresh) return null;
455
- try {
456
- const raw = localStorage.getItem(`cc-cost:${key}`);
457
- if (!raw) return null;
458
- const { data, ts, v } = JSON.parse(raw);
459
- if (v !== CACHE_VERSION || Date.now() - ts > BROWSER_CACHE_TTL) return null;
460
- dataFetchedAt = Math.max(dataFetchedAt, ts);
461
- return data;
462
- } catch {
461
+ const hit = dataCache.get(key);
462
+ if (!hit) return null;
463
+ if (Date.now() - hit.ts > BROWSER_CACHE_TTL) {
464
+ dataCache.delete(key);
463
465
  return null;
464
466
  }
467
+ dataFetchedAt = Math.max(dataFetchedAt, hit.ts);
468
+ return hit.data;
465
469
  }
466
470
 
467
- function setLocalCache(key, data) {
468
- try {
469
- pruneLocalCache();
470
- localStorage.setItem(`cc-cost:${key}`, JSON.stringify({ data, ts: Date.now(), v: CACHE_VERSION }));
471
- } catch {
472
- /* storage full — ignore */
473
- }
474
- }
475
-
476
- function pruneLocalCache() {
477
- const MAX_ENTRIES = 20;
478
- const entries = [];
479
- for (let i = 0; i < localStorage.length; i++) {
480
- const k = localStorage.key(i);
481
- if (!k.startsWith('cc-cost:')) continue;
482
- // Prefs are not cache entries — they have no ts, so they'd sort oldest-first and be
483
- // evicted ahead of real data while also eating the entry budget.
484
- if (isPrefKey(k)) continue;
485
- try {
486
- const { ts } = JSON.parse(localStorage.getItem(k));
487
- entries.push({ k, ts });
488
- } catch {
489
- entries.push({ k, ts: 0 });
490
- }
491
- }
492
- if (entries.length <= MAX_ENTRIES) return;
493
- entries.sort((a, b) => a.ts - b.ts);
494
- const toRemove = entries.length - MAX_ENTRIES;
495
- for (let i = 0; i < toRemove; i++) localStorage.removeItem(entries[i].k);
471
+ function cacheData(key, data) {
472
+ dataCache.delete(key);
473
+ dataCache.set(key, { data, ts: Date.now() });
474
+ if (dataCache.size > MAX_CACHE_ENTRIES) dataCache.delete(dataCache.keys().next().value);
496
475
  }
497
476
 
498
477
  function isPrefKey(k) {
499
- return k.startsWith('cc-cost:sort:') || k === 'cc-cost:range' || k === 'cc-cost:scope';
478
+ return k.startsWith('cc-cost:sort:') || k === 'cc-cost:range' || k === 'cc-cost:scope' || k === 'cc-cost:view';
500
479
  }
501
- function clearLocalCache() {
480
+
481
+ // Earlier versions persisted API payloads under cc-cost:<url>; drop what they left behind.
482
+ function purgeLegacyLocalCache() {
502
483
  const keys = [];
503
484
  for (let i = 0; i < localStorage.length; i++) {
504
485
  const k = localStorage.key(i);
@@ -516,7 +497,7 @@ async function fetchJSON(url, skipCache) {
516
497
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
517
498
  const data = await res.json();
518
499
  dataFetchedAt = Date.now();
519
- if (!skipCache) setLocalCache(url, data);
500
+ if (!skipCache) cacheData(url, data);
520
501
  return data;
521
502
  }
522
503
 
@@ -850,7 +831,7 @@ function renderInsights() {
850
831
  ${viewTabs('insights')}
851
832
  ${scopeIndicator()}
852
833
  <div class="cards-row">
853
- <div class="stat-card">
834
+ <div class="stat-card clickable" role="button" tabindex="0" title="Show plan usage" onclick="openLimitsModal()" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();openLimitsModal()}">
854
835
  <div class="card-label">Active 5h Block</div>
855
836
  <div class="card-value cost">${ab ? formatCost(ab.cost) : '—'}</div>
856
837
  ${ab?.usedPct == null ? '' : meter(ab.usedPct, { label: `${Math.round(ab.usedPct)}%`, ariaLabel: `${Math.round(ab.usedPct)}% of the 5h block used` })}
@@ -2569,7 +2550,7 @@ async function refreshData() {
2569
2550
  const minWait = new Promise((r) => setTimeout(r, 250));
2570
2551
  try {
2571
2552
  await fetch('/api/refresh', { method: 'POST' });
2572
- clearLocalCache();
2553
+ dataCache.clear();
2573
2554
  forceRefresh = true;
2574
2555
  lastRenderHash = {};
2575
2556
  await loadAndRender(currentView);
@@ -2794,6 +2775,7 @@ const SHORTCUT_PAIRS = [
2794
2775
  rows: [
2795
2776
  { keys: ['R'], label: 'Refresh data' },
2796
2777
  { keys: ['T'], label: 'Toggle theme' },
2778
+ { keys: ['Ctrl', 'Shift', 'S'], combo: true, label: 'Plan usage' },
2797
2779
  { keys: ['?'], label: 'Show this help' },
2798
2780
  ],
2799
2781
  },
@@ -2840,6 +2822,235 @@ function buildHelpShortcuts() {
2840
2822
  return cells.join('');
2841
2823
  }
2842
2824
 
2825
+ // Reached only from inline handlers (the card markup, the modal's buttons, the window tabs), which
2826
+ // the linter cannot see. The aliases are what tell it these are live.
2827
+ window.openLimitsModal = openLimitsModal;
2828
+ window.closeLimitsModal = closeLimitsModal;
2829
+ window.refreshLimits = refreshLimits;
2830
+ window.setBehaviorsWindow = setBehaviorsWindow;
2831
+ window.toggleWindowsInfo = toggleWindowsInfo;
2832
+ window.toggleBehaviorsInfo = toggleBehaviorsInfo;
2833
+
2834
+ // The statusline file on disk only knows five_hour/seven_day; the plan's per-model windows come
2835
+ // from the CLI's get_usage control request, which the server probes on demand.
2836
+ let limitsData = null;
2837
+ let limitsBusy = false;
2838
+ let behaviorsWindow = 'week';
2839
+ let behaviorsInfoOpen = false;
2840
+ let windowsInfoOpen = false;
2841
+
2842
+ const INFO_SVG =
2843
+ '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>';
2844
+
2845
+ // Thresholds read out of the minified CLI that computes these rows, so a release can move them
2846
+ // without warning. The units differ. cache_miss, long_context and high_parallel score single
2847
+ // requests, while subagent_heavy and cron score a whole session and charge all of its cost to the
2848
+ // row.
2849
+ const BEHAVIOR_HELP = {
2850
+ cache_miss: 'Requests that sent more than 100k uncached input tokens.',
2851
+ long_context: 'Requests carrying more than 150k input tokens in total, cached or not.',
2852
+ subagent_heavy:
2853
+ 'Sessions with 3 or more subagent requests, or more than half their cost spent in subagents. The whole session counts.',
2854
+ high_parallel: 'Five-minute stretches with 4 or more sessions running at once.',
2855
+ cron: 'Sessions active across 8 or more clock hours. The whole session counts, and nothing checks whether it was really scheduled.',
2856
+ };
2857
+
2858
+ function openLimitsModal() {
2859
+ document.getElementById('limitsModal').classList.add('visible');
2860
+ if (limitsData) renderLimits();
2861
+ else
2862
+ document.getElementById('limitsBody').innerHTML =
2863
+ '<div class="loading-state"><div class="loading-spinner"></div><span>Asking Claude Code for plan usage...</span></div>';
2864
+ loadLimits(false);
2865
+ }
2866
+
2867
+ function refreshLimits() {
2868
+ loadLimits(true);
2869
+ }
2870
+
2871
+ function loadLimits(force) {
2872
+ if (limitsBusy) return;
2873
+ limitsBusy = true;
2874
+ const btn = document.getElementById('limitsRefresh');
2875
+ btn?.classList.add('spinning');
2876
+
2877
+ fetch(`/api/usage-limits${force ? '?refresh=1' : ''}`)
2878
+ .then((r) => (r.ok ? r.json() : r.json().then((e) => Promise.reject(new Error(e.error || 'unavailable')))))
2879
+ .then((d) => {
2880
+ if (!d) return;
2881
+ limitsData = d;
2882
+ renderLimits();
2883
+ })
2884
+ .catch((err) => {
2885
+ if (limitsData) {
2886
+ showToast(`Refresh failed: ${err.message}`);
2887
+ } else {
2888
+ document.getElementById('limitsBody').innerHTML =
2889
+ `<p class="modal-note">Could not read plan usage: ${esc(err.message)}</p>
2890
+ <p class="modal-note">The dashboard asks the local <code>claude</code> CLI for them. They are unavailable on API-key, Bedrock and Vertex sessions.</p>`;
2891
+ }
2892
+ })
2893
+ .finally(() => {
2894
+ limitsBusy = false;
2895
+ btn?.classList.remove('spinning');
2896
+ });
2897
+ }
2898
+
2899
+ function closeLimitsModal() {
2900
+ document.getElementById('limitsModal').classList.remove('visible');
2901
+ }
2902
+
2903
+ function setBehaviorsWindow(win) {
2904
+ behaviorsWindow = win;
2905
+ redrawBehaviors();
2906
+ }
2907
+
2908
+ function redrawBehaviors() {
2909
+ const host = document.getElementById('limitsBehaviors');
2910
+ if (host) host.innerHTML = renderBehaviors(limitsData?.behaviors);
2911
+ }
2912
+
2913
+ function toggleBehaviorsInfo() {
2914
+ behaviorsInfoOpen = !behaviorsInfoOpen;
2915
+ redrawBehaviors();
2916
+ }
2917
+
2918
+ function toggleWindowsInfo() {
2919
+ windowsInfoOpen = !windowsInfoOpen;
2920
+ renderLimits();
2921
+ }
2922
+
2923
+ function formatUntil(iso) {
2924
+ if (!iso) return '';
2925
+ const mins = Math.round((new Date(iso).getTime() - Date.now()) / 60000);
2926
+ if (!Number.isFinite(mins) || mins <= 0) return 'resetting';
2927
+ return `${formatDuration(mins)} left`;
2928
+ }
2929
+
2930
+ function limitRow(w) {
2931
+ const pct = Math.round(w.percent);
2932
+ return `<div class="limit-row pace-${esc(w.severity || 'ok')}">
2933
+ <div class="limit-head">
2934
+ <span class="limit-label">${esc(w.label)}${w.binding ? '<span class="limit-badge">binding</span>' : ''}</span>
2935
+ <span class="limit-pct">${pct}%</span>
2936
+ </div>
2937
+ ${meter(w.percent, { ariaLabel: `${w.label} ${pct}% used` })}
2938
+ <div class="limit-sub">${esc(formatUntil(w.resetsAt))}</div>
2939
+ </div>`;
2940
+ }
2941
+
2942
+ // Bars run on the absolute 0-100 scale rather than normalized to the row max. These are shares of
2943
+ // total usage, and stretching a 2% skill to a full bar would read as "this is what's burning the
2944
+ // plan". The floor keeps a 1% row visible; a true 0 stays empty so it cannot be mistaken for one.
2945
+ function barList(title, rows, help) {
2946
+ if (!rows?.length) return '';
2947
+ return `<div class="bar-group">
2948
+ <div class="bar-group-title">${esc(title)}</div>
2949
+ ${rows
2950
+ .map((r) => {
2951
+ const name = r.name || r.key;
2952
+ const v = r.pct ?? 0;
2953
+ const hint = help?.[r.key];
2954
+ return `<div class="bar-row${v ? '' : ' zero'}">
2955
+ <span class="bar-name${hint ? ' has-hint' : ''}" title="${esc(hint ? `${name}. ${hint}` : name)}">${esc(name)}</span>
2956
+ ${meter(v ? Math.max(1.5, v) : 0, { ariaLabel: `${name} ${v}%` })}
2957
+ <span class="bar-val">${v}%</span>
2958
+ </div>`;
2959
+ })
2960
+ .join('')}
2961
+ </div>`;
2962
+ }
2963
+
2964
+ // The CLI drops behaviors that cost nothing, but "no session ran long enough to count as cron" is
2965
+ // worth seeing, so the missing keys come back at 0%. Behaviors are a closed set upstream; anything
2966
+ // new it starts reporting still renders, since only absent keys get appended.
2967
+ function withIdleBehaviors(rows = []) {
2968
+ const seen = new Set(rows.map((r) => r.key));
2969
+ const idle = Object.keys(BEHAVIOR_HELP)
2970
+ .filter((key) => !seen.has(key))
2971
+ .map((key) => ({ key, pct: 0 }));
2972
+ return [...rows, ...idle];
2973
+ }
2974
+
2975
+ function renderBehaviors(b) {
2976
+ if (!b) {
2977
+ return `<div class="limits-section">
2978
+ <div class="section-title">What's driving it</div>
2979
+ <p class="modal-note">Claude Code reported no transcript breakdown.</p>
2980
+ </div>`;
2981
+ }
2982
+ const w = b[behaviorsWindow];
2983
+ if (!w) return '';
2984
+ const tab = (key, label) =>
2985
+ `<button class="seg-btn${behaviorsWindow === key ? ' on' : ''}" onclick="setBehaviorsWindow('${escAttrJs(key)}')">${label}</button>`;
2986
+ return `<div class="limits-section">
2987
+ <div class="limits-section-head">
2988
+ <div class="limits-section-label">
2989
+ <div class="section-title">What's driving it</div>
2990
+ <button class="modal-icon-btn${behaviorsInfoOpen ? ' on' : ''}" aria-label="What these percentages mean" aria-expanded="${esc(String(behaviorsInfoOpen))}" title="What these percentages mean" onclick="toggleBehaviorsInfo()">${INFO_SVG}</button>
2991
+ </div>
2992
+ <div class="seg">${tab('day', '24h')}${tab('week', '7d')}</div>
2993
+ </div>
2994
+ <p class="modal-note">${w.request_count} requests across ${w.session_count} sessions &middot; from local transcripts, not the server</p>
2995
+ ${
2996
+ behaviorsInfoOpen
2997
+ ? `<div class="info-note">
2998
+ <p>Share of estimated cost, not of requests. Read from local transcripts.</p>
2999
+ <p>Rows overlap, so they will not total 100%. <code>subagent_heavy</code> and <code>cron</code> charge a whole session's cost to one row. Hover a name for its rule.</p>
3000
+ <p>Agents lists skill-launched work under the skill's name. None of this relates to the plan windows above.</p>
3001
+ </div>`
3002
+ : ''
3003
+ }
3004
+ ${barList('Behaviors', withIdleBehaviors(w.behaviors), BEHAVIOR_HELP)}
3005
+ ${barList('Agents', w.agents)}
3006
+ ${barList('Skills', w.skills)}
3007
+ ${barList('Plugins', w.plugins)}
3008
+ ${barList('MCP servers', w.mcp_servers)}
3009
+ </div>`;
3010
+ }
3011
+
3012
+ function renderLimits() {
3013
+ const d = limitsData;
3014
+ if (!d) return;
3015
+ const spend = d.spend;
3016
+ const info = document.getElementById('limitsWindowsInfo');
3017
+ info.classList.toggle('on', windowsInfoOpen);
3018
+ info.setAttribute('aria-expanded', String(windowsInfoOpen));
3019
+ document.getElementById('limitsBody').innerHTML = `
3020
+ <p class="modal-note">${d.subscription ? `${esc(d.subscription)} plan` : 'plan unknown'} &middot; read ${esc(timeAgo(d.fetchedAt))} &middot; Claude refreshes plan usage at most every 5 min</p>
3021
+ ${
3022
+ windowsInfoOpen
3023
+ ? `<div class="info-note">
3024
+ <p>100% is the cap. Windows count independently, so one request hits several and the bars never add up. <strong>Binding</strong> is the one you run out of first.</p>
3025
+ <p>Claude reports these. The cost estimates in this dashboard do not feed them.</p>
3026
+ </div>`
3027
+ : ''
3028
+ }
3029
+ <div class="limits-section">
3030
+ ${d.windows.length ? d.windows.map(limitRow).join('') : '<p class="modal-note">No plan windows reported.</p>'}
3031
+ </div>
3032
+ ${
3033
+ spend
3034
+ ? `<div class="limits-section">
3035
+ <div class="section-title">Usage credits</div>
3036
+ ${
3037
+ spend.enabled
3038
+ ? limitRow({
3039
+ label: 'Credit spend',
3040
+ percent: spend.percent ?? 0,
3041
+ severity: spend.severity,
3042
+ resetsAt: null,
3043
+ binding: false,
3044
+ })
3045
+ : `<p class="modal-note">Disabled${spend.disabledReason ? ` &middot; ${esc(spend.disabledReason)}` : ''}. Nothing covers you past the plan limits.</p>`
3046
+ }
3047
+ </div>`
3048
+ : ''
3049
+ }
3050
+ <div id="limitsBehaviors">${renderBehaviors(d.behaviors)}</div>
3051
+ `;
3052
+ }
3053
+
2843
3054
  function toggleHelpModal() {
2844
3055
  const list = document.getElementById('helpShortcuts');
2845
3056
  if (!list.childElementCount) list.innerHTML = buildHelpShortcuts();
@@ -2925,6 +3136,12 @@ document.addEventListener('keydown', (e) => {
2925
3136
  return;
2926
3137
  }
2927
3138
 
3139
+ if (e.ctrlKey && e.shiftKey && !e.altKey && !e.metaKey && (e.key === 'S' || e.key === 's')) {
3140
+ e.preventDefault();
3141
+ openLimitsModal();
3142
+ return;
3143
+ }
3144
+
2928
3145
  if (e.ctrlKey || e.altKey || e.metaKey) return;
2929
3146
 
2930
3147
  // Shift+P is the project switcher across the hub apps; matches memory and marketplace.
@@ -3033,7 +3250,7 @@ function isAppActive() {
3033
3250
  async function refreshIfStale() {
3034
3251
  if (refreshing || !isAppActive()) return;
3035
3252
  if (Date.now() - dataFetchedAt < BROWSER_CACHE_TTL) return;
3036
- // No clearLocalCache() unlike refreshData: forceRefresh already bypasses the cache read, and the
3253
+ // No dataCache.clear() unlike refreshData: forceRefresh already bypasses the cache read, and the
3037
3254
  // fresh payloads overwrite their own keys. Views the user isn't on keep their cache.
3038
3255
  refreshing = true;
3039
3256
  forceRefresh = true;
@@ -3074,8 +3291,9 @@ async function refreshIfStale() {
3074
3291
  if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
3075
3292
  fwd(e.key);
3076
3293
  }
3077
- // Its own branch: the Alt+digit case below requires !ctrlKey.
3078
- if (e.ctrlKey && e.altKey && !e.shiftKey && !e.metaKey && e.key.toLowerCase() === 'p') {
3294
+ // Own branch: the Alt+digit case below requires !ctrlKey. The hub owns the Ctrl+Alt+letter
3295
+ // keymap and ignores unbound letters.
3296
+ if (e.ctrlKey && e.altKey && !e.shiftKey && !e.metaKey && /^[a-z]$/i.test(e.key)) {
3079
3297
  fwd(e.key);
3080
3298
  }
3081
3299
  if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey && /^[1-9]$/.test(e.key)) {
@@ -3167,6 +3385,7 @@ document.addEventListener('click', async (e) => {
3167
3385
  });
3168
3386
 
3169
3387
  document.addEventListener('DOMContentLoaded', async () => {
3388
+ purgeLegacyLocalCache();
3170
3389
  const state = getUrlState();
3171
3390
  dateRange = loadDateRange();
3172
3391
  buildRangePresets();
@@ -3225,4 +3444,27 @@ if ('serviceWorker' in navigator) {
3225
3444
  navigator.serviceWorker.register('/sw.js').catch(() => {});
3226
3445
  }
3227
3446
 
3447
+ const installBtn = document.getElementById('installBtn');
3448
+ let deferredInstallPrompt = null;
3449
+
3450
+ function setInstallPrompt(e) {
3451
+ deferredInstallPrompt = e;
3452
+ installBtn.hidden = !e;
3453
+ }
3454
+
3455
+ window.addEventListener('beforeinstallprompt', (e) => {
3456
+ e.preventDefault();
3457
+ setInstallPrompt(e);
3458
+ });
3459
+
3460
+ window.addEventListener('appinstalled', () => setInstallPrompt(null));
3461
+
3462
+ // biome-ignore lint/correctness/noUnusedVariables: called from topbar markup
3463
+ async function promptInstall() {
3464
+ const e = deferredInstallPrompt;
3465
+ if (!e) return;
3466
+ setInstallPrompt(null);
3467
+ await e.prompt();
3468
+ }
3469
+
3228
3470
  // #endregion
Binary file
Binary file
package/public/index.html CHANGED
@@ -85,6 +85,10 @@
85
85
  <button class="topbar-btn" id="themeBtn" title="Toggle theme" onclick="toggleTheme()">
86
86
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" id="themeIcon"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
87
87
  </button>
88
+ <button class="topbar-btn" id="installBtn" title="Install as desktop app" onclick="promptInstall()" hidden>
89
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
90
+ Install
91
+ </button>
88
92
  <button class="topbar-btn" id="infoBtn" title="Help & About (?)" onclick="toggleHelpModal()">
89
93
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><circle cx="12" cy="17" r="0.5" fill="currentColor"/></svg>
90
94
  <kbd>?</kbd>
@@ -112,6 +116,24 @@
112
116
  </div>
113
117
  </div>
114
118
 
119
+ <div class="modal-overlay" id="limitsModal" onclick="if(event.target===this)closeLimitsModal()">
120
+ <div class="modal-box modal-limits">
121
+ <div class="modal-header">
122
+ <div class="modal-title">Plan usage</div>
123
+ <div class="modal-actions">
124
+ <button class="modal-icon-btn" id="limitsWindowsInfo" aria-label="What these percentages mean" aria-expanded="false" title="What these percentages mean" onclick="toggleWindowsInfo()">
125
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
126
+ </button>
127
+ <button class="modal-icon-btn" id="limitsRefresh" aria-label="Refresh plan usage" title="Refresh" onclick="refreshLimits()">
128
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 4v6h-6"></path><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></svg>
129
+ </button>
130
+ <button class="modal-close" aria-label="Close dialog" onclick="closeLimitsModal()">&#10005;</button>
131
+ </div>
132
+ </div>
133
+ <div class="modal-body" id="limitsBody"></div>
134
+ </div>
135
+ </div>
136
+
115
137
  <div class="modal-overlay" id="projectPickerModal" onclick="if(event.target===this)closeProjectPicker()">
116
138
  <div class="modal-box picker-box">
117
139
  <div class="modal-header">
@@ -1,14 +1,21 @@
1
1
  {
2
+ "id": "/",
2
3
  "name": "Claude Code Cost",
3
4
  "short_name": "CC Cost",
4
5
  "description": "Cost dashboard for Claude Code usage",
5
6
  "start_url": "/",
7
+ "scope": "/",
6
8
  "display": "standalone",
7
9
  "theme_color": "#101114",
8
10
  "background_color": "#101114",
9
11
  "icons": [
10
12
  { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
11
13
  { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
14
+ { "src": "/icons/icon-512-maskable.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" },
12
15
  { "src": "/icons/icon-svg.svg", "sizes": "any", "type": "image/svg+xml" }
16
+ ],
17
+ "shortcuts": [
18
+ { "name": "Overview", "url": "/?view=overview" },
19
+ { "name": "Insights", "url": "/?view=insights" }
13
20
  ]
14
21
  }
package/public/style.css CHANGED
@@ -42,6 +42,11 @@
42
42
  padding: 0;
43
43
  }
44
44
 
45
+ [hidden] {
46
+ /* biome-ignore lint/complexity/noImportantStyles: must beat every component's own display */
47
+ display: none !important;
48
+ }
49
+
45
50
  body {
46
51
  font-family: var(--mono);
47
52
  font-size: 13px;
@@ -137,10 +142,6 @@ body {
137
142
  max-width: 220px;
138
143
  }
139
144
 
140
- .scope-chip[hidden] {
141
- display: none;
142
- }
143
-
144
145
  .scope-chip > span {
145
146
  overflow: hidden;
146
147
  text-overflow: ellipsis;
@@ -654,6 +655,16 @@ body {
654
655
  border-color: var(--accent-dim);
655
656
  }
656
657
 
658
+ .stat-card.clickable {
659
+ cursor: pointer;
660
+ }
661
+
662
+ .stat-card.clickable:hover,
663
+ .stat-card.clickable:focus-visible {
664
+ border-color: var(--accent);
665
+ outline: none;
666
+ }
667
+
657
668
  .stat-card .card-label {
658
669
  font-size: 10px;
659
670
  text-transform: uppercase;
@@ -684,14 +695,17 @@ body {
684
695
  font-weight: 600;
685
696
  }
686
697
 
687
- .stat-card .meter {
698
+ .meter {
688
699
  display: flex;
689
700
  align-items: center;
690
701
  gap: 6px;
702
+ }
703
+
704
+ .stat-card .meter {
691
705
  margin-top: 8px;
692
706
  }
693
707
 
694
- .stat-card .meter-track {
708
+ .meter-track {
695
709
  flex: 1;
696
710
  min-width: 0;
697
711
  height: 3px;
@@ -700,14 +714,14 @@ body {
700
714
  overflow: hidden;
701
715
  }
702
716
 
703
- .stat-card .meter-track > i {
717
+ .meter-track > i {
704
718
  display: block;
705
719
  height: 100%;
706
720
  background: var(--meter, var(--accent));
707
721
  border-radius: 2px;
708
722
  }
709
723
 
710
- .stat-card .meter-value {
724
+ .meter-value {
711
725
  flex: none;
712
726
  font-family: var(--mono);
713
727
  font-size: 10px;
@@ -1378,20 +1392,25 @@ body.light .rb-window {
1378
1392
  color: var(--accent-text);
1379
1393
  }
1380
1394
 
1381
- .modal-close {
1382
- padding: 2px;
1395
+ .modal-close,
1396
+ .modal-icon-btn {
1383
1397
  background: none;
1384
1398
  border: none;
1385
1399
  color: var(--text-muted);
1386
1400
  cursor: pointer;
1387
- font-size: 16px;
1388
- line-height: 1;
1389
1401
  }
1390
1402
 
1391
- .modal-close:hover {
1403
+ .modal-close:hover,
1404
+ .modal-icon-btn:hover {
1392
1405
  color: var(--text-primary);
1393
1406
  }
1394
1407
 
1408
+ .modal-close {
1409
+ padding: 2px;
1410
+ font-size: 16px;
1411
+ line-height: 1;
1412
+ }
1413
+
1395
1414
  .modal-section p {
1396
1415
  margin: 0 0 8px 0;
1397
1416
  font-size: 12px;
@@ -1408,6 +1427,206 @@ body.light .rb-window {
1408
1427
  max-width: 960px;
1409
1428
  }
1410
1429
 
1430
+ .modal-box.modal-limits {
1431
+ max-width: 680px;
1432
+ }
1433
+
1434
+ .modal-note {
1435
+ font-size: 11px;
1436
+ color: var(--text-muted);
1437
+ }
1438
+
1439
+ .modal-actions {
1440
+ display: flex;
1441
+ align-items: center;
1442
+ gap: 10px;
1443
+ }
1444
+
1445
+ .modal-icon-btn {
1446
+ display: flex;
1447
+ padding: 3px;
1448
+ }
1449
+
1450
+ .modal-icon-btn.on {
1451
+ color: var(--accent-text);
1452
+ }
1453
+
1454
+ .info-note {
1455
+ margin-bottom: 14px;
1456
+ padding: 10px 12px;
1457
+ border: 1px solid var(--border);
1458
+ border-radius: 6px;
1459
+ background: var(--bg-elevated);
1460
+ }
1461
+
1462
+ .info-note p {
1463
+ margin: 0 0 7px;
1464
+ font-size: 11px;
1465
+ line-height: 1.65;
1466
+ color: var(--text-secondary);
1467
+ }
1468
+
1469
+ .info-note p:last-child {
1470
+ margin-bottom: 0;
1471
+ }
1472
+
1473
+ .info-note code {
1474
+ font-family: var(--mono);
1475
+ font-size: 10px;
1476
+ color: var(--text-primary);
1477
+ }
1478
+
1479
+ .modal-icon-btn.spinning {
1480
+ color: var(--accent);
1481
+ animation: spin 0.9s linear infinite;
1482
+ pointer-events: none;
1483
+ }
1484
+
1485
+ .limits-section {
1486
+ margin-top: 16px;
1487
+ padding-top: 14px;
1488
+ border-top: 1px solid var(--border);
1489
+ }
1490
+
1491
+ .limits-section-head {
1492
+ display: flex;
1493
+ align-items: center;
1494
+ justify-content: space-between;
1495
+ gap: 12px;
1496
+ }
1497
+
1498
+ .limits-section-head .section-title {
1499
+ margin-bottom: 0;
1500
+ }
1501
+
1502
+ .limits-section-label {
1503
+ display: flex;
1504
+ align-items: center;
1505
+ gap: 5px;
1506
+ }
1507
+
1508
+ .limit-row + .limit-row {
1509
+ margin-top: 14px;
1510
+ }
1511
+
1512
+ .limit-head {
1513
+ display: flex;
1514
+ align-items: baseline;
1515
+ justify-content: space-between;
1516
+ gap: 8px;
1517
+ }
1518
+
1519
+ .limit-label {
1520
+ font-size: 12px;
1521
+ color: var(--text-primary);
1522
+ }
1523
+
1524
+ .limit-badge {
1525
+ margin-left: 6px;
1526
+ padding: 1px 5px;
1527
+ border-radius: 3px;
1528
+ background: var(--meter-dim, var(--accent-dim));
1529
+ color: var(--meter, var(--accent-text));
1530
+ font-family: var(--mono);
1531
+ font-size: 9px;
1532
+ text-transform: uppercase;
1533
+ letter-spacing: 0.06em;
1534
+ }
1535
+
1536
+ .limit-pct {
1537
+ font-family: var(--mono);
1538
+ font-size: 13px;
1539
+ font-weight: 600;
1540
+ color: var(--meter, var(--text-primary));
1541
+ }
1542
+
1543
+ .limit-row .meter {
1544
+ margin: 6px 0 4px;
1545
+ }
1546
+
1547
+ .limit-row .meter-track {
1548
+ height: 5px;
1549
+ border-radius: 3px;
1550
+ }
1551
+
1552
+ .limit-sub {
1553
+ font-family: var(--mono);
1554
+ font-size: 10px;
1555
+ color: var(--text-muted);
1556
+ }
1557
+
1558
+ .bar-group {
1559
+ margin-top: 12px;
1560
+ }
1561
+
1562
+ .bar-group-title {
1563
+ font-size: 10px;
1564
+ color: var(--text-tertiary);
1565
+ margin-bottom: 5px;
1566
+ }
1567
+
1568
+ .bar-row {
1569
+ display: grid;
1570
+ grid-template-columns: 130px 1fr 42px;
1571
+ align-items: center;
1572
+ gap: 8px;
1573
+ padding: 2px 0;
1574
+ }
1575
+
1576
+ .bar-name {
1577
+ font-size: 11px;
1578
+ color: var(--text-secondary);
1579
+ overflow: hidden;
1580
+ text-overflow: ellipsis;
1581
+ white-space: nowrap;
1582
+ }
1583
+
1584
+ .bar-row.zero .bar-name,
1585
+ .bar-row.zero .bar-val {
1586
+ color: var(--text-tertiary);
1587
+ }
1588
+
1589
+ .bar-name.has-hint {
1590
+ cursor: help;
1591
+ text-decoration: underline dotted var(--border-strong, var(--border));
1592
+ text-underline-offset: 3px;
1593
+ }
1594
+
1595
+ .bar-row .meter-track {
1596
+ height: 4px;
1597
+ }
1598
+
1599
+ .bar-val {
1600
+ font-family: var(--mono);
1601
+ font-size: 10px;
1602
+ color: var(--text-muted);
1603
+ text-align: right;
1604
+ }
1605
+
1606
+ .seg {
1607
+ display: flex;
1608
+ gap: 2px;
1609
+ padding: 2px;
1610
+ border-radius: 5px;
1611
+ background: var(--bg-elevated);
1612
+ }
1613
+
1614
+ .seg-btn {
1615
+ padding: 3px 9px;
1616
+ border: none;
1617
+ border-radius: 4px;
1618
+ background: none;
1619
+ color: var(--text-muted);
1620
+ font-family: var(--mono);
1621
+ font-size: 10px;
1622
+ cursor: pointer;
1623
+ }
1624
+
1625
+ .seg-btn.on {
1626
+ background: var(--bg-hover);
1627
+ color: var(--text-primary);
1628
+ }
1629
+
1411
1630
  .picker-box {
1412
1631
  max-width: 560px;
1413
1632
  padding: 16px;
package/server.js CHANGED
@@ -8,6 +8,7 @@ const { createReadStream } = require('fs');
8
8
  const { createInterface } = require('readline');
9
9
  const os = require('os');
10
10
  const { createNetGuard } = require('./lib/net-guard');
11
+ const { probeUsage, normalizeUsage } = require('./lib/usage-probe');
11
12
 
12
13
  // #region CLI_ARGS
13
14
 
@@ -21,17 +22,21 @@ function getArg(name) {
21
22
 
22
23
  const PORT = getArg('port') || process.env.PORT || 3543;
23
24
  const claudeDirArg = getArg('dir') || process.env.CLAUDE_CONFIG_DIR || process.env.CLAUDE_DIR;
24
- const CLAUDE_DIR = claudeDirArg
25
- ? claudeDirArg.replace(/^~/, os.homedir())
26
- : path.join(os.homedir(), '.claude');
25
+ const DEFAULT_CLAUDE_DIR = path.join(os.homedir(), '.claude');
26
+ const CLAUDE_DIR = claudeDirArg ? claudeDirArg.replace(/^~/, os.homedir()) : DEFAULT_CLAUDE_DIR;
27
27
 
28
28
  const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
29
- const ALT_PROJECTS_DIR = path.join(os.homedir(), '.config', 'claude', 'projects');
29
+ // XDG-style location some builds used for the default profile only. A custom
30
+ // CLAUDE_CONFIG_DIR holds everything itself, so scanning it there would leak
31
+ // the home profile's sessions into the custom one.
32
+ const ALT_PROJECTS_DIR = path.resolve(CLAUDE_DIR) === path.resolve(DEFAULT_CLAUDE_DIR)
33
+ ? path.join(os.homedir(), '.config', 'claude', 'projects')
34
+ : null;
30
35
 
31
36
  function getProjectsDirs() {
32
37
  const dirs = [];
33
38
  if (fs.existsSync(PROJECTS_DIR)) dirs.push(PROJECTS_DIR);
34
- if (fs.existsSync(ALT_PROJECTS_DIR)) dirs.push(ALT_PROJECTS_DIR);
39
+ if (ALT_PROJECTS_DIR && fs.existsSync(ALT_PROJECTS_DIR)) dirs.push(ALT_PROJECTS_DIR);
35
40
  return dirs;
36
41
  }
37
42
 
@@ -1459,6 +1464,45 @@ app.get('/api/sessions/:id', withRange(), async (req, res) => {
1459
1464
  }
1460
1465
  });
1461
1466
 
1467
+ // Each probe spawns a CLI process and fires the config dir's SessionStart hooks, so we cache the
1468
+ // result and let concurrent callers share one in-flight run.
1469
+ //
1470
+ // The TTL mirrors the CLI's own: it refetches plan utilization at most every 5 minutes and shares
1471
+ // the answer through an on-disk cache, so probing faster re-reads the same numbers. A manual
1472
+ // refresh bypasses this cache but still cannot beat that floor.
1473
+ const USAGE_TTL_MS = 5 * 60 * 1000;
1474
+ let usageCache = null;
1475
+ let usageInFlight = null;
1476
+
1477
+ function loadUsage(force = false) {
1478
+ if (!force && usageCache && Date.now() - usageCache.ts < USAGE_TTL_MS) {
1479
+ return Promise.resolve(usageCache.data);
1480
+ }
1481
+ // A forced call still joins an in-flight probe: two spawns would only race for the same answer.
1482
+ if (usageInFlight) return usageInFlight;
1483
+ usageInFlight = probeUsage({ claudeDir: CLAUDE_DIR })
1484
+ .then((raw) => {
1485
+ const data = normalizeUsage(raw);
1486
+ if (data) usageCache = { data, ts: Date.now() };
1487
+ return data;
1488
+ })
1489
+ .finally(() => {
1490
+ usageInFlight = null;
1491
+ });
1492
+ return usageInFlight;
1493
+ }
1494
+
1495
+ app.get('/api/usage-limits', async (req, res) => {
1496
+ try {
1497
+ const data = await loadUsage(req.query.refresh === '1');
1498
+ if (!data) return res.status(503).json({ error: 'No usage data returned' });
1499
+ res.json(data);
1500
+ } catch (err) {
1501
+ console.error('[API] usage-limits error:', err.message);
1502
+ res.status(503).json({ error: err.message });
1503
+ }
1504
+ });
1505
+
1462
1506
  app.get('/api/pricing', async (_req, res) => {
1463
1507
  try {
1464
1508
  const pricing = await fetchPricing();