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(browser): 保留 OAuth 弹窗浏览上下文 (#1690)

Dash44eff0d13a62
diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.ts
index 04413738a4..e7c86b0f32 100644
--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts
@@ -22,6 +22,13 @@ vi.mock('electron', () => ({
},
}));
+const nativePopupWebContentsIds = vi.hoisted(() => new Set<number>());
+
+vi.mock('../rsb-browser-bridge/native-popup-surfaces', () => ({
+ isRsbNativePopupWebContentsId: (webContentsId: number) =>
+ nativePopupWebContentsIds.has(webContentsId),
+}));
+
const mocks = vi.hoisted(() => ({
logger: {
info: vi.fn(),
@@ -392,6 +399,7 @@ describe('armShutdownHardKillWatchdog', () => {
describe('installQuitHandler render-process-gone', () => {
beforeEach(() => {
vi.clearAllMocks();
+ nativePopupWebContentsIds.clear();
});
type RenderGoneHandler = (
@@ -445,6 +453,22 @@ describe('installQuitHandler render-process-gone', () => {
}
});
+ it('main-owned popup crash does NOT shut the app down', async () => {
+ nativePopupWebContentsIds.add(43);
+ const { handler, app, restore } = await installAndGrabHandler();
+ try {
+ handler(undefined, { id: 43, 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('native popup render-process-gone'),
+ );
+ expect(mocks.logger.error).not.toHaveBeenCalled();
+ } 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/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.ts
index 44e195e579..4b525acac7 100644
--- a/apps/desktop/src/main/__tests__/webview-security.test.ts
+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts
@@ -22,6 +22,16 @@ import { EventEmitter } from 'node:events';
import type { BrowserWindow, WebContents } from 'electron';
import { afterEach, describe, expect, it, vi } from 'vitest';
+const nativeSurfaceMocks = vi.hoisted(() => ({
+ create: vi.fn(() => 'surface-oauth'),
+ attribute: vi.fn(),
+}));
+
+vi.mock('../rsb-browser-bridge/native-popup-surfaces', () => ({
+ createRsbNativePopupSurface: nativeSurfaceMocks.create,
+ attributeRsbNativePopupSurface: nativeSurfaceMocks.attribute,
+}));
+
import { BROWSER_PARTITION } from '../../shared/webviewPartition';
import { getEffectiveAppShortcuts, type AppShortcutId } from '../../shared/appShortcuts';
import {
@@ -34,6 +44,7 @@ import {
RSB_BROWSER_POPUP_CHANNEL,
applyGhostWebviewHardening,
applyWebviewHardening,
+ installBrowserGuestHandlers,
installDeferredPopupRouter,
isGuestShortcutKeyDownType,
resolveGuestShortcutAction,
@@ -162,11 +173,11 @@ describe('applyWebviewHardening', () => {
});
});
-describe('BLANK_POPUP_WINDOW_WEB_PREFERENCES(about:blank 中转窗口安全集)', () => {
+describe('BLANK_POPUP_WINDOW_WEB_PREFERENCES(popup WebContents 安全集)', () => {
it('覆盖仓库 BrowserWindow 安全契约的全部显式字段', () => {
// docs/dev-rules/electron-security-and-process-boundaries.md 第 3 节:新增
- // BrowserWindow 必须显式配置的清单。隐藏中转窗口同样是真实 BrowserWindow,
- // 少一个字段就是比主窗宽松的例外。enableBlinkFeatures 的契约是"不设置",
+ // popup WebContents 必须显式配置的清单。少一个字段就是比主窗宽松的例外。
+ // enableBlinkFeatures 的契约是"不设置",
// 一并断言不存在。
expect(BLANK_POPUP_WINDOW_WEB_PREFERENCES).toMatchObject({
sandbox: true,
@@ -186,6 +197,75 @@ describe('BLANK_POPUP_WINDOW_WEB_PREFERENCES(about:blank 中转窗口安全集)'
});
});
+describe('installBrowserGuestHandlers(main-owned popup)', () => {
+ afterEach(() => {
+ nativeSurfaceMocks.create.mockClear();
+ nativeSurfaceMocks.attribute.mockClear();
+ setRsbPopupOpenerResolver(null);
+ setRsbPopupHostResolver(null);
+ });
+
+ function makeContents(id: number) {
+ let openHandler: ((details: { url: string; disposition: string }) => unknown) | null = null;
+ const contents = new EventEmitter() as EventEmitter & {
+ id: number;
+ isDestroyed: () => boolean;
+ send: ReturnType<typeof vi.fn>;
+ close: ReturnType<typeof vi.fn>;
+ setWindowOpenHandler: ReturnType<typeof vi.fn>;
+ getOpenHandler: () => typeof openHandler;
+ };
+ contents.id = id;
+ contents.isDestroyed = () => false;
+ contents.send = vi.fn();
+ contents.close = vi.fn();
+ contents.setWindowOpenHandler = vi.fn((handler) => {
+ openHandler = handler;
+ });
+ contents.getOpenHandler = () => openHandler;
+ return contents;
+ }
+
+ it.each([
+ ['direct URL', 'https://accounts.example.com/oauth'],
+ ['about:blank', 'about:blank'],
+ ])('adopts Electron pre-created WebContents for %s', (_label, url) => {
+ const host = makeContents(1);
+ const opener = makeContents(42);
+ const popup = makeContents(43);
+ installBrowserGuestHandlers(host as never, opener as never);
+
+ const response = opener.getOpenHandler()!({ url, disposition: 'foreground-tab' }) as {
+ action: string;
+ outlivesOpener: boolean;
+ overrideBrowserWindowOptions: { webPreferences: Record<string, unknown> };
+ createWindow: (options: { webContents: WebContents }) => WebContents;
+ };
+ expect(response.action).toBe('allow');
+ expect(response.outlivesOpener).toBe(false);
+ expect(response.overrideBrowserWindowOptions.webPreferences).toMatchObject({
+ sandbox: true,
+ nodeIntegration: false,
+ contextIsolation: true,
+ webSecurity: true,
+ partition: BROWSER_PARTITION,
+ webviewTag: false,
+ });
+
+ const returned = response.createWindow({ webContents: popup as never });
+ expect(returned).toBe(popup);
+ expect(nativeSurfaceMocks.create).toHaveBeenCalledWith(host, popup);
+ // Nested popup handler is installed on the adopted child too.
+ expect(popup.setWindowOpenHandler).toHaveBeenCalledOnce();
+ expect(host.send).toHaveBeenCalledWith(RSB_BROWSER_POPUP_CHANNEL, {
+ url,
+ disposition: 'foreground-tab',
+ nativePopupSurfaceId: 'surface-oauth',
+ });
+ expect(popup.close).not.toHaveBeenCalled();
+ });
+});
+
describe('applyGhostWebviewHardening(意识面板 webview)', () => {
it('同一套安全锁全部生效,但保留意识专属分区、掐死 popup', () => {
const webPreferences: Record<string, unknown> = {
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3ae15f2740..66643657ae 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -187,6 +187,11 @@ import {
registerRsbBrowserBridgeIpc,
registerTabOpResultHandler,
} from './rsb-browser-bridge';
+import {
+ getRsbNativePopupOwnerWebContents,
+ hasActiveRsbNativePopupSurfaces,
+ registerRsbNativePopupSurfaceIpc,
+} from './rsb-browser-bridge/native-popup-surfaces.js';
import { disposeAndroidAdb } from './mcp-integrations/android.js';
import { shutdownCodexEnvironment } from './mcp-integrations/codexEnvironment.js';
import { shutdownPiEnvironment } from './mcp-integrations/piEnvironment.js';
@@ -1172,6 +1177,7 @@ const rsbWindowController = new RsbWindowController({
contextChannel: MAKER_PUSH.RSB_WINDOW_CONTEXT_CHANGED,
commandChannel: MAKER_PUSH.RSB_WINDOW_COMMAND,
isQuitting: () => isQuitting,
+ canCloseWindow: () => !hasActiveRsbNativePopupSurfaces(),
log: createLogger('right-sidebar-window-controller'),
});
registerRsbWindowIpc({
@@ -1225,9 +1231,12 @@ const ghostPanelWindowsController = new GhostPanelWindowsController({
registerGhostPanelWindowIpc(ghostPanelWindowsController);
setGhostsChangedObserver((ghosts) => ghostPanelWindowsController.reconcile(ghosts));
+const rsbBrowserRegistry = getRsbBrowserBridge();
+registerRsbNativePopupSurfaceIpc(rsbBrowserRegistry);
registerRsbBrowserBridgeIpc({
- registry: getRsbBrowserBridge(),
+ registry: rsbBrowserRegistry,
getHostWebContents: () => rsbWindowController.getHostWebContents(),
+ getNativePopupOwnerWebContents: getRsbNativePopupOwnerWebContents,
logger: createLogger('rsb-browser-bridge-bootstrap'),
});
// popup opener 反查:webview-security 的 popup 路由据此把 window.open 的目标
diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.ts
index 6f5a9aa522..a7a87ffa13 100644
--- a/apps/desktop/src/main/lifecycle.ts
+++ b/apps/desktop/src/main/lifecycle.ts
@@ -45,6 +45,7 @@ import {
} from './logger';
import { noteQuitDisposersCompleted, noteShutdownBegin } from './startup-diagnostics';
import { isGhostSandboxWebContentsId } from './cindy-brain/runtime/electronSandboxAdapter';
+import { isRsbNativePopupWebContentsId } from './rsb-browser-bridge/native-popup-surfaces';
/**
* 瞬时网络错误的 wire payload (main → renderer)。code 永远存在 (Node 的 ErrnoException
@@ -471,6 +472,8 @@ export function installQuitHandler(timeoutMs = 2000): void {
// renderer 侧 useBrowserWebview 已有 crash banner + reload 恢复链路。此前
// 这里不区分 guest,网页死递归吃满内存被 OOM kill 时会把整个 App 一起带走
// (VS Code / Cursor 的边界都是 guest 崩溃不退 Workbench)。
+ // 例外 3:RSB popup 虽然是 `window` 类型,但它是局部网页 surface;崩溃时由
+ // native popup manager 回收并让对应 tab 展示恢复态,不能拖垮主窗口。
app.on('render-process-gone', (_event, webContents, details) => {
if (isGhostSandboxWebContentsId(webContents.id)) {
log.warn(
@@ -484,6 +487,12 @@ export function installQuitHandler(timeoutMs = 2000): void {
);
return;
}
+ if (isRsbNativePopupWebContentsId(webContents.id)) {
+ log.warn(
+ `native popup render-process-gone (isolated, no shutdown): reason=${details.reason} exitCode=${details.exitCode}`,
+ );
+ return;
+ }
// arm-first(review P1):沙箱/webview 两个不退出的分支在上面已 return,
// 走到这里必然退出。
armShutdownHardKillWatchdog();
diff --git a/apps/desktop/src/main/right-sidebar-window/controller.ts b/apps/desktop/src/main/right-sidebar-window/controller.ts
index 5d77b3269b..f2415a3eb8 100644
--- a/apps/desktop/src/main/right-sidebar-window/controller.ts
+++ b/apps/desktop/src/main/right-sidebar-window/controller.ts
@@ -52,6 +52,8 @@ export interface RsbWindowControllerDeps {
contextChannel: string;
commandChannel: string;
isQuitting: () => boolean;
+ /** Popup WindowProxy depends on the ordinary webview opener staying alive. */
+ canCloseWindow?: () => boolean;
log: ControllerLogger;
}
@@ -107,6 +109,12 @@ export class RsbWindowController {
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.broadcast();
diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.ts
index c8d8bc3daa..e85e35e1f8 100644
--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts
+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts
@@ -18,6 +18,7 @@ import type {
RsbWindowContext,
} 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';
const log = createLogger('right-sidebar-window-ipc');
@@ -173,6 +174,9 @@ export function registerRsbWindowIpc(opts: {
});
ipcMain.handle(MAKER_INVOKE.RSB_WINDOW_CLOSE, () => {
+ if (hasActiveRsbNativePopupSurfaces()) {
+ throwIpcError('PRECONDITION_FAILED', 'active browser popup must be completed or closed first');
+ }
controller.close();
});
@@ -180,6 +184,9 @@ export function registerRsbWindowIpc(opts: {
if (typeof detached !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'detached required (boolean)');
}
+ if (detached !== controller.getState().detached && hasActiveRsbNativePopupSurfaces()) {
+ throwIpcError('PRECONDITION_FAILED', 'active browser popup must be completed or closed first');
+ }
return controller.setDetached(detached);
});
diff --git a/apps/desktop/src/main/rsb-browser-bridge/__tests__/native-popup-surfaces.test.ts b/apps/desktop/src/main/rsb-browser-bridge/__tests__/native-popup-surfaces.test.ts
new file mode 100644
index 0000000000..f622a2ac2e
--- /dev/null
+++ b/apps/desktop/src/main/rsb-browser-bridge/__tests__/native-popup-surfaces.test.ts
@@ -0,0 +1,350 @@
+import { EventEmitter } from 'node:events';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const electronMocks = vi.hoisted(() => {
+ const handlers = new Map<string, (event: unknown, input: unknown) => unknown>();
+ const windows = new Map<object, object>();
+ const views: Array<{
+ webContents: object;
+ bounds: object | null;
+ visible: boolean;
+ setBounds: ReturnType<typeof vi.fn>;
+ setVisible: ReturnType<typeof vi.fn>;
+ }> = [];
+ return { handlers, windows, views };
+});
+
+vi.mock('electron', () => ({
+ ipcMain: {
+ handle: vi.fn((channel: string, handler: (event: unknown, input: unknown) => unknown) => {
+ electronMocks.handlers.set(channel, handler);
+ }),
+ },
+ BrowserWindow: {
+ fromWebContents: vi.fn((contents: object) => electronMocks.windows.get(contents) ?? null),
+ },
+ WebContentsView: class {
+ webContents: object;
+ bounds: object | null = null;
+ visible = true;
+ setBounds = vi.fn((bounds: object) => {
+ this.bounds = bounds;
+ });
+ setVisible = vi.fn((visible: boolean) => {
+ this.visible = visible;
+ });
+ constructor(options: { webContents: object }) {
+ this.webContents = options.webContents;
+ electronMocks.views.push(this);
+ }
+ },
+}));
+
+vi.mock('../../security/trustedAppRenderer', () => ({
+ assertTrustedAppRendererEvent: vi.fn(),
+}));
+
+import {
+ RSB_NATIVE_POPUP_CLAIM_CHANNEL,
+ RSB_NATIVE_POPUP_CLOSE_CHANNEL,
+ RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL,
+} from '../../../shared/rsbNativePopup';
+import {
+ _resetRsbNativePopupSurfacesForTests,
+ RSB_NATIVE_POPUP_CLAIM_TIMEOUT_MS,
+ attributeRsbNativePopupSurface,
+ createRsbNativePopupSurface,
+ getRsbNativePopupOwnerWebContents,
+ hasActiveRsbNativePopupSurfaces,
+ isRsbNativePopupWebContentsId,
+ registerRsbNativePopupSurfaceIpc,
+} from '../native-popup-surfaces';
+
+function makeContents(id: number) {
+ const contents = new EventEmitter() as EventEmitter & {
+ id: number;
+ destroyed: boolean;
+ sent: Array<{ channel: string; payload: unknown }>;
+ isDestroyed: () => boolean;
+ send: (channel: string, payload: unknown) => void;
+ close: () => void;
+ getURL: () => string;
+ getTitle: () => string;
+ isLoading: () => boolean;
+ canGoBack: () => boolean;
+ canGoForward: () => boolean;
+ isCurrentlyAudible: () => boolean;
+ getZoomFactor: () => number;
+ };
+ contents.id = id;
+ contents.destroyed = false;
+ contents.sent = [];
+ contents.isDestroyed = () => contents.destroyed;
+ contents.send = (channel, payload) => contents.sent.push({ channel, payload });
+ contents.close = vi.fn(() => {
+ if (contents.destroyed) return;
+ contents.destroyed = true;
+ contents.emit('destroyed');
+ });
+ contents.getURL = () => 'https://accounts.example.test/authorize';
+ contents.getTitle = () => 'Authorize';
+ contents.isLoading = () => false;
+ contents.canGoBack = () => true;
+ contents.canGoForward = () => false;
+ contents.isCurrentlyAudible = () => false;
+ contents.getZoomFactor = () => 1;
+ return contents;
+}
+
+function makeWindow() {
+ const children = new Set<object>();
+ return {
+ isDestroyed: () => false,
+ getContentBounds: () => ({ x: 0, y: 0, width: 1200, height: 800 }),
+ contentView: {
+ addChildView: vi.fn((view: object) => children.add(view)),
+ removeChildView: vi.fn((view: object) => children.delete(view)),
+ },
+ children,
+ };
+}
+
+describe('main-owned RSB native popup surfaces', () => {
+ const report = vi.fn();
+ const release = vi.fn();
+ const pinReleases: Array<ReturnType<typeof vi.fn>> = [];
+ const registry = {
+ report,
+ release,
+ acquirePinLease: vi.fn(() => {
+ const fn = vi.fn();
+ pinReleases.push(fn);
+ return fn;
+ }),
+ };
+
+ beforeEach(() => {
+ electronMocks.handlers.clear();
+ electronMocks.windows.clear();
+ electronMocks.views.length = 0;
+ report.mockReset();
+ release.mockReset();
+ registry.acquirePinLease.mockClear();
+ pinReleases.length = 0;
+ registerRsbNativePopupSurfaceIpc(registry as never);
+ });
+
+ afterEach(() => {
+ _resetRsbNativePopupSurfacesForTests();
+ vi.useRealTimers();
+ });
+
+ it('adopts the exact popup WebContents, claims it, and applies renderer bounds', async () => {
+ const host = makeContents(1);
+ const popup = makeContents(42);
+ const hostWindow = makeWindow();
+ electronMocks.windows.set(host, hostWindow);
+
+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never);
+ expect(surfaceId).toBeTypeOf('string');
+ expect(electronMocks.views[0]?.webContents).toBe(popup);
+ expect(hasActiveRsbNativePopupSurfaces()).toBe(true);
+ expect(isRsbNativePopupWebContentsId(42)).toBe(true);
+
+ const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;
+ const claimed = await claim(
+ { sender: host },
+ { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' },
+ );
+ expect(claimed).toMatchObject({
+ alive: true,
+ snapshot: { url: 'https://accounts.example.test/authorize', title: 'Authorize' },
+ });
+ expect(report).toHaveBeenCalledWith({
+ sessionId: 'session-a',
+ tabId: 'tab-popup',
+ webContentsId: 42,
+ });
+ expect(getRsbNativePopupOwnerWebContents(42)).toBe(host);
+
+ const setBounds = electronMocks.handlers.get(RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL)!;
+ await setBounds(
+ { sender: host },
+ {
+ surfaceId,
+ bounds: { x: 10, y: 50, width: 600, height: 400 },
+ visible: true,
+ },
+ );
+ expect(electronMocks.views[0]?.bounds).toEqual({ x: 10, y: 50, width: 600, height: 400 });
+ expect(electronMocks.views[0]?.visible).toBe(true);
+ });
+
+ it('publishes null when a favicon update has no usable URL', async () => {
+ const host = makeContents(1);
+ const popup = makeContents(42);
+ electronMocks.windows.set(host, makeWindow());
+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;
+ const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;
+ await claim({ sender: host }, { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' });
+
+ popup.emit('page-favicon-updated', {}, ['', ' ']);
+
+ expect(host.sent.at(-1)).toEqual({
+ channel: 'rsb-native-popup:event',
+ payload: {
+ surfaceId,
+ type: 'state',
+ snapshot: expect.objectContaining({ favicon: null }),
+ },
+ });
+ });
+
+ it('pins opener and popup, rejects a foreign owner, and closes idempotently', async () => {
+ const host = makeContents(1);
+ const foreign = makeContents(3);
+ const popup = makeContents(42);
+ const hostWindow = makeWindow();
+ electronMocks.windows.set(host, hostWindow);
+ electronMocks.windows.set(foreign, makeWindow());
+
+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;
+ attributeRsbNativePopupSurface(surfaceId, { tabId: 'tab-opener' });
+ const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;
+ expect(() =>
+ claim({ sender: foreign }, { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' }),
+ ).toThrow(/PERMISSION_DENIED/);
+ await claim({ sender: host }, { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' });
+ expect(registry.acquirePinLease).toHaveBeenCalledTimes(2);
+
+ const setBounds = electronMocks.handlers.get(RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL)!;
+ expect(() =>
+ setBounds(
+ { sender: foreign },
+ { surfaceId, bounds: { x: 0, y: 0, width: 10, height: 10 }, visible: true },
+ ),
+ ).toThrow(/PERMISSION_DENIED/);
+
+ const close = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLOSE_CHANNEL)!;
+ await close({ sender: host }, { surfaceId });
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(release).toHaveBeenCalledWith('tab-popup', 42);
+ expect(pinReleases.every((fn) => fn.mock.calls.length === 1)).toBe(true);
+ expect(hasActiveRsbNativePopupSurfaces()).toBe(false);
+ expect(isRsbNativePopupWebContentsId(42)).toBe(false);
+
+ expect(close({ sender: host }, { surfaceId })).toEqual({ ok: true });
+ expect(popup.close).toHaveBeenCalledOnce();
+ });
+
+ it('scales renderer CSS bounds into owner-window DIPs at non-default zoom', async () => {
+ const host = makeContents(1);
+ host.getZoomFactor = () => 1.25;
+ const popup = makeContents(42);
+ electronMocks.windows.set(host, makeWindow());
+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;
+ const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;
+ await claim({ sender: host }, { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' });
+
+ const setBounds = electronMocks.handlers.get(RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL)!;
+ await setBounds(
+ { sender: host },
+ {
+ surfaceId,
+ bounds: { x: 8, y: 40, width: 600, height: 400 },
+ visible: true,
+ },
+ );
+
+ expect(electronMocks.views[0]?.bounds).toEqual({ x: 10, y: 50, width: 750, height: 500 });
+ });
+
+ it('closes a claimed surface when its creating renderer is destroyed', async () => {
+ const host = makeContents(1);
+ const popup = makeContents(42);
+ electronMocks.windows.set(host, makeWindow());
+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;
+ const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;
+ await claim({ sender: host }, { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' });
+
+ host.close();
+
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(release).toHaveBeenCalledWith('tab-popup', 42);
+ expect(hasActiveRsbNativePopupSurfaces()).toBe(false);
+ });
+
+ it('closes a claimed surface when the owner renderer begins a full reload', async () => {
+ const host = makeContents(1);
+ const popup = makeContents(42);
+ electronMocks.windows.set(host, makeWindow());
+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;
+ const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;
+ await claim(
+ { sender: host },
+ { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' },
+ );
+
+ host.emit('did-start-navigation', {}, 'file:///app/index.html', false, true);
+
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(release).toHaveBeenCalledWith('tab-popup', 42);
+ expect(hasActiveRsbNativePopupSurfaces()).toBe(false);
+ });
+
+ it('disposes a popup that is never claimed by a renderer tab', () => {
+ vi.useFakeTimers();
+ const host = makeContents(1);
+ const popup = makeContents(42);
+ electronMocks.windows.set(host, makeWindow());
+
+ createRsbNativePopupSurface(host as never, popup as never);
+ vi.advanceTimersByTime(RSB_NATIVE_POPUP_CLAIM_TIMEOUT_MS);
+
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(hasActiveRsbNativePopupSurfaces()).toBe(false);
+ });
+
+ it('lets the creating renderer dispose a surface before it is claimed', async () => {
+ const host = makeContents(1);
+ const popup = makeContents(42);
+ electronMocks.windows.set(host, makeWindow());
+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;
+
+ const close = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLOSE_CHANNEL)!;
+ await close({ sender: host }, { surfaceId });
+
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(hasActiveRsbNativePopupSurfaces()).toBe(false);
+ });
+
+ it('reports guest window.close to the claimed renderer and drops registry ownership', async () => {
+ const host = makeContents(1);
+ const popup = makeContents(42);
+ const hostWindow = makeWindow();
+ electronMocks.windows.set(host, hostWindow);
+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;
+ const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;
+ await claim({ sender: host }, { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' });
+
+ popup.close();
+
+ expect(host.sent).toContainEqual({
+ channel: 'rsb-native-popup:event',
+ payload: { surfaceId, type: 'closed' },
+ });
+ expect(release).toHaveBeenCalledWith('tab-popup', 42);
+ expect(getRsbNativePopupOwnerWebContents(42)).toBeNull();
+
+ const setBounds = electronMocks.handlers.get(RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL)!;
+ expect(
+ setBounds(
+ { sender: host },
+ { surfaceId, bounds: { x: 0, y: 0, width: 10, height: 10 }, visible: false },
+ ),
+ ).toEqual({ ok: true });
+ const close = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLOSE_CHANNEL)!;
+ expect(close({ sender: host }, { surfaceId })).toEqual({ ok: true });
+ });
+});
diff --git a/apps/desktop/src/main/rsb-browser-bridge/ipc.ts b/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
index b20c7d92fd..366a2d1217 100644
--- a/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
+++ b/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
@@ -62,6 +62,8 @@ export interface RegisterRsbBrowserBridgeOptions {
* futures this becomes a "all main-window renderers" fan-out.
*/
getHostWebContents: () => WebContents | null;
+ /** Main-owned popup WebContents do not expose webview.hostWebContents. */
+ getNativePopupOwnerWebContents?: (webContentsId: number) => WebContents | null;
logger: IpcLogger;
}
@@ -80,7 +82,22 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
}
registered = true;
- const { registry, getHostWebContents, logger } = opts;
+ const { registry, getHostWebContents, getNativePopupOwnerWebContents, logger } = opts;
+
+ const resolveOwner = (target: WebContents): WebContents | null => {
+ const webviewHost = (
+ target as unknown as {
+ hostWebContents?: WebContents & { isDestroyed?: () => boolean };
+ }
+ ).hostWebContents;
+ if (
+ webviewHost &&
+ (typeof webviewHost.isDestroyed !== 'function' || !webviewHost.isDestroyed())
+ ) {
+ return webviewHost;
+ }
+ return getNativePopupOwnerWebContents?.(target.id) ?? null;
+ };
ipcMain.handle(RSB_BROWSER_BRIDGE_REPORT_CHANNEL, (event, payload: unknown) => {
const obj = requireObject(payload, 'report payload');
@@ -113,7 +130,7 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
);
}
// hostWebContents is non-standard but exposed; cast for the typing gap.
- const host = (target as unknown as { hostWebContents?: WebContents }).hostWebContents;
+ const host = resolveOwner(target);
if (!host || host.id !== event.sender.id) {
throwIpcError(
'INVALID_PARAMS',
@@ -187,7 +204,7 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
if (!target) {
throwIpcError('NOT_FOUND', `no live webContents for tab ${tabId}`);
}
- const host = (target as unknown as { hostWebContents?: WebContents }).hostWebContents;
+ const host = resolveOwner(target);
if (!host || host.id !== event.sender.id) {
throwIpcError('INVALID_PARAMS', `tab ${tabId} is not hosted by the sender`);
}
@@ -271,7 +288,7 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
if (!target) {
throwIpcError('NOT_FOUND', `no live webContents for tab ${tabId}`);
}
- const host = (target as unknown as { hostWebContents?: WebContents }).hostWebContents;
+ const host = resolveOwner(target);
if (!host || host.id !== event.sender.id) {
throwIpcError('INVALID_PARAMS', `tab ${tabId} is not hosted by the sender`);
}
@@ -293,9 +310,7 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
// cpu-alert 无人消费,还会掩盖问题)。
const sendResourceEvent = (event: RsbBrowserBridgeResourceEvent) => {
const guest = registry.getWebContentsByTabId(event.tabId);
- const owner = guest
- ? (guest as unknown as { hostWebContents?: WebContents }).hostWebContents
- : null;
+ const owner = guest ? resolveOwner(guest) : null;
const wc = pickResourceEventTarget(owner);
if (!wc) return;
wc.send(RSB_BROWSER_BRIDGE_RESOURCE_EVENT_CHANNEL, event);
@@ -310,9 +325,7 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
// 无归属版本 —— 此时该 tab 也不在 listTabs 里,不会被误处置。
isForeground: (tabId) => {
const guest = registry.getWebContentsByTabId(tabId);
- const owner = guest
- ? (guest as unknown as { hostWebContents?: WebContents }).hostWebContents
- : null;
+ const owner = guest ? resolveOwner(guest) : null;
return owner
? foregroundTracker.isForegroundFor(tabId, owner.id)
: foregroundTracker.isForeground(tabId);
diff --git a/apps/desktop/src/main/rsb-browser-bridge/native-popup-surfaces.ts b/apps/desktop/src/main/rsb-browser-bridge/native-popup-surfaces.ts
new file mode 100644
index 0000000000..2d0c806d93
--- /dev/null
+++ b/apps/desktop/src/main/rsb-browser-bridge/native-popup-surfaces.ts
@@ -0,0 +1,463 @@
+import { randomUUID } from 'node:crypto';
+
+import {
+ BrowserWindow,
+ WebContentsView,
+ ipcMain,
+ type IpcMainInvokeEvent,
+ type WebContents,
+} from 'electron';
+
+import {
+ RSB_NATIVE_POPUP_CLAIM_CHANNEL,
+ RSB_NATIVE_POPUP_CLOSE_CHANNEL,
+ RSB_NATIVE_POPUP_COMMAND_CHANNEL,
+ RSB_NATIVE_POPUP_EVENT_CHANNEL,
+ RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL,
+ type RsbNativePopupBounds,
+ type RsbNativePopupClaimResult,
+ type RsbNativePopupCommand,
+ type RsbNativePopupEvent,
+ type RsbNativePopupSnapshot,
+} from '../../shared/rsbNativePopup.js';
+import { createLogger } from '../logger.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { requireEnum, requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';
+import type { TabRegistry } from './registry.js';
+
+const log = createLogger('rsb-native-popup-surfaces');
+
+interface SurfaceRecord {
+ surfaceId: string;
+ view: WebContentsView;
+ webContents: WebContents;
+ ownerWindow: BrowserWindow;
+ ownerWebContents: WebContents | null;
+ sessionId: string | null;
+ tabId: string | null;
+ favicon: string | null;
+ crash: { reason: string } | null;
+ requestedBounds: RsbNativePopupBounds;
+ requestedVisible: boolean;
+ openerPinRelease: (() => void) | null;
+ popupPinRelease: (() => void) | null;
+ claimTimer: ReturnType<typeof setTimeout> | null;
+ detachOwnerObservers: (() => void) | null;
+}
+
+export const RSB_NATIVE_POPUP_CLAIM_TIMEOUT_MS = 30_000;
+
+const surfaces = new Map<string, SurfaceRecord>();
+const managedWebContentsIds = new Set<number>();
+let registry: TabRegistry | null = null;
+let ipcRegistered = false;
+
+function safeCall<T>(fallback: T, fn: () => T): T {
+ try {
+ return fn();
+ } catch {
+ return fallback;
+ }
+}
+
+function snapshot(record: SurfaceRecord): RsbNativePopupSnapshot {
+ const wc = record.webContents;
+ return {
+ url: safeCall('about:blank', () => wc.getURL() || 'about:blank'),
+ title: safeCall('', () => wc.getTitle()),
+ favicon: record.favicon,
+ isLoading: safeCall(false, () => wc.isLoading()),
+ canGoBack: safeCall(false, () => wc.canGoBack()),
+ canGoForward: safeCall(false, () => wc.canGoForward()),
+ isAudible: safeCall(false, () => wc.isCurrentlyAudible()),
+ crash: record.crash,
+ };
+}
+
+function sendEvent(record: SurfaceRecord, event: RsbNativePopupEvent): void {
+ const owner = record.ownerWebContents;
+ if (!owner || owner.isDestroyed()) return;
+ try {
+ owner.send(RSB_NATIVE_POPUP_EVENT_CHANNEL, event);
+ } catch (err) {
+ log.warn('failed to send native popup event', { surfaceId: record.surfaceId, err });
+ }
+}
+
+function publishState(record: SurfaceRecord): void {
+ if (record.webContents.isDestroyed()) return;
+ sendEvent(record, { surfaceId: record.surfaceId, type: 'state', snapshot: snapshot(record) });
+}
+
+function resolveViewBounds(record: SurfaceRecord): RsbNativePopupBounds {
+ const zoomFactor = safeCall(1, () => record.ownerWebContents?.getZoomFactor() ?? 1);
+ const scale = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
+ const contentBounds = safeCall(
+ { x: 0, y: 0, width: Number.MAX_SAFE_INTEGER, height: Number.MAX_SAFE_INTEGER },
+ () => record.ownerWindow.getContentBounds(),
+ );
+ const maxWidth = Math.max(1, contentBounds.width);
+ const maxHeight = Math.max(1, contentBounds.height);
+ const requested = record.requestedBounds;
+ const left = Math.min(maxWidth - 1, Math.max(0, Math.floor(requested.x * scale)));
+ const top = Math.min(maxHeight - 1, Math.max(0, Math.floor(requested.y * scale)));
+ const right = Math.min(
+ maxWidth,
+ Math.max(left + 1, Math.ceil((requested.x + requested.width) * scale)),
+ );
+ const bottom = Math.min(
+ maxHeight,
+ Math.max(top + 1, Math.ceil((requested.y + requested.height) * scale)),
+ );
+ return { x: left, y: top, width: right - left, height: bottom - top };
+}
+
+function applyVisibility(record: SurfaceRecord): void {
+ const visible = record.requestedVisible && record.crash === null;
+ try {
+ // Renderer bounds are CSS pixels; WebContentsView expects BrowserWindow
+ // content-view DIPs. Electron page zoom changes that ratio.
+ record.view.setBounds(resolveViewBounds(record));
+ record.view.setVisible(visible);
+ } catch (err) {
+ log.warn('failed to update native popup view', { surfaceId: record.surfaceId, err });
+ }
+}
+
+function detachView(record: SurfaceRecord): void {
+ try {
+ if (!record.ownerWindow.isDestroyed()) {
+ record.ownerWindow.contentView.removeChildView(record.view);
+ }
+ } catch {
+ // The owner may be in native teardown; the manager still owns the view/WC.
+ }
+}
+
+function cleanupSurface(record: SurfaceRecord, notifyClosed: boolean): void {
+ if (surfaces.get(record.surfaceId) !== record) return;
+ if (notifyClosed) {
+ sendEvent(record, { surfaceId: record.surfaceId, type: 'closed' });
+ }
+ surfaces.delete(record.surfaceId);
+ managedWebContentsIds.delete(record.webContents.id);
+ if (record.claimTimer) clearTimeout(record.claimTimer);
+ record.claimTimer = null;
+ record.detachOwnerObservers?.();
+ record.detachOwnerObservers = null;
+ detachView(record);
+ record.openerPinRelease?.();
+ record.popupPinRelease?.();
+ record.openerPinRelease = null;
+ record.popupPinRelease = null;
+ if (record.tabId) registry?.release(record.tabId, record.webContents.id);
+}
+
+function installSurfaceObservers(record: SurfaceRecord): void {
+ const wc = record.webContents;
+ const publish = () => publishState(record);
+ wc.on('did-start-loading', () => {
+ record.crash = null;
+ applyVisibility(record);
+ publish();
+ });
+ wc.on('did-stop-loading', publish);
+ wc.on('did-navigate', publish);
+ wc.on('did-navigate-in-page', publish);
+ wc.on('page-title-updated', publish);
+ wc.on('page-favicon-updated', (_event, favicons) => {
+ record.favicon = favicons.find((candidate) => candidate.trim().length > 0) ?? null;
+ publish();
+ });
+ wc.on('audio-state-changed', publish);
+ wc.on('unresponsive', () => {
+ record.crash = { reason: 'unresponsive' };
+ applyVisibility(record);
+ publish();
+ });
+ wc.on('responsive', () => {
+ if (record.crash?.reason !== 'unresponsive') return;
+ record.crash = null;
+ applyVisibility(record);
+ publish();
+ });
+ wc.on('render-process-gone', (_event, details) => {
+ record.crash = { reason: details.reason };
+ applyVisibility(record);
+ publish();
+ });
+ wc.once('destroyed', () => cleanupSurface(record, true));
+}
+
+/** Adopt Chromium's exact popup WebContents; never create a replacement context. */
+export function createRsbNativePopupSurface(
+ hostContents: WebContents,
+ popupContents: WebContents,
+): string | null {
+ if (popupContents.isDestroyed()) return null;
+ const ownerWindow = BrowserWindow.fromWebContents(hostContents);
+ if (!ownerWindow || ownerWindow.isDestroyed()) return null;
+
+ const surfaceId = randomUUID();
+ const view = new WebContentsView({ webContents: popupContents });
+ const record: SurfaceRecord = {
+ surfaceId,
+ view,
+ webContents: popupContents,
+ ownerWindow,
+ // The surface id is sent only to this renderer. Recording the owner at
+ // creation also lets it dispose an unclaimed surface when tab creation or
+ // opener attribution fails.
+ ownerWebContents: hostContents,
+ sessionId: null,
+ tabId: null,
+ favicon: null,
+ crash: null,
+ requestedBounds: { x: 0, y: 0, width: 1, height: 1 },
+ requestedVisible: false,
+ openerPinRelease: null,
+ popupPinRelease: null,
+ claimTimer: null,
+ detachOwnerObservers: null,
+ };
+ surfaces.set(surfaceId, record);
+ managedWebContentsIds.add(popupContents.id);
+ ownerWindow.contentView.addChildView(view);
+ view.setBounds(record.requestedBounds);
+ view.setVisible(false);
+ installSurfaceObservers(record);
+ const handleOwnerDestroyed = () => {
+ if (surfaces.get(surfaceId) !== record) return;
+ cleanupSurface(record, false);
+ if (!popupContents.isDestroyed()) popupContents.close();
+ };
+ const handleOwnerNavigation = (
+ _event: Electron.Event,
+ _url: string,
+ isSameDocument: boolean,
+ isMainFrame: boolean,
+ ) => {
+ if (!isMainFrame || isSameDocument || surfaces.get(surfaceId) !== record) return;
+ // A full renderer reload keeps the same host WebContents, but loses the
+ // runtime tab↔surface map. Close before the old renderer disappears so a
+ // stale view cannot cover the new page or block sidebar reparent forever.
+ cleanupSurface(record, true);
+ if (!popupContents.isDestroyed()) popupContents.close();
+ };
+ hostContents.once('destroyed', handleOwnerDestroyed);
+ hostContents.on('did-start-navigation', handleOwnerNavigation);
+ record.detachOwnerObservers = () => {
+ hostContents.removeListener('destroyed', handleOwnerDestroyed);
+ hostContents.removeListener('did-start-navigation', handleOwnerNavigation);
+ };
+ record.claimTimer = setTimeout(() => {
+ if (surfaces.get(surfaceId) !== record || record.tabId) return;
+ log.warn('disposing unclaimed native popup surface', { surfaceId });
+ cleanupSurface(record, false);
+ if (!popupContents.isDestroyed()) popupContents.close();
+ }, RSB_NATIVE_POPUP_CLAIM_TIMEOUT_MS);
+ record.claimTimer.unref?.();
+ return surfaceId;
+}
+
+/** Pin the ordinary `<webview>` opener while its child still depends on WindowProxy. */
+export function attributeRsbNativePopupSurface(surfaceId: string, opener: { tabId: string }): void {
+ const record = surfaces.get(surfaceId);
+ if (!record || record.openerPinRelease || !registry) return;
+ record.openerPinRelease = registry.acquirePinLease(opener.tabId);
+}
+
+function findSurfaceOwner(event: IpcMainInvokeEvent, surfaceId: string): SurfaceRecord | null {
+ const record = surfaces.get(surfaceId);
+ if (!record) return null;
+ if (!record.ownerWebContents || record.ownerWebContents.id !== event.sender.id) {
+ throwIpcError('PERMISSION_DENIED', 'native popup surface belongs to another window');
+ }
+ return record;
+}
+
+function assertSurfaceOwner(event: IpcMainInvokeEvent, surfaceId: string): SurfaceRecord {
+ const record = findSurfaceOwner(event, surfaceId);
+ if (!record) throwIpcError('NOT_FOUND', `native popup surface ${surfaceId} not found`);
+ return record;
+}
+
+function attachToOwner(record: SurfaceRecord, event: IpcMainInvokeEvent): void {
+ const nextWindow = BrowserWindow.fromWebContents(event.sender);
+ if (!nextWindow || nextWindow.isDestroyed() || nextWindow !== record.ownerWindow) {
+ throwIpcError('PERMISSION_DENIED', 'native popup owner window is unavailable');
+ }
+}
+
+function claimSurface(
+ event: IpcMainInvokeEvent,
+ surfaceId: string,
+ sessionId: string,
+ tabId: string,
+): RsbNativePopupClaimResult {
+ const record = surfaces.get(surfaceId);
+ if (!record || record.webContents.isDestroyed()) return { alive: false };
+ if (record.ownerWebContents && record.ownerWebContents.id !== event.sender.id) {
+ throwIpcError('PERMISSION_DENIED', 'native popup surface belongs to another window');
+ }
+ if (record.tabId && (record.tabId !== tabId || record.sessionId !== sessionId)) {
+ throwIpcError('PERMISSION_DENIED', 'native popup surface is already claimed by another tab');
+ }
+ attachToOwner(record, event);
+ if (record.claimTimer) clearTimeout(record.claimTimer);
+ record.claimTimer = null;
+ record.sessionId = sessionId;
+ record.tabId = tabId;
+ registry?.report({ sessionId, tabId, webContentsId: record.webContents.id });
+ if (!record.popupPinRelease && registry) {
+ record.popupPinRelease = registry.acquirePinLease(tabId);
+ }
+ return { alive: true, snapshot: snapshot(record) };
+}
+
+function isSafeNavigationUrl(raw: string): boolean {
+ if (raw.length > 16_384) return false;
+ try {
+ return ['http:', 'https:', 'file:', 'about:'].includes(new URL(raw).protocol);
+ } catch {
+ return false;
+ }
+}
+
+function runCommand(record: SurfaceRecord, command: RsbNativePopupCommand): void {
+ const wc = record.webContents;
+ if (wc.isDestroyed()) throwIpcError('NOT_FOUND', 'native popup WebContents is destroyed');
+ if (command.command === 'navigate') {
+ if (!isSafeNavigationUrl(command.url)) {
+ throwIpcError('INVALID_PARAMS', 'unsupported native popup navigation URL');
+ }
+ void wc.loadURL(command.url).catch((err) => {
+ log.warn('native popup navigation failed', { surfaceId: record.surfaceId, err });
+ });
+ } else if (command.command === 'reload') {
+ record.crash = null;
+ applyVisibility(record);
+ wc.reload();
+ } else if (command.command === 'go-back') {
+ if (wc.canGoBack()) wc.goBack();
+ } else if (command.command === 'go-forward') {
+ if (wc.canGoForward()) wc.goForward();
+ } else {
+ wc.stop();
+ }
+}
+
+function parseSurfaceId(payload: Record<string, unknown>): string {
+ const surfaceId = requireString(payload.surfaceId, 'surfaceId');
+ if (surfaceId.length > 128) throwIpcError('INVALID_PARAMS', 'surfaceId is too long');
+ return surfaceId;
+}
+
+function parseBounds(value: unknown): RsbNativePopupBounds {
+ const raw = requireObject(value, 'bounds');
+ const result = {} as RsbNativePopupBounds;
+ for (const key of ['x', 'y', 'width', 'height'] as const) {
+ const item = raw[key];
+ if (typeof item !== 'number' || !Number.isFinite(item) || !Number.isInteger(item)) {
+ throwIpcError('INVALID_PARAMS', `bounds.${key} must be a finite integer`);
+ }
+ result[key] = item;
+ }
+ if (result.x < 0 || result.y < 0 || result.width < 1 || result.height < 1) {
+ throwIpcError('INVALID_PARAMS', 'bounds must be positive and inside the host viewport');
+ }
+ if (result.width > 16_384 || result.height > 16_384) {
+ throwIpcError('INVALID_PARAMS', 'bounds exceed the maximum native popup size');
+ }
+ return result;
+}
+
+export function registerRsbNativePopupSurfaceIpc(tabRegistry: TabRegistry): void {
+ registry = tabRegistry;
+ if (ipcRegistered) return;
+ ipcRegistered = true;
+
+ ipcMain.handle(RSB_NATIVE_POPUP_CLAIM_CHANNEL, (event, input: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const raw = requireObject(input, 'native popup claim');
+ return claimSurface(
+ event,
+ parseSurfaceId(raw),
+ requireString(raw.sessionId, 'sessionId'),
+ requireString(raw.tabId, 'tabId'),
+ );
+ });
+
+ ipcMain.handle(RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL, (event, input: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const raw = requireObject(input, 'native popup bounds');
+ const surfaceId = parseSurfaceId(raw);
+ if (typeof raw.visible !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'visible must be boolean');
+ }
+ const bounds = parseBounds(raw.bounds);
+ // window.close() can destroy the native surface while the renderer still
+ // has a queued ResizeObserver update. Treat that late cleanup update as a
+ // successful no-op; malformed input and foreign live surfaces still fail.
+ const record = findSurfaceOwner(event, surfaceId);
+ if (!record) return { ok: true };
+ record.requestedBounds = bounds;
+ record.requestedVisible = raw.visible;
+ applyVisibility(record);
+ return { ok: true };
+ });
+
+ ipcMain.handle(RSB_NATIVE_POPUP_COMMAND_CHANNEL, (event, input: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const raw = requireObject(input, 'native popup command');
+ const record = assertSurfaceOwner(event, parseSurfaceId(raw));
+ const command = requireEnum(
+ raw.command,
+ ['navigate', 'reload', 'go-back', 'go-forward', 'stop'] as const,
+ 'command',
+ );
+ const parsed: RsbNativePopupCommand =
+ command === 'navigate' ? { command, url: requireString(raw.url, 'url') } : { command };
+ runCommand(record, parsed);
+ return { ok: true };
+ });
+
+ ipcMain.handle(RSB_NATIVE_POPUP_CLOSE_CHANNEL, (event, input: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const raw = requireObject(input, 'native popup close');
+ const record = findSurfaceOwner(event, parseSurfaceId(raw));
+ // Guest window.close and renderer tab cleanup race by design. Closing an
+ // already-destroyed surface is idempotent and must not emit a false error.
+ if (!record) return { ok: true };
+ cleanupSurface(record, false);
+ if (!record.webContents.isDestroyed()) record.webContents.close();
+ return { ok: true };
+ });
+}
+
+export function getRsbNativePopupOwnerWebContents(webContentsId: number): WebContents | null {
+ for (const record of surfaces.values()) {
+ if (record.webContents.id !== webContentsId) continue;
+ const owner = record.ownerWebContents;
+ return owner && !owner.isDestroyed() ? owner : null;
+ }
+ return null;
+}
+
+export function isRsbNativePopupWebContentsId(webContentsId: number): boolean {
+ return managedWebContentsIds.has(webContentsId);
+}
+
+export function hasActiveRsbNativePopupSurfaces(): boolean {
+ return surfaces.size > 0;
+}
+
+/** Test-only reset. */
+export function _resetRsbNativePopupSurfacesForTests(): void {
+ for (const record of [...surfaces.values()]) {
+ cleanupSurface(record, false);
+ if (!record.webContents.isDestroyed()) record.webContents.close();
+ }
+ registry = null;
+ ipcRegistered = false;
+}
diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.ts
index 6bdde043a1..3069e52163 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -41,6 +41,10 @@ import {
} from './cindy-brain/index.js';
import { classifyGhostPanelNavigation } from './cindy-brain/previewGate.js';
import { registerGhostWebContents } from './cindy-brain/runtime/electronSandboxAdapter.js';
+import {
+ attributeRsbNativePopupSurface,
+ createRsbNativePopupSurface,
+} from './rsb-browser-bridge/native-popup-surfaces.js';
/**
* RSB 浏览器 webview 的 guest 注入层(页面评论 overlay)产物路径。
@@ -280,6 +284,8 @@ export interface RsbBrowserPopupPayload {
* bucket——没有它时只能落在"用户正在看的 session",agent 后台 session 触发的
* popup 会串进无关会话。 */
openerSessionId?: string;
+ /** Main-owned WebContentsView surface that preserves the popup browsing context. */
+ nativePopupSurfaceId?: string;
}
/**
@@ -412,28 +418,36 @@ function routeBrowserPopup(
openerWebContentsId: number | undefined,
payload: RsbBrowserPopupPayload,
): void {
+ const finish = (opener: ResolvedPopupOpener | null) => {
+ if (payload.nativePopupSurfaceId && opener) {
+ attributeRsbNativePopupSurface(payload.nativePopupSurfaceId, {
+ tabId: opener.openerTabId,
+ });
+ }
+ sendBrowserPopup(hostContents, { ...payload, ...(opener ?? {}) });
+ };
if (openerWebContentsId === undefined || !popupOpenerResolver) {
- sendBrowserPopup(hostContents, payload);
+ finish(null);
return;
}
const opener = resolvePopupOpener(openerWebContentsId);
if (opener) {
- sendBrowserPopup(hostContents, { ...payload, ...opener });
+ finish(opener);
return;
}
void waitForPopupOpener(openerWebContentsId).then((late) => {
- sendBrowserPopup(hostContents, { ...payload, ...(late ?? {}) });
+ finish(late);
});
}
/**
- * about:blank deferred popup 的隐藏中转 BrowserWindow 的 webPreferences。
- * 完整安全集,对齐 docs/dev-rules/electron-security-and-process-boundaries.md
- * 第 3 节的 BrowserWindow 契约 —— 这是一个真实的(隐藏)BrowserWindow,即使
- * 只活到"偷到第一个真实 URL"也不许比主窗宽松。导出供单测钉住字段完整性。
+ * Chromium child popup 的完整安全集。Electron 用这些偏好创建传给
+ * `createWindow` 的真实 popup WebContents;main 随后把同一个 context 放进
+ * WebContentsView。字段对齐 BrowserWindow 安全契约,导出供单测钉住。
*/
export const BLANK_POPUP_WINDOW_WEB_PREFERENCES = Object.freeze({
sandbox: true,
+ devTools: true,
nodeIntegration: false,
nodeIntegrationInSubFrames: false,
nodeIntegrationInWorker: false,
@@ -442,6 +456,7 @@ export const BLANK_POPUP_WINDOW_WEB_PREFERENCES = Object.freeze({
allowRunningInsecureContent: false,
experimentalFeatures: false,
plugins: false,
+ disableDialogs: false,
navigateOnDragDrop: false,
partition: BROWSER_PARTITION,
webviewTag: false,
@@ -555,15 +570,12 @@ export function installDeferredPopupRouter(
* 模块入口(bootstrap-electron)在 app ready 前调一次即可,所有现在 / 未来创建的窗口
* 都生效。
*
- * setWindowOpenHandler 路由策略(对齐 Codex `main-cC-d0ezP.js:48849` 智能路由,
- * 但简化为 RSB tab):
- * - guest 内 `window.open(url)` / `<a target="_blank">` / window.location 跨 host:
- * 若 url 已经是 http(s),直接 deny 真窗口并把 url + disposition 推给 host
- * webContents(主窗 renderer),由 RightSidebarShell 收到后 `store.addTab` 创建
- * 新的 web-browser RSB tab。
- * - 若 popup 先打开 about:blank,再由 opener 脚本写入真实地址(典型登录流),
- * 临时允许一个隐藏 BrowserWindow,只用于捕获后续 will-navigate URL;捕获后
- * 立即关闭隐藏窗口并路由成 RSB tab。用户不会看到原生弹窗。
+ * setWindowOpenHandler 路由策略:
+ * - http(s) 与 about:blank popup 都让 Chromium 创建真实 child WebContents;
+ * - `createWindow` 接管 Electron 预创建的 `options.webContents`,把**同一个**
+ * browsing context 放进 main-owned WebContentsView,再路由成 RSB tab;
+ * - 不能另建 `<webview>`:那会让 opener 手里的 WindowProxy 指向已关闭的旧
+ * context,破坏 OAuth/SSO 对 closed/location/close 的依赖。
* - 推消息走 channel `rsb:browser-popup`,renderer 端通过 preload 的 fanOut 订阅。
*
* 这里 `contents` 闭包指向 host webContents(主窗 renderer),`guestContents` 是
@@ -571,6 +583,76 @@ export function installDeferredPopupRouter(
* 触发),但回调里用 host 的 contents.send 发消息——renderer 端收到的就是主窗 renderer
* 进程。
*/
+export function installBrowserGuestHandlers(
+ hostContents: WebContents,
+ guestContents: WebContents,
+): void {
+ guestContents.setWindowOpenHandler((details) => {
+ if (!isRoutablePopupUrl(details.url) && !isInitialBlankPopupUrl(details.url)) {
+ return { action: 'deny' };
+ }
+ return {
+ action: 'allow',
+ outlivesOpener: false,
+ overrideBrowserWindowOptions: {
+ show: false,
+ autoHideMenuBar: true,
+ webPreferences: { ...BLANK_POPUP_WINDOW_WEB_PREFERENCES },
+ },
+ createWindow: (options) => {
+ // Electron supplies this runtime-only field when createWindow is used
+ // to adopt Chromium's already-created popup browsing context. It is
+ // intentionally absent from BrowserWindowConstructorOptions.d.ts.
+ const popupContents = (
+ options as typeof options & { webContents?: WebContents }
+ ).webContents;
+ if (!popupContents) {
+ throw new Error('Electron did not provide popup WebContents to createWindow');
+ }
+ const surfaceId = createRsbNativePopupSurface(hostContents, popupContents);
+ if (!surfaceId) {
+ popupContents.close();
+ return popupContents;
+ }
+ // Popup-of-popup keeps the same security and WindowProxy semantics.
+ installBrowserGuestHandlers(hostContents, popupContents);
+ routeBrowserPopup(hostContents, guestContents.id, {
+ url: details.url,
+ disposition: details.disposition,
+ nativePopupSurfaceId: surfaceId,
+ });
+ return popupContents;
+ },
+ };
+ });
+
+ // Chromium guest key events do not bubble to the host renderer. Forward the
+ // browser-level shortcuts through the existing host channel for both
+ // ordinary webviews and adopted popup WebContents.
+ guestContents.on('before-input-event', (event, input) => {
+ if (!isGuestShortcutKeyDownType(input.type)) return;
+ const store = getAppShortcutStore();
+ const action = resolveGuestShortcutAction(input, (id) =>
+ store.getEffectiveCombos(id),
+ );
+ if (!action) return;
+ event.preventDefault();
+ let target: WebContents | null = null;
+ try {
+ target = popupHostResolver?.() ?? null;
+ } catch {
+ target = null;
+ }
+ target = target && !target.isDestroyed() ? target : hostContents;
+ if (target.isDestroyed()) return;
+ if (action.kind === 'focus-url-bar') {
+ target.send(RSB_BROWSER_FOCUS_URL_BAR_CHANNEL, null);
+ } else {
+ target.send(RSB_BROWSER_COMMAND_CHANNEL, { command: action.command });
+ }
+ });
+}
+
export function installWebviewHardener(): void {
app.on('web-contents-created', (_event, contents) => {
// will-attach → did-attach 对同一个 guest 同步成对触发;用闭包变量把
@@ -625,56 +707,7 @@ export function installWebviewHardener(): void {
});
return;
}
- guestContents.setWindowOpenHandler((details) => {
- if (isRoutablePopupUrl(details.url)) {
- routeBrowserPopup(contents, guestContents.id, {
- url: details.url,
- disposition: details.disposition,
- });
- return { action: 'deny' };
- }
-
- if (isInitialBlankPopupUrl(details.url)) {
- return {
- action: 'allow',
- overrideBrowserWindowOptions: {
- show: false,
- autoHideMenuBar: true,
- webPreferences: { ...BLANK_POPUP_WINDOW_WEB_PREFERENCES },
- },
- };
- }
-
- return { action: 'deny' };
- });
- guestContents.on('did-create-window', (popupWindow, details) => {
- installDeferredPopupRouter(contents, popupWindow, details.disposition, guestContents.id);
- });
- // 拦截 webview guest 内的"浏览器级"快捷键 —— Electron webview 是独立
- // webContents,guest 触发的 keydown 不冒泡到 host 的 window,host renderer
- // 的全局监听器拿不到。要让 Ctrl/Cmd+L 在用户焦点在 guest 网页内时也能
- // 触发 chrome 的 URL bar 聚焦,必须在 main 端拦截 before-input-event,推
- // 消息给 host renderer。Codex `main-cC-d0ezP.js:48846` 也用同一事件做同
- // 一件事。
- //
- // 组合键从 app-shortcuts store 实时读生效值 (默认 + 用户 override),与
- // host 侧 BrowserTabBody 的监听保持同一份 registry,改绑后两端行为一致。
- // 命中即 preventDefault + 转发,guest 网页不会再收到这次按键。
- guestContents.on('before-input-event', (event, input) => {
- if (!isGuestShortcutKeyDownType(input.type)) return;
- const store = getAppShortcutStore();
- const action = resolveGuestShortcutAction(input, (id) =>
- store.getEffectiveCombos(id),
- );
- if (!action) return;
- event.preventDefault();
- if (contents.isDestroyed()) return;
- if (action.kind === 'focus-url-bar') {
- contents.send(RSB_BROWSER_FOCUS_URL_BAR_CHANNEL, null);
- } else {
- contents.send(RSB_BROWSER_COMMAND_CHANNEL, { command: action.command });
- }
- });
+ installBrowserGuestHandlers(contents, guestContents);
});
});
}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 450df8a5ec..f1293cdf60 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -95,6 +95,18 @@ import type {
RsbWindowCommandRouteRequest,
RsbWindowCommandRouteResult,
} from '../shared/rightSidebarWindow';
+import {
+ RSB_NATIVE_POPUP_CLAIM_CHANNEL,
+ RSB_NATIVE_POPUP_CLOSE_CHANNEL,
+ RSB_NATIVE_POPUP_COMMAND_CHANNEL,
+ RSB_NATIVE_POPUP_EVENT_CHANNEL,
+ RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL,
+ type RsbNativePopupBounds,
+ type RsbNativePopupClaimInput,
+ type RsbNativePopupClaimResult,
+ type RsbNativePopupCommand,
+ type RsbNativePopupEvent,
+} from '../shared/rsbNativePopup';
import type {
DesktopAccountDeletionAvailabilityResult,
DesktopAccountDeletionChallengeResult,
@@ -363,6 +375,7 @@ const fanOutDeepLinkNavigate = createIpcFanOut('deep-link:navigate');
// main 端 webview-security setWindowOpenHandler 把 popup URL 推到这里,renderer
// 端 RightSidebarShell 订阅 → store.addTab 开新 web-browser tab。
const fanOutRsbBrowserPopup = createIpcFanOut('rsb:browser-popup');
+const fanOutRsbNativePopupEvent = createIpcFanOut(RSB_NATIVE_POPUP_EVENT_CHANNEL);
// RSB terminal plugin: main 端 PTY onData / onExit 推过来,renderer 按 id filter。
// 每个 tab 自己订阅,fanOut 内部去重 ipcRenderer.on 绑定。
const fanOutTerminalData = createIpcFanOut('terminal:data');
@@ -2737,6 +2750,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
disposition: string;
openerTabId?: string;
openerSessionId?: string;
+ nativePopupSurfaceId?: string;
}) => void,
): (() => void) =>
fanOutRsbBrowserPopup((payload) => {
@@ -2748,16 +2762,20 @@ contextBridge.exposeInMainWorld('electronAPI', {
disposition?: unknown;
openerTabId?: unknown;
openerSessionId?: unknown;
+ nativePopupSurfaceId?: unknown;
};
if (typeof p.url !== 'string' || typeof p.disposition !== 'string') return;
if (p.openerTabId !== undefined && typeof p.openerTabId !== 'string') return;
if (p.openerSessionId !== undefined && typeof p.openerSessionId !== 'string') return;
+ if (p.nativePopupSurfaceId !== undefined && typeof p.nativePopupSurfaceId !== 'string')
+ return;
callback(
p as {
url: string;
disposition: string;
openerTabId?: string;
openerSessionId?: string;
+ nativePopupSurfaceId?: string;
},
);
}),
@@ -4225,6 +4243,33 @@ contextBridge.exposeInMainWorld('electronAPI', {
fanOutRsbBrowserBridgeResourceEvent(cb as IpcCallback),
},
+ rsbNativePopup: {
+ claim: (input: RsbNativePopupClaimInput): Promise<RsbNativePopupClaimResult> =>
+ ipcRenderer.invoke(RSB_NATIVE_POPUP_CLAIM_CHANNEL, input),
+ setBounds: (input: {
+ surfaceId: string;
+ bounds: RsbNativePopupBounds;
+ visible: boolean;
+ }): Promise<{ ok: true }> => ipcRenderer.invoke(RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL, input),
+ command: (input: { surfaceId: string } & RsbNativePopupCommand): Promise<{ ok: true }> =>
+ ipcRenderer.invoke(RSB_NATIVE_POPUP_COMMAND_CHANNEL, input),
+ close: (input: { surfaceId: string }): Promise<{ ok: true }> =>
+ ipcRenderer.invoke(RSB_NATIVE_POPUP_CLOSE_CHANNEL, input),
+ onEvent: (callback: (event: RsbNativePopupEvent) => void): (() => void) =>
+ fanOutRsbNativePopupEvent((payload) => {
+ if (!payload || typeof payload !== 'object') return;
+ const event = payload as Partial<RsbNativePopupEvent>;
+ if (typeof event.surfaceId !== 'string') return;
+ if (event.type === 'closed') {
+ callback(event as RsbNativePopupEvent);
+ return;
+ }
+ if (event.type === 'state' && event.snapshot && typeof event.snapshot === 'object') {
+ callback(event as RsbNativePopupEvent);
+ }
+ }),
+ },
+
// ── Browser backend toggle (Phase 5) ─────────────────────────────────────
/**
* Settings UI driver — switches the MCP `browser` tool between external
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 1548f1eb1c..2227bbf203 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
@@ -33,6 +33,7 @@ vi.mock('../lib/rsbBrowserBridge', async () => {
import { RightSidebarShell } from '../RightSidebarShell';
import { _resetRsbBrowserBridgeForTests } from '../lib/rsbBrowserBridge';
import { _resetPopupRouterForTests } from '../lib/popupRouter';
+import { _resetNativePopupTabsForTests } from '../lib/nativePopupTabs';
import {
_resetSidebarCommandsForTests,
onRequestRightSidebarVisibility,
@@ -66,9 +67,26 @@ interface RsbBrowserPopupPayloadStub {
disposition: string;
openerTabId?: string;
openerSessionId?: string;
+ nativePopupSurfaceId?: string;
}
let rsbBrowserPopupListeners: Array<(payload: RsbBrowserPopupPayloadStub) => void> = [];
+let rsbNativePopupEventListeners: Array<(payload: { surfaceId: string; type: 'closed' }) => void> =
+ [];
+const rsbNativePopupClaim = vi.fn(async () => ({
+ alive: true as const,
+ snapshot: {
+ url: 'about:blank',
+ title: '',
+ favicon: null,
+ isLoading: false,
+ canGoBack: false,
+ canGoForward: false,
+ isAudible: false,
+ crash: null,
+ },
+}));
+const rsbNativePopupClose = vi.fn(async () => ({ ok: true as const }));
function makeRightSidebarTabsIpc(): RightSidebarTabsIpcStub {
return {
@@ -97,6 +115,13 @@ function installElectronApi(tabsIpc: RightSidebarTabsIpcStub, fullscreen = false
forceKill: ReturnType<typeof vi.fn>;
onResourceEvent: ReturnType<typeof vi.fn>;
};
+ rsbNativePopup: {
+ claim: typeof rsbNativePopupClaim;
+ close: typeof rsbNativePopupClose;
+ setBounds: ReturnType<typeof vi.fn>;
+ command: ReturnType<typeof vi.fn>;
+ onEvent: ReturnType<typeof vi.fn>;
+ };
gitReview: { summary: ReturnType<typeof vi.fn> };
onRsbBrowserPopup: ReturnType<typeof vi.fn>;
onRsbBrowserCommand: (
@@ -125,6 +150,20 @@ function installElectronApi(tabsIpc: RightSidebarTabsIpcStub, fullscreen = false
forceKill: vi.fn(async () => undefined),
onResourceEvent: vi.fn(() => () => undefined),
},
+ rsbNativePopup: {
+ claim: rsbNativePopupClaim,
+ close: rsbNativePopupClose,
+ setBounds: vi.fn(async () => ({ ok: true })),
+ command: vi.fn(async () => ({ ok: true })),
+ onEvent: vi.fn((callback: (payload: { surfaceId: string; type: 'closed' }) => void) => {
+ rsbNativePopupEventListeners.push(callback);
+ return () => {
+ rsbNativePopupEventListeners = rsbNativePopupEventListeners.filter(
+ (cb) => cb !== callback,
+ );
+ };
+ }),
+ },
gitReview: {
summary: vi.fn(async () => ({
scope: {
@@ -205,8 +244,12 @@ describe('RightSidebarShell empty state', () => {
_resetStore();
_resetRsbBrowserBridgeForTests();
_resetPopupRouterForTests();
+ _resetNativePopupTabsForTests();
rsbBrowserCommandListeners = [];
rsbBrowserPopupListeners = [];
+ rsbNativePopupEventListeners = [];
+ rsbNativePopupClaim.mockClear();
+ rsbNativePopupClose.mockClear();
eagerSpawnAndReport.mockClear();
eagerSpawnAndReport.mockImplementation(async () => undefined);
tabsIpc = makeRightSidebarTabsIpc();
@@ -217,6 +260,7 @@ describe('RightSidebarShell empty state', () => {
_resetStore();
_resetRsbBrowserBridgeForTests();
_resetPopupRouterForTests();
+ _resetNativePopupTabsForTests();
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
});
@@ -707,9 +751,13 @@ describe('RightSidebarShell 跨 session popup 归属', () => {
_resetStore();
_resetRsbBrowserBridgeForTests();
_resetPopupRouterForTests();
+ _resetNativePopupTabsForTests();
_resetSidebarCommandsForTests();
rsbBrowserCommandListeners = [];
rsbBrowserPopupListeners = [];
+ rsbNativePopupEventListeners = [];
+ rsbNativePopupClaim.mockClear();
+ rsbNativePopupClose.mockClear();
eagerSpawnAndReport.mockClear();
eagerSpawnAndReport.mockImplementation(async () => undefined);
requests = [];
@@ -726,6 +774,7 @@ describe('RightSidebarShell 跨 session popup 归属', () => {
_resetStore();
_resetRsbBrowserBridgeForTests();
_resetPopupRouterForTests();
+ _resetNativePopupTabsForTests();
delete (window as unknown as { electronAPI?: unknown }).electronAPI;
});
@@ -769,6 +818,44 @@ describe('RightSidebarShell 跨 session popup 归属', () => {
expect(requests[0].opts.userInitiated).toBe(false);
});
+ it('native popup claim 原始 WebContents,不再 eagerSpawn 新 webview,并响应 window.close', async () => {
+ renderShell();
+ await waitFor(() => expect(rsbBrowserPopupListeners).toHaveLength(1));
+ await act(async () => {
+ rsbBrowserPopupListeners[0]({
+ url: 'about:blank',
+ disposition: 'foreground-tab',
+ openerTabId: 'tab-opener',
+ openerSessionId: 's1',
+ nativePopupSurfaceId: 'surface-oauth',
+ });
+ await Promise.resolve();
+ });
+
+ await waitFor(() => expect(getBucket('s1').tabs).toHaveLength(1));
+ const tab = getBucket('s1').tabs[0];
+ await waitFor(() => expect(rsbNativePopupClaim).toHaveBeenCalledTimes(1));
+ expect(rsbNativePopupClaim).toHaveBeenCalledWith({
+ surfaceId: 'surface-oauth',
+ sessionId: 's1',
+ tabId: tab.id,
+ });
+ expect(tab.state).toMatchObject({
+ url: 'about:blank',
+ nativePopupSurfaceId: 'surface-oauth',
+ });
+ expect(eagerSpawnAndReport).not.toHaveBeenCalled();
+
+ await act(async () => {
+ for (const listener of rsbNativePopupEventListeners) {
+ listener({ surfaceId: 'surface-oauth', type: 'closed' });
+ }
+ await Promise.resolve();
+ });
+ await waitFor(() => expect(getBucket('s1').tabs).toHaveLength(0));
+ expect(rsbNativePopupClose).toHaveBeenCalledWith({ surfaceId: 'surface-oauth' });
+ });
+
it('Shell 卸载(route 切换)后 popup 仍被常驻 router 路由,不丢事件', async () => {
// popup 订阅在窗口级常驻模块,不随 Shell 生命周期:用户离开聊天视图 / main
// 端归属等待期间 route 切换,归属明确的 popup 照常落 opener session。
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 46d7a1e8dc..a6b2cd23b0 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
@@ -19,6 +19,7 @@ import {
isPopupSpawnedTab,
markPopupSpawnedTab,
} from '../lib/popupTabs';
+import { browserWebviewPool } from '../lib/browserWebviewPool';
import type { TabKindPlugin } from '../types';
// device-link origin 注册表桩:'remote-' 前缀的 sessionId 视为远程会话。
@@ -98,6 +99,7 @@ describe('RSB store', () => {
store._resetStore();
_resetTabKindRegistry();
_resetPopupTabsForTests();
+ vi.restoreAllMocks();
});
describe('getBucket', () => {
@@ -458,6 +460,16 @@ describe('RSB store', () => {
});
describe('closeTab', () => {
+ it('releases an ordinary browser WebView only after its tab is really closed', async () => {
+ const release = vi.spyOn(browserWebviewPool, 'release').mockImplementation(() => undefined);
+ const tab = await store.addTab('s1', 'web-browser', null);
+
+ await store.closeTab('s1', tab.id);
+
+ expect(release).toHaveBeenCalledOnce();
+ expect(release).toHaveBeenCalledWith(tab.id);
+ });
+
it('清掉 tabId 上的 popup 来源标记(任何关闭入口,不只 guest 自关)', async () => {
const tab = await store.addTab('s1', 'web-browser', null, {
onOptimisticAdd: markPopupSpawnedTab,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/hooks/__tests__/useBrowserWebview.test.ts b/apps/desktop/src/renderer/features/right-sidebar/hooks/__tests__/useBrowserWebview.test.ts
index 3a0fb3e761..083a358dcf 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/hooks/__tests__/useBrowserWebview.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/hooks/__tests__/useBrowserWebview.test.ts
@@ -181,7 +181,7 @@ describe('useBrowserWebview', () => {
expect(result!.webview).toBe(mockWebview);
});
- it('touches an existing entry through acquire when it becomes visible', async () => {
+ it('keeps an existing wrapper stable when a visible tab becomes hidden', async () => {
const { browserWebviewPool } = await import('../../lib/browserWebviewPool');
const existing: MockPoolEntry = {
wrapper: document.createElement('div'),
@@ -191,7 +191,7 @@ describe('useBrowserWebview', () => {
poolMocks.currentEntry = existing;
let result: UseBrowserWebviewResult | null = null;
- render(createElement(HookProbe, {
+ const view = render(createElement(HookProbe, {
visible: true,
onResult: (next) => { result = next; },
}));
@@ -199,6 +199,14 @@ describe('useBrowserWebview', () => {
expect(browserWebviewPool.acquire).toHaveBeenCalledOnce();
expect(result!.wrapper).toBe(existing.wrapper);
expect(result!.webview).toBe(mockWebview);
+
+ view.rerender(createElement(HookProbe, {
+ visible: false,
+ onResult: (next) => { result = next; },
+ }));
+
+ expect(result!.wrapper).toBe(existing.wrapper);
+ expect(result!.webview).toBe(mockWebview);
});
it('observes an entry explicitly created while hidden without navigating it', async () => {
@@ -214,7 +222,7 @@ describe('useBrowserWebview', () => {
});
expect(browserWebviewPool.acquire).toHaveBeenCalledOnce();
- expect(result!.wrapper).toBeNull();
+ expect(result!.wrapper).not.toBeNull();
expect(result!.webview).toBe(mockWebview);
expect(mockWebview.addEventListener).toHaveBeenCalledWith(
'render-process-gone',
diff --git a/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts b/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts
index f2f7c240a3..561f8d000f 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts
@@ -112,6 +112,7 @@ export function useBrowserWebview(
tabId: string,
sessionId?: string,
visible?: boolean,
+ enabled = true,
): UseBrowserWebviewResult {
// pool entry 引用 + 反应式 state。entry 本身在 pool 模块管;hook 只观察。
const [wrapper, setWrapper] = useState<HTMLDivElement | null>(null);
@@ -143,6 +144,7 @@ export function useBrowserWebview(
visibleRef.current = visible === true;
useEffect(() => {
+ if (!enabled) return;
const unsubRelease = browserWebviewPool.onRelease((releasedTabId) => {
if (releasedTabId !== tabId) return;
// 已释放的 wrapper 不再属于 Pool,先撤销发布,避免下一次渲染把旧代际
@@ -164,7 +166,7 @@ export function useBrowserWebview(
unsubRelease();
unsubEntryCreated();
};
- }, [tabId]);
+ }, [enabled, tabId]);
const setObservedUrl = useCallback((nextUrl: string) => {
const suppress = suppressStaleUrlRef.current;
@@ -184,6 +186,7 @@ export function useBrowserWebview(
}, []);
useEffect(() => {
+ if (!enabled) return;
// Shell 会常驻挂载所有 TabBody;没有明确可见时,只复用已有 entry,不首次
// 物化 webview,避免恢复会话就在后台加载持久化 URL。
const existing = browserWebviewPool.peek(tabId);
@@ -427,7 +430,7 @@ export function useBrowserWebview(
// **不**释放 pool entry —— webview DOM 节点继续保活,切回该 tab 时可直接
// 复用。释放是 plugin 在用户主动关闭 tab 时显式调 pool.release(tabId)。
};
- }, [tabId, sessionId, setObservedUrl, entryEpoch, visible]);
+ }, [enabled, tabId, sessionId, setObservedUrl, entryEpoch, visible]);
const navigate = useCallback((nextUrl: string) => {
const wv = webviewRef.current;
@@ -506,13 +509,16 @@ export function useBrowserWebview(
}
}, []);
const dismissResourceAlert = useCallback(() => setResourceAlert(null), []);
- const currentEntry = browserWebviewPool.peek(tabId);
+ const currentEntry = enabled ? browserWebviewPool.peek(tabId) : undefined;
const currentWebview = currentEntry?.wrapper === wrapper ? currentEntry.webview : null;
return {
- // 隐藏时仍观察已有 entry 的 guest 生命周期,但不把 wrapper 交给 caller,
- // 避免隐藏 Body 把它移出停车区并触发首次导航。
- wrapper: visible === true ? wrapper : null,
+ // 隐藏 tab 不首次 acquire(见上方 existing/visible 守门),也不会触发首次导航;
+ // 但已经存在的 wrapper 必须持续交给常驻 TabBody,让它留在自己的 hidden slot。
+ // 若这里因 visible=false 返回 null,BrowserTabBody 会执行 layout cleanup,把
+ // webview reparent 到 parking;Electron 会因此重建 guest WebContents,破坏
+ // window.open 的 opener browsing context 与 WindowProxy 身份。
+ wrapper: enabled ? wrapper : null,
webview: currentWebview,
url,
title,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts b/apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts
new file mode 100644
index 0000000000..00069dd654
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts
@@ -0,0 +1,162 @@
+import { useCallback, useEffect, useState, type RefObject } from 'react';
+
+import { createLogger } from '@/lib/logger';
+
+import type {
+ RsbNativePopupCommand,
+ RsbNativePopupSnapshot,
+} from '../../../../shared/rsbNativePopup';
+import type { UseBrowserWebviewResult } from './useBrowserWebview';
+
+const log = createLogger('rightSidebar.nativePopupSurface');
+
+const EMPTY_SNAPSHOT: RsbNativePopupSnapshot = {
+ url: 'about:blank',
+ title: '',
+ favicon: null,
+ isLoading: false,
+ canGoBack: false,
+ canGoForward: false,
+ isAudible: false,
+ crash: null,
+};
+
+export interface UseNativePopupSurfaceResult extends UseBrowserWebviewResult {
+ closed: boolean;
+}
+
+export function useNativePopupSurface(
+ surfaceId: string | undefined,
+ sessionId: string | undefined,
+ tabId: string,
+ slotRef: RefObject<HTMLDivElement | null>,
+ visible: boolean,
+): UseNativePopupSurfaceResult {
+ const [snapshot, setSnapshot] = useState<RsbNativePopupSnapshot>(EMPTY_SNAPSHOT);
+ const [closed, setClosed] = useState(false);
+
+ useEffect(() => {
+ if (!surfaceId || !sessionId) return;
+ let cancelled = false;
+ const off = window.electronAPI.rsbNativePopup.onEvent((event) => {
+ if (event.surfaceId !== surfaceId) return;
+ if (event.type === 'closed') {
+ setClosed(true);
+ } else {
+ setSnapshot(event.snapshot);
+ }
+ });
+ void window.electronAPI.rsbNativePopup
+ .claim({ surfaceId, sessionId, tabId })
+ .then((result) => {
+ if (cancelled) return;
+ if (!result.alive) {
+ setClosed(true);
+ return;
+ }
+ setSnapshot(result.snapshot);
+ })
+ .catch((err) => {
+ if (!cancelled) log.warn('native popup claim failed', { surfaceId, err });
+ });
+ return () => {
+ cancelled = true;
+ off();
+ };
+ }, [sessionId, surfaceId, tabId]);
+
+ useEffect(() => {
+ if (!surfaceId) return;
+ const slot = slotRef.current;
+ let frame = 0;
+ const sync = () => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ const rect = slot?.getBoundingClientRect();
+ const left = rect ? Math.max(0, Math.ceil(rect.left)) : 0;
+ const top = rect ? Math.max(0, Math.ceil(rect.top)) : 0;
+ const right = rect ? Math.min(window.innerWidth, Math.floor(rect.right)) : 1;
+ const bottom = rect ? Math.min(window.innerHeight, Math.floor(rect.bottom)) : 1;
+ const width = Math.max(1, right - left);
+ const height = Math.max(1, bottom - top);
+ const actuallyVisible =
+ visible &&
+ Boolean(rect) &&
+ rect!.width > 0 &&
+ rect!.height > 0 &&
+ right > left &&
+ bottom > top;
+ void window.electronAPI.rsbNativePopup
+ .setBounds({
+ surfaceId,
+ bounds: { x: left, y: top, width, height },
+ visible: actuallyVisible,
+ })
+ .catch(() => undefined);
+ });
+ };
+ const resizeObserver = slot ? new ResizeObserver(sync) : null;
+ if (slot) resizeObserver?.observe(slot);
+ const intersectionObserver = slot ? new IntersectionObserver(sync) : null;
+ if (slot) intersectionObserver?.observe(slot);
+ window.addEventListener('resize', sync);
+ window.addEventListener('scroll', sync, true);
+ sync();
+ return () => {
+ cancelAnimationFrame(frame);
+ resizeObserver?.disconnect();
+ intersectionObserver?.disconnect();
+ window.removeEventListener('resize', sync);
+ window.removeEventListener('scroll', sync, true);
+ void window.electronAPI.rsbNativePopup
+ .setBounds({
+ surfaceId,
+ bounds: { x: 0, y: 0, width: 1, height: 1 },
+ visible: false,
+ })
+ .catch(() => undefined);
+ };
+ }, [slotRef, surfaceId, visible]);
+
+ const command = useCallback(
+ (input: RsbNativePopupCommand) => {
+ if (!surfaceId) return;
+ void window.electronAPI.rsbNativePopup
+ .command({ ...input, surfaceId })
+ .catch((err) => log.warn('native popup command failed', { surfaceId, err }));
+ },
+ [surfaceId],
+ );
+
+ const navigate = useCallback(
+ (url: string) => {
+ setSnapshot((current) => ({ ...current, url, favicon: null, isLoading: true, crash: null }));
+ command({ command: 'navigate', url });
+ },
+ [command],
+ );
+ const reload = useCallback(() => {
+ setSnapshot((current) => ({ ...current, isLoading: true, crash: null }));
+ command({ command: 'reload' });
+ }, [command]);
+ const goBack = useCallback(() => command({ command: 'go-back' }), [command]);
+ const goForward = useCallback(() => command({ command: 'go-forward' }), [command]);
+ const stop = useCallback(() => {
+ setSnapshot((current) => ({ ...current, isLoading: false }));
+ command({ command: 'stop' });
+ }, [command]);
+
+ return {
+ wrapper: null,
+ webview: null,
+ ...snapshot,
+ resourceAlert: null,
+ navigate,
+ reload,
+ goBack,
+ goForward,
+ stop,
+ dismissResourceAlert: () => undefined,
+ closed,
+ };
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts
new file mode 100644
index 0000000000..7e3883335d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts
@@ -0,0 +1,41 @@
+/** Runtime-only relation between persisted RSB tab ids and main-owned popup surfaces. */
+
+const byTabId = new Map<string, { surfaceId: string; sessionId: string }>();
+const bySurfaceId = new Map<string, { tabId: string; sessionId: string }>();
+
+export function registerNativePopupTab(tabId: string, sessionId: string, surfaceId: string): void {
+ byTabId.set(tabId, { surfaceId, sessionId });
+ bySurfaceId.set(surfaceId, { tabId, sessionId });
+}
+
+export function findNativePopupTabBySurface(
+ surfaceId: string,
+): { tabId: string; sessionId: string } | null {
+ return bySurfaceId.get(surfaceId) ?? null;
+}
+
+/** Runtime lookup used after plugin hydration strips non-persistent fields. */
+export function findNativePopupSurfaceForTab(
+ tabId: string,
+): { surfaceId: string; sessionId: string } | null {
+ return byTabId.get(tabId) ?? null;
+}
+
+/** Called only after the store has definitively removed the tab. */
+export function closeNativePopupForTab(tabId: string): void {
+ const entry = byTabId.get(tabId);
+ if (!entry) return;
+ byTabId.delete(tabId);
+ bySurfaceId.delete(entry.surfaceId);
+ const api = typeof window !== 'undefined' ? window.electronAPI?.rsbNativePopup : undefined;
+ if (!api) return;
+ void api.close({ surfaceId: entry.surfaceId }).catch(() => {
+ // Guest window.close may have destroyed the surface before store cleanup.
+ });
+}
+
+/** Test-only reset. */
+export function _resetNativePopupTabsForTests(): void {
+ byTabId.clear();
+ bySurfaceId.clear();
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts
index 591178b7a6..e5cd956721 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts
@@ -21,9 +21,10 @@
import { createLogger } from '@/lib/logger';
-import { addTab, ensureHydrated, getBucket } from '../store';
+import { addTab, closeTab, ensureHydrated, getBucket } from '../store';
import { eagerSpawnAndReport } from './rsbBrowserBridge';
import { markPopupSpawnedTab } from './popupTabs';
+import { findNativePopupTabBySurface, registerNativePopupTab } from './nativePopupTabs';
import { requestRightSidebarVisibility } from './sidebarCommands';
const log = createLogger('rightSidebar.popupRouter');
@@ -59,11 +60,14 @@ export function initPopupRouter(): () => void {
}
initialized = true;
- const off = api.onRsbBrowserPopup(({ url, openerSessionId }) => {
+ const offPopup = api.onRsbBrowserPopup(({ url, openerSessionId, nativePopupSurfaceId }) => {
const targetSessionId = openerSessionId ?? fallbackSessionId;
if (!targetSessionId) {
// 既无 opener 归属也无任何已知 session(冷启动即触发)——丢弃优于瞎猜。
log.warn('popup dropped: no opener attribution and no known session', { url });
+ if (nativePopupSurfaceId) {
+ void api.rsbNativePopup.close({ surfaceId: nativePopupSurfaceId }).catch(() => undefined);
+ }
return;
}
// 给新 tab 一份完整 default state,只把 url 替换成 popup URL;hydrateState
@@ -74,6 +78,7 @@ export function initPopupRouter(): () => void {
title: '',
favicon: null,
isAudible: false,
+ ...(nativePopupSurfaceId ? { nativePopupSurfaceId } : {}),
};
void (async () => {
// 写 bucket 前一律先水合(含当前 session):store 契约要求先 hydrated 再写 ——
@@ -86,12 +91,33 @@ export function initPopupRouter(): () => void {
// addTab resolve:持久化 IPC 在途期间 React 已可能 mount webview 并加载完
// callback 页,快速 window.close 会赶在登记前到达且 close 事件不重发。
const newTab = await addTab(targetSessionId, 'web-browser', initialState, {
- onOptimisticAdd: markPopupSpawnedTab,
+ onOptimisticAdd: (tabId) => {
+ markPopupSpawnedTab(tabId);
+ if (nativePopupSurfaceId) {
+ registerNativePopupTab(tabId, targetSessionId, nativePopupSurfaceId);
+ }
+ },
});
// addTab IPC(upsert/setActive)在途期间用户可能已关闭该 tab —— closeTab
// 乐观移除 + ipc.close 落库后,tab 已不在 bucket 里。若此时仍 eagerSpawn,
// 会在 pool/Main registry 里留下孤立入口并重新加载 OAuth URL(Codex P1)。
if (!getBucket(targetSessionId).tabs.some((t) => t.id === newTab.id)) return;
+ if (nativePopupSurfaceId) {
+ // Claim immediately so main can register the exact popup WebContents,
+ // deliver self-close, and pin both popup + ordinary webview opener.
+ const claimed = await api.rsbNativePopup.claim({
+ surfaceId: nativePopupSurfaceId,
+ sessionId: targetSessionId,
+ tabId: newTab.id,
+ });
+ if (!claimed.alive) {
+ await closeTab(targetSessionId, newTab.id);
+ return;
+ }
+ } else {
+ // Legacy/non-native payloads still materialize an ordinary webview.
+ await eagerSpawnAndReport(targetSessionId, newTab.id, url);
+ }
// 一律离屏物化,不区分目标 session 是否当前:
// - 跨 session / Shell 已卸载:没有 BrowserTabBody 去出生 webview;
// - 同 session 但侧栏折叠:Shell 挂着但 shellVisible=false,#700 之后隐藏
@@ -99,7 +125,6 @@ export function initPopupRouter(): () => void {
// 各形态都没有别的物化路径(与 main 端 open tab-op 的 eagerSpawnAndReport
// 同理);侧栏可见时 TabBody 会 acquire 同一个 pool entry,eagerSpawn 幂等
// 复用,无副作用。
- await eagerSpawnAndReport(targetSessionId, newTab.id, url);
// 物化期间 tab 可能已经没了:OAuth callback 页在 dom-ready 前就
// window.close()(guest 自关路径会把最后一个 tab 关掉并请求收起侧栏),
// 或用户手动关了它。此时再无条件请求 'open' 会把刚写的"收起"存档翻回
@@ -115,11 +140,26 @@ export function initPopupRouter(): () => void {
});
})().catch((err) => {
log.error('rsb popup → addTab failed', { sessionId: targetSessionId, url, err });
+ if (nativePopupSurfaceId) {
+ void api.rsbNativePopup.close({ surfaceId: nativePopupSurfaceId }).catch(() => undefined);
+ }
});
});
+ const offNative = api.rsbNativePopup
+ ? api.rsbNativePopup.onEvent((event) => {
+ if (event.type !== 'closed') return;
+ const tab = findNativePopupTabBySurface(event.surfaceId);
+ if (!tab) return;
+ void closeTab(tab.sessionId, tab.tabId).catch((err) => {
+ log.warn('native popup self-close → closeTab failed', { ...tab, err });
+ });
+ })
+ : () => undefined;
+
teardown = () => {
- off();
+ offPopup();
+ offNative();
};
return teardown;
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx
index f67c3fd146..66792bac79 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx
@@ -85,6 +85,8 @@ export interface BrowserChromeProps {
onOpenInSystemBrowser: () => void;
/** 「更多」菜单项:复制当前页链接到剪贴板(反馈 toast 由 TabBody 做)。 */
onCopyLink: () => void;
+ /** 原生 popup view 必须在 renderer portal 打开时暂时让出层叠空间。 */
+ onOverlayOpenChange?: (open: boolean) => void;
}
/** Imperative ref —— 父组件(BrowserTabBody)用 keydown 监听 Cmd/Ctrl+L,调
@@ -112,6 +114,7 @@ export const BrowserChrome = forwardRef<BrowserChromeHandle, BrowserChromeProps>
canOpenInSystemBrowser,
onOpenInSystemBrowser,
onCopyLink,
+ onOverlayOpenChange,
},
ref,
) {
@@ -292,7 +295,7 @@ export const BrowserChrome = forwardRef<BrowserChromeHandle, BrowserChromeProps>
)}
{/* 更多菜单:trigger 复用 chrome 图标按钮视觉(默认态 + 菜单打开时 active 高亮,
走 data-[state=open])。菜单项在无有效链接(新标签空白态)时置灰。 */}
- <DropdownMenu>
+ <DropdownMenu onOpenChange={onOverlayOpenChange}>
<DropdownMenuTrigger asChild>
<button
type="button"
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
index f7176a3099..8f140f86a3 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
@@ -27,7 +27,7 @@
* 跳过避免双重 load。
*/
-import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { AlertTriangle, Gauge, RotateCw, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -39,6 +39,7 @@ import { cn } from '@/lib/utils';
import { mapIpcErrorToI18nKey } from '@/utils/ipcError';
import { browserWebviewPool } from '../../lib/browserWebviewPool';
+import { findNativePopupSurfaceForTab } from '../../lib/nativePopupTabs';
import {
forceKillBrowserTab,
setForegroundBrowserTab,
@@ -46,6 +47,7 @@ import {
import { isLocalHtmlFileUrl } from '../../lib/openInSidebarBrowser';
import { closeTab } from '../../store';
import { useBrowserWebview } from '../../hooks/useBrowserWebview';
+import { useNativePopupSurface } from '../../hooks/useNativePopupSurface';
import type { TabKindHostContext } from '../../types';
import { BrowserChrome, type BrowserChromeHandle } from './BrowserChrome';
@@ -93,11 +95,27 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
// 真实可见性:顶层 active tab 且整个侧栏展开。shellVisible 缺省(旧宿主 /
// 测试)按可见处理,与 active 的既有缺省语义一致。
const tabVisible = active === true && shellVisible !== false;
+ const [chromeOverlayOpen, setChromeOverlayOpen] = useState(false);
// BrowserChrome 的 imperative ref —— Cmd/Ctrl+L 快捷键调它的 focusUrlBar()。
const chromeRef = useRef<BrowserChromeHandle>(null);
const rootRef = useRef<HTMLDivElement>(null);
const slotRef = useRef<HTMLDivElement>(null);
- const browser = useBrowserWebview(tabId, sessionId, tabVisible);
+ // hydrateState runs before every TabBody render and intentionally strips
+ // persisted native ids (surfaces do not survive restart). Recover the live
+ // id from the process-local tab↔surface relation registered in the same
+ // optimistic tick as addTab.
+ const nativePopupSurfaceId =
+ findNativePopupSurfaceForTab(tabId)?.surfaceId ?? state.nativePopupSurfaceId;
+ const isNativePopup = Boolean(nativePopupSurfaceId);
+ const webviewBrowser = useBrowserWebview(tabId, sessionId, tabVisible, !isNativePopup);
+ const nativeBrowser = useNativePopupSurface(
+ nativePopupSurfaceId,
+ sessionId,
+ tabId,
+ slotRef,
+ tabVisible && !chromeOverlayOpen,
+ );
+ const browser = isNativePopup ? nativeBrowser : webviewBrowser;
const lastNavigatedWrapperRef = useRef<HTMLDivElement | null>(null);
const stateUrlRef = useRef(state.url);
const browserUrlRef = useRef(browser.url);
@@ -122,12 +140,15 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
});
// 把 pool 的 wrapper 挂进 slot —— useLayoutEffect(在 paint 前移 DOM,避免闪)。
- // 卸载时把 wrapper 挪回 pool 的 off-screen container 保活 webContents。
- // 切到不同 tabId 时:wrapper 引用变,effect 重跑,旧 wrapper 自动回 parking 区。
+ // Shell 会常驻挂载所有 TabBody,并用父节点 display:none 隐藏后台 tab;wrapper
+ // 一旦进入自己的 slot 就不要再随 active 切换搬回 parking。Electron 的 webview
+ // 在跨父节点 reparent 时可能重建 guest WebContents,这会销毁 window.open 的
+ // opener browsing context,连带 outlivesOpener:false 的原生 popup 一起销毁。
+ // 只有 TabBody 真正卸载或 wrapper 代际变化时 effect cleanup 才停回 parking。
useLayoutEffect(() => {
const slot = slotRef.current;
const wrapper = browser.wrapper;
- if (!tabVisible || !slot || !wrapper) return;
+ if (!slot || !wrapper) return;
slot.appendChild(wrapper);
return () => {
// release / LRU 淘汰后的旧 wrapper 已不再属于 Pool,不能因 React effect
@@ -143,7 +164,7 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
wrapper.remove();
}
};
- }, [browser.wrapper, tabId, tabVisible]);
+ }, [browser.wrapper, tabId]);
// hook 事件 → patchState。注意 onPatchState 引用稳定,这里只在 url / title /
// favicon 真实改变(由 webview 推上来)时才写回,不会无限循环。
@@ -202,7 +223,8 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
// 是空的,必须重新用持久化 URL 驱动一次加载(review P1:淘汰后空壳)。
useEffect(() => {
const wrapper = browser.wrapper;
- if (!tabVisible || !wrapper || lastNavigatedWrapperRef.current === wrapper) return;
+ if (isNativePopup || !tabVisible || !wrapper || lastNavigatedWrapperRef.current === wrapper)
+ return;
lastNavigatedWrapperRef.current = wrapper;
const nextUrl = stateUrlRef.current || 'about:blank';
const currentUrl = browserUrlRef.current;
@@ -210,7 +232,14 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
// about:blank 默认状态下也要 navigate,确保 webview 真的处于 about:blank,
// 不会停留在 pool 创建时未 setAttribute('src') 的"未初始化"状态。
navigateRef.current(nextUrl);
- }, [tabId, browser.wrapper, tabVisible]);
+ }, [tabId, browser.wrapper, isNativePopup, tabVisible]);
+
+ useEffect(() => {
+ if (!isNativePopup || !nativeBrowser.closed) return;
+ void closeTab(sessionId, tabId).catch((err) => {
+ log.warn('close native popup tab after guest window.close failed', err);
+ });
+ }, [isNativePopup, nativeBrowser.closed, sessionId, tabId]);
const reloadRef = useRef(browser.reload);
const goBackRef = useRef(browser.goBack);
@@ -334,8 +363,7 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
if (canGoForwardRef.current) goForwardRef.current();
} else if (command === 'close-tab') {
// guest 内 ⌘W / Ctrl+W:关掉本 tab,与焦点在 host 侧右侧栏内按 ⌘W 的
- // 行为对齐(store.closeTab 同路径,BrowserTabBody unmount 时 effect
- // cleanup 释放 pool entry)。
+ // 行为对齐(store.closeTab 同路径;确认关闭后由 store 释放 pool entry)。
void closeTab(sessionId, tabId).catch((err) => {
log.warn('close tab via guest shortcut failed', err);
});
@@ -346,19 +374,6 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
return off;
}, [active, sessionId, tabId]);
- // tab 关闭 / 整个 plugin 卸载时,显式释放 pool entry。
- // 注意:tabId 切换不应释放(切只是 hook 重新 acquire 别的 entry,旧 entry 保活)。
- // 这里只在 BrowserTabBody 真正 unmount(tab 被关闭)时 cleanup —— 用 effect
- // 空 deps,React 会在组件 unmount 时跑 cleanup。但如果 tabId 是 prop,React
- // 不知道"换 tabId == 换 tab",得手动同步当前 tabId 给 cleanup 闭包。
- const releaseTabIdRef = useRef(tabId);
- releaseTabIdRef.current = tabId;
- useEffect(() => {
- return () => {
- browserWebviewPool.release(releaseTabIdRef.current);
- };
- }, []);
-
// 截图:main 端对当前 tab 的 webview capturePage → 系统剪贴板。
// 反馈只用 toast(成功 / 失败各一条),不做视觉动画。
const handleCaptureScreenshot = useCallback(async () => {
@@ -474,6 +489,7 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB
canOpenInSystemBrowser={canOpenInSystemBrowser}
onOpenInSystemBrowser={handleOpenInSystemBrowser}
onCopyLink={handleCopyLink}
+ onOverlayOpenChange={setChromeOverlayOpen}
/>
{/* webview slot:flex-1 占满剩余空间。pool 的 wrapper 用 100% width/height
填满,所以这里不需要再设尺寸。
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
index b07198f723..e2eade7c0b 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
@@ -7,6 +7,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { UseBrowserWebviewResult } from '../../../hooks/useBrowserWebview';
import type { TabKindHostContext } from '../../../types';
+import {
+ _resetNativePopupTabsForTests,
+ registerNativePopupTab,
+} from '../../../lib/nativePopupTabs';
+import { browserWebviewPool } from '../../../lib/browserWebviewPool';
import { BrowserTabBody } from '../BrowserTabBody';
import { useLocalHtmlAutoReload } from '../useLocalHtmlAutoReload';
@@ -17,6 +22,7 @@ const toastMocks = vi.hoisted(() => ({
const browserNavigate = vi.fn();
let browserState: UseBrowserWebviewResult;
+const nativePopupHook = vi.hoisted(() => vi.fn());
const poolMocks = vi.hoisted(() => ({
currentWrapper: null as HTMLDivElement | null,
@@ -33,8 +39,28 @@ vi.mock('@/lib/toast', () => ({ toast: toastMocks }));
vi.mock('@/components/ui/dropdown-menu', () => {
const react = require('react') as typeof import('react');
return {
- DropdownMenu: ({ children }: { children: React.ReactNode }) =>
- react.createElement(react.Fragment, null, children),
+ DropdownMenu: ({
+ children,
+ onOpenChange,
+ }: {
+ children: React.ReactNode;
+ onOpenChange?: (open: boolean) => void;
+ }) =>
+ react.createElement(
+ react.Fragment,
+ null,
+ react.createElement('button', {
+ type: 'button',
+ 'aria-label': 'mock.dropdown.open',
+ onClick: () => onOpenChange?.(true),
+ }),
+ react.createElement('button', {
+ type: 'button',
+ 'aria-label': 'mock.dropdown.close',
+ onClick: () => onOpenChange?.(false),
+ }),
+ children,
+ ),
DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) =>
react.createElement(react.Fragment, null, children),
DropdownMenuContent: ({ children }: { children: React.ReactNode }) =>
@@ -60,6 +86,10 @@ vi.mock('../../../hooks/useBrowserWebview', () => ({
useBrowserWebview: () => browserState,
}));
+vi.mock('../../../hooks/useNativePopupSurface', () => ({
+ useNativePopupSurface: (...args: unknown[]) => nativePopupHook(...args),
+}));
+
vi.mock('../useLocalHtmlAutoReload', () => ({
useLocalHtmlAutoReload: vi.fn(),
}));
@@ -144,6 +174,11 @@ function renderBrowserTab(
describe('BrowserTabBody navigation', () => {
beforeEach(() => {
+ _resetNativePopupTabsForTests();
+ nativePopupHook.mockReturnValue({
+ ...makeBrowserState({ wrapper: null, webview: null, url: 'about:blank' }),
+ closed: false,
+ });
Object.defineProperty(window, 'electronAPI', {
configurable: true,
value: {
@@ -158,6 +193,7 @@ describe('BrowserTabBody navigation', () => {
afterEach(() => {
cleanup();
+ _resetNativePopupTabsForTests();
poolMocks.currentWrapper = null;
document.getElementById('browser-webview-pool')?.remove();
vi.clearAllMocks();
@@ -166,7 +202,48 @@ describe('BrowserTabBody navigation', () => {
browserState = makeBrowserState();
});
- it('keeps an eagerly created hidden wrapper parked without navigating', () => {
+ it('recovers a live native popup surface after plugin hydration strips its id', () => {
+ registerNativePopupTab('tab-browser', 'session-a', 'surface-oauth');
+ browserState = makeBrowserState({ wrapper: sharedWrapper, url: 'about:blank' });
+
+ render(renderBrowserTab('about:blank'));
+
+ expect(nativePopupHook).toHaveBeenLastCalledWith(
+ 'surface-oauth',
+ 'session-a',
+ 'tab-browser',
+ expect.any(Object),
+ true,
+ );
+ expect(sharedWrapper.isConnected).toBe(false);
+ expect(browserNavigate).not.toHaveBeenCalled();
+ });
+
+ it('hides a native popup view while the renderer more-menu portal is open', () => {
+ registerNativePopupTab('tab-browser', 'session-a', 'surface-oauth');
+ browserState = makeBrowserState({ wrapper: sharedWrapper, url: 'about:blank' });
+ render(renderBrowserTab('about:blank'));
+
+ fireEvent.click(screen.getByRole('button', { name: 'mock.dropdown.open' }));
+ expect(nativePopupHook).toHaveBeenLastCalledWith(
+ 'surface-oauth',
+ 'session-a',
+ 'tab-browser',
+ expect.any(Object),
+ false,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'mock.dropdown.close' }));
+ expect(nativePopupHook).toHaveBeenLastCalledWith(
+ 'surface-oauth',
+ 'session-a',
+ 'tab-browser',
+ expect.any(Object),
+ true,
+ );
+ });
+
+ it('keeps a hidden wrapper in its tab slot without navigating or reparenting on activation', () => {
const parking = document.createElement('div');
parking.id = 'browser-webview-pool';
document.body.appendChild(parking);
@@ -176,16 +253,32 @@ describe('BrowserTabBody navigation', () => {
const view = render(renderBrowserTab('https://example.com/persisted', vi.fn(), false));
- expect(sharedWrapper.parentElement).toBe(parking);
+ const hiddenSlot = sharedWrapper.parentElement;
+ expect(hiddenSlot).not.toBe(parking);
expect(browserNavigate).not.toHaveBeenCalled();
view.rerender(renderBrowserTab('https://example.com/persisted', vi.fn(), true));
- expect(sharedWrapper.parentElement).not.toBe(parking);
+ expect(sharedWrapper.parentElement).toBe(hiddenSlot);
expect(browserNavigate).toHaveBeenCalledOnce();
expect(browserNavigate).toHaveBeenCalledWith('https://example.com/persisted');
});
+ it('parks an opener webview without releasing it when the shell unmounts', () => {
+ const parking = document.createElement('div');
+ parking.id = 'browser-webview-pool';
+ document.body.appendChild(parking);
+ parking.appendChild(sharedWrapper);
+ poolMocks.currentWrapper = sharedWrapper;
+ browserState = makeBrowserState({ wrapper: sharedWrapper });
+ const view = render(renderBrowserTab('https://www.taptap.cn/'));
+
+ view.unmount();
+
+ expect(sharedWrapper.parentElement).toBe(parking);
+ expect(browserWebviewPool.release).not.toHaveBeenCalled();
+ });
+
it('does not reconnect a released wrapper when a replacement arrives', () => {
const parking = document.createElement('div');
parking.id = 'browser-webview-pool';
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 4d915cbd96..61fb21c11b 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
@@ -38,6 +38,9 @@ export interface WebBrowserState {
* 应当回到静默态,因为 webview 会重新加载),但运行时仍然写进 state 走 patchState
* 统一通道,UI 通过 state 拿。 */
isAudible: boolean;
+ /** Runtime-only id of a Chromium-created popup adopted by main. Hydration
+ * intentionally drops it because native surfaces do not survive restart. */
+ nativePopupSurfaceId?: string;
}
const DEFAULT_STATE: WebBrowserState = {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.ts
index c0b46db0e9..6b3d868f4b 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts
@@ -20,7 +20,9 @@ import { createLogger } from '@/lib/logger';
import { extractIpcError } from '@/utils/ipcError';
import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';
import { getTabKind } from './registry';
+import { browserWebviewPool } from './lib/browserWebviewPool';
import { unmarkPopupSpawnedTab } from './lib/popupTabs';
+import { closeNativePopupForTab } from './lib/nativePopupTabs';
import type { TabKindId, TabState } from './types';
const log = createLogger('rightSidebar.store');
@@ -550,7 +552,7 @@ export async function addTab(
setBucket(sessionId, { tabs: prev.tabs, activeTabId: prev.activeTabId });
// 这个 tab 从未存在过 —— `onOptimisticAdd` 里登记的旁路记录(popup 标记等)
// 必须跟着回滚,否则没有任何 closeTab 成功分支会来清它。
- forgetClosedTab(sessionId, id);
+ forgetClosedTab(sessionId, id, kind);
// rowCommitted=true 说明 upsert 已成功、SQLite 有这一行,但 addTab 整体失败
// (通常是 setActive 抛错)。cache 已回滚且没有调用方会再发 closeTab —— 走共享
// 的孤儿行清理(与 closeTab 创建失败分支同款 cleanupOrphanTabRow):
@@ -613,17 +615,21 @@ export function hasTabCloseInterceptor(tabId: string): boolean {
}
/**
- * tab 已确定从 store 消失后的收尾:清掉挂在 tabId 上的所有旁路记录。
+ * tab 已确定从 store 消失后的收尾:释放 browser pool entry,并清掉挂在 tabId
+ * 上的所有旁路记录。Shell / session 临时卸载只把 wrapper 停回 parking,不能在
+ * 那里释放 opener,否则 outlivesOpener:false 的原生 popup 会一起被 Chromium 关闭。
*
* 只在"真的没了"的分支调 —— close IPC 失败会回滚 cache(tab 还在),那时这些记录
* 必须留着。popup 来源标记同理:所有关闭入口(用户手关 / closeAllTabs / agent
* close tab-op / guest 自关)都汇聚到 closeTab,标记不会随某条路径泄漏。
*/
-function forgetClosedTab(sessionId: string, tabId: string): void {
+function forgetClosedTab(sessionId: string, tabId: string, kind: TabKindId): void {
const key = tabStateWriteKey(sessionId, tabId);
patchRevisions.delete(key);
persistedStateBaselines.delete(key);
+ if (kind === 'web-browser') browserWebviewPool.release(tabId);
unmarkPopupSpawnedTab(tabId);
+ closeNativePopupForTab(tabId);
}
/**
@@ -680,6 +686,7 @@ export async function closeTab(
const prev = getBucket(sessionId);
const idx = prev.tabs.findIndex((t) => t.id === tabId);
if (idx < 0) return;
+ const closingKind = prev.tabs[idx].kind;
const nextTabs = prev.tabs.filter((t) => t.id !== tabId);
let nextActiveId = prev.activeTabId;
if (tabId === prev.activeTabId) {
@@ -706,7 +713,7 @@ export async function closeTab(
// 不存在"复活失败 tab"的问题)——调用方至少拿到真实结果与日志留痕。
await settleTabStateWrites(sessionId, tabId);
await cleanupOrphanTabRow(sessionId, tabId, 'closeTab');
- forgetClosedTab(sessionId, tabId);
+ forgetClosedTab(sessionId, tabId, closingKind);
return;
}
try {
@@ -774,12 +781,12 @@ export async function closeTab(
}
}
}
- forgetClosedTab(sessionId, tabId);
+ forgetClosedTab(sessionId, tabId, closingKind);
} catch (err) {
// NOT_FOUND:行已被并发的 addTab rollback cleanup 或另一个 closeTab 删掉,
// cache 的乐观删除与 DB 已一致,不需要重新插回——回滚反而造成 cache/DB 分叉。
if (isTabRowMissingError(err)) {
- forgetClosedTab(sessionId, tabId);
+ forgetClosedTab(sessionId, tabId, closingKind);
return;
}
log.error('closeTab IPC failed; rolling back cache', { sessionId, tabId, err });
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 9720a38ee4..1c97a799a1 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2280,9 +2280,29 @@ interface ElectronAPI {
disposition: string;
openerTabId?: string;
openerSessionId?: string;
+ nativePopupSurfaceId?: string;
}) => void,
) => () => void;
+ /** Main-owned WebContentsView used only for Chromium-created popup contexts. */
+ rsbNativePopup: {
+ claim: (
+ input: import('../shared/rsbNativePopup').RsbNativePopupClaimInput,
+ ) => Promise<import('../shared/rsbNativePopup').RsbNativePopupClaimResult>;
+ setBounds: (input: {
+ surfaceId: string;
+ bounds: import('../shared/rsbNativePopup').RsbNativePopupBounds;
+ visible: boolean;
+ }) => Promise<{ ok: true }>;
+ command: (
+ input: { surfaceId: string } & import('../shared/rsbNativePopup').RsbNativePopupCommand,
+ ) => Promise<{ ok: true }>;
+ close: (input: { surfaceId: string }) => Promise<{ ok: true }>;
+ onEvent: (
+ callback: (event: import('../shared/rsbNativePopup').RsbNativePopupEvent) => void,
+ ) => () => void;
+ };
+
/**
* RSB web-browser plugin:guest webview 内按下 Cmd/Ctrl+L 时,main 端
* webview-security 用 before-input-event 拦截后推过来。BrowserTabBody 根据
diff --git a/apps/desktop/src/shared/rsbNativePopup.ts b/apps/desktop/src/shared/rsbNativePopup.ts
new file mode 100644
index 0000000000..c92d8d53fb
--- /dev/null
+++ b/apps/desktop/src/shared/rsbNativePopup.ts
@@ -0,0 +1,47 @@
+/**
+ * Main-owned RSB popup surface IPC contract.
+ *
+ * Popup pages are real child browsing contexts created by Chromium. Main adopts
+ * the exact pre-created WebContents into a WebContentsView; renderer only owns
+ * the sidebar tab chrome and reports the slot bounds.
+ */
+
+export const RSB_NATIVE_POPUP_CLAIM_CHANNEL = 'rsb-native-popup:claim';
+export const RSB_NATIVE_POPUP_SET_BOUNDS_CHANNEL = 'rsb-native-popup:set-bounds';
+export const RSB_NATIVE_POPUP_COMMAND_CHANNEL = 'rsb-native-popup:command';
+export const RSB_NATIVE_POPUP_CLOSE_CHANNEL = 'rsb-native-popup:close';
+export const RSB_NATIVE_POPUP_EVENT_CHANNEL = 'rsb-native-popup:event';
+
+export interface RsbNativePopupBounds {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface RsbNativePopupSnapshot {
+ url: string;
+ title: string;
+ favicon: string | null;
+ isLoading: boolean;
+ canGoBack: boolean;
+ canGoForward: boolean;
+ isAudible: boolean;
+ crash: { reason: string } | null;
+}
+
+export type RsbNativePopupEvent =
+ | { surfaceId: string; type: 'state'; snapshot: RsbNativePopupSnapshot }
+ | { surfaceId: string; type: 'closed' };
+
+export type RsbNativePopupCommand =
+ { command: 'navigate'; url: string } | { command: 'reload' | 'go-back' | 'go-forward' | 'stop' };
+
+export interface RsbNativePopupClaimInput {
+ surfaceId: string;
+ sessionId: string;
+ tabId: string;
+}
+
+export type RsbNativePopupClaimResult =
+ { alive: true; snapshot: RsbNativePopupSnapshot } | { alive: false };