claude-code-cost 0.13.0 → 0.15.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/public/app.js CHANGED
@@ -4,7 +4,7 @@ let currentView = 'overview';
4
4
  let overviewData = null;
5
5
  let projectsData = null;
6
6
  let sessionsData = null;
7
- let sessionsDaily = null;
7
+ let sessionsCostSeries = null;
8
8
  let sessionsModelDistribution = null;
9
9
  let sessionDetailData = null;
10
10
  let currentProjectPath = null;
@@ -24,7 +24,9 @@ const DEFAULT_SORT = {
24
24
  sessions: { field: 'lastTimestamp', order: 'desc' },
25
25
  };
26
26
  const viewSort = structuredClone(DEFAULT_SORT);
27
- let dateRange = 3;
27
+ // A tagged union: a rolling preset the server recomputes per request, or a concrete window of
28
+ // two local dates. Persisted as JSON under cc-cost:range (see loadDateRange).
29
+ let dateRange = { kind: 'preset', value: '3' };
28
30
  const charts = {};
29
31
  let lastRenderHash = {};
30
32
  let navCounter = 0;
@@ -91,9 +93,54 @@ function timeAgo(ts) {
91
93
  return new Date(ts).toLocaleDateString();
92
94
  }
93
95
 
94
- function shortDate(dateStr) {
95
- const d = new Date(`${dateStr}T00:00:00`);
96
- return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
96
+ // Bucket keys arrive as YYYY-MM-DD (day) or YYYY-MM-DDTHH (hour), both in the server's local
97
+ // time with no zone suffix.
98
+ function bucketLabel(key, bucket) {
99
+ if (bucket === 'hour') {
100
+ return new Date(`${key}:00:00`).toLocaleTimeString(undefined, { hour: 'numeric' });
101
+ }
102
+ return new Date(`${key}T00:00:00`).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
103
+ }
104
+
105
+ // Local calendar dates as YYYY-MM-DD: the shape the range API takes, comparable with < and >.
106
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
107
+
108
+ function isoDate(d) {
109
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
110
+ }
111
+
112
+ function todayIso() {
113
+ return isoDate(new Date());
114
+ }
115
+
116
+ function isoParts(iso) {
117
+ return iso.split('-').map(Number);
118
+ }
119
+
120
+ function isoShift(iso, days) {
121
+ const [y, m, d] = isoParts(iso);
122
+ return isoDate(new Date(y, m - 1, d + days));
123
+ }
124
+
125
+ // Inclusive, so a single day counts as 1. Midday avoids a DST shift landing on a boundary.
126
+ function isoDayCount(from, to) {
127
+ const [ay, am, ad] = isoParts(from);
128
+ const [by, bm, bd] = isoParts(to);
129
+ return Math.round((new Date(by, bm - 1, bd, 12) - new Date(ay, am - 1, ad, 12)) / 86400000) + 1;
130
+ }
131
+
132
+ // "AUG 12", carrying a two-digit year only when the date falls outside the current one: "DEC 28 '25".
133
+ function isoDayLabel(iso) {
134
+ const [y] = isoParts(iso);
135
+ const yearTag = y === new Date().getFullYear() ? '' : ` '${String(y).slice(2)}`;
136
+ const dayLabel = new Date(`${iso}T00:00:00`)
137
+ .toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
138
+ .toUpperCase();
139
+ return `${dayLabel}${yearTag}`;
140
+ }
141
+
142
+ function costSeriesTitle(series) {
143
+ return series?.bucket === 'hour' ? 'Hourly Cost' : 'Daily Cost';
97
144
  }
98
145
 
99
146
  function shortModel(model) {
@@ -181,15 +228,58 @@ function getUrlState() {
181
228
  };
182
229
  }
183
230
 
231
+ const DEFAULT_RANGE_PRESET = '3';
232
+
233
+ function presetRange(value) {
234
+ return { kind: 'preset', value: String(value) };
235
+ }
236
+
237
+ function presetDef(value) {
238
+ return RANGE_PRESETS.find((p) => p.value === String(value));
239
+ }
240
+
241
+ function isPresetValue(v) {
242
+ return !!presetDef(v);
243
+ }
244
+
245
+ function isCustomRange(r) {
246
+ return r?.kind === 'custom';
247
+ }
248
+
249
+ // '1 DAY' is gone: under calendar semantics it would have duplicated TODAY, so the rolling day it
250
+ // used to mean is now '24h'. Without this, a stored "1" stops being a preset value and silently
251
+ // lands on the default instead of on the shortcut that kept its meaning.
252
+ function migrateStoredPreset(value) {
253
+ const s = String(value);
254
+ return s === '1' ? '24h' : s;
255
+ }
256
+
257
+ // Reads the JSON tagged union and the legacy bare "3" / "today" scalar that predates it: the key is
258
+ // a preference, so clearLocalCache() never evicts it and old values outlive any cache clear.
259
+ // Anything unrecognized returns null, which lands on the default preset.
260
+ function parseStoredRange(raw) {
261
+ if (!raw) return null;
262
+ let v;
263
+ try {
264
+ v = JSON.parse(raw);
265
+ } catch {
266
+ v = raw; // the legacy bare 'today' is not valid JSON
267
+ }
268
+ if (v?.kind === 'custom') {
269
+ return ISO_DATE_RE.test(v.from) && ISO_DATE_RE.test(v.to) && v.from <= v.to
270
+ ? { kind: 'custom', from: v.from, to: v.to }
271
+ : null;
272
+ }
273
+ const s = migrateStoredPreset(v?.kind === 'preset' ? v.value : v);
274
+ return isPresetValue(s) ? presetRange(s) : null;
275
+ }
276
+
184
277
  function loadDateRange() {
185
- const v = localStorage.getItem('cc-cost:range');
186
- if (!v) return 3;
187
- if (v === 'today') return 'today';
188
- return parseInt(v, 10) || 3;
278
+ return parseStoredRange(localStorage.getItem('cc-cost:range')) || presetRange(DEFAULT_RANGE_PRESET);
189
279
  }
190
280
 
191
281
  function saveDateRange(val) {
192
- localStorage.setItem('cc-cost:range', String(val));
282
+ localStorage.setItem('cc-cost:range', JSON.stringify(val));
193
283
  }
194
284
 
195
285
  function loadScope() {
@@ -214,8 +304,79 @@ function saveScope() {
214
304
  }
215
305
  }
216
306
 
217
- function rangeLabel(r) {
218
- return r === 'today' ? 'today' : `${r} days`;
307
+ // The range reaches these labels either as the client's tagged union or as the shape the server
308
+ // echoes back on the session detail payload: 'today', N days, null for all time, or a bare
309
+ // { from, to } window.
310
+ function normalizeRange(r) {
311
+ if (r == null) return null;
312
+ if (typeof r === 'object') {
313
+ if (r.kind === 'preset' && isPresetValue(r.value)) return presetRange(r.value);
314
+ if (r.from && r.to) return { kind: 'custom', from: r.from, to: r.to };
315
+ return null;
316
+ }
317
+ if (isPresetValue(r)) return presetRange(r);
318
+ // A legacy `range=1` from a bookmarked URL: the server reads it as one calendar day, which is
319
+ // today. Without this it is a positive integer that names no preset, so it would label as
320
+ // "all time" — the shape normalizeRange returns for something it does not recognize.
321
+ if (String(r) === '1') return presetRange('today');
322
+ const n = Number(r);
323
+ return Number.isFinite(n) && n > 0 ? presetRange(n) : null;
324
+ }
325
+
326
+ // "AUG 1 - AUG 12"; a single-day window is just "AUG 12".
327
+ function rangeSpanLabel(r) {
328
+ return r.from === r.to ? isoDayLabel(r.to) : `${isoDayLabel(r.from)} - ${isoDayLabel(r.to)}`;
329
+ }
330
+
331
+ // Every label variant is the same four-way classification of the range — all time, a custom window,
332
+ // today, a rolling preset — with one phrase per class, so only the phrasing lives in the callers:
333
+ // presets keep their rolling phrasing ("last 7 days"), while a custom window is named by its dates,
334
+ // where a "last" prefix would be nonsense. The rolling preset measured in hours must never be
335
+ // pluralized as days, and the empty-state article only fits the rolling presets.
336
+ function rangeText(r, prefix = {}) {
337
+ const n = normalizeRange(r);
338
+ const kind = !n ? 'all' : n.kind === 'custom' ? 'custom' : n.value === 'today' ? 'today' : 'rolling';
339
+ const base =
340
+ kind === 'all'
341
+ ? 'all time'
342
+ : kind === 'custom'
343
+ ? rangeSpanLabel(n)
344
+ : kind === 'today'
345
+ ? 'today'
346
+ : n.value === '24h'
347
+ ? '24 hours'
348
+ : `${n.value} days`;
349
+ return (prefix[kind] || '') + base;
350
+ }
351
+
352
+ const rangeLabel = (r) => rangeText(r);
353
+ const rangeScopeLabel = (r) => rangeText(r, { rolling: 'last ' });
354
+ const rangeInLabel = (r) => rangeText(r, { all: 'in ', custom: 'in ', rolling: 'in the last ' });
355
+
356
+ // Uppercase, for the picker trigger: the preset's own name, or the window's dates.
357
+ const rangeTriggerLabel = (r) => {
358
+ const n = normalizeRange(r) || presetRange(DEFAULT_RANGE_PRESET);
359
+ if (n.kind === 'custom') return rangeSpanLabel(n);
360
+ const def = presetDef(n.value);
361
+ return (def ? def.label : rangeText(n)).toUpperCase();
362
+ };
363
+
364
+ // The overview's window card: "3 Days" for an N-day preset, the preset's own name for a clock preset
365
+ // ("Last 24h"), the date span for a custom window. '1 Year' is the one name that does not fit the
366
+ // card, hence cardLabel.
367
+ const rangeCardLabel = (r) => {
368
+ const n = normalizeRange(r);
369
+ if (!n) return 'All Time';
370
+ if (n.kind === 'custom') return rangeSpanLabel(n);
371
+ const def = presetDef(n.value);
372
+ return def ? def.cardLabel || def.label : `${n.value} Days`;
373
+ };
374
+
375
+ // That card duplicates the Today card when the window is exactly today, so it is dropped instead.
376
+ function isTodayOnlyRange(r) {
377
+ const n = normalizeRange(r);
378
+ if (!n) return false;
379
+ return n.kind === 'custom' ? n.from === n.to && n.to === todayIso() : n.value === 'today';
219
380
  }
220
381
 
221
382
  function loadSort() {
@@ -255,7 +416,7 @@ function updateUrl() {
255
416
  // #region FETCH
256
417
 
257
418
  const BROWSER_CACHE_TTL = 5 * 60 * 1000; // 5 min
258
- const CACHE_VERSION = 3;
419
+ const CACHE_VERSION = 6;
259
420
  let forceRefresh = false;
260
421
  // Age of the data on screen, for the auto-refresh staleness check. A cache hit carries its own
261
422
  // timestamp forward, so a reload with a warm cache doesn't look freshly fetched.
@@ -336,8 +497,14 @@ function scopeParam() {
336
497
  return scopeProject ? `&project=${encodeURIComponent(scopeProject)}` : '';
337
498
  }
338
499
 
500
+ // Presets stay on the rolling `range` param, recomputed server-side; a custom window sends its two
501
+ // local dates, which take precedence over `range`. Every range-consuming fetch goes through this.
502
+ function rangeParams(r = dateRange) {
503
+ return isCustomRange(r) ? `from=${r.from}&to=${r.to}` : `range=${encodeURIComponent(r.value)}`;
504
+ }
505
+
339
506
  async function fetchOverview() {
340
- overviewData = await fetchJSON(`/api/overview?range=${dateRange}${scopeParam()}`);
507
+ overviewData = await fetchJSON(`/api/overview?${rangeParams()}${scopeParam()}`);
341
508
  }
342
509
 
343
510
  // Fire-and-forget label upgrade: /api/projects/:path/sessions carries no project name, so ask
@@ -345,7 +512,7 @@ async function fetchOverview() {
345
512
  async function resolveScopeName() {
346
513
  const target = scopeProject;
347
514
  try {
348
- const rows = await fetchJSON(`/api/projects?range=${dateRange}${scopeParam()}`);
515
+ const rows = await fetchJSON(`/api/projects?${rangeParams()}${scopeParam()}`);
349
516
  const name = rows?.[0]?.encodedPath === target ? rows[0].name : null;
350
517
  if (!name || scopeProject !== target) return;
351
518
  scopeProjectName = name;
@@ -362,18 +529,18 @@ async function resolveScopeName() {
362
529
  }
363
530
 
364
531
  async function fetchProjects() {
365
- projectsData = await fetchJSON(`/api/projects?range=${dateRange}${scopeParam()}`);
532
+ projectsData = await fetchJSON(`/api/projects?${rangeParams()}${scopeParam()}`);
366
533
  }
367
534
 
368
535
  async function fetchSessions(encodedPath) {
369
- const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?range=${dateRange}`, true);
536
+ const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?${rangeParams()}`, true);
370
537
  sessionsData = data.sessions;
371
- sessionsDaily = data.daily || [];
538
+ sessionsCostSeries = data.costSeries;
372
539
  sessionsModelDistribution = data.modelDistribution || [];
373
540
  }
374
541
 
375
542
  async function fetchSessionDetail(sessionId) {
376
- sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}`, true);
543
+ sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}?${rangeParams()}`, true);
377
544
  // Populate project context when opening via deep link (no project in URL)
378
545
  if (sessionDetailData && !currentProjectPath) {
379
546
  currentProjectPath = sessionDetailData.encodedProjectPath;
@@ -400,7 +567,7 @@ function renderOverview() {
400
567
  if (lastRenderHash.overview === h) return;
401
568
  lastRenderHash.overview = h;
402
569
 
403
- const daily = overviewData.daily || [];
570
+ const costSeries = overviewData.costSeries;
404
571
  const models = overviewData.modelDistribution || [];
405
572
 
406
573
  // Return before any chart call so no canvas is touched — there are none in this markup.
@@ -409,7 +576,7 @@ function renderOverview() {
409
576
  ${scopeIndicator()}
410
577
  <div class="empty-state">
411
578
  <div class="empty-icon">$</div>
412
- <div>No usage for ${esc(scopeProjectName || scopeProject)} in the last ${rangeLabel(dateRange)}</div>
579
+ <div>No usage for ${esc(scopeProjectName || scopeProject)} ${esc(rangeInLabel(dateRange))}</div>
413
580
  <div>Clear the project scope to see everything.</div>
414
581
  </div>
415
582
  </div>`;
@@ -420,16 +587,23 @@ function renderOverview() {
420
587
  <div class="dashboard-content">
421
588
  ${scopeIndicator()}
422
589
  <div class="cards-row">
590
+ ${
591
+ // Null rather than 0 when the window ends before today: a zero here would read as
592
+ // "nothing spent today" instead of "today is outside the selected window".
593
+ s.todayCost == null
594
+ ? ''
595
+ : `
423
596
  <div class="stat-card">
424
597
  <div class="card-label">Today</div>
425
598
  <div class="card-value cost">${formatCost(s.todayCost)}</div>
426
- </div>
599
+ </div>`
600
+ }
427
601
  ${
428
- dateRange === 'today'
602
+ isTodayOnlyRange(dateRange)
429
603
  ? ''
430
604
  : `
431
605
  <div class="stat-card">
432
- <div class="card-label">${dateRange} Days</div>
606
+ <div class="card-label">${esc(rangeCardLabel(dateRange))}</div>
433
607
  <div class="card-value cost">${formatCost(s.totalCost)}</div>
434
608
  </div>`
435
609
  }
@@ -451,8 +625,8 @@ function renderOverview() {
451
625
 
452
626
  <div class="charts-row">
453
627
  <div class="chart-box">
454
- <div class="chart-title">Daily Cost</div>
455
- <canvas id="dailyChart"></canvas>
628
+ <div class="chart-title">${costSeriesTitle(costSeries)}</div>
629
+ <canvas id="costChart"></canvas>
456
630
  </div>
457
631
  <div class="chart-box">
458
632
  <div class="chart-title">Cost by Model</div>
@@ -492,7 +666,7 @@ function renderOverview() {
492
666
 
493
667
  // Render charts after DOM is ready
494
668
  requestAnimationFrame(() => {
495
- renderDailyChart(daily);
669
+ renderCostChart(costSeries, 'costChart', 'cost', models);
496
670
  renderModelChart(models);
497
671
  });
498
672
  }
@@ -522,7 +696,7 @@ function renderProjects() {
522
696
  <div class="empty-icon">$</div>
523
697
  ${
524
698
  scopeProject
525
- ? `<div>No usage for ${esc(scopeProjectName || scopeProject)} in the last ${rangeLabel(dateRange)}</div>
699
+ ? `<div>No usage for ${esc(scopeProjectName || scopeProject)} ${esc(rangeInLabel(dateRange))}</div>
526
700
  <div>Clear the project scope to see everything.</div>`
527
701
  : `<div>No project data found</div>
528
702
  <div>Make sure Claude Code session files exist in ~/.claude/projects/</div>`
@@ -572,7 +746,7 @@ function renderSessions() {
572
746
  return;
573
747
  }
574
748
 
575
- const h = JSON.stringify({ sessionsData, sessionsDaily, sessionsModelDistribution, sort: viewSort.sessions });
749
+ const h = JSON.stringify({ sessionsData, sessionsCostSeries, sessionsModelDistribution, sort: viewSort.sessions });
576
750
  if (lastRenderHash.sessions === h) return;
577
751
  lastRenderHash.sessions = h;
578
752
 
@@ -597,8 +771,8 @@ function renderSessions() {
597
771
  </div>
598
772
  <div class="charts-row" style="grid-template-columns:3fr 2fr auto">
599
773
  <div class="chart-box">
600
- <div class="chart-title">Daily Cost</div>
601
- <canvas id="sessionsDailyChart"></canvas>
774
+ <div class="chart-title">${costSeriesTitle(sessionsCostSeries)}</div>
775
+ <canvas id="sessionsCostChart"></canvas>
602
776
  </div>
603
777
  <div class="chart-box">
604
778
  <div class="chart-title">Cost by Model</div>
@@ -642,7 +816,7 @@ function renderSessions() {
642
816
  </div>`;
643
817
 
644
818
  requestAnimationFrame(() => {
645
- renderDailyChart(sessionsDaily || [], 'sessionsDailyChart', 'sessionsDaily');
819
+ renderCostChart(sessionsCostSeries, 'sessionsCostChart', 'sessionsCost', sessionsModelDistribution || []);
646
820
  renderModelChart(sessionsModelDistribution || [], 'sessionsModelChart', 'sessionsModel');
647
821
  });
648
822
  }
@@ -679,7 +853,7 @@ function renderDetail() {
679
853
  <div class="detail-header">
680
854
  <div class="detail-stat">
681
855
  <div class="detail-label">Total Cost</div>
682
- <div class="detail-value cost">${formatCost(d.totalCost)}</div>
856
+ <div class="detail-value cost">${formatCost(d.totalCost)}<span class="detail-label detail-scope">all time</span></div>
683
857
  </div>
684
858
  <div class="detail-stat">
685
859
  <div class="detail-label">Input</div>
@@ -699,17 +873,16 @@ function renderDetail() {
699
873
  </div>
700
874
  <div class="detail-stat">
701
875
  <div class="detail-label">Messages</div>
702
- <div class="detail-value">${d.messages.length}</div>
876
+ <div class="detail-value">${d.messages.length}<span class="detail-label detail-scope">all time</span></div>
703
877
  </div>
704
878
  <div class="detail-stat">
705
879
  <div class="detail-label">Models</div>
706
- <div class="detail-value">${d.models
707
- .map((m) => shortModel(m))
708
- .filter(Boolean)
709
- .join(', ')}</div>
880
+ <div class="detail-value">${esc(d.models.map((m) => shortModel(m)).join(', '))}</div>
710
881
  </div>
711
882
  </div>
712
883
 
884
+ ${detailRangeNote(d)}
885
+
713
886
  <div class="charts-row" style="margin-bottom:20px">
714
887
  <div class="chart-box">
715
888
  <div class="chart-title">Cumulative Cost</div>
@@ -747,6 +920,23 @@ function renderDetail() {
747
920
  });
748
921
  }
749
922
 
923
+ // The session row that links here is scoped to the active range, so a session older than the
924
+ // range would otherwise show larger numbers here with no explanation.
925
+ function detailRangeNote(d) {
926
+ const all = d.messages.length;
927
+ const slice = (label, s) =>
928
+ `<span class="scope-label">${esc(label)}</span> <strong>${formatCost(s.totalCost)}</strong> / ${s.messageCount} msg`;
929
+ // A slice worth showing is a real subset: neither empty nor the whole session.
930
+ const worthShowing = (s) => s && s.messageCount > 0 && s.messageCount < all;
931
+ const parts = [];
932
+ if (worthShowing(d.inRange)) parts.push(slice(rangeScopeLabel(d.range), d.inRange));
933
+ if (worthShowing(d.today) && d.today.messageCount !== d.inRange?.messageCount) {
934
+ parts.push(slice('today', d.today));
935
+ }
936
+ if (!parts.length) return '';
937
+ return `<div class="detail-range-note">Totals above are all-time &middot; ${parts.join(' &middot; ')}</div>`;
938
+ }
939
+
750
940
  function buildMessageRowsWithSubagents(d) {
751
941
  return [...d.messages]
752
942
  .reverse()
@@ -794,6 +984,11 @@ function getChartColors() {
794
984
  };
795
985
  }
796
986
 
987
+ // Single source of the series palette so per-model colors match across charts.
988
+ function chartPalette(c) {
989
+ return [c.chart1, c.chart2, c.chart3, c.chart4, c.chart5, c.chart6];
990
+ }
991
+
797
992
  // Translucent fill from a hex color so chart bars read as a quiet wash, not a solid block.
798
993
  function hexToRgba(hex, alpha) {
799
994
  const h = hex.replace('#', '');
@@ -838,28 +1033,41 @@ function destroyChart(id) {
838
1033
  }
839
1034
  }
840
1035
 
841
- function renderDailyChart(daily, canvasId = 'dailyChart', chartKey = 'daily') {
1036
+ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost', distribution = []) {
1037
+ const points = series?.points;
842
1038
  const canvas = document.getElementById(canvasId);
843
- if (!canvas || !daily?.length) return;
1039
+ if (!canvas || !points?.length) return;
844
1040
  destroyChart(chartKey);
845
1041
 
846
1042
  const c = getChartColors();
847
1043
  const defaults = chartDefaults();
848
1044
 
1045
+ // Stack order follows modelDistribution so segment colors line up with the Cost by Model
1046
+ // chart rendered next to it. 'other' (synthetic models) is absent from the distribution
1047
+ // and lands at the end.
1048
+ const present = new Set();
1049
+ for (const p of points) {
1050
+ for (const m in p.byModel) if (p.byModel[m] > 0) present.add(m);
1051
+ }
1052
+ const models = distribution.filter((d) => present.has(d.model)).map((d) => d.model);
1053
+ for (const m of present) if (!models.includes(m)) models.push(m);
1054
+ const palette = chartPalette(c);
1055
+
1056
+ const datasets = models.map((m, i) => ({
1057
+ label: shortModel(m),
1058
+ data: points.map((p) => p.byModel?.[m] || 0),
1059
+ backgroundColor: hexToRgba(palette[i % palette.length], 0.5),
1060
+ borderColor: palette[i % palette.length],
1061
+ borderWidth: 1.5,
1062
+ borderRadius: 2,
1063
+ stack: 'cost',
1064
+ }));
1065
+
849
1066
  charts[chartKey] = new Chart(canvas, {
850
1067
  type: 'bar',
851
1068
  data: {
852
- labels: daily.map((d) => shortDate(d.date)),
853
- datasets: [
854
- {
855
- label: 'Daily Cost',
856
- data: daily.map((d) => d.cost),
857
- backgroundColor: c.chartFill,
858
- borderColor: c.accent,
859
- borderWidth: 1.5,
860
- borderRadius: 3,
861
- },
862
- ],
1069
+ labels: points.map((p) => bucketLabel(p.key, series.bucket)),
1070
+ datasets,
863
1071
  },
864
1072
  options: {
865
1073
  ...defaults,
@@ -867,6 +1075,12 @@ function renderDailyChart(daily, canvasId = 'dailyChart', chartKey = 'daily') {
867
1075
  events: [],
868
1076
  plugins: {
869
1077
  ...defaults.plugins,
1078
+ // events: [] disables tooltips, so the legend is the only place segment names show.
1079
+ legend: {
1080
+ display: models.length > 1,
1081
+ position: 'bottom',
1082
+ labels: { color: c.text, font: { size: 9 }, boxWidth: 8, boxHeight: 8 },
1083
+ },
870
1084
  tooltip: {
871
1085
  ...defaults.plugins.tooltip,
872
1086
  callbacks: { label: (ctx) => `$${ctx.parsed.y.toFixed(2)}` },
@@ -874,8 +1088,10 @@ function renderDailyChart(daily, canvasId = 'dailyChart', chartKey = 'daily') {
874
1088
  },
875
1089
  scales: {
876
1090
  ...defaults.scales,
1091
+ x: { ...defaults.scales.x, stacked: true },
877
1092
  y: {
878
1093
  ...defaults.scales.y,
1094
+ stacked: true,
879
1095
  ticks: { ...defaults.scales.y.ticks, callback: (v) => `$${v.toFixed(2)}` },
880
1096
  },
881
1097
  },
@@ -889,7 +1105,7 @@ function renderModelChart(models, canvasId = 'modelChart', chartKey = 'model') {
889
1105
  destroyChart(chartKey);
890
1106
 
891
1107
  const colors = getChartColors();
892
- const palette = [colors.chart1, colors.chart2, colors.chart3, colors.chart4, colors.chart5, colors.chart6];
1108
+ const palette = chartPalette(colors);
893
1109
  const defaults = chartDefaults();
894
1110
  const total = models.reduce((s, m) => s + m.cost, 0);
895
1111
 
@@ -1125,6 +1341,326 @@ function setColorTheme(id) {
1125
1341
 
1126
1342
  // #endregion
1127
1343
 
1344
+ // #region DATE_PICKER
1345
+
1346
+ // Presets are sticky: what is stored is the preset, and the server recomputes its rolling window on
1347
+ // every request. `days` only previews the span inside the calendar.
1348
+ const RANGE_PRESETS = [
1349
+ { value: 'today', label: 'Today', days: 0 },
1350
+ { value: '24h', label: 'Last 24h', days: 1 },
1351
+ { value: '3', label: '3 Days', days: 3 },
1352
+ { value: '7', label: '7 Days', days: 7 },
1353
+ { value: '30', label: '30 Days', days: 30 },
1354
+ { value: '90', label: '90 Days', days: 90 },
1355
+ { value: '365', label: '1 Year', days: 365, cardLabel: '365 Days' },
1356
+ ];
1357
+ const RANGE_DOW = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
1358
+ // Two months do not fit a narrow window, so below this the calendar collapses to one. Kept in step
1359
+ // with the same breakpoint in style.css.
1360
+ const ONE_MONTH_QUERY = '(max-width: 760px)';
1361
+ // One live MediaQueryList: matchMedia() hands back a new object each call, so add/removeEventListener
1362
+ // have to share this one or the listener never comes off.
1363
+ const oneMonthMql = window.matchMedia(ONE_MONTH_QUERY);
1364
+ const RANGE_ARROWS = {
1365
+ prev: '<path d="M6.5 1L2.5 5l4 4"/>',
1366
+ next: '<path d="M3.5 1l4 4-4 4"/>',
1367
+ };
1368
+
1369
+ // Non-null only while the popover is open — it is both the draft and the open flag. `picking` is
1370
+ // which end the next day click lands on; `hover` previews the span before the second click.
1371
+ let rangeDraft = null;
1372
+
1373
+ function isRangePickerOpen() {
1374
+ return !!rangeDraft;
1375
+ }
1376
+
1377
+ function oneMonthMode() {
1378
+ return oneMonthMql.matches;
1379
+ }
1380
+
1381
+ // What a preset covers, for highlighting only. '24h' is named here because its span is not a day
1382
+ // count: it straddles the two calendar days a rolling day touches. Everything else is the last N
1383
+ // calendar days ending today, which is now exactly the window the server fetches — 'today' included,
1384
+ // since a span of one day or less is today itself.
1385
+ function rangePresetSpan(value) {
1386
+ const today = todayIso();
1387
+ if (value === '24h') return { from: isoShift(today, -1), to: today };
1388
+ const days = Number(value) || 1;
1389
+ return { from: days <= 1 ? today : isoShift(today, -(days - 1)), to: today };
1390
+ }
1391
+
1392
+ function buildRangePresets() {
1393
+ const host = document.getElementById('rangePresets');
1394
+ if (!host) return;
1395
+ for (const p of RANGE_PRESETS) {
1396
+ const b = document.createElement('button');
1397
+ b.type = 'button';
1398
+ b.className = 'range-preset';
1399
+ b.dataset.value = p.value;
1400
+ b.textContent = p.label;
1401
+ // A shortcut is one click, like the dropdown it replaces: apply and close, no Apply button.
1402
+ b.addEventListener('click', () => {
1403
+ closeRangePicker();
1404
+ applyRange(presetRange(p.value));
1405
+ });
1406
+ host.appendChild(b);
1407
+ }
1408
+ }
1409
+
1410
+ function renderRangeTrigger() {
1411
+ const el = document.getElementById('rangeTriggerLabel');
1412
+ if (el) el.textContent = rangeTriggerLabel(dateRange);
1413
+ }
1414
+
1415
+ // biome-ignore lint/correctness/noUnusedVariables: called from topbar markup
1416
+ function toggleRangePicker(e) {
1417
+ e?.stopPropagation();
1418
+ if (isRangePickerOpen()) closeRangePicker();
1419
+ else openRangePicker();
1420
+ }
1421
+
1422
+ function openRangePicker() {
1423
+ const applied = normalizeRange(dateRange) || presetRange(DEFAULT_RANGE_PRESET);
1424
+ const span = applied.kind === 'custom' ? { from: applied.from, to: applied.to } : rangePresetSpan(applied.value);
1425
+ // The left pane shows the month before the window's end, so today sits in the right one; with a
1426
+ // single month it is that month itself.
1427
+ const [ay, am] = isoParts(span.to);
1428
+ const first = new Date(ay, am - 1 - (oneMonthMode() ? 0 : 1), 1);
1429
+ rangeDraft = {
1430
+ from: span.from,
1431
+ to: span.to,
1432
+ preset: applied.kind === 'custom' ? null : applied.value,
1433
+ picking: 'from',
1434
+ hover: null,
1435
+ month: { y: first.getFullYear(), m: first.getMonth() },
1436
+ };
1437
+ document.getElementById('rangePop').classList.add('open');
1438
+ document.getElementById('rangeTrigger').classList.add('on');
1439
+ // Capture phase: a day click re-renders the grid and detaches its own button, so by the bubble
1440
+ // phase the target is no longer inside #rangePicker and would read as an outside click.
1441
+ document.addEventListener('click', onRangePickerOutsideClick, true);
1442
+ const months = document.getElementById('rangeMonths');
1443
+ months.addEventListener('click', onRangeDayClick);
1444
+ months.addEventListener('mouseover', onRangeDayHover);
1445
+ oneMonthMql.addEventListener('change', renderRangePicker);
1446
+ renderRangePicker();
1447
+ }
1448
+
1449
+ function closeRangePicker() {
1450
+ if (!rangeDraft) return;
1451
+ rangeDraft = null;
1452
+ document.getElementById('rangePop').classList.remove('open');
1453
+ document.getElementById('rangeTrigger').classList.remove('on');
1454
+ document.removeEventListener('click', onRangePickerOutsideClick, true);
1455
+ const months = document.getElementById('rangeMonths');
1456
+ months.removeEventListener('click', onRangeDayClick);
1457
+ months.removeEventListener('mouseover', onRangeDayHover);
1458
+ oneMonthMql.removeEventListener('change', renderRangePicker);
1459
+ }
1460
+
1461
+ // Both grids are delegated: one listener pair on #rangeMonths instead of two per day cell. Only the
1462
+ // selectable days carry data-iso, so the lead padding and the days after today stay inert. It has to
1463
+ // be 'mouseover' — 'mouseenter' does not bubble, so it cannot be delegated.
1464
+ function onRangeDayClick(e) {
1465
+ const iso = e.target.dataset?.iso;
1466
+ if (iso) pickRangeDay(iso);
1467
+ }
1468
+
1469
+ function onRangeDayHover(e) {
1470
+ const iso = e.target.dataset?.iso;
1471
+ if (iso && rangeDraft?.from && !rangeDraft.to && rangeDraft.hover !== iso) {
1472
+ rangeDraft.hover = iso;
1473
+ paintRangeSpan();
1474
+ }
1475
+ }
1476
+
1477
+ // Outside click cancels: the draft is dropped and the applied range stays.
1478
+ function onRangePickerOutsideClick(e) {
1479
+ if (!document.getElementById('rangePicker').contains(e.target)) closeRangePicker();
1480
+ }
1481
+
1482
+ // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
1483
+ function aimRangePicker(which) {
1484
+ if (!rangeDraft) return;
1485
+ rangeDraft.picking = which;
1486
+ renderRangePicker();
1487
+ }
1488
+
1489
+ // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
1490
+ function applyRangeDraft() {
1491
+ const d = rangeDraft;
1492
+ if (!d?.from || !d.to) return;
1493
+ const next = { kind: 'custom', from: d.from, to: d.to };
1494
+ closeRangePicker();
1495
+ applyRange(next);
1496
+ }
1497
+
1498
+ function pickRangeDay(iso) {
1499
+ const d = rangeDraft;
1500
+ d.preset = null;
1501
+ if (d.picking === 'from' || !d.from) {
1502
+ d.from = iso;
1503
+ d.to = null;
1504
+ d.picking = 'to';
1505
+ } else if (iso < d.from) {
1506
+ // A second click before the first flips the pair instead of refusing it.
1507
+ d.to = d.from;
1508
+ d.from = iso;
1509
+ d.picking = 'from';
1510
+ } else {
1511
+ d.to = iso;
1512
+ d.picking = 'from';
1513
+ }
1514
+ d.hover = null;
1515
+ renderRangePicker();
1516
+ }
1517
+
1518
+ function rangeMonthStep(step) {
1519
+ const c = new Date(rangeDraft.month.y, rangeDraft.month.m + step, 1);
1520
+ rangeDraft.month = { y: c.getFullYear(), m: c.getMonth() };
1521
+ renderRangePicker();
1522
+ }
1523
+
1524
+ // There is no cost data ahead of today, so the calendar stops at the current month.
1525
+ function rangeNextDisabled() {
1526
+ const last = new Date(rangeDraft.month.y, rangeDraft.month.m + (oneMonthMode() ? 0 : 1), 1);
1527
+ const now = new Date();
1528
+ return last >= new Date(now.getFullYear(), now.getMonth(), 1);
1529
+ }
1530
+
1531
+ // The highlighted span: the picked window, or from -> the hovered day while the second end is open.
1532
+ function rangeDraftSpan() {
1533
+ const d = rangeDraft;
1534
+ if (!d?.from) return [null, null];
1535
+ if (d.to) return [d.from, d.to];
1536
+ if (!d.hover) return [d.from, d.from];
1537
+ return d.hover < d.from ? [d.hover, d.from] : [d.from, d.hover];
1538
+ }
1539
+
1540
+ // The span highlight is four classes on day cells that already exist, so a hover repaint toggles
1541
+ // them in place instead of rebuilding both grids. Sole owner of those classes — buildRangeMonth
1542
+ // leaves them to the paint pass that follows it, so the two can never drift apart.
1543
+ function paintRangeSpan() {
1544
+ const [a, b] = rangeDraftSpan();
1545
+ for (const btn of document.querySelectorAll('#rangeMonths .range-day[data-iso]')) {
1546
+ const iso = btn.dataset.iso;
1547
+ const inSpan = !!(a && b && iso >= a && iso <= b);
1548
+ const edge = inSpan && (iso === a || iso === b);
1549
+ btn.classList.toggle('edge', edge);
1550
+ btn.classList.toggle('in', inSpan && !edge);
1551
+ btn.classList.toggle('start', inSpan && !edge && isoShift(iso, -1) === a);
1552
+ btn.classList.toggle('end', inSpan && !edge && isoShift(iso, 1) === b);
1553
+ }
1554
+ }
1555
+
1556
+ function renderRangePicker() {
1557
+ const d = rangeDraft;
1558
+ if (!d) return;
1559
+
1560
+ for (const b of document.querySelectorAll('#rangePresets .range-preset')) {
1561
+ b.classList.toggle('on', b.dataset.value === d.preset);
1562
+ }
1563
+
1564
+ const fromBox = document.getElementById('rangeFromBox');
1565
+ const toBox = document.getElementById('rangeToBox');
1566
+ fromBox.textContent = d.from ? isoDayLabel(d.from) : '—';
1567
+ toBox.textContent = d.to ? isoDayLabel(d.to) : '—';
1568
+ fromBox.classList.toggle('empty', !d.from);
1569
+ toBox.classList.toggle('empty', !d.to);
1570
+ fromBox.classList.toggle('active', d.picking === 'from');
1571
+ toBox.classList.toggle('active', d.picking === 'to');
1572
+
1573
+ const [a, b] = rangeDraftSpan();
1574
+ const days = d.from && d.to ? isoDayCount(a, b) : 0;
1575
+ document.getElementById('rangeSummary').textContent = days
1576
+ ? `${days} ${days === 1 ? 'day' : 'days'}`
1577
+ : 'pick an end date';
1578
+ document.getElementById('rangeApply').disabled = !(d.from && d.to);
1579
+
1580
+ const host = document.getElementById('rangeMonths');
1581
+ host.innerHTML = '';
1582
+ const single = oneMonthMode();
1583
+ const first = new Date(d.month.y, d.month.m, 1);
1584
+ host.appendChild(buildRangeMonth(first.getFullYear(), first.getMonth(), { prev: true, next: single }));
1585
+ if (!single) {
1586
+ const second = new Date(d.month.y, d.month.m + 1, 1);
1587
+ host.appendChild(buildRangeMonth(second.getFullYear(), second.getMonth(), { prev: false, next: true }));
1588
+ }
1589
+ paintRangeSpan();
1590
+ }
1591
+
1592
+ function rangeNavButton(dir) {
1593
+ const step = dir === 'next' ? 1 : -1;
1594
+ const btn = document.createElement('button');
1595
+ btn.type = 'button';
1596
+ btn.className = 'range-nav';
1597
+ btn.innerHTML = `<svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">${RANGE_ARROWS[dir]}</svg>`;
1598
+ if (step > 0) btn.disabled = rangeNextDisabled();
1599
+ btn.addEventListener('click', () => rangeMonthStep(step));
1600
+ return btn;
1601
+ }
1602
+
1603
+ // Holds the title centred on the side that carries no arrow.
1604
+ function rangeNavGap() {
1605
+ const gap = document.createElement('span');
1606
+ gap.className = 'range-nav-gap';
1607
+ return gap;
1608
+ }
1609
+
1610
+ function buildRangeMonth(y, m, nav) {
1611
+ const wrap = document.createElement('div');
1612
+ wrap.className = 'range-cal';
1613
+
1614
+ const title = new Date(y, m, 1).toLocaleDateString(undefined, { month: 'short' }).toUpperCase();
1615
+
1616
+ const head = document.createElement('div');
1617
+ head.className = 'range-cal-head';
1618
+ head.appendChild(nav.prev ? rangeNavButton('prev') : rangeNavGap());
1619
+ const titleEl = document.createElement('span');
1620
+ titleEl.className = 'range-cal-title';
1621
+ titleEl.textContent = `${title} ${y}`;
1622
+ head.appendChild(titleEl);
1623
+ head.appendChild(nav.next ? rangeNavButton('next') : rangeNavGap());
1624
+ wrap.appendChild(head);
1625
+
1626
+ const dow = document.createElement('div');
1627
+ dow.className = 'range-dow';
1628
+ dow.innerHTML = RANGE_DOW.map((d) => `<span>${d}</span>`).join('');
1629
+ wrap.appendChild(dow);
1630
+
1631
+ const grid = document.createElement('div');
1632
+ grid.className = 'range-grid';
1633
+ const lead = (new Date(y, m, 1).getDay() + 6) % 7; // Monday-first
1634
+ const dayCount = new Date(y, m + 1, 0).getDate();
1635
+ const today = todayIso();
1636
+
1637
+ for (let i = 0; i < lead; i++) {
1638
+ const pad = document.createElement('span');
1639
+ pad.className = 'range-day pad';
1640
+ grid.appendChild(pad);
1641
+ }
1642
+ for (let day = 1; day <= dayCount; day++) {
1643
+ const iso = isoDate(new Date(y, m, day));
1644
+ const btn = document.createElement('button');
1645
+ btn.type = 'button';
1646
+ btn.className = 'range-day';
1647
+ btn.textContent = day;
1648
+ if (iso === today) btn.classList.add('today');
1649
+ if (iso > today) {
1650
+ btn.classList.add('off');
1651
+ btn.disabled = true;
1652
+ } else {
1653
+ // What the delegated click/hover handlers and paintRangeSpan read the cell's day back from.
1654
+ btn.dataset.iso = iso;
1655
+ }
1656
+ grid.appendChild(btn);
1657
+ }
1658
+ wrap.appendChild(grid);
1659
+ return wrap;
1660
+ }
1661
+
1662
+ // #endregion
1663
+
1128
1664
  // #region ROUTER
1129
1665
 
1130
1666
  function setActiveNav(view) {
@@ -1197,11 +1733,13 @@ function sortBy(field) {
1197
1733
  else renderProjects();
1198
1734
  }
1199
1735
 
1200
- // biome-ignore lint/correctness/noUnusedVariables: called from HTML onchange
1201
- async function onRangeChange(val) {
1202
- dateRange = val === 'today' ? 'today' : parseInt(val, 10) || 7;
1736
+ // The one entry point for a range change, from either half of the picker. The lastRenderHash reset
1737
+ // is load-bearing: the renderers are hash-gated and would not repaint the new window otherwise.
1738
+ async function applyRange(next) {
1739
+ dateRange = next;
1203
1740
  saveDateRange(dateRange);
1204
1741
  lastRenderHash = {};
1742
+ renderRangeTrigger();
1205
1743
  updateUrl();
1206
1744
  const t = showToast(`Recalculating for ${rangeLabel(dateRange)}...`, true);
1207
1745
  await loadAndRender(currentView);
@@ -1432,6 +1970,16 @@ document.addEventListener('keydown', (e) => {
1432
1970
  return;
1433
1971
  }
1434
1972
 
1973
+ // The same exemption the modal above gets: the popover is a div, so the INPUT/SELECT guard does
1974
+ // not cover it, and r/t/j/k/Esc would otherwise fire straight through an open picker.
1975
+ if (isRangePickerOpen()) {
1976
+ if (e.key === 'Escape') {
1977
+ closeRangePicker();
1978
+ e.preventDefault();
1979
+ }
1980
+ return;
1981
+ }
1982
+
1435
1983
  if (e.ctrlKey || e.altKey || e.metaKey) return;
1436
1984
 
1437
1985
  if (e.key === '?' || (e.key === '/' && e.shiftKey)) {
@@ -1669,7 +2217,8 @@ document.addEventListener('click', async (e) => {
1669
2217
  document.addEventListener('DOMContentLoaded', async () => {
1670
2218
  const state = getUrlState();
1671
2219
  dateRange = loadDateRange();
1672
- document.getElementById('rangeSelect').value = dateRange;
2220
+ buildRangePresets();
2221
+ renderRangeTrigger();
1673
2222
 
1674
2223
  // Resolve the scope before any navigate() so the first /api/overview already carries
1675
2224
  // &project=. Read window.location.search directly, not getUrlState() — that falls back to