claude-code-cost 0.22.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.
@@ -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.22.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`;
@@ -830,7 +831,7 @@ function renderInsights() {
830
831
  ${viewTabs('insights')}
831
832
  ${scopeIndicator()}
832
833
  <div class="cards-row">
833
- <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()}">
834
835
  <div class="card-label">Active 5h Block</div>
835
836
  <div class="card-value cost">${ab ? formatCost(ab.cost) : '—'}</div>
836
837
  ${ab?.usedPct == null ? '' : meter(ab.usedPct, { label: `${Math.round(ab.usedPct)}%`, ariaLabel: `${Math.round(ab.usedPct)}% of the 5h block used` })}
@@ -2774,6 +2775,7 @@ const SHORTCUT_PAIRS = [
2774
2775
  rows: [
2775
2776
  { keys: ['R'], label: 'Refresh data' },
2776
2777
  { keys: ['T'], label: 'Toggle theme' },
2778
+ { keys: ['Ctrl', 'Shift', 'S'], combo: true, label: 'Plan usage' },
2777
2779
  { keys: ['?'], label: 'Show this help' },
2778
2780
  ],
2779
2781
  },
@@ -2820,6 +2822,235 @@ function buildHelpShortcuts() {
2820
2822
  return cells.join('');
2821
2823
  }
2822
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
+
2823
3054
  function toggleHelpModal() {
2824
3055
  const list = document.getElementById('helpShortcuts');
2825
3056
  if (!list.childElementCount) list.innerHTML = buildHelpShortcuts();
@@ -2905,6 +3136,12 @@ document.addEventListener('keydown', (e) => {
2905
3136
  return;
2906
3137
  }
2907
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
+
2908
3145
  if (e.ctrlKey || e.altKey || e.metaKey) return;
2909
3146
 
2910
3147
  // Shift+P is the project switcher across the hub apps; matches memory and marketplace.
package/public/index.html CHANGED
@@ -116,6 +116,24 @@
116
116
  </div>
117
117
  </div>
118
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
+
119
137
  <div class="modal-overlay" id="projectPickerModal" onclick="if(event.target===this)closeProjectPicker()">
120
138
  <div class="modal-box picker-box">
121
139
  <div class="modal-header">
package/public/style.css CHANGED
@@ -655,6 +655,16 @@ body {
655
655
  border-color: var(--accent-dim);
656
656
  }
657
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
+
658
668
  .stat-card .card-label {
659
669
  font-size: 10px;
660
670
  text-transform: uppercase;
@@ -685,14 +695,17 @@ body {
685
695
  font-weight: 600;
686
696
  }
687
697
 
688
- .stat-card .meter {
698
+ .meter {
689
699
  display: flex;
690
700
  align-items: center;
691
701
  gap: 6px;
702
+ }
703
+
704
+ .stat-card .meter {
692
705
  margin-top: 8px;
693
706
  }
694
707
 
695
- .stat-card .meter-track {
708
+ .meter-track {
696
709
  flex: 1;
697
710
  min-width: 0;
698
711
  height: 3px;
@@ -701,14 +714,14 @@ body {
701
714
  overflow: hidden;
702
715
  }
703
716
 
704
- .stat-card .meter-track > i {
717
+ .meter-track > i {
705
718
  display: block;
706
719
  height: 100%;
707
720
  background: var(--meter, var(--accent));
708
721
  border-radius: 2px;
709
722
  }
710
723
 
711
- .stat-card .meter-value {
724
+ .meter-value {
712
725
  flex: none;
713
726
  font-family: var(--mono);
714
727
  font-size: 10px;
@@ -1379,20 +1392,25 @@ body.light .rb-window {
1379
1392
  color: var(--accent-text);
1380
1393
  }
1381
1394
 
1382
- .modal-close {
1383
- padding: 2px;
1395
+ .modal-close,
1396
+ .modal-icon-btn {
1384
1397
  background: none;
1385
1398
  border: none;
1386
1399
  color: var(--text-muted);
1387
1400
  cursor: pointer;
1388
- font-size: 16px;
1389
- line-height: 1;
1390
1401
  }
1391
1402
 
1392
- .modal-close:hover {
1403
+ .modal-close:hover,
1404
+ .modal-icon-btn:hover {
1393
1405
  color: var(--text-primary);
1394
1406
  }
1395
1407
 
1408
+ .modal-close {
1409
+ padding: 2px;
1410
+ font-size: 16px;
1411
+ line-height: 1;
1412
+ }
1413
+
1396
1414
  .modal-section p {
1397
1415
  margin: 0 0 8px 0;
1398
1416
  font-size: 12px;
@@ -1409,6 +1427,206 @@ body.light .rb-window {
1409
1427
  max-width: 960px;
1410
1428
  }
1411
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
+
1412
1630
  .picker-box {
1413
1631
  max-width: 560px;
1414
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
 
@@ -1463,6 +1464,45 @@ app.get('/api/sessions/:id', withRange(), async (req, res) => {
1463
1464
  }
1464
1465
  });
1465
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
+
1466
1506
  app.get('/api/pricing', async (_req, res) => {
1467
1507
  try {
1468
1508
  const pricing = await fetchPricing();