opencode-statboard 2.9.1 → 2.9.5

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/attr-worker.js CHANGED
@@ -1,6 +1,17 @@
1
1
  const { parentPort, workerData } = require('worker_threads');
2
2
  const srv = require('./server.js');
3
3
 
4
+ // I/O throttling parameters (from env, with defaults)
5
+ const ITHROTTLE_BATCH = parseInt(process.env.OPENCODE_ITHROTTLE_BATCH || '1000', 10);
6
+ const ITHROTTLE_DELAY_MS = parseInt(process.env.OPENCODE_ITHROTTLE_DELAY_MS || '5', 10);
7
+
8
+ function throttle(iteration) {
9
+ if (iteration % ITHROTTLE_BATCH === 0) {
10
+ return new Promise((r) => setTimeout(r, ITHROTTLE_DELAY_MS));
11
+ }
12
+ return Promise.resolve();
13
+ }
14
+
4
15
  (async () => {
5
16
  const bundle = await srv.buildAttrBundle(workerData.now || Date.now());
6
17
  bundle.builtAt = workerData.now || Date.now();
package/fix-catch.js ADDED
@@ -0,0 +1,49 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+
4
+ // Find the catch block in the refresh function
5
+ const lines = content.split('\n');
6
+ let inRefresh = false;
7
+ let inCatch = false;
8
+ let catchStart = -1;
9
+ let finallyStart = -1;
10
+
11
+ for (let i = 0; i < lines.length; i++) {
12
+ const line = lines[i];
13
+
14
+ if (line.includes('async function refresh()')) {
15
+ inRefresh = true;
16
+ }
17
+
18
+ if (inRefresh && line.trim() === '} catch (e) {') {
19
+ catchStart = i;
20
+ }
21
+
22
+ if (inRefresh && line.trim() === '} finally {') {
23
+ finallyStart = i;
24
+ break;
25
+ }
26
+ }
27
+
28
+ if (catchStart >= 0 && finallyStart >= 0) {
29
+ // Replace the catch block (from catchStart to finallyStart - 1)
30
+ const newCatchBlock = [
31
+ ' } catch (e) {',
32
+ ' console.error("refresh error:", e);',
33
+ ' state.error = e.message;',
34
+ ' state.loading = false;',
35
+ ' } finally {'
36
+ ];
37
+
38
+ const newLines = [
39
+ ...lines.slice(0, catchStart),
40
+ ...newCatchBlock,
41
+ ...lines.slice(finallyStart + 1)
42
+ ];
43
+
44
+ const newContent = newLines.join('\n');
45
+ fs.writeFileSync('server.js', newContent, 'utf8');
46
+ console.log('Done');
47
+ } else {
48
+ console.log('Could not find catch/finally blocks');
49
+ }
package/fix-refresh.js ADDED
@@ -0,0 +1,8 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+ const newContent = content.replace(
4
+ '} catch (e) {\n state.error = e.message;\n } finally {\n state.busy = false;\n }',
5
+ '} catch (e) {\n console.error("refresh error:", e);\n state.error = e.message;\n state.loading = false;\n } finally {\n state.busy = false;\n }'
6
+ );
7
+ fs.writeFileSync('server.js', newContent, 'utf8');
8
+ console.log('Done');
@@ -0,0 +1,8 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+ const newContent = content.replace(
4
+ '} catch (e) {\n state.error = e.message;\n } finally {\n state.busy = false;\n }',
5
+ '} catch (e) {\n console.error("refresh error:", e);\n state.error = e.message;\n state.loading = false;\n } finally {\n state.busy = false;\n }'
6
+ );
7
+ fs.writeFileSync('server.js', newContent, 'utf8');
8
+ console.log('Done');
@@ -0,0 +1,8 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+ const newContent = content.replace(
4
+ '} catch (e) {\n state.error = e.message;\n } finally {\n state.busy = false;\n }',
5
+ '} catch (e) {\n console.error("refresh error:", e);\n state.error = e.message;\n state.loading = false;\n } finally {\n state.busy = false;\n }'
6
+ );
7
+ fs.writeFileSync('server.js', newContent, 'utf8');
8
+ console.log('Done');
@@ -0,0 +1,65 @@
1
+ const fs = require('fs');
2
+ const content = fs.readFileSync('server.js', 'utf8');
3
+ const oldFunc = `async function refresh() {
4
+ if (state.busy) return;
5
+ state.busy = true;
6
+ try {
7
+ // No bundle yet (first run on this machine, or right after \`npm i -g\`
8
+ // wiped the package dir): the worker is still scanning \uFEFFX which can take
9
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
10
+ // the UI cannot tell apart from real numbers.
11
+ if (!attrAllCache) {
12
+ refreshAttrBundle();
13
+ state.loading = true;
14
+ return;
15
+ }
16
+ const p = getStatsFromDb(0);
17
+ if (p && p.ok) {
18
+ state.data = p;
19
+ state.error = null;
20
+ state.updatedAt = Date.now();
21
+ state.loading = false;
22
+ } else {
23
+ state.error = state.error || 'failed to read database';
24
+ }
25
+ } catch (e) {
26
+ state.error = e.message;
27
+ } finally {
28
+ state.busy = false;
29
+ }
30
+ }`;
31
+ const newFunc = `async function refresh() {
32
+ if (state.busy) return;
33
+ state.busy = true;
34
+ try {
35
+ // No bundle yet (first run on this machine, or right after \`npm i -g\`
36
+ // wiped the package dir): the worker is still scanning \uFEFFX which can take
37
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
38
+ // the UI cannot tell apart from real numbers.
39
+ if (!attrAllCache) {
40
+ refreshAttrBundle();
41
+ state.loading = true;
42
+ return;
43
+ }
44
+ const p = getStatsFromDb(0);
45
+ if (p && p.ok) {
46
+ state.data = p;
47
+ state.error = null;
48
+ state.updatedAt = Date.now();
49
+ state.loading = false;
50
+ } else {
51
+ state.error = state.error || 'failed to read database';
52
+ state.loading = false;
53
+ }
54
+ } catch (e) {
55
+ console.error("refresh error:", e);
56
+ state.error = e.message;
57
+ state.loading = false;
58
+ } finally {
59
+ state.busy = false;
60
+ }
61
+ }`;
62
+ const content = fs.readFileSync('server.js', 'utf8');
63
+ const newContent = content.replace(oldFunc, newFunc);
64
+ fs.writeFileSync('server.js', newContent, 'utf8');
65
+ console.log('Done');
@@ -0,0 +1,64 @@
1
+ const fs = require('fs');
2
+ const oldFunc = `async function refresh() {
3
+ if (state.busy) return;
4
+ state.busy = true;
5
+ try {
6
+ // No bundle yet (first run on this machine, or right after \`npm i -g\`
7
+ // wiped the package dir): the worker is still scanning \uFEFFX which can take
8
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
9
+ // the UI cannot tell apart from real numbers.
10
+ if (!attrAllCache) {
11
+ refreshAttrBundle();
12
+ state.loading = true;
13
+ return;
14
+ }
15
+ const p = getStatsFromDb(0);
16
+ if (p && p.ok) {
17
+ state.data = p;
18
+ state.error = null;
19
+ state.updatedAt = Date.now();
20
+ state.loading = false;
21
+ } else {
22
+ state.error = state.error || 'failed to read database';
23
+ }
24
+ } catch (e) {
25
+ state.error = e.message;
26
+ } finally {
27
+ state.busy = false;
28
+ }
29
+ }`;
30
+ const newFunc = `async function refresh() {
31
+ if (state.busy) return;
32
+ state.busy = true;
33
+ try {
34
+ // No bundle yet (first run on this machine, or right after \`npm i -g\`
35
+ // wiped the package dir): the worker is still scanning \uFEFFX which can take
36
+ // 30-60s on a 3GB DB. Publish "loading" instead of an all-zero payload
37
+ // the UI cannot tell apart from real numbers.
38
+ if (!attrAllCache) {
39
+ refreshAttrBundle();
40
+ state.loading = true;
41
+ return;
42
+ }
43
+ const p = getStatsFromDb(0);
44
+ if (p && p.ok) {
45
+ state.data = p;
46
+ state.error = null;
47
+ state.updatedAt = Date.now();
48
+ state.loading = false;
49
+ } else {
50
+ state.error = state.error || 'failed to read database';
51
+ state.loading = false;
52
+ }
53
+ } catch (e) {
54
+ console.error("refresh error:", e);
55
+ state.error = e.message;
56
+ state.loading = false;
57
+ } finally {
58
+ state.busy = false;
59
+ }
60
+ }`;
61
+ const content = fs.readFileSync('server.js', 'utf8');
62
+ const newContent = content.replace(oldFunc, newFunc);
63
+ fs.writeFileSync('server.js', newContent, 'utf8');
64
+ console.log('Done');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "2.9.1",
3
+ "version": "2.9.5",
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
@@ -20,9 +20,13 @@ const TREND_MS = 60 * 1000;
20
20
  const REPORT_TTL = 10 * 60 * 1000;
21
21
  const TOOLS_TTL = 5 * 60 * 1000;
22
22
  const STATS_TTL = 10 * 60 * 1000;
23
- const CACHE_CLEANUP_MS = 5 * 60 * 1000;
23
+ // Backup interval: default 1 hour (was 5 min — far too aggressive for 3GB DB).
24
+ // Configurable via OPENCODE_BACKUP_INTERVAL_MS env var.
25
+ const CACHE_CLEANUP_MS = parseInt(process.env.OPENCODE_BACKUP_INTERVAL_MS || String(60 * 60 * 1000), 10);
24
26
  const BACKUP_DIR = path.join(__dirname, 'backups');
25
27
  const BACKUP_RETENTION = parseInt(process.env.OPENCODE_BACKUP_RETENTION || '3', 10) || 3;
28
+ // Set OPENCODE_BACKUP_INTERVAL_MS=0 to disable auto backup entirely
29
+ const BACKUP_DISABLED = process.env.OPENCODE_BACKUP_INTERVAL_MS === '0';
26
30
  const BACKUP_SRC = process.env.OPENCODE_DATA
27
31
  ? path.join(process.env.OPENCODE_DATA, 'opencode.db')
28
32
  : path.join(process.env.USERPROFILE || process.env.HOME || '', '.local', 'share', 'opencode', 'opencode.db');
@@ -336,6 +340,16 @@ function marketOf(tok, provider, model) {
336
340
  // message count, output, reasoning, active ms, wall span on the MESSAGE clock)
337
341
  // and msgAgentAgg, so reports need no extra queries.
338
342
  const ATTR_TTL = 300000;
343
+ // Minimum interval between full scans, regardless of DB revision changes.
344
+ // Prevents excessive scanning when opencode is actively writing (WAL checkpoints
345
+ // change DB mtime/size constantly, making revision appear changed every time).
346
+ // Default 30 minutes — configurable via OPENCODE_MIN_SCAN_INTERVAL_MS.
347
+ const MIN_SCAN_INTERVAL = parseInt(process.env.OPENCODE_MIN_SCAN_INTERVAL_MS || String(30 * 60 * 1000), 10);
348
+
349
+ // I/O throttling for the attr worker: process N rows, then yield for M ms.
350
+ // Prevents the worker from saturating the disk. Configurable via env vars.
351
+ const ITHROTTLE_BATCH = parseInt(process.env.OPENCODE_ITHROTTLE_BATCH || '1000', 10); // rows per yield
352
+ const ITHROTTLE_DELAY_MS = parseInt(process.env.OPENCODE_ITHROTTLE_DELAY_MS || '5', 10); // ms to sleep
339
353
  // Tool counts change slowly but the embedded-content scan costs ~2.8s on a
340
354
  // 2.7GB live DB, so it is computed by the stats WORKER (see spawnAttrWorker)
341
355
  // and only ever READ here. `fromWorker` marks worker-supplied data, which is
@@ -394,13 +408,14 @@ async function attributeUsage(startMs, endMs, periodStartsMs) {
394
408
  };
395
409
  });
396
410
 
397
- const rows = dbQuery(`SELECT time_created AS t, session_id AS sid, data FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
411
+ // STREAMING iteration with throttling: use .iterate() instead of .all()
412
+ // to avoid loading all rows into memory at once. Throttle every ITHROTTLE_BATCH rows.
413
+ const stmt = db.prepare(`SELECT time_created AS t, session_id AS sid, data FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`);
398
414
  let processed = 0;
399
- for (const row of rows) {
415
+ for (const row of stmt.iterate()) {
400
416
  let d = null;
401
417
  try { d = JSON.parse(row.data); } catch (_) { d = null; }
402
- processed++;
403
- if (!d) continue;
418
+ if (!d) { processed++; continue; }
404
419
  const key = localDayKey(new Date(row.t));
405
420
  const dayMs = dateOfKey(key).getTime();
406
421
  const tk = d.tokens || {};
@@ -463,9 +478,12 @@ async function attributeUsage(startMs, endMs, periodStartsMs) {
463
478
  const ag = sl.msgAgentAgg[agent] || (sl.msgAgentAgg[agent] = { o: 0, ms: 0 });
464
479
  if (hasDur) { ag.o += ov; ag.ms += (t1 - t0); }
465
480
  }
466
- if ((processed & 0x3fff) === 0) await yieldToLoop();
481
+
482
+ // Throttle: yield every ITHROTTLE_BATCH rows to avoid saturating disk
483
+ if ((++processed % ITHROTTLE_BATCH) === 0) await throttle(processed);
467
484
  }
468
485
 
486
+ // Session table: smaller, keep as-is (only ~800 rows)
469
487
  const srows = dbQuery(`SELECT id, agent, COALESCE(json_extract(model, '$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model, '$.id'), 'unknown') AS model, time_created AS tc, time_updated AS tu, tokens_input AS si, tokens_output AS so, tokens_reasoning AS sr, tokens_cache_read AS scr, tokens_cache_write AS scw, cost AS sc FROM ${schema.session} WHERE time_updated >= ${startMs} AND time_created < ${endMs};`) || [];
470
488
  let sessProcessed = 0;
471
489
  for (const s of srows) {
@@ -562,6 +580,17 @@ async function attributeUsage(startMs, endMs, periodStartsMs) {
562
580
  let attrAllCache = null;
563
581
  let attrBundlePending = false;
564
582
  let attrLastSave = 0;
583
+ let attrLastScan = 0; // timestamp of last scan start
584
+ // Set OPENCODE_ATTR_SCAN_DISABLED=1 to disable background attr scans entirely
585
+ const ATTR_SCAN_DISABLED = process.env.OPENCODE_ATTR_SCAN_DISABLED === '1';
586
+
587
+ // Throttle helper: yields to event loop after N iterations
588
+ function throttle(iteration) {
589
+ if (iteration % ITHROTTLE_BATCH === 0) {
590
+ return new Promise((r) => setTimeout(r, ITHROTTLE_DELAY_MS));
591
+ }
592
+ return Promise.resolve();
593
+ }
565
594
  const EMPTY_ATTR = {
566
595
  perDay: {}, perModel: {}, perAgent: {}, perSession: {},
567
596
  totals: { sessions: 0, messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },
@@ -720,18 +749,25 @@ function getAttrPeriod(startMs) {
720
749
  // cache stores, so the swap-in path is identical either way.
721
750
  function refreshAttrBundle() {
722
751
  if (attrBundlePending) return attrAllCache ? attrAllCache.a : null;
752
+ // Allow completely disabling background attribute scans via env var.
753
+ if (ATTR_SCAN_DISABLED) return attrAllCache ? attrAllCache.a : null;
723
754
  const now = Date.now();
724
755
  if (attrAllCache && now - attrAllCache.at < ATTR_TTL) return attrAllCache.a;
756
+ // Enforce minimum scan interval to prevent excessive scanning when DB
757
+ // revision changes frequently (e.g., due to WAL checkpoints during active
758
+ // opencode usage). This is independent of TTL and revision checks.
759
+ if (attrLastScan && now - attrLastScan < MIN_SCAN_INTERVAL) {
760
+ return attrAllCache ? attrAllCache.a : null;
761
+ }
725
762
  const rev = dbRevision();
726
763
  // DB hasn't changed since the last scan: just extend the TTL, no scan.
727
- // This is the common case on a machine where opencode is idle (which is most
728
- // of the time), and it turns a 30-60s rebuild into a stat() call.
729
764
  if (attrAllCache && rev && attrAllCache.dbRevision === rev) {
730
765
  attrAllCache.at = now;
731
766
  return attrAllCache.a;
732
767
  }
733
768
  attrBundlePending = true;
734
769
  attrWorkerActive = true;
770
+ attrLastScan = now;
735
771
  spawnAttrWorker(now, rev);
736
772
  return attrAllCache ? attrAllCache.a : null;
737
773
  }
@@ -993,7 +1029,9 @@ async function refresh() {
993
1029
  state.error = state.error || 'failed to read database';
994
1030
  }
995
1031
  } catch (e) {
1032
+ console.error("refresh error:", e);
996
1033
  state.error = e.message;
1034
+ state.loading = false;
997
1035
  } finally {
998
1036
  state.busy = false;
999
1037
  }