@laoyuehanni/dsh-token-usage 0.4.15 → 0.4.17

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 (122) hide show
  1. package/README.md +3 -3
  2. package/README.zh.md +3 -3
  3. package/docs/DETAIL.md +18 -0
  4. package/docs/DETAIL.zh.md +18 -0
  5. package/lib/aux-request.d.ts +18 -13
  6. package/lib/aux-request.d.ts.map +1 -1
  7. package/lib/aux-request.js +32 -19
  8. package/lib/aux-request.js.map +1 -1
  9. package/lib/backup.d.ts +32 -0
  10. package/lib/backup.d.ts.map +1 -0
  11. package/lib/backup.js +114 -0
  12. package/lib/backup.js.map +1 -0
  13. package/lib/client/CostPill.d.ts.map +1 -1
  14. package/lib/client/CostPill.js +45 -30
  15. package/lib/client/CostPill.js.map +1 -1
  16. package/lib/client/DashboardCards.d.ts +4 -2
  17. package/lib/client/DashboardCards.d.ts.map +1 -1
  18. package/lib/client/DashboardCards.js +2 -2
  19. package/lib/client/DashboardCards.js.map +1 -1
  20. package/lib/client/OverheadRows.d.ts +17 -12
  21. package/lib/client/OverheadRows.d.ts.map +1 -1
  22. package/lib/client/OverheadRows.js +32 -20
  23. package/lib/client/OverheadRows.js.map +1 -1
  24. package/lib/client/OverviewBoard.js +3 -3
  25. package/lib/client/OverviewBoard.js.map +1 -1
  26. package/lib/client/TokenUsageCard.d.ts.map +1 -1
  27. package/lib/client/TokenUsageCard.js +7 -1
  28. package/lib/client/TokenUsageCard.js.map +1 -1
  29. package/lib/client/TokenUsageSection.d.ts.map +1 -1
  30. package/lib/client/TokenUsageSection.js +11 -9
  31. package/lib/client/TokenUsageSection.js.map +1 -1
  32. package/lib/client/UsageRows.js +2 -2
  33. package/lib/client/UsageRows.js.map +1 -1
  34. package/lib/client/UsageView.d.ts +7 -6
  35. package/lib/client/UsageView.d.ts.map +1 -1
  36. package/lib/client/UsageView.js +100 -51
  37. package/lib/client/UsageView.js.map +1 -1
  38. package/lib/client/async-resource.d.ts +5 -2
  39. package/lib/client/async-resource.d.ts.map +1 -1
  40. package/lib/client/async-resource.js +14 -6
  41. package/lib/client/async-resource.js.map +1 -1
  42. package/lib/client/card-form.d.ts +11 -0
  43. package/lib/client/card-form.d.ts.map +1 -1
  44. package/lib/client/card-form.js +26 -6
  45. package/lib/client/card-form.js.map +1 -1
  46. package/lib/client/format.d.ts +11 -0
  47. package/lib/client/format.d.ts.map +1 -1
  48. package/lib/client/format.js +32 -3
  49. package/lib/client/format.js.map +1 -1
  50. package/lib/client/index.d.ts.map +1 -1
  51. package/lib/client/index.js +41 -19
  52. package/lib/client/index.js.map +1 -1
  53. package/lib/client/locales.d.ts +27 -1
  54. package/lib/client/locales.d.ts.map +1 -1
  55. package/lib/client/locales.js +54 -2
  56. package/lib/client/locales.js.map +1 -1
  57. package/lib/client/project-rows.d.ts +3 -2
  58. package/lib/client/project-rows.d.ts.map +1 -1
  59. package/lib/client/project-rows.js +3 -2
  60. package/lib/client/project-rows.js.map +1 -1
  61. package/lib/client/session-stats.d.ts +52 -10
  62. package/lib/client/session-stats.d.ts.map +1 -1
  63. package/lib/client/session-stats.js +88 -11
  64. package/lib/client/session-stats.js.map +1 -1
  65. package/lib/client.js +528 -158
  66. package/lib/client.js.map +1 -1
  67. package/lib/field-completion.d.ts.map +1 -1
  68. package/lib/field-completion.js +4 -1
  69. package/lib/field-completion.js.map +1 -1
  70. package/lib/index.d.ts +9 -4
  71. package/lib/index.d.ts.map +1 -1
  72. package/lib/index.js +140 -23
  73. package/lib/index.js.map +1 -1
  74. package/lib/migrate.d.ts +7 -1
  75. package/lib/migrate.d.ts.map +1 -1
  76. package/lib/migrate.js +116 -9
  77. package/lib/migrate.js.map +1 -1
  78. package/lib/project-rows.d.ts +20 -4
  79. package/lib/project-rows.d.ts.map +1 -1
  80. package/lib/project-rows.js +33 -8
  81. package/lib/project-rows.js.map +1 -1
  82. package/lib/request-observe.d.ts +7 -5
  83. package/lib/request-observe.d.ts.map +1 -1
  84. package/lib/request-observe.js +19 -16
  85. package/lib/request-observe.js.map +1 -1
  86. package/lib/rollup.d.ts +6 -1
  87. package/lib/rollup.d.ts.map +1 -1
  88. package/lib/rollup.js +15 -1
  89. package/lib/rollup.js.map +1 -1
  90. package/lib/session-request-details.d.ts.map +1 -1
  91. package/lib/session-request-details.js +5 -1
  92. package/lib/session-request-details.js.map +1 -1
  93. package/lib/stats-route.d.ts.map +1 -1
  94. package/lib/stats-route.js +65 -8
  95. package/lib/stats-route.js.map +1 -1
  96. package/lib/stats.d.ts +42 -1
  97. package/lib/stats.d.ts.map +1 -1
  98. package/lib/stats.js +240 -16
  99. package/lib/stats.js.map +1 -1
  100. package/lib/sync.d.ts +32 -0
  101. package/lib/sync.d.ts.map +1 -1
  102. package/lib/sync.js +286 -30
  103. package/lib/sync.js.map +1 -1
  104. package/lib/usage-log.d.ts +14 -9
  105. package/lib/usage-log.d.ts.map +1 -1
  106. package/lib/usage-log.js +190 -144
  107. package/lib/usage-log.js.map +1 -1
  108. package/lib/usage-record.d.ts +150 -27
  109. package/lib/usage-record.d.ts.map +1 -1
  110. package/lib/usage-record.js +221 -34
  111. package/lib/usage-record.js.map +1 -1
  112. package/lib/web-call.d.ts +55 -0
  113. package/lib/web-call.d.ts.map +1 -0
  114. package/lib/web-call.js +222 -0
  115. package/lib/web-call.js.map +1 -0
  116. package/lib/wire.d.ts +122 -11
  117. package/lib/wire.d.ts.map +1 -1
  118. package/lib/wire.js +40 -7
  119. package/lib/wire.js.map +1 -1
  120. package/locale/en.json +5 -1
  121. package/locale/zh.json +2 -1
  122. package/package.json +3 -3
package/lib/client.js CHANGED
@@ -15,6 +15,10 @@ window.__ModuleLoader__.load({
15
15
  const PRICING_PATH = "/token-usage/pricing";
16
16
  const PRICING_SYNC_PATH = "/token-usage/pricing-sync";
17
17
  const ASSOCIATIONS_PATH = "/token-usage/pricing-associations";
18
+ /** Query key carrying the scope's root session id. */
19
+ const ROOT_PARAM = "root";
20
+ /** Query key carrying the scope kind; omitted means `self`. */
21
+ const SCOPE_PARAM = "scope";
18
22
  /** Encode one repeated query key (`sessionId=a&sessionId=b`). Empty list yields ''. */
19
23
  function encodeRepeatedParam(key, values) {
20
24
  return values.map((value) => `${key}=${encodeURIComponent(value)}`).join("&");
@@ -25,14 +29,27 @@ window.__ModuleLoader__.load({
25
29
  }
26
30
  /**
27
31
  * Build the stats query string (including the leading `?`, or '' when
28
- * unconstrained). `fields: 'full'` is omitted — that is the default the
29
- * settings page already hits.
32
+ * unconstrained). A `root` request describes a RANGE RULE: the host expands
33
+ * `scope` from its session-metadata lineage index, so the URL never grows
34
+ * with the number of subagents — a subtree of 150+ sessions used to push the
35
+ * request line past Node's 16 KiB header limit (HTTP 431). `scope=self` is
36
+ * the default and is omitted from the wire.
37
+ *
38
+ * The explicit `sessionIds` / `childGroups` form is retained for legacy
39
+ * callers (older browser bundles, hand-written URLs and tests); new client
40
+ * code must use `root`, and the two forms are mutually exclusive.
41
+ * `fields: 'full'` is omitted — that is the default the settings page hits.
30
42
  */
31
43
  function encodeStatsQuery(options) {
32
44
  const parts = [];
33
- if (options.sessionIds !== void 0 && options.sessionIds.length > 0) parts.push(encodeRepeatedParam("sessionId", options.sessionIds));
34
- const children = options.childGroups !== void 0 ? encodeChildGroups(options.childGroups) : "";
35
- if (children !== "") parts.push(children);
45
+ if (options.root !== void 0 && options.root !== "") {
46
+ parts.push(`${ROOT_PARAM}=${encodeURIComponent(options.root)}`);
47
+ if (options.scope === "subtree") parts.push(`${SCOPE_PARAM}=subtree`);
48
+ } else {
49
+ if (options.sessionIds !== void 0 && options.sessionIds.length > 0) parts.push(encodeRepeatedParam("sessionId", options.sessionIds));
50
+ const children = options.childGroups !== void 0 ? encodeChildGroups(options.childGroups) : "";
51
+ if (children !== "") parts.push(children);
52
+ }
36
53
  if (options.fields !== void 0 && options.fields !== "full") parts.push(`fields=${options.fields}`);
37
54
  return parts.length === 0 ? "" : `?${parts.join("&")}`;
38
55
  }
@@ -93,6 +110,8 @@ window.__ModuleLoader__.load({
93
110
  drafts = {};
94
111
  /** Staged sidebar-pin toggle; undefined while untouched. */
95
112
  draftPinned;
113
+ /** Staged settings-section toggle; undefined while untouched. */
114
+ draftSettingsSection;
96
115
  saving = false;
97
116
  failed = false;
98
117
  refusal;
@@ -139,6 +158,12 @@ window.__ModuleLoader__.load({
139
158
  this.refusal = void 0;
140
159
  this.publish();
141
160
  },
161
+ editSettingsSection: (value) => {
162
+ this.draftSettingsSection = value;
163
+ this.failed = false;
164
+ this.refusal = void 0;
165
+ this.publish();
166
+ },
142
167
  clearField: (field) => {
143
168
  this.drafts[field] = "";
144
169
  this.failed = false;
@@ -149,9 +174,10 @@ window.__ModuleLoader__.load({
149
174
  this.save();
150
175
  },
151
176
  discard: () => {
152
- if (Object.keys(this.drafts).length === 0 && this.draftPinned === void 0 && !this.failed) return;
177
+ if (Object.keys(this.drafts).length === 0 && this.draftPinned === void 0 && this.draftSettingsSection === void 0 && !this.failed) return;
153
178
  this.drafts = {};
154
179
  this.draftPinned = void 0;
180
+ this.draftSettingsSection = void 0;
155
181
  this.failed = false;
156
182
  this.refusal = void 0;
157
183
  this.publish();
@@ -178,7 +204,8 @@ window.__ModuleLoader__.load({
178
204
  async save() {
179
205
  const edited = CARD_FIELDS.filter((field) => this.drafts[field] !== void 0);
180
206
  const pinEdit = this.draftPinned;
181
- if (edited.length === 0 && pinEdit === void 0 || this.saving) return;
207
+ const sectionEdit = this.draftSettingsSection;
208
+ if (edited.length === 0 && pinEdit === void 0 && sectionEdit === void 0 || this.saving) return;
182
209
  const intended = edited.map((field) => [field, this.drafts[field].trim()]);
183
210
  this.saving = true;
184
211
  this.failed = false;
@@ -200,11 +227,13 @@ window.__ModuleLoader__.load({
200
227
  for (const [field, text] of intended) if (text === "") await this.target.unset(field);
201
228
  else await this.target.set(field, text);
202
229
  if (pinEdit !== void 0) await this.target.set("sidebarPinned", pinEdit);
230
+ if (sectionEdit !== void 0) await this.target.set("settingsSectionEnabled", sectionEdit);
203
231
  for (const [field, text] of intended) if (text === "" ? this.stored(field) : this.storedValue(field) !== text) {
204
232
  landed = false;
205
233
  break;
206
234
  }
207
235
  if (pinEdit !== void 0 && this.storedValue("sidebarPinned") !== pinEdit) landed = false;
236
+ if (sectionEdit !== void 0 && this.storedValue("settingsSectionEnabled") !== sectionEdit) landed = false;
208
237
  } catch (_settingsWriteFailure) {
209
238
  landed = false;
210
239
  }
@@ -215,6 +244,7 @@ window.__ModuleLoader__.load({
215
244
  if (landed) {
216
245
  for (const [field, _text] of intended) delete this.drafts[field];
217
246
  this.draftPinned = void 0;
247
+ this.draftSettingsSection = void 0;
218
248
  }
219
249
  this.saving = false;
220
250
  this.failed = !landed;
@@ -301,6 +331,7 @@ window.__ModuleLoader__.load({
301
331
  project() {
302
332
  const snapshot = this.snapshot();
303
333
  const pinnedEffective = snapshot.value?.sidebarPinned === true;
334
+ const sectionEffective = snapshot.value?.settingsSectionEnabled !== false;
304
335
  const fields = {};
305
336
  const overridden = {};
306
337
  let textDirty = false;
@@ -314,9 +345,11 @@ window.__ModuleLoader__.load({
314
345
  writable: snapshot.writable,
315
346
  sidebarPinned: pinnedEffective,
316
347
  pinnedDraft: this.draftPinned,
348
+ settingsSectionEnabled: sectionEffective,
349
+ settingsSectionDraft: this.draftSettingsSection,
317
350
  fields,
318
351
  overridden,
319
- dirty: textDirty || this.draftPinned !== void 0 && this.draftPinned !== pinnedEffective,
352
+ dirty: textDirty || this.draftPinned !== void 0 && this.draftPinned !== pinnedEffective || this.draftSettingsSection !== void 0 && this.draftSettingsSection !== sectionEffective,
320
353
  textDirty,
321
354
  saving: this.saving,
322
355
  failed: this.failed,
@@ -415,23 +448,45 @@ window.__ModuleLoader__.load({
415
448
  * Return a value that lags behind its source by `delayMs` — a debounced
416
449
  * snapshot. The initial render already holds `value` (no null sentinel), so
417
450
  * a consumer can fetch immediately on mount without a second shot when the
418
- * first debounce window closes on the same value.
451
+ * first debounce window closes on the same value. When `resetKey` changes,
452
+ * the snapshot snaps to the current `value` immediately so a scope switch
453
+ * fires one fetch instead of a second delayed one when the old timer lands.
419
454
  *
420
455
  * @param value - the source value to debounce.
421
456
  * @param delayMs - the lag window in milliseconds.
457
+ * @param resetKey - optional identity whose change bypasses the debounce lag.
422
458
  * @returns the debounced value.
423
459
  */
424
- function useDebouncedValue(value, delayMs) {
425
- const [debounced, setDebounced] = (0, react.useState)(value);
460
+ function useDebouncedValue(value, delayMs, resetKey) {
461
+ const [state, setState] = (0, react.useState)({
462
+ value,
463
+ resetKey
464
+ });
465
+ const effective = Object.is(state.resetKey, resetKey) ? state.value : value;
426
466
  (0, react.useEffect)(() => {
467
+ if (!Object.is(state.resetKey, resetKey)) {
468
+ setState({
469
+ value,
470
+ resetKey
471
+ });
472
+ return;
473
+ }
427
474
  const timer = setTimeout(() => {
428
- setDebounced(value);
475
+ setState({
476
+ value,
477
+ resetKey
478
+ });
429
479
  }, delayMs);
430
480
  return () => {
431
481
  clearTimeout(timer);
432
482
  };
433
- }, [value, delayMs]);
434
- return debounced;
483
+ }, [
484
+ value,
485
+ delayMs,
486
+ resetKey,
487
+ state.resetKey
488
+ ]);
489
+ return effective;
435
490
  }
436
491
  // src/client/day.ts
437
492
  /** Total tokens across the four buckets (billed input = input + cacheRead + cacheWrite). */
@@ -566,22 +621,38 @@ window.__ModuleLoader__.load({
566
621
  * future code is not in this map and the tooltip renders it verbatim. */
567
622
  const FAILURE_CODE_LABEL_KEYS = {
568
623
  ABORTED: "fail.ABORTED",
624
+ ACCOUNT_QUOTA: "fail.ACCOUNT_QUOTA",
625
+ ACCOUNT_SIGN_IN_REQUIRED: "fail.ACCOUNT_SIGN_IN_REQUIRED",
626
+ ACCOUNT_TOKEN_INVALID: "fail.ACCOUNT_TOKEN_INVALID",
569
627
  AUTH: "fail.AUTH",
628
+ CLIENT_UPGRADE_REQUIRED: "fail.CLIENT_UPGRADE_REQUIRED",
629
+ CONTENT_REFUSED: "fail.CONTENT_REFUSED",
570
630
  CONTEXT_WINDOW_EXCEEDED: "fail.CONTEXT_WINDOW_EXCEEDED",
571
631
  EMPTY_RESPONSE: "fail.EMPTY_RESPONSE",
572
632
  FILES_API: "fail.FILES_API",
633
+ IMAGE_OFFLOAD_REQUIRED: "fail.IMAGE_OFFLOAD_REQUIRED",
573
634
  INVALID_CREDENTIAL: "fail.INVALID_CREDENTIAL",
574
635
  INVALID_REQUEST: "fail.INVALID_REQUEST",
636
+ INVALID_RESPONSE: "fail.INVALID_RESPONSE",
575
637
  MALFORMED_RESPONSE: "fail.MALFORMED_RESPONSE",
576
638
  MISSING_CREDENTIAL: "fail.MISSING_CREDENTIAL",
639
+ MODEL_SWITCH_COMPACTION_FAILED: "fail.MODEL_SWITCH_COMPACTION_FAILED",
640
+ MODEL_UNSUPPORTED: "fail.MODEL_UNSUPPORTED",
641
+ NO_ADAPTER: "fail.NO_ADAPTER",
642
+ PI_AI_ERROR: "fail.PI_AI_ERROR",
577
643
  QUOTA: "fail.QUOTA",
578
644
  RATE_LIMIT: "fail.RATE_LIMIT",
579
645
  REQUEST_EXTENSION: "fail.REQUEST_EXTENSION",
646
+ REQUEST_HEADERS: "fail.REQUEST_HEADERS",
580
647
  SERVER: "fail.SERVER",
581
648
  STREAM_CLOSED: "fail.STREAM_CLOSED",
582
649
  TIMEOUT: "fail.TIMEOUT",
583
650
  TRANSPORT: "fail.TRANSPORT",
584
- UNKNOWN: "fail.UNKNOWN"
651
+ UNKNOWN: "fail.UNKNOWN",
652
+ UNKNOWN_MODEL: "fail.UNKNOWN_MODEL",
653
+ UNSUPPORTED_CONTENT: "fail.UNSUPPORTED_CONTENT",
654
+ UNSUPPORTED_OPTION: "fail.UNSUPPORTED_OPTION",
655
+ UNSUPPORTED_REASONING_EFFORT: "fail.UNSUPPORTED_REASONING_EFFORT"
585
656
  };
586
657
  /** One decimal below 10, integer otherwise, trailing `.0` stripped. */
587
658
  function scale(value) {
@@ -779,6 +850,19 @@ window.__ModuleLoader__.load({
779
850
  }
780
851
  /**
781
852
  * The overhead pill's hover tooltip text: one `label ×count` line per
853
+ /**
854
+ * Total auxiliary (bypass) call count: completed requests plus recorded
855
+ * failures (for example `CONTENT_REFUSED` aux calls that billed before
856
+ * refusal). Kept shared so the overhead pill, card rows, tooltip and detail
857
+ * tab gate stay aligned.
858
+ * @param totals - the totals bucket (usually `aux.total` or a kind row's totals).
859
+ * @returns completed requests plus failures (treating absent failures as 0).
860
+ */
861
+ function auxCallCount(totals) {
862
+ return totals.requests + (totals.failures ?? 0);
863
+ }
864
+ /**
865
+ * Multi-line tooltip text for the overview card's `OverheadPill`: one line per
782
866
  * auxiliary kind, count descending, newline-joined — the same shape as
783
867
  * {@link failuresTooltip}. An absent breakdown yields '' and the caller
784
868
  * suppresses the tooltip (the pill itself still shows its count).
@@ -789,7 +873,7 @@ window.__ModuleLoader__.load({
789
873
  */
790
874
  function overheadTooltip(byKind, t) {
791
875
  if (byKind === void 0) return "";
792
- return byKind.filter((row) => row.totals.requests > 0).sort((left, right) => right.totals.requests - left.totals.requests).map((row) => `${t(`aux.kind.${row.auxKind}`)} ×${row.totals.requests.toLocaleString()}`).join("\n");
876
+ return byKind.filter((row) => auxCallCount(row.totals) > 0).sort((left, right) => auxCallCount(right.totals) - auxCallCount(left.totals)).map((row) => `${t(`aux.kind.${row.auxKind}`)} ×${auxCallCount(row.totals).toLocaleString()}`).join("\n");
793
877
  }
794
878
  // src/client/PricingStatus.tsx
795
879
  function costsAvailable(state) {
@@ -1766,17 +1850,19 @@ window.__ModuleLoader__.load({
1766
1850
  return out;
1767
1851
  }
1768
1852
  /**
1769
- * The immediate subagent parent of one session, when the record names one.
1770
- * The check is on `parentId` rather than `origin` so a mirrored summary that
1771
- * lost its origin tag still answers its lineage — the index is built once
1772
- * per render and shared across all three helpers via {@link ChildIndex}.
1853
+ * The immediate subagent parent of one session, when the record is tagged
1854
+ * `origin === 'subagent'` and names a parent. Ordinary forks — including
1855
+ * historical forks that retained `parentId` without `origin: 'subagent'` —
1856
+ * answer `undefined`, matching {@link buildChildIndex}.
1773
1857
  * @param rows - the retained session-summary mirror.
1774
1858
  * @param id - the current focus session id.
1775
- * @returns the parent session id, or undefined when the record has no
1776
- * parent link (a top-level session or an ordinary fork).
1859
+ * @returns the parent session id, or undefined when the record is not a
1860
+ * subagent child.
1777
1861
  */
1778
1862
  function subagentParentOf(rows, id) {
1779
- const parent = rows[id]?.parentId;
1863
+ const row = rows[id];
1864
+ if (row?.origin !== "subagent") return void 0;
1865
+ const parent = row.parentId;
1780
1866
  return parent === void 0 || parent === id ? void 0 : parent;
1781
1867
  }
1782
1868
  /**
@@ -1826,17 +1912,79 @@ window.__ModuleLoader__.load({
1826
1912
  ].join(".");
1827
1913
  }
1828
1914
  /**
1829
- * Build a debounce key from mirror `updatedAt` plus `sessionStats` churn.
1830
- * The active session reads live projection values from `useProjection`; every
1831
- * other scoped id reads the mirror copy.
1915
+ * Compact fingerprint of one session's summary `tokenUsage` projection —
1916
+ * retained on `session.list` rows in DSH 0.2.2+ after `sessionStats` was
1917
+ * excluded from summaries, so subagent token progress still bumps freshness.
1918
+ */
1919
+ function tokenUsageFingerprint(usage) {
1920
+ if (usage === void 0) return "-";
1921
+ return [
1922
+ usage.uncachedInputTokens,
1923
+ usage.outputTokens,
1924
+ usage.cacheReadTokens,
1925
+ usage.cacheWriteTokens
1926
+ ].join(".");
1927
+ }
1928
+ /**
1929
+ * Build a debounce key from mirror `updatedAt`, summary `tokenUsage` churn
1930
+ * (for subagents in DSH 0.2.2+), and `sessionStats` churn (active session and
1931
+ * legacy hosts).
1832
1932
  */
1833
1933
  function buildStatsFreshnessKey(ids, options) {
1834
1934
  return ids.map((id) => {
1835
1935
  const row = options.rows[id];
1936
+ const tokenUsage = id === options.activeSessionId ? options.liveTokenUsage ?? row?.projectionValues?.tokenUsage : row?.projectionValues?.tokenUsage;
1836
1937
  const stats = id === options.activeSessionId ? options.liveSessionStats ?? row?.projectionValues?.sessionStats : row?.projectionValues?.sessionStats;
1837
- return `${id}:${String(row?.updatedAt ?? 0)}:${sessionStatsFingerprint(stats)}`;
1938
+ return `${id}:${String(row?.updatedAt ?? 0)}:${tokenUsageFingerprint(tokenUsage)}:${sessionStatsFingerprint(stats)}`;
1838
1939
  }).join(",");
1839
1940
  }
1941
+ /** Aggregate retained `sessionStats` projections across `ids`, preferring the
1942
+ * live hook for `activeSessionId` and reading mirror rows for legacy hosts. */
1943
+ function aggregateScopedProjections(ids, rows, activeSessionId, liveSessionStats) {
1944
+ return aggregateProjections(ids.map((id) => {
1945
+ if (id === activeSessionId) return liveSessionStats ?? rows[id]?.projectionValues?.sessionStats;
1946
+ return rows[id]?.projectionValues?.sessionStats;
1947
+ }));
1948
+ }
1949
+ function timingFromBuckets(bucket) {
1950
+ if (bucket === void 0) return {};
1951
+ return {
1952
+ ...bucket.ttftSteps > 0 ? { ttftMs: bucket.ttftMs / bucket.ttftSteps } : {},
1953
+ ...bucket.decodeMs > 0 ? { tokensPerSec: bucket.decodeTokens / (bucket.decodeMs / 1e3) } : {}
1954
+ };
1955
+ }
1956
+ function timingFromPerfTotals(totals) {
1957
+ const samples = totals?.perfStreamCount ?? 0;
1958
+ if (samples <= 0) return {};
1959
+ return {
1960
+ ...totals?.perfStreamFirstMsSum !== void 0 ? { ttftMs: totals.perfStreamFirstMsSum / samples } : {},
1961
+ ...totals?.perfStreamTpsSum !== void 0 ? { tokensPerSec: totals.perfStreamTpsSum / samples } : {}
1962
+ };
1963
+ }
1964
+ /**
1965
+ * Resolve header TTFT and decode throughput while keeping DSH's weighted
1966
+ * projection formula (`ttftMs / ttftSteps`, `decodeTokens / (decodeMs / 1_000)`):
1967
+ * - Solo active session: prefer live `sessionStats` projection (covers
1968
+ * unlogged pre-install history and per-step retries), then host `summary.timing`.
1969
+ * - Subtree or drilled subagent: prefer host-aggregated `summary.timing` (which
1970
+ * covers finished subagents even when `sessionStats` is excluded from
1971
+ * summaries in DSH 0.2.2+), then legacy mirror projections, then `perfStream*`
1972
+ * on `history-incomplete` rollup fallbacks.
1973
+ */
1974
+ function resolveHeaderTiming(input) {
1975
+ const candidates = input.isSoloActive ? [
1976
+ timingFromBuckets(input.liveStats),
1977
+ timingFromBuckets(input.serverTiming),
1978
+ timingFromBuckets(input.mirrorAggregate),
1979
+ timingFromPerfTotals(input.totalPerf)
1980
+ ] : [
1981
+ timingFromBuckets(input.serverTiming),
1982
+ timingFromBuckets(input.mirrorAggregate),
1983
+ timingFromPerfTotals(input.totalPerf)
1984
+ ];
1985
+ for (const candidate of candidates) if (candidate.ttftMs !== void 0 || candidate.tokensPerSec !== void 0) return candidate;
1986
+ return {};
1987
+ }
1840
1988
  // src/client/use-color-scheme.ts
1841
1989
  /**
1842
1990
  * Shared browser-half hook: mirror the shell's root `color-scheme` onto a
@@ -2170,19 +2318,41 @@ window.__ModuleLoader__.load({
2170
2318
  childIndex
2171
2319
  ]);
2172
2320
  const hasSubs = scopeIds.length > 1;
2173
- const freshnessKey = buildStatsFreshnessKey(scopeIds, {
2321
+ const liveStats = useProjection("sessionStats");
2322
+ const scopeIdsKey = scopeIds.join(",");
2323
+ const debouncedFreshnessKey = useDebouncedValue(buildStatsFreshnessKey(scopeIds, {
2174
2324
  activeSessionId: sessionId,
2175
2325
  rows: byId,
2176
- liveSessionStats: useProjection("sessionStats")
2177
- });
2178
- const debouncedKey = useDebouncedValue(`${scopeIds.join("\n")}\n\t${freshnessKey}`, REFRESH_DEBOUNCE_MS$1);
2179
- const { onSummary } = useCostInflate(scopeIds.join("\n"), costRef);
2326
+ liveSessionStats: liveStats
2327
+ }), REFRESH_DEBOUNCE_MS$1, sessionId);
2328
+ const { onSummary } = useCostInflate(`${sessionId}:${scopeIds.length}`, costRef);
2329
+ const recentRef = (0, react.useRef)(void 0);
2180
2330
  const [treeRes, retryTree] = useAsyncResource((signal) => {
2181
- const [idsPart] = debouncedKey.split("\n ");
2182
- return fetchSummary$1((idsPart ?? "").split("\n").filter((id) => id !== ""), "chip", signal);
2183
- }, [debouncedKey, associationTick], {
2331
+ const recent = recentRef.current;
2332
+ if (recent !== void 0 && !recent.coalesced && recent.sessionId === sessionId && recent.scopeIdsKey !== scopeIdsKey && recent.associationTick === associationTick && Date.now() - recent.at < 500 && recent !== void 0) {
2333
+ recentRef.current = {
2334
+ ...recent,
2335
+ scopeIdsKey,
2336
+ at: Date.now(),
2337
+ coalesced: true
2338
+ };
2339
+ return Promise.resolve(recent.value);
2340
+ }
2341
+ return fetchSummary$1(sessionId, "subtree", "chip", signal).then((value) => {
2342
+ if (value !== null) recentRef.current = {
2343
+ sessionId,
2344
+ scopeIdsKey,
2345
+ associationTick,
2346
+ at: Date.now(),
2347
+ value,
2348
+ coalesced: false
2349
+ };
2350
+ return value;
2351
+ });
2352
+ }, [debouncedFreshnessKey, associationTick], {
2184
2353
  silentAfterFirst: true,
2185
- retryToken: 0
2354
+ retryToken: 0,
2355
+ scopeKey: sessionId
2186
2356
  });
2187
2357
  const summary = treeRes.status === "ready" ? treeRes.value : null;
2188
2358
  (0, react.useEffect)(() => {
@@ -2195,29 +2365,24 @@ window.__ModuleLoader__.load({
2195
2365
  window.clearTimeout(timer);
2196
2366
  };
2197
2367
  }, [treeRes, retryTree]);
2198
- const [detailRes] = useAsyncResource((signal) => {
2199
- if (!open) return Promise.resolve(null);
2200
- const [idsPart] = debouncedKey.split("\n ");
2201
- return fetchSummary$1((idsPart ?? "").split("\n").filter((id) => id !== ""), "session", signal);
2202
- }, [
2368
+ const [detailRes] = useAsyncResource((signal) => open ? fetchSummary$1(sessionId, "subtree", "session", signal) : Promise.resolve(null), [
2203
2369
  open,
2204
- debouncedKey,
2370
+ debouncedFreshnessKey,
2205
2371
  associationTick
2206
2372
  ], {
2207
2373
  silentAfterFirst: true,
2208
- retryToken: 0
2374
+ retryToken: 0,
2375
+ scopeKey: sessionId
2209
2376
  });
2210
- const [selfRes] = useAsyncResource((signal) => {
2211
- if (!open || sessionId === "") return Promise.resolve(null);
2212
- return fetchSummary$1([sessionId], "chip", signal);
2213
- }, [
2377
+ const [selfRes] = useAsyncResource((signal) => open && sessionId !== "" ? fetchSummary$1(sessionId, "self", "chip", signal) : Promise.resolve(null), [
2214
2378
  open,
2215
2379
  sessionId,
2216
- debouncedKey,
2380
+ debouncedFreshnessKey,
2217
2381
  associationTick
2218
2382
  ], {
2219
2383
  silentAfterFirst: true,
2220
- retryToken: 0
2384
+ retryToken: 0,
2385
+ scopeKey: sessionId
2221
2386
  });
2222
2387
  (0, react.useEffect)(() => {
2223
2388
  setOpen(false);
@@ -2451,20 +2616,22 @@ window.__ModuleLoader__.load({
2451
2616
  return typeof value === "object" && value !== null && typeof value.total === "object" && value.total !== null;
2452
2617
  }
2453
2618
  /**
2454
- * Fetch one stats summary. Throws on transport failure (network, abort,
2455
- * non-2xx response, or a payload that doesn't look like a stats summary) so
2456
- * the hook can keep the previous render in place.
2457
- * @param sessionIds - the scope's session ids; an empty list skips the
2458
- * fetch (returning null rather than throwing, so the hook's first-load
2459
- * gate stays at "loading").
2460
- * @param fields - `chip` for totals-only reads, `session` when byModel is
2461
- * needed (the detail panel's per-model block).
2619
+ * Fetch one stats summary. The request carries a RANGE RULE (root + scope),
2620
+ * never an enumerated subtree — the host expands it from its lineage index,
2621
+ * so the pill's chip/detail reads stay short even for hundreds of subagents.
2622
+ * Throws on transport failure (network, abort, non-2xx response, or a payload
2623
+ * that doesn't look like a stats summary) so the hook can keep the previous
2624
+ * render in place.
2625
+ * @param root - the scope's root session id; empty skips the fetch.
2626
+ * @param scope - `subtree` for the folded total, `self` for the split.
2627
+ * @param fields - `chip` for totals-only reads, `session` for byModel.
2462
2628
  * @param signal - the cancellation signal from the hook.
2463
2629
  */
2464
- async function fetchSummary$1(sessionIds, fields, signal) {
2465
- if (sessionIds.length === 0) return null;
2630
+ async function fetchSummary$1(root, scope, fields, signal) {
2631
+ if (root === "") return null;
2466
2632
  const response = await fetch(STATS_PATH + encodeStatsQuery({
2467
- sessionIds,
2633
+ root,
2634
+ scope,
2468
2635
  fields
2469
2636
  }), {
2470
2637
  headers: { accept: "application/json" },
@@ -3311,7 +3478,8 @@ window.__ModuleLoader__.load({
3311
3478
  added: body.added,
3312
3479
  skipped: body.skipped,
3313
3480
  removed: typeof body.removed === "number" ? body.removed : 0,
3314
- failedSessions: typeof body.failedSessions === "number" ? body.failedSessions : 0
3481
+ failedSessions: typeof body.failedSessions === "number" ? body.failedSessions : 0,
3482
+ ...typeof body.ignoredImported === "number" && body.ignoredImported > 0 ? { ignoredImported: body.ignoredImported } : {}
3315
3483
  };
3316
3484
  return null;
3317
3485
  }
@@ -3500,6 +3668,29 @@ window.__ModuleLoader__.load({
3500
3668
  children: t("card.sidebarPinned.hint")
3501
3669
  })]
3502
3670
  }),
3671
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3672
+ className: TokenUsageCard_module_css_default.field,
3673
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
3674
+ className: TokenUsageCard_module_css_default.pinRow,
3675
+ htmlFor: "token-usage-card-settings-section",
3676
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
3677
+ id: "token-usage-card-settings-section",
3678
+ type: "checkbox",
3679
+ className: TokenUsageCard_module_css_default.pinCheck,
3680
+ checked: state.settingsSectionDraft ?? state.settingsSectionEnabled,
3681
+ disabled: lockInput,
3682
+ onChange: (event) => {
3683
+ props.editSettingsSection(event.target.checked);
3684
+ }
3685
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
3686
+ className: TokenUsageCard_module_css_default.fieldLabel,
3687
+ children: t("card.settingsSectionEnabled.label")
3688
+ })]
3689
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3690
+ className: TokenUsageCard_module_css_default.hint,
3691
+ children: t("card.settingsSectionEnabled.hint")
3692
+ })]
3693
+ }),
3503
3694
  state.migration !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3504
3695
  className: TokenUsageCard_module_css_default.migration,
3505
3696
  role: "status",
@@ -3541,13 +3732,17 @@ window.__ModuleLoader__.load({
3541
3732
  role: "status",
3542
3733
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
3543
3734
  className: TokenUsageCard_module_css_default.fullSyncProgressLabel,
3544
- children: [t("card.fullSync.progress", {
3545
- processed: String(fullSync.processed),
3546
- total: String(fullSync.total),
3547
- added: String(fullSync.added),
3548
- skipped: String(fullSync.skipped),
3549
- removed: String(fullSync.removed)
3550
- }), fullSync.failedSessions > 0 ? t("card.fullSync.failuresNote", { count: String(fullSync.failedSessions) }) : ""]
3735
+ children: [
3736
+ t("card.fullSync.progress", {
3737
+ processed: String(fullSync.processed),
3738
+ total: String(fullSync.total),
3739
+ added: String(fullSync.added),
3740
+ skipped: String(fullSync.skipped),
3741
+ removed: String(fullSync.removed)
3742
+ }),
3743
+ fullSync.failedSessions > 0 ? t("card.fullSync.failuresNote", { count: String(fullSync.failedSessions) }) : "",
3744
+ fullSync.ignoredImported !== void 0 ? t("card.fullSync.importedNote", { count: String(fullSync.ignoredImported) }) : ""
3745
+ ]
3551
3746
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
3552
3747
  className: TokenUsageCard_module_css_default.fullSyncBar,
3553
3748
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
@@ -3559,11 +3754,15 @@ window.__ModuleLoader__.load({
3559
3754
  fullSync.status === "done" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
3560
3755
  className: TokenUsageCard_module_css_default.fullSyncResult,
3561
3756
  role: "status",
3562
- children: [t("card.fullSync.done", {
3563
- added: String(fullSync.added),
3564
- skipped: String(fullSync.skipped),
3565
- removed: String(fullSync.removed)
3566
- }), fullSync.failedSessions > 0 ? t("card.fullSync.failuresNote", { count: String(fullSync.failedSessions) }) : ""]
3757
+ children: [
3758
+ t("card.fullSync.done", {
3759
+ added: String(fullSync.added),
3760
+ skipped: String(fullSync.skipped),
3761
+ removed: String(fullSync.removed)
3762
+ }),
3763
+ fullSync.failedSessions > 0 ? t("card.fullSync.failuresNote", { count: String(fullSync.failedSessions) }) : "",
3764
+ fullSync.ignoredImported !== void 0 ? t("card.fullSync.importedNote", { count: String(fullSync.ignoredImported) }) : ""
3765
+ ]
3567
3766
  }) : null,
3568
3767
  fullSync.status === "failed" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3569
3768
  className: TokenUsageCard_module_css_default.fullSyncError,
@@ -4139,23 +4338,28 @@ window.__ModuleLoader__.load({
4139
4338
  /**
4140
4339
  * The runtime-overhead card's row shape (browser half): one expanded-by-
4141
4340
  * default row per auxiliary kind — the row carries the kind's aggregate
4142
- * (calls · cost · tokens) and discloses its per-model lines on toggle; the
4143
- * total line sits beneath the list. The semantics are the retired table's
4144
- * (same fold, same empty hints, same defensive read of a payload without
4145
- * `aux`); only the shape moved from columns to rows.
4341
+ * (calls · cost · tokens) and discloses its per-model lines on toggle — plus
4342
+ * one expanded-by-default web-tools row that carries the total call count and
4343
+ * discloses its per-tool lines (`web_search`, `web_fetch`) on toggle. The
4344
+ * total line beneath the list covers the auxiliary kinds only: web tools
4345
+ * never join it, and any tokens a search reported are billed with the
4346
+ * ordinary request totals.
4146
4347
  *
4147
4348
  * @module token-usage/client/OverheadRows
4148
4349
  */
4149
4350
  /**
4150
- * Render the overhead rows: one disclosure row per kind, then the total
4151
- * line. A summary without auxiliary requests — including an older host
4152
- * payload with no `aux` field at all — renders the empty hint instead, so
4153
- * the card keeps a stable body.
4154
- * @param props - the aux layer of the summary (possibly absent), the cost
4155
- * state, the display currency view, and the locale translator.
4351
+ * Render the overhead rows: one disclosure row per auxiliary kind, the
4352
+ * web-search row, then the auxiliary total line. A summary without auxiliary
4353
+ * requests — including an older host payload with no `aux` field at all —
4354
+ * renders the empty hint instead, unless the web-search layer has calls.
4355
+ * A web row renders one line: its call count.
4356
+ * @param props - the aux layer (possibly absent), the web-search layer
4357
+ * (absent on legacy payloads), the cost state, the display currency view,
4358
+ * and the locale translator.
4156
4359
  */
4157
- function OverheadRows({ aux, costState, view, t }) {
4360
+ function OverheadRows({ aux, web, costState, view, t }) {
4158
4361
  const [collapsedKinds, setCollapsedKinds] = (0, react.useState)(() => /* @__PURE__ */ new Set());
4362
+ const [webCollapsed, setWebCollapsed] = (0, react.useState)(false);
4159
4363
  const toggleKind = (auxKind) => {
4160
4364
  setCollapsedKinds((previous) => {
4161
4365
  const next = new Set(previous);
@@ -4164,7 +4368,9 @@ window.__ModuleLoader__.load({
4164
4368
  return next;
4165
4369
  });
4166
4370
  };
4167
- if (aux === void 0 || aux.total.requests === 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
4371
+ const hasAux = aux !== void 0 && auxCallCount(aux.total) > 0;
4372
+ const hasWeb = web !== void 0 && web.calls > 0;
4373
+ if (!hasAux && !hasWeb) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
4168
4374
  className: OverheadRows_module_css_default["muted"],
4169
4375
  children: t("aux.empty")
4170
4376
  });
@@ -4183,11 +4389,11 @@ window.__ModuleLoader__.load({
4183
4389
  formatTokens(tokens)
4184
4390
  ] })]
4185
4391
  });
4186
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
4392
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4187
4393
  className: UsageRows_module_css_default["rows"],
4188
4394
  role: "list",
4189
4395
  "aria-label": t("aux.tab"),
4190
- children: (aux.byKind ?? []).map((kindRow) => {
4396
+ children: [(aux?.byKind ?? []).map((kindRow) => {
4191
4397
  const expanded = !collapsedKinds.has(kindRow.auxKind);
4192
4398
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4193
4399
  className: OverheadRows_module_css_default["orow"],
@@ -4207,7 +4413,7 @@ window.__ModuleLoader__.load({
4207
4413
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
4208
4414
  className: OverheadRows_module_css_default["onums"],
4209
4415
  children: [
4210
- t("aux.requestCount", { count: kindRow.totals.requests.toLocaleString() }),
4416
+ t("aux.requestCount", { count: auxCallCount(kindRow.totals).toLocaleString() }),
4211
4417
  " · ",
4212
4418
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
4213
4419
  className: OverheadRows_module_css_default["onumsCost"],
@@ -4219,13 +4425,42 @@ window.__ModuleLoader__.load({
4219
4425
  })]
4220
4426
  }), expanded ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
4221
4427
  className: OverheadRows_module_css_default["adetail"],
4222
- children: (kindRow.byModel ?? []).map((modelRow) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: modelLine(modelRow.model, modelRow.totals.requests, modelRow.cost, totalTokens$1(modelRow.totals)) }, `${kindRow.auxKind}:${modelRow.model}`))
4428
+ children: (kindRow.byModel ?? []).map((modelRow) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: modelLine(modelRow.model, auxCallCount(modelRow.totals), modelRow.cost, totalTokens$1(modelRow.totals)) }, `${kindRow.auxKind}:${modelRow.model}`))
4223
4429
  }) : null]
4224
4430
  }, kindRow.auxKind);
4225
- })
4226
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4431
+ }), hasWeb ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4432
+ className: OverheadRows_module_css_default["orow"],
4433
+ role: "listitem",
4434
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4435
+ className: OverheadRows_module_css_default["orowTop"],
4436
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
4437
+ type: "button",
4438
+ className: OverheadRows_module_css_default["kindToggle"],
4439
+ "aria-expanded": !webCollapsed,
4440
+ onClick: () => setWebCollapsed((previous) => !previous),
4441
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
4442
+ className: OverheadRows_module_css_default["chevron"],
4443
+ "aria-hidden": "true",
4444
+ children: "▸"
4445
+ }), t("web.title")]
4446
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
4447
+ className: OverheadRows_module_css_default["onums"],
4448
+ children: t("web.calls", { count: web.calls.toLocaleString() })
4449
+ })]
4450
+ }), !webCollapsed && (web.byTool?.length ?? 0) > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
4451
+ className: OverheadRows_module_css_default["adetail"],
4452
+ children: (web.byTool ?? []).map((toolRow) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
4453
+ className: OverheadRows_module_css_default["dline"],
4454
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
4455
+ className: OverheadRows_module_css_default["dmodelName"],
4456
+ children: t(`web.tool.${toolRow.tool}`)
4457
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("web.calls", { count: toolRow.calls.toLocaleString() }) })]
4458
+ }, `web:${toolRow.tool}`))
4459
+ }) : null]
4460
+ }, "web-tools") : null]
4461
+ }), hasAux ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4227
4462
  className: OverheadRows_module_css_default["asum"],
4228
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("aux.totalCount", { count: aux.total.requests.toLocaleString() }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
4463
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("aux.totalCount", { count: auxCallCount(aux.total).toLocaleString() }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
4229
4464
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
4230
4465
  className: OverheadRows_module_css_default["onumsCost"],
4231
4466
  children: costText(aux.cost)
@@ -4233,7 +4468,7 @@ window.__ModuleLoader__.load({
4233
4468
  " · ",
4234
4469
  formatTokens(totalTokens$1(aux.total))
4235
4470
  ] })]
4236
- })] });
4471
+ }) : null] });
4237
4472
  }
4238
4473
  // src/project-rows.ts
4239
4474
  function totalTokens(totals) {
@@ -4244,6 +4479,25 @@ window.__ModuleLoader__.load({
4244
4479
  const parts = cwd.split(/[\\/]/u).filter((part) => part !== "");
4245
4480
  return parts[parts.length - 1] ?? cwd;
4246
4481
  }
4482
+ /** The dsh-worktree plugin's project-internal layout marker: a checkout
4483
+ * at `<repo>/.dsh/gitworktree/<branch>` belongs to `<repo>`. Matches the
4484
+ * branch segment (never the bare layout root) and everything under it,
4485
+ * on either separator. */
4486
+ const WORKTREE_LAYOUT = /[/\\]\.dsh[/\\]gitworktree[/\\][^/\\]+/u;
4487
+ /**
4488
+ * Map a session cwd onto the repository it belongs to for project
4489
+ * aggregation: a `<repo>/.dsh/gitworktree/<branch>` checkout (the
4490
+ * dsh-worktree plugin's project layout, deeper subdirectories included)
4491
+ * folds onto its repository root, so worktree sessions join the
4492
+ * repository's own project row instead of surfacing as a project of
4493
+ * their own. Any other path returns unchanged. Pure string work — the
4494
+ * host fold and the browser's older-host fallback must share one rule,
4495
+ * and neither can probe the disk.
4496
+ */
4497
+ function belongedCwdOf(cwd) {
4498
+ const match = WORKTREE_LAYOUT.exec(cwd);
4499
+ return match === null ? cwd : cwd.slice(0, match.index);
4500
+ }
4247
4501
  /** Element-wise totals sum: the counted fields add, the optional ones
4248
4502
  * treat absence as 0 and stay absent only while both sides lack them. */
4249
4503
  function addTotals(left, right) {
@@ -4277,28 +4531,32 @@ window.__ModuleLoader__.load({
4277
4531
  * Fold session rows into one row per directory tail, token-descending (the
4278
4532
  * dashboard's relative bars take the first row as their 100%). The tail is
4279
4533
  * the bucket key — two different full paths ending in the same segment read
4280
- * as one project here, matching the demo's semantics. Within a bucket the
4281
- * first-seen cwd rides along as the representative full path. The input
4282
- * order is preserved inside a bucket (the served rows arrive cost-sorted).
4534
+ * as one project here, matching the demo's semantics — and a worktree
4535
+ * checkout (`<repo>/.dsh/gitworktree/<branch>`, see {@link belongedCwdOf})
4536
+ * folds onto its repository before the tail is taken, so its sessions join
4537
+ * the repository's project. Within a bucket the first-seen (belonged) cwd
4538
+ * rides along as the representative full path. The input order is preserved
4539
+ * inside a bucket (the served rows arrive cost-sorted).
4283
4540
  * @param rows - subtree-folded root sessions; the host supplies the full
4284
4541
  * set, not the truncated session list.
4285
4542
  */
4286
4543
  function projectRowsOf(rows) {
4287
4544
  const buckets = /* @__PURE__ */ new Map();
4288
4545
  for (const row of rows) {
4289
- const name = row.cwd === void 0 ? "" : dirTailOf(row.cwd);
4546
+ const owned = row.cwd === void 0 ? void 0 : belongedCwdOf(row.cwd);
4547
+ const name = owned === void 0 ? "" : dirTailOf(owned);
4290
4548
  const bucket = buckets.get(name);
4291
4549
  if (bucket === void 0) {
4292
4550
  buckets.set(name, {
4293
4551
  name,
4294
- ...row.cwd === void 0 ? {} : { cwd: row.cwd },
4552
+ ...owned === void 0 ? {} : { cwd: owned },
4295
4553
  sessionCount: 1,
4296
4554
  totals: { ...row.totals },
4297
4555
  cost: row.cost
4298
4556
  });
4299
4557
  continue;
4300
4558
  }
4301
- if (bucket.cwd === void 0 && row.cwd !== void 0) bucket.cwd = row.cwd;
4559
+ if (bucket.cwd === void 0 && owned !== void 0) bucket.cwd = owned;
4302
4560
  bucket.sessionCount += 1;
4303
4561
  bucket.totals = addTotals(bucket.totals, row.totals);
4304
4562
  bucket.cost += row.cost;
@@ -4742,7 +5000,7 @@ window.__ModuleLoader__.load({
4742
5000
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4743
5001
  className: UsageRows_module_css_default["rowSub"],
4744
5002
  children: [
4745
- session.cwd === void 0 ? t("session.untitledDir") : dirTailOf(session.cwd),
5003
+ session.cwd === void 0 ? t("session.untitledDir") : dirTailOf(belongedCwdOf(session.cwd)),
4746
5004
  " · ",
4747
5005
  relativeTimeOf(session.lastTime, t)
4748
5006
  ]
@@ -4789,7 +5047,7 @@ window.__ModuleLoader__.load({
4789
5047
  * providers on the second, runtime overhead on the last. The lists cap
4790
5048
  * their own height and scroll inside the cards.
4791
5049
  */
4792
- function DashboardCards({ projectRows, modelRows, sessionRows, projectSort, onProjectSortChange, modelSort, onModelSortChange, modelPerfView, onModelPerfToggle, providerRows, providerNames, providerSort, onProviderSortChange, sessionSort, onSessionSortChange, aux, pricing, costState, view, t, sessionListed, onSessionOpen, onToggleModel, onModelName, overheadCardRef, overheadFlash }) {
5050
+ function DashboardCards({ projectRows, modelRows, sessionRows, projectSort, onProjectSortChange, modelSort, onModelSortChange, modelPerfView, onModelPerfToggle, providerRows, providerNames, providerSort, onProviderSortChange, sessionSort, onSessionSortChange, aux, web, pricing, costState, view, t, sessionListed, onSessionOpen, onToggleModel, onModelName, overheadCardRef, overheadFlash }) {
4793
5051
  const namedProviderCount = providerRows.filter((row) => row.provider !== "").length;
4794
5052
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
4795
5053
  className: DashboardCards_module_css_default["grid2"],
@@ -4933,6 +5191,7 @@ window.__ModuleLoader__.load({
4933
5191
  })
4934
5192
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OverheadRows, {
4935
5193
  aux,
5194
+ web,
4936
5195
  costState,
4937
5196
  view,
4938
5197
  t
@@ -5961,14 +6220,14 @@ window.__ModuleLoader__.load({
5961
6220
  failuresByCode: total.failuresByCode,
5962
6221
  ...compact ? {
5963
6222
  labelExtra: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OverheadPill, {
5964
- requests: aux?.total.requests,
6223
+ requests: aux !== void 0 ? auxCallCount(aux.total) : void 0,
5965
6224
  byKind: aux?.byKind,
5966
6225
  onActivate: onOverheadActivate,
5967
6226
  t
5968
6227
  }),
5969
6228
  failureBare: true
5970
6229
  } : {
5971
- overheadRequests: aux?.total.requests,
6230
+ overheadRequests: aux !== void 0 ? auxCallCount(aux.total) : void 0,
5972
6231
  overheadByKind: aux?.byKind,
5973
6232
  onOverheadActivate
5974
6233
  },
@@ -7082,7 +7341,8 @@ window.__ModuleLoader__.load({
7082
7341
  const { total } = state.value;
7083
7342
  const view = currencyViewOf(state.value);
7084
7343
  const projectRows = state.value.projectRows ?? projectRowsOf(state.value.sessionRows ?? []);
7085
- const auxRequests = state.value.aux?.total.requests ?? 0;
7344
+ const auxRequests = state.value.aux !== void 0 ? auxCallCount(state.value.aux.total) : 0;
7345
+ const webCalls = state.value.web?.calls ?? 0;
7086
7346
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
7087
7347
  ref: rootRef,
7088
7348
  className: rootClass,
@@ -7148,6 +7408,7 @@ window.__ModuleLoader__.load({
7148
7408
  sessionSort,
7149
7409
  onSessionSortChange: setSessionSort,
7150
7410
  aux: state.value.aux,
7411
+ web: state.value.web,
7151
7412
  pricing: state.value.pricing,
7152
7413
  costState: state.value.costState,
7153
7414
  view,
@@ -7160,7 +7421,7 @@ window.__ModuleLoader__.load({
7160
7421
  onModelName: setDetailModel,
7161
7422
  overheadCardRef,
7162
7423
  overheadFlash
7163
- }) : state.value.byModel.length > 0 || (state.value.sessionRows?.length ?? 0) > 0 || auxRequests > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
7424
+ }) : state.value.byModel.length > 0 || (state.value.sessionRows?.length ?? 0) > 0 || auxRequests > 0 || webCalls > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
7164
7425
  className: TokenUsageSection_module_css_default["detailPanel"],
7165
7426
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
7166
7427
  className: TokenUsageSection_module_css_default["detailToolbar"],
@@ -7198,6 +7459,7 @@ window.__ModuleLoader__.load({
7198
7459
  className: TokenUsageSection_module_css_default["detailBody"],
7199
7460
  children: detailMode === "aux" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OverheadRows, {
7200
7461
  aux: state.value.aux,
7462
+ web: state.value.web,
7201
7463
  costState: state.value.costState,
7202
7464
  view,
7203
7465
  t
@@ -7284,7 +7546,7 @@ window.__ModuleLoader__.load({
7284
7546
  });
7285
7547
  }
7286
7548
  // \0dsh-css:/home/runner/work/dsh-token-usage/dsh-token-usage/src/client/UsageView.module.css.mjs
7287
- const css = ".PR9kTG_root{color:var(--dsw-alias-label-primary);box-sizing:border-box;width:100%;padding:12px calc(var(--dsh-composer-side-clearance,16px) + 16px);padding-bottom:calc(var(--dsh-composer-height,152px) + 16px);flex-direction:column;gap:12px;max-width:1400px;height:100%;min-height:0;margin:0 auto;display:flex;overflow-y:auto;container:PR9kTG_usage/inline-size}.PR9kTG_root>*{flex-shrink:0}.PR9kTG_head{flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:12px;display:flex}.PR9kTG_headRight{align-items:center;gap:10px;display:flex}.PR9kTG_back{border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border-radius:6px;padding:3px 10px;font-size:12px}.PR9kTG_back:hover{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-border-l2)}.PR9kTG_segmented{border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-fill-container,transparent);border-radius:8px;align-items:stretch;gap:2px;padding:2px;display:inline-flex}.PR9kTG_segBtn{color:var(--dsw-alias-label-tertiary,var(--dsw-alias-label-secondary));cursor:pointer;background:0 0;border:none;border-radius:6px;padding:4px 12px;font-size:12px;font-weight:500}.PR9kTG_segBtn:hover:not(.PR9kTG_segActive){color:var(--dsw-alias-label-secondary);background:color-mix(in srgb, var(--dsw-alias-label-primary) 6%, transparent)}.PR9kTG_segBtn:focus-visible{outline:2px solid var(--dsw-alias-border-l2);outline-offset:1px}.PR9kTG_segActive{background:color-mix(in srgb, var(--dsw-alias-label-primary) 16%, transparent);color:var(--dsw-alias-label-primary);font-weight:600}.PR9kTG_muted{color:var(--dsw-alias-label-secondary);margin:0;font-size:12px}.PR9kTG_error{color:var(--dsw-alias-state-error-primary);margin:0;font-size:13px}.PR9kTG_empty{color:var(--dsw-alias-label-secondary);text-align:center;margin:24px 0 0;font-size:13px}.PR9kTG_button{border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border-radius:6px;align-self:flex-start;padding:3px 10px;font-size:12px}.PR9kTG_warning{color:var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-secondary));margin:0;font-size:12px}.PR9kTG_note{color:var(--dsw-alias-label-tertiary);margin:0;font-size:11px}.PR9kTG_cards{grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;display:grid}.PR9kTG_tokenStrip{color:var(--dsw-alias-label-secondary);flex-wrap:wrap;gap:18px;padding:6px 2px 0;font-size:12px;display:flex}.PR9kTG_tokenStrip b{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}.PR9kTG_mid{grid-template-columns:minmax(0,1.2fr) minmax(0,1fr);align-items:start;gap:24px;display:grid}.PR9kTG_chartCol,.PR9kTG_modelCol,.PR9kTG_subagents{flex-direction:column;gap:6px;min-width:0;display:flex}.PR9kTG_subagentsHead,.PR9kTG_chartHead{align-items:center;gap:8px;display:flex}.PR9kTG_subtitle{color:var(--dsw-alias-label-secondary);margin:0;font-size:13px;font-weight:600}.PR9kTG_tableWrap{overflow-x:auto}.PR9kTG_table{border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;min-width:480px;font-size:12px}.PR9kTG_table th,.PR9kTG_table td{text-align:right;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap;padding:4px 6px}.PR9kTG_table tbody tr{transition:background-color .12s}.PR9kTG_table tbody tr:hover{background-color:var(--dsw-interactive-bg-hover)}.PR9kTG_table th{border-bottom:1.5px solid var(--dsw-alias-border-l2);font-weight:600}.PR9kTG_costCol{font-weight:600}.PR9kTG_zeroDim{color:var(--dsw-alias-label-tertiary);opacity:.55}.PR9kTG_table th:first-child,.PR9kTG_table td:first-child,.PR9kTG_modelHead{text-align:left}.PR9kTG_modelCell{font-variant-numeric:normal;text-overflow:ellipsis;max-width:180px;overflow:hidden}.PR9kTG_modelIdentity{align-items:center;gap:4px;max-width:180px;display:inline-flex}.PR9kTG_modelName{text-overflow:ellipsis;min-width:0;overflow:hidden}.PR9kTG_childLink{color:var(--dsw-alias-link-primary,var(--dsw-alias-label-primary));cursor:pointer;text-align:left;text-overflow:ellipsis;white-space:nowrap;background:0 0;border:none;max-width:220px;padding:0;font-size:12px;overflow:hidden}.PR9kTG_childLink:hover{text-decoration:underline}.PR9kTG_nestedBadge{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;margin-left:6px;font-size:11px}.PR9kTG_poolSection{flex-direction:column;gap:6px;min-width:0;margin-top:4px;display:flex}.PR9kTG_poolHead{flex-wrap:wrap;justify-content:space-between;align-items:baseline;gap:8px 12px;display:flex}.PR9kTG_poolContext{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;font-size:11px}.PR9kTG_poolEmpty{color:var(--dsw-alias-label-secondary);padding:12px 0;font-size:12px}.PR9kTG_latestPanel{border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-fill-container,transparent);border-radius:9px;min-width:0;padding:14px 16px}.PR9kTG_requestIdentity{flex-wrap:wrap;align-items:center;gap:6px 10px;min-width:0;display:flex}.PR9kTG_poolBadge{border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);white-space:nowrap;border-radius:5px;flex:none;padding:1px 7px;font-size:11px}.PR9kTG_poolState{white-space:nowrap;font-size:11px}.PR9kTG_requestIdentity .PR9kTG_poolState{align-items:center;gap:5px;display:inline-flex}.PR9kTG_statusDot{background:currentColor;border-radius:50%;flex:none;width:5px;height:5px}.PR9kTG_latestPanel .PR9kTG_modelName{font-size:13px;font-weight:500}.PR9kTG_stateDone{color:var(--dsw-alias-state-success-primary,#16a34a)}.PR9kTG_stateFailed{color:var(--dsw-alias-state-error-primary,#dc2626)}.PR9kTG_statePending{color:light-dark(#b45309,#d9ac64)}.PR9kTG_stateStreaming{color:var(--dsw-alias-link-primary,var(--dsw-alias-label-primary))}.PR9kTG_modelInline{white-space:nowrap;align-items:center;gap:6px;min-width:0;max-width:100%;display:inline-flex}.PR9kTG_cacheLoss{color:light-dark(#b45309,#d9ac64);white-space:nowrap;background:light-dark(#fff1d8,#352b1d);border-radius:4px;flex:none;align-items:center;gap:4px;padding:2px 6px;font-size:11px;display:inline-flex}.PR9kTG_cacheLoss svg{flex:none;width:12px;height:12px}.PR9kTG_auxKind{border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);white-space:nowrap;border-radius:4px;flex:none;padding:2px 5px;font-size:10px}.PR9kTG_requestMetrics{grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;padding:13px 0;display:grid}.PR9kTG_metricValue{letter-spacing:-.25px;white-space:nowrap;font-variant-numeric:tabular-nums;font-size:23px;font-weight:500}.PR9kTG_metricUnit{color:var(--dsw-alias-label-tertiary);letter-spacing:0;margin-left:4px;font-size:11px}.PR9kTG_metricLabel{color:var(--dsw-alias-label-tertiary);margin-top:2px;font-size:11px}.PR9kTG_requestFooter{border-top:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);flex-wrap:nowrap;justify-content:space-between;align-items:baseline;gap:8px 18px;padding-top:8px;font-size:11px;display:flex}.PR9kTG_requestBuckets{flex-wrap:wrap;flex:none;gap:8px 15px;display:flex}.PR9kTG_requestNote{white-space:nowrap;text-overflow:ellipsis;color:light-dark(#b45309,#d9ac64);flex:0 auto;min-width:0;margin:0;font-size:11px;overflow:hidden}.PR9kTG_requestNoteError{color:var(--dsw-alias-state-error-primary)}.PR9kTG_requestNoteNeutral{color:var(--dsw-alias-label-tertiary)}.PR9kTG_requestFooter b{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;font-weight:400}.PR9kTG_poolNotice{color:light-dark(#b45309,#d9ac64);margin:4px 0 0;font-size:11px}.PR9kTG_poolTableWrap{overscroll-behavior:contain;max-height:196px;overflow:auto}.PR9kTG_poolTableWrap::-webkit-scrollbar{width:8px;height:8px}.PR9kTG_poolTableWrap::-webkit-scrollbar-track,.PR9kTG_poolTableWrap::-webkit-scrollbar-corner{background:0 0}.PR9kTG_poolTableWrap::-webkit-scrollbar-button{display:none}.PR9kTG_poolTableWrap::-webkit-scrollbar-thumb{background:0 0;border-radius:4px}.PR9kTG_poolTableWrap.PR9kTG_scrolling::-webkit-scrollbar-thumb{background:color-mix(in srgb, var(--dsw-alias-label-primary) 12%, transparent)}.PR9kTG_poolTableWrap:focus-visible{outline:2px solid var(--dsw-alias-border-l2);outline-offset:2px}.PR9kTG_poolTable{table-layout:fixed;border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;font-size:11px}.PR9kTG_poolTable th,.PR9kTG_poolTable td{text-align:right;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap;padding:8px 6px;overflow:hidden}.PR9kTG_poolTable th{z-index:1;background:var(--dsw-alias-bg-base,var(--dsw-alias-bg-layer-1));color:var(--dsw-alias-label-secondary);border-bottom:1.5px solid var(--dsw-alias-border-l2);padding:6px;font-weight:400;position:sticky;top:0}.PR9kTG_poolTable th:nth-child(-n+4),.PR9kTG_poolTable td:nth-child(-n+4){text-align:left}.PR9kTG_poolOrigin,.PR9kTG_poolTime{color:var(--dsw-alias-label-secondary)}.PR9kTG_poolModel,.PR9kTG_poolModel .PR9kTG_modelInline{max-width:200px}.PR9kTG_poolModel .PR9kTG_modelName{text-overflow:ellipsis;min-width:0;overflow:hidden}.PR9kTG_poolModelHead{text-align:left}.PR9kTG_poolTable tbody tr:hover{background-color:var(--dsw-interactive-bg-hover)}@media (prefers-reduced-motion:no-preference){.PR9kTG_latestPanel{animation:.25s ease-out PR9kTG_pool-arrive}@keyframes PR9kTG_pool-arrive{0%{opacity:.4}to{opacity:1}}}@container PR9kTG_usage (width<=900px){.PR9kTG_requestMetrics{grid-template-columns:repeat(3,minmax(0,1fr))}.PR9kTG_poolTableWrap{max-height:230px}}@container PR9kTG_usage (width<=480px){.PR9kTG_poolTableWrap{max-height:240px}.PR9kTG_poolTable thead{display:none}.PR9kTG_poolTable,.PR9kTG_poolTable tbody{min-width:0;display:block}.PR9kTG_poolTable tbody tr{border-bottom:1px solid var(--dsw-alias-border-l1);grid-template-columns:repeat(3,minmax(0,1fr));gap:4px 9px;padding:9px 0;display:grid}.PR9kTG_poolTable td{border-bottom:none;text-align:left!important;padding:0!important}.PR9kTG_poolTable td:nth-child(4){grid-column:1/-1}.PR9kTG_poolTable td:before{content:attr(data-label) \" \";color:var(--dsw-alias-label-tertiary)}.PR9kTG_poolModel,.PR9kTG_poolModel .PR9kTG_modelInline{max-width:100%}.PR9kTG_metricValue{font-size:21px}}@container PR9kTG_usage (width<=900px){.PR9kTG_cards{grid-template-columns:repeat(3,minmax(0,1fr))}.PR9kTG_mid{grid-template-columns:1fr}}@media (width<=600px){.PR9kTG_root{padding-left:12px;padding-right:12px}}";
7549
+ const css = ".PR9kTG_root{color:var(--dsw-alias-label-primary);box-sizing:border-box;width:100%;padding:12px calc(var(--dsh-composer-side-clearance,16px) + 16px);padding-bottom:calc(var(--dsh-composer-height,152px) + 16px);flex-direction:column;gap:12px;max-width:1400px;height:100%;min-height:0;margin:0 auto;display:flex;overflow-y:auto;container:PR9kTG_usage/inline-size}.PR9kTG_root>*{flex-shrink:0}.PR9kTG_head{flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:12px;display:flex}.PR9kTG_headRight{align-items:center;gap:10px;display:flex}.PR9kTG_back{border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border-radius:6px;padding:3px 10px;font-size:12px}.PR9kTG_back:hover{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-border-l2)}.PR9kTG_segmented{border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-fill-container,transparent);border-radius:8px;align-items:stretch;gap:2px;padding:2px;display:inline-flex}.PR9kTG_segBtn{color:var(--dsw-alias-label-tertiary,var(--dsw-alias-label-secondary));cursor:pointer;background:0 0;border:none;border-radius:6px;padding:4px 12px;font-size:12px;font-weight:500}.PR9kTG_segBtn:hover:not(.PR9kTG_segActive){color:var(--dsw-alias-label-secondary);background:color-mix(in srgb, var(--dsw-alias-label-primary) 6%, transparent)}.PR9kTG_segBtn:focus-visible{outline:2px solid var(--dsw-alias-border-l2);outline-offset:1px}.PR9kTG_segActive{background:color-mix(in srgb, var(--dsw-alias-label-primary) 16%, transparent);color:var(--dsw-alias-label-primary);font-weight:600}.PR9kTG_muted{color:var(--dsw-alias-label-secondary);margin:0;font-size:12px}.PR9kTG_error{color:var(--dsw-alias-state-error-primary);margin:0;font-size:13px}.PR9kTG_empty{color:var(--dsw-alias-label-secondary);text-align:center;margin:24px 0 0;font-size:13px}.PR9kTG_button{border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border-radius:6px;align-self:flex-start;padding:3px 10px;font-size:12px}.PR9kTG_warning{color:var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-secondary));margin:0;font-size:12px}.PR9kTG_note{color:var(--dsw-alias-label-tertiary);margin:0;font-size:11px}.PR9kTG_cards{grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;display:grid}.PR9kTG_tokenStrip{color:var(--dsw-alias-label-secondary);flex-wrap:wrap;gap:18px;padding:6px 2px 0;font-size:12px;display:flex}.PR9kTG_tokenStrip b{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}.PR9kTG_mid{grid-template-columns:minmax(0,1.2fr) minmax(0,1fr);align-items:start;gap:24px;display:grid}.PR9kTG_chartCol,.PR9kTG_modelCol,.PR9kTG_subagents{flex-direction:column;gap:6px;min-width:0;display:flex}.PR9kTG_subagentsHead,.PR9kTG_chartHead{align-items:center;gap:8px;display:flex}.PR9kTG_subtitle{color:var(--dsw-alias-label-secondary);margin:0;font-size:13px;font-weight:600}.PR9kTG_tableWrap{overflow-x:auto}.PR9kTG_table{border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;min-width:480px;font-size:12px}.PR9kTG_table th,.PR9kTG_table td{text-align:right;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap;padding:4px 6px}.PR9kTG_table tbody tr{transition:background-color .12s}.PR9kTG_table tbody tr:hover{background-color:var(--dsw-interactive-bg-hover)}.PR9kTG_table th{border-bottom:1.5px solid var(--dsw-alias-border-l2);font-weight:600}.PR9kTG_subagentsWrap{--subagents-row-height:26px;max-height:calc(var(--subagents-row-height) * 16);overflow:hidden}.PR9kTG_subagentsWrap:focus-within{overflow:auto}.PR9kTG_subagentsWrap::-webkit-scrollbar{width:8px;height:8px}.PR9kTG_subagentsWrap::-webkit-scrollbar-track,.PR9kTG_subagentsWrap::-webkit-scrollbar-corner{background:0 0}.PR9kTG_subagentsWrap::-webkit-scrollbar-button{display:none}.PR9kTG_subagentsWrap::-webkit-scrollbar-thumb{background:0 0;border-radius:4px}.PR9kTG_subagentsWrap:focus-within::-webkit-scrollbar-thumb{background:color-mix(in srgb, var(--dsw-alias-label-primary) 12%, transparent)}.PR9kTG_subagentsWrap:focus-within.PR9kTG_scrolling::-webkit-scrollbar-thumb{background:color-mix(in srgb, var(--dsw-alias-label-primary) 22%, transparent)}.PR9kTG_subagentsWrap:focus-visible{outline:2px solid var(--dsw-alias-border-l2);outline-offset:2px}.PR9kTG_subagentsWrap .PR9kTG_table thead tr,.PR9kTG_subagentsWrap .PR9kTG_table tbody tr{height:var(--subagents-row-height)}.PR9kTG_subagentsWrap .PR9kTG_table th{z-index:1;background:var(--dsw-alias-bg-base,var(--dsw-alias-bg-layer-1));position:sticky;top:0}.PR9kTG_costCol{font-weight:600}.PR9kTG_zeroDim{color:var(--dsw-alias-label-tertiary);opacity:.55}.PR9kTG_table th:first-child,.PR9kTG_table td:first-child,.PR9kTG_modelHead{text-align:left}.PR9kTG_modelCell{font-variant-numeric:normal;text-overflow:ellipsis;max-width:180px;overflow:hidden}.PR9kTG_modelIdentity{align-items:center;gap:4px;max-width:180px;display:inline-flex}.PR9kTG_modelName{text-overflow:ellipsis;min-width:0;overflow:hidden}.PR9kTG_childLink{color:var(--dsw-alias-link-primary,var(--dsw-alias-label-primary));cursor:pointer;text-align:left;text-overflow:ellipsis;white-space:nowrap;background:0 0;border:none;max-width:220px;padding:0;font-size:12px;overflow:hidden}.PR9kTG_childLink:hover{text-decoration:underline}.PR9kTG_nestedBadge{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;margin-left:6px;font-size:11px}.PR9kTG_poolSection{flex-direction:column;gap:6px;min-width:0;margin-top:4px;display:flex}.PR9kTG_poolHead{flex-wrap:wrap;justify-content:space-between;align-items:baseline;gap:8px 12px;display:flex}.PR9kTG_poolContext{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;font-size:11px}.PR9kTG_poolEmpty{color:var(--dsw-alias-label-secondary);padding:12px 0;font-size:12px}.PR9kTG_latestPanel{border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-fill-container,transparent);border-radius:9px;min-width:0;padding:14px 16px}.PR9kTG_requestIdentity{flex-wrap:wrap;align-items:center;gap:6px 10px;min-width:0;display:flex}.PR9kTG_poolBadge{border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);white-space:nowrap;border-radius:5px;flex:none;padding:1px 7px;font-size:11px}.PR9kTG_poolState{white-space:nowrap;font-size:11px}.PR9kTG_requestIdentity .PR9kTG_poolState{align-items:center;gap:5px;display:inline-flex}.PR9kTG_statusDot{background:currentColor;border-radius:50%;flex:none;width:5px;height:5px}.PR9kTG_latestPanel .PR9kTG_modelName{font-size:13px;font-weight:500}.PR9kTG_stateDone{color:var(--dsw-alias-state-success-primary,#16a34a)}.PR9kTG_stateFailed{color:var(--dsw-alias-state-error-primary,#dc2626)}.PR9kTG_statePending{color:light-dark(#b45309,#d9ac64)}.PR9kTG_stateStreaming{color:var(--dsw-alias-link-primary,var(--dsw-alias-label-primary))}.PR9kTG_modelInline{white-space:nowrap;align-items:center;gap:6px;min-width:0;max-width:100%;display:inline-flex}.PR9kTG_cacheLoss{color:light-dark(#b45309,#d9ac64);white-space:nowrap;background:light-dark(#fff1d8,#352b1d);border-radius:4px;flex:none;align-items:center;gap:4px;padding:2px 6px;font-size:11px;display:inline-flex}.PR9kTG_cacheLoss svg{flex:none;width:12px;height:12px}.PR9kTG_auxKind{border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);white-space:nowrap;border-radius:4px;flex:none;padding:2px 5px;font-size:10px}.PR9kTG_requestMetrics{grid-template-columns:repeat(6,minmax(0,1fr));gap:12px;padding:13px 0;display:grid}.PR9kTG_metricValue{letter-spacing:-.25px;white-space:nowrap;font-variant-numeric:tabular-nums;font-size:23px;font-weight:500}.PR9kTG_metricUnit{color:var(--dsw-alias-label-tertiary);letter-spacing:0;margin-left:4px;font-size:11px}.PR9kTG_metricLabel{color:var(--dsw-alias-label-tertiary);margin-top:2px;font-size:11px}.PR9kTG_requestFooter{border-top:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);flex-wrap:nowrap;justify-content:space-between;align-items:baseline;gap:8px 18px;padding-top:8px;font-size:11px;display:flex}.PR9kTG_requestBuckets{flex-wrap:wrap;flex:none;gap:8px 15px;display:flex}.PR9kTG_requestNote{white-space:nowrap;text-overflow:ellipsis;color:light-dark(#b45309,#d9ac64);flex:0 auto;min-width:0;margin:0;font-size:11px;overflow:hidden}.PR9kTG_requestNoteError{color:var(--dsw-alias-state-error-primary)}.PR9kTG_requestNoteNeutral{color:var(--dsw-alias-label-tertiary)}.PR9kTG_requestFooter b{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;font-weight:400}.PR9kTG_poolNotice{color:light-dark(#b45309,#d9ac64);margin:4px 0 0;font-size:11px}.PR9kTG_poolTableWrap{overscroll-behavior:contain;max-height:196px;overflow:auto}.PR9kTG_poolTableWrap::-webkit-scrollbar{width:8px;height:8px}.PR9kTG_poolTableWrap::-webkit-scrollbar-track,.PR9kTG_poolTableWrap::-webkit-scrollbar-corner{background:0 0}.PR9kTG_poolTableWrap::-webkit-scrollbar-button{display:none}.PR9kTG_poolTableWrap::-webkit-scrollbar-thumb{background:0 0;border-radius:4px}.PR9kTG_poolTableWrap.PR9kTG_scrolling::-webkit-scrollbar-thumb{background:color-mix(in srgb, var(--dsw-alias-label-primary) 12%, transparent)}.PR9kTG_poolTableWrap:focus-visible{outline:2px solid var(--dsw-alias-border-l2);outline-offset:2px}.PR9kTG_poolTable{table-layout:fixed;border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;font-size:11px}.PR9kTG_poolTable th,.PR9kTG_poolTable td{text-align:right;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap;padding:8px 6px;overflow:hidden}.PR9kTG_poolTable th{z-index:1;background:var(--dsw-alias-bg-base,var(--dsw-alias-bg-layer-1));color:var(--dsw-alias-label-secondary);border-bottom:1.5px solid var(--dsw-alias-border-l2);padding:6px;font-weight:400;position:sticky;top:0}.PR9kTG_poolTable th:nth-child(-n+4),.PR9kTG_poolTable td:nth-child(-n+4){text-align:left}.PR9kTG_poolOrigin,.PR9kTG_poolTime{color:var(--dsw-alias-label-secondary)}.PR9kTG_poolModel,.PR9kTG_poolModel .PR9kTG_modelInline{max-width:200px}.PR9kTG_poolModel .PR9kTG_modelName{text-overflow:ellipsis;min-width:0;overflow:hidden}.PR9kTG_poolModelHead{text-align:left}.PR9kTG_poolTable tbody tr:hover{background-color:var(--dsw-interactive-bg-hover)}@media (prefers-reduced-motion:no-preference){.PR9kTG_latestPanel{animation:.25s ease-out PR9kTG_pool-arrive}@keyframes PR9kTG_pool-arrive{0%{opacity:.4}to{opacity:1}}}@container PR9kTG_usage (width<=900px){.PR9kTG_requestMetrics{grid-template-columns:repeat(3,minmax(0,1fr))}.PR9kTG_poolTableWrap{max-height:230px}}@container PR9kTG_usage (width<=480px){.PR9kTG_poolTableWrap{max-height:240px}.PR9kTG_poolTable thead{display:none}.PR9kTG_poolTable,.PR9kTG_poolTable tbody{min-width:0;display:block}.PR9kTG_poolTable tbody tr{border-bottom:1px solid var(--dsw-alias-border-l1);grid-template-columns:repeat(3,minmax(0,1fr));gap:4px 9px;padding:9px 0;display:grid}.PR9kTG_poolTable td{border-bottom:none;text-align:left!important;padding:0!important}.PR9kTG_poolTable td:nth-child(4){grid-column:1/-1}.PR9kTG_poolTable td:before{content:attr(data-label) \" \";color:var(--dsw-alias-label-tertiary)}.PR9kTG_poolModel,.PR9kTG_poolModel .PR9kTG_modelInline{max-width:100%}.PR9kTG_metricValue{font-size:21px}}@container PR9kTG_usage (width<=900px){.PR9kTG_cards{grid-template-columns:repeat(3,minmax(0,1fr))}.PR9kTG_mid{grid-template-columns:1fr}}@media (width<=600px){.PR9kTG_root{padding-left:12px;padding-right:12px}}";
7288
7550
  const tagId = "@laoyuehanni/dsh-token-usage/UsageView.module.css";
7289
7551
  if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
7290
7552
  const tag = document.createElement("style");
@@ -7354,6 +7616,7 @@ window.__ModuleLoader__.load({
7354
7616
  "statusDot": "PR9kTG_statusDot",
7355
7617
  "subagents": "PR9kTG_subagents",
7356
7618
  "subagentsHead": "PR9kTG_subagentsHead",
7619
+ "subagentsWrap": "PR9kTG_subagentsWrap",
7357
7620
  "subtitle": "PR9kTG_subtitle",
7358
7621
  "table": "PR9kTG_table",
7359
7622
  "tableWrap": "PR9kTG_tableWrap",
@@ -7973,15 +8236,16 @@ window.__ModuleLoader__.load({
7973
8236
  * pill, 4 token buckets, cost, hit rate, TTFT average, decode throughput) with a
7974
8237
  * scope switch between the session alone and its whole subagent subtree, a
7975
8238
  * per-hour trend chart and the per-model table from the host stats route
7976
- * (`sessionId`-scoped), and a subagent table below — each row drill-in
8239
+ * (`root` + `scope` scoped), and a subagent table below — each row drill-in
7977
8240
  * switches the focus to that child.
7978
8241
  *
7979
8242
  * Data sources: token/cost figures come from the host route (the pricing
7980
- * rule chain's authority); TTFT and throughput come from the framework's
7981
- * retained `sessionStats` projection values (`useProjection` for the current
7982
- * session, `byId[].projectionValues` for every other session), which cover
7983
- * the whole log including history written before this plugin was installed.
7984
- * A footnote states the two scopes so the difference is not a surprise.
8243
+ * rule chain's authority). The header's TTFT and throughput come from the
8244
+ * framework's retained `sessionStats` projection (`useProjection`), which
8245
+ * covers history written before this plugin was installed; the SUBAGENT
8246
+ * table's two timing columns instead read `children[].timing`, folded by the
8247
+ * host from recorded requests (post-install, timed requests only). A
8248
+ * footnote states both scopes so the difference is not a surprise.
7985
8249
  *
7986
8250
  * The root declares `data-conversation-composer-overlay` — the same host
7987
8251
  * opt-in Trajectory uses. ConversationRoot hides the chat-column width
@@ -7998,12 +8262,14 @@ window.__ModuleLoader__.load({
7998
8262
  * full-bleed scroller set this so the chat-column width handles hide and
7999
8263
  * the composer seat overlays instead of stealing clicks over the dashboard. */
8000
8264
  const COMPOSER_OVERLAY = { "data-conversation-composer-overlay": "" };
8001
- /** One fetch of the session-scoped summary from the host stats route,
8002
- * including the direct-child breakdown for the subagent table. */
8003
- function fetchSessionSummary(sessionIds, childGroups, signal) {
8265
+ /** One fetch of the session-scoped summary from the host stats route.
8266
+ * The request carries a RANGE RULE (root + scope), never the enumerated
8267
+ * subtree: the host expands it from its session-metadata lineage, so the URL
8268
+ * stays O(1) however many subagents the conversation has. */
8269
+ function fetchSessionSummary(root, scope, signal) {
8004
8270
  return fetch(STATS_PATH + encodeStatsQuery({
8005
- sessionIds,
8006
- childGroups,
8271
+ root,
8272
+ scope: scope === "tree" ? "subtree" : "self",
8007
8273
  fields: "session"
8008
8274
  }), { signal }).then((response) => {
8009
8275
  if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
@@ -8034,6 +8300,19 @@ window.__ModuleLoader__.load({
8034
8300
  setRetryToken((token) => token + 1);
8035
8301
  };
8036
8302
  usePricingAssociationRefresh(retry);
8303
+ const subagentsRef = (0, react.useRef)(null);
8304
+ const subagentsTimer = (0, react.useRef)(void 0);
8305
+ (0, react.useEffect)(() => () => window.clearTimeout(subagentsTimer.current), []);
8306
+ const handleSubagentsScroll = () => {
8307
+ const box = subagentsRef.current;
8308
+ const cls = UsageView_module_css_default["scrolling"];
8309
+ if (box === null || cls === void 0) return;
8310
+ box.classList.add(cls);
8311
+ window.clearTimeout(subagentsTimer.current);
8312
+ subagentsTimer.current = window.setTimeout(() => {
8313
+ box.classList.remove(cls);
8314
+ }, 800);
8315
+ };
8037
8316
  const byId = useSessions((state) => state.byId);
8038
8317
  const childIndex = (0, react.useMemo)(() => buildChildIndex(byId), [byId]);
8039
8318
  const scopeIds = (0, react.useMemo)(() => scope === "tree" ? subtreeIds(byId, focusId, childIndex) : [focusId], [
@@ -8047,20 +8326,17 @@ window.__ModuleLoader__.load({
8047
8326
  focusId,
8048
8327
  childIndex
8049
8328
  ]);
8050
- const childGroups = (0, react.useMemo)(() => children.map((id) => scope === "tree" ? subtreeIds(byId, id, childIndex) : [id]), [
8051
- children,
8052
- scope,
8053
- byId,
8054
- childIndex
8055
- ]);
8056
8329
  const backParent = subagentParentOf(byId, focusId);
8057
8330
  const liveStats = useProjection("sessionStats");
8058
- const freshnessKey = buildStatsFreshnessKey([.../* @__PURE__ */ new Set([...scopeIds, ...children])], {
8331
+ const scopedIds = [.../* @__PURE__ */ new Set([...scopeIds, ...children])];
8332
+ const scopeIdsKey = scopedIds.join(",");
8333
+ const freshnessKey = buildStatsFreshnessKey(scopedIds, {
8059
8334
  activeSessionId: sessionId,
8060
8335
  rows: byId,
8061
8336
  liveSessionStats: liveStats
8062
8337
  });
8063
- const debouncedKey = useDebouncedValue(`${scopeIds.join("\n")}\n\t${childGroups.map((group) => group.join(",")).join(";")}\n\t${freshnessKey}`, REFRESH_DEBOUNCE_MS);
8338
+ const scopeKey = `${focusId}\t${scope}`;
8339
+ const debouncedFreshnessKey = useDebouncedValue(freshnessKey, REFRESH_DEBOUNCE_MS, scopeKey);
8064
8340
  const [pollTick, setPollTick] = (0, react.useState)(0);
8065
8341
  const [pollSettle, setPollSettle] = (0, react.useState)(0);
8066
8342
  const [staleAt, setStaleAt] = (0, react.useState)(void 0);
@@ -8068,19 +8344,33 @@ window.__ModuleLoader__.load({
8068
8344
  const pollTimerRef = (0, react.useRef)(void 0);
8069
8345
  const fetchingRef = (0, react.useRef)(false);
8070
8346
  const fetchVersionRef = (0, react.useRef)(0);
8071
- const scopeKey = `${scopeIds.join("\n")}\n\t${childGroups.map((group) => group.join(",")).join(";")}`;
8347
+ /** The last successful read. A late session-mirror / sessionStats delivery
8348
+ * bumps the freshness key inside the first debounce window and reruns the
8349
+ * effect; coalescing that run avoids two identical GETs on opening the tab. */
8350
+ const recentRef = (0, react.useRef)(void 0);
8072
8351
  const [summaryState] = useAsyncResource((signal) => {
8073
8352
  clearTimeout(pollTimerRef.current);
8074
8353
  fetchingRef.current = true;
8075
8354
  const version = ++fetchVersionRef.current;
8076
- const [idsPart, groupsPart] = scopeKey.split("\n ");
8077
- return fetchSessionSummary((idsPart ?? "").split("\n").filter((id) => id !== ""), (groupsPart ?? "").split(";").filter((group) => group !== "").map((group) => group.split(",")), signal).then((value) => {
8355
+ const recent = recentRef.current;
8356
+ const canReuse = recent !== void 0 && !recent.coalesced && recent.idsKey !== scopeIdsKey && recent.scopeKey === scopeKey && recent.retryToken === retryToken && recent.pollTick === pollTick && Date.now() - recent.at < 500;
8357
+ const settle = (value) => {
8358
+ recentRef.current = {
8359
+ scopeKey,
8360
+ idsKey: scopeIdsKey,
8361
+ retryToken,
8362
+ pollTick,
8363
+ at: Date.now(),
8364
+ value,
8365
+ coalesced: canReuse
8366
+ };
8078
8367
  if (!signal.aborted) {
8079
8368
  lastOkAtRef.current = Date.now();
8080
8369
  setStaleAt(void 0);
8081
8370
  }
8082
8371
  return value;
8083
- }).catch((error) => {
8372
+ };
8373
+ return (canReuse && recent !== void 0 ? Promise.resolve(recent.value) : fetchSessionSummary(focusId, scope, signal)).then(settle).catch((error) => {
8084
8374
  if (!signal.aborted && lastOkAtRef.current !== void 0) setStaleAt(lastOkAtRef.current);
8085
8375
  throw error;
8086
8376
  }).finally(() => {
@@ -8090,7 +8380,7 @@ window.__ModuleLoader__.load({
8090
8380
  }
8091
8381
  });
8092
8382
  }, [
8093
- debouncedKey.split("\n ")[2],
8383
+ debouncedFreshnessKey,
8094
8384
  retryToken,
8095
8385
  pollTick
8096
8386
  ], {
@@ -8122,19 +8412,12 @@ window.__ModuleLoader__.load({
8122
8412
  document.removeEventListener("visibilitychange", onVisibility);
8123
8413
  };
8124
8414
  }, []);
8125
- const stats = (0, react.useMemo)(() => {
8126
- return aggregateProjections(scopeIds.map((id) => {
8127
- if (id === sessionId) return liveStats;
8128
- return byId[id]?.projectionValues?.sessionStats;
8129
- }));
8130
- }, [
8415
+ const mirrorStats = (0, react.useMemo)(() => aggregateScopedProjections(scopeIds, byId, sessionId, liveStats), [
8131
8416
  scopeIds,
8417
+ byId,
8132
8418
  sessionId,
8133
- liveStats,
8134
- byId
8419
+ liveStats
8135
8420
  ]);
8136
- const ttftText = stats !== void 0 && stats.ttftSteps > 0 ? formatTtft(stats.ttftMs / stats.ttftSteps) : "—";
8137
- const speedText = stats !== void 0 && stats.decodeMs > 0 ? formatSpeed(stats.decodeTokens / (stats.decodeMs / 1e3)) : "—";
8138
8421
  const header = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("header", {
8139
8422
  className: UsageView_module_css_default["head"],
8140
8423
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
@@ -8201,6 +8484,15 @@ window.__ModuleLoader__.load({
8201
8484
  })
8202
8485
  });
8203
8486
  const summary = summaryState.value;
8487
+ const headerTiming = resolveHeaderTiming({
8488
+ isSoloActive: scope === "session" && focusId === sessionId,
8489
+ liveStats,
8490
+ mirrorAggregate: mirrorStats,
8491
+ serverTiming: summary.timing,
8492
+ totalPerf: summary.total
8493
+ });
8494
+ const ttftText = headerTiming.ttftMs !== void 0 ? formatTtft(headerTiming.ttftMs) : "—";
8495
+ const speedText = headerTiming.tokensPerSec !== void 0 ? formatSpeed(headerTiming.tokensPerSec) : "—";
8204
8496
  const view = currencyViewOf(summary);
8205
8497
  const { total } = summary;
8206
8498
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
@@ -8436,7 +8728,12 @@ window.__ModuleLoader__.load({
8436
8728
  className: UsageView_module_css_default["muted"],
8437
8729
  children: t("view.subagents.none")
8438
8730
  }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
8439
- className: UsageView_module_css_default["tableWrap"],
8731
+ ref: subagentsRef,
8732
+ onScroll: handleSubagentsScroll,
8733
+ className: UsageView_module_css_default["subagentsWrap"],
8734
+ tabIndex: 0,
8735
+ role: "region",
8736
+ "aria-label": t("view.subagents.scroll"),
8440
8737
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
8441
8738
  className: UsageView_module_css_default["table"],
8442
8739
  "aria-label": t("view.subagents.title", { count: String(children.length) }),
@@ -8454,7 +8751,7 @@ window.__ModuleLoader__.load({
8454
8751
  ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: children.map((id) => {
8455
8752
  const child = byId[id];
8456
8753
  const row = summary.children?.[id];
8457
- const childStats = aggregateProjections([byId[id]?.projectionValues?.sessionStats]);
8754
+ const timing = row?.timing;
8458
8755
  const nestedCount = directSubagentIds(byId, id, childIndex).length;
8459
8756
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
8460
8757
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("td", {
@@ -8481,8 +8778,8 @@ window.__ModuleLoader__.load({
8481
8778
  children: row !== void 0 && costsAvailable(summary.costState) && costsAvailable(row.costState) ? formatCost(row.totalCost, view) : "—"
8482
8779
  }),
8483
8780
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HitRateText, { totals: row.total }) : "—" }),
8484
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: childStats !== void 0 && childStats.ttftSteps > 0 ? formatTtft(childStats.ttftMs / childStats.ttftSteps) : "—" }),
8485
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: childStats !== void 0 && childStats.decodeMs > 0 ? `${formatSpeed(childStats.decodeTokens / (childStats.decodeMs / 1e3))} tok/s` : "—" })
8781
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: timing !== void 0 && timing.ttftSteps > 0 ? formatTtft(timing.ttftMs / timing.ttftSteps) : "—" }),
8782
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: timing !== void 0 && timing.decodeMs > 0 ? `${formatSpeed(timing.decodeTokens / (timing.decodeMs / 1e3))} tok/s` : "—" })
8486
8783
  ] }, id);
8487
8784
  }) })]
8488
8785
  })
@@ -8588,15 +8885,31 @@ window.__ModuleLoader__.load({
8588
8885
  "fail.TIMEOUT": "超时",
8589
8886
  "fail.TRANSPORT": "网络异常",
8590
8887
  "fail.EMPTY_RESPONSE": "空响应",
8888
+ "fail.CONTENT_REFUSED": "内容安全拒绝",
8591
8889
  "fail.QUOTA": "配额耗尽",
8890
+ "fail.ACCOUNT_QUOTA": "账号余额不足",
8891
+ "fail.ACCOUNT_SIGN_IN_REQUIRED": "需要登录账号",
8892
+ "fail.ACCOUNT_TOKEN_INVALID": "账号凭证无效",
8893
+ "fail.CLIENT_UPGRADE_REQUIRED": "需要升级客户端",
8592
8894
  "fail.CONTEXT_WINDOW_EXCEEDED": "上下文超限",
8593
8895
  "fail.INVALID_CREDENTIAL": "凭证无效",
8594
8896
  "fail.AUTH": "鉴权失败",
8595
8897
  "fail.INVALID_REQUEST": "请求无效",
8898
+ "fail.INVALID_RESPONSE": "响应无效",
8596
8899
  "fail.MISSING_CREDENTIAL": "缺少凭证",
8597
8900
  "fail.ABORTED": "已中止",
8598
8901
  "fail.REQUEST_EXTENSION": "请求扩展失败",
8902
+ "fail.REQUEST_HEADERS": "请求头异常",
8599
8903
  "fail.FILES_API": "文件接口异常",
8904
+ "fail.IMAGE_OFFLOAD_REQUIRED": "图片需转存",
8905
+ "fail.MODEL_SWITCH_COMPACTION_FAILED": "切模型压缩失败",
8906
+ "fail.MODEL_UNSUPPORTED": "模型不支持",
8907
+ "fail.UNKNOWN_MODEL": "未知模型",
8908
+ "fail.NO_ADAPTER": "未注册适配器",
8909
+ "fail.PI_AI_ERROR": "适配器异常",
8910
+ "fail.UNSUPPORTED_CONTENT": "不支持的内容",
8911
+ "fail.UNSUPPORTED_OPTION": "不支持的参数",
8912
+ "fail.UNSUPPORTED_REASONING_EFFORT": "不支持的推理强度",
8600
8913
  "fail.STREAM_CLOSED": "流中断",
8601
8914
  "fail.MALFORMED_RESPONSE": "响应异常",
8602
8915
  "fail.UNKNOWN": "未知错误",
@@ -8628,6 +8941,7 @@ window.__ModuleLoader__.load({
8628
8941
  "aux.kind": "类别",
8629
8942
  "aux.kind.auto-review": "自动审查",
8630
8943
  "aux.kind.session-title": "标题生成",
8944
+ "aux.kind.timeline-report": "时间线报告",
8631
8945
  "aux.kind.translation": "推理翻译",
8632
8946
  "aux.kind.other": "其他",
8633
8947
  "aux.requests": "次数",
@@ -8637,6 +8951,10 @@ window.__ModuleLoader__.load({
8637
8951
  "aux.totalCount": "合计 · {count} 次",
8638
8952
  "aux.requestCount": "{count} 次",
8639
8953
  "aux.tooltipTotal": "运行开销 · 合计",
8954
+ "web.title": "联网工具",
8955
+ "web.tool.web_search": "联网搜索",
8956
+ "web.tool.web_fetch": "网页抓取",
8957
+ "web.calls": "{count} 次",
8640
8958
  "board.projects": "项目",
8641
8959
  "board.sessions": "会话",
8642
8960
  "board.models": "模型",
@@ -8721,6 +9039,8 @@ window.__ModuleLoader__.load({
8721
9039
  "card.overridden": "已覆盖默认值",
8722
9040
  "card.sidebarPinned.label": "常驻侧边栏",
8723
9041
  "card.sidebarPinned.hint": "开启后「Token 用量」固定为左侧边栏的一行,「更多」菜单中的入口随之移除;关闭后从「更多」菜单进入。更改随「保存」生效。",
9042
+ "card.settingsSectionEnabled.label": "在设置中显示 Token 用量",
9043
+ "card.settingsSectionEnabled.hint": "开启后在「设置 → Token 用量」中展示统计页;关闭后隐藏设置内的该扩展页(侧边栏入口与会话「用量」页签不受影响)。更改随「保存」生效。",
8724
9044
  "card.save": "保存",
8725
9045
  "card.saving": "保存中…",
8726
9046
  "card.saveFailed": "保存未生效,请重试。",
@@ -8732,6 +9052,7 @@ window.__ModuleLoader__.load({
8732
9052
  "card.fullSync.running": "扫描中…",
8733
9053
  "card.fullSync.progress": "已处理 {processed}/{total} 个 session,新增 {added} 条,跳过 {skipped} 条,删除 {removed} 条",
8734
9054
  "card.fullSync.failuresNote": ",无法读取 {count} 个 session 已跳过",
9055
+ "card.fullSync.importedNote": ",忽略 {count} 条 DeepSeek chat 导入记录",
8735
9056
  "card.fullSync.done": "扫描完成:新增 {added} 条,跳过 {skipped} 条,删除 {removed} 条",
8736
9057
  "card.fullSync.failed": "扫描失败:{error}",
8737
9058
  "loadFailed": "统计加载失败:{message}",
@@ -8761,7 +9082,8 @@ window.__ModuleLoader__.load({
8761
9082
  "view.subagents.none": "无子会话",
8762
9083
  "view.subagents.titleCol": "会话",
8763
9084
  "view.subagents.nested": "含 {count} 个子会话",
8764
- "view.note": "注:token 与费用来自本插件的请求记录(安装后);平均首token 与 token速度来自 DSH 会话投影(含安装前历史)。",
9085
+ "view.subagents.scroll": "子会话列表,点击后可在此滚动",
9086
+ "view.note": "注:token 与费用来自本插件请求记录;当前单会话顶部平均首token 与 token速度优先来自 DSH 会话投影(含无日志历史),含子会话、子会话详情及子会话表来自本插件有计时的请求记录。",
8765
9087
  "pool.latest.title": "最新请求",
8766
9088
  "pool.latest.context": "单次请求 · 非会话均值",
8767
9089
  "pool.title": "实时请求",
@@ -8783,6 +9105,7 @@ window.__ModuleLoader__.load({
8783
9105
  "pool.kind.compaction": "压缩",
8784
9106
  "pool.kind.auto-review": "审查",
8785
9107
  "pool.kind.session-title": "标题",
9108
+ "pool.kind.timeline-report": "时间线",
8786
9109
  "pool.kind.translation": "翻译",
8787
9110
  "pool.kind.other": "辅助",
8788
9111
  "pool.attribution.prefix": "此请求发出前,宿主的压缩操作改写了上下文前缀,缓存表现可能受影响:",
@@ -8954,15 +9277,31 @@ window.__ModuleLoader__.load({
8954
9277
  "fail.TIMEOUT": "Timed out",
8955
9278
  "fail.TRANSPORT": "Network error",
8956
9279
  "fail.EMPTY_RESPONSE": "Empty response",
9280
+ "fail.CONTENT_REFUSED": "Content refused",
8957
9281
  "fail.QUOTA": "Quota exceeded",
9282
+ "fail.ACCOUNT_QUOTA": "Account quota exceeded",
9283
+ "fail.ACCOUNT_SIGN_IN_REQUIRED": "Sign-in required",
9284
+ "fail.ACCOUNT_TOKEN_INVALID": "Account token invalid",
9285
+ "fail.CLIENT_UPGRADE_REQUIRED": "Client upgrade required",
8958
9286
  "fail.CONTEXT_WINDOW_EXCEEDED": "Context exceeded",
8959
9287
  "fail.INVALID_CREDENTIAL": "Invalid credential",
8960
9288
  "fail.AUTH": "Auth failed",
8961
9289
  "fail.INVALID_REQUEST": "Invalid request",
9290
+ "fail.INVALID_RESPONSE": "Invalid response",
8962
9291
  "fail.MISSING_CREDENTIAL": "Missing credential",
8963
9292
  "fail.ABORTED": "Aborted",
8964
9293
  "fail.REQUEST_EXTENSION": "Request extension failed",
9294
+ "fail.REQUEST_HEADERS": "Request headers error",
8965
9295
  "fail.FILES_API": "Files API error",
9296
+ "fail.IMAGE_OFFLOAD_REQUIRED": "Image offload required",
9297
+ "fail.MODEL_SWITCH_COMPACTION_FAILED": "Model switch compaction failed",
9298
+ "fail.MODEL_UNSUPPORTED": "Model unsupported",
9299
+ "fail.UNKNOWN_MODEL": "Unknown model",
9300
+ "fail.NO_ADAPTER": "No adapter",
9301
+ "fail.PI_AI_ERROR": "Adapter error",
9302
+ "fail.UNSUPPORTED_CONTENT": "Unsupported content",
9303
+ "fail.UNSUPPORTED_OPTION": "Unsupported option",
9304
+ "fail.UNSUPPORTED_REASONING_EFFORT": "Unsupported reasoning effort",
8966
9305
  "fail.STREAM_CLOSED": "Stream closed",
8967
9306
  "fail.MALFORMED_RESPONSE": "Malformed response",
8968
9307
  "fail.UNKNOWN": "Unknown error",
@@ -8994,6 +9333,7 @@ window.__ModuleLoader__.load({
8994
9333
  "aux.kind": "Category",
8995
9334
  "aux.kind.auto-review": "Auto review",
8996
9335
  "aux.kind.session-title": "Session titles",
9336
+ "aux.kind.timeline-report": "Timeline reports",
8997
9337
  "aux.kind.translation": "Translation",
8998
9338
  "aux.kind.other": "Other",
8999
9339
  "aux.requests": "Calls",
@@ -9003,6 +9343,10 @@ window.__ModuleLoader__.load({
9003
9343
  "aux.totalCount": "Total · {count}",
9004
9344
  "aux.requestCount": "{count} calls",
9005
9345
  "aux.tooltipTotal": "Overhead · total",
9346
+ "web.title": "Web tools",
9347
+ "web.tool.web_search": "Web search",
9348
+ "web.tool.web_fetch": "Web fetch",
9349
+ "web.calls": "{count} calls",
9006
9350
  "board.projects": "Projects",
9007
9351
  "board.sessions": "Sessions",
9008
9352
  "board.models": "Models",
@@ -9087,6 +9431,8 @@ window.__ModuleLoader__.load({
9087
9431
  "card.overridden": "Overriding the default",
9088
9432
  "card.sidebarPinned.label": "Pin to sidebar",
9089
9433
  "card.sidebarPinned.hint": "Shows Token Usage as a resident sidebar row and removes it from the More menu; when off, the entry lives in the sidebar More menu. Changes apply on save.",
9434
+ "card.settingsSectionEnabled.label": "Show Token Usage in Settings",
9435
+ "card.settingsSectionEnabled.hint": "Shows the Token Usage stats page under Settings → Token Usage; turn off to hide that settings section (the sidebar entry and conversation Usage tab stay active). Changes apply on save.",
9090
9436
  "card.save": "Save",
9091
9437
  "card.saving": "Saving…",
9092
9438
  "card.saveFailed": "The save did not land; try again.",
@@ -9098,6 +9444,7 @@ window.__ModuleLoader__.load({
9098
9444
  "card.fullSync.running": "Scanning…",
9099
9445
  "card.fullSync.progress": "Processed {processed}/{total} sessions, added {added}, skipped {skipped}, removed {removed}",
9100
9446
  "card.fullSync.failuresNote": ", {count} unreadable sessions skipped",
9447
+ "card.fullSync.importedNote": ", {count} DeepSeek chat imported records ignored",
9101
9448
  "card.fullSync.done": "Scan complete: added {added}, skipped {skipped}, removed {removed}",
9102
9449
  "card.fullSync.failed": "Scan failed: {error}",
9103
9450
  "loadFailed": "Failed to load stats: {message}",
@@ -9127,7 +9474,8 @@ window.__ModuleLoader__.load({
9127
9474
  "view.subagents.none": "No subagents",
9128
9475
  "view.subagents.titleCol": "Session",
9129
9476
  "view.subagents.nested": "With {count} subagents",
9130
- "view.note": "Note: tokens and cost come from this plugin's request log (post-install); average TTFT and token speed come from the DSH session projection (includes pre-install history).",
9477
+ "view.subagents.scroll": "Subagent list — click it to scroll inside",
9478
+ "view.note": "Note: tokens and cost come from this plugin's request log; solo-session header TTFT and token speed prefer the DSH session projection (covers history without logs), while subtree, subagent, and subagent-table timing come from this plugin's timed request records.",
9131
9479
  "pool.latest.title": "Latest request",
9132
9480
  "pool.latest.context": "single request · not a session mean",
9133
9481
  "pool.title": "Live requests",
@@ -9149,6 +9497,7 @@ window.__ModuleLoader__.load({
9149
9497
  "pool.kind.compaction": "Compaction",
9150
9498
  "pool.kind.auto-review": "Review",
9151
9499
  "pool.kind.session-title": "Title",
9500
+ "pool.kind.timeline-report": "Timeline",
9152
9501
  "pool.kind.translation": "Translation",
9153
9502
  "pool.kind.other": "Auxiliary",
9154
9503
  "pool.attribution.prefix": "Before this request, host compaction rewrote the context prefix; cache behaviour may be affected:",
@@ -9325,17 +9674,6 @@ window.__ModuleLoader__.load({
9325
9674
  getUiWorkspace()?.openSession(id);
9326
9675
  return { ok: true };
9327
9676
  };
9328
- ctx.slots.inject("settings.section", () => ctx.slots.register({
9329
- name: "settings.section",
9330
- id: "token-usage",
9331
- order: 50,
9332
- label: () => t("nav.label"),
9333
- locale: NS,
9334
- inject: () => ({
9335
- sessionListed,
9336
- openSession
9337
- })
9338
- }, TokenUsageSection));
9339
9677
  const selectMainPanel = (id) => {
9340
9678
  (ctx.get?.("layout"))?.selectPanel?.(id);
9341
9679
  };
@@ -9426,10 +9764,33 @@ window.__ModuleLoader__.load({
9426
9764
  set: (field, value) => activeTarget.set(field, value),
9427
9765
  unset: (field) => activeTarget.unset(field)
9428
9766
  };
9767
+ let settingsSectionDisposer;
9429
9768
  let residentDisposer;
9430
9769
  let moreDisposer;
9431
9770
  const syncEntries = () => {
9432
- const pinned = activeTarget.getSnapshot().value?.sidebarPinned === true;
9771
+ const snapshotValue = activeTarget.getSnapshot().value;
9772
+ const sectionEnabled = snapshotValue?.settingsSectionEnabled !== false;
9773
+ if (sectionEnabled && settingsSectionDisposer === void 0) try {
9774
+ settingsSectionDisposer = ctx.slots.register({
9775
+ name: "settings.section",
9776
+ id: "token-usage",
9777
+ order: 50,
9778
+ label: () => t("nav.label"),
9779
+ locale: NS,
9780
+ inject: () => ({
9781
+ sessionListed,
9782
+ openSession
9783
+ })
9784
+ }, TokenUsageSection);
9785
+ } catch {
9786
+ settingsSectionDisposer = void 0;
9787
+ }
9788
+ else if (!sectionEnabled && settingsSectionDisposer !== void 0) {
9789
+ const dispose = settingsSectionDisposer;
9790
+ settingsSectionDisposer = void 0;
9791
+ dispose();
9792
+ }
9793
+ const pinned = snapshotValue?.sidebarPinned === true;
9433
9794
  if (pinned && residentDisposer === void 0) try {
9434
9795
  residentDisposer = ctx.slots.register({
9435
9796
  name: "sidebar.panellist",
@@ -9463,6 +9824,10 @@ window.__ModuleLoader__.load({
9463
9824
  dispose();
9464
9825
  }
9465
9826
  };
9827
+ ctx.slots.inject("settings.section", () => {
9828
+ syncEntries();
9829
+ return () => {};
9830
+ });
9466
9831
  ctx.slots.inject("sidebar.panellist", () => {
9467
9832
  syncEntries();
9468
9833
  return () => {};
@@ -9476,6 +9841,11 @@ window.__ModuleLoader__.load({
9476
9841
  syncEntries();
9477
9842
  return () => {
9478
9843
  targetListeners.delete(syncEntries);
9844
+ if (settingsSectionDisposer !== void 0) {
9845
+ const dispose = settingsSectionDisposer;
9846
+ settingsSectionDisposer = void 0;
9847
+ dispose();
9848
+ }
9479
9849
  if (residentDisposer !== void 0) {
9480
9850
  const dispose = residentDisposer;
9481
9851
  residentDisposer = void 0;