opencode-statboard 2.4.0 → 2.6.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.
Files changed (4) hide show
  1. package/package.json +1 -1
  2. package/pricing.js +67 -33
  3. package/public/index.html +699 -470
  4. package/server.js +386 -173
package/server.js CHANGED
@@ -80,13 +80,13 @@ const EXE = (() => {
80
80
 
81
81
  // OpenCode V2 writes sessions to session_v2 and messages to session_message
82
82
  // (tool parts embedded in message content); V1 used session/message/part and
83
- // froze at the upgrade. The V2 migration is LOSSY, so merge — never switch:
83
+ // froze at the upgrade. The V2 migration is LOSSY, so merge ??never switch:
84
84
  // - 455/734 migrated sessions LOST their lifetime totals (196M input tokens):
85
85
  // V2 recomputed them from surviving messages, dropping pruned compaction
86
86
  // history (sessions whose messages were fully pruned went to 0). V1's frozen
87
87
  // totals are the authoritative record, so take per-field MAX of the shared
88
- // rows (same lifetime counter — never SUM, that would double count).
89
- // - 30 messages were never migrated (4.3M input tokens) → union them in.
88
+ // rows (same lifetime counter ??never SUM, that would double count).
89
+ // - 30 messages were never migrated (4.3M input tokens) ??union them in.
90
90
  // - Tool parts: embedded content already covers migrated V1 parts, so only
91
91
  // parts of never-migrated messages are added from `part` (everything else
92
92
  // would double count).
@@ -212,13 +212,13 @@ function cleanExpiredCache(cache, ttl) {
212
212
  async function generateTrend(days) {
213
213
  // Buckets: local midnights, today -> (days-1) days ago.
214
214
  // Values are sliced from the SHARED all-time attribution (getAttrAll(),
215
- // the same object the usage report uses) — never a separate windowed
215
+ // the same object the usage report uses) ??never a separate windowed
216
216
  // attributeUsage call. Windowed attribution inflates in-window days:
217
217
  // messages before the window are excluded from msgTok, so the session
218
218
  // residual grows and lands entirely on windowed days (measured
219
- // +0.25–1.7M input/day on 2026-09-29). One shared attribution makes
219
+ // +0.25??.7M input/day on 2026-09-29). One shared attribution makes
220
220
  // trend buckets and report periods structurally identical; any remaining
221
- // panel difference is only cache age (trend ≤60s, report ≤10min, both
221
+ // panel difference is only cache age (trend ??0s, report ??0min, both
222
222
  // timestamps shown in the UI).
223
223
  const buckets = [];
224
224
  const today = new Date();
@@ -279,15 +279,17 @@ function splitModelName(name) {
279
279
  }
280
280
 
281
281
  // Market estimate for token usage at catalog paid rates (USD). saved is
282
- // market minus actual cost. pricedAs records the catalog entry used
283
- // ("proxy:" prefix = fallback estimate). Null when no pricing catalog.
282
+ // market minus actual cost. kind is 'exact' | 'sibling' | 'proxy' ??how the
283
+ // rate was found; null (kind 'unpriced') when the catalog has NO comparable
284
+ // paid listing, in which case we report no money at all rather than inventing
285
+ // a rate (that fake rate once turned a $0 model into $212 of phantom savings).
284
286
  // Market-price engine rules live in pricing.js (shared with check scripts).
285
287
  function marketOf(tok, provider, model) {
286
288
  const pr = pricing.priceFor(provider, model);
287
- if (!pr) return { market: null, saved: null, pricedAs: null };
289
+ if (!pr) return { market: null, saved: null, pricedAs: null, priced: false, kind: 'unpriced' };
288
290
  const market = pricing.marketOf(tok, pr);
289
291
  const r4m = (v) => Math.round(v * 10000) / 10000;
290
- return { market: r4m(market), saved: r4m(market - (tok.cost || 0)), pricedAs: pr.source };
292
+ return { market: r4m(market), saved: r4m(market - (tok.cost || 0)), pricedAs: pr.source, priced: true, kind: pr.kind };
291
293
  }
292
294
 
293
295
  // Hybrid usage attribution over [startMs, endMs).
@@ -306,105 +308,161 @@ function marketOf(tok, provider, model) {
306
308
  // buckets (perDay/perModel/perSession) are unaffected, so one scan serves both
307
309
  // the trend (lifetime) and the report (period) views. Period buckets group
308
310
  // message tokens by the MESSAGE's own model/agent, and spread session residual
309
- // by the session's model/agent — so per-model report rows sum exactly to the
311
+ // by the session's model/agent ??so per-model report rows sum exactly to the
310
312
  // period totals (self-consistent by construction).
311
- function attributeUsage(startMs, endMs, periodStartMs) {
312
- const periodOn = periodStartMs != null;
313
- const inPeriod = periodOn ? (key) => dateOfKey(key).getTime() >= periodStartMs : () => false;
313
+ // Hybrid attribution over [startMs, endMs), message layer + session residual.
314
+ //
315
+ // PERFORMANCE (measured 2026-10-11 on 62k messages / 993MB of JSON):
316
+ // message rows are fetched as raw `data` and parsed ONCE in Node. Doing the
317
+ // same work with a dozen json_extract() calls per row costs 43.6s in SQLite
318
+ // (it re-parses the whole content blob for every call) versus 1.6s + 0.9s
319
+ // this way. Period slices are folded in the same pass, so the trend, the
320
+ // overview and every report period share ONE scan per ATTR_TTL instead of
321
+ // paying for their own.
322
+ //
323
+ // Message tokens go to their exact local day; each session's residual
324
+ // (session totals minus its message sums, clamped >= 0) is spread across the
325
+ // session's full local-day span, weighted by its per-day message volume
326
+ // (uniform across spanned days when the session has no messages).
327
+ //
328
+ // periodStartsMs: optional ARRAY of local-midnight boundaries. Boundaries are
329
+ // NESTED (today ⊂ 7d ⊂ MTD ⊂ all), so a day feeds every boundary at or
330
+ // before it. Per-period buckets group message tokens by the MESSAGE's own
331
+ // model/agent and spread residual by the session's, so report rows sum
332
+ // exactly to the period totals. Each slice also carries msgAgg (per session:
333
+ // message count, output, reasoning, active ms, wall span on the MESSAGE clock)
334
+ // and msgAgentAgg, so reports need no extra queries.
335
+ 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.
338
+ let toolsCache = null;
339
+ const yieldToLoop = () => new Promise((r) => setImmediate(r));
340
+
341
+ function newTokBucket() {
342
+ return { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
343
+ }
344
+ function addTok(b, iv, ov, rv, crv, cwv, cv) {
345
+ b.input += iv; b.output += ov; b.reasoning += rv; b.cacheRead += crv; b.cacheWrite += cwv; b.cost += cv;
346
+ }
347
+
348
+ async function attributeUsage(startMs, endMs, periodStartsMs) {
349
+ const starts = (Array.isArray(periodStartsMs) ? periodStartsMs : [periodStartsMs])
350
+ .filter((x) => x != null).sort((a, b) => a - b);
351
+
314
352
  const perDay = {};
315
353
  const perModel = {};
316
354
  const perAgent = {};
317
355
  const perSession = {};
318
- const perModelPeriod = {};
319
- const perAgentPeriod = {};
320
- const perAgentModelPeriod = {};
321
- const perSessionPeriod = {};
322
- const perSessionModelPeriod = {};
323
- const ensureDay = (key) => perDay[key] || (perDay[key] = { date: dateOfKey(key), sessions: new Set(), messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
324
- const ensureModel = (n) => perModel[n] || (perModel[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
325
- const ensureAgent = (a) => perAgent[a || 'unknown'] || (perAgent[a || 'unknown'] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
326
- const tok = () => ({ input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
327
- const ensureModelP = (n) => perModelPeriod[n] || (perModelPeriod[n] = { messages: 0, sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
328
- const ensureAgentP = (a) => perAgentPeriod[a || 'unknown'] || (perAgentPeriod[a || 'unknown'] = { sessions: new Set(), input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0, speedOut: 0, speedMs: 0 });
329
- const ensureAgentModelP = (a, m) => {
330
- const k = a || 'unknown';
331
- const bag = perAgentModelPeriod[k] || (perAgentModelPeriod[k] = {});
332
- return bag[m] || (bag[m] = tok());
333
- };
334
- const ensureSessP = (sid) => perSessionPeriod[sid] || (perSessionPeriod[sid] = tok());
335
- const ensureSessModelP = (sid, m) => {
336
- const bag = perSessionModelPeriod[sid] || (perSessionModelPeriod[sid] = {});
337
- return bag[m] || (bag[m] = tok());
338
- };
339
-
340
- // 1. messages in period (exact timing)
341
356
  const msgTok = {};
342
357
  const msgW = {};
343
- const mrows = dbQuery(`SELECT time_created AS t, session_id AS sid, COALESCE(json_extract(data, '$.agent'), 'unknown') AS agent, COALESCE(json_extract(data, '$.providerID'), json_extract(data, '$.model.providerID'), 'unknown') AS provider, COALESCE(json_extract(data, '$.modelID'), json_extract(data, '$.model.modelID'), json_extract(data, '$.model.id'), 'unknown') AS model, COALESCE(CAST(json_extract(data, '$.tokens.input') AS INTEGER), 0) AS input, COALESCE(CAST(json_extract(data, '$.tokens.output') AS INTEGER), 0) AS output, COALESCE(CAST(json_extract(data, '$.tokens.reasoning') AS INTEGER), 0) AS reasoning, COALESCE(CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER), 0) AS cacheRead, COALESCE(CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER), 0) AS cacheWrite, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0) AS cost, CAST(json_extract(data, '$.time.created') AS INTEGER) AS t0, CAST(json_extract(data, '$.time.completed') AS INTEGER) AS t1 FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
344
- for (const r of mrows) {
345
- const key = localDayKey(new Date(r.t));
358
+ const ensureDay = (key) => perDay[key] || (perDay[key] = { date: dateOfKey(key), sessions: new Set(), messages: 0, ...newTokBucket() });
359
+ const ensureModel = (n) => perModel[n] || (perModel[n] = { messages: 0, sessions: new Set(), ...newTokBucket(), speedOut: 0, speedMs: 0 });
360
+ const ensureAgent = (a) => perAgent[a || 'unknown'] || (perAgent[a || 'unknown'] = { messages: 0, sessions: new Set(), ...newTokBucket() });
361
+
362
+ const slices = starts.map((s) => {
363
+ const perModelP = {}, perAgentP = {}, perAgentModelP = {}, perSessionP = {}, perSessionModelP = {};
364
+ const msgAgg = {}, msgAgentAgg = {};
365
+ return {
366
+ start: s,
367
+ perModel: perModelP, perAgent: perAgentP, perAgentModel: perAgentModelP,
368
+ perSession: perSessionP, perSessionModel: perSessionModelP,
369
+ msgAgg, msgAgentAgg,
370
+ model: (n) => perModelP[n] || (perModelP[n] = { messages: 0, sessions: new Set(), ...newTokBucket(), speedOut: 0, speedMs: 0 }),
371
+ agent: (a) => perAgentP[a || 'unknown'] || (perAgentP[a || 'unknown'] = { sessions: new Set(), ...newTokBucket(), speedOut: 0, speedMs: 0 }),
372
+ agentModel: (a, m) => {
373
+ const k = a || 'unknown';
374
+ const bag = perAgentModelP[k] || (perAgentModelP[k] = {});
375
+ return bag[m] || (bag[m] = newTokBucket());
376
+ },
377
+ sess: (sid) => perSessionP[sid] || (perSessionP[sid] = newTokBucket()),
378
+ sessModel: (sid, m) => {
379
+ const bag = perSessionModelP[sid] || (perSessionModelP[sid] = {});
380
+ return bag[m] || (bag[m] = newTokBucket());
381
+ },
382
+ };
383
+ });
384
+
385
+ const rows = dbQuery(`SELECT time_created AS t, session_id AS sid, data FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${endMs};`) || [];
386
+ let processed = 0;
387
+ for (const row of rows) {
388
+ let d = null;
389
+ try { d = JSON.parse(row.data); } catch (_) { d = null; }
390
+ processed++;
391
+ if (!d) continue;
392
+ const key = localDayKey(new Date(row.t));
393
+ const dayMs = dateOfKey(key).getTime();
394
+ const tk = d.tokens || {};
395
+ const cache = tk.cache || {};
396
+ const iv = +tk.input || 0, ov = +tk.output || 0, rv = +tk.reasoning || 0;
397
+ const crv = +cache.read || 0, cwv = +cache.write || 0, cv = +d.cost || 0;
398
+ const md = d.model || {};
399
+ const provider = d.providerID || md.providerID || 'unknown';
400
+ const model = d.modelID || md.modelID || md.id || 'unknown';
401
+ const agent = d.agent || 'unknown';
402
+ const mName = `${provider || 'unknown'}/${model || 'unknown'}`;
403
+ const dm = d.time || {};
404
+ const t0 = +dm.created || 0, t1 = +dm.completed || 0;
405
+ const hasDur = ov > 0 && t1 > t0;
406
+
346
407
  const D = ensureDay(key);
347
408
  D.messages++;
348
- if (r.sid) D.sessions.add(r.sid);
349
- const iv = +r.input || 0, ov = +r.output || 0, rv = +r.reasoning || 0;
350
- const crv = +r.cacheRead || 0, cwv = +r.cacheWrite || 0, cv = +r.cost || 0;
351
- D.input += iv; D.output += ov; D.reasoning += rv; D.cacheRead += crv; D.cacheWrite += cwv; D.cost += cv;
352
- const M = ensureModel(modelNameOf(r.provider, r.model));
409
+ if (row.sid) D.sessions.add(row.sid);
410
+ addTok(D, iv, ov, rv, crv, cwv, cv);
411
+ const M = ensureModel(mName);
353
412
  M.messages++;
354
- if (r.sid) M.sessions.add(r.sid);
355
- M.input += iv; M.output += ov; M.reasoning += rv; M.cacheRead += crv; M.cacheWrite += cwv; M.cost += cv;
356
- // Message-level generation speed only (session residuals have no
357
- // duration): output tokens per active second over completed messages.
358
- const t0 = +r.t0 || 0, t1 = +r.t1 || 0;
359
- if (ov > 0 && t1 > t0) { M.speedOut += ov; M.speedMs += (t1 - t0); }
360
- const A = ensureAgent(r.agent);
413
+ if (row.sid) M.sessions.add(row.sid);
414
+ addTok(M, iv, ov, rv, crv, cwv, cv);
415
+ if (hasDur) { M.speedOut += ov; M.speedMs += (t1 - t0); }
416
+ const A = ensureAgent(agent);
361
417
  A.messages++;
362
- if (r.sid) A.sessions.add(r.sid);
363
- A.input += iv; A.output += ov; A.reasoning += rv; A.cacheRead += crv; A.cacheWrite += cwv; A.cost += cv;
364
- if (r.sid) {
365
- const mt = msgTok[r.sid] || (msgTok[r.sid] = { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 });
366
- mt.input += iv; mt.output += ov; mt.reasoning += rv; mt.cacheRead += crv; mt.cacheWrite += cwv; mt.cost += cv;
367
- const w = msgW[r.sid] || (msgW[r.sid] = { total: 0, perDay: {} });
418
+ if (row.sid) A.sessions.add(row.sid);
419
+ addTok(A, iv, ov, rv, crv, cwv, cv);
420
+
421
+ if (row.sid) {
422
+ const mt = msgTok[row.sid] || (msgTok[row.sid] = newTokBucket());
423
+ addTok(mt, iv, ov, rv, crv, cwv, cv);
424
+ const w = msgW[row.sid] || (msgW[row.sid] = { total: 0, perDay: {} });
368
425
  const vol = iv + ov + rv + crv + cwv;
369
426
  w.total += vol;
370
427
  w.perDay[key] = (w.perDay[key] || 0) + vol;
371
428
  }
372
- // Period slice: message tokens under the MESSAGE's own model/agent.
373
- if (periodOn && inPeriod(key)) {
374
- const mName = modelNameOf(r.provider, r.model);
375
- const aName = r.agent || 'unknown';
376
- const MP = ensureModelP(mName);
429
+
430
+ for (const sl of slices) {
431
+ if (dayMs < sl.start) continue;
432
+ const MP = sl.model(mName);
377
433
  MP.messages++;
378
- if (r.sid) MP.sessions.add(r.sid);
379
- MP.input += iv; MP.output += ov; MP.reasoning += rv; MP.cacheRead += crv; MP.cacheWrite += cwv; MP.cost += cv;
380
- if (ov > 0 && t1 > t0) { MP.speedOut += ov; MP.speedMs += (t1 - t0); }
381
- const AP = ensureAgentP(aName);
382
- if (r.sid) AP.sessions.add(r.sid);
383
- AP.input += iv; AP.output += ov; AP.reasoning += rv; AP.cacheRead += crv; AP.cacheWrite += cwv; AP.cost += cv;
384
- if (ov > 0 && t1 > t0) { AP.speedOut += ov; AP.speedMs += (t1 - t0); }
385
- const AM = ensureAgentModelP(aName, mName);
386
- AM.input += iv; AM.output += ov; AM.reasoning += rv; AM.cacheRead += crv; AM.cacheWrite += cwv; AM.cost += cv;
387
- if (r.sid) {
388
- const SP = ensureSessP(r.sid);
389
- SP.input += iv; SP.output += ov; SP.reasoning += rv; SP.cacheRead += crv; SP.cacheWrite += cwv; SP.cost += cv;
390
- const SM = ensureSessModelP(r.sid, mName);
391
- SM.input += iv; SM.output += ov; SM.reasoning += rv; SM.cacheRead += crv; SM.cacheWrite += cwv; SM.cost += cv;
434
+ if (row.sid) MP.sessions.add(row.sid);
435
+ addTok(MP, iv, ov, rv, crv, cwv, cv);
436
+ if (hasDur) { MP.speedOut += ov; MP.speedMs += (t1 - t0); }
437
+ const AP = sl.agent(agent);
438
+ if (row.sid) AP.sessions.add(row.sid);
439
+ addTok(AP, iv, ov, rv, crv, cwv, cv);
440
+ if (hasDur) { AP.speedOut += ov; AP.speedMs += (t1 - t0); }
441
+ addTok(sl.agentModel(agent, mName), iv, ov, rv, crv, cwv, cv);
442
+ if (row.sid) {
443
+ addTok(sl.sess(row.sid), iv, ov, rv, crv, cwv, cv);
444
+ addTok(sl.sessModel(row.sid, mName), iv, ov, rv, crv, cwv, cv);
445
+ const ma = sl.msgAgg[row.sid] || (sl.msgAgg[row.sid] = { n: 0, o: 0, rq: 0, ms: 0, w0: Infinity, w1: 0 });
446
+ ma.n++;
447
+ if (hasDur) { ma.o += ov; ma.rq += rv; ma.ms += (t1 - t0); }
448
+ if (row.t < ma.w0) ma.w0 = row.t;
449
+ if (t1 > ma.w1) ma.w1 = t1;
392
450
  }
451
+ const ag = sl.msgAgentAgg[agent] || (sl.msgAgentAgg[agent] = { o: 0, ms: 0 });
452
+ if (hasDur) { ag.o += ov; ag.ms += (t1 - t0); }
393
453
  }
454
+ if ((processed & 0x3fff) === 0) await yieldToLoop();
394
455
  }
395
456
 
396
- // 2. sessions intersecting the period: spread residual
397
457
  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};`) || [];
458
+ let sessProcessed = 0;
398
459
  for (const s of srows) {
399
- // Use the session's FULL span for residual distribution. All consumers
400
- // share one all-time attribution (getAttrAll), so per-day values are
401
- // identical whichever period slices them.
402
460
  const d0 = new Date(new Date(s.tc).setHours(0, 0, 0, 0));
403
461
  const d1 = new Date(new Date(s.tu).setHours(0, 0, 0, 0));
404
462
  const spanKeys = [];
405
463
  for (let d = new Date(d0); d <= d1; d.setDate(d.getDate() + 1)) spanKeys.push(localDayKey(d));
406
- if (!spanKeys.length) continue;
407
- const mt = msgTok[s.id] || { input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
464
+ if (!spanKeys.length) { sessProcessed++; continue; }
465
+ const mt = msgTok[s.id] || newTokBucket();
408
466
  const res = {
409
467
  input: Math.max(0, (+s.si || 0) - mt.input),
410
468
  output: Math.max(0, (+s.so || 0) - mt.output),
@@ -413,7 +471,7 @@ function attributeUsage(startMs, endMs, periodStartMs) {
413
471
  cacheWrite: Math.max(0, (+s.scw || 0) - mt.cacheWrite),
414
472
  cost: Math.max(0, (+s.sc || 0) - mt.cost),
415
473
  };
416
- const ps = perSession[s.id] || (perSession[s.id] = { input: mt.input, output: mt.output, reasoning: mt.reasoning, cacheRead: mt.cacheRead, cacheWrite: mt.cacheWrite, cost: mt.cost });
474
+ const ps = perSession[s.id] || (perSession[s.id] = { ...mt });
417
475
  const w = msgW[s.id];
418
476
  let wTotal = 0;
419
477
  if (w) { for (const k of spanKeys) wTotal += w.perDay[k] || 0; }
@@ -422,7 +480,7 @@ function attributeUsage(startMs, endMs, periodStartMs) {
422
480
  } else {
423
481
  ensureDay(localDayKey(new Date(s.tu))).sessions.add(s.id);
424
482
  }
425
- const mName = modelNameOf(s.provider, s.model);
483
+ const mName = `${s.provider || 'unknown'}/${s.model || 'unknown'}`;
426
484
  const aName = s.agent || 'unknown';
427
485
  for (const k of spanKeys) {
428
486
  const share = wTotal > 0 ? ((w.perDay[k] || 0) / wTotal) : 1 / spanKeys.length;
@@ -430,76 +488,188 @@ function attributeUsage(startMs, endMs, periodStartMs) {
430
488
  const D = ensureDay(k);
431
489
  const di = res.input * share, dout = res.output * share, dr = res.reasoning * share;
432
490
  const dcr = res.cacheRead * share, dcw = res.cacheWrite * share, dc = res.cost * share;
433
- D.input += di; D.output += dout; D.reasoning += dr; D.cacheRead += dcr; D.cacheWrite += dcw; D.cost += dc;
491
+ addTok(D, di, dout, dr, dcr, dcw, dc);
434
492
  const M = ensureModel(mName);
435
- M.input += di; M.output += dout; M.reasoning += dr; M.cacheRead += dcr; M.cacheWrite += dcw; M.cost += dc;
493
+ addTok(M, di, dout, dr, dcr, dcw, dc);
436
494
  const A = ensureAgent(aName);
437
- A.input += di; A.output += dout; A.reasoning += dr; A.cacheRead += dcr; A.cacheWrite += dcw; A.cost += dc;
438
- ps.input += di; ps.output += dout; ps.reasoning += dr; ps.cacheRead += dcr; ps.cacheWrite += dcw; ps.cost += dc;
439
- // Period slice: residual shares land under the SESSION's model/agent
440
- // (no per-message model exists for residual), but only on days inside
441
- // the period, so period rows sum exactly to the period totals.
442
- if (periodOn && inPeriod(k)) {
443
- const MP = ensureModelP(mName);
444
- MP.input += di; MP.output += dout; MP.reasoning += dr; MP.cacheRead += dcr; MP.cacheWrite += dcw; MP.cost += dc;
445
- const AP = ensureAgentP(aName);
446
- AP.input += di; AP.output += dout; AP.reasoning += dr; AP.cacheRead += dcr; AP.cacheWrite += dcw; AP.cost += dc;
447
- const AM = ensureAgentModelP(aName, mName);
448
- AM.input += di; AM.output += dout; AM.reasoning += dr; AM.cacheRead += dcr; AM.cacheWrite += dcw; AM.cost += dc;
449
- const SP = ensureSessP(s.id);
450
- SP.input += di; SP.output += dout; SP.reasoning += dr; SP.cacheRead += dcr; SP.cacheWrite += dcw; SP.cost += dc;
451
- const SM = ensureSessModelP(s.id, mName);
452
- SM.input += di; SM.output += dout; SM.reasoning += dr; SM.cacheRead += dcr; SM.cacheWrite += dcw; SM.cost += dc;
495
+ addTok(A, di, dout, dr, dcr, dcw, dc);
496
+ addTok(ps, di, dout, dr, dcr, dcw, dc);
497
+ const dayMs = D.date.getTime();
498
+ for (const sl of slices) {
499
+ if (dayMs < sl.start) continue;
500
+ addTok(sl.model(mName), di, dout, dr, dcr, dcw, dc);
501
+ addTok(sl.agent(aName), di, dout, dr, dcr, dcw, dc);
502
+ addTok(sl.agentModel(aName, mName), di, dout, dr, dcr, dcw, dc);
503
+ addTok(sl.sess(s.id), di, dout, dr, dcr, dcw, dc);
504
+ addTok(sl.sessModel(s.id, mName), di, dout, dr, dcr, dcw, dc);
453
505
  }
454
506
  }
507
+ if ((++sessProcessed & 0x3f) === 0) await yieldToLoop();
455
508
  }
456
509
 
457
- const totals = { sessions: Object.keys(perSession).length, messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
510
+ const totals = { sessions: Object.keys(perSession).length, messages: 0, ...newTokBucket() };
458
511
  for (const k of Object.keys(perDay)) {
459
512
  const D = perDay[k];
460
513
  totals.messages += D.messages;
461
- totals.input += D.input; totals.output += D.output; totals.reasoning += D.reasoning;
462
- totals.cacheRead += D.cacheRead; totals.cacheWrite += D.cacheWrite; totals.cost += D.cost;
514
+ addTok(totals, D.input, D.output, D.reasoning, D.cacheRead, D.cacheWrite, D.cost);
463
515
  }
464
- return {
465
- perDay, perModel, perAgent, perSession, totals,
466
- perModelPeriod, perAgentPeriod, perAgentModelPeriod, perSessionPeriod, perSessionModelPeriod,
467
- periodStartMs,
468
- };
516
+
517
+ const out = { perDay, perModel, perAgent, perSession, totals, periods: new Map() };
518
+ for (const sl of slices) {
519
+ // Every slice also carries the all-time day buckets: the report sums its
520
+ // periodDays off perDay, and period 0 (all-time) IS the all-time view.
521
+ out.periods.set(sl.start, {
522
+ start: sl.start,
523
+ perDay,
524
+ perModelPeriod: sl.perModel,
525
+ perAgentPeriod: sl.perAgent,
526
+ perAgentModelPeriod: sl.perAgentModel,
527
+ perSessionPeriod: sl.perSession,
528
+ perSessionModelPeriod: sl.perSessionModel,
529
+ msgAgg: sl.msgAgg,
530
+ msgAgentAgg: sl.msgAgentAgg,
531
+ });
532
+ if (sl.start === 0) {
533
+ // period 0 == all-time: expose the bucket names the report reads.
534
+ out.perModelPeriod = sl.perModel;
535
+ out.perAgentPeriod = sl.perAgent;
536
+ out.perAgentModelPeriod = sl.perAgentModel;
537
+ out.perSessionPeriod = sl.perSession;
538
+ out.perSessionModelPeriod = sl.perSessionModel;
539
+ out.msgAgg = sl.msgAgg;
540
+ out.msgAgentAgg = sl.msgAgentAgg;
541
+ }
542
+ }
543
+ return out;
469
544
  }
470
545
 
471
- // All-time attribution, memoized 300s (expensive full DB scan; avoids
472
- // re-running attributeUsage on every /api/stats hit).
546
+ // ---- shared attribution bundle cache ----------------------------------
547
+ // One scan serves overview, trend and every report period. Memoized ATTR_TTL;
548
+ // rebuilds run detached (and yield internally), so request handlers never pay
549
+ // for the scan inline and the UI stays responsive while it happens.
473
550
  let attrAllCache = null;
474
- // Tool counts change slowly but the embedded-content scan costs ~1.5s on a
475
- // large DB; cache it so the 15s refresh stays cheap. Keyed on schema+window.
476
- let toolsCache = null;
477
- function getAttrAll() {
478
- const now = Date.now();
479
- if (attrAllCache && now - attrAllCache.at < 300000) return attrAllCache.a;
480
- // periodStartMs = 0: the *Period buckets equal the all-time ones, so the
481
- // All report can read them (single scan serves both views).
482
- const a = attributeUsage(0, now, 0);
483
- attrAllCache = { at: now, a };
551
+ let attrBundlePending = false;
552
+ let attrLastSave = 0;
553
+ const EMPTY_ATTR = {
554
+ perDay: {}, perModel: {}, perAgent: {}, perSession: {},
555
+ totals: { sessions: 0, messages: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },
556
+ periods: new Map(), msgAgg: {}, msgAgentAgg: {},
557
+ };
558
+ function periodStartsFor(now) {
559
+ return {
560
+ 1: periodStartMs(1, now),
561
+ 7: periodStartMs(7, now),
562
+ 30: periodStartMs(30, now),
563
+ '-1': 0,
564
+ };
565
+ }
566
+ async function buildAttrBundle(now) {
567
+ const a = await attributeUsage(0, now, Object.values(periodStartsFor(now)));
568
+ a.byPeriodStart = periodStartsFor(now);
484
569
  return a;
485
570
  }
486
571
 
487
- // Period-scoped attribution (same 300s TTL, one cache slot per period start).
488
- // Report panels slice this instead of the all-time buckets so every row and
489
- // the summary total describe the SAME period.
490
- const attrPeriodCache = new Map();
491
- function getAttrPeriod(startMs) {
492
- const now = Date.now();
493
- const hit = attrPeriodCache.get(startMs);
494
- if (hit && now - hit.at < 300000) return hit.a;
495
- const a = attributeUsage(0, now, startMs);
496
- attrPeriodCache.set(startMs, { at: now, a });
497
- if (attrPeriodCache.size > 6) {
498
- for (const [k, v] of attrPeriodCache) if (now - v.at >= 300000) attrPeriodCache.delete(k);
572
+ // ---- on-disk bundle cache ---------------------------------------------
573
+ // Scanning the live DB costs 5–26s (WAL + concurrent opencode writes), so the
574
+ // computed bundle is persisted and loaded on startup; a stale bundle still
575
+ // serves every request while a fresh one is rebuilt in the background.
576
+ const BUNDLE_FILE = path.join(__dirname, '.attr-bundle.json');
577
+ const BUNDLE_SAVE_MS = 60000; // don't hammer the disk while chatting
578
+ // Cache is bound to the exact database it was computed from, so pointing
579
+ // OPENCODE_DATA at another DB (tests, a restored copy) never reuses it.
580
+ function dbFingerprint() {
581
+ try {
582
+ const st = fs.statSync(BACKUP_SRC);
583
+ return `${BACKUP_SRC}|${st.size}|${Math.round(st.mtimeMs)}`;
584
+ } catch (_) { return BACKUP_SRC; }
585
+ }
586
+ function serializeBundle(a) {
587
+ 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;
590
+ };
591
+ const days = {};
592
+ for (const [k, v] of Object.entries(a.perDay)) days[k] = { ...v, dateMs: +v.date, date: undefined, sessions: [...v.sessions] };
593
+ const periods = {};
594
+ for (const [s, sl] of a.periods) periods[s] = {
595
+ ...sl,
596
+ perModelPeriod: setToArr(sl.perModelPeriod),
597
+ perAgentPeriod: setToArr(sl.perAgentPeriod),
598
+ };
599
+ return JSON.stringify({
600
+ v: 2, builtAt: a.builtAt, db: dbFingerprint(), byPeriodStart: a.byPeriodStart,
601
+ perDay: days,
602
+ perModel: setToArr(a.perModel), perAgent: setToArr(a.perAgent),
603
+ perSession: a.perSession, totals: a.totals, periods,
604
+ perModelPeriod: setToArr(a.perModelPeriod), perAgentPeriod: setToArr(a.perAgentPeriod),
605
+ perAgentModelPeriod: a.perAgentModelPeriod, perSessionPeriod: a.perSessionPeriod,
606
+ perSessionModelPeriod: a.perSessionModelPeriod,
607
+ msgAgg: a.msgAgg, msgAgentAgg: a.msgAgentAgg,
608
+ });
609
+ }
610
+ function reviveBundle(o) {
611
+ const fixDays = (d) => {
612
+ const out = {};
613
+ for (const [k, v] of Object.entries(d)) out[k] = { ...v, date: new Date(v.dateMs), dateMs: undefined, sessions: new Set(v.sessions) };
614
+ return out;
615
+ };
616
+ 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 || {};
619
+ };
620
+ const periods = new Map();
621
+ for (const [s, sl] of Object.entries(o.periods || {})) {
622
+ periods.set(+s, { ...sl, perDay: fixDays(o.perDay), perModelPeriod: fixSets(sl.perModelPeriod), perAgentPeriod: fixSets(sl.perAgentPeriod) });
499
623
  }
624
+ const a = {
625
+ ...o,
626
+ perDay: fixDays(o.perDay),
627
+ perModel: fixSets(o.perModel), perAgent: fixSets(o.perAgent),
628
+ perModelPeriod: fixSets(o.perModelPeriod), perAgentPeriod: fixSets(o.perAgentPeriod),
629
+ periods,
630
+ };
500
631
  return a;
501
632
  }
502
-
633
+ function saveBundleCache(a) {
634
+ try { fs.writeFileSync(BUNDLE_FILE, serializeBundle(a)); } catch (_) {}
635
+ }
636
+ function loadBundleCache() {
637
+ try {
638
+ const raw = fs.readFileSync(BUNDLE_FILE, 'utf8');
639
+ const o = JSON.parse(raw);
640
+ if (o && o.v === 2 && o.db === dbFingerprint() && o.periods && Object.keys(o.periods).length) {
641
+ console.log(`attr bundle loaded from cache (built ${Math.round((Date.now() - o.builtAt) / 60000)} min ago)`);
642
+ return { at: o.builtAt, a: reviveBundle(o) };
643
+ }
644
+ } catch (_) {}
645
+ return null;
646
+ }
647
+ function getAttrAll() {
648
+ if (!attrAllCache) refreshAttrBundle();
649
+ return attrAllCache ? attrAllCache.a : EMPTY_ATTR;
650
+ }
651
+ function getAttrPeriod(startMs) {
652
+ if (!attrAllCache) refreshAttrBundle();
653
+ if (!attrAllCache) return EMPTY_ATTR;
654
+ return attrAllCache.a.periods.get(startMs) || attrAllCache.a;
655
+ }
656
+ function refreshAttrBundle() {
657
+ if (attrBundlePending) return attrAllCache ? attrAllCache.a : null;
658
+ const now = Date.now();
659
+ if (attrAllCache && now - attrAllCache.at < ATTR_TTL) return attrAllCache.a;
660
+ 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) => {
668
+ attrBundlePending = false;
669
+ console.error('attr bundle failed:', e.message);
670
+ });
671
+ return attrAllCache ? attrAllCache.a : null;
672
+ }
503
673
  function computeMedian(arr) {
504
674
  if (!arr.length) return 0;
505
675
  const sorted = arr.slice().sort((a, b) => a - b);
@@ -521,7 +691,7 @@ function getStatsFromDb(days) {
521
691
 
522
692
  // V2: tool parts are embedded in session_message content (part table froze
523
693
  // at the upgrade and its migrated rows were rebuilt into content, so
524
- // querying all of part would double count — only parts of messages that
694
+ // querying all of part would double count ??only parts of messages that
525
695
  // were never migrated are added from `part`). Cached (see toolsCache):
526
696
  // verification accepts api<=expected, so staleness never fails checks.
527
697
  if (!toolsCache || now - toolsCache.at > TOOLS_TTL || toolsCache.embedded !== schema.embeddedTools || toolsCache.startMs !== startMs) {
@@ -581,9 +751,12 @@ function getStatsFromDb(days) {
581
751
  .sort((a, b) => b.cost - a.cost);
582
752
 
583
753
  // Savings estimate: market value of all-time usage at catalog paid rates,
584
- // priced per MESSAGE model (residual falls back to the session's model) —
585
- // the same basis as the report providers table.
754
+ // priced per MESSAGE model (residual falls back to the session's model) ?? // the same basis as the report providers table. Rows the catalog cannot
755
+ // price are EXCLUDED and disclosed (unpricedTokens/unpricedRows) instead of
756
+ // being valued at a made-up rate; proxyShare is how much of the priced
757
+ // total comes from cross-provider estimates.
586
758
  let marketTotal = null, savedTotal = null, priceAsOf = null;
759
+ let unpricedRows = 0, unpricedTokens = 0, proxyMarket = 0;
587
760
  {
588
761
  const info = pricing.catalogInfo();
589
762
  if (info.ok) {
@@ -591,14 +764,19 @@ function getStatsFromDb(days) {
591
764
  marketTotal = 0;
592
765
  for (const [name, m] of Object.entries(attr.perModel)) {
593
766
  const { provider, model } = splitModelName(name);
594
- const mk = marketOf({ input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost }, provider, model);
595
- if (mk.market === null) { marketTotal = null; break; }
767
+ const tok = { input: m.input, output: m.output, reasoning: m.reasoning, cacheRead: m.cacheRead, cost: m.cost };
768
+ const mk = marketOf(tok, provider, model);
769
+ if (!mk.priced) {
770
+ unpricedRows++;
771
+ unpricedTokens += tok.input + tok.output + tok.reasoning + tok.cacheRead;
772
+ continue;
773
+ }
596
774
  marketTotal += mk.market;
775
+ if (mk.kind === 'proxy') proxyMarket += mk.market;
597
776
  }
598
- if (marketTotal !== null) {
599
- marketTotal = Math.round(marketTotal * 10000) / 10000;
600
- savedTotal = Math.round((marketTotal - T.cost) * 10000) / 10000;
601
- } else { savedTotal = null; }
777
+ marketTotal = Math.round(marketTotal * 10000) / 10000;
778
+ savedTotal = Math.round((marketTotal - T.cost) * 10000) / 10000;
779
+ proxyMarket = Math.round(proxyMarket * 10000) / 10000;
602
780
  }
603
781
  }
604
782
 
@@ -616,6 +794,8 @@ function getStatsFromDb(days) {
616
794
  cacheRead: Math.round(T.cacheRead),
617
795
  cacheWrite: Math.round(T.cacheWrite),
618
796
  marketTotal, savedTotal, priceAsOf,
797
+ unpricedRows, unpricedTokens, proxyMarket,
798
+ proxyShare: marketTotal > 0 ? Math.round((proxyMarket / marketTotal) * 1000) / 10 : null,
619
799
  },
620
800
  tools,
621
801
  models,
@@ -754,8 +934,8 @@ function buildReportFromDb(days) {
754
934
  // sessions, market/saved) is sliced to THIS period, so the tables sum to the
755
935
  // card. The all-time buckets (perDay) are still used for the summary totals
756
936
  // and stay identical to the trend chart for the same period.
757
- const a = days === -1 ? getAttrAll() : getAttrPeriod(startMs);
758
- const aNow = days === -1 ? attrAllCache.at : attrPeriodCache.get(startMs).at; // snapshot time of `a`
937
+ const a = getAttrPeriod(startMs);
938
+ const aNow = attrAllCache.at; // snapshot time of the shared bundle
759
939
  // Message-level stats per session within the period (period speed + active
760
940
  // time). One GROUP BY over the merged message view, mapped onto the same
761
941
  // session-meta buckets as tokens so row sets stay identical.
@@ -763,19 +943,17 @@ function buildReportFromDb(days) {
763
943
  // subagent/fork sessions are written with time_updated == time_created
764
944
  // (same millisecond), which would report ~0 wall for hours of real work.
765
945
  // Query the merged message view for the period span per session.
946
+ // Speed / active / wall come from the shared attribution bundle (the same
947
+ // message pass that produced these period buckets), so switching scope costs
948
+ // no SQL at all. Wall uses the MESSAGE clock: subagent/fork sessions are
949
+ // written with time_updated == time_created, which would read as ~0 wall.
950
+ const msgAgg = a.msgAgg || {};
951
+ const msgAgentAgg = a.msgAgentAgg || {};
766
952
  const wallMs = {};
767
- for (const m of (dbQuery(`SELECT session_id AS sid, MIN(time_created) AS t0, MAX(COALESCE(CAST(json_extract(data,'$.time.completed') AS INTEGER), time_updated)) AS t1 FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY session_id`) || [])) {
768
- wallMs[m.sid] = Math.max(0, (+m.t1 || 0) - (+m.t0 || 0));
769
- }
770
- const msgAgg = {};
771
- for (const m of (dbQuery(`SELECT session_id AS sid, COUNT(*) AS n, COALESCE(SUM(CASE WHEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data, '$.time.completed') AS INTEGER) > CAST(json_extract(data, '$.time.created') AS INTEGER) THEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) ELSE 0 END), 0) AS o, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.tokens.reasoning') AS INTEGER) ELSE 0 END), 0) AS rq, COALESCE(SUM(CASE WHEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data, '$.time.completed') AS INTEGER) > CAST(json_extract(data, '$.time.created') AS INTEGER) THEN CAST(json_extract(data, '$.time.completed') AS INTEGER) - CAST(json_extract(data, '$.time.created') AS INTEGER) ELSE 0 END), 0) AS ms FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY sid`) || [])) {
772
- msgAgg[m.sid] = m;
773
- }
774
- // Same aggregates per agent — the message layer can name agents that session
775
- // meta lacks (compaction/plan), so agent speed/active come from messages.
776
- const msgAgentAgg = {};
777
- for (const m of (dbQuery(`SELECT COALESCE(json_extract(data,'$.agent'),'unknown') AS agent, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) ELSE 0 END),0) AS o, COALESCE(SUM(CASE WHEN CAST(json_extract(data,'$.tokens.output') AS INTEGER) > 0 AND CAST(json_extract(data,'$.time.completed') AS INTEGER) > CAST(json_extract(data,'$.time.created') AS INTEGER) THEN CAST(json_extract(data,'$.time.completed') AS INTEGER) - CAST(json_extract(data,'$.time.created') AS INTEGER) ELSE 0 END),0) AS ms FROM ${schema.message} WHERE time_created >= ${startMs} AND time_created < ${aNow} GROUP BY COALESCE(json_extract(data,'$.agent'),'unknown')`) || [])) {
778
- msgAgentAgg[m.agent] = { o: m.o, ms: m.ms };
953
+ for (const sid of Object.keys(msgAgg)) {
954
+ const m = msgAgg[sid];
955
+ const w0 = m.w0 === Infinity ? 0 : m.w0;
956
+ wallMs[sid] = Math.max(0, (+m.w1 || 0) - w0);
779
957
  }
780
958
  const periodDays = {};
781
959
  for (const [key, val] of Object.entries(a.perDay)) {
@@ -793,7 +971,7 @@ function buildReportFromDb(days) {
793
971
  }
794
972
  const t = periodTotals;
795
973
  const activeDays = pdVals.length || 1;
796
- // Avg/median over the PERIOD's token-bearing sessions — period buckets, so
974
+ // Avg/median over the PERIOD's token-bearing sessions ??period buckets, so
797
975
  // Daily/Weekly differ and the value matches the card and the tables.
798
976
  const periodSessionIds = [...periodTotals.sessions];
799
977
  const sessVals = periodSessionIds
@@ -846,20 +1024,21 @@ function buildReportFromDb(days) {
846
1024
  tok_in: Math.round(m.input), tok_out: Math.round(m.output),
847
1025
  tok_reasoning: Math.round(m.reasoning), cache_read: Math.round(m.cacheRead),
848
1026
  speed: m.speedMs > 0 ? Math.round((m.speedOut / (m.speedMs / 1000)) * 10) / 10 : null,
849
- market: mk.market, saved: mk.saved, pricedAs: mk.pricedAs,
1027
+ market: mk.market, saved: mk.saved, pricedAs: mk.pricedAs, priced: mk.priced, kind: mk.kind,
850
1028
  };
851
1029
  })
852
1030
  .sort((x, y) => y.cost - x.cost);
853
1031
 
854
1032
  var pAgentRows = Object.entries(a.perAgentPeriod)
855
1033
  .map(([agent, m]) => {
856
- let market = 0, saved = 0, priced = false;
1034
+ let market = 0, saved = 0, pricedAny = false, unpriced = 0, proxy = 0;
857
1035
  const bag = (a.perAgentModelPeriod && a.perAgentModelPeriod[agent]) || {};
858
1036
  for (const [name, b] of Object.entries(bag)) {
859
1037
  const { provider, model } = splitModelName(name);
860
1038
  const mk = marketOf({ input: b.input, output: b.output, reasoning: b.reasoning, cacheRead: b.cacheRead, cost: b.cost }, provider, model);
861
- if (mk.market === null) { market = null; break; }
862
- market += mk.market; saved += mk.saved; priced = true;
1039
+ if (!mk.priced) { unpriced++; continue; }
1040
+ market += mk.market; saved += mk.saved; pricedAny = true;
1041
+ if (mk.kind === 'proxy') proxy += mk.market;
863
1042
  }
864
1043
  // Wall = period span measured on the message clock (see wallMs above).
865
1044
  let agentWall = 0;
@@ -871,9 +1050,10 @@ function buildReportFromDb(days) {
871
1050
  speed: msgAgentAgg[agent] && msgAgentAgg[agent].ms > 0 ? Math.round((msgAgentAgg[agent].o / (msgAgentAgg[agent].ms / 1000)) * 10) / 10 : null,
872
1051
  wallMs: Math.round(agentWall),
873
1052
  activeMs: msgAgentAgg[agent] ? Math.round(msgAgentAgg[agent].ms) : 0,
874
- market: market === null ? null : Math.round(market * 10000) / 10000,
875
- saved: market === null ? null : Math.round(saved * 10000) / 10000,
876
- pricedAs: priced,
1053
+ market: pricedAny ? Math.round(market * 10000) / 10000 : null,
1054
+ saved: pricedAny ? Math.round(saved * 10000) / 10000 : null,
1055
+ pricedAs: pricedAny ? (proxy > 0 && proxy >= market - 0.01 ? 'mixed' : 'exact') : null,
1056
+ priced: pricedAny, kind: !pricedAny ? 'unpriced' : (unpriced > 0 ? 'partial' : (proxy > 0 ? 'proxy' : 'exact')),
877
1057
  };
878
1058
  })
879
1059
  .sort((x, y) => y.cost - x.cost);
@@ -905,7 +1085,7 @@ function buildReportFromDb(days) {
905
1085
  tok_reasoning: Math.round(mg.rq || 0),
906
1086
  cost: r4(ps.cost),
907
1087
  speed: (mg.ms || 0) > 0 ? Math.round(((mg.o || 0) / (mg.ms / 1000)) * 10) / 10 : null,
908
- market, saved, pricedAs,
1088
+ market, saved, pricedAs, priced: mkS.priced, kind: mkS.kind,
909
1089
  };
910
1090
  })
911
1091
  .sort((x, y) => y.activeMs - x.activeMs)
@@ -916,14 +1096,19 @@ function buildReportFromDb(days) {
916
1096
  var pSessionRows = [];
917
1097
  }
918
1098
 
919
- // Period market = Σ provider rows (already period-scoped); saved = Σ provider
920
- // saved so it can never mix a period cost with a lifetime market.
1099
+ // Period market = 峉 priced provider rows (already period-scoped); saved = 峉
1100
+ // provider saved so it can never mix a period cost with a lifetime market.
1101
+ // Unpriced rows are disclosed, not valued.
921
1102
  const sumMkt = (rows) => rows.reduce((s, r) => s + (r.market || 0), 0);
922
1103
  const sumSaved = (rows) => rows.reduce((s, r) => s + (r.saved || 0), 0);
923
1104
  statsR.cost.marketTotal = Math.round(sumMkt(pProviderRows) * 10000) / 10000;
924
1105
  statsR.cost.savedTotal = Math.round(sumSaved(pProviderRows) * 10000) / 10000;
925
1106
  statsR.cost.savedPct = statsR.cost.marketTotal > 0 ? Math.round((statsR.cost.savedTotal / statsR.cost.marketTotal) * 1000) / 10 : null;
926
1107
  statsR.cost.priceAsOf = pricing.catalogInfo().ok ? new Date(pricing.catalogInfo().mtimeMs).toISOString() : null;
1108
+ statsR.cost.unpricedRows = pProviderRows.filter((r) => !r.priced).length;
1109
+ statsR.cost.unpricedTokens = pProviderRows.filter((r) => !r.priced).reduce((s, r) => s + r.tok_in + r.tok_out + r.tok_reasoning + r.cache_read, 0);
1110
+ const proxyMkt = pProviderRows.filter((r) => r.kind === 'proxy').reduce((s, r) => s + (r.market || 0), 0);
1111
+ statsR.cost.proxyShare = statsR.cost.marketTotal > 0 ? Math.round((proxyMkt / statsR.cost.marketTotal) * 1000) / 10 : null;
927
1112
 
928
1113
  return {
929
1114
  label,
@@ -949,8 +1134,14 @@ function refreshReport(days) {
949
1134
  const r = buildReportFromDb(days);
950
1135
  if (r && r.stats && r.stats.ok) {
951
1136
  reportCache[key] = r;
1137
+ } else {
1138
+ console.error(`report build failed for days=${days}`);
952
1139
  }
953
- } catch (_) {} finally {
1140
+ } catch (e) {
1141
+ // Never swallow silently: a broken report must not look like "still
1142
+ // generating" forever while the frontend retries.
1143
+ console.error(`report build threw for days=${days}:`, e && e.stack ? e.stack.split('\n')[0] : e);
1144
+ } finally {
954
1145
  delete reportBusy[key];
955
1146
  }
956
1147
  });
@@ -1134,9 +1325,32 @@ function tryListen(port, maxPort) {
1134
1325
  const actualPort = await tryListen(PORT, PORT + 5);
1135
1326
  setInterval(refresh, REFRESH_MS);
1136
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;
1331
+ const cached = loadBundleCache();
1332
+ attrAllCache = cached || null;
1333
+ if (cached) refreshAttrBundle();
1334
+ setInterval(refreshAttrBundle, 60000);
1137
1335
  await refresh();
1138
1336
  await refreshModels();
1139
- for (const d of [1, 7, 30]) {
1337
+ 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)`);
1348
+ await refresh();
1349
+ await refreshModels();
1350
+ }
1351
+ // Today's report eagerly (the common first view). Other periods build on
1352
+ // demand in the background via refreshReport stale-while-revalidate.
1353
+ for (const d of [1]) {
1140
1354
  try {
1141
1355
  const r = buildReportFromDb(d);
1142
1356
  if (r && r.stats && r.stats.ok) reportCache[String(d)] = r;
@@ -1148,7 +1362,6 @@ function tryListen(port, maxPort) {
1148
1362
  if (t) trendCache[String(d)] = t;
1149
1363
  } catch (_) {}
1150
1364
  }
1151
- // Defer backup to avoid heavy disk I/O during startup
1152
1365
  // (Windows may kill process for excessive I/O on large DB files).
1153
1366
  setTimeout(() => {
1154
1367
  autoBackupIfDue().catch((_) => {});