-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude-dashboard.py
More file actions
executable file
·4138 lines (3743 loc) · 193 KB
/
Copy pathclaude-dashboard.py
File metadata and controls
executable file
·4138 lines (3743 loc) · 193 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
#!/usr/bin/env python3
"""Auto-updating terminal dashboard for Claude Code cache-token usage.
Scans the JSONL transcripts under ~/.claude/projects/**/*.jsonl, reads the
per-response `usage` structures, and renders a live truecolour dashboard.
The transcript scan refreshes every 5 minutes (--interval, or `r` for now); the screen repaints
~5×/s for the shimmer, live clock, and to surface the background usage fetch.
Covers the last 12 hours in 5-minute buckets.
Three stacked bar charts (24-bit colour, glow gradient, sub-cell-smooth tops,
labelled Y-axis token scale and hourly X-axis):
1. Input tokens - cache write disposition:
blue = uncached (input_tokens)
purple = written to 5m cache (ephemeral_5m, == subagent/sidechain work)
violet = written to 1h cache (ephemeral_1h, == main-thread work)
2. Context assembly:
green = pulled from cache (cache_read_input_tokens)
blue = new input (input_tokens + cache_creation, cache-hit turns)
red = cache miss (whole input on turns that read zero from cache)
3. Output tokens generated (yellow).
Below: a SUMMARY panel and, to its right, an ACTIVE SESSIONS panel listing
sessions active within the lookback window (--active-window, default 1h; also
governs the subagent list in the detail popup) and their main-vs-subagent
fresh-token balance over the last hour and the full window. A renamed session
(/rename) shows its custom title in place of the session id.
Key facts baked in:
- 5-minute ephemeral cache == subagent/sidechain work; 1-hour cache == main
thread (verified from the data via isSidechain).
- Cache miss is inferred: cache_read==0 means the cached prefix was unavailable
(e.g. expired during an idle gap) so the whole prompt was re-paid. The first
request of a session also reads 0 - still uncached cost, shown as miss.
- Each API response spans several JSONL lines sharing one message.id, so
responses are de-duplicated by message.id.
Press H (or click the History menu tab) for a longer-span HISTORY view:
the same three charts over a configurable window (--history-hours, default 168 =
1 week) with an auto-scaled bucket and a day-by-day axis, a SUMMARY with a $ cost
estimate and cache-hit rate, and click-a-bar drill-down. No active-sessions or
allowance panels there.
Press P (or click the PRs menu tab) for a PRS view: every open PR you authored
plus every branch you've pushed commits to that has no open PR, across every
repo `gh` can see for your account — approval status, CI (click a red dot for
the failing checks), last commit, last comment (click for the full text), and
per-row action buttons (merge, once approved/no-review-needed and CI is green;
draft/ready toggle; close; delete branch), each behind a confirm popup. Needs
the `gh` CLI installed and authenticated (`gh auth login`); the tab degrades to
a message instead of a table if it isn't. Refreshed on --pr-refresh-seconds
(default 300s) — each scan is several `gh` subprocess calls.
Stdlib only (except the optional `gh` CLI for the PRS tab). --once prints a
single frame; --interval overrides the period.
Flags can also be set in .claude-dashboard.rc, next to this script (one flag
per line, '#' comments OK) - CLI flags given at the command line override it.
"""
from __future__ import annotations
import argparse
import glob
import json
import logging
import math
import os
import re
import select
import shlex
import shutil
import subprocess
import sys
import termios
import threading
import time
import tty
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
TRANSCRIPT_GLOB = os.path.expanduser("~/.claude/projects/**/*.jsonl")
# Full or partial cwd paths to leave out of every chart/panel entirely - e.g.
# a background/automated job (cron-style `claude -p` run against a fixed
# working directory), not interactive use. No default: empty unless the user
# passes --exclude. Matched case-insensitively as a substring of the cwd (a
# partial path spans multiple path components, e.g. "OneDrive/AI/qmd-memory",
# so this can't be reduced to single-component equality), after normalising
# backslashes to forward slashes - works regardless of which host or path
# style (Windows "C:\...", WSL "/mnt/c/...") wrote the record.
EXCLUDE_PATTERNS = []
def _cwd_excluded(cwd):
if not cwd or not EXCLUDE_PATTERNS:
return False
norm = str(cwd).replace("\\", "/").lower()
return any(p in norm for p in EXCLUDE_PATTERNS)
WIN_GLOBS_TTL = 60 # seconds between re-checks of logged-in Windows users
_win_roots_cache = {"ts": 0.0, "roots": []}
def is_wsl():
"""True when running under WSL (checked once, cached)."""
if is_wsl._cached is None:
try:
with open("/proc/version", encoding="utf-8") as f:
is_wsl._cached = "microsoft" in f.read().lower()
except OSError:
is_wsl._cached = False
return is_wsl._cached
is_wsl._cached = None
def _account_email(claude_json_path):
try:
with open(claude_json_path, encoding="utf-8") as f:
data = json.load(f)
except (OSError, json.JSONDecodeError):
return None
email = (data.get("oauthAccount") or {}).get("emailAddress")
return email.lower() if email else None
def _own_account_emails():
"""Every account this user holds: the live login plus each saved snapshot
in ACCOUNTS_DIR (its "label" is the account email)."""
emails = set()
live = _account_email(os.path.expanduser("~/.claude.json"))
if live:
emails.add(live)
for _slug, label, _exp in list_saved_accounts():
if "@" in label:
emails.add(label.lower())
return emails
def _logged_in_windows_users():
"""Windows usernames with an active session, via `query user` through
cmd.exe (WSL interop). Falls back to every /mnt/c/Users/* profile dir if
interop is unavailable (e.g. disabled, or query user missing)."""
try:
out = subprocess.run(["cmd.exe", "/c", "query user"],
capture_output=True, text=True, timeout=5)
users = []
for line in out.stdout.splitlines()[1:]:
line = line.lstrip(">").strip()
if line:
users.append(line.split()[0])
if users:
return users
except (OSError, subprocess.SubprocessError):
pass
try:
return [os.path.basename(p) for p in glob.glob("/mnt/c/Users/*")
if os.path.isdir(p)]
except OSError:
return []
def windows_transcript_roots():
"""Extra `.claude/projects` roots for Claude Code run on the Windows host
(e.g. via PowerShell), reached from WSL under /mnt/c. Only included for a
Windows user that is currently logged in AND signed into one of THIS
user's Claude accounts (live login or any saved dashboard-accounts
snapshot, matched by email) - otherwise an unrelated account's transcripts
on a shared machine would leak into the dashboard. Matching the live login
alone breaks whenever WSL and Windows sit on different accounts of the
same person, which multi-account switching makes routine.
Cached for WIN_GLOBS_TTL seconds since collect()
runs on a timer and `query user` is a subprocess spawn (slow: WSL
interop into a Windows process)."""
now = time.time()
if now - _win_roots_cache["ts"] < WIN_GLOBS_TTL:
return _win_roots_cache["roots"]
roots = []
if is_wsl() and os.path.isdir("/mnt/c/Users"):
own = _own_account_emails()
if own:
for uname in _logged_in_windows_users():
base = f"/mnt/c/Users/{uname}"
if _account_email(f"{base}/.claude.json") in own:
roots.append(f"{base}/.claude/projects")
_win_roots_cache["ts"] = now
_win_roots_cache["roots"] = roots
return roots
# These window/bucket dimensions are RESOLVED at startup in configure_dimensions()
# from the CLI args and the terminal width; the values here are fallback defaults
# for non-interactive use (import, piped --once when the size is unknown).
WINDOW = timedelta(hours=12)
BUCKET = timedelta(minutes=5)
NUM_BUCKETS = int(WINDOW / BUCKET) # 144 (width = MARGIN + NUM_BUCKETS)
INTERVAL_SECONDS = int(BUCKET.total_seconds())
# How far back a session (and, in the detail popup, a subagent) counts as
# "active". Default 1h; overridden by --active-window-hours. Set in main().
# Distinct from the fixed "1h main/sub" token column, a fixed 1-hour metric.
ACTIVE_WINDOW = timedelta(hours=1)
CHART_HEIGHT = 8
MIN_BAR_H = 2 # floor so 3 charts fit ~9 rows (95x9)
MARGIN = 8 # left gutter for the Y-axis scale
RIGHT_RESERVE = 1 # leave the last terminal column unused
TOTAL_WIDTH = MARGIN + NUM_BUCKETS
# When --window-hours is unset the window fills the terminal width and tracks it
# live on resize (re-bucketing on the next collect); a fixed --window-hours does
# not. Set in configure_dimensions().
AUTOFIT = True
MIN_BUCKETS = 20 # narrowest chart we'll render
# ── history view ──────────────────────────────────────────────────────────────
# A separate, longer-span view (H key / footer) reusing the same chart machinery
# with a coarser bucket. NUM_BUCKETS (the chart width) is shared with the live
# view; the history WINDOW is fixed (--history-hours, default 168 = 1 week) and
# the bucket is derived as window/width, so the span stays exactly a week while
# the bucket scales to the terminal. --history-bucket-minutes overrides the
# bucket instead, deriving the window as bucket*width. Resolved at startup and
# on resize by compute_history_dims().
HISTORY_HOURS = 168.0
HISTORY_BUCKET_MIN = None # None => auto-scale; else fixed minutes
HIST_WINDOW = timedelta(hours=HISTORY_HOURS)
HIST_BUCKET = timedelta(minutes=70)
HIST_NUM_BUCKETS = NUM_BUCKETS
# 7×24 grid of effective tokens (local weekday Mon..Sun × hour 0..23) for the
# history activity-heatmap sub-view; populated by collect(track_heatmap=True).
HIST_HEAT = None
# $ cost estimate = effective-tokens × base-input price. Effective tokens are in
# base-input-token-equivalents, so one blended per-MTok input price converts them
# to dollars. Default = Opus 4.8 input ($5/MTok); --price-per-mtok overrides.
PRICE_PER_MTOK = 5.0
# Active view dimensions, set per render by render_frame from its `mode` arg. In
# live mode they mirror WINDOW/BUCKET; in history mode they hold HIST_WINDOW/
# HIST_BUCKET so the chart axis, bucket-popup span, and summary label all read
# the right window without threading params through the whole render stack.
VIEW_WINDOW = WINDOW
VIEW_BUCKET = BUCKET
VIEW_DAILY = False # day-boundary X-axis (history) vs hourly
# ── 24-bit truecolour palette ────────────────────────────────────────────────
CO = {
"uncached": (84, 160, 255), # blue
"c5m": (170, 120, 255), # purple (subagent)
"c1h": (214, 150, 255), # violet (main)
"read": (52, 224, 150), # green
"new": (84, 160, 255), # blue
"miss": (255, 88, 96), # red
"output": (255, 205, 82), # yellow
"main": (84, 160, 255), # blue
"sub": (170, 120, 255), # purple
}
ACCENT = (90, 232, 232) # cyan
ACCENT2 = (170, 120, 255) # purple
TEXT = (216, 220, 240)
DIM = (124, 128, 158)
DIM2 = (72, 74, 102)
PARTIAL = " ▁▂▃▄▅▆▇█" # 0..8 sub-cell fill levels
CHIP = "▆"
TICK_SECONDS = 0.2 # repaint cadence (shimmer animation @5fps)
PROGRESS_INTERVAL = 0.15 # collect()'s in-scan progress_cb cadence
USAGE_REFRESH = 300 # seconds between live-usage refetches
USAGE_BACKOFF = 900 # after a 429, wait this long before retrying
LOGIN_INLINE_TIMEOUT = 45 # give inline (no-suspend) login this long before
# falling back to a real tty (SSO flows that need
# keyboard input would otherwise hang forever silently)
LOG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"claude-dashboard.log")
RC_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
".claude-dashboard.rc")
logging.basicConfig(filename=LOG_PATH, level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("ccmon")
def rgb(c, text, bold=False):
r, g, b = c
b0 = "\033[1m" if bold else ""
return f"{b0}\033[38;2;{r};{g};{b}m{text}\033[0m"
def styled(text, fg, bg=None, bold=False, underline=False):
"""rgb() plus optional background and SGR-4 underline — the underline is for
Win3.1-style menu accelerator letters."""
if text == "":
return ""
codes = []
if bold:
codes.append("1")
if underline:
codes.append("4")
codes.append(f"38;2;{fg[0]};{fg[1]};{fg[2]}")
if bg is not None:
codes.append(f"48;2;{bg[0]};{bg[1]};{bg[2]}")
return f"\033[{';'.join(codes)}m{text}\033[0m"
def shade(c, f):
return (int(c[0] * f), int(c[1] * f), int(c[2] * f))
def lerp(a, b, f):
return a + (b - a) * f
def grad_rule(width, c1, c2, char="━"):
if width <= 1:
return rgb(c1, char * max(width, 0))
return "".join(
rgb((int(lerp(c1[0], c2[0], i / (width - 1))),
int(lerp(c1[1], c2[1], i / (width - 1))),
int(lerp(c1[2], c2[2], i / (width - 1)))), char)
for i in range(width)
)
def parse_ts(raw):
if not raw:
return None
try:
dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
except (ValueError, TypeError):
return None
# Force tz-aware: a naive timestamp (no offset, no Z) would otherwise raise
# TypeError when compared against the aware `cutoff` and crash collect().
return dt if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc)
def empty_bucket() -> dict:
return {
"uncached": 0, "c5m": 0, "c1h": 0, # chart 1 (write disposition)
"read": 0, "new": 0, "miss": 0, # chart 2 (assembly)
"output": 0, "responses": 0,
}
def add_usage(bk, inp, f5, f1, read, fresh, out):
"""Accumulate one response's usage into a bucket. Shared by the global
buckets and per-session buckets so the two never drift."""
bk["uncached"] += inp
bk["c5m"] += f5
bk["c1h"] += f1
bk["read"] += read
if read > 0:
bk["new"] += fresh
else:
bk["miss"] += fresh
bk["output"] += out
bk["responses"] += 1
def eff_tokens(uncached, c5m, c1h, read, output):
"""Effective tokens: everything normalised to base-input-token-equivalents
using Anthropic's per-token price multipliers. 5m cache write = 1.25x base
input, 1h write = 2x, cache read = 0.1x, uncached input = 1x, and OUTPUT =
5x base input (the output:input price ratio, uniform across Claude models).
One definition shared by the bucket summary and the per-session accounting
so the two never drift."""
return uncached + 1.25 * c5m + 2 * c1h + 0.1 * read + 5 * output
def model_max_window(model):
# Max context a model CAN do. FINDING (2026-06): the 1M context is a per-
# request beta header, NOT a model property — it's stripped from the logged
# model id, absent from every usage/beta field, and not queryable via any
# API after the fact. So we grade against the model's *capability*: any
# Opus or Sonnet generation supports the 1M beta -> grade at 1M (a real 1M
# session then never false-flashes at 175k); Haiku caps at 200k. Trade-off:
# an Opus/Sonnet run in plain 200k mode under-warns (won't alarm near its
# 200k wall) — acceptable, since the 1M beta is opt-in and the alarm is for
# big contexts.
if not model:
return 200_000
m = model.lower()
if "haiku" in m:
return 200_000
if "opus" in m or "sonnet" in m:
return 1_000_000
return 200_000
def window_for(model, peak):
# 1M if the model can do it, OR if we've provably seen this thread exceed
# 200k (which can only happen in a 1M context); else the model's max.
if (peak or 0) > 200_000:
return 1_000_000
return model_max_window(model)
def session_window(s):
return window_for(s.get("model"), s.get("peak_main", 0))
def sub_window(s):
return window_for(s.get("peak_sub_model"), s.get("peak_sub", 0))
def ctx_grade(size, window):
"""Return (colour, flashing) for a context size. Five tiers — green, yellow,
amber, red, flashing red — with thresholds scaled to the window. Bands:
200k window: ≤100k g · ≤125k y · ≤150k a · ≤175k r · >175k flashing
1M window: ≤150k g · ≤300k y · ≤450k a · ≤600k r · >600k flashing"""
if window >= 1_000_000:
g, y, a, r = 150_000, 300_000, 450_000, 600_000
else:
g, y, a, r = 100_000, 125_000, 150_000, 175_000
if size > r:
return HOT_C, True # flashing red
if size > a:
return HOT_C, False # red
if size > y:
return ORANGE_C, False # amber
if size > g:
return WARN_C, False # yellow
return OK_C, False # green
def ctx_dot(size, window, now):
"""The traffic-light ● for a context size. Flashes (2s period, 1s on / 1s
off) when in the flashing-red band; `now` drives the blink."""
col, flashing = ctx_grade(size, window)
if flashing and int(now.timestamp()) % 2: # off half of the 2s period
return rgb(shade(HOT_C, 0.22), "●")
return rgb(col, "●")
def _clean(s):
"""Strip control bytes (incl. ESC/CSI) from any transcript-derived string
before it is painted to the terminal. Slugs, project names, model ids and
API error text come from `~/.claude/projects/**` — untrusted input — and are
rendered via rgb()/_padcol, which only PREPEND colour codes. Without this a
transcript carrying raw escape sequences could drive the cursor, set the
title, or write the clipboard (OSC-52), and also corrupts _visible_len/_padcol
alignment. Strips C0, DEL, and C1 (0x80-0x9f, which includes 8-bit CSI)."""
return re.sub(r"[\x00-\x1f\x7f-\x9f]", "", s) if isinstance(s, str) else s
def _err_text(rec):
m = rec.get("message") or {}
c = m.get("content")
if isinstance(c, list):
t = " ".join(b.get("text", "") for b in c if isinstance(b, dict) and b.get("type") == "text")
if t.strip():
return _clean(t.strip())
if isinstance(c, str) and c.strip():
return _clean(c.strip())
e = rec.get("error")
return _clean(e) if isinstance(e, str) else ""
def model_color(name):
"""A stable colour for a model id (the history model-mix chart), matched by
family substring. Unknown models fall back to neutral grey."""
m = (name or "").lower()
if "opus" in m:
return (84, 160, 255) # blue
if "sonnet" in m:
return (52, 224, 150) # green
if "haiku" in m:
return (255, 138, 56) # amber
if "fable" in m or "mythos" in m:
return (170, 120, 255) # purple
return (150, 150, 170) # grey / unknown
def short_model(m):
"""Compact model id for display: 'claude-opus-4-8' -> 'opus-4-8'."""
if not m or m == "<synthetic>":
return "?"
return _clean(m[7:] if m.startswith("claude-") else m)
def new_session(sid, ts, rec, num_buckets=None):
"""Factory for a per-session stats dict. `last` means the last SUCCESSFUL
turn ts (None until a usage record is seen); `last_act` is the last ANY
activity ts (usage or surfaced error). `num_buckets` sizes the per-session
bucket array; defaults to the global (live) NUM_BUCKETS."""
nb = NUM_BUCKETS if num_buckets is None else num_buckets
return {
"sid": sid, "name": None, "last": None, "cwd": rec.get("cwd") or "",
"main_12": 0, "sub_12": 0, "main_1h": 0, "sub_1h": 0,
"ctx": 0, "ctx_ts": None, "model": None,
"peak_main": 0, "peak_sub": 0, "peak_sub_model": None,
"eff_main_1h": 0.0, "eff_main_12": 0.0,
"eff_sub_1h": 0.0, "eff_sub_12": 0.0,
"subs": {}, # agentId -> per-subagent detail
"buckets": [empty_bucket() for _ in range(nb)],
"err": None, "last_act": ts,
}
def _slugged_patterns():
"""EXCLUDE_PATTERNS, with path separators folded to '-' to match a
project's on-disk directory name - which is a slug of its cwd with every
'/' or '\\' replaced by '-' (e.g. cwd "C:\\Users\\doug\\OneDrive\\AI\\
qmd-memory" -> dir "C--Users-doug-OneDrive-AI-qmd-memory"), so a
multi-component pattern like "OneDrive/AI/qmd-memory" has to be folded
the same way before it can be matched against that slug."""
return [p.replace("\\", "-").replace("/", "-") for p in EXCLUDE_PATTERNS]
def _walk_jsonl_paths(root):
"""Yield every *.jsonl under `root`, pruning whole subtrees whose on-disk
project directory name (a slug of its cwd) contains an excluded pattern.
Pruning during the walk (rather than globbing everything and filtering
paths after) avoids listing/stat-ing an excluded tree at all - the
dominant cost on a slow filesystem (e.g. WSL's /mnt/c DrvFs mount) when
that tree is large, as e.g. the QMD dream job's chunk/subagent files are."""
if not os.path.isdir(root):
return
patterns = _slugged_patterns()
for dirpath, dirnames, filenames in os.walk(root):
if patterns:
dirnames[:] = [d for d in dirnames
if not any(p in d.lower() for p in patterns)]
for fn in filenames:
if fn.endswith(".jsonl"):
yield os.path.join(dirpath, fn)
def _all_transcript_paths():
yield from _walk_jsonl_paths(os.path.expanduser("~/.claude/projects"))
for root in windows_transcript_roots():
yield from _walk_jsonl_paths(root)
def collect(now: datetime, window=None, bucket=None, num_buckets=None,
track_models=False, track_heatmap=False, progress_cb=None,
seed_sessions=None):
"""Return (buckets, sessions): time buckets oldest->newest plus per-session
cache stats, all from de-duplicated usage records. `window`/`bucket`/
`num_buckets` default to the live globals; the history view passes its own
(longer) span and coarser bucket so the same scan feeds both views.
`track_models` adds a per-bucket {model: effective-tokens} map under the
extra "models" key (ignored by the fixed-key aggregation loops) for the
history model-mix chart.
`seed_sessions`, if given, is the caller's PREVIOUS `sessions` dict,
mutated and returned in place instead of starting from empty. A session
already in it stays visible (with its stale, previous-scan numbers)
until this scan re-touches it — the whole point being a refresh never
drops the visible list back to nothing while it re-populates. A session
is re-touched by discarding its carried-over entry and rebuilding it
fresh (via new_session) on FIRST touch this call, so its numbers are a
clean re-aggregation, not stale-plus-incremental double counting;
further touches this call accumulate into that fresh entry as normal.
At the end, any carried-over session this call never touched is dropped
if it's aged out of `window` — mtime_floor already means "never touched"
only happens when a session's file was entirely skipped as older than
the window, so this is nearly always true; the last_act check is the
correctness guard for the rare other case.
`progress_cb(buckets, sessions)`, if given, is called once immediately
(before any file is read - so a caller can paint a first frame right
away) and then again every PROGRESS_INTERVAL seconds while the scan is
still running, with the in-progress `buckets`/`sessions` - the same
objects this call will go on to return, mutated in place, so a slow scan
(many transcripts, or a slow filesystem) shows sessions appearing
incrementally instead of one long blank wait. Single-threaded: the
callback runs on this thread between files, never concurrently with the
mutation, so there's no partial-write tearing to guard against."""
window = WINDOW if window is None else window
bucket = BUCKET if bucket is None else bucket
num_buckets = NUM_BUCKETS if num_buckets is None else num_buckets
cutoff = now - window
last_hour = now - timedelta(hours=1)
mtime_floor = cutoff.timestamp() - 1
buckets = [empty_bucket() for _ in range(num_buckets)]
if track_models:
for b in buckets:
b["models"] = {} # model id -> effective tokens (extra key)
heat = [[0.0] * 24 for _ in range(7)] if track_heatmap else None
sessions: dict[str, dict] = {} if seed_sessions is None else seed_sessions
touched_sids: set[str] = set() # sids (re)touched THIS call
seen: set[str] = set()
titles: dict[str, str] = {} # sid -> custom session title (latest /rename)
def touch(sid, ts, rec):
"""Session dict for `sid`, rebuilt fresh on this call's first touch
(discarding any carried-over seed entry) so a re-scan's numbers are
never stale-plus-incremental double counted; later touches this call
reuse that fresh entry."""
if sid not in touched_sids:
sessions[sid] = new_session(sid, ts, rec, num_buckets)
touched_sids.add(sid)
return sessions[sid]
if progress_cb is not None:
progress_cb(buckets, sessions)
last_progress = time.monotonic()
for path in _all_transcript_paths():
if progress_cb is not None:
t = time.monotonic()
if t - last_progress >= PROGRESS_INTERVAL:
progress_cb(buckets, sessions)
last_progress = t
try:
if os.path.getmtime(path) < mtime_floor:
continue
except OSError:
continue
try:
with open(path, encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue
# A /rename writes a standalone metadata record with no
# timestamp/usage; it'd be dropped by the cutoff check below.
# Capture the latest title per session (file order is append
# order, so last wins) and attach it after the scan.
if rec.get("type") == "custom-title":
t = _clean(rec.get("customTitle") or "").strip()
if t:
tsid = rec.get("sessionId") or os.path.basename(path)[:-6]
titles[tsid] = t
continue
msg = rec.get("message") or {}
ts = parse_ts(rec.get("timestamp"))
if ts is None or ts < cutoff:
continue
sid = rec.get("sessionId") or os.path.basename(path)[:-6]
if _cwd_excluded(rec.get("cwd")):
continue
# Surfaced API failures (synthetic assistant records) carry
# no usage, so they'd be skipped by the usage check below.
# Handle them first: record the latest error per session.
if msg.get("isApiErrorMessage"):
s = touch(sid, ts, rec)
status = rec.get("apiErrorStatus")
text = _err_text(rec)
if s["err"] is None or ts >= s["err"]["ts"]:
s["err"] = {"ts": ts, "status": status, "text": text}
if rec.get("cwd"):
s["cwd"] = rec["cwd"]
if s["last_act"] is None or ts > s["last_act"]:
s["last_act"] = ts
continue
usage = msg.get("usage")
if not usage:
continue
key = msg.get("id") or rec.get("requestId")
if key is not None:
if key in seen:
continue
seen.add(key)
idx = int((ts - cutoff) / bucket)
idx = min(max(idx, 0), num_buckets - 1)
b = buckets[idx]
cc = usage.get("cache_creation") or {}
inp = usage.get("input_tokens", 0) or 0
creation = usage.get("cache_creation_input_tokens", 0) or 0
read = usage.get("cache_read_input_tokens", 0) or 0
f5 = cc.get("ephemeral_5m_input_tokens", 0) or 0
f1 = cc.get("ephemeral_1h_input_tokens", 0) or 0
fresh = inp + creation
out = usage.get("output_tokens", 0) or 0
total_in = inp + creation + read
eff = eff_tokens(inp, f5, f1, read, out)
model = msg.get("model")
# Charts 1 & 2 + output/responses for the global bucket.
add_usage(b, inp, f5, f1, read, fresh, out)
if track_models: # history model-mix: eff tokens by model
mk = short_model(model)
b["models"][mk] = b["models"].get(mk, 0) + eff
if heat is not None: # activity heatmap: eff by weekday×hour
loc = ts.astimezone()
heat[loc.weekday()][loc.hour] += eff
# Per-session drill-down: split fresh tokens (new work) by
# main thread vs subagent (sidechain). Fresh, not total
# input, so the main thread's huge cheap cache reads don't
# drown the subagent signal.
side = "sub" if rec.get("isSidechain") else "main"
s = touch(sid, ts, rec)
# `last` = last SUCCESSFUL turn (the "last prompt" baseline and
# the success cutoff for errored_last); `last_act` = any activity.
if s["last"] is None or ts > s["last"]:
s["last"] = ts
if rec.get("cwd"):
s["cwd"] = rec["cwd"]
if s["last_act"] is None or ts > s["last_act"]:
s["last_act"] = ts
s[f"{side}_12"] += fresh
if ts >= last_hour:
s[f"{side}_1h"] += fresh
# Effective-token accounting (real cache-pricing multipliers,
# in token-equivalents), split main vs subagent.
s[f"eff_{side}_12"] += eff
if ts >= last_hour:
s[f"eff_{side}_1h"] += eff
# Per-subagent detail, keyed by the stable agentId per run.
if side == "sub":
aid = rec.get("agentId") or "untagged"
sub = s["subs"].get(aid)
if sub is None:
# The transcript `slug` is per-session, not
# per-subagent — every subagent in one session
# shares it (e.g. "shimmering-dancing-rainbow"),
# so in this single-session popup it just repeats.
# Show the agentId instead; it is genuinely unique.
sub = s["subs"][aid] = {
"slug": aid,
"start": ts, "stop": ts, "peak": 0, "eff": 0.0,
"model": model}
sub["start"] = min(sub["start"], ts)
sub["stop"] = max(sub["stop"], ts)
sub["peak"] = max(sub["peak"], total_in)
sub["eff"] += eff
if model:
sub["model"] = model
# Context size = latest MAIN-thread turn's total input;
# peak_main = deepest ever, used to infer the 1M window.
if side == "main":
if total_in > s["peak_main"]:
s["peak_main"] = total_in
if s["ctx_ts"] is None or ts > s["ctx_ts"]:
s["ctx_ts"] = ts
s["ctx"] = total_in
if model:
s["model"] = model
# Mirror peak_main for subagents to infer their window.
if side == "sub" and total_in > s["peak_sub"]:
s["peak_sub"] = total_in
s["peak_sub_model"] = model
# Per-session buckets feed the click-through popup charts.
add_usage(s["buckets"][idx], inp, f5, f1, read, fresh, out)
except OSError:
continue
# A carried-over (seed_sessions) session this call never touched has aged
# out of `window` — drop it. (In practice this is the ONLY way a session
# goes untouched: its file's mtime already failed mtime_floor above, since
# any activity within window would have updated the file's mtime too.
# The last_act check is belt-and-braces, not the primary mechanism.)
for sid in list(sessions):
if sid not in touched_sids:
s = sessions[sid]
if s.get("last_act") is None or s["last_act"] < cutoff:
del sessions[sid]
# Attach custom /rename titles to their sessions (titles may be seen before
# the session has any usage record, so this is done after the full scan).
for tsid, t in titles.items():
s = sessions.get(tsid)
if s is not None:
s["name"] = t
if track_heatmap:
global HIST_HEAT
HIST_HEAT = heat
return buckets, sessions
# ── helpers ──────────────────────────────────────────────────────────────────
def fmt(n):
return f"{n:,}"
def fmt_compact(n):
if n >= 1_000_000:
return f"{n / 1_000_000:.1f}M"
if n >= 1_000:
return f"{n / 1_000:.0f}k"
return str(int(n))
def fmt_window(td):
"""A timedelta as a compact label for the UI: '1h', '30m', '1h30m'."""
m = int(td.total_seconds() // 60)
if m % 60 == 0:
return f"{m // 60}h"
if m < 60:
return f"{m}m"
return f"{m // 60}h{m % 60:02d}m"
def pct(part, whole):
return f"{(100.0 * part / whole):.1f}%" if whole else "n/a"
def _visible_len(s):
"""Length of a string ignoring ANSI SGR sequences."""
out, i = 0, 0
while i < len(s):
if s[i] == "\033":
while i < len(s) and s[i] != "m":
i += 1
i += 1
else:
out += 1
i += 1
return out
def _padcol(s, width):
return s + " " * max(width - _visible_len(s), 0)
def _clip(s, width):
"""Truncate a (possibly ANSI-styled) string to `width` visible chars,
keeping SGR codes intact and resetting at the end."""
if _visible_len(s) <= width:
return s
out, vis, i = [], 0, 0
while i < len(s) and vis < width:
if s[i] == "\033":
j = i
while j < len(s) and s[j] != "m":
j += 1
out.append(s[i:j + 1])
i = j + 1
else:
out.append(s[i])
vis += 1
i += 1
out.append("\033[0m")
return "".join(out)
def _slice_from(s, start):
"""Visible chars of a (possibly ANSI-styled) string from column `start`
onward: skips `start` visible chars, then re-emits the last SGR code seen
so the remainder keeps its color instead of falling back to the
terminal's default. Pairs with _clip (the [0, start) prefix) to carve a
middle span — e.g. a modal overlay's rectangle — out of a line so a
repaint can skip it without touching those columns at all."""
if start <= 0:
return s
vis, i, active = 0, 0, ""
while i < len(s) and vis < start:
if s[i] == "\033":
j = i
while j < len(s) and s[j] != "m":
j += 1
active = s[i:j + 1]
i = j + 1
else:
vis += 1
i += 1
return active + s[i:]
def fit_overlay(lines, cols, rows, scroll):
"""Fit a bordered modal into the terminal. Clips every line to the width;
when the modal is taller than the screen, pins the top and bottom border
rows and scrolls the middle, drawing a vertical scrollbar in the last inner
column. Returns (visible_lines, max_scroll)."""
maxw = min(max((_visible_len(l) for l in lines), default=0), cols)
if len(lines) <= rows: # fits whole: just clip width
return [_clip(ln, maxw) for ln in lines], 0
top, mid, bot = lines[0], lines[1:-1], lines[-1]
view_h = max(rows - 2, 1) # rows for the scrolling middle
max_scroll = max(0, len(mid) - view_h)
scroll = max(0, min(scroll, max_scroll))
window = mid[scroll:scroll + view_h]
inner_w = maxw - 1 # last col is the scrollbar
thumb = max(1, round(view_h * view_h / len(mid)))
pos = round(scroll * (view_h - thumb) / max_scroll) if max_scroll else 0
out = [_clip(top, maxw)]
for i, ln in enumerate(window):
on = pos <= i < pos + thumb
out.append(_padcol(_clip(ln, inner_w), inner_w)
+ rgb(ACCENT if on else DIM2, "█" if on else "░"))
out.append(_clip(bot, maxw))
return out, max_scroll
# ── charts ───────────────────────────────────────────────────────────────────
def build_column(vc, total, maxt, height):
"""Return `height` cells bottom->top as (rgb|None, char). Sub-cell smooth:
8 sub-levels per cell, so bar tops render as partial blocks."""
col = [(None, " ")] * height
if total <= 0 or maxt <= 0:
return col
units = height * 8
sub = min(max(int(round(total / maxt * units)), 1), units)
nz = [i for i, (_, v) in enumerate(vc) if v > 0]
alloc = [0] * len(vc)
if sub >= len(nz):
# Seed each active segment one sub-cell so it never vanishes, then
# share the rest by largest remainder.
for i in nz:
alloc[i] = 1
fr = []
for i in nz:
e = vc[i][1] / total * sub
alloc[i] += max(int(e) - 1, 0)
fr.append((e - int(e), i))
used = sum(alloc)
for _, i in sorted(fr, reverse=True)[:max(sub - used, 0)]:
alloc[i] += 1
else:
for i in sorted(nz, key=lambda i: vc[i][1], reverse=True)[:sub]:
alloc[i] = 1
contrib = [dict() for _ in range(height)]
filled = [0] * height
pos = 0
for (color, _), n in zip(vc, alloc):
for _ in range(n):
ci = pos // 8
if ci < height:
contrib[ci][color] = contrib[ci].get(color, 0) + 1
filled[ci] += 1
pos += 1
for ci in range(height):
if filled[ci] <= 0:
continue
color = max(contrib[ci].items(), key=lambda kv: kv[1])[0]
col[ci] = (color, PARTIAL[min(filled[ci], 8)])
return col
def render_chart(title, keys, buckets, height, now, anim=0,
short_title=None, legend_items=None, compact=False, axes=True,
series_of=None, legend_str=None):
"""Render one bar chart as a list of lines. Compact mode folds the title and
legend onto a single header line (using `short_title`) and drops the hourly
tick row, saving 2 rows. axes=False also drops the baseline rule. Non-compact
behaviour (title line only; legend drawn externally) is unchanged.
Normally each bar is stacked from `keys` against the fixed CO palette. Pass
`series_of(b) -> [(rgb_tuple, value), ...]` (with a pre-built `legend_str`)
to stack arbitrary, already-coloured series instead — used by the history
model-mix chart, whose series (one per model) aren't in CO."""
if series_of is not None:
series = [series_of(b) for b in buckets]
totals = [sum(v for _, v in s) for s in series]
maxt = max(totals) if totals else 0
columns = [build_column(s, tot, maxt, height)
for s, tot in zip(series, totals)]
else:
totals = [sum(b[k] for k in keys) for b in buckets]
maxt = max(totals) if totals else 0
columns = [build_column([(CO[k], b[k]) for k in keys], tot, maxt, height)
for b, tot in zip(buckets, totals)]
if compact:
head = (" " + rgb(ACCENT, "▸ ", bold=True)
+ rgb(TEXT, short_title or title, bold=True))
if legend_str is not None:
head += " " + legend_str
elif legend_items:
head += " " + legend(legend_items)
lines = [head]
else:
lines = [" " + rgb(ACCENT, "▸ ", bold=True) + rgb(TEXT, title, bold=True)]
for row in range(height - 1, -1, -1):
f = 0.5 + 0.5 * (row / (height - 1)) if height > 1 else 1.0
if row % 2 == 1: # Y-axis scale, every other cell
val = maxt * (row + 1) / height
label = rgb(DIM, fmt_compact(round(val)).rjust(MARGIN - 2)) + " "
else:
label = " " * MARGIN
cells = []
for i, (base, ch) in enumerate(col[row] for col in columns):
if base:
wave = 1.0 + 0.18 * math.sin(0.20 * i + 0.45 * row - 0.11 * anim)
ff = max(0.12, min(1.0, f * wave))
cells.append(rgb(shade(base, ff), ch))
else:
cells.append(" ")
body = "".join(cells)
lines.append(label + body)
if not axes: # tightest tier: bars only, no baseline/ticks
return lines
# X-axis baseline + tick labels. Live (VIEW_DAILY off): hourly "H:00".
# History (VIEW_DAILY on): one label per local-midnight day boundary ("Mon26")
# so a week of bars stays readable. Dimensions come from the active view
# (VIEW_WINDOW/VIEW_BUCKET) and the rendered bucket count.
nb = len(buckets)