Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(desktop): retain browser webviews in renderer (#17513)

Arvin Xu88495d5612f9
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index e32abf9b0a5..0fba3bfb4f2 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -29,6 +29,18 @@ affordances are product behavior.
**Correct approach:** drive the real UI as blocked and allowed roles, capture both
outcomes, and report raw/missing feedback as a UX finding.
+### L-E3 β€” Publishing synthetic displacement as passing layout evidence
+
+**Wrong approach:** apply a large temporary transform to isolate position syncing,
+then publish a screenshot while the product panel is visibly displaced.
+
+**Why it fails:** the numeric assertion may pass while the visual evidence depicts
+a broken product state and appears to prove the regression.
+
+**Correct approach:** capture the settled result of a real layout transition. Keep
+synthetic position probes as text evidence only, and restore the DOM before any
+passing screenshot.
+
## Product and interaction design
### L-D1 β€” Treating a status badge as the information hierarchy
diff --git a/apps/desktop/src/main/controllers/BrowserControlCtr.ts b/apps/desktop/src/main/controllers/BrowserControlCtr.ts
index d0c67891299..f43fa6a7d95 100644
--- a/apps/desktop/src/main/controllers/BrowserControlCtr.ts
+++ b/apps/desktop/src/main/controllers/BrowserControlCtr.ts
@@ -359,10 +359,6 @@ export default class BrowserControlCtr extends ControllerModule {
} as T;
}
- // Every tool call counts as use, so the pool's memory cap never discards a
- // page an agent is in the middle of driving.
- this.sidebar.touchPage(sessionId);
-
try {
return await action(guest);
} catch (error) {
@@ -379,9 +375,7 @@ export default class BrowserControlCtr extends ControllerModule {
}
/**
- * The overlay is injected into the page rather than drawn in renderer DOM: a
- * WebContentsView always paints above the window's web contents, so nothing
- * the renderer draws can sit on top of the page any more.
+ * The overlay is injected into the guest so it follows page scrolling and zoom.
*/
private inject(guest: WebContents, script: string) {
guest.executeJavaScript(script).catch((error: Error) => {
diff --git a/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts b/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
index aa0d1512458..ad362228fa4 100644
--- a/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
+++ b/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
@@ -6,28 +6,21 @@ import type {
BrowserSidebarPickedElement,
BrowserSidebarPickElementParams,
BrowserSidebarPickElementResult,
+ BrowserSidebarRegisterWebviewParams,
BrowserSidebarResult,
BrowserSidebarSessionParams,
BrowserSidebarState,
- BrowserSidebarViewportParams,
} from '@lobechat/electron-client-ipc';
-import type { BrowserWindow, WebContents } from 'electron';
-import {
- app as electronApp,
- BrowserWindow as ElectronBrowserWindow,
- session as electronSession,
- shell,
-} from 'electron';
+import type { WebContents } from 'electron';
+import { session as electronSession, shell, webContents as electronWebContents } from 'electron';
import type { AgentOverlayLabels } from '@/modules/browser/agentOverlayScript';
-import { BrowserPagePool } from '@/modules/browser/BrowserPagePool';
import type { PickedElementPayload } from '@/modules/browser/elementPickerScript';
import {
ELEMENT_PICKER_CANCEL_SCRIPT,
elementPickerScript,
} from '@/modules/browser/elementPickerScript';
import { importChromeLoginData } from '@/modules/browser/importChromeLoginData';
-import { getIpcContext } from '@/utils/ipc/base';
import { createLogger } from '@/utils/logger';
import { ControllerModule, IpcMethod } from './index';
@@ -86,20 +79,28 @@ const isSupportedNavigationUrl = (url: string): boolean => {
};
/**
- * Owns the in-app browser pages. Each page is a main-process `WebContentsView`,
- * not a renderer `<webview>`: page lifetime must not depend on a React component
- * being mounted, otherwise a background agent has no page of its own and its
- * `navigate` ends up hijacking whichever page the user is looking at.
- *
- * The renderer only reports where the panel is on screen (`setViewport`); the
- * pool hosts the matching view in the window that reported it.
+ * Owns the privileged operations for renderer-retained `<webview>` guests.
+ * The renderer keeps each guest mounted in either the visible browser pane or
+ * an off-screen host; the main process registers its WebContents so agent tools
+ * can continue driving it without coupling page lifetime to the visible pane.
*/
export default class BrowserSidebarCtr extends ControllerModule {
static override readonly groupName = 'browserSidebar';
private partitionConfigured = false;
- private pagePool?: BrowserPagePool;
+ private pages = new Map<
+ string,
+ {
+ error?: string;
+ faviconUrl?: string;
+ isLoading: boolean;
+ title: string;
+ url: string;
+ webContentsId: number;
+ }
+ >();
private overlayLabels: AgentOverlayLabels = DEFAULT_OVERLAY_LABELS;
+ private wiredWebContents = new Set<number>();
/**
* Bumped on every cancel, per session. `pickElement` awaits a pre-cancel
* before injecting its picker, so a `cancelElementPick` (e.g. the pane
@@ -110,21 +111,8 @@ export default class BrowserSidebarCtr extends ControllerModule {
*/
private pickCancelSeqs = new Map<string, number>();
- beforeAppReady() {
- electronApp.on('before-quit', () => this.disposePool());
-
- // The parking window is a real BrowserWindow, so while it is alive the app
- // never sees `window-all-closed` β€” and never quits on Windows/Linux. Tear the
- // pool down once the last app window has gone.
- electronApp.on('browser-window-created', (_event, window) => {
- window.once('closed', () => {
- if (!this.pagePool) return;
- const appWindows = ElectronBrowserWindow.getAllWindows().filter(
- (candidate) => !candidate.isDestroyed() && !this.pagePool!.isParkingWindow(candidate),
- );
- if (appWindows.length === 0) this.disposePool();
- });
- });
+ afterAppReady() {
+ this.configureBrowserSession();
}
/** One-shot capture of the visible page, returned as a data URL so the renderer can attach it to the chat input. */
@@ -147,8 +135,7 @@ export default class BrowserSidebarCtr extends ControllerModule {
/**
* Starts the in-page element picker and stays pending until the user clicks an
* element or the pick dies (Escape, restart, navigation). The picker UI lives
- * inside the guest page β€” a WebContentsView paints above all renderer DOM, so
- * no highlight drawn by the panel could sit on top of the page.
+ * inside the guest page so it tracks the page DOM and viewport precisely.
*/
@IpcMethod()
pickElement(params: BrowserSidebarPickElementParams): Promise<BrowserSidebarPickElementResult> {
@@ -302,11 +289,14 @@ export default class BrowserSidebarCtr extends ControllerModule {
return { error: `Unsupported URL: ${url}`, success: false };
}
- const page = this.pool.ensure(params.sessionId);
+ const page = this.pages.get(params.sessionId);
+ const webContents = this.getSessionWebContents(params.sessionId);
+ if (!page || !webContents) return { error: 'Browser is not ready', success: false };
+
page.url = url;
page.error = undefined;
- await page.view.webContents.loadURL(url).catch((error: Error) => {
+ await webContents.loadURL(url).catch((error: Error) => {
// A superseded navigation rejects here; the did-fail-load handler already
// records anything worth surfacing.
logger.debug(`Navigation to ${url} did not settle cleanly: ${error.message}`);
@@ -345,27 +335,25 @@ export default class BrowserSidebarCtr extends ControllerModule {
});
}
- /**
- * The renderer reports the panel rect (in its own window's coordinates) on every
- * layout change; a missing/degenerate rect means "nobody is looking at this
- * page", which parks it rather than destroying it.
- *
- * The rect is hosted in the *sender's* window, not the main one: the agent route
- * also renders in standalone `chatSingle` windows, and placing the view in the
- * main window would leave the standalone panel blank and paint the page over the
- * wrong window.
- */
+ /** Register (or activate) the retained guest owned by the calling renderer. */
@IpcMethod()
- setViewport(params: BrowserSidebarViewportParams): BrowserSidebarResult {
- const { rect, sessionId } = params;
- const host = this.getSenderWindow();
-
- if (!rect || rect.width < 1 || rect.height < 1 || !host) {
- this.pool.hide(sessionId, host);
- return { success: true };
+ registerWebview(params: BrowserSidebarRegisterWebviewParams): BrowserSidebarResult {
+ const webContents = electronWebContents.fromId(params.webContentsId);
+ if (!webContents || webContents.isDestroyed()) {
+ return { error: 'Browser webview is not ready', success: false };
}
- this.pool.show(sessionId, rect, host);
+ const previous = this.pages.get(params.sessionId);
+ this.pages.set(params.sessionId, {
+ error: previous?.error,
+ faviconUrl: previous?.faviconUrl,
+ isLoading: webContents.isLoading(),
+ title: webContents.getTitle() || previous?.title || '',
+ url: webContents.getURL() || previous?.url || DEFAULT_BROWSER_URL,
+ webContentsId: params.webContentsId,
+ });
+ this.wirePage(params.sessionId, webContents);
+ this.updateSnapshot(params.sessionId);
return { success: true };
}
@@ -378,42 +366,16 @@ export default class BrowserSidebarCtr extends ControllerModule {
/** Accessors for sibling controllers (BrowserControlCtr drives the pages). */
getSessionWebContents(sessionId: string): WebContents | undefined {
- return this.pagePool?.webContentsOf(sessionId);
- }
-
- /** Mark a page as in use so the memory cap doesn't discard it mid-automation. */
- touchPage(sessionId: string): void {
- this.pagePool?.touch(sessionId);
+ const page = this.pages.get(sessionId);
+ if (!page) return undefined;
+ const webContents = electronWebContents.fromId(page.webContentsId);
+ return webContents && !webContents.isDestroyed() ? webContents : undefined;
}
getOverlayLabels(): AgentOverlayLabels {
return this.overlayLabels;
}
- private get pool(): BrowserPagePool {
- if (this.pagePool) return this.pagePool;
-
- this.configureBrowserSession();
- this.pagePool = new BrowserPagePool({
- onPageChanged: (sessionId) => this.updateSnapshot(sessionId),
- partition: BROWSER_PARTITION,
- });
-
- return this.pagePool;
- }
-
- private disposePool(): void {
- this.pagePool?.dispose();
- this.pagePool = undefined;
- }
-
- /** The window whose renderer made the current IPC call. */
- private getSenderWindow(): BrowserWindow | undefined {
- const sender = getIpcContext()?.sender;
- if (!sender || sender.isDestroyed()) return undefined;
- return ElectronBrowserWindow.fromWebContents(sender) ?? undefined;
- }
-
private configureBrowserSession(): void {
if (this.partitionConfigured) return;
@@ -439,28 +401,24 @@ export default class BrowserSidebarCtr extends ControllerModule {
}
private snapshot(sessionId: string): BrowserSidebarState {
- const page = this.pagePool?.get(sessionId);
+ const page = this.pages.get(sessionId);
const webContents = this.getSessionWebContents(sessionId);
- // A page the pool discarded to stay under its memory cap still reports its
- // URL, so the panel keeps showing it and the next visit reloads it there
- // rather than dropping the user on a blank pane.
- const discarded = this.pagePool?.discardedRecord(sessionId);
return {
attached: !!webContents,
canGoBack: webContents?.canGoBack() ?? false,
canGoForward: webContents?.canGoForward() ?? false,
error: page?.error,
- faviconUrl: page?.faviconUrl || discarded?.faviconUrl,
+ faviconUrl: page?.faviconUrl,
isLoading: webContents?.isLoading() ?? page?.isLoading ?? false,
sessionId,
- title: webContents?.getTitle() || page?.title || discarded?.title || '',
- url: webContents?.getURL() || page?.url || discarded?.url || DEFAULT_BROWSER_URL,
+ title: webContents?.getTitle() || page?.title || '',
+ url: webContents?.getURL() || page?.url || DEFAULT_BROWSER_URL,
};
}
private updateSnapshot(sessionId: string): void {
- const page = this.pagePool?.get(sessionId);
+ const page = this.pages.get(sessionId);
const webContents = this.getSessionWebContents(sessionId);
if (page && webContents) {
@@ -475,6 +433,59 @@ export default class BrowserSidebarCtr extends ControllerModule {
);
}
+ private wirePage(sessionId: string, webContents: WebContents): void {
+ if (this.wiredWebContents.has(webContents.id)) return;
+ this.wiredWebContents.add(webContents.id);
+
+ const changed = () => this.updateSnapshot(sessionId);
+ webContents.setWindowOpenHandler(({ url }) => {
+ if (HTTP_URL_PATTERN.test(url)) {
+ void webContents.loadURL(url).catch((error) => {
+ logger.error(`Failed to open URL in browser page ${sessionId}: ${url}`, error);
+ });
+ }
+ return { action: 'deny' };
+ });
+ webContents.on('page-title-updated', changed);
+ webContents.on('page-favicon-updated', (_event, favicons) => {
+ const page = this.pages.get(sessionId);
+ if (page) page.faviconUrl = favicons[0];
+ changed();
+ });
+ webContents.on('did-navigate', changed);
+ webContents.on('did-navigate-in-page', changed);
+ webContents.on('did-start-loading', () => {
+ const page = this.pages.get(sessionId);
+ if (page) {
+ page.error = undefined;
+ page.isLoading = true;
+ }
+ changed();
+ });
+ webContents.on('did-stop-loading', () => {
+ const page = this.pages.get(sessionId);
+ if (page) page.isLoading = false;
+ changed();
+ });
+ webContents.on('did-fail-load', (_event, code, description, url, isMainFrame) => {
+ if (!isMainFrame || code === -3) return;
+ const page = this.pages.get(sessionId);
+ if (page) {
+ page.error = description;
+ page.isLoading = false;
+ page.url = url || page.url;
+ }
+ changed();
+ });
+ webContents.once('destroyed', () => {
+ this.wiredWebContents.delete(webContents.id);
+ if (this.pages.get(sessionId)?.webContentsId === webContents.id) {
+ this.pages.delete(sessionId);
+ this.updateSnapshot(sessionId);
+ }
+ });
+ }
+
private async withPage<T extends BrowserSidebarResult>(
sessionId: string,
action: (webContents: WebContents) => T | Promise<T>,
diff --git a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
index aec2742506d..f830806467c 100644
--- a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
@@ -3,129 +3,33 @@ import { EventEmitter } from 'node:events';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
-import { MAX_LIVE_PAGES } from '@/modules/browser/BrowserPagePool';
import { IpcHandler } from '@/utils/ipc/base';
-import BrowserControlCtr from '../BrowserControlCtr';
import BrowserSidebarCtr from '../BrowserSidebarCtr';
interface FakeWebContents extends EventEmitter {
canGoBack: ReturnType<typeof vi.fn>;
canGoForward: ReturnType<typeof vi.fn>;
- capturePage: ReturnType<typeof vi.fn>;
- close: ReturnType<typeof vi.fn>;
- executeJavaScript: ReturnType<typeof vi.fn>;
getTitle: ReturnType<typeof vi.fn>;
getURL: ReturnType<typeof vi.fn>;
id: number;
isDestroyed: ReturnType<typeof vi.fn>;
isLoading: ReturnType<typeof vi.fn>;
loadURL: ReturnType<typeof vi.fn>;
- reload: ReturnType<typeof vi.fn>;
setWindowOpenHandler: ReturnType<typeof vi.fn>;
- stop: ReturnType<typeof vi.fn>;
}
-interface FakeView {
- setBounds: ReturnType<typeof vi.fn>;
- webContents: FakeWebContents;
-}
-
-/** A stand-in for a real app window (main app, or a standalone `chatSingle`). */
-interface FakeWindow extends EventEmitter {
- contentView: {
- addChildView: ReturnType<typeof vi.fn>;
- removeChildView: ReturnType<typeof vi.fn>;
- };
- destroy: ReturnType<typeof vi.fn>;
- id: number;
- isDestroyed: () => boolean;
- /** The renderer webContents that sends IPC from this window. */
- sender: { id: number; isDestroyed: () => boolean };
- setIgnoreMouseEvents: ReturnType<typeof vi.fn>;
- setOpacity: ReturnType<typeof vi.fn>;
- setPosition: ReturnType<typeof vi.fn>;
- showInactive: ReturnType<typeof vi.fn>;
- webContents: { getZoomFactor: ReturnType<typeof vi.fn> };
-}
-
-let seq = 0;
-const nextId = () => (seq += 1);
-
-const createWebContents = (): FakeWebContents => {
- const wc = new EventEmitter() as FakeWebContents;
- // Track the loaded URL: the pool folds `getURL()` back into the page record, so
- // a fake that always answers the same URL hides which page is which.
- let url = 'about:blank';
- wc.id = nextId();
- wc.canGoBack = vi.fn(() => false);
- wc.canGoForward = vi.fn(() => false);
- wc.capturePage = vi.fn(async () => 'image');
- wc.close = vi.fn();
- wc.executeJavaScript = vi.fn(async () => undefined);
- wc.getTitle = vi.fn(() => 'Example');
- wc.getURL = vi.fn(() => url);
- wc.isDestroyed = vi.fn(() => false);
- wc.isLoading = vi.fn(() => false);
- wc.loadURL = vi.fn(async (next: string) => {
- url = next;
- });
- wc.reload = vi.fn();
- wc.setWindowOpenHandler = vi.fn();
- wc.stop = vi.fn();
- return wc;
-};
-
-const createWindow = (): FakeWindow => {
- let destroyed = false;
- const win = new EventEmitter() as FakeWindow;
- win.id = nextId();
- win.contentView = { addChildView: vi.fn(), removeChildView: vi.fn() };
- win.destroy = vi.fn(() => {
- destroyed = true;
- win.emit('closed');
- });
- win.isDestroyed = () => destroyed;
- win.sender = { id: nextId(), isDestroyed: () => destroyed };
- win.setIgnoreMouseEvents = vi.fn();
- win.setOpacity = vi.fn();
- win.setPosition = vi.fn();
- win.showInactive = vi.fn();
- win.webContents = { getZoomFactor: vi.fn(() => 1) };
- return win;
-};
-
-const {
- appOnMock,
- clipboardWriteImageMock,
- createdViews,
- createdWindows,
- fromWebContentsMock,
- getAllWindowsMock,
- importChromeLoginDataMock,
- ipcHandlers,
- ipcMainHandleMock,
- sessionFromPartitionMock,
- shellOpenExternalMock,
-} = vi.hoisted(() => {
- const handlers = new Map<string, (event: unknown, ...args: unknown[]) => unknown>();
-
+const { fromIdMock, ipcHandlers, ipcMainHandleMock, sessionFromPartitionMock } = vi.hoisted(() => {
+ const handlers = new Map<string, (event: unknown, payload: unknown) => unknown>();
return {
- appOnMock: vi.fn(),
- clipboardWriteImageMock: vi.fn(),
- createdViews: [] as unknown[],
- createdWindows: [] as unknown[],
- fromWebContentsMock: vi.fn(),
- getAllWindowsMock: vi.fn(() => [] as unknown[]),
- importChromeLoginDataMock: vi.fn(),
+ fromIdMock: vi.fn(),
ipcHandlers: handlers,
ipcMainHandleMock: vi.fn(
- (channel: string, handler: (event: unknown, ...args: unknown[]) => unknown) => {
+ (channel: string, handler: (event: unknown, payload: unknown) => unknown) => {
handlers.set(channel, handler);
},
),
sessionFromPartitionMock: vi.fn(),
- shellOpenExternalMock: vi.fn().mockResolvedValue(undefined),
};
});
@@ -133,698 +37,126 @@ vi.mock('@/utils/logger', () => ({
createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
}));
-vi.mock('@/modules/browser/importChromeLoginData', () => ({
- importChromeLoginData: importChromeLoginDataMock,
-}));
-
vi.mock('electron', () => ({
- app: { on: appOnMock },
- BrowserWindow: Object.assign(
- class {
- constructor() {
- return createdWindows.at(-1) as object;
- }
- },
- { fromWebContents: fromWebContentsMock, getAllWindows: getAllWindowsMock },
- ),
- clipboard: { writeImage: clipboardWriteImageMock },
ipcMain: { handle: ipcMainHandleMock },
session: { fromPartition: sessionFromPartitionMock },
- shell: { openExternal: shellOpenExternalMock },
- WebContentsView: class {
- constructor() {
- return createdViews.at(-1) as object;
- }
- },
+ shell: { openExternal: vi.fn() },
+ webContents: { fromId: fromIdMock },
}));
-describe('BrowserSidebarCtr', () => {
+const createWebContents = (id: number): FakeWebContents => {
+ const webContents = new EventEmitter() as FakeWebContents;
+ let url = 'about:blank';
+ webContents.id = id;
+ webContents.canGoBack = vi.fn(() => false);
+ webContents.canGoForward = vi.fn(() => false);
+ webContents.getTitle = vi.fn(() => 'Example');
+ webContents.getURL = vi.fn(() => url);
+ webContents.isDestroyed = vi.fn(() => false);
+ webContents.isLoading = vi.fn(() => false);
+ webContents.loadURL = vi.fn(async (nextUrl: string) => {
+ url = nextUrl;
+ });
+ webContents.setWindowOpenHandler = vi.fn();
+ return webContents;
+};
+
+describe('BrowserSidebarCtr retained webview registration', () => {
const broadcastToAllWindows = vi.fn();
- const mockSession = {
+ const browserSession = {
on: vi.fn(),
setPermissionCheckHandler: vi.fn(),
setPermissionRequestHandler: vi.fn(),
webRequest: { onBeforeRequest: vi.fn() },
};
- let mainWindow: FakeWindow;
let controller: BrowserSidebarCtr;
- /** Hand out a fresh fake for the next `new WebContentsView()`. */
- const queueView = (): FakeView => {
- const view: FakeView = { setBounds: vi.fn(), webContents: createWebContents() };
- createdViews.push(view);
- return view;
- };
-
- /** Hand out a fresh fake for the next `new BrowserWindow()` (the parking lot). */
- const queueParkingWindow = (): FakeWindow => {
- const win = createWindow();
- createdWindows.push(win);
- return win;
- };
-
- /** An app window whose renderer can send IPC β€” the main one, or a standalone chat window. */
- const appWindow = (): FakeWindow => {
- const win = createWindow();
- fromWebContentsMock.mockImplementation((sender: unknown) =>
- [mainWindow, win].find((candidate) => candidate?.sender === sender),
- );
- return win;
- };
-
- /** Invoke an IPC channel as if it came from `from`'s renderer. */
- const invokeIpc = async <T = unknown>(
- channel: string,
- payload?: unknown,
- from: FakeWindow = mainWindow,
- ): Promise<T> => {
+ const invokeIpc = async <T>(channel: string, payload: unknown): Promise<T> => {
const handler = ipcHandlers.get(channel);
if (!handler) throw new Error(`IPC handler for ${channel} not found`);
- return handler({ sender: from.sender }, payload) as Promise<T>;
+ return handler({ sender: {} }, payload) as Promise<T>;
};
- // BrowserControlCtr is wired in too, so the "a tool call keeps the page alive"
- // test exercises the real path (withGuest β†’ touchPage) rather than a stand-in.
- const mockApp = () =>
- ({
- browserManager: { broadcastToAllWindows },
- getController: (Ctor: unknown) => (Ctor === BrowserSidebarCtr ? controller : undefined),
- }) as unknown as App;
-
beforeEach(() => {
vi.clearAllMocks();
ipcHandlers.clear();
- createdViews.length = 0;
- createdWindows.length = 0;
- seq = 0;
(
IpcHandler.getInstance() as unknown as { registeredChannels?: Set<string> }
).registeredChannels?.clear();
+ sessionFromPartitionMock.mockReturnValue(browserSession);
- sessionFromPartitionMock.mockReturnValue(mockSession);
-
- mainWindow = createWindow();
- fromWebContentsMock.mockImplementation((sender: unknown) =>
- mainWindow.sender === sender ? mainWindow : undefined,
- );
-
- const app = mockApp();
- controller = new BrowserSidebarCtr(app);
- controller.beforeAppReady();
- // Registers the browserControl.* channels against the same pool.
+ controller = new BrowserSidebarCtr({
+ browserManager: { broadcastToAllWindows },
+ } as unknown as App);
+ controller.afterAppReady();
+ });
- new BrowserControlCtr(app);
+ it('returns a recoverable error until a renderer guest registers', async () => {
+ await expect(
+ invokeIpc('browserSidebar.navigate', {
+ sessionId: 'topic:a',
+ url: 'https://example.com',
+ }),
+ ).resolves.toEqual({ error: 'Browser is not ready', success: false });
});
- it('creates a page and loads the URL on navigate, without any renderer round-trip', async () => {
- const view = queueView();
- queueParkingWindow();
+ it('routes navigation to the registered retained webview', async () => {
+ const guest = createWebContents(7);
+ fromIdMock.mockImplementation((id: number) => (id === 7 ? guest : undefined));
- const result = await invokeIpc('browserSidebar.navigate', {
- sessionId: 'agent:a',
- url: 'https://example.com',
+ await invokeIpc('browserSidebar.registerWebview', {
+ sessionId: 'topic:a',
+ webContentsId: 7,
});
+ await expect(
+ invokeIpc('browserSidebar.navigate', {
+ sessionId: 'topic:a',
+ url: 'https://example.com',
+ }),
+ ).resolves.toEqual({ success: true });
- expect(result).toEqual({ success: true });
- expect(view.webContents.loadURL).toHaveBeenCalledWith('https://example.com');
+ expect(guest.loadURL).toHaveBeenCalledWith('https://example.com');
expect(broadcastToAllWindows).toHaveBeenCalledWith(
'browserSidebarStateChanged',
- expect.objectContaining({ attached: true, sessionId: 'agent:a' }),
- );
- });
-
- it('gives each session its own page, so a background agent never drives the visible one', async () => {
- const viewA = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- // agent:a is what the user is looking at.
- await invokeIpc('browserSidebar.setViewport', {
- rect: { height: 600, width: 400, x: 10, y: 20 },
- sessionId: 'agent:a',
- });
- expect(mainWindow.contentView.addChildView).toHaveBeenCalledWith(viewA);
-
- // A different agent navigates in the background.
- const viewB = queueView();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:b', url: 'https://b.com' });
-
- expect(viewB).not.toBe(viewA);
- expect(viewB.webContents.loadURL).toHaveBeenCalledWith('https://b.com');
- // The visible page was neither navigated again nor taken out of the window.
- expect(viewA.webContents.loadURL).toHaveBeenCalledTimes(1);
- expect(mainWindow.contentView.removeChildView).not.toHaveBeenCalled();
- });
-
- it('hosts the view in the window that reported the rect, not the main window', async () => {
- // The agent route also renders in standalone `chatSingle` windows. Hosting in
- // the main window would leave the standalone panel blank and paint the page
- // over the wrong window.
- const standalone = appWindow();
- const view = queueView();
- queueParkingWindow();
-
- await invokeIpc(
- 'browserSidebar.navigate',
- { sessionId: 'agent:a', url: 'https://a.com' },
- standalone,
+ expect.objectContaining({ attached: true, sessionId: 'topic:a' }),
);
- await invokeIpc(
- 'browserSidebar.setViewport',
- { rect: { height: 600, width: 400, x: 10, y: 20 }, sessionId: 'agent:a' },
- standalone,
- );
-
- expect(standalone.contentView.addChildView).toHaveBeenCalledWith(view);
- expect(mainWindow.contentView.addChildView).not.toHaveBeenCalled();
- });
-
- it('lets two windows each show a page at the same time', async () => {
- const standalone = appWindow();
- const viewA = queueView();
- const parking = queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
- await invokeIpc('browserSidebar.setViewport', {
- rect: { height: 600, width: 400, x: 0, y: 0 },
- sessionId: 'agent:a',
- });
-
- expect(mainWindow.contentView.addChildView).toHaveBeenCalledWith(viewA);
- // Every page is born in the parking lot, so only calls from here on say
- // anything about whether showing B parked A.
- parking.contentView.addChildView.mockClear();
-
- const viewB = queueView();
- await invokeIpc(
- 'browserSidebar.navigate',
- { sessionId: 'agent:b', url: 'https://b.com' },
- standalone,
- );
- await invokeIpc(
- 'browserSidebar.setViewport',
- { rect: { height: 600, width: 400, x: 0, y: 0 }, sessionId: 'agent:b' },
- standalone,
- );
-
- expect(standalone.contentView.addChildView).toHaveBeenCalledWith(viewB);
- // Showing B in another window must not park A β€” display is per-window.
- expect(parking.contentView.addChildView).not.toHaveBeenCalledWith(viewA);
- expect(mainWindow.contentView.removeChildView).not.toHaveBeenCalled();
- });
-
- it('reclaims the page when a window that lost it regains focus', async () => {
- // One session can be open in two windows (main + its standalone chat window)
- // but there is only one page. The window that loses it never re-reports β€” its
- // rect didn't change β€” so without this its panel stays empty forever.
- const standalone = appWindow();
- const view = queueView();
- queueParkingWindow();
-
- const rect = { height: 600, width: 400, x: 0, y: 0 };
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
- await invokeIpc('browserSidebar.setViewport', { rect, sessionId: 'agent:a' });
- await invokeIpc('browserSidebar.setViewport', { rect, sessionId: 'agent:a' }, standalone);
-
- expect(standalone.contentView.addChildView).toHaveBeenCalledWith(view);
- mainWindow.contentView.addChildView.mockClear();
-
- mainWindow.emit('focus');
-
- expect(standalone.contentView.removeChildView).toHaveBeenCalledWith(view);
- expect(mainWindow.contentView.addChildView).toHaveBeenCalledWith(view);
- });
-
- it('parks a page when its host window closes, instead of letting it die with the window', async () => {
- // Child views are destroyed with the window that holds them, so a page shown
- // in a standalone chat window would be torn down when the user closes it β€”
- // even if an agent is still driving it.
- const standalone = appWindow();
- const view = queueView();
- const parking = queueParkingWindow();
-
- await invokeIpc(
- 'browserSidebar.navigate',
- { sessionId: 'agent:a', url: 'https://a.com' },
- standalone,
- );
- await invokeIpc(
- 'browserSidebar.setViewport',
- { rect: { height: 600, width: 400, x: 0, y: 0 }, sessionId: 'agent:a' },
- standalone,
- );
- parking.contentView.addChildView.mockClear();
-
- standalone.emit('close');
-
- expect(standalone.contentView.removeChildView).toHaveBeenCalledWith(view);
- expect(parking.contentView.addChildView).toHaveBeenCalledWith(view);
- expect(view.webContents.close).not.toHaveBeenCalled();
- });
-
- it('parks a page instead of destroying it when the panel stops showing it', async () => {
- const view = queueView();
- const parking = queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- await invokeIpc('browserSidebar.setViewport', {
- rect: { height: 600, width: 400, x: 0, y: 0 },
- sessionId: 'agent:a',
- });
- expect(mainWindow.contentView.addChildView).toHaveBeenCalledWith(view);
- parking.contentView.addChildView.mockClear();
-
- // A zero-sized rect is what `display: none` reports when another tab is active.
- await invokeIpc('browserSidebar.setViewport', {
- rect: { height: 0, width: 0, x: 0, y: 0 },
- sessionId: 'agent:a',
- });
-
- expect(mainWindow.contentView.removeChildView).toHaveBeenCalledWith(view);
- expect(parking.contentView.addChildView).toHaveBeenCalledWith(view);
- // Still live β€” the agent may still be driving it.
- expect(view.webContents.close).not.toHaveBeenCalled();
- });
-
- it('scales the panel rect by the app zoom factor', async () => {
- const view = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- // The renderer reports CSS px; setBounds wants DIP. At zoom 1.25 the page
- // would otherwise be laid out 25% too small and offset from the panel.
- mainWindow.webContents.getZoomFactor.mockReturnValue(1.25);
- await invokeIpc('browserSidebar.setViewport', {
- rect: { height: 400, width: 200, x: 100, y: 40 },
- sessionId: 'agent:a',
- });
-
- expect(view.setBounds).toHaveBeenLastCalledWith({ height: 500, width: 250, x: 125, y: 50 });
- });
-
- it('keeps the parking window shown but fully transparent', async () => {
- queueView();
- const parking = queueParkingWindow();
-
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- // It must be SHOWN β€” `show: false` leaves its pages with no compositing
- // surface, which is the whole reason this window exists.
- expect(parking.showInactive).toHaveBeenCalled();
- // And invisible by opacity, not by position: the OS clamps a window it thinks
- // is reachable (macOS dragged -8000,-8000 back to the screen edge, where a
- // plain white window showed up over the app).
- expect(parking.setOpacity).toHaveBeenCalledWith(0);
- expect(parking.setIgnoreMouseEvents).toHaveBeenCalledWith(true);
- const [x, y] = parking.setPosition.mock.calls[0];
- expect(x).toBeLessThan(0);
- expect(y).toBeLessThan(0);
- });
-
- it('destroys the parking window once the last app window closes, so `window-all-closed` can fire', async () => {
- queueView();
- const parking = queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- // The controller watches every window Electron creates.
- const onWindowCreated = appOnMock.mock.calls.find(
- ([event]) => event === 'browser-window-created',
- )?.[1];
- onWindowCreated({}, mainWindow);
-
- // Last app window gone; only the pool's own parking window is left standing.
- getAllWindowsMock.mockReturnValue([parking]);
- mainWindow.destroy();
-
- expect(parking.destroy).toHaveBeenCalled();
});
- describe('memory cap', () => {
- // Each live page is a full renderer process (90–345 MB measured), so the pool
- // is capped. These pin what may and may not be thrown away.
- //
- // Sizes are derived from MAX_LIVE_PAGES rather than hardcoded: the cap grows
- // as sessions get finer-grained (per-agent β†’ per-topic β†’ per-tab), and a test
- // that hardcodes the old number does not fail loudly β€” it silently stops
- // reaching the cap and asserts nothing.
- const OVERFLOW = 4;
-
- const navigateN = async (count: number, from = 0) => {
- const views: FakeView[] = [];
- for (let i = from; i < from + count; i += 1) {
- views.push(queueView());
-
- await invokeIpc('browserSidebar.navigate', {
- sessionId: `agent:${i}`,
- url: `https://site-${i}.com`,
- });
- }
- return views;
- };
-
- /** Fill the pool to the cap, then push it one page over. */
- const fillToCapAndOverflow = async () => {
- const views = await navigateN(MAX_LIVE_PAGES);
- // Age them past the in-use window so they are eligible.
- vi.advanceTimersByTime(120_000);
- return views;
- };
-
- const navigateOneMore = async () => {
- queueView();
- await invokeIpc('browserSidebar.navigate', {
- sessionId: `agent:${MAX_LIVE_PAGES}`,
- url: `https://site-${MAX_LIVE_PAGES}.com`,
- });
- };
-
- it('discards the coldest idle page once the pool is over its cap', async () => {
- vi.useFakeTimers();
- queueParkingWindow();
-
- const views = await fillToCapAndOverflow();
- await navigateOneMore();
-
- // agent:0 was the coldest.
- expect(views[0].webContents.close).toHaveBeenCalled();
- expect(views[1].webContents.close).not.toHaveBeenCalled();
- vi.useRealTimers();
- });
-
- it('keeps a discarded page addressable, and reloads it where it left off', async () => {
- vi.useFakeTimers();
- queueParkingWindow();
- const views = await fillToCapAndOverflow();
- await navigateOneMore();
-
- expect(views[0].webContents.close).toHaveBeenCalled();
+ it('keeps sessions isolated and activates the most recently registered host', async () => {
+ const oldGuest = createWebContents(1);
+ const newGuest = createWebContents(2);
+ const otherGuest = createWebContents(3);
+ const guests = new Map([
+ [1, oldGuest],
+ [2, newGuest],
+ [3, otherGuest],
+ ]);
+ fromIdMock.mockImplementation((id: number) => guests.get(id));
- // The panel still knows where that session was.
- const state = await invokeIpc<{ attached: boolean; url: string }>('browserSidebar.getState', {
- sessionId: 'agent:0',
- });
- expect(state.url).toBe('https://site-0.com');
- expect(state.attached).toBe(false);
-
- // Coming back rebuilds the view on the same URL rather than a blank page.
- const revived = queueView();
- await invokeIpc('browserSidebar.setViewport', {
- rect: { height: 600, width: 400, x: 0, y: 0 },
- sessionId: 'agent:0',
- });
- expect(revived.webContents.loadURL).toHaveBeenCalledWith('https://site-0.com');
- vi.useRealTimers();
+ await invokeIpc('browserSidebar.registerWebview', {
+ sessionId: 'topic:a',
+ webContentsId: 1,
});
-
- it('never discards a page an agent is still driving, even over the cap', async () => {
- vi.useFakeTimers();
- queueParkingWindow();
- const views = await fillToCapAndOverflow();
-
- // A tool call on the coldest page counts as use.
- await invokeIpc('browserControl.snapshot', { sessionId: 'agent:0' });
-
- await navigateOneMore();
-
- // agent:0 is in use, so agent:1 β€” the next coldest β€” goes instead.
- expect(views[0].webContents.close).not.toHaveBeenCalled();
- expect(views[1].webContents.close).toHaveBeenCalled();
- vi.useRealTimers();
+ await invokeIpc('browserSidebar.registerWebview', {
+ sessionId: 'topic:b',
+ webContentsId: 3,
});
-
- it('sweeps back down to the cap after a burst goes idle, with no new page to trigger it', async () => {
- // The real failure this guards: a burst of agents opens pages at once, so
- // nothing is evictable (all "in use") β€” and if eviction only ran on create,
- // the pool would stay over the cap forever. Verified against the live app.
- vi.useFakeTimers();
- queueParkingWindow();
- const views = await navigateN(MAX_LIVE_PAGES + OVERFLOW);
-
- // Nothing is evictable yet: everything was just used.
- for (const view of views) expect(view.webContents.close).not.toHaveBeenCalled();
-
- // Nobody creates another page β€” the sweep has to do it.
- await vi.advanceTimersByTimeAsync(150_000);
-
- const closed = views.filter((view) => view.webContents.close.mock.calls.length > 0);
- expect(closed).toHaveLength(OVERFLOW);
- // Oldest first: the first OVERFLOW pages go, the newest stay.
- expect(views[0].webContents.close).toHaveBeenCalled();
- expect(views[OVERFLOW - 1].webContents.close).toHaveBeenCalled();
- expect(views[OVERFLOW].webContents.close).not.toHaveBeenCalled();
- expect(views.at(-1)!.webContents.close).not.toHaveBeenCalled();
- vi.useRealTimers();
- });
-
- it('stays over the cap rather than discard a page that is on screen or in use', async () => {
- vi.useFakeTimers();
- queueParkingWindow();
- // No time passes: every page is within the in-use window.
- const views = await navigateN(MAX_LIVE_PAGES);
-
- await navigateOneMore();
-
- for (const view of views) expect(view.webContents.close).not.toHaveBeenCalled();
- vi.useRealTimers();
+ await invokeIpc('browserSidebar.registerWebview', {
+ sessionId: 'topic:a',
+ webContentsId: 2,
});
- });
-
- it('keeps window.open navigations inside the page', async () => {
- const view = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- const handler = view.webContents.setWindowOpenHandler.mock.calls[0][0];
- expect(handler({ url: 'https://popup.example.com' })).toEqual({ action: 'deny' });
- expect(view.webContents.loadURL).toHaveBeenCalledWith('https://popup.example.com');
- });
-
- it('sends free text to a search engine rather than navigating to it', async () => {
- const view = queueView();
- queueParkingWindow();
-
await invokeIpc('browserSidebar.navigate', {
- sessionId: 'agent:a',
- url: 'how tall is everest',
- });
-
- expect(view.webContents.loadURL).toHaveBeenCalledWith(
- expect.stringContaining('bing.com/search?q=how+tall+is+everest'),
- );
- });
-
- it('returns the page capture as a PNG data URL, downscaled to the attachment cap', async () => {
- const view = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- // A Retina capture is wider than the cap; the resized image is what must be encoded.
- const resized = {
- getSize: () => ({ height: 1285, width: 2000 }),
- toPNG: () => Buffer.from('resized-png'),
- };
- const captured = {
- getSize: () => ({ height: 1800, width: 2800 }),
- resize: vi.fn(() => resized),
- toPNG: () => Buffer.from('full-png'),
- };
- view.webContents.capturePage.mockResolvedValue(captured);
-
- const result = await invokeIpc('browserSidebar.captureScreenshot', { sessionId: 'agent:a' });
-
- expect(captured.resize).toHaveBeenCalledWith({ width: 2000 });
- expect(result).toEqual({
- dataUrl: `data:image/png;base64,${Buffer.from('resized-png').toString('base64')}`,
- success: true,
- title: 'Example',
- });
- });
-
- it('resolves a pick with the element details, its cropped thumbnail and the page source', async () => {
- const view = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- // The picker script is the only injected script that returns a Promise; the
- // cancel script that precedes it resolves undefined.
- view.webContents.executeJavaScript.mockImplementation(async (script: string) =>
- script.includes('new Promise')
- ? JSON.stringify({
- html: '<button class="go">Go</button>',
- // Spills past the viewport's right edge β€” the crop must be clamped.
- rect: { height: 32, width: 96, x: 1240, y: 20 },
- selector: 'form > button.go',
- tag: 'button',
- text: 'Go',
- viewport: { height: 800, width: 1280 },
- })
- : undefined,
- );
- const thumbnail = {
- getSize: () => ({ height: 32, width: 40 }),
- isEmpty: () => false,
- toJPEG: vi.fn(() => Buffer.from('thumb-jpeg')),
- };
- view.webContents.capturePage.mockResolvedValue(thumbnail);
-
- const result = await invokeIpc('browserSidebar.pickElement', {
- hint: 'Click an element',
- sessionId: 'agent:a',
+ sessionId: 'topic:a',
+ url: 'https://a.example',
});
-
- expect(view.webContents.capturePage).toHaveBeenCalledWith({
- height: 32,
- width: 40,
- x: 1240,
- y: 20,
- });
- expect(result).toEqual({
- element: {
- html: '<button class="go">Go</button>',
- pageTitle: 'Example',
- rect: { height: 32, width: 96, x: 1240, y: 20 },
- selector: 'form > button.go',
- tag: 'button',
- text: 'Go',
- thumbnailUrl: `data:image/jpeg;base64,${Buffer.from('thumb-jpeg').toString('base64')}`,
- url: 'https://a.com',
- },
- success: true,
- });
- });
-
- it('still resolves the pick when the thumbnail capture fails', async () => {
- const view = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- view.webContents.executeJavaScript.mockImplementation(async (script: string) =>
- script.includes('new Promise')
- ? JSON.stringify({
- html: '<i>x</i>',
- rect: { height: 20, width: 20, x: 0, y: 0 },
- selector: 'i',
- tag: 'i',
- text: 'x',
- viewport: { height: 800, width: 1280 },
- })
- : undefined,
- );
- view.webContents.capturePage.mockRejectedValue(new Error('render frame gone'));
-
- const result = await invokeIpc<{ element?: { thumbnailUrl?: string }; success: boolean }>(
- 'browserSidebar.pickElement',
- { hint: 'Click an element', sessionId: 'agent:a' },
- );
-
- expect(result.success).toBe(true);
- expect(result.element?.thumbnailUrl).toBeUndefined();
- });
-
- it('reports a cancelled pick (Escape) instead of an element', async () => {
- const view = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- view.webContents.executeJavaScript.mockImplementation(async (script: string) =>
- script.includes('new Promise') ? JSON.stringify({ cancelled: true }) : undefined,
- );
-
- const result = await invokeIpc('browserSidebar.pickElement', {
- hint: 'Click an element',
- sessionId: 'agent:a',
- });
-
- expect(result).toEqual({ cancelled: true, success: true });
- });
-
- it('re-applies a cancel that lands in the gap between pre-cancel and picker injection', async () => {
- // The pane unmounting right after starting a pick fires cancelElementPick
- // while pickElement is still awaiting its pre-cancel. Consumed there by
- // nothing, the cancel must be re-issued after the picker is injected, or
- // the page keeps swallowing every click with no caller left to stop it.
- const view = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- const calls: string[] = [];
- let releasePreCancel!: () => void;
- const preCancelGate = new Promise<void>((resolve) => {
- releasePreCancel = resolve;
- });
- let resolvePick!: (value: string) => void;
- let cancelCalls = 0;
-
- view.webContents.executeJavaScript.mockImplementation((script: string) => {
- if (script.includes('new Promise')) {
- calls.push('install-picker');
- return new Promise<string>((resolve) => {
- resolvePick = resolve;
- });
- }
- // Cancel script. Only an installed picker can react to it.
- cancelCalls += 1;
- if (calls.includes('install-picker')) {
- calls.push('cancel-after-install');
- resolvePick(JSON.stringify({ cancelled: true }));
- return Promise.resolve(undefined);
- }
- calls.push(cancelCalls === 1 ? 'pre-cancel' : 'raced-cancel');
- return cancelCalls === 1 ? preCancelGate : Promise.resolve(undefined);
- });
-
- const pending = invokeIpc('browserSidebar.pickElement', {
- hint: 'Click an element',
- sessionId: 'agent:a',
- });
- // Let pickElement reach (and block on) its pre-cancel await.
- await new Promise((resolve) => setTimeout(resolve, 0));
-
- // The pane unmounts: its cleanup cancel runs against the not-yet-installed picker.
- await invokeIpc('browserSidebar.cancelElementPick', { sessionId: 'agent:a' });
-
- releasePreCancel();
-
- await expect(pending).resolves.toEqual({ cancelled: true, success: true });
- // The decisive assertion: a cancel script was issued AFTER the picker install.
- expect(calls).toContain('cancel-after-install');
- });
-
- it('treats a navigation during a pick as a cancel instead of hanging forever', async () => {
- const view = queueView();
- queueParkingWindow();
- await invokeIpc('browserSidebar.navigate', { sessionId: 'agent:a', url: 'https://a.com' });
-
- // Navigating destroys the page's JS context, so the picker promise never settles.
- view.webContents.executeJavaScript.mockImplementation((script: string) =>
- script.includes('new Promise') ? new Promise(() => {}) : Promise.resolve(undefined),
- );
-
- const pending = invokeIpc('browserSidebar.pickElement', {
- hint: 'Click an element',
- sessionId: 'agent:a',
+ await invokeIpc('browserSidebar.navigate', {
+ sessionId: 'topic:b',
+ url: 'https://b.example',
});
- // Let the handler run its pre-pick cancel and attach the abort listeners.
- await new Promise((resolve) => setTimeout(resolve, 0));
- view.webContents.emit('did-navigate');
-
- await expect(pending).resolves.toEqual({ cancelled: true, success: true });
- });
-
- it('imports Chrome login information into the browser session', async () => {
- importChromeLoginDataMock.mockResolvedValue(7);
-
- const result = await invokeIpc('browserSidebar.importChromeLoginData');
-
- expect(sessionFromPartitionMock).toHaveBeenCalledWith('persist:lobe-browser-app');
- expect(result).toEqual({ importedCount: 7, success: true });
- });
-
- it('returns a recoverable error when Chrome login import fails', async () => {
- importChromeLoginDataMock.mockRejectedValue(new Error('locked'));
-
- const result = await invokeIpc('browserSidebar.importChromeLoginData');
- expect(result).toEqual({ error: 'locked', importedCount: 0, success: false });
+ expect(oldGuest.loadURL).not.toHaveBeenCalled();
+ expect(newGuest.loadURL).toHaveBeenCalledWith('https://a.example');
+ expect(otherGuest.loadURL).toHaveBeenCalledWith('https://b.example');
});
});
diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.ts
index 19138d81b22..0d521b7b375 100644
--- a/apps/desktop/src/main/core/browser/Browser.ts
+++ b/apps/desktop/src/main/core/browser/Browser.ts
@@ -18,6 +18,7 @@ import { WindowStateManager } from './WindowStateManager';
import { WindowThemeManager } from './WindowThemeManager';
const logger = createLogger('core:Browser');
+const BROWSER_WEBVIEW_PARTITION = 'persist:lobe-browser-app';
const getExternalNavigationHosts = () =>
DESKTOP_EXTERNAL_NAVIGATION_HOSTS.split(',')
@@ -180,6 +181,7 @@ export default class Browser {
contextIsolation: true,
preload: path.join(preloadDir, 'index.js'),
sandbox: false,
+ webviewTag: true,
},
width: resolvedState.width,
x: resolvedState.x,
@@ -213,6 +215,35 @@ export default class Browser {
// Setup external link handler (prevents opening new windows in renderer)
this.setupWindowOpenHandler(browserWindow);
+ this.setupWebviewSecurity(browserWindow);
+ }
+
+ private setupWebviewSecurity(browserWindow: BrowserWindow): void {
+ browserWindow.webContents.on('will-attach-webview', (event, webPreferences, params) => {
+ if (params.partition !== BROWSER_WEBVIEW_PARTITION) {
+ event.preventDefault();
+ return;
+ }
+
+ let url: URL;
+ try {
+ url = new URL(params.src);
+ } catch {
+ event.preventDefault();
+ return;
+ }
+
+ if (!['about:', 'http:', 'https:'].includes(url.protocol)) {
+ event.preventDefault();
+ return;
+ }
+
+ delete webPreferences.preload;
+ webPreferences.contextIsolation = true;
+ webPreferences.nodeIntegration = false;
+ webPreferences.partition = BROWSER_WEBVIEW_PARTITION;
+ webPreferences.sandbox = true;
+ });
}
private initiateContentLoading(): void {
diff --git a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
index 287aec1e281..55fe4fa225b 100644
--- a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
+++ b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
@@ -248,6 +248,46 @@ describe('Browser', () => {
expect(browser.options).toEqual(defaultOptions);
});
+ it('should reject webviews outside the approved browser partition', () => {
+ const handler = mockBrowserWindow.webContents.on.mock.calls.find(
+ ([eventName]) => eventName === 'will-attach-webview',
+ )?.[1];
+ const event = { preventDefault: vi.fn() };
+ const webPreferences = { nodeIntegration: true, preload: '/tmp/evil.js' };
+
+ handler(event, webPreferences, {
+ partition: 'persist:attacker-controlled',
+ src: 'https://example.com',
+ });
+
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(webPreferences).toEqual({ nodeIntegration: true, preload: '/tmp/evil.js' });
+ });
+
+ it('should harden webviews in the approved browser partition', () => {
+ const handler = mockBrowserWindow.webContents.on.mock.calls.find(
+ ([eventName]) => eventName === 'will-attach-webview',
+ )?.[1];
+ const event = { preventDefault: vi.fn() };
+ const webPreferences: Record<string, unknown> = {
+ nodeIntegration: true,
+ preload: '/tmp/evil.js',
+ };
+
+ handler(event, webPreferences, {
+ partition: 'persist:lobe-browser-app',
+ src: 'https://example.com',
+ });
+
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(webPreferences).toMatchObject({
+ contextIsolation: true,
+ nodeIntegration: false,
+ partition: 'persist:lobe-browser-app',
+ });
+ expect(webPreferences).not.toHaveProperty('preload');
+ });
+
it('should create BrowserWindow on construction', () => {
expect(MockBrowserWindow).toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/modules/browser/BrowserPagePool.ts b/apps/desktop/src/main/modules/browser/BrowserPagePool.ts
deleted file mode 100644
index dda23bf461f..00000000000
--- a/apps/desktop/src/main/modules/browser/BrowserPagePool.ts
+++ /dev/null
@@ -1,442 +0,0 @@
-import type { Rectangle, WebContents } from 'electron';
-import { BrowserWindow, WebContentsView } from 'electron';
-
-import { createLogger } from '@/utils/logger';
-
-const logger = createLogger('modules:browser:BrowserPagePool');
-
-/**
- * A page keeps working `capturePage()` / `sendInputEvent()` only while its view
- * is attached to a window that is *shown*. Detaching the view, `setVisible(false)`,
- * moving its bounds outside the window rect, or parking it in a `show: false`
- * window all drop the compositing surface β€” capture then throws `UnknownVizError`,
- * and (worse) a just-detached view keeps answering with a STALE frame for a while.
- *
- * So a page that nobody is looking at is not hidden; it is moved to a real,
- * shown window that simply sits off every display. Occlusion is fine: a view
- * covered by a sibling keeps rendering, which is why parked pages can stack.
- */
-const PARKING_ORIGIN = { x: -8000, y: -8000 };
-const PARKING_SIZE = { height: 1200, width: 1920 };
-const DEFAULT_PAGE_SIZE = { height: 800, width: 1200 };
-
-/**
- * Every live page is a full renderer process β€” measured at 90–345 MB each, so an
- * unbounded pool would trade the old `<webview>` design's single page for
- * gigabytes. Pages past this count get discarded (their URL is remembered and
- * reloaded on next use), oldest-idle first.
- *
- * Sessions are keyed per topic (and, later, per tab), so a single agent can hold
- * several pages at once β€” hence the headroom over the original per-agent cap.
- */
-export const MAX_LIVE_PAGES = 10;
-/**
- * A page an agent touched this recently is treated as in use and never discarded
- * mid-run, even over the cap: breaking a running automation is far worse than
- * holding one more process.
- */
-const IN_USE_MS = 90_000;
-/**
- * Eviction has to be a sweep, not just a create-time check: a burst of agents all
- * opening pages at once leaves nothing evictable (everything is "in use"), and if
- * no further page is ever created, the pool would sit over the cap forever.
- */
-const SWEEP_MS = 30_000;
-
-export interface BrowserPage {
- error?: string;
- faviconUrl?: string;
- /**
- * The window currently showing this page. `undefined` means it sits in the
- * parking window β€” never "attached to nothing", which would kill the surface.
- */
- host?: BrowserWindow;
- isLoading: boolean;
- /** Last time the user or an agent did anything with this page (for eviction). */
- lastUsedAt: number;
- sessionId: string;
- /** Viewport the page is laid out at; preserved across parking so refs stay valid. */
- size: { height: number; width: number };
- title: string;
- url: string;
- view: WebContentsView;
-}
-
-interface BrowserPagePoolOptions {
- /** Called whenever a page's observable state (url/title/loading/error) changes. */
- onPageChanged: (sessionId: string) => void;
- /** Hardened persistent partition the pages live in. */
- partition: string;
-}
-
-const HTTP_URL_PATTERN = /^https?:\/\//i;
-
-const clampToParking = (size: { height: number; width: number }) => ({
- height: Math.max(1, Math.min(size.height, PARKING_SIZE.height)),
- width: Math.max(1, Math.min(size.width, PARKING_SIZE.width)),
-});
-
-export class BrowserPagePool {
- private pages = new Map<string, BrowserPage>();
- private parkingWindow?: BrowserWindow;
- /**
- * Which page each window is showing. Per-window, not global: the agent route
- * also renders in standalone `chatSingle` windows, so two windows can each
- * show a page of their own at the same time.
- */
- private displayedByWindow = new Map<number, string>();
- /**
- * The last page each window asked to show, kept even after another window takes
- * that page away. A page can only live in one window, so when the same session
- * is open twice the loser's panel would otherwise sit empty forever: its rect
- * never changes, so its renderer never re-reports. Replaying this on window
- * focus makes the page follow whichever window you are actually looking at.
- */
- private lastRequestByWindow = new Map<number, { rect: Rectangle; sessionId: string }>();
- private watchedWindows = new Set<number>();
- /**
- * URLs of pages discarded by the cap. The session keeps looking like it has a
- * page (the panel still shows its address), and the next use rebuilds the view
- * on the same URL β€” a reload, not a silent reset to blank.
- */
- private discarded = new Map<string, { faviconUrl?: string; title: string; url: string }>();
- private sweepTimer?: NodeJS.Timeout;
-
- constructor(private options: BrowserPagePoolOptions) {}
-
- get(sessionId: string): BrowserPage | undefined {
- return this.pages.get(sessionId);
- }
-
- /** Where a page discarded by the cap left off, so the panel can still show it. */
- discardedRecord(
- sessionId: string,
- ): { faviconUrl?: string; title: string; url: string } | undefined {
- return this.discarded.get(sessionId);
- }
-
- webContentsOf(sessionId: string): WebContents | undefined {
- const view = this.pages.get(sessionId)?.view;
- if (!view || view.webContents.isDestroyed()) return undefined;
- return view.webContents;
- }
-
- /** True for the pool's own off-screen window, which must not count as an app window. */
- isParkingWindow(window: BrowserWindow): boolean {
- return !!this.parkingWindow && this.parkingWindow.id === window.id;
- }
-
- /** Creates the page (parked) if it doesn't exist yet. */
- ensure(sessionId: string): BrowserPage {
- const existing = this.pages.get(sessionId);
- if (existing && !existing.view.webContents.isDestroyed()) {
- existing.lastUsedAt = Date.now();
- return existing;
- }
-
- const view = new WebContentsView({
- webPreferences: {
- contextIsolation: true,
- devTools: true,
- nodeIntegration: false,
- partition: this.options.partition,
- sandbox: true,
- },
- });
-
- const restored = this.discarded.get(sessionId);
- this.discarded.delete(sessionId);
-
- const page: BrowserPage = {
- faviconUrl: restored?.faviconUrl,
- isLoading: false,
- lastUsedAt: Date.now(),
- sessionId,
- size: { ...DEFAULT_PAGE_SIZE },
- title: restored?.title ?? '',
- url: restored?.url ?? 'about:blank',
- view,
- };
- this.pages.set(sessionId, page);
-
- // Born in the parking lot so it holds a live surface from the very first
- // navigation β€” an agent can drive it before the user ever opens the panel.
- const parking = this.ensureParkingWindow();
- parking.contentView.addChildView(view);
- view.setBounds({ x: 0, y: 0, ...page.size });
-
- this.wirePage(page);
-
- // Coming back to a page the cap discarded reloads it where it left off.
- if (restored && restored.url !== 'about:blank') {
- view.webContents.loadURL(restored.url).catch((error: Error) => {
- logger.debug(`Failed to restore discarded page ${sessionId}: ${error.message}`);
- });
- }
-
- logger.debug(`Created browser page for ${sessionId}`);
- this.startSweep();
- this.evictColdPages();
- return page;
- }
-
- private startSweep(): void {
- if (this.sweepTimer) return;
- this.sweepTimer = setInterval(() => this.evictColdPages(), SWEEP_MS);
- // Never hold the app open just to run the sweep.
- this.sweepTimer.unref?.();
- }
-
- /** Record that the page was just used, so the cap discards something colder. */
- touch(sessionId: string): void {
- const page = this.pages.get(sessionId);
- if (page) page.lastUsedAt = Date.now();
- }
-
- /**
- * Hold the pool to MAX_LIVE_PAGES by discarding the coldest pages. A page that
- * is on screen, or that an agent touched within IN_USE_MS, is never a candidate
- * β€” we would rather sit over the cap than kill a page mid-automation.
- */
- private evictColdPages(): void {
- while (this.pages.size > MAX_LIVE_PAGES) {
- const now = Date.now();
- const candidates = [...this.pages.values()]
- .filter((page) => !page.host && now - page.lastUsedAt > IN_USE_MS)
- .sort((a, b) => a.lastUsedAt - b.lastUsedAt);
-
- const coldest = candidates[0];
- if (!coldest) {
- logger.debug(
- `${this.pages.size} browser pages live, all in use β€” staying over the cap of ${MAX_LIVE_PAGES}`,
- );
- return;
- }
-
- logger.debug(`Discarding cold browser page ${coldest.sessionId} (${coldest.url})`);
- this.discarded.set(coldest.sessionId, {
- faviconUrl: coldest.faviconUrl,
- title: coldest.title,
- url: coldest.url,
- });
- this.close(coldest.sessionId);
- this.options.onPageChanged(coldest.sessionId);
- }
- }
-
- /**
- * Show the page inside `host` at `rect`. `host` is the window that reported the
- * rect β€” the agent route renders in standalone windows too, so hard-coding the
- * main window would place the view over the wrong one.
- */
- show(sessionId: string, rect: Rectangle, host: BrowserWindow): void {
- if (host.isDestroyed()) return;
-
- const page = this.ensure(sessionId);
-
- // One page per window: whatever this window was showing goes back to parking.
- const previous = this.displayedByWindow.get(host.id);
- if (previous && previous !== sessionId) this.park(previous);
-
- if (page.host?.id !== host.id) {
- this.detach(page);
- host.contentView.addChildView(page.view);
- page.host = host;
- this.watchHost(host);
- }
-
- // The renderer measures in CSS px but `setBounds` takes DIP, and the two only
- // agree at zoom factor 1 β€” the old <webview> was laid out by CSS and followed
- // the zoom for free, a view has to be scaled by hand or it drifts off the panel.
- const zoom = host.webContents.getZoomFactor() || 1;
- const bounds: Rectangle = {
- height: Math.max(1, Math.round(rect.height * zoom)),
- width: Math.max(1, Math.round(rect.width * zoom)),
- x: Math.round(rect.x * zoom),
- y: Math.round(rect.y * zoom),
- };
-
- page.view.setBounds(bounds);
- page.size = clampToParking({ height: bounds.height, width: bounds.width });
- this.displayedByWindow.set(host.id, sessionId);
- this.lastRequestByWindow.set(host.id, { rect, sessionId });
- }
-
- /** The window's panel no longer wants a page (another tab, or the panel closed). */
- hide(sessionId: string, host?: BrowserWindow): void {
- if (host) this.lastRequestByWindow.delete(host.id);
- this.park(sessionId);
- }
-
- /** Move the page back to the off-screen window, where it keeps running. */
- park(sessionId: string): void {
- const page = this.pages.get(sessionId);
- if (!page || page.view.webContents.isDestroyed() || !page.host) return;
-
- this.detach(page);
- const parking = this.ensureParkingWindow();
- parking.contentView.addChildView(page.view);
- page.view.setBounds({ x: 0, y: 0, ...page.size });
- }
-
- close(sessionId: string): void {
- const page = this.pages.get(sessionId);
- if (!page) return;
-
- this.detach(page);
- this.pages.delete(sessionId);
- if (!page.view.webContents.isDestroyed()) page.view.webContents.close();
- }
-
- /**
- * Tear everything down. The parking window is a real BrowserWindow, so leaving
- * it alive would suppress `window-all-closed` and keep the app from quitting on
- * Windows/Linux.
- */
- dispose(): void {
- if (this.sweepTimer) clearInterval(this.sweepTimer);
- this.sweepTimer = undefined;
- for (const sessionId of this.pages.keys()) this.close(sessionId);
- if (this.parkingWindow && !this.parkingWindow.isDestroyed()) this.parkingWindow.destroy();
- this.parkingWindow = undefined;
- this.displayedByWindow.clear();
- this.watchedWindows.clear();
- }
-
- /** Take the view out of whichever window holds it, leaving it attached to nothing. */
- private detach(page: BrowserPage): void {
- if (page.host) {
- if (!page.host.isDestroyed()) page.host.contentView.removeChildView(page.view);
- if (this.displayedByWindow.get(page.host.id) === page.sessionId) {
- this.displayedByWindow.delete(page.host.id);
- }
- page.host = undefined;
- return;
- }
-
- if (this.parkingWindow && !this.parkingWindow.isDestroyed()) {
- this.parkingWindow.contentView.removeChildView(page.view);
- }
- }
-
- private watchHost(host: BrowserWindow): void {
- if (this.watchedWindows.has(host.id)) return;
- this.watchedWindows.add(host.id);
-
- /**
- * Child views are destroyed with the window that holds them, so a page shown
- * in a standalone chat window would die with it. Park on `close` (which fires
- * *before* teardown) to keep the page β€” and any agent still driving it β€” alive.
- */
- host.once('close', () => {
- this.watchedWindows.delete(host.id);
- this.lastRequestByWindow.delete(host.id);
- for (const page of this.pages.values()) {
- if (page.host?.id === host.id) this.park(page.sessionId);
- }
- });
-
- // Reclaim the page this window last asked for. The renderer's own `focus`
- // event is not a usable signal here: switching between two windows of the
- // same app leaves the previous document reporting `hasFocus() === true` and
- // fires no `focus` on the one you switch to (measured), so a page handed to
- // another window would never come back.
- host.on('focus', () => {
- const request = this.lastRequestByWindow.get(host.id);
- if (!request) return;
- const page = this.pages.get(request.sessionId);
- if (!page || page.host?.id === host.id) return;
- logger.debug(`Reclaiming ${request.sessionId} into window ${host.id} on focus`);
- this.show(request.sessionId, request.rect, host);
- });
- }
-
- private ensureParkingWindow(): BrowserWindow {
- if (this.parkingWindow && !this.parkingWindow.isDestroyed()) return this.parkingWindow;
-
- const win = new BrowserWindow({
- closable: false,
- focusable: false,
- frame: false,
- hasShadow: false,
- height: PARKING_SIZE.height,
- // Invisibility comes from opacity, NOT from `show: false` β€” a hidden window
- // gives its views no compositing surface, which is the whole problem this
- // window exists to avoid.
- opacity: 0,
- show: false,
- skipTaskbar: true,
- width: PARKING_SIZE.width,
- x: PARKING_ORIGIN.x,
- y: PARKING_ORIGIN.y,
- });
-
- win.setIgnoreMouseEvents(true);
- if (process.platform === 'darwin') win.excludedFromShownWindowsMenu = true;
-
- win.showInactive();
- // Off-display coordinates are only defence in depth: the OS clamps a window
- // it considers reachable (macOS pulled -8000,-8000 back to the screen edge,
- // where a plain white window was visible over the app). `opacity: 0` is what
- // actually makes it invisible, and it keeps the compositing surface alive.
- win.setPosition(PARKING_ORIGIN.x, PARKING_ORIGIN.y);
- win.setOpacity(0);
-
- this.parkingWindow = win;
- logger.debug('Created transparent off-screen browser parking window');
- return win;
- }
-
- private wirePage(page: BrowserPage): void {
- const { sessionId, view } = page;
- const { webContents } = view;
- const changed = () => this.options.onPageChanged(sessionId);
-
- webContents.setWindowOpenHandler(({ url }) => {
- // target=_blank stays inside the panel: retarget this page rather than
- // spawn a native window the panel can't manage. (Real tabs land in PR2.)
- if (HTTP_URL_PATTERN.test(url)) {
- webContents.loadURL(url).catch((error) => {
- logger.error(`Failed to open URL in browser page ${sessionId}: ${url}`, error);
- });
- }
- return { action: 'deny' };
- });
-
- webContents.on('page-title-updated', changed);
- webContents.on('page-favicon-updated', (_event, favicons) => {
- page.faviconUrl = favicons[0];
- changed();
- });
- webContents.on('did-navigate', changed);
- webContents.on('did-navigate-in-page', changed);
- webContents.on('did-redirect-navigation', changed);
- webContents.on('did-start-loading', () => {
- page.isLoading = true;
- // A fresh attempt clears the previous failure; did-fail-load fires after
- // this and will set it again if the new navigation also fails.
- page.error = undefined;
- changed();
- });
- webContents.on('did-stop-loading', () => {
- page.isLoading = false;
- changed();
- });
- webContents.on(
- 'did-fail-load',
- (_e, errorCode, errorDescription, validatedURL, isMainFrame) => {
- // -3 is ERR_ABORTED β€” a superseded navigation, not a failure worth showing.
- if (!isMainFrame || errorCode === -3) return;
- page.error = errorDescription;
- page.url = validatedURL || page.url;
- page.isLoading = false;
- changed();
- },
- );
- webContents.on('render-process-gone', (_e, details) => {
- page.error = details.reason;
- page.isLoading = false;
- changed();
- });
- }
-}
diff --git a/apps/desktop/src/main/modules/browser/agentOverlayScript.ts b/apps/desktop/src/main/modules/browser/agentOverlayScript.ts
index 1fc149832c3..370e31961ef 100644
--- a/apps/desktop/src/main/modules/browser/agentOverlayScript.ts
+++ b/apps/desktop/src/main/modules/browser/agentOverlayScript.ts
@@ -1,8 +1,7 @@
/**
* The agent-control affordances (a cursor that glides to each click target, and
- * a "controlling" chip) used to be renderer DOM drawn above the <webview>. A
- * WebContentsView always paints above the window's web contents, so renderer DOM
- * can no longer sit on top of the page β€” the overlay has to live *inside* it.
+ * a "controlling" chip) live inside the guest so they follow page scrolling and
+ * zoom while remaining isolated from the app chrome.
*
* Being inside the page, it must stay invisible to the agent's own tools:
* - it hangs off `documentElement`, not `body`, so `body.innerText` (readPage)
diff --git a/apps/desktop/src/main/modules/browser/elementPickerScript.ts b/apps/desktop/src/main/modules/browser/elementPickerScript.ts
index 98133c97638..b77249a10cb 100644
--- a/apps/desktop/src/main/modules/browser/elementPickerScript.ts
+++ b/apps/desktop/src/main/modules/browser/elementPickerScript.ts
@@ -1,8 +1,7 @@
/**
* In-page element picker for the browser panel's "add element to chat context"
- * action. Like the agent overlay, it must live *inside* the guest page: the page
- * is a WebContentsView that paints above all renderer DOM, so no highlight drawn
- * by the panel could ever sit on top of it.
+ * action. Like the agent overlay, it lives inside the guest page so the highlight
+ * tracks the selected DOM node through scrolling and layout changes.
*
* The script returns a Promise, which `executeJavaScript` awaits β€” the main
* process simply waits until the user clicks an element (resolves with its
diff --git a/packages/electron-client-ipc/src/types/browserSidebar.ts b/packages/electron-client-ipc/src/types/browserSidebar.ts
index 1f53243e509..d0ef64347fc 100644
--- a/packages/electron-client-ipc/src/types/browserSidebar.ts
+++ b/packages/electron-client-ipc/src/types/browserSidebar.ts
@@ -6,6 +6,11 @@ export interface BrowserSidebarNavigateParams extends BrowserSidebarSessionParam
url: string;
}
+export interface BrowserSidebarRegisterWebviewParams extends BrowserSidebarSessionParams {
+ /** Electron guest WebContents id returned by `<webview>.getWebContentsId()`. */
+ webContentsId: number;
+}
+
/** Panel rect in main-window coordinates (CSS px, as `getBoundingClientRect` reports it). */
export interface BrowserSidebarRect {
height: number;
@@ -14,14 +19,6 @@ export interface BrowserSidebarRect {
y: number;
}
-export interface BrowserSidebarViewportParams extends BrowserSidebarSessionParams {
- /**
- * Where to show the page. Omit it (or send a zero-sized rect) when the panel is
- * hidden β€” the page is then parked off-screen: still live, never destroyed.
- */
- rect?: BrowserSidebarRect;
-}
-
/** The agent overlay is drawn inside the page, so its copy has to come from the renderer. */
export interface BrowserSidebarOverlayLabelsParams {
controlling: string;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
index 84d2a2a3f75..d962fb6e028 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
@@ -22,6 +22,7 @@ import { BrowserIcon } from '@/components/BrowserIcon';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import { useLocalStorageState } from '@/hooks/useLocalStorageState';
import { electronBrowserSidebarService } from '@/services/electron/browserSidebar';
+import { browserWebviewRegistry } from '@/services/electron/browserWebviewRegistry';
import { useChatStore } from '@/store/chat';
import { useFileStore } from '@/store/file';
import { useGlobalStore } from '@/store/global';
@@ -32,7 +33,6 @@ import {
buildScreenshotFileName,
createElementContext,
dataUrlToFile,
- getBrowserViewportRect,
normalizeBrowserUrl,
} from './utils';
@@ -43,8 +43,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
position: absolute;
z-index: 3;
- /* Anchored to the toolbar's bottom border β€” the page container below is
- covered by the WebContentsView, which paints above renderer DOM. */
+ /* Anchored to the toolbar's bottom border. */
inset-block-end: -1px;
inset-inline: 0;
@@ -143,8 +142,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
toolbarActions: css`
margin-inline-start: auto;
`,
- /* The page itself is a main-process WebContentsView laid over this element β€”
- nothing renders inside it. It exists to be measured. */
+ /* The retained Electron webview is imperatively attached inside this host. */
viewport: css`
position: absolute;
inset: 0;
@@ -175,16 +173,12 @@ const BrowserPane = memo<BrowserPaneProps>(({ agentId, onMetadataChange, session
const consumedNonce = useRef<number>(undefined);
const viewportRef = useRef<HTMLDivElement>(null);
- // The page lives in the main process, so it exists as soon as anything has
- // navigated it β€” including an agent the user has never watched.
- const hasPage = state.attached || (!!state.url && state.url !== 'about:blank');
-
+ // Metadata comes from the main-process controller registered to this guest.
useEffect(() => {
onMetadataChange?.({ faviconUrl: state.faviconUrl, title: state.title, url: state.url });
}, [onMetadataChange, state.faviconUrl, state.title, state.url]);
- // The overlay is drawn inside the page (a WebContentsView paints above all
- // renderer DOM, so it can't be drawn here any more) β€” hand the copy over.
+ // The automation overlay is drawn inside the guest page β€” hand the copy over.
useEffect(() => {
if (!isDesktop) return;
void electronBrowserSidebarService.setOverlayLabels({
@@ -193,60 +187,22 @@ const BrowserPane = memo<BrowserPaneProps>(({ agentId, onMetadataChange, session
});
}, [t]);
- // Tell the main process where to lay the page out. Polled rather than observed
- // because the panel also moves when nothing about it resizes (the left sidebar
- // collapsing shifts its x), and a ResizeObserver would sleep through that.
- // A zero-sized rect β€” which is what `display: none` reports when another tab is
- // active β€” parks the page off-screen instead of destroying it.
+ // The guest stays alive in a hidden renderer host when this pane unmounts.
+ // Moving the same DOM node into this viewport keeps its browsing context while
+ // allowing ordinary React portals to paint above it.
useEffect(() => {
- if (!isDesktop || !hasPage) return;
-
- let frame = 0;
- let lastKey = '';
-
- const tick = () => {
- const element = viewportRef.current;
- if (element) {
- const rect = getBrowserViewportRect(element.getBoundingClientRect());
- const visible = rect.width >= 1 && rect.height >= 1;
- // devicePixelRatio tracks the app zoom level, and the main process turns
- // this CSS rect into DIP with the zoom factor. Without it in the key, a
- // Cmd +/- that leaves the rect unchanged would strand the page at the
- // bounds it had at the old zoom.
- const key = visible
- ? [rect.x, rect.y, rect.width, rect.height, window.devicePixelRatio]
- .map((value) => Math.round(value * 100))
- .join(',')
- : 'parked';
-
- if (key !== lastKey) {
- lastKey = key;
- void electronBrowserSidebarService.setViewport({
- rect: visible
- ? { height: rect.height, width: rect.width, x: rect.x, y: rect.y }
- : undefined,
- sessionId,
- });
- }
- }
-
- frame = requestAnimationFrame(tick);
- };
-
- frame = requestAnimationFrame(tick);
-
- // Nothing here handles "the same agent is open in another window, which took
- // the page": the rect never changes, so this loop stays silent. The main
- // process reclaims the page on the window's own `focus` event β€” a renderer
- // `focus` listener does not fire when you switch between two windows of the
- // same app (measured), so it cannot be the trigger.
+ const host = viewportRef.current;
+ if (!isDesktop || !host) return;
+ void browserWebviewRegistry.attach(sessionId, host).catch((error) => {
+ console.error('[BrowserSidebar] Failed to attach browser webview:', error);
+ });
return () => {
- cancelAnimationFrame(frame);
- // Park rather than close: the agent may still be driving this page.
- void electronBrowserSidebarService.setViewport({ sessionId });
+ void browserWebviewRegistry.detach(sessionId, host).catch((error) => {
+ console.error('[BrowserSidebar] Failed to retain browser webview:', error);
+ });
};
- }, [hasPage, sessionId]);
+ }, [sessionId]);
useEffect(() => {
if (!isEditing) setAddress(state.url === 'about:blank' ? '' : state.url);
@@ -473,9 +429,7 @@ const BrowserPane = memo<BrowserPaneProps>(({ agentId, onMetadataChange, session
onClick={() => void addScreenshotToInput()}
/>
</Flexbox>
- {/* Sits on the toolbar's edge, not inside the page container: a
- WebContentsView paints above all renderer DOM, so a bar drawn over the
- page area would be hidden the moment a page is showing. */}
+ {/* Sits on the toolbar edge so loading feedback remains stable. */}
{state.isLoading && (
<div
aria-label={t('workingPanel.browser.loading')}
@@ -512,17 +466,7 @@ const BrowserPane = memo<BrowserPaneProps>(({ agentId, onMetadataChange, session
</Flexbox>
)}
<Flexbox className={styles.container}>
- {hasPage ? (
- <div className={styles.viewport} ref={viewportRef} />
- ) : (
- <Center height={'100%'} width={'100%'}>
- <Empty
- description={t('workingPanel.browser.empty.desc')}
- icon={Globe}
- title={t('workingPanel.browser.empty.title')}
- />
- </Center>
- )}
+ <div className={styles.viewport} ref={viewportRef} />
</Flexbox>
</Flexbox>
);
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/utils.test.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/utils.test.ts
index c862032372e..c24ce40b487 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/utils.test.ts
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/utils.test.ts
@@ -4,30 +4,9 @@ import {
buildScreenshotFileName,
createElementContext,
dataUrlToFile,
- getBrowserViewportRect,
normalizeBrowserUrl,
} from './utils';
-describe('getBrowserViewportRect', () => {
- it('leaves the sidebar resize handle outside the native browser viewport', () => {
- expect(getBrowserViewportRect({ height: 640, width: 480, x: 900, y: 80 })).toEqual({
- height: 640,
- width: 472,
- x: 908,
- y: 80,
- });
- });
-
- it('never reports a negative viewport width for a collapsed panel', () => {
- expect(getBrowserViewportRect({ height: 0, width: 0, x: 1200, y: 80 })).toEqual({
- height: 0,
- width: 0,
- x: 1208,
- y: 80,
- });
- });
-});
-
describe('normalizeBrowserUrl', () => {
it('keeps explicit http URLs', () => {
expect(normalizeBrowserUrl('https://lobehub.com')).toBe('https://lobehub.com');
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/utils.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/utils.ts
index 0fb03006f4f..fa907a162fe 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/utils.ts
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/utils.ts
@@ -4,23 +4,6 @@ import { DEFAULT_BROWSER_URL } from './const';
const HTTP_URL_PATTERN = /^https?:\/\//i;
const LOCAL_URL_PATTERN = /^(?:localhost|127(?:\.\d{1,3}){3}|\[?::1\]?)(?::\d+)?(?:[/?#].*)?$/i;
-const VIEWPORT_RESIZE_GUTTER = 8;
-
-interface BrowserViewportRect {
- height: number;
- width: number;
- x: number;
- y: number;
-}
-
-/** Keep the native WebContentsView clear of the sidebar's left resize handle. */
-export const getBrowserViewportRect = (rect: BrowserViewportRect): BrowserViewportRect => ({
- height: rect.height,
- width: Math.max(0, rect.width - VIEWPORT_RESIZE_GUTTER),
- x: rect.x + VIEWPORT_RESIZE_GUTTER,
- y: rect.y,
-});
-
export const normalizeBrowserUrl = (value?: string): string => {
const text = value?.trim();
if (!text) return DEFAULT_BROWSER_URL;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index b3a17148cef..9825a7ce88d 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -214,7 +214,7 @@ const AgentWorkingSidebar = memo(() => {
const filesAvailable = !isChatMode && (isLocalExecution || isDeviceMode) && !!workingDirectory;
const reviewAvailable = (isLocalExecution || isDeviceMode) && !!workingDirectory && !!repoType;
const paramsAvailable = !isHetero;
- // The in-app browser pages are main-process WebContentsViews β€” desktop only,
+ // The in-app browser pages are renderer-retained Electron webviews β€” desktop only,
// and gated behind the Labs toggle while the feature matures.
const enableInAppBrowser = useUserStore(labPreferSelectors.enableInAppBrowser);
const browserAvailable = isDesktop && enableInAppBrowser;
diff --git a/src/routes/(main)/settings/labs/index.tsx b/src/routes/(main)/settings/labs/index.tsx
index 1361f68bc3b..8a44fe689ea 100644
--- a/src/routes/(main)/settings/labs/index.tsx
+++ b/src/routes/(main)/settings/labs/index.tsx
@@ -178,7 +178,7 @@ const Page = memo(() => {
];
// Desktop-only experiments: iMessage bridge, the Claude Code SDK runtime, and
- // the in-app browser (main-process WebContentsViews).
+ // the in-app browser (renderer-retained Electron webviews).
const desktopItems: FormItemProps[] = [
{
children: (
diff --git a/src/services/electron/browserControl.test.ts b/src/services/electron/browserControl.test.ts
new file mode 100644
index 00000000000..af21a1f52a3
--- /dev/null
+++ b/src/services/electron/browserControl.test.ts
@@ -0,0 +1,30 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { click, touch } = vi.hoisted(() => ({
+ click: vi.fn().mockResolvedValue({ success: true }),
+ touch: vi.fn(),
+}));
+
+vi.mock('@/utils/electron/ipc', () => ({
+ ensureElectronIpc: () => ({ browserControl: { click } }),
+}));
+
+vi.mock('./browserWebviewRegistry', () => ({
+ browserWebviewRegistry: { touch },
+}));
+
+describe('electronBrowserControlService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('touches the retained guest before a control call', async () => {
+ const { electronBrowserControlService } = await import('./browserControl');
+
+ await electronBrowserControlService.click({ ref: 'e1', sessionId: 'topic-1' });
+
+ expect(touch).toHaveBeenCalledWith('topic-1');
+ expect(click).toHaveBeenCalledWith({ ref: 'e1', sessionId: 'topic-1' });
+ expect(touch.mock.invocationCallOrder[0]).toBeLessThan(click.mock.invocationCallOrder[0]);
+ });
+});
diff --git a/src/services/electron/browserControl.ts b/src/services/electron/browserControl.ts
index 5016331ecf4..1e432014b4a 100644
--- a/src/services/electron/browserControl.ts
+++ b/src/services/electron/browserControl.ts
@@ -15,6 +15,8 @@ import type {
import { ensureElectronIpc } from '@/utils/electron/ipc';
+import { browserWebviewRegistry } from './browserWebviewRegistry';
+
class ElectronBrowserControlService {
private get ipc() {
return ensureElectronIpc();
@@ -25,34 +27,42 @@ class ElectronBrowserControlService {
}
click(params: BrowserControlClickParams): Promise<BrowserControlClickResult> {
+ browserWebviewRegistry.touch(params.sessionId);
return this.ipc.browserControl.click(params);
}
fill(params: BrowserControlFillParams): Promise<BrowserControlResult> {
+ browserWebviewRegistry.touch(params.sessionId);
return this.ipc.browserControl.fill(params);
}
press(params: BrowserControlPressParams): Promise<BrowserControlResult> {
+ browserWebviewRegistry.touch(params.sessionId);
return this.ipc.browserControl.press(params);
}
readPage(params: BrowserControlParams): Promise<BrowserControlReadPageResult> {
+ browserWebviewRegistry.touch(params.sessionId);
return this.ipc.browserControl.readPage(params);
}
screenshot(params: BrowserControlParams): Promise<BrowserControlScreenshotResult> {
+ browserWebviewRegistry.touch(params.sessionId);
return this.ipc.browserControl.screenshot(params);
}
scroll(params: BrowserControlScrollParams): Promise<BrowserControlResult> {
+ browserWebviewRegistry.touch(params.sessionId);
return this.ipc.browserControl.scroll(params);
}
snapshot(params: BrowserControlParams): Promise<BrowserControlSnapshotResult> {
+ browserWebviewRegistry.touch(params.sessionId);
return this.ipc.browserControl.snapshot(params);
}
waitFor(params: BrowserControlWaitForParams): Promise<BrowserControlResult> {
+ browserWebviewRegistry.touch(params.sessionId);
return this.ipc.browserControl.waitFor(params);
}
}
diff --git a/src/services/electron/browserSidebar.ts b/src/services/electron/browserSidebar.ts
index 69705fbd134..155a1ce3e1a 100644
--- a/src/services/electron/browserSidebar.ts
+++ b/src/services/electron/browserSidebar.ts
@@ -8,11 +8,12 @@ import type {
BrowserSidebarResult,
BrowserSidebarSessionParams,
BrowserSidebarState,
- BrowserSidebarViewportParams,
} from '@lobechat/electron-client-ipc';
import { ensureElectronIpc } from '@/utils/electron/ipc';
+import { browserWebviewRegistry } from './browserWebviewRegistry';
+
class ElectronBrowserSidebarService {
private get ipc() {
return ensureElectronIpc();
@@ -42,7 +43,8 @@ class ElectronBrowserSidebarService {
return this.ipc.browserSidebar.importChromeLoginData();
}
- navigate(params: BrowserSidebarNavigateParams): Promise<BrowserSidebarResult> {
+ async navigate(params: BrowserSidebarNavigateParams): Promise<BrowserSidebarResult> {
+ await browserWebviewRegistry.ensure(params.sessionId);
return this.ipc.browserSidebar.navigate(params);
}
@@ -62,10 +64,6 @@ class ElectronBrowserSidebarService {
return this.ipc.browserSidebar.setOverlayLabels(params);
}
- setViewport(params: BrowserSidebarViewportParams): Promise<BrowserSidebarResult> {
- return this.ipc.browserSidebar.setViewport(params);
- }
-
stop(params: BrowserSidebarSessionParams): Promise<BrowserSidebarResult> {
return this.ipc.browserSidebar.stop(params);
}
diff --git a/src/services/electron/browserWebviewRegistry.test.ts b/src/services/electron/browserWebviewRegistry.test.ts
new file mode 100644
index 00000000000..97627851dd8
--- /dev/null
+++ b/src/services/electron/browserWebviewRegistry.test.ts
@@ -0,0 +1,142 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const registerWebview = vi.fn().mockResolvedValue({ success: true });
+
+vi.mock('@/utils/electron/ipc', () => ({
+ ensureElectronIpc: () => ({ browserSidebar: { registerWebview } }),
+}));
+
+describe('browserWebviewRegistry', () => {
+ const originalCreateElement = document.createElement.bind(document);
+
+ const resolveWebview = async (sessionId: string) => {
+ const { browserWebviewRegistry } = await import('./browserWebviewRegistry');
+ const ready = browserWebviewRegistry.ensure(sessionId);
+ const webview = document.querySelector<HTMLElement>(
+ `webview[data-browser-session-id="${sessionId}"]`,
+ );
+ webview?.dispatchEvent(new Event('dom-ready'));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await ready;
+ return webview;
+ };
+
+ beforeEach(() => {
+ vi.resetModules();
+ registerWebview.mockReset().mockResolvedValue({ success: true });
+ document.body.replaceChildren();
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ disconnect = vi.fn();
+ observe = vi.fn();
+ },
+ );
+ vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
+ const element = originalCreateElement(tagName);
+ if (tagName === 'webview') {
+ Object.assign(element, { getWebContentsId: () => 42 });
+ }
+ return element;
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('keeps the retained webview in its stable host while projecting visible bounds', async () => {
+ const { browserWebviewRegistry } = await import('./browserWebviewRegistry');
+ const portalRoot = document.createElement('div');
+ portalRoot.id = 'lobe-ui-theme-app';
+ const appSurface = document.createElement('div');
+ portalRoot.append(appSurface);
+ document.body.append(portalRoot);
+ const viewport = document.createElement('div');
+ viewport.getBoundingClientRect = () =>
+ ({
+ bottom: 640,
+ height: 600,
+ left: 320,
+ right: 680,
+ top: 40,
+ width: 360,
+ x: 320,
+ y: 40,
+ }) as DOMRect;
+ document.body.append(viewport);
+
+ const attaching = browserWebviewRegistry.attach('topic-1', viewport);
+ const retainedHost = document.querySelector('#lobe-browser-retained-webviews');
+ const webview = retainedHost?.querySelector<HTMLElement>('webview');
+ webview?.dispatchEvent(new Event('dom-ready'));
+ await attaching;
+
+ expect(webview?.parentElement).toBe(retainedHost);
+ expect(retainedHost?.parentElement).toBe(portalRoot);
+ expect(portalRoot.firstElementChild).toBe(appSurface);
+ expect(portalRoot.lastElementChild).toBe(retainedHost);
+
+ const overlayPortal = document.createElement('div');
+ portalRoot.append(overlayPortal);
+ expect(retainedHost?.nextElementSibling).toBe(overlayPortal);
+ expect(webview?.style.left).toBe('320px');
+ expect(webview?.style.top).toBe('40px');
+ expect(webview?.style.width).toBe('360px');
+ expect(webview?.style.height).toBe('600px');
+ expect(retainedHost).toHaveStyle({ overflow: 'visible', zIndex: '' });
+ expect(webview).toHaveStyle({ zIndex: '' });
+ expect(registerWebview).toHaveBeenCalledOnce();
+
+ await browserWebviewRegistry.detach('topic-1', viewport);
+
+ expect(webview?.parentElement).toBe(retainedHost);
+ expect(webview?.style.left).toBe('-10000px');
+ expect(webview?.style.opacity).toBe('0');
+ });
+
+ it('resyncs fixed bounds when the host moves without resizing', async () => {
+ vi.useFakeTimers();
+
+ const { browserWebviewRegistry } = await import('./browserWebviewRegistry');
+ let left = 320;
+ const viewport = document.createElement('div');
+ viewport.getBoundingClientRect = () => ({ height: 600, left, top: 40, width: 360 }) as DOMRect;
+ document.body.append(viewport);
+
+ const attaching = browserWebviewRegistry.attach('moving-topic', viewport);
+ const webview = document.querySelector<HTMLElement>('webview');
+ webview?.dispatchEvent(new Event('dom-ready'));
+ await vi.advanceTimersByTimeAsync(0);
+ await attaching;
+ expect(webview?.style.left).toBe('320px');
+
+ left = 240;
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(webview?.style.left).toBe('240px');
+ await browserWebviewRegistry.detach('moving-topic', viewport);
+ vi.useRealTimers();
+ });
+
+ it('does not evict a recently touched hidden webview', async () => {
+ let now = 0;
+ vi.spyOn(Date, 'now').mockImplementation(() => now);
+ const { browserWebviewRegistry, MAX_RETAINED_BROWSER_WEBVIEWS } =
+ await import('./browserWebviewRegistry');
+
+ for (let index = 0; index < MAX_RETAINED_BROWSER_WEBVIEWS; index++) {
+ now = index;
+ await resolveWebview(`topic-${index}`);
+ }
+
+ now = 120_000;
+ browserWebviewRegistry.touch('topic-0');
+ await resolveWebview('topic-new');
+
+ expect(document.querySelector('webview[data-browser-session-id="topic-0"]')).not.toBeNull();
+ expect(document.querySelector('webview[data-browser-session-id="topic-1"]')).toBeNull();
+ expect(document.querySelector('webview[data-browser-session-id="topic-new"]')).not.toBeNull();
+ });
+});
diff --git a/src/services/electron/browserWebviewRegistry.ts b/src/services/electron/browserWebviewRegistry.ts
new file mode 100644
index 00000000000..0706261ab68
--- /dev/null
+++ b/src/services/electron/browserWebviewRegistry.ts
@@ -0,0 +1,229 @@
+import { ensureElectronIpc } from '@/utils/electron/ipc';
+
+const BROWSER_PARTITION = 'persist:lobe-browser-app';
+const HIDDEN_HOST_ID = 'lobe-browser-retained-webviews';
+const PORTAL_ROOT_ID = 'lobe-ui-theme-app';
+export const MAX_RETAINED_BROWSER_WEBVIEWS = 10;
+const RETAINED_IN_USE_GRACE_MS = 60_000;
+const BOUNDS_POLL_INTERVAL_MS = 100;
+
+interface BrowserWebviewElement extends HTMLElement {
+ getWebContentsId: () => number;
+}
+
+interface RetainedWebview {
+ boundsFrame?: number;
+ boundsPollTimer?: number;
+ host?: HTMLElement;
+ lastBoundsKey?: string;
+ lastUsedAt: number;
+ ready: Promise<BrowserWebviewElement>;
+ resizeObserver?: ResizeObserver;
+ syncBounds?: () => void;
+ visible: boolean;
+ webview: BrowserWebviewElement;
+}
+
+const getHiddenHost = () => {
+ const existing = document.querySelector(`#${HIDDEN_HOST_ID}`);
+ if (existing instanceof HTMLDivElement) return existing;
+
+ const host = document.createElement('div');
+ host.id = HIDDEN_HOST_ID;
+ host.setAttribute('aria-hidden', 'true');
+ Object.assign(host.style, {
+ inset: '0',
+ overflow: 'visible',
+ pointerEvents: 'none',
+ position: 'fixed',
+ });
+ // Keep the guest and application overlays in the same composition subtree.
+ // Electron guests can otherwise paint above a portal even when the portal has
+ // a larger CSS z-index. The theme root already contains the application
+ // surface when this registry is first used; appending the guest here puts it
+ // above that surface, while subsequently opened portals paint above the
+ // guest. The host never moves again, so the browsing context stays intact.
+ const portalRoot = document.querySelector(`#${PORTAL_ROOT_ID}`);
+ if (portalRoot) portalRoot.append(host);
+ else document.body.append(host);
+ return host;
+};
+
+class BrowserWebviewRegistry {
+ private retained = new Map<string, RetainedWebview>();
+
+ async attach(sessionId: string, host: HTMLElement): Promise<BrowserWebviewElement> {
+ const webview = await this.ensure(sessionId);
+ const retained = this.retained.get(sessionId);
+ if (retained) {
+ this.stopBoundsSync(retained);
+ retained.host = host;
+ retained.lastUsedAt = Date.now();
+ retained.visible = true;
+ retained.syncBounds = () => this.scheduleBoundsSync(retained);
+ retained.resizeObserver = new ResizeObserver(retained.syncBounds);
+ retained.resizeObserver.observe(host);
+ window.addEventListener('resize', retained.syncBounds);
+ window.addEventListener('scroll', retained.syncBounds, true);
+ retained.boundsPollTimer = window.setInterval(retained.syncBounds, BOUNDS_POLL_INTERVAL_MS);
+ }
+
+ Object.assign(webview.style, {
+ opacity: '1',
+ pointerEvents: 'auto',
+ position: 'fixed',
+ zIndex: '',
+ });
+ if (retained) this.syncBounds(retained);
+ return webview;
+ }
+
+ async detach(sessionId: string, host?: HTMLElement): Promise<void> {
+ const retained = this.retained.get(sessionId);
+ if (!retained) return;
+
+ const webview = await retained.ready;
+ if (host && retained.host !== host) return;
+
+ this.stopBoundsSync(retained);
+ retained.host = undefined;
+ retained.lastUsedAt = Date.now();
+ retained.lastBoundsKey = undefined;
+ retained.visible = false;
+ Object.assign(webview.style, {
+ height: '800px',
+ left: '-10000px',
+ opacity: '0',
+ pointerEvents: 'none',
+ position: 'fixed',
+ top: '0',
+ width: '1200px',
+ });
+ }
+
+ ensure(sessionId: string): Promise<BrowserWebviewElement> {
+ const existing = this.retained.get(sessionId);
+ if (existing) {
+ existing.lastUsedAt = Date.now();
+ return existing.ready;
+ }
+
+ this.evictColdWebviews();
+
+ const webview = document.createElement('webview') as BrowserWebviewElement;
+ webview.dataset.browserSessionId = sessionId;
+ webview.setAttribute('partition', BROWSER_PARTITION);
+ const initialUrl = 'about:blank';
+ webview.setAttribute('src', initialUrl);
+ webview.setAttribute('webpreferences', 'contextIsolation=yes,nodeIntegration=no,sandbox=yes');
+
+ const ready = new Promise<BrowserWebviewElement>((resolve, reject) => {
+ const onDestroyed = () => reject(new Error(`Browser webview was destroyed: ${sessionId}`));
+ webview.addEventListener('destroyed', onDestroyed, { once: true });
+ webview.addEventListener(
+ 'dom-ready',
+ () => {
+ webview.removeEventListener('destroyed', onDestroyed);
+ // Electron dispatches `dom-ready` before the <webview> wrapper has
+ // finished exposing its guest WebContents to getWebContentsId().
+ // Leave the event stack before registering the guest with main.
+ window.setTimeout(() => {
+ void this.activate(sessionId, webview).then(() => resolve(webview), reject);
+ }, 0);
+ },
+ { once: true },
+ );
+ });
+
+ const retained: RetainedWebview = {
+ lastUsedAt: Date.now(),
+ ready,
+ visible: false,
+ webview,
+ };
+ this.retained.set(sessionId, retained);
+ getHiddenHost().append(webview);
+ Object.assign(webview.style, {
+ height: '800px',
+ left: '-10000px',
+ opacity: '0',
+ pointerEvents: 'none',
+ position: 'fixed',
+ top: '0',
+ width: '1200px',
+ });
+
+ return ready;
+ }
+
+ /** Keep a background guest out of LRU eviction while an agent is driving it. */
+ touch(sessionId: string): void {
+ const retained = this.retained.get(sessionId);
+ if (retained) retained.lastUsedAt = Date.now();
+ }
+
+ private async activate(sessionId: string, webview: BrowserWebviewElement): Promise<void> {
+ const result = await ensureElectronIpc().browserSidebar.registerWebview({
+ sessionId,
+ webContentsId: webview.getWebContentsId(),
+ });
+ if (!result.success) throw new Error(result.error || 'Failed to register browser webview');
+ }
+
+ private scheduleBoundsSync(retained: RetainedWebview): void {
+ if (retained.boundsFrame !== undefined) return;
+ retained.boundsFrame = window.requestAnimationFrame(() => {
+ retained.boundsFrame = undefined;
+ this.syncBounds(retained);
+ });
+ }
+
+ private stopBoundsSync(retained: RetainedWebview): void {
+ retained.resizeObserver?.disconnect();
+ retained.resizeObserver = undefined;
+ if (retained.boundsPollTimer !== undefined) {
+ window.clearInterval(retained.boundsPollTimer);
+ retained.boundsPollTimer = undefined;
+ }
+ if (retained.syncBounds) {
+ window.removeEventListener('resize', retained.syncBounds);
+ window.removeEventListener('scroll', retained.syncBounds, true);
+ }
+ retained.syncBounds = undefined;
+ if (retained.boundsFrame !== undefined) {
+ window.cancelAnimationFrame(retained.boundsFrame);
+ retained.boundsFrame = undefined;
+ }
+ }
+
+ private syncBounds(retained: RetainedWebview): void {
+ if (!retained.visible || !retained.host) return;
+ const bounds = retained.host.getBoundingClientRect();
+ const boundsKey = `${bounds.left},${bounds.top},${bounds.width},${bounds.height}`;
+ if (retained.lastBoundsKey === boundsKey) return;
+ retained.lastBoundsKey = boundsKey;
+ Object.assign(retained.webview.style, {
+ height: `${bounds.height}px`,
+ left: `${bounds.left}px`,
+ top: `${bounds.top}px`,
+ width: `${bounds.width}px`,
+ });
+ }
+
+ private evictColdWebviews(): void {
+ if (this.retained.size < MAX_RETAINED_BROWSER_WEBVIEWS) return;
+
+ const evictionCutoff = Date.now() - RETAINED_IN_USE_GRACE_MS;
+ const candidate = [...this.retained.entries()]
+ .filter(([, retained]) => !retained.visible && retained.lastUsedAt < evictionCutoff)
+ .sort(([, a], [, b]) => a.lastUsedAt - b.lastUsedAt)[0];
+ if (!candidate) return;
+
+ const [sessionId, retained] = candidate;
+ this.stopBoundsSync(retained);
+ this.retained.delete(sessionId);
+ retained.webview.remove();
+ }
+}
+
+export const browserWebviewRegistry = new BrowserWebviewRegistry();