Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): tab 型插件装入勾选「立即开启」自动展开右侧栏并打开页签 (#332)
Lizi713d6c6f581e
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 4e2a1a3b13..e90ddccd73 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -2118,10 +2118,12 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);- 显示形态由 \`panel.position\` 决定:\`right\`(缺省)/ \`left\` = 停靠主聊天窗两侧的常驻面板;\`"tab"\` = 右侧栏页签——与文件/审查/终端同一容器,每会话至多- 一个页签,由用户从右侧栏空态列表或「+」菜单打开(不随装入自动弹出)。页签- 形态没有拖缝宽度语义,声明 \`minWidth\` / \`defaultFraction\` 会被拒装。两种形态- 的面板代码完全一样(同一 panel.html,供片/主题/媒体规则不变),只是宿主容器- 不同;页签形态请把界面做成自适应宽度;+ 一个页签,由用户从右侧栏空态列表或「+」菜单打开。当用户在会话视图内装入+ tab 型插件并勾选「立即开启」时,装入完成后会自动展开右侧栏并打开/聚焦该+ 页签;从插件页(无会话路由)装入或未勾选时,仍由用户手动从空态/「+」菜单+ 打开。页签形态没有拖缝宽度语义,声明 \`minWidth\` / \`defaultFraction\` 会被+ 拒装。两种形态的面板代码完全一样(同一 panel.html,供片/主题/媒体规则不变),+ 只是宿主容器不同;页签形态请把界面做成自适应宽度;- 与电子脑同源,用 \`BroadcastChannel('<自定名>')\` 通信(电子脑发,面板收);- 取自己的媒体:\`cindy-ghost://<id>/media/<指纹><后缀>\`(主机查账验归属,别人的图 404);- 重启回放:\`fetch('cindy-ghost://<id>/gallery')\` 返回本意识作品清单 \`[{src, caption}]\`;diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.tsindex 32e3fec4df..b19711f563 100644--- a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts@@ -227,6 +227,36 @@ describe('right-sidebar-window IPC', () => {).rejects.toThrow(/command.absPath required/);});+ it('validates and forwards open-ghost-tab commands (ghostId 走身份卡同一校验)', async () => {+ const controller = makeController();+ const { handler, mainWebContents } = registerController(controller);++ await handler(+ { sender: mainWebContents },+ {+ command: { type: 'open-ghost-tab', sessionId: 's1', ghostId: 'tab-demo-a' },+ allowOpen: true,+ },+ );+ expect(controller.routeCommand).toHaveBeenCalledWith({+ command: { type: 'open-ghost-tab', sessionId: 's1', ghostId: 'tab-demo-a' },+ allowOpen: true,+ });++ // 野值(路径穿越形状 / 缺失)进不了命令通道。+ for (const ghostId of ['../escape', 'UPPER', '', undefined]) {+ await expect(+ handler(+ { sender: mainWebContents },+ {+ command: { type: 'open-ghost-tab', sessionId: 's1', ghostId },+ allowOpen: true,+ },+ ),+ ).rejects.toThrow(/ghostId/);+ }+ });+it('drops commands from secondary renderers but still validates their payloads', async () => {const controller = makeController();const { handler } = registerController(controller);diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.tsindex 00d2c675b0..66ce25a18c 100644--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts@@ -18,6 +18,7 @@ import type {RsbWindowContext,} from '../../shared/rightSidebarWindow.js';import { parseConversationSearchJump } from '../../shared/conversationSearchJump.js';+import { isValidGhostId } from '../../shared/ghost.js';import type { RsbWindowController } from './controller.js';const log = createLogger('right-sidebar-window-ipc');@@ -54,6 +55,13 @@ function parseCommand(raw: unknown): RsbWindowCommand {}return { type: 'open-web-browser', sessionId: r.sessionId, url: r.url };}+ if (r.type === 'open-ghost-tab') {+ // ghostId 复用身份卡同一校验(小写/数字/连字符,1–32),野值不进命令通道。+ if (!isValidGhostId(r.ghostId)) {+ throwIpcError('INVALID_PARAMS', 'command.ghostId must be a valid ghost id');+ }+ return { type: 'open-ghost-tab', sessionId: r.sessionId, ghostId: r.ghostId };+ }if (r.type === 'ensure-orca-workers-tab') {const hasFocusWorkerSessionId =Object.prototype.hasOwnProperty.call(r, 'focusWorkerSessionId') &&diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsxindex 59f9847df8..f0eaa4bdd9 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx@@ -8,6 +8,13 @@ import { confirmAndInstallGhost } from '../installFlow';vi.mock('@/lib/toast', () => ({toast: { success: vi.fn(), error: vi.fn() },}));+// node 环境无 window:logger 与真实的开页签实现(拉起 right-sidebar store 链)都桩掉。+vi.mock('@/lib/logger', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../features/right-sidebar/lib/openGhostTabInSidebar', () => ({+ openGhostTabInSidebar: vi.fn(async () => undefined),+}));const baseManifest = {schemaVersion: 2 as const,@@ -90,3 +97,147 @@ describe('installFlow · 装入确认', () => {expect(install).toHaveBeenCalledTimes(1);});});++describe('installFlow · tab 型插件「立即开启并打开页签」', () => {+ const tabManifest = {+ schemaVersion: 2 as const,+ id: 'tab-demo-a',+ name: '页签演示 A',+ version: '1.0.0',+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['panel'] as const,+ panel: { html: 'panel.html', position: 'tab' as const },+ };++ function tabDeps(overrides: {+ checked?: boolean;+ sessionId?: string | null;+ openGhostTab?: (sessionId: string, ghostId: string) => Promise<void>;+ }) {+ const confirmWithCheckbox = vi.fn(async () => ({+ ok: true,+ checked: overrides.checked ?? true,+ }));+ return {+ deps: {+ t: ((key: string) => key) as never,+ confirm: vi.fn(async () => true),+ confirmWithCheckbox,+ ...(overrides.sessionId !== undefined+ ? { getSidebarSessionId: () => overrides.sessionId ?? null }+ : {}),+ ...(overrides.openGhostTab ? { openGhostTab: overrides.openGhostTab } : {}),+ },+ confirmWithCheckbox,+ };+ }++ it('tab 清单 + 有会话 + 勾选 → enable 装入并打开 ghost:<id> 页签,勾选文案换 open 版', async () => {+ const { install } = setupWindow(tabManifest);+ const openGhostTab = vi.fn(async () => undefined);+ const { deps: d, confirmWithCheckbox } = tabDeps({ sessionId: 's1', openGhostTab });++ await confirmAndInstallGhost('/tmp/tab.cindy', d);++ expect(confirmWithCheckbox).toHaveBeenCalledWith(+ expect.objectContaining({+ checkboxLabel: 'settings.ghosts.installConfirm.enableNowOpenTab',+ }),+ );+ expect(install).toHaveBeenCalledWith('/tmp/tab.cindy', {+ enable: true,+ expectedPackageSha256: 'a'.repeat(64),+ });+ expect(openGhostTab).toHaveBeenCalledWith('s1', 'tab-demo-a');+ expect(toast.success).toHaveBeenCalledTimes(1);+ });++ it('不勾选 → 沉睡装入,不打开页签', async () => {+ setupWindow(tabManifest);+ const openGhostTab = vi.fn(async () => undefined);+ const { deps: d } = tabDeps({ checked: false, sessionId: 's1', openGhostTab });++ await confirmAndInstallGhost('/tmp/tab.cindy', d);++ expect(openGhostTab).not.toHaveBeenCalled();+ });++ it('无会话入口(getter 缺省/返回 null)→ 勾选文案保持旧版,勾了也不打开', async () => {+ setupWindow(tabManifest);+ const openGhostTab = vi.fn(async () => undefined);++ const noGetter = tabDeps({ openGhostTab });+ await confirmAndInstallGhost('/tmp/tab.cindy', noGetter.deps);+ expect(noGetter.confirmWithCheckbox).toHaveBeenCalledWith(+ expect.objectContaining({ checkboxLabel: 'settings.ghosts.installConfirm.enableNow' }),+ );++ const nullGetter = tabDeps({ sessionId: null, openGhostTab });+ await confirmAndInstallGhost('/tmp/tab.cindy', nullGetter.deps);++ expect(openGhostTab).not.toHaveBeenCalled();+ });++ it('停靠形态(position: right)勾选只带电,不打开页签', async () => {+ setupWindow({+ ...tabManifest,+ panel: { html: 'panel.html', position: 'right' as const },+ });+ const openGhostTab = vi.fn(async () => undefined);+ const { deps: d, confirmWithCheckbox } = tabDeps({ sessionId: 's1', openGhostTab });++ await confirmAndInstallGhost('/tmp/dock.cindy', d);++ expect(confirmWithCheckbox).toHaveBeenCalledWith(+ expect.objectContaining({ checkboxLabel: 'settings.ghosts.installConfirm.enableNow' }),+ );+ expect(openGhostTab).not.toHaveBeenCalled();+ });++ it('Main 原生确认取消(canceled)→ 不打开页签', async () => {+ setupWindow(tabManifest, { canceled: true });+ const openGhostTab = vi.fn(async () => undefined);+ const { deps: d } = tabDeps({ sessionId: 's1', openGhostTab });++ await confirmAndInstallGhost('/tmp/tab.cindy', d);++ expect(openGhostTab).not.toHaveBeenCalled();+ });++ it('打开页签失败只记日志:装入成功 toast 不改口、不冒错误', async () => {+ setupWindow(tabManifest);+ const openGhostTab = vi.fn(async () => {+ throw new Error('sidebar exploded');+ });+ const { deps: d } = tabDeps({ sessionId: 's1', openGhostTab });++ await confirmAndInstallGhost('/tmp/tab.cindy', d);++ expect(toast.success).toHaveBeenCalledTimes(1);+ expect(toast.error).not.toHaveBeenCalled();+ });++ it('安装期间切换会话(getter 变 null)→ 不打开页签(避免写入旧会话)', async () => {+ setupWindow(tabManifest);+ const openGhostTab = vi.fn(async () => undefined);+ let currentSession: string | null = 's1';+ const confirmWithCheckbox = vi.fn(async () => {+ // 模拟用户在确认弹窗期间切走会话+ currentSession = null;+ return { ok: true, checked: true };+ });+ const deps = {+ t: ((key: string) => key) as never,+ confirm: vi.fn(async () => true),+ confirmWithCheckbox,+ getSidebarSessionId: () => currentSession,+ openGhostTab,+ };++ await confirmAndInstallGhost('/tmp/tab.cindy', deps);++ expect(openGhostTab).not.toHaveBeenCalled();+ expect(toast.success).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsxindex 41d49bdba6..f63f487826 100644--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx@@ -1,6 +1,7 @@import type { TFunction } from 'i18next';import type { ReactNode } from 'react';+import { createLogger } from '@/lib/logger';import { toast } from '@/lib/toast';import { extractIpcError } from '@/utils/ipcError';import {@@ -10,6 +11,7 @@ import {type GhostTrustInfo,type InstalledGhost,} from '../../shared/ghost';+import { openGhostTabInSidebar } from '../features/right-sidebar/lib/openGhostTabInSidebar';import {GhostInstallReview,GhostPermissionDiffView,@@ -57,11 +59,20 @@ interface InstallFlowDeps {cancelText?: string;checkboxLabel: string;}) => Promise<{ ok: boolean; checked: boolean }>;+ /**+ * 当前右侧栏会话 id;无会话视图的入口(插件页)不传或返回 null。+ * 只在「tab 型插件 + 勾选立即开启」时消费:装完自动展开右侧栏并打开页签。+ */+ getSidebarSessionId?: () => string | null;+ /** 打开/聚焦插件页签;缺省 openGhostTabInSidebar,测试注入用。 */+ openGhostTab?: (sessionId: string, ghostId: string) => Promise<void>;}/** 意识装入/更新确认框统一宽度:权限清单是富内容,默认 400px 折行到累。 */const GHOST_CONFIRM_MAX_WIDTH = 520;+const installFlowLog = createLogger('ghost-install-flow');+/** 同 id 已装清单查询(sendSync,极小)。 */function findInstalled(id: string): InstalledGhost | null {try {@@ -158,6 +169,10 @@ export async function confirmAndInstallGhost(: t('settings.ghosts.installConfirm.meta', { version: manifest.version });// "立即开启"勾选(2026-07-09 Lizi 定案):默认不勾 = 装入即沉睡,// 用户显式勾选才带电。装入 ≠ 授权运行。+ // tab 型插件(panel.position:'tab')在有会话可落时,勾选语义升级为+ // 「立即开启并打开页签」——文案与真实行为一致,无会话入口不许诺"打开"。+ const sidebarSessionId = deps.getSidebarSessionId?.() ?? null;+ const willOpenTab = manifest.panel?.position === 'tab' && sidebarSessionId !== null;const { ok, checked: enable } = await confirmWithCheckbox({title: t('settings.ghosts.installConfirm.title', { name: manifest.name }),content: (@@ -171,7 +186,11 @@ export async function confirmAndInstallGhost(maxWidth: GHOST_CONFIRM_MAX_WIDTH,confirmText: t('settings.ghosts.installConfirm.confirm'),cancelText: t('settings.ghosts.installConfirm.cancel'),- checkboxLabel: t('settings.ghosts.installConfirm.enableNow'),+ checkboxLabel: t(+ willOpenTab+ ? 'settings.ghosts.installConfirm.enableNowOpenTab'+ : 'settings.ghosts.installConfirm.enableNow',+ ),});if (!ok) return;@@ -187,6 +206,27 @@ export async function confirmAndInstallGhost(? t('settings.ghosts.toast.installed', { name: ghost.manifest.name }): t('settings.ghosts.toast.installedAsleep', { name: ghost.manifest.name }),);+ if (enable && willOpenTab) {+ // 兑现勾选文案:展开右侧栏并打开/聚焦页签(侧栏抽离时路由到子窗口)。+ // main 在 install() resolve 前已广播 ghosts:changed,Tab 注册表通常已就位;+ // 极端竞态下 Shell 的 PlaceholderBody 兜底,注册到位即自愈。+ // 打开失败不回滚安装,只记日志——装入本身已成功,toast 不改口。+ // 重新读取会话 ID——用户可能在确认弹窗/安装期间切换了会话,+ // 用安装完成时的当前会话,而非弹窗出现时的快照。+ const currentSessionId = deps.getSidebarSessionId?.() ?? null;+ if (currentSessionId !== null) {+ const openGhostTab = deps.openGhostTab ?? openGhostTabInSidebar;+ try {+ await openGhostTab(currentSessionId, ghost.manifest.id);+ } catch (err) {+ installFlowLog.warn('open ghost tab after install failed', {+ ghostId: ghost.manifest.id,+ sessionId: currentSessionId,+ err,+ });+ }+ }+ }} catch (err) {toast.error(t(ghostInstallErrorKey(extractIpcError(err)?.code)));}diff --git a/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx b/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsxindex 55405b73e1..4fa78fb397 100644--- a/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx+++ b/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx@@ -49,9 +49,18 @@ type DragHint = 'cindy' | 'share';export interface GlobalDropImportListenerProps {onOpenShareImport: (filePath: string) => void;+ /**+ * 当前右侧栏会话 id 的 getter(MainLayout 的 rightSidebarSessionIdRef 读值,+ * prop 身份稳定)。装入 tab 型插件勾选「立即开启」时用来自动打开页签;+ * 无会话视图返回 null = 跳过自动打开。+ */+ getRightSidebarSessionId?: () => string | null;}-export function GlobalDropImportListener({ onOpenShareImport }: GlobalDropImportListenerProps) {+export function GlobalDropImportListener({+ onOpenShareImport,+ getRightSidebarSessionId,+}: GlobalDropImportListenerProps) {const [dragHint, setDragHint] = useState<DragHint | null>(null);const dragDepthRef = useRef(0);// 当前拖拽序列是否已被 capture 层接管(MIME 悬停识别命中):置位后本序列的@@ -66,13 +75,20 @@ export function GlobalDropImportListener({ onOpenShareImport }: GlobalDropImportuseEffect(() => {const consumePending = async () => {const { filePath } = await window.electronAPI.ghosts.takePendingInstall();- if (filePath) await confirmAndInstallGhost(filePath, { t, confirm, confirmWithCheckbox });+ if (filePath) {+ await confirmAndInstallGhost(filePath, {+ t,+ confirm,+ confirmWithCheckbox,+ getSidebarSessionId: getRightSidebarSessionId,+ });+ }};void consumePending().catch((err) => log.warn('consume pending cindy install failed', err));return window.electronAPI.ghosts.onInstallRequested(() => {void consumePending().catch((err) => log.warn('consume pending cindy install failed', err));});- }, [confirm, confirmWithCheckbox, t]);+ }, [confirm, confirmWithCheckbox, getRightSidebarSessionId, t]);useEffect(() => {// 悬停识别:单文件且 MIME 命中才给遮罩。@@ -132,7 +148,12 @@ export function GlobalDropImportListener({ onOpenShareImport }: GlobalDropImportmarkGlobalDropIntercepted(e);if (kind === 'cindy') {// 验明正身 → 确认弹窗 → 装入的编排在 installFlow(与设置页装入按钮同契约)。- void confirmAndInstallGhost(path, { t, confirm, confirmWithCheckbox });+ void confirmAndInstallGhost(path, {+ t,+ confirm,+ confirmWithCheckbox,+ getSidebarSessionId: getRightSidebarSessionId,+ });return;}void window.electronAPI.localDb.sessionShare@@ -190,7 +211,7 @@ export function GlobalDropImportListener({ onOpenShareImport }: GlobalDropImportwindow.removeEventListener('dragover', onDragOver);window.removeEventListener('drop', onDrop);};- }, [confirm, confirmWithCheckbox, navigate, onOpenShareImport, t]);+ }, [confirm, confirmWithCheckbox, getRightSidebarSessionId, navigate, onOpenShareImport, t]);return (<>diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex 82ea123450..b2b74f5ad5 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -244,6 +244,9 @@ export function MainLayout() {const [rightSidebarSessionId, setRightSidebarSessionId] = useState<string | null>(null);const rightSidebarSessionIdRef = useRef(rightSidebarSessionId);rightSidebarSessionIdRef.current = rightSidebarSessionId;+ // 给树内远端消费方(如 GlobalDropImportListener 的装入编排)的稳定 getter:+ // 读 ref 拿最新值,prop 身份不随会话切换变化,不触发下游 effect 重挂。+ const getRightSidebarSessionId = useCallback(() => rightSidebarSessionIdRef.current, []);const declareRightSidebarSessionId = useCallback((sessionId: string | null, opts: RightSidebarSessionDeclarationOptions = {}) => {rightSidebarSessionIdRef.current = sessionId;@@ -1320,7 +1323,10 @@ export function MainLayout() {{/* FeiShu Bot conflict dialog -- subscribes to main process push and surfaces a global modal */}<FeishuConflictDialogHost />{/* 窗口级拖拽兜底:拖 .cshare 进窗口空白处 → 会话导入向导 */}- <GlobalDropImportListener onOpenShareImport={openShareImport} />+ <GlobalDropImportListener+ onOpenShareImport={openShareImport}+ getRightSidebarSessionId={getRightSidebarSessionId}+ />{shareImportRequest && (<SessionShareImportWizardkey={shareImportRequest.id}diff --git a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsxindex 5bce33fbcd..5a06d6ab4b 100644--- a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx@@ -40,6 +40,10 @@ import { WindowControls } from '@/components/title-bar/WindowControls';import { useAppShortcut } from '@/hooks/useAppShortcut';import { useCloseShortcutShellOwner } from '@/hooks/useCloseWindowShortcut';import { createLogger } from '@/lib/logger';+import {+ ensureGhostPanelsRegistered,+ useGhostPanelsSync,+} from '@/cindy-brain/ghostPanels';const log = createLogger('SidebarWindowLayout');@@ -53,6 +57,10 @@ interface SidebarWindowContext {export function SidebarWindowLayout() {const { t } = useTranslation();useDeviceLinkRemoteProjects();+ // 意识页签注册:子窗口没有 LayoutRoot,必须自行初始化 ghost 面板/页签注册表+ // 并订阅 ghosts:changed,否则 open-ghost-tab 命令路由到这里时 kind 未注册。+ ensureGhostPanelsRegistered();+ useGhostPanelsSync();const isMac = window.electronAPI?.platform === 'darwin';const [ctx, setCtx] = useState<SidebarWindowContext | null>(null);diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.tsindex 9326cf09c1..d686583e49 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts@@ -72,9 +72,12 @@ describe('executeSidebarCommand', () => {focusTab: false,});await executeSidebarCommand({ type: 'close-orca-workers-tab', sessionId: 's1' });+ await executeSidebarCommand({ type: 'open-ghost-tab', sessionId: 's1', ghostId: 'tab-demo-a' });expect(ensureHydrated).toHaveBeenCalledWith('s1');expect(addOrFocusSingletonTab).toHaveBeenCalledWith('s1', 'terminal');+ // 插件页签:与 terminal 同款单例语义,kind 为 ghost:<id>。+ expect(addOrFocusSingletonTab).toHaveBeenCalledWith('s1', 'ghost:tab-demo-a');expect(openUrlInSidebarBrowser).toHaveBeenCalledWith('s1', 'https://example.com/');expect(openDirInSidebarFileBrowser).toHaveBeenCalledWith('s1', 'src');expect(openFileInSidebarFileBrowser).toHaveBeenCalledWith('s1', 'src/App.tsx');diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openGhostTabInSidebar.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openGhostTabInSidebar.test.tsnew file mode 100644index 0000000000..5964300fbf--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openGhostTabInSidebar.test.ts@@ -0,0 +1,77 @@+// @vitest-environment jsdom++/**+ * openGhostTabInSidebar — 覆盖宿主裁决三分支(仿 openInSidebarBrowser.test):+ * - attached:ensureHydrated → addOrFocusSingletonTab(ghost:<id>) → 请求可见+ * - routed:命令已到子窗口,本地只请求可见(持久化折叠态)+ * - queued / stale-context:不动本地 store 也不请求可见+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../../store', () => ({+ addOrFocusSingletonTab: vi.fn(async () => ({ id: 't_1', kind: 'ghost:tab-demo-a', state: null })),+ ensureHydrated: vi.fn(async () => undefined),+}));+vi.mock('../sidebarCommands', () => ({+ requestRightSidebarVisibility: vi.fn(),+}));+vi.mock('../detachedSidebarRouting', () => ({+ routeSidebarCommand: vi.fn(async () => 'attached'),+}));++import { addOrFocusSingletonTab, ensureHydrated } from '../../store';+import { requestRightSidebarVisibility } from '../sidebarCommands';+import { routeSidebarCommand } from '../detachedSidebarRouting';+import { openGhostTabInSidebar } from '../openGhostTabInSidebar';++describe('openGhostTabInSidebar', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(routeSidebarCommand).mockResolvedValue('attached');+ });++ it('attached:先 hydrate 再单例聚焦 ghost:<id>,最后请求侧栏可见', async () => {+ await openGhostTabInSidebar('s1', 'tab-demo-a');++ expect(routeSidebarCommand).toHaveBeenCalledWith({+ type: 'open-ghost-tab',+ sessionId: 's1',+ ghostId: 'tab-demo-a',+ });+ expect(ensureHydrated).toHaveBeenCalledWith('s1');+ expect(vi.mocked(ensureHydrated).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(addOrFocusSingletonTab).mock.invocationCallOrder[0],+ );+ expect(addOrFocusSingletonTab).toHaveBeenCalledWith('s1', 'ghost:tab-demo-a');+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', { sessionId: 's1' });+ });++ it('routed:命令交给子窗口,本地不写 store、仍请求可见', async () => {+ vi.mocked(routeSidebarCommand).mockResolvedValueOnce('routed');++ await openGhostTabInSidebar('remote-lead', 'tab-demo-a');++ expect(ensureHydrated).not.toHaveBeenCalled();+ expect(addOrFocusSingletonTab).not.toHaveBeenCalled();+ expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {+ sessionId: 'remote-lead',+ });+ });++ it.each(['queued', 'stale-context'] as const)('%s:不写本地也不请求可见', async (routeResult) => {+ vi.mocked(routeSidebarCommand).mockResolvedValueOnce(routeResult);++ await openGhostTabInSidebar('stale', 'tab-demo-a');++ expect(ensureHydrated).not.toHaveBeenCalled();+ expect(addOrFocusSingletonTab).not.toHaveBeenCalled();+ expect(requestRightSidebarVisibility).not.toHaveBeenCalled();+ });++ it('addOrFocusSingletonTab 失败时向上抛,不请求可见(调用方兜错)', async () => {+ vi.mocked(addOrFocusSingletonTab).mockRejectedValueOnce(new Error('boom'));+ await expect(openGhostTabInSidebar('s1', 'tab-demo-a')).rejects.toThrow('boom');+ expect(requestRightSidebarVisibility).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.tsindex d9e72f4635..b50b8e96e8 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts@@ -1,5 +1,6 @@/** 执行 main 已裁决并推给当前 renderer host 的 RSB command。 */+import { ghostPanelKind } from '../../../../shared/ghost';import type { RsbWindowCommand } from '../../../../shared/rightSidebarWindow';import { addOrFocusSingletonTab, ensureHydrated } from '../store';import {@@ -41,6 +42,12 @@ export async function executeSidebarCommand(command: RsbWindowCommand): Promise<await closeOrcaWorkersTabAfterTeamEnd(command.sessionId);return;}+ if (command.type === 'open-ghost-tab') {+ // 插件页签与 review/terminal 同款单例语义:已开则聚焦,未开则新建。+ await ensureHydrated(command.sessionId);+ await addOrFocusSingletonTab(command.sessionId, ghostPanelKind(command.ghostId));+ return;+ }await ensureHydrated(command.sessionId);await addOrFocusSingletonTab(command.sessionId, 'terminal');}diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openGhostTabInSidebar.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openGhostTabInSidebar.tsnew file mode 100644index 0000000000..c9556d9764--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openGhostTabInSidebar.ts@@ -0,0 +1,34 @@+/**+ * openGhostTabInSidebar —— "打开/聚焦插件页签"的统一入口。+ *+ * 装入流程(installFlow 勾选「立即开启」)等远端调用点通过它把一个+ * panel.position:'tab' 的插件页签带到用户面前:+ * 1. 先经 routeSidebarCommand 请 main 裁决宿主 —— 侧栏抽离成独立窗口时命令+ * 被路由过去,由子窗口的 executeSidebarCommand 落地;+ * 2. attached(内嵌)形态本地执行:ensureHydrated 消除与 Shell 异步 list+ * 拉取的竞态(同 openInSidebarBrowser 的注释),再 addOrFocusSingletonTab+ * —— 插件页签每会话单例,已开则聚焦;+ * 3. 请求右侧栏可见("已打开 → no-op"由 MainLayout 订阅端自行判断)。+ */++import { ghostPanelKind } from '../../../../shared/ghost';+import { addOrFocusSingletonTab, ensureHydrated } from '../store';+import { routeSidebarCommand } from './detachedSidebarRouting';+import { requestRightSidebarVisibility } from './sidebarCommands';++/** 在指定 session 的右侧栏里打开/聚焦某插件的页签,并确保侧边栏可见。 */+export async function openGhostTabInSidebar(sessionId: string, ghostId: string): Promise<void> {+ const routeResult = await routeSidebarCommand({+ type: 'open-ghost-tab',+ sessionId,+ ghostId,+ });+ if (routeResult !== 'attached') {+ if (routeResult !== 'routed') return;+ requestRightSidebarVisibility('open', { sessionId });+ return;+ }+ await ensureHydrated(sessionId);+ await addOrFocusSingletonTab(sessionId, ghostPanelKind(ghostId));+ requestRightSidebarVisibility('open', { sessionId });+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex f204c50a4a..2e33bf760c 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2309,6 +2309,7 @@"meta": "Version {{version}}. Installs locally and can be uninstalled anytime.","metaWithAuthor": "By {{author}} · Version {{version}}. Installs locally and can be uninstalled anytime.","enableNow": "Enable right after install",+ "enableNowOpenTab": "Enable and open its tab right after install","expandDescription": "Show Full Description","collapseDescription": "Hide Full Description"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 9891035fad..401b781aa5 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2308,6 +2308,7 @@"meta": "バージョン {{version}}。ローカルにインストールされ、いつでもアンインストールできます。","metaWithAuthor": "作者 {{author}} · バージョン {{version}}。ローカルにインストールされ、いつでもアンインストールできます。","enableNow": "インストール後すぐに有効化",+ "enableNowOpenTab": "インストール後すぐに有効化してタブを開く","expandDescription": "紹介全文を表示","collapseDescription": "紹介を折りたたむ"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex dc290d9e8d..db206e20cf 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2308,6 +2308,7 @@"meta": "버전 {{version}}. 로컬에 설치되며 언제든 제거할 수 있습니다.","metaWithAuthor": "제작자 {{author}} · 버전 {{version}}. 로컬에 설치되며 언제든 제거할 수 있습니다.","enableNow": "설치 후 바로 활성화",+ "enableNowOpenTab": "설치 후 바로 활성화하고 탭 열기","expandDescription": "전체 소개 보기","collapseDescription": "소개 접기"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex a7c255866e..0db4520e37 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2308,6 +2308,7 @@"meta": "版本 {{version}}。将安装到本机,可随时卸载。","metaWithAuthor": "作者 {{author}} · 版本 {{version}}。将安装到本机,可随时卸载。","enableNow": "安装后立即生效",+ "enableNowOpenTab": "安装后立即生效并打开页签","expandDescription": "展开完整介绍","collapseDescription": "收起介绍"},diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex ddb4aef346..6c343982a0 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1004,7 +1004,9 @@ export interface GhostTrustInfo {}/** 意识面板的 panelKind(布局树寻址用)。 */-export function ghostPanelKind(id: string): string {+// 返回类型收窄到模板字面量:右侧栏 TabKindId 含 `ghost:${string}` 分支,+// 调用方无需再 as 断言;对既有 string 消费方完全兼容。+export function ghostPanelKind(id: string): `ghost:${string}` {return `${GHOST_PANEL_KIND_PREFIX}${id}`;}diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.tsindex 49b01e45c1..6d391b81f2 100644--- a/apps/desktop/src/shared/rightSidebarWindow.ts+++ b/apps/desktop/src/shared/rightSidebarWindow.ts@@ -33,6 +33,8 @@ export interface RsbWindowContext {export type RsbWindowCommand =| { type: 'open-terminal'; sessionId: string }| { type: 'open-web-browser'; sessionId: string; url: string }+ /** 打开/聚焦插件页签(panel.position:'tab',每会话单例;装入即开与未来入口共用)。 */+ | { type: 'open-ghost-tab'; sessionId: string; ghostId: string }| {type: 'ensure-orca-workers-tab';sessionId: string;