@michengai/dsh-im-connect 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -7,7 +7,7 @@ window.__ModuleLoader__.load({
7
7
  var module = { exports: {} };
8
8
  var exports = module.exports;
9
9
  const React = require("react");
10
- const { useState, useEffect, useLayoutEffect, useCallback, useRef, useSyncExternalStore } = React;
10
+ const { useState, useEffect, useLayoutEffect, useCallback, useMemo, useRef, useSyncExternalStore } = React;
11
11
  const ReactDOM = require("react-dom");
12
12
  const primitives = typeof require === "function" ? (function () { try { return require("@deepseek-ai/dsh-client-ui-primitives"); } catch { return {}; } })() : {};
13
13
  const PrimitiveButton = primitives.Button;
@@ -28,64 +28,28 @@ window.__ModuleLoader__.load({
28
28
  }
29
29
  return function MissingHostIcon() { return null; };
30
30
  }
31
- function hostOrFallback(icon, Fallback) {
32
- return function HostOrFallback(props) {
33
- const node = icon(props);
34
- return node == null ? Fallback(props) : node;
35
- };
36
- }
37
- // 0.1.7 的 Menu 会渲染 children。更早的 Menu 只认 items。样式和列表功能不再按宿主版本分叉。
38
- function hostMenuRendersChildren() {
39
- return typeof primitives.IconEllipsisOutlineRegular === "function";
40
- }
41
- /**
42
- * 宿主 renderer 对「调用本 entry 未声明的子槽位」是直接抛 SlotOwnershipError 的,抛点在调用瞬间。
43
- * sidebar.workspaces.session.menu.item 和 row.action 都是 0.1.7 才声明的子槽位,旧宿主
44
- * (0.1.2 / 0.1.5)没有:一旦抛到宿主,宿主的槽位错误边界只会给这块画一个空的 crash div,
45
- * 整块会话列表跟着消失(Issue #13)。这里统一兜住,失败只当该槽位没有内容。
46
- */
47
- const skippedHostSlotKeys = new Set();
48
- function renderHostSlot(renderSlot, key, slotProps, options) {
49
- if (typeof renderSlot !== "function") return undefined;
50
- try {
51
- return renderSlot(key, slotProps, options);
52
- } catch (error) {
53
- if (!skippedHostSlotKeys.has(key)) {
54
- skippedHostSlotKeys.add(key);
55
- console.warn("[dsh-im-connect] 宿主未声明槽位 " + key + ",已跳过该槽位", error);
56
- }
57
- return undefined;
58
- }
59
- }
60
- const IconListPenOutline16 = pickHostIcon("IconListPenOutlineRegular", "IconListPenOutline16");
61
- const IconEditOutline16 = pickHostIcon("IconEditOutlineRegular", "IconEditOutline16");
62
- const IconBranchOutline16 = pickHostIcon("IconBranchOutlineRegular", "IconBranchOutline16");
63
- const IconArchiveOutline20 = pickHostIcon("IconArchiveOutlineRegular", "IconArchiveOutline20");
64
- const IconArchiveCheckHost = pickHostIcon("IconArchiveCheckOutlineRegular");
65
- const IconTrashOutline16 = pickHostIcon("IconTrashOutlineRegular", "IconTrashOutline16");
66
- const IconEllipsisOutline16 = pickHostIcon("IconEllipsisOutlineRegular", "IconEllipsisOutline16");
67
- const IconSearchHost = pickHostIcon("IconSearchOutlineRegular", "IconSearchOutline16");
68
- const IconCloseFillHost = pickHostIcon("IconCloseFillRegular", "IconCloseOutline16");
69
- const IconSlidersHost = pickHostIcon("IconSlidersTwoOutlineRegular", "IconSlidersOutline16");
70
31
  const IconFolderClose = pickHostIcon("IconFolderCloseRegular", "IconFolderClose16", "IconFolderClose");
71
32
  const IconClockOutline = pickHostIcon("IconClockOutlineRegular", "IconClockOutline16");
72
- const IconFlatListOutline = pickHostIcon("IconFlatListOutlineRegular");
33
+ const IconQueueOutline = pickHostIcon("IconQueueOutlineRegular");
34
+ const IconCheckOutline = pickHostIcon("IconCheckOutlineRegular");
35
+ const IconCheckCircleOutline = pickHostIcon("IconCheckCircleOutlineRegular");
36
+ const IconCloseCircleFill = pickHostIcon("IconCloseCircleFillRegular");
37
+ const IconInfoOutline = pickHostIcon("IconInfoOutlineRegular");
38
+ const IconWarningOutline = pickHostIcon("IconWarningOutlineRegular");
39
+ const IconCloseFill = pickHostIcon("IconCloseFillRegular");
40
+ const IconChevronDownOutline = pickHostIcon("IconChevronDownOutlineRegular");
41
+ const IconChevronRightOutline = pickHostIcon("IconChevronRightOutlineRegular");
42
+ const IconPlusOutline = pickHostIcon("IconPlusOutlineRegular");
43
+ const IconEditOutline = pickHostIcon("IconEditOutlineRegular");
44
+ const IconRefreshOutline = pickHostIcon("IconRefreshOutlineRegular");
45
+ const IconDownloadOutline = pickHostIcon("IconDownloadOutlineRegular");
46
+ const IconCopyOutline = pickHostIcon("IconCopyOutlineRegular");
47
+ const IconLoadingOutline = pickHostIcon("IconLoadingOutlineRegular");
73
48
  function alertIcon(type) {
74
- if (type === "success") {
75
- return React.createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14, fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round" },
76
- React.createElement("path", { d: "m3 8.5 3.5 3.5 6.5-7" })
77
- );
78
- }
79
- if (type === "error") {
80
- return React.createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14, fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round" },
81
- React.createElement("circle", { cx: 8, cy: 8, r: 6 }),
82
- React.createElement("path", { d: "m8 5v3.5M8 11.5h.01" })
83
- );
84
- }
85
- return React.createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14, fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round" },
86
- React.createElement("circle", { cx: 8, cy: 8, r: 6 }),
87
- React.createElement("path", { d: "M8 7.5v3.5M8 5h.01" })
88
- );
49
+ if (type === "success") return h(IconCheckCircleOutline, { size: 14 });
50
+ if (type === "warning") return h(IconWarningOutline, { size: 14 });
51
+ if (type === "error") return h(IconCloseCircleFill, { size: 14 });
52
+ return h(IconInfoOutline, { size: 14 });
89
53
  }
90
54
  function NoticeBar({ type = "info", icon, children, className, role, showIcon }) {
91
55
  const iconNode = icon !== undefined ? icon : (showIcon !== false ? alertIcon(type) : null);
@@ -217,9 +181,7 @@ window.__ModuleLoader__.load({
217
181
  React.createElement("div", { className: "ima-modal-header" },
218
182
  React.createElement("div", { className: "ima-modal-title" }, title),
219
183
  React.createElement("button", { type: "button", className: "ima-modal-close", "aria-label": closeLabel || "Close", onClick: handleClose },
220
- React.createElement("svg", { viewBox: "0 0 16 16", width: 14, height: 14, fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round" },
221
- React.createElement("path", { d: "m4 4 8 8M12 4 4 12" })
222
- )
184
+ h(IconCloseFill, { size: 14 })
223
185
  )
224
186
  ),
225
187
  React.createElement("div", { className: "ima-modal-body" },
@@ -380,18 +342,11 @@ window.__ModuleLoader__.load({
380
342
  onClick: () => { if (!props.disabled) setOpen((prev) => !prev); },
381
343
  },
382
344
  React.createElement("span", { className: "ima-menu-select-label" }, currentText),
383
- React.createElement("svg", {
345
+ h(IconChevronDownOutline, {
346
+ size: 12,
384
347
  className: "ima-menu-select-arrow",
385
- viewBox: "0 0 16 16",
386
- width: 12,
387
- height: 12,
388
- fill: "none",
389
- stroke: "currentColor",
390
- strokeWidth: 1.8,
391
- strokeLinecap: "round",
392
- strokeLinejoin: "round",
393
348
  style: { marginLeft: 4, transition: "transform 150ms ease", transform: open ? "rotate(180deg)" : "none" },
394
- }, React.createElement("path", { d: "m4 6 4 4 4-4" }))
349
+ })
395
350
  ),
396
351
  items: items,
397
352
  ...(footer ? { footer } : {}),
@@ -399,18 +354,11 @@ window.__ModuleLoader__.load({
399
354
  );
400
355
  }
401
356
  function createSpinner() {
402
- return React.createElement("svg", {
357
+ return h(IconLoadingOutline, {
358
+ size: 14,
403
359
  className: "ima-btn-spinner",
404
- viewBox: "0 0 16 16",
405
- width: 14,
406
- height: 14,
407
- fill: "none",
408
- stroke: "currentColor",
409
- strokeWidth: 2,
410
- strokeLinecap: "round",
411
360
  style: { marginRight: 6, display: "inline-block", verticalAlign: "-2px", animation: "ima-spin 0.8s linear infinite" },
412
- "aria-hidden": "true",
413
- }, React.createElement("path", { d: "M8 1.5a6.5 6.5 0 1 0 6.5 6.5" }));
361
+ });
414
362
  }
415
363
  function Button({ variant, type, danger, loading, block, size, shape, className, children, href, target, rel, icon, ...props }) {
416
364
  let mappedVariant = variant ?? "outline";
@@ -467,187 +415,8 @@ window.__ModuleLoader__.load({
467
415
  disabled: props.disabled || loading,
468
416
  }), content);
469
417
  }
470
- const HoverCard = primitives.HoverCard;
471
- const StateDot = primitives.StateDot;
418
+
472
419
  const IconSettingsOutline16 = pickHostIcon("IconSettingsOutlineRegular", "IconSettingsOutline16");
473
- const ARCHIVE_MANAGER_PLUGIN = "@michengai/dsh-archive-manager";
474
- function hasArchiveManagerPlugin(root) {
475
- return !!(root && typeof root.querySelector === "function" && root.querySelector('[data-plugin="' + ARCHIVE_MANAGER_PLUGIN + '"]'));
476
- }
477
- function canDeleteChannelSession(archiveManagerInstalled, deleteSession) {
478
- return archiveManagerInstalled && typeof deleteSession === "function";
479
- }
480
- function canArchiveChannelGroup(archiveManagerInstalled, archiveSession) {
481
- return archiveManagerInstalled && typeof archiveSession === "function";
482
- }
483
- function folderPath(path) {
484
- return String(path || "").replace(/\\/g, "/").replace(/\/+$/, "");
485
- }
486
- function owningParentFolder(path, candidates) {
487
- const child = folderPath(path);
488
- let owner;
489
- let length = -1;
490
- for (const parent of candidates) {
491
- const root = folderPath(parent);
492
- if (root.length > length && child !== root && child.startsWith(root + "/")) {
493
- owner = parent;
494
- length = root.length;
495
- }
496
- }
497
- return owner;
498
- }
499
- function workspaceKey(workspace) {
500
- return workspace.workspaceId || workspace.id || workspace.path || "";
501
- }
502
- /** 0.1.7 宿主的按工作区树:子目录挂到路径最长的已打开工作区下面。 */
503
- function groupChannelSessionsByWorkspaceTree(sessions, workspaces, ungroupedLabel) {
504
- const bySession = new Map();
505
- for (const workspace of workspaces || []) {
506
- for (const sessionId of workspace.sessionIds || []) bySession.set(sessionId, workspace);
507
- }
508
- const buckets = new Map();
509
- const ungrouped = [];
510
- for (const session of sessions) {
511
- const workspace = bySession.get(session.sessionId);
512
- const key = workspace ? workspaceKey(workspace) : "";
513
- if (!workspace || !key) { ungrouped.push(session); continue; }
514
- const bucket = buckets.get(key) || [];
515
- bucket.push(session);
516
- buckets.set(key, bucket);
517
- }
518
- const byPath = new Map();
519
- for (const workspace of workspaces || []) {
520
- if (workspace.path) byPath.set(folderPath(workspace.path), workspace);
521
- }
522
- const included = new Map();
523
- for (const workspace of workspaces || []) {
524
- const key = workspaceKey(workspace);
525
- if (!key || !buckets.has(key)) continue;
526
- included.set(key, workspace);
527
- let path = workspace.path;
528
- const seen = new Set();
529
- while (path && !seen.has(path)) {
530
- seen.add(path);
531
- const parentPath = owningParentFolder(path, [...byPath.keys()]);
532
- if (!parentPath) break;
533
- const parent = byPath.get(folderPath(parentPath));
534
- const parentKey = parent ? workspaceKey(parent) : "";
535
- if (!parent || !parentKey) break;
536
- included.set(parentKey, parent);
537
- path = parent.path;
538
- }
539
- }
540
- const present = [...included.values()];
541
- const paths = present.map((workspace) => workspace.path).filter(Boolean);
542
- const children = new Map();
543
- const roots = [];
544
- for (const workspace of present) {
545
- const parentPath = workspace.path ? owningParentFolder(workspace.path, paths) : undefined;
546
- const parent = parentPath ? present.find((item) => item.path && folderPath(item.path) === folderPath(parentPath)) : undefined;
547
- const parentKey = parent ? workspaceKey(parent) : "";
548
- if (!parent || !parentKey) roots.push(workspace);
549
- else {
550
- const list = children.get(parentKey) || [];
551
- list.push(workspace);
552
- children.set(parentKey, list);
553
- }
554
- }
555
- const byName = (left, right) => String(left.title || left.path || "").localeCompare(String(right.title || right.path || ""));
556
- const groups = [];
557
- const walk = (workspace, depth) => {
558
- const key = workspaceKey(workspace);
559
- const sessionsInWorkspace = buckets.get(key) || [];
560
- const channelIds = [...new Set(sessionsInWorkspace.map((session) => session.channelId).filter(Boolean))];
561
- groups.push({
562
- id: key,
563
- label: workspace.title || workspace.path || ungroupedLabel,
564
- depth,
565
- keep: sessionsInWorkspace.length === 0,
566
- channelId: channelIds.length === 1 ? channelIds[0] : "",
567
- sessions: sessionsInWorkspace,
568
- });
569
- for (const child of (children.get(key) || []).slice().sort(byName)) walk(child, depth + 1);
570
- };
571
- for (const root of roots.slice().sort(byName)) walk(root, 0);
572
- if (ungrouped.length) groups.push({ id: "", label: ungroupedLabel, depth: 0, channelId: "", sessions: ungrouped });
573
- return groups;
574
- }
575
- function channelSessionHoverStatuses(input, t) {
576
- const count = input.runningSubagentCount || 0;
577
- const subagents = count === 0 ? undefined : { state: "ongoing", label: t("rail.subagents", { n: count, count }) };
578
- let pending;
579
- if (input.pendingKind === "approval") pending = { state: "warning", label: t("rail.waitingApproval"), trailing: t("rail.compactApproval") };
580
- else if (input.pendingKind === "plan-review") pending = { state: "warning", label: t("rail.planReview"), trailing: t("rail.compactPlan") };
581
- else if (input.pendingKind === "question") pending = { state: "warning", label: t("rail.waitingAnswer"), trailing: t("rail.compactAnswer") };
582
- let statuses;
583
- if (pending) statuses = subagents ? [pending, subagents] : [pending];
584
- else if (input.running) statuses = subagents ? [{ state: "ongoing", label: t("rail.running") }, subagents] : [{ state: "ongoing", label: t("rail.running") }];
585
- else if (subagents) statuses = [subagents];
586
- else if (input.completed) statuses = [{ state: "done", label: t("rail.completed") }];
587
- else statuses = [{ state: "idle", label: t("rail.idle") }];
588
- const visible = statuses.filter((status) => !(input.archived && (status.state === "done" || status.state === "idle")));
589
- if (input.archived) visible.push({ state: "archived", label: t("rail.archived") });
590
- return visible;
591
- }
592
- function placeSessionTitle(title, left, range) {
593
- title.scrollLeft = left;
594
- if (left > 0) title.dataset.scrolled = "";
595
- else delete title.dataset.scrolled;
596
- if (left < range) title.dataset.clipped = "";
597
- else delete title.dataset.clipped;
598
- }
599
- function restSessionTitle(title) {
600
- title.scrollLeft = 0;
601
- delete title.dataset.scrolled;
602
- delete title.dataset.clipped;
603
- }
604
- function startSessionTitleMarquee(title, frame) {
605
- if (!title) return;
606
- const range = title.scrollWidth - title.clientWidth;
607
- if (range <= 8) return;
608
- if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
609
- placeSessionTitle(title, range, range);
610
- return;
611
- }
612
- cancelAnimationFrame(frame.id);
613
- let previous;
614
- let position = 0;
615
- const step = (now) => {
616
- position += previous === undefined ? 0 : (now - previous) * 0.03;
617
- previous = now;
618
- placeSessionTitle(title, Math.min(position, range), range);
619
- if (position < range) frame.id = requestAnimationFrame(step);
620
- };
621
- frame.id = requestAnimationFrame(step);
622
- }
623
- function stopSessionTitleMarquee(title, frame) {
624
- cancelAnimationFrame(frame.id);
625
- if (title) restSessionTitle(title);
626
- }
627
- function channelSessionVisible(sessionId, archived, filter) {
628
- if (!sessionId) return false;
629
- const isArchived = archived.has(sessionId);
630
- if (filter === "only") return isArchived;
631
- if (filter === "show") return true;
632
- return !isArchived;
633
- }
634
- async function archiveChannelGroup(sessionIds, archiveSession, options) {
635
- for (const sessionId of sessionIds) await archiveSession(sessionId, options);
636
- }
637
- function openStopArchive(error, target, open) {
638
- if (typeof open !== "function" || !activeSessionRefusal(error)) return false;
639
- open(target);
640
- return true;
641
- }
642
- async function finishStopArchive(target, archiveSession) {
643
- if (!target || typeof archiveSession !== "function") return "unavailable";
644
- if (target.sessionIds) {
645
- await archiveChannelGroup(target.sessionIds, archiveSession, { stopActivity: true });
646
- return "group";
647
- }
648
- await archiveSession(target.id, { stopActivity: true });
649
- return "session";
650
- }
651
420
  const CHANNEL_SETTINGS_EVENT = "dsh-im-connect:open-channel-settings";
652
421
  const CHANNEL_SETTINGS_STORAGE_KEY = "dsh-im-connect:pending-channel-settings";
653
422
  const SETTINGS_CODEX_TRIGGER_SELECTOR = "[data-dcu-settings-trigger]";
@@ -686,10 +455,19 @@ window.__ModuleLoader__.load({
686
455
  return { channelId: channel.id, accountId: accounts.length === 1 ? accounts[0].id : undefined };
687
456
  }
688
457
  function pickSettingsSectionButton(buttons, labels) {
689
- for (const label of labels) {
690
- const target = String(label || "").trim();
691
- if (!target) continue;
692
- const match = buttons.find((button) => String(button.textContent || "").replace(/\s+/g, " ").trim() === target);
458
+ const normalize = (value) => String(value || "").replace(/\s+/g, "").trim().toLowerCase();
459
+ const labelOf = (button) => normalize(button.textContent) || normalize(button.getAttribute && button.getAttribute("aria-label"));
460
+ const targets = labels.map(normalize).filter(Boolean);
461
+ for (const target of targets) {
462
+ const match = buttons.find((button) => labelOf(button) === target);
463
+ if (match) return match;
464
+ }
465
+ // 宿主可能在标签旁加计数或徽标;退一步做包含匹配。
466
+ for (const target of targets) {
467
+ const match = buttons.find((button) => {
468
+ const text = labelOf(button);
469
+ return text !== "" && (text.includes(target) || target.includes(text));
470
+ });
693
471
  if (match) return match;
694
472
  }
695
473
  return undefined;
@@ -701,12 +479,33 @@ window.__ModuleLoader__.load({
701
479
  });
702
480
  return named || (buttons.length === 1 ? buttons[0] : undefined);
703
481
  }
482
+ function findAccountMenuTrigger() {
483
+ const exact = [
484
+ 'button[aria-label="账号菜单"]',
485
+ 'button[aria-label="Account menu"]',
486
+ ];
487
+ for (const selector of exact) {
488
+ const found = document.querySelector(selector);
489
+ if (found) return found;
490
+ }
491
+ return [...document.querySelectorAll('button[aria-haspopup="menu"]')].find((button) => {
492
+ const label = `${typeof button.getAttribute === "function" ? button.getAttribute("aria-label") || "" : ""} ${button.textContent || ""}`.trim();
493
+ return /账号|account/i.test(label);
494
+ });
495
+ }
704
496
  function requestCodexSettingsSection(labels) {
705
497
  const trigger = typeof document !== "undefined" && document.querySelector(SETTINGS_CODEX_TRIGGER_SELECTOR);
706
498
  if (!trigger) return false;
707
499
  const request = new CustomEvent(SETTINGS_OPEN_SECTION_EVENT, { detail: { labels: [...labels] }, cancelable: true });
708
500
  return !trigger.dispatchEvent(request);
709
501
  }
502
+ function openImSettingsPage(t) {
503
+ openSettingsSection(
504
+ [t("settings.label"), IM_LOCALES.en["settings.label"], IM_LOCALES.zh["settings.label"]],
505
+ () => {},
506
+ () => console.warn("[dsh-im-connect] 无法打开 IM 助理设置页"),
507
+ );
508
+ }
710
509
  function openSettingsSection(labels, onSelected, onMissing) {
711
510
  if (typeof document === "undefined" || typeof window === "undefined") {
712
511
  if (onMissing) onMissing();
@@ -716,18 +515,27 @@ window.__ModuleLoader__.load({
716
515
  if (onSelected) onSelected();
717
516
  return;
718
517
  }
719
- const launchers = [...document.querySelectorAll('button[aria-haspopup="dialog"]')];
720
- const launcher = pickSettingsLauncher(launchers);
518
+ const launchers = [...document.querySelectorAll('button[aria-haspopup="dialog"], button[aria-label*="设置"], button[aria-label*="Settings"], [data-dcu-settings-trigger]')];
519
+ const namedSettingsButton = [...document.querySelectorAll("button")].find((button) => /^(设置|settings)$/i.test((button.getAttribute("aria-label") || "").trim()));
520
+ const launcher = namedSettingsButton || pickSettingsLauncher(launchers);
721
521
  const pageTrigger = document.querySelector(SETTINGS_CODEX_TRIGGER_SELECTOR);
722
522
  const dialogOpen = document.querySelector('[role="dialog"]') !== null;
723
523
  const pageOpen = document.querySelector(SETTINGS_CODEX_PAGE_SELECTOR) !== null;
524
+ let menuTrigger;
724
525
  if (!dialogOpen && !pageOpen && !launcher && !pageTrigger) {
725
- if (onMissing) onMissing();
726
- return;
526
+ menuTrigger = findAccountMenuTrigger();
527
+ if (!menuTrigger) {
528
+ if (onMissing) onMissing();
529
+ return;
530
+ }
531
+ menuTrigger.click();
532
+ } else if (!dialogOpen && !pageOpen) {
533
+ (pageTrigger || launcher).click();
727
534
  }
728
- if (!dialogOpen && !pageOpen) (pageTrigger || launcher).click();
729
535
  let frame;
730
536
  let finished = false;
537
+ let menuActivated = false;
538
+ let timeout;
731
539
  const observer = new MutationObserver(() => { schedule(); });
732
540
  const cleanup = () => {
733
541
  if (finished) return;
@@ -736,10 +544,29 @@ window.__ModuleLoader__.load({
736
544
  window.clearTimeout(timeout);
737
545
  if (frame !== undefined) window.cancelAnimationFrame(frame);
738
546
  };
547
+ const wait = () => {
548
+ timeout = window.setTimeout(() => {
549
+ if (select()) return;
550
+ cleanup();
551
+ if (onMissing) onMissing();
552
+ }, 5000);
553
+ };
739
554
  const select = () => {
555
+ if (menuTrigger !== undefined && !menuActivated) {
556
+ const items = [...document.querySelectorAll('[role="menuitem"], [role="menu"] button')];
557
+ const entry = pickSettingsSectionButton(items, ["设置", "Settings"]);
558
+ if (!entry) return false;
559
+ menuActivated = true;
560
+ window.clearTimeout(timeout);
561
+ wait();
562
+ entry.click();
563
+ schedule();
564
+ return true;
565
+ }
740
566
  const buttons = [
741
- ...document.querySelectorAll('[role="dialog"] nav button'),
567
+ ...document.querySelectorAll('[role="dialog"] nav button, [role="dialog"] button'),
742
568
  ...document.querySelectorAll(SETTINGS_CODEX_PAGE_SELECTOR + " nav button"),
569
+ ...document.querySelectorAll("nav button, button"),
743
570
  ];
744
571
  const target = pickSettingsSectionButton(buttons, labels);
745
572
  if (!target) return false;
@@ -752,44 +579,25 @@ window.__ModuleLoader__.load({
752
579
  if (finished || frame !== undefined) return;
753
580
  frame = window.requestAnimationFrame(() => { frame = undefined; select(); });
754
581
  };
755
- const timeout = window.setTimeout(() => {
756
- if (select()) return;
757
- cleanup();
758
- if (onMissing) onMissing();
759
- }, 1500);
582
+ wait();
760
583
  observer.observe(document.body, { childList: true, subtree: true });
761
584
  schedule();
762
585
  }
763
586
  const EMPTY_EXTRA_TABS = [];
764
587
  const inject = ["slots", "sessions", "workspaces", "locale"];
765
588
  const API_BASE = "/api/dsh-im-connect";
766
- const TAB_KEY = "dsh-im-connect.sidebar-tab";
589
+ const TAB_KEY = "dsh-native-sidebar.tab";
767
590
  const ACCOUNT_SELECTION_KEY = "dsh-im-connect.settings.selected-account";
768
591
  const IM_LOCALE_NS = "im-connect";
769
- const UPDATE_ICON_PATHS = {
770
- refresh: ["M13.5 5.5V2.5m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.2 12"],
771
- download: ["M8 2v8m0 0 3-3m-3 3-3-3M3 13v2h10v-2"],
772
- copy: ["M5 5h8v8H5z", "M3 3h8"],
773
- close: ["m4 4 8 8M12 4 4 12"],
592
+ const UPDATE_ICONS = {
593
+ refresh: IconRefreshOutline,
594
+ download: IconDownloadOutline,
595
+ copy: IconCopyOutline,
596
+ close: IconCloseFill,
774
597
  };
775
598
  function createPluginUpdateIcon(name) {
776
599
  const element = document.createElement("span");
777
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
778
- svg.setAttribute("viewBox", "0 0 16 16");
779
- svg.setAttribute("width", "16");
780
- svg.setAttribute("height", "16");
781
- svg.setAttribute("fill", "none");
782
- svg.setAttribute("stroke", "currentColor");
783
- svg.setAttribute("stroke-width", "1.5");
784
- svg.setAttribute("stroke-linecap", "round");
785
- svg.setAttribute("stroke-linejoin", "round");
786
- svg.setAttribute("aria-hidden", "true");
787
- UPDATE_ICON_PATHS[name].forEach((d) => {
788
- const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
789
- path.setAttribute("d", d);
790
- svg.append(path);
791
- });
792
- element.append(svg);
600
+ element.innerHTML = channelMarkup(h(UPDATE_ICONS[name] || IconRefreshOutline, { size: 16 }));
793
601
  return element;
794
602
  }
795
603
  const IM_LOCALES = {
@@ -814,9 +622,9 @@ window.__ModuleLoader__.load({
814
622
  "qr.weixin": "请使用微信扫描二维码完成绑定", "qr.feishu": "请使用飞书扫描二维码,将自动创建机器人", "qr.lark": "请使用 Lark 扫描二维码完成配对", "qr.wecom": "请使用企业微信扫描二维码,快捷绑定机器人", "qr.dingtalk": "请使用钉钉扫描二维码,自动创建机器人", "qr.qq": "请使用手机 QQ 扫描二维码,创建开放平台机器人", "qr.default": "请使用对应 App 扫描二维码",
815
623
  "status.connected": "已连接", "action.more": "{channel} 更多",
816
624
  "error.loadAssistant": "无法加载账号配置", "error.noModels": "当前 Host 还没有可用模型,请先在网页里配置提供商", "error.save": "保存失败", "error.chooseWorkspace": "请选择工作区目录", "error.workspaceUnavailable": "当前 Host 无法新增工作区", "error.addWorkspace": "新增工作区失败", "error.load": "加载失败", "error.connection": "无法连接本机 IM 助理接口", "error.request": "请求失败", "error.action": "操作失败", "error.qr": "无法生成二维码", "error.detailsInLog": "操作失败,请查看服务器日志。",
817
- "composer.noWorkspaces": "暂无工作区", "composer.addWorkspace": "添加工作区…", "composer.workspaceRequired": "请先添加工作区,否则无法保存", "composer.permission": "权限", "composer.noModels": "暂无模型", "action.cancel": "取消",
625
+ "composer.noWorkspaces": "暂无工作区", "composer.addWorkspace": "添加工作区…", "composer.workspaceRequired": "请先添加工作区,否则无法保存", "composer.permission": "权限", "composer.noModels": "暂无模型", "action.cancel": "取消",
818
626
  "permission.readOnly": "只读", "permission.workspaceWrite": "工作区写入", "permission.fullAccess": "完全访问",
819
- "rail.workspace": "工作区", "rail.sessions": "会话", "rail.search": "搜索", "rail.searchPlaceholder": "搜索会话...", "rail.clearSearch": "清除搜索", "rail.filter": "筛选", "rail.group": "分组方式", "rail.byWorkspace": "按工作区", "rail.list": "单列表", "rail.byWorkspaceTree": "按工作区树", "rail.sort": "排序方式", "rail.recent": "最近更新", "rail.showArchived": "显示已归档", "rail.onlyArchived": "仅显示已归档", "rail.running": "运行中", "rail.idle": "空闲", "rail.waitingApproval": "等待审批", "rail.planReview": "计划待审", "rail.waitingAnswer": "等待回答", "rail.subagents": "{n} 个子代理运行中", "rail.completed": "已完成", "rail.archived": "已归档", "rail.compactApproval": "待审批", "rail.compactPlan": "计划待审", "rail.compactAnswer": "待回答", "rail.renameAria": "重命名会话", "rail.rename": "重命名", "rail.fork": "分叉会话", "rail.archive": "归档会话", "rail.unarchive": "恢复会话", "rail.stopArchive": "停止并归档", "rail.stopArchiveDescription": "会话“{name}”仍在运行。停止后才能归档。", "rail.stopArchiveConfirm": "停止并归档", "rail.stopArchivePending": "正在停止并归档…", "rail.stopArchiveGroupDescription": "“{name}”下仍有运行中的会话。停止这些会话后才能归档整组。", "rail.archiveFailed": "归档失败,未移除会话。请稍后重试或检查宿主日志。", "rail.deleteSession": "删除会话", "rail.deleteSessionConfirm": "删除会话", "rail.deleteSessionDescription": "将永久删除会话“{name}”及其子代理(含正在运行的)和全部记录(对话内容、统计、缓存),此操作不可恢复。", "rail.deleteSessionPending": "正在删除会话…", "rail.deleteSessionFailed": "删除会话失败:{message}", "rail.deleteSessionClose": "关闭", "rail.deleteSessionCancel": "取消", "rail.groupActions": "“{name}”的频道操作", "rail.channelSettings": "渠道设置", "rail.archiveGroup": "归档整组会话", "rail.archiveGroupConfirm": "确认归档", "rail.archiveGroupDescription": "将归档“{name}”下的 {count} 个会话。归档后可以在“设置 → 已归档”中恢复。", "rail.archiveGroupPending": "正在归档整组会话…", "rail.archiveGroupFailed": "部分会话归档失败:{message}", "rail.archiveGroupClose": "关闭", "rail.archiveGroupCancel": "取消", "rail.empty": "还没有频道会话。先在设置 → IM助理 里连接渠道,并给机器人发一条消息。", "rail.noTasks": "暂无网页任务", "rail.ungrouped": "未分组", "rail.tabsAria": "工作区分类", "rail.tasks": "任务", "rail.channels": "频道",
627
+ "rail.workspace": "工作区", "rail.sessions": "会话", "rail.search": "搜索", "rail.searchPlaceholder": "搜索会话...", "rail.clearSearch": "清除搜索", "rail.filter": "筛选", "rail.group": "分组方式", "rail.byWorkspace": "按工作区", "rail.list": "单列表", "rail.byWorkspaceTree": "按工作区树", "rail.byChannel": "按频道", "rail.treeUnavailable": "当前宿主未提供官方任务树。", "rail.groupReadOnly": "频道分组不能在这里重命名或删除。", "rail.sort": "排序方式", "rail.recent": "最近更新", "rail.showArchived": "显示已归档", "rail.onlyArchived": "仅显示已归档", "rail.running": "运行中", "rail.idle": "空闲", "rail.waitingApproval": "等待审批", "rail.planReview": "计划待审", "rail.waitingAnswer": "等待回答", "rail.subagents": "{n} 个子代理运行中", "rail.completed": "已完成", "rail.archived": "已归档", "rail.compactApproval": "待审批", "rail.compactPlan": "计划待审", "rail.compactAnswer": "待回答", "rail.renameAria": "重命名会话", "rail.rename": "重命名", "rail.fork": "分叉会话", "rail.archive": "归档会话", "rail.unarchive": "恢复会话", "rail.deleteSession": "删除会话", "rail.deleteSessionConfirm": "删除会话", "rail.deleteSessionDescription": "将永久删除会话“{name}”及其子代理(含正在运行的)和全部记录(对话内容、统计、缓存),此操作不可恢复。", "rail.deleteSessionPending": "正在删除会话…", "rail.deleteSessionFailed": "删除会话失败:{message}", "rail.deleteSessionClose": "关闭", "rail.deleteSessionCancel": "取消", "rail.groupActions": "“{name}”的频道操作", "rail.channelSettings": "频道设置", "rail.addChannel": "添加频道", "rail.empty": "还没有频道会话。先在设置 → IM助理 里连接渠道,并给机器人发一条消息。", "rail.ungrouped": "未分组", "rail.tabsAria": "工作区分类", "rail.tasks": "任务", "rail.channels": "频道",
820
628
  "time.now": "刚刚", "time.minutes": "{n}分钟", "time.hours": "{n}小时", "time.days": "{n}天", "time.months": "{n}个月", "time.years": "{n}年", "time.ago": "{t}前",
821
629
  "copy": "复制", "hover.copied": "已复制",
822
630
  "server.unknownChannel": "未知渠道", "server.channelUnconfigured": "渠道未配置", "server.sessionMissing": "会话不存在", "server.accountMissing": "账号不存在", "server.accountConnectFailed": "账号连接失败,请查看本机日志", "server.accountReconnectFailed": "重新连接失败,请查看本机日志", "server.selectAccountSettings": "请选择提供商、模型、工作区或权限", "server.selectModel": "请选择提供商和模型", "server.selectWorkspace": "请选择工作区", "server.createWorkspace": "请先添加工作区", "server.selectPermission": "请选择权限", "server.missingCredentials": "凭据不足,无法启动渠道", "server.qrUnsupported": "该渠道不支持扫码绑定", "server.qrExpired": "二维码已过期", "server.qrIncomplete": "扫码未完成", "server.accessDenied": "未授权:请管理员在设置 → IM助理 中批准你的访问。", "server.remarkTooLong": "账号备注不能超过 40 个字符", "server.remarkControl": "账号备注不能包含换行或控制字符",
@@ -843,9 +651,9 @@ window.__ModuleLoader__.load({
843
651
  "qr.weixin": "Scan the QR code with WeChat to connect", "qr.feishu": "Scan with Feishu; a bot will be created automatically", "qr.lark": "Scan with Lark to pair", "qr.wecom": "Scan with WeCom to quickly connect a bot", "qr.dingtalk": "Scan with DingTalk; a bot will be created automatically", "qr.qq": "Scan with mobile QQ to create an Open Platform bot", "qr.default": "Scan the QR code with the corresponding app",
844
652
  "status.connected": "Connected", "action.more": "More options for {channel}",
845
653
  "error.loadAssistant": "Could not load account settings", "error.noModels": "No models are available in the Host. Configure a provider in the web app first.", "error.save": "Could not save", "error.chooseWorkspace": "Choose a workspace directory", "error.workspaceUnavailable": "This Host cannot create workspaces", "error.addWorkspace": "Could not add workspace", "error.load": "Could not load", "error.connection": "Could not connect to the local IM Assistant API", "error.request": "Request failed", "error.action": "Action failed", "error.qr": "Could not generate a QR code", "error.detailsInLog": "The operation failed. Check the server logs for details.",
846
- "composer.noWorkspaces": "No workspaces", "composer.addWorkspace": "Add workspace…", "composer.workspaceRequired": "Add a workspace before saving.", "composer.permission": "Permission", "composer.noModels": "No models", "action.cancel": "Cancel",
654
+ "composer.noWorkspaces": "No workspaces", "composer.addWorkspace": "Add workspace…", "composer.workspaceRequired": "Add a workspace before saving.", "composer.permission": "Permission", "composer.noModels": "No models", "action.cancel": "Cancel",
847
655
  "permission.readOnly": "Read Only", "permission.workspaceWrite": "Workspace Write", "permission.fullAccess": "Full access",
848
- "rail.workspace": "Workspaces", "rail.sessions": "Sessions", "rail.search": "Search", "rail.searchPlaceholder": "Search sessions...", "rail.clearSearch": "Clear search", "rail.filter": "Filter", "rail.group": "Group by", "rail.byWorkspace": "By workspace", "rail.list": "Single list", "rail.byWorkspaceTree": "Workspace Tree", "rail.sort": "Sort by", "rail.recent": "Recently updated", "rail.showArchived": "Show archived", "rail.onlyArchived": "Archived only", "rail.running": "Running", "rail.idle": "Idle", "rail.waitingApproval": "Waiting for approval", "rail.planReview": "Plan to review", "rail.waitingAnswer": "Waiting for an answer", "rail.subagents": "{n} subagents running", "rail.completed": "Completed", "rail.archived": "Archived", "rail.compactApproval": "Approval", "rail.compactPlan": "Plan review", "rail.compactAnswer": "Answer", "rail.renameAria": "Rename session", "rail.rename": "Rename", "rail.fork": "Fork session", "rail.archive": "Archive session", "rail.unarchive": "Restore session", "rail.stopArchive": "Stop and archive", "rail.stopArchiveDescription": "Session “{name}” is still running. Stop it before archiving.", "rail.stopArchiveConfirm": "Stop and archive", "rail.stopArchivePending": "Stopping and archiving…", "rail.stopArchiveGroupDescription": "Some conversations in “{name}” are still running. Stop them before archiving the group.", "rail.archiveFailed": "Archive failed. The session was kept. Retry or check the Host logs.", "rail.deleteSession": "Delete session", "rail.deleteSessionConfirm": "Delete session", "rail.deleteSessionDescription": "This permanently deletes session “{name}”, its child agents (including any that are still running), and all of its records (conversation, stats, cache). This cannot be undone.", "rail.deleteSessionPending": "Deleting session…", "rail.deleteSessionFailed": "Could not delete the session: {message}", "rail.deleteSessionClose": "Close", "rail.deleteSessionCancel": "Cancel", "rail.groupActions": "Actions for {name}", "rail.channelSettings": "Channel settings", "rail.archiveGroup": "Archive all conversations", "rail.archiveGroupConfirm": "Archive all", "rail.archiveGroupDescription": "Archive all {count} conversations for “{name}”. You can restore them later in Settings → Archived.", "rail.archiveGroupPending": "Archiving conversations…", "rail.archiveGroupFailed": "Some conversations could not be archived: {message}", "rail.archiveGroupClose": "Close", "rail.archiveGroupCancel": "Cancel", "rail.empty": "No channel sessions yet. Connect a channel in Settings → IM Assistant, then send the bot a message.", "rail.noTasks": "No web tasks", "rail.ungrouped": "Ungrouped", "rail.tabsAria": "Workspace categories", "rail.tasks": "Tasks", "rail.channels": "Channels",
656
+ "rail.workspace": "Workspaces", "rail.sessions": "Sessions", "rail.search": "Search", "rail.searchPlaceholder": "Search sessions...", "rail.clearSearch": "Clear search", "rail.filter": "Filter", "rail.group": "Group by", "rail.byWorkspace": "By workspace", "rail.list": "Single list", "rail.byWorkspaceTree": "Workspace Tree", "rail.byChannel": "By channel", "rail.treeUnavailable": "The official tree is unavailable in this Host.", "rail.groupReadOnly": "Channel groups cannot be renamed or deleted here.", "rail.sort": "Sort by", "rail.recent": "Recently updated", "rail.showArchived": "Show archived", "rail.onlyArchived": "Archived only", "rail.running": "Running", "rail.idle": "Idle", "rail.waitingApproval": "Waiting for approval", "rail.planReview": "Plan to review", "rail.waitingAnswer": "Waiting for an answer", "rail.subagents": "{n} subagents running", "rail.completed": "Completed", "rail.archived": "Archived", "rail.compactApproval": "Approval", "rail.compactPlan": "Plan review", "rail.compactAnswer": "Answer", "rail.renameAria": "Rename session", "rail.rename": "Rename", "rail.fork": "Fork session", "rail.archive": "Archive session", "rail.unarchive": "Restore session", "rail.deleteSession": "Delete session", "rail.deleteSessionConfirm": "Delete session", "rail.deleteSessionDescription": "This permanently deletes session “{name}”, its child agents (including any that are still running), and all of its records (conversation, stats, cache). This cannot be undone.", "rail.deleteSessionPending": "Deleting session…", "rail.deleteSessionFailed": "Could not delete the session: {message}", "rail.deleteSessionClose": "Close", "rail.deleteSessionCancel": "Cancel", "rail.groupActions": "Actions for {name}", "rail.channelSettings": "Channel settings", "rail.addChannel": "Add channel", "rail.empty": "No channel sessions yet. Connect a channel in Settings → IM Assistant, then send the bot a message.", "rail.ungrouped": "Ungrouped", "rail.tabsAria": "Workspace categories", "rail.tasks": "Tasks", "rail.channels": "Channels",
849
657
  "time.now": "now", "time.minutes": "{n}min", "time.hours": "{n}h", "time.days": "{n}d", "time.months": "{n}mo", "time.years": "{n}y", "time.ago": "{t} ago",
850
658
  "copy": "Copy", "hover.copied": "Copied",
851
659
  "server.unknownChannel": "Unknown channel", "server.channelUnconfigured": "Channel is not configured", "server.sessionMissing": "Session does not exist", "server.accountMissing": "Account does not exist", "server.accountConnectFailed": "Could not connect the account. Check the local logs.", "server.accountReconnectFailed": "Could not reconnect the account. Check the local logs.", "server.selectAccountSettings": "Select a provider, model, workspace, or permission setting", "server.selectModel": "Select a provider and model", "server.selectWorkspace": "Select a workspace", "server.createWorkspace": "Add a workspace first.", "server.selectPermission": "Select a permission", "server.missingCredentials": "The channel cannot start because credentials are missing", "server.qrUnsupported": "This channel does not support QR setup", "server.qrExpired": "QR code has expired", "server.qrIncomplete": "QR setup was not completed", "server.accessDenied": "Access denied: ask an administrator to approve you in Settings → IM Assistant.", "server.remarkTooLong": "Account remark cannot exceed 40 characters", "server.remarkControl": "Account remark cannot contain line breaks or control characters",
@@ -854,32 +662,6 @@ window.__ModuleLoader__.load({
854
662
  };
855
663
  const fallbackT = (key) => key;
856
664
  const h = React.createElement;
857
- function currentUiLang() {
858
- try {
859
- if (typeof document !== "undefined" && document.documentElement && document.documentElement.lang) {
860
- if (/^en/i.test(document.documentElement.lang)) return "en";
861
- if (/^zh/i.test(document.documentElement.lang)) return "zh";
862
- }
863
- } catch { /* ignore */ }
864
- return "zh";
865
- }
866
- function hostIsDark() {
867
- if (typeof document === "undefined") return false;
868
- return document.documentElement.hasAttribute("data-ds-dark-theme")
869
- || (document.body && document.body.hasAttribute("data-ds-dark-theme") === true);
870
- }
871
- function useHostDark() {
872
- const [dark, setDark] = useState(hostIsDark);
873
- useEffect(() => {
874
- const update = () => setDark(hostIsDark());
875
- update();
876
- const observer = new MutationObserver(update);
877
- observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-ds-dark-theme"] });
878
- if (document.body) observer.observe(document.body, { attributes: true, attributeFilter: ["data-ds-dark-theme"] });
879
- return () => observer.disconnect();
880
- }, []);
881
- return dark;
882
- }
883
665
  function HostThemeProvider({ children }) {
884
666
  return children;
885
667
  }
@@ -893,7 +675,7 @@ window.__ModuleLoader__.load({
893
675
  .ima-title-links{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
894
676
  .ima-title-links>span[data-mpi-check]{display:inline-flex;align-items:center}
895
677
  [data-ima-nav-icon="assistant"]>svg{display:none!important}
896
- .ima-nav-icon-assistant{--ima-nav-icon-mask:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2016%2016%22%3E%3Cpath%20fill%3D%22black%22%20d%3D%22M2.15%202.9h11.7v8.2H6.42L2.15%2013.85V2.9Zm1.4%201.4v6.62l1.78-1.12h7.12V4.3H3.55Z%22%2F%3E%3C%2Fsvg%3E");display:inline-block;flex:none;width:16px;height:16px;background:currentColor;-webkit-mask:var(--ima-nav-icon-mask) center/contain no-repeat;mask:var(--ima-nav-icon-mask) center/contain no-repeat}
678
+ .ima-nav-icon-assistant{display:inline-block;flex:none;width:16px;height:16px;background:currentColor;-webkit-mask:var(--ima-nav-icon-mask) center/contain no-repeat;mask:var(--ima-nav-icon-mask) center/contain no-repeat}
897
679
  .ima-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}
898
680
  .ima-btn:not(.is-primary):not(.ima-btn-danger){color:var(--dsw-alias-label-primary,#eee)!important}
899
681
  .ima-btn:hover:not(:disabled):not(.ima-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}
@@ -923,14 +705,14 @@ window.__ModuleLoader__.load({
923
705
  .ima-feedback-title{font-weight:550;line-height:20px}
924
706
  .ima-pending-list{display:flex;flex-direction:column;gap:6px;width:100%}
925
707
  .ima-pending-row{display:flex;gap:8px;align-items:center;padding:4px 0}
926
- .ima-wrap{display:flex;flex-direction:column;min-height:0;flex:1;height:100%;overflow:hidden}.ima-official-tree{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}.ima-native.ima-rail,.ima-rail.dcu-wb{box-sizing:border-box;overflow:hidden}
708
+ .ima-wrap{display:flex;flex-direction:column;min-height:0;flex:1;height:100%;overflow:hidden}.ima-official-tree{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}
927
709
  .ima-tabs-wrap{display:flex;margin:2px var(--dsh-sidebar-inline-padding,12px) 8px 0;padding:0;width:auto}
928
- .ima-tabs-wrap .ima-segmented-tabs{width:100%;background:color-mix(in srgb,var(--dsw-alias-label-primary,currentColor) 3%,transparent)!important;border-radius:8px!important;border:0.5px solid var(--dsw-alias-border-l1,rgba(255,255,255,.05))!important;box-sizing:border-box;padding:2px!important}
929
- .ima-tabs-wrap .ima-segmented-tabs>span{inset:2px auto 2px 2px!important;width:calc((100% - 4px)/var(--ima-tab-count,2))!important;border-radius:6px!important;border:0.5px solid var(--dsw-alias-border-l2,rgba(255,255,255,.08))!important;background:color-mix(in srgb,var(--dsw-alias-label-primary,currentColor) 8%,transparent)!important;border-color:color-mix(in srgb,var(--dsw-alias-label-primary,currentColor) 12%,transparent)!important;box-shadow:none!important}
930
- .ima-tabs-wrap .ima-segmented-tabs [role=tab]{display:inline-flex!important;align-items:center!important;justify-content:center!important;gap:5px!important;width:100%!important;height:26px!important;padding:0 6px!important;font-size:13px!important;line-height:18px!important;border-radius:6px!important;color:var(--dsw-alias-label-secondary,#8b8f98);text-align:center!important}
710
+ .ima-tabs-wrap .ima-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}
711
+ .ima-tabs-wrap .ima-segmented-tabs>span{inset:2px auto 2px 2px!important;width:calc((100% - 4px)/var(--ima-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}
712
+ .ima-tabs-wrap .ima-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}
931
713
  .ima-tabs-wrap .ima-segmented-tabs [role=tab]>*{display:inline-flex!important;align-items:center!important;justify-content:center!important}
932
- .ima-tabs-wrap .ima-segmented-tabs [role=tab]:hover{color:var(--dsw-alias-label-primary,inherit)}
933
- .ima-tabs-wrap .ima-segmented-tabs [role=tab][aria-selected=true]{color:var(--dsw-alias-label-primary,inherit)!important;font-weight:600}
714
+ .ima-tabs-wrap .ima-segmented-tabs [role=tab]:hover{color:var(--dsw-alias-label-primary,inherit)!important}
715
+ .ima-tabs-wrap .ima-segmented-tabs [role=tab][aria-selected=true]{color:var(--dsw-alias-label-primary,inherit)!important;font-weight:600!important}
934
716
  .ima-bind-tabs-wrap{width:100%;margin:0 0 16px}
935
717
  .ima-bind-tabs-wrap.is-disabled{opacity:.6;pointer-events:none}
936
718
  .ima-bind-panel[hidden]{display:none!important}
@@ -944,12 +726,20 @@ window.__ModuleLoader__.load({
944
726
  .ima-tab{appearance:none;border:0;background:transparent;color:var(--ima-muted);padding:8px 0;font-size:13px;cursor:pointer}
945
727
  .ima-tab.on{color:var(--ima-text);box-shadow:inset 0 -2px 0 currentColor}
946
728
  .ima-tabs{flex:none}
947
- .ima-rail{flex:1 1 auto;min-height:180px;overflow:auto}
948
- .ima-rename{flex:1;min-width:0;min-height:28px;padding:2px 8px;border-radius:6px;border:1px solid var(--ima-line);background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-button-elevated-fill,transparent));color:var(--ima-text);font-size:13px}
949
729
  .ima-empty{color:var(--ima-muted);font-size:12px;padding:12px 8px}
730
+ .ima-channel-official{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden}
731
+ .ima-channel-official>div{flex:1;min-width:0;min-height:0}
732
+ .ima-channel-official>.ima-channel-error{flex:none}
733
+ .ima-channel-official>.ima-channel-unavailable{flex:1}
734
+ .ima-channel-error{padding:8px 12px;color:var(--dsw-alias-state-error-primary,#f85149);font-size:12px;line-height:18px}
735
+ .ima-channel-unavailable{padding:16px 12px;color:var(--dsw-alias-label-tertiary,#8b8f98);font-size:13px;line-height:20px}
736
+ .ima-session-channel-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;flex:none}
737
+ /* 频道页签复用官方工作区浏览器:分组头操作按模式裁剪。 */
738
+ .ima-channel-official[data-mode="channel"] [data-row-key^="workspace:dsh-im-channel:"]>span:last-child>:last-child{display:none!important}
739
+ .ima-channel-official[data-mode="workspace"] [data-row-key^="workspace:"]>span:last-child,
740
+ .ima-channel-official[data-mode="workspace-tree"] [data-row-key^="workspace:"]>span:last-child{display:none!important}
950
741
  .ima-logo{width:28px;height:28px;flex:none;display:block;line-height:0;background:transparent}
951
742
  .ima-logo svg{width:28px;height:28px;display:block}
952
- .ima-logo img.ima-brand-file{width:100%;height:100%;display:block;object-fit:contain;pointer-events:none}
953
743
  .ima-logo.sm{width:16px;height:16px;overflow:hidden;display:grid;place-items:center}
954
744
  .ima-logo.sm svg{width:16px;height:16px;transform:none}
955
745
  .ima-logo[data-brand="wecom"]{border-radius:6px;box-shadow:inset 0 0 0 1px rgba(15,23,42,.12);overflow:hidden;background:#fff}
@@ -960,11 +750,11 @@ window.__ModuleLoader__.load({
960
750
  .ima-hint{margin:0;color:var(--ima-muted);font-size:13px;text-align:center;line-height:1.6}
961
751
  .ima-field{display:flex;flex-direction:column;gap:6px;margin-bottom:12px;font-size:13px}
962
752
  .ima-field .ima-input,.ima-field input{width:100%}
963
- .ima-input,.ima-account-remark-input,.ima-field input,.ima-rename,.ima-n-search-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}
753
+ .ima-input,.ima-account-remark-input,.ima-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}
964
754
  .ima-textarea{height:auto!important;min-height:80px;padding:8px 12px!important;resize:vertical}
965
- .ima-input:hover:not(:disabled),.ima-account-remark-input:hover:not(:disabled),.ima-field input:hover:not(:disabled),.ima-rename:hover,.ima-n-search-input:hover{border-color:var(--dsw-alias-border-l3,#666)!important}
966
- .ima-input:focus,.ima-account-remark-input:focus,.ima-field input:focus,.ima-rename:focus,.ima-n-search-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}
967
- .ima-input::placeholder,.ima-account-remark-input::placeholder,.ima-field input::placeholder,.ima-n-search-input::placeholder{color:var(--dsw-alias-label-tertiary,#888)!important}
755
+ .ima-input:hover:not(:disabled),.ima-account-remark-input:hover:not(:disabled),.ima-field input:hover:not(:disabled){border-color:var(--dsw-alias-border-l3,#666)!important}
756
+ .ima-input:focus,.ima-account-remark-input:focus,.ima-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}
757
+ .ima-input::placeholder,.ima-account-remark-input::placeholder,.ima-field input::placeholder{color:var(--dsw-alias-label-tertiary,#888)!important}
968
758
  .ima-input:disabled,.ima-account-remark-input:disabled{opacity:.5!important;cursor:not-allowed!important}
969
759
  .ima-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}
970
760
  .ima-checkbox-label.is-disabled{opacity:.5;cursor:not-allowed}
@@ -988,7 +778,7 @@ window.__ModuleLoader__.load({
988
778
  .ima-modal-footer-wrap{display:flex;justify-content:flex-end;margin-top:12px;padding-top:16px}
989
779
  .ima-inspector-actions>button{flex:none;white-space:nowrap}
990
780
  .ima-confirm-content{margin:8px 0 0;font-size:13px;line-height:22px;color:var(--dsw-alias-label-secondary,#b9b9b9)}
991
- .ima-page.ima-account-page{container-type:inline-size;min-width:0;max-width:1080px;width:100%;margin:0 auto;padding:0 0 32px}
781
+ .ima-page.ima-account-page{container-type:inline-size;min-width:0;width:100%;padding:0 0 32px}
992
782
  .ima-account-shell,.ima-account-shell *{box-sizing:border-box}
993
783
  .ima-account-shell{display:block;min-height:0;border:0;border-radius:0;overflow:visible;background:transparent}
994
784
  .ima-platforms{display:flex;flex-direction:column;gap:12px;padding:0;border:0;background:transparent;min-width:0}
@@ -1069,15 +859,45 @@ window.__ModuleLoader__.load({
1069
859
  document.head.appendChild(styleEl);
1070
860
  };
1071
861
 
862
+ let requestHostSessionRefresh = () => {};
1072
863
  let channelSessionIds = new Set();
864
+ let channelSessionChannels = new Map();
1073
865
  let channelMembershipRevision = 0;
1074
866
  const channelMembershipListeners = new Set();
1075
867
  function updateChannelMembership(groups) {
1076
- const next = new Set(groups.flatMap(group => (group.sessions || []).map(session => session.sessionId)));
1077
- if (next.size === channelSessionIds.size && [...next].every(id => channelSessionIds.has(id))) return;
1078
- channelSessionIds = next;
1079
- channelMembershipRevision += 1;
1080
- for (const listener of channelMembershipListeners) listener();
868
+ const next = new Set();
869
+ const channels = new Map();
870
+ for (const group of groups) {
871
+ for (const session of group.sessions || []) {
872
+ next.add(session.sessionId);
873
+ channels.set(String(session.sessionId), group.id);
874
+ }
875
+ }
876
+ let changed = next.size !== channelSessionIds.size || [...next].some(id => !channelSessionIds.has(id));
877
+ if (!changed) {
878
+ for (const [id, channel] of channels) {
879
+ if (channelSessionChannels.get(id) !== channel) { changed = true; break; }
880
+ }
881
+ }
882
+ if (changed) {
883
+ channelSessionIds = next;
884
+ channelSessionChannels = channels;
885
+ channelMembershipRevision += 1;
886
+ for (const listener of channelMembershipListeners) listener();
887
+ }
888
+ try { requestHostSessionRefresh(changed); } catch { /* 下次频道轮询继续重试 */ }
889
+ }
890
+ /** IM 会话 ID 包含账号实例;接口映射兼容沿用普通 ID 的已接入会话。 */
891
+ function channelIdOfSession(sessionId) {
892
+ const value = String(sessionId || "");
893
+ const mapped = channelSessionChannels.get(value);
894
+ if (mapped) return mapped;
895
+ if (!value.startsWith("im:")) return undefined;
896
+ const rest = value.slice(3);
897
+ const split = rest.indexOf(":");
898
+ const instance = split > 0 ? rest.slice(0, split) : rest;
899
+ const platform = instance.split("_", 1)[0];
900
+ return platform || undefined;
1081
901
  }
1082
902
  const isChannelSession = (id) => String(id).startsWith("im:") || channelSessionIds.has(String(id));
1083
903
  const subscribeChannelMembership = (listener) => {
@@ -1090,8 +910,9 @@ window.__ModuleLoader__.load({
1090
910
  function sidebarTabForSession(currentId, extraTabs) {
1091
911
  if (typeof currentId !== "string" || currentId === "") return null;
1092
912
  const matched = (extraTabs || []).find((item) => item && item.matchSession && item.matchSession(currentId));
1093
- if (matched && matched.id !== "schedule") return matched.id;
1094
- if (isChannelSession(currentId)) return "channels";
913
+ if (matched && matched.id !== "schedule" && matched.id !== "channels") return matched.id;
914
+ // 频道会话同时存在于任务树和频道页签,不再自动改页签。
915
+ if (isChannelSession(currentId)) return null;
1095
916
  if (matched) return null;
1096
917
  return "tasks";
1097
918
  }
@@ -1099,14 +920,19 @@ window.__ModuleLoader__.load({
1099
920
  function followSidebarTab(state, currentId, extraTabs) {
1100
921
  const ready = !!(state && state.ready);
1101
922
  const next = sidebarTabForSession(currentId, extraTabs);
1102
- if (!ready) return { ready: true, previousId: currentId, tab: next };
923
+ // 首个有效主会话只建立基线,不覆盖用户恢复的页签;空快照继续等待。
924
+ if (!ready) return { ready: typeof currentId === "string" && currentId !== "", previousId: currentId, tab: null };
1103
925
  if (typeof currentId !== "string" || currentId === "") return { ready: true, previousId: currentId, tab: null };
1104
- if (currentId === state.previousId && !isChannelSession(currentId)) return { ready: true, previousId: currentId, tab: null };
926
+ if (currentId === state.previousId) return { ready: true, previousId: currentId, tab: null };
1105
927
  return { ready: true, previousId: currentId, tab: next };
1106
928
  }
1107
929
 
930
+ function resolveSidebarTab(tab, extraTabs) {
931
+ return tab === "tasks" || tab === "channels" || extraTabs.some((item) => item.id === tab) ? tab : "tasks";
932
+ }
933
+
1108
934
  function isHostNewSessionControl(label) {
1109
- return /新会话|新建任务|New chat|New session/i.test(String(label || ""));
935
+ return /^(新会话|新建任务|New chat|New session)(?:\s+(?:Ctrl|Alt|Shift|Meta)(?:\+[^\s+]+)*)?$/i.test(String(label || "").trim());
1110
936
  }
1111
937
 
1112
938
  const api = (path, opts) => {
@@ -1388,15 +1214,7 @@ window.__ModuleLoader__.load({
1388
1214
  if (fromKey && String(fromKey).trim()) return String(fromKey).trim();
1389
1215
  return sessionId;
1390
1216
  }
1391
- function isCurrentListedSession(selectedId, sessionId, sessionById) {
1392
- if (!selectedId || !sessionId) return false;
1393
- if (selectedId === sessionId) return true;
1394
- const listed = sessionById && sessionById[sessionId];
1395
- if (listed && (listed.id === selectedId || listed.sessionId === selectedId)) return true;
1396
- const selected = sessionById && sessionById[selectedId];
1397
- if (selected && (selected.id === sessionId || selected.sessionId === sessionId)) return true;
1398
- return false;
1399
- }
1217
+
1400
1218
  function mainSessionModel(state) {
1401
1219
  const id = currentSessionId(state);
1402
1220
  const row = id && state && state.projectionsBySession && state.projectionsBySession[id];
@@ -1453,13 +1271,6 @@ window.__ModuleLoader__.load({
1453
1271
  error.code = "workspace/picker-unavailable";
1454
1272
  return error;
1455
1273
  }
1456
- function activeSessionRefusal(error) {
1457
- const reason = error && (error.reason || error);
1458
- if (reason && reason.name === "WorkspaceArchiveError") return true;
1459
- const rpc = error && (error.rpcError || error);
1460
- if (rpc && (rpc.code === "workspace/session-active" || (rpc.details && rpc.details.activity))) return true;
1461
- return /workspace\/session-active|WorkspaceArchiveError|still running|still active/i.test(String((error && error.message) || ""));
1462
- }
1463
1274
  function hostWorkspaceApi(ctx) {
1464
1275
  return probeService(ctx, "uiWorkspace") || ctx.workspaces || {};
1465
1276
  }
@@ -1537,7 +1348,6 @@ window.__ModuleLoader__.load({
1537
1348
  }
1538
1349
  tryOpenListedSession(id, hostOpen);
1539
1350
  };
1540
- let channelSkin = "native";
1541
1351
 
1542
1352
  function preferredAssistant(defaults, readModel) {
1543
1353
  const main = typeof readModel === "function" ? readModel() : null;
@@ -1835,9 +1645,7 @@ window.__ModuleLoader__.load({
1835
1645
  return { name: preset.name || preset.id, description: preset.description };
1836
1646
  }
1837
1647
  function PlusIcon() {
1838
- return h("svg", { viewBox: "0 0 16 16", width: 14, height: 14, fill: "none", "aria-hidden": "true" },
1839
- h("path", { d: "M8 3v10M3 8h10", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round" }),
1840
- );
1648
+ return h(IconPlusOutline, { size: 14 });
1841
1649
  }
1842
1650
 
1843
1651
  function formatProviderLabel(provider, defaultLabel, modelT) {
@@ -2324,9 +2132,7 @@ window.__ModuleLoader__.load({
2324
2132
  );
2325
2133
  }
2326
2134
  function FeedbackIcon() {
2327
- return h("svg", { viewBox: "0 0 16 16", width: 16, height: 16, "aria-hidden": true, focusable: "false" },
2328
- h("path", { fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round", d: "M9.5 2.5 13.5 6.5 6 14H2v-4z" }),
2329
- );
2135
+ return h(IconEditOutline, { size: 16 });
2330
2136
  }
2331
2137
 
2332
2138
  function SettingsPage(props) {
@@ -2564,870 +2370,704 @@ window.__ModuleLoader__.load({
2564
2370
  }),
2565
2371
  );
2566
2372
  }
2567
- const WB_CSS = `.dcu-wb,.ima-native{--dsh-session-list-edge-inset:var(--dsh-sidebar-inline-padding,12px);--dsh-session-list-scrollbar-width:5px;--dsh-session-list-scrollbar-offset:2px;display:flex;flex:1;min-width:0;min-height:0;flex-direction:column;padding:0;padding-right:var(--dsh-session-list-edge-inset);box-sizing:border-box;overflow:hidden;color:var(--dsw-alias-label-primary,var(--ima-text));font:14px/20px inherit}.ima-n-toolbar{box-sizing:border-box;flex:none;height:36px;margin:2px -4px 4px 0;padding-left:4px;display:flex;justify-content:flex-end;align-items:center;gap:4px;overflow:visible;position:relative;z-index:2;color:var(--dsw-alias-label-tertiary,#81858C);border-radius:12px}.ima-n-head-label{white-space:nowrap;min-width:0;max-width:45%;flex:none;line-height:20px;font-size:14px;overflow:hidden;transition:max-width .18s var(--ds-ease-in-out,ease),margin-right .18s var(--ds-ease-in-out,ease),opacity .12s var(--ds-ease-in-out,ease),transform .18s var(--ds-ease-in-out,ease),visibility 0s linear}.ima-n-toolbar.is-search .ima-n-head-label{opacity:0;visibility:hidden;max-width:0;margin-right:-4px;transform:translate(-4px);transition-delay:0s,0s,0s,0s,.18s}.ima-n-search-slot{box-sizing:border-box;min-width:28px;max-width:28px;transition:max-width .18s var(--ds-ease-in-out,ease);flex:none;align-items:center;margin-left:auto;display:flex;position:relative;z-index:2}.ima-n-toolbar.is-search .ima-n-search-slot{flex:1;min-width:0;max-width:100%}.ima-n-search{box-sizing:border-box;cursor:text;width:100%;height:28px;color:var(--dsw-alias-label-secondary);transition:width .18s var(--ds-ease-in-out,ease),padding .18s var(--ds-ease-in-out,ease),border-color .18s var(--ds-ease-in-out,ease);background:transparent;border:none;border-radius:50%;flex:none;align-items:center;margin:0;padding:0;display:flex;overflow:hidden}.ima-n-toolbar.is-search .ima-n-search{border:.5px solid var(--dsw-alias-border-l4);width:calc(100% + 4px);height:30px;color:var(--dsw-alias-label-caption);border-radius:10px;margin-inline:-2px;padding:0 4px 0 0}.ima-n-search-btn,.ima-n-head-btn{cursor:pointer;width:28px;height:28px;min-width:28px;min-height:28px;position:relative;z-index:1;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-radius:50%;flex:none;justify-content:center;align-items:center;padding:0;display:inline-flex}.ima-n-toolbar.is-search .ima-n-search-btn{width:28px;height:30px}.ima-n-search-btn:hover,.ima-n-head-btn:hover,.ima-n-head-btn.on,.ima-n-head-btn.is-on{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06));color:var(--dsw-alias-label-primary,var(--ima-text))}.ima-n-toolbar.is-search .ima-n-search-btn:hover{background:transparent}.ima-n-head-acts{opacity:1;visibility:visible;max-width:32px;transition:max-width .18s var(--ds-ease-in-out,ease),opacity .12s var(--ds-ease-in-out,ease),transform .18s var(--ds-ease-in-out,ease),visibility 0s linear;flex:none;align-items:center;gap:4px;display:flex;overflow:visible;position:relative}.ima-n-toolbar.is-search .ima-n-head-acts{opacity:0;visibility:hidden;pointer-events:none;max-width:0;transform:translate(4px);transition-delay:0s,0s,0s,.18s}.ima-n-search-input{display:none;opacity:0;pointer-events:none;width:0;min-width:0;flex:none;color:var(--dsw-alias-label-primary,var(--ima-text));transition:opacity .12s var(--ds-ease-in-out,ease);background:transparent;border:none;outline:none;flex:1;font-size:13px;line-height:18px}.ima-n-toolbar.is-search .ima-n-search-input{display:block;opacity:1;pointer-events:auto;margin-left:-2px;width:auto;flex:1;min-width:0}.ima-n-search-input::placeholder{color:var(--dsw-alias-label-tertiary,#81858C)}.ima-n-search-clear{cursor:pointer;width:24px;height:24px;color:var(--dsw-alias-label-secondary);background:transparent;border:none;border-radius:50%;flex:none;justify-content:center;align-items:center;padding:0;display:inline-flex}.ima-n-search-clear:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))}@media (prefers-reduced-motion:reduce){.ima-n-head-label,.ima-n-search-slot,.ima-n-search,.ima-n-head-acts,.ima-n-search-input{transition:none}}.ima-n-list-area,.dcu-wb-list-area{min-height:0;margin-left:-4px;margin-right:calc(-1 * var(--dsh-session-list-edge-inset));flex-direction:column;flex:1;padding-left:4px;display:flex;overflow:visible}.ima-native-tree,.dcu-wb-tree{flex:1;min-width:0;min-height:0;overflow-x:hidden;overflow-y:auto;user-select:none;margin-left:-4px;margin-right:var(--dsh-session-list-scrollbar-offset);padding-top:0;padding-bottom:16px;padding-left:4px;padding-right:calc(var(--dsh-session-list-edge-inset) - var(--dsh-session-list-scrollbar-width) - var(--dsh-session-list-scrollbar-offset));scrollbar-gutter:stable}.ima-native-project,.dcu-wb-project{position:relative;min-width:0;max-width:100%}.ima-native-project+.ima-native-project,.dcu-wb-project+.dcu-wb-project{margin-top:4px}.ima-native-project>*+*,.dcu-wb-project>*+*{margin-top:2px}.dcu-wb *,.ima-native *{box-sizing:border-box}
2568
- .dcu-wb-tree,.ima-native-tree{flex:1;min-height:0}
2569
- .dcu-wb-project-head,.ima-native-head,.dcu-wb-session,.ima-native-session{display:flex;align-items:center;gap:6px;width:100%;border:0;border-radius:8px;padding:0 8px;background:transparent;color:inherit;cursor:pointer;font:inherit;text-align:left}
2570
- .dcu-wb-project-head,.ima-native-head{height:34px}
2571
- .dcu-wb-project-head:hover,.dcu-wb-session:hover,.dcu-wb-session.dcu-wb-selected,.ima-native-head:hover,.ima-native-session:hover,.ima-native-session.on{background:var(--dsw-alias-interactive-bg-hover,var(--dcu-sidebar-hover,rgba(255,255,255,.06)))}
2572
- .dcu-wb-folder,.ima-native-folder{display:grid;place-items:center;flex:none;width:16px;height:20px}
2573
- .dcu-wb-project-title,.dcu-wb-session-title,.ima-native-title,.ima-n-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;line-height:20px;flex:1;font-weight:400}
2574
- .dcu-wb-session-title,.ima-native-session .ima-native-title{font-weight:400}
2575
- .dcu-wb-session,.ima-native-session{position:relative;min-height:32px;padding-left:32px}
2576
- .dcu-wb-actions,.ima-native-actions{display:none;align-items:center;flex:none}
2577
- .dcu-wb-session:hover .dcu-wb-actions,.dcu-wb-session.dcu-wb-menu-open .dcu-wb-actions,.ima-native-session:hover .ima-native-actions,.ima-native-session.menu-on .ima-native-actions{display:flex}
2578
- .dcu-wb-more,.ima-native-more{display:grid;place-items:center;width:20px;height:20px;border:0;border-radius:4px;padding:0;background:transparent;color:var(--dsw-alias-label-secondary,var(--ima-muted));cursor:pointer}
2579
- .dcu-wb-empty,.ima-native-empty{padding:16px 12px;color:var(--dsw-alias-label-tertiary,var(--ima-muted));font-size:13px}
2580
- .ima-rename{flex:1;min-width:0;min-height:28px;padding:2px 8px;border-radius:6px;border:1px solid var(--dsw-alias-stroke-primary,var(--ima-line));background:transparent;color:inherit;font:inherit}
2581
- .ima-n-row,.ima-n-sess{display:flex;align-items:center;max-width:100%;gap:6px;border-radius:8px;padding:0 8px;padding-inline-start:calc(8px + var(--dsh-workspace-indent,0px));cursor:pointer;user-select:none;width:100%;border:0;background:transparent;color:var(--dsw-alias-label-primary,var(--ima-text));font:14px/20px inherit;text-align:left;box-sizing:border-box}
2582
- .ima-n-row{height:34px}
2583
- .ima-n-sess{height:32px;gap:0;position:relative;appearance:none}
2584
- .ima-n-row:hover,.ima-n-sess:hover,.ima-n-sess.on,.ima-n-sess.is-on,.ima-n-row.menu-on,.ima-n-row.is-menu,.ima-n-sess.menu-on,.ima-n-sess.is-menu{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))}
2585
- .ima-n-row.has-current-session .ima-n-folder{color:var(--dsw-alias-state-business-primary,#4c8dff)}
2586
- .ima-n-project-text{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}
2587
- .ima-n-row .ima-n-acts{height:20px}
2588
- .ima-n-sess.is-flat-idle .ima-n-title{margin-left:0}
2589
- .ima-n-sess:focus{outline:none}.ima-n-sess:focus-visible:not(.is-on){box-shadow:inset 0 0 0 2px var(--dsw-alias-state-business-primary,#4c8dff)}
2590
- .ima-n-slot{flex:none;width:16px;min-width:16px;height:20px;display:inline-flex;align-items:center;justify-content:center;color:var(--dsw-alias-label-tertiary,#81858C)}
2591
- .ima-n-folder{color:var(--dsw-alias-label-secondary,#9ca39f)}.ima-n-folder>.ima-logo,.dcu-wb-folder>.ima-logo{width:16px;height:16px;display:block;line-height:0}.ima-n-folder>.ima-logo svg{width:16px;height:16px;display:block}.ima-n-folder>.ima-logo svg,.dcu-wb-folder>.ima-logo svg{width:16px;height:16px;display:block}
2592
- .ima-n-lead{color:var(--dsw-alias-label-tertiary,#81858C)}
2593
- .ima-n-corner{color:var(--dsw-alias-label-caption,#ADB2B8);width:8px}
2594
- .ima-n-hover{--dsw-hovercard-bg:#2C2C2E;position:fixed;z-index:100;box-sizing:border-box;width:244px;padding:12px 16px;border:0;border-radius:12px;background:var(--dsw-hovercard-bg);box-shadow:var(--dsw-shadow-lv3,0 8px 24px rgba(0,0,0,.36))}
2595
- .ima-n-hover-content{display:flex;flex-direction:column;gap:8px;min-width:0}
2596
- .ima-n-hover-title{color:#fff;font-size:14px;line-height:20px;font-weight:400;overflow-wrap:break-word}
2597
- .ima-n-hover-time{margin:0;color:#cfd3d6;font-size:12px;line-height:16px}
2598
- .ima-n-hover-state{display:flex;align-items:center;gap:8px;margin:0;font-size:12px;line-height:20px;color:#adb2b8}
2599
- .ima-n-hover-dot{width:10px;height:10px;border-radius:50%;background:var(--dsw-alias-state-success-primary,#34c759);flex:none;position:relative}
2600
- .ima-n-hover-dot.is-run{background:var(--dsw-static-deepseek-450,#4c8dff)}
2601
- .ima-n-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;line-height:20px;flex:1;font-weight:400}
2602
- .ima-n-sess .ima-n-title{margin:0 6px 0 4px}
2603
- .ima-n-sess .ima-n-title[data-scrolled]{mask-image:linear-gradient(90deg,#0000,#000 12px)}
2604
- .ima-n-sess .ima-n-title[data-clipped]{mask-image:linear-gradient(270deg,#0000,#000 12px)}
2605
- .ima-n-sess .ima-n-title[data-scrolled][data-clipped]{mask-image:linear-gradient(90deg,#0000,#000 12px calc(100% - 12px),#0000)}
2606
- @media (hover:hover){.ima-n-sess:hover .ima-n-title,.ima-n-sess.is-menu .ima-n-title{text-overflow:clip}}
2607
- .ima-n-sess.is-archived .ima-n-title,.ima-n-sess.is-archived .ima-n-time{color:var(--dsw-alias-label-caption,#ADB2B8)}
2608
- .ima-n-time{flex:none;font-size:10px;line-height:16px;color:var(--dsw-alias-label-caption,#ADB2B8);white-space:nowrap}
2609
- .ima-n-acts{flex:none;display:none;align-items:center;gap:10px}
2610
- .ima-n-row:hover .ima-n-acts,.ima-n-sess:hover .ima-n-acts,.ima-n-row.menu-on .ima-n-acts,.ima-n-row.is-menu .ima-n-acts,.ima-n-sess.menu-on .ima-n-acts,.ima-n-sess.is-menu .ima-n-acts{display:inline-flex}
2611
- .ima-n-sess:hover .ima-n-time,.ima-n-sess.menu-on .ima-n-time,.ima-n-sess.is-menu .ima-n-time{display:none}
2612
- .ima-n-ico{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;border:0;border-radius:4px;padding:0;background:transparent;cursor:pointer;color:var(--dsw-alias-label-tertiary,#81858C)}
2613
- .ima-n-ico:hover{color:var(--dsw-alias-label-primary,var(--ima-text))}
2614
- .ima-n-menu{position:fixed;right:auto;top:auto;z-index:4000;min-width:218px;max-width:360px;box-sizing:border-box;padding:4px;display:flex;flex-direction:column;border:1px solid var(--dsw-alias-border-inverted,rgba(255,255,255,.12));border-radius:12px;background:var(--dsw-specific-menu,var(--dsw-alias-bg-layer-2));box-shadow:var(--dsw-shadow-lv3,0 8px 24px rgba(0,0,0,.36))}
2615
- .ima-n-menu button{display:flex;align-items:center;gap:8px;width:100%;min-height:40px;padding:8px 10px;border:0;border-radius:10px;background:transparent;cursor:pointer;font-size:14px;line-height:22px;color:var(--dsw-alias-label-primary,var(--ima-text));text-align:left}
2616
- .ima-n-menu button:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06))}
2617
- .ima-n-mi{display:inline-flex;flex:none;width:16px;height:16px;align-items:center;justify-content:center;color:var(--dsw-alias-label-tertiary,#81858C)}
2618
- .ima-n-menu button.danger{color:var(--dsw-alias-state-error-primary,#f85149)}
2619
- .ima-n-menu button.danger .ima-n-mi{color:inherit}
2620
- .ima-n-menu button.danger:hover{background:var(--dsw-alias-interactive-bg-hover-danger,rgba(248,81,73,.12))}
2621
- .ima-n-rename{flex:1;min-width:0;margin:0 6px 0 4px;border:.5px solid var(--dsw-alias-border-l4);border-radius:4px;outline:none;background:var(--dsw-alias-button-elevated-fill,rgba(255,255,255,.04));color:inherit;padding:0 2px;font-size:14px;line-height:20px}
2622
- .ima-n-dialog-actions{display:flex;justify-content:flex-end;gap:8px}
2623
- .ima-n-dialog-status{margin-top:12px;color:var(--dsw-alias-label-secondary);font-size:13px;line-height:20px}
2624
- .ima-n-dialog-error{margin-top:12px;color:var(--dsw-alias-state-error-primary,#f85149);font-size:13px;line-height:20px}
2625
- .ima-n-restore{flex:none;border:0;background:transparent;color:var(--dsw-alias-label-secondary,#c9cdd4);font:12px/16px inherit;padding:2px 4px;cursor:pointer}`;
2626
-
2627
- function NativeSvg(viewBox, size, children) {
2628
- return h("svg", { viewBox, width: size, height: size, fill: "none", xmlns: "http://www.w3.org/2000/svg", "aria-hidden": "true" }, children);
2629
- }
2630
- function NativePath(d, extra) {
2631
- return h("path", Object.assign({ d, fill: "currentColor" }, extra || {}));
2632
- }
2373
+
2633
2374
  function IconChevron() {
2634
- return NativeSvg("0 0 14 14", 14, NativePath("M4.25 2.828v8.344c0 .49.592.735.939.389l4.172-4.172a.55.55 0 0 0 0-.778L5.189 2.439c-.347-.347-.939-.101-.939.389Z"));
2635
- }
2636
- function IconSearchFallback(props) {
2637
- const size = props && props.size ? props.size : 16;
2638
- return NativeSvg("0 0 16 16", size, [
2639
- NativePath("M11.894845 6.647401C11.894845 3.725463 9.534486 1.356779 6.623219 1.35657C3.711786 1.35657 1.351635 3.725338 1.351635 6.647401C1.351843 9.569296 3.711911 11.938273 6.623219 11.938273C9.534361 11.938064 11.894637 9.569171 11.894845 6.647401ZM13.245462 6.647401C13.245254 10.317935 10.280401 13.293613 6.623219 13.293821C2.965871 13.293821 0.000204 10.31806 0 6.647401C0 2.976574 2.965746 0 6.623219 0C10.280526 0.000205 13.245462 2.9767 13.245462 6.647401Z"),
2640
- NativePath("M16.000417 15.041079L15.044449 16.000433L11.530434 12.473588L12.486298 11.514234L16.000417 15.041079Z"),
2641
- ]);
2642
- }
2643
- function IconSlidersFallback() {
2644
- return NativeSvg("0 0 16 16", 16, NativePath("M2.2 3.4h6.05a1.85 1.85 0 0 0 3.5 0H13.8v1.3H11.75a1.85 1.85 0 0 0-3.5 0H2.2V3.4Zm8.6 1.15A.75.75 0 1 1 10.05 4.55.75.75 0 0 1 10.8 4.55ZM2.2 7.35h2.35a1.85 1.85 0 0 0 3.5 0H13.8v1.3H8.05a1.85 1.85 0 0 0-3.5 0H2.2V7.35Zm4.1 1.15A.75.75 0 1 1 5.55 8.5a.75.75 0 0 1 .75-.75ZM2.2 11.3h7.35a1.85 1.85 0 0 0 3.5 0H13.8v1.3h-.75a1.85 1.85 0 0 0-3.5 0H2.2v-1.3Zm9.9 1.15a.75.75 0 1 1-.75-.75.75.75 0 0 1 .75.75Z"));
2375
+ return h(IconChevronRightOutline, { size: 14 });
2645
2376
  }
2646
- function IconCloseOutlineFallback(props) {
2647
- const size = props && props.size ? props.size : 16;
2648
- return NativeSvg("0 0 16 16", size, [
2649
- NativePath("M14.1168 13.197L13.197 14.1167L1.8833 2.80303L2.80309 1.88324L14.1168 13.197Z"),
2650
- NativePath("M13.197 1.88326L14.1168 2.80305L2.80309 14.1168L1.8833 13.197L13.197 1.88326Z"),
2651
- ]);
2377
+
2378
+ // ---------------------------------------------------------------------
2379
+ // 频道页签:直接复用官方 WorkspaceBrowser。
2380
+ // 自绘列表已删除;官方树不可用时只显示不可用提示。
2381
+ // ---------------------------------------------------------------------
2382
+
2383
+ const CHANNEL_WORKSPACE_PREFIX = "dsh-im-channel:";
2384
+ const CHANNEL_GROUP_IDS = ["weixin", "wecom", "qq", "feishu", "lark", "dingtalk", "telegram", "discord", "slack"];
2385
+ const EMPTY_SESSION_STATE = { ids: [], byId: {}, current: null };
2386
+ const EMPTY_WORKSPACE_STATE = { items: [], archivedSessionIds: [], pinnedSessionIds: [], state: "idle", phase: "ready", error: null };
2387
+ const CHANNEL_GROUP_OPTION_ATTR = "data-ima-channel-group-option";
2388
+ const CHANNEL_GROUP_MENU_ATTR = "data-ima-channel-group-menu";
2389
+
2390
+ function channelWorkspaceId(id) {
2391
+ return CHANNEL_WORKSPACE_PREFIX + String(id || "");
2652
2392
  }
2653
- function IconListFallback() {
2654
- return NativeSvg("0 0 16 16", 16, NativePath("M3 4h10M3 8h10M3 12h10", { fill: "none", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round" }));
2655
- }
2656
- function IconArchiveCheckFallback() {
2657
- return NativeSvg("0 0 16 16", 16, NativePath("M3 6.5h10v6H3v-6Zm1.2-2.5h7.6L13 6.5H3L4.2 4Zm2.3 5.2 1.3 1.3 2.6-2.6", { fill: "none", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" }));
2658
- }
2659
- const IconSearchOutline = hostOrFallback(IconSearchHost, IconSearchFallback);
2660
- const IconCloseFill = hostOrFallback(IconCloseFillHost, IconCloseOutlineFallback);
2661
- const IconSlidersTwoOutline = hostOrFallback(IconSlidersHost, IconSlidersFallback);
2662
- const IconFlatList = hostOrFallback(IconFlatListOutline, IconListFallback);
2663
- const IconWorkspaceTree = hostOrFallback(pickHostIcon("IconWorkspaceTreeOutlineRegular", "IconWorkspaceTreeOutline16"), function IconTreeFallback() {
2664
- return NativeSvg("0 0 16 16", 16, NativePath("M3 3h4v3H3V3Zm6 1h4M3 10h4v3H3v-3Zm6 1.5h4M7 4.5h2M7 11.5h2", { fill: "none", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round" }));
2665
- });
2666
- const IconArchiveCheckOutline = hostOrFallback(IconArchiveCheckHost, IconArchiveCheckFallback);
2667
- function ChannelWorkspaceHead({ query, sort, groupMode, archivedFilter, onQuery, onSort, onGroupMode, onArchivedFilterChange, t = fallbackT }) {
2668
- const [searching, setSearching] = useState(!!query);
2669
- const [filterOpen, setFilterOpen] = useState(false);
2670
- const searchSize = searching ? 11 : 14;
2671
- const items = [
2672
- { type: "label", id: "group-by", text: t("rail.group") },
2673
- { id: "workspace", label: t("rail.byWorkspace"), icon: h(IconFolderClose, { size: 16 }) },
2674
- { id: "workspace-tree", label: t("rail.byWorkspaceTree"), icon: h(IconWorkspaceTree, { size: 16 }) },
2675
- { id: "flat", label: t("rail.list"), icon: h(IconFlatList, { size: 16 }) },
2676
- { type: "separator", id: "order-by-separator" },
2677
- { type: "label", id: "order-by", text: t("rail.sort") },
2678
- { id: "updated", label: t("rail.recent"), icon: h(IconClockOutline, { size: 16 }) },
2679
- { type: "separator", id: "archived-filter-separator" },
2680
- { type: "label", id: "filter-by", text: t("rail.filter") },
2681
- { id: "show-archived", label: t("rail.showArchived"), icon: h(IconArchiveOutline20, { size: 16 }) },
2682
- { id: "only-archived", label: t("rail.onlyArchived"), icon: h(IconArchiveCheckOutline, { size: 16 }) },
2683
- ];
2684
- const selectedIds = [
2685
- groupMode === "list" ? "flat" : groupMode,
2686
- "updated",
2687
- ...(archivedFilter === "show" ? ["show-archived"] : []),
2688
- ...(archivedFilter === "only" ? ["only-archived"] : []),
2689
- ];
2690
- return h("div", { className: searching ? "ima-n-toolbar is-search" : "ima-n-toolbar" },
2691
- h("span", { className: "ima-n-head-label" }, groupMode === "list" ? t("rail.sessions") : t("rail.workspace")),
2692
- h("div", { className: "ima-n-search-slot" },
2693
- h("div", { className: "ima-n-search", onClick: () => { setFilterOpen(false); setSearching(true); } },
2694
- h("button", { type: "button", className: "ima-n-search-btn", "aria-label": t("rail.search"), "aria-expanded": searching, onClick: () => { setFilterOpen(false); setSearching(true); } }, h(IconSearchOutline, { size: searchSize })),
2695
- h("input", { className: "ima-n-search-input", value: query, placeholder: t("rail.searchPlaceholder"), "aria-label": t("rail.search"), tabIndex: searching ? 0 : -1, "aria-hidden": !searching, onChange: (e) => onQuery(e.target.value), onKeyDown: (e) => { if (e.key === "Escape") { onQuery(""); setSearching(false); } } }),
2696
- searching && h("button", { type: "button", className: "ima-n-search-clear", "aria-label": t("rail.clearSearch"), onClick: (e) => { e.stopPropagation(); onQuery(""); setSearching(false); } }, h(IconCloseFill, { size: 14 })),
2697
- ),
2698
- ),
2699
- h("div", { className: "ima-n-head-acts" },
2700
- h(HostMenu, {
2701
- open: filterOpen,
2702
- onClose: () => { setFilterOpen(false); },
2703
- items,
2704
- selectedIds,
2705
- align: "end",
2706
- dense: true,
2707
- portal: true,
2708
- onSelect: (id) => {
2709
- if (id === "workspace" || id === "workspace-tree") onGroupMode(id);
2710
- if (id === "flat") onGroupMode("list");
2711
- if (id === "updated") onSort("time");
2712
- if (id === "show-archived") onArchivedFilterChange(archivedFilter === "show" ? "default" : "show");
2713
- if (id === "only-archived") onArchivedFilterChange(archivedFilter === "only" ? "default" : "only");
2714
- setFilterOpen(false);
2715
- },
2716
- anchor: h("button", { type: "button", className: filterOpen ? "ima-n-head-btn is-on" : "ima-n-head-btn", "aria-label": t("rail.filter"), "aria-expanded": filterOpen, onClick: () => setFilterOpen((open) => !open) }, h(IconSlidersTwoOutline, { size: 16 })),
2717
- }),
2718
- ),
2719
- );
2393
+
2394
+ function channelIdFromWorkspaceId(workspaceId) {
2395
+ const value = String(workspaceId || "");
2396
+ return value.startsWith(CHANNEL_WORKSPACE_PREFIX) ? value.slice(CHANNEL_WORKSPACE_PREFIX.length) : undefined;
2720
2397
  }
2721
- function ChannelSettingsIcon() {
2722
- return typeof IconSettingsOutline16 === "function" ? h(IconSettingsOutline16, { size: 16 }) : NativeSvg("0 0 16 16", 16, NativePath("M8 2.2a1.2 1.2 0 0 1 1.15.84l.16.5.5.16A1.2 1.2 0 0 1 11.3 5.3l.45.45a1.2 1.2 0 0 1 0 1.7l-.45.45-.16.5A1.2 1.2 0 0 1 10.3 9.7l-.5.16-.16.5A1.2 1.2 0 0 1 8.5 11.8H7.5a1.2 1.2 0 0 1-1.15-.84l-.16-.5-.5-.16A1.2 1.2 0 0 1 4.7 9.7l-.45-.45a1.2 1.2 0 0 1 0-1.7l.45-.45.16-.5A1.2 1.2 0 0 1 5.7 5.3l.5-.16.16-.5A1.2 1.2 0 0 1 7.5 2.2H8Zm0 4.3A1.5 1.5 0 1 0 8 9.5 1.5 1.5 0 0 0 8 6.5Z"));
2723
- }
2724
- function SessionHoverStatusDot({ running, size }) {
2725
- if (typeof StateDot === "function") return h(StateDot, { state: running ? "ongoing" : "idle", size: size || 10 });
2726
- return h("span", { className: running ? "ima-n-hover-dot is-run" : "ima-n-hover-dot" });
2727
- }
2728
- function SessionHoverContent({ title, time, running, statuses, t = fallbackT }) {
2729
- const rows = statuses && statuses.length ? statuses : [{ state: running ? "ongoing" : "idle", label: running ? t("rail.running") : t("rail.idle") }];
2730
- return h("div", { className: "ima-n-hover-content" },
2731
- h("div", { className: "ima-n-hover-title" }, title),
2732
- time ? h("div", { className: "ima-n-hover-time" }, time) : null,
2733
- rows.map((status) => h("div", { key: status.label, className: "ima-n-hover-state" },
2734
- status.state === "archived"
2735
- ? h(IconArchiveOutline20, { size: 14 })
2736
- : (typeof StateDot === "function"
2737
- ? h(StateDot, { state: status.state === "ongoing" ? "ongoing" : status.state === "warning" ? "warning" : status.state === "done" ? "done" : "idle", size: 10 })
2738
- : h(SessionHoverStatusDot, { running: status.state === "ongoing" })),
2739
- status.label,
2740
- )),
2741
- );
2398
+
2399
+ /** 频道页签把官方“添加工作区”按钮复用为“添加频道”。 */
2400
+ function channelAddFlow(select) {
2401
+ return select(true);
2742
2402
  }
2743
- function SessionHoverCard({ title, time, running, statuses, style, cardRef, onMouseEnter, onMouseLeave, t = fallbackT }) {
2744
- return h("div", { className: "ima-n-hover", style, ref: cardRef, onMouseEnter, onMouseLeave },
2745
- h(SessionHoverContent, { title, time, running, statuses, t }),
2746
- );
2403
+
2404
+ function noopChannelAction() {}
2405
+
2406
+ function copySessionOrders(orders) {
2407
+ return Object.fromEntries(Object.entries(orders || {}).map(([key, order]) => [key, [...order]]));
2747
2408
  }
2748
- function nativeSessionHoverStyle(row, card, viewport) {
2749
- const pad = 8;
2750
- const left = row.right + pad;
2751
- const top = row.top + card.height > viewport.height - pad
2752
- ? Math.max(pad, viewport.height - card.height - pad)
2753
- : Math.max(pad, row.top);
2754
- return { position: "fixed", zIndex: 4100, left: Math.round(left) + "px", top: Math.round(top) + "px" };
2755
- }
2756
- function relativeTimeParts(value, now) {
2757
- const ts = Date.parse(value || "");
2758
- if (!Number.isFinite(ts)) return null;
2759
- const MIN = 6e4;
2760
- const HOUR = 36e5;
2761
- const DAY = 864e5;
2762
- const diff = Math.max(0, (now || Date.now()) - ts);
2763
- if (diff < MIN) return { unit: "now", n: 0 };
2764
- if (diff < HOUR) return { unit: "minutes", n: Math.floor(diff / MIN) };
2765
- if (diff < DAY) return { unit: "hours", n: Math.floor(diff / HOUR) };
2766
- if (diff < 30 * DAY) return { unit: "days", n: Math.floor(diff / DAY) };
2767
- if (diff < 365 * DAY) return { unit: "months", n: Math.floor(diff / (30 * DAY)) };
2768
- return { unit: "years", n: Math.floor(diff / (365 * DAY)) };
2769
- }
2770
- function timeLabel(value, t = fallbackT, now) {
2771
- const parts = relativeTimeParts(value, now);
2772
- if (!parts) return "";
2773
- return parts.unit === "now" ? t("time.now") : t("time." + parts.unit, { n: parts.n, count: parts.n });
2774
- }
2775
- function hoverTimeLabel(value, t = fallbackT, now) {
2776
- const parts = relativeTimeParts(value, now);
2777
- if (!parts) return "";
2778
- if (parts.unit === "now") return t("time.now");
2779
- return t("time.ago", { t: t("time." + parts.unit, { n: parts.n, count: parts.n }) });
2780
- }
2781
- function ChannelSessionRow({ sess, selected, onOpen, onChanged, skin, sessionActions, sessionById, menuOpen, onMenuChange, canDelete, onDeleteSession, flat, renderSlot, onStopArchive, hoverStatuses }) {
2782
- const t = arguments[0].t || fallbackT;
2783
- const menu = !!menuOpen;
2784
- const setMenu = (next) => onMenuChange(!!next);
2785
- const [renaming, setRenaming] = useState(false);
2786
- const [draft, setDraft] = useState(sess.title || sess.chatId || "");
2787
- const rowRef = useRef(null);
2788
- const titleRef = useRef(null);
2789
- const titleFrame = useRef({ id: 0 });
2790
- const hoverRef = useRef(null);
2791
- const hoverTimer = useRef(null);
2792
- const [hoverOpen, setHoverOpen] = useState(false);
2793
- const [hoverStyle, setHoverStyle] = useState({});
2794
- const title = sess.title || sess.chatId;
2795
- const native = skin !== "codex";
2796
- const useOfficialHover = native && typeof HoverCard === "function";
2797
- const archived = !!arguments[0].archived;
2798
- const running = !!(sess.running || (sessionById && sessionById[sess.sessionId] && sessionById[sess.sessionId].running));
2799
- const statuses = hoverStatuses || channelSessionHoverStatuses({ running, archived }, t);
2800
- const primary = statuses.find((status) => status.state !== "archived");
2801
- const showDot = !archived && primary && primary.state !== "idle";
2802
- const trailing = primary && primary.trailing;
2803
- const hoverTitle = (sessionById && sessionById[sess.sessionId] && (sessionById[sess.sessionId].displayTitle || sessionById[sess.sessionId].title)) || title;
2804
- const showHover = () => {
2805
- if (menu || !native) return;
2806
- if (hoverTimer.current) window.clearTimeout(hoverTimer.current);
2807
- hoverTimer.current = window.setTimeout(() => setHoverOpen(true), 500);
2409
+
2410
+ /** 频道页签使用独立视图状态,不污染上方任务树。 */
2411
+ function createChannelViewStore() {
2412
+ let state = {
2413
+ groupBy: "channel",
2414
+ orderBy: "updated",
2415
+ groupExpansion: {},
2416
+ sessionOrderByAccount: {},
2417
+ archivedFilter: "default",
2808
2418
  };
2809
- const hideHover = () => {
2810
- if (hoverTimer.current) window.clearTimeout(hoverTimer.current);
2811
- setHoverOpen(false);
2419
+ const listeners = new Set();
2420
+ const publish = (next) => {
2421
+ state = next;
2422
+ for (const listener of listeners) listener();
2812
2423
  };
2813
- useLayoutEffect(() => {
2814
- if (!hoverOpen || menu || !rowRef.current) return;
2815
- const card = hoverRef.current;
2816
- const size = card ? { width: card.offsetWidth || 220, height: card.offsetHeight || 96 } : { width: 220, height: 96 };
2817
- const update = () => {
2818
- if (!rowRef.current) return;
2819
- setHoverStyle(nativeSessionHoverStyle(rowRef.current.getBoundingClientRect(), {
2820
- width: (hoverRef.current && hoverRef.current.offsetWidth) || size.width,
2821
- height: (hoverRef.current && hoverRef.current.offsetHeight) || size.height,
2822
- }, { width: window.innerWidth, height: window.innerHeight }));
2823
- };
2824
- update();
2825
- window.addEventListener("resize", update);
2826
- document.addEventListener("scroll", update, true);
2827
- return () => {
2828
- window.removeEventListener("resize", update);
2829
- document.removeEventListener("scroll", update, true);
2830
- };
2831
- }, [hoverOpen, menu, title, running]);
2832
- useEffect(() => () => {
2833
- if (hoverTimer.current) window.clearTimeout(hoverTimer.current);
2834
- stopSessionTitleMarquee(titleRef.current, titleFrame.current);
2835
- }, []);
2836
- const rowClass = native
2837
- ? ("ima-n-sess" + (selected ? " is-on" : "") + (menu ? " is-menu" : "") + (archived ? " is-archived" : ""))
2838
- : ("dcu-wb-session" + (selected ? " dcu-wb-selected" : "") + (menu ? " dcu-wb-menu-open" : ""));
2839
- const syncList = (groups) => { if (groups) onChanged(groups); };
2840
- const run = (action, extra) => {
2841
- setMenu(false);
2842
- if (action === "copy-title") { try { navigator.clipboard.writeText(title); } catch { /* ignore */ } return; }
2843
- if (action === "copy-id") { try { navigator.clipboard.writeText(sess.sessionId); } catch { /* ignore */ } return; }
2844
- if (action === "copy-link") {
2845
- try { navigator.clipboard.writeText(location.origin + "/?session=" + encodeURIComponent(sess.sessionId)); } catch { /* ignore */ }
2846
- return;
2847
- }
2848
- const acts = sessionActions || {};
2849
- const afterHost = () => api("/sessions/" + (action === "archive" || action === "delete" || action === "fork" ? "remove" : action), {
2850
- method: "POST",
2851
- headers: { "content-type": "application/json" },
2852
- body: JSON.stringify(Object.assign({ sessionId: sess.sessionId }, extra || {})),
2853
- }).then((data) => { if (data.ok) syncList(data.groups); }).catch(() => undefined);
2854
- if (action === "rename" && typeof acts.renameSession === "function") {
2855
- Promise.resolve(acts.renameSession(sess.sessionId, (extra && extra.title) || title)).then(afterHost).catch((error) => console.warn("[dsh-im-connect] 重命名失败", error));
2856
- return;
2857
- }
2858
- if (action === "unarchive") {
2859
- if (typeof acts.unarchiveSession === "function") {
2860
- Promise.resolve(acts.unarchiveSession(sess.sessionId)).catch((error) => console.warn("[dsh-im-connect] 恢复失败", error));
2861
- }
2862
- return;
2863
- }
2864
- if (action === "archive") {
2865
- const cleanupMissing = async error => {
2866
- if (openStopArchive(error, { id: sess.sessionId, title }, onStopArchive)) return;
2867
- console.warn("[dsh-im-connect] archive failed", error);
2868
- try {
2869
- const data = await api("/sessions/cleanup-missing", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sessionId: sess.sessionId }) });
2870
- if (data.ok) { syncList(data.groups); return; }
2871
- } catch (cleanupError) { console.warn("[dsh-im-connect] cleanup failed", cleanupError); }
2872
- window.alert(t("rail.archiveFailed"));
2873
- };
2874
- if (typeof acts.archiveSession === "function") {
2875
- Promise.resolve().then(() => acts.archiveSession(sess.sessionId)).then(afterHost).catch(cleanupMissing);
2876
- } else {
2877
- void cleanupMissing(new Error("Host archive unavailable"));
2424
+ const actions = {
2425
+ setGroupBy(mode) {
2426
+ if (mode !== state.groupBy) publish(Object.assign({}, state, { groupBy: mode }));
2427
+ },
2428
+ setOrderBy(mode, initialOrders) {
2429
+ if (mode === state.orderBy) return;
2430
+ publish(Object.assign({}, state, {
2431
+ orderBy: mode,
2432
+ sessionOrderByAccount: mode === "manual" ? copySessionOrders(initialOrders) : {},
2433
+ }));
2434
+ },
2435
+ setGroupExpanded(key, expanded) {
2436
+ if (state.groupExpansion[key] === expanded) return;
2437
+ publish(Object.assign({}, state, { groupExpansion: Object.assign({}, state.groupExpansion, { [key]: expanded }) }));
2438
+ },
2439
+ retainAccountKeys(workspaceKeys) {
2440
+ const retained = new Set(workspaceKeys || []);
2441
+ const groupExpansion = Object.fromEntries(Object.entries(state.groupExpansion).filter(([key]) => retained.has(key)));
2442
+ const sessionOrderByAccount = Object.fromEntries(Object.entries(state.sessionOrderByAccount).filter(([key]) => retained.has(key)));
2443
+ if (Object.keys(groupExpansion).length === Object.keys(state.groupExpansion).length
2444
+ && Object.keys(sessionOrderByAccount).length === Object.keys(state.sessionOrderByAccount).length) return;
2445
+ publish(Object.assign({}, state, { groupExpansion, sessionOrderByAccount }));
2446
+ },
2447
+ setSessionOrder(accountKey, order, initialOrders) {
2448
+ const sessionOrderByAccount = state.orderBy === "manual"
2449
+ ? Object.assign({}, state.sessionOrderByAccount, { [accountKey]: [...order] })
2450
+ : Object.assign(copySessionOrders(initialOrders), { [accountKey]: [...order] });
2451
+ publish(Object.assign({}, state, { orderBy: "manual", sessionOrderByAccount }));
2452
+ },
2453
+ syncSessionOrders(orders) {
2454
+ if (state.orderBy !== "manual") return;
2455
+ publish(Object.assign({}, state, { sessionOrderByAccount: Object.assign({}, state.sessionOrderByAccount, copySessionOrders(orders)) }));
2456
+ },
2457
+ pinSessionOrder(sessionId, accountKeys, source) {
2458
+ const selected = new Set(accountKeys || []);
2459
+ const sessionOrderByAccount = Object.fromEntries(Object.entries((source && source.members) || {}).map(([key, members]) => {
2460
+ const current = state.sessionOrderByAccount[key] || members;
2461
+ const order = selected.has(key) ? [sessionId, ...current.filter((id) => id !== sessionId)] : [...current];
2462
+ return [key, order];
2463
+ }));
2464
+ publish(Object.assign({}, state, { sessionOrderByAccount }));
2465
+ },
2466
+ setArchivedFilter(filter) {
2467
+ if (filter !== state.archivedFilter) publish(Object.assign({}, state, { archivedFilter: filter }));
2468
+ },
2469
+ ensureExpanded(keys) {
2470
+ let changed = false;
2471
+ const groupExpansion = Object.assign({}, state.groupExpansion);
2472
+ for (const key of keys || []) {
2473
+ if (key === "" || groupExpansion[key] !== undefined) continue;
2474
+ groupExpansion[key] = true;
2475
+ changed = true;
2878
2476
  }
2879
- return;
2880
- }
2881
- if ((action === "delete" || action === "remove") && typeof acts.deleteSession === "function") {
2882
- Promise.resolve(acts.deleteSession(sess.sessionId)).then(() => afterHost()).catch((error) => console.warn("[dsh-im-connect] 删除失败", error));
2883
- return;
2884
- }
2885
- if (action === "fork" && typeof acts.forkSession === "function") {
2886
- Promise.resolve(acts.forkSession(sess.sessionId)).catch(() => undefined);
2887
- return;
2888
- }
2889
- const localAction = action === "delete" ? "remove" : action;
2890
- api("/sessions/" + localAction, {
2891
- method: "POST",
2892
- headers: { "content-type": "application/json" },
2893
- body: JSON.stringify(Object.assign({ sessionId: sess.sessionId }, extra || {})),
2894
- }).then((data) => { if (data.ok) syncList(data.groups); }).catch(() => undefined);
2895
- };
2896
- if (renaming) {
2897
- return h("div", { className: rowClass, ref: rowRef },
2898
- h("input", {
2899
- className: native ? "ima-n-rename" : "ima-rename",
2900
- value: draft,
2901
- autoFocus: true,
2902
- "aria-label": t("rail.renameAria"),
2903
- onChange: (e) => setDraft(e.target.value),
2904
- onClick: (e) => e.stopPropagation(),
2905
- onKeyDown: (e) => {
2906
- if (e.key === "Enter") { e.preventDefault(); setRenaming(false); run("rename", { title: draft.trim() || title }); }
2907
- if (e.key === "Escape") { e.preventDefault(); setRenaming(false); setDraft(title); }
2908
- },
2909
- onBlur: () => { setRenaming(false); if (draft.trim() && draft.trim() !== title) run("rename", { title: draft.trim() }); },
2910
- }),
2911
- );
2912
- }
2913
- const displayTitle = String(hoverTitle || title).trim() || title;
2914
- // 0.1.7 的 Menu 渲染 children。不请求 pin,频道会话不提供置顶。更早版本不渲染 children,仍用下面的 items。
2915
- const menuSlotItems = hostMenuRendersChildren()
2916
- ? ["rename", "fork", "archive", "archive-manager.delete-session"].map((only) => renderHostSlot(renderSlot, "sidebar.workspaces.session.menu.item", {
2917
- sessionId: sess.sessionId,
2918
- displayTitle,
2919
- }, { hookContext: [menu, (open) => onMenuChange(!!open)], only }))
2920
- : undefined;
2921
- // 宿主槽位被跳过时不能留下一个空菜单,退回本地 items。
2922
- const menuSlot = menuSlotItems && menuSlotItems.some((node) => node != null) ? menuSlotItems : undefined;
2923
- const menuItems = menuSlot !== undefined ? [] : (archived
2924
- ? [
2925
- { id: "unarchive", label: t("rail.unarchive"), icon: h(IconArchiveOutline20, { size: 16 }) },
2926
- ...(canDelete ? [{ id: "delete-session", label: t("rail.deleteSession"), icon: h(IconTrashOutline16), danger: true }] : []),
2927
- ]
2928
- : [
2929
- { id: "rename", label: t("rail.rename"), icon: h(IconEditOutline16) },
2930
- { id: "fork", label: t("rail.fork"), icon: h(IconBranchOutline16) },
2931
- { id: "archive", label: t("rail.archive"), icon: h(IconArchiveOutline20, { size: 16 }) },
2932
- ...(canDelete ? [{ id: "delete-session", label: t("rail.deleteSession"), icon: h(IconTrashOutline16), danger: true }] : []),
2933
- ]);
2934
- const row = h("div", {
2935
- ref: rowRef,
2936
- className: rowClass,
2937
- role: "treeitem",
2938
- tabIndex: 0,
2939
- "aria-selected": selected,
2940
- "data-n-menu-root": sess.sessionId,
2941
- onClick: () => { setMenu(false); hideHover(); onOpen(sess.sessionId); },
2942
- onMouseEnter: () => {
2943
- startSessionTitleMarquee(titleRef.current, titleFrame.current);
2944
- if (!useOfficialHover) showHover();
2477
+ if (changed) publish(Object.assign({}, state, { groupExpansion }));
2945
2478
  },
2946
- onMouseLeave: () => {
2947
- stopSessionTitleMarquee(titleRef.current, titleFrame.current);
2948
- if (!useOfficialHover) hideHover();
2479
+ };
2480
+ return {
2481
+ getSnapshot: () => state,
2482
+ subscribe(listener) {
2483
+ listeners.add(listener);
2484
+ return () => listeners.delete(listener);
2949
2485
  },
2950
- onKeyDown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setMenu(false); onOpen(sess.sessionId); } },
2951
- onContextMenu: (e) => { e.preventDefault(); e.stopPropagation(); hideHover(); onMenuChange(true); },
2952
- },
2953
- native && h("span", { className: "ima-n-slot" }, showDot && typeof StateDot === "function" ? h(StateDot, { state: primary.state === "ongoing" ? "ongoing" : primary.state === "warning" ? "warning" : "done", size: 10 }) : null),
2954
- h("span", {
2955
- ref: native ? titleRef : undefined,
2956
- className: native ? "ima-n-title" : "dcu-wb-session-title",
2957
- onDoubleClick: (e) => {
2958
- if (!sessionActions || typeof sessionActions.renameSession !== "function") return;
2959
- e.stopPropagation();
2960
- setRenaming(true);
2961
- },
2962
- }, title),
2963
- native && h("span", { className: "ima-n-time", "aria-hidden": trailing ? true : undefined }, trailing || timeLabel(sess.updatedAt, t)),
2964
- h("span", { className: native ? "ima-n-acts" : "dcu-wb-actions" },
2965
- menuSlot === undefined && archived && h("button", {
2966
- type: "button",
2967
- className: "ima-n-restore",
2968
- onMouseDown: (e) => e.stopPropagation(),
2969
- onClick: (e) => { e.stopPropagation(); run("unarchive"); },
2970
- }, t("rail.unarchive")),
2971
- h(HostMenu, {
2972
- open: menu,
2973
- onClose: () => { onMenuChange(false); },
2974
- items: menuItems,
2975
- onSelect: (action) => {
2976
- onMenuChange(false);
2977
- if (action === "rename") setRenaming(true);
2978
- if (action === "fork") run("fork");
2979
- if (action === "archive") run("archive");
2980
- if (action === "unarchive") run("unarchive");
2981
- if (action === "delete-session") onDeleteSession && onDeleteSession();
2982
- },
2983
- portal: true,
2984
- closeOnPointerLeave: true,
2985
- anchor: h("button", {
2986
- type: "button",
2987
- className: native ? "ima-n-ico" : "dcu-wb-more",
2988
- "data-ima-session-more": "",
2989
- "aria-expanded": menu,
2990
- "aria-label": t("action.more", { channel: title }),
2991
- onMouseDown: (e) => e.stopPropagation(),
2992
- onClick: (e) => { e.stopPropagation(); hideHover(); onMenuChange(!menu); },
2993
- }, h(IconEllipsisOutline16, { size: 16 })),
2994
- }, menuSlot),
2995
- renderHostSlot(renderSlot, "sidebar.workspaces.session.row.action", { sessionId: sess.sessionId, displayTitle }, { only: "archive" }),
2996
- ),
2997
- !useOfficialHover && hoverOpen && !menu && native && typeof document !== "undefined" && ReactDOM.createPortal(h(SessionHoverCard, {
2998
- title: hoverTitle,
2999
- time: hoverTimeLabel(sess.updatedAt, t),
3000
- running,
3001
- statuses,
3002
- t,
3003
- style: hoverStyle,
3004
- cardRef: hoverRef,
3005
- onMouseEnter: showHover,
3006
- onMouseLeave: hideHover,
3007
- }), document.body),
3008
- );
3009
- if (useOfficialHover) {
3010
- return h(HoverCard, {
3011
- anchor: row,
3012
- content: h(SessionHoverContent, { title: hoverTitle, time: hoverTimeLabel(sess.updatedAt, t), running, statuses, t }),
3013
- openDelayMs: 800,
3014
- disabled: menu,
3015
- copyText: displayTitle,
3016
- copyLabel: t("copy"),
3017
- copiedLabel: t("hover.copied"),
3018
- });
2486
+ actions,
2487
+ };
2488
+ }
2489
+
2490
+ let sharedChannelViewStore;
2491
+ function getChannelViewStore() {
2492
+ sharedChannelViewStore = sharedChannelViewStore || createChannelViewStore();
2493
+ return sharedChannelViewStore;
2494
+ }
2495
+
2496
+ const channelSessionStateCache = new WeakMap();
2497
+ const channelSyntheticWorkspaceCache = new WeakMap();
2498
+ const channelRealWorkspaceCache = new WeakMap();
2499
+
2500
+ /** 只保留 /channels 分组里的会话,避免官方树出现“未分组”桶。 */
2501
+ function channelMemberSessionState(state, memberIds) {
2502
+ const src = state || EMPTY_SESSION_STATE;
2503
+ const hit = channelSessionStateCache.get(src);
2504
+ if (hit && hit.ids === memberIds) return hit.result;
2505
+ const ids = (src.ids || []).filter((id) => memberIds.has(String(id)));
2506
+ const result = cacheFilteredSessions(src, ids);
2507
+ channelSessionStateCache.set(src, { ids: memberIds, result });
2508
+ return result;
2509
+ }
2510
+
2511
+ function channelGroupsFromSessionState(state, t) {
2512
+ const groups = new Map(CHANNEL_GROUP_IDS.map((id) => [id, {
2513
+ id,
2514
+ label: channelLabel({ id }, t),
2515
+ sessions: [],
2516
+ }]));
2517
+ const src = state || EMPTY_SESSION_STATE;
2518
+ for (const id of src.ids || []) {
2519
+ const group = groups.get(channelIdOfSession(id));
2520
+ const session = src.byId && src.byId[id];
2521
+ if (group && session) group.sessions.push({ sessionId: id, updatedAt: session.updatedAt });
3019
2522
  }
3020
- return row;
2523
+ return [...groups.values()].filter((group) => group.sessions.length > 0);
3021
2524
  }
3022
2525
 
3023
- function ChannelGroupRow({ id, name, expanded, hasCurrentSession, menuOpen, canArchiveGroup, channelLogo = true, onToggle, onMenuChange, onChannelSettings, onArchiveGroup, t = fallbackT }) {
3024
- const items = [
3025
- ...(channelLogo ? [{ id: "channel-settings", label: t("rail.channelSettings"), icon: h(ChannelSettingsIcon) }] : []),
3026
- ...(canArchiveGroup ? [
3027
- { type: "separator", id: "archive-separator" },
3028
- { id: "archive-group", label: t("rail.archiveGroup"), icon: h(IconArchiveOutline20, { size: 16 }), danger: true },
3029
- ] : []),
3030
- ];
3031
- const rowClass = "ima-n-row" + (hasCurrentSession ? " has-current-session" : "") + (menuOpen ? " is-menu" : "");
3032
- return h("div", {
3033
- className: rowClass,
3034
- role: "treeitem",
3035
- "aria-expanded": expanded,
3036
- "data-n-group": id,
3037
- onClick: onToggle,
3038
- },
3039
- h("span", { className: "ima-n-slot ima-n-folder" }, channelLogo ? h(Logo, { id, small: true }) : h(IconFolderClose, { size: 16 })),
3040
- h("span", { className: "ima-n-project-text" }, h("span", { className: "ima-n-title" }, name)),
3041
- h("span", { className: "ima-n-acts" },
3042
- h(HostMenu, {
3043
- open: menuOpen,
3044
- onClose: () => { onMenuChange(false); },
3045
- items,
3046
- onSelect: (action) => {
3047
- onMenuChange(false);
3048
- if (action === "channel-settings") onChannelSettings && onChannelSettings();
3049
- if (action === "archive-group") onArchiveGroup && onArchiveGroup();
3050
- },
3051
- portal: true,
3052
- closeOnPointerLeave: true,
3053
- anchor: h("button", {
3054
- type: "button",
3055
- className: "ima-n-ico",
3056
- "aria-label": t("rail.groupActions", { name }),
3057
- onMouseDown: (e) => e.stopPropagation(),
3058
- onClick: (e) => { e.stopPropagation(); onMenuChange(!menuOpen); },
3059
- }, h(IconEllipsisOutline16, { size: 16 })),
3060
- }),
3061
- ),
3062
- );
2526
+ function channelGroupCreatedAt(group) {
2527
+ let earliest = Infinity;
2528
+ for (const session of group.sessions || []) {
2529
+ const timestamp = Date.parse(session.updatedAt || "");
2530
+ if (Number.isFinite(timestamp) && timestamp < earliest) earliest = timestamp;
2531
+ }
2532
+ return new Date(Number.isFinite(earliest) ? earliest : 0).toISOString();
3063
2533
  }
3064
2534
 
3065
- function ChannelRail(props) {
3066
- if (typeof props.useSessions === "function" || typeof props.useWorkspaces === "function") return h(ChannelRailWithSessions, props);
3067
- return h(ChannelRailView, props);
2535
+ /**
2536
+ * 按频道分组:每个频道合成一个官方 WorkspaceView。
2537
+ * 保留宿主的 phase/state/归档集合,官方浏览器才能正常渲染。
2538
+ */
2539
+ function syntheticChannelWorkspaceState(state, groups, t) {
2540
+ const src = state || EMPTY_WORKSPACE_STATE;
2541
+ const key = groups.map((group) => [
2542
+ group.id,
2543
+ channelLabel(group, t),
2544
+ channelGroupCreatedAt(group),
2545
+ (group.sessions || []).map((session) => session.sessionId).join(","),
2546
+ ].join("\0")).join("\0\0");
2547
+ const hit = channelSyntheticWorkspaceCache.get(src);
2548
+ if (hit && hit.key === key) return hit.result;
2549
+ const items = groups.filter((group) => (group.sessions || []).length > 0).map((group) => {
2550
+ const workspaceId = channelWorkspaceId(group.id);
2551
+ return {
2552
+ workspaceId,
2553
+ id: workspaceId,
2554
+ title: channelLabel(group, t),
2555
+ path: "",
2556
+ sessionIds: (group.sessions || []).map((session) => session.sessionId),
2557
+ createdAt: channelGroupCreatedAt(group),
2558
+ };
2559
+ });
2560
+ const result = Object.assign({}, src, { items, phase: "ready" });
2561
+ channelSyntheticWorkspaceCache.set(src, { key, result });
2562
+ return result;
3068
2563
  }
3069
2564
 
3070
- function ChannelRailWithSessions(props) {
3071
- const selectedId = typeof props.useSessions === "function"
3072
- ? props.useSessions((state) => currentSessionId(state))
3073
- : (props.selectedId || null);
3074
- const archivedIds = typeof props.useWorkspaces === "function"
3075
- ? props.useWorkspaces((state) => (state && state.archivedSessionIds) || [])
3076
- : (props.archivedIds || []);
3077
- const sessionById = typeof props.useSessions === "function"
3078
- ? props.useSessions((state) => (state && state.byId) || {})
3079
- : {};
3080
- const workspaceItems = typeof props.useWorkspaces === "function"
3081
- ? props.useWorkspaces((state) => (state && state.items) || [])
3082
- : (props.workspaceItems || []);
3083
- const sessionStatuses = typeof props.useSessionStatus === "function"
3084
- ? props.useSessionStatus((state) => state)
3085
- : props.sessionStatuses;
3086
- const projections = typeof props.useSessions === "function"
3087
- ? props.useSessions((state) => (state && state.projectionsBySession) || {})
3088
- : (props.projections || {});
3089
- return h(ChannelRailView, Object.assign({}, props, {
3090
- selectedId: selectedId || props.selectedId || null,
3091
- archivedIds,
3092
- sessionById,
3093
- workspaceItems,
3094
- sessionStatuses,
3095
- projections,
3096
- }));
2565
+ /** 按工作区/工作区树:保留真实工作区,只过滤出频道会话。 */
2566
+ function channelRealWorkspaceState(state, memberIds) {
2567
+ const src = state || EMPTY_WORKSPACE_STATE;
2568
+ const hit = channelRealWorkspaceCache.get(src);
2569
+ if (hit && hit.ids === memberIds) return hit.result;
2570
+ const items = (src.items || []).map((workspace) => {
2571
+ const sessionIds = (workspace.sessionIds || []).filter((id) => memberIds.has(String(id)));
2572
+ return sessionIds.length === (workspace.sessionIds || []).length
2573
+ ? workspace
2574
+ : Object.assign({}, workspace, { sessionIds });
2575
+ });
2576
+ const result = Object.assign({}, src, { items });
2577
+ channelRealWorkspaceCache.set(src, { ids: memberIds, result });
2578
+ return result;
3097
2579
  }
3098
2580
 
3099
- function ChannelRailView(props) {
3100
- const t = props.t || fallbackT;
3101
- const [groups, setGroups] = useState([]);
3102
- const [folded, setFolded] = useState({});
3103
- const [error, setError] = useState("");
3104
- const [openMenu, setOpenMenu] = useState();
3105
- const [openGroupMenu, setOpenGroupMenu] = useState();
3106
- const [query, setQuery] = useState("");
3107
- const [sort, setSort] = useState("time");
3108
- const [groupMode, setGroupMode] = useState("workspace");
3109
- const [archiveManagerInstalled, setArchiveManagerInstalled] = useState(() => typeof document !== "undefined" && hasArchiveManagerPlugin(document));
3110
- const [deleteTarget, setDeleteTarget] = useState();
3111
- const [deleteBusy, setDeleteBusy] = useState(false);
3112
- const [deleteError, setDeleteError] = useState();
3113
- const [archiveGroupTarget, setArchiveGroupTarget] = useState();
3114
- const [archiveGroupBusy, setArchiveGroupBusy] = useState(false);
3115
- const [archiveGroupError, setArchiveGroupError] = useState();
3116
- const [archivedFilter, setArchivedFilter] = useState("default");
3117
- const [stopArchiveTarget, setStopArchiveTarget] = useState();
3118
- const [stopArchiveBusy, setStopArchiveBusy] = useState(false);
3119
- const [stopArchiveError, setStopArchiveError] = useState();
3120
- const selectedId = props.selectedId;
3121
- const archived = new Set(props.archivedIds || []);
3122
- const skin = props.skin || channelSkin;
3123
- const native = skin !== "codex";
3124
- const open = (id) => openListedSession(resolveHostSessionId(id, props.sessionById), props.openSession || props.open);
3125
- const canDelete = canDeleteChannelSession(archiveManagerInstalled, props.deleteSession);
3126
- const canArchiveGroup = canArchiveChannelGroup(archiveManagerInstalled, props.archiveSession);
3127
- useEffect(() => {
3128
- ensureStyle();
3129
- return channelRefresh.subscribe((data, error) => {
3130
- if (error) { setError(t("error.connection")); return; }
3131
- if (data.ok) { setGroups(data.groups || []); setError(""); }
3132
- else setError(serverText(data.error, t) || t("error.load"));
2581
+ let channelIconCssValue;
2582
+
2583
+ /** 把 React 元素渲染成可直接注入官方 DOM 的 HTML。 */
2584
+ function channelMarkup(element) {
2585
+ if (typeof document === "undefined") return "";
2586
+ const hasCreateRoot = typeof ReactDOM.createRoot === "function";
2587
+ const createRoot = ReactDOM.createRoot || function createRootFallback(host) {
2588
+ return {
2589
+ render(node) { if (typeof ReactDOM.render === "function") ReactDOM.render(node, host); },
2590
+ unmount() { if (typeof ReactDOM.unmountComponentAtNode === "function") ReactDOM.unmountComponentAtNode(host); },
2591
+ };
2592
+ };
2593
+ try {
2594
+ const host = document.createElement("div");
2595
+ const root = createRoot(host);
2596
+ try {
2597
+ if (hasCreateRoot && typeof ReactDOM.flushSync === "function") ReactDOM.flushSync(() => root.render(element));
2598
+ else root.render(element);
2599
+ return host.innerHTML;
2600
+ } finally {
2601
+ try { root.unmount(); } catch { /* ignore */ }
2602
+ }
2603
+ } catch {
2604
+ return "";
2605
+ }
2606
+ }
2607
+
2608
+ const channelLogoUrlCache = new Map();
2609
+ /** 频道品牌标 data URL,供分组头和会话行复用。 */
2610
+ function channelLogoUrl(id) {
2611
+ if (channelLogoUrlCache.has(id)) return channelLogoUrlCache.get(id);
2612
+ const markup = channelMarkup(h(BrandMark, { id, compact: true }));
2613
+ const url = markup ? `url("data:image/svg+xml,${encodeURIComponent(markup)}")` : "";
2614
+ channelLogoUrlCache.set(id, url);
2615
+ return url;
2616
+ }
2617
+
2618
+ /** 频道分组头图标:用品牌标覆盖官方文件夹图标,并保持悬停时可见。 */
2619
+ function channelIconCss() {
2620
+ if (channelIconCssValue !== undefined) return channelIconCssValue;
2621
+ if (typeof document === "undefined") {
2622
+ channelIconCssValue = "";
2623
+ return channelIconCssValue;
2624
+ }
2625
+ channelIconCssValue = CHANNEL_GROUP_IDS.map((id) => {
2626
+ const logo = channelLogoUrl(id);
2627
+ if (!logo) return "";
2628
+ const row = `[data-row-key="workspace:${channelWorkspaceId(id)}"]`;
2629
+ return `.ima-channel-official ${row}>span:first-child>svg{display:none!important}`
2630
+ + `.ima-channel-official ${row}>span:first-child{display:inline-flex!important;background:${logo} center/contain no-repeat!important}`
2631
+ // 宿主在悬停时用 chevron 换掉文件夹;频道分组保持品牌图标可见。
2632
+ + `.ima-channel-official ${row}:hover>span:first-child{display:inline-flex!important}`
2633
+ + `.ima-channel-official ${row}:hover>span:nth-child(2){display:none!important}`;
2634
+ }).join("");
2635
+ return channelIconCssValue;
2636
+ }
2637
+
2638
+ let channelWorkspaceIconCache = { key: "", css: "" };
2639
+ /**
2640
+ * 按工作区/工作区树分组时,如果某个工作区的频道会话都来自同一个频道,
2641
+ * 用频道品牌标替换文件夹。混合频道的工作区保持官方文件夹图标。
2642
+ */
2643
+ function channelWorkspaceIconCss(workspaces, memberIds) {
2644
+ const entries = [];
2645
+ for (const workspace of workspaces || []) {
2646
+ const workspaceId = workspace.workspaceId || workspace.id;
2647
+ if (!workspaceId) continue;
2648
+ const channels = new Set();
2649
+ for (const sessionId of workspace.sessionIds || []) {
2650
+ if (!memberIds.has(String(sessionId))) continue;
2651
+ const channelId = channelIdOfSession(sessionId);
2652
+ if (channelId) channels.add(channelId);
2653
+ }
2654
+ if (channels.size !== 1) continue;
2655
+ const channelId = [...channels][0];
2656
+ if (!channelLogoUrl(channelId)) continue;
2657
+ entries.push([workspaceId, channelId]);
2658
+ }
2659
+ const key = entries.map(([workspaceId, channelId]) => `${workspaceId}\0${channelId}`).join("\0\0");
2660
+ if (channelWorkspaceIconCache.key === key) return channelWorkspaceIconCache.css;
2661
+ const css = entries.map(([workspaceId, channelId]) => {
2662
+ const logo = channelLogoUrl(channelId);
2663
+ const row = `[data-row-key=${JSON.stringify("workspace:" + workspaceId)}]`;
2664
+ const scope = `.ima-channel-official:not([data-mode="channel"])`;
2665
+ return `${scope} ${row}>span:first-child>svg{display:none!important}`
2666
+ + `${scope} ${row}>span:first-child{display:inline-flex!important;background:${logo} center/contain no-repeat!important}`
2667
+ + `${scope} ${row}:hover>span:first-child{display:inline-flex!important}`
2668
+ + `${scope} ${row}:hover>span:nth-child(2){display:none!important}`;
2669
+ }).join("");
2670
+ channelWorkspaceIconCache = { key, css };
2671
+ return css;
2672
+ }
2673
+
2674
+ let settingsNavIconMaskValue;
2675
+ /** 设置导航图标:用宿主 IconQueueOutline 的几何生成 mask,保持皮肤安全。 */
2676
+ function settingsNavIconMask() {
2677
+ if (settingsNavIconMaskValue !== undefined) return settingsNavIconMaskValue;
2678
+ const markup = channelMarkup(h(IconQueueOutline, { size: 16 })).split("currentColor").join("#000");
2679
+ settingsNavIconMaskValue = `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
2680
+ return settingsNavIconMaskValue;
2681
+ }
2682
+
2683
+ /**
2684
+ * 官方视图选项菜单没有扩展位,注入第四个分组项「按频道」。
2685
+ * 只在频道页签挂载期间生效。
2686
+ */
2687
+ function installChannelGroupOption(options) {
2688
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {};
2689
+ let frame;
2690
+ const closeMenu = () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
2691
+ const inject = (menu) => {
2692
+ const text = menu.textContent || "";
2693
+ if (!options.groupLabel || !options.workspaceLabel
2694
+ || !text.includes(options.groupLabel) || !text.includes(options.workspaceLabel)) return;
2695
+ if (menu.querySelector(`[${CHANNEL_GROUP_OPTION_ATTR}="true"]`) !== null) return;
2696
+ const items = [...menu.querySelectorAll('button[role="menuitem"]')];
2697
+ const first = items[0];
2698
+ if (!first) return;
2699
+ const wrapper = first.parentElement;
2700
+ if (!wrapper) return;
2701
+ const clone = wrapper.cloneNode(true);
2702
+ const button = clone.querySelector('button[role="menuitem"]');
2703
+ if (!button) return;
2704
+ button.setAttribute(CHANNEL_GROUP_OPTION_ATTR, "true");
2705
+ button.removeAttribute("aria-disabled");
2706
+ button.removeAttribute("disabled");
2707
+ button.disabled = false;
2708
+ button.classList.remove("danger");
2709
+ for (const svg of button.querySelectorAll(":scope > svg")) svg.remove();
2710
+ const spans = button.querySelectorAll("span");
2711
+ if (spans[0] !== undefined) spans[0].innerHTML = channelMarkup(h(IconQueueOutline, { size: 16 }));
2712
+ if (spans[1] !== undefined) spans[1].textContent = options.label;
2713
+ else button.textContent = options.label;
2714
+ if (options.checked) {
2715
+ const check = document.createElement("span");
2716
+ check.innerHTML = channelMarkup(h(IconCheckOutline, { size: 16 }));
2717
+ const svg = check.firstElementChild;
2718
+ if (svg !== null) {
2719
+ if (svg.style) svg.style.marginLeft = "auto";
2720
+ button.append(svg);
2721
+ }
2722
+ }
2723
+ button.addEventListener("click", (event) => {
2724
+ event.preventDefault();
2725
+ event.stopPropagation();
2726
+ closeMenu();
2727
+ window.setTimeout(options.onSelect, 0);
3133
2728
  });
3134
- }, []);
3135
- useEffect(() => {
3136
- if (typeof document === "undefined" || typeof MutationObserver === "undefined") return undefined;
3137
- const refresh = () => { setArchiveManagerInstalled(hasArchiveManagerPlugin(document)); };
3138
- refresh();
3139
- const observer = new MutationObserver(refresh);
3140
- observer.observe(document.documentElement, { childList: true, subtree: true });
3141
- return () => observer.disconnect();
3142
- }, []);
3143
- const confirmDelete = () => {
3144
- if (!deleteTarget || typeof props.deleteSession !== "function" || deleteBusy) return;
3145
- const target = deleteTarget;
3146
- setDeleteBusy(true);
3147
- setDeleteError(undefined);
3148
- Promise.resolve(props.deleteSession(target.id))
3149
- .then(() => api("/sessions/remove", {
3150
- method: "POST",
3151
- headers: { "content-type": "application/json" },
3152
- body: JSON.stringify({ sessionId: target.id }),
3153
- }).then((data) => { if (data.ok && data.groups) setGroups(data.groups); }).catch(() => undefined))
3154
- .then(() => { setDeleteTarget(undefined); })
3155
- .catch((caught) => { setDeleteError(caught instanceof Error ? caught.message : t("error.action")); })
3156
- .finally(() => { setDeleteBusy(false); });
2729
+ wrapper.parentElement?.insertBefore(clone, wrapper);
3157
2730
  };
3158
- const confirmArchiveGroup = () => {
3159
- if (!archiveGroupTarget || typeof props.archiveSession !== "function" || archiveGroupBusy) return;
3160
- const target = archiveGroupTarget;
3161
- setArchiveGroupBusy(true);
3162
- setArchiveGroupError(undefined);
3163
- archiveChannelGroup(target.sessionIds, props.archiveSession)
3164
- .then(() => channelRefresh.invalidate().catch(() => undefined))
3165
- .then(() => { setArchiveGroupTarget(undefined); })
3166
- .catch((caught) => {
3167
- if (openStopArchive(caught, { id: target.id, title: target.name, sessionIds: target.sessionIds, group: true }, (next) => {
3168
- setArchiveGroupTarget(undefined);
3169
- setStopArchiveError(undefined);
3170
- setStopArchiveTarget(next);
3171
- })) return;
3172
- setArchiveGroupError(caught instanceof Error ? caught.message : t("error.action"));
3173
- })
3174
- .finally(() => { setArchiveGroupBusy(false); });
2731
+ const scan = () => {
2732
+ frame = undefined;
2733
+ for (const menu of document.querySelectorAll('[role="menu"]')) inject(menu);
3175
2734
  };
3176
- const confirmStopArchive = () => {
3177
- if (!stopArchiveTarget || typeof props.archiveSession !== "function" || stopArchiveBusy) return;
3178
- const target = stopArchiveTarget;
3179
- setStopArchiveBusy(true);
3180
- setStopArchiveError(undefined);
3181
- const work = finishStopArchive(target, props.archiveSession).then((kind) => {
3182
- if (kind === "group") return channelRefresh.invalidate().catch(() => undefined);
3183
- if (kind !== "session") return;
3184
- return api("/sessions/remove", {
3185
- method: "POST",
3186
- headers: { "content-type": "application/json" },
3187
- body: JSON.stringify({ sessionId: target.id }),
3188
- }).then((data) => { if (data.ok && data.groups) setGroups(data.groups); }).catch(() => undefined);
3189
- });
3190
- work
3191
- .then(() => { setStopArchiveTarget(undefined); })
3192
- .catch((caught) => { setStopArchiveError(caught instanceof Error ? caught.message : t("error.action")); })
3193
- .finally(() => { setStopArchiveBusy(false); });
2735
+ const schedule = () => {
2736
+ if (frame !== undefined) return;
2737
+ frame = window.requestAnimationFrame(scan);
2738
+ };
2739
+ const observer = new MutationObserver(schedule);
2740
+ observer.observe(document.body, { childList: true, subtree: true });
2741
+ schedule();
2742
+ return () => {
2743
+ if (frame !== undefined) window.cancelAnimationFrame(frame);
2744
+ observer.disconnect();
2745
+ for (const item of document.querySelectorAll(`[${CHANNEL_GROUP_OPTION_ATTR}="true"]`)) item.parentElement?.remove();
2746
+ };
2747
+ }
2748
+
2749
+ /**
2750
+ * 官方工作区分组菜单只有重命名/删除;频道组合成工作区需要「频道设置」,因此注入设置入口。
2751
+ */
2752
+ function installChannelGroupMenu(options) {
2753
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {};
2754
+ let channelId;
2755
+ let rememberedAt = 0;
2756
+ let frame;
2757
+ const closeMenu = () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
2758
+ const remember = (event) => {
2759
+ const target = event.target && typeof event.target.closest === "function" ? event.target : undefined;
2760
+ if (target === undefined) return;
2761
+ const row = target.closest(`[data-row-key^="workspace:${CHANNEL_WORKSPACE_PREFIX}"]`);
2762
+ if (row !== null) {
2763
+ const key = row.getAttribute("data-row-key") || "";
2764
+ channelId = channelIdFromWorkspaceId(key.slice("workspace:".length));
2765
+ rememberedAt = performance.now();
2766
+ return;
2767
+ }
2768
+ if (target.closest('[role="menu"]') === null) channelId = undefined;
2769
+ };
2770
+ const hiddenItems = new Map();
2771
+ const hideOthers = (menu, ours) => {
2772
+ for (const item of menu.querySelectorAll('button[role="menuitem"]')) {
2773
+ if (ours.has(item)) continue;
2774
+ if (!hiddenItems.has(item)) {
2775
+ hiddenItems.set(item, {
2776
+ display: item.style.display,
2777
+ ariaHidden: item.getAttribute("aria-hidden"),
2778
+ });
2779
+ }
2780
+ item.style.display = "none";
2781
+ item.setAttribute("aria-hidden", "true");
2782
+ }
2783
+ };
2784
+ const inject = (menu) => {
2785
+ if (channelId === undefined || performance.now() - rememberedAt > 2000) return;
2786
+ if (menu.querySelector(`[${CHANNEL_GROUP_MENU_ATTR}="true"]`) !== null) return;
2787
+ const items = [...menu.querySelectorAll('button[role="menuitem"]')];
2788
+ if (items.length === 0) return;
2789
+ const menuText = items.map((item) => item.textContent || "").join(" ");
2790
+ if (!/(删除工作区|Delete workspace)/i.test(menuText)) return;
2791
+ const group = options.resolve(channelId);
2792
+ if (!group) return;
2793
+ const template = items.find((item) => /^(重命名|Rename)$/i.test((item.textContent || "").trim()))
2794
+ || items.find((item) => !item.disabled && !/danger|删除|Delete/i.test(item.textContent || ""))
2795
+ || items[0];
2796
+ const wrapper = template.parentElement;
2797
+ if (!wrapper) return;
2798
+ const build = (label, icon, onClick) => {
2799
+ const clone = wrapper.cloneNode(true);
2800
+ const button = clone.querySelector('button[role="menuitem"]');
2801
+ if (!button) return undefined;
2802
+ clone.removeAttribute(CHANNEL_GROUP_MENU_ATTR);
2803
+ button.removeAttribute(CHANNEL_GROUP_MENU_ATTR);
2804
+ button.removeAttribute("aria-disabled");
2805
+ button.removeAttribute("disabled");
2806
+ button.disabled = false;
2807
+ button.style.opacity = "";
2808
+ button.style.cursor = "";
2809
+ button.classList.remove("danger");
2810
+ button.setAttribute(CHANNEL_GROUP_MENU_ATTR, "true");
2811
+ const spans = button.querySelectorAll("span");
2812
+ if (spans[0] !== undefined) spans[0].innerHTML = icon;
2813
+ if (spans[1] !== undefined) spans[1].textContent = label;
2814
+ else button.textContent = label;
2815
+ let fired = false;
2816
+ const activate = (event) => {
2817
+ if (fired) return;
2818
+ fired = true;
2819
+ event.preventDefault();
2820
+ event.stopPropagation();
2821
+ if (typeof event.stopImmediatePropagation === "function") event.stopImmediatePropagation();
2822
+ closeMenu();
2823
+ // 等宿主菜单完成卸载后再打开设置,避免同一次点击被菜单的关闭逻辑吞掉。
2824
+ window.setTimeout(onClick, 50);
2825
+ };
2826
+ button.addEventListener("click", activate);
2827
+ button.addEventListener("pointerup", (event) => {
2828
+ if (event.button === 0) activate(event);
2829
+ });
2830
+ return clone;
2831
+ };
2832
+ const node = build(options.settingsLabel, channelMarkup(h(ChannelMenuSettingsIcon)), () => options.onSettings(group));
2833
+ if (node) wrapper.parentElement?.insertBefore(node, wrapper);
2834
+ const injected = new Set(menu.querySelectorAll(`[${CHANNEL_GROUP_MENU_ATTR}="true"]`));
2835
+ if (injected.size > 0) hideOthers(menu, injected);
2836
+ };
2837
+ const scan = () => {
2838
+ frame = undefined;
2839
+ for (const menu of document.querySelectorAll('[role="menu"]')) inject(menu);
2840
+ };
2841
+ const schedule = () => {
2842
+ if (frame !== undefined) return;
2843
+ frame = window.requestAnimationFrame(scan);
2844
+ };
2845
+ document.addEventListener("pointerdown", remember, true);
2846
+ document.addEventListener("click", remember, true);
2847
+ const observer = new MutationObserver(schedule);
2848
+ observer.observe(document.body, { childList: true, subtree: true });
2849
+ schedule();
2850
+ return () => {
2851
+ if (frame !== undefined) window.cancelAnimationFrame(frame);
2852
+ observer.disconnect();
2853
+ document.removeEventListener("pointerdown", remember, true);
2854
+ document.removeEventListener("click", remember, true);
2855
+ for (const [item, previous] of hiddenItems) {
2856
+ item.style.display = previous.display;
2857
+ if (previous.ariaHidden === null) item.removeAttribute("aria-hidden");
2858
+ else item.setAttribute("aria-hidden", previous.ariaHidden);
2859
+ }
2860
+ hiddenItems.clear();
2861
+ for (const item of document.querySelectorAll(`[${CHANNEL_GROUP_MENU_ATTR}="true"]`)) item.parentElement?.remove();
3194
2862
  };
3195
- const needle = query.trim().toLowerCase();
3196
- const visibleGroups = groups.map((g) => {
3197
- const sessions = (g.sessions || []).map((sess) => {
3198
- const host = props.sessionById && props.sessionById[sess.sessionId];
3199
- // 手动标题及来源未知的旧名称,交给后端可靠标题事件同步。
3200
- if (sess.titleSource === "user" || (!sess.titleSource && typeof sess.title === "string" && sess.title.trim())) return sess;
3201
- return host && typeof host.title === "string" && host.title.trim()
3202
- ? Object.assign({}, sess, { title: host.title }) : sess;
3203
- }).filter((sess) => channelSessionVisible(sess.sessionId, archived, archivedFilter)).map((sess) => Object.assign({}, sess, { channelId: g.id }));
3204
- if (!needle) return Object.assign({}, g, { sessions });
3205
- const nameHit = String(channelLabel(g, t)).toLowerCase().includes(needle);
3206
- return Object.assign({}, g, { sessions: nameHit ? sessions : sessions.filter((sess) => String(sess.title || sess.chatId || "").toLowerCase().includes(needle)) });
3207
- }).filter((g) => (g.sessions || []).length > 0);
3208
- if (groupMode === "workspace-tree") {
3209
- const flat = visibleGroups.flatMap((g) => g.sessions || []);
3210
- visibleGroups.splice(0, visibleGroups.length, ...groupChannelSessionsByWorkspaceTree(flat, props.workspaceItems || [], t("rail.ungrouped")));
3211
- } else if (sort === "time") {
3212
- visibleGroups.sort((a, b) => {
3213
- const latest = (g) => Math.max(0, ...(g.sessions || []).map((sess) => Date.parse(sess.updatedAt || "") || 0));
3214
- return latest(b) - latest(a);
3215
- });
3216
- }
3217
- if (groupMode === "list") {
3218
- const sessions = visibleGroups.flatMap((g) => g.sessions || []);
3219
- if (sort === "time") sessions.sort((a, b) => (Date.parse(b.updatedAt || "") || 0) - (Date.parse(a.updatedAt || "") || 0));
3220
- visibleGroups.splice(0, visibleGroups.length);
3221
- if (sessions.length) visibleGroups.push({ id: "__flat__", label: "", sessions });
3222
- }
3223
- return h("div", { className: native ? "ima-native ima-rail" : "dcu-wb ima-rail" },
3224
- h("style", null, WB_CSS),
3225
- h(ChannelWorkspaceHead, { query, sort, groupMode, archivedFilter, onQuery: setQuery, onSort: setSort, onGroupMode: setGroupMode, onArchivedFilterChange: setArchivedFilter, t }),
3226
- h("div", { className: native ? "ima-n-list-area" : "dcu-wb-list-area" },
3227
- h("div", { className: native ? "ima-native-tree" : "dcu-wb-tree", role: "tree" },
3228
- error && h("div", { className: native ? "ima-native-empty" : "dcu-wb-empty" }, error),
3229
- !error && visibleGroups.length === 0 && h("div", { className: native ? "ima-native-empty" : "dcu-wb-empty" }, t("rail.empty")),
3230
- ...visibleGroups.map((g) => {
3231
- const visible = g.sessions || [];
3232
- const expanded = !folded[g.id];
3233
- const hasCurrentSession = typeof selectedId === "string" && visible.some((sess) => isCurrentListedSession(selectedId, sess.sessionId, props.sessionById));
3234
- const depth = g.depth || 0;
3235
- const channelLogo = groupMode !== "workspace-tree" || !!g.channelId;
3236
- const groupStyle = depth > 0 ? { "--dsh-workspace-indent": (depth * 12) + "px" } : undefined;
3237
- return h("div", { key: g.id || "ungrouped", className: native ? "ima-native-project" : "dcu-wb-project", style: groupStyle },
3238
- groupMode !== "list" && (g.keep || visible.length > 0) && (native
3239
- ? h(ChannelGroupRow, {
3240
- id: g.channelId || g.id,
3241
- channelLogo,
3242
- name: channelLabel(g, t),
3243
- expanded,
3244
- hasCurrentSession,
3245
- menuOpen: openGroupMenu === g.id,
3246
- canArchiveGroup,
3247
- onToggle: () => setFolded({ ...folded, [g.id]: !folded[g.id] }),
3248
- onMenuChange: (next) => {
3249
- setOpenMenu(undefined);
3250
- setOpenGroupMenu(next ? g.id : undefined);
3251
- },
3252
- onChannelSettings: () => {
3253
- const channelId = g.channelId || g.id;
3254
- if (typeof props.openChannelSettings === "function") props.openChannelSettings({ channelId, name: channelLabel({ id: channelId, label: g.label }, t) });
3255
- },
3256
- onArchiveGroup: () => {
3257
- setArchiveGroupError(undefined);
3258
- setArchiveGroupTarget({
3259
- id: g.id,
3260
- name: channelLabel(g, t),
3261
- sessionIds: visible.map((sess) => sess.sessionId),
3262
- });
3263
- },
3264
- t,
3265
- })
3266
- : h("button", {
3267
- className: "dcu-wb-project-head",
3268
- type: "button",
3269
- role: "treeitem",
3270
- "aria-expanded": expanded,
3271
- onClick: () => setFolded({ ...folded, [g.id]: !folded[g.id] }),
3272
- },
3273
- h("span", { className: "dcu-wb-folder" }, h(Logo, { id: g.id, small: true })),
3274
- h("span", { className: "dcu-wb-project-title" }, channelLabel(g, t)),
3275
- )
3276
- ),
3277
- (groupMode === "list" || !folded[g.id]) && visible.length > 0 && visible.map((sess) => h(ChannelSessionRow, {
3278
- key: sess.sessionId,
3279
- sess,
3280
- flat: groupMode === "list",
3281
- selected: isCurrentListedSession(selectedId, sess.sessionId, props.sessionById),
3282
- sessionById: props.sessionById,
3283
- menuOpen: openMenu === sess.sessionId,
3284
- onMenuChange: (next) => {
3285
- setOpenGroupMenu(undefined);
3286
- setOpenMenu(next ? sess.sessionId : undefined);
3287
- },
3288
- onOpen: (id) => { setOpenMenu(undefined); open(id); },
3289
- onChanged: (next) => setGroups(next),
3290
- canDelete,
3291
- onDeleteSession: () => {
3292
- setDeleteError(undefined);
3293
- setDeleteTarget({
3294
- id: sess.sessionId,
3295
- title: String((props.sessionById && props.sessionById[sess.sessionId] && (props.sessionById[sess.sessionId].displayTitle || props.sessionById[sess.sessionId].title)) || sess.title || sess.chatId || sess.sessionId),
3296
- });
3297
- },
3298
- archived: archived.has(sess.sessionId),
3299
- hoverStatuses: channelSessionHoverStatuses({
3300
- running: !!(sess.running || (props.sessionById && props.sessionById[sess.sessionId] && props.sessionById[sess.sessionId].running) || (props.sessionStatuses && props.sessionStatuses.get && props.sessionStatuses.get(sess.sessionId) && props.sessionStatuses.get(sess.sessionId).running)),
3301
- archived: archived.has(sess.sessionId),
3302
- completed: !!(props.sessionStatuses && props.sessionStatuses.get && props.sessionStatuses.get(sess.sessionId) && props.sessionStatuses.get(sess.sessionId).completionUnread),
3303
- pendingKind: props.sessionStatuses && props.sessionStatuses.get && props.sessionStatuses.get(sess.sessionId) && props.sessionStatuses.get(sess.sessionId).pendingInteraction && props.sessionStatuses.get(sess.sessionId).pendingInteraction.kind,
3304
- runningSubagentCount: (((props.projections && props.projections[sess.sessionId] && props.projections[sess.sessionId].values && props.projections[sess.sessionId].values.subagentCatalog) || []).filter((child) => child && child.id && props.sessionStatuses && props.sessionStatuses.get && props.sessionStatuses.get(child.id) && props.sessionStatuses.get(child.id).running)).length,
3305
- }, t),
3306
- onStopArchive: (target) => { setStopArchiveError(undefined); setStopArchiveTarget(target); },
3307
- renderSlot: props.renderSlot,
3308
- skin,
3309
- sessionActions: {
3310
- renameSession: props.renameSession,
3311
- archiveSession: props.archiveSession,
3312
- unarchiveSession: props.unarchiveSession,
3313
- deleteSession: props.deleteSession,
3314
- forkSession: props.forkSession,
3315
- openPath: props.openPath,
3316
- },
3317
- t,
3318
- })),
3319
- );
3320
- }),
3321
- ),
3322
- ),
3323
- h(Modal, {
3324
- open: !!archiveGroupTarget,
3325
- layerOwner: "sidebar-archive",
3326
- onClose: () => { if (!archiveGroupBusy) { setArchiveGroupTarget(undefined); setArchiveGroupError(undefined); } },
3327
- closeLabel: t("rail.archiveGroupClose"),
3328
- title: t("rail.archiveGroup"),
3329
- description: archiveGroupTarget ? t("rail.archiveGroupDescription", { name: archiveGroupTarget.name, count: archiveGroupTarget.sessionIds.length }) : "",
3330
- footer: h(React.Fragment, null,
3331
- hostModalButton(t("rail.archiveGroupCancel"), () => { setArchiveGroupTarget(undefined); setArchiveGroupError(undefined); }, "outline", { disabled: archiveGroupBusy }),
3332
- hostModalButton(t("rail.archiveGroupConfirm"), confirmArchiveGroup, "primary", { disabled: archiveGroupBusy }),
3333
- ),
3334
- },
3335
- archiveGroupBusy && h("div", { className: "ima-n-dialog-status", role: "status" }, t("rail.archiveGroupPending")),
3336
- archiveGroupError && h("div", { className: "ima-n-dialog-error", role: "alert" }, t("rail.archiveGroupFailed", { message: archiveGroupError })),
3337
- ),
3338
- h(Modal, {
3339
- open: !!stopArchiveTarget,
3340
- layerOwner: "sidebar-stop",
3341
- onClose: () => { if (!stopArchiveBusy) { setStopArchiveTarget(undefined); setStopArchiveError(undefined); } },
3342
- closeLabel: t("action.cancel"),
3343
- title: t("rail.stopArchive"),
3344
- description: stopArchiveTarget ? t(stopArchiveTarget.group ? "rail.stopArchiveGroupDescription" : "rail.stopArchiveDescription", { name: stopArchiveTarget.title }) : "",
3345
- footer: h(React.Fragment, null,
3346
- hostModalButton(t("action.cancel"), () => { setStopArchiveTarget(undefined); setStopArchiveError(undefined); }, "outline", { disabled: stopArchiveBusy }),
3347
- hostModalButton(t("rail.stopArchiveConfirm"), confirmStopArchive, "primary", { disabled: stopArchiveBusy }),
3348
- ),
3349
- },
3350
- stopArchiveBusy && h("div", { className: "ima-n-dialog-status", role: "status" }, t("rail.stopArchivePending")),
3351
- stopArchiveError && h("div", { className: "ima-n-dialog-error", role: "alert" }, t("rail.archiveFailed")),
3352
- ),
3353
- h(Modal, {
3354
- open: !!deleteTarget,
3355
- layerOwner: "sidebar-delete",
3356
- onClose: () => { if (!deleteBusy) { setDeleteTarget(undefined); setDeleteError(undefined); } },
3357
- closeLabel: t("rail.deleteSessionClose"),
3358
- title: t("rail.deleteSession"),
3359
- description: deleteTarget ? t("rail.deleteSessionDescription", { name: deleteTarget.title }) : "",
3360
- footer: h(React.Fragment, null,
3361
- hostModalButton(t("rail.deleteSessionCancel"), () => { setDeleteTarget(undefined); setDeleteError(undefined); }, "outline", { disabled: deleteBusy }),
3362
- hostModalButton(t("rail.deleteSessionConfirm"), confirmDelete, "primary", { disabled: deleteBusy }),
3363
- ),
3364
- },
3365
- deleteBusy && h("div", { className: "ima-n-dialog-status", role: "status" }, t("rail.deleteSessionPending")),
3366
- deleteError && h("div", { className: "ima-n-dialog-error", role: "alert" }, t("rail.deleteSessionFailed", { message: deleteError })),
3367
- ),
3368
- );
3369
2863
  }
3370
2864
 
3371
- function isTaskSessionItem(item) {
3372
- if (!item) return false;
3373
- if (item.blank) return false;
3374
- if (item.origin === "im" || item.origin === "subagent") return false;
3375
- return !isChannelSession(item.id || "");
2865
+ function ChannelMenuSettingsIcon() {
2866
+ return h(IconSettingsOutline16, { size: 16 });
3376
2867
  }
3377
2868
 
3378
- function TaskList(props) {
3379
- if (typeof props.useSessions === "function") return h(TaskListWithSessions, props);
3380
- return h(TaskListView, { groups: [], current: null, openSession: props.openSession, t: props.t });
2869
+ function ChannelUnavailable({ t }) {
2870
+ return h("div", { className: "ima-channel-unavailable" }, t("rail.treeUnavailable"));
3381
2871
  }
3382
2872
 
3383
- function TaskListWithSessions(props) {
3384
- useSyncExternalStore(subscribeChannelMembership, channelMembershipSnapshot, channelMembershipSnapshot);
3385
- const t = props.t || fallbackT;
3386
- const snap = props.useSessions((state) => state || { ids: [], byId: {}, current: null });
3387
- const workspaces = typeof props.useWorkspaces === "function"
3388
- ? props.useWorkspaces((state) => state || { items: [], archivedSessionIds: [] })
3389
- : { items: [], archivedSessionIds: [] };
3390
- const archived = new Set(workspaces.archivedSessionIds || []);
3391
- const assigned = new Set();
3392
- const groups = [];
3393
- for (const ws of workspaces.items || []) {
3394
- const sessions = (ws.sessionIds || [])
3395
- .map((id) => snap.byId[id])
3396
- .filter((item) => isTaskSessionItem(item) && !archived.has(item.id));
3397
- sessions.forEach((item) => assigned.add(item.id));
3398
- if (sessions.length) {
3399
- groups.push({ id: ws.workspaceId || ws.id, label: ws.title || ws.path || t("rail.workspace"), sessions });
3400
- }
2873
+ class ChannelTreeGuard extends React.Component {
2874
+ constructor(props) {
2875
+ super(props);
2876
+ this.state = { failed: false };
2877
+ }
2878
+ static getDerivedStateFromError() {
2879
+ return { failed: true };
2880
+ }
2881
+ componentDidCatch(error) {
2882
+ console.warn("[dsh-im-connect] 官方频道树渲染失败", error);
2883
+ }
2884
+ render() {
2885
+ return this.state.failed ? h(ChannelUnavailable, { t: this.props.t }) : this.props.children;
3401
2886
  }
3402
- const ungrouped = (snap.ids || [])
3403
- .map((id) => snap.byId[id])
3404
- .filter((item) => item && !assigned.has(item.id) && isTaskSessionItem(item) && !archived.has(item.id));
3405
- if (ungrouped.length) groups.push({ id: "", label: t("rail.ungrouped"), sessions: ungrouped });
3406
- return h(TaskListView, { groups, current: currentSessionId(snap), openSession: props.openSession, t });
3407
2887
  }
3408
2888
 
3409
- function TaskListView({ groups, current, openSession, t = fallbackT }) {
3410
- if (!groups.length) return h("div", { className: "ima-empty" }, t("rail.noTasks"));
3411
- return h("div", { className: "ima-native ima-rail" },
3412
- h("div", { className: "ima-native-tree" },
3413
- ...groups.map((group) => h("div", { key: group.id || "ungrouped", className: "ima-native-project" },
3414
- h("div", { className: "ima-native-head" },
3415
- h("span", { className: "ima-native-title" }, group.label),
3416
- ),
3417
- ...group.sessions.map((item) => h("div", {
3418
- key: item.id,
3419
- className: current === item.id ? "ima-native-session on" : "ima-native-session",
3420
- role: "treeitem",
3421
- tabIndex: 0,
3422
- onClick: () => openSession && openSession(item.id),
3423
- onKeyDown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openSession && openSession(item.id); } },
3424
- }, h("span", { className: "ima-native-title" }, item.title || item.id))),
3425
- )),
2889
+ function ChannelOfficialView(props) {
2890
+ const t = props.t || fallbackT;
2891
+ const hostProps = props.hostProps || {};
2892
+ const Official = props.officialTree;
2893
+ const hostT = typeof props.hostT === "function"
2894
+ ? props.hostT
2895
+ : (typeof hostProps.t === "function" ? hostProps.t : t);
2896
+ const rawUseSessions = hostProps.useSessions;
2897
+ const rawUseWorkspaces = hostProps.useWorkspaces;
2898
+ const store = getChannelViewStore();
2899
+ const membershipRevision = useSyncExternalStore(subscribeChannelMembership, channelMembershipSnapshot, channelMembershipSnapshot);
2900
+ const useChannelStore = useCallback((select) => {
2901
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
2902
+ return select(snapshot);
2903
+ }, [store]);
2904
+ const groupBy = useChannelStore((state) => state.groupBy);
2905
+ const sessionSource = typeof rawUseSessions === "function"
2906
+ ? rawUseSessions((state) => state)
2907
+ : EMPTY_SESSION_STATE;
2908
+ // 宿主 0.2.x 首个权威快照前 phase 为 pending,列表失败时也停在 pending;
2909
+ // 旧宿主快照可能不带 phase,此时按已就绪处理,由 renderable 判定能力缺失。
2910
+ const groupsReady = sessionSource.phase === undefined || sessionSource.phase === "ready";
2911
+ const groupsError = sessionSource.state === "error";
2912
+ const groups = useMemo(() => channelGroupsFromSessionState(sessionSource, t), [membershipRevision, sessionSource, t]);
2913
+ const groupsRef = useRef(groups);
2914
+ groupsRef.current = groups;
2915
+ const [channelIcons, setChannelIcons] = useState("");
2916
+ const [workspaceIcons, setWorkspaceIcons] = useState("");
2917
+ const open = props.openSession || hostProps.open || hostProps.openSession;
2918
+ const openChannelSettings = props.openChannelSettings || hostProps.openChannelSettings;
2919
+ const openImSettings = props.openImSettings || hostProps.openImSettings || (() => openImSettingsPage(t));
2920
+
2921
+ useEffect(() => { ensureStyle(); }, []);
2922
+
2923
+ useEffect(() => {
2924
+ if (groupBy === "channel" && channelIcons === "") setChannelIcons(channelIconCss());
2925
+ }, [channelIcons, groupBy]);
2926
+
2927
+ const memberKey = groups.map((group) => group.id + ":" + (group.sessions || []).map((session) => session.sessionId).join(",")).join("|");
2928
+ const memberIds = useMemo(() => {
2929
+ const ids = new Set();
2930
+ for (const group of groups) {
2931
+ for (const session of group.sessions || []) ids.add(String(session.sessionId));
2932
+ }
2933
+ return ids;
2934
+ }, [memberKey]);
2935
+
2936
+ const useChannelSessions = useCallback((selector, equals) => {
2937
+ if (typeof rawUseSessions !== "function") return selector(EMPTY_SESSION_STATE);
2938
+ return rawUseSessions((state) => selector(channelMemberSessionState(state, memberIds)), equals);
2939
+ }, [memberIds, rawUseSessions]);
2940
+
2941
+ const useChannelWorkspaces = useCallback((selector, equals) => {
2942
+ if (typeof rawUseWorkspaces !== "function") return selector(EMPTY_WORKSPACE_STATE);
2943
+ return rawUseWorkspaces((state) => selector(
2944
+ groupBy === "channel"
2945
+ ? syntheticChannelWorkspaceState(state, groups, t)
2946
+ : channelRealWorkspaceState(state, memberIds),
2947
+ ), equals);
2948
+ }, [groupBy, groups, memberIds, rawUseWorkspaces, t]);
2949
+
2950
+ const workspaceSource = typeof rawUseWorkspaces === "function"
2951
+ ? rawUseWorkspaces((state) => state)
2952
+ : undefined;
2953
+ useEffect(() => {
2954
+ if (groupBy === "channel") {
2955
+ if (workspaceIcons !== "") setWorkspaceIcons("");
2956
+ return;
2957
+ }
2958
+ const items = (workspaceSource && workspaceSource.items) || [];
2959
+ const css = channelWorkspaceIconCss(items, memberIds);
2960
+ if (css !== workspaceIcons) setWorkspaceIcons(css);
2961
+ }, [groupBy, memberIds, membershipRevision, workspaceIcons, workspaceSource]);
2962
+ const groupKeys = useMemo(() => {
2963
+ if (groupBy === "channel") {
2964
+ return groups.filter((group) => (group.sessions || []).length > 0).map((group) => channelWorkspaceId(group.id));
2965
+ }
2966
+ if (groupBy === "flat") return [];
2967
+ return ((workspaceSource && workspaceSource.items) || [])
2968
+ .map((workspace) => String(workspace.workspaceId || workspace.id || ""))
2969
+ .filter((key) => key !== "");
2970
+ }, [groupBy, groups, workspaceSource]);
2971
+ useEffect(() => {
2972
+ store.actions.ensureExpanded(groupKeys);
2973
+ }, [groupKeys, store]);
2974
+
2975
+ const text = useCallback((key, params) => {
2976
+ if (key === "section.workspaces" && groupBy === "channel") return t("rail.channels");
2977
+ if (key === "workspace.add" || key === "menu.addWorkspace") return t("rail.addChannel");
2978
+ return hostT(key, params);
2979
+ }, [groupBy, hostT, t]);
2980
+
2981
+ useEffect(() => installChannelGroupOption({
2982
+ label: t("rail.byChannel"),
2983
+ groupLabel: text("groupBy.label"),
2984
+ workspaceLabel: text("groupBy.workspace"),
2985
+ checked: groupBy === "channel",
2986
+ onSelect: () => store.actions.setGroupBy("channel"),
2987
+ }), [groupBy, store, t, text]);
2988
+
2989
+ useEffect(() => installChannelGroupMenu({
2990
+ settingsLabel: t("rail.channelSettings"),
2991
+ resolve: (channelId) => groupsRef.current.find((group) => group.id === channelId),
2992
+ onSettings: (group) => {
2993
+ if (typeof openChannelSettings === "function") {
2994
+ openChannelSettings({ channelId: group.id, name: channelLabel(group, t) });
2995
+ return;
2996
+ }
2997
+ openImSettings();
2998
+ },
2999
+ }), [openChannelSettings, openImSettings, t]);
3000
+
3001
+ const rawStartSession = hostProps.startSession;
3002
+ const rawRenameWorkspace = hostProps.renameWorkspace;
3003
+ const rawDeleteWorkspace = hostProps.deleteWorkspace;
3004
+ const rawInsertWorkspaceBefore = hostProps.insertWorkspaceBefore;
3005
+ const rawSearch = hostProps.searchSessions;
3006
+ const startChannelSession = useCallback((workspaceId, options) => {
3007
+ if (channelIdFromWorkspaceId(workspaceId) !== undefined) return;
3008
+ if (typeof rawStartSession === "function") rawStartSession(workspaceId, options);
3009
+ }, [rawStartSession]);
3010
+ const renameChannelWorkspace = useCallback(async (workspaceId, title) => {
3011
+ if (channelIdFromWorkspaceId(workspaceId) !== undefined) throw new Error(t("rail.groupReadOnly"));
3012
+ if (typeof rawRenameWorkspace === "function") await rawRenameWorkspace(workspaceId, title);
3013
+ }, [rawRenameWorkspace, t]);
3014
+ const deleteChannelWorkspace = useCallback(async (workspaceId) => {
3015
+ if (channelIdFromWorkspaceId(workspaceId) !== undefined) throw new Error(t("rail.groupReadOnly"));
3016
+ if (typeof rawDeleteWorkspace === "function") await rawDeleteWorkspace(workspaceId);
3017
+ }, [rawDeleteWorkspace, t]);
3018
+ const insertChannelWorkspaceBefore = useCallback(async (workspaceId, beforeWorkspaceId) => {
3019
+ if (channelIdFromWorkspaceId(workspaceId) !== undefined) return;
3020
+ if (typeof rawInsertWorkspaceBefore === "function") await rawInsertWorkspaceBefore(workspaceId, beforeWorkspaceId);
3021
+ }, [rawInsertWorkspaceBefore]);
3022
+ const searchChannelSessions = useCallback(async (query, signal) => {
3023
+ if (typeof rawSearch !== "function") return { items: [], hasMore: false };
3024
+ const result = await rawSearch(query, signal);
3025
+ return {
3026
+ items: (result.items || []).filter((item) => item && item.id !== undefined && memberIds.has(String(item.id))),
3027
+ hasMore: result.hasMore,
3028
+ };
3029
+ }, [memberIds, rawSearch]);
3030
+ const rawUseShortcuts = hostProps.useShortcuts;
3031
+ const useChannelShortcuts = useCallback((select, equals) => {
3032
+ if (typeof rawUseShortcuts !== "function") return select([]);
3033
+ return rawUseShortcuts((rows) => select((rows || []).filter((row) => row && row.id !== "workspace.add")), equals);
3034
+ }, [rawUseShortcuts]);
3035
+
3036
+ const officialProps = Object.assign({}, hostProps, {
3037
+ t: text,
3038
+ useStore: useChannelStore,
3039
+ actions: store.actions,
3040
+ useSessions: useChannelSessions,
3041
+ useWorkspaces: useChannelWorkspaces,
3042
+ open: typeof open === "function" ? open : noopChannelAction,
3043
+ useDirectoryFlow: channelAddFlow,
3044
+ requestAddWorkspace: typeof openImSettings === "function" ? openImSettings : noopChannelAction,
3045
+ startSession: startChannelSession,
3046
+ renameWorkspace: renameChannelWorkspace,
3047
+ deleteWorkspace: deleteChannelWorkspace,
3048
+ insertWorkspaceBefore: insertChannelWorkspaceBefore,
3049
+ });
3050
+ if (typeof rawSearch === "function") officialProps.searchSessions = searchChannelSessions;
3051
+ if (typeof rawUseShortcuts === "function") officialProps.useShortcuts = useChannelShortcuts;
3052
+
3053
+ const renderable = Official !== undefined && Official !== null
3054
+ && typeof rawUseSessions === "function" && typeof rawUseWorkspaces === "function";
3055
+ // 官方树会清理不存在的分组,首个权威快照到达前不能传入空列表。
3056
+ const body = !groupsReady ? null : renderable
3057
+ ? h(ChannelTreeGuard, { t }, h(Official, officialProps))
3058
+ : h(ChannelUnavailable, { t });
3059
+
3060
+ return h(React.Fragment, null,
3061
+ h("div", { className: "ima-channel-official", "data-mode": groupBy },
3062
+ groupBy === "channel" && channelIcons !== "" && h("style", null, channelIcons),
3063
+ groupBy !== "channel" && workspaceIcons !== "" && h("style", null, workspaceIcons),
3064
+ // 宿主列表失败时 phase 仍停在 pending,没有横幅就是整页空白。
3065
+ groupsError && h("div", { className: "ima-channel-error", role: "alert" }, t("error.load")),
3066
+ body,
3426
3067
  ),
3427
3068
  );
3428
3069
  }
3429
3070
 
3430
- const imSessionFilterCache = new WeakMap();
3431
3071
  const registryFilterCache = new WeakMap();
3432
3072
  function cacheFilteredSessions(src, ids) {
3433
3073
  if (ids.length === (src.ids || []).length) return src;
@@ -3437,44 +3077,43 @@ window.__ModuleLoader__.load({
3437
3077
  }
3438
3078
  return Object.assign({}, src, { ids, byId });
3439
3079
  }
3440
- function filterSessionsByIm(state, keepIm) {
3441
- const src = state || { ids: [], byId: {}, current: null };
3442
- const key = keepIm ? "im" : "task";
3443
- if (src && typeof src === "object") {
3444
- const hit = imSessionFilterCache.get(src);
3445
- if (hit && hit.revision === channelMembershipRevision && hit[key]) return hit[key];
3080
+
3081
+ function openRegisteredSession(sessionId, registry, hostOpen) {
3082
+ const openers = registry && Array.isArray(registry.sessionOpeners) ? registry.sessionOpeners : [];
3083
+ const opener = openers
3084
+ .slice()
3085
+ .sort((a, b) => (a.order || 0) - (b.order || 0))
3086
+ .find((item) => item && typeof item.matchSession === "function" && item.matchSession(sessionId));
3087
+ if (!opener) {
3088
+ if (typeof hostOpen === "function") hostOpen(sessionId);
3089
+ return;
3446
3090
  }
3447
- const ids = (src.ids || []).filter((id) => isChannelSession(id) === keepIm);
3448
- const result = cacheFilteredSessions(src, ids);
3449
- if (src && typeof src === "object") {
3450
- const previous = imSessionFilterCache.get(src);
3451
- const bucket = previous && previous.revision === channelMembershipRevision ? previous : { revision: channelMembershipRevision };
3452
- bucket[key] = result;
3453
- imSessionFilterCache.set(src, bucket);
3091
+ try {
3092
+ opener.open(sessionId, hostOpen);
3093
+ } catch {
3094
+ if (typeof hostOpen === "function") hostOpen(sessionId);
3454
3095
  }
3455
- return result;
3456
- }
3457
-
3458
- function filterTaskSessions(state) {
3459
- return filterSessionsByIm(state, false);
3460
- }
3461
-
3462
- function filterChannelSessions(state) {
3463
- return filterSessionsByIm(state, true);
3464
3096
  }
3465
3097
 
3466
3098
  function createNativeTabRegistry(officialTree) {
3467
3099
  const tabs = new Map();
3468
3100
  const sessionFilters = [];
3101
+ const sessionOpeners = [];
3469
3102
  const listeners = new Set();
3470
3103
  let cachedTabs = [];
3104
+ let revision = 0;
3471
3105
  const rebuild = () => { cachedTabs = [...tabs.values()].sort((a, b) => (a.order || 0) - (b.order || 0)); };
3472
- const emit = () => { for (const listener of listeners) listener(); };
3106
+ const emit = () => {
3107
+ revision += 1;
3108
+ for (const listener of listeners) listener();
3109
+ };
3473
3110
  return {
3474
3111
  version: 1,
3475
3112
  officialTree,
3476
3113
  sessionFilters,
3114
+ sessionOpeners,
3477
3115
  getTabs() { return cachedTabs; },
3116
+ getRevision() { return revision; },
3478
3117
  subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
3479
3118
  insert(tab) {
3480
3119
  if (!tab || !tab.id) return () => {};
@@ -3496,6 +3135,15 @@ window.__ModuleLoader__.load({
3496
3135
  emit();
3497
3136
  };
3498
3137
  },
3138
+ addSessionOpener(opener) {
3139
+ sessionOpeners.push(opener);
3140
+ emit();
3141
+ return () => {
3142
+ const index = sessionOpeners.indexOf(opener);
3143
+ if (index >= 0) sessionOpeners.splice(index, 1);
3144
+ emit();
3145
+ };
3146
+ },
3499
3147
  };
3500
3148
  }
3501
3149
 
@@ -3510,17 +3158,18 @@ window.__ModuleLoader__.load({
3510
3158
  return registry?.version === 1 && typeof registry.getTabs === "function" && typeof registry.subscribe === "function" && typeof registry.insert === "function" ? registry : null;
3511
3159
  }
3512
3160
 
3513
- function applyRegistryFilters(state, registry) {
3161
+ function applySessionFilters(state, registry) {
3514
3162
  const src = state || { ids: [], byId: {}, current: null };
3515
3163
  const filters = registry && registry.sessionFilters ? registry.sessionFilters : [];
3516
3164
  if (!filters.length) return src;
3517
- if (src && typeof src === "object") {
3165
+ const revision = registry && typeof registry.getRevision === "function" ? registry.getRevision() : null;
3166
+ if (revision !== null && src && typeof src === "object") {
3518
3167
  const hit = registryFilterCache.get(src);
3519
- if (hit && hit.filters === filters) return hit.result;
3168
+ if (hit && hit.registry === registry && hit.revision === revision) return hit.result;
3520
3169
  }
3521
3170
  const ids = (src.ids || []).filter((id) => filters.every((fn) => fn(String(id))));
3522
3171
  const result = cacheFilteredSessions(src, ids);
3523
- if (src && typeof src === "object") registryFilterCache.set(src, { filters, result });
3172
+ if (revision !== null && src && typeof src === "object") registryFilterCache.set(src, { registry, revision, result });
3524
3173
  return result;
3525
3174
  }
3526
3175
 
@@ -3536,8 +3185,17 @@ window.__ModuleLoader__.load({
3536
3185
  () => (nativeTabs && nativeTabs.getTabs ? nativeTabs.getTabs() : EMPTY_EXTRA_TABS),
3537
3186
  () => EMPTY_EXTRA_TABS,
3538
3187
  );
3188
+ const registryRevision = useSyncExternalStore(
3189
+ (listener) => (nativeTabs && nativeTabs.subscribe ? nativeTabs.subscribe(listener) : () => {}),
3190
+ () => (nativeTabs && nativeTabs.getRevision ? nativeTabs.getRevision() : 0),
3191
+ () => 0,
3192
+ );
3539
3193
  const [tab, setTab] = useState(() => {
3540
- try { return localStorage.getItem(TAB_KEY) || "tasks"; } catch { return "tasks"; }
3194
+ try {
3195
+ return localStorage.getItem(TAB_KEY)
3196
+ || localStorage.getItem("dsh-im-connect.sidebar-tab")
3197
+ || localStorage.getItem("dsh-automation.sidebar-tab") || "tasks";
3198
+ } catch { return "tasks"; }
3541
3199
  });
3542
3200
  const sessionSnap = typeof rawUseSessions === "function"
3543
3201
  ? rawUseSessions((state) => state)
@@ -3548,19 +3206,17 @@ window.__ModuleLoader__.load({
3548
3206
  const sessionById = (sessionSnap && sessionSnap.byId) || {};
3549
3207
  const useTaskSessions = useCallback((selector, eq) => {
3550
3208
  if (typeof rawUseSessions !== "function") return selector({ ids: [], byId: {}, current: null });
3551
- return rawUseSessions((state) => selector(applyRegistryFilters(filterTaskSessions(state), nativeTabs)), eq);
3552
- }, [rawUseSessions, nativeTabs, membershipRevision]);
3553
- const useChannelSessions = useCallback((selector, eq) => {
3554
- if (typeof rawUseSessions !== "function") return selector({ ids: [], byId: {}, current: null });
3555
- return rawUseSessions((state) => selector(filterChannelSessions(state)), eq);
3556
- }, [rawUseSessions, membershipRevision]);
3209
+ // 频道会话也出现在官方任务树;频道页签只是同一批会话的过滤视图。
3210
+ return rawUseSessions((state) => selector(applySessionFilters(state, nativeTabs)), eq);
3211
+ }, [rawUseSessions, nativeTabs, registryRevision]);
3557
3212
  useEffect(() => { ensureStyle(); }, []);
3558
3213
  useEffect(() => { try { localStorage.setItem(TAB_KEY, tab); } catch { /* ignore */ } }, [tab]);
3559
3214
  useEffect(() => {
3560
3215
  const onClick = (event) => {
3561
3216
  const target = event.target && event.target.closest ? event.target.closest("button") : null;
3562
3217
  if (!target) return;
3563
- const label = (target.innerText || "") + " " + (target.getAttribute("aria-label") || "");
3218
+ if (target.closest("[data-row-key]")) return;
3219
+ const label = target.getAttribute("aria-label") || target.innerText || target.textContent || "";
3564
3220
  if (isHostNewSessionControl(label)) setTab("tasks");
3565
3221
  };
3566
3222
  document.addEventListener("click", onClick, true);
@@ -3578,32 +3234,34 @@ window.__ModuleLoader__.load({
3578
3234
  previousCurrentId.current = followed.previousId;
3579
3235
  if (followed.tab) setTab(followed.tab);
3580
3236
  }, [currentId, extraTabs, membershipRevision]);
3237
+ const hostOpen = props.openSession || props.open;
3238
+ const openListed = (id) => {
3239
+ openListedSession(resolveHostSessionId(id, sessionById), hostOpen);
3240
+ };
3581
3241
  const openSession = (id) => {
3582
- openListedSession(resolveHostSessionId(id, sessionById), props.openSession || props.open);
3242
+ if (nativeTabs && Array.isArray(nativeTabs.sessionOpeners)
3243
+ && nativeTabs.sessionOpeners.some((item) => item && item.id === "im-connect")) {
3244
+ openRegisteredSession(id, nativeTabs, hostOpen);
3245
+ return;
3246
+ }
3247
+ openListed(id);
3583
3248
  };
3584
3249
  const officialProps = Object.assign({}, props, { useSessions: useTaskSessions, t: officialT, openSession, open: openSession });
3585
- const channelRail = h(ChannelRail, {
3250
+ const channelView = h(ChannelOfficialView, {
3251
+ officialTree: Official,
3252
+ hostProps: props,
3253
+ hostT: officialT,
3254
+ t,
3586
3255
  openSession,
3587
- open: openSession,
3588
- useSessions: rawUseSessions,
3589
- useWorkspaces: props.useWorkspaces,
3590
- useSessionStatus: props.useSessionStatus,
3591
- selectedId: currentId || props.selectedId || null,
3592
- skin: "native",
3593
- renameSession: props.renameSession,
3594
- archiveSession: props.archiveSession,
3595
- unarchiveSession: props.unarchiveSession,
3596
- deleteSession: props.deleteSession,
3597
- forkSession: props.forkSession,
3598
- openPath: props.openPath,
3599
3256
  openChannelSettings: props.openChannelSettings,
3600
- t,
3257
+ openImSettings: props.openImSettings,
3601
3258
  });
3602
3259
  if (props.wide === false) return Official ? h(Official, officialProps) : null;
3603
3260
  const officialTree = Official
3604
3261
  ? h("div", { className: "ima-official-tree" }, h(Official, officialProps))
3605
3262
  : null;
3606
- const extra = extraTabs.find((item) => item.id === tab);
3263
+ const visibleTab = resolveSidebarTab(tab, extraTabs);
3264
+ const extra = extraTabs.find((item) => item.id === visibleTab);
3607
3265
  const hasChannelTab = extraTabs.some((item) => item.id === "channels");
3608
3266
  const imTabItems = [
3609
3267
  {
@@ -3622,20 +3280,23 @@ window.__ModuleLoader__.load({
3622
3280
  id: "ima-tab-channels",
3623
3281
  panelId: "ima-panel-channels",
3624
3282
  label: h("span", { style: { display: "inline-flex", alignItems: "center", gap: 5 } },
3625
- h("svg", { viewBox: "0 0 16 16", width: 14, height: 14, fill: "none", "aria-hidden": "true" },
3626
- h("path", { fill: "currentColor", d: "M2.15 2.9h11.7v8.2H6.42L2.15 13.85V2.9Zm1.4 1.4v6.62l1.78-1.12h7.12V4.3H3.55Z" }),
3627
- ),
3283
+ h(IconQueueOutline, { size: 14 }),
3628
3284
  h("span", null, t("rail.channels")),
3629
3285
  ),
3630
3286
  });
3631
3287
  }
3632
3288
  for (const item of extraTabs) {
3633
- const itemLabel = item.id === "schedule"
3289
+ const itemLabel = item.id === "channels"
3634
3290
  ? h("span", { style: { display: "inline-flex", alignItems: "center", gap: 5 } },
3635
- h(IconClockOutline, { size: 14 }),
3291
+ h(IconQueueOutline, { size: 14 }),
3636
3292
  h("span", null, item.label),
3637
3293
  )
3638
- : item.label;
3294
+ : item.id === "schedule"
3295
+ ? h("span", { style: { display: "inline-flex", alignItems: "center", gap: 5 } },
3296
+ h(IconClockOutline, { size: 14 }),
3297
+ h("span", null, item.label),
3298
+ )
3299
+ : item.label;
3639
3300
  imTabItems.push({
3640
3301
  value: item.id,
3641
3302
  id: "ima-tab-" + item.id,
@@ -3650,28 +3311,28 @@ window.__ModuleLoader__.load({
3650
3311
  h(HostSegmentedTabs, {
3651
3312
  className: "ima-segmented-tabs",
3652
3313
  label: t("rail.tabsAria"),
3653
- value: tab,
3314
+ value: visibleTab,
3654
3315
  onChange: (next) => setTab(next),
3655
3316
  items: imTabItems,
3656
3317
  }),
3657
3318
  )
3658
3319
  : h("div", { className: "ima-tabs", role: "tablist", "aria-label": t("rail.tabsAria") },
3659
- h("button", { type: "button", role: "tab", "aria-selected": tab === "tasks", className: tab === "tasks" ? "ima-tab on" : "ima-tab", onClick: () => setTab("tasks") }, t("rail.tasks")),
3660
- !hasChannelTab && h("button", { type: "button", role: "tab", "aria-selected": tab === "channels", className: tab === "channels" ? "ima-tab on" : "ima-tab", onClick: () => setTab("channels") }, t("rail.channels")),
3320
+ h("button", { type: "button", role: "tab", "aria-selected": visibleTab === "tasks", className: visibleTab === "tasks" ? "ima-tab on" : "ima-tab", onClick: () => setTab("tasks") }, t("rail.tasks")),
3321
+ !hasChannelTab && h("button", { type: "button", role: "tab", "aria-selected": visibleTab === "channels", className: visibleTab === "channels" ? "ima-tab on" : "ima-tab", onClick: () => setTab("channels") }, t("rail.channels")),
3661
3322
  ...extraTabs.map((item) => h("button", {
3662
3323
  key: item.id,
3663
3324
  type: "button",
3664
3325
  role: "tab",
3665
- "aria-selected": tab === item.id,
3666
- className: tab === item.id ? "ima-tab on" : "ima-tab",
3326
+ "aria-selected": visibleTab === item.id,
3327
+ className: visibleTab === item.id ? "ima-tab on" : "ima-tab",
3667
3328
  onClick: () => setTab(item.id),
3668
3329
  }, item.label)),
3669
3330
  ),
3670
- tab === "tasks"
3671
- ? (officialTree || h(TaskList, { useSessions: useTaskSessions, useWorkspaces: props.useWorkspaces, openSession }))
3331
+ visibleTab === "tasks"
3332
+ ? (officialTree || h(ChannelUnavailable, { t }))
3672
3333
  : extra
3673
- ? extra.render(Object.assign({}, props, { openSession, open: openSession }))
3674
- : channelRail,
3334
+ ? extra.render(Object.assign({}, props, { t: officialT, openSession, open: openSession }))
3335
+ : channelView,
3675
3336
  );
3676
3337
  }
3677
3338
 
@@ -3733,22 +3394,51 @@ window.__ModuleLoader__.load({
3733
3394
  const entries = (read && read.call(ctx.slots, "sidebar.workspaces")) || [];
3734
3395
  for (const item of entries) {
3735
3396
  if (!item || !item.component) continue;
3736
- if (item.component.__imConnectWrapped) continue;
3737
- if (item.component.__imConnectOriginal) continue;
3738
- if (item.component.__dshNativeTabHost) continue;
3739
- if (item.component.__dshAutomationWrapped) continue;
3397
+ if (isWrappedWorkspaceComponent(item.component)) continue;
3740
3398
  return item;
3741
3399
  }
3742
3400
  return null;
3743
3401
  }
3744
3402
 
3403
+ function isWrappedWorkspaceComponent(component) {
3404
+ return !!component && (component.__dshNativeTabWrapped === true
3405
+ || component.__dshNativeTabHost === true
3406
+ || component.__imConnectWrapped === true
3407
+ || component.__imConnectOriginal !== undefined
3408
+ || component.__dshAutomationWrapped === true
3409
+ || component.__dshAutomationOriginal !== undefined);
3410
+ }
3411
+
3745
3412
  function apply(ctx) {
3746
3413
  ensureStyle();
3747
3414
  ctx.effect(() => {
3748
- return channelRefresh.subscribe((data, error) => {
3749
- if (error) console.warn("[dsh-im-connect] 无法刷新渠道会话归属", error);
3750
- });
3751
- }, "im-connect: channel membership");
3415
+ let pending = channelSessionIds.size > 0, flight = null, disposed = false;
3416
+ const refresh = (changed) => {
3417
+ pending = pending || changed;
3418
+ if (disposed || !pending || flight) return;
3419
+ const sessions = probeService(ctx, "sessions");
3420
+ if (!sessions || typeof sessions.refresh !== "function") return;
3421
+ const revision = channelMembershipRevision;
3422
+ flight = Promise.resolve().then(() => {
3423
+ if (disposed) return;
3424
+ return sessions.refresh();
3425
+ }).then(() => {
3426
+ if (disposed) return;
3427
+ const snapshot = sessions.list && typeof sessions.list.getSnapshot === "function" ? sessions.list.getSnapshot() : undefined;
3428
+ if (snapshot && snapshot.state === "error") return;
3429
+ if (revision === channelMembershipRevision) pending = false;
3430
+ }).catch(() => { /* 保留待处理状态,由下次渠道刷新重试 */ })
3431
+ .finally(() => { flight = null; });
3432
+ };
3433
+ requestHostSessionRefresh = refresh;
3434
+ return () => {
3435
+ disposed = true;
3436
+ if (requestHostSessionRefresh === refresh) requestHostSessionRefresh = () => {};
3437
+ };
3438
+ }, "im-connect: host session refresh");
3439
+ ctx.effect(() => channelRefresh.subscribe((data, error) => {
3440
+ if (error) console.warn("[dsh-im-connect] 无法刷新渠道会话归属", error);
3441
+ }), "im-connect: channel membership");
3752
3442
  ctx.effect(() => ctx.locale.register(IM_LOCALE_NS, IM_LOCALES), "im-connect: dictionaries");
3753
3443
  const t = ctx.locale.bind(IM_LOCALE_NS);
3754
3444
  ctx.effect(() => observePluginUpdate({
@@ -3774,17 +3464,29 @@ window.__ModuleLoader__.load({
3774
3464
  () => { requestChannelSettings(next); },
3775
3465
  );
3776
3466
  };
3777
- function LocalizedChannelRail(props) {
3467
+ const openImSettings = () => openImSettingsPage(t);
3468
+ // Codex UI 只把 sidebar.channels 当作页签占用信号,频道内容由它自己的
3469
+ // ChannelBrowser 渲染;这里保留占位,避免未来宿主直接渲染时空白。
3470
+ function LocalizedChannelRail() {
3778
3471
  useSyncExternalStore(subscribeLocale, localeSnapshot, localeSnapshot);
3779
- return h(HostThemeProvider, null, h(ChannelRail, Object.assign({}, props, { t, openChannelSettings })));
3472
+ return h(ChannelUnavailable, { t });
3780
3473
  }
3781
3474
  function LocalizedSessionSwitcher(props) {
3782
3475
  useSyncExternalStore(subscribeLocale, localeSnapshot, localeSnapshot);
3783
- return h(HostThemeProvider, null, h(SessionSwitcher, Object.assign({}, props, { t, officialT: props.t, openChannelSettings })));
3476
+ const archiveSession = props.archiveSession || ((sessionId, options) => archiveHostSession(ctx, sessionId, options));
3477
+ const unarchiveSession = props.unarchiveSession || ((sessionId) => unarchiveHostSession(ctx, sessionId));
3478
+ return h(SessionSwitcher, Object.assign({}, props, {
3479
+ t,
3480
+ officialT: props.t,
3481
+ openChannelSettings,
3482
+ openImSettings,
3483
+ archiveSession,
3484
+ unarchiveSession,
3485
+ }));
3784
3486
  }
3785
3487
  function LocalizedSettingsPage(props) {
3786
3488
  useSyncExternalStore(subscribeLocale, localeSnapshot, localeSnapshot);
3787
- return h(HostThemeProvider, null, h(SettingsPage, Object.assign({}, props, { t, permissionT, modelT, presetT, readMainSessionModel: () => readMainSessionModel(ctx) })));
3489
+ return h(SettingsPage, Object.assign({}, props, { t, permissionT, modelT, presetT, readMainSessionModel: () => readMainSessionModel(ctx) }));
3788
3490
  }
3789
3491
  openImSession = (id) => {
3790
3492
  try {
@@ -3807,7 +3509,7 @@ window.__ModuleLoader__.load({
3807
3509
 
3808
3510
  function applySettingsNavIcon(button, wantedLabel) {
3809
3511
  if (!isOwnNavRow(button.textContent, wantedLabel())) return false;
3810
- if (!button.querySelector("svg")) return false;
3512
+ if (!button.querySelector(":scope > svg")) return false;
3811
3513
  if (button.getAttribute(NAV_ICON_MARKER) === "assistant" && button.querySelector(`.${NAV_ICON_CLASS}`)) return false;
3812
3514
  button.setAttribute(NAV_ICON_MARKER, "assistant");
3813
3515
  let icon = button.querySelector(`.${NAV_ICON_CLASS}`);
@@ -3817,6 +3519,7 @@ window.__ModuleLoader__.load({
3817
3519
  icon = document.createElement("span");
3818
3520
  icon.className = NAV_ICON_CLASS;
3819
3521
  icon.setAttribute("aria-hidden", "true");
3522
+ icon.setAttribute("style", `--ima-nav-icon-mask:${settingsNavIconMask()}`);
3820
3523
  button.prepend(icon);
3821
3524
  }
3822
3525
  return true;
@@ -3895,6 +3598,18 @@ window.__ModuleLoader__.load({
3895
3598
  }),
3896
3599
  }, LocalizedChannelRail));
3897
3600
 
3601
+ // 频道会话行前显示所属频道品牌标,和定时任务的时钟图标同一套 leading 槽位。
3602
+ ctx.slots.inject("sidebar.session.row.leading", () => ctx.slots.register({
3603
+ name: "sidebar.session.row.leading",
3604
+ id: "im-connect-session-channel",
3605
+ order: 10,
3606
+ }, function ChannelSessionLeading({ sessionId }) {
3607
+ useSyncExternalStore(subscribeChannelMembership, channelMembershipSnapshot, channelMembershipSnapshot);
3608
+ const channelId = channelIdOfSession(sessionId);
3609
+ if (!channelId) return null;
3610
+ return h("span", { className: "ima-session-channel-icon", "aria-hidden": "true" }, h(Logo, { id: channelId, small: true }));
3611
+ }));
3612
+
3898
3613
  // 只包一层官方任务树,绝不在通知回调里再 register,否则会把启动卡在 Loading plugins。
3899
3614
  ctx.slots.inject("sidebar.workspaces", () => {
3900
3615
  let wrappedEntry = null;
@@ -3902,16 +3617,34 @@ window.__ModuleLoader__.load({
3902
3617
  let ownedWrapper = null;
3903
3618
  let ownedRegistry = null;
3904
3619
  let removeInsertedTab = () => {};
3620
+ let removeInsertedOpener = () => {};
3905
3621
  let stopInsertedTabLocale = () => {};
3906
3622
  let insertedTabRegistry = null;
3907
3623
  let syncing = false;
3908
3624
  // 与定时插件共享通知,补足直接替换 component 不触发宿主插槽通知的情况。
3909
3625
  const notifyPeers = () => { queueMicrotask(() => window.dispatchEvent(new Event("dsh-native-sidebar-change"))); };
3626
+ const installSessionOpener = (registry) => {
3627
+ if (!registry || typeof registry.addSessionOpener !== "function") return () => {};
3628
+ if (registry.sessionOpeners && registry.sessionOpeners.some((item) => item.id === "im-connect")) return () => {};
3629
+ return registry.addSessionOpener({
3630
+ id: "im-connect",
3631
+ order: 20,
3632
+ // 普通任务行也需要把宿主内部 key 解析成官方 session id;定时 opener 优先级更高。
3633
+ matchSession: (sessionId) => typeof sessionId === "string" && sessionId !== "",
3634
+ open: (sessionId, hostOpen) => {
3635
+ let byId;
3636
+ try { byId = ctx.sessions && ctx.sessions.list && ctx.sessions.list.getSnapshot ? ctx.sessions.list.getSnapshot().byId : undefined; } catch { byId = undefined; }
3637
+ openListedSession(resolveHostSessionId(sessionId, byId), hostOpen);
3638
+ },
3639
+ });
3640
+ };
3910
3641
  const clearInsertedTab = () => {
3911
3642
  stopInsertedTabLocale();
3912
3643
  stopInsertedTabLocale = () => {};
3913
3644
  removeInsertedTab();
3914
3645
  removeInsertedTab = () => {};
3646
+ removeInsertedOpener();
3647
+ removeInsertedOpener = () => {};
3915
3648
  insertedTabRegistry = null;
3916
3649
  };
3917
3650
  const unwrap = () => {
@@ -3929,20 +3662,28 @@ window.__ModuleLoader__.load({
3929
3662
  const insertChannelTab = (entry) => {
3930
3663
  const registry = findNativeTabRegistry(entry);
3931
3664
  if (!registry) return false;
3932
- if (registry.getTabs().some((item) => item.id === "channels")) {
3933
- if (insertedTabRegistry && insertedTabRegistry !== registry) clearInsertedTab();
3934
- return true;
3665
+ if (insertedTabRegistry !== registry) {
3666
+ clearInsertedTab();
3667
+ insertedTabRegistry = registry;
3668
+ removeInsertedOpener = installSessionOpener(registry);
3935
3669
  }
3936
- clearInsertedTab();
3937
- insertedTabRegistry = registry;
3670
+ if (registry.getTabs().some((item) => item.id === "channels")) return true;
3938
3671
  const refreshInsertedTab = () => {
3939
3672
  removeInsertedTab = registry.insert({
3940
3673
  id: "channels",
3941
3674
  label: t("rail.channels"),
3942
3675
  order: 20,
3943
3676
  matchSession: isChannelSession,
3944
- render: (props) => h(ImSidebarFallbackBoundary, { officialTree: null, hostProps: props }, h(LocalizedChannelRail, Object.assign({}, props, {
3945
- skin: "native",
3677
+ render: (props) => h(ImSidebarFallbackBoundary, {
3678
+ officialTree: () => h(ChannelUnavailable, { t }),
3679
+ hostProps: props,
3680
+ }, h(ChannelOfficialView, Object.assign({}, props, {
3681
+ officialTree: registry.officialTree,
3682
+ hostProps: props,
3683
+ hostT: props.officialT || props.t,
3684
+ t,
3685
+ openChannelSettings,
3686
+ openImSettings,
3946
3687
  archiveSession: props.archiveSession || ((id, options) => archiveHostSession(ctx, id, options)),
3947
3688
  unarchiveSession: props.unarchiveSession || ((id) => unarchiveHostSession(ctx, id)),
3948
3689
  }))),
@@ -3959,7 +3700,6 @@ window.__ModuleLoader__.load({
3959
3700
  syncing = true;
3960
3701
  try {
3961
3702
  const combo = hasDshCodexUiSidebar(ctx);
3962
- channelSkin = combo ? "codex" : "native";
3963
3703
  if (combo) {
3964
3704
  unwrap();
3965
3705
  return;
@@ -3970,28 +3710,32 @@ window.__ModuleLoader__.load({
3970
3710
  if (wrappedEntry && (occupant !== wrappedEntry || occupant.component !== ownedWrapper)) unwrap();
3971
3711
  if (!occupant) { clearInsertedTab(); return; }
3972
3712
  if (insertedTabRegistry && findNativeTabRegistry(occupant) !== insertedTabRegistry) clearInsertedTab();
3973
- if (occupant && (occupant.component.__dshNativeTabHost || occupant.component.__dshAutomationWrapped || findNativeTabRegistry(occupant))) {
3713
+ if (occupant && (occupant.component.__dshNativeTabHost || occupant.component.__dshNativeTabWrapped || occupant.component.__dshAutomationWrapped || findNativeTabRegistry(occupant))) {
3974
3714
  insertChannelTab(occupant);
3975
3715
  return;
3976
3716
  }
3977
3717
  const official = pickOfficialWorkspaces(ctx);
3978
- if (!official || official.component.__imConnectWrapped || official.component.__dshNativeTabHost) return;
3718
+ if (!official) return;
3979
3719
  originalComp = official.component;
3980
3720
  const registry = createNativeTabRegistry(originalComp);
3981
3721
  ownedRegistry = registry;
3722
+ removeInsertedOpener = installSessionOpener(registry);
3982
3723
  const tree = originalComp;
3983
3724
  attachNativeTabRegistry(official, registry);
3984
- function ImNativeWorkspaceShell(innerProps) {
3725
+ function DshNativeTabWorkspaceShell(innerProps) {
3985
3726
  return h(ImSidebarFallbackBoundary, { officialTree: tree, hostProps: innerProps },
3986
3727
  h(LocalizedSessionSwitcher, Object.assign({}, innerProps, { officialTree: tree, nativeTabs: registry })));
3987
3728
  }
3988
- ImNativeWorkspaceShell.displayName = "ImNativeWorkspaceShell";
3989
- ImNativeWorkspaceShell.__imConnectWrapped = true;
3990
- ImNativeWorkspaceShell.__imConnectOriginal = originalComp;
3991
- ImNativeWorkspaceShell.__dshNativeTabHost = true;
3992
- attachNativeTabRegistry(ImNativeWorkspaceShell, registry);
3993
- official.component = ImNativeWorkspaceShell;
3994
- ownedWrapper = ImNativeWorkspaceShell;
3729
+ DshNativeTabWorkspaceShell.displayName = "DshNativeTabWorkspaceShell";
3730
+ DshNativeTabWorkspaceShell.__dshNativeTabHost = true;
3731
+ DshNativeTabWorkspaceShell.__dshNativeTabWrapped = true;
3732
+ DshNativeTabWorkspaceShell.__dshNativeTabOriginal = originalComp;
3733
+ DshNativeTabWorkspaceShell.__dshNativeTabOwner = "im-connect";
3734
+ DshNativeTabWorkspaceShell.__imConnectWrapped = true;
3735
+ DshNativeTabWorkspaceShell.__imConnectOriginal = originalComp;
3736
+ attachNativeTabRegistry(DshNativeTabWorkspaceShell, registry);
3737
+ official.component = DshNativeTabWorkspaceShell;
3738
+ ownedWrapper = DshNativeTabWorkspaceShell;
3995
3739
  wrappedEntry = official;
3996
3740
  notifyPeers();
3997
3741
  } catch (error) {