Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
插件可声明默认打开方式,用户放置记忆优先
Dash5f5b5d2da133
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 10fe38b410..c5ea193ed6 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1729,17 +1729,20 @@ 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 暂未支持(排期中)。minWidth / defaultFraction 仍可声明(兼容),当前- // 右侧栏宿主不消费。+ // panel.position:面板显示形态。left(缺省)/ right / top / bottom = 右侧栏常驻面板:+ // 启用后自动成为聊天区对应边页签组里一个不跟对话的全局页签(切任务保留、可最大化、+ // 可弹成独立窗口、用户可拖到任何一边或关闭;用户放置过后主机记住用户的位置,+ // 你的声明只是首次出现时的默认);"tab" = 插件页内的独占面板(用户在插件页点插件卡的+ // 「使用」打开,离开插件页即关闭;同一时刻至多一个;此形态没有拖缝宽度,声明 minWidth /+ // defaultFraction 会被拒装,请移除)。minWidth / defaultFraction 仍可声明(兼容),当前+ // 页签组宿主不消费。// panel.systemButtons(可选):历史字段,保留兼容、当前不生效(右侧栏页签的// 关闭 / 最大化 / 弹出按钮由主机统一提供);position:"tab" 时声明本字段拒装// 一级主视图是独立能力,见 §4.20。使用时直接声明:// "mainView": { "title": "工作台", "icon": "puzzle", "html": "main-view.html" }+ // 可选 "open": "page"(缺省,撑满内容区)/ "sidebar"(作为页签进聊天区某一边,配 "side":+ // left / right / top / bottom)/ "window"(弹成独立窗口);只是左侧栏入口的默认打开方式,+ // 用户拖过 / 弹过后以用户的放置为准。"settingsHtml": "settings.html", // 可选:设置页「自定义设置区」自绘界面(见 §4.8;声明了用户填的凭证时仍必填,用于长期管理/替换/清除;调用前缺失时主机也会在统一 Setup 卡内联收单,见 §4.7)"settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮,高至 800);内容会动态增减时才声明,避免抖动}@@ -4661,6 +4664,11 @@ if (r.ok && r.confirmed) {替代或修改根级 \`icon\` 品牌图片。可用值与 Cindy 系统图标名完全一致:\`puzzle\`、\`globe\`、\`code\`、\`folder\`、\`database\`、\`chart-column\`、\`image\`、\`message-circle\`、\`calendar-days\`;不接受别名、任意图标名或图片路径;+- \`mainView.open\` 可省略(缺省 \`page\`:左侧栏入口点开后撑满内容区)。\`sidebar\` =+ 作为不跟对话的页签放进聊天区某一边的页签组(\`side\`:\`left\` / \`right\` / \`top\` /+ \`bottom\`,缺省 right;其它 open 值下声明 side 拒装);\`window\` = 弹成独立 OS 窗口。+ 这只是**默认**:用户把页签拖到别的边、弹出或合并回来之后,主机记住用户的放置,+ 左侧栏入口此后按用户的位置打开,直到用户在插件详情页「恢复默认位置」;- \`mainView\` 与 \`panel\` 是两种独立 UI 贡献项。可以让两者指向同一 HTML,但必须分别声明;主视图不接受 position、宽度或 systemButtons;- 插件批准并启用后,入口默认显示。用户可以在插件详情关闭“显示在侧边栏”;这只隐藏@@ -4702,10 +4710,11 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件## 5. 面板(panel.html/css/js)-- 显示形态由 \`panel.position\` 决定:\`left\`(缺省)= **右侧栏常驻面板**——插件- 启用后自动成为右侧栏里一个不跟对话的全局页签,切任务时留在原位,用户可以把它- 最大化、弹成独立 OS 窗口或关闭(关闭后在左侧栏入口右键可重新打开;\`right\` 已退役,- 旧包声明 right 自动并入 left);\`"tab"\` = **插件页内的独占面板**——由插件页+- 显示形态由 \`panel.position\` 决定:\`left\`(缺省)/ \`right\` / \`top\` / \`bottom\` =+ **右侧栏常驻面板**——插件启用后自动成为聊天区对应边页签组里一个不跟对话的全局页签,+ 切任务时留在原位,用户可以把它拖到任何一边、最大化、弹成独立 OS 窗口或关闭(关闭后+ 在右侧栏「+」菜单或插件详情页可重新打开;用户放置过后主机记住用户的位置,声明只是+ 首次出现时的默认);\`"tab"\` = **插件页内的独占面板**——由插件页自己承载(不进右侧栏页签容器):用户在插件页点你这张卡的「使用」按钮打开,同一时刻至多一个,**用户离开插件页即关闭卸载**(面板收束,2026-08-02 定案:插件面板不再常驻右侧栏干扰其它会话)。从插件页导入 tab 型插件后,宿主会@@ -4911,7 +4920,8 @@ Cindy 统一归类、随机选择与排序,同批每个场景和每个插件· **未声明 command**:不拒装,但插件页"使用"按钮禁用,用户无法通过插件页一键启用或用 $command 点名;AI 工具调用不受影响(见 §2 说明)- \`tools\` 为空 · panel 详单缺少实际形态(既没有 html,也不是有效的 tab/停靠配置)-- mainView.html 文件缺失/路径不安全、icon 不在系统图标白名单+- mainView.html 文件缺失/路径不安全、icon 不在系统图标白名单、open 不是 page / sidebar /+ window、side 不是四条边之一或在 open 非 sidebar 时声明- settingsHtml 路径不合法/文件不在包里 · settingsHeight 越界(160–800)或没配 settingsHtml 单独声明- panel.systemButtons 格式错(不是对象、已知键的值非布尔,或 position:"tab" 时声明——插件页内面板没有标准头)- keywords(已废弃字段,旧包兼容保留,新意识别写)有单字词 · kind 写了但不是 "chip"(可省略) · schemaVersion 不是 3 · 缺 minCindyVersiondiff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsxindex c1c3fc9da4..b6e876bbfd 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx@@ -22,6 +22,7 @@ import {type PluginViewTabState,} from '../../features/right-sidebar/globalTabs';import { pickGhostPanelMediaUri, syncGhostPanelRegistrations } from '../ghostPanels';+import { __resetTabGroupsForTest, getTabGroup } from '../../features/right-sidebar/tabGroups';function ghost(id: string,@@ -57,10 +58,12 @@ const instanceIds = () =>beforeEach(() => {window.localStorage.clear();__resetGlobalTabsForTest();+ __resetTabGroupsForTest();});afterEach(() => {__resetGlobalTabsForTest();+ __resetTabGroupsForTest();window.localStorage.clear();});@@ -73,6 +76,8 @@ describe('syncGhostPanelRegistrations · 停靠面板插件自动成为右侧栏ghost('view-only', { panel: null, mainView: true }),]);expect(instanceIds()).toEqual(['docked-panel']);+ // 存量停靠面板缺省 position = 停在聊天区左侧:自动页签首次出现落在左侧组。+ expect(getTabGroup('g_docked-panel')).toBe('left');// 再同步一次不重复加。syncGhostPanelRegistrations([ghost('docked-panel')]);expect(instanceIds()).toEqual(['docked-panel']);diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex c3e2a8f6cc..60ce344aa0 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -58,7 +58,12 @@ import {setActiveTab,} from '@/features/right-sidebar/store';import { browserWebviewPool } from '@/features/right-sidebar/lib/browserWebviewPool';-import { findGlobalTab, setActiveGlobalTabId } from '@/features/right-sidebar/globalTabs';+import {+ findGlobalTab,+ rememberPluginWindowPlacement,+ setActiveGlobalTabId,+ type PluginViewTabState,+} from '@/features/right-sidebar/globalTabs';import { TabGroupHostProvider, type TabGroupHostValue } from '@/features/right-sidebar/tabGroupHost';import { useTabGroupPanes } from '@/features/right-sidebar/tabGroupPanes';import { TabDragController } from '@/features/right-sidebar/TabDragController';@@ -1115,7 +1120,11 @@ export function MainLayout() {subagentsAvailable: rightSidebarSubagentsAvailableRef.current,};// 全局页签(插件视图)不属于任何任务:无桶快照,也没有任务级资源要释放。- if (findGlobalTab(tabId)) {+ const globalTab = findGlobalTab(tabId);+ if (globalTab) {+ // 插件视图弹过窗口:记住,下次从左侧栏入口点开直接进窗口。+ const instanceId = (globalTab.state as PluginViewTabState | null)?.instanceId;+ if (instanceId) rememberPluginWindowPlacement(instanceId, true);void api.open({ tabId, sessionId: null, context, handoff: null, ...target }).catch((err) => {applicationMenuLog.warn('pop out global sidebar tab failed', { tabId, err });});@@ -1166,10 +1175,16 @@ export function MainLayout() {if (isSecondaryWindow()) return;const api = window.electronAPI.sidebarTabWindow;if (!api?.onTabReturned) return;- return api.onTabReturned(({ sessionId, tabId, snapshot }) => {+ return api.onTabReturned(({ sessionId, tabId, snapshot, reason }) => {// 全局页签回来:数据一直在全局存储里,只需选中它并确保侧栏展开。if (sessionId === null) {- if (findGlobalTab(tabId)) setActiveGlobalTabId(tabId);+ const globalTab = findGlobalTab(tabId);+ if (globalTab) {+ setActiveGlobalTabId(tabId);+ // 用户主动合并回来 = 不再记「在独立窗口里」;崩溃回来保留记忆。+ const instanceId = (globalTab.state as PluginViewTabState | null)?.instanceId;+ if (instanceId && reason === 'merge') rememberPluginWindowPlacement(instanceId, false);+ }if (isRightSidebarCollapsedRef.current && !rsbDetachedRef.current) {writeCollapsedFor(rightSidebarSessionIdRef.current, false);setIsRightSidebarCollapsed(false);diff --git a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsxindex bad39322c0..fb30c5f1d9 100644--- a/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx+++ b/apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx@@ -1,5 +1,11 @@import { useState } from 'react';-import { PanelRight, SlidersHorizontal } from 'lucide-react';+import {+ AppWindow,+ PanelRight,+ RotateCcw,+ SlidersHorizontal,+ SquareArrowOutUpRight,+} from 'lucide-react';import { useTranslation } from 'react-i18next';import { useMatch, useNavigate } from 'react-router-dom';@@ -10,8 +16,18 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';-import { addGlobalPluginTab, setActiveGlobalTabId } from '@/features/right-sidebar/globalTabs';-import { requestRightSidebarVisibility } from '@/features/right-sidebar/lib/sidebarCommands';+import {+ hasPluginPlacementMemory,+ resetPluginPlacement,+ useGlobalTabs,+} from '@/features/right-sidebar/globalTabs';+import {+ focusExistingPluginTab,+ openPluginInSidebar,+ openPluginInWindow,+ resolvePluginOpenTarget,+} from '@/features/right-sidebar/pluginPlacement';+import { useTabGroupAssignments } from '@/features/right-sidebar/tabGroups';import { cn } from '@/lib/utils';import { SIDEBAR_RAIL_ICON_BUTTON_CLASS } from './SidebarIconButton';@@ -56,22 +72,31 @@ export function GhostMainViewNavEntry({className="shrink-0"/>);- const open = () => navigate(`/apps/${encodeURIComponent(item.instanceId)}`);+ const openPage = () => navigate(`/apps/${encodeURIComponent(item.instanceId)}`);+ // 点击:已在侧边栏 / 窗口里就聚焦;否则按用户放置记忆 → 插件声明 → 内置默认(页面)。+ const open = () => {+ if (focusExistingPluginTab(item.installedGhost)) return;+ const target = resolvePluginOpenTarget(item.installedGhost);+ if (target === 'sidebar') openPluginInSidebar(item.installedGhost);+ else if (target === 'window') openPluginInWindow(item.installedGhost);+ else openPage();+ };const openDetails = () =>navigate(`/settings?tab=ghosts&ghost=${encodeURIComponent(item.instanceId)}`);- // 右键菜单:「在侧边栏中打开」= 把这个插件视图作为全局页签(不跟对话)钉进右侧栏。+ // 右键菜单:在页面 / 侧边栏 / 独立窗口中打开;有放置记忆时可恢复默认位置。+ // 订阅全局页签与组归属,记忆变化时菜单项同步。+ useGlobalTabs();+ useTabGroupAssignments();+ const canReset = hasPluginPlacementMemory(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 openInSidebar = () => openPluginInSidebar(item.installedGhost);+ const openInWindow = () => openPluginInWindow(item.installedGhost);+ const resetPlacement = () => resetPluginPlacement(item.instanceId, item.installedGhost);const contextMenu = (<DropdownMenuopen={contextMenuPos !== null}@@ -93,6 +118,15 @@ export function GhostMainViewNavEntry({/></DropdownMenuTrigger><DropdownMenuContent align="start" sideOffset={2}>+ <DropdownMenuItem+ onClick={() => {+ setContextMenuPos(null);+ openPage();+ }}+ >+ <SquareArrowOutUpRight size={14} aria-hidden="true" />+ {t('ghostMainView.openInPage')}+ </DropdownMenuItem><DropdownMenuItemonClick={() => {setContextMenuPos(null);@@ -102,6 +136,26 @@ export function GhostMainViewNavEntry({<PanelRight size={14} aria-hidden="true" />{t('ghostMainView.openInSidebar')}</DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => {+ setContextMenuPos(null);+ openInWindow();+ }}+ >+ <AppWindow size={14} aria-hidden="true" />+ {t('ghostMainView.openInWindow')}+ </DropdownMenuItem>+ {canReset && (+ <DropdownMenuItem+ onClick={() => {+ setContextMenuPos(null);+ resetPlacement();+ }}+ >+ <RotateCcw size={14} aria-hidden="true" />+ {t('ghostMainView.resetPlacement')}+ </DropdownMenuItem>+ )}</DropdownMenuContent></DropdownMenu>);diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsxindex ec02ea13e2..68f411ab5e 100644--- a/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/GhostMainViewNavEntries.test.tsx@@ -26,17 +26,27 @@ 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(),+const placementMock = vi.hoisted(() => ({+ target: 'page' as 'page' | 'sidebar' | 'window',+ focusExistingPluginTab: vi.fn(() => false),+ openPluginInSidebar: vi.fn(),+ openPluginInWindow: vi.fn(),+ resetPluginPlacement: vi.fn(),+ hasMemory: false,}));vi.mock('@/features/right-sidebar/globalTabs', () => ({- addGlobalPluginTab: globalTabsMock.addGlobalPluginTab,- setActiveGlobalTabId: globalTabsMock.setActiveGlobalTabId,+ hasPluginPlacementMemory: () => placementMock.hasMemory,+ resetPluginPlacement: placementMock.resetPluginPlacement,+ useGlobalTabs: () => [],}));-vi.mock('@/features/right-sidebar/lib/sidebarCommands', () => ({- requestRightSidebarVisibility: globalTabsMock.requestRightSidebarVisibility,+vi.mock('@/features/right-sidebar/tabGroups', () => ({+ useTabGroupAssignments: () => ({}),+}));+vi.mock('@/features/right-sidebar/pluginPlacement', () => ({+ resolvePluginOpenTarget: () => placementMock.target,+ focusExistingPluginTab: placementMock.focusExistingPluginTab,+ openPluginInSidebar: placementMock.openPluginInSidebar,+ openPluginInWindow: placementMock.openPluginInWindow,}));vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -89,8 +99,9 @@ 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', () => {+ // 右键菜单:在页面 / 侧边栏 / 独立窗口中打开;有放置记忆时多一项「恢复默认位置」。+ it('offers page / sidebar / window from the context menu and resets placement when remembered', () => {+ placementMock.hasMemory = true;render(<MemoryRouter initialEntries={['/apps/alpha']}><Routes>@@ -98,11 +109,61 @@ describe('GhostMainViewNavEntries', () => {</Routes></MemoryRouter>,);- fireEvent.contextMenu(screen.getByRole('button', { name: 'Workspace' }));+ const entry = screen.getByRole('button', { name: 'Workspace' });+ fireEvent.contextMenu(entry);fireEvent.click(screen.getByText('ghostMainView.openInSidebar'));- expect(globalTabsMock.addGlobalPluginTab).toHaveBeenCalledWith('workspace');- expect(globalTabsMock.setActiveGlobalTabId).toHaveBeenCalledWith('g-workspace');- expect(globalTabsMock.requestRightSidebarVisibility).toHaveBeenCalledWith('open');+ expect(placementMock.openPluginInSidebar).toHaveBeenCalledWith(items[1].installedGhost);+ fireEvent.contextMenu(entry);+ fireEvent.click(screen.getByText('ghostMainView.openInWindow'));+ expect(placementMock.openPluginInWindow).toHaveBeenCalledWith(items[1].installedGhost);+ fireEvent.contextMenu(entry);+ fireEvent.click(screen.getByText('ghostMainView.resetPlacement'));+ expect(placementMock.resetPluginPlacement).toHaveBeenCalledWith('workspace', items[1].installedGhost);+ placementMock.hasMemory = false;+ });++ // 测试价值+ // - 生产入口与可观察结果:左侧栏入口点击;可观察的是按放置记忆 / 插件声明解析出的目标+ // 分流到页面路由、侧边栏或独立窗口,已有页签时只聚焦不重开。+ // - Bug / 规则依据:插件可声明默认打开方式,用户放置记忆优先(页签组模型第三阶段)。+ // - 现有覆盖缺口:此前点击只会导航到页面。+ // - 最小失败输入:resolvePluginOpenTarget 返回 'window'。+ // - tier:unit(jsdom + MemoryRouter)。+ it('routes a click by the resolved open target and focuses an existing tab instead of reopening', () => {+ const view = render(+ <MemoryRouter initialEntries={['/apps/alpha']}>+ <Routes>+ <Route+ path="*"+ element={+ <>+ <GhostMainViewNavEntries variant="row" />+ <LocationProbe />+ </>+ }+ />+ </Routes>+ </MemoryRouter>,+ );+ const entry = () => screen.getByRole('button', { name: 'Workspace' });+ placementMock.target = 'window';+ fireEvent.click(entry());+ expect(placementMock.openPluginInWindow).toHaveBeenCalledWith(items[1].installedGhost);+ expect(screen.getByTestId('location').textContent).toBe('/apps/alpha');++ placementMock.target = 'sidebar';+ fireEvent.click(entry());+ expect(placementMock.openPluginInSidebar).toHaveBeenCalledWith(items[1].installedGhost);++ placementMock.focusExistingPluginTab.mockReturnValueOnce(true);+ placementMock.openPluginInSidebar.mockClear();+ fireEvent.click(entry());+ expect(placementMock.openPluginInSidebar).not.toHaveBeenCalled();++ placementMock.target = 'page';+ fireEvent.click(entry());+ expect(screen.getByTestId('location').textContent).toBe('/apps/workspace');+ view.unmount();});it('uses the native 18px rail icon geometry without a fallback tile', () => {diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 0486fb1adc..5be6b3e110 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -59,9 +59,14 @@ import { type GhostPluginDetail } from './lib/ghostPluginViewModel';import { GhostPluginIcon } from './GhostPluginIcon';import {addGlobalPluginTab,+ hasPluginPlacementMemory,+ resetPluginPlacement,setActiveGlobalTabId,useGlobalTabs,} from '@/features/right-sidebar/globalTabs';+import { useTabGroupAssignments } from '@/features/right-sidebar/tabGroups';+import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';import { ghostPluginSummary } from './lib/ghostPluginDetailModel';import { ghostPrimaryAction } from './lib/ghostPluginViewModel';import { permissionItemIcon } from './lib/permissionItemIcon';@@ -835,9 +840,17 @@ export function DetailsSection({const { t } = useTranslation();const trustLabelKey = ghostTrustLabelKey(detail.trust);const globalTabs = useGlobalTabs();+ useTabGroupAssignments();+ const installedGhost = useInstalledGhosts().find(+ (ghost) => installedGhostStoragePart(ghost) === detail.id,+ );const inSidebar = globalTabs.some((tab) => (tab.state as { instanceId?: string } | null)?.instanceId === detail.id,);+ // 用户拖过 / 弹过 / 已套过默认边:给「恢复默认位置」。+ const canResetPlacement = hasPluginPlacementMemory(detail.id);+ const placementActionClass =+ 'shrink-0 rounded-md px-2 py-1 text-12 text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]';const facts: Array<{key: string;label: string;@@ -893,19 +906,33 @@ export function DetailsSection({: panelStatus || t('settings.ghosts.detail.panelDismissed'),// 停靠形态面板关掉页签后,这里是除右侧栏「+」菜单外的另一个重开入口// (这类插件没有左侧栏入口)。已在侧栏、停用、tab 形态或无面板时不渲染。- ...(detail.panelMinWidth !== null && !detail.tabPanel && detail.enabled && !inSidebar+ // 「恢复默认位置」:清掉用户的放置记忆(拖到的边 / 弹过窗口),回到插件声明的默认边。+ ...(detail.panelMinWidth !== null && !detail.tabPanel? {action: (- <button- type="button"- onClick={() => {- const tab = addGlobalPluginTab(detail.id);- if (tab) setActiveGlobalTabId(tab.id);- }}- className="shrink-0 rounded-md px-2 py-1 text-12 text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- {t('settings.ghosts.detail.openInSidebar')}- </button>+ <span className="flex shrink-0 items-center gap-1">+ {detail.enabled && !inSidebar && (+ <button+ type="button"+ onClick={() => {+ const tab = addGlobalPluginTab(detail.id, { ghost: installedGhost });+ if (tab) setActiveGlobalTabId(tab.id);+ }}+ className={placementActionClass}+ >+ {t('settings.ghosts.detail.openInSidebar')}+ </button>+ )}+ {canResetPlacement && (+ <button+ type="button"+ onClick={() => resetPluginPlacement(detail.id, installedGhost)}+ className={placementActionClass}+ >+ {t('settings.ghosts.detail.resetPlacement')}+ </button>+ )}+ </span>),}: {}),diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsxindex 39637422ac..a6e7a10a66 100644--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx@@ -158,6 +158,7 @@ export function AddTabDropdown({const instanceId = installedGhostStoragePart(ghost);return {instanceId,+ ghost,title: globalTabTitleForGhost(ghost),icon: MAIN_VIEW_ICONS[ghost.manifest.mainView?.icon ?? 'puzzle'] ?? Puzzle,open: globalTabs.some(@@ -259,7 +260,11 @@ export function AddTabDropdown({label={entry.title}trailing={entry.open ? t('rightSidebar.tabs.menu.alreadyOpen') : undefined}onSelect={() => {- const tab = addGlobalPluginTab(entry.instanceId, { groupId });+ // 本组显式指定;没有指定组(右侧组菜单)时按插件声明 / 放置记忆落位。+ const tab = addGlobalPluginTab(entry.instanceId, {+ ...(groupId && groupId !== 'right' ? { groupId } : {}),+ ghost: entry.ghost,+ });if (tab) {if (!entry.open) onGlobalTabAdded?.(tab.id);setActiveGlobalTabId(tab.id);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.tsindex a80e0052c8..078ce077eb 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/globalTabs.test.ts@@ -17,23 +17,31 @@ import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import {__resetGlobalTabsForTest,addGlobalPluginTab,+ defaultGroupForGhost,getActiveGlobalTabId,getGlobalTabs,getGlobalTabsSnapshot,+ hasPluginPlacementMemory,+ isPluginWindowPlacement,+ rememberPluginWindowPlacement,removeGlobalTab,reorderGlobalTabs,+ resetPluginPlacement,sanitizeGlobalTabsSnapshot,setActiveGlobalTabId,} from '../globalTabs';+import { __resetTabGroupsForTest, getTabGroup, setTabGroup } from '../tabGroups';beforeEach(() => {window.localStorage.clear();__resetGlobalTabsForTest();+ __resetTabGroupsForTest();setDataOwnerGeneration('owner-a', 1);});afterEach(() => {__resetGlobalTabsForTest();+ __resetTabGroupsForTest();window.localStorage.clear();});@@ -97,7 +105,60 @@ describe('globalTabs', () => {).toEqual({tabs: [{ id: 'ok', kind: 'plugin-view', state: { instanceId: 'alpha' } }],dismissedInstanceIds: ['x'],+ placedInstanceIds: [],+ windowInstanceIds: [],});- expect(sanitizeGlobalTabsSnapshot('nope')).toEqual({ tabs: [], dismissedInstanceIds: [] });+ expect(sanitizeGlobalTabsSnapshot('nope')).toEqual({+ tabs: [],+ dismissedInstanceIds: [],+ placedInstanceIds: [],+ windowInstanceIds: [],+ });+ });++ // 测试价值+ // - 生产入口与可观察结果:addGlobalPluginTab({ghost}) / removeGlobalTab / resetPluginPlacement /+ // rememberPluginWindowPlacement;可观察的是页签 id 跟插件实例走(关掉再打开同一 id)、首次+ // 出现按 panel.position / mainView.side 放默认边、关掉再打开保留用户拖到的边、「恢复默认+ // 位置」清掉窗口记忆并回到默认边。+ // - Bug / 规则依据:页签组模型第三阶段——插件给默认放置,用户的放置记忆优先。+ // - 现有覆盖缺口:新行为。+ // - 最小失败输入:一个 panel.position:'bottom' 的插件 + add → setTabGroup('top') → remove → add。+ // - tier:unit(jsdom localStorage)。+ it('keeps placement memory per plugin instance and resets it on demand', () => {+ const ghost = (position?: 'left' | 'right' | 'top' | 'bottom', mainView?: object) =>+ ({+ manifest: {+ id: 'beta',+ name: 'Beta',+ ...(position !== undefined || mainView === undefined+ ? { panel: { html: 'p.html', ...(position ? { position } : {}) } }+ : {}),+ ...(mainView ? { mainView: { html: 'm.html', ...mainView } } : {}),+ },+ enabled: true,+ }) as unknown as import('../../../../shared/ghost').InstalledGhost;++ const tab = addGlobalPluginTab('beta', { ghost: ghost('bottom') })!;+ expect(tab.id).toBe('g_beta');+ expect(getTabGroup('g_beta')).toBe('bottom');+ // 用户拖到上方,关掉再打开:还在上方,不重新套默认边。+ setTabGroup('g_beta', 'top');+ removeGlobalTab('g_beta');+ expect(addGlobalPluginTab('beta', { ghost: ghost('bottom') })!.id).toBe('g_beta');+ expect(getTabGroup('g_beta')).toBe('top');+ expect(hasPluginPlacementMemory('beta')).toBe(true);++ // 弹过窗口的记忆;恢复默认位置 = 清窗口记忆、回到声明的边。+ rememberPluginWindowPlacement('beta', true);+ expect(isPluginWindowPlacement('beta')).toBe(true);+ resetPluginPlacement('beta', ghost('bottom'));+ expect(isPluginWindowPlacement('beta')).toBe(false);+ expect(getTabGroup('g_beta')).toBe('bottom');++ // 缺省 position 的停靠面板 → left(与历史停靠面板一致);mainView.side 优先。+ expect(defaultGroupForGhost(ghost(undefined))).toBe('left');+ expect(defaultGroupForGhost(ghost(undefined, { open: 'sidebar', side: 'right' }))).toBe('right');+ expect(defaultGroupForGhost(ghost(undefined, { open: 'page' }))).toBe('right');});});diff --git a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.tsindex 72241aae81..a1d4a504fe 100644--- a/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts@@ -13,6 +13,11 @@* 出现(reconcileGlobalPluginTabs),用户关掉后记入 dismissed 不再自动加回;卸载即* 清掉它的页签与 dismissed 记录,重装再按首次启用处理。`mainView` 插件不自动加,* 由左侧栏入口「在侧边栏中打开」加入。+ *+ * 放置记忆:全局页签的 id 由插件实例决定(`g_<instanceId>`),所以组归属(tabGroups)在+ * 关掉再打开后仍然有效;首次出现时按插件声明放到默认边(panel.position / mainView.side),+ * 之后以用户拖到的位置为准;弹到独立窗口过的插件下次从左侧栏入口点开也进窗口。+ * 「恢复默认位置」清掉这些记忆。*/import { useSyncExternalStore } from 'react';@@ -23,7 +28,7 @@ import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import { createLogger } from '@/lib/logger';import { isSidebarTabWindow } from '@/lib/sidebarTabWindow';import { isTabPoppedOut } from '@/lib/sidebarTabWindowState';-import { clearTabGroup, setTabGroup, type TabGroupId } from './tabGroups';+import { clearTabGroup, getTabGroupAssignments, setTabGroup, type TabGroupId } from './tabGroups';import type { TabState } from './types';const log = createLogger('rightSidebar.globalTabs');@@ -40,13 +45,23 @@ export interface GlobalTabsSnapshot {tabs: TabState[];/** 用户主动关掉过、不再自动加回的插件实例。 */dismissedInstanceIds: string[];+ /** 已按插件声明放过默认边的实例(之后不再重新套默认,以用户放置为准)。 */+ placedInstanceIds: string[];+ /** 上次是弹在独立窗口里的实例:左侧栏入口点开时直接进窗口。 */+ windowInstanceIds: string[];}const EMPTY: GlobalTabsSnapshot = Object.freeze({tabs: [],dismissedInstanceIds: [],+ placedInstanceIds: [],+ windowInstanceIds: [],}) as GlobalTabsSnapshot;+function stringList(raw: unknown): string[] {+ return Array.isArray(raw) ? raw.filter((id): id is string => typeof id === 'string' && !!id) : [];+}+let cache: GlobalTabsSnapshot | null = null;let cacheOwnerKey: string | null = null;/** 当前窗口里被激活的全局页签;切任务时保持,选中任务页签时清空。不持久化。 */@@ -82,10 +97,12 @@ export function sanitizeGlobalTabsSnapshot(raw: unknown): GlobalTabsSnapshot {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 };+ return {+ tabs,+ dismissedInstanceIds: stringList(raw.dismissedInstanceIds),+ placedInstanceIds: stringList(raw.placedInstanceIds),+ windowInstanceIds: stringList(raw.windowInstanceIds),+ };}function load(): GlobalTabsSnapshot {@@ -139,7 +156,12 @@ function persist(next: GlobalTabsSnapshot): void {cache = next;cacheOwnerKey = key;try {- if (next.tabs.length === 0 && next.dismissedInstanceIds.length === 0) {+ if (+ next.tabs.length === 0 &&+ next.dismissedInstanceIds.length === 0 &&+ next.placedInstanceIds.length === 0 &&+ next.windowInstanceIds.length === 0+ ) {window.localStorage.removeItem(key);} else {window.localStorage.setItem(key, JSON.stringify(next));@@ -150,17 +172,35 @@ function persist(next: GlobalTabsSnapshot): void {notify();}-function makeTabId(): string {- return `g_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;+/** 全局页签 id 由插件实例决定:关掉再打开仍是同一个 id,组归属等记忆因此跟着实例走。 */+export function globalTabIdForInstance(instanceId: string): string {+ return `g_${instanceId}`;+}++/**+ * 插件声明的默认放置边:mainView.open:'sidebar' 的 side;停靠面板的 panel.position+ * (缺省 left,与历史停靠面板「停在聊天区左侧」一致);其它(纯 mainView)右侧组。+ */+export function defaultGroupForGhost(ghost: InstalledGhost): TabGroupId {+ const { manifest } = ghost;+ if (manifest.mainView?.open === 'sidebar' && manifest.mainView.side) {+ return manifest.mainView.side;+ }+ if (manifest.panel && manifest.panel.position !== 'tab') {+ return manifest.panel.position ?? 'left';+ }+ return 'right';}/*** 加入(或返回已有的)某个插件的全局页签。幂等:同一实例只有一个页签。* 用户手动加入会清掉它的 dismissed 记录。+ * 放置:显式 `groupId` 优先;否则首次出现的实例按插件声明放默认边(之后以用户放置为准,+ * 不再重新套默认);都没有就沿用已有组归属(缺省右侧组)。*/export function addGlobalPluginTab(instanceId: string,- opts?: { groupId?: TabGroupId },+ opts?: { groupId?: TabGroupId; ghost?: InstalledGhost },): TabState | null {const current = getGlobalTabsSnapshot();const existing = current.tabs.find(@@ -168,8 +208,9 @@ export function addGlobalPluginTab();const dismissed = current.dismissedInstanceIds.filter((id) => id !== instanceId);if (existing) {+ if (opts?.groupId) setTabGroup(existing.id, opts.groupId);if (dismissed.length !== current.dismissedInstanceIds.length) {- persist({ tabs: current.tabs, dismissedInstanceIds: dismissed });+ persist({ ...current, dismissedInstanceIds: dismissed });}return existing;}@@ -178,13 +219,24 @@ export function addGlobalPluginTab(return null;}const tab: TabState = {- id: makeTabId(),+ id: globalTabIdForInstance(instanceId),kind: 'plugin-view',state: { instanceId } satisfies PluginViewTabState,};+ let placed = current.placedInstanceIds;// 组归属先于页签出现落定,首帧就在目标组里。- if (opts?.groupId) setTabGroup(tab.id, opts.groupId);- persist({ tabs: [...current.tabs, tab], dismissedInstanceIds: dismissed });+ if (opts?.groupId) {+ setTabGroup(tab.id, opts.groupId);+ } else if (opts?.ghost && !placed.includes(instanceId)) {+ setTabGroup(tab.id, defaultGroupForGhost(opts.ghost));+ placed = [...placed, instanceId];+ }+ persist({+ ...current,+ tabs: [...current.tabs, tab],+ dismissedInstanceIds: dismissed,+ placedInstanceIds: placed,+ });return tab;}@@ -198,11 +250,12 @@ export function removeGlobalTab(tabId: string): void {? current.dismissedInstanceIds: [...current.dismissedInstanceIds, instanceId];if (activeGlobalTabId === tabId) activeGlobalTabId = null;+ // 组归属不清:关掉再打开回到用户上次放的那一边(放置记忆)。persist({+ ...current,tabs: current.tabs.filter((candidate) => candidate.id !== tabId),dismissedInstanceIds: dismissed,});- clearTabGroup(tabId);// 页签正弹在独立窗口里:窗口没有内容可交回,直接销毁(与任务页签同一规则)。if (!isSidebarTabWindow() && isTabPoppedOut(tabId)) {void window.electronAPI?.sidebarTabWindow?.closeForTab(tabId).catch((err) => {@@ -221,7 +274,56 @@ export function reorderGlobalTabs(orderedIds: string[]): void {if (!tab) return;next.push(tab);}- persist({ tabs: next, dismissedInstanceIds: current.dismissedInstanceIds });+ persist({ ...current, tabs: next });+}++/** 记住 / 忘记「这个插件上次弹在独立窗口里」。 */+export function rememberPluginWindowPlacement(instanceId: string, inWindow: boolean): void {+ const current = getGlobalTabsSnapshot();+ const has = current.windowInstanceIds.includes(instanceId);+ if (has === inWindow) return;+ persist({+ ...current,+ windowInstanceIds: inWindow+ ? [...current.windowInstanceIds, instanceId]+ : current.windowInstanceIds.filter((id) => id !== instanceId),+ });+}++export function isPluginWindowPlacement(instanceId: string): boolean {+ return getGlobalTabsSnapshot().windowInstanceIds.includes(instanceId);+}++/** 用户是否放置过这个插件(拖到别的边 / 弹过窗口 / 已套过默认边):有记忆才给「恢复默认位置」。 */+export function hasPluginPlacementMemory(instanceId: string): boolean {+ const current = getGlobalTabsSnapshot();+ const tabId = globalTabIdForInstance(instanceId);+ return (+ current.windowInstanceIds.includes(instanceId) ||+ current.placedInstanceIds.includes(instanceId) ||+ tabId in getTabGroupAssignments()+ );+}++/**+ * 恢复默认位置:清掉窗口记忆与组归属;页签还在时按插件声明重新放到默认边。+ * 弹在窗口里的页签由调用方先合并回侧边栏(这里不碰窗口)。+ */+export function resetPluginPlacement(instanceId: string, ghost?: InstalledGhost): void {+ const current = getGlobalTabsSnapshot();+ const tabId = globalTabIdForInstance(instanceId);+ clearTabGroup(tabId);+ const tabPresent = current.tabs.some((tab) => tab.id === tabId);+ let placed = current.placedInstanceIds.filter((id) => id !== instanceId);+ if (tabPresent && ghost) {+ setTabGroup(tabId, defaultGroupForGhost(ghost));+ placed = [...placed, instanceId];+ }+ persist({+ ...current,+ placedInstanceIds: placed,+ windowInstanceIds: current.windowInstanceIds.filter((id) => id !== instanceId),+ });}/** 页签标题:停靠面板用 panel.title,整页视图用 mainView.title,都没有就用插件名。 */@@ -269,26 +371,45 @@ export function reconcileGlobalPluginTabs(ghosts: readonly InstalledGhost[]): voinstalled.has((tab.state as PluginViewTabState).instanceId),);const dismissed = current.dismissedInstanceIds.filter((id) => installed.has(id));+ let placed = current.placedInstanceIds.filter((id) => installed.has(id));+ const windowed = current.windowInstanceIds.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 } }];+ const tabId = globalTabIdForInstance(instanceId);+ // 首次出现:按插件声明放默认边(存量 panel.position 的插件回到它原来停的那一边)。+ if (!placed.includes(instanceId)) {+ setTabGroup(tabId, defaultGroupForGhost(ghost));+ placed = [...placed, instanceId];+ }+ tabs = [...tabs, { id: tabId, 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+ dismissed.length === current.dismissedInstanceIds.length &&+ placed.length === current.placedInstanceIds.length &&+ windowed.length === current.windowInstanceIds.length) {return;}if (activeGlobalTabId && !tabs.some((tab) => tab.id === activeGlobalTabId)) {activeGlobalTabId = null;}+ // 卸载的实例:页签与全部记忆(组归属 / 默认边 / 窗口)一起清。+ for (const id of current.placedInstanceIds) {+ if (!installed.has(id)) clearTabGroup(globalTabIdForInstance(id));+ }for (const tab of current.tabs) if (!tabs.includes(tab)) clearTabGroup(tab.id);- persist({ tabs, dismissedInstanceIds: dismissed });+ persist({+ tabs,+ dismissedInstanceIds: dismissed,+ placedInstanceIds: placed,+ windowInstanceIds: windowed,+ });}export function getActiveGlobalTabId(): string | null {diff --git a/apps/desktop/src/renderer/features/right-sidebar/moveTab.ts b/apps/desktop/src/renderer/features/right-sidebar/moveTab.tsindex df149fdeb3..be3d7ba346 100644--- a/apps/desktop/src/renderer/features/right-sidebar/moveTab.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/moveTab.ts@@ -5,7 +5,13 @@*/import { createLogger } from '@/lib/logger';-import { isGlobalTabId, setActiveGlobalTabId } from './globalTabs';+import {+ findGlobalTab,+ isGlobalTabId,+ rememberPluginWindowPlacement,+ setActiveGlobalTabId,+ type PluginViewTabState,+} from './globalTabs';import { requestRightSidebarVisibility } from './lib/sidebarCommands';import { setActiveTab } from './store';import { getTabGroup, setGroupActiveTabId, setTabGroup, type TabGroupId } from './tabGroups';@@ -22,6 +28,9 @@ export function moveTabToGroup(setGroupActiveTabId(target, sessionId, tabId);if (isGlobalTabId(tabId)) {setActiveGlobalTabId(tabId);+ // 插件视图放回侧边栏的某一边 = 不再记它「在独立窗口里」。+ const instanceId = (findGlobalTab(tabId)?.state as PluginViewTabState | null)?.instanceId;+ if (instanceId) rememberPluginWindowPlacement(instanceId, false);} else if (sessionId) {void setActiveTab(sessionId, tabId).catch((err) => {log.warn('activate moved tab failed', { sessionId, tabId, err });diff --git a/apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.ts b/apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.tsnew file mode 100644index 0000000000..63251d9698--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.ts@@ -0,0 +1,91 @@+/**+ * pluginPlacement —— 左侧栏插件入口点下去,主视图在哪里打开。+ *+ * 决策顺序(用户的放置记忆 > 插件声明的默认 > 内置默认):+ * 1. 页签已经在某扇独立窗口里 → 聚焦那扇窗口;+ * 2. 页签已经在侧边栏的某个组里 → 选中它(右侧组收着就展开);+ * 3. 用户上次把它弹到了独立窗口(windowInstanceIds)→ 再开进窗口;+ * 4. 插件 manifest 的 mainView.open:'sidebar' / 'window';+ * 5. 内置默认:撑满内容区的页面(由调用方 navigate)。+ * 放进侧边栏时的默认边同样是记忆优先(tabGroups 里的组归属),其次 mainView.side /+ * panel.position,最后右侧组(见 globalTabs.defaultGroupForGhost)。+ */++import type { InstalledGhost } from '../../../shared/ghost';+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';+import { createLogger } from '@/lib/logger';+import { isTabPoppedOut } from '@/lib/sidebarTabWindowState';+import {+ addGlobalPluginTab,+ findGlobalTabByInstance,+ isPluginWindowPlacement,+ rememberPluginWindowPlacement,+ setActiveGlobalTabId,+} from './globalTabs';+import { requestRightSidebarVisibility } from './lib/sidebarCommands';+import { getTabGroup } from './tabGroups';++const log = createLogger('rightSidebar.pluginPlacement');++export type PluginOpenTarget = 'page' | 'sidebar' | 'window';++/** 左侧栏入口点击时的打开目标(不含「已在侧边栏 / 窗口里」的聚焦分支)。 */+export function resolvePluginOpenTarget(ghost: InstalledGhost): PluginOpenTarget {+ const instanceId = installedGhostStoragePart(ghost);+ const existing = findGlobalTabByInstance(instanceId);+ if (existing) return isTabPoppedOut(existing.id) ? 'window' : 'sidebar';+ if (isPluginWindowPlacement(instanceId)) return 'window';+ const open = ghost.manifest.mainView?.open;+ if (open === 'sidebar' || open === 'window') return open;+ return 'page';+}++/** 作为全局页签放进侧边栏(默认边见模块说明),选中它;落在右侧组时展开右侧栏。 */+export function openPluginInSidebar(ghost: InstalledGhost): void {+ const instanceId = installedGhostStoragePart(ghost);+ const tab = addGlobalPluginTab(instanceId, { ghost });+ if (!tab) return;+ rememberPluginWindowPlacement(instanceId, false);+ setActiveGlobalTabId(tab.id);+ if (getTabGroup(tab.id) === 'right') requestRightSidebarVisibility('open');+}++/** 弹到独立窗口(已弹出则聚焦那扇窗口)。只在主窗口可用:弹出请求只接受主窗 sender。 */+export function openPluginInWindow(ghost: InstalledGhost): void {+ const instanceId = installedGhostStoragePart(ghost);+ const api = window.electronAPI?.sidebarTabWindow;+ const tab = addGlobalPluginTab(instanceId, { ghost });+ if (!tab || !api) return;+ rememberPluginWindowPlacement(instanceId, true);+ if (isTabPoppedOut(tab.id)) {+ void api.focus(tab.id).catch((err) => log.warn('focus plugin window failed', { err }));+ return;+ }+ if (!api.open) {+ // 副窗口没有弹出权:退回侧边栏。+ setActiveGlobalTabId(tab.id);+ return;+ }+ void api+ .open({+ tabId: tab.id,+ sessionId: null,+ context: { workdir: null, remoteHostId: null },+ handoff: null,+ })+ .catch((err) => log.warn('pop out plugin view failed', { instanceId, err }));+}++/** 已在侧边栏 / 窗口里的页签:聚焦它。返回 false = 还没有页签。 */+export function focusExistingPluginTab(ghost: InstalledGhost): boolean {+ const instanceId = installedGhostStoragePart(ghost);+ const existing = findGlobalTabByInstance(instanceId);+ if (!existing) return false;+ if (isTabPoppedOut(existing.id)) {+ void window.electronAPI?.sidebarTabWindow?.focus(existing.id).catch(() => undefined);+ return true;+ }+ setActiveGlobalTabId(existing.id);+ if (getTabGroup(existing.id) === 'right') requestRightSidebarVisibility('open');+ return true;+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 79ef60c280..27a6c2cc34 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6596,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}}\" · shown in the right sidebar",+ "panelLeft": "Panel \"{{title}}\" · shown in the 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.",@@ -6750,7 +6750,8 @@"collapseTools": "Collapse Tools","viewAllPermissions": "See All","permissionsDialogDescription": "All {{count}} permissions requested by this Plugin",- "closeDialog": "Close Dialog"+ "closeDialog": "Close Dialog",+ "resetPlacement": "Reset to default position"},"contents": {"mainView": "Main view",@@ -7989,7 +7990,10 @@}},"ghostMainView": {- "openInSidebar": "Open in the sidebar"+ "openInSidebar": "Open in the sidebar",+ "openInPage": "Open as page",+ "openInWindow": "Open in a separate window",+ "resetPlacement": "Reset to default position"},"rightSidebar": {"ariaLabel": "Right sidebar",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex d110481351..da0a6f6c1f 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6565,7 +6565,7 @@"nodeResidentDetail": "プラグインが有効な間は実行を続け、無効化、更新、アンインストール、または Cindy 終了時に停止します。","tool": "ツール「{{name}}」","command": "チャット指令 ${{command}}",- "panelLeft": "パネル「{{title}}」· 右サイドバーに表示",+ "panelLeft": "パネル「{{title}}」· サイドバーに表示","panelTab": "パネル「{{title}}」· プラグインページ内で開く","mainView": "Cindy のサイドバーに「{{title}}」への入口を追加できます","mainViewDetail": "クリックするとプラグインのサンドボックス内でメインビューが開き、ファイル、ネットワーク、認証情報へのアクセスが追加で付与されることはありません。",@@ -6719,7 +6719,8 @@"collapseTools": "Tool を折りたたむ","viewAllPermissions": "さらに表示","permissionsDialogDescription": "この Plugin が要求する全 {{count}} 項目の権限",- "closeDialog": "ダイアログを閉じる"+ "closeDialog": "ダイアログを閉じる",+ "resetPlacement": "既定の位置に戻す"},"contents": {"mainView": "メインビュー",@@ -7957,7 +7958,10 @@}},"ghostMainView": {- "openInSidebar": "サイドバーで開く"+ "openInSidebar": "サイドバーで開く",+ "openInPage": "ページで開く",+ "openInWindow": "別ウィンドウで開く",+ "resetPlacement": "既定の位置に戻す"},"rightSidebar": {"ariaLabel": "右サイドバー",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 08a60064b2..71618e62c1 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6565,7 +6565,7 @@"nodeResidentDetail": "플러그인이 활성화된 동안 실행되며 비활성화, 업데이트, 제거 또는 Cindy 종료 시 중지됩니다.","tool": "도구 \"{{name}}\"","command": "채팅 명령 ${{command}}",- "panelLeft": "패널 \"{{title}}\" · 오른쪽 사이드바에 표시",+ "panelLeft": "패널 \"{{title}}\" · 사이드바에 표시","panelTab": "패널 \"{{title}}\" · 플러그인 페이지에서 열기","mainView": "Cindy 사이드바에 “{{title}}” 항목을 추가할 수 있음","mainViewDetail": "클릭하면 플러그인 샌드박스에서 메인 보기가 열리며 파일, 네트워크 또는 자격 증명 접근 권한이 추가로 부여되지 않습니다.",@@ -6719,7 +6719,8 @@"collapseTools": "Tool 접기","viewAllPermissions": "더 보기","permissionsDialogDescription": "이 Plugin이 요청하는 전체 {{count}}개 권한",- "closeDialog": "대화 상자 닫기"+ "closeDialog": "대화 상자 닫기",+ "resetPlacement": "기본 위치로 복원"},"contents": {"mainView": "메인 보기",@@ -7957,7 +7958,10 @@}},"ghostMainView": {- "openInSidebar": "사이드바에서 열기"+ "openInSidebar": "사이드바에서 열기",+ "openInPage": "페이지로 열기",+ "openInWindow": "별도 창에서 열기",+ "resetPlacement": "기본 위치로 복원"},"rightSidebar": {"ariaLabel": "오른쪽 사이드바",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 2e88a43a79..7dad93d1b2 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6565,7 +6565,7 @@"nodeResidentDetail": "插件启用期间会一直运行;停用、更新、卸载或退出 Cindy 时关闭。","tool": "工具「{{name}}」","command": "对话指令 ${{command}}",- "panelLeft": "面板「{{title}}」· 显示在右侧栏",+ "panelLeft": "面板「{{title}}」· 显示在侧边栏","panelTab": "面板「{{title}}」· 插件页内打开","mainView": "可在 Cindy 侧边栏添加“{{title}}”入口","mainViewDetail": "点击后将在插件沙箱中打开主视图,不会因此获得文件、网络或凭证访问权限。",@@ -6719,7 +6719,8 @@"collapseTools": "收起 Tool","viewAllPermissions": "查看更多","permissionsDialogDescription": "该插件申请的全部 {{count}} 项权限",- "closeDialog": "关闭弹窗"+ "closeDialog": "关闭弹窗",+ "resetPlacement": "恢复默认位置"},"contents": {"mainView": "主视图",@@ -7957,7 +7958,10 @@}},"ghostMainView": {- "openInSidebar": "在侧边栏中打开"+ "openInSidebar": "在侧边栏中打开",+ "openInPage": "在页面中打开",+ "openInWindow": "在独立窗口中打开",+ "resetPlacement": "恢复默认位置"},"rightSidebar": {"ariaLabel": "右侧边栏",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex c9844b7577..6132d2e9d4 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -6565,7 +6565,7 @@"nodeResidentDetail": "插件啟用期間會一直執行;停用、更新、解除安裝或退出 Cindy 時關閉。","tool": "工具「{{name}}」","command": "對話指令 ${{command}}",- "panelLeft": "面板「{{title}}」· 顯示在右側欄",+ "panelLeft": "面板「{{title}}」· 顯示在側邊欄","panelTab": "面板「{{title}}」· 插件頁內開啟","mainView": "可在 Cindy 側邊欄新增「{{title}}」入口","mainViewDetail": "點擊後將在插件沙箱中開啟主視圖,不會因此取得檔案、網路或憑證存取權限。",@@ -6719,7 +6719,8 @@"collapseTools": "收起 Tool","viewAllPermissions": "檢視更多","permissionsDialogDescription": "該插件申請的全部 {{count}} 項權限",- "closeDialog": "關閉彈窗"+ "closeDialog": "關閉彈窗",+ "resetPlacement": "恢復預設位置"},"contents": {"mainView": "主視圖",@@ -7957,7 +7958,10 @@}},"ghostMainView": {- "openInSidebar": "在側邊欄中開啟"+ "openInSidebar": "在側邊欄中開啟",+ "openInPage": "在頁面中開啟",+ "openInWindow": "在獨立視窗中開啟",+ "resetPlacement": "恢復預設位置"},"rightSidebar": {"ariaLabel": "右側邊欄",diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex dd1e3f4eb3..c268417b82 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -2314,25 +2314,46 @@ describe('ghost · description(自我介绍)', () => {});describe('ghost · panel.position 校验', () => {- it('left 通过;right 退役兼容归一化为 left;top/bottom 收词但明确拒绝;野值拒', () => {+ it('left / right / top / bottom 都是真实的边(页签组落地后 right 不再并入 left);野值拒', () => {const withPos = (position: unknown) => ({...goodManifest(),panel: { title: 'Hello', html: 'panel.html', position },});- const left = validateGhostManifest(withPos('left'));- expect(left.ok && left.manifest.panel?.position).toBe('left');- // 旧包兼容:right 不拒装(已装插件每次启动重过校验),归一化为 left。- const right = validateGhostManifest(withPos('right'));- expect(right.ok && right.manifest.panel?.position).toBe('left');-- for (const pending of ['top', 'bottom']) {- const v = validateGhostManifest(withPos(pending));- expect(v.ok).toBe(false);- expect(!v.ok && v.reason).toContain('暂未支持');+ for (const side of ['left', 'right', 'top', 'bottom'] as const) {+ const v = validateGhostManifest(withPos(side));+ expect(v.ok && v.manifest.panel?.position).toBe(side);}expect(validateGhostManifest(withPos('center')).ok).toBe(false);});+ // 测试价值+ // - 生产入口与可观察结果:validateGhostManifest 对 mainView.open / side 的校验;可观察的是+ // 合法组合原样保留、open 野值拒、side 在 open 非 sidebar 时拒(规则 9 不静默忽略)。+ // - Bug / 规则依据:插件可声明左侧栏入口的默认打开方式(页签组模型第三阶段)。+ // - 现有覆盖缺口:mainView 此前只有 html / title / icon 用例。+ // - 最小失败输入:{ open: 'sidebar', side: 'left' }。+ // - tier:unit。+ it('mainView.open / side:合法组合保留,open 野值与 open 非 sidebar 时的 side 都拒', () => {+ const withView = (mainView: Record<string, unknown>) => ({+ ...goodChipManifest(),+ minCindyVersion: '1.2.3',+ slots: ['panel', 'main-view'],+ mainView: { html: 'main-view.html', ...mainView },+ });+ expect(validateGhostManifest(withView({ open: 'sidebar', side: 'left' }))).toMatchObject({+ ok: true,+ manifest: { mainView: { open: 'sidebar', side: 'left' } },+ });+ expect(validateGhostManifest(withView({ open: 'window' }))).toMatchObject({+ ok: true,+ manifest: { mainView: { open: 'window' } },+ });+ expect(validateGhostManifest(withView({ open: 'popup' })).ok).toBe(false);+ expect(validateGhostManifest(withView({ open: 'page', side: 'left' })).ok).toBe(false);+ expect(validateGhostManifest(withView({ side: 'left' })).ok).toBe(false);+ expect(validateGhostManifest(withView({ open: 'sidebar', side: 'middle' })).ok).toBe(false);+ });+it("'tab'(右侧栏页签)通过;tab 时 minWidth/defaultFraction 收词明确拒绝", () => {const tab = validateGhostManifest({...goodManifest(),diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 0ef1b02b66..70cf5fac4b 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -430,25 +430,21 @@ export const GHOST_LAUNCH_MODES = ['on-demand', 'resident'] as const;export type GhostLaunchMode = (typeof GHOST_LAUNCH_MODES)[number];/**- * 面板显示形态(相对主聊天窗)。left = 顶层布局树停靠 pane(缺省);- * 'tab' = 不进布局树,作为右侧栏(right-tabs)里的每会话单例页签- * (2026-08 面板收束:页签面板由插件页 GhostPagePanelHost 独占承载)。- * right 已退役(2026-07-25 Lizi 定案:右侧是右侧边栏的地盘,插件面板默认- * 挤过去体验差;用户想放右边用拖拽换位即可)——旧包声明的 right 在校验期- * 归一化为 left(已装插件每次启动都重过校验,硬拒会把存量插件打没;兼容- * 语义与 model→cindy 改名同款)。top / bottom 需要嵌套上下分割(树操作/- * 拖缝/卸载查找全链路),排期中——校验层先收词并明确拒绝,不静默降级(规则 9)。- */-export const GHOST_PANEL_POSITIONS = ['left', 'tab'] as const;+ * 面板显示形态:left / right / top / bottom = 右侧栏页签系统里的停靠组(插件启用后自动+ * 成为对应边页签组里一个不跟对话的全局页签,用户可再拖到任何一边、弹成独立窗口或关闭;+ * 缺省 left,与历史停靠面板「停在聊天区左侧」一致);tab = 插件页内独占面板。+ * right 曾退役并入 left(2026-07-25),页签组落地后重新作为真实的一边。+ */+export const GHOST_PANEL_POSITIONS = ['left', 'right', 'top', 'bottom', 'tab'] as const;export type GhostPanelPosition = (typeof GHOST_PANEL_POSITIONS)[number];/** 面板声明(五个卡槽中的「面板」槽,一段意识至多一块)。 */export interface GhostPanelDecl {/** 面板标题(右侧栏页签 / 插件页标题);缺省用意识 name。 */title?: string;- /** 显示形态:left 停靠主聊天窗左侧(缺省),或 'tab' 插件页内独占面板- * (2026-08-02 面板收束:只从插件页打开,离开插件页即关闭);- * right 已退役并入 left(2026-07-25 Lizi 定案,见 GHOST_PANEL_POSITIONS 注释)。 */+ /** 显示形态:left(缺省)/ right / top / bottom = 聊天区对应边的页签组(用户可再+ * 拖动改位,主机记住用户的放置);'tab' = 插件页内独占面板(2026-08-02 面板收束:+ * 只从插件页打开,离开插件页即关闭)。 */position?: GhostPanelPosition;/** 面板界面入口(安装目录内相对路径,意识自绘)。 */html: string;@@ -482,6 +478,13 @@ export const GHOST_MAIN_VIEW_ICONS = [export type GhostMainViewIcon = (typeof GHOST_MAIN_VIEW_ICONS)[number];/** 应用级插件主视图;与会话内 panel 分开声明和批准。 */+/** 左侧栏入口点击后主视图在哪里打开(插件给的默认偏好;用户放置过后以用户的为准)。 */+export const GHOST_MAIN_VIEW_OPEN_MODES = ['page', 'sidebar', 'window'] as const;+export type GhostMainViewOpenMode = (typeof GHOST_MAIN_VIEW_OPEN_MODES)[number];+/** 主视图以页签形态打开时默认停在聊天区的哪一边。 */+export const GHOST_TAB_SIDES = ['left', 'right', 'top', 'bottom'] as const;+export type GhostTabSide = (typeof GHOST_TAB_SIDES)[number];+export interface GhostMainViewDecl {/** 侧边栏与页面标题;缺省回退插件 name。 */title?: string;@@ -489,6 +492,15 @@ export interface GhostMainViewDecl {icon?: GhostMainViewIcon;/** 主视图界面入口(安装目录内安全相对路径)。 */html: string;+ /**+ * 左侧栏入口点击后的默认打开方式:page(缺省)= 撑满内容区的页面;sidebar = 作为+ * 不跟对话的页签放进聊天区某一边的页签组(`side` 指定,缺省 right);window = 弹成+ * 独立窗口。只是默认值:用户拖过 / 弹过之后主机记住用户的放置,直到用户在插件+ * 详情页「恢复默认位置」。+ */+ open?: GhostMainViewOpenMode;+ /** open:'sidebar' 时的默认边;其它 open 值下声明本字段拒装。 */+ side?: GhostTabSide;}/**@@ -3976,25 +3988,13 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo}let position: GhostPanelPosition | undefined;if (p.position !== undefined) {- if (p.position === 'top' || p.position === 'bottom') {- // 收词但明确拒绝(规则 9 不静默降级):上下停靠等布局引擎嵌套分割就绪后开放。+ if (!(GHOST_PANEL_POSITIONS as readonly string[]).includes(p.position as string)) {return {ok: false,- reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / tab',+ reason: `panel.position 必须是 ${GHOST_PANEL_POSITIONS.join(' / ')}`,};}- if (p.position === 'right') {- // right 退役兼容(见 GHOST_PANEL_POSITIONS 注释):旧包归一化为 left,- // 不硬拒 —— 已装插件每次启动重过本校验,硬拒等于把存量插件打没。- position = 'left';- } else if (!(GHOST_PANEL_POSITIONS as readonly string[]).includes(p.position as string)) {- return {- ok: false,- reason: `panel.position 必须是 ${GHOST_PANEL_POSITIONS.join(' / ')}(right 已退役,旧包自动并入 left)`,- };- } else {- position = p.position as GhostPanelPosition;- }+ position = p.position as GhostPanelPosition;// 页签形态没有拖缝宽度/标准头语义:收词明确拒绝而非静默忽略(规则 9)。if (position === 'tab' &&@@ -4048,10 +4048,31 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: booreason: 'mainView.html 必填,且必须是安装目录内的安全相对路径',};}+ if (+ raw.mainView.open !== undefined &&+ !(GHOST_MAIN_VIEW_OPEN_MODES as readonly unknown[]).includes(raw.mainView.open)+ ) {+ return {+ ok: false,+ reason: `mainView.open 必须是 ${GHOST_MAIN_VIEW_OPEN_MODES.join(' / ')}`,+ };+ }+ if (raw.mainView.side !== undefined) {+ if (raw.mainView.open !== 'sidebar') {+ return { ok: false, reason: "mainView.side 只在 open:'sidebar' 时有效,其它打开方式请移除" };+ }+ if (!(GHOST_TAB_SIDES as readonly unknown[]).includes(raw.mainView.side)) {+ return { ok: false, reason: `mainView.side 必须是 ${GHOST_TAB_SIDES.join(' / ')}` };+ }+ }mainView = {- ...unknownDeclarationFields(raw.mainView, ['html', 'title', 'icon']),+ ...unknownDeclarationFields(raw.mainView, ['html', 'title', 'icon', 'open', 'side']),...(raw.mainView.title !== undefined ? { title: raw.mainView.title } : {}),...(raw.mainView.icon !== undefined ? { icon: raw.mainView.icon as GhostMainViewIcon } : {}),+ ...(raw.mainView.open !== undefined+ ? { open: raw.mainView.open as GhostMainViewOpenMode }+ : {}),+ ...(raw.mainView.side !== undefined ? { side: raw.mainView.side as GhostTabSide } : {}),html: raw.mainView.html,};}