opencode-statboard 2.8.3 → 2.8.4

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.
Files changed (3) hide show
  1. package/AGENTS.md +17 -6
  2. package/package.json +1 -1
  3. package/server.js +48 -16
package/AGENTS.md CHANGED
@@ -16,24 +16,34 @@ opencode-dashboard
16
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.
17
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.
18
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
19
 
21
- ## Startup & latency (measured 2026-10-12, live 2.7GB WAL DB)
20
+ Runtime state lives OUTSIDE the package directory:
21
+
22
+ | State | Location |
23
+ |---|---|
24
+ | Attribution bundle cache | `~/.cache/opencode-statboard/attr-bundle-<sha1(db path)>.json` |
25
+ | DB backups | `<package>/backups/` (wiped by `npm i -g` — acceptable, they are re-creatable) |
26
+
27
+ One cache file per database path (sha1 of the lowercased path). Two servers pointed at different DBs used to overwrite each other's entry and never get a cache hit. The pre-2.8.4 in-package `.attr-bundle.json` is still read once and then migrated.
28
+
29
+ ## Startup & latency (measured 2026-10-12 / 2026-10-16, live 3GB WAL DB)
22
30
 
23
31
  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
32
 
25
33
  | Stage | Before | After |
26
34
  |---|---|---|
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 |
35
+ | Cold start to first data (cache present) | 28.5s | **0.56s** |
36
+ | Cold start, no cache (worker scan runs meanwhile) | 28.5s | 6–58s, UI responsive throughout, reports `loading` |
37
+ | Report request while a scan is in flight | blocked 3–58s | ~1ms |
30
38
  | First switch to an unvisited scope | up to 6.3s | ~130ms, ~0ms after the frontend's idle prefetch |
31
39
 
32
40
  Rules that keep it fast:
33
41
 
34
42
  - **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
- - **The bundle cache is keyed on the DB PATH only.** Keying it on size/mtime looked safer but the live DB grows on every message, so the fingerprint changed constantly and the "instant" cold start silently degraded back to a 6–7s rebuild on a busy machine.
43
+ - **The bundle cache lives in the user cache dir, not the package dir.** `npm install -g` replaces the package directory, so a cache stored next to `server.js` was deleted on every upgrade and each upgrade paid a full 30–60s scan before showing anything.
44
+ - **The bundle cache is keyed on the DB PATH only** (in the filename). Keying it on size/mtime looked safer, but the live DB grows on every message, so the fingerprint changed constantly and the "instant" cold start silently degraded back to a full rebuild on a busy machine.
36
45
  - **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.
46
+ - **With no bundle at all**, `refresh()` keeps `state.loading = true` and `/api/stats` reports `ok:false`, so the UI shows "updating" instead of an all-zero payload it cannot tell apart from real numbers.
37
47
  - 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.
38
48
  - The frontend `warmOtherScopes()` fetches the scopes the user is NOT looking at, on idle, so a scope click is an in-memory swap.
39
49
 
@@ -149,6 +159,7 @@ npm install -g opencode-statboard # after the Actions run is green
149
159
  - `better-sqlite3` is a native addon; must match Node.js ABI
150
160
  - `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`
151
161
  - `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
162
+ - The smoke harness must not capture `/api/stats` before the payload is real: it polls until `ok && trendReady && input > 0 && tools.length`, because a server that just booted (or one mid-rebuild) answers with zeros and no trend, and every DOM assertion would then compare against an empty page
152
163
  - 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)
153
164
  - 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
154
165
  - 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.8.3",
3
+ "version": "2.8.4",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
package/server.js CHANGED
@@ -5,6 +5,7 @@ const fs = require('fs');
5
5
  const path = require('path');
6
6
  const zlib = require('zlib');
7
7
  const { Worker } = require('worker_threads');
8
+ const crypto = require('crypto');
8
9
  const { pipeline } = require('stream');
9
10
  const { promisify } = require('util');
10
11
  const pipelineAsync = promisify(pipeline);
@@ -583,7 +584,15 @@ async function buildAttrBundle(now) {
583
584
  // Scanning the live DB costs 5–26s (WAL + concurrent opencode writes), so the
584
585
  // computed bundle is persisted and loaded on startup; a stale bundle still
585
586
  // serves every request while a fresh one is rebuilt in the background.
586
- const BUNDLE_FILE = path.join(__dirname, '.attr-bundle.json');
587
+ // The bundle cache is RUNTIME state, not package content: `npm install -g`
588
+ // replaces the whole package directory, which used to delete the cache and
589
+ // force every upgrade to pay a full 30-60s scan before showing anything.
590
+ // One file per database path: two servers pointed at different DBs (tests,
591
+ // snapshots) would otherwise keep overwriting each other's entry and never
592
+ // get a cache hit.
593
+ const BUNDLE_DIR = path.join(process.env.USERPROFILE || process.env.HOME || process.cwd(), '.cache', 'opencode-statboard');
594
+ const BUNDLE_FILE = path.join(BUNDLE_DIR, `attr-bundle-${crypto.createHash('sha1').update(BACKUP_SRC.toLowerCase()).digest('hex').slice(0, 12)}.json`);
595
+ const BUNDLE_FILE_LEGACY = path.join(__dirname, '.attr-bundle.json');
587
596
  const BUNDLE_SAVE_MS = 60000; // don't hammer the disk while chatting
588
597
  // Cache is bound to the DATABASE PATH it was computed from, so pointing
589
598
  // OPENCODE_DATA at another DB (tests, a restored copy) never reuses it.
@@ -653,22 +662,35 @@ function reviveBundle(o) {
653
662
  return a;
654
663
  }
655
664
  function saveBundleCache(a, tools) {
656
- try { fs.writeFileSync(BUNDLE_FILE, serializeBundle(a, tools)); } catch (_) {}
665
+ try {
666
+ fs.mkdirSync(BUNDLE_DIR, { recursive: true });
667
+ fs.writeFileSync(BUNDLE_FILE, serializeBundle(a, tools));
668
+ } catch (_) {}
657
669
  }
658
670
  function loadBundleCache() {
659
- try {
660
- const raw = fs.readFileSync(BUNDLE_FILE, 'utf8');
661
- const o = JSON.parse(raw);
662
- if (o && o.v === 2 && o.db === dbFingerprint() && o.periods && Object.keys(o.periods).length) {
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 };
671
+ for (const file of [BUNDLE_FILE, BUNDLE_FILE_LEGACY]) {
672
+ try {
673
+ const raw = fs.readFileSync(file, 'utf8');
674
+ const o = JSON.parse(raw);
675
+ if (o && o.v === 2 && o.db === dbFingerprint() && o.periods && Object.keys(o.periods).length) {
676
+ console.log(`attr bundle loaded from cache (built ${Math.round((Date.now() - o.builtAt) / 60000)} min ago)`);
677
+ // Tool counts ride along so a cold start paints complete numbers before
678
+ // the first worker round lands.
679
+ if (o.tools && o.tools.counts) {
680
+ toolsCache = { at: o.builtAt, embedded: o.tools.embedded, startMs: 0, counts: o.tools.counts, fromWorker: true };
681
+ }
682
+ // Migrate the pre-2.8.4 in-package location on first load.
683
+ if (file !== BUNDLE_FILE) {
684
+ try {
685
+ fs.mkdirSync(BUNDLE_DIR, { recursive: true });
686
+ fs.writeFileSync(BUNDLE_FILE, raw);
687
+ console.log('attr bundle cache migrated to ' + BUNDLE_DIR);
688
+ } catch (_) {}
689
+ }
690
+ return { at: o.builtAt, a: reviveBundle(o) };
668
691
  }
669
- return { at: o.builtAt, a: reviveBundle(o) };
670
- }
671
- } catch (_) {}
692
+ } catch (_) {}
693
+ }
672
694
  return null;
673
695
  }
674
696
  function getAttrAll() {
@@ -932,19 +954,29 @@ async function refresh() {
932
954
  if (state.busy) return;
933
955
  state.busy = true;
934
956
  try {
957
+ // No bundle yet (first run on this machine, or right after `npm i -g`
958
+ // wiped the package dir): the worker is still scanning — which can take
959
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
960
+ // the UI cannot tell apart from real numbers.
961
+ if (!attrAllCache) {
962
+ refreshAttrBundle();
963
+ state.loading = true;
964
+ return;
965
+ }
935
966
  const p = getStatsFromDb(0);
936
967
  if (p && p.ok) {
937
968
  state.data = p;
938
969
  state.error = null;
939
970
  state.updatedAt = Date.now();
971
+ state.loading = false;
940
972
  } else {
941
973
  state.error = state.error || 'failed to read database';
942
974
  }
943
975
  } catch (e) {
944
976
  state.error = e.message;
977
+ } finally {
978
+ state.busy = false;
945
979
  }
946
- state.loading = false;
947
- state.busy = false;
948
980
  }
949
981
 
950
982
  function getModelsFromDb() {