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/server.js CHANGED
@@ -214,21 +214,37 @@ function calculateEntryCost(data, pricing) {
214
214
  // #region DATA_AGGREGATION
215
215
 
216
216
  const CACHE_TTL = 30_000;
217
- let dataCache = {};
218
- let cacheTimestamps = {};
219
217
 
220
- function isCacheValid(key) {
221
- return cacheTimestamps[key] && (Date.now() - cacheTimestamps[key]) < CACHE_TTL;
218
+ // Custom from/to windows make the key space unbounded, so the cache is capped, which would
219
+ // otherwise grow for the process lifetime. A Map keeps insertion order, so the oldest write is
220
+ // always the first key — no sort, no key array.
221
+ const MAX_CACHE_ENTRIES = 50;
222
+ const dataCache = new Map();
223
+
224
+ // undefined means "no usable entry": every cached payload is an object or an array, so it can
225
+ // never collide with a real one. A stale hit is dropped here rather than left resident until the
226
+ // cap pushes it out — detail_<id> entries carry a whole message array.
227
+ function getCache(key) {
228
+ const hit = dataCache.get(key);
229
+ if (!hit) return undefined;
230
+ if ((Date.now() - hit.ts) >= CACHE_TTL) {
231
+ dataCache.delete(key);
232
+ return undefined;
233
+ }
234
+ return hit.data;
222
235
  }
223
236
 
224
237
  function setCache(key, data) {
225
- dataCache[key] = data;
226
- cacheTimestamps[key] = Date.now();
238
+ // Re-inserting moves an existing key to the back, so a rewrite resets its eviction priority.
239
+ dataCache.delete(key);
240
+ dataCache.set(key, { data, ts: Date.now() });
241
+ while (dataCache.size > MAX_CACHE_ENTRIES) {
242
+ dataCache.delete(dataCache.keys().next().value);
243
+ }
227
244
  }
228
245
 
229
246
  function invalidateAllCache() {
230
- dataCache = {};
231
- cacheTimestamps = {};
247
+ dataCache.clear();
232
248
  }
233
249
 
234
250
  function localDateStr(d) {
@@ -238,20 +254,58 @@ function localDateStr(d) {
238
254
  return `${y}-${m}-${day}`;
239
255
  }
240
256
 
241
- function buildFilledDaily(dailyCosts, start, end) {
242
- const filled = [];
243
- if (Object.keys(dailyCosts).length > 0) {
244
- for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
245
- const ds = localDateStr(d);
246
- filled.push({ date: ds, cost: dailyCosts[ds] || 0 });
247
- }
257
+ function localHourStr(d) {
258
+ return `${localDateStr(d)}T${String(d.getHours()).padStart(2, '0')}`;
259
+ }
260
+
261
+ // Cost is bucketed by one of these; the key doubles as the aggregation key and the wire label.
262
+ // An hour key extends the day key (YYYY-MM-DD -> YYYY-MM-DDTHH), so a startsWith test on a day
263
+ // string matches either granularity.
264
+ const BUCKETS = {
265
+ day: {
266
+ key: localDateStr,
267
+ floor: (d) => d.setHours(0, 0, 0, 0),
268
+ next: (d) => d.setDate(d.getDate() + 1),
269
+ },
270
+ hour: {
271
+ key: localHourStr,
272
+ floor: (d) => d.setMinutes(0, 0, 0),
273
+ next: (d) => d.setHours(d.getHours() + 1),
274
+ },
275
+ };
276
+
277
+ // A one-day window collapses the daily chart into a single bar, so those ranges bucket by hour.
278
+ function rangeBucket(range) {
279
+ if (isCustomRange(range)) return range.from === range.to ? 'hour' : 'day';
280
+ return range === 'today' || range === '24h' || range === 1 ? 'hour' : 'day';
281
+ }
282
+
283
+ // Non-real (synthetic) models group under 'other' so the series still sums to the true
284
+ // bucket total, unlike modelDistribution which drops them entirely.
285
+ function addBucketModelCost(acc, key, model, cost) {
286
+ const mk = isRealModel(model) ? model : 'other';
287
+ (acc[key] ||= {})[mk] = (acc[key][mk] || 0) + cost;
288
+ }
289
+
290
+ // Gap-filled so empty buckets stay visible in the chart. The bucket total is derived from
291
+ // the per-model map, so the two can never disagree.
292
+ function buildCostSeries(modelCostsByBucket, start, end, bucket) {
293
+ const b = BUCKETS[bucket];
294
+ const points = [];
295
+ if (Object.keys(modelCostsByBucket).length === 0) return points;
296
+ const d = new Date(start);
297
+ b.floor(d);
298
+ for (; d <= end; b.next(d)) {
299
+ const k = b.key(d);
300
+ const byModel = modelCostsByBucket[k] || {};
301
+ points.push({ key: k, cost: Object.values(byModel).reduce((s, v) => s + v, 0), byModel });
248
302
  }
249
- return filled;
303
+ return points;
250
304
  }
251
305
 
252
306
  function buildModelDistribution(modelCosts) {
253
307
  return Object.entries(modelCosts)
254
- .filter(([model, cost]) => cost > 0 && !model.startsWith('<'))
308
+ .filter(([model, cost]) => cost > 0 && isRealModel(model))
255
309
  .map(([model, cost]) => ({ model, cost }))
256
310
  .sort((a, b) => b.cost - a.cost);
257
311
  }
@@ -339,6 +393,11 @@ function scanSubagentDir(sessionDir) {
339
393
  return result;
340
394
  }
341
395
 
396
+ // `<synthetic>` and friends are Claude Code bookkeeping entries, not models the user chose.
397
+ function isRealModel(model) {
398
+ return !!model && !model.startsWith('<');
399
+ }
400
+
342
401
  function mostFrequentModel(counts) {
343
402
  return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';
344
403
  }
@@ -433,7 +492,7 @@ async function loadProjectData(files, pricing) {
433
492
  session.outputTokens += usage.output_tokens || 0;
434
493
  session.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
435
494
  session.cacheReadTokens += (usage.cache_read_input_tokens || 0);
436
- session.models.add(model);
495
+ if (isRealModel(model)) session.models.add(model);
437
496
 
438
497
  if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
439
498
  if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
@@ -472,7 +531,7 @@ async function loadProjectData(files, pricing) {
472
531
  session.outputTokens += sa.outputTokens;
473
532
  session.cacheCreationTokens += sa.cacheCreationTokens;
474
533
  session.cacheReadTokens += sa.cacheReadTokens;
475
- for (const m of sa.models) session.models.add(m);
534
+ for (const m of sa.models) if (isRealModel(m)) session.models.add(m);
476
535
  session.messages.push({
477
536
  timestamp: sa.firstTimestamp || session.firstTimestamp,
478
537
  model: sa.models[0] || 'unknown',
@@ -491,31 +550,128 @@ async function loadProjectData(files, pricing) {
491
550
  return sessions;
492
551
  }
493
552
 
553
+ // A range is either a preset — 'today', '24h', the last N calendar days, or null for all time, all
554
+ // anchored to the request — or a custom window of two local YYYY-MM-DD dates.
555
+ function isCustomRange(range) {
556
+ return !!range && typeof range === 'object' && !!range.from && !!range.to;
557
+ }
558
+
559
+ function localDayStart(dateStr) {
560
+ const [y, m, d] = dateStr.split('-').map(Number);
561
+ return new Date(y, m - 1, d, 0, 0, 0, 0);
562
+ }
563
+
564
+ // `to` names a whole day, so the window runs through the end of it — a midnight bound would
565
+ // silently drop that day's data.
566
+ function localDayEnd(dateStr) {
567
+ const d = localDayStart(dateStr);
568
+ d.setHours(23, 59, 59, 999);
569
+ return d;
570
+ }
571
+
494
572
  function rangeToCutoff(range, now) {
573
+ if (isCustomRange(range)) return localDayStart(range.from);
495
574
  if (range === 'today') {
496
575
  const c = new Date(now);
497
576
  c.setHours(0, 0, 0, 0);
498
577
  return c;
499
578
  }
579
+ // The one rolling preset left, and the reason it is labelled in hours: no midnight snap, so it
580
+ // spans two calendar days.
581
+ if (range === '24h') return new Date(now.getTime() - 24 * 60 * 60 * 1000);
500
582
  if (!range) return null;
583
+ // N calendar days ending today: identical to from=today-(N-1)&to=today, so the chart draws
584
+ // exactly N buckets instead of N+1 with a partial leading one.
501
585
  const c = new Date(now);
502
- c.setDate(c.getDate() - range);
586
+ c.setDate(c.getDate() - (range - 1));
587
+ c.setHours(0, 0, 0, 0);
503
588
  return c;
504
589
  }
505
590
 
591
+ // The window's upper bound, which used to be an implicit `now` in six places. Presets are rolling,
592
+ // so theirs still is; a custom window ends with its `to` day.
593
+ function rangeToEnd(range, now) {
594
+ return isCustomRange(range) ? localDayEnd(range.to) : new Date(now);
595
+ }
596
+
597
+ // Presets keep an open upper bound: they end at "whenever this request lands", so filtering
598
+ // against a captured `now` would only ever drop rows a live session wrote mid-request.
599
+ function windowEndStr(range, windowEnd) {
600
+ return isCustomRange(range) ? windowEnd.toISOString() : null;
601
+ }
602
+
603
+ // True when today falls inside the window. A null cutoff means open toward the past.
604
+ function windowContainsToday(cutoff, windowEnd, now) {
605
+ const todayStr = localDateStr(now);
606
+ return (!cutoff || localDateStr(cutoff) <= todayStr) && localDateStr(windowEnd) >= todayStr;
607
+ }
608
+
609
+ // Everything a range resolves to, anchored to one captured `now` so the bounds of a single request
610
+ // can never disagree with each other. `cutoff` stays null for the all-time range.
611
+ function resolveWindow(range, now = new Date()) {
612
+ const cutoff = rangeToCutoff(range, now);
613
+ const end = rangeToEnd(range, now);
614
+ return {
615
+ now, cutoff, end,
616
+ cutoffStr: cutoff ? cutoff.toISOString() : null,
617
+ endStr: windowEndStr(range, end),
618
+ hasToday: windowContainsToday(cutoff, end, now),
619
+ };
620
+ }
621
+
622
+ // Two-sided when the window has an end, so a window that stops in the past excludes later
623
+ // messages. A null bound means open in that direction.
624
+ function filterWindow(messages, fromStr, toStr) {
625
+ if (!fromStr && !toStr) return messages;
626
+ return messages.filter((m) => (!fromStr || m.timestamp >= fromStr) && (!toStr || m.timestamp <= toStr));
627
+ }
628
+
629
+ // Custom windows key by their dates, which is why the cache is capped (see MAX_CACHE_ENTRIES).
630
+ function rangeKey(range) {
631
+ if (isCustomRange(range)) return `${range.from}_${range.to}`;
632
+ return range || 'all';
633
+ }
634
+
635
+ // True when the window is exactly today — a preset 'today' or a single-day pick landing on it.
636
+ function isTodayRange(range, now) {
637
+ if (isCustomRange(range)) return range.from === range.to && range.to === localDateStr(now);
638
+ return range === 'today';
639
+ }
640
+
641
+ function summarizeMessages(msgs) {
642
+ const sum = { messageCount: msgs.length, totalCost: 0, inputTokens: 0, outputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0 };
643
+ for (const m of msgs) {
644
+ sum.totalCost += m.cost;
645
+ sum.inputTokens += m.inputTokens;
646
+ sum.outputTokens += m.outputTokens;
647
+ sum.cacheCreationTokens += m.cacheCreationTokens;
648
+ sum.cacheReadTokens += m.cacheReadTokens;
649
+ }
650
+ return sum;
651
+ }
652
+
506
653
  async function getOverviewData(range, projectFilter) {
507
- const cacheKey = `overview_${range}_${projectFilter || 'all'}`;
508
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
654
+ const cacheKey = `overview_${rangeKey(range)}_${projectFilter || 'all'}`;
655
+ const cached = getCache(cacheKey);
656
+ if (cached !== undefined) return cached;
509
657
 
510
658
  const pricing = await fetchPricing();
511
- const now = new Date();
512
- const cutoff = rangeToCutoff(range, now) || new Date(now);
659
+ const w = resolveWindow(range);
660
+ const now = w.now;
661
+ // The series needs a concrete start even for the all-time range, so a null cutoff falls back to
662
+ // now. Deliberately local: pushing it into resolveWindow would hand the other callers a non-null
663
+ // all-time cutoff and change what they filter on.
664
+ const cutoff = w.cutoff || w.now;
665
+ const windowEnd = w.end;
513
666
  const projects = scanProjectDirs(cutoff, projectFilter);
514
667
  const cutoffStr = cutoff.toISOString();
668
+ const endStr = w.endStr;
515
669
 
516
670
  let totalCost = 0, totalSessions = 0;
517
671
  let totalInput = 0, totalOutput = 0, totalCacheCreation = 0, totalCacheRead = 0;
518
- const dailyCosts = {};
672
+ const bucket = rangeBucket(range);
673
+ const bucketKey = BUCKETS[bucket].key;
674
+ const bucketModelCosts = {};
519
675
  const modelCosts = {};
520
676
  const projectSummaries = [];
521
677
 
@@ -526,7 +682,7 @@ async function getOverviewData(range, projectFilter) {
526
682
 
527
683
  for (const [, session] of sessions) {
528
684
  // Filter messages within date range
529
- const inRange = session.messages.filter(m => m.timestamp >= cutoffStr);
685
+ const inRange = filterWindow(session.messages, cutoffStr, endStr);
530
686
  if (inRange.length === 0) continue;
531
687
 
532
688
  let sessionCost = 0, sessionInput = 0, sessionOutput = 0, sessionCacheCreation = 0, sessionCacheRead = 0;
@@ -536,9 +692,9 @@ async function getOverviewData(range, projectFilter) {
536
692
  sessionOutput += m.outputTokens;
537
693
  sessionCacheCreation += m.cacheCreationTokens;
538
694
  sessionCacheRead += m.cacheReadTokens;
539
- const day = localDateStr(new Date(m.timestamp));
540
- dailyCosts[day] = (dailyCosts[day] || 0) + m.cost;
541
- if (m.model && !m.model.startsWith('<')) {
695
+ const k = bucketKey(new Date(m.timestamp));
696
+ addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
697
+ if (isRealModel(m.model)) {
542
698
  modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
543
699
  projModels.add(m.model);
544
700
  }
@@ -567,12 +723,15 @@ async function getOverviewData(range, projectFilter) {
567
723
  }
568
724
  }
569
725
 
570
- const dailyStart = new Date(cutoff);
571
- dailyStart.setHours(0, 0, 0, 0);
572
- const filledDaily = buildFilledDaily(dailyCosts, dailyStart, now);
726
+ const costSeries = buildCostSeries(bucketModelCosts, cutoff, windowEnd, bucket);
573
727
 
728
+ // The today slice is scoped to the window. A window that ends before today has no today bucket,
729
+ // and a 0 there reads as "nothing spent today" rather than "outside the selected window" — so it
730
+ // is reported as null and the card is dropped instead.
574
731
  const todayStr = localDateStr(now);
575
- const todayCost = dailyCosts[todayStr] || 0;
732
+ const todayCost = w.hasToday
733
+ ? costSeries.filter((p) => p.key.startsWith(todayStr)).reduce((s, p) => s + p.cost, 0)
734
+ : null;
576
735
 
577
736
  const totalInputAll = totalInput + totalCacheCreation + totalCacheRead;
578
737
  const cacheEfficiency = totalInputAll > 0 ? totalCacheRead / totalInputAll : 0;
@@ -587,7 +746,7 @@ async function getOverviewData(range, projectFilter) {
587
746
  totalInput, totalOutput, totalCacheCreation, totalCacheRead,
588
747
  cacheEfficiency,
589
748
  },
590
- daily: filledDaily,
749
+ costSeries: { bucket, points: costSeries },
591
750
  modelDistribution,
592
751
  projects: projectSummaries.sort((a, b) => b.totalCost - a.totalCost),
593
752
  };
@@ -597,14 +756,13 @@ async function getOverviewData(range, projectFilter) {
597
756
  }
598
757
 
599
758
  async function getProjectsData(range, projectFilter) {
600
- const cacheKey = `projects_${range || 'all'}_${projectFilter || 'all'}`;
601
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
759
+ const cacheKey = `projects_${rangeKey(range)}_${projectFilter || 'all'}`;
760
+ const cached = getCache(cacheKey);
761
+ if (cached !== undefined) return cached;
602
762
 
603
763
  const pricing = await fetchPricing();
604
- const now = new Date();
605
- const cutoff = rangeToCutoff(range, now);
606
- const projects = scanProjectDirs(cutoff, projectFilter);
607
- const cutoffStr = cutoff ? cutoff.toISOString() : null;
764
+ const w = resolveWindow(range);
765
+ const projects = scanProjectDirs(w.cutoff, projectFilter);
608
766
  const result = [];
609
767
 
610
768
  for (const [encodedPath, proj] of projects) {
@@ -613,16 +771,14 @@ async function getProjectsData(range, projectFilter) {
613
771
  const projModelCounts = {};
614
772
 
615
773
  for (const [, session] of sessions) {
616
- const msgs = cutoffStr
617
- ? session.messages.filter(m => m.timestamp >= cutoffStr)
618
- : session.messages;
774
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
619
775
  if (msgs.length === 0) continue;
620
776
 
621
777
  const cost = msgs.reduce((s, m) => s + m.cost, 0);
622
778
  totalCost += cost;
623
779
  sessionCount++;
624
780
  for (const m of msgs) {
625
- if (m.model && !m.model.startsWith('<')) {
781
+ if (isRealModel(m.model)) {
626
782
  projModelCounts[m.model] = (projModelCounts[m.model] || 0) + 1;
627
783
  }
628
784
  }
@@ -649,36 +805,33 @@ async function getProjectsData(range, projectFilter) {
649
805
  }
650
806
 
651
807
  async function getProjectSessionsData(encodedPath, range) {
652
- const cacheKey = `sessions_${encodedPath}_${range || 'all'}`;
653
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
808
+ const cacheKey = `sessions_${encodedPath}_${rangeKey(range)}`;
809
+ const cached = getCache(cacheKey);
810
+ if (cached !== undefined) return cached;
654
811
 
655
812
  const pricing = await fetchPricing();
656
- const now = new Date();
657
- const cutoff = rangeToCutoff(range, now);
658
- const projects = scanProjectDirs(cutoff);
813
+ const w = resolveWindow(range);
814
+ const projects = scanProjectDirs(w.cutoff);
659
815
  const proj = projects.get(encodedPath);
660
- if (!proj) return { sessions: [], daily: [], modelDistribution: [] };
816
+ const bucket = rangeBucket(range);
817
+ if (!proj) return { sessions: [], costSeries: { bucket, points: [] }, modelDistribution: [] };
661
818
 
662
819
  const sessions = await loadProjectData(proj.files, pricing);
663
- const cutoffStr = cutoff ? cutoff.toISOString() : null;
664
820
  const result = [];
665
- const dailyCosts = {};
821
+ const bucketKey = BUCKETS[bucket].key;
822
+ const bucketModelCosts = {};
666
823
  const modelCosts = {};
667
824
 
668
825
  for (const [, session] of sessions) {
669
- const msgs = cutoffStr
670
- ? session.messages.filter(m => m.timestamp >= cutoffStr)
671
- : session.messages;
826
+ const msgs = filterWindow(session.messages, w.cutoffStr, w.endStr);
672
827
  if (msgs.length === 0) continue;
673
828
 
674
- let cost = 0, input = 0, output = 0, cacheCreation = 0, cacheRead = 0;
829
+ const sum = summarizeMessages(msgs);
675
830
  const sessionModelCounts = {};
676
831
  for (const m of msgs) {
677
- cost += m.cost; input += m.inputTokens; output += m.outputTokens;
678
- cacheCreation += m.cacheCreationTokens; cacheRead += m.cacheReadTokens;
679
- const day = localDateStr(new Date(m.timestamp));
680
- dailyCosts[day] = (dailyCosts[day] || 0) + m.cost;
681
- if (m.model && !m.model.startsWith('<')) {
832
+ const k = bucketKey(new Date(m.timestamp));
833
+ addBucketModelCost(bucketModelCosts, k, m.model, m.cost);
834
+ if (isRealModel(m.model)) {
682
835
  modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
683
836
  sessionModelCounts[m.model] = (sessionModelCounts[m.model] || 0) + 1;
684
837
  }
@@ -691,13 +844,8 @@ async function getProjectSessionsData(encodedPath, range) {
691
844
  result.push({
692
845
  sessionId: session.sessionId,
693
846
  customTitle: session.customTitle,
694
- totalCost: cost,
695
- inputTokens: input,
696
- outputTokens: output,
697
- cacheCreationTokens: cacheCreation,
698
- cacheReadTokens: cacheRead,
699
- totalTokens: input + output + cacheCreation + cacheRead,
700
- messageCount: msgs.length,
847
+ ...sum,
848
+ totalTokens: sum.inputTokens + sum.outputTokens + sum.cacheCreationTokens + sum.cacheReadTokens,
701
849
  models: [...session.models],
702
850
  primaryModel,
703
851
  firstPrompt: session.firstPrompt,
@@ -707,28 +855,49 @@ async function getProjectSessionsData(encodedPath, range) {
707
855
  });
708
856
  }
709
857
 
710
- let dailyStart;
711
- if (cutoff) {
712
- dailyStart = new Date(cutoff);
713
- dailyStart.setHours(0, 0, 0, 0);
714
- } else {
715
- const dates = Object.keys(dailyCosts).sort();
716
- dailyStart = dates.length ? new Date(dates[0] + 'T00:00:00') : now;
858
+ // No range means "everything", so the series starts at the first bucket that has cost.
859
+ let seriesStart = w.cutoff;
860
+ if (!seriesStart) {
861
+ const keys = Object.keys(bucketModelCosts).sort();
862
+ seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : w.now;
717
863
  }
718
- const dailyEnd = now;
719
- const filledDaily = buildFilledDaily(dailyCosts, dailyStart, dailyEnd);
864
+ const costSeries = buildCostSeries(bucketModelCosts, seriesStart, w.end, bucket);
720
865
 
721
866
  const modelDistribution = buildModelDistribution(modelCosts);
722
867
 
723
868
  const sorted = result.sort((a, b) => (b.lastTimestamp || '').localeCompare(a.lastTimestamp || ''));
724
- const response = { sessions: sorted, daily: filledDaily, modelDistribution };
869
+ const response = {
870
+ sessions: sorted,
871
+ costSeries: { bucket, points: costSeries },
872
+ modelDistribution,
873
+ };
725
874
  setCache(cacheKey, response);
726
875
  return response;
727
876
  }
728
877
 
878
+ // The detail view is always the whole session, unlike every other view. `inRange`/`today` carry
879
+ // the slices the UI needs to reconcile itself with the range-scoped session row that linked here,
880
+ // instead of silently disagreeing with it. They are derived outside the cache so switching ranges
881
+ // does not re-parse the session's JSONL.
882
+ function withSessionSlices(base, range) {
883
+ const w = resolveWindow(range);
884
+ const slice = (fromStr) => summarizeMessages(filterWindow(base.messages, fromStr, w.endStr));
885
+ const inRange = w.cutoffStr ? slice(w.cutoffStr) : null;
886
+ const todayStart = rangeToCutoff('today', w.now);
887
+ // Scoped to the window like the overview's today card: a window ending in the past has no
888
+ // today to report, and a zeroed slice would read as "nothing spent today".
889
+ return {
890
+ ...base,
891
+ range,
892
+ inRange,
893
+ today: isTodayRange(range, w.now) ? inRange : w.hasToday ? slice(todayStart.toISOString()) : null,
894
+ };
895
+ }
896
+
729
897
  async function getSessionDetailData(sessionId) {
730
898
  const cacheKey = `detail_${sessionId}`;
731
- if (isCacheValid(cacheKey)) return dataCache[cacheKey];
899
+ const cached = getCache(cacheKey);
900
+ if (cached !== undefined) return cached;
732
901
 
733
902
  const pricing = await fetchPricing();
734
903
  const projects = scanProjectDirs();
@@ -797,10 +966,36 @@ app.get('/hub-config', (_req, res) => {
797
966
 
798
967
  function parseRange(raw, fallback = null) {
799
968
  if (raw === 'today') return 'today';
969
+ if (raw === '24h') return '24h';
800
970
  const n = parseInt(raw, 10);
801
971
  return Number.isFinite(n) ? n : fallback;
802
972
  }
803
973
 
974
+ const DATE_PARAM = /^\d{4}-\d{2}-\d{2}$/;
975
+
976
+ // A local calendar date, normalized so it can safely reach a cache key — same discipline as
977
+ // parseProject. Returns undefined for absent, null for malformed.
978
+ function parseDateParam(raw) {
979
+ if (raw === undefined || raw === '') return undefined;
980
+ if (typeof raw !== 'string' || !DATE_PARAM.test(raw)) return null;
981
+ return localDateStr(localDayStart(raw)) === raw ? raw : null;
982
+ }
983
+
984
+ // A custom window, if the request asked for one: `from`/`to` take precedence over `range`.
985
+ // Reversed pairs are ordered and both ends clamped to today — there is no cost data ahead of now,
986
+ // and an inverted window would otherwise render as an unexplained empty chart.
987
+ // Returns undefined when no window was requested, null when one was but is malformed.
988
+ function parseCustomRange(query) {
989
+ const from = parseDateParam(query.from);
990
+ const to = parseDateParam(query.to);
991
+ if (from === null || to === null) return null;
992
+ if (from === undefined && to === undefined) return undefined;
993
+ if (from === undefined || to === undefined) return null;
994
+ const today = localDateStr(new Date());
995
+ const [lo, hi] = from <= to ? [from, to] : [to, from];
996
+ return { from: lo > today ? today : lo, to: hi > today ? today : hi };
997
+ }
998
+
804
999
  // Encoded project-dir name (the hub sends it pre-encoded — see encodeProjectPath in the hub's
805
1000
  // public/app.js; this regex must stay a superset of that transform's output). Only ever used as
806
1001
  // a Map key, never joined into a path — the regex exists to keep unbounded strings out of the
@@ -813,12 +1008,23 @@ function parseProject(raw) {
813
1008
  return raw;
814
1009
  }
815
1010
 
816
- app.get('/api/overview', async (req, res) => {
1011
+ // Resolves a request's range onto req.range: a custom from/to window wins over `range`. A resolved
1012
+ // range cannot signal malformed input with null (null *is* the all-time range), so the rejection
1013
+ // happens here, ahead of the handler, instead of being threaded back to it as a sentinel value.
1014
+ // Only the range — a route that also scopes by project keeps its own parseProject guard, because
1015
+ // the routes that don't call parseProject must go on ignoring a malformed `project`.
1016
+ const withRange = (fallback = null) => (req, res, next) => {
1017
+ const custom = parseCustomRange(req.query);
1018
+ if (custom === null) return res.status(400).json({ error: 'Invalid date range' });
1019
+ req.range = custom || parseRange(req.query.range, fallback);
1020
+ next();
1021
+ };
1022
+
1023
+ app.get('/api/overview', withRange(30), async (req, res) => {
817
1024
  try {
818
- const range = parseRange(req.query.range, 30);
819
1025
  const project = parseProject(req.query.project);
820
1026
  if (project === null) return res.status(400).json({ error: 'Invalid project' });
821
- const data = await getOverviewData(range, project);
1027
+ const data = await getOverviewData(req.range, project);
822
1028
  res.json(data);
823
1029
  } catch (err) {
824
1030
  console.error('[API] overview error:', err);
@@ -826,12 +1032,11 @@ app.get('/api/overview', async (req, res) => {
826
1032
  }
827
1033
  });
828
1034
 
829
- app.get('/api/projects', async (req, res) => {
1035
+ app.get('/api/projects', withRange(), async (req, res) => {
830
1036
  try {
831
- const range = parseRange(req.query.range);
832
1037
  const project = parseProject(req.query.project);
833
1038
  if (project === null) return res.status(400).json({ error: 'Invalid project' });
834
- const data = await getProjectsData(range, project);
1039
+ const data = await getProjectsData(req.range, project);
835
1040
  res.json(data);
836
1041
  } catch (err) {
837
1042
  console.error('[API] projects error:', err);
@@ -839,10 +1044,9 @@ app.get('/api/projects', async (req, res) => {
839
1044
  }
840
1045
  });
841
1046
 
842
- app.get('/api/projects/:path/sessions', async (req, res) => {
1047
+ app.get('/api/projects/:path/sessions', withRange(), async (req, res) => {
843
1048
  try {
844
- const range = parseRange(req.query.range);
845
- const data = await getProjectSessionsData(req.params.path, range);
1049
+ const data = await getProjectSessionsData(req.params.path, req.range);
846
1050
  res.json(data);
847
1051
  } catch (err) {
848
1052
  console.error('[API] sessions error:', err);
@@ -850,11 +1054,11 @@ app.get('/api/projects/:path/sessions', async (req, res) => {
850
1054
  }
851
1055
  });
852
1056
 
853
- app.get('/api/sessions/:id', async (req, res) => {
1057
+ app.get('/api/sessions/:id', withRange(), async (req, res) => {
854
1058
  try {
855
- const data = await getSessionDetailData(req.params.id);
856
- if (!data) return res.status(404).json({ error: 'Session not found' });
857
- res.json(data);
1059
+ const base = await getSessionDetailData(req.params.id);
1060
+ if (!base) return res.status(404).json({ error: 'Session not found' });
1061
+ res.json(withSessionSlices(base, req.range));
858
1062
  } catch (err) {
859
1063
  console.error('[API] session detail error:', err);
860
1064
  res.status(500).json({ error: 'Failed to load session detail' });