claude-code-cost 0.15.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/package.json +1 -1
- package/public/app.js +424 -108
- package/public/index.html +1 -5
- package/public/style.css +154 -42
- package/server.js +242 -5
package/package.json
CHANGED
package/public/app.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
let currentView = 'overview';
|
|
4
4
|
let overviewData = null;
|
|
5
|
-
let
|
|
5
|
+
let insightsData = null;
|
|
6
6
|
let sessionsData = null;
|
|
7
7
|
let sessionsCostSeries = null;
|
|
8
8
|
let sessionsModelDistribution = null;
|
|
@@ -15,12 +15,10 @@ 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);
|
|
@@ -72,6 +70,10 @@ function formatTokens(count) {
|
|
|
72
70
|
return count.toString();
|
|
73
71
|
}
|
|
74
72
|
|
|
73
|
+
function formatPct(part, total) {
|
|
74
|
+
return total > 0 ? ((part / total) * 100).toFixed(1) : '0.0';
|
|
75
|
+
}
|
|
76
|
+
|
|
75
77
|
function formatDuration(minutes) {
|
|
76
78
|
if (!minutes || minutes < 1) return '<1m';
|
|
77
79
|
if (minutes < 60) return `${minutes}m`;
|
|
@@ -176,10 +178,7 @@ function thClass(field) {
|
|
|
176
178
|
return s && s.field === field ? 'sorted' : '';
|
|
177
179
|
}
|
|
178
180
|
|
|
179
|
-
|
|
180
|
-
const label = parentView === 'overview' ? 'Overview' : 'Projects';
|
|
181
|
-
return `<a class="parent-breadcrumb">${label}</a>`;
|
|
182
|
-
}
|
|
181
|
+
const PARENT_BREADCRUMB = '<a class="parent-breadcrumb">Overview</a>';
|
|
183
182
|
|
|
184
183
|
// In-view reminder that the numbers below cover one project, not everything. Reuses the
|
|
185
184
|
// breadcrumb styling — same role (where am I), no new CSS.
|
|
@@ -192,9 +191,17 @@ function scopeIndicator() {
|
|
|
192
191
|
</div>`;
|
|
193
192
|
}
|
|
194
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
|
+
|
|
195
202
|
function focusPreviousRow(view) {
|
|
196
203
|
let selector;
|
|
197
|
-
if (view === 'overview'
|
|
204
|
+
if (view === 'overview') {
|
|
198
205
|
if (!lastSelectedProject) return;
|
|
199
206
|
selector = `tr[onclick*="'${lastSelectedProject}'"]`;
|
|
200
207
|
} else if (view === 'sessions') {
|
|
@@ -219,12 +226,13 @@ function getUrlState() {
|
|
|
219
226
|
const saved = sessionStorage.getItem('cc-cost:nav');
|
|
220
227
|
if (saved) p = new URLSearchParams(saved);
|
|
221
228
|
}
|
|
229
|
+
const view = p.get('view') || 'overview';
|
|
222
230
|
return {
|
|
223
|
-
view
|
|
231
|
+
// Old bookmarks may still say view=projects; that view is gone, overview covers it.
|
|
232
|
+
view: view === 'projects' ? 'overview' : view,
|
|
224
233
|
project: p.get('project'),
|
|
225
234
|
projectName: p.get('projectName'),
|
|
226
235
|
session: p.get('session'),
|
|
227
|
-
parentView: p.get('parentView') || 'projects',
|
|
228
236
|
};
|
|
229
237
|
}
|
|
230
238
|
|
|
@@ -405,7 +413,6 @@ function updateUrl() {
|
|
|
405
413
|
if (currentProjectPath) p.set('project', currentProjectPath);
|
|
406
414
|
if (currentProjectName) p.set('projectName', currentProjectName);
|
|
407
415
|
if (currentSessionId) p.set('session', currentSessionId);
|
|
408
|
-
if (parentView !== 'projects') p.set('parentView', parentView);
|
|
409
416
|
const qs = p.toString();
|
|
410
417
|
history.replaceState(null, '', qs ? `?${qs}` : '/');
|
|
411
418
|
sessionStorage.setItem('cc-cost:nav', qs);
|
|
@@ -507,6 +514,10 @@ async function fetchOverview() {
|
|
|
507
514
|
overviewData = await fetchJSON(`/api/overview?${rangeParams()}${scopeParam()}`);
|
|
508
515
|
}
|
|
509
516
|
|
|
517
|
+
async function fetchInsights() {
|
|
518
|
+
insightsData = await fetchJSON(`/api/insights?${rangeParams()}${scopeParam()}`);
|
|
519
|
+
}
|
|
520
|
+
|
|
510
521
|
// Fire-and-forget label upgrade: /api/projects/:path/sessions carries no project name, so ask
|
|
511
522
|
// the scoped projects endpoint (one row) for the decoded one.
|
|
512
523
|
async function resolveScopeName() {
|
|
@@ -528,10 +539,6 @@ async function resolveScopeName() {
|
|
|
528
539
|
}
|
|
529
540
|
}
|
|
530
541
|
|
|
531
|
-
async function fetchProjects() {
|
|
532
|
-
projectsData = await fetchJSON(`/api/projects?${rangeParams()}${scopeParam()}`);
|
|
533
|
-
}
|
|
534
|
-
|
|
535
542
|
async function fetchSessions(encodedPath) {
|
|
536
543
|
const data = await fetchJSON(`/api/projects/${encodeURIComponent(encodedPath)}/sessions?${rangeParams()}`, true);
|
|
537
544
|
sessionsData = data.sessions;
|
|
@@ -573,6 +580,7 @@ function renderOverview() {
|
|
|
573
580
|
// Return before any chart call so no canvas is touched — there are none in this markup.
|
|
574
581
|
if (scopeProject && s.totalSessions === 0) {
|
|
575
582
|
el.innerHTML = `<div class="dashboard-content">
|
|
583
|
+
${viewTabs('overview')}
|
|
576
584
|
${scopeIndicator()}
|
|
577
585
|
<div class="empty-state">
|
|
578
586
|
<div class="empty-icon">$</div>
|
|
@@ -585,6 +593,7 @@ function renderOverview() {
|
|
|
585
593
|
|
|
586
594
|
el.innerHTML = `
|
|
587
595
|
<div class="dashboard-content">
|
|
596
|
+
${viewTabs('overview')}
|
|
588
597
|
${scopeIndicator()}
|
|
589
598
|
<div class="cards-row">
|
|
590
599
|
${
|
|
@@ -644,6 +653,7 @@ function renderOverview() {
|
|
|
644
653
|
<th class="${thClass('totalCost')}" onclick="sortBy('totalCost')">Cost ${sortArrow('totalCost')}</th>
|
|
645
654
|
<th class="${thClass('sessionCount')}" onclick="sortBy('sessionCount')">Sessions ${sortArrow('sessionCount')}</th>
|
|
646
655
|
<th class="${thClass('lastActive')}" onclick="sortBy('lastActive')">Last Active ${sortArrow('lastActive')}</th>
|
|
656
|
+
<th>Model</th>
|
|
647
657
|
</tr></thead>
|
|
648
658
|
<tbody>
|
|
649
659
|
${[...overviewData.projects]
|
|
@@ -655,6 +665,7 @@ function renderOverview() {
|
|
|
655
665
|
<td class="cost-cell">${formatCost(p.totalCost)}</td>
|
|
656
666
|
<td>${p.sessionCount}</td>
|
|
657
667
|
<td class="muted">${timeAgo(p.lastActive)}</td>
|
|
668
|
+
<td><span class="model-badge">${esc(shortModel(p.primaryModel))}</span></td>
|
|
658
669
|
</tr>`,
|
|
659
670
|
)
|
|
660
671
|
.join('')}
|
|
@@ -673,65 +684,227 @@ function renderOverview() {
|
|
|
673
684
|
|
|
674
685
|
// #endregion
|
|
675
686
|
|
|
676
|
-
// #region
|
|
687
|
+
// #region RENDER_INSIGHTS
|
|
688
|
+
|
|
689
|
+
const HEATMAP_DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
677
690
|
|
|
678
|
-
|
|
679
|
-
|
|
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)}–${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)}–${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
|
+
}
|
|
770
|
+
|
|
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');
|
|
680
796
|
if (!el) return;
|
|
681
|
-
if (!
|
|
797
|
+
if (!insightsData) {
|
|
682
798
|
el.innerHTML = '<div class="loading-state"><div class="loading-spinner"></div><span>Loading...</span></div>';
|
|
683
799
|
return;
|
|
684
800
|
}
|
|
685
801
|
|
|
686
|
-
const
|
|
687
|
-
|
|
688
|
-
lastRenderHash.
|
|
689
|
-
|
|
690
|
-
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;
|
|
691
806
|
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
scopeProject
|
|
699
|
-
? `<div>No usage for ${esc(scopeProjectName || scopeProject)} ${esc(rangeInLabel(dateRange))}</div>
|
|
700
|
-
<div>Clear the project scope to see everything.</div>`
|
|
701
|
-
: `<div>No project data found</div>
|
|
702
|
-
<div>Make sure Claude Code session files exist in ~/.claude/projects/</div>`
|
|
703
|
-
}
|
|
704
|
-
</div></div>`;
|
|
705
|
-
return;
|
|
706
|
-
}
|
|
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;
|
|
707
813
|
|
|
708
814
|
el.innerHTML = `
|
|
709
815
|
<div class="dashboard-content">
|
|
710
|
-
${
|
|
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)} · ${formatDuration(ab.burn.remainingMin)} left${ab.usedPct != null ? ` · ${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 · proj. ${formatCost(ab.burn.projectedCost)} by block end${pace ? ` · ${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 · ${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])} → ${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>
|
|
711
877
|
<table class="data-table">
|
|
712
878
|
<thead><tr>
|
|
713
|
-
<th
|
|
714
|
-
<th class="${thClass('totalCost')}" onclick="sortBy('totalCost')">Cost ${sortArrow('totalCost')}</th>
|
|
715
|
-
<th class="${thClass('sessionCount')}" onclick="sortBy('sessionCount')">Sessions ${sortArrow('sessionCount')}</th>
|
|
716
|
-
<th class="${thClass('lastActive')}" onclick="sortBy('lastActive')">Last Active ${sortArrow('lastActive')}</th>
|
|
717
|
-
<th>Model</th>
|
|
879
|
+
<th>Block</th><th>Status</th><th>Messages</th><th>Tokens</th><th>Cost</th><th>Models</th>
|
|
718
880
|
</tr></thead>
|
|
719
881
|
<tbody>
|
|
720
|
-
${
|
|
882
|
+
${d.blocks
|
|
721
883
|
.map(
|
|
722
|
-
(
|
|
723
|
-
<tr
|
|
724
|
-
<td>${
|
|
725
|
-
<td class="
|
|
726
|
-
<td>${
|
|
727
|
-
<td
|
|
728
|
-
<td
|
|
884
|
+
(b) => `
|
|
885
|
+
<tr>
|
|
886
|
+
<td>${blockSpanLabel(b)}</td>
|
|
887
|
+
<td>${b.active ? `<span class="block-badge active">ACTIVE · ${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>
|
|
729
892
|
</tr>`,
|
|
730
893
|
)
|
|
731
894
|
.join('')}
|
|
732
895
|
</tbody>
|
|
733
|
-
</table
|
|
896
|
+
</table>`
|
|
897
|
+
: ''
|
|
898
|
+
}
|
|
899
|
+
|
|
734
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
|
+
});
|
|
735
908
|
}
|
|
736
909
|
|
|
737
910
|
// #endregion
|
|
@@ -753,7 +926,7 @@ function renderSessions() {
|
|
|
753
926
|
if (sessionsData.length === 0) {
|
|
754
927
|
el.innerHTML = `<div class="dashboard-content">
|
|
755
928
|
<div class="breadcrumb">
|
|
756
|
-
${
|
|
929
|
+
${PARENT_BREADCRUMB}
|
|
757
930
|
<span class="sep">/</span>
|
|
758
931
|
<span class="current">${esc(currentProjectName || 'Project')}</span>
|
|
759
932
|
</div>
|
|
@@ -765,7 +938,7 @@ function renderSessions() {
|
|
|
765
938
|
el.innerHTML = `
|
|
766
939
|
<div class="dashboard-content">
|
|
767
940
|
<div class="breadcrumb">
|
|
768
|
-
${
|
|
941
|
+
${PARENT_BREADCRUMB}
|
|
769
942
|
<span class="sep">/</span>
|
|
770
943
|
<span class="current">${esc(currentProjectName || 'Project')}</span>
|
|
771
944
|
</div>
|
|
@@ -841,7 +1014,7 @@ function renderDetail() {
|
|
|
841
1014
|
el.innerHTML = `
|
|
842
1015
|
<div class="dashboard-content">
|
|
843
1016
|
<div class="breadcrumb">
|
|
844
|
-
${
|
|
1017
|
+
${PARENT_BREADCRUMB}
|
|
845
1018
|
<span class="sep">/</span>
|
|
846
1019
|
<a onclick="navigateToSessions('${escAttrJs(d.encodedProjectPath)}', '${escAttrJs(d.projectPath)}')">${esc(d.projectPath)}</a>
|
|
847
1020
|
<span class="sep">/</span>
|
|
@@ -1026,6 +1199,63 @@ function chartDefaults() {
|
|
|
1026
1199
|
};
|
|
1027
1200
|
}
|
|
1028
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
|
+
|
|
1029
1259
|
function destroyChart(id) {
|
|
1030
1260
|
if (charts[id]) {
|
|
1031
1261
|
charts[id].destroy();
|
|
@@ -1074,17 +1304,13 @@ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost', dist
|
|
|
1074
1304
|
interaction: { mode: 'nearest', intersect: true },
|
|
1075
1305
|
events: [],
|
|
1076
1306
|
plugins: {
|
|
1077
|
-
...defaults.
|
|
1307
|
+
...withTooltip(defaults, { label: (ctx) => usd(ctx.parsed.y) }),
|
|
1078
1308
|
// events: [] disables tooltips, so the legend is the only place segment names show.
|
|
1079
1309
|
legend: {
|
|
1080
1310
|
display: models.length > 1,
|
|
1081
1311
|
position: 'bottom',
|
|
1082
1312
|
labels: { color: c.text, font: { size: 9 }, boxWidth: 8, boxHeight: 8 },
|
|
1083
1313
|
},
|
|
1084
|
-
tooltip: {
|
|
1085
|
-
...defaults.plugins.tooltip,
|
|
1086
|
-
callbacks: { label: (ctx) => `$${ctx.parsed.y.toFixed(2)}` },
|
|
1087
|
-
},
|
|
1088
1314
|
},
|
|
1089
1315
|
scales: {
|
|
1090
1316
|
...defaults.scales,
|
|
@@ -1092,7 +1318,7 @@ function renderCostChart(series, canvasId = 'costChart', chartKey = 'cost', dist
|
|
|
1092
1318
|
y: {
|
|
1093
1319
|
...defaults.scales.y,
|
|
1094
1320
|
stacked: true,
|
|
1095
|
-
ticks: { ...defaults.scales.y.ticks, callback:
|
|
1321
|
+
ticks: { ...defaults.scales.y.ticks, callback: usd },
|
|
1096
1322
|
},
|
|
1097
1323
|
},
|
|
1098
1324
|
},
|
|
@@ -1128,19 +1354,9 @@ function renderModelChart(models, canvasId = 'modelChart', chartKey = 'model') {
|
|
|
1128
1354
|
indexAxis: 'y',
|
|
1129
1355
|
interaction: { mode: 'nearest', intersect: true },
|
|
1130
1356
|
events: [],
|
|
1131
|
-
plugins: {
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
...defaults.plugins.tooltip,
|
|
1135
|
-
callbacks: {
|
|
1136
|
-
label: (ctx) => {
|
|
1137
|
-
const val = ctx.parsed.x;
|
|
1138
|
-
const pct = ((val / total) * 100).toFixed(1);
|
|
1139
|
-
return `$${val.toFixed(2)} (${pct}%)`;
|
|
1140
|
-
},
|
|
1141
|
-
},
|
|
1142
|
-
},
|
|
1143
|
-
},
|
|
1357
|
+
plugins: withTooltip(defaults, {
|
|
1358
|
+
label: (ctx) => `${usd(ctx.parsed.x)} (${formatPct(ctx.parsed.x, total)}%)`,
|
|
1359
|
+
}),
|
|
1144
1360
|
scales: {
|
|
1145
1361
|
...defaults.scales,
|
|
1146
1362
|
x: { ...defaults.scales.x, ticks: { ...defaults.scales.x.ticks, callback: (v) => `$${v}` } },
|
|
@@ -1250,6 +1466,121 @@ function renderTokenBreakdownChart(messages) {
|
|
|
1250
1466
|
});
|
|
1251
1467
|
}
|
|
1252
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
|
+
|
|
1253
1584
|
// biome-ignore lint/correctness/noUnusedVariables: called from theme toggle
|
|
1254
1585
|
function destroyAllCharts() {
|
|
1255
1586
|
for (const id of Object.keys(charts)) {
|
|
@@ -1663,12 +1994,6 @@ function buildRangeMonth(y, m, nav) {
|
|
|
1663
1994
|
|
|
1664
1995
|
// #region ROUTER
|
|
1665
1996
|
|
|
1666
|
-
function setActiveNav(view) {
|
|
1667
|
-
document.querySelectorAll('.topbar-nav-btn').forEach((btn) => {
|
|
1668
|
-
btn.classList.toggle('active', btn.dataset.view === view);
|
|
1669
|
-
});
|
|
1670
|
-
}
|
|
1671
|
-
|
|
1672
1997
|
function showView(viewId) {
|
|
1673
1998
|
document.querySelectorAll('.view').forEach((v) => v.classList.remove('active'));
|
|
1674
1999
|
const el = document.getElementById(viewId);
|
|
@@ -1682,7 +2007,7 @@ async function navigate(view, params) {
|
|
|
1682
2007
|
if (params?.session) currentSessionId = params.session;
|
|
1683
2008
|
|
|
1684
2009
|
// Clear downstream state
|
|
1685
|
-
if (view === 'overview' || view === '
|
|
2010
|
+
if (view === 'overview' || view === 'insights') {
|
|
1686
2011
|
currentProjectPath = null;
|
|
1687
2012
|
currentProjectName = null;
|
|
1688
2013
|
currentSessionId = null;
|
|
@@ -1691,8 +2016,6 @@ async function navigate(view, params) {
|
|
|
1691
2016
|
currentSessionId = null;
|
|
1692
2017
|
}
|
|
1693
2018
|
|
|
1694
|
-
const navView = view === 'sessions' || view === 'detail' ? parentView : view;
|
|
1695
|
-
setActiveNav(navView);
|
|
1696
2019
|
updateUrl();
|
|
1697
2020
|
await loadAndRender(view);
|
|
1698
2021
|
if (view !== 'detail') selectRow(0);
|
|
@@ -1700,9 +2023,6 @@ async function navigate(view, params) {
|
|
|
1700
2023
|
|
|
1701
2024
|
// biome-ignore lint/correctness/noUnusedVariables: called from HTML onclick
|
|
1702
2025
|
async function navigateToSessions(encodedPath, name) {
|
|
1703
|
-
if (currentView === 'overview' || currentView === 'projects') {
|
|
1704
|
-
parentView = currentView;
|
|
1705
|
-
}
|
|
1706
2026
|
lastSelectedProject = encodedPath;
|
|
1707
2027
|
currentProjectPath = encodedPath;
|
|
1708
2028
|
currentProjectName = name;
|
|
@@ -1719,6 +2039,7 @@ async function navigateToDetail(sessionId) {
|
|
|
1719
2039
|
// biome-ignore lint/correctness/noUnusedVariables: called from HTML onclick
|
|
1720
2040
|
function sortBy(field) {
|
|
1721
2041
|
const s = currentSort();
|
|
2042
|
+
if (!s) return;
|
|
1722
2043
|
if (s.field === field) {
|
|
1723
2044
|
s.order = s.order === 'desc' ? 'asc' : 'desc';
|
|
1724
2045
|
} else {
|
|
@@ -1730,7 +2051,6 @@ function sortBy(field) {
|
|
|
1730
2051
|
updateUrl();
|
|
1731
2052
|
if (currentView === 'overview') renderOverview();
|
|
1732
2053
|
else if (currentView === 'sessions') renderSessions();
|
|
1733
|
-
else renderProjects();
|
|
1734
2054
|
}
|
|
1735
2055
|
|
|
1736
2056
|
// The one entry point for a range change, from either half of the picker. The lastRenderHash reset
|
|
@@ -1775,7 +2095,6 @@ async function applyScope(encoded, name) {
|
|
|
1775
2095
|
// rows.
|
|
1776
2096
|
sessionsData = null;
|
|
1777
2097
|
sessionDetailData = null;
|
|
1778
|
-
parentView = 'overview';
|
|
1779
2098
|
await navigate('sessions', { project: scopeProject, projectName: scopeProjectName });
|
|
1780
2099
|
}
|
|
1781
2100
|
|
|
@@ -1838,10 +2157,10 @@ async function loadAndRender(view) {
|
|
|
1838
2157
|
if (myNav !== navCounter) return;
|
|
1839
2158
|
renderOverview();
|
|
1840
2159
|
break;
|
|
1841
|
-
case '
|
|
1842
|
-
await
|
|
2160
|
+
case 'insights':
|
|
2161
|
+
await fetchInsights();
|
|
1843
2162
|
if (myNav !== navCounter) return;
|
|
1844
|
-
|
|
2163
|
+
renderInsights();
|
|
1845
2164
|
break;
|
|
1846
2165
|
case 'sessions':
|
|
1847
2166
|
if (currentProjectPath) {
|
|
@@ -1883,7 +2202,7 @@ function renderCurrentView() {
|
|
|
1883
2202
|
function ensureViewElements() {
|
|
1884
2203
|
const app = document.getElementById('app');
|
|
1885
2204
|
if (!app) return;
|
|
1886
|
-
const views = ['overview', '
|
|
2205
|
+
const views = ['overview', 'insights', 'sessions', 'detail'];
|
|
1887
2206
|
for (const v of views) {
|
|
1888
2207
|
if (!document.getElementById(`${v}-view`)) {
|
|
1889
2208
|
const div = document.createElement('div');
|
|
@@ -1939,16 +2258,19 @@ function activateSelectedRow() {
|
|
|
1939
2258
|
async function goBack() {
|
|
1940
2259
|
let target;
|
|
1941
2260
|
if (currentView === 'detail') {
|
|
1942
|
-
target = currentProjectPath ? 'sessions' :
|
|
1943
|
-
} else if (currentView === 'sessions') {
|
|
1944
|
-
target = parentView;
|
|
1945
|
-
} else if (currentView === 'projects') {
|
|
2261
|
+
target = currentProjectPath ? 'sessions' : 'overview';
|
|
2262
|
+
} else if (currentView === 'sessions' || currentView === 'insights') {
|
|
1946
2263
|
target = 'overview';
|
|
1947
2264
|
}
|
|
1948
2265
|
if (!target) return;
|
|
1949
2266
|
|
|
2267
|
+
// Insights is a sibling view, not a drill-down: the scope survives a tab switch.
|
|
2268
|
+
const keepScope = currentView === 'insights';
|
|
2269
|
+
|
|
1950
2270
|
if (target === 'sessions') {
|
|
1951
2271
|
await navigate('sessions', { project: currentProjectPath, projectName: currentProjectName });
|
|
2272
|
+
} else if (keepScope) {
|
|
2273
|
+
await navigate(target);
|
|
1952
2274
|
} else {
|
|
1953
2275
|
// Backing out to a top-level view drops the scope with the cursor: a scoped overview
|
|
1954
2276
|
// showing one project has no visible cause once you've left that project behind.
|
|
@@ -1993,9 +2315,10 @@ document.addEventListener('keydown', (e) => {
|
|
|
1993
2315
|
navigate('overview');
|
|
1994
2316
|
return;
|
|
1995
2317
|
}
|
|
2318
|
+
|
|
1996
2319
|
if (e.key === '2') {
|
|
1997
2320
|
e.preventDefault();
|
|
1998
|
-
navigate('
|
|
2321
|
+
navigate('insights');
|
|
1999
2322
|
return;
|
|
2000
2323
|
}
|
|
2001
2324
|
|
|
@@ -2208,9 +2531,8 @@ loadSort();
|
|
|
2208
2531
|
|
|
2209
2532
|
document.addEventListener('click', async (e) => {
|
|
2210
2533
|
if (e.target.matches('.parent-breadcrumb')) {
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
focusPreviousRow(target);
|
|
2534
|
+
await navigate('overview');
|
|
2535
|
+
focusPreviousRow('overview');
|
|
2214
2536
|
}
|
|
2215
2537
|
});
|
|
2216
2538
|
|
|
@@ -2237,20 +2559,15 @@ document.addEventListener('DOMContentLoaded', async () => {
|
|
|
2237
2559
|
|
|
2238
2560
|
if (state.session) {
|
|
2239
2561
|
currentSessionId = state.session;
|
|
2240
|
-
parentView = state.parentView;
|
|
2241
2562
|
currentProjectPath = state.project;
|
|
2242
2563
|
currentProjectName = state.projectName;
|
|
2243
2564
|
await navigate('detail', { session: state.session });
|
|
2244
2565
|
} else if (state.project) {
|
|
2245
|
-
parentView = state.parentView;
|
|
2246
2566
|
currentProjectPath = state.project;
|
|
2247
2567
|
currentProjectName = state.projectName;
|
|
2248
2568
|
await navigate('sessions', { project: state.project, projectName: state.projectName });
|
|
2249
|
-
} else if (state.view === 'projects') {
|
|
2250
|
-
await navigate('projects');
|
|
2251
2569
|
} else if (scopeProject) {
|
|
2252
2570
|
// Same landing rule as applyScope: a scope with no cursor of its own opens its sessions.
|
|
2253
|
-
parentView = 'overview';
|
|
2254
2571
|
currentProjectName = scopeProjectName;
|
|
2255
2572
|
await navigate('sessions', { project: scopeProject, projectName: scopeProjectName });
|
|
2256
2573
|
} else {
|
|
@@ -2261,7 +2578,6 @@ document.addEventListener('DOMContentLoaded', async () => {
|
|
|
2261
2578
|
window.addEventListener('popstate', () => {
|
|
2262
2579
|
const state = getUrlState();
|
|
2263
2580
|
currentView = state.view || 'overview';
|
|
2264
|
-
parentView = state.parentView;
|
|
2265
2581
|
currentProjectPath = state.project;
|
|
2266
2582
|
currentProjectName = state.projectName;
|
|
2267
2583
|
currentSessionId = state.session;
|
package/public/index.html
CHANGED
|
@@ -30,10 +30,6 @@
|
|
|
30
30
|
<span class="logo-text">Cost Dashboard</span>
|
|
31
31
|
</div>
|
|
32
32
|
<div class="spacer"></div>
|
|
33
|
-
<div class="topbar-nav" id="viewNav">
|
|
34
|
-
<button class="topbar-nav-btn active" data-view="overview" onclick="navigate('overview')">Overview</button>
|
|
35
|
-
<button class="topbar-nav-btn" data-view="projects" onclick="navigate('projects')">Projects</button>
|
|
36
|
-
</div>
|
|
37
33
|
<span class="scope-chip" id="scopeChip" hidden title="Scoped to one project">
|
|
38
34
|
<span id="scopeChipName"></span>
|
|
39
35
|
<button class="scope-chip-clear" onclick="clearScope()" title="Clear project scope" aria-label="Clear project scope">
|
|
@@ -114,7 +110,7 @@
|
|
|
114
110
|
<h4 class="shortcut-section">Navigation</h4>
|
|
115
111
|
<table class="shortcut-table">
|
|
116
112
|
<tr><td><kbd>1</kbd></td><td>Overview</td></tr>
|
|
117
|
-
<tr><td><kbd>2</kbd></td><td>
|
|
113
|
+
<tr><td><kbd>2</kbd></td><td>Insights</td></tr>
|
|
118
114
|
<tr><td><kbd>Backspace</kbd></td><td>Go back</td></tr>
|
|
119
115
|
<tr><td><kbd>Esc</kbd></td><td>Close modal / go back</td></tr>
|
|
120
116
|
</table>
|
package/public/style.css
CHANGED
|
@@ -122,42 +122,8 @@ body {
|
|
|
122
122
|
flex: 1;
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
-
.topbar-nav {
|
|
126
|
-
display: flex;
|
|
127
|
-
gap: 2px;
|
|
128
|
-
background: var(--bg-elevated);
|
|
129
|
-
border: 1px solid var(--border);
|
|
130
|
-
border-radius: 6px;
|
|
131
|
-
padding: 2px;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
.topbar-nav-btn {
|
|
135
|
-
padding: 4px 12px;
|
|
136
|
-
border-radius: 4px;
|
|
137
|
-
font-size: 11px;
|
|
138
|
-
font-weight: 500;
|
|
139
|
-
cursor: pointer;
|
|
140
|
-
border: none;
|
|
141
|
-
background: transparent;
|
|
142
|
-
color: var(--text-tertiary);
|
|
143
|
-
font-family: var(--mono);
|
|
144
|
-
transition: all 0.15s ease;
|
|
145
|
-
text-transform: uppercase;
|
|
146
|
-
letter-spacing: 0.03em;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
.topbar-nav-btn:hover {
|
|
150
|
-
color: var(--text-secondary);
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
.topbar-nav-btn.active {
|
|
154
|
-
background: var(--accent-dim);
|
|
155
|
-
color: var(--accent-text);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
125
|
/* #region SCOPE_CHIP */
|
|
159
126
|
|
|
160
|
-
/* Reuses --accent-dim/--accent-text from .topbar-nav-btn.active so LIGHT_THEME needs nothing. */
|
|
161
127
|
.scope-chip {
|
|
162
128
|
display: flex;
|
|
163
129
|
align-items: center;
|
|
@@ -319,6 +285,41 @@ body {
|
|
|
319
285
|
}
|
|
320
286
|
}
|
|
321
287
|
|
|
288
|
+
/* Root-level view switcher, rendered by the overview and insights views rather than the topbar
|
|
289
|
+
itself — drill-down views show a breadcrumb in its place. Reuses --accent-dim/--accent-text,
|
|
290
|
+
so no LIGHT_THEME rule is needed. */
|
|
291
|
+
.view-tabs {
|
|
292
|
+
display: flex;
|
|
293
|
+
gap: 4px;
|
|
294
|
+
margin-bottom: 16px;
|
|
295
|
+
border-bottom: 1px solid var(--border);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
.view-tab {
|
|
299
|
+
background: none;
|
|
300
|
+
border: none;
|
|
301
|
+
border-bottom: 2px solid transparent;
|
|
302
|
+
color: var(--text-tertiary);
|
|
303
|
+
font-family: var(--mono);
|
|
304
|
+
font-size: 12px;
|
|
305
|
+
text-transform: uppercase;
|
|
306
|
+
letter-spacing: 0.05em;
|
|
307
|
+
padding: 8px 14px;
|
|
308
|
+
cursor: pointer;
|
|
309
|
+
transition:
|
|
310
|
+
color 0.15s ease,
|
|
311
|
+
border-color 0.15s ease;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
.view-tab:hover {
|
|
315
|
+
color: var(--text-primary);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
.view-tab.on {
|
|
319
|
+
color: var(--accent-text);
|
|
320
|
+
border-bottom-color: var(--accent);
|
|
321
|
+
}
|
|
322
|
+
|
|
322
323
|
/* #endregion */
|
|
323
324
|
|
|
324
325
|
/* #region DATE_PICKER */
|
|
@@ -736,6 +737,12 @@ body {
|
|
|
736
737
|
color: var(--text-secondary);
|
|
737
738
|
}
|
|
738
739
|
|
|
740
|
+
.chart-title-note {
|
|
741
|
+
color: var(--text-muted);
|
|
742
|
+
font-weight: 400;
|
|
743
|
+
float: right;
|
|
744
|
+
}
|
|
745
|
+
|
|
739
746
|
/* #endregion */
|
|
740
747
|
|
|
741
748
|
/* #region TABLE */
|
|
@@ -1199,6 +1206,119 @@ body {
|
|
|
1199
1206
|
|
|
1200
1207
|
/* #endregion */
|
|
1201
1208
|
|
|
1209
|
+
/* #region INSIGHTS */
|
|
1210
|
+
|
|
1211
|
+
.heatmap {
|
|
1212
|
+
display: flex;
|
|
1213
|
+
flex-direction: column;
|
|
1214
|
+
gap: 3px;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
.hm-row {
|
|
1218
|
+
display: grid;
|
|
1219
|
+
grid-template-columns: 48px repeat(24, 1fr);
|
|
1220
|
+
gap: 3px;
|
|
1221
|
+
align-items: center;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
.hm-row.hm-today .hm-day {
|
|
1225
|
+
color: var(--accent);
|
|
1226
|
+
font-weight: 700;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
.hm-row.hm-today .hm-cell {
|
|
1230
|
+
outline: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
.hm-day,
|
|
1234
|
+
.hm-hour {
|
|
1235
|
+
font-size: 9px;
|
|
1236
|
+
color: var(--text-muted);
|
|
1237
|
+
font-family: var(--mono);
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
.hm-hour {
|
|
1241
|
+
text-align: center;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
.hm-cell {
|
|
1245
|
+
position: relative;
|
|
1246
|
+
aspect-ratio: 1.6;
|
|
1247
|
+
min-height: 12px;
|
|
1248
|
+
border-radius: 2px;
|
|
1249
|
+
background: var(--bg-hover);
|
|
1250
|
+
overflow: hidden;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
.hm-cell i {
|
|
1254
|
+
position: absolute;
|
|
1255
|
+
inset: 0;
|
|
1256
|
+
background: var(--accent);
|
|
1257
|
+
border-radius: 2px;
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
.hm-cell:hover {
|
|
1261
|
+
outline: 1px solid var(--accent);
|
|
1262
|
+
outline-offset: 1px;
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
.hm-tip {
|
|
1266
|
+
position: fixed;
|
|
1267
|
+
z-index: 100;
|
|
1268
|
+
display: none;
|
|
1269
|
+
flex-direction: column;
|
|
1270
|
+
gap: 1px;
|
|
1271
|
+
padding: 5px 8px;
|
|
1272
|
+
background: var(--bg-elevated);
|
|
1273
|
+
border: 1px solid var(--border);
|
|
1274
|
+
border-radius: 4px;
|
|
1275
|
+
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
|
|
1276
|
+
font-family: var(--mono);
|
|
1277
|
+
pointer-events: none;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
.hm-tip.on {
|
|
1281
|
+
display: flex;
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
.hm-tip b {
|
|
1285
|
+
font-size: 12px;
|
|
1286
|
+
color: var(--text-primary);
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
.hm-tip span {
|
|
1290
|
+
font-size: 10px;
|
|
1291
|
+
color: var(--text-muted);
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
.block-badge {
|
|
1295
|
+
display: inline-block;
|
|
1296
|
+
font-size: 10px;
|
|
1297
|
+
font-family: var(--mono);
|
|
1298
|
+
color: var(--text-tertiary);
|
|
1299
|
+
background: var(--bg-hover);
|
|
1300
|
+
border-radius: 3px;
|
|
1301
|
+
padding: 2px 6px;
|
|
1302
|
+
white-space: nowrap;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
.block-badge.active {
|
|
1306
|
+
color: var(--success);
|
|
1307
|
+
background: var(--success-dim);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
.card-value.pace-ok {
|
|
1311
|
+
color: var(--success);
|
|
1312
|
+
}
|
|
1313
|
+
.card-value.pace-warn {
|
|
1314
|
+
color: var(--warning);
|
|
1315
|
+
}
|
|
1316
|
+
.card-value.pace-hot {
|
|
1317
|
+
color: var(--error);
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
/* #endregion */
|
|
1321
|
+
|
|
1202
1322
|
/* #region LIGHT_THEME */
|
|
1203
1323
|
|
|
1204
1324
|
body.light {
|
|
@@ -1259,14 +1379,6 @@ body.light {
|
|
|
1259
1379
|
gap: 8px;
|
|
1260
1380
|
padding: 8px 12px;
|
|
1261
1381
|
}
|
|
1262
|
-
.topbar-nav {
|
|
1263
|
-
order: 10;
|
|
1264
|
-
width: 100%;
|
|
1265
|
-
}
|
|
1266
|
-
.topbar-nav-btn {
|
|
1267
|
-
flex: 1;
|
|
1268
|
-
text-align: center;
|
|
1269
|
-
}
|
|
1270
1382
|
.cards-row {
|
|
1271
1383
|
grid-template-columns: 1fr;
|
|
1272
1384
|
}
|
package/server.js
CHANGED
|
@@ -446,7 +446,8 @@ async function loadSubagentData(subagentInfos, pricing) {
|
|
|
446
446
|
|
|
447
447
|
async function loadProjectData(files, pricing) {
|
|
448
448
|
const sessions = new Map();
|
|
449
|
-
|
|
449
|
+
// hash -> pushed message, so tool_use blocks from duplicate lines can be folded in.
|
|
450
|
+
const seen = new Map();
|
|
450
451
|
|
|
451
452
|
for (const file of files) {
|
|
452
453
|
const sessionId = getSessionIdFromFile(file);
|
|
@@ -479,8 +480,17 @@ async function loadProjectData(files, pricing) {
|
|
|
479
480
|
if (!parsed.timestamp) return;
|
|
480
481
|
|
|
481
482
|
const hash = createDedupeHash(parsed);
|
|
482
|
-
if (hash && seen.has(hash))
|
|
483
|
-
|
|
483
|
+
if (hash && seen.has(hash)) {
|
|
484
|
+
// Streaming writes one JSONL line per content block of the same API message. Usage is
|
|
485
|
+
// identical on every line (deduped), but each line carries different tool_use blocks,
|
|
486
|
+
// so tools must be unioned across duplicates or most calls are lost.
|
|
487
|
+
const dupTools = extractTools(parsed.message?.content);
|
|
488
|
+
if (dupTools) {
|
|
489
|
+
const orig = seen.get(hash);
|
|
490
|
+
orig.tools = (orig.tools || []).concat(dupTools);
|
|
491
|
+
}
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
484
494
|
|
|
485
495
|
const cost = calculateEntryCost(parsed, pricing);
|
|
486
496
|
const usage = parsed.message.usage;
|
|
@@ -497,7 +507,7 @@ async function loadProjectData(files, pricing) {
|
|
|
497
507
|
if (!session.firstTimestamp || ts < session.firstTimestamp) session.firstTimestamp = ts;
|
|
498
508
|
if (!session.lastTimestamp || ts > session.lastTimestamp) session.lastTimestamp = ts;
|
|
499
509
|
|
|
500
|
-
|
|
510
|
+
const msg = {
|
|
501
511
|
timestamp: ts,
|
|
502
512
|
model,
|
|
503
513
|
cost,
|
|
@@ -507,7 +517,9 @@ async function loadProjectData(files, pricing) {
|
|
|
507
517
|
cacheReadTokens: usage.cache_read_input_tokens || 0,
|
|
508
518
|
speed: usage.speed || 'standard',
|
|
509
519
|
tools: extractTools(parsed.message?.content),
|
|
510
|
-
}
|
|
520
|
+
};
|
|
521
|
+
session.messages.push(msg);
|
|
522
|
+
if (hash) seen.set(hash, msg);
|
|
511
523
|
|
|
512
524
|
// Capture first user prompt from the JSONL (look for human/user messages)
|
|
513
525
|
if (!session.firstPrompt && parsed.type === 'human' && parsed.message?.content) {
|
|
@@ -945,6 +957,219 @@ async function getSessionDetailData(sessionId) {
|
|
|
945
957
|
return null;
|
|
946
958
|
}
|
|
947
959
|
|
|
960
|
+
// Claude's usage limits work in rolling 5-hour billing windows. A block starts at the first
|
|
961
|
+
// activity (floored to the hour, mirroring ccusage) and spans exactly 5h; activity past the end
|
|
962
|
+
// opens a new block anchored to its own hour.
|
|
963
|
+
const BLOCK_MS = 5 * 60 * 60 * 1000;
|
|
964
|
+
const HEATMAP_DAYS = 7;
|
|
965
|
+
const MAX_BLOCKS = 24;
|
|
966
|
+
const MAX_TOOLS = 20;
|
|
967
|
+
|
|
968
|
+
// The real window boundary comes from Claude Code's statusline payload (rate_limits.five_hour),
|
|
969
|
+
// spied to disk by the cck plugin. The ccusage hour-floor heuristic can be hours off the actual
|
|
970
|
+
// API window, so when a live resets_at is available it anchors the active block instead.
|
|
971
|
+
function readRateLimits(now) {
|
|
972
|
+
const dir = path.join(CLAUDE_DIR, '.cck', 'context-status');
|
|
973
|
+
let newest = null;
|
|
974
|
+
try {
|
|
975
|
+
for (const f of fs.readdirSync(dir)) {
|
|
976
|
+
if (!f.endsWith('.json')) continue;
|
|
977
|
+
const fp = path.join(dir, f);
|
|
978
|
+
try {
|
|
979
|
+
const mtime = fs.statSync(fp).mtimeMs;
|
|
980
|
+
if (!newest || mtime > newest.mtime) newest = { fp, mtime };
|
|
981
|
+
} catch { /* ignore */ }
|
|
982
|
+
}
|
|
983
|
+
} catch { return null; }
|
|
984
|
+
if (!newest) return null;
|
|
985
|
+
try {
|
|
986
|
+
const rl = JSON.parse(fs.readFileSync(newest.fp, 'utf8'))?.rate_limits;
|
|
987
|
+
const fh = rl?.five_hour;
|
|
988
|
+
// A resets_at in the past means the snapshot predates the current window — don't trust it.
|
|
989
|
+
if (!fh?.resets_at || fh.resets_at * 1000 <= now.getTime()) return null;
|
|
990
|
+
return { usedPct: fh.used_percentage ?? null, resetsAtMs: fh.resets_at * 1000 };
|
|
991
|
+
} catch { return null; }
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
function computeBlocks(messages, now, realResetMs) {
|
|
995
|
+
// When the API told us the live window, the active block spans exactly [reset-5h, reset].
|
|
996
|
+
const activeStartMs = realResetMs && now.getTime() < realResetMs ? realResetMs - BLOCK_MS : null;
|
|
997
|
+
const blocks = [];
|
|
998
|
+
let cur = null;
|
|
999
|
+
for (const m of messages) {
|
|
1000
|
+
const t = new Date(m.timestamp).getTime();
|
|
1001
|
+
if (!Number.isFinite(t)) continue;
|
|
1002
|
+
if (activeStartMs !== null && t >= activeStartMs) {
|
|
1003
|
+
if (!cur || cur.startMs !== activeStartMs) {
|
|
1004
|
+
cur = { startMs: activeStartMs, real: true, lastMs: t, cost: 0, tokens: 0, messageCount: 0, models: new Set() };
|
|
1005
|
+
blocks.push(cur);
|
|
1006
|
+
}
|
|
1007
|
+
} else if (!cur || t >= cur.startMs + BLOCK_MS) {
|
|
1008
|
+
const start = new Date(t);
|
|
1009
|
+
start.setMinutes(0, 0, 0);
|
|
1010
|
+
cur = { startMs: start.getTime(), lastMs: t, cost: 0, tokens: 0, messageCount: 0, models: new Set() };
|
|
1011
|
+
blocks.push(cur);
|
|
1012
|
+
}
|
|
1013
|
+
if (t > cur.lastMs) cur.lastMs = t;
|
|
1014
|
+
cur.cost += m.cost;
|
|
1015
|
+
cur.tokens += m.inputTokens + m.outputTokens + m.cacheCreationTokens + m.cacheReadTokens;
|
|
1016
|
+
cur.messageCount++;
|
|
1017
|
+
if (isRealModel(m.model)) cur.models.add(m.model);
|
|
1018
|
+
}
|
|
1019
|
+
// A live window with no in-range messages yet still exists — surface it as an empty block.
|
|
1020
|
+
if (activeStartMs !== null && !blocks.some((b) => b.startMs === activeStartMs)) {
|
|
1021
|
+
blocks.push({ startMs: activeStartMs, real: true, lastMs: activeStartMs, cost: 0, tokens: 0, messageCount: 0, models: new Set() });
|
|
1022
|
+
}
|
|
1023
|
+
const nowMs = now.getTime();
|
|
1024
|
+
return blocks
|
|
1025
|
+
.reverse()
|
|
1026
|
+
.slice(0, MAX_BLOCKS)
|
|
1027
|
+
.map((b) => {
|
|
1028
|
+
const endMs = b.startMs + BLOCK_MS;
|
|
1029
|
+
// Only the API-anchored window counts as active: the hour-floor heuristic can be hours
|
|
1030
|
+
// off the real boundary, so without live data no block is presented as current.
|
|
1031
|
+
const active = b.real === true && nowMs < endMs;
|
|
1032
|
+
// Floored at 1 so a block opened seconds ago doesn't project an absurd rate.
|
|
1033
|
+
const elapsedMin = active ? Math.max(1, (nowMs - b.startMs) / 60000) : null;
|
|
1034
|
+
return {
|
|
1035
|
+
start: new Date(b.startMs).toISOString(),
|
|
1036
|
+
end: new Date(endMs).toISOString(),
|
|
1037
|
+
lastActivity: new Date(b.lastMs).toISOString(),
|
|
1038
|
+
cost: b.cost,
|
|
1039
|
+
tokens: b.tokens,
|
|
1040
|
+
messageCount: b.messageCount,
|
|
1041
|
+
models: [...b.models],
|
|
1042
|
+
active,
|
|
1043
|
+
burn: active
|
|
1044
|
+
? {
|
|
1045
|
+
costPerHour: (b.cost / elapsedMin) * 60,
|
|
1046
|
+
tokensPerMin: b.tokens / elapsedMin,
|
|
1047
|
+
projectedCost: (b.cost / elapsedMin) * (BLOCK_MS / 60000),
|
|
1048
|
+
remainingMin: Math.round((endMs - nowMs) / 60000),
|
|
1049
|
+
}
|
|
1050
|
+
: null,
|
|
1051
|
+
};
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
async function getInsightsData(range, projectFilter) {
|
|
1056
|
+
const cacheKey = `insights_${rangeKey(range)}_${projectFilter || 'all'}`;
|
|
1057
|
+
const cached = getCache(cacheKey);
|
|
1058
|
+
if (cached !== undefined) return cached;
|
|
1059
|
+
|
|
1060
|
+
const pricing = await fetchPricing();
|
|
1061
|
+
const w = resolveWindow(range);
|
|
1062
|
+
|
|
1063
|
+
// The heatmap covers the last 7 real days ending at the selected window's end — each row
|
|
1064
|
+
// is an actual date, so a short range (today, 3d) still shows a full week of context.
|
|
1065
|
+
const windowEnd = w.end < w.now ? w.end : w.now;
|
|
1066
|
+
const hmStart = new Date(windowEnd);
|
|
1067
|
+
hmStart.setHours(0, 0, 0, 0);
|
|
1068
|
+
hmStart.setDate(hmStart.getDate() - (HEATMAP_DAYS - 1));
|
|
1069
|
+
const hmStartStr = hmStart.toISOString();
|
|
1070
|
+
const scanCutoff = w.cutoff === null ? null : w.cutoff < hmStart ? w.cutoff : hmStart;
|
|
1071
|
+
const projects = scanProjectDirs(scanCutoff, projectFilter);
|
|
1072
|
+
|
|
1073
|
+
// When the cost window already covers the heatmap window, the heatmap rows are a subset of
|
|
1074
|
+
// `all` — filter it instead of re-scanning every session a second time.
|
|
1075
|
+
const hmInAll = w.cutoff === null || w.cutoff <= hmStart;
|
|
1076
|
+
const allParts = [];
|
|
1077
|
+
const hmParts = [];
|
|
1078
|
+
for (const [, proj] of projects) {
|
|
1079
|
+
const sessions = await loadProjectData(proj.files, pricing);
|
|
1080
|
+
for (const [, session] of sessions) {
|
|
1081
|
+
allParts.push(filterWindow(session.messages, w.cutoffStr, w.endStr));
|
|
1082
|
+
if (!hmInAll) hmParts.push(filterWindow(session.messages, hmStartStr, w.endStr));
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
const all = allParts.flat().sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
1086
|
+
const hmMsgs = hmInAll ? all.filter((m) => m.timestamp >= hmStartStr) : hmParts.flat();
|
|
1087
|
+
|
|
1088
|
+
const sum = summarizeMessages(all);
|
|
1089
|
+
const tokens = { input: sum.inputTokens, output: sum.outputTokens, cacheCreation: sum.cacheCreationTokens, cacheRead: sum.cacheReadTokens };
|
|
1090
|
+
let cacheSavings = 0;
|
|
1091
|
+
// One row per real day, oldest first; row index = whole days since hmStart.
|
|
1092
|
+
const heatmap = Array.from({ length: HEATMAP_DAYS }, () => new Array(24).fill(0));
|
|
1093
|
+
const heatmapDays = Array.from({ length: HEATMAP_DAYS }, (_, i) => {
|
|
1094
|
+
const d = new Date(hmStart);
|
|
1095
|
+
d.setDate(d.getDate() + i);
|
|
1096
|
+
return localDateStr(d);
|
|
1097
|
+
});
|
|
1098
|
+
const toolCounts = {};
|
|
1099
|
+
let mainCost = 0;
|
|
1100
|
+
let subagentCost = 0;
|
|
1101
|
+
const weekly = {};
|
|
1102
|
+
|
|
1103
|
+
// getModelPricing falls back to a linear scan of the whole LiteLLM map on a miss, so resolve
|
|
1104
|
+
// it once per distinct model rather than once per message.
|
|
1105
|
+
const priceMemo = new Map();
|
|
1106
|
+
for (const m of all) {
|
|
1107
|
+
// What the same tokens would have cost as fresh input, minus what cache reads actually cost.
|
|
1108
|
+
if (m.cacheReadTokens > 0) {
|
|
1109
|
+
if (!priceMemo.has(m.model)) priceMemo.set(m.model, getModelPricing(pricing, m.model));
|
|
1110
|
+
const mp = priceMemo.get(m.model);
|
|
1111
|
+
if (mp?.input_cost_per_token != null && mp?.cache_read_input_token_cost != null) {
|
|
1112
|
+
cacheSavings += m.cacheReadTokens * (mp.input_cost_per_token - mp.cache_read_input_token_cost);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
const monday = new Date(m.timestamp);
|
|
1117
|
+
monday.setHours(0, 0, 0, 0);
|
|
1118
|
+
monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7));
|
|
1119
|
+
const wk = localDateStr(monday);
|
|
1120
|
+
weekly[wk] = (weekly[wk] || 0) + m.cost;
|
|
1121
|
+
|
|
1122
|
+
if (m._subagent) {
|
|
1123
|
+
subagentCost += m.cost;
|
|
1124
|
+
} else {
|
|
1125
|
+
mainCost += m.cost;
|
|
1126
|
+
if (m.tools) for (const t of m.tools) toolCounts[t] = (toolCounts[t] || 0) + 1;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
for (const m of hmMsgs) {
|
|
1131
|
+
const d = new Date(m.timestamp);
|
|
1132
|
+
const day = new Date(d);
|
|
1133
|
+
day.setHours(0, 0, 0, 0);
|
|
1134
|
+
// Round to survive DST shifts making a "day" 23/25 hours.
|
|
1135
|
+
const idx = Math.round((day - hmStart) / 86400000);
|
|
1136
|
+
if (idx >= 0 && idx < HEATMAP_DAYS) heatmap[idx][d.getHours()] += m.cost;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
const limits = readRateLimits(w.now);
|
|
1140
|
+
// A window ending in the past has no "current" block — don't synthesize the live window there.
|
|
1141
|
+
const blocks = computeBlocks(all, w.now, w.hasToday ? limits?.resetsAtMs || null : null);
|
|
1142
|
+
const activeBlk = blocks.find((b) => b.active);
|
|
1143
|
+
if (activeBlk) activeBlk.usedPct = limits?.usedPct ?? null;
|
|
1144
|
+
|
|
1145
|
+
// Run-rate over the window actually observed: a custom window ending in the past uses its own
|
|
1146
|
+
// span; open-ended ranges run from the first message (all-time) or the cutoff to now.
|
|
1147
|
+
const windowStart = w.cutoff || (all.length ? new Date(all[0].timestamp) : w.now);
|
|
1148
|
+
const dayCount = Math.max(1, Math.ceil((windowEnd - windowStart) / 86400000));
|
|
1149
|
+
const dailyAvg = sum.totalCost / dayCount;
|
|
1150
|
+
|
|
1151
|
+
const result = {
|
|
1152
|
+
tokens,
|
|
1153
|
+
cacheSavings,
|
|
1154
|
+
runRate: { dailyAvg, projectedMonthly: dailyAvg * 30, days: dayCount },
|
|
1155
|
+
blocks,
|
|
1156
|
+
heatmap,
|
|
1157
|
+
heatmapDays,
|
|
1158
|
+
heatmapToday: localDateStr(w.now),
|
|
1159
|
+
tools: Object.entries(toolCounts)
|
|
1160
|
+
.map(([name, count]) => ({ name, count }))
|
|
1161
|
+
.sort((a, b) => b.count - a.count)
|
|
1162
|
+
.slice(0, MAX_TOOLS),
|
|
1163
|
+
subagents: { mainCost, subagentCost },
|
|
1164
|
+
weekly: Object.entries(weekly)
|
|
1165
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
1166
|
+
.map(([weekStart, cost]) => ({ weekStart, cost })),
|
|
1167
|
+
};
|
|
1168
|
+
|
|
1169
|
+
setCache(cacheKey, result);
|
|
1170
|
+
return result;
|
|
1171
|
+
}
|
|
1172
|
+
|
|
948
1173
|
// #endregion
|
|
949
1174
|
|
|
950
1175
|
// #region EXPRESS
|
|
@@ -1032,6 +1257,18 @@ app.get('/api/overview', withRange(30), async (req, res) => {
|
|
|
1032
1257
|
}
|
|
1033
1258
|
});
|
|
1034
1259
|
|
|
1260
|
+
app.get('/api/insights', withRange(30), async (req, res) => {
|
|
1261
|
+
try {
|
|
1262
|
+
const project = parseProject(req.query.project);
|
|
1263
|
+
if (project === null) return res.status(400).json({ error: 'Invalid project' });
|
|
1264
|
+
const data = await getInsightsData(req.range, project);
|
|
1265
|
+
res.json(data);
|
|
1266
|
+
} catch (err) {
|
|
1267
|
+
console.error('[API] insights error:', err);
|
|
1268
|
+
res.status(500).json({ error: 'Failed to load insights data' });
|
|
1269
|
+
}
|
|
1270
|
+
});
|
|
1271
|
+
|
|
1035
1272
|
app.get('/api/projects', withRange(), async (req, res) => {
|
|
1036
1273
|
try {
|
|
1037
1274
|
const project = parseProject(req.query.project);
|