Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 插件面板新增 panel.position 'tab' 右侧栏页签形态 (#297)
Lizi8620755a52fa
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex a30386bbb5..60fa61cfa7 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -360,6 +360,11 @@ describe('FORGE_GUIDE', () => {'宿主代启子进程(childSpawn)','__CINDY_NODE__','spawnEntry',+ // 2026-07-24 面板页签形态:position 'tab' 进右侧栏,每会话单例,+ // 停靠专属字段(minWidth/defaultFraction)拒装;§5 面板章节同步。+ '面板(panel.html/css/js)',+ 'panel.position',+ '右侧栏页签',]) {expect(FORGE_GUIDE).toContain(marker);}diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex d633b2459d..f35df63032 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -677,7 +677,10 @@ my-ghost/"cindy": { "image": ["generate", "edit"] }, // 声明了 cindy 槽时必写:能力详单,见下"panel": { "title": "面板标题", "html": "panel.html", "position": "right","minWidth": 240, "defaultFraction": 0.24 },- // panel.position:相对主聊天窗的停靠位,right(缺省)/ left;top/bottom 暂未支持(排期中)+ // panel.position:面板显示形态。right(缺省)/ left = 停靠主聊天窗两侧;+ // "tab" = 右侧栏页签(与文件/审查/终端同一容器,每会话至多一个,用户从+ // 空态列表或「+」菜单打开;此形态没有拖缝宽度,声明 minWidth /+ // defaultFraction 会被拒装,请移除)。top/bottom 暂未支持(排期中)"settingsHtml": "settings.html", // 可选:设置页「自定义设置区」自绘界面(见 §4.8;声明了用户填的凭证时必填——凭证收单界面,见 §4.7)"settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮,高至 800);内容会动态增减时才声明,避免抖动}@@ -2034,6 +2037,12 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);## 5. 面板(panel.html/css/js)+- 显示形态由 \`panel.position\` 决定:\`right\`(缺省)/ \`left\` = 停靠主聊天窗两侧+ 的常驻面板;\`"tab"\` = 右侧栏页签——与文件/审查/终端同一容器,每会话至多+ 一个页签,由用户从右侧栏空态列表或「+」菜单打开(不随装入自动弹出)。页签+ 形态没有拖缝宽度语义,声明 \`minWidth\` / \`defaultFraction\` 会被拒装。两种形态+ 的面板代码完全一样(同一 panel.html,供片/主题/媒体规则不变),只是宿主容器+ 不同;页签形态请把界面做成自适应宽度;- 与电子脑同源,用 \`BroadcastChannel('<自定名>')\` 通信(电子脑发,面板收);- 取自己的媒体:\`cindy-ghost://<id>/media/<指纹><后缀>\`(主机查账验归属,别人的图 404);- 重启回放:\`fetch('cindy-ghost://<id>/gallery')\` 返回本意识作品清单 \`[{src, caption}]\`;diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsxnew file mode 100644index 0000000000..0b742a5701--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx@@ -0,0 +1,121 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it } from 'vitest';++import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';+import {+ _resetTabKindRegistry,+ getTabKind,+ listGhostTabMenuMetas,+} from '../../features/right-sidebar/registry';+import { __resetPanelRegistryForTest, hasPanelKind } from '../../panels/registry';+import { __resetGhostPanelsForTest, syncGhostPanelRegistrations } from '../ghostPanels';+import {+ __resetGhostTabPluginsForTest,+ buildGhostTabPlugin,+ syncGhostTabRegistrations,+} from '../ghostTabPlugins';++/** 造一个已装意识(panel 可覆写;enabled 默认 true)。 */+function ghost(id: string, panel?: GhostManifest['panel'], enabled = true): InstalledGhost {+ const manifest: GhostManifest = {+ schemaVersion: 2,+ id,+ name: `${id} 意识`,+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['panel'],+ panel: panel ?? { html: 'panel.html', position: 'tab' },+ };+ return { manifest, dir: `/fake/${id}`, enabled };+}++afterEach(() => {+ __resetGhostTabPluginsForTest();+ _resetTabKindRegistry();+ __resetPanelRegistryForTest();+ __resetGhostPanelsForTest();+});++describe('buildGhostTabPlugin · 契约形状', () => {+ it('kind 复用 ghost:<id>;menu 单例、labelText 取 panel.title 缺省意识名', () => {+ const withTitle = buildGhostTabPlugin(ghost('art', { html: 'p.html', position: 'tab', title: '画廊' }).manifest);+ expect(withTitle.kind).toBe('ghost:art');+ expect(withTitle.menu).toMatchObject({+ kind: 'ghost:art',+ labelText: '画廊',+ labelKey: 'rightSidebar.tabs.kinds.ghostPanel',+ singleton: true,+ enabled: true,+ });+ expect(withTitle.defaultState()).toBeNull();++ const noTitle = buildGhostTabPlugin(ghost('plain').manifest);+ expect(noTitle.menu.labelText).toBe('plain 意识');+ });+});++describe('syncGhostTabRegistrations · Tab 注册表与已装清单对齐', () => {+ it("position:'tab' 且启用的注册;停用/消失的注销", () => {+ syncGhostTabRegistrations([ghost('a'), ghost('b')]);+ expect(getTabKind('ghost:a')).not.toBeNull();+ expect(getTabKind('ghost:b')).not.toBeNull();++ // b 停用、a 保留+ syncGhostTabRegistrations([ghost('a'), ghost('b', undefined, false)]);+ expect(getTabKind('ghost:a')).not.toBeNull();+ expect(getTabKind('ghost:b')).toBeNull();++ // 全卸光+ syncGhostTabRegistrations([]);+ expect(getTabKind('ghost:a')).toBeNull();+ });++ it('清单没变 → 不重注册(plugin 身份稳定);换版 → 原位换新', () => {+ syncGhostTabRegistrations([ghost('a')]);+ const before = getTabKind('ghost:a');+ syncGhostTabRegistrations([ghost('a')]);+ expect(getTabKind('ghost:a')).toBe(before);++ const upgraded = ghost('a');+ upgraded.manifest.version = '2.0.0';+ syncGhostTabRegistrations([upgraded]);+ const after = getTabKind('ghost:a');+ expect(after).not.toBe(before);+ expect(after).not.toBeNull();+ });++ it('listGhostTabMenuMetas 只含 ghost 项,按 labelText 稳定排序', () => {+ syncGhostTabRegistrations([+ ghost('zeta', { html: 'p.html', position: 'tab', title: '备忘' }),+ ghost('alpha', { html: 'p.html', position: 'tab', title: '画廊' }),+ ]);+ expect(listGhostTabMenuMetas().map((m) => m.labelText)).toEqual(['备忘', '画廊']);+ });+});++describe('syncGhostPanelRegistrations · 按 position 分派两个注册表', () => {+ it("tab 型只进 Tab 注册表;停靠型只进顶层面板注册表", () => {+ syncGhostPanelRegistrations([+ ghost('tabbed'),+ ghost('docked', { html: 'panel.html', position: 'right' }),+ ]);+ expect(getTabKind('ghost:tabbed')).not.toBeNull();+ expect(hasPanelKind('ghost:tabbed')).toBe(false);+ expect(hasPanelKind('ghost:docked')).toBe(true);+ expect(getTabKind('ghost:docked')).toBeNull();+ });++ it('换版把 position 从 right 改成 tab → 顶层注销、页签注册(反向亦然)', () => {+ syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'right' })]);+ expect(hasPanelKind('ghost:m')).toBe(true);++ syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'tab' })]);+ expect(hasPanelKind('ghost:m')).toBe(false);+ expect(getTabKind('ghost:m')).not.toBeNull();++ syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'left' })]);+ expect(hasPanelKind('ghost:m')).toBe(true);+ expect(getTabKind('ghost:m')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsxnew file mode 100644index 0000000000..8677108c95--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx@@ -0,0 +1,274 @@+import { useEffect, useRef, useState, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';+import { CircleAlert, Copy, FolderOpen } from 'lucide-react';+import type { ContextMenuEvent, WebviewTag } from 'electron';++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { toast } from '@/lib/toast';++import { GHOST_SCHEME, ghostPartition, type GhostManifest } from '../../shared/ghost';+import { createGhostThemeInjector, observeHostTheme } from './ghostPanelTheme';++/**+ * 意识面板体(webview 供片)—— 顶层停靠 pane(ghostPanels)与右侧栏页签+ * (ghostTabPlugins)共用的渲染内核,从 ghostPanels.tsx 原样抽出:+ * 沙箱 webview 装载、主题注入、崩溃接管、媒体右键菜单,全部与宿主容器无关。+ * 安全边界不变:分区/地址由 main 侧 webview 附加闸验明正身(webview-security),+ * 本模块不因换容器多要任何特权。+ */++/**+ * 面板错误接管态:芯片型意识崩溃 / 熔断时面板**不关闭**,+ * 原地显示错误信息 + 两个动作——「重载意识」(清熔断记账重新拉起)与+ * 「关闭意识」(转沉睡,面板收起,可到设置里再唤醒)。+ */+export function GhostPanelError({+ manifest,+ state,+ onReload,+}: {+ manifest: GhostManifest;+ state: string;+ /** 重载动作;缺省走 ghosts:reload(离屏沙箱路径),面板 webview 路径传本地重挂载。 */+ onReload?: () => void;+}): ReactNode {+ const { t } = useTranslation();+ const reload = onReload ?? (() => void window.electronAPI.ghosts.reload(manifest.id).catch(() => {}));+ return (+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-4">+ <CircleAlert size={22} className="text-[var(--error-fg)]" />+ <p className="text-center text-[12px] leading-relaxed text-[var(--text-secondary)]">+ {t(state === 'fused' ? 'settings.ghosts.panelError.fused' : 'settings.ghosts.panelError.crashed')}+ </p>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={reload}+ className="rounded-full border border-[var(--border-default)] px-3.5 py-1.5 text-[12px] font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-chip)]"+ >+ {t('settings.ghosts.panelError.reload')}+ </button>+ {/* 关闭 = 转沉睡,可逆动作,按 docs/design-rules/cindy-design-system.md 红色纪律走灰度次按钮(红只留错误图标)。 */}+ <button+ type="button"+ onClick={() => void window.electronAPI.ghosts.setEnabled(manifest.id, false).catch(() => {})}+ className="rounded-full border border-[var(--border-default)] px-3.5 py-1.5 text-[12px] font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-chip)]"+ >+ {t('settings.ghosts.panelError.close')}+ </button>+ </div>+ </div>+ );+}++/** 面板媒体右键菜单的一次弹出:坐标(宿主窗口系)+ 主机换发的地址与类别。 */+interface GhostPanelMediaMenuState {+ x: number;+ y: number;+ /** 主机拼装的 cindy-media:// 地址(过闸产物,直接喂通用媒体 IPC)。 */+ url: string;+ kind: 'image' | 'video';+}++/**+ * 意识面板产物的右键菜单:与聊天流 ChatImageView / ChatVideoView+ * 右键同款动作——复制文件(copyMediaToClipboard,文件引用形式)+ 打开所在+ * 目录(showItemInFolder)。菜单是宿主自绘(webview 里的右键经 Electron+ * context-menu 事件转出,面板自己画不了也伪造不了),地址已过 main 闸换发,+ * 两个动作走与聊天媒体完全相同的通用 IPC。+ */+function GhostPanelMediaMenu({+ menu,+ onClose,+}: {+ menu: GhostPanelMediaMenuState;+ onClose: () => void;+}): ReactNode {+ const { t } = useTranslation();++ async function handleCopy(): Promise<void> {+ const res = await window.electronAPI.copyMediaToClipboard({ url: menu.url });+ if (res.success) {+ toast.success(t(menu.kind === 'video' ? 'chat.media.videoCopied' : 'chat.media.imageCopied'));+ } else {+ toast.error(res.error ?? t('chat.media.copyFailed'));+ }+ onClose();+ }++ async function handleReveal(): Promise<void> {+ const res = await window.electronAPI.showItemInFolder({ url: menu.url });+ if (!res.success) {+ toast.error(res.error ?? t('chat.media.openFolderFailed'));+ }+ onClose();+ }++ return (+ <DropdownMenu+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <DropdownMenuTrigger asChild>+ <span+ aria-hidden+ style={{+ position: 'fixed',+ left: menu.x,+ top: menu.y,+ width: 0,+ height: 0,+ pointerEvents: 'none',+ }}+ />+ </DropdownMenuTrigger>+ {/* z-index 必须压过 webview:与 lightbox / 对话框等「webview 上方浮层」+ 同档(z-[10000]);默认 z-50 会被面板 webview 的合成层盖住——菜单+ 开了但看不见(指针事件已被 Radix 关掉,表现为光标变默认箭头)。 */}+ <DropdownMenuContent align="start" sideOffset={2} style={{ zIndex: 10000 }}>+ <DropdownMenuItem onClick={handleCopy}>+ <Copy className="mr-2 h-4 w-4" />+ {t(menu.kind === 'video' ? 'chat.media.copyVideo' : 'chat.media.copyImage')}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={handleReveal}>+ <FolderOpen className="mr-2 h-4 w-4" />+ {t(menu.kind === 'video' ? 'chat.media.revealVideo' : 'chat.media.revealImage')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++/**+ * 从一次 webview 右键的命中参数里挑出本意识的媒体地址;不是媒体 cell 返回 null。+ * srcURL 优先(直接右键在 <img> / <video> 上,/media/ 形状),linkURL 兜底+ * (视频缩略 pointer-events:none 时命中的是外层 <a>,/preview/ 形状)。+ * 只认**本面板意识 id** 前缀——面板里出现别的意识地址(理论上只能是作者硬写)+ * 不弹菜单;严校验(指纹形状/归属/mime)仍在 main 闸,这里只是粗筛。+ */+export function pickGhostPanelMediaUri(+ params: { srcURL?: string; linkURL?: string },+ ghostId: string,+): string | null {+ const re = new RegExp(`^${GHOST_SCHEME}://${ghostId}/(media|preview)/[^/?#]+$`);+ for (const candidate of [params.srcURL, params.linkURL]) {+ if (candidate && re.test(candidate)) return candidate;+ }+ return null;+}++/**+ * 芯片型意识的自绘面板体:一块沙箱 webview 装载意识自己的+ * panel.html——分区/地址由 main 侧 webview 附加闸验明正身(webview-security),+ * 主题 token 在 dom-ready 注入、主机换肤时重灌(ghostPanelTheme)。+ * webview 崩溃 = 本地错误接管态(重载 = 原地重挂载,不经主机)。+ */+export function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): ReactNode {+ const [crashed, setCrashed] = useState(false);+ const [generation, setGeneration] = useState(0);+ const [mediaMenu, setMediaMenu] = useState<GhostPanelMediaMenuState | null>(null);+ const hostRef = useRef<HTMLDivElement | null>(null);++ const panelHtml = manifest.panel?.html;+ useEffect(() => {+ if (crashed || !panelHtml) return;+ const host = hostRef.current;+ if (!host) return;+ const webview = document.createElement('webview') as WebviewTag;+ webview.setAttribute('partition', ghostPartition(manifest.id));+ webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${panelHtml}`);+ webview.setAttribute('style', 'display:flex;flex:1 1 auto;width:100%;height:100%;');+ let disposed = false;+ let themeTimer: ReturnType<typeof setTimeout> | null = null;+ // 状态机见 createGhostThemeInjector:换肤误触发去重、dom-ready(含拖动+ // 换位触发的 Electron 整页重载)无条件重灌,规则都封在里面(带单测)。+ const injector = createGhostThemeInjector(webview);+ // 突发属性变动(换肤瞬间多个属性接连翻动)合并成一次注入。+ const scheduleInjectTheme = () => {+ if (themeTimer !== null) return;+ themeTimer = setTimeout(() => {+ themeTimer = null;+ if (!disposed) injector.inject();+ }, 50);+ };+ const onDomReady = () => injector.onDomReady();+ const onGone = () => {+ if (!disposed) setCrashed(true);+ };+ // 右键产物 cell → 宿主自绘菜单(复制文件 / 打开所在目录,与聊天媒体同款)。+ // context-menu 是 Chromium 对真实右键的原生上报,guest 脚本 dispatchEvent+ // 触发不了;地址过 main 闸(形状/归属/mime)换发 cindy-media:// 后才弹,+ // 非本意识名下的产物静默不弹(与预览闸同纪律,不给沙箱差异面)。+ const onContextMenu = (e: ContextMenuEvent) => {+ const uri = pickGhostPanelMediaUri(e.params, manifest.id);+ if (!uri) return;+ // 坐标:webview 转发的 context-menu params.x/y 已经是宿主窗口坐标系+ // (OOPIF 命中测试按根帧算;Windows 实测 2077 > 面板宽,叠加 rect 会把+ // 菜单顶出屏外),直接用,不要再加 webview 偏移。+ const pos = { x: e.params.x, y: e.params.y };+ void window.electronAPI.ghosts.resolvePanelMedia(uri, 'menu').then(+ ({ url, kind }) => {+ if (disposed) return;+ // 焦点还在 guest 里,不挪回宿主的话 Esc/方向键进不了菜单+ // (与 GhostMediaLightboxHost 同款处理)。+ const active = document.activeElement;+ if (active instanceof HTMLElement) active.blur();+ setMediaMenu({ ...pos, url, kind: kind ?? 'image' });+ },+ () => {+ /* 过闸失败:静默不弹(调用方无需区分原因)。 */+ },+ );+ };+ webview.addEventListener('dom-ready', onDomReady);+ webview.addEventListener('render-process-gone', onGone);+ webview.addEventListener('context-menu', onContextMenu);+ const unobserveTheme = observeHostTheme(scheduleInjectTheme);+ host.appendChild(webview);+ return () => {+ disposed = true;+ injector.dispose();+ if (themeTimer !== null) clearTimeout(themeTimer);+ unobserveTheme();+ webview.removeEventListener('dom-ready', onDomReady);+ webview.removeEventListener('render-process-gone', onGone);+ webview.removeEventListener('context-menu', onContextMenu);+ webview.remove();+ // 菜单与 webview 同生共死:原位升级/重载导致的重挂载把开着的旧菜单+ // 一并收掉,避免坐标/内容指向已不存在的旧面板上下文。+ setMediaMenu(null);+ };+ // version 入依赖:原位更新换版后 webview 重挂载,面板立刻跑新代码+ // (供片协议直读安装目录,不重挂会一直渲染旧版缓存的页面)。+ }, [crashed, generation, manifest.id, manifest.version, panelHtml]);++ if (crashed) {+ return (+ <GhostPanelError+ manifest={manifest}+ state="crashed"+ onReload={() => {+ setGeneration((g) => g + 1);+ setCrashed(false);+ }}+ />+ );+ }+ // data-ghost-webview:拖缝/拖面板期间 body.resizing-pane 让指针穿透+ // (globals.css 与内置浏览器 pool 同款规则)。+ return (+ <>+ <div ref={hostRef} data-ghost-webview className="flex min-h-0 flex-1" />+ {mediaMenu ? (+ <GhostPanelMediaMenu menu={mediaMenu} onClose={() => setMediaMenu(null)} />+ ) : null}+ </>+ );+}diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsxindex 3aa5d262a3..18b10a7317 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx@@ -1,27 +1,11 @@-import { useEffect, useRef, useState, type ReactNode } from 'react';-import { useTranslation } from 'react-i18next';-import { CircleAlert, Copy, FolderOpen } from 'lucide-react';-import type { ContextMenuEvent, WebviewTag } from 'electron';+import { useEffect, useState, type ReactNode } from 'react';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';-import { toast } from '@/lib/toast';--import {- GHOST_SCHEME,- ghostPanelKind,- ghostPartition,- type GhostManifest,- type InstalledGhost,-} from '../../shared/ghost';+import { ghostPanelKind, type GhostManifest, type InstalledGhost } from '../../shared/ghost';import { usePanelWidth } from '../layout/paneWidths';import { PanelChrome } from '../panels/PanelChrome';import { registerPanelKind, unregisterPanelKind, type PanelComponentProps } from '../panels/registry';-import { createGhostThemeInjector, observeHostTheme } from './ghostPanelTheme';+import { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';+import { syncGhostTabRegistrations } from './ghostTabPlugins';import { pruneGhostSettingsSnapshots } from './ghostSettingsSnapshot';import { useGhostRuntimeState } from './runtimeStates';@@ -37,260 +21,13 @@ import { useGhostRuntimeState } from './runtimeStates';* - 卸下:广播里不见了的 kind 注销 → 布局树里它的 pane 按"未安装意识"隐藏,* 树数据保留,重装即原位复活(§6 规则 5 的正式生效点)。*- * 声明卡(v1)面板 = 标准头 + 清单正文,无任何可执行内容;芯片卡的沙箱渲染- * 由独立沙箱负责,本模块只认清单数据。+ * 面板体(webview 供片/主题注入/崩溃接管/媒体右键)在 ghostPanelBody.tsx,+ * 与右侧栏页签形态(position:'tab',ghostTabPlugins.tsx)共用;本模块只管+ * 停靠形态(left / right)与两个注册表的同步入口。*/-/**- * 面板错误接管态:芯片型意识崩溃 / 熔断时面板**不关闭**,- * 原地显示错误信息 + 两个动作——「重载意识」(清熔断记账重新拉起)与- * 「关闭意识」(转沉睡,面板收起,可到设置里再唤醒)。- */-function GhostPanelError({- manifest,- state,- onReload,-}: {- manifest: GhostManifest;- state: string;- /** 重载动作;缺省走 ghosts:reload(离屏沙箱路径),面板 webview 路径传本地重挂载。 */- onReload?: () => void;-}): ReactNode {- const { t } = useTranslation();- const reload = onReload ?? (() => void window.electronAPI.ghosts.reload(manifest.id).catch(() => {}));- return (- <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-4">- <CircleAlert size={22} className="text-[var(--error-fg)]" />- <p className="text-center text-[12px] leading-relaxed text-[var(--text-secondary)]">- {t(state === 'fused' ? 'settings.ghosts.panelError.fused' : 'settings.ghosts.panelError.crashed')}- </p>- <div className="flex items-center gap-2">- <button- type="button"- onClick={reload}- className="rounded-full border border-[var(--border-default)] px-3.5 py-1.5 text-[12px] font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-chip)]"- >- {t('settings.ghosts.panelError.reload')}- </button>- {/* 关闭 = 转沉睡,可逆动作,按 docs/design-rules/cindy-design-system.md 红色纪律走灰度次按钮(红只留错误图标)。 */}- <button- type="button"- onClick={() => void window.electronAPI.ghosts.setEnabled(manifest.id, false).catch(() => {})}- className="rounded-full border border-[var(--border-default)] px-3.5 py-1.5 text-[12px] font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-chip)]"- >- {t('settings.ghosts.panelError.close')}- </button>- </div>- </div>- );-}--/** 面板媒体右键菜单的一次弹出:坐标(宿主窗口系)+ 主机换发的地址与类别。 */-interface GhostPanelMediaMenuState {- x: number;- y: number;- /** 主机拼装的 cindy-media:// 地址(过闸产物,直接喂通用媒体 IPC)。 */- url: string;- kind: 'image' | 'video';-}--/**- * 意识面板产物的右键菜单:与聊天流 ChatImageView / ChatVideoView- * 右键同款动作——复制文件(copyMediaToClipboard,文件引用形式)+ 打开所在- * 目录(showItemInFolder)。菜单是宿主自绘(webview 里的右键经 Electron- * context-menu 事件转出,面板自己画不了也伪造不了),地址已过 main 闸换发,- * 两个动作走与聊天媒体完全相同的通用 IPC。- */-function GhostPanelMediaMenu({- menu,- onClose,-}: {- menu: GhostPanelMediaMenuState;- onClose: () => void;-}): ReactNode {- const { t } = useTranslation();-- async function handleCopy(): Promise<void> {- const res = await window.electronAPI.copyMediaToClipboard({ url: menu.url });- if (res.success) {- toast.success(t(menu.kind === 'video' ? 'chat.media.videoCopied' : 'chat.media.imageCopied'));- } else {- toast.error(res.error ?? t('chat.media.copyFailed'));- }- onClose();- }-- async function handleReveal(): Promise<void> {- const res = await window.electronAPI.showItemInFolder({ url: menu.url });- if (!res.success) {- toast.error(res.error ?? t('chat.media.openFolderFailed'));- }- onClose();- }-- return (- <DropdownMenu- open- onOpenChange={(open) => {- if (!open) onClose();- }}- >- <DropdownMenuTrigger asChild>- <span- aria-hidden- style={{- position: 'fixed',- left: menu.x,- top: menu.y,- width: 0,- height: 0,- pointerEvents: 'none',- }}- />- </DropdownMenuTrigger>- {/* z-index 必须压过 webview:与 lightbox / 对话框等「webview 上方浮层」- 同档(z-[10000]);默认 z-50 会被面板 webview 的合成层盖住——菜单- 开了但看不见(指针事件已被 Radix 关掉,表现为光标变默认箭头)。 */}- <DropdownMenuContent align="start" sideOffset={2} style={{ zIndex: 10000 }}>- <DropdownMenuItem onClick={handleCopy}>- <Copy className="mr-2 h-4 w-4" />- {t(menu.kind === 'video' ? 'chat.media.copyVideo' : 'chat.media.copyImage')}- </DropdownMenuItem>- <DropdownMenuItem onClick={handleReveal}>- <FolderOpen className="mr-2 h-4 w-4" />- {t(menu.kind === 'video' ? 'chat.media.revealVideo' : 'chat.media.revealImage')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );-}--/**- * 从一次 webview 右键的命中参数里挑出本意识的媒体地址;不是媒体 cell 返回 null。- * srcURL 优先(直接右键在 <img> / <video> 上,/media/ 形状),linkURL 兜底- * (视频缩略 pointer-events:none 时命中的是外层 <a>,/preview/ 形状)。- * 只认**本面板意识 id** 前缀——面板里出现别的意识地址(理论上只能是作者硬写)- * 不弹菜单;严校验(指纹形状/归属/mime)仍在 main 闸,这里只是粗筛。- */-export function pickGhostPanelMediaUri(- params: { srcURL?: string; linkURL?: string },- ghostId: string,-): string | null {- const re = new RegExp(`^${GHOST_SCHEME}://${ghostId}/(media|preview)/[^/?#]+$`);- for (const candidate of [params.srcURL, params.linkURL]) {- if (candidate && re.test(candidate)) return candidate;- }- return null;-}--/**- * 芯片型意识的自绘面板体:一块沙箱 webview 装载意识自己的- * panel.html——分区/地址由 main 侧 webview 附加闸验明正身(webview-security),- * 主题 token 在 dom-ready 注入、主机换肤时重灌(ghostPanelTheme)。- * webview 崩溃 = 本地错误接管态(重载 = 原地重挂载,不经主机)。- */-function GhostChipPanelBody({ manifest }: { manifest: GhostManifest }): ReactNode {- const [crashed, setCrashed] = useState(false);- const [generation, setGeneration] = useState(0);- const [mediaMenu, setMediaMenu] = useState<GhostPanelMediaMenuState | null>(null);- const hostRef = useRef<HTMLDivElement | null>(null);-- const panelHtml = manifest.panel?.html;- useEffect(() => {- if (crashed || !panelHtml) return;- const host = hostRef.current;- if (!host) return;- const webview = document.createElement('webview') as WebviewTag;- webview.setAttribute('partition', ghostPartition(manifest.id));- webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${panelHtml}`);- webview.setAttribute('style', 'display:flex;flex:1 1 auto;width:100%;height:100%;');- let disposed = false;- let themeTimer: ReturnType<typeof setTimeout> | null = null;- // 状态机见 createGhostThemeInjector:换肤误触发去重、dom-ready(含拖动- // 换位触发的 Electron 整页重载)无条件重灌,规则都封在里面(带单测)。- const injector = createGhostThemeInjector(webview);- // 突发属性变动(换肤瞬间多个属性接连翻动)合并成一次注入。- const scheduleInjectTheme = () => {- if (themeTimer !== null) return;- themeTimer = setTimeout(() => {- themeTimer = null;- if (!disposed) injector.inject();- }, 50);- };- const onDomReady = () => injector.onDomReady();- const onGone = () => {- if (!disposed) setCrashed(true);- };- // 右键产物 cell → 宿主自绘菜单(复制文件 / 打开所在目录,与聊天媒体同款)。- // context-menu 是 Chromium 对真实右键的原生上报,guest 脚本 dispatchEvent- // 触发不了;地址过 main 闸(形状/归属/mime)换发 cindy-media:// 后才弹,- // 非本意识名下的产物静默不弹(与预览闸同纪律,不给沙箱差异面)。- const onContextMenu = (e: ContextMenuEvent) => {- const uri = pickGhostPanelMediaUri(e.params, manifest.id);- if (!uri) return;- // 坐标:webview 转发的 context-menu params.x/y 已经是宿主窗口坐标系- // (OOPIF 命中测试按根帧算;Windows 实测 2077 > 面板宽,叠加 rect 会把- // 菜单顶出屏外),直接用,不要再加 webview 偏移。- const pos = { x: e.params.x, y: e.params.y };- void window.electronAPI.ghosts.resolvePanelMedia(uri, 'menu').then(- ({ url, kind }) => {- if (disposed) return;- // 焦点还在 guest 里,不挪回宿主的话 Esc/方向键进不了菜单- // (与 GhostMediaLightboxHost 同款处理)。- const active = document.activeElement;- if (active instanceof HTMLElement) active.blur();- setMediaMenu({ ...pos, url, kind: kind ?? 'image' });- },- () => {- /* 过闸失败:静默不弹(调用方无需区分原因)。 */- },- );- };- webview.addEventListener('dom-ready', onDomReady);- webview.addEventListener('render-process-gone', onGone);- webview.addEventListener('context-menu', onContextMenu);- const unobserveTheme = observeHostTheme(scheduleInjectTheme);- host.appendChild(webview);- return () => {- disposed = true;- injector.dispose();- if (themeTimer !== null) clearTimeout(themeTimer);- unobserveTheme();- webview.removeEventListener('dom-ready', onDomReady);- webview.removeEventListener('render-process-gone', onGone);- webview.removeEventListener('context-menu', onContextMenu);- webview.remove();- // 菜单与 webview 同生共死:原位升级/重载导致的重挂载把开着的旧菜单- // 一并收掉,避免坐标/内容指向已不存在的旧面板上下文。- setMediaMenu(null);- };- // version 入依赖:原位更新换版后 webview 重挂载,面板立刻跑新代码- // (供片协议直读安装目录,不重挂会一直渲染旧版缓存的页面)。- }, [crashed, generation, manifest.id, manifest.version, panelHtml]);-- if (crashed) {- return (- <GhostPanelError- manifest={manifest}- state="crashed"- onReload={() => {- setGeneration((g) => g + 1);- setCrashed(false);- }}- />- );- }- // data-ghost-webview:拖缝/拖面板期间 body.resizing-pane 让指针穿透- // (globals.css 与内置浏览器 pool 同款规则)。- return (- <>- <div ref={hostRef} data-ghost-webview className="flex min-h-0 flex-1" />- {mediaMenu ? (- <GhostPanelMediaMenu menu={mediaMenu} onClose={() => setMediaMenu(null)} />- ) : null}- </>- );-}+// 兼容既有导入点(测试等):粗筛纯函数随面板体一起搬家,原路径继续可用。+export { pickGhostPanelMediaUri } from './ghostPanelBody';/** 意识面板宿主:标准头(PanelChrome)+ 沙箱自绘面板体(崩溃时错误接管)。 */function GhostPanel({@@ -326,15 +63,20 @@ const registeredFingerprints = new Map<string, string>();* 把注册表与"当前已装清单"对齐:新装的注册、卸下的注销、没变的不动。* 停用(enabled=false)的意识视同不在场 —— 面板注销、布局里 pane 隐藏休眠,* 重新启用时走同一条对齐路径复活(与"卸下再重装"共用 §6 规则 5 语义)。+ * position:'tab' 的面板不进本注册表,分派给右侧栏页签注册表(ghostTabPlugins);+ * 换版改 position 时,两边的差集注销各自兜住旧形态。*/export function syncGhostPanelRegistrations(ghosts: InstalledGhost[]): void {// 顺手清设置区快照缓存的孤儿(卸载的意识不该在 localStorage 留位图);// 本函数是"已装清单"的唯一同步点(启动 + ghosts:changed),挂这里最省。// 注意用全量清单(含沉睡)——沉睡只是不注册面板,快照仍然有效。pruneGhostSettingsSnapshots(ghosts.map((g) => g.manifest.id));+ // 页签形态与停靠形态同源同步:一次广播喂两个注册表,不各自订阅。+ syncGhostTabRegistrations(ghosts);const seen = new Set<string>();for (const { manifest, enabled } of ghosts) {if (!manifest.panel) continue; // 无面板的意识(未来纯工具卡)不进注册表+ if (manifest.panel.position === 'tab') continue; // 页签形态归右侧栏注册表if (enabled === false) continue; // 停用 = 休眠,不注册(注销走下方 seen 差集)const kind = ghostPanelKind(manifest.id);seen.add(kind);diff --git a/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsx b/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsxnew file mode 100644index 0000000000..08032a37b7--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/ghostTabPlugins.tsx@@ -0,0 +1,105 @@+import type { ReactNode } from 'react';+import { Puzzle } from 'lucide-react';++import { ghostPanelKind, type GhostManifest, type InstalledGhost } from '../../shared/ghost';+import { registerTabKind, unregisterTabKind } from '../features/right-sidebar/registry';+import type { TabKindId, TabKindPlugin } from '../features/right-sidebar/types';+import { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';+import { useGhostRuntimeState } from './runtimeStates';++/**+ * 意识面板的右侧栏页签形态(panel.position: 'tab')接入 Tab 插件注册表。+ *+ * 与顶层停靠形态(ghostPanels.tsx)的关系:+ * - 同一数据源:syncGhostPanelRegistrations 是"已装清单"的唯一同步点+ * (启动 listSync + ghosts:changed 广播),按 position 分派到两个注册表,+ * 本模块不自建订阅;+ * - 同一面板体:webview 供片/主题注入/崩溃接管全部复用 ghostPanelBody,+ * 沙箱边界与特权面零变化(附加闸只认分区/地址,与宿主容器无关);+ * - 同一复活语义:停用/卸下 → unregisterTabKind,已开的 tab 落回 Shell 的+ * PlaceholderBody(数据保留);重新启用 → 重注册,原 tab 原位复活。+ *+ * 页签语义对齐 review:menu.singleton = true,每 session 至多一个;+ * kind 复用 ghostPanelKind 的 `ghost:<id>`(DB kind 列无枚举约束,可直存)。+ */++/** 页签体:Shell 已提供容器与 TabBar,不再套 PanelChrome 标准头。 */+function GhostTabBody({ manifest }: { manifest: GhostManifest }): ReactNode {+ // 沙箱崩了/熔断 → 与停靠形态同款错误接管(GhostPanel broken 分支的等价物)。+ const runtimeState = useGhostRuntimeState(manifest.id);+ const broken = runtimeState === 'crashed' || runtimeState === 'fused';+ return (+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">+ {broken ? (+ <GhostPanelError manifest={manifest} state={runtimeState} />+ ) : (+ <GhostChipPanelBody manifest={manifest} />+ )}+ </div>+ );+}++/** 由清单构造一份 Tab 插件契约(纯函数,方便单测直接断言 menu 形状)。 */+export function buildGhostTabPlugin(manifest: GhostManifest): TabKindPlugin {+ const kind = ghostPanelKind(manifest.id) as TabKindId;+ const label = manifest.panel?.title ?? manifest.name;+ const TabPillTitle: TabKindPlugin['TabPillTitle'] = () => <>{label}</>;+ const TabPillIcon: NonNullable<TabKindPlugin['TabPillIcon']> = () => <Puzzle size={13} />;+ const TabBody: TabKindPlugin['TabBody'] = () => <GhostTabBody manifest={manifest} />;+ return {+ kind,+ menu: {+ kind,+ // 插件名是用户内容进不了 i18n,走 labelText 原文;labelKey 只作兜底。+ labelKey: 'rightSidebar.tabs.kinds.ghostPanel',+ labelText: label,+ icon: Puzzle,+ // 排内置项之后;「+」菜单/空态的动态分组内部按 labelText 排+ // (listGhostTabMenuMetas),order 不参与组内排序。+ order: 100,+ enabled: true,+ // 与 review 同款单例:每 session 至多一个页签,已开则切过去。+ singleton: true,+ },+ TabPillTitle,+ TabPillIcon,+ TabBody,+ defaultState: () => null,+ };+}++/** 已注册页签插件:kind → 清单指纹(与 ghostPanels 的 fingerprint 语义一致)。 */+const registeredTabFingerprints = new Map<string, string>();++/**+ * 把 Tab 注册表与"当前已装清单"对齐:启用且 position:'tab' 的注册,+ * 消失/停用/换形态的注销。由 syncGhostPanelRegistrations 每次同步时调用。+ */+export function syncGhostTabRegistrations(ghosts: InstalledGhost[]): void {+ const seen = new Set<string>();+ for (const { manifest, enabled } of ghosts) {+ if (manifest.panel?.position !== 'tab') continue;+ if (enabled === false) continue;+ const kind = ghostPanelKind(manifest.id);+ seen.add(kind);+ const fingerprint = JSON.stringify(manifest);+ if (registeredTabFingerprints.get(kind) === fingerprint) continue;+ // 原位升级换版:先注销旧注册再挂新的(registerTabKind 对重复 kind 抛错)。+ if (registeredTabFingerprints.has(kind)) unregisterTabKind(kind as TabKindId);+ registeredTabFingerprints.set(kind, fingerprint);+ registerTabKind(buildGhostTabPlugin(manifest));+ }+ for (const kind of [...registeredTabFingerprints.keys()]) {+ if (seen.has(kind)) continue;+ registeredTabFingerprints.delete(kind);+ unregisterTabKind(kind as TabKindId);+ }+}++/** 仅测试用:清空本模块注册,保证用例间隔离。 */+export function __resetGhostTabPluginsForTest(): void {+ for (const kind of [...registeredTabFingerprints.keys()]) {+ unregisterTabKind(kind as TabKindId);+ }+ registeredTabFingerprints.clear();+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsxindex d3bfd7577a..4118ca51be 100644--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next';import { FileDiff, FolderTree, Globe, Terminal } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import { cn } from '@/lib/utils';+import { listGhostTabMenuMetas, useTabKindRegistryVersion } from './registry';import type { TabKindId, TabKindMenuMeta } from './types';const DROPDOWN_WIDTH = 220;@@ -108,6 +109,9 @@ export function AddTabDropdown({ onClose, onSelect, existingKinds }: AddTabDropdconst enabled = MENU_ITEMS.filter((m) => m.enabled).sort((a, b) => a.order - b.order);const coming = MENU_ITEMS.filter((m) => !m.enabled).sort((a, b) => a.order - b.order);+ // 插件页签(panel.position:'tab')动态分组:随装/卸/停用增减,版本号驱动重渲。+ useTabKindRegistryVersion();+ const ghostItems = listGhostTabMenuMetas();return (<div@@ -138,6 +142,31 @@ export function AddTabDropdown({ onClose, onSelect, existingKinds }: AddTabDropd/>);})}+ {ghostItems.length > 0 && (+ <>+ <div className="mx-1 my-1 h-px bg-[var(--border-default)]" />+ <GroupHeader label={t('rightSidebar.tabs.menu.pluginGroup')} />+ {ghostItems.map((m) => {+ const alreadyOpen = m.singleton && existingKinds?.has(m.kind);+ return (+ <DropdownItem+ key={m.kind}+ icon={m.icon}+ // 插件名是用户内容原文(labelText),labelKey 只作兜底。+ label={m.labelText ?? t(m.labelKey)}+ trailing={+ alreadyOpen ? (+ <span className="text-[10px] text-[var(--text-tertiary)]">+ {t('rightSidebar.tabs.menu.alreadyOpen')}+ </span>+ ) : undefined+ }+ onClick={() => onSelect(m.kind)}+ />+ );+ })}+ </>+ )}{coming.length > 0 && (<><div className="mx-1 my-1 h-px bg-[var(--border-default)]" />diff --git a/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx b/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsxindex b0827ba4db..425c34a30d 100644--- a/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx@@ -1,20 +1,31 @@/*** EmptyState — 右侧栏一个 tab 都没打开时的占位(对应设计稿 F1 · v2 Welcome 风)。*- * 视觉骨架:左对齐 · 顶部 padding · eyebrow / 标题 / 描述 / 三行动作列表 / 底部 + 提示。+ * 视觉骨架:左对齐 · 顶部 padding · eyebrow / 标题 / 描述 / 动作列表 / 底部 + 提示。* 行右侧用 chevron 而非快捷键(快捷键在代码里没绑定,画 kbd 会骗用户)。* 严格走 token(规则 16),不写 hex。+ *+ * 插件页签行(panel.position:'tab' 的意识,2026-07-24):+ * - 恰好 1 个启用中 → 直接显示它自己(插件名一行);+ * - ≥2 个 → 收进一行可折叠分组(「插件面板」),展开逐个列出。*/-import { ChevronRight, FileDiff, FolderOpen, Globe, Terminal } from 'lucide-react';+import { useState } from 'react';+import { ChevronRight, FileDiff, FolderOpen, Globe, Puzzle, Terminal } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';+import type { TFunction } from 'i18next';+import { cn } from '@/lib/utils';+import type { TabKindId, TabKindMenuMeta } from './types';interface EmptyStateProps {onAddFileTab: () => void;onAddBrowserTab: () => void;onAddTerminalTab: () => void;onAddReviewTab: () => void;+ /** 启用中的插件页签 menu 项(listGhostTabMenuMetas 产物);缺省/空 = 不渲染插件行。 */+ ghostTabMetas?: TabKindMenuMeta[];+ onAddGhostTab?: (kind: TabKindId) => void;}export function EmptyState({@@ -22,6 +33,8 @@ export function EmptyState({onAddBrowserTab,onAddTerminalTab,onAddReviewTab,+ ghostTabMetas = [],+ onAddGhostTab,}: EmptyStateProps) {const { t } = useTranslation();return (@@ -65,6 +78,18 @@ export function EmptyState({sub={t('rightSidebar.tabs.empty.terminalSub')}onClick={onAddTerminalTab}/>+ {ghostTabMetas.length === 1 && (+ // 恰好一个启用中的插件页签:直接显示它自己(插件名原文,不进 i18n)。+ <ActionRow+ icon={ghostTabMetas[0].icon}+ label={ghostTabMetas[0].labelText ?? t(ghostTabMetas[0].labelKey)}+ sub={t('rightSidebar.tabs.empty.pluginSub')}+ onClick={() => onAddGhostTab?.(ghostTabMetas[0].kind)}+ />+ )}+ {ghostTabMetas.length >= 2 && (+ <GhostGroupRows metas={ghostTabMetas} onAdd={onAddGhostTab} t={t} />+ )}</div><p className="px-1 text-[11px] text-[var(--text-tertiary)]">{t('rightSidebar.tabs.empty.addMoreHint')}@@ -73,22 +98,79 @@ export function EmptyState({);}+/**+ * 多个插件页签时的折叠分组:一行「插件面板」expander,展开后逐个列出。+ * 展开态不持久化 —— EmptyState 本身是临时画面,记忆没有意义。+ */+function GhostGroupRows({+ metas,+ onAdd,+ t,+}: {+ metas: TabKindMenuMeta[];+ onAdd?: (kind: TabKindId) => void;+ t: TFunction;+}) {+ const [open, setOpen] = useState(false);+ return (+ <>+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen((v) => !v)}+ className="group flex w-full items-center gap-3.5 border-b border-[var(--border-default)] px-1 py-3 text-left transition-colors hover:bg-[var(--surface-hover)]"+ >+ <Puzzle size={16} className="text-[var(--text-secondary)]" />+ <span className="flex flex-1 flex-col gap-0.5">+ <span className="text-[14px] font-medium text-[var(--text-primary)]">+ {t('rightSidebar.tabs.empty.pluginGroup')}+ </span>+ <span className="text-[11px] text-[var(--text-tertiary)]">+ {t('rightSidebar.tabs.empty.pluginGroupSub', { count: metas.length })}+ </span>+ </span>+ <ChevronRight+ size={14}+ className={cn('text-[var(--text-tertiary)] transition-transform', open && 'rotate-90')}+ />+ </button>+ {open &&+ metas.map((m) => (+ <ActionRow+ key={m.kind}+ icon={m.icon}+ label={m.labelText ?? t(m.labelKey)}+ sub={t('rightSidebar.tabs.empty.pluginSub')}+ onClick={() => onAdd?.(m.kind)}+ inset+ />+ ))}+ </>+ );+}+function ActionRow({icon: Icon,label,sub,onClick,+ inset = false,}: {icon: LucideIcon;label: string;sub: string;onClick: () => void;+ /** 折叠分组的子行:左侧缩进一档,视觉上归属上方 expander。 */+ inset?: boolean;}) {return (<buttontype="button"onClick={onClick}- className="group flex w-full items-center gap-3.5 border-b border-[var(--border-default)] px-1 py-3 text-left transition-colors hover:bg-[var(--surface-hover)]"+ className={cn(+ 'group flex w-full items-center gap-3.5 border-b border-[var(--border-default)] px-1 py-3 text-left transition-colors hover:bg-[var(--surface-hover)]',+ inset && 'pl-9',+ )}><Icon size={16} className="text-[var(--text-secondary)]" /><span className="flex flex-1 flex-col gap-0.5">diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex 3d5ee15ac0..644d8fd876 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -28,7 +28,12 @@ import { RightSidebarDetach } from '@/components/layout/RightSidebarDetach';import { RightSidebarMaximize } from '@/components/layout/RightSidebarMaximize';import { TabBar, TabStrip } from './TabBar';import { EmptyState } from './EmptyState';-import { getTabKind, hydrateTabState } from './registry';+import {+ getTabKind,+ hydrateTabState,+ listGhostTabMenuMetas,+ useTabKindRegistryVersion,+} from './registry';import {addOrFocusSingletonTab,addTab,@@ -167,6 +172,12 @@ export function RightSidebarShell({const tabs = bucket.tabs;const activeTabId = bucket.activeTabId;+ // 插件页签(panel.position:'tab')随装/卸/停用动态注册,版本号驱动重渲——+ // EmptyState 的插件行与「+」菜单动态分组都吃这份数据。+ const tabRegistryVersion = useTabKindRegistryVersion();+ // 注册表是模块级 Map,不在 React 数据流里 —— 版本号是唯一变化信号,拿它当 dep。+ const ghostTabMetas = useMemo(() => listGhostTabMenuMetas(), [tabRegistryVersion]);+// 关掉最后一个 tab → 通知 host 自动收起侧栏。只在 tab 数「从 >0 变 0」的转变时// 触发,不是"等于 0"就触发:// - hydrated 后首帧 prev===null 不触发(区分"刚加载出来就是空"与"关到空");@@ -431,6 +442,8 @@ export function RightSidebarShell({onAddReviewTab={() => handleAdd('review')}onAddBrowserTab={() => handleAdd('web-browser')}onAddTerminalTab={() => handleAdd('terminal')}+ ghostTabMetas={ghostTabMetas}+ onAddGhostTab={handleAdd}/>) : (// 所有 tab 都挂载,只切换可见性(规则 7:杜绝切顶层 tab 时 plugin 内部 state /diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsxindex cac897c495..17ab17eac0 100644--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx@@ -47,7 +47,7 @@ import {} from '@/components/ui/dropdown-menu';import { AddTabDropdown } from './AddTabDropdown';import { getTabKind, hydrateTabState } from './registry';-import type { TabKindId, TabState } from './types';+import type { BuiltinTabKindId, TabKindId, TabState } from './types';interface TabBarProps {tabs: TabState[];@@ -114,7 +114,7 @@ interface TabStripProps {addButtonClassName?: string;}-const KIND_ICON: Record<TabKindId, LucideIcon> = {+const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {'file-browser': FolderTree,'web-browser': Globe,terminal: Terminal,@@ -122,7 +122,7 @@ const KIND_ICON: Record<TabKindId, LucideIcon> = {'orca-workers': UsersRound,};-const KIND_LABEL_KEY: Record<TabKindId, string> = {+const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {'file-browser': 'rightSidebar.tabs.kinds.fileBrowser','web-browser': 'rightSidebar.tabs.kinds.browser',terminal: 'rightSidebar.tabs.kinds.terminal',@@ -143,6 +143,9 @@ function iconForTabKind(kind: TabKindId): LucideIcon {}function labelKeyForTabKind(kind: TabKindId): string {+ // 插件页签的意识被停用/卸下(plugin 已注销)时,pill 兜底显示「插件面板」+ // 而非「未知标签页」——kind 前缀本身就能识别它是谁的地盘。+ if (kind.startsWith('ghost:')) return 'rightSidebar.tabs.kinds.ghostPanel';return ((KIND_LABEL_KEY as Partial<Record<string, string>>)[kind] ??'rightSidebar.tabs.kinds.unknown'diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsxindex 51e66823ba..76c0a9c776 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx@@ -1,15 +1,29 @@// @vitest-environment jsdom-import { cleanup, render, screen } from '@testing-library/react';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';+import { Puzzle } from 'lucide-react';vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));import { EmptyState } from '../EmptyState';+import type { TabKindMenuMeta } from '../types';afterEach(() => cleanup());+function ghostMeta(id: string, label: string): TabKindMenuMeta {+ return {+ kind: `ghost:${id}`,+ labelKey: 'rightSidebar.tabs.kinds.ghostPanel',+ labelText: label,+ icon: Puzzle,+ order: 100,+ enabled: true,+ singleton: true,+ };+}+describe('EmptyState add-more hint', () => {it('renders a non-interactive hint for the existing top add button', () => {render(@@ -29,3 +43,64 @@ describe('EmptyState add-more hint', () => {).toBeNull();});});++describe('EmptyState 插件页签行(1 个直显 / ≥2 折叠)', () => {+ it('恰好 1 个启用中的插件 → 直接显示插件自己的行,点击回传 kind', () => {+ const onAddGhostTab = vi.fn();+ render(+ <EmptyState+ onAddFileTab={vi.fn()}+ onAddReviewTab={vi.fn()}+ onAddBrowserTab={vi.fn()}+ onAddTerminalTab={vi.fn()}+ ghostTabMetas={[ghostMeta('art', '画廊')]}+ onAddGhostTab={onAddGhostTab}+ />,+ );++ // 直显插件名原文,没有折叠分组行+ fireEvent.click(screen.getByText('画廊'));+ expect(onAddGhostTab).toHaveBeenCalledWith('ghost:art');+ expect(screen.queryByText('rightSidebar.tabs.empty.pluginGroup')).toBeNull();+ });++ it('≥2 个 → 折叠分组:默认收起,展开后逐个列出并可点击', () => {+ const onAddGhostTab = vi.fn();+ render(+ <EmptyState+ onAddFileTab={vi.fn()}+ onAddReviewTab={vi.fn()}+ onAddBrowserTab={vi.fn()}+ onAddTerminalTab={vi.fn()}+ ghostTabMetas={[ghostMeta('art', '画廊'), ghostMeta('memo', '备忘')]}+ onAddGhostTab={onAddGhostTab}+ />,+ );++ // 收起态:只有分组行,不见具体插件+ const groupRow = screen.getByText('rightSidebar.tabs.empty.pluginGroup');+ expect(screen.queryByText('画廊')).toBeNull();+ expect(screen.queryByText('备忘')).toBeNull();++ fireEvent.click(groupRow);+ fireEvent.click(screen.getByText('备忘'));+ expect(onAddGhostTab).toHaveBeenCalledWith('ghost:memo');++ // 再点分组行收回去+ fireEvent.click(groupRow);+ expect(screen.queryByText('画廊')).toBeNull();+ });++ it('没有插件(缺省)→ 不渲染任何插件行', () => {+ render(+ <EmptyState+ onAddFileTab={vi.fn()}+ onAddReviewTab={vi.fn()}+ onAddBrowserTab={vi.fn()}+ onAddTerminalTab={vi.fn()}+ />,+ );+ expect(screen.queryByText('rightSidebar.tabs.empty.pluginGroup')).toBeNull();+ expect(screen.queryByText('rightSidebar.tabs.empty.pluginSub')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/registry.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/registry.test.tsindex 36ebc8e1a7..f4f9c58879 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/registry.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/registry.test.ts@@ -20,8 +20,10 @@ import {_resetTabKindRegistry,getTabKind,hydrateTabState,+ listGhostTabMenuMetas,listTabKindMenuMetas,registerTabKind,+ unregisterTabKind,} from '../registry';import type { TabKindId, TabKindPlugin } from '../types';@@ -101,6 +103,59 @@ describe('TabKindRegistry', () => {});});+ describe('unregisterTabKind', () => {+ it('removes a registered plugin; idempotent on missing kind', () => {+ registerTabKind(makePlugin('file-browser', 10));+ unregisterTabKind('file-browser');+ expect(getTabKind('file-browser')).toBeNull();+ // 幂等:再注销同 kind / 从未注册的 kind 都不抛+ expect(() => unregisterTabKind('file-browser')).not.toThrow();+ expect(() => unregisterTabKind('ghost:never')).not.toThrow();+ });++ it('allows re-registering same kind after unregister(停用→重新启用复活)', () => {+ registerTabKind(makePlugin('file-browser', 10));+ unregisterTabKind('file-browser');+ expect(() => registerTabKind(makePlugin('file-browser', 99))).not.toThrow();+ expect(getTabKind('file-browser')?.menu.order).toBe(99);+ });+ });++ describe('listGhostTabMenuMetas', () => {+ it('only returns ghost:* kinds, sorted by labelText', () => {+ registerTabKind(makePlugin('file-browser', 10));+ registerTabKind(+ makePlugin('ghost:zeta' as TabKindId, 100, {+ menu: {+ kind: 'ghost:zeta' as TabKindId,+ labelKey: 'stub.ghost',+ labelText: '备忘',+ icon: Globe,+ order: 100,+ enabled: true,+ singleton: true,+ },+ }),+ );+ registerTabKind(+ makePlugin('ghost:alpha' as TabKindId, 100, {+ menu: {+ kind: 'ghost:alpha' as TabKindId,+ labelKey: 'stub.ghost',+ labelText: '画廊',+ icon: Globe,+ order: 100,+ enabled: true,+ singleton: true,+ },+ }),+ );+ expect(listGhostTabMenuMetas().map((m) => m.labelText)).toEqual(['备忘', '画廊']);+ // 内置项不混入+ expect(listGhostTabMenuMetas().some((m) => m.kind === 'file-browser')).toBe(false);+ });+ });+describe('getTabKind', () => {it('returns null for unregistered kind', () => {expect(getTabKind('terminal')).toBeNull();diff --git a/apps/desktop/src/renderer/features/right-sidebar/registry.ts b/apps/desktop/src/renderer/features/right-sidebar/registry.tsindex 6c5608b28d..621b2440b5 100644--- a/apps/desktop/src/renderer/features/right-sidebar/registry.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/registry.ts@@ -11,10 +11,41 @@* 唯一例外是 dev HMR 下同一插件模块的重新执行,见 registerTabKind 注释。*/+import { useSyncExternalStore } from 'react';+import type { TabKindId, TabKindMenuMeta, TabKindPlugin } from './types';const REGISTRY = new Map<TabKindId, TabKindPlugin>();+/**+ * 注册表变更订阅:插件页签(`ghost:<id>`)随已装清单在运行期注册/注销,+ * 「+」菜单与空态要能感知。内置 plugin 的 import-side-effect 注册发生在+ * 首帧渲染前,订阅者挂载时拿到的已是终态,不受影响。+ */+let registryVersion = 0;+const registryListeners = new Set<() => void>();++function notifyRegistryChanged(): void {+ registryVersion += 1;+ for (const listener of [...registryListeners]) listener();+}++function subscribeTabKindRegistry(listener: () => void): () => void {+ registryListeners.add(listener);+ return () => {+ registryListeners.delete(listener);+ };+}++function getTabKindRegistryVersion(): number {+ return registryVersion;+}++/** 注册表版本号 hook:动态 kind 注册/注销时触发重渲(消费方把返回值放进 deps/渲染路径)。 */+export function useTabKindRegistryVersion(): number {+ return useSyncExternalStore(subscribeTabKindRegistry, getTabKindRegistryVersion);+}+/** 存进 hot.data 的标记 key,值为该模块上次注册过的 kind。 */const HMR_REGISTERED_KEY = '__tabKindRegistered';@@ -45,6 +76,16 @@ export function registerTabKind(plugin: TabKindPlugin, hot?: HotContextLike | nuif (hot?.data) {hot.data[HMR_REGISTERED_KEY] = plugin.kind;}+ notifyRegistryChanged();+}++/**+ * 注销 plugin —— 插件页签的意识停用/卸下时由 ghostTabPlugins 调用,幂等;+ * 内置 plugin 不注销。已打开的同 kind tab 落回 Shell 的 PlaceholderBody,+ * tab 数据保留,重新注册即原位复活(对齐顶层面板「未安装隐藏、重装复活」语义)。+ */+export function unregisterTabKind(kind: TabKindId): void {+ if (REGISTRY.delete(kind)) notifyRegistryChanged();}export function getTabKind(kind: TabKindId): TabKindPlugin | null {@@ -74,7 +115,19 @@ export function listTabKindMenuMetas(): TabKindMenuMeta[] {.sort((a, b) => a.order - b.order);}+/**+ * 启用中的插件页签 menu 项(kind 前缀 `ghost:`),「+」菜单动态分组与空态+ * 「1 个直显 / 多个折叠」共用。按 labelText(插件名)稳定排序。+ */+export function listGhostTabMenuMetas(): TabKindMenuMeta[] {+ return Array.from(REGISTRY.values())+ .map((p) => p.menu)+ .filter((menu) => menu.kind.startsWith('ghost:') && !menu.hiddenFromMenu)+ .sort((a, b) => (a.labelText ?? a.kind).localeCompare(b.labelText ?? b.kind));+}+/** 仅测试 / dev hot-reload 用:清空 registry。production 不应调用。 */export function _resetTabKindRegistry(): void {REGISTRY.clear();+ notifyRegistryChanged();}diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.tsindex 0364056f7c..76bff8a127 100644--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts@@ -13,11 +13,15 @@ import type { TFunction } from 'i18next';import type { TabCloseInterceptor } from './store';/**- * 第一版支持的 4 种 tab kind 字符串字面量联合。+ * tab kind 联合:内置字面量 + 插件页签的动态 kind。* - `file-browser` / `web-browser`:Phase 3 / Phase 5 注册真实 plugin。* - `terminal` / `review`:占位扩展点,Phase 1 在「+」dropdown 里灰显;未来注册新 plugin 时只需在此 union 添加值 + 调 `registerTabKind`,壳子不动。+ * - `ghost:<id>`:panel.position:'tab' 的插件面板页签,由+ * renderer/cindy-brain/ghostTabPlugins.tsx 随已装清单动态注册/注销+ * (字符串与顶层布局的 ghostPanelKind 同形,DB kind 列无枚举约束可直存)。*/-export type TabKindId = 'file-browser' | 'web-browser' | 'terminal' | 'review' | 'orca-workers';+export type BuiltinTabKindId = 'file-browser' | 'web-browser' | 'terminal' | 'review' | 'orca-workers';+export type TabKindId = BuiltinTabKindId | `ghost:${string}`;/** 一个 tab 运行时实例。`state` 由各 plugin 自管理结构 + 序列化,壳子只搬运。 */export interface TabState<TKindState = unknown> {@@ -34,6 +38,11 @@ export interface TabKindMenuMeta {kind: TabKindId;/** i18n key, e.g. 'rightSidebar.tabs.kinds.fileBrowser' */labelKey: string;+ /**+ * 用户内容原文标签(如插件名),优先于 `t(labelKey)` 渲染 —— 插件名不是+ * i18n 资源,进不了 labelKey 体系。内置 plugin 不填。+ */+ labelText?: string;icon: LucideIcon;/** 排序值,小的在前 */order: number;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 0bb91349d5..57ff69fa77 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2297,6 +2297,7 @@"command": "Chat command ${{command}}","panelRight": "Panel \"{{title}}\" · docked right of the chat","panelLeft": "Panel \"{{title}}\" · docked left of the chat",+ "panelTab": "Panel \"{{title}}\" · tab in the right sidebar","code": "Executable code","codeDetail": "Runs in an isolated sandbox with no access to your files or network.","resident": "Always-on (starts when enabled, keeps a background process even when idle)",@@ -3024,7 +3025,8 @@"menu": {"addLabel": "Add tab","comingSoon": "Coming soon",- "alreadyOpen": "Open"+ "alreadyOpen": "Open",+ "pluginGroup": "Plugins"},"kinds": {"fileBrowser": "File browser",@@ -3032,7 +3034,8 @@"terminal": "Terminal","review": "Review","collaboration": "Team",- "unknown": "Unknown tab"+ "unknown": "Unknown tab",+ "ghostPanel": "Plugin panel"},"controls": {"maximizeAria": "Maximize sidebar",@@ -3057,6 +3060,9 @@"browserSub": "Browser","openTerminal": "Open terminal","terminalSub": "Terminal",+ "pluginSub": "Plugin",+ "pluginGroup": "Plugin panels",+ "pluginGroupSub": "{{count}} plugins","addMoreHint": "Use the + button at the top to choose more panel types"},"placeholderHint": "{{kind}} — content coming in a later phase"diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 5f38d618b6..c0282f79c7 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2296,6 +2296,7 @@"command": "チャット指令 ${{command}}","panelRight": "パネル「{{title}}」· チャットの右側にドッキング","panelLeft": "パネル「{{title}}」· チャットの左側にドッキング",+ "panelTab": "パネル「{{title}}」· 右サイドバーのタブ","code": "実行コード","codeDetail": "独立したサンドボックスで実行され、ファイルやネットワークにはアクセスできません。","resident": "常駐実行(有効化すると起動し、呼び出されなくてもバックグラウンドプロセスを維持)",@@ -3023,7 +3024,8 @@"menu": {"addLabel": "タブを追加","comingSoon": "近日対応",- "alreadyOpen": "開いています"+ "alreadyOpen": "開いています",+ "pluginGroup": "プラグイン"},"kinds": {"fileBrowser": "ファイルブラウザ",@@ -3031,7 +3033,8 @@"terminal": "ターミナル","review": "レビュー","collaboration": "コラボ",- "unknown": "不明なタブ"+ "unknown": "不明なタブ",+ "ghostPanel": "プラグインパネル"},"controls": {"maximizeAria": "サイドバーを最大化",@@ -3056,6 +3059,9 @@"browserSub": "Browser","openTerminal": "ターミナルを開く","terminalSub": "Terminal",+ "pluginSub": "Plugin",+ "pluginGroup": "プラグインパネル",+ "pluginGroupSub": "{{count}} 個のプラグイン","addMoreHint": "上部の + ボタンからほかのパネルタイプを選択できます"},"placeholderHint": "{{kind}} — コンテンツは後続フェーズで追加されます"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 29e75f43ac..a210a8f368 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2296,6 +2296,7 @@"command": "채팅 명령 ${{command}}","panelRight": "패널 \"{{title}}\" · 채팅 오른쪽에 도킹","panelLeft": "패널 \"{{title}}\" · 채팅 왼쪽에 도킹",+ "panelTab": "패널 \"{{title}}\" · 오른쪽 사이드바 탭","code": "실행 코드","codeDetail": "격리된 샌드박스에서 실행되며 파일과 네트워크에 접근할 수 없습니다.","resident": "상주 실행(활성화하면 시작되며 호출이 없어도 백그라운드 프로세스 유지)",@@ -3023,7 +3024,8 @@"menu": {"addLabel": "탭 추가","comingSoon": "지원 예정",- "alreadyOpen": "열림"+ "alreadyOpen": "열림",+ "pluginGroup": "플러그인"},"kinds": {"fileBrowser": "파일 브라우저",@@ -3031,7 +3033,8 @@"terminal": "터미널","review": "리뷰","collaboration": "협업",- "unknown": "알 수 없는 탭"+ "unknown": "알 수 없는 탭",+ "ghostPanel": "플러그인 패널"},"controls": {"maximizeAria": "사이드바 최대화",@@ -3056,6 +3059,9 @@"browserSub": "Browser","openTerminal": "터미널 열기","terminalSub": "Terminal",+ "pluginSub": "Plugin",+ "pluginGroup": "플러그인 패널",+ "pluginGroupSub": "플러그인 {{count}}개","addMoreHint": "위쪽 + 버튼에서 다른 패널 유형을 선택할 수 있어요"},"placeholderHint": "{{kind}} — 콘텐츠는 이후 단계에서 추가됩니다"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex de993300a8..4f01e3e04c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2296,6 +2296,7 @@"command": "聊天指令 ${{command}}","panelRight": "面板「{{title}}」· 停靠主聊天区右侧","panelLeft": "面板「{{title}}」· 停靠主聊天区左侧",+ "panelTab": "面板「{{title}}」· 右侧栏页签","code": "可执行代码","codeDetail": "在独立沙箱中运行,无法访问你的文件与网络。","resident": "常驻运行(生效后即启动,不调用也保持后台进程)",@@ -3023,7 +3024,8 @@"menu": {"addLabel": "添加标签","comingSoon": "即将支持",- "alreadyOpen": "已打开"+ "alreadyOpen": "已打开",+ "pluginGroup": "插件"},"kinds": {"fileBrowser": "文件浏览器",@@ -3031,7 +3033,8 @@"terminal": "终端","review": "审查","collaboration": "协同",- "unknown": "未知标签页"+ "unknown": "未知标签页",+ "ghostPanel": "插件面板"},"controls": {"maximizeAria": "最大化侧栏",@@ -3056,6 +3059,9 @@"browserSub": "Browser","openTerminal": "打开终端","terminalSub": "Terminal",+ "pluginSub": "Plugin",+ "pluginGroup": "插件面板",+ "pluginGroupSub": "{{count}} 个插件","addMoreHint": "可通过顶部 + 按钮选择更多面板类型"},"placeholderHint": "{{kind}} — 内容将在后续阶段加入"diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex af533ed8be..54c7b15989 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -483,6 +483,12 @@ describe('ghost · layoutWithGhostPanel(装入即停靠)', () => {// 缺省 position=right,面板在 chat-main 之后(下标 1)。expect((next!.content as SplitNode).children[1].fraction).toBeCloseTo(0.2, 5);});++ it("position: 'tab' → null,不进布局树(页签形态由右侧栏承载)", () => {+ const m = manifest();+ m.panel = { html: 'panel.html', position: 'tab' };+ expect(layoutWithGhostPanel(createDefaultLayout(), m)).toBeNull();+ });});describe('ghost · keywords(语义触发扩展词表)', () => {@@ -706,6 +712,24 @@ describe('ghost · panel.position 校验', () => {}expect(validateGhostManifest(withPos('center')).ok).toBe(false);});++ it("'tab'(右侧栏页签)通过;tab 时 minWidth/defaultFraction 收词明确拒绝", () => {+ const tab = validateGhostManifest({+ ...goodManifest(),+ panel: { title: 'Hello', html: 'panel.html', position: 'tab' },+ });+ expect(tab.ok && tab.manifest.panel?.position).toBe('tab');++ // 页签没有拖缝宽度语义:带停靠专属字段必须明确拒绝,不静默忽略(规则 9)。+ for (const extra of [{ minWidth: 240 }, { defaultFraction: 0.2 }, { minWidth: 240, defaultFraction: 0.2 }]) {+ const v = validateGhostManifest({+ ...goodManifest(),+ panel: { title: 'Hello', html: 'panel.html', position: 'tab', ...extra },+ });+ expect(v.ok, JSON.stringify(extra)).toBe(false);+ expect(!v.ok && v.reason).toContain('仅停靠形态');+ }+ });});describe('ghost · whenToUse(语义召回线索)', () => {@@ -811,6 +835,11 @@ describe('ghost · 逐项权限清单', () => {expect(items.map((i) => i.key)).toEqual(['panel:right', 'code']);expect(items[0]).toMatchObject({ labelKey: 'panelRight', labelArgs: { title: '说明书' } });+ // 页签形态在确认框同样逐项如实展示(labelKey 独立成 panelTab)。+ const tabbed = ghostPermissionItems({ ...plain, panel: { html: 'panel.html', position: 'tab' } });+ expect(tabbed.map((i) => i.key)).toEqual(['panel:tab', 'code']);+ expect(tabbed[0]).toMatchObject({ labelKey: 'panelTab', labelArgs: { title: '说明书' } });+const chipNoNeeds: GhostManifest = {schemaVersion: 2,id: 'c',diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex bcdbbcbe64..5c9a288d2f 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -253,24 +253,26 @@ export const GHOST_LAUNCH_MODES = ['on-demand', 'resident'] as const;export type GhostLaunchMode = (typeof GHOST_LAUNCH_MODES)[number];/**- * 面板停靠位置(相对主聊天窗)。当前布局引擎支持 left / right;+ * 面板显示形态(相对主聊天窗)。left / right = 顶层布局树停靠 pane;+ * 'tab' = 不进布局树,作为右侧栏(right-tabs)里的每会话单例页签+ * (2026-07-24 定案,注册链路见 renderer/cindy-brain/ghostTabPlugins.tsx)。* top / bottom 需要嵌套上下分割(树操作/拖缝/卸载查找全链路),排期中——* 校验层先收词并明确拒绝,不静默降级(规则 9)。*/-export const GHOST_PANEL_POSITIONS = ['left', 'right'] as const;+export const GHOST_PANEL_POSITIONS = ['left', 'right', 'tab'] as const;export type GhostPanelPosition = (typeof GHOST_PANEL_POSITIONS)[number];/** 面板声明(五个卡槽中的「面板」槽,一段意识至多一块)。 */export interface GhostPanelDecl {/** 面板标准头(PanelChrome)标题;缺省用意识 name。 */title?: string;- /** 停靠位置(相对主聊天窗);缺省 = right(2026-07-12 Lizi 定案)。 */+ /** 显示形态:left / right 停靠,或 'tab' 右侧栏页签;缺省 = right(2026-07-12 Lizi 定案)。 */position?: GhostPanelPosition;/** 面板界面入口(安装目录内相对路径,意识自绘)。 */html: string;- /** 面板最小宽度(px),布局引擎拖缝时的下限。 */+ /** 面板最小宽度(px),布局引擎拖缝时的下限。仅停靠形态有效,'tab' 时禁用。 */minWidth?: number;- /** 装入布局时的初始宽度占比(与 layoutTree 的 fraction 同语义)。 */+ /** 装入布局时的初始宽度占比(与 layoutTree 的 fraction 同语义)。仅停靠形态有效,'tab' 时禁用。 */defaultFraction?: number;}@@ -1241,7 +1243,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItitems.push({key: `panel:${position}`,kind: 'panel',- labelKey: position === 'left' ? 'panelLeft' : 'panelRight',+ labelKey: position === 'left' ? 'panelLeft' : position === 'tab' ? 'panelTab' : 'panelRight',labelArgs: { title: manifest.panel.title ?? manifest.name },});}@@ -1389,11 +1391,13 @@ export function ghostWebviewEntryPaths(manifest: GhostManifest): string[] {* 装入带面板的意识后,把面板停进布局树(main 侧随 install 调用)。* - 树上已有同 kind 的 pane(重装)→ 返回 null:不动树,位置记忆保留、原位复活;* - 意识没声明面板 → null;+ * - position:'tab' → null:页签形态不进布局树,由右侧栏页签(ghostTabPlugins)承载;* - 否则停在聊天区右侧(index 1),宽度占比/最小宽取清单声明。* 卸下时**不做**逆操作 —— 树数据保留正是"重装复活"的记忆来源(§6 规则 5)。*/export function layoutWithGhostPanel(layout: Layout, manifest: GhostManifest): Layout | null {if (!manifest.panel) return null;+ if (manifest.panel.position === 'tab') return null;const kind = ghostPanelKind(manifest.id);if (findSplitChildByPanelKind(layout, kind)) return null;// 停靠位置(相对主聊天窗):按 chat-main 的实际下标定插入点,不写死@@ -1505,11 +1509,18 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (p.position !== undefined) {if (p.position === 'top' || p.position === 'bottom') {// 收词但明确拒绝(规则 9 不静默降级):上下停靠等布局引擎嵌套分割就绪后开放。- return { ok: false, reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / right' };+ return { ok: false, reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / right / tab' };}if (!(GHOST_PANEL_POSITIONS as readonly string[]).includes(p.position as string)) {return { ok: false, reason: `panel.position 必须是 ${GHOST_PANEL_POSITIONS.join(' / ')}` };}+ // 页签形态没有拖缝宽度语义:收词明确拒绝而非静默忽略(规则 9)。+ if (p.position === 'tab' && (p.minWidth !== undefined || p.defaultFraction !== undefined)) {+ return {+ ok: false,+ reason: "panel.minWidth / panel.defaultFraction 仅停靠形态(left / right)有效,position:'tab' 时请移除",+ };+ }}panel = {...(p.title !== undefined ? { title: p.title as string } : {}),