@laoyuehanni/dsh-token-usage 0.3.7

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 (215) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -0
  3. package/README.zh.md +182 -0
  4. package/cordis.patch.yml +7 -0
  5. package/lib/client/CostDeltaFlyLabel.d.ts +8 -0
  6. package/lib/client/CostDeltaFlyLabel.d.ts.map +1 -0
  7. package/lib/client/CostDeltaFlyLabel.js +24 -0
  8. package/lib/client/CostDeltaFlyLabel.js.map +1 -0
  9. package/lib/client/HitRateText.d.ts +21 -0
  10. package/lib/client/HitRateText.d.ts.map +1 -0
  11. package/lib/client/HitRateText.js +16 -0
  12. package/lib/client/HitRateText.js.map +1 -0
  13. package/lib/client/QuotaButton.d.ts +70 -0
  14. package/lib/client/QuotaButton.d.ts.map +1 -0
  15. package/lib/client/QuotaButton.js +346 -0
  16. package/lib/client/QuotaButton.js.map +1 -0
  17. package/lib/client/SessionStatsChip.d.ts +47 -0
  18. package/lib/client/SessionStatsChip.d.ts.map +1 -0
  19. package/lib/client/SessionStatsChip.js +141 -0
  20. package/lib/client/SessionStatsChip.js.map +1 -0
  21. package/lib/client/StatCard.d.ts +26 -0
  22. package/lib/client/StatCard.d.ts.map +1 -0
  23. package/lib/client/StatCard.js +10 -0
  24. package/lib/client/StatCard.js.map +1 -0
  25. package/lib/client/TokenUsageCard.d.ts +41 -0
  26. package/lib/client/TokenUsageCard.d.ts.map +1 -0
  27. package/lib/client/TokenUsageCard.js +164 -0
  28. package/lib/client/TokenUsageCard.js.map +1 -0
  29. package/lib/client/TokenUsageSection.d.ts +32 -0
  30. package/lib/client/TokenUsageSection.d.ts.map +1 -0
  31. package/lib/client/TokenUsageSection.js +266 -0
  32. package/lib/client/TokenUsageSection.js.map +1 -0
  33. package/lib/client/TrendChart.d.ts +53 -0
  34. package/lib/client/TrendChart.d.ts.map +1 -0
  35. package/lib/client/TrendChart.js +141 -0
  36. package/lib/client/TrendChart.js.map +1 -0
  37. package/lib/client/UsageView.d.ts +42 -0
  38. package/lib/client/UsageView.d.ts.map +1 -0
  39. package/lib/client/UsageView.js +158 -0
  40. package/lib/client/UsageView.js.map +1 -0
  41. package/lib/client/async-resource.d.ts +54 -0
  42. package/lib/client/async-resource.d.ts.map +1 -0
  43. package/lib/client/async-resource.js +90 -0
  44. package/lib/client/async-resource.js.map +1 -0
  45. package/lib/client/card-form.d.ts +171 -0
  46. package/lib/client/card-form.d.ts.map +1 -0
  47. package/lib/client/card-form.js +300 -0
  48. package/lib/client/card-form.js.map +1 -0
  49. package/lib/client/cost-inflate-motion.d.ts +17 -0
  50. package/lib/client/cost-inflate-motion.d.ts.map +1 -0
  51. package/lib/client/cost-inflate-motion.js +61 -0
  52. package/lib/client/cost-inflate-motion.js.map +1 -0
  53. package/lib/client/cost-inflate.d.ts +28 -0
  54. package/lib/client/cost-inflate.d.ts.map +1 -0
  55. package/lib/client/cost-inflate.js +49 -0
  56. package/lib/client/cost-inflate.js.map +1 -0
  57. package/lib/client/day.d.ts +49 -0
  58. package/lib/client/day.d.ts.map +1 -0
  59. package/lib/client/day.js +84 -0
  60. package/lib/client/day.js.map +1 -0
  61. package/lib/client/format.d.ts +120 -0
  62. package/lib/client/format.d.ts.map +1 -0
  63. package/lib/client/format.js +163 -0
  64. package/lib/client/format.js.map +1 -0
  65. package/lib/client/index.d.ts +26 -0
  66. package/lib/client/index.d.ts.map +1 -0
  67. package/lib/client/index.js +131 -0
  68. package/lib/client/index.js.map +1 -0
  69. package/lib/client/locales.d.ts +131 -0
  70. package/lib/client/locales.d.ts.map +1 -0
  71. package/lib/client/locales.js +230 -0
  72. package/lib/client/locales.js.map +1 -0
  73. package/lib/client/quota-format.d.ts +69 -0
  74. package/lib/client/quota-format.d.ts.map +1 -0
  75. package/lib/client/quota-format.js +147 -0
  76. package/lib/client/quota-format.js.map +1 -0
  77. package/lib/client/session-stats.d.ts +105 -0
  78. package/lib/client/session-stats.d.ts.map +1 -0
  79. package/lib/client/session-stats.js +142 -0
  80. package/lib/client/session-stats.js.map +1 -0
  81. package/lib/client/trend-chart/axis.d.ts +21 -0
  82. package/lib/client/trend-chart/axis.d.ts.map +1 -0
  83. package/lib/client/trend-chart/axis.js +33 -0
  84. package/lib/client/trend-chart/axis.js.map +1 -0
  85. package/lib/client/trend-chart/bucket.d.ts +24 -0
  86. package/lib/client/trend-chart/bucket.d.ts.map +1 -0
  87. package/lib/client/trend-chart/bucket.js +28 -0
  88. package/lib/client/trend-chart/bucket.js.map +1 -0
  89. package/lib/client/trend-chart/index.d.ts +12 -0
  90. package/lib/client/trend-chart/index.d.ts.map +1 -0
  91. package/lib/client/trend-chart/index.js +9 -0
  92. package/lib/client/trend-chart/index.js.map +1 -0
  93. package/lib/client/trend-chart/points.d.ts +46 -0
  94. package/lib/client/trend-chart/points.d.ts.map +1 -0
  95. package/lib/client/trend-chart/points.js +82 -0
  96. package/lib/client/trend-chart/points.js.map +1 -0
  97. package/lib/client/trend-chart/scale.d.ts +47 -0
  98. package/lib/client/trend-chart/scale.d.ts.map +1 -0
  99. package/lib/client/trend-chart/scale.js +75 -0
  100. package/lib/client/trend-chart/scale.js.map +1 -0
  101. package/lib/client/use-color-scheme.d.ts +18 -0
  102. package/lib/client/use-color-scheme.d.ts.map +1 -0
  103. package/lib/client/use-color-scheme.js +37 -0
  104. package/lib/client/use-color-scheme.js.map +1 -0
  105. package/lib/client/use-cost-inflate.d.ts +33 -0
  106. package/lib/client/use-cost-inflate.d.ts.map +1 -0
  107. package/lib/client/use-cost-inflate.js +108 -0
  108. package/lib/client/use-cost-inflate.js.map +1 -0
  109. package/lib/client.js +3892 -0
  110. package/lib/client.js.map +1 -0
  111. package/lib/index.d.ts +132 -0
  112. package/lib/index.d.ts.map +1 -0
  113. package/lib/index.js +599 -0
  114. package/lib/index.js.map +1 -0
  115. package/lib/migrate.d.ts +60 -0
  116. package/lib/migrate.d.ts.map +1 -0
  117. package/lib/migrate.js +126 -0
  118. package/lib/migrate.js.map +1 -0
  119. package/lib/pricing.d.ts +212 -0
  120. package/lib/pricing.d.ts.map +1 -0
  121. package/lib/pricing.js +492 -0
  122. package/lib/pricing.js.map +1 -0
  123. package/lib/quota/adapters/deepseek-balance.d.ts +18 -0
  124. package/lib/quota/adapters/deepseek-balance.d.ts.map +1 -0
  125. package/lib/quota/adapters/deepseek-balance.js +76 -0
  126. package/lib/quota/adapters/deepseek-balance.js.map +1 -0
  127. package/lib/quota/adapters/kimi.d.ts +26 -0
  128. package/lib/quota/adapters/kimi.d.ts.map +1 -0
  129. package/lib/quota/adapters/kimi.js +91 -0
  130. package/lib/quota/adapters/kimi.js.map +1 -0
  131. package/lib/quota/adapters/minimax.d.ts +24 -0
  132. package/lib/quota/adapters/minimax.d.ts.map +1 -0
  133. package/lib/quota/adapters/minimax.js +136 -0
  134. package/lib/quota/adapters/minimax.js.map +1 -0
  135. package/lib/quota/adapters/opencode-go.d.ts +25 -0
  136. package/lib/quota/adapters/opencode-go.d.ts.map +1 -0
  137. package/lib/quota/adapters/opencode-go.js +105 -0
  138. package/lib/quota/adapters/opencode-go.js.map +1 -0
  139. package/lib/quota/adapters/openrouter.d.ts +15 -0
  140. package/lib/quota/adapters/openrouter.d.ts.map +1 -0
  141. package/lib/quota/adapters/openrouter.js +54 -0
  142. package/lib/quota/adapters/openrouter.js.map +1 -0
  143. package/lib/quota/adapters/zhipu.d.ts +38 -0
  144. package/lib/quota/adapters/zhipu.d.ts.map +1 -0
  145. package/lib/quota/adapters/zhipu.js +246 -0
  146. package/lib/quota/adapters/zhipu.js.map +1 -0
  147. package/lib/quota/credentials.d.ts +79 -0
  148. package/lib/quota/credentials.d.ts.map +1 -0
  149. package/lib/quota/credentials.js +130 -0
  150. package/lib/quota/credentials.js.map +1 -0
  151. package/lib/quota/http.d.ts +49 -0
  152. package/lib/quota/http.d.ts.map +1 -0
  153. package/lib/quota/http.js +114 -0
  154. package/lib/quota/http.js.map +1 -0
  155. package/lib/quota/provider-tracking.d.ts +45 -0
  156. package/lib/quota/provider-tracking.d.ts.map +1 -0
  157. package/lib/quota/provider-tracking.js +52 -0
  158. package/lib/quota/provider-tracking.js.map +1 -0
  159. package/lib/quota/quota-route.d.ts +22 -0
  160. package/lib/quota/quota-route.d.ts.map +1 -0
  161. package/lib/quota/quota-route.js +57 -0
  162. package/lib/quota/quota-route.js.map +1 -0
  163. package/lib/quota/quota-service.d.ts +54 -0
  164. package/lib/quota/quota-service.d.ts.map +1 -0
  165. package/lib/quota/quota-service.js +171 -0
  166. package/lib/quota/quota-service.js.map +1 -0
  167. package/lib/quota/registry.d.ts +24 -0
  168. package/lib/quota/registry.d.ts.map +1 -0
  169. package/lib/quota/registry.js +38 -0
  170. package/lib/quota/registry.js.map +1 -0
  171. package/lib/quota/types.d.ts +79 -0
  172. package/lib/quota/types.d.ts.map +1 -0
  173. package/lib/quota/types.js +24 -0
  174. package/lib/quota/types.js.map +1 -0
  175. package/lib/record-cache.d.ts +38 -0
  176. package/lib/record-cache.d.ts.map +1 -0
  177. package/lib/record-cache.js +143 -0
  178. package/lib/record-cache.js.map +1 -0
  179. package/lib/rollup.d.ts +52 -0
  180. package/lib/rollup.d.ts.map +1 -0
  181. package/lib/rollup.js +117 -0
  182. package/lib/rollup.js.map +1 -0
  183. package/lib/stats-route.d.ts +88 -0
  184. package/lib/stats-route.d.ts.map +1 -0
  185. package/lib/stats-route.js +313 -0
  186. package/lib/stats-route.js.map +1 -0
  187. package/lib/stats.d.ts +158 -0
  188. package/lib/stats.d.ts.map +1 -0
  189. package/lib/stats.js +426 -0
  190. package/lib/stats.js.map +1 -0
  191. package/lib/sync-state.d.ts +27 -0
  192. package/lib/sync-state.d.ts.map +1 -0
  193. package/lib/sync-state.js +56 -0
  194. package/lib/sync-state.js.map +1 -0
  195. package/lib/sync.d.ts +74 -0
  196. package/lib/sync.d.ts.map +1 -0
  197. package/lib/sync.js +64 -0
  198. package/lib/sync.js.map +1 -0
  199. package/lib/trend-bucket.d.ts +48 -0
  200. package/lib/trend-bucket.d.ts.map +1 -0
  201. package/lib/trend-bucket.js +87 -0
  202. package/lib/trend-bucket.js.map +1 -0
  203. package/lib/usage-log.d.ts +64 -0
  204. package/lib/usage-log.d.ts.map +1 -0
  205. package/lib/usage-log.js +144 -0
  206. package/lib/usage-log.js.map +1 -0
  207. package/lib/usage-record.d.ts +59 -0
  208. package/lib/usage-record.d.ts.map +1 -0
  209. package/lib/usage-record.js +115 -0
  210. package/lib/usage-record.js.map +1 -0
  211. package/lib/wire.d.ts +452 -0
  212. package/lib/wire.d.ts.map +1 -0
  213. package/lib/wire.js +144 -0
  214. package/lib/wire.js.map +1 -0
  215. package/package.json +100 -0
package/lib/client.js ADDED
@@ -0,0 +1,3892 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-token-usage",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let react = require("react");
8
+ let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
9
+ let react_jsx_runtime = require("react/jsx-runtime");
10
+ //#region src/wire.ts
11
+ /** The stats endpoint path, served by the host half's webServer route. */
12
+ const STATS_PATH = "/token-usage/stats";
13
+ /** Encode one repeated query key (`sessionId=a&sessionId=b`). Empty list yields ''. */
14
+ function encodeRepeatedParam(key, values) {
15
+ return values.map((value) => `${key}=${encodeURIComponent(value)}`).join("&");
16
+ }
17
+ /** Encode child groups as repeated `childId=<id>[,member…]` parameters. */
18
+ function encodeChildGroups(groups) {
19
+ return groups.filter((group) => group.length > 0 && group[0] !== "").map((group) => `childId=${encodeURIComponent(group.join(","))}`).join("&");
20
+ }
21
+ /**
22
+ * Build the stats query string (including the leading `?`, or '' when
23
+ * unconstrained). `fields: 'full'` is omitted — that is the default the
24
+ * settings page already hits.
25
+ */
26
+ function encodeStatsQuery(options) {
27
+ const parts = [];
28
+ if (options.sessionIds !== void 0 && options.sessionIds.length > 0) parts.push(encodeRepeatedParam("sessionId", options.sessionIds));
29
+ const children = options.childGroups !== void 0 ? encodeChildGroups(options.childGroups) : "";
30
+ if (children !== "") parts.push(children);
31
+ if (options.fields !== void 0 && options.fields !== "full") parts.push(`fields=${options.fields}`);
32
+ return parts.length === 0 ? "" : `?${parts.join("&")}`;
33
+ }
34
+ /**
35
+ * The quota endpoint path: the input-bar quota button polls this for the
36
+ * current provider's rate-limit / balance snapshot. Served by the host
37
+ * half's quota route; the query carries `?session=<id>` so the host can
38
+ * resolve the provider the ACTIVE session is using.
39
+ */
40
+ const QUOTA_PATH = "/token-usage/quota";
41
+ /** The migration-progress endpoint path, polled by the browser card. */
42
+ const MIGRATION_PATH = "/token-usage/migration";
43
+ /**
44
+ * The directory-guard endpoint path, consulted by the browser card before a
45
+ * staged directory save commits. The settings wire swallows a refused write
46
+ * (the bound scope recovers silently and never rejects), so this route is the
47
+ * one channel that can tell the card WHY a save would not land.
48
+ */
49
+ const DIR_GUARD_PATH = "/token-usage/dir-guard";
50
+ /**
51
+ * The full-sync endpoint path: the card's manual "scan again" affordance.
52
+ * `POST` starts one full scan over every session log (the same scan the
53
+ * one-shot startup sync ran on first install — list + inspect + dedupe), and
54
+ * `GET` returns the live progress. The scan is fire-and-forget on the host
55
+ * side, so the card polls while it runs.
56
+ */
57
+ const FULL_SYNC_PATH = "/token-usage/full-sync";
58
+ //#endregion
59
+ //#region src/client/card-form.ts
60
+ /** The fields this card edits. */
61
+ const CARD_FIELDS = ["path", "pricingRegion"];
62
+ /**
63
+ * Stages the settings edits over the `token-usage` scope.
64
+ *
65
+ * The form publishes through a snapshot store because the slot component
66
+ * reads through a snapshot selector while both the scope and the local drafts
67
+ * change underneath; every projection is rebuilt from the two together. Only
68
+ * fields the user touched are staged, so a save writes a sparse patch and
69
+ * never restates fields it did not see.
70
+ */
71
+ var CardForm = class {
72
+ scope;
73
+ snapshotValue;
74
+ listeners = /* @__PURE__ */ new Set();
75
+ drafts = {};
76
+ saving = false;
77
+ failed = false;
78
+ refusal;
79
+ migrationView;
80
+ pollTimer;
81
+ /**
82
+ * @param scope - the bound settings scope for the `token-usage` namespace.
83
+ */
84
+ constructor(scope) {
85
+ this.scope = scope;
86
+ this.snapshotValue = this.project();
87
+ scope.subscribe(() => {
88
+ this.publish();
89
+ });
90
+ this.pollMigration();
91
+ }
92
+ /** @returns the store the card's component reads through its bound selector. */
93
+ bind() {
94
+ return {
95
+ getSnapshot: () => this.snapshotValue,
96
+ subscribe: (listener) => {
97
+ this.listeners.add(listener);
98
+ return () => {
99
+ this.listeners.delete(listener);
100
+ };
101
+ },
102
+ set: (next) => {
103
+ this.store(next);
104
+ }
105
+ };
106
+ }
107
+ /** @returns the edit, clear, save, and discard actions bound to this form. */
108
+ actions() {
109
+ return {
110
+ editField: (field, text) => {
111
+ this.drafts[field] = text;
112
+ this.failed = false;
113
+ this.refusal = void 0;
114
+ this.publish();
115
+ },
116
+ clearField: (field) => {
117
+ this.drafts[field] = "";
118
+ this.failed = false;
119
+ this.refusal = void 0;
120
+ this.publish();
121
+ },
122
+ save: () => {
123
+ this.save();
124
+ },
125
+ discard: () => {
126
+ if (Object.keys(this.drafts).length === 0 && !this.failed) return;
127
+ this.drafts = {};
128
+ this.failed = false;
129
+ this.refusal = void 0;
130
+ this.publish();
131
+ }
132
+ };
133
+ }
134
+ /**
135
+ * Write the staged edits, then re-seed from what the Host accepted.
136
+ *
137
+ * The Host is the only authority on acceptance — an empty draft clears the
138
+ * field, anything else stores the trimmed text (so blanking a control and
139
+ * saving is the same gesture as clearing it). A save that did not land keeps
140
+ * its drafts so the user can correct it instead of retyping. A landed save
141
+ * that moved the data directory starts the migration poll: the Host
142
+ * relocates as a two-phase commit and the card shows the file progress
143
+ * until it settles.
144
+ *
145
+ * A staged directory edit is vetted through the plugin's guard route
146
+ * before anything writes, and re-checked when the write did not land: the
147
+ * settings wire swallows a refused write (the bound scope recovers
148
+ * silently), so the guard is the only channel that can name the refusal —
149
+ * otherwise the card could only say "did not land".
150
+ */
151
+ async save() {
152
+ const edited = CARD_FIELDS.filter((field) => this.drafts[field] !== void 0);
153
+ if (edited.length === 0 || this.saving) return;
154
+ const intended = edited.map((field) => [field, this.drafts[field].trim()]);
155
+ this.saving = true;
156
+ this.failed = false;
157
+ this.refusal = void 0;
158
+ this.publish();
159
+ const pathEdit = intended.find(([field]) => field === "path");
160
+ if (pathEdit !== void 0) {
161
+ const blocked = await this.guard(pathEdit[1]);
162
+ if (blocked !== void 0) {
163
+ this.saving = false;
164
+ this.failed = true;
165
+ this.refusal = blocked;
166
+ this.publish();
167
+ return;
168
+ }
169
+ }
170
+ let landed = true;
171
+ try {
172
+ for (const [field, text] of intended) if (text === "") await this.scope.unset(field);
173
+ else await this.scope.set(field, text);
174
+ for (const [field, text] of intended) if (text === "" ? this.stored(field) : this.storedValue(field) !== text) {
175
+ landed = false;
176
+ break;
177
+ }
178
+ } catch (_settingsWriteFailure) {
179
+ landed = false;
180
+ }
181
+ if (!landed && pathEdit !== void 0) {
182
+ const blocked = await this.guard(pathEdit[1]);
183
+ if (blocked !== void 0) this.refusal = blocked;
184
+ }
185
+ if (landed) for (const [field, _text] of intended) delete this.drafts[field];
186
+ this.saving = false;
187
+ this.failed = !landed;
188
+ if (landed && intended.some(([field]) => field === "path")) this.pollMigration();
189
+ this.publish();
190
+ }
191
+ /**
192
+ * Ask the Host's guard route whether saving this directory would be refused
193
+ * right now; a transport failure stays advisory (the write path's own
194
+ * read-back still governs acceptance).
195
+ * @param path - the staged path text ('' for the clear-to-default gesture).
196
+ * @returns the refusal to show, or undefined when the save may proceed.
197
+ */
198
+ async guard(path) {
199
+ try {
200
+ const response = await fetch(`${DIR_GUARD_PATH}?path=${encodeURIComponent(path)}`);
201
+ if (!response.ok) return void 0;
202
+ const body = await response.json();
203
+ if (body.blocked === true && typeof body.interactingSessions === "number" && body.interactingSessions > 0) return {
204
+ kind: "sessions-interacting",
205
+ interactingSessions: body.interactingSessions
206
+ };
207
+ } catch (_guardFailure) {}
208
+ }
209
+ /**
210
+ * Poll the Host's migration endpoint until it answers null (no migration
211
+ * running), publishing each progress step.
212
+ */
213
+ async pollMigration() {
214
+ if (this.pollTimer !== void 0) return;
215
+ const tick = async () => {
216
+ let view;
217
+ try {
218
+ const response = await fetch(MIGRATION_PATH);
219
+ if (response.ok) {
220
+ const body = await response.json();
221
+ if (body !== null && (body.phase === "copying" || body.phase === "cleaning") && typeof body.done === "number" && typeof body.total === "number") view = body;
222
+ }
223
+ } catch (_migrationPollFailure) {}
224
+ if (view === void 0 && this.migrationView === void 0) {
225
+ this.stopPolling();
226
+ return;
227
+ }
228
+ if (view === void 0) this.stopPolling();
229
+ this.migrationView = view;
230
+ this.publish();
231
+ };
232
+ await tick();
233
+ if (this.pollTimer === void 0 && this.migrationView !== void 0) this.pollTimer = setInterval(() => {
234
+ tick();
235
+ }, 300);
236
+ }
237
+ /** Stop the poll timer; the progress line leaves with the next publish. */
238
+ stopPolling() {
239
+ if (this.pollTimer !== void 0) {
240
+ clearInterval(this.pollTimer);
241
+ this.pollTimer = void 0;
242
+ }
243
+ }
244
+ snapshot() {
245
+ return this.scope.getSnapshot();
246
+ }
247
+ /** The raw user layer narrowed to a record; the wire answer is `unknown`. */
248
+ userLayer() {
249
+ const user = this.snapshot().user;
250
+ return typeof user === "object" && user !== null ? user : void 0;
251
+ }
252
+ storedValue(field) {
253
+ return this.userLayer()?.[field];
254
+ }
255
+ stored(field) {
256
+ const user = this.userLayer();
257
+ return user !== void 0 && Object.hasOwn(user, field);
258
+ }
259
+ /** The resolved (draft-free) text of one field; '' means inherited. */
260
+ effectiveOf(field) {
261
+ const value = this.snapshot().value?.[field];
262
+ return typeof value === "string" ? value : "";
263
+ }
264
+ /** The effective (draft-or-resolved) text of one field; '' means inherited. */
265
+ textOf(field) {
266
+ return this.drafts[field] ?? this.effectiveOf(field);
267
+ }
268
+ project() {
269
+ const snapshot = this.snapshot();
270
+ const fields = {};
271
+ const overridden = {};
272
+ let dirty = false;
273
+ for (const field of CARD_FIELDS) {
274
+ fields[field] = this.textOf(field);
275
+ overridden[field] = this.drafts[field] !== void 0 ? this.drafts[field].trim() !== "" : this.stored(field);
276
+ if (this.drafts[field] !== void 0 && this.drafts[field] !== this.effectiveOf(field)) dirty = true;
277
+ }
278
+ return {
279
+ available: snapshot.status === "ready",
280
+ writable: snapshot.writable,
281
+ fields,
282
+ overridden,
283
+ dirty,
284
+ saving: this.saving,
285
+ failed: this.failed,
286
+ refusal: this.refusal,
287
+ migration: this.migrationView
288
+ };
289
+ }
290
+ /** Replace the snapshot reference and notify, only when the fact moved. */
291
+ store(next) {
292
+ if (next === this.snapshotValue) return;
293
+ this.snapshotValue = next;
294
+ for (const listener of this.listeners) listener();
295
+ }
296
+ publish() {
297
+ this.store(this.project());
298
+ }
299
+ };
300
+ //#endregion
301
+ //#region src/client/async-resource.ts
302
+ /**
303
+ * Shared async-resource state machine for the conversation-view consumers.
304
+ * Every fetch-driven component repeats the same shape — three states
305
+ * (`loading` / `error` / `ready`), a retry counter, and cancellation on
306
+ * dependency change. Centralising the pattern here means a regression in
307
+ * the cancellation logic lands in one spot instead of three.
308
+ *
309
+ * @module token-usage/client/async-resource
310
+ */
311
+ /**
312
+ * Drive one fetcher's lifecycle: reruns on dependency change, cancels the
313
+ * previous attempt on a new fetch, and on retry-bump refetches even with
314
+ * the same deps. `silentAfterFirst` keeps the previous value on screen —
315
+ * the dashboard never blanks during a refresh once data is up.
316
+ *
317
+ * @param fetcher - the async loader; receives an `AbortSignal` for
318
+ * cancellation. Throwing aborts the fetch (the next effect run triggers
319
+ * a fresh attempt).
320
+ * @param deps - the dependency list that retriggers a fetch (passed
321
+ * through to React's effect; the retry counter joins the list).
322
+ * @param options.silentAfterFirst - when true, the first fetch goes to
323
+ * `loading` and subsequent refreshes keep the prior `value` on screen
324
+ * until the new one lands.
325
+ * @param options.retryToken - bumping this value triggers a refetch even
326
+ * with unchanged deps (the consumer wires a "retry" button to it).
327
+ * @returns `[state, retry]` — the current state plus a stable `retry()`
328
+ * callback that bumps the internal counter and re-runs the effect.
329
+ */
330
+ function useAsyncResource(fetcher, deps, options) {
331
+ const silent = options.silentAfterFirst === true;
332
+ const [state, setState] = (0, react.useState)({ status: "loading" });
333
+ const loadedRef = (0, react.useRef)(false);
334
+ const [retryTick, setRetryTick] = (0, react.useState)(0);
335
+ const retry = (0, react.useCallback)(() => {
336
+ setRetryTick((tick) => tick + 1);
337
+ }, []);
338
+ (0, react.useEffect)(() => {
339
+ const controller = new AbortController();
340
+ if (!silent || !loadedRef.current) setState({ status: "loading" });
341
+ fetcher(controller.signal).then((value) => {
342
+ if (controller.signal.aborted) return;
343
+ loadedRef.current = true;
344
+ setState({
345
+ status: "ready",
346
+ value
347
+ });
348
+ }).catch((error) => {
349
+ if (controller.signal.aborted) return;
350
+ if (silent && loadedRef.current) return;
351
+ setState({
352
+ status: "error",
353
+ message: error instanceof Error ? error.message : String(error)
354
+ });
355
+ });
356
+ return () => {
357
+ controller.abort();
358
+ };
359
+ }, [
360
+ ...deps,
361
+ options.retryToken,
362
+ retryTick,
363
+ silent
364
+ ]);
365
+ return [state, retry];
366
+ }
367
+ /**
368
+ * Return a value that lags behind its source by `delayMs` — a debounced
369
+ * snapshot. The initial render already holds `value` (no null sentinel), so
370
+ * a consumer can fetch immediately on mount without a second shot when the
371
+ * first debounce window closes on the same value.
372
+ *
373
+ * @param value - the source value to debounce.
374
+ * @param delayMs - the lag window in milliseconds.
375
+ * @returns the debounced value.
376
+ */
377
+ function useDebouncedValue(value, delayMs) {
378
+ const [debounced, setDebounced] = (0, react.useState)(value);
379
+ (0, react.useEffect)(() => {
380
+ const timer = setTimeout(() => {
381
+ setDebounced(value);
382
+ }, delayMs);
383
+ return () => {
384
+ clearTimeout(timer);
385
+ };
386
+ }, [value, delayMs]);
387
+ return debounced;
388
+ }
389
+ //#endregion
390
+ //#region src/client/quota-format.ts
391
+ /** Severity thresholds on the REMAINING share (percent) — the traffic-light
392
+ * standard: above 60 reads green (plenty left), 20–60 yellow (watch it),
393
+ * below 20 red (effectively gone). */
394
+ const REMAIN_YELLOW = 60;
395
+ const REMAIN_RED = 20;
396
+ /** Whole-number percent, one decimal kept when it exists (`62%`, `87.5%`). */
397
+ function formatQuotaPercent(value) {
398
+ const rounded = Math.round(value * 10) / 10;
399
+ return `${Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1)}%`;
400
+ }
401
+ /** A money figure with its symbol: `$6.80` / `¥110.00`. */
402
+ function formatQuotaMoney(value, unit) {
403
+ return `${unit === "usd" ? "$" : "¥"}${value.toFixed(2)}`;
404
+ }
405
+ /**
406
+ * The used share of one window, 0–100, whichever direction the provider
407
+ * reported: the explicit `usedPercent`, else `remainingPercent` inverted,
408
+ * else the balance fraction (`1 - remaining/max`). Undefined when the
409
+ * window carries no computable ratio (a balance without a total).
410
+ */
411
+ function quotaUsedPercent(window) {
412
+ if (window.usedPercent !== void 0) return clampPercent(window.usedPercent);
413
+ if (window.remainingPercent !== void 0) return clampPercent(100 - window.remainingPercent);
414
+ if (window.remainingValue !== void 0 && window.maxValue !== void 0 && window.maxValue > 0) return clampPercent((1 - window.remainingValue / window.maxValue) * 100);
415
+ }
416
+ /**
417
+ * The remaining share of one window, 0–100 — the severity input (severity
418
+ * reads what is LEFT, not what is spent). Mirrors {@link quotaUsedPercent}'s
419
+ * fallback chain in the opposite direction.
420
+ */
421
+ function quotaRemainingPercent(window) {
422
+ if (window.remainingPercent !== void 0) return clampPercent(window.remainingPercent);
423
+ if (window.usedPercent !== void 0) return clampPercent(100 - window.usedPercent);
424
+ if (window.remainingValue !== void 0 && window.maxValue !== void 0 && window.maxValue > 0) return clampPercent(window.remainingValue / window.maxValue * 100);
425
+ }
426
+ /** Map a remaining share (percent) to the traffic-light band: green above
427
+ * 60, yellow 20–60, red below 20. A window with no computable ratio reads
428
+ * by its absolute amount: an overdrawn/empty balance (≤ 0) is red,
429
+ * anything else uncolored — a plain balance never paints alarm just for
430
+ * lacking a total. */
431
+ function quotaSeverityOf(window) {
432
+ const remaining = quotaRemainingPercent(window);
433
+ if (remaining === void 0) return window.remainingValue !== void 0 && window.remainingValue <= 0 ? "exhausted" : "ok";
434
+ if (remaining < REMAIN_RED) return "exhausted";
435
+ if (remaining <= REMAIN_YELLOW) return "warn";
436
+ return "ok";
437
+ }
438
+ /**
439
+ * The FINEST-granularity window of a payload — 5-hour over weekly over
440
+ * monthly over balance. The trigger icon reads this one, not the worst
441
+ * across windows: the finest unit is the constraint the session is
442
+ * currently acting inside (a calm 5-hour window carries the icon even when
443
+ * the weekly pool runs low). Undefined when there is no window at all.
444
+ */
445
+ function finestQuotaWindow(windows) {
446
+ const rank = {
447
+ five_hour: 0,
448
+ weekly: 1,
449
+ monthly: 2,
450
+ balance: 3
451
+ };
452
+ let pick;
453
+ for (const window of windows) if (pick === void 0 || rank[window.tier] < rank[pick.tier]) pick = window;
454
+ return pick;
455
+ }
456
+ /**
457
+ * Fill share of the trigger ring, 0–1. Ratio windows map the remaining
458
+ * percent; a funded balance without a total paints a full ring (the color
459
+ * stays neutral — amounts tint only at ≤ 0); empty / overdrawn / missing
460
+ * windows leave the track only.
461
+ */
462
+ function quotaIconFillShare(window) {
463
+ if (window === void 0) return 0;
464
+ const remaining = quotaRemainingPercent(window);
465
+ if (remaining !== void 0) return remaining / 100;
466
+ if (window.remainingValue !== void 0 && window.remainingValue > 0) return 1;
467
+ return 0;
468
+ }
469
+ /**
470
+ * The trigger tooltip's figure for one window: the remaining share as a
471
+ * percent when a ratio exists (any direction, or the balance fraction),
472
+ * else the remaining amount (a ratio-less balance, the DeepSeek shape);
473
+ * undefined when the window carries neither (nothing to show beyond the
474
+ * plain label).
475
+ */
476
+ function quotaTriggerFigure(window) {
477
+ if (window === void 0) return void 0;
478
+ const remaining = quotaRemainingPercent(window);
479
+ if (remaining !== void 0) return formatQuotaPercent(remaining);
480
+ if (window.remainingValue !== void 0) return formatQuotaMoney(window.remainingValue, window.unit ?? "cny");
481
+ }
482
+ /**
483
+ * The reset countdown in the shell's compact shape: `2h 14m` under a day,
484
+ * `48m` under an hour, `1d 3h` above; a non-positive remainder reads `0m`
485
+ * (the next poll refreshes the stale window).
486
+ * @param resetAt - epoch ms of the window's reset.
487
+ * @param now - epoch ms the countdown is taken at.
488
+ */
489
+ function formatResetCountdown(resetAt, now) {
490
+ const minutes = Math.max(0, Math.floor((resetAt - now) / 6e4));
491
+ if (minutes < 60) return `${String(minutes)}m`;
492
+ const hours = Math.floor(minutes / 60);
493
+ if (hours < 24) return `${String(hours)}h ${String(minutes % 60)}m`;
494
+ return `${String(Math.floor(hours / 24))}d ${String(hours % 24)}h`;
495
+ }
496
+ /** A wall-clock `HH:MM` stamp of an epoch-ms time (the "updated at" figure). */
497
+ function formatQuotaClock(ms) {
498
+ const date = new Date(ms);
499
+ const pad = (value) => String(value).padStart(2, "0");
500
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
501
+ }
502
+ /** Clamp into 0–100. */
503
+ function clampPercent(value) {
504
+ return Math.min(100, Math.max(0, value));
505
+ }
506
+ //#endregion
507
+ //#region src/client/use-color-scheme.ts
508
+ /**
509
+ * Shared browser-half hook: mirror the shell's root `color-scheme` onto a
510
+ * plugin-owned root element. The shell sets the property on
511
+ * `document.documentElement` only, so form controls inside plugin surfaces
512
+ * render with the UA default (white) in dark mode; scoping the property to
513
+ * the surface's root fixes selects, inputs, and dialogs without touching
514
+ * anything outside it. Used by the settings section and the conversation
515
+ * view tab.
516
+ *
517
+ * @module token-usage/client/use-color-scheme
518
+ */
519
+ /**
520
+ * Mirror the shell's `color-scheme` inline style onto the given root element.
521
+ * @param rootRef - the surface's root element ref.
522
+ */
523
+ function useColorSchemeMirror(rootRef) {
524
+ (0, react.useEffect)(() => {
525
+ const root = document.documentElement;
526
+ const element = rootRef.current;
527
+ if (element === null) return;
528
+ const sync = () => {
529
+ const scheme = root.style.colorScheme;
530
+ if (scheme !== "") element.style.colorScheme = scheme;
531
+ else element.style.removeProperty("color-scheme");
532
+ };
533
+ sync();
534
+ const observer = new MutationObserver(sync);
535
+ observer.observe(root, {
536
+ attributes: true,
537
+ attributeFilter: ["style"]
538
+ });
539
+ return () => observer.disconnect();
540
+ }, [rootRef]);
541
+ }
542
+ //#endregion
543
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\QuotaButton.module.css.mjs
544
+ const css$7 = ".jYASuG_root{flex:none;display:inline-flex;position:relative}.jYASuG_trigger{width:28px;height:28px;color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;border-radius:999px;flex:none;place-items:center;padding:0;display:grid}.jYASuG_trigger svg{display:block}.jYASuG_trigger:hover,.jYASuG_trigger[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}.jYASuG_trigger.jYASuG_icon-ok:hover,.jYASuG_trigger.jYASuG_icon-ok[aria-expanded=true]{color:var(--dsw-alias-state-success-primary)}.jYASuG_trigger.jYASuG_icon-warn:hover,.jYASuG_trigger.jYASuG_icon-warn[aria-expanded=true]{color:var(--dsw-alias-state-warn-primary)}.jYASuG_trigger.jYASuG_icon-exhausted:hover,.jYASuG_trigger.jYASuG_icon-exhausted[aria-expanded=true]{color:var(--dsw-alias-state-error-primary)}.jYASuG_icon-ok{color:var(--dsw-alias-state-success-primary)}.jYASuG_icon-warn{color:var(--dsw-alias-state-warn-primary)}.jYASuG_icon-exhausted{color:var(--dsw-alias-state-error-primary)}.jYASuG_panel{z-index:100;box-sizing:border-box;border:1px solid var(--dsw-alias-border-inverted);background:var(--dsw-specific-menu);width:320px;max-width:calc(100vw - 32px);box-shadow:var(--dsw-shadow-lv3);color:var(--dsw-alias-label-secondary);text-align:left;cursor:default;border-radius:12px;padding:12px;font-size:12px;line-height:20px;position:absolute;bottom:calc(100% + 8px)}.jYASuG_header{justify-content:space-between;align-items:baseline;gap:8px;margin-bottom:10px;display:flex}.jYASuG_title{color:var(--dsw-alias-label-primary);white-space:nowrap;text-overflow:ellipsis;font-size:13px;font-weight:500;overflow:hidden}.jYASuG_plan{color:var(--dsw-alias-label-tertiary);font-weight:400}.jYASuG_updated{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;flex:none;font-size:11px}.jYASuG_grid{grid-template-columns:repeat(var(--cols,3), 1fr);gap:14px;display:grid}.jYASuG_col{min-width:0}.jYASuG_label{color:var(--dsw-alias-label-tertiary);white-space:nowrap;text-overflow:ellipsis;margin-bottom:2px;font-size:11px;line-height:16px;overflow:hidden}.jYASuG_value{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;white-space:nowrap;margin-bottom:6px;font-size:13px;font-weight:600;line-height:18px}.jYASuG_meta{color:var(--dsw-alias-label-tertiary);font-size:11px;font-weight:400}.jYASuG_bar{background:var(--dsw-alias-interactive-bg-hover);border-radius:999px;height:4px;overflow:hidden}.jYASuG_fill{border-radius:999px;height:100%;transition:width .3s}.jYASuG_ok{background:var(--dsw-alias-state-success-primary)}.jYASuG_warn{background:var(--dsw-alias-state-warn-primary)}.jYASuG_exhausted{background:var(--dsw-alias-state-error-primary)}.jYASuG_aux{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;white-space:nowrap;margin-top:4px;font-size:11px;line-height:14px}.jYASuG_dot{vertical-align:middle;border-radius:50%;width:5px;height:5px;margin-right:3px;display:inline-block}.jYASuG_error{flex-direction:column;gap:8px;display:flex}.jYASuG_errorText{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere;font-size:12px;line-height:18px}.jYASuG_retry{color:var(--dsw-alias-label-primary);cursor:pointer;text-underline-offset:2px;background:0 0;border:none;align-self:flex-start;padding:0;font-size:12px;text-decoration:underline}.jYASuG_retry:hover{color:var(--dsw-alias-brand-primary)}";
545
+ const tagId$7 = "dsh-token-usage/QuotaButton.module.css";
546
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$7) + "]") === null) {
547
+ const tag = document.createElement("style");
548
+ tag.dataset.plugin = "dsh-token-usage";
549
+ tag.dataset.pluginCss = tagId$7;
550
+ tag.textContent = css$7;
551
+ document.head.appendChild(tag);
552
+ }
553
+ var QuotaButton_module_css_default = {
554
+ "aux": "jYASuG_aux",
555
+ "bar": "jYASuG_bar",
556
+ "col": "jYASuG_col",
557
+ "dot": "jYASuG_dot",
558
+ "error": "jYASuG_error",
559
+ "errorText": "jYASuG_errorText",
560
+ "exhausted": "jYASuG_exhausted",
561
+ "fill": "jYASuG_fill",
562
+ "grid": "jYASuG_grid",
563
+ "header": "jYASuG_header",
564
+ "icon-exhausted": "jYASuG_icon-exhausted",
565
+ "icon-ok": "jYASuG_icon-ok",
566
+ "icon-warn": "jYASuG_icon-warn",
567
+ "label": "jYASuG_label",
568
+ "meta": "jYASuG_meta",
569
+ "ok": "jYASuG_ok",
570
+ "panel": "jYASuG_panel",
571
+ "plan": "jYASuG_plan",
572
+ "retry": "jYASuG_retry",
573
+ "root": "jYASuG_root",
574
+ "title": "jYASuG_title",
575
+ "trigger": "jYASuG_trigger",
576
+ "updated": "jYASuG_updated",
577
+ "value": "jYASuG_value",
578
+ "warn": "jYASuG_warn"
579
+ };
580
+ //#endregion
581
+ //#region src/client/QuotaButton.tsx
582
+ /**
583
+ * Input-bar quota button (browser half): a 28×28 round trigger registered
584
+ * into the `conversation.input.right` slot (it renders left of the model
585
+ * chip — the host's fixed tool-row order). The glyph is a remaining-share
586
+ * ring (ContextMeter family) colored by the finest window. Clicking opens a
587
+ * width-tiered popup (amount-only 200px / one progress bar 232px / two
588
+ * bars 320px) centered on the button with the current provider's quota
589
+ * windows: progress columns (5 小时 / 每周) for coding-plan providers, an
590
+ * amount row for balance providers.
591
+ *
592
+ * The provider follows the model CHIP's live selection (the shell's
593
+ * model-selection service reports the host's next selection before any
594
+ * request is sent); without that service the host falls back to the last
595
+ * request's provider, else the default selection.
596
+ *
597
+ * The button SELF-GATES: it renders nothing while the host cannot
598
+ * determine a provider (`no-provider`), the provider has no quota adapter
599
+ * (`unsupported`), or the feature is off (`disabled`) — switching
600
+ * providers makes it appear again. A supported provider whose query fails
601
+ * KEEPS the button and shows the error with a retry inside the panel.
602
+ *
603
+ * The hover tooltip reads provider name + the finest window's exact
604
+ * remaining figure (percent, or the amount when no ratio exists).
605
+ *
606
+ * The interaction copies ContextMeter verbatim (click toggles, document
607
+ * pointerdown outside closes, Escape closes); mutual exclusion with the
608
+ * ContextMeter panel falls out of both components' outside-close
609
+ * handlers — opening one closes the other on its next pointerdown.
610
+ *
611
+ * @module token-usage/client/QuotaButton
612
+ */
613
+ /** The poll cadence fallback (seconds) while no payload has named one. */
614
+ const DEFAULT_POLL_SEC = 60;
615
+ /** Panel width tiers (px), by how much the windows paint: a lone amount
616
+ * reads at a glance, one progress bar needs breathing room, two bars (the
617
+ * 5-hour + weekly coding plans, or a long error body) the full plate. Kept
618
+ * in sync with the CSS max-width clamp. */
619
+ const PANEL_WIDTH_BALANCE = 200;
620
+ const PANEL_WIDTH_SINGLE = 232;
621
+ const PANEL_WIDTH_FULL = 320;
622
+ const PANEL_VIEWPORT_MARGIN = 16;
623
+ /** Tier → label key; the locale dictionaries carry both languages. */
624
+ const TIER_LABEL_KEYS = {
625
+ five_hour: "quota.tier.fiveHour",
626
+ weekly: "quota.tier.weekly",
627
+ monthly: "quota.tier.monthly",
628
+ balance: "quota.tier.balance"
629
+ };
630
+ /**
631
+ * Render the input-bar quota button for the active session's provider.
632
+ * @param props - the framework session id, the locale seat, and the
633
+ * optional model-directory holder (the chip's live selection).
634
+ * @returns the trigger + panel, or null while hidden (see the module note).
635
+ */
636
+ function QuotaButton({ sessionId, t, modelDirectory }) {
637
+ const rootRef = (0, react.useRef)(null);
638
+ useColorSchemeMirror(rootRef);
639
+ const [open, setOpen] = (0, react.useState)(false);
640
+ const [panelLeft, setPanelLeft] = (0, react.useState)(void 0);
641
+ const measurePanelLeft = (0, react.useCallback)((width) => {
642
+ const wrapper = rootRef.current;
643
+ if (wrapper === null) return;
644
+ const { left: wrapperLeft, width: wrapperWidth } = wrapper.getBoundingClientRect();
645
+ const panelWidth = Math.min(width, window.innerWidth - 32);
646
+ const desired = (wrapperWidth - panelWidth) / 2;
647
+ const minLeft = PANEL_VIEWPORT_MARGIN - wrapperLeft;
648
+ const maxLeft = window.innerWidth - PANEL_VIEWPORT_MARGIN - panelWidth - wrapperLeft;
649
+ setPanelLeft(Math.min(Math.max(desired, minLeft), Math.max(minLeft, maxLeft)));
650
+ }, []);
651
+ const modelService = modelDirectory?.service;
652
+ const readChipProvider = () => {
653
+ if (sessionId === "" || modelService === void 0) return void 0;
654
+ try {
655
+ return modelService.directoryFor(sessionId).store.getSnapshot().current?.provider ?? void 0;
656
+ } catch {
657
+ return;
658
+ }
659
+ };
660
+ const [chipProvider, setChipProvider] = (0, react.useState)(readChipProvider);
661
+ (0, react.useEffect)(() => {
662
+ setChipProvider(readChipProvider());
663
+ if (sessionId === "" || modelService === void 0) return;
664
+ let directory;
665
+ try {
666
+ directory = modelService.directoryFor(sessionId);
667
+ } catch {
668
+ return;
669
+ }
670
+ return directory.store.subscribe(() => {
671
+ setChipProvider(readChipProvider());
672
+ });
673
+ }, [sessionId, modelService]);
674
+ const [resource, retry] = useAsyncResource((signal) => fetchQuotaPayload(sessionId, chipProvider, signal), [sessionId, chipProvider], {
675
+ silentAfterFirst: true,
676
+ retryToken: 0
677
+ });
678
+ const payload = resource.status === "ready" ? resource.value : null;
679
+ const panelWidth = panelWidthOf(payload);
680
+ const pollMs = (payload?.intervalSec ?? DEFAULT_POLL_SEC) * 1e3;
681
+ (0, react.useEffect)(() => {
682
+ const timer = setInterval(retry, pollMs);
683
+ return () => {
684
+ clearInterval(timer);
685
+ };
686
+ }, [pollMs, retry]);
687
+ const visible = payload !== null && (payload.status === "ok" || payload.status === "error");
688
+ (0, react.useEffect)(() => {
689
+ if (!visible && open) setOpen(false);
690
+ }, [visible, open]);
691
+ (0, react.useEffect)(() => {
692
+ if (!open) return;
693
+ const onPointerDown = (event) => {
694
+ if (event.target instanceof Node && rootRef.current?.contains(event.target) === true) return;
695
+ setOpen(false);
696
+ };
697
+ const onKeyDown = (event) => {
698
+ if (event.key === "Escape") setOpen(false);
699
+ };
700
+ document.addEventListener("pointerdown", onPointerDown);
701
+ document.addEventListener("keydown", onKeyDown);
702
+ return () => {
703
+ document.removeEventListener("pointerdown", onPointerDown);
704
+ document.removeEventListener("keydown", onKeyDown);
705
+ };
706
+ }, [open]);
707
+ (0, react.useEffect)(() => {
708
+ if (!open) return;
709
+ const onViewportChange = () => {
710
+ measurePanelLeft(panelWidth);
711
+ };
712
+ measurePanelLeft(panelWidth);
713
+ window.addEventListener("resize", onViewportChange);
714
+ window.addEventListener("scroll", onViewportChange, true);
715
+ return () => {
716
+ window.removeEventListener("resize", onViewportChange);
717
+ window.removeEventListener("scroll", onViewportChange, true);
718
+ };
719
+ }, [
720
+ open,
721
+ panelWidth,
722
+ measurePanelLeft
723
+ ]);
724
+ if (!visible || payload === null) return null;
725
+ const finest = finestQuotaWindow(payload.status === "ok" ? payload.windows : []);
726
+ const severity = finest === void 0 ? "ok" : quotaSeverityOf(finest);
727
+ const triggerClass = [QuotaButton_module_css_default.trigger];
728
+ if (severity === "warn") triggerClass.push(QuotaButton_module_css_default["icon-warn"]);
729
+ else if (severity === "exhausted") triggerClass.push(QuotaButton_module_css_default["icon-exhausted"]);
730
+ else if (finest !== void 0 && quotaRemainingPercent(finest) !== void 0) triggerClass.push(QuotaButton_module_css_default["icon-ok"]);
731
+ const triggerClassName = triggerClass.join(" ").trim();
732
+ const figure = quotaTriggerFigure(finest);
733
+ const triggerTip = figure === void 0 ? t("quota.trigger") : t("quota.triggerSummary", {
734
+ name: payload.providerName ?? payload.provider,
735
+ figure
736
+ });
737
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
738
+ ref: rootRef,
739
+ className: QuotaButton_module_css_default.root,
740
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
741
+ label: triggerTip,
742
+ side: "top",
743
+ delayMs: 200,
744
+ disabled: open,
745
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
746
+ type: "button",
747
+ className: triggerClassName,
748
+ "aria-haspopup": "dialog",
749
+ "aria-expanded": open,
750
+ "aria-label": t("quota.trigger"),
751
+ onClick: () => {
752
+ if (!open) {
753
+ retry();
754
+ measurePanelLeft(panelWidth);
755
+ }
756
+ setOpen(!open);
757
+ },
758
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QuotaGlyph, { share: quotaIconFillShare(finest) })
759
+ })
760
+ }), open && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
761
+ className: QuotaButton_module_css_default.panel,
762
+ role: "dialog",
763
+ "aria-label": t("quota.panel"),
764
+ style: {
765
+ width: `${String(panelWidth)}px`,
766
+ ...panelLeft === void 0 ? {} : { left: `${String(panelLeft)}px` }
767
+ },
768
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
769
+ className: QuotaButton_module_css_default.header,
770
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
771
+ className: QuotaButton_module_css_default.title,
772
+ children: [payload.providerName ?? payload.provider, payload.status === "ok" && payload.planTier !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
773
+ className: QuotaButton_module_css_default.plan,
774
+ children: [" · ", payload.planTier]
775
+ }) : null]
776
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
777
+ className: QuotaButton_module_css_default.updated,
778
+ children: t("quota.updatedAt", { time: formatQuotaClock(payload.fetchedAt) })
779
+ })]
780
+ }), payload.status === "error" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
781
+ className: QuotaButton_module_css_default.error,
782
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
783
+ className: QuotaButton_module_css_default.errorText,
784
+ children: errorText(payload.error, t)
785
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
786
+ type: "button",
787
+ className: QuotaButton_module_css_default.retry,
788
+ onClick: retry,
789
+ children: t("quota.retry")
790
+ })]
791
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
792
+ className: QuotaButton_module_css_default.grid,
793
+ style: { "--cols": String(Math.min(payload.windows.length, 3)) },
794
+ children: payload.windows.map((window, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(QuotaColumn, {
795
+ window,
796
+ t
797
+ }, `${window.tier}:${String(index)}`))
798
+ })]
799
+ })]
800
+ });
801
+ }
802
+ /** Ring geometry matches ContextMeter: 14px viewBox, r 5.5, 2px stroke.
803
+ * Circumference feeds the remaining-share dasharray, starting at 12
804
+ * o'clock. A 0 share omits the fill stroke — a round cap at 0 would still
805
+ * paint a dot. */
806
+ const RING_R = 5.5;
807
+ const RING_C = 2 * Math.PI * RING_R;
808
+ /** Round caps paint half a stroke width beyond each dash end; their
809
+ * combined reach is what the dash compensation subtracts, so the painted
810
+ * arc (dash + caps) equals the nominal share and the caps cannot seal the
811
+ * 12-o'clock gap. */
812
+ const RING_CAP_REACH = 2;
813
+ /** The trigger glyph: a ContextMeter-family donut whose fill arc is the
814
+ * remaining share of the finest window. Color comes from the button's
815
+ * severity class (`currentColor`); this only draws the arc. */
816
+ function QuotaGlyph({ share }) {
817
+ const clamped = Math.min(1, Math.max(0, share));
818
+ const nominal = clamped * RING_C;
819
+ const dashLen = clamped >= 1 ? RING_C : nominal <= RING_CAP_REACH ? nominal : nominal - RING_CAP_REACH;
820
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
821
+ viewBox: "0 0 14 14",
822
+ width: "14",
823
+ height: "14",
824
+ "aria-hidden": "true",
825
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
826
+ cx: "7",
827
+ cy: "7",
828
+ r: RING_R,
829
+ fill: "none",
830
+ stroke: "currentColor",
831
+ strokeWidth: "2",
832
+ opacity: "0.22"
833
+ }), clamped > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
834
+ cx: "7",
835
+ cy: "7",
836
+ r: RING_R,
837
+ fill: "none",
838
+ stroke: "currentColor",
839
+ strokeWidth: "2",
840
+ strokeLinecap: clamped < 1 ? "round" : "butt",
841
+ strokeDasharray: `${dashLen.toFixed(3)} ${RING_C.toFixed(3)}`,
842
+ transform: "rotate(-90 7 7)"
843
+ }) : null]
844
+ });
845
+ }
846
+ /** One progress column: label / value / bar / aux. The value and the bar
847
+ * both carry the REMAINING share (the traffic-light standard reads what is
848
+ * left), colored by severity. */
849
+ function QuotaColumn({ window, t }) {
850
+ const remaining = quotaRemainingPercent(window);
851
+ const severity = quotaSeverityOf(window);
852
+ const label = t(TIER_LABEL_KEYS[window.tier]);
853
+ let value;
854
+ let meta;
855
+ if (window.tier === "balance" && window.remainingValue !== void 0) {
856
+ const unit = window.unit ?? "cny";
857
+ value = formatQuotaMoney(window.remainingValue, unit);
858
+ if (window.maxValue !== void 0) meta = `/ ${formatQuotaMoney(window.maxValue, unit)}`;
859
+ } else value = remaining !== void 0 ? formatQuotaPercent(remaining) : "—";
860
+ const aux = window.resetAt !== void 0 ? t("quota.resetIn", { time: formatResetCountdown(window.resetAt, Date.now()) }) : void 0;
861
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
862
+ className: QuotaButton_module_css_default.col,
863
+ children: [
864
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
865
+ className: QuotaButton_module_css_default.label,
866
+ children: label
867
+ }),
868
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
869
+ className: QuotaButton_module_css_default.value,
870
+ children: [value, meta !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
871
+ className: QuotaButton_module_css_default.meta,
872
+ children: [" ", meta]
873
+ }) : null]
874
+ }),
875
+ remaining !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
876
+ className: QuotaButton_module_css_default.bar,
877
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
878
+ className: `${QuotaButton_module_css_default.fill} ${QuotaButton_module_css_default[severity]}`,
879
+ style: { width: `${String(Math.round(remaining))}%` }
880
+ })
881
+ }),
882
+ aux !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
883
+ className: QuotaButton_module_css_default.aux,
884
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: `${QuotaButton_module_css_default.dot} ${QuotaButton_module_css_default[severity]}` }), aux]
885
+ })
886
+ ]
887
+ });
888
+ }
889
+ /** The panel's width tier for one payload: what the windows PAINT decides —
890
+ * a lone amount (no computable bar, the DeepSeek shape) reads at the
891
+ * minimal plate, one bar (a weekly-only plan, or a balance with a spend
892
+ * total like OpenRouter) the middle one, two or more bars the full plate.
893
+ * Errors and payloads without windows read the full plate (their copy
894
+ * runs long). */
895
+ function panelWidthOf(payload) {
896
+ if (payload === null || payload.status !== "ok") return PANEL_WIDTH_FULL;
897
+ const bars = payload.windows.filter((window) => quotaUsedPercent(window) !== void 0).length;
898
+ if (bars === 0) return payload.windows.length > 0 ? PANEL_WIDTH_BALANCE : PANEL_WIDTH_FULL;
899
+ return bars === 1 ? PANEL_WIDTH_SINGLE : PANEL_WIDTH_FULL;
900
+ }
901
+ /** Friendly locale copy for one normalized query error. */
902
+ function errorText(error, t) {
903
+ switch (error.kind) {
904
+ case "auth": return t("quota.error.auth", { message: error.message });
905
+ case "no-credential": return t("quota.error.noCredential", { ref: error.message });
906
+ case "http": return t("quota.error.http", { message: error.message });
907
+ case "network": return t("quota.error.network", { message: error.message });
908
+ case "parse": return t("quota.error.parse", { message: error.message });
909
+ }
910
+ }
911
+ /** Defensive shape check: a misrouted response must not paint the button. */
912
+ function looksLikeQuotaPayload(value) {
913
+ return typeof value === "object" && value !== null && typeof value.status === "string" && typeof value.intervalSec === "number";
914
+ }
915
+ /**
916
+ * Fetch the quota payload for the active session, naming the chip-selected
917
+ * provider when one is known. Throws on transport failure or a payload that
918
+ * does not look like one, so the hook can keep the previous render
919
+ * (silentAfterFirst) or stay hidden (first failure).
920
+ */
921
+ async function fetchQuotaPayload(sessionId, provider, signal) {
922
+ const params = new URLSearchParams();
923
+ if (sessionId !== "") params.set("session", sessionId);
924
+ if (provider !== void 0 && provider !== "") params.set("provider", provider);
925
+ const encoded = params.toString();
926
+ const query = encoded === "" ? "" : `?${encoded}`;
927
+ const response = await fetch(QUOTA_PATH + query, {
928
+ headers: { accept: "application/json" },
929
+ signal
930
+ });
931
+ if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
932
+ const value = await response.json();
933
+ if (!looksLikeQuotaPayload(value)) throw new Error("unexpected quota response");
934
+ return value;
935
+ }
936
+ //#endregion
937
+ //#region src/client/day.ts
938
+ /** Total tokens across the four buckets (billed input = input + cacheRead + cacheWrite). */
939
+ function totalTokens(totals) {
940
+ return totals.inputTokens + totals.outputTokens + totals.cacheReadTokens + totals.cacheWriteTokens;
941
+ }
942
+ /** Local `YYYY-MM-DD` key of a date, matching the host's day-file convention. */
943
+ function dayKeyOf(date) {
944
+ const month = String(date.getMonth() + 1).padStart(2, "0");
945
+ const day = String(date.getDate()).padStart(2, "0");
946
+ return `${date.getFullYear()}-${month}-${day}`;
947
+ }
948
+ /** Local day key of today shifted by whole days (test seam on `now`). */
949
+ function shiftedDayKey(deltaDays, now = () => /* @__PURE__ */ new Date()) {
950
+ const date = now();
951
+ date.setDate(date.getDate() + deltaDays);
952
+ return dayKeyOf(date);
953
+ }
954
+ /**
955
+ * The zero-filled daily token series over a day range: every calendar day of
956
+ * the range appears once (days without records plot as zero). Absent bounds
957
+ * fall back to the first/last row day; no rows and no range yield [].
958
+ * @param rows - the (already filtered) per-day rows.
959
+ * @param from - first day key, inclusive.
960
+ * @param to - last day key, inclusive.
961
+ */
962
+ function daySeries(rows, from, to) {
963
+ const first = from ?? rows[0]?.day;
964
+ const last = to ?? (rows.length > 0 ? rows[rows.length - 1].day : void 0);
965
+ if (first === void 0 || last === void 0 || first > last) return [];
966
+ const tokens = new Map(rows.map((row) => [row.day, totalTokens(row.totals)]));
967
+ const points = [];
968
+ const cursor = /* @__PURE__ */ new Date(`${first}T00:00:00`);
969
+ const end = /* @__PURE__ */ new Date(`${last}T00:00:00`);
970
+ while (cursor <= end) {
971
+ const day = dayKeyOf(cursor);
972
+ points.push({
973
+ day,
974
+ tokens: tokens.get(day) ?? 0
975
+ });
976
+ cursor.setDate(cursor.getDate() + 1);
977
+ }
978
+ return points;
979
+ }
980
+ /** Local `YYYY-MM-DDTHH` key of a date, matching the host's hour convention. */
981
+ function hourKeyOf(date) {
982
+ const hour = String(date.getHours()).padStart(2, "0");
983
+ return `${dayKeyOf(date)}T${hour}`;
984
+ }
985
+ /**
986
+ * The zero-filled hourly token series over a day range: every whole hour of
987
+ * the range appears once (hours without records plot as zero), so a single
988
+ * day yields the full 00:00–23:00 sequence and future hours of today read
989
+ * zero. The per-(hour, model) rows fold by hour. Absent bounds fall back to
990
+ * the first/last row hour; no rows and no range yield [].
991
+ * @param rows - the (already filtered) per-hour × per-model rows.
992
+ * @param from - first day key (`YYYY-MM-DD`), inclusive; the series starts
993
+ * at that day's 00:00.
994
+ * @param to - last day key, inclusive; the series ends at that day's 23:00.
995
+ */
996
+ function hourSeries(rows, from, to) {
997
+ const first = from !== void 0 ? `${from}T00` : rows[0]?.hour;
998
+ const last = to !== void 0 ? `${to}T23` : rows.length > 0 ? rows[rows.length - 1].hour : void 0;
999
+ if (first === void 0 || last === void 0 || first > last) return [];
1000
+ const tokens = /* @__PURE__ */ new Map();
1001
+ for (const row of rows) tokens.set(row.hour, (tokens.get(row.hour) ?? 0) + totalTokens(row.totals));
1002
+ const points = [];
1003
+ const cursor = /* @__PURE__ */ new Date(`${first.slice(0, 10)}T${first.slice(11)}:00:00`);
1004
+ const end = /* @__PURE__ */ new Date(`${last.slice(0, 10)}T${last.slice(11)}:00:00`);
1005
+ while (cursor <= end) {
1006
+ const hour = hourKeyOf(cursor);
1007
+ points.push({
1008
+ hour,
1009
+ tokens: tokens.get(hour) ?? 0
1010
+ });
1011
+ cursor.setHours(cursor.getHours() + 1);
1012
+ }
1013
+ return points;
1014
+ }
1015
+ //#endregion
1016
+ //#region src/client/format.ts
1017
+ /** One decimal below 10, integer otherwise, trailing `.0` stripped. */
1018
+ function scale(value) {
1019
+ if (value >= 10) return String(Math.round(value));
1020
+ const oneDecimal = value.toFixed(1);
1021
+ return oneDecimal.endsWith(".0") ? oneDecimal.slice(0, -2) : oneDecimal;
1022
+ }
1023
+ /**
1024
+ * Abbreviate a token count: raw below 1K, `xxK` below 1M, `xxM` below 10 亿
1025
+ * (1e9) — 1 亿 is `100M`, 2.5 亿 is `250M`, 9.5 亿 is `950M` — and `xxB`
1026
+ * only from 10 亿 up (B = 10 亿, no fractional-B tier): `1B`, `1.5B`, `3B`.
1027
+ * One decimal while the scaled value is below 10, integer otherwise —
1028
+ * `950K`, `1.5M`, `950M`, `3B`.
1029
+ * @param count - a non-negative token count.
1030
+ * @returns the compact display string.
1031
+ */
1032
+ function formatTokens(count) {
1033
+ if (count < 1e3) return String(count);
1034
+ if (count < 1e6) return scale(count / 1e3) + "K";
1035
+ if (count < 1e9) return scale(count / 1e6) + "M";
1036
+ return scale(count / 1e9) + "B";
1037
+ }
1038
+ /** Always one decimal (stripped when `.0`), unlike {@link scale}: percentages keep their precision. */
1039
+ function percent(value) {
1040
+ const oneDecimal = value.toFixed(1);
1041
+ return oneDecimal.endsWith(".0") ? oneDecimal.slice(0, -2) : oneDecimal;
1042
+ }
1043
+ /** Hit-rate thresholds (inclusive lower bound, exclusive upper). Boundary
1044
+ * values sit in the higher tier: 0.60 is `amber`, 0.80 is `lime`, 0.95
1045
+ * is `healthy`. The numbers are guideposts, not hard cutoffs — a 78%
1046
+ * cache hit rate is still in `amber`, exactly because cache misses at
1047
+ * ~1/5 of requests is worth flagging. */
1048
+ const HIT_RATE_AMBER = .6;
1049
+ const HIT_RATE_LIME = .8;
1050
+ const HIT_RATE_HEALTHY = .95;
1051
+ /** Map a 0-1 fraction to one of the four chip color buckets. */
1052
+ function bandOf(hitRate) {
1053
+ if (hitRate >= HIT_RATE_HEALTHY) return "healthy";
1054
+ if (hitRate >= HIT_RATE_LIME) return "lime";
1055
+ if (hitRate >= HIT_RATE_AMBER) return "amber";
1056
+ return "critical";
1057
+ }
1058
+ /**
1059
+ * Compute the cache hit rate's display shape in one pass.
1060
+ * @param totals - the aggregated totals.
1061
+ * @returns `{ text, band }` — `text` is `—` for an empty denominator,
1062
+ * `band` defaults to `amber` so an unused session reads as a mild
1063
+ * "no signal yet" (neither alarming nor celebratory).
1064
+ */
1065
+ function hitRateDisplay(totals) {
1066
+ const served = totals.inputTokens + totals.cacheReadTokens;
1067
+ if (served === 0) return {
1068
+ text: "—",
1069
+ band: "amber"
1070
+ };
1071
+ const rate = totals.cacheReadTokens / served;
1072
+ return {
1073
+ text: `${percent(rate * 100)}%`,
1074
+ band: bandOf(rate)
1075
+ };
1076
+ }
1077
+ /** The RMB display view: amounts render as stored. */
1078
+ const CNY_VIEW = {
1079
+ symbol: "¥",
1080
+ rate: 1
1081
+ };
1082
+ /**
1083
+ * The display view of one stats summary: USD when the region pick says so
1084
+ * (amounts ÷ `usdExchangeRate`, `$` prefix), else RMB as stored.
1085
+ * @param summary - the stats payload (its `currency`/`usdExchangeRate` fields).
1086
+ * @returns the view the format functions render through.
1087
+ */
1088
+ function currencyViewOf(summary) {
1089
+ return summary.currency === "USD" ? {
1090
+ symbol: "$",
1091
+ rate: summary.usdExchangeRate
1092
+ } : CNY_VIEW;
1093
+ }
1094
+ /**
1095
+ * Cost as display text: the view's symbol plus two decimals, following the
1096
+ * analyzer's cost formatting (`¥1.25`, `$0.18`). A cost is always shown,
1097
+ * never omitted. USD divides the wire's RMB amount by the exchange rate.
1098
+ * @param cost - a non-negative cost in ¥ (as carried on the wire).
1099
+ * @param view - the display currency view.
1100
+ * @returns e.g. `¥1.25`, or `$0.18` under a rate-7 USD view.
1101
+ */
1102
+ function formatCost(cost, view = CNY_VIEW) {
1103
+ return `${view.symbol}${(cost / view.rate).toFixed(2)}`;
1104
+ }
1105
+ /**
1106
+ * A per-million-token rate as display text, converted through the view:
1107
+ * integral rates stay bare (`8`, `$1.14`-style conversion applied first for
1108
+ * USD), fractional ones keep up to four decimals with trailing zeros
1109
+ * stripped and a two-decimal minimum (`0.50`, `0.25`, `0.025`). The caller
1110
+ * appends the `/M` unit and the view's symbol where needed.
1111
+ * @param rate - a non-negative rate in ¥ per million tokens.
1112
+ * @param view - the display currency view.
1113
+ * @returns the display string (symbol-less, converted for USD).
1114
+ */
1115
+ function formatRate(rate, view = CNY_VIEW) {
1116
+ const converted = rate / view.rate;
1117
+ if (Number.isInteger(converted)) return String(converted);
1118
+ let s = converted.toFixed(4);
1119
+ const dot = s.indexOf(".");
1120
+ s = s.replace(/0+$/u, "");
1121
+ if (s.endsWith(".")) s += "00";
1122
+ const minEnd = dot + 3;
1123
+ while (s.length < minEnd) s += "0";
1124
+ return s;
1125
+ }
1126
+ /**
1127
+ * A per-million-token rate as complete display text: the view's symbol plus
1128
+ * {@link formatRate}'s converted number — what the pricing table cells render.
1129
+ * @param rate - a non-negative rate in ¥ per million tokens.
1130
+ * @param view - the display currency view.
1131
+ * @returns e.g. `¥8`, or `$1.1429` under a rate-7 USD view.
1132
+ */
1133
+ function formatRateWithSymbol(rate, view = CNY_VIEW) {
1134
+ return `${view.symbol}${formatRate(rate, view)}`;
1135
+ }
1136
+ /**
1137
+ * Average first-token latency in the shell's compact duration shape:
1138
+ * one decimal under a minute (`45.2s`), `2m42s` from there on.
1139
+ * @param ms - total first-token latency.
1140
+ * @returns the display string.
1141
+ */
1142
+ function formatTtft(ms) {
1143
+ const s = ms / 1e3;
1144
+ if (s < 60) return `${String(Math.round(s * 10) / 10)}s`;
1145
+ const whole = Math.round(s);
1146
+ return `${Math.floor(whole / 60)}m${whole % 60}s`;
1147
+ }
1148
+ /**
1149
+ * Decode-throughput display figure in the shell's shape: whole tokens from
1150
+ * ten up, one decimal below (the `tok/s` unit lives in the locale template).
1151
+ * @param tokensPerSecond - tokens per second.
1152
+ * @returns the display number.
1153
+ */
1154
+ function formatSpeed(tokensPerSecond) {
1155
+ const clamped = Math.max(0, tokensPerSecond);
1156
+ return clamped >= 10 ? String(Math.round(clamped)) : String(Math.round(clamped * 10) / 10);
1157
+ }
1158
+ //#endregion
1159
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\hit-rate-band.module.css.mjs
1160
+ const css$6 = ".t6JM8a_band_critical{color:var(--dsw-alias-state-error-primary,#dc2626)}.t6JM8a_band_amber{color:#f59e0b}.t6JM8a_band_lime{color:#84cc16}.t6JM8a_band_healthy{color:var(--dsw-alias-state-success-primary,#16a34a)}";
1161
+ const tagId$6 = "dsh-token-usage/hit-rate-band.module.css";
1162
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$6) + "]") === null) {
1163
+ const tag = document.createElement("style");
1164
+ tag.dataset.plugin = "dsh-token-usage";
1165
+ tag.dataset.pluginCss = tagId$6;
1166
+ tag.textContent = css$6;
1167
+ document.head.appendChild(tag);
1168
+ }
1169
+ var hit_rate_band_module_css_default = {
1170
+ "band_amber": "t6JM8a_band_amber",
1171
+ "band_critical": "t6JM8a_band_critical",
1172
+ "band_healthy": "t6JM8a_band_healthy",
1173
+ "band_lime": "t6JM8a_band_lime"
1174
+ };
1175
+ //#endregion
1176
+ //#region src/client/HitRateText.tsx
1177
+ /** CSS-module class for one hit-rate colour bucket. */
1178
+ function bandClassOf(band) {
1179
+ return hit_rate_band_module_css_default[`band_${band}`] ?? "";
1180
+ }
1181
+ /**
1182
+ * Render a hit-rate percentage (or `—`) in its threshold colour.
1183
+ * @param totals - the aggregated token buckets the rate is computed from.
1184
+ */
1185
+ function HitRateText({ totals }) {
1186
+ const { text, band } = hitRateDisplay(totals);
1187
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1188
+ className: bandClassOf(band),
1189
+ children: text
1190
+ });
1191
+ }
1192
+ //#endregion
1193
+ //#region src/client/session-stats.ts
1194
+ /** Build a session-parent → direct-subagent-children index in one O(n) pass:
1195
+ * every session whose `origin === 'subagent'` lands in its `parentId`'s
1196
+ * bucket, in iteration order (so the result matches {@link directSubagentIds}).
1197
+ * @param rows - the retained session-summary mirror.
1198
+ * @returns the immutable child index.
1199
+ */
1200
+ function buildChildIndex(rows) {
1201
+ const index = /* @__PURE__ */ new Map();
1202
+ for (const [id, summary] of Object.entries(rows)) {
1203
+ if (summary.origin !== "subagent" || summary.parentId === void 0) continue;
1204
+ const bucket = index.get(summary.parentId);
1205
+ if (bucket === void 0) index.set(summary.parentId, [id]);
1206
+ else bucket.push(id);
1207
+ }
1208
+ return index;
1209
+ }
1210
+ /** Look up the direct subagent children of one session. Falls back to a
1211
+ * fresh {@link buildChildIndex} when the caller has no cached index. */
1212
+ function directSubagentIds(rows, parentId, index) {
1213
+ if (index !== void 0) return index.get(parentId) ?? [];
1214
+ return buildChildIndex(rows).get(parentId) ?? [];
1215
+ }
1216
+ /**
1217
+ * The whole subagent subtree of one session, including the root itself,
1218
+ * using the parent → children index for an O(n) walk regardless of depth.
1219
+ * Cycles are bounded by a `seen` set (a depth-first traversal visits each
1220
+ * id once), so a self-referential or cyclic record set returns the root
1221
+ * alone. Stacks are reversed after pushing so siblings come back out in
1222
+ * insertion order, matching the runtime's lineage index.
1223
+ * @param rows - the retained session-summary mirror (unused when the
1224
+ * caller already built an index).
1225
+ * @param rootId - the scope's root session id.
1226
+ * @param index - optional precomputed index from {@link buildChildIndex}.
1227
+ * @returns the root and its subagent descendants, depth-first.
1228
+ */
1229
+ function subtreeIds(rows, rootId, index = buildChildIndex(rows)) {
1230
+ const out = [rootId];
1231
+ if (!index.has(rootId) && rows[rootId] === void 0) return out;
1232
+ const seen = /* @__PURE__ */ new Set([rootId]);
1233
+ const stack = [];
1234
+ const seedChildren = index.get(rootId) ?? [];
1235
+ for (let i = seedChildren.length - 1; i >= 0; i -= 1) stack.push(seedChildren[i]);
1236
+ while (stack.length > 0) {
1237
+ const current = stack.pop();
1238
+ if (seen.has(current)) continue;
1239
+ seen.add(current);
1240
+ out.push(current);
1241
+ const children = index.get(current) ?? [];
1242
+ for (let i = children.length - 1; i >= 0; i -= 1) stack.push(children[i]);
1243
+ }
1244
+ return out;
1245
+ }
1246
+ /**
1247
+ * The immediate subagent parent of one session, when the record names one.
1248
+ * The check is on `parentId` rather than `origin` so a mirrored summary that
1249
+ * lost its origin tag still answers its lineage — the index is built once
1250
+ * per render and shared across all three helpers via {@link ChildIndex}.
1251
+ * @param rows - the retained session-summary mirror.
1252
+ * @param id - the current focus session id.
1253
+ * @returns the parent session id, or undefined when the record has no
1254
+ * parent link (a top-level session or an ordinary fork).
1255
+ */
1256
+ function subagentParentOf(rows, id) {
1257
+ const parent = rows[id]?.parentId;
1258
+ return parent === void 0 || parent === id ? void 0 : parent;
1259
+ }
1260
+ /**
1261
+ * Sum one or more `SessionStatsProjection` values over a scope. A scope with
1262
+ * no value at all yields `undefined` — the view renders an em-dash for an
1263
+ * absent capability. The `contributing` count lets the caller tell
1264
+ * "every scope session was empty" apart from "the scope itself was empty".
1265
+ * @param values - the per-session projection values (typically drawn from
1266
+ * the mirror + the live hook).
1267
+ * @returns the summed buckets plus the contributing count, or undefined
1268
+ * when no projection was present.
1269
+ */
1270
+ function aggregateProjections(values) {
1271
+ let ttftMs = 0;
1272
+ let ttftSteps = 0;
1273
+ let decodeMs = 0;
1274
+ let decodeTokens = 0;
1275
+ let contributing = 0;
1276
+ for (const stats of values) {
1277
+ if (stats === void 0) continue;
1278
+ contributing += 1;
1279
+ ttftMs += stats.ttftMs;
1280
+ ttftSteps += stats.ttftSteps;
1281
+ decodeMs += stats.decodeMs;
1282
+ decodeTokens += stats.decodeTokens;
1283
+ }
1284
+ if (contributing === 0) return void 0;
1285
+ return {
1286
+ ttftMs,
1287
+ ttftSteps,
1288
+ decodeMs,
1289
+ decodeTokens,
1290
+ contributing
1291
+ };
1292
+ }
1293
+ /**
1294
+ * Compact fingerprint of one session's retained stats projection — bumps on
1295
+ * every finished request step (same signal that drives TTFT / throughput).
1296
+ */
1297
+ function sessionStatsFingerprint(stats) {
1298
+ if (stats === void 0) return "-";
1299
+ return [
1300
+ stats.steps,
1301
+ stats.ttftSteps,
1302
+ stats.decodeTokens,
1303
+ stats.turns
1304
+ ].join(".");
1305
+ }
1306
+ /**
1307
+ * Build a debounce key from mirror `updatedAt` plus `sessionStats` churn.
1308
+ * The active session reads live projection values from `useProjection`; every
1309
+ * other scoped id reads the mirror copy.
1310
+ */
1311
+ function buildStatsFreshnessKey(ids, options) {
1312
+ return ids.map((id) => {
1313
+ const row = options.rows[id];
1314
+ const stats = id === options.activeSessionId ? options.liveSessionStats ?? row?.projectionValues?.sessionStats : row?.projectionValues?.sessionStats;
1315
+ return `${id}:${String(row?.updatedAt ?? 0)}:${sessionStatsFingerprint(stats)}`;
1316
+ }).join(",");
1317
+ }
1318
+ //#endregion
1319
+ //#region src/client/cost-inflate-motion.ts
1320
+ /** The user's motion preference: both runners refuse to animate (returning
1321
+ * null) when the OS asks for reduced motion. Exported so the chip hook can
1322
+ * skip spawning the DOM for flies that would never animate — a static +Δ
1323
+ * flash reads as a glitch, not information. */
1324
+ function motionAllowed() {
1325
+ return typeof window.matchMedia !== "function" || !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1326
+ }
1327
+ function waapiAvailable(el) {
1328
+ return typeof el.animate === "function";
1329
+ }
1330
+ /** Scale bounce on the cost figure (`costPop`). */
1331
+ function runCostPop(el, v) {
1332
+ if (!motionAllowed() || !waapiAvailable(el)) return null;
1333
+ const popScale = Number(v.popScale);
1334
+ const echo = 1 + (popScale - 1) * .28;
1335
+ const warnMix = v.warnMix;
1336
+ return el.animate([
1337
+ {
1338
+ transform: "scale(1)",
1339
+ color: "var(--dsw-alias-label-primary)"
1340
+ },
1341
+ {
1342
+ transform: `scale(${String(popScale)})`,
1343
+ color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-primary))`,
1344
+ offset: .35
1345
+ },
1346
+ {
1347
+ transform: `scale(${String(echo)})`,
1348
+ color: `color-mix(in srgb, var(--dsw-alias-state-warn-primary) ${warnMix}, var(--dsw-alias-label-primary))`,
1349
+ offset: .7
1350
+ },
1351
+ {
1352
+ transform: "scale(1)",
1353
+ color: "var(--dsw-alias-label-primary)"
1354
+ }
1355
+ ], {
1356
+ duration: v.inflateMs,
1357
+ easing: "cubic-bezier(0.25, 0.85, 0.35, 1)",
1358
+ fill: "both"
1359
+ });
1360
+ }
1361
+ /** +Δ label rise (`deltaRise`). Caller must position the element (absolute). */
1362
+ function runDeltaFly(el, v) {
1363
+ if (!motionAllowed() || !waapiAvailable(el)) return null;
1364
+ return el.animate([
1365
+ {
1366
+ opacity: 0,
1367
+ transform: "translate(-50%, -20%)"
1368
+ },
1369
+ {
1370
+ opacity: 1,
1371
+ transform: "translate(-50%, -20%)",
1372
+ offset: .15
1373
+ },
1374
+ {
1375
+ opacity: 0,
1376
+ transform: `translate(calc(-50% + ${v.flyX}), calc(-100% - ${v.flyY}))`
1377
+ }
1378
+ ], {
1379
+ duration: v.inflateMs,
1380
+ easing: "cubic-bezier(0.22, 0.55, 0.25, 1)",
1381
+ fill: "both"
1382
+ });
1383
+ }
1384
+ //#endregion
1385
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\SessionStatsChip.module.css.mjs
1386
+ const css$5 = ".d5ISLa_strip{border:1px solid var(--dsw-alias-border-l2);font-variant-numeric:tabular-nums;background:0 0;border-radius:14px;flex:none;align-items:stretch;min-width:0;height:28px;font-size:12px;line-height:18px;display:inline-flex;overflow:hidden}.d5ISLa_stripFlyOverflow{z-index:2;position:relative;overflow:visible}.d5ISLa_cell{color:var(--dsw-alias-label-primary);white-space:nowrap;align-items:center;padding:0 10px;display:inline-flex}.d5ISLa_cell+.d5ISLa_cell{border-left:1px solid var(--dsw-alias-border-l1)}.d5ISLa_cellHit{font-weight:500}.d5ISLa_costCell{z-index:1;position:relative;overflow:visible}.d5ISLa_costInner{transform-origin:50%;z-index:2;justify-content:center;align-items:center;display:inline-flex;position:relative}.d5ISLa_deltaLayer{pointer-events:none;z-index:3;position:absolute;inset:0;overflow:visible}.d5ISLa_deltaFly{color:var(--dsw-alias-state-warn-primary);font-variant-numeric:tabular-nums;white-space:nowrap;pointer-events:none;text-shadow:0 0 8px color-mix(in srgb, var(--dsw-alias-state-warn-primary) 35%, transparent);font-size:11px;font-weight:600;position:absolute;top:0;left:50%;transform:translate(-50%,-100%)}@media (prefers-reduced-motion:reduce){.d5ISLa_deltaFly{display:none}}@media (width<=560px){.d5ISLa_strip{font-size:11px}.d5ISLa_cell{padding:0 7px}}";
1387
+ const tagId$5 = "dsh-token-usage/SessionStatsChip.module.css";
1388
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$5) + "]") === null) {
1389
+ const tag = document.createElement("style");
1390
+ tag.dataset.plugin = "dsh-token-usage";
1391
+ tag.dataset.pluginCss = tagId$5;
1392
+ tag.textContent = css$5;
1393
+ document.head.appendChild(tag);
1394
+ }
1395
+ var SessionStatsChip_module_css_default = {
1396
+ "cell": "d5ISLa_cell",
1397
+ "cellHit": "d5ISLa_cellHit",
1398
+ "costCell": "d5ISLa_costCell",
1399
+ "costInner": "d5ISLa_costInner",
1400
+ "deltaFly": "d5ISLa_deltaFly",
1401
+ "deltaLayer": "d5ISLa_deltaLayer",
1402
+ "strip": "d5ISLa_strip",
1403
+ "stripFlyOverflow": "d5ISLa_stripFlyOverflow"
1404
+ };
1405
+ //#endregion
1406
+ //#region src/client/CostDeltaFlyLabel.tsx
1407
+ /** One +Δ fly label; animation starts on mount via WAAPI. */
1408
+ function CostDeltaFlyLabel({ text, vars }) {
1409
+ const ref = (0, react.useRef)(null);
1410
+ (0, react.useLayoutEffect)(() => {
1411
+ const el = ref.current;
1412
+ if (el === null) return;
1413
+ const anim = runDeltaFly(el, vars);
1414
+ if (anim === null) {
1415
+ el.style.visibility = "hidden";
1416
+ return;
1417
+ }
1418
+ return () => {
1419
+ anim.cancel();
1420
+ };
1421
+ }, [vars]);
1422
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1423
+ ref,
1424
+ className: SessionStatsChip_module_css_default["deltaFly"],
1425
+ children: text
1426
+ });
1427
+ }
1428
+ //#endregion
1429
+ //#region src/client/cost-inflate.ts
1430
+ const MISS_RATE_CAP = .55;
1431
+ const OUT_CAP = 32e3;
1432
+ /** Clamp to the unit interval. */
1433
+ function clamp01(n) {
1434
+ return Math.max(0, Math.min(1, n));
1435
+ }
1436
+ /** Token totals of one refresh minus the previous snapshot (non-negative). */
1437
+ function deltaTotals(prev, next) {
1438
+ return {
1439
+ requests: Math.max(0, next.requests - prev.requests),
1440
+ inputTokens: Math.max(0, next.inputTokens - prev.inputTokens),
1441
+ outputTokens: Math.max(0, next.outputTokens - prev.outputTokens),
1442
+ cacheReadTokens: Math.max(0, next.cacheReadTokens - prev.cacheReadTokens),
1443
+ cacheWriteTokens: Math.max(0, next.cacheWriteTokens - prev.cacheWriteTokens)
1444
+ };
1445
+ }
1446
+ /**
1447
+ * Single-step intensity from the latest request's token delta (not session
1448
+ * cumulative hit rate): `I = clamp01(0.55·norm(miss) + 0.45·norm(output))`.
1449
+ */
1450
+ function computeIntensityFromDelta(delta) {
1451
+ const served = delta.inputTokens + delta.cacheReadTokens;
1452
+ const miss = clamp01((1 - (served > 0 ? delta.cacheReadTokens / served : .5)) / MISS_RATE_CAP);
1453
+ const out = clamp01(delta.outputTokens / OUT_CAP);
1454
+ return clamp01(.55 * miss + .45 * out);
1455
+ }
1456
+ function lerp(a, b, t) {
1457
+ return a + (b - a) * t;
1458
+ }
1459
+ /** Map step intensity I to animation parameters. */
1460
+ function animVars(I) {
1461
+ return {
1462
+ inflateMs: Math.round(lerp(1e3, 1800, I)),
1463
+ popScale: lerp(1.08, 1.32, I).toFixed(3),
1464
+ warnMix: `${Math.round(lerp(0, 55, I))}%`,
1465
+ flyY: `${lerp(22, 38, I).toFixed(1)}px`,
1466
+ flyX: `${((Math.random() - .5) * 10).toFixed(1)}px`
1467
+ };
1468
+ }
1469
+ //#endregion
1470
+ //#region src/client/use-cost-inflate.ts
1471
+ /**
1472
+ * Request-driven cost-cell inflate animation for SessionStatsChip: detects
1473
+ * new usage from summary deltas and drives WAAPI motion on the cost figure
1474
+ * and ephemeral +Δ fly labels.
1475
+ *
1476
+ * @module token-usage/client/use-cost-inflate
1477
+ */
1478
+ const MIN_WIRE_DELTA_COST = 5e-4;
1479
+ function hasUsageChurn(prev, summary) {
1480
+ const delta = deltaTotals(prev.totals, summary.total);
1481
+ if (delta.requests > 0) return true;
1482
+ if (summary.totalCost - prev.totalCost > MIN_WIRE_DELTA_COST) return true;
1483
+ return totalTokens(delta) > 0;
1484
+ }
1485
+ /**
1486
+ * Hook the chip uses to play costPop + deltaRise on each new request.
1487
+ * @param scopeKey - changes reset the diff baseline.
1488
+ * @param costRef - the live cost figure span (WAAPI target).
1489
+ */
1490
+ function useCostInflate(scopeKey, costRef) {
1491
+ const prevRef = (0, react.useRef)(null);
1492
+ const flyIdRef = (0, react.useRef)(0);
1493
+ const timersRef = (0, react.useRef)([]);
1494
+ const flyCountRef = (0, react.useRef)(0);
1495
+ const popAnimRef = (0, react.useRef)(null);
1496
+ const [flies, setFlies] = (0, react.useState)([]);
1497
+ const [flyOverflow, setFlyOverflow] = (0, react.useState)(false);
1498
+ const clearTimers = (0, react.useCallback)(() => {
1499
+ for (const id of timersRef.current) window.clearTimeout(id);
1500
+ timersRef.current = [];
1501
+ }, []);
1502
+ const schedule = (0, react.useCallback)((fn, ms) => {
1503
+ const id = window.setTimeout(fn, ms);
1504
+ timersRef.current.push(id);
1505
+ }, []);
1506
+ const reset = (0, react.useCallback)(() => {
1507
+ clearTimers();
1508
+ popAnimRef.current?.cancel();
1509
+ popAnimRef.current = null;
1510
+ prevRef.current = null;
1511
+ flyIdRef.current = 0;
1512
+ flyCountRef.current = 0;
1513
+ setFlies([]);
1514
+ setFlyOverflow(false);
1515
+ }, [clearTimers]);
1516
+ (0, react.useEffect)(() => {
1517
+ reset();
1518
+ }, [scopeKey, reset]);
1519
+ (0, react.useEffect)(() => () => {
1520
+ clearTimers();
1521
+ }, [clearTimers]);
1522
+ const maybeClearOverflow = (0, react.useCallback)(() => {
1523
+ if (flyCountRef.current <= 0) setFlyOverflow(false);
1524
+ }, []);
1525
+ const playCostPop = (0, react.useCallback)((v) => {
1526
+ const el = costRef.current;
1527
+ if (el === null) return;
1528
+ popAnimRef.current?.cancel();
1529
+ popAnimRef.current = runCostPop(el, v);
1530
+ }, [costRef]);
1531
+ return {
1532
+ flies,
1533
+ flyOverflow,
1534
+ onSummary: (0, react.useCallback)((summary) => {
1535
+ const nextSnapshot = {
1536
+ totals: summary.total,
1537
+ totalCost: summary.totalCost
1538
+ };
1539
+ const prev = prevRef.current;
1540
+ prevRef.current = nextSnapshot;
1541
+ if (prev === null) return;
1542
+ if (!hasUsageChurn(prev, summary)) return;
1543
+ if (!motionAllowed()) return;
1544
+ const v = animVars(computeIntensityFromDelta(deltaTotals(prev.totals, summary.total)));
1545
+ setFlyOverflow(true);
1546
+ window.requestAnimationFrame(() => {
1547
+ playCostPop(v);
1548
+ });
1549
+ const wireDeltaCost = summary.totalCost - prev.totalCost;
1550
+ if (wireDeltaCost > MIN_WIRE_DELTA_COST) {
1551
+ const view = currencyViewOf(summary);
1552
+ const text = `+${view.symbol}${(wireDeltaCost / view.rate).toFixed(2)}`;
1553
+ const id = ++flyIdRef.current;
1554
+ flyCountRef.current += 1;
1555
+ setFlies((current) => [...current, {
1556
+ id,
1557
+ text,
1558
+ vars: v
1559
+ }]);
1560
+ schedule(() => {
1561
+ flyCountRef.current -= 1;
1562
+ setFlies((current) => current.filter((fly) => fly.id !== id));
1563
+ maybeClearOverflow();
1564
+ }, v.inflateMs + 40);
1565
+ } else schedule(maybeClearOverflow, v.inflateMs + 40);
1566
+ }, [
1567
+ maybeClearOverflow,
1568
+ playCostPop,
1569
+ schedule
1570
+ ]),
1571
+ reset
1572
+ };
1573
+ }
1574
+ //#endregion
1575
+ //#region src/client/SessionStatsChip.tsx
1576
+ /**
1577
+ * Session-header stats chip (browser half): a one-line compact strip rendered
1578
+ * into the `conversation.session.header.utilities` slot — three sub-chips
1579
+ * (total tokens / cache hit rate / session cost) beside the Session log
1580
+ * button. Data comes from `/token-usage/stats?fields=chip` scoped to the
1581
+ * active session and its subagent subtree (the Usage tab's "with
1582
+ * subagents" range), so a parent that spawned children shows the same
1583
+ * folded numbers the header is meant to summarise. Numbers refresh at
1584
+ * REQUEST granularity (same cadence as the Usage tab): `sessionStats`
1585
+ * projection churn (plus mirror `updatedAt` when present) is debounced
1586
+ * into one fetch, so idle sessions do not poll and a finished request
1587
+ * updates the header within ~250 ms. When cost
1588
+ * rises on a new request, the cost cell plays `costPop` (scale bounce) and
1589
+ * `deltaRise` (+Δ fly); reduced-motion users get silent figure updates
1590
+ * instead. A failed FIRST fetch retries itself on a 3 s cadence — the old
1591
+ * poll's safety net — so an idle-but-used session still gets its chip.
1592
+ *
1593
+ * Visibility contract: a session with no recorded requests renders nothing
1594
+ * (an empty header strip is worse than no strip; the chip never blanks to
1595
+ * "—"). Hit-rate colour is the four-bucket mapping in `format.hitRateDisplay`:
1596
+ * ≥95% healthy (green), 80–95% lime, 60–80% amber, below 60% critical (red).
1597
+ * Amber/lime fill the warm→cool gap so the four stops read as one progression.
1598
+ *
1599
+ * @module token-usage/client/SessionStatsChip
1600
+ */
1601
+ /** Refresh debounce: bursts of session-mirror updates (one request's events)
1602
+ * collapse into a single fetch, matching the Usage tab's request-scale
1603
+ * cadence instead of a steady poll. */
1604
+ const REFRESH_DEBOUNCE_MS$1 = 250;
1605
+ /** Self-heal cadence after a failed first fetch. With the poll gone, this
1606
+ * retry is the only thing that recovers an idle session's chip: refresh
1607
+ * failures after the first land keep the prior figures (silent mode) and
1608
+ * self-heal on the next request churn, so they never reach the error state. */
1609
+ const FETCH_FAILURE_RETRY_MS = 3e3;
1610
+ /**
1611
+ * Render the session-header stats chip for the active session. Renders
1612
+ * nothing when the session has no recorded usage, when the fetch fails, or
1613
+ * while the first fetch is in flight — the spec's "data has no value, the
1614
+ * block does not render" rule.
1615
+ * @param props - framework session id, the session-list mirror, and the locale seat.
1616
+ * @returns the chip strip, or null when the data is empty/unavailable.
1617
+ */
1618
+ function SessionStatsChip({ sessionId, useSessions, useProjection, t }) {
1619
+ const rootRef = (0, react.useRef)(null);
1620
+ const costRef = (0, react.useRef)(null);
1621
+ useColorSchemeMirror(rootRef);
1622
+ const byId = useSessions((state) => state.byId);
1623
+ const childIndex = (0, react.useMemo)(() => buildChildIndex(byId), [byId]);
1624
+ const scopeIds = (0, react.useMemo)(() => sessionId === "" ? [] : subtreeIds(byId, sessionId, childIndex), [
1625
+ byId,
1626
+ sessionId,
1627
+ childIndex
1628
+ ]);
1629
+ const freshnessKey = buildStatsFreshnessKey(scopeIds, {
1630
+ activeSessionId: sessionId,
1631
+ rows: byId,
1632
+ liveSessionStats: useProjection("sessionStats")
1633
+ });
1634
+ const debouncedKey = useDebouncedValue(`${scopeIds.join("\n")}\n\t${freshnessKey}`, REFRESH_DEBOUNCE_MS$1);
1635
+ const { flies, flyOverflow, onSummary } = useCostInflate(scopeIds.join("\n"), costRef);
1636
+ const [resource, retry] = useAsyncResource((signal) => {
1637
+ const [idsPart] = debouncedKey.split("\n ");
1638
+ return fetchSessionSummary$1((idsPart ?? "").split("\n").filter((id) => id !== ""), signal);
1639
+ }, [debouncedKey], {
1640
+ silentAfterFirst: true,
1641
+ retryToken: 0
1642
+ });
1643
+ const summary = resource.status === "ready" ? resource.value : null;
1644
+ (0, react.useEffect)(() => {
1645
+ if (summary !== null) onSummary(summary);
1646
+ }, [summary, onSummary]);
1647
+ (0, react.useEffect)(() => {
1648
+ if (resource.status !== "error") return;
1649
+ const timer = window.setTimeout(retry, FETCH_FAILURE_RETRY_MS);
1650
+ return () => {
1651
+ window.clearTimeout(timer);
1652
+ };
1653
+ }, [resource, retry]);
1654
+ if (summary === null || summary.total.requests === 0) return null;
1655
+ const view = currencyViewOf(summary);
1656
+ const { total } = summary;
1657
+ const tokensText = formatTokens(totalTokens(total));
1658
+ const hitText = hitRateDisplay(total).text;
1659
+ const costText = formatCost(summary.totalCost, view);
1660
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1661
+ ref: rootRef,
1662
+ className: `${SessionStatsChip_module_css_default["strip"]}${flyOverflow ? ` ${SessionStatsChip_module_css_default["stripFlyOverflow"]}` : ""}`,
1663
+ role: "group",
1664
+ "aria-label": t("view.usage"),
1665
+ children: [
1666
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1667
+ className: SessionStatsChip_module_css_default["cell"],
1668
+ "aria-label": t("chip.tokens", { value: tokensText }),
1669
+ children: tokensText
1670
+ }),
1671
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1672
+ className: `${SessionStatsChip_module_css_default["cell"]} ${SessionStatsChip_module_css_default["cellHit"]}`,
1673
+ "aria-label": t("chip.hitRate", { value: hitText }),
1674
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HitRateText, { totals: total })
1675
+ }),
1676
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1677
+ className: `${SessionStatsChip_module_css_default["cell"]} ${SessionStatsChip_module_css_default["costCell"]}`,
1678
+ "aria-label": t("chip.cost", { value: costText }),
1679
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1680
+ ref: costRef,
1681
+ className: SessionStatsChip_module_css_default["costInner"],
1682
+ children: costText
1683
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1684
+ className: SessionStatsChip_module_css_default["deltaLayer"],
1685
+ "aria-hidden": "true",
1686
+ children: flies.map((fly) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CostDeltaFlyLabel, {
1687
+ text: fly.text,
1688
+ vars: fly.vars
1689
+ }, fly.id))
1690
+ })]
1691
+ })
1692
+ ]
1693
+ });
1694
+ }
1695
+ /** Defensive shape check: an older host build or a misrouted response
1696
+ * would otherwise paint the header chip with garbage. */
1697
+ function looksLikeUsageSummary(value) {
1698
+ return typeof value === "object" && value !== null && typeof value.total === "object" && value.total !== null;
1699
+ }
1700
+ /**
1701
+ * Fetch the summary scoped to one session and its subagent subtree. Throws
1702
+ * on transport failure (network, abort, non-2xx response, or a payload
1703
+ * that doesn't look like a stats summary) so the hook can keep the
1704
+ * previous render in place — a transient miss never blanks the chip. The
1705
+ * hook's `silentAfterFirst` flag is what suppresses the resulting error
1706
+ * state.
1707
+ * @param sessionIds - the active session plus its subagent descendants;
1708
+ * an empty list skips the fetch (returning null rather than throwing, so
1709
+ * the hook's first-load gate stays at "loading").
1710
+ * @param signal - the cancellation signal from the hook.
1711
+ */
1712
+ async function fetchSessionSummary$1(sessionIds, signal) {
1713
+ if (sessionIds.length === 0) return null;
1714
+ const response = await fetch(STATS_PATH + encodeStatsQuery({
1715
+ sessionIds,
1716
+ fields: "chip"
1717
+ }), {
1718
+ headers: { accept: "application/json" },
1719
+ signal
1720
+ });
1721
+ if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
1722
+ const value = await response.json();
1723
+ if (!looksLikeUsageSummary(value)) throw new Error("unexpected stats response");
1724
+ return value;
1725
+ }
1726
+ //#endregion
1727
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\TokenUsageCard.module.css.mjs
1728
+ const css$4 = "._1bMeTa_card{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-3);border-radius:12px;list-style:none;transition:border-color .16s,background .16s}._1bMeTa_card:hover{border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_cardOpen{background:var(--dsw-alias-bg-layer-2);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_header{appearance:none;width:100%;font:inherit;color:inherit;text-align:left;cursor:pointer;background:0 0;border:0;border-radius:12px;align-items:center;gap:12px;padding:14px 16px;display:flex}._1bMeTa_header:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-2px}._1bMeTa_headText{flex-direction:column;flex:1;gap:4px;min-width:0;display:flex}._1bMeTa_name{color:var(--dsw-alias-label-primary);font-size:15px;font-weight:600;line-height:1.4}._1bMeTa_description{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.5}._1bMeTa_pending{white-space:nowrap;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary);border-radius:999px;flex:none;padding:1px 8px;font-size:11px;font-weight:500;line-height:17px}._1bMeTa_chevron{color:var(--dsw-alias-label-tertiary);flex:none;transition:transform .16s}._1bMeTa_chevronOpen{transform:rotate(180deg)}._1bMeTa_body{border-top:1px solid var(--dsw-alias-border-l2);flex-direction:column;gap:10px;margin:0 16px;padding:12px 0 8px;display:flex}._1bMeTa_note{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}._1bMeTa_field{flex-direction:column;gap:4px;display:flex}._1bMeTa_fieldLabel{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5}._1bMeTa_input{box-sizing:border-box;width:100%;font:inherit;color:var(--dsw-alias-label-primary);background-color:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);appearance:none;border-radius:6px;padding:4px 8px;font-size:13px;line-height:20px}._1bMeTa_input:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-1px}._1bMeTa_input:disabled{opacity:.6}._1bMeTa_inputRow{align-items:center;gap:6px;display:flex}._1bMeTa_inputRow ._1bMeTa_input{flex:1;min-width:0}._1bMeTa_browse{appearance:none;border:1px solid var(--dsw-alias-border-l2);font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;white-space:nowrap;background:0 0;border-radius:6px;flex:none;padding:4px 10px;font-size:13px;line-height:20px}._1bMeTa_browse:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_browse:disabled{opacity:.4;cursor:default}._1bMeTa_browse:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_hint{color:var(--dsw-alias-label-tertiary);margin:0;font-size:12px;line-height:1.5}._1bMeTa_migration{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);border-radius:6px;flex-direction:column;gap:4px;padding:8px 10px;display:flex}._1bMeTa_migrationLabel{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;font-size:12px;line-height:1.5}._1bMeTa_migrationBar{background:var(--dsw-alias-bg-multi-select);border-radius:2px;height:4px;display:block;overflow:hidden}._1bMeTa_migrationFill{background:var(--dsw-alias-brand-primary);border-radius:2px;height:100%;transition:width .2s;display:block}._1bMeTa_footer{border-top:1px solid var(--dsw-alias-border-l2);justify-content:flex-end;align-items:center;gap:8px;padding:8px 0 4px;display:flex}._1bMeTa_failed{min-width:0;color:var(--dsw-alias-label-error);flex:1;margin:0;font-size:12px;line-height:1.5}._1bMeTa_discard,._1bMeTa_save{appearance:none;font:inherit;cursor:pointer;border:1px solid #0000;border-radius:8px;padding:5px 14px;font-size:13px;line-height:1.5}._1bMeTa_discard{border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);background:0 0}._1bMeTa_discard:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_save{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3)}._1bMeTa_discard:disabled,._1bMeTa_save:disabled{opacity:.4;cursor:default}._1bMeTa_discard:focus-visible,._1bMeTa_save:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_fullSync{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);border-radius:8px;flex-direction:column;gap:8px;padding:10px 12px;display:flex}._1bMeTa_fullSyncHeader{flex-direction:column;gap:2px;display:flex}._1bMeTa_fullSyncTitle{color:var(--dsw-alias-label-primary);font-size:13px;font-weight:600;line-height:1.4}._1bMeTa_fullSyncHint{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:1.5}._1bMeTa_fullSyncButton{appearance:none;border:1px solid var(--dsw-alias-border-l2);font:inherit;color:var(--dsw-alias-label-secondary);cursor:pointer;white-space:nowrap;background:0 0;border-radius:6px;align-self:flex-start;padding:4px 12px;font-size:13px;line-height:20px}._1bMeTa_fullSyncButton:hover:not(:disabled){color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-label-dimmed)}._1bMeTa_fullSyncButton:disabled{opacity:.5;cursor:default}._1bMeTa_fullSyncButton:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}._1bMeTa_fullSyncProgress{flex-direction:column;gap:4px;display:flex}._1bMeTa_fullSyncProgressLabel{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;font-size:12px;line-height:1.5}._1bMeTa_fullSyncBar{background:var(--dsw-alias-bg-multi-select);border-radius:2px;height:4px;display:block;overflow:hidden}._1bMeTa_fullSyncFill{background:var(--dsw-alias-brand-primary);border-radius:2px;height:100%;transition:width .2s;display:block}._1bMeTa_fullSyncResult{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;margin:0;font-size:12px;line-height:1.5}._1bMeTa_fullSyncError{color:var(--dsw-alias-label-error);margin:0;font-size:12px;line-height:1.5}";
1729
+ const tagId$4 = "dsh-token-usage/TokenUsageCard.module.css";
1730
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$4) + "]") === null) {
1731
+ const tag = document.createElement("style");
1732
+ tag.dataset.plugin = "dsh-token-usage";
1733
+ tag.dataset.pluginCss = tagId$4;
1734
+ tag.textContent = css$4;
1735
+ document.head.appendChild(tag);
1736
+ }
1737
+ var TokenUsageCard_module_css_default = {
1738
+ "body": "_1bMeTa_body",
1739
+ "browse": "_1bMeTa_browse",
1740
+ "card": "_1bMeTa_card",
1741
+ "cardOpen": "_1bMeTa_cardOpen",
1742
+ "chevron": "_1bMeTa_chevron",
1743
+ "chevronOpen": "_1bMeTa_chevronOpen",
1744
+ "description": "_1bMeTa_description",
1745
+ "discard": "_1bMeTa_discard",
1746
+ "failed": "_1bMeTa_failed",
1747
+ "field": "_1bMeTa_field",
1748
+ "fieldLabel": "_1bMeTa_fieldLabel",
1749
+ "footer": "_1bMeTa_footer",
1750
+ "fullSync": "_1bMeTa_fullSync",
1751
+ "fullSyncBar": "_1bMeTa_fullSyncBar",
1752
+ "fullSyncButton": "_1bMeTa_fullSyncButton",
1753
+ "fullSyncError": "_1bMeTa_fullSyncError",
1754
+ "fullSyncFill": "_1bMeTa_fullSyncFill",
1755
+ "fullSyncHeader": "_1bMeTa_fullSyncHeader",
1756
+ "fullSyncHint": "_1bMeTa_fullSyncHint",
1757
+ "fullSyncProgress": "_1bMeTa_fullSyncProgress",
1758
+ "fullSyncProgressLabel": "_1bMeTa_fullSyncProgressLabel",
1759
+ "fullSyncResult": "_1bMeTa_fullSyncResult",
1760
+ "fullSyncTitle": "_1bMeTa_fullSyncTitle",
1761
+ "headText": "_1bMeTa_headText",
1762
+ "header": "_1bMeTa_header",
1763
+ "hint": "_1bMeTa_hint",
1764
+ "input": "_1bMeTa_input",
1765
+ "inputRow": "_1bMeTa_inputRow",
1766
+ "migration": "_1bMeTa_migration",
1767
+ "migrationBar": "_1bMeTa_migrationBar",
1768
+ "migrationFill": "_1bMeTa_migrationFill",
1769
+ "migrationLabel": "_1bMeTa_migrationLabel",
1770
+ "name": "_1bMeTa_name",
1771
+ "note": "_1bMeTa_note",
1772
+ "pending": "_1bMeTa_pending",
1773
+ "save": "_1bMeTa_save"
1774
+ };
1775
+ //#endregion
1776
+ //#region src/client/TokenUsageCard.tsx
1777
+ /**
1778
+ * The token-usage card on the Plugins configuration tab: a collapsible row
1779
+ * whose header names the plugin over a one-line description of what its
1780
+ * settings govern, disclosing the data-directory control and the mirror
1781
+ * region pick (`domestic` gitee / `overseas` github) when open. The card owns
1782
+ * everything inside it — chrome, controls, and copy — per the keyed-slot
1783
+ * contract; the tab only dispatches it under the `token-usage` namespace key.
1784
+ *
1785
+ * Renders nothing while the namespace is unavailable: a deployment that did
1786
+ * not compose the host half shows no trace of the card. A region change takes
1787
+ * effect live (the host re-syncs the pricing mirror); a directory change the
1788
+ * guard refuses while conversations run shows the wait-for-them notice on the
1789
+ * failure line, and one that lands migrates the data across under a live
1790
+ * progress bar that locks the controls until it settles.
1791
+ *
1792
+ * @module token-usage/client/TokenUsageCard
1793
+ */
1794
+ /**
1795
+ * Render the token-usage settings card.
1796
+ * @param props - locale copy, the card snapshot, and its form actions.
1797
+ * @returns the card, or nothing when the namespace is unavailable.
1798
+ */
1799
+ function TokenUsageCard(props) {
1800
+ const [open, setOpen] = (0, react.useState)(false);
1801
+ const [picking, setPicking] = (0, react.useState)(false);
1802
+ const { t } = props;
1803
+ const state = props.useTokenUsageCard((snapshot) => snapshot);
1804
+ if (!state.available) return null;
1805
+ const migrating = state.migration !== void 0;
1806
+ const lockInput = !state.writable || migrating;
1807
+ const lockActions = !state.dirty || state.saving || migrating;
1808
+ /**
1809
+ * Open the shell's native folder dialog and stage the chosen path — the
1810
+ * same picker the workspace flows use, driven through the injected
1811
+ * workspace service. A dismissal leaves the staged draft exactly as it
1812
+ * was; the text input stays the fallback either way.
1813
+ */
1814
+ const browse = async () => {
1815
+ if (picking || lockInput) return;
1816
+ setPicking(true);
1817
+ try {
1818
+ const picked = await props.pickDirectory();
1819
+ if (picked !== null && picked !== "") props.editField("path", picked);
1820
+ } catch (_pickFailure) {} finally {
1821
+ setPicking(false);
1822
+ }
1823
+ };
1824
+ const [fullSync, setFullSync] = (0, react.useState)({ status: "idle" });
1825
+ const fullSyncRunning = fullSync.status === "running";
1826
+ /**
1827
+ * Fetch the current full-sync status from the host. A transport failure
1828
+ * keeps the previous view (a transient miss never blanks the bar).
1829
+ */
1830
+ const fetchFullSync = (0, react.useCallback)(async () => {
1831
+ try {
1832
+ const response = await fetch(FULL_SYNC_PATH, { headers: { accept: "application/json" } });
1833
+ if (!response.ok) return null;
1834
+ const body = await response.json();
1835
+ if (body.status === "idle") return { status: "idle" };
1836
+ if (body.status === "running" || body.status === "done") {
1837
+ if (typeof body.processed === "number" && typeof body.total === "number" && typeof body.added === "number" && typeof body.skipped === "number") return {
1838
+ status: body.status,
1839
+ processed: body.processed,
1840
+ total: body.total,
1841
+ added: body.added,
1842
+ skipped: body.skipped
1843
+ };
1844
+ return null;
1845
+ }
1846
+ if (body.status === "failed" && typeof body.error === "string") return {
1847
+ status: "failed",
1848
+ error: body.error
1849
+ };
1850
+ return null;
1851
+ } catch (_pollFailure) {
1852
+ return null;
1853
+ }
1854
+ }, []);
1855
+ (0, react.useEffect)(() => {
1856
+ if (!fullSyncRunning) return;
1857
+ let cancelled = false;
1858
+ const tick = async () => {
1859
+ const next = await fetchFullSync();
1860
+ if (cancelled || next === null) return;
1861
+ setFullSync(next);
1862
+ };
1863
+ tick();
1864
+ const timer = setInterval(() => {
1865
+ tick();
1866
+ }, 300);
1867
+ return () => {
1868
+ cancelled = true;
1869
+ clearInterval(timer);
1870
+ };
1871
+ }, [fullSyncRunning, fetchFullSync]);
1872
+ /**
1873
+ * Kick off one full scan. The button shows the request as soon as the
1874
+ * POST returns 202; the polling effect above then drives the bar until
1875
+ * the host settles into `done` or `failed`. A 409 (already running) is
1876
+ * a no-op — the polling will already see the running state.
1877
+ */
1878
+ const startFullSync = (0, react.useCallback)(async () => {
1879
+ try {
1880
+ const response = await fetch(FULL_SYNC_PATH, { method: "POST" });
1881
+ if (response.status === 202) {
1882
+ setFullSync({
1883
+ status: "running",
1884
+ processed: 0,
1885
+ total: 0,
1886
+ added: 0,
1887
+ skipped: 0
1888
+ });
1889
+ return;
1890
+ }
1891
+ if (response.status === 409) {
1892
+ const next = await fetchFullSync();
1893
+ if (next !== null) setFullSync(next);
1894
+ }
1895
+ } catch (_triggerFailure) {}
1896
+ }, [fetchFullSync]);
1897
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", {
1898
+ className: open ? `${TokenUsageCard_module_css_default.card} ${TokenUsageCard_module_css_default.cardOpen}` : TokenUsageCard_module_css_default.card,
1899
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1900
+ type: "button",
1901
+ className: TokenUsageCard_module_css_default.header,
1902
+ "aria-expanded": open,
1903
+ "aria-label": `${t(open ? "card.collapse" : "card.expand")}: ${t("card.title")}`,
1904
+ onClick: () => {
1905
+ setOpen(!open);
1906
+ },
1907
+ children: [
1908
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1909
+ className: TokenUsageCard_module_css_default.headText,
1910
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1911
+ className: TokenUsageCard_module_css_default.name,
1912
+ children: t("card.title")
1913
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1914
+ className: TokenUsageCard_module_css_default.description,
1915
+ children: t("card.description")
1916
+ })]
1917
+ }),
1918
+ state.dirty ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1919
+ className: TokenUsageCard_module_css_default.pending,
1920
+ children: t("card.unsaved")
1921
+ }) : null,
1922
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconChevronDownOutline14, { className: open ? `${TokenUsageCard_module_css_default.chevron} ${TokenUsageCard_module_css_default.chevronOpen}` : TokenUsageCard_module_css_default.chevron })
1923
+ ]
1924
+ }), open ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1925
+ className: TokenUsageCard_module_css_default.body,
1926
+ children: [
1927
+ !state.writable ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1928
+ className: TokenUsageCard_module_css_default.note,
1929
+ role: "status",
1930
+ children: t("card.readOnly")
1931
+ }) : null,
1932
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
1933
+ className: TokenUsageCard_module_css_default.field,
1934
+ htmlFor: "token-usage-card-path",
1935
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1936
+ className: TokenUsageCard_module_css_default.fieldLabel,
1937
+ children: t("card.pathLabel")
1938
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1939
+ className: TokenUsageCard_module_css_default.inputRow,
1940
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1941
+ id: "token-usage-card-path",
1942
+ className: TokenUsageCard_module_css_default.input,
1943
+ type: "text",
1944
+ spellCheck: false,
1945
+ value: state.fields.path,
1946
+ disabled: lockInput,
1947
+ onChange: (event) => {
1948
+ props.editField("path", event.target.value);
1949
+ }
1950
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1951
+ type: "button",
1952
+ className: TokenUsageCard_module_css_default.browse,
1953
+ disabled: lockInput || picking,
1954
+ onClick: () => {
1955
+ browse();
1956
+ },
1957
+ children: t(picking ? "card.picking" : "card.browse")
1958
+ })]
1959
+ })]
1960
+ }),
1961
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1962
+ className: TokenUsageCard_module_css_default.hint,
1963
+ children: t("card.pathHint")
1964
+ }),
1965
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
1966
+ className: TokenUsageCard_module_css_default.field,
1967
+ htmlFor: "token-usage-card-region",
1968
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1969
+ className: TokenUsageCard_module_css_default.fieldLabel,
1970
+ children: t("card.regionLabel")
1971
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
1972
+ id: "token-usage-card-region",
1973
+ className: TokenUsageCard_module_css_default.input,
1974
+ value: state.fields.pricingRegion,
1975
+ disabled: lockInput,
1976
+ onChange: (event) => {
1977
+ props.editField("pricingRegion", event.target.value);
1978
+ },
1979
+ children: [
1980
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
1981
+ value: "",
1982
+ children: t("card.regionDefault")
1983
+ }),
1984
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
1985
+ value: "domestic",
1986
+ children: t("card.region.domestic")
1987
+ }),
1988
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
1989
+ value: "overseas",
1990
+ children: t("card.region.overseas")
1991
+ })
1992
+ ]
1993
+ })]
1994
+ }),
1995
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
1996
+ className: TokenUsageCard_module_css_default.hint,
1997
+ children: [t("card.hint"), state.overridden.pricingRegion ? ` ${t("card.overridden")}` : ""]
1998
+ }),
1999
+ state.migration !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2000
+ className: TokenUsageCard_module_css_default.migration,
2001
+ role: "status",
2002
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2003
+ className: TokenUsageCard_module_css_default.migrationLabel,
2004
+ children: t(state.migration.phase === "copying" ? "card.migratingCopy" : "card.migratingClean").replace("{done}", String(state.migration.done)).replace("{total}", String(state.migration.total))
2005
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2006
+ className: TokenUsageCard_module_css_default.migrationBar,
2007
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2008
+ className: TokenUsageCard_module_css_default.migrationFill,
2009
+ style: { width: `${String(Math.round(state.migration.done / Math.max(state.migration.total, 1) * 100))}%` }
2010
+ })
2011
+ })]
2012
+ }) : null,
2013
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2014
+ className: TokenUsageCard_module_css_default.fullSync,
2015
+ children: [
2016
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2017
+ className: TokenUsageCard_module_css_default.fullSyncHeader,
2018
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2019
+ className: TokenUsageCard_module_css_default.fullSyncTitle,
2020
+ children: t("card.fullSync.title")
2021
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2022
+ className: TokenUsageCard_module_css_default.fullSyncHint,
2023
+ children: t("card.fullSync.hint")
2024
+ })]
2025
+ }),
2026
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2027
+ type: "button",
2028
+ className: TokenUsageCard_module_css_default.fullSyncButton,
2029
+ disabled: fullSyncRunning,
2030
+ onClick: () => {
2031
+ startFullSync();
2032
+ },
2033
+ children: t(fullSyncRunning ? "card.fullSync.running" : "card.fullSync.button")
2034
+ }),
2035
+ fullSync.status === "running" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2036
+ className: TokenUsageCard_module_css_default.fullSyncProgress,
2037
+ role: "status",
2038
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2039
+ className: TokenUsageCard_module_css_default.fullSyncProgressLabel,
2040
+ children: t("card.fullSync.progress", {
2041
+ processed: String(fullSync.processed),
2042
+ total: String(fullSync.total),
2043
+ added: String(fullSync.added),
2044
+ skipped: String(fullSync.skipped)
2045
+ })
2046
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2047
+ className: TokenUsageCard_module_css_default.fullSyncBar,
2048
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2049
+ className: TokenUsageCard_module_css_default.fullSyncFill,
2050
+ style: { width: `${String(Math.round(fullSync.processed / Math.max(fullSync.total, 1) * 100))}%` }
2051
+ })
2052
+ })]
2053
+ }) : null,
2054
+ fullSync.status === "done" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2055
+ className: TokenUsageCard_module_css_default.fullSyncResult,
2056
+ role: "status",
2057
+ children: t("card.fullSync.done", {
2058
+ added: String(fullSync.added),
2059
+ skipped: String(fullSync.skipped)
2060
+ })
2061
+ }) : null,
2062
+ fullSync.status === "failed" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2063
+ className: TokenUsageCard_module_css_default.fullSyncError,
2064
+ role: "status",
2065
+ children: t("card.fullSync.failed", { error: fullSync.error })
2066
+ }) : null
2067
+ ]
2068
+ }),
2069
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2070
+ className: TokenUsageCard_module_css_default.footer,
2071
+ children: [
2072
+ state.failed ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2073
+ className: TokenUsageCard_module_css_default.failed,
2074
+ role: "status",
2075
+ children: state.refusal !== void 0 ? t("card.saveBlockedSessions").replace("{count}", String(state.refusal.interactingSessions)) : t("card.saveFailed")
2076
+ }) : null,
2077
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2078
+ type: "button",
2079
+ className: TokenUsageCard_module_css_default.discard,
2080
+ disabled: lockActions,
2081
+ onClick: props.discard,
2082
+ children: t("card.discard")
2083
+ }),
2084
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2085
+ type: "button",
2086
+ className: TokenUsageCard_module_css_default.save,
2087
+ disabled: lockActions,
2088
+ onClick: props.save,
2089
+ children: t(state.saving ? "card.saving" : "card.save")
2090
+ })
2091
+ ]
2092
+ })
2093
+ ]
2094
+ }) : null]
2095
+ });
2096
+ }
2097
+ //#endregion
2098
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\StatCard.module.css.mjs
2099
+ const css$3 = ".F2LbNW_card{border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-fill-container,transparent);border-radius:8px;flex-direction:column;gap:2px;min-width:0;padding:10px 12px;display:flex}.F2LbNW_cardLabel{color:var(--dsw-alias-label-secondary);white-space:nowrap;text-overflow:ellipsis;font-size:11px;overflow:hidden}.F2LbNW_cardValue{font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary);white-space:nowrap;text-overflow:ellipsis;font-size:18px;font-weight:600;overflow:hidden}";
2100
+ const tagId$3 = "dsh-token-usage/StatCard.module.css";
2101
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$3) + "]") === null) {
2102
+ const tag = document.createElement("style");
2103
+ tag.dataset.plugin = "dsh-token-usage";
2104
+ tag.dataset.pluginCss = tagId$3;
2105
+ tag.textContent = css$3;
2106
+ document.head.appendChild(tag);
2107
+ }
2108
+ var StatCard_module_css_default = {
2109
+ "card": "F2LbNW_card",
2110
+ "cardLabel": "F2LbNW_cardLabel",
2111
+ "cardValue": "F2LbNW_cardValue"
2112
+ };
2113
+ //#endregion
2114
+ //#region src/client/StatCard.tsx
2115
+ /**
2116
+ * Render one stat card. The value uses the standard label-primary color.
2117
+ * The label clamps to one line and ellipsizes if the column is squeezed.
2118
+ */
2119
+ function StatCard({ label, value }) {
2120
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2121
+ className: StatCard_module_css_default["card"],
2122
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2123
+ className: StatCard_module_css_default["cardLabel"],
2124
+ children: label
2125
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2126
+ className: StatCard_module_css_default["cardValue"],
2127
+ children: value
2128
+ })]
2129
+ });
2130
+ }
2131
+ //#endregion
2132
+ //#region src/client/trend-chart/axis.ts
2133
+ /**
2134
+ * Trend-chart axis helpers: the roundest step from 1/2/2.5/5 × 10ⁿ not
2135
+ * below a rough target, and the y-axis tick values (one nice step apart,
2136
+ * inclusive of the chart top). Pure functions, no React, no I/O.
2137
+ *
2138
+ * @module token-usage/client/trend-chart/axis
2139
+ */
2140
+ /**
2141
+ * The roundest step from {1, 2, 2.5, 5, 10} × 10ⁿ not below `rough`.
2142
+ * A `niceStep(0)` returns 1; a `niceStep(80)` returns 100 (the next nice
2143
+ * step above 80 in the same decade).
2144
+ * @param rough - the target value (positive).
2145
+ * @returns the nice step.
2146
+ */
2147
+ function niceStep(rough) {
2148
+ const base = 10 ** Math.floor(Math.log10(rough));
2149
+ const fraction = rough / base;
2150
+ return (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 2.5 ? 2.5 : fraction <= 5 ? 5 : 10) * base;
2151
+ }
2152
+ /** The y-axis tick values from one step up to the chart top (inclusive). */
2153
+ function tickValues(max) {
2154
+ if (max === 0) return {
2155
+ top: 1,
2156
+ ticks: []
2157
+ };
2158
+ const step = niceStep(max / 4);
2159
+ const top = Math.ceil(max / step) * step;
2160
+ const ticks = [];
2161
+ for (let value = step; value < top; value += step) ticks.push(value);
2162
+ ticks.push(top);
2163
+ return {
2164
+ top,
2165
+ ticks
2166
+ };
2167
+ }
2168
+ //#endregion
2169
+ //#region src/trend-bucket.ts
2170
+ /**
2171
+ * Bucket widths tried from fine to coarse (ms); the first whose bucket count
2172
+ * stays at or under {@link MAX_BUCKETS} wins, so a short session gets
2173
+ * fine-grained 5-second buckets and a multi-day session one per several
2174
+ * hours — always within the render cap.
2175
+ */
2176
+ const BUCKET_STEPS_MS = [
2177
+ 5e3,
2178
+ 15e3,
2179
+ 6e4,
2180
+ 3e5,
2181
+ 9e5,
2182
+ 36e5,
2183
+ 108e5,
2184
+ 216e5,
2185
+ 432e5,
2186
+ 864e5
2187
+ ];
2188
+ /** The bucket width for one span: the finest step whose count fits the cap. */
2189
+ function bucketWidth(spanMs) {
2190
+ for (const step of BUCKET_STEPS_MS) if (Math.ceil(spanMs / step) <= 60) return step;
2191
+ return Math.ceil(spanMs / 60 / 36e5) * 36e5;
2192
+ }
2193
+ /**
2194
+ * Fold a request series into uniformly sized time buckets spanning the
2195
+ * series' own first-to-last window. The axis starts at the series' first
2196
+ * record, ends at its latest, and the middle is evenly divided — the chart
2197
+ * shows the trend over TIME, not one point per request. Buckets align to
2198
+ * the window's first record, not to wall-clock round hours.
2199
+ *
2200
+ * Implementation note: the buckets are tracked in a `Map` keyed by their
2201
+ * 0-based index, not in a sparse array. A multi-month session could
2202
+ * otherwise blow past V8's sparse-array bounds (the indices approach
2203
+ * `spanMs / 5_000` which is unbounded); the Map collapses absent keys
2204
+ * cleanly.
2205
+ *
2206
+ * @param requests - the per-request series, time-ascending.
2207
+ * @returns the buckets in time order (empty for an empty series; only
2208
+ * buckets holding at least one request are emitted).
2209
+ */
2210
+ function bucketSeries(requests) {
2211
+ if (requests.length === 0) return [];
2212
+ const first = requests[0].time;
2213
+ const last = requests[requests.length - 1].time;
2214
+ const width = bucketWidth(Math.max(last - first, 1));
2215
+ const buckets = /* @__PURE__ */ new Map();
2216
+ for (const request of requests) {
2217
+ const index = Math.floor((request.time - first) / width);
2218
+ const existing = buckets.get(index);
2219
+ if (existing === void 0) buckets.set(index, {
2220
+ start: first + index * width,
2221
+ end: first + (index + 1) * width,
2222
+ tokens: request.tokens,
2223
+ count: 1
2224
+ });
2225
+ else {
2226
+ existing.tokens += request.tokens;
2227
+ existing.count += 1;
2228
+ }
2229
+ }
2230
+ return [...buckets.entries()].sort(([left], [right]) => left - right).map(([, bucket]) => bucket);
2231
+ }
2232
+ //#endregion
2233
+ //#region src/client/trend-chart/bucket.ts
2234
+ /**
2235
+ * Scale one wall time into an x offset across the series' actual span —
2236
+ * the first and last points pin the axis ends, and everything in between
2237
+ * lands at its real proportion of that span (a 55-request session
2238
+ * spreads across the full width, a burst inside one minute bunches up).
2239
+ * @param firstTime - the series' first record time.
2240
+ * @param lastTime - the series' last record time.
2241
+ * @param time - the record's wall time.
2242
+ * @param innerWidth - the plottable width in pixels.
2243
+ * @returns the x offset from the left edge; the center when every record
2244
+ * shares one timestamp (a zero span cannot scale).
2245
+ */
2246
+ function scaleToSpan(firstTime, lastTime, time, innerWidth) {
2247
+ const span = lastTime - firstTime;
2248
+ if (span <= 0) return innerWidth / 2;
2249
+ return (time - firstTime) / span * innerWidth;
2250
+ }
2251
+ //#endregion
2252
+ //#region src/client/trend-chart/points.ts
2253
+ /** Render-mode priority: request buckets outrank per-hour, which
2254
+ * outranks per-day. A session-scoped read passes `requests`; the settings
2255
+ * page passes `hours` for a single-day range; everything else plots days. */
2256
+ function buildChartPoints(input) {
2257
+ if (input.requests !== void 0 && input.requests.length > 0) {
2258
+ const buckets = bucketsOf(input.requests);
2259
+ if (buckets.length > 0) {
2260
+ const crossDay = new Date(buckets[0].start).toDateString() !== new Date(buckets[buckets.length - 1].start).toDateString();
2261
+ return {
2262
+ mode: "temporal",
2263
+ points: buckets.map((bucket, index) => ({
2264
+ key: `b${index}`,
2265
+ label: bucketLabel(bucket.start, crossDay),
2266
+ full: `${bucketLabel(bucket.start, crossDay)}–${bucketLabel(bucket.end, crossDay)}`,
2267
+ tokens: bucket.tokens,
2268
+ time: bucket.start,
2269
+ count: bucket.count
2270
+ }))
2271
+ };
2272
+ }
2273
+ }
2274
+ if (input.hours !== void 0) {
2275
+ const points = hourSeries(input.hours, input.from, input.to);
2276
+ if (points.length > 0) return {
2277
+ mode: "equidistant",
2278
+ points: points.map(hourToPoint)
2279
+ };
2280
+ }
2281
+ const points = daySeries(input.rows, input.from, input.to);
2282
+ if (points.length > 0) return {
2283
+ mode: "equidistant",
2284
+ points: points.map(dayToPoint)
2285
+ };
2286
+ return null;
2287
+ }
2288
+ /** A series that already carries `count` (the host's `fields=session`
2289
+ * downsample) is plotted as-is; a raw per-request series is folded here. */
2290
+ function bucketsOf(requests) {
2291
+ if (requests[0]?.count !== void 0) return requests.map((point) => ({
2292
+ start: point.time,
2293
+ end: point.end ?? point.time,
2294
+ tokens: point.tokens,
2295
+ count: point.count ?? 1
2296
+ }));
2297
+ return bucketSeries(requests);
2298
+ }
2299
+ function dayToPoint(point) {
2300
+ return {
2301
+ key: point.day,
2302
+ label: point.day.slice(5),
2303
+ full: point.day,
2304
+ tokens: point.tokens
2305
+ };
2306
+ }
2307
+ function hourToPoint(point) {
2308
+ return {
2309
+ key: point.hour,
2310
+ label: `${point.hour.slice(11)}:00`,
2311
+ full: `${point.hour.slice(0, 10)} ${point.hour.slice(11)}:00`,
2312
+ tokens: point.tokens
2313
+ };
2314
+ }
2315
+ /** Zero-padded HH:mm of one wall time, local-time. */
2316
+ function clockOf(time) {
2317
+ const d = new Date(time);
2318
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
2319
+ }
2320
+ /** The x-axis label of one bucket start: HH:mm within one day,
2321
+ * MM-DD HH:mm once the session crosses midnight. */
2322
+ function bucketLabel(time, crossDay) {
2323
+ if (!crossDay) return clockOf(time);
2324
+ const d = new Date(time);
2325
+ return `${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")} ${clockOf(time)}`;
2326
+ }
2327
+ //#endregion
2328
+ //#region src/client/trend-chart/scale.ts
2329
+ /**
2330
+ * Pick the right x scale for a {@link ChartSeries} and produce the
2331
+ * per-point offsets in absolute viewBox coordinates. Equidistant modes
2332
+ * lay points one stride apart across the `[leftEdge, rightEdge]` span;
2333
+ * temporal mode uses each point's wall time against the series' own
2334
+ * first-to-last span and adds `leftEdge` to the result. Single-point
2335
+ * series pin to the centerline of the span (a zero stride would not
2336
+ * scale, and temporal scale would divide by zero).
2337
+ *
2338
+ * @param series - the discriminated-union series from {@link buildChartPoints}.
2339
+ * @param leftEdge - the absolute SVG x of the chart's left edge (the
2340
+ * y-axis line in the renderer).
2341
+ * @param rightEdge - the absolute SVG x of the chart's right edge
2342
+ * (typically `viewBox.width − RIGHT.margin`).
2343
+ * @returns the per-point x offsets plus `innerWidth = rightEdge − leftEdge`.
2344
+ */
2345
+ function scaleSeries(series, leftEdge, rightEdge) {
2346
+ const innerWidth = rightEdge - leftEdge;
2347
+ const { points } = series;
2348
+ if (series.mode === "equidistant") {
2349
+ const xs = [];
2350
+ if (points.length === 1) xs.push((leftEdge + rightEdge) / 2);
2351
+ else {
2352
+ const stride = innerWidth / (points.length - 1);
2353
+ for (let i = 0; i < points.length; i += 1) xs.push(leftEdge + i * stride);
2354
+ }
2355
+ return {
2356
+ xs,
2357
+ innerWidth
2358
+ };
2359
+ }
2360
+ const temporal = points;
2361
+ const first = temporal[0].time;
2362
+ const last = temporal[temporal.length - 1].time;
2363
+ const xs = [];
2364
+ if (temporal.length === 1 || first === last) xs.push((leftEdge + rightEdge) / 2);
2365
+ else for (const point of temporal) xs.push(leftEdge + scaleToSpan(first, last, point.time, innerWidth));
2366
+ return {
2367
+ xs,
2368
+ innerWidth
2369
+ };
2370
+ }
2371
+ /**
2372
+ * The x-axis label positions: first, middle, and last point for long
2373
+ * ranges. Short ranges (≤3 points) label every point so a 1- or 2- day
2374
+ * window does not skip the only "middle" data.
2375
+ */
2376
+ function labelIndices(length) {
2377
+ if (length <= 3) return Array.from({ length }, (_, index) => index);
2378
+ const middle = Math.floor((length - 1) / 2);
2379
+ return [.../* @__PURE__ */ new Set([
2380
+ 0,
2381
+ middle,
2382
+ length - 1
2383
+ ])];
2384
+ }
2385
+ /** Choose a dot radius that survives dense point clouds without
2386
+ * overlapping but stays visible for sparse ones. Three tiers, picked by
2387
+ * point count. */
2388
+ function dotRadius(pointCount) {
2389
+ if (pointCount > 90) return 1.5;
2390
+ if (pointCount > 30) return 2;
2391
+ return 3;
2392
+ }
2393
+ //#endregion
2394
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\TrendChart.module.css.mjs
2395
+ const css$2 = ".DWJgoW_chart{width:100%;height:auto;display:block}.DWJgoW_axis{stroke:var(--dsw-alias-border-l2);stroke-width:1px}.DWJgoW_grid{stroke:var(--dsw-alias-border-l2);stroke-width:1px;stroke-dasharray:3 3}.DWJgoW_line{fill:none;stroke:var(--dsw-alias-label-primary);stroke-width:2px;stroke-linejoin:round;stroke-linecap:round}.DWJgoW_dot{fill:var(--dsw-alias-label-primary)}.DWJgoW_dotActive{fill:var(--dsw-alias-label-primary);stroke:var(--dsw-alias-bg-layer-2);stroke-width:2px}.DWJgoW_guide{stroke:var(--dsw-alias-label-secondary);stroke-width:1px;stroke-dasharray:3 3}.DWJgoW_hit{cursor:default}.DWJgoW_pointLabel rect{fill:var(--dsw-alias-bg-layer-3);stroke:var(--dsw-alias-border-l2)}.DWJgoW_pointLabel text{fill:var(--dsw-alias-label-primary);font-size:11px}.DWJgoW_tick{fill:var(--dsw-alias-label-secondary);font-size:11px}.DWJgoW_empty{text-align:center;color:var(--dsw-alias-label-secondary);margin:0;padding:24px 0;font-size:13px}";
2396
+ const tagId$2 = "dsh-token-usage/TrendChart.module.css";
2397
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$2) + "]") === null) {
2398
+ const tag = document.createElement("style");
2399
+ tag.dataset.plugin = "dsh-token-usage";
2400
+ tag.dataset.pluginCss = tagId$2;
2401
+ tag.textContent = css$2;
2402
+ document.head.appendChild(tag);
2403
+ }
2404
+ var TrendChart_module_css_default = {
2405
+ "axis": "DWJgoW_axis",
2406
+ "chart": "DWJgoW_chart",
2407
+ "dot": "DWJgoW_dot",
2408
+ "dotActive": "DWJgoW_dotActive",
2409
+ "empty": "DWJgoW_empty",
2410
+ "grid": "DWJgoW_grid",
2411
+ "guide": "DWJgoW_guide",
2412
+ "hit": "DWJgoW_hit",
2413
+ "line": "DWJgoW_line",
2414
+ "pointLabel": "DWJgoW_pointLabel",
2415
+ "tick": "DWJgoW_tick"
2416
+ };
2417
+ //#endregion
2418
+ //#region src/client/TrendChart.tsx
2419
+ /**
2420
+ * Daily / hourly / request-bucketed token trend chart (browser half):
2421
+ * a dependency-free SVG line chart over the already-filtered summary.
2422
+ * The renderer is pure presentation; the bucketing, scaling, and
2423
+ * point-shape decisions live in `./trend-chart/*` so each piece can be
2424
+ * tested in isolation.
2425
+ *
2426
+ * Two granularities share one renderer — per-day rows (x axis spans
2427
+ * every calendar day of the active range, days without records plot as
2428
+ * zero) and per-hour rows (a single-day window plots every whole hour of
2429
+ * that day, 00:00–23:00, future hours of today reading zero). The
2430
+ * third mode — request buckets — folds the request series into uniformly
2431
+ * sized time buckets spanning the session's actual first-to-last window
2432
+ * and scales each bucket at its real temporal proportion of the span.
2433
+ *
2434
+ * Hovering (or keyboard-focusing) a point highlights it and floats a
2435
+ * label with that point's date/time and total tokens.
2436
+ *
2437
+ * @module token-usage/client/TrendChart
2438
+ */
2439
+ /** SVG canvas metrics; the element scales to the section width via viewBox. */
2440
+ const WIDTH = 800;
2441
+ const HEIGHT = 190;
2442
+ const TOP = 12;
2443
+ const LEFT = 44;
2444
+ const HIT_TARGET_FLOOR = 6;
2445
+ /**
2446
+ * Apply the `t`-based localisation to a point's `full` tooltip. The pre-shape
2447
+ * labels live in points.ts; the chart's aria-label and the floating tooltip
2448
+ * both use this single source so the two stay consistent.
2449
+ * @param t - the locale seat.
2450
+ * @param point - the pre-shaped point.
2451
+ * @returns the tooltip / aria-label text.
2452
+ */
2453
+ function tipOf(t, point) {
2454
+ if (point.time !== void 0) return t("chart.bucket", {
2455
+ window: point.full,
2456
+ count: String(point.count ?? 0),
2457
+ tokens: formatTokens(point.tokens)
2458
+ });
2459
+ return t("chart.pointLabel", {
2460
+ day: point.full,
2461
+ tokens: formatTokens(point.tokens)
2462
+ });
2463
+ }
2464
+ /**
2465
+ * Render the daily / hourly / request-bucketed token line chart. Pure
2466
+ * presentation: every data-driven decision (bucketing, axis scaling,
2467
+ * point ordering) lives in `./trend-chart/*`; this component picks the
2468
+ * right `chartAria` string for screen readers and forwards hover /
2469
+ * focus state to the dot + label.
2470
+ *
2471
+ * Empty ranges (no data on any branch) render a placeholder instead of an
2472
+ * axis so the layout does not collapse to an empty SVG.
2473
+ *
2474
+ * @param props - the filtered per-day rows plus the optional per-hour rows
2475
+ * (when present the chart plots hours instead of days), the optional
2476
+ * per-request series (session-scoped reads), the active range bounds
2477
+ * (absent when unfiltered; the chart then spans first to last row), and
2478
+ * the `t` seat for the empty hint and chart aria-label.
2479
+ * @returns the SVG chart, or a placeholder for an empty range.
2480
+ */
2481
+ function TrendChart({ rows, hours, requests, from, to, t }) {
2482
+ const series = buildChartPoints({
2483
+ rows,
2484
+ hours,
2485
+ requests,
2486
+ from,
2487
+ to
2488
+ });
2489
+ if (series === null) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2490
+ className: TrendChart_module_css_default.empty,
2491
+ children: t("chart.empty")
2492
+ });
2493
+ const points = series.points.map((point) => ({
2494
+ key: point.key,
2495
+ label: point.label,
2496
+ full: point.full,
2497
+ tokens: point.tokens,
2498
+ time: "time" in point ? point.time : void 0,
2499
+ count: "count" in point ? point.count : void 0
2500
+ }));
2501
+ const { top, ticks } = tickValues(Math.max(...points.map((p) => p.tokens)));
2502
+ const innerHeight = 140;
2503
+ const { xs, innerWidth } = scaleSeries(series, LEFT, 784);
2504
+ const radius = dotRadius(points.length);
2505
+ const [active, setActive] = (0, react.useState)(null);
2506
+ const activePoint = active === null ? null : points[active] ?? null;
2507
+ const y = (tokens) => 152 - tokens / top * innerHeight;
2508
+ const path = points.map((point, index) => `${index === 0 ? "M" : "L"}${xs[index].toFixed(1)},${y(point.tokens).toFixed(1)}`).join(" ");
2509
+ const chartAria = series.mode === "temporal" ? t("chart.ariaRequests") : hours !== void 0 ? t("chart.ariaHour") : t("chart.aria");
2510
+ const hitExtent = (index) => {
2511
+ if (points.length === 1) return {
2512
+ start: LEFT,
2513
+ width: innerWidth
2514
+ };
2515
+ const center = xs[index];
2516
+ const before = index === 0 ? void 0 : xs[index - 1];
2517
+ const after = index === points.length - 1 ? void 0 : xs[index + 1];
2518
+ const toPrev = before === void 0 ? innerWidth : (center - before) / 2;
2519
+ const toNext = after === void 0 ? innerWidth : (after - center) / 2;
2520
+ const half = Math.max(Math.min(toPrev, toNext), HIT_TARGET_FLOOR);
2521
+ return {
2522
+ start: center - half,
2523
+ width: half * 2
2524
+ };
2525
+ };
2526
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
2527
+ role: "img",
2528
+ "aria-label": chartAria,
2529
+ viewBox: `0 0 ${WIDTH} ${HEIGHT}`,
2530
+ className: TrendChart_module_css_default.chart,
2531
+ onMouseLeave: () => setActive(null),
2532
+ children: [
2533
+ ticks.map((tick) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("g", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
2534
+ x1: LEFT,
2535
+ y1: y(tick),
2536
+ x2: 784,
2537
+ y2: y(tick),
2538
+ className: TrendChart_module_css_default.grid
2539
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("text", {
2540
+ x: 38,
2541
+ y: y(tick) + 3,
2542
+ textAnchor: "end",
2543
+ className: TrendChart_module_css_default.tick,
2544
+ children: formatTokens(tick)
2545
+ })] }, tick)),
2546
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
2547
+ x1: LEFT,
2548
+ y1: y(0),
2549
+ x2: 784,
2550
+ y2: y(0),
2551
+ className: TrendChart_module_css_default.axis
2552
+ }),
2553
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("path", {
2554
+ d: path,
2555
+ className: TrendChart_module_css_default.line
2556
+ }),
2557
+ points.map((point, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
2558
+ cx: xs[index],
2559
+ cy: y(point.tokens),
2560
+ r: active === index ? radius + 2.5 : radius,
2561
+ className: active === index ? TrendChart_module_css_default.dotActive : TrendChart_module_css_default.dot
2562
+ }, point.key)),
2563
+ activePoint !== null ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
2564
+ x1: xs[active],
2565
+ y1: y(activePoint.tokens),
2566
+ x2: xs[active],
2567
+ y2: y(0),
2568
+ className: TrendChart_module_css_default.guide
2569
+ }) : null,
2570
+ points.map((point, index) => {
2571
+ const hit = hitExtent(index);
2572
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
2573
+ x: hit.start,
2574
+ y: TOP,
2575
+ width: hit.width,
2576
+ height: innerHeight,
2577
+ fill: "transparent",
2578
+ "aria-label": tipOf(t, point),
2579
+ role: "button",
2580
+ tabIndex: 0,
2581
+ className: TrendChart_module_css_default.hit,
2582
+ onMouseEnter: () => setActive(index),
2583
+ onFocus: () => setActive(index),
2584
+ onBlur: () => setActive((current) => current === index ? null : current)
2585
+ }, point.key);
2586
+ }),
2587
+ activePoint !== null ? (() => {
2588
+ const label = tipOf(t, activePoint);
2589
+ const labelWidth = label.length * 6.2 + 12;
2590
+ const center = xs[active];
2591
+ const left = Math.min(Math.max(center - labelWidth / 2, LEFT), 784 - labelWidth);
2592
+ const labelY = Math.max(y(activePoint.tokens) - 12, 20);
2593
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("g", {
2594
+ className: TrendChart_module_css_default.pointLabel,
2595
+ pointerEvents: "none",
2596
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("rect", {
2597
+ x: left,
2598
+ y: labelY - 13,
2599
+ width: labelWidth,
2600
+ height: 20,
2601
+ rx: 5
2602
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("text", {
2603
+ x: left + labelWidth / 2,
2604
+ y: labelY,
2605
+ textAnchor: "middle",
2606
+ children: label
2607
+ })]
2608
+ });
2609
+ })() : null,
2610
+ labelIndices(points.length).map((index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("text", {
2611
+ x: xs[index],
2612
+ y: 184,
2613
+ textAnchor: index === 0 ? "start" : index === points.length - 1 ? "end" : "middle",
2614
+ className: TrendChart_module_css_default.tick,
2615
+ children: points[index].label
2616
+ }, index))
2617
+ ]
2618
+ });
2619
+ }
2620
+ //#endregion
2621
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\TokenUsageSection.module.css.mjs
2622
+ const css$1 = ".RbkiSa_section{flex-direction:column;gap:16px;width:100%;display:flex}.RbkiSa_head{justify-content:space-between;align-items:center;gap:12px;display:flex}.RbkiSa_title{color:var(--dsw-alias-label-primary);margin:0;font-size:16px;font-weight:600}.RbkiSa_muted{color:var(--dsw-alias-label-secondary);margin:0;font-size:12px}.RbkiSa_rateNote{color:var(--dsw-alias-label-secondary);margin:6px 0 0;font-size:12px}.RbkiSa_error{color:var(--dsw-alias-state-error-primary);margin:0;font-size:13px}.RbkiSa_subtitle{color:var(--dsw-alias-label-secondary);margin:0;font-size:14px;font-weight:600}.RbkiSa_tableWrap{overflow-x:auto}.RbkiSa_table{border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;min-width:500px;font-size:12px}.RbkiSa_table th,.RbkiSa_table td{text-align:right;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap;padding:4px 6px}.RbkiSa_table th.RbkiSa_modelHead,.RbkiSa_table td.RbkiSa_modelCol{text-align:left;width:150px;max-width:150px}.RbkiSa_table th{color:var(--dsw-alias-label-secondary);font-weight:500}.RbkiSa_table td{color:var(--dsw-alias-label-primary)}.RbkiSa_empty{color:var(--dsw-alias-label-secondary);margin:0;font-size:13px}.RbkiSa_button{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);cursor:pointer;border-radius:6px;padding:4px 12px;font-size:13px;line-height:20px}.RbkiSa_button:hover{background:var(--dsw-interactive-bg-hover)}.RbkiSa_filters{flex-wrap:nowrap;align-items:center;gap:8px;display:flex}.RbkiSa_control,.RbkiSa_modelControl{appearance:none;background-image:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12' fill='none'%3E%3Cpath d='M3 4.5L6 7.5L9 4.5' stroke='%2381858C' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E\");background-position:right 6px center;background-repeat:no-repeat;background-size:12px 12px;padding-right:26px}.RbkiSa_control{box-sizing:border-box;color:var(--dsw-alias-label-primary);background-color:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:6px;padding:4px 26px 4px 8px;font-size:13px;line-height:20px}.RbkiSa_dateControl{box-sizing:border-box;width:138px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:6px;flex:none;padding:4px 6px;font-size:13px;line-height:20px}.RbkiSa_modelControl{box-sizing:border-box;text-overflow:ellipsis;min-width:0;max-width:220px;color:var(--dsw-alias-label-primary);background-color:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:6px;padding:4px 26px 4px 8px;font-size:13px;line-height:20px;overflow:hidden}.RbkiSa_rangeSeparator{color:var(--dsw-alias-label-secondary);font-size:12px}.RbkiSa_cards{grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:8px;display:grid}.RbkiSa_warning{color:var(--dsw-alias-state-warn-label);background:var(--dsw-alias-state-warn-tertiary);border-radius:6px;margin:0;padding:6px 10px;font-size:12px}.RbkiSa_modelCell{align-items:center;gap:4px;max-width:138px;display:inline-flex;position:relative}.RbkiSa_modelName{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.RbkiSa_unpricedTag{color:var(--dsw-alias-state-warn-label);background:var(--dsw-alias-state-warn-tertiary);border-radius:8px;flex:none;padding:0 6px;font-size:10px;line-height:16px}.RbkiSa_pricingButton{color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);cursor:pointer;border-radius:8px;flex:none;padding:0 6px;font-size:10px;line-height:16px}.RbkiSa_pricingButton:hover{color:var(--dsw-alias-state-warn-primary);background:var(--dsw-alias-state-warn-tertiary);border-color:var(--dsw-alias-state-warn-primary)}.RbkiSa_dialog{width:min(600px,100vw - 48px);max-height:calc(100vh - 48px);color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:10px;padding:14px 16px;overflow-y:auto}.RbkiSa_dialog::backdrop{background:#0006}.RbkiSa_dialogHead{justify-content:space-between;align-items:center;gap:12px;margin-bottom:8px;display:flex}.RbkiSa_dialogTitle{text-overflow:ellipsis;white-space:nowrap;font-variant-numeric:tabular-nums;font-size:14px;font-weight:600;overflow:hidden}.RbkiSa_dialogClose{color:var(--dsw-alias-label-secondary);cursor:pointer;background:0 0;border:none;border-radius:6px;flex:none;padding:2px 8px;font-size:12px;line-height:18px}.RbkiSa_dialogClose:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-interactive-bg-hover)}th.RbkiSa_conditionHead,td.RbkiSa_conditionCell{text-align:left;white-space:normal;min-width:200px}td.RbkiSa_conditionCell{color:var(--dsw-alias-label-secondary);padding-left:20px}.RbkiSa_groupRow>td{text-align:left;white-space:normal;color:var(--dsw-alias-label-secondary);border-bottom:none;padding-top:8px;font-size:11px;font-weight:600}.RbkiSa_groupRow:not(:first-child)>td{border-top:1px solid var(--dsw-alias-border-l1)}";
2623
+ const tagId$1 = "dsh-token-usage/TokenUsageSection.module.css";
2624
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$1) + "]") === null) {
2625
+ const tag = document.createElement("style");
2626
+ tag.dataset.plugin = "dsh-token-usage";
2627
+ tag.dataset.pluginCss = tagId$1;
2628
+ tag.textContent = css$1;
2629
+ document.head.appendChild(tag);
2630
+ }
2631
+ var TokenUsageSection_module_css_default = {
2632
+ "button": "RbkiSa_button",
2633
+ "cards": "RbkiSa_cards",
2634
+ "conditionCell": "RbkiSa_conditionCell",
2635
+ "conditionHead": "RbkiSa_conditionHead",
2636
+ "control": "RbkiSa_control",
2637
+ "dateControl": "RbkiSa_dateControl",
2638
+ "dialog": "RbkiSa_dialog",
2639
+ "dialogClose": "RbkiSa_dialogClose",
2640
+ "dialogHead": "RbkiSa_dialogHead",
2641
+ "dialogTitle": "RbkiSa_dialogTitle",
2642
+ "empty": "RbkiSa_empty",
2643
+ "error": "RbkiSa_error",
2644
+ "filters": "RbkiSa_filters",
2645
+ "groupRow": "RbkiSa_groupRow",
2646
+ "head": "RbkiSa_head",
2647
+ "modelCell": "RbkiSa_modelCell",
2648
+ "modelCol": "RbkiSa_modelCol",
2649
+ "modelControl": "RbkiSa_modelControl",
2650
+ "modelHead": "RbkiSa_modelHead",
2651
+ "modelName": "RbkiSa_modelName",
2652
+ "muted": "RbkiSa_muted",
2653
+ "pricingButton": "RbkiSa_pricingButton",
2654
+ "rangeSeparator": "RbkiSa_rangeSeparator",
2655
+ "rateNote": "RbkiSa_rateNote",
2656
+ "section": "RbkiSa_section",
2657
+ "subtitle": "RbkiSa_subtitle",
2658
+ "table": "RbkiSa_table",
2659
+ "tableWrap": "RbkiSa_tableWrap",
2660
+ "title": "RbkiSa_title",
2661
+ "unpricedTag": "RbkiSa_unpricedTag",
2662
+ "warning": "RbkiSa_warning"
2663
+ };
2664
+ //#endregion
2665
+ //#region src/client/TokenUsageSection.tsx
2666
+ /**
2667
+ * Token-usage settings page (browser half): fetches the stats summary from
2668
+ * the host route and renders the filter bar (inclusive day range, model
2669
+ * select, 1d/7d/30d quick ranges where 1d spans today 00:00–23:59), the
2670
+ * total-usage strip, the daily-token trend chart, the per-model detail
2671
+ * table with the hit rate last, and — opened by each priced model row's
2672
+ * “定价” affordance — a dialog with that model's full price table — all
2673
+ * following the active filters. There is no refresh button: entering the
2674
+ * page or changing a filter refetches (the route answers no-store); only
2675
+ * the error state keeps a retry.
2676
+ *
2677
+ * @module token-usage/client/TokenUsageSection
2678
+ */
2679
+ /** Fetch the summary for one query string; the caller owns the failure
2680
+ * presentation. The AbortSignal wires into the request so a filter change
2681
+ * cancels the in-flight fetch instead of letting its response overwrite
2682
+ * the next filter's data. */
2683
+ function fetchSummary(query, signal) {
2684
+ return fetch(STATS_PATH + query, { signal }).then((response) => {
2685
+ if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
2686
+ return response.json();
2687
+ }).then((value) => {
2688
+ if (typeof value !== "object" || value === null || typeof value.total !== "object") throw new Error("unexpected stats response");
2689
+ return value;
2690
+ });
2691
+ }
2692
+ /**
2693
+ * The query string of one filter selection ('' when unconstrained), or null
2694
+ * while the range is mid-edit (`from > to`): editing the two date inputs
2695
+ * one at a time passes through inverted ranges, and fetching those would
2696
+ * only flash an HTTP 400 — the request waits until the range settles.
2697
+ */
2698
+ function filterQuery(filters) {
2699
+ if (filters.from !== "" && filters.to !== "" && filters.from > filters.to) return null;
2700
+ const params = new URLSearchParams();
2701
+ if (filters.from !== "") params.set("from", filters.from);
2702
+ if (filters.to !== "") params.set("to", filters.to);
2703
+ if (filters.model !== "") params.set("model", filters.model);
2704
+ return Array.from(params).length > 0 ? `?${params.toString()}` : "";
2705
+ }
2706
+ /** Quick-range day span in days (1 = today only, inclusive on both ends). */
2707
+ const QUICK_DAYS = [
2708
+ 1,
2709
+ 7,
2710
+ 30
2711
+ ];
2712
+ /** The day keys of one quick range: today minus (days - 1) through today. */
2713
+ function quickRange(days) {
2714
+ return {
2715
+ from: shiftedDayKey(-(days - 1)),
2716
+ to: shiftedDayKey(0)
2717
+ };
2718
+ }
2719
+ /** Whether the filters exactly hold one quick range. */
2720
+ function isQuickActive(days, filters) {
2721
+ const range = quickRange(days);
2722
+ return filters.from === range.from && filters.to === range.to;
2723
+ }
2724
+ /** The four base rates of one model as display text (symbol included,
2725
+ * converted for a USD view); a missing cache rate bills at the input rate. */
2726
+ function billedRates(rates, view) {
2727
+ return {
2728
+ input: formatRateWithSymbol(rates.inputPerMillion, view),
2729
+ output: formatRateWithSymbol(rates.outputPerMillion, view),
2730
+ cacheRead: formatRateWithSymbol(rates.cacheReadPerMillion ?? rates.inputPerMillion, view),
2731
+ cacheWrite: formatRateWithSymbol(rates.cacheWritePerMillion ?? rates.inputPerMillion, view)
2732
+ };
2733
+ }
2734
+ /** `HH:MM-HH:MM` of one peak window (half-open, local minutes). */
2735
+ function windowText(window) {
2736
+ const clock = (minute) => `${String(Math.floor(minute / 60)).padStart(2, "0")}:${String(minute % 60).padStart(2, "0")}`;
2737
+ return `${clock(window.startMinute)}-${clock(window.endMinute)}`;
2738
+ }
2739
+ /** The when-it-applies text of one peak slot: its label plus its windows. */
2740
+ function slotCondition(slot, t) {
2741
+ return `${slot.label ?? t("pricing.peak")} ${slot.windows.map(windowText).join(t("pricing.windowSep"))}`;
2742
+ }
2743
+ /**
2744
+ * The price rows of one rate node (a time rule's or the model root's): the
2745
+ * node's own base rates, then its peak slots, then its context tiers
2746
+ * (ascending), each tier followed by the peak slots hanging on that tier —
2747
+ * mirroring {@link resolveRate}'s node chain, where a matching tier's slots
2748
+ * replace the node's and peak rates replace the node's rates wholesale.
2749
+ */
2750
+ function nodePriceRows(node, t) {
2751
+ const rows = [{
2752
+ condition: t("pricing.default"),
2753
+ rates: node.rates
2754
+ }];
2755
+ const tiers = [...node.tiers ?? []].sort((a, b) => a.threshold - b.threshold);
2756
+ for (const tier of tiers) {
2757
+ const tierCondition = t("pricing.tier", { threshold: formatTokens(tier.threshold) });
2758
+ rows.push({
2759
+ condition: tierCondition,
2760
+ rates: tier.rates
2761
+ });
2762
+ for (const slot of tier.dailySlots ?? []) rows.push({
2763
+ condition: `${tierCondition} · ${slotCondition(slot, t)}`,
2764
+ rates: slot.rates
2765
+ });
2766
+ }
2767
+ for (const slot of node.slots ?? []) rows.push({
2768
+ condition: slotCondition(slot, t),
2769
+ rates: slot.rates
2770
+ });
2771
+ return rows;
2772
+ }
2773
+ /**
2774
+ * One model's price table: rows are billing conditions — grouped into the
2775
+ * model root (“常规”, omitted when it is the only group) and one group per
2776
+ * time rule with its date window — so tier, peak, and time-rule pricing
2777
+ * each show when they apply and what they bill. Shared by the pricing
2778
+ * dialog; the structure mirrors {@link resolveRate}'s node chain.
2779
+ */
2780
+ function ModelPriceTable({ rules, view, t }) {
2781
+ const groups = [{
2782
+ title: rules.timeRules.length > 0 ? t("pricing.regular") : null,
2783
+ rows: nodePriceRows({
2784
+ rates: rules.base,
2785
+ tiers: rules.contextTiers,
2786
+ slots: rules.dailySlots
2787
+ }, t)
2788
+ }, ...rules.timeRules.map((rule) => ({
2789
+ title: `${rule.label !== void 0 ? `${rule.label} ` : ""}${rule.startTime > 0 ? `${dayKeyOf(/* @__PURE__ */ new Date(rule.startTime * 1e3))} ~ ` : "~ "}${dayKeyOf(/* @__PURE__ */ new Date(rule.endTime * 1e3))}`,
2790
+ rows: nodePriceRows({
2791
+ rates: rule.rates,
2792
+ tiers: rule.contextTiers,
2793
+ slots: rule.dailySlots
2794
+ }, t)
2795
+ }))];
2796
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2797
+ className: TokenUsageSection_module_css_default["tableWrap"],
2798
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
2799
+ className: TokenUsageSection_module_css_default["table"],
2800
+ "aria-label": t("pricing.title"),
2801
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
2802
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", {
2803
+ className: TokenUsageSection_module_css_default["conditionHead"],
2804
+ children: t("pricing.condition")
2805
+ }),
2806
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("th", { children: [t("pricing.input"), t("pricing.perMillion")] }),
2807
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("th", { children: [t("pricing.output"), t("pricing.perMillion")] }),
2808
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("th", { children: [t("pricing.cacheRead"), t("pricing.perMillion")] }),
2809
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("th", { children: [t("pricing.cacheWrite"), t("pricing.perMillion")] })
2810
+ ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: groups.flatMap((group) => [...group.title !== null ? [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("tr", {
2811
+ className: TokenUsageSection_module_css_default["groupRow"],
2812
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", {
2813
+ colSpan: 5,
2814
+ children: group.title
2815
+ })
2816
+ }, group.title)] : [], ...group.rows.map((row, index) => {
2817
+ const billed = billedRates(row.rates, view);
2818
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
2819
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", {
2820
+ className: TokenUsageSection_module_css_default["conditionCell"],
2821
+ children: row.condition
2822
+ }),
2823
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: billed.input }),
2824
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: billed.output }),
2825
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: billed.cacheRead }),
2826
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: billed.cacheWrite })
2827
+ ] }, `${group.title ?? ""}-${index}-${row.condition}`);
2828
+ })]) })]
2829
+ }), view.symbol === "$" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
2830
+ className: TokenUsageSection_module_css_default["rateNote"],
2831
+ children: t("pricing.exchangeRateNote", { rate: formatRate(view.rate) })
2832
+ }) : null]
2833
+ });
2834
+ }
2835
+ /**
2836
+ * The pricing dialog of one model: a native `<dialog>` (Esc closes, focus
2837
+ * is trapped, the backdrop dims, and the top layer renders it above the
2838
+ * table's scroll shell) opened by the “定价” affordance in a model row.
2839
+ * Mounts only while a model is selected; every close path funnels through
2840
+ * the dialog's `close` event, which clears the selection and unmounts it.
2841
+ */
2842
+ function PricingDialog({ model, rules, view, onClose, t }) {
2843
+ const dialogRef = (0, react.useRef)(null);
2844
+ (0, react.useEffect)(() => {
2845
+ const dialog = dialogRef.current;
2846
+ if (dialog !== null && !dialog.open) dialog.showModal();
2847
+ }, []);
2848
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("dialog", {
2849
+ ref: dialogRef,
2850
+ className: TokenUsageSection_module_css_default["dialog"],
2851
+ "aria-label": t("pricing.title"),
2852
+ onClose,
2853
+ onClick: (event) => {
2854
+ if (event.target === dialogRef.current) dialogRef.current?.close();
2855
+ },
2856
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2857
+ className: TokenUsageSection_module_css_default["dialogHead"],
2858
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2859
+ className: TokenUsageSection_module_css_default["dialogTitle"],
2860
+ children: model
2861
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2862
+ type: "button",
2863
+ className: TokenUsageSection_module_css_default["dialogClose"],
2864
+ "aria-label": t("pricing.close"),
2865
+ onClick: () => dialogRef.current?.close(),
2866
+ children: "✕"
2867
+ })]
2868
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ModelPriceTable, {
2869
+ rules,
2870
+ view,
2871
+ t
2872
+ })]
2873
+ });
2874
+ }
2875
+ /** The filter bar: quick range select, day range, model select — one row. */
2876
+ function FilterBar({ filters, models, onChange, t }) {
2877
+ const quickValue = QUICK_DAYS.find((days) => isQuickActive(days, filters)) ?? "custom";
2878
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2879
+ className: TokenUsageSection_module_css_default["filters"],
2880
+ children: [
2881
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
2882
+ "aria-label": t("filter.quickRange"),
2883
+ className: TokenUsageSection_module_css_default["control"],
2884
+ value: quickValue,
2885
+ onChange: (event) => {
2886
+ const days = Number(event.target.value);
2887
+ if (days > 0) onChange({
2888
+ ...filters,
2889
+ ...quickRange(days)
2890
+ });
2891
+ },
2892
+ children: [
2893
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2894
+ value: "1",
2895
+ children: "1d"
2896
+ }),
2897
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2898
+ value: "7",
2899
+ children: "7d"
2900
+ }),
2901
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2902
+ value: "30",
2903
+ children: "30d"
2904
+ }),
2905
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2906
+ value: "custom",
2907
+ children: t("filter.custom")
2908
+ })
2909
+ ]
2910
+ }),
2911
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
2912
+ type: "date",
2913
+ "aria-label": t("filter.from"),
2914
+ className: TokenUsageSection_module_css_default["dateControl"],
2915
+ value: filters.from,
2916
+ onChange: (event) => onChange({
2917
+ ...filters,
2918
+ from: event.target.value
2919
+ })
2920
+ }),
2921
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
2922
+ className: TokenUsageSection_module_css_default["rangeSeparator"],
2923
+ children: t("filter.separator")
2924
+ }),
2925
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
2926
+ type: "date",
2927
+ "aria-label": t("filter.to"),
2928
+ className: TokenUsageSection_module_css_default["dateControl"],
2929
+ value: filters.to,
2930
+ onChange: (event) => onChange({
2931
+ ...filters,
2932
+ to: event.target.value
2933
+ })
2934
+ }),
2935
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
2936
+ "aria-label": t("filter.model"),
2937
+ className: TokenUsageSection_module_css_default["modelControl"],
2938
+ value: filters.model,
2939
+ onChange: (event) => onChange({
2940
+ ...filters,
2941
+ model: event.target.value
2942
+ }),
2943
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2944
+ value: "",
2945
+ children: t("filter.allModels")
2946
+ }), models.map((model) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
2947
+ value: model,
2948
+ children: model
2949
+ }, model))]
2950
+ })
2951
+ ]
2952
+ });
2953
+ }
2954
+ /**
2955
+ * Render the Token Usage section content column. The `t` seat arrives from
2956
+ * the registration's `locale:` declaration and follows the active locale.
2957
+ * @param props - the settings shell's owner share (close is unused: the nav
2958
+ * rail owns leaving the panel) plus the framework-injected translate seat.
2959
+ * @returns the section, one of loading / error / ready.
2960
+ */
2961
+ function TokenUsageSection({ t }) {
2962
+ const rootRef = (0, react.useRef)(null);
2963
+ useColorSchemeMirror(rootRef);
2964
+ const [filters, setFilters] = (0, react.useState)(() => ({
2965
+ model: "",
2966
+ ...quickRange(1)
2967
+ }));
2968
+ const [models, setModels] = (0, react.useState)([]);
2969
+ const [detailModel, setDetailModel] = (0, react.useState)(null);
2970
+ const [retryToken, setRetryToken] = (0, react.useState)(0);
2971
+ const retry = (0, react.useCallback)(() => {
2972
+ setRetryToken((previous) => previous + 1);
2973
+ }, []);
2974
+ const query = filterQuery(filters);
2975
+ const lastValidQueryRef = (0, react.useRef)(query ?? "");
2976
+ if (query !== null) lastValidQueryRef.current = query;
2977
+ const fetchQuery = query ?? lastValidQueryRef.current;
2978
+ const [state] = useAsyncResource((signal) => fetchSummary(fetchQuery, signal), [fetchQuery, retryToken], {
2979
+ silentAfterFirst: false,
2980
+ retryToken
2981
+ });
2982
+ (0, react.useEffect)(() => {
2983
+ if (state.status !== "ready") return;
2984
+ if (filters.model !== "") return;
2985
+ const next = state.value.byModel.map((row) => row.model);
2986
+ if (next.length === models.length && next.every((m, i) => m === models[i])) return;
2987
+ setModels(next);
2988
+ }, [
2989
+ state,
2990
+ filters.model,
2991
+ models
2992
+ ]);
2993
+ if (state.status === "loading") return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2994
+ ref: rootRef,
2995
+ className: TokenUsageSection_module_css_default["section"],
2996
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", {
2997
+ className: TokenUsageSection_module_css_default["title"],
2998
+ children: t("nav.label")
2999
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3000
+ className: TokenUsageSection_module_css_default["muted"],
3001
+ children: t("loading")
3002
+ })]
3003
+ });
3004
+ if (state.status === "error") return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3005
+ ref: rootRef,
3006
+ className: TokenUsageSection_module_css_default["section"],
3007
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3008
+ className: TokenUsageSection_module_css_default["head"],
3009
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", {
3010
+ className: TokenUsageSection_module_css_default["title"],
3011
+ children: t("nav.label")
3012
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3013
+ type: "button",
3014
+ className: TokenUsageSection_module_css_default["button"],
3015
+ onClick: retry,
3016
+ children: t("retry")
3017
+ })]
3018
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3019
+ className: TokenUsageSection_module_css_default["error"],
3020
+ children: t("loadFailed", { message: state.message })
3021
+ })]
3022
+ });
3023
+ const { total } = state.value;
3024
+ const view = currencyViewOf(state.value);
3025
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3026
+ ref: rootRef,
3027
+ className: TokenUsageSection_module_css_default["section"],
3028
+ children: [
3029
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", {
3030
+ className: TokenUsageSection_module_css_default["title"],
3031
+ children: t("nav.label")
3032
+ }),
3033
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3034
+ className: TokenUsageSection_module_css_default["muted"],
3035
+ children: t("dataDir", { path: state.value.dataDir })
3036
+ }),
3037
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FilterBar, {
3038
+ filters,
3039
+ models,
3040
+ onChange: setFilters,
3041
+ t
3042
+ }),
3043
+ total.requests === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3044
+ className: TokenUsageSection_module_css_default["empty"],
3045
+ children: t("empty")
3046
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
3047
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3048
+ className: TokenUsageSection_module_css_default["cards"],
3049
+ children: [
3050
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3051
+ label: t("stat.requests"),
3052
+ value: total.requests.toLocaleString()
3053
+ }),
3054
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3055
+ label: t("stat.cost"),
3056
+ value: formatCost(state.value.totalCost, view)
3057
+ }),
3058
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3059
+ label: t("stat.totalTokens"),
3060
+ value: formatTokens(totalTokens(total))
3061
+ }),
3062
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3063
+ label: t("stat.hitRate"),
3064
+ value: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HitRateText, { totals: total })
3065
+ })
3066
+ ]
3067
+ }),
3068
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3069
+ className: TokenUsageSection_module_css_default["cards"],
3070
+ children: [
3071
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3072
+ label: t("stat.input"),
3073
+ value: formatTokens(total.inputTokens)
3074
+ }),
3075
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3076
+ label: t("stat.output"),
3077
+ value: formatTokens(total.outputTokens)
3078
+ }),
3079
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3080
+ label: t("stat.cacheRead"),
3081
+ value: formatTokens(total.cacheReadTokens)
3082
+ }),
3083
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3084
+ label: t("stat.cacheWrite"),
3085
+ value: formatTokens(total.cacheWriteTokens)
3086
+ })
3087
+ ]
3088
+ }),
3089
+ state.value.unpricedModels.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3090
+ className: TokenUsageSection_module_css_default["warning"],
3091
+ role: "status",
3092
+ children: t("unpriced.warning", {
3093
+ count: String(state.value.unpricedModels.length),
3094
+ models: state.value.unpricedModels.join(", "),
3095
+ zero: formatCost(0, view)
3096
+ })
3097
+ }) : null,
3098
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TrendChart, {
3099
+ rows: state.value.byDay,
3100
+ t,
3101
+ ...filters.from !== "" ? { from: filters.from } : {},
3102
+ ...filters.to !== "" ? { to: filters.to } : {},
3103
+ ...filters.from !== "" && filters.from === filters.to ? { hours: state.value.byHour } : {}
3104
+ }),
3105
+ state.value.byModel.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
3106
+ className: TokenUsageSection_module_css_default["subtitle"],
3107
+ children: t("byModel.title")
3108
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3109
+ className: TokenUsageSection_module_css_default["tableWrap"],
3110
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
3111
+ className: TokenUsageSection_module_css_default["table"],
3112
+ "aria-label": t("byModel.title"),
3113
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
3114
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", {
3115
+ className: TokenUsageSection_module_css_default["modelHead"],
3116
+ children: t("filter.model")
3117
+ }),
3118
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.requests") }),
3119
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.cost") }),
3120
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.totalTokens") }),
3121
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.input") }),
3122
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.output") }),
3123
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.cacheRead") }),
3124
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.cacheWrite") }),
3125
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.hitRate") })
3126
+ ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: state.value.byModel.map((row) => {
3127
+ const rules = state.value.pricing[row.model];
3128
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
3129
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", {
3130
+ className: TokenUsageSection_module_css_default["modelCol"],
3131
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
3132
+ className: TokenUsageSection_module_css_default["modelCell"],
3133
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
3134
+ className: TokenUsageSection_module_css_default["modelName"],
3135
+ children: row.model
3136
+ }), rules !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3137
+ type: "button",
3138
+ className: TokenUsageSection_module_css_default["pricingButton"],
3139
+ "aria-label": t("pricing.view", { model: row.model }),
3140
+ onClick: () => setDetailModel(row.model),
3141
+ children: t("pricing.viewShort")
3142
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
3143
+ className: TokenUsageSection_module_css_default["unpricedTag"],
3144
+ children: t("pricing.unpriced")
3145
+ })]
3146
+ })
3147
+ }),
3148
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row.totals.requests.toLocaleString() }),
3149
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: rules !== void 0 ? formatCost(row.cost, view) : "—" }),
3150
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(totalTokens(row.totals)) }),
3151
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(row.totals.inputTokens) }),
3152
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(row.totals.outputTokens) }),
3153
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(row.totals.cacheReadTokens) }),
3154
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(row.totals.cacheWriteTokens) }),
3155
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HitRateText, { totals: row.totals }) })
3156
+ ] }, row.model);
3157
+ }) })]
3158
+ })
3159
+ })] }) : null,
3160
+ detailModel !== null && state.value.pricing[detailModel] !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PricingDialog, {
3161
+ model: detailModel,
3162
+ rules: state.value.pricing[detailModel],
3163
+ view,
3164
+ onClose: () => setDetailModel(null),
3165
+ t
3166
+ }) : null
3167
+ ] })
3168
+ ]
3169
+ });
3170
+ }
3171
+ //#endregion
3172
+ //#region \0dsh-css:D:\Code\dsh-token-usage\src\client\UsageView.module.css.mjs
3173
+ const css = "._0MkXVa_root{box-sizing:border-box;width:100%;padding:12px calc(var(--dsh-composer-side-clearance,16px) + 16px);flex-direction:column;gap:12px;max-width:1400px;height:100%;margin:0 auto;display:flex;overflow-y:auto}._0MkXVa_head{flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:12px;display:flex}._0MkXVa_headRight{align-items:center;gap:10px;display:flex}._0MkXVa_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}._0MkXVa_back:hover{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-border-l2)}._0MkXVa_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}._0MkXVa_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}._0MkXVa_segBtn:hover:not(._0MkXVa_segActive){color:var(--dsw-alias-label-secondary);background:color-mix(in srgb, var(--dsw-alias-label-primary) 6%, transparent)}._0MkXVa_segBtn:focus-visible{outline:2px solid var(--dsw-alias-border-l2);outline-offset:1px}._0MkXVa_segActive{background:color-mix(in srgb, var(--dsw-alias-label-primary) 16%, transparent);color:var(--dsw-alias-label-primary);font-weight:600}._0MkXVa_muted{color:var(--dsw-alias-label-secondary);margin:0;font-size:12px}._0MkXVa_error{color:var(--dsw-alias-state-error-primary);margin:0;font-size:13px}._0MkXVa_empty{color:var(--dsw-alias-label-secondary);text-align:center;margin:24px 0 0;font-size:13px}._0MkXVa_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}._0MkXVa_warning{color:var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-secondary));margin:0;font-size:12px}._0MkXVa_note{color:var(--dsw-alias-label-tertiary);margin:0;font-size:11px}._0MkXVa_cards{grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;display:grid}._0MkXVa_tokenStrip{color:var(--dsw-alias-label-secondary);flex-wrap:wrap;gap:18px;padding:6px 2px 0;font-size:12px;display:flex}._0MkXVa_tokenStrip b{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}._0MkXVa_mid{grid-template-columns:minmax(0,3fr) minmax(0,2fr);align-items:start;gap:14px;display:grid}._0MkXVa_chartCol,._0MkXVa_modelCol,._0MkXVa_subagents{flex-direction:column;gap:6px;min-width:0;display:flex}._0MkXVa_subagentsHead{align-items:center;gap:8px;display:flex}._0MkXVa_subtitle{color:var(--dsw-alias-label-secondary);margin:0;font-size:13px;font-weight:600}._0MkXVa_tableWrap{overflow-x:auto}._0MkXVa_table{border-collapse:collapse;font-variant-numeric:tabular-nums;width:100%;min-width:480px;font-size:12px}._0MkXVa_table th,._0MkXVa_table td{text-align:right;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap;padding:4px 6px}._0MkXVa_table th:first-child,._0MkXVa_table td:first-child,._0MkXVa_modelHead{text-align:left}._0MkXVa_modelCell{font-variant-numeric:normal;text-overflow:ellipsis;max-width:180px;overflow:hidden}._0MkXVa_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}._0MkXVa_childLink:hover{text-decoration:underline}._0MkXVa_nestedBadge{color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;margin-left:6px;font-size:11px}@media (width<=900px){._0MkXVa_cards{grid-template-columns:repeat(3,minmax(0,1fr))}._0MkXVa_mid{grid-template-columns:1fr}}";
3174
+ const tagId = "dsh-token-usage/UsageView.module.css";
3175
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
3176
+ const tag = document.createElement("style");
3177
+ tag.dataset.plugin = "dsh-token-usage";
3178
+ tag.dataset.pluginCss = tagId;
3179
+ tag.textContent = css;
3180
+ document.head.appendChild(tag);
3181
+ }
3182
+ var UsageView_module_css_default = {
3183
+ "back": "_0MkXVa_back",
3184
+ "button": "_0MkXVa_button",
3185
+ "cards": "_0MkXVa_cards",
3186
+ "chartCol": "_0MkXVa_chartCol",
3187
+ "childLink": "_0MkXVa_childLink",
3188
+ "empty": "_0MkXVa_empty",
3189
+ "error": "_0MkXVa_error",
3190
+ "head": "_0MkXVa_head",
3191
+ "headRight": "_0MkXVa_headRight",
3192
+ "mid": "_0MkXVa_mid",
3193
+ "modelCell": "_0MkXVa_modelCell",
3194
+ "modelCol": "_0MkXVa_modelCol",
3195
+ "modelHead": "_0MkXVa_modelHead",
3196
+ "muted": "_0MkXVa_muted",
3197
+ "nestedBadge": "_0MkXVa_nestedBadge",
3198
+ "note": "_0MkXVa_note",
3199
+ "root": "_0MkXVa_root",
3200
+ "segActive": "_0MkXVa_segActive",
3201
+ "segBtn": "_0MkXVa_segBtn",
3202
+ "segmented": "_0MkXVa_segmented",
3203
+ "subagents": "_0MkXVa_subagents",
3204
+ "subagentsHead": "_0MkXVa_subagentsHead",
3205
+ "subtitle": "_0MkXVa_subtitle",
3206
+ "table": "_0MkXVa_table",
3207
+ "tableWrap": "_0MkXVa_tableWrap",
3208
+ "tokenStrip": "_0MkXVa_tokenStrip",
3209
+ "warning": "_0MkXVa_warning"
3210
+ };
3211
+ //#endregion
3212
+ //#region src/client/UsageView.tsx
3213
+ /**
3214
+ * The conversation view tab "Usage" (browser half): one entry of the
3215
+ * `conversation.view` slot ring (beside Chat / Trajectory), rendering the
3216
+ * per-session token & cost dashboard for the ACTIVE conversation. The tab
3217
+ * shows the focused session's totals (4 token buckets, cost, hit rate,
3218
+ * TTFT average, decode throughput) with a scope switch between the session
3219
+ * alone and its whole subagent subtree, a per-hour trend chart and the
3220
+ * per-model table from the host stats route (`sessionId`-scoped), and a
3221
+ * subagent table below — each row drill-in switches the focus to that child.
3222
+ *
3223
+ * Data sources: token/cost figures come from the host route (the pricing
3224
+ * rule chain's authority); TTFT and throughput come from the framework's
3225
+ * retained `sessionStats` projection values (`useProjection` for the current
3226
+ * session, `byId[].projectionValues` for every other session), which cover
3227
+ * the whole log including history written before this plugin was installed.
3228
+ * A footnote states the two scopes so the difference is not a surprise.
3229
+ *
3230
+ * @module token-usage/client/UsageView
3231
+ */
3232
+ /** Refresh debounce: bursts of session-mirror updates (one request's events)
3233
+ * collapse into a single fetch, so the dashboard refreshes at REQUEST
3234
+ * granularity instead of per event or per turn. */
3235
+ const REFRESH_DEBOUNCE_MS = 250;
3236
+ /** One fetch of the session-scoped summary from the host stats route,
3237
+ * including the direct-child breakdown for the subagent table. */
3238
+ function fetchSessionSummary(sessionIds, childGroups, signal) {
3239
+ return fetch(STATS_PATH + encodeStatsQuery({
3240
+ sessionIds,
3241
+ childGroups,
3242
+ fields: "session"
3243
+ }), { signal }).then((response) => {
3244
+ if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
3245
+ return response.json();
3246
+ }).then((value) => {
3247
+ if (typeof value !== "object" || value === null || typeof value.total !== "object") throw new Error("unexpected stats response");
3248
+ return value;
3249
+ });
3250
+ }
3251
+ /**
3252
+ * Render the Usage view tab for the active conversation.
3253
+ * @param props - the framework session kit, the session mirror, and the
3254
+ * locale seat (from the registration's `locale:` declaration).
3255
+ * @returns the dashboard: header (title, scope switch, back), stat cards
3256
+ * and the 4-token strip, the chart/model columns, and the subagent table.
3257
+ */
3258
+ function UsageView({ useSessions, useProjection, sessionId, t }) {
3259
+ const rootRef = (0, react.useRef)(null);
3260
+ useColorSchemeMirror(rootRef);
3261
+ const [scope, setScope] = (0, react.useState)("session");
3262
+ const [focusId, setFocusId] = (0, react.useState)(sessionId);
3263
+ (0, react.useEffect)(() => {
3264
+ setFocusId(sessionId);
3265
+ }, [sessionId]);
3266
+ const [retryToken, setRetryToken] = (0, react.useState)(0);
3267
+ const retry = () => {
3268
+ setRetryToken((token) => token + 1);
3269
+ };
3270
+ const byId = useSessions((state) => state.byId);
3271
+ const childIndex = (0, react.useMemo)(() => buildChildIndex(byId), [byId]);
3272
+ const scopeIds = (0, react.useMemo)(() => scope === "tree" ? subtreeIds(byId, focusId, childIndex) : [focusId], [
3273
+ byId,
3274
+ scope,
3275
+ focusId,
3276
+ childIndex
3277
+ ]);
3278
+ const children = (0, react.useMemo)(() => directSubagentIds(byId, focusId, childIndex), [
3279
+ byId,
3280
+ focusId,
3281
+ childIndex
3282
+ ]);
3283
+ const childGroups = (0, react.useMemo)(() => children.map((id) => scope === "tree" ? subtreeIds(byId, id, childIndex) : [id]), [
3284
+ children,
3285
+ scope,
3286
+ byId,
3287
+ childIndex
3288
+ ]);
3289
+ const backParent = subagentParentOf(byId, focusId);
3290
+ const liveStats = useProjection("sessionStats");
3291
+ const freshnessKey = buildStatsFreshnessKey([.../* @__PURE__ */ new Set([...scopeIds, ...children])], {
3292
+ activeSessionId: sessionId,
3293
+ rows: byId,
3294
+ liveSessionStats: liveStats
3295
+ });
3296
+ const debouncedKey = useDebouncedValue(`${scopeIds.join("\n")}\n\t${childGroups.map((group) => group.join(",")).join(";")}\n\t${freshnessKey}`, REFRESH_DEBOUNCE_MS);
3297
+ const [summaryState] = useAsyncResource((signal) => {
3298
+ const [idsPart, groupsPart] = debouncedKey.split("\n ");
3299
+ return fetchSessionSummary((idsPart ?? "").split("\n").filter((id) => id !== ""), (groupsPart ?? "").split(";").filter((group) => group !== "").map((group) => group.split(",")), signal);
3300
+ }, [debouncedKey, retryToken], {
3301
+ silentAfterFirst: true,
3302
+ retryToken
3303
+ });
3304
+ const stats = (0, react.useMemo)(() => {
3305
+ return aggregateProjections(scopeIds.map((id) => {
3306
+ if (id === sessionId) return liveStats;
3307
+ return byId[id]?.projectionValues?.sessionStats;
3308
+ }));
3309
+ }, [
3310
+ scopeIds,
3311
+ sessionId,
3312
+ liveStats,
3313
+ byId
3314
+ ]);
3315
+ const ttftText = stats !== void 0 && stats.ttftSteps > 0 ? formatTtft(stats.ttftMs / stats.ttftSteps) : "—";
3316
+ const speedText = stats !== void 0 && stats.decodeMs > 0 ? formatSpeed(stats.decodeTokens / (stats.decodeMs / 1e3)) : "—";
3317
+ const header = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("header", {
3318
+ className: UsageView_module_css_default["head"],
3319
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3320
+ className: UsageView_module_css_default["headRight"],
3321
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3322
+ className: UsageView_module_css_default["segmented"],
3323
+ role: "group",
3324
+ "aria-label": t("view.scope.label"),
3325
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3326
+ type: "button",
3327
+ className: scope === "session" ? `${UsageView_module_css_default["segBtn"]} ${UsageView_module_css_default["segActive"]}` : UsageView_module_css_default["segBtn"],
3328
+ "aria-pressed": scope === "session",
3329
+ onClick: () => setScope("session"),
3330
+ children: t("view.scope.session")
3331
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3332
+ type: "button",
3333
+ className: scope === "tree" ? `${UsageView_module_css_default["segBtn"]} ${UsageView_module_css_default["segActive"]}` : UsageView_module_css_default["segBtn"],
3334
+ "aria-pressed": scope === "tree",
3335
+ onClick: () => setScope("tree"),
3336
+ children: t("view.scope.tree")
3337
+ })]
3338
+ })
3339
+ })
3340
+ });
3341
+ if (summaryState.status === "loading") return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3342
+ ref: rootRef,
3343
+ className: UsageView_module_css_default["root"],
3344
+ children: [header, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3345
+ className: UsageView_module_css_default["muted"],
3346
+ children: t("loading")
3347
+ })]
3348
+ });
3349
+ if (summaryState.status === "error") return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3350
+ ref: rootRef,
3351
+ className: UsageView_module_css_default["root"],
3352
+ children: [
3353
+ header,
3354
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3355
+ className: UsageView_module_css_default["error"],
3356
+ children: t("loadFailed", { message: summaryState.message })
3357
+ }),
3358
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3359
+ type: "button",
3360
+ className: UsageView_module_css_default["button"],
3361
+ onClick: retry,
3362
+ children: t("retry")
3363
+ })
3364
+ ]
3365
+ });
3366
+ const summary = summaryState.value;
3367
+ const view = currencyViewOf(summary);
3368
+ const { total } = summary;
3369
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3370
+ ref: rootRef,
3371
+ className: UsageView_module_css_default["root"],
3372
+ children: [
3373
+ header,
3374
+ total.requests === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3375
+ className: UsageView_module_css_default["empty"],
3376
+ children: t("view.empty")
3377
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
3378
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3379
+ className: UsageView_module_css_default["cards"],
3380
+ children: [
3381
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3382
+ label: t("stat.requests"),
3383
+ value: total.requests.toLocaleString()
3384
+ }),
3385
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3386
+ label: t("stat.cost"),
3387
+ value: formatCost(summary.totalCost, view)
3388
+ }),
3389
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3390
+ label: t("stat.totalTokens"),
3391
+ value: formatTokens(totalTokens(total))
3392
+ }),
3393
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3394
+ label: t("stat.hitRate"),
3395
+ value: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HitRateText, { totals: total })
3396
+ }),
3397
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3398
+ label: t("view.ttft"),
3399
+ value: ttftText
3400
+ }),
3401
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StatCard, {
3402
+ label: t("view.speed"),
3403
+ value: `${speedText} tok/s`
3404
+ })
3405
+ ]
3406
+ }),
3407
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3408
+ className: UsageView_module_css_default["tokenStrip"],
3409
+ children: [
3410
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
3411
+ t("stat.input"),
3412
+ " ",
3413
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: formatTokens(total.inputTokens) })
3414
+ ] }),
3415
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
3416
+ t("stat.output"),
3417
+ " ",
3418
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: formatTokens(total.outputTokens) })
3419
+ ] }),
3420
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
3421
+ t("stat.cacheRead"),
3422
+ " ",
3423
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: formatTokens(total.cacheReadTokens) })
3424
+ ] }),
3425
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [
3426
+ t("stat.cacheWrite"),
3427
+ " ",
3428
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("b", { children: formatTokens(total.cacheWriteTokens) })
3429
+ ] })
3430
+ ]
3431
+ }),
3432
+ summary.unpricedModels.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3433
+ className: UsageView_module_css_default["warning"],
3434
+ role: "status",
3435
+ children: t("unpriced.warning", {
3436
+ count: String(summary.unpricedModels.length),
3437
+ models: summary.unpricedModels.join(", "),
3438
+ zero: formatCost(0, view)
3439
+ })
3440
+ }) : null,
3441
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3442
+ className: UsageView_module_css_default["mid"],
3443
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
3444
+ className: UsageView_module_css_default["chartCol"],
3445
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
3446
+ className: UsageView_module_css_default["subtitle"],
3447
+ children: t("view.chart.title")
3448
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TrendChart, {
3449
+ rows: summary.byDay,
3450
+ t,
3451
+ ...summary.requestSeries !== void 0 ? { requests: summary.requestSeries } : {},
3452
+ ...summary.byDay.length === 1 ? { hours: summary.byHour } : {}
3453
+ })]
3454
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
3455
+ className: UsageView_module_css_default["modelCol"],
3456
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
3457
+ className: UsageView_module_css_default["subtitle"],
3458
+ children: t("byModel.title")
3459
+ }), summary.byModel.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3460
+ className: UsageView_module_css_default["tableWrap"],
3461
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
3462
+ className: UsageView_module_css_default["table"],
3463
+ "aria-label": t("byModel.title"),
3464
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
3465
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", {
3466
+ className: UsageView_module_css_default["modelHead"],
3467
+ children: t("filter.model")
3468
+ }),
3469
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.requests") }),
3470
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.input") }),
3471
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.output") }),
3472
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.cacheRead") }),
3473
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.cacheWrite") }),
3474
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.hitRate") }),
3475
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.cost") })
3476
+ ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: summary.byModel.map((row) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
3477
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", {
3478
+ className: UsageView_module_css_default["modelCell"],
3479
+ children: row.model
3480
+ }),
3481
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row.totals.requests.toLocaleString() }),
3482
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(row.totals.inputTokens) }),
3483
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(row.totals.outputTokens) }),
3484
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(row.totals.cacheReadTokens) }),
3485
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatTokens(row.totals.cacheWriteTokens) }),
3486
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HitRateText, { totals: row.totals }) }),
3487
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: formatCost(row.cost, view) })
3488
+ ] }, row.model)) })]
3489
+ })
3490
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3491
+ className: UsageView_module_css_default["muted"],
3492
+ children: t("chart.empty")
3493
+ })]
3494
+ })]
3495
+ })
3496
+ ] }),
3497
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
3498
+ className: UsageView_module_css_default["subagents"],
3499
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3500
+ className: UsageView_module_css_default["subagentsHead"],
3501
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
3502
+ className: UsageView_module_css_default["subtitle"],
3503
+ children: t("view.subagents.title", { count: String(children.length) })
3504
+ }), (() => {
3505
+ if (backParent === void 0) return null;
3506
+ const parentSummary = byId[backParent];
3507
+ if (parentSummary === void 0) return null;
3508
+ const parentId = backParent;
3509
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3510
+ type: "button",
3511
+ className: UsageView_module_css_default["back"],
3512
+ onClick: () => setFocusId(parentId),
3513
+ children: t("view.back", { title: parentSummary.displayTitle ?? parentId })
3514
+ });
3515
+ })()]
3516
+ }), children.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3517
+ className: UsageView_module_css_default["muted"],
3518
+ children: t("view.subagents.none")
3519
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3520
+ className: UsageView_module_css_default["tableWrap"],
3521
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
3522
+ className: UsageView_module_css_default["table"],
3523
+ "aria-label": t("view.subagents.title", { count: String(children.length) }),
3524
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
3525
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", {
3526
+ className: UsageView_module_css_default["modelHead"],
3527
+ children: t("view.subagents.titleCol")
3528
+ }),
3529
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.requests") }),
3530
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.totalTokens") }),
3531
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.cost") }),
3532
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("stat.hitRate") }),
3533
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("view.ttft") }),
3534
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", { children: t("view.speed") })
3535
+ ] }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: children.map((id) => {
3536
+ const child = byId[id];
3537
+ const row = summary.children?.[id];
3538
+ const childStats = aggregateProjections([byId[id]?.projectionValues?.sessionStats]);
3539
+ const nestedCount = directSubagentIds(byId, id, childIndex).length;
3540
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("tr", { children: [
3541
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("td", {
3542
+ className: UsageView_module_css_default["modelCell"],
3543
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
3544
+ type: "button",
3545
+ className: UsageView_module_css_default["childLink"],
3546
+ onClick: () => setFocusId(id),
3547
+ children: child?.displayTitle ?? id
3548
+ }), nestedCount > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
3549
+ className: UsageView_module_css_default["nestedBadge"],
3550
+ "aria-label": t("view.subagents.nested", { count: String(nestedCount) }),
3551
+ children: [
3552
+ "(",
3553
+ nestedCount,
3554
+ ")"
3555
+ ]
3556
+ }) : null]
3557
+ }),
3558
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row?.total.requests.toLocaleString() ?? "—" }),
3559
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row !== void 0 ? formatTokens(totalTokens(row.total)) : "—" }),
3560
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row !== void 0 ? formatCost(row.totalCost, view) : "—" }),
3561
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: row !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HitRateText, { totals: row.total }) : "—" }),
3562
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: childStats !== void 0 && childStats.ttftSteps > 0 ? formatTtft(childStats.ttftMs / childStats.ttftSteps) : "—" }),
3563
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", { children: childStats !== void 0 && childStats.decodeMs > 0 ? `${formatSpeed(childStats.decodeTokens / (childStats.decodeMs / 1e3))} tok/s` : "—" })
3564
+ ] }, id);
3565
+ }) })]
3566
+ })
3567
+ })]
3568
+ }),
3569
+ total.requests > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
3570
+ className: UsageView_module_css_default["note"],
3571
+ children: t("view.note")
3572
+ })
3573
+ ]
3574
+ });
3575
+ }
3576
+ //#endregion
3577
+ //#region src/client/locales.ts
3578
+ /**
3579
+ * `token-usage` locale namespace dictionaries (browser half). zh is the
3580
+ * key-set source of truth; en is checked complete against it — the typed
3581
+ * `ctx.locale.register(NS, { zh, en })` call enforces both at compile time
3582
+ * and the `t` standard seat narrows its key domain to this union plus the
3583
+ * shared common vocabulary.
3584
+ *
3585
+ * @module token-usage/client/locales
3586
+ */
3587
+ /** Dictionary namespace owned by this plugin. */
3588
+ const NS = "token-usage";
3589
+ /** Simplified Chinese dictionary (the key-set source of truth). */
3590
+ const zh = {
3591
+ "nav.label": "Token 用量",
3592
+ "filter.quickRange": "快捷区间",
3593
+ "filter.custom": "自定义",
3594
+ "filter.from": "开始日期",
3595
+ "filter.to": "结束日期",
3596
+ "filter.separator": "至",
3597
+ "filter.model": "模型",
3598
+ "filter.allModels": "全部模型",
3599
+ "stat.requests": "请求数",
3600
+ "stat.totalTokens": "总 token",
3601
+ "stat.hitRate": "命中率",
3602
+ "stat.cost": "费用",
3603
+ "stat.input": "入",
3604
+ "stat.output": "出",
3605
+ "stat.cacheRead": "缓",
3606
+ "stat.cacheWrite": "写",
3607
+ "byModel.title": "按模型",
3608
+ "pricing.title": "模型定价",
3609
+ "pricing.view": "查看 {model} 定价",
3610
+ "pricing.viewShort": "定价",
3611
+ "pricing.close": "关闭",
3612
+ "pricing.condition": "计费条件",
3613
+ "pricing.default": "默认",
3614
+ "pricing.regular": "常规(规则期外)",
3615
+ "pricing.tier": "上下文 ≥{threshold}",
3616
+ "pricing.peak": "峰时",
3617
+ "pricing.input": "入",
3618
+ "pricing.output": "出",
3619
+ "pricing.cacheRead": "缓",
3620
+ "pricing.cacheWrite": "写",
3621
+ "pricing.perMillion": "/M",
3622
+ "pricing.exchangeRateNote": "按 1 USD = {rate} CNY 换算",
3623
+ "pricing.unpriced": "未定价",
3624
+ "pricing.windowSep": "、",
3625
+ "unpriced.warning": "{count} 个模型未定价:{models}(费用按 {zero} 计)",
3626
+ "dataDir": "数据目录:{path}",
3627
+ "card.title": "Token 用量",
3628
+ "card.description": "数据目录与定价数据源",
3629
+ "card.expand": "展开",
3630
+ "card.collapse": "折叠",
3631
+ "card.unsaved": "未保存",
3632
+ "card.readOnly": "设置文档当前为只读,本次无法修改。",
3633
+ "card.pathLabel": "数据目录",
3634
+ "card.pathHint": "留空使用默认位置(~/.dsh/token-usage)。",
3635
+ "card.browse": "浏览…",
3636
+ "card.picking": "选择中…",
3637
+ "card.migratingCopy": "正在复制数据 {done}/{total} 个文件…",
3638
+ "card.migratingClean": "正在清理旧目录 {done}/{total} 个文件…",
3639
+ "card.regionLabel": "定价区域",
3640
+ "card.regionDefault": "默认(国内 Gitee)",
3641
+ "card.region.domestic": "国内(Gitee)",
3642
+ "card.region.overseas": "全球(GitHub)",
3643
+ "card.hint": "切换到「全球」后从 GitHub 镜像拉取定价表,费用按美元展示(RMB ÷ 汇率);保存后立即重新同步,失败沿用旧镜像。",
3644
+ "card.overridden": "已覆盖默认值",
3645
+ "card.save": "保存",
3646
+ "card.saving": "保存中…",
3647
+ "card.saveFailed": "保存未生效,请重试。",
3648
+ "card.saveBlockedSessions": "有会话正在进行对话,无法保存目录修改;请等待对话结束(当前 {count} 个)。",
3649
+ "card.discard": "放弃",
3650
+ "card.fullSync.title": "全量扫描同步",
3651
+ "card.fullSync.hint": "手动扫一遍所有 session 日志,把可能漏掉的历史请求补进来(已记录的会跳过)。",
3652
+ "card.fullSync.button": "开始扫描",
3653
+ "card.fullSync.running": "扫描中…",
3654
+ "card.fullSync.progress": "已处理 {processed}/{total} 个 session,新增 {added} 条,跳过 {skipped} 条",
3655
+ "card.fullSync.done": "扫描完成:新增 {added} 条,跳过 {skipped} 条",
3656
+ "card.fullSync.failed": "扫描失败:{error}",
3657
+ "loadFailed": "统计加载失败:{message}",
3658
+ "empty": "暂无数据。可调整筛选条件;模型请求成功后会自动写入,安装前已发生的历史记录会在首次启动时自动补齐。",
3659
+ "chart.empty": "区间内暂无数据",
3660
+ "chart.aria": "每日总 token 曲线",
3661
+ "chart.ariaHour": "单日分时 token 曲线",
3662
+ "chart.ariaRequests": "按时间分段的 token 曲线",
3663
+ "chart.pointLabel": "{day} 总量 {tokens}",
3664
+ "chart.bucket": "{window} · {count} 请求 · {tokens}",
3665
+ "view.usage": "用量",
3666
+ "view.scope.label": "统计范围",
3667
+ "view.scope.session": "本会话",
3668
+ "view.scope.tree": "含子会话",
3669
+ "view.back": "← 返回 {title}",
3670
+ "view.ttft": "平均首token",
3671
+ "view.speed": "token速度",
3672
+ "view.empty": "该会话暂无用量记录。",
3673
+ "view.chart.title": "趋势",
3674
+ "view.subagents.title": "子会话({count})",
3675
+ "view.subagents.none": "无子会话",
3676
+ "view.subagents.titleCol": "会话",
3677
+ "view.subagents.nested": "含 {count} 个子会话",
3678
+ "view.note": "注:token 与费用来自本插件的请求记录(安装后);平均首token 与 token速度来自 DSH 会话投影(含安装前历史)。",
3679
+ "chip.tokens": "含子会话 token 用量 {value}",
3680
+ "chip.hitRate": "含子会话缓存命中率 {value}",
3681
+ "chip.cost": "含子会话费用 {value}",
3682
+ "quota.trigger": "供应商配额",
3683
+ "quota.triggerSummary": "{name} · {figure}",
3684
+ "quota.panel": "供应商配额面板",
3685
+ "quota.tier.fiveHour": "5 小时",
3686
+ "quota.tier.weekly": "每周",
3687
+ "quota.tier.monthly": "每月",
3688
+ "quota.tier.balance": "余额",
3689
+ "quota.resetIn": "{time} 后重置",
3690
+ "quota.updatedAt": "更新于 {time}",
3691
+ "quota.retry": "重试",
3692
+ "quota.error.auth": "鉴权失败({message});请检查该供应商的 API Key。",
3693
+ "quota.error.noCredential": "未解析到 API Key({ref});请先在供应商设置中配置密钥。",
3694
+ "quota.error.http": "供应商接口返回错误({message})。",
3695
+ "quota.error.network": "网络错误({message})。",
3696
+ "quota.error.parse": "响应解析失败({message})。"
3697
+ };
3698
+ /** English dictionary (same key set). */
3699
+ const en = {
3700
+ "nav.label": "Token Usage",
3701
+ "filter.quickRange": "Quick range",
3702
+ "filter.custom": "Custom",
3703
+ "filter.from": "Start date",
3704
+ "filter.to": "End date",
3705
+ "filter.separator": "to",
3706
+ "filter.model": "Model",
3707
+ "filter.allModels": "All models",
3708
+ "stat.requests": "Requests",
3709
+ "stat.totalTokens": "Total",
3710
+ "stat.hitRate": "Hit %",
3711
+ "stat.cost": "Cost",
3712
+ "stat.input": "In",
3713
+ "stat.output": "Out",
3714
+ "stat.cacheRead": "Cache",
3715
+ "stat.cacheWrite": "Write",
3716
+ "byModel.title": "By model",
3717
+ "pricing.title": "Model pricing",
3718
+ "pricing.view": "View rates for {model}",
3719
+ "pricing.viewShort": "Rates",
3720
+ "pricing.close": "Close",
3721
+ "pricing.condition": "Condition",
3722
+ "pricing.default": "Default",
3723
+ "pricing.regular": "Regular (outside rule windows)",
3724
+ "pricing.tier": "context ≥{threshold}",
3725
+ "pricing.peak": "Peak",
3726
+ "pricing.input": "In",
3727
+ "pricing.output": "Out",
3728
+ "pricing.cacheRead": "Cache",
3729
+ "pricing.cacheWrite": "Write",
3730
+ "pricing.perMillion": "/M",
3731
+ "pricing.exchangeRateNote": "Converted at 1 USD = {rate} CNY",
3732
+ "pricing.unpriced": "Unpriced",
3733
+ "pricing.windowSep": ", ",
3734
+ "unpriced.warning": "{count} models unpriced: {models} (cost counts as {zero})",
3735
+ "dataDir": "Data directory: {path}",
3736
+ "card.title": "Token Usage",
3737
+ "card.description": "Data directory and pricing source",
3738
+ "card.expand": "Expand",
3739
+ "card.collapse": "Collapse",
3740
+ "card.unsaved": "Unsaved",
3741
+ "card.readOnly": "The settings document is read-only right now; changes are disabled.",
3742
+ "card.pathLabel": "Data directory",
3743
+ "card.pathHint": "Leave empty for the default location (~/.dsh/token-usage).",
3744
+ "card.browse": "Browse…",
3745
+ "card.picking": "Picking…",
3746
+ "card.migratingCopy": "Copying data {done}/{total} files…",
3747
+ "card.migratingClean": "Cleaning the old directory {done}/{total} files…",
3748
+ "card.regionLabel": "Pricing region",
3749
+ "card.regionDefault": "Default (Gitee)",
3750
+ "card.region.domestic": "CN (Gitee)",
3751
+ "card.region.overseas": "Global (GitHub)",
3752
+ "card.hint": "Switching to Global pulls the pricing table from the GitHub mirror and shows costs in USD (RMB ÷ rate); saving re-syncs immediately, falling back to the previous mirror on failure.",
3753
+ "card.overridden": "Overriding the default",
3754
+ "card.save": "Save",
3755
+ "card.saving": "Saving…",
3756
+ "card.saveFailed": "The save did not land; try again.",
3757
+ "card.saveBlockedSessions": "A conversation is still in progress, so the directory change was not saved; wait for it to end first ({count} active).",
3758
+ "card.discard": "Discard",
3759
+ "card.fullSync.title": "Full scan sync",
3760
+ "card.fullSync.hint": "Walk every session log once and fold any historical requests the log does not yet hold (rows already recorded are skipped).",
3761
+ "card.fullSync.button": "Start scan",
3762
+ "card.fullSync.running": "Scanning…",
3763
+ "card.fullSync.progress": "Processed {processed}/{total} sessions, added {added}, skipped {skipped}",
3764
+ "card.fullSync.done": "Scan complete: added {added}, skipped {skipped}",
3765
+ "card.fullSync.failed": "Scan failed: {error}",
3766
+ "loadFailed": "Failed to load stats: {message}",
3767
+ "empty": "No data yet. Adjust the filters; requests are written automatically after each successful model call, and pre-install history is backfilled automatically on the first startup.",
3768
+ "chart.empty": "No data in range",
3769
+ "chart.aria": "Daily total token trend",
3770
+ "chart.ariaHour": "Single-day hourly token trend",
3771
+ "chart.ariaRequests": "Time-bucketed token trend",
3772
+ "chart.pointLabel": "{day} total {tokens}",
3773
+ "chart.bucket": "{window} · {count} requests · {tokens}",
3774
+ "view.usage": "Usage",
3775
+ "view.scope.label": "Scope",
3776
+ "view.scope.session": "Session",
3777
+ "view.scope.tree": "With subagents",
3778
+ "view.back": "← Back to {title}",
3779
+ "view.ttft": "Avg TTFT",
3780
+ "view.speed": "Token speed",
3781
+ "view.empty": "No usage recorded for this session.",
3782
+ "view.chart.title": "Trend",
3783
+ "view.subagents.title": "Subagents ({count})",
3784
+ "view.subagents.none": "No subagents",
3785
+ "view.subagents.titleCol": "Session",
3786
+ "view.subagents.nested": "With {count} subagents",
3787
+ "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).",
3788
+ "chip.tokens": "Tokens with subagents {value}",
3789
+ "chip.hitRate": "Cache hit rate with subagents {value}",
3790
+ "chip.cost": "Cost with subagents {value}",
3791
+ "quota.trigger": "Provider quota",
3792
+ "quota.triggerSummary": "{name} · {figure}",
3793
+ "quota.panel": "Provider quota panel",
3794
+ "quota.tier.fiveHour": "5-hour",
3795
+ "quota.tier.weekly": "Weekly",
3796
+ "quota.tier.monthly": "Monthly",
3797
+ "quota.tier.balance": "Balance",
3798
+ "quota.resetIn": "resets in {time}",
3799
+ "quota.updatedAt": "Updated {time}",
3800
+ "quota.retry": "Retry",
3801
+ "quota.error.auth": "Authentication failed ({message}); check this provider's API key.",
3802
+ "quota.error.noCredential": "No API key resolved ({ref}); configure the provider's key first.",
3803
+ "quota.error.http": "The provider endpoint returned an error ({message}).",
3804
+ "quota.error.network": "Network error ({message}).",
3805
+ "quota.error.parse": "Failed to parse the response ({message})."
3806
+ };
3807
+ //#endregion
3808
+ //#region src/client/index.ts
3809
+ /**
3810
+ * Namespace of the token-usage settings section. Spelled here rather than
3811
+ * imported: a client package must not depend on a Host package.
3812
+ */
3813
+ const TOKEN_USAGE_NS = "token-usage";
3814
+ /** Required services: the slot registry, the locale dictionaries, the
3815
+ * settings scope, and the workspace service (its native directory picker
3816
+ * backs the card's browse button). */
3817
+ const inject = [
3818
+ "slots",
3819
+ "locale",
3820
+ "connection",
3821
+ "remote",
3822
+ "settingsScope",
3823
+ "workspaces"
3824
+ ];
3825
+ /**
3826
+ * Register the dictionary pair, then the settings page and the plugin
3827
+ * configuration card once the shell's declarations are on the ledger.
3828
+ * @param ctx - client root context.
3829
+ */
3830
+ function apply(ctx) {
3831
+ ctx.effect(() => ctx.locale.register(NS, {
3832
+ zh,
3833
+ en
3834
+ }), "token-usage: dictionaries");
3835
+ const t = ctx.locale.bind(NS);
3836
+ ctx.slots.inject("settings.section", () => ctx.slots.register({
3837
+ name: "settings.section",
3838
+ id: "token-usage",
3839
+ order: 50,
3840
+ label: () => t("nav.label"),
3841
+ locale: NS
3842
+ }, TokenUsageSection));
3843
+ ctx.slots.inject("conversation.view", () => ctx.slots.register({
3844
+ name: "conversation.view",
3845
+ id: "usage",
3846
+ order: 20,
3847
+ label: () => t("view.usage"),
3848
+ locale: NS
3849
+ }, UsageView));
3850
+ ctx.slots.inject("conversation.session.header.utilities", () => ctx.slots.register({
3851
+ name: "conversation.session.header.utilities",
3852
+ id: "session-stats",
3853
+ order: -10,
3854
+ locale: NS
3855
+ }, SessionStatsChip));
3856
+ const modelDirectory = { service: void 0 };
3857
+ ctx.inject(["modelDirectories"], (modelCtx) => {
3858
+ modelCtx.effect(() => {
3859
+ modelDirectory.service = modelCtx.modelDirectories;
3860
+ return () => {
3861
+ modelDirectory.service = void 0;
3862
+ };
3863
+ }, "token-usage: model directory seam");
3864
+ });
3865
+ ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
3866
+ name: "conversation.input.right",
3867
+ id: "token-usage-quota",
3868
+ order: 10,
3869
+ locale: NS,
3870
+ inject: () => ({ modelDirectory })
3871
+ }, QuotaButton));
3872
+ const form = new CardForm(ctx.settingsScope.bind({ namespace: TOKEN_USAGE_NS }));
3873
+ const store = form.bind();
3874
+ ctx.slots.inject("settings.plugin.item", () => ctx.slots.register({
3875
+ name: "settings.plugin.item",
3876
+ key: TOKEN_USAGE_NS,
3877
+ locale: NS,
3878
+ inject: () => ({
3879
+ hooks: { tokenUsageCard: store },
3880
+ ...form.actions(),
3881
+ pickDirectory: () => ctx.workspaces.pickDirectory()
3882
+ })
3883
+ }, TokenUsageCard));
3884
+ }
3885
+ //#endregion
3886
+ exports.apply = apply;
3887
+ exports.inject = inject;
3888
+ return module.exports;
3889
+ }
3890
+ });
3891
+
3892
+ //# sourceMappingURL=client.js.map