claude-code-cost 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/public/app.js +55 -26
- package/public/style.css +26 -0
- package/server.js +109 -49
package/package.json
CHANGED
package/public/app.js
CHANGED
|
@@ -4,7 +4,7 @@ let currentView = 'overview';
|
|
|
4
4
|
let overviewData = null;
|
|
5
5
|
let projectsData = null;
|
|
6
6
|
let sessionsData = null;
|
|
7
|
-
let
|
|
7
|
+
let sessionsCostSeries = null;
|
|
8
8
|
let sessionsModelDistribution = null;
|
|
9
9
|
let sessionDetailData = null;
|
|
10
10
|
let currentProjectPath = null;
|
|
@@ -91,9 +91,17 @@ function timeAgo(ts) {
|
|
|
91
91
|
return new Date(ts).toLocaleDateString();
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
94
|
+
// Bucket keys arrive as YYYY-MM-DD (day) or YYYY-MM-DDTHH (hour), both in the server's local
|
|
95
|
+
// time with no zone suffix.
|
|
96
|
+
function bucketLabel(key, bucket) {
|
|
97
|
+
if (bucket === 'hour') {
|
|
98
|
+
return new Date(`${key}:00:00`).toLocaleTimeString(undefined, { hour: 'numeric' });
|
|
99
|
+
}
|
|
100
|
+
return new Date(`${key}T00:00:00`).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function costSeriesTitle(series) {
|
|
104
|
+
return series?.bucket === 'hour' ? 'Hourly Cost' : 'Daily Cost';
|
|
97
105
|
}
|
|
98
106
|
|
|
99
107
|
function shortModel(model) {
|
|
@@ -218,6 +226,10 @@ function rangeLabel(r) {
|
|
|
218
226
|
return r === 'today' ? 'today' : `${r} days`;
|
|
219
227
|
}
|
|
220
228
|
|
|
229
|
+
function rangeScopeLabel(r) {
|
|
230
|
+
return r === 'today' ? rangeLabel(r) : `last ${rangeLabel(r)}`;
|
|
231
|
+
}
|
|
232
|
+
|
|
221
233
|
function loadSort() {
|
|
222
234
|
for (const view of Object.keys(DEFAULT_SORT)) {
|
|
223
235
|
const raw = localStorage.getItem(`cc-cost:sort:${view}`);
|
|
@@ -255,7 +267,7 @@ function updateUrl() {
|
|
|
255
267
|
// #region FETCH
|
|
256
268
|
|
|
257
269
|
const BROWSER_CACHE_TTL = 5 * 60 * 1000; // 5 min
|
|
258
|
-
const CACHE_VERSION =
|
|
270
|
+
const CACHE_VERSION = 4;
|
|
259
271
|
let forceRefresh = false;
|
|
260
272
|
// Age of the data on screen, for the auto-refresh staleness check. A cache hit carries its own
|
|
261
273
|
// timestamp forward, so a reload with a warm cache doesn't look freshly fetched.
|
|
@@ -368,12 +380,12 @@ async function fetchProjects() {
|
|
|
368
380
|
async function fetchSessions(encodedPath) {
|
|
369
381
|
const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?range=${dateRange}`, true);
|
|
370
382
|
sessionsData = data.sessions;
|
|
371
|
-
|
|
383
|
+
sessionsCostSeries = data.costSeries;
|
|
372
384
|
sessionsModelDistribution = data.modelDistribution || [];
|
|
373
385
|
}
|
|
374
386
|
|
|
375
387
|
async function fetchSessionDetail(sessionId) {
|
|
376
|
-
sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}`, true);
|
|
388
|
+
sessionDetailData = await fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}?range=${dateRange}`, true);
|
|
377
389
|
// Populate project context when opening via deep link (no project in URL)
|
|
378
390
|
if (sessionDetailData && !currentProjectPath) {
|
|
379
391
|
currentProjectPath = sessionDetailData.encodedProjectPath;
|
|
@@ -400,7 +412,7 @@ function renderOverview() {
|
|
|
400
412
|
if (lastRenderHash.overview === h) return;
|
|
401
413
|
lastRenderHash.overview = h;
|
|
402
414
|
|
|
403
|
-
const
|
|
415
|
+
const costSeries = overviewData.costSeries;
|
|
404
416
|
const models = overviewData.modelDistribution || [];
|
|
405
417
|
|
|
406
418
|
// Return before any chart call so no canvas is touched — there are none in this markup.
|
|
@@ -451,8 +463,8 @@ function renderOverview() {
|
|
|
451
463
|
|
|
452
464
|
<div class="charts-row">
|
|
453
465
|
<div class="chart-box">
|
|
454
|
-
<div class="chart-title"
|
|
455
|
-
<canvas id="
|
|
466
|
+
<div class="chart-title">${costSeriesTitle(costSeries)}</div>
|
|
467
|
+
<canvas id="costChart"></canvas>
|
|
456
468
|
</div>
|
|
457
469
|
<div class="chart-box">
|
|
458
470
|
<div class="chart-title">Cost by Model</div>
|
|
@@ -492,7 +504,7 @@ function renderOverview() {
|
|
|
492
504
|
|
|
493
505
|
// Render charts after DOM is ready
|
|
494
506
|
requestAnimationFrame(() => {
|
|
495
|
-
|
|
507
|
+
renderCostChart(costSeries);
|
|
496
508
|
renderModelChart(models);
|
|
497
509
|
});
|
|
498
510
|
}
|
|
@@ -572,7 +584,7 @@ function renderSessions() {
|
|
|
572
584
|
return;
|
|
573
585
|
}
|
|
574
586
|
|
|
575
|
-
const h = JSON.stringify({ sessionsData,
|
|
587
|
+
const h = JSON.stringify({ sessionsData, sessionsCostSeries, sessionsModelDistribution, sort: viewSort.sessions });
|
|
576
588
|
if (lastRenderHash.sessions === h) return;
|
|
577
589
|
lastRenderHash.sessions = h;
|
|
578
590
|
|
|
@@ -597,8 +609,8 @@ function renderSessions() {
|
|
|
597
609
|
</div>
|
|
598
610
|
<div class="charts-row" style="grid-template-columns:3fr 2fr auto">
|
|
599
611
|
<div class="chart-box">
|
|
600
|
-
<div class="chart-title"
|
|
601
|
-
<canvas id="
|
|
612
|
+
<div class="chart-title">${costSeriesTitle(sessionsCostSeries)}</div>
|
|
613
|
+
<canvas id="sessionsCostChart"></canvas>
|
|
602
614
|
</div>
|
|
603
615
|
<div class="chart-box">
|
|
604
616
|
<div class="chart-title">Cost by Model</div>
|
|
@@ -642,7 +654,7 @@ function renderSessions() {
|
|
|
642
654
|
</div>`;
|
|
643
655
|
|
|
644
656
|
requestAnimationFrame(() => {
|
|
645
|
-
|
|
657
|
+
renderCostChart(sessionsCostSeries, 'sessionsCostChart', 'sessionsCost');
|
|
646
658
|
renderModelChart(sessionsModelDistribution || [], 'sessionsModelChart', 'sessionsModel');
|
|
647
659
|
});
|
|
648
660
|
}
|
|
@@ -679,7 +691,7 @@ function renderDetail() {
|
|
|
679
691
|
<div class="detail-header">
|
|
680
692
|
<div class="detail-stat">
|
|
681
693
|
<div class="detail-label">Total Cost</div>
|
|
682
|
-
<div class="detail-value cost">${formatCost(d.totalCost)}</div>
|
|
694
|
+
<div class="detail-value cost">${formatCost(d.totalCost)}<span class="detail-label detail-scope">all time</span></div>
|
|
683
695
|
</div>
|
|
684
696
|
<div class="detail-stat">
|
|
685
697
|
<div class="detail-label">Input</div>
|
|
@@ -699,17 +711,16 @@ function renderDetail() {
|
|
|
699
711
|
</div>
|
|
700
712
|
<div class="detail-stat">
|
|
701
713
|
<div class="detail-label">Messages</div>
|
|
702
|
-
<div class="detail-value">${d.messages.length}</div>
|
|
714
|
+
<div class="detail-value">${d.messages.length}<span class="detail-label detail-scope">all time</span></div>
|
|
703
715
|
</div>
|
|
704
716
|
<div class="detail-stat">
|
|
705
717
|
<div class="detail-label">Models</div>
|
|
706
|
-
<div class="detail-value">${d.models
|
|
707
|
-
.map((m) => shortModel(m))
|
|
708
|
-
.filter(Boolean)
|
|
709
|
-
.join(', ')}</div>
|
|
718
|
+
<div class="detail-value">${esc(d.models.map((m) => shortModel(m)).join(', '))}</div>
|
|
710
719
|
</div>
|
|
711
720
|
</div>
|
|
712
721
|
|
|
722
|
+
${detailRangeNote(d)}
|
|
723
|
+
|
|
713
724
|
<div class="charts-row" style="margin-bottom:20px">
|
|
714
725
|
<div class="chart-box">
|
|
715
726
|
<div class="chart-title">Cumulative Cost</div>
|
|
@@ -747,6 +758,23 @@ function renderDetail() {
|
|
|
747
758
|
});
|
|
748
759
|
}
|
|
749
760
|
|
|
761
|
+
// The session row that links here is scoped to the active range, so a session older than the
|
|
762
|
+
// range would otherwise show larger numbers here with no explanation.
|
|
763
|
+
function detailRangeNote(d) {
|
|
764
|
+
const all = d.messages.length;
|
|
765
|
+
const slice = (label, s) =>
|
|
766
|
+
`<span class="scope-label">${esc(label)}</span> <strong>${formatCost(s.totalCost)}</strong> / ${s.messageCount} msg`;
|
|
767
|
+
// A slice worth showing is a real subset: neither empty nor the whole session.
|
|
768
|
+
const worthShowing = (s) => s && s.messageCount > 0 && s.messageCount < all;
|
|
769
|
+
const parts = [];
|
|
770
|
+
if (worthShowing(d.inRange)) parts.push(slice(rangeScopeLabel(d.range), d.inRange));
|
|
771
|
+
if (worthShowing(d.today) && d.today.messageCount !== d.inRange?.messageCount) {
|
|
772
|
+
parts.push(slice('today', d.today));
|
|
773
|
+
}
|
|
774
|
+
if (!parts.length) return '';
|
|
775
|
+
return `<div class="detail-range-note">Totals above are all-time · ${parts.join(' · ')}</div>`;
|
|
776
|
+
}
|
|
777
|
+
|
|
750
778
|
function buildMessageRowsWithSubagents(d) {
|
|
751
779
|
return [...d.messages]
|
|
752
780
|
.reverse()
|
|
@@ -838,9 +866,10 @@ function destroyChart(id) {
|
|
|
838
866
|
}
|
|
839
867
|
}
|
|
840
868
|
|
|
841
|
-
function
|
|
869
|
+
function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost') {
|
|
870
|
+
const points = series?.points;
|
|
842
871
|
const canvas = document.getElementById(canvasId);
|
|
843
|
-
if (!canvas || !
|
|
872
|
+
if (!canvas || !points?.length) return;
|
|
844
873
|
destroyChart(chartKey);
|
|
845
874
|
|
|
846
875
|
const c = getChartColors();
|
|
@@ -849,11 +878,11 @@ function renderDailyChart(daily, canvasId = 'dailyChart', chartKey = 'daily') {
|
|
|
849
878
|
charts[chartKey] = new Chart(canvas, {
|
|
850
879
|
type: 'bar',
|
|
851
880
|
data: {
|
|
852
|
-
labels:
|
|
881
|
+
labels: points.map((p) => bucketLabel(p.key, series.bucket)),
|
|
853
882
|
datasets: [
|
|
854
883
|
{
|
|
855
|
-
label:
|
|
856
|
-
data:
|
|
884
|
+
label: costSeriesTitle(series),
|
|
885
|
+
data: points.map((p) => p.cost),
|
|
857
886
|
backgroundColor: c.chartFill,
|
|
858
887
|
borderColor: c.accent,
|
|
859
888
|
borderWidth: 1.5,
|
package/public/style.css
CHANGED
|
@@ -639,6 +639,32 @@ body {
|
|
|
639
639
|
color: var(--accent-text);
|
|
640
640
|
}
|
|
641
641
|
|
|
642
|
+
/* Rides on .detail-label for the small-muted-caption look; only the offset differs. */
|
|
643
|
+
.detail-stat .detail-scope {
|
|
644
|
+
margin-left: 5px;
|
|
645
|
+
font-weight: 400;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
.detail-header:has(+ .detail-range-note) {
|
|
649
|
+
margin-bottom: 8px;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
.detail-range-note {
|
|
653
|
+
margin: 0 0 18px;
|
|
654
|
+
font-size: 10px;
|
|
655
|
+
color: var(--text-muted);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
.detail-range-note .scope-label {
|
|
659
|
+
text-transform: uppercase;
|
|
660
|
+
letter-spacing: 0.03em;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
.detail-range-note strong {
|
|
664
|
+
color: var(--text-secondary);
|
|
665
|
+
font-weight: 500;
|
|
666
|
+
}
|
|
667
|
+
|
|
642
668
|
.messages-table {
|
|
643
669
|
width: 100%;
|
|
644
670
|
border-collapse: collapse;
|
package/server.js
CHANGED
|
@@ -238,20 +238,48 @@ function localDateStr(d) {
|
|
|
238
238
|
return `${y}-${m}-${day}`;
|
|
239
239
|
}
|
|
240
240
|
|
|
241
|
-
function
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
241
|
+
function localHourStr(d) {
|
|
242
|
+
return `${localDateStr(d)}T${String(d.getHours()).padStart(2, '0')}`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Cost is bucketed by one of these; the key doubles as the aggregation key and the wire label.
|
|
246
|
+
// An hour key extends the day key (YYYY-MM-DD -> YYYY-MM-DDTHH), so a startsWith test on a day
|
|
247
|
+
// string matches either granularity.
|
|
248
|
+
const BUCKETS = {
|
|
249
|
+
day: {
|
|
250
|
+
key: localDateStr,
|
|
251
|
+
floor: (d) => d.setHours(0, 0, 0, 0),
|
|
252
|
+
next: (d) => d.setDate(d.getDate() + 1),
|
|
253
|
+
},
|
|
254
|
+
hour: {
|
|
255
|
+
key: localHourStr,
|
|
256
|
+
floor: (d) => d.setMinutes(0, 0, 0),
|
|
257
|
+
next: (d) => d.setHours(d.getHours() + 1),
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// A one-day window collapses the daily chart into a single bar, so those ranges bucket by hour.
|
|
262
|
+
function rangeBucket(range) {
|
|
263
|
+
return range === 'today' || range === 1 ? 'hour' : 'day';
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Gap-filled so empty buckets stay visible in the chart.
|
|
267
|
+
function buildCostSeries(costs, start, end, bucket) {
|
|
268
|
+
const b = BUCKETS[bucket];
|
|
269
|
+
const points = [];
|
|
270
|
+
if (Object.keys(costs).length === 0) return points;
|
|
271
|
+
const d = new Date(start);
|
|
272
|
+
b.floor(d);
|
|
273
|
+
for (; d <= end; b.next(d)) {
|
|
274
|
+
const k = b.key(d);
|
|
275
|
+
points.push({ key: k, cost: costs[k] || 0 });
|
|
248
276
|
}
|
|
249
|
-
return
|
|
277
|
+
return points;
|
|
250
278
|
}
|
|
251
279
|
|
|
252
280
|
function buildModelDistribution(modelCosts) {
|
|
253
281
|
return Object.entries(modelCosts)
|
|
254
|
-
.filter(([model, cost]) => cost > 0 &&
|
|
282
|
+
.filter(([model, cost]) => cost > 0 && isRealModel(model))
|
|
255
283
|
.map(([model, cost]) => ({ model, cost }))
|
|
256
284
|
.sort((a, b) => b.cost - a.cost);
|
|
257
285
|
}
|
|
@@ -339,6 +367,11 @@ function scanSubagentDir(sessionDir) {
|
|
|
339
367
|
return result;
|
|
340
368
|
}
|
|
341
369
|
|
|
370
|
+
// `<synthetic>` and friends are Claude Code bookkeeping entries, not models the user chose.
|
|
371
|
+
function isRealModel(model) {
|
|
372
|
+
return !!model && !model.startsWith('<');
|
|
373
|
+
}
|
|
374
|
+
|
|
342
375
|
function mostFrequentModel(counts) {
|
|
343
376
|
return Object.entries(counts).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';
|
|
344
377
|
}
|
|
@@ -433,7 +466,7 @@ async function loadProjectData(files, pricing) {
|
|
|
433
466
|
session.outputTokens += usage.output_tokens || 0;
|
|
434
467
|
session.cacheCreationTokens += (usage.cache_creation_input_tokens || 0);
|
|
435
468
|
session.cacheReadTokens += (usage.cache_read_input_tokens || 0);
|
|
436
|
-
session.models.add(model);
|
|
469
|
+
if (isRealModel(model)) session.models.add(model);
|
|
437
470
|
|
|
438
471
|
if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
|
|
439
472
|
if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
|
|
@@ -472,7 +505,7 @@ async function loadProjectData(files, pricing) {
|
|
|
472
505
|
session.outputTokens += sa.outputTokens;
|
|
473
506
|
session.cacheCreationTokens += sa.cacheCreationTokens;
|
|
474
507
|
session.cacheReadTokens += sa.cacheReadTokens;
|
|
475
|
-
for (const m of sa.models) session.models.add(m);
|
|
508
|
+
for (const m of sa.models) if (isRealModel(m)) session.models.add(m);
|
|
476
509
|
session.messages.push({
|
|
477
510
|
timestamp: sa.firstTimestamp || session.firstTimestamp,
|
|
478
511
|
model: sa.models[0] || 'unknown',
|
|
@@ -503,6 +536,18 @@ function rangeToCutoff(range, now) {
|
|
|
503
536
|
return c;
|
|
504
537
|
}
|
|
505
538
|
|
|
539
|
+
function summarizeMessages(msgs) {
|
|
540
|
+
const sum = { messageCount: msgs.length, totalCost: 0, inputTokens: 0, outputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0 };
|
|
541
|
+
for (const m of msgs) {
|
|
542
|
+
sum.totalCost += m.cost;
|
|
543
|
+
sum.inputTokens += m.inputTokens;
|
|
544
|
+
sum.outputTokens += m.outputTokens;
|
|
545
|
+
sum.cacheCreationTokens += m.cacheCreationTokens;
|
|
546
|
+
sum.cacheReadTokens += m.cacheReadTokens;
|
|
547
|
+
}
|
|
548
|
+
return sum;
|
|
549
|
+
}
|
|
550
|
+
|
|
506
551
|
async function getOverviewData(range, projectFilter) {
|
|
507
552
|
const cacheKey = `overview_${range}_${projectFilter || 'all'}`;
|
|
508
553
|
if (isCacheValid(cacheKey)) return dataCache[cacheKey];
|
|
@@ -515,7 +560,9 @@ async function getOverviewData(range, projectFilter) {
|
|
|
515
560
|
|
|
516
561
|
let totalCost = 0, totalSessions = 0;
|
|
517
562
|
let totalInput = 0, totalOutput = 0, totalCacheCreation = 0, totalCacheRead = 0;
|
|
518
|
-
const
|
|
563
|
+
const bucket = rangeBucket(range);
|
|
564
|
+
const bucketKey = BUCKETS[bucket].key;
|
|
565
|
+
const bucketCosts = {};
|
|
519
566
|
const modelCosts = {};
|
|
520
567
|
const projectSummaries = [];
|
|
521
568
|
|
|
@@ -536,9 +583,9 @@ async function getOverviewData(range, projectFilter) {
|
|
|
536
583
|
sessionOutput += m.outputTokens;
|
|
537
584
|
sessionCacheCreation += m.cacheCreationTokens;
|
|
538
585
|
sessionCacheRead += m.cacheReadTokens;
|
|
539
|
-
const
|
|
540
|
-
|
|
541
|
-
if (m.model
|
|
586
|
+
const k = bucketKey(new Date(m.timestamp));
|
|
587
|
+
bucketCosts[k] = (bucketCosts[k] || 0) + m.cost;
|
|
588
|
+
if (isRealModel(m.model)) {
|
|
542
589
|
modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
|
|
543
590
|
projModels.add(m.model);
|
|
544
591
|
}
|
|
@@ -567,12 +614,12 @@ async function getOverviewData(range, projectFilter) {
|
|
|
567
614
|
}
|
|
568
615
|
}
|
|
569
616
|
|
|
570
|
-
const
|
|
571
|
-
dailyStart.setHours(0, 0, 0, 0);
|
|
572
|
-
const filledDaily = buildFilledDaily(dailyCosts, dailyStart, now);
|
|
617
|
+
const costSeries = buildCostSeries(bucketCosts, cutoff, now, bucket);
|
|
573
618
|
|
|
574
619
|
const todayStr = localDateStr(now);
|
|
575
|
-
const todayCost =
|
|
620
|
+
const todayCost = Object.entries(bucketCosts)
|
|
621
|
+
.filter(([k]) => k.startsWith(todayStr))
|
|
622
|
+
.reduce((s, [, c]) => s + c, 0);
|
|
576
623
|
|
|
577
624
|
const totalInputAll = totalInput + totalCacheCreation + totalCacheRead;
|
|
578
625
|
const cacheEfficiency = totalInputAll > 0 ? totalCacheRead / totalInputAll : 0;
|
|
@@ -587,7 +634,7 @@ async function getOverviewData(range, projectFilter) {
|
|
|
587
634
|
totalInput, totalOutput, totalCacheCreation, totalCacheRead,
|
|
588
635
|
cacheEfficiency,
|
|
589
636
|
},
|
|
590
|
-
|
|
637
|
+
costSeries: { bucket, points: costSeries },
|
|
591
638
|
modelDistribution,
|
|
592
639
|
projects: projectSummaries.sort((a, b) => b.totalCost - a.totalCost),
|
|
593
640
|
};
|
|
@@ -622,7 +669,7 @@ async function getProjectsData(range, projectFilter) {
|
|
|
622
669
|
totalCost += cost;
|
|
623
670
|
sessionCount++;
|
|
624
671
|
for (const m of msgs) {
|
|
625
|
-
if (m.model
|
|
672
|
+
if (isRealModel(m.model)) {
|
|
626
673
|
projModelCounts[m.model] = (projModelCounts[m.model] || 0) + 1;
|
|
627
674
|
}
|
|
628
675
|
}
|
|
@@ -657,12 +704,14 @@ async function getProjectSessionsData(encodedPath, range) {
|
|
|
657
704
|
const cutoff = rangeToCutoff(range, now);
|
|
658
705
|
const projects = scanProjectDirs(cutoff);
|
|
659
706
|
const proj = projects.get(encodedPath);
|
|
660
|
-
|
|
707
|
+
const bucket = rangeBucket(range);
|
|
708
|
+
if (!proj) return { sessions: [], costSeries: { bucket, points: [] }, modelDistribution: [] };
|
|
661
709
|
|
|
662
710
|
const sessions = await loadProjectData(proj.files, pricing);
|
|
663
711
|
const cutoffStr = cutoff ? cutoff.toISOString() : null;
|
|
664
712
|
const result = [];
|
|
665
|
-
const
|
|
713
|
+
const bucketKey = BUCKETS[bucket].key;
|
|
714
|
+
const bucketCosts = {};
|
|
666
715
|
const modelCosts = {};
|
|
667
716
|
|
|
668
717
|
for (const [, session] of sessions) {
|
|
@@ -671,14 +720,12 @@ async function getProjectSessionsData(encodedPath, range) {
|
|
|
671
720
|
: session.messages;
|
|
672
721
|
if (msgs.length === 0) continue;
|
|
673
722
|
|
|
674
|
-
|
|
723
|
+
const sum = summarizeMessages(msgs);
|
|
675
724
|
const sessionModelCounts = {};
|
|
676
725
|
for (const m of msgs) {
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
dailyCosts[day] = (dailyCosts[day] || 0) + m.cost;
|
|
681
|
-
if (m.model && !m.model.startsWith('<')) {
|
|
726
|
+
const k = bucketKey(new Date(m.timestamp));
|
|
727
|
+
bucketCosts[k] = (bucketCosts[k] || 0) + m.cost;
|
|
728
|
+
if (isRealModel(m.model)) {
|
|
682
729
|
modelCosts[m.model] = (modelCosts[m.model] || 0) + m.cost;
|
|
683
730
|
sessionModelCounts[m.model] = (sessionModelCounts[m.model] || 0) + 1;
|
|
684
731
|
}
|
|
@@ -691,13 +738,8 @@ async function getProjectSessionsData(encodedPath, range) {
|
|
|
691
738
|
result.push({
|
|
692
739
|
sessionId: session.sessionId,
|
|
693
740
|
customTitle: session.customTitle,
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
outputTokens: output,
|
|
697
|
-
cacheCreationTokens: cacheCreation,
|
|
698
|
-
cacheReadTokens: cacheRead,
|
|
699
|
-
totalTokens: input + output + cacheCreation + cacheRead,
|
|
700
|
-
messageCount: msgs.length,
|
|
741
|
+
...sum,
|
|
742
|
+
totalTokens: sum.inputTokens + sum.outputTokens + sum.cacheCreationTokens + sum.cacheReadTokens,
|
|
701
743
|
models: [...session.models],
|
|
702
744
|
primaryModel,
|
|
703
745
|
firstPrompt: session.firstPrompt,
|
|
@@ -707,25 +749,43 @@ async function getProjectSessionsData(encodedPath, range) {
|
|
|
707
749
|
});
|
|
708
750
|
}
|
|
709
751
|
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
const dates = Object.keys(dailyCosts).sort();
|
|
716
|
-
dailyStart = dates.length ? new Date(dates[0] + 'T00:00:00') : now;
|
|
752
|
+
// No range means "everything", so the series starts at the first bucket that has cost.
|
|
753
|
+
let seriesStart = cutoff;
|
|
754
|
+
if (!seriesStart) {
|
|
755
|
+
const keys = Object.keys(bucketCosts).sort();
|
|
756
|
+
seriesStart = keys.length ? new Date(`${keys[0]}T00:00:00`) : now;
|
|
717
757
|
}
|
|
718
|
-
const
|
|
719
|
-
const filledDaily = buildFilledDaily(dailyCosts, dailyStart, dailyEnd);
|
|
758
|
+
const costSeries = buildCostSeries(bucketCosts, seriesStart, now, bucket);
|
|
720
759
|
|
|
721
760
|
const modelDistribution = buildModelDistribution(modelCosts);
|
|
722
761
|
|
|
723
762
|
const sorted = result.sort((a, b) => (b.lastTimestamp || '').localeCompare(a.lastTimestamp || ''));
|
|
724
|
-
const response = {
|
|
763
|
+
const response = {
|
|
764
|
+
sessions: sorted,
|
|
765
|
+
costSeries: { bucket, points: costSeries },
|
|
766
|
+
modelDistribution,
|
|
767
|
+
};
|
|
725
768
|
setCache(cacheKey, response);
|
|
726
769
|
return response;
|
|
727
770
|
}
|
|
728
771
|
|
|
772
|
+
// The detail view is always the whole session, unlike every other view. `inRange`/`today` carry
|
|
773
|
+
// the slices the UI needs to reconcile itself with the range-scoped session row that linked here,
|
|
774
|
+
// instead of silently disagreeing with it. They are derived outside the cache so switching ranges
|
|
775
|
+
// does not re-parse the session's JSONL.
|
|
776
|
+
function withSessionSlices(base, range) {
|
|
777
|
+
const now = new Date();
|
|
778
|
+
const cutoff = rangeToCutoff(range, now);
|
|
779
|
+
const sliceFrom = (from) => summarizeMessages(base.messages.filter(m => m.timestamp >= from));
|
|
780
|
+
const inRange = cutoff ? sliceFrom(cutoff.toISOString()) : null;
|
|
781
|
+
return {
|
|
782
|
+
...base,
|
|
783
|
+
range,
|
|
784
|
+
inRange,
|
|
785
|
+
today: range === 'today' ? inRange : sliceFrom(rangeToCutoff('today', now).toISOString()),
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
|
|
729
789
|
async function getSessionDetailData(sessionId) {
|
|
730
790
|
const cacheKey = `detail_${sessionId}`;
|
|
731
791
|
if (isCacheValid(cacheKey)) return dataCache[cacheKey];
|
|
@@ -852,9 +912,9 @@ app.get('/api/projects/:path/sessions', async (req, res) => {
|
|
|
852
912
|
|
|
853
913
|
app.get('/api/sessions/:id', async (req, res) => {
|
|
854
914
|
try {
|
|
855
|
-
const
|
|
856
|
-
if (!
|
|
857
|
-
res.json(
|
|
915
|
+
const base = await getSessionDetailData(req.params.id);
|
|
916
|
+
if (!base) return res.status(404).json({ error: 'Session not found' });
|
|
917
|
+
res.json(withSessionSlices(base, parseRange(req.query.range)));
|
|
858
918
|
} catch (err) {
|
|
859
919
|
console.error('[API] session detail error:', err);
|
|
860
920
|
res.status(500).json({ error: 'Failed to load session detail' });
|