claude-code-cost 0.19.1 → 0.21.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.19.1",
3
+ "version": "0.21.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/app.js CHANGED
@@ -877,7 +877,7 @@ function renderInsights() {
877
877
  <div class="card-label">Subagent Share</div>
878
878
  <div class="card-value">${subPct}%</div>
879
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>
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>
881
881
  </div>
882
882
  </div>
883
883
 
@@ -1015,7 +1015,7 @@ function renderSessions() {
1015
1015
  <td class="truncate" title="${esc(s.customTitle || s.firstPrompt || s.sessionId)}">${esc(s.customTitle || s.firstPrompt || s.sessionId)}</td>
1016
1016
  <td class="cost-cell">${formatCost(s.totalCost)}</td>
1017
1017
  <td>${formatTokens(s.totalTokens)}</td>
1018
- <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>
1019
1019
  <td class="muted">${formatDuration(s.durationMinutes)}</td>
1020
1020
  <td><span class="model-badge">${esc(shortModel(s.primaryModel))}</span></td>
1021
1021
  <td class="muted">${timeAgo(s.lastTimestamp)}</td>
@@ -1090,9 +1090,12 @@ function renderDetail() {
1090
1090
  <div class="detail-label">Models</div>
1091
1091
  <div class="detail-value">${esc(d.models.map((m) => shortModel(m)).join(', '))}</div>
1092
1092
  </div>
1093
+ ${compactionStat(d.compactions)}
1093
1094
  </div>
1094
1095
 
1095
1096
  ${detailRangeNote(d)}
1097
+ ${compactionNote(d.compactions)}
1098
+ ${workflowsSection(d)}
1096
1099
 
1097
1100
  <div class="charts-row" style="margin-bottom:20px">
1098
1101
  <div class="chart-box">
@@ -1107,7 +1110,7 @@ function renderDetail() {
1107
1110
 
1108
1111
  ${rangeBrushHtml(d.messages.length)}
1109
1112
 
1110
- <div class="section-title">Messages (${d.messages.length})</div>
1113
+ <div class="section-title" id="messagesTitle"></div>
1111
1114
  <table class="messages-table">
1112
1115
  <thead><tr>
1113
1116
  <th>#</th>
@@ -1120,9 +1123,7 @@ function renderDetail() {
1120
1123
  <th>Cost</th>
1121
1124
  <th>Cumulative</th>
1122
1125
  </tr></thead>
1123
- <tbody>
1124
- ${buildMessageRowsWithSubagents(d)}
1125
- </tbody>
1126
+ <tbody id="messagesBody"></tbody>
1126
1127
  </table>
1127
1128
  </div>`;
1128
1129
 
@@ -1151,18 +1152,92 @@ function detailRangeNote(d) {
1151
1152
  return `<div class="detail-range-note">Totals above are all-time &middot; ${parts.join(' &middot; ')}</div>`;
1152
1153
  }
1153
1154
 
1154
- function buildMessageRowsWithSubagents(d) {
1155
- return [...d.messages]
1156
- .reverse()
1157
- .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
+ })
1158
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('');
1159
1234
  }
1160
1235
 
1161
1236
  function buildMessageRow(m) {
1162
1237
  const sa = m._subagent;
1163
1238
  const toolTags = !sa && m.tools ? m.tools.map((t) => `<span class="tool-tag">${esc(t)}</span>`).join(' ') : '';
1164
1239
  const modelCol = sa
1165
- ? `<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>`
1166
1241
  : `<span class="model-badge">${esc(shortModel(m.model))}</span>${toolTags ? ` ${toolTags}` : ''}`;
1167
1242
  return `<tr>
1168
1243
  <td class="muted">${m.index}</td>
@@ -1468,6 +1543,43 @@ function tokenBreakdownChartData(messages, c) {
1468
1543
  };
1469
1544
  }
1470
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
+
1471
1583
  function renderCumulativeChart(messages) {
1472
1584
  const canvas = document.getElementById('cumulativeChart');
1473
1585
  if (!canvas || !messages?.length) return;
@@ -1479,6 +1591,7 @@ function renderCumulativeChart(messages) {
1479
1591
  charts.cumulative = new Chart(canvas, {
1480
1592
  type: 'line',
1481
1593
  data: cumulativeChartData(messages, c),
1594
+ plugins: [compactionMarkers],
1482
1595
  options: {
1483
1596
  ...defaults,
1484
1597
  plugins: withTooltip(defaults, { title: (items) => messageTooltipTitle(detailSlice, items) }),
@@ -1495,6 +1608,7 @@ function renderCumulativeChart(messages) {
1495
1608
  },
1496
1609
  },
1497
1610
  });
1611
+ markCompactions(charts.cumulative, messages, c);
1498
1612
  }
1499
1613
 
1500
1614
  function renderTokenBreakdownChart(messages) {
@@ -1508,6 +1622,7 @@ function renderTokenBreakdownChart(messages) {
1508
1622
  charts.tokenBreakdown = new Chart(canvas, {
1509
1623
  type: 'bar',
1510
1624
  data: tokenBreakdownChartData(messages, c),
1625
+ plugins: [compactionMarkers],
1511
1626
  options: {
1512
1627
  ...defaults,
1513
1628
  plugins: {
@@ -1535,6 +1650,7 @@ function renderTokenBreakdownChart(messages) {
1535
1650
  },
1536
1651
  },
1537
1652
  });
1653
+ markCompactions(charts.tokenBreakdown, messages, c);
1538
1654
  }
1539
1655
 
1540
1656
  // #region RANGE BRUSH
@@ -1559,14 +1675,25 @@ function median(sorted) {
1559
1675
  const CACHE_BURST_RATIO = 4;
1560
1676
  const CACHE_BURST_MIN_TOKENS = 20000;
1561
1677
 
1562
- function cacheBurstIndices(messages) {
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) {
1563
1681
  const writes = messages
1564
1682
  .filter((m) => !m._subagent && m.cacheCreationTokens > 0)
1565
1683
  .map((m) => m.cacheCreationTokens)
1566
1684
  .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] : []));
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
+ });
1570
1697
  }
1571
1698
 
1572
1699
  function clampRange(start, end, total) {
@@ -1586,12 +1713,15 @@ function detailRangeFor(d) {
1586
1713
 
1587
1714
  function applyDetailRange(messages, range) {
1588
1715
  detailSlice = messages.slice(range.start, range.end);
1716
+ renderMessageRows(detailSlice, messages.length);
1589
1717
  const c = getChartColors();
1590
1718
  if (charts.cumulative && charts.tokenBreakdown) {
1591
1719
  charts.cumulative.data = cumulativeChartData(detailSlice, c);
1592
- charts.cumulative.update('none');
1593
1720
  charts.tokenBreakdown.data = tokenBreakdownChartData(detailSlice, c);
1594
- charts.tokenBreakdown.update('none');
1721
+ for (const chart of [charts.cumulative, charts.tokenBreakdown]) {
1722
+ markCompactions(chart, detailSlice, c);
1723
+ chart.update('none');
1724
+ }
1595
1725
  } else {
1596
1726
  renderCumulativeChart(detailSlice);
1597
1727
  renderTokenBreakdownChart(detailSlice);
@@ -1646,19 +1776,25 @@ function initRangeBrush(messages) {
1646
1776
 
1647
1777
  drawRangeOverview(q('.rb-overview'), messages);
1648
1778
 
1649
- const bursts = cacheBurstIndices(messages);
1779
+ const markers = notableEvents(messages);
1650
1780
  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
- })
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
+ )
1657
1786
  .join('');
1658
- const burstEls = [...burstsEl.children].map((el, k) => ({ el, i: bursts[k] }));
1659
- if (bursts.length) {
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) {
1660
1796
  burstCount.hidden = false;
1661
- burstCount.append(`${bursts.length} cache burst${bursts.length === 1 ? '' : 's'}`);
1797
+ burstCount.innerHTML = counts.join('<span class="rb-sep">·</span>');
1662
1798
  }
1663
1799
 
1664
1800
  const layout = () => {
@@ -2333,7 +2469,6 @@ async function navigate(view, params) {
2333
2469
  if (view !== 'detail') selectRow(0);
2334
2470
  }
2335
2471
 
2336
- // biome-ignore lint/correctness/noUnusedVariables: called from HTML onclick
2337
2472
  async function navigateToSessions(encodedPath, name) {
2338
2473
  lastSelectedProject = encodedPath;
2339
2474
  currentProjectPath = encodedPath;
@@ -2532,7 +2667,183 @@ function ensureViewElements() {
2532
2667
 
2533
2668
  // #region MODAL
2534
2669
 
2670
+ // The picker drills in — it navigates to a project's sessions view. That is a different act
2671
+ // from the hub's scope chip, which filters every view without moving the cursor.
2672
+ let pickerProjects = [];
2673
+ let pickerRows = [];
2674
+ let pickerIdx = 0;
2675
+
2676
+ async function openProjectPicker() {
2677
+ const modal = document.getElementById('projectPickerModal');
2678
+ const input = document.getElementById('projectPickerInput');
2679
+ const list = document.getElementById('projectPickerList');
2680
+ modal.classList.add('visible');
2681
+ input.value = '';
2682
+ input.focus();
2683
+ list.innerHTML = '<div class="picker-empty">Loading...</div>';
2684
+ try {
2685
+ // Deliberately unscoped: a switcher that only lists the project you are already scoped to
2686
+ // cannot switch anything.
2687
+ pickerProjects = ((await fetchJSON(`/api/projects?${rangeParams()}`)) || []).sort((a, b) =>
2688
+ sortCompare(a, b, 'totalCost', 'desc'),
2689
+ );
2690
+ } catch {
2691
+ pickerProjects = [];
2692
+ list.innerHTML = '<div class="picker-empty">Failed to load projects</div>';
2693
+ return;
2694
+ }
2695
+ renderProjectPicker();
2696
+ }
2697
+
2698
+ function closeProjectPicker() {
2699
+ document.getElementById('projectPickerModal').classList.remove('visible');
2700
+ }
2701
+
2702
+ function renderProjectPicker() {
2703
+ const list = document.getElementById('projectPickerList');
2704
+ const q = document.getElementById('projectPickerInput').value.trim().toLowerCase();
2705
+ pickerRows = q ? pickerProjects.filter((p) => p.name.toLowerCase().includes(q)) : pickerProjects;
2706
+ if (!pickerRows.length) {
2707
+ list.innerHTML = '<div class="picker-empty">No projects match</div>';
2708
+ return;
2709
+ }
2710
+ list.innerHTML = pickerRows
2711
+ .map(
2712
+ (p, i) => `<button class="picker-row" onclick="pickProject(${i})">
2713
+ <span class="picker-name">${esc(p.name)}</span>
2714
+ <span class="picker-cost">${formatCost(p.totalCost)}</span>
2715
+ </button>`,
2716
+ )
2717
+ .join('');
2718
+ setPickerCursor(0);
2719
+ }
2720
+
2721
+ function setPickerCursor(idx) {
2722
+ const list = document.getElementById('projectPickerList');
2723
+ list.children[pickerIdx]?.classList.remove('selected');
2724
+ pickerIdx = Math.min(Math.max(idx, 0), pickerRows.length - 1);
2725
+ const row = list.children[pickerIdx];
2726
+ row?.classList.add('selected');
2727
+ row?.scrollIntoView({ block: 'nearest' });
2728
+ }
2729
+
2730
+ function pickProject(idx) {
2731
+ const p = pickerRows[idx];
2732
+ if (!p) return;
2733
+ closeProjectPicker();
2734
+ navigateToSessions(p.encodedPath, p.name);
2735
+ }
2736
+
2737
+ function initProjectPicker() {
2738
+ const input = document.getElementById('projectPickerInput');
2739
+ input.addEventListener('input', renderProjectPicker);
2740
+ // Bound on the input because the global handler bails out on INPUT targets.
2741
+ input.addEventListener('keydown', (e) => {
2742
+ if (e.key === 'Escape') {
2743
+ e.preventDefault();
2744
+ closeProjectPicker();
2745
+ } else if (e.key === 'ArrowDown' || (e.key === 'n' && e.ctrlKey)) {
2746
+ e.preventDefault();
2747
+ setPickerCursor(pickerIdx + 1);
2748
+ } else if (e.key === 'ArrowUp' || (e.key === 'p' && e.ctrlKey)) {
2749
+ e.preventDefault();
2750
+ setPickerCursor(pickerIdx - 1);
2751
+ } else if (e.key === 'Enter') {
2752
+ e.preventDefault();
2753
+ pickProject(pickerIdx);
2754
+ }
2755
+ });
2756
+ }
2757
+
2758
+ // Each entry pairs a left and a right group onto the same grid rows, so their
2759
+ // headings sit level and the shorter group just leaves empty rows.
2760
+ // `combo` joins the keys with a plus (a chord) instead of listing them as
2761
+ // alternatives; `hub` marks rows that only work inside Claude Code Hub.
2762
+ const SHORTCUT_PAIRS = [
2763
+ [
2764
+ {
2765
+ title: 'Navigate',
2766
+ rows: [
2767
+ { keys: ['1'], label: 'Overview' },
2768
+ { keys: ['2'], label: 'Insights' },
2769
+ { keys: ['Backspace'], label: 'Go back' },
2770
+ { keys: ['Shift', 'P'], combo: true, label: 'Switch project' },
2771
+ { keys: ['Esc'], label: 'Close modal / go back' },
2772
+ ],
2773
+ },
2774
+ {
2775
+ title: 'Table',
2776
+ rows: [
2777
+ { keys: ['J', '↓'], label: 'Next row' },
2778
+ { keys: ['K', '↑'], label: 'Previous row' },
2779
+ { keys: ['Enter', 'Space'], label: 'Open selected row' },
2780
+ ],
2781
+ },
2782
+ ],
2783
+ [
2784
+ {
2785
+ title: 'Timeline range',
2786
+ rows: [
2787
+ { keys: ['←', '→'], label: 'Pan one step' },
2788
+ { keys: ['Shift', '←/→'], combo: true, label: 'Pan a full window' },
2789
+ { keys: ['Home', 'End'], label: 'Jump to start / end' },
2790
+ ],
2791
+ },
2792
+ {
2793
+ title: 'View',
2794
+ rows: [
2795
+ { keys: ['R'], label: 'Refresh data' },
2796
+ { keys: ['T'], label: 'Toggle theme' },
2797
+ { keys: ['?'], label: 'Show this help' },
2798
+ ],
2799
+ },
2800
+ ],
2801
+ [
2802
+ {
2803
+ title: 'Hub',
2804
+ hub: true,
2805
+ rows: [
2806
+ { keys: ['Ctrl', 'Alt', '←/→'], combo: true, label: 'Previous / next hub app' },
2807
+ { keys: ['Alt', '1…9'], combo: true, label: 'Jump to hub app by number' },
2808
+ { keys: ['Ctrl', 'Alt', 'P'], combo: true, label: 'Project picker' },
2809
+ ],
2810
+ },
2811
+ ],
2812
+ ];
2813
+
2814
+ const EMPTY_GROUP = { title: '', rows: [] };
2815
+
2816
+ // Interleaves each pair's rows left-then-right so CSS grid auto-placement lands
2817
+ // them on shared row tracks (see .shortcuts in style.css).
2818
+ function buildHelpShortcuts() {
2819
+ const cells = [];
2820
+ SHORTCUT_PAIRS.forEach(([left, right = EMPTY_GROUP], pair) => {
2821
+ const first = pair === 0 ? ' sc-first' : '';
2822
+ const sides = [
2823
+ [left, 'sc-l'],
2824
+ [right, 'sc-r'],
2825
+ ];
2826
+ const head = (g, side) =>
2827
+ g.title ? `<div class="${esc(`sc-group ${side}${first}${g.hub ? ' sc-hub' : ''}`)}">${g.title}</div>` : '';
2828
+ cells.push(sides.map(([g, side]) => head(g, side)).join(''));
2829
+ for (let i = 0; i < Math.max(left.rows.length, right.rows.length); i++) {
2830
+ for (const [group, side] of sides) {
2831
+ const row = group.rows[i];
2832
+ if (!row) continue;
2833
+ const sep = row.combo ? '<span class="sc-plus">+</span>' : '<span class="sc-or">/</span>';
2834
+ const keys = row.keys.map((k) => `<kbd>${esc(k)}</kbd>`).join(sep);
2835
+ const cls = side + (group.hub ? ' sc-hub' : '');
2836
+ cells.push(`<dt class="${esc(cls)}">${keys}</dt><dd class="${esc(cls)}">${esc(row.label)}</dd>`);
2837
+ }
2838
+ }
2839
+ });
2840
+ return cells.join('');
2841
+ }
2842
+
2535
2843
  function toggleHelpModal() {
2844
+ const list = document.getElementById('helpShortcuts');
2845
+ if (!list.childElementCount) list.innerHTML = buildHelpShortcuts();
2846
+ list.classList.toggle('sc-standalone', !window.__HUB__?.enabled);
2536
2847
  document.getElementById('helpModal').classList.toggle('visible');
2537
2848
  }
2538
2849
 
@@ -2597,7 +2908,7 @@ document.addEventListener('keydown', (e) => {
2597
2908
 
2598
2909
  const anyModal = document.querySelector('.modal-overlay.visible');
2599
2910
  if (anyModal) {
2600
- if (e.key === 'Escape') {
2911
+ if (e.key === 'Escape' || (e.key === '?' && anyModal.id === 'helpModal')) {
2601
2912
  anyModal.classList.remove('visible');
2602
2913
  e.preventDefault();
2603
2914
  }
@@ -2616,6 +2927,13 @@ document.addEventListener('keydown', (e) => {
2616
2927
 
2617
2928
  if (e.ctrlKey || e.altKey || e.metaKey) return;
2618
2929
 
2930
+ // Shift+P is the project switcher across the hub apps; matches memory and marketplace.
2931
+ if (e.key === 'P' && e.shiftKey) {
2932
+ e.preventDefault();
2933
+ openProjectPicker();
2934
+ return;
2935
+ }
2936
+
2619
2937
  if (e.key === '?' || (e.key === '/' && e.shiftKey)) {
2620
2938
  e.preventDefault();
2621
2939
  toggleHelpModal();
@@ -2853,6 +3171,7 @@ document.addEventListener('DOMContentLoaded', async () => {
2853
3171
  dateRange = loadDateRange();
2854
3172
  buildRangePresets();
2855
3173
  renderRangeTrigger();
3174
+ initProjectPicker();
2856
3175
 
2857
3176
  // Resolve the scope before any navigate() so the first /api/overview already carries
2858
3177
  // &project=. Read window.location.search directly, not getUrlState() — that falls back to
package/public/index.html CHANGED
@@ -95,9 +95,10 @@
95
95
  </div>
96
96
 
97
97
  <div class="modal-overlay" id="helpModal" onclick="if(event.target===this)toggleHelpModal()">
98
- <div class="modal-box">
98
+ <div class="modal-box modal-help">
99
99
  <div class="modal-header">
100
100
  <div class="modal-title">Cost Dashboard</div>
101
+ <button class="modal-close" aria-label="Close dialog" onclick="toggleHelpModal()">&#10005;</button>
101
102
  </div>
102
103
  <div class="modal-body">
103
104
  <div class="modal-section">
@@ -106,36 +107,18 @@
106
107
  </div>
107
108
  <hr class="modal-divider">
108
109
  <h4 class="shortcut-section">Keyboard Shortcuts</h4>
109
- <div class="shortcut-grid">
110
- <div>
111
- <h4 class="shortcut-section">Navigation</h4>
112
- <table class="shortcut-table">
113
- <tr><td><kbd>1</kbd></td><td>Overview</td></tr>
114
- <tr><td><kbd>2</kbd></td><td>Insights</td></tr>
115
- <tr><td><kbd>Backspace</kbd></td><td>Go back</td></tr>
116
- <tr><td><kbd>Esc</kbd></td><td>Close modal / go back</td></tr>
117
- </table>
118
- </div>
119
- <div>
120
- <h4 class="shortcut-section">Table</h4>
121
- <table class="shortcut-table">
122
- <tr><td><kbd>J</kbd> / <kbd>&darr;</kbd></td><td>Next row</td></tr>
123
- <tr><td><kbd>K</kbd> / <kbd>&uarr;</kbd></td><td>Previous row</td></tr>
124
- <tr><td><kbd>Enter</kbd></td><td>Open selected row</td></tr>
125
- </table>
126
- </div>
127
- <div>
128
- <h4 class="shortcut-section">Actions</h4>
129
- <table class="shortcut-table">
130
- <tr><td><kbd>R</kbd></td><td>Refresh data</td></tr>
131
- <tr><td><kbd>T</kbd></td><td>Toggle theme</td></tr>
132
- <tr><td><kbd>?</kbd></td><td>Show this help</td></tr>
133
- <tr><td><kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>P</kbd></td><td>Switch project (hub only)</td></tr>
134
- </table>
135
- </div>
136
- </div>
110
+ <dl class="shortcuts" id="helpShortcuts"></dl>
111
+ </div>
112
+ </div>
113
+ </div>
114
+
115
+ <div class="modal-overlay" id="projectPickerModal" onclick="if(event.target===this)closeProjectPicker()">
116
+ <div class="modal-box picker-box">
117
+ <div class="modal-header">
118
+ <div class="modal-title">Switch project</div>
137
119
  </div>
138
- <button class="modal-close" onclick="toggleHelpModal()">Close</button>
120
+ <input class="picker-input" id="projectPickerInput" type="text" placeholder="Filter projects..." autocomplete="off" spellcheck="false">
121
+ <div class="picker-list" id="projectPickerList"></div>
139
122
  </div>
140
123
  </div>
141
124
 
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 */
@@ -823,6 +824,22 @@ body {
823
824
  vertical-align: middle;
824
825
  }
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
+
826
843
  .rb-presets {
827
844
  display: flex;
828
845
  gap: 4px;
@@ -936,6 +953,10 @@ body {
936
953
  left: 2.5px;
937
954
  }
938
955
 
956
+ .rb-burst.compact::before {
957
+ background: var(--compact);
958
+ }
959
+
939
960
  /* The shade outside the window is the window's own shadow, clipped by the track. */
940
961
  .rb-window {
941
962
  position: absolute;
@@ -1209,32 +1230,47 @@ body.light .rb-window {
1209
1230
  font-size: 10px;
1210
1231
  }
1211
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
+
1212
1249
  /* #endregion */
1213
1250
 
1214
1251
  /* #region SUBAGENT */
1215
1252
 
1216
- .subagent-tag {
1253
+ .subagent-tag,
1254
+ .tool-tag,
1255
+ .compaction-tag {
1217
1256
  font-size: 9px;
1218
- text-transform: uppercase;
1219
1257
  letter-spacing: 0.03em;
1220
- color: var(--text-muted);
1221
- background: var(--bg-hover);
1222
1258
  padding: 1px 5px;
1223
1259
  border-radius: 3px;
1224
1260
  margin-left: 4px;
1225
1261
  vertical-align: middle;
1226
1262
  }
1227
1263
 
1264
+ .subagent-tag {
1265
+ text-transform: uppercase;
1266
+ color: var(--text-muted);
1267
+ background: var(--bg-hover);
1268
+ }
1269
+
1228
1270
  .tool-tag {
1229
- font-size: 9px;
1230
1271
  text-transform: lowercase;
1231
- letter-spacing: 0.03em;
1232
1272
  color: var(--chart-2, #60a5fa);
1233
1273
  background: rgba(96, 165, 250, 0.12);
1234
- padding: 1px 5px;
1235
- border-radius: 3px;
1236
- margin-left: 4px;
1237
- vertical-align: middle;
1238
1274
  }
1239
1275
 
1240
1276
  /* #endregion */
@@ -1343,21 +1379,16 @@ body.light .rb-window {
1343
1379
  }
1344
1380
 
1345
1381
  .modal-close {
1346
- margin-top: 20px;
1347
- width: 100%;
1348
- padding: 8px;
1349
- background: var(--bg-elevated);
1350
- border: 1px solid var(--border);
1351
- border-radius: 6px;
1352
- color: var(--text-secondary);
1382
+ padding: 2px;
1383
+ background: none;
1384
+ border: none;
1385
+ color: var(--text-muted);
1353
1386
  cursor: pointer;
1354
- font-family: var(--mono);
1355
- font-size: 12px;
1356
- text-transform: uppercase;
1387
+ font-size: 16px;
1388
+ line-height: 1;
1357
1389
  }
1358
1390
 
1359
1391
  .modal-close:hover {
1360
- background: var(--bg-hover);
1361
1392
  color: var(--text-primary);
1362
1393
  }
1363
1394
 
@@ -1372,18 +1403,93 @@ body.light .rb-window {
1372
1403
  margin-bottom: 0;
1373
1404
  }
1374
1405
 
1406
+ /* The paired shortcut columns need room the 500px default cannot give. */
1407
+ .modal-box.modal-help {
1408
+ max-width: 960px;
1409
+ }
1410
+
1411
+ .picker-box {
1412
+ max-width: 560px;
1413
+ padding: 16px;
1414
+ display: flex;
1415
+ flex-direction: column;
1416
+ gap: 10px;
1417
+ overflow: hidden;
1418
+ }
1419
+
1420
+ .picker-input {
1421
+ width: 100%;
1422
+ padding: 8px 10px;
1423
+ background: var(--bg-deep);
1424
+ border: 1px solid var(--border);
1425
+ border-radius: 6px;
1426
+ color: var(--text-primary);
1427
+ font-family: inherit;
1428
+ font-size: 13px;
1429
+ }
1430
+
1431
+ .picker-input:focus {
1432
+ outline: none;
1433
+ border-color: var(--accent);
1434
+ }
1435
+
1436
+ .picker-list {
1437
+ max-height: 50vh;
1438
+ overflow-y: auto;
1439
+ display: flex;
1440
+ flex-direction: column;
1441
+ gap: 2px;
1442
+ }
1443
+
1444
+ .picker-row {
1445
+ display: flex;
1446
+ align-items: center;
1447
+ justify-content: space-between;
1448
+ gap: 12px;
1449
+ width: 100%;
1450
+ padding: 7px 10px;
1451
+ background: none;
1452
+ border: 1px solid transparent;
1453
+ border-radius: 6px;
1454
+ color: var(--text-primary);
1455
+ font-family: inherit;
1456
+ font-size: 13px;
1457
+ text-align: left;
1458
+ cursor: pointer;
1459
+ }
1460
+
1461
+ .picker-row:hover {
1462
+ background: var(--bg-hover);
1463
+ }
1464
+
1465
+ .picker-row.selected {
1466
+ background: var(--bg-hover);
1467
+ border-color: var(--accent);
1468
+ }
1469
+
1470
+ .picker-name {
1471
+ overflow: hidden;
1472
+ text-overflow: ellipsis;
1473
+ white-space: nowrap;
1474
+ }
1475
+
1476
+ .picker-cost {
1477
+ color: var(--text-secondary);
1478
+ white-space: nowrap;
1479
+ }
1480
+
1481
+ .picker-empty {
1482
+ padding: 12px 10px;
1483
+ color: var(--text-muted);
1484
+ font-size: 12px;
1485
+ }
1486
+
1375
1487
  .modal-divider {
1376
1488
  border: none;
1377
1489
  border-top: 1px solid var(--border);
1378
1490
  margin: 16px 0;
1379
1491
  }
1380
1492
 
1381
- .shortcut-grid {
1382
- display: grid;
1383
- grid-template-columns: 1fr 1fr;
1384
- gap: 20px;
1385
- }
1386
-
1387
1493
  .shortcut-section {
1388
1494
  margin: 0 0 8px 0;
1389
1495
  color: var(--text-primary);
@@ -1391,22 +1497,100 @@ body.light .rb-window {
1391
1497
  font-weight: 600;
1392
1498
  }
1393
1499
 
1394
- .shortcut-table {
1395
- width: 100%;
1396
- font-size: 12px;
1500
+ /* One shared grid for both halves (key | label | spacer | key | label): each key
1501
+ gutter is sized by its column's widest combo, and left/right rows share row
1502
+ tracks, so paired groups line up — a shorter group just leaves empty rows.
1503
+ Cells opt into a half via sc-l / sc-r; the markup is generated from
1504
+ SHORTCUT_PAIRS in app.js. */
1505
+ .shortcuts {
1506
+ margin: 0;
1507
+ display: grid;
1508
+ grid-template-columns: max-content 1fr 28px max-content 1fr;
1509
+ column-gap: 14px;
1510
+ }
1511
+
1512
+ .shortcuts dt.sc-l {
1513
+ grid-column: 1;
1397
1514
  }
1398
1515
 
1399
- .shortcut-table td {
1516
+ .shortcuts dd.sc-l {
1517
+ grid-column: 2;
1518
+ }
1519
+
1520
+ .shortcuts dt.sc-r {
1521
+ grid-column: 4;
1522
+ }
1523
+
1524
+ .shortcuts dd.sc-r {
1525
+ grid-column: 5;
1526
+ }
1527
+
1528
+ .shortcuts .sc-group.sc-l {
1529
+ grid-column: 1 / 3;
1530
+ }
1531
+
1532
+ .shortcuts .sc-group.sc-r {
1533
+ grid-column: 4 / 6;
1534
+ }
1535
+
1536
+ .shortcuts dt {
1537
+ margin: 0;
1538
+ display: flex;
1539
+ align-items: center;
1540
+ align-self: center;
1541
+ gap: 4px;
1400
1542
  padding: 3px 0;
1543
+ }
1544
+
1545
+ .shortcuts dd {
1546
+ margin: 0;
1547
+ font-size: 13px;
1401
1548
  color: var(--text-secondary);
1549
+ align-self: center;
1550
+ padding: 3px 0;
1402
1551
  }
1403
1552
 
1404
- .shortcut-table td:first-child {
1405
- width: 120px;
1553
+ /* Section headings carry the column: full-width rule + primary ink, so the eye
1554
+ finds the group before it reads any single row. */
1555
+ .shortcuts .sc-group {
1556
+ padding: 18px 0 6px;
1557
+ margin-bottom: 6px;
1558
+ font-size: 11px;
1559
+ font-weight: 700;
1560
+ letter-spacing: 0.16em;
1561
+ text-transform: uppercase;
1562
+ color: var(--text-primary);
1563
+ border-bottom: 1px solid var(--border);
1406
1564
  }
1407
1565
 
1408
- .shortcut-table td:last-child {
1566
+ .shortcuts .sc-group.sc-first {
1567
+ padding-top: 2px;
1568
+ }
1569
+
1570
+ /* keycap chips: thicker bottom border reads as a key */
1571
+ .shortcuts kbd {
1572
+ display: inline-flex;
1573
+ align-items: center;
1574
+ justify-content: center;
1575
+ min-width: 22px;
1576
+ height: 22px;
1577
+ padding: 0 6px;
1578
+ box-sizing: border-box;
1409
1579
  color: var(--text-primary);
1580
+ border-bottom-width: 2px;
1581
+ border-radius: 5px;
1582
+ }
1583
+
1584
+ .shortcuts .sc-plus,
1585
+ .shortcuts .sc-or {
1586
+ color: var(--text-muted);
1587
+ font-size: 11px;
1588
+ }
1589
+
1590
+ /* Hub keys do nothing outside Claude Code Hub, so the standalone app hides that
1591
+ whole column rather than listing keys that no-op. */
1592
+ .shortcuts.sc-standalone .sc-hub {
1593
+ display: none;
1410
1594
  }
1411
1595
 
1412
1596
  kbd {
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 })),