-
Notifications
You must be signed in to change notification settings - Fork 342
Expand file tree
/
Copy pathdashboard.py
More file actions
1808 lines (1665 loc) · 84 KB
/
Copy pathdashboard.py
File metadata and controls
1808 lines (1665 loc) · 84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
dashboard.py - Local web dashboard served on localhost:8080.
"""
import json
import os
import sqlite3
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
from pathlib import Path
from datetime import datetime
from scanner import VERSION
DB_PATH = Path.home() / ".claude" / "usage.db"
# Which surface is rendering the dashboard: "web" (standalone `cli.py dashboard`)
# or "vscode" (embedded in the extension's sidebar webview). serve() sets this
# from the --surface flag the extension passes. The footer reads it to decide
# what to show — the web build promotes the VS Code extension and offers a
# "check GitHub for a newer release" update link; the embedded build shows just
# the version (VS Code updates the extension itself, and a GitHub-release check
# would misfire there because the Marketplace publish lags the GitHub release).
SURFACE = "web"
def get_dashboard_data(db_path=DB_PATH):
if not db_path.exists():
return {"error": "Database not found. Run: python cli.py scan"}
conn = sqlite3.connect(db_path)
# The dashboard reads while a background scan may be committing (cmd_dashboard
# serves first, scans in a background thread; /api/rescan scans in-process too).
# Wait briefly for write locks instead of raising "database is locked".
conn.execute("PRAGMA busy_timeout = 5000")
conn.row_factory = sqlite3.Row
# ── All models (for filter UI) ────────────────────────────────────────────
# GROUP BY uses the normalised expression too so NULL and '' don't end up
# as two separate "unknown" rows.
model_rows = conn.execute("""
SELECT COALESCE(NULLIF(model, ''), 'unknown') as model
FROM turns
GROUP BY COALESCE(NULLIF(model, ''), 'unknown')
ORDER BY SUM(input_tokens + output_tokens) DESC
""").fetchall()
all_models = [r["model"] for r in model_rows]
# ── Daily per-model, ALL history (client filters by range) ────────────────
daily_rows = conn.execute("""
SELECT
substr(timestamp, 1, 10) as day,
COALESCE(NULLIF(model, ''), 'unknown') as model,
SUM(input_tokens) as input,
SUM(output_tokens) as output,
SUM(cache_read_tokens) as cache_read,
SUM(cache_creation_tokens) as cache_creation,
COUNT(*) as turns
FROM turns
GROUP BY day, COALESCE(NULLIF(model, ''), 'unknown')
ORDER BY day, model
""").fetchall()
daily_by_model = [{
"day": r["day"],
"model": r["model"],
"input": r["input"] or 0,
"output": r["output"] or 0,
"cache_read": r["cache_read"] or 0,
"cache_creation": r["cache_creation"] or 0,
"turns": r["turns"] or 0,
} for r in daily_rows]
# ── Hourly per-day per-model (client filters by range + TZ-shifts) ────────
# Timestamps are ISO8601 UTC (e.g. "2026-04-08T09:30:00Z"); chars 12-13 = hour.
hourly_rows = conn.execute("""
SELECT
substr(timestamp, 1, 10) as day,
CAST(substr(timestamp, 12, 2) AS INTEGER) as hour,
COALESCE(NULLIF(model, ''), 'unknown') as model,
SUM(output_tokens) as output,
COUNT(*) as turns
FROM turns
WHERE timestamp IS NOT NULL AND length(timestamp) >= 13
GROUP BY day, hour, COALESCE(NULLIF(model, ''), 'unknown')
ORDER BY day, hour, model
""").fetchall()
hourly_by_model = [{
"day": r["day"],
"hour": r["hour"] if r["hour"] is not None else 0,
"model": r["model"],
"output": r["output"] or 0,
"turns": r["turns"] or 0,
} for r in hourly_rows]
# ── All sessions (client filters by range and model) ──────────────────────
session_rows = conn.execute("""
SELECT
session_id, project_name, first_timestamp, last_timestamp,
total_input_tokens, total_output_tokens,
total_cache_read, total_cache_creation, model, turn_count,
git_branch
FROM sessions
ORDER BY last_timestamp DESC
""").fetchall()
sessions_all = []
for r in session_rows:
try:
t1 = datetime.fromisoformat(r["first_timestamp"].replace("Z", "+00:00"))
t2 = datetime.fromisoformat(r["last_timestamp"].replace("Z", "+00:00"))
duration_min = round((t2 - t1).total_seconds() / 60, 1)
except Exception:
duration_min = 0
sessions_all.append({
"session_id": r["session_id"][:8],
"project": r["project_name"] or "unknown",
"branch": r["git_branch"] or "",
"last": (r["last_timestamp"] or "")[:16].replace("T", " "),
"last_date": (r["last_timestamp"] or "")[:10],
"duration_min": duration_min,
"model": r["model"] or "unknown",
"turns": r["turn_count"] or 0,
"input": r["total_input_tokens"] or 0,
"output": r["total_output_tokens"] or 0,
"cache_read": r["total_cache_read"] or 0,
"cache_creation": r["total_cache_creation"] or 0,
})
conn.close()
return {
"all_models": all_models,
"daily_by_model": daily_by_model,
"hourly_by_model": hourly_by_model,
"sessions_all": sessions_all,
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
HTML_TEMPLATE = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Claude Code Usage Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>window.APP_CONFIG = __APP_CONFIG_JSON__;</script>
<style>
:root {
--bg: #161617; /* page base */
--card: #1E1F20; /* raised one step above the page */
--border: #2C2D2E;
--text: #BFBFBF;
--muted: #4F4F50;
--accent: #d97757;
--blue: #48A0C7;
--green: #74C991;
--red: #C74E39;
--raised: #2E2F31; /* hover / raised surfaces — top of the elevation ladder */
--selected: #262626; /* selected chips / tabs (neutral, not accent) */
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: var(--bg); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; }
/* VS Code-style scrollbars. The dashboard renders inside a webview iframe,
which doesn't inherit VS Code's --vscode-* theme variables, so we set the
scrollbar here: no arrows, grey thumb (#28292B, #8B8B8D on hover) over a
#121314 track, in a 21px gutter. Also fits the dark UI standalone. */
* { scrollbar-width: auto; scrollbar-color: #28292B #121314; }
::-webkit-scrollbar { width: 21px; height: 21px; }
::-webkit-scrollbar-track { background: #121314; }
::-webkit-scrollbar-thumb { background-color: #28292B; border: 3px solid transparent; background-clip: padding-box; }
::-webkit-scrollbar-thumb:hover { background-color: #8B8B8D; }
::-webkit-scrollbar-thumb:active { background-color: #8B8B8D; }
::-webkit-scrollbar-corner { background: #121314; }
header { background: var(--card); border-bottom: 1px solid var(--border); padding: 16px 24px; display: flex; align-items: center; justify-content: space-between; }
header h1 { font-size: 18px; font-weight: 600; color: var(--text); }
header .header-title { display: flex; align-items: center; gap: 10px; }
/* The icon is a monochrome silhouette (white shape on transparent). We paint
it with the title color via a CSS mask + background-color, so it matches
`header h1` — the lightest text color. */
header .header-icon {
width: 26px; height: 26px; flex-shrink: 0; display: block;
background-color: var(--text);
-webkit-mask: url("icon.svg") no-repeat center / contain;
mask: url("icon.svg") no-repeat center / contain;
}
header .meta { color: var(--muted); font-size: 12px; text-align: right; line-height: 1.5; margin-right: 20px; }
#rescan-btn { background: var(--card); border: 1px solid var(--border); color: var(--muted); padding: 4px 12px; border-radius: 6px; cursor: pointer; font-size: 12px; margin-top: 4px; }
#rescan-btn:hover { color: var(--text); border-color: var(--accent); }
#rescan-btn:disabled { opacity: 0.5; cursor: not-allowed; }
#filter-bar { background: var(--card); border-bottom: 1px solid var(--border); padding: 10px 24px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.filter-label { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); white-space: nowrap; }
.filter-sep { width: 1px; height: 22px; background: var(--border); flex-shrink: 0; }
/* Model multi-select: a compact trigger in the bar that opens a grouped panel. */
.model-select { position: relative; flex-shrink: 0; }
.model-trigger { display: flex; align-items: center; gap: 8px; min-width: 170px; max-width: 320px; padding: 5px 10px; background: var(--card); border: 1px solid var(--border); border-radius: 6px; color: var(--text); font-size: 12px; cursor: pointer; transition: border-color 0.15s; }
.model-trigger:hover, .model-trigger.open { border-color: var(--accent); }
#model-trigger-label { flex: 1; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.model-caret { color: var(--muted); font-size: 10px; flex-shrink: 0; transition: transform 0.15s; }
.model-trigger.open .model-caret { transform: rotate(180deg); }
.model-panel { position: absolute; top: calc(100% + 6px); left: 0; z-index: 50; min-width: 250px; max-width: 340px; max-height: 360px; overflow-y: auto; background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 8px; box-shadow: 0 8px 24px rgba(0,0,0,0.35); }
.model-panel[hidden] { display: none; }
.model-panel-actions { display: flex; gap: 6px; padding-bottom: 8px; margin-bottom: 4px; border-bottom: 1px solid var(--border); }
.model-group-label { font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); padding: 8px 8px 4px; }
.model-cb-label { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 6px; cursor: pointer; font-size: 12px; color: var(--muted); transition: background 0.12s, color 0.12s; user-select: none; }
.model-cb-label:hover { background: var(--raised); color: var(--text); }
.model-cb-label.checked { color: var(--text); }
.model-cb-label input { display: none; }
.model-cb-box { width: 15px; height: 15px; flex-shrink: 0; border-radius: 4px; border: 1px solid var(--border); display: flex; align-items: center; justify-content: center; font-size: 10px; line-height: 1; color: transparent; transition: background 0.12s, border-color 0.12s; }
.model-cb-label.checked .model-cb-box { background: var(--accent); border-color: var(--accent); color: #fff; }
.model-cb-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.filter-btn { padding: 3px 10px; border-radius: 4px; border: 1px solid var(--border); background: transparent; color: var(--muted); font-size: 11px; cursor: pointer; white-space: nowrap; }
.filter-btn:hover { border-color: var(--accent); color: var(--text); }
.range-group { display: flex; border: 1px solid var(--border); border-radius: 6px; overflow: hidden; flex-shrink: 0; }
.range-btn { padding: 4px 13px; background: transparent; border: none; border-right: 1px solid var(--border); color: var(--muted); font-size: 12px; cursor: pointer; transition: background 0.15s, color 0.15s; }
.range-btn:last-child { border-right: none; }
.range-btn:hover { background: var(--raised); color: var(--text); }
.range-btn.active { background: var(--selected); color: var(--text); font-weight: 600; }
.container { max-width: 1400px; margin: 0 auto; padding: 24px; }
.stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; margin-bottom: 24px; }
.stat-card { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 16px; }
.stat-card .label { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 6px; }
.stat-card .value { font-size: 22px; font-weight: 700; }
.stat-card .sub { color: var(--muted); font-size: 11px; margin-top: 4px; }
.charts-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px; }
/* min-width:0 lets the grid column shrink below the canvas's intrinsic
pixel width; without it, narrowing the window can't narrow the container,
so Chart.js's ResizeObserver never fires until a data refresh rebuilds the
canvas. (Expanding already works — 1fr columns grow freely.) */
.chart-card { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 20px; min-width: 0; }
.chart-card.wide { grid-column: 1 / -1; }
.chart-card h2 { font-size: 13px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 16px; }
.chart-wrap { position: relative; height: 240px; }
.chart-wrap.tall { height: 300px; }
.chart-header { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 16px; }
.chart-header h2 { margin-bottom: 0; }
.chart-header-right { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.chart-day-count { font-size: 11px; color: var(--muted); }
.tz-group { display: flex; border: 1px solid var(--border); border-radius: 6px; overflow: hidden; }
.tz-btn { padding: 3px 10px; background: transparent; border: none; border-right: 1px solid var(--border); color: var(--muted); font-size: 11px; cursor: pointer; transition: background 0.15s, color 0.15s; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 600; }
.tz-btn:last-child { border-right: none; }
.tz-btn:hover { background: var(--raised); color: var(--text); }
.tz-btn.active { background: var(--selected); color: var(--text); }
.peak-legend { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--muted); }
.peak-swatch { width: 10px; height: 10px; background: var(--red); border-radius: 2px; display: inline-block; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; padding: 8px 12px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); border-bottom: 1px solid var(--border); white-space: nowrap; }
th.sortable { cursor: pointer; user-select: none; }
th.sortable:hover { color: var(--text); }
.sort-icon { font-size: 9px; opacity: 0.8; }
td { padding: 10px 12px; border-bottom: 1px solid var(--border); font-size: 13px; }
tr:last-child td { border-bottom: none; }
tr:hover td { background: var(--raised); }
.model-tag { display: inline-block; padding: 2px 7px; border-radius: 4px; font-size: 11px; background: rgba(72,160,199,0.15); color: var(--blue); }
.cost { color: var(--green); font-family: monospace; }
.cost-na { color: var(--muted); font-family: monospace; font-size: 11px; }
.num { font-family: monospace; }
.muted { color: var(--muted); }
.section-title { font-size: 13px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 12px; }
.section-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.section-header .section-title { margin-bottom: 0; }
.export-btn { background: var(--card); border: 1px solid var(--border); color: var(--muted); padding: 3px 10px; border-radius: 5px; cursor: pointer; font-size: 11px; }
.export-btn:hover { color: var(--text); border-color: var(--accent); }
.table-card { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 20px; margin-bottom: 24px; overflow-x: auto; }
.table-foot { display: flex; justify-content: flex-end; align-items: center; gap: 12px; margin-top: 12px; }
.table-foot:empty { margin-top: 0; }
.show-more-btn { background: transparent; border: 1px solid var(--border); color: var(--muted); padding: 4px 12px; border-radius: 6px; cursor: pointer; font-size: 12px; }
.show-more-btn:hover { color: var(--text); border-color: var(--accent); }
.show-more-link { color: var(--blue); text-decoration: none; font-size: 12px; cursor: pointer; }
.show-more-link:hover { text-decoration: underline; }
footer { border-top: 1px solid var(--border); padding: 20px 24px; margin-top: 8px; }
.footer-content { max-width: 1400px; margin: 0 auto; }
.footer-content p { color: var(--muted); font-size: 12px; line-height: 1.7; margin-bottom: 4px; }
.footer-content p:last-child { margin-bottom: 0; }
.footer-content a { color: var(--blue); text-decoration: none; }
.footer-content a:hover { text-decoration: underline; }
.footer-content a.update-link { color: var(--accent); font-weight: 600; }
@media (max-width: 768px) { .charts-grid { grid-template-columns: 1fr; } .chart-card.wide { grid-column: 1; } }
</style>
</head>
<body>
<header>
<div class="header-title">
<span class="header-icon" role="img" aria-label="Claude Usage"></span>
<h1>Claude Code Usage</h1>
</div>
<div class="meta" id="meta">Loading...</div>
<button id="rescan-btn" onclick="triggerRescan()" title="Scan for new usage since the last update. Adds new turns without affecting existing history.">↻ Rescan</button>
</header>
<div id="filter-bar">
<div class="filter-label">Models</div>
<div class="model-select" id="model-select">
<button class="model-trigger" id="model-trigger" aria-haspopup="true" aria-expanded="false" onclick="toggleModelPanel(event)">
<span id="model-trigger-label">All models</span>
<span class="model-caret">▾</span>
</button>
<div class="model-panel" id="model-panel" hidden>
<div class="model-panel-actions">
<button class="filter-btn" onclick="selectAllModels()">All</button>
<button class="filter-btn" onclick="clearAllModels()">None</button>
</div>
<div id="model-checkboxes"></div>
</div>
</div>
<div class="filter-sep"></div>
<div class="filter-label">Range</div>
<div class="range-group">
<button class="range-btn" data-range="today" onclick="setRange('today')">Today</button>
<button class="range-btn" data-range="week" onclick="setRange('week')">This Week</button>
<button class="range-btn" data-range="month" onclick="setRange('month')">This Month</button>
<button class="range-btn" data-range="prev-month" onclick="setRange('prev-month')">Prev Month</button>
<button class="range-btn" data-range="7d" onclick="setRange('7d')">7d</button>
<button class="range-btn" data-range="30d" onclick="setRange('30d')">30d</button>
<button class="range-btn" data-range="90d" onclick="setRange('90d')">90d</button>
<button class="range-btn" data-range="all" onclick="setRange('all')">All</button>
</div>
</div>
<div class="container">
<div class="stats-row" id="stats-row"></div>
<div class="charts-grid">
<div class="chart-card wide">
<h2 id="daily-chart-title">Daily Token Usage</h2>
<div class="chart-wrap tall"><canvas id="chart-daily"></canvas></div>
</div>
<div class="chart-card wide">
<div class="chart-header">
<h2 id="hourly-chart-title">Average Hourly Distribution</h2>
<div class="chart-header-right">
<span class="peak-legend" title="Mon–Fri 05:00–11:00 PT — Anthropic peak-hour throttling window"><span class="peak-swatch"></span>Peak hours (PT)</span>
<span class="chart-day-count" id="hourly-day-count"></span>
<div class="tz-group">
<button class="tz-btn" data-tz="local" onclick="setHourlyTZ('local')">Local</button>
<button class="tz-btn" data-tz="utc" onclick="setHourlyTZ('utc')">UTC</button>
</div>
</div>
</div>
<div class="chart-wrap"><canvas id="chart-hourly"></canvas></div>
</div>
<div class="chart-card">
<h2>By Model</h2>
<div class="chart-wrap"><canvas id="chart-model"></canvas></div>
</div>
<div class="chart-card">
<h2>Top Projects by Tokens</h2>
<div class="chart-wrap"><canvas id="chart-project"></canvas></div>
</div>
</div>
<div class="table-card">
<div class="section-title">Cost by Model</div>
<table>
<thead><tr>
<th>Model</th>
<th class="sortable" onclick="setModelSort('turns')">Turns <span class="sort-icon" id="msort-turns"></span></th>
<th class="sortable" onclick="setModelSort('input')">Input <span class="sort-icon" id="msort-input"></span></th>
<th class="sortable" onclick="setModelSort('output')">Output <span class="sort-icon" id="msort-output"></span></th>
<th class="sortable" onclick="setModelSort('cache_read')">Cache Read <span class="sort-icon" id="msort-cache_read"></span></th>
<th class="sortable" onclick="setModelSort('cache_creation')">Cache Creation <span class="sort-icon" id="msort-cache_creation"></span></th>
<th class="sortable" onclick="setModelSort('cost')">Est. Cost <span class="sort-icon" id="msort-cost"></span></th>
</tr></thead>
<tbody id="model-cost-body"></tbody>
</table>
<div class="table-foot" id="model-cost-foot"></div>
</div>
<div class="table-card">
<div class="section-header"><div class="section-title">Recent Sessions</div><button class="export-btn" onclick="exportSessionsCSV()" title="Export all filtered sessions to CSV">⤓ CSV</button></div>
<table>
<thead><tr>
<th>Session</th>
<th>Project</th>
<th class="sortable" onclick="setSessionSort('last')">Last Active <span class="sort-icon" id="sort-icon-last"></span></th>
<th class="sortable" onclick="setSessionSort('duration_min')">Duration <span class="sort-icon" id="sort-icon-duration_min"></span></th>
<th>Model</th>
<th class="sortable" onclick="setSessionSort('turns')">Turns <span class="sort-icon" id="sort-icon-turns"></span></th>
<th class="sortable" onclick="setSessionSort('input')">Input <span class="sort-icon" id="sort-icon-input"></span></th>
<th class="sortable" onclick="setSessionSort('output')">Output <span class="sort-icon" id="sort-icon-output"></span></th>
<th class="sortable" onclick="setSessionSort('cost')">Est. Cost <span class="sort-icon" id="sort-icon-cost"></span></th>
</tr></thead>
<tbody id="sessions-body"></tbody>
</table>
<div class="table-foot" id="sessions-foot"></div>
</div>
<div class="table-card">
<div class="section-header"><div class="section-title">Cost by Project</div><button class="export-btn" onclick="exportProjectsCSV()" title="Export all projects to CSV">⤓ CSV</button></div>
<table>
<thead><tr>
<th>Project</th>
<th class="sortable" onclick="setProjectSort('sessions')">Sessions <span class="sort-icon" id="psort-sessions"></span></th>
<th class="sortable" onclick="setProjectSort('turns')">Turns <span class="sort-icon" id="psort-turns"></span></th>
<th class="sortable" onclick="setProjectSort('input')">Input <span class="sort-icon" id="psort-input"></span></th>
<th class="sortable" onclick="setProjectSort('output')">Output <span class="sort-icon" id="psort-output"></span></th>
<th class="sortable" onclick="setProjectSort('cost')">Est. Cost <span class="sort-icon" id="psort-cost"></span></th>
</tr></thead>
<tbody id="project-cost-body"></tbody>
</table>
<div class="table-foot" id="project-cost-foot"></div>
</div>
<div class="table-card">
<div class="section-header"><div class="section-title">Cost by Project & Branch</div><button class="export-btn" onclick="exportProjectBranchCSV()" title="Export project+branch breakdown to CSV">⤓ CSV</button></div>
<table>
<thead><tr>
<th>Project</th>
<th>Branch</th>
<th class="sortable" onclick="setProjectBranchSort('sessions')">Sessions <span class="sort-icon" id="pbsort-sessions"></span></th>
<th class="sortable" onclick="setProjectBranchSort('turns')">Turns <span class="sort-icon" id="pbsort-turns"></span></th>
<th class="sortable" onclick="setProjectBranchSort('input')">Input <span class="sort-icon" id="pbsort-input"></span></th>
<th class="sortable" onclick="setProjectBranchSort('output')">Output <span class="sort-icon" id="pbsort-output"></span></th>
<th class="sortable" onclick="setProjectBranchSort('cost')">Est. Cost <span class="sort-icon" id="pbsort-cost"></span></th>
</tr></thead>
<tbody id="project-branch-cost-body"></tbody>
</table>
<div class="table-foot" id="project-branch-cost-foot"></div>
</div>
</div>
<footer>
<div class="footer-content">
<p>Cost estimates based on Anthropic API pricing (<a href="https://claude.com/pricing#api" target="_blank">claude.com/pricing#api</a>) as of June 2026. Only models containing <em>fable</em>, <em>mythos</em>, <em>opus</em>, <em>sonnet</em>, or <em>haiku</em> in the name are included in cost calculations. Actual costs for Max/Pro subscribers differ from API pricing.</p>
<p>
GitHub: <a href="https://github.com/phuryn/claude-usage" target="_blank">https://github.com/phuryn/claude-usage</a>
·
Created by: <a href="https://www.productcompass.pm" target="_blank">The Product Compass Newsletter</a>
·
License: MIT
</p>
<p id="footer-meta"></p>
</div>
</footer>
<script>
// ── Helpers ────────────────────────────────────────────────────────────────
function esc(s) {
const d = document.createElement('div');
d.textContent = String(s);
return d.innerHTML;
}
// ── State ──────────────────────────────────────────────────────────────────
let rawData = null;
let selectedModels = new Set();
let allModelsList = [];
let selectedRange = '30d';
let charts = {};
let sessionSortCol = 'last';
let modelSortCol = 'cost';
let modelSortDir = 'desc';
let projectSortCol = 'cost';
let projectSortDir = 'desc';
let branchSortCol = 'cost';
let branchSortDir = 'desc';
let lastFilteredSessions = [];
let lastByModel = [];
let lastByProject = [];
let lastByProjectBranch = [];
let sessionSortDir = 'desc';
// Tables reveal rows in steps: 10 -> 25 -> 50, capped at 50 because rendering
// more than that visibly hurts performance. Past 50 the footer offers a
// "Download CSV to see more" link instead of another in-table step, plus a
// Show less button that resets straight back to 10. Limits persist across
// re-renders so sorting/filtering keeps the user's chosen depth (visible rows
// always reflect the active sort).
const TABLE_STEPS = [10, 25, 50];
const TABLE_MAX = TABLE_STEPS[TABLE_STEPS.length - 1]; // hard cap on in-table rows
function nextTableLimit(current, total) {
for (const s of TABLE_STEPS) {
if (s > current && s < total) return s;
}
return Math.min(total, TABLE_MAX); // reveal everything, but never past the cap
}
let modelLimit = TABLE_STEPS[0];
let sessionsLimit = TABLE_STEPS[0];
let projectLimit = TABLE_STEPS[0];
let branchLimit = TABLE_STEPS[0];
let hourlyTZ = 'local'; // 'local' or 'utc'
// ── Peak-hour config ───────────────────────────────────────────────────────
// Anthropic throttles Mon–Fri 05:00–11:00 PT. We approximate as fixed UTC hours
// 12–17 (matches PDT; during PST the window shifts by 1h — accepted simplification).
const PEAK_HOURS_UTC = new Set([12, 13, 14, 15, 16, 17]);
// Local-timezone offset in hours (signed). Fractional offsets (e.g. India UTC+5:30)
// are rounded to the nearest hour for bucket alignment.
function localOffsetHours() {
return Math.round(-new Date().getTimezoneOffset() / 60);
}
// Return the UTC hour (0–23) corresponding to a displayed-hour bucket.
function displayHourToUTC(displayHour, tzMode) {
if (tzMode === 'utc') return displayHour;
return ((displayHour - localOffsetHours()) % 24 + 24) % 24;
}
// Return the displayed-hour bucket for a UTC hour.
function utcHourToDisplay(utcHour, tzMode) {
if (tzMode === 'utc') return utcHour;
return ((utcHour + localOffsetHours()) % 24 + 24) % 24;
}
function isPeakHour(displayHour, tzMode) {
return PEAK_HOURS_UTC.has(displayHourToUTC(displayHour, tzMode));
}
function formatHourLabel(h) {
return String(h).padStart(2, '0') + ':00';
}
function tzDisplayName(tzMode) {
if (tzMode === 'utc') return 'UTC';
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'Local';
} catch(e) {
return 'Local';
}
}
// ── Pricing (Anthropic API, June 2026) ─────────────────────────────────────
const PRICING = {
// Fable / Mythos — Anthropic's most capable class, priced at 2x Opus.
// (Mythos 5 shares Fable 5's pricing; Project-Glasswing access only.)
'claude-fable-5': { input: 10.00, output: 50.00, cache_write: 12.50, cache_read: 1.00 },
'claude-mythos-5': { input: 10.00, output: 50.00, cache_write: 12.50, cache_read: 1.00 },
'claude-opus-4-8': { input: 5.00, output: 25.00, cache_write: 6.25, cache_read: 0.50 },
'claude-opus-4-7': { input: 5.00, output: 25.00, cache_write: 6.25, cache_read: 0.50 },
'claude-opus-4-6': { input: 5.00, output: 25.00, cache_write: 6.25, cache_read: 0.50 },
'claude-opus-4-5': { input: 5.00, output: 25.00, cache_write: 6.25, cache_read: 0.50 },
'claude-sonnet-4-7': { input: 3.00, output: 15.00, cache_write: 3.75, cache_read: 0.30 },
'claude-sonnet-4-6': { input: 3.00, output: 15.00, cache_write: 3.75, cache_read: 0.30 },
'claude-sonnet-4-5': { input: 3.00, output: 15.00, cache_write: 3.75, cache_read: 0.30 },
'claude-haiku-4-7': { input: 1.00, output: 5.00, cache_write: 1.25, cache_read: 0.10 },
'claude-haiku-4-6': { input: 1.00, output: 5.00, cache_write: 1.25, cache_read: 0.10 },
'claude-haiku-4-5': { input: 1.00, output: 5.00, cache_write: 1.25, cache_read: 0.10 },
};
function isBillable(model) {
if (!model) return false;
const m = model.toLowerCase();
return m.includes('fable') || m.includes('mythos') ||
m.includes('opus') || m.includes('sonnet') || m.includes('haiku');
}
function getPricing(model) {
if (!model) return null;
if (PRICING[model]) return PRICING[model];
for (const key of Object.keys(PRICING)) {
if (model.startsWith(key)) return PRICING[key];
}
const m = model.toLowerCase();
if (m.includes('fable') || m.includes('mythos')) return PRICING['claude-fable-5'];
if (m.includes('opus')) return PRICING['claude-opus-4-8'];
if (m.includes('sonnet')) return PRICING['claude-sonnet-4-6'];
if (m.includes('haiku')) return PRICING['claude-haiku-4-5'];
return null;
}
function calcCost(model, inp, out, cacheRead, cacheCreation) {
if (!isBillable(model)) return 0;
const p = getPricing(model);
if (!p) return 0;
return (
inp * p.input / 1e6 +
out * p.output / 1e6 +
cacheRead * p.cache_read / 1e6 +
cacheCreation * p.cache_write / 1e6
);
}
// ── Formatting ─────────────────────────────────────────────────────────────
function fmt(n) {
if (n >= 1e9) return (n/1e9).toFixed(2)+'B';
if (n >= 1e6) return (n/1e6).toFixed(2)+'M';
if (n >= 1e3) return (n/1e3).toFixed(1)+'K';
return n.toLocaleString();
}
function fmtCost(c) { return '$' + c.toLocaleString(undefined, { minimumFractionDigits: 4, maximumFractionDigits: 4 }); }
function fmtCostBig(c) { return '$' + c.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
// ── Chart colors ───────────────────────────────────────────────────────────
// Warm/neutral palette kept in sync with the CSS :root variables so charts match
// the Claude Code interface (less blue). Chart legends/axes use C.axis (a touch
// lighter than --muted so small labels stay legible on the dark card); grid uses
// C.border.
const C = {
text: '#BFBFBF',
muted: '#4F4F50',
axis: '#6F6F70',
border: '#2C2D2E',
card: '#1E1F20',
blue: '#48A0C7',
green: '#74C991',
red: '#C74E39',
accent: '#d97757',
amber: '#D9A84E',
purple: '#9B7EC7',
teal: '#5BB8A3',
mauve: '#C77E9B',
};
const TOKEN_COLORS = {
input: 'rgba(72,160,199,0.85)', // blue
output: 'rgba(217,119,87,0.85)', // accent / coral
cache_read: 'rgba(116,201,145,0.75)', // green
cache_creation: 'rgba(217,168,78,0.75)', // amber
};
// Hover lifts on a dark theme: bars/series go to full opacity (a touch brighter).
const TOKEN_HOVER = {
input: 'rgba(72,160,199,1)',
output: 'rgba(217,119,87,1)',
cache_read: 'rgba(116,201,145,1)',
cache_creation: 'rgba(217,168,78,1)',
};
// Donut / categorical palette — warm, Anthropic-leaning (clay, tan, sage, dusty
// blue, mauve, ochre, taupe, terracotta) rather than a saturated rainbow.
const MODEL_COLORS = ['#D97757','#C9A26B','#7FA98C','#6E97A8','#B98AA0','#D9A84E','#A88B6A','#C2705A'];
// Tooltip color swatches: solid fill, no border (Chart.js's default draws a
// bordered box that looked offset/inconsistent). Lines use their solid stroke
// color instead of the translucent area fill.
Chart.defaults.color = C.axis;
// multiKeyBackground defaults to white and is drawn behind each tooltip swatch,
// peeking out as a thin white border on plain-box charts — make it transparent.
Chart.defaults.plugins.tooltip.multiKeyBackground = 'transparent';
Chart.defaults.plugins.tooltip.callbacks.labelColor = (ctx) => {
const ds = ctx.dataset || {};
let col = Array.isArray(ds.backgroundColor) ? ds.backgroundColor[ctx.dataIndex] : ds.backgroundColor;
if (ds.type === 'line') col = ds.borderColor;
return { borderColor: col, backgroundColor: col, borderWidth: 0 };
};
// Legend visibility must survive repaints (filter changes, auto-refresh, sort) —
// the charts are destroyed and rebuilt each render, which otherwise resets any
// series the user toggled off. We track hidden series by label per chart and
// reapply on rebuild: dataset charts via `dataset.hidden`, the doughnut via
// per-slice data visibility (see applyModelHidden).
const hiddenSeries = { daily: new Set(), hourly: new Set(), project: new Set(), model: new Set() };
function legendToggle(key) {
return (e, item, legend) => {
const ci = legend.chart;
const ds = ci.data.datasets[item.datasetIndex];
ds.hidden = !ds.hidden;
if (ds.hidden) hiddenSeries[key].add(ds.label); else hiddenSeries[key].delete(ds.label);
ci.update();
};
}
// ── Time range ─────────────────────────────────────────────────────────────
const RANGE_LABELS = { 'today': 'Today', 'week': 'This Week', 'month': 'This Month', 'prev-month': 'Previous Month', '7d': 'Last 7 Days', '30d': 'Last 30 Days', '90d': 'Last 90 Days', 'all': 'All Time' };
const RANGE_TICKS = { 'today': 1, 'week': 7, 'month': 15, 'prev-month': 15, '7d': 7, '30d': 15, '90d': 13, 'all': 12 };
const VALID_RANGES = Object.keys(RANGE_LABELS);
function rangeIncludesToday(range) {
if (range === 'all') return true;
const { start, end } = getRangeBounds(range);
const today = new Date().toISOString().slice(0, 10);
if (start && today < start) return false;
if (end && today > end) return false;
return true;
}
function getRangeBounds(range) {
if (range === 'all') return { start: null, end: null };
const today = new Date();
const iso = d => d.toISOString().slice(0, 10);
if (range === 'today') {
const t = iso(today);
return { start: t, end: t };
}
if (range === 'week') {
const day = today.getDay();
const diffToMon = day === 0 ? 6 : day - 1;
const mon = new Date(today); mon.setDate(today.getDate() - diffToMon);
const sun = new Date(mon); sun.setDate(mon.getDate() + 6);
return { start: iso(mon), end: iso(sun) };
}
if (range === 'month') {
const start = new Date(today.getFullYear(), today.getMonth(), 1);
const end = new Date(today.getFullYear(), today.getMonth() + 1, 0);
return { start: iso(start), end: iso(end) };
}
if (range === 'prev-month') {
const start = new Date(today.getFullYear(), today.getMonth() - 1, 1);
const end = new Date(today.getFullYear(), today.getMonth(), 0);
return { start: iso(start), end: iso(end) };
}
const days = range === '7d' ? 7 : range === '30d' ? 30 : 90;
const d = new Date();
d.setDate(d.getDate() - days);
return { start: iso(d), end: null };
}
function readURLRange() {
const p = new URLSearchParams(window.location.search).get('range');
return VALID_RANGES.includes(p) ? p : '30d';
}
function setRange(range) {
selectedRange = range;
document.querySelectorAll('.range-btn').forEach(btn =>
btn.classList.toggle('active', btn.dataset.range === range)
);
updateURL();
applyFilter();
scheduleAutoRefresh();
}
function setHourlyTZ(mode) {
hourlyTZ = mode;
document.querySelectorAll('.tz-btn').forEach(btn =>
btn.classList.toggle('active', btn.dataset.tz === mode)
);
applyFilter();
}
// ── Model filter ───────────────────────────────────────────────────────────
function modelPriority(m) {
const ml = m.toLowerCase();
if (ml.includes('fable') || ml.includes('mythos')) return 0;
if (ml.includes('opus')) return 1;
if (ml.includes('sonnet')) return 2;
if (ml.includes('haiku')) return 3;
return 4;
}
function sortedModels(models) {
return [...models].sort((a, b) => {
const pa = modelPriority(a), pb = modelPriority(b);
return pa !== pb ? pa - pb : a.localeCompare(b);
});
}
// Compact display name for the collapsed trigger, e.g. "claude-opus-4-8" ->
// "Opus 4.8", "claude-fable-5" -> "Fable 5". Non-Anthropic ids fall back to the
// basename with any provider prefix and trailing date suffix stripped.
function shortModelName(m) {
const ml = m.toLowerCase();
let family = null;
if (ml.includes('fable')) family = 'Fable';
else if (ml.includes('mythos')) family = 'Mythos';
else if (ml.includes('opus')) family = 'Opus';
else if (ml.includes('sonnet')) family = 'Sonnet';
else if (ml.includes('haiku')) family = 'Haiku';
if (family) {
const two = m.match(/(\d+)[._-](\d+)/);
if (two) return family + ' ' + two[1] + '.' + two[2];
const one = m.match(/(\d+)/);
return one ? family + ' ' + one[1] : family;
}
let base = m.split('/').pop().split(':')[0];
base = base.replace(/[-_]?\d{6,}.*$/, '');
return base || m;
}
function readURLModels(allModels) {
const param = new URLSearchParams(window.location.search).get('models');
if (!param) {
const billable = allModels.filter(m => isBillable(m));
// Fallback: if the user only has non-billable / unknown models (e.g. all
// local-LLM runs), default to all models so the dashboard isn't blank.
return new Set(billable.length ? billable : allModels);
}
const fromURL = new Set(param.split(',').map(s => s.trim()).filter(Boolean));
return new Set(allModels.filter(m => fromURL.has(m)));
}
function isDefaultModelSelection(allModels) {
const billable = allModels.filter(m => isBillable(m));
const expected = billable.length ? billable : allModels;
if (selectedModels.size !== expected.length) return false;
return expected.every(m => selectedModels.has(m));
}
function buildFilterUI(allModels) {
allModelsList = [...allModels];
selectedModels = readURLModels(allModels);
const sorted = sortedModels(allModels);
const anthropic = sorted.filter(m => isBillable(m));
const other = sorted.filter(m => !isBillable(m));
const rowHTML = m => {
const checked = selectedModels.has(m);
return `<label class="model-cb-label ${checked ? 'checked' : ''}" data-model="${esc(m)}" title="${esc(m)}">
<input type="checkbox" value="${esc(m)}" ${checked ? 'checked' : ''} onchange="onModelToggle(this)">
<span class="model-cb-box">✓</span>
<span class="model-cb-text">${esc(m)}</span>
</label>`;
};
let html = '';
// Only show a group heading when both groups are present — a single-group
// list doesn't need a label.
const labelled = anthropic.length && other.length;
if (anthropic.length) {
if (labelled) html += '<div class="model-group-label">Anthropic</div>';
html += anthropic.map(rowHTML).join('');
}
if (other.length) {
if (labelled) html += '<div class="model-group-label">Other providers</div>';
html += other.map(rowHTML).join('');
}
document.getElementById('model-checkboxes').innerHTML = html;
updateModelTriggerLabel();
}
// Collapsed trigger text, in priority order:
// "All models" — everything selected
// "No models" — nothing selected
// "All Anthropic" — every Anthropic model (opus/sonnet/haiku/mythos/fable)
// selected and no other provider; "+N" if some others too
// "Fable 5, Opus 4.7 +5" — otherwise, first two names + overflow count
function updateModelTriggerLabel() {
const labelEl = document.getElementById('model-trigger-label');
if (!labelEl) return;
const n = selectedModels.size;
if (n === 0) { labelEl.textContent = 'No models'; return; }
if (n === allModelsList.length) { labelEl.textContent = 'All models'; return; }
const anthropic = allModelsList.filter(m => isBillable(m));
const others = allModelsList.filter(m => !isBillable(m));
if (anthropic.length && anthropic.every(m => selectedModels.has(m))) {
// n < total (handled above), so when others exist at least one is unselected.
const otherSel = others.filter(m => selectedModels.has(m)).length;
labelEl.textContent = otherSel ? 'All Anthropic +' + otherSel : 'All Anthropic';
return;
}
const chosen = sortedModels(allModelsList).filter(m => selectedModels.has(m));
const shown = chosen.slice(0, 2).map(shortModelName);
const extra = chosen.length - shown.length;
labelEl.textContent = shown.join(', ') + (extra > 0 ? ' +' + extra : '');
}
function toggleModelPanel(event) {
if (event) event.stopPropagation();
const panel = document.getElementById('model-panel');
const trigger = document.getElementById('model-trigger');
const open = panel.hidden;
panel.hidden = !open;
trigger.classList.toggle('open', open);
trigger.setAttribute('aria-expanded', open ? 'true' : 'false');
}
function closeModelPanel() {
const panel = document.getElementById('model-panel');
if (!panel || panel.hidden) return;
panel.hidden = true;
const trigger = document.getElementById('model-trigger');
trigger.classList.remove('open');
trigger.setAttribute('aria-expanded', 'false');
}
// Close the panel on outside click or Escape. Clicks inside #model-select
// (including the checkboxes and All/None) keep it open so multiple models can
// be toggled in one pass.
document.addEventListener('click', (e) => {
const sel = document.getElementById('model-select');
if (sel && !sel.contains(e.target)) closeModelPanel();
});
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeModelPanel(); });
function onModelToggle(cb) {
const label = cb.closest('label');
if (cb.checked) { selectedModels.add(cb.value); label.classList.add('checked'); }
else { selectedModels.delete(cb.value); label.classList.remove('checked'); }
updateModelTriggerLabel();
updateURL();
applyFilter();
}
function selectAllModels() {
document.querySelectorAll('#model-checkboxes input').forEach(cb => {
cb.checked = true; selectedModels.add(cb.value); cb.closest('label').classList.add('checked');
});
updateModelTriggerLabel(); updateURL(); applyFilter();
}
function clearAllModels() {
document.querySelectorAll('#model-checkboxes input').forEach(cb => {
cb.checked = false; selectedModels.delete(cb.value); cb.closest('label').classList.remove('checked');
});
updateModelTriggerLabel(); updateURL(); applyFilter();
}
// ── URL persistence ────────────────────────────────────────────────────────
function updateURL() {
const allModels = Array.from(document.querySelectorAll('#model-checkboxes input')).map(cb => cb.value);
const params = new URLSearchParams();
if (selectedRange !== '30d') params.set('range', selectedRange);
if (!isDefaultModelSelection(allModels)) params.set('models', Array.from(selectedModels).join(','));
const search = params.toString() ? '?' + params.toString() : '';
history.replaceState(null, '', window.location.pathname + search);
}
// ── Session sort ───────────────────────────────────────────────────────────
function setSessionSort(col) {
if (sessionSortCol === col) {
sessionSortDir = sessionSortDir === 'desc' ? 'asc' : 'desc';
} else {
sessionSortCol = col;
sessionSortDir = 'desc';
}
updateSortIcons();
applyFilter();
}
function updateSortIcons() {
document.querySelectorAll('.sort-icon').forEach(el => el.textContent = '');
const icon = document.getElementById('sort-icon-' + sessionSortCol);
if (icon) icon.textContent = sessionSortDir === 'desc' ? ' \u25bc' : ' \u25b2';
}
function sortSessions(sessions) {
return [...sessions].sort((a, b) => {
let av, bv;
if (sessionSortCol === 'cost') {
av = calcCost(a.model, a.input, a.output, a.cache_read, a.cache_creation);
bv = calcCost(b.model, b.input, b.output, b.cache_read, b.cache_creation);
} else if (sessionSortCol === 'duration_min') {
av = parseFloat(a.duration_min) || 0;
bv = parseFloat(b.duration_min) || 0;
} else {
av = a[sessionSortCol] ?? 0;
bv = b[sessionSortCol] ?? 0;
}
if (av < bv) return sessionSortDir === 'desc' ? 1 : -1;
if (av > bv) return sessionSortDir === 'desc' ? -1 : 1;
return 0;
});
}
// ── Aggregation & filtering ────────────────────────────────────────────────
function applyFilter() {
if (!rawData) return;
const { start, end } = getRangeBounds(selectedRange);
// Filter daily rows by model + date range
const filteredDaily = rawData.daily_by_model.filter(r =>
selectedModels.has(r.model) && (!start || r.day >= start) && (!end || r.day <= end)
);
// Daily chart: aggregate by day
const dailyMap = {};
for (const r of filteredDaily) {
if (!dailyMap[r.day]) dailyMap[r.day] = { day: r.day, input: 0, output: 0, cache_read: 0, cache_creation: 0 };
const d = dailyMap[r.day];
d.input += r.input;
d.output += r.output;
d.cache_read += r.cache_read;
d.cache_creation += r.cache_creation;
}
const daily = Object.values(dailyMap).sort((a, b) => a.day.localeCompare(b.day));
// By model: aggregate tokens + turns from daily data
const modelMap = {};
for (const r of filteredDaily) {
if (!modelMap[r.model]) modelMap[r.model] = { model: r.model, input: 0, output: 0, cache_read: 0, cache_creation: 0, turns: 0, sessions: 0 };
const m = modelMap[r.model];
m.input += r.input;
m.output += r.output;
m.cache_read += r.cache_read;
m.cache_creation += r.cache_creation;
m.turns += r.turns;
}
// Filter sessions by model + date range
const filteredSessions = rawData.sessions_all.filter(s =>
selectedModels.has(s.model) && (!start || s.last_date >= start) && (!end || s.last_date <= end)
);
// Add session counts into modelMap
for (const s of filteredSessions) {
if (modelMap[s.model]) modelMap[s.model].sessions++;
}
const byModel = Object.values(modelMap).sort((a, b) => (b.input + b.output) - (a.input + a.output));
// By project: aggregate from filtered sessions
const projMap = {};
for (const s of filteredSessions) {
if (!projMap[s.project]) projMap[s.project] = { project: s.project, input: 0, output: 0, cache_read: 0, cache_creation: 0, turns: 0, sessions: 0, cost: 0 };
const p = projMap[s.project];
p.input += s.input;
p.output += s.output;
p.cache_read += s.cache_read;
p.cache_creation += s.cache_creation;
p.turns += s.turns;
p.sessions++;
p.cost += calcCost(s.model, s.input, s.output, s.cache_read, s.cache_creation);
}
const byProject = Object.values(projMap).sort((a, b) => (b.input + b.output) - (a.input + a.output));
// By project+branch: aggregate from filtered sessions
const projBranchMap = {};
for (const s of filteredSessions) {