claude-code-cost 0.22.0 → 0.23.1

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.1",
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`;
@@ -493,7 +494,11 @@ async function fetchJSON(url, skipCache) {
493
494
  if (cached) return cached;
494
495
  }
495
496
  const res = await fetch(url);
496
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
497
+ if (!res.ok) {
498
+ const err = new Error(`HTTP ${res.status}`);
499
+ err.status = res.status;
500
+ throw err;
501
+ }
497
502
  const data = await res.json();
498
503
  dataFetchedAt = Date.now();
499
504
  if (!skipCache) cacheData(url, data);
@@ -830,7 +835,7 @@ function renderInsights() {
830
835
  ${viewTabs('insights')}
831
836
  ${scopeIndicator()}
832
837
  <div class="cards-row">
833
- <div class="stat-card">
838
+ <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
839
  <div class="card-label">Active 5h Block</div>
835
840
  <div class="card-value cost">${ab ? formatCost(ab.cost) : '—'}</div>
836
841
  ${ab?.usedPct == null ? '' : meter(ab.usedPct, { label: `${Math.round(ab.usedPct)}%`, ariaLabel: `${Math.round(ab.usedPct)}% of the 5h block used` })}
@@ -1111,7 +1116,7 @@ function renderDetail() {
1111
1116
  destroyChart('cumulative');
1112
1117
  destroyChart('tokenBreakdown');
1113
1118
  applyDetailRange(d.messages, detailRangeFor(d));
1114
- initRangeBrush(d.messages);
1119
+ initRangeBrush(d.messages, d.workflows);
1115
1120
  });
1116
1121
  }
1117
1122
 
@@ -1725,6 +1730,7 @@ function rangeBrushHtml(total) {
1725
1730
  <div class="rb-track" tabindex="0" role="slider" aria-label="Visible message range"
1726
1731
  aria-valuemin="1" aria-valuemax="${esc(total)}">
1727
1732
  ${rangeOverviewSvg}
1733
+ <div class="rb-spans"></div>
1728
1734
  <div class="rb-bursts"></div>
1729
1735
  <div class="rb-window">
1730
1736
  <div class="rb-handle rb-handle-left" data-edge="start"></div>
@@ -1739,7 +1745,7 @@ function rangeBrushHtml(total) {
1739
1745
  const rangeOverviewSvg =
1740
1746
  '<svg class="rb-overview" viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><polygon /><polyline /></svg>';
1741
1747
 
1742
- function initRangeBrush(messages) {
1748
+ function initRangeBrush(messages, workflows) {
1743
1749
  const root = document.getElementById('rangeBrush');
1744
1750
  if (!root) return;
1745
1751
  const total = messages.length;
@@ -1756,6 +1762,16 @@ function initRangeBrush(messages) {
1756
1762
 
1757
1763
  drawRangeOverview(q('.rb-overview'), messages);
1758
1764
 
1765
+ const runs = workflows || [];
1766
+ q('.rb-spans').innerHTML = runs
1767
+ .map((w) => {
1768
+ const left = ((w.startIndex - 1) / total) * 100;
1769
+ const width = Math.max(((w.endIndex - w.startIndex + 1) / total) * 100, 0.6);
1770
+ const tip = `${w.name} · ${w.agents} agent${w.agents === 1 ? '' : 's'} · ${formatCost(w.totalCost)}`;
1771
+ return `<span class="rb-span" style="left:${left}%;width:${width}%" title="${esc(tip)}"><i>${esc(w.name)}</i></span>`;
1772
+ })
1773
+ .join('');
1774
+
1759
1775
  const markers = notableEvents(messages);
1760
1776
  const burstsEl = q('.rb-bursts');
1761
1777
  burstsEl.innerHTML = markers
@@ -1766,12 +1782,12 @@ function initRangeBrush(messages) {
1766
1782
  .join('');
1767
1783
  const burstEls = [...burstsEl.children].map((el, k) => ({ el, i: markers[k].i }));
1768
1784
  const counts = [
1769
- ['burst', 'cache burst', ''],
1770
- ['compaction', 'compaction', ' class="compact"'],
1771
- ].flatMap(([kind, label, attr]) => {
1772
- const n = markers.filter((k) => k.kind === kind).length;
1773
- return n ? [`<span${attr}><i></i>${n} ${label}${n === 1 ? '' : 's'}</span>`] : [];
1774
- });
1785
+ [markers.filter((k) => k.kind === 'burst').length, 'cache burst', ''],
1786
+ [markers.filter((k) => k.kind === 'compaction').length, 'compaction', ' class="compact"'],
1787
+ [runs.length, 'workflow', ' class="workflow"'],
1788
+ ]
1789
+ .filter(([n]) => n)
1790
+ .map(([n, label, attr]) => `<span${attr}><i></i>${n} ${label}${n === 1 ? '' : 's'}</span>`);
1775
1791
  if (counts.length) {
1776
1792
  burstCount.hidden = false;
1777
1793
  burstCount.innerHTML = counts.join('<span class="rb-sep">·</span>');
@@ -2616,6 +2632,15 @@ async function loadAndRender(view) {
2616
2632
  } catch (err) {
2617
2633
  if (myNav !== navCounter) return;
2618
2634
  console.error(`Failed to load ${view}:`, err);
2635
+ // The cursor is restored from sessionStorage when the iframe reloads with no query, so a
2636
+ // config-dir switch leaves it pointing at a session the new dir never had. A 404 there is a
2637
+ // stale cursor, not a broken app: drop it and land on the overview.
2638
+ if (err.status === 404 && view === 'detail') {
2639
+ sessionDetailData = null;
2640
+ showToast('Not in this config dir — showing overview');
2641
+ await navigate('overview');
2642
+ return;
2643
+ }
2619
2644
  showToast(`Error: ${err.message}`);
2620
2645
  const viewEl = document.getElementById(`${view}-view`);
2621
2646
  if (viewEl) viewEl.innerHTML = `<div class="loading-state"><span>Failed to load data: ${err.message}</span></div>`;
@@ -2733,6 +2758,20 @@ function initProjectPicker() {
2733
2758
  pickProject(pickerIdx);
2734
2759
  }
2735
2760
  });
2761
+ // Vimium eats Escape inside a text input and only blurs it, so the page never sees the key.
2762
+ // A blur that no click in the picker caused, while the window keeps focus and the input is
2763
+ // still shown, is that Escape.
2764
+ const modal = document.getElementById('projectPickerModal');
2765
+ let pointerDown = false;
2766
+ modal.addEventListener('mousedown', () => {
2767
+ pointerDown = true;
2768
+ });
2769
+ document.addEventListener('mouseup', () => {
2770
+ pointerDown = false;
2771
+ });
2772
+ input.addEventListener('blur', () => {
2773
+ if (!pointerDown && document.hasFocus() && input.checkVisibility()) closeProjectPicker();
2774
+ });
2736
2775
  }
2737
2776
 
2738
2777
  // Each entry pairs a left and a right group onto the same grid rows, so their
@@ -2774,6 +2813,7 @@ const SHORTCUT_PAIRS = [
2774
2813
  rows: [
2775
2814
  { keys: ['R'], label: 'Refresh data' },
2776
2815
  { keys: ['T'], label: 'Toggle theme' },
2816
+ { keys: ['Ctrl', 'Shift', 'S'], combo: true, label: 'Plan usage' },
2777
2817
  { keys: ['?'], label: 'Show this help' },
2778
2818
  ],
2779
2819
  },
@@ -2820,6 +2860,235 @@ function buildHelpShortcuts() {
2820
2860
  return cells.join('');
2821
2861
  }
2822
2862
 
2863
+ // Reached only from inline handlers (the card markup, the modal's buttons, the window tabs), which
2864
+ // the linter cannot see. The aliases are what tell it these are live.
2865
+ window.openLimitsModal = openLimitsModal;
2866
+ window.closeLimitsModal = closeLimitsModal;
2867
+ window.refreshLimits = refreshLimits;
2868
+ window.setBehaviorsWindow = setBehaviorsWindow;
2869
+ window.toggleWindowsInfo = toggleWindowsInfo;
2870
+ window.toggleBehaviorsInfo = toggleBehaviorsInfo;
2871
+
2872
+ // The statusline file on disk only knows five_hour/seven_day; the plan's per-model windows come
2873
+ // from the CLI's get_usage control request, which the server probes on demand.
2874
+ let limitsData = null;
2875
+ let limitsBusy = false;
2876
+ let behaviorsWindow = 'week';
2877
+ let behaviorsInfoOpen = false;
2878
+ let windowsInfoOpen = false;
2879
+
2880
+ const INFO_SVG =
2881
+ '<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>';
2882
+
2883
+ // Thresholds read out of the minified CLI that computes these rows, so a release can move them
2884
+ // without warning. The units differ. cache_miss, long_context and high_parallel score single
2885
+ // requests, while subagent_heavy and cron score a whole session and charge all of its cost to the
2886
+ // row.
2887
+ const BEHAVIOR_HELP = {
2888
+ cache_miss: 'Requests that sent more than 100k uncached input tokens.',
2889
+ long_context: 'Requests carrying more than 150k input tokens in total, cached or not.',
2890
+ subagent_heavy:
2891
+ 'Sessions with 3 or more subagent requests, or more than half their cost spent in subagents. The whole session counts.',
2892
+ high_parallel: 'Five-minute stretches with 4 or more sessions running at once.',
2893
+ cron: 'Sessions active across 8 or more clock hours. The whole session counts, and nothing checks whether it was really scheduled.',
2894
+ };
2895
+
2896
+ function openLimitsModal() {
2897
+ document.getElementById('limitsModal').classList.add('visible');
2898
+ if (limitsData) renderLimits();
2899
+ else
2900
+ document.getElementById('limitsBody').innerHTML =
2901
+ '<div class="loading-state"><div class="loading-spinner"></div><span>Asking Claude Code for plan usage...</span></div>';
2902
+ loadLimits(false);
2903
+ }
2904
+
2905
+ function refreshLimits() {
2906
+ loadLimits(true);
2907
+ }
2908
+
2909
+ function loadLimits(force) {
2910
+ if (limitsBusy) return;
2911
+ limitsBusy = true;
2912
+ const btn = document.getElementById('limitsRefresh');
2913
+ btn?.classList.add('spinning');
2914
+
2915
+ fetch(`/api/usage-limits${force ? '?refresh=1' : ''}`)
2916
+ .then((r) => (r.ok ? r.json() : r.json().then((e) => Promise.reject(new Error(e.error || 'unavailable')))))
2917
+ .then((d) => {
2918
+ if (!d) return;
2919
+ limitsData = d;
2920
+ renderLimits();
2921
+ })
2922
+ .catch((err) => {
2923
+ if (limitsData) {
2924
+ showToast(`Refresh failed: ${err.message}`);
2925
+ } else {
2926
+ document.getElementById('limitsBody').innerHTML =
2927
+ `<p class="modal-note">Could not read plan usage: ${esc(err.message)}</p>
2928
+ <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>`;
2929
+ }
2930
+ })
2931
+ .finally(() => {
2932
+ limitsBusy = false;
2933
+ btn?.classList.remove('spinning');
2934
+ });
2935
+ }
2936
+
2937
+ function closeLimitsModal() {
2938
+ document.getElementById('limitsModal').classList.remove('visible');
2939
+ }
2940
+
2941
+ function setBehaviorsWindow(win) {
2942
+ behaviorsWindow = win;
2943
+ redrawBehaviors();
2944
+ }
2945
+
2946
+ function redrawBehaviors() {
2947
+ const host = document.getElementById('limitsBehaviors');
2948
+ if (host) host.innerHTML = renderBehaviors(limitsData?.behaviors);
2949
+ }
2950
+
2951
+ function toggleBehaviorsInfo() {
2952
+ behaviorsInfoOpen = !behaviorsInfoOpen;
2953
+ redrawBehaviors();
2954
+ }
2955
+
2956
+ function toggleWindowsInfo() {
2957
+ windowsInfoOpen = !windowsInfoOpen;
2958
+ renderLimits();
2959
+ }
2960
+
2961
+ function formatUntil(iso) {
2962
+ if (!iso) return '';
2963
+ const mins = Math.round((new Date(iso).getTime() - Date.now()) / 60000);
2964
+ if (!Number.isFinite(mins) || mins <= 0) return 'resetting';
2965
+ return `${formatDuration(mins)} left`;
2966
+ }
2967
+
2968
+ function limitRow(w) {
2969
+ const pct = Math.round(w.percent);
2970
+ return `<div class="limit-row pace-${esc(w.severity || 'ok')}">
2971
+ <div class="limit-head">
2972
+ <span class="limit-label">${esc(w.label)}${w.binding ? '<span class="limit-badge">binding</span>' : ''}</span>
2973
+ <span class="limit-pct">${pct}%</span>
2974
+ </div>
2975
+ ${meter(w.percent, { ariaLabel: `${w.label} ${pct}% used` })}
2976
+ <div class="limit-sub">${esc(formatUntil(w.resetsAt))}</div>
2977
+ </div>`;
2978
+ }
2979
+
2980
+ // Bars run on the absolute 0-100 scale rather than normalized to the row max. These are shares of
2981
+ // total usage, and stretching a 2% skill to a full bar would read as "this is what's burning the
2982
+ // plan". The floor keeps a 1% row visible; a true 0 stays empty so it cannot be mistaken for one.
2983
+ function barList(title, rows, help) {
2984
+ if (!rows?.length) return '';
2985
+ return `<div class="bar-group">
2986
+ <div class="bar-group-title">${esc(title)}</div>
2987
+ ${rows
2988
+ .map((r) => {
2989
+ const name = r.name || r.key;
2990
+ const v = r.pct ?? 0;
2991
+ const hint = help?.[r.key];
2992
+ return `<div class="bar-row${v ? '' : ' zero'}">
2993
+ <span class="bar-name${hint ? ' has-hint' : ''}" title="${esc(hint ? `${name}. ${hint}` : name)}">${esc(name)}</span>
2994
+ ${meter(v ? Math.max(1.5, v) : 0, { ariaLabel: `${name} ${v}%` })}
2995
+ <span class="bar-val">${v}%</span>
2996
+ </div>`;
2997
+ })
2998
+ .join('')}
2999
+ </div>`;
3000
+ }
3001
+
3002
+ // The CLI drops behaviors that cost nothing, but "no session ran long enough to count as cron" is
3003
+ // worth seeing, so the missing keys come back at 0%. Behaviors are a closed set upstream; anything
3004
+ // new it starts reporting still renders, since only absent keys get appended.
3005
+ function withIdleBehaviors(rows = []) {
3006
+ const seen = new Set(rows.map((r) => r.key));
3007
+ const idle = Object.keys(BEHAVIOR_HELP)
3008
+ .filter((key) => !seen.has(key))
3009
+ .map((key) => ({ key, pct: 0 }));
3010
+ return [...rows, ...idle];
3011
+ }
3012
+
3013
+ function renderBehaviors(b) {
3014
+ if (!b) {
3015
+ return `<div class="limits-section">
3016
+ <div class="section-title">What's driving it</div>
3017
+ <p class="modal-note">Claude Code reported no transcript breakdown.</p>
3018
+ </div>`;
3019
+ }
3020
+ const w = b[behaviorsWindow];
3021
+ if (!w) return '';
3022
+ const tab = (key, label) =>
3023
+ `<button class="seg-btn${behaviorsWindow === key ? ' on' : ''}" onclick="setBehaviorsWindow('${escAttrJs(key)}')">${label}</button>`;
3024
+ return `<div class="limits-section">
3025
+ <div class="limits-section-head">
3026
+ <div class="limits-section-label">
3027
+ <div class="section-title">What's driving it</div>
3028
+ <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>
3029
+ </div>
3030
+ <div class="seg">${tab('day', '24h')}${tab('week', '7d')}</div>
3031
+ </div>
3032
+ <p class="modal-note">${w.request_count} requests across ${w.session_count} sessions &middot; from local transcripts, not the server</p>
3033
+ ${
3034
+ behaviorsInfoOpen
3035
+ ? `<div class="info-note">
3036
+ <p>Share of estimated cost, not of requests. Read from local transcripts.</p>
3037
+ <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>
3038
+ <p>Agents lists skill-launched work under the skill's name. None of this relates to the plan windows above.</p>
3039
+ </div>`
3040
+ : ''
3041
+ }
3042
+ ${barList('Behaviors', withIdleBehaviors(w.behaviors), BEHAVIOR_HELP)}
3043
+ ${barList('Agents', w.agents)}
3044
+ ${barList('Skills', w.skills)}
3045
+ ${barList('Plugins', w.plugins)}
3046
+ ${barList('MCP servers', w.mcp_servers)}
3047
+ </div>`;
3048
+ }
3049
+
3050
+ function renderLimits() {
3051
+ const d = limitsData;
3052
+ if (!d) return;
3053
+ const spend = d.spend;
3054
+ const info = document.getElementById('limitsWindowsInfo');
3055
+ info.classList.toggle('on', windowsInfoOpen);
3056
+ info.setAttribute('aria-expanded', String(windowsInfoOpen));
3057
+ document.getElementById('limitsBody').innerHTML = `
3058
+ <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>
3059
+ ${
3060
+ windowsInfoOpen
3061
+ ? `<div class="info-note">
3062
+ <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>
3063
+ <p>Claude reports these. The cost estimates in this dashboard do not feed them.</p>
3064
+ </div>`
3065
+ : ''
3066
+ }
3067
+ <div class="limits-section">
3068
+ ${d.windows.length ? d.windows.map(limitRow).join('') : '<p class="modal-note">No plan windows reported.</p>'}
3069
+ </div>
3070
+ ${
3071
+ spend
3072
+ ? `<div class="limits-section">
3073
+ <div class="section-title">Usage credits</div>
3074
+ ${
3075
+ spend.enabled
3076
+ ? limitRow({
3077
+ label: 'Credit spend',
3078
+ percent: spend.percent ?? 0,
3079
+ severity: spend.severity,
3080
+ resetsAt: null,
3081
+ binding: false,
3082
+ })
3083
+ : `<p class="modal-note">Disabled${spend.disabledReason ? ` &middot; ${esc(spend.disabledReason)}` : ''}. Nothing covers you past the plan limits.</p>`
3084
+ }
3085
+ </div>`
3086
+ : ''
3087
+ }
3088
+ <div id="limitsBehaviors">${renderBehaviors(d.behaviors)}</div>
3089
+ `;
3090
+ }
3091
+
2823
3092
  function toggleHelpModal() {
2824
3093
  const list = document.getElementById('helpShortcuts');
2825
3094
  if (!list.childElementCount) list.innerHTML = buildHelpShortcuts();
@@ -2905,6 +3174,12 @@ document.addEventListener('keydown', (e) => {
2905
3174
  return;
2906
3175
  }
2907
3176
 
3177
+ if (e.ctrlKey && e.shiftKey && !e.altKey && !e.metaKey && (e.key === 'S' || e.key === 's')) {
3178
+ e.preventDefault();
3179
+ openLimitsModal();
3180
+ return;
3181
+ }
3182
+
2908
3183
  if (e.ctrlKey || e.altKey || e.metaKey) return;
2909
3184
 
2910
3185
  // Shift+P is the project switcher across the hub apps; matches memory and marketplace.
@@ -3046,21 +3321,24 @@ async function refreshIfStale() {
3046
3321
 
3047
3322
  window.__HUB__ = cfg;
3048
3323
 
3324
+ // e.code travels with e.key because macOS composes Option+<key> into a character (Option+P is
3325
+ // 'π'), so the key alone cannot identify the binding. The hub owns the keymap and normalizes;
3326
+ // these tests only decide whether a press is the hub's to handle.
3049
3327
  document.addEventListener('keydown', (e) => {
3050
- const fwd = (key) => {
3328
+ const fwd = () => {
3051
3329
  e.preventDefault();
3052
- hubPost({ type: 'hub:keydown', key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey });
3330
+ hubPost({ type: 'hub:keydown', key: e.key, code: e.code, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey });
3053
3331
  };
3054
3332
  if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
3055
- fwd(e.key);
3333
+ fwd();
3056
3334
  }
3057
3335
  // Own branch: the Alt+digit case below requires !ctrlKey. The hub owns the Ctrl+Alt+letter
3058
3336
  // keymap and ignores unbound letters.
3059
- if (e.ctrlKey && e.altKey && !e.shiftKey && !e.metaKey && /^[a-z]$/i.test(e.key)) {
3060
- fwd(e.key);
3337
+ if (e.ctrlKey && e.altKey && !e.shiftKey && !e.metaKey && (/^[a-z]$/i.test(e.key) || /^Key[A-Z]$/.test(e.code))) {
3338
+ fwd();
3061
3339
  }
3062
- if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey && /^[1-9]$/.test(e.key)) {
3063
- fwd(e.key);
3340
+ if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey && (/^[1-9]$/.test(e.key) || /^Digit[1-9]$/.test(e.code))) {
3341
+ fwd();
3064
3342
  }
3065
3343
  });
3066
3344
  })();
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
@@ -30,6 +30,7 @@
30
30
  --chart-5: #b784f5;
31
31
  --chart-6: #fb7185;
32
32
  --compact: var(--chart-5);
33
+ --workflow: var(--chart-2);
33
34
  }
34
35
 
35
36
  /* #endregion */
@@ -655,6 +656,16 @@ body {
655
656
  border-color: var(--accent-dim);
656
657
  }
657
658
 
659
+ .stat-card.clickable {
660
+ cursor: pointer;
661
+ }
662
+
663
+ .stat-card.clickable:hover,
664
+ .stat-card.clickable:focus-visible {
665
+ border-color: var(--accent);
666
+ outline: none;
667
+ }
668
+
658
669
  .stat-card .card-label {
659
670
  font-size: 10px;
660
671
  text-transform: uppercase;
@@ -685,14 +696,17 @@ body {
685
696
  font-weight: 600;
686
697
  }
687
698
 
688
- .stat-card .meter {
699
+ .meter {
689
700
  display: flex;
690
701
  align-items: center;
691
702
  gap: 6px;
703
+ }
704
+
705
+ .stat-card .meter {
692
706
  margin-top: 8px;
693
707
  }
694
708
 
695
- .stat-card .meter-track {
709
+ .meter-track {
696
710
  flex: 1;
697
711
  min-width: 0;
698
712
  height: 3px;
@@ -701,14 +715,14 @@ body {
701
715
  overflow: hidden;
702
716
  }
703
717
 
704
- .stat-card .meter-track > i {
718
+ .meter-track > i {
705
719
  display: block;
706
720
  height: 100%;
707
721
  background: var(--meter, var(--accent));
708
722
  border-radius: 2px;
709
723
  }
710
724
 
711
- .stat-card .meter-value {
725
+ .meter-value {
712
726
  flex: none;
713
727
  font-family: var(--mono);
714
728
  font-size: 10px;
@@ -829,6 +843,15 @@ body {
829
843
  color: var(--compact);
830
844
  }
831
845
 
846
+ .rb-burst-count .workflow {
847
+ color: var(--workflow);
848
+ }
849
+
850
+ .rb-burst-count .workflow i {
851
+ border-radius: 1px;
852
+ background: var(--workflow);
853
+ }
854
+
832
855
  .rb-burst-count .compact i,
833
856
  .rb-burst.compact::after {
834
857
  border-radius: 1px;
@@ -906,12 +929,38 @@ body {
906
929
  vector-effect: non-scaling-stroke;
907
930
  }
908
931
 
909
- .rb-bursts {
932
+ .rb-bursts,
933
+ .rb-spans {
910
934
  position: absolute;
911
935
  inset: 0;
912
936
  pointer-events: none;
913
937
  }
914
938
 
939
+ .rb-span {
940
+ position: absolute;
941
+ top: 0;
942
+ bottom: 0;
943
+ background: color-mix(in srgb, var(--workflow) 16%, transparent);
944
+ border-left: 1px solid var(--workflow);
945
+ border-right: 1px solid var(--workflow);
946
+ pointer-events: auto;
947
+ overflow: hidden;
948
+ }
949
+
950
+ .rb-span i {
951
+ position: absolute;
952
+ bottom: 2px;
953
+ left: 3px;
954
+ right: 2px;
955
+ font-size: 9px;
956
+ font-style: normal;
957
+ letter-spacing: 0.03em;
958
+ color: var(--workflow);
959
+ white-space: nowrap;
960
+ overflow: hidden;
961
+ text-overflow: ellipsis;
962
+ }
963
+
915
964
  .rb-burst {
916
965
  position: absolute;
917
966
  top: 0;
@@ -1379,20 +1428,25 @@ body.light .rb-window {
1379
1428
  color: var(--accent-text);
1380
1429
  }
1381
1430
 
1382
- .modal-close {
1383
- padding: 2px;
1431
+ .modal-close,
1432
+ .modal-icon-btn {
1384
1433
  background: none;
1385
1434
  border: none;
1386
1435
  color: var(--text-muted);
1387
1436
  cursor: pointer;
1388
- font-size: 16px;
1389
- line-height: 1;
1390
1437
  }
1391
1438
 
1392
- .modal-close:hover {
1439
+ .modal-close:hover,
1440
+ .modal-icon-btn:hover {
1393
1441
  color: var(--text-primary);
1394
1442
  }
1395
1443
 
1444
+ .modal-close {
1445
+ padding: 2px;
1446
+ font-size: 16px;
1447
+ line-height: 1;
1448
+ }
1449
+
1396
1450
  .modal-section p {
1397
1451
  margin: 0 0 8px 0;
1398
1452
  font-size: 12px;
@@ -1409,6 +1463,206 @@ body.light .rb-window {
1409
1463
  max-width: 960px;
1410
1464
  }
1411
1465
 
1466
+ .modal-box.modal-limits {
1467
+ max-width: 680px;
1468
+ }
1469
+
1470
+ .modal-note {
1471
+ font-size: 11px;
1472
+ color: var(--text-muted);
1473
+ }
1474
+
1475
+ .modal-actions {
1476
+ display: flex;
1477
+ align-items: center;
1478
+ gap: 10px;
1479
+ }
1480
+
1481
+ .modal-icon-btn {
1482
+ display: flex;
1483
+ padding: 3px;
1484
+ }
1485
+
1486
+ .modal-icon-btn.on {
1487
+ color: var(--accent-text);
1488
+ }
1489
+
1490
+ .info-note {
1491
+ margin-bottom: 14px;
1492
+ padding: 10px 12px;
1493
+ border: 1px solid var(--border);
1494
+ border-radius: 6px;
1495
+ background: var(--bg-elevated);
1496
+ }
1497
+
1498
+ .info-note p {
1499
+ margin: 0 0 7px;
1500
+ font-size: 11px;
1501
+ line-height: 1.65;
1502
+ color: var(--text-secondary);
1503
+ }
1504
+
1505
+ .info-note p:last-child {
1506
+ margin-bottom: 0;
1507
+ }
1508
+
1509
+ .info-note code {
1510
+ font-family: var(--mono);
1511
+ font-size: 10px;
1512
+ color: var(--text-primary);
1513
+ }
1514
+
1515
+ .modal-icon-btn.spinning {
1516
+ color: var(--accent);
1517
+ animation: spin 0.9s linear infinite;
1518
+ pointer-events: none;
1519
+ }
1520
+
1521
+ .limits-section {
1522
+ margin-top: 16px;
1523
+ padding-top: 14px;
1524
+ border-top: 1px solid var(--border);
1525
+ }
1526
+
1527
+ .limits-section-head {
1528
+ display: flex;
1529
+ align-items: center;
1530
+ justify-content: space-between;
1531
+ gap: 12px;
1532
+ }
1533
+
1534
+ .limits-section-head .section-title {
1535
+ margin-bottom: 0;
1536
+ }
1537
+
1538
+ .limits-section-label {
1539
+ display: flex;
1540
+ align-items: center;
1541
+ gap: 5px;
1542
+ }
1543
+
1544
+ .limit-row + .limit-row {
1545
+ margin-top: 14px;
1546
+ }
1547
+
1548
+ .limit-head {
1549
+ display: flex;
1550
+ align-items: baseline;
1551
+ justify-content: space-between;
1552
+ gap: 8px;
1553
+ }
1554
+
1555
+ .limit-label {
1556
+ font-size: 12px;
1557
+ color: var(--text-primary);
1558
+ }
1559
+
1560
+ .limit-badge {
1561
+ margin-left: 6px;
1562
+ padding: 1px 5px;
1563
+ border-radius: 3px;
1564
+ background: var(--meter-dim, var(--accent-dim));
1565
+ color: var(--meter, var(--accent-text));
1566
+ font-family: var(--mono);
1567
+ font-size: 9px;
1568
+ text-transform: uppercase;
1569
+ letter-spacing: 0.06em;
1570
+ }
1571
+
1572
+ .limit-pct {
1573
+ font-family: var(--mono);
1574
+ font-size: 13px;
1575
+ font-weight: 600;
1576
+ color: var(--meter, var(--text-primary));
1577
+ }
1578
+
1579
+ .limit-row .meter {
1580
+ margin: 6px 0 4px;
1581
+ }
1582
+
1583
+ .limit-row .meter-track {
1584
+ height: 5px;
1585
+ border-radius: 3px;
1586
+ }
1587
+
1588
+ .limit-sub {
1589
+ font-family: var(--mono);
1590
+ font-size: 10px;
1591
+ color: var(--text-muted);
1592
+ }
1593
+
1594
+ .bar-group {
1595
+ margin-top: 12px;
1596
+ }
1597
+
1598
+ .bar-group-title {
1599
+ font-size: 10px;
1600
+ color: var(--text-tertiary);
1601
+ margin-bottom: 5px;
1602
+ }
1603
+
1604
+ .bar-row {
1605
+ display: grid;
1606
+ grid-template-columns: 130px 1fr 42px;
1607
+ align-items: center;
1608
+ gap: 8px;
1609
+ padding: 2px 0;
1610
+ }
1611
+
1612
+ .bar-name {
1613
+ font-size: 11px;
1614
+ color: var(--text-secondary);
1615
+ overflow: hidden;
1616
+ text-overflow: ellipsis;
1617
+ white-space: nowrap;
1618
+ }
1619
+
1620
+ .bar-row.zero .bar-name,
1621
+ .bar-row.zero .bar-val {
1622
+ color: var(--text-tertiary);
1623
+ }
1624
+
1625
+ .bar-name.has-hint {
1626
+ cursor: help;
1627
+ text-decoration: underline dotted var(--border-strong, var(--border));
1628
+ text-underline-offset: 3px;
1629
+ }
1630
+
1631
+ .bar-row .meter-track {
1632
+ height: 4px;
1633
+ }
1634
+
1635
+ .bar-val {
1636
+ font-family: var(--mono);
1637
+ font-size: 10px;
1638
+ color: var(--text-muted);
1639
+ text-align: right;
1640
+ }
1641
+
1642
+ .seg {
1643
+ display: flex;
1644
+ gap: 2px;
1645
+ padding: 2px;
1646
+ border-radius: 5px;
1647
+ background: var(--bg-elevated);
1648
+ }
1649
+
1650
+ .seg-btn {
1651
+ padding: 3px 9px;
1652
+ border: none;
1653
+ border-radius: 4px;
1654
+ background: none;
1655
+ color: var(--text-muted);
1656
+ font-family: var(--mono);
1657
+ font-size: 10px;
1658
+ cursor: pointer;
1659
+ }
1660
+
1661
+ .seg-btn.on {
1662
+ background: var(--bg-hover);
1663
+ color: var(--text-primary);
1664
+ }
1665
+
1412
1666
  .picker-box {
1413
1667
  max-width: 560px;
1414
1668
  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
 
@@ -432,7 +433,10 @@ function collectAgents(dir, workflowId, out) {
432
433
  }
433
434
  continue;
434
435
  }
435
- if (!e.name.endsWith('.jsonl')) continue;
436
+ // A workflow run also drops its journal.jsonl next to the agents; only `agent-*.jsonl` is a
437
+ // transcript, and counting the journal inflated the run's agent count by one and stretched its
438
+ // span, since a file with no priced turns falls back to the session's own start time.
439
+ if (!e.name.startsWith('agent-') || !e.name.endsWith('.jsonl')) continue;
436
440
  const agentId = e.name.replace('.jsonl', '');
437
441
  let meta = {};
438
442
  try { meta = JSON.parse(fs.readFileSync(path.join(dir, `${agentId}.meta.json`), 'utf-8')); } catch { /* no meta */ }
@@ -498,31 +502,43 @@ async function loadSubagentData(subagentInfos, pricing) {
498
502
  messageCount: 0,
499
503
  models: new Set(),
500
504
  firstTimestamp: null,
505
+ lastTimestamp: null,
501
506
  };
502
- const seen = new Set();
507
+ // An agent log writes one line per streamed content block, each carrying the usage as it stood
508
+ // then, so a turn's first line can report one output token and its last the whole reply: the
509
+ // turn is the largest usage logged for its (message.id, requestId). The session log repeats the
510
+ // final usage on every line, which is why first-wins reads the same there.
511
+ const kept = new Map();
512
+ const unhashed = [];
503
513
  await processJSONLFile(info.filePath, async (line) => {
504
514
  let parsed;
505
515
  try { parsed = JSON.parse(line); } catch { return; }
506
- if (!parsed.message?.usage?.input_tokens && parsed.message?.usage?.input_tokens !== 0) return;
516
+ const usage = parsed.message?.usage;
517
+ if (!usage?.input_tokens && usage?.input_tokens !== 0) return;
507
518
  if (!parsed.timestamp) return;
508
519
 
520
+ // Only what the totals need: `parsed` also holds the turn's content blocks.
521
+ const entry = { costUSD: parsed.costUSD, timestamp: parsed.timestamp, message: { model: parsed.message.model, usage } };
509
522
  const hash = createDedupeHash(parsed);
510
- if (hash && seen.has(hash)) return;
511
- if (hash) seen.add(hash);
512
-
513
- const cost = calculateEntryCost(parsed, pricing);
514
- const usage = parsed.message.usage;
515
- agent.totalCost += cost;
516
- agent.inputTokens += usage.input_tokens || 0;
517
- agent.outputTokens += usage.output_tokens || 0;
518
- agent.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
519
- agent.cacheReadTokens += (usage.cache_read_input_tokens || 0);
520
- agent.messageCount++;
521
- agent.models.add(parsed.message?.model || 'unknown');
522
- if (!agent.firstTimestamp || parsed.timestamp < agent.firstTimestamp) {
523
- agent.firstTimestamp = parsed.timestamp;
524
- }
523
+ if (!hash) { unhashed.push(entry); return; }
524
+ const prev = kept.get(hash);
525
+ if (!prev || (usage.output_tokens || 0) > (prev.message.usage.output_tokens || 0)) kept.set(hash, entry);
525
526
  });
527
+ const turns = [...kept.values(), ...unhashed].map(e => ({
528
+ cost: calculateEntryCost(e, pricing),
529
+ inputTokens: e.message.usage.input_tokens || 0,
530
+ outputTokens: e.message.usage.output_tokens || 0,
531
+ cacheCreationTokens: e.message.usage.cache_creation_input_tokens || 0,
532
+ cacheReadTokens: e.message.usage.cache_read_input_tokens || 0,
533
+ model: e.message.model || 'unknown',
534
+ timestamp: e.timestamp,
535
+ }));
536
+ Object.assign(agent, summarizeMessages(turns));
537
+ for (const t of turns) {
538
+ agent.models.add(t.model);
539
+ if (!agent.firstTimestamp || t.timestamp < agent.firstTimestamp) agent.firstTimestamp = t.timestamp;
540
+ if (!agent.lastTimestamp || t.timestamp > agent.lastTimestamp) agent.lastTimestamp = t.timestamp;
541
+ }
526
542
  agent.models = [...agent.models];
527
543
  return agent;
528
544
  }));
@@ -634,6 +650,10 @@ async function loadProjectData(files, pricing) {
634
650
  if (subagentInfos.length > 0) {
635
651
  const subagents = await loadSubagentData(subagentInfos, pricing);
636
652
  for (const sa of subagents) {
653
+ // An agent log with no priced turns — empty, truncated, or a crash before the first
654
+ // response — would fold in as a zero-cost message dated at the session's own start,
655
+ // which stretches every span it lands in.
656
+ if (sa.messageCount === 0) continue;
637
657
  session.totalCost += sa.totalCost;
638
658
  session.inputTokens += sa.inputTokens;
639
659
  session.outputTokens += sa.outputTokens;
@@ -649,7 +669,7 @@ async function loadProjectData(files, pricing) {
649
669
  cacheCreationTokens: sa.cacheCreationTokens,
650
670
  cacheReadTokens: sa.cacheReadTokens,
651
671
  speed: 'standard',
652
- _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount, workflowId: sa.workflowId },
672
+ _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount, workflowId: sa.workflowId, lastTimestamp: sa.lastTimestamp },
653
673
  });
654
674
  }
655
675
  }
@@ -1061,12 +1081,21 @@ async function getSessionDetailData(sessionId) {
1061
1081
  : new Map();
1062
1082
  const workflows = [...byWorkflow].map(([id, msgs]) => {
1063
1083
  const { messageCount, ...totals } = summarizeMessages(msgs);
1084
+ // A folded message carries its agent's start time, so the run ends at the latest agent's
1085
+ // own last turn — the last folded message only says when that agent started.
1086
+ const end = msgs.reduce((max, m) => {
1087
+ const t = m._subagent.lastTimestamp || m.timestamp;
1088
+ return t > max ? t : max;
1089
+ }, msgs[0].timestamp);
1064
1090
  return {
1065
1091
  id,
1066
1092
  name: names.get(id) || id,
1067
1093
  agents: messageCount,
1068
1094
  firstTimestamp: msgs[0].timestamp,
1069
- lastTimestamp: msgs.at(-1).timestamp,
1095
+ lastTimestamp: end,
1096
+ // Where the run sits in `messages`, for the timeline band.
1097
+ startIndex: msgs[0].index,
1098
+ endIndex: msgs.at(-1).index,
1070
1099
  ...totals,
1071
1100
  };
1072
1101
  }).sort((a, b) => b.totalCost - a.totalCost);
@@ -1463,6 +1492,45 @@ app.get('/api/sessions/:id', withRange(), async (req, res) => {
1463
1492
  }
1464
1493
  });
1465
1494
 
1495
+ // Each probe spawns a CLI process and fires the config dir's SessionStart hooks, so we cache the
1496
+ // result and let concurrent callers share one in-flight run.
1497
+ //
1498
+ // The TTL mirrors the CLI's own: it refetches plan utilization at most every 5 minutes and shares
1499
+ // the answer through an on-disk cache, so probing faster re-reads the same numbers. A manual
1500
+ // refresh bypasses this cache but still cannot beat that floor.
1501
+ const USAGE_TTL_MS = 5 * 60 * 1000;
1502
+ let usageCache = null;
1503
+ let usageInFlight = null;
1504
+
1505
+ function loadUsage(force = false) {
1506
+ if (!force && usageCache && Date.now() - usageCache.ts < USAGE_TTL_MS) {
1507
+ return Promise.resolve(usageCache.data);
1508
+ }
1509
+ // A forced call still joins an in-flight probe: two spawns would only race for the same answer.
1510
+ if (usageInFlight) return usageInFlight;
1511
+ usageInFlight = probeUsage({ claudeDir: CLAUDE_DIR })
1512
+ .then((raw) => {
1513
+ const data = normalizeUsage(raw);
1514
+ if (data) usageCache = { data, ts: Date.now() };
1515
+ return data;
1516
+ })
1517
+ .finally(() => {
1518
+ usageInFlight = null;
1519
+ });
1520
+ return usageInFlight;
1521
+ }
1522
+
1523
+ app.get('/api/usage-limits', async (req, res) => {
1524
+ try {
1525
+ const data = await loadUsage(req.query.refresh === '1');
1526
+ if (!data) return res.status(503).json({ error: 'No usage data returned' });
1527
+ res.json(data);
1528
+ } catch (err) {
1529
+ console.error('[API] usage-limits error:', err.message);
1530
+ res.status(503).json({ error: err.message });
1531
+ }
1532
+ });
1533
+
1466
1534
  app.get('/api/pricing', async (_req, res) => {
1467
1535
  try {
1468
1536
  const pricing = await fetchPricing();