claude-code-cost 0.9.0 → 0.12.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/README.md CHANGED
@@ -4,7 +4,11 @@
4
4
  [![license](https://img.shields.io/npm/l/claude-code-cost)](LICENSE)
5
5
  [![npm downloads](https://img.shields.io/npm/dm/claude-code-cost)](https://www.npmjs.com/package/claude-code-cost)
6
6
 
7
- > Know what Claude Code costs you — per day, per project, per session.
7
+ **[Live Demo & Docs](https://nikiforovall.blog/claude-code-cost/)**
8
+
9
+ > Know what [Claude Code](https://docs.anthropic.com/en/docs/claude-code) costs you — per day, per project, per session.
10
+
11
+ ![Cost dashboard overview](assets/shot-overview.png)
8
12
 
9
13
  ## Getting Started
10
14
 
@@ -12,90 +16,35 @@
12
16
  npx claude-code-cost --open
13
17
  ```
14
18
 
15
- Open http://localhost:3543 (or use `--open` to auto-launch the browser).
16
-
17
- That's it. No hooks, no config — the dashboard reads your existing Claude Code session files.
18
-
19
- ### Overview
20
-
21
- ![Overview — Dark](assets/overview-dark.png)
22
- ![Overview — Light](assets/overview-light.png)
23
-
24
- ### Projects
19
+ That's it — no hooks, no config. The dashboard reads the JSONL session logs Claude Code already writes to `~/.claude/projects/` and aggregates them server-side. Completely read-only; nothing leaves your machine.
25
20
 
26
- ![Projects — Dark](assets/projects-dark.png)
27
- ![Projects — Light](assets/projects-light.png)
21
+ ## Features
28
22
 
29
- ### Session Detail
23
+ - **Top-down drill-down** — total → project → session → message; every number is one click from its breakdown
24
+ - **Dynamic pricing** — live model prices from [LiteLLM](https://github.com/BerriAI/litellm) with tiered pricing (200K threshold), cache token costs, and fast mode multipliers; offline fallback included
25
+ - **Daily cost chart** — configurable range from 1 day to 1 year
26
+ - **Cost by model** — see how spend splits across Opus, Sonnet, and Haiku
27
+ - **Cache efficiency** — cache reads vs. fresh input tokens across sessions
28
+ - **Session detail** — cumulative cost curve, stacked token bars, per-message table with model, tools, and running total
29
+ - **Accurate accounting** — same pricing logic as [ccusage](https://github.com/ryoppippi/ccusage): pre-calculated `costUSD` when present, deduplication by `messageId + requestId`
30
+ - **17 color themes** — Ember, Gruvbox, Catppuccin, Tokyo Night, Dracula, Nord, and more — each in light and dark, PWA installable
31
+ - **Hub integration** — runs standalone or as a tab in [Claude Code Hub](https://github.com/NikiforovAll/claude-code-hub) alongside Kanban, Marketplace, and Memory
30
32
 
31
- ![Session — Dark](assets/session-dark.png)
32
- ![Session — Light](assets/sesssion-light.png)
33
+ ![Project drill-down with per-session costs](assets/shot-project-sessions.png)
33
34
 
34
- ## Features
35
+ ![Session detail with cumulative cost and per-message table](assets/shot-session-detail.png)
35
36
 
36
- - **Top-down drill-down** — Total cost → per project → per session → per message
37
- - **Dynamic pricing** — Fetches live model prices from [LiteLLM](https://github.com/BerriAI/litellm), supports tiered pricing (200K threshold), cache token costs, and fast mode multipliers
38
- - **Daily cost chart** — Bar chart with cumulative line, configurable date range (1d / 3d / 7d / 30d / 90d / 1y)
39
- - **Model distribution** — Donut chart showing cost breakdown by model
40
- - **Cache efficiency** — Track how well prompt caching is working across your sessions
41
- - **Project breakdown** — See which projects cost the most, sortable by cost, sessions, or activity
42
- - **Session detail** — Message-level cost breakdown with cumulative cost and token stacked bar charts
43
- - **Dark & light theme** — Matches the Claude Code Hub design system
44
- - **Hub integration** — Works as a tab in Claude Code Hub alongside Kanban and Marketplace
45
- - **Instant reload** — API responses cached in browser; Refresh button for fresh data
37
+ ![Dark theme — Tokyo Night](assets/shot-dark-theme.png)
46
38
 
47
39
  ## Configuration
48
40
 
49
- ```bash
50
- PORT=8080 npx claude-code-cost # Custom port
51
- npx claude-code-cost --open # Auto-open browser
52
- npx claude-code-cost --dir=~/.claude-work # Custom Claude config dir
53
41
  ```
54
-
55
- If port 3543 is in use, the server falls back to a random available port.
56
-
57
- ### Global install
58
-
59
- ```bash
60
- npm install -g claude-code-cost
61
- claude-code-cost --open
42
+ --port <number> Custom port (default: 3543, falls back if busy)
43
+ --dir <path> Custom Claude config dir (default: ~/.claude)
44
+ --open Open browser on start
62
45
  ```
63
46
 
64
- ## How It Works
65
-
66
- Claude Code writes conversation logs to `~/.claude/projects/` as JSONL files. Each assistant response includes token counts (`input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`) and model info.
67
-
68
- The dashboard:
69
- 1. **Reads** JSONL session files (streamed line-by-line for large files)
70
- 2. **Fetches** live model pricing from LiteLLM (cached 6h, offline fallback included)
71
- 3. **Calculates** cost per message using tiered pricing with 200K token threshold
72
- 4. **Aggregates** by day, project, and session — all server-side
73
- 5. **Renders** with Chart.js — no build step, vanilla JS
74
-
75
- Nothing is modified — the dashboard is read-only.
76
-
77
- ### Cost Calculation
78
-
79
- Uses the same pricing logic as [ccusage](https://github.com/ryoppippi/ccusage):
80
-
81
- - **Auto mode** — Uses pre-calculated `costUSD` from JSONL when available, otherwise calculates from tokens
82
- - **Tiered pricing** — Tokens above 200K threshold charged at higher rate (Claude 1M context models)
83
- - **Fast mode** — Applies provider-specific multiplier for fast/streaming responses
84
- - **Deduplication** — Skips duplicate messages by `messageId + requestId` hash
85
-
86
- ## FAQ
87
-
88
- **Where does pricing data come from?**
89
- Live from [LiteLLM's pricing dataset](https://github.com/BerriAI/litellm) (2000+ models). Cached for 6 hours. If the fetch fails, a bundled offline snapshot of Claude model prices is used.
90
-
91
- **Does it work offline?**
92
- Yes. The offline pricing fallback covers all current Claude models. PWA support included.
93
-
94
- **Does it modify any files?**
95
- No. Completely read-only — only reads JSONL files from `~/.claude/projects/`.
96
-
97
- **Does it work with Claude Code Hub?**
98
- Yes. Exposes `/hub-config` endpoint and forwards keyboard shortcuts (Ctrl+Alt+Arrow, Alt+1-9) to the hub parent frame.
47
+ The config dir can also be set via the `CLAUDE_CONFIG_DIR` environment variable.
99
48
 
100
49
  ## License
101
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "0.9.0",
3
+ "version": "0.12.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/app.js CHANGED
@@ -9,6 +9,11 @@ let sessionsModelDistribution = null;
9
9
  let sessionDetailData = null;
10
10
  let currentProjectPath = null;
11
11
  let currentProjectName = null;
12
+ // Two distinct notions, deliberately not merged: scope is what the views aggregate over
13
+ // (hub-owned, persisted, never written to the URL by updateUrl); currentProjectPath is the
14
+ // drill-down cursor, and `?project=` in the URL means "I drilled in" to five readers.
15
+ let scopeProject = null;
16
+ let scopeProjectName = null;
12
17
  let currentSessionId = null;
13
18
  let parentView = 'projects';
14
19
  let lastSelectedProject = null;
@@ -112,6 +117,17 @@ function parentBreadcrumb() {
112
117
  return `<a class="parent-breadcrumb">${label}</a>`;
113
118
  }
114
119
 
120
+ // In-view reminder that the numbers below cover one project, not everything. Reuses the
121
+ // breadcrumb styling — same role (where am I), no new CSS.
122
+ function scopeIndicator() {
123
+ if (!scopeProject) return '';
124
+ return `<div class="breadcrumb">
125
+ <span class="current">${esc(scopeProjectName || scopeProject)}</span>
126
+ <span class="sep">/</span>
127
+ <a onclick="clearScope()">all projects</a>
128
+ </div>`;
129
+ }
130
+
115
131
  function focusPreviousRow(view) {
116
132
  let selector;
117
133
  if (view === 'overview' || view === 'projects') {
@@ -159,6 +175,28 @@ function saveDateRange(val) {
159
175
  localStorage.setItem('cc-cost:range', String(val));
160
176
  }
161
177
 
178
+ function loadScope() {
179
+ const raw = localStorage.getItem('cc-cost:scope');
180
+ if (!raw) return;
181
+ try {
182
+ const { encoded, name } = JSON.parse(raw);
183
+ if (encoded) {
184
+ scopeProject = encoded;
185
+ scopeProjectName = name || encoded;
186
+ }
187
+ } catch {
188
+ /* ignore */
189
+ }
190
+ }
191
+
192
+ function saveScope() {
193
+ if (scopeProject) {
194
+ localStorage.setItem('cc-cost:scope', JSON.stringify({ encoded: scopeProject, name: scopeProjectName }));
195
+ } else {
196
+ localStorage.removeItem('cc-cost:scope');
197
+ }
198
+ }
199
+
162
200
  function rangeLabel(r) {
163
201
  return r === 'today' ? 'today' : `${r} days`;
164
202
  }
@@ -202,6 +240,9 @@ function updateUrl() {
202
240
  const BROWSER_CACHE_TTL = 5 * 60 * 1000; // 5 min
203
241
  const CACHE_VERSION = 3;
204
242
  let forceRefresh = false;
243
+ // Age of the data on screen, for the auto-refresh staleness check. A cache hit carries its own
244
+ // timestamp forward, so a reload with a warm cache doesn't look freshly fetched.
245
+ let dataFetchedAt = 0;
205
246
 
206
247
  function getCached(key) {
207
248
  if (forceRefresh) return null;
@@ -210,6 +251,7 @@ function getCached(key) {
210
251
  if (!raw) return null;
211
252
  const { data, ts, v } = JSON.parse(raw);
212
253
  if (v !== CACHE_VERSION || Date.now() - ts > BROWSER_CACHE_TTL) return null;
254
+ dataFetchedAt = Math.max(dataFetchedAt, ts);
213
255
  return data;
214
256
  } catch {
215
257
  return null;
@@ -231,6 +273,9 @@ function pruneLocalCache() {
231
273
  for (let i = 0; i < localStorage.length; i++) {
232
274
  const k = localStorage.key(i);
233
275
  if (!k.startsWith('cc-cost:')) continue;
276
+ // Prefs are not cache entries — they have no ts, so they'd sort oldest-first and be
277
+ // evicted ahead of real data while also eating the entry budget.
278
+ if (isPrefKey(k)) continue;
234
279
  try {
235
280
  const { ts } = JSON.parse(localStorage.getItem(k));
236
281
  entries.push({ k, ts });
@@ -245,7 +290,7 @@ function pruneLocalCache() {
245
290
  }
246
291
 
247
292
  function isPrefKey(k) {
248
- return k.startsWith('cc-cost:sort:') || k === 'cc-cost:range';
293
+ return k.startsWith('cc-cost:sort:') || k === 'cc-cost:range' || k === 'cc-cost:scope';
249
294
  }
250
295
  function clearLocalCache() {
251
296
  const keys = [];
@@ -264,16 +309,43 @@ async function fetchJSON(url, skipCache) {
264
309
  const res = await fetch(url);
265
310
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
266
311
  const data = await res.json();
312
+ dataFetchedAt = Date.now();
267
313
  if (!skipCache) setLocalCache(url, data);
268
314
  return data;
269
315
  }
270
316
 
317
+ // fetchJSON caches by full URL, so the scoped and unscoped variants key apart for free.
318
+ function scopeParam() {
319
+ return scopeProject ? `&project=${encodeURIComponent(scopeProject)}` : '';
320
+ }
321
+
271
322
  async function fetchOverview() {
272
- overviewData = await fetchJSON(`/api/overview?range=${dateRange}`);
323
+ overviewData = await fetchJSON(`/api/overview?range=${dateRange}${scopeParam()}`);
324
+ }
325
+
326
+ // Fire-and-forget label upgrade: /api/projects/:path/sessions carries no project name, so ask
327
+ // the scoped projects endpoint (one row) for the decoded one.
328
+ async function resolveScopeName() {
329
+ const target = scopeProject;
330
+ try {
331
+ const rows = await fetchJSON(`/api/projects?range=${dateRange}${scopeParam()}`);
332
+ const name = rows?.[0]?.encodedPath === target ? rows[0].name : null;
333
+ if (!name || scopeProject !== target) return;
334
+ scopeProjectName = name;
335
+ if (currentProjectPath === target) currentProjectName = name;
336
+ saveScope();
337
+ renderScopeChip();
338
+ lastRenderHash = {};
339
+ // Repaint via loadAndRender rather than a renderer directly: fetchJSON serves the already
340
+ // cached payloads, so this is a re-render, not a second round trip.
341
+ await loadAndRender(currentView);
342
+ } catch {
343
+ /* label stays encoded — cosmetic only */
344
+ }
273
345
  }
274
346
 
275
347
  async function fetchProjects() {
276
- projectsData = await fetchJSON(`/api/projects?range=${dateRange}`);
348
+ projectsData = await fetchJSON(`/api/projects?range=${dateRange}${scopeParam()}`);
277
349
  }
278
350
 
279
351
  async function fetchSessions(encodedPath) {
@@ -305,15 +377,31 @@ function renderOverview() {
305
377
  }
306
378
 
307
379
  const s = overviewData.summary;
308
- const h = JSON.stringify({ overviewData, sort: viewSort.overview });
380
+ // Scope is in the hash because two different empty projects produce byte-identical payloads —
381
+ // without it the indicator label would never repaint.
382
+ const h = JSON.stringify({ overviewData, sort: viewSort.overview, scopeProject, scopeProjectName });
309
383
  if (lastRenderHash.overview === h) return;
310
384
  lastRenderHash.overview = h;
311
385
 
312
386
  const daily = overviewData.daily || [];
313
387
  const models = overviewData.modelDistribution || [];
314
388
 
389
+ // Return before any chart call so no canvas is touched — there are none in this markup.
390
+ if (scopeProject && s.totalSessions === 0) {
391
+ el.innerHTML = `<div class="dashboard-content">
392
+ ${scopeIndicator()}
393
+ <div class="empty-state">
394
+ <div class="empty-icon">$</div>
395
+ <div>No usage for ${esc(scopeProjectName || scopeProject)} in the last ${rangeLabel(dateRange)}</div>
396
+ <div>Clear the project scope to see everything.</div>
397
+ </div>
398
+ </div>`;
399
+ return;
400
+ }
401
+
315
402
  el.innerHTML = `
316
403
  <div class="dashboard-content">
404
+ ${scopeIndicator()}
317
405
  <div class="cards-row">
318
406
  <div class="stat-card">
319
407
  <div class="card-label">Today</div>
@@ -404,24 +492,31 @@ function renderProjects() {
404
492
  return;
405
493
  }
406
494
 
407
- const h = JSON.stringify({ projectsData, sort: viewSort.projects });
495
+ const h = JSON.stringify({ projectsData, sort: viewSort.projects, scopeProject, scopeProjectName });
408
496
  if (lastRenderHash.projects === h) return;
409
497
  lastRenderHash.projects = h;
410
498
 
411
499
  const sorted = [...projectsData].sort((a, b) => sortCompare(a, b, viewSort.projects.field, viewSort.projects.order));
412
500
 
413
501
  if (sorted.length === 0) {
414
- el.innerHTML = `<div class="dashboard-content"><div class="empty-state">
502
+ el.innerHTML = `<div class="dashboard-content">
503
+ ${scopeIndicator()}
504
+ <div class="empty-state">
415
505
  <div class="empty-icon">$</div>
416
- <div>No project data found</div>
417
- <div>Make sure Claude Code session files exist in ~/.claude/projects/</div>
506
+ ${
507
+ scopeProject
508
+ ? `<div>No usage for ${esc(scopeProjectName || scopeProject)} in the last ${rangeLabel(dateRange)}</div>
509
+ <div>Clear the project scope to see everything.</div>`
510
+ : `<div>No project data found</div>
511
+ <div>Make sure Claude Code session files exist in ~/.claude/projects/</div>`
512
+ }
418
513
  </div></div>`;
419
514
  return;
420
515
  }
421
516
 
422
517
  el.innerHTML = `
423
518
  <div class="dashboard-content">
424
- <div class="section-title">All Projects</div>
519
+ ${scopeProject ? scopeIndicator() : '<div class="section-title">All Projects</div>'}
425
520
  <table class="data-table">
426
521
  <thead><tr>
427
522
  <th class="${thClass('name')}" onclick="sortBy('name')">Project ${sortArrow('name')}</th>
@@ -967,7 +1062,7 @@ function buildThemeMenu() {
967
1062
  const menu = document.getElementById('themeMenu');
968
1063
  menu.innerHTML = COLOR_THEMES.map(
969
1064
  ([id, label]) =>
970
- `<button type="button" class="theme-menu-item" data-theme-id="${id}"
1065
+ `<button type="button" class="theme-menu-item theme-swatch-${id}" data-theme-id="${id}"
971
1066
  onclick="event.stopPropagation(); setColorTheme('${id}'); toggleThemeMenu()">
972
1067
  <span class="theme-swatch theme-swatch-${id}"><i class="sw-bg"></i><i class="sw-accent"></i><i class="sw-ink"></i></span>${label}
973
1068
  </button>`,
@@ -1096,6 +1191,45 @@ async function onRangeChange(val) {
1096
1191
  dismissToast(t);
1097
1192
  }
1098
1193
 
1194
+ function renderScopeChip() {
1195
+ const chip = document.getElementById('scopeChip');
1196
+ if (!chip) return;
1197
+ chip.hidden = !scopeProject;
1198
+ if (scopeProject) {
1199
+ document.getElementById('scopeChipName').textContent = scopeProjectName || scopeProject;
1200
+ }
1201
+ }
1202
+
1203
+ // Assigns before the first await (the lastTheme echo-suppression idiom), so the hub's
1204
+ // per-iframe-load replay of the same project is absorbed for free.
1205
+ async function applyScope(encoded, name) {
1206
+ if (encoded === scopeProject) return;
1207
+ scopeProject = encoded || null;
1208
+ scopeProjectName = encoded ? name || encoded : null;
1209
+ saveScope();
1210
+ lastRenderHash = {};
1211
+ renderScopeChip();
1212
+
1213
+ if (!scopeProject) {
1214
+ // Clearing drops the cursor too — it was the scope, and there is nothing left to drill into.
1215
+ await navigate('overview');
1216
+ return;
1217
+ }
1218
+ // A scope means "show me this project", so land on its sessions rather than a one-row
1219
+ // overview. Null the stale payloads first so the loading state shows, not the old project's
1220
+ // rows.
1221
+ sessionsData = null;
1222
+ sessionDetailData = null;
1223
+ parentView = 'overview';
1224
+ await navigate('sessions', { project: scopeProject, projectName: scopeProjectName });
1225
+ }
1226
+
1227
+ // biome-ignore lint/correctness/noUnusedVariables: called from HTML onclick
1228
+ async function clearScope() {
1229
+ // No redirect when clearing: the cursor is still a valid drill-down.
1230
+ await applyScope(null, null);
1231
+ }
1232
+
1099
1233
  async function refreshData() {
1100
1234
  const btn = document.getElementById('refreshBtn');
1101
1235
  btn.classList.add('loading');
@@ -1351,6 +1485,47 @@ function dismissToast(el) {
1351
1485
 
1352
1486
  // #endregion
1353
1487
 
1488
+ // #region AUTO_REFRESH
1489
+
1490
+ // Whether cost is the app the user is looking at. document.hidden alone can't answer that inside
1491
+ // the hub: the hub hides inactive apps with display:none, and a nested document's visibilityState
1492
+ // mirrors the top-level tab regardless. So the hub tells us (hub:active); standalone stays true.
1493
+ let hubActive = true;
1494
+ const STALE_CHECK_MS = 30_000;
1495
+ // Three triggers share refreshIfStale (interval, visibilitychange, hub:active), so they'd otherwise
1496
+ // overlap and the first one's finally would clear forceRefresh out from under the others.
1497
+ let refreshing = false;
1498
+
1499
+ function isAppActive() {
1500
+ return !document.hidden && hubActive;
1501
+ }
1502
+
1503
+ async function refreshIfStale() {
1504
+ if (refreshing || !isAppActive()) return;
1505
+ if (Date.now() - dataFetchedAt < BROWSER_CACHE_TTL) return;
1506
+ // No clearLocalCache() unlike refreshData: forceRefresh already bypasses the cache read, and the
1507
+ // fresh payloads overwrite their own keys. Views the user isn't on keep their cache.
1508
+ refreshing = true;
1509
+ forceRefresh = true;
1510
+ try {
1511
+ await loadAndRender(currentView);
1512
+ } catch {
1513
+ /* transient — the next tick retries */
1514
+ } finally {
1515
+ forceRefresh = false;
1516
+ refreshing = false;
1517
+ }
1518
+ }
1519
+
1520
+ (function initAutoRefresh() {
1521
+ // Polled rather than a 5-min timer: staleness also has to be re-evaluated the moment the app
1522
+ // becomes active again, and a single clock keeps the two paths from racing.
1523
+ setInterval(refreshIfStale, STALE_CHECK_MS);
1524
+ document.addEventListener('visibilitychange', refreshIfStale);
1525
+ })();
1526
+
1527
+ // #endregion
1528
+
1354
1529
  // #region HUB_INTEGRATION
1355
1530
 
1356
1531
  (async function initHub() {
@@ -1362,17 +1537,26 @@ function dismissToast(el) {
1362
1537
  window.__HUB__ = cfg;
1363
1538
 
1364
1539
  document.addEventListener('keydown', (e) => {
1365
- if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
1540
+ const fwd = (key) => {
1366
1541
  e.preventDefault();
1367
- window.parent?.postMessage({ type: 'hub:keydown', key: e.key }, '*');
1542
+ window.parent?.postMessage({ type: 'hub:keydown', key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey }, '*');
1543
+ };
1544
+ if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
1545
+ fwd(e.key);
1546
+ }
1547
+ // Its own branch: the Alt+digit case below requires !ctrlKey.
1548
+ if (e.ctrlKey && e.altKey && !e.shiftKey && !e.metaKey && e.key.toLowerCase() === 'p') {
1549
+ fwd(e.key);
1368
1550
  }
1369
1551
  if (e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey && /^[1-9]$/.test(e.key)) {
1370
- e.preventDefault();
1371
- window.parent?.postMessage({ type: 'hub:keydown', key: e.key }, '*');
1552
+ fwd(e.key);
1372
1553
  }
1373
1554
  });
1374
1555
  })();
1375
1556
 
1557
+ // Hoisted out of initHubTheme so initHubProject can share it.
1558
+ const hubOrigin = () => (window.__HUB__?.url ? new URL(window.__HUB__.url).origin : null);
1559
+
1376
1560
  window.hubNavigate = function hubNavigate(app, url) {
1377
1561
  if (!window.__HUB__?.enabled) return;
1378
1562
  window.parent?.postMessage({ type: 'hub:navigate', app, url }, '*');
@@ -1381,7 +1565,6 @@ window.hubNavigate = function hubNavigate(app, url) {
1381
1565
  (function initHubTheme() {
1382
1566
  const getTheme = () => (document.body.classList.contains('light') ? 'light' : 'dark');
1383
1567
  const getColorTheme = () => document.body.dataset.colorTheme || 'ember';
1384
- const hubOrigin = () => (window.__HUB__?.url ? new URL(window.__HUB__.url).origin : null);
1385
1568
  // lastTheme/lastColorTheme are updated synchronously when applying a hub
1386
1569
  // message, so the (async) observer sees no diff and doesn't echo it back.
1387
1570
  let lastTheme = getTheme();
@@ -1412,6 +1595,27 @@ window.hubNavigate = function hubNavigate(app, url) {
1412
1595
  });
1413
1596
  })();
1414
1597
 
1598
+ (function initHubActive() {
1599
+ window.addEventListener('message', (e) => {
1600
+ if (e.source !== window.parent || e.origin !== hubOrigin()) return;
1601
+ if (e.data?.type !== 'hub:active') return;
1602
+ hubActive = !!e.data.active;
1603
+ // Becoming active is the main refresh trigger — the interval only covers staying active.
1604
+ if (hubActive) refreshIfStale();
1605
+ });
1606
+ })();
1607
+
1608
+ (function initHubProject() {
1609
+ window.addEventListener('message', (e) => {
1610
+ if (e.source !== window.parent || e.origin !== hubOrigin()) return;
1611
+ if (e.data?.type !== 'hub:project') return;
1612
+ // The hub owns the abs->encoded transform, so cost never converts anything itself.
1613
+ const encoded = e.data.encoded;
1614
+ if (typeof encoded !== 'string' || !encoded) return;
1615
+ applyScope(encoded, e.data.name);
1616
+ });
1617
+ })();
1618
+
1415
1619
  // #endregion
1416
1620
 
1417
1621
  // #region INIT
@@ -1432,6 +1636,21 @@ document.addEventListener('DOMContentLoaded', async () => {
1432
1636
  dateRange = loadDateRange();
1433
1637
  document.getElementById('rangeSelect').value = dateRange;
1434
1638
 
1639
+ // Resolve the scope before any navigate() so the first /api/overview already carries
1640
+ // &project=. Read window.location.search directly, not getUrlState() — that falls back to
1641
+ // sessionStorage['cc-cost:nav'] when the URL has no view/session/project, which would
1642
+ // discard a scope-only URL.
1643
+ loadScope();
1644
+ const urlScope = new URLSearchParams(window.location.search).get('scope');
1645
+ if (urlScope) {
1646
+ scopeProject = urlScope;
1647
+ scopeProjectName = urlScope;
1648
+ saveScope();
1649
+ }
1650
+ renderScopeChip();
1651
+ // A ?scope= deep link carries only the encoded dir name; the hub always sends a real one.
1652
+ if (scopeProject && scopeProjectName === scopeProject) resolveScopeName();
1653
+
1435
1654
  if (state.session) {
1436
1655
  currentSessionId = state.session;
1437
1656
  parentView = state.parentView;
@@ -1445,6 +1664,11 @@ document.addEventListener('DOMContentLoaded', async () => {
1445
1664
  await navigate('sessions', { project: state.project, projectName: state.projectName });
1446
1665
  } else if (state.view === 'projects') {
1447
1666
  await navigate('projects');
1667
+ } else if (scopeProject) {
1668
+ // Same landing rule as applyScope: a scope with no cursor of its own opens its sessions.
1669
+ parentView = 'overview';
1670
+ currentProjectName = scopeProjectName;
1671
+ await navigate('sessions', { project: scopeProject, projectName: scopeProjectName });
1448
1672
  } else {
1449
1673
  await navigate('overview');
1450
1674
  }
package/public/index.html CHANGED
@@ -34,6 +34,10 @@
34
34
  <button class="topbar-nav-btn active" data-view="overview" onclick="navigate('overview')">Overview</button>
35
35
  <button class="topbar-nav-btn" data-view="projects" onclick="navigate('projects')">Projects</button>
36
36
  </div>
37
+ <span class="scope-chip" id="scopeChip" hidden title="Scoped to one project">
38
+ <span id="scopeChipName"></span>
39
+ <button class="scope-chip-clear" onclick="clearScope()" title="Clear project scope">&times;</button>
40
+ </span>
37
41
  <select class="topbar-select" id="rangeSelect" onchange="onRangeChange(this.value)">
38
42
  <option value="today">Today</option>
39
43
  <option value="1">1 day</option>
@@ -98,6 +102,7 @@
98
102
  <tr><td><kbd>R</kbd></td><td>Refresh data</td></tr>
99
103
  <tr><td><kbd>T</kbd></td><td>Toggle theme</td></tr>
100
104
  <tr><td><kbd>?</kbd></td><td>Show this help</td></tr>
105
+ <tr><td><kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>P</kbd></td><td>Switch project (hub only)</td></tr>
101
106
  </table>
102
107
  </div>
103
108
  </div>
package/public/style.css CHANGED
@@ -174,6 +174,50 @@ body {
174
174
  color: var(--text-primary);
175
175
  }
176
176
 
177
+ /* #region SCOPE_CHIP */
178
+
179
+ /* Reuses --accent-dim/--accent-text from .topbar-nav-btn.active so LIGHT_THEME needs nothing. */
180
+ .scope-chip {
181
+ display: flex;
182
+ align-items: center;
183
+ gap: 4px;
184
+ background: var(--accent-dim);
185
+ color: var(--accent-text);
186
+ border-radius: 6px;
187
+ font-family: var(--mono);
188
+ font-size: 11px;
189
+ padding: 4px 4px 4px 8px;
190
+ max-width: 220px;
191
+ }
192
+
193
+ .scope-chip[hidden] {
194
+ display: none;
195
+ }
196
+
197
+ .scope-chip > span {
198
+ overflow: hidden;
199
+ text-overflow: ellipsis;
200
+ white-space: nowrap;
201
+ }
202
+
203
+ .scope-chip-clear {
204
+ background: none;
205
+ border: none;
206
+ color: inherit;
207
+ cursor: pointer;
208
+ font-family: inherit;
209
+ font-size: 13px;
210
+ line-height: 1;
211
+ opacity: 0.7;
212
+ padding: 0 3px;
213
+ }
214
+
215
+ .scope-chip-clear:hover {
216
+ opacity: 1;
217
+ }
218
+
219
+ /* #endregion */
220
+
177
221
  .topbar-btn {
178
222
  display: flex;
179
223
  align-items: center;
@@ -247,8 +291,11 @@ body {
247
291
  background: var(--bg-hover);
248
292
  color: var(--text-primary);
249
293
  }
294
+ /* Highlighted with the row's *own* theme accent rather than the active theme's, so the selected
295
+ row previews the theme it names. --sw-accent comes from the theme-swatch-<id> class on the row. */
250
296
  .theme-menu-item.on {
251
- color: var(--accent-text);
297
+ color: var(--sw-accent, var(--accent-text));
298
+ background: color-mix(in srgb, var(--sw-accent, var(--accent-text)) 16%, transparent);
252
299
  }
253
300
  /* 3-dot palette preview: surface, accent, ink (colors from themes.css vars) */
254
301
  .theme-swatch {
package/server.js CHANGED
@@ -19,7 +19,7 @@ function getArg(name) {
19
19
  }
20
20
 
21
21
  const PORT = getArg('port') || process.env.PORT || 3543;
22
- const claudeDirArg = getArg('dir');
22
+ const claudeDirArg = getArg('dir') || process.env.CLAUDE_CONFIG_DIR || process.env.CLAUDE_DIR;
23
23
  const CLAUDE_DIR = claudeDirArg
24
24
  ? claudeDirArg.replace(/^~/, os.homedir())
25
25
  : path.join(os.homedir(), '.claude');
@@ -255,7 +255,9 @@ function buildModelDistribution(modelCosts) {
255
255
  .sort((a, b) => b.cost - a.cost);
256
256
  }
257
257
 
258
- function scanProjectDirs(cutoffDate) {
258
+ // onlyKey narrows the scan to a single encoded project dir. The dir name *is* the key, so this
259
+ // skips the per-project readdir and per-file statSync for everything else.
260
+ function scanProjectDirs(cutoffDate, onlyKey) {
259
261
  const projects = new Map();
260
262
  const cutoffMs = cutoffDate ? cutoffDate.getTime() : 0;
261
263
  for (const baseDir of getProjectsDirs()) {
@@ -263,6 +265,7 @@ function scanProjectDirs(cutoffDate) {
263
265
  const entries = fs.readdirSync(baseDir, { withFileTypes: true });
264
266
  for (const entry of entries) {
265
267
  if (!entry.isDirectory()) continue;
268
+ if (onlyKey && entry.name !== onlyKey) continue;
266
269
  const projDir = path.join(baseDir, entry.name);
267
270
  const files = [];
268
271
  try {
@@ -499,14 +502,14 @@ function rangeToCutoff(range, now) {
499
502
  return c;
500
503
  }
501
504
 
502
- async function getOverviewData(range) {
503
- const cacheKey = `overview_${range}`;
505
+ async function getOverviewData(range, projectFilter) {
506
+ const cacheKey = `overview_${range}_${projectFilter || 'all'}`;
504
507
  if (isCacheValid(cacheKey)) return dataCache[cacheKey];
505
508
 
506
509
  const pricing = await fetchPricing();
507
510
  const now = new Date();
508
511
  const cutoff = rangeToCutoff(range, now) || new Date(now);
509
- const projects = scanProjectDirs(cutoff);
512
+ const projects = scanProjectDirs(cutoff, projectFilter);
510
513
  const cutoffStr = cutoff.toISOString();
511
514
 
512
515
  let totalCost = 0, totalSessions = 0;
@@ -592,14 +595,14 @@ async function getOverviewData(range) {
592
595
  return result;
593
596
  }
594
597
 
595
- async function getProjectsData(range) {
596
- const cacheKey = `projects_${range || 'all'}`;
598
+ async function getProjectsData(range, projectFilter) {
599
+ const cacheKey = `projects_${range || 'all'}_${projectFilter || 'all'}`;
597
600
  if (isCacheValid(cacheKey)) return dataCache[cacheKey];
598
601
 
599
602
  const pricing = await fetchPricing();
600
603
  const now = new Date();
601
604
  const cutoff = rangeToCutoff(range, now);
602
- const projects = scanProjectDirs(cutoff);
605
+ const projects = scanProjectDirs(cutoff, projectFilter);
603
606
  const cutoffStr = cutoff ? cutoff.toISOString() : null;
604
607
  const result = [];
605
608
 
@@ -790,10 +793,24 @@ function parseRange(raw, fallback = null) {
790
793
  return Number.isFinite(n) ? n : fallback;
791
794
  }
792
795
 
796
+ // Encoded project-dir name (the hub sends it pre-encoded — see encodeProjectPath in the hub's
797
+ // public/app.js; this regex must stay a superset of that transform's output). Only ever used as
798
+ // a Map key, never joined into a path — the regex exists to keep unbounded strings out of the
799
+ // cache keys.
800
+ // Returns undefined for absent, null for malformed, so callers can 400 instead of silently
801
+ // dropping the scope.
802
+ function parseProject(raw) {
803
+ if (raw === undefined || raw === '') return undefined;
804
+ if (typeof raw !== 'string' || !/^[A-Za-z0-9._-]+$/.test(raw)) return null;
805
+ return raw;
806
+ }
807
+
793
808
  app.get('/api/overview', async (req, res) => {
794
809
  try {
795
810
  const range = parseRange(req.query.range, 30);
796
- const data = await getOverviewData(range);
811
+ const project = parseProject(req.query.project);
812
+ if (project === null) return res.status(400).json({ error: 'Invalid project' });
813
+ const data = await getOverviewData(range, project);
797
814
  res.json(data);
798
815
  } catch (err) {
799
816
  console.error('[API] overview error:', err);
@@ -804,7 +821,9 @@ app.get('/api/overview', async (req, res) => {
804
821
  app.get('/api/projects', async (req, res) => {
805
822
  try {
806
823
  const range = parseRange(req.query.range);
807
- const data = await getProjectsData(range);
824
+ const project = parseProject(req.query.project);
825
+ if (project === null) return res.status(400).json({ error: 'Invalid project' });
826
+ const data = await getProjectsData(range, project);
808
827
  res.json(data);
809
828
  } catch (err) {
810
829
  console.error('[API] projects error:', err);