claude-code-cost 0.10.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "0.10.0",
3
+ "version": "0.12.1",
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,55 @@ 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
+ // Scope teardown without applyScope's landing rule, for callers that navigate themselves.
1228
+ function dropScope() {
1229
+ if (!scopeProject) return;
1230
+ scopeProject = null;
1231
+ scopeProjectName = null;
1232
+ saveScope();
1233
+ lastRenderHash = {};
1234
+ renderScopeChip();
1235
+ }
1236
+
1237
+ // biome-ignore lint/correctness/noUnusedVariables: called from HTML onclick
1238
+ async function clearScope() {
1239
+ // No redirect when clearing: the cursor is still a valid drill-down.
1240
+ await applyScope(null, null);
1241
+ }
1242
+
1099
1243
  async function refreshData() {
1100
1244
  const btn = document.getElementById('refreshBtn');
1101
1245
  btn.classList.add('loading');
@@ -1240,21 +1384,23 @@ function activateSelectedRow() {
1240
1384
  async function goBack() {
1241
1385
  let target;
1242
1386
  if (currentView === 'detail') {
1243
- if (currentProjectPath) {
1244
- target = 'sessions';
1245
- await navigate('sessions', { project: currentProjectPath, projectName: currentProjectName });
1246
- } else {
1247
- target = parentView;
1248
- await navigate(parentView);
1249
- }
1387
+ target = currentProjectPath ? 'sessions' : parentView;
1250
1388
  } else if (currentView === 'sessions') {
1251
1389
  target = parentView;
1252
- await navigate(parentView);
1253
1390
  } else if (currentView === 'projects') {
1254
1391
  target = 'overview';
1255
- await navigate('overview');
1256
1392
  }
1257
- if (target) focusPreviousRow(target);
1393
+ if (!target) return;
1394
+
1395
+ if (target === 'sessions') {
1396
+ await navigate('sessions', { project: currentProjectPath, projectName: currentProjectName });
1397
+ } else {
1398
+ // Backing out to a top-level view drops the scope with the cursor: a scoped overview
1399
+ // showing one project has no visible cause once you've left that project behind.
1400
+ dropScope();
1401
+ await navigate(target);
1402
+ }
1403
+ focusPreviousRow(target);
1258
1404
  }
1259
1405
 
1260
1406
  document.addEventListener('keydown', (e) => {
@@ -1351,6 +1497,47 @@ function dismissToast(el) {
1351
1497
 
1352
1498
  // #endregion
1353
1499
 
1500
+ // #region AUTO_REFRESH
1501
+
1502
+ // Whether cost is the app the user is looking at. document.hidden alone can't answer that inside
1503
+ // the hub: the hub hides inactive apps with display:none, and a nested document's visibilityState
1504
+ // mirrors the top-level tab regardless. So the hub tells us (hub:active); standalone stays true.
1505
+ let hubActive = true;
1506
+ const STALE_CHECK_MS = 30_000;
1507
+ // Three triggers share refreshIfStale (interval, visibilitychange, hub:active), so they'd otherwise
1508
+ // overlap and the first one's finally would clear forceRefresh out from under the others.
1509
+ let refreshing = false;
1510
+
1511
+ function isAppActive() {
1512
+ return !document.hidden && hubActive;
1513
+ }
1514
+
1515
+ async function refreshIfStale() {
1516
+ if (refreshing || !isAppActive()) return;
1517
+ if (Date.now() - dataFetchedAt < BROWSER_CACHE_TTL) return;
1518
+ // No clearLocalCache() unlike refreshData: forceRefresh already bypasses the cache read, and the
1519
+ // fresh payloads overwrite their own keys. Views the user isn't on keep their cache.
1520
+ refreshing = true;
1521
+ forceRefresh = true;
1522
+ try {
1523
+ await loadAndRender(currentView);
1524
+ } catch {
1525
+ /* transient — the next tick retries */
1526
+ } finally {
1527
+ forceRefresh = false;
1528
+ refreshing = false;
1529
+ }
1530
+ }
1531
+
1532
+ (function initAutoRefresh() {
1533
+ // Polled rather than a 5-min timer: staleness also has to be re-evaluated the moment the app
1534
+ // becomes active again, and a single clock keeps the two paths from racing.
1535
+ setInterval(refreshIfStale, STALE_CHECK_MS);
1536
+ document.addEventListener('visibilitychange', refreshIfStale);
1537
+ })();
1538
+
1539
+ // #endregion
1540
+
1354
1541
  // #region HUB_INTEGRATION
1355
1542
 
1356
1543
  (async function initHub() {
@@ -1362,17 +1549,26 @@ function dismissToast(el) {
1362
1549
  window.__HUB__ = cfg;
1363
1550
 
1364
1551
  document.addEventListener('keydown', (e) => {
1365
- if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
1552
+ const fwd = (key) => {
1366
1553
  e.preventDefault();
1367
- window.parent?.postMessage({ type: 'hub:keydown', key: e.key }, '*');
1554
+ window.parent?.postMessage({ type: 'hub:keydown', key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey }, '*');
1555
+ };
1556
+ if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
1557
+ fwd(e.key);
1558
+ }
1559
+ // Its own branch: the Alt+digit case below requires !ctrlKey.
1560
+ if (e.ctrlKey && e.altKey && !e.shiftKey && !e.metaKey && e.key.toLowerCase() === 'p') {
1561
+ fwd(e.key);
1368
1562
  }
1369
1563
  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 }, '*');
1564
+ fwd(e.key);
1372
1565
  }
1373
1566
  });
1374
1567
  })();
1375
1568
 
1569
+ // Hoisted out of initHubTheme so initHubProject can share it.
1570
+ const hubOrigin = () => (window.__HUB__?.url ? new URL(window.__HUB__.url).origin : null);
1571
+
1376
1572
  window.hubNavigate = function hubNavigate(app, url) {
1377
1573
  if (!window.__HUB__?.enabled) return;
1378
1574
  window.parent?.postMessage({ type: 'hub:navigate', app, url }, '*');
@@ -1381,7 +1577,6 @@ window.hubNavigate = function hubNavigate(app, url) {
1381
1577
  (function initHubTheme() {
1382
1578
  const getTheme = () => (document.body.classList.contains('light') ? 'light' : 'dark');
1383
1579
  const getColorTheme = () => document.body.dataset.colorTheme || 'ember';
1384
- const hubOrigin = () => (window.__HUB__?.url ? new URL(window.__HUB__.url).origin : null);
1385
1580
  // lastTheme/lastColorTheme are updated synchronously when applying a hub
1386
1581
  // message, so the (async) observer sees no diff and doesn't echo it back.
1387
1582
  let lastTheme = getTheme();
@@ -1412,6 +1607,27 @@ window.hubNavigate = function hubNavigate(app, url) {
1412
1607
  });
1413
1608
  })();
1414
1609
 
1610
+ (function initHubActive() {
1611
+ window.addEventListener('message', (e) => {
1612
+ if (e.source !== window.parent || e.origin !== hubOrigin()) return;
1613
+ if (e.data?.type !== 'hub:active') return;
1614
+ hubActive = !!e.data.active;
1615
+ // Becoming active is the main refresh trigger — the interval only covers staying active.
1616
+ if (hubActive) refreshIfStale();
1617
+ });
1618
+ })();
1619
+
1620
+ (function initHubProject() {
1621
+ window.addEventListener('message', (e) => {
1622
+ if (e.source !== window.parent || e.origin !== hubOrigin()) return;
1623
+ if (e.data?.type !== 'hub:project') return;
1624
+ // The hub owns the abs->encoded transform, so cost never converts anything itself.
1625
+ const encoded = e.data.encoded;
1626
+ if (typeof encoded !== 'string' || !encoded) return;
1627
+ applyScope(encoded, e.data.name);
1628
+ });
1629
+ })();
1630
+
1415
1631
  // #endregion
1416
1632
 
1417
1633
  // #region INIT
@@ -1432,6 +1648,21 @@ document.addEventListener('DOMContentLoaded', async () => {
1432
1648
  dateRange = loadDateRange();
1433
1649
  document.getElementById('rangeSelect').value = dateRange;
1434
1650
 
1651
+ // Resolve the scope before any navigate() so the first /api/overview already carries
1652
+ // &project=. Read window.location.search directly, not getUrlState() — that falls back to
1653
+ // sessionStorage['cc-cost:nav'] when the URL has no view/session/project, which would
1654
+ // discard a scope-only URL.
1655
+ loadScope();
1656
+ const urlScope = new URLSearchParams(window.location.search).get('scope');
1657
+ if (urlScope) {
1658
+ scopeProject = urlScope;
1659
+ scopeProjectName = urlScope;
1660
+ saveScope();
1661
+ }
1662
+ renderScopeChip();
1663
+ // A ?scope= deep link carries only the encoded dir name; the hub always sends a real one.
1664
+ if (scopeProject && scopeProjectName === scopeProject) resolveScopeName();
1665
+
1435
1666
  if (state.session) {
1436
1667
  currentSessionId = state.session;
1437
1668
  parentView = state.parentView;
@@ -1445,6 +1676,11 @@ document.addEventListener('DOMContentLoaded', async () => {
1445
1676
  await navigate('sessions', { project: state.project, projectName: state.projectName });
1446
1677
  } else if (state.view === 'projects') {
1447
1678
  await navigate('projects');
1679
+ } else if (scopeProject) {
1680
+ // Same landing rule as applyScope: a scope with no cursor of its own opens its sessions.
1681
+ parentView = 'overview';
1682
+ currentProjectName = scopeProjectName;
1683
+ await navigate('sessions', { project: scopeProject, projectName: scopeProjectName });
1448
1684
  } else {
1449
1685
  await navigate('overview');
1450
1686
  }
package/public/index.html CHANGED
@@ -34,6 +34,14 @@
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" aria-label="Clear project scope">
40
+ <svg viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">
41
+ <path d="M3 3l6 6M9 3l-6 6"/>
42
+ </svg>
43
+ </button>
44
+ </span>
37
45
  <select class="topbar-select" id="rangeSelect" onchange="onRangeChange(this.value)">
38
46
  <option value="today">Today</option>
39
47
  <option value="1">1 day</option>
@@ -98,6 +106,7 @@
98
106
  <tr><td><kbd>R</kbd></td><td>Refresh data</td></tr>
99
107
  <tr><td><kbd>T</kbd></td><td>Toggle theme</td></tr>
100
108
  <tr><td><kbd>?</kbd></td><td>Show this help</td></tr>
109
+ <tr><td><kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>P</kbd></td><td>Switch project (hub only)</td></tr>
101
110
  </table>
102
111
  </div>
103
112
  </div>
package/public/style.css CHANGED
@@ -155,18 +155,33 @@ body {
155
155
  color: var(--accent-text);
156
156
  }
157
157
 
158
+ /* Native chevron is OS-styled and clashes with the mono topbar, so appearance is reset
159
+ and the chevron redrawn; its gray reads as tertiary text in both themes. */
158
160
  .topbar-select {
159
- background: var(--bg-elevated);
161
+ appearance: none;
162
+ background-color: var(--bg-elevated);
163
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6' fill='none' stroke='%238a8d95' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M1 1.5L5 5 9 1.5'/%3E%3C/svg%3E");
164
+ background-repeat: no-repeat;
165
+ background-position: right 9px center;
166
+ background-size: 9px 6px;
160
167
  border: 1px solid var(--border);
161
168
  border-radius: 6px;
162
- color: var(--text-secondary);
169
+ color: var(--text-tertiary);
163
170
  font-family: var(--mono);
164
171
  font-size: 11px;
165
- padding: 4px 8px;
172
+ font-weight: 500;
173
+ letter-spacing: 0.03em;
174
+ text-transform: uppercase;
175
+ padding: 6px 26px 6px 10px;
166
176
  outline: none;
167
177
  cursor: pointer;
178
+ transition: all 0.15s ease;
179
+ }
180
+ .topbar-select:hover {
181
+ border-color: var(--accent);
182
+ color: var(--text-secondary);
168
183
  }
169
- .topbar-select:focus {
184
+ .topbar-select:focus-visible {
170
185
  border-color: var(--accent);
171
186
  }
172
187
  .topbar-select option {
@@ -174,6 +189,59 @@ body {
174
189
  color: var(--text-primary);
175
190
  }
176
191
 
192
+ /* #region SCOPE_CHIP */
193
+
194
+ /* Reuses --accent-dim/--accent-text from .topbar-nav-btn.active so LIGHT_THEME needs nothing. */
195
+ .scope-chip {
196
+ display: flex;
197
+ align-items: center;
198
+ gap: 4px;
199
+ background: var(--accent-dim);
200
+ color: var(--accent-text);
201
+ border-radius: 6px;
202
+ font-family: var(--mono);
203
+ font-size: 11px;
204
+ padding: 4px 4px 4px 8px;
205
+ max-width: 220px;
206
+ }
207
+
208
+ .scope-chip[hidden] {
209
+ display: none;
210
+ }
211
+
212
+ .scope-chip > span {
213
+ overflow: hidden;
214
+ text-overflow: ellipsis;
215
+ white-space: nowrap;
216
+ }
217
+
218
+ /* SVG cross instead of a &times; glyph: the glyph's ink sits ~1px below its line box, so it never centers. */
219
+ .scope-chip-clear {
220
+ display: flex;
221
+ align-items: center;
222
+ justify-content: center;
223
+ width: 15px;
224
+ height: 15px;
225
+ padding: 0;
226
+ background: none;
227
+ border: none;
228
+ border-radius: 4px;
229
+ color: inherit;
230
+ cursor: pointer;
231
+ opacity: 0.7;
232
+ }
233
+
234
+ .scope-chip-clear svg {
235
+ width: 10px;
236
+ height: 10px;
237
+ }
238
+
239
+ .scope-chip-clear:hover {
240
+ opacity: 1;
241
+ }
242
+
243
+ /* #endregion */
244
+
177
245
  .topbar-btn {
178
246
  display: flex;
179
247
  align-items: center;
@@ -247,8 +315,11 @@ body {
247
315
  background: var(--bg-hover);
248
316
  color: var(--text-primary);
249
317
  }
318
+ /* Highlighted with the row's *own* theme accent rather than the active theme's, so the selected
319
+ row previews the theme it names. --sw-accent comes from the theme-swatch-<id> class on the row. */
250
320
  .theme-menu-item.on {
251
- color: var(--accent-text);
321
+ color: var(--sw-accent, var(--accent-text));
322
+ background: color-mix(in srgb, var(--sw-accent, var(--accent-text)) 16%, transparent);
252
323
  }
253
324
  /* 3-dot palette preview: surface, accent, ink (colors from themes.css vars) */
254
325
  .theme-swatch {
package/server.js CHANGED
@@ -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);