@alexpeng/dsh-custom-plugin 0.7.0 → 0.8.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.
package/lib/client.js CHANGED
@@ -69,6 +69,7 @@ window.__ModuleLoader__.load({
69
69
  "peakCacheW",
70
70
  "peakOut"
71
71
  ];
72
+ [...PEAK_COUNTER_KEYS];
72
73
  function isCounter(value) {
73
74
  return typeof value === "number" && Number.isFinite(value) && value >= 0;
74
75
  }
@@ -316,6 +317,8 @@ window.__ModuleLoader__.load({
316
317
  "#E6E1D0"
317
318
  ]
318
319
  ];
320
+ /** Parse a #rrggbb (or bare rrggbb) hex color; malformed input yields the
321
+ * palette's neutral gray rather than throwing. */
319
322
  function hexToRgb(hex) {
320
323
  const match = /^#?([0-9a-f]{6})$/i.exec(String(hex ?? "").trim());
321
324
  if (match === null) return [
@@ -524,6 +527,13 @@ window.__ModuleLoader__.load({
524
527
  }
525
528
  //#endregion
526
529
  //#region src/productivity.ts
530
+ function budgetState(summary, budgetCny, warningPercent = 80) {
531
+ if (!Number.isFinite(budgetCny) || budgetCny <= 0) return "disabled";
532
+ if (!summary.exact) return "unknown";
533
+ const ratio = summary.costCny / budgetCny * 100;
534
+ if (ratio >= 100) return "over";
535
+ return ratio >= Math.max(1, Math.min(100, warningPercent)) ? "warning" : "ok";
536
+ }
527
537
  function summarizeUsage(usage, days) {
528
538
  const out = {
529
539
  tokens: 0,
@@ -805,6 +815,48 @@ window.__ModuleLoader__.load({
805
815
  return "https://mermaid.live/edit#pako:" + (await deflateZlibBase64Url(state) ?? bytesToBase64Url(new TextEncoder().encode(state)));
806
816
  }
807
817
  //#endregion
818
+ //#region src/client/timeline-diff.ts
819
+ /** Whether two timeline entries would render identically. */
820
+ function sameTimelineItem(a, b) {
821
+ return a.seq === b.seq && a.time === b.time && a.turn === b.turn && a.text === b.text && a.imageCount === b.imageCount && a.hasLatex === b.hasLatex && a.hasMathml === b.hasMathml && a.hasMermaid === b.hasMermaid;
822
+ }
823
+ /**
824
+ * Diff one fetched timeline against the previous snapshot by sequence.
825
+ * @param previous - previous ordered items, or null when this is the first fetch.
826
+ * @param previousBySeq - seq index for `previous` (same generation), or null.
827
+ * @param next - freshly fetched items.
828
+ * @returns reused items plus whether any rendered field changed.
829
+ */
830
+ function reuseTimelineItems(previous, previousBySeq, next) {
831
+ const bySeq = /* @__PURE__ */ new Map();
832
+ const items = [];
833
+ let changed = previous === null || previous.length !== next.length;
834
+ for (let index = 0; index < next.length; index++) {
835
+ const raw = next[index];
836
+ const old = previousBySeq?.get(raw.seq);
837
+ const item = old !== void 0 && sameTimelineItem(old, raw) ? old : raw;
838
+ items.push(item);
839
+ bySeq.set(item.seq, item);
840
+ if (!changed && previous !== null && previous[index] !== item) changed = true;
841
+ }
842
+ return {
843
+ items,
844
+ bySeq,
845
+ changed
846
+ };
847
+ }
848
+ /** Compact DOM identity for a rendered Mermaid block. A 32-bit FNV-1a hash
849
+ * plus the source length is enough to distinguish live blocks without
850
+ * duplicating every diagram's text into a `data-*` attribute. */
851
+ function mermaidCodeKey(code) {
852
+ let hash = 2166136261;
853
+ for (let i = 0; i < code.length; i++) {
854
+ hash ^= code.charCodeAt(i);
855
+ hash = Math.imul(hash, 16777619);
856
+ }
857
+ return (hash >>> 0).toString(36) + "-" + code.length.toString(36);
858
+ }
859
+ //#endregion
808
860
  //#region src/client/styles.ts
809
861
  /**
810
862
  * Static styles for the Custom suite, injected as one owned <style> tag at
@@ -878,6 +930,36 @@ window.__ModuleLoader__.load({
878
930
  color: #eef1f7;
879
931
  }
880
932
  }
933
+ /* The GUI theme can disagree with the OS scheme (dsh selects light/dark
934
+ independently — dark GUI on a light OS left these surfaces frosted
935
+ light), so the frost fills and panel text colors key on the mirrored
936
+ root classes, not the OS alone. The media queries above remain the
937
+ pre-boot fallback, before the client has applied the classes; the liquid
938
+ rules below out-rank these by specificity, not by order. */
939
+ :root.vx-light .vx-glass {
940
+ background: rgba(255, 255, 255, .64);
941
+ color: inherit;
942
+ }
943
+ :root.vx-dark .vx-glass {
944
+ background: rgba(13, 17, 25, .62);
945
+ color: #eef1f7;
946
+ }
947
+ :root.vx-light .vx-panel,
948
+ :root.vx-light .vx-modal,
949
+ :root.vx-light .vx-folders {
950
+ color: #20242e;
951
+ }
952
+ :root.vx-dark .vx-panel,
953
+ :root.vx-dark .vx-modal,
954
+ :root.vx-dark .vx-folders {
955
+ color: #e8ebf2;
956
+ }
957
+ :root.vx-light .vx-balance-hover {
958
+ color: #20242e;
959
+ }
960
+ :root.vx-dark .vx-balance-hover {
961
+ color: #e8ebf2;
962
+ }
881
963
  /* Liquid glass: the SVG displacement filter bends the backdrop at the
882
964
  surface's edges; the chained blur+saturate keeps text over the middle of
883
965
  large panels readable (pure displacement leaves the mid-area untouched,
@@ -1126,10 +1208,6 @@ window.__ModuleLoader__.load({
1126
1208
  border-color: #7fa4e0;
1127
1209
  box-shadow: 0 0 0 2px rgba(127, 164, 224, .35);
1128
1210
  }
1129
- .vx-swatch:disabled {
1130
- opacity: .35;
1131
- cursor: not-allowed;
1132
- }
1133
1211
  .vx-swatch-label {
1134
1212
  font-size: 10px;
1135
1213
  opacity: .85;
@@ -1180,16 +1258,6 @@ window.__ModuleLoader__.load({
1180
1258
  padding: 6px 10px;
1181
1259
  font-size: 12px;
1182
1260
  }
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
1261
  .vx-toggle-row {
1194
1262
  display: flex;
1195
1263
  gap: 8px;
@@ -1597,7 +1665,7 @@ window.__ModuleLoader__.load({
1597
1665
  .vx-root.vx-light .vx-toast {
1598
1666
  background: rgba(26, 32, 44, .92);
1599
1667
  }
1600
- }`;
1668
+ `;
1601
1669
  //#endregion
1602
1670
  //#region src/client/custom.tsx
1603
1671
  /**
@@ -1693,6 +1761,7 @@ window.__ModuleLoader__.load({
1693
1761
  usage: {},
1694
1762
  sessionId: null,
1695
1763
  turns: null,
1764
+ turnsBySeq: null,
1696
1765
  anchors: /* @__PURE__ */ new Map(),
1697
1766
  panelOpen: false,
1698
1767
  panelTab: "look",
@@ -1739,6 +1808,46 @@ window.__ModuleLoader__.load({
1739
1808
  }, []);
1740
1809
  return S;
1741
1810
  }
1811
+ /** Shallow object equality for selector results. */
1812
+ function shallowEqual(a, b) {
1813
+ if (a === b) return true;
1814
+ const aKeys = Object.keys(a);
1815
+ if (aKeys.length !== Object.keys(b).length) return false;
1816
+ for (const key of aKeys) if (!Object.is(a[key], b[key])) return false;
1817
+ return true;
1818
+ }
1819
+ /**
1820
+ * Subscribe to a slice of the store. The store fan-out is intentionally
1821
+ * simple (one listener set), but per-turn entries are the hot path: a
1822
+ * balance tick or a toast must not re-render 400 turn-tail rows. The
1823
+ * selector runs on every store write; only an unequal result forces a
1824
+ * render.
1825
+ */
1826
+ function useSSelector(selector, equal = Object.is) {
1827
+ const [, force] = react.useReducer((x) => x + 1, 0);
1828
+ const selectorRef = react.useRef(selector);
1829
+ selectorRef.current = selector;
1830
+ const equalRef = react.useRef(equal);
1831
+ equalRef.current = equal;
1832
+ const current = selector(S);
1833
+ const currentRef = react.useRef(current);
1834
+ currentRef.current = current;
1835
+ react.useEffect(() => {
1836
+ const listener = () => {
1837
+ const next = selectorRef.current(S);
1838
+ if (!equalRef.current(currentRef.current, next)) {
1839
+ currentRef.current = next;
1840
+ force();
1841
+ }
1842
+ };
1843
+ listeners.push(listener);
1844
+ listener();
1845
+ return () => {
1846
+ listeners = listeners.filter((l) => l !== listener);
1847
+ };
1848
+ }, []);
1849
+ return current;
1850
+ }
1742
1851
  function useSessionsSafe(props) {
1743
1852
  try {
1744
1853
  return props.useSessions((st) => st);
@@ -1780,7 +1889,8 @@ window.__ModuleLoader__.load({
1780
1889
  S.anchors.clear();
1781
1890
  setS({
1782
1891
  sessionId: id,
1783
- turns: null
1892
+ turns: null,
1893
+ turnsBySeq: null
1784
1894
  });
1785
1895
  fetchTurns(id);
1786
1896
  }
@@ -1790,7 +1900,8 @@ window.__ModuleLoader__.load({
1790
1900
  S.anchors.clear();
1791
1901
  setS({
1792
1902
  sessionId: null,
1793
- turns: null
1903
+ turns: null,
1904
+ turnsBySeq: null
1794
1905
  });
1795
1906
  }
1796
1907
  };
@@ -1870,11 +1981,6 @@ window.__ModuleLoader__.load({
1870
1981
  }]
1871
1982
  ],
1872
1983
  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
1984
  download: [
1879
1985
  ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }],
1880
1986
  ["polyline", { points: "7 10 12 15 17 10" }],
@@ -1941,25 +2047,6 @@ window.__ModuleLoader__.load({
1941
2047
  y2: 18
1942
2048
  }]],
1943
2049
  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
2050
  copy: [["rect", {
1964
2051
  x: 9,
1965
2052
  y: 9,
@@ -2092,8 +2179,6 @@ window.__ModuleLoader__.load({
2092
2179
  r: 2.1
2093
2180
  }]
2094
2181
  ],
2095
- arrowUp: [["polyline", { points: "18 15 12 9 6 15" }]],
2096
- arrowDown: [["polyline", { points: "6 9 12 15 18 9" }]],
2097
2182
  minimize: [
2098
2183
  ["polyline", { points: "4 14 10 14 10 20" }],
2099
2184
  ["polyline", { points: "20 10 14 10 14 4" }],
@@ -2110,62 +2195,6 @@ window.__ModuleLoader__.load({
2110
2195
  y2: 14
2111
2196
  }]
2112
2197
  ],
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
2198
  list: [
2170
2199
  ["line", {
2171
2200
  x1: 8,
@@ -2273,20 +2302,6 @@ window.__ModuleLoader__.load({
2273
2302
  cb
2274
2303
  } });
2275
2304
  }
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
2305
  function rgbaOf(hex, alpha) {
2291
2306
  const c = hexToRgb(hex);
2292
2307
  return `rgba(${c[0]},${c[1]},${c[2]},${alpha})`;
@@ -2384,7 +2399,16 @@ window.__ModuleLoader__.load({
2384
2399
  6e3
2385
2400
  ];
2386
2401
  let loadCfgAttempt = 0;
2402
+ let loadRetryTimer = null;
2403
+ let greetTimer = null;
2404
+ let disposed = false;
2405
+ let cfgLoaded = false;
2387
2406
  async function loadCfg() {
2407
+ if (disposed) return;
2408
+ if (loadRetryTimer !== null) {
2409
+ clearTimeout(loadRetryTimer);
2410
+ loadRetryTimer = null;
2411
+ }
2388
2412
  let failure = null;
2389
2413
  try {
2390
2414
  const result = await apiStateGet();
@@ -2410,6 +2434,7 @@ window.__ModuleLoader__.load({
2410
2434
  if (data.credentialStorage === "system" || data.credentialStorage === "legacy-state" || data.credentialStorage === "environment" || data.credentialStorage === "dsh" || data.credentialStorage === "none") S.credentialStorage = data.credentialStorage;
2411
2435
  if (data.usage !== void 0 && data.usage !== null && typeof data.usage === "object") S.usage = data.usage;
2412
2436
  loadCfgAttempt = 0;
2437
+ cfgLoaded = true;
2413
2438
  } else if (result.ok !== true) failure = result.error ?? "状态读取失败";
2414
2439
  } catch (error) {
2415
2440
  failure = String(error?.message ?? error);
@@ -2419,19 +2444,34 @@ window.__ModuleLoader__.load({
2419
2444
  if (loadCfgAttempt < LOAD_RETRY_DELAYS.length) {
2420
2445
  const delay = LOAD_RETRY_DELAYS[loadCfgAttempt];
2421
2446
  loadCfgAttempt++;
2422
- setTimeout(() => {
2447
+ if (loadRetryTimer !== null) clearTimeout(loadRetryTimer);
2448
+ loadRetryTimer = setTimeout(() => {
2449
+ loadRetryTimer = null;
2423
2450
  loadCfg();
2424
2451
  }, delay);
2425
2452
  } else if (S.booted) toast("配置读取失败:" + failure, "error");
2426
2453
  }
2454
+ if (disposed) return;
2427
2455
  S.booted = true;
2428
2456
  setS({});
2429
2457
  if (!S.greeted) {
2430
2458
  S.greeted = true;
2431
- new Promise((resolve) => setTimeout(resolve, 1200)).then(() => toast(failure !== null ? "Custom 便利套件加载失败:" + failure : "Custom 便利套件已就绪", failure !== null ? "error" : "info")).catch(() => {});
2459
+ if (greetTimer !== null) clearTimeout(greetTimer);
2460
+ greetTimer = setTimeout(() => {
2461
+ greetTimer = null;
2462
+ if (disposed) return;
2463
+ toast(failure !== null ? "Custom 便利套件加载失败:" + failure : "Custom 便利套件已就绪", failure !== null ? "error" : "info");
2464
+ }, 1200);
2432
2465
  }
2433
2466
  }
2434
2467
  function saveCfg() {
2468
+ if (disposed) return;
2469
+ if (!cfgLoaded) {
2470
+ toast("配置尚未读取完成,已重新加载,请重试", "error");
2471
+ loadCfgAttempt = 0;
2472
+ loadCfg();
2473
+ return;
2474
+ }
2435
2475
  const cfg = { ...S.cfg };
2436
2476
  delete cfg.clouds;
2437
2477
  delete cfg.wind;
@@ -2785,14 +2825,17 @@ window.__ModuleLoader__.load({
2785
2825
  }
2786
2826
  }
2787
2827
  function FxCanvas() {
2788
- const s = useS();
2828
+ const { weather, dark } = useSSelector((state) => ({
2829
+ weather: state.cfg.weather ?? "none",
2830
+ dark: state.dark === true
2831
+ }), shallowEqual);
2789
2832
  const ref = react.useRef(null);
2790
2833
  /** 粒子配色跟随背景亮度:浅色主题需要更深的粒子颜色才可辨识。
2791
2834
  * ref 让 RAF 循环每帧读到最新值,主题/背景切换时无需重建粒子场。 */
2792
- const lightRef = react.useRef(!(s.dark === true));
2835
+ const lightRef = react.useRef(!dark);
2793
2836
  react.useEffect(() => {
2794
- lightRef.current = !(s.dark === true);
2795
- }, [s.dark]);
2837
+ lightRef.current = !dark;
2838
+ }, [dark]);
2796
2839
  react.useEffect(() => {
2797
2840
  const cvs = ref.current;
2798
2841
  if (cvs === null) return;
@@ -2800,11 +2843,10 @@ window.__ModuleLoader__.load({
2800
2843
  if (g === null) return;
2801
2844
  const w = cvs.clientWidth || 0;
2802
2845
  const h = cvs.clientHeight || 0;
2803
- initFx(s.cfg.weather ?? "none", w, h);
2846
+ initFx(weather, w, h);
2804
2847
  let raf = 0;
2805
2848
  const t0 = Date.now();
2806
2849
  const loop = () => {
2807
- const weather = s.cfg.weather ?? "none";
2808
2850
  if (weather === "none") {
2809
2851
  try {
2810
2852
  g.clearRect(0, 0, cvs.width, cvs.height);
@@ -2820,7 +2862,7 @@ window.__ModuleLoader__.load({
2820
2862
  cancelAnimationFrame(raf);
2821
2863
  } catch {}
2822
2864
  };
2823
- }, [s.cfg.weather]);
2865
+ }, [weather]);
2824
2866
  return react.createElement("canvas", {
2825
2867
  ref,
2826
2868
  className: "vx-fx"
@@ -2833,6 +2875,7 @@ window.__ModuleLoader__.load({
2833
2875
  const now = Date.now();
2834
2876
  const at = diagAtByKey.get(key);
2835
2877
  if (at !== void 0 && now - at < 5e3) return;
2878
+ if (diagAtByKey.size > 200) diagAtByKey.clear();
2836
2879
  diagAtByKey.set(key, now);
2837
2880
  reportDiag(message);
2838
2881
  }
@@ -2840,14 +2883,22 @@ window.__ModuleLoader__.load({
2840
2883
  const requestSerial = ++turnsRequestSerial;
2841
2884
  try {
2842
2885
  const result = await apiTimelineGet(sessionId);
2843
- if (sessionId !== S.sessionId || requestSerial !== turnsRequestSerial) return;
2886
+ if (sessionId !== S.sessionId || requestSerial !== turnsRequestSerial || disposed) return;
2844
2887
  if (result.ok === true) {
2888
+ const items = result.items ?? [];
2889
+ const previous = S.turns !== null && S.turns.sessionId === sessionId ? S.turns : null;
2890
+ const diff = reuseTimelineItems(previous?.items ?? null, previous !== null ? S.turnsBySeq : null, items);
2891
+ if (!diff.changed) return;
2845
2892
  S.turns = {
2846
2893
  sessionId,
2847
- items: result.items ?? []
2894
+ items: diff.items
2848
2895
  };
2849
- setS({ turns: S.turns });
2850
- diagThrottled("timeline " + (result.items?.length ?? 0) + " items " + sessionId.slice(0, 24));
2896
+ S.turnsBySeq = diff.bySeq;
2897
+ setS({
2898
+ turns: S.turns,
2899
+ turnsBySeq: diff.bySeq
2900
+ });
2901
+ diagThrottled("timeline " + items.length + " items " + sessionId.slice(0, 24));
2851
2902
  } else diagThrottled("timeline failed: " + String(result.error ?? "unknown"));
2852
2903
  } catch (error) {
2853
2904
  diagThrottled("timeline fetch error: " + String(error?.message ?? error));
@@ -3015,6 +3066,17 @@ window.__ModuleLoader__.load({
3015
3066
  return mermaidState.status === "ready";
3016
3067
  }
3017
3068
  mermaidState = { status: "loading" };
3069
+ const d0 = typeof document !== "undefined" ? document : null;
3070
+ const watchdog = setTimeout(() => {
3071
+ if (mermaidState.status !== "loading") return;
3072
+ mermaidState = {
3073
+ status: "failed",
3074
+ error: "脚本加载超时"
3075
+ };
3076
+ try {
3077
+ if (d0 !== null) for (const el of d0.querySelectorAll(`script[src="${MERMAID_SCRIPT_PATH}"]`)) el.remove();
3078
+ } catch {}
3079
+ }, 3e4);
3018
3080
  try {
3019
3081
  const result = await apiMermaidFetch();
3020
3082
  if (result.ok === true) {
@@ -3027,10 +3089,17 @@ window.__ModuleLoader__.load({
3027
3089
  const script = d.createElement("script");
3028
3090
  script.src = MERMAID_SCRIPT_PATH;
3029
3091
  script.onload = () => resolve();
3030
- script.onerror = () => reject(/* @__PURE__ */ new Error("script load failed"));
3092
+ script.onerror = () => {
3093
+ script.remove();
3094
+ reject(/* @__PURE__ */ new Error("script load failed"));
3095
+ };
3031
3096
  d.head.appendChild(script);
3032
3097
  });
3033
3098
  mermaidState = { status: "ready" };
3099
+ if (d0 !== null) {
3100
+ for (const el of Array.from(d0.querySelectorAll("[data-vx-mmd-fail]"))) delete el.dataset.vxMmdFail;
3101
+ if (S.cfg.mermaid === true) scanMermaidBlocks(S.dark);
3102
+ }
3034
3103
  return true;
3035
3104
  }
3036
3105
  mermaidState = {
@@ -3044,6 +3113,8 @@ window.__ModuleLoader__.load({
3044
3113
  error: String(error?.message ?? error)
3045
3114
  };
3046
3115
  return false;
3116
+ } finally {
3117
+ clearTimeout(watchdog);
3047
3118
  }
3048
3119
  }
3049
3120
  async function renderMermaid(code, dark = false) {
@@ -3116,18 +3187,19 @@ window.__ModuleLoader__.load({
3116
3187
  * GUI-owned nodes — React keeps reconciling its tree; the block is only
3117
3188
  * visually swapped with the diagram stage via display. */
3118
3189
  async function renderInPlace(block, code, dark) {
3119
- if (block.dataset.vxMmd === code) return;
3190
+ const key = mermaidCodeKey(code);
3191
+ const existingWrap = block.previousElementSibling;
3192
+ if (block.dataset.vxMmd === key && existingWrap !== null && existingWrap.classList.contains("vx-mmd-wrap")) return;
3120
3193
  if (!await ensureMermaid()) {
3121
- block.dataset.vxMmdFail = code;
3194
+ block.dataset.vxMmdFail = key;
3122
3195
  return;
3123
3196
  }
3124
3197
  const r = await renderMermaid(code, dark);
3125
3198
  if (!r.ok) {
3126
- block.dataset.vxMmdFail = code;
3199
+ block.dataset.vxMmdFail = key;
3127
3200
  return;
3128
3201
  }
3129
3202
  delete block.dataset.vxMmdFail;
3130
- block.dataset.vxMmd = code;
3131
3203
  const d = typeof document !== "undefined" ? document : null;
3132
3204
  if (d === null) return;
3133
3205
  let wrap = block.previousElementSibling;
@@ -3174,7 +3246,9 @@ window.__ModuleLoader__.load({
3174
3246
  showDiagram();
3175
3247
  }
3176
3248
  const stage = wrap.querySelector(".vx-mmd-stage");
3177
- if (stage !== null) stage.innerHTML = r.svg;
3249
+ if (stage === null) return;
3250
+ stage.innerHTML = r.svg;
3251
+ block.dataset.vxMmd = key;
3178
3252
  }
3179
3253
  /** Scan every chat code block and render the mermaid ones in place. */
3180
3254
  async function scanMermaidBlocks(dark) {
@@ -3190,6 +3264,7 @@ window.__ModuleLoader__.load({
3190
3264
  if (codeRaw === null) continue;
3191
3265
  const code = normalizeMermaidText(codeRaw).trim();
3192
3266
  if (code === "") continue;
3267
+ const key = mermaidCodeKey(code);
3193
3268
  const info = blockInfostring(block);
3194
3269
  if (info !== null && info.trim().toLowerCase() === "mermaid") {
3195
3270
  if (code.split("\n").filter((l) => l.trim() !== "").length < 2) continue;
@@ -3197,7 +3272,7 @@ window.__ModuleLoader__.load({
3197
3272
  if (!isGenericInfostring(info)) continue;
3198
3273
  if (!isMermaidCode(codeRaw)) continue;
3199
3274
  }
3200
- if (block.dataset.vxMmd === code || block.dataset.vxMmdFail === code) continue;
3275
+ if (block.dataset.vxMmd === key || block.dataset.vxMmdFail === key) continue;
3201
3276
  mmdInflight.add(block);
3202
3277
  try {
3203
3278
  await renderInPlace(block, code, dark);
@@ -3577,23 +3652,32 @@ window.__ModuleLoader__.load({
3577
3652
  }
3578
3653
  function UsageHistory() {
3579
3654
  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);
3655
+ const { summary, daily, maxTokens, byModel, month } = react.useMemo(() => {
3656
+ const keys = recentDayKeys(s.usageRange);
3657
+ const selected = new Set(keys);
3658
+ const summary = summarizeUsage(s.usage, selected);
3659
+ const daily = keys.map((day) => ({
3660
+ day,
3661
+ ...summarizeUsage(s.usage, /* @__PURE__ */ new Set([day]))
3662
+ }));
3663
+ const maxTokens = Math.max(1, ...daily.map((row) => row.tokens));
3664
+ const byModel = Object.create(null);
3665
+ for (const day of keys) for (const [model, row] of Object.entries(s.usage[day] ?? {})) mergeUsageRow(byModel[model] ?? (byModel[model] = createUsageRow()), row);
3666
+ const monthPrefix = dayKey().slice(0, 7) + "-";
3667
+ const monthDays = new Set(Object.keys(s.usage).filter((day) => day.startsWith(monthPrefix)));
3668
+ return {
3669
+ summary,
3670
+ daily,
3671
+ maxTokens,
3672
+ byModel,
3673
+ month: summarizeUsage(s.usage, monthDays)
3674
+ };
3675
+ }, [s.usage, s.usageRange]);
3593
3676
  const budget = Math.max(0, Number(s.cfg.monthlyBudgetCny ?? 0));
3594
3677
  const warning = Math.max(1, Math.min(100, Number(s.cfg.budgetWarningPercent ?? 80)));
3595
3678
  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)}%`;
3679
+ const state = budgetState(month, budget, warning);
3680
+ const budgetText = state === "disabled" ? "预算提醒已关闭" : state === "unknown" ? "历史峰闲数据不完整,无法判断预算" : state === "over" ? `已超出月预算(${ratio.toFixed(0)}%)` : state === "warning" ? `已达到月预算 ${ratio.toFixed(0)}%` : `本月预算使用 ${ratio.toFixed(0)}%`;
3597
3681
  return react.createElement("div", { className: "vx-col" }, react.createElement("div", { className: "vx-row wrap" }, [
3598
3682
  7,
3599
3683
  30,
@@ -3633,7 +3717,7 @@ window.__ModuleLoader__.load({
3633
3717
  } })))), 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
3718
  const cost = usageCostBreakdown(row, model);
3635
3719
  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", {
3720
+ }))) : 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
3721
  className: "vx-input",
3638
3722
  style: { width: 100 },
3639
3723
  type: "number",
@@ -3769,11 +3853,14 @@ window.__ModuleLoader__.load({
3769
3853
  const node = sel.anchorNode;
3770
3854
  if (node !== null && node.nodeType === 1 && /TEXTAREA|INPUT/.test(node.nodeName)) return;
3771
3855
  const r = range.getBoundingClientRect();
3772
- setS({ quoteSel: {
3856
+ const next = {
3773
3857
  text: text.slice(0, 8e3),
3774
3858
  x: r.left + r.width / 2,
3775
3859
  y: r.top - 6
3776
- } });
3860
+ };
3861
+ const prev = S.quoteSel;
3862
+ if (prev !== null && prev.text === next.text && Math.abs(prev.x - next.x) < 1 && Math.abs(prev.y - next.y) < 1) return;
3863
+ setS({ quoteSel: next });
3777
3864
  } catch {}
3778
3865
  };
3779
3866
  d.addEventListener("selectionchange", onSel);
@@ -3811,11 +3898,14 @@ window.__ModuleLoader__.load({
3811
3898
  useViewedSession(props);
3812
3899
  const seq = typeof props.seq === "number" ? props.seq : null;
3813
3900
  const turn = props.turn;
3814
- const s = useS();
3901
+ const { item, formula, mermaid } = useSSelector((state) => ({
3902
+ item: seq !== null && state.turns !== null && state.turns.sessionId === state.sessionId ? state.turnsBySeq?.get(seq) ?? null : null,
3903
+ formula: state.cfg.formula === true,
3904
+ mermaid: state.cfg.mermaid === true
3905
+ }), shallowEqual);
3815
3906
  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;
3817
3907
  const btns = [];
3818
- if (item !== null && s.cfg.formula === true) {
3908
+ if (item !== null && formula) {
3819
3909
  if (item.hasLatex === true) btns.push(react.createElement("button", {
3820
3910
  key: "lx",
3821
3911
  className: "vx-chip",
@@ -3835,7 +3925,7 @@ window.__ModuleLoader__.load({
3835
3925
  size: 11
3836
3926
  }), " MathML"));
3837
3927
  }
3838
- if (item !== null && s.cfg.mermaid === true && item.hasMermaid === true) btns.push(react.createElement("button", {
3928
+ if (item !== null && mermaid && item.hasMermaid === true) btns.push(react.createElement("button", {
3839
3929
  key: "md",
3840
3930
  className: "vx-chip",
3841
3931
  title: "渲染 Mermaid 图表",
@@ -5337,13 +5427,20 @@ window.__ModuleLoader__.load({
5337
5427
  };
5338
5428
  const d = typeof document !== "undefined" ? document : null;
5339
5429
  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
- } });
5430
+ let final = null;
5431
+ const move = (ev) => {
5432
+ final = {
5433
+ x: start.x + ev.clientX - start.mx,
5434
+ y: start.y + ev.clientY - start.my
5435
+ };
5436
+ el.style.left = `${final.x}px`;
5437
+ el.style.top = `${final.y}px`;
5438
+ el.style.right = "auto";
5439
+ };
5344
5440
  const up = () => {
5345
5441
  d.removeEventListener("mousemove", move);
5346
5442
  d.removeEventListener("mouseup", up);
5443
+ if (final !== null) setS({ panelPos: final });
5347
5444
  };
5348
5445
  d.addEventListener("mousemove", move);
5349
5446
  d.addEventListener("mouseup", up);
@@ -5492,6 +5589,9 @@ window.__ModuleLoader__.load({
5492
5589
  ]);
5493
5590
  react.useEffect(() => {
5494
5591
  syncAntiScroll(s.cfg.antiScroll === true);
5592
+ return () => {
5593
+ syncAntiScroll(false);
5594
+ };
5495
5595
  }, [s.cfg.antiScroll]);
5496
5596
  react.useEffect(() => {
5497
5597
  const w = typeof window !== "undefined" ? window : null;
@@ -5546,12 +5646,32 @@ window.__ModuleLoader__.load({
5546
5646
  const sessions = useSessionsSafe(props);
5547
5647
  const summary = sessions !== null && s.sessionId !== null ? sessions.byId[s.sessionId] : null;
5548
5648
  react.useEffect(() => {
5549
- if (S.sessionId === null) return;
5550
- const running = summary?.running === true;
5551
- const handle = setInterval(() => {
5552
- if (running && S.sessionId !== null) fetchTurns(S.sessionId);
5553
- }, 3e3);
5554
- return () => clearInterval(handle);
5649
+ const watchedId = S.sessionId;
5650
+ if (watchedId === null) return;
5651
+ if (!(summary?.running === true)) return;
5652
+ let inFlight = false;
5653
+ const tick = () => {
5654
+ if (inFlight) return;
5655
+ const d = typeof document !== "undefined" ? document : null;
5656
+ if (d !== null && d.hidden) return;
5657
+ const id = S.sessionId;
5658
+ if (id === null) return;
5659
+ inFlight = true;
5660
+ fetchTurns(id).finally(() => {
5661
+ inFlight = false;
5662
+ });
5663
+ };
5664
+ const handle = setInterval(tick, 3e3);
5665
+ const onVisibility = () => {
5666
+ const d = typeof document !== "undefined" ? document : null;
5667
+ if (d === null || !d.hidden) tick();
5668
+ };
5669
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisibility);
5670
+ return () => {
5671
+ clearInterval(handle);
5672
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisibility);
5673
+ if (!disposed && S.sessionId === watchedId) fetchTurns(watchedId);
5674
+ };
5555
5675
  }, [s.sessionId, summary?.running]);
5556
5676
  const children = [react.createElement(FxCanvas, { key: "fx" })];
5557
5677
  children.push(react.createElement(MermaidInPlace, { key: "mmd" }));
@@ -5663,9 +5783,47 @@ window.__ModuleLoader__.load({
5663
5783
  }, HeaderBalance);
5664
5784
  reportDiag(`client installed: ${injectedCount} injection requests / ${injectedKeys.size} slots`);
5665
5785
  return () => {
5786
+ disposed = true;
5666
5787
  for (const unregister of unregisterAll.splice(0)) try {
5667
5788
  unregister();
5668
5789
  } catch {}
5790
+ if (loadRetryTimer !== null) {
5791
+ clearTimeout(loadRetryTimer);
5792
+ loadRetryTimer = null;
5793
+ }
5794
+ if (greetTimer !== null) {
5795
+ clearTimeout(greetTimer);
5796
+ greetTimer = null;
5797
+ }
5798
+ if (tokenDisposer !== null) {
5799
+ try {
5800
+ tokenDisposer();
5801
+ } catch {}
5802
+ tokenDisposer = null;
5803
+ }
5804
+ if (balanceRetryTimer !== null) {
5805
+ clearTimeout(balanceRetryTimer);
5806
+ balanceRetryTimer = null;
5807
+ }
5808
+ try {
5809
+ syncAntiScroll(false);
5810
+ } catch {}
5811
+ try {
5812
+ restoreMermaidBlocks();
5813
+ } catch {}
5814
+ const d = typeof document !== "undefined" ? document : null;
5815
+ if (d !== null) {
5816
+ for (const cls of [
5817
+ "vx-liquid",
5818
+ "vx-dark",
5819
+ "vx-light"
5820
+ ]) try {
5821
+ d.documentElement.classList.remove(cls);
5822
+ } catch {}
5823
+ try {
5824
+ d.getElementById("vx-lg-filter")?.remove();
5825
+ } catch {}
5826
+ }
5669
5827
  removeDynCss();
5670
5828
  };
5671
5829
  }