Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 插件停靠面板系统按钮(撑满/独立窗口)与 position 收敛

Lizi93e54814a34a
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 891b7c93d6..a2943e0d69 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -342,6 +342,14 @@ import {
import { RsbWindowController } from './right-sidebar-window/controller.js';
import { createRightSidebarWindow } from './right-sidebar-window/window.js';
import { registerRsbWindowIpc } from './right-sidebar-window/ipc.js';
+import { GhostPanelWindowsController } from './ghost-panel-window/controller.js';
+import { createGhostPanelWindow } from './ghost-panel-window/window.js';
+import { registerGhostPanelWindowIpc } from './ghost-panel-window/ipc.js';
+import {
+ patchGhostPanelWindowEntry,
+ readGhostPanelWindowsSettings,
+ removeGhostPanelWindowEntry,
+} from './ghost-panel-window/settings-store.js';
import {
readRsbWindowSettings,
writeRsbWindowSettingsPatch,
@@ -535,7 +543,14 @@ import {
} from './app-shortcuts/index.js';
import { installNewMakerWindowShortcut } from './app-shortcuts/new-maker-window-shortcut.js';
import { registerLayoutIpc } from './layout/index.js';
-import { registerGhostIpc, suspendAllGhosts, waitForGhostMutations } from './cindy-brain/index.js';
+import {
+ getGhostManager,
+ isGhostAvailableForActiveSession,
+ registerGhostIpc,
+ setGhostsChangedObserver,
+ suspendAllGhosts,
+ waitForGhostMutations,
+} from './cindy-brain/index.js';
import { registerPluginMarketIpc } from './plugin-market/registerIpc.js';
import { findCindyFileInArgv } from './cindy-brain/argv.js';
import { handleIncomingCindyFile } from './cindy-brain/openFileInstall.js';
@@ -979,6 +994,52 @@ registerRsbWindowIpc({
getMainWindow: () => mainWindowRef,
});
+// ── 插件停靠面板独立窗口(ghost panel window)────────────────────────────
+// 每 ghostId 一扇窗:PanelChrome「独立窗口」按钮 → setDetached(id, true) 开窗,
+// 主窗布局树里该 pane 停止渲染(树不动);关窗/合并即回停靠。装/卸/启停广播
+// 经 setGhostsChangedObserver 喂 reconcile,失去资格的窗口即时收掉。
+// deps 同样全 lazy(isQuitting 声明在后),状态机见 ghost-panel-window/controller.ts。
+const ghostPanelWindowsController = new GhostPanelWindowsController({
+ settings: {
+ read: readGhostPanelWindowsSettings,
+ patchEntry: patchGhostPanelWindowEntry,
+ removeEntry: removeGhostPanelWindowEntry,
+ },
+ createWindow: (ghostId) => {
+ const ghost = getGhostManager()
+ .list()
+ .find((g) => g.manifest.id === ghostId);
+ const title = ghost?.manifest.panel?.title ?? ghost?.manifest.name ?? ghostId;
+ return createGhostPanelWindow(ghostId, title);
+ },
+ isGhostDetachable: (ghostId) => {
+ const ghost = getGhostManager()
+ .list()
+ .find((g) => g.manifest.id === ghostId);
+ return (
+ ghost !== undefined &&
+ ghost.enabled !== false &&
+ ghost.manifest.panel !== undefined &&
+ ghost.manifest.panel.position !== 'tab' &&
+ isGhostAvailableForActiveSession(ghostId)
+ );
+ },
+ broadcastState: (state) => {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (win.isDestroyed()) continue;
+ try {
+ win.webContents.send(MAKER_PUSH.GHOST_PANEL_WINDOW_STATE_CHANGED, state);
+ } catch {
+ // window torn down mid-broadcast — ignore
+ }
+ }
+ },
+ isQuitting: () => isQuitting,
+ log: createLogger('ghost-panel-window-controller'),
+});
+registerGhostPanelWindowIpc(ghostPanelWindowsController);
+setGhostsChangedObserver((ghosts) => ghostPanelWindowsController.reconcile(ghosts));
+
registerRsbBrowserBridgeIpc({
registry: getRsbBrowserBridge(),
getHostWebContents: () => rsbWindowController.getHostWebContents(),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 615367eeec..25091bcbde 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -368,6 +368,11 @@ describe('FORGE_GUIDE', () => {
'面板(panel.html/css/js)',
'panel.position',
'右侧栏页签',
+ // 2026-07-25 标准头系统按钮:主机画标题条,systemButtons 逐个关
+ // (maximize 撑满 / detach 独立窗口);§2 样例与 §5 面板章节同步。
+ 'systemButtons',
+ '撑满内容区',
+ '在独立窗口中打开',
]) {
expect(FORGE_GUIDE).toContain(marker);
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index e90ddccd73..b964f52adf 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -675,12 +675,19 @@ my-ghost/
"command": "画图", // 可选:用户 $画图 显式点名(与已装意识查重,冲突拒装)
"tools": [ /* 见 §3 */ ],
"cindy": { "image": ["generate", "edit"] }, // 声明了 cindy 槽时必写:能力详单,见下
- "panel": { "title": "面板标题", "html": "panel.html", "position": "right",
- "minWidth": 240, "defaultFraction": 0.24 },
- // panel.position:面板显示形态。right(缺省)/ left = 停靠主聊天窗两侧;
+ "panel": { "title": "面板标题", "html": "panel.html", "position": "left",
+ "minWidth": 240, "defaultFraction": 0.24,
+ "systemButtons": { "maximize": false } },
+ // panel.position:面板显示形态。left(缺省)= 停靠主聊天窗左侧;
// "tab" = 右侧栏页签(与文件/审查/终端同一容器,每会话至多一个,用户从
// 空态列表或「+」菜单打开;此形态没有拖缝宽度,声明 minWidth /
- // defaultFraction 会被拒装,请移除)。top/bottom 暂未支持(排期中)
+ // defaultFraction 会被拒装,请移除)。right 已退役(右侧是右侧边栏的地盘;
+ // 旧包声明 right 自动并入 left,用户想放右边可自己拖拽换位)。
+ // top/bottom 暂未支持(排期中)
+ // panel.systemButtons(可选,仅停靠形态):标准头系统按钮开关,缺省全开、
+ // 声明 false 逐个关闭。当前一批:maximize(撑满内容区)、detach(在独立
+ // 窗口中打开)。标题条本体恒由主机绘制、关不掉;未知键拒装;
+ // position:"tab" 时声明本字段拒装
"settingsHtml": "settings.html", // 可选:设置页「自定义设置区」自绘界面(见 §4.8;声明了用户填的凭证时必填——凭证收单界面,见 §4.7)
"settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮,高至 800);内容会动态增减时才声明,避免抖动
}
@@ -2116,14 +2123,23 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);
## 5. 面板(panel.html/css/js)
-- 显示形态由 \`panel.position\` 决定:\`right\`(缺省)/ \`left\` = 停靠主聊天窗两侧
- 的常驻面板;\`"tab"\` = 右侧栏页签——与文件/审查/终端同一容器,每会话至多
- 一个页签,由用户从右侧栏空态列表或「+」菜单打开。当用户在会话视图内装入
+- 显示形态由 \`panel.position\` 决定:\`left\`(缺省)= 停靠主聊天窗左侧的常驻
+ 面板(\`right\` 已退役:右侧是右侧边栏的地盘,旧包声明 right 自动并入 left,
+ 用户想放右边可自己拖拽换位);\`"tab"\` = 右侧栏页签——与文件/审查/终端同一
+ 容器,每会话至多一个页签,由用户从右侧栏空态列表或「+」菜单打开。当用户在会话视图内装入
tab 型插件并勾选「立即开启」时,装入完成后会自动展开右侧栏并打开/聚焦该
页签;从插件页(无会话路由)装入或未勾选时,仍由用户手动从空态/「+」菜单
打开。页签形态没有拖缝宽度语义,声明 \`minWidth\` / \`defaultFraction\` 会被
拒装。两种形态的面板代码完全一样(同一 panel.html,供片/主题/媒体规则不变),
只是宿主容器不同;页签形态请把界面做成自适应宽度;
+- 停靠形态的**标题条(标准头)由主机绘制**:标题(\`panel.title\`)+ 一批系统
+ 按钮(当前:「撑满内容区」与「在独立窗口中打开」——用户可把你的面板抽进
+ 自己的 OS 窗口,关窗/合并即回停靠原位,面板代码零感知;后续新增的系统按钮
+ 也长在这里)。你的 panel.html 只画标题条以下的部分,**不要自己再画一条
+ 标题栏**。不想要某颗系统按钮时在身份卡声明
+ \`"systemButtons": { "maximize": false, "detach": false }\` 逐个关闭(缺省
+ 全开;标题条本体关不掉;未知键拒装;\`position:"tab"\` 没有标准头,声明本
+ 字段拒装);
- 与电子脑同源,用 \`BroadcastChannel('<自定名>')\` 通信(电子脑发,面板收);
- 取自己的媒体:\`cindy-ghost://<id>/media/<指纹><后缀>\`(主机查账验归属,别人的图 404);
- 重启回放:\`fetch('cindy-ghost://<id>/gallery')\` 返回本意识作品清单 \`[{src, caption}]\`;
@@ -2214,6 +2230,7 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);
- \`id\` 不合法(大写/下划线/超长)· 声明了 command 但没有 tools · command 与已装意识撞名
- 声明了 tool 槽但缺 tools(或反之)· panel.html 声明了但 slots 没有 "panel"
- settingsHtml 路径不合法/文件不在包里 · settingsHeight 越界(160–800)或没配 settingsHtml 单独声明
+- panel.systemButtons 格式错(不是对象、未知键、值非布尔,或 position:"tab" 时声明——页签形态没有标准头)
- keywords(已废弃字段,旧包兼容保留,新意识别写)有单字词 · kind 写了但不是 "chip"(可省略) · schemaVersion 不是 2
- cindy 详单格式错(未知类目/动作、空数组、有详单但 slots 没有 "cindy")
- agent 详单格式错(有详单但 slots 没有 "agent",或 background 不是 true;只需点击触发时应省略 agent 字段)
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 10cd9d6421..4e22f51aa9 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1826,7 +1826,6 @@ export async function installOrUpdateMarketGhostPackage(
ghostId: string;
version: string;
initiallyEnabled?: boolean;
- nodeAuthorizationWebContents?: WebContents;
},
): Promise<InstalledGhost> {
const mutationOwner = captureGhostMutationOwner();
@@ -3116,6 +3115,30 @@ function broadcastGhostsChanged(ghosts: InstalledGhost[]): void {
if (window.isDestroyed()) return;
window.webContents.send('ghosts:changed', { ghosts: visible });
});
+ // 与 renderer 同一份可见清单喂给观察者(独立窗口 controller reconcile 等);
+ // 观察者异常不拖垮广播本体。
+ if (ghostsChangedObserver) {
+ try {
+ ghostsChangedObserver(visible);
+ } catch (err) {
+ log.warn('ghosts-changed observer failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+}
+
+let ghostsChangedObserver: ((ghosts: InstalledGhost[]) => void) | null = null;
+
+/**
+ * bootstrap 注入:装/卸/启停/换版广播的 main 侧同步观察者(当前消费方:插件面板
+ * 独立窗口 controller 的 reconcile)。保持 cindy-brain 不反向依赖窗口模块
+ * (与 setGhostAgentTurnRunner 同款倒置)。
+ */
+export function setGhostsChangedObserver(
+ observer: ((ghosts: InstalledGhost[]) => void) | null,
+): void {
+ ghostsChangedObserver = observer;
}
/** Plugin 顶部快捷行的 host-owned MRU 快照,多窗口同步。 */
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
new file mode 100644
index 0000000000..f0b0fbb8c3
--- /dev/null
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
@@ -0,0 +1,196 @@
+// GhostPanelWindowsController 状态机单测(纯 DI,不 mock electron):
+// - setDetached(true) 开窗 + 落盘 + 广播;两个 ghost 互不影响
+// - 用户关窗(closed 事件)清标志 = 回停靠;app 退出路径保留标志供重启恢复
+// - open 资格不符(卸载/停用/tab 形态)→ 清条目不开窗
+// - reconcile:卸载删条目并收窗;停用清标志并收窗
+
+import { describe, expect, it, vi } from 'vitest';
+import type { BrowserWindow } from 'electron';
+
+import type { GhostPanelWindowsState } from '../../../shared/ghostPanelWindow.js';
+import {
+ GhostPanelWindowsController,
+ type GhostPanelWindowsControllerDeps,
+} from '../controller.js';
+import type { InstalledGhost, GhostManifest } from '../../../shared/ghost.js';
+
+interface FakeWindow {
+ on: ReturnType<typeof vi.fn>;
+ close: ReturnType<typeof vi.fn>;
+ show: ReturnType<typeof vi.fn>;
+ focus: ReturnType<typeof vi.fn>;
+ restore: ReturnType<typeof vi.fn>;
+ isMinimized: () => boolean;
+ isDestroyed: () => boolean;
+ destroyed: boolean;
+ emitClosed: () => void;
+}
+
+function fakeWindow(): FakeWindow {
+ const listeners = new Map<string, () => void>();
+ const win: FakeWindow = {
+ on: vi.fn((event: string, cb: () => void) => {
+ listeners.set(event, cb);
+ }),
+ close: vi.fn(() => {
+ win.destroyed = true;
+ listeners.get('closed')?.();
+ }),
+ show: vi.fn(),
+ focus: vi.fn(),
+ restore: vi.fn(),
+ isMinimized: () => false,
+ isDestroyed: () => win.destroyed,
+ destroyed: false,
+ emitClosed: () => {
+ win.destroyed = true;
+ listeners.get('closed')?.();
+ },
+ };
+ return win;
+}
+
+function ghost(id: string, opts: { enabled?: boolean; position?: 'left' | 'tab' } = {}): InstalledGhost {
+ const manifest: GhostManifest = {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['panel'],
+ panel: {
+ html: 'panel.html',
+ ...(opts.position !== undefined ? { position: opts.position } : {}),
+ },
+ };
+ return { manifest, dir: `/fake/${id}`, enabled: opts.enabled ?? true };
+}
+
+function makeHarness(detachableIds: Set<string>) {
+ let entries: Record<string, { detached: boolean; lastOpen: boolean }> = {};
+ let quitting = false;
+ const created: Array<{ ghostId: string; win: FakeWindow }> = [];
+ const broadcasts: GhostPanelWindowsState[] = [];
+
+ const deps: GhostPanelWindowsControllerDeps = {
+ settings: {
+ read: () => ({ windows: structuredClone(entries) }),
+ patchEntry: (id, patch) => {
+ const base = entries[id] ?? { detached: false, lastOpen: false };
+ entries[id] = { ...base, ...patch };
+ },
+ removeEntry: (id) => {
+ delete entries[id];
+ },
+ },
+ createWindow: (ghostId) => {
+ const win = fakeWindow();
+ created.push({ ghostId, win });
+ return win as unknown as BrowserWindow;
+ },
+ isGhostDetachable: (id) => detachableIds.has(id),
+ broadcastState: (s) => {
+ broadcasts.push(s);
+ },
+ isQuitting: () => quitting,
+ log: { info: vi.fn(), warn: vi.fn() },
+ };
+ const controller = new GhostPanelWindowsController(deps);
+ return {
+ controller,
+ created,
+ broadcasts,
+ entries: () => entries,
+ setEntries: (next: Record<string, { detached: boolean; lastOpen: boolean }>) => {
+ entries = next;
+ },
+ setQuitting: (v: boolean) => {
+ quitting = v;
+ },
+ };
+}
+
+describe('GhostPanelWindowsController', () => {
+ it('setDetached(true) 开窗 + 落盘 detached/lastOpen + 广播 open:true', () => {
+ const h = makeHarness(new Set(['a']));
+ const state = h.controller.setDetached('a', true);
+ expect(h.created.map((c) => c.ghostId)).toEqual(['a']);
+ expect(h.entries().a).toEqual({ detached: true, lastOpen: true });
+ expect(state.a).toEqual({ detached: true, lastOpen: true, open: true });
+ expect(h.broadcasts.length).toBeGreaterThan(0);
+ });
+
+ it('重复 setDetached(true) 幂等:不再建窗,已开窗 focus', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.setDetached('a', true);
+ h.controller.setDetached('a', true);
+ expect(h.created).toHaveLength(1);
+ expect(h.created[0].win.focus).toHaveBeenCalled();
+ });
+
+ it('两个 ghost 各开各窗、互不影响;setDetached(false) 只收自己的', () => {
+ const h = makeHarness(new Set(['a', 'b']));
+ h.controller.setDetached('a', true);
+ h.controller.setDetached('b', true);
+ expect(h.created.map((c) => c.ghostId)).toEqual(['a', 'b']);
+ const state = h.controller.setDetached('a', false);
+ expect(state.a).toEqual({ detached: false, lastOpen: false, open: false });
+ expect(state.b).toEqual({ detached: true, lastOpen: true, open: true });
+ expect(h.created[0].win.close).toHaveBeenCalled();
+ expect(h.created[1].win.close).not.toHaveBeenCalled();
+ });
+
+ it('用户关窗(closed):清两标志 = 回停靠;app 退出路径保留标志', () => {
+ const h = makeHarness(new Set(['a', 'b']));
+ h.controller.setDetached('a', true);
+ h.created[0].win.emitClosed();
+ expect(h.entries().a).toEqual({ detached: false, lastOpen: false });
+
+ h.controller.setDetached('b', true);
+ h.setQuitting(true);
+ h.created[1].win.emitClosed();
+ expect(h.entries().b).toEqual({ detached: true, lastOpen: true });
+ });
+
+ it('open 资格不符(卸载/停用/tab)→ 清条目不开窗', () => {
+ const h = makeHarness(new Set());
+ h.setEntries({ a: { detached: true, lastOpen: true } });
+ h.controller.open('a');
+ expect(h.created).toHaveLength(0);
+ expect(h.entries().a).toBeUndefined();
+ });
+
+ it('reconcile:卸载收窗删条目;停用收窗清标志;在场且合格的不动', () => {
+ const h = makeHarness(new Set(['gone', 'disabled', 'stays']));
+ h.controller.setDetached('gone', true);
+ h.controller.setDetached('disabled', true);
+ h.controller.setDetached('stays', true);
+
+ h.controller.reconcile([ghost('disabled', { enabled: false }), ghost('stays')]);
+
+ expect(h.created[0].win.close).toHaveBeenCalled(); // gone(清单里消失)
+ expect(h.created[1].win.close).toHaveBeenCalled(); // disabled
+ expect(h.created[2].win.close).not.toHaveBeenCalled();
+ expect(h.entries().gone).toBeUndefined();
+ expect(h.entries().disabled).toEqual({ detached: false, lastOpen: false });
+ expect(h.entries().stays).toEqual({ detached: true, lastOpen: true });
+ });
+
+ it('reconcile:换成 tab 形态视同失去资格', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.setDetached('a', true);
+ h.controller.reconcile([ghost('a', { position: 'tab' })]);
+ expect(h.created[0].win.close).toHaveBeenCalled();
+ expect(h.entries().a).toEqual({ detached: false, lastOpen: false });
+ });
+
+ it('getState:无条目 ghost 不出现;开窗态 open:true', () => {
+ const h = makeHarness(new Set(['a']));
+ expect(h.controller.getState()).toEqual({});
+ h.controller.setDetached('a', true);
+ expect(h.controller.getState()).toEqual({
+ a: { detached: true, lastOpen: true, open: true },
+ });
+ });
+});
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts
new file mode 100644
index 0000000000..df54f0b5fb
--- /dev/null
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts
@@ -0,0 +1,34 @@
+// normalizeGhostPanelWindowsSettings:坏数据 fail-closed 清洗。
+import { describe, expect, it } from 'vitest';
+
+import { normalizeGhostPanelWindowsSettings } from '../settings-store.js';
+
+describe('normalizeGhostPanelWindowsSettings', () => {
+ it('合法条目原样保留', () => {
+ expect(
+ normalizeGhostPanelWindowsSettings({
+ windows: { 'stock-2400-tracker': { detached: true, lastOpen: false } },
+ }),
+ ).toEqual({ windows: { 'stock-2400-tracker': { detached: true, lastOpen: false } } });
+ });
+
+ it('非对象 / 缺 windows / windows 非对象 → 空表', () => {
+ expect(normalizeGhostPanelWindowsSettings(null)).toEqual({ windows: {} });
+ expect(normalizeGhostPanelWindowsSettings('x')).toEqual({ windows: {} });
+ expect(normalizeGhostPanelWindowsSettings({})).toEqual({ windows: {} });
+ expect(normalizeGhostPanelWindowsSettings({ windows: 42 })).toEqual({ windows: {} });
+ });
+
+ it('非法 ghostId / 非布尔字段 / 非对象条目:整条丢弃,不影响同表其它条目', () => {
+ expect(
+ normalizeGhostPanelWindowsSettings({
+ windows: {
+ 'BAD ID': { detached: true, lastOpen: true },
+ 'cindy-art': { detached: 'yes', lastOpen: true },
+ 'no-fields': null,
+ good: { detached: false, lastOpen: true },
+ },
+ }),
+ ).toEqual({ windows: { good: { detached: false, lastOpen: true } } });
+ });
+});
diff --git a/apps/desktop/src/main/ghost-panel-window/controller.ts b/apps/desktop/src/main/ghost-panel-window/controller.ts
new file mode 100644
index 0000000000..8b6cf0458e
--- /dev/null
+++ b/apps/desktop/src/main/ghost-panel-window/controller.ts
@@ -0,0 +1,182 @@
+/**
+ * GhostPanelWindowsController —— 插件停靠面板独立窗口的状态机(main 侧单例,
+ * 依赖注入可测)。蓝本是 RsbWindowController,按 ghostId 多实例并做了减法:
+ * 面板体只吃 manifest(广播全窗口可达),无需 ready 握手 / 上下文中继 / 命令队列。
+ *
+ * 每个 ghostId 的三态(与 RSB 同构):
+ * A. detached=false —— 面板停靠在主窗布局树里
+ * C. detached=true, 窗口打开 —— 面板活在独立窗口
+ * (v1 关窗即回停靠,不保留"偏好开着但窗口收起"的 B 态;lastOpen 仅在
+ * app 退出路径保留,供重启恢复。)
+ *
+ * 职责:
+ * - 每 ghost 窗口生命周期(重复 open = focus;closed 区分用户关窗 vs app 退出)
+ * - 偏好 / lastOpen 落盘(settings-store),状态变化广播所有窗口
+ * - reconcile:插件卸载/停用/换形态时收窗(卸载删条目;停用清标志,
+ * 避免"面板既不停靠也开不了窗"的死角)
+ */
+
+import type { BrowserWindow } from 'electron';
+
+import type {
+ GhostPanelWindowEntryState,
+ GhostPanelWindowsState,
+} from '../../shared/ghostPanelWindow.js';
+import type { InstalledGhost } from '../../shared/ghost.js';
+import type { GhostPanelWindowsSettings } from './settings-store.js';
+
+interface ControllerLogger {
+ info(message: string, ...args: unknown[]): void;
+ warn(message: string, ...args: unknown[]): void;
+}
+
+export interface GhostPanelWindowsControllerDeps {
+ settings: {
+ read(): GhostPanelWindowsSettings;
+ patchEntry(ghostId: string, patch: Partial<{ detached: boolean; lastOpen: boolean }>): void;
+ removeEntry(ghostId: string): void;
+ };
+ /** 创建子窗口(不负责挂 closed 钩子,controller 自己挂)。 */
+ createWindow: (ghostId: string) => BrowserWindow;
+ /**
+ * 该插件当前是否具备"可抽离的停靠面板"资格:已装、启用、声明了 panel 且
+ * position 不是 'tab'。open/setDetached 前置校验与 reconcile 共用同一判据。
+ */
+ isGhostDetachable: (ghostId: string) => boolean;
+ /** 状态变化广播(所有窗口)。bootstrap 注入 getAllWindows 遍历实现。 */
+ broadcastState: (state: GhostPanelWindowsState) => void;
+ isQuitting: () => boolean;
+ log: ControllerLogger;
+}
+
+export class GhostPanelWindowsController {
+ private readonly windows = new Map<string, BrowserWindow>();
+ /** close() 到 closed 事件之间窗口仍未 destroyed,不能继续当活窗。 */
+ private readonly closingIds = new Set<string>();
+
+ constructor(private readonly deps: GhostPanelWindowsControllerDeps) {}
+
+ getState(): GhostPanelWindowsState {
+ const out: GhostPanelWindowsState = {};
+ const { windows } = this.deps.settings.read();
+ for (const [id, entry] of Object.entries(windows)) {
+ out[id] = this.entryState(id, entry);
+ }
+ // 运行时开着但条目被清了的窗口(理论不存在,防御性合入)
+ for (const id of this.windows.keys()) {
+ if (!(id in out)) out[id] = this.entryState(id, { detached: false, lastOpen: false });
+ }
+ return out;
+ }
+
+ /** 幂等打开:已开则 show + focus;资格不符则清条目(防陈年状态复活废窗)。 */
+ open(ghostId: string): void {
+ const existing = this.windows.get(ghostId);
+ if (existing && !existing.isDestroyed()) {
+ if (this.closingIds.has(ghostId)) return;
+ if (existing.isMinimized()) existing.restore();
+ existing.show();
+ existing.focus();
+ return;
+ }
+ if (!this.deps.isGhostDetachable(ghostId)) {
+ this.deps.log.warn('ghost not detachable, pruning window entry', { ghostId });
+ this.deps.settings.removeEntry(ghostId);
+ this.broadcast();
+ return;
+ }
+ const win = this.deps.createWindow(ghostId);
+ this.windows.set(ghostId, win);
+ this.closingIds.delete(ghostId);
+ win.on('closed', () => this.onClosed(ghostId));
+ this.deps.settings.patchEntry(ghostId, { detached: true, lastOpen: true });
+ this.broadcast();
+ this.deps.log.info('ghost panel window opened', { ghostId });
+ }
+
+ /** 写偏好;true 附带开窗,false 附带关窗(= 回停靠)。返回新 state 供 invoke 直接回。 */
+ setDetached(ghostId: string, next: boolean): GhostPanelWindowsState {
+ if (next) {
+ this.open(ghostId); // open 内部落 detached/lastOpen 并广播
+ } else {
+ this.deps.settings.patchEntry(ghostId, { detached: false, lastOpen: false });
+ const win = this.windows.get(ghostId);
+ if (win && !win.isDestroyed()) {
+ // onClosed 会广播,这里不重复
+ this.closingIds.add(ghostId);
+ win.close();
+ } else {
+ this.broadcast();
+ }
+ }
+ // open/close 的幂等分支可能没广播(如重复 setDetached(true)),兜底广播必达。
+ this.broadcast();
+ return this.getState();
+ }
+
+ /**
+ * 与"当前已装清单"对齐(broadcastGhostsChanged 观察者):
+ * 失去抽离资格(卸载/停用/换 tab 形态)→ 收窗;卸载删条目,其余清标志
+ * ——面板回停靠(或随卸载消失),不留"够不着"的死角。
+ */
+ reconcile(ghosts: InstalledGhost[]): void {
+ const byId = new Map(ghosts.map((g) => [g.manifest.id, g]));
+ const knownIds = new Set([
+ ...Object.keys(this.deps.settings.read().windows),
+ ...this.windows.keys(),
+ ]);
+ let changed = false;
+ for (const id of knownIds) {
+ const ghost = byId.get(id);
+ const detachable =
+ ghost !== undefined &&
+ ghost.enabled !== false &&
+ ghost.manifest.panel !== undefined &&
+ ghost.manifest.panel.position !== 'tab';
+ if (detachable) continue;
+ const win = this.windows.get(id);
+ if (win && !win.isDestroyed() && !this.closingIds.has(id)) {
+ this.closingIds.add(id);
+ win.close();
+ }
+ if (ghost === undefined) {
+ this.deps.settings.removeEntry(id);
+ } else {
+ this.deps.settings.patchEntry(id, { detached: false, lastOpen: false });
+ }
+ changed = true;
+ this.deps.log.info('ghost panel window reconciled away', { ghostId: id });
+ }
+ if (changed) this.broadcast();
+ }
+
+ private entryState(
+ ghostId: string,
+ entry: { detached: boolean; lastOpen: boolean },
+ ): GhostPanelWindowEntryState {
+ return { detached: entry.detached, lastOpen: entry.lastOpen, open: this.isOpen(ghostId) };
+ }
+
+ private isOpen(ghostId: string): boolean {
+ const win = this.windows.get(ghostId);
+ return win !== undefined && !this.closingIds.has(ghostId) && !win.isDestroyed();
+ }
+
+ private onClosed(ghostId: string): void {
+ this.windows.delete(ghostId);
+ this.closingIds.delete(ghostId);
+ // app 退出路径:保留 detached/lastOpen 供下次启动恢复,也不广播(窗口都在销毁)
+ if (this.deps.isQuitting()) return;
+ // reconcile 的卸载路径可能已删条目(真实 close 是异步的,closed 晚到)——
+ // 不要凭空再造一条陈年条目。
+ if (ghostId in this.deps.settings.read().windows) {
+ this.deps.settings.patchEntry(ghostId, { detached: false, lastOpen: false });
+ }
+ this.broadcast();
+ this.deps.log.info('ghost panel window closed (re-docked)', { ghostId });
+ }
+
+ private broadcast(): void {
+ this.deps.broadcastState(this.getState());
+ }
+}
diff --git a/apps/desktop/src/main/ghost-panel-window/ipc.ts b/apps/desktop/src/main/ghost-panel-window/ipc.ts
new file mode 100644
index 0000000000..329315f83f
--- /dev/null
+++ b/apps/desktop/src/main/ghost-panel-window/ipc.ts
@@ -0,0 +1,63 @@
+/**
+ * registerGhostPanelWindowIpc —— 插件面板独立窗口的 IPC 注册。
+ *
+ * 全部委托给 GhostPanelWindowsController,这里只做:
+ * - sender 归属校验:invoke 一律 assertTrustedAppRendererEvent(主窗/副窗/
+ * 面板子窗都是 markAppContentWindow 过的同源受信 renderer;插件 webview
+ * 没有 preload 根本到不了这些通道,这层闸防的是越权 frame);
+ * - payload 运行时校验(throwIpcError INVALID_PARAMS);
+ * - 首帧 sendSync 通道:不受信 sender 回空对象,绝不 throw 进 sendSync。
+ */
+
+import { ipcMain } from 'electron';
+
+import { MAKER_INVOKE } from '../maker-ipc/channels.js';
+import { createLogger } from '../logger.js';
+import { assertTrustedAppRendererEvent, isTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { isValidGhostId } from '../../shared/ghost.js';
+import type { GhostPanelWindowsController } from './controller.js';
+
+const log = createLogger('ghost-panel-window-ipc');
+
+/** 首帧同步读通道(与 layout:get / ghosts:list 同模式,见 channels.ts 注释)。 */
+export const GHOST_PANEL_WINDOW_GET_STATE_SYNC = 'ghost-panel-window:get-state-sync';
+
+export function registerGhostPanelWindowIpc(controller: GhostPanelWindowsController): void {
+ ipcMain.handle(MAKER_INVOKE.GHOST_PANEL_WINDOW_GET_STATE, (event) => {
+ assertTrustedAppRendererEvent(event);
+ return controller.getState();
+ });
+
+ ipcMain.handle(MAKER_INVOKE.GHOST_PANEL_WINDOW_OPEN, (event, ghostId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (!isValidGhostId(ghostId)) {
+ throwIpcError('INVALID_PARAMS', 'ghostId must be a valid ghost id');
+ }
+ controller.open(ghostId);
+ });
+
+ ipcMain.handle(
+ MAKER_INVOKE.GHOST_PANEL_WINDOW_SET_DETACHED,
+ (event, ghostId: unknown, detached: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (!isValidGhostId(ghostId)) {
+ throwIpcError('INVALID_PARAMS', 'ghostId must be a valid ghost id');
+ }
+ if (typeof detached !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'detached required (boolean)');
+ }
+ return controller.setDetached(ghostId, detached);
+ },
+ );
+
+ ipcMain.on(GHOST_PANEL_WINDOW_GET_STATE_SYNC, (event) => {
+ // sendSync 不能 throw(会把异常序列化回 sendSync 调用点);不受信回空 map。
+ if (!isTrustedAppRendererEvent(event)) {
+ log.warn('get-state-sync from untrusted sender, returning empty state');
+ event.returnValue = {};
+ return;
+ }
+ event.returnValue = controller.getState();
+ });
+}
diff --git a/apps/desktop/src/main/ghost-panel-window/settings-store.ts b/apps/desktop/src/main/ghost-panel-window/settings-store.ts
new file mode 100644
index 0000000000..5aca781ed1
--- /dev/null
+++ b/apps/desktop/src/main/ghost-panel-window/settings-store.ts
@@ -0,0 +1,83 @@
+/**
+ * ghost-panel-window settings-store —— 「插件面板在独立窗口中显示」的持久化。
+ *
+ * File: <userData>/ghost-panel-windows-settings.json
+ *
+ * 形如 { windows: { <ghostId>: { detached, lastOpen } } }。语义对照
+ * right-sidebar-window/settings-store.ts(同一 override 模型、同只由 main 的
+ * controller 写),差异是按 ghostId 多条:每个插件面板各自记偏好与恢复状态。
+ * - detached: **偏好**。用户点了该面板的「独立窗口」按钮;
+ * - lastOpen: **状态**。退出时该窗口是否开着,供下次启动恢复。
+ * 没有条目 = 从未抽离(等价两个 false)。
+ */
+
+import { app } from 'electron';
+import path from 'node:path';
+
+import { isValidGhostId } from '../../shared/ghost.js';
+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
+
+const log = desktopMakerLogger.child('ghost-panel-window-settings-store');
+
+export interface GhostPanelWindowEntrySettings {
+ detached: boolean;
+ lastOpen: boolean;
+}
+
+export interface GhostPanelWindowsSettings {
+ windows: Record<string, GhostPanelWindowEntrySettings>;
+}
+
+const DEFAULTS: GhostPanelWindowsSettings = { windows: {} };
+
+function settingsFilePath(): string {
+ return path.join(app.getPath('userData'), 'ghost-panel-windows-settings.json');
+}
+
+/** 逐条清洗:非法 ghostId / 非布尔字段整条丢弃(fail closed,坏数据不进状态机)。 */
+export function normalizeGhostPanelWindowsSettings(raw: unknown): GhostPanelWindowsSettings {
+ if (!raw || typeof raw !== 'object') return { windows: {} };
+ const rawWindows = (raw as Record<string, unknown>).windows;
+ if (!rawWindows || typeof rawWindows !== 'object') return { windows: {} };
+ const windows: Record<string, GhostPanelWindowEntrySettings> = {};
+ for (const [id, entry] of Object.entries(rawWindows as Record<string, unknown>)) {
+ if (!isValidGhostId(id)) continue;
+ if (!entry || typeof entry !== 'object') continue;
+ const e = entry as Record<string, unknown>;
+ if (typeof e.detached !== 'boolean' || typeof e.lastOpen !== 'boolean') continue;
+ windows[id] = { detached: e.detached, lastOpen: e.lastOpen };
+ }
+ return { windows };
+}
+
+const store = createOverrideSettingsFile<GhostPanelWindowsSettings>({
+ filePath: settingsFilePath,
+ defaults: DEFAULTS,
+ normalize: normalizeGhostPanelWindowsSettings,
+ log,
+ label: 'ghost-panel-windows',
+});
+
+export function readGhostPanelWindowsSettings(): GhostPanelWindowsSettings {
+ return store.read();
+}
+
+/** 单条 patch:writePatch 是浅合并,windows map 必须整体读改写。 */
+export function patchGhostPanelWindowEntry(
+ ghostId: string,
+ patch: Partial<GhostPanelWindowEntrySettings>,
+): void {
+ const current = store.read().windows;
+ const entry = current[ghostId] ?? { detached: false, lastOpen: false };
+ store.writePatch({ windows: { ...current, [ghostId]: { ...entry, ...patch } } });
+}
+
+/** 删条目(卸载清理):不存在时为 no-op。 */
+export function removeGhostPanelWindowEntry(ghostId: string): void {
+ const current = store.read().windows;
+ if (!(ghostId in current)) return;
+ const next = { ...current };
+ delete next[ghostId];
+ store.writePatch({ windows: next });
+}
diff --git a/apps/desktop/src/main/ghost-panel-window/window.ts b/apps/desktop/src/main/ghost-panel-window/window.ts
new file mode 100644
index 0000000000..0b55e49202
--- /dev/null
+++ b/apps/desktop/src/main/ghost-panel-window/window.ts
@@ -0,0 +1,101 @@
+/**
+ * createGhostPanelWindow —— 插件停靠面板独立窗口的 BrowserWindow 工厂。
+ *
+ * 蓝本是 right-sidebar-window/window.ts,差异:
+ * - 按 ghostId 多实例:窗口位置记忆每插件一份
+ * (ghost-panel-window-state-<id>.json,id 字符集 [a-z0-9-] 文件名安全);
+ * - webPreferences 按 electron-security-and-process-boundaries §3 显式带全量
+ * 安全项(该规则晚于主窗/RSB 窗,新窗口必须逐项写明,不吃默认值);
+ * - `webviewTag: true`:面板体就是 <webview>(cindy-ghost:// 分区)。附加闸/
+ * 硬化器(webview-security.ts)对所有窗口全局生效,这里零额外授权;
+ * - 启动参数 `?ghostPanelWindow=<id>` + hash `/ghost-panel-window`:renderer
+ * 单入口,router 据此只挂 GhostPanelWindowLayout。
+ */
+
+import { BrowserWindow, app, nativeTheme } from 'electron';
+import path from 'node:path';
+import windowStateKeeper from 'electron-window-state';
+
+import { createLogger } from '../logger.js';
+import { markAppContentWindow } from '../windowFocusClassifier.js';
+import { readWindowBehaviorSettings } from '../window-behavior-settings-store.js';
+import { installExternalLinkGuards } from '../secondary-windows.js';
+import { installSelectionContextMenu } from '../selection-context-menu.js';
+
+const log = createLogger('ghost-panel-window');
+
+export function createGhostPanelWindow(ghostId: string, title: string): BrowserWindow {
+ const platformOptions =
+ process.platform === 'darwin'
+ ? { titleBarStyle: 'hidden' as const, trafficLightPosition: { x: 12, y: 16 } }
+ : { frame: false };
+ const bgColor = nativeTheme.shouldUseDarkColors ? '#1f1f1e' : '#f8f8f6';
+
+ // 与主窗 / 副窗保持 acceptFirstMouse 一致(见 secondary-windows.ts 同款注释)。
+ const swallowActivationClick = readWindowBehaviorSettings().swallowActivationClick;
+
+ const windowState = windowStateKeeper({
+ defaultWidth: 480,
+ defaultHeight: 720,
+ file: `ghost-panel-window-state-${ghostId}.json`,
+ });
+
+ const win = new BrowserWindow({
+ x: windowState.x,
+ y: windowState.y,
+ width: windowState.width,
+ height: windowState.height,
+ minWidth: 320,
+ minHeight: 400,
+ title,
+ icon: app.isPackaged
+ ? path.join(process.resourcesPath, 'icon.png')
+ : path.join(__dirname, '../../resources/icon.png'),
+ autoHideMenuBar: true,
+ show: false,
+ backgroundColor: bgColor,
+ acceptFirstMouse: !swallowActivationClick,
+ ...platformOptions,
+ webPreferences: {
+ preload: path.join(__dirname, 'preload.js'),
+ spellcheck: false,
+ webviewTag: true,
+ // 安全规则 §3 全量显式项(新建窗口不吃默认值,逐项写明):
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ },
+ });
+ markAppContentWindow(win);
+ installSelectionContextMenu(win);
+ windowState.manage(win);
+
+ installExternalLinkGuards(win);
+
+ win.once('ready-to-show', () => {
+ if (!win.isDestroyed()) win.show();
+ });
+
+ const hash = '/ghost-panel-window';
+ if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
+ const url = new URL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
+ url.searchParams.set('ghostPanelWindow', ghostId);
+ url.hash = hash;
+ void win.loadURL(url.toString());
+ } else {
+ void win.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`), {
+ query: { ghostPanelWindow: ghostId },
+ hash,
+ });
+ }
+
+ log.info('ghost panel window created', { ghostId });
+ return win;
+}
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 3072d47d5c..8c680a6ab9 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -538,6 +538,18 @@ export const MAKER_INVOKE = {
RSB_WINDOW_GET_CONTEXT: 'maker:rsb-window:get-context',
RSB_WINDOW_READY: 'maker:rsb-window:ready',
RSB_WINDOW_SEND_COMMAND: 'maker:rsb-window:send-command',
+ /**
+ * 插件停靠面板独立窗口(ghost panel window)——每 ghostId 一扇窗。
+ * 状态机见 main/ghost-panel-window/controller.ts。
+ * - GET_STATE: 拉全量 { <ghostId>: { detached, lastOpen, open } }
+ * - OPEN(ghostId): 幂等开(已开则 focus);资格不符清条目
+ * - SET_DETACHED(ghostId, boolean): true 开窗抽离,false 关窗回停靠;返回新全量 state
+ * 首帧同步读走裸 sendSync 通道 'ghost-panel-window:get-state-sync'
+ * (与 layout:get / ghosts:list 同模式,规则 7 首帧无跳变)。
+ */
+ GHOST_PANEL_WINDOW_GET_STATE: 'maker:ghost-panel-window:get-state',
+ GHOST_PANEL_WINDOW_OPEN: 'maker:ghost-panel-window:open',
+ GHOST_PANEL_WINDOW_SET_DETACHED: 'maker:ghost-panel-window:set-detached',
/**
* 会话内 /goal 自主续跑(goal-host)——
* - GOAL_SET: 设/替换目标并立刻发首轮。入参 { sessionId, objective, agentKind, budgetTokens? }(budgetTokens 留空=不设预算)
@@ -696,6 +708,11 @@ export const MAKER_PUSH = {
RSB_WINDOW_CONTEXT_CHANGED: 'maker:rsb-window:context-changed',
/** main → 子窗口命令(如 open-terminal),只发子窗口。payload = RsbWindowCommand。 */
RSB_WINDOW_COMMAND: 'maker:rsb-window:command',
+ /**
+ * 插件面板独立窗口状态广播(全量 GhostPanelWindowsState)——发所有窗口
+ * (主窗布局过滤 + 各子窗口自身都消费)。
+ */
+ GHOST_PANEL_WINDOW_STATE_CHANGED: 'maker:ghost-panel-window:state-changed',
} as const;
/**
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 0edd218939..912d56bedd 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -61,7 +61,6 @@ export function registerPluginMarketIpc(): void {
return invokePluginMarket(() =>
service().install(requireString(pluginId, 'pluginId'), {
allowPermissionExpansion,
- nodeAuthorizationWebContents: event.sender,
}),
);
},
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index ecf1658cb4..b2c7a49b41 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -232,7 +232,6 @@ export class PluginMarketService {
pluginId: string,
options?: {
allowPermissionExpansion?: boolean;
- nodeAuthorizationWebContents?: WebContents;
},
): Promise<{ ghost: InstalledGhost }> {
if (!isValidPluginResourceId(pluginId)) {
@@ -261,9 +260,6 @@ export class PluginMarketService {
{
allowPermissionExpansion:
options?.allowPermissionExpansion === true,
- ...(options?.nodeAuthorizationWebContents
- ? { nodeAuthorizationWebContents: options.nodeAuthorizationWebContents }
- : {}),
},
owner,
ledger,
@@ -336,7 +332,6 @@ export class PluginMarketService {
options: {
allowPermissionExpansion?: boolean;
initiallyEnabled?: boolean;
- nodeAuthorizationWebContents?: WebContents;
} = {},
owner = captureMarketOwner(),
ledger = this.ledgerForOwner(owner),
@@ -388,9 +383,6 @@ export class PluginMarketService {
ghostId: plugin.ghostId,
version: plugin.currentRelease.version,
initiallyEnabled: options.initiallyEnabled === true,
- ...(options.nodeAuthorizationWebContents
- ? { nodeAuthorizationWebContents: options.nodeAuthorizationWebContents }
- : {}),
});
// Once the package directory is committed, finish provenance against the
// owner captured at operation start even if the active session changes.
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 53b27b9db1..7c75516fb3 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -253,6 +253,8 @@ const fanOutOrcaWorkerChanged = createIpcFanOut('maker:orca:worker-changed');
const fanOutRsbWindowStateChanged = createIpcFanOut('maker:rsb-window:state-changed');
const fanOutRsbWindowContextChanged = createIpcFanOut('maker:rsb-window:context-changed');
const fanOutRsbWindowCommand = createIpcFanOut('maker:rsb-window:command');
+// 插件停靠面板独立窗口(ghost panel window)状态推送
+const fanOutGhostPanelWindowStateChanged = createIpcFanOut('maker:ghost-panel-window:state-changed');
const fanOutBinaryDownloadProgress = createIpcFanOut('binary-download-progress');
// Settings →「电脑使用」cua-driver 更新的下载进度(main 侧采样后广播)
const fanOutComputerDriverUpdateProgress = createIpcFanOut('computer-driver-update-progress');
@@ -1089,6 +1091,30 @@ contextBridge.exposeInMainWorld('electronAPI', {
onCommand: fanOutRsbWindowCommand,
},
+ // ── 插件停靠面板独立窗口(ghost panel window)──────────────────────────
+ // 每 ghostId 一扇窗。状态机在 main(ghost-panel-window/controller.ts),
+ // renderer 只 invoke + 订阅广播;首帧走 sendSync(规则 7 无跳变)。
+ ghostPanelWindow: {
+ /** 首帧同步读全量状态(ghostId → { detached, lastOpen, open })。 */
+ getStateSync: (): Record<string, { detached: boolean; lastOpen: boolean; open: boolean }> =>
+ ipcRenderer.sendSync('ghost-panel-window:get-state-sync') as Record<
+ string,
+ { detached: boolean; lastOpen: boolean; open: boolean }
+ >,
+ getState: (): Promise<Record<string, { detached: boolean; lastOpen: boolean; open: boolean }>> =>
+ ipcRenderer.invoke('maker:ghost-panel-window:get-state'),
+ /** 幂等:已开则 show + focus。 */
+ open: (ghostId: string): Promise<void> =>
+ ipcRenderer.invoke('maker:ghost-panel-window:open', ghostId),
+ /** 写偏好;true 开窗抽离,false 关窗回停靠。返回新全量 state。 */
+ setDetached: (
+ ghostId: string,
+ detached: boolean,
+ ): Promise<Record<string, { detached: boolean; lastOpen: boolean; open: boolean }>> =>
+ ipcRenderer.invoke('maker:ghost-panel-window:set-detached', ghostId, detached),
+ onStateChanged: fanOutGhostPanelWindowStateChanged,
+ },
+
agentIsland: {
setVisibleSession: (sessionId: string | string[] | null): Promise<{ ok: true }> =>
ipcRenderer.invoke(AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL, sessionId),
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index a1229e9984..0c5d5a8234 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -18,6 +18,7 @@ import { LoginFirstLaunchLightGateBridge } from '@/components/login/LoginFirstLa
import { LoginBrandStage } from '@/components/login/LoginBrandStage';
import { isSecondaryWindow } from '@/lib/secondaryWindow';
import { isSidebarWindow } from '@/lib/sidebarWindow';
+import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';
import { ToastContainer } from '@/components/ui/toast';
import { LegacyMigrationDialog } from '@/components/auth/LegacyMigrationDialog';
import { Tooltip } from '@/components/ui/tooltip';
@@ -277,8 +278,8 @@ export function App() {
{/* 副窗口(「在新窗口打开」)/ 右侧栏子窗口跳过 splash:env/热更检查
由主窗启动时完成,附属窗 EnvCheckProvider 初始即 'passed',
不需要也不应再走 splash 流程。 */}
- {!isSecondaryWindow() && !isSidebarWindow() && <LoginBrandStage />}
- {!isSecondaryWindow() && !isSidebarWindow() && <SplashScreen />}
+ {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && <LoginBrandStage />}
+ {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && <SplashScreen />}
<EnvCheckGuard>
<MakerBootstrap />
<ProjectAutomationNotifyBridge />
@@ -288,7 +289,7 @@ export function App() {
<FindInPageBar />
<ToastContainer />
{/* 首登轻量数据迁移弹窗:只挂主窗(副窗/侧栏窗不重复弹) */}
- {!isSecondaryWindow() && !isSidebarWindow() && <LegacyMigrationDialog />}
+ {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && <LegacyMigrationDialog />}
</Tooltip.Provider>
</PrRefsProvider>
</WorktreeProvider>
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx
index abef7a302e..f5a38ede40 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx
@@ -55,7 +55,7 @@ describe('GhostPermissionList(装入全量清单)', () => {
expect(screen.getByText(/perm\.tool:.*gen_image/)).toBeTruthy();
expect(screen.getByText('根据描述出图')).toBeTruthy(); // 作者自由文本如实展示
expect(screen.getByText(/perm\.command:.*画图/)).toBeTruthy();
- expect(screen.getByText(/perm\.panelRight:.*画廊/)).toBeTruthy();
+ expect(screen.getByText(/perm\.panelLeft:.*画廊/)).toBeTruthy();
expect(screen.getByText('settings.ghosts.perm.code')).toBeTruthy();
expect(screen.getByText('settings.ghosts.perm.codeDetail')).toBeTruthy(); // 主机固定说明走 i18n
});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx
index 0b742a5701..99fd1a5f85 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostTabPlugins.test.tsx
@@ -98,7 +98,7 @@ describe('syncGhostPanelRegistrations · 按 position 分派两个注册表', ()
it("tab 型只进 Tab 注册表;停靠型只进顶层面板注册表", () => {
syncGhostPanelRegistrations([
ghost('tabbed'),
- ghost('docked', { html: 'panel.html', position: 'right' }),
+ ghost('docked', { html: 'panel.html', position: 'left' }),
]);
expect(getTabKind('ghost:tabbed')).not.toBeNull();
expect(hasPanelKind('ghost:tabbed')).toBe(false);
@@ -106,8 +106,8 @@ describe('syncGhostPanelRegistrations · 按 position 分派两个注册表', ()
expect(getTabKind('ghost:docked')).toBeNull();
});
- it('换版把 position 从 right 改成 tab → 顶层注销、页签注册(反向亦然)', () => {
- syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'right' })]);
+ it('换版把 position 从 left 改成 tab → 顶层注销、页签注册(反向亦然)', () => {
+ syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'left' })]);
expect(hasPanelKind('ghost:m')).toBe(true);
syncGhostPanelRegistrations([ghost('m', { html: 'panel.html', position: 'tab' })]);
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
index 90f2bf6afd..e8add1e264 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
@@ -179,10 +179,10 @@ describe('installFlow · tab 型插件「立即开启并打开页签」', () =>
expect(openGhostTab).not.toHaveBeenCalled();
});
- it('停靠形态(position: right)勾选只带电,不打开页签', async () => {
+ it('停靠形态(position: left)勾选只带电,不打开页签', async () => {
setupWindow({
...tabManifest,
- panel: { html: 'panel.html', position: 'right' as const },
+ panel: { html: 'panel.html', position: 'left' as const },
});
const openGhostTab = vi.fn(async () => undefined);
const { deps: d, confirmWithCheckbox } = tabDeps({ sessionId: 's1', openGhostTab });
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
index 18b10a7317..c1895d5ab4 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState, type ReactNode } from 'react';
import { ghostPanelKind, type GhostManifest, type InstalledGhost } from '../../shared/ghost';
+import { usePanelMaximize } from '../layout/panelMaximize';
import { usePanelWidth } from '../layout/paneWidths';
import { PanelChrome } from '../panels/PanelChrome';
import { registerPanelKind, unregisterPanelKind, type PanelComponentProps } from '../panels/registry';
@@ -36,6 +37,17 @@ function GhostPanel({
const kind = ghostPanelKind(manifest.id);
// 宽度由引擎下发(fraction × 可用宽,缝把手可拖);兜底用清单 minWidth。
const width = usePanelWidth(kind) ?? manifest.panel?.minWidth ?? 300;
+ // 撑满态(引擎视图态):固定宽让位给 flex-1,树上的 fraction 账本不动。
+ const maximize = usePanelMaximize();
+ const isMaximized = maximize?.maximizedKind === kind;
+ // 标准头系统按钮:身份卡可逐个关闭(panel.systemButtons.<键>:false);
+ // 关闭 = 不把对应入参交给标准头,按钮不长出(标题条本体恒在)。
+ const maximizeEnabled = manifest.panel?.systemButtons?.maximize !== false;
+ const detachEnabled = manifest.panel?.systemButtons?.detach !== false;
+ // 换版更新把按钮关掉时,若面板正撑满,自动还原 —— 否则按钮没了、态出不去。
+ useEffect(() => {
+ if (!maximizeEnabled && isMaximized) maximize?.toggle(kind);
+ }, [maximizeEnabled, isMaximized, maximize, kind]);
// 沙箱崩了 → 面板原地进入错误接管态。
const runtimeState = useGhostRuntimeState(manifest.id);
const broken = runtimeState === 'crashed' || runtimeState === 'fused';
@@ -43,10 +55,22 @@ function GhostPanel({
<section
data-panel-drag-root={kind}
// 侧边分割线由布局引擎统一绘制(LayoutRoot layout-divider),面板不自画。
- className="flex h-full shrink-0 flex-col overflow-hidden bg-[var(--panel-bg)]"
- style={{ width }}
+ className={
+ isMaximized
+ ? 'flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]'
+ : 'flex h-full shrink-0 flex-col overflow-hidden bg-[var(--panel-bg)]'
+ }
+ style={isMaximized ? undefined : { width }}
>
- <PanelChrome title={manifest.panel?.title ?? manifest.name} />
+ <PanelChrome
+ title={manifest.panel?.title ?? manifest.name}
+ panelKind={maximizeEnabled ? kind : undefined}
+ onDetach={
+ detachEnabled
+ ? () => void window.electronAPI?.ghostPanelWindow?.setDetached(manifest.id, true)
+ : undefined
+ }
+ />
{broken ? (
<GhostPanelError manifest={manifest} state={runtimeState} />
) : (
diff --git a/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx
new file mode 100644
index 0000000000..2e96bec6b6
--- /dev/null
+++ b/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx
@@ -0,0 +1,125 @@
+/**
+ * GhostPanelWindowLayout —— 插件停靠面板独立窗口的根组件(路由 `/ghost-panel-window`)。
+ *
+ * 窗口由 main/ghost-panel-window/window.ts 打开(`?ghostPanelWindow=<id>`),本组件:
+ * - 画 46px 自绘 chrome(蓝本 SidebarWindowLayout):整条 drag region;mac 左端
+ * 红绿灯让位、win 右端 WindowControls(close 按 sender 解析 = 只关本窗);
+ * 右端「合并回主窗口」按钮 → setDetached(id, false)(main 落盘 + 关本窗,
+ * 主窗收广播后面板原位回停靠)。
+ * - 面板体零改动复用 GhostChipPanelBody(webview 供片/主题/崩溃接管全同款;
+ * 附加闸只认分区/地址,与宿主窗口无关);崩溃/熔断走 GhostPanelError。
+ * - manifest 经 useInstalledGhosts 自查(ghosts:changed 广播发所有窗口);
+ * 插件被卸载/停用时 main 的 reconcile 会直接收窗,这里只需短暂占位。
+ * - 挂 GhostMediaLightboxHost:面板 /preview/ 点图事件推给本窗口(embedder),
+ * 不挂的话子窗里"点开看大图"没有承接端。无 sessionId,「发送到对话」隐藏。
+ * - ⌘W / Ctrl+W:本窗口没有 tab 语义,直接关窗(= 合并回主窗的同一条 main 收口)。
+ */
+
+import { useTranslation } from 'react-i18next';
+import { PictureInPicture2, Puzzle } from 'lucide-react';
+
+import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';
+import { GhostChipPanelBody, GhostPanelError } from '@/cindy-brain/ghostPanelBody';
+import { useGhostRuntimeState } from '@/cindy-brain/runtimeStates';
+import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
+import { WindowControls } from '@/components/title-bar/WindowControls';
+import { useAppShortcut } from '@/hooks/useAppShortcut';
+import { useCloseShortcutShellOwner } from '@/hooks/useCloseWindowShortcut';
+import { getGhostPanelWindowGhostId } from '@/lib/ghostPanelWindow';
+import { createLogger } from '@/lib/logger';
+import type { GhostManifest } from '../../../shared/ghost';
+
+const log = createLogger('GhostPanelWindowLayout');
+
+/** 面板体 + 崩溃接管(与停靠形态 GhostPanel 同一分支逻辑,不含标准头)。 */
+function PanelBody({ manifest }: { manifest: GhostManifest }) {
+ const runtimeState = useGhostRuntimeState(manifest.id);
+ const broken = runtimeState === 'crashed' || runtimeState === 'fused';
+ return broken ? (
+ <GhostPanelError manifest={manifest} state={runtimeState} />
+ ) : (
+ <GhostChipPanelBody manifest={manifest} />
+ );
+}
+
+export function GhostPanelWindowLayout() {
+ const { t } = useTranslation();
+ const isMac = window.electronAPI?.platform === 'darwin';
+ const ghostId = getGhostPanelWindowGhostId();
+ const ghosts = useInstalledGhosts();
+ const ghost = ghostId ? ghosts.find((g) => g.manifest.id === ghostId) : undefined;
+ // 停用/卸载的瞬间 main 的 reconcile 会收窗;这里只兜住收窗前的一两帧。
+ const manifest = ghost && ghost.enabled !== false ? ghost.manifest : undefined;
+ const title = manifest?.panel?.title ?? manifest?.name ?? '';
+
+ // ⌘W / Ctrl+W:直接关本窗(main 端按 sender win.close(),controller 走
+ // onClosed = 回停靠)。声明壳层所有权,App 根的 fallback 让路。
+ useCloseShortcutShellOwner();
+ useAppShortcut('close-tab-or-window', () => {
+ window.electronAPI.windowClose();
+ return true;
+ });
+
+ const mergeBack = () => {
+ if (!ghostId) return;
+ void window.electronAPI.ghostPanelWindow.setDetached(ghostId, false).catch((err) => {
+ log.warn('merge back failed', err);
+ });
+ };
+
+ return (
+ <div className="flex h-screen flex-col bg-content-area text-foreground">
+ {/* 46px 自绘 chrome:整条 drag region;布局对齐 SidebarWindowLayout。 */}
+ <div
+ className="relative flex h-[46px] shrink-0 items-center border-b border-[var(--border-default)] bg-[var(--panel-bg)]"
+ style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
+ >
+ <div className={isMac ? 'w-20 shrink-0' : 'w-3 shrink-0'} />
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <Puzzle size={14} className="shrink-0 text-[var(--text-tertiary)]" />
+ <span className="truncate text-[13px] text-[var(--text-secondary)]">{title}</span>
+ </div>
+ <div
+ className="flex shrink-0 items-center gap-1 pr-2"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ {/* 合并回主窗口:关偏好 + 关本窗,面板原位回停靠 */}
+ <button
+ type="button"
+ onClick={mergeBack}
+ title={t('ghostPanelWindow.mergeBack')}
+ aria-label={t('ghostPanelWindow.mergeBack')}
+ className="inline-flex h-7 items-center gap-1.5 rounded-full px-2.5 text-[12px] text-[var(--titlebar-icon)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ >
+ <PictureInPicture2 size={14} />
+ <span>{t('ghostPanelWindow.mergeBack')}</span>
+ </button>
+ </div>
+ {!isMac && (
+ <div
+ className="flex h-full shrink-0 items-center"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ <WindowControls />
+ </div>
+ )}
+ </div>
+
+ {/* 面板体:manifest 在场即挂 webview;不在场(收窗前瞬态/野 URL)给占位。 */}
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">
+ {manifest ? (
+ <PanelBody manifest={manifest} />
+ ) : (
+ <div className="flex flex-1 items-center justify-center">
+ <span className="text-[13px] text-[var(--text-tertiary)]">
+ {t('ghostPanelWindow.unavailable')}
+ </span>
+ </div>
+ )}
+ </div>
+
+ {/* 面板 /preview/ 点图的承接端(无 sessionId:「发送到对话」隐藏)。 */}
+ <GhostMediaLightboxHost />
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 4e4baa6eef..4c02ef3da0 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -820,6 +820,18 @@ export function MainLayout() {
void window.electronAPI.rightSidebarWindow.open().catch(() => undefined);
}
});
+ // 插件面板独立窗口的重启恢复(同款语义,按 ghostId 逐个):detached &&
+ // lastOpen 的条目重开。open 走 main 复验资格(卸载/停用过的自动清)。
+ try {
+ const ghostWindows = window.electronAPI.ghostPanelWindow?.getStateSync() ?? {};
+ for (const [ghostId, entry] of Object.entries(ghostWindows)) {
+ if (entry.detached && entry.lastOpen && !entry.open) {
+ void window.electronAPI.ghostPanelWindow.open(ghostId).catch(() => undefined);
+ }
+ }
+ } catch {
+ // 桥不可用(测试环境)= 没有可恢复窗口
+ }
}, []);
// 4) 「在新窗口打开」入口(mac 浮层 / win TabBar 按钮共用):开偏好 + 弹出。
diff --git a/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx b/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
index 8a19415077..b9f62158c5 100644
--- a/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
+++ b/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
@@ -8,6 +8,7 @@ import { Spinner } from '@/components/ui/spinner';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { isSecondaryWindow } from '@/lib/secondaryWindow';
import { isSidebarWindow } from '@/lib/sidebarWindow';
+import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';
import type { WindowsCloseBehavior } from '../../../shared/windowBehavior';
interface WindowControlsProps {
@@ -41,7 +42,13 @@ export function WindowControls({
const { t } = useTranslation();
useEffect(() => {
- if (window.electronAPI.platform !== 'win32' || isSecondaryWindow() || isSidebarWindow()) return;
+ if (
+ window.electronAPI.platform !== 'win32' ||
+ isSecondaryWindow() ||
+ isSidebarWindow() ||
+ isGhostPanelWindow()
+ )
+ return;
return window.electronAPI.windowBehavior.onWindowsCloseBehaviorRequested(() => {
if (windowsCloseBehaviorDialogVisibleRef.current) {
window.electronAPI.windowBehavior.notifyWindowsCloseBehaviorPromptShown();
@@ -120,10 +127,11 @@ export function WindowControls({
// splash / login 阶段 maker-ipc handler 还没注册, invoke 会 reject ——
// catch 后当作 false 处理 (那个阶段本来就不可能有 in-flight)。
const handleCloseClick = async (): Promise<void> => {
- // 「在新窗口打开」的副窗口 / 右侧栏子窗口:关闭只关本窗(会话活在主进程,
- // 不受影响),不退出 app,也没有 disposer chain,所以跳过 in-flight 确认框 +
- // 全屏 closing overlay,直接调 windowClose(main 端按 sender 解析为 win.close())。
- if (isSecondaryWindow() || isSidebarWindow()) {
+ // 「在新窗口打开」的副窗口 / 右侧栏子窗口 / 插件面板子窗口:关闭只关本窗
+ // (会话活在主进程,不受影响),不退出 app,也没有 disposer chain,所以跳过
+ // in-flight 确认框 + 全屏 closing overlay,直接调 windowClose(main 端按
+ // sender 解析为 win.close())。
+ if (isSecondaryWindow() || isSidebarWindow() || isGhostPanelWindow()) {
window.electronAPI.windowClose();
return;
}
diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsx
index 4ec20572cc..2fa1776c65 100644
--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx
+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx
@@ -29,6 +29,7 @@ import { setUserPromptOwner } from '@/lib/userPromptStore';
import { bootstrapMemorySettingsFromMain, setMemorySettingsOwner } from '@/lib/memorySettingsStore';
import { sessionsStore } from '@/lib/sessionsStore';
import { isSidebarWindow } from '@/lib/sidebarWindow';
+import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';
import { setNewMakerDraftOwner } from '@/state/newMakerDraft';
import { setComposerDraftOwner } from '@/lib/composerDraftStore';
@@ -199,7 +200,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
useEffect(() => {
if (!isAuthenticated || !accountDeletionRestored) return;
setAccountDeletionRestored(false);
- if (isSecondaryWindow() || isSidebarWindow()) return;
+ if (isSecondaryWindow() || isSidebarWindow() || isGhostPanelWindow()) return;
let disposed = false;
void authServiceRef
.current!.consumeAccountDeletionRestoredNotice()
diff --git a/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx b/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx
index 1c9dd1a820..affb663b18 100644
--- a/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx
+++ b/apps/desktop/src/renderer/contexts/EnvCheckContext.tsx
@@ -11,13 +11,15 @@ import {
import { isSecondaryWindow } from '@/lib/secondaryWindow';
import { isSidebarWindow } from '@/lib/sidebarWindow';
+import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';
/**
- * 由主窗派生的附属窗口(会话多开副窗 / 右侧栏子窗口):主窗启动时已完成
- * env check + 热更检查,附属窗口一律跳过(初始 'passed' + 不跑 auto-check)。
+ * 由主窗派生的附属窗口(会话多开副窗 / 右侧栏子窗口 / 插件面板子窗口):
+ * 主窗启动时已完成 env check + 热更检查,附属窗口一律跳过
+ * (初始 'passed' + 不跑 auto-check)。
*/
function isDerivedWindow(): boolean {
- return isSecondaryWindow() || isSidebarWindow();
+ return isSecondaryWindow() || isSidebarWindow() || isGhostPanelWindow();
}
/* ── Types ── */
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index c6115efcac..b9db9a51e7 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2366,7 +2366,6 @@
"nodeResidentDetail": "Runs while the plugin is enabled and stops when disabled, updated, uninstalled, or when Cindy exits.",
"tool": "Tool \"{{name}}\"",
"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",
@@ -3087,6 +3086,15 @@
"collapsePanel": "Collapse",
"expandPanel": "Expand"
},
+ "panelChrome": {
+ "maximizeAria": "Maximize panel",
+ "restoreAria": "Restore panel size",
+ "detachAria": "Open in a new window"
+ },
+ "ghostPanelWindow": {
+ "mergeBack": "Merge back into main window",
+ "unavailable": "This plugin panel is currently unavailable"
+ },
"rightSidebar": {
"ariaLabel": "Right sidebar",
"window": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index b32cb31bd7..16987cf528 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2365,7 +2365,6 @@
"nodeResidentDetail": "プラグインが有効な間は実行を続け、無効化、更新、アンインストール、または Cindy 終了時に停止します。",
"tool": "ツール「{{name}}」",
"command": "チャット指令 ${{command}}",
- "panelRight": "パネル「{{title}}」· チャットの右側にドッキング",
"panelLeft": "パネル「{{title}}」· チャットの左側にドッキング",
"panelTab": "パネル「{{title}}」· 右サイドバーのタブ",
"code": "実行コード",
@@ -3086,6 +3085,15 @@
"collapsePanel": "折りたたみ",
"expandPanel": "展開"
},
+ "panelChrome": {
+ "maximizeAria": "パネルを最大化",
+ "restoreAria": "パネルのサイズを元に戻す",
+ "detachAria": "新しいウィンドウで開く"
+ },
+ "ghostPanelWindow": {
+ "mergeBack": "メインウィンドウに戻す",
+ "unavailable": "このプラグインパネルは現在利用できません"
+ },
"rightSidebar": {
"ariaLabel": "右サイドバー",
"window": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f2836be101..e5292f91d8 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2365,7 +2365,6 @@
"nodeResidentDetail": "플러그인이 활성화된 동안 실행되며 비활성화, 업데이트, 제거 또는 Cindy 종료 시 중지됩니다.",
"tool": "도구 \"{{name}}\"",
"command": "채팅 명령 ${{command}}",
- "panelRight": "패널 \"{{title}}\" · 채팅 오른쪽에 도킹",
"panelLeft": "패널 \"{{title}}\" · 채팅 왼쪽에 도킹",
"panelTab": "패널 \"{{title}}\" · 오른쪽 사이드바 탭",
"code": "실행 코드",
@@ -3086,6 +3085,15 @@
"collapsePanel": "접기",
"expandPanel": "펼치기"
},
+ "panelChrome": {
+ "maximizeAria": "패널 최대화",
+ "restoreAria": "패널 크기 복원",
+ "detachAria": "새 창에서 열기"
+ },
+ "ghostPanelWindow": {
+ "mergeBack": "메인 창으로 되돌리기",
+ "unavailable": "이 플러그인 패널은 현재 사용할 수 없습니다"
+ },
"rightSidebar": {
"ariaLabel": "오른쪽 사이드바",
"window": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index c2117c9fe1..780b93acfc 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2365,7 +2365,6 @@
"nodeResidentDetail": "插件启用期间会一直运行;停用、更新、卸载或退出 Cindy 时关闭。",
"tool": "工具「{{name}}」",
"command": "聊天指令 ${{command}}",
- "panelRight": "面板「{{title}}」· 停靠主聊天区右侧",
"panelLeft": "面板「{{title}}」· 停靠主聊天区左侧",
"panelTab": "面板「{{title}}」· 右侧栏页签",
"code": "可执行代码",
@@ -3086,6 +3085,15 @@
"collapsePanel": "折叠",
"expandPanel": "展开"
},
+ "panelChrome": {
+ "maximizeAria": "撑满内容区",
+ "restoreAria": "还原面板大小",
+ "detachAria": "在独立窗口中打开"
+ },
+ "ghostPanelWindow": {
+ "mergeBack": "合并回主窗口",
+ "unavailable": "该插件面板当前不可用"
+ },
"rightSidebar": {
"ariaLabel": "右侧边栏",
"window": {
diff --git a/apps/desktop/src/renderer/layout/LayoutRoot.tsx b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
index fcd9601374..57c70cff79 100644
--- a/apps/desktop/src/renderer/layout/LayoutRoot.tsx
+++ b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
@@ -11,9 +11,11 @@ import {
ensureGhostPanelsRegistered,
useGhostPanelsSync,
} from '../cindy-brain/ghostPanels';
+import { isGhostPanelKindDetached, useGhostPanelWindowsState } from '../lib/ghostPanelWindowState';
import { registerBuiltinPanels } from '../panels/builtinPanels';
import { getPanelKind } from '../panels/registry';
import { installLayoutDevTools } from './layoutDevTools';
+import { PanelMaximizeContext, type PanelMaximizeState } from './panelMaximize';
import { PaneWidthProvider, useContentAvailableWidth } from './paneWidths';
/**
@@ -49,10 +51,19 @@ const CHAT_MIN_PX = 400;
*/
const NON_CHAT_FLOOR_PX = 120;
-/** 单个 pane 的挂载点:查注册表渲染;未注册 kind = 隐藏(数据保留在树里)。 */
+/**
+ * pane 是否在本窗口渲染:未注册 kind(未安装/停用的插件残留)与已抽离进
+ * 独立窗口的面板都不渲染 —— 树数据一律保留,重装/合并即原位恢复
+ * (architecture-invariants「已抽离的面板允许保留在存档中但不渲染」)。
+ */
+function isPanelKindVisible(kind: string): boolean {
+ return getPanelKind(kind) !== null && !isGhostPanelKindDetached(kind);
+}
+
+/** 单个 pane 的挂载点:查注册表渲染;不可见 kind = 隐藏(数据保留在树里)。 */
function PanelHost({ node }: { node: PaneNode }): ReactNode {
const def = getPanelKind(node.panelKind);
- if (!def) return null;
+ if (!def || isGhostPanelKindDetached(node.panelKind)) return null;
const Component = def.Component;
return <Component paneId={node.id} />;
}
@@ -63,11 +74,11 @@ interface SplitChildEntry {
node: LayoutNode;
}
-/** 过滤出可见子项(未注册 kind 的 pane 不可见),保留树内原始下标供 fraction 操作寻址。 */
+/** 过滤出可见子项(未注册/已抽离 kind 的 pane 不可见),保留树内原始下标供 fraction 操作寻址。 */
function visibleSplitChildren(children: { fraction: number; node: LayoutNode }[]): SplitChildEntry[] {
return children
.map((c, treeIndex) => ({ treeIndex, fraction: c.fraction, node: c.node }))
- .filter((e) => e.node.type !== 'pane' || getPanelKind(e.node.panelKind) !== null);
+ .filter((e) => e.node.type !== 'pane' || isPanelKindVisible(e.node.panelKind));
}
/** 面板的最小像素宽:chat 硬下限 400,其余只有防拖丢兜底(见 NON_CHAT_FLOOR_PX)。 */
@@ -133,7 +144,7 @@ function computePanelWidths(
for (const child of layout.content.children) {
const node = child.node;
if (node.type !== 'pane' || node.panelKind === 'chat-main') continue;
- if (!getPanelKind(node.panelKind)) continue;
+ if (!isPanelKindVisible(node.panelKind)) continue;
const fraction = live?.[node.id] ?? child.fraction;
const min = paneMinPx(node);
const max = Math.max(min, avail - CHAT_MIN_PX);
@@ -174,12 +185,14 @@ function NodeView({ node }: { node: LayoutNode }): ReactNode {
interface RootDividerPropsExtra {
/**
- * chat-main 的**实际渲染宽**(px)。chat 是弹性 flex-1,会吸收隐藏面板
- * (卸载残留)与折叠面板的份额,账面 fraction 严重低估它的真实宽度——
+ * chat-main 渲染宽的**账本估值**(px,仅兜底用)。chat 是弹性 flex-1,会吸收
+ * 隐藏面板(卸载残留)与折叠面板的份额,账面 fraction 严重低估它的真实宽度——
* 按账面算余量会把拖缝整个钳死(2026-07-09 mac 实测"纹丝不动"的根因)。
- * 折叠工具栏的份额此处未剔除(其折叠态在面板内部,引擎不可见),导致
- * 估值偏保守:拖动会提前一点到头,不会越界。份额记忆与活跃份额分账的
- * 根治方案暂未纳入布局树职责。
+ * 本估值仍把折叠/抽离面板按账面份额记成"占着地方"(右侧栏收起时误差可达
+ * 数百像素,2026-07-25 Lizi 实测"拖不到头"的根因),所以拖缝的事实来源改为
+ * **起拖时实测 chat-main 元素矩形**(见 onPointerDown;一次布局读取,符合
+ * 起拖测量口径);本值只在量不到元素(测试环境等)时兜底。份额记忆与活跃
+ * 份额分账的根治方案暂未纳入布局树职责。
*/
chatRenderedPx: number;
}
@@ -227,15 +240,22 @@ function RootDivider({ splitId, left, right, avail, chatRenderedPx, onLive, onCo
const startL = left.fraction;
const startR = right.fraction;
// delta(给左侧的增量)的允许区间,每侧余量 = min(渲染余量, 账面余量):
- // - 渲染余量:chat 用实际渲染宽算(弹性吸收了隐藏/折叠份额,账面失真,
- // 见 RootDividerPropsExtra);非 chat 面板 px = fraction × avail,账面即渲染。
+ // - 渲染余量:chat 用**起拖时实测的元素宽**算 —— 账本估值会把折叠/抽离
+ // 面板的份额也记成"占着地方"(右侧栏收起时聊天区实际早已吸收那块空间,
+ // 估值一保守拖动就提前到头,见 RootDividerPropsExtra);起拖只量这一次,
+ // 拖动期间界面静止,没有失效场景。非 chat 面板 px = fraction × avail,
+ // 账面即渲染。
// - 账面余量:transferSplitFraction 低于 0.05 整单拒绝(不收窄),实时
// 拖动必须同受此限,否则松手回弹。
const leftIsChat = left.node.type === 'pane' && left.node.panelKind === 'chat-main';
const rightIsChat = right.node.type === 'pane' && right.node.panelKind === 'chat-main';
const minLF = Math.max(0.05, paneMinPx(left.node) / avail);
const minRF = Math.max(0.05, paneMinPx(right.node) / avail);
- const chatRenderRoom = Math.max(0, (chatRenderedPx - CHAT_MIN_PX) / avail);
+ const measuredChatPx = document
+ .querySelector('[data-panel-drag-root="chat-main"]')
+ ?.getBoundingClientRect().width;
+ const chatPx = measuredChatPx && measuredChatPx > 0 ? measuredChatPx : chatRenderedPx;
+ const chatRenderRoom = Math.max(0, (chatPx - CHAT_MIN_PX) / avail);
const roomL = leftIsChat ? Math.min(startL - 0.05, chatRenderRoom) : startL - minLF;
const roomR = rightIsChat ? Math.min(startR - 0.05, chatRenderRoom) : startR - minRF;
const dMin = -Math.max(0, roomL);
@@ -323,6 +343,8 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
// 装/卸广播 → 注册表对齐 + 重渲(卸下不动布局树,靠这里让引擎重过滤在场面板)。
const ghostSyncVersion = useGhostPanelsSync();
+ // 抽离状态广播 → 重渲(isPanelKindVisible 读的是模块级镜像,靠这个 hook 感知变化)。
+ const ghostWindowsState = useGhostPanelWindowsState();
// 首帧同步读取(sendSync):布局在第一帧就位,不出现默认布局闪现。
const [layout, setLayout] = useState<Layout>(() => window.electronAPI.layout.getStateSync().layout);
@@ -331,14 +353,26 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
[],
);
+ // 撑满态(panelMaximize.tsx):会话级视图态,树账本不动。同 kind 再点还原。
+ const [maximizedKind, setMaximizedKind] = useState<string | null>(null);
+ const maximizeCtx = useMemo<PanelMaximizeState>(
+ () => ({
+ maximizedKind,
+ toggle: (kind) => setMaximizedKind((cur) => (cur === kind ? null : kind)),
+ }),
+ [maximizedKind],
+ );
+
// 分割线拖动中的瞬时 fraction 覆盖(paneId → fraction);面板宽度实时跟手,
// 松手清空回落树值 —— 拖动全程不写 IPC。
const [liveFractions, setLiveFractions] = useState<Record<string, number> | null>(null);
const availCtx = useContentAvailableWidth();
const avail = availCtx ?? AVAILABLE_WIDTH_FALLBACK;
+ // eslint 会说 ghostWindowsState 没被直接读——它是 computePanelWidths 里
+ // isPanelKindVisible 的隐式数据源(模块级镜像),必须进 deps 才能感知抽离变化。
const widths = useMemo(
() => computePanelWidths(layout, liveFractions, avail),
- [layout, liveFractions, avail],
+ [layout, liveFractions, avail, ghostWindowsState],
);
// chat 实际渲染宽 ≈ 可用宽 − 可见非 chat 面板宽度之和(拖缝余量用,见
// RootDividerPropsExtra;折叠面板的误差偏保守)。
@@ -354,13 +388,26 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
// 接管态下可用宽是接管方的(设置页全宽),按它改账本会失真 —— 不自愈。
if (suppressNonChatPanels || availCtx === null || liveFractions !== null) return;
const timer = setTimeout(() => {
- const fixed = normalizeSubMinFractions(layout, availCtx, (kind) => getPanelKind(kind) !== null);
+ const fixed = normalizeSubMinFractions(layout, availCtx, isPanelKindVisible);
if (!fixed) return;
setLayout(fixed);
void window.electronAPI.layout.set(fixed).catch(() => undefined);
}, 250);
return () => clearTimeout(timer);
- }, [availCtx, ghostSyncVersion, layout, liveFractions, suppressNonChatPanels]);
+ }, [availCtx, ghostSyncVersion, ghostWindowsState, layout, liveFractions, suppressNonChatPanels]);
+
+ // 撑满目标失效自动还原:面板被卸下/停用(kind 注销)、抽离进独立窗口或
+ // pane 离开树时清态,免得下次回来以陈年撑满态惊回。接管态(设置页)只是
+ // 暂不渲染,不清 —— 退出接管原样恢复。
+ useEffect(() => {
+ if (maximizedKind === null || suppressNonChatPanels) return;
+ const c = layout.content;
+ const present =
+ c.type === 'split' &&
+ c.children.some((ch) => ch.node.type === 'pane' && ch.node.panelKind === maximizedKind) &&
+ isPanelKindVisible(maximizedKind);
+ if (!present) setMaximizedKind(null);
+ }, [layout, ghostSyncVersion, ghostWindowsState, maximizedKind, suppressNonChatPanels]);
const content = layout.content;
let body: ReactNode;
@@ -370,6 +417,40 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
const visible = visibleSplitChildren(content.children).filter(
(e) => !suppressNonChatPanels || (e.node.type === 'pane' && e.node.panelKind === 'chat-main'),
);
+ // 撑满态:目标 pane 独占一行(自身经 PanelMaximizeContext 切成 flex-1),
+ // 兄弟收成 0 宽裁切 —— 保持挂载不动 display:webview 卸载丢 webContents,
+ // display:none 对 webview 也不友好;分割线整组不画。树账本(fraction/顺序)
+ // 一字不动,还原即回原样 —— 不触碰布局树结构不变量(chat-main 仍在树中,
+ // 与 RSB maximize 隐藏主区同档的视图态先例)。
+ const maximizedEntry =
+ maximizedKind === null
+ ? undefined
+ : visible.find(
+ (e) =>
+ e.node.type === 'pane' &&
+ e.node.panelKind === maximizedKind &&
+ e.node.panelKind !== 'chat-main',
+ );
+ if (maximizedEntry) {
+ body = (
+ <>
+ {visible.map((entry) =>
+ entry === maximizedEntry ? (
+ <NodeView key={entry.node.id} node={entry.node} />
+ ) : (
+ <div key={entry.node.id} aria-hidden className="flex w-0 flex-none overflow-hidden">
+ <NodeView node={entry.node} />
+ </div>
+ ),
+ )}
+ </>
+ );
+ return (
+ <PanelMaximizeContext.Provider value={maximizeCtx}>
+ <PaneWidthProvider value={widths}>{body}</PaneWidthProvider>
+ </PanelMaximizeContext.Provider>
+ );
+ }
const items: ReactNode[] = [];
visible.forEach((entry, i) => {
if (i > 0) {
@@ -400,5 +481,9 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
} else {
body = <NodeView node={content} />;
}
- return <PaneWidthProvider value={widths}>{body}</PaneWidthProvider>;
+ return (
+ <PanelMaximizeContext.Provider value={maximizeCtx}>
+ <PaneWidthProvider value={widths}>{body}</PaneWidthProvider>
+ </PanelMaximizeContext.Provider>
+ );
}
diff --git a/apps/desktop/src/renderer/layout/panelMaximize.tsx b/apps/desktop/src/renderer/layout/panelMaximize.tsx
new file mode 100644
index 0000000000..38de16f512
--- /dev/null
+++ b/apps/desktop/src/renderer/layout/panelMaximize.tsx
@@ -0,0 +1,27 @@
+import { createContext, useContext } from 'react';
+
+/**
+ * PanelMaximizeContext —— 停靠面板「撑满内容区」的引擎级视图态。
+ *
+ * 语义与边界(2026-07-25 首版):
+ * - 这是**视图态而非布局树变换**:maximized 期间树数据(fraction / 顺序)一字
+ * 不动,还原即回原样 —— 不触碰 architecture-invariants 的树结构不变量;
+ * chat-main 仅被视觉收起(0 宽裁切,保持挂载),与 RSB maximize 隐藏主区的
+ * 既有先例同一档语义。
+ * - 会话级瞬时态,不持久化:重启回到常规布局(撑满是"临时看大图"式的查看态)。
+ * - 状态由 LayoutRoot 持有并下发;标准头(PanelChrome)凭 panelKind 消费,
+ * 面板作者无感 —— 系统按钮由引擎统一长出,不进面板自绘区。
+ */
+export interface PanelMaximizeState {
+ /** 当前撑满的面板 kind;null = 常规布局。 */
+ maximizedKind: string | null;
+ /** 切换某面板的撑满态(同 kind 再点 = 还原)。 */
+ toggle: (kind: string) => void;
+}
+
+export const PanelMaximizeContext = createContext<PanelMaximizeState | null>(null);
+
+/** 面板侧消费入口;LayoutRoot 之外(如测试单渲组件)拿到 null,按钮不渲染。 */
+export function usePanelMaximize(): PanelMaximizeState | null {
+ return useContext(PanelMaximizeContext);
+}
diff --git a/apps/desktop/src/renderer/lib/ghostPanelWindow.ts b/apps/desktop/src/renderer/lib/ghostPanelWindow.ts
new file mode 100644
index 0000000000..5f2e4dd423
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/ghostPanelWindow.ts
@@ -0,0 +1,29 @@
+/**
+ * ghostPanelWindow —— 「我是不是插件面板独立窗口」的窗口身份判定。
+ *
+ * 与 sidebarWindow.ts 同款:main 的窗口工厂在启动 URL 上带
+ * `?ghostPanelWindow=<ghostId>`,renderer 启动时读一次;身份在窗口生命周期内
+ * 不变。id 过校验(isValidGhostId)才算数,野值视同普通窗口。
+ */
+
+import { isValidGhostId } from '../../shared/ghost';
+
+let cached: string | null | undefined;
+
+/** 本窗口承载的 ghostId;非插件面板窗口返回 null。 */
+export function getGhostPanelWindowGhostId(): string | null {
+ if (cached === undefined) {
+ const raw = new URLSearchParams(window.location.search).get('ghostPanelWindow');
+ cached = isValidGhostId(raw) ? raw : null;
+ }
+ return cached;
+}
+
+export function isGhostPanelWindow(): boolean {
+ return getGhostPanelWindowGhostId() !== null;
+}
+
+/** 仅测试用。 */
+export function __resetGhostPanelWindowForTest(): void {
+ cached = undefined;
+}
diff --git a/apps/desktop/src/renderer/lib/ghostPanelWindowState.ts b/apps/desktop/src/renderer/lib/ghostPanelWindowState.ts
new file mode 100644
index 0000000000..a10cbca437
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/ghostPanelWindowState.ts
@@ -0,0 +1,92 @@
+/**
+ * ghostPanelWindowState —— 插件停靠面板独立窗口状态的 renderer 端镜像。
+ *
+ * Source of truth 在 main(ghost-panel-window/controller.ts + settings-store):
+ * ghostId → { detached, lastOpen, open },经 `maker:ghost-panel-window:state-changed`
+ * 广播到所有窗口。与 rightSidebarWindowState 的差异:
+ * - **首帧走 sendSync**(规则 7):LayoutRoot 第一帧就要知道哪些面板已抽离,
+ * 异步拉取会先画停靠面板再消失(重启恢复场景闪一下);
+ * - 过滤谓词按 **detached** 而非 open:恢复期窗口还没建出来时面板同样不许
+ * 在主窗停靠位出现。
+ *
+ * 消费方:LayoutRoot(抽离的 pane 不渲染)、GhostPanel(按钮态)、
+ * GhostPanelWindowLayout(子窗自身)。
+ */
+
+import { useSyncExternalStore } from 'react';
+
+import type { GhostPanelWindowsState } from '../../shared/ghostPanelWindow';
+import { GHOST_PANEL_KIND_PREFIX } from '../../shared/ghost';
+
+let state: GhostPanelWindowsState | null = null;
+const subscribers = new Set<() => void>();
+let wired = false;
+
+function readInitial(): GhostPanelWindowsState {
+ // 无桥环境(jsdom 单测 / stub 不全)视同"没有任何抽离",不是错误。
+ try {
+ const api = window.electronAPI?.ghostPanelWindow;
+ if (!api) return {};
+ return api.getStateSync() ?? {};
+ } catch {
+ return {};
+ }
+}
+
+/** 惰性绑定 main 广播(整个 renderer 只绑一次,fan-out 在 preload 层)。 */
+function ensureWired(): void {
+ if (wired) return;
+ wired = true;
+ try {
+ window.electronAPI?.ghostPanelWindow?.onStateChanged((s) => {
+ state = s ?? {};
+ subscribers.forEach((cb) => cb());
+ });
+ } catch {
+ // 无桥环境:保持首读快照
+ }
+}
+
+export function getGhostPanelWindowsState(): GhostPanelWindowsState {
+ if (state === null) {
+ state = readInitial();
+ ensureWired();
+ }
+ return state;
+}
+
+function subscribe(cb: () => void): () => void {
+ getGhostPanelWindowsState();
+ subscribers.add(cb);
+ return () => {
+ subscribers.delete(cb);
+ };
+}
+
+/**
+ * 布局过滤谓词(非 hook,LayoutRoot 的纯函数路径用):该 panelKind 是否
+ * 已抽离进独立窗口。非 ghost 面板恒 false。
+ */
+export function isGhostPanelKindDetached(panelKind: string): boolean {
+ if (!panelKind.startsWith(GHOST_PANEL_KIND_PREFIX)) return false;
+ const ghostId = panelKind.slice(GHOST_PANEL_KIND_PREFIX.length);
+ return getGhostPanelWindowsState()[ghostId]?.detached === true;
+}
+
+/** React hook:订阅全量镜像(引用变化 = 有广播)。 */
+export function useGhostPanelWindowsState(): GhostPanelWindowsState {
+ return useSyncExternalStore(subscribe, getGhostPanelWindowsState);
+}
+
+/** 仅测试用。 */
+export function __setGhostPanelWindowsStateForTest(next: GhostPanelWindowsState): void {
+ state = next;
+ subscribers.forEach((cb) => cb());
+}
+
+/** 仅测试用。 */
+export function __resetGhostPanelWindowsStateForTest(): void {
+ state = null;
+ subscribers.clear();
+ wired = false;
+}
diff --git a/apps/desktop/src/renderer/panels/PanelChrome.tsx b/apps/desktop/src/renderer/panels/PanelChrome.tsx
index dec98ad114..d277f77b7e 100644
--- a/apps/desktop/src/renderer/panels/PanelChrome.tsx
+++ b/apps/desktop/src/renderer/panels/PanelChrome.tsx
@@ -1,4 +1,8 @@
import type { CSSProperties, ReactNode } from 'react';
+import { Maximize2, Minimize2, PictureInPicture2 } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { usePanelMaximize } from '../layout/panelMaximize';
/**
* PanelChrome —— 面板标准头。
@@ -10,20 +14,36 @@ import type { CSSProperties, ReactNode } from 'react';
* PanelDragController 识别;窗口拖动走 46px 顶带,见 B3 口径);
* 3. 左标题 / 右 actions 槽:标题给面板身份,actions 给面板自定义控件。
*
- * 右端两颗系统按钮(独立窗口 / 撑满页面)**暂缺**:对应的引擎级能力
- * (任意面板 detach / maximize)还没泛化,能力落地时由本组件统一
- * 长出,面板作者无感 —— 这正是"标准头由引擎提供"的意义。
+ * 右端系统按钮(一批,由引擎统一长出,面板作者无感;身份卡
+ * panel.systemButtons 可逐个关闭):
+ * - 「独立窗口」(detach):传 onDetach 即得,点击把面板抽进自己的 OS 窗口
+ * (状态机在 main 的 ghost-panel-window/controller.ts);
+ * - 「撑满内容区」(maximize):传 panelKind 即得,状态在 LayoutRoot 的
+ * PanelMaximizeContext。
*
- * 视觉走主题 token(规则 16);组件自身无文案(标题由调用方传入并自行 i18n)。
+ * 视觉走主题 token(规则 16);按钮 aria 文案走 i18n(panelChrome.*),
+ * 标题由调用方传入并自行 i18n。
*/
export interface PanelChromeProps {
/** 左侧标题(调用方自行 i18n;可以是文本或自定义节点)。 */
title: ReactNode;
- /** 右端自定义控件槽(排在未来系统按钮的左侧)。 */
+ /** 右端自定义控件槽(排在系统按钮的左侧)。 */
actions?: ReactNode;
+ /**
+ * 面板在布局树里的 panelKind。传入且处于 LayoutRoot 的
+ * PanelMaximizeContext 之下时,标准头长出「撑满内容区」系统按钮;
+ * 不传(或脱离引擎单渲)则不渲染,行为与旧版完全一致。
+ */
+ panelKind?: string;
+ /** 传入即长出「独立窗口」系统按钮(排在撑满按钮左侧),点击回调归调用方。 */
+ onDetach?: () => void;
}
-export function PanelChrome({ title, actions }: PanelChromeProps): ReactNode {
+export function PanelChrome({ title, actions, panelKind, onDetach }: PanelChromeProps): ReactNode {
+ const { t } = useTranslation();
+ const maximize = usePanelMaximize();
+ const showMaximize = panelKind !== undefined && maximize !== null;
+ const isMaximized = showMaximize && maximize.maximizedKind === panelKind;
return (
<>
{/* 窗口 chrome 让位带(§6 规则 3:顶部 46px 是系统领地,任何面板不得占用)。
@@ -42,7 +62,33 @@ export function PanelChrome({ title, actions }: PanelChromeProps): ReactNode {
<div className="min-w-0 truncate text-[12px] font-medium text-[var(--text-secondary)]">
{title}
</div>
- {actions && <div className="flex shrink-0 items-center gap-0.5">{actions}</div>}
+ {(actions || showMaximize || onDetach) && (
+ <div className="flex shrink-0 items-center gap-0.5">
+ {actions}
+ {onDetach && (
+ <button
+ type="button"
+ aria-label={t('panelChrome.detachAria')}
+ onClick={onDetach}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-full text-[var(--titlebar-icon)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ >
+ <PictureInPicture2 size={14} />
+ </button>
+ )}
+ {showMaximize && (
+ // 按下命中 button 时 PanelDragController 会让路(标准头手势面的
+ // 交互元素豁免),点击不会误触"拿起面板"。
+ <button
+ type="button"
+ aria-label={t(isMaximized ? 'panelChrome.restoreAria' : 'panelChrome.maximizeAria')}
+ onClick={() => maximize.toggle(panelKind)}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-full text-[var(--titlebar-icon)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ >
+ {isMaximized ? <Minimize2 size={14} /> : <Maximize2 size={14} />}
+ </button>
+ )}
+ </div>
+ )}
</div>
</>
);
diff --git a/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx b/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx
new file mode 100644
index 0000000000..d2c302a493
--- /dev/null
+++ b/apps/desktop/src/renderer/panels/__tests__/PanelChrome.test.tsx
@@ -0,0 +1,71 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { useState } from 'react';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+
+import { PanelMaximizeContext, type PanelMaximizeState } from '../../layout/panelMaximize';
+import { PanelChrome } from '../PanelChrome';
+
+// 仓库同款 i18n mock:t 返回 key 本身,便于断言。
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+/** 带真实 toggle 语义的 harness:同 kind 再点 = 还原(与 LayoutRoot 实现一致)。 */
+function Harness({ panelKind }: { panelKind?: string }) {
+ const [maximizedKind, setMaximizedKind] = useState<string | null>(null);
+ const ctx: PanelMaximizeState = {
+ maximizedKind,
+ toggle: (kind) => setMaximizedKind((cur) => (cur === kind ? null : kind)),
+ };
+ return (
+ <PanelMaximizeContext.Provider value={ctx}>
+ <PanelChrome title="测试面板" panelKind={panelKind} />
+ </PanelMaximizeContext.Provider>
+ );
+}
+
+afterEach(cleanup);
+
+describe('PanelChrome · 撑满系统按钮', () => {
+ it('传 panelKind 且在 PanelMaximizeContext 下 → 长出撑满按钮,点按在撑满/还原间切换', () => {
+ render(<Harness panelKind="ghost:demo" />);
+ const btn = screen.getByRole('button', { name: 'panelChrome.maximizeAria' });
+ fireEvent.click(btn);
+ // 撑满后按钮语义翻转为"还原"
+ const restore = screen.getByRole('button', { name: 'panelChrome.restoreAria' });
+ fireEvent.click(restore);
+ expect(screen.getByRole('button', { name: 'panelChrome.maximizeAria' })).toBeTruthy();
+ });
+
+ it('不传 panelKind → 不渲染系统按钮(旧行为不变)', () => {
+ render(<Harness />);
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('脱离 PanelMaximizeContext 单渲(如测试/独立宿主)→ 不渲染系统按钮', () => {
+ render(<PanelChrome title="测试面板" panelKind="ghost:demo" />);
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('传 onDetach → 长出独立窗口按钮,点击回调触发;与撑满按钮并存', () => {
+ const onDetach = vi.fn();
+ render(
+ <PanelMaximizeContext.Provider
+ value={{ maximizedKind: null, toggle: () => undefined }}
+ >
+ <PanelChrome title="测试面板" panelKind="ghost:demo" onDetach={onDetach} />
+ </PanelMaximizeContext.Provider>,
+ );
+ const detachBtn = screen.getByRole('button', { name: 'panelChrome.detachAria' });
+ fireEvent.click(detachBtn);
+ expect(onDetach).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole('button', { name: 'panelChrome.maximizeAria' })).toBeTruthy();
+ });
+
+ it('只传 onDetach(无 panelKind)→ 只有独立窗口按钮', () => {
+ render(<PanelChrome title="测试面板" onDetach={() => undefined} />);
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ expect(screen.getByRole('button', { name: 'panelChrome.detachAria' })).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsx
index e184c7902e..9e70a99ba3 100644
--- a/apps/desktop/src/renderer/router.tsx
+++ b/apps/desktop/src/renderer/router.tsx
@@ -3,6 +3,7 @@ import { createHashRouter, Navigate } from 'react-router-dom';
import { MainLayout } from '@/components/layout/MainLayout';
import { RouteErrorFallback } from '@/components/error/RouteErrorFallback';
import { SidebarWindowLayout } from '@/components/layout/SidebarWindowLayout';
+import { GhostPanelWindowLayout } from '@/components/layout/GhostPanelWindowLayout';
import { SettingsView } from '@/components/settings/SettingsView';
import { LoginPage } from '@/components/login/LoginPage';
import { ProtectedRoute } from '@/components/auth/ProtectedRoute';
@@ -65,6 +66,13 @@ export const router = createHashRouter([
element: <SidebarWindowLayout />,
errorElement: <RouteErrorFallback variant="section" />,
},
+ // 插件面板独立窗口(?ghostPanelWindow=<id>)的根路由 —— 同样与
+ // MainLayout 平级,只挂 46px chrome + 面板体。
+ {
+ path: 'ghost-panel-window',
+ element: <GhostPanelWindowLayout />,
+ errorElement: <RouteErrorFallback variant="section" />,
+ },
{
element: <MainLayout />,
children: [
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index f7d9d28a3e..0b0df966e5 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1404,6 +1404,23 @@ interface ElectronAPI {
onCommand: (cb: (cmd: RsbWindowCommand) => void) => () => void;
};
+ /** 插件停靠面板独立窗口(每 ghostId 一扇窗;状态机在 main)。 */
+ ghostPanelWindow: {
+ /** 首帧同步读全量状态(ghostId → entry)。 */
+ getStateSync: () => import('../shared/ghostPanelWindow').GhostPanelWindowsState;
+ getState: () => Promise<import('../shared/ghostPanelWindow').GhostPanelWindowsState>;
+ /** 幂等:已开则 show + focus。 */
+ open: (ghostId: string) => Promise<void>;
+ /** 写偏好;true 开窗抽离,false 关窗回停靠。返回新全量 state。 */
+ setDetached: (
+ ghostId: string,
+ detached: boolean,
+ ) => Promise<import('../shared/ghostPanelWindow').GhostPanelWindowsState>;
+ onStateChanged: (
+ cb: (state: import('../shared/ghostPanelWindow').GhostPanelWindowsState) => void,
+ ) => () => void;
+ };
+
agentIsland: {
setVisibleSession: (sessionId: string | string[] | null) => Promise<{ ok: true }>;
setEnabled: (enabled: boolean) => Promise<{ ok: true }>;
diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.ts
index 2bc18e8688..4cfb499498 100644
--- a/apps/desktop/src/shared/__tests__/ghost.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts
@@ -196,6 +196,38 @@ describe('ghost · 清单校验', () => {
expect(withPanel({}).ok).toBe(true);
});
+ it('panel.systemButtons:标准头系统按钮开关 —— 布尔白名单键,tab 形态拒装', () => {
+ const withPanel = (panel: Record<string, unknown>) =>
+ validateGhostManifest({ ...goodManifest(), panel: { html: 'panel.html', ...panel } });
+ // 合法:关掉 maximize / detach / 空对象(= 全默认) / 显式 true / 双键并存
+ const off = withPanel({ systemButtons: { maximize: false } });
+ expect(off.ok && (off as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons).toEqual({
+ maximize: false,
+ });
+ const detachOff = withPanel({ systemButtons: { detach: false } });
+ expect(
+ detachOff.ok && (detachOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,
+ ).toEqual({ detach: false });
+ const bothOff = withPanel({ systemButtons: { maximize: false, detach: false } });
+ expect(
+ bothOff.ok && (bothOff as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,
+ ).toEqual({ maximize: false, detach: false });
+ expect(withPanel({ systemButtons: {} }).ok).toBe(true);
+ expect(withPanel({ systemButtons: { maximize: true, detach: true } }).ok).toBe(true);
+ // 非对象 / 未知键 / 非布尔值:收词明确拒绝(规则 9)
+ expect(withPanel({ systemButtons: 'off' }).ok).toBe(false);
+ expect(withPanel({ systemButtons: { refresh: false } }).ok).toBe(false);
+ expect(withPanel({ systemButtons: { maximize: 'no' } }).ok).toBe(false);
+ expect(withPanel({ systemButtons: { detach: 0 } }).ok).toBe(false);
+ // 页签形态没有标准头:声明即拒(与 minWidth/defaultFraction 同款语义)
+ expect(withPanel({ position: 'tab', systemButtons: { maximize: false } }).ok).toBe(false);
+ // 缺省(不声明)不产出字段
+ const plain = withPanel({});
+ expect(
+ plain.ok && (plain as { ok: true; manifest: GhostManifest }).manifest.panel?.systemButtons,
+ ).toBeUndefined();
+ });
+
it('author:可选展示名,1–64 字符,原样输出', () => {
const base = validateGhostManifest({ ...goodManifest(), author: 'Lizi' });
expect(base.ok && (base as { ok: true; manifest: GhostManifest }).manifest.author).toBe('Lizi');
@@ -586,16 +618,16 @@ describe('ghost · layoutWithGhostPanel(装入即停靠)', () => {
panel: { html: 'panel.html', minWidth: 240, defaultFraction: 0.18 },
});
- it('新装缺省 position:停在主聊天窗右侧(默认 right,2026-07-12 定案)', () => {
+ it('新装缺省 position:停在主聊天窗左侧(right 退役,2026-07-25 定案)', () => {
const next = layoutWithGhostPanel(createDefaultLayout(), manifest());
expect(next).not.toBeNull();
const split = next!.content as SplitNode;
expect(split.children.map((c) => (c.node.type === 'pane' ? c.node.panelKind : '?'))).toEqual([
- 'chat-main',
'ghost:hello',
+ 'chat-main',
'right-tabs',
]);
- const pane = split.children[1];
+ const pane = split.children[0];
expect(pane.fraction).toBeCloseTo(0.18, 5);
expect(pane.node.type === 'pane' && pane.node.minWidth).toBe(240);
// 全体份额仍归一
@@ -629,8 +661,8 @@ describe('ghost · layoutWithGhostPanel(装入即停靠)', () => {
const m = manifest();
delete m.panel!.defaultFraction;
const next = layoutWithGhostPanel(createDefaultLayout(), m);
- // 缺省 position=right,面板在 chat-main 之后(下标 1)。
- expect((next!.content as SplitNode).children[1].fraction).toBeCloseTo(0.2, 5);
+ // 缺省 position=left,面板在 chat-main 之前(下标 0)。
+ expect((next!.content as SplitNode).children[0].fraction).toBeCloseTo(0.2, 5);
});
it("position: 'tab' → null,不进布局树(页签形态由右侧栏承载)", () => {
@@ -844,15 +876,16 @@ describe('ghost · description(自我介绍)', () => {
});
describe('ghost · panel.position 校验', () => {
- it('left/right 通过并进清单;top/bottom 收词但明确拒绝;野值拒', () => {
+ it('left 通过;right 退役兼容归一化为 left;top/bottom 收词但明确拒绝;野值拒', () => {
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('right');
+ expect(right.ok && right.manifest.panel?.position).toBe('left');
for (const pending of ['top', 'bottom']) {
const v = validateGhostManifest(withPos(pending));
@@ -981,8 +1014,8 @@ describe('ghost · 逐项权限清单', () => {
panel: { html: 'panel.html' },
};
const items = ghostPermissionItems(plain);
- expect(items.map((i) => i.key)).toEqual(['panel:right', 'code']);
- expect(items[0]).toMatchObject({ labelKey: 'panelRight', labelArgs: { title: '说明书' } });
+ expect(items.map((i) => i.key)).toEqual(['panel:left', 'code']);
+ expect(items[0]).toMatchObject({ labelKey: 'panelLeft', labelArgs: { title: '说明书' } });
// 页签形态在确认框同样逐项如实展示(labelKey 独立成 panelTab)。
const tabbed = ghostPermissionItems({ ...plain, panel: { html: 'panel.html', position: 'tab' } });
@@ -1009,10 +1042,10 @@ describe('ghost · 逐项权限清单', () => {
version: '2.0.0',
cindy: { image: ['generate'] }, // 移除 edit
tools: [...(fullChip().tools ?? []), { name: 'style_image', description: '风格化' }], // 新增工具
- panel: { title: '画廊', html: 'panel.html', position: 'right' }, // 换边
+ panel: { title: '画廊', html: 'panel.html', position: 'tab' }, // 换形态(right 已退役)
};
const diff = diffGhostPermissionItems(prev, next);
- expect(diff.added.map((i) => i.key).sort()).toEqual(['panel:right', 'tool:style_image']);
+ expect(diff.added.map((i) => i.key).sort()).toEqual(['panel:tab', 'tool:style_image']);
expect(diff.removed.map((i) => i.key).sort()).toEqual(['cindy:image.edit', 'panel:left']);
expect(diff.unchanged.map((i) => i.key)).toEqual([
'cindy:image.generate',
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 6c343982a0..a895a66c7a 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -292,20 +292,24 @@ export const GHOST_LAUNCH_MODES = ['on-demand', 'resident'] as const;
export type GhostLaunchMode = (typeof GHOST_LAUNCH_MODES)[number];
/**
- * 面板显示形态(相对主聊天窗)。left / right = 顶层布局树停靠 pane;
+ * 面板显示形态(相对主聊天窗)。left = 顶层布局树停靠 pane(缺省);
* 'tab' = 不进布局树,作为右侧栏(right-tabs)里的每会话单例页签
* (2026-07-24 定案,注册链路见 renderer/cindy-brain/ghostTabPlugins.tsx)。
- * top / bottom 需要嵌套上下分割(树操作/拖缝/卸载查找全链路),排期中——
- * 校验层先收词并明确拒绝,不静默降级(规则 9)。
+ * right 已退役(2026-07-25 Lizi 定案:右侧是右侧边栏的地盘,插件面板默认
+ * 挤过去体验差;用户想放右边用拖拽换位即可)——旧包声明的 right 在校验期
+ * 归一化为 left(已装插件每次启动都重过校验,硬拒会把存量插件打没;兼容
+ * 语义与 model→cindy 改名同款)。top / bottom 需要嵌套上下分割(树操作/
+ * 拖缝/卸载查找全链路),排期中——校验层先收词并明确拒绝,不静默降级(规则 9)。
*/
-export const GHOST_PANEL_POSITIONS = ['left', 'right', 'tab'] as const;
+export const GHOST_PANEL_POSITIONS = ['left', 'tab'] as const;
export type GhostPanelPosition = (typeof GHOST_PANEL_POSITIONS)[number];
/** 面板声明(五个卡槽中的「面板」槽,一段意识至多一块)。 */
export interface GhostPanelDecl {
/** 面板标准头(PanelChrome)标题;缺省用意识 name。 */
title?: string;
- /** 显示形态:left / right 停靠,或 'tab' 右侧栏页签;缺省 = right(2026-07-12 Lizi 定案)。 */
+ /** 显示形态:left 停靠主聊天窗左侧(缺省),或 'tab' 右侧栏页签;
+ * right 已退役并入 left(2026-07-25 Lizi 定案,见 GHOST_PANEL_POSITIONS 注释)。 */
position?: GhostPanelPosition;
/** 面板界面入口(安装目录内相对路径,意识自绘)。 */
html: string;
@@ -313,6 +317,14 @@ export interface GhostPanelDecl {
minWidth?: number;
/** 装入布局时的初始宽度占比(与 layoutTree 的 fraction 同语义)。仅停靠形态有效,'tab' 时禁用。 */
defaultFraction?: number;
+ /**
+ * 标准头系统按钮开关(2026-07-25):缺省全开,声明 false 逐个关闭。
+ * 当前一批:maximize =「撑满内容区」、detach =「在独立窗口中打开」。
+ * 标准头本体(标题条)恒由主机绘制、不可关——可配置的只是系统按钮;
+ * 'tab' 形态没有标准头,声明本字段拒装。未知键按规则 9 收词明确拒绝,
+ * 新按钮上线时在这里扩键。
+ */
+ systemButtons?: { maximize?: boolean; detach?: boolean };
}
/**
@@ -1293,11 +1305,11 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt
});
}
if (manifest.panel) {
- const position = manifest.panel.position ?? 'right';
+ const position = manifest.panel.position ?? 'left';
items.push({
key: `panel:${position}`,
kind: 'panel',
- labelKey: position === 'left' ? 'panelLeft' : position === 'tab' ? 'panelTab' : 'panelRight',
+ labelKey: position === 'tab' ? 'panelTab' : 'panelLeft',
labelArgs: { title: manifest.panel.title ?? manifest.name },
});
}
@@ -1446,7 +1458,7 @@ export function ghostWebviewEntryPaths(manifest: GhostManifest): string[] {
* - 树上已有同 kind 的 pane(重装)→ 返回 null:不动树,位置记忆保留、原位复活;
* - 意识没声明面板 → null;
* - position:'tab' → null:页签形态不进布局树,由右侧栏页签(ghostTabPlugins)承载;
- * - 否则停在聊天区右侧(index 1),宽度占比/最小宽取清单声明。
+ * - 否则停在聊天区左侧,宽度占比/最小宽取清单声明。
* 卸下时**不做**逆操作 —— 树数据保留正是"重装复活"的记忆来源(§6 规则 5)。
*/
export function layoutWithGhostPanel(layout: Layout, manifest: GhostManifest): Layout | null {
@@ -1455,13 +1467,14 @@ export function layoutWithGhostPanel(layout: Layout, manifest: GhostManifest): L
const kind = ghostPanelKind(manifest.id);
if (findSplitChildByPanelKind(layout, kind)) return null;
// 停靠位置(相对主聊天窗):按 chat-main 的实际下标定插入点,不写死
- // 序号(未来树形态变化不至于错位)。缺省 right(2026-07-12 Lizi 定案)。
+ // 序号(未来树形态变化不至于错位)。停靠恒在聊天区左侧(2026-07-25 Lizi
+ // 定案:right 退役,右侧留给右侧边栏;用户要右侧自己拖拽换位——已在树里
+ // 的 pane 是用户布局记忆,本函数只管首次装入,不搬动存量)。
const chatIndex =
layout.content.type === 'split'
? layout.content.children.findIndex((c) => c.node.type === 'pane' && c.node.panelKind === 'chat-main')
: -1;
- const position = manifest.panel.position ?? 'right';
- const index = chatIndex < 0 ? 1 : position === 'left' ? chatIndex : chatIndex + 1;
+ const index = chatIndex < 0 ? 0 : chatIndex;
const result = insertRootSplitPane(
layout,
{
@@ -1560,28 +1573,66 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {
) {
return { ok: false, reason: 'panel.defaultFraction 必须是 0.05–0.8 之间的数字' };
}
+ let systemButtons: GhostPanelDecl['systemButtons'];
+ if (p.systemButtons !== undefined) {
+ const sb = p.systemButtons;
+ if (!isPlainObject(sb)) {
+ return { ok: false, reason: 'panel.systemButtons 必须是对象(如 { "maximize": false })' };
+ }
+ // 收词明确拒绝未知键(规则 9):新系统按钮上线时在白名单里扩键。
+ const knownButtons = ['maximize', 'detach'];
+ for (const key of Object.keys(sb)) {
+ if (!knownButtons.includes(key)) {
+ return { ok: false, reason: `panel.systemButtons 只认 ${knownButtons.join(' / ')},未知键:${key}` };
+ }
+ if (typeof (sb as Record<string, unknown>)[key] !== 'boolean') {
+ return { ok: false, reason: `panel.systemButtons.${key} 必须是布尔值` };
+ }
+ }
+ const maximize = (sb as Record<string, unknown>).maximize;
+ const detach = (sb as Record<string, unknown>).detach;
+ systemButtons = {
+ ...(typeof maximize === 'boolean' ? { maximize } : {}),
+ ...(typeof detach === 'boolean' ? { detach } : {}),
+ };
+ }
+ let position: GhostPanelPosition | undefined;
if (p.position !== undefined) {
if (p.position === 'top' || p.position === 'bottom') {
// 收词但明确拒绝(规则 9 不静默降级):上下停靠等布局引擎嵌套分割就绪后开放。
- return { ok: false, reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / right / tab' };
+ return { ok: false, reason: 'panel.position 的 top / bottom 暂未支持(排期中),当前可用:left / tab' };
}
- if (!(GHOST_PANEL_POSITIONS as readonly string[]).includes(p.position as string)) {
- return { ok: false, 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;
}
- // 页签形态没有拖缝宽度语义:收词明确拒绝而非静默忽略(规则 9)。
- if (p.position === 'tab' && (p.minWidth !== undefined || p.defaultFraction !== undefined)) {
+ // 页签形态没有拖缝宽度/标准头语义:收词明确拒绝而非静默忽略(规则 9)。
+ if (
+ position === 'tab' &&
+ (p.minWidth !== undefined || p.defaultFraction !== undefined || p.systemButtons !== undefined)
+ ) {
return {
ok: false,
- reason: "panel.minWidth / panel.defaultFraction 仅停靠形态(left / right)有效,position:'tab' 时请移除",
+ reason:
+ "panel.minWidth / panel.defaultFraction / panel.systemButtons 仅停靠形态(left)有效,position:'tab' 时请移除",
};
}
}
panel = {
...(p.title !== undefined ? { title: p.title as string } : {}),
- ...(p.position !== undefined ? { position: p.position as GhostPanelPosition } : {}),
+ ...(position !== undefined ? { position } : {}),
html: p.html as string,
...(p.minWidth !== undefined ? { minWidth: p.minWidth as number } : {}),
...(p.defaultFraction !== undefined ? { defaultFraction: p.defaultFraction as number } : {}),
+ ...(systemButtons !== undefined ? { systemButtons } : {}),
};
}
diff --git a/apps/desktop/src/shared/ghostPanelWindow.ts b/apps/desktop/src/shared/ghostPanelWindow.ts
new file mode 100644
index 0000000000..291331eecf
--- /dev/null
+++ b/apps/desktop/src/shared/ghostPanelWindow.ts
@@ -0,0 +1,21 @@
+/**
+ * 插件停靠面板独立窗口(ghost panel window)的跨进程共享类型。
+ *
+ * 三方共用:main(controller / IPC handler)、preload(桥接签名)、renderer
+ * (主窗镜像 store + 子窗口根组件)。只放纯类型,不放运行时代码。
+ * 语义对照 shared/rightSidebarWindow.ts 的 RsbWindowState,差异是按 ghostId
+ * 多实例(每个插件至多一扇窗)。
+ */
+
+/** 单个插件窗口状态:detached 是持久化偏好,lastOpen 供重启恢复,open 是运行时开闭。 */
+export interface GhostPanelWindowEntryState {
+ /** 偏好:「该插件面板在独立窗口中显示」。持久化,default false。 */
+ detached: boolean;
+ /** 状态:上次退出时窗口是否处于打开态(供重启恢复)。持久化。 */
+ lastOpen: boolean;
+ /** 运行时:子窗口当前是否存在。不持久化。 */
+ open: boolean;
+}
+
+/** 全量状态:ghostId → 窗口状态。没有条目 = 从未抽离(等价三 false)。 */
+export type GhostPanelWindowsState = Record<string, GhostPanelWindowEntryState>;
diff --git a/docs/dev-rules/electron-security-and-process-boundaries.md b/docs/dev-rules/electron-security-and-process-boundaries.md
index ffcfc16842..6b7816e130 100644
--- a/docs/dev-rules/electron-security-and-process-boundaries.md
+++ b/docs/dev-rules/electron-security-and-process-boundaries.md
@@ -65,8 +65,11 @@ Renderer 可以负责组件渲染、交互状态、表单状态、展示数据
- `navigateOnDragDrop: false`
窗口可以追加 preload、partition、节流等功能配置,但不得覆盖上述字段为更宽松的值。
-`webviewTag` 默认关闭;主界面和右侧栏因内置浏览器需要而开启,是受控例外,必须继续由
-`webview-security.ts` 在 `will-attach-webview` 阶段覆盖 Renderer 传入的全部安全选项。
+`webviewTag` 默认关闭;受控例外目前有三处——主界面与右侧栏子窗口(内置浏览器需要),
+以及插件面板独立窗口(`main/ghost-panel-window/window.ts`,仅承载 ghost 分区面板
+webview)——所有例外都必须继续由 `webview-security.ts` 在 `will-attach-webview` 阶段
+覆盖 Renderer 传入的全部安全选项(hardener 挂在 `web-contents-created`,对所有窗口
+全局生效,ghost 附加闸只认分区与地址、不认宿主窗口)。
内置浏览器为了捕获 `window.open`,会在 Main hardener 中设置 `allowpopups`,随后由
`setWindowOpenHandler` 拒绝真实弹窗并转成受控标签页。这是唯一允许的窄例外;Renderer