claude-code-cost 0.14.0 → 0.16.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
@@ -2,7 +2,7 @@
2
2
 
3
3
  let currentView = 'overview';
4
4
  let overviewData = null;
5
- let projectsData = null;
5
+ let insightsData = null;
6
6
  let sessionsData = null;
7
7
  let sessionsCostSeries = null;
8
8
  let sessionsModelDistribution = null;
@@ -15,16 +15,16 @@ let currentProjectName = null;
15
15
  let scopeProject = null;
16
16
  let scopeProjectName = null;
17
17
  let currentSessionId = null;
18
- let parentView = 'projects';
19
18
  let lastSelectedProject = null;
20
19
  let lastSelectedSession = null;
21
20
  const DEFAULT_SORT = {
22
21
  overview: { field: 'totalCost', order: 'desc' },
23
- projects: { field: 'lastActive', order: 'desc' },
24
22
  sessions: { field: 'lastTimestamp', order: 'desc' },
25
23
  };
26
24
  const viewSort = structuredClone(DEFAULT_SORT);
27
- let dateRange = 3;
25
+ // A tagged union: a rolling preset the server recomputes per request, or a concrete window of
26
+ // two local dates. Persisted as JSON under cc-cost:range (see loadDateRange).
27
+ let dateRange = { kind: 'preset', value: '3' };
28
28
  const charts = {};
29
29
  let lastRenderHash = {};
30
30
  let navCounter = 0;
@@ -70,6 +70,10 @@ function formatTokens(count) {
70
70
  return count.toString();
71
71
  }
72
72
 
73
+ function formatPct(part, total) {
74
+ return total > 0 ? ((part / total) * 100).toFixed(1) : '0.0';
75
+ }
76
+
73
77
  function formatDuration(minutes) {
74
78
  if (!minutes || minutes < 1) return '<1m';
75
79
  if (minutes < 60) return `${minutes}m`;
@@ -100,6 +104,43 @@ function bucketLabel(key, bucket) {
100
104
  return new Date(`${key}T00:00:00`).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
101
105
  }
102
106
 
107
+ // Local calendar dates as YYYY-MM-DD: the shape the range API takes, comparable with < and >.
108
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
109
+
110
+ function isoDate(d) {
111
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
112
+ }
113
+
114
+ function todayIso() {
115
+ return isoDate(new Date());
116
+ }
117
+
118
+ function isoParts(iso) {
119
+ return iso.split('-').map(Number);
120
+ }
121
+
122
+ function isoShift(iso, days) {
123
+ const [y, m, d] = isoParts(iso);
124
+ return isoDate(new Date(y, m - 1, d + days));
125
+ }
126
+
127
+ // Inclusive, so a single day counts as 1. Midday avoids a DST shift landing on a boundary.
128
+ function isoDayCount(from, to) {
129
+ const [ay, am, ad] = isoParts(from);
130
+ const [by, bm, bd] = isoParts(to);
131
+ return Math.round((new Date(by, bm - 1, bd, 12) - new Date(ay, am - 1, ad, 12)) / 86400000) + 1;
132
+ }
133
+
134
+ // "AUG 12", carrying a two-digit year only when the date falls outside the current one: "DEC 28 '25".
135
+ function isoDayLabel(iso) {
136
+ const [y] = isoParts(iso);
137
+ const yearTag = y === new Date().getFullYear() ? '' : ` '${String(y).slice(2)}`;
138
+ const dayLabel = new Date(`${iso}T00:00:00`)
139
+ .toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
140
+ .toUpperCase();
141
+ return `${dayLabel}${yearTag}`;
142
+ }
143
+
103
144
  function costSeriesTitle(series) {
104
145
  return series?.bucket === 'hour' ? 'Hourly Cost' : 'Daily Cost';
105
146
  }
@@ -137,10 +178,7 @@ function thClass(field) {
137
178
  return s && s.field === field ? 'sorted' : '';
138
179
  }
139
180
 
140
- function parentBreadcrumb() {
141
- const label = parentView === 'overview' ? 'Overview' : 'Projects';
142
- return `<a class="parent-breadcrumb">${label}</a>`;
143
- }
181
+ const PARENT_BREADCRUMB = '<a class="parent-breadcrumb">Overview</a>';
144
182
 
145
183
  // In-view reminder that the numbers below cover one project, not everything. Reuses the
146
184
  // breadcrumb styling — same role (where am I), no new CSS.
@@ -153,9 +191,17 @@ function scopeIndicator() {
153
191
  </div>`;
154
192
  }
155
193
 
194
+ // Top-level view switcher shared by the two sibling views. Drill-down views (sessions, detail)
195
+ // keep their breadcrumb instead — tabs only make sense at the root.
196
+ function viewTabs(active) {
197
+ const tab = (id, label) =>
198
+ `<button class="view-tab${active === id ? ' on' : ''}" onclick="navigate('${id}')">${label}</button>`;
199
+ return `<div class="view-tabs">${tab('overview', 'Overview')}${tab('insights', 'Insights')}</div>`;
200
+ }
201
+
156
202
  function focusPreviousRow(view) {
157
203
  let selector;
158
- if (view === 'overview' || view === 'projects') {
204
+ if (view === 'overview') {
159
205
  if (!lastSelectedProject) return;
160
206
  selector = `tr[onclick*="'${lastSelectedProject}'"]`;
161
207
  } else if (view === 'sessions') {
@@ -180,24 +226,68 @@ function getUrlState() {
180
226
  const saved = sessionStorage.getItem('cc-cost:nav');
181
227
  if (saved) p = new URLSearchParams(saved);
182
228
  }
229
+ const view = p.get('view') || 'overview';
183
230
  return {
184
- view: p.get('view') || 'overview',
231
+ // Old bookmarks may still say view=projects; that view is gone, overview covers it.
232
+ view: view === 'projects' ? 'overview' : view,
185
233
  project: p.get('project'),
186
234
  projectName: p.get('projectName'),
187
235
  session: p.get('session'),
188
- parentView: p.get('parentView') || 'projects',
189
236
  };
190
237
  }
191
238
 
239
+ const DEFAULT_RANGE_PRESET = '3';
240
+
241
+ function presetRange(value) {
242
+ return { kind: 'preset', value: String(value) };
243
+ }
244
+
245
+ function presetDef(value) {
246
+ return RANGE_PRESETS.find((p) => p.value === String(value));
247
+ }
248
+
249
+ function isPresetValue(v) {
250
+ return !!presetDef(v);
251
+ }
252
+
253
+ function isCustomRange(r) {
254
+ return r?.kind === 'custom';
255
+ }
256
+
257
+ // '1 DAY' is gone: under calendar semantics it would have duplicated TODAY, so the rolling day it
258
+ // used to mean is now '24h'. Without this, a stored "1" stops being a preset value and silently
259
+ // lands on the default instead of on the shortcut that kept its meaning.
260
+ function migrateStoredPreset(value) {
261
+ const s = String(value);
262
+ return s === '1' ? '24h' : s;
263
+ }
264
+
265
+ // Reads the JSON tagged union and the legacy bare "3" / "today" scalar that predates it: the key is
266
+ // a preference, so clearLocalCache() never evicts it and old values outlive any cache clear.
267
+ // Anything unrecognized returns null, which lands on the default preset.
268
+ function parseStoredRange(raw) {
269
+ if (!raw) return null;
270
+ let v;
271
+ try {
272
+ v = JSON.parse(raw);
273
+ } catch {
274
+ v = raw; // the legacy bare 'today' is not valid JSON
275
+ }
276
+ if (v?.kind === 'custom') {
277
+ return ISO_DATE_RE.test(v.from) && ISO_DATE_RE.test(v.to) && v.from <= v.to
278
+ ? { kind: 'custom', from: v.from, to: v.to }
279
+ : null;
280
+ }
281
+ const s = migrateStoredPreset(v?.kind === 'preset' ? v.value : v);
282
+ return isPresetValue(s) ? presetRange(s) : null;
283
+ }
284
+
192
285
  function loadDateRange() {
193
- const v = localStorage.getItem('cc-cost:range');
194
- if (!v) return 3;
195
- if (v === 'today') return 'today';
196
- return parseInt(v, 10) || 3;
286
+ return parseStoredRange(localStorage.getItem('cc-cost:range')) || presetRange(DEFAULT_RANGE_PRESET);
197
287
  }
198
288
 
199
289
  function saveDateRange(val) {
200
- localStorage.setItem('cc-cost:range', String(val));
290
+ localStorage.setItem('cc-cost:range', JSON.stringify(val));
201
291
  }
202
292
 
203
293
  function loadScope() {
@@ -222,12 +312,79 @@ function saveScope() {
222
312
  }
223
313
  }
224
314
 
225
- function rangeLabel(r) {
226
- return r === 'today' ? 'today' : `${r} days`;
227
- }
315
+ // The range reaches these labels either as the client's tagged union or as the shape the server
316
+ // echoes back on the session detail payload: 'today', N days, null for all time, or a bare
317
+ // { from, to } window.
318
+ function normalizeRange(r) {
319
+ if (r == null) return null;
320
+ if (typeof r === 'object') {
321
+ if (r.kind === 'preset' && isPresetValue(r.value)) return presetRange(r.value);
322
+ if (r.from && r.to) return { kind: 'custom', from: r.from, to: r.to };
323
+ return null;
324
+ }
325
+ if (isPresetValue(r)) return presetRange(r);
326
+ // A legacy `range=1` from a bookmarked URL: the server reads it as one calendar day, which is
327
+ // today. Without this it is a positive integer that names no preset, so it would label as
328
+ // "all time" — the shape normalizeRange returns for something it does not recognize.
329
+ if (String(r) === '1') return presetRange('today');
330
+ const n = Number(r);
331
+ return Number.isFinite(n) && n > 0 ? presetRange(n) : null;
332
+ }
333
+
334
+ // "AUG 1 - AUG 12"; a single-day window is just "AUG 12".
335
+ function rangeSpanLabel(r) {
336
+ return r.from === r.to ? isoDayLabel(r.to) : `${isoDayLabel(r.from)} - ${isoDayLabel(r.to)}`;
337
+ }
338
+
339
+ // Every label variant is the same four-way classification of the range — all time, a custom window,
340
+ // today, a rolling preset — with one phrase per class, so only the phrasing lives in the callers:
341
+ // presets keep their rolling phrasing ("last 7 days"), while a custom window is named by its dates,
342
+ // where a "last" prefix would be nonsense. The rolling preset measured in hours must never be
343
+ // pluralized as days, and the empty-state article only fits the rolling presets.
344
+ function rangeText(r, prefix = {}) {
345
+ const n = normalizeRange(r);
346
+ const kind = !n ? 'all' : n.kind === 'custom' ? 'custom' : n.value === 'today' ? 'today' : 'rolling';
347
+ const base =
348
+ kind === 'all'
349
+ ? 'all time'
350
+ : kind === 'custom'
351
+ ? rangeSpanLabel(n)
352
+ : kind === 'today'
353
+ ? 'today'
354
+ : n.value === '24h'
355
+ ? '24 hours'
356
+ : `${n.value} days`;
357
+ return (prefix[kind] || '') + base;
358
+ }
359
+
360
+ const rangeLabel = (r) => rangeText(r);
361
+ const rangeScopeLabel = (r) => rangeText(r, { rolling: 'last ' });
362
+ const rangeInLabel = (r) => rangeText(r, { all: 'in ', custom: 'in ', rolling: 'in the last ' });
363
+
364
+ // Uppercase, for the picker trigger: the preset's own name, or the window's dates.
365
+ const rangeTriggerLabel = (r) => {
366
+ const n = normalizeRange(r) || presetRange(DEFAULT_RANGE_PRESET);
367
+ if (n.kind === 'custom') return rangeSpanLabel(n);
368
+ const def = presetDef(n.value);
369
+ return (def ? def.label : rangeText(n)).toUpperCase();
370
+ };
228
371
 
229
- function rangeScopeLabel(r) {
230
- return r === 'today' ? rangeLabel(r) : `last ${rangeLabel(r)}`;
372
+ // The overview's window card: "3 Days" for an N-day preset, the preset's own name for a clock preset
373
+ // ("Last 24h"), the date span for a custom window. '1 Year' is the one name that does not fit the
374
+ // card, hence cardLabel.
375
+ const rangeCardLabel = (r) => {
376
+ const n = normalizeRange(r);
377
+ if (!n) return 'All Time';
378
+ if (n.kind === 'custom') return rangeSpanLabel(n);
379
+ const def = presetDef(n.value);
380
+ return def ? def.cardLabel || def.label : `${n.value} Days`;
381
+ };
382
+
383
+ // That card duplicates the Today card when the window is exactly today, so it is dropped instead.
384
+ function isTodayOnlyRange(r) {
385
+ const n = normalizeRange(r);
386
+ if (!n) return false;
387
+ return n.kind === 'custom' ? n.from === n.to && n.to === todayIso() : n.value === 'today';
231
388
  }
232
389
 
233
390
  function loadSort() {
@@ -256,7 +413,6 @@ function updateUrl() {
256
413
  if (currentProjectPath) p.set('project', currentProjectPath);
257
414
  if (currentProjectName) p.set('projectName', currentProjectName);
258
415
  if (currentSessionId) p.set('session', currentSessionId);
259
- if (parentView !== 'projects') p.set('parentView', parentView);
260
416
  const qs = p.toString();
261
417
  history.replaceState(null, '', qs ? `?${qs}` : '/');
262
418
  sessionStorage.setItem('cc-cost:nav', qs);
@@ -267,7 +423,7 @@ function updateUrl() {
267
423
  // #region FETCH
268
424
 
269
425
  const BROWSER_CACHE_TTL = 5 * 60 * 1000; // 5 min
270
- const CACHE_VERSION = 4;
426
+ const CACHE_VERSION = 6;
271
427
  let forceRefresh = false;
272
428
  // Age of the data on screen, for the auto-refresh staleness check. A cache hit carries its own
273
429
  // timestamp forward, so a reload with a warm cache doesn't look freshly fetched.
@@ -348,8 +504,18 @@ function scopeParam() {
348
504
  return scopeProject ? `&project=${encodeURIComponent(scopeProject)}` : '';
349
505
  }
350
506
 
507
+ // Presets stay on the rolling `range` param, recomputed server-side; a custom window sends its two
508
+ // local dates, which take precedence over `range`. Every range-consuming fetch goes through this.
509
+ function rangeParams(r = dateRange) {
510
+ return isCustomRange(r) ? `from=${r.from}&to=${r.to}` : `range=${encodeURIComponent(r.value)}`;
511
+ }
512
+
351
513
  async function fetchOverview() {
352
- overviewData = await fetchJSON(`/api/overview?range=${dateRange}${scopeParam()}`);
514
+ overviewData = await fetchJSON(`/api/overview?${rangeParams()}${scopeParam()}`);
515
+ }
516
+
517
+ async function fetchInsights() {
518
+ insightsData = await fetchJSON(`/api/insights?${rangeParams()}${scopeParam()}`);
353
519
  }
354
520
 
355
521
  // Fire-and-forget label upgrade: /api/projects/:path/sessions carries no project name, so ask
@@ -357,7 +523,7 @@ async function fetchOverview() {
357
523
  async function resolveScopeName() {
358
524
  const target = scopeProject;
359
525
  try {
360
- const rows = await fetchJSON(`/api/projects?range=${dateRange}${scopeParam()}`);
526
+ const rows = await fetchJSON(`/api/projects?${rangeParams()}${scopeParam()}`);
361
527
  const name = rows?.[0]?.encodedPath === target ? rows[0].name : null;
362
528
  if (!name || scopeProject !== target) return;
363
529
  scopeProjectName = name;
@@ -373,19 +539,15 @@ async function resolveScopeName() {
373
539
  }
374
540
  }
375
541
 
376
- async function fetchProjects() {
377
- projectsData = await fetchJSON(`/api/projects?range=${dateRange}${scopeParam()}`);
378
- }
379
-
380
542
  async function fetchSessions(encodedPath) {
381
- const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?range=${dateRange}`, true);
543
+ const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?${rangeParams()}`, true);
382
544
  sessionsData = data.sessions;
383
545
  sessionsCostSeries = data.costSeries;
384
546
  sessionsModelDistribution = data.modelDistribution || [];
385
547
  }
386
548
 
387
549
  async function fetchSessionDetail(sessionId) {
388
- sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}?range=${dateRange}`, true);
550
+ sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}?${rangeParams()}`, true);
389
551
  // Populate project context when opening via deep link (no project in URL)
390
552
  if (sessionDetailData && !currentProjectPath) {
391
553
  currentProjectPath = sessionDetailData.encodedProjectPath;
@@ -418,10 +580,11 @@ function renderOverview() {
418
580
  // Return before any chart call so no canvas is touched — there are none in this markup.
419
581
  if (scopeProject && s.totalSessions === 0) {
420
582
  el.innerHTML = `<div class="dashboard-content">
583
+ ${viewTabs('overview')}
421
584
  ${scopeIndicator()}
422
585
  <div class="empty-state">
423
586
  <div class="empty-icon">$</div>
424
- <div>No usage for ${esc(scopeProjectName || scopeProject)} in the last ${rangeLabel(dateRange)}</div>
587
+ <div>No usage for ${esc(scopeProjectName || scopeProject)} ${esc(rangeInLabel(dateRange))}</div>
425
588
  <div>Clear the project scope to see everything.</div>
426
589
  </div>
427
590
  </div>`;
@@ -430,18 +593,26 @@ function renderOverview() {
430
593
 
431
594
  el.innerHTML = `
432
595
  <div class="dashboard-content">
596
+ ${viewTabs('overview')}
433
597
  ${scopeIndicator()}
434
598
  <div class="cards-row">
599
+ ${
600
+ // Null rather than 0 when the window ends before today: a zero here would read as
601
+ // "nothing spent today" instead of "today is outside the selected window".
602
+ s.todayCost == null
603
+ ? ''
604
+ : `
435
605
  <div class="stat-card">
436
606
  <div class="card-label">Today</div>
437
607
  <div class="card-value cost">${formatCost(s.todayCost)}</div>
438
- </div>
608
+ </div>`
609
+ }
439
610
  ${
440
- dateRange === 'today'
611
+ isTodayOnlyRange(dateRange)
441
612
  ? ''
442
613
  : `
443
614
  <div class="stat-card">
444
- <div class="card-label">${dateRange} Days</div>
615
+ <div class="card-label">${esc(rangeCardLabel(dateRange))}</div>
445
616
  <div class="card-value cost">${formatCost(s.totalCost)}</div>
446
617
  </div>`
447
618
  }
@@ -482,6 +653,7 @@ function renderOverview() {
482
653
  <th class="${thClass('totalCost')}" onclick="sortBy('totalCost')">Cost ${sortArrow('totalCost')}</th>
483
654
  <th class="${thClass('sessionCount')}" onclick="sortBy('sessionCount')">Sessions ${sortArrow('sessionCount')}</th>
484
655
  <th class="${thClass('lastActive')}" onclick="sortBy('lastActive')">Last Active ${sortArrow('lastActive')}</th>
656
+ <th>Model</th>
485
657
  </tr></thead>
486
658
  <tbody>
487
659
  ${[...overviewData.projects]
@@ -493,6 +665,7 @@ function renderOverview() {
493
665
  <td class="cost-cell">${formatCost(p.totalCost)}</td>
494
666
  <td>${p.sessionCount}</td>
495
667
  <td class="muted">${timeAgo(p.lastActive)}</td>
668
+ <td><span class="model-badge">${esc(shortModel(p.primaryModel))}</span></td>
496
669
  </tr>`,
497
670
  )
498
671
  .join('')}
@@ -504,72 +677,234 @@ function renderOverview() {
504
677
 
505
678
  // Render charts after DOM is ready
506
679
  requestAnimationFrame(() => {
507
- renderCostChart(costSeries);
680
+ renderCostChart(costSeries, 'costChart', 'cost', models);
508
681
  renderModelChart(models);
509
682
  });
510
683
  }
511
684
 
512
685
  // #endregion
513
686
 
514
- // #region RENDER_PROJECTS
687
+ // #region RENDER_INSIGHTS
688
+
689
+ const HEATMAP_DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
690
+
691
+ // "YYYY-MM-DD" → "Sat 22"; parsed as local parts to avoid the UTC shift of Date("YYYY-MM-DD").
692
+ function heatmapDayLabel(dateStr) {
693
+ const [y, m, d] = isoParts(dateStr);
694
+ return `${HEATMAP_DAYS[new Date(y, m - 1, d).getDay()]} ${d}`;
695
+ }
696
+
697
+ // Columns start at 6 AM so the typical workday sits left-of-center instead of the dead
698
+ // early-morning hours.
699
+ const HEATMAP_START_HOUR = 6;
700
+
701
+ function ampm(h) {
702
+ if (h === 0) return '12am';
703
+ if (h === 12) return '12pm';
704
+ return h < 12 ? `${h}am` : `${h - 12}pm`;
705
+ }
706
+
707
+ function buildHeatmap(hm, days, today) {
708
+ const max = hm.reduce((m, row) => Math.max(m, ...row), 0);
709
+ if (max === 0) return '<div class="empty-state"><div>No activity in this range</div></div>';
710
+ const hourAt = (col) => (col + HEATMAP_START_HOUR) % 24;
711
+ const hours = Array.from(
712
+ { length: 24 },
713
+ (_, col) => `<span class="hm-hour">${hourAt(col) % 3 === 0 ? ampm(hourAt(col)) : ''}</span>`,
714
+ ).join('');
715
+ const rows = hm
716
+ .map((row, d) => {
717
+ const label = heatmapDayLabel(days[d]);
718
+ return `
719
+ <div class="hm-row${days[d] === today ? ' hm-today' : ''}">
720
+ <span class="hm-day">${label}</span>
721
+ ${Array.from({ length: 24 }, (_, col) => {
722
+ const h = hourAt(col);
723
+ const cost = row[h];
724
+ return `
725
+ <span class="hm-cell" data-hm="${label}|${h}|${cost}">
726
+ <i style="opacity:${cost > 0 ? Math.max(0.12, cost / max).toFixed(2) : 0}"></i>
727
+ </span>`;
728
+ }).join('')}
729
+ </div>`;
730
+ })
731
+ .join('');
732
+ return `<div class="heatmap">${rows}<div class="hm-row"><span class="hm-day"></span>${hours}</div></div>`;
733
+ }
734
+
735
+ // Shared floating tooltip for heatmap cells — the native title attr is too slow and unstyled.
736
+ let hmTipEl = null;
737
+ function initHeatmapTooltip() {
738
+ if (hmTipEl) return;
739
+ hmTipEl = document.createElement('div');
740
+ hmTipEl.className = 'hm-tip';
741
+ document.body.appendChild(hmTipEl);
742
+ document.addEventListener('mouseover', (e) => {
743
+ const cell = e.target.closest('.hm-cell[data-hm]');
744
+ if (!cell) {
745
+ hmTipEl.classList.remove('on');
746
+ return;
747
+ }
748
+ const [day, h, cost] = cell.dataset.hm.split('|');
749
+ hmTipEl.innerHTML = `<b>${formatCost(+cost)}</b><span>${day} ${ampm(+h)}&ndash;${ampm((+h + 1) % 24)}</span>`;
750
+ hmTipEl.classList.add('on');
751
+ const r = cell.getBoundingClientRect();
752
+ const tr = hmTipEl.getBoundingClientRect();
753
+ const left = Math.max(8, Math.min(r.left + r.width / 2 - tr.width / 2, window.innerWidth - tr.width - 8));
754
+ const top = r.top - tr.height - 6;
755
+ hmTipEl.style.left = `${left}px`;
756
+ hmTipEl.style.top = `${top < 4 ? r.bottom + 6 : top}px`;
757
+ });
758
+ }
759
+
760
+ // Hour-only span (e.g. "15:00–20:00") so the card makes it obvious a fresh block just opened.
761
+ function blockHours(b) {
762
+ const t = (iso) => new Date(iso).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
763
+ return `${t(b.start)}&ndash;${t(b.end)}`;
764
+ }
765
+
766
+ function blockSpanLabel(b) {
767
+ const opts = { month: 'short', day: 'numeric', hour: 'numeric' };
768
+ return `${new Date(b.start).toLocaleString(undefined, opts)} – ${new Date(b.end).toLocaleTimeString(undefined, { hour: 'numeric' })}`;
769
+ }
515
770
 
516
- function renderProjects() {
517
- const el = document.getElementById('projects-view');
771
+ // Classifies the active block's projection: against the live usage limit when the statusline
772
+ // snapshot gave us used %, else against this range's completed blocks (median/P90 of cost).
773
+ // Returns null when there is no active block or nothing to compare against.
774
+ function burnPace(ab, blocks) {
775
+ if (!ab?.burn) return null;
776
+ const blockMin = (new Date(ab.end) - new Date(ab.start)) / 60000;
777
+ const elapsedMin = Math.max(1, blockMin - ab.burn.remainingMin);
778
+ if (ab.usedPct != null) {
779
+ const projPct = (ab.usedPct / elapsedMin) * blockMin;
780
+ const cls = projPct >= 100 ? 'hot' : projPct >= 80 ? 'warn' : 'ok';
781
+ return { cls, note: `on pace for ${Math.round(Math.min(projPct, 999))}% of limit` };
782
+ }
783
+ const past = blocks
784
+ .filter((b) => !b.active && b.cost > 0)
785
+ .map((b) => b.cost)
786
+ .sort((a, b) => a - b);
787
+ if (past.length < 3) return null;
788
+ const median = past[Math.floor(past.length / 2)];
789
+ const p90 = past[Math.min(past.length - 1, Math.floor(past.length * 0.9))];
790
+ const cls = ab.burn.projectedCost > p90 ? 'hot' : ab.burn.projectedCost > median ? 'warn' : 'ok';
791
+ return { cls, note: `vs. ${formatCost(median)} median block` };
792
+ }
793
+
794
+ function renderInsights() {
795
+ const el = document.getElementById('insights-view');
518
796
  if (!el) return;
519
- if (!projectsData) {
797
+ if (!insightsData) {
520
798
  el.innerHTML = '<div class="loading-state"><div class="loading-spinner"></div><span>Loading...</span></div>';
521
799
  return;
522
800
  }
523
801
 
524
- const h = JSON.stringify({ projectsData, sort: viewSort.projects, scopeProject, scopeProjectName });
525
- if (lastRenderHash.projects === h) return;
526
- lastRenderHash.projects = h;
527
-
528
- const sorted = [...projectsData].sort((a, b) => sortCompare(a, b, viewSort.projects.field, viewSort.projects.order));
802
+ const d = insightsData;
803
+ const h = JSON.stringify({ insightsData, scopeProject, scopeProjectName });
804
+ if (lastRenderHash.insights === h) return;
805
+ lastRenderHash.insights = h;
529
806
 
530
- if (sorted.length === 0) {
531
- el.innerHTML = `<div class="dashboard-content">
532
- ${scopeIndicator()}
533
- <div class="empty-state">
534
- <div class="empty-icon">$</div>
535
- ${
536
- scopeProject
537
- ? `<div>No usage for ${esc(scopeProjectName || scopeProject)} in the last ${rangeLabel(dateRange)}</div>
538
- <div>Clear the project scope to see everything.</div>`
539
- : `<div>No project data found</div>
540
- <div>Make sure Claude Code session files exist in ~/.claude/projects/</div>`
541
- }
542
- </div></div>`;
543
- return;
544
- }
807
+ const ab = d.blocks.find((b) => b.active) || null;
808
+ const pace = burnPace(ab, d.blocks);
809
+ const sub = d.subagents;
810
+ const agentTotal = sub.mainCost + sub.subagentCost;
811
+ const subPct = formatPct(sub.subagentCost, agentTotal);
812
+ const showWeekly = d.weekly.length >= 3;
545
813
 
546
814
  el.innerHTML = `
547
815
  <div class="dashboard-content">
548
- ${scopeProject ? scopeIndicator() : '<div class="section-title">All Projects</div>'}
816
+ ${viewTabs('insights')}
817
+ ${scopeIndicator()}
818
+ <div class="cards-row">
819
+ <div class="stat-card">
820
+ <div class="card-label">Active 5h Block</div>
821
+ <div class="card-value cost">${ab ? formatCost(ab.cost) : '—'}</div>
822
+ <div class="card-sub">${ab ? `${blockHours(ab)} &middot; ${formatDuration(ab.burn.remainingMin)} left${ab.usedPct != null ? ` &middot; ${ab.usedPct}% used` : ''}` : 'no live window data'}</div>
823
+ </div>
824
+ <div class="stat-card">
825
+ <div class="card-label">Burn Rate</div>
826
+ <div class="card-value${pace ? ` pace-${esc(pace.cls)}` : ''}">${ab ? `${formatCost(ab.burn.costPerHour)}/h` : '—'}</div>
827
+ <div class="card-sub">${ab ? `${formatTokens(Math.round(ab.burn.tokensPerMin))} tok/min &middot; proj. ${formatCost(ab.burn.projectedCost)} by block end${pace ? ` &middot; ${pace.note}` : ''}` : 'no active block'}</div>
828
+ </div>
829
+ <div class="stat-card">
830
+ <div class="card-label">Monthly Run-Rate</div>
831
+ <div class="card-value cost">${formatCost(d.runRate.projectedMonthly)}</div>
832
+ <div class="card-sub">${formatCost(d.runRate.dailyAvg)}/day over ${d.runRate.days} ${d.runRate.days === 1 ? 'day' : 'days'}</div>
833
+ </div>
834
+ <div class="stat-card">
835
+ <div class="card-label">Cache Savings</div>
836
+ <div class="card-value cost">${formatCost(d.cacheSavings)}</div>
837
+ <div class="card-sub">vs. uncached input &middot; ${formatTokens(d.tokens.cacheRead)} reads</div>
838
+ </div>
839
+ <div class="stat-card">
840
+ <div class="card-label">Subagent Share</div>
841
+ <div class="card-value">${subPct}%</div>
842
+ <div class="card-sub">${formatCost(sub.subagentCost)} of ${formatCost(agentTotal)}</div>
843
+ </div>
844
+ </div>
845
+
846
+ <div class="charts-row">
847
+ <div class="chart-box">
848
+ <div class="chart-title">Token Composition <span class="chart-title-note">log scale</span></div>
849
+ <canvas id="tokenSplitChart"></canvas>
850
+ </div>
851
+ <div class="chart-box">
852
+ <div class="chart-title">Top Tools</div>
853
+ ${d.tools.length ? '<canvas id="toolsChart"></canvas>' : '<div class="card-sub">No tool calls in this range</div>'}
854
+ </div>
855
+ </div>
856
+
857
+ <div class="charts-row" style="grid-template-columns:${showWeekly ? '3fr 2fr' : '1fr'}">
858
+ <div class="chart-box">
859
+ <div class="chart-title">Activity Heatmap (cost by hour) <span class="chart-title-note">${isoDayLabel(d.heatmapDays[0])} &rarr; ${isoDayLabel(d.heatmapDays[d.heatmapDays.length - 1])}</span></div>
860
+ ${buildHeatmap(d.heatmap, d.heatmapDays, d.heatmapToday)}
861
+ </div>
862
+ ${
863
+ showWeekly
864
+ ? `
865
+ <div class="chart-box">
866
+ <div class="chart-title">Weekly Cost</div>
867
+ <canvas id="weeklyChart"></canvas>
868
+ </div>`
869
+ : ''
870
+ }
871
+ </div>
872
+
873
+ ${
874
+ d.blocks.length
875
+ ? `
876
+ <div class="section-title">5-Hour Billing Blocks</div>
549
877
  <table class="data-table">
550
878
  <thead><tr>
551
- <th class="${thClass('name')}" onclick="sortBy('name')">Project ${sortArrow('name')}</th>
552
- <th class="${thClass('totalCost')}" onclick="sortBy('totalCost')">Cost ${sortArrow('totalCost')}</th>
553
- <th class="${thClass('sessionCount')}" onclick="sortBy('sessionCount')">Sessions ${sortArrow('sessionCount')}</th>
554
- <th class="${thClass('lastActive')}" onclick="sortBy('lastActive')">Last Active ${sortArrow('lastActive')}</th>
555
- <th>Model</th>
879
+ <th>Block</th><th>Status</th><th>Messages</th><th>Tokens</th><th>Cost</th><th>Models</th>
556
880
  </tr></thead>
557
881
  <tbody>
558
- ${sorted
882
+ ${d.blocks
559
883
  .map(
560
- (p) => `
561
- <tr data-clickable onclick="navigateToSessions('${escAttrJs(p.encodedPath)}', '${escAttrJs(p.name)}')">
562
- <td>${esc(p.name)}</td>
563
- <td class="cost-cell">${formatCost(p.totalCost)}</td>
564
- <td>${p.sessionCount}</td>
565
- <td class="muted">${timeAgo(p.lastActive)}</td>
566
- <td><span class="model-badge">${esc(shortModel(p.primaryModel))}</span></td>
884
+ (b) => `
885
+ <tr>
886
+ <td>${blockSpanLabel(b)}</td>
887
+ <td>${b.active ? `<span class="block-badge active">ACTIVE &middot; ${formatDuration(b.burn.remainingMin)} left</span>` : `<span class="block-badge">ended ${timeAgo(b.lastActivity)}</span>`}</td>
888
+ <td>${b.messageCount}</td>
889
+ <td>${formatTokens(b.tokens)}</td>
890
+ <td class="cost-cell">${formatCost(b.cost)}</td>
891
+ <td>${b.models.map((m) => `<span class="model-badge">${esc(shortModel(m))}</span>`).join(' ')}</td>
567
892
  </tr>`,
568
893
  )
569
894
  .join('')}
570
895
  </tbody>
571
- </table>
896
+ </table>`
897
+ : ''
898
+ }
899
+
572
900
  </div>`;
901
+
902
+ initHeatmapTooltip();
903
+ requestAnimationFrame(() => {
904
+ renderTokenSplitChart(d.tokens);
905
+ if (d.tools.length) renderToolsChart(d.tools);
906
+ if (showWeekly) renderWeeklyChart(d.weekly);
907
+ });
573
908
  }
574
909
 
575
910
  // #endregion
@@ -591,7 +926,7 @@ function renderSessions() {
591
926
  if (sessionsData.length === 0) {
592
927
  el.innerHTML = `<div class="dashboard-content">
593
928
  <div class="breadcrumb">
594
- ${parentBreadcrumb()}
929
+ ${PARENT_BREADCRUMB}
595
930
  <span class="sep">/</span>
596
931
  <span class="current">${esc(currentProjectName || 'Project')}</span>
597
932
  </div>
@@ -603,7 +938,7 @@ function renderSessions() {
603
938
  el.innerHTML = `
604
939
  <div class="dashboard-content">
605
940
  <div class="breadcrumb">
606
- ${parentBreadcrumb()}
941
+ ${PARENT_BREADCRUMB}
607
942
  <span class="sep">/</span>
608
943
  <span class="current">${esc(currentProjectName || 'Project')}</span>
609
944
  </div>
@@ -654,7 +989,7 @@ function renderSessions() {
654
989
  </div>`;
655
990
 
656
991
  requestAnimationFrame(() => {
657
- renderCostChart(sessionsCostSeries, 'sessionsCostChart', 'sessionsCost');
992
+ renderCostChart(sessionsCostSeries, 'sessionsCostChart', 'sessionsCost', sessionsModelDistribution || []);
658
993
  renderModelChart(sessionsModelDistribution || [], 'sessionsModelChart', 'sessionsModel');
659
994
  });
660
995
  }
@@ -679,7 +1014,7 @@ function renderDetail() {
679
1014
  el.innerHTML = `
680
1015
  <div class="dashboard-content">
681
1016
  <div class="breadcrumb">
682
- ${parentBreadcrumb()}
1017
+ ${PARENT_BREADCRUMB}
683
1018
  <span class="sep">/</span>
684
1019
  <a onclick="navigateToSessions('${escAttrJs(d.encodedProjectPath)}', '${escAttrJs(d.projectPath)}')">${esc(d.projectPath)}</a>
685
1020
  <span class="sep">/</span>
@@ -822,6 +1157,11 @@ function getChartColors() {
822
1157
  };
823
1158
  }
824
1159
 
1160
+ // Single source of the series palette so per-model colors match across charts.
1161
+ function chartPalette(c) {
1162
+ return [c.chart1, c.chart2, c.chart3, c.chart4, c.chart5, c.chart6];
1163
+ }
1164
+
825
1165
  // Translucent fill from a hex color so chart bars read as a quiet wash, not a solid block.
826
1166
  function hexToRgba(hex, alpha) {
827
1167
  const h = hex.replace('#', '');
@@ -859,6 +1199,63 @@ function chartDefaults() {
859
1199
  };
860
1200
  }
861
1201
 
1202
+ // Chart.js log axes tick (and draw a gridline) at every 2..9 within a decade, which reads as
1203
+ // visual noise — keep labels and gridlines at powers of 10 only. Epsilon because Math.log10
1204
+ // of exact powers is not guaranteed to be integral.
1205
+ function isDecade(v) {
1206
+ const l = Math.log10(v);
1207
+ return Math.abs(l - Math.round(l)) < 1e-9;
1208
+ }
1209
+
1210
+ // maxValue caps the axis at the largest bar and labels it, so the longest bar ends at a
1211
+ // readable number instead of running past the last decade tick.
1212
+ function logAxis(xDefaults, maxValue) {
1213
+ const labeled = (v) => isDecade(v) || v === maxValue;
1214
+ return {
1215
+ ...xDefaults,
1216
+ type: 'logarithmic',
1217
+ min: 1,
1218
+ ...(maxValue > 1 ? { max: maxValue } : {}),
1219
+ // Chart.js doesn't always emit a tick at the axis max — force one so the longest bar ends
1220
+ // at its real value, and drop a decade tick sitting close enough to collide with its label.
1221
+ afterBuildTicks: (scale) => {
1222
+ if (maxValue <= 1) return;
1223
+ scale.ticks = scale.ticks.filter(
1224
+ (t) => t.value !== maxValue && !(isDecade(t.value) && Math.abs(Math.log10(maxValue / t.value)) < 0.25),
1225
+ );
1226
+ scale.ticks.push({ value: maxValue });
1227
+ },
1228
+ grid: {
1229
+ ...xDefaults.grid,
1230
+ color: (ctx) => (ctx.tick && labeled(ctx.tick.value) ? xDefaults.grid.color : 'transparent'),
1231
+ },
1232
+ ticks: {
1233
+ ...xDefaults.ticks,
1234
+ // autoSkip would drop the forced max tick before it ever renders.
1235
+ autoSkip: false,
1236
+ callback: (v) => (labeled(v) ? formatTokens(v) : ''),
1237
+ },
1238
+ };
1239
+ }
1240
+
1241
+ function barDataset(data, color) {
1242
+ return {
1243
+ data,
1244
+ backgroundColor: Array.isArray(color) ? color.map((x) => hexToRgba(x, 0.5)) : hexToRgba(color, 0.5),
1245
+ borderColor: color,
1246
+ borderWidth: 1.5,
1247
+ borderRadius: 3,
1248
+ };
1249
+ }
1250
+
1251
+ function withTooltip(defaults, callbacks) {
1252
+ return { ...defaults.plugins, tooltip: { ...defaults.plugins.tooltip, callbacks } };
1253
+ }
1254
+
1255
+ // Exact dollars for cost axes and their tooltips — formatCost's thresholds are for cards, where
1256
+ // "<$0.01" reads better than a chart tick that has to line up with its neighbours.
1257
+ const usd = (v) => `$${v.toFixed(2)}`;
1258
+
862
1259
  function destroyChart(id) {
863
1260
  if (charts[id]) {
864
1261
  charts[id].destroy();
@@ -866,7 +1263,7 @@ function destroyChart(id) {
866
1263
  }
867
1264
  }
868
1265
 
869
- function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost') {
1266
+ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost', distribution = []) {
870
1267
  const points = series?.points;
871
1268
  const canvas = document.getElementById(canvasId);
872
1269
  if (!canvas || !points?.length) return;
@@ -875,37 +1272,53 @@ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost') {
875
1272
  const c = getChartColors();
876
1273
  const defaults = chartDefaults();
877
1274
 
1275
+ // Stack order follows modelDistribution so segment colors line up with the Cost by Model
1276
+ // chart rendered next to it. 'other' (synthetic models) is absent from the distribution
1277
+ // and lands at the end.
1278
+ const present = new Set();
1279
+ for (const p of points) {
1280
+ for (const m in p.byModel) if (p.byModel[m] > 0) present.add(m);
1281
+ }
1282
+ const models = distribution.filter((d) => present.has(d.model)).map((d) => d.model);
1283
+ for (const m of present) if (!models.includes(m)) models.push(m);
1284
+ const palette = chartPalette(c);
1285
+
1286
+ const datasets = models.map((m, i) => ({
1287
+ label: shortModel(m),
1288
+ data: points.map((p) => p.byModel?.[m] || 0),
1289
+ backgroundColor: hexToRgba(palette[i % palette.length], 0.5),
1290
+ borderColor: palette[i % palette.length],
1291
+ borderWidth: 1.5,
1292
+ borderRadius: 2,
1293
+ stack: 'cost',
1294
+ }));
1295
+
878
1296
  charts[chartKey] = new Chart(canvas, {
879
1297
  type: 'bar',
880
1298
  data: {
881
1299
  labels: points.map((p) => bucketLabel(p.key, series.bucket)),
882
- datasets: [
883
- {
884
- label: costSeriesTitle(series),
885
- data: points.map((p) => p.cost),
886
- backgroundColor: c.chartFill,
887
- borderColor: c.accent,
888
- borderWidth: 1.5,
889
- borderRadius: 3,
890
- },
891
- ],
1300
+ datasets,
892
1301
  },
893
1302
  options: {
894
1303
  ...defaults,
895
1304
  interaction: { mode: 'nearest', intersect: true },
896
1305
  events: [],
897
1306
  plugins: {
898
- ...defaults.plugins,
899
- tooltip: {
900
- ...defaults.plugins.tooltip,
901
- callbacks: { label: (ctx) => `$${ctx.parsed.y.toFixed(2)}` },
1307
+ ...withTooltip(defaults, { label: (ctx) => usd(ctx.parsed.y) }),
1308
+ // events: [] disables tooltips, so the legend is the only place segment names show.
1309
+ legend: {
1310
+ display: models.length > 1,
1311
+ position: 'bottom',
1312
+ labels: { color: c.text, font: { size: 9 }, boxWidth: 8, boxHeight: 8 },
902
1313
  },
903
1314
  },
904
1315
  scales: {
905
1316
  ...defaults.scales,
1317
+ x: { ...defaults.scales.x, stacked: true },
906
1318
  y: {
907
1319
  ...defaults.scales.y,
908
- ticks: { ...defaults.scales.y.ticks, callback: (v) => `$${v.toFixed(2)}` },
1320
+ stacked: true,
1321
+ ticks: { ...defaults.scales.y.ticks, callback: usd },
909
1322
  },
910
1323
  },
911
1324
  },
@@ -918,7 +1331,7 @@ function renderModelChart(models, canvasId = 'modelChart', chartKey = 'model') {
918
1331
  destroyChart(chartKey);
919
1332
 
920
1333
  const colors = getChartColors();
921
- const palette = [colors.chart1, colors.chart2, colors.chart3, colors.chart4, colors.chart5, colors.chart6];
1334
+ const palette = chartPalette(colors);
922
1335
  const defaults = chartDefaults();
923
1336
  const total = models.reduce((s, m) => s + m.cost, 0);
924
1337
 
@@ -941,19 +1354,9 @@ function renderModelChart(models, canvasId = 'modelChart', chartKey = 'model') {
941
1354
  indexAxis: 'y',
942
1355
  interaction: { mode: 'nearest', intersect: true },
943
1356
  events: [],
944
- plugins: {
945
- ...defaults.plugins,
946
- tooltip: {
947
- ...defaults.plugins.tooltip,
948
- callbacks: {
949
- label: (ctx) => {
950
- const val = ctx.parsed.x;
951
- const pct = ((val / total) * 100).toFixed(1);
952
- return `$${val.toFixed(2)} (${pct}%)`;
953
- },
954
- },
955
- },
956
- },
1357
+ plugins: withTooltip(defaults, {
1358
+ label: (ctx) => `${usd(ctx.parsed.x)} (${formatPct(ctx.parsed.x, total)}%)`,
1359
+ }),
957
1360
  scales: {
958
1361
  ...defaults.scales,
959
1362
  x: { ...defaults.scales.x, ticks: { ...defaults.scales.x.ticks, callback: (v) => `$${v}` } },
@@ -1063,6 +1466,121 @@ function renderTokenBreakdownChart(messages) {
1063
1466
  });
1064
1467
  }
1065
1468
 
1469
+ function renderTokenSplitChart(t) {
1470
+ const canvas = document.getElementById('tokenSplitChart');
1471
+ if (!canvas) return;
1472
+ destroyChart('tokenSplit');
1473
+
1474
+ const c = getChartColors();
1475
+ const defaults = chartDefaults();
1476
+ const rows = [
1477
+ ['Input', t.input, c.chart1],
1478
+ ['Output', t.output, c.chart2],
1479
+ ['Cache Write', t.cacheCreation, c.chart3],
1480
+ ['Cache Read', t.cacheRead, c.chart4],
1481
+ ];
1482
+ const total = rows.reduce((s, r) => s + r[1], 0);
1483
+
1484
+ charts.tokenSplit = new Chart(canvas, {
1485
+ type: 'bar',
1486
+ data: {
1487
+ labels: rows.map((r) => r[0]),
1488
+ datasets: [
1489
+ barDataset(
1490
+ rows.map((r) => r[1]),
1491
+ rows.map((r) => r[2]),
1492
+ ),
1493
+ ],
1494
+ },
1495
+ options: {
1496
+ ...defaults,
1497
+ indexAxis: 'y',
1498
+ interaction: { mode: 'index', axis: 'y', intersect: false },
1499
+ plugins: withTooltip(defaults, {
1500
+ label: (ctx) => `${formatTokens(ctx.parsed.x)} (${formatPct(ctx.parsed.x, total)}%)`,
1501
+ }),
1502
+ scales: {
1503
+ ...defaults.scales,
1504
+ // Log scale: cache reads structurally dwarf fresh input by 3-5 orders of magnitude,
1505
+ // so a linear axis renders every other bar invisible. Tooltip carries exact values + %.
1506
+ x: logAxis(defaults.scales.x, Math.max(...rows.map((r) => r[1]))),
1507
+ },
1508
+ },
1509
+ });
1510
+ }
1511
+
1512
+ function renderToolsChart(tools) {
1513
+ const canvas = document.getElementById('toolsChart');
1514
+ if (!canvas || !tools?.length) return;
1515
+ destroyChart('tools');
1516
+
1517
+ const c = getChartColors();
1518
+ const defaults = chartDefaults();
1519
+
1520
+ // Top 8 with every label visible beats a longer list where Chart.js skips every other tick.
1521
+ const top = tools.slice(0, 8);
1522
+ // MCP tool names ("mcp__plugin_x__ctx_execute") are too long for axis labels — keep the tail.
1523
+ const shortName = (n) => (n.includes('__') ? n.split('__').pop() : n);
1524
+
1525
+ charts.tools = new Chart(canvas, {
1526
+ type: 'bar',
1527
+ data: {
1528
+ labels: top.map((t) => shortName(t.name)),
1529
+ datasets: [
1530
+ barDataset(
1531
+ top.map((t) => t.count),
1532
+ c.chart2,
1533
+ ),
1534
+ ],
1535
+ },
1536
+ options: {
1537
+ ...defaults,
1538
+ indexAxis: 'y',
1539
+ // Row-wise hit testing, so the tooltip also opens over the axis label and the empty
1540
+ // space past a short bar — the label is where the eye goes for a truncated MCP name.
1541
+ interaction: { mode: 'index', axis: 'y', intersect: false },
1542
+ plugins: withTooltip(defaults, {
1543
+ title: (items) => top[items[0].dataIndex]?.name || '',
1544
+ label: (ctx) => `${ctx.parsed.x} calls`,
1545
+ }),
1546
+ scales: {
1547
+ ...defaults.scales,
1548
+ y: { ...defaults.scales.y, ticks: { ...defaults.scales.y.ticks, autoSkip: false } },
1549
+ },
1550
+ },
1551
+ });
1552
+ }
1553
+
1554
+ function renderWeeklyChart(weekly) {
1555
+ const canvas = document.getElementById('weeklyChart');
1556
+ if (!canvas || !weekly?.length) return;
1557
+ destroyChart('weekly');
1558
+
1559
+ const c = getChartColors();
1560
+ const defaults = chartDefaults();
1561
+
1562
+ charts.weekly = new Chart(canvas, {
1563
+ type: 'bar',
1564
+ data: {
1565
+ labels: weekly.map((w) => isoDayLabel(w.weekStart)),
1566
+ datasets: [
1567
+ barDataset(
1568
+ weekly.map((w) => w.cost),
1569
+ c.chart1,
1570
+ ),
1571
+ ],
1572
+ },
1573
+ options: {
1574
+ ...defaults,
1575
+ plugins: withTooltip(defaults, { label: (ctx) => usd(ctx.parsed.y) }),
1576
+ scales: {
1577
+ ...defaults.scales,
1578
+ y: { ...defaults.scales.y, ticks: { ...defaults.scales.y.ticks, callback: usd } },
1579
+ },
1580
+ },
1581
+ });
1582
+ }
1583
+
1066
1584
  // biome-ignore lint/correctness/noUnusedVariables: called from theme toggle
1067
1585
  function destroyAllCharts() {
1068
1586
  for (const id of Object.keys(charts)) {
@@ -1154,14 +1672,328 @@ function setColorTheme(id) {
1154
1672
 
1155
1673
  // #endregion
1156
1674
 
1157
- // #region ROUTER
1675
+ // #region DATE_PICKER
1676
+
1677
+ // Presets are sticky: what is stored is the preset, and the server recomputes its rolling window on
1678
+ // every request. `days` only previews the span inside the calendar.
1679
+ const RANGE_PRESETS = [
1680
+ { value: 'today', label: 'Today', days: 0 },
1681
+ { value: '24h', label: 'Last 24h', days: 1 },
1682
+ { value: '3', label: '3 Days', days: 3 },
1683
+ { value: '7', label: '7 Days', days: 7 },
1684
+ { value: '30', label: '30 Days', days: 30 },
1685
+ { value: '90', label: '90 Days', days: 90 },
1686
+ { value: '365', label: '1 Year', days: 365, cardLabel: '365 Days' },
1687
+ ];
1688
+ const RANGE_DOW = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
1689
+ // Two months do not fit a narrow window, so below this the calendar collapses to one. Kept in step
1690
+ // with the same breakpoint in style.css.
1691
+ const ONE_MONTH_QUERY = '(max-width: 760px)';
1692
+ // One live MediaQueryList: matchMedia() hands back a new object each call, so add/removeEventListener
1693
+ // have to share this one or the listener never comes off.
1694
+ const oneMonthMql = window.matchMedia(ONE_MONTH_QUERY);
1695
+ const RANGE_ARROWS = {
1696
+ prev: '<path d="M6.5 1L2.5 5l4 4"/>',
1697
+ next: '<path d="M3.5 1l4 4-4 4"/>',
1698
+ };
1158
1699
 
1159
- function setActiveNav(view) {
1160
- document.querySelectorAll('.topbar-nav-btn').forEach((btn) => {
1161
- btn.classList.toggle('active', btn.dataset.view === view);
1162
- });
1700
+ // Non-null only while the popover is open — it is both the draft and the open flag. `picking` is
1701
+ // which end the next day click lands on; `hover` previews the span before the second click.
1702
+ let rangeDraft = null;
1703
+
1704
+ function isRangePickerOpen() {
1705
+ return !!rangeDraft;
1706
+ }
1707
+
1708
+ function oneMonthMode() {
1709
+ return oneMonthMql.matches;
1710
+ }
1711
+
1712
+ // What a preset covers, for highlighting only. '24h' is named here because its span is not a day
1713
+ // count: it straddles the two calendar days a rolling day touches. Everything else is the last N
1714
+ // calendar days ending today, which is now exactly the window the server fetches — 'today' included,
1715
+ // since a span of one day or less is today itself.
1716
+ function rangePresetSpan(value) {
1717
+ const today = todayIso();
1718
+ if (value === '24h') return { from: isoShift(today, -1), to: today };
1719
+ const days = Number(value) || 1;
1720
+ return { from: days <= 1 ? today : isoShift(today, -(days - 1)), to: today };
1721
+ }
1722
+
1723
+ function buildRangePresets() {
1724
+ const host = document.getElementById('rangePresets');
1725
+ if (!host) return;
1726
+ for (const p of RANGE_PRESETS) {
1727
+ const b = document.createElement('button');
1728
+ b.type = 'button';
1729
+ b.className = 'range-preset';
1730
+ b.dataset.value = p.value;
1731
+ b.textContent = p.label;
1732
+ // A shortcut is one click, like the dropdown it replaces: apply and close, no Apply button.
1733
+ b.addEventListener('click', () => {
1734
+ closeRangePicker();
1735
+ applyRange(presetRange(p.value));
1736
+ });
1737
+ host.appendChild(b);
1738
+ }
1739
+ }
1740
+
1741
+ function renderRangeTrigger() {
1742
+ const el = document.getElementById('rangeTriggerLabel');
1743
+ if (el) el.textContent = rangeTriggerLabel(dateRange);
1744
+ }
1745
+
1746
+ // biome-ignore lint/correctness/noUnusedVariables: called from topbar markup
1747
+ function toggleRangePicker(e) {
1748
+ e?.stopPropagation();
1749
+ if (isRangePickerOpen()) closeRangePicker();
1750
+ else openRangePicker();
1751
+ }
1752
+
1753
+ function openRangePicker() {
1754
+ const applied = normalizeRange(dateRange) || presetRange(DEFAULT_RANGE_PRESET);
1755
+ const span = applied.kind === 'custom' ? { from: applied.from, to: applied.to } : rangePresetSpan(applied.value);
1756
+ // The left pane shows the month before the window's end, so today sits in the right one; with a
1757
+ // single month it is that month itself.
1758
+ const [ay, am] = isoParts(span.to);
1759
+ const first = new Date(ay, am - 1 - (oneMonthMode() ? 0 : 1), 1);
1760
+ rangeDraft = {
1761
+ from: span.from,
1762
+ to: span.to,
1763
+ preset: applied.kind === 'custom' ? null : applied.value,
1764
+ picking: 'from',
1765
+ hover: null,
1766
+ month: { y: first.getFullYear(), m: first.getMonth() },
1767
+ };
1768
+ document.getElementById('rangePop').classList.add('open');
1769
+ document.getElementById('rangeTrigger').classList.add('on');
1770
+ // Capture phase: a day click re-renders the grid and detaches its own button, so by the bubble
1771
+ // phase the target is no longer inside #rangePicker and would read as an outside click.
1772
+ document.addEventListener('click', onRangePickerOutsideClick, true);
1773
+ const months = document.getElementById('rangeMonths');
1774
+ months.addEventListener('click', onRangeDayClick);
1775
+ months.addEventListener('mouseover', onRangeDayHover);
1776
+ oneMonthMql.addEventListener('change', renderRangePicker);
1777
+ renderRangePicker();
1778
+ }
1779
+
1780
+ function closeRangePicker() {
1781
+ if (!rangeDraft) return;
1782
+ rangeDraft = null;
1783
+ document.getElementById('rangePop').classList.remove('open');
1784
+ document.getElementById('rangeTrigger').classList.remove('on');
1785
+ document.removeEventListener('click', onRangePickerOutsideClick, true);
1786
+ const months = document.getElementById('rangeMonths');
1787
+ months.removeEventListener('click', onRangeDayClick);
1788
+ months.removeEventListener('mouseover', onRangeDayHover);
1789
+ oneMonthMql.removeEventListener('change', renderRangePicker);
1790
+ }
1791
+
1792
+ // Both grids are delegated: one listener pair on #rangeMonths instead of two per day cell. Only the
1793
+ // selectable days carry data-iso, so the lead padding and the days after today stay inert. It has to
1794
+ // be 'mouseover' — 'mouseenter' does not bubble, so it cannot be delegated.
1795
+ function onRangeDayClick(e) {
1796
+ const iso = e.target.dataset?.iso;
1797
+ if (iso) pickRangeDay(iso);
1798
+ }
1799
+
1800
+ function onRangeDayHover(e) {
1801
+ const iso = e.target.dataset?.iso;
1802
+ if (iso && rangeDraft?.from && !rangeDraft.to && rangeDraft.hover !== iso) {
1803
+ rangeDraft.hover = iso;
1804
+ paintRangeSpan();
1805
+ }
1806
+ }
1807
+
1808
+ // Outside click cancels: the draft is dropped and the applied range stays.
1809
+ function onRangePickerOutsideClick(e) {
1810
+ if (!document.getElementById('rangePicker').contains(e.target)) closeRangePicker();
1163
1811
  }
1164
1812
 
1813
+ // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
1814
+ function aimRangePicker(which) {
1815
+ if (!rangeDraft) return;
1816
+ rangeDraft.picking = which;
1817
+ renderRangePicker();
1818
+ }
1819
+
1820
+ // biome-ignore lint/correctness/noUnusedVariables: called from popover markup
1821
+ function applyRangeDraft() {
1822
+ const d = rangeDraft;
1823
+ if (!d?.from || !d.to) return;
1824
+ const next = { kind: 'custom', from: d.from, to: d.to };
1825
+ closeRangePicker();
1826
+ applyRange(next);
1827
+ }
1828
+
1829
+ function pickRangeDay(iso) {
1830
+ const d = rangeDraft;
1831
+ d.preset = null;
1832
+ if (d.picking === 'from' || !d.from) {
1833
+ d.from = iso;
1834
+ d.to = null;
1835
+ d.picking = 'to';
1836
+ } else if (iso < d.from) {
1837
+ // A second click before the first flips the pair instead of refusing it.
1838
+ d.to = d.from;
1839
+ d.from = iso;
1840
+ d.picking = 'from';
1841
+ } else {
1842
+ d.to = iso;
1843
+ d.picking = 'from';
1844
+ }
1845
+ d.hover = null;
1846
+ renderRangePicker();
1847
+ }
1848
+
1849
+ function rangeMonthStep(step) {
1850
+ const c = new Date(rangeDraft.month.y, rangeDraft.month.m + step, 1);
1851
+ rangeDraft.month = { y: c.getFullYear(), m: c.getMonth() };
1852
+ renderRangePicker();
1853
+ }
1854
+
1855
+ // There is no cost data ahead of today, so the calendar stops at the current month.
1856
+ function rangeNextDisabled() {
1857
+ const last = new Date(rangeDraft.month.y, rangeDraft.month.m + (oneMonthMode() ? 0 : 1), 1);
1858
+ const now = new Date();
1859
+ return last >= new Date(now.getFullYear(), now.getMonth(), 1);
1860
+ }
1861
+
1862
+ // The highlighted span: the picked window, or from -> the hovered day while the second end is open.
1863
+ function rangeDraftSpan() {
1864
+ const d = rangeDraft;
1865
+ if (!d?.from) return [null, null];
1866
+ if (d.to) return [d.from, d.to];
1867
+ if (!d.hover) return [d.from, d.from];
1868
+ return d.hover < d.from ? [d.hover, d.from] : [d.from, d.hover];
1869
+ }
1870
+
1871
+ // The span highlight is four classes on day cells that already exist, so a hover repaint toggles
1872
+ // them in place instead of rebuilding both grids. Sole owner of those classes — buildRangeMonth
1873
+ // leaves them to the paint pass that follows it, so the two can never drift apart.
1874
+ function paintRangeSpan() {
1875
+ const [a, b] = rangeDraftSpan();
1876
+ for (const btn of document.querySelectorAll('#rangeMonths .range-day[data-iso]')) {
1877
+ const iso = btn.dataset.iso;
1878
+ const inSpan = !!(a && b && iso >= a && iso <= b);
1879
+ const edge = inSpan && (iso === a || iso === b);
1880
+ btn.classList.toggle('edge', edge);
1881
+ btn.classList.toggle('in', inSpan && !edge);
1882
+ btn.classList.toggle('start', inSpan && !edge && isoShift(iso, -1) === a);
1883
+ btn.classList.toggle('end', inSpan && !edge && isoShift(iso, 1) === b);
1884
+ }
1885
+ }
1886
+
1887
+ function renderRangePicker() {
1888
+ const d = rangeDraft;
1889
+ if (!d) return;
1890
+
1891
+ for (const b of document.querySelectorAll('#rangePresets .range-preset')) {
1892
+ b.classList.toggle('on', b.dataset.value === d.preset);
1893
+ }
1894
+
1895
+ const fromBox = document.getElementById('rangeFromBox');
1896
+ const toBox = document.getElementById('rangeToBox');
1897
+ fromBox.textContent = d.from ? isoDayLabel(d.from) : '—';
1898
+ toBox.textContent = d.to ? isoDayLabel(d.to) : '—';
1899
+ fromBox.classList.toggle('empty', !d.from);
1900
+ toBox.classList.toggle('empty', !d.to);
1901
+ fromBox.classList.toggle('active', d.picking === 'from');
1902
+ toBox.classList.toggle('active', d.picking === 'to');
1903
+
1904
+ const [a, b] = rangeDraftSpan();
1905
+ const days = d.from && d.to ? isoDayCount(a, b) : 0;
1906
+ document.getElementById('rangeSummary').textContent = days
1907
+ ? `${days} ${days === 1 ? 'day' : 'days'}`
1908
+ : 'pick an end date';
1909
+ document.getElementById('rangeApply').disabled = !(d.from && d.to);
1910
+
1911
+ const host = document.getElementById('rangeMonths');
1912
+ host.innerHTML = '';
1913
+ const single = oneMonthMode();
1914
+ const first = new Date(d.month.y, d.month.m, 1);
1915
+ host.appendChild(buildRangeMonth(first.getFullYear(), first.getMonth(), { prev: true, next: single }));
1916
+ if (!single) {
1917
+ const second = new Date(d.month.y, d.month.m + 1, 1);
1918
+ host.appendChild(buildRangeMonth(second.getFullYear(), second.getMonth(), { prev: false, next: true }));
1919
+ }
1920
+ paintRangeSpan();
1921
+ }
1922
+
1923
+ function rangeNavButton(dir) {
1924
+ const step = dir === 'next' ? 1 : -1;
1925
+ const btn = document.createElement('button');
1926
+ btn.type = 'button';
1927
+ btn.className = 'range-nav';
1928
+ btn.innerHTML = `<svg viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">${RANGE_ARROWS[dir]}</svg>`;
1929
+ if (step > 0) btn.disabled = rangeNextDisabled();
1930
+ btn.addEventListener('click', () => rangeMonthStep(step));
1931
+ return btn;
1932
+ }
1933
+
1934
+ // Holds the title centred on the side that carries no arrow.
1935
+ function rangeNavGap() {
1936
+ const gap = document.createElement('span');
1937
+ gap.className = 'range-nav-gap';
1938
+ return gap;
1939
+ }
1940
+
1941
+ function buildRangeMonth(y, m, nav) {
1942
+ const wrap = document.createElement('div');
1943
+ wrap.className = 'range-cal';
1944
+
1945
+ const title = new Date(y, m, 1).toLocaleDateString(undefined, { month: 'short' }).toUpperCase();
1946
+
1947
+ const head = document.createElement('div');
1948
+ head.className = 'range-cal-head';
1949
+ head.appendChild(nav.prev ? rangeNavButton('prev') : rangeNavGap());
1950
+ const titleEl = document.createElement('span');
1951
+ titleEl.className = 'range-cal-title';
1952
+ titleEl.textContent = `${title} ${y}`;
1953
+ head.appendChild(titleEl);
1954
+ head.appendChild(nav.next ? rangeNavButton('next') : rangeNavGap());
1955
+ wrap.appendChild(head);
1956
+
1957
+ const dow = document.createElement('div');
1958
+ dow.className = 'range-dow';
1959
+ dow.innerHTML = RANGE_DOW.map((d) => `<span>${d}</span>`).join('');
1960
+ wrap.appendChild(dow);
1961
+
1962
+ const grid = document.createElement('div');
1963
+ grid.className = 'range-grid';
1964
+ const lead = (new Date(y, m, 1).getDay() + 6) % 7; // Monday-first
1965
+ const dayCount = new Date(y, m + 1, 0).getDate();
1966
+ const today = todayIso();
1967
+
1968
+ for (let i = 0; i < lead; i++) {
1969
+ const pad = document.createElement('span');
1970
+ pad.className = 'range-day pad';
1971
+ grid.appendChild(pad);
1972
+ }
1973
+ for (let day = 1; day <= dayCount; day++) {
1974
+ const iso = isoDate(new Date(y, m, day));
1975
+ const btn = document.createElement('button');
1976
+ btn.type = 'button';
1977
+ btn.className = 'range-day';
1978
+ btn.textContent = day;
1979
+ if (iso === today) btn.classList.add('today');
1980
+ if (iso > today) {
1981
+ btn.classList.add('off');
1982
+ btn.disabled = true;
1983
+ } else {
1984
+ // What the delegated click/hover handlers and paintRangeSpan read the cell's day back from.
1985
+ btn.dataset.iso = iso;
1986
+ }
1987
+ grid.appendChild(btn);
1988
+ }
1989
+ wrap.appendChild(grid);
1990
+ return wrap;
1991
+ }
1992
+
1993
+ // #endregion
1994
+
1995
+ // #region ROUTER
1996
+
1165
1997
  function showView(viewId) {
1166
1998
  document.querySelectorAll('.view').forEach((v) => v.classList.remove('active'));
1167
1999
  const el = document.getElementById(viewId);
@@ -1175,7 +2007,7 @@ async function navigate(view, params) {
1175
2007
  if (params?.session) currentSessionId = params.session;
1176
2008
 
1177
2009
  // Clear downstream state
1178
- if (view === 'overview' || view === 'projects') {
2010
+ if (view === 'overview' || view === 'insights') {
1179
2011
  currentProjectPath = null;
1180
2012
  currentProjectName = null;
1181
2013
  currentSessionId = null;
@@ -1184,8 +2016,6 @@ async function navigate(view, params) {
1184
2016
  currentSessionId = null;
1185
2017
  }
1186
2018
 
1187
- const navView = view === 'sessions' || view === 'detail' ? parentView : view;
1188
- setActiveNav(navView);
1189
2019
  updateUrl();
1190
2020
  await loadAndRender(view);
1191
2021
  if (view !== 'detail') selectRow(0);
@@ -1193,9 +2023,6 @@ async function navigate(view, params) {
1193
2023
 
1194
2024
  // biome-ignore lint/correctness/noUnusedVariables: called from HTML onclick
1195
2025
  async function navigateToSessions(encodedPath, name) {
1196
- if (currentView === 'overview' || currentView === 'projects') {
1197
- parentView = currentView;
1198
- }
1199
2026
  lastSelectedProject = encodedPath;
1200
2027
  currentProjectPath = encodedPath;
1201
2028
  currentProjectName = name;
@@ -1212,6 +2039,7 @@ async function navigateToDetail(sessionId) {
1212
2039
  // biome-ignore lint/correctness/noUnusedVariables: called from HTML onclick
1213
2040
  function sortBy(field) {
1214
2041
  const s = currentSort();
2042
+ if (!s) return;
1215
2043
  if (s.field === field) {
1216
2044
  s.order = s.order === 'desc' ? 'asc' : 'desc';
1217
2045
  } else {
@@ -1223,14 +2051,15 @@ function sortBy(field) {
1223
2051
  updateUrl();
1224
2052
  if (currentView === 'overview') renderOverview();
1225
2053
  else if (currentView === 'sessions') renderSessions();
1226
- else renderProjects();
1227
2054
  }
1228
2055
 
1229
- // biome-ignore lint/correctness/noUnusedVariables: called from HTML onchange
1230
- async function onRangeChange(val) {
1231
- dateRange = val === 'today' ? 'today' : parseInt(val, 10) || 7;
2056
+ // The one entry point for a range change, from either half of the picker. The lastRenderHash reset
2057
+ // is load-bearing: the renderers are hash-gated and would not repaint the new window otherwise.
2058
+ async function applyRange(next) {
2059
+ dateRange = next;
1232
2060
  saveDateRange(dateRange);
1233
2061
  lastRenderHash = {};
2062
+ renderRangeTrigger();
1234
2063
  updateUrl();
1235
2064
  const t = showToast(`Recalculating for ${rangeLabel(dateRange)}...`, true);
1236
2065
  await loadAndRender(currentView);
@@ -1266,7 +2095,6 @@ async function applyScope(encoded, name) {
1266
2095
  // rows.
1267
2096
  sessionsData = null;
1268
2097
  sessionDetailData = null;
1269
- parentView = 'overview';
1270
2098
  await navigate('sessions', { project: scopeProject, projectName: scopeProjectName });
1271
2099
  }
1272
2100
 
@@ -1329,10 +2157,10 @@ async function loadAndRender(view) {
1329
2157
  if (myNav !== navCounter) return;
1330
2158
  renderOverview();
1331
2159
  break;
1332
- case 'projects':
1333
- await fetchProjects();
2160
+ case 'insights':
2161
+ await fetchInsights();
1334
2162
  if (myNav !== navCounter) return;
1335
- renderProjects();
2163
+ renderInsights();
1336
2164
  break;
1337
2165
  case 'sessions':
1338
2166
  if (currentProjectPath) {
@@ -1374,7 +2202,7 @@ function renderCurrentView() {
1374
2202
  function ensureViewElements() {
1375
2203
  const app = document.getElementById('app');
1376
2204
  if (!app) return;
1377
- const views = ['overview', 'projects', 'sessions', 'detail'];
2205
+ const views = ['overview', 'insights', 'sessions', 'detail'];
1378
2206
  for (const v of views) {
1379
2207
  if (!document.getElementById(`${v}-view`)) {
1380
2208
  const div = document.createElement('div');
@@ -1430,16 +2258,19 @@ function activateSelectedRow() {
1430
2258
  async function goBack() {
1431
2259
  let target;
1432
2260
  if (currentView === 'detail') {
1433
- target = currentProjectPath ? 'sessions' : parentView;
1434
- } else if (currentView === 'sessions') {
1435
- target = parentView;
1436
- } else if (currentView === 'projects') {
2261
+ target = currentProjectPath ? 'sessions' : 'overview';
2262
+ } else if (currentView === 'sessions' || currentView === 'insights') {
1437
2263
  target = 'overview';
1438
2264
  }
1439
2265
  if (!target) return;
1440
2266
 
2267
+ // Insights is a sibling view, not a drill-down: the scope survives a tab switch.
2268
+ const keepScope = currentView === 'insights';
2269
+
1441
2270
  if (target === 'sessions') {
1442
2271
  await navigate('sessions', { project: currentProjectPath, projectName: currentProjectName });
2272
+ } else if (keepScope) {
2273
+ await navigate(target);
1443
2274
  } else {
1444
2275
  // Backing out to a top-level view drops the scope with the cursor: a scoped overview
1445
2276
  // showing one project has no visible cause once you've left that project behind.
@@ -1461,6 +2292,16 @@ document.addEventListener('keydown', (e) => {
1461
2292
  return;
1462
2293
  }
1463
2294
 
2295
+ // The same exemption the modal above gets: the popover is a div, so the INPUT/SELECT guard does
2296
+ // not cover it, and r/t/j/k/Esc would otherwise fire straight through an open picker.
2297
+ if (isRangePickerOpen()) {
2298
+ if (e.key === 'Escape') {
2299
+ closeRangePicker();
2300
+ e.preventDefault();
2301
+ }
2302
+ return;
2303
+ }
2304
+
1464
2305
  if (e.ctrlKey || e.altKey || e.metaKey) return;
1465
2306
 
1466
2307
  if (e.key === '?' || (e.key === '/' && e.shiftKey)) {
@@ -1474,9 +2315,10 @@ document.addEventListener('keydown', (e) => {
1474
2315
  navigate('overview');
1475
2316
  return;
1476
2317
  }
2318
+
1477
2319
  if (e.key === '2') {
1478
2320
  e.preventDefault();
1479
- navigate('projects');
2321
+ navigate('insights');
1480
2322
  return;
1481
2323
  }
1482
2324
 
@@ -1689,16 +2531,16 @@ loadSort();
1689
2531
 
1690
2532
  document.addEventListener('click', async (e) => {
1691
2533
  if (e.target.matches('.parent-breadcrumb')) {
1692
- const target = parentView;
1693
- await navigate(target);
1694
- focusPreviousRow(target);
2534
+ await navigate('overview');
2535
+ focusPreviousRow('overview');
1695
2536
  }
1696
2537
  });
1697
2538
 
1698
2539
  document.addEventListener('DOMContentLoaded', async () => {
1699
2540
  const state = getUrlState();
1700
2541
  dateRange = loadDateRange();
1701
- document.getElementById('rangeSelect').value = dateRange;
2542
+ buildRangePresets();
2543
+ renderRangeTrigger();
1702
2544
 
1703
2545
  // Resolve the scope before any navigate() so the first /api/overview already carries
1704
2546
  // &project=. Read window.location.search directly, not getUrlState() — that falls back to
@@ -1717,20 +2559,15 @@ document.addEventListener('DOMContentLoaded', async () => {
1717
2559
 
1718
2560
  if (state.session) {
1719
2561
  currentSessionId = state.session;
1720
- parentView = state.parentView;
1721
2562
  currentProjectPath = state.project;
1722
2563
  currentProjectName = state.projectName;
1723
2564
  await navigate('detail', { session: state.session });
1724
2565
  } else if (state.project) {
1725
- parentView = state.parentView;
1726
2566
  currentProjectPath = state.project;
1727
2567
  currentProjectName = state.projectName;
1728
2568
  await navigate('sessions', { project: state.project, projectName: state.projectName });
1729
- } else if (state.view === 'projects') {
1730
- await navigate('projects');
1731
2569
  } else if (scopeProject) {
1732
2570
  // Same landing rule as applyScope: a scope with no cursor of its own opens its sessions.
1733
- parentView = 'overview';
1734
2571
  currentProjectName = scopeProjectName;
1735
2572
  await navigate('sessions', { project: scopeProject, projectName: scopeProjectName });
1736
2573
  } else {
@@ -1741,7 +2578,6 @@ document.addEventListener('DOMContentLoaded', async () => {
1741
2578
  window.addEventListener('popstate', () => {
1742
2579
  const state = getUrlState();
1743
2580
  currentView = state.view || 'overview';
1744
- parentView = state.parentView;
1745
2581
  currentProjectPath = state.project;
1746
2582
  currentProjectName = state.projectName;
1747
2583
  currentSessionId = state.session;