@ds-hu/dsh-token-quota 0.0.0-stage → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/CONTEXT.md +179 -0
  3. package/README.md +270 -2
  4. package/cordis.patch.yml +10 -0
  5. package/docs/windows-desktop-adaptation.md +80 -0
  6. package/icon.svg +21 -0
  7. package/lib/client.js +2371 -0
  8. package/lib/detect.js +448 -0
  9. package/lib/index.js +1161 -0
  10. package/lib/legacy-config.js +129 -0
  11. package/lib/providers.js +1203 -0
  12. package/lib/quota-history.js +303 -0
  13. package/lib/routes.js +13 -0
  14. package/lib/scan-coordinator.js +227 -0
  15. package/lib/scheduler.js +86 -0
  16. package/lib/season.js +271 -0
  17. package/lib/storage.js +453 -0
  18. package/lib/usage.js +87 -0
  19. package/locale/en.json +6 -0
  20. package/locale/zh.json +6 -0
  21. package/package.json +73 -4
  22. package/playwright.config.mjs +6 -0
  23. package/scripts/benchmark-runtime.mjs +227 -0
  24. package/scripts/benchmark-storage.mjs +104 -0
  25. package/scripts/check-package.mjs +46 -0
  26. package/scripts/verify-desktop.mjs +200 -0
  27. package/scripts/verify-lifecycle.cjs +75 -0
  28. package/scripts/verify-web.mjs +170 -0
  29. package/test/browser/edit-identity.spec.mjs +343 -0
  30. package/test/browser/interactions.spec.mjs +690 -0
  31. package/test/browser/server.mjs +123 -0
  32. package/test/browser/shell.html +33 -0
  33. package/test/client-lifecycle.mjs +515 -0
  34. package/test/client.mjs +878 -0
  35. package/test/copy.mjs +47 -0
  36. package/test/css.mjs +63 -0
  37. package/test/desktop-services.mjs +91 -0
  38. package/test/detect.mjs +164 -0
  39. package/test/draft-config.mjs +38 -0
  40. package/test/harness.mjs +136 -0
  41. package/test/legacy-config.mjs +106 -0
  42. package/test/lifecycle.mjs +81 -0
  43. package/test/migration.mjs +127 -0
  44. package/test/mock-dsh.mjs +399 -0
  45. package/test/package-meta.mjs +49 -0
  46. package/test/pagination.mjs +21 -0
  47. package/test/provider-contracts.mjs +145 -0
  48. package/test/quota-history.mjs +191 -0
  49. package/test/reset-times.mjs +68 -0
  50. package/test/route-consistency.mjs +45 -0
  51. package/test/runtime.mjs +389 -0
  52. package/test/scan-coordinator.mjs +353 -0
  53. package/test/scheduler.mjs +98 -0
  54. package/test/season.mjs +173 -0
  55. package/test/smoke.mjs +264 -0
  56. package/test/storage-recovery.mjs +81 -0
  57. package/test/storage.mjs +377 -0
  58. package/test/usage-saves.mjs +107 -0
  59. package/test/usage.mjs +119 -0
  60. package/ui-prototype.html +509 -0
package/lib/client.js ADDED
@@ -0,0 +1,2371 @@
1
+ // DSH Web / Windows Desktop 共用客户端。官方槽位、无构建 React 加载。
2
+ // 展示控制器统一请求与会话订阅;面板草稿独立于展示缓存与本地偏好。
3
+ (function () {
4
+ window.__ModuleLoader__.load({
5
+ id: "dsh-token-quota",
6
+ factory: (require) => {
7
+ var module = { exports: {} };
8
+ var exports = module.exports;
9
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
10
+
11
+ const React = require("react");
12
+ const { createPortal } = require("react-dom");
13
+ const h = React.createElement;
14
+
15
+ const NS = "dsh-token-quota";
16
+ const API = "/api/dsh-token-quota";
17
+ // 按会话页缓存最近一次 /state:切回某页时先显示缓存再后台刷新(切页实时,不闪「暂无调用」)
18
+ const STATE_CACHE_LIMIT = 20;
19
+ const stateCache = new Map(); // sessionKey -> payload
20
+ // 当前「显示页」= Session Controller 的 sessions.list.current;apply 时装配订阅源,
21
+ // 由 FooterSlotWithSession(useSyncExternalStore)消费,切页即时重渲。
22
+ let sessionListSource = null;
23
+
24
+ // 0.2 的会话目录不再保存 current;主视图通过 mainView 引用标记所选会话。
25
+ // 只读宿主的公开快照,不为监控额外 retain 会话,也不把后台运行页当成当前页。
26
+ const selectedSessionId = (snapshot) => {
27
+ if (snapshot && Object.prototype.hasOwnProperty.call(snapshot, "current")) {
28
+ return typeof snapshot.current === "string" ? snapshot.current : "";
29
+ }
30
+ const main = Object.values(snapshot?.byId || {}).filter((session) =>
31
+ typeof session?.id === "string" && session.retainedBy?.mainView > 0);
32
+ // 导航过渡期间若有多个主视图引用,先显示空页,避免短暂串到其它会话。
33
+ return main.length === 1 ? main[0].id : "";
34
+ };
35
+
36
+ // ---------- 工具 ----------
37
+ // Token 量级一律 3 位有效数字(1.32M / 64.4M / 193M / 12.0K),而不是「固定 1 位小数」:
38
+ // 后者让 1.3M 只报 2 位有效数字,小量级的精度被静默丢掉。尾零保留,1.00M 仍是 3 位。
39
+ // < 1000 直接给整数:token 计数没有小数意义,补成 12.0 只是假精度。
40
+ const BIG_UNITS = [[1e12, "T"], [1e9, "B"], [1e6, "M"], [1e3, "K"]];
41
+ /** 缩放后数值的整数位数(1.32 → 1,64.4 → 2,193 → 3),用于补足 3 位有效数字。 */
42
+ const digitsOf = (scaled) => Math.min(3, Math.max(1, Math.floor(Math.log10(Math.abs(scaled))) + 1));
43
+ const fmtBig = (n) => {
44
+ if (n === null || n === undefined) return "—";
45
+ const v = Number(n);
46
+ if (!Number.isFinite(v)) return "—";
47
+ const abs = Math.abs(v);
48
+ if (abs < 1000) return String(Math.round(v));
49
+ let index = BIG_UNITS.findIndex(([scale]) => abs >= scale);
50
+ if (index < 0) index = BIG_UNITS.length - 1;
51
+ // 进位后仍要 3 位有效数字:999.6K 属于 M 量级,不是 1000K。
52
+ if (index > 0 && abs / BIG_UNITS[index][0] >= 999.5) index -= 1;
53
+ const [scale, suffix] = BIG_UNITS[index];
54
+ const scaled = v / scale;
55
+ return `${scaled.toFixed(3 - digitsOf(scaled))}${suffix}`;
56
+ };
57
+ // 阈值判定(A3 统一口径):详情卡、供应商状态药丸、设置页预览与 stateToken 共用这一个纯函数。
58
+ // 默认 80/95;无值/未知值/NaN 一律归为 unknown,绝不折成正常的 0%。
59
+ const WARN_PCT_DEFAULT = 80;
60
+ const CRIT_PCT_DEFAULT = 95;
61
+ const classifyPct = (pct, { warnPct, critPct } = {}) => {
62
+ const value = pct === null || pct === undefined || pct === "" ? NaN : Number(pct);
63
+ if (!Number.isFinite(value)) return "unknown";
64
+ const warn = Number.isFinite(Number(warnPct)) ? Number(warnPct) : WARN_PCT_DEFAULT;
65
+ const crit = Number.isFinite(Number(critPct)) ? Number(critPct) : CRIT_PCT_DEFAULT;
66
+ return value >= crit ? "crit" : value >= warn ? "warn" : "ok";
67
+ };
68
+ const stateClass = (s) => s?.state || "off";
69
+ const stateToken = (s) => {
70
+ if (!s) return "stateOff";
71
+ if (s.state === "err") return "stateErr";
72
+ if (s.state === "off") return "stateOff";
73
+ const pct = Math.max(...(s.entries || []).map((x) => x.pct).filter(Number.isFinite));
74
+ if (Number.isFinite(pct)) {
75
+ const cls = classifyPct(pct, { warnPct: s.warnPct, critPct: s.critPct });
76
+ if (cls === "crit") return "stateCrit";
77
+ if (cls === "warn") return "stateWarn";
78
+ }
79
+ return "stateOk";
80
+ };
81
+ const pctText = (v) => {
82
+ if (v === null || v === undefined) return "—";
83
+ const s = String(v);
84
+ return s.includes("%") ? s : `${s}%`;
85
+ };
86
+ const displayValue = (value) => value === null || value === undefined || value === "" ? "—" : String(value);
87
+ const buildEntryView = (entry, supplier = {}, tr = (key) => key) => {
88
+ const quota = Number.isFinite(entry.pct) || entry.kind === "win";
89
+ const kind = quota ? "quota" : entry.kind === "bal" ? "balance" : entry.kind === "cost" ? "cost" : "usage";
90
+ const status = classifyPct(entry.pct, supplier);
91
+ return { kind, label: tr(kind), name: entry.name || tr(kind),
92
+ value: Number.isFinite(entry.pct) ? pctText(entry.pct) : displayValue(kind === "balance" ? entry.remain : entry.used),
93
+ reset: resetTextOf(entry, null, tr), note: (entry.note || "")
94
+ .replace("官方插件字段;不推断周窗口或重置时间", tr("resetUnavailable"))
95
+ .replace("公开契约允许无限额度", tr("unlimited"))
96
+ .replace("(报告美分按 1/100 转为美元)", "")
97
+ .replace("管理密钥 · total_credits − total_usage", tr("accountBalance")),
98
+ tone: supplier.state === "err" || supplier.enabled === false || status === "unknown" ? "neutral" : status,
99
+ warning: supplier.state !== "err" && supplier.enabled !== false && ["warn", "crit"].includes(status) ? tr(status === "crit" ? "stateCrit" : "stateWarn") : null };
100
+ };
101
+ const selectPrimaryMetric = (supplier, tr = (key) => key) => {
102
+ const entries = supplier?.entries || [];
103
+ const entry = tightestOf(entries) || entries.find(e => e.kind === "bal") || entries.find(e => e.kind === "cost") || entries[0];
104
+ if (!entry) return { kind: "unknown", value: "—", label: "", name: "", reset: null, tone: "neutral", more: 0, text: "—" };
105
+ const view = buildEntryView(entry, supplier, tr);
106
+ const more = view.kind === "balance" ? entries.filter(e => e.kind === "bal").length - 1 : 0;
107
+ return { ...view, more, text: [view.name, view.kind === "quota" ? tr("usedShort") : view.label, view.value,
108
+ more > 0 ? tr("moreMetrics", { n: more }) : null,
109
+ ["cost", "usage"].includes(view.kind) ? view.note : null].filter(Boolean).join(" · ") };
110
+ };
111
+ // 概览明细与编辑页预览共用的指标行:额度按「已用/限额/重置」列,余额与报告按各自列。
112
+ // 只在这里决定分组与列语义;渲染层不再为每种条目写一套卡片。
113
+ const METRIC_COLUMNS = {
114
+ quota: [{ key: "used", labelKey: "usedShort" }, { key: "limit", labelKey: "colLimit" }, { key: "reset", labelKey: "colReset" }],
115
+ balance: [{ key: "value", labelKey: "colValue" }],
116
+ cost: [{ key: "value", labelKey: "colValue" }, { key: "period", labelKey: "colPeriod" }],
117
+ usage: [{ key: "value", labelKey: "colValue" }, { key: "period", labelKey: "colPeriod" }],
118
+ };
119
+ const METRIC_TITLES = { quota: "quota", balance: "balance", cost: "cost", usage: "usage" };
120
+ const metricRowsOf = (supplier, tr = (key) => key) => {
121
+ const groups = new Map();
122
+ for (const entry of supplier?.entries || []) {
123
+ const view = buildEntryView(entry, supplier, tr);
124
+ if (!groups.has(view.kind)) groups.set(view.kind, []);
125
+ const row = { key: entry.key || `${view.kind}-${groups.get(view.kind).length}`, name: view.name, tone: view.tone,
126
+ aria: `${view.name} ${view.value}${view.warning ? ` ${view.warning}` : ""}` };
127
+ if (view.kind === "quota") { row.used = view.value; row.limit = displayValue(entry.limit); row.reset = view.reset || "—"; }
128
+ else if (view.kind === "balance") { row.value = view.value; }
129
+ else { row.value = view.value; row.period = entry.note || view.reset || "—"; }
130
+ groups.get(view.kind).push(row);
131
+ }
132
+ return [...groups].map(([kind, rows]) => ({
133
+ kind, titleKey: METRIC_TITLES[kind],
134
+ columns: [{ key: "name", labelKey: "colMetric" }, ...METRIC_COLUMNS[kind]], rows,
135
+ }));
136
+ };
137
+ const supplierStatus = (s, tr) => s?.state === "err"
138
+ ? tr(s.entries?.length ? "staleFailure" : "unavailable")
139
+ : s?.enabled === false ? tr("disabled") : !s?.entries?.length ? tr("notQueried") : tr(stateToken(s));
140
+ const todayTotal = (state) => (state?.suppliers || []).filter(s => s.current)
141
+ .reduce((sum, s) => sum + (typeof s.todayTokens === "number" ? s.todayTokens : 0), 0);
142
+
143
+ // ---------- 今日 Token 分布(数据来自宿主 todayUsage / usageDays,五分量互不相交) ----------
144
+ // label 是 i18n key,cls 是分布条/图例的配色类。前 3 项(命中/未命中/输出)构成归一比例,
145
+ // 详情里的分布条取全部五分量 —— 比例口径与用户读数保持三段。
146
+ const USAGE_PARTS = [
147
+ { key: "cacheReadTokens", label: "cacheHit", cls: "hit" },
148
+ { key: "inputTokens", label: "cacheMiss", cls: "miss" },
149
+ { key: "outputTokens", label: "outputLabel", cls: "out" },
150
+ { key: "cacheWriteTokens", label: "cacheWrite", cls: "write" },
151
+ { key: "unsplitTokens", label: "unsplit", cls: "unsplit" },
152
+ ];
153
+ const num0 = (value) => Math.max(0, Number(value) || 0);
154
+ /** 完整五分量(含写缓存、未细分),零分量剔除;详情里的当日分布条与图例用。 */
155
+ const splitPartsOf = (usage) => USAGE_PARTS
156
+ .map((part) => ({ ...part, value: num0(usage?.[part.key]) })).filter((part) => part.value > 0);
157
+ /**
158
+ * 比例数字:一律 3 位有效数字(30.0 / 1.00 / 0.150),与卡片量级同一口径 ——
159
+ * 比例两侧的量级常常差两个数量级,位数不统一就没法竖着比。
160
+ * 小数最多 4 位;再小就显式给 <0.0001,绝不四舍五入成 0 冒充「没有用量」。
161
+ */
162
+ const fmtRatioPart = (x) => {
163
+ if (!(x > 0)) return "0.00";
164
+ const decimals = Math.min(4, Math.max(0, 2 - Math.floor(Math.log10(x))));
165
+ const text = x.toFixed(decimals);
166
+ return Number(text) === 0 ? "<0.0001" : text;
167
+ };
168
+ /**
169
+ * 命中 : 未命中 : 输出,归一到未命中 = 1(例:30.0 : 1.00 : 0.150)。
170
+ * 未命中为 0 时改按三分量中的最大者归一(避免除零);三分量全 0 返回 null —— 没有用量就不编比例。
171
+ * unsplitTokens(旧版合并数据)不进比例:它没有分量信息,硬塞进任何一段都会撒谎。
172
+ */
173
+ const usageRatioOf = (usage) => {
174
+ const hit = num0(usage?.cacheReadTokens), miss = num0(usage?.inputTokens), out = num0(usage?.outputTokens);
175
+ const base = miss > 0 ? miss : Math.max(hit, out);
176
+ if (base <= 0) return null;
177
+ const parts = { hit: fmtRatioPart(hit / base), miss: fmtRatioPart(miss / base), out: fmtRatioPart(out / base) };
178
+ return { ...parts, text: `${parts.hit} : ${parts.miss} : ${parts.out}`, hitValue: hit, missValue: miss, outValue: out };
179
+ };
180
+ /** 跨多行(usageDays)求和成一份五分量;统计页的窗口合计与窗口比例用。 */
181
+ const sumUsageOf = (rows) => (rows || []).reduce((acc, row) => {
182
+ for (const part of USAGE_PARTS) acc[part.key] = num0(acc[part.key]) + num0(row?.[part.key]);
183
+ return acc;
184
+ }, {});
185
+
186
+ // ---------- 统计图:token 柱 + 剩余额度折线(同一张图、同一时间轴) ----------
187
+ /** 折线配色:按指标顺序取色,与 token 分量的配色区分开(分量只出现在上方的分布条里)。 */
188
+ const LINE_COLORS = ["#fbbf24", "#22d3ee", "#a78bfa", "#f472b6", "#4ade80"];
189
+ /** "YYYY-MM-DD" → 本地当日 00:00 的 epoch-毫秒;格式不对返回 NaN。 */
190
+ const dayStartOf = (label) => {
191
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(label || ""));
192
+ if (!match) return NaN;
193
+ return new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])).getTime();
194
+ };
195
+ /**
196
+ * 图表时间轴:左缘取第一天 00:00,右缘取「今天结束」与 now 的较大值钳到明天 00:00。
197
+ * 用自然日边界而不是首末采样点:柱是整天一格,线必须落在同一把尺子上。
198
+ */
199
+ const chartDomainOf = (days, now = Date.now()) => {
200
+ const starts = (days || []).map((day) => dayStartOf(day?.day)).filter(Number.isFinite).sort((a, b) => a - b);
201
+ if (!starts.length) return null;
202
+ const start = starts[0];
203
+ const lastStart = starts[starts.length - 1] + 24 * 3600_000;
204
+ const end = Math.max(start + 3600_000, Math.min(now, lastStart));
205
+ return { start, end };
206
+ };
207
+ /**
208
+ * 把 [[t, pct], ...] 拆成若干连续段:pct 下降即换了新窗口(额度在窗口内只增不减),
209
+ * 段与段之间不连线,锯齿才画得出来。样本按升序传入。
210
+ */
211
+ const quotaSegmentsOf = (samples) => {
212
+ const segments = [];
213
+ let current = null;
214
+ let previous = null;
215
+ for (const point of samples || []) {
216
+ if (!Array.isArray(point) || point.length < 2) continue;
217
+ const t = Number(point[0]), pct = Number(point[1]);
218
+ if (!Number.isFinite(t) || !Number.isFinite(pct)) continue;
219
+ if (previous !== null && pct < previous) current = null; // 新窗口:断开
220
+ if (!current) { current = []; segments.push(current); }
221
+ current.push([t, pct]);
222
+ previous = pct;
223
+ }
224
+ // 单点段没有形状,但它是新窗口的起点:保留下来,由渲染层画成圆点
225
+ return segments;
226
+ };
227
+ /** 图例条目:指标名 + 当前剩余百分比(100 − 已用)。没有样本的指标不出现。 */
228
+ const quotaLegendOf = (quota, entries, tr) => (Object.entries(quota || {})).map(([key, samples], index) => {
229
+ const known = (entries || []).find((entry) => entry?.key === key);
230
+ const valid = (samples || []).filter((point) => Array.isArray(point) && Number.isFinite(Number(point[1])));
231
+ if (!valid.length) return null;
232
+ const lastPct = Math.max(0, Math.min(100, Number(valid[valid.length - 1][1])));
233
+ return {
234
+ key,
235
+ label: known?.short || known?.name || key,
236
+ color: LINE_COLORS[index % LINE_COLORS.length],
237
+ remaining: Math.round(100 - lastPct),
238
+ samples: valid,
239
+ segments: quotaSegmentsOf(valid),
240
+ };
241
+ }).filter(Boolean);
242
+ /**
243
+ * 某个时刻的已用百分比:取最近一次采样(样本只在变化时落盘,「保持到下一次变化」就是真实语义)。
244
+ * 不做时间插值 —— 那会造出从未采样到的数字。
245
+ */
246
+ const quotaUsedAt = (samples, at) => {
247
+ let used = null;
248
+ for (const point of samples || []) {
249
+ const time = Number(point?.[0]);
250
+ if (Number.isFinite(time) && time <= at) used = Number(point[1]);
251
+ }
252
+ return Number.isFinite(used) ? used : null;
253
+ };
254
+ /** 悬停读数里的时刻:MM-DD HH:mm。分钟够用,秒对判断窗口没有意义。 */
255
+ const clockOf = (ms) => {
256
+ const date = new Date(ms);
257
+ const pad = (n) => String(n).padStart(2, "0");
258
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
259
+ };
260
+
261
+ // 已用比例最高的窗口及其重置时刻必须对应;不借用另一条 headline 的时刻。
262
+ const tightestOf = (entries) => {
263
+ let best = null;
264
+ for (const e of entries || []) {
265
+ if (!Number.isFinite(e?.pct)) continue;
266
+ if (!best || e.pct > best.pct) best = e;
267
+ }
268
+ return best;
269
+ };
270
+ // 周窗口:名称含「周」且确实给了百分比的窗口项。窗口标签是 lib/providers.js 生成的中文常量
271
+ // (Token 用量(周)/ 周用量 / 周窗口 · GOAT / 周期额度 · 每周重置),不是客户端拼的文案。
272
+ // 绝不按数组位置猜窗口:认不出来就返回 null,由调用方回落到「最紧的有效窗口」。
273
+ const WEEK_LABEL = /周/;
274
+ const weeklyEntryOf = (entries) => {
275
+ const weeks = (entries || []).filter((e) => e?.kind === "win" && Number.isFinite(e?.pct) && WEEK_LABEL.test(String(e?.name || "")));
276
+ return weeks.length ? tightestOf(weeks) : null;
277
+ };
278
+ /**
279
+ * 常驻卡片进度条的指标(可多条):
280
+ * 1. 用户配置的关注限额(`displayKeys`,保持配置顺序),只认当前真有百分比、且 key 对得上的条目;
281
+ * 2. 交集为空 → 默认规则:周窗口优先,其次最紧的有效窗口;
282
+ * 3. 两者都没有(纯余额/报告费用)→ 空数组,调用方回落成文字,绝不画一条 0% 的假进度条。
283
+ * 颜色按供应商自己的阈值分档;旧数据(state=err)与已停用一律中性,不冒充新的告警状态。
284
+ */
285
+ const selectBarMetrics = (supplier, tr = (key) => key) => {
286
+ const entries = supplier?.entries || [];
287
+ const stale = supplier?.state === "err" || supplier?.enabled === false;
288
+ const toBar = (entry, opts = {}) => ({
289
+ entry,
290
+ weekly: entry.kind === "win" && WEEK_LABEL.test(String(entry.name || "")),
291
+ label: opts.defaultLabel || entry.short || entry.name || "",
292
+ tone: stale ? "neutral" : classifyPct(entry.pct, supplier),
293
+ reset: resetTextOf(entry, null, tr, true),
294
+ });
295
+ const barKeys = Array.isArray(supplier?.displayKeys) ? supplier.displayKeys : [];
296
+ if (barKeys.length) {
297
+ const byKey = new Map(entries.filter((e) => e?.key && Number.isFinite(e?.pct)).map((e) => [e.key, e]));
298
+ const watched = barKeys.map((key) => byKey.get(key)).filter(Boolean);
299
+ if (watched.length) return watched.map((entry) => toBar(entry));
300
+ }
301
+ const weekly = weeklyEntryOf(entries);
302
+ const entry = weekly || tightestOf(entries);
303
+ if (!entry) return [];
304
+ return [toBar(entry, weekly ? { defaultLabel: tr("weekTag") } : {})];
305
+ };
306
+ /** 合法重置时刻的下界:epoch-毫秒。低于此值视为「未提供重置时刻」的占位。 */
307
+ const MIN_RESET_EPOCH_MS = 1e12;
308
+
309
+ // 重置倒计时:宿主若给了原始时刻(entry.resetAt / headline.resetAt,epoch-毫秒),
310
+ // 由客户端精确算剩余量——< 1 天显示 *h*m,≥ 1 天显示 *d*h。
311
+ // 宿主只给文案(如「约 43 小时后重置」)或没有时刻时不猜:原样回落,绝不推算时刻。
312
+ // naked = 只给时长(卡片条上每条自带,省宽度),不带「后重置」这类叙述词。
313
+ const fmtCountdown = (resetAt, tr, naked = false) => {
314
+ const ms = Number(resetAt);
315
+ // 与数据层一致,只接受 2001-09 之后的 epoch-毫秒时刻(>= 1e12)。
316
+ // 上游偶尔给出 0 / 负值 / 秒级值当作「无重置时刻」的占位(真实样本:
317
+ // Command Code windowLimits 缺失时 resetAt=0)——这类值绝不能拿去算倒计时,
318
+ // 否则会画出「即将重置」这种上游从未说过的结论。
319
+ if (!Number.isFinite(ms) || ms < MIN_RESET_EPOCH_MS) return null;
320
+ const diff = ms - Date.now();
321
+ if (diff <= 0) return tr("resetSoon");
322
+ const totalMin = Math.floor(diff / 60_000);
323
+ const mins = totalMin % 60;
324
+ const hours = Math.floor(totalMin / 60);
325
+ if (hours < 24) return tr(naked ? "resetHM" : "resetInHM", { h: hours, m: String(mins).padStart(2, "0") });
326
+ return tr(naked ? "resetDH" : "resetInDH", { d: Math.floor(hours / 24), h: hours % 24 });
327
+ };
328
+ // 重置时间文本:优先精确倒计时,否则用宿主文案("—" 视为缺失)
329
+ const resetTextOf = (entry, headline, tr, naked = false) => {
330
+ const countdown = fmtCountdown(entry ? entry.resetAt : headline?.resetAt, tr, naked);
331
+ if (countdown) return countdown;
332
+ const raw = (entry?.reset && entry.reset !== "—" ? entry.reset : null)
333
+ || (!entry && headline?.reset && headline.reset !== "—" ? headline.reset : null);
334
+ return raw || null;
335
+ };
336
+ // 小组件第 1 行的连接状态(票 #9 追加口径)= DSH 事件通道是否活着 × 限额取数健康度:
337
+ // ok 通道已见真实流量事件,且已配置供应商无取数失败
338
+ // warn 通道活着,但有供应商取数失败(降级)
339
+ // err 本次启动后通道尚未见到任何流量事件,且没有任何已配置供应商 → 未连接
340
+ // off 插件已加载、有已配置供应商,但通道还没见到流量 → 待命
341
+ // (别把「插件刚起来/还没发起调用」谎报成「断开」)
342
+ const connStateOf = (state) => {
343
+ const channelAlive = !!state?.traffic?.channelAlive;
344
+ const suppliers = state?.suppliers || [];
345
+ const failed = suppliers.filter((s) => s.enabled && s.added && s.state === "err").length;
346
+ if (!channelAlive && suppliers.length === 0) return { key: "err", cls: "err", failed: 0 };
347
+ if (!channelAlive) return { key: "off", cls: "off", failed: 0 };
348
+ if (failed > 0) return { key: "warn", cls: "warn", failed };
349
+ return { key: "ok", cls: "ok", failed: 0 };
350
+ };
351
+
352
+ // ---------- 峰谷计费时段(只做展示,规则判定在宿主 lib/season.js) ----------
353
+ // 这里刻意不复制峰谷与节假日规则:lib/client.js 是手写无构建文件,无法共享宿主源码,
354
+ // 双份实现只会在官方改规则时漂移。客户端只消费 /state 的 season 结论,并用 flipAt 本地递减。
355
+ const SEASON_MIN_FLIP_MS = 1e12; // 与数据层同口径:低于此值的 flipAt 视为「未提供时刻」的占位
356
+
357
+ /** 距下次切换还剩多久;宿主未给时刻或时刻非法时返回 null(不推算)。 */
358
+ const seasonRemainingMs = (season, now = Date.now()) => {
359
+ const ms = Number(season?.flipAt);
360
+ if (!Number.isFinite(ms) || ms < SEASON_MIN_FLIP_MS) return null;
361
+ return ms - now;
362
+ };
363
+ /** 切换倒计时文案:1 天内 h m,超过 1 天用 d h;宿主没给时刻则为 null。 */
364
+ const seasonCountdown = (season, tr, now = Date.now()) => {
365
+ const diff = seasonRemainingMs(season, now);
366
+ if (diff === null) return null;
367
+ if (diff <= 0) return tr("seasonFlipSoon");
368
+ const totalMin = Math.floor(diff / 60_000);
369
+ if (totalMin < 60) return tr("seasonFlipInM", { m: totalMin });
370
+ const hours = Math.floor(totalMin / 60);
371
+ if (hours < 24) return tr("seasonFlipInHM", { h: hours, m: String(totalMin % 60).padStart(2, "0") });
372
+ return tr("seasonFlipInDH", { d: Math.floor(hours / 24), h: hours % 24 });
373
+ };
374
+ /** 时段档位文案 + 成因标记(节假日/周末只在谷价时成立)。 */
375
+ const seasonLabelOf = (season, tr) => {
376
+ const tier = tr(season?.peak ? "seasonPeak" : "seasonValley");
377
+ const reason = season?.valleyReason === "holiday" ? tr("seasonHoliday")
378
+ : season?.valleyReason === "weekend" ? tr("seasonWeekend") : "";
379
+ return reason ? `${tier}(${reason})` : tier;
380
+ };
381
+ /** 只报档位、不带成因:常驻卡片只需知道「现在是不是谷价」,成因由明细弹窗说明。 */
382
+ const seasonTierOf = (season, tr) => tr(season?.peak ? "seasonPeak" : "seasonValley");
383
+ /** 今日用量按计费时段拆分的展示文案;没有可用数据时返回 null。 */
384
+ const seasonSplitText = (split, tr) => {
385
+ if (!split) return null;
386
+ const peak = Number(split.peakTokens) || 0;
387
+ const valley = Number(split.valleyTokens) || 0;
388
+ const unknown = Number(split.unknownTokens) || 0;
389
+ const total = peak + valley + unknown;
390
+ if (total <= 0) return null;
391
+ const pct = (value) => `${Math.round((value / total) * 100)}%`;
392
+ const parts = [];
393
+ if (peak > 0) parts.push(tr("seasonSplitPeak", { n: fmtBig(peak), pct: pct(peak) }));
394
+ if (valley > 0) parts.push(tr("seasonSplitValley", { n: fmtBig(valley), pct: pct(valley) }));
395
+ // 未知段只在确实存在时出现:它表示早于峰谷定价生效的旧桶,不是「没算出来」
396
+ if (unknown > 0) parts.push(tr("seasonSplitUnknown", { n: fmtBig(unknown) }));
397
+ return parts.join(" · ");
398
+ };
399
+ /** 宿主时区与北京时区是否一致:不一致时界面必须点名「北京时间」,避免把本地白天误读成峰价。 */
400
+ const hostOffsetMinutes = () => {
401
+ try { return -new Date().getTimezoneOffset(); } catch { return 480; }
402
+ };
403
+ const seasonUsesBeijingNote = () => hostOffsetMinutes() !== 480;
404
+
405
+ // 节假日覆盖表在界面上是一个文本框:每行一个日期,也接受逗号/空格/顿号分隔。
406
+ // 保存时归一成数组交给宿主;宿主逐条校验并拒绝非法项,不做静默丢弃。
407
+ const parseHolidayText = (value) => String(value ?? "")
408
+ .split(/[\s,,、;;]+/).map((day) => day.trim()).filter(Boolean).sort();
409
+ const holidaysTextOf = (value) => (Array.isArray(value) ? [...value].sort().join("\n") : parseHolidayText(value).join("\n"));
410
+ // 与宿主 lib/season.js 的 isValidDayKey 同口径:格式对但日期不存在(2027-02-30)也算非法。
411
+ // 前端先拦一道只是为了不白跑一次请求,最终把关仍在宿主。
412
+ const isValidHolidayDay = (value) => {
413
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
414
+ const [y, m, d] = value.split("-").map(Number);
415
+ const parsed = new Date(Date.UTC(y, m - 1, d));
416
+ return parsed.getUTCFullYear() === y && parsed.getUTCMonth() === m - 1 && parsed.getUTCDate() === d;
417
+ };
418
+ const UI_PREF_KEY = "dsh-token-quota.ui.v1";
419
+ let density = "expanded";
420
+ try { if (JSON.parse(window.localStorage.getItem(UI_PREF_KEY))?.sidebarDensity === "compact") density = "compact"; } catch { /* 浏览器禁用存储时使用内存偏好。 */ }
421
+ const preferenceListeners = new Set();
422
+ const preferences = {
423
+ subscribe(fn) { preferenceListeners.add(fn); return () => preferenceListeners.delete(fn); },
424
+ getSnapshot: () => density,
425
+ set(next) {
426
+ density = next === "compact" ? "compact" : "expanded";
427
+ try { window.localStorage.setItem(UI_PREF_KEY, JSON.stringify({ sidebarDensity: density })); } catch { /* 保留当次选择。 */ }
428
+ for (const fn of preferenceListeners) fn();
429
+ },
430
+ };
431
+ const useDensity = () => React.useSyncExternalStore(preferences.subscribe, preferences.getSnapshot, preferences.getSnapshot);
432
+ let displayController;
433
+ // 面板会话只持有未保存草稿与滚动位置,不进入展示缓存或本地存储。
434
+ const createPanelSession = () => ({ globalForm: null, editor: null, editorId: 0, positions: {}, pendingSave: null });
435
+ let panelSession = createPanelSession();
436
+ const settingsWrites = new Set();
437
+
438
+ // ---------- 界面状态 ----------
439
+ // 同一时刻只有一个界面:null(关闭)| dialog(卡片打开)| page(宿主设置内嵌)。
440
+ // tab 与 editing 是它的子状态。旧实现的 popover/detail/stats 三个布尔层已删除:
441
+ // 打开哪个界面不再由调用方拼布尔值,非法组合在状态机里不存在。
442
+ let surfaceSnapshot = { host: null, tab: "overview", editing: null, focus: 0, opening: false };
443
+ const surfaceListeners = new Set();
444
+ const surface = {
445
+ subscribe(fn) { surfaceListeners.add(fn); return () => surfaceListeners.delete(fn); },
446
+ getSnapshot: () => surfaceSnapshot,
447
+ update(patch) { surfaceSnapshot = { ...surfaceSnapshot, ...patch }; for (const fn of surfaceListeners) fn(); },
448
+ bump() { for (const fn of surfaceListeners) fn(); },
449
+ waitForWrites(focus) {
450
+ const pending = [...settingsWrites].map((operation) => operation.promise);
451
+ if (!pending.length && !surfaceSnapshot.opening) return;
452
+ surface.update({ opening: true });
453
+ void Promise.allSettled(pending).then(() => displayController.reload()).finally(() => {
454
+ if (surfaceSnapshot.focus === focus) surface.update({ opening: false });
455
+ });
456
+ },
457
+ open({ tab = "overview" } = {}) {
458
+ // 宿主设置页正开着时,卡片只切换该页的视图,不再叠一层对话框。
459
+ if (surfaceSnapshot.host === "page") { surface.update({ tab, editing: null }); return; }
460
+ panelSession = createPanelSession();
461
+ const focus = surfaceSnapshot.focus + 1;
462
+ const waiting = surfaceSnapshot.opening || settingsWrites.size > 0;
463
+ surface.update({ host: "dialog", tab, editing: null, focus, opening: waiting });
464
+ surface.waitForWrites(focus);
465
+ },
466
+ close() {
467
+ panelSession = createPanelSession();
468
+ surface.update({ host: null, tab: "overview", editing: null, opening: false });
469
+ },
470
+ showTab(tab) { surface.update({ tab, editing: null }); },
471
+ editSupplier(id) { surface.update({ tab: "suppliers", editing: id }); },
472
+ leaveEditor() { surface.update({ editing: null }); },
473
+ attachPage() {
474
+ // 原生设置页接管已打开的对话框与草稿;不抢宿主焦点,也不丢失正在编辑的子页。
475
+ // 接管时不在页面上再等一遍保存:controller 会从 pendingSave 继承保存锁并显示禁用态;
476
+ // 只有全新挂载的页面才需要 opening 等待,避免显示未同步的全局表单。
477
+ const takingOver = surfaceSnapshot.host === "dialog";
478
+ const waiting = surfaceSnapshot.opening || (!takingOver && settingsWrites.size > 0);
479
+ surface.update({ host: "page", tab: "suppliers", editing: surfaceSnapshot.editing, opening: waiting });
480
+ if (waiting) surface.waitForWrites(surfaceSnapshot.focus);
481
+ },
482
+ detachPage() {
483
+ if (surfaceSnapshot.host !== "page") return;
484
+ panelSession = createPanelSession();
485
+ surface.update({ host: null, tab: "overview", editing: null, opening: false });
486
+ },
487
+ };
488
+ const useSurface = () => React.useSyncExternalStore(surface.subscribe, surface.getSnapshot, surface.getSnapshot);
489
+
490
+ // ---------- API ----------
491
+ // sessionId undefined = 不按会话(沿用全局最近一次,兼容无 sessions 服务的嵌入场景);
492
+ // sessionId 为具体 id / 空串 = 严格「当前页」语义(空串即无当前页,显示暂无调用)。
493
+ //
494
+ // 请求生命周期(A1):
495
+ // - 每个请求都有「初始等待上限」(超时即 abort 并进入重试),但超时不等于服务端操作失败:
496
+ // refresh/test 可能在服务端继续跑到 120s,客户端只是先放弃等待。
497
+ // - 取消一律走 AbortController(释放请求);「请求代次校验」负责阻止不可取消或
498
+ // 已完成的请求回写 —— 两者不能互相替代。
499
+ // - 后台 GET 采用「完成后调度」:上一次结束后再等 BACKOFF,而不是固定间隔不断发起。
500
+ const REQUEST_TIMEOUT_MS = 30_000; // GET /state 的初始等待上限
501
+ const MUTATE_TIMEOUT_MS = 150_000; // refresh/test:后端最长 120s 查询 + 余量
502
+ const WRITE_TIMEOUT_MS = 30_000; // settings/rescan:本地写入与扫描
503
+ const POST_TIMEOUT_MS = {
504
+ [`${API}/refresh`]: MUTATE_TIMEOUT_MS,
505
+ [`${API}/test`]: MUTATE_TIMEOUT_MS,
506
+ [`${API}/settings`]: WRITE_TIMEOUT_MS,
507
+ [`${API}/rescan`]: WRITE_TIMEOUT_MS,
508
+ };
509
+ const POLL_BACKOFF_MS = [10_000, 20_000, 40_000, 60_000]; // 后台 GET 成功后复位到 10s
510
+ const backoffDelay = (failures) => POLL_BACKOFF_MS[Math.min(Math.max(failures, 1), POLL_BACKOFF_MS.length) - 1];
511
+
512
+ const timeoutController = (signal, ms) => {
513
+ const controller = new AbortController();
514
+ const timer = setTimeout(() => controller.abort(timeoutError(ms)), ms);
515
+ return { signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal, clear: () => clearTimeout(timer) };
516
+ };
517
+ const timeoutError = (ms) => {
518
+ const error = new Error(`timeout after ${ms}ms`);
519
+ error.name = "TimeoutError";
520
+ return error;
521
+ };
522
+ // 取消(切页/隐藏/卸载,AbortError)与等待超时(TimeoutError)都释放请求,但语义不同:
523
+ // 取消不计为失败;超时按失败推进退避(10→20→40→60s,见 load 的 catch)。
524
+ const isCancelled = (error) => error?.name === "AbortError";
525
+
526
+ const cacheState = (key, payload) => {
527
+ if (stateCache.has(key)) stateCache.delete(key); // 置新后按最近使用排序,淘汰最旧
528
+ stateCache.set(key, payload);
529
+ if (stateCache.size > STATE_CACHE_LIMIT) stateCache.delete(stateCache.keys().next().value);
530
+ };
531
+ const queryOf = (sessionId, extra) => {
532
+ const params = [];
533
+ if (sessionId !== undefined) params.push(`session=${encodeURIComponent(sessionId || "")}`);
534
+ if (extra) params.push(extra);
535
+ return params.length ? `?${params.join("&")}` : "";
536
+ };
537
+
538
+ /** GET /state:校验 HTTP 状态与载荷 ok 字段;signal 释放请求,超时由局部 helper 统一管理。 */
539
+ const getState = async (sessionId, { signal, quota = false } = {}) => {
540
+ const guard = timeoutController(signal, REQUEST_TIMEOUT_MS);
541
+ try {
542
+ const response = await fetch(`${API}/state${queryOf(sessionId, quota ? "quota=1" : null)}`, { cache: "no-store", signal: guard.signal });
543
+ // 显式失败才算失败(ok === false):保持与 post 同一判定,兼容不带 ok 字段的替身响应
544
+ if (response.ok === false) throw new Error(`HTTP ${response.status}`);
545
+ const payload = await response.json().catch(() => {
546
+ throw new Error("invalid JSON payload");
547
+ });
548
+ if (payload?.ok === false) throw new Error(payload.error || "state unavailable");
549
+ return payload;
550
+ } finally {
551
+ guard.clear(); // 成功、失败、取消都必须释放超时定时器
552
+ }
553
+ };
554
+ const post = async (path, body, sessionId, { signal } = {}) => {
555
+ const guard = timeoutController(signal, POST_TIMEOUT_MS[path] ?? REQUEST_TIMEOUT_MS);
556
+ try {
557
+ const response = await fetch(`${path}${queryOf(sessionId)}`, {
558
+ method: "POST",
559
+ headers: { "content-type": "application/json" },
560
+ body: JSON.stringify(body || {}),
561
+ signal: guard.signal,
562
+ });
563
+ const result = await response.json().catch(() => {
564
+ throw new Error(`HTTP ${response.status}`);
565
+ });
566
+ if (response.ok === false || result?.ok === false) throw new Error(result?.error || `HTTP ${response.status}`);
567
+ return result;
568
+ } finally {
569
+ guard.clear();
570
+ }
571
+ };
572
+
573
+ function createDisplayController(source) {
574
+ const listeners = new Set();
575
+ let snapshot = { state: null, refreshing: false, loadError: null };
576
+ let key, generation = 0, timer = null, active = false, disposed = false, failures = 0;
577
+ let inflight = null, manual = null, unsubscribe;
578
+ const hidden = () => document.visibilityState === "hidden";
579
+ const publish = (patch) => { snapshot = { ...snapshot, ...patch }; for (const fn of listeners) fn(); };
580
+ const clearTimer = () => { if (timer !== null) clearTimeout(timer); timer = null; };
581
+ const invalidate = () => {
582
+ generation++; clearTimer(); inflight?.controller.abort(); manual?.controller.abort(); inflight = manual = null;
583
+ };
584
+ const arm = (delay) => {
585
+ clearTimer();
586
+ if (!active || hidden() || manual) return;
587
+ timer = setTimeout(() => { timer = null; void load(); }, delay); timer?.unref?.();
588
+ };
589
+ const load = () => {
590
+ if (inflight) return inflight.promise;
591
+ if (!active || hidden() || manual) return Promise.resolve({ status: "cancelled" });
592
+ clearTimer();
593
+ const token = { controller: new AbortController(), generation, key };
594
+ inflight = token;
595
+ token.promise = (async () => {
596
+ try {
597
+ const state = await getState(token.key, { signal: token.controller.signal });
598
+ if (inflight !== token || token.generation !== generation || !active) return { status: "cancelled" };
599
+ failures = 0; cacheState(key, state); publish({ state, loadError: null });
600
+ return { status: "ok", payload: state };
601
+ } catch (error) {
602
+ if (inflight !== token || token.generation !== generation || !active || isCancelled(error)) return { status: "cancelled" };
603
+ failures++; publish({ loadError: error.message }); return { status: "failed", error };
604
+ } finally {
605
+ if (inflight === token) { inflight = null; arm(failures ? backoffDelay(failures) : POLL_BACKOFF_MS[0]); }
606
+ }
607
+ })();
608
+ return token.promise;
609
+ };
610
+ const refresh = () => {
611
+ if (manual) return manual.promise;
612
+ if (!active || hidden()) return Promise.resolve({ status: "cancelled" });
613
+ invalidate();
614
+ const token = { controller: new AbortController(), generation, key };
615
+ manual = token; publish({ refreshing: true });
616
+ token.promise = (async () => {
617
+ try {
618
+ const state = await post(`${API}/refresh`, undefined, token.key, { signal: token.controller.signal });
619
+ if (manual !== token || generation !== token.generation || !active) return { status: "cancelled" };
620
+ failures = 0; cacheState(key, state); publish({ state, loadError: null });
621
+ return { status: "ok", payload: state };
622
+ } catch (error) {
623
+ if (manual !== token || generation !== token.generation || !active || isCancelled(error)) return { status: "cancelled" };
624
+ publish({ loadError: error.message }); return { status: "failed", error };
625
+ } finally {
626
+ if (manual === token) { manual = null; publish({ refreshing: false }); arm(POLL_BACKOFF_MS[0]); }
627
+ }
628
+ })();
629
+ return token.promise;
630
+ };
631
+ const selectSession = () => {
632
+ const next = source ? source.getSnapshot() : undefined;
633
+ if (next === key && active) return;
634
+ key = next; invalidate(); failures = 0;
635
+ publish({ state: stateCache.get(key) || null, refreshing: false, loadError: null }); void load();
636
+ };
637
+ const visibility = () => {
638
+ invalidate(); publish({ refreshing: false }); if (!hidden()) void load();
639
+ };
640
+ const stop = () => {
641
+ active = false; invalidate(); unsubscribe?.(); unsubscribe = null;
642
+ document.removeEventListener("visibilitychange", visibility);
643
+ };
644
+ return {
645
+ subscribe(fn) {
646
+ if (disposed) return () => {};
647
+ listeners.add(fn);
648
+ if (!active) {
649
+ active = true; key = source ? source.getSnapshot() : undefined;
650
+ publish({ state: stateCache.get(key) || null, refreshing: false, loadError: null });
651
+ unsubscribe = source?.subscribe(selectSession);
652
+ document.addEventListener("visibilitychange", visibility); void load();
653
+ }
654
+ return () => { listeners.delete(fn); if (!listeners.size) stop(); };
655
+ },
656
+ getSnapshot: () => snapshot, refresh,
657
+ // 当前订阅的会话键:统计弹窗要按同一条作用域另取额度历史(?quota=1)
658
+ sessionKey: () => key,
659
+ async reload() {
660
+ if (manual) await manual.promise;
661
+ if (!active) return;
662
+ invalidate();
663
+ let result = await load();
664
+ // 多个配置完成回调共享最新读取,不能把被新读取替代的取消当作已经同步。
665
+ while (active && !hidden() && result?.status === "cancelled" && inflight) result = await inflight.promise;
666
+ return result;
667
+ },
668
+ dispose() { disposed = true; stop(); listeners.clear(); stateCache.clear(); },
669
+ };
670
+ }
671
+ function useQuotaState() {
672
+ const snapshot = React.useSyncExternalStore(displayController.subscribe, displayController.getSnapshot, displayController.getSnapshot);
673
+ return { ...snapshot, refresh: displayController.refresh, sessionKey: displayController.sessionKey() };
674
+ }
675
+
676
+ /**
677
+ * 按需拉取带额度历史的 state(?quota=1)。只在概览首次展开供应商时取一次,
678
+ * 同一面板会话内复用;失败不报错,图表降级为只有 token 柱。
679
+ */
680
+ function useQuotaHistory(sessionKey, enabled) {
681
+ const cache = React.useRef({ key: null, payload: null });
682
+ const generation = React.useRef(0);
683
+ const [result, setResult] = React.useState({ loading: false, error: null, payload: null });
684
+ const fetchQuota = React.useCallback(() => {
685
+ if (!enabled) return;
686
+ const gen = ++generation.current;
687
+ setResult((old) => ({ ...old, loading: true, error: null }));
688
+ getState(sessionKey, { quota: true })
689
+ .then((payload) => {
690
+ if (gen !== generation.current) return;
691
+ cache.current = { key: sessionKey, payload };
692
+ setResult({ loading: false, error: null, payload });
693
+ })
694
+ .catch((error) => {
695
+ if (gen !== generation.current) return;
696
+ setResult({ loading: false, error: error?.message || String(error), payload: null });
697
+ });
698
+ }, [enabled, sessionKey]);
699
+ // 会话切换先让在途请求失效,再按新会话取一次。
700
+ React.useEffect(() => {
701
+ generation.current++;
702
+ cache.current = { key: null, payload: null };
703
+ setResult({ loading: false, error: null, payload: null });
704
+ }, [sessionKey]);
705
+ React.useEffect(() => {
706
+ if (!enabled) return;
707
+ if (cache.current.key === sessionKey && cache.current.payload) {
708
+ setResult({ loading: false, error: null, payload: cache.current.payload });
709
+ return;
710
+ }
711
+ fetchQuota();
712
+ }, [enabled, sessionKey, fetchQuota]);
713
+ return { ...result, reload: fetchQuota };
714
+ }
715
+ const supplierDraft = (sup) => ({
716
+ enabled: !!sup.enabled, baseUrl: sup.baseUrl || sup.baseUrlDefault || "",
717
+ warnPct: sup.warnPct ?? 80, critPct: sup.critPct ?? 95,
718
+ apiKeyEnv: sup.apiKeyEnv || "",
719
+ // 关注限额:有序数组;空数组 = 未配置(卡片走默认规则)。草稿复制一份,避免直接改 state。
720
+ displayKeys: Array.isArray(sup.displayKeys) ? [...sup.displayKeys] : [],
721
+ ...Object.fromEntries((sup.meta?.needs || []).map((need) => [need.key, need.secret ? "" : (sup[need.key] ?? "")])),
722
+ });
723
+ function supplierPatch(sup, form) {
724
+ const patch = { enabled: !!form.enabled, baseUrl: String(form.baseUrl || ""),
725
+ warnPct: Number(form.warnPct), critPct: Number(form.critPct),
726
+ apiKeyEnv: String(form.apiKeyEnv || "").trim(),
727
+ displayKeys: (Array.isArray(form.displayKeys) ? form.displayKeys : []).map(String).slice(0, 12) };
728
+ for (const need of sup.meta?.needs || []) {
729
+ const value = String(form[need.key] ?? "");
730
+ if (!need.secret) patch[need.key] = value;
731
+ else if (value.trim()) patch[need.key] = value.trim();
732
+ }
733
+ return patch;
734
+ }
735
+
736
+ function FooterWidget({ wide, t }) {
737
+ const entryRef = React.useRef(null), widthRef = React.useRef(null);
738
+ const preference = useDensity(), panel = useSurface();
739
+ const [narrow, setNarrow] = React.useState(false);
740
+ const { state, loadError } = useQuotaState();
741
+ // 单击卡片直接打开唯一的面板;已经打开时不重复触发(关闭走面板自己的未保存确认)。
742
+ const activateEntry = () => { if (panel.host !== "dialog") surface.open({ tab: "overview" }); };
743
+ React.useEffect(() => {
744
+ const node = widthRef.current;
745
+ if (!node || typeof ResizeObserver === "undefined") return;
746
+ const update = (width) => setNarrow(width > 0 && width < 200);
747
+ update(node.getBoundingClientRect().width);
748
+ const observer = new ResizeObserver(entries => { for (const e of entries) update(e.contentRect.width); });
749
+ observer.observe(node); return () => observer.disconnect();
750
+ }, [wide]);
751
+ const compact = narrow || preference === "compact";
752
+ const active = state?.active;
753
+ const supplier = active && state?.suppliers?.find(s => s.id === active.supplierId);
754
+ const metric = selectPrimaryMetric(supplier, t);
755
+ const name = active?.name || t("noneActive");
756
+ const todayCount = typeof supplier?.todayTokens === "number" ? supplier.todayTokens : 0;
757
+ const bars = selectBarMetrics(supplier, t);
758
+ const resetText = bars.length ? bars.map(bar => bar.reset).filter(Boolean).join(" · ") : metric.reset;
759
+ const failure = loadError ? t(state ? "staleFailure" : "unavailable") : supplier?.state === "err" ? supplierStatus(supplier, t) : "";
760
+ const conn = connStateOf(state);
761
+ const connText = t(conn.key === "ok" ? "eventsObserved" : conn.key === "warn" ? "connWarn" : "connStandby");
762
+ const season = state?.season || null;
763
+ const seasonCount = season ? seasonCountdown(season, t) : null;
764
+ const seasonTitle = season
765
+ ? [seasonLabelOf(season, t), seasonCount, `${t("seasonBeijingNow")} ${season.beijing?.weekday || ""} ${season.beijing?.clock || ""}`.trim(),
766
+ seasonUsesBeijingNote() ? t("seasonBeijingOnly") : null].filter(Boolean).join(" · ")
767
+ : "";
768
+ // 卡片上的可见文字只留数据;完整状态(今日口径、连接、峰谷成因)进 aria/title。
769
+ const title = [name, metric.text, resetText, seasonTitle, failure, t("todayScope"), t("today", { n: state ? fmtBig(todayTotal(state)) : "—" }), connText].filter(Boolean).join(" · ");
770
+ return h(React.Fragment, null,
771
+ !wide ? h("button", { type: "button", ref: entryRef, "data-qm-entry": "", className: "qm-rail", "aria-label": t("title"), "aria-haspopup": "dialog", "aria-expanded": !!panel.host, title, onClick: activateEntry }, "◉") :
772
+ h("div", { "data-qm-linerow": "", "data-qm-density": compact ? "compact" : "expanded", ref: widthRef, className: "qm-footer" },
773
+ h("button", { type: "button", ref: entryRef, "data-qm-entry": "", className: "qm-card-body",
774
+ "aria-haspopup": "dialog", "aria-expanded": !!panel.host, title, "aria-label": title, onClick: activateEntry },
775
+ compact ? null : h("div", { className: "qm-head" },
776
+ h("div", { className: "qm-l1" },
777
+ h("b", { className: "qm-plan" }, name),
778
+ failure ? h("span", { className: "qm-fetch-status" }, failure) : null,
779
+ supplier ? h("span", { className: "qm-today-chip" }, t("todayShort", { n: fmtBig(todayCount) })) : null)),
780
+ compact ? h("div", { className: "qm-compact-line" }, h("span", { className: "qm-provider" }, name),
781
+ h("span", { className: "qm-primary" },
782
+ h("span", { className: "qm-metric-name" }, failure || [metric.name, metric.kind === "quota" ? t("usedShort") : metric.label].filter(Boolean).join(" ")),
783
+ h("strong", { className: "qm-metric-value" }, metric.value),
784
+ metric.more > 0 ? h("span", { className: "qm-more", title: t("moreMetrics", { n: metric.more }) }, `+${metric.more}`) : null)) :
785
+ h(React.Fragment, null,
786
+ bars.length ? h("div", { className: "qm-bars" }, bars.flatMap((bar, i) => [
787
+ h("span", { key: `l${i}`, className: "qm-bar-label", title: bar.entry.name }, bar.label),
788
+ h("span", { key: `b${i}`, className: "qm-bar", "data-qm-bar": "", "data-qm-tone": bar.tone, "data-qm-window": bar.weekly ? "week" : "other",
789
+ role: "progressbar", "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": bar.entry.pct,
790
+ "aria-label": t("barAria", { name: bar.entry.name, pct: pctText(bar.entry.pct) }) },
791
+ h("i", { className: `qm-bar-fill ${bar.tone}`, style: { width: `${Math.max(0, Math.min(100, bar.entry.pct))}%` } })),
792
+ h("span", { key: `p${i}`, className: "qm-bar-pct" }, pctText(bar.entry.pct)),
793
+ bar.reset ? h("span", { key: `r${i}`, className: "qm-bar-reset" }, bar.reset) : null,
794
+ ])) : h("div", { className: "qm-l2" }, h("span", { className: "qm-primary", title: metric.text }, metric.text)),
795
+ season ? h("div", { className: `qm-season ${season.peak ? "peak" : "valley"}`, "data-qm-season": season.tier, title: seasonTitle },
796
+ h("span", { className: `qm-season-dot ${season.peak ? "peak" : "valley"}` }),
797
+ h("b", null, seasonTierOf(season, t)),
798
+ seasonCount ? h("span", { className: "qm-season-meta" }, seasonCount) : null) : null)),
799
+ h("button", { type: "button", className: "qm-density", "aria-label": t(compact ? "expand" : "collapse"), title: t(compact ? "expand" : "collapse"),
800
+ onClick: () => preferences.set(compact ? "expanded" : "compact") }, compact ? "▾" : "▴")),
801
+ panel.host === "dialog" ? createPortal(h(PanelHost, { t, host: "dialog", onClose: () => surface.close(), returnFocusRef: entryRef }), document.body) : null);
802
+ }
803
+
804
+ function FooterSlotWithSession(props) { return h(FooterWidget, props); }
805
+
806
+ function InfoHint({ t, text }) {
807
+ if (!text) return null;
808
+ return h("details", { className: "qm-info" },
809
+ h("summary", { "aria-label": t("moreInfo"), title: t("moreInfo") }, "ⓘ"),
810
+ h("p", null, text));
811
+ }
812
+
813
+ function Empty({ text, action, onAction }) {
814
+ return h("div", { className: "qm-empty" },
815
+ h("p", null, text),
816
+ action ? h("button", { type: "button", onClick: onAction }, action) : null);
817
+ }
818
+
819
+ // ---------- 唯一面板:dialog(卡片)与 page(宿主设置)共用同一内容 ----------
820
+ function PanelHost({ t, host, onClose, returnFocusRef }) {
821
+ return h(Panel, { t, host, onClose, returnFocusRef });
822
+ }
823
+
824
+ function Panel({ t, host, onClose, returnFocusRef }) {
825
+ const { state, loadError, refresh, refreshing, sessionKey } = useQuotaState();
826
+ const snap = useSurface();
827
+ const [expandedId, setExpandedId] = React.useState(null);
828
+ // 没有本地用量行的供应商不画图,也就不必为它取额度历史。
829
+ const expandedSupplier = (state?.suppliers || []).find((sup) => sup.id === expandedId);
830
+ const quota = useQuotaHistory(sessionKey, Array.isArray(expandedSupplier?.usageDays) && expandedSupplier.usageDays.length > 0);
831
+ const dialog = host === "dialog";
832
+ // Escape / 外部点击必须走 controller 的未保存确认;useDialog 只拿到这个稳定转发器。
833
+ const closeRef = React.useRef(() => {});
834
+ const dialogRef = useDialog(() => closeRef.current(), returnFocusRef, dialog);
835
+ const ctl = usePanelController({ t, state, loadError, refresh, refreshing, sessionKey, host, onClose, snap, dialogRef });
836
+ closeRef.current = ctl.requestClose;
837
+ React.useEffect(() => { setExpandedId(null); }, [sessionKey]);
838
+ const refreshAll = () => { void refresh(); if (quota.payload) quota.reload(); };
839
+ const card = h("div", { ref: dialogRef, tabIndex: -1,
840
+ ...(dialog ? { role: "dialog", "aria-modal": true, "aria-label": t("title") } : {}),
841
+ className: `qm-card qm-settings${dialog ? "" : " qm-settings-page"}` },
842
+ h("div", { className: "qm-panel-head" }, h("h3", { tabIndex: -1 }, t("title")),
843
+ h("button", { type: "button", disabled: refreshing, onClick: refreshAll }, t(refreshing ? "refreshing" : "refresh")),
844
+ dialog ? h("button", { type: "button", onClick: ctl.requestClose, "aria-label": t("close") }, t("close")) : null),
845
+ h("div", { className: "qm-tabs", role: "tablist", "aria-label": t("title") }, ["overview", "suppliers"].map(name => h("button", {
846
+ type: "button", role: "tab", key: name, "aria-selected": snap.tab === name || (name === "suppliers" && !!snap.editing), onClick: () => ctl.navigate(name) }, t(name)))),
847
+ ctl.savedBanner,
848
+ ctl.saveError ? h("div", { role: "alert", className: "ci-err" }, ctl.saveError) : null,
849
+ state?.storageError ? h("div", { role: "alert", className: "ci-err" }, state.storageError) : null,
850
+ loadError ? h("div", { role: "alert", className: "ci-err" }, `${t(state ? "staleFailure" : "unavailable")}:${loadError}`) : null,
851
+ !state || snap.opening ? h("p", { role: "status" }, t(loadError ? "unavailable" : "loading")) :
852
+ snap.editing ? h(SupplierEditor, { state, t, ctl }) :
853
+ snap.tab === "suppliers" ? h(SuppliersView, { state, t, ctl }) :
854
+ h(OverviewView, { state, t, quota, expandedId, onExpand: setExpandedId, onEdit: ctl.openSupplier, onManage: () => ctl.navigate("suppliers") }),
855
+ ctl.confirmation ? h("div", { role: "alertdialog", "aria-label": t("unsaved"), className: "qm-confirm" },
856
+ h("p", null, t("unsaved")), h("button", { type: "button", autoFocus: true, onClick: () => ctl.setConfirmation(null) }, t("keepEditing")),
857
+ h("button", { type: "button", onClick: () => { const action = ctl.confirmation; ctl.setConfirmation(null); action(); } }, t("discard"))) : null);
858
+ return dialog ? h("div", { className: "qm-overlay", onClick: (ev) => ev.target === ev.currentTarget && ctl.requestClose() }, card) : card;
859
+ }
860
+
861
+ function usePanelController({ t, state, loadError, refresh, refreshing, host, onClose, snap, dialogRef }) {
862
+ const [globalForm, setGlobalLocal] = React.useState(panelSession.globalForm);
863
+ const [editor, setEditorLocal] = React.useState(panelSession.editor);
864
+ const [confirmation, setConfirmation] = React.useState(null);
865
+ const [advanced, setAdvanced] = React.useState(false);
866
+ const [testState, setTestState] = React.useState({});
867
+ const [saved, setSaved] = React.useState(null);
868
+ const [saveError, setSaveError] = React.useState(null);
869
+ const [scanBusy, setScanBusy] = React.useState(false);
870
+ const [freshIds, setFreshIds] = React.useState([]);
871
+ const [testBusy, setTestBusy] = React.useState(null);
872
+ const [toggling, setToggling] = React.useState({});
873
+ const opRef = React.useRef({ editorId: panelSession.editorId, opSeq: 0, revision: editor?.revision || 0 });
874
+ const testSeq = React.useRef(0);
875
+ const mountedRef = React.useRef(true);
876
+ const togglingRef = React.useRef(new Set());
877
+ const advancedRef = React.useRef(null);
878
+
879
+ const setEditor = (next) => setEditorLocal(old => { const value = typeof next === "function" ? next(old) : next; panelSession.editor = value; return value; });
880
+ const setGlobalForm = (next) => setGlobalLocal(old => { const value = typeof next === "function" ? next(old) : next; panelSession.globalForm = value; return value; });
881
+ const comparable = form => ({ ...form, warnPct: Number(form.warnPct), critPct: Number(form.critPct) });
882
+ const dirty = !!editor && JSON.stringify(comparable(editor.form)) !== JSON.stringify(comparable(editor.initial));
883
+ const globalDirty = !!globalForm && (Number(globalForm.intervalSeconds) !== (state?.poll?.intervalSeconds ?? 60)
884
+ || Number(globalForm.retentionDays) !== (state?.poll?.retentionDays ?? 7)
885
+ || holidaysTextOf(globalForm.holidays) !== holidaysTextOf(state?.holidays));
886
+ const guarded = (action, all = false) => { if (dirty || (all && globalDirty)) setConfirmation(() => action); else action(); };
887
+ const requestClose = () => guarded(onClose, true);
888
+ const scrollContainer = () => {
889
+ let node = dialogRef.current;
890
+ while (node) {
891
+ if (/(auto|scroll)/.test(window.getComputedStyle?.(node).overflowY || "")) return node;
892
+ node = node.parentElement;
893
+ }
894
+ return document.scrollingElement || dialogRef.current;
895
+ };
896
+ const viewKey = snap.editing ? "supplier" : snap.tab;
897
+ const rememberPosition = () => { panelSession.positions[viewKey] = scrollContainer()?.scrollTop || 0; };
898
+ const navigate = (name) => {
899
+ rememberPosition();
900
+ if (name === "suppliers" && editor) { surface.editSupplier(editor.supplierId); return; }
901
+ surface.showTab(name);
902
+ };
903
+
904
+ React.useEffect(() => {
905
+ const session = panelSession;
906
+ mountedRef.current = true;
907
+ return () => {
908
+ mountedRef.current = false;
909
+ if (host === "dialog" && surface.getSnapshot().host === "dialog" && panelSession === session) surface.close();
910
+ };
911
+ }, []);
912
+ // 原生设置分区接管时继承同一保存锁;结算只影响同一编辑身份。
913
+ const inheritedSave = panelSession.pendingSave?.editorId === panelSession.editorId ? panelSession.pendingSave : null;
914
+ const [opBusy, setOpBusy] = React.useState(!!inheritedSave);
915
+ const opBusyRef = React.useRef(!!inheritedSave);
916
+ React.useEffect(() => {
917
+ const pending = inheritedSave;
918
+ if (!pending) return;
919
+ const editorId = editor?.editorId ?? opRef.current.editorId;
920
+ pending.promise.then(result => {
921
+ if (!mountedRef.current || opRef.current.editorId !== editorId) return;
922
+ opBusyRef.current = false; setOpBusy(false);
923
+ if (!result.ok) { setSaveError(result.error); setAdvanced(true); return; }
924
+ setSaved(pending.supplierId || "global");
925
+ if (pending.supplierId && panelSession.editor?.editorId === editorId) {
926
+ if (surface.getSnapshot().editing) surface.showTab(panelSession.editor.origin || "suppliers");
927
+ setEditor(null); nextEditorId();
928
+ }
929
+ });
930
+ }, []);
931
+ React.useEffect(() => { if (editor) { opRef.current.editorId = editor.editorId; opRef.current.revision = editor.revision; } }, []);
932
+ React.useEffect(() => { if (state && !snap.opening && !globalForm) setGlobalForm({ intervalSeconds: state.poll?.intervalSeconds ?? 60, retentionDays: state.poll?.retentionDays ?? 7, holidays: holidaysTextOf(state.holidays ?? []) }); }, [state, snap.opening]);
933
+ React.useLayoutEffect(() => { const node = scrollContainer(); if (node) node.scrollTop = panelSession.positions[viewKey] || 0; }, [viewKey]);
934
+ React.useEffect(() => { if (snap.focus) dialogRef.current?.querySelector("h3")?.focus(); }, [snap.focus]);
935
+
936
+ const nextEditorId = () => { const id = ++opRef.current.editorId; panelSession.editorId = id; opRef.current.revision = 0; return id; };
937
+ const discardEditor = () => {
938
+ const origin = editor?.origin || "suppliers";
939
+ nextEditorId(); testSeq.current++; setTestBusy(null); opBusyRef.current = false; setOpBusy(false); setEditor(null); surface.showTab(origin); setSaveError(null);
940
+ };
941
+ const closeEditor = () => guarded(discardEditor);
942
+ const beginSave = (supplierId, trackOnly = false) => {
943
+ const session = panelSession;
944
+ let resolve;
945
+ const promise = new Promise(done => { resolve = done; });
946
+ const pending = { supplierId, promise, editorId: opRef.current.editorId };
947
+ if (!trackOnly) session.pendingSave = pending;
948
+ settingsWrites.add(pending);
949
+ return result => {
950
+ if (session.pendingSave === pending) session.pendingSave = null;
951
+ settingsWrites.delete(pending); resolve(result); surface.bump();
952
+ };
953
+ };
954
+ const reload = React.useCallback(() => displayController.reload(), []);
955
+ const openSupplier = (id) => {
956
+ const sup = (state?.suppliers || []).find((s) => s.id === id);
957
+ if (!sup) return;
958
+ if (editor?.supplierId === id) { surface.editSupplier(id); return; }
959
+ if (dirty) { setConfirmation(() => () => { setEditor(null); enterSupplier(sup); }); return; }
960
+ enterSupplier(sup);
961
+ };
962
+ const enterSupplier = (sup) => {
963
+ const id = sup.id;
964
+ const pending = [...settingsWrites].find(operation => operation.supplierId === id);
965
+ if (pending) {
966
+ const identity = nextEditorId();
967
+ setEditor(null); surface.editSupplier(id);
968
+ void pending.promise.then(async () => {
969
+ await reload();
970
+ if (!mountedRef.current || opRef.current.editorId !== identity || surface.getSnapshot().editing !== id) return;
971
+ const savedSup = displayController.getSnapshot().state?.suppliers?.find(s => s.id === id);
972
+ if (savedSup) openSupplierClean(savedSup);
973
+ });
974
+ return;
975
+ }
976
+ openSupplierClean(sup);
977
+ };
978
+ const openSupplierClean = (sup) => {
979
+ rememberPosition();
980
+ const form = supplierDraft(sup);
981
+ const editorId = nextEditorId();
982
+ setEditor({ editorId, supplierId: sup.id, form, initial: { ...form }, origin: surface.getSnapshot().tab === "overview" ? "overview" : "suppliers", revision: 0 });
983
+ setAdvanced(false);
984
+ surface.editSupplier(sup.id);
985
+ testSeq.current++;
986
+ setTestState({});
987
+ setTestBusy(null);
988
+ setSaved(null);
989
+ setSaveError(null);
990
+ setOpBusy(false);
991
+ opBusyRef.current = false;
992
+ };
993
+ const setEditorField = (key, value) => {
994
+ opRef.current.revision++;
995
+ testSeq.current++;
996
+ setTestBusy(null);
997
+ setSaved(null);
998
+ setTestState((x) => {
999
+ if (!editor || !(editor.supplierId in x)) return x;
1000
+ const next = { ...x };
1001
+ delete next[editor.supplierId];
1002
+ return next;
1003
+ });
1004
+ setEditor((e) => (e ? { ...e, form: { ...e.form, [key]: value }, revision: opRef.current.revision } : e));
1005
+ };
1006
+ const saveGlobal = async () => {
1007
+ if (!globalForm || opBusyRef.current || [...settingsWrites].some(operation => operation.supplierId === null)) return;
1008
+ const interval = Number(globalForm.intervalSeconds), retention = Number(globalForm.retentionDays);
1009
+ if (!Number.isFinite(interval) || interval < 10 || interval > 3600 || !Number.isFinite(retention) || retention < 1 || retention > 90) { setSaveError(t("invalidGlobal")); return; }
1010
+ const holidays = parseHolidayText(globalForm.holidays);
1011
+ const invalid = holidays.filter((day) => !isValidHolidayDay(day));
1012
+ if (invalid.length) { setSaveError(t("invalidHolidays", { list: invalid.slice(0, 3).join("、") })); return; }
1013
+ const editorId = opRef.current.editorId, seq = ++opRef.current.opSeq;
1014
+ const latest = () => mountedRef.current && opRef.current.editorId === editorId && opRef.current.opSeq === seq;
1015
+ const finish = beginSave(null);
1016
+ let outcome = { ok: false, error: t("unavailable") };
1017
+ opBusyRef.current = true; setOpBusy(true);
1018
+ setSaved(null); setSaveError(null);
1019
+ try {
1020
+ await post(`${API}/settings`, {
1021
+ intervalSeconds: Number(globalForm.intervalSeconds),
1022
+ retentionDays: Number(globalForm.retentionDays),
1023
+ holidays,
1024
+ });
1025
+ await reload();
1026
+ outcome = { ok: true };
1027
+ if (!latest()) return;
1028
+ setSaved("global");
1029
+ } catch (error) {
1030
+ outcome = { ok: false, error: error.message };
1031
+ if (!latest()) return;
1032
+ setSaveError(error.message);
1033
+ console.error("[dsh-token-quota] global settings save failed", error);
1034
+ } finally { finish(outcome); if (latest()) { opBusyRef.current = false; setOpBusy(false); } }
1035
+ };
1036
+ const saveSupplier = async () => {
1037
+ if (!editor || opBusyRef.current || [...settingsWrites].some(operation => operation.supplierId === editor.supplierId)) return;
1038
+ const { editorId, supplierId, form, origin } = editor;
1039
+ const sup = (state?.suppliers || []).find((s) => s.id === supplierId);
1040
+ if (!sup) return;
1041
+ const warn = Number(form.warnPct), crit = Number(form.critPct);
1042
+ if (!Number.isFinite(warn) || !Number.isFinite(crit) || warn < 1 || warn >= crit || crit > 100) {
1043
+ setSaveError(t("invalidThreshold")); setAdvanced(true);
1044
+ requestAnimationFrame(() => advancedRef.current?.querySelector('input[type="number"]')?.focus()); return;
1045
+ }
1046
+ const seq = ++opRef.current.opSeq;
1047
+ const latest = () => mountedRef.current && opRef.current.editorId === editorId && opRef.current.opSeq === seq;
1048
+ const finish = beginSave(supplierId);
1049
+ let outcome = { ok: false, error: t("unavailable") };
1050
+ setSaved(null); setSaveError(null);
1051
+ opBusyRef.current = true;
1052
+ setOpBusy(true);
1053
+ try {
1054
+ const p = supplierPatch(sup, form);
1055
+ await post(`${API}/settings`, { suppliers: { [supplierId]: p } });
1056
+ await reload();
1057
+ outcome = { ok: true };
1058
+ if (!latest()) return;
1059
+ setSaved(supplierId);
1060
+ opBusyRef.current = false;
1061
+ setOpBusy(false);
1062
+ if (surface.getSnapshot().editing) surface.showTab(origin || "suppliers");
1063
+ setEditor(null);
1064
+ nextEditorId();
1065
+ } catch (error) {
1066
+ outcome = { ok: false, error: error.message };
1067
+ if (!latest()) return;
1068
+ setSaveError(error.message);
1069
+ setAdvanced(true);
1070
+ requestAnimationFrame(() => advancedRef.current?.querySelector("input")?.focus());
1071
+ console.error("[dsh-token-quota] supplier settings save failed", error);
1072
+ } finally {
1073
+ finish(outcome);
1074
+ if (opRef.current.editorId === editorId && opRef.current.opSeq === seq) {
1075
+ opBusyRef.current = false;
1076
+ if (mountedRef.current) setOpBusy(false);
1077
+ }
1078
+ }
1079
+ };
1080
+ const toggleEnabled = async (sup) => {
1081
+ if (togglingRef.current.has(sup.id) || [...settingsWrites].some(operation => operation.supplierId === sup.id)) return;
1082
+ const finish = beginSave(sup.id, true);
1083
+ let outcome = { ok: false, error: t("unavailable") };
1084
+ togglingRef.current.add(sup.id);
1085
+ setToggling((x) => ({ ...x, [sup.id]: true }));
1086
+ setSaveError(null);
1087
+ try {
1088
+ await post(`${API}/settings`, { suppliers: { [sup.id]: { enabled: !sup.enabled } } });
1089
+ await reload();
1090
+ outcome = { ok: true };
1091
+ } catch (error) {
1092
+ outcome = { ok: false, error: error.message };
1093
+ if (!mountedRef.current) return;
1094
+ setSaveError(error.message);
1095
+ console.error("[dsh-token-quota] enable toggle failed", error);
1096
+ } finally {
1097
+ finish(outcome);
1098
+ togglingRef.current.delete(sup.id);
1099
+ if (mountedRef.current) setToggling((x) => ({ ...x, [sup.id]: false }));
1100
+ }
1101
+ };
1102
+ const runTest = (id) => {
1103
+ const sup = (state?.suppliers || []).find((s) => s.id === id);
1104
+ const editing = editor?.supplierId === id ? editor : null;
1105
+ const editorId = editing ? opRef.current.editorId : null;
1106
+ const revision = editing ? opRef.current.revision : null;
1107
+ const config = editing ? supplierPatch(sup, editing.form) : undefined;
1108
+ const seq = ++testSeq.current;
1109
+ setTestState((x) => ({ ...x, [id]: t("testing") }));
1110
+ setTestBusy(id);
1111
+ const stillCurrent = () => mountedRef.current && seq === testSeq.current
1112
+ && (!editing || opRef.current.editorId === editorId && opRef.current.revision === revision);
1113
+ post(`${API}/test`, { supplier: id, config })
1114
+ .then((r) => { if (stillCurrent()) setTestState((x) => ({ ...x, [id]: r })); })
1115
+ .catch((error) => { if (stillCurrent()) setTestState((x) => ({ ...x, [id]: { ok: false, error: error.message } })); })
1116
+ .finally(() => { if (mountedRef.current && seq === testSeq.current) setTestBusy(null); });
1117
+ };
1118
+ const runRescan = async () => {
1119
+ if (scanBusy) return;
1120
+ const prevAddable = new Set((state?.suppliers || []).filter((s) => s.added === false).map((s) => s.id));
1121
+ setScanBusy(true);
1122
+ try {
1123
+ const next = await post(`${API}/rescan`);
1124
+ if (!next || next.ok === false) throw new Error((next && next.error) || "rescan failed");
1125
+ if (!mountedRef.current) return;
1126
+ await reload();
1127
+ const nowAddable = (next.suppliers || []).filter((s) => s.added === false);
1128
+ setFreshIds(nowAddable.filter((s) => !prevAddable.has(s.id)).map((s) => s.id));
1129
+ } catch (error) {
1130
+ if (!mountedRef.current) return;
1131
+ setSaveError(t("scanLineFail", { err: error.message }));
1132
+ console.error("[dsh-token-quota] rescan failed", error);
1133
+ await reload();
1134
+ } finally {
1135
+ if (mountedRef.current) setScanBusy(false);
1136
+ }
1137
+ };
1138
+ const globalBusy = opBusy || [...settingsWrites].some(operation => operation.supplierId === null);
1139
+ return {
1140
+ view: snap.editing ? { name: "supplier", id: snap.editing } : { name: snap.tab },
1141
+ editor, globalForm, dirty, globalDirty, confirmation, advanced, testState, testBusy, saved, saveError,
1142
+ scanBusy, freshIds, opBusy, globalBusy, toggling, advancedRef, setConfirmation, setAdvanced,
1143
+ navigate, openSupplier, closeEditor, setEditorField, setGlobalForm, saveGlobal, saveSupplier, runTest, runRescan, toggleEnabled,
1144
+ requestClose, reload,
1145
+ savedBanner: saved ? h("div", { className: "s-saved", style: { marginBottom: 8 } }, t("saved")) : null,
1146
+ };
1147
+ }
1148
+
1149
+ // ---------- 概览:供应商行 + 展开明细 ----------
1150
+ function OverviewView({ state, t, quota, expandedId, onExpand, onEdit, onManage }) {
1151
+ const suppliers = (state.suppliers || []).filter(s => s.added !== false).sort((a, b) =>
1152
+ Number(b.id === state.active?.supplierId) - Number(a.id === state.active?.supplierId) || a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
1153
+ const attention = s => s.state === "err" || (s.enabled !== false && ["stateWarn", "stateCrit"].includes(stateToken(s)));
1154
+ const [filter, setFilter] = React.useState("all");
1155
+ const shown = filter === "all" ? suppliers : suppliers.filter(attention);
1156
+ const quotaOf = (id) => (quota.payload?.suppliers || []).find((sup) => sup.id === id)?.quotaHistory || {};
1157
+ return h(React.Fragment, null,
1158
+ h("div", { className: "qm-overview-head" },
1159
+ h("span", { className: "qm-today-total" }, h("span", null, t("todayLabel")), h("b", null, fmtBig(todayTotal(state))), h("span", null, "tokens"),
1160
+ h(InfoHint, { t, text: t("todayScope") })),
1161
+ h("div", { className: "qm-filter", role: "group", "aria-label": t("overview") },
1162
+ ["all", "attention"].map(key => h("button", { key, type: "button", "aria-pressed": filter === key, onClick: () => setFilter(key) },
1163
+ t(key), h("span", { className: "qm-count" }, key === "all" ? suppliers.length : suppliers.filter(attention).length))))),
1164
+ shown.length
1165
+ ? h("div", { className: "qm-rows" }, shown.map(sup => h(SupplierRow, {
1166
+ key: sup.id, sup, t, season: state.season, quota: quotaOf(sup.id),
1167
+ expanded: expandedId === sup.id, onToggle: () => onExpand(expandedId === sup.id ? null : sup.id), onEdit })))
1168
+ : h(Empty, { text: t(filter === "attention" ? "noAttention" : "overviewEmpty"), action: filter === "all" ? t("manageSuppliers") : null, onAction: onManage }),
1169
+ h(HistoryTable, { rows: (state.history || []).slice(0, 50), t }));
1170
+ }
1171
+
1172
+ function SupplierRow({ sup, t, season, quota, expanded, onToggle, onEdit }) {
1173
+ const metric = selectPrimaryMetric(sup, t);
1174
+ const todayNumber = typeof sup.todayTokens === "number" ? sup.todayTokens : 0;
1175
+ const error = String(sup.error?.message || sup.error?.code || "");
1176
+ const detailId = `qm-detail-${sup.id}`;
1177
+ return h("article", { className: `qm-row${expanded ? " open" : ""}`, "data-supplier": sup.id },
1178
+ h("button", { type: "button", className: "qm-row-head", "data-qm-row": "", "aria-expanded": expanded, "aria-controls": detailId, onClick: onToggle },
1179
+ h("span", { className: `qm-dot ${stateClass(sup)}` }),
1180
+ h("b", { className: "qm-row-name" }, sup.name),
1181
+ sup.current ? h("span", { className: "qm-cur" }, t("current")) : null,
1182
+ h("span", { className: `qm-pill ${stateClass(sup)}` }, supplierStatus(sup, t)),
1183
+ h("span", { className: "qm-row-metric" }, metric.value),
1184
+ h("span", { className: "qm-row-today" }, `${t("todayLabel")} ${fmtBig(todayNumber)}`),
1185
+ h("span", { className: "qm-chevron", "aria-hidden": "true" }, expanded ? "▴" : "▾")),
1186
+ expanded ? h("div", { id: detailId, className: "qm-row-detail", role: "region", "aria-label": `${sup.name} ${t("detailTitle")}` },
1187
+ sup.state === "err" ? h("div", { className: "ci-err", role: "status" }, supplierStatus(sup, t), error ? `:${error.slice(0, 180)}` : "",
1188
+ error.length > 180 ? h("details", null, h("summary", null, t("errorDetails")), h("p", null, error)) : null) : null,
1189
+ sup.lastSuccessAt ? h("div", { className: "qm-data-time" }, `${t("lastSuccess")} ${new Date(sup.lastSuccessAt).toLocaleString()}`) : null,
1190
+ h(MetricTable, { supplier: sup, t }),
1191
+ h(TodayLine, { sup, t }),
1192
+ h(UsageSplit, { usage: sup.todayUsage, t }),
1193
+ h(SeasonBlock, { season, split: sup.seasonSplit, t }),
1194
+ h("div", { className: "qm-row-actions" }, h("button", { type: "button", onClick: () => onEdit(sup.id) }, t("openPage"))),
1195
+ Array.isArray(sup.usageDays) && sup.usageDays.length
1196
+ ? h(UsageChart, { sup, days: sup.usageDays, quota, windowTotal: sup.usageDays.reduce((sum, day) => sum + (Number(day?.total) || 0), 0), t })
1197
+ : null) : null);
1198
+ }
1199
+
1200
+ function MetricTable({ supplier, t }) {
1201
+ const groups = metricRowsOf(supplier, t);
1202
+ if (!groups.length) return h("div", { className: "qm-empty-line" }, t("notQueried"));
1203
+ return h("div", { className: "qm-metric-tables" }, groups.map((group) =>
1204
+ h("table", { key: group.kind, className: "qm-metric-table", "aria-label": t(group.titleKey) },
1205
+ h("thead", null, h("tr", null, group.columns.map((column) => h("th", { key: column.key, scope: "col" }, t(column.labelKey))))),
1206
+ h("tbody", null, group.rows.map((row) =>
1207
+ h("tr", { key: row.key, title: row.aria },
1208
+ h("th", { scope: "row" }, row.name),
1209
+ group.columns.slice(1).map((column) =>
1210
+ h("td", { key: column.key, className: column.key === "used" ? `qm-tone ${row.tone}` : column.key === "value" ? "qm-num" : "" }, row[column.key] ?? "—"))))))));
1211
+ }
1212
+
1213
+ function TodayLine({ sup, t }) {
1214
+ const total = fmtBig(typeof sup.todayTokens === "number" ? sup.todayTokens : 0);
1215
+ const ratio = usageRatioOf(sup.todayUsage);
1216
+ const detailText = ratio ? t("ratioAria", { hit: fmtBig(ratio.hitValue), miss: fmtBig(ratio.missValue), out: fmtBig(ratio.outValue) }) : "";
1217
+ return h("div", { className: "qm-today-line" },
1218
+ h("span", { className: "qm-today-text" }, t("today", { n: total })),
1219
+ ratio ? h("span", { className: "qm-ratio", title: detailText },
1220
+ h("b", { className: "r-hit" }, ratio.hit), " : ", h("b", { className: "r-miss" }, ratio.miss), " : ", h("b", { className: "r-out" }, ratio.out)) : null);
1221
+ }
1222
+
1223
+ /** 五分量分布:条与图例一一对应;今日比例只取前三项,写缓存与未细分在这里出现。 */
1224
+ function UsageSplit({ usage, t }) {
1225
+ const parts = splitPartsOf(usage);
1226
+ const total = parts.reduce((sum, part) => sum + part.value, 0);
1227
+ if (!total) return null;
1228
+ return h("div", { className: "qm-usage-split" },
1229
+ h("span", { className: "qm-split-bar qm-split-lg" }, parts.map((part) =>
1230
+ h("i", { key: part.key, className: `seg-${part.cls}`, style: { width: `${(part.value / total) * 100}%` } }))),
1231
+ h("div", { className: "qm-usage-legend" }, parts.map((part) =>
1232
+ h("span", { key: part.key }, h("i", { className: `seg-${part.cls}` }), `${t(part.label)} ${fmtBig(part.value)}`))));
1233
+ }
1234
+
1235
+ function SeasonBlock({ season, split, t }) {
1236
+ if (!season || !split) return null;
1237
+ const peak = Number(split.peakTokens) || 0;
1238
+ const valley = Number(split.valleyTokens) || 0;
1239
+ const unknown = Number(split.unknownTokens) || 0;
1240
+ const total = peak + valley + unknown;
1241
+ if (total <= 0) return null;
1242
+ const pct = (value) => `${Math.round((value / total) * 100)}%`;
1243
+ return h("div", { className: "qm-season-block", "data-qm-season-block": season.tier },
1244
+ h("div", { className: "qm-kv" }, h("span", null, t("seasonTier")), h("span", null, seasonLabelOf(season, t))),
1245
+ h("div", { className: "qm-kv" }, h("span", null, t("seasonNext")), h("span", null, seasonCountdown(season, t) || "—")),
1246
+ season.beijing && seasonUsesBeijingNote() ? h("div", { className: "qm-kv" }, h("span", null, t("seasonBeijingNow")), h("span", null, `${season.beijing.weekday} ${season.beijing.clock}`)) : null,
1247
+ h("div", { className: "qm-split-stats" },
1248
+ peak > 0 ? h("span", { className: "qm-split-stat" }, h("i", { className: "seg-warn" }), t("seasonSplitPeak", { n: fmtBig(peak), pct: pct(peak) })) : null,
1249
+ valley > 0 ? h("span", { className: "qm-split-stat" }, h("i", { className: "seg-ok" }), t("seasonSplitValley", { n: fmtBig(valley), pct: pct(valley) })) : null,
1250
+ unknown > 0 ? h("span", { className: "qm-split-stat" }, h("i", { className: "seg-unsplit" }), t("seasonSplitUnknown", { n: fmtBig(unknown) })) : null));
1251
+ }
1252
+
1253
+ // ---------- 供应商页:目录 + 全局设置 + 可添加 ----------
1254
+ function SuppliersView({ state, t, ctl }) {
1255
+ const all = state.suppliers || [];
1256
+ const added = all.filter((s) => s.added !== false).sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
1257
+ const addable = all.filter((s) => s.added === false).sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
1258
+ const det = state.detect || {};
1259
+ const density = useDensity();
1260
+ const [addableOpen, setAddableOpen] = React.useState(false);
1261
+ const [globalOpen, setGlobalOpen] = React.useState(!!state.season?.warning);
1262
+ React.useEffect(() => { if (ctl.freshIds.length) setAddableOpen(true); }, [ctl.freshIds]);
1263
+ React.useEffect(() => { if (state.season?.warning) setGlobalOpen(true); }, [state.season?.warning]);
1264
+ const scanLine = () => {
1265
+ const time = det.at ? String(det.at) : null;
1266
+ if (ctl.scanBusy) return h("span", null, t("scanLineBusy"));
1267
+ if (det.error) return h("span", { className: "err", title: String(det.error).slice(0, 300) },
1268
+ t("scanLineFail", { err: String(det.error || "").slice(0, 60) }), time ? ` · ${time}` : "");
1269
+ if (!det.at) return h("span", null, t("scanLineIdle"));
1270
+ return h("span", null, h("b", { className: "ok" }, t("connectedChip", { n: added.length })), time ? ` · ${time}` : "");
1271
+ };
1272
+ return h(React.Fragment, null,
1273
+ h("div", { className: "qm-pages-title qm-head-b" },
1274
+ h("b", null, t("supplierPages")),
1275
+ h("div", { className: "qm-title-actions" },
1276
+ h("span", { className: "chip" }, t("connectedChip", { n: added.length })),
1277
+ h("button", { type: "button", className: `qm-rescan-btn${ctl.scanBusy ? " busy" : ""}`, disabled: ctl.scanBusy, onClick: ctl.runRescan }, `⟳ ${t("rescan")}`))),
1278
+ h("div", { className: "qm-scanline" }, scanLine()),
1279
+ added.length ? orderedRows(added, t, ctl) : h(Empty, { text: t("emptyAdded"), action: t("rescan"), onAction: ctl.runRescan }),
1280
+ addable.length ? h("details", { className: "qm-addable", open: addableOpen, onToggle: (e) => setAddableOpen(e.currentTarget.open) },
1281
+ h("summary", null, h("span", null, t("addableTitle")), h("span", { className: "cnt" }, addable.length)),
1282
+ h("div", { className: "addable-list" }, addable.map((a) => h("div", { key: a.id, className: `qm-add-row${ctl.freshIds.includes(a.id) ? " fresh" : ""}` },
1283
+ h("span", { className: `qm-dot ${stateClass(a)}` }),
1284
+ h("span", { className: "qm-page-name" }, a.name),
1285
+ h("span", { className: "qm-page-pill" }, t(a.meta?.credentialLabelKey || "apiKey")),
1286
+ h("button", { type: "button", className: "s-test qm-pri-soft", onClick: () => ctl.openSupplier(a.id) }, t("openPage")))))) : null,
1287
+ state.detectedUnmapped && state.detectedUnmapped.length
1288
+ ? h("div", { className: "qm-unmapped", title: state.detectedUnmapped.map((u) => `${u.displayName || u.route}${u.detail ? t("unmappedDetail", { detail: u.detail }) : ""}`).join("、") },
1289
+ `${t("unmapped")} ${state.detectedUnmapped.length}`) : null,
1290
+ state.season?.warning ? h("div", { className: "qm-season-warn", role: "status" }, state.season.warning) : null,
1291
+ h("details", { className: "s-group qm-global", open: globalOpen, onToggle: (e) => setGlobalOpen(e.currentTarget.open) },
1292
+ h("summary", null, t("global")),
1293
+ h("div", { className: "s-grid" },
1294
+ h("label", null, t("interval"), h("input", { type: "number", min: 10, max: 3600, value: ctl.globalForm?.intervalSeconds ?? 60, disabled: ctl.globalBusy, onChange: (e) => ctl.setGlobalForm((g) => ({ ...g, intervalSeconds: e.target.value })) })),
1295
+ h("label", null, t("retention"), h("input", { type: "number", min: 1, max: 90, value: ctl.globalForm?.retentionDays ?? 7, disabled: ctl.globalBusy, onChange: (e) => ctl.setGlobalForm((g) => ({ ...g, retentionDays: e.target.value })) }))),
1296
+ h("label", { className: "qm-holidays" }, h("span", null, t("holidaysLabel"), h(InfoHint, { t, text: t("holidaysHint") })),
1297
+ h("textarea", { rows: 4, spellCheck: false, placeholder: t("holidaysPlaceholder"), "aria-label": t("holidaysLabel"), disabled: ctl.globalBusy,
1298
+ value: ctl.globalForm?.holidays ?? "", onChange: (e) => ctl.setGlobalForm((g) => ({ ...g, holidays: e.target.value })) })),
1299
+ h("div", { className: "s-row", style: { justifyContent: "flex-end" } },
1300
+ h("button", { type: "button", className: "qm-pri", disabled: ctl.globalBusy, onClick: ctl.saveGlobal }, t("save")))),
1301
+ h("div", { className: "qm-display-row" },
1302
+ h("span", null, t("sidebarDisplay"), h(InfoHint, { t, text: t("browserOnly") })),
1303
+ h("select", { "aria-label": t("sidebarDisplay"), value: density, onChange: e => preferences.set(e.target.value) },
1304
+ h("option", { value: "expanded" }, t("expanded")), h("option", { value: "compact" }, t("compact")))));
1305
+ }
1306
+
1307
+ function orderedRows(added, t, ctl) {
1308
+ return h("div", { className: "qm-page-list" }, added.map((sup) =>
1309
+ h("div", { key: sup.id, "data-supplier": sup.id, className: "qm-page-row" },
1310
+ h("div", { className: "qm-page-main" },
1311
+ h("span", { className: `qm-dot ${stateClass(sup)}` }),
1312
+ h("span", { className: "qm-page-name", title: sup.meta?.compat ? t("compatSource") : undefined }, sup.name),
1313
+ h("span", { className: "qm-row-metric" }, selectPrimaryMetric(sup, t).value),
1314
+ h("span", { className: `qm-pill ${stateClass(sup)}` }, supplierStatus(sup, t)),
1315
+ h("span", { className: "qm-page-pill" }, t(sup.meta?.credentialLabelKey || "apiKey"))),
1316
+ h("div", { className: "qm-page-actions" },
1317
+ h("label", { className: "qm-page-toggle" },
1318
+ h("input", { type: "checkbox", checked: !!sup.enabled, disabled: !!ctl.toggling[sup.id] || [...settingsWrites].some(operation => operation.supplierId === sup.id), onChange: () => ctl.toggleEnabled(sup) }),
1319
+ h("span", null, t("enable"))),
1320
+ h("button", { type: "button", className: "s-test qm-pri-soft", onClick: () => ctl.openSupplier(sup.id) }, t("openPage"))))));
1321
+ }
1322
+
1323
+ // ---------- 供应商配置子页 ----------
1324
+ function needsLabel(sup, need, t) {
1325
+ if (need.key === "apiKey") return t(sup.meta?.credentialLabelKey || "apiKey");
1326
+ if (need.key === "allowanceToken") return t("allowanceToken");
1327
+ if (need.key === "orgId") return t("orgId");
1328
+ return need.label || need.key;
1329
+ }
1330
+ function secretPlaceholder(sup, need, t) {
1331
+ if (sup[`${need.key}Set`]) return t("keySet");
1332
+ if (need.key === "apiKey" && sup.apiKeyEnv) return sup.keyRefResolved ? t("keyRefResolved", { env: sup.apiKeyEnv }) : t("keyRefMissing", { env: sup.apiKeyEnv });
1333
+ if (need.key === "apiKey" && sup.autoDetected && sup.envKeySet) return t("keyAuto", { env: sup.autoEnvName || t("dshKey") });
1334
+ return t("keyEmpty");
1335
+ }
1336
+ function testResultOf(testState, id, t) {
1337
+ const result = testState[id];
1338
+ if (!result) return null;
1339
+ if (typeof result === "string") return h("span", { className: "s-test-res bad" }, result);
1340
+ return h("span", { className: `s-test-res ${result.ok ? "ok" : "bad"}` }, result.ok ? t("testOk") : (result.error || t("testFail")));
1341
+ }
1342
+
1343
+ function SupplierEditor({ state, t, ctl }) {
1344
+ const sup = (state.suppliers || []).find((s) => s.id === ctl.view.id);
1345
+ const editor = ctl.editor;
1346
+ if (!sup || !editor) return h("div", { className: "qm-sub", role: "status" }, t("loading"));
1347
+ const f = editor.form;
1348
+ const needsInputs = (sup.meta?.needs || []).map((need) =>
1349
+ h("label", { key: need.key }, needsLabel(sup, need, t),
1350
+ h("input", {
1351
+ type: need.secret ? "password" : "text",
1352
+ placeholder: need.secret ? secretPlaceholder(sup, need, t) : t("keyEmpty"),
1353
+ value: f[need.key] || "",
1354
+ disabled: ctl.opBusy,
1355
+ onChange: (e) => ctl.setEditorField(need.key, e.target.value),
1356
+ })));
1357
+ return h(React.Fragment, null,
1358
+ h("div", { className: "qm-page-head" },
1359
+ h("button", { type: "button", className: "s-test", onClick: ctl.closeEditor }, `← ${t("back")}`),
1360
+ h("b", null, sup.name),
1361
+ h("label", { className: "qm-inline-toggle" },
1362
+ h("input", { type: "checkbox", checked: !!f.enabled, disabled: ctl.opBusy, onChange: (e) => ctl.setEditorField("enabled", e.target.checked) }),
1363
+ h("span", null, t("enable"))),
1364
+ h("span", { className: `qm-pill ${stateClass(sup)}` }, supplierStatus(sup, t)),
1365
+ h("span", { className: "qm-page-pill" }, t(sup.meta?.credentialLabelKey || "apiKey"))),
1366
+ h("div", { className: "s-group qm-quota-preview" },
1367
+ h("div", { className: "qm-section-head" }, h("h5", null, t("currentQuota")), h(InfoHint, { t, text: t("previewSaved") })),
1368
+ h(MetricTable, { supplier: sup, t })),
1369
+ h("div", { className: "s-group" },
1370
+ h("div", { className: "qm-section-head" }, h("h5", null, t("credentials")), h(InfoHint, { t, text: t("settingsSub") })),
1371
+ needsInputs,
1372
+ h("label", null, h("span", null, t("apiKeyEnv"), h(InfoHint, { t, text: t("apiKeyEnvHint") })),
1373
+ h("input", { type: "text", placeholder: t("apiKeyEnvPlaceholder"), value: f.apiKeyEnv || "", disabled: ctl.opBusy, onChange: (e) => ctl.setEditorField("apiKeyEnv", e.target.value) })),
1374
+ sup.apiKeyEnv && !sup.apiKeySet ? h("span", { className: "qm-ref-state" }, t(sup.keyRefResolved ? "keyRefResolved" : "keyRefMissing", { env: sup.apiKeyEnv })) : null),
1375
+ h(WatchedLimits, { supplier: sup, form: f, t, disabled: ctl.opBusy, onChange: (keys) => ctl.setEditorField("displayKeys", keys) }),
1376
+ h("details", { ref: ctl.advancedRef, className: "s-group qm-advanced", open: ctl.advanced, onToggle: e => ctl.setAdvanced(e.currentTarget.open) },
1377
+ h("summary", null, t("advanced")),
1378
+ h("label", null, t("baseUrl"), h("input", { type: "text", value: f.baseUrl || "", disabled: ctl.opBusy, onChange: (e) => ctl.setEditorField("baseUrl", e.target.value) })),
1379
+ h("div", { className: "s-grid" },
1380
+ h("label", null, t("warnPct"), h("input", { type: "number", min: 1, max: 99, value: f.warnPct, disabled: ctl.opBusy, onChange: (e) => ctl.setEditorField("warnPct", e.target.value) })),
1381
+ h("label", null, t("critPct"), h("input", { type: "number", min: 1, max: 100, value: f.critPct, disabled: ctl.opBusy, onChange: (e) => ctl.setEditorField("critPct", e.target.value) })))),
1382
+ h("div", { className: "s-row" },
1383
+ h("button", { type: "button", className: "s-test", disabled: ctl.opBusy || ctl.testBusy === sup.id, onClick: () => ctl.runTest(sup.id) }, ctl.testBusy === sup.id ? t("testing") : `⟳ ${t("test")}`),
1384
+ testResultOf(ctl.testState, sup.id, t)),
1385
+ h("div", { className: "s-actions" },
1386
+ ctl.saved === sup.id ? h("span", { className: "s-saved" }, t("saved")) : null,
1387
+ h("button", { type: "button", onClick: ctl.closeEditor, disabled: ctl.opBusy }, t("cancel")),
1388
+ h("button", { type: "button", className: "qm-pri", onClick: ctl.saveSupplier, disabled: ctl.opBusy }, t("save"))));
1389
+ }
1390
+
1391
+ /** 关注限额:供应商卡片第 2 行画哪些条目(有序多选)。 */
1392
+ function WatchedLimits({ supplier, form, t, disabled, onChange }) {
1393
+ const available = (supplier.entries || []).filter((e) => e?.key && Number.isFinite(e?.pct));
1394
+ const byKey = new Map(available.map((e) => [e.key, e]));
1395
+ const watchedKeys = Array.isArray(form.displayKeys) ? form.displayKeys : [];
1396
+ const rows = [
1397
+ ...watchedKeys.map((key) => ({ key, entry: byKey.get(key) || null, watched: true })),
1398
+ ...available.filter((e) => !watchedKeys.includes(e.key)).map((e) => ({ key: e.key, entry: e, watched: false })),
1399
+ ];
1400
+ if (!rows.length) return null;
1401
+ const toggle = (key, on) => onChange(on ? [...watchedKeys, key] : watchedKeys.filter((k) => k !== key));
1402
+ const move = (index, delta) => {
1403
+ const target = index + delta;
1404
+ if (index < 0 || target < 0 || target >= watchedKeys.length) return;
1405
+ const next = [...watchedKeys];
1406
+ [next[index], next[target]] = [next[target], next[index]];
1407
+ onChange(next);
1408
+ };
1409
+ return h("div", { className: "s-group" },
1410
+ h("div", { className: "qm-section-head" }, h("h5", null, t("watchTitle")), h(InfoHint, { t, text: t("watchDefaultHint") })),
1411
+ watchedKeys.length ? null : h("p", { className: "qm-empty-line" }, t("watchDefaultShort")),
1412
+ h("div", { className: "qm-watch" }, rows.map(({ key, entry, watched }) => {
1413
+ const index = watchedKeys.indexOf(key);
1414
+ return h("div", { key, className: `w-row${watched ? " watched" : ""}${entry ? "" : " off"}` },
1415
+ h("input", { type: "checkbox", checked: watched, disabled, onChange: (e) => toggle(key, e.target.checked) }),
1416
+ h("span", { className: "w-name", title: entry?.name || key }, entry?.name || key),
1417
+ h("span", { className: "w-val" }, entry ? pctText(entry.pct) : t("watchUnavailable")),
1418
+ h("span", { className: "w-move" },
1419
+ h("button", { type: "button", disabled: disabled || index <= 0, "aria-label": t("moveUp"), title: t("moveUp"), onClick: () => move(index, -1) }, "↑"),
1420
+ h("button", { type: "button", disabled: disabled || index >= watchedKeys.length - 1, "aria-label": t("moveDown"), title: t("moveDown"), onClick: () => move(index, 1) }, "↓")));
1421
+ })));
1422
+ }
1423
+
1424
+ function HistoryTable({ rows, t }) {
1425
+ if (!rows.length) return null;
1426
+ return h("details", { className: "qm-history" }, h("summary", { tabIndex: 0 }, t("historySummary", { n: rows.length })),
1427
+ h("div", { className: "qm-history-scroll", tabIndex: 0, role: "region", "aria-label": t("historySummary", { n: rows.length }) },
1428
+ h("table", null,
1429
+ h("thead", null, h("tr", null, ...["colTime", "colSupplier", "colTier", "colResult", "colMain", "colNote"].map(key => h("th", { key, scope: "col" }, t(key))))),
1430
+ h("tbody", null, rows.map((row, i) => h("tr", { key: i }, h("td", null, row.t), h("td", null, row.supplier),
1431
+ h("td", { className: row.tier === "peak" ? "h-peak" : row.tier === "valley" ? "h-valley" : "" },
1432
+ row.tier === "peak" ? t("seasonPeak") : row.tier === "valley" ? t("seasonValley") : "—"),
1433
+ h("td", { className: row.ok ? "h-ok" : "h-bad" }, t(row.ok ? "colOk" : "colFail")), h("td", null, row.summary), h("td", null, row.error || "")))))));
1434
+ }
1435
+
1436
+ /**
1437
+ * 一张图两套量纲:柱 = 每日 token 消耗(左轴,总量),线 = 各窗口剩余额度(右轴,固定 0–100%)。
1438
+ * 共用一条时间轴,所以「今天烧了多少」和「这个窗口还剩多少」能直接对着看。
1439
+ */
1440
+ function UsageChart({ sup, days, quota, windowTotal, t }) {
1441
+ const domain = chartDomainOf(days);
1442
+ const [cursor, setCursor] = React.useState(null);
1443
+ if (!domain) return null;
1444
+ const legend = quotaLegendOf(quota, sup.entries, t);
1445
+ const W = 600, H = 120, padL = 4, padR = 6, padT = 10, padB = 6;
1446
+ const plotW = W - padL - padR, plotH = H - padT - padB;
1447
+ const scaleX = (ms) => padL + plotW * Math.min(1, Math.max(0, (ms - domain.start) / (domain.end - domain.start)));
1448
+ const scaleY = (pct) => padT + plotH * (Math.max(0, Math.min(100, Number(pct) || 0)) / 100);
1449
+ const px = (ms) => `${((scaleX(ms) / W) * 100).toFixed(3)}%`;
1450
+ const py = (pct) => `${((scaleY(pct) / H) * 100).toFixed(3)}%`;
1451
+ const maxDay = Math.max(...days.map((day) => Number(day?.total) || 0), 1);
1452
+ /** 每日柱的几何:柱、标签、刻度共用同一套坐标,避免两处公式漂移。 */
1453
+ const dayBars = days.map((day, index) => {
1454
+ const start = dayStartOf(day?.day);
1455
+ if (!Number.isFinite(start)) return null;
1456
+ const end = Math.min(start + 24 * 3600_000, domain.end);
1457
+ const total = Math.max(0, Number(day?.total) || 0);
1458
+ const height = plotH * (total / maxDay);
1459
+ const x0 = scaleX(start), x1 = scaleX(end);
1460
+ return { day, index, total, height, x0, x1, x: x0 + 0.75, width: Math.max(0.5, x1 - x0 - 1.5) };
1461
+ }).filter(Boolean);
1462
+ const visibleBars = dayBars.filter((bar) => bar.height > 0);
1463
+ // 标签密度:最多 10 个;更长的窗口只标峰值那根,避免 30/90 天糊成一片
1464
+ const labeledBars = visibleBars.length <= 10 ? visibleBars : [visibleBars.slice(1).reduce(
1465
+ (best, bar) => (bar.total > best.total ? bar : best), visibleBars[0])];
1466
+ const summary = [
1467
+ `${t("statsWindow", { n: days.length })} token ${fmtBig(windowTotal)}`,
1468
+ legend.length ? legend.map((item) => `${item.label} ${t("remainLabel", { n: item.remaining })}`).join(" · ") : null,
1469
+ ].filter(Boolean).join(";");
1470
+ const cursorDay = cursor === null ? null : days.find((day) => {
1471
+ const start = dayStartOf(day?.day);
1472
+ return Number.isFinite(start) && cursor >= start && cursor < start + 24 * 3600_000;
1473
+ });
1474
+ const readout = cursor === null ? [] : legend.map((item) => {
1475
+ const used = quotaUsedAt(item.samples, cursor);
1476
+ return used === null ? null : { key: item.key, label: item.label, color: item.color, remaining: Math.round(100 - used) };
1477
+ }).filter(Boolean);
1478
+ const tipX = cursor === null ? 0 : (scaleX(cursor) / W) * 100;
1479
+ const sampleTimes = legend.flatMap((item) => item.samples.map(([at]) => at));
1480
+ const snap = (at) => {
1481
+ const limit = ((domain.end - domain.start) * 8) / plotW;
1482
+ let best = null, gap = Infinity;
1483
+ for (const time of sampleTimes) {
1484
+ const distance = Math.abs(time - at);
1485
+ if (distance < gap) { gap = distance; best = time; }
1486
+ }
1487
+ return best !== null && gap <= limit ? best : at;
1488
+ };
1489
+ return h("div", { className: "qm-chart" },
1490
+ h("div", { className: "qm-chart-cap" }, h("span", null, `${t("statsWindow", { n: days.length })} ${fmtBig(windowTotal)} token`)),
1491
+ h("div", {
1492
+ className: "qm-chart-plot", role: "img", "aria-label": summary, "data-qm-chart": sup.id, tabIndex: 0,
1493
+ onPointerMove: (ev) => {
1494
+ const box = ev?.currentTarget?.getBoundingClientRect?.();
1495
+ if (!box?.width) return;
1496
+ const ratio = Math.min(1, Math.max(0, (ev.clientX - box.left) / box.width));
1497
+ const stepped = Math.round(ratio * W) / W;
1498
+ setCursor(snap(domain.start + stepped * (domain.end - domain.start)));
1499
+ },
1500
+ onPointerLeave: (ev) => { if (ev?.pointerType !== "touch") setCursor(null); },
1501
+ onKeyDown: (ev) => {
1502
+ if (ev.key !== "ArrowLeft" && ev.key !== "ArrowRight") return;
1503
+ ev.preventDefault();
1504
+ const stepMs = (domain.end - domain.start) / 48;
1505
+ const from = cursor === null ? domain.end : cursor;
1506
+ setCursor(Math.min(domain.end, Math.max(domain.start, from + (ev.key === "ArrowLeft" ? -stepMs : stepMs))));
1507
+ },
1508
+ onBlur: () => setCursor(null),
1509
+ },
1510
+ h("svg", { viewBox: `0 0 ${W} ${H}`, preserveAspectRatio: "none", "aria-hidden": "true", focusable: "false" },
1511
+ visibleBars.map((bar) => h("rect", { key: bar.day?.day || bar.index, className: "qm-chart-bar", x: bar.x.toFixed(1),
1512
+ y: (padT + plotH - bar.height).toFixed(1), width: bar.width.toFixed(1), height: bar.height.toFixed(1), rx: 1.5 })),
1513
+ h("line", { className: "qm-chart-grid", x1: padL, x2: W - padR, y1: padT, y2: padT }),
1514
+ h("line", { className: "qm-chart-axis", x1: padL, x2: W - padR, y1: padT + plotH, y2: padT + plotH }),
1515
+ legend.flatMap((item) => item.segments.filter((segment) => segment.length > 1).map((segment, index) =>
1516
+ h("polyline", { key: `${item.key}-${index}`, className: "qm-chart-line", fill: "none",
1517
+ stroke: item.color, "vector-effect": "non-scaling-stroke",
1518
+ points: segment.map(([at, pct]) => `${scaleX(at).toFixed(1)},${scaleY(pct).toFixed(1)}`).join(" ") })))),
1519
+ h("svg", { className: "qm-chart-overlay", "aria-hidden": "true", focusable: "false" },
1520
+ legend.flatMap((item) => item.segments.slice(1).map((segment, index) => {
1521
+ const previous = item.segments[index];
1522
+ const from = previous[previous.length - 1], to = segment[0];
1523
+ return h("line", { key: `${item.key}-drop-${index}`, className: "qm-chart-drop", stroke: item.color,
1524
+ x1: px(from[0]), y1: py(from[1]), x2: px(to[0]), y2: py(to[1]) });
1525
+ })),
1526
+ legend.flatMap((item) => item.samples.map(([at, pct], index) =>
1527
+ h("circle", { key: `${item.key}-dot-${index}`, className: at === cursor ? "qm-chart-dot is-on" : "qm-chart-dot",
1528
+ cx: px(at), cy: py(pct), r: at === cursor ? 3.2 : 2, fill: item.color }))),
1529
+ cursor === null ? null : h("line", { className: "qm-chart-cursor", x1: px(cursor), y1: py(100), x2: px(cursor), y2: py(0) })),
1530
+ labeledBars.length ? h("div", { className: "qm-chart-labels", "aria-hidden": "true" }, labeledBars.map((bar) => {
1531
+ const inside = bar.height >= plotH * 0.18;
1532
+ const top = ((padT + plotH - bar.height) / H) * 100;
1533
+ const left = ((bar.x + bar.width / 2) / W) * 100;
1534
+ return h("span", { key: bar.day?.day || bar.index, className: "qm-chart-value",
1535
+ style: { left: `${left.toFixed(3)}%`, top: `calc(${top.toFixed(3)}% ${inside ? "+" : "-"} 3px)`,
1536
+ transform: `translate(-50%, ${inside ? "0" : "-100%"})` } }, fmtBig(bar.total));
1537
+ })) : null,
1538
+ cursor === null ? null : h("div", { className: "qm-chart-tip", "aria-hidden": "true",
1539
+ style: { left: `${tipX.toFixed(2)}%`, transform: `translateX(${tipX < 20 ? "0" : tipX > 80 ? "-100%" : "-50%"})` } },
1540
+ h("b", null, clockOf(cursor)),
1541
+ cursorDay && Number(cursorDay.total) > 0 ? h("span", { className: "qm-chart-tip-tok" }, `${fmtBig(Number(cursorDay.total))} token`) : null,
1542
+ readout.map((row) => h("span", { key: row.key, className: "qm-chart-tip-row" },
1543
+ h("i", { style: { background: row.color } }), `${row.label} ${t("remainLabel", { n: row.remaining })}`)))),
1544
+ h("div", { className: "qm-chart-ticks", "aria-hidden": "true" }, days.map((day, index) => {
1545
+ const start = dayStartOf(day?.day);
1546
+ if (!Number.isFinite(start)) return null;
1547
+ const end = Math.min(start + 24 * 3600_000, domain.end);
1548
+ const center = (start + end) / 2;
1549
+ const fraction = (center - domain.start) / (domain.end - domain.start);
1550
+ const left = ((padL + plotW * fraction) / W) * 100;
1551
+ return h("span", { key: day?.day || index, className: "qm-chart-tick", style: { left: `${left.toFixed(2)}%` } },
1552
+ String(day?.day || "").slice(5));
1553
+ })),
1554
+ legend.length ? h("div", { className: "qm-chart-legend" }, legend.map((item) =>
1555
+ h("span", { key: item.key, className: "qm-chart-key", "data-qm-line": item.key },
1556
+ h("i", { style: { background: item.color } }), `${item.label} ${t("remainLabel", { n: item.remaining })}`))) : null);
1557
+ }
1558
+
1559
+ function SettingsSection({ t }) {
1560
+ const panel = useSurface();
1561
+ // 用 passive effect:useSyncExternalStore 的订阅在 layout 阶段之后才生效,
1562
+ // 在 layout effect 里 attachPage 会让宿主页错过第一次快照,直到保存结束才挂上。
1563
+ React.useEffect(() => {
1564
+ surface.attachPage();
1565
+ return () => surface.detachPage();
1566
+ }, []);
1567
+ return panel.host === "page" ? h(PanelHost, { t, host: "page", onClose: () => {} }) : null;
1568
+ }
1569
+ // ---------- 通用小 hook ----------
1570
+ function useDialog(onClose, returnFocusRef, enabled = true) {
1571
+ const ref = React.useRef(null);
1572
+ const close = React.useRef(onClose);
1573
+ close.current = onClose;
1574
+ React.useEffect(() => {
1575
+ const node = ref.current;
1576
+ if (!node || !enabled) return;
1577
+ const previous = document.activeElement;
1578
+ const focusable = () => Array.from(node.querySelectorAll(
1579
+ 'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex="0"]',
1580
+ )).filter((el) => el.getClientRects().length > 0);
1581
+ (focusable()[0] || node).focus();
1582
+ const onKey = (event) => {
1583
+ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); close.current(); }
1584
+ if (event.key !== "Tab") return;
1585
+ const items = focusable(), first = items[0], last = items[items.length - 1];
1586
+ if (!first) { event.preventDefault(); node.focus(); }
1587
+ else if (event.shiftKey && (document.activeElement === first || !node.contains(document.activeElement) || document.activeElement === node)) {
1588
+ event.preventDefault(); last.focus();
1589
+ } else if (!event.shiftKey && (document.activeElement === last || !node.contains(document.activeElement) || document.activeElement === node)) {
1590
+ event.preventDefault(); first.focus();
1591
+ }
1592
+ };
1593
+ document.addEventListener("keydown", onKey, true);
1594
+ return () => {
1595
+ document.removeEventListener("keydown", onKey, true);
1596
+ // 对话框关闭后返回持久的侧栏入口。
1597
+ const target = returnFocusRef?.current || previous;
1598
+ if (target?.isConnected) target.focus();
1599
+ };
1600
+ }, [enabled]);
1601
+ return ref;
1602
+ }
1603
+
1604
+ // ---------- 本地化 ----------
1605
+ const LOCALES = {
1606
+ zh: {
1607
+ current: "当前",
1608
+ moreInfo: "说明",
1609
+ colMetric: "指标",
1610
+ colLimit: "限额",
1611
+ colReset: "重置",
1612
+ colValue: "数值",
1613
+ colPeriod: "周期",
1614
+ watchDefaultShort: "未选:默认周窗口",
1615
+ overviewEmpty: "尚未添加供应商",
1616
+ manageSuppliers: "管理供应商",
1617
+ errorDetails: "错误详情",
1618
+ resetUnavailable: "重置时间未公布",
1619
+ unlimited: "未设额度上限",
1620
+ accountBalance: "账户余额",
1621
+ overview: "概览",
1622
+ suppliers: "供应商",
1623
+ expanded: "完整",
1624
+ compact: "紧凑",
1625
+ sidebarDisplay: "侧栏显示",
1626
+ browserOnly: "仅当前浏览器,选择后立即生效",
1627
+ expand: "展开",
1628
+ collapse: "收起",
1629
+ balance: "余额",
1630
+ cost: "报告费用",
1631
+ usage: "报告用量",
1632
+ moreMetrics: "另有 {n} 项",
1633
+ staleFailure: "更新失败 · 上次数据",
1634
+ unavailable: "暂时无法获取",
1635
+ disabled: "未启用",
1636
+ notQueried: "尚未查询",
1637
+ lastSuccess: "数据时间",
1638
+ todayScope: "当前供应商的今日 Token 用量,按宿主本地日统计",
1639
+ eventsObserved: "已观测到调用事件",
1640
+ previewSaved: "已保存配置的最近查询结果;编辑草稿不会改变此预览。",
1641
+ advanced: "高级选项",
1642
+ unsaved: "存在未保存的修改",
1643
+ keepEditing: "继续编辑",
1644
+ discard: "放弃修改",
1645
+ all: "全部",
1646
+ attention: "需关注",
1647
+ noAttention: "暂无需要关注的供应商",
1648
+ loading: "正在获取数据…",
1649
+ invalidThreshold: "阈值必须满足 1 ≤ 警告 < 临界 ≤ 100",
1650
+ invalidGlobal: "轮询间隔应为 10–3600 秒,保留期应为 1–90 天。",
1651
+ invalidHolidays: "节假日日期应为 YYYY-MM-DD:{list}",
1652
+
1653
+ // ---- 峰谷计费时段(峰值/谷值判定在宿主 lib/season.js,客户端只展示) ----
1654
+ seasonPeak: "峰价",
1655
+ seasonValley: "谷价",
1656
+ seasonHoliday: "法定节假日",
1657
+ seasonWeekend: "周末",
1658
+ seasonTier: "计费时段",
1659
+ seasonNext: "下次切换",
1660
+ seasonBeijingNow: "北京时间",
1661
+ seasonBeijingOnly: "按北京时间判定",
1662
+ seasonFlipInM: "{m} 分钟后切换",
1663
+ seasonFlipInHM: "{h}h{m}m 后切换",
1664
+ seasonFlipInDH: "{d}d{h}h 后切换",
1665
+ seasonFlipSoon: "即将切换",
1666
+ seasonSplitLabel: "今日按时段",
1667
+ seasonSplitPeak: "高峰 {n}({pct})",
1668
+ seasonSplitValley: "空闲 {n}({pct})",
1669
+ seasonSplitUnknown: "未标记 {n}",
1670
+ holidaysLabel: "节假日覆盖表(每行一个日期)",
1671
+ holidaysPlaceholder: "2027-01-01\n2027-02-06",
1672
+ holidaysHint: "留空使用内置表。内置表按国务院公布的年度安排维护;缺次年时工作日假期会被误判为峰价,粘贴覆盖表可即时修正。",
1673
+
1674
+ // ---- 常驻卡片:plan 名 + 周窗口进度条 ----
1675
+ weekTag: "周",
1676
+ barAria: "{name} 已用 {pct}",
1677
+
1678
+ title: "用量监控",
1679
+ connWarn: "已连接 · 降级",
1680
+ connStandby: "待命",
1681
+ resetInHM: "{h}h{m}m 后重置",
1682
+ resetInDH: "{d}d{h}h 后重置",
1683
+ // 卡片条上的裸倒计时:不带叙述词,靠列对齐与弱色表达归属
1684
+ resetHM: "{h}h{m}m",
1685
+ resetDH: "{d}d{h}h",
1686
+ resetSoon: "即将重置",
1687
+ watchTitle: "关注限额",
1688
+ watchUnavailable: "当前不可用",
1689
+ watchDefaultHint: "不勾选时按默认规则:周窗口优先,缺少周窗口取已用比例最高的有效窗口。",
1690
+ moveUp: "上移",
1691
+ moveDown: "下移",
1692
+ todayLabel: "今日",
1693
+ noneActive: "暂无调用",
1694
+ today: "今日用量 {n} tokens",
1695
+ todayShort: "今日 {n}",
1696
+ statsWindow: "近 {n} 天",
1697
+ remainLabel: "剩余 {n}%",
1698
+ ratioAria: "缓存命中 {hit} · 缓存未命中 {miss} · 输出 {out}",
1699
+ cacheHit: "缓存命中",
1700
+ cacheMiss: "缓存未命中",
1701
+ outputLabel: "输出",
1702
+ cacheWrite: "缓存写入",
1703
+ unsplit: "未细分",
1704
+ refresh: "刷新",
1705
+ refreshing: "刷新中…",
1706
+ close: "关闭",
1707
+ cancel: "取消",
1708
+ save: "保存",
1709
+ saved: "已保存 ✓",
1710
+ stateOk: "正常",
1711
+ stateWarn: "警告",
1712
+ stateCrit: "临界",
1713
+ stateErr: "取数失败",
1714
+ stateOff: "未配置",
1715
+ quota: "限额",
1716
+ usedShort: "已用",
1717
+ detailTitle: "明细",
1718
+ historySummary: "刷新历史(最近 {n} 条)",
1719
+ colTime: "时间",
1720
+ colSupplier: "供应商",
1721
+ colResult: "结果",
1722
+ colOk: "成功",
1723
+ colFail: "失败",
1724
+ colMain: "主指标",
1725
+ colNote: "备注",
1726
+ colTier: "时段",
1727
+ settingsSub: "密钥保存在 DSH 配置中,此处不显示原文;留空可保留已有密钥",
1728
+ global: "全局设置",
1729
+ supplierPages: "供应商",
1730
+ rescan: "重新扫描",
1731
+ connectedChip: "已接入 {n}",
1732
+ scanLineBusy: "扫描中…",
1733
+ scanLineIdle: "未扫描",
1734
+ scanLineFail: "扫描失败:{err}",
1735
+ addableTitle: "可添加供应商",
1736
+ addableCount: "{n} 个",
1737
+ emptyAdded: "尚未接入供应商",
1738
+ openPage: "配置",
1739
+ back: "返回",
1740
+ credentials: "凭据",
1741
+ compatSource: "兼容来源",
1742
+
1743
+ enable: "启用",
1744
+ test: "测试连接",
1745
+ testing: "测试中…",
1746
+ testOk: "连接正常",
1747
+ testFail: "失败",
1748
+ apiKey: "API Key",
1749
+ managementKey: "Management Key",
1750
+ adminKey: "Admin Key",
1751
+ codingPlanKey: "Coding Plan Key",
1752
+ tokenPlanKey: "Token Plan Key",
1753
+ currentQuota: "当前额度(最近一次取数)",
1754
+ unmappedDetail: "({detail})",
1755
+ keySet: "已设置(留空保持不变)",
1756
+ keyEmpty: "未设置",
1757
+ keyAuto: "自动读取 {env}",
1758
+ apiKeyEnv: "凭据引用",
1759
+ apiKeyEnvPlaceholder: "如 COMMAND_CODE_API_KEY",
1760
+ apiKeyEnvHint: "填 DSH 凭据库里的记录名或环境变量名;密钥本体不写进本插件配置。",
1761
+ keyRefResolved: "引用 {env}(已解析)",
1762
+ keyRefMissing: "引用 {env}(未解析)",
1763
+ dshKey: "DSH 密钥",
1764
+ allowanceToken: "allowance Token(OAuth)",
1765
+ orgId: "org id(可选)",
1766
+ baseUrl: "Base URL",
1767
+ warnPct: "警告阈值 %",
1768
+ critPct: "临界阈值 %",
1769
+ interval: "轮询间隔(秒,10–3600)",
1770
+ retention: "用量保留期(天,1–90)",
1771
+ unmapped: "另探测到 DSH 内已添加但本插件暂不支持的供应商",
1772
+ },
1773
+ en: {
1774
+ current: "Current",
1775
+ moreInfo: "More info",
1776
+ colMetric: "Metric",
1777
+ colLimit: "Limit",
1778
+ colReset: "Resets",
1779
+ colValue: "Value",
1780
+ colPeriod: "Period",
1781
+ watchDefaultShort: "None selected — weekly window",
1782
+ overviewEmpty: "No suppliers yet",
1783
+ manageSuppliers: "Manage suppliers",
1784
+ errorDetails: "Error details",
1785
+ resetUnavailable: "Reset time unavailable",
1786
+ unlimited: "No quota limit",
1787
+ accountBalance: "Account balance",
1788
+ overview: "Overview",
1789
+ suppliers: "Suppliers",
1790
+ expanded: "Expanded",
1791
+ compact: "Compact",
1792
+ sidebarDisplay: "Sidebar display",
1793
+ browserOnly: "Only this browser; changes apply immediately",
1794
+ expand: "Expand",
1795
+ collapse: "Collapse",
1796
+ balance: "Balance",
1797
+ cost: "Reported cost",
1798
+ usage: "Reported usage",
1799
+ moreMetrics: "{n} more",
1800
+ staleFailure: "Update failed · previous data",
1801
+ unavailable: "Temporarily unavailable",
1802
+ disabled: "Disabled",
1803
+ notQueried: "Not queried yet",
1804
+ lastSuccess: "Data updated",
1805
+ todayScope: "Today's Token usage for current suppliers, measured by the host local day",
1806
+ eventsObserved: "Call events observed",
1807
+ previewSaved: "Latest query for the saved configuration. Draft edits do not change this preview.",
1808
+ advanced: "Advanced options",
1809
+ unsaved: "You have unsaved changes",
1810
+ keepEditing: "Continue editing",
1811
+ discard: "Discard changes",
1812
+ all: "All",
1813
+ attention: "Needs attention",
1814
+ noAttention: "No suppliers need attention",
1815
+ loading: "Loading data…",
1816
+ invalidThreshold: "Thresholds must satisfy 1 ≤ warning < critical ≤ 100",
1817
+ invalidGlobal: "Poll interval must be 10–3600 seconds; retention must be 1–90 days.",
1818
+ invalidHolidays: "Holiday dates must be YYYY-MM-DD: {list}",
1819
+
1820
+ // ---- DeepSeek peak/valley billing windows (decided host-side in lib/season.js) ----
1821
+ seasonPeak: "Peak",
1822
+ seasonValley: "Off-peak",
1823
+ seasonHoliday: "public holiday",
1824
+ seasonWeekend: "weekend",
1825
+ seasonTier: "Billing window",
1826
+ seasonNext: "Next switch",
1827
+ seasonBeijingNow: "Beijing time",
1828
+ seasonBeijingOnly: "decided in Beijing time",
1829
+ seasonFlipInM: "switches in {m}m",
1830
+ seasonFlipInHM: "switches in {h}h{m}m",
1831
+ seasonFlipInDH: "switches in {d}d{h}h",
1832
+ seasonFlipSoon: "switching now",
1833
+ seasonSplitLabel: "Today by window",
1834
+ seasonSplitPeak: "peak {n} ({pct})",
1835
+ seasonSplitValley: "off-peak {n} ({pct})",
1836
+ seasonSplitUnknown: "untagged {n}",
1837
+ holidaysLabel: "Holiday overrides (one per line)",
1838
+ holidaysPlaceholder: "2027-01-01\n2027-02-06",
1839
+ holidaysHint: "Empty uses the built-in table. That table only covers years the State Council has published; without next year's dates, weekday holidays count as peak — paste an override to correct it immediately.",
1840
+
1841
+ // ---- sidebar card: plan name + weekly progress bar ----
1842
+ weekTag: "Week",
1843
+ barAria: "{name} used {pct}",
1844
+
1845
+ title: "Usage monitor",
1846
+ connWarn: "Connected · degraded",
1847
+ connStandby: "Standby",
1848
+ resetInHM: "resets in {h}h{m}m",
1849
+ resetInDH: "resets in {d}d{h}h",
1850
+ resetHM: "{h}h{m}m",
1851
+ resetDH: "{d}d{h}h",
1852
+ resetSoon: "resetting now",
1853
+ watchTitle: "Watched limits",
1854
+ watchUnavailable: "Unavailable now",
1855
+ watchDefaultHint: "With nothing checked the card falls back to the weekly window, then the highest-used valid window.",
1856
+ moveUp: "Move up",
1857
+ moveDown: "Move down",
1858
+ todayLabel: "Today",
1859
+ noneActive: "No calls yet",
1860
+ today: "Today {n} tokens",
1861
+ todayShort: "Today {n}",
1862
+ statsWindow: "Last {n} days",
1863
+ remainLabel: "{n}% left",
1864
+ ratioAria: "Cache hits {hit} · cache misses {miss} · output {out}",
1865
+ cacheHit: "Cache hits",
1866
+ cacheMiss: "Cache misses",
1867
+ outputLabel: "Output",
1868
+ cacheWrite: "Cache writes",
1869
+ unsplit: "Unsplit",
1870
+ refresh: "Refresh",
1871
+ refreshing: "Refreshing…",
1872
+ close: "Close",
1873
+ cancel: "Cancel",
1874
+ save: "Save",
1875
+ saved: "Saved ✓",
1876
+ stateOk: "OK",
1877
+ stateWarn: "Warning",
1878
+ stateCrit: "Critical",
1879
+ stateErr: "Fetch failed",
1880
+ stateOff: "Not configured",
1881
+ quota: "Limit",
1882
+ usedShort: "Used",
1883
+ detailTitle: "Details",
1884
+ historySummary: "Refresh history (latest {n})",
1885
+ colTime: "Time",
1886
+ colSupplier: "Supplier",
1887
+ colResult: "Result",
1888
+ colOk: "OK",
1889
+ colFail: "Failed",
1890
+ colMain: "Headline",
1891
+ colNote: "Note",
1892
+ colTier: "Tier",
1893
+ settingsSub: "Secrets are stored in DSH configuration and are never displayed here. Leave blank to keep the existing secret.",
1894
+ global: "Global settings",
1895
+ supplierPages: "Suppliers",
1896
+ rescan: "Rescan",
1897
+ connectedChip: "Connected {n}",
1898
+ scanLineBusy: "Scanning…",
1899
+ scanLineIdle: "Not scanned",
1900
+ scanLineFail: "Scan failed: {err}",
1901
+ addableTitle: "Addable suppliers",
1902
+ addableCount: "{n}",
1903
+ emptyAdded: "No suppliers connected yet",
1904
+ openPage: "Configure",
1905
+ back: "Back",
1906
+ credentials: "Credentials",
1907
+ compatSource: "compat",
1908
+
1909
+ enable: "Enable",
1910
+ test: "Test connection",
1911
+ testing: "Testing…",
1912
+ testOk: "Connected",
1913
+ testFail: "Failed",
1914
+ apiKey: "API Key",
1915
+ managementKey: "Management Key",
1916
+ adminKey: "Admin Key",
1917
+ codingPlanKey: "Coding Plan Key",
1918
+ tokenPlanKey: "Token Plan Key",
1919
+ currentQuota: "Current quota (latest fetch)",
1920
+ unmappedDetail: "({detail})",
1921
+ keySet: "Set (blank keeps current)",
1922
+ keyEmpty: "Not set",
1923
+ keyAuto: "Auto-read {env}",
1924
+ apiKeyEnv: "Credential reference",
1925
+ apiKeyEnvPlaceholder: "e.g. COMMAND_CODE_API_KEY",
1926
+ apiKeyEnvHint: "Name of a DSH credential record or an environment variable; the key itself is never written to this plugin's config.",
1927
+ keyRefResolved: "ref {env} (resolved)",
1928
+ keyRefMissing: "ref {env} (unresolved)",
1929
+ dshKey: "DSH key",
1930
+ allowanceToken: "allowance Token (OAuth)",
1931
+ orgId: "org id (optional)",
1932
+ baseUrl: "Base URL",
1933
+ warnPct: "Warn threshold %",
1934
+ critPct: "Critical threshold %",
1935
+ interval: "Poll interval (s, 10–3600)",
1936
+ retention: "Usage retention (days, 1–90)",
1937
+ unmapped: "Detected DSH suppliers this plugin does not support yet",
1938
+ },
1939
+ };
1940
+
1941
+ // ---------- 样式(一次性注入,作用域化) ----------
1942
+ const CSS = `
1943
+ [data-qm-entry],.qm-density{box-sizing:border-box;color:var(--dsw-alias-label-primary,#dbe2ee);font:12px var(--dsw-font-family),system-ui,sans-serif;}
1944
+ div:has(> div[data-slot="sidebar.footer.action"] > [data-qm-linerow]){flex-wrap:wrap;}
1945
+ [data-qm-linerow]{flex:1 1 100%;min-width:100%;box-sizing:border-box;order:-1;margin:2px 0;}
1946
+ .qm-footer{position:relative;display:flex;flex-direction:column;align-items:stretch;border:1px solid var(--dsw-alias-border-l2,#363d4d);border-radius:9px;background:var(--dsw-alias-bg-layer-2,#151922);overflow:hidden;}
1947
+ .qm-density{position:absolute;right:4px;top:4px;width:26px;height:24px;border:0;border-radius:5px;background:transparent;cursor:pointer;}
1948
+ .qm-l1{display:flex;gap:8px;align-items:center;padding-right:26px;}
1949
+ .qm-plan{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
1950
+ .qm-fetch-status{font-size:10px;min-width:0;color:var(--dsw-alias-state-error-primary,#f87171);}
1951
+ /* 第 2 行:窗口标签 + 已用百分比进度条 + 百分比数字(颜色即阈值分档,不再另设圆点)
1952
+ 关注限额可以是多条:四列网格让所有行共享 label/条/百分比/倒计时列宽,行与行严格对齐 */
1953
+ .qm-bars{display:grid;grid-template-columns:minmax(0,max-content) minmax(24px,1fr) max-content max-content;
1954
+ column-gap:6px;row-gap:6px;align-items:center;min-width:0;}
1955
+ /* 回落成主指标文字(只有余额/报告)时同样要能截断:这一行放不下就省略,不许撑破卡片 */
1956
+ .qm-l2{display:flex;align-items:center;gap:6px;min-width:0;}
1957
+ .qm-l2>.qm-primary{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
1958
+ /* 长度上限用 em 而不是百分比:百分比在 grid 自动轨道里会对尚未确定的轨道尺寸解析,
1959
+ 把「月用量」夹成十几像素只剩省略号。em 是绝对长度,列宽由最长(但受限)的 label 决定。 */
1960
+ .qm-bar-label{font-size:10px;line-height:14px;max-width:5.5em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary,#a9b2c5);}
1961
+ .qm-bar{min-width:24px;height:6px;border-radius:3px;overflow:hidden;background:var(--dsw-alias-border-l1,#1d2330);}
1962
+ .qm-bar-fill{display:block;height:100%;border-radius:3px;background:var(--dsw-alias-label-tertiary,#6b7280);}
1963
+ .qm-bar-fill.ok{background:var(--dsw-alias-state-success-primary,#34d399);}
1964
+ .qm-bar-fill.warn{background:var(--dsw-alias-state-warn-primary,#fbbf24);}
1965
+ .qm-bar-fill.crit{background:var(--dsw-alias-state-error-primary,#f87171);}
1966
+ .qm-bar-pct{font-size:11px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#a9b2c5);}
1967
+ /* 裸倒计时:不带「后重置」这类叙述词,靠右对齐 + 弱色 + min-width 保证多行对齐 */
1968
+ .qm-bar-reset{min-width:36px;margin-left:4px;text-align:right;font-size:10px;font-variant-numeric:tabular-nums;
1969
+ color:var(--dsw-alias-label-tertiary,#8b94a8);}
1970
+ .qm-primary{font-weight:600;font-variant-numeric:tabular-nums;}
1971
+ /* 卡片标题行:供应商名 + 今日用量,点击进统计;监控条与时段留在下方主按钮里。
1972
+ padding-right 给绝对定位的密度按钮(右侧 4px 起、宽 26px)留位,不与今日数重叠 */
1973
+ .qm-head{display:flex;align-items:center;gap:8px;border:0;background:transparent;cursor:pointer;text-align:left;
1974
+ color:inherit;font:inherit;line-height:17px;padding:8px 32px 0 8px;}
1975
+ .qm-today-chip{margin-left:auto;flex:none;font-size:11px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#a9b2c5);}
1976
+ /* 详情弹窗:今日用量与归一比例同一行;窄栏放不下就换行,不把总量和数字拆散。
1977
+ 左右内缩 10px,与时段块、指标卡的文字对齐 */
1978
+ .qm-today-line{display:flex;align-items:baseline;flex-wrap:wrap;gap:2px 10px;margin:8px 10px 6px;
1979
+ color:var(--dsw-alias-label-secondary,#a9b2c5);font-size:11px;font-variant-numeric:tabular-nums;}
1980
+ .qm-today-text{flex:none;}
1981
+ /* 分布条:详情行只有一条五段条(命中/未命中/输出/写缓存/未细分);段宽 = 分量占比 */
1982
+ .qm-split-bar{display:inline-flex;flex:1 1 64px;min-width:48px;height:5px;border-radius:2.5px;overflow:hidden;
1983
+ background:var(--dsw-alias-border-l1,#1d2330);}
1984
+ .qm-split-bar i{display:block;height:100%;}
1985
+ .qm-split-lg{flex-basis:120px;height:8px;border-radius:4px;}
1986
+ .seg-hit{background:var(--dsw-alias-state-success-primary,#34d399);}
1987
+ .seg-miss{background:var(--dsw-alias-state-business-primary,#4f8cff);}
1988
+ .seg-out{background:#a78bfa;}
1989
+ .seg-write{background:var(--dsw-alias-label-tertiary,#8b94a8);}
1990
+ .seg-unsplit{background:var(--dsw-alias-border-l2,#363d4d);}
1991
+ /* 归一比例:三个数字分别着段色,与分布条一一对应;分隔冒号保持弱色。
1992
+ 必须是 inline 而不是 flex:flex 容器会把分隔用的空白裁掉,冒号两侧就贴住了。 */
1993
+ .qm-ratio{display:inline;font-weight:600;font-variant-numeric:tabular-nums;}
1994
+ .qm-ratio b{font-weight:700;}
1995
+ .qm-ratio .r-hit{color:var(--dsw-alias-state-success-primary,#34d399);}
1996
+ .qm-ratio .r-miss{color:var(--dsw-alias-state-business-primary,#4f8cff);}
1997
+ .qm-ratio .r-out{color:#a78bfa;}
1998
+ /* 合并图:柱 = 每日 token(左轴量级),线 = 各窗口剩余额度(右轴恒定 0–100%) */
1999
+ .qm-chart{margin-top:12px;}
2000
+ .qm-chart-cap{display:flex;justify-content:space-between;flex-wrap:wrap;gap:2px 8px;font-size:10px;
2001
+ color:var(--dsw-alias-label-tertiary,#5c6577);font-variant-numeric:tabular-nums;}
2002
+ .qm-chart-plot{position:relative;margin-top:2px;height:112px;cursor:crosshair;outline:none;}
2003
+ .qm-chart-plot:focus-visible{outline:1px solid var(--dsw-alias-border-l2,#363d4d);outline-offset:2px;border-radius:4px;}
2004
+ /* preserveAspectRatio=none 让 svg 铺满容器;折线用 non-scaling-stroke 保持 1.5px 不被横向拉扁 */
2005
+ .qm-chart-plot svg{display:block;width:100%;height:100%;overflow:visible;}
2006
+ /* 柱值标签:按绘图区百分比定位,文字本身不参与 svg 的横向拉伸 */
2007
+ .qm-chart-labels{position:absolute;inset:0;pointer-events:none;}
2008
+ .qm-chart-value{position:absolute;transform:translateX(-50%);font-size:10px;line-height:1;white-space:nowrap;
2009
+ font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#a9b2c5);pointer-events:none;}
2010
+ .qm-chart-bar{fill:var(--dsw-alias-state-business-primary,#4f8cff);fill-opacity:.32;}
2011
+ .qm-chart-grid{stroke:var(--dsw-alias-border-l2,#363d4d);stroke-width:1;stroke-dasharray:3 3;vector-effect:non-scaling-stroke;}
2012
+ .qm-chart-axis{stroke:var(--dsw-alias-border-l2,#363d4d);stroke-width:1;vector-effect:non-scaling-stroke;}
2013
+ .qm-chart-line{stroke-width:1.5;stroke-linejoin:round;stroke-linecap:round;}
2014
+ /* 叠加层不参与坐标拉伸:点是像素半径,线是像素宽度 */
2015
+ .qm-chart-overlay{position:absolute;inset:0;pointer-events:none;}
2016
+ .qm-chart-dot{stroke:none;}
2017
+ .qm-chart-dot.is-on{stroke:var(--dsw-alias-bg-base,#0b0e13);stroke-width:1.5;}
2018
+ .qm-chart-drop{fill:none;stroke-width:1;stroke-dasharray:2.5 2.5;opacity:.55;vector-effect:non-scaling-stroke;}
2019
+ .qm-chart-cursor{stroke:var(--dsw-alias-label-tertiary,#8b94a8);stroke-width:1;opacity:.75;vector-effect:non-scaling-stroke;}
2020
+ .qm-chart-tip{position:absolute;top:0;z-index:2;pointer-events:none;display:flex;flex-direction:column;gap:2px;
2021
+ padding:5px 8px;border-radius:7px;white-space:nowrap;font-size:11px;line-height:1.45;font-variant-numeric:tabular-nums;
2022
+ color:var(--dsw-alias-label-secondary,#a9b2c5);background:var(--dsw-alias-bg-base,#0b0e13);
2023
+ border:1px solid var(--dsw-alias-border-l2,#363d4d);box-shadow:0 4px 14px #0006;}
2024
+ .qm-chart-tip b{font-weight:600;color:var(--dsw-alias-label-primary,#dbe2ee);}
2025
+ .qm-chart-tip-tok{color:var(--dsw-alias-label-tertiary,#8b94a8);}
2026
+ .qm-chart-tip-row{display:flex;align-items:center;gap:6px;}
2027
+ .qm-chart-tip-row i{display:inline-block;flex:none;width:7px;height:7px;border-radius:1px;}
2028
+ .qm-chart-ticks{position:relative;height:12px;margin-top:1px;}
2029
+ .qm-chart-tick{position:absolute;transform:translateX(-50%);font-size:10px;white-space:nowrap;
2030
+ color:var(--dsw-alias-label-tertiary,#5c6577);font-variant-numeric:tabular-nums;}
2031
+ .qm-chart-legend{display:flex;gap:12px;flex-wrap:wrap;margin-top:6px;font-size:11px;
2032
+ color:var(--dsw-alias-label-secondary,#a9b2c5);font-variant-numeric:tabular-nums;}
2033
+ .qm-chart-key{display:inline-flex;align-items:center;gap:5px;}
2034
+ .qm-chart-key i{display:inline-block;width:10px;height:2px;border-radius:1px;}
2035
+ /* 供应商配置页:关注限额复选列表(勾选顺序即卡片排列顺序) */
2036
+ .qm-watch{border:1px solid var(--dsw-alias-border-l2,#262d3d);border-radius:8px;padding:8px 10px 4px;}
2037
+ .qm-watch .w-hint{color:var(--dsw-alias-label-tertiary,#8b94a8);font-size:11px;}
2038
+ .qm-watch .w-row{display:flex;align-items:center;gap:8px;padding:5px 0;border-bottom:1px solid var(--dsw-alias-border-l1,#1d2330);}
2039
+ .qm-watch .w-row:last-child{border-bottom:none;}
2040
+ .qm-watch .w-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
2041
+ .qm-watch .w-val{flex:none;font-size:11px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#a9b2c5);}
2042
+ .qm-watch .w-row.off .w-name,.qm-watch .w-row.off .w-val{color:var(--dsw-alias-label-tertiary,#8b94a8);}
2043
+ .qm-watch .w-move{flex:none;display:flex;gap:2px;visibility:hidden;}
2044
+ .qm-watch .w-row.watched .w-move{visibility:visible;}
2045
+ .qm-watch .w-move button{width:20px;height:20px;border:1px solid var(--dsw-alias-border-l2,#262d3d);border-radius:5px;
2046
+ background:none;color:var(--dsw-alias-label-secondary,#a9b2c5);cursor:pointer;font-size:10px;line-height:1;padding:0;}
2047
+ .qm-watch .w-move button:hover:not(:disabled){color:var(--dsw-alias-label-primary,#dbe2ee);border-color:var(--dsw-alias-state-business-primary,#4f8cff);}
2048
+ .qm-watch .w-move button:disabled{opacity:.35;cursor:default;}
2049
+ .qm-season{display:flex;align-items:center;gap:5px;font-size:11px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#a9b2c5);}
2050
+ .qm-season b{font-weight:600;}
2051
+ .qm-season.peak b,.qm-season-dot.peak{color:var(--dsw-alias-state-warn-primary,#fbbf24);}
2052
+ .qm-season.valley b{color:var(--dsw-alias-state-success-primary,#34d399);}
2053
+ .qm-season-dot{width:6px;height:6px;border-radius:50%;flex:none;display:inline-block;background:var(--dsw-alias-label-tertiary,#6b7280);}
2054
+ .qm-season-dot.peak{background:var(--dsw-alias-state-warn-primary,#fbbf24);}
2055
+ .qm-season-dot.valley{background:var(--dsw-alias-state-success-primary,#34d399);}
2056
+ .qm-season-block{margin:0 10px 10px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l1,#1d2330);border-radius:8px;}
2057
+ .qm-season-block .qm-season-row{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:var(--dsw-alias-label-secondary,#a9b2c5);}
2058
+ .qm-season-block .qm-season-row+.qm-season-row{margin-top:4px;}
2059
+ .qm-season-warn{margin-top:6px;font-size:11px;color:var(--dsw-alias-state-warn-primary,#fbbf24);}
2060
+ .qm-settings .qm-holidays textarea{width:100%;box-sizing:border-box;resize:vertical;font:11px var(--dsw-font-family),ui-monospace,monospace;
2061
+ background:var(--dsw-alias-bg-layer-2,#151922);border:1px solid var(--dsw-alias-border-l2,#262d3d);border-radius:8px;
2062
+ color:var(--dsw-alias-label-primary,#dbe2ee);padding:6px 8px;}
2063
+ .qm-settings .qm-holidays textarea:focus{outline:2px solid var(--dsw-alias-state-business-primary,#4f8cff);outline-offset:1px;}
2064
+ .qm-compact-line{display:flex;gap:5px;align-items:center;padding:8px 24px 0 0;white-space:nowrap;}
2065
+ .qm-compact-line .qm-provider{min-width:24px;max-width:32%;overflow:hidden;text-overflow:ellipsis;flex:0 1 auto;}
2066
+ .qm-compact-line .qm-primary{min-width:0;display:flex;gap:3px;align-items:center;flex:1;font-size:11px;}
2067
+ .qm-metric-name{min-width:0;overflow:hidden;text-overflow:ellipsis;}
2068
+ .qm-metric-value,.qm-more{flex:none;}
2069
+ .qm-rail{width:32px;height:32px;border:none;border-radius:8px;background:transparent;cursor:pointer;}
2070
+ .qm-dot{width:7px;height:7px;border-radius:50%;flex:none;display:inline-block;background:var(--dsw-alias-label-tertiary,#6b7280);}
2071
+ .qm-dot.ok{background:var(--dsw-alias-state-success-primary,#34d399);}
2072
+ .qm-dot.warn{background:var(--dsw-alias-state-warn-primary,#fbbf24);}
2073
+ .qm-dot.crit{background:var(--dsw-alias-state-error-primary,#f87171);}
2074
+ .qm-overlay{position:fixed;inset:0;z-index:1500;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;}
2075
+ .qm-overlay .qm-card{width:min(960px,calc(100vw - 32px));max-height:86vh;overflow:auto;
2076
+ background:var(--dsw-alias-bg-base,#0b0e13);border:1px solid var(--dsw-alias-border-l2,#262d3d);
2077
+ border-radius:14px;padding:20px 24px 24px;color:var(--dsw-alias-label-primary,#dbe2ee);
2078
+ font-family:var(--dsw-font-family),sans-serif;box-sizing:border-box;}
2079
+ .qm-overlay .qm-card h3{margin:0 0 4px;font-size:15px;}
2080
+ .qm-overlay .qm-sub{color:var(--dsw-alias-label-tertiary,#8b94a8);font-size:11px;margin-bottom:12px;}
2081
+ /* 设置页版设置面板:已嵌在设置面板内容列里,不再要遮罩/卡片边框与宽度上限 */
2082
+ .qm-settings-page{color:var(--dsw-alias-label-primary,#dbe2ee);font-family:var(--dsw-font-family),sans-serif;padding-top:8px;}
2083
+ .qm-settings-page h3{margin:0 0 4px;font-size:15px;}
2084
+ .qm-settings-page .qm-sub{color:var(--dsw-alias-label-tertiary,#8b94a8);font-size:11px;margin-bottom:12px;}
2085
+ .qm-pill{display:inline-block;padding:0 8px;border-radius:9px;font-size:11px;
2086
+ border:1px solid var(--dsw-alias-border-l2,#262d3d);color:var(--dsw-alias-label-secondary,#8b94a8);}
2087
+ .qm-pill.warn{color:var(--dsw-alias-state-warn-primary,#fbbf24);border-color:var(--dsw-alias-state-warn-primary,#fbbf24);}
2088
+ .qm-pill.crit{color:var(--dsw-alias-state-error-primary,#f87171);border-color:var(--dsw-alias-state-error-primary,#f87171);}
2089
+ .qm-pill.err{color:var(--dsw-alias-label-tertiary,#6b7280);}
2090
+ .qm-pill.ok{color:var(--dsw-alias-state-success-primary,#34d399);}
2091
+ .qm-pill.off{color:var(--dsw-alias-label-tertiary,#6b7280);}
2092
+ .qm-history{margin-top:14px;border:1px solid var(--dsw-alias-border-l1,#262d3d);border-radius:10px;
2093
+ background:var(--dsw-alias-bg-layer-2,#151922);}
2094
+ .qm-history summary{cursor:pointer;padding:8px 12px;font-size:12px;color:var(--dsw-alias-label-secondary,#8b94a8);}
2095
+ .qm-history table{width:100%;border-collapse:collapse;font-size:11px;}
2096
+ .qm-history td,.qm-history th{padding:4px 8px;border-top:1px solid var(--dsw-alias-border-l1,#1d2330);text-align:left;color:var(--dsw-alias-label-secondary,#8b94a8);}
2097
+ .qm-history .h-ok{color:var(--dsw-alias-state-success-primary,#34d399);}
2098
+ .qm-history .h-peak{color:var(--dsw-alias-state-warn-primary,#fbbf24);}
2099
+ .qm-history .h-valley{color:var(--dsw-alias-state-success-primary,#34d399);}
2100
+ .qm-history .h-bad{color:var(--dsw-alias-state-error-primary,#f87171);}
2101
+ .qm-settings input[type=text],.qm-settings input[type=password],.qm-settings input[type=number]{
2102
+ width:100%;box-sizing:border-box;background:var(--dsw-specific-input-major,#1c2230);
2103
+ border:1px solid var(--dsw-alias-border-l2,#262d3d);border-radius:8px;color:var(--dsw-alias-label-primary,#dbe2ee);
2104
+ padding:6px 8px;font-size:12px;font-family:inherit;margin-top:2px;}
2105
+ .qm-settings input:focus{outline:2px solid var(--dsw-alias-state-business-primary,#4f8cff);outline-offset:1px;}
2106
+ .qm-settings label{display:block;margin-bottom:10px;font-size:12px;color:var(--dsw-alias-label-secondary,#8b94a8);}
2107
+ .qm-settings .s-group{border:1px solid var(--dsw-alias-border-l1,#262d3d);border-radius:10px;padding:10px 12px;margin-bottom:10px;
2108
+ background:var(--dsw-alias-bg-layer-2,#151922);}
2109
+ .qm-settings .s-group h5{margin:0 0 8px;font-size:13px;display:flex;justify-content:space-between;align-items:center;}
2110
+ .qm-settings .s-grid{display:grid;grid-template-columns:1fr 1fr;gap:0 12px;}
2111
+ .qm-settings .s-row{display:flex;gap:8px;align-items:center;margin-bottom:6px;}
2112
+ .qm-settings .s-row input[type=checkbox]{accent-color:var(--dsw-alias-state-business-primary,#4f8cff);}
2113
+ .qm-settings .s-test{margin-left:8px;border:1px solid var(--dsw-alias-border-l2,#262d3d);background:none;border-radius:6px;
2114
+ color:var(--dsw-alias-label-primary,#dbe2ee);cursor:pointer;padding:2px 10px;font-size:11px;font-family:inherit;}
2115
+ .qm-settings .s-test-res{font-size:11px;margin-left:8px;}
2116
+ .qm-settings .s-test-res.ok{color:var(--dsw-alias-state-success-primary,#34d399);}
2117
+ .qm-settings .s-test-res.bad{color:var(--dsw-alias-state-error-primary,#f87171);}
2118
+ .qm-settings .s-actions{display:flex;gap:8px;justify-content:flex-end;}
2119
+ .qm-settings .s-actions button{border:1px solid var(--dsw-alias-border-l2,#262d3d);background:none;border-radius:8px;
2120
+ color:var(--dsw-alias-label-primary,#dbe2ee);cursor:pointer;padding:5px 14px;font-size:12px;font-family:inherit;}
2121
+ .qm-settings .s-actions button.qm-pri{background:var(--dsw-alias-button-info-fill,#4f8cff);border-color:transparent;color:#fff;}
2122
+ .qm-settings .s-saved{color:var(--dsw-alias-state-success-primary,#34d399);font-size:11px;align-self:center;}
2123
+
2124
+ .qm-settings .qm-pages-title{display:flex;justify-content:space-between;margin:4px 0 8px;color:var(--dsw-alias-label-secondary,#8b94a8);font-size:12px;}
2125
+ .qm-settings .qm-pages-title span{color:var(--dsw-alias-label-tertiary,#5c6577);font-size:10px;}
2126
+ .qm-page-list{display:flex;flex-direction:column;gap:6px;}
2127
+ .qm-page-row{display:flex;align-items:center;gap:10px;border:1px solid var(--dsw-alias-border-l1,#262d3d);border-radius:10px;padding:6px 10px;background:var(--dsw-alias-bg-layer-2,#151922);}
2128
+ .qm-page-main{flex:1 1 0;min-width:0;display:flex;align-items:center;gap:8px;cursor:pointer;}
2129
+ .qm-page-name{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
2130
+ .qm-page-pill{flex:none;padding:1px 8px;border-radius:8px;font-size:10px;border:1px solid var(--dsw-alias-border-l2,#262d3d);color:var(--dsw-alias-label-secondary,#8b94a8);}
2131
+ .qm-page-pill.ghost{opacity:.6;}
2132
+ .qm-page-actions{flex:none;display:flex;align-items:center;gap:6px;font-size:11px;}
2133
+ .qm-page-toggle{display:flex;gap:4px;align-items:center;margin:0;font-size:11px;}
2134
+ .qm-page-toggle input[type=checkbox]{accent-color:var(--dsw-alias-state-business-primary,#4f8cff);}
2135
+ .qm-settings .s-test.qm-pri-soft{border-color:var(--dsw-alias-state-business-primary,#4f8cff);color:var(--dsw-alias-state-business-primary,#4f8cff);}
2136
+ .qm-settings .qm-page-head{display:flex;align-items:center;gap:8px;margin-bottom:8px;}
2137
+ .qm-settings .qm-page-head b{flex:1 1 0;font-size:14px;}
2138
+ .qm-settings .qm-inline-toggle{display:flex;align-items:center;gap:6px;margin:8px 0 0;font-size:12px;}
2139
+ .qm-settings .qm-inline-toggle input[type=checkbox]{accent-color:var(--dsw-alias-state-business-primary,#4f8cff);}
2140
+ /* v1.1:已添加过滤目录 + 重新扫描标题行 + 可添加折叠列表 */
2141
+ .qm-settings .qm-pages-title.qm-head-b{align-items:center;}
2142
+ .qm-settings .qm-pages-title .qm-added-only{margin-left:6px;color:var(--dsw-alias-label-tertiary,#5c6577);font-size:10px;font-weight:400;}
2143
+ .qm-settings .qm-title-actions{display:flex;align-items:center;gap:8px;flex:none;}
2144
+ .qm-settings .chip{display:inline-block;padding:1px 8px;border-radius:8px;font-size:10px;border:1px solid var(--dsw-alias-border-l2,#262d3d);color:var(--dsw-alias-label-secondary,#8b94a8);background:var(--dsw-alias-bg-layer-2,#151922);white-space:nowrap;}
2145
+ .qm-rescan-btn{border:1px solid var(--dsw-alias-border-l2,#262d3d);background:none;border-radius:8px;color:var(--dsw-alias-label-primary,#dbe2ee);cursor:pointer;padding:3px 12px;font-size:11px;font-family:inherit;white-space:nowrap;}
2146
+ .qm-rescan-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,#20283a);}
2147
+ .qm-rescan-btn:disabled{cursor:default;opacity:.55;}
2148
+ .qm-settings .qm-scanline{display:flex;justify-content:flex-end;align-items:center;gap:6px;flex-wrap:wrap;min-height:16px;
2149
+ margin:-4px 0 8px;color:var(--dsw-alias-label-tertiary,#8b94a8);font-size:11px;}
2150
+ .qm-settings .qm-scanline b{font-weight:600;}
2151
+ .qm-settings .qm-scanline .ok{color:var(--dsw-alias-state-success-primary,#34d399);}
2152
+ .qm-settings .qm-scanline .err{color:var(--dsw-alias-state-error-primary,#f87171);}
2153
+ .qm-settings .qm-scanline .names{max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block;vertical-align:middle;}
2154
+ .qm-settings .qm-empty-added{color:var(--dsw-alias-label-tertiary,#8b94a8);text-align:center;padding:18px 8px;
2155
+ border:1px dashed var(--dsw-alias-border-l1,#262d3d);border-radius:10px;margin-bottom:4px;}
2156
+ .qm-settings .qm-addable{margin-top:10px;border:1px dashed var(--dsw-alias-border-l2,#262d3d);border-radius:10px;}
2157
+ .qm-settings .qm-addable summary{cursor:pointer;padding:8px 12px;font-size:12px;color:var(--dsw-alias-label-secondary,#8b94a8);list-style:none;display:flex;align-items:center;gap:8px;user-select:none;}
2158
+ .qm-settings .qm-addable summary::-webkit-details-marker{display:none;}
2159
+ .qm-settings .qm-addable summary::before{content:"▸";font-size:10px;color:var(--dsw-alias-label-tertiary,#5c6577);transition:transform .15s;}
2160
+ .qm-settings .qm-addable[open] summary::before{transform:rotate(90deg);}
2161
+ .qm-settings .qm-addable .cnt{color:var(--dsw-alias-label-tertiary,#8b94a8);font-size:10px;}
2162
+ .qm-settings .addable-list{padding:0 8px 8px;display:flex;flex-direction:column;gap:6px;}
2163
+ .qm-settings .qm-add-row{display:flex;align-items:center;gap:8px;border:1px solid var(--dsw-alias-border-l1,#262d3d);border-radius:8px;padding:5px 8px;background:var(--dsw-alias-bg-layer-2,#151922);}
2164
+ .qm-settings .qm-add-row.fresh{animation:qm-fresh 1.8s ease-out;}
2165
+ @keyframes qm-fresh{from{background:rgba(79,140,255,.30);}to{background:transparent;}}
2166
+
2167
+ .qm-card{container-type:inline-size;min-width:0;overflow-wrap:anywhere;}
2168
+ .qm-card button,.qm-card select{font:inherit;font-size:12px;color:var(--dsw-alias-label-primary,#dbe2ee);background:var(--dsw-alias-bg-layer-2,#151922);border:1px solid var(--dsw-alias-border-l2,#363d4d);border-radius:7px;padding:5px 10px;cursor:pointer;}
2169
+ .qm-card button:disabled{opacity:.55;cursor:default;}
2170
+ .qm-card button:focus-visible,.qm-card summary:focus-visible,.qm-card select:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4f8cff);outline-offset:2px;}
2171
+ .qm-panel-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:12px;}
2172
+ .qm-panel-head h3{flex:1;}
2173
+ .qm-tabs{display:flex;gap:8px;border-bottom:1px solid var(--dsw-alias-border-l2,#363d4d);padding-bottom:10px;margin-bottom:16px;}
2174
+ .qm-tabs [aria-selected=true]{color:var(--dsw-alias-state-business-primary,#4f8cff);border-color:currentColor;}
2175
+ @container (max-width:460px){.qm-settings .s-grid{grid-template-columns:minmax(0,1fr);}.qm-page-actions{width:100%;}.qm-chart-value{font-size:9px;}}
2176
+ /* 极窄面板(内容宽 ≤240px)里柱值会互相压住:只保留日期刻度与悬停读数 */
2177
+ @container (max-width:240px){.qm-chart-value{display:none;}}
2178
+ .qm-cur{color:var(--dsw-alias-state-business-primary,#4f8cff);font-weight:400;}
2179
+ .qm-history-scroll{overflow-x:auto;}
2180
+ .qm-history-scroll table{min-width:560px;}
2181
+ .ci-err{color:var(--dsw-alias-state-error-primary,#f87171);font-size:12px;margin:8px 0;white-space:pre-wrap;}
2182
+ .qm-page-row,.qm-add-row{flex-wrap:wrap;}
2183
+ .qm-page-main{cursor:default;flex-wrap:wrap;min-width:150px;}
2184
+ .qm-row-metric{font-size:11px;font-variant-numeric:tabular-nums;}
2185
+ .qm-page-actions{flex-wrap:wrap;}
2186
+ .qm-settings .qm-page-toggle{display:flex;align-items:center;margin:0;}
2187
+ .qm-settings .qm-pages-title{flex-wrap:wrap;gap:8px;}
2188
+ .qm-settings .qm-page-head{flex-wrap:wrap;}
2189
+ .qm-settings .qm-page-head b{min-width:100px;}
2190
+ .qm-advanced summary{cursor:pointer;font-size:13px;margin-bottom:10px;}
2191
+ .qm-confirm{position:sticky;bottom:0;padding:14px;border:2px solid var(--dsw-alias-state-warn-primary,#fbbf24);border-radius:10px;background:var(--dsw-alias-bg-base,#0b0e13);box-shadow:0 3px 14px #0004;z-index:1;}
2192
+ .qm-confirm button{margin-right:8px;}
2193
+ .qm-empty{text-align:center;padding:18px 8px;color:var(--dsw-alias-label-tertiary,#8b94a8);}
2194
+ .qm-empty p{margin:0 0 8px;}
2195
+ /* 卡片:标题行 + 监控条合并为一个按钮,密度切换仍是同级兄弟 */
2196
+ .qm-card-body{flex:1;min-width:0;display:flex;flex-direction:column;align-items:stretch;gap:1px;padding:0 6px 8px;border:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;}
2197
+ .qm-card-body:hover,.qm-density:hover{background:var(--dsw-alias-interactive-bg-hover,#20283a);}
2198
+ .qm-card-body:focus-visible,.qm-density:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4f8cff);outline-offset:-2px;}
2199
+ .qm-head{display:flex;align-items:center;gap:8px;padding:8px 24px 0 0;margin-bottom:3px;text-align:left;}
2200
+ .qm-season-meta{color:var(--dsw-alias-label-tertiary,#8b94a8);}
2201
+ /* 概览:供应商行 + 展开明细 */
2202
+ .qm-overview-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:2px 0 10px;font-size:12px;}
2203
+ .qm-today-total{display:flex;align-items:baseline;gap:5px;font-variant-numeric:tabular-nums;}
2204
+ .qm-today-total b{font-size:15px;}
2205
+ .qm-today-total>span:first-child{color:var(--dsw-alias-label-secondary,#a9b2c5);}
2206
+ .qm-filter{display:flex;gap:6px;margin-left:auto;}
2207
+ .qm-filter button{font-size:11px;padding:3px 8px;}
2208
+ .qm-filter .qm-count{opacity:.65;margin-left:5px;}
2209
+ .qm-rows{display:flex;flex-direction:column;gap:8px;}
2210
+ .qm-row{border:1px solid var(--dsw-alias-border-l2,#363d4d);border-radius:10px;background:var(--dsw-alias-bg-layer-2,#151922);overflow:hidden;}
2211
+ .qm-row-head{width:100%;display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 10px;border:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;}
2212
+ .qm-row-head:hover{background:var(--dsw-alias-interactive-bg-hover,#20283a);}
2213
+ .qm-row-head:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4f8cff);outline-offset:-2px;}
2214
+ .qm-row-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
2215
+ .qm-row-metric{margin-left:auto;font-weight:700;font-variant-numeric:tabular-nums;}
2216
+ .qm-row-today{font-size:11px;color:var(--dsw-alias-label-secondary,#a9b2c5);font-variant-numeric:tabular-nums;}
2217
+ .qm-chevron{flex:none;font-size:10px;color:var(--dsw-alias-label-tertiary,#8b94a8);}
2218
+ .qm-row-detail{padding:0 10px 10px;border-top:1px solid var(--dsw-alias-border-l1,#1d2330);}
2219
+ .qm-row-actions{display:flex;justify-content:flex-end;margin:8px 0;}
2220
+ .qm-data-time{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b94a8);margin:6px 0;}
2221
+ .qm-metric-tables{display:flex;flex-direction:column;gap:8px;margin-top:8px;overflow-x:auto;}
2222
+ .qm-metric-table{width:100%;border-collapse:collapse;font-size:11px;font-variant-numeric:tabular-nums;}
2223
+ .qm-metric-table th{font-weight:500;color:var(--dsw-alias-label-secondary,#a9b2c5);text-align:left;padding:4px 6px;border-bottom:1px solid var(--dsw-alias-border-l1,#1d2330);white-space:nowrap;}
2224
+ /* 列头与单元格同侧:首列(指标名)左,其余数值/重置列右 */
2225
+ .qm-metric-table th:not(:first-child){text-align:right;}
2226
+ .qm-metric-table td{padding:4px 6px;border-bottom:1px solid var(--dsw-alias-border-l1,#1d2330);text-align:right;white-space:nowrap;}
2227
+ .qm-metric-table tr:last-child th,.qm-metric-table tr:last-child td{border-bottom:none;}
2228
+ .qm-tone.ok{color:var(--dsw-alias-state-success-primary,#34d399);}
2229
+ .qm-tone.warn{color:var(--dsw-alias-state-warn-primary,#fbbf24);}
2230
+ .qm-tone.crit{color:var(--dsw-alias-state-error-primary,#f87171);}
2231
+ .qm-tone.neutral{color:var(--dsw-alias-label-primary,#dbe2ee);}
2232
+ .qm-num{font-variant-numeric:tabular-nums;}
2233
+ .qm-kv{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:var(--dsw-alias-label-secondary,#a9b2c5);margin-top:6px;}
2234
+ .qm-kv>span:first-child{color:var(--dsw-alias-label-tertiary,#8b94a8);}
2235
+ .qm-split-stats{display:flex;gap:10px;flex-wrap:wrap;margin-top:8px;font-size:11px;color:var(--dsw-alias-label-secondary,#a9b2c5);}
2236
+ .qm-split-stat{display:flex;align-items:center;gap:4px;}
2237
+ .qm-split-stat i{width:8px;height:8px;border-radius:2px;display:inline-block;}
2238
+ .qm-split-stat b{font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary,#dbe2ee);}
2239
+ .qm-split-stat .seg-warn{background:var(--dsw-alias-state-warn-primary,#fbbf24);}
2240
+ .qm-split-stat .seg-ok{background:var(--dsw-alias-state-success-primary,#34d399);}
2241
+ .qm-split-stat .seg-unsplit{background:var(--dsw-alias-label-tertiary,#6b7280);}
2242
+ .qm-empty-line{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b94a8);margin:6px 0;}
2243
+ .qm-section-head{display:flex;align-items:center;gap:6px;}
2244
+ .qm-section-head h5{margin:0;}
2245
+ .qm-info{display:inline-block;margin-left:4px;vertical-align:middle;}
2246
+ .qm-info summary{list-style:none;cursor:pointer;color:var(--dsw-alias-label-tertiary,#8b94a8);font-size:11px;}
2247
+ .qm-info summary::-webkit-details-marker{display:none;}
2248
+ .qm-info p{font-size:11px;line-height:1.5;color:var(--dsw-alias-label-secondary,#a9b2c5);margin:4px 0 0;max-width:46em;}
2249
+ .qm-display-row{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:12px;color:var(--dsw-alias-label-secondary,#a9b2c5);}
2250
+ .qm-display-row select{margin-left:auto;}
2251
+ .qm-global summary{cursor:pointer;font-size:13px;color:var(--dsw-alias-label-secondary,#a9b2c5);list-style:none;display:flex;align-items:center;gap:6px;}
2252
+ .qm-global summary::-webkit-details-marker{display:none;}
2253
+ .qm-global summary::before{content:"▸";font-size:10px;color:var(--dsw-alias-label-tertiary,#5c6577);}
2254
+ .qm-global[open] summary::before{transform:rotate(90deg);}
2255
+ .qm-global[open] summary{margin-bottom:8px;}
2256
+ .qm-unmapped{font-size:11px;color:var(--dsw-alias-label-tertiary,#8b94a8);margin-top:8px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
2257
+ .qm-ref-state{display:block;font-size:11px;color:var(--dsw-alias-label-tertiary,#8b94a8);margin-top:-4px;}
2258
+ .qm-usage-split{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:4px 10px 0;}
2259
+ .qm-usage-legend{display:flex;gap:10px;flex-wrap:wrap;font-size:11px;color:var(--dsw-alias-label-secondary,#a9b2c5);}
2260
+ .qm-usage-legend span{display:inline-flex;align-items:center;gap:4px;}
2261
+ .qm-usage-legend i{width:8px;height:8px;border-radius:2px;display:inline-block;}
2262
+ `;
2263
+
2264
+ function ensureStyle() {
2265
+ const tagId = "dsh-token-quota/widget.css";
2266
+ // 热替换会再次执行 apply:复用同一个 <style> 并重写内容,否则新 JS 只能配旧 CSS。
2267
+ let tag = document.querySelector(`style[data-plugin-css="${tagId}"]`);
2268
+ if (!tag) {
2269
+ tag = document.createElement("style");
2270
+ tag.dataset.plugin = "dsh-token-quota";
2271
+ tag.dataset.pluginCss = tagId;
2272
+ document.head.appendChild(tag);
2273
+ }
2274
+ tag.textContent = CSS;
2275
+ }
2276
+
2277
+ // ---------- 应用入口 ----------
2278
+ const inject = ["slots", "locale", "sessions"];
2279
+
2280
+ function apply(ctx) {
2281
+ ensureStyle();
2282
+
2283
+
2284
+ // 本地化词典(DSH 官方模式:locale.register 后由槽位注入 t)。
2285
+ // localeT 是同一份词典的绑定视图:槽位导航项(label thunk)拿不到注入的 t,用它取文案。
2286
+ let disposeLocale = null;
2287
+ let localeT = null;
2288
+ try {
2289
+ disposeLocale = ctx.locale.register(NS, LOCALES);
2290
+ localeT = typeof ctx.locale.bind === "function" ? ctx.locale.bind(NS) : null;
2291
+ } catch (error) {
2292
+ console.warn("[dsh-token-quota] locale register failed", error);
2293
+ }
2294
+
2295
+ // 装配「当前显示页」订阅源:官方 sessions.list(Session Controller 客户端)。
2296
+ // 切页 → sessions.list 变化 → FooterSlotWithSession 即时重渲并带新 sessionId 重新拉 /state。
2297
+ sessionListSource = null;
2298
+ try {
2299
+ const sessions = ctx.get ? ctx.get("sessions") : ctx.sessions;
2300
+ const list = sessions?.list;
2301
+ if (list && typeof list.subscribe === "function" && typeof list.getSnapshot === "function") {
2302
+ sessionListSource = {
2303
+ getSnapshot: () => {
2304
+ try {
2305
+ return selectedSessionId(list.getSnapshot());
2306
+ } catch {
2307
+ return "";
2308
+ }
2309
+ },
2310
+ subscribe: (listener) => {
2311
+ try {
2312
+ return list.subscribe(listener) || (() => {});
2313
+ } catch {
2314
+ return () => {};
2315
+ }
2316
+ },
2317
+ };
2318
+ }
2319
+ } catch (error) {
2320
+ console.warn("[dsh-token-quota] sessions service unavailable, sidebar shows global latest", error);
2321
+ }
2322
+
2323
+ displayController?.dispose();
2324
+ displayController = createDisplayController(sessionListSource);
2325
+
2326
+ // 侧边栏底槽:小组件(list slot,keyed id,官方渲染契约)
2327
+ let disposeFooter = null;
2328
+ let disposeCard = null;
2329
+ try {
2330
+ disposeFooter = ctx.slots.inject("sidebar.footer.action", () =>
2331
+ ctx.slots.register({
2332
+ name: "sidebar.footer.action",
2333
+ id: "dsh-token-quota",
2334
+ locale: NS,
2335
+ }, FooterSlotWithSession),
2336
+ );
2337
+ } catch (error) {
2338
+ console.warn("[dsh-token-quota] sidebar footer slot unavailable", error);
2339
+ }
2340
+
2341
+ // DSH 设置面板:本插件自成一页(0.1.7 起 settings.plugin.item 槽位已移除,
2342
+ // 列表式 settings.section 取代它;导航项文案随 locale 版本重取)。
2343
+ try {
2344
+ disposeCard = ctx.slots.inject("settings.section", () =>
2345
+ ctx.slots.register({
2346
+ name: "settings.section",
2347
+ id: NS,
2348
+ order: 20,
2349
+ label: () => (localeT ? localeT("title") : "用量监控"),
2350
+ locale: NS,
2351
+ }, SettingsSection),
2352
+ );
2353
+ } catch (error) {
2354
+ console.warn("[dsh-token-quota] settings section slot unavailable", error);
2355
+ }
2356
+
2357
+ ctx.effect(() => () => {
2358
+ disposeLocale?.();
2359
+ disposeFooter?.();
2360
+ disposeCard?.();
2361
+ displayController.dispose();
2362
+ surface.close();
2363
+ }, "dsh-token-quota: slot disposers");
2364
+ }
2365
+
2366
+ exports.apply = apply;
2367
+ exports.inject = inject;
2368
+ return module.exports;
2369
+ },
2370
+ });
2371
+ })();