claude-code-cost 0.23.0 → 0.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "0.23.0",
3
+ "version": "0.23.1",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/app.js CHANGED
@@ -494,7 +494,11 @@ async function fetchJSON(url, skipCache) {
494
494
  if (cached) return cached;
495
495
  }
496
496
  const res = await fetch(url);
497
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
497
+ if (!res.ok) {
498
+ const err = new Error(`HTTP ${res.status}`);
499
+ err.status = res.status;
500
+ throw err;
501
+ }
498
502
  const data = await res.json();
499
503
  dataFetchedAt = Date.now();
500
504
  if (!skipCache) cacheData(url, data);
@@ -1112,7 +1116,7 @@ function renderDetail() {
1112
1116
  destroyChart('cumulative');
1113
1117
  destroyChart('tokenBreakdown');
1114
1118
  applyDetailRange(d.messages, detailRangeFor(d));
1115
- initRangeBrush(d.messages);
1119
+ initRangeBrush(d.messages, d.workflows);
1116
1120
  });
1117
1121
  }
1118
1122
 
@@ -1726,6 +1730,7 @@ function rangeBrushHtml(total) {
1726
1730
  <div class="rb-track" tabindex="0" role="slider" aria-label="Visible message range"
1727
1731
  aria-valuemin="1" aria-valuemax="${esc(total)}">
1728
1732
  ${rangeOverviewSvg}
1733
+ <div class="rb-spans"></div>
1729
1734
  <div class="rb-bursts"></div>
1730
1735
  <div class="rb-window">
1731
1736
  <div class="rb-handle rb-handle-left" data-edge="start"></div>
@@ -1740,7 +1745,7 @@ function rangeBrushHtml(total) {
1740
1745
  const rangeOverviewSvg =
1741
1746
  '<svg class="rb-overview" viewBox="0 0 1000 100" preserveAspectRatio="none" aria-hidden="true"><polygon /><polyline /></svg>';
1742
1747
 
1743
- function initRangeBrush(messages) {
1748
+ function initRangeBrush(messages, workflows) {
1744
1749
  const root = document.getElementById('rangeBrush');
1745
1750
  if (!root) return;
1746
1751
  const total = messages.length;
@@ -1757,6 +1762,16 @@ function initRangeBrush(messages) {
1757
1762
 
1758
1763
  drawRangeOverview(q('.rb-overview'), messages);
1759
1764
 
1765
+ const runs = workflows || [];
1766
+ q('.rb-spans').innerHTML = runs
1767
+ .map((w) => {
1768
+ const left = ((w.startIndex - 1) / total) * 100;
1769
+ const width = Math.max(((w.endIndex - w.startIndex + 1) / total) * 100, 0.6);
1770
+ const tip = `${w.name} · ${w.agents} agent${w.agents === 1 ? '' : 's'} · ${formatCost(w.totalCost)}`;
1771
+ return `<span class="rb-span" style="left:${left}%;width:${width}%" title="${esc(tip)}"><i>${esc(w.name)}</i></span>`;
1772
+ })
1773
+ .join('');
1774
+
1760
1775
  const markers = notableEvents(messages);
1761
1776
  const burstsEl = q('.rb-bursts');
1762
1777
  burstsEl.innerHTML = markers
@@ -1767,12 +1782,12 @@ function initRangeBrush(messages) {
1767
1782
  .join('');
1768
1783
  const burstEls = [...burstsEl.children].map((el, k) => ({ el, i: markers[k].i }));
1769
1784
  const counts = [
1770
- ['burst', 'cache burst', ''],
1771
- ['compaction', 'compaction', ' class="compact"'],
1772
- ].flatMap(([kind, label, attr]) => {
1773
- const n = markers.filter((k) => k.kind === kind).length;
1774
- return n ? [`<span${attr}><i></i>${n} ${label}${n === 1 ? '' : 's'}</span>`] : [];
1775
- });
1785
+ [markers.filter((k) => k.kind === 'burst').length, 'cache burst', ''],
1786
+ [markers.filter((k) => k.kind === 'compaction').length, 'compaction', ' class="compact"'],
1787
+ [runs.length, 'workflow', ' class="workflow"'],
1788
+ ]
1789
+ .filter(([n]) => n)
1790
+ .map(([n, label, attr]) => `<span${attr}><i></i>${n} ${label}${n === 1 ? '' : 's'}</span>`);
1776
1791
  if (counts.length) {
1777
1792
  burstCount.hidden = false;
1778
1793
  burstCount.innerHTML = counts.join('<span class="rb-sep">·</span>');
@@ -2617,6 +2632,15 @@ async function loadAndRender(view) {
2617
2632
  } catch (err) {
2618
2633
  if (myNav !== navCounter) return;
2619
2634
  console.error(`Failed to load ${view}:`, err);
2635
+ // The cursor is restored from sessionStorage when the iframe reloads with no query, so a
2636
+ // config-dir switch leaves it pointing at a session the new dir never had. A 404 there is a
2637
+ // stale cursor, not a broken app: drop it and land on the overview.
2638
+ if (err.status === 404 && view === 'detail') {
2639
+ sessionDetailData = null;
2640
+ showToast('Not in this config dir — showing overview');
2641
+ await navigate('overview');
2642
+ return;
2643
+ }
2620
2644
  showToast(`Error: ${err.message}`);
2621
2645
  const viewEl = document.getElementById(`${view}-view`);
2622
2646
  if (viewEl) viewEl.innerHTML = `<div class="loading-state"><span>Failed to load data: ${err.message}</span></div>`;
@@ -2734,6 +2758,20 @@ function initProjectPicker() {
2734
2758
  pickProject(pickerIdx);
2735
2759
  }
2736
2760
  });
2761
+ // Vimium eats Escape inside a text input and only blurs it, so the page never sees the key.
2762
+ // A blur that no click in the picker caused, while the window keeps focus and the input is
2763
+ // still shown, is that Escape.
2764
+ const modal = document.getElementById('projectPickerModal');
2765
+ let pointerDown = false;
2766
+ modal.addEventListener('mousedown', () => {
2767
+ pointerDown = true;
2768
+ });
2769
+ document.addEventListener('mouseup', () => {
2770
+ pointerDown = false;
2771
+ });
2772
+ input.addEventListener('blur', () => {
2773
+ if (!pointerDown && document.hasFocus() && input.checkVisibility()) closeProjectPicker();
2774
+ });
2737
2775
  }
2738
2776
 
2739
2777
  // Each entry pairs a left and a right group onto the same grid rows, so their
@@ -3043,7 +3081,7 @@ function renderLimits() {
3043
3081
  binding: false,
3044
3082
  })
3045
3083
  : `<p class="modal-note">Disabled${spend.disabledReason ? ` &middot; ${esc(spend.disabledReason)}` : ''}. Nothing covers you past the plan limits.</p>`
3046
- }
3084
+ }
3047
3085
  </div>`
3048
3086
  : ''
3049
3087
  }
@@ -3283,21 +3321,24 @@ async function refreshIfStale() {
3283
3321
 
3284
3322
  window.__HUB__ = cfg;
3285
3323
 
3324
+ // e.code travels with e.key because macOS composes Option+<key> into a character (Option+P is
3325
+ // 'π'), so the key alone cannot identify the binding. The hub owns the keymap and normalizes;
3326
+ // these tests only decide whether a press is the hub's to handle.
3286
3327
  document.addEventListener('keydown', (e) => {
3287
- const fwd = (key) => {
3328
+ const fwd = () => {
3288
3329
  e.preventDefault();
3289
- hubPost({ type: 'hub:keydown', key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey });
3330
+ hubPost({ type: 'hub:keydown', key: e.key, code: e.code, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey });
3290
3331
  };
3291
3332
  if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
3292
- fwd(e.key);
3333
+ fwd();
3293
3334
  }
3294
3335
  // Own branch: the Alt+digit case below requires !ctrlKey. The hub owns the Ctrl+Alt+letter
3295
3336
  // keymap and ignores unbound letters.
3296
- if (e.ctrlKey && e.altKey && !e.shiftKey && !e.metaKey && /^[a-z]$/i.test(e.key)) {
3297
- fwd(e.key);
3337
+ if (e.ctrlKey && e.altKey && !e.shiftKey && !e.metaKey && (/^[a-z]$/i.test(e.key) || /^Key[A-Z]$/.test(e.code))) {
3338
+ fwd();
3298
3339
  }
3299
- if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey && /^[1-9]$/.test(e.key)) {
3300
- fwd(e.key);
3340
+ if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey && (/^[1-9]$/.test(e.key) || /^Digit[1-9]$/.test(e.code))) {
3341
+ fwd();
3301
3342
  }
3302
3343
  });
3303
3344
  })();
package/public/style.css CHANGED
@@ -30,6 +30,7 @@
30
30
  --chart-5: #b784f5;
31
31
  --chart-6: #fb7185;
32
32
  --compact: var(--chart-5);
33
+ --workflow: var(--chart-2);
33
34
  }
34
35
 
35
36
  /* #endregion */
@@ -842,6 +843,15 @@ body {
842
843
  color: var(--compact);
843
844
  }
844
845
 
846
+ .rb-burst-count .workflow {
847
+ color: var(--workflow);
848
+ }
849
+
850
+ .rb-burst-count .workflow i {
851
+ border-radius: 1px;
852
+ background: var(--workflow);
853
+ }
854
+
845
855
  .rb-burst-count .compact i,
846
856
  .rb-burst.compact::after {
847
857
  border-radius: 1px;
@@ -919,12 +929,38 @@ body {
919
929
  vector-effect: non-scaling-stroke;
920
930
  }
921
931
 
922
- .rb-bursts {
932
+ .rb-bursts,
933
+ .rb-spans {
923
934
  position: absolute;
924
935
  inset: 0;
925
936
  pointer-events: none;
926
937
  }
927
938
 
939
+ .rb-span {
940
+ position: absolute;
941
+ top: 0;
942
+ bottom: 0;
943
+ background: color-mix(in srgb, var(--workflow) 16%, transparent);
944
+ border-left: 1px solid var(--workflow);
945
+ border-right: 1px solid var(--workflow);
946
+ pointer-events: auto;
947
+ overflow: hidden;
948
+ }
949
+
950
+ .rb-span i {
951
+ position: absolute;
952
+ bottom: 2px;
953
+ left: 3px;
954
+ right: 2px;
955
+ font-size: 9px;
956
+ font-style: normal;
957
+ letter-spacing: 0.03em;
958
+ color: var(--workflow);
959
+ white-space: nowrap;
960
+ overflow: hidden;
961
+ text-overflow: ellipsis;
962
+ }
963
+
928
964
  .rb-burst {
929
965
  position: absolute;
930
966
  top: 0;
package/server.js CHANGED
@@ -433,7 +433,10 @@ function collectAgents(dir, workflowId, out) {
433
433
  }
434
434
  continue;
435
435
  }
436
- if (!e.name.endsWith('.jsonl')) continue;
436
+ // A workflow run also drops its journal.jsonl next to the agents; only `agent-*.jsonl` is a
437
+ // transcript, and counting the journal inflated the run's agent count by one and stretched its
438
+ // span, since a file with no priced turns falls back to the session's own start time.
439
+ if (!e.name.startsWith('agent-') || !e.name.endsWith('.jsonl')) continue;
437
440
  const agentId = e.name.replace('.jsonl', '');
438
441
  let meta = {};
439
442
  try { meta = JSON.parse(fs.readFileSync(path.join(dir, `${agentId}.meta.json`), 'utf-8')); } catch { /* no meta */ }
@@ -499,31 +502,43 @@ async function loadSubagentData(subagentInfos, pricing) {
499
502
  messageCount: 0,
500
503
  models: new Set(),
501
504
  firstTimestamp: null,
505
+ lastTimestamp: null,
502
506
  };
503
- const seen = new Set();
507
+ // An agent log writes one line per streamed content block, each carrying the usage as it stood
508
+ // then, so a turn's first line can report one output token and its last the whole reply: the
509
+ // turn is the largest usage logged for its (message.id, requestId). The session log repeats the
510
+ // final usage on every line, which is why first-wins reads the same there.
511
+ const kept = new Map();
512
+ const unhashed = [];
504
513
  await processJSONLFile(info.filePath, async (line) => {
505
514
  let parsed;
506
515
  try { parsed = JSON.parse(line); } catch { return; }
507
- if (!parsed.message?.usage?.input_tokens && parsed.message?.usage?.input_tokens !== 0) return;
516
+ const usage = parsed.message?.usage;
517
+ if (!usage?.input_tokens && usage?.input_tokens !== 0) return;
508
518
  if (!parsed.timestamp) return;
509
519
 
520
+ // Only what the totals need: `parsed` also holds the turn's content blocks.
521
+ const entry = { costUSD: parsed.costUSD, timestamp: parsed.timestamp, message: { model: parsed.message.model, usage } };
510
522
  const hash = createDedupeHash(parsed);
511
- if (hash && seen.has(hash)) return;
512
- if (hash) seen.add(hash);
513
-
514
- const cost = calculateEntryCost(parsed, pricing);
515
- const usage = parsed.message.usage;
516
- agent.totalCost += cost;
517
- agent.inputTokens += usage.input_tokens || 0;
518
- agent.outputTokens += usage.output_tokens || 0;
519
- agent.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
520
- agent.cacheReadTokens += (usage.cache_read_input_tokens || 0);
521
- agent.messageCount++;
522
- agent.models.add(parsed.message?.model || 'unknown');
523
- if (!agent.firstTimestamp || parsed.timestamp < agent.firstTimestamp) {
524
- agent.firstTimestamp = parsed.timestamp;
525
- }
523
+ if (!hash) { unhashed.push(entry); return; }
524
+ const prev = kept.get(hash);
525
+ if (!prev || (usage.output_tokens || 0) > (prev.message.usage.output_tokens || 0)) kept.set(hash, entry);
526
526
  });
527
+ const turns = [...kept.values(), ...unhashed].map(e => ({
528
+ cost: calculateEntryCost(e, pricing),
529
+ inputTokens: e.message.usage.input_tokens || 0,
530
+ outputTokens: e.message.usage.output_tokens || 0,
531
+ cacheCreationTokens: e.message.usage.cache_creation_input_tokens || 0,
532
+ cacheReadTokens: e.message.usage.cache_read_input_tokens || 0,
533
+ model: e.message.model || 'unknown',
534
+ timestamp: e.timestamp,
535
+ }));
536
+ Object.assign(agent, summarizeMessages(turns));
537
+ for (const t of turns) {
538
+ agent.models.add(t.model);
539
+ if (!agent.firstTimestamp || t.timestamp < agent.firstTimestamp) agent.firstTimestamp = t.timestamp;
540
+ if (!agent.lastTimestamp || t.timestamp > agent.lastTimestamp) agent.lastTimestamp = t.timestamp;
541
+ }
527
542
  agent.models = [...agent.models];
528
543
  return agent;
529
544
  }));
@@ -635,6 +650,10 @@ async function loadProjectData(files, pricing) {
635
650
  if (subagentInfos.length > 0) {
636
651
  const subagents = await loadSubagentData(subagentInfos, pricing);
637
652
  for (const sa of subagents) {
653
+ // An agent log with no priced turns — empty, truncated, or a crash before the first
654
+ // response — would fold in as a zero-cost message dated at the session's own start,
655
+ // which stretches every span it lands in.
656
+ if (sa.messageCount === 0) continue;
638
657
  session.totalCost += sa.totalCost;
639
658
  session.inputTokens += sa.inputTokens;
640
659
  session.outputTokens += sa.outputTokens;
@@ -650,7 +669,7 @@ async function loadProjectData(files, pricing) {
650
669
  cacheCreationTokens: sa.cacheCreationTokens,
651
670
  cacheReadTokens: sa.cacheReadTokens,
652
671
  speed: 'standard',
653
- _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount, workflowId: sa.workflowId },
672
+ _subagent: { agentId: sa.agentId, agentType: sa.agentType, description: sa.description, messageCount: sa.messageCount, workflowId: sa.workflowId, lastTimestamp: sa.lastTimestamp },
654
673
  });
655
674
  }
656
675
  }
@@ -1062,12 +1081,21 @@ async function getSessionDetailData(sessionId) {
1062
1081
  : new Map();
1063
1082
  const workflows = [...byWorkflow].map(([id, msgs]) => {
1064
1083
  const { messageCount, ...totals } = summarizeMessages(msgs);
1084
+ // A folded message carries its agent's start time, so the run ends at the latest agent's
1085
+ // own last turn — the last folded message only says when that agent started.
1086
+ const end = msgs.reduce((max, m) => {
1087
+ const t = m._subagent.lastTimestamp || m.timestamp;
1088
+ return t > max ? t : max;
1089
+ }, msgs[0].timestamp);
1065
1090
  return {
1066
1091
  id,
1067
1092
  name: names.get(id) || id,
1068
1093
  agents: messageCount,
1069
1094
  firstTimestamp: msgs[0].timestamp,
1070
- lastTimestamp: msgs.at(-1).timestamp,
1095
+ lastTimestamp: end,
1096
+ // Where the run sits in `messages`, for the timeline band.
1097
+ startIndex: msgs[0].index,
1098
+ endIndex: msgs.at(-1).index,
1071
1099
  ...totals,
1072
1100
  };
1073
1101
  }).sort((a, b) => b.totalCost - a.totalCost);