claude-code-cost 0.17.1 → 0.19.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "0.17.1",
3
+ "version": "0.19.1",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/app.js CHANGED
@@ -74,6 +74,27 @@ function formatPct(part, total) {
74
74
  return total > 0 ? ((part / total) * 100).toFixed(1) : '0.0';
75
75
  }
76
76
 
77
+ // Intl puts U+202F before AM/PM, which reads as a stray gap in the mono font. Every
78
+ // locale format that can emit an hour goes through here so the strip cannot drift.
79
+ function stripNarrowSpace(str) {
80
+ return str.replace(/\u202f/g, ' ');
81
+ }
82
+
83
+ function localTime(iso, opts) {
84
+ return stripNarrowSpace(new Date(iso).toLocaleTimeString(undefined, opts));
85
+ }
86
+
87
+ // One meter for every share/progress card. Owns the clamp and the aria contract so a new
88
+ // call site cannot invent a sixth clamping idiom.
89
+ function meter(pct, { label = '', cls = '', ariaLabel = '' } = {}) {
90
+ const width = Math.min(100, Math.max(0, Number(pct) || 0)).toFixed(1);
91
+ const klass = esc(cls ? `meter ${cls}` : 'meter');
92
+ return `<div class="${klass}" role="img" aria-label="${esc(ariaLabel)}">
93
+ <div class="meter-track"><i style="width:${width}%"></i></div>
94
+ ${label ? `<span class="meter-value">${esc(label)}</span>` : ''}
95
+ </div>`;
96
+ }
97
+
77
98
  function formatDuration(minutes) {
78
99
  if (!minutes || minutes < 1) return '<1m';
79
100
  if (minutes < 60) return `${minutes}m`;
@@ -99,7 +120,7 @@ function timeAgo(ts) {
99
120
  // time with no zone suffix.
100
121
  function bucketLabel(key, bucket) {
101
122
  if (bucket === 'hour') {
102
- return new Date(`${key}:00:00`).toLocaleTimeString(undefined, { hour: 'numeric' });
123
+ return localTime(`${key}:00:00`, { hour: 'numeric' });
103
124
  }
104
125
  return new Date(`${key}T00:00:00`).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
105
126
  }
@@ -576,6 +597,8 @@ function renderOverview() {
576
597
 
577
598
  const costSeries = overviewData.costSeries;
578
599
  const models = overviewData.modelDistribution || [];
600
+ // null, not 0, when nothing cacheable ran — an empty range should show no meter at all.
601
+ const cachePct = s.totalCacheRead + s.totalCacheCreation > 0 ? s.cacheEfficiency * 100 : null;
579
602
 
580
603
  // Return before any chart call so no canvas is touched — there are none in this markup.
581
604
  if (scopeProject && s.totalSessions === 0) {
@@ -627,8 +650,9 @@ function renderOverview() {
627
650
  </div>
628
651
  <div class="stat-card">
629
652
  <div class="card-label">Cache Efficiency</div>
630
- <div class="card-value">${(s.cacheEfficiency * 100).toFixed(1)}%</div>
631
- <div class="card-sub">Read: ${formatTokens(s.totalCacheRead)} / Created: ${formatTokens(s.totalCacheCreation)}</div>
653
+ <div class="card-value">${cachePct == null ? '0.0' : cachePct.toFixed(1)}%</div>
654
+ ${cachePct == null ? '' : meter(cachePct, { ariaLabel: `${cachePct.toFixed(1)}% of all input tokens were served from cache` })}
655
+ <div class="card-sub">Read: <strong>${formatTokens(s.totalCacheRead)}</strong> / Created: ${formatTokens(s.totalCacheCreation)}</div>
632
656
  </div>
633
657
  </div>
634
658
 
@@ -768,13 +792,13 @@ function initHeatmapTooltip() {
768
792
 
769
793
  // Hour-only span (e.g. "15:00–20:00") so the card makes it obvious a fresh block just opened.
770
794
  function blockHours(b) {
771
- const t = (iso) => new Date(iso).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
772
- return `${t(b.start)}&ndash;${t(b.end)}`;
795
+ const opts = { hour: '2-digit', minute: '2-digit' };
796
+ return `${localTime(b.start, opts)} &ndash; ${localTime(b.end, opts)}`;
773
797
  }
774
798
 
775
799
  function blockSpanLabel(b) {
776
800
  const opts = { month: 'short', day: 'numeric', hour: 'numeric' };
777
- return `${new Date(b.start).toLocaleString(undefined, opts)} – ${new Date(b.end).toLocaleTimeString(undefined, { hour: 'numeric' })}`;
801
+ return `${stripNarrowSpace(new Date(b.start).toLocaleString(undefined, opts))} – ${localTime(b.end, { hour: 'numeric' })}`;
778
802
  }
779
803
 
780
804
  // Classifies the active block's projection: against the live usage limit when the statusline
@@ -787,16 +811,15 @@ function burnPace(ab, blocks) {
787
811
  if (ab.usedPct != null) {
788
812
  const projPct = (ab.usedPct / elapsedMin) * blockMin;
789
813
  const cls = projPct >= 100 ? 'hot' : projPct >= 80 ? 'warn' : 'ok';
790
- return { cls, note: `on pace for ${Math.round(Math.min(projPct, 999))}% of limit` };
814
+ return { cls, pct: Math.round(Math.min(projPct, 999)) };
791
815
  }
792
816
  const past = blocks
793
817
  .filter((b) => !b.active && b.cost > 0)
794
818
  .map((b) => b.cost)
795
819
  .sort((a, b) => a - b);
796
820
  if (past.length < 3) return null;
797
- const median = past[Math.floor(past.length / 2)];
798
821
  const p90 = past[Math.min(past.length - 1, Math.floor(past.length * 0.9))];
799
- const cls = ab.burn.projectedCost > p90 ? 'hot' : ab.burn.projectedCost > median ? 'warn' : 'ok';
822
+ const cls = ab.burn.projectedCost > p90 ? 'hot' : ab.burn.projectedCost > median(past) ? 'warn' : 'ok';
800
823
  return { cls, note: `vs. ${formatCost(median)} median block` };
801
824
  }
802
825
 
@@ -818,6 +841,8 @@ function renderInsights() {
818
841
  const sub = d.subagents;
819
842
  const agentTotal = sub.mainCost + sub.subagentCost;
820
843
  const subPct = formatPct(sub.subagentCost, agentTotal);
844
+ const cacheable = d.tokens.cacheRead + d.tokens.cacheCreation;
845
+ const cacheHitPct = cacheable > 0 ? Math.round((d.tokens.cacheRead / cacheable) * 100) : null;
821
846
  const showWeekly = d.weekly.length >= 3;
822
847
 
823
848
  el.innerHTML = `
@@ -828,27 +853,31 @@ function renderInsights() {
828
853
  <div class="stat-card">
829
854
  <div class="card-label">Active 5h Block</div>
830
855
  <div class="card-value cost">${ab ? formatCost(ab.cost) : '—'}</div>
831
- <div class="card-sub">${ab ? `${blockHours(ab)} &middot; ${formatDuration(ab.burn.remainingMin)} left${ab.usedPct != null ? ` &middot; ${Math.round(ab.usedPct)}% used` : ''}` : 'no live window data'}</div>
856
+ ${ab?.usedPct == null ? '' : meter(ab.usedPct, { label: `${Math.round(ab.usedPct)}%`, ariaLabel: `${Math.round(ab.usedPct)}% of the 5h block used` })}
857
+ <div class="card-sub">${ab ? `${blockHours(ab)} &middot; <strong>${formatDuration(ab.burn.remainingMin)} left</strong>` : 'no live window data'}</div>
832
858
  </div>
833
859
  <div class="stat-card">
834
860
  <div class="card-label">Burn Rate</div>
835
861
  <div class="card-value ${esc(pace ? `pace-${pace.cls}` : '')}">${ab ? `${formatCost(ab.burn.costPerHour)}/h` : '—'}</div>
836
- <div class="card-sub">${ab ? `${formatTokens(Math.round(ab.burn.tokensPerMin))} tok/min &middot; proj. ${formatCost(ab.burn.projectedCost)} by block end${pace ? ` &middot; ${pace.note}` : ''}` : 'no active block'}</div>
862
+ ${pace?.pct == null ? '' : meter(pace.pct, { label: `${pace.pct}%`, cls: `pace-${pace.cls}`, ariaLabel: `on pace for ${pace.pct}% of the usage limit` })}
863
+ <div class="card-sub">${ab ? `${formatTokens(Math.round(ab.burn.tokensPerMin))} tok/min &middot; proj. <strong>${formatCost(ab.burn.projectedCost)}</strong> by block end${pace?.note ? ` &middot; ${pace.note}` : ''}` : 'no active block'}</div>
837
864
  </div>
838
865
  <div class="stat-card">
839
866
  <div class="card-label">Monthly Run-Rate</div>
840
867
  <div class="card-value cost">${formatCost(d.runRate.projectedMonthly)}</div>
841
- <div class="card-sub">${formatCost(d.runRate.dailyAvg)}/day over ${d.runRate.days} ${d.runRate.days === 1 ? 'day' : 'days'}</div>
868
+ <div class="card-sub"><strong>${formatCost(d.runRate.dailyAvg)}/day</strong> over ${d.runRate.days} ${d.runRate.days === 1 ? 'day' : 'days'}</div>
842
869
  </div>
843
870
  <div class="stat-card">
844
871
  <div class="card-label">Cache Savings</div>
845
872
  <div class="card-value cost">${formatCost(d.cacheSavings)}</div>
846
- <div class="card-sub">vs. uncached input &middot; ${formatTokens(d.tokens.cacheRead)} reads</div>
873
+ ${cacheHitPct == null ? '' : meter(cacheHitPct, { label: `${cacheHitPct}% hit`, ariaLabel: `${cacheHitPct}% of cacheable input was served from cache, not re-sent` })}
874
+ <div class="card-sub">vs. uncached input &middot; <strong>${formatTokens(d.tokens.cacheRead)}</strong> reads</div>
847
875
  </div>
848
876
  <div class="stat-card">
849
877
  <div class="card-label">Subagent Share</div>
850
878
  <div class="card-value">${subPct}%</div>
851
- <div class="card-sub">${formatCost(sub.subagentCost)} of ${formatCost(agentTotal)}</div>
879
+ ${agentTotal > 0 ? meter(subPct, { ariaLabel: `subagents are ${subPct}% of ${formatCost(agentTotal)} in agent cost` }) : ''}
880
+ <div class="card-sub"><strong>${formatCost(sub.subagentCost)}</strong> of ${formatCost(agentTotal)}</div>
852
881
  </div>
853
882
  </div>
854
883
 
@@ -1076,6 +1105,8 @@ function renderDetail() {
1076
1105
  </div>
1077
1106
  </div>
1078
1107
 
1108
+ ${rangeBrushHtml(d.messages.length)}
1109
+
1079
1110
  <div class="section-title">Messages (${d.messages.length})</div>
1080
1111
  <table class="messages-table">
1081
1112
  <thead><tr>
@@ -1096,8 +1127,10 @@ function renderDetail() {
1096
1127
  </div>`;
1097
1128
 
1098
1129
  requestAnimationFrame(() => {
1099
- renderCumulativeChart(d.messages);
1100
- renderTokenBreakdownChart(d.messages);
1130
+ destroyChart('cumulative');
1131
+ destroyChart('tokenBreakdown');
1132
+ applyDetailRange(d.messages, detailRangeFor(d));
1133
+ initRangeBrush(d.messages);
1101
1134
  });
1102
1135
  }
1103
1136
 
@@ -1133,7 +1166,7 @@ function buildMessageRow(m) {
1133
1166
  : `<span class="model-badge">${esc(shortModel(m.model))}</span>${toolTags ? ` ${toolTags}` : ''}`;
1134
1167
  return `<tr>
1135
1168
  <td class="muted">${m.index}</td>
1136
- <td class="muted">${new Date(m.timestamp).toLocaleTimeString()}</td>
1169
+ <td class="muted">${localTime(m.timestamp)}</td>
1137
1170
  <td>${modelCol}</td>
1138
1171
  <td>${formatTokens(m.inputTokens)}</td>
1139
1172
  <td>${formatTokens(m.outputTokens)}</td>
@@ -1154,6 +1187,9 @@ function getChartColors() {
1154
1187
  accent: style.getPropertyValue('--accent').trim() || '#e86f33',
1155
1188
  chartFill: style.getPropertyValue('--chart-fill').trim() || 'rgba(232,111,51,0.6)',
1156
1189
  text: style.getPropertyValue('--text-secondary').trim() || '#c2c4c9',
1190
+ textPrimary: style.getPropertyValue('--text-primary').trim() || '#f0f1f3',
1191
+ textMuted: style.getPropertyValue('--text-muted').trim() || '#7d808a',
1192
+ mono: style.getPropertyValue('--mono').trim() || "'IBM Plex Mono', monospace",
1157
1193
  border: style.getPropertyValue('--border').trim() || '#363840',
1158
1194
  bg: style.getPropertyValue('--bg-elevated').trim() || '#1e2025',
1159
1195
  chart1: style.getPropertyValue('--chart-1').trim() || '#e86f33',
@@ -1186,19 +1222,29 @@ function messageTooltipTitle(messages, items) {
1186
1222
  return `#${m.index}${m._subagent ? ` · ${m._subagent.agentType}` : ''}`;
1187
1223
  }
1188
1224
 
1189
- function chartDefaults() {
1190
- const c = getChartColors();
1225
+ // Takes the palette the caller already read, so a chart costs one getComputedStyle, not two.
1226
+ function chartDefaults(c = getChartColors()) {
1191
1227
  return {
1192
1228
  responsive: true,
1193
1229
  maintainAspectRatio: false,
1194
1230
  plugins: {
1195
1231
  legend: { display: false },
1232
+ // Mirrors .hm-tip so a chart hover and a heatmap hover read as the same tooltip:
1233
+ // elevated bg, muted label above, primary value below, mono throughout.
1196
1234
  tooltip: {
1197
1235
  backgroundColor: c.bg,
1198
- titleColor: c.text,
1199
- bodyColor: c.text,
1236
+ titleColor: c.textMuted,
1237
+ bodyColor: c.textPrimary,
1200
1238
  borderColor: c.border,
1201
1239
  borderWidth: 1,
1240
+ cornerRadius: 4,
1241
+ padding: { top: 5, bottom: 5, left: 8, right: 8 },
1242
+ titleFont: { family: c.mono, size: 10, weight: 'normal' },
1243
+ bodyFont: { family: c.mono, size: 13, weight: '600' },
1244
+ titleMarginBottom: 2,
1245
+ boxWidth: 8,
1246
+ boxHeight: 8,
1247
+ boxPadding: 4,
1202
1248
  },
1203
1249
  },
1204
1250
  scales: {
@@ -1317,10 +1363,9 @@ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost', dist
1317
1363
  options: {
1318
1364
  ...defaults,
1319
1365
  interaction: { mode: 'nearest', intersect: true },
1320
- events: [],
1321
1366
  plugins: {
1322
- ...withTooltip(defaults, { label: (ctx) => usd(ctx.parsed.y) }),
1323
- // events: [] disables tooltips, so the legend is the only place segment names show.
1367
+ ...withTooltip(defaults, { label: (ctx) => `${ctx.dataset.label} ${usd(ctx.parsed.y)}` }),
1368
+ // The legend still carries segment names for the hours nobody hovers.
1324
1369
  legend: {
1325
1370
  display: models.length > 1,
1326
1371
  position: 'bottom',
@@ -1368,7 +1413,6 @@ function renderModelChart(models, canvasId = 'modelChart', chartKey = 'model') {
1368
1413
  ...defaults,
1369
1414
  indexAxis: 'y',
1370
1415
  interaction: { mode: 'nearest', intersect: true },
1371
- events: [],
1372
1416
  plugins: withTooltip(defaults, {
1373
1417
  label: (ctx) => `${usd(ctx.parsed.x)} (${formatPct(ctx.parsed.x, total)}%)`,
1374
1418
  }),
@@ -1380,6 +1424,50 @@ function renderModelChart(models, canvasId = 'modelChart', chartKey = 'model') {
1380
1424
  });
1381
1425
  }
1382
1426
 
1427
+ function cumulativeChartData(messages, c) {
1428
+ return {
1429
+ labels: messages.map((m) => m.index),
1430
+ datasets: [
1431
+ {
1432
+ label: 'Cumulative Cost',
1433
+ data: messages.map((m) => m.cumulativeCost),
1434
+ borderColor: c.accent,
1435
+ backgroundColor: c.chartFill,
1436
+ fill: true,
1437
+ borderWidth: 2,
1438
+ pointRadius: messages.length > 50 ? 0 : 3,
1439
+ // Subagent points render hollow so they read as folded-in cost, not main-loop turns.
1440
+ pointBackgroundColor: messages.length > 50 ? c.accent : messages.map((m) => (m._subagent ? c.bg : c.accent)),
1441
+ pointBorderColor: c.accent,
1442
+ tension: 0.2,
1443
+ },
1444
+ ],
1445
+ };
1446
+ }
1447
+
1448
+ function tokenBreakdownChartData(messages, c) {
1449
+ // Subagent bars render translucent so they read as folded-in usage, not main-loop turns.
1450
+ const barColors = (hex) => {
1451
+ const faded = hexToRgba(hex, 0.45);
1452
+ return messages.map((m) => (m._subagent ? faded : hex));
1453
+ };
1454
+ const series = [
1455
+ ['Input', 'inputTokens', c.chart1],
1456
+ ['Output', 'outputTokens', c.chart2],
1457
+ ['Cache Create', 'cacheCreationTokens', c.chart3],
1458
+ ['Cache Read', 'cacheReadTokens', c.chart4],
1459
+ ];
1460
+ return {
1461
+ labels: messages.map((m) => m.index),
1462
+ datasets: series.map(([label, key, hex]) => ({
1463
+ label,
1464
+ data: messages.map((m) => m[key]),
1465
+ backgroundColor: barColors(hex),
1466
+ borderRadius: 2,
1467
+ })),
1468
+ };
1469
+ }
1470
+
1383
1471
  function renderCumulativeChart(messages) {
1384
1472
  const canvas = document.getElementById('cumulativeChart');
1385
1473
  if (!canvas || !messages?.length) return;
@@ -1390,27 +1478,10 @@ function renderCumulativeChart(messages) {
1390
1478
 
1391
1479
  charts.cumulative = new Chart(canvas, {
1392
1480
  type: 'line',
1393
- data: {
1394
- labels: messages.map((m) => m.index),
1395
- datasets: [
1396
- {
1397
- label: 'Cumulative Cost',
1398
- data: messages.map((m) => m.cumulativeCost),
1399
- borderColor: c.accent,
1400
- backgroundColor: c.chartFill,
1401
- fill: true,
1402
- borderWidth: 2,
1403
- pointRadius: messages.length > 50 ? 0 : 3,
1404
- // Subagent points render hollow so they read as folded-in cost, not main-loop turns.
1405
- pointBackgroundColor: messages.length > 50 ? c.accent : messages.map((m) => (m._subagent ? c.bg : c.accent)),
1406
- pointBorderColor: c.accent,
1407
- tension: 0.2,
1408
- },
1409
- ],
1410
- },
1481
+ data: cumulativeChartData(messages, c),
1411
1482
  options: {
1412
1483
  ...defaults,
1413
- plugins: withTooltip(defaults, { title: (items) => messageTooltipTitle(messages, items) }),
1484
+ plugins: withTooltip(defaults, { title: (items) => messageTooltipTitle(detailSlice, items) }),
1414
1485
  scales: {
1415
1486
  ...defaults.scales,
1416
1487
  x: {
@@ -1434,53 +1505,19 @@ function renderTokenBreakdownChart(messages) {
1434
1505
  const c = getChartColors();
1435
1506
  const defaults = chartDefaults();
1436
1507
 
1437
- // Subagent bars render translucent so they read as folded-in usage, not main-loop turns.
1438
- const barColors = (hex) => {
1439
- const faded = hexToRgba(hex, 0.45);
1440
- return messages.map((m) => (m._subagent ? faded : hex));
1441
- };
1442
-
1443
1508
  charts.tokenBreakdown = new Chart(canvas, {
1444
1509
  type: 'bar',
1445
- data: {
1446
- labels: messages.map((m) => m.index),
1447
- datasets: [
1448
- {
1449
- label: 'Input',
1450
- data: messages.map((m) => m.inputTokens),
1451
- backgroundColor: barColors(c.chart1),
1452
- borderRadius: 2,
1453
- },
1454
- {
1455
- label: 'Output',
1456
- data: messages.map((m) => m.outputTokens),
1457
- backgroundColor: barColors(c.chart2),
1458
- borderRadius: 2,
1459
- },
1460
- {
1461
- label: 'Cache Create',
1462
- data: messages.map((m) => m.cacheCreationTokens),
1463
- backgroundColor: barColors(c.chart3),
1464
- borderRadius: 2,
1465
- },
1466
- {
1467
- label: 'Cache Read',
1468
- data: messages.map((m) => m.cacheReadTokens),
1469
- backgroundColor: barColors(c.chart4),
1470
- borderRadius: 2,
1471
- },
1472
- ],
1473
- },
1510
+ data: tokenBreakdownChartData(messages, c),
1474
1511
  options: {
1475
1512
  ...defaults,
1476
1513
  plugins: {
1477
- ...withTooltip(defaults, { title: (items) => messageTooltipTitle(messages, items) }),
1514
+ ...withTooltip(defaults, { title: (items) => messageTooltipTitle(detailSlice, items) }),
1478
1515
  legend: {
1479
1516
  display: true,
1480
1517
  position: 'bottom',
1481
1518
  labels: {
1482
1519
  color: c.text,
1483
- font: { size: 10, family: "'IBM Plex Mono', monospace" },
1520
+ font: { size: 10, family: c.mono },
1484
1521
  padding: 8,
1485
1522
  boxWidth: 12,
1486
1523
  boxHeight: 12,
@@ -1500,6 +1537,245 @@ function renderTokenBreakdownChart(messages) {
1500
1537
  });
1501
1538
  }
1502
1539
 
1540
+ // #region RANGE BRUSH
1541
+ // Long sessions squash both per-message charts into noise, so the detail view shows a window of
1542
+ // the last DETAIL_WINDOW messages by default and lets the user drag that window across an overview
1543
+ // of the whole session. State lives outside the DOM because renderDetail rebuilds its innerHTML on
1544
+ // every refresh; a window that sits at the tail stays there so new messages scroll into view.
1545
+ const DETAIL_WINDOW_PRESETS = [25, 50, 100, 200];
1546
+ const DETAIL_WINDOW = DETAIL_WINDOW_PRESETS[0];
1547
+ const DETAIL_WINDOW_MIN = 10;
1548
+ let detailRange = null;
1549
+ let detailSlice = [];
1550
+
1551
+ function median(sorted) {
1552
+ return sorted[Math.floor(sorted.length / 2)];
1553
+ }
1554
+
1555
+ // A cache burst is a main-loop turn that wrote far more cache than the session normally does:
1556
+ // the prompt prefix was invalidated (edited system prompt, compaction, new tool set, long gap) and
1557
+ // had to be re-cached. Relative to the session median so a chatty session and a heavy one both
1558
+ // surface their own outliers; the absolute floor drops noise in tiny sessions.
1559
+ const CACHE_BURST_RATIO = 4;
1560
+ const CACHE_BURST_MIN_TOKENS = 20000;
1561
+
1562
+ function cacheBurstIndices(messages) {
1563
+ const writes = messages
1564
+ .filter((m) => !m._subagent && m.cacheCreationTokens > 0)
1565
+ .map((m) => m.cacheCreationTokens)
1566
+ .sort((a, b) => a - b);
1567
+ if (writes.length < 5) return [];
1568
+ const threshold = Math.max(CACHE_BURST_MIN_TOKENS, median(writes) * CACHE_BURST_RATIO);
1569
+ return messages.flatMap((m, i) => (!m._subagent && m.cacheCreationTokens >= threshold ? [i] : []));
1570
+ }
1571
+
1572
+ function clampRange(start, end, total) {
1573
+ const s = Math.max(0, Math.min(start, total - DETAIL_WINDOW_MIN));
1574
+ return { start: s, end: Math.max(s + DETAIL_WINDOW_MIN, Math.min(end, total)) };
1575
+ }
1576
+
1577
+ function detailRangeFor(d) {
1578
+ const total = d.messages.length;
1579
+ const prev = detailRange?.key === d.sessionId ? detailRange : null;
1580
+ const size = prev ? prev.end - prev.start : DETAIL_WINDOW;
1581
+ const atTail = !prev || prev.end === prev.total;
1582
+ const start = atTail ? total - size : prev.start;
1583
+ detailRange = { key: d.sessionId, total, ...clampRange(start, start + size, total) };
1584
+ return detailRange;
1585
+ }
1586
+
1587
+ function applyDetailRange(messages, range) {
1588
+ detailSlice = messages.slice(range.start, range.end);
1589
+ const c = getChartColors();
1590
+ if (charts.cumulative && charts.tokenBreakdown) {
1591
+ charts.cumulative.data = cumulativeChartData(detailSlice, c);
1592
+ charts.cumulative.update('none');
1593
+ charts.tokenBreakdown.data = tokenBreakdownChartData(detailSlice, c);
1594
+ charts.tokenBreakdown.update('none');
1595
+ } else {
1596
+ renderCumulativeChart(detailSlice);
1597
+ renderTokenBreakdownChart(detailSlice);
1598
+ }
1599
+ }
1600
+
1601
+ function rangeBrushHtml(total) {
1602
+ if (total <= DETAIL_WINDOW) return '';
1603
+ const presets = DETAIL_WINDOW_PRESETS.filter((n) => n < total)
1604
+ .map((n) => `<button type="button" class="rb-preset" data-size="${n}">${n}</button>`)
1605
+ .join('');
1606
+ return `
1607
+ <div class="range-brush" id="rangeBrush">
1608
+ <div class="rb-head">
1609
+ <span class="rb-label"><span class="rb-scope"></span><span class="rb-burst-count" hidden><i></i></span></span>
1610
+ <div class="rb-presets" role="group" aria-label="Window size">
1611
+ ${presets}
1612
+ <button type="button" class="rb-preset" data-size="all">All</button>
1613
+ </div>
1614
+ </div>
1615
+ <div class="rb-track" tabindex="0" role="slider" aria-label="Visible message range"
1616
+ aria-valuemin="1" aria-valuemax="${esc(total)}">
1617
+ ${rangeOverviewSvg}
1618
+ <div class="rb-bursts"></div>
1619
+ <div class="rb-window">
1620
+ <div class="rb-handle rb-handle-left" data-edge="start"></div>
1621
+ <div class="rb-handle rb-handle-right" data-edge="end"></div>
1622
+ </div>
1623
+ </div>
1624
+ </div>`;
1625
+ }
1626
+
1627
+ // The overview shares the brush's percentage coordinate space, so it stretches with the track and
1628
+ // needs no resize handling. Points are filled in by initRangeBrush.
1629
+ const rangeOverviewSvg =
1630
+ '<svg class="rb-overview" viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><polygon /><polyline /></svg>';
1631
+
1632
+ function initRangeBrush(messages) {
1633
+ const root = document.getElementById('rangeBrush');
1634
+ if (!root) return;
1635
+ const total = messages.length;
1636
+ const range = detailRange;
1637
+ const q = (sel) => root.querySelector(sel);
1638
+ const track = q('.rb-track');
1639
+ const win = q('.rb-window');
1640
+ const scope = q('.rb-scope');
1641
+ const burstCount = q('.rb-burst-count');
1642
+ const presets = [...root.querySelectorAll('.rb-preset')].map((el) => ({
1643
+ el,
1644
+ size: el.dataset.size === 'all' ? total : Number(el.dataset.size),
1645
+ }));
1646
+
1647
+ drawRangeOverview(q('.rb-overview'), messages);
1648
+
1649
+ const bursts = cacheBurstIndices(messages);
1650
+ const burstsEl = q('.rb-bursts');
1651
+ burstsEl.innerHTML = bursts
1652
+ .map((i) => {
1653
+ const m = messages[i];
1654
+ const tip = `#${m.index} · cache write ${formatTokens(m.cacheCreationTokens)}`;
1655
+ return `<button type="button" class="rb-burst" data-i="${i}" style="left:${((i + 0.5) / total) * 100}%" title="${esc(tip)}" aria-label="${esc(tip)}"></button>`;
1656
+ })
1657
+ .join('');
1658
+ const burstEls = [...burstsEl.children].map((el, k) => ({ el, i: bursts[k] }));
1659
+ if (bursts.length) {
1660
+ burstCount.hidden = false;
1661
+ burstCount.append(`${bursts.length} cache burst${bursts.length === 1 ? '' : 's'}`);
1662
+ }
1663
+
1664
+ const layout = () => {
1665
+ const size = range.end - range.start;
1666
+ win.style.left = `${(range.start / total) * 100}%`;
1667
+ win.style.width = `${(size / total) * 100}%`;
1668
+ const text =
1669
+ size === total
1670
+ ? `All ${total} messages`
1671
+ : `Messages #${messages[range.start].index} – #${messages[range.end - 1].index} · ${size} of ${total}`;
1672
+ scope.textContent = text;
1673
+ track.setAttribute('aria-valuenow', String(range.start + 1));
1674
+ track.setAttribute('aria-valuetext', text);
1675
+ for (const p of presets) p.el.classList.toggle('on', p.size === size);
1676
+ for (const b of burstEls) b.el.classList.toggle('in', b.i >= range.start && b.i < range.end);
1677
+ };
1678
+
1679
+ // Pointer and wheel events outrun the frame rate, so range writes are coalesced into one paint.
1680
+ let frame = 0;
1681
+ const setRange = (from, to) => {
1682
+ const next = clampRange(from, to, total);
1683
+ if (next.start === range.start && next.end === range.end) return;
1684
+ Object.assign(range, next);
1685
+ if (frame) return;
1686
+ frame = requestAnimationFrame(() => {
1687
+ frame = 0;
1688
+ layout();
1689
+ applyDetailRange(messages, range);
1690
+ });
1691
+ };
1692
+ const size = () => range.end - range.start;
1693
+ const step = () => Math.max(1, Math.round(size() / 10));
1694
+ const pan = (delta) => setRange(range.start + delta, range.end + delta);
1695
+ const centerOn = (i) => {
1696
+ const start = Math.max(0, Math.min(i - Math.floor(size() / 2), total - size()));
1697
+ setRange(start, start + size());
1698
+ };
1699
+ const resize = (n) => {
1700
+ const end = Math.min(total, Math.max(range.end, n));
1701
+ setRange(end - n, end);
1702
+ };
1703
+
1704
+ // Pointer capture keeps a fast drag alive after the cursor leaves the thin track. The rect is
1705
+ // read once per drag: reading it per move right after writing the window's style would thrash.
1706
+ track.addEventListener('pointerdown', (e) => {
1707
+ if (e.button !== 0) return;
1708
+ e.preventDefault();
1709
+ track.focus({ preventScroll: true });
1710
+ const rect = track.getBoundingClientRect();
1711
+ const perPx = total / rect.width;
1712
+ const edge = e.target.dataset?.edge;
1713
+ if (!edge && e.target !== win) centerOn(Math.round((e.clientX - rect.left) * perPx));
1714
+ const origin = { x: e.clientX, start: range.start, end: range.end };
1715
+ track.classList.add('dragging');
1716
+ track.setPointerCapture(e.pointerId);
1717
+ const move = (ev) => {
1718
+ const delta = Math.round((ev.clientX - origin.x) * perPx);
1719
+ if (edge === 'start') setRange(origin.start + delta, origin.end);
1720
+ else if (edge === 'end') setRange(origin.start, origin.end + delta);
1721
+ else {
1722
+ const n = origin.end - origin.start;
1723
+ const start = Math.max(0, Math.min(origin.start + delta, total - n));
1724
+ setRange(start, start + n);
1725
+ }
1726
+ };
1727
+ const up = () => {
1728
+ track.classList.remove('dragging');
1729
+ track.removeEventListener('pointermove', move);
1730
+ track.removeEventListener('pointerup', up);
1731
+ track.removeEventListener('pointercancel', up);
1732
+ };
1733
+ track.addEventListener('pointermove', move);
1734
+ track.addEventListener('pointerup', up);
1735
+ track.addEventListener('pointercancel', up);
1736
+ });
1737
+
1738
+ track.addEventListener(
1739
+ 'wheel',
1740
+ (e) => {
1741
+ e.preventDefault();
1742
+ pan((e.deltaY || e.deltaX) > 0 ? step() : -step());
1743
+ },
1744
+ { passive: false },
1745
+ );
1746
+
1747
+ track.addEventListener('keydown', (e) => {
1748
+ const n = e.shiftKey ? size() : step();
1749
+ if (e.key === 'ArrowLeft') pan(-n);
1750
+ else if (e.key === 'ArrowRight') pan(n);
1751
+ else if (e.key === 'Home') setRange(0, size());
1752
+ else if (e.key === 'End') setRange(total - size(), total);
1753
+ else return;
1754
+ e.preventDefault();
1755
+ });
1756
+
1757
+ for (const p of presets) p.el.addEventListener('click', () => resize(p.size));
1758
+
1759
+ burstsEl.addEventListener('pointerdown', (e) => {
1760
+ const b = e.target.closest('.rb-burst');
1761
+ if (!b) return;
1762
+ e.stopPropagation();
1763
+ e.preventDefault();
1764
+ centerOn(Number(b.dataset.i));
1765
+ });
1766
+
1767
+ layout();
1768
+ }
1769
+
1770
+ function drawRangeOverview(svg, messages) {
1771
+ const n = messages.length;
1772
+ const max = messages[n - 1]?.cumulativeCost || 1;
1773
+ const pts = messages.map((m, i) => `${(i / Math.max(1, n - 1)) * 1000},${100 - (m.cumulativeCost / max) * 96 - 2}`);
1774
+ svg.querySelector('polyline').setAttribute('points', pts.join(' '));
1775
+ svg.querySelector('polygon').setAttribute('points', `0,100 ${pts.join(' ')} 1000,100`);
1776
+ }
1777
+ // #endregion
1778
+
1503
1779
  function renderTokenSplitChart(t) {
1504
1780
  const canvas = document.getElementById('tokenSplitChart');
1505
1781
  if (!canvas) return;
package/public/style.css CHANGED
@@ -618,7 +618,7 @@ body {
618
618
  }
619
619
 
620
620
  .dashboard-content {
621
- max-width: 1400px;
621
+ max-width: 1600px;
622
622
  margin: 0 auto;
623
623
  }
624
624
 
@@ -636,7 +636,7 @@ body {
636
636
 
637
637
  .cards-row {
638
638
  display: grid;
639
- grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
639
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
640
640
  gap: 12px;
641
641
  margin-bottom: 20px;
642
642
  }
@@ -678,6 +678,42 @@ body {
678
678
  margin-top: 4px;
679
679
  }
680
680
 
681
+ .stat-card .card-sub strong {
682
+ color: var(--text-primary);
683
+ font-weight: 600;
684
+ }
685
+
686
+ .stat-card .meter {
687
+ display: flex;
688
+ align-items: center;
689
+ gap: 6px;
690
+ margin-top: 8px;
691
+ }
692
+
693
+ .stat-card .meter-track {
694
+ flex: 1;
695
+ min-width: 0;
696
+ height: 3px;
697
+ background: var(--meter-dim, var(--accent-dim));
698
+ border-radius: 2px;
699
+ overflow: hidden;
700
+ }
701
+
702
+ .stat-card .meter-track > i {
703
+ display: block;
704
+ height: 100%;
705
+ background: var(--meter, var(--accent));
706
+ border-radius: 2px;
707
+ }
708
+
709
+ .stat-card .meter-value {
710
+ flex: none;
711
+ font-family: var(--mono);
712
+ font-size: 10px;
713
+ font-weight: 600;
714
+ color: var(--meter, var(--text-primary));
715
+ }
716
+
681
717
  /* #endregion */
682
718
 
683
719
  /* #region CHARTS */
@@ -744,6 +780,222 @@ body {
744
780
 
745
781
  /* #endregion */
746
782
 
783
+ /* #region RANGE BRUSH */
784
+
785
+ .range-brush {
786
+ background: var(--bg-surface);
787
+ border: 1px solid var(--border);
788
+ border-radius: 6px;
789
+ padding: 10px 16px 12px;
790
+ margin: -8px 0 20px;
791
+ }
792
+
793
+ .rb-head {
794
+ display: flex;
795
+ align-items: center;
796
+ justify-content: space-between;
797
+ gap: 12px;
798
+ margin-bottom: 8px;
799
+ }
800
+
801
+ .rb-label {
802
+ font-size: 11px;
803
+ color: var(--text-muted);
804
+ text-transform: uppercase;
805
+ letter-spacing: 0.05em;
806
+ white-space: nowrap;
807
+ overflow: hidden;
808
+ text-overflow: ellipsis;
809
+ }
810
+
811
+ .rb-burst-count {
812
+ margin-left: 10px;
813
+ color: var(--warning);
814
+ }
815
+
816
+ .rb-burst-count i {
817
+ display: inline-block;
818
+ width: 6px;
819
+ height: 6px;
820
+ border-radius: 50%;
821
+ background: var(--warning);
822
+ margin-right: 5px;
823
+ vertical-align: middle;
824
+ }
825
+
826
+ .rb-presets {
827
+ display: flex;
828
+ gap: 4px;
829
+ }
830
+
831
+ .rb-preset {
832
+ font: inherit;
833
+ font-size: 10px;
834
+ letter-spacing: 0.03em;
835
+ color: var(--text-tertiary);
836
+ background: transparent;
837
+ border: 1px solid var(--border);
838
+ border-radius: 4px;
839
+ padding: 2px 8px;
840
+ cursor: pointer;
841
+ }
842
+
843
+ .rb-preset:hover {
844
+ color: var(--text-primary);
845
+ border-color: var(--text-muted);
846
+ }
847
+
848
+ .rb-preset.on {
849
+ color: var(--accent-text);
850
+ border-color: var(--accent);
851
+ background: var(--accent-dim);
852
+ }
853
+
854
+ .rb-track {
855
+ position: relative;
856
+ height: 44px;
857
+ border-radius: 4px;
858
+ background: var(--bg-deep);
859
+ border: 1px solid var(--border);
860
+ overflow: hidden;
861
+ cursor: crosshair;
862
+ user-select: none;
863
+ touch-action: none;
864
+ outline: none;
865
+ }
866
+
867
+ .rb-track:focus-visible {
868
+ border-color: var(--accent);
869
+ box-shadow: 0 0 0 2px var(--accent-dim);
870
+ }
871
+
872
+ .rb-overview {
873
+ position: absolute;
874
+ inset: 0;
875
+ width: 100%;
876
+ height: 100%;
877
+ display: block;
878
+ }
879
+
880
+ .rb-overview polygon {
881
+ fill: var(--chart-fill);
882
+ }
883
+
884
+ .rb-overview polyline {
885
+ fill: none;
886
+ stroke: var(--accent);
887
+ stroke-width: 1.5;
888
+ vector-effect: non-scaling-stroke;
889
+ }
890
+
891
+ .rb-bursts {
892
+ position: absolute;
893
+ inset: 0;
894
+ pointer-events: none;
895
+ }
896
+
897
+ .rb-burst {
898
+ position: absolute;
899
+ top: 0;
900
+ bottom: 0;
901
+ width: 7px;
902
+ margin-left: -3.5px;
903
+ padding: 0;
904
+ border: 0;
905
+ background: transparent;
906
+ cursor: pointer;
907
+ pointer-events: auto;
908
+ }
909
+
910
+ .rb-burst::before {
911
+ content: '';
912
+ position: absolute;
913
+ top: 0;
914
+ bottom: 0;
915
+ left: 3px;
916
+ width: 1px;
917
+ background: var(--warning);
918
+ opacity: 0.55;
919
+ }
920
+
921
+ .rb-burst::after {
922
+ content: '';
923
+ position: absolute;
924
+ top: 3px;
925
+ left: 1px;
926
+ width: 5px;
927
+ height: 5px;
928
+ border-radius: 50%;
929
+ background: var(--warning);
930
+ }
931
+
932
+ .rb-burst.in::before,
933
+ .rb-burst:hover::before {
934
+ opacity: 1;
935
+ width: 2px;
936
+ left: 2.5px;
937
+ }
938
+
939
+ /* The shade outside the window is the window's own shadow, clipped by the track. */
940
+ .rb-window {
941
+ position: absolute;
942
+ top: 0;
943
+ bottom: 0;
944
+ border: 1px solid var(--accent);
945
+ border-radius: 3px;
946
+ background: var(--accent-dim);
947
+ box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.45);
948
+ cursor: grab;
949
+ box-sizing: border-box;
950
+ min-width: 8px;
951
+ }
952
+
953
+ body.light .rb-window {
954
+ box-shadow: 0 0 0 9999px rgba(255, 255, 255, 0.55);
955
+ }
956
+
957
+ .rb-track.dragging,
958
+ .rb-track.dragging .rb-window {
959
+ cursor: grabbing;
960
+ }
961
+
962
+ .rb-handle {
963
+ position: absolute;
964
+ top: 0;
965
+ bottom: 0;
966
+ width: 10px;
967
+ cursor: ew-resize;
968
+ }
969
+
970
+ .rb-handle::after {
971
+ content: '';
972
+ position: absolute;
973
+ top: 50%;
974
+ width: 3px;
975
+ height: 14px;
976
+ margin-top: -7px;
977
+ border-radius: 2px;
978
+ background: var(--accent);
979
+ }
980
+
981
+ .rb-handle-left {
982
+ left: -5px;
983
+ }
984
+
985
+ .rb-handle-left::after {
986
+ left: 3px;
987
+ }
988
+
989
+ .rb-handle-right {
990
+ right: -5px;
991
+ }
992
+
993
+ .rb-handle-right::after {
994
+ right: 3px;
995
+ }
996
+
997
+ /* #endregion */
998
+
747
999
  /* #region TABLE */
748
1000
 
749
1001
  .section-title {
@@ -1248,8 +1500,8 @@ kbd {
1248
1500
 
1249
1501
  .hm-cell {
1250
1502
  position: relative;
1251
- aspect-ratio: 1.6;
1252
- min-height: 12px;
1503
+ aspect-ratio: 2.4;
1504
+ min-height: 10px;
1253
1505
  border-radius: 2px;
1254
1506
  background: var(--bg-hover);
1255
1507
  overflow: hidden;
@@ -1287,7 +1539,7 @@ kbd {
1287
1539
  }
1288
1540
 
1289
1541
  .hm-tip b {
1290
- font-size: 12px;
1542
+ font-size: 13px;
1291
1543
  color: var(--text-primary);
1292
1544
  }
1293
1545
 
@@ -1312,14 +1564,25 @@ kbd {
1312
1564
  background: var(--success-dim);
1313
1565
  }
1314
1566
 
1315
- .card-value.pace-ok {
1316
- color: var(--success);
1567
+ /* One status mapping for every pace-colored element: the modifier sets the tokens,
1568
+ .card-value and .meter both read them. A new pace state costs one line. */
1569
+ .pace-ok {
1570
+ --meter: var(--success);
1571
+ --meter-dim: var(--success-dim);
1317
1572
  }
1318
- .card-value.pace-warn {
1319
- color: var(--warning);
1573
+ .pace-warn {
1574
+ --meter: var(--warning);
1575
+ --meter-dim: var(--warning-dim);
1320
1576
  }
1577
+ .pace-hot {
1578
+ --meter: var(--error);
1579
+ --meter-dim: var(--error-dim);
1580
+ }
1581
+
1582
+ .card-value.pace-ok,
1583
+ .card-value.pace-warn,
1321
1584
  .card-value.pace-hot {
1322
- color: var(--error);
1585
+ color: var(--meter);
1323
1586
  }
1324
1587
 
1325
1588
  /* #endregion */