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。

fix(desktop): preserve sidebar tabs across detached window handoff

David5de024c455f3
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b188b5603a..e3af342fb6 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1459,6 +1459,7 @@ const rsbWindowController = new RsbWindowController({
},
contextChannel: MAKER_PUSH.RSB_WINDOW_CONTEXT_CHANGED,
commandChannel: MAKER_PUSH.RSB_WINDOW_COMMAND,
+ tabHandoffChannel: MAKER_PUSH.RSB_WINDOW_TAB_HANDOFF,
isQuitting: () => isQuitting,
canCloseWindow: () => !hasActiveRsbNativePopupSurfaces(),
log: createLogger('right-sidebar-window-controller'),
@@ -3862,8 +3863,8 @@ const registerIpcHandlers = () => {
// Fullscreen state query — renderer calls this on mount to recover from the
// race where `enter-full-screen` fires before the renderer subscribes (e.g.
// when window-state restores a fullscreen window on launch).
- ipcMain.handle('get-fullscreen-state', (): boolean => {
- const win = getWindow();
+ ipcMain.handle('get-fullscreen-state', (event): boolean => {
+ const win = BrowserWindow.fromWebContents(event.sender) ?? getWindow();
if (!win) return false;
return win.isFullScreen() || win.isSimpleFullScreen();
});
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
index c9b5bd509b..c23dc5f4d9 100644
--- 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
@@ -56,6 +56,7 @@ describe('ghost panel preload contract', () => {
expect(topLevel).toEqual(expect.arrayContaining([
'platform', 'preferredSystemLocale', 'windowMinimize', 'windowMaximize', 'windowClose',
'appearanceSettings', 'localThemes', 'appShortcuts', 'theme',
+ 'onFullscreenChange', 'getFullscreenState',
'copyMediaToClipboard', 'showItemInFolder', 'cacheMediaForSession',
'openMediaWithDefaultApp', 'saveMediaAs', 'ghostPanelWindow', 'ghosts',
]));
diff --git a/apps/desktop/src/main/ghost-panel-window/window.ts b/apps/desktop/src/main/ghost-panel-window/window.ts
index 44a757aa22..d6f34c90e5 100644
--- a/apps/desktop/src/main/ghost-panel-window/window.ts
+++ b/apps/desktop/src/main/ghost-panel-window/window.ts
@@ -75,6 +75,14 @@ export function createGhostPanelWindow(ghostId: string, title: string): BrowserW
navigateOnDragDrop: false,
},
});
+ // Keep the detached plugin renderer in sync with its own native fullscreen
+ // state; the main window's listener cannot describe this BrowserWindow.
+ win.on('enter-full-screen', () => {
+ if (!win.isDestroyed()) win.webContents.send('fullscreen-change', true);
+ });
+ win.on('leave-full-screen', () => {
+ if (!win.isDestroyed()) win.webContents.send('fullscreen-change', false);
+ });
markGhostPanelWebContentsId(win.webContents.id);
markAppContentWindow(win);
applyAppearanceToWindow(win);
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 270525789f..28b3b24991 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -887,6 +887,8 @@ export const MAKER_PUSH = {
RSB_WINDOW_CONTEXT_CHANGED: 'maker:rsb-window:context-changed',
/** main → 子窗口命令(如 open-terminal),只发子窗口。payload = RsbWindowCommand。 */
RSB_WINDOW_COMMAND: 'maker:rsb-window:command',
+ /** 子窗口合并回主窗口前交接不可持久化 session 的 tab 快照,只发主窗口。 */
+ RSB_WINDOW_TAB_HANDOFF: 'maker:rsb-window:tab-handoff',
/** Main-owned H.264 access unit pushed without Renderer polling. */
IOS_SIMULATOR_H264_FRAME: 'maker:ios-simulator:h264-frame',
/** Main-owned public route selection/status for the iOS Simulator viewer. */
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 85dbbee36e..a8f2779e28 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
@@ -128,6 +128,7 @@ function makeHarness(initial: Partial<RsbWindowSettings> = {}) {
},
contextChannel: 'ctx-channel',
commandChannel: 'cmd-channel',
+ tabHandoffChannel: 'handoff-channel',
isQuitting: () => quitting,
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
};
@@ -441,6 +442,51 @@ describe('setDetached', () => {
expect(state).toEqual({ detached: true, lastOpen: true, open: true });
});
+ it('true: queues a memory-only tab snapshot until the detached renderer is ready', () => {
+ const h = makeHarness();
+ h.controller.setContext(ctx);
+ const handoff = {
+ snapshots: [
+ {
+ sessionId: 's1',
+ tabs: [{ id: 't1', kind: 'web-browser', state: { url: 'about:blank' } }],
+ activeTabId: 't1',
+ persistable: false as const,
+ },
+ ],
+ };
+
+ h.controller.setDetached(true, handoff);
+ const win = h.windows[0];
+ expect(h.sends.some((entry) => entry.channel === 'handoff-channel')).toBe(false);
+
+ markReady(h.controller, win);
+
+ const handoffIndex = h.sends.findIndex((entry) => entry.channel === 'handoff-channel');
+ expect(h.sends[handoffIndex]).toEqual({ channel: 'handoff-channel', payload: handoff });
+ expect(h.sendTargets[handoffIndex]).toBe(win.webContents.id);
+ });
+
+ it('true: drops a queued snapshot if the main context changes before renderer ready', () => {
+ const h = makeHarness();
+ h.controller.setContext(ctx);
+ h.controller.setDetached(true, {
+ snapshots: [
+ {
+ sessionId: 's1',
+ tabs: [{ id: 't1', kind: 'web-browser', state: null }],
+ activeTabId: 't1',
+ persistable: false,
+ },
+ ],
+ });
+ h.controller.setContext({ ...ctx, sessionId: 's2' });
+
+ markReady(h.controller, h.windows[0]);
+
+ expect(h.sends.some((entry) => entry.channel === 'handoff-channel')).toBe(false);
+ });
+
it('false: destroys window + broadcasts detached:false', () => {
const h = makeHarness({ detached: true });
h.controller.prewarm();
@@ -454,6 +500,64 @@ describe('setDetached', () => {
expect(state.open).toBe(false);
expect(h.broadcasts.at(-1)).toEqual({ detached: false, open: false });
});
+
+ it('false: hands off the current memory-only tab snapshot before destroying the window', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.setContext(ctx);
+ h.controller.open({ userInitiated: false });
+
+ const handoff = {
+ snapshots: [
+ {
+ sessionId: 's1',
+ tabs: [{ id: 't1', kind: 'web-browser', state: { url: 'https://example.com' } }],
+ activeTabId: 't1',
+ persistable: false,
+ },
+ ],
+ };
+ h.controller.setDetached(false, handoff);
+
+ const handoffIndex = h.sends.findIndex((entry) => entry.channel === 'handoff-channel');
+ expect(handoffIndex).toBeGreaterThanOrEqual(0);
+ expect(h.sends[handoffIndex]).toEqual({
+ channel: 'handoff-channel',
+ payload: handoff,
+ });
+ expect(h.sendTargets[handoffIndex]).toBe(h.mainWin.webContents.id);
+ expect(win.destroy).toHaveBeenCalledOnce();
+ });
+
+ it('drops persistable and stale-session handoff snapshots', () => {
+ const h = makeHarness({ detached: true });
+ h.controller.prewarm();
+ const win = h.windows[0];
+ markReady(h.controller, win);
+ h.controller.setContext(ctx);
+ h.controller.open({ userInitiated: false });
+
+ h.controller.setDetached(false, {
+ snapshots: [
+ {
+ sessionId: 's1',
+ tabs: [],
+ activeTabId: null,
+ persistable: true,
+ },
+ {
+ sessionId: 'other',
+ tabs: [],
+ activeTabId: null,
+ persistable: false,
+ },
+ ],
+ });
+
+ expect(h.sends.some((entry) => entry.channel === 'handoff-channel')).toBe(false);
+ });
});
// ═══════════════════════════════════════════════════════════════════════
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 5ff55208f5..998830b932 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
@@ -19,6 +19,12 @@ import { MAKER_INVOKE, MAKER_SEND } from '../../maker-ipc/channels.js';
import { registerRsbWindowIpc } from '../ipc.js';
import type { RsbWindowController } from '../controller.js';
+type RsbWindowControllerMock = RsbWindowController & {
+ getState: ReturnType<typeof vi.fn>;
+ getSidebarWebContents: ReturnType<typeof vi.fn>;
+ routeCommand: ReturnType<typeof vi.fn>;
+};
+
function makeController() {
return {
getState: vi.fn(),
@@ -33,7 +39,7 @@ function makeController() {
refreshContext: vi.fn(),
setContext: vi.fn(),
routeCommand: vi.fn(async () => 'routed'),
- } as unknown as RsbWindowController & { routeCommand: ReturnType<typeof vi.fn> };
+ } as unknown as RsbWindowControllerMock;
}
function getSendCommandHandler() {
@@ -457,6 +463,66 @@ describe('right-sidebar-window IPC', () => {
expect(() => open({}, { userInitiated: 1 })).toThrow(/options.userInitiated/);
});
+ it('accepts a memory-only tab handoff only from the detached sidebar sender', () => {
+ const controller = makeController();
+ const sidebarWebContents = { id: 3 };
+ controller.getState.mockReturnValue({ detached: true, lastOpen: true, open: true });
+ controller.getSidebarWebContents.mockReturnValue(sidebarWebContents);
+ registerController(controller);
+ const handlers = (
+ ipcMain as unknown as { __handlers: Map<string, (e: unknown, p: unknown, h?: unknown) => unknown> }
+ ).__handlers;
+ const setDetached = handlers.get(MAKER_INVOKE.RSB_WINDOW_SET_DETACHED);
+ if (!setDetached) throw new Error('RSB_WINDOW_SET_DETACHED handler not registered');
+ const handoff = {
+ snapshots: [
+ {
+ sessionId: 's1',
+ tabs: [{ id: 't1', kind: 'web-browser', state: { url: 'https://example.com' } }],
+ activeTabId: 't1',
+ persistable: false,
+ },
+ ],
+ };
+
+ setDetached({ sender: sidebarWebContents }, false, handoff);
+ expect(controller.setDetached).toHaveBeenCalledWith(false, handoff);
+
+ expect(() => setDetached({ sender: { id: 4 } }, false, handoff)).toThrow(/sender/);
+ expect(() => setDetached({ sender: sidebarWebContents }, false, {
+ snapshots: [{ sessionId: 's1', tabs: [], activeTabId: null, persistable: true }],
+ })).toThrow(/non-persistable/);
+ });
+
+ it('accepts a memory-only tab handoff for detach only from the main window sender', () => {
+ const controller = makeController();
+ const sidebarWebContents = { id: 3 };
+ controller.getState.mockReturnValue({ detached: false, lastOpen: false, open: false });
+ controller.getSidebarWebContents.mockReturnValue(sidebarWebContents);
+ const { mainWebContents } = registerController(controller);
+ const handlers = (
+ ipcMain as unknown as {
+ __handlers: Map<string, (e: unknown, p: unknown, h?: unknown) => unknown>;
+ }
+ ).__handlers;
+ const setDetached = handlers.get(MAKER_INVOKE.RSB_WINDOW_SET_DETACHED);
+ if (!setDetached) throw new Error('RSB_WINDOW_SET_DETACHED handler not registered');
+ const handoff = {
+ snapshots: [
+ {
+ sessionId: 's1',
+ tabs: [{ id: 't1', kind: 'web-browser', state: { url: 'about:blank' } }],
+ activeTabId: 't1',
+ persistable: false,
+ },
+ ],
+ };
+
+ setDetached({ sender: mainWebContents }, true, handoff);
+ expect(controller.setDetached).toHaveBeenCalledWith(true, handoff);
+ expect(() => setDetached({ sender: sidebarWebContents }, true, handoff)).toThrow(/main window/);
+ });
+
it('requires an explicit allowOpen boolean in the IPC envelope', async () => {
const controller = makeController();
const { handler, mainWebContents } = registerController(controller);
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
index 23ea747454..22be7135e7 100644
--- 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
@@ -132,6 +132,8 @@ describe('sidebarWindowPreload 椤跺眰濂戠害', () => {
expect(topLevel).toEqual(expect.arrayContaining(['localThemes']));
expect(topLevel).toEqual(expect.arrayContaining(['appShortcuts']));
expect(topLevel).toEqual(expect.arrayContaining(['theme']));
+ expect(topLevel).toEqual(expect.arrayContaining(['onFullscreenChange']));
+ expect(topLevel).toEqual(expect.arrayContaining(['getFullscreenState']));
expect(topLevel).toEqual(expect.arrayContaining(['search']));
});
@@ -274,6 +276,7 @@ describe('rightSidebarWindow 鍛藉悕绌洪棿', () => {
expect(rswKeys).toEqual(expect.arrayContaining(['refreshContext']));
expect(rswKeys).toEqual(expect.arrayContaining(['onStateChanged']));
expect(rswKeys).toEqual(expect.arrayContaining(['onContextChanged']));
+ expect(rswKeys).toEqual(expect.arrayContaining(['onTabHandoff']));
expect(rswKeys).toEqual(expect.arrayContaining(['onCommand']));
expect(rswKeys).toEqual(expect.arrayContaining(['sendCommand']));
expect(rswKeys).toEqual(expect.arrayContaining(['onVisibilityChanged']));
diff --git a/apps/desktop/src/main/right-sidebar-window/controller.ts b/apps/desktop/src/main/right-sidebar-window/controller.ts
index 066aa6dc82..c4aadfaf86 100644
--- a/apps/desktop/src/main/right-sidebar-window/controller.ts
+++ b/apps/desktop/src/main/right-sidebar-window/controller.ts
@@ -26,6 +26,7 @@ import type {
RsbWindowCommandRouteResult,
RsbWindowContext,
RsbWindowState,
+ RsbWindowTabHandoff,
} from '../../shared/rightSidebarWindow.js';
import {
RSB_WINDOW_LOCALE_CHANGED_CHANNEL,
@@ -59,6 +60,8 @@ export interface RsbWindowControllerDeps {
sendToWindow: (win: BrowserWindow, channel: string, payload: unknown) => void;
contextChannel: string;
commandChannel: string;
+ /** main → renderer host;用于内嵌 / 分离宿主之间交接内存态 tab。 */
+ tabHandoffChannel?: string;
isQuitting: () => boolean;
/** Popup WindowProxy depends on the ordinary webview opener staying alive. */
canCloseWindow?: () => boolean;
@@ -120,6 +123,8 @@ export class RsbWindowController {
private recoveryStabilityTimeout: NodeJS.Timeout | null = null;
private automaticRecoveryAttempts = 0;
private lastContext: RsbWindowContext | null = null;
+ /** 冷启动分离窗尚未 presentation-ready 时暂存主窗交来的内存态 tab。 */
+ private pendingDetachedTabHandoff: RsbWindowTabHandoff | null = null;
/**
* allowOpen=false 时按宿主 session 保序排队的 deferred 命令。
*
@@ -225,11 +230,14 @@ export class RsbWindowController {
}
/** 写偏好;true 附带开窗,false 附带真正销毁窗口 + 恢复主窗内嵌侧栏。 */
- setDetached(next: boolean): RsbWindowState {
+ setDetached(next: boolean, handoff?: RsbWindowTabHandoff): RsbWindowState {
this.deps.settings.writePatch({ detached: next });
if (next) {
+ this.queueTabHandoffToDetachedHost(handoff);
this.open({ userInitiated: true });
} else {
+ this.pendingDetachedTabHandoff = null;
+ this.sendTabHandoffToAttachedHost(handoff);
this.flushDeferredCommandsToAttachedHost();
this.disposeCachedWindow();
}
@@ -268,6 +276,9 @@ export class RsbWindowController {
clearTimeout(w.timeout);
w.resolve();
}
+ // 冷窗口的主窗快照必须先进入子 renderer store,再允许 show + context
+ // hydrate;否则不可持久化会话会先以空 bucket 提交首帧。
+ this.flushTabHandoffToDetachedHost();
if (this.pendingOpen) {
this.showWindow(win, this.pendingOpenShouldFocus);
}
@@ -706,6 +717,44 @@ export class RsbWindowController {
this.deps.log.info('right-sidebar window disposed (merged back to main)');
}
+ private sendTabHandoffToAttachedHost(handoff?: RsbWindowTabHandoff): void {
+ const channel = this.deps.tabHandoffChannel;
+ const main = this.deps.getMainWindow();
+ const filtered = this.filterTabHandoffForCurrentContext(handoff);
+ if (!channel || !main || main.isDestroyed() || !filtered) return;
+ this.deps.sendToWindow(main, channel, filtered);
+ }
+
+ private queueTabHandoffToDetachedHost(handoff?: RsbWindowTabHandoff): void {
+ this.pendingDetachedTabHandoff = this.filterTabHandoffForCurrentContext(handoff);
+ if (this.presentationReady) this.flushTabHandoffToDetachedHost();
+ }
+
+ private flushTabHandoffToDetachedHost(): void {
+ const channel = this.deps.tabHandoffChannel;
+ const win = this.winRef;
+ const handoff = this.filterTabHandoffForCurrentContext(
+ this.pendingDetachedTabHandoff ?? undefined,
+ );
+ if (!channel || !win || win.isDestroyed() || !this.presentationReady || !handoff) return;
+ this.pendingDetachedTabHandoff = null;
+ this.deps.sendToWindow(win, channel, handoff);
+ }
+
+ private filterTabHandoffForCurrentContext(
+ handoff?: RsbWindowTabHandoff,
+ ): RsbWindowTabHandoff | null {
+ const currentSessionId = this.lastContext?.available ? this.lastContext.sessionId : null;
+ if (!currentSessionId || !handoff) return null;
+
+ // Main owns the current context. Drop renderer-reported snapshots for any
+ // other session and never use a persistable snapshot as a DB replacement.
+ const snapshots = handoff.snapshots.filter(
+ (snapshot) => !snapshot.persistable && snapshot.sessionId === currentSessionId,
+ );
+ return snapshots.length > 0 ? { snapshots } : null;
+ }
+
// ── 命令路由辅助 ─────────────────────────────────────────────────
private canDispatchCommand(cmd: RsbWindowCommand): boolean {
diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.ts
index 1ce6b9f4fb..1cfe651453 100644
--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts
+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts
@@ -18,10 +18,14 @@ import type {
RsbWindowCommandRouteRequest,
RsbWindowContext,
} from '../../shared/rightSidebarWindow.js';
+import {
+ MAX_STATE_JSON_BYTES,
+} from '../../shared/rightSidebarTabState.js';
import {
RSB_WINDOW_PRESENTATION_READY_CHANNEL,
RSB_WINDOW_REFRESH_CONTEXT_CHANNEL,
RSB_WINDOW_RENDERER_READY_CHANNEL,
+ type RsbWindowTabHandoff,
} from '../../shared/rightSidebarWindow.js';
import { parseConversationSearchJump } from '../../shared/conversationSearchJump.js';
import { hasActiveRsbNativePopupSurfaces } from '../rsb-browser-bridge/native-popup-surfaces.js';
@@ -254,6 +258,64 @@ function parseOpenUserInitiated(raw: unknown): boolean {
return r.userInitiated !== false;
}
+const MAX_HANDOFF_SNAPSHOTS = 8;
+const MAX_HANDOFF_TABS = 20;
+const MAX_HANDOFF_STRING_LENGTH = 512;
+
+function parseTabHandoff(raw: unknown): RsbWindowTabHandoff | undefined {
+ if (raw === undefined) return undefined;
+ const root = requireObject(raw, 'tab handoff');
+ if (!Array.isArray(root.snapshots) || root.snapshots.length > MAX_HANDOFF_SNAPSHOTS) {
+ throwIpcError('INVALID_PARAMS', 'tab handoff snapshots must be an array');
+ }
+ const snapshots = root.snapshots.map((rawSnapshot, snapshotIndex) => {
+ const snapshot = requireObject(rawSnapshot, `tab handoff snapshots[${snapshotIndex}]`);
+ const sessionId = snapshot.sessionId;
+ if (
+ typeof sessionId !== 'string' ||
+ sessionId.length === 0 ||
+ sessionId.length > MAX_HANDOFF_STRING_LENGTH
+ ) {
+ throwIpcError('INVALID_PARAMS', 'tab handoff sessionId is invalid');
+ }
+ if (snapshot.persistable !== false) {
+ throwIpcError('INVALID_PARAMS', 'tab handoff snapshot must be non-persistable');
+ }
+ if (!Array.isArray(snapshot.tabs) || snapshot.tabs.length > MAX_HANDOFF_TABS) {
+ throwIpcError('INVALID_PARAMS', 'tab handoff tabs must be an array');
+ }
+ const activeTabId = snapshot.activeTabId;
+ if (activeTabId !== null && (typeof activeTabId !== 'string' || activeTabId.length > MAX_HANDOFF_STRING_LENGTH)) {
+ throwIpcError('INVALID_PARAMS', 'tab handoff activeTabId is invalid');
+ }
+ const tabs = snapshot.tabs.map((rawTab, tabIndex) => {
+ const tab = requireObject(rawTab, `tab handoff tabs[${tabIndex}]`);
+ if (
+ typeof tab.id !== 'string' ||
+ tab.id.length === 0 ||
+ tab.id.length > MAX_HANDOFF_STRING_LENGTH ||
+ typeof tab.kind !== 'string' ||
+ tab.kind.length === 0 ||
+ tab.kind.length > MAX_HANDOFF_STRING_LENGTH
+ ) {
+ throwIpcError('INVALID_PARAMS', 'tab handoff tab identity is invalid');
+ }
+ let stateJson: string | undefined;
+ try {
+ stateJson = JSON.stringify(tab.state);
+ } catch {
+ throwIpcError('INVALID_PARAMS', 'tab handoff tab state is not JSON-serializable');
+ }
+ if (typeof stateJson !== 'string' || Buffer.byteLength(stateJson, 'utf8') > MAX_STATE_JSON_BYTES) {
+ throwIpcError('RIGHT_SIDEBAR_STATE_TOO_LARGE', 'tab handoff tab state is too large');
+ }
+ return { id: tab.id, kind: tab.kind, state: tab.state };
+ });
+ return { sessionId, tabs, activeTabId, persistable: false };
+ });
+ return { snapshots };
+}
+
export function registerRsbWindowIpc(opts: {
controller: RsbWindowController;
getMainWindow: () => BrowserWindow | null;
@@ -273,14 +335,30 @@ export function registerRsbWindowIpc(opts: {
controller.close();
});
- ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_SET_DETACHED, (_e, detached: unknown) => {
+ ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_SET_DETACHED, (event, detached: unknown, rawHandoff: unknown) => {
if (typeof detached !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'detached required (boolean)');
}
+ const handoff = parseTabHandoff(rawHandoff);
+ if (handoff) {
+ const main = getMainWindow();
+ const sidebarWc = controller.getSidebarWebContents();
+ const validSender = detached
+ ? Boolean(main && !main.isDestroyed() && event.sender === main.webContents)
+ : Boolean(sidebarWc && event.sender === sidebarWc);
+ if (!validSender) {
+ throwIpcError(
+ 'PERMISSION_DENIED',
+ detached
+ ? 'tab handoff sender is not the main window'
+ : 'tab handoff sender is not the detached sidebar',
+ );
+ }
+ }
if (detached !== controller.getState().detached && hasActiveRsbNativePopupSurfaces()) {
throwIpcError('PRECONDITION_FAILED', 'active browser popup must be completed or closed first');
}
- return controller.setDetached(detached);
+ return controller.setDetached(detached, handoff);
});
ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_GET_CONTEXT, () => controller.getContext());
diff --git a/apps/desktop/src/main/right-sidebar-window/window.ts b/apps/desktop/src/main/right-sidebar-window/window.ts
index 3058e385e6..309f4e1157 100644
--- a/apps/desktop/src/main/right-sidebar-window/window.ts
+++ b/apps/desktop/src/main/right-sidebar-window/window.ts
@@ -74,6 +74,15 @@ export function createRightSidebarWindow(): BrowserWindow {
webviewTag: true,
},
});
+ // The detached sidebar has its own hidden title bar and renderer. Fullscreen
+ // state changes therefore need to be sent from this window, not only from
+ // the primary window's bootstrap listener.
+ win.on('enter-full-screen', () => {
+ if (!win.isDestroyed()) win.webContents.send('fullscreen-change', true);
+ });
+ win.on('leave-full-screen', () => {
+ if (!win.isDestroyed()) win.webContents.send('fullscreen-change', false);
+ });
markRsbWindowWebContentsId(win.webContents.id);
markAppContentWindow(win);
applyAppearanceToWindow(win);
diff --git a/apps/desktop/src/preload/ghostPanelWindowPreload.ts b/apps/desktop/src/preload/ghostPanelWindowPreload.ts
index e25154f6b2..67f32065f8 100644
--- a/apps/desktop/src/preload/ghostPanelWindowPreload.ts
+++ b/apps/desktop/src/preload/ghostPanelWindowPreload.ts
@@ -118,6 +118,9 @@ const appearanceSettings = ipcRenderer.sendSync(
'appearance-settings:get-sync',
) as AppearanceSettings | null;
+const fanOutFullscreenChange = (cb: (isFullscreen: boolean) => void): Unsub =>
+ onPayload('fullscreen-change', cb);
+
contextBridge.exposeInMainWorld('electronAPI', {
platform: process.platform,
preferredSystemLocale: readPreferredSystemLocale(),
@@ -156,6 +159,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.send('theme:apply-vibrancy', { familyId, isDark });
},
},
+ // Shared panel chrome may need this when a detached plugin window is used
+ // on macOS, where the traffic-light area changes during native fullscreen.
+ onFullscreenChange: fanOutFullscreenChange,
+ getFullscreenState: (): Promise<boolean> => ipcRenderer.invoke('get-fullscreen-state'),
// ── 媒体操作(面板产物右键菜单 / 拖拽引渡) ──────────────────────────
// 与主 preload 同款 channel,main 侧 handler 对所有受信 renderer 生效。
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 1e26348286..ca092116ea 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -122,7 +122,9 @@ import type {
import type {
RsbWindowCommandRouteRequest,
RsbWindowCommandRouteResult,
+ RsbWindowTabHandoff,
} from '../shared/rightSidebarWindow';
+import { RSB_WINDOW_TAB_HANDOFF_CHANNEL } from '../shared/rightSidebarWindow';
import {
RSB_NATIVE_POPUP_CLAIM_CHANNEL,
RSB_NATIVE_POPUP_CLOSE_CHANNEL,
@@ -384,6 +386,7 @@ const fanOutOrcaWorkerChanged = createIpcFanOut('maker:orca:worker-changed');
const fanOutRsbWindowStateChanged = createIpcFanOut('maker:rsb-window:state-changed');
const fanOutRsbWindowContextChanged = createIpcFanOut('maker:rsb-window:context-changed');
const fanOutRsbWindowCommand = createIpcFanOut('maker:rsb-window:command');
+const fanOutRsbWindowTabHandoff = createIpcFanOut(RSB_WINDOW_TAB_HANDOFF_CHANNEL);
// 插件停靠面板独立窗口(ghost panel window)状态推送
const fanOutGhostPanelWindowStateChanged = createIpcFanOut(
'maker:ghost-panel-window:state-changed',
@@ -1530,8 +1533,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** 写偏好;true 附带开窗,false 附带关窗。返回新 state。 */
setDetached: (
detached: boolean,
+ handoff?: RsbWindowTabHandoff,
): Promise<{ detached: boolean; lastOpen: boolean; open: boolean }> =>
- ipcRenderer.invoke('maker:rsb-window:set-detached', detached),
+ ipcRenderer.invoke('maker:rsb-window:set-detached', detached, handoff),
/** 子窗口 mount 时拉主窗上报的渲染上下文(main 缓存的最后一份)。 */
getContext: (): Promise<{
sessionId: string | null;
@@ -1556,6 +1560,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
onStateChanged: fanOutRsbWindowStateChanged,
onContextChanged: fanOutRsbWindowContextChanged,
onCommand: fanOutRsbWindowCommand,
+ onTabHandoff: (cb: (handoff: RsbWindowTabHandoff) => void): (() => void) =>
+ fanOutRsbWindowTabHandoff((data) => cb(data as RsbWindowTabHandoff)),
},
// ── 插件停靠面板独立窗口(ghost panel window)──────────────────────────
diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.ts
index 3dbbc0cabe..a2fa98e51c 100644
--- a/apps/desktop/src/preload/sidebarWindowPreload.ts
+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts
@@ -24,8 +24,10 @@ import {
RSB_WINDOW_REFRESH_CONTEXT_CHANNEL,
RSB_WINDOW_RENDERER_READY_CHANNEL,
RSB_WINDOW_LOCALE_CHANGED_CHANNEL,
+ RSB_WINDOW_TAB_HANDOFF_CHANNEL,
RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL,
} from '../shared/rightSidebarWindow';
+import type { RsbWindowTabHandoff } from '../shared/rightSidebarWindow';
type ApplicationMenuLocale = SupportedLocale;
@@ -60,6 +62,9 @@ const appearanceSettings = ipcRenderer.sendSync(
'appearance-settings:get-sync',
) as AppearanceSettings | null;
+const fanOutFullscreenChange = (cb: (isFullscreen: boolean) => void): (() => void) =>
+ onPayload('fullscreen-change', cb);
+
contextBridge.exposeInMainWorld('electronAPI', {
platform: process.platform,
preferredSystemLocale: readPreferredSystemLocale(),
@@ -98,6 +103,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.send('theme:apply-vibrancy', { familyId, isDark });
},
},
+ // PanelChrome uses this on macOS to keep the traffic-light area and actions
+ // aligned while the detached sidebar enters or leaves native fullscreen.
+ onFullscreenChange: fanOutFullscreenChange,
+ getFullscreenState: (): Promise<boolean> => ipcRenderer.invoke('get-fullscreen-state'),
// AuthProvider 在分离侧栏中只负责初始化账号快照、监听账号边界变化,以及给
// device-link 子面板投影当前身份。该窗口没有登录/登出/本地模式/账号删除 UI,
@@ -291,8 +300,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
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),
+ setDetached: (
+ detached: boolean,
+ handoff?: RsbWindowTabHandoff,
+ ): Promise<{ detached: boolean; lastOpen: boolean; open: boolean }> =>
+ ipcRenderer.invoke('maker:rsb-window:set-detached', detached, handoff),
getContext: (): Promise<{
sessionId: string | null;
workdir: string | null;
@@ -323,6 +335,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
onCommand: (
cb: (cmd: unknown) => void,
): (() => void) => onPayload('maker:push:rsb-window:command', cb),
+ onTabHandoff: (cb: (handoff: RsbWindowTabHandoff) => void): (() => void) =>
+ onPayload(RSB_WINDOW_TAB_HANDOFF_CHANNEL, cb),
sendCommand: (request: unknown): Promise<string> =>
ipcRenderer.invoke('maker:rsb-window:send-command', request),
/** 闅愯棌/鏄剧ず鏃堕€氱煡瀛愮獥鍙e埛鏂?context + 閲嶇疆鐬椂浜や簰鎬併€?*/
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 9dccf7ebe2..af0524c355 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -43,7 +43,9 @@ import {
closeTab,
ensureHydrated,
getBucket,
- invalidateSessionCaches,
+ getTabSnapshot,
+ importTabSnapshot,
+ resetCachesForHostTransition,
} from '@/features/right-sidebar/store';
import { browserWebviewPool } from '@/features/right-sidebar/lib/browserWebviewPool';
import { markAllPtyDetached } from '@/features/right-sidebar/plugins/terminal/lib/xtermPool';
@@ -727,6 +729,16 @@ export function MainLayout() {
writeCollapsedFor(sessionId, true);
}, [rsbDetached]);
+ // 分离侧栏合并回主窗时,main 先转发不可持久化 session 的 tab 快照,
+ // 再广播 detached=false 让这里重挂内嵌 Shell。快照必须在 cache invalidation
+ // 之前接收;store 会把它保留到本次 hydrate,避免远程/草稿会话回到空栏。
+ useEffect(() => {
+ if (isSecondaryWindow()) return;
+ return window.electronAPI.rightSidebarWindow.onTabHandoff((handoff) => {
+ for (const snapshot of handoff.snapshots) importTabSnapshot(snapshot);
+ });
+ }, []);
+
// sessionId 切换时按新 session 的存档刷新折叠态。无需 prime 动画 —— RightSidebar 默认
// 直接同步,切 session "瞬间生效"(用户体感:不应看着一栏慢慢展开/收起)。
useLayoutEffect(() => {
@@ -907,10 +919,10 @@ export function MainLayout() {
// 过期(PTY sink 会被对方窗口 re-attach 抢走),两个方向都要复位,否则
// "弹出 → 合并回主窗"往返后 guard 跳过 re-attach,终端失活。
markAllPtyDetached();
- invalidateSessionCaches();
+ resetCachesForHostTransition();
} else {
markAllPtyDetached();
- invalidateSessionCaches();
+ resetCachesForHostTransition();
const sessionId = rightSidebarSessionIdRef.current;
if (sessionId) {
writeCollapsedFor(sessionId, false);
@@ -933,7 +945,11 @@ export function MainLayout() {
const handleDetachRightSidebar = useCallback(() => {
if (isSecondaryWindow()) return;
writeCollapsedFor(rightSidebarSessionId, false);
- void window.electronAPI.rightSidebarWindow.setDetached(true).catch(() => undefined);
+ const snapshot = getTabSnapshot(rightSidebarSessionId);
+ const handoff = snapshot ? { snapshots: [snapshot] } : undefined;
+ void window.electronAPI.rightSidebarWindow
+ .setDetached(true, handoff)
+ .catch(() => undefined);
}, [rightSidebarSessionId]);
const handlePageZoomIn = useCallback(() => {
diff --git a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
index a0af9f56f0..0e0db3c119 100644
--- a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
@@ -35,6 +35,8 @@ import { executeSidebarCommand } from '@/features/right-sidebar/lib/executeSideb
import {
closeTab,
getBucket,
+ getTabSnapshot,
+ importTabSnapshot,
} from '@/features/right-sidebar/store';
import { WindowControls } from '@/components/title-bar/WindowControls';
import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';
@@ -98,6 +100,11 @@ export function SidebarWindowLayout() {
contextRevisionRef.current += 1;
setCtx(next);
});
+ // 必须早于 presentationReady() 注册:冷分离窗的主窗快照由 main 在
+ // presentation-ready 回调中投递,晚注册会丢掉这条一次性 handoff。
+ const offTabHandoff = window.electronAPI.rightSidebarWindow.onTabHandoff((handoff) => {
+ for (const snapshot of handoff.snapshots) importTabSnapshot(snapshot);
+ });
// renderer-ready:Shell 已挂载,controller 可知 React 组件树就绪。
void window.electronAPI.rightSidebarWindow.rendererReady().catch((err) => {
log.warn('renderer-ready handshake failed', err);
@@ -105,6 +112,7 @@ export function SidebarWindowLayout() {
return () => {
cancelled = true;
offCtx();
+ offTabHandoff();
};
}, []);
@@ -280,7 +288,9 @@ export function SidebarWindowLayout() {
{/* 合并回主窗口:关偏好 + 关本窗,主窗恢复内嵌展开 */}
<ChromeIconButton
onClick={() => {
- void window.electronAPI.rightSidebarWindow.setDetached(false).catch((err) => {
+ const snapshot = getTabSnapshot(interactiveSessionId);
+ const handoff = snapshot ? { snapshots: [snapshot] } : undefined;
+ void window.electronAPI.rightSidebarWindow.setDetached(false, handoff).catch((err) => {
log.warn('merge back failed', err);
});
}}
diff --git a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
index ab748d5dfd..f52c749718 100644
--- a/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
+++ b/apps/desktop/src/renderer/components/layout/__tests__/ReusableWindowChrome.test.tsx
@@ -7,6 +7,9 @@ import type { RsbWindowContext } from '../../../../shared/rightSidebarWindow';
const mocks = vi.hoisted(() => ({
controlsMounts: 0,
sidebarVisibilityListener: null as ((payload: { visible: boolean }) => void) | null,
+ sidebarTabHandoffListener: null as
+ | ((handoff: import('../../../../shared/rightSidebarWindow').RsbWindowTabHandoff) => void)
+ | null,
ghostVisibilityListener: null as ((payload: { visible: boolean }) => void) | null,
ghostMinimizeListener: null as (() => void) | null,
ghostMinimizeEnabled: true,
@@ -16,6 +19,7 @@ const mocks = vi.hoisted(() => ({
sidebarLightboxMounts: 0,
sidebarLightboxMountId: undefined as number | undefined,
initGlobalListeners: vi.fn(),
+ importTabSnapshot: vi.fn(),
minimizeGhostPanel: vi.fn(),
restoreGhostPanel: vi.fn(),
}));
@@ -67,6 +71,8 @@ vi.mock('@/features/right-sidebar/lib/executeSidebarCommand', () => ({
vi.mock('@/features/right-sidebar/store', () => ({
closeTab: vi.fn(),
getBucket: () => ({ activeTabId: null }),
+ getTabSnapshot: vi.fn(() => null),
+ importTabSnapshot: mocks.importTabSnapshot,
}));
vi.mock('@/cindy-brain/ghostPanels', () => ({
ensureGhostPanelsRegistered: vi.fn(),
@@ -143,6 +149,7 @@ describe('reusable auxiliary window chrome', () => {
vi.clearAllMocks();
mocks.controlsMounts = 0;
mocks.sidebarVisibilityListener = null;
+ mocks.sidebarTabHandoffListener = null;
mocks.ghostVisibilityListener = null;
mocks.ghostMinimizeListener = null;
mocks.ghostMinimizeEnabled = true;
@@ -165,6 +172,10 @@ describe('reusable auxiliary window chrome', () => {
}),
),
onContextChanged: vi.fn(() => vi.fn()),
+ onTabHandoff: vi.fn((listener) => {
+ mocks.sidebarTabHandoffListener = listener;
+ return vi.fn();
+ }),
rendererReady: vi.fn(() => Promise.resolve()),
presentationReady: vi.fn(() => Promise.resolve()),
onVisibilityChanged: vi.fn((listener) => {
@@ -223,6 +234,29 @@ describe('reusable auxiliary window chrome', () => {
});
});
+ it('subscribes to tab handoff before reporting presentation ready', async () => {
+ const snapshot = {
+ sessionId: 'session-a',
+ tabs: [{ id: 'tab-a', kind: 'web-browser', state: { url: 'about:blank' } }],
+ activeTabId: 'tab-a',
+ persistable: false as const,
+ };
+ window.electronAPI.rightSidebarWindow.presentationReady = vi.fn(async () => {
+ mocks.sidebarTabHandoffListener?.({ snapshots: [snapshot] });
+ });
+
+ render(<SidebarWindowLayout />);
+
+ await waitFor(() => expect(mocks.importTabSnapshot).toHaveBeenCalledWith(snapshot));
+ expect(
+ (window.electronAPI.rightSidebarWindow.onTabHandoff as ReturnType<typeof vi.fn>).mock
+ .invocationCallOrder[0],
+ ).toBeLessThan(
+ (window.electronAPI.rightSidebarWindow.presentationReady as ReturnType<typeof vi.fn>).mock
+ .invocationCallOrder[0],
+ );
+ });
+
it('remounts ghost-panel controls when the cached window is hidden', async () => {
render(<GhostPanelWindowLayout />);
const controlsBeforeHide = screen.getByTestId('window-controls');
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts
index 8c702c056c..a72680a869 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts
@@ -186,6 +186,87 @@ describe('RSB store', () => {
expect((store.getBucket('ghost-s1').tabs[0].state as { title: string }).title).toBe('Example');
});
+ it('exports and restores a memory-only bucket across host cache invalidation', async () => {
+ ipc.list.mockResolvedValueOnce({ tabs: [], activeTabId: null, persistable: false });
+ await store.ensureHydrated('handoff-s1');
+ const tab = await store.addTab('handoff-s1', 'web-browser', { url: 'https://example.com' });
+
+ const snapshot = store.getTabSnapshot('handoff-s1');
+ expect(snapshot).toEqual({
+ sessionId: 'handoff-s1',
+ tabs: [{ id: tab.id, kind: 'web-browser', state: { url: 'https://example.com' } }],
+ activeTabId: tab.id,
+ persistable: false,
+ });
+
+ store.invalidateSessionCaches();
+ store.importTabSnapshot(snapshot!);
+ store.invalidateSessionCaches();
+ await store.ensureHydrated('handoff-s1');
+
+ expect(ipc.list).toHaveBeenCalledOnce();
+ expect(store.getBucket('handoff-s1')).toEqual({
+ hydrated: true,
+ tabs: [{ id: tab.id, kind: 'web-browser', state: { url: 'https://example.com' } }],
+ activeTabId: tab.id,
+ });
+ });
+
+ it('restores a pending handoff synchronously during the target host transition', async () => {
+ ipc.list.mockResolvedValueOnce({ tabs: [], activeTabId: null, persistable: false });
+ await store.ensureHydrated('handoff-transition');
+ const tab = await store.addTab('handoff-transition', 'web-browser', {
+ url: 'https://example.com',
+ });
+ const snapshot = store.getTabSnapshot('handoff-transition');
+
+ store.invalidateSessionCaches();
+ store.importTabSnapshot(snapshot!);
+ store.resetCachesForHostTransition();
+
+ expect(store.getBucket('handoff-transition')).toEqual({
+ hydrated: true,
+ tabs: [{ id: tab.id, kind: 'web-browser', state: { url: 'https://example.com' } }],
+ activeTabId: tab.id,
+ });
+ });
+
+ it('does not let a late empty hydrate overwrite a received handoff', async () => {
+ let resolveList!: (value: {
+ tabs: never[];
+ activeTabId: null;
+ persistable: false;
+ }) => void;
+ ipc.list.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveList = resolve;
+ }),
+ );
+ const hydration = store.ensureHydrated('handoff-race');
+ const snapshot = {
+ sessionId: 'handoff-race',
+ tabs: [{ id: 'tab-a', kind: 'web-browser', state: { url: 'about:blank' } }],
+ activeTabId: 'tab-a',
+ persistable: false as const,
+ };
+
+ store.importTabSnapshot(snapshot);
+ resolveList({ tabs: [], activeTabId: null, persistable: false });
+ await hydration;
+
+ expect(store.getBucket('handoff-race')).toEqual({
+ hydrated: true,
+ tabs: snapshot.tabs,
+ activeTabId: 'tab-a',
+ });
+ });
+
+ it('does not export a persistable local-DB bucket as a renderer handoff', async () => {
+ await store.ensureHydrated('persisted-s1');
+ expect(store.getTabSnapshot('persisted-s1')).toBeNull();
+ });
+
it('sanitizes non-persistable favicons when hydrating web-browser tabs', async () => {
ipc.list.mockResolvedValueOnce({
tabs: [
diff --git a/apps/desktop/src/renderer/features/right-sidebar/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.ts
index 01b2d1b722..d8da9f6c7f 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts
@@ -27,6 +27,7 @@ import { browserWebviewPool } from './lib/browserWebviewPool';
import { unmarkPopupSpawnedTab } from './lib/popupTabs';
import { closeNativePopupForTab } from './lib/nativePopupTabs';
import type { TabKindId, TabState } from './types';
+import type { RsbWindowTabSnapshot } from '../../../shared/rightSidebarWindow';
const log = createLogger('rightSidebar.store');
@@ -47,6 +48,12 @@ const inflight = new Map<string, Promise<void>>();
const singletonInflight = new Map<string, Promise<TabState>>();
const listeners = new Set<Listener>();
const memoryOnlySessions = new Set<string>();
+/**
+ * Handoff snapshots survive the attached renderer's cache invalidation that
+ * accompanies a detached → attached transition. They are renderer-local and
+ * never persisted; a newer handoff for the same session replaces the old one.
+ */
+const pendingHandoffBuckets = new Map<string, TabBucket>();
const closeInterceptors = new Map<string, TabCloseInterceptor>();
const patchRevisions = new Map<string, number>();
/**
@@ -476,6 +483,52 @@ export function getBucket(sessionId: string | null | undefined): TabBucket {
return cache.get(sessionId) ?? EMPTY_BUCKET;
}
+/** Export the current renderer-owned tab bucket for a merge-back handoff. */
+export function getTabSnapshot(sessionId: string | null | undefined): RsbWindowTabSnapshot | null {
+ if (!sessionId) return null;
+ const bucket = cache.get(sessionId);
+ if (!bucket?.hydrated || shouldPersist(sessionId)) return null;
+ return {
+ sessionId,
+ tabs: bucket.tabs.map(({ id, kind, state }) => ({ id, kind, state })),
+ activeTabId: bucket.activeTabId,
+ persistable: false,
+ };
+}
+
+/** Import a non-persistable tab bucket received before the previous host is destroyed. */
+export function importTabSnapshot(snapshot: RsbWindowTabSnapshot): void {
+ if (snapshot.persistable || !snapshot.sessionId) return;
+ const seen = new Set<string>();
+ const tabs: TabState[] = snapshot.tabs.filter((tab) => {
+ if (!tab.id || !tab.kind || seen.has(tab.id)) return false;
+ seen.add(tab.id);
+ return true;
+ }).map((tab) => ({ ...tab, kind: tab.kind as TabKindId }));
+ const activeTabId = snapshot.activeTabId && seen.has(snapshot.activeTabId)
+ ? snapshot.activeTabId
+ : null;
+ const bucket: TabBucket = { hydrated: true, tabs, activeTabId };
+ memoryOnlySessions.add(snapshot.sessionId);
+ pendingHandoffBuckets.set(snapshot.sessionId, bucket);
+ setBucket(snapshot.sessionId, bucket);
+}
+
+/**
+ * 宿主切换时清掉旧 renderer cache,并同步恢复 main 已转发到本 renderer 的快照。
+ *
+ * React 的父 effect(MainLayout)晚于子 effect(RightSidebarShell)执行;若只 clear cache
+ * 再期待子组件重新触发 ensureHydrated,已挂载 Shell 不一定会再跑 hydration effect。
+ * 这里在同一个同步步骤里消费 pending handoff,避免合并后永久停在 EMPTY_BUCKET。
+ */
+export function resetCachesForHostTransition(): void {
+ invalidateSessionCaches();
+ for (const [sessionId, bucket] of pendingHandoffBuckets) {
+ pendingHandoffBuckets.delete(sessionId);
+ setBucket(sessionId, bucket);
+ }
+}
+
/**
* 按 tabId 反查所属 sessionId(只扫已水合进本 renderer 的 bucket)。
* guest 自关(window.close)路径用:pool 的 close 事件只带 tabId,要落到
@@ -494,6 +547,11 @@ export async function ensureHydrated(sessionId: string): Promise<void> {
if (!sessionId) return;
const current = cache.get(sessionId);
if (current?.hydrated) return;
+ const pending = pendingHandoffBuckets.get(sessionId);
+ if (pending) {
+ setBucket(sessionId, pending);
+ return;
+ }
const existing = inflight.get(sessionId);
if (existing) return existing;
const ipc = ipcApi();
@@ -503,9 +561,13 @@ export async function ensureHydrated(sessionId: string): Promise<void> {
setBucket(sessionId, { hydrated: true, tabs: [], activeTabId: null });
return;
}
+ const generation = cacheGeneration;
const promise = (async () => {
try {
const result = (await ipc.list({ sessionId })) as RightSidebarTabsListResult;
+ // 宿主迁移或 handoff 在 list IPC 期间发生时,本次结果属于旧宿主视图。
+ // 特别是 persistable:false 返回的空列表,不能覆盖 main 已转发的内存快照。
+ if (generation !== cacheGeneration || pendingHandoffBuckets.has(sessionId)) return;
if (result.persistable === false) {
markMemoryOnlySession(sessionId);
} else {
@@ -1082,6 +1144,7 @@ export function _resetStore(): void {
inflight.clear();
singletonInflight.clear();
memoryOnlySessions.clear();
+ pendingHandoffBuckets.clear();
closeInterceptors.clear();
pendingTabCreates.clear();
closeMutationQueues.clear();
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useMacFullscreen.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useMacFullscreen.test.ts
new file mode 100644
index 0000000000..0cb7d666b6
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useMacFullscreen.test.ts
@@ -0,0 +1,44 @@
+// @vitest-environment jsdom
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+
+import { useMacFullscreen } from '../useMacFullscreen';
+
+describe('useMacFullscreen', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete (window as { electronAPI?: unknown }).electronAPI;
+ });
+
+ it('does not crash when an older preload has no fullscreen bridge', () => {
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { platform: 'darwin' },
+ });
+
+ const { result } = renderHook(() => useMacFullscreen());
+
+ expect(result.current).toEqual({ isMac: true, isFullscreen: false });
+ });
+
+ it('subscribes to fullscreen changes when the bridge is available', async () => {
+ const onFullscreenChange = vi.fn(() => () => undefined);
+ const getFullscreenState = vi.fn(() => Promise.resolve(true));
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ platform: 'darwin',
+ onFullscreenChange,
+ getFullscreenState,
+ },
+ });
+
+ const { result } = renderHook(() => useMacFullscreen());
+
+ expect(getFullscreenState).toHaveBeenCalledOnce();
+ expect(onFullscreenChange).toHaveBeenCalledOnce();
+ await act(async () => undefined);
+ expect(result.current.isFullscreen).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useMacFullscreen.ts b/apps/desktop/src/renderer/hooks/useMacFullscreen.ts
index 69b9518b5f..5245efab59 100644
--- a/apps/desktop/src/renderer/hooks/useMacFullscreen.ts
+++ b/apps/desktop/src/renderer/hooks/useMacFullscreen.ts
@@ -24,7 +24,10 @@ export function useMacFullscreen(): { isMac: boolean; isFullscreen: boolean } {
window.electronAPI?.getFullscreenState?.().then((fs) => {
if (!cancelled) setIsFullscreen(fs);
});
- const unsub = window.electronAPI?.onFullscreenChange((fs: boolean) => {
+ // Older packaged preload scripts (or a renderer/preload mismatch during an
+ // update) may not expose the fullscreen bridge yet. The layout can safely
+ // fall back to the non-fullscreen spacing; it must not crash the window.
+ const unsub = window.electronAPI?.onFullscreenChange?.((fs: boolean) => {
setIsFullscreen(fs);
});
return () => {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index f18ef37443..b844bcffad 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1806,6 +1806,7 @@ interface ElectronAPI {
/** 写偏好;true 附带开窗,false 附带关窗。返回新 state。 */
setDetached: (
detached: boolean,
+ handoff?: import('../shared/rightSidebarWindow').RsbWindowTabHandoff,
) => Promise<{ detached: boolean; lastOpen: boolean; open: boolean }>;
/** 子窗口 mount 时拉主窗上报的渲染上下文(main 缓存的最后一份)。 */
getContext: () => Promise<{
@@ -1844,6 +1845,9 @@ interface ElectronAPI {
available: boolean;
}) => void,
) => () => void;
+ onTabHandoff: (
+ callback: (handoff: import('../shared/rightSidebarWindow').RsbWindowTabHandoff) => void,
+ ) => () => void;
onCommand: (cb: (cmd: RsbWindowCommand) => void) => () => void;
};
diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.ts
index ce09618c72..d9a23a0dbd 100644
--- a/apps/desktop/src/shared/rightSidebarWindow.ts
+++ b/apps/desktop/src/shared/rightSidebarWindow.ts
@@ -111,6 +111,23 @@ export type RsbWindowCommandRouteResult =
| 'queued'
| 'stale-context';
+/**
+ * 主 renderer 与分离侧栏 renderer 切换宿主时双向交接的内存态 tab 快照。
+ *
+ * 只用于 persistable=false 的 session。普通本地 session 的权威来源仍是
+ * SQLite,避免用子窗口里可能过期的 renderer 快照覆盖持久化真相。
+ */
+export interface RsbWindowTabSnapshot {
+ sessionId: string;
+ tabs: Array<{ id: string; kind: string; state: unknown }>;
+ activeTabId: string | null;
+ persistable: boolean;
+}
+
+export interface RsbWindowTabHandoff {
+ snapshots: RsbWindowTabSnapshot[];
+}
+
// ── 预热/就绪/隐藏复用 IPC channel 常量 ──────────────────────────────
// renderer → main(invoke):轻量窗口根组件已经挂载(Renderer shell 可展示)。
export const RSB_WINDOW_RENDERER_READY_CHANNEL = 'rsb-window:renderer-ready';
@@ -121,3 +138,5 @@ export const RSB_WINDOW_VISIBILITY_CHANGED_CHANNEL = 'rsb-window:visibility-chan
// 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';
+/** main → 主 renderer:合并前交接不可持久化 session 的 tab 快照。 */
+export const RSB_WINDOW_TAB_HANDOFF_CHANNEL = 'maker:rsb-window:tab-handoff';