Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
插件停靠面板收束为右侧栏全局页签;mainView 可在侧边栏中打开
Dashabb83fa21ca9
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex c3bf43daf7..59250f72cd 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -2172,12 +2172,6 @@ const config: ForgeConfig = {config: 'vite.preload.config.ts',target: 'preload',},- {- // 插件面板独立窗口专用 preload:最小权限 bridge。- entry: 'src/preload/ghostPanelWindowPreload.ts',- config: 'vite.preload.config.ts',- target: 'preload',- },{// RSB 内置浏览器 webview 的 guest 注入层(页面评论 overlay)。由// main 的 webview hardener 在 will-attach-webview 时按diff --git a/apps/desktop/help-knowledge/appearance.md b/apps/desktop/help-knowledge/appearance.mdindex 076c14c931..9e65b6b62b 100644--- a/apps/desktop/help-knowledge/appearance.md+++ b/apps/desktop/help-knowledge/appearance.md@@ -26,7 +26,6 @@ Settings > Appearance controls how the app looks. It starts with the theme and aThe example filenames describe the final display areas; source images may be exported at 2x/3x while keeping the same aspect ratios. Paths must be absolute JSON strings; spaces do not need shell quotes. PNG, JPEG, and WebP are supported. Transparent padding is trimmed at render time without changing the source file. Only `brand.icon` and `brand.logo` are recognized; the previous single-image fields are not compatible with the redesigned two-asset layout.-- **Plugin panel restore entry**: choose whether minimized plugin panels come back from a floating bubble or from the sidebar.- **Panel layout**: panel positions and widths are saved automatically; **Restore default layout** puts them back.- **Reply Animation**: new reply text fades in while it streams. Turn it off to show text immediately. It stays off when your system reduces motion.diff --git a/apps/desktop/help-knowledge/plugins.md b/apps/desktop/help-knowledge/plugins.mdindex 1b12691936..a671a40057 100644--- a/apps/desktop/help-knowledge/plugins.md+++ b/apps/desktop/help-knowledge/plugins.md@@ -4,7 +4,7 @@ title: Plugins (extending what the agents can do)summary: What plugins are, how to browse / install / enable / disable them, per-working-directory control, the permission model, and invoking one with a $command.tab: ghosts----Plugins (internally "意识" / Ghost) extend what the agents can do — they add AI-callable tools, dockable UI panels, and "ask Cindy to make it" media generation. Each plugin is a self-contained `.cindy` capability pack that runs in its own isolated sandbox.+Plugins (internally "意识" / Ghost) extend what the agents can do — they add AI-callable tools, panels that live as pinned tabs in the right sidebar, full-page app views, and "ask Cindy to make it" media generation. Each plugin is a self-contained `.cindy` capability pack that runs in its own isolated sandbox.**The Plugins page:**@@ -22,7 +22,7 @@ Plugins (internally "意识" / Ghost) extend what the agents can do — they add**Enabling and disabling:**-- **Enable / disable (globally)** from the plugin's detail page. Disabling puts its tools and panel to sleep but keeps the plugin installed — its layout position is remembered and restored when you re-enable it.+- **Enable / disable (globally)** from the plugin's detail page. Disabling puts its tools and panel to sleep but keeps the plugin installed — its right-sidebar tab is kept and comes back when you re-enable it. A plugin's panel shows up as a pinned tab in the right sidebar that stays across tasks; close it from the tab, and reopen it later by right-clicking the plugin's entry in the left sidebar and choosing "Open in the sidebar".- **Disable for one working directory only** — a plugin can be turned off just for a specific project. In that project's sessions it behaves as if it isn't installed (its tools and `$command` are unavailable there); everywhere else it stays on.**Installing:**diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.tsindex a9d5ef8ba0..9404d6051f 100644--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts@@ -34,7 +34,6 @@ vi.mock('electron', () => ({const nativePopupWebContentsIds = vi.hoisted(() => new Set<number>());const resourceUsageWebContentsIds = vi.hoisted(() => new Set<number>());const rsbWindowWebContentsIds = vi.hoisted(() => new Set<number>());-const ghostPanelWebContentsIds = vi.hoisted(() => new Set<number>());const reviewArtifactConfirmWebContentsIds = vi.hoisted(() => new Set<number>());vi.mock('../rsb-browser-bridge/native-popup-surfaces', () => ({@@ -51,10 +50,6 @@ vi.mock('../right-sidebar-window/registry.js', () => ({isRsbWindowWebContentsId: (webContentsId: number) => rsbWindowWebContentsIds.has(webContentsId),}));-vi.mock('../ghost-panel-window/registry.js', () => ({- isGhostPanelWebContentsId: (webContentsId: number) =>- ghostPanelWebContentsIds.has(webContentsId),-}));vi.mock('../reviewer/reviewArtifactConfirmWindowRegistry.js', () => ({isReviewArtifactConfirmWebContentsId: (webContentsId: number) =>@@ -591,7 +586,6 @@ describe('installQuitHandler render-process-gone', () => {nativePopupWebContentsIds.clear();resourceUsageWebContentsIds.clear();rsbWindowWebContentsIds.clear();- ghostPanelWebContentsIds.clear();reviewArtifactConfirmWebContentsIds.clear();});@@ -693,21 +687,6 @@ describe('installQuitHandler render-process-gone', () => {}});- it('ghost panel renderer crash does NOT shut the app down', async () => {- ghostPanelWebContentsIds.add(46);- const { handler, app, restore } = await installAndGrabHandler();- try {- handler(undefined, { id: 46, getType: () => 'window' }, { reason: 'crashed', exitCode: 5 });- await new Promise((r) => setTimeout(r, 20));- expect(app.exit).not.toHaveBeenCalled();- expect(mocks.logger.warn).toHaveBeenCalledWith(- expect.stringContaining('ghost panel render-process-gone'),- );- } finally {- restore();- }- });-it('Review artifact consent renderer crash denies locally without shutting the app down', async () => {reviewArtifactConfirmWebContentsIds.add(47);const { handler, app, restore } = await installAndGrabHandler();diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 996b551ca7..c1091edaaa 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -749,19 +749,10 @@ import { ResourceUsageWindowController } from './resource-usage-window/controlleimport { createResourceUsageWindow } from './resource-usage-window/window.js';import { registerResourceUsageWindowIpc } from './resource-usage-window/ipc.js';import { isResourceUsageOpenSender } from './resource-usage-window/open-sender.js';-import { GhostPanelWindowsController } from './ghost-panel-window/controller.js';-import { createGhostPanelWindow } from './ghost-panel-window/window.js';-import { registerGhostPanelWindowIpc } from './ghost-panel-window/ipc.js';import { SidebarTabWindowsController } from './sidebar-tab-window/controller.js';import { createSidebarTabWindow } from './sidebar-tab-window/window.js';import { registerSidebarTabWindowIpc } from './sidebar-tab-window/ipc.js';import { setRightSidebarTabsChangeBroadcaster } from './localDb/ipc/rightSidebarTabs.js';-import {- patchGhostPanelWindowEntry,- readGhostPanelWindowsSettings,- removeGhostPanelWindowEntry,- resetGhostPanelWindowSettingsForStartup,-} from './ghost-panel-window/settings-store.js';import {readRsbWindowSettings,resetRsbWindowSettingsForStartup,@@ -1115,18 +1106,15 @@ import {getGhostManager,getGhostSessionActivityTracker,interruptGhostCallsForAccountBoundary,- isGhostAvailableForActiveSession,reconcileGhostOauthAccountsForActiveOwner,refreshGhostLocalization,refreshPluginUsageBindings,registerGhostIpc,runStableOwnerPostCommitTask,setGhostNodeRuntimeStartAttemptContextReader,- setGhostsChangedObserver,suspendAllGhosts,waitForGhostMutations,} from './cindy-brain/index.js';-import { installedGhostStoragePart } from '../shared/pluginIdentity.js';import { setCodexImageAuthBinding } from './cindy-brain/codexImageAuthBinding.js';import { listActiveClaudeBackgroundActivitySessions } from './maker-host/claude-session-background-activity.js';import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';@@ -2297,58 +2285,6 @@ registerRsbWindowIpc({getMainWindow: () => mainWindowRef,});-// ── 插件停靠面板独立窗口(ghost panel window)────────────────────────────-// 每 ghostId 一扇窗:PanelChrome「独立窗口」按钮 → setDetached(id, true) 开窗,-// 主窗布局树里该 pane 停止渲染(树不动);关窗/合并即回停靠。装/卸/启停广播-// 经 setGhostsChangedObserver 喂 reconcile,失去资格的窗口即时收掉。-// deps 同样全 lazy(isQuitting 声明在后),状态机见 ghost-panel-window/controller.ts。-resetGhostPanelWindowSettingsForStartup();-const ghostPanelWindowsController = new GhostPanelWindowsController({- settings: {- read: readGhostPanelWindowsSettings,- patchEntry: patchGhostPanelWindowEntry,- removeEntry: removeGhostPanelWindowEntry,- },- createWindow: (ghostId) => {- const ghost = getGhostManager()- .list()- .find((g) => installedGhostStoragePart(g) === ghostId);- const title = ghost?.manifest.panel?.title ?? ghost?.manifest.name ?? ghostId;- return createGhostPanelWindow(ghostId, title);- },- isGhostDetachable: (ghostId) => {- const ghost = getGhostManager()- .list()- .find((g) => installedGhostStoragePart(g) === ghostId);- return (- ghost !== undefined &&- ghost.enabled !== false &&- ghost.manifest.panel !== undefined &&- ghost.manifest.panel.position !== 'tab' &&- isGhostAvailableForActiveSession(ghostId)- );- },- broadcastState: (state) => {- for (const win of BrowserWindow.getAllWindows()) {- if (win.isDestroyed()) continue;- try {- win.webContents.send(MAKER_PUSH.GHOST_PANEL_WINDOW_STATE_CHANGED, state);- } catch {- // window torn down mid-broadcast — ignore- }- }- },- sendToWindow: (win, channel, payload) => {- try {- win.webContents.send(channel, payload);- } catch {- /* ignore */- }- },- isQuitting: () => isQuitting,- log: createLogger('ghost-panel-window-controller'),-});-registerGhostPanelWindowIpc(ghostPanelWindowsController);// ── 右侧栏单页签独立窗口(sidebar tab window)────────────────────────────// 每个弹出的页签一扇窗:侧栏「在独立窗口中打开」→ open(request);主窗侧栏把该@@ -2438,10 +2374,6 @@ const remoteDesktopViewerWindows = new RemoteDesktopViewerWindows((sender) =>);remoteDesktopViewerWindows.register();-setGhostsChangedObserver((ghosts) => {- ghostPanelWindowsController.reconcile(ghosts);-});-const rsbBrowserRegistry = getRsbBrowserBridge();registerRsbNativePopupSurfaceIpc(rsbBrowserRegistry);registerRsbBrowserBridgeIpc({@@ -2540,7 +2472,6 @@ setAppSessionCommitBoundaryHook(() => {cancelClaudeCliLogin();clearAllSessionAttention();remoteDesktopViewerWindows.reset();- ghostPanelWindowsController.closeForOwnerChange();clearAllSessionProviders();clearAllSessionRuntimeAxes();clearAllSessionRuntimeControlStates();@@ -3099,7 +3030,6 @@ ipcMain.handle('app-menu:set-locale', (_event, locale: unknown): { ok: true } =>resourceUsageWindowController.setLocale(currentApplicationMenuLocale);remoteDesktopViewerWindows.setLocale(currentApplicationMenuLocale);rsbWindowController.setLocale(currentApplicationMenuLocale);- ghostPanelWindowsController.setLocale(currentApplicationMenuLocale);sidebarTabWindowsController.setLocale(currentApplicationMenuLocale);refreshGhostLocalization();const mainWindow = mainWindowRef && !mainWindowRef.isDestroyed() ? mainWindowRef : null;@@ -4004,7 +3934,6 @@ const createWindow = () => {resourceUsageWindowController.destroyWindow();remoteDesktopViewerWindows.reset();rsbWindowController.destroyWindow();- ghostPanelWindowsController.destroyAllWindows();sidebarTabWindowsController.destroyAllWindows();if (mainWindowRef === mainWindow) mainWindowRef = null;setDeepLinkMainWindow(null);@@ -9928,7 +9857,6 @@ onQuit('auth-manager', () => authManager.dispose(), 'sync');onQuit('windows-process-scan-workers', disposeWindowsProcessScanWorkers, 'sync');onQuit('resource-usage-window', () => resourceUsageWindowController.dispose(), 'sync');onQuit('rsb-window', () => rsbWindowController.dispose(), 'sync');-onQuit('ghost-panel-windows', () => ghostPanelWindowsController.dispose(), 'sync');onQuit('sidebar-tab-windows', () => sidebarTabWindowsController.dispose(), 'sync');onQuit('app-badge-clear', () => clearAllSessionAttention(), 'sync');onQuit('session-drag-preview', () => disposeSessionDragPreview(), 'sync');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 294066c785..5e6b2fe865 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -2145,14 +2145,12 @@ describe('FORGE_GUIDE', () => {'面板(panel.html/css/js)','panel.position','右侧栏页签',- // 2026-07-25 标准头系统按钮:主机画标题条,systemButtons 逐个关- // (maximize 撑满 / detach 独立窗口 / minimize 气泡);§2 样例与 §5- // 面板章节同步。+ // 2026-10 停靠面板收束:panel.position left = 右侧栏常驻面板(不跟对话的全局+ // 页签),systemButtons 保留兼容但不生效;§0 / §2 样例与 §5 面板章节同步。'systemButtons',- '撑满内容区',- '在独立窗口中打开',- 'minimize',- '最小化面板',+ '右侧栏常驻面板',+ '全局页签',+ '弹成独立 OS 窗口',// Manifest v3:直接字段声明能力;未知字段保留但不授权。'v3 直接用顶层字段声明插件贡献项与自主 Host 能力','v2 的 `slots` 只用于存量包兼容',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.tsindex 17fd7a3ae5..8d76af191b 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts@@ -351,10 +351,10 @@ describe('GhostScheduleSlot 硬约束:只能开面板,不能建任务', () => {* 否则取 candidates[0]。这里用判据函数复现那条规则,验证**无论窗口列表顺序如何**,* 回落都只会落到真正的主窗口 —— 副窗被判据挡在 candidates 之外,所以它排第几都不影响。*/-describe('选窗回落:插件面板聚焦时只能落到主窗口', () => {+describe('选窗回落:右侧栏弹出窗口聚焦时只能落到主窗口', () => {const MAIN = 'file:///app/index.html#/cc-agent';const SECONDARY = 'file:///app/index.html?secondaryWindow=1&bootSession=s1#/cc-agent';- const PANEL = 'file:///app/index.html?ghostPanelWindow=codex-reset-planner#/ghost-panel-window';+ const PANEL = 'file:///app/index.html?sidebarWindow=1&sidebarTabWindow=1#/sidebar-window';/** 复刻 index.ts 装配处的选窗规则(那里拿的是 BrowserWindow,这里用 URL 代表窗口)。 */const pick = (all: string[], focused: string | null): string | undefined => {@@ -367,7 +367,7 @@ describe('选窗回落:插件面板聚焦时只能落到主窗口', () => {['副窗在前', [SECONDARY, MAIN, PANEL]],['面板窗在前', [PANEL, SECONDARY, MAIN]],['副窗夹在中间', [PANEL, SECONDARY, MAIN, SECONDARY]],- ])('%s:focused=插件面板窗 → 回落到主窗口而不是副窗', (_label, all) => {+ ])('%s:focused=弹出窗 → 回落到主窗口而不是副窗', (_label, all) => {expect(pick(all, PANEL)).toBe(MAIN);});@@ -399,8 +399,7 @@ describe('isMainShellWindowUrl(投给哪个窗口的判据)', () => {it.each([// 这两类窗口与 MainLayout 平级,没有草稿订阅、也去不了自动化页。- ['插件面板独立窗(query)', 'file:///app/index.html?ghostPanelWindow=sign#/ghost-panel-window'],- ['插件面板独立窗(仅 hash)', 'file:///app/index.html#/ghost-panel-window'],+ ['右侧栏页签弹出窗(query)', 'file:///app/index.html?sidebarWindow=1&sidebarTabWindow=1#/sidebar-window'],['右侧栏独立窗(query)', 'file:///app/index.html?sidebarWindow=1#/sidebar-window'],['右侧栏独立窗(仅 hash)', 'file:///app/index.html#/sidebar-window'],// utility 窗:统一带 ?view=<名字>,一律接不住草稿(review 第三轮)。@@ -424,10 +423,12 @@ describe('isMainShellWindowUrl(投给哪个窗口的判据)', () => {/*** 这条是本能力的主使用路径:编写手册 §4.11.2 第 1 步就是「用户在你的插件面板上- * 点一下」,而面板可以被拉成独立窗口。那一刻 focused 是面板窗——若判据把它当成- * 可投窗口,草稿就投给了一个接不住它的窗口,用户点了什么都不会发生。+ * 点一下」,而面板(右侧栏插件视图页签)可以被弹成独立窗口。那一刻 focused 是弹出窗——+ * 若判据把它当成可投窗口,草稿就投给了一个接不住它的窗口,用户点了什么都不会发生。*/- it('插件面板独立窗绝不能被当作可投窗口(本能力的主使用路径)', () => {- expect(isMainShellWindowUrl('file:///app/index.html?ghostPanelWindow=codex-reset-planner#/ghost-panel-window')).toBe(false);+ it('右侧栏页签弹出窗绝不能被当作可投窗口(本能力的主使用路径)', () => {+ expect(+ isMainShellWindowUrl('file:///app/index.html?sidebarWindow=1&sidebarTabWindow=1#/sidebar-window'),+ ).toBe(false);});});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 84b0fc8da1..10fe38b410 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1639,8 +1639,8 @@ Cindy 会默认把自身版本写进这份具体插件的 \`minCindyVersion\`;值得主动摆出来让用户选的"隐藏"设计选项(详见对应章节):- **界面形态**:无界面(纯工具)/ 聊天卡片(card 能力,§4.5)/ Cindy 一级主视图- (mainView 能力,§4.20)/ 停靠面板(panel.position- left,§5)/ 插件页内独占面板(position "tab",从插件页「使用」打开、离开即关,§5)。+ (mainView 能力,§4.20)/ 右侧栏常驻面板(panel.position+ left,§5;作为不跟对话的全局页签钉在右侧栏)/ 插件页内独占面板(position "tab",从插件页「使用」打开、离开即关,§5)。- **唤起方式**:只靠 AI 按 whenToUse 自动想起,还是同时声明 \`command\` 点名词让用户显式点名(推荐,§2)。- **启动模式**:on-demand 按需拉起(缺省,推荐)/ resident 常驻(仅订阅型、要秒响应@@ -1729,17 +1729,15 @@ my-ghost/"panel": { "title": "面板标题", "html": "panel.html", "position": "left","minWidth": 240, "defaultFraction": 0.24,"systemButtons": { "maximize": false } },- // panel.position:面板显示形态。left(缺省)= 停靠主聊天窗左侧;- // "tab" = 插件页内的独占面板(用户在插件页点插件卡的「使用」打开,离开- // 插件页即关闭;同一时刻至多一个;此形态没有拖缝宽度,声明 minWidth /- // defaultFraction 会被拒装,请移除)。right 已退役(右侧是右侧边栏的地盘;- // 旧包声明 right 自动并入 left,用户想放右边可自己拖拽换位)。- // top/bottom 暂未支持(排期中)- // panel.systemButtons(可选,仅停靠形态):标准头系统按钮开关,缺省全开、- // 声明 false 逐个关闭。当前一批:maximize(撑满内容区)、detach(在独立- // 窗口中打开)、minimize(最小化面板;恢复入口由用户偏好决定为浮动气泡或- // 左侧栏)。标题条本体恒由主机绘制、- // 关不掉;未知键保留但不生效;position:"tab" 时声明本字段拒装+ // panel.position:面板显示形态。left(缺省)= 右侧栏常驻面板:启用后自动成为+ // 右侧栏里一个不跟对话的全局页签(切任务保留、可最大化、可弹成独立窗口、+ // 用户可关闭);"tab" = 插件页内的独占面板(用户在插件页点插件卡的「使用」打开,+ // 离开插件页即关闭;同一时刻至多一个;此形态没有拖缝宽度,声明 minWidth /+ // defaultFraction 会被拒装,请移除)。right 已退役(旧包声明 right 自动并入 left)。+ // top/bottom 暂未支持(排期中)。minWidth / defaultFraction 仍可声明(兼容),当前+ // 右侧栏宿主不消费。+ // panel.systemButtons(可选):历史字段,保留兼容、当前不生效(右侧栏页签的+ // 关闭 / 最大化 / 弹出按钮由主机统一提供);position:"tab" 时声明本字段拒装// 一级主视图是独立能力,见 §4.20。使用时直接声明:// "mainView": { "title": "工作台", "icon": "puzzle", "html": "main-view.html" }"settingsHtml": "settings.html", // 可选:设置页「自定义设置区」自绘界面(见 §4.8;声明了用户填的凭证时仍必填,用于长期管理/替换/清除;调用前缺失时主机也会在统一 Setup 卡内联收单,见 §4.7)@@ -3584,7 +3582,7 @@ await cindy.send({ type: 'badge', unread: false });- **限速**只挡点亮方向:同一意识两次点亮最小间隔 500 毫秒;\`unread:false\` 的清零不限速(降级动作被拦会留下一颗清不掉的死点);- **用户打开你的面板 = 已读**,主机自动清零(三种面板宿主都算:插件页页签、- 停靠态、独立窗口);+ 右侧栏页签、弹出的独立窗口);- **沉睡只停显示、不算已读**:用户唤醒你之后那颗点会回来。卸载、或更新后身份卡不再声明 badge,既有未读则被清除(权限撤了就不再兑现);- 角标**不出声、不震动、不进系统通知中心**——它只是屏幕内的一颗点;@@ -4704,9 +4702,10 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件## 5. 面板(panel.html/css/js)-- 显示形态由 \`panel.position\` 决定:\`left\`(缺省)= 停靠主聊天窗左侧的常驻- 面板(\`right\` 已退役:右侧是右侧边栏的地盘,旧包声明 right 自动并入 left,- 用户想放右边可自己拖拽换位);\`"tab"\` = **插件页内的独占面板**——由插件页+- 显示形态由 \`panel.position\` 决定:\`left\`(缺省)= **右侧栏常驻面板**——插件+ 启用后自动成为右侧栏里一个不跟对话的全局页签,切任务时留在原位,用户可以把它+ 最大化、弹成独立 OS 窗口或关闭(关闭后在左侧栏入口右键可重新打开;\`right\` 已退役,+ 旧包声明 right 自动并入 left);\`"tab"\` = **插件页内的独占面板**——由插件页自己承载(不进右侧栏页签容器):用户在插件页点你这张卡的「使用」按钮打开,同一时刻至多一个,**用户离开插件页即关闭卸载**(面板收束,2026-08-02 定案:插件面板不再常驻右侧栏干扰其它会话)。从插件页导入 tab 型插件后,宿主会@@ -4717,16 +4716,11 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件供片/主题/媒体规则不变),只是宿主容器不同;此形态请把界面做成自适应宽度,并且**不要假设自己会在后台长期存活**——每次打开都可能是全新加载,状态要自己持久化(见 §4.6 的偏好存储);-- 停靠形态的**标题条(标准头)由主机绘制**:标题(\`panel.title\`)+ 一批系统- 按钮(当前:「撑满内容区」、「在独立窗口中打开」——用户可把你的面板抽进- 自己的 OS 窗口,关窗/合并即回停靠原位——以及「最小化面板」——用户选择的- 恢复入口可能是一枚悬浮在主窗最上层的可拖动圆形气泡,也可能是左侧栏入口;- 最小化状态重启保留;三者面板代码全程零感知;后续新增的系统按钮- 也长在这里)。你的 panel.html 只画标题条以下的部分,**不要自己再画一条- 标题栏**。不想要某颗系统按钮时在身份卡声明- \`"systemButtons": { "maximize": false, "detach": false, "minimize": false }\`- 逐个关闭(缺省全开;标题条本体关不掉;未知键保留但不生效;\`position:"tab"\` 由插件页- 自绘头,没有这套标准头,声明本字段拒装);+- 右侧栏常驻形态的**页签与标题由主机绘制**:页签标题取 \`panel.title\`,关闭 /+ 最大化 / 弹出窗口等控件由右侧栏统一提供,面板代码全程零感知。你的 panel.html+ 只画内容区,**不要自己再画一条标题栏**。历史字段 \`systemButtons\` 仍可声明+ (兼容旧包,当前不生效;\`position:"tab"\` 由插件页自绘头,声明本字段拒装);+ 面板宽度随右侧栏,请把界面做成自适应宽度;- 与电子脑同源,用 \`BroadcastChannel('<自定名>')\` 通信(电子脑发,面板收);- 取自己的媒体:\`cindy-ghost://<id>/media/<指纹><后缀>\`(主机查账验归属,别人的图 404);- 重启回放:\`fetch('cindy-ghost://<id>/gallery')\` 返回本意识作品清单 \`[{src, caption}]\`;diff --git a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts b/apps/desktop/src/main/cindy-brain/scheduleSlot.tsindex d7fbf312c9..264d04ac1a 100644--- a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts+++ b/apps/desktop/src/main/cindy-brain/scheduleSlot.ts@@ -79,7 +79,7 @@ function fail(** ⚠️ 本判据被 review 连着推了三轮(面板窗 → 会话副窗 → utility 窗),所以这一版**按* 窗口约定收口,不再逐个枚举**:main 侧全部 `new BrowserWindow` 的位置只有 7 处- * (secondary-windows / bootstrap / 插件沙箱 / ghost-panel-window /+ * (secondary-windows / bootstrap / 插件沙箱 / sidebar-tab-window /* right-sidebar-window / computer-permission-guide / voice-input),下面四条把它们* 全覆盖了,**只有 bootstrap 建的主窗口不带任何标识** —— 新增窗口类型只要沿用现有* 约定(utility 窗带 `?view=`),就自动落在排除侧,不需要再改这里。@@ -92,11 +92,11 @@ function fail(* `voice-input-dictionary-toast`、权限引导 `computer-permission-guide` 与它的* backdrop。这里按 **`view` 这个 key** 排除而不是枚举取值 —— 它是 app 的 utility* 窗约定,枚举取值就等着下一个新窗口再漏一次(review 第三轮)。- * 3. **插件面板独立窗**(`?ghostPanelWindow=<id>`)与**右侧栏独立窗**(`?sidebarWindow=1`):- * 与 MainLayout **平级**(router.tsx 两条根路由),只挂轻壳,**没有草稿订阅、也去不了- * 自动化页** → 投过去静默丢失。而插件面板恰恰可以被用户拉成独立窗口,「在插件面板- * 上点一下」正是本能力的主使用路径(编写手册 §4.11.2 第 1 步)——那一刻 focused 就是- * 面板窗,若照 confirm 槽那样只写 `focused ?? all[0]` 就丢了。hash 两路也查,兜底。+ * 3. **右侧栏独立窗**(`?sidebarWindow=1`,含整栏子窗口与单页签弹出窗口):与 MainLayout+ * **平级**,只挂轻壳,**没有草稿订阅、也去不了自动化页** → 投过去静默丢失。而插件视图+ * 页签恰恰可以被用户弹成独立窗口,「在插件面板上点一下」正是本能力的主使用路径+ * (编写手册 §4.11.2 第 1 步)——那一刻 focused 就是弹出窗,若照 confirm 槽那样只写+ * `focused ?? all[0]` 就丢了。hash 也查,兜底。* 4. **「在新窗口打开」的会话副窗**(`?secondaryWindow=1`,main/secondary-windows.ts):* 它**挂的是完整 MainLayout**(有订阅、技术上接得住),但它是用户为某个会话单独开的* 窗口。回落时把创建面板弹进它 = 落错地方:用户以为在主窗口建任务,主窗口却什么也@@ -121,7 +121,6 @@ export function isMainShellWindowUrl(rawUrl: string): boolean {if (// utility 窗的统一约定:按 key 排除,不枚举取值(见上方第 2 条)。parsed.searchParams.has('view') ||- parsed.searchParams.has('ghostPanelWindow') ||parsed.searchParams.has('sidebarWindow') ||// 会话副窗:挂完整壳、技术上接得住,但它不是用户建任务时看的那个窗口。// 取 === '1' 而不是 has():带 secondaryWindow=0 的主窗不该被误排除。@@ -130,7 +129,7 @@ export function isMainShellWindowUrl(rawUrl: string): boolean {return false;}const hash = parsed.hash;- if (hash.includes('/ghost-panel-window') || hash.includes('/sidebar-window')) return false;+ if (hash.includes('/sidebar-window')) return false;return true;}diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.tsdeleted file mode 100644index f8c57f86b2..0000000000--- a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts+++ /dev/null@@ -1,700 +0,0 @@-// GhostPanelWindowsController lifecycle state-machine tests (DI only, no electron).-// Covers: prewarm, hide-reuse close, setDetached(false)=dispose, two-phase ready,-// multi-instance isolation, reconcile cleanup, crash recovery, sender guard.--import { describe, expect, it, vi } from 'vitest';-import type { BrowserWindow, WebContents } from 'electron';--import type { GhostPanelWindowsState } from '../../../shared/ghostPanelWindow.js';-import {- GhostPanelWindowsController,- type GhostPanelWindowsControllerDeps,-} from '../controller.js';-import type { InstalledGhost, GhostManifest } from '../../../shared/ghost.js';--interface FakeWindow {- on: ReturnType<typeof vi.fn>;- close: ReturnType<typeof vi.fn>;- destroy: ReturnType<typeof vi.fn>;- hide: ReturnType<typeof vi.fn>;- show: ReturnType<typeof vi.fn>;- focus: ReturnType<typeof vi.fn>;- restore: ReturnType<typeof vi.fn>;- isMinimized: () => boolean;- isVisible: () => boolean;- isDestroyed: () => boolean;- destroyed: boolean;- visible: boolean;- webContents: {- id: number;- on: ReturnType<typeof vi.fn>;- isDestroyed: () => boolean;- };- emitClosed: () => void;- emitWindowEvent: (event: string, ...args: unknown[]) => void;- emitWebContentsEvent: (event: string, ...args: unknown[]) => void;- _id: number;-}--let nextId = 1;-function fakeWindow(): FakeWindow {- const id = nextId++;- const winListeners = new Map<string, (...args: unknown[]) => void>();- const wcListeners = new Map<string, (...args: unknown[]) => void>();- let destroyed = false;- let visible = false;- const wcOn = vi.fn((event: string, cb: (...args: unknown[]) => void) => {- wcListeners.set(event, cb);- });- const win: FakeWindow = {- on: vi.fn((event: string, cb: (...args: unknown[]) => void) => {- winListeners.set(event, cb);- }),- close: vi.fn(() => {- let prevented = false;- winListeners.get('close')?.({ preventDefault: () => { prevented = true; } });- if (prevented) return;- destroyed = true;- visible = false;- winListeners.get('closed')?.();- }),- destroy: vi.fn(() => { destroyed = true; visible = false; winListeners.get('closed')?.(); }),- hide: vi.fn(() => { visible = false; }),- show: vi.fn(() => { visible = true; }),- focus: vi.fn(),- restore: vi.fn(),- isMinimized: () => false,- isVisible: () => visible,- isDestroyed: () => destroyed,- destroyed: false,- visible: false,- webContents: {- id,- on: wcOn,- isDestroyed: () => destroyed,- },- emitClosed: () => {- destroyed = true;- visible = false;- winListeners.get('closed')?.();- },- emitWindowEvent: (event, ...args) => {- if (event === 'hide') visible = false;- if (event === 'show') visible = true;- winListeners.get(event)?.(...args);- },- emitWebContentsEvent: (event, ...args) => wcListeners.get(event)?.(...args),- _id: id,- };- return win;-}--function ghost(id: string, opts: { enabled?: boolean; position?: 'left' | 'tab' } = {}): InstalledGhost {- const manifest: GhostManifest = {- schemaVersion: 2,- id,- name: id,- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- panel: {- html: 'panel.html',- ...(opts.position !== undefined ? { position: opts.position } : {}),- },- };- return {- manifest,- dir: `/fake/${id}`,- enabled: opts.enabled ?? true,- approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },- };-}--function makeHarness(detachableIds: Set<string>) {- let entries: Record<string, { detached: boolean; lastOpen: boolean }> = {};- let quitting = false;- const created: Array<{ ghostId: string; win: FakeWindow }> = [];- const broadcasts: GhostPanelWindowsState[] = [];- const sends: Array<{ channel: string; payload: unknown }> = [];-- const deps: GhostPanelWindowsControllerDeps = {- settings: {- read: () => ({ windows: structuredClone(entries) }),- patchEntry: (id, patch) => {- const base = entries[id] ?? { detached: false, lastOpen: false };- entries[id] = { ...base, ...patch };- },- removeEntry: (id) => { delete entries[id]; },- },- createWindow: (ghostId) => {- const win = fakeWindow();- created.push({ ghostId, win });- return win as unknown as BrowserWindow;- },- isGhostDetachable: (id) => detachableIds.has(id),- broadcastState: (s) => { broadcasts.push(s); },- sendToWindow: (_win, channel, payload) => { sends.push({ channel, payload }); },- isQuitting: () => quitting,- log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },- };- const controller = new GhostPanelWindowsController(deps);- return {- controller,- created,- broadcasts,- sends,- entries: () => entries,- setEntries: (next: Record<string, { detached: boolean; lastOpen: boolean }>) => { entries = next; },- setDetachable: (ghostId: string, detachable: boolean) => {- if (detachable) detachableIds.add(ghostId);- else detachableIds.delete(ghostId);- },- setQuitting: (v: boolean) => { quitting = v; },- };-}--function markReady(controller: GhostPanelWindowsController, win: FakeWindow): void {- controller.markRendererReady(win.webContents as unknown as WebContents);- controller.markPresentationReady(win.webContents as unknown as WebContents);-}--describe('prewarm / open / close (hide-reuse)', () => {- it('prewarm creates hidden window without showing or focusing', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- expect(h.created).toHaveLength(1);- const win = h.created[0].win;- expect(win.show).not.toHaveBeenCalled();- expect(win.focus).not.toHaveBeenCalled();- expect(h.entries().a?.lastOpen).toBeUndefined(); // prewarm doesn't set lastOpen- });-- it('open creates window + sets lastOpen + broadcasts', () => {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- expect(h.created).toHaveLength(1);- expect(h.entries().a).toEqual({ detached: true, lastOpen: true });- expect(h.broadcasts.length).toBeGreaterThan(0);- });-- it('hot open on prewarmed+ready window shows + focuses immediately', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const win = h.created[0].win;- markReady(h.controller, win);-- h.controller.open('a');- expect(win.show).toHaveBeenCalled();- expect(win.focus).toHaveBeenCalled();- expect(h.created).toHaveLength(1); // no second window- });-- it('open waits for presentation-ready then shows', () => {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- const win = h.created[0].win;- // Not shown yet — renderer isn't ready- expect(win.show).not.toHaveBeenCalled();-- // presentation-ready triggers show- h.controller.markPresentationReady(win.webContents as unknown as WebContents);- expect(win.show).toHaveBeenCalled();- expect(win.focus).toHaveBeenCalled();- });-- it('close hides window without destroying', () => {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- const win = h.created[0].win;- markReady(h.controller, win);-- h.controller.close('a');- expect(win.hide).toHaveBeenCalled();- expect(win.isDestroyed()).toBe(false);- expect(h.entries().a?.lastOpen).toBe(false);- // detached preference preserved- expect(h.entries().a?.detached).toBe(true);- });-- it('re-open after close reuses same window (hot path, no recreate)', () => {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- const win = h.created[0].win;- markReady(h.controller, win);- h.controller.close('a');-- win.show.mockClear();- h.controller.open('a');- expect(h.created).toHaveLength(1); // no new window created- expect(win.show).toHaveBeenCalled(); // reuse- });-- it('native hide updates state and open shows the cached window again', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const win = h.created[0].win;- markReady(h.controller, win);- h.controller.open('a');-- win.emitWindowEvent('hide');- expect(h.controller.getState().a?.open).toBe(false);-- win.show.mockClear();- win.focus.mockClear();- h.controller.open('a');- expect(h.created).toHaveLength(1);- expect(win.show).toHaveBeenCalledOnce();- expect(win.focus).toHaveBeenCalledOnce();- expect(h.controller.getState().a?.open).toBe(true);- });-- it('open repairs stale controller visibility using the native window state', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const win = h.created[0].win;- markReady(h.controller, win);- h.controller.open('a');-- win.hide();- win.show.mockClear();- win.focus.mockClear();-- h.controller.open('a');- expect(win.show).toHaveBeenCalledOnce();- expect(win.focus).toHaveBeenCalledOnce();- expect(h.controller.getState().a?.open).toBe(true);- });-});--describe('renderer navigation lifecycle', () => {- it('ignores same-document main-frame navigation such as hash routing', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const win = h.created[0].win;- markReady(h.controller, win);- h.controller.open('a');-- win.hide.mockClear();- win.emitWebContentsEvent(- 'did-start-navigation',- {},- 'http://localhost:5173/?ghostPanelWindow=a#/ghost-panel-window',- true,- true,- );-- expect(win.hide).not.toHaveBeenCalled();- expect(h.controller.getState().a?.open).toBe(true);- });-- it('ignores child-frame navigation from the embedded ghost webview', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const win = h.created[0].win;- markReady(h.controller, win);- h.controller.open('a');-- win.hide.mockClear();- win.emitWebContentsEvent(- 'did-start-navigation',- {},- 'cindy-ghost://a/panel.html',- false,- false,- );-- expect(win.hide).not.toHaveBeenCalled();- expect(h.controller.getState().a?.open).toBe(true);- });-- it('temporarily hides and restores for main-frame renderer navigation', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const win = h.created[0].win;- markReady(h.controller, win);- h.controller.open('a');-- win.emitWebContentsEvent(- 'did-start-navigation',- {},- 'http://localhost:5173/?ghostPanelWindow=1#/ghost-panel-window/a',- false,- true,- );- expect(win.hide).toHaveBeenCalledOnce();- expect(h.controller.getState().a?.open).toBe(true);-- markReady(h.controller, win);- expect(win.show).toHaveBeenCalledTimes(2);- expect(h.controller.getState().a?.open).toBe(true);- });-});--describe('setDetached', () => {- it('true: opens window + sets detached preference', () => {- const h = makeHarness(new Set(['a']));- const state = h.controller.setDetached('a', true);- expect(h.created).toHaveLength(1);- expect(h.entries().a).toEqual({ detached: true, lastOpen: true });- expect(state.a).toEqual({ detached: true, lastOpen: true, open: true });- });-- it('false: disposes window + clears flags', () => {- const h = makeHarness(new Set(['a']));- h.controller.setDetached('a', true);- const win = h.created[0].win;- markReady(h.controller, win);-- const state = h.controller.setDetached('a', false);- expect(win.isDestroyed()).toBe(true);- expect(h.entries().a).toEqual({ detached: false, lastOpen: false });- expect(state.a.open).toBe(false);- });-- it('false: only affects specified ghost, others untouched', () => {- const h = makeHarness(new Set(['a', 'b']));- h.controller.setDetached('a', true);- h.controller.setDetached('b', true);- const state = h.controller.setDetached('a', false);- expect(state.a.open).toBe(false);- expect(state.b.open).toBe(true);- });-});--describe('native minimize', () => {- it('routes native minimize to the renderer panel-minimize action', () => {- const h = makeHarness(new Set(['a']));- h.controller.setDetached('a', true);- const win = h.created[0].win;-- win.emitWindowEvent('minimize');-- expect(h.sends).toContainEqual({- channel: 'ghost-panel-window:minimize-requested',- payload: undefined,- });- });-});--describe('multi-instance isolation', () => {- it('two ghosts maintain independent windows', () => {- const h = makeHarness(new Set(['a', 'b']));- h.controller.prewarm('a');- h.controller.prewarm('b');- expect(h.created).toHaveLength(2);- const winA = h.created[0].win;- const winB = h.created[1].win;- markReady(h.controller, winA);- markReady(h.controller, winB);-- h.controller.open('a');- expect(winA.show).toHaveBeenCalled();- expect(winB.show).not.toHaveBeenCalled();-- h.controller.close('a');- expect(winA.hide).toHaveBeenCalled();- expect(winB.hide).not.toHaveBeenCalled();-- h.controller.open('b');- expect(winB.show).toHaveBeenCalled();- });- it('same ghostId in different namespaces get independent windows', () => {- const h = makeHarness(new Set(['helper', '_ns__acme__helper']));- h.controller.setDetached('helper', true);- h.controller.setDetached('_ns__acme__helper', true);- expect(h.created).toHaveLength(2);- expect(h.created[0].ghostId).toBe('helper');- expect(h.created[1].ghostId).toBe('_ns__acme__helper');- h.controller.setDetached('helper', false);- expect(h.created[0].win.isDestroyed()).toBe(true);- expect(h.created[1].win.isDestroyed()).toBe(false);- });--- it('setDetached(false) on one ghost does not affect another', () => {- const h = makeHarness(new Set(['a', 'b']));- h.controller.setDetached('a', true);- h.controller.setDetached('b', true);- h.controller.setDetached('a', false);- expect(h.created[0].win.isDestroyed()).toBe(true);- expect(h.created[1].win.isDestroyed()).toBe(false);- });-});--describe('closed event', () => {- it('user closes window via OS: clears flags', () => {- const h = makeHarness(new Set(['a']));- h.controller.setDetached('a', true);- h.created[0].win.emitClosed();- expect(h.entries().a).toEqual({ detached: false, lastOpen: false });- });-- it('app quitting: preserves detached/lastOpen', () => {- const h = makeHarness(new Set(['b']));- h.controller.setDetached('b', true);- h.setQuitting(true);- h.created[0].win.emitClosed();- expect(h.entries().b).toEqual({ detached: true, lastOpen: true });- });-});--describe('owner change', () => {- it('destroys visible, hidden, pending, and prewarmed windows and returns entries to docked', () => {- const h = makeHarness(new Set(['visible', 'hidden', 'pending', 'prewarmed']));- h.controller.open('visible');- markReady(h.controller, h.created[0].win);- h.controller.open('hidden');- markReady(h.controller, h.created[1].win);- h.controller.close('hidden');- h.controller.open('pending');- h.controller.prewarm('prewarmed');-- h.controller.closeForOwnerChange();-- expect(h.created.map(({ win }) => win.isDestroyed())).toEqual([true, true, true, true]);- expect(h.created.every(({ win }) => win.destroy.mock.calls.length === 1)).toBe(true);- expect(h.created.every(({ win }) => win.close.mock.calls.length === 0)).toBe(true);- expect(h.entries()).toEqual({- visible: { detached: false, lastOpen: false },- hidden: { detached: false, lastOpen: false },- pending: { detached: false, lastOpen: false },- });- expect(h.controller.getState()).toEqual({- visible: { detached: false, lastOpen: false, open: false },- hidden: { detached: false, lastOpen: false, open: false },- pending: { detached: false, lastOpen: false, open: false },- });- expect(h.broadcasts.at(-1)).toEqual(h.controller.getState());- });-- it('keeps the panel docked through reconcile and only creates a new slot on explicit detach', () => {- const h = makeHarness(new Set(['a']));- h.controller.setDetached('a', true);- const ownerAWindow = h.created[0].win;-- h.controller.closeForOwnerChange();- h.controller.reconcile([ghost('a')]);-- expect(ownerAWindow.isDestroyed()).toBe(true);- expect(h.created).toHaveLength(1);- expect(h.entries().a).toEqual({ detached: false, lastOpen: false });-- const state = h.controller.setDetached('a', true);- expect(h.created).toHaveLength(2);- expect(h.created[1].win.isDestroyed()).toBe(false);- expect(h.entries().a).toEqual({ detached: true, lastOpen: true });- expect(state.a).toEqual({ detached: true, lastOpen: true, open: true });- });-});--describe('open guard (non-detachable)', () => {- it('non-detachable plugin: prunes entry, no window', () => {- const h = makeHarness(new Set());- h.setEntries({ a: { detached: true, lastOpen: true } });- h.controller.open('a');- expect(h.created).toHaveLength(0);- expect(h.entries().a).toBeUndefined();- });-- it('non-detachable plugin: disposes a stale prewarmed window', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const win = h.created[0].win;- h.setDetachable('a', false);- h.controller.open('a');- expect(win.isDestroyed()).toBe(true);- expect(h.created).toHaveLength(1);- });-- it('prewarm for non-detachable is no-op', () => {- const h = makeHarness(new Set());- h.controller.prewarm('nonexistent');- expect(h.created).toHaveLength(0);- });-});--describe('reconcile', () => {- it('uninstall: disposes window + removes entry', () => {- const h = makeHarness(new Set(['gone', 'stays']));- h.controller.setDetached('gone', true);- h.controller.setDetached('stays', true);- h.controller.reconcile([ghost('stays')]);- expect(h.created[0].win.isDestroyed()).toBe(true); // gone- expect(h.created[1].win.isDestroyed()).toBe(false); // stays- expect(h.entries().gone).toBeUndefined();- expect(h.entries().stays).toEqual({ detached: true, lastOpen: true });- });-- it('disabled: disposes window + clears flags', () => {- const h = makeHarness(new Set(['disabled']));- h.controller.setDetached('disabled', true);- h.controller.reconcile([ghost('disabled', { enabled: false })]);- expect(h.created[0].win.isDestroyed()).toBe(true);- expect(h.entries().disabled).toEqual({ detached: false, lastOpen: false });- });-- it('tab position: treated as non-detachable', () => {- const h = makeHarness(new Set(['a']));- h.controller.setDetached('a', true);- h.controller.reconcile([ghost('a', { position: 'tab' })]);- expect(h.created[0].win.isDestroyed()).toBe(true);- expect(h.entries().a).toEqual({ detached: false, lastOpen: false });- });- it('reconcile keeps a namespaced detached window and does not treat it as the root id', () => {- const h = makeHarness(new Set(['_ns__acme__helper']));- h.controller.setDetached('_ns__acme__helper', true);- const org = ghost('helper');- org.namespace = 'acme';- org.dir = '/fake/_ns/acme/helper';- h.controller.reconcile([org]);- expect(h.created[0].win.isDestroyed()).toBe(false);- expect(h.entries()['_ns__acme__helper']).toEqual({ detached: true, lastOpen: true });- });--});--describe('two-phase ready + sender guard', () => {- it('keeps a legacy organization window when a same-name root is installed separately', () => {- const h = makeHarness(new Set(['helper', '_root__helper']));- h.controller.setDetached('helper', true);- const oldWindow = h.created[0].win;- const org = ghost('helper');- org.namespace = 'acme';- org.dir = '/fake/helper';- const root = ghost('helper');- root.namespace = null;- root.dir = '/fake/_ns/_root/helper';- h.controller.reconcile([org, root]);- expect(oldWindow.isDestroyed()).toBe(false);- expect(h.entries().helper).toEqual({ detached: true, lastOpen: true });- expect(h.entries()['_root__helper']).toBeUndefined();- });- it('markRendererReady from correct sender succeeds', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const win = h.created[0].win;- h.controller.markRendererReady(win.webContents as unknown as WebContents);- // slotForSender finds the slot- expect(h.controller.slotForSender(win.webContents as unknown as WebContents)).not.toBeNull();- });-- it('markPresentationReady from wrong sender is no-op', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- const wrongSender = { id: 99999 } as unknown as WebContents;- h.controller.markPresentationReady(wrongSender);- // slotForSender returns null- expect(h.controller.slotForSender(wrongSender)).toBeNull();- });-- it('getSidebarWebContents returns null for wrong ghostId', () => {- const h = makeHarness(new Set(['a']));- h.controller.prewarm('a');- expect(h.controller.getSidebarWebContents('nonexistent')).toBeNull();- });-});--describe('crash recovery', () => {- it('render-process-gone invalidates window and rebuilds if pendingOpen', () => {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- const win1 = h.created[0].win;- win1.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });- expect(win1.isDestroyed()).toBe(true);- expect(h.created).toHaveLength(2); // auto-recovered- });-- it('recovery is bounded per ghostId', () => {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- const win1 = h.created[0].win;- // Don't mark ready — simulate rapid crashes where renderer never stabilizes.- // Without presentationReady resetting the counter, each crash increments.- win1.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });- expect(h.created).toHaveLength(2); // auto-recovered once-- const win2 = h.created[1].win;- win2.emitWebContentsEvent('render-process-gone', {}, { reason: 'killed' });- expect(h.created).toHaveLength(2); // no third window (quota exhausted)- });-- it('presentation-ready does not immediately reset the recovery quota', () => {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- h.created[0].win.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });- const replacement = h.created[1].win;- markReady(h.controller, replacement);-- replacement.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed-again' });- expect(h.created).toHaveLength(2);- });-});--describe('open timeout (window rule §3.1)', () => {- it('renderer shell not ready at timeout: invalidates and rebuilds with bounded recovery', () => {- vi.useFakeTimers();- try {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- const win1 = h.created[0].win;-- vi.advanceTimersByTime(5000);-- // shell 未就绪:不得展示空白窗口;作废缓存并重建重开(有界恢复)。- expect(win1.isDestroyed()).toBe(true);- expect(h.created).toHaveLength(2);- expect(h.created[1].win.show).not.toHaveBeenCalled();- expect(h.created[1].win.focus).not.toHaveBeenCalled();-- // 恢复额度耗尽:重建窗口再次超时后不再重建,也不展示。- vi.advanceTimersByTime(5000);- expect(h.created).toHaveLength(2);- expect(h.created[1].win.show).not.toHaveBeenCalled();- } finally {- vi.useRealTimers();- }- });-- it('renderer ready but content pending at timeout: shows the mounted shell', () => {- vi.useFakeTimers();- try {- const h = makeHarness(new Set(['a']));- h.controller.open('a');- const win = h.created[0].win;- h.controller.markRendererReady(win.webContents as unknown as WebContents);-- vi.advanceTimersByTime(5000);-- // 仅 shell 就绪、内容未到:展示已挂载的 Loading 壳(基线允许)。- expect(win.show).toHaveBeenCalledTimes(1);- expect(win.focus).toHaveBeenCalled();- } finally {- vi.useRealTimers();- }- });-});--describe('dispose', () => {- it('dispose destroys all windows', () => {- const h = makeHarness(new Set(['a', 'b']));- h.controller.setDetached('a', true);- h.controller.setDetached('b', true);- h.controller.dispose();- expect(h.created[0].win.isDestroyed()).toBe(true);- expect(h.created[1].win.isDestroyed()).toBe(true);- });-- it('dispose is idempotent', () => {- const h = makeHarness(new Set(['a']));- h.controller.setDetached('a', true);- h.controller.dispose();- h.controller.dispose(); // no throw- });-- it('destroyAllWindows preserves detached preferences for a future main window', () => {- const h = makeHarness(new Set(['a']));- h.controller.setDetached('a', true);- h.controller.destroyAllWindows();- expect(h.entries().a).toEqual({ detached: true, lastOpen: true });- });-});diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.tsdeleted file mode 100644index 6fd83e3c00..0000000000--- a/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts+++ /dev/null@@ -1,112 +0,0 @@-import { readFileSync } from 'node:fs';-import path from 'node:path';-import { describe, expect, it } from 'vitest';--const preloadPath = path.resolve(- process.cwd().endsWith(`${path.sep}apps${path.sep}desktop`)- ? process.cwd()- : path.join(process.cwd(), 'apps', 'desktop'),- 'src/preload/ghostPanelWindowPreload.ts',-);--const source = readFileSync(preloadPath, 'utf8').replace(/\r\n/g, '\n');--function balancedObject(start: number): string {- const open = source.indexOf('{', start);- let depth = 0;- let quote = '';- let escaped = false;- for (let i = open; i < source.length; i += 1) {- const char = source[i];- if (quote) {- if (escaped) escaped = false;- else if (char === '\\') escaped = true;- else if (char === quote) quote = '';- continue;- }- if (char === '"' || char === "'" || char === '`') {- quote = char;- } else if (char === '{') {- depth += 1;- } else if (char === '}') {- depth -= 1;- if (depth === 0) return source.slice(open + 1, i);- }- }- return '';-}--function objectBody(name: string): string {- const match = new RegExp(`(?:^|\\n)[ \\t]*${name}[ \\t]*:[ \\t]*\\{`, 'm').exec(source);- return match ? balancedObject(match.index + match[0].length - 1) : '';-}--function keys(body: string): string[] {- return [...body.matchAll(/^([ \t]*)([A-Za-z_$][\w$]*)[ \t]*:/gm)]- .filter((match, _, all) => match[1].length === Math.min(...all.map((item) => item[1].length)))- .map((match) => match[2]);-}--const topLevel = keys(balancedObject(source.indexOf("contextBridge.exposeInMainWorld('electronAPI'")));-const ghostPanelWindow = keys(objectBody('ghostPanelWindow'));-const ghosts = keys(objectBody('ghosts'));--describe('ghost panel preload contract', () => {- it('exposes only the window chrome and media capabilities needed by the panel', () => {- expect(topLevel).toEqual(expect.arrayContaining([- 'platform', 'preferredSystemLocale', 'windowMinimize', 'windowMaximize', 'windowClose',- 'appearanceSettings', 'localThemes', 'appShortcuts', 'theme',- 'onFullscreenChange', 'getFullscreenState',- 'copyMediaToClipboard', 'showItemInFolder', 'cacheMediaForSession',- 'openMediaWithDefaultApp', 'saveMediaAs', 'ghostPanelWindow', 'ghosts',- ]));- });-- it('does not expose unrelated privileged namespaces', () => {- expect(topLevel).not.toEqual(expect.arrayContaining([- 'maker', 'agent', 'voiceInput', 'login', 'auth', 'settings', 'updater', 'chat',- 'session', 'processMonitor', 'rightSidebarWindow', 'rsbBrowserBridge', 'deviceLink',- ]));- });-- it('exposes the ghost panel lifecycle bridge', () => {- expect(ghostPanelWindow).toEqual(expect.arrayContaining([- 'getStateSync', 'getState', 'open', 'setDetached', 'onStateChanged',- 'rendererReady', 'presentationReady', 'onVisibilityChanged',- 'onMinimizeRequested',- ]));- });-- it('exposes the panel runtime and unread bridge', () => {- expect(ghosts).toEqual(expect.arrayContaining([- 'listSync', 'reload', 'setEnabled', 'resolvePanelMedia', 'runtimeStates',- 'onChanged', 'onRuntimeChanged', 'onPreviewMedia', 'unreadSync', 'clearUnread',- 'onBadge', 'onUnreadSnapshot',- ]));- });-- it('guards plugin mutations to the current detached panel id', () => {- expect(source).toContain("new URLSearchParams(window.location.search).get('ghostPanelWindow')");- expect(source).toContain('mutationErrorForGhostPanel(id)');- expect(source).toContain("return ipcRenderer.invoke('maker:ghost-panel-window:open', ghostId);");- expect(source).toContain("return ipcRenderer.invoke('maker:ghost-panel-window:set-detached', ghostId, detached);");- expect(source).toContain("ipcRenderer.invoke('ghosts:reload', id)");- expect(source).toContain("ipcRenderer.invoke('ghosts:set-enabled', id, enabled, expectedInstalledApproval)");- expect(source).toContain("return ipcRenderer.invoke('ghosts:clear-unread', id, seenAt);");- });-- it('scopes unread snapshots and badge events to the current detached panel', () => {- expect(source).toContain('onCurrentGhostBadge');- expect(source).toContain('onCurrentGhostUnreadSnapshot');- expect(source).toContain('if (ghostId !== currentGhostPanelId || typeof at !== \'number\') continue;');- expect(source).toContain('if (candidate.ghostId !== currentGhostPanelId) return;');- expect(source).toContain('if (candidate.ghostId !== currentGhostPanelId || typeof candidate.at !== \'number\') continue;');- });-- it('uses shared lifecycle channel constants', () => {- expect(source).toContain('GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL');- expect(source).toContain('GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL');- expect(source).toContain('GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL');- expect(source).toContain('GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL');- });-});diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.tsdeleted file mode 100644index b147a832cf..0000000000--- a/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts+++ /dev/null@@ -1,111 +0,0 @@-// normalizeGhostPanelWindowsSettings:坏数据 fail-closed 清洗。-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import fs from 'node:fs';-import os from 'node:os';-import path from 'node:path';--const tmpUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ghost-panel-window-settings-'));--vi.mock('electron', () => ({- app: {- getPath: (name: string) => {- if (name !== 'userData') throw new Error(`unexpected getPath(${name})`);- return tmpUserData;- },- },-}));--vi.mock('../../maker-host/logger-adapter.js', () => ({- desktopMakerLogger: {- child: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),- },-}));--import {- normalizeGhostPanelWindowsSettings,- patchGhostPanelWindowEntry,- readGhostPanelWindowsSettings,- resetGhostPanelWindowSettingsForStartup,-} from '../settings-store.js';--const settingsFile = path.join(tmpUserData, 'ghost-panel-windows-settings.json');--beforeEach(() => {- if (fs.existsSync(settingsFile)) fs.unlinkSync(settingsFile);- resetGhostPanelWindowSettingsForStartup();-});--afterEach(() => {- if (fs.existsSync(settingsFile)) fs.unlinkSync(settingsFile);-});--describe('normalizeGhostPanelWindowsSettings', () => {- it('合法条目原样保留', () => {- expect(- normalizeGhostPanelWindowsSettings({- windows: { 'stock-2400-tracker': { detached: true, lastOpen: false } },- }),- ).toEqual({ windows: { 'stock-2400-tracker': { detached: true, lastOpen: false } } });- });-- it('非对象 / 缺 windows / windows 非对象 → 空表', () => {- expect(normalizeGhostPanelWindowsSettings(null)).toEqual({ windows: {} });- expect(normalizeGhostPanelWindowsSettings('x')).toEqual({ windows: {} });- expect(normalizeGhostPanelWindowsSettings({})).toEqual({ windows: {} });- expect(normalizeGhostPanelWindowsSettings({ windows: 42 })).toEqual({ windows: {} });- });-- it('非法 ghostId / 非布尔字段 / 非对象条目:整条丢弃,不影响同表其它条目', () => {- expect(- normalizeGhostPanelWindowsSettings({- windows: {- 'BAD ID': { detached: true, lastOpen: true },- 'cindy-art': { detached: 'yes', lastOpen: true },- 'no-fields': null,- good: { detached: false, lastOpen: true },- },- }),- ).toEqual({ windows: { good: { detached: false, lastOpen: true } } });- });-- it('企业实例 storage part 是合法键,斜杠目录 id 丢弃', () => {- expect(- normalizeGhostPanelWindowsSettings({- windows: {- '_ns__acme__helper': { detached: true, lastOpen: true },- '_ns/acme/helper': { detached: true, lastOpen: true },- helper: { detached: false, lastOpen: false },- },- }),- ).toEqual({- windows: {- '_ns__acme__helper': { detached: true, lastOpen: true },- helper: { detached: false, lastOpen: false },- },- });- });-});--describe('runtime state', () => {- it('每个插件的分离状态仅保存在当前进程内', () => {- patchGhostPanelWindowEntry('cindy-art', { detached: true, lastOpen: true });-- expect(readGhostPanelWindowsSettings()).toEqual({- windows: { 'cindy-art': { detached: true, lastOpen: true } },- });- expect(fs.existsSync(settingsFile)).toBe(false);- });-- it('startup 清空所有插件分离态并删除旧版本偏好文件', () => {- patchGhostPanelWindowEntry('cindy-art', { detached: true, lastOpen: true });- fs.writeFileSync(- settingsFile,- JSON.stringify({ windows: { 'cindy-art': { detached: true, lastOpen: true } } }),- );-- resetGhostPanelWindowSettingsForStartup();-- expect(readGhostPanelWindowsSettings()).toEqual({ windows: {} });- expect(fs.existsSync(settingsFile)).toBe(false);- });-});diff --git a/apps/desktop/src/main/ghost-panel-window/controller.ts b/apps/desktop/src/main/ghost-panel-window/controller.tsdeleted file mode 100644index b2387b7683..0000000000--- a/apps/desktop/src/main/ghost-panel-window/controller.ts+++ /dev/null@@ -1,547 +0,0 @@-/**- * GhostPanelWindowsController —— 插件停靠面板独立窗口的状态机(main 侧单例,- * 依赖注入可测)。- *- * 每 ghostId 三态(与 RSB 同构):- * A. detached=false —— 面板停靠在主窗布局树里- * C. detached=true, 窗口打开 —— 面板活在独立窗口(隐藏复用,紧接开/关只隐藏)- *- * 生命周期基线对齐 PR #2434 ResourceUsageWindowController 与右侧栏窗口改造:- * - 惰性预热:首次 open/setDetached(true) 创建隐藏窗口,presentation-ready 后展示- * - 本次运行期按需创建:首次分离后隐藏复用,客户端重启后回到主窗口- * - 双阶段就绪握手(renderer-ready → presentation-ready),5s 超时展示壳- * - 隐藏复用:普通关窗只 hide(setDetached(false) 才真正 destroy)- * - 崩溃恢复有界(每 ghostId 独立计数)- * - 多 ghostId 实例间状态隔离- * - reconcile:插件卸载/停用/换形态时 dispose 对应窗口- */--import type { BrowserWindow, WebContents } from 'electron';--import type {- GhostPanelWindowEntryState,- GhostPanelWindowsState,-} from '../../shared/ghostPanelWindow.js';-import {- GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL,- GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL,- GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL,- GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL,-} from '../../shared/ghostPanelWindow.js';-import type { SupportedLocale } from '../../shared/locale.js';-import type { InstalledGhost } from '../../shared/ghost.js';-import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';-import type { GhostPanelWindowsSettings } from './settings-store.js';--interface ControllerLogger {- info(message: string, ...args: unknown[]): void;- warn(message: string, ...args: unknown[]): void;- error(message: string, ...args: unknown[]): void;-}--export interface GhostPanelWindowsControllerDeps {- settings: {- read(): GhostPanelWindowsSettings;- patchEntry(ghostId: string, patch: Partial<{ detached: boolean; lastOpen: boolean }>): void;- removeEntry(ghostId: string): void;- };- createWindow: (ghostId: string) => BrowserWindow;- isGhostDetachable: (ghostId: string) => boolean;- broadcastState: (state: GhostPanelWindowsState) => void;- /** main → renderer push(仅子窗口)。 */- sendToWindow: (win: BrowserWindow, channel: string, payload: unknown) => void;- isQuitting: () => boolean;- log: ControllerLogger;-}--const DEFAULT_OPEN_TIMEOUT_MS = 5000;-const DEFAULT_RECOVERY_STABILITY_MS = 30_000;-const MAX_AUTOMATIC_RECOVERY_ATTEMPTS = 1;--interface WindowSlot {- win: BrowserWindow;- rendererReady: boolean;- presentationReady: boolean;- visible: boolean;- pendingOpen: boolean;- destroyingWindow: boolean;- openTimeout: NodeJS.Timeout | null;- recoveryStabilityTimeout: NodeJS.Timeout | null;- automaticRecoveryAttempts: number;-}--export class GhostPanelWindowsController {- private readonly slots = new Map<string, WindowSlot>();- private disposed = false;- private locale: SupportedLocale | null = null;-- constructor(private readonly deps: GhostPanelWindowsControllerDeps) {}-- // ══════════════════════════════════════════════════════════════════════- // 公共接口- // ══════════════════════════════════════════════════════════════════════-- getState(): GhostPanelWindowsState {- const out: GhostPanelWindowsState = {};- const { windows } = this.deps.settings.read();- for (const [id, entry] of Object.entries(windows)) {- out[id] = this.entryState(id, entry);- }- for (const id of this.slots.keys()) {- if (!(id in out)) out[id] = this.entryState(id, { detached: false, lastOpen: false });- }- return out;- }-- /**- * 后台预热指定 ghostId:创建隐藏窗口并加载 renderer,不改变用户焦点。- * 可在当前运行期提前为即将打开的插件面板准备 renderer。- */- prewarm(ghostId: string): void {- if (this.disposed) return;- if (!this.deps.isGhostDetachable(ghostId)) return;- this.ensureSlot(ghostId);- }-- setLocale(locale: SupportedLocale): void {- this.locale = locale;- for (const slot of this.slots.values()) {- if (slot.win.isDestroyed()) continue;- try {- slot.win.webContents.send(GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL, locale);- } catch {- // Window may be tearing down.- }- }- }-- /**- * 幂等打开:热窗口(presentationReady)立即显示;冷窗口等待首份内容。- * 资格不符则清条目防陈年状态复活。- */- open(ghostId: string): void {- if (this.disposed) return;- if (!this.deps.isGhostDetachable(ghostId)) {- this.deps.log.warn('ghost not detachable, pruning entry', { ghostId });- const staleSlot = this.slots.get(ghostId);- if (staleSlot && !staleSlot.destroyingWindow) this.disposeSlot(ghostId, staleSlot);- this.deps.settings.removeEntry(ghostId);- this.broadcast();- return;- }-- const existing = this.slots.get(ghostId);- if (existing) {- if (- existing.visible &&- existing.win.isVisible() &&- !existing.win.isMinimized()- ) {- existing.win.focus();- return;- }- if (existing.presentationReady) {- this.showAndFocus(ghostId, existing);- return;- }- existing.pendingOpen = true;- this.scheduleOpenFallback(ghostId, existing);- this.deps.settings.patchEntry(ghostId, { detached: true, lastOpen: true });- this.broadcast();- return;- }-- const slot = this.ensureSlot(ghostId);- if (!slot) return;- slot.pendingOpen = true;- if (slot.presentationReady) {- this.showAndFocus(ghostId, slot);- } else {- this.scheduleOpenFallback(ghostId, slot);- }- this.deps.settings.patchEntry(ghostId, { detached: true, lastOpen: true });- this.broadcast();- }-- /** 普通关窗只隐藏(保留 renderer,供下次瞬时恢复)。偏好保持 detached:true。 */- close(ghostId: string): void {- const slot = this.slots.get(ghostId);- if (!slot) {- // 窗口不存在,但仍需落盘 lastOpen=false- this.deps.settings.patchEntry(ghostId, { lastOpen: false });- this.broadcast();- return;- }- this.hideWindow(ghostId, slot);- }-- /** 写偏好;true 开窗,false 真正销毁窗口(= 回停靠)。 */- setDetached(ghostId: string, next: boolean): GhostPanelWindowsState {- if (next) {- this.open(ghostId);- } else {- this.deps.settings.patchEntry(ghostId, { detached: false, lastOpen: false });- const slot = this.slots.get(ghostId);- if (slot && !slot.destroyingWindow) {- this.disposeSlot(ghostId, slot);- }- this.broadcast();- }- return this.getState();- }--- // ── 双阶段就绪 ──────────────────────────────────────────────────────-- markRendererReady(sender: WebContents): void {- const entry = this.slotForSender(sender);- if (!entry) return;- entry.slot.rendererReady = true;- if (this.locale) {- try {- sender.send(GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL, this.locale);- } catch {- // Renderer may be tearing down.- }- }- }-- markPresentationReady(sender: WebContents): void {- const entry = this.slotForSender(sender);- if (!entry) return;- entry.slot.presentationReady = true;- this.scheduleRecoveryStabilityReset(entry.slot);- if (entry.slot.pendingOpen) {- this.showAndFocus(entry.ghostId, entry.slot);- }- }-- /** 查找 sender 对应的 ghostId+slot;非本 controller 管理的窗口返回 null。 */- slotForSender(sender: WebContents): { ghostId: string; slot: WindowSlot } | null {- for (const [id, slot] of this.slots) {- if (slot.win && !slot.win.isDestroyed() && slot.win.webContents === sender) {- return { ghostId: id, slot };- }- }- return null;- }-- getSidebarWebContents(ghostId: string): WebContents | null {- const slot = this.slots.get(ghostId);- if (!slot || slot.win.isDestroyed()) return null;- return slot.win.webContents;- }-- requestClose(sender: WebContents): void {- const entry = this.slotForSender(sender);- if (!entry) return;- this.deps.sendToWindow(entry.slot.win, GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL, undefined);- }-- resolveCloseRequest(sender: WebContents, approved: boolean): void {- const entry = this.slotForSender(sender);- // The renderer owns the confirmation and performs setEnabled(false) after- // approval. Keep the window visible until that operation succeeds so an IPC- // failure does not silently hide an enabled plugin.- if (!entry || !approved) return;- }-- // ── reconcile ──────────────────────────────────────────────────────-- reconcile(ghosts: InstalledGhost[]): void {- const byId = new Map(ghosts.map((g) => [installedGhostStoragePart(g), g]));- const knownIds = new Set([- ...Object.keys(this.deps.settings.read().windows),- ...this.slots.keys(),- ]);- let changed = false;- for (const id of knownIds) {- const ghost = byId.get(id);- const detachable =- ghost !== undefined &&- ghost.enabled !== false &&- ghost.manifest.panel !== undefined &&- ghost.manifest.panel.position !== 'tab';- if (detachable) continue;-- const slot = this.slots.get(id);- if (slot && !slot.destroyingWindow) {- this.disposeSlot(id, slot);- }- if (ghost === undefined) {- this.deps.settings.removeEntry(id);- } else {- this.deps.settings.patchEntry(id, { detached: false, lastOpen: false });- }- changed = true;- this.deps.log.info('ghost panel window reconciled away', { ghostId: id });- }- if (changed) this.broadcast();- }-- // ── 生命周期 ────────────────────────────────────────────────────────-- /**- * data owner 真变化时同步销毁旧 owner 的所有独立窗口。- * 把既有面板收口回 docked/closed,避免新 owner 失去正常 UI 入口。- */- closeForOwnerChange(): void {- const { windows } = this.deps.settings.read();- this.destroyAllWindows();- for (const ghostId of Object.keys(windows)) {- this.deps.settings.patchEntry(ghostId, { detached: false, lastOpen: false });- }- this.broadcast();- }-- /** 主窗口销毁时回收所有隐藏窗口;controller 仍可随下一扇主窗重新预热。 */- destroyAllWindows(): void {- for (const [, slot] of this.slots) {- this.clearTimeouts(slot);- if (!slot.win.isDestroyed()) {- slot.destroyingWindow = true;- try { slot.win.destroy(); } catch { /* already gone */ }- }- }- this.slots.clear();- }-- /** 应用退出时永久停止并同步销毁所有缓存窗口。 */- dispose(): void {- if (this.disposed) return;- this.disposed = true;- this.destroyAllWindows();- }-- // ══════════════════════════════════════════════════════════════════════- // 内部:窗口创建与生命周期- // ══════════════════════════════════════════════════════════════════════-- private ensureSlot(ghostId: string): WindowSlot | null {- const existing = this.slots.get(ghostId);- if (existing && !existing.win.isDestroyed()) return existing;-- let win: BrowserWindow;- try {- win = this.deps.createWindow(ghostId);- } catch (error) {- this.deps.log.warn('ghost panel window creation failed', {- ghostId,- error: error instanceof Error ? error.message : String(error),- });- return null;- }-- const slot: WindowSlot = {- win,- rendererReady: false,- presentationReady: false,- visible: false,- pendingOpen: false,- destroyingWindow: false,- openTimeout: null,- recoveryStabilityTimeout: null,- automaticRecoveryAttempts: 0,- };- this.slots.set(ghostId, slot);-- win.on('close', (event) => {- if (slot.destroyingWindow || this.disposed) return;- event.preventDefault();- this.requestClose(win.webContents);- });- win.on('minimize', () => {- if (slot.destroyingWindow || this.disposed) return;- // 原生标题栏(macOS 黄灯)与系统级最小化入口也必须复用插件面板最小化语义。- // 先恢复,避免在 renderer 完成 setDetached(false) 前短暂留在 Dock/任务栏。- if (win.isMinimized()) win.restore();- this.deps.sendToWindow(win, GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL, undefined);- });- win.on('show', () => this.onNativeVisibilityChanged(ghostId, slot, true));- win.on('hide', () => this.onNativeVisibilityChanged(ghostId, slot, false));- win.on('closed', () => this.onClosed(ghostId, slot));- win.webContents.on('did-start-navigation', (_event, _url, isInPlace, isMainFrame) => {- if (isMainFrame && !isInPlace) this.onRendererReloadStarted(ghostId, slot);- });- win.webContents.on(- 'did-fail-load',- (_event, errorCode, errorDescription, _validatedUrl, isMainFrame) => {- if (isMainFrame && errorCode !== -3) {- this.invalidateSlot(ghostId, slot, `load failed (${errorCode}): ${errorDescription}`);- }- },- );- win.webContents.on('render-process-gone', (_event, details) => {- this.invalidateSlot(ghostId, slot, `renderer process gone: ${details.reason}`);- });-- return slot;- }-- private showAndFocus(ghostId: string, slot: WindowSlot): void {- this.clearOpenTimeout(slot);- slot.pendingOpen = false;- if (slot.win.isMinimized()) slot.win.restore();- slot.win.show();- slot.win.focus();- slot.visible = true;- this.deps.sendToWindow(slot.win, GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible: true });- this.broadcast();- }-- private hideWindow(ghostId: string, slot: WindowSlot): void {- this.clearOpenTimeout(slot);- slot.pendingOpen = false;- if (slot.win.isVisible()) slot.win.hide();- slot.visible = false;- try {- this.deps.sendToWindow(slot.win, GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible: false });- } catch { /* window may be torn down */ }- this.deps.settings.patchEntry(ghostId, { lastOpen: false });- this.broadcast();- this.deps.log.info('ghost panel window hidden', { ghostId });- }-- private onNativeVisibilityChanged(- ghostId: string,- slot: WindowSlot,- visible: boolean,- ): void {- if (- this.slots.get(ghostId) !== slot ||- slot.win.isDestroyed() ||- slot.destroyingWindow ||- this.disposed- ) {- return;- }- if (slot.visible === visible && !slot.pendingOpen) return;- slot.visible = visible;- if (visible) slot.pendingOpen = false;- try {- this.deps.sendToWindow(slot.win, GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible });- } catch {- // Native visibility can change while the renderer is tearing down.- }- this.broadcast();- }-- private onClosed(ghostId: string, slot: WindowSlot): void {- this.clearTimeouts(slot);- if (this.slots.get(ghostId) !== slot) return;- this.slots.delete(ghostId);- if (slot.destroyingWindow) return;- if (this.deps.isQuitting()) return;- if (ghostId in this.deps.settings.read().windows) {- this.deps.settings.patchEntry(ghostId, { detached: false, lastOpen: false });- }- this.broadcast();- this.deps.log.info('ghost panel window closed (destroyed)', { ghostId });- }-- // ── 超时 ────────────────────────────────────────────────────────────-- private scheduleOpenFallback(ghostId: string, slot: WindowSlot): void {- this.clearOpenTimeout(slot);- slot.openTimeout = setTimeout(() => {- slot.openTimeout = null;- if (slot.win.isDestroyed() || !slot.pendingOpen) return;- // 窗口规则 §3.1:shell(rendererReady)未就绪时展示可能是空白窗口;按资源用量- // 窗口基线作废缓存并走有界恢复(重建重开),恢复额度耗尽才放弃。- if (!slot.rendererReady) {- this.invalidateSlot(ghostId, slot, 'renderer readiness timed out');- return;- }- if (!slot.visible) this.showAndFocus(ghostId, slot);- }, DEFAULT_OPEN_TIMEOUT_MS);- slot.openTimeout.unref?.();- }-- private clearOpenTimeout(slot: WindowSlot): void {- if (!slot.openTimeout) return;- clearTimeout(slot.openTimeout);- slot.openTimeout = null;- }-- private scheduleRecoveryStabilityReset(slot: WindowSlot): void {- if (slot.automaticRecoveryAttempts === 0) return;- if (slot.recoveryStabilityTimeout) {- clearTimeout(slot.recoveryStabilityTimeout);- }- slot.recoveryStabilityTimeout = setTimeout(() => {- slot.recoveryStabilityTimeout = null;- if (slot.win.isDestroyed() || !slot.presentationReady) return;- slot.automaticRecoveryAttempts = 0;- }, DEFAULT_RECOVERY_STABILITY_MS);- slot.recoveryStabilityTimeout.unref?.();- }-- // ── 崩溃恢复 ────────────────────────────────────────────────────────-- private onRendererReloadStarted(_ghostId: string, slot: WindowSlot): void {- if (slot.win.isDestroyed()) return;- const shouldRestore = slot.visible || slot.pendingOpen;- if (shouldRestore) slot.pendingOpen = true;- if (slot.visible) slot.win.hide();- slot.rendererReady = false;- slot.presentationReady = false;- if (shouldRestore) {- this.scheduleOpenFallback(_ghostId, slot);- }- }-- private invalidateSlot(ghostId: string, slot: WindowSlot, reason: string): void {- if (slot.win.isDestroyed()) return;- const reopen = slot.pendingOpen || slot.visible;- this.deps.log.warn('ghost panel cached window invalidated', { ghostId, reason, reopen });- this.disposeSlot(ghostId, slot);- if (!reopen || this.disposed) return;- if (slot.automaticRecoveryAttempts >= MAX_AUTOMATIC_RECOVERY_ATTEMPTS) {- this.deps.log.error('ghost panel automatic recovery exhausted', { ghostId, reason });- return;- }- // 重建并重新 open:恢复额度在 presentationReady 时重置- const replacement = this.ensureSlot(ghostId);- if (!replacement) return;- replacement.automaticRecoveryAttempts = slot.automaticRecoveryAttempts + 1;- replacement.pendingOpen = true;- this.scheduleOpenFallback(ghostId, replacement);- this.deps.settings.patchEntry(ghostId, { detached: true, lastOpen: true });- this.broadcast();- }-- // ── 销毁 ────────────────────────────────────────────────────────────-- private disposeSlot(ghostId: string, slot: WindowSlot): void {- this.clearTimeouts(slot);- this.slots.delete(ghostId);- slot.destroyingWindow = true;- try {- if (!slot.win.isDestroyed()) slot.win.destroy();- } catch { /* already gone */ }- }-- private clearTimeouts(slot: WindowSlot): void {- if (slot.openTimeout) { clearTimeout(slot.openTimeout); slot.openTimeout = null; }- if (slot.recoveryStabilityTimeout) { clearTimeout(slot.recoveryStabilityTimeout); slot.recoveryStabilityTimeout = null; }- }-- // ── 查询 ────────────────────────────────────────────────────────────-- private entryState(- ghostId: string,- entry: { detached: boolean; lastOpen: boolean },- ): GhostPanelWindowEntryState {- return { detached: entry.detached, lastOpen: entry.lastOpen, open: this.isOpen(ghostId) };- }-- private isOpen(ghostId: string): boolean {- const slot = this.slots.get(ghostId);- if (!slot || slot.win.isDestroyed()) return false;- return slot.visible || slot.pendingOpen;- }-- private broadcast(): void {- this.deps.broadcastState(this.getState());- }-}diff --git a/apps/desktop/src/main/ghost-panel-window/ipc.ts b/apps/desktop/src/main/ghost-panel-window/ipc.tsdeleted file mode 100644index 5cd0c87d9f..0000000000--- a/apps/desktop/src/main/ghost-panel-window/ipc.ts+++ /dev/null@@ -1,88 +0,0 @@-/**- * registerGhostPanelWindowIpc —— 插件面板独立窗口的 IPC 注册。- *- * 全部委托给 GhostPanelWindowsController,这里只做:- * - sender 归属校验:invoke 一律 assertTrustedAppRendererEvent(主窗/副窗/- * 面板子窗都是 markAppContentWindow 过的同源受信 renderer;插件 webview- * 没有 preload 根本到不了这些通道,这层闸防的是越权 frame);- * - payload 运行时校验(throwIpcError INVALID_PARAMS);- * - 首帧 sendSync 通道:不受信 sender 回空对象,绝不 throw 进 sendSync。- */--import { ipcMain } from 'electron';--import { MAKER_INVOKE } from '../maker-ipc/channels.js';-import { createLogger } from '../logger.js';-import { assertTrustedAppRendererEvent, isTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';-import { throwIpcError } from '../utils/ipcValidate.js';-import { isValidPluginStoragePart } from '../../shared/pluginIdentity.js';-import {- GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL,- GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL,- GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL,-} from '../../shared/ghostPanelWindow.js';-import type { GhostPanelWindowsController } from './controller.js';--const log = createLogger('ghost-panel-window-ipc');--/** 首帧同步读通道(与 layout:get / ghosts:list 同模式,见 channels.ts 注释)。 */-export const GHOST_PANEL_WINDOW_GET_STATE_SYNC = 'ghost-panel-window:get-state-sync';--export function registerGhostPanelWindowIpc(controller: GhostPanelWindowsController): void {- ipcMain.handle(MAKER_INVOKE.GHOST_PANEL_WINDOW_GET_STATE, (event) => {- assertTrustedAppRendererEvent(event);- return controller.getState();- });-- ipcMain.handle(MAKER_INVOKE.GHOST_PANEL_WINDOW_OPEN, (event, ghostId: unknown) => {- assertTrustedAppRendererEvent(event);- if (!isValidPluginStoragePart(ghostId)) {- throwIpcError('INVALID_PARAMS', 'ghostId must be a valid ghost id');- }- controller.open(ghostId);- });-- ipcMain.handle(- MAKER_INVOKE.GHOST_PANEL_WINDOW_SET_DETACHED,- (event, ghostId: unknown, detached: unknown) => {- assertTrustedAppRendererEvent(event);- if (!isValidPluginStoragePart(ghostId)) {- throwIpcError('INVALID_PARAMS', 'ghostId must be a valid ghost id');- }- if (typeof detached !== 'boolean') {- throwIpcError('INVALID_PARAMS', 'detached required (boolean)');- }- return controller.setDetached(ghostId, detached);- },- );-- ipcMain.on(GHOST_PANEL_WINDOW_GET_STATE_SYNC, (event) => {- // sendSync 不能 throw(会把异常序列化回 sendSync 调用点);不受信回空 map。- if (!isTrustedAppRendererEvent(event)) {- log.warn('get-state-sync from untrusted sender, returning empty state');- event.returnValue = {};- return;- }- event.returnValue = controller.getState();- });-- // ── 双阶段就绪握手(对齐 §3.1 基线) ────────────────────────────────-- ipcMain.handle(GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL, (event) => {- assertTrustedAppRendererEvent(event);- controller.markRendererReady(event.sender);- });-- ipcMain.handle(GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL, (event) => {- assertTrustedAppRendererEvent(event);- controller.markPresentationReady(event.sender);- });-- ipcMain.handle(GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL, (event, approved: unknown) => {- assertTrustedAppRendererEvent(event);- if (typeof approved !== 'boolean') {- throwIpcError('INVALID_PARAMS', 'approved required (boolean)');- }- controller.resolveCloseRequest(event.sender, approved);- });-}diff --git a/apps/desktop/src/main/ghost-panel-window/registry.ts b/apps/desktop/src/main/ghost-panel-window/registry.tsdeleted file mode 100644index d86ac47634..0000000000--- a/apps/desktop/src/main/ghost-panel-window/registry.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Ghost panel windows are independently recoverable auxiliary renderers.- * Keep their WebContents ids registered so a crash cannot take down the app.- */--const ghostPanelWebContentsIds = new Set<number>();--export function markGhostPanelWebContentsId(id: number): void {- ghostPanelWebContentsIds.add(id);-}--export function isGhostPanelWebContentsId(id: number): boolean {- return ghostPanelWebContentsIds.has(id);-}diff --git a/apps/desktop/src/main/ghost-panel-window/settings-store.ts b/apps/desktop/src/main/ghost-panel-window/settings-store.tsdeleted file mode 100644index 2a3e2a320e..0000000000--- a/apps/desktop/src/main/ghost-panel-window/settings-store.ts+++ /dev/null@@ -1,81 +0,0 @@-/**- * ghost-panel-window 进程内状态。- *- * 每个 ghostId 的 detached / lastOpen 只服务当前客户端进程,用于窗口状态机和隐藏复用;- * 客户端重启后所有插件面板一律回到主窗口。启动时还会删除旧版本留下的分离偏好文件。- * 窗口尺寸与位置由独立的 window-state 文件管理,不受这里影响。- */--import { app } from 'electron';-import fs from 'node:fs';-import path from 'node:path';--import { isValidPluginStoragePart } from '../../shared/pluginIdentity.js';-import { desktopMakerLogger } from '../maker-host/logger-adapter.js';--const log = desktopMakerLogger.child('ghost-panel-window-settings-store');--export interface GhostPanelWindowEntrySettings {- detached: boolean;- lastOpen: boolean;-}--export interface GhostPanelWindowsSettings {- windows: Record<string, GhostPanelWindowEntrySettings>;-}--let runtimeSettings: GhostPanelWindowsSettings = { windows: {} };--function settingsFilePath(): string {- return path.join(app.getPath('userData'), 'ghost-panel-windows-settings.json');-}--/** 逐条清洗:非法 ghostId / 非布尔字段整条丢弃(fail closed,坏数据不进状态机)。 */-export function normalizeGhostPanelWindowsSettings(raw: unknown): GhostPanelWindowsSettings {- if (!raw || typeof raw !== 'object') return { windows: {} };- const rawWindows = (raw as Record<string, unknown>).windows;- if (!rawWindows || typeof rawWindows !== 'object') return { windows: {} };- const windows: Record<string, GhostPanelWindowEntrySettings> = {};- for (const [id, entry] of Object.entries(rawWindows as Record<string, unknown>)) {- if (!isValidPluginStoragePart(id)) continue;- if (!entry || typeof entry !== 'object') continue;- const e = entry as Record<string, unknown>;- if (typeof e.detached !== 'boolean' || typeof e.lastOpen !== 'boolean') continue;- windows[id] = { detached: e.detached, lastOpen: e.lastOpen };- }- return { windows };-}--export function readGhostPanelWindowsSettings(): GhostPanelWindowsSettings {- return { windows: { ...runtimeSettings.windows } };-}--/** 单条 patch:writePatch 是浅合并,windows map 必须整体读改写。 */-export function patchGhostPanelWindowEntry(- ghostId: string,- patch: Partial<GhostPanelWindowEntrySettings>,-): void {- const current = runtimeSettings.windows;- const entry = current[ghostId] ?? { detached: false, lastOpen: false };- runtimeSettings = { windows: { ...current, [ghostId]: { ...entry, ...patch } } };-}--/** 删条目(卸载清理):不存在时为 no-op。 */-export function removeGhostPanelWindowEntry(ghostId: string): void {- const current = runtimeSettings.windows;- if (!(ghostId in current)) return;- const next = { ...current };- delete next[ghostId];- runtimeSettings = { windows: next };-}--/** 新进程重置全部插件面板的分离状态,并清理旧版本遗留的持久化偏好。 */-export function resetGhostPanelWindowSettingsForStartup(): void {- runtimeSettings = { windows: {} };- const legacyFile = settingsFilePath();- try {- fs.rmSync(legacyFile, { force: true });- } catch (err) {- log.warn('failed to remove legacy ghost-panel window settings', { legacyFile, err });- }-}diff --git a/apps/desktop/src/main/ghost-panel-window/window.ts b/apps/desktop/src/main/ghost-panel-window/window.tsdeleted file mode 100644index 2a94cf832b..0000000000--- a/apps/desktop/src/main/ghost-panel-window/window.ts+++ /dev/null@@ -1,119 +0,0 @@-/**- * createGhostPanelWindow —— 插件停靠面板独立窗口的 BrowserWindow 工厂。- *- * 蓝本是 right-sidebar-window/window.ts,差异:- * - 按 ghostId 多实例:窗口位置记忆每插件一份- * (ghost-panel-window-state-<id>.json,id 为 storage part,文件名安全);- * - webPreferences 按 electron-security-and-process-boundaries §3 显式带全量- * 安全项(该规则晚于主窗/RSB 窗,新窗口必须逐项写明,不吃默认值);- * - `webviewTag: true`:面板体就是 <webview>(cindy-ghost:// 分区)。附加闸/- * 硬化器(webview-security.ts)对所有窗口全局生效,这里零额外授权;- * - 启动参数 `?ghostPanelWindow=<id>` + hash `/ghost-panel-window`:renderer- * 单入口,router 据此只挂 GhostPanelWindowLayout。- */--import { BrowserWindow, app, nativeTheme } from 'electron';-import path from 'node:path';-import windowStateKeeper from 'electron-window-state';--import { createLogger } from '../logger.js';-import { markAppContentWindow } from '../windowFocusClassifier.js';-import { readWindowBehaviorSettings } from '../window-behavior-settings-store.js';-import { installExternalLinkGuards } from '../secondary-windows.js';-import { installSelectionContextMenu } from '../selection-context-menu.js';-import { applyAppearanceToWindow } from '../appearance-settings-ipc.js';-import { markGhostPanelWebContentsId } from './registry.js';--const log = createLogger('ghost-panel-window');--export function createGhostPanelWindow(ghostId: string, title: string): BrowserWindow {- const platformOptions =- process.platform === 'darwin'- ? { titleBarStyle: 'hidden' as const, trafficLightPosition: { x: 12, y: 16 } }- : { frame: false };- const bgColor = nativeTheme.shouldUseDarkColors ? '#1f1f1e' : '#f8f8f6';-- // 与主窗 / 副窗保持 acceptFirstMouse 一致(见 secondary-windows.ts 同款注释)。- const swallowActivationClick = readWindowBehaviorSettings().swallowActivationClick;-- const windowState = windowStateKeeper({- defaultWidth: 480,- defaultHeight: 720,- file: `ghost-panel-window-state-${ghostId}.json`,- });-- const win = new BrowserWindow({- x: windowState.x,- y: windowState.y,- width: windowState.width,- height: windowState.height,- minWidth: 320,- minHeight: 400,- title,- icon: app.isPackaged- ? path.join(process.resourcesPath, 'icon.png')- : path.join(__dirname, '../../resources/icon.png'),- autoHideMenuBar: true,- show: false,- backgroundColor: bgColor,- acceptFirstMouse: !swallowActivationClick,- ...platformOptions,- webPreferences: {- preload: path.join(__dirname, 'ghostPanelWindowPreload.js'),- spellcheck: false,- webviewTag: true,- // 安全规则 §3 全量显式项(新建窗口不吃默认值,逐项写明):- sandbox: true,- contextIsolation: true,- nodeIntegration: false,- nodeIntegrationInSubFrames: false,- nodeIntegrationInWorker: false,- webSecurity: true,- allowRunningInsecureContent: false,- experimentalFeatures: false,- plugins: false,- navigateOnDragDrop: false,- },- });- // Keep the detached plugin renderer in sync with its own native fullscreen- // state; the main window's listener cannot describe this BrowserWindow.- win.on('enter-full-screen', () => {- if (!win.isDestroyed()) win.webContents.send('fullscreen-change', true);- });- win.on('leave-full-screen', () => {- if (!win.isDestroyed()) win.webContents.send('fullscreen-change', false);- });- markGhostPanelWebContentsId(win.webContents.id);- markAppContentWindow(win);- applyAppearanceToWindow(win);- win.webContents.on('did-finish-load', () => {- if (win.isDestroyed()) return;- applyAppearanceToWindow(win);- });- installSelectionContextMenu(win);- windowState.manage(win);-- installExternalLinkGuards(win);-- // ready-to-show 不再直接 show();由 controller 的双阶段就绪握手控制展示时机。- // 窗口以 show:false 创建,首次显示由 controller 在 presentation-ready 后触发。- win.once('ready-to-show', () => {- // no-op: 窗口由 controller 控制展示- });-- const hash = '/ghost-panel-window';- if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {- const url = new URL(MAIN_WINDOW_VITE_DEV_SERVER_URL);- url.searchParams.set('ghostPanelWindow', ghostId);- url.hash = hash;- void win.loadURL(url.toString());- } else {- void win.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`), {- query: { ghostPanelWindow: ghostId },- hash,- });- }-- log.info('ghost panel window created', { ghostId });- return win;-}diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.tsindex 8c87ad8b10..ddf472f8ca 100644--- a/apps/desktop/src/main/lifecycle.ts+++ b/apps/desktop/src/main/lifecycle.ts@@ -52,7 +52,6 @@ import { isRsbNativePopupWebContentsId } from './rsb-browser-bridge/native-popupimport { isResourceUsageWebContentsId } from './resource-usage-window/registry.js';import { isRemoteDesktopViewer } from './remote-desktop-viewer/registry.js';import { isRsbWindowWebContentsId } from './right-sidebar-window/registry.js';-import { isGhostPanelWebContentsId } from './ghost-panel-window/registry.js';import { isReviewArtifactConfirmWebContentsId } from './reviewer/reviewArtifactConfirmWindowRegistry.js';/**@@ -671,12 +670,6 @@ export function installQuitHandler(timeoutMs = 2000): void {);return;}- if (isGhostPanelWebContentsId(webContents.id)) {- log.warn(- `ghost panel render-process-gone (isolated, no shutdown): reason=${details.reason} exitCode=${details.exitCode}`,- );- return;- }if (isReviewArtifactConfirmWebContentsId(webContents.id)) {log.warn(`Review artifact consent render-process-gone (isolated, access denied): reason=${details.reason} exitCode=${details.exitCode}`,diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 02513c1926..14e32c4200 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -746,18 +746,6 @@ export const MAKER_INVOKE = {RSB_WINDOW_GET_CONTEXT: 'maker:rsb-window:get-context',RSB_WINDOW_READY: 'maker:rsb-window:ready',RSB_WINDOW_SEND_COMMAND: 'maker:rsb-window:send-command',- /**- * 插件停靠面板独立窗口(ghost panel window)——每 ghostId 一扇窗。- * 状态机见 main/ghost-panel-window/controller.ts。- * - GET_STATE: 拉全量 { <ghostId>: { detached, lastOpen, open } }- * - OPEN(ghostId): 幂等开(已开则 focus);资格不符清条目- * - SET_DETACHED(ghostId, boolean): true 开窗抽离,false 关窗回停靠;返回新全量 state- * 首帧同步读走裸 sendSync 通道 'ghost-panel-window:get-state-sync'- * (与 layout:get / ghosts:list 同模式,规则 7 首帧无跳变)。- */- GHOST_PANEL_WINDOW_GET_STATE: 'maker:ghost-panel-window:get-state',- GHOST_PANEL_WINDOW_OPEN: 'maker:ghost-panel-window:open',- GHOST_PANEL_WINDOW_SET_DETACHED: 'maker:ghost-panel-window:set-detached',/*** 右侧栏单页签独立窗口(sidebar tab window)——每个弹出的页签一扇窗。* 状态机见 main/sidebar-tab-window/controller.ts。@@ -1062,11 +1050,6 @@ export const MAKER_PUSH = {RSB_WINDOW_COMMAND: 'maker:rsb-window:command',/** 子窗口合并回主窗口前交接不可持久化 session 的 tab 快照,只发主窗口。 */RSB_WINDOW_TAB_HANDOFF: 'maker:rsb-window:tab-handoff',- /**- * 插件面板独立窗口状态广播(全量 GhostPanelWindowsState)——发所有窗口- * (主窗布局过滤 + 各子窗口自身都消费)。- */- GHOST_PANEL_WINDOW_STATE_CHANGED: 'maker:ghost-panel-window:state-changed',/*** 右侧栏单页签独立窗口状态广播(全量 SidebarTabWindowsState)——发所有窗口* (主窗侧栏据此隐藏已弹出页签;弹出窗口自身不消费)。diff --git a/apps/desktop/src/main/sidebar-tab-window/controller.ts b/apps/desktop/src/main/sidebar-tab-window/controller.tsindex 32f73615c6..d6d087c7fa 100644--- a/apps/desktop/src/main/sidebar-tab-window/controller.ts+++ b/apps/desktop/src/main/sidebar-tab-window/controller.ts@@ -9,7 +9,7 @@* 「偏好」可落盘:弹出是本次运行期的视图态,客户端重启后所有页签都回到主窗。** 生命周期基线对齐 docs/dev-rules/electron-security-and-process-boundaries.md §3.1- * 与 ghost-panel-window/controller.ts:+ * (资源用量窗口 controller 为权威基线):* - 预热:主窗首帧稳定后后台创建一扇**未指派**的隐藏窗口(spare);弹出时直接* 指派页签给它,用户点击路径只剩「指派 → 首份内容 → show+focus」。指派后再* 延迟补一扇 spare。diff --git a/apps/desktop/src/main/sidebar-tab-window/ipc.ts b/apps/desktop/src/main/sidebar-tab-window/ipc.tsindex d845954403..6179723b29 100644--- a/apps/desktop/src/main/sidebar-tab-window/ipc.ts+++ b/apps/desktop/src/main/sidebar-tab-window/ipc.ts@@ -120,7 +120,8 @@ function parseOpenRequest(raw: unknown): SidebarTabWindowOpenRequest {const obj = requireObject(raw, 'open request');return {tabId: requireId(obj.tabId, 'tabId'),- sessionId: requireId(obj.sessionId, 'sessionId'),+ // 全局页签(插件视图)不属于任何任务:sessionId 为 null。+ sessionId: optionalNullableString(obj.sessionId, 'sessionId') ?? null,context: parseContext(obj.context),handoff: parseHandoff(obj.handoff),};diff --git a/apps/desktop/src/preload/ghostPanelWindowPreload.ts b/apps/desktop/src/preload/ghostPanelWindowPreload.tsdeleted file mode 100644index 9b918cfdb2..0000000000--- a/apps/desktop/src/preload/ghostPanelWindowPreload.ts+++ /dev/null@@ -1,303 +0,0 @@-/**- * 插件面板独立窗口专用 preload:最小权限 bridge。- *- * 能力清单基于 GhostPanelWindowLayout + GhostChipPanelBody + GhostMediaLightboxHost +- * ghostPanels + useInstalledGhosts + runtimeStates + ghostMediaHandover 的实际- * `window.electronAPI.*` 调用栈静态收窄:- * - 窗口 chrome(appearance / windowControls / shortcuts / theme)- * - 插件面板窗口状态(detach / attach)- * - 双阶段就绪握手 + visibility 刷新- * - 插件管理(list / reload / setEnabled / resolvePanelMedia / runtimeStates +- * 事件订阅 onChanged / onRuntimeChanged / onLibraryReplaced / onPreviewMedia)- * - 面板产物右键菜单媒体动作(copyMediaToClipboard / showItemInFolder)- * - 面板拖拽引渡落会话附件(cacheMediaForSession)- *- * 不得复制主 preload 的完整 ghosts bridge 或 maker/session/voice/login 桥。- */--import { contextBridge, ipcRenderer } from 'electron';--import { createAppearanceSnapshotBridge } from './appearanceSnapshot';-import type { LocalThemesResult } from '../shared/local-themes';-import type { GhostPanelWindowsState } from '../shared/ghostPanelWindow';-import { isValidPluginStoragePart } from '../shared/pluginIdentity';-import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from '../shared/locale';-import {- GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL,- GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL,- GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL,- GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL,- GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL,- GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL,- GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL,-} from '../shared/ghostPanelWindow';--type Unsub = () => void;-type ApplicationMenuLocale = SupportedLocale;--function readPreferredSystemLocale(): ApplicationMenuLocale {- try {- const value = ipcRenderer.sendSync('app-locale:get-preferred-system-locale-sync');- return typeof value === 'string' && (SUPPORTED_LOCALES as readonly string[]).includes(value)- ? (value as ApplicationMenuLocale)- : DEFAULT_LOCALE;- } catch {- return DEFAULT_LOCALE;- }-}--function onPayload<T>(channel: string, cb: (payload: T) => void): Unsub {- const listener = (_event: Electron.IpcRendererEvent, payload: T): void => cb(payload);- ipcRenderer.on(channel, listener);- return () => ipcRenderer.removeListener(channel, listener);-}--const currentGhostPanelId = (() => {- const raw = new URLSearchParams(window.location.search).get('ghostPanelWindow');- return isValidPluginStoragePart(raw) ? raw : null;-})();--function mutationErrorForGhostPanel(id: string): Error | null {- if (currentGhostPanelId === null || id !== currentGhostPanelId) {- return new Error('ghost panel mutation must target the current panel');- }- return null;-}--// 事件扇出型通道(main 广播 → 所有 renderer),按名注册 listener,fan-out 在 preload 层。-function fanOut(channel: string): (cb: (payload: unknown) => void) => Unsub {- return (cb) => {- const listener = (_event: Electron.IpcRendererEvent, payload: unknown): void => cb(payload);- ipcRenderer.on(channel, listener);- return () => ipcRenderer.removeListener(channel, listener);- };-}--const fanOutGhostsChanged = fanOut('ghosts:changed');-const fanOutGhostRuntimeChanged = fanOut('ghosts:runtime-changed');-const fanOutGhostLibraryReplaced = fanOut('ghosts:library-replaced');-const fanOutGhostPreviewMedia = fanOut('ghosts:preview-media');--function onCurrentGhostBadge(- cb: (payload: { ghostId: string; unread: boolean; summary?: string; at?: number }) => void,-): Unsub {- const listener = (_event: Electron.IpcRendererEvent, payload: unknown): void => {- if (currentGhostPanelId === null || typeof payload !== 'object' || payload === null) return;- const candidate = payload as { ghostId?: unknown };- if (candidate.ghostId !== currentGhostPanelId) return;- cb(payload as { ghostId: string; unread: boolean; summary?: string; at?: number });- };- ipcRenderer.on('ghosts:badge', listener);- return () => ipcRenderer.removeListener('ghosts:badge', listener);-}--function onCurrentGhostUnreadSnapshot(- cb: (payload: { entries: { ghostId: string; summary?: string; at: number }[] }) => void,-): Unsub {- const listener = (_event: Electron.IpcRendererEvent, payload: unknown): void => {- if (currentGhostPanelId === null || typeof payload !== 'object' || payload === null) return;- const entries = (payload as { entries?: unknown }).entries;- if (!Array.isArray(entries)) return;- const scoped: { ghostId: string; summary?: string; at: number }[] = [];- for (const entry of entries) {- if (typeof entry !== 'object' || entry === null) continue;- const candidate = entry as { ghostId?: unknown; at?: unknown; summary?: unknown };- if (candidate.ghostId !== currentGhostPanelId || typeof candidate.at !== 'number') continue;- scoped.push({- ghostId: currentGhostPanelId,- at: candidate.at,- ...(typeof candidate.summary === 'string' ? { summary: candidate.summary } : {}),- });- }- cb({ entries: scoped });- };- ipcRenderer.on('ghosts:unread-snapshot', listener);- return () => ipcRenderer.removeListener('ghosts:unread-snapshot', listener);-}--const appearanceSnapshot = createAppearanceSnapshotBridge({ wallpaperAssets: true });--const fanOutFullscreenChange = (cb: (isFullscreen: boolean) => void): Unsub =>- onPayload('fullscreen-change', cb);--contextBridge.exposeInMainWorld('electronAPI', {- platform: process.platform,- preferredSystemLocale: readPreferredSystemLocale(),- windowMinimize: (): void => ipcRenderer.send('window-minimize'),- windowMaximize: (): void => ipcRenderer.send('window-maximize'),- windowClose: (): void => ipcRenderer.send('window-close'),- logToMain: (- level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal',- scope: string,- msg: string,- ): void => ipcRenderer.send('renderer:log', level, scope, msg),- onLocaleChanged: (cb: (locale: SupportedLocale) => void): Unsub =>- onPayload(GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL, cb),- appearanceSettings: appearanceSnapshot,- localThemes: {- listSync: (): LocalThemesResult => {- try {- return ipcRenderer.sendSync('local-themes:list-sync') as LocalThemesResult;- } catch (error) {- return { success: false, error: String(error), themes: [], diagnostics: [] };- }- },- },- appShortcuts: {- getState: (): { overrides: Record<string, unknown>; platform: string } =>- ipcRenderer.sendSync('app-shortcuts:get'),- onChanged: (cb: (payload: { overrides?: Record<string, unknown> }) => void): Unsub =>- onPayload('app-shortcuts:changed', cb),- },- theme: {- applyVibrancy: (familyId: string, isDark: boolean): void => {- ipcRenderer.send('theme:apply-vibrancy', { familyId, isDark });- },- },- // Shared panel chrome may need this when a detached plugin window is used- // on macOS, where the traffic-light area changes during native fullscreen.- onFullscreenChange: fanOutFullscreenChange,- getFullscreenState: (): Promise<boolean> => ipcRenderer.invoke('get-fullscreen-state'),-- // ── 媒体操作(面板产物右键菜单 / 拖拽引渡) ──────────────────────────- // 与主 preload 同款 channel,main 侧 handler 对所有受信 renderer 生效。-- copyMediaToClipboard: (params: {- url?: string;- filePath?: string;- }): Promise<{ success: boolean; error?: string }> =>- ipcRenderer.invoke('media:copy-to-clipboard', params),-- showItemInFolder: (params: {- url?: string;- filePath?: string;- }): Promise<{ success: boolean; error?: string }> =>- ipcRenderer.invoke('shell:show-item-in-folder', params),-- cacheMediaForSession: (params: {- url: string;- sessionId: string;- }): Promise<{- url: string;- name: string;- ext: string;- size: number;- mimeType: string;- }> => ipcRenderer.invoke('media:cache-for-session', params),-- /** 用系统默认应用打开图片/视频(cindy-media:// 源——lightbox 内菜单项)。 */- openMediaWithDefaultApp: (params: { url: string }): Promise<void> =>- ipcRenderer.invoke('media:open-with-default-app', params),-- /** 「另存为」系统保存对话框(lightbox 内菜单项)。 */- saveMediaAs: (params: { url: string }): Promise<{ canceled: boolean; savedPath?: string }> =>- ipcRenderer.invoke('media:save-as', params),-- // ── 插件面板窗口状态 ────────────────────────────────────────────────-- ghostPanelWindow: {- getStateSync: (): GhostPanelWindowsState =>- ipcRenderer.sendSync('ghost-panel-window:get-state-sync') as GhostPanelWindowsState,- getState: (): Promise<GhostPanelWindowsState> =>- ipcRenderer.invoke('maker:ghost-panel-window:get-state'),- open: (ghostId: string): Promise<void> => {- const error = mutationErrorForGhostPanel(ghostId);- if (error) return Promise.reject(error);- return ipcRenderer.invoke('maker:ghost-panel-window:open', ghostId);- },- setDetached: (- ghostId: string,- detached: boolean,- ): Promise<GhostPanelWindowsState> => {- const error = mutationErrorForGhostPanel(ghostId);- if (error) return Promise.reject(error);- return ipcRenderer.invoke('maker:ghost-panel-window:set-detached', ghostId, detached);- },- onStateChanged: (cb: (state: GhostPanelWindowsState) => void): Unsub =>- onPayload('maker:push:ghost-panel-window:state-changed', cb),- rendererReady: (): Promise<void> =>- ipcRenderer.invoke(GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL),- presentationReady: (): Promise<void> =>- ipcRenderer.invoke(GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL),- onVisibilityChanged: (cb: (payload: { visible: boolean }) => void): Unsub =>- onPayload(GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL, cb),- onCloseRequested: (cb: () => void): Unsub =>- onPayload(GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL, cb),- onMinimizeRequested: (cb: () => void): Unsub =>- onPayload(GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL, cb),- resolveCloseRequest: (approved: boolean): Promise<void> =>- ipcRenderer.invoke(GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL, approved),- },-- // ── 插件管理(GhostPanelWindowLayout 依赖方法集) ─────────────────────-- ghosts: {- /** 已装清单(同步:与面板体同帧渲染,不闪占位)。 */- listSync: (): { ghosts: unknown[] } => ipcRenderer.sendSync('ghosts:list'),- /** 重载插件(面板崩溃后恢复)。 */- reload: (id: string): Promise<{ state: string }> => {- const error = mutationErrorForGhostPanel(id);- if (error) return Promise.reject(error);- return ipcRenderer.invoke('ghosts:reload', id);- },- /** 启用/停用(面板错误态「关闭」按钮)。 */- setEnabled: (id: string, enabled: boolean, expectedInstalledApproval?: string): Promise<{ ok: true }> => {- const error = mutationErrorForGhostPanel(id);- if (error) return Promise.reject(error);- return ipcRenderer.invoke('ghosts:set-enabled', id, enabled, expectedInstalledApproval);- },- /** 解析面板媒体 URI → cindy-media:// 地址(右键菜单 / 拖拽引渡)。 */- resolvePanelMedia: (- uri: string,- purpose?: 'attach' | 'menu',- instanceId?: string,- sourceToken?: string,- ): Promise<- | { url: string; kind?: 'image' }- | { url: string; kind: 'video'; absPath: string; size: number; name: string; ext: string; mimeType: string }- > => sourceToken !== undefined- ? ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose, instanceId, sourceToken)- : instanceId === undefined- ? ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose)- : ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose, instanceId),- /** 运行时状态快照(面板崩溃/熔断错误态接管)。 */- runtimeStates: (): Promise<{ states: Record<string, string> }> =>- ipcRenderer.invoke('ghosts:runtime-states'),- // ── 事件订阅 ──────────────────────────────────────────────────────- /** 插件装/卸/启/停/换面板形态。 */- onChanged: fanOutGhostsChanged,- /** 插件运行时状态变化(crashed / fused / off 等)。 */- onRuntimeChanged: fanOutGhostRuntimeChanged,- onLibraryReplaced: fanOutGhostLibraryReplaced,- /** 面板点图/视频预览(宿主弹 lightbox)。 */- onPreviewMedia: fanOutGhostPreviewMedia,- /** 未读角标快照(ghostUnreadStore 首帧)。 */- unreadSync: (): { entries: { ghostId: string; summary?: string; at: number }[] } => {- if (currentGhostPanelId === null) return { entries: [] };- try {- const result = ipcRenderer.sendSync('ghosts:unread') as { entries?: unknown } | null;- if (!Array.isArray(result?.entries)) return { entries: [] };- const entries: { ghostId: string; summary?: string; at: number }[] = [];- for (const raw of result.entries) {- if (typeof raw !== 'object' || raw === null) continue;- const { ghostId, summary, at } = raw as Record<string, unknown>;- if (ghostId !== currentGhostPanelId || typeof at !== 'number') continue;- entries.push({ ghostId, ...(typeof summary === 'string' ? { summary } : {}), at });- }- return { entries };- } catch {- return { entries: [] };- }- },- /** 熄灭未读(打开面板 = 已读)。 */- clearUnread: (id: string, seenAt?: number): Promise<{ ok: boolean }> => {- const error = mutationErrorForGhostPanel(id);- if (error) return Promise.reject(error);- return ipcRenderer.invoke('ghosts:clear-unread', id, seenAt);- },- /** 未读角标变化。 */- onBadge: onCurrentGhostBadge,- /** 未读快照变化(ghostUnreadStore 增量更新)。 */- onUnreadSnapshot: onCurrentGhostUnreadSnapshot,- },-});diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex ba9430f85a..b8aed2c104 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -553,10 +553,6 @@ const fanOutRsbWindowStateChanged = createIpcFanOut('maker:rsb-window:state-chanconst fanOutRsbWindowContextChanged = createIpcFanOut('maker:rsb-window:context-changed');const fanOutRsbWindowCommand = createIpcFanOut('maker:rsb-window:command');const fanOutRsbWindowTabHandoff = createIpcFanOut(RSB_WINDOW_TAB_HANDOFF_CHANNEL);-// 插件停靠面板独立窗口(ghost panel window)状态推送-const fanOutGhostPanelWindowStateChanged = createIpcFanOut(- 'maker:ghost-panel-window:state-changed',-);// 右侧栏单页签独立窗口(sidebar tab window)状态 / 页签交回 / 页签持久化变更推送const fanOutSidebarTabWindowStateChanged = createIpcFanOut('maker:sidebar-tab-window:state-changed',@@ -1994,30 +1990,6 @@ contextBridge.exposeInMainWorld('electronAPI', {fanOutRsbWindowTabHandoff((data) => cb(data as RsbWindowTabHandoff)),},- // ── 插件停靠面板独立窗口(ghost panel window)──────────────────────────- // 每 ghostId 一扇窗。状态机在 main(ghost-panel-window/controller.ts),- // renderer 只 invoke + 订阅广播;首帧走 sendSync(规则 7 无跳变)。- ghostPanelWindow: {- /** 首帧同步读全量状态(ghostId → { detached, lastOpen, open })。 */- getStateSync: (): Record<string, { detached: boolean; lastOpen: boolean; open: boolean }> =>- ipcRenderer.sendSync('ghost-panel-window:get-state-sync') as Record<- string,- { detached: boolean; lastOpen: boolean; open: boolean }- >,- getState: (): Promise<- Record<string, { detached: boolean; lastOpen: boolean; open: boolean }>- > => ipcRenderer.invoke('maker:ghost-panel-window:get-state'),- /** 幂等:已开则 show + focus。 */- open: (ghostId: string): Promise<void> =>- ipcRenderer.invoke('maker:ghost-panel-window:open', ghostId),- /** 写偏好;true 开窗抽离,false 关窗回停靠。返回新全量 state。 */- setDetached: (- ghostId: string,- detached: boolean,- ): Promise<Record<string, { detached: boolean; lastOpen: boolean; open: boolean }>> =>- ipcRenderer.invoke('maker:ghost-panel-window:set-detached', ghostId, detached),- onStateChanged: fanOutGhostPanelWindowStateChanged,- },// ── 资源用量独立子窗口 ──────────────────────────────────────────────// 主窗口只持有打开能力;资源窗口的关闭与就绪能力在专用 preload 中暴露。diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex 60e68f5dcc..2a6a914132 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -25,7 +25,6 @@ import { LoginBrandStage } from '@/components/login/LoginBrandStage';import { StartupLogSupport } from '@/components/log-support/StartupLogSupport';import { isSecondaryWindow } from '@/lib/secondaryWindow';import { isSidebarWindow } from '@/lib/sidebarWindow';-import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';import { ToastContainer } from '@/components/ui/toast';import { LegacyMigrationDialog } from '@/components/auth/LegacyMigrationDialog';import { Tooltip } from '@/components/ui/tooltip';@@ -424,17 +423,11 @@ export function App() {{/* 副窗口(「在新窗口打开」)/ 右侧栏子窗口跳过 splash:env/热更检查由主窗启动时完成,附属窗 EnvCheckProvider 初始即 'passed',不需要也不应再走 splash 流程。 */}- {!isSecondaryWindow() &&- !isSidebarWindow() &&- !isGhostPanelWindow() && <LoginBrandStage />}- {!isSecondaryWindow() &&- !isSidebarWindow() &&- !isGhostPanelWindow() && <SplashScreen />}+ {!isSecondaryWindow() && !isSidebarWindow() && <LoginBrandStage />}+ {!isSecondaryWindow() && !isSidebarWindow() && <SplashScreen />}<EnvCheckGuard><MakerBootstrap />- {!isSecondaryWindow() &&- !isSidebarWindow() &&- !isGhostPanelWindow() && <RemoteDesktopHost />}+ {!isSecondaryWindow() && !isSidebarWindow() && <RemoteDesktopHost />}<ProjectAutomationNotifyBridge />{/* confirm 槽:插件请主机弹确认框。必须在 ConfirmDialogProvider内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口@@ -445,16 +438,12 @@ export function App() {<PluginPublisherConfirmHost /><OwnerScopedRouter /></EnvCheckGuard>- {!isSecondaryWindow() &&- !isSidebarWindow() &&- !isGhostPanelWindow() && <StartupLogSupport />}+ {!isSecondaryWindow() && !isSidebarWindow() && <StartupLogSupport />}</LoginHandoffHost><FindInPageBar /><ToastContainer />{/* 首登轻量数据迁移弹窗:只挂主窗(副窗/侧栏窗不重复弹) */}- {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && (- <LegacyMigrationDialog />- )}+ {!isSecondaryWindow() && !isSidebarWindow() && <LegacyMigrationDialog />}</Tooltip.Provider></PrRefsProvider></WorktreeProvider>diff --git a/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx b/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsxindex 18cfda8981..c7526e9086 100644--- a/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx@@ -44,8 +44,8 @@ vi.mock('../cindy-brain/ghostPanels', () => ({ ensureGhostPanelsRegistered: vi.fvi.mock('../components/layout/SidebarWindowLayout', () => ({SidebarWindowLayout: () => <div>sidebar host</div>,}));-vi.mock('../components/layout/GhostPanelWindowLayout', () => ({- GhostPanelWindowLayout: () => <div>plugin host</div>,+vi.mock('../components/layout/SidebarTabWindowLayout', () => ({+ SidebarTabWindowLayout: () => <div>tab host</div>,}));afterEach(async () => {@@ -64,7 +64,7 @@ afterEach(async () => {vi.restoreAllMocks();});-it.each(['sidebar', 'plugin'] as const)(+it.each(['sidebar'] as const)('boots %s with a wallpaper using its read-only bridge and follows live changes',async (kind) => {vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);@@ -110,12 +110,9 @@ it.each(['sidebar', 'plugin'] as const)(},});await act(async () => {- if (kind === 'sidebar') await import('../sidebar-window-entry');- else await import('../ghost-panel-window-entry');+ await import('../sidebar-window-entry');});- expect(document.body.textContent).toContain(- kind === 'sidebar' ? 'sidebar host' : 'plugin host',- );+ expect(document.body.textContent).toContain('sidebar host');expect(document.documentElement.dataset.wallpaperActive).toBe('true');expect(document.querySelectorAll('video')).toHaveLength(1);expect(document.querySelector('video')?.getAttribute('src')).toBe(videoUrl);diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.tsindex 8dcea673f6..124793421d 100644--- a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts+++ b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts@@ -129,41 +129,25 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不expect(featureContextSource).toContain('export function useOwnsTopNavScrollableRows');});- // 导航改为用户自定义顺序:内置入口与插件主视图按保存顺序排列,面板恢复入口- // 紧随其后,「更多」收尾;展开态与 rail 同一契约。- it('插件主视图与内置入口按保存顺序排列,面板恢复入口在其后、「更多」收尾', () => {+ // 导航改为用户自定义顺序:内置入口与插件主视图按保存顺序排列,「更多」收尾;+ // 展开态与 rail 同一契约。(插件停靠面板恢复入口已随停靠面板一起退场。)+ it('插件主视图与内置入口按保存顺序排列,「更多」收尾', () => {expect(topNavSource).toContain('<GhostMainViewNavEntry item={app} variant="row" />');const scrollRowsIdx = topNavSource.indexOf('{orderedNavigationRows}');- const scrollRestoreIdx = topNavSource.indexOf('{restoreRow}', scrollRowsIdx);- const scrollMoreIdx = topNavSource.indexOf('{customizeRow}', scrollRestoreIdx);+ const scrollMoreIdx = topNavSource.indexOf('{customizeRow}', scrollRowsIdx);expect(scrollRowsIdx).toBeGreaterThanOrEqual(0);- expect(scrollRestoreIdx).toBeGreaterThan(scrollRowsIdx);- expect(scrollMoreIdx).toBeGreaterThan(scrollRestoreIdx);+ expect(scrollMoreIdx).toBeGreaterThan(scrollRowsIdx);const persistentRowsIdx = topNavSource.lastIndexOf('orderedNavigationRows');- const persistentRestoreIdx = topNavSource.indexOf(- '!customizing && restoreRow',- persistentRowsIdx,- );- const persistentMoreIdx = topNavSource.indexOf(- '!customizing && customizeRow',- persistentRestoreIdx,- );- expect(persistentRowsIdx).toBeGreaterThan(scrollRowsIdx);- expect(persistentRestoreIdx).toBeGreaterThan(persistentRowsIdx);- expect(persistentMoreIdx).toBeGreaterThan(persistentRestoreIdx);+ const persistentMoreIdx = topNavSource.indexOf('!customizing && customizeRow', persistentRowsIdx);+ expect(persistentMoreIdx).toBeGreaterThan(persistentRowsIdx);const railStart = topNavSource.indexOf('export function SidebarRailNavigation');const railTilesIdx = topNavSource.indexOf('variant="rail" />', railStart);- const railRestoreIdx = topNavSource.indexOf(- '<GhostPanelRestoreEntry variant="rail"',- railTilesIdx,- );- const railMoreIdx = topNavSource.indexOf('<SidebarNavigationMoreMenu', railRestoreIdx);+ const railMoreIdx = topNavSource.indexOf('<SidebarNavigationMoreMenu', railTilesIdx);expect(railStart).toBeGreaterThanOrEqual(0);expect(railTilesIdx).toBeGreaterThan(railStart);- expect(railRestoreIdx).toBeGreaterThan(railTilesIdx);- expect(railMoreIdx).toBeGreaterThan(railRestoreIdx);+ expect(railMoreIdx).toBeGreaterThan(railTilesIdx);});// 2026-08-12 用户反馈:滚动后首行紧贴固定的「新建」被硬切、露出半截字。diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsxdeleted file mode 100644index 5f0f7243ec..0000000000--- a/apps/desktop/src/renderer/cindy-brain/GhostPanelBubbleLayer.tsx+++ /dev/null@@ -1,458 +0,0 @@-/**- * GhostPanelBubbleLayer —— 最小化插件面板的浮动气泡层(安卓聊天气泡式)。- *- * 挂在 MainLayout(GhostMediaLightboxHost 旁),portal 到 document.body:- * - 形态(2026-07-31 Lizi 定案,取代此前「1 个直渲单气泡 / ≥2 合并堆叠」- * 双形态):只要有 ≥1 个「已装 && 启用 && 停靠形态 && 已最小化 && 未抽离- * 独立窗」的插件,就渲染**一枚**幽灵球(lucide Ghost 脸 + 数量角标),- * 不再按数量分形态。点球纵向展开各插件自己的气泡(向下,空间不够则- * 向上),点谁恢复谁的面板;点球或空白处收拢。全部面板都开着(没有- * 最小化的)整层消失 —— 幽灵球只在有面板可恢复且用户选择气泡入口时在场。- * - 子气泡脸 = 插件图标(InstalledGhost.iconDataUrl,主窗拿不到- * cindy-ghost://,data URL 直接 <img>;缺图标兜底 lucide Ghost);- * - 定位用 left/top 而非 transform(2026-07-31 Lizi 实测:草稿页气泡拖- * 不动):Electron 的 -webkit-app-region 命中区按**布局矩形**计算、不跟随- * CSS transform(ChromeActions.tsx 同坑)。气泡浮在窗口拖拽区上(如- * 草稿页 InvisibleWindowDragStrip 叠在页签条下,覆盖到窗口 36~86px,- * 正好压住默认停靠位)时 pointerdown 会被系统当成拖窗吞掉;修法是气泡- * 自身标 no-drag 挖洞,而挖洞矩形要与视觉位置一致就必须用 left/top 定位- * ——fixed 定位的 48px 元素改 left/top 重排范围只有自身,热路径可接受;- * - 拖拽仍走 PanelDragController 的性能口径:热路径零 React,直改 DOM- * (left/top);拖动期间挂 body.resizing-pane 让 webview 指针穿透;4px- * 阈值区分点击与拖动(windowDrag.tsx 同款);- * - 动效时序(2026-07-25 Lizi 定案"两段都要有戏"):收起 → 面板宽度先- * 折叠到 0,等 300ms 圆圈渐显、幽灵再跳进来;点子气泡展开 → 幽灵先跳走、- * 圆圈再渐隐,计时器到点(260ms)才真正 restore,面板宽度展开回停靠位- * (编排见 globals.css;面板侧提交时序在 ghostPanels.tsx,减弱动效自动停);- * - 幽灵球可拖,落点独立持久化,重启保留;没拖过默认停右上角(默认位让开- * 顶部拖动带);渲染时 clamp 到视口,四边同 EDGE_MARGIN、顶部无额外下限 ——- * 手拖可停窗内任意位置(2026-08-01 Lizi 定案);展开期间拖球,子气泡跟着- * 实时走(同一条零 React 热路径直改子气泡 DOM,排布算式 stackChildPos- * 与渲染共用)。- */--import { useEffect, useRef, useState, type ReactNode, type RefObject } from 'react';-import { createPortal } from 'react-dom';-import { Ghost } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import type { GhostManifest } from '../../shared/ghost';-import { installedGhostStoragePart } from '../../shared/pluginIdentity';-import { WINDOW_NO_DRAG_STYLE } from '../components/layout/windowDrag';-import { restoreGhostPanel } from '../lib/ghostPanelBubbleState';-import { useGhostPanelRestoreMode } from '../hooks/useGhostPanelRestoreMode';-import { useMinimizedGhostPanels } from './useMinimizedGhostPanels';--const BUBBLE_SIZE = 48;-const EDGE_MARGIN = 12;-const STACK_GAP = 8;-const DRAG_THRESHOLD_PX = 4;-/** 没拖过的球的默认顶部偏移:顶部 46px 是窗口拖动带(§6 规则 3),默认位不占它。- * 仅作用于默认位 —— 用户手拖不受此限,见 clampToViewport。 */-const DEFAULT_TOP = 46 + EDGE_MARGIN;-/** 点子气泡展开:幽灵跳走(160ms)+ 圆圈渐隐(120ms 延迟 + 140ms)的总时长,- * 到点才真正 restore(与 globals.css 的 exit 编排对齐)。 */-const EXIT_MS = 260;--/** 幽灵球落点的独立持久化键(不进 ghostPanelBubbleState:那张表按 ghostId- * 归属、由已装清单 reconcile,塞保留键会被当孤儿清掉)。 */-const STACK_POS_KEY = 'xdt:ghostPanelBubbleStack:v1';--function loadStackPos(): { x: number; y: number } | null {- try {- const raw = window.localStorage.getItem(STACK_POS_KEY);- if (!raw) return null;- const parsed = JSON.parse(raw) as { x?: unknown; y?: unknown };- if (!Number.isFinite(parsed?.x) || !Number.isFinite(parsed?.y)) return null;- return { x: Math.round(parsed.x as number), y: Math.round(parsed.y as number) };- } catch {- return null;- }-}--function saveStackPos(x: number, y: number): void {- try {- window.localStorage.setItem(STACK_POS_KEY, JSON.stringify({ x, y }));- } catch {- // 持久化失败不拦交互(隐私模式等),内存态照常生效- }-}--/** 视口 clamp(渲染与落点共用;存储里不 clamp,换屏不破坏存值)。- * 四边同一条 EDGE_MARGIN,顶部不再额外设下限 —— 幽灵球可停在窗内任意位置,- * 只要四边不出窗(2026-08-01 Lizi 定案,取代此前"y 下限 = 顶部拖动带下沿");- * 停进顶部拖动带时,可点性由气泡自身的 no-drag 挖洞保证(见文件头),代价是- * 被盖住的那 48px 不再能拖窗。 */-function clampToViewport(x: number, y: number): { x: number; y: number } {- const maxX = Math.max(EDGE_MARGIN, window.innerWidth - BUBBLE_SIZE - EDGE_MARGIN);- const maxY = Math.max(EDGE_MARGIN, window.innerHeight - BUBBLE_SIZE - EDGE_MARGIN);- return {- x: Math.min(maxX, Math.max(EDGE_MARGIN, x)),- y: Math.min(maxY, Math.max(EDGE_MARGIN, y)),- };-}--/** 没拖过的幽灵球默认位:右上角(2026-07-31 Lizi 定案由右下角改到右上角,- * DEFAULT_TOP 让开窗口拖动带 —— 只是默认位的取值,不构成拖动下限)。 */-function defaultPosition(): { x: number; y: number } {- return { x: window.innerWidth - BUBBLE_SIZE - EDGE_MARGIN, y: DEFAULT_TOP };-}--/** 直改 DOM 落位(拖拽热路径与基准位回写共用):left/top 而非 transform ——- * no-drag 挖洞矩形按布局算,必须与视觉位置一致(见文件头)。 */-function placeBubbleEl(el: HTMLButtonElement, x: number, y: number): void {- el.style.left = `${x}px`;- el.style.top = `${y}px`;-}--/** 展开的子气泡位:锚点(幽灵球)下方放得下全部就向下排,否则向上;- * React 渲染与拖动热路径共用同一套算式,拖到哪儿子气泡就排到哪儿。 */-function stackChildPos(- anchor: { x: number; y: number },- index: number,- count: number,-): { x: number; y: number } {- const step = BUBBLE_SIZE + STACK_GAP;- // 两头都放不下时 clamp 兜底,极小窗口下允许压边,不做更复杂的绕排。- const fitsDown = anchor.y + step * count + BUBBLE_SIZE + EDGE_MARGIN <= window.innerHeight;- return clampToViewport(anchor.x, anchor.y + (fitsDown ? 1 : -1) * step * (index + 1));-}--/**- * 幽灵球拖拽:热路径零 React,left/top 直改 DOM;4px 阈值区分点击与拖动;- * 拖后第一次合成 click 由 consumeDraggedClick 吞掉。- * onMove 在每步拖动(及取消回滚)时带当前坐标回调,供联动子气泡。- */-function useBubbleDrag({- elRef,- pos,- onDrop,- onMove,-}: {- elRef: RefObject<HTMLButtonElement | null>;- pos: { x: number; y: number };- onDrop: (x: number, y: number) => void;- onMove?: (x: number, y: number) => void;-}) {- const dragRef = useRef<{- pointerId: number;- startClientX: number;- startClientY: number;- baseX: number;- baseY: number;- dragging: boolean;- lastX: number;- lastY: number;- } | null>(null);- const draggedRef = useRef(false);-- // 基准位变化(store 更新/默认位重排/窗口缩放)时回写 left/top ——- // 非拖动期间落位完全由 React 渲染值决定。- useEffect(() => {- const el = elRef.current;- if (el && !dragRef.current?.dragging) placeBubbleEl(el, pos.x, pos.y);- }, [elRef, pos.x, pos.y]);-- const endDragCleanup = () => {- document.body.classList.remove('resizing-pane');- document.body.style.userSelect = '';- };-- const onPointerDown = (e: React.PointerEvent<HTMLButtonElement>) => {- if (e.button !== 0 || dragRef.current) return;- dragRef.current = {- pointerId: e.pointerId,- startClientX: e.clientX,- startClientY: e.clientY,- baseX: pos.x,- baseY: pos.y,- dragging: false,- lastX: pos.x,- lastY: pos.y,- };- // jsdom 没有 setPointerCapture,包一层照常走点击/拖动逻辑。- try {- elRef.current?.setPointerCapture(e.pointerId);- } catch {- /* noop */- }- };-- const onPointerMove = (e: React.PointerEvent<HTMLButtonElement>) => {- const d = dragRef.current;- if (!d || e.pointerId !== d.pointerId) return;- const dx = e.clientX - d.startClientX;- const dy = e.clientY - d.startClientY;- if (!d.dragging) {- if (Math.hypot(dx, dy) < DRAG_THRESHOLD_PX) return;- d.dragging = true;- // webview 指针穿透 + 禁选中(与拖缝/拖面板同款方案)。- document.body.classList.add('resizing-pane');- document.body.style.userSelect = 'none';- }- const next = clampToViewport(d.baseX + dx, d.baseY + dy);- d.lastX = next.x;- d.lastY = next.y;- const el = elRef.current;- if (el) placeBubbleEl(el, next.x, next.y);- onMove?.(next.x, next.y);- };-- const finishDrag = (persist: boolean) => {- const d = dragRef.current;- if (!d) return;- dragRef.current = null;- try {- elRef.current?.releasePointerCapture(d.pointerId);- } catch {- /* noop */- }- if (!d.dragging) return; // 纯点击:等 onClick 走各自的激活时序- endDragCleanup();- draggedRef.current = true; // 吞掉随后的合成 click- if (persist) {- onDrop(d.lastX, d.lastY);- } else {- // 取消:回滚到拖前基准位(子气泡也一并滚回去)- const el = elRef.current;- if (el) placeBubbleEl(el, d.baseX, d.baseY);- onMove?.(d.baseX, d.baseY);- }- };-- /** 拖后紧随的合成 click 返回 true(调用方直接吞掉)。 */- const consumeDraggedClick = (): boolean => {- if (draggedRef.current) {- draggedRef.current = false;- return true;- }- return false;- };-- return { onPointerDown, onPointerMove, finishDrag, consumeDraggedClick };-}--interface BubbleProps {- manifest: GhostManifest;- instanceId: string;- iconDataUrl: string | undefined;- /** 渲染基准位(已按锚点排布 + clamp)。 */- pos: { x: number; y: number };- /** 把气泡按钮元素登记给上层(拖幽灵球时热路径直改子气泡落位用)。 */- registerEl?: (el: HTMLButtonElement | null) => void;-}--/** 展开出的子气泡:不可拖(位置由幽灵球锚定),点击恢复对应面板。 */-function Bubble({ manifest, instanceId, iconDataUrl, pos, registerEl }: BubbleProps): ReactNode {- const { t } = useTranslation();- const [imgBroken, setImgBroken] = useState(false);- /** 点击后进入"缩没退场"态:播 .ghost-bubble-exit,计时器到点才 restore。 */- const [exiting, setExiting] = useState(false);- const exitTimerRef = useRef(0);-- // 卸载时清退场计时器(restore 本身是 store 调用,晚到也无害,但别留悬垂)。- useEffect(() => () => window.clearTimeout(exitTimerRef.current), []);-- const onClick = () => {- if (exiting) return;- // 展开的"过程感":幽灵先跳走、圆圈再渐隐(共 EXIT_MS),到点才真正恢复- // 面板(面板侧再接宽度展开,见 ghostPanels.tsx 的 ghost-panel-enter)。- setExiting(true);- exitTimerRef.current = window.setTimeout(() => restoreGhostPanel(instanceId), EXIT_MS);- };-- const name = manifest.panel?.title ?? manifest.name;- return (- <button- ref={(el) => registerEl?.(el)}- type="button"- data-testid={`ghost-panel-bubble-${instanceId}`}- data-ghost-bubble-layer- aria-label={t('ghostPanelBubble.restoreAria', { name })}- title={t('ghostPanelBubble.restoreAria', { name })}- onClick={onClick}- // 按钮本体只管位置(left/top)与命中区,不带视觉——圆圈(描边/底色/- // 阴影)与幽灵分层,动画各编各的(见 globals.css 悬浮球一节)。- // 描边四轮定(2026-07-25 Lizi):border-default 太浅 → accent-emphasis- // 太深 → text-tertiary 中间档(亮色中灰/暗色中灰);2px 太粗 → 1px。- className={`ghost-bubble group fixed z-[9900] flex h-12 w-12 cursor-pointer items-center justify-center ${- exiting ? 'ghost-bubble-exit' : 'ghost-bubble-enter'- }`}- style={{ left: pos.x, top: pos.y, ...WINDOW_NO_DRAG_STYLE }}- >- <span- aria-hidden- className="ghost-bubble-circle absolute inset-0 rounded-full border border-[var(--text-tertiary)] bg-[var(--surface-elevated)] shadow-xl transition-colors group-hover:bg-[var(--surface-chip)]"- />- <span className="ghost-bubble-face-jump relative flex items-center justify-center">- {iconDataUrl && !imgBroken ? (- <img- src={iconDataUrl}- alt=""- draggable={false}- className="h-8 w-8 rounded-full object-cover"- onError={() => setImgBroken(true)}- />- ) : (- <span className="ghost-bubble-face inline-flex">- <Ghost size={22} className="text-[var(--text-primary)]" />- </span>- )}- </span>- </button>- );-}--/** 幽灵球:气泡模式下被最小化面板的聚合入口(Ghost 脸 + 数量角标)。 */-function StackBubble({- count,- pos,- expanded,- onToggle,- onDrop,- onDragMove,-}: {- count: number;- pos: { x: number; y: number };- expanded: boolean;- onToggle: () => void;- onDrop: (x: number, y: number) => void;- /** 拖动每步回调当前锚点(展开中的子气泡跟着实时走)。 */- onDragMove?: (x: number, y: number) => void;-}): ReactNode {- const { t } = useTranslation();- const elRef = useRef<HTMLButtonElement | null>(null);- const drag = useBubbleDrag({ elRef, pos, onDrop, onMove: onDragMove });- const label = expanded- ? t('ghostPanelBubble.stackCollapseAria')- : t('ghostPanelBubble.stackExpandAria', { count });- return (- <button- ref={elRef}- type="button"- data-testid="ghost-panel-bubble-stack"- data-ghost-bubble-layer- aria-label={label}- title={label}- aria-expanded={expanded}- onPointerDown={drag.onPointerDown}- onPointerMove={drag.onPointerMove}- onPointerUp={() => drag.finishDrag(true)}- onPointerCancel={() => drag.finishDrag(false)}- onClick={() => {- if (drag.consumeDraggedClick()) return;- onToggle();- }}- className="ghost-bubble ghost-bubble-enter group fixed z-[9900] flex h-12 w-12 cursor-pointer items-center justify-center"- style={{ left: pos.x, top: pos.y, ...WINDOW_NO_DRAG_STYLE }}- >- <span- aria-hidden- className="ghost-bubble-circle absolute inset-0 rounded-full border border-[var(--text-tertiary)] bg-[var(--surface-elevated)] shadow-xl transition-colors group-hover:bg-[var(--surface-chip)]"- />- <span className="relative flex items-center justify-center">- <Ghost size={22} className="text-[var(--text-primary)]" />- </span>- {/* 数量角标:语义 token 灰阶,不引新强调色(与图钉同纪律)。 */}- <span- aria-hidden- className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full border border-[var(--text-tertiary)] bg-[var(--surface-chip)] px-1 text-10 font-medium leading-none text-[var(--text-secondary)]"- >- {count}- </span>- </button>- );-}--/** 气泡层:没有最小化面板时不渲染;窗口缩放防抖重渲以重算 clamp/默认位。 */-export function GhostPanelBubbleLayer(): ReactNode {- const { mode } = useGhostPanelRestoreMode();- const minimized = useMinimizedGhostPanels();- // 展开态(纯运行时,不落盘;落盘会让"重启后自动摊开一排"变成惊吓)。- const [expanded, setExpanded] = useState(false);- const [stackPos, setStackPos] = useState<{ x: number; y: number } | null>(() => loadStackPos());- // 展开中的子气泡元素表(拖幽灵球时热路径直改落位,不走 React)。- const childElsRef = useRef(new Map<string, HTMLButtonElement>());-- const [, setResizeTick] = useState(0);- useEffect(() => {- let timer = 0;- const onResize = () => {- window.clearTimeout(timer);- timer = window.setTimeout(() => setResizeTick((v) => v + 1), 100);- };- window.addEventListener('resize', onResize);- return () => {- window.clearTimeout(timer);- window.removeEventListener('resize', onResize);- };- }, []);-- const empty = mode !== 'bubble' || minimized.length === 0;-- // 整层退场(全部面板都开着)时收拢,防下次出现直接摊开一排。- useEffect(() => {- if (empty) setExpanded(false);- }, [empty]);-- // 展开期间点空白处收拢(气泡都带 data-ghost-bubble-layer;capture 期判定,- // 不干扰气泡自身的点击/拖拽)。- useEffect(() => {- if (empty || !expanded) return;- const onPointerDown = (e: PointerEvent) => {- const target = e.target;- if (target instanceof Element && target.closest('[data-ghost-bubble-layer]')) return;- setExpanded(false);- };- document.addEventListener('pointerdown', onPointerDown, true);- return () => document.removeEventListener('pointerdown', onPointerDown, true);- }, [empty, expanded]);-- if (empty) return null;-- const anchor = clampToViewport(- stackPos?.x ?? defaultPosition().x,- stackPos?.y ?? defaultPosition().y,- );- // 拖幽灵球的每一步把展开中的子气泡一起带走(同一条零 React 热路径)。- const onStackDragMove = (x: number, y: number) => {- minimized.forEach((g, index) => {- const el = childElsRef.current.get(installedGhostStoragePart(g));- if (!el) return;- const p = stackChildPos({ x, y }, index, minimized.length);- placeBubbleEl(el, p.x, p.y);- });- };- return createPortal(- <>- <StackBubble- count={minimized.length}- pos={anchor}- expanded={expanded}- onToggle={() => setExpanded((v) => !v)}- onDrop={(x, y) => {- saveStackPos(x, y);- setStackPos({ x, y });- }}- onDragMove={onStackDragMove}- />- {expanded- ? minimized.map((g, index) => (- <Bubble- key={installedGhostStoragePart(g)}- manifest={g.manifest}- instanceId={installedGhostStoragePart(g)}- iconDataUrl={g.iconDataUrl}- pos={stackChildPos(anchor, index, minimized.length)}- registerEl={(el) => {- const id = installedGhostStoragePart(g);- if (el) childElsRef.current.set(id, el);- else childElsRef.current.delete(id);- }}- />- ))- : null}- </>,- document.body,- );-}diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPanelRestoreEntry.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPanelRestoreEntry.tsxdeleted file mode 100644index 2e7404cb86..0000000000--- a/apps/desktop/src/renderer/cindy-brain/GhostPanelRestoreEntry.tsx+++ /dev/null@@ -1,138 +0,0 @@-import { useState, type ReactNode } from 'react';-import { Ghost } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';-import { useGhostPanelRestoreMode } from '@/hooks/useGhostPanelRestoreMode';-import { cn } from '@/lib/utils';-import type { InstalledGhost } from '../../shared/ghost';-import { installedGhostStoragePart } from '../../shared/pluginIdentity';-import { restoreGhostPanel } from '../lib/ghostPanelBubbleState';-import { useMinimizedGhostPanels } from './useMinimizedGhostPanels';--function panelName(ghost: InstalledGhost): string {- return ghost.manifest.panel?.title ?? ghost.manifest.name;-}--function GhostEntryIcon({ ghost, size }: { ghost?: InstalledGhost; size: number }): ReactNode {- const [broken, setBroken] = useState(false);- if (ghost?.iconDataUrl && !broken) {- return (- <img- src={ghost.iconDataUrl}- alt=""- draggable={false}- className="shrink-0 rounded-full object-cover"- style={{ width: size, height: size }}- onError={() => setBroken(true)}- />- );- }- return <Ghost size={size} strokeWidth={1.8} className="shrink-0" aria-hidden />;-}--export function GhostPanelRestoreEntry({- variant,- className,-}: {- variant: 'row' | 'rail';- className?: string;-}): ReactNode {- const { t } = useTranslation();- const { mode } = useGhostPanelRestoreMode();- const minimized = useMinimizedGhostPanels();- if (mode !== 'sidebar' || minimized.length === 0) return null;-- const single = minimized.length === 1 ? minimized[0] : null;- const label = single ? panelName(single) : t('ghostPanelRestore.multiple');- const ariaLabel = single- ? t('ghostPanelRestore.single', { name: label })- : t('ghostPanelRestore.multipleAria', { count: minimized.length });- const content = (- <>- <GhostEntryIcon ghost={single ?? undefined} size={variant === 'rail' ? 18 : 15} />- {variant === 'row' ? (- <>- <span- data-testid="ghost-panel-restore-label"- className="min-w-0 flex-1 truncate text-left leading-none"- >- {label}- </span>- {minimized.length > 1 ? (- <span- data-testid="ghost-panel-restore-count"- aria-hidden- className="flex h-4 min-w-4 items-center justify-center rounded-full bg-[var(--surface-chip)] px-1 text-10 font-medium leading-none text-[var(--text-secondary)]"- >- {minimized.length}- </span>- ) : null}- </>- ) : minimized.length > 1 ? (- <span- aria-hidden- className="absolute right-1 top-1 flex h-4 min-w-4 items-center justify-center rounded-full border border-[var(--text-tertiary)] bg-[var(--surface-chip)] px-1 text-10 font-medium leading-none text-[var(--text-secondary)]"- >- {minimized.length}- </span>- ) : null}- </>- );-- if (single) {- return (- <button- type="button"- data-testid="ghost-panel-restore-entry"- aria-label={ariaLabel}- title={label}- onClick={() => restoreGhostPanel(installedGhostStoragePart(single))}- className={className}- >- {content}- </button>- );- }-- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- data-testid="ghost-panel-restore-entry"- aria-label={ariaLabel}- title={label}- className={cn('relative', className)}- >- {content}- </button>- </DropdownMenuTrigger>- <DropdownMenuContent- side="right"- align="start"- sideOffset={6}- className="min-w-[200px] max-w-[320px]"- >- {minimized.map((ghost) => {- const name = panelName(ghost);- return (- <DropdownMenuItem- key={installedGhostStoragePart(ghost)}- onSelect={() => restoreGhostPanel(installedGhostStoragePart(ghost))}- className="gap-2.5"- >- <GhostEntryIcon ghost={ghost} size={18} />- <span className="min-w-0 flex-1 truncate">{name}</span>- </DropdownMenuItem>- );- })}- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsxdeleted file mode 100644index b5f2b39a09..0000000000--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx+++ /dev/null@@ -1,238 +0,0 @@-// @vitest-environment jsdom-// GhostPanelBubbleLayer:幽灵球单形态(≥1 个最小化即一枚球)/ 展开点子气泡-// 恢复(先缩没后还原)/ 拖后吞点击 / left-top 定位 / detach 隐藏。-import { afterEach, describe, expect, it, vi } from 'vitest';-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';--import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';-import {- __resetGhostPanelBubbleStateForTest,- getGhostPanelBubbleState,- minimizeGhostPanel,-} from '../../lib/ghostPanelBubbleState';-import {- __resetGhostPanelWindowsStateForTest,- __setGhostPanelWindowsStateForTest,-} from '../../lib/ghostPanelWindowState';-import {- __resetGhostPanelRestoreModeForTest,- setGhostPanelRestoreMode,-} from '../../hooks/useGhostPanelRestoreMode';-import { __resetInstalledGhostsStoreForTest } from '../useInstalledGhosts';-import { GhostPanelBubbleLayer } from '../GhostPanelBubbleLayer';--// 仓库同款 i18n mock:t 返回 key(带参拼上,便于断言)。-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, args?: Record<string, unknown>) =>- args ? `${key}:${JSON.stringify(args)}` : key,- }),-}));--function ghost(id: string, enabled = true): InstalledGhost {- const manifest: GhostManifest = {- schemaVersion: 2,- id,- name: `${id} 插件`,- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- panel: { title: `${id} 面板`, html: 'panel.html' },- };- return {- manifest,- dir: `/fake/${id}`,- enabled,- approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },- };-}--function stubGhostsBridge(ghosts: InstalledGhost[]): void {- (window as unknown as { electronAPI: unknown }).electronAPI = {- ghosts: {- listSync: () => ({ ghosts }),- onChanged: () => () => undefined,- },- };-}--afterEach(() => {- cleanup();- __resetGhostPanelBubbleStateForTest();- __resetGhostPanelRestoreModeForTest();- __resetGhostPanelWindowsStateForTest();- __resetInstalledGhostsStoreForTest();- window.localStorage.removeItem('xdt:ghostPanelBubbleStack:v1');- window.localStorage.removeItem('ghostPanel.restoreMode');- delete (window as unknown as { electronAPI?: unknown }).electronAPI;-});--describe('GhostPanelBubbleLayer', () => {- it('只要有 1 个最小化就渲染幽灵球(数量角标 1);没有最小化不渲染', () => {- stubGhostsBridge([ghost('a'), ghost('b')]);- minimizeGhostPanel('a');- render(<GhostPanelBubbleLayer />);- const stack = screen.getByTestId('ghost-panel-bubble-stack');- expect(stack).toBeTruthy();- expect(stack.textContent).toContain('1');- // 单个也不再直渲插件自己的气泡(2026-07-31 定案:不分 1 个还是多个)。- expect(screen.queryByTestId('ghost-panel-bubble-a')).toBeNull();- expect(screen.queryByTestId('ghost-panel-bubble-b')).toBeNull();- });-- it('全部面板都开着(无最小化)整层不渲染', () => {- stubGhostsBridge([ghost('a'), ghost('b')]);- render(<GhostPanelBubbleLayer />);- expect(screen.queryByTestId('ghost-panel-bubble-stack')).toBeNull();- });-- it('选择侧栏恢复入口时不渲染浮动幽灵球', () => {- stubGhostsBridge([ghost('a')]);- minimizeGhostPanel('a');- setGhostPanelRestoreMode('sidebar');- render(<GhostPanelBubbleLayer />);- expect(screen.queryByTestId('ghost-panel-bubble-stack')).toBeNull();- });-- it('点球展开子气泡(aria 带面板名);点子气泡先播缩没退场,到点恢复;最后一个恢复后整层卸载', async () => {- stubGhostsBridge([ghost('a')]);- minimizeGhostPanel('a');- render(<GhostPanelBubbleLayer />);- fireEvent.click(screen.getByTestId('ghost-panel-bubble-stack'));- const childA = screen.getByTestId('ghost-panel-bubble-a');- expect(- screen.getByRole('button', { name: 'ghostPanelBubble.restoreAria:{"name":"a 面板"}' }),- ).toBeTruthy();- fireEvent.click(childA);- // 点击后不是立刻恢复:退场动画窗口内仍处于最小化态- expect(getGhostPanelBubbleState().a?.minimized).toBe(true);- await waitFor(() => {- expect(getGhostPanelBubbleState().a?.minimized).not.toBe(true);- });- await waitFor(() => {- expect(screen.queryByTestId('ghost-panel-bubble-stack')).toBeNull();- });- });-- it('已抽离独立窗口的插件不计入(合并回来自动复现)', () => {- stubGhostsBridge([ghost('a')]);- minimizeGhostPanel('a');- __setGhostPanelWindowsStateForTest({ a: { detached: true, lastOpen: true, open: true } });- const { rerender } = render(<GhostPanelBubbleLayer />);- expect(screen.queryByTestId('ghost-panel-bubble-stack')).toBeNull();- act(() => __setGhostPanelWindowsStateForTest({}));- rerender(<GhostPanelBubbleLayer />);- expect(screen.getByTestId('ghost-panel-bubble-stack')).toBeTruthy();- });-- it('停用的插件不计入', () => {- stubGhostsBridge([ghost('a', false)]);- minimizeGhostPanel('a');- render(<GhostPanelBubbleLayer />);- expect(screen.queryByTestId('ghost-panel-bubble-stack')).toBeNull();- });-- it('多个最小化仍是一枚球(带数量);点子气泡恢复该插件后球和角标还在', async () => {- stubGhostsBridge([ghost('a'), ghost('b')]);- minimizeGhostPanel('a');- minimizeGhostPanel('b');- render(<GhostPanelBubbleLayer />);- const stack = screen.getByTestId('ghost-panel-bubble-stack');- expect(stack.textContent).toContain('2');- fireEvent.click(stack);- const childA = screen.getByTestId('ghost-panel-bubble-a');- expect(childA).toBeTruthy();- expect(screen.getByTestId('ghost-panel-bubble-b')).toBeTruthy();- fireEvent.click(childA);- await waitFor(() => {- expect(getGhostPanelBubbleState().a?.minimized).not.toBe(true);- });- // 只剩 b:球不消失、不再回落单气泡形态,角标变 1。- await waitFor(() => {- expect(screen.queryByTestId('ghost-panel-bubble-a')).toBeNull();- });- expect(screen.getByTestId('ghost-panel-bubble-stack').textContent).toContain('1');- expect(screen.getByTestId('ghost-panel-bubble-b')).toBeTruthy();- });-- it('再点球收拢子气泡;点空白处也收拢', () => {- stubGhostsBridge([ghost('a'), ghost('b')]);- minimizeGhostPanel('a');- minimizeGhostPanel('b');- render(<GhostPanelBubbleLayer />);- const stack = screen.getByTestId('ghost-panel-bubble-stack');- fireEvent.click(stack);- expect(screen.getByTestId('ghost-panel-bubble-a')).toBeTruthy();- fireEvent.click(stack);- expect(screen.queryByTestId('ghost-panel-bubble-a')).toBeNull();- fireEvent.click(stack);- expect(screen.getByTestId('ghost-panel-bubble-a')).toBeTruthy();- fireEvent.pointerDown(document.body);- expect(screen.queryByTestId('ghost-panel-bubble-a')).toBeNull();- });-- it('展开期间拖球:子气泡实时跟走(left/top 直改),松手后保持展开', () => {- stubGhostsBridge([ghost('a'), ghost('b')]);- minimizeGhostPanel('a');- minimizeGhostPanel('b');- render(<GhostPanelBubbleLayer />);- const stack = screen.getByTestId('ghost-panel-bubble-stack');- fireEvent.click(stack);- const childA = screen.getByTestId('ghost-panel-bubble-a');- const childB = screen.getByTestId('ghost-panel-bubble-b');- fireEvent.pointerDown(stack, { button: 0, pointerId: 1, clientX: 500, clientY: 500 });- fireEvent.pointerMove(stack, { pointerId: 1, clientX: 420, clientY: 430 });- // jsdom 视口 1024x768:默认锚点 (964, 58),拖 (-80, -70) → (884, -12),y 被- // clamp 到四边边距 12(顶部无额外下限)→ 锚点 (884, 12),子气泡向下排在- // 68 / 124(还没松手)。- // 落位断言 left/top 而非 transform:app-region 挖洞按布局矩形算,定位- // 必须走布局属性(2026-07-31 草稿页拖不动的修复口径)。- expect((childA as HTMLElement).style.left).toBe('884px');- expect((childA as HTMLElement).style.top).toBe('68px');- expect((childB as HTMLElement).style.left).toBe('884px');- expect((childB as HTMLElement).style.top).toBe('124px');- fireEvent.pointerUp(stack, { pointerId: 1, clientX: 420, clientY: 430 });- fireEvent.click(stack);- // 拖后 click 被吞:展开态不翻转,子气泡还在,且落在与拖动终点一致的位置。- const settledA = screen.getByTestId('ghost-panel-bubble-a') as HTMLElement;- const settledB = screen.getByTestId('ghost-panel-bubble-b') as HTMLElement;- expect(settledA.style.left).toBe('884px');- expect(settledA.style.top).toBe('68px');- expect(settledB.style.left).toBe('884px');- expect(settledB.style.top).toBe('124px');- });-- it('拖动幽灵球:落点持久化到独立键、随后的 click 被吞(不展开)、拖完清理', () => {- stubGhostsBridge([ghost('a'), ghost('b')]);- minimizeGhostPanel('a');- minimizeGhostPanel('b');- render(<GhostPanelBubbleLayer />);- const stack = screen.getByTestId('ghost-panel-bubble-stack');- fireEvent.pointerDown(stack, { button: 0, pointerId: 1, clientX: 500, clientY: 500 });- fireEvent.pointerMove(stack, { pointerId: 1, clientX: 420, clientY: 430 });- fireEvent.pointerUp(stack, { pointerId: 1, clientX: 420, clientY: 430 });- fireEvent.click(stack);- expect(screen.queryByTestId('ghost-panel-bubble-a')).toBeNull(); // 拖后 click 被吞- const raw = window.localStorage.getItem('xdt:ghostPanelBubbleStack:v1');- expect(raw).toBeTruthy();- const parsed = JSON.parse(raw as string) as { x: number; y: number };- expect(Number.isFinite(parsed.x) && Number.isFinite(parsed.y)).toBe(true);- // 往上拖过头只被四边边距 12 拦住(不再卡在顶部拖动带下沿 58):- // 默认位 y=58 + dy(-70) = -12 → 12。- expect(parsed.y).toBe(12);- expect(document.body.classList.contains('resizing-pane')).toBe(false);- });-- it('拖动阈值内的按-放不算拖:随后的 click 正常展开', () => {- stubGhostsBridge([ghost('a')]);- minimizeGhostPanel('a');- render(<GhostPanelBubbleLayer />);- const stack = screen.getByTestId('ghost-panel-bubble-stack');- fireEvent.pointerDown(stack, { button: 0, pointerId: 1, clientX: 500, clientY: 500 });- fireEvent.pointerMove(stack, { pointerId: 1, clientX: 501, clientY: 501 });- fireEvent.pointerUp(stack, { pointerId: 1, clientX: 501, clientY: 501 });- fireEvent.click(stack);- expect(screen.getByTestId('ghost-panel-bubble-a')).toBeTruthy();- expect(window.localStorage.getItem('xdt:ghostPanelBubbleStack:v1')).toBeNull();- });-});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelRestoreEntry.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelRestoreEntry.test.tsxdeleted file mode 100644index 42dc29da79..0000000000--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelRestoreEntry.test.tsx+++ /dev/null@@ -1,107 +0,0 @@-// @vitest-environment jsdom--import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';--import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';-import {- __resetGhostPanelRestoreModeForTest,- setGhostPanelRestoreMode,-} from '../../hooks/useGhostPanelRestoreMode';-import {- __resetGhostPanelBubbleStateForTest,- getGhostPanelBubbleState,- minimizeGhostPanel,-} from '../../lib/ghostPanelBubbleState';-import { __resetGhostPanelWindowsStateForTest } from '../../lib/ghostPanelWindowState';-import { GhostPanelRestoreEntry } from '../GhostPanelRestoreEntry';-import { __resetInstalledGhostsStoreForTest } from '../useInstalledGhosts';--vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, args?: Record<string, unknown>) =>- args ? `${key}:${JSON.stringify(args)}` : key,- }),-}));--function ghost(id: string): InstalledGhost {- const manifest: GhostManifest = {- schemaVersion: 2,- id,- name: `${id} 插件`,- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['panel'],- panel: { title: `${id} 面板`, html: 'panel.html' },- };- return {- manifest,- dir: `/fake/${id}`,- enabled: true,- approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },- };-}--function stubGhostsBridge(ghosts: InstalledGhost[]): void {- (window as unknown as { electronAPI: unknown }).electronAPI = {- ghosts: {- listSync: () => ({ ghosts }),- onChanged: () => () => undefined,- },- };-}--afterEach(() => {- cleanup();- __resetGhostPanelBubbleStateForTest();- __resetGhostPanelRestoreModeForTest();- __resetGhostPanelWindowsStateForTest();- __resetInstalledGhostsStoreForTest();- window.localStorage.removeItem('ghostPanel.restoreMode');- delete (window as unknown as { electronAPI?: unknown }).electronAPI;-});--describe('GhostPanelRestoreEntry', () => {- it('气泡模式或没有最小化面板时不占侧栏位置', () => {- stubGhostsBridge([ghost('a')]);- minimizeGhostPanel('a');- const view = render(<GhostPanelRestoreEntry variant="row" />);- expect(screen.queryByTestId('ghost-panel-restore-entry')).toBeNull();-- act(() => setGhostPanelRestoreMode('sidebar'));- const trigger = screen.getByTestId('ghost-panel-restore-entry');- expect(screen.getByTestId('ghost-panel-restore-label').textContent).toBe('a 面板');- expect(trigger.getAttribute('title')).toBe('a 面板');- expect(trigger.getAttribute('aria-label')).toContain('ghostPanelRestore.single');-- act(() => {- fireEvent.click(trigger);- });- expect(getGhostPanelBubbleState().a?.minimized).not.toBe(true);- expect(screen.queryByTestId('ghost-panel-restore-entry')).toBeNull();- view.unmount();- });-- it('多个面板显示聚合入口并从菜单恢复指定面板', () => {- stubGhostsBridge([ghost('a'), ghost('b')]);- minimizeGhostPanel('a');- minimizeGhostPanel('b');- setGhostPanelRestoreMode('sidebar');- render(<GhostPanelRestoreEntry variant="row" />);-- const trigger = screen.getByTestId('ghost-panel-restore-entry');- expect(screen.getByTestId('ghost-panel-restore-label').textContent).toBe(- 'ghostPanelRestore.multiple',- );- expect(screen.getByTestId('ghost-panel-restore-label').className).toContain('text-left');- expect(screen.getByTestId('ghost-panel-restore-count').textContent).toBe('2');- expect(trigger.getAttribute('title')).toBe('ghostPanelRestore.multiple');- expect(trigger.getAttribute('aria-label')).toContain('"count":2');- fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });- fireEvent.click(screen.getByText('a 面板'));-- expect(getGhostPanelBubbleState().a?.minimized).not.toBe(true);- expect(getGhostPanelBubbleState().b?.minimized).toBe(true);- });-});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsxindex 922c54d29f..c1c3fc9da4 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx@@ -1,361 +1,135 @@// @vitest-environment jsdom-import { afterEach, describe, expect, it, vi } from 'vitest';-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';--import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';-import {- ghostInstallApprovalToken,- type GhostManifest,- type InstalledGhost,-} from '../../../shared/ghost';-import {- __resetGhostPanelBubbleStateForTest,- getGhostPanelBubbleState,- minimizeGhostPanel,-} from '../../lib/ghostPanelBubbleState';-import {- __resetPanelRegistryForTest,- getPanelKind,- hasPanelKind,- listPanelKinds,-} from '../../panels/registry';+/**+ * 测试价值+ * - 生产入口与可观察结果:syncGhostPanelRegistrations(启动首帧 / ghosts:changed 的唯一同步点)+ * 与 globalTabs 的 reconcile;可观察的是右侧栏全局页签列表:声明停靠面板的已启用插件+ * 自动出现、用户关掉后不再自动加回、卸载即清、停用保留页签数据、`tab` 形态与无面板插件+ * 不进右侧栏。+ * - Bug / 规则依据:plugin-security-and-authoring.md §5 存量插件兼容红线——停靠面板从布局树+ * 迁到右侧栏全局页签后,升级前已启用的 `panel` 插件升级后必须自动出现,用户什么都不做。+ * - 现有覆盖缺口:原停靠面板注册表用例随面板退场删除;新迁移路径此前无覆盖。+ * - 最小失败输入:一个 enabled 且 panel.position 缺省的插件 + 一次 sync。+ * - tier:unit(jsdom localStorage)。+ */++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';import {- __resetGhostPanelsForTest,- ensureGhostPanelsRegistered,- pickGhostPanelMediaUri,- syncGhostPanelRegistrations,-} from '../ghostPanels';-import { __resetInstalledGhostsStoreForTest } from '../useInstalledGhosts';--// 仓库同款 i18n mock:t 返回 key(带参拼上,便于断言)。-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, args?: Record<string, unknown>) =>- args ? `${key}:${JSON.stringify(args)}` : key,- }),-}));--// 面板体是 webview 供片,jsdom 渲不了也不该渲 —— 置空,只测宿主壳(标准头/关闭链路)。-vi.mock('../ghostPanelBody', async (importOriginal) => ({- ...(await importOriginal<typeof import('../ghostPanelBody')>()),- GhostChipPanelBody: ({ ghost: installed }: { ghost: InstalledGhost }) => (- <div- data-testid="ghost-body"- data-dir={installed.dir}- data-approval={ghostInstallApprovalToken(installed.approval)}- />- ),- GhostPanelError: () => null,-}));--/** 造一个已装意识(panel 可覆写/置空;enabled 默认 true)。 */-function ghost(id: string, panel?: GhostManifest['panel'] | null, enabled = true): InstalledGhost {+ __resetGlobalTabsForTest,+ getGlobalTabs,+ removeGlobalTab,+ type PluginViewTabState,+} from '../../features/right-sidebar/globalTabs';+import { pickGhostPanelMediaUri, syncGhostPanelRegistrations } from '../ghostPanels';++function ghost(+ id: string,+ opts: {+ enabled?: boolean;+ panel?: Partial<GhostManifest['panel']> | null;+ mainView?: boolean;+ } = {},+): InstalledGhost {const manifest: GhostManifest = {schemaVersion: 2,id,- name: `${id} 意识`,+ name: id,version: '1.0.0',kind: 'chip',entry: 'main.js',- ...(panel === null ? {} : { panel: panel ?? { title: id, html: 'panel.html' } }),- };+ ...(opts.panel === null+ ? {}+ : { panel: { html: 'panel.html', title: `${id} panel`, ...(opts.panel ?? {}) } }),+ ...(opts.mainView ? { mainView: { html: 'main-view.html', title: `${id} view` } } : {}),+ } as GhostManifest;return {manifest,dir: `/fake/${id}`,- enabled,+ enabled: opts.enabled ?? true,approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },- };+ } as InstalledGhost;}-function bridgeGhosts(initial: InstalledGhost[], setEnabled = vi.fn()) {- let roster = initial;- const listeners = new Set<(event: { ghosts: InstalledGhost[] }) => void>();- const api = {- setEnabled,- listSync: vi.fn(() => ({ ghosts: roster })),- onChanged: vi.fn((listener: (event: { ghosts: InstalledGhost[] }) => void) => {- listeners.add(listener);- return () => listeners.delete(listener);- }),- change(next: InstalledGhost[]) {- roster = next;- listeners.forEach((listener) => listener({ ghosts: next }));- },- };- (window as unknown as { electronAPI: unknown }).electronAPI = { ghosts: api };- return api;-}+const instanceIds = () =>+ getGlobalTabs().map((tab) => (tab.state as PluginViewTabState).instanceId);-afterEach(() => {- cleanup();- __resetPanelRegistryForTest();- __resetGhostPanelsForTest();- __resetInstalledGhostsStoreForTest();- __resetGhostPanelBubbleStateForTest();- delete (window as unknown as { electronAPI?: unknown }).electronAPI;+beforeEach(() => {+ window.localStorage.clear();+ __resetGlobalTabsForTest();});-describe('syncGhostPanelRegistrations · 注册表与已装清单对齐', () => {- it('装入的意识面板进注册表;无面板声明的意识不进', () => {- syncGhostPanelRegistrations([ghost('hello'), ghost('toolonly', null)]);- expect(hasPanelKind('ghost:hello')).toBe(true);- expect(hasPanelKind('ghost:toolonly')).toBe(false);- });-- it('卸下(清单里消失)→ 注销;其余不动', () => {- syncGhostPanelRegistrations([ghost('a'), ghost('b')]);- expect(hasPanelKind('ghost:a')).toBe(true);- syncGhostPanelRegistrations([ghost('b')]);- expect(hasPanelKind('ghost:a')).toBe(false);- expect(hasPanelKind('ghost:b')).toBe(true);- });-- it('清单没变 → 不重注册(组件身份稳定,不触发重挂载)', () => {- syncGhostPanelRegistrations([ghost('a')]);- const before = listPanelKinds().length;- syncGhostPanelRegistrations([ghost('a')]);- expect(listPanelKinds().length).toBe(before);- });+afterEach(() => {+ __resetGlobalTabsForTest();+ window.localStorage.clear();+});- it('全卸光 → 注册表回空', () => {- syncGhostPanelRegistrations([ghost('a'), ghost('b')]);+describe('syncGhostPanelRegistrations · 停靠面板插件自动成为右侧栏全局页签', () => {+ it('声明停靠面板的已启用插件自动加入;tab 形态、无面板、仅 mainView 的插件不自动加', () => {+ syncGhostPanelRegistrations([+ ghost('docked-panel'),+ ghost('tabbed-panel', { panel: { position: 'tab' } }),+ ghost('tool-only', { panel: null }),+ ghost('view-only', { panel: null, mainView: true }),+ ]);+ expect(instanceIds()).toEqual(['docked-panel']);+ // 再同步一次不重复加。+ syncGhostPanelRegistrations([ghost('docked-panel')]);+ expect(instanceIds()).toEqual(['docked-panel']);+ });++ it('用户关掉后不再自动加回;卸载即清掉页签与关闭记录,重装视同首次启用', () => {+ syncGhostPanelRegistrations([ghost('docked-panel')]);+ const [tab] = getGlobalTabs();+ removeGlobalTab(tab.id);+ expect(instanceIds()).toEqual([]);+ syncGhostPanelRegistrations([ghost('docked-panel')]);+ expect(instanceIds()).toEqual([]);++ // 卸载(清单里消失)→ 关闭记录一并清掉。syncGhostPanelRegistrations([]);- expect(hasPanelKind('ghost:a')).toBe(false);- expect(hasPanelKind('ghost:b')).toBe(false);- });-- it.each(['approval', 'directory', 'manifest'] as const)('广播更新 %s 后使用当前实例,不替换面板组件', (field) => {- const installed = ghost('demo');- const api = bridgeGhosts([installed]);- ensureGhostPanelsRegistered();- const Component = getPanelKind('ghost:demo')!.Component;- render(<ConfirmDialogProvider><Component paneId="pane-1" /></ConfirmDialogProvider>);- const updated: InstalledGhost = {- ...installed,- ...(field === 'approval'- ? { approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' } }- : {}),- ...(field === 'directory' ? { dir: '/other/demo' } : {}),- ...(field === 'manifest'- ? { manifest: { ...installed.manifest, panel: { ...installed.manifest.panel!, title: 'updated title' } } }- : {}),- };- act(() => {- syncGhostPanelRegistrations([updated]);- api.change([updated]);- });- expect(getPanelKind('ghost:demo')!.Component).toBe(Component);- expect(screen.getByTestId('ghost-body').getAttribute('data-dir')).toBe(updated.dir);- expect(screen.getByTestId('ghost-body').getAttribute('data-approval'))- .toBe(ghostInstallApprovalToken(updated.approval));- if (field === 'manifest') expect(screen.getByText('updated title')).toBeTruthy();- expect(api.listSync).toHaveBeenCalledTimes(1);- });-- it('同名 root / 组织面板各自消费物理实例,清单移除后不显示旧实例', () => {- const root = { ...ghost('helper'), namespace: null };- const organization = { ...ghost('helper'), namespace: 'acme', dir: '/fake/_ns/acme/helper' };- const api = bridgeGhosts([root, organization]);- ensureGhostPanelsRegistered();- const Root = getPanelKind('ghost:helper')!.Component;- const Organization = getPanelKind('ghost:_ns__acme__helper')!.Component;- render(- <ConfirmDialogProvider>- <Root paneId="root" />- <Organization paneId="organization" />- </ConfirmDialogProvider>,- );- expect(screen.getAllByTestId('ghost-body').map((element) => element.getAttribute('data-dir')))- .toEqual([root.dir, organization.dir]);- act(() => api.change([root]));- expect(screen.getAllByTestId('ghost-body')).toHaveLength(1);- expect(screen.getByTestId('ghost-body').getAttribute('data-dir')).toBe(root.dir);- expect(api.listSync).toHaveBeenCalledTimes(1);- });-- it('同步时对齐气泡状态:卸载删条目、停用强制还原(不留死角)', () => {- minimizeGhostPanel('gone');- minimizeGhostPanel('disabled');- syncGhostPanelRegistrations([ghost('disabled', undefined, false)]);- const bubbles = getGhostPanelBubbleState();- expect(bubbles.gone).toBeUndefined();- expect(bubbles.disabled?.minimized).not.toBe(true);+ syncGhostPanelRegistrations([ghost('docked-panel')]);+ expect(instanceIds()).toEqual(['docked-panel']);+ });++ it('停用的插件保留页签数据(投影层按可用性隐藏),重新启用原位回来;停用期间不新加', () => {+ syncGhostPanelRegistrations([ghost('ghost-a'), ghost('ghost-b')]);+ expect(instanceIds()).toEqual(['ghost-a', 'ghost-b']);+ syncGhostPanelRegistrations([ghost('ghost-a', { enabled: false }), ghost('ghost-b')]);+ expect(instanceIds()).toEqual(['ghost-a', 'ghost-b']);+ // 从未加入过的停用插件不会被加进来。+ syncGhostPanelRegistrations([+ ghost('ghost-a', { enabled: false }),+ ghost('ghost-b'),+ ghost('ghost-c', { enabled: false }),+ ]);+ expect(instanceIds()).toEqual(['ghost-a', 'ghost-b']);});});describe('pickGhostPanelMediaUri · 右键命中参数挑媒体地址', () => {- const HASH = 'a'.repeat(64);- const MEDIA = `cindy-ghost://art/media/${HASH}.png`;- const PREVIEW = `cindy-ghost://art/preview/${HASH}.mp4`;-+ const uri = (p: string) => `cindy-ghost://my-ghost/${p}`;it('srcURL 优先(直接右键在 img/video 上);linkURL 兜底(视频缩略命中外层 <a>)', () => {- expect(pickGhostPanelMediaUri({ srcURL: MEDIA, linkURL: PREVIEW }, 'art')).toBe(MEDIA);- expect(pickGhostPanelMediaUri({ srcURL: '', linkURL: PREVIEW }, 'art')).toBe(PREVIEW);- });-- it('非媒体 cell(普通元素/外部地址)返回 null,不弹菜单', () => {- expect(pickGhostPanelMediaUri({}, 'art')).toBeNull();- expect(pickGhostPanelMediaUri({ srcURL: 'https://evil.example/x.png' }, 'art')).toBeNull();- expect(pickGhostPanelMediaUri({ linkURL: `cindy-ghost://art/gallery` }, 'art')).toBeNull();- });-- it('只认本面板意识 id 前缀,别的意识地址不弹', () => {- expect(pickGhostPanelMediaUri({ srcURL: MEDIA }, 'other')).toBeNull();- });-- it('多级路径 / query 形状拒绝(严校验仍在 main 闸,这里是粗筛)', () => {- expect(pickGhostPanelMediaUri({ srcURL: `cindy-ghost://art/media/../${HASH}.png` }, 'art')).toBeNull();- expect(pickGhostPanelMediaUri({ srcURL: `${MEDIA}?x=1` }, 'art')).toBeNull();- });-});--describe('syncGhostPanelRegistrations · 停用即休眠', () => {- it('停用的意识不注册面板;重新启用后同一条对齐路径复活', () => {- syncGhostPanelRegistrations([ghost('a', undefined, false)]);- expect(hasPanelKind('ghost:a')).toBe(false);- syncGhostPanelRegistrations([ghost('a', undefined, true)]);- expect(hasPanelKind('ghost:a')).toBe(true);- });-- it('运行中停用 → 已注册的面板被注销', () => {- syncGhostPanelRegistrations([ghost('a')]);- expect(hasPanelKind('ghost:a')).toBe(true);- syncGhostPanelRegistrations([ghost('a', undefined, false)]);- expect(hasPanelKind('ghost:a')).toBe(false);- });-});--describe('GhostPanel · 标准头关闭按钮(二次确认后停用插件)', () => {- function renderPanel(- setEnabled: ReturnType<typeof vi.fn>,- installed = ghost('demo'),- otherGhosts: InstalledGhost[] = [],- ) {- const api = bridgeGhosts([installed, ...otherGhosts], setEnabled);- syncGhostPanelRegistrations([installed, ...otherGhosts]);- const def = getPanelKind('ghost:demo');- if (!def) throw new Error('面板未注册');- const Component = def.Component;- const view = render(- <ConfirmDialogProvider>- <Component paneId="pane-1" />- </ConfirmDialogProvider>,+ expect(+ pickGhostPanelMediaUri(+ { srcURL: uri('media/a.png'), linkURL: uri('media/b.mp4') },+ 'my-ghost',+ ),+ ).toBe(uri('media/a.png'));+ expect(pickGhostPanelMediaUri({ srcURL: '', linkURL: uri('preview/b.mp4') }, 'my-ghost')).toBe(+ uri('preview/b.mp4'),);- return { api, view };- }-- it('点关闭 → 弹确认框;确认后 setEnabled(id, false)', async () => {- const setEnabled = vi.fn().mockResolvedValue({ ok: true });- renderPanel(setEnabled);- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- // 确认框标题带插件名(t mock 把插值参数拼在 key 后)。- await screen.findByText('ghostPanel.disableConfirm.title:{"name":"demo 意识"}');- expect(setEnabled).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: 'ghostPanel.disableConfirm.confirm' }));- await waitFor(() => expect(setEnabled).toHaveBeenCalledWith('demo', false, ghostInstallApprovalToken(ghost('demo').approval)));- expect(setEnabled).toHaveBeenCalledTimes(1);- });-- it('点关闭后取消 → 不停用', async () => {- const setEnabled = vi.fn().mockResolvedValue({ ok: true });- renderPanel(setEnabled);- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- await screen.findByText('ghostPanel.disableConfirm.title:{"name":"demo 意识"}');- fireEvent.click(screen.getByRole('button', { name: 'commonUi.confirmDialog.cancel' }));- await waitFor(() =>- expect(- screen.queryByText('ghostPanel.disableConfirm.title:{"name":"demo 意识"}'),- ).toBeNull(),- );- expect(setEnabled).not.toHaveBeenCalled();- });-- it('原实例卸载后取消旧确认,不关闭仍在场的组织同名实例', async () => {- const setEnabled = vi.fn().mockResolvedValue({ ok: true });- const organization = { ...ghost('demo'), namespace: 'acme', dir: '/fake/_ns/acme/demo' };- const { api } = renderPanel(setEnabled, { ...ghost('demo'), namespace: null }, [organization]);- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- const staleConfirm = await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });-- act(() => api.change([organization]));-- await waitFor(() => expect(screen.queryByRole('button', { name: 'ghostPanel.disableConfirm.confirm' })).toBeNull());- fireEvent.click(staleConfirm);- expect(setEnabled).not.toHaveBeenCalled();});-- it.each(['approval', 'directory', 'namespace', 'disabled', 'panel'] as const)(- '原实例 %s 变更后取消旧确认,新确认仍可用',- async (field) => {- const setEnabled = vi.fn().mockResolvedValue({ ok: true });- const installed = ghost('demo');- const { api } = renderPanel(setEnabled, installed);- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- const staleConfirm = await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });- const updated: InstalledGhost = {- ...installed,- ...(field === 'approval' ? { approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' } } : {}),- ...(field === 'directory' ? { dir: '/other/demo' } : {}),- ...(field === 'namespace' ? { namespace: 'acme' } : {}),- ...(field === 'disabled' ? { enabled: false } : {}),- ...(field === 'panel' ? { manifest: { ...installed.manifest, panel: { html: 'panel.html', position: 'tab' } } } : {}),- };-- act(() => api.change([updated]));-- await waitFor(() => expect(screen.queryByRole('button', { name: 'ghostPanel.disableConfirm.confirm' })).toBeNull());- fireEvent.click(staleConfirm);- expect(setEnabled).not.toHaveBeenCalled();-- if (field === 'disabled' || field === 'panel') act(() => api.change([installed]));- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- fireEvent.click(await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' }));- const confirmed = field === 'disabled' || field === 'panel' ? installed : updated;- await waitFor(() => expect(setEnabled).toHaveBeenCalledExactlyOnceWith('demo', false, ghostInstallApprovalToken(confirmed.approval)));- },- );-- it('面板卸载但全局确认宿主保留时取消旧确认', async () => {- const setEnabled = vi.fn().mockResolvedValue({ ok: true });- const { view } = renderPanel(setEnabled);- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- const staleConfirm = await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });-- view.rerender(<ConfirmDialogProvider><div /></ConfirmDialogProvider>);-- await waitFor(() => expect(screen.queryByRole('button', { name: 'ghostPanel.disableConfirm.confirm' })).toBeNull());- fireEvent.click(staleConfirm);- expect(setEnabled).not.toHaveBeenCalled();- });-- it('安装身份未变化的清单刷新不取消用户确认', async () => {- const setEnabled = vi.fn().mockResolvedValue({ ok: true });- const installed = ghost('demo');- const { api } = renderPanel(setEnabled, installed);- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });-- act(() => api.change([{ ...installed, manifest: { ...installed.manifest } }]));-- fireEvent.click(screen.getByRole('button', { name: 'ghostPanel.disableConfirm.confirm' }));- await waitFor(() => expect(setEnabled).toHaveBeenCalledExactlyOnceWith('demo', false, ghostInstallApprovalToken(installed.approval)));- });-- it.each(['uninstall', 'approval'] as const)('确认恢复前原实例 %s 不执行旧关闭', async (change) => {- const setEnabled = vi.fn().mockResolvedValue({ ok: true });- const installed = ghost('demo');- const { api } = renderPanel(setEnabled, installed);- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- const confirmButton = await screen.findByRole('button', { name: 'ghostPanel.disableConfirm.confirm' });-- await act(async () => {- fireEvent.click(confirmButton);- api.change(change === 'uninstall' ? [] : [{- ...installed,- approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' },- }]);- });-- expect(setEnabled).not.toHaveBeenCalled();+ it('非媒体地址 / 别的意识地址返回 null,不弹菜单', () => {+ expect(+ pickGhostPanelMediaUri({ srcURL: 'https://x/a.png', linkURL: '' }, 'my-ghost'),+ ).toBeNull();+ expect(+ pickGhostPanelMediaUri(+ { srcURL: 'cindy-ghost://other/media/a.png', linkURL: '' },+ 'my-ghost',+ ),+ ).toBeNull();+ expect(pickGhostPanelMediaUri({ srcURL: uri('a.png'), linkURL: '' }, 'my-ghost')).toBeNull();});});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/useMinimizedGhostPanels.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/useMinimizedGhostPanels.test.tsdeleted file mode 100644index 5c449443b0..0000000000--- a/apps/desktop/src/renderer/cindy-brain/__tests__/useMinimizedGhostPanels.test.ts+++ /dev/null@@ -1,71 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';-import { selectMinimizedGhostPanels } from '../useMinimizedGhostPanels';--function ghost(- id: string,- options: { enabled?: boolean; panel?: boolean; position?: 'left' | 'tab' } = {},-): InstalledGhost {- const manifest: GhostManifest = {- schemaVersion: 2,- id,- name: id,- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: options.panel === false ? [] : ['panel'],- ...(options.panel === false- ? {}- : { panel: { html: 'panel.html', position: options.position ?? 'left' } }),- };- return {- manifest,- dir: `/fake/${id}`,- enabled: options.enabled ?? true,- approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },- };-}--describe('selectMinimizedGhostPanels', () => {- it('只返回启用、停靠、已最小化且未抽离的插件面板', () => {- const ghosts = [- ghost('ready'),- ghost('open'),- ghost('disabled', { enabled: false }),- ghost('tab', { position: 'tab' }),- ghost('tool', { panel: false }),- ghost('detached'),- ];-- expect(- selectMinimizedGhostPanels(- ghosts,- {- ready: { minimized: true },- open: { minimized: false },- disabled: { minimized: true },- tab: { minimized: true },- tool: { minimized: true },- detached: { minimized: true },- },- { detached: { detached: true, open: true, lastOpen: true } },- ).map((item) => item.manifest.id),- ).toEqual(['ready']);- });-- it('企业实例按 storage part 认最小化,不和 root 同名抢条目', () => {- const rootGhost = ghost('helper');- const orgGhost = { ...ghost('helper'), namespace: 'acme', dir: '/fake/_ns/acme/helper' };- expect(- selectMinimizedGhostPanels(- [rootGhost, orgGhost],- {- helper: { minimized: false },- '_ns__acme__helper': { minimized: true },- },- {},- ).map((item) => [item.namespace ?? null, item.manifest.id]),- ).toEqual([['acme', 'helper']]);- });-});diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsxindex 5fde640c91..d586d575eb 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx@@ -344,7 +344,7 @@ export function GhostChipPanelBody({* 面板体挂载 = 未读已读(badge 槽的 explicit 清零)。** 清零收在这里而不是各宿主的"打开"动作里:面板体有三个宿主(插件页页签- * GhostPagePanelHost、布局停靠 ghostPanels、独立窗口 GhostPanelWindowLayout),+ * GhostPagePanelHost、右侧栏插件视图页签 plugin-view 及其弹出窗口),* 挂载到本组件才是"内容确实在用户眼前"的唯一判据,三处天然对称。* unread 进依赖:面板**已经开着**时插件又点亮一次(后台拿到新内容),用户* 正看着它,不该留一颗清不掉的点。diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsxindex c38abe2690..baf31fc422 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx@@ -1,264 +1,62 @@-import { useEffect, useRef, useState, type ReactNode } from 'react';-import { useTranslation } from 'react-i18next';+import { useEffect, useState } from 'react';-import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';-import { ghostInstallApprovalToken, ghostPanelKind, type InstalledGhost } from '../../shared/ghost';-import {- installedGhostLogicalIdentity,- installedGhostStoragePart,- pluginStoragePart,-} from '../../shared/pluginIdentity';-import { minimizeGhostPanel, reconcileGhostPanelBubbles } from '../lib/ghostPanelBubbleState';-import { toast } from '../lib/toast';-import { usePanelMaximize } from '../layout/panelMaximize';-import { usePaneAtWindowTop, usePaneFill } from '../layout/panePlacement';-import { usePanelWidth } from '../layout/paneWidths';-import { PanelChrome } from '../panels/PanelChrome';-import {- registerPanelKind,- unregisterPanelKind,- type PanelComponentProps,-} from '../panels/registry';-import { extractIpcError } from '../utils/ipcError';-import { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';-import { ghostInstallErrorKey } from './installErrorKey';+import type { InstalledGhost } from '../../shared/ghost';+import { installedGhostLogicalIdentity, pluginStoragePart } from '../../shared/pluginIdentity';+import { reconcileGlobalPluginTabs } from '../features/right-sidebar/globalTabs';import { pruneGhostSettingsHeights } from './ghostSettingsHeight';-import { useGhostRuntimeState } from './runtimeStates';-import { readInstalledGhostsSnapshot, useInstalledGhosts } from './useInstalledGhosts';+import { readInstalledGhostsSnapshot } from './useInstalledGhosts';import { getDataOwnerGeneration } from '../contexts/dataOwnerGeneration';/**- * 意识面板接入布局引擎。+ * 插件面板与已装清单的同步入口。*- * 数据流(布局与沙箱边界见 docs/dev-rules/architecture-invariants.md / docs/dev-rules/plugin-security-and-authoring.md):- * - 启动:LayoutRoot 首帧前 ensureGhostPanelsRegistered() 同步拉已装清单- * (sendSync)→ 声明了面板的意识逐个注册进面板注册表 —— 与内置面板同帧- * 就位,布局第一帧即完整(设计规范规则 7);- * - 装入:main 侧装好后广播 ghosts:changed → 注册新面板 + 触发重渲;- * 面板停靠(树里加 pane)由 main 侧随 install 完成,走 layout:changed 热更新;- * - 卸下:广播里不见了的 kind 注销 → 布局树里它的 pane 按"未安装意识"隐藏,- * 树数据保留,重装即原位复活(§6 规则 5 的正式生效点)。+ * 停靠形态(`panel.position: 'left'`)的插件面板不再作为独立 pane 挂进主窗布局树,+ * 而是以右侧栏的**全局页签**(不跟对话,切任务不变)承载,见+ * features/right-sidebar/globalTabs.ts 与 plugins/plugin-view。本模块只剩两件事:+ * - 启动首帧前 / `ghosts:changed` 时把全局页签与已装清单对齐(停靠面板自动加入、+ * 卸载即清);+ * - 清理已卸载插件的设置页高度缓存。*- * 面板体(webview 供片/主题注入/崩溃接管/媒体右键)在 ghostPanelBody.tsx,- * 与插件页页签形态(position:'tab',features/plugin/GhostPagePanelHost)共用;本模块只管- * 停靠形态(left / right)与两个注册表的同步入口。+ * 布局树里历史遗留的 `ghost:<id>` pane 继续按「未注册面板」隐藏、数据保留+ * (docs/dev-rules/architecture-invariants.md §3),不再有渲染方。+ * 页签形态(`position: 'tab'`)照旧由插件页独占承载(features/plugin/GhostPagePanelHost)。*/// 兼容既有导入点(测试等):粗筛纯函数随面板体一起搬家,原路径继续可用。export { pickGhostPanelMediaUri } from './ghostPanelBody';/**- * 停靠面板入场动画的"启动首屏豁免窗":凡是这个时刻之后才挂载的 GhostPanel- * (点气泡展开、独立窗合并回来、装入、启用)都播宽度展开(ghost-panel-enter,- * 见 globals.css),不再"先占宽再出现"(2026-07-25 Lizi:出现要丝滑);- * 启动首屏全家同帧就位,不各展各的——本模块在 LayoutRoot 首帧前装载- * (ensureGhostPanelsRegistered 走 sendSync),首屏挂载与模块装载几乎同刻,- * 1.5s 窗口足够宽;极端慢启动多播一次展开也无害。- */-const PANEL_ENTER_ARMED_AT = Date.now() + 1500;-/** 最小化折叠动画时长:与 globals.css 的 ghost-panel-collapse 对齐,- * 到点才真正提交 minimized(随后气泡侧再等 300ms 入场,接力不抢戏)。 */-const PANEL_EXIT_MS = 180;--/** 意识面板宿主:标准头(PanelChrome)+ 沙箱自绘面板体(崩溃时错误接管)。 */-function GhostPanel({- ghost,-}: PanelComponentProps & { ghost: InstalledGhost }): ReactNode {- const { manifest } = ghost;- const instanceId = installedGhostStoragePart(ghost);- const kind = ghostPanelKind(instanceId);- const fillContainer = usePaneFill();- const atWindowTop = usePaneAtWindowTop();- // 宽度由引擎下发(fraction × 可用宽,缝把手可拖);兜底用清单 minWidth。- const width = usePanelWidth(kind) ?? manifest.panel?.minWidth ?? 300;- // 撑满态(引擎视图态):固定宽让位给 flex-1,树上的 fraction 账本不动。- const maximize = usePanelMaximize();- const isMaximized = maximize?.maximizedKind === kind;- // 标准头系统按钮:身份卡可逐个关闭(panel.systemButtons.<键>:false);- // 关闭 = 不把对应入参交给标准头,按钮不长出(标题条本体恒在)。- const maximizeEnabled = manifest.panel?.systemButtons?.maximize !== false;- const detachEnabled = manifest.panel?.systemButtons?.detach !== false;- const minimizeEnabled = manifest.panel?.systemButtons?.minimize !== false;- // 换版更新把按钮关掉时,若面板正撑满,自动还原 —— 否则按钮没了、态出不去。- useEffect(() => {- if (!maximizeEnabled && isMaximized) maximize?.toggle(kind);- }, [maximizeEnabled, isMaximized, maximize, kind]);- // 沙箱崩了 → 面板原地进入错误接管态。- const runtimeState = useGhostRuntimeState(instanceId);- const broken = runtimeState === 'crashed' || runtimeState === 'fused';- // 挂载即定(useState 初始化跑一次):启动首屏后出现的面板播宽度展开。- const [enter] = useState(() => Date.now() >= PANEL_ENTER_ARMED_AT);- // 点最小化 → 先播宽度折叠(closing),计时器到点才真正提交 minimized;- // 减弱动效直接提交;撑满态是 flex-1(宽度动画不生效),也直接提交,- // LayoutRoot 的可见性 effect 会顺手清撑满。- const [closing, setClosing] = useState(false);- const closeTimerRef = useRef(0);- useEffect(() => () => window.clearTimeout(closeTimerRef.current), []);- const beginMinimize = (): void => {- if (closing) return;- const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;- if (reduced || isMaximized) {- minimizeGhostPanel(instanceId);- return;- }- setClosing(true);- closeTimerRef.current = window.setTimeout(() => minimizeGhostPanel(instanceId), PANEL_EXIT_MS);- };- // 标准头「关闭」= 二次确认后停用整个插件(setEnabled false):面板、工具、- // 沙箱一并休眠,与插件页全局开关同一条链路(ghosts:changed 广播回来时- // 本面板经 syncGhostPanelRegistrations 注销,无需自己收尾)。恒在,不受- // 身份卡 systemButtons 控制——它是宿主给用户的退路,不是作者可关的能力。- const { t } = useTranslation();- const { confirm } = useConfirmDialog();- const closeAbortRef = useRef<AbortController | null>(null);- const approvalToken = ghostInstallApprovalToken(ghost.approval);- useEffect(- () => () => closeAbortRef.current?.abort(),- [instanceId, ghost.dir, ghost.namespace, approvalToken],- );- const beginClose = async (): Promise<void> => {- if (closeAbortRef.current) return;- const abort = new AbortController();- closeAbortRef.current = abort;- try {- const approved = await confirm({- title: t('ghostPanel.disableConfirm.title', { name: manifest.name }),- description: t('ghostPanel.disableConfirm.body'),- confirmText: t('ghostPanel.disableConfirm.confirm'),- }, abort.signal);- if (!approved || abort.signal.aborted) return;- const current = readInstalledGhostsSnapshot().find(- (candidate) => installedGhostStoragePart(candidate) === instanceId,- );- if (- !current?.enabled || !current.manifest.panel || current.manifest.panel.position === 'tab' ||- current.dir !== ghost.dir || current.namespace !== ghost.namespace ||- ghostInstallApprovalToken(current.approval) !== approvalToken- ) return;- await window.electronAPI?.ghosts?.setEnabled(instanceId, false, approvalToken);- } catch (error) {- toast.error(t(ghostInstallErrorKey(extractIpcError(error)?.code)));- } finally {- if (closeAbortRef.current === abort) closeAbortRef.current = null;- }- };- return (- // 外层壳管布局占宽(出现/收起的宽度动画只动这层),内层 section 恒为- // 实宽被裁切——展开像"拉开抽屉"露出成形的面板,webview 不逐帧改宽。- <div- className={- isMaximized- ? 'flex h-full min-w-0 flex-1'- : fillContainer- ? 'flex h-full min-h-0 min-w-0 flex-1 overflow-hidden'- : `h-full shrink-0 overflow-hidden${enter ? ' ghost-panel-enter' : ''}${- closing ? ' ghost-panel-exit' : ''- }`- }- style={isMaximized || fillContainer ? undefined : { width }}- >- <section- data-panel-drag-root={kind}- // 侧边分割线由布局引擎统一绘制(LayoutRoot layout-divider),面板不自画。- className={- isMaximized || fillContainer- ? 'flex h-full w-full min-w-0 flex-col overflow-hidden bg-[var(--panel-bg)]'- : 'flex h-full shrink-0 flex-col overflow-hidden bg-[var(--panel-bg)]'- }- style={isMaximized || fillContainer ? undefined : { width }}- >- <PanelChrome- title={manifest.panel?.title ?? manifest.name}- showWindowSpacer={atWindowTop}- panelKind={maximizeEnabled ? kind : undefined}- onMinimize={minimizeEnabled ? beginMinimize : undefined}- onDetach={- detachEnabled- ? () => void window.electronAPI?.ghostPanelWindow?.setDetached(instanceId, true)- : undefined- }- onClose={() => void beginClose()}- />- {broken ? (- <GhostPanelError ghost={ghost} state={runtimeState} />- ) : (- <GhostChipPanelBody ghost={ghost} />- )}- </section>- </div>- );-}--const registeredKinds = new Set<string>();--/**- * 把注册表与"当前已装清单"对齐:新装的注册、卸下的注销、没变的不动。- * 停用(enabled=false)的意识视同不在场 —— 面板注销、布局里 pane 隐藏休眠,- * 重新启用时走同一条对齐路径复活(与"卸下再重装"共用 §6 规则 5 语义)。- * position:'tab' 的面板不进任何常驻注册表(面板收束,2026-08):由插件页- * 独占承载(features/plugin/GhostPagePanelHost),离开插件页即卸载。+ * 把全局页签与"当前已装清单"对齐,并清理卸载插件的高度缓存。+ * 本函数是"已装清单"的唯一同步点(启动 + ghosts:changed)。*/export function syncGhostPanelRegistrations(ghosts: InstalledGhost[]): void {- // 清理已卸载插件的高度缓存,并将当前 owner 的旧截图缓存收敛为纯高度;- // 本函数是"已装清单"的唯一同步点(启动 + ghosts:changed),挂这里最省。- // 注意用全量清单(含沉睡)——沉睡只是不注册面板,高度仍可复用。+ // 注意用全量清单(含沉睡)——沉睡只是不显示,高度仍可复用。pruneGhostSettingsHeights(getDataOwnerGeneration().dataOwnerId,ghosts.map((g) => pluginStoragePart(installedGhostLogicalIdentity(g))),);- // 气泡状态对齐(与高度 prune 不同:停用/失格的要强制还原,不只清卸载)——- // 气泡是"面板不可见 + 唯一恢复入口",失格后必须回停靠,不留死角。- reconcileGhostPanelBubbles(ghosts);- const seen = new Set<string>();- for (const ghost of ghosts) {- const { manifest, enabled } = ghost;- if (!manifest.panel) continue; // 无面板的意识(未来纯工具卡)不进注册表- if (manifest.panel.position === 'tab') continue; // 页签形态由插件页承载(面板收束)- if (enabled === false) continue; // 停用 = 休眠,不注册(注销走下方 seen 差集)- const instanceId = installedGhostStoragePart(ghost);- const kind = ghostPanelKind(instanceId);- seen.add(kind);- if (registeredKinds.has(kind)) continue;- registeredKinds.add(kind);- const Component = (props: PanelComponentProps): ReactNode => {- const installed = useInstalledGhosts().find(- (candidate) => installedGhostStoragePart(candidate) === instanceId,- );- if (!installed?.enabled || !installed.manifest.panel || installed.manifest.panel.position === 'tab') {- return null;- }- return <GhostPanel {...props} ghost={installed} />;- };- registerPanelKind({ kind, Component, collapseMemory: 'global' });- }- for (const kind of registeredKinds) {- if (seen.has(kind)) continue;- registeredKinds.delete(kind);- unregisterPanelKind(kind);- }+ reconcileGlobalPluginTabs(ghosts);}let initialSynced = false;/**- * 首帧前的一次性同步注册(幂等)。由 LayoutRoot 在渲染体内调用 —— 必须发生在- * 引擎第一次查注册表之前,意识面板才能与内置面板同帧出现(规则 7 无跳变)。+ * 首帧前的一次性同步(幂等)。由 LayoutRoot / 侧栏子窗口在渲染体内调用,+ * 让停靠面板迁移来的全局页签与侧栏首帧同时就位。*/export function ensureGhostPanelsRegistered(): void {if (initialSynced) return;initialSynced = true;// 测试/无桥环境(如 LayoutRoot 单测只 stub 了 layout)没有 ghosts 桥:- // 视同"没装任何意识",不是错误。+ // 视同"没装任何插件",不是错误。const api = window.electronAPI?.ghosts;if (!api) return;syncGhostPanelRegistrations(readInstalledGhostsSnapshot());}/**- * 订阅装/卸广播:同步注册表 + 触发一次重渲(卸下不改布局树,没有 layout:changed- * 可搭,必须自己 bump 才能让引擎重新按注册表过滤在场面板)。- * 返回同步版本号 —— 注册表是模块级 Map,不在 React 数据流里,依赖"注册表- * 内容"的 effect(如 LayoutRoot 布局自愈)把版本号放进 deps 才能感知变化。+ * 订阅装/卸广播:同步全局页签 + 返回版本号(依赖"已装清单"的 effect 把版本号+ * 放进 deps 才能感知变化)。*/export function useGhostPanelsSync(): number {const [version, bump] = useState(0);@@ -273,8 +71,7 @@ export function useGhostPanelsSync(): number {return version;}-/** 仅测试用:允许用例重复走首帧注册路径。 */+/** 仅测试用:允许用例重复走首帧同步路径。 */export function __resetGhostPanelsForTest(): void {initialSynced = false;- registeredKinds.clear();}diff --git a/apps/desktop/src/renderer/cindy-brain/mainViewIcons.ts b/apps/desktop/src/renderer/cindy-brain/mainViewIcons.tsnew file mode 100644index 0000000000..acfb6d3a4d--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/mainViewIcons.ts@@ -0,0 +1,31 @@+/**+ * 插件 mainView 图标名 → lucide 图标。左侧栏导航入口与右侧栏插件视图页签共用,+ * 单独成模块避免页签插件为取图标表而拖进路由相关依赖。+ */++import {+ CalendarDays,+ ChartColumn,+ Code,+ Database,+ Folder,+ Globe,+ Image,+ MessageCircle,+ Puzzle,+ type LucideIcon,+} from 'lucide-react';++import type { GhostMainViewIcon } from '../../shared/ghost';++export const MAIN_VIEW_ICONS: Record<GhostMainViewIcon, LucideIcon> = {+ puzzle: Puzzle,+ globe: Globe,+ code: Code,+ folder: Folder,+ database: Database,+ 'chart-column': ChartColumn,+ image: Image,+ 'message-circle': MessageCircle,+ 'calendar-days': CalendarDays,+};diff --git a/apps/desktop/src/renderer/cindy-brain/useMinimizedGhostPanels.ts b/apps/desktop/src/renderer/cindy-brain/useMinimizedGhostPanels.tsdeleted file mode 100644index 59b4402151..0000000000--- a/apps/desktop/src/renderer/cindy-brain/useMinimizedGhostPanels.ts+++ /dev/null@@ -1,40 +0,0 @@-import { useMemo } from 'react';--import type { InstalledGhost } from '../../shared/ghost';-import { installedGhostStoragePart } from '../../shared/pluginIdentity';-import type { GhostPanelWindowsState } from '../../shared/ghostPanelWindow';-import {- useGhostPanelBubbleState,- type GhostPanelBubbleMap,-} from '../lib/ghostPanelBubbleState';-import { useGhostPanelWindowsState } from '../lib/ghostPanelWindowState';-import { useInstalledGhosts } from './useInstalledGhosts';--/**- * 两种恢复入口共享的唯一筛选器。只有已装、启用、停靠形态、已最小化且未抽离到- * 独立窗口的插件面板才允许出现在恢复入口中。- */-export function selectMinimizedGhostPanels(- ghosts: readonly InstalledGhost[],- bubbles: GhostPanelBubbleMap,- windows: GhostPanelWindowsState,-): InstalledGhost[] {- return ghosts.filter(- (ghost) =>- ghost.enabled !== false &&- ghost.manifest.panel !== undefined &&- ghost.manifest.panel.position !== 'tab' &&- bubbles[installedGhostStoragePart(ghost)]?.minimized === true &&- windows[installedGhostStoragePart(ghost)]?.detached !== true,- );-}--export function useMinimizedGhostPanels(): InstalledGhost[] {- const ghosts = useInstalledGhosts();- const bubbles = useGhostPanelBubbleState();- const windows = useGhostPanelWindowsState();- return useMemo(- () => selectMinimizedGhostPanels(ghosts, bubbles, windows),- [bubbles, ghosts, windows],- );-}diff --git a/apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx b/apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsxindex 588969c786..cb906645f2 100644--- a/apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx+++ b/apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx@@ -50,7 +50,6 @@ function getRenderEntryContext(): RenderEntryContext {try {const params = new URLSearchParams(window.location.search);const view = params.get('view');- const ghostPanel = params.get('ghostPanelWindow');if (params.get('sidebarWindow') === '1') {return {@@ -59,13 +58,6 @@ function getRenderEntryContext(): RenderEntryContext {appVersion: window.electronAPI?.appVersion,};}- if (ghostPanel) {- return {- entry: 'ghost-panel',- windowKind: 'ghost-panel',- appVersion: window.electronAPI?.appVersion,- };- }if (params.get('secondaryWindow') === '1') {return {entry: 'secondary-window',diff --git a/apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx b/apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsxindex 7af56474fa..2b0c044550 100644--- a/apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx+++ b/apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx@@ -612,7 +612,7 @@ export function FindInPageBar() {)}// 页面顶行的窗口拖拽区(新建草稿页的 InvisibleWindowDragStrip、插件页// 页头等)与本栏几何重叠;拖拽区不看 z-index,会把关闭 / 翻页按钮上的- // 点击当成拖窗吞掉(#3908)。自身标 no-drag 挖洞,同 GhostPanelBubbleLayer。+ // 点击当成拖窗吞掉(#3908)。自身标 no-drag 挖洞。// ⚠️ 挖洞成立依赖布局树顺序(规则见 windowDrag.tsx 头注):本栏在 App.tsx// 里必须排在承载页面路由的 LoginHandoffHost 之后,别把它挪到路由前面。style={WINDOW_NO_DRAG_STYLE}diff --git a/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsxdeleted file mode 100644index af4b4ae0fe..0000000000--- a/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx+++ /dev/null@@ -1,220 +0,0 @@-/**- * GhostPanelWindowLayout —�?插件停靠面板独立窗口的根组件(路由 `/ghost-panel-window`)�?- *- * 窗口�?main/ghost-panel-window/window.ts 打开(`?ghostPanelWindow=<id>`),本组�?- * - �?46px 自绘 chrome(蓝本 SidebarWindowLayout):整条 drag region;mac 左端- * 红绿灯让位、win 右端 WindowControls(close �?sender 解析 = 只关本窗);- * 右端「合并回主窗口」按�?�?setDetached(id, false)(main 落盘 + 关本�?- * 主窗收广播后面板原位回停�?�?- * - 面板体零改动复用 GhostChipPanelBody(webview 供片/主题/崩溃接管全同�?- * 附加闸只认分�?地址,与宿主窗口无�?;崩溃/熔断�?GhostPanelError�?- * - manifest �?useInstalledGhosts 自查(ghosts:changed 广播发所有窗�?;- * 插件被卸�?停用�?main �?reconcile 会直接收�?这里只需短暂占位�?- * - �?GhostMediaLightboxHost:面板 /preview/ 点图事件推给本窗�?embedder),- * 不挂的话子窗�?点开看大�?没有承接端。无 sessionId,「发送到对话」隐藏�?- * - ⌘W / Ctrl+W:本窗口没�?tab 语义,直接关窗(= 合并回主窗的同一�?main 收口)�?- */--import { useEffect, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { PictureInPicture2, Puzzle } from 'lucide-react';--import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';-import { GhostChipPanelBody, GhostPanelError } from '@/cindy-brain/ghostPanelBody';-import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';-import { useGhostRuntimeState } from '@/cindy-brain/runtimeStates';-import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';-import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';-import { WindowControls } from '@/components/title-bar/WindowControls';-import { useAppShortcut } from '@/hooks/useAppShortcut';-import { useCloseShortcutShellOwner } from '@/hooks/useCloseWindowShortcut';-import { useLocale } from '@/hooks/useLocale';-import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';-import { minimizeGhostPanel, restoreGhostPanel } from '@/lib/ghostPanelBubbleState';-import { getGhostPanelWindowGhostId } from '@/lib/ghostPanelWindow';-import { createLogger } from '@/lib/logger';-import { toast } from '@/lib/toast';-import { extractIpcError } from '@/utils/ipcError';-import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost';-import { installedGhostStoragePart } from '../../../shared/pluginIdentity';--const log = createLogger('GhostPanelWindowLayout');--/** 面板�?+ 崩溃接管(与停靠形�?GhostPanel 同一分支逻辑,不含标准�?�?*/-function PanelBody({ ghost }: { ghost: InstalledGhost }) {- const { manifest } = ghost;- const instanceId = installedGhostStoragePart(ghost);- const runtimeState = useGhostRuntimeState(instanceId);- const broken = runtimeState === 'crashed' || runtimeState === 'fused';- return broken ? (- <GhostPanelError ghost={ghost} state={runtimeState} />- ) : (- <GhostChipPanelBody ghost={ghost} />- );-}--export function GhostPanelWindowLayout() {- const { t } = useTranslation();- const { effectiveLocale, setLocale } = useLocale();- const { confirm } = useConfirmDialog();- const isMac = window.electronAPI?.platform === 'darwin';- const ghostId = getGhostPanelWindowGhostId();- const ghosts = useInstalledGhosts();- const ghost = ghostId ? ghosts.find((g) => installedGhostStoragePart(g) === ghostId) : undefined;- // 停用/卸载的瞬�?main �?reconcile 会收�?这里只兜住收窗前的一两帧�?- const manifest = ghost && ghost.enabled !== false ? ghost.manifest : undefined;- const title = manifest?.panel?.title ?? manifest?.name ?? '';- const minimizeEnabled =- manifest !== undefined && manifest.panel?.systemButtons?.minimize !== false;- const presentationReadySentRef = useRef(false);- // 复用隐藏窗口时,Chromium 可能保留上一次关闭按钮的 focus / :hover 状态�?- // 与资源用量窗口一致,隐藏时重挂载 chrome,确保再次显示从干净状态开始�?- const [windowChromeRevision, setWindowChromeRevision] = useState(0);-- const minimizePanel = async (): Promise<void> => {- if (!ghostId || !minimizeEnabled) return;- minimizeGhostPanel(ghostId);- try {- await window.electronAPI.ghostPanelWindow.setDetached(ghostId, false);- } catch (err) {- restoreGhostPanel(ghostId);- log.warn('minimize ghost panel failed', err);- }- };-- const disableAndClose = async (): Promise<void> => {- if (!ghostId || !manifest || !ghost) return;- const approvalToken = ghostInstallApprovalToken(ghost.approval);- const approved = await confirm({- title: t('ghostPanel.disableConfirm.title', { name: manifest.name }),- description: t('ghostPanel.disableConfirm.body'),- confirmText: t('ghostPanel.disableConfirm.confirm'),- });- await window.electronAPI.ghostPanelWindow.resolveCloseRequest(approved);- if (!approved) return;- try {- await window.electronAPI.ghosts.setEnabled(ghostId, false, approvalToken);- } catch (error) {- toast.error(t(ghostInstallErrorKey(extractIpcError(error)?.code)));- }- };-- // mount:renderer-ready 握手 + presentation-ready(manifest 就绪�?�?- useEffect(() => {- void window.electronAPI.ghostPanelWindow.rendererReady().catch((err) => {- log.warn('renderer-ready handshake failed', err);- });- }, []);-- useEffect(() => {- if (presentationReadySentRef.current || !manifest) return;- presentationReadySentRef.current = true;- void window.electronAPI.ghostPanelWindow.presentationReady().catch((err) => {- log.warn('presentation-ready handshake failed', err);- });- }, [manifest]);-- // 隐藏/显示时重置瞬时交互态�?- useEffect(() => {- return window.electronAPI.ghostPanelWindow.onVisibilityChanged((payload) => {- if (!payload.visible) {- if (document.activeElement instanceof HTMLElement) document.activeElement.blur();- setWindowChromeRevision((revision) => revision + 1);- } else {- // 重新显示时模糊焦�?+ �?webview 重获焦点(面板内容持续运行)- if (document.activeElement instanceof HTMLElement) document.activeElement.blur();- }- });- }, []);-- useEffect(() => {- return window.electronAPI.ghostPanelWindow.onCloseRequested(() => {- void disableAndClose();- });- }, [ghostId, ghost, manifest, confirm, t, window.electronAPI.ghostPanelWindow]);-- useEffect(() => {- if (!minimizeEnabled) return;- return window.electronAPI.ghostPanelWindow.onMinimizeRequested(() => {- void minimizePanel();- });- }, [ghostId, minimizeEnabled, window.electronAPI.ghostPanelWindow]);-- useEffect(() => {- return window.electronAPI.onLocaleChanged?.((locale) => {- if (locale !== effectiveLocale) setLocale(locale);- }) ?? undefined;- }, [effectiveLocale, setLocale]);-- // ⌘W / Ctrl+W:直接关本�?main 端按 sender win.close(),controller �?- // onClosed = 回停�?。声明壳层所有权,App 根的 fallback 让路�?- useCloseShortcutShellOwner();- useAppShortcut('close-tab-or-window', () => {- void disableAndClose();- return true;- });-- const mergeBack = () => {- if (!ghostId) return;- void window.electronAPI.ghostPanelWindow.setDetached(ghostId, false).catch((err) => {- log.warn('merge back failed', err);- });- };-- return (- <div className="flex h-screen flex-col bg-content-area text-foreground">- {/* 46px 自绘 chrome:整条 drag region;布局对齐 SidebarWindowLayout�?*/}- <div- className="relative flex h-[46px] shrink-0 items-center border-b border-[var(--border-default)] bg-[var(--panel-bg)]"- style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}- >- <div className={isMac ? 'w-20 shrink-0' : 'w-3 shrink-0'} />- <div className="flex min-w-0 flex-1 items-center gap-2">- <Puzzle size={14} className="shrink-0 text-[var(--text-tertiary)]" />- <span className="truncate text-13 text-[var(--text-secondary)]">{title}</span>- </div>- <div- className="flex shrink-0 items-center gap-0.5 pr-2"- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}- >- {/* 合并回主窗口:关偏�?+ 关本�?面板原位回停�?*/}- <ChromeIconButton- onClick={mergeBack}- aria-label={t('rightSidebar.window.mergeBack')}- >- <PictureInPicture2 size={14} />- </ChromeIconButton>- </div>- {!isMac && (- <div- className="flex h-full shrink-0 items-center"- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}- >- <WindowControls- key={windowChromeRevision}- onMinimize={minimizePanel}- showMinimize={minimizeEnabled}- onClose={disableAndClose}- />- </div>- )}- </div>-- {/* 面板�?manifest 在场即挂 webview;不在�?收窗前瞬�?�?URL)给占位�?*/}- <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">- {ghost && manifest ? (- <PanelBody ghost={ghost} />- ) : (- <div className="flex flex-1 items-center justify-center">- <span className="text-13 text-[var(--text-tertiary)]">- {t('ghostPanelWindow.unavailable')}- </span>- </div>- )}- </div>-- {/* 面板 /preview/ 点图的承接端(�?sessionId:「发送到对话」隐�?�?*/}- <GhostMediaLightboxHost />- </div>- );-}diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex 8a61e438ea..9e557ec3cb 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -20,7 +20,6 @@ import { getSplitSessionIds, useSplitGroup } from '@/features/cc-agent/splitGrouimport { LayoutRoot } from '@/layout/LayoutRoot';import { PanelDragController } from '@/layout/PanelDragController';import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';-import { GhostPanelBubbleLayer } from '@/cindy-brain/GhostPanelBubbleLayer';import {migrateLegacySidebarCollapsed,readPanelCollapsed,@@ -59,6 +58,7 @@ import {setActiveTab,} from '@/features/right-sidebar/store';import { browserWebviewPool } from '@/features/right-sidebar/lib/browserWebviewPool';+import { findGlobalTab, setActiveGlobalTabId } from '@/features/right-sidebar/globalTabs';import {markAllPtyDetached,markPtyDetached,@@ -1093,27 +1093,30 @@ export function MainLayout() {// 交回后本窗必须再 attach 一次)。不可持久化会话附整桶内存快照。const handleDetachRightSidebarTab = useCallback((tabId: string) => {if (isSecondaryWindow()) return;+ const api = window.electronAPI.sidebarTabWindow;+ if (!api?.open) return;+ const info = rightSidebarWorkdirInfoRef.current;+ const context = {+ workdir: info.workdir || null,+ remoteHostId: info.remoteHostId,+ deviceLinkDeviceId: info.deviceLinkDeviceId,+ subagentsAvailable: rightSidebarSubagentsAvailableRef.current,+ };+ // 全局页签(插件视图)不属于任何任务:无桶快照,也没有任务级资源要释放。+ if (findGlobalTab(tabId)) {+ void api.open({ tabId, sessionId: null, context, handoff: null }).catch((err) => {+ applicationMenuLog.warn('pop out global sidebar tab failed', { tabId, err });+ });+ return;+ }const sessionId = rightSidebarSessionIdRef.current;if (!sessionId) return;const tab = getBucket(sessionId).tabs.find((candidate) => candidate.id === tabId);if (!tab) return;- const api = window.electronAPI.sidebarTabWindow;- if (!api?.open) return;if (tab.kind === 'web-browser') browserWebviewPool.release(tabId);if (tab.kind === 'terminal') markPtyDetached(tabId);- const info = rightSidebarWorkdirInfoRef.current;void api- .open({- tabId,- sessionId,- context: {- workdir: info.workdir || null,- remoteHostId: info.remoteHostId,- deviceLinkDeviceId: info.deviceLinkDeviceId,- subagentsAvailable: rightSidebarSubagentsAvailableRef.current,- },- handoff: getTabSnapshot(sessionId),- })+ .open({ tabId, sessionId, context, handoff: getTabSnapshot(sessionId) }).catch((err) => {applicationMenuLog.warn('pop out sidebar tab failed', { sessionId, tabId, err });});@@ -1128,6 +1131,15 @@ export function MainLayout() {const api = window.electronAPI.sidebarTabWindow;if (!api?.onTabReturned) return;return api.onTabReturned(({ sessionId, tabId, snapshot }) => {+ // 全局页签回来:数据一直在全局存储里,只需选中它并确保侧栏展开。+ if (sessionId === null) {+ if (findGlobalTab(tabId)) setActiveGlobalTabId(tabId);+ if (isRightSidebarCollapsedRef.current && !rsbDetachedRef.current) {+ writeCollapsedFor(rightSidebarSessionIdRef.current, false);+ setIsRightSidebarCollapsed(false);+ }+ return;+ }markPtyDetached(tabId);const refreshed = snapshot? Promise.resolve(importReturnedTabState(snapshot))@@ -1741,10 +1753,6 @@ export function MainLayout() {推送到本窗口,这里弹标准 ImageLightbox(整窗一份,纯监听无 UI)。sessionId = 当前聊天会话 → lightbox 里「发送到对话」可用。 */}<GhostMediaLightboxHost sessionId={rightSidebarSessionId ?? undefined} />- {/* 最小化插件面板的浮动气泡层(portal 到 body,z-[9900];点击气泡- 恢复停靠,拖动换位并持久化)。设置页等接管态也保持在场——气泡是- 被最小化面板的唯一恢复入口。 */}- <GhostPanelBubbleLayer />{/* Windows 顶层浮层 chrome:窗口控制按钮(min/max/close),所有路由常驻(含设置页),永远钉在窗口角,开/关右栏都不动 —— 解决「右栏作为 <main>sibling 会把窗口按钮挤左」的问题。no-drag(按钮可点),周围窗口拖拽区由diff --git a/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsxindex fb3391dba8..1c52ea691b 100644--- a/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx@@ -34,6 +34,11 @@ import { mergeSidebarWindowBack } from '@/features/right-sidebar/lib/mergeSidebaimport { setSoloTabId } from '@/features/right-sidebar/lib/tabHosting';import { getTabKind, hydrateTabState } from '@/features/right-sidebar/registry';import { closeTab, getBucket, importTabSnapshot, subscribe } from '@/features/right-sidebar/store';+import {+ findGlobalTab,+ removeGlobalTab,+ useGlobalTabs,+} from '@/features/right-sidebar/globalTabs';import { iconForTabKind, labelKeyForTabKind } from '@/features/right-sidebar/TabBar';import { WindowControls } from '@/components/title-bar/WindowControls';import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';@@ -131,29 +136,34 @@ export function SidebarTabWindowLayout() {);const getBucketSnapshot = useCallback(() => getBucket(sessionId), [sessionId]);const bucket = useSyncExternalStore(subscribeBucket, getBucketSnapshot);- const tab = useMemo(- () => (tabId ? (bucket.tabs.find((candidate) => candidate.id === tabId) ?? null) : null),- [bucket.tabs, tabId],- );+ // 全局页签(插件视图,sessionId=null)不在任务桶里,从全局存储找;它不需要任务桶水合。+ const globalTabs = useGlobalTabs();+ const isGlobal = assignment !== null && assignment.sessionId === null;+ const tab = useMemo(() => {+ if (!tabId) return null;+ if (isGlobal) return globalTabs.find((candidate) => candidate.id === tabId) ?? null;+ return bucket.tabs.find((candidate) => candidate.id === tabId) ?? null;+ }, [bucket.tabs, globalTabs, isGlobal, tabId]);+ const contentReady = isGlobal || bucket.hydrated;// presentation-ready:被指派页签的桶已水合且页签在场 → main 可以展示窗口。useEffect(() => {- if (presentationReadySentRef.current || !assignment || !bucket.hydrated || !tab) return;+ if (presentationReadySentRef.current || !assignment || !contentReady || !tab) return;presentationReadySentRef.current = true;void api?.presentationReady?.().catch((err) => {log.warn('presentation-ready handshake failed', err);});- }, [api, assignment, bucket.hydrated, tab]);+ }, [api, assignment, contentReady, tab]);- // 页签已不在桶里(本窗口内被关闭):销毁本窗口,不交回。+ // 页签已不在桶 / 全局列表里(本窗口内被关闭):销毁本窗口,不交回。useEffect(() => {- if (!assignment || !bucket.hydrated || tab || leavingRef.current) return;+ if (!assignment || !contentReady || tab || leavingRef.current) return;leavingRef.current = true;void api?.closeForTab(assignment.tabId).catch((err) => {leavingRef.current = false;log.warn('close window for closed tab failed', err);});- }, [api, assignment, bucket.hydrated, tab]);+ }, [api, assignment, contentReady, tab]);const mergeBack = useCallback(() => {if (!assignment || leavingRef.current) return;@@ -168,6 +178,11 @@ export function SidebarTabWindowLayout() {// 都不发生;页签真的消失后,上面的 effect 再请求 main 销毁窗口。const closeOwnTab = useCallback(() => {if (!assignment || leavingRef.current) return;+ if (assignment.sessionId === null) {+ // 全局页签:关闭是全局动作,列表变化后上面的 effect 收窗。+ if (findGlobalTab(assignment.tabId)) removeGlobalTab(assignment.tabId);+ return;+ }void closeTab(assignment.sessionId, assignment.tabId).catch((err) => {log.warn('close popped-out tab failed', err);});@@ -253,7 +268,7 @@ export function SidebarTabWindowLayout() {{(!windowVisible || !assignment || !tab) && (<div className="absolute inset-0 z-10 flex items-center justify-center bg-[var(--panel-bg)]"><span className="text-13 text-[var(--text-tertiary)]">- {assignment && bucket.hydrated && !tab+ {assignment && contentReady && !tab? t('rightSidebar.tabWindow.closed'): t('rightSidebar.tabWindow.loading')}</span>diff --git a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsxindex 812491618f..b8306eb3fb 100644--- a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx+++ b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdomimport React from 'react';-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { RsbWindowContext } from '../../../../shared/rightSidebarWindow';@@ -10,11 +10,7 @@ const mocks = vi.hoisted(() => ({sidebarTabHandoffListener: null as| ((handoff: import('../../../../shared/rightSidebarWindow').RsbWindowTabHandoff) => void)| null,- ghostVisibilityListener: null as ((payload: { visible: boolean }) => void) | null,- ghostMinimizeListener: null as (() => void) | null,- ghostMinimizeEnabled: true,confirm: vi.fn(() => Promise.resolve(false)),- ghostCloseListener: null as (() => void) | null,ghostApprovalRevision: '00000000-0000-4000-8000-000000000001',sidebarShellVisible: undefined as boolean | undefined,sidebarShellSessionId: undefined as string | null | undefined,@@ -23,8 +19,6 @@ const mocks = vi.hoisted(() => ({sidebarLightboxMountId: undefined as number | undefined,initGlobalListeners: vi.fn(),importTabSnapshot: vi.fn(),- minimizeGhostPanel: vi.fn(),- restoreGhostPanel: vi.fn(),}));vi.mock('@/components/title-bar/WindowControls', () => ({@@ -105,9 +99,6 @@ vi.mock('@/cindy-brain/useInstalledGhosts', () => ({name: 'Test Ghost',panel: {title: 'Test Panel',- ...(mocks.ghostMinimizeEnabled- ? {}- : { systemButtons: { minimize: false } }),},},},@@ -121,11 +112,6 @@ vi.mock('@/hooks/useCloseWindowShortcut', () => ({ useCloseShortcutShellOwner: vvi.mock('@/hooks/useLocale', () => ({useLocale: () => ({ effectiveLocale: 'en', setLocale: vi.fn() }),}));-vi.mock('@/lib/ghostPanelWindow', () => ({ getGhostPanelWindowGhostId: () => 'test-ghost' }));-vi.mock('@/lib/ghostPanelBubbleState', () => ({- minimizeGhostPanel: mocks.minimizeGhostPanel,- restoreGhostPanel: mocks.restoreGhostPanel,-}));vi.mock('@/lib/makerChatStore', () => ({makerChatStore: { initGlobalListeners: mocks.initGlobalListeners },}));@@ -146,7 +132,6 @@ vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));-import { GhostPanelWindowLayout } from '../GhostPanelWindowLayout';import { SidebarWindowLayout } from '../SidebarWindowLayout';describe('reusable auxiliary window chrome', () => {@@ -155,11 +140,7 @@ describe('reusable auxiliary window chrome', () => {mocks.controlsMounts = 0;mocks.sidebarVisibilityListener = null;mocks.sidebarTabHandoffListener = null;- mocks.ghostVisibilityListener = null;- mocks.ghostMinimizeListener = null;- mocks.ghostMinimizeEnabled = true;mocks.confirm.mockReset().mockResolvedValue(false);- mocks.ghostCloseListener = null;mocks.ghostApprovalRevision = '00000000-0000-4000-8000-000000000001';mocks.sidebarShellVisible = undefined;mocks.sidebarShellSessionId = undefined;@@ -195,24 +176,6 @@ describe('reusable auxiliary window chrome', () => {close: vi.fn(() => Promise.resolve()),setDetached: vi.fn(() => Promise.resolve()),},- ghostPanelWindow: {- rendererReady: vi.fn(() => Promise.resolve()),- presentationReady: vi.fn(() => Promise.resolve()),- onVisibilityChanged: vi.fn((listener) => {- mocks.ghostVisibilityListener = listener;- return vi.fn();- }),- onCloseRequested: vi.fn((listener) => {- mocks.ghostCloseListener = listener;- return vi.fn();- }),- onMinimizeRequested: vi.fn((listener) => {- mocks.ghostMinimizeListener = listener;- return vi.fn();- }),- resolveCloseRequest: vi.fn(() => Promise.resolve()),- setDetached: vi.fn(() => Promise.resolve()),- },ghosts: { setEnabled: vi.fn(() => Promise.resolve()) },},});@@ -220,19 +183,6 @@ describe('reusable auxiliary window chrome', () => {afterEach(() => cleanup());- it('keeps the detached close bound to the approval shown before confirmation', async () => {- let confirmClose!: (confirmed: boolean) => void;- mocks.confirm.mockReturnValue(new Promise<boolean>((resolve) => { confirmClose = resolve; }));- const view = render(<GhostPanelWindowLayout />);- act(() => mocks.ghostCloseListener?.());- mocks.ghostApprovalRevision = '00000000-0000-4000-8000-000000000002';- view.rerender(<GhostPanelWindowLayout />);- await act(async () => confirmClose(true));- expect(window.electronAPI.ghosts.setEnabled).toHaveBeenCalledExactlyOnceWith(- 'test-ghost', false, 'approved:00000000-0000-4000-8000-000000000001',- );- });-it('remounts right-sidebar controls when the cached window is hidden', async () => {render(<SidebarWindowLayout />);const controlsBeforeHide = screen.getByTestId('window-controls');@@ -281,71 +231,6 @@ describe('reusable auxiliary window chrome', () => {);});- it('remounts ghost-panel controls when the cached window is hidden', async () => {- render(<GhostPanelWindowLayout />);- const controlsBeforeHide = screen.getByTestId('window-controls');- controlsBeforeHide.focus();-- await act(async () => mocks.ghostVisibilityListener?.({ visible: false }));-- const controlsAfterHide = screen.getByTestId('window-controls');- expect(controlsAfterHide).not.toBe(controlsBeforeHide);- expect(document.activeElement).not.toBe(controlsAfterHide);- });-- it('uses an icon-only merge-back action for detached plugin windows', async () => {- render(<GhostPanelWindowLayout />);-- const mergeBack = screen.getByRole('button', { name: 'rightSidebar.window.mergeBack' });- expect(mergeBack.getAttribute('title')).toBeNull();- expect(mergeBack.textContent).not.toContain('rightSidebar.window.mergeBack');- fireEvent.click(mergeBack);-- expect(window.electronAPI.ghostPanelWindow.setDetached).toHaveBeenCalledWith(- 'test-ghost',- false,- );- });-- it('minimizes a detached plugin window through the main-window restore flow', async () => {- render(<GhostPanelWindowLayout />);-- fireEvent.click(screen.getByRole('button', { name: 'titleBar.minimize' }));-- expect(mocks.minimizeGhostPanel).toHaveBeenCalledWith('test-ghost');- expect(window.electronAPI.ghostPanelWindow.setDetached).toHaveBeenCalledWith(- 'test-ghost',- false,- );- expect(mocks.restoreGhostPanel).not.toHaveBeenCalled();- });-- it('restores the bubble state when merging the minimized plugin window fails', async () => {- window.electronAPI.ghostPanelWindow.setDetached = vi.fn(() =>- Promise.reject(new Error('failed')),- );- render(<GhostPanelWindowLayout />);-- await act(async () => {- fireEvent.click(screen.getByRole('button', { name: 'titleBar.minimize' }));- });-- expect(mocks.minimizeGhostPanel).toHaveBeenCalledWith('test-ghost');- expect(mocks.restoreGhostPanel).toHaveBeenCalledWith('test-ghost');- });-- it('uses the same Ghost bubble action for a native minimize request', async () => {- render(<GhostPanelWindowLayout />);-- await act(async () => mocks.ghostMinimizeListener?.());-- expect(mocks.minimizeGhostPanel).toHaveBeenCalledWith('test-ghost');- expect(window.electronAPI.ghostPanelWindow.setDetached).toHaveBeenCalledWith(- 'test-ghost',- false,- );- });-it('restores right-sidebar tab bodies only after the visible window has fresh context', async () => {render(<SidebarWindowLayout />);expect(mocks.initGlobalListeners).toHaveBeenCalledWith({ ownsRemoteAuthRetry: false, ownsRemoteListCache: false });@@ -468,14 +353,4 @@ describe('reusable auxiliary window chrome', () => {expect(mocks.sidebarLightboxSessionId).toBe('session-b');});- it('respects a plugin manifest that disables minimize in the detached window', async () => {- mocks.ghostMinimizeEnabled = false;-- render(<GhostPanelWindowLayout />);-- expect(screen.queryByRole('button', { name: 'titleBar.minimize' })).toBeNull();- expect(window.electronAPI.ghostPanelWindow.onMinimizeRequested).not.toHaveBeenCalled();- expect(mocks.ghostMinimizeListener).toBeNull();- expect(mocks.minimizeGhostPanel).not.toHaveBeenCalled();- });});diff --git a/apps/desktop/src/renderer/components/layout/windowDrag.tsx b/apps/desktop/src/renderer/components/layout/windowDrag.tsxindex 08fd09b526..58c13ca416 100644--- a/apps/desktop/src/renderer/components/layout/windowDrag.tsx+++ b/apps/desktop/src/renderer/components/layout/windowDrag.tsx@@ -17,7 +17,7 @@* DOM 里排在 drag 区之前的浮层/兄弟节点,其 no-drag 会被后来的 drag 盖回* (ContentHeader.tsx「浮层 no-drag 不被计入」、FileTabsBar.tsx 的实机结论* 即此情形)。排在 drag 区之后的浮层(如 App.tsx 路由之后的 FindInPageBar、- * portal 到 body 的 GhostPanelBubbleLayer)自身标 no-drag 可以挖洞。+ * portal 到 body 的查找条)自身标 no-drag 可以挖洞。* 交互元素漏标 no-drag 会变成"点了就拖窗口";* 反之 drag 条叠在交互元素上同样会吞掉点击 —— InvisibleWindowDragStrip* 只能用在顶部确实无交互元素的页面。diff --git a/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsxindex a3d5a4806c..7717f38e0a 100644--- a/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsx@@ -35,9 +35,6 @@ vi.mock('@/lib/secondaryWindow', () => ({vi.mock('@/lib/sidebarWindow', () => ({isSidebarWindow: () => false,}));-vi.mock('@/lib/ghostPanelWindow', () => ({- isGhostPanelWindow: () => false,-}));vi.mock('../LoginPage', () => ({LoginPage: ({ onClose }: { onClose?: () => void }) => (diff --git a/apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts b/apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.tsindex ee651b7e76..63654db9b4 100644--- a/apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts+++ b/apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts@@ -20,7 +20,6 @@ export default {{ id: 'settings.appearance.font.codeSize.label', fallbackTargetId: 'settings-search-target-appearance-fonts', tab: 'appearance', targetId: 'settings-search-settings-appearance-font-codeSize-label', titleKey: 'settings.appearance.font.codeSize.label', sectionKey: 'settings.appearance.font.title', descriptionKey: 'settings.appearance.font.codeSize.description' },{ id: 'settings.appearance.sidebarCardMode.label', fallbackTargetId: 'settings-search-target-appearance-sidebar', tab: 'appearance', targetId: 'settings-search-settings-appearance-sidebarCardMode-label', titleKey: 'settings.appearance.sidebarCardMode.label', sectionKey: 'settings.appearance.sidebarAndPanels', descriptionKey: 'settings.appearance.sidebarCardMode.hint' },{ id: 'settings.appearance.sidebarMainListMode.label', fallbackTargetId: 'settings-search-target-appearance-sidebar', tab: 'appearance', targetId: 'settings-search-settings-appearance-sidebarMainListMode-label', titleKey: 'settings.appearance.sidebarMainListMode.label', sectionKey: 'settings.appearance.sidebarAndPanels', descriptionKey: 'settings.appearance.sidebarMainListMode.hint' },- { id: 'settings.appearance.ghostPanelRestore.label', fallbackTargetId: 'settings-search-target-appearance-sidebar', tab: 'appearance', targetId: 'settings-search-settings-appearance-ghostPanelRestore-label', titleKey: 'settings.appearance.ghostPanelRestore.label', sectionKey: 'settings.appearance.sidebarAndPanels', descriptionKey: 'settings.appearance.ghostPanelRestore.hint' },{ id: 'appearance.streamFade', tab: 'appearance', targetId: 'settings-search-target-appearance-stream-fade', titleKey: 'settings.sections.streamFade', sectionKey: 'settings.sections.streamFade', aliases: ['personalization.streamFade', 'settings-search-target-personalization-stream-fade'] },{ id: 'settings.streamFade.label', fallbackTargetId: 'settings-search-target-appearance-stream-fade', tab: 'appearance', targetId: 'settings-search-target-appearance-stream-fade', titleKey: 'settings.streamFade.label', sectionKey: 'settings.sections.streamFade', aliases: ['fade in', '流式淡入'] },],diff --git a/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx b/apps/desktop/src/renderer/components/settings/AppearanceSection.tsxindex 79560732f3..b2f3a0c604 100644--- a/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx+++ b/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx@@ -25,7 +25,6 @@ import {useFontSettings,} from '@/hooks/useFontSettings';import { useSidebarCardMode, useSidebarMainViewMode } from '@/hooks/useSidebarCardMode';-import { useGhostPanelRestoreMode } from '@/hooks/useGhostPanelRestoreMode';import { getThemeFamilies, resolveFamilyVariant, type ThemeFamily } from '@/themes/families';import { resolveThemeValue } from '@/themes/theme-service';import type { Theme } from '@/themes/types';@@ -415,8 +414,6 @@ export function AppearanceSection() {} = useFontSettings();const { mode: sidebarViewMode, setMode: setSidebarViewMode } = useSidebarCardMode();const { mode: sidebarMainViewMode, setMode: setSidebarMainViewMode } = useSidebarMainViewMode();- const { mode: ghostPanelRestoreMode, setMode: setGhostPanelRestoreMode } =- useGhostPanelRestoreMode();const { t } = useTranslation();const [localThemesVersion, setLocalThemesVersion] = useState(0);const [uiSizeInput, setUiSizeInput] = useState(String(uiSize));@@ -972,32 +969,6 @@ export function AppearanceSection() {/></div>- <div className={SETTINGS_ROW_DIVIDER_CLASS} />-- <div className="cindy-segmented-row px-4 py-4">- <div className="flex min-w-0 flex-col gap-1">- <p- id="settings-search-settings-appearance-ghostPanelRestore-label"- className="text-13 font-medium text-[var(--settings-section-sublabel)]"- style={{ letterSpacing: '0.12px' }}- >- {t('settings.appearance.ghostPanelRestore.label')}- </p>- <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">- {t('settings.appearance.ghostPanelRestore.hint')}- </p>- </div>-- <SegmentedControl- aria-label={t('settings.appearance.ghostPanelRestore.aria')}- value={ghostPanelRestoreMode}- onValueChange={setGhostPanelRestoreMode}- options={[- { value: 'bubble', label: t('settings.appearance.ghostPanelRestore.bubble') },- { value: 'sidebar', label: t('settings.appearance.ghostPanelRestore.sidebar') },- ]}- />- </div><div className={SETTINGS_ROW_DIVIDER_CLASS} />diff --git a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsxindex 742b6a6caa..bad39322c0 100644--- a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx+++ b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx@@ -1,22 +1,18 @@-import {- CalendarDays,- ChartColumn,- Code,- Database,- Folder,- Globe,- Image,- MessageCircle,- Puzzle,- SlidersHorizontal,- type LucideIcon,-} from 'lucide-react';+import { useState } from 'react';+import { PanelRight, SlidersHorizontal } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useMatch, useNavigate } from 'react-router-dom';import { useGhostMainViews, type GhostMainViewItem } from '@/cindy-brain/ghostMainViews';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { addGlobalPluginTab, setActiveGlobalTabId } from '@/features/right-sidebar/globalTabs';+import { requestRightSidebarVisibility } from '@/features/right-sidebar/lib/sidebarCommands';import { cn } from '@/lib/utils';-import type { GhostMainViewIcon } from '../../../shared/ghost';import { SIDEBAR_RAIL_ICON_BUTTON_CLASS } from './SidebarIconButton';import { Tip } from '../ui/tooltip';@@ -28,17 +24,8 @@ const ROW_ACTIVE_CLASS =const RAIL_ACTIVE_CLASS ='[--button-face-bg:var(--chat-input-chip-bg)] text-[var(--msg-assistant-text)] enabled:hover:[--button-face-bg:var(--chat-input-chip-bg)] enabled:active:[--button-face-bg:var(--chat-input-chip-bg)]';-export const MAIN_VIEW_ICONS: Record<GhostMainViewIcon, LucideIcon> = {- puzzle: Puzzle,- globe: Globe,- code: Code,- folder: Folder,- database: Database,- 'chart-column': ChartColumn,- image: Image,- 'message-circle': MessageCircle,- 'calendar-days': CalendarDays,-};+export { MAIN_VIEW_ICONS } from '@/cindy-brain/mainViewIcons';+import { MAIN_VIEW_ICONS } from '@/cindy-brain/mainViewIcons';/** Expanded and rail variants consume the exact same sorted visibility projection. */export function GhostMainViewNavEntries({ variant }: { variant: 'row' | 'rail' }) {@@ -72,25 +59,79 @@ export function GhostMainViewNavEntry({const open = () => navigate(`/apps/${encodeURIComponent(item.instanceId)}`);const openDetails = () =>navigate(`/settings?tab=ghosts&ghost=${encodeURIComponent(item.instanceId)}`);+ // 右键菜单:「在侧边栏中打开」= 把这个插件视图作为全局页签(不跟对话)钉进右侧栏。+ const [contextMenuPos, setContextMenuPos] = useState<{ x: number; y: number } | null>(null);+ const onContextMenu = (e: React.MouseEvent) => {+ e.preventDefault();+ e.stopPropagation();+ setContextMenuPos({ x: e.clientX, y: e.clientY });+ };+ const openInSidebar = () => {+ const tab = addGlobalPluginTab(item.instanceId);+ if (!tab) return;+ setActiveGlobalTabId(tab.id);+ requestRightSidebarVisibility('open');+ };+ const contextMenu = (+ <DropdownMenu+ open={contextMenuPos !== null}+ onOpenChange={(isOpen) => {+ if (!isOpen) setContextMenuPos(null);+ }}+ >+ <DropdownMenuTrigger asChild>+ <span+ aria-hidden+ style={{+ position: 'fixed',+ left: contextMenuPos?.x ?? 0,+ top: contextMenuPos?.y ?? 0,+ width: 0,+ height: 0,+ pointerEvents: 'none',+ }}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={2}>+ <DropdownMenuItem+ onClick={() => {+ setContextMenuPos(null);+ openInSidebar();+ }}+ >+ <PanelRight size={14} aria-hidden="true" />+ {t('ghostMainView.openInSidebar')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );if (variant === 'rail') {return (- <Tip text={item.title} side="right">- <button- type="button"- aria-label={item.title}- aria-current={active ? 'page' : undefined}- onClick={open}- className={cn(SIDEBAR_RAIL_ICON_BUTTON_CLASS, active && RAIL_ACTIVE_CLASS)}- >- {icon}- </button>- </Tip>+ <>+ <Tip text={item.title} side="right">+ <button+ type="button"+ aria-label={item.title}+ aria-current={active ? 'page' : undefined}+ onClick={open}+ onContextMenu={onContextMenu}+ className={cn(SIDEBAR_RAIL_ICON_BUTTON_CLASS, active && RAIL_ACTIVE_CLASS)}+ >+ {icon}+ </button>+ </Tip>+ {contextMenu}+ </>);}return (- <div className={cn(ROW_CLASS, 'group/main-view gap-0 px-0', active && ROW_ACTIVE_CLASS)}>+ <div+ className={cn(ROW_CLASS, 'group/main-view gap-0 px-0', active && ROW_ACTIVE_CLASS)}+ onContextMenu={onContextMenu}+ >+ {contextMenu}<buttontype="button"aria-label={item.title}diff --git a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsxindex b2ec3fc4f4..c29fa213c1 100644--- a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx+++ b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx@@ -41,7 +41,6 @@ import { AttentionDot, type DotTone } from '@/components/sidebar/AttentionDot';import { useAnyGhostUnread } from '@/cindy-brain/ghostUnreadStore';import { useGhostMainViews, type GhostMainViewItem } from '@/cindy-brain/ghostMainViews';import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';-import { GhostPanelRestoreEntry } from '@/cindy-brain/GhostPanelRestoreEntry';import { useActiveMainView } from '@/hooks/useActiveMainView';import { SidebarInlineSearch } from '@/features/cc-agent/sidebar/SidebarInlineSearch';import { SidebarIconButton, SIDEBAR_RAIL_ICON_BUTTON_CLASS } from './SidebarIconButton';@@ -398,7 +397,6 @@ export function SidebarRailNavigation({/>);})}- <GhostPanelRestoreEntry variant="rail" className={SIDEBAR_RAIL_ICON_BUTTON_CLASS} /><SidebarNavigationMoreMenuhiddenIds={entries.hidden}actions={actions}@@ -496,9 +494,6 @@ export function SidebarTopNav({</button>);};- const restoreRow = showScrollable ? (- <GhostPanelRestoreEntry variant="row" className={ROW_CLASS} />- ) : null;const searchRow = showScrollable ? (<SidebarInlineSearchsearch={search}@@ -573,7 +568,6 @@ export function SidebarTopNav({) : !showSearch ? (<div className="flex flex-col gap-0.5 pr-3 pl-3">{orderedNavigationRows}- {restoreRow}{customizeRow}</div>) : (@@ -594,8 +588,7 @@ export function SidebarTopNav({results follow them instead of replacing them. */}<div className="-mt-1.5 flex flex-col gap-0.5 pr-3 pl-3">{rowsAfterSearch}- {restoreRow}- {customizeRow}+ {customizeRow}</div></>)}@@ -603,7 +596,7 @@ export function SidebarTopNav({);}- // Persistent-view contract: saved navigation order -> {restoreRow} -> More.+ // Persistent-view contract: saved navigation order -> More.return (// pt-1(原 2.5):顶行 chrome 收窄到 46px 后,列表整体上提贴近顶行(对齐 Codex)。// 分段渲染时(section≠'all')两段各自成块,由调用方分别放进固定区 / 滚动区;@@ -637,7 +630,6 @@ export function SidebarTopNav({) : (orderedNavigationRows))}- {showScrollable && !customizing && restoreRow}{showScrollable && !customizing && customizeRow}</div>);diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsxindex dece6e5274..ec02ea13e2 100644--- a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx@@ -26,6 +26,18 @@ const items = [vi.mock('@/cindy-brain/ghostMainViews', () => ({useGhostMainViews: () => ({ declared: items, routeCapable: items, sidebarVisible: items }),}));+const globalTabsMock = vi.hoisted(() => ({+ addGlobalPluginTab: vi.fn((instanceId: string) => ({ id: `g-${instanceId}`, kind: 'plugin-view', state: { instanceId } })),+ setActiveGlobalTabId: vi.fn(),+ requestRightSidebarVisibility: vi.fn(),+}));+vi.mock('@/features/right-sidebar/globalTabs', () => ({+ addGlobalPluginTab: globalTabsMock.addGlobalPluginTab,+ setActiveGlobalTabId: globalTabsMock.setActiveGlobalTabId,+}));+vi.mock('@/features/right-sidebar/lib/sidebarCommands', () => ({+ requestRightSidebarVisibility: globalTabsMock.requestRightSidebarVisibility,+}));vi.mock('react-i18next', () => ({useTranslation: () => ({t: (key: string, options?: { name?: string }) =>@@ -77,6 +89,22 @@ describe('GhostMainViewNavEntries', () => {expect(screen.getByTestId('location').textContent).toBe('/settings?tab=ghosts&ghost=alpha');});+ // 右键「在侧边栏中打开」= 把该插件视图钉进右侧栏(全局页签)、选中并展开侧栏。+ it('offers "open in the sidebar" from the context menu and pins the plugin view as a global tab', () => {+ render(+ <MemoryRouter initialEntries={['/apps/alpha']}>+ <Routes>+ <Route path="*" element={<GhostMainViewNavEntries variant="row" />} />+ </Routes>+ </MemoryRouter>,+ );+ fireEvent.contextMenu(screen.getByRole('button', { name: 'Workspace' }));+ fireEvent.click(screen.getByText('ghostMainView.openInSidebar'));+ expect(globalTabsMock.addGlobalPluginTab).toHaveBeenCalledWith('workspace');+ expect(globalTabsMock.setActiveGlobalTabId).toHaveBeenCalledWith('g-workspace');+ expect(globalTabsMock.requestRightSidebarVisibility).toHaveBeenCalledWith('open');+ });+it('uses the native 18px rail icon geometry without a fallback tile', () => {render(<MemoryRouter initialEntries={['/apps/alpha']}>diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarTopNav.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarTopNav.test.tsxindex d4f841c425..6884850219 100644--- a/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarTopNav.test.tsx+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/SidebarTopNav.test.tsx@@ -41,7 +41,6 @@ vi.mock('@/cindy-brain/ghostMainViews', () => ({sidebarVisible: mainViewsMock.sidebarVisible,}),}));-vi.mock('@/cindy-brain/GhostPanelRestoreEntry', () => ({ GhostPanelRestoreEntry: () => null }));vi.mock('../GhostMainViewNavEntries', () => ({GhostMainViewNavEntry: ({ item, variant }: { item: { title: string }; variant: string }) =><button aria-label={item.title} data-variant={variant} />,diff --git a/apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx b/apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsxindex eb0bce95ef..ea0cb3eb1d 100644--- a/apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx+++ b/apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx@@ -6,7 +6,7 @@ import '../ui/button.css';/*** ChromeIconButton —— 标题栏 28px 圆形图标按钮基元。*- * 统一 PanelChrome、TabBar、GhostPanelWindowLayout、SidebarWindowLayout+ * 统一 TabBar、SidebarWindowLayout、SidebarTabWindowLayout* 四处的按钮视觉规格:* - 28×28 圆形,透明底* - 图标 14pxdiff --git a/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx b/apps/desktop/src/renderer/components/title-bar/WindowControls.tsxindex bba1b57d6c..9c26f69514 100644--- a/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx+++ b/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx@@ -8,7 +8,6 @@ import { Spinner } from '@/components/ui/spinner';import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { isSecondaryWindow } from '@/lib/secondaryWindow';import { isSidebarWindow } from '@/lib/sidebarWindow';-import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';import { isResourceUsageWindow } from '@/lib/resourceUsageWindow';import type {LinuxCloseBehavior,@@ -62,7 +61,6 @@ export function WindowControls({(window.electronAPI.platform !== 'win32' && window.electronAPI.platform !== 'linux') ||isSecondaryWindow() ||isSidebarWindow() ||- isGhostPanelWindow() ||isResourceUsageWindow())return;@@ -183,7 +181,6 @@ export function WindowControls({if (isSecondaryWindow() ||isSidebarWindow() ||- isGhostPanelWindow() ||isResourceUsageWindow()) {window.electronAPI.windowClose();diff --git a/apps/desktop/src/renderer/contexts/AppShellCoverContext.tsx b/apps/desktop/src/renderer/contexts/AppShellCoverContext.tsxindex 2c1de9bc72..edc202539f 100644--- a/apps/desktop/src/renderer/contexts/AppShellCoverContext.tsx+++ b/apps/desktop/src/renderer/contexts/AppShellCoverContext.tsx@@ -1,7 +1,6 @@import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react';import { useAuth } from '@/contexts/AuthContext';-import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';import { isSecondaryWindow } from '@/lib/secondaryWindow';import { isSidebarWindow } from '@/lib/sidebarWindow';@@ -33,7 +32,7 @@ const FALLBACK_VALUE: AppShellCoverContextValue = Object.freeze({});function isDerivedWindow(): boolean {- return isSecondaryWindow() || isSidebarWindow() || isGhostPanelWindow();+ return isSecondaryWindow() || isSidebarWindow();}export function AppShellCoverProvider({ children }: { children: ReactNode }) {diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsxindex 317d62dd28..272e3b8021 100644--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@ -42,7 +42,6 @@ import {import { sessionsStore } from '@/lib/sessionsStore';import { recentWorkdirsStore } from '@/lib/recentWorkdirsStore';import { isSidebarWindow } from '@/lib/sidebarWindow';-import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';import { setModelEnginePrefsOwner } from '@/state/modelEnginePrefs';import { setModelFavoritesOwner } from '@/state/modelFavorites';import { setProviderModelMemoryOwner } from '@/state/providerModelMemory';@@ -454,7 +453,7 @@ export function AuthProvider({useEffect(() => {if (!isAuthenticated || !accountDeletionRestored) return;setAccountDeletionRestored(false);- if (isSecondaryWindow() || isSidebarWindow() || isGhostPanelWindow()) return;+ if (isSecondaryWindow() || isSidebarWindow()) return;let disposed = false;void authServiceRef.current!.consumeAccountDeletionRestoredNotice()diff --git a/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx b/apps/desktop/src/renderer/contexts/EnvCheckContext.tsxindex 897b9a5b87..107ee6c640 100644--- a/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx+++ b/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx@@ -11,7 +11,6 @@ import {import { isSecondaryWindow } from '@/lib/secondaryWindow';import { isSidebarWindow } from '@/lib/sidebarWindow';-import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';/*** 由主窗派生的附属窗口(会话多开副窗 / 右侧栏子窗口 / 插件面板子窗口):@@ -19,7 +18,7 @@ import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';* (初始 'passed' + 不跑 auto-check)。*/function isDerivedWindow(): boolean {- return isSecondaryWindow() || isSidebarWindow() || isGhostPanelWindow();+ return isSecondaryWindow() || isSidebarWindow();}/* ── Types ── */diff --git a/apps/desktop/src/renderer/contexts/__tests__/AppShellCoverContext.test.tsx b/apps/desktop/src/renderer/contexts/__tests__/AppShellCoverContext.test.tsxindex 457d1443bf..5504c1036f 100644--- a/apps/desktop/src/renderer/contexts/__tests__/AppShellCoverContext.test.tsx+++ b/apps/desktop/src/renderer/contexts/__tests__/AppShellCoverContext.test.tsx@@ -19,9 +19,6 @@ vi.mock('@/lib/secondaryWindow', () => ({vi.mock('@/lib/sidebarWindow', () => ({isSidebarWindow: () => false,}));-vi.mock('@/lib/ghostPanelWindow', () => ({- isGhostPanelWindow: () => false,-}));import { AppShellCoverProvider, useAppShellCover } from '../AppShellCoverContext';diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 788ed75016..5fc1629f17 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -881,7 +881,7 @@ export function DetailsSection({value:detail.panelMinWidth === null? t('settings.ghosts.detail.panelNone')- : panelStatus || t('settings.ghosts.detail.panelNotDocked'),+ : panelStatus || t('settings.ghosts.detail.panelDismissed'),},...(detail.installDir? [diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 3a86d4e7f9..74f218de39 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -76,11 +76,10 @@ import {useGhostUnreadSummary,} from '@/cindy-brain/ghostUnreadStore';import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';-import { findSplitChildByPanelKind } from '../../../shared/layoutTree';+import { useGlobalTabs } from '@/features/right-sidebar/globalTabs';import { resolveSystemLocale } from '../../../shared/locale';import {ghostInstallApprovalToken,- ghostPanelKind,isUserInstallReservedGhostId,type GhostSetupStatus,type InstalledGhost,@@ -970,23 +969,19 @@ export function GhostPluginPage({setOpenPanelId((current) => nextOpenPanelIdForOwner(previous, panelOwnerKey, current));}, [panelOwnerKey]);+ // 停靠形态的面板现在以右侧栏全局页签承载:状态只分「在右侧栏中」与「已从右侧栏关闭」。+ const globalTabs = useGlobalTabs();const panelStatus = useMemo(() => {if (!selectedDetail || selectedDetail.panelMinWidth === null) return null;// 页签形态(面板收束):由插件页承载,没有停靠状态可言。if (selectedDetail.tabPanel) return t('settings.ghosts.detail.panelPageHosted');- try {- const kind = ghostPanelKind(selectedDetail.id);- const docked =- findSplitChildByPanelKind(window.electronAPI.layout.getStateSync().layout, kind) !== null;- return docked- ? t('settings.ghosts.detail.panelDocked', {- min: selectedDetail.panelMinWidth,- })- : t('settings.ghosts.detail.panelNotDocked');- } catch {- return t('settings.ghosts.detail.panelNotDocked');- }- }, [selectedDetail, t]);+ const inSidebar = globalTabs.some(+ (tab) => (tab.state as { instanceId?: string } | null)?.instanceId === selectedDetail.id,+ );+ return inSidebar+ ? t('settings.ghosts.detail.panelInSidebar')+ : t('settings.ghosts.detail.panelDismissed');+ }, [globalTabs, selectedDetail, t]);const handleToggle = useCallback(async (id: string, enabled: boolean, displayName: string) => {diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsxindex 341b233749..68e746a97e 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx@@ -75,7 +75,7 @@ vi.mock('react-i18next', () => ({'settings.ghosts.detail.openLocation': 'Open Install Location','settings.ghosts.detail.expandInfoValue': `Show full ${String(options?.label ?? '')}`,'settings.ghosts.detail.collapseInfoValue': `Collapse ${String(options?.label ?? '')}`,- 'settings.ghosts.detail.panelNotDocked': 'Not docked',+ 'settings.ghosts.detail.panelDismissed': 'Not docked','settings.providers.openai.title': 'OpenAI','settings.providers.xd.title': 'Cindy AI','settings.defaults.restore': 'Restore default',diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex 6ac8ab52dc..097e0bc8f8 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -66,6 +66,13 @@ import { TabBodyErrorBoundary } from './TabBodyErrorBoundary';import { useRetainedBrowserTabHosts } from './hooks/useRetainedBrowserTabHosts';import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';import { useSidebarTabWindowsState } from '@/lib/sidebarTabWindowState';+import {+ isGlobalTabId,+ removeGlobalTab,+ setActiveGlobalTabId,+ useActiveGlobalTabId,+ useGlobalTabs,+} from './globalTabs';import {mergeAvailableTabOrder,projectAvailableTabs,@@ -220,13 +227,21 @@ export function RightSidebarShell({);const getBucketSnapshot = useCallback(() => getBucket(sessionId), [sessionId]);const bucket = useSyncExternalStore(subscribeBucket, getBucketSnapshot);+ // 全局页签(不跟对话):在所有任务里都在场,切任务留在原位;与任务页签一起投影。+ const globalTabs = useGlobalTabs();+ const activeGlobalTabId = useActiveGlobalTabId();+ // 没有任务(sessionId=null)时任务桶不存在,但全局页签照常可展示——弹出窗口里+ // 承载全局页签就是这种形态。+ const contentReady = bucket.hydrated || sessionId === null;const hiddenTabIds = useMemo<ReadonlySet<string> | undefined>(() => {if (soloMode) {- return new Set(bucket.tabs.map((tab) => tab.id).filter((id) => id !== soloTabId));+ return new Set(+ [...globalTabs, ...bucket.tabs].map((tab) => tab.id).filter((id) => id !== soloTabId),+ );}const ids = Object.keys(poppedOutTabs);return ids.length > 0 ? new Set(ids) : undefined;- }, [bucket.tabs, poppedOutTabs, soloMode, soloTabId]);+ }, [bucket.tabs, globalTabs, poppedOutTabs, soloMode, soloTabId]);const previousShellVisibleRef = useRef(shellVisible);const subagentsEligibilityKnown = typeof subagentsAvailable === 'boolean';const subagentsEnabled = subagentsAvailable === true;@@ -283,8 +298,30 @@ export function RightSidebarShell({() => projectAvailableTabs(bucket.tabs, bucket.activeTabId, tabAvailability),[bucket.activeTabId, bucket.tabs, tabAvailability],);- const tabs = projectedTabs.tabs;- const activeTabId = projectedTabs.activeTabId;+ // 全局页签的可用性只看本机已装插件(插件视图运行在本机,不随任务归属变化)。+ const globalAvailability = useMemo(+ () => ({+ installedGhosts: [] as typeof installedGhosts,+ subagentsAvailable: true,+ hiddenTabIds,+ pluginViewGhosts: installedGhosts,+ }),+ [hiddenTabIds, installedGhosts],+ );+ const pinnedTabs = useMemo(+ () => projectAvailableTabs(globalTabs, null, globalAvailability).tabs,+ [globalAvailability, globalTabs],+ );+ const sessionTabs = projectedTabs.tabs;+ const sessionActiveTabId = projectedTabs.activeTabId;+ /** 侧栏可见页签 = 全局页签(钉在前) + 当前任务页签。 */+ const tabs = useMemo(() => [...pinnedTabs, ...sessionTabs], [pinnedTabs, sessionTabs]);+ // 激活位:用户选中的全局页签优先并跨任务保持;否则是任务自己的激活页签;+ // 任务没有页签时落到第一个全局页签。+ const activeTabId =+ activeGlobalTabId && pinnedTabs.some((tab) => tab.id === activeGlobalTabId)+ ? activeGlobalTabId+ : sessionActiveTabId ?? pinnedTabs[0]?.id ?? null;// 首帧只挂当前激活 tab。其余 tab 在浏览器空闲期逐个补挂载,随后继续按原有// keep-alive 语义保留组件 / webview / 编辑器状态。这样恢复一个多 tab 会话时,@@ -358,16 +395,16 @@ export function RightSidebarShell({useEffect(() => {// 单页签独立窗口不写激活位:它只投影自己承载的页签,激活位归主窗侧栏管。if (soloMode || !subagentsEligibilityKnown) return;- if (!bucket.hydrated || !sessionId || bucket.activeTabId === activeTabId) return;- void setActiveTab(sessionId, activeTabId).catch((err) => {+ if (!bucket.hydrated || !sessionId || bucket.activeTabId === sessionActiveTabId) return;+ void setActiveTab(sessionId, sessionActiveTabId).catch((err) => {log.error('unavailable active-tab reconciliation failed', {sessionId,- activeTabId,+ activeTabId: sessionActiveTabId,err,});});}, [- activeTabId,+ sessionActiveTabId,bucket.activeTabId,bucket.hydrated,sessionId,@@ -437,14 +474,15 @@ export function RightSidebarShell({// - hydrated 后首帧 prev===null 不触发(区分"刚加载出来就是空"与"关到空");// - 展开一个本就 0-tab 的 session 也不会被立刻折叠,用户仍能在 EmptyState 加 tab。// sessionId 变化时重置计数,避免"切到一个空 session"被误判成"关空"。+ // 全局页签计入可见页签数:有全局页签在场时侧栏不会因任务页签关空而自动收起。useEffect(() => {- if (!bucket.hydrated) return; // 未 hydrate 的空数组不算"关空"+ if (!contentReady) return; // 未 hydrate 的空数组不算"关空"const prev = prevTabCountRef.current;prevTabCountRef.current = tabs.length;if (prev !== null && prev > 0 && tabs.length === 0) {onAllTabsClosed?.();}- }, [bucket.hydrated, tabs.length, onAllTabsClosed]);+ }, [contentReady, tabs.length, onAllTabsClosed]);const handleAdd = useCallback((kind: TabKindId) => {@@ -489,6 +527,11 @@ export function RightSidebarShell({const handleClose = useCallback((tabId: string) => {+ // 全局页签的关闭是全局动作(所有任务里一起消失),不进任务桶。+ if (isGlobalTabId(tabId)) {+ removeGlobalTab(tabId);+ return;+ }if (!sessionId) return;void closeTab(sessionId, tabId).catch((err) => {log.error('handleClose failed', { sessionId, tabId, err });@@ -499,6 +542,12 @@ export function RightSidebarShell({const handleActivate = useCallback((tabId: string) => {+ if (isGlobalTabId(tabId)) {+ setActiveGlobalTabId(tabId);+ return;+ }+ // 选中任务页签 = 离开全局页签;任务自己的激活位照常落库。+ setActiveGlobalTabId(null);if (!sessionId) return;void setActiveTab(sessionId, tabId).catch((err) => {log.error('handleActivate failed', { sessionId, tabId, err });@@ -532,12 +581,10 @@ export function RightSidebarShell({: (activeIndex + (direction === 'next' ? 1 : -1) + tabs.length) % tabs.length;const nextTabId = tabs[nextIndex]?.id;if (!nextTabId || nextTabId === activeTabId) return false;- void setActiveTab(sessionId, nextTabId).catch((err) => {- log.error('cycle right sidebar tab failed', { sessionId, direction, nextTabId, err });- });+ handleActivate(nextTabId);return true;},- [activeTabId, sessionId, shellVisible, tabs],+ [activeTabId, handleActivate, sessionId, shellVisible, tabs],);useAppShortcut('right-tab-prev', () => handleCycleTab('prev'), {@@ -555,7 +602,8 @@ export function RightSidebarShell({const handleCloseOthers = useCallback(async (keepTabId: string) => {if (!sessionId) return;- const targets = tabs.filter((t) => t.id !== keepTabId).map((t) => t.id);+ // 「关闭其他 / 关闭所有」只作用于任务页签;全局页签要用户逐个显式关闭。+ const targets = sessionTabs.filter((t) => t.id !== keepTabId).map((t) => t.id);for (const tabId of targets) {try {await closeTab(sessionId, tabId);@@ -565,13 +613,13 @@ export function RightSidebarShell({}}},- [sessionId, tabs],+ [sessionId, sessionTabs],);// 右键菜单"关闭所有":关掉本 session 的全部 tab。const handleCloseAll = useCallback(async () => {if (!sessionId) return;- const targets = tabs.map((t) => t.id);+ const targets = sessionTabs.map((t) => t.id);for (const tabId of targets) {try {await closeTab(sessionId, tabId);@@ -580,7 +628,7 @@ export function RightSidebarShell({break;}}- }, [sessionId, tabs]);+ }, [sessionId, sessionTabs]);// popup 路由已挪到窗口级常驻模块(lib/popupRouter.ts):订阅不随 Shell 生命// 周期,用户离开聊天视图 / main 端归属等待期间 route 切换都不再丢 popup。@@ -613,7 +661,7 @@ export function RightSidebarShell({);const bodyHosts = useRetainedBrowserTabHosts(- bucket.hydrated+ contentReady? tabs.filter((tab) => tab.id === activeTabId || deferredMountedTabIds.has(tab.id)).map((tab) => ({ tab, sessionId, workdir, remoteHostId, deviceLinkDeviceId }))@@ -676,7 +724,8 @@ export function RightSidebarShell({「+」wrapper 传 h-[30px](pill 高)而非 h-full:TabStrip 根高度由内容驱动,百分比高度会退化。 */}<TabStrip- tabs={tabs}+ tabs={sessionTabs}+ pinnedTabs={pinnedTabs}activeTabId={activeTabId}sessionId={sessionId}onActivate={handleActivate}@@ -727,7 +776,8 @@ export function RightSidebarShell({</div>) : (<TabBar- tabs={tabs}+ tabs={sessionTabs}+ pinnedTabs={pinnedTabs}activeTabId={activeTabId}sessionId={sessionId}onActivate={handleActivate}@@ -752,7 +802,7 @@ export function RightSidebarShell({{/* 首次切到某 session 时 cache 尚未 hydrate(等 IPC list 回包),保留 panel背景而非闪 EmptyState —— EmptyState 是"真的没 tab"的 Welcome 内容。sessionId 为 null 也走这条:Shell 不显示任何内容(无激活会话)。 */}- {!bucket.hydrated || soloMode ? null : tabs.length === 0 ? (+ {!contentReady || soloMode || !sessionId ? null : tabs.length === 0 ? (// tab 列表为空时永远渲染 EmptyState。审查页签只通过「+」dropdown 或// EmptyState 的"打开审查"入口由用户主动创建。<EmptyStatediff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsxindex e4885e680e..6cd6ced4da 100644--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx@@ -19,7 +19,7 @@*/import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Activity, Bot, FolderTree, Globe, Terminal, GitPullRequestArrow, UsersRound, LayoutGrid, ListTodo, Plus, Puzzle, X, Maximize2, Minimize2, PanelRightClose, PictureInPicture2, Wrench } from 'lucide-react';+import { Activity, Bot, FolderTree, Globe, Terminal, GitPullRequestArrow, UsersRound, LayoutGrid, ListTodo, Pin, Plus, Puzzle, X, Maximize2, Minimize2, PanelRightClose, PictureInPicture2, Wrench } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';@@ -41,6 +41,8 @@ import type { BuiltinTabKindId, TabKindId, TabState } from './types';interface TabBarProps {tabs: TabState[];+ /** 全局页签(不跟对话):钉在条首,不参与拖拽排序,切任务不变。 */+ pinnedTabs?: TabState[];activeTabId: string | null;sessionId?: string | null;onActivate: (id: string) => void;@@ -85,6 +87,8 @@ interface TabBarProps {interface TabStripProps {tabs: TabState[];+ /** 全局页签(不跟对话):钉在条首,不参与拖拽排序,切任务不变。 */+ pinnedTabs?: TabState[];activeTabId: string | null;sessionId?: string | null;onActivate: (id: string) => void;@@ -129,6 +133,7 @@ const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {'bot-workbench': LayoutGrid,'resource-usage': Activity,'cindy-make': Wrench,+ 'plugin-view': Puzzle,};const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {@@ -144,6 +149,7 @@ const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {'bot-workbench': 'bots.workbench.title','resource-usage': 'rightSidebar.tabs.kinds.resourceUsage','cindy-make': 'settings.cindyMake.title',+ 'plugin-view': 'rightSidebar.tabs.kinds.pluginView',};/**@@ -190,6 +196,7 @@ function scrollTabIntoContainerView(container: HTMLElement | null, tab: HTMLElemexport function TabBar({tabs,+ pinnedTabs,activeTabId,sessionId,onActivate,@@ -222,6 +229,7 @@ export function TabBar({><TabStriptabs={tabs}+ pinnedTabs={pinnedTabs}activeTabId={activeTabId}sessionId={sessionId}onActivate={onActivate}@@ -288,6 +296,7 @@ export function TabBar({export function TabStrip({tabs,+ pinnedTabs = [],activeTabId,sessionId = null,onActivate,@@ -315,6 +324,8 @@ export function TabStrip({const [contextMenu, setContextMenu] = useState<{pos: { x: number; y: number };tabId: string;+ /** 全局页签:右键只有「关闭」与「在独立窗口中打开」,不提供关闭其他 / 全部。 */+ pinned: boolean;} | null>(null);const closeContextMenu = () => setContextMenu(null);@@ -395,6 +406,34 @@ export function TabStrip({} as React.CSSProperties}>+ {pinnedTabs.length > 0 && (+ <div+ data-testid="right-sidebar-pinned-tabs"+ className={cn('flex w-max gap-1', pillVariant === 'chip' ? 'items-center' : 'items-end')}+ >+ {pinnedTabs.map((tab) => (+ <TabPill+ key={tab.id}+ tab={tab}+ active={tab.id === activeTabId}+ pinned+ pillVariant={pillVariant}+ sessionId={sessionId}+ fallbackLabel={t(labelKeyForTabKind(tab.kind))}+ t={t}+ onActivate={() => onActivate(tab.id)}+ onClose={() => onClose(tab.id)}+ onContextMenu={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setContextMenu({ pos: { x: e.clientX, y: e.clientY }, tabId: tab.id, pinned: true });+ }}+ scrollContainerRef={tabsScrollRef}+ closeAriaLabel={t('rightSidebar.tabs.tabCloseAria')}+ />+ ))}+ </div>+ )}<SortableListitems={tabs}getId={(tab) => tab.id}@@ -418,7 +457,7 @@ export function TabStrip({onContextMenu={(e) => {e.preventDefault();e.stopPropagation();- setContextMenu({ pos: { x: e.clientX, y: e.clientY }, tabId: tab.id });+ setContextMenu({ pos: { x: e.clientX, y: e.clientY }, tabId: tab.id, pinned: false });}}scrollContainerRef={tabsScrollRef}closeAriaLabel={t('rightSidebar.tabs.tabCloseAria')}@@ -500,25 +539,29 @@ export function TabStrip({>{t('rightSidebar.tabs.contextMenu.close')}</DropdownMenuItem>- <DropdownMenuItem- disabled={tabs.length <= 1}- onClick={() => {- if (tabs.length <= 1) return;- const id = contextMenu.tabId;- closeContextMenu();- onCloseOthers?.(id);- }}- >- {t('rightSidebar.tabs.contextMenu.closeOthers')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => {- closeContextMenu();- onCloseAll?.();- }}- >- {t('rightSidebar.tabs.contextMenu.closeAll')}- </DropdownMenuItem>+ {!contextMenu.pinned && (+ <DropdownMenuItem+ disabled={tabs.length <= 1}+ onClick={() => {+ if (tabs.length <= 1) return;+ const id = contextMenu.tabId;+ closeContextMenu();+ onCloseOthers?.(id);+ }}+ >+ {t('rightSidebar.tabs.contextMenu.closeOthers')}+ </DropdownMenuItem>+ )}+ {!contextMenu.pinned && (+ <DropdownMenuItem+ onClick={() => {+ closeContextMenu();+ onCloseAll?.();+ }}+ >+ {t('rightSidebar.tabs.contextMenu.closeAll')}+ </DropdownMenuItem>+ )}{onDetachTab && (<DropdownMenuItemonClick={() => {@@ -541,6 +584,7 @@ export function TabStrip({function TabPill({tab,active,+ pinned = false,pillVariant,sessionId,fallbackLabel,@@ -553,6 +597,8 @@ function TabPill({}: {tab: TabState;active: boolean;+ /** 全局页签:标题前带图钉,提示它不随任务切换。 */+ pinned?: boolean;/** 见 TabStripProps.pillVariant:flush = 贴底三边框 tab,chip = 居中四边框 chip。 */pillVariant: 'flush' | 'chip';sessionId: string | null;@@ -582,6 +628,7 @@ function TabPill({return (<divref={pillRef}+ data-pinned={pinned || undefined}onContextMenu={onContextMenu}// 中键(滚轮键)关闭当前 tab —— 对齐浏览器等多 tab 应用的通用习惯。// auxclick 对所有非主键(中/右键)都会触发,这里只认中键(button === 1);@@ -615,6 +662,13 @@ function TabPill({onClick={onActivate}className="flex items-center gap-1.5 max-w-[160px]">+ {pinned && (+ <Pin+ size={10}+ aria-label={t('rightSidebar.tabs.pinnedAria')}+ className="shrink-0 text-[var(--text-tertiary)]"+ />+ )}<spanclassName={cn('shrink-0',diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.tsindex c513fca5cc..f4a2d76c92 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts@@ -32,6 +32,12 @@ vi.mock('@/lib/toast', () => ({vi.mock('../plugins', () => ({}));+const installedGhostsMock = vi.hoisted(() => ({ list: [] as unknown[] }));+vi.mock('@/cindy-brain/useInstalledGhosts', () => ({+ useInstalledGhosts: () => installedGhostsMock.list,+ readInstalledGhostsSnapshot: () => installedGhostsMock.list,+}));+// Real guest preload and host, joined only at the Electron IPC boundary.const commentIpc = vi.hoisted(() => ({listeners: new Map<string, (event: unknown, payload: unknown) => void>(),@@ -77,6 +83,11 @@ import {__resetSidebarTabWindowsStateForTest,__setSidebarTabWindowsStateForTest,} from '@/lib/sidebarTabWindowState';+import {+ __resetGlobalTabsForTest,+ addGlobalPluginTab,+ getActiveGlobalTabId,+} from '../globalTabs';import { toast } from '@/lib/toast';import { writePanelCollapsed } from '@/layout/collapsePrefs';import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';@@ -299,9 +310,94 @@ describe('RightSidebarShell empty state', () => {_resetPopupRouterForTests();_resetNativePopupTabsForTests();__resetSidebarTabWindowsStateForTest();+ __resetGlobalTabsForTest();+ window.localStorage.clear();+ installedGhostsMock.list = [];delete (window as unknown as { electronAPI?: unknown }).electronAPI;});+ // 测试价值+ // - 生产入口与可观察结果:RightSidebarShell 同时投影全局页签(globalTabs,不跟对话)与任务+ // 页签;可观察的是全局页签钉在条首并带图钉、切任务后仍在、点它只改本窗口的全局激活位+ // 而不写任务桶的 setActive、有全局页签在场时任务页签关空不触发自动收起、关闭全局页签+ // 是全局动作、插件停用后它从投影里消失但数据保留。+ // - Bug / 规则依据:右侧栏「跟对话 / 不跟对话」两类页签模型(本 PR)。+ // - 现有覆盖缺口:其余用例只覆盖任务桶。+ // - 最小失败输入:一个 plugin-view 全局页签 + 一个任务页签,切换任务。+ // - tier:unit(jsdom,localStorage 全局页签 + 进程内 store)。+ it('pins global plugin-view tabs across tasks without touching the task bucket active marker', async () => {+ installedGhostsMock.list = [+ { manifest: { id: 'alpha', name: 'Alpha', panel: { html: 'p.html', title: 'Alpha Panel' } }, enabled: true },+ ];+ const globalTab = addGlobalPluginTab('alpha')!;+ const onAllTabsClosed = vi.fn();+ tabsIpc.list.mockResolvedValueOnce({+ tabs: [{ id: 'tab-files', kind: 'file-browser', state: null }],+ activeTabId: 'tab-files',+ });+ const { rerender } = render(+ createElement(RightSidebarShell, {+ sessionId: 's1',+ workdir: '/tmp/repo',+ remoteHostId: null,+ isMac: true,+ unifiedTopbar: true,+ subagentsAvailable: false,+ onAllTabsClosed,+ }),+ );+ await waitFor(() => expect(screen.getByText('rightSidebar.tabs.kinds.fileBrowser')).toBeTruthy());+ const pinned = screen.getByTestId('right-sidebar-pinned-tabs');+ expect(pinned.textContent).toContain('rightSidebar.tabs.kinds.pluginView');+ expect(pinned.querySelector('[data-pinned]')).toBeTruthy();++ // 选中全局页签:只改本窗口的全局激活位,任务桶的 setActive 不落库。+ tabsIpc.setActive.mockClear();+ fireEvent.click(screen.getByText('rightSidebar.tabs.kinds.pluginView'));+ expect(getActiveGlobalTabId()).toBe(globalTab.id);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(tabsIpc.setActive).not.toHaveBeenCalled();++ // 切到空任务:全局页签还在、仍是激活页签;任务没有页签但不渲染空态、不触发收起。+ tabsIpc.list.mockResolvedValueOnce({ tabs: [], activeTabId: null });+ rerender(+ createElement(RightSidebarShell, {+ sessionId: 's2',+ workdir: '/tmp/repo',+ remoteHostId: null,+ isMac: true,+ unifiedTopbar: true,+ subagentsAvailable: false,+ onAllTabsClosed,+ }),+ );+ await waitFor(() => expect(getBucket('s2').hydrated).toBe(true));+ expect(screen.getByTestId('right-sidebar-pinned-tabs').textContent).toContain(+ 'rightSidebar.tabs.kinds.pluginView',+ );+ expect(screen.queryByText('rightSidebar.tabs.empty.title')).toBeNull();+ expect(onAllTabsClosed).not.toHaveBeenCalled();++ // 插件停用:页签从投影消失(数据保留),没有别的页签了才算关空。+ installedGhostsMock.list = [+ { manifest: { id: 'alpha', name: 'Alpha', panel: { html: 'p.html', title: 'Alpha Panel' } }, enabled: false },+ ];+ rerender(+ createElement(RightSidebarShell, {+ sessionId: 's2',+ workdir: '/tmp/other',+ remoteHostId: null,+ isMac: true,+ unifiedTopbar: true,+ subagentsAvailable: false,+ onAllTabsClosed,+ }),+ );+ await waitFor(() => expect(screen.queryByTestId('right-sidebar-pinned-tabs')).toBeNull());+ expect(screen.getByText('rightSidebar.tabs.empty.title')).toBeTruthy();+ await waitFor(() => expect(onAllTabsClosed).toHaveBeenCalledOnce());+ });+it.each([{ otherBrowser: false, release: 'close' },{ otherBrowser: true, release: 'close' },diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.tsnew file mode 100644index 0000000000..a80e0052c8--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.ts@@ -0,0 +1,103 @@+// @vitest-environment jsdom+/**+ * 测试价值+ * - 生产入口与可观察结果:globalTabs 的 add / remove / reorder / active 与 localStorage 持久化;+ * 可观察的是全局页签列表按数据所有者分键保存、用户关闭后记入 dismissed、另一个窗口的+ * 写入通过 storage 事件同步进来、激活位只认仍在列表里的页签。+ * - Bug / 规则依据:右侧栏「不跟对话」的全局页签(本 PR);多窗口共享同一份列表是产品承诺+ * (弹出的页签窗口与主窗看到同一组全局页签)。+ * - 现有覆盖缺口:ghostPanels.test 只覆盖与已装清单的对齐,不覆盖用户动作与跨窗口同步。+ * - 最小失败输入:加一个页签后切换 owner、或在另一窗口写 localStorage。+ * - tier:unit(jsdom localStorage + storage 事件)。+ */++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import {+ __resetGlobalTabsForTest,+ addGlobalPluginTab,+ getActiveGlobalTabId,+ getGlobalTabs,+ getGlobalTabsSnapshot,+ removeGlobalTab,+ reorderGlobalTabs,+ sanitizeGlobalTabsSnapshot,+ setActiveGlobalTabId,+} from '../globalTabs';++beforeEach(() => {+ window.localStorage.clear();+ __resetGlobalTabsForTest();+ setDataOwnerGeneration('owner-a', 1);+});++afterEach(() => {+ __resetGlobalTabsForTest();+ window.localStorage.clear();+});++describe('globalTabs', () => {+ it('adds one tab per plugin instance, persists per data owner and remembers dismissals', () => {+ const tab = addGlobalPluginTab('alpha')!;+ expect(addGlobalPluginTab('alpha')).toBe(tab);+ expect(getGlobalTabs()).toHaveLength(1);+ expect(window.localStorage.getItem('xdt:rightSidebarGlobalTabs:v1:owner-a')).toContain('alpha');++ // 另一个数据所有者看不到这份列表。+ setDataOwnerGeneration('owner-b', 1);+ expect(getGlobalTabs()).toEqual([]);+ setDataOwnerGeneration('owner-a', 1);+ expect(getGlobalTabs()).toHaveLength(1);++ setActiveGlobalTabId(tab.id);+ expect(getActiveGlobalTabId()).toBe(tab.id);+ removeGlobalTab(tab.id);+ expect(getGlobalTabs()).toEqual([]);+ expect(getGlobalTabsSnapshot().dismissedInstanceIds).toEqual(['alpha']);+ // 关掉的页签不再是激活位;用户主动重新加入会清掉关闭记录。+ expect(getActiveGlobalTabId()).toBeNull();+ addGlobalPluginTab('alpha');+ expect(getGlobalTabsSnapshot().dismissedInstanceIds).toEqual([]);+ });++ it('reorders only with a complete id list and picks up writes from other windows', () => {+ const a = addGlobalPluginTab('alpha')!;+ const b = addGlobalPluginTab('beta')!;+ reorderGlobalTabs([b.id]);+ expect(getGlobalTabs().map((tab) => tab.id)).toEqual([a.id, b.id]);+ reorderGlobalTabs([b.id, a.id]);+ expect(getGlobalTabs().map((tab) => tab.id)).toEqual([b.id, a.id]);++ // 另一个窗口写入同一键:storage 事件让本窗口重新读取。+ const key = 'xdt:rightSidebarGlobalTabs:v1:owner-a';+ window.localStorage.setItem(+ key,+ JSON.stringify({+ tabs: [{ id: 'g_other', kind: 'plugin-view', state: { instanceId: 'gamma' } }],+ dismissedInstanceIds: [],+ }),+ );+ window.dispatchEvent(new StorageEvent('storage', { key }));+ expect(getGlobalTabs().map((tab) => tab.id)).toEqual(['g_other']);+ });++ it('drops malformed persisted entries instead of loading them', () => {+ expect(+ sanitizeGlobalTabsSnapshot({+ tabs: [+ { id: 'ok', kind: 'plugin-view', state: { instanceId: 'alpha' } },+ { id: 'ok', kind: 'plugin-view', state: { instanceId: 'dup' } },+ { id: 'bad-kind', kind: 'terminal', state: {} },+ { id: 'bad-state', kind: 'plugin-view', state: null },+ 'junk',+ ],+ dismissedInstanceIds: ['x', 3, ''],+ }),+ ).toEqual({+ tabs: [{ id: 'ok', kind: 'plugin-view', state: { instanceId: 'alpha' } }],+ dismissedInstanceIds: ['x'],+ });+ expect(sanitizeGlobalTabsSnapshot('nope')).toEqual({ tabs: [], dismissedInstanceIds: [] });+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabAvailability.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabAvailability.test.tsindex ff37ce6f13..9c50dd50a0 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabAvailability.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/tabAvailability.test.ts@@ -13,6 +13,27 @@ const affected = {retirement: { id: 'embedded-ios-simulator', eligible: true, unread: true },} as InstalledGhost;describe('sidebar availability', () => {+ // 全局插件视图页签:插件卸载 / 停用 / 失去面板声明时隐藏(数据保留),与远程任务无关。+ it('hides plugin-view tabs whose plugin is gone or disabled, only when the local plugin list is given', () => {+ const pluginTabs = [+ { id: 'view-a', kind: 'plugin-view', state: { instanceId: 'alpha' } },+ { id: 'view-b', kind: 'plugin-view', state: { instanceId: 'beta' } },+ { id: 'view-c', kind: 'plugin-view', state: { instanceId: 'gone' } },+ ] as unknown as TabState[];+ const alpha = { manifest: { id: 'alpha', panel: { html: 'p.html' } }, enabled: true } as InstalledGhost;+ const beta = { manifest: { id: 'beta', mainView: { html: 'm.html' } }, enabled: false } as InstalledGhost;+ const visible = projectAvailableTabs(pluginTabs, 'view-b', {+ installedGhosts: [],+ subagentsAvailable: true,+ pluginViewGhosts: [alpha, beta],+ });+ expect(visible.tabs.map((tab) => tab.id)).toEqual(['view-a']);+ expect(visible.activeTabId).toBe('view-a');+ // 不提供本机插件清单(如纯投影场景)时不做过滤。+ expect(+ projectAvailableTabs(pluginTabs, null, { installedGhosts: [], subagentsAvailable: true }).tabs,+ ).toHaveLength(3);+ });it('filters persisted Cindy Make tabs when the product is disabled', () => {const cindyTabs = [{ id: 'file', kind: 'file-browser', state: null },diff --git a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.tsnew file mode 100644index 0000000000..4984282b86--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts@@ -0,0 +1,308 @@+/**+ * globalTabs —— 右侧栏「不跟对话」的全局页签。+ *+ * 右侧栏的页签分两类:任务页签(store.ts,按任务分桶、切任务跟着换)与全局页签+ * (本模块,全局一份、切任务留在原位)。全局页签今天只有一种内容:插件视图+ * (kind `plugin-view`,承载插件的 `mainView` 或 `panel` 页面)。+ *+ * 持久化:renderer 自有的 localStorage(按数据所有者分键,重启保留,不经 main),+ * 与旧停靠面板的最小化状态同一条路;`storage` 事件做跨窗口同步(主窗 / 副窗 /+ * 弹出的页签窗口各自一份镜像)。存的是 UI 配置,不是任务数据,所以不进 SQLite。+ *+ * 兼容:插件 manifest 里声明了 `panel`(非 `tab` 形态)的插件,启用后自动以全局页签+ * 出现(reconcileGlobalPluginTabs),用户关掉后记入 dismissed 不再自动加回;卸载即+ * 清掉它的页签与 dismissed 记录,重装再按首次启用处理。`mainView` 插件不自动加,+ * 由左侧栏入口「在侧边栏中打开」加入。+ */++import { useSyncExternalStore } from 'react';++import type { InstalledGhost } from '../../../shared/ghost';+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import { createLogger } from '@/lib/logger';+import { isSidebarTabWindow } from '@/lib/sidebarTabWindow';+import { isTabPoppedOut } from '@/lib/sidebarTabWindowState';+import type { TabState } from './types';++const log = createLogger('rightSidebar.globalTabs');++const STORAGE_KEY_PREFIX = 'xdt:rightSidebarGlobalTabs:v1:';+const MAX_GLOBAL_TABS = 20;++export interface PluginViewTabState {+ /** 插件物理实例 id(storage part)。 */+ instanceId: string;+}++export interface GlobalTabsSnapshot {+ tabs: TabState[];+ /** 用户主动关掉过、不再自动加回的插件实例。 */+ dismissedInstanceIds: string[];+}++const EMPTY: GlobalTabsSnapshot = Object.freeze({+ tabs: [],+ dismissedInstanceIds: [],+}) as GlobalTabsSnapshot;++let cache: GlobalTabsSnapshot | null = null;+let cacheOwnerKey: string | null = null;+/** 当前窗口里被激活的全局页签;切任务时保持,选中任务页签时清空。不持久化。 */+let activeGlobalTabId: string | null = null;+const subscribers = new Set<() => void>();+let storageListenerWired = false;++function ownerKey(): string {+ return STORAGE_KEY_PREFIX + (getDataOwnerGeneration().dataOwnerId ?? 'none');+}++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v);+}++/** 解析并清洗持久化数据:坏条目整条丢弃,fail closed 不进状态。 */+export function sanitizeGlobalTabsSnapshot(raw: unknown): GlobalTabsSnapshot {+ if (!isPlainObject(raw)) return EMPTY;+ const tabs: TabState[] = [];+ const seen = new Set<string>();+ if (Array.isArray(raw.tabs)) {+ for (const entry of raw.tabs) {+ if (!isPlainObject(entry)) continue;+ if (typeof entry.id !== 'string' || !entry.id || seen.has(entry.id)) continue;+ if (entry.kind !== 'plugin-view') continue;+ if (!isPlainObject(entry.state) || typeof entry.state.instanceId !== 'string') continue;+ seen.add(entry.id);+ tabs.push({+ id: entry.id,+ kind: 'plugin-view',+ state: { instanceId: entry.state.instanceId } satisfies PluginViewTabState,+ });+ if (tabs.length >= MAX_GLOBAL_TABS) break;+ }+ }+ const dismissedInstanceIds = Array.isArray(raw.dismissedInstanceIds)+ ? raw.dismissedInstanceIds.filter((id): id is string => typeof id === 'string' && !!id)+ : [];+ return { tabs, dismissedInstanceIds };+}++function load(): GlobalTabsSnapshot {+ try {+ const raw = window.localStorage.getItem(ownerKey());+ if (!raw) return EMPTY;+ return sanitizeGlobalTabsSnapshot(JSON.parse(raw));+ } catch {+ return EMPTY;+ }+}++function notify(): void {+ for (const cb of [...subscribers]) cb();+}++function ensureStorageListener(): void {+ if (storageListenerWired || typeof window === 'undefined') return;+ storageListenerWired = true;+ window.addEventListener('storage', (event) => {+ if (event.key !== null && event.key !== cacheOwnerKey) return;+ cache = null;+ notify();+ });+}++export function getGlobalTabsSnapshot(): GlobalTabsSnapshot {+ const key = ownerKey();+ if (cache === null || cacheOwnerKey !== key) {+ cache = load();+ cacheOwnerKey = key;+ ensureStorageListener();+ }+ return cache;+}++export function getGlobalTabs(): TabState[] {+ return getGlobalTabsSnapshot().tabs;+}++export function isGlobalTabId(tabId: string): boolean {+ return getGlobalTabs().some((tab) => tab.id === tabId);+}++export function findGlobalTab(tabId: string): TabState | null {+ return getGlobalTabs().find((tab) => tab.id === tabId) ?? null;+}++function persist(next: GlobalTabsSnapshot): void {+ const key = ownerKey();+ cache = next;+ cacheOwnerKey = key;+ try {+ if (next.tabs.length === 0 && next.dismissedInstanceIds.length === 0) {+ window.localStorage.removeItem(key);+ } else {+ window.localStorage.setItem(key, JSON.stringify(next));+ }+ } catch (err) {+ log.warn('persist global tabs failed', { err });+ }+ notify();+}++function makeTabId(): string {+ return `g_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;+}++/**+ * 加入(或返回已有的)某个插件的全局页签。幂等:同一实例只有一个页签。+ * 用户手动加入会清掉它的 dismissed 记录。+ */+export function addGlobalPluginTab(instanceId: string): TabState | null {+ const current = getGlobalTabsSnapshot();+ const existing = current.tabs.find(+ (tab) => (tab.state as PluginViewTabState | null)?.instanceId === instanceId,+ );+ const dismissed = current.dismissedInstanceIds.filter((id) => id !== instanceId);+ if (existing) {+ if (dismissed.length !== current.dismissedInstanceIds.length) {+ persist({ tabs: current.tabs, dismissedInstanceIds: dismissed });+ }+ return existing;+ }+ if (current.tabs.length >= MAX_GLOBAL_TABS) {+ log.warn('global tab limit reached', { instanceId });+ return null;+ }+ const tab: TabState = {+ id: makeTabId(),+ kind: 'plugin-view',+ state: { instanceId } satisfies PluginViewTabState,+ };+ persist({ tabs: [...current.tabs, tab], dismissedInstanceIds: dismissed });+ return tab;+}++/** 用户关闭全局页签:全局动作,同时记 dismissed,插件不再自动加回。 */+export function removeGlobalTab(tabId: string): void {+ const current = getGlobalTabsSnapshot();+ const tab = current.tabs.find((candidate) => candidate.id === tabId);+ if (!tab) return;+ const instanceId = (tab.state as PluginViewTabState).instanceId;+ const dismissed = current.dismissedInstanceIds.includes(instanceId)+ ? current.dismissedInstanceIds+ : [...current.dismissedInstanceIds, instanceId];+ if (activeGlobalTabId === tabId) activeGlobalTabId = null;+ persist({+ tabs: current.tabs.filter((candidate) => candidate.id !== tabId),+ dismissedInstanceIds: dismissed,+ });+ // 页签正弹在独立窗口里:窗口没有内容可交回,直接销毁(与任务页签同一规则)。+ if (!isSidebarTabWindow() && isTabPoppedOut(tabId)) {+ void window.electronAPI?.sidebarTabWindow?.closeForTab(tabId).catch((err) => {+ log.warn('close sidebar tab window for removed global tab failed', { tabId, err });+ });+ }+}++export function reorderGlobalTabs(orderedIds: string[]): void {+ const current = getGlobalTabsSnapshot();+ if (orderedIds.length !== current.tabs.length) return;+ const byId = new Map(current.tabs.map((tab) => [tab.id, tab]));+ const next: TabState[] = [];+ for (const id of orderedIds) {+ const tab = byId.get(id);+ if (!tab) return;+ next.push(tab);+ }+ persist({ tabs: next, dismissedInstanceIds: current.dismissedInstanceIds });+}++/** 停靠形态(非 `tab`)的插件面板 = 应自动出现在右侧栏的全局页签。 */+export function isAutoGlobalPanelGhost(ghost: InstalledGhost): boolean {+ return (+ ghost.enabled !== false &&+ ghost.manifest.panel !== undefined &&+ ghost.manifest.panel.position !== 'tab'+ );+}++/** 插件是否能作为全局页签承载(有 mainView 或停靠形态 panel 的已启用插件)。 */+export function isGlobalTabCapableGhost(ghost: InstalledGhost): boolean {+ return (+ ghost.enabled !== false &&+ (ghost.manifest.mainView !== undefined || isAutoGlobalPanelGhost(ghost))+ );+}++/**+ * 与已装清单对齐(启动 + ghosts:changed):+ * - 已启用、声明停靠面板、未被用户关掉的插件 → 自动加页签(存量插件兼容:+ * 升级前靶在布局树里的停靠面板,升级后出现在右侧栏,用户什么都不用做);+ * - 清单里不存在的实例 → 删页签与 dismissed 记录(重装视同首次启用)。+ * 停用的插件页签**保留**(投影时按可用性隐藏),重新启用原位回来。+ */+export function reconcileGlobalPluginTabs(ghosts: readonly InstalledGhost[]): void {+ const current = getGlobalTabsSnapshot();+ const installed = new Map(ghosts.map((ghost) => [installedGhostStoragePart(ghost), ghost]));+ let tabs = current.tabs.filter((tab) =>+ installed.has((tab.state as PluginViewTabState).instanceId),+ );+ const dismissed = current.dismissedInstanceIds.filter((id) => installed.has(id));+ const present = new Set(tabs.map((tab) => (tab.state as PluginViewTabState).instanceId));+ for (const [instanceId, ghost] of installed) {+ if (!isAutoGlobalPanelGhost(ghost)) continue;+ if (present.has(instanceId) || dismissed.includes(instanceId)) continue;+ if (tabs.length >= MAX_GLOBAL_TABS) break;+ tabs = [...tabs, { id: makeTabId(), kind: 'plugin-view', state: { instanceId } }];+ present.add(instanceId);+ }+ if (+ tabs.length === current.tabs.length &&+ tabs.every((tab, index) => tab === current.tabs[index]) &&+ dismissed.length === current.dismissedInstanceIds.length+ ) {+ return;+ }+ if (activeGlobalTabId && !tabs.some((tab) => tab.id === activeGlobalTabId)) {+ activeGlobalTabId = null;+ }+ persist({ tabs, dismissedInstanceIds: dismissed });+}++export function getActiveGlobalTabId(): string | null {+ if (activeGlobalTabId && !isGlobalTabId(activeGlobalTabId)) activeGlobalTabId = null;+ return activeGlobalTabId;+}++/** 选中全局页签(null = 回到任务页签)。只影响本窗口。 */+export function setActiveGlobalTabId(tabId: string | null): void {+ const next = tabId && isGlobalTabId(tabId) ? tabId : null;+ if (next === activeGlobalTabId) return;+ activeGlobalTabId = next;+ notify();+}++export function subscribeGlobalTabs(cb: () => void): () => void {+ getGlobalTabsSnapshot();+ subscribers.add(cb);+ return () => {+ subscribers.delete(cb);+ };+}++/** React hook:全局页签列表(引用变化 = 有写入或跨窗口同步)。 */+export function useGlobalTabs(): TabState[] {+ return useSyncExternalStore(subscribeGlobalTabs, getGlobalTabs);+}++export function useActiveGlobalTabId(): string | null {+ return useSyncExternalStore(subscribeGlobalTabs, getActiveGlobalTabId);+}++/** 仅测试用。 */+export function __resetGlobalTabsForTest(): void {+ cache = null;+ cacheOwnerKey = null;+ activeGlobalTabId = null;+ subscribers.clear();+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.tsindex c3df787785..67b5f33bfb 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts@@ -20,3 +20,4 @@ import './background-tasks';import './resource-usage';import './routines';import './bot-workbench';+import './plugin-view';diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsxnew file mode 100644index 0000000000..2d7d5c162d--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx@@ -0,0 +1,97 @@+/**+ * plugin-view —— 右侧栏里承载插件页面的页签(全局页签,不跟对话)。+ *+ * 一个页签对应一个已装插件实例:插件声明了 `panel`(停靠形态)时展示 panel 页面+ * (沿用 GhostChipPanelBody,挂载即清未读),否则展示 `mainView` 页面。webview 分区、+ * 主题注入、崩溃接管与插件页 / 整页 mainView 完全同一条路(ghostPanelBody.tsx)。+ *+ * 页签不进「+」菜单:由插件的左侧栏入口「在侧边栏中打开」或停靠面板的自动迁移加入+ * (features/right-sidebar/globalTabs.ts)。插件被停用 / 卸载时页签按可用性隐藏,+ * 数据由 globalTabs 的 reconcile 处理,本模块只负责渲染。+ */++import { Puzzle } from 'lucide-react';+import type { TFunction } from 'i18next';++import {+ GhostChipPanelBody,+ GhostPanelError,+ GhostWebviewBody,+} from '@/cindy-brain/ghostPanelBody';+import { useGhostRuntimeState } from '@/cindy-brain/runtimeStates';+import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';+import { MAIN_VIEW_ICONS } from '@/cindy-brain/mainViewIcons';+import type { InstalledGhost } from '../../../../../shared/ghost';+import { installedGhostStoragePart } from '../../../../../shared/pluginIdentity';+import type { PluginViewTabState } from '../../globalTabs';+import { registerTabKind } from '../../registry';+import type { TabKindBodyProps, TabKindPlugin } from '../../types';++function useInstalledGhostByInstance(instanceId: string): InstalledGhost | undefined {+ return useInstalledGhosts().find((ghost) => installedGhostStoragePart(ghost) === instanceId);+}++/** 页签标题:停靠面板用 panel.title,整页视图用 mainView.title,都没有就用插件名。 */+export function pluginViewTitle(ghost: InstalledGhost): string {+ const { manifest } = ghost;+ return manifest.panel?.title ?? manifest.mainView?.title ?? manifest.name;+}++function PluginViewTabPillTitle({ state, t }: { state: PluginViewTabState; t: TFunction }) {+ const ghost = useInstalledGhostByInstance(state.instanceId);+ return <>{ghost ? pluginViewTitle(ghost) : t('rightSidebar.tabs.kinds.pluginView')}</>;+}++function PluginViewTabPillIcon({ state }: { state: PluginViewTabState }) {+ const ghost = useInstalledGhostByInstance(state.instanceId);+ const Icon = MAIN_VIEW_ICONS[ghost?.manifest.mainView?.icon ?? 'puzzle'] ?? Puzzle;+ return <Icon size={13} />;+}++function PluginViewBody({ state }: TabKindBodyProps<PluginViewTabState>) {+ const ghost = useInstalledGhostByInstance(state.instanceId);+ const runtimeState = useGhostRuntimeState(state.instanceId);+ // 停用 / 卸载的瞬间投影层已把页签隐藏,这里只兜住收起前的一两帧。+ if (!ghost || ghost.enabled === false) return null;+ if (runtimeState === 'crashed' || runtimeState === 'fused') {+ return <GhostPanelError ghost={ghost} state={runtimeState} />;+ }+ const panelHtml =+ ghost.manifest.panel?.position !== 'tab' ? ghost.manifest.panel?.html : undefined;+ return (+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden">+ {panelHtml ? (+ <GhostChipPanelBody ghost={ghost} />+ ) : (+ <GhostWebviewBody ghost={ghost} html={ghost.manifest.mainView?.html} />+ )}+ </div>+ );+}++const plugin: TabKindPlugin<PluginViewTabState> = {+ kind: 'plugin-view',+ menu: {+ kind: 'plugin-view',+ labelKey: 'rightSidebar.tabs.kinds.pluginView',+ icon: Puzzle,+ order: 90,+ enabled: true,+ hiddenFromMenu: true,+ },+ TabPillTitle: PluginViewTabPillTitle,+ TabPillIcon: PluginViewTabPillIcon,+ TabBody: PluginViewBody,+ defaultState: () => ({ instanceId: '' }),+ hydrateState: (raw) => {+ const instanceId =+ raw &&+ typeof raw === 'object' &&+ typeof (raw as { instanceId?: unknown }).instanceId === 'string'+ ? (raw as { instanceId: string }).instanceId+ : '';+ return { instanceId };+ },+};++registerTabKind(plugin as unknown as TabKindPlugin, import.meta.hot);diff --git a/apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts b/apps/desktop/src/renderer/features/right-sidebar/tabAvailability.tsindex cceb8e3677..68136286c9 100644--- a/apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts@@ -1,6 +1,8 @@import type { InstalledGhost } from '../../../shared/ghost';import { CINDY_MAKE_ENABLED } from '@cindy/maker-shared/cindy-make-feature';import { FEATURE_RETIREMENTS } from '../../../shared/featureRetirements';+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';+import { isGlobalTabCapableGhost, type PluginViewTabState } from './globalTabs';import type { TabState } from './types';export interface RightSidebarTabAvailability {@@ -11,6 +13,25 @@ export interface RightSidebarTabAvailability {* 窗口关闭后再回到投影。缺省 = 没有弹出。*/hiddenTabIds?: ReadonlySet<string>;+ /**+ * 插件视图页签(`plugin-view`)可承载的本机已装插件。与 installedGhosts 分开:+ * 后者在远程任务下被清空以关闭本地专属能力,而插件视图是全局页签、运行在本机,+ * 不随任务归属变化。缺省 = 不做可用性过滤。+ */+ pluginViewGhosts?: readonly InstalledGhost[];+}++function isUnavailablePluginView(+ tab: TabState,+ availability: RightSidebarTabAvailability,+): boolean {+ if (tab.kind !== 'plugin-view' || !availability.pluginViewGhosts) return false;+ const instanceId = (tab.state as PluginViewTabState | null)?.instanceId;+ if (!instanceId) return true;+ const ghost = availability.pluginViewGhosts.find(+ (candidate) => installedGhostStoragePart(candidate) === instanceId,+ );+ return !ghost || !isGlobalTabCapableGhost(ghost);}function retiredTab(@@ -36,6 +57,7 @@ function retiredTab(function isUnavailableTab(tab: TabState, availability: RightSidebarTabAvailability): boolean {return (availability.hiddenTabIds?.has(tab.id) === true ||+ isUnavailablePluginView(tab, availability) ||(!CINDY_MAKE_ENABLED && tab.kind === 'cindy-make') ||retiredTab(tab, availability) === null ||(tab.kind === 'subagents' && !availability.subagentsAvailable)diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.tsindex 2582da1d9e..3ca92c0aa0 100644--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts@@ -33,7 +33,9 @@ export type BuiltinTabKindId =| 'routines'| 'bot-workbench'| 'resource-usage'- | 'cindy-make';+ | 'cindy-make'+ /** 全局页签(不跟对话):承载插件的 mainView / panel 页面,见 globalTabs.ts。 */+ | 'plugin-view';export type TabKindId = BuiltinTabKindId | `ghost:${string}`;/** 一个 tab 运行时实例。`state` 由各 plugin 自管理结构 + 序列化,壳子只搬运。 */diff --git a/apps/desktop/src/renderer/ghost-panel-window-entry.tsx b/apps/desktop/src/renderer/ghost-panel-window-entry.tsxdeleted file mode 100644index 017d75e299..0000000000--- a/apps/desktop/src/renderer/ghost-panel-window-entry.tsx+++ /dev/null@@ -1,56 +0,0 @@-/**- * 插件面板独立子窗口的轻量渲染入口。- *- * 与 sidebar-window-entry.tsx 模式一致:只加载字体/CSS/主题/Provider,- * 直接渲染 GhostPanelWindowLayout,不经过 main-entry.tsx 的完整 App 链。- *- * 插件面板需要 ghost 管理基础设施(cindy-brain/ghostPanels/runtimeStates)- * 但不需要 maker 会话、登录、设置、语音等重量模块。- *- * 由 index.tsx 的 ?ghostPanelWindow=<id> 分发进入。- */--import { createRoot } from 'react-dom/client';--import '@fontsource-variable/inter';-import '@fontsource-variable/jetbrains-mono';-import 'harmonyos-sans-sc-webfont-splitted';--import '@/i18n';-import './themes/colors';-import './styles/globals.css';--import { TopLevelErrorBoundary } from './components/error/TopLevelErrorBoundary';-import { GhostPanelWindowLayout } from './components/layout/GhostPanelWindowLayout';-import { ConfirmDialogProvider } from './components/ui/confirm-dialog-provider';-import { applyFontSettings, getInitialFontSettings } from './hooks/useFontSettings';-import { bootstrapInitialLocale, LocaleProvider } from './hooks/useLocale';-import { getInitialThemeVariant } from './hooks/useTheme';-import { WallpaperSettingsProvider } from './hooks/useWallpaperSettings';-import { bootstrapLocalThemesSync } from './themes/local-themes';-import { themeService } from './themes/theme-service';-import {- ensureGhostPanelsRegistered,-} from '@/cindy-brain/ghostPanels';--document.documentElement.dataset.platform = window.electronAPI.platform;-bootstrapLocalThemesSync();-themeService.applyTheme(getInitialThemeVariant().theme);-applyFontSettings(getInitialFontSettings());-bootstrapInitialLocale();-ensureGhostPanelsRegistered();--const rootElement = document.getElementById('root');-if (!rootElement) throw new Error('Missing #root element');--createRoot(rootElement).render(- <TopLevelErrorBoundary>- <LocaleProvider>- <ConfirmDialogProvider>- <WallpaperSettingsProvider>- <GhostPanelWindowLayout />- </WallpaperSettingsProvider>- </ConfirmDialogProvider>- </LocaleProvider>- </TopLevelErrorBoundary>,-);diff --git a/apps/desktop/src/renderer/hooks/__tests__/useGhostPanelRestoreMode.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useGhostPanelRestoreMode.test.tsxdeleted file mode 100644index f216002cdc..0000000000--- a/apps/desktop/src/renderer/hooks/__tests__/useGhostPanelRestoreMode.test.tsx+++ /dev/null@@ -1,60 +0,0 @@-// @vitest-environment jsdom--import { act, cleanup, renderHook } from '@testing-library/react';-import { afterEach, describe, expect, it } from 'vitest';--import {- __resetGhostPanelRestoreModeForTest,- getGhostPanelRestoreMode,- setGhostPanelRestoreMode,- useGhostPanelRestoreMode,-} from '../useGhostPanelRestoreMode';--afterEach(() => {- cleanup();- window.localStorage.removeItem('ghostPanel.restoreMode');- __resetGhostPanelRestoreModeForTest();-});--describe('useGhostPanelRestoreMode', () => {- it('默认沿用浮动气泡且不写默认值快照', () => {- expect(getGhostPanelRestoreMode()).toBe('bubble');- expect(window.localStorage.getItem('ghostPanel.restoreMode')).toBeNull();- });-- it('切换到侧栏会持久化并通知同窗口消费者', () => {- const first = renderHook(() => useGhostPanelRestoreMode());- const second = renderHook(() => useGhostPanelRestoreMode());-- act(() => first.result.current.setMode('sidebar'));-- expect(first.result.current.mode).toBe('sidebar');- expect(second.result.current.mode).toBe('sidebar');- expect(window.localStorage.getItem('ghostPanel.restoreMode')).toBe('sidebar');- });-- it('切回默认气泡会删除 override', () => {- setGhostPanelRestoreMode('sidebar');- expect(window.localStorage.getItem('ghostPanel.restoreMode')).toBe('sidebar');-- setGhostPanelRestoreMode('bubble');-- expect(getGhostPanelRestoreMode()).toBe('bubble');- expect(window.localStorage.getItem('ghostPanel.restoreMode')).toBeNull();- });-- it('接收其他窗口的偏好变更', () => {- const view = renderHook(() => useGhostPanelRestoreMode());-- act(() => {- window.dispatchEvent(- new StorageEvent('storage', {- key: 'ghostPanel.restoreMode',- newValue: 'sidebar',- }),- );- });-- expect(view.result.current.mode).toBe('sidebar');- });-});diff --git a/apps/desktop/src/renderer/hooks/useGhostPanelRestoreMode.ts b/apps/desktop/src/renderer/hooks/useGhostPanelRestoreMode.tsdeleted file mode 100644index c4e5ef4128..0000000000--- a/apps/desktop/src/renderer/hooks/useGhostPanelRestoreMode.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * useGhostPanelRestoreMode —— 最小化插件面板的恢复入口偏好。- *- * 两种入口严格互斥:- * - bubble:主窗口浮动幽灵球(历史默认);- * - sidebar:左侧栏“恢复插件面板”入口。- *- * 默认值只存在于代码中,localStorage 仅保存 sidebar override。这样老用户升级后- * 继续看到原有幽灵球,未来调整默认值时也不会被无意义的默认快照卡住。- */--import { useCallback, useEffect, useState } from 'react';--export type GhostPanelRestoreMode = 'bubble' | 'sidebar';--const STORAGE_KEY = 'ghostPanel.restoreMode';-const DEFAULT_MODE: GhostPanelRestoreMode = 'bubble';--let memoryValue: GhostPanelRestoreMode | null = null;-const listeners = new Set<() => void>();-let storageSubscribed = false;--function parseMode(raw: string | null): GhostPanelRestoreMode | null {- return raw === 'bubble' || raw === 'sidebar' ? raw : null;-}--function notifyListeners(): void {- listeners.forEach((listener) => listener());-}--function onStorage(event: StorageEvent): void {- if (event.key !== STORAGE_KEY) return;- memoryValue = parseMode(event.newValue) ?? DEFAULT_MODE;- notifyListeners();-}--function subscribe(listener: () => void): () => void {- listeners.add(listener);- if (!storageSubscribed) {- window.addEventListener('storage', onStorage);- storageSubscribed = true;- }- return () => {- listeners.delete(listener);- if (listeners.size === 0 && storageSubscribed) {- window.removeEventListener('storage', onStorage);- storageSubscribed = false;- }- };-}--export function getGhostPanelRestoreMode(): GhostPanelRestoreMode {- if (memoryValue !== null) return memoryValue;- try {- const parsed = parseMode(window.localStorage.getItem(STORAGE_KEY));- if (parsed === DEFAULT_MODE) {- window.localStorage.removeItem(STORAGE_KEY);- return (memoryValue = DEFAULT_MODE);- }- if (parsed) return (memoryValue = parsed);- } catch {- // localStorage 不可用时保留代码默认值,后续显式设置仍可在内存中即时生效。- }- return DEFAULT_MODE;-}--export function setGhostPanelRestoreMode(next: GhostPanelRestoreMode): void {- memoryValue = next;- try {- if (next === DEFAULT_MODE) window.localStorage.removeItem(STORAGE_KEY);- else window.localStorage.setItem(STORAGE_KEY, next);- } catch {- // 持久化失败不拦当前窗口交互。- }- notifyListeners();-}--export function useGhostPanelRestoreMode(): {- mode: GhostPanelRestoreMode;- setMode: (next: GhostPanelRestoreMode) => void;-} {- const [mode, setModeState] = useState<GhostPanelRestoreMode>(getGhostPanelRestoreMode);- const setMode = useCallback((next: GhostPanelRestoreMode) => {- setGhostPanelRestoreMode(next);- }, []);-- useEffect(() => {- const sync = () => setModeState(getGhostPanelRestoreMode());- return subscribe(sync);- }, []);-- return { mode, setMode };-}--/** 仅测试用。 */-export function __resetGhostPanelRestoreModeForTest(): void {- memoryValue = null;- listeners.clear();- if (storageSubscribed) {- window.removeEventListener('storage', onStorage);- storageSubscribed = false;- }-}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 9688574c58..1735add12e 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1715,13 +1715,6 @@"hint": "For unpinned sessions: Text uses one line; List adds a preview.","aria": "Switch session list style"},- "ghostPanelRestore": {- "label": "Plugin panel restore entry",- "hint": "Choose where minimized plugin panels can be restored.",- "aria": "Choose the plugin panel restore entry",- "bubble": "Floating bubble",- "sidebar": "Sidebar"- },"wallpaper": {"title": "Wallpaper","description": "Choose a Cindy scene, image or video for the whole app, independently of the theme.",@@ -6603,7 +6596,7 @@"nodeResidentDetail": "Runs while the plugin is enabled and stops when disabled, updated, uninstalled, or when Cindy exits.","tool": "Tool \"{{name}}\"","command": "Chat command ${{command}}",- "panelLeft": "Panel \"{{title}}\" · docked left of the chat",+ "panelLeft": "Panel \"{{title}}\" · shown in the right sidebar","panelTab": "Panel \"{{title}}\" · opens inside the Plugins page","mainView": "Can add a “{{title}}” entry to Cindy's sidebar","mainViewDetail": "Opening it displays the main view in the plugin sandbox and does not grant file, network, or credential access.",@@ -6700,8 +6693,8 @@"locationCopied": "Install location copied","locationCopyFailed": "Could not copy the install location. Copy it manually.","openLocation": "Open install location",- "panelDocked": "Docked · min width {{min}}px",- "panelNotDocked": "Not docked (no layout record yet)",+ "panelInSidebar": "Shown in the right sidebar (kept across tasks)",+ "panelDismissed": "Closed from the right sidebar · right-click its entry in the left sidebar to reopen","panelPageHosted": "Opens from the Plugin page · closes when you leave","panelNone": "This plugin has no panel","customSlotTitle": "Plugin custom settings area",@@ -7986,19 +7979,7 @@"collapsePanel": "Collapse","expandPanel": "Expand"},- "panelChrome": {- "maximizeAria": "Maximize panel",- "restoreAria": "Restore panel size",- "detachAria": "Open in a new window",- "minimizeAria": "Minimize panel",- "closeAria": "Close panel and disable plugin"- },"ghostPanel": {- "disableConfirm": {- "title": "Disable \"{{name}}\"?",- "body": "Closing this panel disables the plugin and pauses its capabilities. You can re-enable it anytime from Plugins in the sidebar.",- "confirm": "Disable"- },"externalLinkConfirm": {"title": "Allow Cindy to open an external website?","message": "Allow Cindy to open an external website?",@@ -8006,19 +7987,8 @@"cancel": "Cancel"}},- "ghostPanelWindow": {- "mergeBack": "Return to main window",- "unavailable": "This plugin panel is currently unavailable"- },- "ghostPanelBubble": {- "restoreAria": "Restore {{name}} panel",- "stackExpandAria": "{{count}} plugin panels minimized. Click to expand",- "stackCollapseAria": "Collapse the plugin panel list"- },- "ghostPanelRestore": {- "single": "Restore {{name}}",- "multiple": "Minimized plugin panels",- "multipleAria": "{{count}} plugin panels minimized. Choose a panel to restore"+ "ghostMainView": {+ "openInSidebar": "Open in the sidebar"},"rightSidebar": {"ariaLabel": "Right sidebar",@@ -8044,6 +8014,7 @@"addAria": "Add tab","addFailed": "Failed to add tab","tabCloseAria": "Close tab",+ "pinnedAria": "Global tab, kept across tasks","menu": {"addLabel": "Add tab","comingSoon": "Coming soon",@@ -8059,7 +8030,8 @@"resourceUsage": "Activity Monitor","collaboration": "Team","unknown": "Unknown tab",- "ghostPanel": "Plugin panel"+ "ghostPanel": "Plugin panel",+ "pluginView": "Plugin view"},"controls": {"showAria": "Show sidebar",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 80f2ca4c49..ded0b2a9f0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1686,13 +1686,6 @@"hint": "ピン留め以外のセッションは、テキストなら1行、リストならプレビュー付きで表示します。","aria": "セッションリストの表示を切り替える"},- "ghostPanelRestore": {- "label": "プラグインパネルの復元場所",- "hint": "最小化したプラグインパネルを復元する場所を選択します。",- "aria": "プラグインパネルの復元場所を選択",- "bubble": "フローティングバブル",- "sidebar": "サイドバー"- },"wallpaper": {"title": "壁紙","description": "アプリ全体に Cindy の壁紙や自分の画像・動画を設定できます。テーマは独立して選べます。",@@ -6572,7 +6565,7 @@"nodeResidentDetail": "プラグインが有効な間は実行を続け、無効化、更新、アンインストール、または Cindy 終了時に停止します。","tool": "ツール「{{name}}」","command": "チャット指令 ${{command}}",- "panelLeft": "パネル「{{title}}」· チャットの左側にドッキング",+ "panelLeft": "パネル「{{title}}」· 右サイドバーに表示","panelTab": "パネル「{{title}}」· プラグインページ内で開く","mainView": "Cindy のサイドバーに「{{title}}」への入口を追加できます","mainViewDetail": "クリックするとプラグインのサンドボックス内でメインビューが開き、ファイル、ネットワーク、認証情報へのアクセスが追加で付与されることはありません。",@@ -6669,8 +6662,8 @@"locationCopied": "インストール場所をコピーしました","locationCopyFailed": "インストール場所をコピーできませんでした。手動でコピーしてください","openLocation": "インストール場所を開く",- "panelDocked": "ドッキング済み · 最小幅 {{min}}px",- "panelNotDocked": "未ドッキング(レイアウトに位置記録なし)",+ "panelInSidebar": "右サイドバーに表示(すべてのタスクで保持)",+ "panelDismissed": "右サイドバーから閉じました · 左サイドバーの入口を右クリックで再度開けます","panelPageHosted": "プラグインページから開く · 離れると自動的に閉じます","panelNone": "このプラグインにパネルはありません","customSlotTitle": "プラグインのカスタム設定エリア",@@ -7954,19 +7947,7 @@"collapsePanel": "折りたたみ","expandPanel": "展開"},- "panelChrome": {- "maximizeAria": "パネルを最大化",- "restoreAria": "パネルのサイズを元に戻す",- "detachAria": "新しいウィンドウで開く",- "minimizeAria": "パネルを最小化",- "closeAria": "パネルを閉じてプラグインを無効化"- },"ghostPanel": {- "disableConfirm": {- "title": "「{{name}}」を無効にしますか?",- "body": "このパネルを閉じるとプラグインが無効になり、機能が停止します。サイドバーの「プラグイン」からいつでも再度有効にできます。",- "confirm": "無効にする"- },"externalLinkConfirm": {"title": "Cindy で外部ウェブサイトを開きますか?","message": "Cindy で外部ウェブサイトを開きますか?",@@ -7974,19 +7955,8 @@"cancel": "キャンセル"}},- "ghostPanelWindow": {- "mergeBack": "メインウィンドウに戻る",- "unavailable": "このプラグインパネルは現在利用できません"- },- "ghostPanelBubble": {- "restoreAria": "{{name}} パネルを元に戻す",- "stackExpandAria": "{{count}} 個のプラグインパネルを最小化中。クリックで展開",- "stackCollapseAria": "プラグインパネルの一覧を畳む"- },- "ghostPanelRestore": {- "single": "{{name}}を復元",- "multiple": "最小化したプラグインパネル",- "multipleAria": "{{count}}個のプラグインパネルが最小化されています。復元するパネルを選択"+ "ghostMainView": {+ "openInSidebar": "サイドバーで開く"},"rightSidebar": {"ariaLabel": "右サイドバー",@@ -8012,6 +7982,7 @@"addAria": "タブを追加","addFailed": "タブを追加できませんでした","tabCloseAria": "タブを閉じる",+ "pinnedAria": "グローバルタブ。タスクを切り替えても保持されます","menu": {"addLabel": "タブを追加","comingSoon": "近日対応",@@ -8027,7 +7998,8 @@"resourceUsage": "アクティビティモニタ","collaboration": "コラボ","unknown": "不明なタブ",- "ghostPanel": "プラグインパネル"+ "ghostPanel": "プラグインパネル",+ "pluginView": "プラグインビュー"},"controls": {"showAria": "サイドバーを表示",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6081d22bae..6a6642d3f1 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1686,13 +1686,6 @@"hint": "고정하지 않은 세션: 텍스트는 한 줄로, 목록은 미리보기와 함께 표시합니다.","aria": "세션 목록 표시 방식 전환"},- "ghostPanelRestore": {- "label": "플러그인 패널 복원 위치",- "hint": "최소화한 플러그인 패널을 어디에서 복원할지 선택합니다.",- "aria": "플러그인 패널 복원 위치 선택",- "bubble": "플로팅 버블",- "sidebar": "사이드바"- },"wallpaper": {"title": "배경화면","description": "앱 전체에 Cindy 배경이나 내 이미지 또는 동영상을 적용하세요. 테마는 별도로 선택할 수 있습니다.",@@ -6572,7 +6565,7 @@"nodeResidentDetail": "플러그인이 활성화된 동안 실행되며 비활성화, 업데이트, 제거 또는 Cindy 종료 시 중지됩니다.","tool": "도구 \"{{name}}\"","command": "채팅 명령 ${{command}}",- "panelLeft": "패널 \"{{title}}\" · 채팅 왼쪽에 도킹",+ "panelLeft": "패널 \"{{title}}\" · 오른쪽 사이드바에 표시","panelTab": "패널 \"{{title}}\" · 플러그인 페이지에서 열기","mainView": "Cindy 사이드바에 “{{title}}” 항목을 추가할 수 있음","mainViewDetail": "클릭하면 플러그인 샌드박스에서 메인 보기가 열리며 파일, 네트워크 또는 자격 증명 접근 권한이 추가로 부여되지 않습니다.",@@ -6669,8 +6662,8 @@"locationCopied": "설치 위치를 복사했습니다","locationCopyFailed": "설치 위치를 복사하지 못했습니다. 수동으로 복사하세요","openLocation": "설치 위치 열기",- "panelDocked": "도킹됨 · 최소 너비 {{min}}px",- "panelNotDocked": "도킹되지 않음(레이아웃에 위치 기록 없음)",+ "panelInSidebar": "오른쪽 사이드바에 표시(모든 작업에서 유지)",+ "panelDismissed": "오른쪽 사이드바에서 닫음 · 왼쪽 사이드바 항목을 우클릭해 다시 열 수 있습니다","panelPageHosted": "플러그인 페이지에서 열림 · 벗어나면 자동으로 닫힘","panelNone": "이 플러그인에는 패널이 없습니다","customSlotTitle": "플러그인 사용자 정의 설정 영역",@@ -7954,19 +7947,7 @@"collapsePanel": "접기","expandPanel": "펼치기"},- "panelChrome": {- "maximizeAria": "패널 최대화",- "restoreAria": "패널 크기 복원",- "detachAria": "새 창에서 열기",- "minimizeAria": "패널 최소화",- "closeAria": "패널 닫기 및 플러그인 비활성화"- },"ghostPanel": {- "disableConfirm": {- "title": "\"{{name}}\" 플러그인을 비활성화할까요?",- "body": "이 패널을 닫으면 플러그인이 비활성화되고 기능이 중지됩니다. 사이드바의 '플러그인'에서 언제든지 다시 활성화할 수 있습니다.",- "confirm": "비활성화"- },"externalLinkConfirm": {"title": "Cindy에서 외부 웹사이트를 열까요?","message": "Cindy에서 외부 웹사이트를 열까요?",@@ -7974,19 +7955,8 @@"cancel": "취소"}},- "ghostPanelWindow": {- "mergeBack": "메인 창으로 돌아가기",- "unavailable": "이 플러그인 패널은 현재 사용할 수 없습니다"- },- "ghostPanelBubble": {- "restoreAria": "{{name}} 패널 복원",- "stackExpandAria": "플러그인 패널 {{count}}개가 최소화됨. 클릭하여 펼치기",- "stackCollapseAria": "플러그인 패널 목록 접기"- },- "ghostPanelRestore": {- "single": "{{name}} 복원",- "multiple": "최소화된 플러그인 패널",- "multipleAria": "플러그인 패널 {{count}}개가 최소화되었습니다. 복원할 패널 선택"+ "ghostMainView": {+ "openInSidebar": "사이드바에서 열기"},"rightSidebar": {"ariaLabel": "오른쪽 사이드바",@@ -8012,6 +7982,7 @@"addAria": "탭 추가","addFailed": "탭을 추가하지 못했습니다","tabCloseAria": "탭 닫기",+ "pinnedAria": "전역 탭, 작업을 전환해도 유지됩니다","menu": {"addLabel": "탭 추가","comingSoon": "지원 예정",@@ -8027,7 +7998,8 @@"resourceUsage": "활성 상태 보기","collaboration": "협업","unknown": "알 수 없는 탭",- "ghostPanel": "플러그인 패널"+ "ghostPanel": "플러그인 패널",+ "pluginView": "플러그인 보기"},"controls": {"showAria": "사이드바 표시",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex c49c2e57d2..b83713c962 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1686,13 +1686,6 @@"hint": "未置顶任务:文字单行,列表带预览","aria": "切换任务列表显示方式"},- "ghostPanelRestore": {- "label": "插件面板恢复入口",- "hint": "选择最小化插件面板后从哪里恢复。",- "aria": "选择插件面板恢复入口",- "bubble": "浮动气泡",- "sidebar": "侧边栏"- },"wallpaper": {"title": "壁纸","description": "为整个应用选择 Cindy 场景、自己的图片或视频,主题保持独立。",@@ -6572,7 +6565,7 @@"nodeResidentDetail": "插件启用期间会一直运行;停用、更新、卸载或退出 Cindy 时关闭。","tool": "工具「{{name}}」","command": "对话指令 ${{command}}",- "panelLeft": "面板「{{title}}」· 停靠主对话区左侧",+ "panelLeft": "面板「{{title}}」· 显示在右侧栏","panelTab": "面板「{{title}}」· 插件页内打开","mainView": "可在 Cindy 侧边栏添加“{{title}}”入口","mainViewDetail": "点击后将在插件沙箱中打开主视图,不会因此获得文件、网络或凭证访问权限。",@@ -6669,8 +6662,8 @@"locationCopied": "安装位置已复制","locationCopyFailed": "复制安装位置失败,请手动复制","openLocation": "打开安装位置",- "panelDocked": "已停靠 · 最小宽 {{min}}px",- "panelNotDocked": "未停靠(布局中暂无位置记录)",+ "panelInSidebar": "显示在右侧栏(所有任务中保留)",+ "panelDismissed": "已从右侧栏关闭 · 可在左侧栏入口右键重新打开","panelPageHosted": "从插件页打开 · 离开插件页自动关闭","panelNone": "这个插件不含面板","customSlotTitle": "插件自定义设置区",@@ -7954,19 +7947,7 @@"collapsePanel": "收起","expandPanel": "展开"},- "panelChrome": {- "maximizeAria": "撑满内容区",- "restoreAria": "还原面板大小",- "detachAria": "在独立窗口中打开",- "minimizeAria": "最小化面板",- "closeAria": "关闭面板并停用插件"- },"ghostPanel": {- "disableConfirm": {- "title": "停用「{{name}}」?",- "body": "关闭这个面板会停用插件并暂停其能力。你可以随时在侧边栏「插件」中重新启用。",- "confirm": "停用"- },"externalLinkConfirm": {"title": "是否要 Cindy 打开外部网站","message": "是否要 Cindy 打开外部网站",@@ -7974,19 +7955,8 @@"cancel": "取消"}},- "ghostPanelWindow": {- "mergeBack": "返回主窗口",- "unavailable": "该插件面板当前不可用"- },- "ghostPanelBubble": {- "restoreAria": "恢复 {{name}} 面板",- "stackExpandAria": "已收起 {{count}} 个插件面板,点击展开",- "stackCollapseAria": "收拢插件面板列表"- },- "ghostPanelRestore": {- "single": "恢复 {{name}}",- "multiple": "已收起的插件面板",- "multipleAria": "已收起 {{count}} 个插件面板,点击选择要恢复的面板"+ "ghostMainView": {+ "openInSidebar": "在侧边栏中打开"},"rightSidebar": {"ariaLabel": "右侧边栏",@@ -8012,6 +7982,7 @@"addAria": "添加标签","addFailed": "添加标签失败","tabCloseAria": "关闭标签",+ "pinnedAria": "全局页签,切换任务时保留","menu": {"addLabel": "添加标签","comingSoon": "即将支持",@@ -8027,7 +7998,8 @@"resourceUsage": "资源监视器","collaboration": "协同","unknown": "未知标签页",- "ghostPanel": "插件面板"+ "ghostPanel": "插件面板",+ "pluginView": "插件视图"},"controls": {"showAria": "显示侧栏",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 5c3753cb97..d12292c53c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1686,13 +1686,6 @@"hint": "未置頂任務:文字單行,列表附預覽","aria": "切換任務列表顯示方式"},- "ghostPanelRestore": {- "label": "插件面板恢復入口",- "hint": "選擇最小化插件面板後從哪裡恢復。",- "aria": "選擇插件面板恢復入口",- "bubble": "浮動氣泡",- "sidebar": "側邊欄"- },"wallpaper": {"title": "桌布","description": "為整個應用程式選擇 Cindy 場景、自己的圖片或影片,主題保持獨立。",@@ -6572,7 +6565,7 @@"nodeResidentDetail": "插件啟用期間會一直執行;停用、更新、解除安裝或退出 Cindy 時關閉。","tool": "工具「{{name}}」","command": "對話指令 ${{command}}",- "panelLeft": "面板「{{title}}」· 停靠主對話區左側",+ "panelLeft": "面板「{{title}}」· 顯示在右側欄","panelTab": "面板「{{title}}」· 插件頁內開啟","mainView": "可在 Cindy 側邊欄新增「{{title}}」入口","mainViewDetail": "點擊後將在插件沙箱中開啟主視圖,不會因此取得檔案、網路或憑證存取權限。",@@ -6669,8 +6662,8 @@"locationCopied": "安裝位置已複製","locationCopyFailed": "複製安裝位置失敗,請手動複製","openLocation": "開啟安裝位置",- "panelDocked": "已停靠 · 最小寬 {{min}}px",- "panelNotDocked": "未停靠(佈局中暫無位置記錄)",+ "panelInSidebar": "顯示在右側欄(所有任務中保留)",+ "panelDismissed": "已從右側欄關閉 · 可在左側欄入口右鍵重新開啟","panelPageHosted": "從插件頁開啟 · 離開插件頁自動關閉","panelNone": "這個插件不含面板","customSlotTitle": "插件自定義設定區",@@ -7954,19 +7947,7 @@"collapsePanel": "收起","expandPanel": "展開"},- "panelChrome": {- "maximizeAria": "撐滿內容區",- "restoreAria": "還原面板大小",- "detachAria": "在獨立視窗中開啟",- "minimizeAria": "最小化面板",- "closeAria": "關閉面板並停用插件"- },"ghostPanel": {- "disableConfirm": {- "title": "停用「{{name}}」?",- "body": "關閉這個面板會停用插件並暫停其能力。你可以隨時在側邊欄「插件」中重新啟用。",- "confirm": "停用"- },"externalLinkConfirm": {"title": "是否要讓 Cindy 開啟外部網站","message": "是否要讓 Cindy 開啟外部網站",@@ -7974,19 +7955,8 @@"cancel": "取消"}},- "ghostPanelWindow": {- "mergeBack": "返回主視窗",- "unavailable": "該插件面板當前不可用"- },- "ghostPanelBubble": {- "restoreAria": "恢復 {{name}} 面板",- "stackExpandAria": "已收起 {{count}} 個插件面板,點選展開",- "stackCollapseAria": "收攏插件面板列表"- },- "ghostPanelRestore": {- "single": "恢復 {{name}}",- "multiple": "已收起的插件面板",- "multipleAria": "已收起 {{count}} 個插件面板,點擊選擇要恢復的面板"+ "ghostMainView": {+ "openInSidebar": "在側邊欄中開啟"},"rightSidebar": {"ariaLabel": "右側邊欄",@@ -8012,6 +7982,7 @@"addAria": "新增標籤","addFailed": "新增標籤失敗","tabCloseAria": "關閉標籤",+ "pinnedAria": "全域頁籤,切換任務時保留","menu": {"addLabel": "新增標籤","comingSoon": "即將支援",@@ -8027,7 +7998,8 @@"resourceUsage": "資源監視器","collaboration": "協同","unknown": "未知標籤頁",- "ghostPanel": "插件面板"+ "ghostPanel": "插件面板",+ "pluginView": "插件視圖"},"controls": {"showAria": "顯示側欄",diff --git a/apps/desktop/src/renderer/index.tsx b/apps/desktop/src/renderer/index.tsxindex e65c36a3d0..82e30ba68a 100644--- a/apps/desktop/src/renderer/index.tsx+++ b/apps/desktop/src/renderer/index.tsx@@ -10,7 +10,6 @@ const urlParams = new URLSearchParams(window.location.search);const isRemoteDesktopViewer = urlParams.get('remoteDesktopViewer') === '1';const isResourceUsageWindow = urlParams.get('resourceUsageWindow') === '1';const isSidebarWindow = urlParams.get('sidebarWindow') === '1';-const ghostPanelWindowId = urlParams.get('ghostPanelWindow');void (isRemoteDesktopViewer? import('./remote-desktop-viewer-entry')@@ -18,9 +17,7 @@ void (isRemoteDesktopViewer? import('./resource-usage-entry'): isSidebarWindow? import('./sidebar-window-entry')- : ghostPanelWindowId- ? import('./ghost-panel-window-entry')- : import('./main-entry')+ : import('./main-entry')).catch((error: unknown) => {// 入口加载失败发生在 React boundary 之前,仍通过统一 renderer logger 落盘。window.electronAPI?.logToMain?.(diff --git a/apps/desktop/src/renderer/layout/LayoutRoot.tsx b/apps/desktop/src/renderer/layout/LayoutRoot.tsxindex 086395d8bf..626acd41e4 100644--- a/apps/desktop/src/renderer/layout/LayoutRoot.tsx+++ b/apps/desktop/src/renderer/layout/LayoutRoot.tsx@@ -19,8 +19,6 @@ import {} from '../../shared/layoutTree';import { installGhostDevTools } from '../cindy-brain/ghostDevTools';import { ensureGhostPanelsRegistered, useGhostPanelsSync } from '../cindy-brain/ghostPanels';-import { isGhostPanelKindMinimized, useGhostPanelBubbleState } from '../lib/ghostPanelBubbleState';-import { isGhostPanelKindDetached, useGhostPanelWindowsState } from '../lib/ghostPanelWindowState';import { registerBuiltinPanels } from '../panels/builtinPanels';import { getPanelKind, type PanelDefinition } from '../panels/registry';import { installLayoutDevTools } from './layoutDevTools';@@ -71,17 +69,12 @@ const ROOT_WIDTH_SELF_HEAL_SETTLE_MS = 120;const NON_CHAT_FLOOR_PX = 120;/**- * pane 是否在本窗口渲染:未注册 kind(未安装/停用的插件残留)、已抽离进- * 独立窗口、以及已最小化的面板都不渲染 —— 树数据一律保留,- * 重装/合并/恢复即原位复活(architecture-invariants「已抽离的面板允许保留- * 在存档中但不渲染」)。+ * pane 是否在本窗口渲染:未注册 kind(历史遗留的插件停靠面板 `ghost:*`、未安装+ * 面板的残留)不渲染 —— 树数据一律保留(architecture-invariants「未注册的面板+ * 允许保留在存档中但不渲染」)。*/function isPanelKindVisible(kind: string): boolean {- return (- getPanelKind(kind) !== null &&- !isGhostPanelKindDetached(kind) &&- !isGhostPanelKindMinimized(kind)- );+ return getPanelKind(kind) !== null;}/** 单个 pane 的挂载点:查注册表渲染;不可见 kind = 隐藏(数据保留在树里)。 */@@ -824,10 +817,6 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =// 装/卸广播 → 注册表对齐 + 重渲(卸下不动布局树,靠这里让引擎重过滤在场面板)。const ghostSyncVersion = useGhostPanelsSync();- // 抽离/气泡状态变化 → 重渲(isPanelKindVisible 读的是模块级镜像,靠这两个- // hook 感知变化)。- const ghostWindowsState = useGhostPanelWindowsState();- const ghostBubbleState = useGhostPanelBubbleState();// 首帧同步读取(sendSync):布局在第一帧就位,不出现默认布局闪现。const [layout, setLayout] = useState<Layout>(@@ -870,7 +859,7 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =if (observer === null) window.removeEventListener('resize', schedule);if (timer !== null) window.clearTimeout(timer);};- }, [ghostBubbleState, ghostSyncVersion, ghostWindowsState, layout, suppressNonChatPanels]);+ }, [ghostSyncVersion, layout, suppressNonChatPanels]);// 撑满态(panelMaximize.tsx):会话级视图态,树账本不动。同 kind 再点还原。const [maximizedKind, setMaximizedKind] = useState<string | null>(null);@@ -886,11 +875,11 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =// 松手清空回落树值 —— 拖动全程不写 IPC。const [liveFractions, setLiveFractions] = useState<Record<string, number> | null>(null);const availableWidthHint = useContentAvailableWidth();- // eslint 会说 ghostWindowsState 没被直接读——它是 computeRootWidths 里- // isPanelKindVisible 的隐式数据源(模块级镜像),必须进 deps 才能感知抽离变化。+ // eslint 会说 ghostSyncVersion 没被直接读——它是 computeRootWidths 里+ // isPanelKindVisible 的隐式数据源(模块级注册表),必须进 deps 才能感知装卸。const rootWidths = useMemo(() => computeRootWidths(layout, liveFractions),- [layout, liveFractions, ghostBubbleState, ghostSyncVersion, ghostWindowsState],+ [layout, liveFractions, ghostSyncVersion],);// 撑满目标失效自动还原:面板被卸下/停用(kind 注销)、抽离进独立窗口或@@ -901,14 +890,7 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =const present =containsPanelKind(layout.content, maximizedKind) && isPanelKindVisible(maximizedKind);if (!present) setMaximizedKind(null);- }, [- layout,- ghostBubbleState,- ghostSyncVersion,- ghostWindowsState,- maximizedKind,- suppressNonChatPanels,- ]);+ }, [layout, ghostSyncVersion, maximizedKind, suppressNonChatPanels]);const content = layout.content;let body: ReactNode;diff --git a/apps/desktop/src/renderer/layout/panelMaximize.tsx b/apps/desktop/src/renderer/layout/panelMaximize.tsxindex 38de16f512..b6c433565c 100644--- a/apps/desktop/src/renderer/layout/panelMaximize.tsx+++ b/apps/desktop/src/renderer/layout/panelMaximize.tsx@@ -9,7 +9,7 @@ import { createContext, useContext } from 'react';* chat-main 仅被视觉收起(0 宽裁切,保持挂载),与 RSB maximize 隐藏主区的* 既有先例同一档语义。* - 会话级瞬时态,不持久化:重启回到常规布局(撑满是"临时看大图"式的查看态)。- * - 状态由 LayoutRoot 持有并下发;标准头(PanelChrome)凭 panelKind 消费,+ * - 状态由 LayoutRoot 持有并下发;面板标准头凭 panelKind 消费,* 面板作者无感 —— 系统按钮由引擎统一长出,不进面板自绘区。*/export interface PanelMaximizeState {diff --git a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.tsdeleted file mode 100644index 81b9078c54..0000000000--- a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts+++ /dev/null@@ -1,160 +0,0 @@-// @vitest-environment jsdom-// ghostPanelBubbleState:localStorage 持久化的气泡最小化状态。-import { afterEach, describe, expect, it } from 'vitest';--import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';-import {- __resetGhostPanelBubbleStateForTest,- getGhostPanelBubbleState,- isGhostPanelKindMinimized,- minimizeGhostPanel,- reconcileGhostPanelBubbles,- restoreGhostPanel,- setGhostPanelBubblePosition,-} from '../ghostPanelBubbleState';--const KEY = 'xdt:ghostPanelBubble:v1';--function ghost(- id: string,- opts: { enabled?: boolean; position?: 'left' | 'tab'; minimizeButton?: boolean; panel?: boolean } = {},-): InstalledGhost {- const manifest: GhostManifest = {- schemaVersion: 2,- id,- name: id,- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- ...(opts.panel === false- ? {}- : {- panel: {- html: 'panel.html',- ...(opts.position !== undefined ? { position: opts.position } : {}),- ...(opts.minimizeButton === false ? { systemButtons: { minimize: false } } : {}),- },- }),- };- return {- manifest,- dir: `/fake/${id}`,- enabled: opts.enabled ?? true,- approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },- };-}--afterEach(() => {- __resetGhostPanelBubbleStateForTest();-});--describe('ghostPanelBubbleState · sanitize', () => {- it('坏 JSON / 非对象 → 空表', () => {- window.localStorage.setItem(KEY, '{{{');- expect(getGhostPanelBubbleState()).toEqual({});- __resetGhostPanelBubbleStateForTest();- window.localStorage.setItem(KEY, '[1,2]');- expect(getGhostPanelBubbleState()).toEqual({});- });-- it('minimized 非布尔整条丢;x/y 非双双有限数则略去;空条目不留', () => {- window.localStorage.setItem(- KEY,- JSON.stringify({- bad: { minimized: 'yes', x: 1, y: 2 },- halfpos: { minimized: true, x: 10 },- floaty: { minimized: true, x: 10.6, y: 20.2 },- empty: { minimized: false },- good: { minimized: false, x: 5, y: 6 },- }),- );- expect(getGhostPanelBubbleState()).toEqual({- halfpos: { minimized: true },- floaty: { minimized: true, x: 11, y: 20 },- good: { minimized: false, x: 5, y: 6 },- });- });-});--describe('ghostPanelBubbleState · 最小化/恢复/位置', () => {- it('minimize → restore 往返:位置保留;无位置的还原条目清除;持久化可重读', () => {- minimizeGhostPanel('a');- expect(isGhostPanelKindMinimized('ghost:a')).toBe(true);- setGhostPanelBubblePosition('a', 100.4, 200.6);- restoreGhostPanel('a');- expect(isGhostPanelKindMinimized('ghost:a')).toBe(false);- expect(getGhostPanelBubbleState().a).toEqual({ minimized: false, x: 100, y: 201 });-- // 持久化载荷可直接重读(模拟重启的数据面)- minimizeGhostPanel('b');- setGhostPanelBubblePosition('b', 1, 2);- const raw = JSON.parse(window.localStorage.getItem(KEY) ?? '{}');- expect(raw.b).toEqual({ minimized: true, x: 1, y: 2 });-- // 无位置的还原条目直接清除- minimizeGhostPanel('c');- restoreGhostPanel('c');- expect(getGhostPanelBubbleState().c).toBeUndefined();- });-- it('谓词:非 ghost 前缀恒 false', () => {- minimizeGhostPanel('a');- expect(isGhostPanelKindMinimized('chat-main')).toBe(false);- expect(isGhostPanelKindMinimized('right-tabs')).toBe(false);- });-});--describe('ghostPanelBubbleState · reconcile(与已装清单对齐)', () => {- it('卸载删条目;停用/tab/关按钮强制还原(留位置);合格的不动', () => {- minimizeGhostPanel('gone');- minimizeGhostPanel('disabled');- setGhostPanelBubblePosition('disabled', 9, 9);- minimizeGhostPanel('tabbed');- minimizeGhostPanel('nobtn');- minimizeGhostPanel('stays');-- reconcileGhostPanelBubbles([- ghost('disabled', { enabled: false }),- ghost('tabbed', { position: 'tab' }),- ghost('nobtn', { minimizeButton: false }),- ghost('stays'),- ]);-- const state = getGhostPanelBubbleState();- expect(state.gone).toBeUndefined();- expect(state.disabled).toEqual({ minimized: false, x: 9, y: 9 });- expect(state.tabbed).toBeUndefined(); // 无位置的还原条目清除- expect(state.nobtn).toBeUndefined();- expect(state.stays).toEqual({ minimized: true });- });-});--describe('ghostPanelBubbleState · 变化信号(引用替换)', () => {- it('只有真实变化才替换表引用(useSyncExternalStore 的更新信号)', () => {- const before = getGhostPanelBubbleState();- reconcileGhostPanelBubbles([ghost('x')]); // 无条目 → 无变化,同一引用- expect(getGhostPanelBubbleState()).toBe(before);- minimizeGhostPanel('x'); // commit 替换引用- expect(getGhostPanelBubbleState()).not.toBe(before);- const after = getGhostPanelBubbleState();- minimizeGhostPanel('x'); // 已最小化,幂等短路,不替换- expect(getGhostPanelBubbleState()).toBe(after);- });-});--describe('ghostPanelBubbleState · 跨独立窗口同步', () => {- it('另一个 BrowserWindow 写入气泡状态后刷新本窗口镜像', () => {- // 首次读取会惰性注册 storage listener。- getGhostPanelBubbleState();-- window.dispatchEvent(- new StorageEvent('storage', {- key: 'xdt:ghostPanelBubble:v1',- storageArea: window.localStorage,- newValue: JSON.stringify({ a: { minimized: true } }),- }),- );-- expect(getGhostPanelBubbleState().a).toEqual({ minimized: true });- });-});diff --git a/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts b/apps/desktop/src/renderer/lib/ghostPanelBubbleState.tsdeleted file mode 100644index e658114255..0000000000--- a/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts+++ /dev/null@@ -1,201 +0,0 @@-/**- * ghostPanelBubbleState —— 插件停靠面板的最小化状态(历史命名沿用 bubble)。- *- * 纯视图态,renderer 自有(localStorage 持久化,重启保留),不经 main:- * 与 maximize(会话态)/ detach(main 持久化)三分天下——气泡既要重启保留- * 又不涉及窗口/进程,localStorage 恰好(键规范照 state/modelVisibilityPrefs.ts)。- *- * 形如 { [ghostId]: { minimized, x?, y? } }:- * - minimized:面板是否收进气泡(LayoutRoot 据此隐藏停靠 pane,树不动);- * - x/y:**遗留字段**(2026-07-31 起气泡层只画一枚幽灵球,子气泡由球锚定,- * 不再各记各的位置;幽灵球落点在气泡层自己的独立键)。历史写入保留不清,- * sanitize 照旧容忍,setGhostPanelBubblePosition 留作 API 兼容。- *- * reconcile 语义对齐 main/ghost-panel-window controller:卸载删条目;停用/- * 无 panel/tab 形态/身份卡关按钮 → 强制还原(留位置)——气泡永不成死角。- */--import { useSyncExternalStore } from 'react';--import { GHOST_PANEL_KIND_PREFIX, type InstalledGhost } from '../../shared/ghost';-import { installedGhostStoragePart } from '../../shared/pluginIdentity';--const STORAGE_KEY = 'xdt:ghostPanelBubble:v1';--export interface GhostPanelBubbleEntry {- minimized: boolean;- x?: number;- y?: number;-}--export type GhostPanelBubbleMap = Record<string, GhostPanelBubbleEntry>;--let cache: GhostPanelBubbleMap | null = null;-const subscribers = new Set<() => void>();-let storageListenerWired = false;--function isPlainObject(v: unknown): v is Record<string, unknown> {- return typeof v === 'object' && v !== null && !Array.isArray(v);-}--/** 解析并清洗持久化数据:坏形态整条丢弃,x/y 必须双双有限数否则略去。 */-function sanitize(raw: unknown): GhostPanelBubbleMap {- if (!isPlainObject(raw)) return {};- const out: GhostPanelBubbleMap = {};- for (const [id, entry] of Object.entries(raw)) {- if (!isPlainObject(entry)) continue;- if (typeof entry.minimized !== 'boolean') continue;- const hasPos = Number.isFinite(entry.x) && Number.isFinite(entry.y);- if (!entry.minimized && !hasPos) continue; // 空条目不留- out[id] = {- minimized: entry.minimized,- ...(hasPos ? { x: Math.round(entry.x as number), y: Math.round(entry.y as number) } : {}),- };- }- return out;-}--function load(): GhostPanelBubbleMap {- try {- const raw = window.localStorage.getItem(STORAGE_KEY);- if (!raw) return {};- return sanitize(JSON.parse(raw));- } catch {- return {};- }-}--function ensureLoaded(): GhostPanelBubbleMap {- if (cache === null) cache = load();- ensureStorageListener();- return cache;-}--/** Keep the in-memory mirror aligned when another BrowserWindow changes the bubble state. */-function ensureStorageListener(): void {- if (storageListenerWired || typeof window === 'undefined') return;- storageListenerWired = true;- window.addEventListener('storage', (event) => {- if (event.storageArea !== window.localStorage || event.key !== STORAGE_KEY) return;- let next: unknown = {};- if (event.newValue) {- try {- next = JSON.parse(event.newValue);- } catch {- next = {};- }- }- cache = sanitize(next);- subscribers.forEach((cb) => cb());- });-}--/** 整表替换 + 持久化 + 通知(引用变化即订阅者更新信号)。 */-function commit(next: GhostPanelBubbleMap): void {- cache = next;- try {- window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));- } catch {- // 持久化失败不拦交互(隐私模式等),内存态照常生效- }- subscribers.forEach((cb) => cb());-}--export function getGhostPanelBubbleState(): GhostPanelBubbleMap {- return ensureLoaded();-}--/** 布局过滤谓词(非 hook,LayoutRoot 纯函数路径用)。非 ghost 面板恒 false。 */-export function isGhostPanelKindMinimized(panelKind: string): boolean {- if (!panelKind.startsWith(GHOST_PANEL_KIND_PREFIX)) return false;- const ghostId = panelKind.slice(GHOST_PANEL_KIND_PREFIX.length);- return ensureLoaded()[ghostId]?.minimized === true;-}--/** 收进气泡(保留既有位置,重最小化回老位置)。 */-export function minimizeGhostPanel(ghostId: string): void {- const cur = ensureLoaded();- if (cur[ghostId]?.minimized === true) return;- commit({ ...cur, [ghostId]: { ...cur[ghostId], minimized: true } });-}--/** 从气泡恢复停靠(位置保留;入场滑入由 GhostPanel 挂载时机自判)。 */-export function restoreGhostPanel(ghostId: string): void {- const cur = ensureLoaded();- const entry = cur[ghostId];- if (!entry || entry.minimized === false) return;- const next = { ...cur };- const hasPos = Number.isFinite(entry.x) && Number.isFinite(entry.y);- if (hasPos) next[ghostId] = { ...entry, minimized: false };- else delete next[ghostId]; // 没位置的还原条目是空信息,不留- commit(next);-}--/** 气泡拖放落点(视口 px,取整)。 */-export function setGhostPanelBubblePosition(ghostId: string, x: number, y: number): void {- if (!Number.isFinite(x) || !Number.isFinite(y)) return;- const cur = ensureLoaded();- const entry = cur[ghostId] ?? { minimized: false };- commit({ ...cur, [ghostId]: { ...entry, x: Math.round(x), y: Math.round(y) } });-}--/**- * 与"当前已装清单"对齐(syncGhostPanelRegistrations 每次同步时调):- * 卸载删条目;失去气泡资格(停用/无 panel/tab 形态/身份卡关按钮)强制还原。- */-export function reconcileGhostPanelBubbles(- ghosts: readonly Pick<InstalledGhost, 'manifest' | 'enabled' | 'namespace'>[],-): void {- const cur = ensureLoaded();- const ids = Object.keys(cur);- if (ids.length === 0) return;- const byId = new Map(ghosts.map((g) => [installedGhostStoragePart(g), g]));- let changed = false;- const next: GhostPanelBubbleMap = { ...cur };- for (const id of ids) {- const ghost = byId.get(id);- if (!ghost) {- delete next[id];- changed = true;- continue;- }- const eligible =- ghost.enabled !== false &&- ghost.manifest.panel !== undefined &&- ghost.manifest.panel.position !== 'tab' &&- ghost.manifest.panel.systemButtons?.minimize !== false;- if (!eligible && next[id].minimized) {- const entry = next[id];- const hasPos = Number.isFinite(entry.x) && Number.isFinite(entry.y);- if (hasPos) next[id] = { ...entry, minimized: false };- else delete next[id];- changed = true;- }- }- if (changed) commit(next);-}--function subscribe(cb: () => void): () => void {- ensureLoaded();- subscribers.add(cb);- return () => {- subscribers.delete(cb);- };-}--/** React hook:订阅全量表(commit 替换对象引用 = 更新信号)。 */-export function useGhostPanelBubbleState(): GhostPanelBubbleMap {- return useSyncExternalStore(subscribe, getGhostPanelBubbleState);-}--/** 仅测试用。 */-export function __resetGhostPanelBubbleStateForTest(): void {- cache = null;- subscribers.clear();- storageListenerWired = false;- try {- window.localStorage.removeItem(STORAGE_KEY);- } catch {- // ignore- }-}diff --git a/apps/desktop/src/renderer/lib/ghostPanelWindow.ts b/apps/desktop/src/renderer/lib/ghostPanelWindow.tsdeleted file mode 100644index beac9b9731..0000000000--- a/apps/desktop/src/renderer/lib/ghostPanelWindow.ts+++ /dev/null@@ -1,29 +0,0 @@-/**- * ghostPanelWindow —— 「我是不是插件面板独立窗口」的窗口身份判定。- *- * 与 sidebarWindow.ts 同款:main 的窗口工厂在启动 URL 上带- * `?ghostPanelWindow=<ghostId>`,renderer 启动时读一次;身份在窗口生命周期内- * 不变。id 过校验(isValidPluginStoragePart)才算数,野值视同普通窗口。- */--import { isValidPluginStoragePart } from '../../shared/pluginIdentity';--let cached: string | null | undefined;--/** 本窗口承载的 ghostId;非插件面板窗口返回 null。 */-export function getGhostPanelWindowGhostId(): string | null {- if (cached === undefined) {- const raw = new URLSearchParams(window.location.search).get('ghostPanelWindow');- cached = isValidPluginStoragePart(raw) ? raw : null;- }- return cached;-}--export function isGhostPanelWindow(): boolean {- return getGhostPanelWindowGhostId() !== null;-}--/** 仅测试用。 */-export function __resetGhostPanelWindowForTest(): void {- cached = undefined;-}diff --git a/apps/desktop/src/renderer/lib/ghostPanelWindowState.ts b/apps/desktop/src/renderer/lib/ghostPanelWindowState.tsdeleted file mode 100644index a10cbca437..0000000000--- a/apps/desktop/src/renderer/lib/ghostPanelWindowState.ts+++ /dev/null@@ -1,92 +0,0 @@-/**- * ghostPanelWindowState —— 插件停靠面板独立窗口状态的 renderer 端镜像。- *- * Source of truth 在 main(ghost-panel-window/controller.ts + settings-store):- * ghostId → { detached, lastOpen, open },经 `maker:ghost-panel-window:state-changed`- * 广播到所有窗口。与 rightSidebarWindowState 的差异:- * - **首帧走 sendSync**(规则 7):LayoutRoot 第一帧就要知道哪些面板已抽离,- * 异步拉取会先画停靠面板再消失(重启恢复场景闪一下);- * - 过滤谓词按 **detached** 而非 open:恢复期窗口还没建出来时面板同样不许- * 在主窗停靠位出现。- *- * 消费方:LayoutRoot(抽离的 pane 不渲染)、GhostPanel(按钮态)、- * GhostPanelWindowLayout(子窗自身)。- */--import { useSyncExternalStore } from 'react';--import type { GhostPanelWindowsState } from '../../shared/ghostPanelWindow';-import { GHOST_PANEL_KIND_PREFIX } from '../../shared/ghost';--let state: GhostPanelWindowsState | null = null;-const subscribers = new Set<() => void>();-let wired = false;--function readInitial(): GhostPanelWindowsState {- // 无桥环境(jsdom 单测 / stub 不全)视同"没有任何抽离",不是错误。- try {- const api = window.electronAPI?.ghostPanelWindow;- if (!api) return {};- return api.getStateSync() ?? {};- } catch {- return {};- }-}--/** 惰性绑定 main 广播(整个 renderer 只绑一次,fan-out 在 preload 层)。 */-function ensureWired(): void {- if (wired) return;- wired = true;- try {- window.electronAPI?.ghostPanelWindow?.onStateChanged((s) => {- state = s ?? {};- subscribers.forEach((cb) => cb());- });- } catch {- // 无桥环境:保持首读快照- }-}--export function getGhostPanelWindowsState(): GhostPanelWindowsState {- if (state === null) {- state = readInitial();- ensureWired();- }- return state;-}--function subscribe(cb: () => void): () => void {- getGhostPanelWindowsState();- subscribers.add(cb);- return () => {- subscribers.delete(cb);- };-}--/**- * 布局过滤谓词(非 hook,LayoutRoot 的纯函数路径用):该 panelKind 是否- * 已抽离进独立窗口。非 ghost 面板恒 false。- */-export function isGhostPanelKindDetached(panelKind: string): boolean {- if (!panelKind.startsWith(GHOST_PANEL_KIND_PREFIX)) return false;- const ghostId = panelKind.slice(GHOST_PANEL_KIND_PREFIX.length);- return getGhostPanelWindowsState()[ghostId]?.detached === true;-}--/** React hook:订阅全量镜像(引用变化 = 有广播)。 */-export function useGhostPanelWindowsState(): GhostPanelWindowsState {- return useSyncExternalStore(subscribe, getGhostPanelWindowsState);-}--/** 仅测试用。 */-export function __setGhostPanelWindowsStateForTest(next: GhostPanelWindowsState): void {- state = next;- subscribers.forEach((cb) => cb());-}--/** 仅测试用。 */-export function __resetGhostPanelWindowsStateForTest(): void {- state = null;- subscribers.clear();- wired = false;-}diff --git a/apps/desktop/src/renderer/main-entry.tsx b/apps/desktop/src/renderer/main-entry.tsxindex 0a38f6bb06..47302b633e 100644--- a/apps/desktop/src/renderer/main-entry.tsx+++ b/apps/desktop/src/renderer/main-entry.tsx@@ -35,7 +35,6 @@ import { bootstrapGitSafetySettingsFromMain } from './lib/gitSafetySettingsStoreimport { bootstrapLspModeFromMain } from './lib/lspModeStore';import { bootstrapSilentEncryptedRetryFromMain } from './lib/silentEncryptedRetryStore';import { initRsbBrowserBridge } from './features/right-sidebar/lib/rsbBrowserBridge';-import { isGhostPanelWindow } from './lib/ghostPanelWindow';import { isSecondaryWindow } from './lib/secondaryWindow';import {installForegroundRecoveryDiagnostics,@@ -207,7 +206,7 @@ void (async () => {// or unmounted sidebar UI. Only the primary and dedicated sidebar windows// can own RSB tabs; other full-app windows must not publish an empty pool// snapshot into the primary registry.- if (!isGhostPanelWindow() && !isSecondaryWindow()) {+ if (!isSecondaryWindow()) {const disposeRsbBrowserBridge = initRsbBrowserBridge();import.meta.hot?.dispose(disposeRsbBrowserBridge);}diff --git a/apps/desktop/src/renderer/panels/PanelChrome.tsx b/apps/desktop/src/renderer/panels/PanelChrome.tsxdeleted file mode 100644index c31b0593a5..0000000000--- a/apps/desktop/src/renderer/panels/PanelChrome.tsx+++ /dev/null@@ -1,159 +0,0 @@-import type { CSSProperties, ReactNode } from 'react';-import { Maximize2, Minimize2, Minus, PictureInPicture2, X } from 'lucide-react';-import { useTranslation } from 'react-i18next';--import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';-import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';-import { useMacFullscreen } from '@/hooks/useMacFullscreen';--import { usePanelMaximize } from '../layout/panelMaximize';--/**- * PanelChrome —— 面板标准头。- *- * 任何顶级面板(尤其未来意识面板)都应以本组件作为顶带,拿到三件事:- * 1. 统一视觉:36px 行高、下边框、panel-bg —— 与工具面板 TabBar 同规格族,- * 多面板并排时顶带连成一条水平线;- * 2. 拖拽手柄:整条即"拖面板换位"手势面(data-panel-drag-handle,- * PanelDragController 识别;窗口拖动走 46px 顶带,见 B3 口径);- * 3. 左标题 / 右 actions 槽:标题给面板身份,actions 给面板自定义控件。- *- * 右端系统按钮(一批,由引擎统一长出,面板作者无感;身份卡- * panel.systemButtons 可逐个关闭):- * - 「最小化面板」(minimize):传 onMinimize 即得,点击隐藏停靠面板;恢复入口由- * 用户偏好决定为浮动气泡或左侧栏(状态在 renderer/lib/ghostPanelBubbleState.ts);- * - 「独立窗口」(detach):传 onDetach 即得,点击把面板抽进自己的 OS 窗口- * (状态机在 main 的 ghost-panel-window/controller.ts);- * - 「撑满内容区」(maximize):传 panelKind 即得,状态在 LayoutRoot 的- * PanelMaximizeContext;- * - 「关闭」(close):传 onClose 即得,永远排最右。语义归调用方- * (意识面板用它走"二次确认后停用插件",见 ghostPanels.tsx)。- *- * 视觉走主题 token(规则 16);按钮 aria 文案走 i18n(panelChrome.*),- * 标题由调用方传入并自行 i18n。- */-export interface PanelChromeProps {- /** 左侧标题(调用方自行 i18n;可以是文本或自定义节点)。 */- title: ReactNode;- /** 右端自定义控件槽(排在系统按钮的左侧)。 */- actions?: ReactNode;- /**- * 面板在布局树里的 panelKind。传入且处于 LayoutRoot 的- * PanelMaximizeContext 之下时,标准头长出「撑满内容区」系统按钮;- * 不传(或脱离引擎单渲)则不渲染,行为与旧版完全一致。- */- panelKind?: string;- /** 传入即长出「独立窗口」系统按钮(排在撑满按钮左侧),点击回调归调用方。 */- onDetach?: () => void;- /** 传入即长出「最小化面板」系统按钮(排在独立窗口按钮左侧)。 */- onMinimize?: () => void;- /** 传入即长出「关闭」系统按钮(恒排最右);二次确认等语义归调用方。 */- onClose?: () => void;- /**- * 是否渲染贴主窗口顶边的 46px 窗口拖拽带。纵向 Grid 的非首行传 false,- * 避免在窗口中部浪费高度并产生误触拖窗区域;默认 true 保持根级面板行为。- */- showWindowSpacer?: boolean;-}--export function PanelChrome({- title,- actions,- panelKind,- onDetach,- onMinimize,- onClose,- showWindowSpacer = true,-}: PanelChromeProps): ReactNode {- const { t } = useTranslation();- const maximize = usePanelMaximize();- const showMaximize = panelKind !== undefined && maximize !== null;- const isMaximized = showMaximize && maximize.maximizedKind === panelKind;- // ChromeActions 按钮簇的窗口坐标(与 ChromeActions.tsx 的 x 同式):- // 面板顶带的 no-drag 洞必须钉在这里,见下方洞元素注释。- const { isMac, isFullscreen } = useMacFullscreen();- const chromeClusterX =- isMac && !isFullscreen- ? CHROME_ACTIONS_GEOMETRY.macTrafficLightLeft- : CHROME_ACTIONS_GEOMETRY.defaultLeft;- return (- <>- {/* 窗口 chrome 让位带(§6 规则 3:顶部 46px 是系统领地,任何面板不得占用)。- 做进标准头 = 约束由引擎兜底,面板作者不靠自觉;整条归窗口拖动- (B3 口径:46px 带拖窗、36px 头拖面板),与聊天顶栏/工具面板顶带连成一线。 */}- {showWindowSpacer && (- <div- aria-hidden- data-testid="panel-chrome-window-spacer"- className="h-[46px] shrink-0 border-b border-[var(--border-default)] bg-[var(--panel-bg)]"- style={{ WebkitAppRegion: 'drag' } as CSSProperties}- >- {/* ChromeActions 浮层按钮簇的 no-drag 洞:左栏折叠时本面板可能顶到窗口- 最左,顶带会盖住左上角折叠/菜单按钮 —— Electron 拖拽区是纯几何- (drag 矩形减 no-drag 矩形)且挖洞只在 drag 元素后代上可靠生效,- 浮层自身的 no-drag 不算数(同 Sidebar 顶行 / ContentHeader spacer)。- fixed 定位取窗口坐标:面板不在左上角时矩形与顶带不相交 = 几何- no-op,无需感知自己的列位;pointer-events:none 不挡命中(拖拽区- 注册是几何计算,不依赖 DOM 事件)。 */}- <div- data-testid="panel-chrome-actions-hit-hole"- className="pointer-events-none fixed top-0 h-[46px]"- style={- {- left: chromeClusterX,- width: CHROME_ACTIONS_GEOMETRY.clusterWidth,- WebkitAppRegion: 'no-drag',- } as CSSProperties- }- />- </div>- )}- <div- data-panel-drag-handle=""- className="flex h-[36px] shrink-0 items-center justify-between gap-2 border-b border-[var(--border-default)] bg-[var(--panel-bg)] px-3"- style={{ WebkitAppRegion: 'no-drag' } as CSSProperties}- >- <div className="min-w-0 truncate text-12 font-medium text-[var(--text-secondary)]">- {title}- </div>- {(actions || showMaximize || onDetach || onMinimize || onClose) && (- <div className="flex shrink-0 items-center gap-0.5">- {actions}- {onMinimize && (- <ChromeIconButton- aria-label={t('panelChrome.minimizeAria')}- onClick={onMinimize}- >- <Minus size={14} />- </ChromeIconButton>- )}- {onDetach && (- <ChromeIconButton- aria-label={t('panelChrome.detachAria')}- onClick={onDetach}- >- <PictureInPicture2 size={14} />- </ChromeIconButton>- )}- {showMaximize && (- <ChromeIconButton- aria-label={t(isMaximized ? 'panelChrome.restoreAria' : 'panelChrome.maximizeAria')}- onClick={() => maximize.toggle(panelKind)}- >- {isMaximized ? <Minimize2 size={14} /> : <Maximize2 size={14} />}- </ChromeIconButton>- )}- {onClose && (- <ChromeIconButton- aria-label={t('panelChrome.closeAria')}- onClick={onClose}- >- <X size={14} />- </ChromeIconButton>- )}- </div>- )}- </div>- </>- );-}diff --git a/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx b/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsxdeleted file mode 100644index 73265d6664..0000000000--- a/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx+++ /dev/null@@ -1,152 +0,0 @@-// @vitest-environment jsdom-import { afterEach, describe, expect, it, vi } from 'vitest';-import { useState } from 'react';-import { cleanup, fireEvent, render, screen } from '@testing-library/react';--import { CHROME_ACTIONS_GEOMETRY } from '../../components/layout/chromeActionsGeometry';-import { PanelMaximizeContext, type PanelMaximizeState } from '../../layout/panelMaximize';-import { PanelChrome } from '../PanelChrome';--// 仓库同款 i18n mock:t 返回 key 本身,便于断言。-vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}));--/** 带真实 toggle 语义的 harness:同 kind 再点 = 还原(与 LayoutRoot 实现一致)。 */-function Harness({ panelKind }: { panelKind?: string }) {- const [maximizedKind, setMaximizedKind] = useState<string | null>(null);- const ctx: PanelMaximizeState = {- maximizedKind,- toggle: (kind) => setMaximizedKind((cur) => (cur === kind ? null : kind)),- };- return (- <PanelMaximizeContext.Provider value={ctx}>- <PanelChrome title="测试面板" panelKind={panelKind} />- </PanelMaximizeContext.Provider>- );-}--afterEach(cleanup);--describe('PanelChrome · 撑满系统按钮', () => {- it('传 panelKind 且在 PanelMaximizeContext 下 → 长出撑满按钮,点按在撑满/还原间切换', () => {- render(<Harness panelKind="ghost:demo" />);- const btn = screen.getByRole('button', { name: 'panelChrome.maximizeAria' });- fireEvent.click(btn);- // 撑满后按钮语义翻转为"还原"- const restore = screen.getByRole('button', { name: 'panelChrome.restoreAria' });- fireEvent.click(restore);- expect(screen.getByRole('button', { name: 'panelChrome.maximizeAria' })).toBeTruthy();- });-- it('不传 panelKind → 不渲染系统按钮(旧行为不变)', () => {- render(<Harness />);- expect(screen.queryByRole('button')).toBeNull();- });-- it('脱离 PanelMaximizeContext 单渲(如测试/独立宿主)→ 不渲染系统按钮', () => {- render(<PanelChrome title="测试面板" panelKind="ghost:demo" />);- expect(screen.queryByRole('button')).toBeNull();- });-- it('传 onDetach → 长出独立窗口按钮,点击回调触发;与撑满按钮并存', () => {- const onDetach = vi.fn();- render(- <PanelMaximizeContext.Provider- value={{ maximizedKind: null, toggle: () => undefined }}- >- <PanelChrome title="测试面板" panelKind="ghost:demo" onDetach={onDetach} />- </PanelMaximizeContext.Provider>,- );- const detachBtn = screen.getByRole('button', { name: 'panelChrome.detachAria' });- fireEvent.click(detachBtn);- expect(onDetach).toHaveBeenCalledTimes(1);- expect(screen.getByRole('button', { name: 'panelChrome.maximizeAria' })).toBeTruthy();- });-- it('只传 onDetach(无 panelKind)→ 只有独立窗口按钮', () => {- render(<PanelChrome title="测试面板" onDetach={() => undefined} />);- expect(screen.getAllByRole('button')).toHaveLength(1);- expect(screen.getByRole('button', { name: 'panelChrome.detachAria' })).toBeTruthy();- });-- it('46px 顶带为 ChromeActions 按钮簇挖 no-drag 洞(左栏折叠 + 面板顶到窗口最左时按钮可点)', () => {- render(<PanelChrome title="测试面板" />);- const hole = screen.getByTestId('panel-chrome-actions-hit-hole');- const strip = hole.parentElement as HTMLElement;- // 洞必须是 drag 顶带的后代(Electron 挖洞只在 drag 元素后代上可靠生效)。- expect(- (strip.style as CSSStyleDeclaration & { WebkitAppRegion: string }).WebkitAppRegion,- ).toBe('drag');- expect(- (hole.style as CSSStyleDeclaration & { WebkitAppRegion: string }).WebkitAppRegion,- ).toBe('no-drag');- // fixed 定位钉窗口坐标(jsdom 无 electronAPI → 非 mac → defaultLeft)。- expect(hole.className).toContain('fixed');- expect(hole.style.left).toBe(`${CHROME_ACTIONS_GEOMETRY.defaultLeft}px`);- expect(hole.style.width).toBe(`${CHROME_ACTIONS_GEOMETRY.clusterWidth}px`);- });-- it('纵向 Grid 非首行可关闭窗口拖拽带,只保留面板标题栏', () => {- render(<PanelChrome title="测试面板" showWindowSpacer={false} />);- expect(screen.queryByTestId('panel-chrome-window-spacer')).toBeNull();- expect(screen.queryByTestId('panel-chrome-actions-hit-hole')).toBeNull();- expect(document.querySelector('[data-panel-drag-handle]')).not.toBeNull();- });-- it('传 onMinimize → 长出气泡最小化按钮并触发回调;三按钮 DOM 顺序 minimize→detach→maximize', () => {- const onMinimize = vi.fn();- render(- <PanelMaximizeContext.Provider value={{ maximizedKind: null, toggle: () => undefined }}>- <PanelChrome- title="测试面板"- panelKind="ghost:demo"- onDetach={() => undefined}- onMinimize={onMinimize}- />- </PanelMaximizeContext.Provider>,- );- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.minimizeAria' }));- expect(onMinimize).toHaveBeenCalledTimes(1);- const labels = screen- .getAllByRole('button')- .map((b) => b.getAttribute('aria-label'));- expect(labels).toEqual([- 'panelChrome.minimizeAria',- 'panelChrome.detachAria',- 'panelChrome.maximizeAria',- ]);- });-- it('传 onClose → 长出关闭按钮并触发回调;四按钮齐时关闭恒排最右', () => {- const onClose = vi.fn();- render(- <PanelMaximizeContext.Provider value={{ maximizedKind: null, toggle: () => undefined }}>- <PanelChrome- title="测试面板"- panelKind="ghost:demo"- onDetach={() => undefined}- onMinimize={() => undefined}- onClose={onClose}- />- </PanelMaximizeContext.Provider>,- );- fireEvent.click(screen.getByRole('button', { name: 'panelChrome.closeAria' }));- expect(onClose).toHaveBeenCalledTimes(1);- const labels = screen- .getAllByRole('button')- .map((b) => b.getAttribute('aria-label'));- expect(labels).toEqual([- 'panelChrome.minimizeAria',- 'panelChrome.detachAria',- 'panelChrome.maximizeAria',- 'panelChrome.closeAria',- ]);- });-- it('只传 onClose(无其它系统按钮)→ 只有关闭按钮', () => {- render(<PanelChrome title="测试面板" onClose={() => undefined} />);- expect(screen.getAllByRole('button')).toHaveLength(1);- expect(screen.getByRole('button', { name: 'panelChrome.closeAria' })).toBeTruthy();- });-});diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsxindex 0604c8617c..e2819b7ab7 100644--- a/apps/desktop/src/renderer/router.tsx+++ b/apps/desktop/src/renderer/router.tsx@@ -5,7 +5,6 @@ import { MainLayout } from '@/components/layout/MainLayout';import { MainEntryRedirect } from '@/components/layout/MainEntryRedirect';import { RouteErrorFallback } from '@/components/error/RouteErrorFallback';import { SidebarWindowLayout } from '@/components/layout/SidebarWindowLayout';-import { GhostPanelWindowLayout } from '@/components/layout/GhostPanelWindowLayout';import { SettingsView } from '@/components/settings/SettingsView';import { LoginPage } from '@/components/login/LoginPage';import { AddAccountLoginPage } from '@/components/login/AddAccountLoginPage';@@ -83,13 +82,6 @@ export const router = createHashRouter([element: <SidebarWindowLayout />,errorElement: <RouteErrorFallback variant="section" />,},- // 插件面板独立窗口(?ghostPanelWindow=<id>)的根路由 —— 同样与- // MainLayout 平级,只挂 46px chrome + 面板体。- {- path: 'ghost-panel-window',- element: <GhostPanelWindowLayout />,- errorElement: <RouteErrorFallback variant="section" />,- },{element: <MainLayout />,children: [diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.cssindex 5ad116cefd..65cc2d9fad 100644--- a/apps/desktop/src/renderer/styles/globals.css+++ b/apps/desktop/src/renderer/styles/globals.css@@ -2277,110 +2277,6 @@ mark.doc-search-mark [class] {stroke-width: 2;}-/* ── 插件面板悬浮球(GhostPanelBubbleLayer)────────────────────────────- 动效按 engineering-conventions §7 红线:只动 transform/opacity、动画挂- HTML wrapper(不挂 SVG)、常驻循环仅 hover 期间播放、减弱动效时停用。- 任何动画都不压在气泡按钮本体上 —— 按钮本体只管落位与 no-drag 命中区- (left/top 定位,app-region 挖洞按布局矩形算、不跟随 transform,见- GhostPanelBubbleLayer.tsx 文件头);圆圈与幽灵各自分层- (.ghost-bubble-circle / .ghost-bubble-face-jump)编排。- 时序(2026-07-25 Lizi 定案"两段都要有戏"):- 出现 = 面板收走 → 等 300ms → 圆圈渐显(160ms)→ 幽灵跳进来(240ms,回弹);- 消失 = 幽灵跳走(160ms)→ 圆圈渐隐(120ms 延迟 + 140ms)→ 面板滑入。 */-@keyframes ghost-bubble-circle-in {- from {- transform: scale(0.85);- opacity: 0;- }- to {- transform: scale(1);- opacity: 1;- }-}-@keyframes ghost-bubble-circle-out {- to {- transform: scale(0.9);- opacity: 0;- }-}-@keyframes ghost-bubble-ghost-in {- 0% {- transform: translateY(12px) scale(0.4);- opacity: 0;- }- 65% {- transform: translateY(-4px) scale(1.08);- opacity: 1;- }- 100% {- transform: none;- opacity: 1;- }-}-@keyframes ghost-bubble-ghost-out {- to {- transform: translateY(-14px) scale(0.4);- opacity: 0;- }-}-@keyframes ghost-bubble-bob {- 0%,- 100% {- transform: translateY(0);- }- 50% {- transform: translateY(-3px);- }-}-.ghost-bubble-enter .ghost-bubble-circle {- animation: ghost-bubble-circle-in 160ms ease-out 300ms backwards;-}-.ghost-bubble-enter .ghost-bubble-face-jump {- animation: ghost-bubble-ghost-in 240ms cubic-bezier(0.34, 1.4, 0.64, 1) 420ms backwards;-}-.ghost-bubble-exit .ghost-bubble-face-jump {- animation: ghost-bubble-ghost-out 160ms ease-in forwards;-}-.ghost-bubble-exit .ghost-bubble-circle {- animation: ghost-bubble-circle-out 140ms ease-in 120ms forwards;-}-.ghost-bubble:hover .ghost-bubble-face {- animation: ghost-bubble-bob 1.1s ease-in-out infinite;-}-/* 停靠面板出现/收起(气泡展开/合并/装入/启用出现,点最小化收起;启动首屏- 豁免与提交时序都在 ghostPanels.tsx):外层壳宽度 0↔实宽 折叠展开。- 这是 §7 compositor-only 的窄例外(同登录 handoff 的容器形变口径):- 一次性、有状态含义;内容层定实宽被外壳裁切,webview 不逐帧重排。- keyframes 缺省端取元素实宽(inline style),不用变量传宽。 */-@keyframes ghost-panel-expand {- from {- width: 0;- }-}-@keyframes ghost-panel-collapse {- to {- width: 0;- }-}-.ghost-panel-enter {- animation: ghost-panel-expand 200ms ease-out;-}-/* exit 在 enter 之后声明:出现瞬间就点收起时,后者整段覆盖前者。 */-.ghost-panel-exit {- animation: ghost-panel-collapse 180ms ease-in forwards;-}-@media (prefers-reduced-motion: reduce) {- .ghost-bubble-enter .ghost-bubble-circle,- .ghost-bubble-enter .ghost-bubble-face-jump,- .ghost-bubble-exit .ghost-bubble-circle,- .ghost-bubble-exit .ghost-bubble-face-jump,- .ghost-panel-enter,- .ghost-panel-exit,- .ghost-bubble:hover .ghost-bubble-face {- animation: none;- }-}-/* Opt-in whole-window wallpaper. Page surfaces share one fixed canvas;elevated controls and external web content keep their readable surfaces. */html[data-wallpaper-active='true'] body {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 969808abc8..d5570a0de5 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2044,28 +2044,6 @@ interface ElectronAPI {) => () => void;};- /** 插件停靠面板独立窗口(每 ghostId 一扇窗;状态机在 main)。 */- ghostPanelWindow: {- /** 首帧同步读全量状态(ghostId → entry)。 */- getStateSync: () => import('../shared/ghostPanelWindow').GhostPanelWindowsState;- getState: () => Promise<import('../shared/ghostPanelWindow').GhostPanelWindowsState>;- /** 幂等:已开则 show + focus。 */- open: (ghostId: string) => Promise<void>;- /** 写偏好;true 开窗抽离,false 关窗回停靠。返回新全量 state。 */- setDetached: (- ghostId: string,- detached: boolean,- ) => Promise<import('../shared/ghostPanelWindow').GhostPanelWindowsState>;- onStateChanged: (- cb: (state: import('../shared/ghostPanelWindow').GhostPanelWindowsState) => void,- ) => () => void;- rendererReady: () => Promise<void>;- presentationReady: () => Promise<void>;- onVisibilityChanged: (cb: (payload: { visible: boolean }) => void) => () => void;- onCloseRequested: (cb: () => void) => () => void;- onMinimizeRequested: (cb: () => void) => () => void;- resolveCloseRequest: (approved: boolean) => Promise<void>;- };/*** 右侧栏单页签独立窗口(每个弹出的页签一扇窗;状态机在 main)。diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 65f1971664..0a34b0b86a 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -445,7 +445,7 @@ export type GhostPanelPosition = (typeof GHOST_PANEL_POSITIONS)[number];/** 面板声明(五个卡槽中的「面板」槽,一段意识至多一块)。 */export interface GhostPanelDecl {- /** 面板标准头(PanelChrome)标题;缺省用意识 name。 */+ /** 面板标题(右侧栏页签 / 插件页标题);缺省用意识 name。 */title?: string;/** 显示形态:left 停靠主聊天窗左侧(缺省),或 'tab' 插件页内独占面板* (2026-08-02 面板收束:只从插件页打开,离开插件页即关闭);diff --git a/apps/desktop/src/shared/ghostPanelWindow.ts b/apps/desktop/src/shared/ghostPanelWindow.tsdeleted file mode 100644index 014e8e2991..0000000000--- a/apps/desktop/src/shared/ghostPanelWindow.ts+++ /dev/null@@ -1,39 +0,0 @@-/**- * 插件停靠面板独立窗口(ghost panel window)的跨进程共享类型。- *- * 三方共用:main(controller / IPC handler)、preload(桥接签名)、renderer- * (主窗镜像 store + 子窗口根组件)。只放纯类型,不放运行时代码。- * 语义对照 shared/rightSidebarWindow.ts 的 RsbWindowState,差异是按 ghostId- * 多实例(每个插件至多一扇窗)。- */--/** 单个插件窗口状态:均仅在当前进程有效;重启后 detached / lastOpen 重置。 */-export interface GhostPanelWindowEntryState {- /** 当前运行期是否在独立窗口中显示。 */- detached: boolean;- /** 当前运行期是否曾请求保持窗口打开;不跨客户端重启。 */- lastOpen: boolean;- /** 运行时:子窗口当前是否存在。不持久化。 */- open: boolean;-}--/** 全量状态:ghostId → 窗口状态。没有条目 = 从未抽离(等价三 false)。 */-export type GhostPanelWindowsState = Record<string, GhostPanelWindowEntryState>;--// ── 预热/就绪/隐藏复用 IPC channel 常量 ──────────────────────────────-/** renderer → main(invoke):窗口根组件已挂载(React shell 可展示)。 */-export const GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL = 'ghost-panel-window:renderer-ready';-/** renderer → main(invoke):首份面板内容已提交(至少空态/错误态可渲染)。 */-export const GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL =- 'ghost-panel-window:presentation-ready';-/** main → renderer(send):隐藏/显示时通知子窗口刷新面板 + 重置瞬时交互态。 */-export const GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL =- 'ghost-panel-window:visibility-changed';-export const GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL =- 'ghost-panel-window:close-requested';-/** main → renderer(send):原生窗口最小化也统一进入插件面板的最小化状态。 */-export const GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL =- 'ghost-panel-window:minimize-requested';-export const GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL =- 'ghost-panel-window:close-request-resolved';-export const GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL = 'ghost-panel-window:locale-changed';diff --git a/apps/desktop/src/shared/sidebarTabWindow.ts b/apps/desktop/src/shared/sidebarTabWindow.tsindex 11c8c407a4..7e296fd030 100644--- a/apps/desktop/src/shared/sidebarTabWindow.ts+++ b/apps/desktop/src/shared/sidebarTabWindow.ts@@ -22,7 +22,8 @@ export interface SidebarTabWindowContext {/** main 指派给某扇弹出窗口的页签身份;窗口整个生命周期只承载这一个页签。 */export interface SidebarTabWindowAssignment {tabId: string;- sessionId: string;+ /** 任务页签所属任务;全局页签(不跟对话,如插件视图)为 null。 */+ sessionId: string | null;context: SidebarTabWindowContext;}@@ -39,7 +40,7 @@ export interface SidebarTabReturnSnapshot {/** 单扇弹出窗口的运行时状态;只在当前进程有效,不跨重启。 */export interface SidebarTabWindowEntryState {- sessionId: string;+ sessionId: string | null;/** 窗口是否已经展示(或正在等待首份内容后展示)。 */open: boolean;}@@ -49,7 +50,7 @@ export type SidebarTabWindowsState = Record<string, SidebarTabWindowEntryState>;/** main → 主窗:页签离开弹出窗口,回到侧边栏(合并 / 窗口崩溃)。 */export interface SidebarTabReturnedPayload {- sessionId: string;+ sessionId: string | null;tabId: string;/** 不可持久化会话交回的内存态;可持久化会话为 null,主窗按 SQLite 刷新。 */snapshot: SidebarTabReturnSnapshot | null;diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex 060ebd5cac..2ba9653338 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -11,7 +11,7 @@生成命令:`pnpm design:inventory`。裸颜色匹配与 `scripts/hardcoded-color-audit.mjs` 共用 `scripts/shared/hardcoded-color-match.mjs`(HEX / RGB / HSL / OKLCH 等字面通道),两者在共享 matcher 内统一排除纯语义包装、注释及 PR 编号;数值颜色函数还需位于样式属性、CSS 声明/函数或任意值语境,普通文案字符串里的颜色函数文本不计入;字面 fallback 仍计入——语义 token 消费与注释引用不是迁移债务;裸圆角为粗粒度(`rounded*` class、`border-radius:` 与 React style 对象的 `borderRadius:`)。Token 计数为样式源里 `var(--token)` / `hsl(var(--token)` 的去重 ID 数;Mobile 的 ThemeColors / typeScale 等 RN 属性不计入此列,不能将 0 解释为未使用 Token。-登记 surface 数:53。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。+登记 surface 数:52。平台包含 Desktop 与 Mobile;静态入口发现不表示已迁移或已实机验证。| ID | 平台 | 标题 | 生产入口 | 可达组件 | 样式来源 | Token 数 | 裸颜色 | 裸圆角 || --- | --- | --- | --- | --- | --- | ---: | ---: | ---: |@@ -39,16 +39,15 @@| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 || `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 27 | 0 | 48 || `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/AvatarCropEditor.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerFilterCard.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/avatarCropGeometry.ts, apps/desktop/src/renderer/components/settings/avatarCropImage.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsRowClasses.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageFilterSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 136 | 95 | 542 |-| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 143 | 46 | 196 |+| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 143 | 46 | 196 || `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginManagementLayout, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx | 35 | 0 | 43 || `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 43 | 0 | 37 || `desktop.window.computer-permission-guide` | desktop | 电脑使用权限引导 | `?view=computer-permission-guide` → ComputerPermissionGuideWindow;backdrop 同文件 | ComputerPermissionBackdrop, ComputerPermissionGuideWindow | apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts, apps/desktop/src/main/computer-permission-guide/placement.ts, apps/desktop/src/main/computer-permission-guide/request.ts, apps/desktop/src/main/computer-permission-guide/switch-target.ts, apps/desktop/src/main/computer-permission-guide/window.ts, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx | 7 | 2 | 9 |-| `desktop.window.ghost-panel` | desktop | 插件面板独立窗口 | `?ghostPanelWindow=<id>` → renderer/ghost-panel-window-entry.tsx;hash `/ghost-panel-window` | GhostPanelWindowLayout | apps/desktop/src/main/ghost-panel-window/controller.ts, apps/desktop/src/main/ghost-panel-window/ipc.ts, apps/desktop/src/main/ghost-panel-window/registry.ts, apps/desktop/src/main/ghost-panel-window/settings-store.ts, apps/desktop/src/main/ghost-panel-window/window.ts, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/ghost-panel-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 77 | 38 | 15 || `desktop.window.remote-desktop` | desktop | 远程桌面独立窗口 | `?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx | Button, ConfirmDialog, FormField, Popover, RemoteDesktopViewerWindow, Select, Switch, Tip | apps/desktop/src/main/remote-desktop-viewer/connection.ts, apps/desktop/src/main/remote-desktop-viewer/credentials.ts, apps/desktop/src/main/remote-desktop-viewer/preferences.ts, apps/desktop/src/main/remote-desktop-viewer/registry.ts, apps/desktop/src/main/remote-desktop-viewer/resolutionMemory.ts, apps/desktop/src/main/remote-desktop-viewer/safety.ts, apps/desktop/src/main/remote-desktop-viewer/windows.ts, apps/desktop/src/renderer/components/ui/button.tsx, apps/desktop/src/renderer/components/ui/confirm-dialog.tsx, apps/desktop/src/renderer/components/ui/form-field.tsx, apps/desktop/src/renderer/components/ui/popover.tsx, apps/desktop/src/renderer/components/ui/select-parts.tsx, apps/desktop/src/renderer/components/ui/select.css, apps/desktop/src/renderer/components/ui/select.tsx, apps/desktop/src/renderer/components/ui/switch.tsx, apps/desktop/src/renderer/components/ui/tooltip.tsx, apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx, apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css, apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 132 | 36 | 29 || `desktop.window.resource-usage` | desktop | 资源用量窗口 | `?resourceUsageWindow=1` → renderer/resource-usage-entry.tsx(不走 router.tsx) | ResourceUsageWindowLayout, ResourceUsageWindowRoot | apps/desktop/src/main/resource-usage-window/controller.ts, apps/desktop/src/main/resource-usage-window/ipc.ts, apps/desktop/src/main/resource-usage-window/open-sender.ts, apps/desktop/src/main/resource-usage-window/registry.ts, apps/desktop/src/main/resource-usage-window/window.ts, apps/desktop/src/renderer/components/resource-usage/ResourceUsageWindowLayout.tsx, apps/desktop/src/renderer/resource-usage-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 77 | 38 | 15 || `desktop.window.review-artifact-confirm` | desktop | Review 成果确认窗 | main/reviewer/reviewArtifactConfirmWindow.ts 内联 HTML/CSS(不走 renderer 路由) | reviewArtifactConfirmWindow | apps/desktop/src/main/reviewer/reviewArtifactConfirmWindow.ts | 8 | 18 | 2 || `desktop.window.session-drag-preview` | desktop | 会话拖拽预览 | main/session-drag-preview.ts 透明预览窗 | session-drag-preview | apps/desktop/src/main/session-drag-preview.ts | 0 | 1 | 0 |-| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 110 | 45 | 115 |+| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 110 | 45 | 115 || `desktop.window.voice-dictionary-toast` | desktop | 语音词典 Toast 窗 | `?view=voice-input-dictionary-toast` → main-entry.tsx → VoiceInputDictionaryToast | VoiceInputDictionaryToast | apps/desktop/src/renderer/voice-input/VoiceInputDictionaryToast.tsx | 6 | 0 | 2 || `desktop.window.voice-overlay` | desktop | 语音输入浮窗 | `?view=voice-input-overlay` → main-entry.tsx → VoiceInputOverlay | VoiceInputOverlay, VoiceInputStatusNotice | apps/desktop/src/main/voice-input/global.ts, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css, apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx, apps/desktop/src/renderer/voice-input/VoiceInputStatusNotice.tsx | 82 | 38 | 20 || `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AdaptiveWindow, AnchoredPullDownMenu, AnchoredPullDownMenu.android, AndroidUpdateSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, FoldTouchpad, HomeEntryProvider, HomeHeaderGlassButton, HomeHeaderGlassButton.ios, HomeNativeStackHeader, HomeStackHeader, IncomingShareBridge, McpAppViews, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileOutboxBridge, MobilePrimitives, NativeBottomSheet, NativeBottomSheet.android, NativeChromeBackButton.ios, NativeChromeButton.ios, NativeMcpAppSurface, NativePullDownMenu, NativeRemoteDesktopView, NativeResidentHistory, NativeSwitch, OutsideTap, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RecentMessageHistories, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopChrome.ios, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopHost, RemoteDesktopIcons, RemoteDesktopMouseControls, RemoteDesktopMouseControls.ios, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, RemoteDesktopWindows, RemoteHistoryPrefetchBridge, ResidentHomeList, SheetModal, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, nativeToolbarMenuItems, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/AdaptiveWindow.tsx, apps/mobile/src/platform/OutsideTap.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.android.tsx, apps/mobile/src/platform/chrome/AnchoredPullDownMenu.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/HomeStackHeader.tsx, apps/mobile/src/platform/chrome/NativeChromeBackButton.ios.tsx, apps/mobile/src/platform/chrome/NativeChromeButton.ios.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/chrome/nativeToolbarMenuItems.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/FoldTouchpad.tsx, apps/mobile/src/remote-desktop/NativeRemoteDesktopView.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopHost.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopMouseControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopWindows.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/HomeEntryProvider.tsx, apps/mobile/src/session/HomeHeaderGlassButton.ios.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/McpAppViews.tsx, apps/mobile/src/session/MobileOutboxBridge.tsx, apps/mobile/src/session/NativeBottomSheet.android.tsx, apps/mobile/src/session/NativeBottomSheet.tsx, apps/mobile/src/session/NativeMcpAppSurface.tsx, apps/mobile/src/session/NativeResidentHistory.tsx, apps/mobile/src/session/RecentMessageHistories.tsx, apps/mobile/src/session/RemoteHistoryPrefetchBridge.tsx, apps/mobile/src/session/ResidentHomeList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts, apps/mobile/src/update/AndroidUpdateSheet.tsx | 0 | 214 | 59 |@@ -92,7 +91,6 @@| `/cc-agent/new` | NewMakerDraftRoute | `desktop.chat.new-draft` || `/cc-agent/orca/:sessionId` | OrcaWorkflowRoute | `desktop.chat.orca-workflow` || `/cc-agent/scheduled` | SchedulerPage | `desktop.chat.scheduled` |-| `/ghost-panel-window` | GhostPanelWindowLayout | `desktop.window.ghost-panel` || `/issues` | IssueTrackerFeatureLayout | `desktop.issues.guide` || `/login` | LoginPage | `desktop.auth.login` || `/maker-experimental` | MakerExperimentalView | `desktop.dev.maker-experimental` |@@ -212,7 +210,6 @@ Mobile 已由 DS-7 纳入同一台账(2026-09-10 静态入口发现),保| `desktop.skillhub.local` | Codex(DS-9 影响核对)/ kirozeng(验收协调) | legacy | — | SkillhubDiffPanel 继承 DiffView 排版,文件比较和发布逻辑不变 | 同一 DiffView 的真实 Worker/长行/大字号验证;Skill Hub 真实网络长反馈未联调;2026-09-17 或 DS-10 开工前复查 || `desktop.skillhub.market` | Codex(DS-9 影响核对)/ kirozeng(验收协调) | legacy | — | SkillhubDiffPanel 复用 DiffView,列表/网络逻辑不变 | 真实 Diff 组件验证不等于市场流程完成;真实远端联调按 DS-10 平台清单继续安排;2026-09-17 或 DS-10 开工前复查 || `desktop.window.computer-permission-guide` | Codex(DS-9 影响核对)/ kirozeng(验收协调) | legacy | — | DS-9 保留现有专属表面;未改全局 Button/主题源,按共享依赖核影响 | 本批未直接改该入口;无真实实例的独立/原生/账号/插件场景保留原合同,未作完整运行验收;kirozeng 安排所需环境,Codex 核对,2026-09-17 或 DS-10 开工前复查 |-| `desktop.window.ghost-panel` | Codex(DS-9 影响核对)/ kirozeng(验收协调) | legacy | — | DS-9 保留现有专属表面;未改全局 Button/主题源,按共享依赖核影响 | 本批未直接改该入口;无真实实例的独立/原生/账号/插件场景保留原合同,未作完整运行验收;kirozeng 安排所需环境,Codex 核对,2026-09-17 或 DS-10 开工前复查 || `desktop.window.remote-desktop` | unassigned | legacy | — | 查现有标准组件与治理 §12 当前路线;按人工下一动作接管 | 保持现状;发现问题记下一动作,本张不修视觉 || `desktop.window.resource-usage` | Codex(DS-9 影响核对)/ kirozeng(验收协调) | legacy | 外部主题导入保护 token(进程类别色) | DS-9 保留现有专属表面;未改全局 Button/主题源,按共享依赖核影响 | 本批未直接改该入口;无真实实例的独立/原生/账号/插件场景保留原合同,未作完整运行验收;kirozeng 安排所需环境,Codex 核对,2026-09-17 或 DS-10 开工前复查 || `desktop.window.review-artifact-confirm` | Codex(DS-9 影响核对)/ kirozeng(验收协调) | legacy | — | DS-9 保留现有专属表面;未改全局 Button/主题源,按共享依赖核影响 | 本批未直接改该入口;无真实实例的独立/原生/账号/插件场景保留原合同,未作完整运行验收;kirozeng 安排所需环境,Codex 核对,2026-09-17 或 DS-10 开工前复查 |diff --git a/docs/dev-rules/electron-security-and-process-boundaries.md b/docs/dev-rules/electron-security-and-process-boundaries.mdindex d85cfbd1f6..bb1b6e4885 100644--- a/docs/dev-rules/electron-security-and-process-boundaries.md+++ b/docs/dev-rules/electron-security-and-process-boundaries.md@@ -127,11 +127,11 @@ Renderer 可以负责组件渲染、交互状态、表单状态、展示数据注释和测试中写明冲突点;例外只豁免冲突项,其余预热、就绪握手、安全配置、状态清理与故障隔离要求仍然适用。-`webviewTag` 默认关闭;受控例外目前有三类——主界面与右侧栏子窗口(内置浏览器需要;+`webviewTag` 默认关闭;受控例外目前只有两类——主界面与右侧栏子窗口(内置浏览器需要;右侧栏整栏子窗口与单页签弹出窗口共用 `main/right-sidebar-window/window.ts` 的`createSidebarHostWindow` 工厂与 `sidebarWindowPreload`,`main/sidebar-tab-window/window.ts`-只改启动参数、尺寸与位置记忆),以及插件面板独立窗口(`main/ghost-panel-window/window.ts`,-仅承载 ghost 分区面板 webview)——所有例外都必须继续由 `webview-security.ts` 在 `will-attach-webview` 阶段+只改启动参数、尺寸与位置记忆)。插件面板(ghost 分区 webview)不再有专属窗口:它以右侧栏+全局页签承载,弹出时走同一扇页签窗口——所有例外都必须继续由 `webview-security.ts` 在 `will-attach-webview` 阶段覆盖 Renderer 传入的全部安全选项(hardener 挂在 `web-contents-created`,对所有窗口全局生效,ghost 附加闸只认分区与地址、不认宿主窗口)。diff --git a/scripts/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjsindex 8b33cbdb53..e57575076f 100644--- a/scripts/shared/design-inventory.mjs+++ b/scripts/shared/design-inventory.mjs@@ -361,7 +361,7 @@ export function extractViewEntries(mainEntrySource) {/*** 从 renderer/index.tsx 抽出模块图分发入口:`urlParams.get('<param>')` 条件决定- * 加载哪个 entry 模块(resource-usage / sidebar-window / ghost-panel / main)。+ * 加载哪个 entry 模块(resource-usage / sidebar-window / main)。* 返回「参数名 → 入口模块」映射——只核参数名不够:参数保留但分支改加载别的入口* 时(换窗口实现),catalog 的 productionEntry / styleRoots 仍指向旧窗口,* --check 却照样通过。映射核对与路由组件核对同构。@@ -755,25 +755,6 @@ export function catalogSurfaces() {rendererEntryModules: { sidebarWindow: './sidebar-window-entry' },routeEntryComponents: { '/sidebar-window': 'SidebarWindowLayout' },},- {- id: 'desktop.window.ghost-panel',- platform: 'desktop',- title: '插件面板独立窗口',- productionEntry:- '`?ghostPanelWindow=<id>` → renderer/ghost-panel-window-entry.tsx;hash `/ghost-panel-window`',- reachableComponents: ['GhostPanelWindowLayout'],- styleRoots: [- 'apps/desktop/src/renderer/ghost-panel-window-entry.tsx',- 'apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx',- 'apps/desktop/src/main/ghost-panel-window',- // ghost-panel-window-entry.tsx 直接导入 globals.css(同侧栏窗理由)。- 'apps/desktop/src/renderer/styles/globals.css',- 'apps/desktop/src/renderer/styles/generated/tokens.css',- ],- routerPaths: ['/ghost-panel-window'],- rendererEntryModules: { ghostPanelWindow: './ghost-panel-window-entry' },- routeEntryComponents: { '/ghost-panel-window': 'GhostPanelWindowLayout' },- },{id: 'desktop.window.resource-usage',platform: 'desktop',