@alexpeng/dsh-custom-plugin 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,94 @@ All notable changes to this project are documented here. The format loosely
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions
5
5
  follow [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## 0.7.1 — 2026-10-03
8
+
9
+ 数据安全与健壮性加固版:封住两条不可恢复配置丢失路径与一条跨宿主丢更新路径,装上浏览器提交的形状门,补齐卸载回收与凭据状态缓存;测试从 143 增至 185。
10
+
11
+ ### Fixed
12
+
13
+ - **宿主读档失败不再静默用默认值覆盖状态文件**:此前 `loadStateFile` 把
14
+ `ENOENT`、瞬态占用(Windows 杀毒扫描 / 同步盘 / 与桌面宿主的 rename 竞争)
15
+ 与 JSON 损坏一律折叠成「无文件」,随后启动流程立即把默认文档写入真实路径——
16
+ folders / prompts / stars / 用量台账被无条件清空且不留副本。现在:瞬态错误按
17
+ 1.5s/3s/6s 重试(与客户端重试梯子同节奏);重试耗尽或 JSON 损坏时先以
18
+ pid 后缀名将原文件改名隔离(`.corrupt-<pid>`,两个宿主共享一个
19
+ `$DSH_HOME` 也不会互相抢占恢复名)再采用默认值;仅当原文件既读不出又移不走
20
+ 时 loader 才 reject,宿主转入只读模式(抑制一切保存)而不是销毁可能完好的
21
+ 文档。启动后的首次规范化保存失败也不再误入加载失败分支。
22
+ - **客户端重试耗尽后不再把出厂空配置写回宿主**:桌面壳页面可能先于宿主路由
23
+ 就绪,客户端重试梯子(约 10.5 秒)耗尽后停在出厂默认值;此后用户切换任何
24
+ 开关都会触发一次全量 POST,把已存 folders / prompts / stars 整组替换为空。
25
+ 现在 `saveCfg` 以「曾成功读取过状态」为门槛:未加载成功一律改为重新读取并
26
+ 提示「配置尚未读取完成,已重新加载,请重试」。
27
+ - **插件停用/重声明后全局副作用全部回收**:卸载清理器此前只注销插槽并移除动
28
+ 态样式,`theme.overrideTokens` 的设计令牌覆盖(停用后 GUI 配色仍被插件锁
29
+ 死)、`<html>` 上的 `vx-liquid/vx-dark/vx-light` 类、液态玻璃 SVG 滤镜节点、
30
+ 待触发的余额重试定时器(会继续外呼最多 3 次)全部残留。现在清理器逐一还原。
31
+ - **共享 `$DSH_HOME` 的两个宿主不再互相清空对方的写入**(Web 与 Desktop 各自持有整份内存文档、整文件回写,最后写者赢):现在每次保存前先用 stat 身份(mtime+size)对比本进程上次读/写看到的文件,发现外部变更就回读并做三方合并——本进程未动过的配置段(cfg/folders/prompts/stars)采纳外部版本,动过的保留本地版本,用量台账按计数器做 `对方 + 本地 − 共同基线` 的精确并集(两个宿主的会话流来自不同 profile、天然不重叠)。启动加载也改用同一文件句柄做 fstat+read,基线与合并字节描述同一份文档。
32
+ - **`POST /state` 形状门**:浏览器提交的 folders / stars 此前未经校验直接落
33
+ state——畸形深层嵌套可让此后每次保存的 `JSON.stringify` 抛 `RangeError`,
34
+ 保存从此持续失败需手改状态文件。现在 `normalizeFolders`(唯一 id、纯字符
35
+ 串 id 列表、深度 ≤32、节点 ≤2000)与 `normalizeStars`(安全对象键、纯数字
36
+ 序号、`true` 值、总量 ≤10000)把关,违规整笔拒绝(400「文件夹数据无效」/
37
+ 「星标数据无效」),绝不截断——客户端持有全量文档,静默丢段等于丢数据。
38
+ - **缓冲用量回放不再把宿主已学到的模型覆盖为 `unknown`**:启动缓冲的
39
+ `session/event` 用量回放时,`null` 模型改为传 `undefined`,让宿主回退到自己
40
+ 在加载期间学到的 session 模型映射。
41
+ - **用量重扫不再白付全量代价后必然失败**:流式对话期间触发重扫时,revision 检查从「全部 I/O 完成后查一次」改为每个会话读取前检查,已注定作废的扫描会立即停止读取剩余会话日志。
42
+ - **Mermaid CDN 兜底不再被 200-HTML 投毒**:绑架门户/镜像异常返回的 200 HTML 页此前会被缓存为「引擎」且宿主生命周期内不再重取;现在要求载荷是 ≥1000 字节、不以 `<` 开头的脚本形态,否则记为该镜像失败并继续尝试下一个。
43
+ - **客户端脚本加载挂起不再无限等待**:`ensureMermaid` 的 120ms 轮询等待没有出口,网络黑洞(onload/onerror 都不触发)会让每个流式新代码块再挂一个永久等待者、「预加载」按钮永远「加载中」;现在 30 秒看门狗翻到 failed 并移除 script 标签,重试可重新插入。
44
+ - **GUI 主题与 OS 配色不一致时玻璃/面板不再用错颜色**:深色 GUI + 浅色 OS 下余额悬浮卡、面板、模态保持浅色磨砂(反之亦然)——这些规则此前只跟 `prefers-color-scheme` 走;现在按客户端镜像到 `<html>` 的 `vx-dark/vx-light` 类选择,媒体查询降级为类就绪前的启动兜底(液态玻璃规则本就按此模式工作,磨砂路径对齐)。
45
+
46
+ ### Changed
47
+
48
+ - **凭据状态短 TTL 缓存**:`credentialStatus` 每次 `/state` GET 与保存响应都
49
+ 打一次 OS keychain + 读凭据文件;现在对「来源判定」结果缓存 5 秒(从不缓
50
+ 存键值本身),`applyEdit` 与遗留迁移立即失效,保存响应永远如实反映刚应用
51
+ 的编辑。
52
+ - **长会话交互开销**:`TurnTailEntry`(每条消息一个)对轮次数据的查找从每次 store 变更 O(轮数) 线性扫描改为 fetch 时构建的 `seq → item` Map O(1) 查表;选中拖拽时 `selectionchange` 以 60Hz 触发 `setS`,现在文本与坐标未变(<1px)时跳过发布;用量面板的 90 天汇总/按天/按模型统计改为 `useMemo`(预算输入每次击键不再重算全部统计);面板拖拽改为 mousemove 直写 DOM、mouseup 才落 store;预算状态判定复用 `productivity.budgetState`(此前为生产死代码,客户端内联了一份会漂移的副本)。
53
+ - **死代码清理**:六个无引用 ICONS 条目(clock/fork/arrowUp/arrowDown/moon/
54
+ sun)、两条无匹配死规则(`.vx-swatch:disabled`、`.vx-textarea`)移除;
55
+ `hexToRgb` 收敛到 palette.ts 单一导出实现。
56
+ - **smoke 收紧**:未构建即跑 smoke 给出明确「先 pnpm build」报错而非裸 ENOENT 堆栈;新增 bundle `require()` 字面量 ⊆ `PLATFORM_MODULES` 交叉校验(防未声明外部化导致的静默消失类断裂);`lib/client.js` 落后于 `src/client` 或 `tsdown.config.ts` 时判红(防对过期产物盖章);Windows 下 PATH 探测补 `.exe` 后缀。
57
+ - **typecheck 收编构建配置**:`tsdown.config.ts`、`vitest.config.ts` 进入 `pnpm typecheck` 范围。
58
+ - **CI 补浏览器段**:`setup-chrome` 后跑全量 `pnpm smoke`——客户端注册握手
59
+ (bundle 必须注册 {id, factory} 且不物化、无页面错误)首次进入 CI,此前只
60
+ 在本机跑。
61
+
62
+ ### Tests
63
+
64
+ 测试从 143 增至 185。
65
+
66
+ - **路由错误面**(信任边界此前只测了围栏与备份校验):全部路由的 405、坏
67
+ JSON → 400、流级超限 → 413、timeline/export 缺 `sessionId` → 400、kinds
68
+ 数组内单项非法 → 400、`POST /state` 成功路径与 `applyEdit` 失败 → 400 映射、
69
+ Mermaid 脚本路由引擎未就绪 → 503 及其围栏 403。
70
+ - **状态加载失败处理**:损坏文档隔离、重试耗尽后隔离、瞬态故障恢复后正常合
71
+ 并、隔离失败时 reject 且原文件字节不动。
72
+ - **跨宿主同步合并**:外部写入按段采纳/保留、同一用量行两宿主并发累加的精确
73
+ 并集、全新安装保存不触发合并。
74
+ - **形状门**:合法树/星标通过、重复 id 与非字符串成员拒绝、超深树拒绝、不安
75
+ 全对象键(`JSON.parse` 产生的自有 `__proto__`)拒绝。
76
+ - **装载入口集成测试**(`src/index.ts` 此前零覆盖):全路由与状态工具注册、
77
+ 启动规范化落盘、`stateReady` 前的用量缓冲、500ms 防抖合并为一次写入、损坏
78
+ 文档隔离后继续写入、隔离失败转只读(诊断含 read-only、内存台账仍在、磁盘
79
+ 无写入)、fiber 卸载回收路由/工具并重新武装单例守卫。
80
+ - **单例守卫 / 家目录 / 凭据存储零覆盖补齐**:`mountOnce` 首挂生效、重挂静默、
81
+ fiber 卸载后重武装(effect 须「返回」解标记的契约被锁死);`resolveDshHome`
82
+ 的 `~` 展开与相对路径锚定;keytar 缺席时 `SystemCredentialStore` 全操作软
83
+ 失败(本仓库与最小安装实际走的路径)。
84
+ - **凭据缓存**:TTL 窗口内命中缓存、编辑后失效重解析。
85
+ - **样式不变量**(`styles.spec.ts`):把 0.7.0 的实发 bug 类锁死为断言
86
+ ——`.vx-liquid` 永不出现在 `.vx-root` 之后(死规则类)、磨砂/液态玻璃与余
87
+ 额卡必须按 `:root.vx-dark/vx-light` 主题类出规则、无退役类名(vx-dots /
88
+ vx-timeline)、花括号平衡。测试首次落地就抓出一个存量孤儿 `}`(历史上删
89
+ 媒体块残留,浏览器静默忽略),已清除。
90
+ - **Mermaid 载荷校验**:200-HTML 拒收并落到下一镜像、全部镜像 HTML 时不投毒
91
+ 缓存、过小 200 体拒收。
92
+ - **用量重扫提前中止**:扫描进行中来新用量时,剩余会话不再被读取即返回重试
93
+ 错误。
94
+
7
95
  ## 0.7.0 — 2026-09-30
8
96
 
9
97
  桌面版适配修复版。0.6.0 及之前的产物在 dsh Desktop 里几乎全部功能失效——本版
package/lib/client.js CHANGED
@@ -316,6 +316,8 @@ window.__ModuleLoader__.load({
316
316
  "#E6E1D0"
317
317
  ]
318
318
  ];
319
+ /** Parse a #rrggbb (or bare rrggbb) hex color; malformed input yields the
320
+ * palette's neutral gray rather than throwing. */
319
321
  function hexToRgb(hex) {
320
322
  const match = /^#?([0-9a-f]{6})$/i.exec(String(hex ?? "").trim());
321
323
  if (match === null) return [
@@ -524,6 +526,13 @@ window.__ModuleLoader__.load({
524
526
  }
525
527
  //#endregion
526
528
  //#region src/productivity.ts
529
+ function budgetState(summary, budgetCny, warningPercent = 80) {
530
+ if (!Number.isFinite(budgetCny) || budgetCny <= 0) return "disabled";
531
+ if (!summary.exact) return "unknown";
532
+ const ratio = summary.costCny / budgetCny * 100;
533
+ if (ratio >= 100) return "over";
534
+ return ratio >= Math.max(1, Math.min(100, warningPercent)) ? "warning" : "ok";
535
+ }
527
536
  function summarizeUsage(usage, days) {
528
537
  const out = {
529
538
  tokens: 0,
@@ -878,6 +887,36 @@ window.__ModuleLoader__.load({
878
887
  color: #eef1f7;
879
888
  }
880
889
  }
890
+ /* The GUI theme can disagree with the OS scheme (dsh selects light/dark
891
+ independently — dark GUI on a light OS left these surfaces frosted
892
+ light), so the frost fills and panel text colors key on the mirrored
893
+ root classes, not the OS alone. The media queries above remain the
894
+ pre-boot fallback, before the client has applied the classes; the liquid
895
+ rules below out-rank these by specificity, not by order. */
896
+ :root.vx-light .vx-glass {
897
+ background: rgba(255, 255, 255, .64);
898
+ color: inherit;
899
+ }
900
+ :root.vx-dark .vx-glass {
901
+ background: rgba(13, 17, 25, .62);
902
+ color: #eef1f7;
903
+ }
904
+ :root.vx-light .vx-panel,
905
+ :root.vx-light .vx-modal,
906
+ :root.vx-light .vx-folders {
907
+ color: #20242e;
908
+ }
909
+ :root.vx-dark .vx-panel,
910
+ :root.vx-dark .vx-modal,
911
+ :root.vx-dark .vx-folders {
912
+ color: #e8ebf2;
913
+ }
914
+ :root.vx-light .vx-balance-hover {
915
+ color: #20242e;
916
+ }
917
+ :root.vx-dark .vx-balance-hover {
918
+ color: #e8ebf2;
919
+ }
881
920
  /* Liquid glass: the SVG displacement filter bends the backdrop at the
882
921
  surface's edges; the chained blur+saturate keeps text over the middle of
883
922
  large panels readable (pure displacement leaves the mid-area untouched,
@@ -1126,10 +1165,6 @@ window.__ModuleLoader__.load({
1126
1165
  border-color: #7fa4e0;
1127
1166
  box-shadow: 0 0 0 2px rgba(127, 164, 224, .35);
1128
1167
  }
1129
- .vx-swatch:disabled {
1130
- opacity: .35;
1131
- cursor: not-allowed;
1132
- }
1133
1168
  .vx-swatch-label {
1134
1169
  font-size: 10px;
1135
1170
  opacity: .85;
@@ -1180,16 +1215,6 @@ window.__ModuleLoader__.load({
1180
1215
  padding: 6px 10px;
1181
1216
  font-size: 12px;
1182
1217
  }
1183
- .vx-textarea {
1184
- border: 1px solid rgba(128, 140, 160, .4);
1185
- background: rgba(255, 255, 255, .16);
1186
- color: inherit;
1187
- border-radius: 9px;
1188
- padding: 6px 10px;
1189
- font-size: 12px;
1190
- resize: vertical;
1191
- font-family: inherit;
1192
- }
1193
1218
  .vx-toggle-row {
1194
1219
  display: flex;
1195
1220
  gap: 8px;
@@ -1597,7 +1622,7 @@ window.__ModuleLoader__.load({
1597
1622
  .vx-root.vx-light .vx-toast {
1598
1623
  background: rgba(26, 32, 44, .92);
1599
1624
  }
1600
- }`;
1625
+ `;
1601
1626
  //#endregion
1602
1627
  //#region src/client/custom.tsx
1603
1628
  /**
@@ -1693,6 +1718,7 @@ window.__ModuleLoader__.load({
1693
1718
  usage: {},
1694
1719
  sessionId: null,
1695
1720
  turns: null,
1721
+ turnsBySeq: null,
1696
1722
  anchors: /* @__PURE__ */ new Map(),
1697
1723
  panelOpen: false,
1698
1724
  panelTab: "look",
@@ -1780,7 +1806,8 @@ window.__ModuleLoader__.load({
1780
1806
  S.anchors.clear();
1781
1807
  setS({
1782
1808
  sessionId: id,
1783
- turns: null
1809
+ turns: null,
1810
+ turnsBySeq: null
1784
1811
  });
1785
1812
  fetchTurns(id);
1786
1813
  }
@@ -1790,7 +1817,8 @@ window.__ModuleLoader__.load({
1790
1817
  S.anchors.clear();
1791
1818
  setS({
1792
1819
  sessionId: null,
1793
- turns: null
1820
+ turns: null,
1821
+ turnsBySeq: null
1794
1822
  });
1795
1823
  }
1796
1824
  };
@@ -1870,11 +1898,6 @@ window.__ModuleLoader__.load({
1870
1898
  }]
1871
1899
  ],
1872
1900
  zap: [["path", { d: "M13 2 3 14h9l-1 8 10-12h-9l1-8z" }]],
1873
- clock: [["circle", {
1874
- cx: 12,
1875
- cy: 12,
1876
- r: 10
1877
- }], ["polyline", { points: "12 6 12 12 16 14" }]],
1878
1901
  download: [
1879
1902
  ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }],
1880
1903
  ["polyline", { points: "7 10 12 15 17 10" }],
@@ -1941,25 +1964,6 @@ window.__ModuleLoader__.load({
1941
1964
  y2: 18
1942
1965
  }]],
1943
1966
  star: [["path", { d: "M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" }]],
1944
- fork: [
1945
- ["line", {
1946
- x1: 6,
1947
- y1: 3,
1948
- x2: 6,
1949
- y2: 15
1950
- }],
1951
- ["circle", {
1952
- cx: 18,
1953
- cy: 6,
1954
- r: 3
1955
- }],
1956
- ["circle", {
1957
- cx: 6,
1958
- cy: 18,
1959
- r: 3
1960
- }],
1961
- ["path", { d: "M18 9a9 9 0 0 1-9 9" }]
1962
- ],
1963
1967
  copy: [["rect", {
1964
1968
  x: 9,
1965
1969
  y: 9,
@@ -2092,8 +2096,6 @@ window.__ModuleLoader__.load({
2092
2096
  r: 2.1
2093
2097
  }]
2094
2098
  ],
2095
- arrowUp: [["polyline", { points: "18 15 12 9 6 15" }]],
2096
- arrowDown: [["polyline", { points: "6 9 12 15 18 9" }]],
2097
2099
  minimize: [
2098
2100
  ["polyline", { points: "4 14 10 14 10 20" }],
2099
2101
  ["polyline", { points: "20 10 14 10 14 4" }],
@@ -2110,62 +2112,6 @@ window.__ModuleLoader__.load({
2110
2112
  y2: 14
2111
2113
  }]
2112
2114
  ],
2113
- moon: [["path", { d: "M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" }]],
2114
- sun: [
2115
- ["circle", {
2116
- cx: 12,
2117
- cy: 12,
2118
- r: 4
2119
- }],
2120
- ["line", {
2121
- x1: 12,
2122
- y1: 2,
2123
- x2: 12,
2124
- y2: 5
2125
- }],
2126
- ["line", {
2127
- x1: 12,
2128
- y1: 19,
2129
- x2: 12,
2130
- y2: 22
2131
- }],
2132
- ["line", {
2133
- x1: 2,
2134
- y1: 12,
2135
- x2: 5,
2136
- y2: 12
2137
- }],
2138
- ["line", {
2139
- x1: 19,
2140
- y1: 12,
2141
- x2: 22,
2142
- y2: 12
2143
- }],
2144
- ["line", {
2145
- x1: 4.93,
2146
- y1: 4.93,
2147
- x2: 7.07,
2148
- y2: 7.07
2149
- }],
2150
- ["line", {
2151
- x1: 16.93,
2152
- y1: 16.93,
2153
- x2: 19.07,
2154
- y2: 19.07
2155
- }],
2156
- ["line", {
2157
- x1: 4.93,
2158
- y1: 19.07,
2159
- x2: 7.07,
2160
- y2: 16.93
2161
- }],
2162
- ["line", {
2163
- x1: 16.93,
2164
- y1: 7.07,
2165
- x2: 19.07,
2166
- y2: 4.93
2167
- }]
2168
- ],
2169
2115
  list: [
2170
2116
  ["line", {
2171
2117
  x1: 8,
@@ -2273,20 +2219,6 @@ window.__ModuleLoader__.load({
2273
2219
  cb
2274
2220
  } });
2275
2221
  }
2276
- function hexToRgb(hex) {
2277
- const match = /^#?([0-9a-f]{6})$/i.exec(String(hex ?? "").trim());
2278
- if (match === null) return [
2279
- 235,
2280
- 238,
2281
- 242
2282
- ];
2283
- const value = parseInt(match[1], 16);
2284
- return [
2285
- value >> 16 & 255,
2286
- value >> 8 & 255,
2287
- value & 255
2288
- ];
2289
- }
2290
2222
  function rgbaOf(hex, alpha) {
2291
2223
  const c = hexToRgb(hex);
2292
2224
  return `rgba(${c[0]},${c[1]},${c[2]},${alpha})`;
@@ -2384,6 +2316,7 @@ window.__ModuleLoader__.load({
2384
2316
  6e3
2385
2317
  ];
2386
2318
  let loadCfgAttempt = 0;
2319
+ let cfgLoaded = false;
2387
2320
  async function loadCfg() {
2388
2321
  let failure = null;
2389
2322
  try {
@@ -2410,6 +2343,7 @@ window.__ModuleLoader__.load({
2410
2343
  if (data.credentialStorage === "system" || data.credentialStorage === "legacy-state" || data.credentialStorage === "environment" || data.credentialStorage === "dsh" || data.credentialStorage === "none") S.credentialStorage = data.credentialStorage;
2411
2344
  if (data.usage !== void 0 && data.usage !== null && typeof data.usage === "object") S.usage = data.usage;
2412
2345
  loadCfgAttempt = 0;
2346
+ cfgLoaded = true;
2413
2347
  } else if (result.ok !== true) failure = result.error ?? "状态读取失败";
2414
2348
  } catch (error) {
2415
2349
  failure = String(error?.message ?? error);
@@ -2432,6 +2366,12 @@ window.__ModuleLoader__.load({
2432
2366
  }
2433
2367
  }
2434
2368
  function saveCfg() {
2369
+ if (!cfgLoaded) {
2370
+ toast("配置尚未读取完成,已重新加载,请重试", "error");
2371
+ loadCfgAttempt = 0;
2372
+ loadCfg();
2373
+ return;
2374
+ }
2435
2375
  const cfg = { ...S.cfg };
2436
2376
  delete cfg.clouds;
2437
2377
  delete cfg.wind;
@@ -2842,12 +2782,19 @@ window.__ModuleLoader__.load({
2842
2782
  const result = await apiTimelineGet(sessionId);
2843
2783
  if (sessionId !== S.sessionId || requestSerial !== turnsRequestSerial) return;
2844
2784
  if (result.ok === true) {
2785
+ const items = result.items ?? [];
2786
+ const bySeq = /* @__PURE__ */ new Map();
2787
+ for (const item of items) bySeq.set(item.seq, item);
2845
2788
  S.turns = {
2846
2789
  sessionId,
2847
- items: result.items ?? []
2790
+ items
2848
2791
  };
2849
- setS({ turns: S.turns });
2850
- diagThrottled("timeline " + (result.items?.length ?? 0) + " items " + sessionId.slice(0, 24));
2792
+ S.turnsBySeq = bySeq;
2793
+ setS({
2794
+ turns: S.turns,
2795
+ turnsBySeq: bySeq
2796
+ });
2797
+ diagThrottled("timeline " + items.length + " items " + sessionId.slice(0, 24));
2851
2798
  } else diagThrottled("timeline failed: " + String(result.error ?? "unknown"));
2852
2799
  } catch (error) {
2853
2800
  diagThrottled("timeline fetch error: " + String(error?.message ?? error));
@@ -3015,6 +2962,17 @@ window.__ModuleLoader__.load({
3015
2962
  return mermaidState.status === "ready";
3016
2963
  }
3017
2964
  mermaidState = { status: "loading" };
2965
+ const d0 = typeof document !== "undefined" ? document : null;
2966
+ const watchdog = setTimeout(() => {
2967
+ if (mermaidState.status !== "loading") return;
2968
+ mermaidState = {
2969
+ status: "failed",
2970
+ error: "脚本加载超时"
2971
+ };
2972
+ try {
2973
+ if (d0 !== null) for (const el of d0.querySelectorAll(`script[src="${MERMAID_SCRIPT_PATH}"]`)) el.remove();
2974
+ } catch {}
2975
+ }, 3e4);
3018
2976
  try {
3019
2977
  const result = await apiMermaidFetch();
3020
2978
  if (result.ok === true) {
@@ -3044,6 +3002,8 @@ window.__ModuleLoader__.load({
3044
3002
  error: String(error?.message ?? error)
3045
3003
  };
3046
3004
  return false;
3005
+ } finally {
3006
+ clearTimeout(watchdog);
3047
3007
  }
3048
3008
  }
3049
3009
  async function renderMermaid(code, dark = false) {
@@ -3577,23 +3537,32 @@ window.__ModuleLoader__.load({
3577
3537
  }
3578
3538
  function UsageHistory() {
3579
3539
  const s = useS();
3580
- const keys = recentDayKeys(s.usageRange);
3581
- const selected = new Set(keys);
3582
- const summary = summarizeUsage(s.usage, selected);
3583
- const daily = keys.map((day) => ({
3584
- day,
3585
- ...summarizeUsage(s.usage, /* @__PURE__ */ new Set([day]))
3586
- }));
3587
- const maxTokens = Math.max(1, ...daily.map((row) => row.tokens));
3588
- const byModel = Object.create(null);
3589
- for (const day of keys) for (const [model, row] of Object.entries(s.usage[day] ?? {})) mergeUsageRow(byModel[model] ?? (byModel[model] = createUsageRow()), row);
3590
- const monthPrefix = dayKey().slice(0, 7) + "-";
3591
- const monthDays = new Set(Object.keys(s.usage).filter((day) => day.startsWith(monthPrefix)));
3592
- const month = summarizeUsage(s.usage, monthDays);
3540
+ const { summary, daily, maxTokens, byModel, month } = react.useMemo(() => {
3541
+ const keys = recentDayKeys(s.usageRange);
3542
+ const selected = new Set(keys);
3543
+ const summary = summarizeUsage(s.usage, selected);
3544
+ const daily = keys.map((day) => ({
3545
+ day,
3546
+ ...summarizeUsage(s.usage, /* @__PURE__ */ new Set([day]))
3547
+ }));
3548
+ const maxTokens = Math.max(1, ...daily.map((row) => row.tokens));
3549
+ const byModel = Object.create(null);
3550
+ for (const day of keys) for (const [model, row] of Object.entries(s.usage[day] ?? {})) mergeUsageRow(byModel[model] ?? (byModel[model] = createUsageRow()), row);
3551
+ const monthPrefix = dayKey().slice(0, 7) + "-";
3552
+ const monthDays = new Set(Object.keys(s.usage).filter((day) => day.startsWith(monthPrefix)));
3553
+ return {
3554
+ summary,
3555
+ daily,
3556
+ maxTokens,
3557
+ byModel,
3558
+ month: summarizeUsage(s.usage, monthDays)
3559
+ };
3560
+ }, [s.usage, s.usageRange]);
3593
3561
  const budget = Math.max(0, Number(s.cfg.monthlyBudgetCny ?? 0));
3594
3562
  const warning = Math.max(1, Math.min(100, Number(s.cfg.budgetWarningPercent ?? 80)));
3595
3563
  const ratio = budget > 0 && month.exact ? month.costCny / budget * 100 : 0;
3596
- const budgetText = budget <= 0 ? "预算提醒已关闭" : !month.exact ? "历史峰闲数据不完整,无法判断预算" : ratio >= 100 ? `已超出月预算(${ratio.toFixed(0)}%)` : ratio >= warning ? `已达到月预算 ${ratio.toFixed(0)}%` : `本月预算使用 ${ratio.toFixed(0)}%`;
3564
+ const state = budgetState(month, budget, warning);
3565
+ const budgetText = state === "disabled" ? "预算提醒已关闭" : state === "unknown" ? "历史峰闲数据不完整,无法判断预算" : state === "over" ? `已超出月预算(${ratio.toFixed(0)}%)` : state === "warning" ? `已达到月预算 ${ratio.toFixed(0)}%` : `本月预算使用 ${ratio.toFixed(0)}%`;
3597
3566
  return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-row wrap" }, [
3598
3567
  7,
3599
3568
  30,
@@ -3633,7 +3602,7 @@ window.__ModuleLoader__.load({
3633
3602
  } })))), Object.keys(byModel).length > 0 ? react.createElement("table", { className: "vx-table" }, react.createElement("thead", null, react.createElement("tr", null, react.createElement("th", null, "模型"), react.createElement("th", null, "Token"), react.createElement("th", null, "调用"), react.createElement("th", null, "费用 ¥"))), react.createElement("tbody", null, Object.entries(byModel).map(([model, row]) => {
3634
3603
  const cost = usageCostBreakdown(row, model);
3635
3604
  return react.createElement("tr", { key: model }, react.createElement("td", null, model), react.createElement("td", null, formatTokenCount(row.in + row.out + row.cacheIn + row.cacheW)), react.createElement("td", null, row.calls), react.createElement("td", null, cost.exact ? cost.totalCostCny.toFixed(4) : "—"));
3636
- }))) : null, react.createElement("div", { className: ratio >= 100 ? "vx-error" : "vx-muted" }, budgetText), react.createElement("div", { className: "vx-row wrap" }, react.createElement("label", { className: "vx-muted" }, "月预算 ¥ ", react.createElement("input", {
3605
+ }))) : null, react.createElement("div", { className: state === "over" ? "vx-error" : "vx-muted" }, budgetText), react.createElement("div", { className: "vx-row wrap" }, react.createElement("label", { className: "vx-muted" }, "月预算 ¥ ", react.createElement("input", {
3637
3606
  className: "vx-input",
3638
3607
  style: { width: 100 },
3639
3608
  type: "number",
@@ -3769,11 +3738,14 @@ window.__ModuleLoader__.load({
3769
3738
  const node = sel.anchorNode;
3770
3739
  if (node !== null && node.nodeType === 1 && /TEXTAREA|INPUT/.test(node.nodeName)) return;
3771
3740
  const r = range.getBoundingClientRect();
3772
- setS({ quoteSel: {
3741
+ const next = {
3773
3742
  text: text.slice(0, 8e3),
3774
3743
  x: r.left + r.width / 2,
3775
3744
  y: r.top - 6
3776
- } });
3745
+ };
3746
+ const prev = S.quoteSel;
3747
+ if (prev !== null && prev.text === next.text && Math.abs(prev.x - next.x) < 1 && Math.abs(prev.y - next.y) < 1) return;
3748
+ setS({ quoteSel: next });
3777
3749
  } catch {}
3778
3750
  };
3779
3751
  d.addEventListener("selectionchange", onSel);
@@ -3813,7 +3785,7 @@ window.__ModuleLoader__.load({
3813
3785
  const turn = props.turn;
3814
3786
  const s = useS();
3815
3787
  let registered = null;
3816
- const item = seq !== null && s.turns !== null && s.turns.sessionId === S.sessionId ? s.turns.items.find((t) => t.seq === seq) ?? null : null;
3788
+ const item = seq !== null && s.turns !== null && s.turns.sessionId === S.sessionId ? s.turnsBySeq?.get(seq) ?? null : null;
3817
3789
  const btns = [];
3818
3790
  if (item !== null && s.cfg.formula === true) {
3819
3791
  if (item.hasLatex === true) btns.push(react.createElement("button", {
@@ -5337,13 +5309,20 @@ window.__ModuleLoader__.load({
5337
5309
  };
5338
5310
  const d = typeof document !== "undefined" ? document : null;
5339
5311
  if (d === null) return;
5340
- const move = (ev) => setS({ panelPos: {
5341
- x: start.x + ev.clientX - start.mx,
5342
- y: start.y + ev.clientY - start.my
5343
- } });
5312
+ let final = null;
5313
+ const move = (ev) => {
5314
+ final = {
5315
+ x: start.x + ev.clientX - start.mx,
5316
+ y: start.y + ev.clientY - start.my
5317
+ };
5318
+ el.style.left = `${final.x}px`;
5319
+ el.style.top = `${final.y}px`;
5320
+ el.style.right = "auto";
5321
+ };
5344
5322
  const up = () => {
5345
5323
  d.removeEventListener("mousemove", move);
5346
5324
  d.removeEventListener("mouseup", up);
5325
+ if (final !== null) setS({ panelPos: final });
5347
5326
  };
5348
5327
  d.addEventListener("mousemove", move);
5349
5328
  d.addEventListener("mouseup", up);
@@ -5666,6 +5645,29 @@ window.__ModuleLoader__.load({
5666
5645
  for (const unregister of unregisterAll.splice(0)) try {
5667
5646
  unregister();
5668
5647
  } catch {}
5648
+ if (tokenDisposer !== null) {
5649
+ try {
5650
+ tokenDisposer();
5651
+ } catch {}
5652
+ tokenDisposer = null;
5653
+ }
5654
+ if (balanceRetryTimer !== null) {
5655
+ clearTimeout(balanceRetryTimer);
5656
+ balanceRetryTimer = null;
5657
+ }
5658
+ const d = typeof document !== "undefined" ? document : null;
5659
+ if (d !== null) {
5660
+ for (const cls of [
5661
+ "vx-liquid",
5662
+ "vx-dark",
5663
+ "vx-light"
5664
+ ]) try {
5665
+ d.documentElement.classList.remove(cls);
5666
+ } catch {}
5667
+ try {
5668
+ d.getElementById("vx-lg-filter")?.remove();
5669
+ } catch {}
5670
+ }
5669
5671
  removeDynCss();
5670
5672
  };
5671
5673
  }