claude-code-cost 0.18.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "0.18.1",
3
+ "version": "0.20.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/app.js CHANGED
@@ -818,9 +818,8 @@ function burnPace(ab, blocks) {
818
818
  .map((b) => b.cost)
819
819
  .sort((a, b) => a - b);
820
820
  if (past.length < 3) return null;
821
- const median = past[Math.floor(past.length / 2)];
822
821
  const p90 = past[Math.min(past.length - 1, Math.floor(past.length * 0.9))];
823
- 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';
824
823
  return { cls, note: `vs. ${formatCost(median)} median block` };
825
824
  }
826
825
 
@@ -878,7 +877,7 @@ function renderInsights() {
878
877
  <div class="card-label">Subagent Share</div>
879
878
  <div class="card-value">${subPct}%</div>
880
879
  ${agentTotal > 0 ? meter(subPct, { ariaLabel: `subagents are ${subPct}% of ${formatCost(agentTotal)} in agent cost` }) : ''}
881
- <div class="card-sub"><strong>${formatCost(sub.subagentCost)}</strong> of ${formatCost(agentTotal)}</div>
880
+ <div class="card-sub"><strong>${formatCost(sub.subagentCost)}</strong> of ${formatCost(agentTotal)}${sub.workflowRuns ? ` &middot; ${formatCost(sub.workflowCost)} in ${sub.workflowRuns} workflow${sub.workflowRuns === 1 ? '' : 's'}` : ''}</div>
882
881
  </div>
883
882
  </div>
884
883
 
@@ -1016,7 +1015,7 @@ function renderSessions() {
1016
1015
  <td class="truncate" title="${esc(s.customTitle || s.firstPrompt || s.sessionId)}">${esc(s.customTitle || s.firstPrompt || s.sessionId)}</td>
1017
1016
  <td class="cost-cell">${formatCost(s.totalCost)}</td>
1018
1017
  <td>${formatTokens(s.totalTokens)}</td>
1019
- <td>${s.messageCount}</td>
1018
+ <td>${s.messageCount}${s.compactions?.count ? ` <span class="compaction-tag" title="${esc(`${s.compactions.count} compaction(s), ~${formatCost(s.compactions.totalCost)}`)}">${s.compactions.count}&times; compact</span>` : ''}</td>
1020
1019
  <td class="muted">${formatDuration(s.durationMinutes)}</td>
1021
1020
  <td><span class="model-badge">${esc(shortModel(s.primaryModel))}</span></td>
1022
1021
  <td class="muted">${timeAgo(s.lastTimestamp)}</td>
@@ -1091,9 +1090,12 @@ function renderDetail() {
1091
1090
  <div class="detail-label">Models</div>
1092
1091
  <div class="detail-value">${esc(d.models.map((m) => shortModel(m)).join(', '))}</div>
1093
1092
  </div>
1093
+ ${compactionStat(d.compactions)}
1094
1094
  </div>
1095
1095
 
1096
1096
  ${detailRangeNote(d)}
1097
+ ${compactionNote(d.compactions)}
1098
+ ${workflowsSection(d)}
1097
1099
 
1098
1100
  <div class="charts-row" style="margin-bottom:20px">
1099
1101
  <div class="chart-box">
@@ -1106,7 +1108,9 @@ function renderDetail() {
1106
1108
  </div>
1107
1109
  </div>
1108
1110
 
1109
- <div class="section-title">Messages (${d.messages.length})</div>
1111
+ ${rangeBrushHtml(d.messages.length)}
1112
+
1113
+ <div class="section-title" id="messagesTitle"></div>
1110
1114
  <table class="messages-table">
1111
1115
  <thead><tr>
1112
1116
  <th>#</th>
@@ -1119,15 +1123,15 @@ function renderDetail() {
1119
1123
  <th>Cost</th>
1120
1124
  <th>Cumulative</th>
1121
1125
  </tr></thead>
1122
- <tbody>
1123
- ${buildMessageRowsWithSubagents(d)}
1124
- </tbody>
1126
+ <tbody id="messagesBody"></tbody>
1125
1127
  </table>
1126
1128
  </div>`;
1127
1129
 
1128
1130
  requestAnimationFrame(() => {
1129
- renderCumulativeChart(d.messages);
1130
- renderTokenBreakdownChart(d.messages);
1131
+ destroyChart('cumulative');
1132
+ destroyChart('tokenBreakdown');
1133
+ applyDetailRange(d.messages, detailRangeFor(d));
1134
+ initRangeBrush(d.messages);
1131
1135
  });
1132
1136
  }
1133
1137
 
@@ -1148,18 +1152,92 @@ function detailRangeNote(d) {
1148
1152
  return `<div class="detail-range-note">Totals above are all-time &middot; ${parts.join(' &middot; ')}</div>`;
1149
1153
  }
1150
1154
 
1151
- function buildMessageRowsWithSubagents(d) {
1152
- return [...d.messages]
1153
- .reverse()
1154
- .map((m) => buildMessageRow(m))
1155
+ function compactionStat(c) {
1156
+ if (!c?.count) return '';
1157
+ return `<div class="detail-stat">
1158
+ <div class="detail-label">Compactions</div>
1159
+ <div class="detail-value">${c.count}<span class="detail-label detail-scope">~${formatCost(c.totalCost)}</span></div>
1160
+ </div>`;
1161
+ }
1162
+
1163
+ // The summarizer call is not in the JSONL, so its share is an estimate; the re-warm share is real
1164
+ // spend already inside the total. Both are spelled out so the header number is not read as exact.
1165
+ function compactionNote(c) {
1166
+ if (!c?.count) return '';
1167
+ const trigger =
1168
+ c.auto === c.count ? 'all auto' : c.auto === 0 ? 'all manual' : `${c.auto} auto, ${c.count - c.auto} manual`;
1169
+ return `<div class="detail-range-note compaction-note">
1170
+ <span class="scope-label">compaction</span> ${trigger} &middot;
1171
+ dropped <strong>${formatTokens(c.droppedTokens)}</strong> tokens &middot;
1172
+ summarizer <strong>~${formatCost(c.estCost)}</strong> (estimate, not in total) &middot;
1173
+ cache re-warm <strong>${formatCost(c.rewarmCost)}</strong> / ${formatTokens(c.rewarmTokens)} (in total)
1174
+ </div>`;
1175
+ }
1176
+
1177
+ function compactionRow(c) {
1178
+ return `<tr class="compaction-row">
1179
+ <td></td>
1180
+ <td class="muted">${localTime(c.timestamp)}</td>
1181
+ <td colspan="5"><span class="compaction-tag">${esc(c.trigger)} compact</span>
1182
+ ${formatTokens(c.preTokens)} &rarr; ${formatTokens(c.postTokens)} (&minus;${formatPct(c.preTokens - c.postTokens, c.preTokens)}%) &middot; ${Math.round(c.durationMs / 1000)}s</td>
1183
+ <td class="cost-cell">~${formatCost(c.estCost)}</td>
1184
+ <td class="cumulative">est.</td>
1185
+ </tr>`;
1186
+ }
1187
+
1188
+ // A Workflow run fans out to tens of agents, each folded into one message row — so the run itself
1189
+ // is the unit worth reading, not the rows.
1190
+ function workflowsSection(d) {
1191
+ if (!d.workflows?.length) return '';
1192
+ const rows = d.workflows
1193
+ .map((w) => {
1194
+ const pct = d.totalCost > 0 ? Math.round((w.totalCost / d.totalCost) * 100) : 0;
1195
+ const mins = Math.round((new Date(w.lastTimestamp) - new Date(w.firstTimestamp)) / 60000);
1196
+ return `<tr>
1197
+ <td>${esc(w.name)}</td>
1198
+ <td>${w.agents}</td>
1199
+ <td class="muted">${mins} min</td>
1200
+ <td>${formatTokens(w.inputTokens + w.cacheCreationTokens + w.cacheReadTokens)}</td>
1201
+ <td>${formatTokens(w.outputTokens)}</td>
1202
+ <td class="cost-cell">${formatCost(w.totalCost)}</td>
1203
+ <td>${meter(pct, { label: `${pct}%`, ariaLabel: `${pct}% of session cost` })}</td>
1204
+ </tr>`;
1205
+ })
1155
1206
  .join('');
1207
+ return `
1208
+ <div class="section-title">Workflows (${d.workflows.length})</div>
1209
+ <table class="messages-table" style="margin-bottom:20px">
1210
+ <thead><tr>
1211
+ <th>Workflow</th>
1212
+ <th>Agents</th>
1213
+ <th>Span</th>
1214
+ <th>Input</th>
1215
+ <th>Output</th>
1216
+ <th>Cost</th>
1217
+ <th>Share</th>
1218
+ </tr></thead>
1219
+ <tbody>${rows}</tbody>
1220
+ </table>`;
1221
+ }
1222
+
1223
+ function renderMessageRows(slice, total) {
1224
+ const body = document.getElementById('messagesBody');
1225
+ if (!body) return;
1226
+ document.getElementById('messagesTitle').textContent =
1227
+ slice.length === total ? `Messages (${total})` : `Messages (${slice.length} of ${total})`;
1228
+ const rows = [];
1229
+ for (let i = slice.length - 1; i >= 0; i--) {
1230
+ const m = slice[i];
1231
+ rows.push(buildMessageRow(m) + (m.compaction ? compactionRow(m.compaction) : ''));
1232
+ }
1233
+ body.innerHTML = rows.join('');
1156
1234
  }
1157
1235
 
1158
1236
  function buildMessageRow(m) {
1159
1237
  const sa = m._subagent;
1160
1238
  const toolTags = !sa && m.tools ? m.tools.map((t) => `<span class="tool-tag">${esc(t)}</span>`).join(' ') : '';
1161
1239
  const modelCol = sa
1162
- ? `<span class="model-badge">${esc(shortModel(m.model))}</span> <span class="subagent-tag">${esc(sa.agentType)}</span>`
1240
+ ? `<span class="model-badge">${esc(shortModel(m.model))}</span> <span class="subagent-tag">${esc(sa.workflowId ? 'workflow' : sa.agentType)}</span>`
1163
1241
  : `<span class="model-badge">${esc(shortModel(m.model))}</span>${toolTags ? ` ${toolTags}` : ''}`;
1164
1242
  return `<tr>
1165
1243
  <td class="muted">${m.index}</td>
@@ -1421,6 +1499,87 @@ function renderModelChart(models, canvasId = 'modelChart', chartKey = 'model') {
1421
1499
  });
1422
1500
  }
1423
1501
 
1502
+ function cumulativeChartData(messages, c) {
1503
+ return {
1504
+ labels: messages.map((m) => m.index),
1505
+ datasets: [
1506
+ {
1507
+ label: 'Cumulative Cost',
1508
+ data: messages.map((m) => m.cumulativeCost),
1509
+ borderColor: c.accent,
1510
+ backgroundColor: c.chartFill,
1511
+ fill: true,
1512
+ borderWidth: 2,
1513
+ pointRadius: messages.length > 50 ? 0 : 3,
1514
+ // Subagent points render hollow so they read as folded-in cost, not main-loop turns.
1515
+ pointBackgroundColor: messages.length > 50 ? c.accent : messages.map((m) => (m._subagent ? c.bg : c.accent)),
1516
+ pointBorderColor: c.accent,
1517
+ tension: 0.2,
1518
+ },
1519
+ ],
1520
+ };
1521
+ }
1522
+
1523
+ function tokenBreakdownChartData(messages, c) {
1524
+ // Subagent bars render translucent so they read as folded-in usage, not main-loop turns.
1525
+ const barColors = (hex) => {
1526
+ const faded = hexToRgba(hex, 0.45);
1527
+ return messages.map((m) => (m._subagent ? faded : hex));
1528
+ };
1529
+ const series = [
1530
+ ['Input', 'inputTokens', c.chart1],
1531
+ ['Output', 'outputTokens', c.chart2],
1532
+ ['Cache Create', 'cacheCreationTokens', c.chart3],
1533
+ ['Cache Read', 'cacheReadTokens', c.chart4],
1534
+ ];
1535
+ return {
1536
+ labels: messages.map((m) => m.index),
1537
+ datasets: series.map(([label, key, hex]) => ({
1538
+ label,
1539
+ data: messages.map((m) => m[key]),
1540
+ backgroundColor: barColors(hex),
1541
+ borderRadius: 2,
1542
+ })),
1543
+ };
1544
+ }
1545
+
1546
+ // Draws a dashed vertical line just before each turn that followed a compaction, so the flat
1547
+ // stretch in cache-read and the cache-create spike next to it read as one event, not noise.
1548
+ // Reads chart.$compactions, set by markCompactions, so a draw costs no style lookup or scan.
1549
+ const compactionMarkers = {
1550
+ id: 'compactionMarkers',
1551
+ afterDatasetsDraw(chart) {
1552
+ const marks = chart.$compactions;
1553
+ if (!marks?.indices.length) return;
1554
+ const { ctx, chartArea, scales } = chart;
1555
+ ctx.save();
1556
+ ctx.strokeStyle = marks.color;
1557
+ ctx.lineWidth = 1;
1558
+ ctx.setLineDash([4, 3]);
1559
+ ctx.font = `9px ${marks.font}`;
1560
+ ctx.fillStyle = marks.color;
1561
+ ctx.textAlign = 'center';
1562
+ for (const i of marks.indices) {
1563
+ const p = scales.x.getPixelForValue(i);
1564
+ const x = i > 0 ? (p + scales.x.getPixelForValue(i - 1)) / 2 : p;
1565
+ ctx.beginPath();
1566
+ ctx.moveTo(x, chartArea.top);
1567
+ ctx.lineTo(x, chartArea.bottom);
1568
+ ctx.stroke();
1569
+ ctx.fillText('compact', x, chartArea.top - 2);
1570
+ }
1571
+ ctx.restore();
1572
+ },
1573
+ };
1574
+
1575
+ function markCompactions(chart, messages, c) {
1576
+ chart.$compactions = {
1577
+ indices: messages.flatMap((m, i) => (m.compaction ? [i] : [])),
1578
+ color: c.chart5,
1579
+ font: c.mono,
1580
+ };
1581
+ }
1582
+
1424
1583
  function renderCumulativeChart(messages) {
1425
1584
  const canvas = document.getElementById('cumulativeChart');
1426
1585
  if (!canvas || !messages?.length) return;
@@ -1431,27 +1590,11 @@ function renderCumulativeChart(messages) {
1431
1590
 
1432
1591
  charts.cumulative = new Chart(canvas, {
1433
1592
  type: 'line',
1434
- data: {
1435
- labels: messages.map((m) => m.index),
1436
- datasets: [
1437
- {
1438
- label: 'Cumulative Cost',
1439
- data: messages.map((m) => m.cumulativeCost),
1440
- borderColor: c.accent,
1441
- backgroundColor: c.chartFill,
1442
- fill: true,
1443
- borderWidth: 2,
1444
- pointRadius: messages.length > 50 ? 0 : 3,
1445
- // Subagent points render hollow so they read as folded-in cost, not main-loop turns.
1446
- pointBackgroundColor: messages.length > 50 ? c.accent : messages.map((m) => (m._subagent ? c.bg : c.accent)),
1447
- pointBorderColor: c.accent,
1448
- tension: 0.2,
1449
- },
1450
- ],
1451
- },
1593
+ data: cumulativeChartData(messages, c),
1594
+ plugins: [compactionMarkers],
1452
1595
  options: {
1453
1596
  ...defaults,
1454
- plugins: withTooltip(defaults, { title: (items) => messageTooltipTitle(messages, items) }),
1597
+ plugins: withTooltip(defaults, { title: (items) => messageTooltipTitle(detailSlice, items) }),
1455
1598
  scales: {
1456
1599
  ...defaults.scales,
1457
1600
  x: {
@@ -1465,6 +1608,7 @@ function renderCumulativeChart(messages) {
1465
1608
  },
1466
1609
  },
1467
1610
  });
1611
+ markCompactions(charts.cumulative, messages, c);
1468
1612
  }
1469
1613
 
1470
1614
  function renderTokenBreakdownChart(messages) {
@@ -1475,47 +1619,14 @@ function renderTokenBreakdownChart(messages) {
1475
1619
  const c = getChartColors();
1476
1620
  const defaults = chartDefaults();
1477
1621
 
1478
- // Subagent bars render translucent so they read as folded-in usage, not main-loop turns.
1479
- const barColors = (hex) => {
1480
- const faded = hexToRgba(hex, 0.45);
1481
- return messages.map((m) => (m._subagent ? faded : hex));
1482
- };
1483
-
1484
1622
  charts.tokenBreakdown = new Chart(canvas, {
1485
1623
  type: 'bar',
1486
- data: {
1487
- labels: messages.map((m) => m.index),
1488
- datasets: [
1489
- {
1490
- label: 'Input',
1491
- data: messages.map((m) => m.inputTokens),
1492
- backgroundColor: barColors(c.chart1),
1493
- borderRadius: 2,
1494
- },
1495
- {
1496
- label: 'Output',
1497
- data: messages.map((m) => m.outputTokens),
1498
- backgroundColor: barColors(c.chart2),
1499
- borderRadius: 2,
1500
- },
1501
- {
1502
- label: 'Cache Create',
1503
- data: messages.map((m) => m.cacheCreationTokens),
1504
- backgroundColor: barColors(c.chart3),
1505
- borderRadius: 2,
1506
- },
1507
- {
1508
- label: 'Cache Read',
1509
- data: messages.map((m) => m.cacheReadTokens),
1510
- backgroundColor: barColors(c.chart4),
1511
- borderRadius: 2,
1512
- },
1513
- ],
1514
- },
1624
+ data: tokenBreakdownChartData(messages, c),
1625
+ plugins: [compactionMarkers],
1515
1626
  options: {
1516
1627
  ...defaults,
1517
1628
  plugins: {
1518
- ...withTooltip(defaults, { title: (items) => messageTooltipTitle(messages, items) }),
1629
+ ...withTooltip(defaults, { title: (items) => messageTooltipTitle(detailSlice, items) }),
1519
1630
  legend: {
1520
1631
  display: true,
1521
1632
  position: 'bottom',
@@ -1539,8 +1650,268 @@ function renderTokenBreakdownChart(messages) {
1539
1650
  },
1540
1651
  },
1541
1652
  });
1653
+ markCompactions(charts.tokenBreakdown, messages, c);
1654
+ }
1655
+
1656
+ // #region RANGE BRUSH
1657
+ // Long sessions squash both per-message charts into noise, so the detail view shows a window of
1658
+ // the last DETAIL_WINDOW messages by default and lets the user drag that window across an overview
1659
+ // of the whole session. State lives outside the DOM because renderDetail rebuilds its innerHTML on
1660
+ // every refresh; a window that sits at the tail stays there so new messages scroll into view.
1661
+ const DETAIL_WINDOW_PRESETS = [25, 50, 100, 200];
1662
+ const DETAIL_WINDOW = DETAIL_WINDOW_PRESETS[0];
1663
+ const DETAIL_WINDOW_MIN = 10;
1664
+ let detailRange = null;
1665
+ let detailSlice = [];
1666
+
1667
+ function median(sorted) {
1668
+ return sorted[Math.floor(sorted.length / 2)];
1669
+ }
1670
+
1671
+ // A cache burst is a main-loop turn that wrote far more cache than the session normally does:
1672
+ // the prompt prefix was invalidated (edited system prompt, compaction, new tool set, long gap) and
1673
+ // had to be re-cached. Relative to the session median so a chatty session and a heavy one both
1674
+ // surface their own outliers; the absolute floor drops noise in tiny sessions.
1675
+ const CACHE_BURST_RATIO = 4;
1676
+ const CACHE_BURST_MIN_TOKENS = 20000;
1677
+
1678
+ // A compaction explains the burst on the turn that follows it, so that turn is labelled
1679
+ // `compaction`; `burst` is left for the re-caches with no boundary behind them.
1680
+ function notableEvents(messages) {
1681
+ const writes = messages
1682
+ .filter((m) => !m._subagent && m.cacheCreationTokens > 0)
1683
+ .map((m) => m.cacheCreationTokens)
1684
+ .sort((a, b) => a - b);
1685
+ const threshold = writes.length < 5 ? Infinity : Math.max(CACHE_BURST_MIN_TOKENS, median(writes) * CACHE_BURST_RATIO);
1686
+ return messages.flatMap((m, i) => {
1687
+ if (m.compaction) {
1688
+ const c = m.compaction;
1689
+ const tip = `#${m.index} · ${c.trigger} compaction ${formatTokens(c.preTokens)} → ${formatTokens(c.postTokens)} · ~${formatCost(c.estCost)}`;
1690
+ return [{ i, kind: 'compaction', tip }];
1691
+ }
1692
+ if (!m._subagent && m.cacheCreationTokens >= threshold) {
1693
+ return [{ i, kind: 'burst', tip: `#${m.index} · cache write ${formatTokens(m.cacheCreationTokens)}` }];
1694
+ }
1695
+ return [];
1696
+ });
1697
+ }
1698
+
1699
+ function clampRange(start, end, total) {
1700
+ const s = Math.max(0, Math.min(start, total - DETAIL_WINDOW_MIN));
1701
+ return { start: s, end: Math.max(s + DETAIL_WINDOW_MIN, Math.min(end, total)) };
1542
1702
  }
1543
1703
 
1704
+ function detailRangeFor(d) {
1705
+ const total = d.messages.length;
1706
+ const prev = detailRange?.key === d.sessionId ? detailRange : null;
1707
+ const size = prev ? prev.end - prev.start : DETAIL_WINDOW;
1708
+ const atTail = !prev || prev.end === prev.total;
1709
+ const start = atTail ? total - size : prev.start;
1710
+ detailRange = { key: d.sessionId, total, ...clampRange(start, start + size, total) };
1711
+ return detailRange;
1712
+ }
1713
+
1714
+ function applyDetailRange(messages, range) {
1715
+ detailSlice = messages.slice(range.start, range.end);
1716
+ renderMessageRows(detailSlice, messages.length);
1717
+ const c = getChartColors();
1718
+ if (charts.cumulative && charts.tokenBreakdown) {
1719
+ charts.cumulative.data = cumulativeChartData(detailSlice, c);
1720
+ charts.tokenBreakdown.data = tokenBreakdownChartData(detailSlice, c);
1721
+ for (const chart of [charts.cumulative, charts.tokenBreakdown]) {
1722
+ markCompactions(chart, detailSlice, c);
1723
+ chart.update('none');
1724
+ }
1725
+ } else {
1726
+ renderCumulativeChart(detailSlice);
1727
+ renderTokenBreakdownChart(detailSlice);
1728
+ }
1729
+ }
1730
+
1731
+ function rangeBrushHtml(total) {
1732
+ if (total <= DETAIL_WINDOW) return '';
1733
+ const presets = DETAIL_WINDOW_PRESETS.filter((n) => n < total)
1734
+ .map((n) => `<button type="button" class="rb-preset" data-size="${n}">${n}</button>`)
1735
+ .join('');
1736
+ return `
1737
+ <div class="range-brush" id="rangeBrush">
1738
+ <div class="rb-head">
1739
+ <span class="rb-label"><span class="rb-scope"></span><span class="rb-burst-count" hidden><i></i></span></span>
1740
+ <div class="rb-presets" role="group" aria-label="Window size">
1741
+ ${presets}
1742
+ <button type="button" class="rb-preset" data-size="all">All</button>
1743
+ </div>
1744
+ </div>
1745
+ <div class="rb-track" tabindex="0" role="slider" aria-label="Visible message range"
1746
+ aria-valuemin="1" aria-valuemax="${esc(total)}">
1747
+ ${rangeOverviewSvg}
1748
+ <div class="rb-bursts"></div>
1749
+ <div class="rb-window">
1750
+ <div class="rb-handle rb-handle-left" data-edge="start"></div>
1751
+ <div class="rb-handle rb-handle-right" data-edge="end"></div>
1752
+ </div>
1753
+ </div>
1754
+ </div>`;
1755
+ }
1756
+
1757
+ // The overview shares the brush's percentage coordinate space, so it stretches with the track and
1758
+ // needs no resize handling. Points are filled in by initRangeBrush.
1759
+ const rangeOverviewSvg =
1760
+ '<svg class="rb-overview" viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><polygon /><polyline /></svg>';
1761
+
1762
+ function initRangeBrush(messages) {
1763
+ const root = document.getElementById('rangeBrush');
1764
+ if (!root) return;
1765
+ const total = messages.length;
1766
+ const range = detailRange;
1767
+ const q = (sel) => root.querySelector(sel);
1768
+ const track = q('.rb-track');
1769
+ const win = q('.rb-window');
1770
+ const scope = q('.rb-scope');
1771
+ const burstCount = q('.rb-burst-count');
1772
+ const presets = [...root.querySelectorAll('.rb-preset')].map((el) => ({
1773
+ el,
1774
+ size: el.dataset.size === 'all' ? total : Number(el.dataset.size),
1775
+ }));
1776
+
1777
+ drawRangeOverview(q('.rb-overview'), messages);
1778
+
1779
+ const markers = notableEvents(messages);
1780
+ const burstsEl = q('.rb-bursts');
1781
+ burstsEl.innerHTML = markers
1782
+ .map(
1783
+ (k) =>
1784
+ `<button type="button" class="rb-burst${k.kind === 'compaction' ? ' compact' : ''}" data-i="${esc(String(k.i))}" style="left:${((k.i + 0.5) / total) * 100}%" title="${esc(k.tip)}" aria-label="${esc(k.tip)}"></button>`,
1785
+ )
1786
+ .join('');
1787
+ const burstEls = [...burstsEl.children].map((el, k) => ({ el, i: markers[k].i }));
1788
+ const counts = [
1789
+ ['burst', 'cache burst', ''],
1790
+ ['compaction', 'compaction', ' class="compact"'],
1791
+ ].flatMap(([kind, label, attr]) => {
1792
+ const n = markers.filter((k) => k.kind === kind).length;
1793
+ return n ? [`<span${attr}><i></i>${n} ${label}${n === 1 ? '' : 's'}</span>`] : [];
1794
+ });
1795
+ if (counts.length) {
1796
+ burstCount.hidden = false;
1797
+ burstCount.innerHTML = counts.join('<span class="rb-sep">·</span>');
1798
+ }
1799
+
1800
+ const layout = () => {
1801
+ const size = range.end - range.start;
1802
+ win.style.left = `${(range.start / total) * 100}%`;
1803
+ win.style.width = `${(size / total) * 100}%`;
1804
+ const text =
1805
+ size === total
1806
+ ? `All ${total} messages`
1807
+ : `Messages #${messages[range.start].index} – #${messages[range.end - 1].index} · ${size} of ${total}`;
1808
+ scope.textContent = text;
1809
+ track.setAttribute('aria-valuenow', String(range.start + 1));
1810
+ track.setAttribute('aria-valuetext', text);
1811
+ for (const p of presets) p.el.classList.toggle('on', p.size === size);
1812
+ for (const b of burstEls) b.el.classList.toggle('in', b.i >= range.start && b.i < range.end);
1813
+ };
1814
+
1815
+ // Pointer and wheel events outrun the frame rate, so range writes are coalesced into one paint.
1816
+ let frame = 0;
1817
+ const setRange = (from, to) => {
1818
+ const next = clampRange(from, to, total);
1819
+ if (next.start === range.start && next.end === range.end) return;
1820
+ Object.assign(range, next);
1821
+ if (frame) return;
1822
+ frame = requestAnimationFrame(() => {
1823
+ frame = 0;
1824
+ layout();
1825
+ applyDetailRange(messages, range);
1826
+ });
1827
+ };
1828
+ const size = () => range.end - range.start;
1829
+ const step = () => Math.max(1, Math.round(size() / 10));
1830
+ const pan = (delta) => setRange(range.start + delta, range.end + delta);
1831
+ const centerOn = (i) => {
1832
+ const start = Math.max(0, Math.min(i - Math.floor(size() / 2), total - size()));
1833
+ setRange(start, start + size());
1834
+ };
1835
+ const resize = (n) => {
1836
+ const end = Math.min(total, Math.max(range.end, n));
1837
+ setRange(end - n, end);
1838
+ };
1839
+
1840
+ // Pointer capture keeps a fast drag alive after the cursor leaves the thin track. The rect is
1841
+ // read once per drag: reading it per move right after writing the window's style would thrash.
1842
+ track.addEventListener('pointerdown', (e) => {
1843
+ if (e.button !== 0) return;
1844
+ e.preventDefault();
1845
+ track.focus({ preventScroll: true });
1846
+ const rect = track.getBoundingClientRect();
1847
+ const perPx = total / rect.width;
1848
+ const edge = e.target.dataset?.edge;
1849
+ if (!edge && e.target !== win) centerOn(Math.round((e.clientX - rect.left) * perPx));
1850
+ const origin = { x: e.clientX, start: range.start, end: range.end };
1851
+ track.classList.add('dragging');
1852
+ track.setPointerCapture(e.pointerId);
1853
+ const move = (ev) => {
1854
+ const delta = Math.round((ev.clientX - origin.x) * perPx);
1855
+ if (edge === 'start') setRange(origin.start + delta, origin.end);
1856
+ else if (edge === 'end') setRange(origin.start, origin.end + delta);
1857
+ else {
1858
+ const n = origin.end - origin.start;
1859
+ const start = Math.max(0, Math.min(origin.start + delta, total - n));
1860
+ setRange(start, start + n);
1861
+ }
1862
+ };
1863
+ const up = () => {
1864
+ track.classList.remove('dragging');
1865
+ track.removeEventListener('pointermove', move);
1866
+ track.removeEventListener('pointerup', up);
1867
+ track.removeEventListener('pointercancel', up);
1868
+ };
1869
+ track.addEventListener('pointermove', move);
1870
+ track.addEventListener('pointerup', up);
1871
+ track.addEventListener('pointercancel', up);
1872
+ });
1873
+
1874
+ track.addEventListener(
1875
+ 'wheel',
1876
+ (e) => {
1877
+ e.preventDefault();
1878
+ pan((e.deltaY || e.deltaX) > 0 ? step() : -step());
1879
+ },
1880
+ { passive: false },
1881
+ );
1882
+
1883
+ track.addEventListener('keydown', (e) => {
1884
+ const n = e.shiftKey ? size() : step();
1885
+ if (e.key === 'ArrowLeft') pan(-n);
1886
+ else if (e.key === 'ArrowRight') pan(n);
1887
+ else if (e.key === 'Home') setRange(0, size());
1888
+ else if (e.key === 'End') setRange(total - size(), total);
1889
+ else return;
1890
+ e.preventDefault();
1891
+ });
1892
+
1893
+ for (const p of presets) p.el.addEventListener('click', () => resize(p.size));
1894
+
1895
+ burstsEl.addEventListener('pointerdown', (e) => {
1896
+ const b = e.target.closest('.rb-burst');
1897
+ if (!b) return;
1898
+ e.stopPropagation();
1899
+ e.preventDefault();
1900
+ centerOn(Number(b.dataset.i));
1901
+ });
1902
+
1903
+ layout();
1904
+ }
1905
+
1906
+ function drawRangeOverview(svg, messages) {
1907
+ const n = messages.length;
1908
+ const max = messages[n - 1]?.cumulativeCost || 1;
1909
+ const pts = messages.map((m, i) => `${(i / Math.max(1, n - 1)) * 1000},${100 - (m.cumulativeCost / max) * 96 - 2}`);
1910
+ svg.querySelector('polyline').setAttribute('points', pts.join(' '));
1911
+ svg.querySelector('polygon').setAttribute('points', `0,100 ${pts.join(' ')} 1000,100`);
1912
+ }
1913
+ // #endregion
1914
+
1544
1915
  function renderTokenSplitChart(t) {
1545
1916
  const canvas = document.getElementById('tokenSplitChart');
1546
1917
  if (!canvas) return;
package/public/style.css CHANGED
@@ -29,6 +29,7 @@
29
29
  --chart-4: #f0b429;
30
30
  --chart-5: #b784f5;
31
31
  --chart-6: #fb7185;
32
+ --compact: var(--chart-5);
32
33
  }
33
34
 
34
35
  /* #endregion */
@@ -780,6 +781,242 @@ body {
780
781
 
781
782
  /* #endregion */
782
783
 
784
+ /* #region RANGE BRUSH */
785
+
786
+ .range-brush {
787
+ background: var(--bg-surface);
788
+ border: 1px solid var(--border);
789
+ border-radius: 6px;
790
+ padding: 10px 16px 12px;
791
+ margin: -8px 0 20px;
792
+ }
793
+
794
+ .rb-head {
795
+ display: flex;
796
+ align-items: center;
797
+ justify-content: space-between;
798
+ gap: 12px;
799
+ margin-bottom: 8px;
800
+ }
801
+
802
+ .rb-label {
803
+ font-size: 11px;
804
+ color: var(--text-muted);
805
+ text-transform: uppercase;
806
+ letter-spacing: 0.05em;
807
+ white-space: nowrap;
808
+ overflow: hidden;
809
+ text-overflow: ellipsis;
810
+ }
811
+
812
+ .rb-burst-count {
813
+ margin-left: 10px;
814
+ color: var(--warning);
815
+ }
816
+
817
+ .rb-burst-count i {
818
+ display: inline-block;
819
+ width: 6px;
820
+ height: 6px;
821
+ border-radius: 50%;
822
+ background: var(--warning);
823
+ margin-right: 5px;
824
+ vertical-align: middle;
825
+ }
826
+
827
+ .rb-burst-count .compact {
828
+ color: var(--compact);
829
+ }
830
+
831
+ .rb-burst-count .compact i,
832
+ .rb-burst.compact::after {
833
+ border-radius: 1px;
834
+ transform: rotate(45deg);
835
+ background: var(--compact);
836
+ }
837
+
838
+ .rb-burst-count .rb-sep {
839
+ margin: 0 6px;
840
+ color: var(--text-muted);
841
+ }
842
+
843
+ .rb-presets {
844
+ display: flex;
845
+ gap: 4px;
846
+ }
847
+
848
+ .rb-preset {
849
+ font: inherit;
850
+ font-size: 10px;
851
+ letter-spacing: 0.03em;
852
+ color: var(--text-tertiary);
853
+ background: transparent;
854
+ border: 1px solid var(--border);
855
+ border-radius: 4px;
856
+ padding: 2px 8px;
857
+ cursor: pointer;
858
+ }
859
+
860
+ .rb-preset:hover {
861
+ color: var(--text-primary);
862
+ border-color: var(--text-muted);
863
+ }
864
+
865
+ .rb-preset.on {
866
+ color: var(--accent-text);
867
+ border-color: var(--accent);
868
+ background: var(--accent-dim);
869
+ }
870
+
871
+ .rb-track {
872
+ position: relative;
873
+ height: 44px;
874
+ border-radius: 4px;
875
+ background: var(--bg-deep);
876
+ border: 1px solid var(--border);
877
+ overflow: hidden;
878
+ cursor: crosshair;
879
+ user-select: none;
880
+ touch-action: none;
881
+ outline: none;
882
+ }
883
+
884
+ .rb-track:focus-visible {
885
+ border-color: var(--accent);
886
+ box-shadow: 0 0 0 2px var(--accent-dim);
887
+ }
888
+
889
+ .rb-overview {
890
+ position: absolute;
891
+ inset: 0;
892
+ width: 100%;
893
+ height: 100%;
894
+ display: block;
895
+ }
896
+
897
+ .rb-overview polygon {
898
+ fill: var(--chart-fill);
899
+ }
900
+
901
+ .rb-overview polyline {
902
+ fill: none;
903
+ stroke: var(--accent);
904
+ stroke-width: 1.5;
905
+ vector-effect: non-scaling-stroke;
906
+ }
907
+
908
+ .rb-bursts {
909
+ position: absolute;
910
+ inset: 0;
911
+ pointer-events: none;
912
+ }
913
+
914
+ .rb-burst {
915
+ position: absolute;
916
+ top: 0;
917
+ bottom: 0;
918
+ width: 7px;
919
+ margin-left: -3.5px;
920
+ padding: 0;
921
+ border: 0;
922
+ background: transparent;
923
+ cursor: pointer;
924
+ pointer-events: auto;
925
+ }
926
+
927
+ .rb-burst::before {
928
+ content: '';
929
+ position: absolute;
930
+ top: 0;
931
+ bottom: 0;
932
+ left: 3px;
933
+ width: 1px;
934
+ background: var(--warning);
935
+ opacity: 0.55;
936
+ }
937
+
938
+ .rb-burst::after {
939
+ content: '';
940
+ position: absolute;
941
+ top: 3px;
942
+ left: 1px;
943
+ width: 5px;
944
+ height: 5px;
945
+ border-radius: 50%;
946
+ background: var(--warning);
947
+ }
948
+
949
+ .rb-burst.in::before,
950
+ .rb-burst:hover::before {
951
+ opacity: 1;
952
+ width: 2px;
953
+ left: 2.5px;
954
+ }
955
+
956
+ .rb-burst.compact::before {
957
+ background: var(--compact);
958
+ }
959
+
960
+ /* The shade outside the window is the window's own shadow, clipped by the track. */
961
+ .rb-window {
962
+ position: absolute;
963
+ top: 0;
964
+ bottom: 0;
965
+ border: 1px solid var(--accent);
966
+ border-radius: 3px;
967
+ background: var(--accent-dim);
968
+ box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.45);
969
+ cursor: grab;
970
+ box-sizing: border-box;
971
+ min-width: 8px;
972
+ }
973
+
974
+ body.light .rb-window {
975
+ box-shadow: 0 0 0 9999px rgba(255, 255, 255, 0.55);
976
+ }
977
+
978
+ .rb-track.dragging,
979
+ .rb-track.dragging .rb-window {
980
+ cursor: grabbing;
981
+ }
982
+
983
+ .rb-handle {
984
+ position: absolute;
985
+ top: 0;
986
+ bottom: 0;
987
+ width: 10px;
988
+ cursor: ew-resize;
989
+ }
990
+
991
+ .rb-handle::after {
992
+ content: '';
993
+ position: absolute;
994
+ top: 50%;
995
+ width: 3px;
996
+ height: 14px;
997
+ margin-top: -7px;
998
+ border-radius: 2px;
999
+ background: var(--accent);
1000
+ }
1001
+
1002
+ .rb-handle-left {
1003
+ left: -5px;
1004
+ }
1005
+
1006
+ .rb-handle-left::after {
1007
+ left: 3px;
1008
+ }
1009
+
1010
+ .rb-handle-right {
1011
+ right: -5px;
1012
+ }
1013
+
1014
+ .rb-handle-right::after {
1015
+ right: 3px;
1016
+ }
1017
+
1018
+ /* #endregion */
1019
+
783
1020
  /* #region TABLE */
784
1021
 
785
1022
  .section-title {
@@ -993,32 +1230,47 @@ body {
993
1230
  font-size: 10px;
994
1231
  }
995
1232
 
1233
+ .compaction-tag {
1234
+ text-transform: uppercase;
1235
+ color: var(--compact);
1236
+ background: color-mix(in srgb, var(--compact) 14%, transparent);
1237
+ white-space: nowrap;
1238
+ }
1239
+
1240
+ .compaction-row td {
1241
+ background: color-mix(in srgb, var(--compact) 6%, transparent);
1242
+ color: var(--text-muted);
1243
+ }
1244
+
1245
+ .compaction-row td:first-child {
1246
+ border-left: 2px solid var(--compact);
1247
+ }
1248
+
996
1249
  /* #endregion */
997
1250
 
998
1251
  /* #region SUBAGENT */
999
1252
 
1000
- .subagent-tag {
1253
+ .subagent-tag,
1254
+ .tool-tag,
1255
+ .compaction-tag {
1001
1256
  font-size: 9px;
1002
- text-transform: uppercase;
1003
1257
  letter-spacing: 0.03em;
1004
- color: var(--text-muted);
1005
- background: var(--bg-hover);
1006
1258
  padding: 1px 5px;
1007
1259
  border-radius: 3px;
1008
1260
  margin-left: 4px;
1009
1261
  vertical-align: middle;
1010
1262
  }
1011
1263
 
1264
+ .subagent-tag {
1265
+ text-transform: uppercase;
1266
+ color: var(--text-muted);
1267
+ background: var(--bg-hover);
1268
+ }
1269
+
1012
1270
  .tool-tag {
1013
- font-size: 9px;
1014
1271
  text-transform: lowercase;
1015
- letter-spacing: 0.03em;
1016
1272
  color: var(--chart-2, #60a5fa);
1017
1273
  background: rgba(96, 165, 250, 0.12);
1018
- padding: 1px 5px;
1019
- border-radius: 3px;
1020
- margin-left: 4px;
1021
- vertical-align: middle;
1022
1274
  }
1023
1275
 
1024
1276
  /* #endregion */
package/server.js CHANGED
@@ -209,6 +209,44 @@ function calculateEntryCost(data, pricing) {
209
209
  return calculateCostForModel(data.message.usage, model, pricing, speed);
210
210
  }
211
211
 
212
+ // The summarization call behind a compact_boundary is not logged with usage, so its cost is an
213
+ // estimate: the whole pre-compaction context read from cache, and a summary no larger than the
214
+ // post-compaction context written out.
215
+ function estimateCompactionCost(meta, model, pricing) {
216
+ return calculateCostForModel(
217
+ { output_tokens: meta.postTokens, cache_read_input_tokens: meta.preTokens },
218
+ model, pricing);
219
+ }
220
+
221
+ function compactionFacts(parsed) {
222
+ const meta = parsed.compactMetadata || {};
223
+ const preTokens = meta.preTokens || 0;
224
+ const postTokens = meta.postTokens || 0;
225
+ return {
226
+ timestamp: parsed.timestamp,
227
+ trigger: meta.trigger || 'unknown',
228
+ preTokens,
229
+ postTokens,
230
+ droppedTokens: Math.max(0, preTokens - postTokens),
231
+ durationMs: meta.durationMs || 0,
232
+ };
233
+ }
234
+
235
+ // The first turn after a boundary rebuilds the prompt cache from the summary, so its cache
236
+ // creation is spend the compaction caused. It is already in the session total; the record only
237
+ // attributes it. Models without pricing get null, not a zero that reads as "free".
238
+ function priceCompaction(facts, msg, pricing) {
239
+ const model = isRealModel(msg.model) ? msg.model : null;
240
+ return {
241
+ ...facts,
242
+ estCost: model ? estimateCompactionCost(facts, model, pricing) : null,
243
+ rewarmTokens: msg.cacheCreationTokens,
244
+ rewarmCost: model
245
+ ? calculateCostForModel({ cache_creation_input_tokens: msg.cacheCreationTokens }, model, pricing, msg.speed)
246
+ : null,
247
+ };
248
+ }
249
+
212
250
  // #endregion
213
251
 
214
252
  // #region DATA_AGGREGATION
@@ -372,27 +410,68 @@ function getSessionIdFromFile(filePath) {
372
410
  return path.basename(filePath, '.jsonl');
373
411
  }
374
412
 
413
+ function readdirSafe(dir) {
414
+ try { return fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
415
+ }
416
+
417
+ // Agents sit at subagents/agent-*.jsonl, but a Workflow run nests its own under
418
+ // subagents/workflows/<wfId>/ — and a workflow that starts a workflow nests deeper still, so walk
419
+ // rather than hard-code the depth. Descending only into a listed entry also keeps the common
420
+ // no-workflow session at one readdir.
421
+ function collectAgents(dir, workflowId, out) {
422
+ for (const e of readdirSafe(dir)) {
423
+ if (e.isDirectory()) {
424
+ if (e.name !== 'workflows') continue;
425
+ const runsDir = path.join(dir, e.name);
426
+ for (const run of readdirSafe(runsDir)) {
427
+ if (run.isDirectory()) collectAgents(path.join(runsDir, run.name), run.name, out);
428
+ }
429
+ continue;
430
+ }
431
+ if (!e.name.endsWith('.jsonl')) continue;
432
+ const agentId = e.name.replace('.jsonl', '');
433
+ let meta = {};
434
+ try { meta = JSON.parse(fs.readFileSync(path.join(dir, `${agentId}.meta.json`), 'utf-8')); } catch { /* no meta */ }
435
+ out.push({
436
+ agentId,
437
+ filePath: path.join(dir, e.name),
438
+ agentType: meta.agentType || 'unknown',
439
+ description: meta.description || '',
440
+ workflowId,
441
+ });
442
+ }
443
+ }
444
+
375
445
  function scanSubagentDir(sessionDir) {
376
- const subagentsDir = path.join(sessionDir, 'subagents');
377
446
  const result = [];
378
- try {
379
- for (const f of fs.readdirSync(subagentsDir)) {
380
- if (!f.endsWith('.jsonl')) continue;
381
- const agentId = f.replace('.jsonl', '');
382
- const metaPath = path.join(subagentsDir, `${agentId}.meta.json`);
383
- let meta = {};
384
- try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8')); } catch { /* no meta */ }
385
- result.push({
386
- agentId,
387
- filePath: path.join(subagentsDir, f),
388
- agentType: meta.agentType || 'unknown',
389
- description: meta.description || '',
390
- });
391
- }
392
- } catch { /* dir doesn't exist or unreadable */ }
447
+ collectAgents(path.join(sessionDir, 'subagents'), null, result);
393
448
  return result;
394
449
  }
395
450
 
451
+ // The run's script is saved as <name>-<wfId>.js under a session dir keyed by the workflow's cwd,
452
+ // which need not be the project the session file lives in — so the session's own project dir is
453
+ // only the likely home, and a miss falls back to sweeping the rest.
454
+ function findWorkflowNames(sessionId, wantedIds, likelyProjectDir) {
455
+ const names = new Map();
456
+ const wanted = new Set(wantedIds);
457
+ const scan = (projectDir) => {
458
+ for (const f of readdirSafe(path.join(projectDir, sessionId, 'workflows', 'scripts'))) {
459
+ const m = f.name.match(/^(.*)-(wf_.+)\.js$/);
460
+ if (m && wanted.has(m[2])) names.set(m[2], m[1]);
461
+ }
462
+ return names.size === wanted.size;
463
+ };
464
+ for (const baseDir of getProjectsDirs()) {
465
+ if (scan(path.join(baseDir, likelyProjectDir))) return names;
466
+ }
467
+ for (const baseDir of getProjectsDirs()) {
468
+ for (const e of readdirSafe(baseDir)) {
469
+ if (e.isDirectory() && e.name !== likelyProjectDir && scan(path.join(baseDir, e.name))) return names;
470
+ }
471
+ }
472
+ return names;
473
+ }
474
+
396
475
  // `<synthetic>` and friends are Claude Code bookkeeping entries, not models the user chose.
397
476
  function isRealModel(model) {
398
477
  return !!model && !model.startsWith('<');
@@ -408,6 +487,7 @@ async function loadSubagentData(subagentInfos, pricing) {
408
487
  agentId: info.agentId,
409
488
  agentType: info.agentType,
410
489
  description: info.description,
490
+ workflowId: info.workflowId || null,
411
491
  totalCost: 0,
412
492
  inputTokens: 0, outputTokens: 0,
413
493
  cacheCreationTokens: 0, cacheReadTokens: 0,
@@ -466,6 +546,9 @@ async function loadProjectData(files, pricing) {
466
546
  });
467
547
  }
468
548
  const session = sessions.get(sessionId);
549
+ // A boundary is attributed to the next counted turn, so the message list is the only record
550
+ // of compactions; a boundary with no turn after it has nothing to price and is dropped.
551
+ let pendingCompaction = null;
469
552
 
470
553
  await processJSONLFile(file, async (line) => {
471
554
  let parsed;
@@ -476,6 +559,11 @@ async function loadProjectData(files, pricing) {
476
559
  return;
477
560
  }
478
561
 
562
+ if (parsed.type === 'system' && parsed.subtype === 'compact_boundary' && parsed.timestamp) {
563
+ pendingCompaction = compactionFacts(parsed);
564
+ return;
565
+ }
566
+
479
567
  if (!parsed.message?.usage?.input_tokens && parsed.message?.usage?.input_tokens !== 0) return;
480
568
  if (!parsed.timestamp) return;
481
569
 
@@ -518,6 +606,10 @@ async function loadProjectData(files, pricing) {
518
606
  speed: usage.speed || 'standard',
519
607
  tools: extractTools(parsed.message?.content),
520
608
  };
609
+ if (pendingCompaction) {
610
+ msg.compaction = priceCompaction(pendingCompaction, msg, pricing);
611
+ pendingCompaction = null;
612
+ }
521
613
  session.messages.push(msg);
522
614
  if (hash) seen.set(hash, msg);
523
615
 
@@ -553,7 +645,7 @@ async function loadProjectData(files, pricing) {
553
645
  cacheCreationTokens: sa.cacheCreationTokens,
554
646
  cacheReadTokens: sa.cacheReadTokens,
555
647
  speed: 'standard',
556
- _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount },
648
+ _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount, workflowId: sa.workflowId },
557
649
  });
558
650
  }
559
651
  }
@@ -664,6 +756,21 @@ function summarizeMessages(msgs) {
664
756
  return sum;
665
757
  }
666
758
 
759
+ function summarizeCompactions(msgs) {
760
+ const sum = { count: 0, auto: 0, totalCost: 0, estCost: 0, rewarmCost: 0, rewarmTokens: 0, droppedTokens: 0 };
761
+ for (const { compaction: c } of msgs) {
762
+ if (!c) continue;
763
+ sum.count++;
764
+ if (c.trigger === 'auto') sum.auto++;
765
+ sum.estCost += c.estCost || 0;
766
+ sum.rewarmCost += c.rewarmCost || 0;
767
+ sum.rewarmTokens += c.rewarmTokens;
768
+ sum.droppedTokens += c.droppedTokens;
769
+ }
770
+ sum.totalCost = sum.estCost + sum.rewarmCost;
771
+ return sum;
772
+ }
773
+
667
774
  async function getOverviewData(range, projectFilter) {
668
775
  const cacheKey = `overview_${rangeKey(range)}_${projectFilter || 'all'}`;
669
776
  const cached = getCache(cacheKey);
@@ -866,6 +973,7 @@ async function getProjectSessionsData(encodedPath, range) {
866
973
  firstTimestamp: session.firstTimestamp,
867
974
  lastTimestamp: session.lastTimestamp,
868
975
  durationMinutes: Math.round(durationMs / 60000),
976
+ compactions: summarizeCompactions(msgs),
869
977
  });
870
978
  }
871
979
 
@@ -935,6 +1043,30 @@ async function getSessionDetailData(sessionId) {
935
1043
  return { ...m, index: i + 1, cumulativeCost: cumulative };
936
1044
  });
937
1045
 
1046
+ // One folded-in message per agent, and `messages` is already sorted, so a group's ends are
1047
+ // the run's first and last agent.
1048
+ const byWorkflow = new Map();
1049
+ for (const m of messages) {
1050
+ const wf = m._subagent?.workflowId;
1051
+ if (!wf) continue;
1052
+ if (!byWorkflow.has(wf)) byWorkflow.set(wf, []);
1053
+ byWorkflow.get(wf).push(m);
1054
+ }
1055
+ const names = byWorkflow.size > 0
1056
+ ? findWorkflowNames(sessionId, byWorkflow.keys(), encodedPath)
1057
+ : new Map();
1058
+ const workflows = [...byWorkflow].map(([id, msgs]) => {
1059
+ const { messageCount, ...totals } = summarizeMessages(msgs);
1060
+ return {
1061
+ id,
1062
+ name: names.get(id) || id,
1063
+ agents: messageCount,
1064
+ firstTimestamp: msgs[0].timestamp,
1065
+ lastTimestamp: msgs.at(-1).timestamp,
1066
+ ...totals,
1067
+ };
1068
+ }).sort((a, b) => b.totalCost - a.totalCost);
1069
+
938
1070
  const result = {
939
1071
  sessionId,
940
1072
  customTitle: session.customTitle,
@@ -949,6 +1081,8 @@ async function getSessionDetailData(sessionId) {
949
1081
  firstPrompt: session.firstPrompt,
950
1082
  firstTimestamp: session.firstTimestamp,
951
1083
  lastTimestamp: session.lastTimestamp,
1084
+ workflows,
1085
+ compactions: summarizeCompactions(messages),
952
1086
  messages,
953
1087
  };
954
1088
 
@@ -1113,6 +1247,8 @@ async function getInsightsData(range, projectFilter) {
1113
1247
  const toolCounts = {};
1114
1248
  let mainCost = 0;
1115
1249
  let subagentCost = 0;
1250
+ let workflowCost = 0;
1251
+ const workflowRuns = new Set();
1116
1252
  const weekly = {};
1117
1253
 
1118
1254
  // getModelPricing falls back to a linear scan of the whole LiteLLM map on a miss, so resolve
@@ -1136,6 +1272,10 @@ async function getInsightsData(range, projectFilter) {
1136
1272
 
1137
1273
  if (m._subagent) {
1138
1274
  subagentCost += m.cost;
1275
+ if (m._subagent.workflowId) {
1276
+ workflowCost += m.cost;
1277
+ workflowRuns.add(m._subagent.workflowId);
1278
+ }
1139
1279
  } else {
1140
1280
  mainCost += m.cost;
1141
1281
  if (m.tools) for (const t of m.tools) toolCounts[t] = (toolCounts[t] || 0) + 1;
@@ -1175,7 +1315,9 @@ async function getInsightsData(range, projectFilter) {
1175
1315
  .map(([name, count]) => ({ name, count }))
1176
1316
  .sort((a, b) => b.count - a.count)
1177
1317
  .slice(0, MAX_TOOLS),
1178
- subagents: { mainCost, subagentCost },
1318
+ // workflowCost is the slice of subagentCost spent inside Workflow runs, not a third peer —
1319
+ // mainCost + subagentCost is still the whole.
1320
+ subagents: { mainCost, subagentCost, workflowCost, workflowRuns: workflowRuns.size },
1179
1321
  weekly: Object.entries(weekly)
1180
1322
  .sort(([a], [b]) => a.localeCompare(b))
1181
1323
  .map(([weekStart, cost]) => ({ weekStart, cost })),