opencode-statboard 2.7.0 → 2.8.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/AGENTS.md CHANGED
@@ -13,8 +13,33 @@ opencode-dashboard
13
13
  ## Architecture
14
14
 
15
15
  - `server.js` — Node.js HTTP server (zero frameworks, pure `http` module)
16
+ - `attr-worker.js` — Stats worker (`worker_threads`). Runs the heavy scan off the request thread and posts back the serialized bundle + tool counts. `server.js` is `require`-able (it guards all side effects behind `require.main === module`) so the worker reuses the exact same scan code instead of a copy.
16
17
  - `public/index.html` — Single-file frontend (vanilla JS/CSS/HTML, no build step). Report charts (`#speed-bars`, `#agent-bars`, `#session-bars`) render from `/api/report` data via `renderReportCharts`; `check-frontend-smoke.js` executes the page's real script against live API data with a stub DOM.
17
18
  - `backups/` — Gzipped DB backups (auto-rotated, `OPENCODE_BACKUP_RETENTION`)
19
+ - `.attr-bundle.json` — Persisted attribution bundle (git/npm-ignored). Keyed by DB path+size+mtime, so pointing `OPENCODE_DATA` elsewhere never reuses it.
20
+
21
+ ## Startup & latency (measured 2026-10-12, live 2.7GB WAL DB)
22
+
23
+ The message table is ~1GB of JSON; scanning it with `json_extract` costs **43s**, fetching the raw `data` blob and calling `JSON.parse` once per row costs **~2.5s**. That scan is still synchronous `better-sqlite3`, so it runs in `attr-worker.js`:
24
+
25
+ | Stage | Before | After |
26
+ |---|---|---|
27
+ | Cold start to first data (cache present) | 28.5s | **0.52s** |
28
+ | Cold start, no cache (worker scan runs meanwhile) | 28.5s | 6.5s, UI responsive throughout |
29
+ | Report request while a scan is in flight | blocked 3–29s | ~1ms |
30
+ | First switch to an unvisited scope | up to 6.3s | ~130ms, ~0ms after the frontend's idle prefetch |
31
+
32
+ Rules that keep it fast:
33
+
34
+ - **Nothing on the request path may run a full scan.** `toolCountsFor()` returns the worker/cached counts while a worker round is in flight; only if the worker is unavailable does it fall back to an inline scan.
35
+ - **Reports refuse to build without a bundle** (`refreshReport` returns `ready:false`), otherwise an all-zero report sits in the 10-minute cache and blanks the dashboard.
36
+ - The bundle is persisted with its tool counts, so a cold start paints complete numbers before the first worker round lands. `settleBundle` repaints and prewarms the default scope report.
37
+ - The frontend `warmOtherScopes()` fetches the scopes the user is NOT looking at, on idle, so a scope click is an in-memory swap.
38
+
39
+ ### Two traps that cost real data
40
+
41
+ 1. **`schema.*` must not be interpolated before the DB is opened.** `detectSchema()` runs inside `getDb()`, and `schema` starts at the V1-only defaults. A template literal like `` `... FROM ${schema.message} ...` `` is evaluated *before* `dbQuery()` opens the connection, so the query silently ran against the V1 tables and dropped every V2 row (V1+V2 total 784M input → 741M, i.e. 62,526 messages read as 28,817). `attributeUsage()` and `scanToolCounts()` now call `getDb()` first.
42
+ 2. **Serializing the bundle must not mutate it.** `serializeBundle` used to swap each bucket's `sessions` Set for an array in place; arrays have no `.size`, so after the first disk save every provider/agent row lost its `sessions` count. Both `serializeBundle` and `reviveBundle` copy instead.
18
43
 
19
44
  ## Key Patterns
20
45
 
@@ -54,6 +79,7 @@ This ensures multi-day sessions (e.g. a session created Monday, updated Thursday
54
79
  |----------|-------------|-----------|
55
80
  | `GET /api/stats?days=7` | Overview + trend data | 60s (trend) |
56
81
  | `GET /api/report?days=1\|7\|30\|-1` | Usage report (Daily/Weekly/Monthly/All) | 10min |
82
+ | `.attr-bundle.json` | Persisted attribution bundle (internal, not an endpoint) | 5min (`ATTR_TTL`) |
57
83
  | `GET /api/backup` | Manual backup trigger | — |
58
84
  | `GET /api/backups` | List backups | — |
59
85
  | `GET /api/vacuum` | DB vacuum (skips if freelist <64MB) | — |
@@ -120,7 +146,8 @@ npm install -g opencode-statboard # after the Actions run is green
120
146
  ## Known Constraints
121
147
 
122
148
  - `better-sqlite3` is a native addon; must match Node.js ABI
123
- - `attributeUsage` does a full DB scan (~35k messages); cached 300s via `getAttrAll()`
149
+ - `attributeUsage` does a full DB scan (~62k messages, ~1GB JSON) — always in the worker thread; the result is memoized for `ATTR_TTL` and persisted to `.attr-bundle.json`
150
+ - `check-frontend-smoke.js` compares the rendered DOM against the report for the scope the page is showing; it is scope-aware and pre-fetches every scope the page can visit, because a stub that answers every `/api/report` with one scope makes the "repainted for new scope" checks meaningless
124
151
  - Trend buckets are sliced from the same `getAttrAll()` attribution the report uses — never a separate windowed call (windowed calls inflate in-window days via residual growth; fixed 2026-09-29 after measuring +0.25–1.7M input/day). Remaining panel differences are cache ages only (trend ≤60s, report ≤10min, both timestamps shown)
125
152
  - V2 tool counts use `json_each` over `session_message` content (~1.5s full scan), cached 5min via `toolsCache` (the 15s refresh serves cache; verification accepts api<=expected so staleness never fails checks); legacy V1 DBs scan `part` instead
126
153
  - OpenCode V2 writes `cost = 0` for free/subscription providers, so $ totals only reflect paid (per-token billed) usage — same field, not a schema issue
package/attr-worker.js ADDED
@@ -0,0 +1,26 @@
1
+ // Stats worker: runs the heavy, SYNCHRONOUS database work off the request
2
+ // thread. Scanning the message table (JSON.parse of ~1GB of content) plus the
3
+ // embedded tool-part scan takes 3-29s against a live 2.7GB WAL DB while
4
+ // opencode is writing; doing that inline froze the HTTP server for exactly as
5
+ // long, which showed up as a slow cold start and stalled scope switches.
6
+ //
7
+ // It reuses server.js's own scan functions (no duplicated logic): requiring
8
+ // server.js as a module skips every server-side side effect (see the
9
+ // require.main guard near the bottom of that file).
10
+ const { parentPort, workerData } = require('worker_threads');
11
+ const srv = require('./server.js');
12
+
13
+ (async () => {
14
+ const now = workerData.now || Date.now();
15
+ const bundle = await srv.buildAttrBundle(now);
16
+ bundle.builtAt = now;
17
+ const counts = srv.scanToolCounts(workerData.toolsStartMs || 0);
18
+ parentPort.postMessage({
19
+ ok: true,
20
+ builtAt: now,
21
+ json: srv.serializeBundle(bundle, { embedded: srv.getEmbeddedToolsFlag(), startMs: workerData.toolsStartMs || 0, counts }),
22
+ tools: { embedded: srv.getEmbeddedToolsFlag(), startMs: workerData.toolsStartMs || 0, counts },
23
+ });
24
+ })().catch((e) => {
25
+ parentPort.postMessage({ ok: false, error: (e && e.message) || String(e) });
26
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
package/public/index.html CHANGED
@@ -311,13 +311,13 @@ const STRINGS = {
311
311
  tokens: 'Tokens', tIn: 'in', tOut: 'out', tReasoning: 'reasoning', tCache: 'cache re-reads', tokensInclCache: 'incl. cache re-reads: {v}',
312
312
  totalCost: 'Total Cost', marketValue: 'Market Value', saved: 'Saved',
313
313
  costShare: 'actual paid', atCatalog: 'same usage at catalog list prices',
314
- savedOf: '{pct}% of market value',
314
+ savedOf: '{pct} of market value',
315
315
  sessionsLabel: 'Sessions', messagesLabel: 'Messages', daysLabel: 'Days',
316
316
  avgCostDay: 'Avg cost / day', avgTokensSession: 'Avg tokens / session', medianTokensSession: 'Median tokens / session',
317
317
  activeLabel: 'active',
318
318
  pricesAsOf: 'prices as of {d}',
319
319
  unpricedModels: '{n} models unpriced ({t} tokens not valued)',
320
- proxyShare: '{pct}% of market value is proxy estimate',
320
+ proxyShare: '{pct} of market value is proxy estimate',
321
321
  caveat: 'V1+V2 merged · per-message token authority · session residual spread across the session\'s days',
322
322
  tabModels: 'Models', tabAgents: 'Agents', tabSessions: 'Sessions',
323
323
  thName: 'Name', thShare: 'Share', thSessions: 'Sessions', thMsgs: 'Msgs',
@@ -357,13 +357,13 @@ const STRINGS = {
357
357
  tokens: 'Tokens', tIn: '輸入', tOut: '輸出', tReasoning: '推理', tCache: '快取重讀', tokensInclCache: '含快取重讀:{v}',
358
358
  totalCost: '總費用', marketValue: '市價', saved: '已節省',
359
359
  costShare: '實際付費', atCatalog: '同等用量依牌價換算',
360
- savedOf: '占市價 {pct}%',
360
+ savedOf: '占市價 {pct}',
361
361
  sessionsLabel: '工作階段', messagesLabel: '訊息數', daysLabel: '天數',
362
362
  avgCostDay: '平均費用 / 天', avgTokensSession: '平均 tokens / 場', medianTokensSession: '中位數 tokens / 場',
363
363
  activeLabel: '實際執行',
364
364
  pricesAsOf: '牌價日期 {d}',
365
365
  unpricedModels: '{n} 個模型查無牌價({t} tokens 未計價)',
366
- proxyShare: '市價中有 {pct}% 屬借價代估',
366
+ proxyShare: '市價中有 {pct} 屬借價代估',
367
367
  caveat: 'V1+V2 資料合併 · 以單則訊息 token 為準 · 場次餘額依該場涵蓋的天數分攤',
368
368
  tabModels: '模型', tabAgents: '代理', tabSessions: '場次',
369
369
  thName: '名稱', thShare: '占比', thSessions: '場次', thMsgs: '訊息',
@@ -856,6 +856,28 @@ async function loadReport(days) {
856
856
  }
857
857
  }
858
858
 
859
+ // Warm the scopes the user is NOT looking at, while they read this one.
860
+ // Every scope is served from the shared attribution bundle, so this is pure
861
+ // network + one server-side build per scope: it turns the first click on
862
+ // Today/All into an instant in-memory swap instead of a ~200ms wait.
863
+ // Renders nothing — the visible scope must not be repainted by a warm fetch.
864
+ let scopeWarmStarted = false;
865
+ function warmOtherScopes() {
866
+ if (scopeWarmStarted) return;
867
+ scopeWarmStarted = true;
868
+ const idle = window.requestIdleCallback || ((fn) => setTimeout(fn, 800));
869
+ idle(async () => {
870
+ for (const d of SCOPE_DAYS) {
871
+ if (reportCache[d]) continue;
872
+ try {
873
+ const r = await fetch('/api/report?days=' + d + '&_=' + Date.now(), { cache: 'no-store' });
874
+ const j = await r.json();
875
+ if (j && j.ready && j.report) reportCache[d] = j.report;
876
+ } catch (_) {}
877
+ }
878
+ });
879
+ }
880
+
859
881
  // ---- global scope switch ----------------------------------------------
860
882
  // Always repaints every section's scope tag first (cache-backed, instant),
861
883
  // then refreshes from the API only for a scope we have not seen yet.
@@ -872,11 +894,13 @@ async function setScope(days) {
872
894
  window.__lastReport = cached;
873
895
  applyScopeTags();
874
896
  renderAll();
897
+ warmOtherScopes();
875
898
  return cached;
876
899
  }
877
900
  applyScopeTags();
878
901
  $('rawText').textContent = '⏳ ' + t('generating') + '…';
879
902
  const [rep] = await Promise.all([loadReport(days), poll()]);
903
+ warmOtherScopes();
880
904
  return rep;
881
905
  }
882
906
 
package/server.js CHANGED
@@ -4,6 +4,7 @@ const http = require('http');
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
6
  const zlib = require('zlib');
7
+ const { Worker } = require('worker_threads');
7
8
  const { pipeline } = require('stream');
8
9
  const { promisify } = require('util');
9
10
  const pipelineAsync = promisify(pipeline);
@@ -333,9 +334,13 @@ function marketOf(tok, provider, model) {
333
334
  // message count, output, reasoning, active ms, wall span on the MESSAGE clock)
334
335
  // and msgAgentAgg, so reports need no extra queries.
335
336
  const ATTR_TTL = 300000;
336
- // Tool counts change slowly but the embedded-content scan costs ~1.5s on a
337
- // large DB; cache it so the 15s refresh stays cheap. Keyed on schema+window.
337
+ // Tool counts change slowly but the embedded-content scan costs ~2.8s on a
338
+ // 2.7GB live DB, so it is computed by the stats WORKER (see spawnAttrWorker)
339
+ // and only ever READ here. `fromWorker` marks worker-supplied data, which is
340
+ // always as fresh as the last worker round and therefore exempt from TOOLS_TTL.
338
341
  let toolsCache = null;
342
+ let attrWorkerActive = false;
343
+ const ATTR_WORKER = path.join(__dirname, 'attr-worker.js');
339
344
  const yieldToLoop = () => new Promise((r) => setImmediate(r));
340
345
 
341
346
  function newTokBucket() {
@@ -346,6 +351,11 @@ function addTok(b, iv, ov, rv, crv, cwv, cv) {
346
351
  }
347
352
 
348
353
  async function attributeUsage(startMs, endMs, periodStartsMs) {
354
+ // CRITICAL: open the DB (which runs detectSchema) BEFORE any schema.* value
355
+ // is interpolated into a query. Template literals evaluate left to right, so
356
+ // a query built before the first getDb() would silently use the V1-only
357
+ // defaults and drop every V2 row.
358
+ getDb();
349
359
  const starts = (Array.isArray(periodStartsMs) ? periodStartsMs : [periodStartsMs])
350
360
  .filter((x) => x != null).sort((a, b) => a - b);
351
361
 
@@ -583,10 +593,17 @@ function dbFingerprint() {
583
593
  return `${BACKUP_SRC}|${st.size}|${Math.round(st.mtimeMs)}`;
584
594
  } catch (_) { return BACKUP_SRC; }
585
595
  }
586
- function serializeBundle(a) {
596
+ function serializeBundle(a, tools) {
597
+ // MUST NOT mutate: the caller serializes the LIVE bundle, and swapping a
598
+ // bucket's `sessions` Set for an array in place would break every later
599
+ // `.sessions.size` read (arrays have no .size).
587
600
  const setToArr = (obj) => {
588
- for (const k of Object.keys(obj)) if (obj[k] && obj[k].sessions) obj[k].sessions = [...obj[k].sessions];
589
- return obj;
601
+ const out = {};
602
+ for (const k of Object.keys(obj || {})) {
603
+ const v = obj[k];
604
+ out[k] = (v && v.sessions) ? { ...v, sessions: [...v.sessions] } : v;
605
+ }
606
+ return out;
590
607
  };
591
608
  const days = {};
592
609
  for (const [k, v] of Object.entries(a.perDay)) days[k] = { ...v, dateMs: +v.date, date: undefined, sessions: [...v.sessions] };
@@ -598,6 +615,7 @@ function serializeBundle(a) {
598
615
  };
599
616
  return JSON.stringify({
600
617
  v: 2, builtAt: a.builtAt, db: dbFingerprint(), byPeriodStart: a.byPeriodStart,
618
+ tools: tools ? { embedded: tools.embedded, startMs: tools.startMs, counts: tools.counts } : null,
601
619
  perDay: days,
602
620
  perModel: setToArr(a.perModel), perAgent: setToArr(a.perAgent),
603
621
  perSession: a.perSession, totals: a.totals, periods,
@@ -614,8 +632,12 @@ function reviveBundle(o) {
614
632
  return out;
615
633
  };
616
634
  const fixSets = (obj) => {
617
- for (const k of Object.keys(obj || {})) if (obj[k] && Array.isArray(obj[k].sessions)) obj[k].sessions = new Set(obj[k].sessions);
618
- return obj || {};
635
+ const out = {};
636
+ for (const k of Object.keys(obj || {})) {
637
+ const v = obj[k];
638
+ out[k] = (v && Array.isArray(v.sessions)) ? { ...v, sessions: new Set(v.sessions) } : v;
639
+ }
640
+ return out;
619
641
  };
620
642
  const periods = new Map();
621
643
  for (const [s, sl] of Object.entries(o.periods || {})) {
@@ -630,8 +652,8 @@ function reviveBundle(o) {
630
652
  };
631
653
  return a;
632
654
  }
633
- function saveBundleCache(a) {
634
- try { fs.writeFileSync(BUNDLE_FILE, serializeBundle(a)); } catch (_) {}
655
+ function saveBundleCache(a, tools) {
656
+ try { fs.writeFileSync(BUNDLE_FILE, serializeBundle(a, tools)); } catch (_) {}
635
657
  }
636
658
  function loadBundleCache() {
637
659
  try {
@@ -639,6 +661,11 @@ function loadBundleCache() {
639
661
  const o = JSON.parse(raw);
640
662
  if (o && o.v === 2 && o.db === dbFingerprint() && o.periods && Object.keys(o.periods).length) {
641
663
  console.log(`attr bundle loaded from cache (built ${Math.round((Date.now() - o.builtAt) / 60000)} min ago)`);
664
+ // Tool counts ride along so a cold start paints complete numbers before
665
+ // the first worker round lands.
666
+ if (o.tools && o.tools.counts) {
667
+ toolsCache = { at: o.builtAt, embedded: o.tools.embedded, startMs: 0, counts: o.tools.counts, fromWorker: true };
668
+ }
642
669
  return { at: o.builtAt, a: reviveBundle(o) };
643
670
  }
644
671
  } catch (_) {}
@@ -653,22 +680,133 @@ function getAttrPeriod(startMs) {
653
680
  if (!attrAllCache) return EMPTY_ATTR;
654
681
  return attrAllCache.a.periods.get(startMs) || attrAllCache.a;
655
682
  }
683
+ // Kick a fresh scan. The scan runs in a WORKER THREAD because it is
684
+ // synchronous better-sqlite3 + JSON work: inline it froze the event loop for
685
+ // 3-29s on a contended 2.7GB WAL DB, which is exactly what made cold starts
686
+ // and scope clicks feel slow. The worker posts back the same JSON the disk
687
+ // cache stores, so the swap-in path is identical either way.
656
688
  function refreshAttrBundle() {
657
689
  if (attrBundlePending) return attrAllCache ? attrAllCache.a : null;
658
690
  const now = Date.now();
659
691
  if (attrAllCache && now - attrAllCache.at < ATTR_TTL) return attrAllCache.a;
660
692
  attrBundlePending = true;
661
- buildAttrBundle(now).then((a) => {
662
- a.builtAt = now;
663
- attrAllCache = { at: now, a };
664
- attrBundlePending = false;
665
- console.log(`attr bundle rebuilt in ${Date.now() - now}ms`);
666
- if (now - (attrLastSave || 0) > BUNDLE_SAVE_MS) { attrLastSave = now; saveBundleCache(a); }
667
- }).catch((e) => {
693
+ attrWorkerActive = true;
694
+ spawnAttrWorker(now);
695
+ return attrAllCache ? attrAllCache.a : null;
696
+ }
697
+
698
+ const attrBundleWaiters = [];
699
+ function waitForBundle(timeoutMs) {
700
+ if (attrAllCache) return Promise.resolve(attrAllCache);
701
+ return new Promise((resolve) => {
702
+ let done = false;
703
+ const finish = () => { if (!done) { done = true; clearTimeout(t); resolve(attrAllCache); } };
704
+ const t = setTimeout(finish, timeoutMs || 120000);
705
+ attrBundleWaiters.push(finish);
706
+ });
707
+ }
708
+
709
+ function spawnAttrWorker(now) {
710
+ // Failure path: unblock waiters and, on a truly cold start, build inline so
711
+ // the dashboard still shows numbers.
712
+ function failBundle(msg) {
713
+ if (!attrBundlePending) return;
668
714
  attrBundlePending = false;
669
- console.error('attr bundle failed:', e.message);
715
+ attrWorkerActive = false;
716
+ console.error('attr worker failed:', msg);
717
+ const waiters = attrBundleWaiters.splice(0);
718
+ for (const f of waiters) f();
719
+ if (!attrAllCache) {
720
+ buildAttrBundle(now).then((a) => {
721
+ a.builtAt = now;
722
+ attrAllCache = { at: now, a };
723
+ settleBundle(now, `built inline in ${Date.now() - now}ms (worker unavailable)`);
724
+ }).catch((e) => console.error('inline bundle failed:', e && e.message));
725
+ }
726
+ }
727
+ let w;
728
+ try {
729
+ w = new Worker(ATTR_WORKER, { workerData: { now, toolsStartMs: 0 } });
730
+ } catch (e) {
731
+ // Worker unavailable (very old Node / restricted env): build inline.
732
+ console.error('attr worker spawn failed, building inline:', e.message);
733
+ failBundle(e.message);
734
+ return;
735
+ }
736
+ let settled = false;
737
+ w.on('message', (m) => {
738
+ if (settled) return;
739
+ settled = true;
740
+ try { w.terminate(); } catch (_) {}
741
+ if (!m || !m.ok) return failBundle((m && m.error) || 'unknown worker error');
742
+ try {
743
+ const a = reviveBundle(JSON.parse(m.json));
744
+ a.builtAt = m.builtAt;
745
+ attrAllCache = { at: m.builtAt, a };
746
+ if (m.tools) {
747
+ toolsCache = { at: m.builtAt, embedded: m.tools.embedded, startMs: 0, counts: m.tools.counts, fromWorker: true };
748
+ }
749
+ settleBundle(m.builtAt, `rebuilt in ${Date.now() - m.builtAt}ms (worker)`);
750
+ } catch (e) {
751
+ failBundle('bad worker payload: ' + (e && e.message));
752
+ }
670
753
  });
671
- return attrAllCache ? attrAllCache.a : null;
754
+ w.on('error', (e) => { if (!settled) { settled = true; failBundle(e && e.message); } });
755
+ // A worker that posted its result exits 0 right after; only an unsettled
756
+ // exit is a failure.
757
+ w.on('exit', (code) => { if (!settled) { settled = true; failBundle('worker exited with code ' + code); } });
758
+ }
759
+
760
+ function settleBundle(now, msg) {
761
+ attrBundlePending = false;
762
+ attrWorkerActive = false;
763
+ console.log(`attr bundle ${msg}`);
764
+ if (now - (attrLastSave || 0) > BUNDLE_SAVE_MS) {
765
+ attrLastSave = now;
766
+ saveBundleCache(attrAllCache.a, toolsCache);
767
+ }
768
+ const waiters = attrBundleWaiters.splice(0);
769
+ for (const f of waiters) f();
770
+ // A brand-new bundle changes the numbers behind every panel; repaint now
771
+ // instead of waiting for the next 15s tick.
772
+ if (typeof refresh === 'function') Promise.resolve(refresh()).catch(() => {});
773
+ // The default scope is the first thing on screen: build it the moment the
774
+ // bundle lands so the opening view never shows a "generating" spinner.
775
+ setImmediate(() => {
776
+ try {
777
+ const r = buildReportFromDb(1);
778
+ if (r && r.stats && r.stats.ok) reportCache['1'] = r;
779
+ } catch (_) {}
780
+ });
781
+ }
782
+
783
+ // Pure tool-count scan (no cache side effects) so the worker can run it.
784
+ function scanToolCounts(startMs) {
785
+ getDb(); // detectSchema must run before schema.embeddedTools is read
786
+ const timeFilterPart = startMs ? `AND p.time_updated >= ${startMs}` : '';
787
+ const toolRows = schema.embeddedTools
788
+ ? dbQuery(`SELECT COALESCE(json_extract(je.value, '$.tool'), json_extract(je.value, '$.name')) AS tool FROM session_message sm, json_each(json_extract(sm.data, '$.content')) je WHERE json_extract(je.value, '$.type') = 'tool' ${startMs ? `AND sm.time_updated >= ${startMs}` : ''}
789
+ UNION ALL
790
+ SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' AND p.message_id NOT IN (SELECT id FROM session_message) ${startMs ? `AND p.time_updated >= ${startMs}` : ''};`) || []
791
+ : dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
792
+ const counts = {};
793
+ for (const row of toolRows) {
794
+ if (row.tool) counts[row.tool] = (counts[row.tool] || 0) + 1;
795
+ }
796
+ return counts;
797
+ }
798
+
799
+ // Read side: prefer worker-supplied counts; NEVER scan inline while a worker
800
+ // round is in flight (a few seconds of empty tools beats a frozen UI).
801
+ function toolCountsFor(now, startMs) {
802
+ const hit = toolsCache;
803
+ if (hit && hit.startMs === startMs && hit.embedded === schema.embeddedTools
804
+ && (hit.fromWorker || now - hit.at <= TOOLS_TTL)) {
805
+ return hit.counts;
806
+ }
807
+ if (attrWorkerActive || (hit && hit.startMs === startMs)) return (hit && hit.counts) || {};
808
+ toolsCache = { at: now, embedded: schema.embeddedTools, startMs, counts: scanToolCounts(startMs) };
809
+ return toolsCache.counts;
672
810
  }
673
811
  function computeMedian(arr) {
674
812
  if (!arr.length) return 0;
@@ -694,19 +832,7 @@ function getStatsFromDb(days) {
694
832
  // querying all of part would double count ??only parts of messages that
695
833
  // were never migrated are added from `part`). Cached (see toolsCache):
696
834
  // verification accepts api<=expected, so staleness never fails checks.
697
- if (!toolsCache || now - toolsCache.at > TOOLS_TTL || toolsCache.embedded !== schema.embeddedTools || toolsCache.startMs !== startMs) {
698
- const toolRows = schema.embeddedTools
699
- ? dbQuery(`SELECT COALESCE(json_extract(je.value, '$.tool'), json_extract(je.value, '$.name')) AS tool FROM session_message sm, json_each(json_extract(sm.data, '$.content')) je WHERE json_extract(je.value, '$.type') = 'tool' ${startMs ? `AND sm.time_updated >= ${startMs}` : ''}
700
- UNION ALL
701
- SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' AND p.message_id NOT IN (SELECT id FROM session_message) ${startMs ? `AND p.time_updated >= ${startMs}` : ''};`) || []
702
- : dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
703
- const counts = {};
704
- for (const row of toolRows) {
705
- if (row.tool) counts[row.tool] = (counts[row.tool] || 0) + 1;
706
- }
707
- toolsCache = { at: now, embedded: schema.embeddedTools, startMs, counts };
708
- }
709
- const toolCounts = toolsCache.counts;
835
+ const toolCounts = toolCountsFor(now, startMs);
710
836
  const totalToolUse = Object.values(toolCounts).reduce((s, v) => s + v, 0) || 1;
711
837
  const tools = Object.entries(toolCounts)
712
838
  .map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
@@ -935,7 +1061,7 @@ function buildReportFromDb(days) {
935
1061
  // card. The all-time buckets (perDay) are still used for the summary totals
936
1062
  // and stay identical to the trend chart for the same period.
937
1063
  const a = getAttrPeriod(startMs);
938
- const aNow = attrAllCache.at; // snapshot time of the shared bundle
1064
+ const aNow = attrAllCache ? attrAllCache.at : now; // snapshot time of the shared bundle
939
1065
  // Message-level stats per session within the period (period speed + active
940
1066
  // time). One GROUP BY over the merged message view, mapped onto the same
941
1067
  // session-meta buckets as tokens so row sets stay identical.
@@ -1127,6 +1253,12 @@ function refreshReport(days) {
1127
1253
  const hit = reportCache[key];
1128
1254
  const fresh = hit && Date.now() - hit.generatedAt < REPORT_TTL;
1129
1255
  if (fresh) return { report: hit, ready: true };
1256
+ // Never build a report from a missing bundle: an all-zero report would sit in
1257
+ // the 10-minute cache and blank the whole dashboard until it expires.
1258
+ if (!attrAllCache) {
1259
+ refreshAttrBundle();
1260
+ return { report: null, ready: false };
1261
+ }
1130
1262
  if (!reportBusy[key]) {
1131
1263
  reportBusy[key] = true;
1132
1264
  setImmediate(() => {
@@ -1274,6 +1406,21 @@ const server = http.createServer(async (req, res) => {
1274
1406
  }
1275
1407
  });
1276
1408
 
1409
+ // Loaded as a MODULE by the stats worker (attr-worker.js): publish the scan
1410
+ // helpers and bail out before any server-side side effect (listening, timers,
1411
+ // signal handlers). `bin` points straight at this file, so a normal
1412
+ // `opencode-dashboard` run always has require.main === module.
1413
+ if (require.main !== module) {
1414
+ module.exports = {
1415
+ buildAttrBundle,
1416
+ serializeBundle,
1417
+ reviveBundle,
1418
+ scanToolCounts,
1419
+ getEmbeddedToolsFlag: () => schema.embeddedTools,
1420
+ };
1421
+ return;
1422
+ }
1423
+
1277
1424
  function gracefulShutdown() {
1278
1425
  console.log('\nShutting down...');
1279
1426
  if (db) try { db.close(); } catch (_) {}
@@ -1323,31 +1470,27 @@ function tryListen(port, maxPort) {
1323
1470
  (async () => {
1324
1471
  try {
1325
1472
  const actualPort = await tryListen(PORT, PORT + 5);
1326
- setInterval(refresh, REFRESH_MS);
1327
- setInterval(refreshModels, 60000);
1328
- // Serve from the persisted bundle immediately (startup is instant even when a
1329
- // live scan would take 5–26s), then refresh in the background when stale.
1330
- attrBundlePending = true;
1473
+ // Serve the persisted bundle + tool counts IMMEDIATELY. Nothing on this
1474
+ // path touches the live DB, so the first request answers in milliseconds
1475
+ // instead of waiting out a 3-29s scan.
1331
1476
  const cached = loadBundleCache();
1332
1477
  attrAllCache = cached || null;
1333
- if (cached) refreshAttrBundle();
1334
- setInterval(refreshAttrBundle, 60000);
1478
+ getDb(); // detect schema now, so the worker result lands on a warm handle
1479
+ // Spawn the fresh scan BEFORE the first refresh: while it is in flight the
1480
+ // request thread never runs the inline tool scan (toolCountsFor skips it).
1481
+ refreshAttrBundle();
1335
1482
  await refresh();
1336
1483
  await refreshModels();
1337
1484
  if (!cached) {
1338
- // Cold start (no cache file yet): one blocking scan, then persist it so
1339
- // every later start is instant.
1340
- attrBundlePending = true;
1341
- const warmT0 = Date.now();
1342
- attrAllCache = { at: warmT0, a: await buildAttrBundle(Date.now()) };
1343
- attrAllCache.a.builtAt = warmT0;
1344
- attrBundlePending = false;
1345
- attrLastSave = warmT0;
1346
- saveBundleCache(attrAllCache.a);
1347
- console.log(`attr bundle warm in ${Date.now() - warmT0}ms (cached to disk)`);
1485
+ // No cache file yet (first run on this machine): there is nothing to
1486
+ // serve until the worker's first result arrives.
1487
+ await waitForBundle(180000);
1348
1488
  await refresh();
1349
1489
  await refreshModels();
1350
1490
  }
1491
+ setInterval(refresh, REFRESH_MS);
1492
+ setInterval(refreshModels, 60000);
1493
+ setInterval(refreshAttrBundle, 60000);
1351
1494
  // Today's report eagerly (the common first view). Other periods build on
1352
1495
  // demand in the background via refreshReport stale-while-revalidate.
1353
1496
  for (const d of [1]) {