@cubeai/dsh-weixin-channel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +18 -0
  3. package/README.md +64 -2
  4. package/client.js +3112 -0
  5. package/cordis.patch.yml +4 -0
  6. package/docs/dsh-weixin-channel.md +473 -0
  7. package/icon.svg +15 -0
  8. package/locale/en.json +6 -0
  9. package/locale/zh.json +6 -0
  10. package/package.json +76 -4
  11. package/src/channels/connection-state.js +12 -0
  12. package/src/channels/diagnostics.js +77 -0
  13. package/src/channels/factory.js +22 -0
  14. package/src/channels/file-send.js +34 -0
  15. package/src/channels/media.js +9 -0
  16. package/src/channels/meta.js +24 -0
  17. package/src/channels/qr/hub.js +229 -0
  18. package/src/channels/qr/render.js +8 -0
  19. package/src/channels/qr/shared.js +50 -0
  20. package/src/channels/qr/weixin.js +76 -0
  21. package/src/channels/weixin.js +965 -0
  22. package/src/engine/abort.js +35 -0
  23. package/src/engine/access.js +23 -0
  24. package/src/engine/agent-options.js +19 -0
  25. package/src/engine/approval.js +70 -0
  26. package/src/engine/assistant-settings.js +38 -0
  27. package/src/engine/assistant-text.js +11 -0
  28. package/src/engine/atomic-file.js +45 -0
  29. package/src/engine/chat-commands.js +752 -0
  30. package/src/engine/choice-delivery.js +20 -0
  31. package/src/engine/choices.js +103 -0
  32. package/src/engine/command-locale.js +70 -0
  33. package/src/engine/command-messages.js +434 -0
  34. package/src/engine/command-permissions.js +38 -0
  35. package/src/engine/command-replies.js +59 -0
  36. package/src/engine/credentials.js +54 -0
  37. package/src/engine/deferred-delivery.js +260 -0
  38. package/src/engine/delivery-history.js +39 -0
  39. package/src/engine/file-delivery.js +215 -0
  40. package/src/engine/file-input.js +52 -0
  41. package/src/engine/file-log.js +25 -0
  42. package/src/engine/gateway.js +1337 -0
  43. package/src/engine/image-input.js +31 -0
  44. package/src/engine/json-state.js +25 -0
  45. package/src/engine/keyed-queue.js +20 -0
  46. package/src/engine/merge.js +56 -0
  47. package/src/engine/message-progress.js +274 -0
  48. package/src/engine/question.js +201 -0
  49. package/src/engine/quiet-logger.js +25 -0
  50. package/src/engine/reply-stream.js +86 -0
  51. package/src/engine/router.js +759 -0
  52. package/src/engine/secure-file.js +8 -0
  53. package/src/engine/seen-store.js +43 -0
  54. package/src/engine/session-export.js +64 -0
  55. package/src/engine/session-history.js +30 -0
  56. package/src/engine/session-id.js +62 -0
  57. package/src/engine/session-store.js +109 -0
  58. package/src/engine/session-title.js +29 -0
  59. package/src/engine/split.js +291 -0
  60. package/src/engine/workspace-path.js +9 -0
  61. package/src/index.js +62 -0
  62. package/src/manager.js +1297 -0
package/client.js ADDED
@@ -0,0 +1,3112 @@
1
+ /**
2
+ * dsh-weixin-channel 浏览器端:微信频道设置页 + 工作区频道槽。
3
+ */
4
+ window.__ModuleLoader__.load({
5
+ id: "@cubeai/dsh-weixin-channel",
6
+ factory: (require) => {
7
+ var module = { exports: {} };
8
+ var exports = module.exports;
9
+ const React = require("react");
10
+ const { useState, useEffect, useLayoutEffect, useCallback, useMemo, useRef, useSyncExternalStore } = React;
11
+ let ReactDOM = {};
12
+ try { ReactDOM = require("react-dom"); } catch { /* react-dom is optional; SVG markup degrades gracefully */ }
13
+ const primitives = typeof require === "function" ? (function () { try { return require("@deepseek-ai/dsh-client-ui-primitives"); } catch { return {}; } })() : {};
14
+ const PrimitiveButton = primitives.Button;
15
+ const HostMenu = primitives.Menu || function FallbackMenu(props) {
16
+ const items = Array.isArray(props.items) ? props.items : [];
17
+ const footer = Array.isArray(props.footer) ? props.footer : [];
18
+ const option = (item) => React.createElement("button", {
19
+ key: String(item.value),
20
+ type: "button",
21
+ role: "option",
22
+ disabled: item.disabled,
23
+ "aria-selected": props.selectedId !== undefined && String(item.value) === String(props.selectedId),
24
+ style: {
25
+ display: "block",
26
+ width: "100%",
27
+ padding: "6px 8px",
28
+ border: 0,
29
+ borderRadius: 6,
30
+ background: props.selectedId !== undefined && String(item.value) === String(props.selectedId) ? "var(--dsw-alias-interactive-bg-hover, rgba(0,0,0,.06))" : "transparent",
31
+ color: "var(--dsw-alias-label-primary, inherit)",
32
+ textAlign: "left",
33
+ cursor: item.disabled ? "not-allowed" : "pointer",
34
+ opacity: item.disabled ? 0.5 : 1,
35
+ },
36
+ onClick: () => {
37
+ if (item.disabled) return;
38
+ props.onSelect?.(item.value);
39
+ props.onClose?.();
40
+ },
41
+ }, item.label);
42
+ return React.createElement("div", { className: "dwc-fallback-menu-wrap", style: { position: "relative", display: "inline-flex", width: "100%" } },
43
+ props.anchor,
44
+ props.open && React.createElement("div", {
45
+ className: ["dwc-form-menu", props.listClassName].filter(Boolean).join(" "),
46
+ role: "listbox",
47
+ style: {
48
+ position: "absolute",
49
+ zIndex: 1200,
50
+ top: "calc(100% + 4px)",
51
+ left: 0,
52
+ minWidth: "100%",
53
+ maxHeight: 280,
54
+ overflow: "auto",
55
+ background: "var(--dsw-alias-bg-layer-2, #fff)",
56
+ border: "1px solid var(--dsw-alias-border-l1, rgba(0,0,0,.12))",
57
+ borderRadius: 8,
58
+ padding: 4,
59
+ boxShadow: "0 8px 24px rgba(0,0,0,.16)",
60
+ },
61
+ }, items.map(option), footer.map(option)));
62
+ };
63
+ const HostModal = primitives.Modal;
64
+ const HostSegmentedTabs = primitives.SegmentedTabs || function FallbackSegmentedTabs(props) {
65
+ return React.createElement("div", {
66
+ className: [props.className, "dwc-tabs"].filter(Boolean).join(" "),
67
+ role: "tablist",
68
+ "aria-label": props.label,
69
+ }, (props.items || []).map((item) => React.createElement("button", {
70
+ key: item.value,
71
+ type: "button",
72
+ role: "tab",
73
+ "aria-selected": item.value === props.value,
74
+ className: item.value === props.value ? "dwc-tab on" : "dwc-tab",
75
+ onClick: () => props.onChange(item.value),
76
+ }, item.label)));
77
+ };
78
+ // 宿主 Button 由 forwardRef 包成对象,typeof 是 object,不是 function。
79
+ function isHostComponent(component) {
80
+ return typeof component === "function" || (!!component && typeof component === "object" && typeof component.render === "function");
81
+ }
82
+ // 只关最上层。下层监听先注册,不是顶层就放行,避免一次 Escape 关掉弹窗和宿主设置。
83
+ const modalLayers = [];
84
+ // 0.1.7 把尺寸从图标名里拿掉了(IconEditOutlineRegular)。旧宿主仍导出 *16/*20。
85
+ function pickHostIcon(...names) {
86
+ for (const name of names) {
87
+ const icon = primitives[name];
88
+ if (typeof icon === "function") return icon;
89
+ }
90
+ return function MissingHostIcon() { return null; };
91
+ }
92
+ const IconFolderClose = pickHostIcon("IconFolderCloseRegular", "IconFolderClose16", "IconFolderClose");
93
+ const IconClockOutline = pickHostIcon("IconClockOutlineRegular", "IconClockOutline16");
94
+ const IconQueueOutline = pickHostIcon("IconQueueOutlineRegular");
95
+ const IconCheckOutline = pickHostIcon("IconCheckOutlineRegular");
96
+ const IconCheckCircleOutline = pickHostIcon("IconCheckCircleOutlineRegular");
97
+ const IconCloseCircleFill = pickHostIcon("IconCloseCircleFillRegular");
98
+ const IconInfoOutline = pickHostIcon("IconInfoOutlineRegular");
99
+ const IconWarningOutline = pickHostIcon("IconWarningOutlineRegular");
100
+ const IconCloseFill = pickHostIcon("IconCloseFillRegular");
101
+ const IconChevronDownOutline = pickHostIcon("IconChevronDownOutlineRegular");
102
+ const IconChevronRightOutline = pickHostIcon("IconChevronRightOutlineRegular");
103
+ const IconPlusOutline = pickHostIcon("IconPlusOutlineRegular");
104
+ const IconEditOutline = pickHostIcon("IconEditOutlineRegular");
105
+ const IconRefreshOutline = pickHostIcon("IconRefreshOutlineRegular");
106
+ const IconDownloadOutline = pickHostIcon("IconDownloadOutlineRegular");
107
+ const IconCopyOutline = pickHostIcon("IconCopyOutlineRegular");
108
+ const IconLoadingOutline = pickHostIcon("IconLoadingOutlineRegular");
109
+ const IconStopFill = pickHostIcon("IconStopFillRegular", "IconStopFill16", "IconStopFill");
110
+ function alertIcon(type) {
111
+ if (type === "success") return h(IconCheckCircleOutline, { size: 14 });
112
+ if (type === "warning") return h(IconWarningOutline, { size: 14 });
113
+ if (type === "error") return h(IconCloseCircleFill, { size: 14 });
114
+ return h(IconInfoOutline, { size: 14 });
115
+ }
116
+ function NoticeBar({ type = "info", icon, children, className, role, showIcon }) {
117
+ const iconNode = icon !== undefined ? icon : (showIcon !== false ? alertIcon(type) : null);
118
+ return React.createElement("div", {
119
+ role: role || (type === "error" ? "alert" : undefined),
120
+ className: ["dwc-feedback", "dwc-feedback-" + type, className].filter(Boolean).join(" "),
121
+ },
122
+ iconNode && React.createElement("span", { className: "dwc-feedback-icon" }, iconNode),
123
+ React.createElement("div", { className: "dwc-feedback-body" }, children)
124
+ );
125
+ }
126
+ function Tag({ color, children, icon, className, bordered, ...props }) {
127
+ const colorCls = color ? "dwc-tag-" + color : "";
128
+ return React.createElement("span", {
129
+ ...props,
130
+ className: ["dwc-tag", colorCls, className].filter(Boolean).join(" "),
131
+ }, icon && React.createElement("span", { className: "dwc-tag-icon", style: { display: "inline-flex", alignItems: "center", marginRight: children ? 4 : 0 } }, icon), children);
132
+ }
133
+ function Input(props) {
134
+ const { className, type = "text", ...rest } = props;
135
+ return React.createElement("input", {
136
+ type,
137
+ ...rest,
138
+ className: ["dwc-input", className].filter(Boolean).join(" "),
139
+ });
140
+ }
141
+ function TextArea(props) {
142
+ const { autoSize, className, rows, ...rest } = props;
143
+ return React.createElement("textarea", {
144
+ ...rest,
145
+ className: ["dwc-input dwc-textarea", className].filter(Boolean).join(" "),
146
+ rows: autoSize?.minRows || rows || 4,
147
+ });
148
+ }
149
+ Input.TextArea = TextArea;
150
+ function Checkbox({ checked, onChange, children, className, disabled, ...props }) {
151
+ return React.createElement("label", {
152
+ className: ["dwc-checkbox-label", disabled ? "is-disabled" : "", className].filter(Boolean).join(" "),
153
+ },
154
+ React.createElement("input", {
155
+ type: "checkbox",
156
+ checked: Boolean(checked),
157
+ disabled,
158
+ onChange,
159
+ className: "dwc-checkbox",
160
+ ...props,
161
+ }),
162
+ children ? React.createElement("span", { className: "dwc-checkbox-text" }, children) : null
163
+ );
164
+ }
165
+ function hostModalButton(label, onClick, kind, extra) {
166
+ const options = extra || {};
167
+ const isDanger = kind === "danger" || options.danger;
168
+ const variant = isDanger ? "outline" : (kind === "primary" ? "primary" : "outline");
169
+ const dangerClass = isDanger ? "dwc-btn-danger" : "";
170
+ const className = [options.className, dangerClass].filter(Boolean).join(" ") || undefined;
171
+ if (isHostComponent(PrimitiveButton)) {
172
+ return React.createElement(PrimitiveButton, {
173
+ variant,
174
+ disabled: options.disabled,
175
+ className,
176
+ onClick,
177
+ type: "button",
178
+ }, label);
179
+ }
180
+ return React.createElement(Button, {
181
+ variant,
182
+ disabled: options.disabled,
183
+ className,
184
+ onClick,
185
+ }, label);
186
+ }
187
+ function Modal(props) {
188
+ const { open, title, onCancel, onOk, okText, cancelText, okButtonProps, confirmLoading, width = 640, zIndex = 1100, children, footer, className, contentClassName, keyboard, maskClosable, closeLabel, description } = props;
189
+ const requestClose = onCancel || props.onClose;
190
+ const closeRef = useRef(requestClose);
191
+ closeRef.current = requestClose;
192
+ const layerRef = useRef(null);
193
+ if (!layerRef.current) layerRef.current = { owner: props.layerOwner || "modal" };
194
+ useEffect(() => {
195
+ if (!open) return undefined;
196
+ const layer = layerRef.current;
197
+ modalLayers.push(layer);
198
+ const onKey = (event) => {
199
+ if (event.key !== "Escape") return;
200
+ if (modalLayers[modalLayers.length - 1] !== layer) return;
201
+ event.preventDefault();
202
+ event.stopPropagation();
203
+ if (typeof event.stopImmediatePropagation === "function") event.stopImmediatePropagation();
204
+ if (keyboard === false) return;
205
+ if (closeRef.current) closeRef.current();
206
+ };
207
+ window.addEventListener("keydown", onKey, true);
208
+ return () => {
209
+ window.removeEventListener("keydown", onKey, true);
210
+ const index = modalLayers.lastIndexOf(layer);
211
+ if (index >= 0) modalLayers.splice(index, 1);
212
+ };
213
+ }, [open, keyboard]);
214
+ if (!open) return null;
215
+ const handleClose = () => { if (closeRef.current) closeRef.current(); };
216
+ const handleOk = () => { if (onOk) onOk(); };
217
+ const actionRow = footer === null ? null : (footer || React.createElement(React.Fragment, null,
218
+ hostModalButton(cancelText || "取消", handleClose, "outline"),
219
+ hostModalButton(okText || "确定", handleOk, okButtonProps?.danger ? "danger" : "primary", { disabled: okButtonProps?.disabled || confirmLoading, danger: okButtonProps?.danger })
220
+ ));
221
+ const footerNode = Array.isArray(actionRow)
222
+ ? React.createElement(React.Fragment, null, actionRow)
223
+ : actionRow;
224
+ const hostDescription = typeof description === "string" && description !== "" ? { description } : {};
225
+ if (typeof HostModal === "function") {
226
+ return h(HostModal, {
227
+ open: true,
228
+ title,
229
+ onClose: handleClose,
230
+ closeLabel: closeLabel || "Close",
231
+ className,
232
+ // 宿主 Modal 把内容区裁在视口内;标记 content 区,让它在超长时滚动。
233
+ contentClassName: ["dwc-modal-content", contentClassName].filter(Boolean).join(" "),
234
+ footer: footerNode,
235
+ ...hostDescription,
236
+ }, children);
237
+ }
238
+ const allowMask = maskClosable !== false && modalLayers[modalLayers.length - 1] === layerRef.current;
239
+ return React.createElement("div", { className: "dwc-modal-root", style: { zIndex } },
240
+ React.createElement("div", { className: "dwc-modal-mask", onClick: allowMask ? handleClose : undefined }),
241
+ React.createElement("div", { className: ["dwc-modal-wrap", className].filter(Boolean).join(" ") },
242
+ React.createElement("div", { className: "dwc-modal-panel", style: { width } },
243
+ React.createElement("div", { className: "dwc-modal-header" },
244
+ React.createElement("div", { className: "dwc-modal-title" }, title),
245
+ React.createElement("button", { type: "button", className: "dwc-modal-close", "aria-label": closeLabel || "Close", onClick: handleClose },
246
+ h(IconCloseFill, { size: 14 })
247
+ )
248
+ ),
249
+ React.createElement("div", { className: "dwc-modal-body" },
250
+ description ? React.createElement("p", { className: "dwc-confirm-content" }, description) : null,
251
+ children),
252
+ footerNode && React.createElement("div", { className: "dwc-modal-footer-wrap" }, footerNode)
253
+ )
254
+ )
255
+ );
256
+ }
257
+ function useModal() {
258
+ const [config, setConfig] = React.useState(null);
259
+ const confirm = (opts) => { setConfig(opts); };
260
+ const holder = config ? React.createElement(Modal, {
261
+ open: true,
262
+ title: config.title,
263
+ width: 480,
264
+ description: config.description,
265
+ onCancel: () => { setConfig(null); },
266
+ onOk: () => {
267
+ const p = config.onOk?.();
268
+ if (p && typeof p.then === "function") {
269
+ p.then(() => setConfig(null));
270
+ } else {
271
+ setConfig(null);
272
+ }
273
+ },
274
+ okText: config.okText,
275
+ cancelText: config.cancelText,
276
+ okButtonProps: config.okButtonProps,
277
+ }, config.content ? React.createElement("p", { className: "dwc-confirm-content" }, config.content) : null) : null;
278
+ return [{ confirm }, holder];
279
+ }
280
+ Modal.useModal = useModal;
281
+ function Switch(props) {
282
+ const on = Boolean(props.checked);
283
+ return React.createElement("button", {
284
+ type: "button",
285
+ role: "switch",
286
+ "aria-checked": on,
287
+ "aria-label": props["aria-label"],
288
+ title: props.title,
289
+ disabled: props.disabled,
290
+ className: "dwc-enable-switch" + (props.className ? " " + props.className : ""),
291
+ onClick: function (event) {
292
+ if (event && typeof event.stopPropagation === "function") event.stopPropagation();
293
+ if (!props.disabled && props.onChange) props.onChange(!on);
294
+ },
295
+ }, React.createElement("span", { className: "dwc-enable-switch-thumb", "aria-hidden": "true" }));
296
+ }
297
+ function Select(props) {
298
+ const [open, setOpen] = useState(false);
299
+ const rootRef = useRef(null);
300
+
301
+ useEffect(() => {
302
+ if (!open) return undefined;
303
+ const updateWidth = () => {
304
+ const width = rootRef.current?.getBoundingClientRect().width ?? 0;
305
+ if (width > 0) document.documentElement.style.setProperty("--dwc-menu-width", `${Math.round(width)}px`);
306
+ };
307
+ updateWidth();
308
+ window.addEventListener("resize", updateWidth);
309
+ return () => {
310
+ window.removeEventListener("resize", updateWidth);
311
+ document.documentElement.style.removeProperty("--dwc-menu-width");
312
+ };
313
+ }, [open]);
314
+
315
+ useEffect(() => {
316
+ if (!open || typeof window === "undefined") return undefined;
317
+ const layer = { owner: "select" };
318
+ modalLayers.push(layer);
319
+ function onKey(event) {
320
+ if (event.key !== "Escape") return;
321
+ if (modalLayers[modalLayers.length - 1] !== layer) return;
322
+ event.preventDefault();
323
+ event.stopPropagation();
324
+ event.stopImmediatePropagation();
325
+ setOpen(false);
326
+ }
327
+ window.addEventListener("keydown", onKey, true);
328
+ return () => {
329
+ window.removeEventListener("keydown", onKey, true);
330
+ const index = modalLayers.lastIndexOf(layer);
331
+ if (index >= 0) modalLayers.splice(index, 1);
332
+ };
333
+ }, [open]);
334
+
335
+ const items = React.useMemo(() => {
336
+ const list = [];
337
+ (props.options || []).forEach((opt, idx) => {
338
+ if (Array.isArray(opt.options)) {
339
+ list.push({ type: "label", id: "group-" + idx, text: opt.label || "" });
340
+ opt.options.forEach((sub) => {
341
+ list.push({ id: String(sub.value), label: sub.label, disabled: sub.disabled, danger: sub.danger });
342
+ });
343
+ } else {
344
+ list.push({ id: String(opt.value), label: opt.label, disabled: opt.disabled, danger: opt.danger });
345
+ }
346
+ });
347
+ return list;
348
+ }, [props.options]);
349
+
350
+ const footer = React.useMemo(() => {
351
+ if (!Array.isArray(props.footer) || props.footer.length === 0) return undefined;
352
+ return props.footer.map((item) => ({
353
+ id: String(item.value),
354
+ label: item.label,
355
+ disabled: item.disabled,
356
+ danger: item.danger,
357
+ }));
358
+ }, [props.footer]);
359
+
360
+ const selectedOption = React.useMemo(() => {
361
+ for (const opt of props.options || []) {
362
+ if (Array.isArray(opt.options)) {
363
+ const found = opt.options.find((sub) => String(sub.value) === String(props.value));
364
+ if (found) return found;
365
+ } else if (String(opt.value) === String(props.value)) {
366
+ return opt;
367
+ }
368
+ }
369
+ return null;
370
+ }, [props.options, props.value]);
371
+
372
+ const currentText = selectedOption ? selectedOption.label : (props.placeholder || props["aria-label"] || "");
373
+
374
+ return React.createElement("div", {
375
+ ref: rootRef,
376
+ className: "dwc-menu-select-wrap " + (props.className || ""),
377
+ style: props.style,
378
+ },
379
+ React.createElement(HostMenu, {
380
+ open: open,
381
+ listClassName: ["dwc-form-menu", props.listClassName].filter(Boolean).join(" "),
382
+ onClose: () => setOpen(false),
383
+ onSelect: (id) => {
384
+ if (props.footer && props.footer.some((item) => String(item.value) === id)) {
385
+ if (typeof props.onFooter === "function") props.onFooter(id);
386
+ setOpen(false);
387
+ return;
388
+ }
389
+ if (props.onChange) props.onChange(id);
390
+ setOpen(false);
391
+ },
392
+ selectedId: props.value != null ? String(props.value) : undefined,
393
+ align: "start",
394
+ portal: true,
395
+ dense: true,
396
+ anchor: React.createElement(Button, {
397
+ variant: "outline",
398
+ size: "sm",
399
+ role: "combobox",
400
+ "aria-label": props["aria-label"] || props.placeholder,
401
+ "aria-expanded": open,
402
+ disabled: props.disabled,
403
+ className: "dwc-menu-select-trigger" + (open ? " is-open" : ""),
404
+ onClick: () => { if (!props.disabled) setOpen((prev) => !prev); },
405
+ },
406
+ React.createElement("span", { className: "dwc-menu-select-label" }, currentText),
407
+ h(IconChevronDownOutline, {
408
+ size: 12,
409
+ className: "dwc-menu-select-arrow",
410
+ style: { marginLeft: 4, transition: "transform 150ms ease", transform: open ? "rotate(180deg)" : "none" },
411
+ })
412
+ ),
413
+ items: items,
414
+ ...(footer ? { footer } : {}),
415
+ })
416
+ );
417
+ }
418
+ function createSpinner() {
419
+ return h(IconLoadingOutline, {
420
+ size: 14,
421
+ className: "dwc-btn-spinner",
422
+ style: { marginRight: 6, display: "inline-block", verticalAlign: "-2px", animation: "dwc-spin 0.8s linear infinite" },
423
+ });
424
+ }
425
+ function Button({ variant, type, danger, loading, block, size, shape, className, children, href, target, rel, icon, ...props }) {
426
+ let mappedVariant = variant ?? "outline";
427
+ if (type === "primary") mappedVariant = "primary";
428
+ else if (type === "text" || type === "link") mappedVariant = "ghost";
429
+
430
+ const isPrimary = mappedVariant === "primary";
431
+ const mappedSize = (size === "small" || size === "sm") ? "sm" : "md";
432
+
433
+ const classes = [
434
+ "dwc-btn",
435
+ href ? "dwc-link-btn" : "",
436
+ className,
437
+ isPrimary ? "is-primary" : "",
438
+ danger ? "is-danger dwc-btn-danger" : "",
439
+ (danger && isPrimary) ? "dwc-btn-danger-primary" : "",
440
+ block ? "is-block" : "",
441
+ loading ? "is-loading" : "",
442
+ ].filter(Boolean).join(" ");
443
+
444
+ const iconElement = loading
445
+ ? createSpinner()
446
+ : (icon ? React.createElement("span", {
447
+ key: "icon",
448
+ className: "dwc-btn-icon",
449
+ style: { display: "inline-flex", alignItems: "center" },
450
+ }, icon) : null);
451
+ const content = [iconElement, children];
452
+
453
+ if (href) {
454
+ return React.createElement("a", Object.assign({}, props, {
455
+ href,
456
+ target,
457
+ rel: rel || (target === "_blank" ? "noreferrer" : undefined),
458
+ className: classes || undefined,
459
+ "aria-label": props["aria-label"],
460
+ style: props.style,
461
+ }), content);
462
+ }
463
+
464
+ if (isHostComponent(PrimitiveButton)) {
465
+ return React.createElement(PrimitiveButton, Object.assign({}, props, {
466
+ variant: mappedVariant,
467
+ size: mappedSize,
468
+ className: [className, danger ? "dwc-btn-danger" : ""].filter(Boolean).join(" ") || undefined,
469
+ disabled: props.disabled || loading,
470
+ icon: loading ? undefined : icon,
471
+ }), loading ? createSpinner() : children);
472
+ }
473
+
474
+ return React.createElement("button", Object.assign({}, props, {
475
+ type: "button",
476
+ className: classes || undefined,
477
+ disabled: props.disabled || loading,
478
+ }), content);
479
+ }
480
+
481
+ const IconSettingsOutline16 = pickHostIcon("IconSettingsOutlineRegular", "IconSettingsOutline16");
482
+ const CHANNEL_SETTINGS_EVENT = "dsh-weixin-channel:open-channel-settings";
483
+ const CHANNEL_SETTINGS_STORAGE_KEY = "dsh-weixin-channel:pending-channel-settings";
484
+ const SETTINGS_CODEX_TRIGGER_SELECTOR = "[data-dcu-settings-trigger]";
485
+ const SETTINGS_CODEX_PAGE_SELECTOR = "[data-dcu-settings-page]";
486
+ const SETTINGS_OPEN_SECTION_EVENT = "dcu-settings-open-section";
487
+ function parseChannelSettingsRequest(value) {
488
+ if (!value || typeof value !== "object") return undefined;
489
+ const channelId = typeof value.channelId === "string" ? value.channelId.trim() : "";
490
+ if (!channelId) return undefined;
491
+ return { channelId, name: typeof value.name === "string" ? value.name : "" };
492
+ }
493
+ function writeChannelSettingsRequest(storage, request) {
494
+ try { storage && storage.setItem(CHANNEL_SETTINGS_STORAGE_KEY, JSON.stringify(request)); } catch { /* ignore */ }
495
+ }
496
+ function requestChannelSettings(request) {
497
+ if (typeof window === "undefined") return;
498
+ writeChannelSettingsRequest(window.sessionStorage, request);
499
+ window.dispatchEvent(new CustomEvent(CHANNEL_SETTINGS_EVENT, { detail: request }));
500
+ }
501
+ function readChannelSettingsRequest(storage) {
502
+ if (!storage) return undefined;
503
+ try {
504
+ const raw = storage.getItem(CHANNEL_SETTINGS_STORAGE_KEY);
505
+ return raw == null ? undefined : parseChannelSettingsRequest(JSON.parse(raw));
506
+ } catch { return undefined; }
507
+ }
508
+ function clearChannelSettingsRequest(storage) {
509
+ try { storage && storage.removeItem(CHANNEL_SETTINGS_STORAGE_KEY); } catch { /* ignore */ }
510
+ }
511
+ function resolveChannelSettingsTarget(request, channels) {
512
+ const parsed = parseChannelSettingsRequest(request);
513
+ if (!parsed || !Array.isArray(channels)) return undefined;
514
+ const channel = channels.find((item) => item && item.id === parsed.channelId);
515
+ if (!channel) return undefined;
516
+ const accounts = channel.accounts || [];
517
+ return { channelId: channel.id, accountId: accounts.length === 1 ? accounts[0].id : undefined };
518
+ }
519
+ function pickSettingsSectionButton(buttons, labels) {
520
+ const normalize = (value) => String(value || "").replace(/\s+/g, "").trim().toLowerCase();
521
+ const labelOf = (button) => normalize(button.textContent) || normalize(button.getAttribute && button.getAttribute("aria-label"));
522
+ const targets = labels.map(normalize).filter(Boolean);
523
+ for (const target of targets) {
524
+ const match = buttons.find((button) => labelOf(button) === target);
525
+ if (match) return match;
526
+ }
527
+ // 宿主可能在标签旁加计数或徽标;退一步做包含匹配。
528
+ for (const target of targets) {
529
+ const match = buttons.find((button) => {
530
+ const text = labelOf(button);
531
+ return text !== "" && (text.includes(target) || target.includes(text));
532
+ });
533
+ if (match) return match;
534
+ }
535
+ return undefined;
536
+ }
537
+ function pickSettingsLauncher(buttons) {
538
+ const named = buttons.find((button) => {
539
+ const label = `${button.textContent || ""} ${typeof button.getAttribute === "function" ? button.getAttribute("aria-label") || "" : ""}`.trim();
540
+ return /(^|\s)(设置|settings)(\s|$)/i.test(label);
541
+ });
542
+ return named || (buttons.length === 1 ? buttons[0] : undefined);
543
+ }
544
+ function findAccountMenuTrigger() {
545
+ const exact = [
546
+ 'button[aria-label="账号菜单"]',
547
+ 'button[aria-label="Account menu"]',
548
+ ];
549
+ for (const selector of exact) {
550
+ const found = document.querySelector(selector);
551
+ if (found) return found;
552
+ }
553
+ return [...document.querySelectorAll('button[aria-haspopup="menu"]')].find((button) => {
554
+ const label = `${typeof button.getAttribute === "function" ? button.getAttribute("aria-label") || "" : ""} ${button.textContent || ""}`.trim();
555
+ return /账号|account/i.test(label);
556
+ });
557
+ }
558
+ function requestCodexSettingsSection(labels) {
559
+ const trigger = typeof document !== "undefined" && document.querySelector(SETTINGS_CODEX_TRIGGER_SELECTOR);
560
+ if (!trigger) return false;
561
+ const request = new CustomEvent(SETTINGS_OPEN_SECTION_EVENT, { detail: { labels: [...labels] }, cancelable: true });
562
+ return !trigger.dispatchEvent(request);
563
+ }
564
+ function openImSettingsPage(t) {
565
+ openSettingsSection(
566
+ [t("settings.label"), DWC_LOCALES.en["settings.label"], DWC_LOCALES.zh["settings.label"]],
567
+ () => {},
568
+ () => console.warn("[dsh-weixin-channel] 无法打开 IM 助理设置页"),
569
+ );
570
+ }
571
+ function openSettingsSection(labels, onSelected, onMissing) {
572
+ if (typeof document === "undefined" || typeof window === "undefined") {
573
+ if (onMissing) onMissing();
574
+ return;
575
+ }
576
+ if (requestCodexSettingsSection(labels)) {
577
+ if (onSelected) onSelected();
578
+ return;
579
+ }
580
+ const launchers = [...document.querySelectorAll('button[aria-haspopup="dialog"], button[aria-label*="设置"], button[aria-label*="Settings"], [data-dcu-settings-trigger]')];
581
+ const namedSettingsButton = [...document.querySelectorAll("button")].find((button) => /^(设置|settings)$/i.test((button.getAttribute("aria-label") || "").trim()));
582
+ const launcher = namedSettingsButton || pickSettingsLauncher(launchers);
583
+ const pageTrigger = document.querySelector(SETTINGS_CODEX_TRIGGER_SELECTOR);
584
+ const dialogOpen = document.querySelector('[role="dialog"]') !== null;
585
+ const pageOpen = document.querySelector(SETTINGS_CODEX_PAGE_SELECTOR) !== null;
586
+ let menuTrigger;
587
+ if (!dialogOpen && !pageOpen && !launcher && !pageTrigger) {
588
+ menuTrigger = findAccountMenuTrigger();
589
+ if (!menuTrigger) {
590
+ if (onMissing) onMissing();
591
+ return;
592
+ }
593
+ menuTrigger.click();
594
+ } else if (!dialogOpen && !pageOpen) {
595
+ (pageTrigger || launcher).click();
596
+ }
597
+ let frame;
598
+ let finished = false;
599
+ let menuActivated = false;
600
+ let timeout;
601
+ const observer = new MutationObserver(() => { schedule(); });
602
+ const cleanup = () => {
603
+ if (finished) return;
604
+ finished = true;
605
+ observer.disconnect();
606
+ window.clearTimeout(timeout);
607
+ if (frame !== undefined) window.cancelAnimationFrame(frame);
608
+ };
609
+ const wait = () => {
610
+ timeout = window.setTimeout(() => {
611
+ if (select()) return;
612
+ cleanup();
613
+ if (onMissing) onMissing();
614
+ }, 5000);
615
+ };
616
+ const select = () => {
617
+ if (menuTrigger !== undefined && !menuActivated) {
618
+ const items = [...document.querySelectorAll('[role="menuitem"], [role="menu"] button')];
619
+ const entry = pickSettingsSectionButton(items, ["设置", "Settings"]);
620
+ if (!entry) return false;
621
+ menuActivated = true;
622
+ window.clearTimeout(timeout);
623
+ wait();
624
+ entry.click();
625
+ schedule();
626
+ return true;
627
+ }
628
+ const buttons = [
629
+ ...document.querySelectorAll('[role="dialog"] nav button, [role="dialog"] button'),
630
+ ...document.querySelectorAll(SETTINGS_CODEX_PAGE_SELECTOR + " nav button"),
631
+ ...document.querySelectorAll("nav button, button"),
632
+ ];
633
+ const target = pickSettingsSectionButton(buttons, labels);
634
+ if (!target) return false;
635
+ cleanup();
636
+ target.click();
637
+ if (onSelected) onSelected();
638
+ return true;
639
+ };
640
+ const schedule = () => {
641
+ if (finished || frame !== undefined) return;
642
+ frame = window.requestAnimationFrame(() => { frame = undefined; select(); });
643
+ };
644
+ wait();
645
+ observer.observe(document.body, { childList: true, subtree: true });
646
+ schedule();
647
+ }
648
+ const EMPTY_EXTRA_TABS = [];
649
+ const inject = ["slots", "sessions", "workspaces", "locale", "uiWorkspace", "layout"];
650
+ const API_BASE = "/api/dsh-weixin-channel";
651
+ const TAB_KEY = "dsh-weixin-channel.sidebar-tab";
652
+ const ACCOUNT_SELECTION_KEY = "dsh-weixin-channel.settings.selected-account";
653
+ const DWC_LOCALE_NS = "weixin-channel";
654
+ const DWC_LOCALES = {
655
+ zh: {
656
+ "account.autoNameNote": "该名称仅用于本机显示。",
657
+ "account.channelName": "频道名称",
658
+ "account.currentWorkspace": "当前工作区",
659
+ "account.defaultName": "{channel}频道 {count}",
660
+ "account.noSessions": "还没有会话。用微信给机器人发一条消息后,会话会出现在这里。",
661
+ "account.presetNote": "更改后使用新会话,旧会话保留。",
662
+ "account.presetUnavailable": "预设不可用",
663
+ "account.privateAccess": "私聊准入",
664
+ "account.privateAll": "允许所有私聊用户",
665
+ "account.privateApproved": "仅已批准用户",
666
+ "account.remark": "频道名称",
667
+ "account.removeConfirm": "确定删除这个微信频道?本机保存的配置、登录凭据和会话映射将一并删除,删除后可以重新添加频道。",
668
+ "account.rename": "修改频道名称",
669
+ "account.selectModel": "请选择模型",
670
+ "account.selectPermission": "请选择权限",
671
+ "account.selectWorkspace": "请选择工作区",
672
+ "account.sendMode": "发送方式",
673
+ "account.sendQueue": "排队发送",
674
+ "account.sendSteer": "插话发送",
675
+ "account.sendSteerNote": "插话发送会把消息作为补充指令立即交给运行中的任务;任务空闲时与排队发送相同。",
676
+ "account.statusNotConnected": "未连接",
677
+ "account.workspace": "工作区",
678
+ "action.addAccount": "添加微信频道",
679
+ "action.approve": "批准",
680
+ "action.cancel": "取消",
681
+ "action.checkConnection": "诊断连接",
682
+ "action.collapse": "收起",
683
+ "action.confirm": "确认",
684
+ "action.deny": "拒绝",
685
+ "action.expand": "展开",
686
+ "action.generateQr": "生成二维码",
687
+ "action.reconnectAccount": "重新连接",
688
+ "action.removeAccount": "删除频道",
689
+ "action.saving": "保存中…",
690
+ "action.settings": "设置",
691
+ "app.copied": "已复制",
692
+ "app.copy": "复制",
693
+ "app.info": "微信绑定信息",
694
+ "app.loggedIn": "已登录",
695
+ "app.login": "登录状态",
696
+ "app.notLoggedIn": "未登录",
697
+ "app.notSaved": "未保存",
698
+ "app.wechatId": "微信用户 ID",
699
+ "bind.expire": "二维码 {time} 后过期",
700
+ "bind.generating": "正在生成…",
701
+ "bind.manual": "手动配置",
702
+ "bind.newIdentity": "检测到新的微信身份",
703
+ "bind.qrAlt": "{channel} 登录二维码",
704
+ "bind.quick": "快捷绑定(推荐)",
705
+ "bind.refresh": "重新生成二维码",
706
+ "bind.retry": "请重新生成二维码",
707
+ "bind.saving": "正在保存频道…",
708
+ "bind.scanned": "已扫码,请在手机上确认",
709
+ "bind.success": "登录成功,微信频道已连接",
710
+ "bind.tabsAria": "绑定方式",
711
+ "bind.title": "添加微信频道",
712
+ "channel.empty": "添加微信频道后,就可以在微信里直接驱动本机智能体。个人微信一个用户只能创建一个机器人,删除现有频道后才能重新添加。",
713
+ "channel.emptyTitle": "还没有微信频道",
714
+ "channel.sessions": "微信会话",
715
+ "channel.status": "连接状态",
716
+ "channel.wechatId": "微信用户",
717
+ "channel.weixin": "微信",
718
+ "command.disabled": "仅正常对话",
719
+ "command.dm": "私聊命令",
720
+ "command.enabled": "可以执行命令",
721
+ "command.group": "群聊命令",
722
+ "composer.addWorkspace": "添加工作区…",
723
+ "composer.model": "模型",
724
+ "composer.modelLoading": "模型加载中",
725
+ "composer.modelReadOnly": "在频道设置中切换模型",
726
+ "composer.modelUnavailable": "模型不可用",
727
+ "composer.noWorkspaces": "暂无工作区",
728
+ "composer.permission": "权限",
729
+ "composer.remoteHint": "该会话只能在微信客户端继续;本地输入已禁用。",
730
+ "composer.remoteTitle": "微信频道会话",
731
+ "composer.stopConfirm": "停止生成",
732
+ "composer.stopDescription": "将中断当前会话正在运行的大模型推理;已排队的消息会保留。",
733
+ "composer.stopTitle": "停止生成?",
734
+ "composer.workspaceRequired": "请先添加工作区,否则无法保存",
735
+ "connection.checkFailed": "状态检查未完成,请重试;仍失败时查看本机日志。",
736
+ "connection.checkedAt": "检查时间",
737
+ "connection.checking": "检查中…",
738
+ "connection.connected": "已连接",
739
+ "connection.connecting": "连接中",
740
+ "connection.diagnostics": "连接诊断",
741
+ "connection.disconnected": "未连接",
742
+ "connection.error": "连接异常",
743
+ "connection.paused": "接收已暂停",
744
+ "connection.receiveOff": "接收开关已关闭;请在频道设置中开启后再发送消息。",
745
+ "connection.receiveOn": "接收开关已开启",
746
+ "connection.receiveUnknown": "无法读取接收开关,请重启 DSH 并刷新页面。",
747
+ "connection.reconnecting": "重连中",
748
+ "connection.restartRequired": "前后端版本不一致。请完整重启 DSH 并刷新页面后重新诊断。",
749
+ "connection.stopped": "已停止",
750
+ "connection.unknown": "状态未知",
751
+ "diagnostic.auth": "微信登录已失效,请重新扫码登录或删除频道后重新添加。",
752
+ "diagnostic.cancelled": "诊断已取消,未确认连接状态。",
753
+ "diagnostic.changed": "频道状态已变化,请重新诊断。",
754
+ "diagnostic.config": "微信登录与接口检查",
755
+ "diagnostic.failed": "失败",
756
+ "diagnostic.invalid-response": "平台响应不完整或格式不符,无法确认可用。",
757
+ "diagnostic.local-state": "无法读取凭据或初始化本地频道状态,请检查本机配置及文件访问权限。",
758
+ "diagnostic.missing-context": "缺少原聊天上下文,请让微信账号先发送一条消息后重试。",
759
+ "diagnostic.network": "网络请求失败,请检查网络或代理。",
760
+ "diagnostic.not-connected": "当前没有可验证的连接,请先重新连接。",
761
+ "diagnostic.ok": "平台已返回有效响应",
762
+ "diagnostic.passed": "通过",
763
+ "diagnostic.permission": "平台拒绝访问,请检查微信登录状态。",
764
+ "diagnostic.rate-limit": "平台限流,请稍后再试。",
765
+ "diagnostic.rejected": "平台拒绝请求,请稍后再试。",
766
+ "diagnostic.scope": "以下为本次平台接口或心跳检查结果。未发送测试消息,消息投递权限仍未验证。",
767
+ "diagnostic.server": "平台服务异常,请稍后再试。",
768
+ "diagnostic.timeout": "诊断超时,请检查网络后重试。",
769
+ "diagnostic.title": "连接诊断",
770
+ "diagnostic.unsupported": "当前配置不支持此诊断,未判定为通过。",
771
+ "diagnostic.unverified": "未验证",
772
+ "error.action": "操作失败",
773
+ "error.addWorkspace": "新增工作区失败",
774
+ "error.chooseWorkspace": "请选择工作区目录",
775
+ "error.connection": "无法连接本机微信频道接口",
776
+ "error.detailsInLog": "操作失败,请查看服务器日志。",
777
+ "error.load": "加载失败",
778
+ "error.qr": "无法生成二维码",
779
+ "error.request": "请求失败",
780
+ "error.save": "保存失败",
781
+ "error.workspaceUnavailable": "当前 Host 无法新增工作区",
782
+ "loading": "加载中…",
783
+ "pending.notice": "有访问请求。批准后该用户才能驱动本机助手。",
784
+ "permission.fullAccess": "完全访问",
785
+ "permission.readOnly": "只读",
786
+ "permission.workspaceWrite": "工作区写入",
787
+ "qr.default": "请使用手机微信扫描二维码",
788
+ "qr.weixin": "请使用手机微信扫描二维码并确认登录",
789
+ "rail.weixin": "微信频道",
790
+ "server.accessDenied": "未授权:请管理员在设置 → DSH微信频道 中批准你的访问。",
791
+ "server.accountConnectFailed": "频道连接失败,请查看本机日志",
792
+ "server.accountMissing": "频道不存在",
793
+ "server.accountReconnectFailed": "重新连接频道失败,请查看本机日志",
794
+ "server.channelExists": "已有微信频道,请先删除现有频道后再添加",
795
+ "server.channelUnconfigured": "渠道未配置",
796
+ "server.createWorkspace": "请先添加工作区",
797
+ "server.missingCredentials": "凭据不足,无法启动渠道",
798
+ "server.qrExpired": "二维码已过期",
799
+ "server.qrIncomplete": "扫码未完成",
800
+ "server.qrUnsupported": "该渠道不支持扫码绑定",
801
+ "server.remarkControl": "频道名称不能包含换行或控制字符",
802
+ "server.remarkTooLong": "频道名称不能超过 40 个字符",
803
+ "server.selectAccountSettings": "请选择提供商、模型、工作区或权限",
804
+ "server.selectModel": "请选择提供商和模型",
805
+ "server.selectPermission": "请选择权限",
806
+ "server.selectWorkspace": "请选择工作区",
807
+ "server.sessionMissing": "会话不存在",
808
+ "server.unknownChannel": "未知渠道",
809
+ "session.untitled": "未命名会话",
810
+ "settings.aria": "DSH微信频道",
811
+ "settings.description": "把个人微信机器人接入本机 DeepSeek Harness;一个插件只承载一个微信频道,配置仅保存在本机。",
812
+ "settings.label": "DSH微信频道",
813
+ "settings.publicChatNotice": "未批准用户可以发起聊天,但不能批准工具调用。",
814
+ "settings.title": "DSH微信频道",
815
+ "status.longConnection": "已登录",
816
+ "status.saved": "已保存",
817
+ "status.saving": "保存中…",
818
+ "status.stopped": "已停止",
819
+ "time.ago": "{t}前",
820
+ "time.days": "{n}天",
821
+ "time.hours": "{n}小时",
822
+ "time.minutes": "{n}分钟",
823
+ "time.months": "{n}个月",
824
+ "time.now": "刚刚",
825
+ "time.years": "{n}年",
826
+ },
827
+ en: {
828
+ "account.autoNameNote": "This name is only used locally.",
829
+ "account.channelName": "Channel name",
830
+ "account.currentWorkspace": "Current workspace",
831
+ "account.defaultName": "{channel} channel {count}",
832
+ "account.noSessions": "No sessions yet. Send the bot a message from WeChat and the session will appear here.",
833
+ "account.presetNote": "Changes start a new session; previous sessions are kept.",
834
+ "account.presetUnavailable": "Preset unavailable",
835
+ "account.privateAccess": "Direct chat access",
836
+ "account.privateAll": "Allow all DM users",
837
+ "account.privateApproved": "Approved users only",
838
+ "account.remark": "Channel name",
839
+ "account.removeConfirm": "Remove this WeChat channel? Its saved settings, login credential, and session mappings will be deleted. You can add a channel again afterwards.",
840
+ "account.rename": "Edit channel name",
841
+ "account.selectModel": "Select a model",
842
+ "account.selectPermission": "Select a permission",
843
+ "account.selectWorkspace": "Select a workspace",
844
+ "account.sendMode": "Send mode",
845
+ "account.sendQueue": "Queue",
846
+ "account.sendSteer": "Steer",
847
+ "account.sendSteerNote": "Steer hands the message to the running task as additional instructions at its next step; when the task is idle it behaves like Queue.",
848
+ "account.statusNotConnected": "Not connected",
849
+ "account.workspace": "Workspace",
850
+ "action.addAccount": "Add Weixin channel",
851
+ "action.approve": "Approve",
852
+ "action.cancel": "Cancel",
853
+ "action.checkConnection": "Diagnose connection",
854
+ "action.collapse": "Collapse",
855
+ "action.confirm": "Confirm",
856
+ "action.deny": "Deny",
857
+ "action.expand": "Expand",
858
+ "action.generateQr": "Generate QR code",
859
+ "action.reconnectAccount": "Reconnect",
860
+ "action.removeAccount": "Remove",
861
+ "action.saving": "Saving…",
862
+ "action.settings": "Settings",
863
+ "app.copied": "Copied",
864
+ "app.copy": "Copy",
865
+ "app.info": "WeChat binding",
866
+ "app.loggedIn": "Signed in",
867
+ "app.login": "Login",
868
+ "app.notLoggedIn": "Not signed in",
869
+ "app.notSaved": "Not saved",
870
+ "app.wechatId": "WeChat user ID",
871
+ "bind.expire": "QR code expires in {time}",
872
+ "bind.generating": "Generating…",
873
+ "bind.manual": "Manual setup",
874
+ "bind.newIdentity": "A new WeChat identity was detected",
875
+ "bind.qrAlt": "{channel} login QR code",
876
+ "bind.quick": "Quick setup (recommended)",
877
+ "bind.refresh": "Generate a new QR code",
878
+ "bind.retry": "Generate a new QR code",
879
+ "bind.saving": "Saving channel…",
880
+ "bind.scanned": "Scanned. Confirm on your phone.",
881
+ "bind.success": "Signed in and the WeChat channel is connected",
882
+ "bind.tabsAria": "Sign-in method",
883
+ "bind.title": "Add WeChat channel",
884
+ "channel.empty": "Add a WeChat channel to drive local agents from WeChat. A personal WeChat user can create only one bot, so you must remove the current channel before adding another.",
885
+ "channel.emptyTitle": "No WeChat channel yet",
886
+ "channel.sessions": "WeChat sessions",
887
+ "channel.status": "Connection",
888
+ "channel.wechatId": "WeChat user",
889
+ "channel.weixin": "WeChat",
890
+ "command.disabled": "Conversation only",
891
+ "command.dm": "Direct chat commands",
892
+ "command.enabled": "Commands enabled",
893
+ "command.group": "Group commands",
894
+ "composer.addWorkspace": "Add workspace…",
895
+ "composer.model": "Model",
896
+ "composer.modelLoading": "Loading models",
897
+ "composer.modelReadOnly": "Change the model in channel settings",
898
+ "composer.modelUnavailable": "Model unavailable",
899
+ "composer.noWorkspaces": "No workspaces",
900
+ "composer.permission": "Permission",
901
+ "composer.remoteHint": "This session can only continue in WeChat; local input is disabled.",
902
+ "composer.remoteTitle": "WeChat channel session",
903
+ "composer.stopConfirm": "Stop generating",
904
+ "composer.stopDescription": "This interrupts the running model turn in this session; queued messages are preserved.",
905
+ "composer.stopTitle": "Stop generating?",
906
+ "composer.workspaceRequired": "Add a workspace before saving.",
907
+ "connection.checkFailed": "The status check did not finish. Retry, or check the local logs if it keeps failing.",
908
+ "connection.checkedAt": "Checked at",
909
+ "connection.checking": "Checking…",
910
+ "connection.connected": "Connected",
911
+ "connection.connecting": "Connecting",
912
+ "connection.diagnostics": "Connection diagnostics",
913
+ "connection.disconnected": "Disconnected",
914
+ "connection.error": "Connection error",
915
+ "connection.paused": "Receiving paused",
916
+ "connection.receiveOff": "Receiving is disabled. Enable it in channel settings before sending messages.",
917
+ "connection.receiveOn": "Receiving is enabled",
918
+ "connection.receiveUnknown": "The receiving switch is unavailable. Restart DSH and refresh the page.",
919
+ "connection.reconnecting": "Reconnecting",
920
+ "connection.restartRequired": "Frontend and backend versions differ. Restart DSH, refresh the page, and run the check again.",
921
+ "connection.stopped": "Stopped",
922
+ "connection.unknown": "Status unknown",
923
+ "diagnostic.auth": "The WeChat login expired. Sign in again by QR code, or remove the channel and add it again.",
924
+ "diagnostic.cancelled": "The check was cancelled. Connection status was not verified.",
925
+ "diagnostic.changed": "The channel state changed. Run diagnostics again.",
926
+ "diagnostic.config": "WeChat login and API check",
927
+ "diagnostic.failed": "Failed",
928
+ "diagnostic.invalid-response": "The platform response was incomplete or invalid. Availability could not be confirmed.",
929
+ "diagnostic.local-state": "Could not read credentials or initialize local channel state. Check local configuration and file permissions.",
930
+ "diagnostic.missing-context": "The original chat context is missing. Send a message from the WeChat account first, then retry.",
931
+ "diagnostic.network": "The request failed. Check your network or proxy.",
932
+ "diagnostic.not-connected": "No active connection is available to verify. Reconnect first.",
933
+ "diagnostic.ok": "The platform returned a valid response",
934
+ "diagnostic.passed": "Passed",
935
+ "diagnostic.permission": "Access was denied. Check the WeChat login state.",
936
+ "diagnostic.rate-limit": "The platform rate limit was reached. Retry later.",
937
+ "diagnostic.rejected": "The platform rejected the request. Retry later.",
938
+ "diagnostic.scope": "Results from platform queries or a connection heartbeat in this check. No test messages were sent; message delivery permissions remain unverified.",
939
+ "diagnostic.server": "The platform service failed. Retry later.",
940
+ "diagnostic.timeout": "The check timed out. Check your network and retry.",
941
+ "diagnostic.title": "Connection diagnostics",
942
+ "diagnostic.unsupported": "The current configuration does not support this check. It has not passed.",
943
+ "diagnostic.unverified": "Unverified",
944
+ "error.action": "Action failed",
945
+ "error.addWorkspace": "Could not add workspace",
946
+ "error.chooseWorkspace": "Choose a workspace directory",
947
+ "error.connection": "Could not connect to the local WeChat channel API",
948
+ "error.detailsInLog": "The operation failed. Check the server logs for details.",
949
+ "error.load": "Could not load",
950
+ "error.qr": "Could not generate a QR code",
951
+ "error.request": "Request failed",
952
+ "error.save": "Could not save",
953
+ "error.workspaceUnavailable": "This Host cannot create workspaces",
954
+ "loading": "Loading…",
955
+ "pending.notice": "There are access requests. Approve a user before they can control the local assistant.",
956
+ "permission.fullAccess": "Full access",
957
+ "permission.readOnly": "Read Only",
958
+ "permission.workspaceWrite": "Workspace Write",
959
+ "qr.default": "Scan the QR code with WeChat on your phone",
960
+ "qr.weixin": "Scan the QR code with WeChat on your phone and confirm the login",
961
+ "rail.weixin": "Weixin",
962
+ "server.accessDenied": "Access denied: ask an administrator to approve you in Settings → DSH WeChat Channel.",
963
+ "server.accountConnectFailed": "Could not connect the channel. Check the local logs.",
964
+ "server.accountMissing": "Channel does not exist",
965
+ "server.accountReconnectFailed": "Could not reconnect the channel. Check the local logs.",
966
+ "server.channelExists": "A WeChat channel already exists. Remove it before adding another.",
967
+ "server.channelUnconfigured": "Channel is not configured",
968
+ "server.createWorkspace": "Add a workspace first.",
969
+ "server.missingCredentials": "The channel cannot start because credentials are missing",
970
+ "server.qrExpired": "QR code has expired",
971
+ "server.qrIncomplete": "QR setup was not completed",
972
+ "server.qrUnsupported": "This channel does not support QR setup",
973
+ "server.remarkControl": "Channel name cannot contain line breaks or control characters",
974
+ "server.remarkTooLong": "Channel name cannot exceed 40 characters",
975
+ "server.selectAccountSettings": "Select a provider, model, workspace, or permission setting",
976
+ "server.selectModel": "Select a provider and model",
977
+ "server.selectPermission": "Select a permission",
978
+ "server.selectWorkspace": "Select a workspace",
979
+ "server.sessionMissing": "Session does not exist",
980
+ "server.unknownChannel": "Unknown channel",
981
+ "session.untitled": "Untitled session",
982
+ "settings.aria": "DSH WeChat Channel",
983
+ "settings.description": "Connect a personal WeChat bot to the local DeepSeek Harness. One plugin hosts exactly one WeChat channel; settings stay on this machine.",
984
+ "settings.label": "DSH WeChat Channel",
985
+ "settings.publicChatNotice": "Unapproved users can start chats, but they cannot approve tool calls.",
986
+ "settings.title": "DSH WeChat Channel",
987
+ "status.longConnection": "Signed in",
988
+ "status.saved": "Saved",
989
+ "status.saving": "Saving…",
990
+ "status.stopped": "Stopped",
991
+ "time.ago": "{t} ago",
992
+ "time.days": "{n}d",
993
+ "time.hours": "{n}h",
994
+ "time.minutes": "{n}min",
995
+ "time.months": "{n}mo",
996
+ "time.now": "now",
997
+ "time.years": "{n}y",
998
+ },
999
+ };
1000
+ const fallbackT = (key) => key;
1001
+ const h = React.createElement;
1002
+ function HostThemeProvider({ children }) {
1003
+ return children;
1004
+ }
1005
+
1006
+ const CSS = `
1007
+ .dwc-page,.dwc-account-modal,.dwc-bind-modal,.dwc-inspector{--dwc-text:var(--dsw-alias-label-primary,var(--dsh-text,#e6edf3));--dwc-muted:var(--dsw-alias-label-tertiary,var(--dsh-text-muted,#8b949e));--dwc-line:var(--dsw-alias-border-l2,var(--dsh-border,rgba(255,255,255,.1)));--dwc-card:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.04));--dwc-card-hover:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06));--dwc-ok:var(--dsw-alias-state-success-primary,#3fb950);--dwc-warning:var(--dsw-alias-state-warning-primary,#d29922);--dwc-danger:var(--dsw-alias-state-error-primary,#f85149);--dwc-accent:var(--dsw-alias-brand-primary,#4b7cff)}
1008
+ .dwc-page{box-sizing:border-box;max-width:none;width:100%;margin:0;padding:0 0 32px;color:var(--dwc-text)}
1009
+ .dwc-head{display:flex;flex-direction:column;align-items:stretch;gap:12px;margin-bottom:12px}
1010
+ .dwc-heading h2,.dwc-title{margin:0;font-size:24px;line-height:32px;font-weight:600;letter-spacing:-.4px;white-space:nowrap;text-align:left}
1011
+ .dwc-title-row{display:flex;align-items:center;gap:8px 12px;min-width:0;flex-wrap:wrap}
1012
+ .dwc-title-links{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
1013
+ .dwc-title-links>span[data-mpi-check]{display:inline-flex;align-items:center}
1014
+ [data-dwc-nav-icon="assistant"]>svg{display:none!important}
1015
+ .dwc-nav-icon-assistant{display:inline-block;flex:none;width:16px;height:16px;background:currentColor;-webkit-mask:var(--dwc-nav-icon-mask) center/contain no-repeat;mask:var(--dwc-nav-icon-mask) center/contain no-repeat}
1016
+ .dwc-btn{display:inline-flex;align-items:center;justify-content:center;gap:4px;height:32px;padding:0 12px;border:0.5px solid var(--dsw-alias-border-l3,#555);border-radius:var(--dsw-radius-sm,8px);background:transparent;color:var(--dsw-alias-label-primary,#eee);font:inherit;font-size:13px;line-height:20px;cursor:pointer;user-select:none;box-sizing:border-box;text-decoration:none;transition:border-color 120ms ease,color 120ms ease,background 120ms ease}
1017
+ .dwc-btn:not(.is-primary):not(.dwc-btn-danger){color:var(--dsw-alias-label-primary,#eee)!important}
1018
+ .dwc-btn:hover:not(:disabled):not(.dwc-btn-danger){border-color:var(--dsw-alias-border-l3,#666)!important;color:var(--dsw-alias-label-primary,#fff)!important;background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))!important}
1019
+ .dwc-btn:focus-visible{outline:var(--dsw-focus-ring-width,1px) solid var(--dsw-focus-ring-color,var(--dsw-alias-brand-primary,#4b7cff))!important;outline-offset:0!important}
1020
+ .dwc-btn:disabled,.dwc-btn.is-disabled{opacity:.4!important;cursor:not-allowed!important;pointer-events:none!important}
1021
+ .dwc-btn.is-primary,.dwc-bind-ready .dwc-btn.is-primary{background:var(--dsw-alias-button-primary-fill,#f9fafb)!important;border-color:transparent!important;color:var(--dsw-alias-label-primary-foreground,#0f1115)!important}
1022
+ .dwc-btn.is-primary *,.dwc-bind-ready .dwc-btn.is-primary *{color:inherit!important;fill:currentColor!important}
1023
+ .dwc-btn.is-primary:hover:not(:disabled),.dwc-bind-ready .dwc-btn.is-primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-hover,#ebeef2)!important;color:var(--dsw-alias-label-primary-foreground,#0f1115)!important}
1024
+ .dwc-btn.is-primary:disabled,.dwc-bind-ready .dwc-btn.is-primary:disabled{opacity:.4!important;cursor:not-allowed!important}
1025
+ .dwc-btn.is-block{width:100%!important}
1026
+ .dwc-link-btn{height:28px!important;padding:0 10px!important;font-size:12px!important}
1027
+ .dwc-sub{margin:12px 0 0;max-width:none;color:var(--dwc-muted);font-size:14px;line-height:22px;text-align:left}
1028
+ .dwc-error{color:var(--dwc-danger);font-size:12px;margin:0 0 12px}
1029
+ .dwc-pending,.dwc-page>.dwc-feedback,.dwc-inspector .dwc-feedback{margin:0 0 12px}
1030
+ .dwc-feedback{display:flex;align-items:flex-start;gap:8px;padding:10px 14px;border-radius:var(--dsw-radius-sm,8px);font-size:13px;line-height:20px;border:0.5px solid var(--dsw-alias-border-l2,rgba(255,255,255,.1));background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.08));color:var(--dsw-alias-label-primary,#eee)}
1031
+ .dwc-feedback-error{background:color-mix(in srgb, var(--dsw-alias-state-error-primary,#f85149) 12%, transparent);border-color:color-mix(in srgb, var(--dsw-alias-state-error-primary,#f85149) 30%, transparent);color:var(--dsw-alias-label-primary,#eee)}
1032
+ .dwc-feedback-error .dwc-feedback-icon{color:var(--dsw-alias-state-error-primary,#f85149)}
1033
+ .dwc-feedback-warning{background:color-mix(in srgb, var(--dsw-alias-state-warning-primary,#d29922) 12%, transparent);border-color:color-mix(in srgb, var(--dsw-alias-state-warning-primary,#d29922) 30%, transparent);color:var(--dsw-alias-label-primary,#eee)}
1034
+ .dwc-feedback-warning .dwc-feedback-icon{color:var(--dsw-alias-state-warning-primary,#d29922)}
1035
+ .dwc-feedback-success{background:color-mix(in srgb, var(--dsw-alias-state-success-primary,#3fb950) 12%, transparent);border-color:color-mix(in srgb, var(--dsw-alias-state-success-primary,#3fb950) 30%, transparent);color:var(--dsw-alias-label-primary,#eee)}
1036
+ .dwc-feedback-success .dwc-feedback-icon{color:var(--dsw-alias-state-success-primary,#3fb950)}
1037
+ .dwc-feedback-info{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.08));color:var(--dsw-alias-label-primary,#eee)}
1038
+ .dwc-feedback-icon{display:inline-flex;align-items:center;flex:none;margin-top:3px}
1039
+ .dwc-feedback-body{flex:1;min-width:0;word-break:break-word}
1040
+ .dwc-pending{display:flex;flex-direction:column;gap:8px}
1041
+ .dwc-feedback-head{display:flex;align-items:center;gap:8px}
1042
+ .dwc-feedback-title{font-weight:550;line-height:20px}
1043
+ .dwc-pending-list{display:flex;flex-direction:column;gap:6px;width:100%}
1044
+ .dwc-pending-row{display:flex;gap:8px;align-items:center;padding:4px 0}
1045
+ .dwc-wrap{display:flex;flex-direction:column;min-height:0;flex:1;height:100%;overflow:hidden}.dwc-official-tree{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}
1046
+ .dwc-tabs-wrap{display:flex;margin:2px var(--dsh-sidebar-inline-padding,12px) 8px 0;padding:0;width:auto}
1047
+ .dwc-tabs-wrap .dwc-segmented-tabs{display:grid!important;width:100%!important;box-sizing:border-box!important;height:32px!important;min-height:32px!important;max-height:32px!important;padding:2px!important;border:0!important;border-radius:var(--dsw-radius-sm,8px)!important;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l2,rgba(255,255,255,.08))!important;background:var(--dsw-alias-bg-layer-1,rgba(255,255,255,.02))!important}
1048
+ .dwc-tabs-wrap .dwc-segmented-tabs>span{inset:2px auto 2px 2px!important;width:calc((100% - 4px)/var(--dwc-tab-count,2))!important;border-radius:6px!important;border:0.5px solid var(--dsw-alias-border-l3,rgba(255,255,255,.12))!important;background:var(--dsw-alias-bg-layer-3,rgba(255,255,255,.08))!important;box-shadow:none!important}
1049
+ .dwc-tabs-wrap .dwc-segmented-tabs [role=tab]{display:inline-flex!important;align-items:center!important;justify-content:center!important;gap:6px!important;height:28px!important;padding:0 clamp(6px,calc(100% - 60px),12px)!important;font-size:13px!important;line-height:20px!important;border-radius:6px!important;color:var(--dsw-alias-label-secondary,#8b8f98)!important;text-align:center!important;white-space:nowrap!important;box-sizing:border-box!important;transition:color 150ms ease!important}
1050
+ .dwc-tabs-wrap .dwc-segmented-tabs [role=tab]>*{display:inline-flex!important;align-items:center!important;justify-content:center!important}
1051
+ .dwc-tabs-wrap .dwc-segmented-tabs [role=tab]:hover{color:var(--dsw-alias-label-primary,inherit)!important}
1052
+ .dwc-tabs-wrap .dwc-segmented-tabs [role=tab][aria-selected=true]{color:var(--dsw-alias-label-primary,inherit)!important;font-weight:600!important}
1053
+ .dwc-bind-tabs-wrap{width:100%;margin:0 0 16px}
1054
+ .dwc-bind-tabs-wrap.is-disabled{opacity:.6;pointer-events:none}
1055
+ .dwc-bind-panel[hidden]{display:none!important}
1056
+ .dwc-bind-tabs-wrap .dwc-bind-tabs{width:100%;height:32px;box-sizing:border-box;border-bottom:0;background:color-mix(in srgb,var(--dsw-alias-label-primary,currentColor) 3%,transparent)!important;border-radius:var(--dsw-radius-sm,8px)!important;border:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.05))!important;padding:2px!important}
1057
+ .dwc-bind-tabs-wrap .dwc-bind-tabs>span{inset:2px auto 2px 2px!important;width:calc((100% - 4px)/2)!important;border-radius:calc(var(--dsw-radius-sm,8px) - 2px)!important;border:0.5px solid color-mix(in srgb,var(--dsw-alias-label-primary,currentColor) 12%,transparent)!important;background:color-mix(in srgb,var(--dsw-alias-label-primary,currentColor) 8%,transparent)!important;box-shadow:none!important}
1058
+ .dwc-bind-tabs-wrap .dwc-bind-tabs [role=tab]{display:inline-flex!important;align-items:center!important;justify-content:center!important;gap:6px!important;width:100%!important;height:26px!important;padding:0 10px!important;font-size:13px!important;line-height:18px!important;border-radius:calc(var(--dsw-radius-sm,8px) - 2px)!important;color:var(--dsw-alias-label-secondary,#8b8f98);text-align:center!important}
1059
+ .dwc-bind-tabs-wrap .dwc-bind-tabs [role=tab]>*{display:inline-flex!important;align-items:center!important;justify-content:center!important}
1060
+ .dwc-bind-tabs-wrap .dwc-bind-tabs [role=tab]:hover{color:var(--dsw-alias-label-primary,inherit)}
1061
+ .dwc-bind-tabs-wrap .dwc-bind-tabs [role=tab][aria-selected=true]{color:var(--dsw-alias-label-primary,inherit)!important;font-weight:600}
1062
+ .dwc-tabs{display:flex;gap:18px;padding:4px 12px 0;border-bottom:1px solid var(--dwc-line)}
1063
+ .dwc-tab{appearance:none;border:0;background:transparent;color:var(--dwc-muted);padding:8px 0;font-size:13px;cursor:pointer}
1064
+ .dwc-tab.on{color:var(--dwc-text);box-shadow:inset 0 -2px 0 currentColor}
1065
+ .dwc-tabs{flex:none}
1066
+ .dwc-empty{color:var(--dwc-muted);font-size:12px;padding:12px 8px}
1067
+ .dwc-channel-official{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden}
1068
+ .dwc-channel-official>div{flex:1;min-width:0;min-height:0}
1069
+ .dwc-channel-official>.dwc-channel-error{flex:none}
1070
+ .dwc-channel-official>.dwc-channel-unavailable{flex:1}
1071
+ .dwc-channel-error{padding:8px 12px;color:var(--dsw-alias-state-error-primary,#f85149);font-size:12px;line-height:18px}
1072
+ .dwc-channel-unavailable{padding:16px 12px;color:var(--dsw-alias-label-tertiary,#8b8f98);font-size:13px;line-height:20px}
1073
+ .dwc-session-channel-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;flex:none}
1074
+ /* 频道页签复用官方工作区浏览器:分组头操作按模式裁剪。 */
1075
+ .dwc-channel-official[data-mode="channel"] [data-row-key^="workspace:dsh-im-channel:"]>span:last-child>:last-child{display:none!important}
1076
+ .dwc-channel-official[data-mode="workspace"] [data-row-key^="workspace:"]>span:last-child,
1077
+ .dwc-channel-official[data-mode="workspace-tree"] [data-row-key^="workspace:"]>span:last-child{display:none!important}
1078
+ .dwc-logo{width:28px;height:28px;flex:none;display:block;line-height:0;background:transparent}
1079
+ .dwc-logo svg{width:28px;height:28px;display:block}
1080
+ .dwc-logo.sm{width:16px;height:16px;overflow:hidden;display:grid;place-items:center}
1081
+ .dwc-logo.sm svg{width:16px;height:16px;transform:none}
1082
+ .dwc-qrbox{display:flex;flex-direction:column;align-items:center;gap:10px;padding:8px 0 4px}
1083
+ .dwc-qrbox img{width:200px;height:200px;background:#fff;border:1px solid var(--dwc-line);border-radius:12px;object-fit:contain}
1084
+ .dwc-bind-ready{display:flex;flex-direction:column;align-items:center;gap:14px;padding:12px 0 4px}.dwc-bind-ready .dwc-btn{min-width:136px}.dwc-bind-status{min-height:40px;display:grid;place-items:center;color:var(--dwc-muted);font-size:13px;text-align:center}
1085
+ .dwc-hint{margin:0;color:var(--dwc-muted);font-size:13px;text-align:center;line-height:1.6}
1086
+ .dwc-field{display:flex;flex-direction:column;gap:6px;margin-bottom:12px;font-size:13px}
1087
+ .dwc-field .dwc-input,.dwc-field input{width:100%}
1088
+ .dwc-input,.dwc-account-remark-input,.dwc-field input{box-sizing:border-box!important;height:36px!important;padding:0 12px!important;border:0.5px solid var(--dsw-alias-border-l2,#494949)!important;border-radius:var(--dsw-radius-sm,8px)!important;background:var(--dsw-alias-bg-layer-1,transparent)!important;color:var(--dsw-alias-label-primary,#eee)!important;font:inherit!important;font-size:13px!important;line-height:20px!important;transition:border-color 120ms ease,background 120ms ease!important}
1089
+ .dwc-textarea{height:auto!important;min-height:80px;padding:8px 12px!important;resize:vertical}
1090
+ .dwc-input:hover:not(:disabled),.dwc-account-remark-input:hover:not(:disabled),.dwc-field input:hover:not(:disabled){border-color:var(--dsw-alias-border-l3,#666)!important}
1091
+ .dwc-input:focus,.dwc-account-remark-input:focus,.dwc-field input:focus{border-color:var(--dsw-alias-brand-primary,#4b7cff)!important;outline:var(--dsw-focus-ring-width,1px) solid var(--dsw-focus-ring-color,var(--dsw-alias-brand-primary,#4b7cff))!important;outline-offset:0!important}
1092
+ .dwc-input::placeholder,.dwc-account-remark-input::placeholder,.dwc-field input::placeholder{color:var(--dsw-alias-label-tertiary,#888)!important}
1093
+ .dwc-input:disabled,.dwc-account-remark-input:disabled{opacity:.5!important;cursor:not-allowed!important}
1094
+ .dwc-checkbox-label{display:inline-flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-primary,#eee);cursor:pointer;user-select:none}
1095
+ .dwc-checkbox-label.is-disabled{opacity:.5;cursor:not-allowed}
1096
+ .dwc-checkbox{width:16px;height:16px;margin:0;accent-color:var(--dsw-alias-state-business-primary,#4176e6);cursor:inherit}
1097
+ .dwc-tag{display:inline-flex!important;align-items:center!important;gap:4px!important;height:22px!important;padding:0 8px!important;font-size:12px!important;line-height:20px!important;border-radius:var(--dsw-radius-sm,6px)!important;font-weight:500!important;box-sizing:border-box!important;vertical-align:middle!important;background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.12));color:var(--dsw-alias-label-secondary,#b9b9b9);border:none}
1098
+ .dwc-tag .dwc-btn-spinner{width:11px!important;height:11px!important;margin-right:2px!important;vertical-align:0!important}
1099
+ .dwc-tag-info,.dwc-tag-processing,.dwc-tag.is-busy{background:color-mix(in srgb,var(--dsw-alias-state-business-primary,#4176e6) 14%,transparent)!important;color:var(--dsw-alias-state-business-primary,#4176e6)!important}
1100
+ .dwc-tag-success{background:color-mix(in srgb,var(--dsw-alias-state-success-primary,#3fb950) 14%,transparent)!important;color:var(--dsw-alias-state-success-primary,#3fb950)!important}
1101
+ .dwc-tag-warning{background:color-mix(in srgb,var(--dsw-alias-state-warn-primary,#d29922) 14%,transparent)!important;color:var(--dsw-alias-state-warn-primary,#d29922)!important}
1102
+ .dwc-tag-error{background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#f85149) 14%,transparent)!important;color:var(--dsw-alias-state-error-primary,#f85149)!important}
1103
+ .dwc-modal-root{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;z-index:1100}
1104
+ .dwc-modal-mask{position:absolute;inset:0;background:rgba(0,0,0,.45);backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px)}
1105
+ .dwc-modal-wrap{position:relative;max-width:calc(100vw - 32px);max-height:calc(100vh - 48px);overflow:auto;display:flex}
1106
+ .dwc-modal-panel{position:relative;isolation:isolate;box-sizing:border-box;padding:24px 28px 28px;border-radius:var(--dsw-radius-panel,28px);background:var(--dsw-specific-menu,var(--dsw-alias-bg-layer-1));backdrop-filter:var(--dsw-menu-backdrop-filter,blur(20px));-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter,blur(20px));border:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.1));box-shadow:var(--dsw-elevation-panel,0 20px 48px -12px rgba(0,0,0,.35));color:var(--dsw-alias-label-primary,#eee);display:flex;flex-direction:column;gap:16px}
1107
+ .dwc-modal-header{display:flex;align-items:center;justify-content:space-between;min-height:24px}
1108
+ .dwc-modal-title{font-size:17px;font-weight:600;line-height:24px;color:var(--dsw-alias-label-primary,#eee)}
1109
+ .dwc-modal-close{width:28px;height:28px;display:flex;align-items:center;justify-content:center;border:none;border-radius:var(--dsw-radius-sm,8px);background:transparent;color:var(--dsw-alias-label-tertiary,#888);cursor:pointer;transition:all 120ms ease}
1110
+ .dwc-modal-close:hover{color:var(--dsw-alias-label-primary,#fff);background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.12))}
1111
+ .dwc-modal-body{min-height:0;overflow:visible;display:flex;flex-direction:column;gap:12px}
1112
+ .dwc-modal-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:8px}
1113
+ .dwc-modal-footer-wrap{display:flex;justify-content:flex-end;margin-top:12px;padding-top:16px}
1114
+ .dwc-inspector-actions>button{flex:none;white-space:nowrap}
1115
+ .dwc-confirm-content{margin:8px 0 0;font-size:13px;line-height:22px;color:var(--dsw-alias-label-secondary,#b9b9b9)}
1116
+ .dwc-page.dwc-account-page{container-type:inline-size;min-width:0;width:100%;padding:0 0 32px}
1117
+ .dwc-account-shell,.dwc-account-shell *{box-sizing:border-box}
1118
+ .dwc-account-shell{display:block;min-height:0;border:0;border-radius:0;overflow:visible;background:transparent}
1119
+ .dwc-platforms{display:flex;flex-direction:column;gap:12px;padding:0;border:0;background:transparent;min-width:0}
1120
+ .dwc-platform{border:1px solid color-mix(in srgb,var(--dwc-text) 16%,transparent);border-radius:12px;margin:0;overflow:hidden;background:var(--dsw-alias-bg-layer-1,color-mix(in srgb,var(--dwc-text) 4%,transparent))}.dwc-platform.open{border-color:color-mix(in srgb,var(--dwc-text) 24%,transparent)}
1121
+ .dwc-platform-head{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:10px;width:100%;min-height:56px;padding:10px 16px;border:0;border-radius:0;background:transparent;color:inherit;text-align:left;cursor:pointer}
1122
+ .dwc-platform:not(.open):not(.empty) .dwc-platform-head:hover{background:var(--dwc-card-hover)}.dwc-platform.empty .dwc-platform-head{cursor:default}
1123
+ .dwc-platform-head>.dwc-logo,.dwc-platform-head>.dwc-logo svg{width:24px;height:24px}
1124
+ .dwc-platform-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;font-weight:600}
1125
+ .dwc-platform-meta{display:inline-flex;align-items:center;gap:10px}
1126
+ .dwc-platform-count{color:var(--dwc-muted);font-size:12px;white-space:nowrap}
1127
+ .dwc-platform-caret{display:grid;width:18px;height:18px;place-items:center;color:var(--dwc-muted);transition:transform .15s ease}.dwc-platform-caret.empty{visibility:hidden}.dwc-platform.open .dwc-platform-caret{transform:rotate(90deg)}
1128
+ .dwc-account-list{display:flex;flex-direction:column;gap:8px;padding:0 14px 14px}
1129
+ .dwc-account-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto auto;align-items:center;gap:12px;width:100%;min-height:48px;padding:10px 12px;border:0;border-radius:8px;background:color-mix(in srgb,var(--dwc-text) 7%,transparent);color:inherit;text-align:left}
1130
+ .dwc-account-row:hover{background:var(--dwc-card-hover)}
1131
+ .dwc-platform-head:focus-visible,.dwc-account-row:focus-visible{outline:2px solid var(--dwc-accent);outline-offset:2px}
1132
+ .dwc-account-copy{min-width:0}.dwc-account-name{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;font-weight:500}.dwc-account-rename-button{width:100%;padding:0;border:0;background:transparent;color:inherit;text-align:left;cursor:text}.dwc-account-rename-button:hover,.dwc-account-rename-button:focus-visible{color:var(--dwc-accent)}.dwc-account-rename,.dwc-account-remark-input{box-sizing:border-box;width:100%;height:32px;padding:4px 8px;border:1px solid var(--dwc-line);border-radius:6px;background:transparent;color:inherit;font:inherit}.dwc-account-id{display:block;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dwc-muted);font-size:11px}
1133
+ .dwc-account-row .dwc-tag{margin-inline-end:0}
1134
+ .dwc-account-receive{display:inline-flex;align-items:center;justify-content:flex-end;gap:8px;white-space:nowrap;font-size:12px;color:var(--dwc-muted)}
1135
+ .dwc-inspector{padding:22px 24px 26px;min-width:0}.dwc-inspector-head{display:flex;align-items:flex-start;gap:12px;padding-bottom:18px;border-bottom:1px solid var(--dwc-line)}.dwc-inspector-head-copy{min-width:0;flex:1}.dwc-inspector-title{margin:1px 0 3px;font-size:17px;line-height:24px}.dwc-inspector-title-row{display:flex;align-items:center;gap:12px;min-width:0}.dwc-inspector-title-row .dwc-inspector-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin:0}.dwc-inspector-title-row .dwc-inspector-status{flex:none;white-space:nowrap;font-size:11px}.dwc-inspector-head-copy>.dwc-account-id{margin-top:5px}
1136
+ .dwc-inspector-status{flex:none}
1137
+ .dwc-form{display:flex;flex-direction:column;gap:16px;padding-top:20px}
1138
+ .dwc-command-permissions{min-width:0;margin:0;padding:0;border:0}
1139
+ .dwc-diagnostic-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.dwc-inspector-title-row .dwc-tag{margin-inline-end:0}.dwc-bind-modal .dwc-feedback{margin-bottom:12px}.dwc-connection-check{display:grid;gap:6px;padding:12px;border:1px solid var(--dwc-line);border-radius:8px;font-size:12px;line-height:1.6;overflow-wrap:anywhere;color:var(--dwc-muted)}.dwc-connection-check strong{color:var(--dwc-text)}.dwc-diagnostic-item{padding:8px 0;border-top:1px solid var(--dwc-line)}
1140
+ .dwc-inspector-actions{display:flex!important;flex-wrap:wrap!important;align-items:center!important;justify-content:flex-end!important;gap:8px!important;margin-top:16px!important;padding-top:16px!important;padding-bottom:4px!important}
1141
+ .dwc-account-modal .dwc-inspector{padding:0 0 16px 0}
1142
+ .dwc-bind-modal,.dwc-account-modal{width:min(720px,100%) !important;max-height:100%;min-height:0}
1143
+ /* 宿主 Modal 只把 dialog 限制在视口内,内容区默认不滚动,长内容会被裁掉;
1144
+ 把宿主的 content 区设为滚动容器,footer 保持在容器外可见。 */
1145
+ .dwc-bind-modal>.dwc-modal-content,.dwc-account-modal>.dwc-modal-content{flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-gutter:stable}
1146
+ .dwc-account-settings{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px 16px;width:100%;box-sizing:border-box}
1147
+ .dwc-account-settings.compact{grid-template-columns:1fr}
1148
+ .dwc-picker-field{display:flex;min-width:0;width:100%;flex-direction:column;gap:6px;box-sizing:border-box}
1149
+ .dwc-picker-field.wide,.dwc-picker-note,.dwc-model-effort{grid-column:1/-1}
1150
+ .dwc-model-effort{display:grid;grid-template-columns:1fr 1fr;gap:14px 16px;min-width:0;width:100%;box-sizing:border-box}
1151
+ .dwc-account-settings.compact .dwc-model-effort{grid-template-columns:1fr}
1152
+ .dwc-picker-label{color:var(--dsw-alias-label-secondary,var(--dwc-muted));font-size:12px;font-weight:550;line-height:16px}
1153
+ .dwc-picker-note{color:var(--dsw-alias-label-tertiary,var(--dwc-muted));font-size:11px;line-height:1.6;margin-top:2px}
1154
+ .dwc-picker-note.warning{color:var(--dwc-warning)}
1155
+ .dwc-save-note{color:var(--dwc-muted);font-size:11px}.dwc-save-note.ok{color:var(--dwc-ok)}
1156
+ .dwc-bind-modal .dwc-setup-section{padding:16px!important;margin:0 0 16px!important;border-radius:var(--dsw-radius-md,12px)!important;background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.04))!important;border:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.06))!important}
1157
+ .dwc-bind-ready{display:flex!important;flex-direction:column!important;align-items:center!important;gap:14px!important;padding:20px 16px!important;border-radius:var(--dsw-radius-md,12px)!important;background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.04))!important;border:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.06))!important}
1158
+ .dwc-bind-ready .dwc-btn{min-width:140px!important;height:36px!important}
1159
+ .dwc-account-picker{width:100%}
1160
+ .dwc-enable-switch{box-sizing:border-box;position:relative;flex:0 0 auto;width:36px;height:20px;padding:2px;border:0;border-radius:999px;corner-shape:round;background:var(--dsw-alias-border-l3,#555);cursor:pointer}
1161
+ .dwc-enable-switch[aria-checked=true]{background:var(--dsw-alias-brand-primary)}
1162
+ .dwc-enable-switch:disabled{cursor:default;opacity:.5}
1163
+ .dwc-enable-switch:focus-visible{outline:var(--dsw-focus-ring-width,1px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
1164
+ .dwc-enable-switch-thumb{display:block;width:16px;height:16px;border-radius:50%;corner-shape:round;background:var(--dsw-alias-label-primary-foreground,#fff);transition:transform 120ms ease;pointer-events:none}
1165
+ .dwc-enable-switch[aria-checked=false] .dwc-enable-switch-thumb{background:var(--dsw-alias-switch-thumb,#fff)}
1166
+ .dwc-enable-switch[aria-checked=true] .dwc-enable-switch-thumb{transform:translateX(16px)}
1167
+ .dwc-form-menu{box-sizing:border-box;width:max(var(--dwc-menu-width,144px),144px)!important;min-width:max(var(--dwc-menu-width,144px),144px)!important;max-width:100%!important}
1168
+ .dwc-menu-select-wrap,.dwc-menu-select-wrap > *,.dwc-menu-select-wrap span[class*="_root_"],.dwc-menu-select-wrap .dwc-menu-select-trigger,.dwc-account-picker{display:flex!important;width:100%!important;min-width:0!important;box-sizing:border-box!important}
1169
+ .dwc-menu-select-trigger{display:flex!important;align-items:center!important;justify-content:space-between!important;gap:6px!important;width:100%!important;height:36px!important;padding:0 12px!important;border:0.5px solid var(--dsw-alias-border-l2,#494949)!important;border-radius:var(--dsw-radius-sm,8px)!important;background:var(--dsw-alias-bg-layer-1,transparent)!important;color:var(--dsw-alias-label-primary,#eee)!important;font:inherit!important;font-size:13px!important;cursor:pointer!important;user-select:none!important;box-sizing:border-box!important;transition:border-color 120ms ease,background 120ms ease!important}
1170
+ .dwc-menu-select-trigger:hover:not(:disabled){border-color:var(--dsw-alias-border-l3,#666)!important;background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))!important}
1171
+ .dwc-menu-select-trigger.is-open{border-color:var(--dsw-alias-brand-primary,#4b7cff)!important;outline:var(--dsw-focus-ring-width,1px) solid var(--dsw-focus-ring-color,var(--dsw-alias-brand-primary,#4b7cff))!important}
1172
+ .dwc-menu-select-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;text-align:left}
1173
+ .dwc-menu-select-arrow{flex:none;opacity:0.6}
1174
+ .dwc-btn-spinner{display:inline-block;vertical-align:-2px;animation:dwc-spin 0.8s linear infinite}
1175
+ @keyframes dwc-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}
1176
+ .dwc-btn-danger{color:var(--dsw-alias-state-error-primary,var(--dwc-danger))!important;border-color:var(--dsw-alias-state-error-primary,var(--dwc-danger))!important}
1177
+ .dwc-btn-danger:hover:not(:disabled){color:var(--dsw-alias-state-error-primary,var(--dwc-danger))!important;border-color:var(--dsw-alias-state-error-primary,var(--dwc-danger))!important;background:rgba(239,68,68,.12)!important}
1178
+ .dwc-btn-danger-primary,.dwc-btn-danger.dwc-btn-danger-primary{background:var(--dsw-alias-state-error-primary,var(--dwc-danger))!important;border-color:var(--dsw-alias-state-error-primary,var(--dwc-danger))!important;color:#fff!important}
1179
+ @container (max-width:480px){.dwc-account-row{grid-template-columns:minmax(0,1fr) auto auto;gap:8px;padding:10px}.dwc-account-receive>span{display:none}.dwc-platform-head{padding:10px 12px}.dwc-account-list{padding:0 12px 12px}}
1180
+
1181
+ .dwc-channel-page{display:flex;flex-direction:column;gap:10px;min-height:0;height:100%;box-sizing:border-box;padding:10px 14px 16px 3px;overflow:auto}
1182
+ .dwc-channel-head{display:flex;align-items:center;justify-content:stretch;gap:8px;min-height:30px;padding:0 0 8px;flex:none;width:100%}
1183
+ .dwc-channel-add{width:100%!important;height:30px!important;min-height:30px!important;padding:0 10px!important;border:0.5px solid var(--dsw-alias-border-l2,#494949)!important;border-radius:var(--dsw-radius-sm,8px)!important;background:var(--dsw-alias-bg-layer-1,transparent)!important;color:var(--dsw-alias-label-secondary,#b9b9b9)!important;font-size:12px!important;font-weight:500!important;box-shadow:none!important}
1184
+ .dwc-channel-add:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))!important;border-color:var(--dsw-alias-border-l3,#666)!important;color:var(--dsw-alias-label-primary,#eee)!important}
1185
+ .dwc-channel-empty{display:flex;align-items:center;justify-content:center;min-height:120px;padding:18px;border:0.5px dashed var(--dsw-alias-border-l2,#494949);border-radius:var(--dsw-radius-md,12px);color:var(--dsw-alias-label-tertiary,#888);font-size:12px;line-height:1.6;text-align:center}
1186
+ .dwc-channel-pending{padding:10px;border:0.5px solid color-mix(in srgb,var(--dsw-alias-state-warn-primary,#d29922) 35%,transparent);border-radius:var(--dsw-radius-md,12px);background:color-mix(in srgb,var(--dsw-alias-state-warn-primary,#d29922) 8%,transparent)}
1187
+ .dwc-channel-pending-title{font-size:12px;font-weight:600;color:var(--dsw-alias-state-warn-primary,#d29922);margin-bottom:6px}
1188
+ .dwc-channel-pending-row{display:flex;align-items:center;gap:6px;padding:4px 0;font-size:11px}
1189
+ .dwc-channel-pending-user{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-secondary,#b9b9b9)}
1190
+ .dwc-channel-accounts{display:flex;flex-direction:column;gap:8px;min-height:0}
1191
+ .dwc-channel-account{border:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08));border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-bg-layer-1,transparent);padding:7px 8px;display:flex;flex-direction:column;gap:5px;min-width:0}
1192
+ .dwc-channel-account-head{display:flex;align-items:center;gap:6px;min-width:0;flex-wrap:nowrap}
1193
+ .dwc-channel-account-copy{flex:1;min-width:90px;display:flex;flex-direction:column;gap:1px}
1194
+ .dwc-channel-account-name{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary,#eee);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1195
+ .dwc-channel-account-actions{display:flex;align-items:center;gap:4px;flex:none;margin-left:auto}
1196
+ .dwc-channel-account-head .dwc-tag{height:18px!important;min-height:18px!important;font-size:10px!important;line-height:16px!important;padding:0 6px!important}
1197
+ .dwc-channel-settings{width:24px!important;height:24px!important;min-height:24px!important;padding:0!important;border:0!important;background:transparent!important;color:var(--dsw-alias-label-tertiary,#888)!important;box-shadow:none!important}
1198
+ .dwc-channel-settings:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))!important;color:var(--dsw-alias-label-primary,#eee)!important}
1199
+ .dwc-channel-sessions{display:flex;flex-direction:column;gap:1px;border-top:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.07));padding-top:5px}
1200
+ .dwc-channel-session{display:flex;align-items:center;gap:8px;width:100%;min-width:0;border:0;background:transparent;color:inherit;text-align:left;padding:6px 7px;border-radius:var(--dsw-radius-sm,8px);cursor:pointer;font:inherit;transition:background 120ms ease}
1201
+ .dwc-channel-session:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))}
1202
+ .dwc-channel-session.is-current{background:color-mix(in srgb,var(--dsw-alias-state-business-primary,#4b7cff) 14%,transparent);box-shadow:inset 2px 0 0 var(--dsw-alias-state-business-primary,#4b7cff)}
1203
+ .dwc-channel-session.is-current .dwc-channel-session-title{color:var(--dsw-alias-label-primary,#eee);font-weight:600}
1204
+ .dwc-channel-session-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;color:var(--dsw-alias-label-primary,#eee)}
1205
+ .dwc-channel-session-time{flex:none;font-size:10px;color:var(--dsw-alias-label-tertiary,#888);white-space:nowrap}
1206
+ .dwc-channel-account-empty{font-size:11px;color:var(--dsw-alias-label-tertiary,#888);line-height:1.5;padding:2px 1px}
1207
+ .dwc-channel-name-field{margin-bottom:14px}
1208
+ .dwc-channel-name-field .dwc-picker-label{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary,#eee)}
1209
+ .dwc-app-info{display:flex;flex-direction:column;gap:7px;padding:0;border:0;border-radius:0;background:transparent;margin-bottom:10px}
1210
+ .dwc-app-info-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary,#eee)}
1211
+ .dwc-app-fields{display:grid;grid-template-columns:minmax(0,0.66fr) minmax(0,1.34fr);gap:14px;min-width:0}
1212
+ .dwc-app-fields .dwc-picker-field{margin:0;min-width:0}
1213
+ .dwc-app-fields .dwc-copy-row{min-width:0}
1214
+ .dwc-app-fields .dwc-copy-row .dwc-btn{height:26px!important;padding:0 6px!important;font-size:10px!important;white-space:nowrap}
1215
+ .dwc-app-info .dwc-picker-field{margin:0}.dwc-app-info .dwc-picker-label{font-size:10px;color:var(--dsw-alias-label-tertiary,#888)}
1216
+ .dwc-copy-row{display:flex;align-items:center;gap:6px;min-width:0}
1217
+ .dwc-copy-row .dwc-input{flex:1;min-width:0}
1218
+ .dwc-copy-row .dwc-btn{flex:none;white-space:nowrap}
1219
+ .dwc-app-warning{display:flex;align-items:center;gap:8px;justify-content:space-between;font-size:11px;line-height:1.5;color:var(--dsw-alias-state-warn-primary,#d29922)}
1220
+ .dwc-app-warning .dwc-btn{flex:none;height:24px;padding:0 7px;font-size:10px}.dwc-app-warning a{color:var(--dsw-alias-brand-primary,#4b7cff);text-decoration:none;font-weight:600}.dwc-app-warning a:hover{text-decoration:underline}
1221
+
1222
+ .dwc-tab-inline{display:inline-flex;align-items:center;gap:5px;min-width:0}
1223
+ .dwc-tab-brand{display:inline-flex;align-items:center;justify-content:center;width:14px;height:14px;flex:none;color:currentColor}
1224
+ .dwc-tab-brand svg{width:14px;height:14px;display:block}
1225
+ .dwc-check-section{display:flex;flex-direction:column;gap:8px;padding:10px 0 2px;border-top:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08))}
1226
+ .dwc-check-head{display:flex;align-items:center;gap:8px}
1227
+ .dwc-check-title{flex:1;min-width:0;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary,#b9b9b9)}
1228
+ .dwc-check-toggle{height:24px!important;padding:0 7px!important;font-size:11px!important;color:var(--dsw-alias-label-tertiary,#888)!important}
1229
+ .dwc-remote-composer{box-sizing:border-box;width:100%;max-width:var(--dsh-composer-card-max-width,952px);margin:0 auto;padding:0 var(--dsh-composer-side-clearance,16px) 18px;display:flex;justify-content:center}
1230
+ .dwc-remote-composer-card{box-sizing:border-box;width:100%;display:flex;align-items:center;gap:10px;padding:12px 14px;border-radius:var(--dsw-radius-panel,20px);border:0.5px solid var(--dsw-alias-border-l2,#494949);background:var(--dsw-specific-input-major,var(--dsw-alias-bg-layer-1,#1b1b1b));box-shadow:var(--dsw-elevation-soft,0 4px 16px rgba(0,0,0,.12))}
1231
+ .dwc-remote-composer-icon{width:28px;height:28px;flex:none;display:grid;place-items:center;border-radius:calc(var(--dsw-radius-sm,8px));background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06));color:var(--dsw-alias-label-secondary,#b9b9b9)}
1232
+ .dwc-remote-composer-icon svg{width:18px;height:18px;display:block}
1233
+ .dwc-remote-composer-copy{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}
1234
+ .dwc-remote-composer-title{font-size:13px;font-weight:600;line-height:18px;color:var(--dsw-alias-label-primary,#eee)}
1235
+ .dwc-remote-composer-hint{font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,#888)}
1236
+ .dwc-remote-model{display:flex;align-items:center;gap:6px;flex:none;min-width:0}
1237
+ .dwc-remote-model-label{font-size:12px;line-height:16px;color:var(--dsw-alias-label-tertiary,#888);white-space:nowrap}
1238
+ .dwc-remote-model-value{box-sizing:border-box;max-width:260px;padding:5px 9px;border:0.5px solid var(--dsw-alias-border-l2,#494949);border-radius:var(--dsw-radius-sm,8px);background:var(--dsw-alias-bg-layer-1,transparent);color:var(--dsw-alias-label-primary,#eee);font-size:13px;line-height:18px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1239
+ .dwc-remote-model-missing{font-size:11px}
1240
+ .dwc-remote-stop{flex:none;width:30px!important;height:30px!important;min-width:30px!important;padding:0!important;border-radius:50%!important;background:#111!important;border:0.5px solid #333!important;color:#fff!important;margin-left:8px;box-shadow:none!important}
1241
+ .dwc-remote-stop:hover:not(:disabled){background:#000!important;border-color:#444!important;color:#fff!important}
1242
+ .dwc-remote-stop svg{fill:currentColor!important}
1243
+ .dwc-remote-model-missing{flex:none;font-size:10px;line-height:14px;color:var(--dsw-alias-label-tertiary,#888);white-space:nowrap}
1244
+ @media (max-width:520px){.dwc-app-fields{grid-template-columns:minmax(0,1fr)}.dwc-remote-composer-card{flex-wrap:wrap}.dwc-remote-model{margin-left:auto}.dwc-remote-model-value{max-width:180px}}
1245
+
1246
+
1247
+ .dwc-panel{box-sizing:border-box;display:flex;flex-direction:column;min-height:0;height:100%;width:100%;background:var(--dsw-alias-bg-base,transparent);color:var(--dsw-alias-label-primary,#eee)}
1248
+ .dwc-panel-head{display:flex;align-items:flex-start;gap:16px;padding:22px 28px 16px;border-bottom:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08));flex:none}
1249
+ .dwc-panel-head-copy{flex:1;min-width:0;display:flex;flex-direction:column;gap:4px}
1250
+ .dwc-panel-title{margin:0;display:flex;align-items:center;gap:12px;flex-wrap:wrap;text-align:left}
1251
+ .dwc-panel-title-name{font-size:24px;line-height:32px;font-weight:600;letter-spacing:-.3px}
1252
+ .dwc-panel-title-plugin{font-size:20px;line-height:28px;font-weight:600;letter-spacing:-.2px}
1253
+ .dwc-panel-title-status{display:inline-flex;align-items:center;gap:6px;font-size:13px;line-height:20px;font-weight:500;color:var(--dsw-alias-state-success-primary,#0aa457)}
1254
+ .dwc-panel-title-status.is-warning{color:var(--dsw-alias-state-warn-primary,#d29922)}
1255
+ .dwc-panel-title-status.is-error{color:var(--dsw-alias-state-error-primary,#f85149)}
1256
+ .dwc-panel-title-status.is-idle{color:var(--dsw-alias-label-tertiary,#888)}
1257
+ .dwc-panel-status-dot{width:7px;height:7px;flex:none;border-radius:50%;background:currentColor}
1258
+ .dwc-panel-desc{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,#888);text-align:left}
1259
+ .dwc-panel-actions{flex:none;display:flex;align-items:center;gap:8px;padding-top:2px}
1260
+ .dwc-panel-body{flex:1;min-height:0;overflow:auto;padding:18px 28px 28px;display:flex;flex-direction:column;gap:14px}
1261
+ .dwc-panel .dwc-channel-empty{width:100%}
1262
+ .dwc-panel .dwc-channel-pending{margin:0}
1263
+ .dwc-empty-hero{flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;text-align:center;padding:40px 24px}
1264
+ .dwc-empty-hero-icon{width:76px;height:76px;border-radius:22px;display:grid;place-items:center;background:color-mix(in srgb,var(--dsw-alias-brand-primary,#07c160) 12%,transparent);color:var(--dsw-alias-brand-primary,#07c160)}
1265
+ .dwc-empty-hero-icon svg{width:42px;height:42px;display:block}
1266
+ .dwc-empty-hero-title{margin:0;font-size:18px;line-height:26px;font-weight:600}
1267
+ .dwc-empty-hero-desc{margin:0;max-width:440px;font-size:13px;line-height:20px;color:var(--dsw-alias-label-tertiary,#888)}
1268
+ .dwc-empty-hero-add{height:40px!important;padding:0 20px!important;font-size:14px!important;margin-top:6px}
1269
+ .dwc-panel .dwc-channel-account{padding:16px 18px;gap:12px;border-radius:16px}
1270
+ .dwc-panel .dwc-channel-account-name{font-size:15px;line-height:22px}
1271
+ .dwc-panel .dwc-logo{width:36px;height:36px;border-radius:11px}
1272
+ .dwc-panel .dwc-logo svg{width:22px;height:22px;display:block}
1273
+ .dwc-channel-meta{display:flex;flex-wrap:wrap;gap:6px 18px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,#888)}
1274
+ .dwc-channel-meta strong{font-weight:600;color:var(--dsw-alias-label-secondary,#b9b9b9);word-break:break-all}
1275
+ .dwc-panel-section-title{font-size:12px;font-weight:600;line-height:18px;color:var(--dsw-alias-label-secondary,#b9b9b9);letter-spacing:.02em}
1276
+ .dwc-panel .dwc-channel-sessions{display:flex;flex-direction:column;gap:2px;border-top:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08));padding-top:10px}
1277
+ .dwc-panel .dwc-channel-session{padding:9px 10px;border-radius:10px}
1278
+ .dwc-panel .dwc-channel-session-title{font-size:13px}
1279
+ .dwc-session-channel-icon{display:inline-flex;align-items:center;justify-content:center;width:14px;height:14px;flex:none;color:var(--dsw-alias-label-tertiary,#888)}
1280
+ .dwc-session-channel-icon svg{width:14px;height:14px;display:block}
1281
+ .dwc-panel-embed-body{flex:1;min-height:0;overflow:hidden;padding:0 28px 24px;display:flex;flex-direction:column;gap:12px}
1282
+ .dwc-embed{flex:1;min-height:0;display:flex;flex-direction:column;border:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08));border-radius:16px;background:var(--dsw-alias-bg-layer-1,transparent);overflow:hidden}
1283
+ .dwc-embed-head{flex:none;display:flex;align-items:center;gap:10px;padding:10px 16px;border-bottom:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.08));background:var(--dsw-alias-bg-layer-1,transparent)}
1284
+ .dwc-embed-title{flex:1;min-width:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,#eee);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1285
+ .dwc-embed-time{flex:none;font-size:11px;color:var(--dsw-alias-label-tertiary,#888);white-space:nowrap}
1286
+ .dwc-embed-session-select{flex:none;min-width:160px;max-width:280px}
1287
+ .dwc-embed-body{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}
1288
+ .dwc-embed-body > *{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}
1289
+ `;
1290
+
1291
+ const TITLE_LINK_CSS = "@media(max-width:720px){.dwc-title-row{flex-wrap:wrap}}";
1292
+
1293
+ let styleEl = null;
1294
+ const ensureStyle = () => {
1295
+ if (styleEl && styleEl.isConnected) {
1296
+ styleEl.setAttribute("data-plugin", "@cubeai/dsh-weixin-channel");
1297
+ return;
1298
+ }
1299
+ styleEl = document.createElement("style");
1300
+ styleEl.setAttribute("data-plugin", "@cubeai/dsh-weixin-channel");
1301
+ styleEl.textContent = CSS + TITLE_LINK_CSS;
1302
+ document.head.appendChild(styleEl);
1303
+ };
1304
+
1305
+ let requestHostSessionRefresh = () => {};
1306
+ let channelSessionIds = new Set();
1307
+ let channelSessionChannels = new Map();
1308
+ let channelMembershipRevision = 0;
1309
+ const channelMembershipListeners = new Set();
1310
+ function updateChannelMembership(groups) {
1311
+ const next = new Set();
1312
+ const channels = new Map();
1313
+ for (const group of groups) {
1314
+ for (const session of group.sessions || []) {
1315
+ next.add(session.sessionId);
1316
+ channels.set(String(session.sessionId), group.id);
1317
+ }
1318
+ }
1319
+ let changed = next.size !== channelSessionIds.size || [...next].some(id => !channelSessionIds.has(id));
1320
+ if (!changed) {
1321
+ for (const [id, channel] of channels) {
1322
+ if (channelSessionChannels.get(id) !== channel) { changed = true; break; }
1323
+ }
1324
+ }
1325
+ if (changed) {
1326
+ channelSessionIds = next;
1327
+ channelSessionChannels = channels;
1328
+ channelMembershipRevision += 1;
1329
+ for (const listener of channelMembershipListeners) listener();
1330
+ }
1331
+ try { requestHostSessionRefresh(changed); } catch { /* 下次频道轮询继续重试 */ }
1332
+ }
1333
+ /** IM 会话 ID 包含账号实例;接口映射兼容沿用普通 ID 的已接入会话。 */
1334
+ function channelIdOfSession(sessionId) {
1335
+ const value = String(sessionId || "");
1336
+ const mapped = channelSessionChannels.get(value);
1337
+ if (mapped) return mapped;
1338
+ if (!value.startsWith("dwc:")) return undefined;
1339
+ const rest = value.slice(3);
1340
+ const split = rest.indexOf(":");
1341
+ const instance = split > 0 ? rest.slice(0, split) : rest;
1342
+ const platform = instance.split("_", 1)[0];
1343
+ return platform || undefined;
1344
+ }
1345
+ /** 从 dwc:<account>:<kind>:... 中取出微信频道 id。 */
1346
+ function accountIdOfSession(sessionId) {
1347
+ const value = String(sessionId || "");
1348
+ if (!value.startsWith("dwc:")) return "";
1349
+ const rest = value.slice(4);
1350
+ const split = rest.indexOf(":");
1351
+ return split > 0 ? rest.slice(0, split) : "";
1352
+ }
1353
+ const isChannelSession = (id) => String(id).startsWith("dwc:") || channelSessionIds.has(String(id));
1354
+ const subscribeChannelMembership = (listener) => {
1355
+ channelMembershipListeners.add(listener);
1356
+ return () => channelMembershipListeners.delete(listener);
1357
+ };
1358
+ const channelMembershipSnapshot = () => channelMembershipRevision;
1359
+
1360
+ /** 微信会话自动认领“微信频道”页签;其他插件的页签不抢。 */
1361
+ function sidebarTabForSession(currentId, extraTabs) {
1362
+ if (typeof currentId !== "string" || currentId === "") return null;
1363
+ if (isChannelSession(currentId)) return "weixin";
1364
+ const matched = (extraTabs || []).find((item) => item && item.matchSession && item.matchSession(currentId));
1365
+ if (matched && matched.id !== "schedule" && matched.id !== "channels") return matched.id;
1366
+ if (matched) return null;
1367
+ return "tasks";
1368
+ }
1369
+
1370
+ function followSidebarTab(state, currentId, extraTabs) {
1371
+ const ready = !!(state && state.ready);
1372
+ const next = sidebarTabForSession(currentId, extraTabs);
1373
+ // 首个有效主会话只建立基线,不覆盖用户恢复的页签;空快照继续等待。
1374
+ if (!ready) return { ready: typeof currentId === "string" && currentId !== "", previousId: currentId, tab: null };
1375
+ if (typeof currentId !== "string" || currentId === "") return { ready: true, previousId: currentId, tab: null };
1376
+ if (currentId === state.previousId) return { ready: true, previousId: currentId, tab: null };
1377
+ return { ready: true, previousId: currentId, tab: next };
1378
+ }
1379
+
1380
+ function resolveSidebarTab(tab, extraTabs) {
1381
+ return tab === "tasks" || tab === "weixin" || extraTabs.some((item) => item.id === tab) ? tab : "tasks";
1382
+ }
1383
+
1384
+ function isHostNewSessionControl(label) {
1385
+ return /^(新会话|新建任务|New chat|New session)(?:\s+(?:Ctrl|Alt|Shift|Meta)(?:\+[^\s+]+)*)?$/i.test(String(label || "").trim());
1386
+ }
1387
+
1388
+ const api = (path, opts) => {
1389
+ // 管理路由复用宿主登录 Cookie,不缓存账号状态或认证错误。
1390
+ const request = Object.assign({}, opts || {}, { credentials: "same-origin", cache: "no-store" });
1391
+ const method = String(request.method || "GET").toUpperCase();
1392
+ if (method !== "GET" && method !== "HEAD") {
1393
+ request.headers = Object.assign({ "content-type": "application/json" }, request.headers || {}, { "x-dsh-weixin-channel-client": "1" });
1394
+ if (request.body === undefined) request.body = "{}";
1395
+ }
1396
+ return fetch(API_BASE + path, request).then((r) => r.json()).then((data) => {
1397
+ if (!request.signal?.aborted && data.ok && Array.isArray(data.groups)) updateChannelMembership(data.groups);
1398
+ return data;
1399
+ });
1400
+ };
1401
+
1402
+ // One request and timer for all channel consumers. Schedule only after settlement.
1403
+ function createChannelRefreshStore(load) {
1404
+ const listeners = new Set();
1405
+ let flight = null, timer = null, latest = null, failures = 0, epoch = 0;
1406
+ const visible = () => typeof document === "undefined" || document.visibilityState !== "hidden";
1407
+ const clearTimer = () => { if (timer !== null) clearTimeout(timer); timer = null; };
1408
+ const notify = (data, error) => { for (const listener of listeners) listener(data, error); };
1409
+ const schedule = () => {
1410
+ clearTimer();
1411
+ if (listeners.size && visible()) timer = setTimeout(() => {
1412
+ timer = null;
1413
+ refresh().catch(() => undefined);
1414
+ }, Math.min(4000 * 2 ** failures, 60000));
1415
+ };
1416
+ function refresh() {
1417
+ if (flight) return flight.promise;
1418
+ clearTimer();
1419
+ const current = { controller: new AbortController(), promise: null };
1420
+ flight = current;
1421
+ current.promise = Promise.resolve().then(() => {
1422
+ current.controller.signal.throwIfAborted();
1423
+ return load(current.controller.signal);
1424
+ }).then(data => {
1425
+ if (flight !== current || current.controller.signal.aborted) return data;
1426
+ failures = data.ok ? 0 : failures + 1;
1427
+ latest = { data, error: null };
1428
+ notify(data, null);
1429
+ return data;
1430
+ }).catch(error => {
1431
+ if (flight === current && !current.controller.signal.aborted) {
1432
+ failures++;
1433
+ latest = { data: null, error };
1434
+ notify(null, error);
1435
+ }
1436
+ throw error;
1437
+ }).finally(() => {
1438
+ if (flight !== current) return;
1439
+ flight = null;
1440
+ schedule();
1441
+ });
1442
+ return current.promise;
1443
+ }
1444
+ // A mutation must fetch again after any pre-mutation request has settled.
1445
+ function invalidate() {
1446
+ const generation = epoch;
1447
+ return (flight ? flight.promise.catch(() => undefined) : Promise.resolve()).then(() => {
1448
+ if (generation === epoch) return refresh();
1449
+ });
1450
+ }
1451
+ const onVisibility = () => {
1452
+ clearTimer();
1453
+ if (visible() && listeners.size) refresh().catch(() => undefined);
1454
+ };
1455
+ function subscribe(listener) {
1456
+ listeners.add(listener);
1457
+ if (latest) listener(latest.data, latest.error);
1458
+ if (listeners.size === 1) {
1459
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisibility);
1460
+ if (visible()) refresh().catch(() => undefined);
1461
+ }
1462
+ return () => {
1463
+ listeners.delete(listener);
1464
+ if (listeners.size) return;
1465
+ epoch++;
1466
+ clearTimer();
1467
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisibility);
1468
+ if (flight) flight.controller.abort();
1469
+ flight = null;
1470
+ latest = null;
1471
+ failures = 0;
1472
+ };
1473
+ }
1474
+ return { subscribe, refresh, invalidate };
1475
+ }
1476
+ const channelRefresh = createChannelRefreshStore(signal => api("/channels", { signal }));
1477
+
1478
+ const storedAccountSelection = () => {
1479
+ try { return window.localStorage.getItem(ACCOUNT_SELECTION_KEY) || ""; }
1480
+ catch { return ""; }
1481
+ };
1482
+ const rememberAccountSelection = (id) => {
1483
+ try {
1484
+ if (id) window.localStorage.setItem(ACCOUNT_SELECTION_KEY, id);
1485
+ else window.localStorage.removeItem(ACCOUNT_SELECTION_KEY);
1486
+ } catch { /* Local storage can be unavailable in restricted browser contexts. */ }
1487
+ };
1488
+
1489
+ function BrandMark({ id, compact, mono, size }) {
1490
+ const svg = (viewBox, children) => h("svg", {
1491
+ viewBox,
1492
+ width: size || undefined,
1493
+ height: size || undefined,
1494
+ xmlns: "http://www.w3.org/2000/svg",
1495
+ fill: "none",
1496
+ "aria-hidden": "true",
1497
+ }, children);
1498
+ const tone = (color) => mono ? "currentColor" : color;
1499
+ if (id === "weixin") {
1500
+ return svg("0 0 48 48", [
1501
+ h("path", { key: "wing", d: "M10 8c0 1 7 3.5 14.745 16.744 0 0 4.184-4.363 6.255-5.744 1.5-1 2.712-1.332 2.712-1.332C33.712 15.156 29.5 8 28 8z", fill: tone("#00d6b9") }),
1502
+ h("path", { key: "head", d: "M43.5 18.5c-1-.667-3.65-1.771-6.5-1.5a15 15 0 0 0-3.288.668S32.5 18 31 19c-2.07 1.38-6.255 5.744-6.255 5.744-1.428 1.397-3.05 2.732-5.245 3.756 0 0 7 3 11.5 3 5.063 0 7-3.5 7-3.5 1.5-3.305 3.5-7 5.5-9.5", fill: tone("#163c9a") }),
1503
+ h("path", { key: "body", d: "M4 17.5v17c0 1 6 5.5 15 5.5 10 0 17.05-7.705 19-12 0 0-1.937 3.5-7 3.5-4.5 0-11.5-3-11.5-3-5.117-2.239-10.03-6.577-12.906-9.117C4.974 17.953 4 17.093 4 17.5", fill: tone("#3370ff") }),
1504
+ ]);
1505
+ }
1506
+ return svg("0 0 24 24", [
1507
+ h("circle", { key: "bg", cx: 12, cy: 12, r: 12, fill: tone("#8b949e") }),
1508
+ ]);
1509
+ }
1510
+
1511
+ function Logo({ id, small }) {
1512
+ return h("div", { className: small ? "dwc-logo sm" : "dwc-logo", "data-brand": id, "aria-hidden": "true" }, h(BrandMark, { id, compact: small }));
1513
+ }
1514
+
1515
+ function isRasterQr(value) {
1516
+ return typeof value === "string" && (/^data:image\//i.test(value) || /\.(png|jpe?g|gif|webp)(\?|$)/i.test(value));
1517
+ }
1518
+
1519
+ function qrSrc(pairing) {
1520
+ if (!pairing) return "";
1521
+ if (isRasterQr(pairing.qrImage)) return pairing.qrImage;
1522
+ return "";
1523
+ }
1524
+
1525
+ const SERVER_TEXT_KEYS = new Map([
1526
+ ["未知渠道", "server.unknownChannel"], ["渠道未配置", "server.channelUnconfigured"], ["会话不存在", "server.sessionMissing"],
1527
+ ["频道不存在", "server.accountMissing"], ["频道连接失败,请查看本机日志", "server.accountConnectFailed"], ["重新连接频道失败,请查看本机日志", "server.accountReconnectFailed"],
1528
+ ["频道名称不能超过 40 个字符", "server.remarkTooLong"], ["频道名称不能包含换行或控制字符", "server.remarkControl"],
1529
+ ["请选择提供商、模型、工作区或权限", "server.selectAccountSettings"], ["请选择提供商和模型", "server.selectModel"], ["请选择工作区", "server.selectWorkspace"], ["请先添加工作区", "server.createWorkspace"], ["请选择权限", "server.selectPermission"], ["凭据不足,无法启动渠道", "server.missingCredentials"],
1530
+ ["该渠道不支持扫码绑定", "server.qrUnsupported"], ["二维码已过期", "server.qrExpired"], ["扫码未完成", "server.qrIncomplete"],
1531
+ ["未授权:请管理员在设置 → 微信频道 中批准你的访问。", "server.accessDenied"],
1532
+ ["已有微信频道,请先删除现有频道后再添加", "server.channelExists"],
1533
+ ["未连接", "account.statusNotConnected"], ["已停止", "status.stopped"], ["长连接已建立", "status.longConnection"],
1534
+ ]);
1535
+ function serverText(value, t) {
1536
+ const text = value == null ? "" : String(value);
1537
+ const key = SERVER_TEXT_KEYS.get(text);
1538
+ if (key) return t(key);
1539
+ // Server adapters return diagnostics, not locale keys. Do not leak a
1540
+ // Chinese diagnostic into an English UI; the detailed value remains in
1541
+ // the server log while the browser gets a usable localized fallback.
1542
+ if (/[\u3400-\u9fff]/.test(text) && t("settings.label") === "WeChat Channel") return t("error.detailsInLog");
1543
+ return value;
1544
+ }
1545
+ async function copyText(value) {
1546
+ const text = String(value ?? "");
1547
+ if (!text) return false;
1548
+ try {
1549
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
1550
+ await navigator.clipboard.writeText(text);
1551
+ return true;
1552
+ }
1553
+ } catch { /* fall through to the DOM fallback */ }
1554
+ try {
1555
+ const area = document.createElement("textarea");
1556
+ area.value = text;
1557
+ area.setAttribute("readonly", "");
1558
+ area.style.position = "fixed";
1559
+ area.style.opacity = "0";
1560
+ document.body.appendChild(area);
1561
+ area.select();
1562
+ const ok = typeof document.execCommand === "function" ? document.execCommand("copy") : false;
1563
+ area.remove();
1564
+ return ok;
1565
+ } catch { return false; }
1566
+ }
1567
+
1568
+ function relativeTime(value, t) {
1569
+ const ms = Date.parse(value || "");
1570
+ if (!Number.isFinite(ms)) return "";
1571
+ const diff = Math.max(0, Date.now() - ms);
1572
+ const minutes = Math.floor(diff / 60000);
1573
+ if (minutes < 1) return t("time.now");
1574
+ if (minutes < 60) return t("time.ago", { t: t("time.minutes", { n: minutes }) });
1575
+ const hours = Math.floor(minutes / 60);
1576
+ if (hours < 24) return t("time.ago", { t: t("time.hours", { n: hours }) });
1577
+ const days = Math.floor(hours / 24);
1578
+ if (days < 30) return t("time.ago", { t: t("time.days", { n: days }) });
1579
+ const months = Math.floor(days / 30);
1580
+ if (months < 12) return t("time.ago", { t: t("time.months", { n: months }) });
1581
+ return t("time.ago", { t: t("time.years", { n: Math.floor(months / 12) }) });
1582
+ }
1583
+
1584
+ function defaultChannelName(ch) {
1585
+ const count = Array.isArray(ch && ch.accounts) ? ch.accounts.length : 0;
1586
+ return `微信频道${Math.max(1, count + 1)}`;
1587
+ }
1588
+
1589
+ function channelLabel(ch, t) {
1590
+ const key = "channel." + ch.id;
1591
+ const translated = t(key);
1592
+ return translated === key ? (ch.label || ch.id) : translated;
1593
+ }
1594
+ function accountLabel(account, t) {
1595
+ if (!account || !account.autoName) return account && (account.name || account.id) || "";
1596
+ return t("account.defaultName", {
1597
+ channel: channelLabel({ id: account.platform, label: account.platform }, t),
1598
+ count: account.nameOrdinal || 1,
1599
+ });
1600
+ }
1601
+ function fieldLabel(ch, field, t) {
1602
+ const key = "field." + ch.id + "." + field.key;
1603
+ const translated = t(key);
1604
+ return translated === key ? field.label : translated;
1605
+ }
1606
+ function hintOf(ch, t) {
1607
+ const key = "qr." + ch.id;
1608
+ const translated = t(key);
1609
+ return translated === key ? t("qr.default") : translated;
1610
+ }
1611
+
1612
+ // 有 reflect 时只 probe,不能硬读未注入的官方导航服务,否则 Cordis 会挡住插件激活。
1613
+ function probeService(ctx, name) {
1614
+ if (!ctx) return undefined;
1615
+ const reflect = ctx.reflect;
1616
+ if (reflect && typeof reflect.get === "function") {
1617
+ try {
1618
+ const found = reflect.get(name);
1619
+ if (found !== undefined) return found;
1620
+ } catch { /* 未注入时不硬读 ctx[name],改走 get */ }
1621
+ }
1622
+ if (typeof ctx.get === "function") {
1623
+ try {
1624
+ const found = ctx.get(name);
1625
+ if (found !== undefined) return found;
1626
+ } catch { return undefined; }
1627
+ }
1628
+ if (reflect && typeof reflect.get === "function") return undefined;
1629
+ try { return ctx[name]; } catch { return undefined; }
1630
+ }
1631
+ // 旧宿主读 list.current;alpha.2 主视图改由 retainedBy.mainView 标记。
1632
+ function currentSessionId(state) {
1633
+ if (!state) return null;
1634
+ if (typeof state.current === "string" && state.current) return state.current;
1635
+ const byId = state.byId || {};
1636
+ const ids = Array.isArray(state.ids) && state.ids.length ? state.ids : Object.keys(byId);
1637
+ const pick = (id, row) => {
1638
+ if (!row || !row.retainedBy || (row.retainedBy.mainView ?? 0) <= 0) return null;
1639
+ const explicit = row.id && String(row.id).trim();
1640
+ return explicit || id;
1641
+ };
1642
+ for (let i = 0; i < ids.length; i++) {
1643
+ const found = pick(ids[i], byId[ids[i]]);
1644
+ if (found) return found;
1645
+ }
1646
+ for (const id in byId) {
1647
+ if (ids.indexOf(id) !== -1) continue;
1648
+ const found = pick(id, byId[id]);
1649
+ if (found) return found;
1650
+ }
1651
+ return null;
1652
+ }
1653
+ function resolveHostSessionId(sessionId, sessionById) {
1654
+ if (!sessionId) return sessionId;
1655
+ const listed = sessionById && sessionById[sessionId];
1656
+ const fromKey = listed && (listed.id || listed.sessionId);
1657
+ if (fromKey && String(fromKey).trim()) return String(fromKey).trim();
1658
+ return sessionId;
1659
+ }
1660
+
1661
+ function mainSessionModel(state) {
1662
+ const id = currentSessionId(state);
1663
+ const row = id && state && state.projectionsBySession && state.projectionsBySession[id];
1664
+ const selection = row && row.values && row.values.modelSelection;
1665
+ const next = selection && (selection.next || selection.lastUsed);
1666
+ if (!next || !next.provider || !next.model) return null;
1667
+ return { provider: next.provider, model: next.model, reasoningEffort: next.reasoningEffort || "" };
1668
+ }
1669
+ function readMainSessionModel(ctx) {
1670
+ const sessions = probeService(ctx, "sessions");
1671
+ const list = sessions && sessions.list;
1672
+ if (!list || typeof list.getSnapshot !== "function") return null;
1673
+ try { return mainSessionModel(list.getSnapshot()); } catch { return null; }
1674
+ }
1675
+ function openHostSession(ctx, id) {
1676
+ if (!id) return false;
1677
+ const uiWorkspace = (ctx && ctx.uiWorkspace) || probeService(ctx, "uiWorkspace");
1678
+ if (uiWorkspace && typeof uiWorkspace.openSession === "function") {
1679
+ uiWorkspace.openSession(id);
1680
+ return true;
1681
+ }
1682
+ // alpha.2 有 retain:旧的 sessions.open 即使还在也不会写入 mainView,点了等于没打开。
1683
+ if (ctx.sessions && typeof ctx.sessions.retain === "function") return false;
1684
+ if (ctx.sessions && typeof ctx.sessions.open === "function") {
1685
+ ctx.sessions.open(id);
1686
+ return true;
1687
+ }
1688
+ return false;
1689
+ }
1690
+ function parsePickedPath(value) {
1691
+ if (typeof value === "string" && value.trim() !== "") return value;
1692
+ if (value === null || typeof value !== "object") return undefined;
1693
+ if (value.canceled === true) return undefined;
1694
+ if (typeof value.path === "string" && value.path.trim() !== "") return value.path;
1695
+ const first = Array.isArray(value.filePaths) ? value.filePaths[0] : undefined;
1696
+ return typeof first === "string" && first.trim() !== "" ? first : undefined;
1697
+ }
1698
+ function pickHostDirectory(ctx) {
1699
+ const host = typeof globalThis !== "undefined" ? globalThis.__DSH_DIRECTORY_PICKER__ : undefined;
1700
+ if (host && typeof host.pick === "function") {
1701
+ return Promise.resolve(host.pick()).then(parsePickedPath);
1702
+ }
1703
+ const uiWorkspace = probeService(ctx, "uiWorkspace");
1704
+ if (uiWorkspace && typeof uiWorkspace.pickDirectory === "function") return Promise.resolve(uiWorkspace.pickDirectory()).then(parsePickedPath);
1705
+ const dialog = probeService(ctx, "dialog");
1706
+ if (dialog && typeof dialog.pickDirectory === "function") return Promise.resolve(dialog.pickDirectory()).then(parsePickedPath);
1707
+ if (ctx && ctx.workspaces && typeof ctx.workspaces.pickDirectory === "function") return Promise.resolve(ctx.workspaces.pickDirectory()).then(parsePickedPath);
1708
+ // 全部来源都不可用时必须显式拒绝:调用方据此提示“当前 Host 无法新增工作区”,
1709
+ // 否则点击“添加工作区…”会静默无响应(取消选择由 resolve(undefined) 表示,二者不能混淆)。
1710
+ return Promise.reject(workspacePickerUnavailable());
1711
+ }
1712
+ function workspacePickerUnavailable() {
1713
+ const error = new Error("workspace picker unavailable");
1714
+ error.code = "workspace/picker-unavailable";
1715
+ return error;
1716
+ }
1717
+ function hostWorkspaceApi(ctx) {
1718
+ return probeService(ctx, "uiWorkspace") || ctx.workspaces || {};
1719
+ }
1720
+ function archiveHostSession(ctx, id, options) {
1721
+ const api = hostWorkspaceApi(ctx);
1722
+ if (typeof api.archiveSession !== "function") return;
1723
+ return options ? api.archiveSession(id, options) : api.archiveSession(id);
1724
+ }
1725
+ function unarchiveHostSession(ctx, id) {
1726
+ const api = hostWorkspaceApi(ctx);
1727
+ if (typeof api.unarchiveSession === "function") return api.unarchiveSession(id);
1728
+ if (typeof api.restoreSession === "function") return api.restoreSession(id);
1729
+ }
1730
+ function forkHostSession(ctx, id) {
1731
+ const uiWorkspace = probeService(ctx, "uiWorkspace");
1732
+ if (uiWorkspace && typeof uiWorkspace.forkSession === "function") return Promise.resolve(uiWorkspace.forkSession(id));
1733
+ if (!ctx.sessions || typeof ctx.sessions.fork !== "function") return Promise.resolve();
1734
+ return ctx.sessions.fork({ sessionId: id, increaseTitle: true })
1735
+ .then((childId) => { openHostSession(ctx, childId); })
1736
+ .catch(() => undefined);
1737
+ }
1738
+ async function renameHostSession(ctx, sessionId, title) {
1739
+ const sessions = ctx.sessions;
1740
+ if (!sessions) throw new Error("unknown session");
1741
+ const renameBound = async (session) => {
1742
+ if (!session || typeof session.rename !== "function") throw new Error("unknown session");
1743
+ const result = await session.rename(title);
1744
+ if (result && result.ok === false) throw new Error((result.error && result.error.message) || "rename failed");
1745
+ };
1746
+ if (typeof sessions.using === "function") {
1747
+ return sessions.using(sessionId, { source: "controllerOperation" }, async (reference) => {
1748
+ if (reference && reference.ready) await reference.ready;
1749
+ return renameBound(reference && reference.binding && reference.binding.session);
1750
+ });
1751
+ }
1752
+ const existing = sessions.binding && sessions.binding(sessionId);
1753
+ if (existing && existing.session) return renameBound(existing.session);
1754
+ if (typeof sessions.retain !== "function") throw new Error("unknown session");
1755
+ const ref = sessions.retain(sessionId, { source: "controllerOperation" });
1756
+ try {
1757
+ if (ref && ref.ready) await ref.ready;
1758
+ return renameBound(ref && ref.binding && ref.binding.session);
1759
+ } finally {
1760
+ if (ref && typeof ref.release === "function") ref.release();
1761
+ }
1762
+ }
1763
+
1764
+ let openImSession = (id) => {
1765
+ try {
1766
+ if (window.__dshSessionsOpen) { window.__dshSessionsOpen(id); return true; }
1767
+ } catch { /* ignore */ }
1768
+ return false;
1769
+ };
1770
+ const tryOpenListedSession = (id, hostOpen) => {
1771
+ if (openImSession(id)) return true;
1772
+ if (typeof hostOpen !== "function") return false;
1773
+ try { hostOpen(id); return true; } catch { return false; }
1774
+ };
1775
+ const openListedSession = (id, hostOpen) => {
1776
+ if (!id) return;
1777
+ if (isChannelSession(id)) {
1778
+ api("/sessions/ensure", {
1779
+ method: "POST",
1780
+ headers: { "content-type": "application/json" },
1781
+ body: JSON.stringify({ sessionId: id }),
1782
+ }).then((data) => {
1783
+ if (!data.ok) { console.warn("[dsh-weixin-channel] 无法恢复会话", data.error || id); return; }
1784
+ const tryOpen = (left) => {
1785
+ if (openImSession(id) || left <= 0) return;
1786
+ setTimeout(() => tryOpen(left - 1), 80);
1787
+ };
1788
+ tryOpen(20);
1789
+ }).catch((error) => console.warn("[dsh-weixin-channel] 无法恢复会话", id, error));
1790
+ return;
1791
+ }
1792
+ tryOpenListedSession(id, hostOpen);
1793
+ };
1794
+
1795
+ function preferredAssistant(defaults, readModel) {
1796
+ const main = typeof readModel === "function" ? readModel() : null;
1797
+ if (main && main.provider && main.model) return main;
1798
+ const assistant = defaults && defaults.assistant;
1799
+ return assistant && assistant.provider && assistant.model ? assistant : null;
1800
+ }
1801
+ function selectableWorkspace(preferred, workspaces) {
1802
+ const items = Array.isArray(workspaces) ? workspaces : [];
1803
+ const key = (path) => {
1804
+ const value = String(path || "");
1805
+ const windows = /^[a-z]:[\\/]|^\\\\|^\/\//i.test(value);
1806
+ const normalized = (windows ? value.replace(/\\/g, "/") : value).replace(/\/+$/, "");
1807
+ return windows ? normalized.toLowerCase() : normalized;
1808
+ };
1809
+ const wanted = key(preferred);
1810
+ const matched = wanted && items.find((item) => item && key(item.path) === wanted);
1811
+ if (matched && matched.path) return matched.path;
1812
+ const first = items.find((item) => item && item.path);
1813
+ return first ? first.path : "";
1814
+ }
1815
+ function workspaceIsListed(cwd, workspaces) {
1816
+ const items = Array.isArray(workspaces) ? workspaces : [];
1817
+ const key = (path) => {
1818
+ const value = String(path || "");
1819
+ const windows = /^[a-z]:[\\/]|^\\\\|^\/\//i.test(value);
1820
+ const normalized = (windows ? value.replace(/\\/g, "/") : value).replace(/\/+$/, "");
1821
+ return windows ? normalized.toLowerCase() : normalized;
1822
+ };
1823
+ const wanted = key(cwd);
1824
+ return Boolean(wanted && items.some((item) => item && key(item.path) === wanted));
1825
+ }
1826
+ function BindModal({ ch, onClose, onConnected, catalog, permissions, agentPresets, workspaces, defaults, readMainSessionModel, createWorkspace, pickDirectory, modelT, permissionT, presetT, t = fallbackT }) {
1827
+ const hasQr = ch.kind === "qr" || ch.kind === "qr-or-credentials";
1828
+ const hasManual = false;
1829
+ const showTabs = false;
1830
+ const [tab, setTab] = useState("qr");
1831
+ const [pairing, setPairing] = useState(null);
1832
+ const [qrStarted, setQrStarted] = useState(false);
1833
+ const [draft, setDraft] = useState({});
1834
+ const [busy, setBusy] = useState(false);
1835
+ const [error, setError] = useState("");
1836
+ const [success, setSuccess] = useState("");
1837
+ const modelTouched = useRef(false);
1838
+ const workspaceTouched = useRef(false);
1839
+ const [settings, setSettings] = useState(() => {
1840
+ const assistant = preferredAssistant(defaults, readMainSessionModel);
1841
+ return {
1842
+ name: defaultChannelName(ch),
1843
+ cwd: selectableWorkspace(defaults && defaults.cwd, workspaces),
1844
+ provider: assistant && assistant.provider || "",
1845
+ model: assistant && assistant.model || "",
1846
+ reasoningEffort: assistant && assistant.reasoningEffort || "",
1847
+ permission: defaults && defaults.permission || "",
1848
+ privateAccess: "approved",
1849
+ sendMode: "queue",
1850
+ agentPreset: defaults && defaults.agentPreset || "standard",
1851
+ };
1852
+ });
1853
+ const alive = useRef(true);
1854
+ useEffect(() => {
1855
+ if (modelTouched.current) return;
1856
+ const assistant = preferredAssistant(defaults, readMainSessionModel);
1857
+ if (!assistant) return;
1858
+ setSettings((current) => current.provider === assistant.provider && current.model === assistant.model
1859
+ ? current
1860
+ : { ...current, provider: assistant.provider, model: assistant.model, reasoningEffort: assistant.reasoningEffort || "" });
1861
+ }, [defaults, readMainSessionModel]);
1862
+ useEffect(() => {
1863
+ if (workspaceTouched.current) return;
1864
+ const next = selectableWorkspace(defaults && defaults.cwd, workspaces);
1865
+ setSettings((current) => current.cwd === next ? current : { ...current, cwd: next });
1866
+ }, [defaults, workspaces]);
1867
+
1868
+ const startQr = useCallback((refresh) => {
1869
+ if (!hasQr || !workspaceIsListed(settings.cwd, workspaces)) return;
1870
+ setQrStarted(true);
1871
+ setBusy(true);
1872
+ setError("");
1873
+ setSuccess("");
1874
+ api(`/channels/${ch.id}/qr/${refresh ? "refresh" : "start"}`, {
1875
+ method: "POST",
1876
+ headers: { "content-type": "application/json" },
1877
+ body: JSON.stringify({ settings }),
1878
+ }).then((data) => {
1879
+ if (!alive.current) return;
1880
+ if (!data.ok && !data.pairing) setError(serverText(data.error, t) || t("error.qr"));
1881
+ setPairing(data.pairing || null);
1882
+ }).catch(() => { if (alive.current) setError(t("error.qr")); })
1883
+ .finally(() => { if (alive.current) setBusy(false); });
1884
+ }, [ch.id, hasQr, settings, workspaces]);
1885
+
1886
+ useEffect(() => {
1887
+ alive.current = true;
1888
+ return () => { alive.current = false; };
1889
+ }, []);
1890
+
1891
+ const finished = useRef(false);
1892
+ const onConnectedRef = useRef(onConnected);
1893
+ onConnectedRef.current = onConnected;
1894
+ const finish = (delayMs) => {
1895
+ if (finished.current) return;
1896
+ finished.current = true;
1897
+ alive.current = false;
1898
+ window.setTimeout(() => onConnectedRef.current(), delayMs);
1899
+ };
1900
+
1901
+ useEffect(() => {
1902
+ if (tab !== "qr" || !qrStarted) return undefined;
1903
+ const timer = setInterval(() => {
1904
+ api(`/channels/${ch.id}/qr/status`).then((data) => {
1905
+ if (finished.current || !alive.current || !data.ok) return;
1906
+ setPairing(data.pairing);
1907
+ if (data.pairing && data.pairing.status === "success") finish(800);
1908
+ }).catch(() => undefined);
1909
+ }, 2000);
1910
+ return () => clearInterval(timer);
1911
+ }, [tab, ch.id, qrStarted]);
1912
+
1913
+ const status = qrStarted && pairing && pairing.status;
1914
+ const saving = status === "saving";
1915
+ const close = () => {
1916
+ if (finished.current || saving) return;
1917
+ alive.current = false;
1918
+ if (hasQr) api("/channels/" + ch.id + "/qr/cancel", { method: "POST" }).catch(() => undefined);
1919
+ onClose();
1920
+ };
1921
+ const onCloseRef = useRef(onClose);
1922
+ onCloseRef.current = onClose;
1923
+ useEffect(() => {
1924
+ const onKeyDown = (event) => {
1925
+ if (modalLayers.length && modalLayers[modalLayers.length - 1].owner !== "bind") return;
1926
+ if (event.key !== "Escape") return;
1927
+ event.preventDefault();
1928
+ event.stopPropagation();
1929
+ if (typeof event.stopImmediatePropagation === "function") event.stopImmediatePropagation();
1930
+ if (saving) return;
1931
+ alive.current = false;
1932
+ if (hasQr) api("/channels/" + ch.id + "/qr/cancel", { method: "POST" }).catch(() => undefined);
1933
+ onCloseRef.current();
1934
+ };
1935
+ window.addEventListener("keydown", onKeyDown, true);
1936
+ return () => window.removeEventListener("keydown", onKeyDown, true);
1937
+ }, [hasQr, ch.id, saving]);
1938
+
1939
+ const saveManual = () => {
1940
+ if (!workspaceIsListed(settings.cwd, workspaces)) {
1941
+ setError(t("composer.workspaceRequired"));
1942
+ return;
1943
+ }
1944
+ const config = { ...draft };
1945
+ setBusy(true);
1946
+ setError("");
1947
+ setSuccess("");
1948
+ api(`/channels/${ch.id}/connect`, {
1949
+ method: "POST",
1950
+ headers: { "content-type": "application/json" },
1951
+ body: JSON.stringify({ config, settings }),
1952
+ }).then((data) => {
1953
+ if (!data.ok) setError(serverText(data.error, t) || t("error.save"));
1954
+ else {
1955
+ setSuccess(data.newIdentity ? t("bind.newIdentity") : t("bind.success"));
1956
+ finish(data.newIdentity ? 1400 : 500);
1957
+ }
1958
+ }).catch(() => setError(t("error.save"))).finally(() => setBusy(false));
1959
+ };
1960
+
1961
+ const switchTab = (next) => {
1962
+ if (saving) return;
1963
+ setTab(next);
1964
+ setError("");
1965
+ setSuccess("");
1966
+ if (next !== "qr") {
1967
+ setQrStarted(false);
1968
+ setPairing(null);
1969
+ api(`/channels/${ch.id}/qr/cancel`, { method: "POST" }).catch(() => undefined);
1970
+ }
1971
+ };
1972
+
1973
+ const src = qrStarted ? qrSrc(pairing) : "";
1974
+ const remain = qrStarted && pairing && pairing.remainingSeconds;
1975
+
1976
+ return h(Modal, {
1977
+ open: true,
1978
+ className: "dwc-bind-modal",
1979
+ title: t("bind.title", { channel: channelLabel(ch, t) }),
1980
+ width: 720,
1981
+ zIndex: 1100,
1982
+ destroyOnHidden: true,
1983
+ layerOwner: "bind",
1984
+ maskClosable: !saving,
1985
+ onCancel: close,
1986
+ footer: tab === "manual" && hasManual
1987
+ ? h("div", { className: "dwc-modal-actions" },
1988
+ hostModalButton(t("action.cancel"), close, "outline", { disabled: busy }),
1989
+ hostModalButton(busy ? t("action.saving") : t("action.confirm"), saveManual, "primary", { disabled: busy || !workspaceIsListed(settings.cwd, workspaces) }),
1990
+ )
1991
+ : null,
1992
+ },
1993
+ showTabs && h("div", {
1994
+ className: ["dwc-bind-tabs-wrap", saving ? "is-disabled" : ""].filter(Boolean).join(" "),
1995
+ "aria-disabled": saving ? "true" : undefined,
1996
+ }, h(HostSegmentedTabs, {
1997
+ className: "dwc-bind-tabs",
1998
+ label: t("bind.tabsAria"),
1999
+ value: tab,
2000
+ onChange: (next) => switchTab(next),
2001
+ items: [
2002
+ { value: "qr", id: "dwc-bind-tab-qr", panelId: "dwc-bind-panel-qr", label: t("bind.quick") },
2003
+ { value: "manual", id: "dwc-bind-tab-manual", panelId: "dwc-bind-panel-manual", label: t("bind.manual") },
2004
+ ],
2005
+ })),
2006
+ error && h(NoticeBar, { type: "error" }, error),
2007
+ success && h(NoticeBar, { type: "success" }, success),
2008
+ h("label", { className: "dwc-field dwc-channel-name-field" },
2009
+ h("span", { className: "dwc-picker-label" }, t("account.channelName")),
2010
+ h(Input, {
2011
+ type: "text",
2012
+ value: settings.name || "",
2013
+ placeholder: defaultChannelName(ch),
2014
+ onChange: (event) => setSettings((current) => ({ ...current, name: event.target.value })),
2015
+ }),
2016
+ ),
2017
+ h("div", { className: "dwc-setup-section" },
2018
+ h(AccountSettingsPicker, {
2019
+ value: settings,
2020
+ onChange: (patch) => {
2021
+ if (patch && patch.cwd !== undefined) workspaceTouched.current = true;
2022
+ if (patch && (patch.provider !== undefined || patch.model !== undefined)) modelTouched.current = true;
2023
+ setSettings((current) => ({ ...current, ...patch }));
2024
+ },
2025
+ catalog,
2026
+ permissions,
2027
+ agentPresets,
2028
+ workspaces,
2029
+ createWorkspace,
2030
+ pickDirectory,
2031
+ modelT,
2032
+ permissionT,
2033
+ presetT,
2034
+ showAutoNameNote: false,
2035
+ t,
2036
+ }),
2037
+ h(CommandPermissionSettings, { value: settings.commandPermissions, onSave: commandPermissions => setSettings(current => ({ ...current, commandPermissions })), t }),
2038
+ ),
2039
+ hasQr && h("div", showTabs ? { className: "dwc-bind-panel", id: "dwc-bind-panel-qr", role: "tabpanel", "aria-labelledby": "dwc-bind-tab-qr", hidden: tab !== "qr" } : null,
2040
+ status === "success"
2041
+ ? h(NoticeBar, { type: "success" }, t("bind.success"))
2042
+ : status === "saving"
2043
+ ? h("div", { className: "dwc-bind-status" }, t("bind.saving"))
2044
+ : src
2045
+ ? h("div", { className: "dwc-qrbox" },
2046
+ h("p", { className: "dwc-hint" }, hintOf(ch, t)),
2047
+ h("img", { src, alt: t("bind.qrAlt", { channel: channelLabel(ch, t) }) }),
2048
+ remain > 0 && h("p", { className: "dwc-hint" }, t("bind.expire", { time: Math.floor(remain / 60) + ":" + String(remain % 60).padStart(2, "0") })),
2049
+ status === "scanned" && h("p", { className: "dwc-hint" }, t("bind.scanned")),
2050
+ (status === "expired" || status === "failed") && h("p", { className: "dwc-error" }, serverText(pairing && pairing.error, t) || t("bind.retry")),
2051
+ hostModalButton(t("bind.refresh"), () => startQr(true), "outline", { disabled: busy }),
2052
+ )
2053
+ : h("div", { className: "dwc-bind-ready" },
2054
+ h("p", { className: "dwc-hint" }, hintOf(ch, t)),
2055
+ (busy || status === "starting") && h("div", { className: "dwc-bind-status" }, t("bind.generating")),
2056
+ (status === "expired" || status === "failed") && h("div", { className: "dwc-error" }, serverText(pairing && pairing.error, t) || t("bind.retry")),
2057
+ hostModalButton(busy ? t("bind.generating") : qrStarted ? t("bind.refresh") : t("action.generateQr"), () => startQr(qrStarted), "primary", { disabled: busy || !workspaceIsListed(settings.cwd, workspaces) || !settings.provider || !settings.model || !settings.permission }),
2058
+ )
2059
+ ),
2060
+ hasManual && h("div", showTabs ? { className: "dwc-bind-panel", id: "dwc-bind-panel-manual", role: "tabpanel", "aria-labelledby": "dwc-bind-tab-manual", hidden: tab !== "manual" } : null,
2061
+ ...ch.fields.filter((f) => !f.settingsOnly).map((f) => h("label", { key: f.key, className: "dwc-field" },
2062
+ fieldLabel(ch, f, t),
2063
+ h(Input, {
2064
+ type: f.secret ? "password" : "text",
2065
+ value: draft[f.key] || "",
2066
+ placeholder: fieldLabel(ch, f, t),
2067
+ onChange: (e) => setDraft({ ...draft, [f.key]: e.target.value }),
2068
+ }),
2069
+ )),
2070
+ ),
2071
+ );
2072
+ }
2073
+
2074
+ const BUILT_IN_PERMISSION_LABELS = new Map([
2075
+ ["read-only", ["permission.readOnly", "Read Only"]],
2076
+ ["workspace-write", ["permission.workspaceWrite", "Workspace Write"]],
2077
+ ["danger-full-access", ["permission.fullAccess", "Full access"]],
2078
+ ]);
2079
+
2080
+ function permissionLabel(option, t) {
2081
+ const builtIn = BUILT_IN_PERMISSION_LABELS.get(option.value);
2082
+ if (builtIn && (option.name === option.value || option.name === builtIn[1])) return t(builtIn[0]);
2083
+ return option.name || option.value;
2084
+ }
2085
+
2086
+ // 与宿主 settings.agentPreset 一致:内置预设没有自报名称时走官方词条。
2087
+ const BUILT_IN_PRESET_KEYS = {
2088
+ standard: { name: "presetStandardName", description: "presetStandardDescription" },
2089
+ ptc: { name: "presetPtcName", description: "presetPtcDescription" },
2090
+ minimal: { name: "presetMinimalName", description: "presetMinimalDescription" },
2091
+ cordis: { name: "presetCordisName", description: "presetCordisDescription" },
2092
+ };
2093
+ function presetDisplayText(preset, presetT) {
2094
+ const keys = BUILT_IN_PRESET_KEYS[preset.id];
2095
+ if (keys && (preset.name === undefined || preset.name === "" || preset.name === preset.id)) {
2096
+ return { name: presetT(keys.name), description: presetT(keys.description) };
2097
+ }
2098
+ return { name: preset.name || preset.id, description: preset.description };
2099
+ }
2100
+ function PlusIcon() {
2101
+ return h(IconPlusOutline, { size: 14 });
2102
+ }
2103
+
2104
+ function formatProviderLabel(provider, defaultLabel, modelT) {
2105
+ if (provider === "deepseek-account") {
2106
+ const localized = modelT("provider.account");
2107
+ if (localized && localized !== "provider.account") return localized;
2108
+ }
2109
+ return defaultLabel;
2110
+ }
2111
+
2112
+ function orderProviders(left, right) {
2113
+ const leftRank = left === "deepseek-account" ? 0 : left === "deepseek-official" ? 1 : 2;
2114
+ const rightRank = right === "deepseek-account" ? 0 : right === "deepseek-official" ? 1 : 2;
2115
+ return leftRank - rightRank;
2116
+ }
2117
+
2118
+ function renderModelOptionLabel(item) {
2119
+ const isOfficialFlash = (item.provider === "deepseek-account" || item.provider === "deepseek-official") && item.model === "deepseek-flash";
2120
+ if (!isOfficialFlash) return item.label;
2121
+ return React.createElement("span", { style: { display: "inline-flex", alignItems: "center", gap: 6 } },
2122
+ React.createElement("span", null, item.label),
2123
+ React.createElement(Tag, { color: "info" }, "1017")
2124
+ );
2125
+ }
2126
+
2127
+ function AccountSettingsPicker(props) {
2128
+ const t = props.t || fallbackT;
2129
+ const modelT = props.modelT || ((key) => key);
2130
+ const permissionT = props.permissionT || ((key) => key);
2131
+ const presetT = props.presetT || ((key) => key);
2132
+ const value = props.value || {};
2133
+ const [addBusy, setAddBusy] = useState(false);
2134
+ const [hint, setHint] = useState("");
2135
+ const [confirmingFullAccess, setConfirmingFullAccess] = useState(false);
2136
+ const [fullAccessAcknowledged, setFullAccessAcknowledged] = useState(false);
2137
+ const items = props.workspaces || [];
2138
+ const providers = props.catalog || [];
2139
+ const permissions = props.permissions || [];
2140
+ const provider = value.provider || (value.assistant && value.assistant.provider) || "";
2141
+ const model = value.model || (value.assistant && value.assistant.model) || "";
2142
+ const effort = value.reasoningEffort || (value.assistant && value.assistant.reasoningEffort) || "";
2143
+ const cwd = value.cwd || "";
2144
+ const permission = value.permission || "";
2145
+ const privateAccess = value.privateAccess === "all" ? "all" : "approved";
2146
+ const sendMode = value.sendMode === "steer" ? "steer" : "queue";
2147
+ const workspace = items.find((item) => item.path === cwd);
2148
+ const modelGroups = providers.map((item) => {
2149
+ const providerName = formatProviderLabel(item.id, item.name || item.id, modelT);
2150
+ return {
2151
+ id: item.id,
2152
+ name: providerName,
2153
+ models: (item.models || []).map((entry) => ({
2154
+ value: item.id + "::" + entry.id,
2155
+ provider: item.id,
2156
+ providerName: providerName,
2157
+ model: entry.id,
2158
+ label: entry.name || entry.id,
2159
+ description: entry.description,
2160
+ reasoning: entry.reasoning,
2161
+ })),
2162
+ };
2163
+ }).filter((item) => item.models.length > 0).sort((left, right) => orderProviders(left.id, right.id));
2164
+ const models = modelGroups.flatMap((item) => item.models);
2165
+ const currentModel = models.find((item) => item.provider === provider && item.model === model);
2166
+ const reasoning = currentModel && currentModel.reasoning;
2167
+ const effectiveEffort = effort || (reasoning && reasoning.defaultEffort) || "";
2168
+ const efforts = reasoning
2169
+ ? [
2170
+ ...(reasoning.defaultEffort ? [] : [{ id: "", name: modelT("effort.providerDefault") }]),
2171
+ ...((reasoning.efforts || []).map((item) => ({ id: item.id, name: item.name || item.id, description: item.description }))),
2172
+ ]
2173
+ : [];
2174
+ const effortLabel = reasoning
2175
+ ? ((efforts.find((item) => item.id === effectiveEffort) || {}).name || effectiveEffort || modelT("effort.providerDefault"))
2176
+ : "";
2177
+ const permissionOptions = permissions.map((item) => ({ ...item, label: permissionLabel(item, t) }));
2178
+ const currentPermission = permissionOptions.find((item) => item.value === permission);
2179
+ const update = (patch) => {
2180
+ setHint("");
2181
+ if (typeof props.onChange === "function") props.onChange(patch);
2182
+ };
2183
+
2184
+ const addWorkspace = (path) => {
2185
+ const next = (path || "").trim();
2186
+ if (!next) { setHint(t("error.chooseWorkspace")); return Promise.resolve(); }
2187
+ if (typeof props.createWorkspace !== "function") { setHint(t("error.workspaceUnavailable")); return Promise.resolve(); }
2188
+ setAddBusy(true);
2189
+ return Promise.resolve(props.createWorkspace({ path: next })).then((created) => {
2190
+ const cwdPath = (created && (created.path || created.cwd)) || next;
2191
+ update({ cwd: cwdPath });
2192
+ }).catch((error) => setHint((error && error.message) || t("error.addWorkspace")))
2193
+ .finally(() => setAddBusy(false));
2194
+ };
2195
+ const onAddWorkspace = () => {
2196
+ setHint("");
2197
+ if (typeof props.pickDirectory !== "function") {
2198
+ setHint(t("error.workspaceUnavailable"));
2199
+ return Promise.resolve();
2200
+ }
2201
+ setAddBusy(true);
2202
+ return Promise.resolve()
2203
+ .then(() => props.pickDirectory())
2204
+ .then((picked) => {
2205
+ if (typeof picked === "string" && picked.trim()) {
2206
+ return addWorkspace(picked);
2207
+ }
2208
+ })
2209
+ .catch((error) => {
2210
+ setHint(error && error.code === "workspace/picker-unavailable"
2211
+ ? t("error.workspaceUnavailable")
2212
+ : (error && error.message) || t("error.addWorkspace"));
2213
+ })
2214
+ .finally(() => {
2215
+ setAddBusy(false);
2216
+ });
2217
+ };
2218
+ const selectPermission = (next) => {
2219
+ if (next === permission) return;
2220
+ if (next === "danger-full-access") {
2221
+ setFullAccessAcknowledged(false);
2222
+ setConfirmingFullAccess(true);
2223
+ return;
2224
+ }
2225
+ update({ permission: next });
2226
+ };
2227
+ const field = (key, label, picker, wide) => h("div", { key, className: "dwc-picker-field" + (wide ? " wide" : "") },
2228
+ h("span", { className: "dwc-picker-label" }, label),
2229
+ picker,
2230
+ );
2231
+
2232
+ return h("div", { className: "dwc-account-settings" + (props.compact ? " compact" : "") },
2233
+ field("workspace", props.workspaceLabel || t("account.workspace"), items.length === 0
2234
+ ? h("div", null,
2235
+ h(Button, { variant: "primary", icon: h(PlusIcon), disabled: addBusy, onClick: onAddWorkspace }, t("composer.addWorkspace")),
2236
+ h("div", { className: "dwc-picker-note warning" }, t("composer.workspaceRequired")),
2237
+ )
2238
+ : h(Select, {
2239
+ className: "dwc-account-picker dwc-workspace-picker",
2240
+ value: cwd || undefined,
2241
+ placeholder: t("account.selectWorkspace"),
2242
+ "aria-label": props.workspaceLabel || t("account.workspace"),
2243
+ popupMatchSelectWidth: false,
2244
+ options: items.map((item) => ({ value: item.path, label: item.title || item.path })),
2245
+ footer: [{ value: "add-workspace", label: t("composer.addWorkspace"), disabled: addBusy }],
2246
+ onFooter: () => { onAddWorkspace(); },
2247
+ notFoundContent: t("composer.noWorkspaces"),
2248
+ onChange: (next) => update({ cwd: next }),
2249
+ })),
2250
+ field("agentPreset", presetT("nav"), h(Select, {
2251
+ className: "dwc-account-picker",
2252
+ value: value.agentPreset || undefined,
2253
+ "aria-label": presetT("nav"),
2254
+ options: (props.agentPresets || []).map((item) => {
2255
+ const copy = presetDisplayText(item, presetT);
2256
+ return {
2257
+ value: item.id,
2258
+ label: copy.name,
2259
+ disabled: !!item.broken,
2260
+ title: item.broken ? t("account.presetUnavailable") : copy.description,
2261
+ };
2262
+ }),
2263
+ onChange: (next) => update({ agentPreset: next }),
2264
+ })),
2265
+ h("div", { key: "model-effort", className: "dwc-model-effort" },
2266
+ field("model", modelT("menu.model"), h(Select, {
2267
+ className: "dwc-account-picker dwc-model-select",
2268
+ value: currentModel ? currentModel.value : undefined,
2269
+ placeholder: t("account.selectModel"),
2270
+ title: currentModel && currentModel.label,
2271
+ "aria-label": modelT("trigger.selectAria"),
2272
+ popupMatchSelectWidth: false,
2273
+ options: modelGroups.map((group) => ({
2274
+ label: group.name,
2275
+ options: group.models.map((item) => ({ value: item.value, label: renderModelOptionLabel(item) })),
2276
+ })),
2277
+ notFoundContent: modelT("empty.models"),
2278
+ onChange: (next) => {
2279
+ const item = models.find((entry) => entry.value === next);
2280
+ if (!item) return;
2281
+ update({ provider: item.provider, model: item.model, reasoningEffort: (item.reasoning && item.reasoning.defaultEffort) || "" });
2282
+ },
2283
+ })),
2284
+ reasoning && field("effort", modelT("menu.effort"), h(Select, {
2285
+ className: "dwc-account-picker",
2286
+ value: effectiveEffort,
2287
+ "aria-label": modelT("menu.effort"),
2288
+ options: efforts.map((item) => ({ value: item.id, label: item.name })),
2289
+ onChange: (next) => update({ provider, model, reasoningEffort: next }),
2290
+ })),
2291
+ ),
2292
+ field("permission", t("composer.permission"), h(Select, {
2293
+ className: "dwc-account-picker",
2294
+ value: permission || undefined,
2295
+ placeholder: t("account.selectPermission"),
2296
+ "aria-label": t("composer.permission"),
2297
+ options: permissionOptions.map((item) => ({ value: item.value, label: item.label })),
2298
+ onChange: selectPermission,
2299
+ })),
2300
+ field("private", t("account.privateAccess"), h(Select, {
2301
+ className: "dwc-account-picker",
2302
+ value: privateAccess,
2303
+ "aria-label": t("account.privateAccess"),
2304
+ options: [
2305
+ { value: "approved", label: t("account.privateApproved") },
2306
+ { value: "all", label: t("account.privateAll") },
2307
+ ],
2308
+ onChange: (next) => update({ privateAccess: next }),
2309
+ })),
2310
+ field("sendMode", t("account.sendMode"), h(Select, {
2311
+ className: "dwc-account-picker",
2312
+ value: sendMode,
2313
+ "aria-label": t("account.sendMode"),
2314
+ options: [
2315
+ { value: "queue", label: t("account.sendQueue") },
2316
+ { value: "steer", label: t("account.sendSteer") },
2317
+ ],
2318
+ onChange: (next) => update({ sendMode: next }),
2319
+ })),
2320
+ h("div", { className: "dwc-picker-note" }, t("account.presetNote")),
2321
+ sendMode === "steer" && h("div", { className: "dwc-picker-note" }, t("account.sendSteerNote")),
2322
+ privateAccess === "all" && h("div", { className: "dwc-picker-note warning" }, t("settings.publicChatNotice")),
2323
+ hint && h("div", { className: "dwc-picker-note" }, hint),
2324
+ props.showAutoNameNote && h("div", { className: "dwc-picker-note" }, t("account.autoNameNote")),
2325
+ h(Modal, {
2326
+ open: confirmingFullAccess,
2327
+ layerOwner: "full-access",
2328
+ title: permissionT("confirm.title"),
2329
+ keyboard: false,
2330
+ maskClosable: false,
2331
+ okText: permissionT("confirm.enable"),
2332
+ cancelText: permissionT("confirm.cancel"),
2333
+ okButtonProps: { disabled: !fullAccessAcknowledged },
2334
+ onCancel: () => { setFullAccessAcknowledged(false); setConfirmingFullAccess(false); },
2335
+ onOk: () => {
2336
+ if (!fullAccessAcknowledged) return;
2337
+ update({ permission: "danger-full-access" });
2338
+ setFullAccessAcknowledged(false);
2339
+ setConfirmingFullAccess(false);
2340
+ },
2341
+ },
2342
+ h("p", null, permissionT("confirm.description")),
2343
+ h(Checkbox, { checked: fullAccessAcknowledged, onChange: (event) => setFullAccessAcknowledged(event.target.checked) }, permissionT("confirm.acknowledge")),
2344
+ ),
2345
+ );
2346
+ }
2347
+
2348
+ // 与账号配置共用两列网格和 Ant 下拉,私聊与群聊分别保存。
2349
+ function CommandPermissionSettings({ value, onSave, t }) {
2350
+ const policy = value || { dm: { enabled: true, users: [] }, group: { enabled: true, users: [] } };
2351
+ return h("div", { className: "dwc-command-permissions dwc-account-settings" },
2352
+ ...["dm", "group"].map(kind => h("div", { key: kind, className: "dwc-picker-field" },
2353
+ h("span", { className: "dwc-picker-label" }, t("command." + kind)),
2354
+ h(Select, {
2355
+ className: "dwc-account-picker",
2356
+ value: policy[kind].enabled ? "on" : "off",
2357
+ "aria-label": t("command." + kind),
2358
+ options: [
2359
+ { value: "on", label: t("command.enabled") },
2360
+ { value: "off", label: t("command.disabled") },
2361
+ ],
2362
+ onChange: (next) => onSave({ dm: { enabled: policy.dm.enabled, users: [] }, group: { enabled: policy.group.enabled, users: [] }, [kind]: { enabled: next === "on", users: [] } }),
2363
+ }))));
2364
+ }
2365
+
2366
+ function AccountConnectionCheck({ account, t }) {
2367
+ const diagnostics = account.diagnostics;
2368
+ return h("div", { className: "dwc-connection-check", role: "status", "aria-live": "polite" },
2369
+ h("strong", null, t("diagnostic.title")),
2370
+ h("div", null, t("connection.checkedAt") + ": ", h("time", { dateTime: diagnostics.checkedAt }, new Date(diagnostics.checkedAt).toLocaleString(t("settings.label") === "WeChat Channel" ? "en-US" : "zh-CN"))),
2371
+ diagnostics.checks.map(item => h("div", { className: "dwc-diagnostic-item", key: item.id },
2372
+ h("div", { className: "dwc-diagnostic-head" },
2373
+ h("strong", null, t("diagnostic." + item.id)),
2374
+ h(Tag, { color: item.status === "passed" ? "success" : item.status === "failed" ? "error" : "warning" }, t("diagnostic." + item.status)),
2375
+ ),
2376
+ h("div", null, t("diagnostic." + item.reason)),
2377
+ h("small", null, [item.durationMs == null ? null : item.durationMs + " ms", item.httpStatus == null ? null : "HTTP " + item.httpStatus, item.platformCode == null ? null : "Code " + item.platformCode].filter(Boolean).join(" · ")),
2378
+ )),
2379
+ h("div", null, t(account.receiveConfigured === true ? "connection.receiveOn" : account.receiveConfigured === false ? "connection.receiveOff" : "connection.receiveUnknown")),
2380
+ h("div", null, t("diagnostic.scope")),
2381
+ );
2382
+ }
2383
+
2384
+ function AccountInspector({ account, catalog, permissions, agentPresets, workspaces, createWorkspace, pickDirectory, modelT, permissionT, presetT, t, onAction, onSave, busy }) {
2385
+ const [modal, modalHolder] = Modal.useModal();
2386
+ const [draft, setDraft] = useState(account);
2387
+ const [note, setNote] = useState("");
2388
+ const [checkResult, setCheckResult] = useState(null);
2389
+ const [checkFailed, setCheckFailed] = useState(false);
2390
+ const [checking, setChecking] = useState(false);
2391
+ const [checkOpen, setCheckOpen] = useState(true);
2392
+ const checkRequest = useRef(0);
2393
+ const checkPending = useRef(false);
2394
+ useEffect(() => {
2395
+ checkRequest.current += 1;
2396
+ checkPending.current = false;
2397
+ setCheckResult(null);
2398
+ setCheckFailed(false);
2399
+ setChecking(false);
2400
+ setCheckOpen(true);
2401
+ return () => { checkRequest.current += 1; };
2402
+ }, [account.id]);
2403
+ const check = async () => {
2404
+ if (checkPending.current) return;
2405
+ checkPending.current = true;
2406
+ const request = ++checkRequest.current;
2407
+ setChecking(true);
2408
+ setCheckResult(null);
2409
+ setCheckFailed(false);
2410
+ try {
2411
+ const result = await onAction(account.id, "check");
2412
+ if (request === checkRequest.current) {
2413
+ if (result && result.account && result.diagnostics?.version === 1 && Array.isArray(result.diagnostics.checks) && result.diagnostics.checks.length) {
2414
+ setCheckResult({ ...result.account, diagnostics: result.diagnostics });
2415
+ setCheckOpen(true);
2416
+ }
2417
+ else if (result && result.account) setCheckFailed("connection.restartRequired");
2418
+ else setCheckFailed(true);
2419
+ }
2420
+ } catch {
2421
+ if (request === checkRequest.current) setCheckFailed(true);
2422
+ } finally {
2423
+ if (request === checkRequest.current) { checkPending.current = false; setChecking(false); }
2424
+ }
2425
+ };
2426
+ const saveSeq = useRef(0);
2427
+ useEffect(() => {
2428
+ saveSeq.current += 1;
2429
+ setDraft(account);
2430
+ setNote("");
2431
+ }, [account.id, account.cwd, account.permission, account.agentPreset, account.privateAccess, account.sendMode, JSON.stringify(account.commandPermissions), account.receiveEnabled, account.assistant && account.assistant.provider, account.assistant && account.assistant.model, account.assistant && account.assistant.reasoningEffort]);
2432
+ const save = (patch) => {
2433
+ const seq = ++saveSeq.current;
2434
+ const next = { ...draft, ...patch };
2435
+ setDraft(next);
2436
+ setNote("status.saving");
2437
+ const payload = {
2438
+ name: next.name,
2439
+ cwd: next.cwd,
2440
+ provider: next.assistant.provider,
2441
+ model: next.assistant.model,
2442
+ reasoningEffort: next.assistant.reasoningEffort || null,
2443
+ permission: next.permission,
2444
+ privateAccess: next.privateAccess,
2445
+ sendMode: next.sendMode,
2446
+ agentPreset: next.agentPreset,
2447
+ commandPermissions: next.commandPermissions,
2448
+ };
2449
+ return onSave(account.id, payload).then((ok) => {
2450
+ if (seq === saveSeq.current) setNote(ok ? "status.saved" : "error.save");
2451
+ return ok;
2452
+ });
2453
+ };
2454
+ const applySettings = (patch) => {
2455
+ const hasAssistant = Object.prototype.hasOwnProperty.call(patch, "provider") || Object.prototype.hasOwnProperty.call(patch, "model") || Object.prototype.hasOwnProperty.call(patch, "reasoningEffort");
2456
+ if (!hasAssistant) return save(patch);
2457
+ const assistant = {
2458
+ ...(draft.assistant || {}),
2459
+ ...(Object.prototype.hasOwnProperty.call(patch, "provider") ? { provider: patch.provider } : {}),
2460
+ ...(Object.prototype.hasOwnProperty.call(patch, "model") ? { model: patch.model } : {}),
2461
+ ...(Object.prototype.hasOwnProperty.call(patch, "reasoningEffort") ? { reasoningEffort: patch.reasoningEffort || undefined } : {}),
2462
+ };
2463
+ return save({ assistant });
2464
+ };
2465
+ return h("div", { className: "dwc-inspector" },
2466
+ modalHolder,
2467
+ h("div", { className: "dwc-inspector-head" },
2468
+ h(Logo, { id: account.platform }),
2469
+ h("div", { className: "dwc-inspector-head-copy" },
2470
+ h("div", { className: "dwc-inspector-title-row" },
2471
+ h("h3", { className: "dwc-inspector-title" }, accountLabel(account, t)),
2472
+ h("div", { className: account.connectionState === "connected" ? "dwc-inspector-status ok" : "dwc-inspector-status" }, h(Tag, {
2473
+ color: account.receiveConfigured === false ? "warning" : account.connectionState === "connected" ? "success" : "warning",
2474
+ bordered: false,
2475
+ }, t(account.receiveConfigured === false ? "connection.paused" : "connection." + (account.connectionState || "unknown")))),
2476
+ ),
2477
+ ),
2478
+ ),
2479
+ h("div", { className: "dwc-form" },
2480
+ h("div", { className: "dwc-picker-field" },
2481
+ h("span", { className: "dwc-picker-label" }, t("account.remark")),
2482
+ h(AccountRemarkEditor, { account, t, always: true, disabled: Boolean(busy), onSave: (name) => save({ name }) }),
2483
+ ),
2484
+ h(AccountSettingsPicker, {
2485
+ value: draft,
2486
+ onChange: applySettings,
2487
+ catalog,
2488
+ permissions,
2489
+ agentPresets,
2490
+ workspaces,
2491
+ createWorkspace,
2492
+ pickDirectory,
2493
+ modelT,
2494
+ permissionT,
2495
+ presetT,
2496
+ workspaceLabel: t("account.currentWorkspace"),
2497
+ t,
2498
+ }),
2499
+ h(CommandPermissionSettings, { value: draft.commandPermissions, onSave: commandPermissions => save({ commandPermissions }), t }),
2500
+ note && h("div", { className: note === "status.saved" ? "dwc-save-note ok" : "dwc-save-note" }, t(note)),
2501
+ h("div", { className: "dwc-inspector-actions" },
2502
+ h(Button, { variant: "outline", disabled: Boolean(busy) || checking, onClick: check }, t(checking ? "connection.checking" : "action.checkConnection")),
2503
+ h(Button, { variant: "outline", disabled: Boolean(busy) || checking, onClick: () => { setCheckResult(null); return onAction(account.id, "reconnect"); } }, t("action.reconnectAccount")),
2504
+ h(Button, { variant: "outline", danger: true, disabled: Boolean(busy) || checking, onClick: () => {
2505
+ modal.confirm({
2506
+ title: t("action.removeAccount"),
2507
+ description: t("account.removeConfirm"),
2508
+ okText: t("action.removeAccount"),
2509
+ cancelText: t("action.cancel"),
2510
+ okButtonProps: { danger: true },
2511
+ onOk: () => onAction(account.id, "remove"),
2512
+ });
2513
+ } }, t("action.removeAccount")),
2514
+ ),
2515
+ checkResult && h("div", { className: "dwc-check-section" },
2516
+ h("div", { className: "dwc-check-head" },
2517
+ h("span", { className: "dwc-check-title" }, t("connection.diagnostics")),
2518
+ h(Button, {
2519
+ size: "sm",
2520
+ variant: "ghost",
2521
+ className: "dwc-check-toggle",
2522
+ icon: h(checkOpen ? IconChevronDownOutline : IconChevronRightOutline, { size: 13 }),
2523
+ onClick: () => setCheckOpen((open) => !open),
2524
+ }, t(checkOpen ? "action.collapse" : "action.expand")),
2525
+ ),
2526
+ checkOpen && h(AccountConnectionCheck, { account: checkResult, t }),
2527
+ ),
2528
+ checkFailed && h(NoticeBar, { type: "error", role: "alert" }, t(typeof checkFailed === "string" ? checkFailed : "connection.checkFailed")),
2529
+ ),
2530
+ );
2531
+ }
2532
+
2533
+ function AccountRemarkEditor(props) {
2534
+ const account = props.account;
2535
+ const t = props.t;
2536
+ const display = accountLabel(account, t);
2537
+ const stored = account.autoName ? "" : (account.name || "");
2538
+ const [draft, setDraft] = useState(stored);
2539
+ const [editing, setEditing] = useState(Boolean(props.always));
2540
+ const skipCommit = useRef(false);
2541
+ useEffect(() => {
2542
+ setDraft(account.autoName ? "" : (account.name || ""));
2543
+ if (!props.always) setEditing(false);
2544
+ }, [account.id, account.name, account.autoName, props.always]);
2545
+ const commit = () => {
2546
+ if (skipCommit.current) {
2547
+ skipCommit.current = false;
2548
+ return;
2549
+ }
2550
+ const next = draft.trim();
2551
+ const current = account.autoName ? "" : (account.name || "");
2552
+ if (next === current) {
2553
+ if (!props.always) setEditing(false);
2554
+ return;
2555
+ }
2556
+ Promise.resolve(props.onSave(next)).then((ok) => {
2557
+ if (!ok) setDraft(current);
2558
+ if (!props.always) setEditing(false);
2559
+ });
2560
+ };
2561
+ if (!props.always && !editing) {
2562
+ return h("button", {
2563
+ type: "button",
2564
+ className: "dwc-account-name dwc-account-rename-button",
2565
+ title: t("account.rename"),
2566
+ "aria-label": display + " · " + t("account.rename"),
2567
+ disabled: Boolean(props.disabled),
2568
+ onClick: (event) => { event.stopPropagation(); setEditing(true); },
2569
+ }, display);
2570
+ }
2571
+ return h("input", {
2572
+ type: "text",
2573
+ className: props.always ? "dwc-account-remark-input" : "dwc-account-rename",
2574
+ autoFocus: !props.always,
2575
+ maxLength: 40,
2576
+ value: draft,
2577
+ placeholder: display,
2578
+ "aria-label": t("account.remark"),
2579
+ disabled: Boolean(props.disabled),
2580
+ onClick: (event) => event.stopPropagation(),
2581
+ onMouseDown: (event) => event.stopPropagation(),
2582
+ onChange: (event) => setDraft(event.target.value),
2583
+ onBlur: commit,
2584
+ onKeyDown: (event) => {
2585
+ if (event.key === "Enter") { event.preventDefault(); event.currentTarget.blur(); }
2586
+ if (event.key === "Escape" && !props.always) {
2587
+ event.preventDefault();
2588
+ event.stopPropagation();
2589
+ skipCommit.current = true;
2590
+ setDraft(stored);
2591
+ setEditing(false);
2592
+ }
2593
+ },
2594
+ });
2595
+ }
2596
+
2597
+ function WeixinRemoteModelSelect({ sessionId, t }) {
2598
+ const accountId = accountIdOfSession(sessionId);
2599
+ const [accounts, setAccounts] = useState([]);
2600
+ useEffect(() => channelRefresh.subscribe((data) => {
2601
+ if (!data || !data.ok) return;
2602
+ setAccounts((data.channels || []).flatMap((channel) => channel.accounts || []));
2603
+ }), []);
2604
+ if (!accountId) return h("span", { className: "dwc-remote-model-missing" }, t("composer.modelUnavailable"));
2605
+ const account = accounts.find((item) => item.id === accountId);
2606
+ if (!account) return h("span", { className: "dwc-remote-model-missing" }, t("composer.modelLoading"));
2607
+ const assistant = account.assistant || {};
2608
+ const label = assistant.provider && assistant.model
2609
+ ? String(assistant.provider) + " / " + String(assistant.model)
2610
+ : "";
2611
+ if (!label) return h("span", { className: "dwc-remote-model-missing" }, t("composer.modelUnavailable"));
2612
+ return h("div", { className: "dwc-remote-model", title: t("composer.modelReadOnly") },
2613
+ h("span", { className: "dwc-remote-model-label" }, t("composer.model")),
2614
+ h("span", { className: "dwc-remote-model-value" }, label),
2615
+ );
2616
+ }
2617
+
2618
+ function WeixinStopButton({ ctx, sessionId, useSession, t }) {
2619
+ const running = useSession((state) => Boolean(state && state.running));
2620
+ const [modal, modalHolder] = Modal.useModal();
2621
+ if (!running) return null;
2622
+ const cancel = async () => {
2623
+ const scoped = ctx && ctx.sessions && typeof ctx.sessions.scope === "function"
2624
+ ? ctx.sessions.scope(sessionId)
2625
+ : undefined;
2626
+ const conversation = scoped && typeof scoped.get === "function"
2627
+ ? scoped.get("conversation")
2628
+ : undefined;
2629
+ if (conversation && typeof conversation.cancel === "function") {
2630
+ await conversation.cancel();
2631
+ return;
2632
+ }
2633
+ if (ctx && ctx.sessions && typeof ctx.sessions.cancel === "function") {
2634
+ await ctx.sessions.cancel(sessionId);
2635
+ return;
2636
+ }
2637
+ throw new Error("session cancel unavailable");
2638
+ };
2639
+ const requestStop = () => {
2640
+ modal.confirm({
2641
+ title: t("composer.stopTitle"),
2642
+ description: t("composer.stopDescription"),
2643
+ okText: t("composer.stopConfirm"),
2644
+ cancelText: t("action.cancel"),
2645
+ okButtonProps: { danger: true },
2646
+ onOk: async () => {
2647
+ try {
2648
+ await cancel();
2649
+ } catch (error) {
2650
+ console.warn("[dsh-weixin-channel] 无法停止推理", error);
2651
+ }
2652
+ },
2653
+ });
2654
+ };
2655
+ return h(React.Fragment, null,
2656
+ modalHolder,
2657
+ h(Button, {
2658
+ size: "sm",
2659
+ variant: "outline",
2660
+ className: "dwc-remote-stop",
2661
+ icon: h(IconStopFill, { size: 12 }),
2662
+ "aria-label": t("composer.stopConfirm"),
2663
+ title: t("composer.stopConfirm"),
2664
+ onClick: requestStop,
2665
+ }),
2666
+ );
2667
+ }
2668
+
2669
+ function WeixinComposerGuard(props) {
2670
+ const t = props.t || fallbackT;
2671
+ return h("div", { className: "dwc-remote-composer", "data-dwc-composer-guard": "1", role: "group", "aria-label": t("composer.remoteTitle") },
2672
+ h("div", { className: "dwc-remote-composer-card" },
2673
+ h("div", { className: "dwc-remote-composer-icon", "aria-hidden": "true" }, h(BrandMark, { id: "weixin", compact: true, mono: true })),
2674
+ h("div", { className: "dwc-remote-composer-copy" },
2675
+ h("div", { className: "dwc-remote-composer-title" }, t("composer.remoteTitle")),
2676
+ h("div", { className: "dwc-remote-composer-hint" }, t("composer.remoteHint")),
2677
+ ),
2678
+ h(WeixinRemoteModelSelect, { sessionId: props.sessionId, t }),
2679
+ typeof props.useSession === "function"
2680
+ ? h(WeixinStopButton, { ctx: props.ctx, sessionId: props.sessionId, useSession: props.useSession, t })
2681
+ : null,
2682
+ ),
2683
+ );
2684
+ }
2685
+
2686
+ const PANEL_ID = "weixin-channel";
2687
+ const EMBED_SLOT = "weixin-channel.conversation";
2688
+
2689
+ function EmbeddedChatView({ renderSlot }) {
2690
+ return renderSlot("conversation.session", { view: "chat" });
2691
+ }
2692
+
2693
+ function EmbeddedWeixinConversation({ sessionId, renderFactorySlot }) {
2694
+ if (sessionId === undefined) return null;
2695
+ if (typeof renderFactorySlot !== "function") return null;
2696
+ return renderFactorySlot("conversation.content", {
2697
+ variant: "embedded",
2698
+ phase: "active",
2699
+ hero: false,
2700
+ }, { slots: { views: EmbeddedChatView } });
2701
+ }
2702
+
2703
+ /** 面板内嵌会话需要显式 retain;切换或卸载时释放引用。 */
2704
+ function useRetainedSession(sessions, sessionId) {
2705
+ const [state, setState] = useState({ sessionId: undefined, reference: null, ready: false });
2706
+ useEffect(() => {
2707
+ if (!sessions || typeof sessions.retain !== "function" || !sessionId) {
2708
+ setState({ sessionId, reference: null, ready: false });
2709
+ return undefined;
2710
+ }
2711
+ let cancelled = false;
2712
+ let reference;
2713
+ try {
2714
+ reference = sessions.retain(sessionId, { source: "weixin-channel" });
2715
+ } catch {
2716
+ setState({ sessionId, reference: null, ready: false });
2717
+ return undefined;
2718
+ }
2719
+ setState({ sessionId, reference, ready: false });
2720
+ Promise.resolve(reference.ready).then(() => {
2721
+ if (!cancelled) setState({ sessionId, reference, ready: true });
2722
+ }).catch(() => {
2723
+ if (!cancelled) setState({ sessionId, reference: null, ready: false });
2724
+ });
2725
+ return () => {
2726
+ cancelled = true;
2727
+ try { reference.release(); } catch { /* already released */ }
2728
+ };
2729
+ }, [sessions, sessionId]);
2730
+ if (state.sessionId !== sessionId) return { sessionId, reference: null, ready: false };
2731
+ return state;
2732
+ }
2733
+
2734
+ /** 左侧边栏全局面板图标:双气泡表示微信。 */
2735
+ function PanelGlyph({ size = 20 }) {
2736
+ return h("svg", {
2737
+ width: size,
2738
+ height: size,
2739
+ viewBox: "0 0 24 24",
2740
+ fill: "none",
2741
+ "aria-hidden": "true",
2742
+ style: { display: "block" },
2743
+ },
2744
+ h("path", {
2745
+ d: "M2.6 8.5c0-2.8 2.7-5 6-5s6 2.2 6 5-2.7 5-6 5c-.7 0-1.4-.1-2-.2l-2.6 1.4c-.4.2-.9-.2-.7-.6l.5-2c-.8-.9-1.2-2.1-1.2-3.6Z",
2746
+ fill: "currentColor",
2747
+ opacity: 0.45,
2748
+ }),
2749
+ h("path", {
2750
+ d: "M9.2 12.1c0-2.6 2.6-4.7 5.8-4.7s5.8 2.1 5.8 4.7-2.6 4.7-5.8 4.7c-.8 0-1.5-.1-2.2-.3l-2.7 1.5c-.4.2-.9-.2-.7-.6l.6-1.9c-.5-.9-.8-2-.8-3.4Z",
2751
+ fill: "currentColor",
2752
+ }),
2753
+ );
2754
+ }
2755
+
2756
+ function WeixinChannelPanel(props) {
2757
+ const t = props.t || fallbackT;
2758
+ const ctx = props.ctx;
2759
+ const [data, setData] = useState(null);
2760
+ const [catalog, setCatalog] = useState({ providers: [], permissions: [], agentPresets: [], agentPreset: "standard", assistant: null, cwd: "", permission: "" });
2761
+ const [error, setError] = useState("");
2762
+ const [loading, setLoading] = useState(true);
2763
+ const [adding, setAdding] = useState(false);
2764
+ const [settingsOpen, setSettingsOpen] = useState(false);
2765
+ const [busy, setBusy] = useState(false);
2766
+ const refresh = useCallback(() => channelRefresh.invalidate().catch(() => undefined), []);
2767
+ useEffect(() => channelRefresh.subscribe((next, failure) => {
2768
+ if (failure) {
2769
+ setError(t("error.connection"));
2770
+ setLoading(false);
2771
+ return;
2772
+ }
2773
+ if (next && next.ok) {
2774
+ setData(next);
2775
+ setError("");
2776
+ } else if (next) {
2777
+ setError(serverText(next.error, t) || t("error.load"));
2778
+ }
2779
+ setLoading(false);
2780
+ }), []);
2781
+ useEffect(() => {
2782
+ api("/assistant").then((next) => {
2783
+ if (!next.ok) return;
2784
+ setCatalog({
2785
+ providers: next.providers || [],
2786
+ permissions: next.permissions || [],
2787
+ agentPresets: next.agentPresets || [],
2788
+ agentPreset: next.agentPreset || "standard",
2789
+ assistant: next.assistant || null,
2790
+ cwd: next.cwd || "",
2791
+ permission: next.permission || "",
2792
+ });
2793
+ }).catch(() => undefined);
2794
+ }, []);
2795
+ const useWorkspacesHook = typeof props.useWorkspaces === "function" ? props.useWorkspaces : null;
2796
+ const workspaces = useWorkspacesHook ? (useWorkspacesHook((state) => (state && state.items) || []) || []) : [];
2797
+ const createWorkspace = (input) => (ctx && ctx.workspaces && typeof ctx.workspaces.create === "function"
2798
+ ? ctx.workspaces.create(input)
2799
+ : Promise.reject(new Error("workspace unavailable")));
2800
+ const pickDirectory = () => pickHostDirectory(ctx);
2801
+ const channels = (data && data.channels) || [];
2802
+ const ch = channels.find((item) => item.id === "weixin") || {
2803
+ id: "weixin", label: "微信", description: "", kind: "qr", fields: [], accounts: [],
2804
+ };
2805
+ const accounts = Array.isArray(ch.accounts) ? ch.accounts : [];
2806
+ const account = accounts[0] || null;
2807
+ const groups = (data && data.groups) || [];
2808
+ const sessions = groups.flatMap((group) => (group && group.sessions) || [])
2809
+ .filter((session) => !account || String(session.channel || "") === account.id)
2810
+ .sort((a, b) => (Date.parse(b.updatedAt || "") || 0) - (Date.parse(a.updatedAt || "") || 0));
2811
+ const [selectedSessionId, setSelectedSessionId] = useState("");
2812
+ const activeSession = sessions.find((session) => String(session.sessionId) === selectedSessionId) || sessions[0] || null;
2813
+ const attached = useRetainedSession(ctx && ctx.sessions, activeSession ? activeSession.sessionId : undefined);
2814
+ const EmbedSessionProvider = props.SessionProvider;
2815
+ const renderSlot = props.renderSlot;
2816
+ const canEmbed = Boolean(activeSession) && attached.ready && typeof EmbedSessionProvider === "function" && typeof renderSlot === "function";
2817
+ const pending = ((data && data.pending) || []).filter((item) => !account || item.channelId === account.id);
2818
+ const openSession = (sessionId) => {
2819
+ if (!sessionId) return;
2820
+ const hostOpen = props.openSession || props.open;
2821
+ let opened = false;
2822
+ if (typeof hostOpen === "function") {
2823
+ hostOpen(sessionId);
2824
+ opened = true;
2825
+ } else {
2826
+ opened = openHostSession(ctx, sessionId);
2827
+ }
2828
+ // 宿主 sidebar shell 提供的全局打开入口作为兜底。
2829
+ if (!opened && typeof window !== "undefined" && typeof window.__dshSessionsOpen === "function") {
2830
+ try { window.__dshSessionsOpen(sessionId); opened = true; } catch { /* 旧宿主没有该入口 */ }
2831
+ }
2832
+ // 全局面板不会因为打开会话而自动退出:null 才是“回到会话”的官方选择。
2833
+ const layout = (ctx && ctx.layout) || probeService(ctx, "layout");
2834
+ if (layout && typeof layout.selectPanel === "function") {
2835
+ try { layout.selectPanel(null); } catch {
2836
+ try { layout.selectPanel("conversation"); } catch { /* 旧宿主没有该面板 */ }
2837
+ }
2838
+ }
2839
+ };
2840
+ const onAction = (id, action, body) => {
2841
+ setBusy(true);
2842
+ return api("/accounts/" + id + "/" + action, {
2843
+ method: "POST",
2844
+ headers: { "content-type": "application/json" },
2845
+ body: JSON.stringify(body || {}),
2846
+ }).then((result) => {
2847
+ if (!result.ok) {
2848
+ setError(serverText(result.error, t) || t("error.action"));
2849
+ return false;
2850
+ }
2851
+ setError("");
2852
+ if (action === "remove") setSettingsOpen(false);
2853
+ refresh();
2854
+ return action === "check" ? result : true;
2855
+ }).catch(() => {
2856
+ setError(t("error.request"));
2857
+ return false;
2858
+ }).finally(() => setBusy(false));
2859
+ };
2860
+ const saveAccount = (id, body) => onAction(id, "settings", body);
2861
+ const approve = (item, allow) => onAction(item.channelId, allow ? "approve" : "deny", { userId: item.userId });
2862
+ const statusKey = account
2863
+ ? (account.receiveConfigured === false ? "connection.paused" : "connection." + (account.connectionState || "unknown"))
2864
+ : "";
2865
+ const statusTone = !account || account.receiveConfigured === false
2866
+ ? "idle"
2867
+ : account.connectionState === "connected"
2868
+ ? "success"
2869
+ : account.connectionState === "error"
2870
+ ? "error"
2871
+ : "warning";
2872
+ return h("section", { className: "dwc-panel", "aria-label": t("settings.label") },
2873
+ h("header", { className: "dwc-panel-head" },
2874
+ h("div", { className: "dwc-panel-head-copy" },
2875
+ h("h2", { className: "dwc-panel-title" },
2876
+ account
2877
+ ? [
2878
+ h("span", { key: "name", className: "dwc-panel-title-name" }, accountLabel(account, t)),
2879
+ h("span", { key: "status", className: "dwc-panel-title-status is-" + statusTone },
2880
+ h("span", { className: "dwc-panel-status-dot", "aria-hidden": "true" }),
2881
+ t(statusKey),
2882
+ ),
2883
+ ]
2884
+ : h("span", { className: "dwc-panel-title-plugin" }, t("settings.title")),
2885
+ ),
2886
+ h("p", { className: "dwc-panel-desc" }, t("settings.description")),
2887
+ ),
2888
+ account
2889
+ ? h("div", { className: "dwc-panel-actions" },
2890
+ h(Button, {
2891
+ variant: "outline",
2892
+ size: "sm",
2893
+ icon: h(IconSettingsOutline16, { size: 14 }),
2894
+ disabled: Boolean(busy),
2895
+ onClick: () => setSettingsOpen(true),
2896
+ }, t("action.settings")),
2897
+ )
2898
+ : null,
2899
+ ),
2900
+ error && h("div", { className: "dwc-panel-body" }, h(NoticeBar, { type: "error", role: "alert" }, error)),
2901
+ loading && !data
2902
+ ? h("div", { className: "dwc-panel-body" }, h("div", { className: "dwc-channel-empty" }, t("loading")))
2903
+ : !account
2904
+ ? h("div", { className: "dwc-empty-hero" },
2905
+ h("div", { className: "dwc-empty-hero-icon" }, h(BrandMark, { id: "weixin", size: 42 })),
2906
+ h("h3", { className: "dwc-empty-hero-title" }, t("channel.emptyTitle")),
2907
+ h("p", { className: "dwc-empty-hero-desc" }, t("channel.empty")),
2908
+ h(Button, {
2909
+ variant: "primary",
2910
+ className: "dwc-empty-hero-add",
2911
+ icon: h(IconPlusOutline, { size: 15 }),
2912
+ disabled: !data || busy,
2913
+ onClick: () => setAdding(true),
2914
+ }, t("action.addAccount")),
2915
+ )
2916
+ : h("div", { className: "dwc-panel-body" },
2917
+ pending.length > 0 && h("div", { className: "dwc-channel-pending", role: "region" },
2918
+ h("div", { className: "dwc-channel-pending-title" }, t("pending.notice")),
2919
+ ...pending.map((item) => h("div", { key: item.channelId + item.userId, className: "dwc-channel-pending-row" },
2920
+ h("span", { className: "dwc-channel-pending-user" }, item.username || item.userId),
2921
+ h(Button, { size: "sm", variant: "primary", onClick: () => approve(item, true) }, t("action.approve")),
2922
+ h(Button, { size: "sm", variant: "outline", danger: true, onClick: () => approve(item, false) }, t("action.deny")),
2923
+ )),
2924
+ ),
2925
+ canEmbed
2926
+ ? h("div", { className: "dwc-embed" },
2927
+ h("div", { className: "dwc-embed-head" },
2928
+ h("span", { className: "dwc-embed-title" }, activeSession.title || t("session.untitled")),
2929
+ h("span", { className: "dwc-embed-time" }, relativeTime(activeSession.updatedAt, t)),
2930
+ sessions.length > 1
2931
+ ? h(Select, {
2932
+ className: "dwc-embed-session-select",
2933
+ value: String(activeSession.sessionId),
2934
+ "aria-label": t("channel.sessions"),
2935
+ options: sessions.map((session) => ({ value: String(session.sessionId), label: session.title || t("session.untitled") })),
2936
+ onChange: (next) => setSelectedSessionId(next),
2937
+ })
2938
+ : null,
2939
+ ),
2940
+ h(EmbedSessionProvider, { session: attached.reference },
2941
+ h("div", { className: "dwc-embed-body" },
2942
+ renderSlot(EMBED_SLOT, {}))),
2943
+ )
2944
+ : sessions.length > 0
2945
+ ? h("div", { className: "dwc-channel-account" },
2946
+ h("div", { className: "dwc-panel-section-title" }, t("channel.sessions")),
2947
+ h("div", { className: "dwc-panel-sessions" },
2948
+ ...sessions.map((session) => h("button", {
2949
+ key: session.sessionId,
2950
+ type: "button",
2951
+ className: "dwc-channel-session",
2952
+ title: session.title || t("session.untitled"),
2953
+ onClick: () => openSession(session.sessionId),
2954
+ },
2955
+ h("span", { className: "dwc-channel-session-title" }, session.title || t("session.untitled")),
2956
+ h("span", { className: "dwc-channel-session-time" }, relativeTime(session.updatedAt, t)),
2957
+ )),
2958
+ ),
2959
+ )
2960
+ : h("div", { className: "dwc-channel-account" },
2961
+ h("div", { className: "dwc-panel-section-title" }, t("channel.sessions")),
2962
+ h("div", { className: "dwc-channel-account-empty" }, t("account.noSessions")),
2963
+ ),
2964
+ ),
2965
+ adding && h(BindModal, {
2966
+ ch,
2967
+ catalog: catalog.providers,
2968
+ permissions: catalog.permissions,
2969
+ agentPresets: catalog.agentPresets,
2970
+ workspaces,
2971
+ createWorkspace,
2972
+ pickDirectory,
2973
+ modelT: props.modelT,
2974
+ permissionT: props.permissionT,
2975
+ presetT: props.presetT,
2976
+ defaults: catalog,
2977
+ readMainSessionModel: props.readMainSessionModel,
2978
+ onClose: () => setAdding(false),
2979
+ onConnected: () => { setAdding(false); refresh(); },
2980
+ t,
2981
+ }),
2982
+ account && settingsOpen && h(Modal, {
2983
+ open: true,
2984
+ className: "dwc-account-modal",
2985
+ title: t("action.settings"),
2986
+ width: 760,
2987
+ zIndex: 1100,
2988
+ layerOwner: "weixin-account",
2989
+ destroyOnHidden: true,
2990
+ onCancel: () => setSettingsOpen(false),
2991
+ footer: null,
2992
+ }, h(AccountInspector, {
2993
+ account,
2994
+ busy: Boolean(busy),
2995
+ catalog: catalog.providers,
2996
+ permissions: catalog.permissions,
2997
+ agentPresets: catalog.agentPresets,
2998
+ workspaces,
2999
+ createWorkspace,
3000
+ pickDirectory,
3001
+ modelT: props.modelT,
3002
+ permissionT: props.permissionT,
3003
+ presetT: props.presetT,
3004
+ t,
3005
+ onAction,
3006
+ onSave: saveAccount,
3007
+ })),
3008
+ );
3009
+ }
3010
+
3011
+ function apply(ctx) {
3012
+ ensureStyle();
3013
+ ctx.effect(() => ctx.locale.register(DWC_LOCALE_NS, DWC_LOCALES), "weixin-channel: dictionaries");
3014
+ const t = ctx.locale.bind(DWC_LOCALE_NS);
3015
+ const permissionT = ctx.locale.bind("permission.access");
3016
+ const modelT = ctx.locale.bind("model");
3017
+ const presetT = ctx.locale.bind("settings.agentPreset");
3018
+ const subscribeLocale = (listener) => ctx.locale.subscribe(listener);
3019
+ const localeSnapshot = () => ctx.locale.getSnapshot();
3020
+ function LocalizedPanel(props) {
3021
+ useSyncExternalStore(subscribeLocale, localeSnapshot, localeSnapshot);
3022
+ return h(WeixinChannelPanel, Object.assign({}, props, {
3023
+ ctx,
3024
+ t,
3025
+ permissionT,
3026
+ modelT,
3027
+ presetT,
3028
+ readMainSessionModel: () => readMainSessionModel(ctx),
3029
+ }));
3030
+ }
3031
+ function LocalizedComposerGuard(props) {
3032
+ useSyncExternalStore(subscribeLocale, localeSnapshot, localeSnapshot);
3033
+ return h(WeixinComposerGuard, Object.assign({}, props, { t, ctx }));
3034
+ }
3035
+
3036
+ // 频道会话归属依赖宿主 session 列表;插件激活后持续刷新,避免打开会话时 composer 尚未接管。
3037
+ ctx.effect(() => {
3038
+ let pending = channelSessionIds.size > 0, flight = null, disposed = false;
3039
+ const refresh = (changed) => {
3040
+ pending = pending || changed;
3041
+ if (disposed || !pending || flight) return;
3042
+ const sessions = probeService(ctx, "sessions");
3043
+ if (!sessions || typeof sessions.refresh !== "function") return;
3044
+ const revision = channelMembershipRevision;
3045
+ flight = Promise.resolve().then(() => {
3046
+ if (disposed) return;
3047
+ return sessions.refresh();
3048
+ }).then(() => {
3049
+ if (disposed) return;
3050
+ const snapshot = sessions.list && typeof sessions.list.getSnapshot === "function" ? sessions.list.getSnapshot() : undefined;
3051
+ if (snapshot && snapshot.state === "error") return;
3052
+ if (revision === channelMembershipRevision) pending = false;
3053
+ }).catch(() => { /* 保留待处理状态,由下次渠道刷新重试 */ })
3054
+ .finally(() => { flight = null; });
3055
+ };
3056
+ requestHostSessionRefresh = refresh;
3057
+ return () => {
3058
+ disposed = true;
3059
+ if (requestHostSessionRefresh === refresh) requestHostSessionRefresh = () => {};
3060
+ };
3061
+ }, "weixin-channel: host session refresh");
3062
+ ctx.effect(() => channelRefresh.subscribe((data, error) => {
3063
+ if (error) console.warn("[dsh-weixin-channel] 无法刷新频道会话归属", error);
3064
+ }), "weixin-channel: channel membership");
3065
+
3066
+ // 1) 左侧边栏菜单项,与官方客户端类菜单项平级。
3067
+ ctx.slots.inject("sidebar.panellist", () => ctx.slots.register({
3068
+ name: "sidebar.panellist",
3069
+ id: PANEL_ID,
3070
+ order: 30,
3071
+ label: () => t("settings.label"),
3072
+ }, PanelGlyph));
3073
+
3074
+ // 2) 主界面:空状态显示“添加微信频道”,存在频道后右上角显示“设置”。
3075
+ ctx.slots.inject("main", () => ctx.slots.register({
3076
+ name: "main",
3077
+ key: PANEL_ID,
3078
+ children: {
3079
+ [EMBED_SLOT]: { kind: "single", scope: "session" },
3080
+ },
3081
+ }, LocalizedPanel));
3082
+ ctx.slots.inject(EMBED_SLOT, () => ctx.slots.register({
3083
+ name: EMBED_SLOT,
3084
+ }, EmbeddedWeixinConversation));
3085
+
3086
+ // 3) 微信会话行前显示微信品牌标。
3087
+ ctx.slots.inject("sidebar.session.row.leading", () => ctx.slots.register({
3088
+ name: "sidebar.session.row.leading",
3089
+ id: "weixin-channel-session-channel",
3090
+ order: 10,
3091
+ }, function ChannelSessionLeading({ sessionId }) {
3092
+ useSyncExternalStore(subscribeChannelMembership, channelMembershipSnapshot, channelMembershipSnapshot);
3093
+ if (!isChannelSession(sessionId)) return null;
3094
+ return h("span", { className: "dwc-session-channel-icon", "aria-hidden": "true" }, h(Logo, { id: "weixin", small: true }));
3095
+ }));
3096
+
3097
+ // 微信会话只能通过微信继续;替换宿主 composer,避免本地输入被丢弃。
3098
+ ctx.slots.inject("conversation.composer", () => ctx.slots.register({
3099
+ name: "conversation.composer",
3100
+ select: (owner) => {
3101
+ if (!owner || !isChannelSession(owner.sessionId)) return null;
3102
+ if (owner.pendingInteraction) return null;
3103
+ return true;
3104
+ },
3105
+ }, LocalizedComposerGuard));
3106
+ }
3107
+
3108
+ exports.apply = apply;
3109
+ exports.inject = inject;
3110
+ return module.exports;
3111
+ },
3112
+ });