opencode-statboard 2.9.2 → 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.2",
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
@@ -343,8 +343,13 @@ const ATTR_TTL = 300000;
343
343
  // Minimum interval between full scans, regardless of DB revision changes.
344
344
  // Prevents excessive scanning when opencode is actively writing (WAL checkpoints
345
345
  // change DB mtime/size constantly, making revision appear changed every time).
346
- // Default 15 minutes — configurable via OPENCODE_MIN_SCAN_INTERVAL_MS.
347
- const MIN_SCAN_INTERVAL = parseInt(process.env.OPENCODE_MIN_SCAN_INTERVAL_MS || String(15 * 60 * 1000), 10);
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
348
353
  // Tool counts change slowly but the embedded-content scan costs ~2.8s on a
349
354
  // 2.7GB live DB, so it is computed by the stats WORKER (see spawnAttrWorker)
350
355
  // and only ever READ here. `fromWorker` marks worker-supplied data, which is
@@ -403,13 +408,14 @@ async function attributeUsage(startMs, endMs, periodStartsMs) {
403
408
  };
404
409
  });
405
410
 
406
- 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};`);
407
414
  let processed = 0;
408
- for (const row of rows) {
415
+ for (const row of stmt.iterate()) {
409
416
  let d = null;
410
417
  try { d = JSON.parse(row.data); } catch (_) { d = null; }
411
- processed++;
412
- if (!d) continue;
418
+ if (!d) { processed++; continue; }
413
419
  const key = localDayKey(new Date(row.t));
414
420
  const dayMs = dateOfKey(key).getTime();
415
421
  const tk = d.tokens || {};
@@ -472,9 +478,12 @@ async function attributeUsage(startMs, endMs, periodStartsMs) {
472
478
  const ag = sl.msgAgentAgg[agent] || (sl.msgAgentAgg[agent] = { o: 0, ms: 0 });
473
479
  if (hasDur) { ag.o += ov; ag.ms += (t1 - t0); }
474
480
  }
475
- 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);
476
484
  }
477
485
 
486
+ // Session table: smaller, keep as-is (only ~800 rows)
478
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};`) || [];
479
488
  let sessProcessed = 0;
480
489
  for (const s of srows) {
@@ -574,6 +583,14 @@ let attrLastSave = 0;
574
583
  let attrLastScan = 0; // timestamp of last scan start
575
584
  // Set OPENCODE_ATTR_SCAN_DISABLED=1 to disable background attr scans entirely
576
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
+ }
577
594
  const EMPTY_ATTR = {
578
595
  perDay: {}, perModel: {}, perAgent: {}, perSession: {},
579
596
  totals: { sessions: 0, messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },
@@ -732,6 +749,8 @@ function getAttrPeriod(startMs) {
732
749
  // cache stores, so the swap-in path is identical either way.
733
750
  function refreshAttrBundle() {
734
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;
735
754
  const now = Date.now();
736
755
  if (attrAllCache && now - attrAllCache.at < ATTR_TTL) return attrAllCache.a;
737
756
  // Enforce minimum scan interval to prevent excessive scanning when DB
@@ -1010,7 +1029,9 @@ async function refresh() {
1010
1029
  state.error = state.error || 'failed to read database';
1011
1030
  }
1012
1031
  } catch (e) {
1032
+ console.error("refresh error:", e);
1013
1033
  state.error = e.message;
1034
+ state.loading = false;
1014
1035
  } finally {
1015
1036
  state.busy = false;
1016
1037
  }