opencode-statboard 1.0.11 → 1.0.13

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": "opencode-statboard",
3
- "version": "1.0.11",
3
+ "version": "1.0.13",
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
@@ -20,6 +20,9 @@
20
20
  .pill.err { color: #f85149; border-color: #da3633; background: rgba(248,81,73,.08); }
21
21
  .pill.lang { color: var(--text); border-color: var(--border); background: rgba(139,148,158,.08); }
22
22
  .pill.lang:hover { background: rgba(139,148,158,.18); }
23
+ .pill.backup { color: var(--cache); border-color: var(--cache); background: rgba(210,153,34,.08); }
24
+ .pill.backup:hover { background: rgba(210,153,34,.18); }
25
+ .pill.backup.busy { opacity: .6; pointer-events: none; }
23
26
  .range-btns { display: flex; gap: 4px; }
24
27
  .range-btns .pill.active { color: var(--text); border-color: #58a6ff; background: rgba(88,166,255,.12); }
25
28
  .range-btns .pill:not(.active) { color: var(--muted); border-color: var(--border); background: transparent; }
@@ -66,17 +69,19 @@
66
69
  .skeleton-card { height: 60px; }
67
70
  .trend-bar { position: absolute; bottom: 0; border-radius: 2px 2px 0 0; transition: height .4s ease; }
68
71
  .trend-bar-cache { left: 0; right: 0; opacity: .2; }
72
+ .version { font-size: 11px; color: var(--muted); background: var(--panel); border: 1px solid var(--border); padding: 2px 8px; border-radius: 4px; }
69
73
  .trend-bar-input { left: 25%; width: 22%; z-index: 1; }
70
74
  .trend-bar-output { left: 53%; width: 22%; z-index: 1; }
71
75
  </style>
72
76
  </head>
73
77
  <body>
74
78
  <header>
75
- <h1><span class="dot">●</span> <span data-i18n="title">opencode Dashboard</span></h1>
79
+ <h1><span class="dot">●</span> <span data-i18n="title">opencode Dashboard</span> <span class="version">v__VERSION__</span></h1>
76
80
  <div class="status">
77
81
  <span id="updated">Loading…</span>
78
82
  <span class="pill ok" id="pill" data-i18n="live">Live</span>
79
83
  <span class="pill lang" id="langBtn" onclick="toggleLang()"></span>
84
+ <span class="pill backup" id="backupBtn" onclick="backupDb()" data-i18n="backup">Backup DB</span>
80
85
  </div>
81
86
  </header>
82
87
 
@@ -180,6 +185,7 @@ const STRINGS = {
180
185
  live: 'Live', loading: 'Loading…', lastUpdated: 'Last updated', dataAgo: 'data generated',
181
186
  statsFail: 'Failed to read opencode stats', connFail: 'Connection failed',
182
187
  langBtn: '繁中',
188
+ backup: 'Backup DB', backingUp: 'Backing up…', backupFail: 'Backup failed',
183
189
  },
184
190
  'zh-TW': {
185
191
  title: 'opencode 用量儀表板',
@@ -196,6 +202,7 @@ const STRINGS = {
196
202
  live: '即時更新', loading: '載入中…', lastUpdated: '更新於', dataAgo: '數據產生於',
197
203
  statsFail: 'opencode stats 讀取失敗', connFail: '連線失敗',
198
204
  langBtn: 'EN',
205
+ backup: '備份 DB', backingUp: '備份中…', backupFail: '備份失敗',
199
206
  }
200
207
  };
201
208
 
@@ -217,7 +224,29 @@ function applyI18n() {
217
224
  function toggleLang() {
218
225
  lang = lang === 'en' ? 'zh-TW' : 'en';
219
226
  localStorage.setItem('lang', lang);
220
- applyI18n();
227
+ async function backupDb() {
228
+ const btn = $('backupBtn');
229
+ btn.classList.add('busy');
230
+ btn.textContent = t('backingUp');
231
+ try {
232
+ const r = await fetch('/api/backup', { cache: 'no-store' });
233
+ const j = await r.json();
234
+ if (j.ok && j.file) {
235
+ btn.textContent = '✓ ' + j.file;
236
+ btn.title = (j.size / 1024 / 1024).toFixed(1) + ' MB';
237
+ } else {
238
+ btn.textContent = '✗ ' + t('backupFail');
239
+ btn.title = j.error || '';
240
+ }
241
+ } catch (e) {
242
+ btn.textContent = '✗ ' + t('backupFail');
243
+ btn.title = e.message;
244
+ }
245
+ btn.classList.remove('busy');
246
+ setTimeout(() => { btn.textContent = t('backup'); }, 5000);
247
+ }
248
+
249
+ applyI18n();
221
250
  }
222
251
 
223
252
  const $ = (id) => document.getElementById(id);
package/server.js CHANGED
@@ -9,6 +9,13 @@ const REFRESH_MS = 15000;
9
9
  const TREND_MS = 10 * 60 * 1000;
10
10
  const REPORT_TTL = 10 * 60 * 1000;
11
11
  const CACHE_CLEANUP_MS = 5 * 60 * 1000;
12
+ const BACKUP_DIR = path.join(__dirname, 'backups');
13
+ const BACKUP_RETENTION = parseInt(process.env.OPENCODE_BACKUP_RETENTION || '0', 10) || 0;
14
+ const BACKUP_SRC = process.env.OPENCODE_DATA
15
+ ? path.join(process.env.OPENCODE_DATA, 'opencode.db')
16
+ : path.join(process.env.USERPROFILE || process.env.HOME || '', '.local', 'share', 'opencode', 'opencode.db');
17
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
18
+ const VERSION = pkg.version;
12
19
 
13
20
  const EXE = (() => {
14
21
  const candidates = [
@@ -22,6 +29,9 @@ const state = { data: null, busy: false, error: null, updatedAt: 0, models: null
22
29
 
23
30
  let indexHtmlCache = null;
24
31
 
32
+ let backupBusy = false;
33
+ let lastAutoBackupDay = '';
34
+
25
35
  function loadIndexHtml(callback) {
26
36
  if (indexHtmlCache) return callback(null, indexHtmlCache);
27
37
  fs.readFile(path.join(__dirname, 'public', 'index.html'), 'utf8', (err, data) => {
@@ -235,6 +245,61 @@ async function refreshModels() {
235
245
  state.modelsBusy = false;
236
246
  }
237
247
 
248
+ function backupDirName() {
249
+ const d = new Date();
250
+ const p = (n) => String(n).padStart(2, '0');
251
+ return `opencode-${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
252
+ }
253
+
254
+ async function performBackup(auto) {
255
+ if (backupBusy) return { ok: false, busy: true };
256
+ backupBusy = true;
257
+ try {
258
+ if (!fs.existsSync(BACKUP_SRC)) return { ok: false, error: 'source db not found: ' + BACKUP_SRC };
259
+ const srcDir = path.dirname(BACKUP_SRC);
260
+ const files = ['opencode.db', 'opencode.db-wal', 'opencode.db-shm'].filter((n) => fs.existsSync(path.join(srcDir, n)));
261
+ const dir = backupDirName();
262
+ const destDir = path.join(BACKUP_DIR, dir);
263
+ fs.mkdirSync(destDir, { recursive: true });
264
+ let size = 0;
265
+ for (const n of files) {
266
+ fs.copyFileSync(path.join(srcDir, n), path.join(destDir, n));
267
+ size += fs.statSync(path.join(destDir, n)).size;
268
+ }
269
+ if (auto) lastAutoBackupDay = dir.slice(9, 17);
270
+ if (BACKUP_RETENTION > 0) {
271
+ const dirs = fs.readdirSync(BACKUP_DIR)
272
+ .filter((f) => f.startsWith('opencode-') && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())
273
+ .sort();
274
+ if (dirs.length > BACKUP_RETENTION) {
275
+ for (const f of dirs.slice(0, dirs.length - BACKUP_RETENTION)) {
276
+ fs.rmSync(path.join(BACKUP_DIR, f), { recursive: true, force: true });
277
+ }
278
+ }
279
+ }
280
+ console.log(`backup ok: ${dir} (${(size / 1024 / 1024).toFixed(1)} MB)`);
281
+ return { ok: true, file: dir, size, files };
282
+ } catch (e) {
283
+ return { ok: false, error: e.message };
284
+ } finally {
285
+ backupBusy = false;
286
+ }
287
+ }
288
+
289
+ async function autoBackupIfDue() {
290
+ const d = new Date();
291
+ const p = (n) => String(n).padStart(2, '0');
292
+ const day = `opencode-${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}`;
293
+ if (lastAutoBackupDay === day.slice(9, 17)) return;
294
+ try {
295
+ if (fs.readdirSync(BACKUP_DIR).some((f) => f.startsWith(day) && fs.statSync(path.join(BACKUP_DIR, f)).isDirectory())) {
296
+ lastAutoBackupDay = day.slice(9, 17);
297
+ return;
298
+ }
299
+ } catch (e) { /* dir not created yet */ }
300
+ await performBackup(true);
301
+ }
302
+
238
303
  function clamp(n) {
239
304
  return Number.isFinite(n) && n > 0 ? n : 0;
240
305
  }
@@ -349,6 +414,11 @@ const server = http.createServer(async (req, res) => {
349
414
  ready: r.ready,
350
415
  report: r.report,
351
416
  }));
417
+ } else if (u === '/api/backup') {
418
+ performBackup(false).then((r) => {
419
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
420
+ res.end(JSON.stringify(r));
421
+ });
352
422
  } else if (u === '/') {
353
423
  loadIndexHtml((err, data) => {
354
424
  if (err) {
@@ -357,7 +427,7 @@ const server = http.createServer(async (req, res) => {
357
427
  return;
358
428
  }
359
429
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
360
- res.end(data);
430
+ res.end(data.replace('__VERSION__', VERSION));
361
431
  });
362
432
  } else {
363
433
  res.statusCode = 404;
@@ -379,6 +449,7 @@ process.on('SIGTERM', gracefulShutdown);
379
449
  setInterval(() => {
380
450
  cleanExpiredCache(trendCache, TREND_MS * 2);
381
451
  cleanExpiredCache(reportCache, REPORT_TTL * 2);
452
+ autoBackupIfDue();
382
453
  }, CACHE_CLEANUP_MS);
383
454
 
384
455
  (async () => {
@@ -397,4 +468,5 @@ setInterval(() => {
397
468
  const t = await generateTrend(d);
398
469
  if (t) trendCache[String(d)] = t;
399
470
  }
471
+ await autoBackupIfDue();
400
472
  })();