opencode-usage-insights 0.3.1 → 0.4.1

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 (57) hide show
  1. package/README.md +67 -542
  2. package/dist/core.d.ts +15 -1
  3. package/dist/gui-experimental.cjs +3 -3
  4. package/dist/index.d.ts +0 -47
  5. package/dist/index.js +1734 -1209
  6. package/dist/index.js.map +23 -16
  7. package/dist/line.d.ts +1 -0
  8. package/dist/panel-data.d.ts +9 -2
  9. package/dist/recorder.d.ts +1 -0
  10. package/dist/rpc.d.ts +4 -4
  11. package/dist/rpc.js +5 -5
  12. package/dist/rpc.js.map +3 -3
  13. package/dist/settings-client.d.ts +29 -0
  14. package/dist/settings-rpc.d.ts +746 -0
  15. package/dist/settings.d.ts +114 -0
  16. package/dist/sidebar.d.ts +3 -3
  17. package/dist/stats/aggregates.d.ts +15 -3
  18. package/dist/stats/constants.d.ts +7 -0
  19. package/dist/stats/db.d.ts +8 -128
  20. package/dist/stats/legacy.d.ts +25 -0
  21. package/dist/stats/maintenance.d.ts +1 -1
  22. package/dist/stats/migrate.d.ts +7 -0
  23. package/dist/stats/ndjson.d.ts +16 -0
  24. package/dist/stats/open.d.ts +15 -0
  25. package/dist/stats/paths.d.ts +5 -4
  26. package/dist/stats/queries.d.ts +30 -35
  27. package/dist/stats/records.d.ts +94 -0
  28. package/dist/stats/schema.d.ts +26 -0
  29. package/dist/stats-client.d.ts +9 -0
  30. package/dist/stats-worker.js +597 -367
  31. package/dist/stats-worker.js.map +17 -12
  32. package/dist/text.d.ts +2 -0
  33. package/dist/tui-settings.d.ts +18 -0
  34. package/dist/tui.d.ts +1 -57
  35. package/dist/tui.js +974 -158
  36. package/dist/tui.js.map +17 -13
  37. package/docs/cli.md +24 -0
  38. package/docs/configuration.md +108 -0
  39. package/docs/costs.md +44 -0
  40. package/docs/demo.md +94 -68
  41. package/docs/desktop.md +91 -0
  42. package/docs/images/desktop-overview-annotated.png +0 -0
  43. package/docs/images/desktop-overview.png +0 -0
  44. package/docs/images/desktop-settings.png +0 -0
  45. package/docs/images/desktop-turns-go-annotated.png +0 -0
  46. package/docs/images/desktop-turns.png +0 -0
  47. package/docs/images/line.png +0 -0
  48. package/docs/images/panel-cache.png +0 -0
  49. package/docs/images/panel-help.png +0 -0
  50. package/docs/images/panel-latency.png +0 -0
  51. package/docs/images/panel-overview.png +0 -0
  52. package/docs/images/panel-providers.png +0 -0
  53. package/docs/images/sidebar.png +0 -0
  54. package/docs/internals.md +87 -36
  55. package/docs/privacy.md +60 -0
  56. package/docs/tui.md +175 -0
  57. package/package.json +8 -7
package/dist/tui.js CHANGED
@@ -351,23 +351,9 @@ function formatLine(stats, options) {
351
351
  return formatLineSegments(stats, options).map((segment) => segment.text).join(" \xB7 ");
352
352
  }
353
353
 
354
- // src/limits.ts
355
- var MAX_PANEL_WIDTH = 200;
356
- var MAX_HISTORY_WIDTH = 120;
357
- var MAX_TURNS = 50;
358
- function clampPanelWidth(value) {
359
- if (!Number.isFinite(value))
360
- return 20;
361
- return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
362
- }
363
- function clampTurnsLimit(value) {
364
- if (!Number.isFinite(value))
365
- return 1;
366
- return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
367
- }
368
-
369
354
  // src/text.ts
370
355
  var TEXT_LIMIT = 512;
356
+ var LABEL_LIMIT = 4 * TEXT_LIMIT;
371
357
  function sanitizeText(value, limit = TEXT_LIMIT) {
372
358
  if (limit <= 0)
373
359
  return "";
@@ -497,7 +483,6 @@ function lineText(parts) {
497
483
  }
498
484
 
499
485
  // src/stats/queries.ts
500
- var COMPACTION_KIND = "compaction";
501
486
  var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
502
487
  function spend(usage) {
503
488
  return usage.cost + usage.listCost;
@@ -567,9 +552,12 @@ function otherUsageRows(db, range, filters) {
567
552
  }
568
553
  }
569
554
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
570
- var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
555
+ var MODEL_KEY_SEPARATOR = "#";
556
+ function modelKeySQL(prefix = "") {
557
+ return `COALESCE(${prefix}model_id, '(unknown)') || '${MODEL_KEY_SEPARATOR}' || COALESCE(${prefix}variant, '')`;
558
+ }
571
559
  function modelKey(modelID, variant) {
572
- return `${modelID}#${variant ?? ""}`;
560
+ return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? ""}`;
573
561
  }
574
562
  function modelLabel(modelID, variant) {
575
563
  return variant === undefined ? modelID : `${modelID} ${variant}`;
@@ -607,24 +595,24 @@ function rangeWhere(range, column = STEP_TIME) {
607
595
  }
608
596
  return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
609
597
  }
610
- function buildWhere(range, filters, column = STEP_TIME) {
598
+ function buildWhere(range, filters, column = STEP_TIME, prefix = "") {
611
599
  const rangeClause = rangeWhere(range, column);
612
600
  const clauses = rangeClause.where === "" ? [] : [rangeClause.where.slice("WHERE ".length)];
613
601
  const params = [...rangeClause.params];
614
602
  if (filters?.modelID !== undefined && filters.modelID !== "") {
615
- clauses.push("model_id = ?");
603
+ clauses.push(`${prefix}model_id = ?`);
616
604
  params.push(filters.modelID);
617
605
  }
618
606
  if (filters?.modelKey !== undefined && filters.modelKey !== "") {
619
- clauses.push(`${MODEL_KEY_SQL} = ?`);
607
+ clauses.push(`${modelKeySQL(prefix)} = ?`);
620
608
  params.push(filters.modelKey);
621
609
  }
622
610
  if (filters?.provider !== undefined && filters.provider !== "") {
623
- clauses.push("provider_id = ?");
611
+ clauses.push(`${prefix}provider_id = ?`);
624
612
  params.push(filters.provider);
625
613
  }
626
614
  if (filters?.sessionID !== undefined && filters.sessionID !== "") {
627
- clauses.push("session_id = ?");
615
+ clauses.push(`${prefix}session_id = ?`);
628
616
  params.push(filters.sessionID);
629
617
  }
630
618
  return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
@@ -640,7 +628,10 @@ function overview(db, range, filters) {
640
628
  MIN(${STEP_TIME}) AS firstAt,
641
629
  MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
642
630
  COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,
643
- COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
631
+ COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window,
632
+ COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at) THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS decodeProduced,
633
+ COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at)
634
+ THEN streamed_at - COALESCE(first_token_at, created_at) ELSE 0 END), 0) AS decodeWindow
644
635
  FROM steps ${steps.where}`).get(...steps.params);
645
636
  const prompts = rangeWhere(range, "created_at");
646
637
  const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
@@ -651,6 +642,10 @@ function overview(db, range, filters) {
651
642
  }
652
643
  const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
653
644
  const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
645
+ const ttftFilter = steps.where === "" ? "WHERE" : `${steps.where} AND`;
646
+ const ttftRows = db.query(`SELECT MAX(0, first_token_at - created_at) AS ttft
647
+ FROM steps ${ttftFilter} created_at IS NOT NULL AND first_token_at IS NOT NULL`).all(...steps.params);
648
+ const ttft = ttftRows.length === 0 ? undefined : percentile(ttftRows.map((entry) => entry.ttft), 50);
654
649
  const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
655
650
  const other = otherUsage(db, range, filters);
656
651
  return {
@@ -662,7 +657,9 @@ function overview(db, range, filters) {
662
657
  firstAt: row?.firstAt ?? undefined,
663
658
  lastAt: row?.lastAt ?? undefined,
664
659
  cacheHitRatio: cacheHitRatio(usage),
665
- tps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0)
660
+ tps: row === null ? undefined : tokensPerSecond(row.decodeProduced ?? 0, 0, row.decodeWindow ?? 0),
661
+ requestTps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),
662
+ ttft
666
663
  };
667
664
  }
668
665
  function models(db, range, filters) {
@@ -731,7 +728,7 @@ function sessions(db, options) {
731
728
  if (options?.sessionIDs !== undefined && options.sessionIDs.length === 0)
732
729
  return [];
733
730
  const range = options?.range;
734
- const filter = buildWhere(range, options?.filters, "COALESCE(st.created_at, st.recorded_at)");
731
+ const filter = buildWhere(range, options?.filters, "COALESCE(st.created_at, st.recorded_at)", "st.");
735
732
  const limit = options?.limit ?? 20;
736
733
  const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
737
734
  const params = [...filter.params];
@@ -795,8 +792,8 @@ function sessions(db, options) {
795
792
  function childSessionIDs(db, parentID) {
796
793
  return db.query("SELECT session_id FROM sessions WHERE parent_id = ? ORDER BY session_id").all(parentID).map((row) => row.session_id);
797
794
  }
798
- function sessionUsageOf(db, sessionIDs) {
799
- return sessions(db, { sessionIDs, limit: sessionIDs.length });
795
+ function sessionUsageOf(db, sessionIDs, filters) {
796
+ return sessions(db, { sessionIDs, limit: sessionIDs.length, filters });
800
797
  }
801
798
  function turnFinished(finish) {
802
799
  return finish !== null && finish !== "" && finish !== "tool-calls";
@@ -817,7 +814,11 @@ function stepMessage(row) {
817
814
  return {
818
815
  type: "assistant",
819
816
  id: row.message_id,
820
- time: { created: row.created_at ?? row.recorded_at, completed: row.completed_at ?? undefined },
817
+ time: {
818
+ created: row.created_at ?? row.recorded_at,
819
+ firstToken: row.first_token_at ?? undefined,
820
+ completed: row.completed_at ?? undefined
821
+ },
821
822
  model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
822
823
  tokens: {
823
824
  input: row.input_tokens ?? 0,
@@ -848,7 +849,7 @@ function turns(db, options) {
848
849
  }
849
850
  const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
850
851
  input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
851
- created_at, streamed_at, recorded_at, completed_at, finish
852
+ created_at, first_token_at, streamed_at, recorded_at, completed_at, finish
852
853
  FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
853
854
  ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
854
855
  const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
@@ -891,12 +892,22 @@ function turns(db, options) {
891
892
  const variant = last.variant ?? undefined;
892
893
  let produced = 0;
893
894
  let window = 0;
895
+ let decodeProduced = 0;
896
+ let decodeWindow = 0;
894
897
  for (const row of bucket) {
895
- if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
896
- continue;
897
- produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
898
- window += row.streamed_at - row.created_at;
898
+ const tokens = (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
899
+ if (row.created_at !== null && row.streamed_at !== null && row.streamed_at > row.created_at) {
900
+ produced += tokens;
901
+ window += row.streamed_at - row.created_at;
902
+ }
903
+ const start = row.first_token_at ?? row.created_at;
904
+ if (start !== null && row.streamed_at !== null && row.streamed_at > start) {
905
+ decodeProduced += tokens;
906
+ decodeWindow += row.streamed_at - start;
907
+ }
899
908
  }
909
+ const first = bucket[0];
910
+ const ttft = first !== undefined && first.created_at !== null && first.first_token_at !== null ? Math.max(0, first.first_token_at - first.created_at) : undefined;
900
911
  const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
901
912
  const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
902
913
  const firstAt = bucket[0]?.created_at ?? promptAt;
@@ -916,7 +927,9 @@ function turns(db, options) {
916
927
  totals,
917
928
  drops,
918
929
  finish: last.finish ?? undefined,
919
- tps: tokensPerSecond(produced, 0, window)
930
+ tps: tokensPerSecond(decodeProduced, 0, decodeWindow),
931
+ requestTps: tokensPerSecond(produced, 0, window),
932
+ ttft
920
933
  });
921
934
  bucket = [];
922
935
  }
@@ -1093,8 +1106,8 @@ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
1093
1106
  var GRANULARITIES = ["day", "week", "month"];
1094
1107
  var SORT_KEYS = {
1095
1108
  models: ["steps", "cached", "hit", "out", "cost"],
1096
- providers: ["steps", "cached", "hit", "cost", "share", "tps"],
1097
- latency: ["n", "tps", "wall"],
1109
+ providers: ["steps", "cached", "hit", "cost", "share", "tps", "ttft"],
1110
+ latency: ["n", "tps", "ttft", "wall"],
1098
1111
  sessions: ["last", "steps", "cached", "cost"],
1099
1112
  turns: ["time", "cost", "tokens"]
1100
1113
  };
@@ -1192,10 +1205,10 @@ function formatTps(value) {
1192
1205
  return "\u2013";
1193
1206
  return `${value.toFixed(1)}/s`;
1194
1207
  }
1195
- function formatTpsCompact(value) {
1208
+ function formatRateValue(value) {
1196
1209
  if (value === undefined || !Number.isFinite(value) || value < 0)
1197
1210
  return "\u2013";
1198
- return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
1211
+ return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
1199
1212
  }
1200
1213
  function formatGap(value) {
1201
1214
  if (value === undefined || !Number.isFinite(value))
@@ -1369,15 +1382,16 @@ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
1369
1382
  const index = views.indexOf(view);
1370
1383
  return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
1371
1384
  }
1372
- function keysFor(of) {
1385
+ function keysFor(of, range) {
1373
1386
  if (of === QUOTA_VIEW)
1374
1387
  return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
1375
1388
  if (of === "db")
1376
1389
  return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 0 view \xB7 ? help";
1377
1390
  if (of === "periods")
1378
1391
  return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
1379
- if (of === "turns")
1380
- return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
1392
+ if (of === "turns") {
1393
+ return range === "session" ? "\u2191\u2193 move \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help" : "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
1394
+ }
1381
1395
  return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
1382
1396
  }
1383
1397
  function filterSummary(filters) {
@@ -1399,7 +1413,7 @@ function helpLines(width) {
1399
1413
  { text: " t shift+t previous / next range" },
1400
1414
  { text: " s shift+s cycle sort column \xB7 reverse" },
1401
1415
  { text: " b periods bucket: day \u2192 week \u2192 month" },
1402
- { text: " a turns scope: this session \u2194 all sessions" },
1416
+ { text: " a turns scope: this session \u2194 all sessions (time ranges)" },
1403
1417
  { text: " m p filter by model / provider (x clears)" },
1404
1418
  { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
1405
1419
  { text: " e db: backfill list-price estimates for the $0 steps" },
@@ -1426,7 +1440,11 @@ function helpLines(width) {
1426
1440
  { text: " \u2248 list-price estimate for steps the host reported as $0;" },
1427
1441
  { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
1428
1442
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
1429
- { text: " tps out / streaming seconds, shown as p50" },
1443
+ { text: " ttft request \u2192 first streamed token" },
1444
+ { text: " tps output+reasoning / first token \u2192 last chunk (OpenCode)" },
1445
+ { text: " rtps output+reasoning / request \u2192 last chunk (includes TTFT)" },
1446
+ { text: " turn 200 tps \xB7 2.1s ttft \xB7 cost" },
1447
+ { text: " session 200 tps \xB7 167 rtps \xB7 ttft p50 \xB7 cost" },
1430
1448
  { text: " switches how often a step's model or provider differs from the step" },
1431
1449
  { text: " before it in the same session (the models view's detail), with" },
1432
1450
  { text: " the cache a provider switch cost" },
@@ -1555,12 +1573,16 @@ function usagePairs(usage, estimates = true) {
1555
1573
  ];
1556
1574
  if (buckets.reasoning > 0)
1557
1575
  pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
1576
+ if ("tps" in usage && usage.tps !== undefined)
1577
+ pairs.push(["tps", formatTps(usage.tps)]);
1578
+ if ("requestTps" in usage && usage.requestTps !== undefined)
1579
+ pairs.push(["rtps", formatTps(usage.requestTps)]);
1580
+ if ("ttft" in usage && usage.ttft !== undefined)
1581
+ pairs.push(["ttft p50", formatMs(usage.ttft)]);
1558
1582
  pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
1559
1583
  const other = usage.otherCost ?? 0;
1560
1584
  if (other > 0)
1561
1585
  pairs.push(["other", `${formatCost(other)} comp/title`]);
1562
- if ("tps" in usage && usage.tps !== undefined)
1563
- pairs.push(["tps", formatTps(usage.tps)]);
1564
1586
  return pairs;
1565
1587
  }
1566
1588
  function overviewLines(data, width) {
@@ -1613,6 +1635,7 @@ function coveragePairs(coverage) {
1613
1635
  ["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
1614
1636
  ["providers", formatCount(coverage.providers)],
1615
1637
  ["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
1638
+ ["no ttft", share(coverage.missingFirstToken)],
1616
1639
  [
1617
1640
  "window",
1618
1641
  `${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
@@ -1723,7 +1746,8 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
1723
1746
  { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1724
1747
  { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
1725
1748
  { header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
1726
- { header: "wall", width: 7, align: "right", priority: 6, cell: (row) => formatMs(row.wall) },
1749
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 6, cell: (row) => formatMs(row.ttft) },
1750
+ { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
1727
1751
  { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1728
1752
  ], width, {
1729
1753
  limit,
@@ -1743,7 +1767,8 @@ function providerLines(rows, width, limit = 40, estimates = true) {
1743
1767
  { header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
1744
1768
  { header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
1745
1769
  { header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
1746
- { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
1770
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 7, cell: (row) => formatMs(row.ttft) },
1771
+ { header: "wall", width: 7, align: "right", priority: 8, cell: (row) => formatMs(row.wall) },
1747
1772
  { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1748
1773
  ], width, {
1749
1774
  limit,
@@ -1981,7 +2006,15 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
1981
2006
  tone: "base"
1982
2007
  });
1983
2008
  lines.push({
1984
- text: formatTableRow(["throughput", "p50", formatTps(report.tps.p50), "p90", formatTps(report.tps.p90), "p99", formatTps(report.tps.p99)], [10, 4, 9, 4, 9, 4, 9]),
2009
+ text: formatTableRow(["ttft", "p50", formatMs(report.ttft.p50), "p90", formatMs(report.ttft.p90), "p99", formatMs(report.ttft.p99)], [10, 4, 9, 4, 9, 4, 9]),
2010
+ tone: "base"
2011
+ });
2012
+ lines.push({
2013
+ text: formatTableRow(["tps", "p50", formatTps(report.tps.p50), "p90", formatTps(report.tps.p90), "p99", formatTps(report.tps.p99)], [10, 4, 9, 4, 9, 4, 9]),
2014
+ tone: "base"
2015
+ });
2016
+ lines.push({
2017
+ text: formatTableRow(["rtps", "p50", formatTps(report.requestTps.p50), "p90", formatTps(report.requestTps.p90), "p99", formatTps(report.requestTps.p99)], [10, 4, 9, 4, 9, 4, 9]),
1985
2018
  tone: "base"
1986
2019
  });
1987
2020
  } else {
@@ -1994,13 +2027,25 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
1994
2027
  tone: "base"
1995
2028
  });
1996
2029
  lines.push({
1997
- text: latencyMetric("throughput", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
2030
+ text: latencyMetric("ttft", [`p50 ${formatMs(report.ttft.p50)}`, `p90 ${formatMs(report.ttft.p90)}`, `p99 ${formatMs(report.ttft.p99)}`], width),
2031
+ tone: "base"
2032
+ });
2033
+ lines.push({
2034
+ text: latencyMetric("tps", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
2035
+ tone: "base"
2036
+ });
2037
+ lines.push({
2038
+ text: latencyMetric("rtps", [`p50 ${formatTps(report.requestTps.p50)}`, `p90 ${formatTps(report.requestTps.p90)}`, `p99 ${formatTps(report.requestTps.p99)}`], width),
1998
2039
  tone: "base"
1999
2040
  });
2000
2041
  }
2001
2042
  lines.push({ text: "", tone: "muted" });
2002
2043
  lines.push({
2003
- text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
2044
+ text: truncate("wall = request to completed \xB7 stream = request to last chunk", width),
2045
+ tone: "muted"
2046
+ });
2047
+ lines.push({
2048
+ text: truncate("ttft = request to first token \xB7 tps = first token to last chunk \xB7 rtps = request to last chunk", width),
2004
2049
  tone: "muted"
2005
2050
  });
2006
2051
  if (report.wall.count === 0)
@@ -2015,7 +2060,8 @@ function latencyLines(report, width, groups, limit = 12, estimates = true) {
2015
2060
  { header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
2016
2061
  { header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
2017
2062
  { header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
2018
- { header: "tps p90", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatTps(row.tps.p90) },
2063
+ { header: "tps p90", width: 8, max: 9, align: "right", priority: 4, cell: (row) => formatTps(row.tps.p90) },
2064
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatMs(row.ttft.p50) },
2019
2065
  { header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2020
2066
  ], width);
2021
2067
  if (columns.length > 0) {
@@ -2244,7 +2290,9 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
2244
2290
  const cached = formatTokens(buckets.cached);
2245
2291
  const out = formatTokens(buckets.output);
2246
2292
  const hit = formatPercent(buckets.hit);
2247
- const tps = formatTpsCompact(usage.tps);
2293
+ const tps = usage.tps === undefined ? undefined : `${formatRateValue(usage.tps)} tps`;
2294
+ const rtps = usage.requestTps === undefined ? undefined : `${formatRateValue(usage.requestTps)} rtps`;
2295
+ const ttft = usage.ttft === undefined ? undefined : `ttft p50 ${formatMs(usage.ttft)}`;
2248
2296
  const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
2249
2297
  const first = [
2250
2298
  ` ${steps} steps \xB7 in ${input}`,
@@ -2254,16 +2302,22 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
2254
2302
  ` cached ${cached} \xB7 out ${out}`,
2255
2303
  ` cached ${cached}`
2256
2304
  ].find((text) => text.length <= budget);
2257
- const last = [
2258
- ` hit ${hit} \xB7 ${tps} \xB7 ${cost}`,
2259
- ` hit ${hit} \xB7 ${cost}`,
2260
- ` ${cost}`
2305
+ const rates = [tps, rtps].filter((part) => part !== undefined);
2306
+ const rateLine = [
2307
+ ` hit ${hit}${rates.length > 0 ? ` \xB7 ${rates.join(" \xB7 ")}` : ""}`,
2308
+ ` hit ${hit}${rates[0] !== undefined ? ` \xB7 ${rates[0]}` : ""}`,
2309
+ ` hit ${hit}`
2261
2310
  ].find((text) => text.length <= budget);
2311
+ const tail = [
2312
+ ttft === undefined ? undefined : ` ${ttft} \xB7 ${cost}`,
2313
+ ` ${cost}`
2314
+ ].filter((text) => text !== undefined).find((text) => text.length <= budget);
2262
2315
  return [
2263
2316
  { text: truncate("session", budget), tone: HEADER_TONE },
2264
2317
  { text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
2265
2318
  { text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
2266
- { text: truncate(last ?? ` ${cost}`, budget), tone: "base" },
2319
+ { text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: "base" },
2320
+ { text: truncate(tail ?? ` ${cost}`, budget), tone: "base" },
2267
2321
  { text: "", tone: "muted" }
2268
2322
  ];
2269
2323
  }
@@ -2280,20 +2334,28 @@ function sidebarLines(rows, options) {
2280
2334
  const output = formatTokens(display.output);
2281
2335
  const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
2282
2336
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
2283
- const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
2337
+ const tps = turn.tps === undefined ? undefined : `${formatRateValue(turn.tps)} tps`;
2338
+ const ttft = turn.ttft === undefined ? undefined : `${formatMs(turn.ttft)} ttft`;
2339
+ const rate = [tps, ttft].filter((part) => part !== undefined).join(" \xB7 ");
2284
2340
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
2285
2341
  const header = `${clock} ${provider}`;
2286
2342
  const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
2343
+ const join = (...parts) => parts.filter((part) => part !== undefined && part !== "").join(" \xB7 ");
2287
2344
  const volumes = [
2288
- ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
2345
+ ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
2346
+ ` ${labels.input} ${input} \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
2289
2347
  ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
2290
2348
  ` ${labels.input} ${input}`
2291
2349
  ];
2350
+ const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1];
2351
+ const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`;
2292
2352
  const facts = [
2293
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`} \xB7 ${cost}${suffix}`,
2294
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`}${suffix}`,
2295
- ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
2296
- ` hit ${hit}${suffix}`
2353
+ ` ${join(hitPart, rate, `${cost}${suffix}`)}`,
2354
+ ` ${join(hitPart, tps, `${cost}${suffix}`)}`,
2355
+ ` ${join(tps, `${cost}${suffix}`)}`,
2356
+ ` ${join(tps)}`,
2357
+ ` ${join(hitPart, `${cost}${suffix}`)}`,
2358
+ ` ${join(`${cost}${suffix}`)}`
2297
2359
  ];
2298
2360
  lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
2299
2361
  const edge = index === 0 || index === rows.length - 1;
@@ -2301,10 +2363,7 @@ function sidebarLines(rows, options) {
2301
2363
  const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
2302
2364
  lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
2303
2365
  }
2304
- lines.push({
2305
- text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
2306
- tone: "muted"
2307
- });
2366
+ lines.push({ text: truncate(volume, budget), tone: "muted" });
2308
2367
  lines.push({
2309
2368
  text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
2310
2369
  tone: turn.drops.length > 0 ? "warning" : "muted"
@@ -2327,6 +2386,21 @@ import { createElement as _$createElement } from "@opentui/solid";
2327
2386
  import { TextAttributes } from "@opentui/core";
2328
2387
  import { For, Show, createEffect, createMemo, createRenderEffect, createSignal } from "solid-js";
2329
2388
 
2389
+ // src/limits.ts
2390
+ var MAX_PANEL_WIDTH = 200;
2391
+ var MAX_HISTORY_WIDTH = 120;
2392
+ var MAX_TURNS = 50;
2393
+ function clampPanelWidth(value) {
2394
+ if (!Number.isFinite(value))
2395
+ return 20;
2396
+ return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
2397
+ }
2398
+ function clampTurnsLimit(value) {
2399
+ if (!Number.isFinite(value))
2400
+ return 1;
2401
+ return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
2402
+ }
2403
+
2330
2404
  // src/rpc.ts
2331
2405
  import { Rpc } from "@opencode/plugin/rpc";
2332
2406
  var Tone = { type: "string", enum: ["base", "muted", "warning", "accent"] };
@@ -2410,10 +2484,10 @@ var PruneResultSchema = {
2410
2484
  properties: {
2411
2485
  steps: { type: "number" },
2412
2486
  prompts: { type: "number" },
2413
- events: { type: "number" },
2487
+ compactions: { type: "number" },
2414
2488
  usage: { type: "number" }
2415
2489
  },
2416
- required: ["steps", "prompts", "events", "usage"],
2490
+ required: ["steps", "prompts", "compactions", "usage"],
2417
2491
  additionalProperties: false
2418
2492
  };
2419
2493
  var WipeResultSchema = {
@@ -2421,11 +2495,11 @@ var WipeResultSchema = {
2421
2495
  properties: {
2422
2496
  steps: { type: "number" },
2423
2497
  prompts: { type: "number" },
2424
- events: { type: "number" },
2498
+ compactions: { type: "number" },
2425
2499
  usage: { type: "number" },
2426
2500
  sessions: { type: "number" }
2427
2501
  },
2428
- required: ["steps", "prompts", "events", "usage", "sessions"],
2502
+ required: ["steps", "prompts", "compactions", "usage", "sessions"],
2429
2503
  additionalProperties: false
2430
2504
  };
2431
2505
  var BackfillResultSchema = {
@@ -2825,7 +2899,7 @@ function Panel(props) {
2825
2899
  confirm: true
2826
2900
  });
2827
2901
  props.ctx.ui.toast.show({
2828
- message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
2902
+ message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.compactions} compactions \xB7 ${result.usage} other usage`,
2829
2903
  variant: "success"
2830
2904
  });
2831
2905
  } catch (cause) {
@@ -2871,7 +2945,7 @@ function Panel(props) {
2871
2945
  confirm: true
2872
2946
  });
2873
2947
  props.ctx.ui.toast.show({
2874
- message: `wiped ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage \xB7 ${result.sessions} sessions`,
2948
+ message: `wiped ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.compactions} compactions \xB7 ${result.usage} other usage \xB7 ${result.sessions} sessions`,
2875
2949
  variant: "success"
2876
2950
  });
2877
2951
  } catch (cause) {
@@ -3059,8 +3133,11 @@ function Panel(props) {
3059
3133
  draft.granularity = nextIn(GRANULARITIES, sanitizeSettings(draft).granularity, 1);
3060
3134
  draft.view = "periods";
3061
3135
  })), command("usage-insights.scope", "Toggle the turns scope", "a", () => props.update((draft) => {
3062
- draft.turnsScope = sanitizeSettings(draft).turnsScope === "session" ? "all" : "session";
3136
+ const state = sanitizeSettings(draft);
3063
3137
  draft.view = "turns";
3138
+ if (state.range === "session")
3139
+ return;
3140
+ draft.turnsScope = state.turnsScope === "session" ? "all" : "session";
3064
3141
  })), command("usage-insights.filter.model", "Filter by model", "m", () => void pickFilter("model")), command("usage-insights.filter.provider", "Filter by provider", "p", () => void pickFilter("provider")), command("usage-insights.filter.clear", "Clear filters", "x", () => {
3065
3142
  props.update((draft) => {
3066
3143
  draft.modelID = "";
@@ -3163,7 +3240,7 @@ function Panel(props) {
3163
3240
  return _el$3;
3164
3241
  }
3165
3242
  }), _el$5);
3166
- _$insert(_el$6, () => keysFor(view()));
3243
+ _$insert(_el$6, () => keysFor(view(), settings().range));
3167
3244
  _$effect((_p$) => {
3168
3245
  var _v$ = props.ctx.theme.text.muted, _v$2 = props.ctx.theme.text.muted;
3169
3246
  _v$ !== _p$.e && (_p$.e = _$setProp(_el$5, "fg", _v$, _p$.e));
@@ -3320,6 +3397,383 @@ async function fetchGoQuota(client, location, signal) {
3320
3397
  return normalizeQuota(data, Date.now());
3321
3398
  }
3322
3399
 
3400
+ // src/settings-rpc.ts
3401
+ import { Rpc as Rpc2 } from "@opencode/plugin/rpc";
3402
+
3403
+ // src/settings.ts
3404
+ var SETTINGS_STORAGE_KEY = "settings";
3405
+ var MAX_LABEL_LENGTH = 80;
3406
+ var MAX_QUOTA_NAME_LENGTH = 120;
3407
+ var DEFAULT_SIDEBAR_TURNS = 8;
3408
+ var TURN_TOTALS = ["latest", "sum"];
3409
+ var FIELD_KEYS = Object.keys(DEFAULT_FIELDS);
3410
+ var LABEL_KEYS = Object.keys(DEFAULT_LABELS);
3411
+ var DEFAULT_SERVER_POLICY = {
3412
+ maintenance: true,
3413
+ exposePaths: false
3414
+ };
3415
+ var DEFAULT_USAGE_SETTINGS = {
3416
+ pricing: true,
3417
+ turnTotals: "latest",
3418
+ fields: { ...DEFAULT_FIELDS },
3419
+ labels: { ...DEFAULT_LABELS },
3420
+ panel: true,
3421
+ sidebar: true,
3422
+ sidebarTurns: DEFAULT_SIDEBAR_TURNS,
3423
+ quota: true,
3424
+ quotaName: ""
3425
+ };
3426
+ function defaultUsageSettings() {
3427
+ return {
3428
+ ...DEFAULT_USAGE_SETTINGS,
3429
+ fields: { ...DEFAULT_USAGE_SETTINGS.fields },
3430
+ labels: { ...DEFAULT_USAGE_SETTINGS.labels }
3431
+ };
3432
+ }
3433
+ function defaultSettingsEnvelope(policy = DEFAULT_SERVER_POLICY) {
3434
+ return { settings: defaultUsageSettings(), policy: { ...policy } };
3435
+ }
3436
+ function isRecord(value) {
3437
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3438
+ }
3439
+ function sanitizeSidebarTurns(value) {
3440
+ if (typeof value === "number" && Number.isFinite(value))
3441
+ return clampTurnsLimit(value);
3442
+ if (typeof value === "string" && value.trim() !== "") {
3443
+ const parsed = Number(value);
3444
+ if (Number.isFinite(parsed))
3445
+ return clampTurnsLimit(parsed);
3446
+ }
3447
+ return DEFAULT_SIDEBAR_TURNS;
3448
+ }
3449
+ function sanitizeLabels(value) {
3450
+ const labels = { ...DEFAULT_LABELS };
3451
+ if (!isRecord(value))
3452
+ return labels;
3453
+ for (const key of LABEL_KEYS) {
3454
+ const entry = value[key];
3455
+ if (typeof entry === "string")
3456
+ labels[key] = sanitizeText(entry, MAX_LABEL_LENGTH);
3457
+ }
3458
+ return labels;
3459
+ }
3460
+ function sanitizeFields(value) {
3461
+ const fields = { ...DEFAULT_FIELDS };
3462
+ if (!isRecord(value))
3463
+ return fields;
3464
+ for (const key of FIELD_KEYS) {
3465
+ const entry = value[key];
3466
+ if (typeof entry === "boolean")
3467
+ fields[key] = entry;
3468
+ }
3469
+ return fields;
3470
+ }
3471
+ function sanitizeUsageSettings(value) {
3472
+ if (!isRecord(value))
3473
+ return defaultUsageSettings();
3474
+ return {
3475
+ pricing: typeof value.pricing === "boolean" ? value.pricing : DEFAULT_USAGE_SETTINGS.pricing,
3476
+ turnTotals: TURN_TOTALS.includes(value.turnTotals) ? value.turnTotals : DEFAULT_USAGE_SETTINGS.turnTotals,
3477
+ fields: sanitizeFields(value.fields),
3478
+ labels: sanitizeLabels(value.labels),
3479
+ panel: typeof value.panel === "boolean" ? value.panel : DEFAULT_USAGE_SETTINGS.panel,
3480
+ sidebar: typeof value.sidebar === "boolean" ? value.sidebar : DEFAULT_USAGE_SETTINGS.sidebar,
3481
+ sidebarTurns: sanitizeSidebarTurns(value.sidebarTurns),
3482
+ quota: typeof value.quota === "boolean" ? value.quota : DEFAULT_USAGE_SETTINGS.quota,
3483
+ quotaName: typeof value.quotaName === "string" ? sanitizeText(value.quotaName.trim(), MAX_QUOTA_NAME_LENGTH) : DEFAULT_USAGE_SETTINGS.quotaName
3484
+ };
3485
+ }
3486
+ function sanitizeServerPolicy(value) {
3487
+ if (!isRecord(value))
3488
+ return { ...DEFAULT_SERVER_POLICY };
3489
+ return {
3490
+ maintenance: typeof value.maintenance === "boolean" ? value.maintenance : DEFAULT_SERVER_POLICY.maintenance,
3491
+ exposePaths: typeof value.exposePaths === "boolean" ? value.exposePaths : DEFAULT_SERVER_POLICY.exposePaths
3492
+ };
3493
+ }
3494
+ function sanitizeSettingsEnvelope(value) {
3495
+ return {
3496
+ settings: sanitizeUsageSettings(isRecord(value) ? value.settings : undefined),
3497
+ policy: sanitizeServerPolicy(isRecord(value) ? value.policy : undefined)
3498
+ };
3499
+ }
3500
+ function mergeUsageSettings(current, patch) {
3501
+ const next = {
3502
+ ...current,
3503
+ ...typeof patch.pricing === "boolean" ? { pricing: patch.pricing } : {},
3504
+ ...TURN_TOTALS.includes(patch.turnTotals) ? { turnTotals: patch.turnTotals } : {},
3505
+ ...isRecord(patch.fields) ? { fields: { ...current.fields, ...patch.fields } } : {},
3506
+ ...isRecord(patch.labels) ? { labels: { ...current.labels, ...patch.labels } } : {},
3507
+ ...typeof patch.panel === "boolean" ? { panel: patch.panel } : {},
3508
+ ...typeof patch.sidebar === "boolean" ? { sidebar: patch.sidebar } : {},
3509
+ ...patch.sidebarTurns !== undefined ? { sidebarTurns: patch.sidebarTurns } : {},
3510
+ ...typeof patch.quota === "boolean" ? { quota: patch.quota } : {},
3511
+ ...typeof patch.quotaName === "string" ? { quotaName: patch.quotaName } : {}
3512
+ };
3513
+ return sanitizeUsageSettings(next);
3514
+ }
3515
+ function resolveUsageSettings(settings) {
3516
+ return {
3517
+ format: {
3518
+ labels: settings.labels,
3519
+ fields: settings.fields,
3520
+ turnTotals: settings.turnTotals,
3521
+ estimates: settings.pricing
3522
+ },
3523
+ sidebarTurns: clampTurnsLimit(settings.sidebarTurns),
3524
+ quotaName: settings.quotaName.trim() || undefined
3525
+ };
3526
+ }
3527
+ function isValidSidebarTurns(raw) {
3528
+ const value = Number(raw);
3529
+ return raw.trim() !== "" && Number.isInteger(value) && value >= 1 && value <= 50;
3530
+ }
3531
+ function parseSidebarTurns(raw) {
3532
+ if (!isValidSidebarTurns(raw))
3533
+ return;
3534
+ return clampTurnsLimit(Number(raw));
3535
+ }
3536
+ var TRUE_VALUES = new Set(["1", "true", "on", "yes", "y"]);
3537
+ var FALSE_VALUES = new Set(["0", "false", "off", "no", "n"]);
3538
+ function envFlag(value, fallback) {
3539
+ if (value === undefined || value.trim() === "")
3540
+ return fallback;
3541
+ const normalized = value.trim().toLowerCase();
3542
+ if (TRUE_VALUES.has(normalized))
3543
+ return true;
3544
+ if (FALSE_VALUES.has(normalized))
3545
+ return false;
3546
+ return fallback;
3547
+ }
3548
+ function serverPolicy(env = process.env) {
3549
+ return {
3550
+ maintenance: envFlag(env.OPENCODE_USAGE_INSIGHTS_MAINTENANCE, true),
3551
+ exposePaths: envFlag(env.OPENCODE_USAGE_INSIGHTS_EXPOSE_PATHS, false)
3552
+ };
3553
+ }
3554
+
3555
+ // src/settings-rpc.ts
3556
+ var LineFields = {
3557
+ type: "object",
3558
+ properties: {
3559
+ clock: { type: "boolean" },
3560
+ delta: { type: "boolean" },
3561
+ model: { type: "boolean" },
3562
+ variant: { type: "boolean" },
3563
+ turn: { type: "boolean" },
3564
+ session: { type: "boolean" },
3565
+ reasoning: { type: "boolean" },
3566
+ cost: { type: "boolean" },
3567
+ cacheExpiry: { type: "boolean" }
3568
+ },
3569
+ additionalProperties: false
3570
+ };
3571
+ var LineLabels = {
3572
+ type: "object",
3573
+ properties: {
3574
+ delta: { type: "string", maxLength: MAX_LABEL_LENGTH },
3575
+ turn: { type: "string", maxLength: MAX_LABEL_LENGTH },
3576
+ session: { type: "string", maxLength: MAX_LABEL_LENGTH },
3577
+ step: { type: "string", maxLength: MAX_LABEL_LENGTH },
3578
+ steps: { type: "string", maxLength: MAX_LABEL_LENGTH },
3579
+ input: { type: "string", maxLength: MAX_LABEL_LENGTH },
3580
+ cached: { type: "string", maxLength: MAX_LABEL_LENGTH },
3581
+ output: { type: "string", maxLength: MAX_LABEL_LENGTH },
3582
+ reasoning: { type: "string", maxLength: MAX_LABEL_LENGTH },
3583
+ cost: { type: "string", maxLength: MAX_LABEL_LENGTH },
3584
+ estimate: { type: "string", maxLength: MAX_LABEL_LENGTH },
3585
+ cacheExpired: { type: "string", maxLength: MAX_LABEL_LENGTH },
3586
+ providerChanged: { type: "string", maxLength: MAX_LABEL_LENGTH },
3587
+ modelChanged: { type: "string", maxLength: MAX_LABEL_LENGTH }
3588
+ },
3589
+ additionalProperties: false
3590
+ };
3591
+ var Settings = {
3592
+ type: "object",
3593
+ properties: {
3594
+ pricing: { type: "boolean" },
3595
+ turnTotals: { type: "string", enum: ["latest", "sum"] },
3596
+ fields: LineFields,
3597
+ labels: LineLabels,
3598
+ panel: { type: "boolean" },
3599
+ sidebar: { type: "boolean" },
3600
+ sidebarTurns: { type: "number", minimum: 1, maximum: 50 },
3601
+ quota: { type: "boolean" },
3602
+ quotaName: { type: "string", maxLength: MAX_QUOTA_NAME_LENGTH }
3603
+ },
3604
+ required: ["pricing", "turnTotals", "fields", "labels", "panel", "sidebar", "sidebarTurns", "quota", "quotaName"],
3605
+ additionalProperties: false
3606
+ };
3607
+ var Patch = {
3608
+ type: "object",
3609
+ properties: {
3610
+ pricing: { type: "boolean" },
3611
+ turnTotals: { type: "string", enum: ["latest", "sum"] },
3612
+ fields: LineFields,
3613
+ labels: LineLabels,
3614
+ panel: { type: "boolean" },
3615
+ sidebar: { type: "boolean" },
3616
+ sidebarTurns: { type: "number", minimum: 1, maximum: 50 },
3617
+ quota: { type: "boolean" },
3618
+ quotaName: { type: "string", maxLength: MAX_QUOTA_NAME_LENGTH }
3619
+ },
3620
+ additionalProperties: false
3621
+ };
3622
+ var Policy = {
3623
+ type: "object",
3624
+ properties: {
3625
+ maintenance: { type: "boolean" },
3626
+ exposePaths: { type: "boolean" }
3627
+ },
3628
+ required: ["maintenance", "exposePaths"],
3629
+ additionalProperties: false
3630
+ };
3631
+ var Envelope = {
3632
+ type: "object",
3633
+ properties: {
3634
+ settings: Settings,
3635
+ policy: Policy
3636
+ },
3637
+ required: ["settings", "policy"],
3638
+ additionalProperties: false
3639
+ };
3640
+ var Empty = { type: "object", properties: {}, additionalProperties: false };
3641
+ var SetInput = {
3642
+ type: "object",
3643
+ properties: { patch: Patch },
3644
+ required: ["patch"],
3645
+ additionalProperties: false
3646
+ };
3647
+ var UsageInsightsSettings = Rpc2.define({
3648
+ id: "usage-insights.settings",
3649
+ methods: {
3650
+ get: { input: Empty, output: Envelope },
3651
+ set: { input: SetInput, output: Envelope },
3652
+ reset: { input: Empty, output: Envelope }
3653
+ },
3654
+ events: {
3655
+ updated: { schema: Envelope }
3656
+ }
3657
+ });
3658
+
3659
+ // src/settings-client.ts
3660
+ function settingsError(cause) {
3661
+ return cause instanceof Error ? cause.message : String(cause);
3662
+ }
3663
+ function createSettingsSync(options) {
3664
+ let stopEvents;
3665
+ let stopped = false;
3666
+ function rpc() {
3667
+ const client = options.client();
3668
+ if (typeof client.rpc !== "function")
3669
+ return;
3670
+ try {
3671
+ return client.rpc(UsageInsightsSettings);
3672
+ } catch {
3673
+ return;
3674
+ }
3675
+ }
3676
+ async function refresh(force = false) {
3677
+ const client = rpc();
3678
+ if (!client) {
3679
+ if (!stopped)
3680
+ options.onLoadError?.("the settings service is unavailable");
3681
+ return;
3682
+ }
3683
+ try {
3684
+ const next = sanitizeSettingsEnvelope(await client.get({}));
3685
+ if (stopped)
3686
+ return;
3687
+ if (!force && options.canApply && !options.canApply(next))
3688
+ return;
3689
+ options.set(next);
3690
+ } catch (cause) {
3691
+ if (!stopped)
3692
+ options.onLoadError?.(settingsError(cause));
3693
+ }
3694
+ }
3695
+ function connect() {
3696
+ stopped = false;
3697
+ stopEvents?.();
3698
+ stopEvents = undefined;
3699
+ const client = rpc();
3700
+ if (client) {
3701
+ try {
3702
+ stopEvents = client.events.on("updated", (event) => {
3703
+ if (stopped)
3704
+ return;
3705
+ try {
3706
+ const next = sanitizeSettingsEnvelope(event.data);
3707
+ if (options.acceptEvent) {
3708
+ if (!options.acceptEvent(next))
3709
+ return;
3710
+ } else if (options.canApply && !options.canApply(next)) {
3711
+ return;
3712
+ }
3713
+ if (!stopped)
3714
+ options.set(next);
3715
+ } catch (cause) {
3716
+ if (!stopped)
3717
+ options.onLoadError?.(settingsError(cause));
3718
+ }
3719
+ });
3720
+ } catch (cause) {
3721
+ options.onLoadError?.(settingsError(cause));
3722
+ }
3723
+ }
3724
+ refresh();
3725
+ }
3726
+ async function update(patch) {
3727
+ if (stopped)
3728
+ return;
3729
+ const client = rpc();
3730
+ if (!client) {
3731
+ options.onSaveError?.("the settings service is unavailable");
3732
+ return;
3733
+ }
3734
+ try {
3735
+ const saved = sanitizeSettingsEnvelope(await client.set({ patch }));
3736
+ if (!stopped)
3737
+ options.set(saved);
3738
+ } catch (cause) {
3739
+ if (stopped)
3740
+ return;
3741
+ options.onSaveError?.(settingsError(cause));
3742
+ await refresh(true);
3743
+ }
3744
+ }
3745
+ async function reset() {
3746
+ if (stopped)
3747
+ return;
3748
+ const client = rpc();
3749
+ if (!client) {
3750
+ options.onSaveError?.("the settings service is unavailable");
3751
+ return;
3752
+ }
3753
+ try {
3754
+ const saved = sanitizeSettingsEnvelope(await client.reset({}));
3755
+ if (!stopped)
3756
+ options.set(saved);
3757
+ } catch (cause) {
3758
+ if (stopped)
3759
+ return;
3760
+ options.onSaveError?.(settingsError(cause));
3761
+ await refresh(true);
3762
+ }
3763
+ }
3764
+ return {
3765
+ connect,
3766
+ refresh,
3767
+ update,
3768
+ reset,
3769
+ stop: () => {
3770
+ stopped = true;
3771
+ stopEvents?.();
3772
+ stopEvents = undefined;
3773
+ }
3774
+ };
3775
+ }
3776
+
3323
3777
  // src/sidebar.tsx
3324
3778
  import { insert as _$insert2 } from "@opentui/solid";
3325
3779
  import { effect as _$effect2 } from "@opentui/solid";
@@ -3351,7 +3805,7 @@ function TurnsSidebar(props) {
3351
3805
  props.deps.refresh();
3352
3806
  const input = {
3353
3807
  sessionID: props.sessionID,
3354
- limit: props.deps.limit,
3808
+ limit: props.deps.limit(),
3355
3809
  width: props.deps.budget ?? 34
3356
3810
  };
3357
3811
  const current = ++generation;
@@ -3423,6 +3877,294 @@ function TurnsSidebar(props) {
3423
3877
  })();
3424
3878
  }
3425
3879
 
3880
+ // src/tui-settings.ts
3881
+ var FIELD_TITLES = {
3882
+ clock: "Clock",
3883
+ delta: "Time since previous prompt",
3884
+ model: "Provider and model",
3885
+ variant: "Model variant",
3886
+ turn: "Turn label prefix",
3887
+ session: "Session totals",
3888
+ reasoning: "Reasoning tokens",
3889
+ cost: "Cost",
3890
+ cacheExpiry: "Cache expiry warning"
3891
+ };
3892
+ var LABEL_TITLES = {
3893
+ delta: "Time since previous prompt",
3894
+ turn: "Turn prefix",
3895
+ session: "Session prefix",
3896
+ step: "Single step",
3897
+ steps: "Several steps",
3898
+ input: "Uncached input",
3899
+ cached: "Cached input",
3900
+ output: "Output",
3901
+ reasoning: "Reasoning",
3902
+ cost: "Cost",
3903
+ estimate: "Estimate marker",
3904
+ cacheExpired: "Cache expired warning",
3905
+ providerChanged: "Provider changed warning",
3906
+ modelChanged: "Model changed warning"
3907
+ };
3908
+ function onOff(value) {
3909
+ return value ? "on" : "off";
3910
+ }
3911
+ function fieldsSummary(settings) {
3912
+ const enabled = Object.keys(DEFAULT_FIELDS).filter((key) => settings.fields[key]).length;
3913
+ return `${enabled}/${Object.keys(DEFAULT_FIELDS).length} on`;
3914
+ }
3915
+ function labelsSummary(settings) {
3916
+ const custom = Object.keys(DEFAULT_LABELS).filter((key) => {
3917
+ const name = key;
3918
+ return settings.labels[name] !== DEFAULT_LABELS[name];
3919
+ }).length;
3920
+ return custom === 0 ? "defaults" : `${custom} custom`;
3921
+ }
3922
+ async function openUsageInsightsSettings(ctx, state) {
3923
+ for (;; ) {
3924
+ const current = state.settings();
3925
+ const error = state.error();
3926
+ const choice = await ctx.ui.dialog.select({
3927
+ title: "Usage insights settings",
3928
+ placeholder: "Filter settings",
3929
+ options: [
3930
+ ...error === undefined ? [] : [
3931
+ {
3932
+ title: "Settings service unavailable",
3933
+ value: "done",
3934
+ description: error,
3935
+ category: "Connection",
3936
+ disabled: true
3937
+ },
3938
+ {
3939
+ title: "Retry connection",
3940
+ value: "retry",
3941
+ description: "Reload the shared settings",
3942
+ category: "Connection"
3943
+ }
3944
+ ],
3945
+ {
3946
+ title: "List-price estimates",
3947
+ value: "pricing",
3948
+ description: onOff(current.pricing),
3949
+ category: "Recording"
3950
+ },
3951
+ {
3952
+ title: "Turn totals",
3953
+ value: "turnTotals",
3954
+ description: current.turnTotals === "sum" ? "sum every step" : "latest step",
3955
+ category: "Line"
3956
+ },
3957
+ {
3958
+ title: "Fields",
3959
+ value: "fields",
3960
+ description: fieldsSummary(current),
3961
+ category: "Line"
3962
+ },
3963
+ {
3964
+ title: "Labels",
3965
+ value: "labels",
3966
+ description: labelsSummary(current),
3967
+ category: "Line"
3968
+ },
3969
+ {
3970
+ title: "Panel",
3971
+ value: "panel",
3972
+ description: onOff(current.panel),
3973
+ category: "Surfaces"
3974
+ },
3975
+ {
3976
+ title: "Sidebar history",
3977
+ value: "sidebar",
3978
+ description: onOff(current.sidebar),
3979
+ category: "Surfaces"
3980
+ },
3981
+ {
3982
+ title: "Sidebar turns",
3983
+ value: "sidebarTurns",
3984
+ description: String(current.sidebarTurns),
3985
+ category: "Surfaces"
3986
+ },
3987
+ {
3988
+ title: "OpenCode Go allowance",
3989
+ value: "quota",
3990
+ description: onOff(current.quota),
3991
+ category: "Allowance"
3992
+ },
3993
+ {
3994
+ title: "Allowance label",
3995
+ value: "quotaName",
3996
+ description: current.quotaName || "provider default",
3997
+ category: "Allowance"
3998
+ },
3999
+ {
4000
+ title: "Server maintenance",
4001
+ value: "done",
4002
+ description: state.policy().maintenance ? "allowed" : "disabled by the server policy",
4003
+ category: "Server policy",
4004
+ disabled: true
4005
+ },
4006
+ {
4007
+ title: "Expose database paths",
4008
+ value: "done",
4009
+ description: state.policy().exposePaths ? "yes" : "no",
4010
+ category: "Server policy",
4011
+ disabled: true
4012
+ },
4013
+ {
4014
+ title: "Database path",
4015
+ value: "done",
4016
+ description: "OPENCODE_USAGE_INSIGHTS_DB",
4017
+ category: "Server policy",
4018
+ disabled: true
4019
+ },
4020
+ {
4021
+ title: "Reset to defaults",
4022
+ value: "reset",
4023
+ description: "Restore every shared setting",
4024
+ category: "Reset"
4025
+ },
4026
+ { title: "Done", value: "done", category: "Actions" }
4027
+ ]
4028
+ });
4029
+ if (choice === undefined || choice === "done")
4030
+ return;
4031
+ switch (choice) {
4032
+ case "pricing":
4033
+ await state.update({ pricing: !current.pricing });
4034
+ break;
4035
+ case "turnTotals":
4036
+ await editTurnTotals(ctx, state, current);
4037
+ break;
4038
+ case "fields":
4039
+ await editFields(ctx, state, current);
4040
+ break;
4041
+ case "labels":
4042
+ await editLabels(ctx, state, current);
4043
+ break;
4044
+ case "panel":
4045
+ await state.update({ panel: !current.panel });
4046
+ break;
4047
+ case "sidebar":
4048
+ await state.update({ sidebar: !current.sidebar });
4049
+ break;
4050
+ case "sidebarTurns":
4051
+ await editSidebarTurns(ctx, state, current);
4052
+ break;
4053
+ case "quota":
4054
+ await state.update({ quota: !current.quota });
4055
+ break;
4056
+ case "quotaName":
4057
+ await editQuotaName(ctx, state, current);
4058
+ break;
4059
+ case "retry":
4060
+ await state.refresh();
4061
+ break;
4062
+ case "reset":
4063
+ await reset(ctx, state);
4064
+ break;
4065
+ }
4066
+ }
4067
+ }
4068
+ async function editTurnTotals(ctx, state, current) {
4069
+ const value = await ctx.ui.dialog.select({
4070
+ title: "Turn totals",
4071
+ current: current.turnTotals,
4072
+ options: [
4073
+ {
4074
+ title: "Latest step",
4075
+ value: "latest",
4076
+ description: "The prompt size the turn ended with",
4077
+ category: "Current"
4078
+ },
4079
+ {
4080
+ title: "Sum every step",
4081
+ value: "sum",
4082
+ description: "Add the prompt of each step in the turn",
4083
+ category: "Current"
4084
+ }
4085
+ ]
4086
+ });
4087
+ if (value === undefined)
4088
+ return;
4089
+ await state.update({ turnTotals: value });
4090
+ }
4091
+ async function editFields(ctx, state, current) {
4092
+ const key = await ctx.ui.dialog.select({
4093
+ title: "Line fields",
4094
+ current: undefined,
4095
+ options: Object.keys(DEFAULT_FIELDS).map((name) => ({
4096
+ title: FIELD_TITLES[name],
4097
+ value: name,
4098
+ description: onOff(current.fields[name]),
4099
+ category: "Current"
4100
+ }))
4101
+ });
4102
+ if (key === undefined)
4103
+ return;
4104
+ await state.update({ fields: { [key]: !current.fields[key] } });
4105
+ }
4106
+ async function editLabels(ctx, state, current) {
4107
+ const key = await ctx.ui.dialog.select({
4108
+ title: "Line labels",
4109
+ placeholder: "Filter labels",
4110
+ current: undefined,
4111
+ options: Object.keys(DEFAULT_LABELS).map((name) => ({
4112
+ title: LABEL_TITLES[name],
4113
+ value: name,
4114
+ description: current.labels[name] || "(empty)",
4115
+ category: "Current"
4116
+ }))
4117
+ });
4118
+ if (key === undefined)
4119
+ return;
4120
+ const value = await ctx.ui.dialog.prompt({
4121
+ title: LABEL_TITLES[key],
4122
+ description: "Text shown on the line. Leave it empty to hide the label.",
4123
+ value: current.labels[key]
4124
+ });
4125
+ if (value === undefined)
4126
+ return;
4127
+ await state.update({ labels: { [key]: sanitizeText(value, MAX_LABEL_LENGTH) } });
4128
+ }
4129
+ async function editSidebarTurns(ctx, state, current) {
4130
+ const value = await ctx.ui.dialog.prompt({
4131
+ title: "Sidebar turns",
4132
+ description: "How many turns the TUI sidebar and the Desktop Turns tab show (1-50).",
4133
+ value: String(current.sidebarTurns)
4134
+ });
4135
+ if (value === undefined)
4136
+ return;
4137
+ const turns = parseSidebarTurns(value);
4138
+ if (turns === undefined) {
4139
+ await ctx.ui.dialog.alert({
4140
+ title: "Invalid number of turns",
4141
+ message: "Use a whole number from 1 to 50. No change was saved."
4142
+ });
4143
+ return;
4144
+ }
4145
+ await state.update({ sidebarTurns: turns });
4146
+ }
4147
+ async function editQuotaName(ctx, state, current) {
4148
+ const value = await ctx.ui.dialog.prompt({
4149
+ title: "Allowance label",
4150
+ description: "Shown above the Go meters. Leave it empty for the provider name or OpenCode Go.",
4151
+ value: current.quotaName
4152
+ });
4153
+ if (value === undefined)
4154
+ return;
4155
+ await state.update({ quotaName: sanitizeText(value.trim(), MAX_QUOTA_NAME_LENGTH) });
4156
+ }
4157
+ async function reset(ctx, state) {
4158
+ const current = state.policy();
4159
+ const confirmed = await ctx.ui.dialog.confirm({
4160
+ title: "Reset Usage insights settings",
4161
+ message: `Restore the built-in line, panel and allowance settings${current.maintenance ? "" : " (server maintenance is disabled)"}?`,
4162
+ label: { confirm: "Reset", cancel: "Cancel" }
4163
+ });
4164
+ if (confirmed)
4165
+ await state.reset();
4166
+ }
4167
+
3426
4168
  // src/tui.tsx
3427
4169
  var REFRESH_THROTTLE_MS = 300;
3428
4170
  var __test = {
@@ -3434,14 +4176,81 @@ var __test = {
3434
4176
  var tui_default = Plugin.define({
3435
4177
  id: "usage-insights",
3436
4178
  setup(ctx) {
3437
- const options = ctx.options ?? {};
3438
- if (options.enabled === false)
3439
- return;
3440
- const panelEnabled = options.panel !== false;
3441
- const pricing = options.pricing !== "off";
3442
- const quotaEnabled = options.quota !== "off";
3443
- const quotaActive = quotaEnabled && (options.sidebar !== false || panelEnabled);
3444
- const views = quotaEnabled ? CLIENT_VIEWS : PANEL_VIEWS;
4179
+ const [usageSettings, setUsageSettings] = createSignal3(defaultUsageSettings());
4180
+ const [policy, setPolicy] = createSignal3(defaultSettingsEnvelope().policy);
4181
+ const [settingsError, setSettingsError] = createSignal3(undefined);
4182
+ const [settingsLoaded, setSettingsLoaded] = createSignal3(false);
4183
+ let firstSettings = true;
4184
+ let saving = false;
4185
+ const envelope = () => ({
4186
+ settings: usageSettings(),
4187
+ policy: policy()
4188
+ });
4189
+ const sync = createSettingsSync({
4190
+ client: () => ctx.client,
4191
+ set: (next) => {
4192
+ setUsageSettings(next.settings);
4193
+ setPolicy(next.policy);
4194
+ setSettingsError(undefined);
4195
+ setSettingsLoaded(true);
4196
+ if (!firstSettings)
4197
+ bumpRefresh();
4198
+ firstSettings = false;
4199
+ },
4200
+ canApply: () => !saving,
4201
+ acceptEvent: (next) => {
4202
+ if (saving)
4203
+ return false;
4204
+ return JSON.stringify(next) !== JSON.stringify(envelope());
4205
+ },
4206
+ onLoadError: (message) => {
4207
+ setSettingsError(message);
4208
+ setSettingsLoaded(true);
4209
+ firstSettings = false;
4210
+ },
4211
+ onSaveError: (message) => {
4212
+ setSettingsError(message);
4213
+ ctx.ui.toast.show({
4214
+ message: `Usage insights settings: ${message}`,
4215
+ variant: "error"
4216
+ });
4217
+ }
4218
+ });
4219
+ sync.connect();
4220
+ const panelEnabled = () => usageSettings().panel;
4221
+ const pricing = () => usageSettings().pricing;
4222
+ const quotaEnabled = () => usageSettings().quota;
4223
+ const quotaActive = () => settingsLoaded() && quotaEnabled() && (usageSettings().sidebar || panelEnabled());
4224
+ const views = createMemo3(() => quotaEnabled() ? CLIENT_VIEWS : PANEL_VIEWS);
4225
+ const resolved = createMemo3(() => resolveUsageSettings(usageSettings()));
4226
+ async function saveSettings(patch) {
4227
+ setUsageSettings((current) => mergeUsageSettings(current, patch));
4228
+ saving = true;
4229
+ try {
4230
+ await sync.update(patch);
4231
+ bumpRefresh();
4232
+ } finally {
4233
+ saving = false;
4234
+ }
4235
+ }
4236
+ async function resetSettings() {
4237
+ setUsageSettings(defaultUsageSettings());
4238
+ saving = true;
4239
+ try {
4240
+ await sync.reset();
4241
+ bumpRefresh();
4242
+ } finally {
4243
+ saving = false;
4244
+ }
4245
+ }
4246
+ const settingsState = {
4247
+ settings: usageSettings,
4248
+ policy,
4249
+ error: settingsError,
4250
+ refresh: () => sync.refresh(true),
4251
+ update: saveSettings,
4252
+ reset: resetSettings
4253
+ };
3445
4254
  function providerName() {
3446
4255
  try {
3447
4256
  const providers = ctx.data.location?.provider?.list(ctx.location);
@@ -3450,7 +4259,7 @@ var tui_default = Plugin.define({
3450
4259
  return;
3451
4260
  }
3452
4261
  }
3453
- const quotaName = quotaNameOf(options.quotaName, providerName());
4262
+ const quotaName = () => quotaNameOf(resolved().quotaName, providerName());
3454
4263
  const PRICE_TTL_MS = 5 * 60 * 1000;
3455
4264
  let priceCache;
3456
4265
  function errorMessage(cause) {
@@ -3462,16 +4271,16 @@ var tui_default = Plugin.define({
3462
4271
  return "the usage limits request failed";
3463
4272
  }
3464
4273
  const [quotaState, setQuotaState] = createSignal3(undefined);
3465
- const [quotaLoading, setQuotaLoading] = createSignal3(quotaActive);
4274
+ const [quotaLoading, setQuotaLoading] = createSignal3(quotaActive());
3466
4275
  const [quotaError, setQuotaError] = createSignal3(undefined);
3467
4276
  const [quotaTick, setQuotaTick] = createSignal3(0);
3468
4277
  let quotaGeneration = 0;
3469
4278
  const refreshQuota = () => {
3470
- if (quotaActive)
4279
+ if (quotaActive())
3471
4280
  setQuotaTick((value) => value + 1);
3472
4281
  };
3473
4282
  createEffect3(() => {
3474
- if (!quotaActive)
4283
+ if (!quotaActive())
3475
4284
  return;
3476
4285
  quotaTick();
3477
4286
  const generation = ++quotaGeneration;
@@ -3493,7 +4302,7 @@ var tui_default = Plugin.define({
3493
4302
  });
3494
4303
  });
3495
4304
  createEffect3(() => {
3496
- if (!quotaActive)
4305
+ if (!quotaActive())
3497
4306
  return;
3498
4307
  const timer = setInterval(() => setQuotaTick((value) => value + 1), QUOTA_POLL_MS);
3499
4308
  onCleanup2(() => clearInterval(timer));
@@ -3505,7 +4314,7 @@ var tui_default = Plugin.define({
3505
4314
  refresh: refreshQuota
3506
4315
  };
3507
4316
  function priceTableFor() {
3508
- if (!pricing)
4317
+ if (!pricing())
3509
4318
  return;
3510
4319
  const now = Date.now();
3511
4320
  if (priceCache !== undefined && now - priceCache.at < PRICE_TTL_MS)
@@ -3526,11 +4335,11 @@ var tui_default = Plugin.define({
3526
4335
  const table = priceTableFor();
3527
4336
  return table === undefined ? undefined : (ref, tokens) => costOf(table, ref, tokens);
3528
4337
  }
3529
- const [settings, updateSettings] = ctx.storage.store("panel", {
4338
+ const [panelSettings, updatePanelSettings] = ctx.storage.store("panel", {
3530
4339
  initial: DEFAULT_SETTINGS
3531
4340
  });
3532
- const patchSettings = (mutation) => {
3533
- updateSettings(mutation);
4341
+ const patchPanelSettings = (mutation) => {
4342
+ updatePanelSettings(mutation);
3534
4343
  };
3535
4344
  const [refresh, setRefresh] = createSignal3(0);
3536
4345
  const [listCosts, setListCosts] = createSignal3({});
@@ -3557,12 +4366,12 @@ var tui_default = Plugin.define({
3557
4366
  refreshTimer.unref?.();
3558
4367
  }
3559
4368
  function listCostFor(sessionID) {
3560
- if (!pricing)
4369
+ if (!pricing())
3561
4370
  return 0;
3562
4371
  return listCosts()[sessionID] ?? 0;
3563
4372
  }
3564
4373
  async function loadListCost(sessionID) {
3565
- if (!pricing)
4374
+ if (!pricing())
3566
4375
  return;
3567
4376
  if (pendingListCost.has(sessionID)) {
3568
4377
  dirtyListCost.add(sessionID);
@@ -3600,7 +4409,7 @@ var tui_default = Plugin.define({
3600
4409
  function lineFor(sessionID) {
3601
4410
  if (!sessionIdle(sessionID))
3602
4411
  return;
3603
- if (pricing)
4412
+ if (pricing())
3604
4413
  refresh();
3605
4414
  const messages = ctx.data.session.message.list(sessionID);
3606
4415
  const info = ctx.data.session.get(sessionID);
@@ -3615,12 +4424,7 @@ var tui_default = Plugin.define({
3615
4424
  return ctx.theme.text.base;
3616
4425
  }
3617
4426
  function Line(props) {
3618
- const parts = createMemo3(() => lineParts(lineFor(props.sessionID), {
3619
- labels: options.labels,
3620
- fields: options.fields,
3621
- turnTotals: options.turnTotals,
3622
- estimates: pricing
3623
- }));
4427
+ const parts = createMemo3(() => lineParts(lineFor(props.sessionID), resolved().format));
3624
4428
  createEffect3(() => {
3625
4429
  props.sessionID;
3626
4430
  refresh();
@@ -3658,46 +4462,50 @@ var tui_default = Plugin.define({
3658
4462
  }
3659
4463
  })
3660
4464
  });
3661
- const disposePanel = panelEnabled ? ctx.ui.slot({
4465
+ const disposePanel = ctx.ui.slot({
3662
4466
  append: "session.panel",
3663
- render: (input) => input.name === PANEL_NAME ? _$createComponent3(Panel, {
4467
+ render: (input) => input.name === PANEL_NAME && panelEnabled() ? _$createComponent3(Panel, {
3664
4468
  input,
3665
4469
  ctx,
3666
4470
  deps: {
3667
4471
  refresh,
3668
4472
  bump: bumpRefresh
3669
4473
  },
3670
- settings,
3671
- update: patchSettings,
4474
+ settings: panelSettings,
4475
+ update: patchPanelSettings,
3672
4476
  get maintenance() {
3673
- return options.maintenance !== false;
4477
+ return policy().maintenance;
4478
+ },
4479
+ get views() {
4480
+ return views();
3674
4481
  },
3675
- views,
3676
4482
  quota: quotaResource,
3677
- quotaName
4483
+ get quotaName() {
4484
+ return quotaName();
4485
+ }
3678
4486
  }) : null
3679
- }) : () => {};
4487
+ });
3680
4488
  const disposeSidebar = ctx.ui.slot({
3681
4489
  append: "sidebar.content",
3682
- render: (input) => options.sidebar === false ? null : _$createComponent3(TurnsSidebar, {
4490
+ render: (input) => usageSettings().sidebar ? _$createComponent3(TurnsSidebar, {
3683
4491
  get sessionID() {
3684
4492
  return input.sessionID;
3685
4493
  },
3686
4494
  ctx,
3687
- get deps() {
3688
- return {
3689
- refresh,
3690
- limit: clampTurnsLimit(options.sidebarTurns ?? 8)
3691
- };
4495
+ deps: {
4496
+ refresh,
4497
+ limit: () => resolved().sidebarTurns
3692
4498
  },
3693
- quota: quotaEnabled ? quotaState : undefined,
3694
- quotaName
3695
- })
4499
+ quota: () => quotaEnabled() ? quotaState() : undefined,
4500
+ get quotaName() {
4501
+ return quotaName();
4502
+ }
4503
+ }) : null
3696
4504
  });
3697
4505
  function open(input) {
3698
- const parsed = parseArgs(input, views);
4506
+ const parsed = parseArgs(input, views());
3699
4507
  if (parsed.view !== undefined || parsed.range !== undefined) {
3700
- patchSettings((draft) => {
4508
+ patchPanelSettings((draft) => {
3701
4509
  if (parsed.view !== undefined)
3702
4510
  draft.view = parsed.view;
3703
4511
  if (parsed.range !== undefined)
@@ -3711,34 +4519,45 @@ var tui_default = Plugin.define({
3711
4519
  }
3712
4520
  return ctx.ui.panel.open(PANEL_NAME);
3713
4521
  }
3714
- if (panelEnabled) {
3715
- ctx.keymap.layer(() => {
3716
- return {
3717
- mode: "global",
3718
- commands: [{
3719
- id: "usage-insights.stats",
3720
- title: "Usage insights",
3721
- description: "Open the usage statistics panel",
3722
- group: "Usage insights",
3723
- bind: false,
3724
- palette: true,
3725
- slash: {
3726
- name: "usage-insights",
3727
- aliases: ["insights"],
3728
- arguments: true
3729
- },
3730
- run: (input) => {
3731
- if (!open(input)) {
3732
- ctx.ui.toast.show({
3733
- message: "Open a session first, then run /usage-insights",
3734
- variant: "warning"
3735
- });
3736
- }
4522
+ ctx.keymap.layer(() => {
4523
+ return {
4524
+ mode: "global",
4525
+ commands: [{
4526
+ id: "usage-insights.stats",
4527
+ title: "Usage insights",
4528
+ description: "Open the usage statistics panel",
4529
+ group: "Usage insights",
4530
+ bind: false,
4531
+ palette: true,
4532
+ enabled: () => panelEnabled(),
4533
+ slash: {
4534
+ name: "usage-insights",
4535
+ aliases: ["insights"],
4536
+ arguments: true
4537
+ },
4538
+ run: (input) => {
4539
+ if (!open(input)) {
4540
+ ctx.ui.toast.show({
4541
+ message: "Open a session first, then run /usage-insights",
4542
+ variant: "warning"
4543
+ });
3737
4544
  }
3738
- }]
3739
- };
3740
- });
3741
- }
4545
+ }
4546
+ }, {
4547
+ id: "usage-insights.settings",
4548
+ title: "Usage insights settings",
4549
+ description: "Line, panel and allowance settings shared with the Desktop",
4550
+ group: "Usage insights",
4551
+ bind: false,
4552
+ palette: true,
4553
+ slash: {
4554
+ name: "insights-settings",
4555
+ aliases: ["usage-insights-settings"]
4556
+ },
4557
+ run: () => void openUsageInsightsSettings(ctx, settingsState)
4558
+ }]
4559
+ };
4560
+ });
3742
4561
  const watchRecorded = () => {
3743
4562
  try {
3744
4563
  return api.onRecorded(() => bumpRefresh());
@@ -3755,21 +4574,17 @@ var tui_default = Plugin.define({
3755
4574
  ctx.data.on("session.compaction.ended", () => bumpRefresh()),
3756
4575
  ctx.data.on("model.updated", () => {
3757
4576
  priceCache = undefined;
3758
- })
4577
+ }),
4578
+ ctx.data.on("server.connected", () => sync.connect())
3759
4579
  ];
3760
4580
  __test.line = lineFor;
3761
4581
  __test.lineText = (sessionID) => {
3762
4582
  loadListCost(sessionID);
3763
- return lineText(lineParts(lineFor(sessionID), {
3764
- labels: options.labels,
3765
- fields: options.fields,
3766
- turnTotals: options.turnTotals,
3767
- estimates: pricing
3768
- }));
4583
+ return lineText(lineParts(lineFor(sessionID), resolved().format));
3769
4584
  };
3770
4585
  __test.open = open;
3771
4586
  __test.state = () => {
3772
- const current = sanitizeSettings(settings, views);
4587
+ const current = sanitizeSettings(panelSettings, views());
3773
4588
  return {
3774
4589
  view: current.view,
3775
4590
  range: current.range
@@ -3778,6 +4593,7 @@ var tui_default = Plugin.define({
3778
4593
  return () => {
3779
4594
  if (refreshTimer !== undefined)
3780
4595
  clearTimeout(refreshTimer);
4596
+ sync.stop();
3781
4597
  for (const dispose of disposeEvents)
3782
4598
  dispose();
3783
4599
  disposeLine();
@@ -3791,4 +4607,4 @@ export {
3791
4607
  tui_default as default
3792
4608
  };
3793
4609
 
3794
- //# debugId=42E094B28C9AC36E64756E2164756E21
4610
+ //# debugId=6E4C8A078FE321D964756E2164756E21