@alexpeng/dsh-custom-plugin 0.7.1 → 0.9.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
  }
@@ -814,6 +815,48 @@ window.__ModuleLoader__.load({
814
815
  return "https://mermaid.live/edit#pako:" + (await deflateZlibBase64Url(state) ?? bytesToBase64Url(new TextEncoder().encode(state)));
815
816
  }
816
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
817
860
  //#region src/client/styles.ts
818
861
  /**
819
862
  * Static styles for the Custom suite, injected as one owned <style> tag at
@@ -1765,6 +1808,46 @@ window.__ModuleLoader__.load({
1765
1808
  }, []);
1766
1809
  return S;
1767
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
+ }
1768
1851
  function useSessionsSafe(props) {
1769
1852
  try {
1770
1853
  return props.useSessions((st) => st);
@@ -2316,8 +2399,16 @@ window.__ModuleLoader__.load({
2316
2399
  6e3
2317
2400
  ];
2318
2401
  let loadCfgAttempt = 0;
2402
+ let loadRetryTimer = null;
2403
+ let greetTimer = null;
2404
+ let disposed = false;
2319
2405
  let cfgLoaded = false;
2320
2406
  async function loadCfg() {
2407
+ if (disposed) return;
2408
+ if (loadRetryTimer !== null) {
2409
+ clearTimeout(loadRetryTimer);
2410
+ loadRetryTimer = null;
2411
+ }
2321
2412
  let failure = null;
2322
2413
  try {
2323
2414
  const result = await apiStateGet();
@@ -2353,19 +2444,28 @@ window.__ModuleLoader__.load({
2353
2444
  if (loadCfgAttempt < LOAD_RETRY_DELAYS.length) {
2354
2445
  const delay = LOAD_RETRY_DELAYS[loadCfgAttempt];
2355
2446
  loadCfgAttempt++;
2356
- setTimeout(() => {
2447
+ if (loadRetryTimer !== null) clearTimeout(loadRetryTimer);
2448
+ loadRetryTimer = setTimeout(() => {
2449
+ loadRetryTimer = null;
2357
2450
  loadCfg();
2358
2451
  }, delay);
2359
2452
  } else if (S.booted) toast("配置读取失败:" + failure, "error");
2360
2453
  }
2454
+ if (disposed) return;
2361
2455
  S.booted = true;
2362
2456
  setS({});
2363
2457
  if (!S.greeted) {
2364
2458
  S.greeted = true;
2365
- 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);
2366
2465
  }
2367
2466
  }
2368
2467
  function saveCfg() {
2468
+ if (disposed) return;
2369
2469
  if (!cfgLoaded) {
2370
2470
  toast("配置尚未读取完成,已重新加载,请重试", "error");
2371
2471
  loadCfgAttempt = 0;
@@ -2725,14 +2825,17 @@ window.__ModuleLoader__.load({
2725
2825
  }
2726
2826
  }
2727
2827
  function FxCanvas() {
2728
- const s = useS();
2828
+ const { weather, dark } = useSSelector((state) => ({
2829
+ weather: state.cfg.weather ?? "none",
2830
+ dark: state.dark === true
2831
+ }), shallowEqual);
2729
2832
  const ref = react.useRef(null);
2730
2833
  /** 粒子配色跟随背景亮度:浅色主题需要更深的粒子颜色才可辨识。
2731
2834
  * ref 让 RAF 循环每帧读到最新值,主题/背景切换时无需重建粒子场。 */
2732
- const lightRef = react.useRef(!(s.dark === true));
2835
+ const lightRef = react.useRef(!dark);
2733
2836
  react.useEffect(() => {
2734
- lightRef.current = !(s.dark === true);
2735
- }, [s.dark]);
2837
+ lightRef.current = !dark;
2838
+ }, [dark]);
2736
2839
  react.useEffect(() => {
2737
2840
  const cvs = ref.current;
2738
2841
  if (cvs === null) return;
@@ -2740,11 +2843,10 @@ window.__ModuleLoader__.load({
2740
2843
  if (g === null) return;
2741
2844
  const w = cvs.clientWidth || 0;
2742
2845
  const h = cvs.clientHeight || 0;
2743
- initFx(s.cfg.weather ?? "none", w, h);
2846
+ initFx(weather, w, h);
2744
2847
  let raf = 0;
2745
2848
  const t0 = Date.now();
2746
2849
  const loop = () => {
2747
- const weather = s.cfg.weather ?? "none";
2748
2850
  if (weather === "none") {
2749
2851
  try {
2750
2852
  g.clearRect(0, 0, cvs.width, cvs.height);
@@ -2760,7 +2862,7 @@ window.__ModuleLoader__.load({
2760
2862
  cancelAnimationFrame(raf);
2761
2863
  } catch {}
2762
2864
  };
2763
- }, [s.cfg.weather]);
2865
+ }, [weather]);
2764
2866
  return react.createElement("canvas", {
2765
2867
  ref,
2766
2868
  className: "vx-fx"
@@ -2773,6 +2875,7 @@ window.__ModuleLoader__.load({
2773
2875
  const now = Date.now();
2774
2876
  const at = diagAtByKey.get(key);
2775
2877
  if (at !== void 0 && now - at < 5e3) return;
2878
+ if (diagAtByKey.size > 200) diagAtByKey.clear();
2776
2879
  diagAtByKey.set(key, now);
2777
2880
  reportDiag(message);
2778
2881
  }
@@ -2780,19 +2883,20 @@ window.__ModuleLoader__.load({
2780
2883
  const requestSerial = ++turnsRequestSerial;
2781
2884
  try {
2782
2885
  const result = await apiTimelineGet(sessionId);
2783
- if (sessionId !== S.sessionId || requestSerial !== turnsRequestSerial) return;
2886
+ if (sessionId !== S.sessionId || requestSerial !== turnsRequestSerial || disposed) return;
2784
2887
  if (result.ok === true) {
2785
2888
  const items = result.items ?? [];
2786
- const bySeq = /* @__PURE__ */ new Map();
2787
- for (const item of items) bySeq.set(item.seq, item);
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;
2788
2892
  S.turns = {
2789
2893
  sessionId,
2790
- items
2894
+ items: diff.items
2791
2895
  };
2792
- S.turnsBySeq = bySeq;
2896
+ S.turnsBySeq = diff.bySeq;
2793
2897
  setS({
2794
2898
  turns: S.turns,
2795
- turnsBySeq: bySeq
2899
+ turnsBySeq: diff.bySeq
2796
2900
  });
2797
2901
  diagThrottled("timeline " + items.length + " items " + sessionId.slice(0, 24));
2798
2902
  } else diagThrottled("timeline failed: " + String(result.error ?? "unknown"));
@@ -2985,10 +3089,17 @@ window.__ModuleLoader__.load({
2985
3089
  const script = d.createElement("script");
2986
3090
  script.src = MERMAID_SCRIPT_PATH;
2987
3091
  script.onload = () => resolve();
2988
- script.onerror = () => reject(/* @__PURE__ */ new Error("script load failed"));
3092
+ script.onerror = () => {
3093
+ script.remove();
3094
+ reject(/* @__PURE__ */ new Error("script load failed"));
3095
+ };
2989
3096
  d.head.appendChild(script);
2990
3097
  });
2991
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
+ }
2992
3103
  return true;
2993
3104
  }
2994
3105
  mermaidState = {
@@ -3076,18 +3187,19 @@ window.__ModuleLoader__.load({
3076
3187
  * GUI-owned nodes — React keeps reconciling its tree; the block is only
3077
3188
  * visually swapped with the diagram stage via display. */
3078
3189
  async function renderInPlace(block, code, dark) {
3079
- 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;
3080
3193
  if (!await ensureMermaid()) {
3081
- block.dataset.vxMmdFail = code;
3194
+ block.dataset.vxMmdFail = key;
3082
3195
  return;
3083
3196
  }
3084
3197
  const r = await renderMermaid(code, dark);
3085
3198
  if (!r.ok) {
3086
- block.dataset.vxMmdFail = code;
3199
+ block.dataset.vxMmdFail = key;
3087
3200
  return;
3088
3201
  }
3089
3202
  delete block.dataset.vxMmdFail;
3090
- block.dataset.vxMmd = code;
3091
3203
  const d = typeof document !== "undefined" ? document : null;
3092
3204
  if (d === null) return;
3093
3205
  let wrap = block.previousElementSibling;
@@ -3134,7 +3246,9 @@ window.__ModuleLoader__.load({
3134
3246
  showDiagram();
3135
3247
  }
3136
3248
  const stage = wrap.querySelector(".vx-mmd-stage");
3137
- if (stage !== null) stage.innerHTML = r.svg;
3249
+ if (stage === null) return;
3250
+ stage.innerHTML = r.svg;
3251
+ block.dataset.vxMmd = key;
3138
3252
  }
3139
3253
  /** Scan every chat code block and render the mermaid ones in place. */
3140
3254
  async function scanMermaidBlocks(dark) {
@@ -3150,6 +3264,7 @@ window.__ModuleLoader__.load({
3150
3264
  if (codeRaw === null) continue;
3151
3265
  const code = normalizeMermaidText(codeRaw).trim();
3152
3266
  if (code === "") continue;
3267
+ const key = mermaidCodeKey(code);
3153
3268
  const info = blockInfostring(block);
3154
3269
  if (info !== null && info.trim().toLowerCase() === "mermaid") {
3155
3270
  if (code.split("\n").filter((l) => l.trim() !== "").length < 2) continue;
@@ -3157,7 +3272,7 @@ window.__ModuleLoader__.load({
3157
3272
  if (!isGenericInfostring(info)) continue;
3158
3273
  if (!isMermaidCode(codeRaw)) continue;
3159
3274
  }
3160
- if (block.dataset.vxMmd === code || block.dataset.vxMmdFail === code) continue;
3275
+ if (block.dataset.vxMmd === key || block.dataset.vxMmdFail === key) continue;
3161
3276
  mmdInflight.add(block);
3162
3277
  try {
3163
3278
  await renderInPlace(block, code, dark);
@@ -3783,11 +3898,14 @@ window.__ModuleLoader__.load({
3783
3898
  useViewedSession(props);
3784
3899
  const seq = typeof props.seq === "number" ? props.seq : null;
3785
3900
  const turn = props.turn;
3786
- 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);
3787
3906
  let registered = null;
3788
- const item = seq !== null && s.turns !== null && s.turns.sessionId === S.sessionId ? s.turnsBySeq?.get(seq) ?? null : null;
3789
3907
  const btns = [];
3790
- if (item !== null && s.cfg.formula === true) {
3908
+ if (item !== null && formula) {
3791
3909
  if (item.hasLatex === true) btns.push(react.createElement("button", {
3792
3910
  key: "lx",
3793
3911
  className: "vx-chip",
@@ -3807,7 +3925,7 @@ window.__ModuleLoader__.load({
3807
3925
  size: 11
3808
3926
  }), " MathML"));
3809
3927
  }
3810
- 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", {
3811
3929
  key: "md",
3812
3930
  className: "vx-chip",
3813
3931
  title: "渲染 Mermaid 图表",
@@ -5471,6 +5589,9 @@ window.__ModuleLoader__.load({
5471
5589
  ]);
5472
5590
  react.useEffect(() => {
5473
5591
  syncAntiScroll(s.cfg.antiScroll === true);
5592
+ return () => {
5593
+ syncAntiScroll(false);
5594
+ };
5474
5595
  }, [s.cfg.antiScroll]);
5475
5596
  react.useEffect(() => {
5476
5597
  const w = typeof window !== "undefined" ? window : null;
@@ -5525,12 +5646,32 @@ window.__ModuleLoader__.load({
5525
5646
  const sessions = useSessionsSafe(props);
5526
5647
  const summary = sessions !== null && s.sessionId !== null ? sessions.byId[s.sessionId] : null;
5527
5648
  react.useEffect(() => {
5528
- if (S.sessionId === null) return;
5529
- const running = summary?.running === true;
5530
- const handle = setInterval(() => {
5531
- if (running && S.sessionId !== null) fetchTurns(S.sessionId);
5532
- }, 3e3);
5533
- 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
+ };
5534
5675
  }, [s.sessionId, summary?.running]);
5535
5676
  const children = [react.createElement(FxCanvas, { key: "fx" })];
5536
5677
  children.push(react.createElement(MermaidInPlace, { key: "mmd" }));
@@ -5642,9 +5783,18 @@ window.__ModuleLoader__.load({
5642
5783
  }, HeaderBalance);
5643
5784
  reportDiag(`client installed: ${injectedCount} injection requests / ${injectedKeys.size} slots`);
5644
5785
  return () => {
5786
+ disposed = true;
5645
5787
  for (const unregister of unregisterAll.splice(0)) try {
5646
5788
  unregister();
5647
5789
  } catch {}
5790
+ if (loadRetryTimer !== null) {
5791
+ clearTimeout(loadRetryTimer);
5792
+ loadRetryTimer = null;
5793
+ }
5794
+ if (greetTimer !== null) {
5795
+ clearTimeout(greetTimer);
5796
+ greetTimer = null;
5797
+ }
5648
5798
  if (tokenDisposer !== null) {
5649
5799
  try {
5650
5800
  tokenDisposer();
@@ -5655,6 +5805,12 @@ window.__ModuleLoader__.load({
5655
5805
  clearTimeout(balanceRetryTimer);
5656
5806
  balanceRetryTimer = null;
5657
5807
  }
5808
+ try {
5809
+ syncAntiScroll(false);
5810
+ } catch {}
5811
+ try {
5812
+ restoreMermaidBlocks();
5813
+ } catch {}
5658
5814
  const d = typeof document !== "undefined" ? document : null;
5659
5815
  if (d !== null) {
5660
5816
  for (const cls of [