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。

perf(desktop): 优化侧边栏与插件分离窗口

DavidShen9a117394f8b2
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index d1bc26c7ac..0e22a965b6 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -1508,6 +1508,18 @@ const config: ForgeConfig = {
config: 'vite.preload.config.ts',
target: 'preload',
},
+ {
+ // 右侧栏独立子窗口专用 preload:最小权限 bridge,不加载主 preload 完整桥。
+ entry: 'src/preload/sidebarWindowPreload.ts',
+ config: 'vite.preload.config.ts',
+ target: 'preload',
+ },
+ {
+ // 插件面板独立窗口专用 preload:最小权限 bridge。
+ entry: 'src/preload/ghostPanelWindowPreload.ts',
+ config: 'vite.preload.config.ts',
+ target: 'preload',
+ },
{
// RSB 内置浏览器 webview 的 guest 注入层(页面评论 overlay)。由
// main 的 webview hardener 在 will-attach-webview 时按
diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.ts
index 117ce6660c..f2db745e72 100644
--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts
@@ -28,6 +28,8 @@ vi.mock('electron', () => ({
const nativePopupWebContentsIds = vi.hoisted(() => new Set<number>());
const resourceUsageWebContentsIds = vi.hoisted(() => new Set<number>());
+const rsbWindowWebContentsIds = vi.hoisted(() => new Set<number>());
+const ghostPanelWebContentsIds = vi.hoisted(() => new Set<number>());
vi.mock('../rsb-browser-bridge/native-popup-surfaces', () => ({
isRsbNativePopupWebContentsId: (webContentsId: number) =>
@@ -39,6 +41,15 @@ vi.mock('../resource-usage-window/registry.js', () => ({
resourceUsageWebContentsIds.has(webContentsId),
}));
+vi.mock('../right-sidebar-window/registry.js', () => ({
+ isRsbWindowWebContentsId: (webContentsId: number) => rsbWindowWebContentsIds.has(webContentsId),
+}));
+
+vi.mock('../ghost-panel-window/registry.js', () => ({
+ isGhostPanelWebContentsId: (webContentsId: number) =>
+ ghostPanelWebContentsIds.has(webContentsId),
+}));
+
const mocks = vi.hoisted(() => ({
logger: {
info: vi.fn(),
@@ -489,6 +500,8 @@ describe('installQuitHandler render-process-gone', () => {
vi.clearAllMocks();
nativePopupWebContentsIds.clear();
resourceUsageWebContentsIds.clear();
+ rsbWindowWebContentsIds.clear();
+ ghostPanelWebContentsIds.clear();
});
type RenderGoneHandler = (
@@ -574,6 +587,36 @@ describe('installQuitHandler render-process-gone', () => {
}
});
+ it('right sidebar renderer crash does NOT shut the app down', async () => {
+ rsbWindowWebContentsIds.add(45);
+ const { handler, app, restore } = await installAndGrabHandler();
+ try {
+ handler(undefined, { id: 45, getType: () => 'window' }, { reason: 'crashed', exitCode: 5 });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(app.exit).not.toHaveBeenCalled();
+ expect(mocks.logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('right sidebar render-process-gone'),
+ );
+ } finally {
+ restore();
+ }
+ });
+
+ it('ghost panel renderer crash does NOT shut the app down', async () => {
+ ghostPanelWebContentsIds.add(46);
+ const { handler, app, restore } = await installAndGrabHandler();
+ try {
+ handler(undefined, { id: 46, getType: () => 'window' }, { reason: 'crashed', exitCode: 5 });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(app.exit).not.toHaveBeenCalled();
+ expect(mocks.logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('ghost panel render-process-gone'),
+ );
+ } finally {
+ restore();
+ }
+ });
+
it('main window renderer crash still shuts the app down with exit(1)', async () => {
const { handler, app, restore } = await installAndGrabHandler();
try {
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 7ad0338e23..dbc7b5538b 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -486,9 +486,11 @@ import {
patchGhostPanelWindowEntry,
readGhostPanelWindowsSettings,
removeGhostPanelWindowEntry,
+ resetGhostPanelWindowSettingsForStartup,
} from './ghost-panel-window/settings-store.js';
import {
readRsbWindowSettings,
+ resetRsbWindowSettingsForStartup,
writeRsbWindowSettingsPatch,
} from './right-sidebar-window/settings-store.js';
import {
@@ -1301,15 +1303,16 @@ installWebviewHardener();
// 通知用的 host webContents 通过 mainWindowRef lazy 取,主窗未就绪时静默跳过
// (pin 状态由 main 端 registry 保权威,renderer 端会通过 reconciliation 跟上)。
// ── 右侧栏独立子窗口(RSB window)────────────────────────────────────────
-// 「侧边栏在新窗口中显示」偏好 + 子窗口生命周期状态机。detached 且窗口开着时,
+// 右侧栏当前进程内的分离状态 + 子窗口生命周期状态机。detached 且窗口开着时,
// RSB host(pin/unpin 通知、tab-op dispatch 的目标 renderer)是子窗口而非主窗,
// 下方三处 RSB bridge wiring 统一经 controller.getHostWebContents() 解析。
// deps 全部是 lazy 闭包(mainWindowRef / isQuitting 在文件更靠后声明+赋值,
// 调用时机远晚于此处构造),状态机本体见 right-sidebar-window/controller.ts。
+resetRsbWindowSettingsForStartup();
const rsbWindowController = new RsbWindowController({
settings: { read: readRsbWindowSettings, writePatch: writeRsbWindowSettingsPatch },
- createWindow: (opts) => {
- const window = createRightSidebarWindow(opts);
+ createWindow: () => {
+ const window = createRightSidebarWindow();
const mainTarget =
mainWindowRef && !mainWindowRef.isDestroyed() && !mainWindowRef.webContents.isDestroyed()
? mainWindowRef.webContents
@@ -1475,6 +1478,7 @@ registerRsbWindowIpc({
// 主窗布局树里该 pane 停止渲染(树不动);关窗/合并即回停靠。装/卸/启停广播
// 经 setGhostsChangedObserver 喂 reconcile,失去资格的窗口即时收掉。
// deps 同样全 lazy(isQuitting 声明在后),状态机见 ghost-panel-window/controller.ts。
+resetGhostPanelWindowSettingsForStartup();
const ghostPanelWindowsController = new GhostPanelWindowsController({
settings: {
read: readGhostPanelWindowsSettings,
@@ -1510,6 +1514,9 @@ const ghostPanelWindowsController = new GhostPanelWindowsController({
}
}
},
+ sendToWindow: (win, channel, payload) => {
+ try { win.webContents.send(channel, payload); } catch { /* ignore */ }
+ },
isQuitting: () => isQuitting,
log: createLogger('ghost-panel-window-controller'),
});
@@ -2013,6 +2020,8 @@ ipcMain.handle('app-menu:set-locale', (_event, locale: unknown): { ok: true } =>
setSelectionContextMenuLocale(currentApplicationMenuLocale);
setMainLocale(currentApplicationMenuLocale);
resourceUsageWindowController.setLocale(currentApplicationMenuLocale);
+ rsbWindowController.setLocale(currentApplicationMenuLocale);
+ ghostPanelWindowsController.setLocale(currentApplicationMenuLocale);
refreshGhostLocalization();
const mainWindow = mainWindowRef && !mainWindowRef.isDestroyed() ? mainWindowRef : null;
if (mainWindow) {
@@ -2738,6 +2747,8 @@ const createWindow = () => {
resourceUsagePrewarmTimer = null;
}
resourceUsageWindowController.destroyWindow();
+ rsbWindowController.destroyWindow();
+ ghostPanelWindowsController.destroyAllWindows();
if (mainWindowRef === mainWindow) mainWindowRef = null;
setDeepLinkMainWindow(null);
});
@@ -2813,6 +2824,10 @@ const createWindow = () => {
currentApplicationMenuLocale ?? getPreferredApplicationLocale(),
);
resourceUsageWindowController.prewarm();
+ // 右侧栏子窗口预热:复刻资源用量窗口模式,主窗口可见后后台创建
+ // 隐藏 BrowserWindow 并加载轻量 renderer,后续 detach 点击仅 show+focus。
+ rsbWindowController.prewarm();
+ // 插件面板保持按需创建:分离状态不跨重启恢复,多实例也不在启动期全量预热。
}, 1_500);
resourceUsagePrewarmTimer.unref?.();
// 日志上报的启动补传:采集 + 脱敏是同步的重活,必须让主窗口先出来(内部再延迟 15s,
@@ -7119,6 +7134,8 @@ onQuit(
);
onQuit('auth-manager', () => authManager.dispose(), 'sync');
onQuit('resource-usage-window', () => resourceUsageWindowController.dispose(), 'sync');
+onQuit('rsb-window', () => rsbWindowController.dispose(), 'sync');
+onQuit('ghost-panel-windows', () => ghostPanelWindowsController.dispose(), 'sync');
onQuit('app-badge-clear', () => clearAllSessionAttention(), 'sync');
onQuit('session-drag-preview', () => disposeSessionDragPreview(), 'sync');
// 自带 adb 的常驻 server 守护进程随退出收掉(fire-and-forget detached spawn,
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
index f0b0fbb8c3..d33ff757bb 100644
--- a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
@@ -1,11 +1,9 @@
-// GhostPanelWindowsController 状态机单测(纯 DI,不 mock electron):
-// - setDetached(true) 开窗 + 落盘 + 广播;两个 ghost 互不影响
-// - 用户关窗(closed 事件)清标志 = 回停靠;app 退出路径保留标志供重启恢复
-// - open 资格不符(卸载/停用/tab 形态)→ 清条目不开窗
-// - reconcile:卸载删条目并收窗;停用清标志并收窗
+// GhostPanelWindowsController lifecycle state-machine tests (DI only, no electron).
+// Covers: prewarm, hide-reuse close, setDetached(false)=dispose, two-phase ready,
+// multi-instance isolation, reconcile cleanup, crash recovery, sender guard.
import { describe, expect, it, vi } from 'vitest';
-import type { BrowserWindow } from 'electron';
+import type { BrowserWindow, WebContents } from 'electron';
import type { GhostPanelWindowsState } from '../../../shared/ghostPanelWindow.js';
import {
@@ -17,35 +15,76 @@ import type { InstalledGhost, GhostManifest } from '../../../shared/ghost.js';
interface FakeWindow {
on: ReturnType<typeof vi.fn>;
close: ReturnType<typeof vi.fn>;
+ destroy: ReturnType<typeof vi.fn>;
+ hide: ReturnType<typeof vi.fn>;
show: ReturnType<typeof vi.fn>;
focus: ReturnType<typeof vi.fn>;
restore: ReturnType<typeof vi.fn>;
isMinimized: () => boolean;
+ isVisible: () => boolean;
isDestroyed: () => boolean;
destroyed: boolean;
+ visible: boolean;
+ webContents: {
+ id: number;
+ on: ReturnType<typeof vi.fn>;
+ isDestroyed: () => boolean;
+ };
emitClosed: () => void;
+ emitWindowEvent: (event: string, ...args: unknown[]) => void;
+ emitWebContentsEvent: (event: string, ...args: unknown[]) => void;
+ _id: number;
}
+let nextId = 1;
function fakeWindow(): FakeWindow {
- const listeners = new Map<string, () => void>();
+ const id = nextId++;
+ const winListeners = new Map<string, (...args: unknown[]) => void>();
+ const wcListeners = new Map<string, (...args: unknown[]) => void>();
+ let destroyed = false;
+ let visible = false;
+ const wcOn = vi.fn((event: string, cb: (...args: unknown[]) => void) => {
+ wcListeners.set(event, cb);
+ });
const win: FakeWindow = {
- on: vi.fn((event: string, cb: () => void) => {
- listeners.set(event, cb);
+ on: vi.fn((event: string, cb: (...args: unknown[]) => void) => {
+ winListeners.set(event, cb);
}),
close: vi.fn(() => {
- win.destroyed = true;
- listeners.get('closed')?.();
+ let prevented = false;
+ winListeners.get('close')?.({ preventDefault: () => { prevented = true; } });
+ if (prevented) return;
+ destroyed = true;
+ visible = false;
+ winListeners.get('closed')?.();
}),
- show: vi.fn(),
+ destroy: vi.fn(() => { destroyed = true; visible = false; winListeners.get('closed')?.(); }),
+ hide: vi.fn(() => { visible = false; }),
+ show: vi.fn(() => { visible = true; }),
focus: vi.fn(),
restore: vi.fn(),
isMinimized: () => false,
- isDestroyed: () => win.destroyed,
+ isVisible: () => visible,
+ isDestroyed: () => destroyed,
destroyed: false,
+ visible: false,
+ webContents: {
+ id,
+ on: wcOn,
+ isDestroyed: () => destroyed,
+ },
emitClosed: () => {
- win.destroyed = true;
- listeners.get('closed')?.();
+ destroyed = true;
+ visible = false;
+ winListeners.get('closed')?.();
},
+ emitWindowEvent: (event, ...args) => {
+ if (event === 'hide') visible = false;
+ if (event === 'show') visible = true;
+ winListeners.get(event)?.(...args);
+ },
+ emitWebContentsEvent: (event, ...args) => wcListeners.get(event)?.(...args),
+ _id: id,
};
return win;
}
@@ -72,6 +111,7 @@ function makeHarness(detachableIds: Set<string>) {
let quitting = false;
const created: Array<{ ghostId: string; win: FakeWindow }> = [];
const broadcasts: GhostPanelWindowsState[] = [];
+ const sends: Array<{ channel: string; payload: unknown }> = [];
const deps: GhostPanelWindowsControllerDeps = {
settings: {
@@ -80,9 +120,7 @@ function makeHarness(detachableIds: Set<string>) {
const base = entries[id] ?? { detached: false, lastOpen: false };
entries[id] = { ...base, ...patch };
},
- removeEntry: (id) => {
- delete entries[id];
- },
+ removeEntry: (id) => { delete entries[id]; },
},
createWindow: (ghostId) => {
const win = fakeWindow();
@@ -90,70 +128,302 @@ function makeHarness(detachableIds: Set<string>) {
return win as unknown as BrowserWindow;
},
isGhostDetachable: (id) => detachableIds.has(id),
- broadcastState: (s) => {
- broadcasts.push(s);
- },
+ broadcastState: (s) => { broadcasts.push(s); },
+ sendToWindow: (_win, channel, payload) => { sends.push({ channel, payload }); },
isQuitting: () => quitting,
- log: { info: vi.fn(), warn: vi.fn() },
+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
};
const controller = new GhostPanelWindowsController(deps);
return {
controller,
created,
broadcasts,
+ sends,
entries: () => entries,
- setEntries: (next: Record<string, { detached: boolean; lastOpen: boolean }>) => {
- entries = next;
- },
- setQuitting: (v: boolean) => {
- quitting = v;
+ setEntries: (next: Record<string, { detached: boolean; lastOpen: boolean }>) => { entries = next; },
+ setDetachable: (ghostId: string, detachable: boolean) => {
+ if (detachable) detachableIds.add(ghostId);
+ else detachableIds.delete(ghostId);
},
+ setQuitting: (v: boolean) => { quitting = v; },
};
}
-describe('GhostPanelWindowsController', () => {
- it('setDetached(true) 开窗 + 落盘 detached/lastOpen + 广播 open:true', () => {
+function markReady(controller: GhostPanelWindowsController, win: FakeWindow): void {
+ controller.markRendererReady(win.webContents as unknown as WebContents);
+ controller.markPresentationReady(win.webContents as unknown as WebContents);
+}
+
+describe('prewarm / open / close (hide-reuse)', () => {
+ it('prewarm creates hidden window without showing or focusing', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ expect(h.created).toHaveLength(1);
+ const win = h.created[0].win;
+ expect(win.show).not.toHaveBeenCalled();
+ expect(win.focus).not.toHaveBeenCalled();
+ expect(h.entries().a?.lastOpen).toBeUndefined(); // prewarm doesn't set lastOpen
+ });
+
+ it('open creates window + sets lastOpen + broadcasts', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.open('a');
+ expect(h.created).toHaveLength(1);
+ expect(h.entries().a).toEqual({ detached: true, lastOpen: true });
+ expect(h.broadcasts.length).toBeGreaterThan(0);
+ });
+
+ it('hot open on prewarmed+ready window shows + focuses immediately', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+
+ h.controller.open('a');
+ expect(win.show).toHaveBeenCalled();
+ expect(win.focus).toHaveBeenCalled();
+ expect(h.created).toHaveLength(1); // no second window
+ });
+
+ it('open waits for presentation-ready then shows', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.open('a');
+ const win = h.created[0].win;
+ // Not shown yet — renderer isn't ready
+ expect(win.show).not.toHaveBeenCalled();
+
+ // presentation-ready triggers show
+ h.controller.markPresentationReady(win.webContents as unknown as WebContents);
+ expect(win.show).toHaveBeenCalled();
+ expect(win.focus).toHaveBeenCalled();
+ });
+
+ it('close hides window without destroying', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.open('a');
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+
+ h.controller.close('a');
+ expect(win.hide).toHaveBeenCalled();
+ expect(win.isDestroyed()).toBe(false);
+ expect(h.entries().a?.lastOpen).toBe(false);
+ // detached preference preserved
+ expect(h.entries().a?.detached).toBe(true);
+ });
+
+ it('re-open after close reuses same window (hot path, no recreate)', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.open('a');
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+ h.controller.close('a');
+
+ win.show.mockClear();
+ h.controller.open('a');
+ expect(h.created).toHaveLength(1); // no new window created
+ expect(win.show).toHaveBeenCalled(); // reuse
+ });
+
+ it('native hide updates state and open shows the cached window again', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+ h.controller.open('a');
+
+ win.emitWindowEvent('hide');
+ expect(h.controller.getState().a?.open).toBe(false);
+
+ win.show.mockClear();
+ win.focus.mockClear();
+ h.controller.open('a');
+ expect(h.created).toHaveLength(1);
+ expect(win.show).toHaveBeenCalledOnce();
+ expect(win.focus).toHaveBeenCalledOnce();
+ expect(h.controller.getState().a?.open).toBe(true);
+ });
+
+ it('open repairs stale controller visibility using the native window state', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+ h.controller.open('a');
+
+ win.hide();
+ win.show.mockClear();
+ win.focus.mockClear();
+
+ h.controller.open('a');
+ expect(win.show).toHaveBeenCalledOnce();
+ expect(win.focus).toHaveBeenCalledOnce();
+ expect(h.controller.getState().a?.open).toBe(true);
+ });
+});
+
+describe('renderer navigation lifecycle', () => {
+ it('ignores same-document main-frame navigation such as hash routing', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+ h.controller.open('a');
+
+ win.hide.mockClear();
+ win.emitWebContentsEvent(
+ 'did-start-navigation',
+ {},
+ 'http://localhost:5173/?ghostPanelWindow=a#/ghost-panel-window',
+ true,
+ true,
+ );
+
+ expect(win.hide).not.toHaveBeenCalled();
+ expect(h.controller.getState().a?.open).toBe(true);
+ });
+
+ it('ignores child-frame navigation from the embedded ghost webview', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+ h.controller.open('a');
+
+ win.hide.mockClear();
+ win.emitWebContentsEvent(
+ 'did-start-navigation',
+ {},
+ 'cindy-ghost://a/panel.html',
+ false,
+ false,
+ );
+
+ expect(win.hide).not.toHaveBeenCalled();
+ expect(h.controller.getState().a?.open).toBe(true);
+ });
+
+ it('temporarily hides and restores for main-frame renderer navigation', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+ h.controller.open('a');
+
+ win.emitWebContentsEvent(
+ 'did-start-navigation',
+ {},
+ 'http://localhost:5173/?ghostPanelWindow=1#/ghost-panel-window/a',
+ false,
+ true,
+ );
+ expect(win.hide).toHaveBeenCalledOnce();
+ expect(h.controller.getState().a?.open).toBe(true);
+
+ markReady(h.controller, win);
+ expect(win.show).toHaveBeenCalledTimes(2);
+ expect(h.controller.getState().a?.open).toBe(true);
+ });
+});
+
+describe('setDetached', () => {
+ it('true: opens window + sets detached preference', () => {
const h = makeHarness(new Set(['a']));
const state = h.controller.setDetached('a', true);
- expect(h.created.map((c) => c.ghostId)).toEqual(['a']);
+ expect(h.created).toHaveLength(1);
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', () => {
+ it('false: disposes window + clears flags', () => {
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();
+ const win = h.created[0].win;
+ markReady(h.controller, win);
+
+ const state = h.controller.setDetached('a', false);
+ expect(win.isDestroyed()).toBe(true);
+ expect(h.entries().a).toEqual({ detached: false, lastOpen: false });
+ expect(state.a.open).toBe(false);
});
- it('两个 ghost 各开各窗、互不影响;setDetached(false) 只收自己的', () => {
+ it('false: only affects specified ghost, others untouched', () => {
const h = makeHarness(new Set(['a', 'b']));
h.controller.setDetached('a', true);
h.controller.setDetached('b', true);
- 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();
+ expect(state.a.open).toBe(false);
+ expect(state.b.open).toBe(true);
});
+});
+
+describe('native minimize', () => {
+ it('routes native minimize to the renderer bubble action', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.setDetached('a', true);
+ const win = h.created[0].win;
+
+ win.emitWindowEvent('minimize');
- it('用户关窗(closed):清两标志 = 回停靠;app 退出路径保留标志', () => {
+ expect(h.sends).toContainEqual({
+ channel: 'ghost-panel-window:minimize-requested',
+ payload: undefined,
+ });
+ });
+});
+
+describe('multi-instance isolation', () => {
+ it('two ghosts maintain independent windows', () => {
+ const h = makeHarness(new Set(['a', 'b']));
+ h.controller.prewarm('a');
+ h.controller.prewarm('b');
+ expect(h.created).toHaveLength(2);
+ const winA = h.created[0].win;
+ const winB = h.created[1].win;
+ markReady(h.controller, winA);
+ markReady(h.controller, winB);
+
+ h.controller.open('a');
+ expect(winA.show).toHaveBeenCalled();
+ expect(winB.show).not.toHaveBeenCalled();
+
+ h.controller.close('a');
+ expect(winA.hide).toHaveBeenCalled();
+ expect(winB.hide).not.toHaveBeenCalled();
+
+ h.controller.open('b');
+ expect(winB.show).toHaveBeenCalled();
+ });
+
+ it('setDetached(false) on one ghost does not affect another', () => {
const h = makeHarness(new Set(['a', 'b']));
h.controller.setDetached('a', true);
+ h.controller.setDetached('b', true);
+ h.controller.setDetached('a', false);
+ expect(h.created[0].win.isDestroyed()).toBe(true);
+ expect(h.created[1].win.isDestroyed()).toBe(false);
+ });
+});
+
+describe('closed event', () => {
+ it('user closes window via OS: clears flags', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.setDetached('a', true);
h.created[0].win.emitClosed();
expect(h.entries().a).toEqual({ detached: false, lastOpen: false });
+ });
+ it('app quitting: preserves detached/lastOpen', () => {
+ const h = makeHarness(new Set(['b']));
h.controller.setDetached('b', true);
h.setQuitting(true);
- h.created[1].win.emitClosed();
+ h.created[0].win.emitClosed();
expect(h.entries().b).toEqual({ detached: true, lastOpen: true });
});
+});
- it('open 资格不符(卸载/停用/tab)→ 清条目不开窗', () => {
+describe('open guard (non-detachable)', () => {
+ it('non-detachable plugin: prunes entry, no window', () => {
const h = makeHarness(new Set());
h.setEntries({ a: { detached: true, lastOpen: true } });
h.controller.open('a');
@@ -161,36 +431,135 @@ describe('GhostPanelWindowsController', () => {
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);
+ it('non-detachable plugin: disposes a stale prewarmed window', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const win = h.created[0].win;
+ h.setDetachable('a', false);
+ h.controller.open('a');
+ expect(win.isDestroyed()).toBe(true);
+ expect(h.created).toHaveLength(1);
+ });
- h.controller.reconcile([ghost('disabled', { enabled: false }), ghost('stays')]);
+ it('prewarm for non-detachable is no-op', () => {
+ const h = makeHarness(new Set());
+ h.controller.prewarm('nonexistent');
+ expect(h.created).toHaveLength(0);
+ });
+});
- expect(h.created[0].win.close).toHaveBeenCalled(); // gone(清单里消失)
- expect(h.created[1].win.close).toHaveBeenCalled(); // disabled
- expect(h.created[2].win.close).not.toHaveBeenCalled();
+describe('reconcile', () => {
+ it('uninstall: disposes window + removes entry', () => {
+ const h = makeHarness(new Set(['gone', 'stays']));
+ h.controller.setDetached('gone', true);
+ h.controller.setDetached('stays', true);
+ h.controller.reconcile([ghost('stays')]);
+ expect(h.created[0].win.isDestroyed()).toBe(true); // gone
+ expect(h.created[1].win.isDestroyed()).toBe(false); // stays
expect(h.entries().gone).toBeUndefined();
- expect(h.entries().disabled).toEqual({ detached: false, lastOpen: false });
expect(h.entries().stays).toEqual({ detached: true, lastOpen: true });
});
- it('reconcile:换成 tab 形态视同失去资格', () => {
+ it('disabled: disposes window + clears flags', () => {
+ const h = makeHarness(new Set(['disabled']));
+ h.controller.setDetached('disabled', true);
+ h.controller.reconcile([ghost('disabled', { enabled: false })]);
+ expect(h.created[0].win.isDestroyed()).toBe(true);
+ expect(h.entries().disabled).toEqual({ detached: false, lastOpen: false });
+ });
+
+ it('tab position: treated as non-detachable', () => {
const h = makeHarness(new Set(['a']));
h.controller.setDetached('a', true);
h.controller.reconcile([ghost('a', { position: 'tab' })]);
- expect(h.created[0].win.close).toHaveBeenCalled();
+ expect(h.created[0].win.isDestroyed()).toBe(true);
expect(h.entries().a).toEqual({ detached: false, lastOpen: false });
});
+});
+
+describe('two-phase ready + sender guard', () => {
+ it('markRendererReady from correct sender succeeds', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const win = h.created[0].win;
+ h.controller.markRendererReady(win.webContents as unknown as WebContents);
+ // slotForSender finds the slot
+ expect(h.controller.slotForSender(win.webContents as unknown as WebContents)).not.toBeNull();
+ });
+
+ it('markPresentationReady from wrong sender is no-op', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ const wrongSender = { id: 99999 } as unknown as WebContents;
+ h.controller.markPresentationReady(wrongSender);
+ // slotForSender returns null
+ expect(h.controller.slotForSender(wrongSender)).toBeNull();
+ });
+
+ it('getSidebarWebContents returns null for wrong ghostId', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.prewarm('a');
+ expect(h.controller.getSidebarWebContents('nonexistent')).toBeNull();
+ });
+});
+
+describe('crash recovery', () => {
+ it('render-process-gone invalidates window and rebuilds if pendingOpen', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.open('a');
+ const win1 = h.created[0].win;
+ win1.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });
+ expect(win1.isDestroyed()).toBe(true);
+ expect(h.created).toHaveLength(2); // auto-recovered
+ });
+
+ it('recovery is bounded per ghostId', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.open('a');
+ const win1 = h.created[0].win;
+ // Don't mark ready — simulate rapid crashes where renderer never stabilizes.
+ // Without presentationReady resetting the counter, each crash increments.
+ win1.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });
+ expect(h.created).toHaveLength(2); // auto-recovered once
+
+ const win2 = h.created[1].win;
+ win2.emitWebContentsEvent('render-process-gone', {}, { reason: 'killed' });
+ expect(h.created).toHaveLength(2); // no third window (quota exhausted)
+ });
- it('getState:无条目 ghost 不出现;开窗态 open:true', () => {
+ it('presentation-ready does not immediately reset the recovery quota', () => {
const h = makeHarness(new Set(['a']));
- expect(h.controller.getState()).toEqual({});
+ h.controller.open('a');
+ h.created[0].win.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });
+ const replacement = h.created[1].win;
+ markReady(h.controller, replacement);
+
+ replacement.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed-again' });
+ expect(h.created).toHaveLength(2);
+ });
+});
+
+describe('dispose', () => {
+ it('dispose destroys all windows', () => {
+ const h = makeHarness(new Set(['a', 'b']));
h.controller.setDetached('a', true);
- expect(h.controller.getState()).toEqual({
- a: { detached: true, lastOpen: true, open: true },
- });
+ h.controller.setDetached('b', true);
+ h.controller.dispose();
+ expect(h.created[0].win.isDestroyed()).toBe(true);
+ expect(h.created[1].win.isDestroyed()).toBe(true);
+ });
+
+ it('dispose is idempotent', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.setDetached('a', true);
+ h.controller.dispose();
+ h.controller.dispose(); // no throw
+ });
+
+ it('destroyAllWindows preserves detached preferences for a future main window', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.setDetached('a', true);
+ h.controller.destroyAllWindows();
+ expect(h.entries().a).toEqual({ detached: true, lastOpen: true });
});
});
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts
new file mode 100644
index 0000000000..53daae0271
--- /dev/null
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/preload-contract.test.ts
@@ -0,0 +1,93 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+const preloadPath = path.resolve(
+ process.cwd().endsWith(`${path.sep}apps${path.sep}desktop`)
+ ? process.cwd()
+ : path.join(process.cwd(), 'apps', 'desktop'),
+ 'src/preload/ghostPanelWindowPreload.ts',
+);
+
+const source = readFileSync(preloadPath, 'utf8').replace(/\r\n/g, '\n');
+
+function balancedObject(start: number): string {
+ const open = source.indexOf('{', start);
+ let depth = 0;
+ let quote = '';
+ let escaped = false;
+ for (let i = open; i < source.length; i += 1) {
+ const char = source[i];
+ if (quote) {
+ if (escaped) escaped = false;
+ else if (char === '\\') escaped = true;
+ else if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'" || char === '`') {
+ quote = char;
+ } else if (char === '{') {
+ depth += 1;
+ } else if (char === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(open + 1, i);
+ }
+ }
+ return '';
+}
+
+function objectBody(name: string): string {
+ const match = new RegExp(`(?:^|\\n)[ \\t]*${name}[ \\t]*:[ \\t]*\\{`, 'm').exec(source);
+ return match ? balancedObject(match.index + match[0].length - 1) : '';
+}
+
+function keys(body: string): string[] {
+ return [...body.matchAll(/^([ \t]*)([A-Za-z_$][\w$]*)[ \t]*:/gm)]
+ .filter((match, _, all) => match[1].length === Math.min(...all.map((item) => item[1].length)))
+ .map((match) => match[2]);
+}
+
+const topLevel = keys(balancedObject(source.indexOf("contextBridge.exposeInMainWorld('electronAPI'")));
+const ghostPanelWindow = keys(objectBody('ghostPanelWindow'));
+const ghosts = keys(objectBody('ghosts'));
+
+describe('ghost panel preload contract', () => {
+ it('exposes only the window chrome and media capabilities needed by the panel', () => {
+ expect(topLevel).toEqual(expect.arrayContaining([
+ 'platform', 'preferredSystemLocale', 'windowMinimize', 'windowMaximize', 'windowClose',
+ 'appearanceSettings', 'localThemes', 'appShortcuts', 'theme',
+ 'copyMediaToClipboard', 'showItemInFolder', 'cacheMediaForSession',
+ 'openMediaWithDefaultApp', 'saveMediaAs', 'ghostPanelWindow', 'ghosts',
+ ]));
+ });
+
+ it('does not expose unrelated privileged namespaces', () => {
+ expect(topLevel).not.toEqual(expect.arrayContaining([
+ 'maker', 'agent', 'voiceInput', 'login', 'auth', 'settings', 'updater', 'chat',
+ 'session', 'processMonitor', 'rightSidebarWindow', 'rsbBrowserBridge', 'deviceLink',
+ ]));
+ });
+
+ it('exposes the ghost panel lifecycle bridge', () => {
+ expect(ghostPanelWindow).toEqual(expect.arrayContaining([
+ 'getStateSync', 'getState', 'open', 'setDetached', 'onStateChanged',
+ 'rendererReady', 'presentationReady', 'onVisibilityChanged',
+ 'onMinimizeRequested',
+ ]));
+ });
+
+ it('exposes the panel runtime and unread bridge', () => {
+ expect(ghosts).toEqual(expect.arrayContaining([
+ 'listSync', 'reload', 'setEnabled', 'resolvePanelMedia', 'runtimeStates',
+ 'onChanged', 'onRuntimeChanged', 'onPreviewMedia', 'unreadSync', 'clearUnread',
+ 'onBadge', 'onUnreadSnapshot',
+ ]));
+ });
+
+ it('uses shared lifecycle channel constants', () => {
+ expect(source).toContain('GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL');
+ expect(source).toContain('GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL');
+ expect(source).toContain('GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL');
+ expect(source).toContain('GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL');
+ });
+});
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/settings-store.test.ts
index df54f0b5fb..f65d767001 100644
--- 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
@@ -1,7 +1,43 @@
// normalizeGhostPanelWindowsSettings:坏数据 fail-closed 清洗。
-import { describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
-import { normalizeGhostPanelWindowsSettings } from '../settings-store.js';
+const tmpUserData = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ghost-panel-window-settings-'));
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: (name: string) => {
+ if (name !== 'userData') throw new Error(`unexpected getPath(${name})`);
+ return tmpUserData;
+ },
+ },
+}));
+
+vi.mock('../../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: {
+ child: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+ },
+}));
+
+import {
+ normalizeGhostPanelWindowsSettings,
+ patchGhostPanelWindowEntry,
+ readGhostPanelWindowsSettings,
+ resetGhostPanelWindowSettingsForStartup,
+} from '../settings-store.js';
+
+const settingsFile = path.join(tmpUserData, 'ghost-panel-windows-settings.json');
+
+beforeEach(() => {
+ if (fs.existsSync(settingsFile)) fs.unlinkSync(settingsFile);
+ resetGhostPanelWindowSettingsForStartup();
+});
+
+afterEach(() => {
+ if (fs.existsSync(settingsFile)) fs.unlinkSync(settingsFile);
+});
describe('normalizeGhostPanelWindowsSettings', () => {
it('合法条目原样保留', () => {
@@ -32,3 +68,27 @@ describe('normalizeGhostPanelWindowsSettings', () => {
).toEqual({ windows: { good: { detached: false, lastOpen: true } } });
});
});
+
+describe('runtime state', () => {
+ it('每个插件的分离状态仅保存在当前进程内', () => {
+ patchGhostPanelWindowEntry('cindy-art', { detached: true, lastOpen: true });
+
+ expect(readGhostPanelWindowsSettings()).toEqual({
+ windows: { 'cindy-art': { detached: true, lastOpen: true } },
+ });
+ expect(fs.existsSync(settingsFile)).toBe(false);
+ });
+
+ it('startup 清空所有插件分离态并删除旧版本偏好文件', () => {
+ patchGhostPanelWindowEntry('cindy-art', { detached: true, lastOpen: true });
+ fs.writeFileSync(
+ settingsFile,
+ JSON.stringify({ windows: { 'cindy-art': { detached: true, lastOpen: true } } }),
+ );
+
+ resetGhostPanelWindowSettingsForStartup();
+
+ expect(readGhostPanelWindowsSettings()).toEqual({ windows: {} });
+ expect(fs.existsSync(settingsFile)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/ghost-panel-window/controller.ts b/apps/desktop/src/main/ghost-panel-window/controller.ts
index 8b6cf0458e..273e5abce8 100644
--- a/apps/desktop/src/main/ghost-panel-window/controller.ts
+++ b/apps/desktop/src/main/ghost-panel-window/controller.ts
@@ -1,33 +1,43 @@
/**
* GhostPanelWindowsController —— 插件停靠面板独立窗口的状态机(main 侧单例,
- * 依赖注入可测)。蓝本是 RsbWindowController,按 ghostId 多实例并做了减法:
- * 面板体只吃 manifest(广播全窗口可达),无需 ready 握手 / 上下文中继 / 命令队列。
+ * 依赖注入可测)。
*
- * 每个 ghostId 的三态(与 RSB 同构):
+ * 每 ghostId 三态(与 RSB 同构):
* A. detached=false —— 面板停靠在主窗布局树里
- * C. detached=true, 窗口打开 —— 面板活在独立窗口
- * (v1 关窗即回停靠,不保留"偏好开着但窗口收起"的 B 态;lastOpen 仅在
- * app 退出路径保留,供重启恢复。)
+ * C. detached=true, 窗口打开 —— 面板活在独立窗口(隐藏复用,紧接开/关只隐藏)
*
- * 职责:
- * - 每 ghost 窗口生命周期(重复 open = focus;closed 区分用户关窗 vs app 退出)
- * - 偏好 / lastOpen 落盘(settings-store),状态变化广播所有窗口
- * - reconcile:插件卸载/停用/换形态时收窗(卸载删条目;停用清标志,
- * 避免"面板既不停靠也开不了窗"的死角)
+ * 生命周期基线对齐 PR #2434 ResourceUsageWindowController 与右侧栏窗口改造:
+ * - 惰性预热:首次 open/setDetached(true) 创建隐藏窗口,presentation-ready 后展示
+ * - 本次运行期按需创建:首次分离后隐藏复用,客户端重启后回到主窗口
+ * - 双阶段就绪握手(renderer-ready → presentation-ready),5s 超时展示壳
+ * - 隐藏复用:普通关窗只 hide(setDetached(false) 才真正 destroy)
+ * - 崩溃恢复有界(每 ghostId 独立计数)
+ * - 多 ghostId 实例间状态隔离
+ * - reconcile:插件卸载/停用/换形态时 dispose 对应窗口
*/
-import type { BrowserWindow } from 'electron';
+import type { BrowserWindow, WebContents } from 'electron';
import type {
GhostPanelWindowEntryState,
GhostPanelWindowsState,
} from '../../shared/ghostPanelWindow.js';
+import {
+ GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL,
+ GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL,
+ GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL,
+ GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL,
+ GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL,
+ GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL,
+} from '../../shared/ghostPanelWindow.js';
+import type { SupportedLocale } from '../../shared/locale.js';
import type { InstalledGhost } from '../../shared/ghost.js';
import type { GhostPanelWindowsSettings } from './settings-store.js';
interface ControllerLogger {
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
+ error(message: string, ...args: unknown[]): void;
}
export interface GhostPanelWindowsControllerDeps {
@@ -36,94 +46,213 @@ export interface GhostPanelWindowsControllerDeps {
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;
+ /** main → renderer push(仅子窗口)。 */
+ sendToWindow: (win: BrowserWindow, channel: string, payload: unknown) => void;
isQuitting: () => boolean;
log: ControllerLogger;
}
+const DEFAULT_OPEN_TIMEOUT_MS = 5000;
+const DEFAULT_RECOVERY_STABILITY_MS = 30_000;
+const MAX_AUTOMATIC_RECOVERY_ATTEMPTS = 1;
+
+interface WindowSlot {
+ win: BrowserWindow;
+ rendererReady: boolean;
+ presentationReady: boolean;
+ visible: boolean;
+ pendingOpen: boolean;
+ destroyingWindow: boolean;
+ openTimeout: NodeJS.Timeout | null;
+ recoveryStabilityTimeout: NodeJS.Timeout | null;
+ automaticRecoveryAttempts: number;
+}
+
export class GhostPanelWindowsController {
- private readonly windows = new Map<string, BrowserWindow>();
- /** close() 到 closed 事件之间窗口仍未 destroyed,不能继续当活窗。 */
- private readonly closingIds = new Set<string>();
+ private readonly slots = new Map<string, WindowSlot>();
+ private disposed = false;
+ private locale: SupportedLocale | null = null;
constructor(private readonly deps: GhostPanelWindowsControllerDeps) {}
+ // ══════════════════════════════════════════════════════════════════════
+ // 公共接口
+ // ══════════════════════════════════════════════════════════════════════
+
getState(): GhostPanelWindowsState {
const out: GhostPanelWindowsState = {};
const { windows } = this.deps.settings.read();
for (const [id, entry] of Object.entries(windows)) {
out[id] = this.entryState(id, entry);
}
- // 运行时开着但条目被清了的窗口(理论不存在,防御性合入)
- for (const id of this.windows.keys()) {
+ for (const id of this.slots.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;
+ /**
+ * 后台预热指定 ghostId:创建隐藏窗口并加载 renderer,不改变用户焦点。
+ * 可在当前运行期提前为即将打开的插件面板准备 renderer。
+ */
+ prewarm(ghostId: string): void {
+ if (this.disposed) return;
+ if (!this.deps.isGhostDetachable(ghostId)) return;
+ this.ensureSlot(ghostId);
+ }
+
+ setLocale(locale: SupportedLocale): void {
+ this.locale = locale;
+ for (const slot of this.slots.values()) {
+ if (slot.win.isDestroyed()) continue;
+ try {
+ slot.win.webContents.send(GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL, locale);
+ } catch {
+ // Window may be tearing down.
+ }
}
+ }
+
+ /**
+ * 幂等打开:热窗口(presentationReady)立即显示;冷窗口等待首份内容。
+ * 资格不符则清条目防陈年状态复活。
+ */
+ open(ghostId: string): void {
+ if (this.disposed) return;
if (!this.deps.isGhostDetachable(ghostId)) {
- this.deps.log.warn('ghost not detachable, pruning window entry', { ghostId });
+ this.deps.log.warn('ghost not detachable, pruning entry', { ghostId });
+ const staleSlot = this.slots.get(ghostId);
+ if (staleSlot && !staleSlot.destroyingWindow) this.disposeSlot(ghostId, staleSlot);
this.deps.settings.removeEntry(ghostId);
this.broadcast();
return;
}
- const win = this.deps.createWindow(ghostId);
- this.windows.set(ghostId, win);
- this.closingIds.delete(ghostId);
- win.on('closed', () => this.onClosed(ghostId));
+
+ const existing = this.slots.get(ghostId);
+ if (existing) {
+ if (
+ existing.visible &&
+ existing.win.isVisible() &&
+ !existing.win.isMinimized()
+ ) {
+ existing.win.focus();
+ return;
+ }
+ if (existing.presentationReady) {
+ this.showAndFocus(ghostId, existing);
+ return;
+ }
+ existing.pendingOpen = true;
+ this.scheduleOpenFallback(ghostId, existing);
+ this.deps.settings.patchEntry(ghostId, { detached: true, lastOpen: true });
+ this.broadcast();
+ return;
+ }
+
+ const slot = this.ensureSlot(ghostId);
+ if (!slot) return;
+ slot.pendingOpen = true;
+ if (slot.presentationReady) {
+ this.showAndFocus(ghostId, slot);
+ } else {
+ this.scheduleOpenFallback(ghostId, slot);
+ }
this.deps.settings.patchEntry(ghostId, { detached: true, lastOpen: true });
this.broadcast();
- this.deps.log.info('ghost panel window opened', { ghostId });
}
- /** 写偏好;true 附带开窗,false 附带关窗(= 回停靠)。返回新 state 供 invoke 直接回。 */
+ /** 普通关窗只隐藏(保留 renderer,供下次瞬时恢复)。偏好保持 detached:true。 */
+ close(ghostId: string): void {
+ const slot = this.slots.get(ghostId);
+ if (!slot) {
+ // 窗口不存在,但仍需落盘 lastOpen=false
+ this.deps.settings.patchEntry(ghostId, { lastOpen: false });
+ this.broadcast();
+ return;
+ }
+ this.hideWindow(ghostId, slot);
+ }
+
+ /** 写偏好;true 开窗,false 真正销毁窗口(= 回停靠)。 */
setDetached(ghostId: string, next: boolean): GhostPanelWindowsState {
if (next) {
- this.open(ghostId); // open 内部落 detached/lastOpen 并广播
+ this.open(ghostId);
} 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();
+ const slot = this.slots.get(ghostId);
+ if (slot && !slot.destroyingWindow) {
+ this.disposeSlot(ghostId, slot);
}
+ this.broadcast();
}
- // open/close 的幂等分支可能没广播(如重复 setDetached(true)),兜底广播必达。
- this.broadcast();
return this.getState();
}
- /**
- * 与"当前已装清单"对齐(broadcastGhostsChanged 观察者):
- * 失去抽离资格(卸载/停用/换 tab 形态)→ 收窗;卸载删条目,其余清标志
- * ——面板回停靠(或随卸载消失),不留"够不着"的死角。
- */
+ // ── 双阶段就绪 ──────────────────────────────────────────────────────
+
+ markRendererReady(sender: WebContents): void {
+ const entry = this.slotForSender(sender);
+ if (!entry) return;
+ entry.slot.rendererReady = true;
+ if (this.locale) {
+ try {
+ sender.send(GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL, this.locale);
+ } catch {
+ // Renderer may be tearing down.
+ }
+ }
+ }
+
+ markPresentationReady(sender: WebContents): void {
+ const entry = this.slotForSender(sender);
+ if (!entry) return;
+ entry.slot.presentationReady = true;
+ this.scheduleRecoveryStabilityReset(entry.slot);
+ if (entry.slot.pendingOpen) {
+ this.showAndFocus(entry.ghostId, entry.slot);
+ }
+ }
+
+ /** 查找 sender 对应的 ghostId+slot;非本 controller 管理的窗口返回 null。 */
+ slotForSender(sender: WebContents): { ghostId: string; slot: WindowSlot } | null {
+ for (const [id, slot] of this.slots) {
+ if (slot.win && !slot.win.isDestroyed() && slot.win.webContents === sender) {
+ return { ghostId: id, slot };
+ }
+ }
+ return null;
+ }
+
+ getSidebarWebContents(ghostId: string): WebContents | null {
+ const slot = this.slots.get(ghostId);
+ if (!slot || slot.win.isDestroyed()) return null;
+ return slot.win.webContents;
+ }
+
+ requestClose(sender: WebContents): void {
+ const entry = this.slotForSender(sender);
+ if (!entry) return;
+ this.deps.sendToWindow(entry.slot.win, GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL, undefined);
+ }
+
+ resolveCloseRequest(sender: WebContents, approved: boolean): void {
+ const entry = this.slotForSender(sender);
+ // The renderer owns the confirmation and performs setEnabled(false) after
+ // approval. Keep the window visible until that operation succeeds so an IPC
+ // failure does not silently hide an enabled plugin.
+ if (!entry || !approved) return;
+ }
+
+ // ── reconcile ──────────────────────────────────────────────────────
+
reconcile(ghosts: InstalledGhost[]): void {
const byId = new Map(ghosts.map((g) => [g.manifest.id, g]));
const knownIds = new Set([
...Object.keys(this.deps.settings.read().windows),
- ...this.windows.keys(),
+ ...this.slots.keys(),
]);
let changed = false;
for (const id of knownIds) {
@@ -134,10 +263,10 @@ export class GhostPanelWindowsController {
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();
+
+ const slot = this.slots.get(id);
+ if (slot && !slot.destroyingWindow) {
+ this.disposeSlot(id, slot);
}
if (ghost === undefined) {
this.deps.settings.removeEntry(id);
@@ -150,30 +279,247 @@ export class GhostPanelWindowsController {
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) };
+ // ── 生命周期 ────────────────────────────────────────────────────────
+
+ /** 主窗口销毁时回收所有隐藏窗口;controller 仍可随下一扇主窗重新预热。 */
+ destroyAllWindows(): void {
+ for (const [id, slot] of this.slots) {
+ this.clearTimeouts(slot);
+ if (!slot.win.isDestroyed()) {
+ slot.destroyingWindow = true;
+ try { slot.win.destroy(); } catch { /* already gone */ }
+ }
+ }
+ this.slots.clear();
}
- private isOpen(ghostId: string): boolean {
- const win = this.windows.get(ghostId);
- return win !== undefined && !this.closingIds.has(ghostId) && !win.isDestroyed();
+ /** 应用退出时永久停止并同步销毁所有缓存窗口。 */
+ dispose(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.destroyAllWindows();
+ }
+
+ // ══════════════════════════════════════════════════════════════════════
+ // 内部:窗口创建与生命周期
+ // ══════════════════════════════════════════════════════════════════════
+
+ private ensureSlot(ghostId: string): WindowSlot | null {
+ const existing = this.slots.get(ghostId);
+ if (existing && !existing.win.isDestroyed()) return existing;
+
+ let win: BrowserWindow;
+ try {
+ win = this.deps.createWindow(ghostId);
+ } catch (error) {
+ this.deps.log.warn('ghost panel window creation failed', {
+ ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ }
+
+ const slot: WindowSlot = {
+ win,
+ rendererReady: false,
+ presentationReady: false,
+ visible: false,
+ pendingOpen: false,
+ destroyingWindow: false,
+ openTimeout: null,
+ recoveryStabilityTimeout: null,
+ automaticRecoveryAttempts: 0,
+ };
+ this.slots.set(ghostId, slot);
+
+ win.on('close', (event) => {
+ if (slot.destroyingWindow || this.disposed) return;
+ event.preventDefault();
+ this.requestClose(win.webContents);
+ });
+ win.on('minimize', () => {
+ if (slot.destroyingWindow || this.disposed) return;
+ // 原生标题栏(macOS 黄灯)与系统级最小化入口也必须复用 Ghost 气泡语义。
+ // 先恢复,避免在 renderer 完成 setDetached(false) 前短暂留在 Dock/任务栏。
+ if (win.isMinimized()) win.restore();
+ this.deps.sendToWindow(win, GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL, undefined);
+ });
+ win.on('show', () => this.onNativeVisibilityChanged(ghostId, slot, true));
+ win.on('hide', () => this.onNativeVisibilityChanged(ghostId, slot, false));
+ win.on('closed', () => this.onClosed(ghostId, slot));
+ win.webContents.on('did-start-navigation', (_event, _url, isInPlace, isMainFrame) => {
+ if (isMainFrame && !isInPlace) this.onRendererReloadStarted(ghostId, slot);
+ });
+ win.webContents.on(
+ 'did-fail-load',
+ (_event, errorCode, errorDescription, _validatedUrl, isMainFrame) => {
+ if (isMainFrame && errorCode !== -3) {
+ this.invalidateSlot(ghostId, slot, `load failed (${errorCode}): ${errorDescription}`);
+ }
+ },
+ );
+ win.webContents.on('render-process-gone', (_event, details) => {
+ this.invalidateSlot(ghostId, slot, `renderer process gone: ${details.reason}`);
+ });
+
+ return slot;
}
- private onClosed(ghostId: string): void {
- this.windows.delete(ghostId);
- this.closingIds.delete(ghostId);
- // app 退出路径:保留 detached/lastOpen 供下次启动恢复,也不广播(窗口都在销毁)
+ private showAndFocus(ghostId: string, slot: WindowSlot): void {
+ this.clearOpenTimeout(slot);
+ slot.pendingOpen = false;
+ if (slot.win.isMinimized()) slot.win.restore();
+ slot.win.show();
+ slot.win.focus();
+ slot.visible = true;
+ this.deps.sendToWindow(slot.win, GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible: true });
+ this.broadcast();
+ }
+
+ private hideWindow(ghostId: string, slot: WindowSlot): void {
+ this.clearOpenTimeout(slot);
+ slot.pendingOpen = false;
+ if (slot.win.isVisible()) slot.win.hide();
+ slot.visible = false;
+ try {
+ this.deps.sendToWindow(slot.win, GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible: false });
+ } catch { /* window may be torn down */ }
+ this.deps.settings.patchEntry(ghostId, { lastOpen: false });
+ this.broadcast();
+ this.deps.log.info('ghost panel window hidden', { ghostId });
+ }
+
+ private onNativeVisibilityChanged(
+ ghostId: string,
+ slot: WindowSlot,
+ visible: boolean,
+ ): void {
+ if (
+ this.slots.get(ghostId) !== slot ||
+ slot.win.isDestroyed() ||
+ slot.destroyingWindow ||
+ this.disposed
+ ) {
+ return;
+ }
+ if (slot.visible === visible && !slot.pendingOpen) return;
+ slot.visible = visible;
+ if (visible) slot.pendingOpen = false;
+ try {
+ this.deps.sendToWindow(slot.win, GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible });
+ } catch {
+ // Native visibility can change while the renderer is tearing down.
+ }
+ this.broadcast();
+ }
+
+ private onClosed(ghostId: string, slot: WindowSlot): void {
+ this.clearTimeouts(slot);
+ if (this.slots.get(ghostId) !== slot) return;
+ this.slots.delete(ghostId);
+ if (slot.destroyingWindow) return;
if (this.deps.isQuitting()) return;
- // 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 });
+ this.deps.log.info('ghost panel window closed (destroyed)', { ghostId });
+ }
+
+ // ── 超时 ────────────────────────────────────────────────────────────
+
+ private scheduleOpenFallback(ghostId: string, slot: WindowSlot): void {
+ this.clearOpenTimeout(slot);
+ slot.openTimeout = setTimeout(() => {
+ slot.openTimeout = null;
+ if (slot.win.isDestroyed() || !slot.pendingOpen) return;
+ if (!slot.visible) this.showAndFocus(ghostId, slot);
+ }, DEFAULT_OPEN_TIMEOUT_MS);
+ slot.openTimeout.unref?.();
+ }
+
+ private clearOpenTimeout(slot: WindowSlot): void {
+ if (!slot.openTimeout) return;
+ clearTimeout(slot.openTimeout);
+ slot.openTimeout = null;
+ }
+
+ private scheduleRecoveryStabilityReset(slot: WindowSlot): void {
+ if (slot.automaticRecoveryAttempts === 0) return;
+ if (slot.recoveryStabilityTimeout) {
+ clearTimeout(slot.recoveryStabilityTimeout);
+ }
+ slot.recoveryStabilityTimeout = setTimeout(() => {
+ slot.recoveryStabilityTimeout = null;
+ if (slot.win.isDestroyed() || !slot.presentationReady) return;
+ slot.automaticRecoveryAttempts = 0;
+ }, DEFAULT_RECOVERY_STABILITY_MS);
+ slot.recoveryStabilityTimeout.unref?.();
+ }
+
+ // ── 崩溃恢复 ────────────────────────────────────────────────────────
+
+ private onRendererReloadStarted(_ghostId: string, slot: WindowSlot): void {
+ if (slot.win.isDestroyed()) return;
+ const shouldRestore = slot.visible || slot.pendingOpen;
+ if (shouldRestore) slot.pendingOpen = true;
+ if (slot.visible) slot.win.hide();
+ slot.rendererReady = false;
+ slot.presentationReady = false;
+ if (shouldRestore) {
+ this.scheduleOpenFallback(_ghostId, slot);
+ }
+ }
+
+ private invalidateSlot(ghostId: string, slot: WindowSlot, reason: string): void {
+ if (slot.win.isDestroyed()) return;
+ const reopen = slot.pendingOpen || slot.visible;
+ this.deps.log.warn('ghost panel cached window invalidated', { ghostId, reason, reopen });
+ this.disposeSlot(ghostId, slot);
+ if (!reopen || this.disposed) return;
+ if (slot.automaticRecoveryAttempts >= MAX_AUTOMATIC_RECOVERY_ATTEMPTS) {
+ this.deps.log.error('ghost panel automatic recovery exhausted', { ghostId, reason });
+ return;
+ }
+ // 重建并重新 open:恢复额度在 presentationReady 时重置
+ const replacement = this.ensureSlot(ghostId);
+ if (!replacement) return;
+ replacement.automaticRecoveryAttempts = slot.automaticRecoveryAttempts + 1;
+ replacement.pendingOpen = true;
+ this.scheduleOpenFallback(ghostId, replacement);
+ this.deps.settings.patchEntry(ghostId, { detached: true, lastOpen: true });
+ this.broadcast();
+ }
+
+ // ── 销毁 ────────────────────────────────────────────────────────────
+
+ private disposeSlot(ghostId: string, slot: WindowSlot): void {
+ this.clearTimeouts(slot);
+ this.slots.delete(ghostId);
+ slot.destroyingWindow = true;
+ try {
+ if (!slot.win.isDestroyed()) slot.win.destroy();
+ } catch { /* already gone */ }
+ }
+
+ private clearTimeouts(slot: WindowSlot): void {
+ if (slot.openTimeout) { clearTimeout(slot.openTimeout); slot.openTimeout = null; }
+ if (slot.recoveryStabilityTimeout) { clearTimeout(slot.recoveryStabilityTimeout); slot.recoveryStabilityTimeout = null; }
+ }
+
+ // ── 查询 ────────────────────────────────────────────────────────────
+
+ private entryState(
+ ghostId: string,
+ entry: { detached: boolean; lastOpen: boolean },
+ ): GhostPanelWindowEntryState {
+ return { detached: entry.detached, lastOpen: entry.lastOpen, open: this.isOpen(ghostId) };
+ }
+
+ private isOpen(ghostId: string): boolean {
+ const slot = this.slots.get(ghostId);
+ if (!slot || slot.win.isDestroyed()) return false;
+ return slot.visible || slot.pendingOpen;
}
private broadcast(): void {
diff --git a/apps/desktop/src/main/ghost-panel-window/ipc.ts b/apps/desktop/src/main/ghost-panel-window/ipc.ts
index 329315f83f..a0056e66e5 100644
--- a/apps/desktop/src/main/ghost-panel-window/ipc.ts
+++ b/apps/desktop/src/main/ghost-panel-window/ipc.ts
@@ -16,6 +16,11 @@ 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 {
+ GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL,
+ GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL,
+ GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL,
+} from '../../shared/ghostPanelWindow.js';
import type { GhostPanelWindowsController } from './controller.js';
const log = createLogger('ghost-panel-window-ipc');
@@ -60,4 +65,24 @@ export function registerGhostPanelWindowIpc(controller: GhostPanelWindowsControl
}
event.returnValue = controller.getState();
});
+
+ // ── 双阶段就绪握手(对齐 §3.1 基线) ────────────────────────────────
+
+ ipcMain.handle(GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL, (event) => {
+ assertTrustedAppRendererEvent(event);
+ controller.markRendererReady(event.sender);
+ });
+
+ ipcMain.handle(GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL, (event) => {
+ assertTrustedAppRendererEvent(event);
+ controller.markPresentationReady(event.sender);
+ });
+
+ ipcMain.handle(GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL, (event, approved: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof approved !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'approved required (boolean)');
+ }
+ controller.resolveCloseRequest(event.sender, approved);
+ });
}
diff --git a/apps/desktop/src/main/ghost-panel-window/registry.ts b/apps/desktop/src/main/ghost-panel-window/registry.ts
new file mode 100644
index 0000000000..d86ac47634
--- /dev/null
+++ b/apps/desktop/src/main/ghost-panel-window/registry.ts
@@ -0,0 +1,14 @@
+/**
+ * Ghost panel windows are independently recoverable auxiliary renderers.
+ * Keep their WebContents ids registered so a crash cannot take down the app.
+ */
+
+const ghostPanelWebContentsIds = new Set<number>();
+
+export function markGhostPanelWebContentsId(id: number): void {
+ ghostPanelWebContentsIds.add(id);
+}
+
+export function isGhostPanelWebContentsId(id: number): boolean {
+ return ghostPanelWebContentsIds.has(id);
+}
diff --git a/apps/desktop/src/main/ghost-panel-window/settings-store.ts b/apps/desktop/src/main/ghost-panel-window/settings-store.ts
index 5aca781ed1..92258a8fe0 100644
--- a/apps/desktop/src/main/ghost-panel-window/settings-store.ts
+++ b/apps/desktop/src/main/ghost-panel-window/settings-store.ts
@@ -1,22 +1,17 @@
/**
- * ghost-panel-window settings-store —— 「插件面板在独立窗口中显示」的持久化。
+ * ghost-panel-window 进程内状态。
*
- * File: <userData>/ghost-panel-windows-settings.json
- *
- * 形如 { windows: { <ghostId>: { detached, lastOpen } } }。语义对照
- * right-sidebar-window/settings-store.ts(同一 override 模型、同只由 main 的
- * controller 写),差异是按 ghostId 多条:每个插件面板各自记偏好与恢复状态。
- * - detached: **偏好**。用户点了该面板的「独立窗口」按钮;
- * - lastOpen: **状态**。退出时该窗口是否开着,供下次启动恢复。
- * 没有条目 = 从未抽离(等价两个 false)。
+ * 每个 ghostId 的 detached / lastOpen 只服务当前客户端进程,用于窗口状态机和隐藏复用;
+ * 客户端重启后所有插件面板一律回到主窗口。启动时还会删除旧版本留下的分离偏好文件。
+ * 窗口尺寸与位置由独立的 window-state 文件管理,不受这里影响。
*/
import { app } from 'electron';
+import fs from 'node:fs';
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');
@@ -29,7 +24,7 @@ export interface GhostPanelWindowsSettings {
windows: Record<string, GhostPanelWindowEntrySettings>;
}
-const DEFAULTS: GhostPanelWindowsSettings = { windows: {} };
+let runtimeSettings: GhostPanelWindowsSettings = { windows: {} };
function settingsFilePath(): string {
return path.join(app.getPath('userData'), 'ghost-panel-windows-settings.json');
@@ -51,16 +46,8 @@ export function normalizeGhostPanelWindowsSettings(raw: unknown): GhostPanelWind
return { windows };
}
-const store = createOverrideSettingsFile<GhostPanelWindowsSettings>({
- filePath: settingsFilePath,
- defaults: DEFAULTS,
- normalize: normalizeGhostPanelWindowsSettings,
- log,
- label: 'ghost-panel-windows',
-});
-
export function readGhostPanelWindowsSettings(): GhostPanelWindowsSettings {
- return store.read();
+ return { windows: { ...runtimeSettings.windows } };
}
/** 单条 patch:writePatch 是浅合并,windows map 必须整体读改写。 */
@@ -68,16 +55,27 @@ export function patchGhostPanelWindowEntry(
ghostId: string,
patch: Partial<GhostPanelWindowEntrySettings>,
): void {
- const current = store.read().windows;
+ const current = runtimeSettings.windows;
const entry = current[ghostId] ?? { detached: false, lastOpen: false };
- store.writePatch({ windows: { ...current, [ghostId]: { ...entry, ...patch } } });
+ runtimeSettings = { windows: { ...current, [ghostId]: { ...entry, ...patch } } };
}
/** 删条目(卸载清理):不存在时为 no-op。 */
export function removeGhostPanelWindowEntry(ghostId: string): void {
- const current = store.read().windows;
+ const current = runtimeSettings.windows;
if (!(ghostId in current)) return;
const next = { ...current };
delete next[ghostId];
- store.writePatch({ windows: next });
+ runtimeSettings = { windows: next };
+}
+
+/** 新进程重置全部插件面板的分离状态,并清理旧版本遗留的持久化偏好。 */
+export function resetGhostPanelWindowSettingsForStartup(): void {
+ runtimeSettings = { windows: {} };
+ const legacyFile = settingsFilePath();
+ try {
+ fs.rmSync(legacyFile, { force: true });
+ } catch (err) {
+ log.warn('failed to remove legacy ghost-panel window settings', { legacyFile, err });
+ }
}
diff --git a/apps/desktop/src/main/ghost-panel-window/window.ts b/apps/desktop/src/main/ghost-panel-window/window.ts
index 248a01eec0..44a757aa22 100644
--- a/apps/desktop/src/main/ghost-panel-window/window.ts
+++ b/apps/desktop/src/main/ghost-panel-window/window.ts
@@ -22,6 +22,7 @@ import { readWindowBehaviorSettings } from '../window-behavior-settings-store.js
import { installExternalLinkGuards } from '../secondary-windows.js';
import { installSelectionContextMenu } from '../selection-context-menu.js';
import { applyAppearanceToWindow } from '../appearance-settings-ipc.js';
+import { markGhostPanelWebContentsId } from './registry.js';
const log = createLogger('ghost-panel-window');
@@ -58,7 +59,7 @@ export function createGhostPanelWindow(ghostId: string, title: string): BrowserW
acceptFirstMouse: !swallowActivationClick,
...platformOptions,
webPreferences: {
- preload: path.join(__dirname, 'preload.js'),
+ preload: path.join(__dirname, 'ghostPanelWindowPreload.js'),
spellcheck: false,
webviewTag: true,
// 安全规则 §3 全量显式项(新建窗口不吃默认值,逐项写明):
@@ -74,6 +75,7 @@ export function createGhostPanelWindow(ghostId: string, title: string): BrowserW
navigateOnDragDrop: false,
},
});
+ markGhostPanelWebContentsId(win.webContents.id);
markAppContentWindow(win);
applyAppearanceToWindow(win);
win.webContents.on('did-finish-load', () => {
@@ -85,8 +87,10 @@ export function createGhostPanelWindow(ghostId: string, title: string): BrowserW
installExternalLinkGuards(win);
+ // ready-to-show 不再直接 show();由 controller 的双阶段就绪握手控制展示时机。
+ // 窗口以 show:false 创建,首次显示由 controller 在 presentation-ready 后触发。
win.once('ready-to-show', () => {
- if (!win.isDestroyed()) win.show();
+ // no-op: 窗口由 controller 控制展示
});
const hash = '/ghost-panel-window';
diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.ts
index e1c00d006d..2b7210b53a 100644
--- a/apps/desktop/src/main/lifecycle.ts
+++ b/apps/desktop/src/main/lifecycle.ts
@@ -50,6 +50,8 @@ import { noteQuitDisposersCompleted, noteShutdownBegin } from './startup-diagnos
import { isGhostSandboxWebContentsId } from './cindy-brain/runtime/electronSandboxAdapter';
import { isRsbNativePopupWebContentsId } from './rsb-browser-bridge/native-popup-surfaces';
import { isResourceUsageWebContentsId } from './resource-usage-window/registry.js';
+import { isRsbWindowWebContentsId } from './right-sidebar-window/registry.js';
+import { isGhostPanelWebContentsId } from './ghost-panel-window/registry.js';
/**
* 瞬时网络错误的 wire payload (main → renderer)。code 永远存在 (Node 的 ErrnoException
@@ -661,6 +663,18 @@ export function installQuitHandler(timeoutMs = 2000): void {
);
return;
}
+ if (isRsbWindowWebContentsId(webContents.id)) {
+ log.warn(
+ `right sidebar render-process-gone (isolated, no shutdown): reason=${details.reason} exitCode=${details.exitCode}`,
+ );
+ return;
+ }
+ if (isGhostPanelWebContentsId(webContents.id)) {
+ log.warn(
+ `ghost panel render-process-gone (isolated, no shutdown): reason=${details.reason} exitCode=${details.exitCode}`,
+ );
+ return;
+ }
// arm-first(review P1):所有可隔离恢复的 renderer 分支在上面已 return,
// 走到这里必然退出。
armShutdownHardKillWatchdog();
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/controller.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/controller.test.ts
index fceb750670..dab598f7c1 100644
--- a/apps/desktop/src/main/right-sidebar-window/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/controller.test.ts
@@ -1,12 +1,13 @@
// RsbWindowController 状态机单测(纯 DI,不 mock electron):
-// - open / close / setDetached 的落盘 + 广播行为
-// - 用户关窗(closed 事件)在 quitting / 非 quitting 下 lastOpen 的差异
-// - ensureOpenForAutomation:非 detached no-op、开窗等 ready、超时、窗口先关
+// - prewarm / open / close / setDetached 的落盘 + 广播行为
+// - 双阶段就绪握手(renderer-ready → presentation-ready)
+// - 隐藏复用(close = hide, 不销毁; setDetached(false) = 真正 destroy)
+// - 崩溃恢复有界
// - getHostWebContents 三态(detached+open → 子窗;否则主窗)
-// - setContext 缓存 + 仅窗口开着时转发;routeCommand 原子裁决宿主并处理 deferred intent
+// - setContext 缓存 + 仅窗口活跃时转发;routeCommand 原子裁决宿主
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { BrowserWindow } from 'electron';
+import type { BrowserWindow, WebContents } from 'electron';
import { RsbWindowController, type RsbWindowControllerDeps } from '../controller.js';
import type { RsbWindowSettings } from '../settings-store.js';
@@ -14,52 +15,93 @@ import type { RsbWindowSettings } from '../settings-store.js';
interface FakeWindow {
on: ReturnType<typeof vi.fn>;
close: ReturnType<typeof vi.fn>;
+ destroy: ReturnType<typeof vi.fn>;
+ hide: ReturnType<typeof vi.fn>;
show: ReturnType<typeof vi.fn>;
focus: ReturnType<typeof vi.fn>;
restore: ReturnType<typeof vi.fn>;
isMinimized: () => boolean;
+ isVisible: () => boolean;
isDestroyed: () => boolean;
destroyed: boolean;
- webContents: { id: number };
- /** 测试用:触发已注册的 closed listener(模拟用户关窗 / win.close() 完成)。 */
+ visible: boolean;
+ webContents: {
+ id: number;
+ on: ReturnType<typeof vi.fn>;
+ setBackgroundThrottling: ReturnType<typeof vi.fn>;
+ isDestroyed: () => boolean;
+ };
emitClosed: () => void;
+ emitWindowEvent: (event: string, ...args: unknown[]) => void;
+ emitWebContentsEvent: (event: string, ...args: unknown[]) => void;
}
-function fakeWindow(id = 1, asyncClose = false): FakeWindow {
- const listeners = new Map<string, () => void>();
+function fakeWindow(id = 1): FakeWindow {
+ const winListeners = new Map<string, (...args: unknown[]) => void>();
+ const wcListeners = new Map<string, (...args: unknown[]) => void>();
+ let destroyed = false;
+ let visible = false;
+ let minimized = false;
+ const webContentsOn = vi.fn((event: string, cb: (...args: unknown[]) => void) => {
+ wcListeners.set(event, cb);
+ });
const win: FakeWindow = {
- on: vi.fn((event: string, cb: () => void) => {
- listeners.set(event, cb);
+ on: vi.fn((event: string, cb: (...args: unknown[]) => void) => {
+ winListeners.set(event, cb);
}),
- // 真实 BrowserWindow.close() 异步走到 'closed';fake 里同步触发,足够覆盖状态机
close: vi.fn(() => {
- if (asyncClose) return;
- win.destroyed = true;
- listeners.get('closed')?.();
+ let prevented = false;
+ winListeners.get('close')?.({ preventDefault: () => { prevented = true; } });
+ if (prevented) return;
+ destroyed = true;
+ visible = false;
+ winListeners.get('closed')?.();
+ }),
+ destroy: vi.fn(() => {
+ destroyed = true;
+ visible = false;
+ winListeners.get('closed')?.();
}),
- show: vi.fn(),
+ hide: vi.fn(() => { visible = false; }),
+ show: vi.fn(() => { visible = true; }),
focus: vi.fn(),
- restore: vi.fn(),
- isMinimized: () => false,
- isDestroyed: () => win.destroyed,
+ restore: vi.fn(() => {
+ minimized = false;
+ winListeners.get('restore')?.();
+ }),
+ isMinimized: () => minimized,
+ isVisible: () => visible,
+ isDestroyed: () => destroyed,
destroyed: false,
- webContents: { id },
+ visible: false,
+ webContents: {
+ id,
+ on: webContentsOn,
+ setBackgroundThrottling: vi.fn(),
+ isDestroyed: () => destroyed,
+ },
emitClosed: () => {
- win.destroyed = true;
- listeners.get('closed')?.();
+ destroyed = true;
+ visible = false;
+ winListeners.get('closed')?.();
+ },
+ emitWindowEvent: (event, ...args) => {
+ if (event === 'minimize') minimized = true;
+ if (event === 'restore') minimized = false;
+ if (event === 'hide') visible = false;
+ if (event === 'show') visible = true;
+ winListeners.get(event)?.(...args);
},
+ emitWebContentsEvent: (event, ...args) => wcListeners.get(event)?.(...args),
};
return win;
}
-function makeHarness(
- initial: Partial<RsbWindowSettings> = {},
- opts: { asyncClose?: boolean } = {},
-) {
+function makeHarness(initial: Partial<RsbWindowSettings> = {}) {
let settings: RsbWindowSettings = { detached: false, lastOpen: false, ...initial };
let quitting = false;
const windows: FakeWindow[] = [];
- const createWindowCalls: Array<{ userInitiated: boolean }> = [];
+ const createWindowCalls: Array<Record<string, never>> = [];
const mainWin = fakeWindow(100);
const broadcasts: Array<{ detached: boolean; open: boolean }> = [];
const sends: Array<{ channel: string; payload: unknown }> = [];
@@ -68,28 +110,24 @@ function makeHarness(
const deps: RsbWindowControllerDeps = {
settings: {
read: () => ({ ...settings }),
- writePatch: (patch) => {
- settings = { ...settings, ...patch };
- },
+ writePatch: (patch) => { settings = { ...settings, ...patch }; },
},
- createWindow: (createOpts) => {
- createWindowCalls.push(createOpts);
- const w = fakeWindow(200 + windows.length, opts.asyncClose === true);
+ createWindow: () => {
+ createWindowCalls.push({});
+ const w = fakeWindow(200 + windows.length);
windows.push(w);
return w as unknown as BrowserWindow;
},
getMainWindow: () => mainWin as unknown as BrowserWindow,
- broadcastState: (s) => {
- broadcasts.push(s);
- },
+ broadcastState: (s) => { broadcasts.push(s); },
sendToWindow: (win, channel, payload) => {
sends.push({ channel, payload });
- sendTargets.push((win.webContents as { id: number }).id);
+ sendTargets.push((win.webContents as unknown as FakeWindow['webContents']).id);
},
contextChannel: 'ctx-channel',
commandChannel: 'cmd-channel',
isQuitting: () => quitting,
- log: { info: vi.fn(), warn: vi.fn() },
+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
};
const controller = new RsbWindowController(deps);
return {
@@ -101,132 +139,326 @@ function makeHarness(
sends,
sendTargets,
getSettings: () => settings,
- setQuitting: (v: boolean) => {
- quitting = v;
- },
+ setQuitting: (v: boolean) => { quitting = v; },
};
}
-beforeEach(() => {
- vi.useFakeTimers();
-});
+function markReady(controller: RsbWindowController, win: FakeWindow): void {
+ expect(controller.markRendererReady(win.webContents as unknown as WebContents)).toBe(true);
+ expect(controller.markPresentationReady(win.webContents as unknown as WebContents)).toBe(true);
+}
+
+const ctx = { sessionId: 's1', workdir: '/w', remoteHostId: null, available: true };
+
+beforeEach(() => { vi.useFakeTimers(); });
+afterEach(() => { vi.useRealTimers(); });
+
+// ═══════════════════════════════════════════════════════════════════════
+// prewarm: 后台预热
+// ═══════════════════════════════════════════════════════════════════════
+describe('prewarm', () => {
+ it('prewarm creates window without showing or focusing it', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ expect(h.windows).toHaveLength(1);
+ const win = h.windows[0];
+ expect(win.webContents.setBackgroundThrottling).toHaveBeenCalledWith(false);
+ expect(win.show).not.toHaveBeenCalled();
+ expect(win.focus).not.toHaveBeenCalled();
+ expect(h.getSettings().lastOpen).toBe(false);
+ expect(h.broadcasts).toHaveLength(0);
+ });
+
+ it('restores background throttling after presentation-ready', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const win = h.windows[0];
+
+ markReady(h.controller, win);
+
+ expect(win.webContents.setBackgroundThrottling).toHaveBeenLastCalledWith(true);
+ });
+
+ it('restores background throttling when hidden prewarm times out', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const win = h.windows[0];
+
+ vi.advanceTimersByTime(10_000);
+
+ expect(win.webContents.setBackgroundThrottling).toHaveBeenLastCalledWith(true);
+ expect(h.controller.getState().open).toBe(false);
+ });
+
+ it('prewarm is no-op when disposed', () => {
+ const h = makeHarness();
+ h.controller.dispose();
+ h.controller.prewarm();
+ expect(h.windows).toHaveLength(0);
+ });
+
+ it('open on a prewarmed completed window shows + focuses immediately', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+
+ h.controller.open({ userInitiated: true });
+ expect(win.show).toHaveBeenCalled();
+ expect(win.focus).toHaveBeenCalled();
+ expect(h.windows).toHaveLength(1);
+ });
+
+ it('open on a prewarmed but not-ready window waits for presentation-ready', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const win = h.windows[0];
+ // Only renderer-ready, not presentation-ready
+ expect(h.controller.markRendererReady(win.webContents as unknown as WebContents)).toBe(true);
-afterEach(() => {
- vi.useRealTimers();
+ h.controller.open({ userInitiated: true });
+ // Not shown yet — waiting for presentation
+ expect(win.show).not.toHaveBeenCalled();
+ expect(win.focus).not.toHaveBeenCalled();
+
+ // presentation-ready → now shown
+ expect(h.controller.markPresentationReady(win.webContents as unknown as WebContents)).toBe(true);
+ expect(win.show).toHaveBeenCalled();
+ expect(win.focus).toHaveBeenCalled();
+ });
});
-describe('open / close', () => {
- it('open 建窗 + lastOpen=true + 广播 open:true;重复 open 只 focus 不重建', () => {
+// ═══════════════════════════════════════════════════════════════════════
+// open / close: 隐藏复用
+// ═══════════════════════════════════════════════════════════════════════
+describe('open / close (hide-reuse)', () => {
+ it('open creates window + sets lastOpen=true + broadcasts open:true', () => {
const h = makeHarness();
h.controller.open();
expect(h.windows).toHaveLength(1);
expect(h.getSettings().lastOpen).toBe(true);
expect(h.broadcasts.at(-1)).toEqual({ detached: false, open: true });
+ });
+ it('repeat open on shown window only focuses', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
h.controller.open();
expect(h.windows).toHaveLength(1);
- expect(h.windows[0].focus).toHaveBeenCalled();
+
+ win.show.mockClear();
+ win.focus.mockClear();
+ h.controller.open();
+ // Only focus (show would be redundant since already visible)
+ expect(h.windows).toHaveLength(1);
});
- it('close 落 lastOpen=false;closed 回调广播 open:false', () => {
+ it('close hides window without destroying (hide-reuse)', () => {
const h = makeHarness();
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
h.controller.open();
- h.controller.close();
- expect(h.getSettings().lastOpen).toBe(false);
- expect(h.windows[0].close).toHaveBeenCalled();
- expect(h.broadcasts.at(-1)).toEqual({ detached: false, open: false });
- });
- it('窗口不存在时 close 也落 lastOpen=false 并广播', () => {
- const h = makeHarness({ lastOpen: true });
h.controller.close();
+ expect(win.hide).toHaveBeenCalled();
+ expect(win.isDestroyed()).toBe(false);
expect(h.getSettings().lastOpen).toBe(false);
expect(h.broadcasts.at(-1)).toEqual({ detached: false, open: false });
});
-});
-describe('userInitiated:false 不抢用户前台', () => {
- it('窗口已开:程序自发的 open 完全不动窗口(无 show / focus / restore)', () => {
+ it('re-open after close reuses the same window (hot path)', () => {
const h = makeHarness();
- h.controller.open();
+ h.controller.prewarm();
const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+ h.controller.close();
+
win.show.mockClear();
win.focus.mockClear();
- win.restore.mockClear();
+ h.controller.open();
+ // Same window, no recreate
+ expect(h.windows).toHaveLength(1);
+ expect(h.windows[0]).toBe(win);
+ expect(win.show).toHaveBeenCalled();
+ expect(win.focus).toHaveBeenCalled();
+ });
- h.controller.open({ userInitiated: false });
+ it('native minimize exposes a recovery entry and open restores the hot window', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+
+ win.emitWindowEvent('minimize');
+ expect(h.controller.getState()).toEqual({ detached: true, lastOpen: true, open: false });
+ expect(h.broadcasts.at(-1)).toEqual({ detached: true, open: false });
+ win.show.mockClear();
+ win.focus.mockClear();
+ h.controller.open();
expect(h.windows).toHaveLength(1);
- expect(win.show).not.toHaveBeenCalled();
- expect(win.focus).not.toHaveBeenCalled();
- expect(win.restore).not.toHaveBeenCalled();
+ expect(win.restore).toHaveBeenCalledOnce();
+ expect(win.show).toHaveBeenCalledOnce();
+ expect(win.focus).toHaveBeenCalledOnce();
+ expect(h.controller.getState().open).toBe(true);
});
- it('窗口未开:照常建窗并落 lastOpen,但把 userInitiated:false 透传给窗口工厂', () => {
- const h = makeHarness();
- h.controller.open({ userInitiated: false });
+ it('native taskbar restore updates the main-window state mirror', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+ win.emitWindowEvent('minimize');
+
+ win.emitWindowEvent('restore');
+ expect(h.broadcasts.at(-1)).toEqual({ detached: true, open: true });
+ expect(h.controller.getState().open).toBe(true);
+ });
+
+ it('native hide updates state and open shows the cached window again', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+
+ win.emitWindowEvent('hide');
+ expect(h.controller.getState()).toEqual({ detached: true, lastOpen: true, open: false });
+ expect(h.broadcasts.at(-1)).toEqual({ detached: true, open: false });
+
+ win.show.mockClear();
+ win.focus.mockClear();
+ h.controller.open();
expect(h.windows).toHaveLength(1);
- expect(h.createWindowCalls).toEqual([{ userInitiated: false }]);
- expect(h.getSettings().lastOpen).toBe(true);
- expect(h.broadcasts.at(-1)).toEqual({ detached: false, open: true });
+ expect(win.show).toHaveBeenCalledOnce();
+ expect(win.focus).toHaveBeenCalledOnce();
+ expect(h.controller.getState().open).toBe(true);
});
- it('ensureOpenForAutomation 缺省按程序自发处理(建窗不抢焦点)', async () => {
+ it('open repairs stale controller visibility using the native window state', () => {
const h = makeHarness({ detached: true });
- const p = h.controller.ensureOpenForAutomation();
- h.controller.markReady();
- await expect(p).resolves.toBeUndefined();
- expect(h.createWindowCalls).toEqual([{ userInitiated: false }]);
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+
+ // Simulate an external native hide that happened before the controller learned about it.
+ win.hide();
+ win.show.mockClear();
+ win.focus.mockClear();
+
+ h.controller.open();
+ expect(win.show).toHaveBeenCalledOnce();
+ expect(win.focus).toHaveBeenCalledOnce();
+ expect(h.controller.getState().open).toBe(true);
});
+});
- it('routeCommand userInitiated:false:命令照常派发,但开窗不抢焦点', async () => {
+describe('renderer navigation lifecycle', () => {
+ it('ignores same-document main-frame navigation such as hash routing', () => {
const h = makeHarness({ detached: true });
- h.controller.setContext({
- sessionId: 's1',
- workdir: '/w',
- remoteHostId: null,
- available: true,
- });
- const command = { type: 'open-web-browser' as const, sessionId: 's1', url: 'https://x.test/' };
- const routed = h.controller.routeCommand({
- command,
- allowOpen: true,
- userInitiated: false,
- });
- h.controller.markReady();
- await expect(routed).resolves.toBe('routed');
- expect(h.createWindowCalls).toEqual([{ userInitiated: false }]);
- expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: command });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+
+ win.hide.mockClear();
+ win.emitWebContentsEvent(
+ 'did-start-navigation',
+ {},
+ 'http://localhost:5173/?sidebarWindow=1#/sidebar-window',
+ true,
+ true,
+ );
+
+ expect(win.hide).not.toHaveBeenCalled();
+ expect(h.controller.getState().open).toBe(true);
});
- it('routeCommand 缺省(用户手势)仍走聚焦开窗', async () => {
+ it('ignores child-frame navigation such as a newly attached browser webview', () => {
const h = makeHarness({ detached: true });
- h.controller.setContext({
- sessionId: 's1',
- workdir: '/w',
- remoteHostId: null,
- available: true,
- });
- const routed = h.controller.routeCommand({
- command: { type: 'open-terminal', sessionId: 's1' },
- allowOpen: true,
- });
- h.controller.markReady();
- await expect(routed).resolves.toBe('routed');
- expect(h.createWindowCalls).toEqual([{ userInitiated: true }]);
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+
+ win.hide.mockClear();
+ win.emitWebContentsEvent(
+ 'did-start-navigation',
+ {},
+ 'https://example.com/',
+ false,
+ false,
+ );
+
+ expect(win.hide).not.toHaveBeenCalled();
+ expect(h.controller.getState().open).toBe(true);
});
- it('setDetached(true)(用户点按钮)开窗并聚焦', () => {
+ it('temporarily hides and restores only for main-frame renderer navigation', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+
+ win.emitWebContentsEvent(
+ 'did-start-navigation',
+ {},
+ 'http://localhost:5173/?sidebarWindow=1#/sidebar-window',
+ false,
+ true,
+ );
+ expect(win.hide).toHaveBeenCalledOnce();
+ expect(win.webContents.setBackgroundThrottling).toHaveBeenLastCalledWith(false);
+ expect(h.controller.getState().open).toBe(true);
+
+ markReady(h.controller, win);
+ expect(win.webContents.setBackgroundThrottling).toHaveBeenLastCalledWith(true);
+ expect(win.show).toHaveBeenCalledTimes(2);
+ expect(h.controller.getState().open).toBe(true);
+ });
+});
+
+// ═══════════════════════════════════════════════════════════════════════
+// setDetached
+// ═══════════════════════════════════════════════════════════════════════
+describe('setDetached', () => {
+ it('true: sets preference + opens window', () => {
const h = makeHarness();
- h.controller.setDetached(true);
- expect(h.createWindowCalls).toEqual([{ userInitiated: true }]);
- h.controller.setDetached(true);
- expect(h.windows[0].focus).toHaveBeenCalled();
+ const state = h.controller.setDetached(true);
+ expect(h.getSettings().detached).toBe(true);
+ expect(h.windows).toHaveLength(1);
+ expect(h.createWindowCalls).toHaveLength(1);
+ expect(state).toEqual({ detached: true, lastOpen: true, open: true });
+ });
+
+ it('false: destroys window + broadcasts detached:false', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open();
+
+ const state = h.controller.setDetached(false);
+ expect(h.getSettings().detached).toBe(false);
+ expect(win.isDestroyed()).toBe(true);
+ expect(state.open).toBe(false);
+ expect(h.broadcasts.at(-1)).toEqual({ detached: false, open: false });
});
});
-describe('closed 事件(用户关窗 vs app 退出)', () => {
- it('非 quitting:lastOpen=false + 广播 open:false', () => {
+// ═══════════════════════════════════════════════════════════════════════
+// closed 事件(用户用 OS 关闭按钮 vs app 退出)
+// ═══════════════════════════════════════════════════════════════════════
+describe('closed event', () => {
+ it('non-quitting: lastOpen=false + broadcast open:false', () => {
const h = makeHarness();
h.controller.open();
h.windows[0].emitClosed();
@@ -235,67 +467,93 @@ describe('closed 事件(用户关窗 vs app 退出)', () => {
expect(h.controller.getState().open).toBe(false);
});
- it('quitting:lastOpen 保留 true(供重启恢复),不广播', () => {
+ it('quitting: preserves lastOpen=true, no broadcast', () => {
const h = makeHarness();
h.controller.open();
- const broadcastCount = h.broadcasts.length;
+ const count = h.broadcasts.length;
h.setQuitting(true);
h.windows[0].emitClosed();
expect(h.getSettings().lastOpen).toBe(true);
- expect(h.broadcasts).toHaveLength(broadcastCount);
+ expect(h.broadcasts).toHaveLength(count);
});
});
-describe('setDetached', () => {
- it('true:落偏好 + 开窗;返回新 state', () => {
+// ═══════════════════════════════════════════════════════════════════════
+// userInitiated:false 不抢用户前台
+// ═══════════════════════════════════════════════════════════════════════
+describe('userInitiated:false', () => {
+ it('window already visible: automated open is no-op', () => {
const h = makeHarness();
- const state = h.controller.setDetached(true);
- expect(h.getSettings().detached).toBe(true);
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.open({ userInitiated: true });
+
+ win.show.mockClear();
+ win.focus.mockClear();
+ h.controller.open({ userInitiated: false });
+ expect(win.show).not.toHaveBeenCalled();
+ expect(win.focus).not.toHaveBeenCalled();
+ });
+
+ it('window not yet built: creates window without showing', () => {
+ const h = makeHarness();
+ h.controller.open({ userInitiated: false });
expect(h.windows).toHaveLength(1);
- expect(state).toEqual({ detached: true, lastOpen: true, open: true });
+ expect(h.createWindowCalls).toHaveLength(1);
});
- it('false:落偏好 + 关窗;广播最终态 detached:false open:false', () => {
- const h = makeHarness({ detached: true });
- h.controller.open();
- const state = h.controller.setDetached(false);
- expect(h.getSettings().detached).toBe(false);
- expect(state.open).toBe(false);
- expect(h.broadcasts.at(-1)).toEqual({ detached: false, open: false });
+ it('setDetached(true) opens window', () => {
+ const h = makeHarness();
+ h.controller.setDetached(true);
+ expect(h.windows).toHaveLength(1);
+ expect(h.createWindowCalls).toHaveLength(1);
});
});
+// ═══════════════════════════════════════════════════════════════════════
+// ensureOpenForAutomation
+// ═══════════════════════════════════════════════════════════════════════
describe('ensureOpenForAutomation', () => {
- it('非 detached:no-op resolve,不开窗', async () => {
+ it('non-detached: no-op resolve', async () => {
const h = makeHarness();
await expect(h.controller.ensureOpenForAutomation()).resolves.toBeUndefined();
expect(h.windows).toHaveLength(0);
});
- it('detached + 窗口关:开窗并等 markReady', async () => {
+ it('detached + presentation-ready: direct resolve', async () => {
const h = makeHarness({ detached: true });
- const pending = h.controller.ensureOpenForAutomation();
- expect(h.windows).toHaveLength(1);
- h.controller.markReady();
- await expect(pending).resolves.toBeUndefined();
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ await expect(h.controller.ensureOpenForAutomation()).resolves.toBeUndefined();
});
- it('detached + 已 ready:直接 resolve', async () => {
+ it('detached + no window: opens and waits for presentation-ready', async () => {
const h = makeHarness({ detached: true });
- h.controller.open();
- h.controller.markReady();
- await expect(h.controller.ensureOpenForAutomation()).resolves.toBeUndefined();
+ const pending = h.controller.ensureOpenForAutomation();
+ expect(h.windows).toHaveLength(1);
+ const win = h.windows[0];
+ expect(h.controller.markRendererReady(win.webContents as unknown as WebContents)).toBe(true);
+ let settled = false;
+ void pending.then(() => { settled = true; });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+ h.controller.markPresentationReady(win.webContents as unknown as WebContents);
+ await expect(pending).resolves.toBeUndefined();
});
- it('ready 超时 reject', async () => {
+ it('ready timeout rejects', async () => {
const h = makeHarness({ detached: true });
const pending = h.controller.ensureOpenForAutomation();
+ // ensureOpenForAutomation 内部 readyWaiter 超时为 READY_TIMEOUT_MS(8s)。
+ // 5s openFallback 会 showAndFocus 但不影响 readyWaiter。
const assertion = expect(pending).rejects.toThrow(/ready timeout/);
vi.advanceTimersByTime(8000);
await assertion;
});
- it('窗口在 ready 前被关:reject', async () => {
+ it('window closed before ready rejects', async () => {
const h = makeHarness({ detached: true });
const pending = h.controller.ensureOpenForAutomation();
const assertion = expect(pending).rejects.toThrow(/closed before ready/);
@@ -304,51 +562,57 @@ describe('ensureOpenForAutomation', () => {
});
});
+// ═══════════════════════════════════════════════════════════════════════
+// getHostWebContents
+// ═══════════════════════════════════════════════════════════════════════
describe('getHostWebContents', () => {
- it('非 detached → 主窗 webContents', () => {
+ it('non-detached → main window webContents', () => {
const h = makeHarness();
expect(h.controller.getHostWebContents()).toBe(h.mainWin.webContents);
});
- it('detached + 窗口关 → 回落主窗', () => {
+ it('detached + no window → main window', () => {
const h = makeHarness({ detached: true });
expect(h.controller.getHostWebContents()).toBe(h.mainWin.webContents);
});
- it('detached + 窗口开 → 子窗口 webContents;关窗后回落主窗', () => {
+ it('detached + window open → child window webContents', () => {
const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
h.controller.open();
- expect(h.controller.getHostWebContents()).toBe(h.windows[0].webContents);
- h.windows[0].emitClosed();
- expect(h.controller.getHostWebContents()).toBe(h.mainWin.webContents);
+ expect(h.controller.getHostWebContents()).toBe(win.webContents);
});
- it('异步 closing 阶段立即排除旧子窗口 host', () => {
- const h = makeHarness({ detached: true }, { asyncClose: true });
+ it('after destroy: falls back to main', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
h.controller.open();
- h.controller.markReady();
- h.controller.close();
-
- expect(h.windows[0].isDestroyed()).toBe(false);
- expect(h.controller.getState().open).toBe(false);
- expect(h.controller.getSidebarWebContents()).toBeNull();
+ h.controller.setDetached(false);
expect(h.controller.getHostWebContents()).toBe(h.mainWin.webContents);
});
});
+// ═══════════════════════════════════════════════════════════════════════
+// setContext / routeCommand
+// ═══════════════════════════════════════════════════════════════════════
describe('setContext / routeCommand', () => {
- const ctx = { sessionId: 's1', workdir: '/w', remoteHostId: null, available: true };
- const terminalRequest = (sessionId = 's1', allowOpen = true) => ({
- command: { type: 'open-terminal' as const, sessionId },
- allowOpen,
- });
+ function terminalRequest(sessionId = 's1', allowOpen = true) {
+ return { command: { type: 'open-terminal' as const, sessionId }, allowOpen };
+ }
- it('窗口关着:只缓存不转发;开着:转发到 context channel', () => {
+ it('caches context; forwards only when window alive', () => {
const h = makeHarness();
h.controller.setContext(ctx);
expect(h.sends).toHaveLength(0);
expect(h.controller.getContext()).toEqual(ctx);
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
h.controller.open();
h.controller.setContext({ ...ctx, sessionId: 's2' });
expect(h.sends.at(-1)).toEqual({
@@ -357,274 +621,183 @@ describe('setContext / routeCommand', () => {
});
});
- it('attached:残留异步 closing 子窗仍返回 attached 且绝不发送', async () => {
- const h = makeHarness({ detached: true }, { asyncClose: true });
- h.controller.setContext(ctx);
- h.controller.open();
- h.controller.markReady();
- h.controller.setDetached(false);
- expect(h.windows[0].isDestroyed()).toBe(false);
-
- await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('attached');
- expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
- });
-
- it('detached + allowOpen=true:开窗等 ready 后 routed', async () => {
+ it('detached + allowOpen: opens window, waits ready, routes', async () => {
const h = makeHarness({ detached: true });
h.controller.setContext(ctx);
const pending = h.controller.routeCommand(terminalRequest());
expect(h.windows).toHaveLength(1);
expect(h.sends).toHaveLength(0);
- h.controller.markReady();
- await expect(pending).resolves.toBe('routed');
- expect(h.sends.at(-1)).toEqual({
- channel: 'cmd-channel',
- payload: { type: 'open-terminal', sessionId: 's1' },
- });
- });
-
- it('renderer 旧 attached 镜像不影响 main 的最新 detached 裁决', async () => {
- const h = makeHarness({ detached: false });
- h.controller.setContext(ctx);
- h.controller.setDetached(true);
-
- const pending = h.controller.routeCommand(terminalRequest());
- h.controller.markReady();
+ const win = h.windows[0];
+ markReady(h.controller, win);
await expect(pending).resolves.toBe('routed');
expect(h.sends.at(-1)).toEqual({
channel: 'cmd-channel',
payload: { type: 'open-terminal', sessionId: 's1' },
});
- expect(h.sendTargets.at(-1)).toBe(h.windows[0].webContents.id);
});
- it('detached:协同 tab 命令复用同一条 command channel', async () => {
+ it('context mismatch returns stale-context', async () => {
const h = makeHarness({ detached: true });
- h.controller.setContext(ctx);
- h.controller.open();
- h.controller.markReady();
-
- await h.controller.routeCommand({
- command: {
- type: 'ensure-orca-workers-tab',
- sessionId: 's1',
- focusWorkerSessionId: 'worker-s1',
- focusTab: true,
- },
- allowOpen: true,
- });
- await h.controller.routeCommand({
- command: { type: 'close-orca-workers-tab', sessionId: 's1' },
- allowOpen: false,
- });
-
- expect(h.sends.at(-2)).toEqual({
- channel: 'cmd-channel',
- payload: {
- type: 'ensure-orca-workers-tab',
- sessionId: 's1',
- focusWorkerSessionId: 'worker-s1',
- focusTab: true,
- },
- });
- expect(h.sends.at(-1)).toEqual({
- channel: 'cmd-channel',
- payload: { type: 'close-orca-workers-tab', sessionId: 's1' },
- });
- });
-
- it('跨会话 open-turn-review 按 hostSessionId(lead 桶)裁决,worker sessionId 不拒发', async () => {
- // 协同面板审查 worker 轮次:command.sessionId 是取数目标 worker,可见桶是
- // lead(hostSessionId)。detached context 停在 lead 上,按 sessionId 裁决会
- // 误判 stale-context,worker 审查入口在 detached 形态下点了没反应。
- const h = makeHarness({ detached: true });
- h.controller.setContext(ctx);
- h.controller.open();
- h.controller.markReady();
-
- const command = {
- type: 'open-turn-review' as const,
- sessionId: 'worker-1',
- changeSetIds: ['c1'],
- selectedDiffId: null,
- selectedPath: null,
- requestNonce: 1,
- hostSessionId: 's1',
- };
- await expect(
- h.controller.routeCommand({ command, allowOpen: true }),
- ).resolves.toBe('routed');
- expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: command });
-
- // hostSessionId 与当前 context 不符时仍是 stale-context(不能放宽成任意会话)。
- await expect(
- h.controller.routeCommand({
- command: { ...command, hostSessionId: 'other-lead' },
- allowOpen: true,
- }),
- ).resolves.toBe('stale-context');
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('stale-context');
});
- it('跨会话 open-turn-review 延迟命令按 lead 桶入队,lead ready 后派发', async () => {
+ it('allowOpen=false + window hidden: queued, flushed on ready', async () => {
const h = makeHarness({ detached: true });
h.controller.setContext(ctx);
-
- const command = {
- type: 'open-turn-review' as const,
- sessionId: 'worker-1',
- changeSetIds: ['c1'],
- selectedDiffId: null,
- selectedPath: null,
- requestNonce: 2,
- hostSessionId: 's1',
- };
+ const cmd = { type: 'close-orca-workers-tab' as const, sessionId: 's1' };
await expect(
- h.controller.routeCommand({ command, allowOpen: false }),
+ h.controller.routeCommand({ command: cmd, allowOpen: false }),
).resolves.toBe('queued');
expect(h.windows).toHaveLength(0);
- // context 一直是 lead(s1),不会切到 worker;flush 必须按 lead 桶命中。
- h.controller.open();
- h.controller.markReady();
- expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: command });
- });
-
- it('context mismatch / unavailable 返回 stale-context,不开窗也不派发', async () => {
- const h = makeHarness({ detached: true });
- h.controller.setContext({ ...ctx, sessionId: 's2' });
-
- await expect(
- h.controller.routeCommand(terminalRequest()),
- ).resolves.toBe('stale-context');
- h.controller.setContext({ ...ctx, available: false });
- await expect(
- h.controller.routeCommand(terminalRequest()),
- ).resolves.toBe('stale-context');
-
- expect(h.windows).toHaveLength(0);
- expect(h.sends).toHaveLength(0);
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: cmd });
});
- it('等待 detached renderer ready 时 context A->B 返回 stale 且不派旧命令', async () => {
+ it('detach preference change mid-wait: returns attached, no send to destroyed host', async () => {
const h = makeHarness({ detached: true });
h.controller.setContext(ctx);
const pending = h.controller.routeCommand(terminalRequest());
expect(h.windows).toHaveLength(1);
- h.controller.setContext({ ...ctx, sessionId: 's2' });
- h.controller.markReady();
- await expect(pending).resolves.toBe('stale-context');
- expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
- });
-
- it('ready 等待期间偏好切 attached 返回 attached,不向 closing 旧 host 发送', async () => {
- const h = makeHarness({ detached: true }, { asyncClose: true });
- h.controller.setContext(ctx);
- const pending = h.controller.routeCommand(terminalRequest());
- expect(h.windows).toHaveLength(1);
-
h.controller.setDetached(false);
- h.windows[0].emitClosed();
+ // setDetached(false) now destroys the window
await expect(pending).resolves.toBe('attached');
- expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
+ expect(h.sends.filter(e => e.channel === 'cmd-channel')).toEqual([]);
});
- it('allowOpen=false + detached closed:queued 且不重开;同 session ready 后派发', async () => {
+ it('context switch during ready wait: returns stale-context', async () => {
const h = makeHarness({ detached: true });
h.controller.setContext(ctx);
- const command = {
- type: 'ensure-orca-workers-tab' as const,
- sessionId: 's1',
- focusWorkerSessionId: 'worker-s1',
- focusTab: false,
- };
-
- await expect(
- h.controller.routeCommand({ command, allowOpen: false }),
- ).resolves.toBe('queued');
- expect(h.windows).toHaveLength(0);
+ const pending = h.controller.routeCommand(terminalRequest());
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ await expect(pending).resolves.toBe('stale-context');
+ });
+});
+// ═══════════════════════════════════════════════════════════════════════
+// 崩溃恢复
+// ═══════════════════════════════════════════════════════════════════════
+describe('crash recovery', () => {
+ it('did-fail-load invalidates window and rebuilds if pendingOpen', () => {
+ const h = makeHarness();
h.controller.open();
- expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
- h.controller.markReady();
- expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: command });
+ const win = h.windows[0];
+ expect(h.controller.markRendererReady(win.webContents as unknown as WebContents)).toBe(true);
+
+ // Simulate load failure
+ win.emitWebContentsEvent('did-fail-load', {}, -105, 'ERR_NAME_NOT_RESOLVED', 'url', true);
+ vi.advanceTimersByTime(10);
+
+ // Window should have been destroyed and a new one created (auto-recovery)
+ expect(win.isDestroyed()).toBe(true);
+ expect(h.windows).toHaveLength(2);
});
- it('allowOpen=false + closing:不重开并排队,下一 host ready 后派发', async () => {
- const h = makeHarness({ detached: true }, { asyncClose: true });
- h.controller.setContext(ctx);
+ it('render-process-gone invalidates window with bounded recovery', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const win1 = h.windows[0];
+ markReady(h.controller, win1);
h.controller.open();
- h.controller.markReady();
- h.controller.close();
- const command = { type: 'close-orca-workers-tab' as const, sessionId: 's1' };
- await expect(
- h.controller.routeCommand({ command, allowOpen: false }),
- ).resolves.toBe('queued');
- expect(h.windows).toHaveLength(1);
- h.windows[0].emitClosed();
- h.controller.open();
- h.controller.markReady();
- expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: command });
+ // First crash: auto-recover
+ win1.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });
+ vi.advanceTimersByTime(10);
+ expect(win1.isDestroyed()).toBe(true);
+ expect(h.windows).toHaveLength(2); // new window created
+
+ // Second crash: recovery exhausted
+ const win2 = h.windows[1];
+ markReady(h.controller, win2);
+ win2.emitWebContentsEvent('render-process-gone', {}, { reason: 'killed' });
+ vi.advanceTimersByTime(10);
+ expect(h.windows).toHaveLength(2); // no third window
});
- it('closing + terminal 快速返回 stale,不等待关窗或进入 ready timeout', async () => {
- const h = makeHarness({ detached: true }, { asyncClose: true });
- h.controller.setContext(ctx);
+ it('recovery quota resets after stability period', () => {
+ const h = makeHarness();
h.controller.open();
- h.controller.markReady();
- h.controller.close();
+ const win1 = h.windows[0];
+ markReady(h.controller, win1);
- await expect(h.controller.routeCommand(terminalRequest())).resolves.toBe('stale-context');
+ win1.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });
+ vi.advanceTimersByTime(10);
+ expect(h.windows).toHaveLength(2);
- expect(h.windows).toHaveLength(1);
- expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
- expect(vi.getTimerCount()).toBe(0);
+ // Wait for stability period
+ vi.advanceTimersByTime(30_000);
+
+ // Recovery creates win2; need to open (request visibility) before second crash.
+ const win2 = h.windows[1];
+ markReady(h.controller, win2);
+ h.controller.open();
+ win2.emitWebContentsEvent('render-process-gone', {}, { reason: 'crashed' });
+ vi.advanceTimersByTime(10);
+ expect(h.windows).toHaveLength(3); // recovery quota reset allows third window
});
+});
- it('queued A intent 在 context 切到 B 后丢弃,不发子 host 也不转主 host', async () => {
- const h = makeHarness({ detached: true });
- h.controller.setContext(ctx);
- await h.controller.routeCommand({
- command: { type: 'close-orca-workers-tab', sessionId: 's1' },
- allowOpen: false,
- });
+// ═══════════════════════════════════════════════════════════════════════
+// dispose
+// ═══════════════════════════════════════════════════════════════════════
+describe('dispose', () => {
+ it('dispose destroys the window and prevents further prewarm', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const win = h.windows[0];
+ h.controller.dispose();
+ expect(win.isDestroyed()).toBe(true);
- h.controller.setContext({ ...ctx, sessionId: 's2' });
- h.controller.open();
- h.controller.markReady();
- expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toEqual([]);
+ // prewarm should be no-op after dispose
+ h.controller.prewarm();
+ expect(h.windows).toHaveLength(1); // no new window
});
- it('queued current-session intent 在切 attached 时交给主 renderer', async () => {
- const h = makeHarness({ detached: true });
- h.controller.setContext(ctx);
- const command = { type: 'close-orca-workers-tab' as const, sessionId: 's1' };
- await h.controller.routeCommand({ command, allowOpen: false });
+ it('dispose is idempotent', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ h.controller.dispose();
+ h.controller.dispose();
+ // Does not throw
+ });
+});
- h.controller.setDetached(false);
- expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: command });
- expect(h.sendTargets.at(-1)).toBe(h.mainWin.webContents.id);
+// ═══════════════════════════════════════════════════════════════════════
+// sender guard: markRendererReady/markPresentationReady reject wrong sender
+// ═══════════════════════════════════════════════════════════════════════
+describe('sender guard', () => {
+ it('markRendererReady rejects non-sidebar sender', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const wrongSender = { id: 999 } as unknown as WebContents;
+ expect(h.controller.markRendererReady(wrongSender)).toBe(false);
});
- it('passive ensure 不覆盖已排队的显式 worker intent', async () => {
- const h = makeHarness({ detached: true });
- h.controller.setContext(ctx);
- const explicit = {
- type: 'ensure-orca-workers-tab' as const,
- sessionId: 's1',
- focusWorkerSessionId: 'worker-s1',
- focusTab: false,
- };
- await h.controller.routeCommand({ command: explicit, allowOpen: false });
- await h.controller.routeCommand({
- command: { type: 'ensure-orca-workers-tab', sessionId: 's1', focusTab: false },
- allowOpen: false,
- });
+ it('markPresentationReady rejects non-sidebar sender', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const wrongSender = { id: 999 } as unknown as WebContents;
+ expect(h.controller.markPresentationReady(wrongSender)).toBe(false);
+ });
- h.controller.open();
- h.controller.markReady();
- expect(h.sends.at(-1)).toEqual({ channel: 'cmd-channel', payload: explicit });
+ it('refreshContext rejects non-sidebar sender', () => {
+ const h = makeHarness();
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.setContext({ sessionId: 's1', workdir: '/w', remoteHostId: null, available: true });
+ // setContext sends to the window when alive, so there is already traffic.
+ const sendCountBefore = h.sends.length;
+ const wrongSender = { id: 999 } as unknown as WebContents;
+ h.controller.refreshContext(wrongSender);
+ // No additional send from refreshContext with wrong sender
+ expect(h.sends.length).toBe(sendCountBefore);
});
it('同会话多条不同 passive 命令保序全量下发,不再互相覆盖(#2409)', async () => {
@@ -641,7 +814,7 @@ describe('setContext / routeCommand', () => {
await expect(h.controller.routeCommand({ command: close, allowOpen: false })).resolves.toBe('queued');
h.controller.open();
- h.controller.markReady();
+ markReady(h.controller, h.windows[0]);
const delivered = h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload);
expect(delivered).toEqual([register, close]);
});
@@ -681,7 +854,7 @@ describe('setContext / routeCommand', () => {
await h.controller.routeCommand({ command: { ...register }, allowOpen: false });
h.controller.open();
- h.controller.markReady();
+ markReady(h.controller, h.windows[0]);
expect(h.sends.filter((entry) => entry.channel === 'cmd-channel')).toHaveLength(1);
});
@@ -703,7 +876,7 @@ describe('setContext / routeCommand', () => {
await h.controller.routeCommand({ command: close, allowOpen: false });
h.controller.open();
- h.controller.markReady();
+ markReady(h.controller, h.windows[0]);
const delivered = h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload);
expect(delivered).toEqual([explicit, close]);
});
@@ -724,7 +897,7 @@ describe('setContext / routeCommand', () => {
await h.controller.routeCommand({ command: reopen, allowOpen: false });
h.controller.open();
- h.controller.markReady();
+ markReady(h.controller, h.windows[0]);
const delivered = h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload);
expect(delivered).toEqual([explicit, close, reopen]);
});
@@ -739,7 +912,7 @@ describe('setContext / routeCommand', () => {
await h.controller.routeCommand({ command: { ...ensure }, allowOpen: false });
h.controller.open();
- h.controller.markReady();
+ markReady(h.controller, h.windows[0]);
const delivered = h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload);
expect(delivered).toEqual([ensure, close, ensure]);
});
@@ -773,7 +946,7 @@ describe('setContext / routeCommand', () => {
await h.controller.routeCommand({ command: fresh, allowOpen: false });
h.controller.open();
- h.controller.markReady();
+ markReady(h.controller, h.windows[0]);
const delivered = h.sends.filter((entry) => entry.channel === 'cmd-channel').map((entry) => entry.payload);
expect(delivered).toEqual([other, fresh]);
});
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
index dc3b1b50e5..5ff55208f5 100644
--- a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
@@ -28,6 +28,9 @@ function makeController() {
getContext: vi.fn(),
getSidebarWebContents: vi.fn(),
markReady: vi.fn(),
+ markRendererReady: vi.fn(),
+ markPresentationReady: vi.fn(),
+ refreshContext: vi.fn(),
setContext: vi.fn(),
routeCommand: vi.fn(async () => 'routed'),
} as unknown as RsbWindowController & { routeCommand: ReturnType<typeof vi.fn> };
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts
new file mode 100644
index 0000000000..3eda543ff3
--- /dev/null
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/preload-contract.test.ts
@@ -0,0 +1,302 @@
+/**
+ * sidebarWindowPreload 闈欐€佸绾︽祴璇曘€?
+ *
+ * 楠岃瘉 RSB 涓撶敤 preload 鏆撮湶鐨?bridge 鏂规硶涓?SidebarWindowLayout + RightSidebarShell
+ * 鍙婂叾渚濊禆鏍戠殑瀹為檯 window.electronAPI.* 璋冪敤瀹屽叏鍖归厤銆?
+ */
+
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+const PRELOAD_PATH = path.resolve(
+ process.cwd().toLowerCase().endsWith((path.sep + 'apps' + path.sep + 'desktop').toLowerCase())
+ ? process.cwd()
+ : path.join(process.cwd(), 'apps', 'desktop'),
+ 'src/preload/sidebarWindowPreload.ts',
+);
+
+let source = '';
+try {
+ source = readFileSync(PRELOAD_PATH, 'utf-8').replace(/\r\n/g, '\n');
+} catch {
+ // skip on bundled builds
+}
+
+function exposedTopLevelKeys(src: string): string[] {
+ const start = src.indexOf("contextBridge.exposeInMainWorld('electronAPI'");
+ if (start < 0) return [];
+ const open = src.indexOf('{', start);
+ const body = open < 0 ? null : readBalancedObject(src, open);
+ return body === null ? [] : objectKeys(body, 2);
+}
+
+function exposedNestedKeys(src: string, parent: string): string[] {
+ const body = extractBlock(src, parent);
+ return body === null ? [] : objectKeys(body);
+}
+
+function extractBlock(src: string, key: string): string | null {
+ const re = new RegExp(`(?:^|\\n)[ \\t]*${key}[ \\t]*:[ \\t]*\\{`, 'm');
+ const match = re.exec(src);
+ if (!match) return null;
+ const open = src.indexOf('{', match.index + match[0].length - 1);
+ return readBalancedObject(src, open);
+}
+
+function readBalancedObject(src: string, open: number): string | null {
+ if (open < 0 || src[open] !== '{') return null;
+ let depth = 0;
+ let quote: string | null = null;
+ let escaped = false;
+ let lineComment = false;
+ let blockComment = false;
+ for (let i = open; i < src.length; i += 1) {
+ const char = src[i];
+ const next = src[i + 1];
+ if (lineComment) {
+ if (char === '\n') lineComment = false;
+ continue;
+ }
+ if (blockComment) {
+ if (char === '*' && next === '/') {
+ blockComment = false;
+ i += 1;
+ }
+ continue;
+ }
+ if (quote !== null) {
+ if (escaped) escaped = false;
+ else if (char === '\\') escaped = true;
+ else if (char === quote) quote = null;
+ continue;
+ }
+ if (char === '/' && next === '/') {
+ lineComment = true;
+ i += 1;
+ continue;
+ }
+ if (char === '/' && next === '*') {
+ blockComment = true;
+ i += 1;
+ continue;
+ }
+ if (char === '"' || char === "'" || char === '`') {
+ quote = char;
+ continue;
+ }
+ if (char === '{') depth += 1;
+ else if (char === '}') {
+ depth -= 1;
+ if (depth === 0) return src.slice(open + 1, i);
+ }
+ }
+ return null;
+}
+
+function objectKeys(body: string, baseIndent?: number): string[] {
+ const candidates = [...body.matchAll(/^([ \t]*)([A-Za-z_$][\w$]*)[ \t]*:/gm)];
+ if (candidates.length === 0) return [];
+ const indent = baseIndent ?? Math.min(...candidates.map((match) => match[1].length));
+ return candidates
+ .filter((match) => match[1].length === indent)
+ .map((match) => match[2]);
+}
+
+const topLevel = exposedTopLevelKeys(source);
+const rswKeys = exposedNestedKeys(source, 'rightSidebarWindow');
+const deviceLinkKeys = exposedNestedKeys(source, 'deviceLink');
+const mirrorCacheKeys = exposedNestedKeys(source, 'mirrorCache');
+const localDbBody = extractBlock(source, 'localDb') ?? '';
+const localDbKeys = objectKeys(localDbBody);
+const rightSidebarTabsKeys = exposedNestedKeys(localDbBody, 'rightSidebarTabs');
+const subagentRunsKeys = exposedNestedKeys(localDbBody, 'subagentRuns');
+const orcaWorkflowKeys = exposedNestedKeys(localDbBody, 'orcaWorkflows');
+const gitReviewKeys = exposedNestedKeys(source, 'gitReview');
+const makerKeys = exposedNestedKeys(source, 'maker');
+const iosSimulatorKeys = exposedNestedKeys(source, 'iosSimulator');
+const fileBrowserKeys = exposedNestedKeys(source, 'fileBrowser');
+const terminalKeys = exposedNestedKeys(source, 'terminal');
+const processMonitorKeys = exposedNestedKeys(source, 'processMonitor');
+const nativePopupKeys = exposedNestedKeys(source, 'rsbNativePopup');
+
+describe('sidebarWindowPreload 椤跺眰濂戠害', () => {
+ it('鏆撮湶 chrome 鑳藉姏', () => {
+ expect(topLevel).toEqual(expect.arrayContaining(['platform']));
+ expect(topLevel).toEqual(expect.arrayContaining(['windowMinimize']));
+ expect(topLevel).toEqual(expect.arrayContaining(['windowMaximize']));
+ expect(topLevel).toEqual(expect.arrayContaining(['windowClose']));
+ expect(topLevel).toEqual(expect.arrayContaining(['logToMain']));
+ expect(topLevel).toEqual(expect.arrayContaining(['appearanceSettings']));
+ expect(topLevel).toEqual(expect.arrayContaining(['localThemes']));
+ expect(topLevel).toEqual(expect.arrayContaining(['appShortcuts']));
+ expect(topLevel).toEqual(expect.arrayContaining(['theme']));
+ expect(topLevel).toEqual(expect.arrayContaining(['safeStorageRead', 'safeStorageRemove']));
+ expect(topLevel).toEqual(expect.arrayContaining(['search']));
+ });
+
+ it('鏆撮湶 AuthProvider 鎵€闇€鐨勬渶灏忚璇佺姸鎬?bridge', () => {
+ expect(topLevel).toEqual(expect.arrayContaining([
+ 'authHasPersistedSessionHintSync',
+ 'authInitialize',
+ 'authGetLoginState',
+ 'authDispatchLoginAction',
+ 'authLogout',
+ 'authEnterLocal',
+ 'authExitLocal',
+ 'authGetAccountDeletionAvailability',
+ 'authRequestAccountDeletionChallenge',
+ 'authConfirmAccountDeletion',
+ 'authGetAccountDeletionStatus',
+ 'authClearAccountDeletionReceipt',
+ 'authConsumeAccountDeletionRestoredNotice',
+ 'onAuthStateChange',
+ 'onAuthSessionExpired',
+ ]));
+ });
+
+ it('鏆撮湶 rightSidebarWindow 鍛藉悕绌洪棿', () => {
+ expect(topLevel).toEqual(expect.arrayContaining(['rightSidebarWindow']));
+ });
+
+ it('鏆撮湶 RSB tab 鎸佷箙鍖?+ browser bridge', () => {
+ expect(topLevel).toEqual(expect.arrayContaining(['localDb']));
+ expect(topLevel).toEqual(expect.arrayContaining(['rsbBrowserBridge']));
+ expect(topLevel).toEqual(expect.arrayContaining(['onRsbBrowserCommand']));
+ const browserKeys = exposedNestedKeys(source, 'rsbBrowserBridge');
+ expect(browserKeys).toEqual(expect.arrayContaining([
+ 'report', 'release', 'snapshot', 'captureScreenshot', 'captureScreenshotData',
+ 'onPin', 'onUnpin', 'onTabOpRequest', 'tabOpResult', 'setActiveSession',
+ 'setForeground', 'forceKill', 'onResourceEvent',
+ ]));
+ });
+
+ it('鏆撮湶鍒嗙鍙充晶鏍忓疄闄呮寕杞介潰鏉挎墍闇€鐨勬渶灏?bridge', () => {
+ expect(topLevel).toEqual(expect.arrayContaining([
+ 'fileBrowser', 'terminal', 'gitReview', 'processMonitor', 'rsbNativePopup',
+ 'openExternal', 'openFileInBrowser', 'openPath', 'showItemInFolder',
+ 'getFilePath', 'cacheImageFromBuffer', 'maker', 'localDb',
+ ]));
+ expect(fileBrowserKeys).toEqual(expect.arrayContaining([
+ 'listDir', 'listAllFiles', 'readFile', 'writeFile', 'createFile', 'createFolder',
+ 'deleteEntry', 'renameEntry', 'stat', 'startWatch', 'stopWatch', 'onEvent',
+ 'fetchRemote', 'readCached', 'cachePut', 'onTransferProgress', 'chatFetch', 'chatStat',
+ ]));
+ expect(terminalKeys).toEqual(expect.arrayContaining([
+ 'create', 'write', 'resize', 'dispose', 'restart', 'onData', 'onExit',
+ ]));
+ expect(gitReviewKeys).toEqual(expect.arrayContaining([
+ 'get', 'summary', 'commits', 'commitDiff', 'branchDiff', 'fileDiff', 'imagePreview',
+ 'markdownPreview', 'openFile', 'stageFile', 'unstageFile', 'discardFile', 'stageHunk',
+ 'unstageHunk', 'discardHunk', 'stageAll', 'unstageAll', 'discardAll', 'commit', 'push',
+ ]));
+ expect(processMonitorKeys).toEqual(expect.arrayContaining([
+ 'subscribe', 'unsubscribe', 'terminate', 'onSample',
+ ]));
+ expect(nativePopupKeys).toEqual(expect.arrayContaining([
+ 'claim', 'setBounds', 'command', 'close', 'onEvent',
+ ]));
+ });
+
+ it('涓嶆毚闇?maker / agent / voice / login 鑷不鑳藉姏', () => {
+ const forbidden = [
+ 'agent', 'voiceInput', 'login', 'settings',
+ 'updater', 'chat', 'session',
+ 'resourceUsageWindow', 'ghostPanelWindow', 'ghosts',
+ 'pluginMarket', 'deepLink', 'gitContext',
+ 'copyMediaToClipboard', 'cacheMediaForSession',
+ ];
+ for (const key of forbidden) {
+ expect(topLevel).not.toEqual(expect.arrayContaining([key]));
+ }
+ });
+
+ it('RSB browser bridge contract', () => {
+ const browserKeys = exposedNestedKeys(source, 'rsbBrowserBridge');
+ expect(browserKeys).toEqual(expect.arrayContaining([
+ 'report', 'release', 'snapshot', 'captureScreenshot', 'captureScreenshotData',
+ 'onPin', 'onUnpin', 'onTabOpRequest', 'tabOpResult', 'setActiveSession',
+ 'setForeground', 'forceKill', 'onResourceEvent',
+ ]));
+ });
+});
+
+describe('deviceLink 閺堚偓鐏忓繗绻欑粙瀣╃窗鐠囨繃藟閹?', () => {
+ it('閸欘亝姣氶棁鑼剁箼缁嬪绱扮拠婵嗗灙鐞涖劋绗岄梹婊冨剼缂傛挸鐡ㄩ幍鈧棁鈧懗钘夊', () => {
+ expect(topLevel).toEqual(expect.arrayContaining(['deviceLink']));
+ expect(deviceLinkKeys).toEqual(expect.arrayContaining([
+ 'getState', 'listDevices', 'invoke', 'subscribe', 'unsubscribe',
+ 'onPresenceChanged', 'onStatusChanged', 'onRemotePush', 'onAccessRevoked',
+ 'onControlTargetChanged', 'onResponsivenessChanged', 'mirrorCache',
+ ]));
+ expect(mirrorCacheKeys).toEqual(expect.arrayContaining([
+ 'getMessages', 'putMessages', 'getSessionList', 'putSessionList', 'clear',
+ ]));
+ });
+
+ it('娑撳秵姣氶棁鑼额啎婢跺洨顓搁悶鍡曠瑢閺夊啴妾?mutation', () => {
+ for (const key of [
+ 'setEnabled', 'setKeepAwake', 'setDeviceControlEnabled', 'renameDevice',
+ 'deleteDevice', 'openLink', 'closeLink', 'disconnectAll', 'revoke', 'restore',
+ ]) {
+ expect(deviceLinkKeys).not.toEqual(expect.arrayContaining([key]));
+ }
+ });
+});
+
+describe('rightSidebarWindow 鍛藉悕绌洪棿', () => {
+ it('rightSidebarWindow namespace contract', () => {
+ expect(rswKeys).toEqual(expect.arrayContaining(['getState']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['open']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['close']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['setDetached']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['getContext']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['ready']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['rendererReady']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['presentationReady']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['refreshContext']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['onStateChanged']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['onContextChanged']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['onCommand']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['sendCommand']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['onVisibilityChanged']));
+ });
+});
+
+describe('sidebar nested namespace contract', () => {
+ it('localDb nested namespace contract', () => {
+ expect(localDbKeys).toEqual(
+ expect.arrayContaining(['sessions', 'messages', 'rightSidebarTabs', 'subagentRuns']),
+ );
+ expect(exposedNestedKeys(localDbBody, 'sessions')).toEqual(
+ expect.arrayContaining(['get', 'list', 'resolveReferences', 'ackInterrupted']),
+ );
+ expect(exposedNestedKeys(localDbBody, 'messages')).toEqual(
+ expect.arrayContaining([
+ 'list', 'around', 'aroundClientId', 'estimatedSessionValue',
+ 'onCreated', 'onDeleted', 'onErrorPersisted',
+ ]),
+ );
+ expect(rightSidebarTabsKeys).toEqual(expect.arrayContaining([
+ 'list', 'ensureSingleton', 'upsert', 'close', 'setActive', 'reorder',
+ ]));
+ expect(subagentRunsKeys).toEqual(expect.arrayContaining(['list', 'detail', 'onChanged']));
+ expect(orcaWorkflowKeys).toEqual(expect.arrayContaining([
+ 'getByLeadSession', 'getByWorkerSession', 'listWorkersByLead', 'listWorkersByLeads',
+ 'createWorker', 'switchFocus', 'idleWorker', 'archiveWorker', 'endTeam',
+ 'getCollaborationSettings', 'onOrcaWorkerChanged',
+ ]));
+ });
+ it('maker capability contract', () => {
+ expect(makerKeys).toEqual(expect.arrayContaining([
+ 'getTurnChangeSets', 'getWorkflowProgress', 'listSessionBackgroundTasks', 'stopAgentTask',
+ 'getPendingInteractions',
+ 'iosSimulator',
+ ]));
+ expect(iosSimulatorKeys).toEqual(expect.arrayContaining([
+ 'requestAccess', 'status', 'call', 'setAgentControl', 'setMutationControl',
+ 'setViewerVisibility', 'latestFrame', 'setStreamProfile', 'liveTouch',
+ 'onH264Frame', 'onRouteStatus', 'onFocusRequest',
+ ]));
+ });
+});
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/settings-store.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/settings-store.test.ts
index 3c1d758881..afeec517b5 100644
--- a/apps/desktop/src/main/right-sidebar-window/__tests__/settings-store.test.ts
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/settings-store.test.ts
@@ -28,6 +28,7 @@ vi.mock('../../maker-host/logger-adapter.js', () => ({
import {
normalizeRsbWindowSettings,
readRsbWindowSettings,
+ resetRsbWindowSettingsForStartup,
writeRsbWindowSettingsPatch,
} from '../settings-store.js';
@@ -35,6 +36,7 @@ const settingsFile = path.join(tmpUserData, 'right-sidebar-window-settings.json'
beforeEach(() => {
if (fs.existsSync(settingsFile)) fs.unlinkSync(settingsFile);
+ resetRsbWindowSettingsForStartup();
});
afterEach(() => {
@@ -60,17 +62,28 @@ describe('normalizeRsbWindowSettings', () => {
});
});
-describe('read / writePatch round-trip', () => {
- it('writePatch 落盘 override,read 返回合并值', () => {
+describe('runtime state', () => {
+ it('writePatch 仅更新当前进程内状态', () => {
writeRsbWindowSettingsPatch({ detached: true });
expect(readRsbWindowSettings()).toEqual({ detached: true, lastOpen: false });
writeRsbWindowSettingsPatch({ lastOpen: true });
expect(readRsbWindowSettings()).toEqual({ detached: true, lastOpen: true });
- // 写回默认值 → override 键被清除(default+override 模型)
+ expect(fs.existsSync(settingsFile)).toBe(false);
+
writeRsbWindowSettingsPatch({ detached: false, lastOpen: false });
expect(readRsbWindowSettings()).toEqual({ detached: false, lastOpen: false });
expect(fs.existsSync(settingsFile)).toBe(false);
});
+
+ it('startup 重置运行态并删除旧版本的持久化分离偏好', () => {
+ writeRsbWindowSettingsPatch({ detached: true, lastOpen: true });
+ fs.writeFileSync(settingsFile, JSON.stringify({ detached: true, lastOpen: true }));
+
+ resetRsbWindowSettingsForStartup();
+
+ expect(readRsbWindowSettings()).toEqual({ detached: false, lastOpen: false });
+ expect(fs.existsSync(settingsFile)).toBe(false);
+ });
});
diff --git a/apps/desktop/src/main/right-sidebar-window/controller.ts b/apps/desktop/src/main/right-sidebar-window/controller.ts
index f24bb26a4b..b7ab7f097e 100644
--- a/apps/desktop/src/main/right-sidebar-window/controller.ts
+++ b/apps/desktop/src/main/right-sidebar-window/controller.ts
@@ -3,16 +3,16 @@
*
* 三态模型(与偏好 detached / 运行时窗口开闭正交组合):
* A. detached=false —— 现状:侧边栏内嵌在主窗
- * B. detached=true, 窗口关闭 —— 偏好开着但用户收起了(关了子窗口)
+ * B. detached=true, 窗口关闭 —— 偏好开着但用户收起了(隐藏子窗口)
* C. detached=true, 窗口打开 —— 侧边栏活在子窗口里
*
- * 职责:
- * - 窗口生命周期(单实例,重复 open = focus;closed 事件区分用户关窗 vs app 退出)
- * - 偏好 / lastOpen 落盘(settings-store),状态变化广播所有窗口
- * - 渲染上下文中转(主窗上报 → 缓存 → 转发子窗口)
- * - RSB host webContents 解析(浏览器自动化 backend 的 tab-op / pin 通知路由):
- * detached && 窗口开 → 子窗口,否则主窗
- * - ensureOpenForAutomation:agent tab-op 在 B 态时先开窗、等 renderer ready 握手
+ * 生命周期基线对齐 PR #2434 的 ResourceUsageWindowController 与
+ * docs/dev-rules/electron-security-and-process-boundaries.md §3.1:
+ * - 后台预热:创建隐藏窗口 + renderer 挂载 + 首份 context 就绪
+ * - 双阶段就绪握手(renderer-ready → presentation-ready),超时展示 Loading 壳
+ * - 隐藏复用:普通关窗只 hide,setDetached(false) 才真正 dispose
+ * - 崩溃恢复有界
+ * - 隐藏时暂停后台重活、重置瞬时交互态
*
* 不直接 import electron —— BrowserWindow 的创建 / 主窗引用 / 广播全部由
* bootstrap-electron 注入,单测用 mock deps 直接驱动状态机。
@@ -27,11 +27,19 @@ import type {
RsbWindowContext,
RsbWindowState,
} from '../../shared/rightSidebarWindow.js';
+import {
+ RSB_WINDOW_LOCALE_CHANGED_CHANNEL,
+ RSB_WINDOW_PRESENTATION_READY_CHANNEL,
+ RSB_WINDOW_RENDERER_READY_CHANNEL,
+ RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL,
+} from '../../shared/rightSidebarWindow.js';
+import type { SupportedLocale } from '../../shared/locale.js';
import type { RsbWindowSettings } from './settings-store.js';
interface ControllerLogger {
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
+ error(message: string, ...args: unknown[]): void;
}
export interface RsbWindowControllerDeps {
@@ -41,9 +49,9 @@ export interface RsbWindowControllerDeps {
};
/**
* 创建子窗口(不负责挂 closed 钩子,controller 自己挂)。
- * userInitiated=false 时实现方须用不抢焦点的方式显示(showInactive)。
+ * 窗口以 show:false 创建,由 controller 的 presentation-ready 握手决定展示时机。
*/
- createWindow: (opts: { userInitiated: boolean }) => BrowserWindow;
+ createWindow: () => BrowserWindow;
getMainWindow: () => BrowserWindow | null;
/** 状态变化广播(所有窗口)。bootstrap 注入 getAllWindows 遍历实现。 */
broadcastState: (state: { detached: boolean; open: boolean }) => void;
@@ -59,6 +67,10 @@ export interface RsbWindowControllerDeps {
/** ensureOpenForAutomation 等 renderer ready 握手的超时。 */
const READY_TIMEOUT_MS = 8000;
+const DEFAULT_OPEN_TIMEOUT_MS = 5000;
+const DEFAULT_PREWARM_TIMEOUT_MS = 10_000;
+const DEFAULT_RECOVERY_STABILITY_MS = 30_000;
+const MAX_AUTOMATIC_RECOVERY_ATTEMPTS = 1;
const MAX_DEFERRED_SESSIONS = 8;
/**
* 单会话 deferred 队列上限。正常路径远达不到(passive 命令种类有限且有合并
@@ -91,15 +103,21 @@ function segmentAfterLastOrcaClose(queue: readonly RsbWindowCommand[]): readonly
export class RsbWindowController {
private winRef: BrowserWindow | null = null;
- /** BrowserWindow.close() 到 closed 事件之间仍未 destroyed,不能继续当活 host。 */
- private closing = false;
- /** 子窗口 renderer 根组件已挂载(READY 握手过)。窗口销毁时复位。 */
- private ready = false;
+ private destroyingWindow = false;
+ private rendererReady = false;
+ private presentationReady = false;
+ private visible = false;
+ private pendingOpen = false;
+ private disposed = false;
private readyWaiters: Array<{
resolve: () => void;
reject: (err: Error) => void;
timeout: NodeJS.Timeout;
}> = [];
+ private openTimeout: NodeJS.Timeout | null = null;
+ private prewarmTimeout: NodeJS.Timeout | null = null;
+ private recoveryStabilityTimeout: NodeJS.Timeout | null = null;
+ private automaticRecoveryAttempts = 0;
private lastContext: RsbWindowContext | null = null;
/**
* allowOpen=false 时按宿主 session 保序排队的 deferred 命令。
@@ -112,105 +130,185 @@ export class RsbWindowController {
* 帧与「generic ensure 不得顶掉更具体的 Orca intent」在 enqueue 时合并。
*/
private deferredCommands = new Map<string, RsbWindowCommand[]>();
- private closeWaiters: Array<() => void> = [];
+ private locale: SupportedLocale | null = null;
constructor(private readonly deps: RsbWindowControllerDeps) {}
+ // ══════════════════════════════════════════════════════════════════════
+ // 公共接口
+ // ══════════════════════════════════════════════════════════════════════
+
getState(): RsbWindowState {
const s = this.deps.settings.read();
- return { detached: s.detached, lastOpen: s.lastOpen, open: this.isOpen() };
+ // pendingOpen:窗口已创建但等待 presentation-ready,外部视为 open。
+ return { detached: s.detached, lastOpen: s.lastOpen, open: this.isOpen() || this.pendingOpen };
+ }
+
+ /** 后台预热:主窗口首帧后创建隐藏窗口并挂载 renderer。不改变用户焦点。 */
+ prewarm(): void {
+ if (this.disposed) return;
+ this.ensureWindow();
+ }
+
+ setLocale(locale: SupportedLocale): void {
+ this.locale = locale;
+ if (!this.winRef || this.winRef.isDestroyed()) return;
+ try {
+ this.winRef.webContents.send(RSB_WINDOW_LOCALE_CHANGED_CHANNEL, locale);
+ } catch {
+ // Window may be tearing down.
+ }
}
/**
- * 幂等打开:已开则 show + focus;未开则建窗 + lastOpen=true + 广播。
- *
- * userInitiated(缺省 true)= 这次开窗是用户当次手势要求的,保持既有
- * 「带出并聚焦子窗口」行为。程序自发的开窗(插件 preview 槽、agent
- * 浏览器自动化)必须传 false:
- * - 窗口已经开着 → **什么都不做**。内容经命令通道照常送达,用户看得见;
- * 这里再 show/focus 只会把用户正在用的别的应用顶掉(Windows 上
- * focus() 即抢前台),属于纯粹的干扰。
- * - 窗口还没开 → 照常建窗,但由 createWindow 走 showInactive 不抢焦点。
+ * 幂等打开:热窗口(presentationReady)立即显示;冷窗口等待首份业务内容,
+ * 超时按 Loading 壳兜底。
*/
open(opts: { userInitiated?: boolean } = {}): void {
+ if (this.disposed) return;
const userInitiated = opts.userInitiated !== false;
+
+ this.automaticRecoveryAttempts = 0;
+ this.clearRecoveryStabilityTimeout();
+ this.deps.settings.writePatch({ lastOpen: true });
+
if (this.winRef && !this.winRef.isDestroyed()) {
- if (this.closing) return;
if (!userInitiated) return;
- if (this.winRef.isMinimized()) this.winRef.restore();
- this.winRef.show();
- this.winRef.focus();
+ if (this.visible && this.winRef.isVisible()) {
+ this.winRef.focus();
+ return;
+ }
+ if (this.presentationReady) {
+ this.showAndFocus(this.winRef);
+ return;
+ }
+ // 窗口存在但渲染尚未完成,等待 presentation-ready 或超时
+ this.winRef.webContents.setBackgroundThrottling(false);
+ this.pendingOpen = true;
+ this.scheduleOpenFallback(this.winRef);
+ this.broadcast();
return;
}
- const win = this.deps.createWindow({ userInitiated });
- this.winRef = win;
- this.closing = false;
- this.ready = false;
- win.on('close', (event) => {
- if (this.deps.isQuitting() || this.deps.canCloseWindow?.() !== false) return;
- event.preventDefault();
- this.closing = false;
- this.deps.log.warn('right-sidebar window close blocked by active browser popup');
- });
- win.on('closed', () => this.onClosed());
- this.deps.settings.writePatch({ lastOpen: true });
+
+ this.pendingOpen = true;
+ const win = this.ensureWindow();
+ if (!win) {
+ this.pendingOpen = false;
+ return;
+ }
+ if (this.presentationReady) {
+ this.showAndFocus(win);
+ return;
+ }
+ this.scheduleOpenFallback(win);
this.broadcast();
- this.deps.log.info('right-sidebar window opened');
}
- /** 关闭子窗口(toggle 收起 / 合并回主窗)。窗口不存在时也保证 lastOpen 落 false。 */
+ /** 普通关窗只隐藏(保留 renderer + context,供下次瞬时恢复)。 */
close(): void {
- this.deps.settings.writePatch({ lastOpen: false });
if (this.winRef && !this.winRef.isDestroyed()) {
- // onClosed 会广播 {open:false},这里不重复
- this.closing = true;
- this.winRef.close();
+ this.hideWindow(this.winRef);
} else {
- this.closing = false;
+ this.deps.settings.writePatch({ lastOpen: false });
+ this.pendingOpen = false;
this.broadcast();
}
}
- /** 写偏好;true 附带开窗,false 附带关窗。返回新 state 供 invoke handler 直接回。 */
+ /** 写偏好;true 附带开窗,false 附带真正销毁窗口 + 恢复主窗内嵌侧栏。 */
setDetached(next: boolean): RsbWindowState {
this.deps.settings.writePatch({ detached: next });
if (next) {
- // 唯一入口是用户点「在新窗口中打开」按钮 —— 明确的用户手势,该带出并聚焦。
this.open({ userInitiated: true });
} else {
- // queued 调用方早已返回;attach 时必须把 ownership 显式交回主 renderer。
this.flushDeferredCommandsToAttachedHost();
- this.close();
+ this.disposeCachedWindow();
}
- // open()/close() 已各自广播,但两者都可能命中"窗口状态没变"的幂等分支
- // (如重复 setDetached(true)),兜底再广播一次保证 detached 变化必达。
- this.broadcast();
return this.getState();
}
- /** 子窗口 renderer 根组件挂载握手。 */
- markReady(): void {
- this.ready = true;
+ // ── 双阶段就绪握手 ─────────────────────────────────────────────────
+
+ /** renderer 根组件已挂载;用于确认超时兜底至少有 React 壳可展示。 */
+ markRendererReady(sender: WebContents): boolean {
+ const win = this.winRef;
+ if (!win || win.isDestroyed() || sender !== win.webContents) return false;
+ this.rendererReady = true;
+ if (this.locale) {
+ try {
+ sender.send(RSB_WINDOW_LOCALE_CHANGED_CHANNEL, this.locale);
+ } catch {
+ // Renderer may be tearing down.
+ }
+ }
+ return true;
+ }
+
+ /** 首份业务内容已提交;隐藏预热到此结束。 */
+ markPresentationReady(sender: WebContents): boolean {
+ const win = this.winRef;
+ if (!win || win.isDestroyed() || sender !== win.webContents) return false;
+ this.presentationReady = true;
+ // 预热期间临时保持 renderer 可调度,避免 show:false 窗口的 React effect / IPC
+ // 被后台节流拖到点击路径。壳首帧提交后立即恢复 Electron 默认节流策略。
+ sender.setBackgroundThrottling(true);
+ this.scheduleRecoveryStabilityReset();
+ this.clearPrewarmTimeout();
const waiters = this.readyWaiters.splice(0);
for (const w of waiters) {
clearTimeout(w.timeout);
w.resolve();
}
+ if (this.pendingOpen) {
+ this.showAndFocus(win);
+ }
+ // 无论是纯预热还是用户点击打开,presentation-ready 都是 deferred
+ // command 可以安全交付的统一边界。不能在 showAndFocus 后提前返回,否则
+ // 点击路径会永久留下此前排队的 passive intent。
this.flushDeferredCommandsToDetachedHost();
+ return true;
}
+ /** 子窗口请求刷新 context(从 main 缓存拉最新值推回)。 */
+ refreshContext(sender: WebContents): void {
+ const win = this.winRef;
+ if (!win || win.isDestroyed() || sender !== win.webContents) return;
+ if (!this.lastContext) return;
+ this.deps.sendToWindow(win, this.deps.contextChannel, this.lastContext);
+ }
+
+ // ── 生命周期 ────────────────────────────────────────────────────────
+
+ /** 主窗口真实销毁时回收其子窗口;controller 仍可随下一扇主窗口重新预热。 */
+ destroyWindow(): void {
+ this.clearOpenTimeout();
+ this.clearPrewarmTimeout();
+ this.pendingOpen = false;
+ if (!this.winRef || this.winRef.isDestroyed()) {
+ this.resetWindowState();
+ return;
+ }
+ this.destroyCachedWindow();
+ }
+
+ /** 应用退出时永久停止该 controller,并同步销毁缓存窗口。 */
+ dispose(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.destroyWindow();
+ }
+
+ // ── ensureOpen / context / routeCommand ─────────────────────────────
+
/**
- * agent tab-op(浏览器自动化)前置:detached 且窗口未就绪时先开窗并等 ready 握手,
- * 保证 dispatchTabOp 时子窗口 renderer 的 RSB store / webview 池已可用。
- * 非 detached 时 no-op(host 是主窗,常驻)。
+ * agent tab-op(浏览器自动化)前置:detached 且窗口未就绪时先开窗并等 ready 握手。
*/
ensureOpenForAutomation(opts: { userInitiated?: boolean } = {}): Promise<void> {
if (!this.deps.settings.read().detached) return Promise.resolve();
- if (this.ready && this.winRef && !this.winRef.isDestroyed()) return Promise.resolve();
- // 缺省 false:本入口的名字就是 "for automation" —— 调用方没表态时按
- // 「程序自发」处理,不抢用户焦点。用户手势路径显式传 true。
+ if (this.presentationReady && this.winRef && !this.winRef.isDestroyed())
+ return Promise.resolve();
this.open({ userInitiated: opts.userInitiated === true });
- if (this.ready) return Promise.resolve();
+ if (this.presentationReady) return Promise.resolve();
return new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
const idx = this.readyWaiters.findIndex((w) => w.timeout === timeout);
@@ -221,7 +319,7 @@ export class RsbWindowController {
});
}
- /** 主窗上报渲染上下文:缓存 + 窗口开着就转发。 */
+ /** 主窗上报渲染上下文:缓存 + 窗口活跃就转发。 */
setContext(ctx: RsbWindowContext): void {
const previousSessionId = this.lastContext?.sessionId ?? null;
this.lastContext = ctx;
@@ -232,7 +330,7 @@ export class RsbWindowController {
if (sessionId !== ctx.sessionId) this.deferredCommands.delete(sessionId);
}
}
- if (this.winRef && !this.winRef.isDestroyed() && !this.closing) {
+ if (this.winRef && !this.winRef.isDestroyed()) {
this.deps.sendToWindow(this.winRef, this.deps.contextChannel, ctx);
}
this.flushDeferredCommandsToDetachedHost();
@@ -242,39 +340,22 @@ export class RsbWindowController {
return this.lastContext;
}
- private canDispatchCommand(cmd: RsbWindowCommand): boolean {
- return Boolean(
- this.lastContext?.available &&
- this.lastContext.sessionId &&
- this.lastContext.sessionId === commandHostSessionId(cmd),
- );
- }
-
/** main 原子裁决 command ownership;renderer 只在 attached 结果下写本地 store。 */
async routeCommand(
request: RsbWindowCommandRouteRequest,
): Promise<RsbWindowCommandRouteResult> {
const { command, allowOpen } = request;
- // 缺省 true:既有调用点绝大多数是用户手势(点链接 / 菜单 / 快捷键),行为不变。
- // 插件 preview 槽与 agent 自动化显式传 false,只送内容不抢焦点。
const userInitiated = request.userInitiated !== false;
if (!this.deps.settings.read().detached) return 'attached';
if (!this.canDispatchCommand(command)) return 'stale-context';
- if (!allowOpen && (this.closing || !this.isOpen() || !this.ready)) {
+ const windowAlive = this.winRef && !this.winRef.isDestroyed();
+ if (!allowOpen && (!windowAlive || !this.presentationReady)) {
this.enqueueDeferredCommand(command);
return 'queued';
}
- if (this.closing) {
- // 终端快捷键由 renderer 做短时、可取消的专属重试。closing 阶段立即返回,
- // 避免旧调用等待 close 后再开窗并悬挂在 8s ready timeout,也避免晚到后重复派发。
- if (allowOpen && command.type === 'open-terminal') return 'stale-context';
- await this.waitUntilClosed();
- return this.routeCommand(request);
- }
-
- if (allowOpen && (!this.isOpen() || !this.ready)) {
+ if (allowOpen && (!this.isOpen() || !this.presentationReady)) {
try {
await this.ensureOpenForAutomation({ userInitiated });
} catch (err) {
@@ -284,18 +365,10 @@ export class RsbWindowController {
}
}
- // ready 等待期间 detach 偏好或主窗 session 都可能变化,发送前必须二次裁决。
if (!this.deps.settings.read().detached) return 'attached';
if (!this.canDispatchCommand(command)) return 'stale-context';
- if (this.closing) {
- if (!allowOpen) {
- this.enqueueDeferredCommand(command);
- return 'queued';
- }
- await this.waitUntilClosed();
- return this.routeCommand(request);
- }
- if (!this.isOpen() || !this.ready || !this.winRef) {
+ const windowReady = this.winRef && !this.winRef.isDestroyed() && this.presentationReady;
+ if (!windowReady) {
if (!allowOpen) {
this.enqueueDeferredCommand(command);
return 'queued';
@@ -303,13 +376,306 @@ export class RsbWindowController {
return 'stale-context';
}
- this.deps.sendToWindow(this.winRef, this.deps.commandChannel, command);
+ const win = this.winRef;
+ if (!win || win.isDestroyed()) return 'stale-context';
+ this.deps.sendToWindow(win, this.deps.commandChannel, command);
return 'routed';
}
+ // ══════════════════════════════════════════════════════════════════════
+ // 窗口生命周期
+ // ══════════════════════════════════════════════════════════════════════
+
+ getHostWebContents(): WebContents | null {
+ if (
+ this.deps.settings.read().detached &&
+ this.winRef &&
+ !this.winRef.isDestroyed()
+ ) {
+ return this.winRef.webContents;
+ }
+ const main = this.deps.getMainWindow();
+ return main && !main.isDestroyed() ? main.webContents : null;
+ }
+
+ /** IPC 层校验 sender 用。 */
+ getSidebarWebContents(): WebContents | null {
+ return this.winRef && !this.winRef.isDestroyed()
+ ? this.winRef.webContents
+ : null;
+ }
+
+ /** 窗口存在 + 可见(隐藏复用模型中隐藏不算 open)。 */
+ isOpen(): boolean {
+ return (
+ this.winRef !== null &&
+ !this.winRef.isDestroyed() &&
+ this.visible
+ );
+ }
+
+ // ══════════════════════════════════════════════════════════════════════
+ // 内部实现
+ // ══════════════════════════════════════════════════════════════════════
+
+ private ensureWindow(): BrowserWindow | null {
+ if (this.winRef && !this.winRef.isDestroyed()) return this.winRef;
+ let win: BrowserWindow;
+ try {
+ win = this.deps.createWindow();
+ } catch (error) {
+ this.resetWindowState();
+ this.deps.log.warn('right-sidebar window creation failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return null;
+ }
+ this.winRef = win;
+ this.rendererReady = false;
+ this.presentationReady = false;
+ this.visible = false;
+ this.destroyingWindow = false;
+ // 只覆盖隐藏预热的短暂初始化阶段。presentation-ready 后会恢复为 true,
+ // 因此长期隐藏复用仍按 Electron 默认策略节流,不增加持续后台开销。
+ win.webContents.setBackgroundThrottling(false);
+
+ win.on('close', (event) => {
+ if (this.destroyingWindow || this.disposed) return;
+ event.preventDefault();
+ if (this.deps.canCloseWindow?.() === false) {
+ this.deps.log.warn('right-sidebar window close blocked by active browser popup');
+ return;
+ }
+ this.hideWindow(win);
+ });
+ win.on('closed', () => this.onClosed(win));
+ // 原生最小化不会触发 controller.close(),但对主窗口来说同样需要一个
+ // 可恢复入口。把 minimized 映射为 open:false,同时保留 lastOpen 和
+ // renderer;用户点击入口时 open() 会 restore + focus 同一个热窗口。
+ win.on('show', () => this.onNativeVisibilityChanged(win, true));
+ win.on('restore', () => this.onNativeVisibilityChanged(win, true));
+ win.on('hide', () => this.onNativeVisibilityChanged(win, false));
+ win.on('minimize', () => this.onNativeVisibilityChanged(win, false));
+ win.webContents.on('did-start-navigation', (_event, _url, isInPlace, isMainFrame) => {
+ if (isMainFrame && !isInPlace) this.onRendererReloadStarted(win);
+ });
+ win.webContents.on(
+ 'did-fail-load',
+ (_event, errorCode, errorDescription, _validatedUrl, isMainFrame) => {
+ if (isMainFrame && errorCode !== -3) {
+ this.invalidateWindow(win, `load failed (${errorCode}): ${errorDescription}`);
+ }
+ },
+ );
+ win.webContents.on('render-process-gone', (_event, details) => {
+ this.invalidateWindow(win, `renderer process gone: ${details.reason}`);
+ });
+
+ this.schedulePrewarmFallback(win);
+ return win;
+ }
+
+ private showAndFocus(win: BrowserWindow): void {
+ this.clearOpenTimeout();
+ this.clearPrewarmTimeout();
+ this.pendingOpen = false;
+ if (win.isMinimized()) win.restore();
+ win.webContents.setBackgroundThrottling(true);
+ win.show();
+ win.focus();
+ this.visible = true;
+ // lastOpen 由 open() 在外层写,这里只负责展示
+ this.deps.sendToWindow(win, RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible: true });
+ this.broadcast();
+ }
+
+ private hideWindow(win: BrowserWindow): void {
+ this.clearOpenTimeout();
+ this.clearPrewarmTimeout();
+ this.pendingOpen = false;
+ if (win.isVisible()) win.hide();
+ this.visible = false;
+ try {
+ this.deps.sendToWindow(win, RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible: false });
+ } catch {
+ // 窗口可能在 isVisible 检查与 send 之间被系统销毁
+ }
+ this.deps.settings.writePatch({ lastOpen: false });
+ this.broadcast();
+ this.deps.log.info('right-sidebar window hidden');
+ }
+
+ private onNativeVisibilityChanged(win: BrowserWindow, visible: boolean): void {
+ if (win !== this.winRef || win.isDestroyed() || this.destroyingWindow || this.disposed) return;
+ if (this.visible === visible && !this.pendingOpen) return;
+ this.visible = visible;
+ if (visible) this.pendingOpen = false;
+ try {
+ this.deps.sendToWindow(win, RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL, { visible });
+ } catch {
+ // Native visibility can change while the renderer is tearing down.
+ }
+ this.broadcast();
+ }
+
+ private onClosed(win: BrowserWindow): void {
+ if (win !== this.winRef) return;
+ this.resetWindowState();
+ }
+
+ private resetWindowState(): void {
+ this.clearOpenTimeout();
+ this.clearPrewarmTimeout();
+ // 注意:不清理 recoveryStabilityTimeout — 它跟踪的是 controller 级别的
+ // 自动恢复额度,不跟随单个窗口实例的销毁而去。
+ this.winRef = null;
+ this.rendererReady = false;
+ this.presentationReady = false;
+ this.visible = false;
+ this.pendingOpen = false;
+ this.destroyingWindow = false;
+
+ const waiters = this.readyWaiters.splice(0);
+ for (const w of waiters) {
+ clearTimeout(w.timeout);
+ w.reject(new Error('right-sidebar window closed before ready'));
+ }
+
+ if (this.deps.isQuitting()) return;
+ this.deps.settings.writePatch({ lastOpen: false });
+ this.broadcast();
+ this.deps.log.info('right-sidebar window closed');
+ }
+
+ // ── 超时与恢复 ────────────────────────────────────────────────────
+
+ private scheduleOpenFallback(win: BrowserWindow): void {
+ this.clearOpenTimeout();
+ this.openTimeout = setTimeout(() => {
+ this.openTimeout = null;
+ if (win !== this.winRef || win.isDestroyed() || !this.pendingOpen) return;
+ // renderer shell 未就绪时仍展示(loadURL 在 BrowserWindow 创建时就开始了,
+ // 5s 足够 Electron 完成 HTML 加载和 React 根挂载);即使只有 Loading 壳也是
+ // 可辨识的反馈,比永久不给用户任何反应好。
+ if (!this.rendererReady && !this.visible) {
+ this.deps.log.warn('right-sidebar open timed out before renderer-ready');
+ }
+ if (!this.visible) this.showAndFocus(win);
+ }, DEFAULT_OPEN_TIMEOUT_MS);
+ this.openTimeout.unref?.();
+ }
+
+ private schedulePrewarmFallback(win: BrowserWindow): void {
+ this.clearPrewarmTimeout();
+ if (this.visible || this.pendingOpen) return;
+ this.prewarmTimeout = setTimeout(() => {
+ this.prewarmTimeout = null;
+ if (win !== this.winRef || win.isDestroyed() || this.visible || this.pendingOpen) return;
+ win.webContents.setBackgroundThrottling(true);
+ this.deps.log.warn('right-sidebar prewarm timed out; keeping cached window');
+ }, DEFAULT_PREWARM_TIMEOUT_MS);
+ this.prewarmTimeout.unref?.();
+ }
+
+ private scheduleRecoveryStabilityReset(): void {
+ this.clearRecoveryStabilityTimeout();
+ if (this.automaticRecoveryAttempts === 0) return;
+ this.recoveryStabilityTimeout = setTimeout(() => {
+ this.recoveryStabilityTimeout = null;
+ this.automaticRecoveryAttempts = 0;
+ }, DEFAULT_RECOVERY_STABILITY_MS);
+ this.recoveryStabilityTimeout.unref?.();
+ }
+
+ private clearOpenTimeout(): void {
+ if (!this.openTimeout) return;
+ clearTimeout(this.openTimeout);
+ this.openTimeout = null;
+ }
+
+ private clearPrewarmTimeout(): void {
+ if (!this.prewarmTimeout) return;
+ clearTimeout(this.prewarmTimeout);
+ this.prewarmTimeout = null;
+ }
+
+ private clearRecoveryStabilityTimeout(): void {
+ if (!this.recoveryStabilityTimeout) return;
+ clearTimeout(this.recoveryStabilityTimeout);
+ this.recoveryStabilityTimeout = null;
+ }
+
+ // ── 崩溃恢复 ─────────────────────────────────────────────────────
+
+ private onRendererReloadStarted(win: BrowserWindow): void {
+ if (win !== this.winRef || win.isDestroyed()) return;
+ const shouldRestore = this.visible || this.pendingOpen;
+ if (shouldRestore) this.pendingOpen = true;
+ if (this.visible) win.hide();
+ win.webContents.setBackgroundThrottling(false);
+ this.rendererReady = false;
+ this.presentationReady = false;
+ if (shouldRestore) {
+ this.scheduleOpenFallback(win);
+ return;
+ }
+ this.schedulePrewarmFallback(win);
+ }
+
+ private invalidateWindow(win: BrowserWindow, reason: string): void {
+ if (win !== this.winRef || win.isDestroyed()) return;
+ const reopen = this.pendingOpen || this.visible;
+ this.deps.log.warn('right-sidebar cached window invalidated', { reason, reopen });
+ this.destroyCachedWindow();
+ if (!reopen || this.disposed) return;
+ if (this.automaticRecoveryAttempts >= MAX_AUTOMATIC_RECOVERY_ATTEMPTS) {
+ this.deps.log.error('right-sidebar automatic recovery exhausted', { reason });
+ return;
+ }
+ this.automaticRecoveryAttempts += 1;
+ this.pendingOpen = true;
+ const replacement = this.ensureWindow();
+ if (!replacement) {
+ this.pendingOpen = false;
+ return;
+ }
+ this.scheduleOpenFallback(replacement);
+ }
+
+ // ── 销毁 ─────────────────────────────────────────────────────────
+
+ private destroyCachedWindow(): void {
+ const win = this.winRef;
+ if (!win || win.isDestroyed()) {
+ this.resetWindowState();
+ return;
+ }
+ this.resetWindowState();
+ this.destroyingWindow = true;
+ try {
+ if (!win.isDestroyed()) win.destroy();
+ } finally {
+ this.destroyingWindow = false;
+ }
+ }
+
+ private disposeCachedWindow(): void {
+ this.destroyCachedWindow();
+ this.broadcast();
+ this.deps.log.info('right-sidebar window disposed (merged back to main)');
+ }
+
+ // ── 命令路由辅助 ─────────────────────────────────────────────────
+
+ private canDispatchCommand(cmd: RsbWindowCommand): boolean {
+ return Boolean(
+ this.lastContext?.available &&
+ this.lastContext.sessionId &&
+ this.lastContext.sessionId === commandHostSessionId(cmd),
+ );
+ }
+
private enqueueDeferredCommand(command: RsbWindowCommand): void {
- // 按宿主桶排队:跨会话 open-turn-review 属于 lead 的桶,须由 lead 上下文
- // flush;按 worker sessionId 入队会在 context 保持 lead 时永远刷不出来。
const hostSessionId = commandHostSessionId(command);
const queue = this.deferredCommands.get(hostSessionId);
// Orca 既有优先规则:队列里已有 ensure-orca intent(带定位与否都算)时,
@@ -390,15 +756,19 @@ export class RsbWindowController {
private flushDeferredCommandsToDetachedHost(): void {
if (
!this.deps.settings.read().detached ||
- this.closing ||
- !this.ready ||
+ !this.presentationReady ||
!this.winRef ||
this.winRef.isDestroyed()
) {
return;
}
this.flushDeferredCommands(
- () => Boolean(this.winRef && !this.winRef.isDestroyed() && !this.closing),
+ () => Boolean(
+ this.winRef &&
+ !this.winRef.isDestroyed() &&
+ !this.destroyingWindow &&
+ !this.disposed,
+ ),
(command) => this.deps.sendToWindow(this.winRef!, this.deps.commandChannel, command),
);
}
@@ -413,60 +783,9 @@ export class RsbWindowController {
);
}
- private waitUntilClosed(): Promise<void> {
- if (!this.closing) return Promise.resolve();
- return new Promise((resolve) => this.closeWaiters.push(resolve));
- }
-
- /**
- * RSB host webContents —— rsb-browser-bridge 的 pin/unpin 通知与 tab-op dispatch
- * 目标窗口。detached 且子窗口活着 → 子窗口;否则回落主窗(内嵌形态)。
- */
- getHostWebContents(): WebContents | null {
- if (
- this.deps.settings.read().detached &&
- !this.closing &&
- this.winRef &&
- !this.winRef.isDestroyed()
- ) {
- return this.winRef.webContents;
- }
- const main = this.deps.getMainWindow();
- return main && !main.isDestroyed() ? main.webContents : null;
- }
-
- /** IPC 层校验 READY 握手 sender 用。 */
- getSidebarWebContents(): WebContents | null {
- return !this.closing && this.winRef && !this.winRef.isDestroyed()
- ? this.winRef.webContents
- : null;
- }
-
- private isOpen(): boolean {
- return this.winRef !== null && !this.closing && !this.winRef.isDestroyed();
- }
-
- private onClosed(): void {
- this.winRef = null;
- this.ready = false;
- this.closing = false;
- const closeWaiters = this.closeWaiters.splice(0);
- closeWaiters.forEach((resolve) => resolve());
- // 悬着的 ready 等待全部失败(窗口没等到挂载就没了)
- const waiters = this.readyWaiters.splice(0);
- for (const w of waiters) {
- clearTimeout(w.timeout);
- w.reject(new Error('right-sidebar window closed before ready'));
- }
- // app 退出路径:保留 lastOpen=true 供下次启动恢复,也不必广播(所有窗口都在销毁)
- if (this.deps.isQuitting()) return;
- this.deps.settings.writePatch({ lastOpen: false });
- this.broadcast();
- this.deps.log.info('right-sidebar window closed');
- }
-
private broadcast(): void {
const s = this.deps.settings.read();
- this.deps.broadcastState({ detached: s.detached, open: this.isOpen() });
+ // pendingOpen:窗口已创建但等待 presentation-ready,从调用方视角视为 open。
+ this.deps.broadcastState({ detached: s.detached, open: this.isOpen() || this.pendingOpen });
}
}
diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.ts
index 742231a06c..1ce6b9f4fb 100644
--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts
+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts
@@ -18,6 +18,11 @@ import type {
RsbWindowCommandRouteRequest,
RsbWindowContext,
} from '../../shared/rightSidebarWindow.js';
+import {
+ RSB_WINDOW_PRESENTATION_READY_CHANNEL,
+ RSB_WINDOW_REFRESH_CONTEXT_CHANNEL,
+ RSB_WINDOW_RENDERER_READY_CHANNEL,
+} from '../../shared/rightSidebarWindow.js';
import { parseConversationSearchJump } from '../../shared/conversationSearchJump.js';
import { hasActiveRsbNativePopupSurfaces } from '../rsb-browser-bridge/native-popup-surfaces.js';
import type { RsbWindowController } from './controller.js';
@@ -281,15 +286,46 @@ export function registerRsbWindowIpc(opts: {
ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_GET_CONTEXT, () => controller.getContext());
ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_READY, (event) => {
- // 只有子窗口 renderer 的握手才算数,主窗误调不置 ready(避免 ensureOpen 提前放行)
+ // 存量 READY 握手映射到 renderer-ready:renderer shell 已挂载。
const sidebarWc = controller.getSidebarWebContents();
if (!sidebarWc || event.sender !== sidebarWc) {
log.warn('RSB_WINDOW_READY from non-sidebar sender, ignored');
return;
}
- controller.markReady();
+ controller.markRendererReady(event.sender);
});
+ // ── 双阶段就绪 + context 刷新(对齐 PR #2434 基线) ────────────────
+
+ ipcMain.handle(RSB_WINDOW_RENDERER_READY_CHANNEL, (event) => {
+ const sidebarWc = controller.getSidebarWebContents();
+ if (!sidebarWc || event.sender !== sidebarWc) {
+ log.warn('RSB_WINDOW_RENDERER_READY from non-sidebar sender, ignored');
+ return;
+ }
+ controller.markRendererReady(event.sender);
+ });
+
+ ipcMain.handle(RSB_WINDOW_PRESENTATION_READY_CHANNEL, (event) => {
+ const sidebarWc = controller.getSidebarWebContents();
+ if (!sidebarWc || event.sender !== sidebarWc) {
+ log.warn('RSB_WINDOW_PRESENTATION_READY from non-sidebar sender, ignored');
+ return;
+ }
+ controller.markPresentationReady(event.sender);
+ });
+
+ ipcMain.handle(RSB_WINDOW_REFRESH_CONTEXT_CHANNEL, (event) => {
+ const sidebarWc = controller.getSidebarWebContents();
+ if (!sidebarWc || event.sender !== sidebarWc) {
+ log.warn('RSB_WINDOW_REFRESH_CONTEXT from non-sidebar sender, ignored');
+ return;
+ }
+ controller.refreshContext(event.sender);
+ });
+
+ // ── 命令路由 ─────────────────────────────────────────────────────
+
ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_SEND_COMMAND, async (event, payload: unknown) => {
// 参数错误无论 sender 身份都按 IPC 契约抛 INVALID_PARAMS。
const request = parseCommandRouteRequest(payload);
diff --git a/apps/desktop/src/main/right-sidebar-window/registry.ts b/apps/desktop/src/main/right-sidebar-window/registry.ts
new file mode 100644
index 0000000000..db4515a2e3
--- /dev/null
+++ b/apps/desktop/src/main/right-sidebar-window/registry.ts
@@ -0,0 +1,18 @@
+/**
+ * RSB window WebContents id registry.
+ *
+ * The RSB window is an independently recoverable auxiliary renderer; its crash
+ * must not trigger the main app's fatal exit chain. WebContents ids never get
+ * reused within one Electron process, so an add-only set covers the gone/closed
+ * event race.
+ */
+
+const rsbWindowWebContentsIds = new Set<number>();
+
+export function markRsbWindowWebContentsId(id: number): void {
+ rsbWindowWebContentsIds.add(id);
+}
+
+export function isRsbWindowWebContentsId(id: number): boolean {
+ return rsbWindowWebContentsIds.has(id);
+}
diff --git a/apps/desktop/src/main/right-sidebar-window/settings-store.ts b/apps/desktop/src/main/right-sidebar-window/settings-store.ts
index 39c78e6a3c..ec8c9ccf2c 100644
--- a/apps/desktop/src/main/right-sidebar-window/settings-store.ts
+++ b/apps/desktop/src/main/right-sidebar-window/settings-store.ts
@@ -1,21 +1,16 @@
/**
- * right-sidebar-window settings-store —— 「侧边栏在新窗口中显示」的持久化。
+ * right-sidebar-window 进程内状态。
*
- * File: <userData>/right-sidebar-window-settings.json
- *
- * 两个字段语义不同但同生命周期、同读写方(都只由 main 的 RsbWindowController 写),
- * 所以放同一文件:
- * - detached: **偏好**(default false)。用户显式选择「侧边栏在新窗口打开」;
- * 走 override 模型(未自定义时跟随版本默认值,见 docs/dev-rules/configuration-and-overrides.md)。
- * - lastOpen: **状态**(default false)。退出时子窗口是否处于打开态,供下次启动
- * 恢复(detached && lastOpen → 主窗 mount 后自动重开子窗口)。不经 Settings UI。
+ * detached / lastOpen 只服务当前客户端进程,用于窗口状态机和隐藏复用;客户端重启后
+ * 一律回到主窗口。启动时还会删除旧版本留下的分离偏好文件,避免继续恢复历史状态。
+ * 窗口尺寸与位置由独立的 window-state 文件管理,不受这里影响。
*/
import { app } from 'electron';
+import fs from 'node:fs';
import path from 'node:path';
import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
-import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
const log = desktopMakerLogger.child('right-sidebar-window-settings-store');
@@ -29,6 +24,8 @@ const DEFAULTS: RsbWindowSettings = {
lastOpen: false,
};
+let runtimeSettings: RsbWindowSettings = { ...DEFAULTS };
+
function settingsFilePath(): string {
return path.join(app.getPath('userData'), 'right-sidebar-window-settings.json');
}
@@ -42,18 +39,21 @@ export function normalizeRsbWindowSettings(raw: unknown): RsbWindowSettings {
};
}
-const store = createOverrideSettingsFile<RsbWindowSettings>({
- filePath: settingsFilePath,
- defaults: DEFAULTS,
- normalize: normalizeRsbWindowSettings,
- log,
- label: 'right-sidebar-window',
-});
-
export function readRsbWindowSettings(): RsbWindowSettings {
- return store.read();
+ return { ...runtimeSettings };
}
export function writeRsbWindowSettingsPatch(patch: Partial<RsbWindowSettings>): void {
- store.writePatch(patch);
+ runtimeSettings = normalizeRsbWindowSettings({ ...runtimeSettings, ...patch });
+}
+
+/** 新进程重置分离状态,并清理旧版本遗留的持久化偏好。 */
+export function resetRsbWindowSettingsForStartup(): void {
+ runtimeSettings = { ...DEFAULTS };
+ const legacyFile = settingsFilePath();
+ try {
+ fs.rmSync(legacyFile, { force: true });
+ } catch (err) {
+ log.warn('failed to remove legacy right-sidebar window settings', { legacyFile, err });
+ }
}
diff --git a/apps/desktop/src/main/right-sidebar-window/window.ts b/apps/desktop/src/main/right-sidebar-window/window.ts
index fe75baccc8..3058e385e6 100644
--- a/apps/desktop/src/main/right-sidebar-window/window.ts
+++ b/apps/desktop/src/main/right-sidebar-window/window.ts
@@ -1,12 +1,14 @@
/**
* createRightSidebarWindow —— 右侧栏子窗口的 BrowserWindow 工厂。
*
- * frame / 外链守卫 / acceptFirstMouse 复刻 secondary-windows.ts(会话多开副窗),
- * 差异点:
- * - `webviewTag: true`:内嵌浏览器 plugin 需要 <webview>(副窗没有 RSB 不需要)
- * - 独立的窗口位置记忆文件 right-sidebar-window-state.json(不与主窗 window-state.json 串)
- * - 启动参数 `?sidebarWindow=1` + hash `/sidebar-window`:renderer 单入口,
- * router 据此只挂 SidebarWindowLayout(不挂 MainLayout 完整壳)
+ * 生命周期基线对齐 PR #2434:
+ * - 使用专用 sidebarWindowPreload.js(最小权限 bridge,不加载主 preload 完整桥)
+ * - 加载轻量渲染入口(sidebar-window-entry.tsx,不经过完整 main-entry)
+ * - 显式安全配置(§3.1 基线: sandbox + contextIsolation + 无 Node)
+ * - 隐藏预热:窗口以 show:false 创建,由 controller 的双阶段就绪握手决定展示时机
+ *
+ * frame / 外链守卫 / acceptFirstMouse 复刻 secondary-windows.ts(会话多开副窗)。
+ * 独立的窗口位置记忆文件 right-sidebar-window-state.json(不与主窗 window-state.json 串)。
*/
import { BrowserWindow, app, nativeTheme } from 'electron';
@@ -20,29 +22,17 @@ import { readWindowBehaviorSettings } from '../window-behavior-settings-store.js
import { installExternalLinkGuards } from '../secondary-windows.js';
import { installSelectionContextMenu } from '../selection-context-menu.js';
import { applyAppearanceToWindow } from '../appearance-settings-ipc.js';
+import { markRsbWindowWebContentsId } from './registry.js';
const log = createLogger('right-sidebar-window');
-export interface CreateRightSidebarWindowOptions {
- /**
- * 建窗是不是用户当次手势要求的。缺省 true = 首帧就绪后 show()(拿焦点)。
- * false(插件 preview / agent 自动化)走 showInactive():窗口照常出现在原位,
- * 但不夺走用户当前前台应用的焦点。
- */
- userInitiated?: boolean;
-}
-
-export function createRightSidebarWindow(
- options: CreateRightSidebarWindowOptions = {},
-): BrowserWindow {
- const userInitiated = options.userInitiated !== false;
+export function createRightSidebarWindow(): 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({
@@ -68,11 +58,23 @@ export function createRightSidebarWindow(
acceptFirstMouse: !swallowActivationClick,
...platformOptions,
webPreferences: {
- preload: path.join(__dirname, 'preload.js'),
+ // 使用专用预载脚本:右侧栏窗口只暴露 RSB 所需 bridge,不走主 preload。
+ preload: path.join(__dirname, 'sidebarWindowPreload.js'),
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
spellcheck: false,
webviewTag: true,
},
});
+ markRsbWindowWebContentsId(win.webContents.id);
markAppContentWindow(win);
applyAppearanceToWindow(win);
win.webContents.on('did-finish-load', () => {
@@ -84,10 +86,10 @@ export function createRightSidebarWindow(
installExternalLinkGuards(win);
+ // ready-to-show: 窗口以 show:false 创建,由 controller 的双阶段就绪握手
+ // (renderer-ready → presentation-ready) 控制展示时机,此处不做任何展示。
win.once('ready-to-show', () => {
- if (win.isDestroyed()) return;
- if (userInitiated) win.show();
- else win.showInactive();
+ // no-op — display is governed by RsbWindowController
});
const hash = '/sidebar-window';
diff --git a/apps/desktop/src/preload/ghostPanelWindowPreload.ts b/apps/desktop/src/preload/ghostPanelWindowPreload.ts
new file mode 100644
index 0000000000..1035fbd34e
--- /dev/null
+++ b/apps/desktop/src/preload/ghostPanelWindowPreload.ts
@@ -0,0 +1,229 @@
+/**
+ * 插件面板独立窗口专用 preload:最小权限 bridge。
+ *
+ * 能力清单基于 GhostPanelWindowLayout + GhostChipPanelBody + GhostMediaLightboxHost +
+ * ghostPanels + useInstalledGhosts + runtimeStates + ghostMediaHandover 的实际
+ * `window.electronAPI.*` 调用栈静态收窄:
+ * - 窗口 chrome(appearance / windowControls / shortcuts / theme)
+ * - 插件面板窗口状态(detach / attach)
+ * - 双阶段就绪握手 + visibility 刷新
+ * - 插件管理(list / reload / setEnabled / resolvePanelMedia / runtimeStates +
+ * 事件订阅 onChanged / onRuntimeChanged / onPreviewMedia)
+ * - 面板产物右键菜单媒体动作(copyMediaToClipboard / showItemInFolder)
+ * - 面板拖拽引渡落会话附件(cacheMediaForSession)
+ *
+ * 不得复制主 preload 的完整 ghosts bridge 或 maker/session/voice/login 桥。
+ */
+
+import { contextBridge, ipcRenderer } from 'electron';
+
+import type { AppearanceSettings } from '../shared/appearanceSettings';
+import type { LocalThemesResult } from '../shared/local-themes';
+import type { GhostPanelWindowsState } from '../shared/ghostPanelWindow';
+import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from '../shared/locale';
+import {
+ GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL,
+ GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL,
+ GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL,
+ GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL,
+ GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL,
+ GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL,
+ GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL,
+} from '../shared/ghostPanelWindow';
+
+type Unsub = () => void;
+type ApplicationMenuLocale = SupportedLocale;
+
+function readPreferredSystemLocale(): ApplicationMenuLocale {
+ try {
+ const value = ipcRenderer.sendSync('app-locale:get-preferred-system-locale-sync');
+ return typeof value === 'string' && (SUPPORTED_LOCALES as readonly string[]).includes(value)
+ ? (value as ApplicationMenuLocale)
+ : DEFAULT_LOCALE;
+ } catch {
+ return DEFAULT_LOCALE;
+ }
+}
+
+function onPayload<T>(channel: string, cb: (payload: T) => void): Unsub {
+ const listener = (_event: Electron.IpcRendererEvent, payload: T): void => cb(payload);
+ ipcRenderer.on(channel, listener);
+ return () => ipcRenderer.removeListener(channel, listener);
+}
+
+// 事件扇出型通道(main 广播 → 所有 renderer),按名注册 listener,fan-out 在 preload 层。
+function fanOut(channel: string): (cb: (payload: unknown) => void) => Unsub {
+ return (cb) => {
+ const listener = (_event: Electron.IpcRendererEvent, payload: unknown): void => cb(payload);
+ ipcRenderer.on(channel, listener);
+ return () => ipcRenderer.removeListener(channel, listener);
+ };
+}
+
+const fanOutGhostsChanged = fanOut('ghosts:changed');
+const fanOutGhostRuntimeChanged = fanOut('ghosts:runtime-changed');
+const fanOutGhostPreviewMedia = fanOut('ghosts:preview-media');
+const fanOutGhostBadge = fanOut('ghosts:badge');
+const fanOutGhostUnreadSnapshot = fanOut('ghosts:unread-snapshot');
+
+const appearanceSettings = ipcRenderer.sendSync(
+ 'appearance-settings:get-sync',
+) as AppearanceSettings | null;
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ platform: process.platform,
+ preferredSystemLocale: readPreferredSystemLocale(),
+ windowMinimize: (): void => ipcRenderer.send('window-minimize'),
+ windowMaximize: (): void => ipcRenderer.send('window-maximize'),
+ windowClose: (): void => ipcRenderer.send('window-close'),
+ logToMain: (
+ level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal',
+ scope: string,
+ msg: string,
+ ): void => ipcRenderer.send('renderer:log', level, scope, msg),
+ onLocaleChanged: (cb: (locale: SupportedLocale) => void): Unsub =>
+ onPayload(GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL, cb),
+ appearanceSettings: {
+ getSync: (): AppearanceSettings | null => appearanceSettings,
+ onChanged: (cb: (settings: AppearanceSettings) => void): Unsub =>
+ onPayload('appearance-settings:changed', cb),
+ },
+ localThemes: {
+ listSync: (): LocalThemesResult => {
+ try {
+ return ipcRenderer.sendSync('local-themes:list-sync') as LocalThemesResult;
+ } catch (error) {
+ return { success: false, error: String(error), themes: [], diagnostics: [] };
+ }
+ },
+ },
+ appShortcuts: {
+ getState: (): { overrides: Record<string, unknown>; platform: string } =>
+ ipcRenderer.sendSync('app-shortcuts:get'),
+ onChanged: (cb: (payload: { overrides?: Record<string, unknown> }) => void): Unsub =>
+ onPayload('app-shortcuts:changed', cb),
+ },
+ theme: {
+ applyVibrancy: (familyId: string, isDark: boolean): void => {
+ ipcRenderer.send('theme:apply-vibrancy', { familyId, isDark });
+ },
+ },
+
+ // ── 媒体操作(面板产物右键菜单 / 拖拽引渡) ──────────────────────────
+ // 与主 preload 同款 channel,main 侧 handler 对所有受信 renderer 生效。
+
+ copyMediaToClipboard: (params: {
+ url?: string;
+ filePath?: string;
+ }): Promise<{ success: boolean; error?: string }> =>
+ ipcRenderer.invoke('media:copy-to-clipboard', params),
+
+ showItemInFolder: (params: {
+ url?: string;
+ filePath?: string;
+ }): Promise<{ success: boolean; error?: string }> =>
+ ipcRenderer.invoke('shell:show-item-in-folder', params),
+
+ cacheMediaForSession: (params: {
+ url: string;
+ sessionId: string;
+ }): Promise<{
+ url: string;
+ name: string;
+ ext: string;
+ size: number;
+ mimeType: string;
+ }> => ipcRenderer.invoke('media:cache-for-session', params),
+
+ /** 用系统默认应用打开图片/视频(cindy-media:// 源——lightbox 内菜单项)。 */
+ openMediaWithDefaultApp: (params: { url: string }): Promise<void> =>
+ ipcRenderer.invoke('media:open-with-default-app', params),
+
+ /** 「另存为」系统保存对话框(lightbox 内菜单项)。 */
+ saveMediaAs: (params: { url: string }): Promise<{ canceled: boolean; savedPath?: string }> =>
+ ipcRenderer.invoke('media:save-as', params),
+
+ // ── 插件面板窗口状态 ────────────────────────────────────────────────
+
+ ghostPanelWindow: {
+ getStateSync: (): GhostPanelWindowsState =>
+ ipcRenderer.sendSync('ghost-panel-window:get-state-sync') as GhostPanelWindowsState,
+ getState: (): Promise<GhostPanelWindowsState> =>
+ ipcRenderer.invoke('maker:ghost-panel-window:get-state'),
+ open: (ghostId: string): Promise<void> =>
+ ipcRenderer.invoke('maker:ghost-panel-window:open', ghostId),
+ setDetached: (
+ ghostId: string,
+ detached: boolean,
+ ): Promise<GhostPanelWindowsState> =>
+ ipcRenderer.invoke('maker:ghost-panel-window:set-detached', ghostId, detached),
+ onStateChanged: (cb: (state: GhostPanelWindowsState) => void): Unsub =>
+ onPayload('maker:push:ghost-panel-window:state-changed', cb),
+ rendererReady: (): Promise<void> =>
+ ipcRenderer.invoke(GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL),
+ presentationReady: (): Promise<void> =>
+ ipcRenderer.invoke(GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL),
+ onVisibilityChanged: (cb: (payload: { visible: boolean }) => void): Unsub =>
+ onPayload(GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL, cb),
+ onCloseRequested: (cb: () => void): Unsub =>
+ onPayload(GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL, cb),
+ onMinimizeRequested: (cb: () => void): Unsub =>
+ onPayload(GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL, cb),
+ resolveCloseRequest: (approved: boolean): Promise<void> =>
+ ipcRenderer.invoke(GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL, approved),
+ },
+
+ // ── 插件管理(GhostPanelWindowLayout 依赖方法集) ─────────────────────
+
+ ghosts: {
+ /** 已装清单(同步:与面板体同帧渲染,不闪占位)。 */
+ listSync: (): { ghosts: unknown[] } => ipcRenderer.sendSync('ghosts:list'),
+ /** 重载插件(面板崩溃后恢复)。 */
+ reload: (id: string): Promise<{ state: string }> => ipcRenderer.invoke('ghosts:reload', id),
+ /** 启用/停用(面板错误态「关闭」按钮)。 */
+ setEnabled: (id: string, enabled: boolean): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('ghosts:set-enabled', id, enabled),
+ /** 解析面板媒体 URI → cindy-media:// 地址(右键菜单 / 拖拽引渡)。 */
+ resolvePanelMedia: (
+ uri: string,
+ purpose?: 'attach' | 'menu',
+ ): Promise<
+ | { url: string; kind?: 'image' }
+ | { url: string; kind: 'video'; absPath: string; size: number; name: string; ext: string; mimeType: string }
+ > => ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose),
+ /** 运行时状态快照(面板崩溃/熔断错误态接管)。 */
+ runtimeStates: (): Promise<{ states: Record<string, string> }> =>
+ ipcRenderer.invoke('ghosts:runtime-states'),
+ // ── 事件订阅 ──────────────────────────────────────────────────────
+ /** 插件装/卸/启/停/换面板形态。 */
+ onChanged: fanOutGhostsChanged,
+ /** 插件运行时状态变化(crashed / fused / off 等)。 */
+ onRuntimeChanged: fanOutGhostRuntimeChanged,
+ /** 面板点图/视频预览(宿主弹 lightbox)。 */
+ onPreviewMedia: fanOutGhostPreviewMedia,
+ /** 未读角标快照(ghostUnreadStore 首帧)。 */
+ unreadSync: (): { entries: { ghostId: string; summary?: string; at: number }[] } => {
+ try {
+ const result = ipcRenderer.sendSync('ghosts:unread') as { entries?: unknown } | null;
+ if (!Array.isArray(result?.entries)) return { entries: [] };
+ const entries: { ghostId: string; summary?: string; at: number }[] = [];
+ for (const raw of result.entries) {
+ if (typeof raw !== 'object' || raw === null) continue;
+ const { ghostId, summary, at } = raw as Record<string, unknown>;
+ if (typeof ghostId !== 'string' || typeof at !== 'number') continue;
+ entries.push({ ghostId, ...(typeof summary === 'string' ? { summary } : {}), at });
+ }
+ return { entries };
+ } catch {
+ return { entries: [] };
+ }
+ },
+ /** 熄灭未读(打开面板 = 已读)。 */
+ clearUnread: (id: string, seenAt?: number): Promise<{ ok: boolean }> =>
+ ipcRenderer.invoke('ghosts:clear-unread', id, seenAt),
+ /** 未读角标变化。 */
+ onBadge: fanOutGhostBadge,
+ /** 未读快照变化(ghostUnreadStore 增量更新)。 */
+ onUnreadSnapshot: fanOutGhostUnreadSnapshot,
+ },
+});
diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.ts
new file mode 100644
index 0000000000..88fd96cf38
--- /dev/null
+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts
@@ -0,0 +1,531 @@
+/**
+ * 鍙充晶鏍忓瓙绐楀彛涓撶敤 preload锛氬彧鏆撮湶 RSB 绐楀彛鎵€闇€鐨勬渶灏忚兘鍔涖€?
+ *
+ * 鍙充晶鏍忔壙杞?WebView(browser plugin)銆佺粓绔€佹枃浠舵祻瑙堝櫒銆丱rca workers銆?
+ * 瀹℃煡闈㈡澘绛夎兘鍔涳紝鏈?preload 鍙毚闇?RSB 绐楀彛 chrome + context 鍚屾 +
+ * 鍛戒护鎺ユ敹 + RSB tab 鎸佷箙鍖?+ webview security IPC + 澶栬/涓婚/蹇嵎閿?+
+ * device-link 杩滅▼浼氳瘽闇€瑕佺殑妗ユ銆?
+ *
+ * 涓庝富 preload.ts 鐨勫尯鍒細
+ * - 涓嶅惈 maker 浼氳瘽 IPC銆乤gent IPC銆乿oice-input銆佺櫥褰?璁剧疆/鏇存柊绛?
+ * - 涓嶅惈 full bridge 鏆撮湶(濡?process monitor銆乻ubagentRuns銆乧hat 绛?
+ * - 淇濈暀 RSB 蹇呴渶鐨?rightSidebarTabs銆乺sbBrowserBridge銆乤ppearance銆?
+ * appShortcuts銆乼heme銆乴ocalThemes銆乸latform 绛?chrome 鑳藉姏
+ */
+
+import { contextBridge, ipcRenderer, webUtils } from 'electron';
+
+import type { AppearanceSettings } from '../shared/appearanceSettings';
+import { DEVICE_LINK_INVOKE, DEVICE_LINK_PUSH } from '../shared/deviceLinkIpc';
+import type { LocalThemesResult } from '../shared/local-themes';
+import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from '../shared/locale';
+import {
+ RSB_WINDOW_PRESENTATION_READY_CHANNEL,
+ RSB_WINDOW_REFRESH_CONTEXT_CHANNEL,
+ RSB_WINDOW_RENDERER_READY_CHANNEL,
+ RSB_WINDOW_LOCALE_CHANGED_CHANNEL,
+ RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL,
+} from '../shared/rightSidebarWindow';
+
+type ApplicationMenuLocale = SupportedLocale;
+
+function onPayload<T>(channel: string, cb: (payload: T) => void): () => void {
+ const listener = (_event: Electron.IpcRendererEvent, payload: T): void => cb(payload);
+ ipcRenderer.on(channel, listener);
+ return () => ipcRenderer.removeListener(channel, listener);
+}
+
+function onPayloadWithMetadata<T, M>(
+ channel: string,
+ cb: (payload: T, metadata?: M) => void,
+): () => void {
+ const listener = (_event: Electron.IpcRendererEvent, payload: T, metadata?: M): void =>
+ cb(payload, metadata);
+ ipcRenderer.on(channel, listener);
+ return () => ipcRenderer.removeListener(channel, listener);
+}
+
+function readPreferredSystemLocale(): ApplicationMenuLocale {
+ try {
+ const value = ipcRenderer.sendSync('app-locale:get-preferred-system-locale-sync');
+ return typeof value === 'string' && (SUPPORTED_LOCALES as readonly string[]).includes(value)
+ ? value as ApplicationMenuLocale
+ : DEFAULT_LOCALE;
+ } catch {
+ return DEFAULT_LOCALE;
+ }
+}
+
+const appearanceSettings = ipcRenderer.sendSync(
+ 'appearance-settings:get-sync',
+) as AppearanceSettings | null;
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ platform: process.platform,
+ preferredSystemLocale: readPreferredSystemLocale(),
+ windowMinimize: (): void => ipcRenderer.send('window-minimize'),
+ windowMaximize: (): void => ipcRenderer.send('window-maximize'),
+ windowClose: (): void => ipcRenderer.send('window-close'),
+ logToMain: (
+ level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal',
+ scope: string,
+ msg: string,
+ ): void => ipcRenderer.send('renderer:log', level, scope, msg),
+ safeStorageStore: (key: string, value: string): Promise<boolean> =>
+ ipcRenderer.invoke('safe-storage-store', key, value),
+ safeStorageRead: (key: string): Promise<string | null> =>
+ ipcRenderer.invoke('safe-storage-read', key),
+ safeStorageRemove: (key: string): Promise<{ success: boolean; error?: string }> =>
+ ipcRenderer.invoke('safe-storage-remove', key),
+ onLocaleChanged: (cb: (locale: SupportedLocale) => void): (() => void) =>
+ onPayload(RSB_WINDOW_LOCALE_CHANGED_CHANNEL, cb),
+ appearanceSettings: {
+ getSync: (): AppearanceSettings | null => appearanceSettings,
+ onChanged: (cb: (settings: AppearanceSettings) => void): (() => void) =>
+ onPayload('appearance-settings:changed', cb),
+ },
+ localThemes: {
+ listSync: (): LocalThemesResult => {
+ try {
+ return ipcRenderer.sendSync('local-themes:list-sync') as LocalThemesResult;
+ } catch (error) {
+ return { success: false, error: String(error), themes: [], diagnostics: [] };
+ }
+ },
+ },
+ appShortcuts: {
+ getState: (): { overrides: Record<string, unknown>; platform: string } =>
+ ipcRenderer.sendSync('app-shortcuts:get'),
+ onChanged: (cb: (payload: { overrides?: Record<string, unknown> }) => void): (() => void) =>
+ onPayload('app-shortcuts:changed', cb),
+ },
+ theme: {
+ applyVibrancy: (familyId: string, isDark: boolean): void => {
+ ipcRenderer.send('theme:apply-vibrancy', { familyId, isDark });
+ },
+ },
+
+ // Auth state is read-only for this window's normal startup. The methods are
+ // kept together because AuthProvider also owns account-boundary cleanup and
+ // must observe the same main-process auth broadcasts as the primary window.
+ authHasPersistedSessionHintSync: (): boolean =>
+ ipcRenderer.sendSync('auth:has-persisted-session-hint-sync') === true,
+ authInitialize: (): Promise<unknown> => ipcRenderer.invoke('auth:initialize'),
+ authGetLoginState: (): Promise<unknown> => ipcRenderer.invoke('auth:get-login-state'),
+ authDispatchLoginAction: (action: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('auth:dispatch-login-action', action),
+ authLogout: (): Promise<void> => ipcRenderer.invoke('auth:logout'),
+ authEnterLocal: (): Promise<unknown> => ipcRenderer.invoke('auth:enter-local'),
+ authExitLocal: (): Promise<unknown> => ipcRenderer.invoke('auth:exit-local'),
+ authGetAccountDeletionAvailability: (): Promise<unknown> =>
+ ipcRenderer.invoke('auth:account-deletion:get-availability'),
+ authRequestAccountDeletionChallenge: (): Promise<unknown> =>
+ ipcRenderer.invoke('auth:account-deletion:request-challenge'),
+ authConfirmAccountDeletion: (input: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('auth:account-deletion:confirm', input),
+ authGetAccountDeletionStatus: (): Promise<unknown> =>
+ ipcRenderer.invoke('auth:account-deletion:get-status'),
+ authClearAccountDeletionReceipt: (): Promise<void> =>
+ ipcRenderer.invoke('auth:account-deletion:clear-receipt'),
+ authConsumeAccountDeletionRestoredNotice: (): Promise<boolean> =>
+ ipcRenderer.invoke('auth:account-deletion:consume-restored-notice'),
+ onAuthStateChange: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('auth:state-change', cb),
+ onAuthSessionExpired: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('auth:session-expired', cb),
+
+ // 鈹€鈹€ 鍙充晶鏍忓瓙绐楀彛涓撶敤 API 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
+
+ deviceLink: {
+ getState: (): Promise<unknown> => ipcRenderer.invoke(DEVICE_LINK_INVOKE.GET_STATE),
+ listDevices: (): Promise<unknown> => ipcRenderer.invoke(DEVICE_LINK_INVOKE.LIST_DEVICES),
+ invoke: (deviceId: string, channel: string, args: unknown[]): Promise<unknown> =>
+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.INVOKE, { deviceId, channel, args }),
+ subscribe: (deviceId: string, topics: string[]): Promise<{ ok: true }> =>
+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.SUBSCRIBE, { deviceId, topics }),
+ unsubscribe: (deviceId: string, topics: string[]): Promise<{ ok: true }> =>
+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.UNSUBSCRIBE, { deviceId, topics }),
+ onPresenceChanged: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload(DEVICE_LINK_PUSH.PRESENCE_CHANGED, cb),
+ onStatusChanged: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload(DEVICE_LINK_PUSH.STATUS_CHANGED, cb),
+ onRemotePush: (cb: (payload: unknown, localOwnerStamp?: unknown) => void): (() => void) =>
+ onPayloadWithMetadata(DEVICE_LINK_PUSH.REMOTE_PUSH, cb),
+ onAccessRevoked: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload(DEVICE_LINK_PUSH.ACCESS_REVOKED, cb),
+ onControlTargetChanged: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload(DEVICE_LINK_PUSH.CONTROL_TARGET_CHANGED, cb),
+ onResponsivenessChanged: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload(DEVICE_LINK_PUSH.RESPONSIVENESS_CHANGED, cb),
+ mirrorCache: {
+ getMessages: (deviceId: string, sessionId: string): Promise<unknown> =>
+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.MIRROR_CACHE_GET_MESSAGES, { deviceId, sessionId }),
+ putMessages: (
+ deviceId: string,
+ sessionId: string,
+ messages: readonly Record<string, unknown>[],
+ expectedInvalidation?: number,
+ expectedOwnerToken?: string,
+ expectedAccountCounter?: number,
+ ): Promise<unknown> =>
+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.MIRROR_CACHE_PUT_MESSAGES, {
+ deviceId,
+ sessionId,
+ messages,
+ expectedInvalidation,
+ expectedOwnerToken,
+ expectedAccountCounter,
+ }),
+ getSessionList: (): Promise<unknown> =>
+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.MIRROR_CACHE_GET_SESSION_LIST),
+ putSessionList: (
+ devices: ReadonlyArray<{
+ deviceId: string;
+ deviceName: string;
+ sessions: readonly Record<string, unknown>[];
+ }>,
+ expectedOwnerToken?: string,
+ expectedAccountCounter?: number,
+ ): Promise<unknown> =>
+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.MIRROR_CACHE_PUT_SESSION_LIST, {
+ devices,
+ expectedOwnerToken,
+ expectedAccountCounter,
+ }),
+ clear: (deviceId: string): Promise<{ ok: true }> =>
+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.MIRROR_CACHE_CLEAR, { deviceId }),
+ },
+ },
+
+ // Right-sidebar plugin capabilities. These are intentionally limited to the
+ // APIs consumed by the built-in RSB tabs; the full primary-window bridge is
+ // not exposed to this detached renderer.
+ fileBrowser: {
+ listDir: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:list-dir', params),
+ listAllFiles: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:list-all', params),
+ readFile: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:read-file', params),
+ writeFile: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:write-file', params),
+ createFile: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:create-file', params),
+ createFolder: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:create-folder', params),
+ deleteEntry: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:delete-entry', params),
+ renameEntry: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:rename-entry', params),
+ stat: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:stat', params),
+ startWatch: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:start-watch', params),
+ stopWatch: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:stop-watch', params),
+ onEvent: (cb: (event: unknown) => void): (() => void) => onPayload('maker:file-browser:event', cb),
+ fetchRemote: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:fetch-remote', params),
+ readCached: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:read-cached', params),
+ cachePut: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:cache-put', params),
+ onTransferProgress: (cb: (event: unknown) => void): (() => void) => onPayload('maker:file-browser:transfer', cb),
+ chatFetch: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:chat-file:fetch', params),
+ chatStat: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:chat-file:stat', params),
+ },
+ terminal: {
+ create: (params: unknown): Promise<unknown> => ipcRenderer.invoke('terminal:create', params),
+ write: (id: string, data: string): Promise<unknown> => ipcRenderer.invoke('terminal:write', id, data),
+ resize: (id: string, cols: number, rows: number): Promise<unknown> => ipcRenderer.invoke('terminal:resize', id, cols, rows),
+ dispose: (id: string): Promise<unknown> => ipcRenderer.invoke('terminal:dispose', id),
+ restart: (id: string): Promise<unknown> => ipcRenderer.invoke('terminal:restart', id),
+ onData: (cb: (event: unknown) => void): (() => void) => onPayload('terminal:data', cb),
+ onExit: (cb: (event: unknown) => void): (() => void) => onPayload('terminal:exit', cb),
+ },
+ processMonitor: {
+ subscribe: (): Promise<unknown> => ipcRenderer.invoke('process-monitor:subscribe'),
+ unsubscribe: (): Promise<unknown> => ipcRenderer.invoke('process-monitor:unsubscribe'),
+ terminate: (request: unknown): Promise<unknown> => ipcRenderer.invoke('process-monitor:terminate-agent', request),
+ onSample: (cb: (sample: unknown) => void): (() => void) => onPayload('process-monitor:sample', cb),
+ },
+ rsbNativePopup: {
+ claim: (input: unknown): Promise<unknown> => ipcRenderer.invoke('rsb-native-popup:claim', input),
+ setBounds: (input: unknown): Promise<unknown> => ipcRenderer.invoke('rsb-native-popup:set-bounds', input),
+ command: (input: unknown): Promise<unknown> => ipcRenderer.invoke('rsb-native-popup:command', input),
+ close: (input: unknown): Promise<unknown> => ipcRenderer.invoke('rsb-native-popup:close', input),
+ onEvent: (cb: (event: unknown) => void): (() => void) => onPayload('rsb-native-popup:event', cb),
+ },
+ openExternal: (url: string): Promise<unknown> => ipcRenderer.invoke('shell:open-external', url),
+ openFileInBrowser: (pathOrUrl: string): Promise<unknown> => ipcRenderer.invoke('shell:open-file-in-browser', pathOrUrl),
+ openPath: (pathOrUrl: string): Promise<unknown> => ipcRenderer.invoke('shell:open-path', pathOrUrl),
+ showItemInFolder: (params: unknown): Promise<unknown> => ipcRenderer.invoke('shell:show-item-in-folder', params),
+ getFilePath: (file: File): string => {
+ try {
+ return webUtils.getPathForFile(file);
+ } catch {
+ return '';
+ }
+ },
+ cacheImageFromBuffer: (params: unknown): Promise<unknown> => ipcRenderer.invoke('image-cache:from-buffer', params),
+ onRsbBrowserFocusUrlBar: (cb: () => void): (() => void) => onPayload('rsb:browser-focus-url-bar', cb),
+
+ rightSidebarWindow: {
+ getState: (): Promise<{ detached: boolean; lastOpen: boolean; open: boolean }> =>
+ ipcRenderer.invoke('maker:rsb-window:get-state'),
+ open: (payload?: unknown): Promise<void> =>
+ ipcRenderer.invoke('maker:rsb-window:open', payload),
+ close: (): Promise<void> => ipcRenderer.invoke('maker:rsb-window:close'),
+ setDetached: (detached: boolean): Promise<{ detached: boolean; lastOpen: boolean; open: boolean }> =>
+ ipcRenderer.invoke('maker:rsb-window:set-detached', detached),
+ getContext: (): Promise<{
+ sessionId: string | null;
+ workdir: string | null;
+ remoteHostId: string | null;
+ deviceLinkDeviceId?: string | null;
+ available: boolean;
+ } | null> => ipcRenderer.invoke('maker:rsb-window:get-context'),
+ /** 瀛橀噺灏辩华鎻℃墜 鈫?鏄犲皠鍒?renderer-ready(renderer shell 宸叉寕杞?銆?*/
+ ready: (): Promise<void> => ipcRenderer.invoke('maker:rsb-window:ready'),
+ /** 鍙岄樁娈靛氨缁?renderer shell 鎸傝浇銆?*/
+ rendererReady: (): Promise<void> => ipcRenderer.invoke(RSB_WINDOW_RENDERER_READY_CHANNEL),
+ /** 鍙岄樁娈靛氨缁?棣栦唤涓氬姟鍐呭宸叉彁浜ゃ€?*/
+ presentationReady: (): Promise<void> => ipcRenderer.invoke(RSB_WINDOW_PRESENTATION_READY_CHANNEL),
+ /** 璇锋眰浠?main 缂撳瓨鍒锋柊 context銆?*/
+ refreshContext: (): Promise<void> => ipcRenderer.invoke(RSB_WINDOW_REFRESH_CONTEXT_CHANNEL),
+ onStateChanged: (
+ cb: (state: { detached: boolean; open: boolean }) => void,
+ ): (() => void) => onPayload('maker:push:rsb-window:state-changed', cb),
+ onContextChanged: (
+ cb: (ctx: {
+ sessionId: string | null;
+ workdir: string | null;
+ remoteHostId: string | null;
+ deviceLinkDeviceId?: string | null;
+ available: boolean;
+ }) => void,
+ ): (() => void) => onPayload('maker:push:rsb-window:context-changed', cb),
+ onCommand: (
+ cb: (cmd: unknown) => void,
+ ): (() => void) => onPayload('maker:push:rsb-window:command', cb),
+ sendCommand: (request: unknown): Promise<string> =>
+ ipcRenderer.invoke('maker:rsb-window:send-command', request),
+ /** 闅愯棌/鏄剧ず鏃堕€氱煡瀛愮獥鍙e埛鏂?context + 閲嶇疆鐬椂浜や簰鎬併€?*/
+ onVisibilityChanged: (cb: (payload: { visible: boolean }) => void): (() => void) =>
+ onPayload(RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL, cb),
+ },
+
+ // 鈹€鈹€ RSB tab 鎸佷箙鍖?杞婚噺,浠?RSB 闇€瑕? 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
+
+ rightSidebarTabs: {
+ list: (input: { sessionId: string }): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:right-sidebar-tabs:list', input),
+ ensureSingleton: (input: {
+ sessionId: string;
+ kind: string;
+ state?: unknown;
+ }): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:right-sidebar-tabs:ensure-singleton', input),
+ upsert: (input: {
+ id: string;
+ sessionId: string;
+ kind: string;
+ position: number;
+ state?: unknown;
+ }): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:upsert', input),
+ close: (input: { id: string }): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:right-sidebar-tabs:close', input),
+ setActive: (input: { sessionId: string; id: string | null }): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:right-sidebar-tabs:setActive', input),
+ reorder: (input: { sessionId: string; orderedIds: string[] }): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:right-sidebar-tabs:reorder', input),
+ },
+
+ // 鈹€鈹€ RSB browser bridge(WebView 鎵胯浇) 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€
+
+ rsbBrowserBridge: {
+ report: (input: {
+ sessionId: string;
+ tabId: string;
+ webContentsId: number;
+ }): Promise<unknown> => ipcRenderer.invoke('rsb-browser-bridge:report', input),
+ release: (input: { tabId: string; webContentsId?: number }): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:release', input),
+ snapshot: (input: { liveTabIds: string[] }): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:snapshot', input),
+ captureScreenshot: (input: { tabId: string }): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:capture-screenshot', input),
+ captureScreenshotData: (input: { tabId: string }): Promise<{ ok: true; data: Uint8Array }> =>
+ ipcRenderer.invoke('rsb-browser-bridge:capture-screenshot-data', input),
+ onPin: (cb: (payload: { tabId: string }) => void): (() => void) =>
+ onPayload('rsb-browser-bridge:pin', cb),
+ onUnpin: (cb: (payload: { tabId: string }) => void): (() => void) =>
+ onPayload('rsb-browser-bridge:unpin', cb),
+ onTabOpRequest: (cb: (request: unknown) => void): (() => void) =>
+ onPayload('rsb-browser-bridge:tab-op-request', cb),
+ tabOpResult: (result: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:tab-op-result', result),
+ setActiveSession: (input: { sessionId: string | null }): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:set-active-session', input),
+ setForeground: (input: { tabId: string | null }): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:set-foreground', input),
+ forceKill: (input: { tabId: string; webContentsId?: number }): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:force-kill', input),
+ onResourceEvent: (cb: (event: unknown) => void): (() => void) =>
+ onPayload('rsb-browser-bridge:resource-event', cb),
+ },
+
+ // The renderer's durable-tab consumers use the canonical localDb namespace.
+ // Keep the legacy top-level alias above for compatibility with older builds.
+ localDb: {
+ // Minimal read-only chat hydration bridge used by BackgroundTasks and the
+ // shared makerChatStore. Do not expose the primary window's full DB API.
+ sessions: {
+ get: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get', id),
+ list: (limit?: number, status?: string): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:sessions:list', limit, status),
+ resolveReferences: (sessionIds: string[]): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:sessions:resolve-references', sessionIds),
+ ackInterrupted: (id: string): Promise<void> =>
+ ipcRenderer.invoke('local-db:sessions:ack-interrupted', id),
+ },
+ messages: {
+ list: (
+ sessionId: string,
+ opts?: { limit?: number; before?: string; beforeTs?: number },
+ ): Promise<unknown> => ipcRenderer.invoke('local-db:messages:list', sessionId, opts),
+ around: (
+ sessionId: string,
+ messageId: string,
+ opts?: { radius?: number },
+ ): Promise<unknown> => ipcRenderer.invoke('local-db:messages:around', sessionId, messageId, opts),
+ aroundClientId: (
+ sessionId: string,
+ clientId: string,
+ opts?: { radius?: number },
+ ): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:messages:around-client-id', sessionId, clientId, opts),
+ estimatedSessionValue: (sessionId: string): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:messages:estimatedSessionValue', sessionId),
+ onCreated: (cb: (payload: unknown, ownerStamp?: unknown) => void): (() => void) =>
+ onPayloadWithMetadata('local-db:messages:created', cb),
+ onDeleted: (cb: (payload: unknown, ownerStamp?: unknown) => void): (() => void) =>
+ onPayloadWithMetadata('local-db:messages:deleted', cb),
+ onErrorPersisted: (cb: (payload: unknown, ownerStamp?: unknown) => void): (() => void) =>
+ onPayloadWithMetadata('local-db:session:error-persisted', cb),
+ },
+ rightSidebarTabs: {
+ list: (input: unknown): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:list', input),
+ ensureSingleton: (input: unknown): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:ensure-singleton', input),
+ upsert: (input: unknown): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:upsert', input),
+ close: (input: unknown): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:close', input),
+ setActive: (input: unknown): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:setActive', input),
+ reorder: (input: unknown): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:reorder', input),
+ },
+ subagentRuns: {
+ list: (input: unknown): Promise<unknown> => ipcRenderer.invoke('local-db:subagent-runs:list', input),
+ detail: (input: unknown): Promise<unknown> => ipcRenderer.invoke('local-db:subagent-runs:detail', input),
+ onChanged: (cb: (payload: unknown, ownerStamp?: unknown) => void): (() => void) => onPayloadWithMetadata('local-db:subagent-runs:changed', cb),
+ },
+ orcaWorkflows: {
+ getByLeadSession: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:orca-workflows:get-by-lead', id),
+ getByWorkerSession: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:orca-workflows:get-by-worker-session', id),
+ listWorkersByLead: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:orca-workflows:list-workers-by-lead', id),
+ listWorkersByLeads: (ids: string[]): Promise<unknown> => ipcRenderer.invoke('local-db:orca-workflows:list-workers-by-leads', ids),
+ createWorker: (input: Record<string, unknown>): Promise<unknown> =>
+ ipcRenderer.invoke('maker:worker:create', input),
+ switchFocus: (input: Record<string, unknown>): Promise<unknown> =>
+ ipcRenderer.invoke('maker:worker:switch-focus', input),
+ idleWorker: (
+ leadSessionId: string,
+ workerId: string,
+ expectedStatus?: 'done',
+ ): Promise<unknown> => {
+ if (expectedStatus === 'done') {
+ return ipcRenderer.invoke('maker:worker:acknowledge-done', {
+ leadSessionId,
+ workerId,
+ });
+ }
+ return ipcRenderer.invoke('maker:worker:idle', {
+ leadSessionId,
+ workerId,
+ ...(expectedStatus ? { expectedStatus } : {}),
+ });
+ },
+ archiveWorker: (leadSessionId: string, workerId: string): Promise<unknown> =>
+ ipcRenderer.invoke('maker:worker:archive', { leadSessionId, workerId }),
+ endTeam: (leadSessionId: string): Promise<unknown> =>
+ ipcRenderer.invoke('maker:team:end', leadSessionId),
+ getCollaborationSettings: (): Promise<unknown> =>
+ ipcRenderer.invoke('maker:collaboration-settings:get'),
+ onOrcaWorkerChanged: (cb: (payload: unknown) => void): (() => void) => onPayload('maker:orca:worker-changed', cb),
+ },
+ },
+
+ gitReview: {
+ get: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:get', params),
+ summary: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:summary', params),
+ commits: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:commits', params),
+ commitDiff: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:commit-diff', params),
+ branchDiff: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:branch-diff', params),
+ fileDiff: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:file-diff', params),
+ imagePreview: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:image-preview', params),
+ markdownPreview: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:markdown-preview', params),
+ openFile: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:open-file', params),
+ stageFile: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:stage-file', params),
+ unstageFile: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:unstage-file', params),
+ discardFile: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:discard-file', params),
+ stageHunk: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:stage-hunk', params),
+ unstageHunk: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:unstage-hunk', params),
+ discardHunk: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:discard-hunk', params),
+ stageAll: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:stage-all', params),
+ unstageAll: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:unstage-all', params),
+ discardAll: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:discard-all', params),
+ commit: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:commit', params),
+ push: (params: unknown): Promise<unknown> => ipcRenderer.invoke('git-review:push', params),
+ },
+ maker: {
+ // Live event subset consumed by makerChatStore in the detached renderer.
+ onEvent: (cb: (payload: unknown) => void): (() => void) => onPayload('maker:event', cb),
+ onStatusChanged: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('maker:status-changed', cb),
+ onInputProjection: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('maker:input:projection', cb),
+ onInteractionRequest: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('maker:interaction-request', cb),
+ onInteractionDismissed: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('maker:interaction-dismissed', cb),
+ getTurnChangeSets: (sessionId: string, ids: string[]): Promise<unknown> =>
+ ipcRenderer.invoke('maker:turn-change-sets:get', sessionId, ids),
+ getWorkflowProgress: (sessionId: string, taskId: string): Promise<unknown> =>
+ ipcRenderer.invoke('maker:get-workflow-progress', sessionId, taskId),
+ listSessionBackgroundTasks: (sessionId: string): Promise<unknown> =>
+ ipcRenderer.invoke('maker:session-background-tasks:list', sessionId),
+ stopAgentTask: (sessionId: string, taskId: string): Promise<unknown> =>
+ ipcRenderer.invoke('maker:agent-task:stop', sessionId, taskId),
+ getPendingInteractions: (sessionId: string): Promise<unknown> =>
+ ipcRenderer.invoke('maker:get-pending-interactions', sessionId),
+ iosSimulator: {
+ requestAccess: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:request-access', request),
+ status: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:status', request),
+ call: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:call', request),
+ setAgentControl: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:set-agent-control', request),
+ setMutationControl: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:set-mutation-control', request),
+ setViewerVisibility: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:set-viewer-visibility', request),
+ latestFrame: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:latest-frame', request),
+ setStreamProfile: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:set-stream-profile', request),
+ liveTouch: (request: unknown): Promise<unknown> =>
+ ipcRenderer.invoke('maker:ios-simulator:live-touch', request),
+ onH264Frame: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('maker:ios-simulator:h264-frame', cb),
+ onRouteStatus: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('maker:ios-simulator:route-status', cb),
+ onFocusRequest: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('maker:ios-simulator:focus-request', cb),
+ },
+ },
+ /** 涓荤獥鎺ㄩ€?RSB 娴忚鍣ㄦ寜閿懡浠?鈱樷嚙鈫?绛?鍒板瓙绐楀彛銆?*/
+ search: {
+ start: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:search:start', params),
+ cancel: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:search:cancel', params),
+ onEvent: (cb: (event: unknown) => void): (() => void) => onPayload('maker:search:event', cb),
+ },
+ onRsbBrowserCommand: (
+ cb: (payload: { command: string }) => void,
+ ): (() => void) => onPayload('maker:push:rsb-browser-command', cb),
+});
diff --git a/apps/desktop/src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts b/apps/desktop/src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts
index acbf72153f..d005e46c98 100644
--- a/apps/desktop/src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts
@@ -142,9 +142,12 @@ describe('orca 远程路由接线不变式', () => {
});
it('右侧栏协同 tab close 不带路由副作用,避免 detached 窗口跳回 MainLayout', () => {
- const src = read('features/right-sidebar/plugins/orca-workers/index.tsx');
- expect(src).toContain('navigateOnSuccess: false');
- expect(src).not.toContain('navigateOnSuccess: true');
+ const src = read('features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx');
+ expect(src).toContain('useStopOrcaCollabWithoutNavigation');
+ expect(src).not.toContain('useStopOrcaCollab({');
+ expect(src).toContain('isSidebarWindow() ? (');
+ expect(src).toContain('<MemoryRouter initialEntries={[`/cc-agent/${ctx.sessionId}`]}>');
+ expect(src).toContain('<RoutedOrcaWorkerPanel {...workerPanelProps} />');
});
it('detached 子窗口消费 browser/file/orca intent,主窗口 helper 不直接写子窗宿主 store', () => {
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkerProjectionContracts.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkerProjectionContracts.test.ts
index d9d2ee39cb..8f0aff32f2 100644
--- a/apps/desktop/src/renderer/__tests__/orcaWorkerProjectionContracts.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaWorkerProjectionContracts.test.ts
@@ -3,8 +3,18 @@ import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
const repoRoot = resolve(__dirname, '..', '..', '..');
-const pluginSource = readFileSync(
- resolve(repoRoot, 'src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx'),
+const attentionIconSource = readFileSync(
+ resolve(
+ repoRoot,
+ 'src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx',
+ ),
+ 'utf8',
+);
+const tabBodySource = readFileSync(
+ resolve(
+ repoRoot,
+ 'src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx',
+ ),
'utf8',
);
const selectionSource = readFileSync(
@@ -22,40 +32,22 @@ const sessionHeaderSource = readFileSync(
describe('Orca worker projection integration contracts', () => {
it('keeps inactive right-sidebar pills on the read-only projection path', () => {
- const attentionDotBlock = extractBetween(
- pluginSource,
- 'function OrcaWorkersAttentionDot',
- 'function OrcaWorkersTabBody',
- );
-
- expect(attentionDotBlock).toContain('useWorkerProjection(sessionId)');
- expect(attentionDotBlock).not.toContain('useWorkers(');
- expect(attentionDotBlock).not.toContain('revalidate');
+ expect(attentionIconSource).toContain("useWorkerProjection(sessionId ?? '')");
+ expect(attentionIconSource).not.toContain('useWorkers(');
+ expect(attentionIconSource).not.toContain('revalidate');
});
it('keeps right-sidebar tab bodies owning projections across active and detached lifetimes', () => {
- const tabBodyBlock = extractBetween(
- pluginSource,
- 'function OrcaWorkersTabBody',
- 'const plugin: TabKindPlugin',
- );
-
- expect(tabBodyBlock).toContain('useWorkerProjectionOwner(ctx.sessionId);');
- expect(tabBodyBlock).toContain('revalidateActiveWorkersProjection(ctx.sessionId)');
- expect(tabBodyBlock).toContain('revalidateActiveWorkerSettings(ctx.sessionId)');
- expect(tabBodyBlock).toContain('if (!active || !shellVisible || !windowVisible) return;');
+ expect(tabBodySource).toContain('useWorkerProjectionOwner(ctx.sessionId);');
+ expect(tabBodySource).toContain('revalidateActiveWorkersProjection(ctx.sessionId)');
+ expect(tabBodySource).toContain('revalidateActiveWorkerSettings(ctx.sessionId)');
+ expect(tabBodySource).toContain('if (!active || !shellVisible || !windowVisible) return;');
});
it('runs the attention projection inside the detached sidebar renderer', () => {
- const tabBodyBlock = extractBetween(
- pluginSource,
- 'function OrcaWorkersTabBody',
- 'const plugin: TabKindPlugin',
- );
-
- expect(tabBodyBlock).toContain('isSidebarWindow() ? [ctx.sessionId] : []');
- expect(tabBodyBlock).toContain('useOrcaWorkerAttentionByLeadIds(');
- expect(tabBodyBlock).toContain('viewVisible ? ctx.sessionId : undefined');
+ expect(tabBodySource).toContain('isSidebarWindow() ? [ctx.sessionId] : []');
+ expect(tabBodySource).toContain('useOrcaWorkerAttentionByLeadIds(');
+ expect(tabBodySource).toContain('viewVisible ? ctx.sessionId : undefined');
});
it('keeps doc rail worker selection on useWorkers so it still receives live projection updates', () => {
@@ -70,12 +62,3 @@ describe('Orca worker projection integration contracts', () => {
expect(sessionHeaderSource).not.toContain('.listWorkersByLead(session.id)');
});
});
-
-function extractBetween(source: string, start: string, end: string): string {
- const startIndex = source.indexOf(start);
- const endIndex = source.indexOf(end, startIndex + start.length);
- if (startIndex < 0 || endIndex < 0) {
- throw new Error(`missing source block ${start}..${end}`);
- }
- return source.slice(startIndex, endIndex);
-}
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
index b6fd0416e5..623e3fc5e5 100644
--- a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
@@ -63,6 +63,18 @@ const workerPanelSource = readTextLf(
resolve(__dirname, '..', 'features', 'cc-agent', 'OrcaWorkerPanel.tsx'),
'utf8',
);
+const workersTabBodySource = readTextLf(
+ resolve(
+ __dirname,
+ '..',
+ 'features',
+ 'right-sidebar',
+ 'plugins',
+ 'orca-workers',
+ 'OrcaWorkersTabBody.tsx',
+ ),
+ 'utf8',
+);
const workerSelectionHookSource = readTextLf(
resolve(__dirname, '..', 'features', 'cc-agent', 'hooks', 'useOrcaWorkerSelection.ts'),
'utf8',
@@ -398,8 +410,9 @@ describe('OrcaWorkflowRoute source invariants', () => {
});
it('does not navigate the detached sidebar window to settings from the worker toolbar', () => {
- expect(workerPanelSource).toContain("import { isSidebarWindow } from '@/lib/sidebarWindow';");
- expect(workerPanelSource).toContain('settingsEnabled={!isSidebarWindow()}');
+ expect(workersTabBodySource).toContain("import { isSidebarWindow } from '@/lib/sidebarWindow';");
+ expect(workersTabBodySource).toContain('<OrcaWorkerPanel {...workerPanelProps} />');
+ expect(workersTabBodySource).toContain('<RoutedOrcaWorkerPanel {...workerPanelProps} />');
});
it('marks the collaboration worker chat as sidebar-embedded so it cannot replace the host route', () => {
diff --git a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
index dcdbdf074d..d40feb1f85 100644
--- a/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteWorkerCreationContext.test.ts
@@ -40,11 +40,13 @@ describe('remote Orca Worker creation context', () => {
it('passes the same device context through both Worker creation entry points', () => {
const sessionView = read('features/cc-agent/CCAgentSessionView.tsx');
const workerPanel = read('features/cc-agent/OrcaWorkerPanel.tsx');
- const workersPlugin = read('features/right-sidebar/plugins/orca-workers/index.tsx');
+ const workersTabBody = read(
+ 'features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx',
+ );
expect(sessionView).toContain('deviceId={remoteDeviceId}');
expect(workerPanel).toContain('deviceId={deviceId}');
- expect(workersPlugin).toContain('deviceId={leadSession?.deviceLinkDeviceId}');
+ expect(workersTabBody).toContain('deviceId: leadSession?.deviceLinkDeviceId');
});
it('never uses the controller API key to gate a remote model row', () => {
diff --git a/apps/desktop/src/renderer/__tests__/windowCloseBehavior.test.tsx b/apps/desktop/src/renderer/__tests__/windowCloseBehavior.test.tsx
index 6f94e4cde4..295d6483fc 100644
--- a/apps/desktop/src/renderer/__tests__/windowCloseBehavior.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/windowCloseBehavior.test.tsx
@@ -55,6 +55,26 @@ afterEach(() => {
});
describe('Windows close behavior', () => {
+ it('uses the default minimize action when no override is provided', () => {
+ installWindowsApi(null);
+ render(<WindowControls />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'titleBar.minimize' }));
+
+ expect(window.electronAPI.windowMinimize).toHaveBeenCalledTimes(1);
+ });
+
+ it('uses a window-specific minimize action when provided', () => {
+ installWindowsApi(null);
+ const onMinimize = vi.fn();
+ render(<WindowControls onMinimize={onMinimize} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'titleBar.minimize' }));
+
+ expect(onMinimize).toHaveBeenCalledTimes(1);
+ expect(window.electronAPI.windowMinimize).not.toHaveBeenCalled();
+ });
+
it('does not subscribe to main-window close requests from a secondary window', () => {
window.history.replaceState({}, '', '/?secondaryWindow=1');
const api = installWindowsApi(null);
diff --git a/apps/desktop/src/renderer/components/layout/ContentHeader.tsx b/apps/desktop/src/renderer/components/layout/ContentHeader.tsx
index 6f53b97dea..76ba6e88a5 100644
--- a/apps/desktop/src/renderer/components/layout/ContentHeader.tsx
+++ b/apps/desktop/src/renderer/components/layout/ContentHeader.tsx
@@ -30,15 +30,14 @@ import { cn } from '@/lib/utils';
import { CHROME_ACTIONS_GEOMETRY } from './chromeActionsGeometry';
/**
- * Windows 窗口控制按钮宽度(3 × 46px)。窗口控制按钮已 hoist 到 MainLayout
- * 顶层浮层(恒钉窗口右上角、浮在右栏之上),这里在右端留出等宽占位,防止
- * 注入的 header 内容滑到浮动 min/max/close 按钮下面。
+ * Windows 窗口控制按钮宽度(3 × 46px)。固定侧栏入口位于下一行的内容区,
+ * 不占用本标题栏。
*/
const WIN_CONTROLS_WIDTH = 138;
/**
- * mac 右栏折叠按钮宽度占位(按钮 28 + 右距 8;2026-07 随左右按钮簇统一缩到
- * 28px 规格族)。开关已 hoist 到 MainLayout 顶层浮层(钉窗口右上角,见
+ * mac 右栏固定唤起按钮宽度占位(按钮 28 + 右距 8)。按钮已 hoist 到 MainLayout
+ * 顶层浮层(钉窗口右上角,见
* MainLayout 的 mac 浮层),这里同 Windows 一样在右端留等宽占位,防止注入的
* header 内容滑到浮动开关下面。
*/
@@ -66,9 +65,8 @@ interface ContentHeaderProps {
showCollapsedActions: boolean;
/** 左侧栏是否处于 rail 态(拖到最窄但仍保留图标列)。 */
isSidebarRail: boolean;
- /** mac 右上浮层按钮是否在场(2026-07-09 口径:右栏在场即 true,不分贴哪侧 ——
- * 折叠 toggle 恒钉窗口右上角,面板贴左时它压在本 header 右端)。mac 据此在
- * 右端留折叠按钮占位 + 决定是否留住空 header;Windows 仅影响空 header 判定,
+ /** mac 右上固定唤起按钮是否在场。mac 据此在右端留按钮占位并决定是否留住空
+ * header;Windows 仅影响空 header 判定,
* 占位恒为窗口控制按钮宽。 */
rightSidebarAvailable: boolean;
/** MainLayout 经 useContentHeaderHidden 预判的结果(与 --content-header-h 同源)。 */
@@ -107,7 +105,7 @@ export function ContentHeader({
// mac 红绿灯的所在行,藏了按钮会压在页面内容上
// - mac —— Windows 上这条空 header 仍保留为拖拽细条(窗口控制按钮已
// hoist 到 MainLayout 顶层浮层,但顶栏仍是 Windows 拖动窗口的抓手)
- // - 右栏开关在场(rightSidebarAvailable,mac 把开关放在本 header 右端)——
+ // - 右栏唤起入口在场(rightSidebarAvailable,mac 把入口放在本 header 右端)——
// 即使无注入内容也留住空 header 当开关落点,否则全屏聊天视图在 mac 上会
// 失去关闭右栏的入口
// 设置页天然不满足 sidebarVisible,维持隐形 chrome 现状。
@@ -172,12 +170,11 @@ export function ContentHeader({
<div className="flex h-full min-w-0 flex-1 items-center">{headerContent}</div>
{/* 右端占位 —— 平台分流(两端都只留占位,不再放交互按钮):
- - mac:全屏聊天视图在场时(rightSidebarAvailable)留出折叠按钮等宽占位。
- 折叠按钮本身已 hoist 到 MainLayout 顶层浮层(钉窗口右上角,右栏打开时
- 落在右栏顶部 toolbar 条右端,实现「始终在最右」);这里仅占位防注入
+ - mac:全屏聊天视图在场时(rightSidebarAvailable)留出固定唤起按钮等宽占位。
+ 按钮本身已 hoist 到 MainLayout 顶层浮层(钉窗口右上角);这里仅占位防注入
内容被压到浮层按钮下。不在场则右端留空。
- Windows:留出 WIN_CONTROLS_WIDTH 等宽占位(窗口控制按钮已 hoist 到
- MainLayout 顶层浮层);右栏开关走聊天视图的 chip 栈,不在这里。 */}
+ MainLayout 顶层浮层);固定侧栏入口位于下一行内容区。 */}
{isMac ? (
rightSidebarAvailable && (
<div aria-hidden className="h-full shrink-0" style={{ width: MAC_RIGHT_TOGGLE_WIDTH }} />
diff --git a/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx
index 121245b826..58ef8c8f43 100644
--- a/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx
@@ -1,37 +1,45 @@
/**
- * GhostPanelWindowLayout —— 插件停靠面板独立窗口的根组件(路由 `/ghost-panel-window`)。
+ * 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 收口)。
+ * 窗口�?main/ghost-panel-window/window.ts 打开(`?ghostPanelWindow=<id>`),本组�?
+ * - �?46px 自绘 chrome(蓝本 SidebarWindowLayout):整条 drag region;mac 左端
+ * 红绿灯让位、win 右端 WindowControls(close �?sender 解析 = 只关本窗);
+ * 右端「合并回主窗口」按�?�?setDetached(id, false)(main 落盘 + 关本�?
+ * 主窗收广播后面板原位回停�?�?
+ * - 面板体零改动复用 GhostChipPanelBody(webview 供片/主题/崩溃接管全同�?
+ * 附加闸只认分�?地址,与宿主窗口无�?;崩溃/熔断�?GhostPanelError�?
+ * - manifest �?useInstalledGhosts 自查(ghosts:changed 广播发所有窗�?;
+ * 插件被卸�?停用�?main �?reconcile 会直接收�?这里只需短暂占位�?
+ * - �?GhostMediaLightboxHost:面板 /preview/ 点图事件推给本窗�?embedder),
+ * 不挂的话子窗�?点开看大�?没有承接端。无 sessionId,「发送到对话」隐藏�?
+ * - ⌘W / Ctrl+W:本窗口没�?tab 语义,直接关窗(= 合并回主窗的同一�?main 收口)�?
*/
+import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PictureInPicture2, Puzzle } from 'lucide-react';
import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';
import { GhostChipPanelBody, GhostPanelError } from '@/cindy-brain/ghostPanelBody';
+import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';
import { useGhostRuntimeState } from '@/cindy-brain/runtimeStates';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { WindowControls } from '@/components/title-bar/WindowControls';
import { useAppShortcut } from '@/hooks/useAppShortcut';
import { useCloseShortcutShellOwner } from '@/hooks/useCloseWindowShortcut';
+import { useLocale } from '@/hooks/useLocale';
+import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';
+import { minimizeGhostPanel, restoreGhostPanel } from '@/lib/ghostPanelBubbleState';
import { getGhostPanelWindowGhostId } from '@/lib/ghostPanelWindow';
import { createLogger } from '@/lib/logger';
+import { toast } from '@/lib/toast';
+import { extractIpcError } from '@/utils/ipcError';
import type { GhostManifest } from '../../../shared/ghost';
const log = createLogger('GhostPanelWindowLayout');
-/** 面板体 + 崩溃接管(与停靠形态 GhostPanel 同一分支逻辑,不含标准头)。 */
+/** 面板�?+ 崩溃接管(与停靠形�?GhostPanel 同一分支逻辑,不含标准�?�?*/
function PanelBody({ manifest }: { manifest: GhostManifest }) {
const runtimeState = useGhostRuntimeState(manifest.id);
const broken = runtimeState === 'crashed' || runtimeState === 'fused';
@@ -44,19 +52,98 @@ function PanelBody({ manifest }: { manifest: GhostManifest }) {
export function GhostPanelWindowLayout() {
const { t } = useTranslation();
+ const { effectiveLocale, setLocale } = useLocale();
+ const { confirm } = useConfirmDialog();
const isMac = window.electronAPI?.platform === 'darwin';
const ghostId = getGhostPanelWindowGhostId();
const ghosts = useInstalledGhosts();
const ghost = ghostId ? ghosts.find((g) => g.manifest.id === ghostId) : undefined;
- // 停用/卸载的瞬间 main 的 reconcile 会收窗;这里只兜住收窗前的一两帧。
+ // 停用/卸载的瞬�?main �?reconcile 会收�?这里只兜住收窗前的一两帧�?
const manifest = ghost && ghost.enabled !== false ? ghost.manifest : undefined;
const title = manifest?.panel?.title ?? manifest?.name ?? '';
+ const presentationReadySentRef = useRef(false);
+ // 复用隐藏窗口时,Chromium 可能保留上一次关闭按钮的 focus / :hover 状态�?
+ // 与资源用量窗口一致,隐藏时重挂载 chrome,确保再次显示从干净状态开始�?
+ const [windowChromeRevision, setWindowChromeRevision] = useState(0);
- // ⌘W / Ctrl+W:直接关本窗(main 端按 sender win.close(),controller 走
- // onClosed = 回停靠)。声明壳层所有权,App 根的 fallback 让路。
+ const minimizeToBubble = async (): Promise<void> => {
+ if (!ghostId) return;
+ minimizeGhostPanel(ghostId);
+ try {
+ await window.electronAPI.ghostPanelWindow.setDetached(ghostId, false);
+ } catch (err) {
+ restoreGhostPanel(ghostId);
+ log.warn('minimize ghost panel to bubble failed', err);
+ }
+ };
+
+ const disableAndClose = async (): Promise<void> => {
+ if (!ghostId || !manifest) return;
+ const approved = await confirm({
+ title: t('ghostPanel.disableConfirm.title', { name: manifest.name }),
+ description: t('ghostPanel.disableConfirm.body'),
+ confirmText: t('ghostPanel.disableConfirm.confirm'),
+ });
+ await window.electronAPI.ghostPanelWindow.resolveCloseRequest(approved);
+ if (!approved) return;
+ try {
+ await window.electronAPI.ghosts.setEnabled(ghostId, false);
+ } catch (error) {
+ toast.error(t(ghostInstallErrorKey(extractIpcError(error)?.code)));
+ }
+ };
+
+ // mount:renderer-ready 握手 + presentation-ready(manifest 就绪�?�?
+ useEffect(() => {
+ void window.electronAPI.ghostPanelWindow.rendererReady().catch((err) => {
+ log.warn('renderer-ready handshake failed', err);
+ });
+ }, []);
+
+ useEffect(() => {
+ if (presentationReadySentRef.current || !manifest) return;
+ presentationReadySentRef.current = true;
+ void window.electronAPI.ghostPanelWindow.presentationReady().catch((err) => {
+ log.warn('presentation-ready handshake failed', err);
+ });
+ }, [manifest]);
+
+ // 隐藏/显示时重置瞬时交互态�?
+ useEffect(() => {
+ return window.electronAPI.ghostPanelWindow.onVisibilityChanged((payload) => {
+ if (!payload.visible) {
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+ setWindowChromeRevision((revision) => revision + 1);
+ } else {
+ // 重新显示时模糊焦�?+ �?webview 重获焦点(面板内容持续运行)
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+ }
+ });
+ }, []);
+
+ useEffect(() => {
+ return window.electronAPI.ghostPanelWindow.onCloseRequested(() => {
+ void disableAndClose();
+ });
+ }, [ghostId, manifest, confirm, t, window.electronAPI.ghostPanelWindow]);
+
+ useEffect(() => {
+ return window.electronAPI.ghostPanelWindow.onMinimizeRequested(() => {
+ void minimizeToBubble();
+ });
+ }, [ghostId, window.electronAPI.ghostPanelWindow]);
+
+ useEffect(() => {
+ return window.electronAPI.onLocaleChanged?.((locale) => {
+ if (locale !== effectiveLocale) setLocale(locale);
+ }) ?? undefined;
+ }, [effectiveLocale, setLocale]);
+
+ // ⌘W / Ctrl+W:直接关本�?main 端按 sender win.close(),controller �?
+ // onClosed = 回停�?。声明壳层所有权,App 根的 fallback 让路�?
useCloseShortcutShellOwner();
useAppShortcut('close-tab-or-window', () => {
- window.electronAPI.windowClose();
+ void disableAndClose();
return true;
});
@@ -69,7 +156,7 @@ export function GhostPanelWindowLayout() {
return (
<div className="flex h-screen flex-col bg-content-area text-foreground">
- {/* 46px 自绘 chrome:整条 drag region;布局对齐 SidebarWindowLayout。 */}
+ {/* 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}
@@ -80,32 +167,33 @@ export function GhostPanelWindowLayout() {
<span className="truncate text-13 text-[var(--text-secondary)]">{title}</span>
</div>
<div
- className="flex shrink-0 items-center gap-1 pr-2"
+ className="flex shrink-0 items-center gap-0.5 pr-2"
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
>
- {/* 合并回主窗口:关偏好 + 关本窗,面板原位回停靠 */}
- <button
- type="button"
+ {/* 合并回主窗口:关偏�?+ 关本�?面板原位回停�?*/}
+ <ChromeIconButton
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-12 text-[var(--titlebar-icon)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
+ title={t('rightSidebar.window.mergeBack')}
+ aria-label={t('rightSidebar.window.mergeBack')}
>
<PictureInPicture2 size={14} />
- <span>{t('ghostPanelWindow.mergeBack')}</span>
- </button>
+ </ChromeIconButton>
</div>
{!isMac && (
<div
className="flex h-full shrink-0 items-center"
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
>
- <WindowControls />
+ <WindowControls
+ key={windowChromeRevision}
+ onMinimize={minimizeToBubble}
+ onClose={disableAndClose}
+ />
</div>
)}
</div>
- {/* 面板体:manifest 在场即挂 webview;不在场(收窗前瞬态/野 URL)给占位。 */}
+ {/* 面板�?manifest 在场即挂 webview;不在�?收窗前瞬�?�?URL)给占位�?*/}
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--panel-bg)]">
{manifest ? (
<PanelBody manifest={manifest} />
@@ -118,7 +206,7 @@ export function GhostPanelWindowLayout() {
)}
</div>
- {/* 面板 /preview/ 点图的承接端(无 sessionId:「发送到对话」隐藏)。 */}
+ {/* 面板 /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 0524616a44..9dccf7ebe2 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -9,7 +9,6 @@ import { ContentHeaderSlot } from '@/components/layout/ContentHeader';
import { rightSidebarOwnsRailChromeActions as resolveRightSidebarRailChromeActionsOwner } from '@/components/layout/railChromeActions';
import { FadeSwitcher } from '@/components/layout/FadeSwitcher';
import { RightSidebar, type RightSidebarHandle } from '@/components/layout/RightSidebar';
-import { RightSidebarMaximize } from '@/components/layout/RightSidebarMaximize';
import { RightSidebarToggle } from '@/components/layout/RightSidebarToggle';
import { Sidebar } from '@/components/sidebar/Sidebar';
import {
@@ -57,7 +56,6 @@ import { didUserCloseDetachedSidebarWindow } from '@/lib/rsbWindowTransitions';
import { routeSidebarCommand } from '@/features/right-sidebar/lib/detachedSidebarRouting';
import { openTerminalFromShortcut } from '@/features/right-sidebar/lib/openTerminalShortcut';
import { executeSidebarCommand } from '@/features/right-sidebar/lib/executeSidebarCommand';
-import { RightSidebarDetach } from '@/components/layout/RightSidebarDetach';
import { useSidebarResize } from '@/hooks/useSidebarResize';
import { useSidebarCardMode } from '@/hooks/useSidebarCardMode';
import { useSidebarPeek } from '@/hooks/useSidebarPeek';
@@ -129,6 +127,7 @@ interface RightSidebarSessionDeclarationOptions {
}
const applicationMenuLog = createLogger('ApplicationMenu');
+const log = createLogger('MainLayout');
// Keep in sync with single-segment static routes under /cc-agent in router.tsx.
const CC_AGENT_STATIC_SEGMENTS = ['boot', 'files', 'new', 'new-dialogue', 'orca', 'scheduled'];
@@ -687,32 +686,33 @@ export function MainLayout() {
// (sessionId 切换 / 草稿切换 / init)都不调,RightSidebar 默认走"直接同步"无动画。
const rightSidebarRef = useRef<RightSidebarHandle>(null);
- const handleToggleRightSidebar = useCallback(() => {
+ const handleOpenRightSidebar = useCallback(() => {
if (!rsbWindow.loaded) return;
- // 偏好「在新窗口显示侧边栏」开启时,toggle 语义改为子窗口开/关:
- // 展开 = 打开/聚焦子窗口,收起 = 关闭子窗口。内嵌折叠态不动
- // (按钮显隐由 rsbWindow.open 镜像驱动,见下方渲染处)。
+ // 主窗口固定入口只负责显示 / 聚焦,不承担关闭语义。
if (rsbDetached) {
- if (rsbWindow.open) {
- writeCollapsedFor(rightSidebarSessionId, true);
- void window.electronAPI.rightSidebarWindow.close().catch(() => undefined);
- } else {
- writeCollapsedFor(rightSidebarSessionId, false);
- void window.electronAPI.rightSidebarWindow.open().catch(() => undefined);
- }
+ writeCollapsedFor(rightSidebarSessionId, false);
+ void window.electronAPI.rightSidebarWindow
+ .open()
+ .catch((err) => log.warn('show detached right sidebar failed', err));
return;
}
+ if (!isRightSidebarCollapsed) return;
// 打开时沿用上次记住的比例(useRightSidebarResize 持久化的 fraction):展开后
// 右栏 = fraction × 可用宽、中间 flex-1 吸收剩余,窗口缩放时两栏按比例同步变化。
// 持久化按 rightSidebarSessionId 分桶 —— 各 session 独立记忆开关状态(切 session 不串扰)。
- // 显式 prime RightSidebar 走动画 —— 这是唯一会触发 250ms 折叠动画的入口。
+ // 显式 prime RightSidebar 走动画。
rightSidebarRef.current?.requestAnimateNextChange();
- setIsRightSidebarCollapsed((prev) => {
- const next = !prev;
- writeCollapsedFor(rightSidebarSessionId, next);
- return next;
- });
- }, [rightSidebarSessionId, rsbDetached, rsbWindow.loaded, rsbWindow.open]);
+ writeCollapsedFor(rightSidebarSessionId, false);
+ setIsRightSidebarCollapsed(false);
+ }, [isRightSidebarCollapsed, rightSidebarSessionId, rsbDetached, rsbWindow.loaded]);
+
+ // 面板自身的关闭按钮继续只负责收起内嵌面板。
+ const handleCloseRightSidebar = useCallback(() => {
+ if (rsbDetached || isRightSidebarCollapsed) return;
+ rightSidebarRef.current?.requestAnimateNextChange();
+ writeCollapsedFor(rightSidebarSessionId, true);
+ setIsRightSidebarCollapsed(true);
+ }, [isRightSidebarCollapsed, rightSidebarSessionId, rsbDetached]);
// 关掉右侧栏最后一个 tab 时自动收起(由 RightSidebarShell 在 tab 数 >0→0 时回调)。
// detached 子窗口形态不在此处理(那时主窗根本不渲染内嵌 Shell,也收不到此回调)。
@@ -919,36 +919,14 @@ export function MainLayout() {
}
}, [rsbDetached]);
- // 3) 重启恢复:detached && lastOpen(上次退出时窗口开着)→ 自动重开子窗口。
- // 时机对齐 takePendingDeepLink 的 pull-on-mount(ProtectedRoute + LocalDbGate
- // 之内,登录态天然就绪);ref 守护 strict-mode 双跑。open 幂等,已开则 focus。
- const rsbWindowRestoredRef = useRef(false);
+ // 3) 启动期只从 main 拉取当前进程状态。分离状态不跨客户端重启恢复;main 在
+ // controller 创建前已重置 detached / lastOpen,并清理旧版本遗留的偏好文件。
+ const rsbWindowBootstrappedRef = useRef(false);
useEffect(() => {
- if (rsbWindowRestoredRef.current) return;
- rsbWindowRestoredRef.current = true;
+ if (rsbWindowBootstrappedRef.current) return;
+ rsbWindowBootstrappedRef.current = true;
if (isSecondaryWindow()) return;
- void bootstrapRsbWindowState().then((s) => {
- if (!s) return;
- if (s.detached && s.lastOpen && !s.open) {
- // 启动恢复不是用户当次手势:窗口照常回到上次位置,但走 showInactive,
- // 不在冷启动瞬间把焦点从主窗(或用户别的应用)抢过去。
- void window.electronAPI.rightSidebarWindow
- .open({ userInitiated: false })
- .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 {
- // 桥不可用(测试环境)= 没有可恢复窗口
- }
+ void bootstrapRsbWindowState();
}, []);
// 4) 「在新窗口打开」入口(mac 浮层 / win TabBar 按钮共用):开偏好 + 弹出。
@@ -1278,7 +1256,7 @@ export function MainLayout() {
// 手势面是 ContentHeader(Windows),窗体长按亦可。
data-panel-drag-root="chat-main"
className={cn(
- 'flex flex-1 flex-col overflow-hidden bg-content-area',
+ 'relative flex flex-1 flex-col overflow-hidden bg-content-area',
isSettingsRoute ? 'min-w-0' : 'min-w-[400px]',
// RSB Maximize(Phase 6):主区彻底 display:none,把整个非左栏空间让给 RSB。
isRightSidebarMaximized && 'hidden',
@@ -1309,15 +1287,39 @@ export function MainLayout() {
shrink-0 在 main 的 flex 列里独占一行把内容推下(不遮盖)。放在
FadeSwitcher 之外 —— 它是全局状态提示,不参与路由切换动画。 */}
<CredentialStoreBanner />
+ {!isMac &&
+ rightSidebarAvailable &&
+ rsbWindow.loaded &&
+ (rsbDetached || isRightSidebarCollapsed) && (
+ <div
+ data-testid="right-sidebar-fixed-trigger"
+ className={cn(
+ 'pointer-events-none absolute z-50',
+ rightSidebarSide === 'left' ? 'left-2' : 'right-2',
+ )}
+ style={
+ {
+ top: 'calc(var(--content-header-h) + 0.25rem)',
+ WebkitAppRegion: 'no-drag',
+ } as React.CSSProperties
+ }
+ >
+ <RightSidebarToggle
+ action="show"
+ collapsed
+ onToggle={handleOpenRightSidebar}
+ side={rightSidebarSide}
+ />
+ </div>
+ )}
<FadeSwitcher key={location.pathname.split('/')[1] || 'root'}>
<Outlet
context={{
sidebarWidth,
- // detached 模式下"折叠态"= 子窗口是否关闭(chip / 按钮显示口径统一)
- rightSidebarCollapsed: rsbDetached
- ? !rsbWindow.open
- : isRightSidebarCollapsed,
- onToggleRightSidebar: handleToggleRightSidebar,
+ // detached 时主窗口没有内嵌侧栏,始终按折叠态布局;子窗口开闭
+ // 不改变主窗口浮动控件的占位语义。
+ rightSidebarCollapsed: rsbDetached || isRightSidebarCollapsed,
+ onToggleRightSidebar: handleOpenRightSidebar,
// B2b:面板所在侧,聊天视图据此决定展开入口落左上还是右上。
rightSidebarSide,
setRightSidebarAvailable,
@@ -1344,7 +1346,7 @@ export function MainLayout() {
isMac={isMac}
// Windows 展开态的折叠入口归属工具面板自身,放回 TabBar 右端;
// 收起后聊天区角上才显示展开入口。mac 仍走窗口右上浮层。
- onCloseSidebar={isMac ? undefined : handleToggleRightSidebar}
+ onCloseSidebar={handleCloseRightSidebar}
onMaximize={handleMaximizeRightSidebar}
isMaximized={isRightSidebarMaximized}
reserveLeftChromeActions={shouldReserveLeftChromeActions({
@@ -1396,8 +1398,8 @@ export function MainLayout() {
(含设置页),永远钉在窗口角,开/关右栏都不动 —— 解决「右栏作为 <main>
sibling 会把窗口按钮挤左」的问题。no-drag(按钮可点),周围窗口拖拽区由
ContentHeader / 左栏顶行提供。
- mac 不渲染本块(用系统红绿灯)。
- (Windows 折叠态的展开入口走聊天视图 chip,展开态的折叠入口在右栏 TabBar。) */}
+ mac 不渲染本块(用系统红绿灯)。Windows 固定侧栏入口保留在内容区
+ 右上角(系统按钮下一行),与截图中的原位置一致。 */}
{!isMac && (
<div
className="absolute right-0 top-0 z-50 flex h-[46px] items-center"
@@ -1418,39 +1420,21 @@ export function MainLayout() {
左上角的左栏折叠按钮(ChromeActions)对称、不跟面板跑;detach/maximize
是面板自属控件,贴右(或 maximize 撑满)时在浮层里(视觉落在面板顶栏
右端),贴左时跟面板走进 Shell 顶栏右端(见 RightSidebarShell)。 */}
- {isMac && rightSidebarAvailable && rsbWindow.loaded && (
+ {isMac &&
+ rightSidebarAvailable &&
+ rsbWindow.loaded &&
+ (rsbDetached || isRightSidebarCollapsed) && (
<div
className="absolute right-0 top-0 z-50 flex h-[46px] items-center gap-1 pr-2"
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
>
- {/* Mac 端:maximize + 折叠按钮浮在窗口右上 46px 区,与 macOS 系统标题栏规范
- 对齐;视觉上与最右 pane 顶部 46px chrome 共占同一 y 区间(z-50 覆盖,
- RSB chrome / ContentHeader 内部留占位让位)。Win 端不渲染浮层
- (maximize/折叠在 TabBar 内右端)。
- detach / maximize 仅在 RSB 展开**且是最右 pane**(贴右或 maximize
- 撑满)时显示 —— 贴左时它们跟面板走(Shell 顶栏),折叠态 maximize
- 无作用语义,只留 toggle 作为"打开"入口。 */}
- {!isRightSidebarCollapsed &&
- !rsbDetached &&
- (rightSidebarSide === 'right' || isRightSidebarMaximized) && (
- <>
- {/* 「在新窗口打开」:开偏好 + 弹出子窗口(win 端此按钮在 TabBar 内)。 */}
- {!isSecondaryWindow() && (
- <RightSidebarDetach size="toolbar" onDetach={handleDetachRightSidebar} />
- )}
- <RightSidebarMaximize
- size="toolbar"
- onMaximize={handleMaximizeRightSidebar}
- isMaximized={isRightSidebarMaximized}
- />
- </>
- )}
- {/* detached:toggle 的"折叠态"跟随子窗口开闭(收起 = 关子窗口)。
- side 只管图标方向(画"面板贴哪条边"),按钮位置恒在窗口右上。 */}
+ {/* 固定唤起入口只负责显示 / 聚焦。detach / maximize / 收起属于面板自身,
+ 在 RightSidebarShell 的顶栏内渲染,不再与本入口混用。 */}
<RightSidebarToggle
size="toolbar"
+ action="show"
collapsed={rsbDetached ? !rsbWindow.open : isRightSidebarCollapsed}
- onToggle={handleToggleRightSidebar}
+ onToggle={handleOpenRightSidebar}
side={rightSidebarSide}
/>
</div>
diff --git a/apps/desktop/src/renderer/components/layout/RightSidebar.tsx b/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
index 5440b4411f..0a59586c74 100644
--- a/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
+++ b/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
@@ -54,6 +54,8 @@ interface RightSidebarProps {
isMac: boolean;
/** 关闭整个 RightSidebar(走外层 toggle handler);仅 Win 端 TabBar 内会渲染对应按钮(Mac 走 MainLayout 浮层)。 */
onCloseSidebar?: () => void;
+ /** 固定唤起入口;只负责显示已展开的侧栏,不承担关闭语义。 */
+ onShowSidebar?: () => void;
/** 最大化 RightSidebar;Phase 6 接真行为,Phase 1 渲染按钮即可。Mac 走 MainLayout 浮层、Win 走 TabBar 右端。 */
onMaximize?: () => void;
/** 当前 cc-agent session id;由 MainLayout 持有,CCAgentSessionView ownsRoute 时通过 outlet context 推上来。
@@ -88,6 +90,7 @@ export const RightSidebar = forwardRef<RightSidebarHandle, RightSidebarProps>(fu
width,
isMac,
onCloseSidebar,
+ onShowSidebar,
onMaximize,
isMaximized,
reserveLeftChromeActions = false,
@@ -262,6 +265,7 @@ export const RightSidebar = forwardRef<RightSidebarHandle, RightSidebarProps>(fu
isMac={isMac}
unifiedTopbar={isMac}
onCloseSidebar={onCloseSidebar}
+ onShowSidebar={onShowSidebar}
onMaximize={onMaximize}
isMaximized={isMaximized}
reserveLeftChromeActions={reserveLeftChromeActions}
diff --git a/apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx b/apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx
index 0681783114..0814f18762 100644
--- a/apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx
+++ b/apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx
@@ -1,16 +1,15 @@
/**
* RightSidebarToggle — 工具面板开关按钮(纯图标,无选中底色)
* ---------------------------------------------------------------------------
- * 单一一份裸图标按钮,两处复用,两平台同款样式、不同落点:
- * - Mac:放在 ContentHeader 右端(mac 那侧没有窗口控制按钮,这个位置本就空着)。
- * - Windows:右栏折叠后放在全屏聊天视图的 chip 栈第一行 —— 落在哪个角由 `side` 决定
- * (B2b 去方位化:面板贴哪侧,展开入口就留守哪侧的 top-3 角,与 DiffPanelToggle /
- * PrevMessageJumpChip 同层(content 层,z-20),随聊天视图天然出现/消失);展开态的
- * 折叠入口放在右栏自身 TabBar 内,不悬在聊天内容上。
+ * 单一一份裸图标按钮,多处复用,两平台同款样式、不同落点:
+ * - Mac:由 MainLayout 钉在窗口右上角。
+ * - Windows:内嵌展开时位于右栏 TabBar 末端;收起或分离时由 MainLayout
+ * 放在内容区靠面板一侧的角上。入口不依赖具体路由页面渲染。
+ * `action="show"` 是单向显示 / 聚焦语义,关闭或收起由面板自己的按钮负责。
* resting 无底无边、仅 hover 底色(用户明确这个开关不要圆底;chip 栈里下方两个
* chip 保留圆底,裸图标 + 圆底 chip 连成一列)。两种尺寸(size prop):
* - 'chip'(默认,h-7 / 图标 15 / rounded-full):与 chip 栈内其它 chip 对齐,
- * 供 Windows chip 栈用。
+ * 供 Windows 内容区入口与 TabBar 用。
* - 'toolbar'(h-7 / 图标 15 / rounded-md):与左栏折叠按钮(ChromeActions 的
* PanelLeft,同为 28px / 15 / rounded-md 规格族)对齐,供 mac 右上浮层用
* (2026-07 随左簇一起从 36px 缩到 28px,左右对称)。
@@ -37,6 +36,8 @@ interface RightSidebarToggleProps {
size?: 'chip' | 'toolbar';
/** 面板当前贴哪条边(B2b:由布局树推导,经 MainLayout 下发);决定图标方向。默认 'right'。 */
side?: 'left' | 'right';
+ /** toggle 表达展开 / 收起;show 是主窗口里固定保留的显示 / 聚焦入口。 */
+ action?: 'toggle' | 'show';
}
export function RightSidebarToggle({
@@ -44,6 +45,7 @@ export function RightSidebarToggle({
onToggle,
size = 'chip',
side = 'right',
+ action = 'toggle',
}: RightSidebarToggleProps) {
const { t } = useTranslation();
const isToolbar = size === 'toolbar';
@@ -62,8 +64,20 @@ export function RightSidebarToggle({
onClick={onToggle}
// B2c:文案只说动作(折叠/展开),不提"右栏"等方位名词 —— 按钮按位置寻址,
// 管的是"贴这条缘的面板",绑定方位词会在面板换侧后说谎。
- aria-label={t(collapsed ? 'contentHeader.expandPanel' : 'contentHeader.collapsePanel')}
- title={t(collapsed ? 'contentHeader.expandPanel' : 'contentHeader.collapsePanel')}
+ aria-label={t(
+ action === 'show'
+ ? 'rightSidebar.tabs.controls.showAria'
+ : collapsed
+ ? 'contentHeader.expandPanel'
+ : 'contentHeader.collapsePanel',
+ )}
+ title={t(
+ action === 'show'
+ ? 'rightSidebar.tabs.controls.showAria'
+ : collapsed
+ ? 'contentHeader.expandPanel'
+ : 'contentHeader.collapsePanel',
+ )}
aria-expanded={!collapsed}
>
<Icon size={15} />
diff --git a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
index bd2bc44ad0..8c7a6ef7a8 100644
--- a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
@@ -24,7 +24,7 @@
* 来源路由到被控端。
*/
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PanelRight } from 'lucide-react';
@@ -37,9 +37,12 @@ import {
getBucket,
} from '@/features/right-sidebar/store';
import { WindowControls } from '@/components/title-bar/WindowControls';
+import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';
import { useAppShortcut } from '@/hooks/useAppShortcut';
import { useCloseShortcutShellOwner } from '@/hooks/useCloseWindowShortcut';
+import { useLocale } from '@/hooks/useLocale';
import { createLogger } from '@/lib/logger';
+import { makerChatStore } from '@/lib/makerChatStore';
import {
ensureGhostPanelsRegistered,
useGhostPanelsSync,
@@ -57,29 +60,37 @@ interface SidebarWindowContext {
export function SidebarWindowLayout() {
const { t } = useTranslation();
+ const { effectiveLocale, setLocale } = useLocale();
useDeviceLinkRemoteProjects();
// 意识面板注册:子窗口没有 LayoutRoot,必须自行初始化 ghost 面板注册表
// 并订阅 ghosts:changed(停靠形态所需;历史持久化的 ghost 页签也靠它识别 kind)。
ensureGhostPanelsRegistered();
useGhostPanelsSync();
+ useEffect(() => {
+ makerChatStore.initGlobalListeners();
+ }, []);
const isMac = window.electronAPI?.platform === 'darwin';
const [ctx, setCtx] = useState<SidebarWindowContext | null>(null);
+ const presentationReadySentRef = useRef(false);
+ // 复用隐藏窗口时,Chromium 可能保留上一次关闭按钮的 focus / :hover 状态。
+ // 与资源用量窗口一致,隐藏时重挂载 chrome,确保再次显示从干净状态开始。
+ const [windowChromeRevision, setWindowChromeRevision] = useState(0);
- // mount:拉一次 context + 订阅跟随推送 + ready 握手。
+ // mount:拉一次 context + 订阅跟随推送 + renderer-ready 握手。
useEffect(() => {
let cancelled = false;
void window.electronAPI.rightSidebarWindow
.getContext()
.then((initial) => {
- // 订阅推送里可能先到更新 —— 已有值时不用 stale 的 getContext 结果覆盖
if (!cancelled) setCtx((prev) => prev ?? initial);
})
.catch((err) => log.warn('getContext failed', err));
const offCtx = window.electronAPI.rightSidebarWindow.onContextChanged((next) => {
setCtx(next);
});
- void window.electronAPI.rightSidebarWindow.ready().catch((err) => {
- log.warn('ready handshake failed', err);
+ // renderer-ready:Shell 已挂载,controller 可知 React 组件树就绪。
+ void window.electronAPI.rightSidebarWindow.rendererReady().catch((err) => {
+ log.warn('renderer-ready handshake failed', err);
});
return () => {
cancelled = true;
@@ -87,6 +98,38 @@ export function SidebarWindowLayout() {
};
}, []);
+ useEffect(() => {
+ return window.electronAPI.onLocaleChanged?.((locale) => {
+ if (locale !== effectiveLocale) setLocale(locale);
+ }) ?? undefined;
+ }, [effectiveLocale, setLocale]);
+
+ // presentation-ready 只代表轻量壳已经提交首帧。不能等待主窗 context:
+ // 隐藏预热阶段 Chromium 可能节流 renderer,而 context 又由主窗异步上推;
+ // 把二者绑定会形成「等 context 才 ready、等 ready 才显示」的循环,最终只能
+ // 命中 controller 的 5s fallback。真实任务上下文继续由 getContext / 推送恢复。
+ useEffect(() => {
+ if (presentationReadySentRef.current) return;
+ presentationReadySentRef.current = true;
+ void window.electronAPI.rightSidebarWindow.presentationReady().catch((err) => {
+ log.warn('presentation-ready handshake failed', err);
+ });
+ }, []);
+
+ // 隐藏/显示时刷新 context(主窗 session 可能已切换)并重置瞬时交互态。
+ useEffect(() => {
+ return window.electronAPI.rightSidebarWindow.onVisibilityChanged((payload) => {
+ if (!payload.visible) {
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+ setWindowChromeRevision((revision) => revision + 1);
+ } else {
+ // 重新显示时从 main 缓存拉最新 context
+ void window.electronAPI.rightSidebarWindow.refreshContext().catch(() => undefined);
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+ }
+ });
+ }, []);
+
const sessionId = ctx?.available ? ctx.sessionId : null;
// agent tab-op 触发的可见性请求(本窗口内 rsbBrowserBridge 派发):
@@ -157,12 +200,11 @@ export function SidebarWindowLayout() {
</span>
</div>
<div
- className="flex shrink-0 items-center gap-1 pr-2"
+ className="flex shrink-0 items-center gap-0.5 pr-2"
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
>
{/* 合并回主窗口:关偏好 + 关本窗,主窗恢复内嵌展开 */}
- <button
- type="button"
+ <ChromeIconButton
onClick={() => {
void window.electronAPI.rightSidebarWindow.setDetached(false).catch((err) => {
log.warn('merge back failed', err);
@@ -170,18 +212,23 @@ export function SidebarWindowLayout() {
}}
title={t('rightSidebar.window.mergeBack')}
aria-label={t('rightSidebar.window.mergeBack')}
- className="inline-flex h-7 items-center gap-1.5 rounded-full px-2.5 text-12 text-[var(--titlebar-icon)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--text-primary)]"
>
<PanelRight size={14} />
- <span>{t('rightSidebar.window.mergeBack')}</span>
- </button>
+ </ChromeIconButton>
</div>
{!isMac && (
<div
className="flex h-full shrink-0 items-center"
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
>
- <WindowControls />
+ <WindowControls
+ key={windowChromeRevision}
+ onClose={() =>
+ window.electronAPI.rightSidebarWindow.close().catch((err) => {
+ log.warn('close window via title bar failed', err);
+ })
+ }
+ />
</div>
)}
</div>
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
new file mode 100644
index 0000000000..3ceaa862e0
--- /dev/null
+++ b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
@@ -0,0 +1,239 @@
+// @vitest-environment jsdom
+import React from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { RsbWindowContext } from '../../../../shared/rightSidebarWindow';
+
+const mocks = vi.hoisted(() => ({
+ controlsMounts: 0,
+ sidebarVisibilityListener: null as ((payload: { visible: boolean }) => void) | null,
+ ghostVisibilityListener: null as ((payload: { visible: boolean }) => void) | null,
+ ghostMinimizeListener: null as (() => void) | null,
+ minimizeGhostPanel: vi.fn(),
+ restoreGhostPanel: vi.fn(),
+}));
+
+vi.mock('@/components/title-bar/WindowControls', () => ({
+ WindowControls: ({ onMinimize }: { onMinimize?: () => void | Promise<void> }) => {
+ const [mountId] = React.useState(() => ++mocks.controlsMounts);
+ return (
+ <button
+ data-testid="window-controls"
+ data-mount-id={mountId}
+ onClick={() => void onMinimize?.()}
+ />
+ );
+ },
+}));
+vi.mock('@/features/right-sidebar/RightSidebarShell', () => ({ RightSidebarShell: () => null }));
+vi.mock('@/features/device-link/useDeviceLinkRemoteProjects', () => ({
+ useDeviceLinkRemoteProjects: vi.fn(),
+}));
+vi.mock('@/features/right-sidebar/lib/sidebarCommands', () => ({
+ onRequestRightSidebarVisibility: () => vi.fn(),
+}));
+vi.mock('@/features/right-sidebar/lib/executeSidebarCommand', () => ({
+ executeSidebarCommand: vi.fn(),
+}));
+vi.mock('@/features/right-sidebar/store', () => ({
+ closeTab: vi.fn(),
+ getBucket: () => ({ activeTabId: null }),
+}));
+vi.mock('@/cindy-brain/ghostPanels', () => ({
+ ensureGhostPanelsRegistered: vi.fn(),
+ useGhostPanelsSync: vi.fn(),
+}));
+vi.mock('@/cindy-brain/GhostMediaLightboxHost', () => ({ GhostMediaLightboxHost: () => null }));
+vi.mock('@/cindy-brain/ghostPanelBody', () => ({
+ GhostChipPanelBody: () => null,
+ GhostPanelError: () => null,
+}));
+vi.mock('@/cindy-brain/installErrorKey', () => ({ ghostInstallErrorKey: () => 'error' }));
+vi.mock('@/cindy-brain/runtimeStates', () => ({ useGhostRuntimeState: () => 'running' }));
+vi.mock('@/cindy-brain/useInstalledGhosts', () => ({
+ useInstalledGhosts: () => [
+ {
+ enabled: true,
+ manifest: { id: 'test-ghost', name: 'Test Ghost', panel: { title: 'Test Panel' } },
+ },
+ ],
+}));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn(() => Promise.resolve(false)) }),
+}));
+vi.mock('@/hooks/useAppShortcut', () => ({ useAppShortcut: vi.fn() }));
+vi.mock('@/hooks/useCloseWindowShortcut', () => ({ useCloseShortcutShellOwner: vi.fn() }));
+vi.mock('@/hooks/useLocale', () => ({
+ useLocale: () => ({ effectiveLocale: 'en', setLocale: vi.fn() }),
+}));
+vi.mock('@/lib/ghostPanelWindow', () => ({ getGhostPanelWindowGhostId: () => 'test-ghost' }));
+vi.mock('@/lib/ghostPanelBubbleState', () => ({
+ minimizeGhostPanel: mocks.minimizeGhostPanel,
+ restoreGhostPanel: mocks.restoreGhostPanel,
+}));
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: { initGlobalListeners: vi.fn() },
+}));
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn() } }));
+vi.mock('@/utils/ipcError', () => ({ extractIpcError: () => null }));
+vi.mock('lucide-react', () => ({
+ PanelRight: () => null,
+ Minus: () => null,
+ PictureInPicture2: () => null,
+ Puzzle: () => null,
+}));
+vi.mock('react-i18next', () => ({
+ initReactI18next: { type: '3rdParty', init: vi.fn() },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { GhostPanelWindowLayout } from '../GhostPanelWindowLayout';
+import { SidebarWindowLayout } from '../SidebarWindowLayout';
+
+describe('reusable auxiliary window chrome', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.controlsMounts = 0;
+ mocks.sidebarVisibilityListener = null;
+ mocks.ghostVisibilityListener = null;
+ mocks.ghostMinimizeListener = null;
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ platform: 'win32',
+ rightSidebarWindow: {
+ getContext: vi.fn(() =>
+ Promise.resolve({
+ sessionId: null,
+ workdir: null,
+ remoteHostId: null,
+ available: false,
+ }),
+ ),
+ onContextChanged: vi.fn(() => vi.fn()),
+ rendererReady: vi.fn(() => Promise.resolve()),
+ presentationReady: vi.fn(() => Promise.resolve()),
+ onVisibilityChanged: vi.fn((listener) => {
+ mocks.sidebarVisibilityListener = listener;
+ return vi.fn();
+ }),
+ refreshContext: vi.fn(() => Promise.resolve()),
+ onCommand: vi.fn(() => vi.fn()),
+ close: vi.fn(() => Promise.resolve()),
+ setDetached: vi.fn(() => Promise.resolve()),
+ },
+ ghostPanelWindow: {
+ rendererReady: vi.fn(() => Promise.resolve()),
+ presentationReady: vi.fn(() => Promise.resolve()),
+ onVisibilityChanged: vi.fn((listener) => {
+ mocks.ghostVisibilityListener = listener;
+ return vi.fn();
+ }),
+ onCloseRequested: vi.fn(() => vi.fn()),
+ onMinimizeRequested: vi.fn((listener) => {
+ mocks.ghostMinimizeListener = listener;
+ return vi.fn();
+ }),
+ resolveCloseRequest: vi.fn(() => Promise.resolve()),
+ setDetached: vi.fn(() => Promise.resolve()),
+ },
+ ghosts: { setEnabled: vi.fn(() => Promise.resolve()) },
+ },
+ });
+ });
+
+ afterEach(() => cleanup());
+
+ it('remounts right-sidebar controls when the cached window is hidden', async () => {
+ render(<SidebarWindowLayout />);
+ const controlsBeforeHide = screen.getByTestId('window-controls');
+ controlsBeforeHide.focus();
+
+ await act(async () => mocks.sidebarVisibilityListener?.({ visible: false }));
+
+ const controlsAfterHide = screen.getByTestId('window-controls');
+ expect(controlsAfterHide).not.toBe(controlsBeforeHide);
+ expect(document.activeElement).not.toBe(controlsAfterHide);
+ });
+
+ it('reports the sidebar shell ready without waiting for session context', async () => {
+ window.electronAPI.rightSidebarWindow.getContext = vi.fn(
+ () => new Promise<RsbWindowContext | null>(() => undefined),
+ );
+
+ render(<SidebarWindowLayout />);
+
+ await waitFor(() => {
+ expect(window.electronAPI.rightSidebarWindow.rendererReady).toHaveBeenCalledOnce();
+ expect(window.electronAPI.rightSidebarWindow.presentationReady).toHaveBeenCalledOnce();
+ });
+ });
+
+ it('remounts ghost-panel controls when the cached window is hidden', async () => {
+ render(<GhostPanelWindowLayout />);
+ const controlsBeforeHide = screen.getByTestId('window-controls');
+ controlsBeforeHide.focus();
+
+ await act(async () => mocks.ghostVisibilityListener?.({ visible: false }));
+
+ const controlsAfterHide = screen.getByTestId('window-controls');
+ expect(controlsAfterHide).not.toBe(controlsBeforeHide);
+ expect(document.activeElement).not.toBe(controlsAfterHide);
+ });
+
+ it('uses an icon-only merge-back action for detached plugin windows', async () => {
+ render(<GhostPanelWindowLayout />);
+
+ const mergeBack = screen.getByRole('button', { name: 'rightSidebar.window.mergeBack' });
+ expect(mergeBack.getAttribute('title')).toBe('rightSidebar.window.mergeBack');
+ expect(mergeBack.textContent).not.toContain('rightSidebar.window.mergeBack');
+ fireEvent.click(mergeBack);
+
+ expect(window.electronAPI.ghostPanelWindow.setDetached).toHaveBeenCalledWith(
+ 'test-ghost',
+ false,
+ );
+ });
+
+ it('minimizes a detached plugin window into the main-window Ghost bubble', async () => {
+ render(<GhostPanelWindowLayout />);
+
+ fireEvent.click(screen.getByTestId('window-controls'));
+
+ expect(mocks.minimizeGhostPanel).toHaveBeenCalledWith('test-ghost');
+ expect(window.electronAPI.ghostPanelWindow.setDetached).toHaveBeenCalledWith(
+ 'test-ghost',
+ false,
+ );
+ expect(mocks.restoreGhostPanel).not.toHaveBeenCalled();
+ });
+
+ it('restores the bubble state when merging the minimized plugin window fails', async () => {
+ window.electronAPI.ghostPanelWindow.setDetached = vi.fn(() =>
+ Promise.reject(new Error('failed')),
+ );
+ render(<GhostPanelWindowLayout />);
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('window-controls'));
+ });
+
+ expect(mocks.minimizeGhostPanel).toHaveBeenCalledWith('test-ghost');
+ expect(mocks.restoreGhostPanel).toHaveBeenCalledWith('test-ghost');
+ });
+
+ it('uses the same Ghost bubble action for a native minimize request', async () => {
+ render(<GhostPanelWindowLayout />);
+
+ await act(async () => mocks.ghostMinimizeListener?.());
+
+ expect(mocks.minimizeGhostPanel).toHaveBeenCalledWith('test-ghost');
+ expect(window.electronAPI.ghostPanelWindow.setDetached).toHaveBeenCalledWith(
+ 'test-ghost',
+ false,
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/RightSidebarToggle.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/RightSidebarToggle.test.tsx
new file mode 100644
index 0000000000..24b2b80e2f
--- /dev/null
+++ b/apps/desktop/src/renderer/components/layout/__tests__/RightSidebarToggle.test.tsx
@@ -0,0 +1,43 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+import { RightSidebarToggle } from '../RightSidebarToggle';
+
+describe('RightSidebarToggle', () => {
+ it.each([true, false])(
+ 'uses one stable show label for the fixed trigger when collapsed=%s',
+ (collapsed) => {
+ const onToggle = vi.fn();
+ render(
+ <RightSidebarToggle
+ action="show"
+ collapsed={collapsed}
+ onToggle={onToggle}
+ />,
+ );
+
+ const button = screen.getByRole('button', {
+ name: 'rightSidebar.tabs.controls.showAria',
+ });
+ expect(button.getAttribute('title')).toBe('rightSidebar.tabs.controls.showAria');
+ fireEvent.click(button);
+ expect(onToggle).toHaveBeenCalledOnce();
+ },
+ );
+
+ it('keeps the panel-owned toggle labels stateful', () => {
+ const { rerender } = render(
+ <RightSidebarToggle collapsed onToggle={vi.fn()} />,
+ );
+ expect(screen.getByRole('button', { name: 'contentHeader.expandPanel' })).toBeTruthy();
+
+ rerender(<RightSidebarToggle collapsed={false} onToggle={vi.fn()} />);
+ expect(screen.getByRole('button', { name: 'contentHeader.collapsePanel' })).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx b/apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx
new file mode 100644
index 0000000000..e432e546b2
--- /dev/null
+++ b/apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx
@@ -0,0 +1,27 @@
+import type { ButtonHTMLAttributes, ReactNode } from 'react';
+
+/**
+ * ChromeIconButton —— 标题栏 28px 圆形图标按钮基元。
+ *
+ * 统一 PanelChrome、TabBar、GhostPanelWindowLayout、SidebarWindowLayout
+ * 四处的按钮视觉规格:
+ * - 28×28 圆形,透明底
+ * - 图标 14px
+ * - titlebar-icon 颜色 + surface-hover 悬浮态
+ *
+ * 快捷键逻辑由各调用方自行注册,不进入本组件。
+ */
+const CHROME_ICON_BUTTON_CLASS =
+ '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)]';
+
+export function ChromeIconButton({
+ children,
+ className,
+ ...rest
+}: ButtonHTMLAttributes<HTMLButtonElement> & { children?: ReactNode }) {
+ return (
+ <button type="button" className={[CHROME_ICON_BUTTON_CLASS, className].filter(Boolean).join(' ')} {...rest}>
+ {children}
+ </button>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx b/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
index 57e73d873b..ec9a25e48d 100644
--- a/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
+++ b/apps/desktop/src/renderer/components/title-bar/WindowControls.tsx
@@ -20,12 +20,18 @@ interface WindowControlsProps {
* to match the Stone/Silver tones from docs/design-rules/cindy-design-system.md.
*/
iconClassName?: string;
+ /** Override the default minimize action for an auxiliary window. */
+ onMinimize?: () => void | Promise<void>;
+ /** Override the default close action for an auxiliary window. */
+ onClose?: () => void | Promise<void>;
}
const DEFAULT_ICON_CLASS = 'text-titlebar-icon';
export function WindowControls({
iconClassName = DEFAULT_ICON_CLASS,
+ onMinimize,
+ onClose,
}: WindowControlsProps = {}) {
const [showCloseDialog, setShowCloseDialog] = useState(false);
const [showWindowsCloseBehaviorDialog, setShowWindowsCloseBehaviorDialog] = useState(false);
@@ -69,11 +75,19 @@ export function WindowControls({
const controlBase = cn(
'flex items-center justify-center',
- 'h-9 w-[46px]',
+ 'h-7 w-7',
iconClassName,
'transition-colors',
);
+ const handleMinimizeClick = (): void => {
+ if (onMinimize) {
+ void onMinimize();
+ return;
+ }
+ window.electronAPI.windowMinimize();
+ };
+
// 进入 closing 态 + 调 main 端关闭。同时被"点 X 无 in-flight 直走"和 ConfirmDialog
// 的 onConfirm 调用,共用一份语义。幂等: closingRef 守住重复调用。
const beginClose = (): void => {
@@ -129,6 +143,10 @@ export function WindowControls({
// splash / login 阶段 maker-ipc handler 还没注册, invoke 会 reject ——
// catch 后当作 false 处理 (那个阶段本来就不可能有 in-flight)。
const handleCloseClick = async (): Promise<void> => {
+ if (onClose) {
+ await onClose();
+ return;
+ }
// 「在新窗口打开」的副窗口 / 右侧栏子窗口 / 插件面板子窗口:关闭只关本窗
// (会话活在主进程,不受影响),不退出 app,也没有 disposer chain,所以跳过
// in-flight 确认框 + 全屏 closing overlay,直接调 windowClose(main 端按
@@ -161,13 +179,13 @@ export function WindowControls({
return (
<>
- <div className="flex">
+ <div className="flex gap-0.5">
<button
className={cn(controlBase, 'hover:bg-titlebar-control-hover')}
- onClick={() => window.electronAPI.windowMinimize()}
+ onClick={handleMinimizeClick}
aria-label={t('titleBar.minimize')}
>
- <Minus size={16} />
+ <Minus size={14} />
</button>
<button
className={cn(controlBase, 'hover:bg-titlebar-control-hover')}
@@ -182,7 +200,7 @@ export function WindowControls({
aria-label={t('titleBar.close')}
disabled={closing}
>
- <X size={16} />
+ <X size={14} />
</button>
</div>
<ConfirmDialog
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 50a430ce73..e47908a1c7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -99,7 +99,6 @@ import { Tip } from '@/components/ui/tooltip';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { useSilentEncryptedRetry } from '@/hooks/useSilentEncryptedRetry';
import { TodaySpendChip } from '@/components/status/TodaySpendChip';
-import { RightSidebarToggle } from '@/components/layout/RightSidebarToggle';
import { TopRightChipStack, TopRightChipStackProvider } from '@/components/chat/TopRightChipStack';
import { ChatDisplaySnapshotProvider } from '@/components/chat/ChatDisplaySnapshotContext';
import { useCCAgentChat } from '@/hooks/useCCAgentChat';
@@ -626,8 +625,6 @@ export function CCAgentSessionView({
) => void;
} | null>();
const rightSidebarCollapsed = outletContext?.rightSidebarCollapsed ?? true;
- const onToggleRightSidebar = outletContext?.onToggleRightSidebar;
- // B2b:面板所在侧 —— 折叠态的展开入口要留守面板消失的那一侧(缺省经典右侧)。
const rightSidebarSide = outletContext?.rightSidebarSide ?? 'right';
const setRightSidebarAvailable = outletContext?.setRightSidebarAvailable;
const setRightSidebarSessionId = outletContext?.setRightSidebarSessionId;
@@ -694,10 +691,7 @@ export function CCAgentSessionView({
const hasControlledBanner = showComposerControlledBanner && controlledBy.length > 0;
const controlledBannerCollapsed = useComposerCollapsed(sessionId ?? null);
const showExpandedControlledBanner = hasControlledBanner && !controlledBannerCollapsed;
- // 平台分流:mac 右栏开关放在 ContentHeader 右端(见 ContentHeader.tsx),Windows
- // 放在下方 chip 栈第一行。两端都靠 ownsRoute 限定只在全屏聊天视图出现。
const isMac = window.electronAPI?.platform === 'darwin';
-
// messageWidth:消息流容器宽度(视觉边距 50px / compact 20px)
// inputWidth:ChatInput / 状态栏 / workingDir 行的宽度(视觉边距 40px / compact 10px)
// doc rail 内嵌场景(isCompactRail)恒 compact;主会话不显式传 compact,由 hook
@@ -4521,41 +4515,18 @@ export function CCAgentSessionView({
</div>
{/* TopRightChipStack:聊天视图右上 chip 浮层。
- chip 栈第一行 = 右栏展开入口(仅 Windows 且右栏折叠时;展开态的折叠按钮
- 归属右栏 TabBar;mac 开关在 ContentHeader 右端,故 !isMac 守卫)。
+ Windows 固定侧栏入口由 MainLayout 承载;当入口位于右侧时在本栈第一行
+ 保留等尺寸占位,让消息跳转等 portal chip 自然落到下一行。
MessageStream 内部的 PrevMessageJumpChip 通过 portal 挂入同一栈,自然落到下一行。
"本次会话改动文件列表"已迁移到 RSB review tab,不再保留浮动按钮 + 滑入抽屉。 */}
<TopRightChipStack>
- {/* Windows 折叠态的展开入口钉在聊天区靠缝的角上;面板贴右时在右上
- (本栈第一行),贴左时镜像到左上(下方容器)。 */}
{!isMac &&
- rightSidebarCollapsed &&
(ownsRoute || showRsbToggle) &&
- onToggleRightSidebar &&
+ rightSidebarCollapsed &&
rightSidebarSide === 'right' && (
- <RightSidebarToggle
- collapsed={rightSidebarCollapsed}
- onToggle={onToggleRightSidebar}
- side="right"
- />
+ <div aria-hidden className="h-7 w-7 shrink-0" />
)}
</TopRightChipStack>
- {/* mac 不渲染本 chip(2026-07-09 Lizi 口径):mac 的折叠 toggle 无论面板贴
- 哪侧都**恒钉窗口右上角**(MainLayout 浮层,与左栏折叠按钮对称);
- Windows 仅折叠态显示,面板贴左时镜像到聊天区左上角。 */}
- {!isMac &&
- rightSidebarCollapsed &&
- (ownsRoute || showRsbToggle) &&
- onToggleRightSidebar &&
- rightSidebarSide === 'left' && (
- <div className="pointer-events-none absolute left-3 top-3 z-20 flex flex-col items-start gap-2">
- <RightSidebarToggle
- collapsed={rightSidebarCollapsed}
- onToggle={onToggleRightSidebar}
- side="left"
- />
- </div>
- )}
</section>
</>
);
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 4b1d1a6a01..76c120b7ab 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -51,7 +51,6 @@ import {
type FolderPickerSelectSource,
} from '@/components/new-chat/FolderPickerPopover';
import { DeviceSwitcherPill } from '@/components/new-chat/DeviceSwitcherPill';
-import { RightSidebarToggle } from '@/components/layout/RightSidebarToggle';
import {
AddRemoteProjectDialog,
type RemoteProjectTarget,
@@ -233,10 +232,7 @@ import {
} from './deviceLinkDraftDefaults';
import { makeMirrorAccessors, replaceScope, clearScope } from '@/state/deviceLinkModelMirror';
import type { ModelMemoryAccessors } from '@/components/new-chat/ModelSelector';
-import {
- DRAFT_RIGHT_SIDEBAR_TOGGLE_DRAG_STYLE,
- resolveNewMakerDraftRightSidebar,
-} from './newMakerDraftRightSidebar';
+import { resolveNewMakerDraftRightSidebar } from './newMakerDraftRightSidebar';
import { resolveNewMakerDraftEffort } from './newMakerDraftModelPrefs';
import { closeAllTabs as closeRightSidebarTabs } from '@/features/right-sidebar/store';
import { revealOrcaWorkersTab } from '@/features/right-sidebar/plugins/orca-workers/actions';
@@ -632,8 +628,6 @@ export function NewMakerDraftRoute() {
) => void;
} | null>();
const rightSidebarCollapsed = outletContext?.rightSidebarCollapsed ?? true;
- const onToggleRightSidebar = outletContext?.onToggleRightSidebar;
- // B2b:面板所在侧 —— 展开入口留守面板消失的那一侧(缺省经典右侧)。
const rightSidebarSide = outletContext?.rightSidebarSide ?? 'right';
const setRightSidebarAvailable = outletContext?.setRightSidebarAvailable;
const setRightSidebarSessionId = outletContext?.setRightSidebarSessionId;
@@ -4399,35 +4393,16 @@ export function NewMakerDraftRoute() {
{/* mac 上本页不渲染通用 ContentHeader 且顶部无交互元素,垫一条透明
窗口拖拽条(windowDrag.tsx 约定) */}
<InvisibleWindowDragStrip />
- {/* Windows 折叠态显示展开入口,面板贴右在右上、贴左镜像左上,
- 与 CCAgentSessionView 同规则。展开态的折叠按钮归属右栏 TabBar。
- mac 不渲染(2026-07-09 Lizi 口径):
- 折叠 toggle 无论面板贴哪侧都恒钉窗口右上角(MainLayout 浮层)。 */}
+ {/* 固定入口由 MainLayout 承载;入口在右侧且未内嵌时保留第一行位置,
+ 避免其它 chip 与它重叠。 */}
{!IS_MAC_PLATFORM &&
- rightSidebarCollapsed &&
draftRightSidebar.available &&
- onToggleRightSidebar &&
- (rightSidebarSide === 'right' ? (
+ rightSidebarCollapsed &&
+ rightSidebarSide === 'right' && (
<TopRightChipStack>
- <div style={DRAFT_RIGHT_SIDEBAR_TOGGLE_DRAG_STYLE}>
- <RightSidebarToggle
- collapsed={rightSidebarCollapsed}
- onToggle={onToggleRightSidebar}
- side="right"
- />
- </div>
+ <div aria-hidden className="h-7 w-7 shrink-0" />
</TopRightChipStack>
- ) : (
- <div className="pointer-events-none absolute left-3 top-3 z-20">
- <div style={DRAFT_RIGHT_SIDEBAR_TOGGLE_DRAG_STYLE}>
- <RightSidebarToggle
- collapsed={rightSidebarCollapsed}
- onToggle={onToggleRightSidebar}
- side="left"
- />
- </div>
- </div>
- ))}
+ )}
<main
data-testid="create-agent-main"
className={cn(
diff --git a/apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx b/apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx
index d653c0158c..87b16a3505 100644
--- a/apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx
@@ -14,7 +14,7 @@ import { useRemoteProjectSessions } from '@/features/device-link/remoteProjectsS
import { cn } from '@/lib/utils';
import { CCAgentSessionView } from './CCAgentSessionView';
import { isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';
-import { useStopOrcaCollab } from './hooks/useStopOrcaCollab';
+import { useStopOrcaCollabWithoutNavigation } from './hooks/useStopOrcaCollab';
import {
clearWorkerAttention,
useWorkerAttentionSnapshot,
@@ -54,9 +54,8 @@ export function OrcaSplitView({
() => mergeSessionSources(localSessions, remoteSessions),
[localSessions, remoteSessions],
);
- const { requestStop: requestStopCollab } = useStopOrcaCollab({
+ const { requestStop: requestStopCollab } = useStopOrcaCollabWithoutNavigation({
leadSessionId,
- navigateOnSuccess: false,
});
const {
selectedWorkerRecord,
diff --git a/apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx b/apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx
index a652a5fc1c..c77b93aa91 100644
--- a/apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx
@@ -7,7 +7,6 @@
*/
import { useCallback, useEffect, useRef } from 'react';
-import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { isAgentIslandSupported } from '@/hooks/useAgentIslandSettings';
@@ -37,6 +36,8 @@ export interface OrcaWorkerPanelProps {
onFocusWorkerSessionIdConsumed?: (revision: number) => void;
onSelectionIntentCleared?: (revision: number) => void;
onSearchJumpConsumed?: () => void;
+ /** Main-window host navigation. Detached sidebar windows omit it and hide the settings action. */
+ onOpenSettings?: () => void;
}
function sameVisibleSessionPayload(
@@ -60,9 +61,9 @@ export function OrcaWorkerPanel({
onFocusWorkerSessionIdConsumed,
onSelectionIntentCleared,
onSearchJumpConsumed,
+ onOpenSettings,
}: OrcaWorkerPanelProps) {
const { t } = useTranslation();
- const navigate = useNavigate();
const {
workers,
focusedWorker,
@@ -165,8 +166,8 @@ export function OrcaWorkerPanel({
hardLimit={hardLimit}
onSwitchFocus={handleSwitchFocus}
onOpenCreate={() => void handleOpenCreate()}
- onOpenSettings={() => navigate('/settings?section=collaboration')}
- settingsEnabled={!isSidebarWindow()}
+ onOpenSettings={() => onOpenSettings?.()}
+ settingsEnabled={!isSidebarWindow() && Boolean(onOpenSettings)}
onArchiveWorker={handleArchiveWorker}
clearAttentionWhenVisible={viewVisible}
/>
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useStopOrcaCollab.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useStopOrcaCollab.ts
index da17ac191a..c0affb1604 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useStopOrcaCollab.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useStopOrcaCollab.ts
@@ -11,7 +11,7 @@
* 失败:toast 提示, 不抛错(swallowed), busy 状态自动复位。
*/
import { useCallback, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useNavigate, type NavigateFunction } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
@@ -41,11 +41,13 @@ export interface StopOrcaCollabApi {
busy: boolean;
}
-export function useStopOrcaCollab(opts: UseStopOrcaCollabOptions): StopOrcaCollabApi {
+function useStopOrcaCollabCore(
+ opts: UseStopOrcaCollabOptions,
+ navigate: NavigateFunction | null,
+): StopOrcaCollabApi {
const { leadSessionId, navigateOnSuccess = true } = opts;
const { t } = useTranslation();
const { confirm: confirmDialog } = useConfirmDialog();
- const navigate = useNavigate();
const [busy, setBusy] = useState(false);
const requestStop = useCallback(async () => {
@@ -63,7 +65,7 @@ export function useStopOrcaCollab(opts: UseStopOrcaCollabOptions): StopOrcaColla
// 销毁一个不存在的 team、或撞上同 id 的本机会话,而远端的协同其实还开着。
await makerApiForSticky(leadSessionId).disableOrca(leadSessionId);
void sessionsStore.forceRefresh('active');
- if (navigateOnSuccess) {
+ if (navigateOnSuccess && navigate) {
navigate(`/cc-agent/${leadSessionId}`, { replace: true });
}
return true;
@@ -78,3 +80,18 @@ export function useStopOrcaCollab(opts: UseStopOrcaCollabOptions): StopOrcaColla
return { requestStop, busy };
}
+
+/** Router host path: stop collaboration and optionally navigate back to the lead task. */
+export function useStopOrcaCollab(opts: UseStopOrcaCollabOptions): StopOrcaCollabApi {
+ return useStopOrcaCollabCore(opts, useNavigate());
+}
+
+/**
+ * Lightweight auxiliary-window path. It deliberately avoids React Router so the detached
+ * sidebar can keep its minimal renderer entry while reusing the same stop-confirmation flow.
+ */
+export function useStopOrcaCollabWithoutNavigation(
+ opts: Omit<UseStopOrcaCollabOptions, 'navigateOnSuccess'>,
+): StopOrcaCollabApi {
+ return useStopOrcaCollabCore({ ...opts, navigateOnSuccess: false }, null);
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
index 76db1e460f..d6610c5984 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
@@ -19,7 +19,15 @@
* - workdir 为空串 = remote session 或还没解析,plugin 自行降级渲染占位。
*/
-import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
+import {
+ Suspense,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from 'react';
import { useTranslation } from 'react-i18next';
import { createLogger } from '@/lib/logger';
@@ -28,6 +36,7 @@ import { useAppShortcut } from '@/hooks/useAppShortcut';
import { useMacFullscreen } from '@/hooks/useMacFullscreen';
import { RightSidebarDetach } from '@/components/layout/RightSidebarDetach';
import { RightSidebarMaximize } from '@/components/layout/RightSidebarMaximize';
+import { RightSidebarToggle } from '@/components/layout/RightSidebarToggle';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
import { TabBar, TabStrip } from './TabBar';
import { EmptyState } from './EmptyState';
@@ -52,6 +61,7 @@ import './plugins';
import { initRsbBrowserBridge } from './lib/rsbBrowserBridge';
import { initIOSSimulatorFocusBridge } from './lib/iosSimulatorFocusBridge';
import { initPopupRouter, setPopupFallbackSession } from './lib/popupRouter';
+import { TabBodyErrorBoundary } from './TabBodyErrorBoundary';
import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
import {
isIOSSimulatorPluginAvailable,
@@ -60,15 +70,12 @@ import {
} from './iosSimulatorPluginAvailability';
const log = createLogger('rightSidebar.shell');
+const EMPTY_TAB_ID_SET = new Set<string>();
/**
- * Mac 合并顶栏右端 spacer 宽度,对应 MainLayout 浮层按钮簇(MainLayout.tsx
- * `isMac && rightSidebarAvailable` 那块 `absolute right-0 top-0 z-50` 浮层)
- * 展开态的占宽:3 个 h-7 w-7 按钮(detach / maximize / 折叠,28×3=84;
- * #650 起与左簇统一 28px 规格族)+ gap-1 × 2(4×2=8)+ pr-2(8)= 100。
- * 两处没有共享常量(浮层用 tailwind 类布局,绑不到同一个数字上),MainLayout
- * 侧增删按钮 / 改间距时必须同步核对本值,否则 tab strip 会被浮层遮挡或留白。
+ * Mac 合并顶栏右端 spacer 宽度,对应 MainLayout 固定唤起按钮:28px 按钮 + 8px 右距。
+ * detach / maximize / 收起均属于面板自身,直接渲染在本顶栏中。
*/
-const MAC_HEADER_ACTION_SPACER_PX = 100;
+const MAC_HEADER_ACTION_SPACER_PX = 36;
type RightTabDirection = 'prev' | 'next';
interface RightSidebarShellProps {
@@ -97,6 +104,8 @@ interface RightSidebarShellProps {
*/
unifiedTopbar?: boolean;
onCloseSidebar?: () => void;
+ /** Windows 内嵌展开态的固定唤起入口;Mac 由 MainLayout 窗口级浮层承载。 */
+ onShowSidebar?: () => void;
onMaximize?: () => void;
/** maximize 态 — 用来让 TabBar 把 maximize 按钮换图标(Maximize2 ↔ Minimize2)。 */
isMaximized?: boolean;
@@ -135,6 +144,7 @@ export function RightSidebarShell({
isMac,
unifiedTopbar = false,
onCloseSidebar,
+ onShowSidebar,
onMaximize,
isMaximized,
onDetach,
@@ -222,6 +232,69 @@ export function RightSidebarShell({
const tabs = projectedTabs.tabs;
const activeTabId = projectedTabs.activeTabId;
+ // 首帧只挂当前激活 tab。其余 tab 在浏览器空闲期逐个补挂载,随后继续按原有
+ // keep-alive 语义保留组件 / webview / 编辑器状态。这样恢复一个多 tab 会话时,
+ // 非当前面板不会与窗口首帧、presentation-ready 握手争抢主线程。
+ const [deferredMountState, setDeferredMountState] = useState<{
+ sessionId: string | null;
+ tabIds: Set<string>;
+ }>(() => ({ sessionId: null, tabIds: new Set() }));
+ const deferredMountedTabIds =
+ deferredMountState.sessionId === sessionId ? deferredMountState.tabIds : EMPTY_TAB_ID_SET;
+
+ useEffect(() => {
+ setDeferredMountState((previous) => {
+ if (previous.sessionId !== sessionId) {
+ return {
+ sessionId,
+ tabIds: activeTabId ? new Set([activeTabId]) : new Set(),
+ };
+ }
+ if (!activeTabId || previous.tabIds.has(activeTabId)) return previous;
+ const next = new Set(previous.tabIds);
+ next.add(activeTabId);
+ return { sessionId, tabIds: next };
+ });
+ }, [activeTabId, sessionId]);
+
+ useEffect(() => {
+ if (!bucket.hydrated || !sessionId) return;
+ const pendingTabIds = tabs
+ .map((tab) => tab.id)
+ .filter((tabId) => tabId !== activeTabId && !deferredMountedTabIds.has(tabId));
+ if (pendingTabIds.length === 0) return;
+
+ let cancelled = false;
+ let idleId: number | null = null;
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
+ let nextIndex = 0;
+ const scheduleNext = () => {
+ if (cancelled || nextIndex >= pendingTabIds.length) return;
+ const mountNext = () => {
+ if (cancelled) return;
+ const tabId = pendingTabIds[nextIndex++];
+ setDeferredMountState((previous) => {
+ if (previous.sessionId !== sessionId || previous.tabIds.has(tabId)) return previous;
+ const next = new Set(previous.tabIds);
+ next.add(tabId);
+ return { sessionId, tabIds: next };
+ });
+ scheduleNext();
+ };
+ if (typeof window.requestIdleCallback === 'function') {
+ idleId = window.requestIdleCallback(mountNext, { timeout: 1000 });
+ } else {
+ timeoutId = setTimeout(mountNext, 32);
+ }
+ };
+ scheduleNext();
+ return () => {
+ cancelled = true;
+ if (idleId !== null) window.cancelIdleCallback(idleId);
+ if (timeoutId !== null) clearTimeout(timeoutId);
+ };
+ }, [activeTabId, bucket.hydrated, deferredMountedTabIds, sessionId, tabs]);
+
// If a now-hidden simulator tab owned the active marker, move the persisted
// marker to a visible tab (or null). The simulator tab itself remains stored
// and returns when the plugin is enabled again.
@@ -527,31 +600,34 @@ export function RightSidebarShell({
addButtonWrapperClassName="h-[30px]"
iosSimulatorAvailable={iosSimulatorPluginAvailable}
/>
- {/* 右端两态(M2,2026-07-09 Lizi 口径修订):
- - 贴右(默认)/ maximize 撑满:MainLayout 的 mac 浮层按钮钉在窗口
- 右上角(此时正压在本顶栏右端),这里用固定 spacer 给 detach /
- maximize / 折叠三按钮让位,避免 tab strip 展开时压到浮层下方。
- - 贴左(非 maximize):窗口右上浮层只剩折叠 toggle(钉在最右 pane
- = 聊天区的顶栏角上,不跟面板跑),面板自属控件跟面板走 —— 在本
- 顶栏右端渲染真按钮(detach + maximize)。 */}
- {panelSide === 'left' && !isMaximized ? (
- <div
- data-testid="right-sidebar-topbar-actions"
- className="flex h-full shrink-0 items-center gap-1"
- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
- >
- {onDetach && <RightSidebarDetach size="toolbar" onDetach={onDetach} />}
- {onMaximize && (
- <RightSidebarMaximize
- size="toolbar"
- onMaximize={onMaximize}
- isMaximized={isMaximized}
- />
- )}
- </div>
- ) : (
+ {/* 面板自属控件始终跟随面板:detach → maximize → 收起。固定唤起入口只在
+ 面板收起或分离时存在;展开态不渲染无效的 show 按钮,也不预留空位。 */}
+ <div
+ data-testid="right-sidebar-topbar-actions"
+ className="flex h-full shrink-0 items-center gap-0.5"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ {onDetach && <RightSidebarDetach size="toolbar" onDetach={onDetach} />}
+ {onMaximize && (
+ <RightSidebarMaximize
+ size="toolbar"
+ onMaximize={onMaximize}
+ isMaximized={isMaximized}
+ />
+ )}
+ {onCloseSidebar && (
+ <RightSidebarToggle
+ size="toolbar"
+ collapsed={false}
+ onToggle={onCloseSidebar}
+ side={panelSide}
+ />
+ )}
+ </div>
+ {onShowSidebar && (panelSide === 'right' || isMaximized) && (
<div
aria-hidden
+ data-testid="right-sidebar-fixed-trigger-spacer"
className="pointer-events-none h-full shrink-0"
style={{ width: MAC_HEADER_ACTION_SPACER_PX }}
/>
@@ -569,6 +645,8 @@ export function RightSidebarShell({
showWindowControls={!isMac}
onMaximize={onMaximize}
onCloseSidebar={onCloseSidebar}
+ onShowSidebar={onShowSidebar}
+ panelSide={panelSide}
isMaximized={isMaximized}
onDetach={onDetach}
onCloseOthers={handleCloseOthers}
@@ -596,7 +674,9 @@ export function RightSidebarShell({
// 所有 tab 都挂载,只切换可见性(规则 7:杜绝切顶层 tab 时 plugin 内部 state /
// webview / 编辑器 / 文件树 expansion 全部丢失重建)。pointer-events 用
// `hidden` 自然 disable,visibility 状态由 onVisibilityChange 给 plugin。
- tabs.map((tab) => (
+ tabs
+ .filter((tab) => tab.id === activeTabId || deferredMountedTabIds.has(tab.id))
+ .map((tab) => (
<PluginBodyHost
key={tab.id}
tab={tab}
@@ -608,7 +688,7 @@ export function RightSidebarShell({
shellVisible={shellVisible}
t={t}
/>
- ))
+ ))
)}
</div>
</div>
@@ -706,12 +786,16 @@ function PluginBodyHost({
aria-hidden={!active || undefined}
>
{plugin ? (
- <plugin.TabBody
- state={hydratedState}
- ctx={ctx}
- active={active}
- shellVisible={shellVisible}
- />
+ <TabBodyErrorBoundary tabId={tab.id} tabKind={tab.kind} t={t}>
+ <Suspense fallback={null}>
+ <plugin.TabBody
+ state={hydratedState}
+ ctx={ctx}
+ active={active}
+ shellVisible={shellVisible}
+ />
+ </Suspense>
+ </TabBodyErrorBoundary>
) : (
<PlaceholderBody tab={tab} t={t} />
)}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
index 4caed8d766..75775be044 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
@@ -40,6 +40,8 @@ import {
import type { LucideIcon } from 'lucide-react';
import type { TFunction } from 'i18next';
import { useTranslation } from 'react-i18next';
+import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';
+import { RightSidebarToggle } from '@/components/layout/RightSidebarToggle';
import { SortableList } from '@/components/sidebar/SortableList';
import { useReducedMotion } from '@/hooks/useReducedMotion';
import { cn } from '@/lib/utils';
@@ -71,6 +73,10 @@ interface TabBarProps {
onMaximize?: () => void;
/** 关闭整个 RSB 的 toggle(仅 showWindowControls=true 时使用)。 */
onCloseSidebar?: () => void;
+ /** 固定显示 / 聚焦入口;与关闭按钮分离,点击已展开侧栏时为 no-op。 */
+ onShowSidebar?: () => void;
+ /** 当前面板所在侧,用于固定入口图标方向。 */
+ panelSide?: 'left' | 'right';
/** maximize 当前态(Phase 6)— 用来切换按钮图标 Maximize2 ↔ Minimize2,
* 让用户视觉上知道按一下是"退出最大化"。 */
isMaximized?: boolean;
@@ -199,6 +205,8 @@ export function TabBar({
showWindowControls,
onMaximize,
onCloseSidebar,
+ onShowSidebar,
+ panelSide = 'right',
isMaximized,
onCloseOthers,
onCloseAll,
@@ -269,6 +277,14 @@ export function TabBar({
<PanelRightClose size={15} />
</ChromeIconButton>
)}
+ {onShowSidebar && (
+ <RightSidebarToggle
+ action="show"
+ collapsed={false}
+ onToggle={onShowSidebar}
+ side={panelSide}
+ />
+ )}
</div>
)}
</div>
@@ -640,15 +656,3 @@ function TabPill({
</div>
);
}
-
-function ChromeIconButton({ children, ...rest }: React.ButtonHTMLAttributes<HTMLButtonElement>) {
- return (
- <button
- type="button"
- {...rest}
- 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)]"
- >
- {children}
- </button>
- );
-}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx
new file mode 100644
index 0000000000..43843c947d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx
@@ -0,0 +1,87 @@
+import { Component, type ErrorInfo, type ReactNode } from 'react';
+import { RotateCcw, TriangleAlert } from 'lucide-react';
+import type { TFunction } from 'i18next';
+
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('right-sidebar.tab-error-boundary');
+
+interface Props {
+ children: ReactNode;
+ tabId: string;
+ tabKind: string;
+ t: TFunction;
+}
+
+interface State {
+ error: Error | null;
+ retryKey: number;
+}
+
+/** Isolate one sidebar plugin from the rest of the detached window. */
+export class TabBodyErrorBoundary extends Component<Props, State> {
+ state: State = { error: null, retryKey: 0 };
+
+ static getDerivedStateFromError(error: Error): Partial<State> {
+ return { error };
+ }
+
+ componentDidCatch(error: Error, info: ErrorInfo): void {
+ log.error('sidebar tab render crashed', {
+ tabId: this.props.tabId,
+ tabKind: this.props.tabKind,
+ message: error.message,
+ stack: error.stack,
+ componentStack: info.componentStack ?? undefined,
+ });
+ }
+
+ componentDidUpdate(previousProps: Props): void {
+ if (previousProps.tabId !== this.props.tabId || previousProps.tabKind !== this.props.tabKind) {
+ if (this.state.error !== null) {
+ this.setState({ error: null, retryKey: this.state.retryKey + 1 });
+ }
+ }
+ }
+
+ private retry = (): void => {
+ this.setState((state) => ({ error: null, retryKey: state.retryKey + 1 }));
+ };
+
+ render(): ReactNode {
+ if (this.state.error !== null) {
+ const { t } = this.props;
+ return (
+ <div className="flex min-h-0 flex-1 items-center justify-center bg-content-area px-4">
+ <div className="flex w-full max-w-sm flex-col items-center gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface)] px-5 py-6 text-center">
+ <span className="flex h-8 w-8 items-center justify-center rounded-full bg-[var(--surface-chip)] text-[var(--text-secondary)]">
+ <TriangleAlert size={16} aria-hidden="true" />
+ </span>
+ <div>
+ <h2 className="text-13 font-medium text-[var(--text-primary)]">
+ {t('rightSidebar.panelError.title')}
+ </h2>
+ <p className="mt-1 text-12 leading-relaxed text-[var(--text-secondary)]">
+ {t('rightSidebar.panelError.description')}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={this.retry}
+ className="inline-flex h-7 items-center gap-1.5 rounded-full px-3 text-12 font-medium transition-opacity hover:opacity-90"
+ style={{
+ backgroundColor: 'var(--accent-cta-bg)',
+ color: 'var(--accent-pure-cta-fg)',
+ }}
+ >
+ <RotateCcw size={13} aria-hidden="true" />
+ {t('rightSidebar.panelError.reload')}
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ return <div key={this.state.retryKey} className="flex min-h-0 flex-1 flex-col">{this.props.children}</div>;
+ }
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
index 2227bbf203..10adbb8478 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
@@ -1,9 +1,10 @@
// @vitest-environment jsdom
-import { createElement } from 'react';
+import { createElement, useEffect } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import type { AppShortcutOverrides } from '../../../../shared/appShortcuts';
+import type { LucideIcon } from 'lucide-react';
vi.mock('react-i18next', () => ({
initReactI18next: { type: '3rdParty', init: vi.fn() },
@@ -31,6 +32,7 @@ vi.mock('../lib/rsbBrowserBridge', async () => {
});
import { RightSidebarShell } from '../RightSidebarShell';
+import { registerTabKind, unregisterTabKind } from '../registry';
import { _resetRsbBrowserBridgeForTests } from '../lib/rsbBrowserBridge';
import { _resetPopupRouterForTests } from '../lib/popupRouter';
import { _resetNativePopupTabsForTests } from '../lib/nativePopupTabs';
@@ -40,7 +42,7 @@ import {
type SidebarVisibilityRequest,
type SidebarVisibilityRequestOptions,
} from '../lib/sidebarCommands';
-import { _resetStore, closeTab, getBucket } from '../store';
+import { _resetStore, closeTab, getBucket, setActiveTab } from '../store';
import { writePanelCollapsed } from '@/layout/collapsePrefs';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
@@ -264,6 +266,116 @@ describe('RightSidebarShell empty state', () => {
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
});
+ it('mounts only the active body first, then idle-mounts and keeps the rest alive', async () => {
+ const idleCallbacks: IdleRequestCallback[] = [];
+ Object.defineProperty(window, 'requestIdleCallback', {
+ configurable: true,
+ value: vi.fn((callback: IdleRequestCallback) => {
+ idleCallbacks.push(callback);
+ return idleCallbacks.length;
+ }),
+ });
+ Object.defineProperty(window, 'cancelIdleCallback', {
+ configurable: true,
+ value: vi.fn(),
+ });
+ const mountA = vi.fn();
+ const unmountA = vi.fn();
+ const mountB = vi.fn();
+ const unmountB = vi.fn();
+ const BodyA = () => {
+ useEffect(() => {
+ mountA();
+ return unmountA;
+ }, []);
+ return createElement('div', { 'data-testid': 'body-a' });
+ };
+ const BodyB = () => {
+ useEffect(() => {
+ mountB();
+ return unmountB;
+ }, []);
+ return createElement('div', { 'data-testid': 'body-b' });
+ };
+ const Pill = () => createElement('span');
+ const Icon = (() => null) as unknown as LucideIcon;
+ registerTabKind({
+ kind: 'file-browser',
+ menu: {
+ kind: 'file-browser',
+ labelKey: 'rightSidebar.tabs.kinds.fileBrowser',
+ icon: Icon,
+ order: 1,
+ enabled: true,
+ },
+ TabPillTitle: Pill,
+ TabBody: BodyA,
+ defaultState: () => ({}),
+ });
+ registerTabKind({
+ kind: 'terminal',
+ menu: {
+ kind: 'terminal',
+ labelKey: 'rightSidebar.tabs.kinds.terminal',
+ icon: Icon,
+ order: 2,
+ enabled: true,
+ },
+ TabPillTitle: Pill,
+ TabBody: BodyB,
+ defaultState: () => ({}),
+ });
+ tabsIpc.list.mockResolvedValueOnce({
+ tabs: [
+ { id: 'tab-a', kind: 'file-browser', state: null },
+ { id: 'tab-b', kind: 'terminal', state: null },
+ ],
+ activeTabId: 'tab-a',
+ });
+
+ try {
+ const view = render(
+ createElement(RightSidebarShell, {
+ sessionId: 's1',
+ workdir: '/tmp/repo',
+ remoteHostId: null,
+ isMac: true,
+ }),
+ );
+
+ await waitFor(() => expect(screen.getByTestId('body-a')).toBeTruthy());
+ expect(screen.queryByTestId('body-b')).toBeNull();
+ expect(idleCallbacks).toHaveLength(1);
+
+ act(() => {
+ idleCallbacks.shift()?.({
+ didTimeout: false,
+ timeRemaining: () => 50,
+ });
+ });
+
+ await waitFor(() => expect(screen.getByTestId('body-b')).toBeTruthy());
+ expect(screen.getByTestId('body-a')).toBeTruthy();
+
+ await act(async () => {
+ await setActiveTab('s1', 'tab-b');
+ });
+
+ expect(screen.getByTestId('body-a')).toBeTruthy();
+ expect(screen.getByTestId('body-b')).toBeTruthy();
+ expect(mountA).toHaveBeenCalledOnce();
+ expect(mountB).toHaveBeenCalledOnce();
+ expect(unmountA).not.toHaveBeenCalled();
+ expect(unmountB).not.toHaveBeenCalled();
+ view.unmount();
+ } finally {
+ unregisterTabKind('file-browser');
+ unregisterTabKind('terminal');
+ delete (window as unknown as { requestIdleCallback?: unknown }).requestIdleCallback;
+ delete (window as unknown as { cancelIdleCallback?: unknown }).cancelIdleCallback;
+ }
+ });
+
it('cycles right sidebar tabs in strip order and wraps around', async () => {
tabsIpc.list.mockResolvedValueOnce({
tabs: [
@@ -524,12 +636,11 @@ describe('RightSidebarShell empty state', () => {
});
});
- it('renders detach/maximize in the topbar when panel is docked left (mac M2), spacer when right or maximized', async () => {
- // 贴左:窗口右上浮层只剩折叠 toggle(恒钉窗口右上角,2026-07-09 Lizi 口径),
- // detach / maximize 是面板自属控件,必须由 Shell 顶栏右端自渲染,否则面板
- // 控件全体消失(mac 实测 bug);折叠 toggle 不下沉进面板。
+ it('keeps mac panel actions in the panel topbar without reserving a hidden show trigger', async () => {
+ // 展开态没有固定唤起入口;detach / maximize / 收起始终属于面板自身。
const onDetach = vi.fn();
const onMaximize = vi.fn();
+ const onCloseSidebar = vi.fn();
const { unmount } = render(
createElement(RightSidebarShell, {
sessionId: 's1',
@@ -540,6 +651,7 @@ describe('RightSidebarShell empty state', () => {
panelSide: 'left',
onDetach,
onMaximize,
+ onCloseSidebar,
}),
);
@@ -550,11 +662,12 @@ describe('RightSidebarShell empty state', () => {
expect(onDetach).toHaveBeenCalledOnce();
screen.getByRole('button', { name: 'rightSidebar.tabs.controls.maximizeAria' }).click();
expect(onMaximize).toHaveBeenCalledOnce();
- // 折叠 toggle 不在面板顶栏(恒在 MainLayout 窗口右上浮层)。
- expect(screen.queryByRole('button', { name: 'contentHeader.collapsePanel' })).toBeNull();
+ screen.getByRole('button', { name: 'contentHeader.collapsePanel' }).click();
+ expect(onCloseSidebar).toHaveBeenCalledOnce();
+ expect(screen.queryByTestId('right-sidebar-fixed-trigger-spacer')).toBeNull();
unmount();
- // 贴左 + maximize 撑满:面板成为最右 pane,浮层接管三按钮,Shell 回落 spacer。
+ // maximize 后面板占据最右边缘,仍保留自属控件,但不为隐藏的唤起入口留空。
const { unmount: unmountMax } = render(
createElement(RightSidebarShell, {
sessionId: 's1',
@@ -566,13 +679,15 @@ describe('RightSidebarShell empty state', () => {
isMaximized: true,
onDetach,
onMaximize,
+ onCloseSidebar,
}),
);
await waitFor(() => expect(screen.getByText('rightSidebar.tabs.empty.title')).toBeTruthy());
- expect(screen.queryByTestId('right-sidebar-topbar-actions')).toBeNull();
+ expect(screen.getByTestId('right-sidebar-topbar-actions')).toBeTruthy();
+ expect(screen.queryByTestId('right-sidebar-fixed-trigger-spacer')).toBeNull();
unmountMax();
- // 贴右(默认):按钮在 MainLayout 浮层,Shell 只渲染让位 spacer。
+ // 贴右时同样保留面板自属控件,不显示无效唤起入口,也不留空。
render(
createElement(RightSidebarShell, {
sessionId: 's1',
@@ -582,17 +697,19 @@ describe('RightSidebarShell empty state', () => {
unifiedTopbar: true,
onDetach,
onMaximize,
+ onCloseSidebar,
}),
);
await waitFor(() => expect(screen.getByText('rightSidebar.tabs.empty.title')).toBeTruthy());
- expect(screen.queryByTestId('right-sidebar-topbar-actions')).toBeNull();
- expect(
- screen.queryByRole('button', { name: 'rightSidebar.tabs.controls.detachAria' }),
- ).toBeNull();
+ expect(screen.getByTestId('right-sidebar-topbar-actions')).toBeTruthy();
+ expect(screen.queryByTestId('right-sidebar-fixed-trigger-spacer')).toBeNull();
+ expect(screen.getByRole('button', { name: 'rightSidebar.tabs.controls.detachAria' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'contentHeader.collapsePanel' })).toBeTruthy();
});
it('keeps the existing 36px TabBar host on Windows', async () => {
const onCloseSidebar = vi.fn();
+ const onShowSidebar = vi.fn();
render(
createElement(RightSidebarShell, {
sessionId: 's1',
@@ -600,6 +717,7 @@ describe('RightSidebarShell empty state', () => {
remoteHostId: null,
isMac: false,
onCloseSidebar,
+ onShowSidebar,
onMaximize: vi.fn(),
onDetach: vi.fn(),
}),
@@ -618,6 +736,34 @@ describe('RightSidebarShell empty state', () => {
});
collapseButton.click();
expect(onCloseSidebar).toHaveBeenCalledOnce();
+ const showButton = screen.getByRole('button', {
+ name: 'rightSidebar.tabs.controls.showAria',
+ });
+ showButton.click();
+ expect(onShowSidebar).toHaveBeenCalledOnce();
+ expect(showButton.getAttribute('aria-expanded')).toBe('true');
+ });
+
+ it('does not render the fixed show action while the Windows sidebar is already expanded', async () => {
+ render(
+ createElement(RightSidebarShell, {
+ sessionId: 's1',
+ workdir: '/tmp/repo',
+ remoteHostId: null,
+ isMac: false,
+ onCloseSidebar: vi.fn(),
+ onMaximize: vi.fn(),
+ onDetach: vi.fn(),
+ }),
+ );
+
+ await waitFor(() => expect(screen.getByText('rightSidebar.tabs.empty.title')).toBeTruthy());
+ expect(
+ screen.queryByRole('button', { name: 'rightSidebar.tabs.controls.showAria' }),
+ ).toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'rightSidebar.tabs.controls.closeAria' }),
+ ).toBeTruthy();
});
it('keeps the legacy TabBar without window controls for the detached mac window (no unifiedTopbar)', async () => {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBodyErrorBoundary.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBodyErrorBoundary.test.tsx
new file mode 100644
index 0000000000..71130e1f2c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/TabBodyErrorBoundary.test.tsx
@@ -0,0 +1,68 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { useState } from 'react';
+import type { TFunction } from 'i18next';
+
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({
+ error: vi.fn(),
+ }),
+}));
+
+import { TabBodyErrorBoundary } from '../TabBodyErrorBoundary';
+
+afterEach(() => cleanup());
+
+const t = ((key: string) => key) as TFunction;
+
+function ThrowingBody({ shouldThrow }: { shouldThrow: boolean }) {
+ if (shouldThrow) throw new Error('bridge missing');
+ return <div>panel content</div>;
+}
+
+describe('TabBodyErrorBoundary', () => {
+ it('isolates a crashed tab and shows a localized reload action', () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ render(
+ <div>
+ <TabBodyErrorBoundary tabId="broken" tabKind="web-browser" t={t}>
+ <ThrowingBody shouldThrow />
+ </TabBodyErrorBoundary>
+ <TabBodyErrorBoundary tabId="healthy" tabKind="terminal" t={t}>
+ <div>healthy panel</div>
+ </TabBodyErrorBoundary>
+ </div>,
+ );
+
+ expect(screen.getByText('rightSidebar.panelError.title')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'rightSidebar.panelError.reload' })).toBeTruthy();
+ expect(screen.getByText('healthy panel')).toBeTruthy();
+ errorSpy.mockRestore();
+ });
+
+ it('remounts the failed tab after retry', () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ function Harness() {
+ const [shouldThrow, setShouldThrow] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setShouldThrow(false)}>
+ make healthy
+ </button>
+ <TabBodyErrorBoundary tabId="broken" tabKind="review" t={t}>
+ <ThrowingBody shouldThrow={shouldThrow} />
+ </TabBodyErrorBoundary>
+ </>
+ );
+ }
+
+ render(<Harness />);
+ expect(screen.getByText('rightSidebar.panelError.title')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'make healthy' }));
+ fireEvent.click(screen.getByRole('button', { name: 'rightSidebar.panelError.reload' }));
+ expect(screen.getByText('panel content')).toBeTruthy();
+ expect(screen.queryByText('rightSidebar.panelError.title')).toBeNull();
+ errorSpy.mockRestore();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx
index b4f169ce92..c7465e22df 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx
@@ -9,12 +9,16 @@
* - 注册:模块顶层 import-side-effect,由 plugins/index.ts 汇总。
*/
+import { lazy } from 'react';
import { ListTodo } from 'lucide-react';
import type { TFunction } from 'i18next';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
-import { BackgroundTasksBody } from './BackgroundTasksBody';
+
+const BackgroundTasksBody = lazy(() =>
+ import('./BackgroundTasksBody').then((module) => ({ default: module.BackgroundTasksBody })),
+);
export interface BackgroundTasksState {
/** 一次性详情定位请求:对应 workflow 任务时直接进详情,消费后清空。 */
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx
index 09e0adc2eb..52af0f66ad 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx
@@ -17,12 +17,16 @@
* `./plugins` 触发本文件执行。
*/
+import { lazy } from 'react';
import { FolderTree } from 'lucide-react';
import type { TFunction } from 'i18next';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
-import { FileBrowserBody } from './FileBrowserBody';
+
+const FileBrowserBody = lazy(() =>
+ import('./FileBrowserBody').then((module) => ({ default: module.FileBrowserBody })),
+);
/** plugin state shape — 跟 store 序列化结构一致,默认 JSON identity 即可 hydrate。 */
export interface FileBrowserState {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx
index 6f9f0d497d..bf5fd796f1 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx
@@ -3,12 +3,16 @@
* Apple tooling remains in main; this renderer plugin only consumes typed IPC.
*/
+import { lazy } from 'react';
import { Smartphone } from 'lucide-react';
import type { TFunction } from 'i18next';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
-import { IOSSimulatorTabBody } from './IOSSimulatorTabBody';
+
+const IOSSimulatorTabBody = lazy(() =>
+ import('./IOSSimulatorTabBody').then((module) => ({ default: module.IOSSimulatorTabBody })),
+);
export interface IOSSimulatorTabState {
instanceId: string | null;
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx
new file mode 100644
index 0000000000..81ba9e2938
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx
@@ -0,0 +1,34 @@
+import { UsersRound } from 'lucide-react';
+
+import { AttentionDot } from '@/components/sidebar/AttentionDot';
+import { useWorkerProjection } from '@/features/cc-agent/hooks/workerProjectionStore';
+import { useWorkerAttentionSnapshot } from '@/features/cc-agent/lib/workerAttentionStore';
+
+export function OrcaWorkersAttentionIcon({
+ sessionId,
+ active,
+}: {
+ sessionId: string | null;
+ active: boolean;
+}) {
+ const attention = useWorkerAttentionSnapshot();
+ const projection = useWorkerProjection(sessionId ?? '');
+ const hasAttention = Boolean(
+ sessionId && projection.workers.some((worker) => attention.has(worker.workerId)),
+ );
+
+ return (
+ <span className="relative inline-flex">
+ <UsersRound size={13} />
+ {!active && hasAttention && (
+ <span
+ aria-label="unread"
+ className="absolute -right-[3px] -top-[3px] inline-flex rounded-full"
+ style={{ boxShadow: '0 0 0 1.5px var(--surface)' }}
+ >
+ <AttentionDot size={6} />
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx
new file mode 100644
index 0000000000..9d402b424e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx
@@ -0,0 +1,140 @@
+import { useCallback, useEffect, useMemo } from 'react';
+import { MemoryRouter, useNavigate } from 'react-router-dom';
+
+import { useCCSessions } from '@/hooks/useCCSessions';
+import { useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';
+import { OrcaWorkerPanel } from '@/features/cc-agent/OrcaWorkerPanel';
+import { useOrcaWorkerAttentionByLeadIds } from '@/features/cc-agent/hooks/useOrcaWorkerAttentionWatcher';
+import { useStopOrcaCollabWithoutNavigation } from '@/features/cc-agent/hooks/useStopOrcaCollab';
+import {
+ revalidateActiveWorkerSettings,
+ revalidateActiveWorkersProjection,
+ useWorkerProjectionOwner,
+} from '@/features/cc-agent/hooks/workerProjectionStore';
+import { mergeSessionSources } from '@/features/cc-agent/lib/mergeSessionSources';
+import { useDocumentVisible, useWindowVisible } from '@/hooks/useWindowVisible';
+import { isSidebarWindow } from '@/lib/sidebarWindow';
+import { createLogger } from '@/lib/logger';
+import { SidebarHostSessionProvider } from '../../lib/sidebarHostSession';
+import type { TabKindBodyProps } from '../../types';
+import {
+ clearOrcaWorkersSelectionIntent,
+ consumeOrcaWorkersFocusHint,
+ consumeOrcaWorkersSearchJump,
+ type OrcaWorkersState,
+} from './actions';
+import { getOrcaWorkersCloseDecision } from './closeDecision';
+
+const log = createLogger('OrcaWorkersPlugin');
+
+function RoutedOrcaWorkerPanel(
+ props: Omit<React.ComponentProps<typeof OrcaWorkerPanel>, 'onOpenSettings'>,
+) {
+ const navigate = useNavigate();
+ return (
+ <OrcaWorkerPanel
+ {...props}
+ onOpenSettings={() => navigate('/settings?section=collaboration')}
+ />
+ );
+}
+
+export function OrcaWorkersTabBody({
+ state,
+ ctx,
+ active,
+ shellVisible = true,
+}: {
+ state: OrcaWorkersState;
+ ctx: TabKindBodyProps<OrcaWorkersState>['ctx'];
+ active?: boolean;
+ shellVisible?: boolean;
+}) {
+ useWorkerProjectionOwner(ctx.sessionId);
+ const windowVisible = useWindowVisible(Boolean(active && shellVisible));
+ const documentVisible = useDocumentVisible(Boolean(active && shellVisible));
+ const viewVisible = Boolean(active && shellVisible && windowVisible);
+ const chatRealtime = Boolean(active && shellVisible && documentVisible);
+ const detachedLeadSessionIds = useMemo(
+ () => (isSidebarWindow() ? [ctx.sessionId] : []),
+ [ctx.sessionId],
+ );
+ useOrcaWorkerAttentionByLeadIds(
+ detachedLeadSessionIds,
+ viewVisible ? ctx.sessionId : undefined,
+ );
+ const { sessions, isLoading } = useCCSessions();
+ const remoteSessions = useRemoteProjectSessions();
+ const leadSession =
+ mergeSessionSources(sessions, remoteSessions).find(
+ (candidate) => candidate.id === ctx.sessionId,
+ ) ?? null;
+ const closeDecision = getOrcaWorkersCloseDecision({ isLoading, leadSession });
+ const { requestStop } = useStopOrcaCollabWithoutNavigation({
+ leadSessionId: ctx.sessionId,
+ });
+ const closeHandler = useCallback(() => {
+ if (closeDecision === 'close') return true;
+ if (closeDecision === 'stop-team') return requestStop();
+ return false;
+ }, [closeDecision, requestStop]);
+
+ useEffect(() => ctx.setCloseInterceptor(closeHandler), [closeHandler, ctx]);
+ useEffect(() => {
+ if (!active || !shellVisible || !windowVisible) return;
+ void revalidateActiveWorkersProjection(ctx.sessionId);
+ void revalidateActiveWorkerSettings(ctx.sessionId);
+ }, [active, ctx.sessionId, shellVisible, windowVisible]);
+
+ const handleFocusWorkerSessionIdConsumed = useCallback(
+ (revision: number) => {
+ void consumeOrcaWorkersFocusHint(ctx.sessionId, ctx.tabId, revision).catch((err) => {
+ log.warn('consume focus worker hint failed', err);
+ });
+ },
+ [ctx],
+ );
+ const handleSearchJumpConsumed = useCallback(() => {
+ void consumeOrcaWorkersSearchJump(
+ ctx.sessionId,
+ ctx.tabId,
+ state.focusWorkerHintRevision ?? 0,
+ ).catch((err) => {
+ log.warn('consume worker search jump failed', err);
+ });
+ }, [ctx, state.focusWorkerHintRevision]);
+ const handleSelectionIntentCleared = useCallback(
+ (revision: number) => {
+ void clearOrcaWorkersSelectionIntent(ctx.sessionId, ctx.tabId, revision).catch((err) => {
+ log.warn('clear worker selection intent failed', err);
+ });
+ },
+ [ctx],
+ );
+
+ const workerPanelProps = {
+ leadSessionId: ctx.sessionId,
+ deviceId: leadSession?.deviceLinkDeviceId,
+ sshRemote: !!leadSession?.remoteHostId,
+ viewVisible,
+ chatRealtime,
+ focusWorkerSessionId: state.focusWorkerSessionId,
+ focusWorkerHintRevision: state.focusWorkerHintRevision,
+ searchJump: state.searchJump,
+ onFocusWorkerSessionIdConsumed: handleFocusWorkerSessionIdConsumed,
+ onSelectionIntentCleared: handleSelectionIntentCleared,
+ onSearchJumpConsumed: handleSearchJumpConsumed,
+ };
+
+ return (
+ <SidebarHostSessionProvider sessionId={ctx.sessionId}>
+ {isSidebarWindow() ? (
+ <MemoryRouter initialEntries={[`/cc-agent/${ctx.sessionId}`]}>
+ <OrcaWorkerPanel {...workerPanelProps} />
+ </MemoryRouter>
+ ) : (
+ <RoutedOrcaWorkerPanel {...workerPanelProps} />
+ )}
+ </SidebarHostSessionProvider>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx
index f578352c8c..c2faba4020 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx
@@ -6,43 +6,28 @@
* disableOrca;body 未挂载时 onBeforeClose fail-closed,拒绝误关协同。
*/
-import { useCallback, useEffect, useMemo } from 'react';
+import { lazy, Suspense } from 'react';
import { UsersRound } from 'lucide-react';
import type { TFunction } from 'i18next';
-import { AttentionDot } from '@/components/sidebar/AttentionDot';
-import { useCCSessions } from '@/hooks/useCCSessions';
-import { useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';
-import { OrcaWorkerPanel } from '@/features/cc-agent/OrcaWorkerPanel';
-import { useOrcaWorkerAttentionByLeadIds } from '@/features/cc-agent/hooks/useOrcaWorkerAttentionWatcher';
-import { useStopOrcaCollab } from '@/features/cc-agent/hooks/useStopOrcaCollab';
-import {
- revalidateActiveWorkerSettings,
- revalidateActiveWorkersProjection,
- useWorkerProjection,
- useWorkerProjectionOwner,
-} from '@/features/cc-agent/hooks/workerProjectionStore';
-import { mergeSessionSources } from '@/features/cc-agent/lib/mergeSessionSources';
-import { useWorkerAttentionSnapshot } from '@/features/cc-agent/lib/workerAttentionStore';
-import { useDocumentVisible, useWindowVisible } from '@/hooks/useWindowVisible';
import { isOrcaLeadSession } from '@/lib/orcaSessionIdentity';
-import { isSidebarWindow } from '@/lib/sidebarWindow';
import * as sessionService from '@/lib/sessionService';
-import { createLogger } from '@/lib/logger';
-import { SidebarHostSessionProvider } from '../../lib/sidebarHostSession';
import { registerTabKind } from '../../registry';
import { hasTabCloseInterceptor } from '../../store';
import type { TabKindPlugin } from '../../types';
import {
- clearOrcaWorkersSelectionIntent,
- consumeOrcaWorkersFocusHint,
- consumeOrcaWorkersSearchJump,
hydrateOrcaWorkersState,
type OrcaWorkersState,
} from './actions';
-import { getOrcaWorkersCloseDecision } from './closeDecision';
-const log = createLogger('OrcaWorkersPlugin');
+const OrcaWorkersTabBody = lazy(() =>
+ import('./OrcaWorkersTabBody').then((module) => ({ default: module.OrcaWorkersTabBody })),
+);
+const OrcaWorkersAttentionIcon = lazy(() =>
+ import('./OrcaWorkersAttentionIcon').then((module) => ({
+ default: module.OrcaWorkersAttentionIcon,
+ })),
+);
function OrcaWorkersTabPillTitle({ t }: { state: OrcaWorkersState; t: TFunction }) {
return <>{t('rightSidebar.tabs.kinds.collaboration')}</>;
@@ -57,126 +42,9 @@ function OrcaWorkersTabPillIcon({
active: boolean;
}) {
return (
- <span className="relative inline-flex">
- <UsersRound size={13} />
- {!active && sessionId && <OrcaWorkersAttentionDot sessionId={sessionId} />}
- </span>
- );
-}
-
-function OrcaWorkersAttentionDot({ sessionId }: { sessionId: string }) {
- const attention = useWorkerAttentionSnapshot();
- const projection = useWorkerProjection(sessionId);
- const hasAttention = projection.workers.some((worker) => attention.has(worker.workerId));
- if (!hasAttention) return null;
-
- return (
- <span
- aria-label="unread"
- className="absolute -right-[3px] -top-[3px] inline-flex rounded-full"
- style={{ boxShadow: '0 0 0 1.5px var(--surface)' }}
- >
- <AttentionDot size={6} />
- </span>
- );
-}
-
-function OrcaWorkersTabBody({
- state,
- ctx,
- active,
- shellVisible = true,
-}: {
- state: OrcaWorkersState;
- ctx: Parameters<TabKindPlugin<OrcaWorkersState>['TabBody']>[0]['ctx'];
- active?: boolean;
- shellVisible?: boolean;
-}) {
- useWorkerProjectionOwner(ctx.sessionId);
- const windowVisible = useWindowVisible(Boolean(active && shellVisible));
- const documentVisible = useDocumentVisible(Boolean(active && shellVisible));
- const viewVisible = Boolean(active && shellVisible && windowVisible);
- const chatRealtime = Boolean(active && shellVisible && documentVisible);
- const detachedLeadSessionIds = useMemo(
- () => (isSidebarWindow() ? [ctx.sessionId] : []),
- [ctx.sessionId],
- );
- useOrcaWorkerAttentionByLeadIds(
- detachedLeadSessionIds,
- viewVisible ? ctx.sessionId : undefined,
- );
- const { sessions, isLoading } = useCCSessions();
- const remoteSessions = useRemoteProjectSessions();
- const leadSession =
- mergeSessionSources(sessions, remoteSessions).find(
- (candidate) => candidate.id === ctx.sessionId,
- ) ?? null;
- const closeDecision = getOrcaWorkersCloseDecision({ isLoading, leadSession });
- const { requestStop } = useStopOrcaCollab({
- leadSessionId: ctx.sessionId,
- navigateOnSuccess: false,
- });
- const closeHandler = useCallback(() => {
- if (closeDecision === 'close') return true;
- if (closeDecision === 'stop-team') return requestStop();
- return false;
- }, [closeDecision, requestStop]);
-
- useEffect(() => ctx.setCloseInterceptor(closeHandler), [closeHandler, ctx]);
- useEffect(() => {
- if (!active || !shellVisible || !windowVisible) return;
- void revalidateActiveWorkersProjection(ctx.sessionId);
- void revalidateActiveWorkerSettings(ctx.sessionId);
- }, [active, ctx.sessionId, shellVisible, windowVisible]);
-
- const handleFocusWorkerSessionIdConsumed = useCallback(
- (revision: number) => {
- // 消费 string 只清 payload、不递增 revision;hook 因而保留刚建立的 pin。
- // 外部显式 null 会经 actions 递增 revision,mounted hook 才会立即清 pin。
- void consumeOrcaWorkersFocusHint(ctx.sessionId, ctx.tabId, revision).catch((err) => {
- log.warn('consume focus worker hint failed', err);
- });
- },
- [ctx],
- );
- const handleSearchJumpConsumed = useCallback(() => {
- void consumeOrcaWorkersSearchJump(
- ctx.sessionId,
- ctx.tabId,
- state.focusWorkerHintRevision ?? 0,
- ).catch((err) => {
- log.warn('consume worker search jump failed', err);
- });
- }, [ctx, state.focusWorkerHintRevision]);
- const handleSelectionIntentCleared = useCallback(
- (revision: number) => {
- void clearOrcaWorkersSelectionIntent(ctx.sessionId, ctx.tabId, revision).catch((err) => {
- log.warn('clear worker selection intent failed', err);
- });
- },
- [ctx],
- );
-
- return (
- // 内嵌 worker 流里的审查等入口据此把 RSB tab 开到 lead 的可见桶,
- // 而不是 worker 自己的(协同视图下不可见的)桶。
- <SidebarHostSessionProvider sessionId={ctx.sessionId}>
- <OrcaWorkerPanel
- leadSessionId={ctx.sessionId}
- deviceId={leadSession?.deviceLinkDeviceId}
- // SSH 远程 Lead:worker 创建面板按 SSH 口径过滤模型清单(与 main 侧
- // remote-worker guard 同规则,codex review R28)。
- sshRemote={!!leadSession?.remoteHostId}
- viewVisible={viewVisible}
- chatRealtime={chatRealtime}
- focusWorkerSessionId={state.focusWorkerSessionId}
- focusWorkerHintRevision={state.focusWorkerHintRevision}
- searchJump={state.searchJump}
- onFocusWorkerSessionIdConsumed={handleFocusWorkerSessionIdConsumed}
- onSelectionIntentCleared={handleSelectionIntentCleared}
- onSearchJumpConsumed={handleSearchJumpConsumed}
- />
- </SidebarHostSessionProvider>
+ <Suspense fallback={<UsersRound size={13} />}>
+ <OrcaWorkersAttentionIcon sessionId={sessionId} active={active} />
+ </Suspense>
);
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx
index c5895fb2c5..037ba6fec0 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx
@@ -5,14 +5,15 @@
* plugin,让数据库中已持久化的旧页签仍可原位恢复和关闭,但不再允许新建。
*/
+import { lazy } from 'react';
import { Activity } from 'lucide-react';
import type { TFunction } from 'i18next';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
-import { ResourceUsageBody } from './ResourceUsageBody';
-
-export { ResourceUsageBody };
+const ResourceUsageBody = lazy(() =>
+ import('./ResourceUsageBody').then((module) => ({ default: module.ResourceUsageBody })),
+);
export type ResourceUsageState = Record<never, never>;
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
index 34fc4fb234..f9d268ea44 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx
@@ -12,15 +12,19 @@
* 注册:模块顶层 import-side-effect。plugins/index.ts 把它 import 进来。
*/
+import { lazy } from 'react';
import { FileDiff } from 'lucide-react';
import type { TFunction } from 'i18next';
import { isSafeBranchBaseRef } from '../../../../../shared/reviewBranchRef';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
-import { ReviewTabBody } from './ReviewTabBody';
import type { DiffViewMode } from './DiffViewer/PlainUnifiedDiff';
+const ReviewTabBody = lazy(() =>
+ import('./ReviewTabBody').then((module) => ({ default: module.ReviewTabBody })),
+);
+
export interface ReviewState {
/** Programmatic exact-turn review target. Null keeps the normal Git-backed review surface. */
turnTarget: {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx
index c992014e24..6f0773676e 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx
@@ -1,12 +1,16 @@
/** Cindy-owned durable Subagent workspace tab. */
+import { lazy } from 'react';
import { Bot } from 'lucide-react';
import type { TFunction } from 'i18next';
import type { SubagentProvider } from '@cindy/maker-shared/subagent-workspace';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
-import { SubagentsBody } from './SubagentsBody';
+
+const SubagentsBody = lazy(() =>
+ import('./SubagentsBody').then((module) => ({ default: module.SubagentsBody })),
+);
export interface SubagentsState {
selectedRunId?: string | null;
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx
index 96a81956e9..4018980724 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx
@@ -15,13 +15,16 @@
* 注册:模块顶层 import-side-effect。plugins/index.ts 把它 import 进来。
*/
+import { lazy } from 'react';
import { Terminal as TerminalIcon } from 'lucide-react';
import type { TFunction } from 'i18next';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
-import { TerminalTabBody } from './TerminalTabBody';
-import { disposeXterm } from './lib/xtermPool';
+
+const TerminalTabBody = lazy(() =>
+ import('./TerminalTabBody').then((module) => ({ default: module.TerminalTabBody })),
+);
export interface TerminalState {
/** PTY 是否已在 main 端 spawn。每次 app 启动后 hydrate 强制设 false(PTY 死了) */
@@ -88,6 +91,7 @@ const plugin: TabKindPlugin<TerminalState> = {
} catch {
/* 已经 disposed / not found 都静默 */
}
+ const { disposeXterm } = await import('./lib/xtermPool');
disposeXterm(ctx.tabId);
},
};
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx
index 61fb21c11b..a48d455d92 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx
@@ -17,13 +17,16 @@
import { Globe, Volume2 } from 'lucide-react';
import type { TFunction } from 'i18next';
-import { useState } from 'react';
+import { lazy, useState } from 'react';
import { cn } from '@/lib/utils';
import { registerTabKind } from '../../registry';
import type { TabKindPlugin } from '../../types';
-import { BrowserTabBody } from './BrowserTabBody';
+
+const BrowserTabBody = lazy(() =>
+ import('./BrowserTabBody').then((module) => ({ default: module.BrowserTabBody })),
+);
/** plugin state shape —— 反序列化口径:JSON identity 即可恢复。 */
export interface WebBrowserState {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.ts
index 0f8873c74d..9b149eca9b 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts
@@ -7,7 +7,7 @@
* Plugin 解耦原则:壳子 / TabBar / 持久层永远不感知具体 kind,只通过 registry 拿 plugin 渲染。
*/
-import type { FC } from 'react';
+import type { ComponentType, FC, LazyExoticComponent } from 'react';
import type { LucideIcon } from 'lucide-react';
import type { TFunction } from 'i18next';
import type { TabCloseInterceptor } from './store';
@@ -101,6 +101,13 @@ export interface TabKindHostContext {
setCloseInterceptor: (interceptor: TabCloseInterceptor | null) => () => void;
}
+export interface TabKindBodyProps<TState = unknown> {
+ state: TState;
+ ctx: TabKindHostContext;
+ active?: boolean;
+ shellVisible?: boolean;
+}
+
export interface TabPillRenderProps<TState = unknown> {
state: TState;
sessionId: string | null;
@@ -131,12 +138,9 @@ export interface TabKindPlugin<TState = unknown> {
/** 真正的内容区。每个 tab 实例独立挂载,display:none 切换可见性,不卸载。
* `active` 标记当前是否是顶层激活 tab(用户在它上面)—— plugin 据此分支处理
* 焦点路由 / 媒体 mute / 性能节流等。可选,不读默认忽略。 */
- TabBody: FC<{
- state: TState;
- ctx: TabKindHostContext;
- active?: boolean;
- shellVisible?: boolean;
- }>;
+ TabBody:
+ | ComponentType<TabKindBodyProps<TState>>
+ | LazyExoticComponent<ComponentType<TabKindBodyProps<TState>>>;
/** 新建 tab 时的初始状态(对应「+」点击 / EmptyState 快捷入口创建)。 */
defaultState: () => TState;
/** 持久化前的序列化(可选);默认 JSON.stringify,plugin 可剔除非持久字段。 */
diff --git a/apps/desktop/src/renderer/ghost-panel-window-entry.tsx b/apps/desktop/src/renderer/ghost-panel-window-entry.tsx
new file mode 100644
index 0000000000..b554897ce9
--- /dev/null
+++ b/apps/desktop/src/renderer/ghost-panel-window-entry.tsx
@@ -0,0 +1,53 @@
+/**
+ * 插件面板独立子窗口的轻量渲染入口。
+ *
+ * 与 sidebar-window-entry.tsx 模式一致:只加载字体/CSS/主题/Provider,
+ * 直接渲染 GhostPanelWindowLayout,不经过 main-entry.tsx 的完整 App 链。
+ *
+ * 插件面板需要 ghost 管理基础设施(cindy-brain/ghostPanels/runtimeStates)
+ * 但不需要 maker 会话、登录、设置、语音等重量模块。
+ *
+ * 由 index.tsx 的 ?ghostPanelWindow=<id> 分发进入。
+ */
+
+import { createRoot } from 'react-dom/client';
+
+import '@fontsource-variable/inter';
+import '@fontsource-variable/jetbrains-mono';
+import 'harmonyos-sans-sc-webfont-splitted';
+
+import '@/i18n';
+import './themes/colors';
+import './styles/globals.css';
+
+import { TopLevelErrorBoundary } from './components/error/TopLevelErrorBoundary';
+import { GhostPanelWindowLayout } from './components/layout/GhostPanelWindowLayout';
+import { ConfirmDialogProvider } from './components/ui/confirm-dialog-provider';
+import { applyFontSettings, getInitialFontSettings } from './hooks/useFontSettings';
+import { bootstrapInitialLocale, LocaleProvider } from './hooks/useLocale';
+import { getInitialThemeVariant } from './hooks/useTheme';
+import { bootstrapLocalThemesSync } from './themes/local-themes';
+import { themeService } from './themes/theme-service';
+import {
+ ensureGhostPanelsRegistered,
+} from '@/cindy-brain/ghostPanels';
+
+document.documentElement.dataset.platform = window.electronAPI.platform;
+bootstrapLocalThemesSync();
+themeService.applyTheme(getInitialThemeVariant().theme);
+applyFontSettings(getInitialFontSettings());
+bootstrapInitialLocale();
+ensureGhostPanelsRegistered();
+
+const rootElement = document.getElementById('root');
+if (!rootElement) throw new Error('Missing #root element');
+
+createRoot(rootElement).render(
+ <TopLevelErrorBoundary>
+ <LocaleProvider>
+ <ConfirmDialogProvider>
+ <GhostPanelWindowLayout />
+ </ConfirmDialogProvider>
+ </LocaleProvider>
+ </TopLevelErrorBoundary>,
+);
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx
index 0d6fccbf60..f47a45626e 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx
+++ b/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx
@@ -249,12 +249,14 @@ describe('useCCAgentChat hidden chat snapshot freeze', () => {
});
it('keeps chat realtime separate from read visibility and does not remount MessageStream', () => {
- const pluginSource = rendererSource('features/right-sidebar/plugins/orca-workers/index.tsx');
+ const tabBodySource = rendererSource(
+ 'features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx',
+ );
const panelSource = rendererSource('features/cc-agent/OrcaWorkerPanel.tsx');
const sessionViewSource = rendererSource('features/cc-agent/CCAgentSessionView.tsx');
const messageStreamSource = rendererSource('components/chat/MessageStream.tsx');
- expect(pluginSource).toContain(
+ expect(tabBodySource).toContain(
'const chatRealtime = Boolean(active && shellVisible && documentVisible);',
);
expect(panelSource).toContain('viewVisible={viewVisible}');
diff --git a/apps/desktop/src/renderer/hooks/useLocale.ts b/apps/desktop/src/renderer/hooks/useLocale.ts
index b2f2fa6b63..2354df22a4 100644
--- a/apps/desktop/src/renderer/hooks/useLocale.ts
+++ b/apps/desktop/src/renderer/hooks/useLocale.ts
@@ -85,6 +85,19 @@ function applyLocale(loc: SupportedLocale): void {
syncApplicationMenuLocale(loc);
}
+/**
+ * Apply the persisted locale before the first React render.
+ *
+ * Lightweight windows render their error boundary outside the provider tree;
+ * initializing i18next synchronously here keeps even an early render failure
+ * in the user's selected language.
+ */
+export function bootstrapInitialLocale(): SupportedLocale {
+ const effectiveLocale = effectiveOf(readStoredLocale());
+ applyLocale(effectiveLocale);
+ return effectiveLocale;
+}
+
export function LocaleProvider({ children }: { children: ReactNode }) {
const [locale, setLocaleState] = useState<LocalePreference>(readStoredLocale);
const [effectiveLocale, setEffectiveLocale] = useState<SupportedLocale>(() =>
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 3c03950032..305bd5291d 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4466,12 +4466,12 @@
"ghostPanel": {
"disableConfirm": {
"title": "Disable \"{{name}}\"?",
- "body": "Closing this panel disables the whole plugin — its panel and capabilities will pause. You can re-enable it anytime from Plugins in the sidebar.",
+ "body": "Closing this panel disables the plugin and pauses its capabilities. You can re-enable it anytime from Plugins in the sidebar.",
"confirm": "Disable"
}
},
"ghostPanelWindow": {
- "mergeBack": "Merge back into main window",
+ "mergeBack": "Return to main window",
"unavailable": "This plugin panel is currently unavailable"
},
"ghostPanelBubble": {
@@ -4481,6 +4481,11 @@
},
"rightSidebar": {
"ariaLabel": "Right sidebar",
+ "panelError": {
+ "title": "Panel failed to load",
+ "description": "This panel is unavailable right now. Other panels are still available.",
+ "reload": "Reload panel"
+ },
"window": {
"title": "Sidebar",
"mergeBack": "Merge back to main window",
@@ -4511,6 +4516,7 @@
"ghostPanel": "Plugin panel"
},
"controls": {
+ "showAria": "Show sidebar",
"maximizeAria": "Maximize sidebar",
"restoreAria": "Restore sidebar",
"closeAria": "Close sidebar",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3c4e3d6d10..bc7fc9682a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4464,12 +4464,12 @@
"ghostPanel": {
"disableConfirm": {
"title": "「{{name}}」を無効にしますか?",
- "body": "このパネルを閉じるとプラグイン全体が無効になり、パネルと機能が停止します。サイドバーの「プラグイン」からいつでも再度有効にできます。",
+ "body": "このパネルを閉じるとプラグインが無効になり、機能が停止します。サイドバーの「プラグイン」からいつでも再度有効にできます。",
"confirm": "無効にする"
}
},
"ghostPanelWindow": {
- "mergeBack": "メインウィンドウに戻す",
+ "mergeBack": "メインウィンドウに戻る",
"unavailable": "このプラグインパネルは現在利用できません"
},
"ghostPanelBubble": {
@@ -4479,6 +4479,11 @@
},
"rightSidebar": {
"ariaLabel": "右サイドバー",
+ "panelError": {
+ "title": "パネルの読み込みに失敗しました",
+ "description": "このパネルは現在表示できません。他のパネルは引き続き利用できます。",
+ "reload": "パネルを再読み込み"
+ },
"window": {
"title": "サイドバー",
"mergeBack": "メインウィンドウに戻す",
@@ -4509,6 +4514,7 @@
"ghostPanel": "プラグインパネル"
},
"controls": {
+ "showAria": "サイドバーを表示",
"maximizeAria": "サイドバーを最大化",
"restoreAria": "最大化を解除",
"closeAria": "サイドバーを閉じる",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index c0556f9a25..90115d3d33 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4464,12 +4464,12 @@
"ghostPanel": {
"disableConfirm": {
"title": "\"{{name}}\" 플러그인을 비활성화할까요?",
- "body": "이 패널을 닫으면 플러그인 전체가 비활성화되어 패널과 기능이 중지됩니다. 사이드바의 '플러그인'에서 언제든지 다시 활성화할 수 있습니다.",
+ "body": "이 패널을 닫으면 플러그인이 비활성화되고 기능이 중지됩니다. 사이드바의 '플러그인'에서 언제든지 다시 활성화할 수 있습니다.",
"confirm": "비활성화"
}
},
"ghostPanelWindow": {
- "mergeBack": "메인 창으로 되돌리기",
+ "mergeBack": "메인 창으로 돌아가기",
"unavailable": "이 플러그인 패널은 현재 사용할 수 없습니다"
},
"ghostPanelBubble": {
@@ -4479,6 +4479,11 @@
},
"rightSidebar": {
"ariaLabel": "오른쪽 사이드바",
+ "panelError": {
+ "title": "패널을 불러오지 못했습니다",
+ "description": "이 패널은 지금 표시할 수 없습니다. 다른 패널은 계속 사용할 수 있습니다.",
+ "reload": "패널 다시 불러오기"
+ },
"window": {
"title": "사이드바",
"mergeBack": "메인 창으로 되돌리기",
@@ -4509,6 +4514,7 @@
"ghostPanel": "플러그인 패널"
},
"controls": {
+ "showAria": "사이드바 표시",
"maximizeAria": "사이드바 최대화",
"restoreAria": "최대화 해제",
"closeAria": "사이드바 닫기",
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 e231128b96..4f7c017dc8 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4460,12 +4460,12 @@
"ghostPanel": {
"disableConfirm": {
"title": "停用「{{name}}」?",
- "body": "关闭这个面板会停用整个插件,它的面板和能力都会暂停。之后可以随时在侧边栏「插件」里重新开启。",
+ "body": "关闭这个面板会停用插件并暂停其能力。你可以随时在侧边栏「插件」中重新启用。",
"confirm": "停用"
}
},
"ghostPanelWindow": {
- "mergeBack": "合并回主窗口",
+ "mergeBack": "返回主窗口",
"unavailable": "该插件面板当前不可用"
},
"ghostPanelBubble": {
@@ -4475,6 +4475,11 @@
},
"rightSidebar": {
"ariaLabel": "右侧边栏",
+ "panelError": {
+ "title": "面板加载失败",
+ "description": "这个面板暂时无法显示,其他面板仍可继续使用。",
+ "reload": "重新加载面板"
+ },
"window": {
"title": "侧边栏",
"mergeBack": "合并回主窗口",
@@ -4505,6 +4510,7 @@
"ghostPanel": "插件面板"
},
"controls": {
+ "showAria": "显示侧栏",
"maximizeAria": "最大化侧栏",
"restoreAria": "退出最大化",
"closeAria": "关闭侧栏",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index d4f2e53a1f..3d5b7f78e4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -4463,12 +4463,12 @@
"ghostPanel": {
"disableConfirm": {
"title": "停用「{{name}}」?",
- "body": "關閉這個面板會停用整個插件,它的面板和能力都會暫停。之後可以隨時在側邊欄「插件」裡重新開啟。",
+ "body": "關閉這個面板會停用插件並暫停其能力。你可以隨時在側邊欄「插件」中重新啟用。",
"confirm": "停用"
}
},
"ghostPanelWindow": {
- "mergeBack": "合併回主視窗",
+ "mergeBack": "返回主視窗",
"unavailable": "該插件面板當前不可用"
},
"ghostPanelBubble": {
@@ -4478,6 +4478,11 @@
},
"rightSidebar": {
"ariaLabel": "右側邊欄",
+ "panelError": {
+ "title": "面板載入失敗",
+ "description": "此面板目前無法顯示,其他面板仍可繼續使用。",
+ "reload": "重新載入面板"
+ },
"window": {
"title": "側邊欄",
"mergeBack": "合併回主視窗",
@@ -4508,6 +4513,7 @@
"ghostPanel": "插件面板"
},
"controls": {
+ "showAria": "顯示側欄",
"maximizeAria": "最大化側欄",
"restoreAria": "退出最大化",
"closeAria": "關閉側欄",
diff --git a/apps/desktop/src/renderer/index.tsx b/apps/desktop/src/renderer/index.tsx
index a649ea8048..8a0a26fe36 100644
--- a/apps/desktop/src/renderer/index.tsx
+++ b/apps/desktop/src/renderer/index.tsx
@@ -1,16 +1,23 @@
/**
* Renderer 模块图分发入口。
*
- * 资源用量窗口与主应用共用同一个受信任 HTML/origin,但从这里开始加载不同的模块图。
- * 判断必须发生在任何主应用静态依赖之前,否则 ESM 会先执行语音、诊断和设置初始化。
+ * 资源用量窗口、右侧栏独立子窗口与主应用共用同一个受信任 HTML/origin,
+ * 但从这里开始加载不同的模块图。判断必须发生在任何主应用静态依赖之前,
+ * 否则 ESM 会先执行语音、诊断和设置初始化。
*/
-const isResourceUsageWindow =
- new URLSearchParams(window.location.search).get('resourceUsageWindow') === '1';
+const urlParams = new URLSearchParams(window.location.search);
+const isResourceUsageWindow = urlParams.get('resourceUsageWindow') === '1';
+const isSidebarWindow = urlParams.get('sidebarWindow') === '1';
+const ghostPanelWindowId = urlParams.get('ghostPanelWindow');
void (isResourceUsageWindow
? import('./resource-usage-entry')
- : import('./main-entry')
+ : isSidebarWindow
+ ? import('./sidebar-window-entry')
+ : ghostPanelWindowId
+ ? import('./ghost-panel-window-entry')
+ : import('./main-entry')
).catch((error: unknown) => {
// 入口加载失败发生在 React boundary 之前,仍通过统一 renderer logger 落盘。
window.electronAPI?.logToMain?.(
diff --git a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts
index 4c10098ccc..2c6cd7f4d4 100644
--- a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts
@@ -137,3 +137,20 @@ describe('ghostPanelBubbleState · 变化信号(引用替换)', () => {
expect(getGhostPanelBubbleState()).toBe(after);
});
});
+
+describe('ghostPanelBubbleState · 跨独立窗口同步', () => {
+ it('另一个 BrowserWindow 写入气泡状态后刷新本窗口镜像', () => {
+ // 首次读取会惰性注册 storage listener。
+ getGhostPanelBubbleState();
+
+ window.dispatchEvent(
+ new StorageEvent('storage', {
+ key: 'xdt:ghostPanelBubble:v1',
+ storageArea: window.localStorage,
+ newValue: JSON.stringify({ a: { minimized: true } }),
+ }),
+ );
+
+ expect(getGhostPanelBubbleState().a).toEqual({ minimized: true });
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts b/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts
index 1c7a7df552..60271123c9 100644
--- a/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts
+++ b/apps/desktop/src/renderer/lib/ghostPanelBubbleState.ts
@@ -31,6 +31,7 @@ export type GhostPanelBubbleMap = Record<string, GhostPanelBubbleEntry>;
let cache: GhostPanelBubbleMap | null = null;
const subscribers = new Set<() => void>();
+let storageListenerWired = false;
function isPlainObject(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -65,9 +66,29 @@ function load(): GhostPanelBubbleMap {
function ensureLoaded(): GhostPanelBubbleMap {
if (cache === null) cache = load();
+ ensureStorageListener();
return cache;
}
+/** Keep the in-memory mirror aligned when another BrowserWindow changes the bubble state. */
+function ensureStorageListener(): void {
+ if (storageListenerWired || typeof window === 'undefined') return;
+ storageListenerWired = true;
+ window.addEventListener('storage', (event) => {
+ if (event.storageArea !== window.localStorage || event.key !== STORAGE_KEY) return;
+ let next: unknown = {};
+ if (event.newValue) {
+ try {
+ next = JSON.parse(event.newValue);
+ } catch {
+ next = {};
+ }
+ }
+ cache = sanitize(next);
+ subscribers.forEach((cb) => cb());
+ });
+}
+
/** 整表替换 + 持久化 + 通知(引用变化即订阅者更新信号)。 */
function commit(next: GhostPanelBubbleMap): void {
cache = next;
@@ -170,6 +191,7 @@ export function useGhostPanelBubbleState(): GhostPanelBubbleMap {
export function __resetGhostPanelBubbleStateForTest(): void {
cache = null;
subscribers.clear();
+ storageListenerWired = false;
try {
window.localStorage.removeItem(STORAGE_KEY);
} catch {
diff --git a/apps/desktop/src/renderer/lib/rightSidebarWindowState.ts b/apps/desktop/src/renderer/lib/rightSidebarWindowState.ts
index 14e5610122..ac43543f55 100644
--- a/apps/desktop/src/renderer/lib/rightSidebarWindowState.ts
+++ b/apps/desktop/src/renderer/lib/rightSidebarWindowState.ts
@@ -2,11 +2,10 @@
* rightSidebarWindowState —— 「侧边栏在新窗口中显示」状态的 renderer 端镜像。
*
* Source of truth 在 main(right-sidebar-window/controller.ts + settings-store):
- * - detached: 持久化偏好
+ * - detached: 当前进程内的分离状态
* - open: 子窗口运行时开闭
* 两者都经 `maker:rsb-window:state-changed` 广播到所有窗口,这里只做内存镜像 +
- * useSyncExternalStore 订阅(open 是运行时状态,**不落 localStorage**——重启后
- * 由 bootstrapRsbWindowState 从 main 拉真值)。
+ * useSyncExternalStore 订阅;两者都不落 localStorage,客户端重启后回到主窗口。
*
* MainLayout 用它决定:内嵌右侧栏是否渲染、展开按钮的语义(内嵌展开 vs 开子窗口)。
*/
@@ -65,7 +64,7 @@ export function subscribeRsbWindowUiState(cb: () => void): () => void {
}
/**
- * 启动期从 main 拉全量 state(含 lastOpen,供重启恢复判断)。
+ * 启动期从 main 拉全量当前进程 state。
* 失败兜底:静默,保持默认 { detached:false, open:false }(等广播纠正)。
*/
export async function bootstrapRsbWindowState(): Promise<{
diff --git a/apps/desktop/src/renderer/panels/PanelChrome.tsx b/apps/desktop/src/renderer/panels/PanelChrome.tsx
index 003c9d8b1c..98488e5a8a 100644
--- a/apps/desktop/src/renderer/panels/PanelChrome.tsx
+++ b/apps/desktop/src/renderer/panels/PanelChrome.tsx
@@ -3,6 +3,7 @@ import { Maximize2, Minimize2, Minus, PictureInPicture2, X } from 'lucide-react'
import { useTranslation } from 'react-i18next';
import { CHROME_ACTIONS_GEOMETRY } from '@/components/layout/chromeActionsGeometry';
+import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';
import { useMacFullscreen } from '@/hooks/useMacFullscreen';
import { usePanelMaximize } from '../layout/panelMaximize';
@@ -110,46 +111,36 @@ export function PanelChrome({
<div className="flex shrink-0 items-center gap-0.5">
{actions}
{onMinimize && (
- <button
- type="button"
+ <ChromeIconButton
aria-label={t('panelChrome.minimizeAria')}
onClick={onMinimize}
- 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)]"
>
<Minus size={14} />
- </button>
+ </ChromeIconButton>
)}
{onDetach && (
- <button
- type="button"
+ <ChromeIconButton
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>
+ </ChromeIconButton>
)}
{showMaximize && (
- // 按下命中 button 时 PanelDragController 会让路(标准头手势面的
- // 交互元素豁免),点击不会误触"拿起面板"。
- <button
- type="button"
+ <ChromeIconButton
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>
+ </ChromeIconButton>
)}
{onClose && (
- <button
- type="button"
+ <ChromeIconButton
aria-label={t('panelChrome.closeAria')}
onClick={onClose}
- 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)]"
>
<X size={14} />
- </button>
+ </ChromeIconButton>
)}
</div>
)}
diff --git a/apps/desktop/src/renderer/sidebar-window-entry.tsx b/apps/desktop/src/renderer/sidebar-window-entry.tsx
new file mode 100644
index 0000000000..e05e9262d3
--- /dev/null
+++ b/apps/desktop/src/renderer/sidebar-window-entry.tsx
@@ -0,0 +1,50 @@
+/**
+ * 右侧栏独立子窗口的轻量渲染入口。
+ *
+ * 与 resource-usage-entry.tsx 模式一致:只加载字体/CSS/主题/Provider,
+ * 直接渲染 SidebarWindowLayout,不经过 main-entry.tsx 的完整 App 链
+ * (完整 App 包含 maker-ipc 会话、登录、设置、语音等上千行启动代码)。
+ *
+ * 由 index.tsx 的 ?sidebarWindow=1 分发进入。
+ */
+
+import { createRoot } from 'react-dom/client';
+
+import '@fontsource-variable/inter';
+import '@fontsource-variable/jetbrains-mono';
+import 'harmonyos-sans-sc-webfont-splitted';
+
+import '@/i18n';
+import './themes/colors';
+import './styles/globals.css';
+
+import { TopLevelErrorBoundary } from './components/error/TopLevelErrorBoundary';
+import { SidebarWindowLayout } from './components/layout/SidebarWindowLayout';
+import { AuthProvider } from './contexts/AuthContext';
+import { ConfirmDialogProvider } from './components/ui/confirm-dialog-provider';
+import { applyFontSettings, getInitialFontSettings } from './hooks/useFontSettings';
+import { LocaleProvider, bootstrapInitialLocale } from './hooks/useLocale';
+import { getInitialThemeVariant } from './hooks/useTheme';
+import { bootstrapLocalThemesSync } from './themes/local-themes';
+import { themeService } from './themes/theme-service';
+
+document.documentElement.dataset.platform = window.electronAPI.platform;
+bootstrapLocalThemesSync();
+themeService.applyTheme(getInitialThemeVariant().theme);
+applyFontSettings(getInitialFontSettings());
+bootstrapInitialLocale();
+
+const rootElement = document.getElementById('root');
+if (!rootElement) throw new Error('Missing #root element');
+
+createRoot(rootElement).render(
+ <TopLevelErrorBoundary>
+ <LocaleProvider>
+ <ConfirmDialogProvider>
+ <AuthProvider>
+ <SidebarWindowLayout />
+ </AuthProvider>
+ </ConfirmDialogProvider>
+ </LocaleProvider>
+ </TopLevelErrorBoundary>,
+);
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index fa4891841b..684f6e0586 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1076,6 +1076,7 @@ interface ElectronAPI {
appDisplayVersion: string;
appDisplayVersionDetail: string;
preferredSystemLocale: ApplicationMenuLocale;
+ onLocaleChanged?: (cb: (locale: import('../shared/locale').SupportedLocale) => void) => () => void;
getDeviceId: () => Promise<string>;
windowMinimize: () => void;
windowMaximize: () => void;
@@ -1787,6 +1788,10 @@ interface ElectronAPI {
} | null>;
/** 子窗口根组件挂载握手。 */
ready: () => Promise<void>;
+ rendererReady: () => Promise<void>;
+ presentationReady: () => Promise<void>;
+ refreshContext: () => Promise<void>;
+ onVisibilityChanged: (cb: (payload: { visible: boolean }) => void) => () => void;
/** 主窗把命令转发给子窗口(必要时 main 先开窗)。 */
/** main 原子裁决 attached / routed / queued / stale-context。 */
sendCommand: (
@@ -1838,6 +1843,12 @@ interface ElectronAPI {
onStateChanged: (
cb: (state: import('../shared/ghostPanelWindow').GhostPanelWindowsState) => void,
) => () => void;
+ rendererReady: () => Promise<void>;
+ presentationReady: () => Promise<void>;
+ onVisibilityChanged: (cb: (payload: { visible: boolean }) => void) => () => void;
+ onCloseRequested: (cb: () => void) => () => void;
+ onMinimizeRequested: (cb: () => void) => () => void;
+ resolveCloseRequest: (approved: boolean) => Promise<void>;
};
agentIsland: {
diff --git a/apps/desktop/src/shared/ghostPanelWindow.ts b/apps/desktop/src/shared/ghostPanelWindow.ts
index 291331eecf..cb31952653 100644
--- a/apps/desktop/src/shared/ghostPanelWindow.ts
+++ b/apps/desktop/src/shared/ghostPanelWindow.ts
@@ -7,11 +7,11 @@
* 多实例(每个插件至多一扇窗)。
*/
-/** 单个插件窗口状态:detached 是持久化偏好,lastOpen 供重启恢复,open 是运行时开闭。 */
+/** 单个插件窗口状态:均仅在当前进程有效;重启后 detached / lastOpen 重置。 */
export interface GhostPanelWindowEntryState {
- /** 偏好:「该插件面板在独立窗口中显示」。持久化,default false。 */
+ /** 当前运行期是否在独立窗口中显示。 */
detached: boolean;
- /** 状态:上次退出时窗口是否处于打开态(供重启恢复)。持久化。 */
+ /** 当前运行期是否曾请求保持窗口打开;不跨客户端重启。 */
lastOpen: boolean;
/** 运行时:子窗口当前是否存在。不持久化。 */
open: boolean;
@@ -19,3 +19,21 @@ export interface GhostPanelWindowEntryState {
/** 全量状态:ghostId → 窗口状态。没有条目 = 从未抽离(等价三 false)。 */
export type GhostPanelWindowsState = Record<string, GhostPanelWindowEntryState>;
+
+// ── 预热/就绪/隐藏复用 IPC channel 常量 ──────────────────────────────
+/** renderer → main(invoke):窗口根组件已挂载(React shell 可展示)。 */
+export const GHOST_PANEL_WINDOW_RENDERER_READY_CHANNEL = 'ghost-panel-window:renderer-ready';
+/** renderer → main(invoke):首份面板内容已提交(至少空态/错误态可渲染)。 */
+export const GHOST_PANEL_WINDOW_PRESENTATION_READY_CHANNEL =
+ 'ghost-panel-window:presentation-ready';
+/** main → renderer(send):隐藏/显示时通知子窗口刷新面板 + 重置瞬时交互态。 */
+export const GHOST_PANEL_WINDOW_VISIBILITY_CHANGED_CHANNEL =
+ 'ghost-panel-window:visibility-changed';
+export const GHOST_PANEL_WINDOW_CLOSE_REQUESTED_CHANNEL =
+ 'ghost-panel-window:close-requested';
+/** main → renderer(send):原生窗口最小化也统一收进主窗口 Ghost 气泡。 */
+export const GHOST_PANEL_WINDOW_MINIMIZE_REQUESTED_CHANNEL =
+ 'ghost-panel-window:minimize-requested';
+export const GHOST_PANEL_WINDOW_CLOSE_REQUEST_RESOLVED_CHANNEL =
+ 'ghost-panel-window:close-request-resolved';
+export const GHOST_PANEL_WINDOW_LOCALE_CHANGED_CHANNEL = 'ghost-panel-window:locale-changed';
diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.ts
index 4c004180fa..ce09618c72 100644
--- a/apps/desktop/src/shared/rightSidebarWindow.ts
+++ b/apps/desktop/src/shared/rightSidebarWindow.ts
@@ -9,11 +9,11 @@ import type { SubagentProvider } from '@cindy/maker-shared/subagent-workspace';
import type { ConversationSearchJump } from './conversationSearchJump.js';
-/** 子窗口全局状态:detached 是持久化偏好,lastOpen 是重启恢复用的状态,open 是运行时窗口开闭。 */
+/** 子窗口全局状态:均仅在当前进程有效;重启后 detached / lastOpen 重置。 */
export interface RsbWindowState {
- /** 偏好:「侧边栏在新窗口中显示」。持久化,default false。 */
+ /** 当前运行期是否在独立窗口中显示。 */
detached: boolean;
- /** 状态:上次退出时窗口是否处于打开态(供重启恢复)。持久化。 */
+ /** 当前运行期是否曾请求保持窗口打开;不跨客户端重启。 */
lastOpen: boolean;
/** 运行时:子窗口当前是否存在。不持久化。 */
open: boolean;
@@ -110,3 +110,14 @@ export type RsbWindowCommandRouteResult =
| 'routed'
| 'queued'
| 'stale-context';
+
+// ── 预热/就绪/隐藏复用 IPC channel 常量 ──────────────────────────────
+// renderer → main(invoke):轻量窗口根组件已经挂载(Renderer shell 可展示)。
+export const RSB_WINDOW_RENDERER_READY_CHANNEL = 'rsb-window:renderer-ready';
+// renderer → main(invoke):首份业务内容已提交(context+store 就绪,至少 EmptyState 可见)。
+export const RSB_WINDOW_PRESENTATION_READY_CHANNEL = 'rsb-window:presentation-ready';
+// main → renderer(send):隐藏/显示时通知子窗口刷新 context 与重置瞬时交互态。
+export const RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL = 'rsb-window:visibility-changed';
+// renderer → main(invoke):子窗口请求刷新 context(从 main 缓存拉最新值)。
+export const RSB_WINDOW_REFRESH_CONTEXT_CHANNEL = 'rsb-window:refresh-context';
+export const RSB_WINDOW_LOCALE_CHANGED_CHANNEL = 'rsb-window:locale-changed';