@michengai/dsh-im-connect 0.1.62 → 0.1.64

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 (46) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/CHANGELOG.zh-CN.md +15 -0
  3. package/README.md +4 -0
  4. package/README.zh-CN.md +4 -0
  5. package/client.js +101 -33
  6. package/lib/client.js +101 -33
  7. package/lib/engine/chat-commands.d.ts.map +1 -1
  8. package/lib/engine/chat-commands.js +54 -3
  9. package/lib/engine/chat-commands.js.map +1 -1
  10. package/lib/engine/command-messages.d.ts +20 -0
  11. package/lib/engine/command-messages.d.ts.map +1 -1
  12. package/lib/engine/command-messages.js +20 -0
  13. package/lib/engine/command-messages.js.map +1 -1
  14. package/lib/engine/gateway.d.ts.map +1 -1
  15. package/lib/engine/gateway.js +26 -12
  16. package/lib/engine/gateway.js.map +1 -1
  17. package/lib/engine/reply-stream.d.ts +7 -5
  18. package/lib/engine/reply-stream.d.ts.map +1 -1
  19. package/lib/engine/reply-stream.js +30 -5
  20. package/lib/engine/reply-stream.js.map +1 -1
  21. package/lib/engine/router.d.ts +12 -1
  22. package/lib/engine/router.d.ts.map +1 -1
  23. package/lib/engine/router.js +60 -5
  24. package/lib/engine/router.js.map +1 -1
  25. package/lib/engine/session-id.d.ts +4 -0
  26. package/lib/engine/session-id.d.ts.map +1 -1
  27. package/lib/engine/session-id.js.map +1 -1
  28. package/lib/engine/session-store.d.ts +2 -0
  29. package/lib/engine/session-store.d.ts.map +1 -1
  30. package/lib/engine/session-store.js +13 -0
  31. package/lib/engine/session-store.js.map +1 -1
  32. package/lib/manager.d.ts +2 -2
  33. package/lib/manager.d.ts.map +1 -1
  34. package/lib/manager.js +11 -5
  35. package/lib/manager.js.map +1 -1
  36. package/locale/en.json +6 -0
  37. package/locale/zh.json +6 -0
  38. package/package.json +4 -2
  39. package/src/engine/chat-commands.ts +45 -3
  40. package/src/engine/command-messages.ts +33 -0
  41. package/src/engine/gateway.ts +23 -12
  42. package/src/engine/reply-stream.ts +24 -5
  43. package/src/engine/router.ts +59 -6
  44. package/src/engine/session-id.ts +4 -0
  45. package/src/engine/session-store.ts +12 -0
  46. package/src/manager.ts +9 -4
package/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@
4
4
 
5
5
  Recent published versions are listed below. Git tags and GitHub Releases now mirror these entries; historical sections retain links to their original release commits.
6
6
 
7
+ ## Unreleased
8
+
9
+ ## 0.1.64 - 2026-10-06
10
+
11
+ - The installed-plugin list shows “IM Connect” and a localized description instead of the package name. Titles and descriptions come from `meta.title` and `meta.description` in `locale/zh.json` and `locale/en.json`.
12
+
13
+ ## 0.1.63 - 2026-10-04
14
+
15
+ - Switching through `/new`, `/clear`, `/session`, `/workspace`, `/preset`, or `/fork` stops previous sessions from pushing output to the same chat. Detached registrations persist across restarts without hiding web history, and session handles remain managed until channel teardown.
16
+ - Added `/unbind [number|ID|all]`, `/mute number-or-ID`, and `/unmute number-or-ID`. Invalid numbers point to `/unbind`; explicitly selecting a session restores its output. Mute pauses assistant text and files while approvals, questions, and task status notices remain available.
17
+ - Reply streams track their owning session. Switching or muting the owner discards stale queued updates; clearing other historical registrations does not interrupt the current reply. Session-event routing no longer sorts the full history on each streamed chunk.
18
+ - Channel panels share polling and group sessions once per refresh, avoiding overlapping polling from multiple panels.
19
+ - Added Feishu message-to-reply end-to-end coverage for session switching, mute/unmute, and restart recovery. CI now includes real Host export contracts alongside session, command, image, file, and authentication contracts.
20
+ - Existing registrations from an older installation are cleared on the next session switch; `/unbind all` can clear old registrations immediately while keeping the current session. Already sent partial cards may remain visible. Restart DSH and refresh the page after upgrading.
21
+
7
22
  ## 0.1.62 - 2026-10-02
8
23
 
9
24
  - Long replies no longer exceed a channel's length limit after the (n/m) marker is added. Tables and code fences still use the full limit and keep their structure; only prose chunks reserve room for the marker.
@@ -4,6 +4,21 @@
4
4
 
5
5
  以下记录近期发布的版本。Git 标签与 GitHub Release 现已和这些条目同步;历史条目继续保留原始发布提交链接。
6
6
 
7
+ ## 未发布
8
+
9
+ ## 0.1.64 - 2026-10-06
10
+
11
+ - 已安装插件列表显示「IM Connect」和中文简介,不再只用包名。显示名来自 `locale/zh.json` 和 `locale/en.json` 的 `meta.title`、`meta.description`。
12
+
13
+ ## 0.1.63 - 2026-10-04
14
+
15
+ - 通过 `/new`、`/clear`、`/session`、`/workspace`、`/preset` 或 `/fork` 切换后,旧会话停止向同一聊天推送输出。解绑状态重启后仍保留,不隐藏网页历史;会话句柄仍由渠道卸载流程统一释放。
16
+ - 新增 `/unbind [序号|ID|all]`、`/mute 序号或ID`、`/unmute 序号或ID`。无效序号正确指向 `/unbind`;显式选择会话会恢复其输出。静音暂停助手正文和文件,审批、提问及任务状态通知仍可送达。
17
+ - 回复流记录实际会话归属。切换或静音该会话会丢弃旧的排队增量;清理其他历史登记不会中断当前回复。流式事件的会话路由不再逐块排序完整历史列表。
18
+ - 多个渠道面板共用轮询,每轮刷新只分组一次会话,避免多个面板产生重叠轮询。
19
+ - 新增飞书消息入口到回复出口的端到端测试,覆盖会话切换、静音恢复和重启恢复。CI 在会话、命令、图片、文件及认证契约之外,补齐真实 Host 导出契约检查。
20
+ - 升级前的旧登记会在该聊天下一次切换时解除;也可立即发送 `/unbind all` 清理旧登记,当前会话保留。已经发送的半截卡片可能仍可见。升级后请重启 DSH 并刷新页面。
21
+
7
22
  ## 0.1.62 - 2026-10-02
8
23
 
9
24
  - 长回复加上序号后不再超出渠道字数上限。表格和代码块仍用完整上限并保持结构,只有纯文字片为序号预留空间。
package/README.md CHANGED
@@ -260,6 +260,10 @@ Open **Settings → IM Assistant**, select **Add account** under the target chan
260
260
 
261
261
  After `/workspace`, `/new` and continuing after archiving the current session keep the selected workspace and use the account model, Agent preset, and permission preset. `/session` and `/fork` preserve the original session configuration.
262
262
 
263
+ Switching sessions stops output pushes from previous sessions to this chat, including switches through `/preset` and `/fork`. History remains available on the web, and the stopped delivery stays stopped after restarting DSH. `/unbind` lists this chat's registered sessions; `/unbind <number or ID>` removes an old registration, and `/unbind all` keeps only the current session. `/mute <number or ID>` pauses assistant output without removing the registration; `/unmute` with the same target resumes future output. Use the numbers from `/unbind`.
264
+
265
+ Explicitly binding a session with `/session` restores its output, including when selecting the current session again. Mute pauses assistant text and file output; approvals, questions, and task status notices still arrive. Switching or muting discards queued stream updates and cached text; an already sent partial card may remain visible, but the next output starts a fresh stream.
266
+
263
267
  DingTalk replies prefer official AI Card streaming. If card creation fails, plain text preserves line breaks; code fences and list markers remain literal. QQ replies use official markdown and keep headings, bold text, links, and tables; only a platform rejection falls back to plain text (where tables become lists). Telegram replies are sent as Rich Messages with Markdown so headings, bold text, and tables render, falling back to plain text when that method is unavailable; do not enable Webhook on the same bot. Feishu normal replies also use card Markdown, so headings and tables render; cards are split so none holds more than five tables, with a plain-text fallback. Long replies split with structure awareness: table chunks repeat the header, code fences are re-closed, and the `(n/m)` marker only prefixes prose chunks. `/help` is grouped as getting around / sessions and workspaces / models and reasoning / tasks and delivery, with one entry per feature and the usable aliases marked; group titles are bold while the rest of the command copy stays plain text, which keeps them scannable on a phone. Discord renders headings, bold text, code, and lists on the client but has no Markdown tables, and mobile clients cannot scroll horizontally, so pipe tables become a vertical block per row (first two columns as a bold title, remaining columns as `header: value`). Everything else is sent verbatim. Do not configure a Discord Interactions Endpoint URL, or button clicks will not arrive through the Gateway.
264
268
 
265
269
  Send commands as separate text messages; image captions remain ordinary input. Start with `/help`; individual replies also suggest related actions.
package/README.zh-CN.md CHANGED
@@ -260,6 +260,10 @@ dsh --profile web --dump-config
260
260
 
261
261
  通过 `/workspace` 新建后,`/new` 和当前会话归档后的续聊会保留所选工作区,并使用账号配置的模型、Agent 与权限预设。`/session` 接续已有会话、`/fork` 分叉则保留原会话配置。
262
262
 
263
+ 切换会话后,旧会话不再向本聊天推送输出,`/preset`、`/fork` 切换也遵循此规则。网页历史仍保留,重启 DSH 后也不会恢复旧推送。`/unbind` 查看本聊天登记的会话;`/unbind 序号或ID` 解除旧登记,`/unbind all` 仅保留当前会话。`/mute 序号或ID` 保留登记但暂停助手输出,`/unmute` 使用同一目标恢复后续输出。序号以 `/unbind` 列表为准。
264
+
265
+ 通过 `/session` 显式绑定会话会恢复输出,重新选择当前会话也会解除静音。静音暂停助手正文和文件输出,审批、提问和任务状态通知仍会送达。切换或静音会丢弃排队中的流式更新和缓存文本;已经发送的半截卡片可能仍可见,但后续输出会开启新流。
266
+
263
267
  钉钉回复优先走官方 AI Card 流式卡片;创建失败则回退纯文本,保留换行;代码与列表标记按原文显示。QQ 回复走官方 markdown,保留标题、加粗、链接和表格;只有平台拒绝 markdown 时才退回纯文本(那时表格降级成列表)。Telegram 回复用 Rich Message 发送 Markdown,标题、加粗和表格可渲染;该方法不可用时自动回退纯文本,同一 Bot 不要同时开 Webhook。飞书普通回复也用卡片 Markdown,标题和表格会被渲染;按表格数量拆卡,单卡最多 5 个表格,卡片被拒时回退纯文本。长回复分片会保护结构:表格分片重复表头,代码块补齐围栏,序号只加在纯文字片。`/help` 按「入口 / 会话与工作区 / 模型与推理 / 任务与交付」分组,每个功能只列一条入口,并标出可直接使用的别名;分组标题会加粗,其余命令文案保持纯文本,便于在手机上扫读。Discord 客户端会自己渲染标题、加粗、代码和列表,但不支持 Markdown 表格,手机端又无法横向滚动,所以正文里的表格会逐行竖排成「粗体标题 + 表头:值」,其余正文原样发送;不要配置 Interactions Endpoint URL,否则按钮不会从 Gateway 进来。
264
268
 
265
269
  命令单独发送为文字,图片说明按普通消息处理。首次使用可发 `/help`,各命令回复也会给出相关操作。
package/client.js CHANGED
@@ -598,11 +598,87 @@ window.__ModuleLoader__.load({
598
598
  if (request.body === undefined) request.body = "{}";
599
599
  }
600
600
  return fetch(API_BASE + path, request).then((r) => r.json()).then((data) => {
601
- if (data.ok && Array.isArray(data.groups)) updateChannelMembership(data.groups);
601
+ if (!request.signal?.aborted && data.ok && Array.isArray(data.groups)) updateChannelMembership(data.groups);
602
602
  return data;
603
603
  });
604
604
  };
605
605
 
606
+ // One request and timer for all channel consumers. Schedule only after settlement.
607
+ function createChannelRefreshStore(load) {
608
+ const listeners = new Set();
609
+ let flight = null, timer = null, latest = null, failures = 0, epoch = 0;
610
+ const visible = () => typeof document === "undefined" || document.visibilityState !== "hidden";
611
+ const clearTimer = () => { if (timer !== null) clearTimeout(timer); timer = null; };
612
+ const notify = (data, error) => { for (const listener of listeners) listener(data, error); };
613
+ const schedule = () => {
614
+ clearTimer();
615
+ if (listeners.size && visible()) timer = setTimeout(() => {
616
+ timer = null;
617
+ refresh().catch(() => undefined);
618
+ }, Math.min(4000 * 2 ** failures, 60000));
619
+ };
620
+ function refresh() {
621
+ if (flight) return flight.promise;
622
+ clearTimer();
623
+ const current = { controller: new AbortController(), promise: null };
624
+ flight = current;
625
+ current.promise = Promise.resolve().then(() => {
626
+ current.controller.signal.throwIfAborted();
627
+ return load(current.controller.signal);
628
+ }).then(data => {
629
+ if (flight !== current || current.controller.signal.aborted) return data;
630
+ failures = data.ok ? 0 : failures + 1;
631
+ latest = { data, error: null };
632
+ notify(data, null);
633
+ return data;
634
+ }).catch(error => {
635
+ if (flight === current && !current.controller.signal.aborted) {
636
+ failures++;
637
+ latest = { data: null, error };
638
+ notify(null, error);
639
+ }
640
+ throw error;
641
+ }).finally(() => {
642
+ if (flight !== current) return;
643
+ flight = null;
644
+ schedule();
645
+ });
646
+ return current.promise;
647
+ }
648
+ // A mutation must fetch again after any pre-mutation request has settled.
649
+ function invalidate() {
650
+ const generation = epoch;
651
+ return (flight ? flight.promise.catch(() => undefined) : Promise.resolve()).then(() => {
652
+ if (generation === epoch) return refresh();
653
+ });
654
+ }
655
+ const onVisibility = () => {
656
+ clearTimer();
657
+ if (visible() && listeners.size) refresh().catch(() => undefined);
658
+ };
659
+ function subscribe(listener) {
660
+ listeners.add(listener);
661
+ if (latest) listener(latest.data, latest.error);
662
+ if (listeners.size === 1) {
663
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisibility);
664
+ if (visible()) refresh().catch(() => undefined);
665
+ }
666
+ return () => {
667
+ listeners.delete(listener);
668
+ if (listeners.size) return;
669
+ epoch++;
670
+ clearTimer();
671
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisibility);
672
+ if (flight) flight.controller.abort();
673
+ flight = null;
674
+ latest = null;
675
+ failures = 0;
676
+ };
677
+ }
678
+ return { subscribe, refresh, invalidate };
679
+ }
680
+ const channelRefresh = createChannelRefreshStore(signal => api("/channels", { signal }));
681
+
606
682
  const storedAccountSelection = () => {
607
683
  try { return window.localStorage.getItem(ACCOUNT_SELECTION_KEY) || ""; }
608
684
  catch { return ""; }
@@ -1559,7 +1635,6 @@ window.__ModuleLoader__.load({
1559
1635
  const [channelSettingsRequest, setChannelSettingsRequest] = useState(() => typeof window !== "undefined" ? readChannelSettingsRequest(window.sessionStorage) : undefined);
1560
1636
  const [catalog, setCatalog] = useState({ providers: [], permissions: [], assistant: null, cwd: "", permission: "" });
1561
1637
  const workspaces = props.useWorkspaces ? (props.useWorkspaces((state) => state && state.items || []) || []) : [];
1562
- const refreshSeq = useRef(0);
1563
1638
  const selectAccount = useCallback((id) => {
1564
1639
  const next = id || "";
1565
1640
  setSelected(next);
@@ -1567,31 +1642,30 @@ window.__ModuleLoader__.load({
1567
1642
  }, []);
1568
1643
 
1569
1644
  const refresh = useCallback(() => {
1570
- const seq = ++refreshSeq.current;
1571
- api("/channels").then((data) => {
1572
- if (seq !== refreshSeq.current) return;
1573
- if (data.ok) {
1574
- setChannels(data.channels);
1575
- setPending(data.pending || []);
1576
- setError("");
1577
- const all = (data.channels || []).flatMap((channel) => channel.accounts || []);
1578
- setSelected((current) => {
1579
- const next = all.some((item) => item.id === current) ? current : "";
1580
- if (next !== current) rememberAccountSelection(next);
1581
- return next;
1582
- });
1583
- } else setError(serverText(data.error, t) || t("error.load"));
1584
- }).catch(() => { if (seq === refreshSeq.current) setError(t("error.connection")); });
1645
+ return channelRefresh.invalidate().catch(() => undefined);
1585
1646
  }, []);
1586
1647
 
1648
+ useEffect(() => channelRefresh.subscribe((data, error) => {
1649
+ if (error) { setError(t("error.connection")); return; }
1650
+ if (data.ok) {
1651
+ setChannels(data.channels);
1652
+ setPending(data.pending || []);
1653
+ setError("");
1654
+ const all = (data.channels || []).flatMap((channel) => channel.accounts || []);
1655
+ setSelected((current) => {
1656
+ const next = all.some((item) => item.id === current) ? current : "";
1657
+ if (next !== current) rememberAccountSelection(next);
1658
+ return next;
1659
+ });
1660
+ } else setError(serverText(data.error, t) || t("error.load"));
1661
+ }), []);
1662
+
1587
1663
  useEffect(() => {
1588
1664
  ensureStyle();
1589
- refresh();
1590
1665
  api("/assistant").then((data) => {
1591
1666
  if (data.ok) setCatalog({ providers: data.providers || [], permissions: data.permissions || [], agentPresets: data.agentPresets || [], agentPreset: data.agentPreset || "standard", assistant: data.assistant || null, cwd: data.cwd || "", permission: data.permission || "" });
1592
1667
  }).catch(() => undefined);
1593
1668
  }, [refresh]);
1594
- useEffect(() => { const timer = setInterval(refresh, 4000); return () => clearInterval(timer); }, [refresh]);
1595
1669
  useEffect(() => {
1596
1670
  if (!settingsAccount) return undefined;
1597
1671
  const onKey = (event) => {
@@ -2331,13 +2405,11 @@ window.__ModuleLoader__.load({
2331
2405
  const canArchiveGroup = canArchiveChannelGroup(archiveManagerInstalled, props.archiveSession);
2332
2406
  useEffect(() => {
2333
2407
  ensureStyle();
2334
- const load = () => api("/channels").then((data) => {
2408
+ return channelRefresh.subscribe((data, error) => {
2409
+ if (error) { setError(t("error.connection")); return; }
2335
2410
  if (data.ok) { setGroups(data.groups || []); setError(""); }
2336
2411
  else setError(serverText(data.error, t) || t("error.load"));
2337
- }).catch(() => setError(t("error.connection")));
2338
- load();
2339
- const timer = setInterval(load, 4000);
2340
- return () => clearInterval(timer);
2412
+ });
2341
2413
  }, []);
2342
2414
  useEffect(() => {
2343
2415
  if (typeof document === "undefined" || typeof MutationObserver === "undefined") return undefined;
@@ -2368,7 +2440,7 @@ window.__ModuleLoader__.load({
2368
2440
  setArchiveGroupBusy(true);
2369
2441
  setArchiveGroupError(undefined);
2370
2442
  archiveChannelGroup(target.sessionIds, props.archiveSession)
2371
- .then(() => api("/channels").then((data) => { if (data.ok) setGroups(data.groups || []); }).catch(() => undefined))
2443
+ .then(() => channelRefresh.invalidate().catch(() => undefined))
2372
2444
  .then(() => { setArchiveGroupTarget(undefined); })
2373
2445
  .catch((caught) => {
2374
2446
  if (openStopArchive(caught, { id: target.id, title: target.name, sessionIds: target.sessionIds, group: true }, (next) => {
@@ -2386,7 +2458,7 @@ window.__ModuleLoader__.load({
2386
2458
  setStopArchiveBusy(true);
2387
2459
  setStopArchiveError(undefined);
2388
2460
  const work = finishStopArchive(target, props.archiveSession).then((kind) => {
2389
- if (kind === "group") return api("/channels").then((data) => { if (data.ok) setGroups(data.groups || []); }).catch(() => undefined);
2461
+ if (kind === "group") return channelRefresh.invalidate().catch(() => undefined);
2390
2462
  if (kind !== "session") return;
2391
2463
  return api("/sessions/remove", {
2392
2464
  method: "POST",
@@ -2890,13 +2962,9 @@ window.__ModuleLoader__.load({
2890
2962
  function apply(ctx) {
2891
2963
  ensureStyle();
2892
2964
  ctx.effect(() => {
2893
- let active = true;
2894
- const refresh = () => fetch(API_BASE + "/channels", { credentials: "same-origin", cache: "no-store" })
2895
- .then(response => response.json()).then(data => { if (active && data.ok && Array.isArray(data.groups)) updateChannelMembership(data.groups); })
2896
- .catch(error => { if (active) console.warn("[dsh-im-connect] 无法刷新渠道会话归属", error); });
2897
- refresh();
2898
- const timer = setInterval(refresh, 4000);
2899
- return () => { active = false; clearInterval(timer); };
2965
+ return channelRefresh.subscribe((data, error) => {
2966
+ if (error) console.warn("[dsh-im-connect] 无法刷新渠道会话归属", error);
2967
+ });
2900
2968
  }, "im-connect: channel membership");
2901
2969
  ctx.effect(() => ctx.locale.register(IM_LOCALE_NS, IM_LOCALES), "im-connect: dictionaries");
2902
2970
  const t = ctx.locale.bind(IM_LOCALE_NS);
package/lib/client.js CHANGED
@@ -1108,11 +1108,87 @@ react-is/cjs/react-is.production.js:
1108
1108
  if (request.body === undefined) request.body = "{}";
1109
1109
  }
1110
1110
  return fetch(API_BASE + path, request).then((r) => r.json()).then((data) => {
1111
- if (data.ok && Array.isArray(data.groups)) updateChannelMembership(data.groups);
1111
+ if (!request.signal?.aborted && data.ok && Array.isArray(data.groups)) updateChannelMembership(data.groups);
1112
1112
  return data;
1113
1113
  });
1114
1114
  };
1115
1115
 
1116
+ // One request and timer for all channel consumers. Schedule only after settlement.
1117
+ function createChannelRefreshStore(load) {
1118
+ const listeners = new Set();
1119
+ let flight = null, timer = null, latest = null, failures = 0, epoch = 0;
1120
+ const visible = () => typeof document === "undefined" || document.visibilityState !== "hidden";
1121
+ const clearTimer = () => { if (timer !== null) clearTimeout(timer); timer = null; };
1122
+ const notify = (data, error) => { for (const listener of listeners) listener(data, error); };
1123
+ const schedule = () => {
1124
+ clearTimer();
1125
+ if (listeners.size && visible()) timer = setTimeout(() => {
1126
+ timer = null;
1127
+ refresh().catch(() => undefined);
1128
+ }, Math.min(4000 * 2 ** failures, 60000));
1129
+ };
1130
+ function refresh() {
1131
+ if (flight) return flight.promise;
1132
+ clearTimer();
1133
+ const current = { controller: new AbortController(), promise: null };
1134
+ flight = current;
1135
+ current.promise = Promise.resolve().then(() => {
1136
+ current.controller.signal.throwIfAborted();
1137
+ return load(current.controller.signal);
1138
+ }).then(data => {
1139
+ if (flight !== current || current.controller.signal.aborted) return data;
1140
+ failures = data.ok ? 0 : failures + 1;
1141
+ latest = { data, error: null };
1142
+ notify(data, null);
1143
+ return data;
1144
+ }).catch(error => {
1145
+ if (flight === current && !current.controller.signal.aborted) {
1146
+ failures++;
1147
+ latest = { data: null, error };
1148
+ notify(null, error);
1149
+ }
1150
+ throw error;
1151
+ }).finally(() => {
1152
+ if (flight !== current) return;
1153
+ flight = null;
1154
+ schedule();
1155
+ });
1156
+ return current.promise;
1157
+ }
1158
+ // A mutation must fetch again after any pre-mutation request has settled.
1159
+ function invalidate() {
1160
+ const generation = epoch;
1161
+ return (flight ? flight.promise.catch(() => undefined) : Promise.resolve()).then(() => {
1162
+ if (generation === epoch) return refresh();
1163
+ });
1164
+ }
1165
+ const onVisibility = () => {
1166
+ clearTimer();
1167
+ if (visible() && listeners.size) refresh().catch(() => undefined);
1168
+ };
1169
+ function subscribe(listener) {
1170
+ listeners.add(listener);
1171
+ if (latest) listener(latest.data, latest.error);
1172
+ if (listeners.size === 1) {
1173
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisibility);
1174
+ if (visible()) refresh().catch(() => undefined);
1175
+ }
1176
+ return () => {
1177
+ listeners.delete(listener);
1178
+ if (listeners.size) return;
1179
+ epoch++;
1180
+ clearTimer();
1181
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisibility);
1182
+ if (flight) flight.controller.abort();
1183
+ flight = null;
1184
+ latest = null;
1185
+ failures = 0;
1186
+ };
1187
+ }
1188
+ return { subscribe, refresh, invalidate };
1189
+ }
1190
+ const channelRefresh = createChannelRefreshStore(signal => api("/channels", { signal }));
1191
+
1116
1192
  const storedAccountSelection = () => {
1117
1193
  try { return window.localStorage.getItem(ACCOUNT_SELECTION_KEY) || ""; }
1118
1194
  catch { return ""; }
@@ -2069,7 +2145,6 @@ react-is/cjs/react-is.production.js:
2069
2145
  const [channelSettingsRequest, setChannelSettingsRequest] = useState(() => typeof window !== "undefined" ? readChannelSettingsRequest(window.sessionStorage) : undefined);
2070
2146
  const [catalog, setCatalog] = useState({ providers: [], permissions: [], assistant: null, cwd: "", permission: "" });
2071
2147
  const workspaces = props.useWorkspaces ? (props.useWorkspaces((state) => state && state.items || []) || []) : [];
2072
- const refreshSeq = useRef(0);
2073
2148
  const selectAccount = useCallback((id) => {
2074
2149
  const next = id || "";
2075
2150
  setSelected(next);
@@ -2077,31 +2152,30 @@ react-is/cjs/react-is.production.js:
2077
2152
  }, []);
2078
2153
 
2079
2154
  const refresh = useCallback(() => {
2080
- const seq = ++refreshSeq.current;
2081
- api("/channels").then((data) => {
2082
- if (seq !== refreshSeq.current) return;
2083
- if (data.ok) {
2084
- setChannels(data.channels);
2085
- setPending(data.pending || []);
2086
- setError("");
2087
- const all = (data.channels || []).flatMap((channel) => channel.accounts || []);
2088
- setSelected((current) => {
2089
- const next = all.some((item) => item.id === current) ? current : "";
2090
- if (next !== current) rememberAccountSelection(next);
2091
- return next;
2092
- });
2093
- } else setError(serverText(data.error, t) || t("error.load"));
2094
- }).catch(() => { if (seq === refreshSeq.current) setError(t("error.connection")); });
2155
+ return channelRefresh.invalidate().catch(() => undefined);
2095
2156
  }, []);
2096
2157
 
2158
+ useEffect(() => channelRefresh.subscribe((data, error) => {
2159
+ if (error) { setError(t("error.connection")); return; }
2160
+ if (data.ok) {
2161
+ setChannels(data.channels);
2162
+ setPending(data.pending || []);
2163
+ setError("");
2164
+ const all = (data.channels || []).flatMap((channel) => channel.accounts || []);
2165
+ setSelected((current) => {
2166
+ const next = all.some((item) => item.id === current) ? current : "";
2167
+ if (next !== current) rememberAccountSelection(next);
2168
+ return next;
2169
+ });
2170
+ } else setError(serverText(data.error, t) || t("error.load"));
2171
+ }), []);
2172
+
2097
2173
  useEffect(() => {
2098
2174
  ensureStyle();
2099
- refresh();
2100
2175
  api("/assistant").then((data) => {
2101
2176
  if (data.ok) setCatalog({ providers: data.providers || [], permissions: data.permissions || [], agentPresets: data.agentPresets || [], agentPreset: data.agentPreset || "standard", assistant: data.assistant || null, cwd: data.cwd || "", permission: data.permission || "" });
2102
2177
  }).catch(() => undefined);
2103
2178
  }, [refresh]);
2104
- useEffect(() => { const timer = setInterval(refresh, 4000); return () => clearInterval(timer); }, [refresh]);
2105
2179
  useEffect(() => {
2106
2180
  if (!settingsAccount) return undefined;
2107
2181
  const onKey = (event) => {
@@ -2841,13 +2915,11 @@ react-is/cjs/react-is.production.js:
2841
2915
  const canArchiveGroup = canArchiveChannelGroup(archiveManagerInstalled, props.archiveSession);
2842
2916
  useEffect(() => {
2843
2917
  ensureStyle();
2844
- const load = () => api("/channels").then((data) => {
2918
+ return channelRefresh.subscribe((data, error) => {
2919
+ if (error) { setError(t("error.connection")); return; }
2845
2920
  if (data.ok) { setGroups(data.groups || []); setError(""); }
2846
2921
  else setError(serverText(data.error, t) || t("error.load"));
2847
- }).catch(() => setError(t("error.connection")));
2848
- load();
2849
- const timer = setInterval(load, 4000);
2850
- return () => clearInterval(timer);
2922
+ });
2851
2923
  }, []);
2852
2924
  useEffect(() => {
2853
2925
  if (typeof document === "undefined" || typeof MutationObserver === "undefined") return undefined;
@@ -2878,7 +2950,7 @@ react-is/cjs/react-is.production.js:
2878
2950
  setArchiveGroupBusy(true);
2879
2951
  setArchiveGroupError(undefined);
2880
2952
  archiveChannelGroup(target.sessionIds, props.archiveSession)
2881
- .then(() => api("/channels").then((data) => { if (data.ok) setGroups(data.groups || []); }).catch(() => undefined))
2953
+ .then(() => channelRefresh.invalidate().catch(() => undefined))
2882
2954
  .then(() => { setArchiveGroupTarget(undefined); })
2883
2955
  .catch((caught) => {
2884
2956
  if (openStopArchive(caught, { id: target.id, title: target.name, sessionIds: target.sessionIds, group: true }, (next) => {
@@ -2896,7 +2968,7 @@ react-is/cjs/react-is.production.js:
2896
2968
  setStopArchiveBusy(true);
2897
2969
  setStopArchiveError(undefined);
2898
2970
  const work = finishStopArchive(target, props.archiveSession).then((kind) => {
2899
- if (kind === "group") return api("/channels").then((data) => { if (data.ok) setGroups(data.groups || []); }).catch(() => undefined);
2971
+ if (kind === "group") return channelRefresh.invalidate().catch(() => undefined);
2900
2972
  if (kind !== "session") return;
2901
2973
  return api("/sessions/remove", {
2902
2974
  method: "POST",
@@ -3400,13 +3472,9 @@ react-is/cjs/react-is.production.js:
3400
3472
  function apply(ctx) {
3401
3473
  ensureStyle();
3402
3474
  ctx.effect(() => {
3403
- let active = true;
3404
- const refresh = () => fetch(API_BASE + "/channels", { credentials: "same-origin", cache: "no-store" })
3405
- .then(response => response.json()).then(data => { if (active && data.ok && Array.isArray(data.groups)) updateChannelMembership(data.groups); })
3406
- .catch(error => { if (active) console.warn("[dsh-im-connect] 无法刷新渠道会话归属", error); });
3407
- refresh();
3408
- const timer = setInterval(refresh, 4000);
3409
- return () => { active = false; clearInterval(timer); };
3475
+ return channelRefresh.subscribe((data, error) => {
3476
+ if (error) console.warn("[dsh-im-connect] 无法刷新渠道会话归属", error);
3477
+ });
3410
3478
  }, "im-connect: channel membership");
3411
3479
  ctx.effect(() => ctx.locale.register(IM_LOCALE_NS, IM_LOCALES), "im-connect: dictionaries");
3412
3480
  const t = ctx.locale.bind(IM_LOCALE_NS);
@@ -1 +1 @@
1
- {"version":3,"file":"chat-commands.d.ts","sourceRoot":"","sources":["../../src/engine/chat-commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAM1C,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAG3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAahD,MAAM,WAAW,WAAW;IAAG,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE;AAC3D,eAAO,MAAM,eAAe,cA4BhB,CAAA;AAEZ,qBAAa,YAAY;IAIX,OAAO,CAAC,QAAQ,CAAC,IAAI;IAAe,OAAO,CAAC,QAAQ,CAAC,MAAM;IACrE,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC;IAN/B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAuC;IAChE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwD;IAChF,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA0H;gBAC9H,IAAI,EAAE,WAAW,EAAmB,MAAM,EAAE,aAAa,EACnE,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,EACvC,SAAS,GAAE,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,KAAK,IAAgB,EAClE,WAAW,CAAC,GAAE,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,OAAO,KAAK,OAAO,CAAC,MAAM,CAAC,aAAA;IAEvK,KAAK,IAAI,IAAI;IAEb,OAAO,CAAC,OAAO;YAMD,IAAI;YASJ,OAAO;IAKrB,OAAO,CAAC,eAAe;YAWT,KAAK;YAML,QAAQ;YAMR,UAAU;YAMV,YAAY;IAK1B,OAAO,CAAC,QAAQ;IAKhB,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,OAAO;YAQD,IAAI;IAOlB,OAAO,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC;IAmCtF,gCAAgC;YAClB,QAAQ;YAYR,UAAU;YAiBV,GAAG;CA8ZlB"}
1
+ {"version":3,"file":"chat-commands.d.ts","sourceRoot":"","sources":["../../src/engine/chat-commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAM1C,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAG3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAahD,MAAM,WAAW,WAAW;IAAG,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE;AAC3D,eAAO,MAAM,eAAe,cA8BhB,CAAA;AAEZ,qBAAa,YAAY;IAIX,OAAO,CAAC,QAAQ,CAAC,IAAI;IAAe,OAAO,CAAC,QAAQ,CAAC,MAAM;IACrE,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC;IAN/B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAuC;IAChE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAwD;IAChF,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA0H;gBAC9H,IAAI,EAAE,WAAW,EAAmB,MAAM,EAAE,aAAa,EACnE,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,EACvC,SAAS,GAAE,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,KAAK,IAAgB,EAClE,WAAW,CAAC,GAAE,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,OAAO,KAAK,OAAO,CAAC,MAAM,CAAC,aAAA;IAEvK,KAAK,IAAI,IAAI;IAEb,OAAO,CAAC,OAAO;YAMD,IAAI;YASJ,OAAO;IAKrB,OAAO,CAAC,eAAe;YAWT,KAAK;YAML,QAAQ;YAMR,UAAU;YAMV,YAAY;IAK1B,OAAO,CAAC,QAAQ;IAKhB,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,OAAO;YAWD,IAAI;IAOlB,OAAO,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC;IAmCtF,gCAAgC;YAClB,QAAQ;YAYR,UAAU;YAiBV,GAAG;CAmclB"}
@@ -32,6 +32,8 @@ export const chatControlHelp = () => [
32
32
  replyText('/steer 补充要求 — 提交补充指令'),
33
33
  replyText('/queue — 查看队列和操作方法'),
34
34
  replyText('/delivery — 查看交付记录和补发方法'),
35
+ replyText('/unbind [序号|ID|all] — 解除本聊天对旧会话的登记,不再推送其输出'),
36
+ replyText('/mute 序号或ID — 静音指定会话的推送;/unmute 恢复'),
35
37
  replyText('/export — 导出当前会话 ZIP 并发送'), '',
36
38
  replyText('命令单独发送为文字;图片说明按普通消息处理。'),
37
39
  ].join('\n');
@@ -123,8 +125,11 @@ export class ChatCommands {
123
125
  return value;
124
126
  const choice = this.choices.get(key);
125
127
  const selected = choice && Date.now() - choice.time < 15 * 60_000 ? choice.values[Number(value) - 1] : undefined;
126
- if (!selected)
128
+ if (!selected) {
129
+ if (key.endsWith(':unbind'))
130
+ throw new Error(replyText('序号无效或已过期,本次操作未执行。请发送 /unbind 获取新列表。'));
127
131
  throw new Error(replyText('序号无效或已过期,尚未切换。请发送 /{0} 获取新列表。', key.endsWith(':reasoning') ? 'reasoning' : key.endsWith(':presets') ? 'presets' : key.endsWith(':models') ? 'models' : key.endsWith(':workspaces') ? 'workspaces' : 'sessions'));
132
+ }
128
133
  return selected;
129
134
  }
130
135
  async idle(sessionId, signal, command) {
@@ -219,7 +224,7 @@ export class ChatCommands {
219
224
  const input = match[2].trim();
220
225
  const kind = msg.kind === 'group' ? 'group' : 'dm';
221
226
  const scope = JSON.stringify([channel.id, kind, msg.chatId, msg.userId ?? '']);
222
- if (msg.media?.length && ['preset', 'presets', 'presetlist', 'help', 'new', 'clear', 'sessions', 'sessionlist', 'session', 'workspaces', 'workspacelist', 'workspace', 'models', 'status', 'current', 'stop', 'steer', 'rename', 'fork', 'model', 'reasoning', 'reasonings', 'reasoninglist', 'history', 'queue', 'export'].includes(command))
227
+ if (msg.media?.length && ['preset', 'presets', 'presetlist', 'help', 'new', 'clear', 'sessions', 'sessionlist', 'session', 'unbind', 'mute', 'unmute', 'workspaces', 'workspacelist', 'workspace', 'models', 'status', 'current', 'stop', 'steer', 'rename', 'fork', 'model', 'reasoning', 'reasonings', 'reasoninglist', 'history', 'queue', 'export'].includes(command))
223
228
  throw new Error(replyText('该控制命令不接受附件,请单独发送。'));
224
229
  const current = this.router.lookup(channel.id, kind, msg.chatId);
225
230
  const requireCurrent = () => { if (!current)
@@ -349,7 +354,8 @@ export class ChatCommands {
349
354
  if (current && this.host.get('sessionController'))
350
355
  await this.idle(current.sessionId, signal, command);
351
356
  const next = await this.router.rotate(channel.id, kind, msg.chatId, msg.username || msg.chatId, { signal });
352
- return [replyText('已开启新会话'), await this.newDetails(next, signal), replyText('旧会话已保留,直接发送消息即可开始。')].filter(Boolean).join('\n') + related(replyText('查看旧会话:/sessions'), replyText('查看当前配置:/status'));
357
+ return [replyText('已开启新会话'), await this.newDetails(next, signal), replyText('旧会话已保留,直接发送消息即可开始。')].filter(Boolean).join('\n')
358
+ + related(replyText('查看旧会话:/sessions'), replyText('查看当前配置:/status'));
353
359
  }
354
360
  if (command === 'sessions' || command === 'sessionlist') {
355
361
  const page = input ? Number(input) : 1;
@@ -396,6 +402,51 @@ export class ChatCommands {
396
402
  await this.router.bind(channel.id, kind, msg.chatId, id, row.projections?.values?.title || id, await this.agent(id), row.cwd || workspace.items.find((item) => item.sessionIds?.includes(id))?.path);
397
403
  return replyText('已切换会话:{0}\n工作区:{1}\n接下来的消息会发送到此会话。', oneLine(row.projections?.values?.title || id), row.cwd || workspace.items.find((item) => item.sessionIds?.includes(id))?.path || replyText('暂时无法读取')) + related(replyText('最近记录:/history'), replyText('重新开始:/new'));
398
404
  }
405
+ if (command === 'unbind' || command === 'mute' || command === 'unmute') {
406
+ if (command !== 'unbind' && !input)
407
+ throw new Error(replyText('用法:/{0} 序号或ID。先发送 /unbind 查看本聊天登记的会话。', command));
408
+ const records = this.router.chatRecords(channel.id, kind, msg.chatId);
409
+ if (command === 'unbind' && !input) {
410
+ this.remember(scope + ':unbind', records.map((item) => item.sessionId));
411
+ if (!records.length)
412
+ return replyText('本聊天没有登记任何会话。');
413
+ return replyText('本聊天登记的会话 · 共 {0} 个\n\n', records.length)
414
+ + records.map((item, i) => `${i + 1}. ${oneLine(item.title || '未命名会话')}${item.sessionId === current?.sessionId ? replyText('〔当前〕') : ''}${item.muted ? replyText('〔已静音〕') : ''}\n${item.sessionId}`).join('\n\n')
415
+ + related(replyText('解除登记:/unbind 序号或ID;全部解除(当前会话除外):/unbind all'), replyText('保留登记但暂停推送:/mute 序号或ID;恢复:/unmute 序号或ID'));
416
+ }
417
+ if (!records.length)
418
+ throw new Error(replyText('本聊天没有登记任何会话。'));
419
+ const target = input.toLowerCase() === 'all' ? 'all' : this.resolve(scope + ':unbind', input);
420
+ const label = (id) => {
421
+ const title = records.find(item => item.sessionId === id)?.title;
422
+ return title && title !== id ? `${oneLine(title)} (${oneLine(id)})` : oneLine(id);
423
+ };
424
+ if (command === 'unbind') {
425
+ if (target === 'all') {
426
+ let removed = 0;
427
+ for (const item of records) {
428
+ if (item.sessionId === current?.sessionId)
429
+ continue;
430
+ if (this.router.unbindSession(channel.id, kind, msg.chatId, item.sessionId))
431
+ removed += 1;
432
+ }
433
+ return replyText(removed ? '已解除 {0} 个会话的登记,它们不再向本聊天推送输出。' : '没有需要解除的登记。', removed) + related(current ? replyText('当前会话未受影响。') : '');
434
+ }
435
+ if (target === current?.sessionId)
436
+ throw new Error(replyText('不能解除当前会话;请先 /new 或 /session 切换。'));
437
+ if (!this.router.unbindSession(channel.id, kind, msg.chatId, target))
438
+ throw new Error(replyText('本聊天没有登记该会话,请发送 /unbind 查看。'));
439
+ return replyText('已解除登记:{0}\n该会话不再向本聊天推送输出;历史仍保留在网页 Chat 中。', label(target)) + related(replyText('查看登记:/unbind'));
440
+ }
441
+ const sessionId = this.resolve(scope + ':unbind', input);
442
+ if (!records.some((item) => item.sessionId === sessionId))
443
+ throw new Error(replyText('本聊天没有登记该会话,请发送 /unbind 查看。'));
444
+ if (!this.router.setMuted(sessionId, command === 'mute'))
445
+ throw new Error(replyText('会话登记异常,请发送 /unbind 查看。'));
446
+ return command === 'mute'
447
+ ? replyText('已静音:{0}\n该会话的输出不再推送到本聊天;/unmute {1} 恢复。', label(sessionId), input)
448
+ : replyText('已恢复推送:{0}', label(sessionId)) + related(replyText('静音:/mute {0}', input));
449
+ }
399
450
  if (command === 'workspaces' || command === 'workspacelist' || command === 'workspace') {
400
451
  const { items } = await this.workspaces(signal);
401
452
  if (command !== 'workspace' || !input) {