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): own in-app browser pages in the main process (#17155)

Arvin Xu6634198b7d9b
diff --git a/apps/desktop/src/main/controllers/BrowserControlCtr.ts b/apps/desktop/src/main/controllers/BrowserControlCtr.ts
index 15caf57f375..a1b0671d9c3 100644
--- a/apps/desktop/src/main/controllers/BrowserControlCtr.ts
+++ b/apps/desktop/src/main/controllers/BrowserControlCtr.ts
@@ -15,6 +15,11 @@ import type {
} from '@lobechat/electron-client-ipc';
import type { WebContents } from 'electron';
+import {
+ OVERLAY_REMOVE_SCRIPT,
+ overlayControllingScript,
+ overlayCursorScript,
+} from '@/modules/browser/agentOverlayScript';
import { createLogger } from '@/utils/logger';
import BrowserSidebarCtr from './BrowserSidebarCtr';
@@ -234,8 +239,8 @@ export default class BrowserControlCtr extends ControllerModule {
return { error: 'click needs a ref or x/y coordinates', success: false };
}
- this.markControlling(params.sessionId);
- this.broadcastCursor(params.sessionId, x, y, true);
+ this.markControlling(params.sessionId, guest);
+ this.showCursor(guest, x, y, true);
await sleep(CURSOR_TRAVEL_MS);
guest.sendInputEvent({ type: 'mouseMove', x, y });
@@ -250,7 +255,7 @@ export default class BrowserControlCtr extends ControllerModule {
@IpcMethod()
async fill(params: BrowserControlFillParams): Promise<BrowserControlResult> {
return this.withGuest(params.sessionId, async (guest) => {
- this.markControlling(params.sessionId);
+ this.markControlling(params.sessionId, guest);
const raw = await guest.executeJavaScript(fillScript(params.ref, params.text));
const result = JSON.parse(raw);
if (result.error) return { error: result.error, success: false };
@@ -267,7 +272,7 @@ export default class BrowserControlCtr extends ControllerModule {
@IpcMethod()
async press(params: BrowserControlPressParams): Promise<BrowserControlResult> {
return this.withGuest(params.sessionId, (guest) => {
- this.markControlling(params.sessionId);
+ this.markControlling(params.sessionId, guest);
this.sendKey(guest, params.key);
return { success: true };
});
@@ -276,7 +281,7 @@ export default class BrowserControlCtr extends ControllerModule {
@IpcMethod()
async scroll(params: BrowserControlScrollParams): Promise<BrowserControlResult> {
return this.withGuest(params.sessionId, async (guest) => {
- this.markControlling(params.sessionId);
+ this.markControlling(params.sessionId, guest);
await guest.executeJavaScript(
`window.scrollBy({ behavior: 'smooth', left: ${Number(params.dx) || 0}, top: ${Number(params.dy) || 0} })`,
);
@@ -288,6 +293,10 @@ export default class BrowserControlCtr extends ControllerModule {
@IpcMethod()
async screenshot(params: BrowserControlParams): Promise<BrowserControlScreenshotResult> {
return this.withGuest(params.sessionId, async (guest) => {
+ // Strip the agent cursor/chip first β€” otherwise the model sees its own
+ // overlay in the frame it just asked for.
+ await guest.executeJavaScript(OVERLAY_REMOVE_SCRIPT).catch(() => {});
+
let image = await guest.capturePage();
const size = image.getSize();
if (size.width > SCREENSHOT_MAX_WIDTH) image = image.resize({ width: SCREENSHOT_MAX_WIDTH });
@@ -342,6 +351,10 @@ 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) {
@@ -357,32 +370,32 @@ export default class BrowserControlCtr extends ControllerModule {
guest.sendInputEvent({ keyCode: key, type: 'keyUp' });
}
- private broadcastCursor(sessionId: string, x: number, y: number, click?: boolean) {
- this.app.browserManager.broadcastToAllWindows('browserSidebarAgentCursor', {
- click,
- sessionId,
- x,
- y,
+ /**
+ * 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.
+ */
+ private inject(guest: WebContents, script: string) {
+ guest.executeJavaScript(script).catch((error: Error) => {
+ logger.debug(`Agent overlay injection failed: ${error.message}`);
});
}
- private markControlling(sessionId: string) {
+ private showCursor(guest: WebContents, x: number, y: number, click: boolean) {
+ this.inject(guest, overlayCursorScript(this.sidebar.getOverlayLabels(), x, y, click));
+ }
+
+ private markControlling(sessionId: string, guest: WebContents) {
const existing = this.idleTimers.get(sessionId);
if (existing) clearTimeout(existing);
- else
- this.app.browserManager.broadcastToAllWindows('browserSidebarAgentState', {
- active: true,
- sessionId,
- });
+ else this.inject(guest, overlayControllingScript(this.sidebar.getOverlayLabels(), true));
this.idleTimers.set(
sessionId,
setTimeout(() => {
this.idleTimers.delete(sessionId);
- this.app.browserManager.broadcastToAllWindows('browserSidebarAgentState', {
- active: false,
- sessionId,
- });
+ if (guest.isDestroyed()) return;
+ this.inject(guest, overlayControllingScript(this.sidebar.getOverlayLabels(), false));
}, CONTROL_IDLE_MS),
);
}
diff --git a/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts b/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
index cc9c0eb6780..a58250dfa4f 100644
--- a/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
+++ b/apps/desktop/src/main/controllers/BrowserSidebarCtr.ts
@@ -1,47 +1,45 @@
import type {
- BrowserSidebarAttachParams,
BrowserSidebarImportResult,
BrowserSidebarNavigateParams,
+ BrowserSidebarOverlayLabelsParams,
BrowserSidebarResult,
BrowserSidebarSessionParams,
BrowserSidebarState,
+ BrowserSidebarViewportParams,
} from '@lobechat/electron-client-ipc';
-import type { WebContents, WebPreferences } from 'electron';
+import type { BrowserWindow, WebContents } from 'electron';
import {
app as electronApp,
+ BrowserWindow as ElectronBrowserWindow,
clipboard,
session as electronSession,
shell,
- webContents as electronWebContents,
} from 'electron';
+import type { AgentOverlayLabels } from '@/modules/browser/agentOverlayScript';
+import { BrowserPagePool } from '@/modules/browser/BrowserPagePool';
import { importChromeLoginData } from '@/modules/browser/importChromeLoginData';
+import { getIpcContext } from '@/utils/ipc/base';
import { createLogger } from '@/utils/logger';
import { ControllerModule, IpcMethod } from './index';
const logger = createLogger('controllers:BrowserSidebarCtr');
-// Shared persistent profile: logins/cookies survive across agents and restarts,
-// mirroring a regular browser. Agent-driven sessions (M2) will get an isolated
-// partition instead. The renderer sets this as the <webview> `partition`
-// attribute β€” the only reliable identity channel into `will-attach-webview`
-// (custom data-* attributes are NOT forwarded in its params).
+/**
+ * Shared persistent profile: logins/cookies survive across agents and restarts,
+ * mirroring a regular browser.
+ */
const BROWSER_PARTITION = 'persist:lobe-browser-app';
-const BROWSER_PARTITION_PREFIX = 'persist:lobe-browser-';
const DEFAULT_BROWSER_URL = 'about:blank';
const HTTP_URL_PATTERN = /^https?:\/\//i;
const LOCAL_URL_PATTERN = /^(?:localhost|127(?:\.\d{1,3}){3}|\[?::1\]?)(?::\d+)?(?:[/?#].*)?$/i;
const SUPPORTED_PROTOCOLS = new Set(['about:', 'http:', 'https:']);
-interface BrowserPageRecord {
- error?: string;
- isLoading: boolean;
- sessionId: string;
- title: string;
- url: string;
- webContents?: WebContents;
-}
+const DEFAULT_OVERLAY_LABELS: AgentOverlayLabels = {
+ controlling: 'Agent is controlling this page',
+ cursor: 'Agent',
+};
const normalizeBrowserUrl = (value?: string): string => {
const text = value?.trim();
@@ -70,46 +68,42 @@ 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.
+ */
export default class BrowserSidebarCtr extends ControllerModule {
static override readonly groupName = 'browserSidebar';
- private ownerWebContentsIds = new Set<number>();
- private pages = new Map<string, BrowserPageRecord>();
private partitionConfigured = false;
+ private pagePool?: BrowserPagePool;
+ private overlayLabels: AgentOverlayLabels = DEFAULT_OVERLAY_LABELS;
beforeAppReady() {
- electronApp.on('web-contents-created', (_event, webContents) => {
- this.attachOwnerWebContents(webContents);
+ 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();
+ });
});
}
- /**
- * Bind a session to an attached <webview> guest. Identity flows through this
- * explicit call (renderer reads `getWebContentsId()` on dom-ready) because
- * `will-attach-webview` params carry no custom attributes to match on.
- */
- @IpcMethod()
- attach(params: BrowserSidebarAttachParams): BrowserSidebarResult {
- const guest = electronWebContents.fromId(params.webContentsId);
- if (!guest || guest.isDestroyed()) {
- return { error: 'Webview is not available', success: false };
- }
-
- // Only guests living in our hardened browser partition may be claimed.
- if (guest.session !== electronSession.fromPartition(BROWSER_PARTITION)) {
- logger.warn(`Rejected attach for webContents ${params.webContentsId}: wrong session`);
- return { error: 'Webview does not belong to the browser sidebar', success: false };
- }
-
- if (this.getLiveWebContents(params.sessionId)?.id === guest.id) return { success: true };
-
- this.attachPageWebContents(params.sessionId, guest);
- return { success: true };
- }
-
@IpcMethod()
captureScreenshotToClipboard(params: BrowserSidebarSessionParams): Promise<BrowserSidebarResult> {
- return this.withPageWebContents(params.sessionId, async (webContents) => {
+ return this.withPage(params.sessionId, async (webContents) => {
const image = await webContents.capturePage();
clipboard.writeImage(image);
return { success: true };
@@ -139,7 +133,7 @@ export default class BrowserSidebarCtr extends ControllerModule {
@IpcMethod()
goBack(params: BrowserSidebarSessionParams): Promise<BrowserSidebarResult> {
- return this.withPageWebContents(params.sessionId, (webContents) => {
+ return this.withPage(params.sessionId, (webContents) => {
if (!webContents.canGoBack()) return { success: false };
webContents.goBack();
return { success: true };
@@ -148,13 +142,17 @@ export default class BrowserSidebarCtr extends ControllerModule {
@IpcMethod()
goForward(params: BrowserSidebarSessionParams): Promise<BrowserSidebarResult> {
- return this.withPageWebContents(params.sessionId, (webContents) => {
+ return this.withPage(params.sessionId, (webContents) => {
if (!webContents.canGoForward()) return { success: false };
webContents.goForward();
return { success: true };
});
}
+ /**
+ * Creates the page if this session doesn't have one yet, so an agent can drive
+ * a page the user has never opened β€” no UI round-trip, no waiting for a mount.
+ */
@IpcMethod()
async navigate(params: BrowserSidebarNavigateParams): Promise<BrowserSidebarResult> {
const url = normalizeBrowserUrl(params.url);
@@ -162,24 +160,23 @@ export default class BrowserSidebarCtr extends ControllerModule {
return { error: `Unsupported URL: ${url}`, success: false };
}
- const page = this.ensurePage(params.sessionId);
+ const page = this.pool.ensure(params.sessionId);
page.url = url;
page.error = undefined;
- const webContents = this.getLiveWebContents(params.sessionId);
- if (!webContents) {
- this.broadcastState(params.sessionId);
- return { success: true };
- }
+ await page.view.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}`);
+ });
- await webContents.loadURL(url);
this.updateSnapshot(params.sessionId);
return { success: true };
}
@IpcMethod()
openExternal(params: BrowserSidebarSessionParams): Promise<BrowserSidebarResult> {
- return this.withPageWebContents(params.sessionId, async (webContents) => {
+ return this.withPage(params.sessionId, async (webContents) => {
const url = webContents.getURL();
if (!url || !HTTP_URL_PATTERN.test(url)) {
return { error: `Unsupported URL: ${url}`, success: false };
@@ -192,7 +189,7 @@ export default class BrowserSidebarCtr extends ControllerModule {
@IpcMethod()
reload(params: BrowserSidebarSessionParams): Promise<BrowserSidebarResult> {
- return this.withPageWebContents(params.sessionId, (webContents) => {
+ return this.withPage(params.sessionId, (webContents) => {
webContents.reload();
return { success: true };
});
@@ -200,107 +197,79 @@ export default class BrowserSidebarCtr extends ControllerModule {
@IpcMethod()
stop(params: BrowserSidebarSessionParams): Promise<BrowserSidebarResult> {
- return this.withPageWebContents(params.sessionId, (webContents) => {
+ return this.withPage(params.sessionId, (webContents) => {
webContents.stop();
return { success: true };
});
}
- private attachOwnerWebContents(webContents: WebContents): void {
- if (this.ownerWebContentsIds.has(webContents.id)) return;
-
- this.ownerWebContentsIds.add(webContents.id);
-
- webContents.on('will-attach-webview', (event, webPreferences, params) => {
- // Custom data-* attributes are not forwarded here, so the partition
- // attribute (set by the renderer) is the recognition signal.
- if (!params.partition?.startsWith(BROWSER_PARTITION_PREFIX)) return;
+ /**
+ * 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.
+ */
+ @IpcMethod()
+ setViewport(params: BrowserSidebarViewportParams): BrowserSidebarResult {
+ const { rect, sessionId } = params;
+ const host = this.getSenderWindow();
- const initialUrl = normalizeBrowserUrl(params.src);
- if (!isSupportedNavigationUrl(initialUrl)) {
- event.preventDefault();
- logger.warn(`Blocked unsupported browser sidebar URL: ${initialUrl}`);
- return;
- }
+ if (!rect || rect.width < 1 || rect.height < 1 || !host) {
+ this.pool.hide(sessionId, host);
+ return { success: true };
+ }
- this.configureBrowserSession();
+ this.pool.show(sessionId, rect, host);
+ return { success: true };
+ }
- params.src = initialUrl;
- params.partition = BROWSER_PARTITION;
+ /** The overlay is drawn inside the page, so its copy has to come from the renderer. */
+ @IpcMethod()
+ setOverlayLabels(params: BrowserSidebarOverlayLabelsParams): BrowserSidebarResult {
+ this.overlayLabels = { controlling: params.controlling, cursor: params.cursor };
+ return { success: true };
+ }
- this.applySecureWebPreferences(webPreferences);
- });
+ /** Accessors for sibling controllers (BrowserControlCtr drives the pages). */
+ getSessionWebContents(sessionId: string): WebContents | undefined {
+ return this.pagePool?.webContentsOf(sessionId);
+ }
- webContents.once('destroyed', () => {
- this.ownerWebContentsIds.delete(webContents.id);
- });
+ /** Mark a page as in use so the memory cap doesn't discard it mid-automation. */
+ touchPage(sessionId: string): void {
+ this.pagePool?.touch(sessionId);
}
- private applySecureWebPreferences(webPreferences: WebPreferences): void {
- Object.assign(webPreferences, {
- contextIsolation: true,
- devTools: true,
- nodeIntegration: false,
- partition: BROWSER_PARTITION,
- preload: undefined,
- sandbox: true,
- } satisfies Partial<WebPreferences>);
+ getOverlayLabels(): AgentOverlayLabels {
+ return this.overlayLabels;
}
- private attachPageWebContents(sessionId: string, webContents: WebContents): void {
- const page = this.ensurePage(sessionId);
- page.webContents = webContents;
-
- webContents.setWindowOpenHandler(({ url }) => {
- // target=_blank links stay inside the sidebar: retarget the current page
- // instead of spawning detached native windows the sidebar can't manage.
- if (HTTP_URL_PATTERN.test(url)) {
- webContents.loadURL(url).catch((error) => {
- logger.error(`Failed to open URL in browser sidebar: ${url}`, error);
- });
- }
+ private get pool(): BrowserPagePool {
+ if (this.pagePool) return this.pagePool;
- return { action: 'deny' };
+ this.configureBrowserSession();
+ this.pagePool = new BrowserPagePool({
+ onPageChanged: (sessionId) => this.updateSnapshot(sessionId),
+ partition: BROWSER_PARTITION,
});
- const update = () => this.updateSnapshot(sessionId);
+ return this.pagePool;
+ }
- webContents.on('page-title-updated', update);
- webContents.on('did-start-loading', () => {
- page.isLoading = true;
- this.updateSnapshot(sessionId);
- });
- webContents.on('did-stop-loading', () => {
- page.isLoading = false;
- this.updateSnapshot(sessionId);
- });
- webContents.on('did-navigate', update);
- webContents.on('did-navigate-in-page', update);
- webContents.on('did-redirect-navigation', update);
- webContents.on(
- 'did-fail-load',
- (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
- if (!isMainFrame || errorCode === -3) return;
- page.error = errorDescription;
- page.url = validatedURL || page.url;
- page.isLoading = false;
- this.broadcastState(sessionId);
- },
- );
- webContents.once('destroyed', () => {
- if (page.webContents?.id === webContents.id) {
- page.webContents = undefined;
- page.isLoading = false;
- this.broadcastState(sessionId);
- }
- });
- webContents.on('render-process-gone', (_event, details) => {
- page.error = details.reason;
- page.isLoading = false;
- this.broadcastState(sessionId);
- });
+ private disposePool(): void {
+ this.pagePool?.dispose();
+ this.pagePool = undefined;
+ }
- this.updateSnapshot(sessionId);
+ /** 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 {
@@ -327,73 +296,47 @@ export default class BrowserSidebarCtr extends ControllerModule {
this.partitionConfigured = true;
}
- private ensurePage(sessionId: string): BrowserPageRecord {
- const current = this.pages.get(sessionId);
- if (current) return current;
-
- const page: BrowserPageRecord = {
- isLoading: false,
- sessionId,
- title: '',
- url: DEFAULT_BROWSER_URL,
- };
- this.pages.set(sessionId, page);
- return page;
- }
-
- private getLiveWebContents(sessionId: string): WebContents | undefined {
- const webContents = this.pages.get(sessionId)?.webContents;
- if (!webContents || webContents.isDestroyed()) return undefined;
- return webContents;
- }
-
- /** Guest accessor for sibling controllers (BrowserControlCtr drives it). */
- getSessionWebContents(sessionId: string): WebContents | undefined {
- return this.getLiveWebContents(sessionId);
- }
-
private snapshot(sessionId: string): BrowserSidebarState {
- const page = this.ensurePage(sessionId);
- const webContents = this.getLiveWebContents(sessionId);
+ const page = this.pagePool?.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,
- isLoading: webContents?.isLoading() ?? page.isLoading,
+ error: page?.error,
+ isLoading: webContents?.isLoading() ?? page?.isLoading ?? false,
sessionId,
- title: webContents?.getTitle() || page.title,
- url: webContents?.getURL() || page.url,
+ title: webContents?.getTitle() || page?.title || discarded?.title || '',
+ url: webContents?.getURL() || page?.url || discarded?.url || DEFAULT_BROWSER_URL,
};
}
private updateSnapshot(sessionId: string): void {
- const page = this.ensurePage(sessionId);
- const webContents = this.getLiveWebContents(sessionId);
+ const page = this.pagePool?.get(sessionId);
+ const webContents = this.getSessionWebContents(sessionId);
- if (webContents) {
+ if (page && webContents) {
page.title = webContents.getTitle();
page.url = webContents.getURL() || page.url;
page.isLoading = webContents.isLoading();
- page.error = undefined;
}
- this.broadcastState(sessionId);
- }
-
- private broadcastState(sessionId: string): void {
this.app.browserManager.broadcastToAllWindows(
'browserSidebarStateChanged',
this.snapshot(sessionId),
);
}
- private async withPageWebContents(
+ private async withPage(
sessionId: string,
action: (webContents: WebContents) => BrowserSidebarResult | Promise<BrowserSidebarResult>,
): Promise<BrowserSidebarResult> {
- const webContents = this.getLiveWebContents(sessionId);
+ const webContents = this.getSessionWebContents(sessionId);
if (!webContents) return { error: 'Browser is not ready', success: false };
return action(webContents);
diff --git a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
index 1c53d05f886..f77eb5f5054 100644
--- a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
@@ -1,49 +1,135 @@
import { EventEmitter } from 'node:events';
-import type { WebContents } from 'electron';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
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,
- webContentsFromIdMock,
} = vi.hoisted(() => {
const handlers = new Map<string, (event: unknown, ...args: unknown[]) => unknown>();
- const handle = vi.fn(
- (channel: string, handler: (event: unknown, ...args: unknown[]) => unknown) => {
- handlers.set(channel, handler);
- },
- );
return {
appOnMock: vi.fn(),
clipboardWriteImageMock: vi.fn(),
+ createdViews: [] as unknown[],
+ createdWindows: [] as unknown[],
+ fromWebContentsMock: vi.fn(),
+ getAllWindowsMock: vi.fn(() => [] as unknown[]),
importChromeLoginDataMock: vi.fn(),
ipcHandlers: handlers,
- ipcMainHandleMock: handle,
+ ipcMainHandleMock: vi.fn(
+ (channel: string, handler: (event: unknown, ...args: unknown[]) => unknown) => {
+ handlers.set(channel, handler);
+ },
+ ),
sessionFromPartitionMock: vi.fn(),
shellOpenExternalMock: vi.fn().mockResolvedValue(undefined),
- webContentsFromIdMock: vi.fn(),
};
});
vi.mock('@/utils/logger', () => ({
- createLogger: () => ({
- debug: vi.fn(),
- error: vi.fn(),
- info: vi.fn(),
- warn: vi.fn(),
- }),
+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
}));
vi.mock('@/modules/browser/importChromeLoginData', () => ({
@@ -51,227 +137,492 @@ vi.mock('@/modules/browser/importChromeLoginData', () => ({
}));
vi.mock('electron', () => ({
- app: {
- on: appOnMock,
- },
- clipboard: {
- writeImage: clipboardWriteImageMock,
- },
- ipcMain: {
- handle: ipcMainHandleMock,
- },
- session: {
- fromPartition: sessionFromPartitionMock,
- },
- shell: {
- openExternal: shellOpenExternalMock,
- },
- webContents: {
- fromId: webContentsFromIdMock,
+ 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;
+ }
},
}));
-const createOwnerWebContents = (id = 1): WebContents => {
- const owner = new EventEmitter() as EventEmitter & { id: number };
- owner.id = id;
- return owner as unknown as WebContents;
-};
-
-const createGuestWebContents = (overrides?: Partial<WebContents>): WebContents => {
- const guest = new EventEmitter() as EventEmitter & Partial<WebContents> & { id: number };
- guest.id = 2;
- guest.canGoBack = vi.fn(() => false);
- guest.canGoForward = vi.fn(() => false);
- guest.capturePage = vi.fn(async () => 'image') as unknown as WebContents['capturePage'];
- guest.getTitle = vi.fn(() => 'Example');
- guest.getURL = vi.fn(() => 'https://example.com');
- guest.isDestroyed = vi.fn(() => false);
- guest.isLoading = vi.fn(() => false);
- guest.loadURL = vi.fn(async () => undefined);
- guest.reload = vi.fn();
- guest.setWindowOpenHandler = vi.fn();
- guest.stop = vi.fn();
- Object.assign(guest, overrides);
- return guest as unknown as WebContents;
-};
-
-const invokeIpc = async <T = unknown>(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: { id: 'test' } }, payload) as Promise<T>;
-};
-
describe('BrowserSidebarCtr', () => {
const broadcastToAllWindows = vi.fn();
const mockSession = {
on: vi.fn(),
setPermissionCheckHandler: vi.fn(),
setPermissionRequestHandler: vi.fn(),
- webRequest: {
- onBeforeRequest: vi.fn(),
- },
+ webRequest: { onBeforeRequest: vi.fn() },
};
- const mockApp = {
- browserManager: {
- broadcastToAllWindows,
- },
- } as unknown as App;
+ let mainWindow: FakeWindow;
let controller: BrowserSidebarCtr;
- const emitWillAttach = (owner: WebContents, params: Record<string, unknown>) => {
- const webPreferences = {};
- const event = { preventDefault: vi.fn() };
- owner.emit('will-attach-webview', event, webPreferences, params);
- return { event, webPreferences };
+ /** 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;
};
- const setupOwner = () => {
- controller.beforeAppReady();
- const webContentsCreatedHandler = appOnMock.mock.calls.find(
- ([eventName]) => eventName === 'web-contents-created',
- )?.[1];
- const owner = createOwnerWebContents();
- webContentsCreatedHandler({}, owner);
- return owner;
+ /** 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;
};
- const attachGuest = async (guest: WebContents, sessionId = 'session-1') => {
- // Guest must live in the hardened browser partition to be claimable.
- (guest as unknown as { session: unknown }).session = mockSession;
- webContentsFromIdMock.mockReturnValue(guest);
- return invokeIpc('browserSidebar.attach', { sessionId, webContentsId: guest.id });
+ /** 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 handler = ipcHandlers.get(channel);
+ if (!handler) throw new Error(`IPC handler for ${channel} not found`);
+ return handler({ sender: from.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();
- ipcMainHandleMock.mockClear();
+ createdViews.length = 0;
+ createdWindows.length = 0;
+ seq = 0;
(
IpcHandler.getInstance() as unknown as { registeredChannels?: Set<string> }
).registeredChannels?.clear();
+
sessionFromPartitionMock.mockReturnValue(mockSession);
- controller = new BrowserSidebarCtr(mockApp);
- });
- it('should harden webviews recognized by the browser partition attribute', () => {
- const owner = setupOwner();
+ mainWindow = createWindow();
+ fromWebContentsMock.mockImplementation((sender: unknown) =>
+ mainWindow.sender === sender ? mainWindow : undefined,
+ );
- const params = {
- partition: 'persist:lobe-browser-app',
- src: 'example.com',
- };
- const { webPreferences } = emitWillAttach(owner, params);
+ const app = mockApp();
+ controller = new BrowserSidebarCtr(app);
+ controller.beforeAppReady();
+ // Registers the browserControl.* channels against the same pool.
+
+ new BrowserControlCtr(app);
+ });
- expect(params).toMatchObject({
- partition: 'persist:lobe-browser-app',
- src: 'https://example.com',
+ it('creates a page and loads the URL on navigate, without any renderer round-trip', async () => {
+ const view = queueView();
+ queueParkingWindow();
+
+ const result = await invokeIpc('browserSidebar.navigate', {
+ sessionId: 'agent:a',
+ url: 'https://example.com',
});
- expect(webPreferences).toMatchObject({
- contextIsolation: true,
- nodeIntegration: false,
- partition: 'persist:lobe-browser-app',
- sandbox: true,
+
+ expect(result).toEqual({ success: true });
+ expect(view.webContents.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(sessionFromPartitionMock).toHaveBeenCalledWith('persist:lobe-browser-app');
- expect(mockSession.setPermissionRequestHandler).toHaveBeenCalled();
- expect(mockSession.setPermissionCheckHandler).toHaveBeenCalled();
- expect(mockSession.webRequest.onBeforeRequest).toHaveBeenCalled();
+ 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('should ignore webviews without the browser partition', () => {
- const owner = setupOwner();
+ 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,
+ );
+ 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();
+ });
- const params = { partition: 'persist:other', src: 'https://example.com' };
- const { webPreferences } = emitWillAttach(owner, params);
+ 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(webPreferences).toEqual({});
- expect(sessionFromPartitionMock).not.toHaveBeenCalled();
+ 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('should bind sessions through the attach IPC and broadcast state', async () => {
- setupOwner();
- const guest = createGuestWebContents();
+ 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();
- await expect(attachGuest(guest)).resolves.toEqual({ success: true });
+ 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(guest.setWindowOpenHandler).toHaveBeenCalled();
- expect(broadcastToAllWindows).toHaveBeenCalledWith(
- 'browserSidebarStateChanged',
- expect.objectContaining({
- attached: true,
- sessionId: 'session-1',
- title: 'Example',
- url: 'https://example.com',
- }),
+ 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('should reject attaching webContents outside the browser partition', async () => {
- setupOwner();
- const guest = createGuestWebContents();
- (guest as unknown as { session: unknown }).session = { notOurs: true };
- webContentsFromIdMock.mockReturnValue(guest);
+ 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 expect(
- invokeIpc('browserSidebar.attach', { sessionId: 'session-1', webContentsId: guest.id }),
- ).resolves.toMatchObject({ success: false });
- expect(guest.setWindowOpenHandler).not.toHaveBeenCalled();
+ 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('should keep window.open navigations inside the sidebar page', async () => {
- setupOwner();
- const guest = createGuestWebContents();
- await attachGuest(guest);
+ 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',
+ });
- const windowOpenHandler = vi.mocked(guest.setWindowOpenHandler).mock.calls[0][0];
- const result = windowOpenHandler({ url: 'https://lobehub.com' } as never);
+ expect(view.setBounds).toHaveBeenLastCalledWith({ height: 500, width: 250, x: 125, y: 50 });
+ });
- expect(result).toEqual({ action: 'deny' });
- expect(guest.loadURL).toHaveBeenCalledWith('https://lobehub.com');
- expect(shellOpenExternalMock).not.toHaveBeenCalled();
+ 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('should navigate and capture the attached page through IPC methods', async () => {
- setupOwner();
- const guest = createGuestWebContents();
- await attachGuest(guest);
-
- await expect(
- invokeIpc('browserSidebar.navigate', { sessionId: 'session-1', url: 'lobehub.com' }),
- ).resolves.toEqual({ success: true });
- expect(guest.loadURL).toHaveBeenCalledWith('https://lobehub.com');
-
- await expect(
- invokeIpc('browserSidebar.navigate', { sessionId: 'session-1', url: 'localhost:3000' }),
- ).resolves.toEqual({ success: true });
- expect(guest.loadURL).toHaveBeenCalledWith('http://localhost:3000');
-
- await expect(
- invokeIpc('browserSidebar.captureScreenshotToClipboard', { sessionId: 'session-1' }),
- ).resolves.toEqual({ success: true });
- expect(guest.capturePage).toHaveBeenCalled();
- expect(clipboardWriteImageMock).toHaveBeenCalledWith('image');
+ 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();
});
- it('should import Chrome login information into the browser session', async () => {
- importChromeLoginDataMock.mockResolvedValue(12);
+ 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.
+ 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;
+ };
+
+ it('discards the coldest idle page once the pool is over its cap', async () => {
+ vi.useFakeTimers();
+ queueParkingWindow();
+
+ const views = await navigateN(6);
+ // Age them past the in-use window so they are eligible.
+ vi.advanceTimersByTime(120_000);
- await expect(invokeIpc('browserSidebar.importChromeLoginData')).resolves.toEqual({
- importedCount: 12,
- success: true,
+ queueView();
+ await invokeIpc('browserSidebar.navigate', {
+ sessionId: 'agent:6',
+ url: 'https://site-6.com',
+ });
+
+ // 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 navigateN(6);
+ vi.advanceTimersByTime(120_000);
+
+ queueView();
+ await invokeIpc('browserSidebar.navigate', {
+ sessionId: 'agent:6',
+ url: 'https://site-6.com',
+ });
+ expect(views[0].webContents.close).toHaveBeenCalled();
+
+ // 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();
+ });
+
+ it('never discards a page an agent is still driving, even over the cap', async () => {
+ vi.useFakeTimers();
+ queueParkingWindow();
+ const views = await navigateN(6);
+ vi.advanceTimersByTime(120_000);
+
+ // A tool call on the coldest page counts as use.
+ await invokeIpc('browserControl.snapshot', { sessionId: 'agent:0' });
+
+ queueView();
+ await invokeIpc('browserSidebar.navigate', {
+ sessionId: 'agent:6',
+ url: 'https://site-6.com',
+ });
+
+ // 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();
+ });
+
+ 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: 10 agents open pages at once, so nothing is
+ // evictable (all "in use") β€” and if eviction only ran on create, the pool
+ // would stay at 10 forever. Verified against the live app.
+ vi.useFakeTimers();
+ queueParkingWindow();
+ const views = await navigateN(10);
+
+ // 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(4);
+ // Oldest first: agent:0..3 go, agent:6..9 stay.
+ expect(views[0].webContents.close).toHaveBeenCalled();
+ expect(views[3].webContents.close).toHaveBeenCalled();
+ expect(views[9].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();
+ const views = await navigateN(6);
+ // No time passes: every page is within the in-use window.
+
+ queueView();
+ await invokeIpc('browserSidebar.navigate', {
+ sessionId: 'agent:6',
+ url: 'https://site-6.com',
+ });
+
+ for (const view of views) expect(view.webContents.close).not.toHaveBeenCalled();
+ vi.useRealTimers();
});
- expect(importChromeLoginDataMock).toHaveBeenCalledWith(mockSession);
});
- it('should return a recoverable error when Chrome login import fails', async () => {
- importChromeLoginDataMock.mockRejectedValue(new Error('Chrome profile was not found'));
+ 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');
+ });
- await expect(invokeIpc('browserSidebar.importChromeLoginData')).resolves.toEqual({
- error: 'Chrome profile was not found',
- importedCount: 0,
- success: false,
+ 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('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 });
});
});
diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.ts
index d633d59b3ba..19138d81b22 100644
--- a/apps/desktop/src/main/core/browser/Browser.ts
+++ b/apps/desktop/src/main/core/browser/Browser.ts
@@ -180,7 +180,6 @@ export default class Browser {
contextIsolation: true,
preload: path.join(preloadDir, 'index.js'),
sandbox: false,
- webviewTag: true,
},
width: resolvedState.width,
x: resolvedState.x,
diff --git a/apps/desktop/src/main/modules/browser/BrowserPagePool.ts b/apps/desktop/src/main/modules/browser/BrowserPagePool.ts
new file mode 100644
index 00000000000..c3c1cd533e9
--- /dev/null
+++ b/apps/desktop/src/main/modules/browser/BrowserPagePool.ts
@@ -0,0 +1,427 @@
+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.
+ */
+const MAX_LIVE_PAGES = 6;
+/**
+ * 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;
+ /**
+ * 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, { 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): { 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 = {
+ 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, { 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('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
new file mode 100644
index 00000000000..1fc149832c3
--- /dev/null
+++ b/apps/desktop/src/main/modules/browser/agentOverlayScript.ts
@@ -0,0 +1,131 @@
+/**
+ * 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.
+ *
+ * Being inside the page, it must stay invisible to the agent's own tools:
+ * - it hangs off `documentElement`, not `body`, so `body.innerText` (readPage)
+ * never picks up the chip text;
+ * - its content lives in a shadow root, so the snapshot's `querySelectorAll`
+ * can't walk into it and mint refs for it;
+ * - `screenshot` removes it before capturing, so the model never sees its own
+ * cursor in the frame.
+ */
+
+export interface AgentOverlayLabels {
+ /** Chip text, e.g. "Agent is controlling". */
+ controlling: string;
+ /** Cursor label, e.g. "Agent". */
+ cursor: string;
+}
+
+const OVERLAY_HOST_ID = '__lobe-agent-overlay';
+
+/** Idempotent: creates the overlay if the current document doesn't have one. */
+const ensureOverlay = (labels: AgentOverlayLabels) => `((labels) => {
+ if (window.__lobeAgentOverlay && document.documentElement.contains(window.__lobeAgentOverlay.host)) {
+ window.__lobeAgentOverlay.labels = labels;
+ return;
+ }
+
+ const host = document.createElement('div');
+ host.id = ${JSON.stringify(OVERLAY_HOST_ID)};
+ host.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483647';
+ const root = host.attachShadow({ mode: 'closed' });
+ root.innerHTML = \`
+ <style>
+ .cursor {
+ position: fixed;
+ margin: -4px 0 0 -4px;
+ transition: left .4s cubic-bezier(.3,.9,.4,1), top .4s cubic-bezier(.3,.9,.4,1);
+ opacity: 0;
+ }
+ .cursor.on { opacity: 1 }
+ .cursor svg { display: block; color: #2f54eb; filter: drop-shadow(0 1px 2px rgba(0,0,0,.3)) }
+ .label {
+ position: absolute; top: 18px; left: 13px;
+ padding: 2px 8px; border-radius: 20px;
+ font: 500 12px/18px system-ui, sans-serif; color: #fff; white-space: nowrap;
+ background: #2f54eb; box-shadow: 0 1px 4px rgba(0,0,0,.15);
+ }
+ .ripple {
+ position: absolute; top: -10px; left: -10px;
+ width: 28px; height: 28px; border: 2px solid #2f54eb; border-radius: 50%;
+ opacity: 0;
+ }
+ .ripple.go { animation: r .5s ease-out }
+ @keyframes r { 0% { transform: scale(.4); opacity: 1 } 100% { transform: scale(1.2); opacity: 0 } }
+ .chip {
+ position: fixed; top: 8px; left: 50%; transform: translateX(-50%);
+ display: none; gap: 6px; align-items: center;
+ padding: 4px 10px; border-radius: 16px;
+ font: 12px system-ui, sans-serif; color: #fff;
+ background: rgba(0,0,0,.55); backdrop-filter: blur(4px);
+ }
+ .chip.on { display: flex }
+ .dot { width: 6px; height: 6px; border-radius: 50%; background: #52c41a; animation: p 1.2s ease-in-out infinite }
+ @keyframes p { 50% { opacity: .3 } }
+ </style>
+ <div class="chip"><span class="dot"></span><span class="chip-text"></span></div>
+ <div class="cursor">
+ <div class="ripple"></div>
+ <svg fill="none" height="22" viewBox="0 0 24 24" width="22">
+ <path d="M5 3l14 8-6.5 1.5L9 19 5 3z" stroke="#fff" stroke-linejoin="round" stroke-width="2.2"/>
+ <path d="M5 3l14 8-6.5 1.5L9 19 5 3z" fill="currentColor" stroke="currentColor" stroke-linejoin="round" stroke-width=".8"/>
+ </svg>
+ <div class="label"></div>
+ </div>
+ \`;
+ document.documentElement.append(host);
+
+ const api = {
+ host,
+ labels,
+ chip: root.querySelector('.chip'),
+ chipText: root.querySelector('.chip-text'),
+ cursor: root.querySelector('.cursor'),
+ label: root.querySelector('.label'),
+ ripple: root.querySelector('.ripple'),
+ };
+ window.__lobeAgentOverlay = api;
+})(${JSON.stringify(labels)})`;
+
+export const overlayCursorScript = (
+ labels: AgentOverlayLabels,
+ x: number,
+ y: number,
+ click: boolean,
+) => `${ensureOverlay(labels)};
+((x, y, click) => {
+ const o = window.__lobeAgentOverlay;
+ if (!o) return;
+ o.label.textContent = o.labels.cursor;
+ o.cursor.style.left = x + 'px';
+ o.cursor.style.top = y + 'px';
+ o.cursor.classList.add('on');
+ if (click) {
+ o.ripple.classList.remove('go');
+ void o.ripple.offsetWidth;
+ o.ripple.classList.add('go');
+ }
+})(${x}, ${y}, ${click})`;
+
+export const overlayControllingScript = (
+ labels: AgentOverlayLabels,
+ active: boolean,
+) => `${ensureOverlay(labels)};
+((active) => {
+ const o = window.__lobeAgentOverlay;
+ if (!o) return;
+ o.chipText.textContent = o.labels.controlling;
+ o.chip.classList.toggle('on', active);
+ if (!active) o.cursor.classList.remove('on');
+})(${active})`;
+
+/** Strip the overlay so the agent never captures its own cursor. */
+export const OVERLAY_REMOVE_SCRIPT = `(() => {
+ const host = document.getElementById(${JSON.stringify(OVERLAY_HOST_ID)});
+ if (host) host.remove();
+ delete window.__lobeAgentOverlay;
+})()`;
diff --git a/packages/builtin-tool-browser/src/client/executor/index.ts b/packages/builtin-tool-browser/src/client/executor/index.ts
index b2804b337a6..2afdb8e3468 100644
--- a/packages/builtin-tool-browser/src/client/executor/index.ts
+++ b/packages/builtin-tool-browser/src/client/executor/index.ts
@@ -21,16 +21,15 @@ const BrowserApiEnum = {
snapshot: 'snapshot' as const,
};
-const ATTACH_TIMEOUT_MS = 12_000;
-
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/**
* Browser Tool Executor (client / desktop only)
*
- * Drives the WorkingSidebar in-app browser through the Electron IPC control
- * gateway. The browser session is shared with the UI (`agent:<agentId>`), so
- * the user watches every action live in the sidebar.
+ * Drives the in-app browser through the Electron IPC control gateway. Pages are
+ * owned by the main process and keyed by session (`agent:<agentId>`), so every
+ * agent drives its own page whether or not the user is watching it β€” an agent
+ * running in the background never touches the page in front of the user.
*/
class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
readonly identifier = BrowserIdentifier;
@@ -61,27 +60,11 @@ class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
const sessionId = this.sessionIdOf(ctx);
const { electronBrowserSidebarService } = await import('@/services/electron/browserSidebar');
- const state = await electronBrowserSidebarService.getState({ sessionId });
-
- if (state.attached) {
- await this.revealBrowserTab();
- const result = await electronBrowserSidebarService.navigate({
- sessionId,
- url: params.url,
- });
- if (!result.success) return this.failure(result.error ?? 'Navigation failed');
- } else {
- // No webview yet β€” mount it through the store request, which also opens
- // the right panel and switches to the browser tab.
- const { useGlobalStore } = await import('@/store/global');
- useGlobalStore.getState().openInBrowserTab(params.url);
-
- const attached = await this.waitForAttach(sessionId);
- if (!attached)
- return this.failure(
- 'The in-app browser did not open. Make sure the conversation is visible in the desktop app.',
- );
- }
+ // The main process creates the page on demand, so there is nothing to wait
+ // for and no UI to open first β€” a background agent navigates its own page.
+ await this.revealBrowserTab(ctx);
+ const result = await electronBrowserSidebarService.navigate({ sessionId, url: params.url });
+ if (!result.success) return this.failure(result.error ?? 'Navigation failed');
// Let the page settle before reporting where we landed.
await this.waitForLoad(sessionId);
@@ -121,7 +104,7 @@ class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
try {
const disabled = await this.labDisabledFailure();
if (disabled) return disabled;
- await this.revealBrowserTab();
+ await this.revealBrowserTab(ctx);
const { electronBrowserControlService } = await import('@/services/electron/browserControl');
const result = await electronBrowserControlService.click({
ref: params.ref,
@@ -144,7 +127,7 @@ class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
try {
const disabled = await this.labDisabledFailure();
if (disabled) return disabled;
- await this.revealBrowserTab();
+ await this.revealBrowserTab(ctx);
const { electronBrowserControlService } = await import('@/services/electron/browserControl');
const result = await electronBrowserControlService.fill({
ref: params.ref,
@@ -199,7 +182,7 @@ class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
try {
const disabled = await this.labDisabledFailure();
if (disabled) return disabled;
- await this.revealBrowserTab();
+ await this.revealBrowserTab(ctx);
const { electronBrowserControlService } = await import('@/services/electron/browserControl');
const result = await electronBrowserControlService.screenshot({
sessionId: this.sessionIdOf(ctx),
@@ -242,25 +225,24 @@ class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
return `agent:${ctx.agentId}`;
}
- /** Keep the user in the loop: surface the browser tab whenever the agent acts. */
- private async revealBrowserTab() {
- const { useGlobalStore } = await import('@/store/global');
+ /**
+ * Keep the user in the loop β€” but only for the agent they are actually looking
+ * at. Revealing the panel for a background agent would yank the user's view to
+ * a run they didn't ask about, and (before pages were main-process owned) it
+ * was how a background agent ended up driving the foreground agent's page.
+ */
+ private async revealBrowserTab(ctx?: BuiltinToolContext) {
+ const [{ useAgentStore }, { useGlobalStore }] = await Promise.all([
+ import('@/store/agent'),
+ import('@/store/global'),
+ ]);
+ if (!ctx?.agentId || useAgentStore.getState().activeAgentId !== ctx.agentId) return;
+
const store = useGlobalStore.getState();
store.toggleRightPanel(true);
store.setWorkingSidebarTab('browser');
}
- private async waitForAttach(sessionId: string): Promise<boolean> {
- const { electronBrowserSidebarService } = await import('@/services/electron/browserSidebar');
- const deadline = Date.now() + ATTACH_TIMEOUT_MS;
- while (Date.now() < deadline) {
- const state = await electronBrowserSidebarService.getState({ sessionId });
- if (state.attached) return true;
- await sleep(300);
- }
- return false;
- }
-
private async waitForLoad(sessionId: string, timeoutMs = 8000): Promise<void> {
const { electronBrowserSidebarService } = await import('@/services/electron/browserSidebar');
const deadline = Date.now() + timeoutMs;
diff --git a/packages/electron-client-ipc/src/events/browserSidebar.ts b/packages/electron-client-ipc/src/events/browserSidebar.ts
index 36461413b15..a4c7728027a 100644
--- a/packages/electron-client-ipc/src/events/browserSidebar.ts
+++ b/packages/electron-client-ipc/src/events/browserSidebar.ts
@@ -1,13 +1,7 @@
-import type {
- BrowserGatewayToolCallPayload,
- BrowserSidebarAgentCursorPayload,
- BrowserSidebarAgentStatePayload,
-} from '../types/browserControl';
+import type { BrowserGatewayToolCallPayload } from '../types/browserControl';
import type { BrowserSidebarState } from '../types/browserSidebar';
export interface BrowserSidebarBroadcastEvents {
- browserSidebarAgentCursor: (data: BrowserSidebarAgentCursorPayload) => void;
- browserSidebarAgentState: (data: BrowserSidebarAgentStatePayload) => void;
browserSidebarGatewayToolCall: (data: BrowserGatewayToolCallPayload) => void;
browserSidebarStateChanged: (data: BrowserSidebarState) => void;
}
diff --git a/packages/electron-client-ipc/src/types/browserControl.ts b/packages/electron-client-ipc/src/types/browserControl.ts
index 0f49a79a67e..f715535c722 100644
--- a/packages/electron-client-ipc/src/types/browserControl.ts
+++ b/packages/electron-client-ipc/src/types/browserControl.ts
@@ -85,15 +85,3 @@ export interface BrowserGatewayToolResultParams {
requestId: string;
result: BrowserToolCallResult;
}
-
-export interface BrowserSidebarAgentStatePayload {
- active: boolean;
- sessionId: string;
-}
-
-export interface BrowserSidebarAgentCursorPayload {
- click?: boolean;
- sessionId: string;
- x: number;
- y: number;
-}
diff --git a/packages/electron-client-ipc/src/types/browserSidebar.ts b/packages/electron-client-ipc/src/types/browserSidebar.ts
index 3b5757101c9..fbb997cd106 100644
--- a/packages/electron-client-ipc/src/types/browserSidebar.ts
+++ b/packages/electron-client-ipc/src/types/browserSidebar.ts
@@ -2,14 +2,32 @@ export interface BrowserSidebarSessionParams {
sessionId: string;
}
-export interface BrowserSidebarAttachParams extends BrowserSidebarSessionParams {
- webContentsId: number;
-}
-
export interface BrowserSidebarNavigateParams extends BrowserSidebarSessionParams {
url: string;
}
+/** Panel rect in main-window coordinates (CSS px, as `getBoundingClientRect` reports it). */
+export interface BrowserSidebarRect {
+ height: number;
+ width: number;
+ x: number;
+ 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;
+ cursor: string;
+}
+
export interface BrowserSidebarState {
attached: boolean;
canGoBack: boolean;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/AgentOverlay.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/AgentOverlay.tsx
deleted file mode 100644
index 3f0a3e97a5c..00000000000
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/AgentOverlay.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
-import { Flexbox } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-const styles = createStaticStyles(({ css, cssVar }) => ({
- chip: css`
- pointer-events: none;
-
- position: absolute;
- z-index: 20;
- inset-block-start: 8px;
- inset-inline-start: 50%;
- transform: translateX(-50%);
-
- display: flex;
- gap: 6px;
- align-items: center;
-
- padding-block: 4px;
- padding-inline: 10px;
- border-radius: 16px;
-
- font-size: 12px;
- color: ${cssVar.colorTextLightSolid};
-
- background: ${cssVar.colorBgMask};
- backdrop-filter: blur(4px);
- `,
- cursor: css`
- pointer-events: none;
-
- position: absolute;
- z-index: 20;
-
- margin-block-start: -4px;
- margin-inline-start: -4px;
-
- transition:
- inset-inline-start 0.4s cubic-bezier(0.3, 0.9, 0.4, 1),
- inset-block-start 0.4s cubic-bezier(0.3, 0.9, 0.4, 1);
- `,
- cursorLabel: css`
- position: absolute;
- inset-block-start: 18px;
- inset-inline-start: 13px;
-
- padding-block: 2px;
- padding-inline: 8px;
- border-radius: 20px;
-
- font-size: 12px;
- font-weight: 500;
- line-height: 18px;
- color: #fff;
- white-space: nowrap;
-
- background: ${cssVar.geekblue};
- box-shadow: 0 1px 4px rgb(0 0 0 / 15%);
- `,
- cursorSvg: css`
- display: block;
- color: ${cssVar.geekblue};
- filter: drop-shadow(0 1px 2px rgb(0 0 0 / 30%));
- `,
- dot: css`
- width: 6px;
- height: 6px;
- border-radius: 50%;
-
- background: ${cssVar.colorSuccess};
-
- animation: lobe-browser-agent-pulse 1.2s ease-in-out infinite;
-
- @keyframes lobe-browser-agent-pulse {
- 50% {
- opacity: 0.3;
- }
- }
- `,
- ripple: css`
- position: absolute;
- inset-block-start: -10px;
- inset-inline-start: -10px;
-
- width: 28px;
- height: 28px;
- border: 2px solid ${cssVar.geekblue};
- border-radius: 50%;
-
- opacity: 0;
-
- animation: lobe-browser-agent-ripple 0.5s ease-out 0.45s;
-
- @keyframes lobe-browser-agent-ripple {
- 0% {
- transform: scale(0.4);
- opacity: 1;
- }
-
- 100% {
- transform: scale(1.2);
- opacity: 0;
- }
- }
- `,
-}));
-
-interface AgentOverlayProps {
- sessionId: string;
-}
-
-/**
- * Draws the agent-control affordances above the webview: a floating cursor
- * that glides to each click target (broadcast by BrowserControlCtr before the
- * real input event lands) and a "controlling" status chip.
- */
-const AgentOverlay = memo<AgentOverlayProps>(({ sessionId }) => {
- const { t } = useTranslation('chat');
- const [controlling, setControlling] = useState(false);
- const [cursor, setCursor] = useState<{ visible: boolean; x: number; y: number }>({
- visible: false,
- x: 0,
- y: 0,
- });
- // Remount the ripple animation per click.
- const [clickSeq, setClickSeq] = useState(0);
-
- useWatchBroadcast('browserSidebarAgentState', (data) => {
- if (data.sessionId !== sessionId) return;
- setControlling(data.active);
- if (!data.active) setCursor((prev) => ({ ...prev, visible: false }));
- });
-
- useWatchBroadcast('browserSidebarAgentCursor', (data) => {
- if (data.sessionId !== sessionId) return;
- setCursor({ visible: true, x: data.x, y: data.y });
- if (data.click) setClickSeq((n) => n + 1);
- });
-
- return (
- <>
- {controlling && (
- <Flexbox horizontal className={styles.chip}>
- <span className={styles.dot} />
- {t('workingPanel.browser.agentControlling')}
- </Flexbox>
- )}
- {cursor.visible && (
- <div
- className={styles.cursor}
- style={{ insetBlockStart: cursor.y, insetInlineStart: cursor.x }}
- >
- {clickSeq > 0 && <div className={styles.ripple} key={clickSeq} />}
- <svg className={styles.cursorSvg} fill="none" height={22} viewBox="0 0 24 24" width={22}>
- {/* White halo underneath the body. */}
- <path
- d="M5 3l14 8-6.5 1.5L9 19 5 3z"
- stroke="#fff"
- strokeLinejoin="round"
- strokeWidth={2.2}
- />
- {/* A same-color round-joined stroke softens the arrow's sharp
- vertices with a ~0.4 corner radius (radius = width / 2). */}
- <path
- d="M5 3l14 8-6.5 1.5L9 19 5 3z"
- fill="currentColor"
- stroke="currentColor"
- strokeLinejoin="round"
- strokeWidth={0.8}
- />
- </svg>
- <div className={styles.cursorLabel}>{t('workingPanel.browser.agentCursor')}</div>
- </div>
- )}
- </>
- );
-});
-
-AgentOverlay.displayName = 'AgentOverlay';
-
-export default AgentOverlay;
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/const.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/const.ts
index 8c4f14b14d8..517a0da1681 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/const.ts
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/const.ts
@@ -1,10 +1,3 @@
-export const BROWSER_WEBVIEW_SESSION_ATTRIBUTE = 'data-lobe-browser-session-id';
export const BROWSER_IMPORT_BANNER_DISMISSED_STORAGE_KEY =
'lobechat:desktop:browser-import-banner:dismissed:v1';
-/**
- * Must stay in sync with BROWSER_PARTITION in the main-process
- * BrowserSidebarCtr β€” the partition attribute is how `will-attach-webview`
- * recognizes (and hardens) browser sidebar webviews.
- */
-export const BROWSER_WEBVIEW_PARTITION = 'persist:lobe-browser-app';
export const DEFAULT_BROWSER_URL = 'https://www.bing.com';
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 74d769dfcdf..7df6e554919 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
@@ -29,24 +29,19 @@ import { useChatStore } from '@/store/chat';
import { useFileStore } from '@/store/file';
import { useGlobalStore } from '@/store/global';
-import AgentOverlay from './AgentOverlay';
-import {
- BROWSER_IMPORT_BANNER_DISMISSED_STORAGE_KEY,
- BROWSER_WEBVIEW_PARTITION,
- BROWSER_WEBVIEW_SESSION_ATTRIBUTE,
-} from './const';
+import { BROWSER_IMPORT_BANNER_DISMISSED_STORAGE_KEY } from './const';
import { useBrowserSidebarState } from './useBrowserSidebarState';
import { createBrowserContext, normalizeBrowserUrl } from './utils';
-type WebviewElement = HTMLElement & { getWebContentsId: () => number };
-
const styles = createStaticStyles(({ css, cssVar }) => ({
loadingBar: css`
pointer-events: none;
position: absolute;
z-index: 3;
- inset-block-start: 0;
+ /* Anchored to the toolbar's bottom border β€” the page container below is
+ covered by the WebContentsView, which paints above renderer DOM. */
+ inset-block-end: -1px;
inset-inline: 0;
overflow: hidden;
@@ -144,13 +139,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
toolbarActions: css`
margin-inline-start: auto;
`,
- webview: css`
+ /* The page itself is a main-process WebContentsView laid over this element β€”
+ nothing renders inside it. It exists to be measured. */
+ viewport: css`
position: absolute;
inset: 0;
-
- width: 100%;
- height: 100%;
- border: 0;
`,
}));
@@ -160,15 +153,7 @@ interface BrowserPaneProps {
const BrowserPane = memo<BrowserPaneProps>(({ sessionId }) => {
const { t } = useTranslation('chat');
- // The webview always mounts on a constant about:blank; the real first
- // navigation is issued through the controller IPC once the guest is attached,
- // so user-typed text never reaches the src attribute (a DOM-XSS sink). Later
- // navigations go through the same IPC so the guest page doesn't remount.
- // `initialUrl === undefined` renders the empty state instead of a webview;
- // its value only seeds the address bar until the first state broadcast.
- const [initialUrl, setInitialUrl] = useState<string>();
- const pendingUrl = useRef<string>(undefined);
- const state = useBrowserSidebarState(sessionId, initialUrl);
+ const state = useBrowserSidebarState(sessionId);
const [address, setAddress] = useState('');
const [isEditing, setIsEditing] = useState(false);
const [isImporting, setIsImporting] = useState(false);
@@ -178,42 +163,76 @@ const BrowserPane = memo<BrowserPaneProps>(({ sessionId }) => {
);
const browserRequest = useGlobalStore((s) => s.status.workingSidebarBrowserRequest);
const consumedNonce = useRef<number>(undefined);
- const webviewRef = useRef<WebviewElement>(null);
+ const viewportRef = useRef<HTMLDivElement>(null);
- // will-attach-webview only sees standard attributes, so the main process
- // can't learn the sessionId there β€” bind it explicitly once the guest exists.
- // The pending first navigation rides on a successful attach.
+ // 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');
+
+ // 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.
+ useEffect(() => {
+ if (!isDesktop) return;
+ void electronBrowserSidebarService.setOverlayLabels({
+ controlling: t('workingPanel.browser.agentControlling'),
+ cursor: t('workingPanel.browser.agentCursor'),
+ });
+ }, [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.
useEffect(() => {
- const el = webviewRef.current;
- if (!el) return;
-
- const handleDomReady = () => {
- const webContentsId = el.getWebContentsId();
- electronBrowserSidebarService
- .attach({ sessionId, webContentsId })
- .then((result) => {
- if (!result.success) return;
- const pending = pendingUrl.current;
- pendingUrl.current = undefined;
- if (pending) return electronBrowserSidebarService.navigate({ sessionId, url: pending });
- })
- .catch((error) => {
- console.error('[BrowserSidebar] Failed to attach webview:', error);
- });
+ if (!isDesktop || !hasPage) return;
+
+ let frame = 0;
+ let lastKey = '';
+
+ const tick = () => {
+ const element = viewportRef.current;
+ if (element) {
+ const rect = 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);
};
- el.addEventListener('dom-ready', handleDomReady);
- return () => el.removeEventListener('dom-ready', handleDomReady);
- }, [initialUrl, sessionId]);
+ frame = requestAnimationFrame(tick);
- // The pane is keyed by session, so switching agents back remounts it with
- // empty local state while the main process still holds the session's page.
- // Bring the webview back on the recorded URL instead of an empty pane.
- useEffect(() => {
- if (initialUrl || !state.url || state.url === 'about:blank') return;
- pendingUrl.current = state.url;
- setInitialUrl(state.url);
- }, [initialUrl, state.url]);
+ // 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.
+
+ return () => {
+ cancelAnimationFrame(frame);
+ // Park rather than close: the agent may still be driving this page.
+ void electronBrowserSidebarService.setViewport({ sessionId });
+ };
+ }, [hasPage, sessionId]);
useEffect(() => {
if (!isEditing) setAddress(state.url === 'about:blank' ? '' : state.url);
@@ -234,13 +253,6 @@ const BrowserPane = memo<BrowserPaneProps>(({ sessionId }) => {
const openUrl = (rawUrl: string) => {
const url = normalizeBrowserUrl(rawUrl);
setAddress(url);
-
- if (!initialUrl) {
- pendingUrl.current = url;
- setInitialUrl(url);
- return;
- }
-
void runAction(() => electronBrowserSidebarService.navigate({ sessionId, url }));
};
@@ -430,6 +442,17 @@ const BrowserPane = memo<BrowserPaneProps>(({ sessionId }) => {
}
/>
</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. */}
+ {state.isLoading && (
+ <div
+ aria-label={t('workingPanel.browser.loading')}
+ aria-valuetext={t('workingPanel.browser.loading')}
+ className={styles.loadingBar}
+ role="progressbar"
+ />
+ )}
</Flexbox>
{!isImportBannerDismissed && (
<Flexbox horizontal align={'center'} className={styles.importBanner} gap={12}>
@@ -458,24 +481,8 @@ const BrowserPane = memo<BrowserPaneProps>(({ sessionId }) => {
</Flexbox>
)}
<Flexbox className={styles.container}>
- {state.isLoading && (
- <div
- aria-label={t('workingPanel.browser.loading')}
- aria-valuetext={t('workingPanel.browser.loading')}
- className={styles.loadingBar}
- role="progressbar"
- />
- )}
- <AgentOverlay sessionId={sessionId} />
- {initialUrl ? (
- <webview
- className={styles.webview}
- key={sessionId}
- partition={BROWSER_WEBVIEW_PARTITION}
- ref={webviewRef}
- src={'about:blank'}
- {...{ [BROWSER_WEBVIEW_SESSION_ATTRIBUTE]: sessionId }}
- />
+ {hasPage ? (
+ <div className={styles.viewport} ref={viewportRef} />
) : (
<Center height={'100%'} width={'100%'}>
<Empty
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index 5b19a46e263..2ae5d731d45 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -91,18 +91,24 @@ const TWO_PANE_MIN_WIDTH = 560;
const AgentWorkingSidebar = memo(() => {
const { t } = useTranslation(['chat', 'setting']);
- const [storedWidth, updateSystemStatus, toggleRightPanel, setWorkingSidebarTab, showRightPanel, storedTab] =
- useGlobalStore((s) => [
- systemStatusSelectors.workingSidebarWidth(s),
- s.updateSystemStatus,
- s.toggleRightPanel,
- s.setWorkingSidebarTab,
- // Panel open/collapsed state (drives the `<RightPanel>` expand). Used to gate
- // the resources pane's document fetch so a collapsed sidebar doesn't pull the
- // full agent-document list into the conversation's initial batch.
- s.status.showRightPanel,
- s.status.workingSidebarTab,
- ]);
+ const [
+ storedWidth,
+ updateSystemStatus,
+ toggleRightPanel,
+ setWorkingSidebarTab,
+ showRightPanel,
+ storedTab,
+ ] = useGlobalStore((s) => [
+ systemStatusSelectors.workingSidebarWidth(s),
+ s.updateSystemStatus,
+ s.toggleRightPanel,
+ s.setWorkingSidebarTab,
+ // Panel open/collapsed state (drives the `<RightPanel>` expand). Used to gate
+ // the resources pane's document fetch so a collapsed sidebar doesn't pull the
+ // full agent-document list into the conversation's initial batch.
+ s.status.showRightPanel,
+ s.status.workingSidebarTab,
+ ]);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const topicId = useChatStore((s) => s.activeTopicId);
const isLocalSystemEnabled = useAgentStore((s) =>
@@ -152,7 +158,7 @@ const AgentWorkingSidebar = memo(() => {
const reviewAvailable =
(isLocalSystemEnabled || isDeviceMode) && !!workingDirectory && !!repoType;
const paramsAvailable = !isHetero;
- // The in-app browser rides on the Electron <webview> tag β€” desktop only,
+ // The in-app browser pages are main-process WebContentsViews β€” 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/advanced/index.tsx b/src/routes/(main)/settings/advanced/index.tsx
index df4598fd428..ecefc5d679c 100644
--- a/src/routes/(main)/settings/advanced/index.tsx
+++ b/src/routes/(main)/settings/advanced/index.tsx
@@ -290,7 +290,7 @@ const Page = memo(() => {
} satisfies FormItemProps,
]
: []),
- // The in-app browser rides on the Electron <webview> tag β€” desktop only.
+ // The in-app browser pages are main-process WebContentsViews β€” desktop only.
...(isDesktop
? [
{
diff --git a/src/services/electron/browserSidebar.ts b/src/services/electron/browserSidebar.ts
index 66b9d8a42e6..1af93322b99 100644
--- a/src/services/electron/browserSidebar.ts
+++ b/src/services/electron/browserSidebar.ts
@@ -1,10 +1,11 @@
import type {
- BrowserSidebarAttachParams,
BrowserSidebarImportResult,
BrowserSidebarNavigateParams,
+ BrowserSidebarOverlayLabelsParams,
BrowserSidebarResult,
BrowserSidebarSessionParams,
BrowserSidebarState,
+ BrowserSidebarViewportParams,
} from '@lobechat/electron-client-ipc';
import { ensureElectronIpc } from '@/utils/electron/ipc';
@@ -14,10 +15,6 @@ class ElectronBrowserSidebarService {
return ensureElectronIpc();
}
- attach(params: BrowserSidebarAttachParams): Promise<BrowserSidebarResult> {
- return this.ipc.browserSidebar.attach(params);
- }
-
captureScreenshotToClipboard(params: BrowserSidebarSessionParams): Promise<BrowserSidebarResult> {
return this.ipc.browserSidebar.captureScreenshotToClipboard(params);
}
@@ -50,6 +47,14 @@ class ElectronBrowserSidebarService {
return this.ipc.browserSidebar.reload(params);
}
+ setOverlayLabels(params: BrowserSidebarOverlayLabelsParams): Promise<BrowserSidebarResult> {
+ 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/types/global.d.ts b/src/types/global.d.ts
index a4baab3d323..22864f28476 100644
--- a/src/types/global.d.ts
+++ b/src/types/global.d.ts
@@ -58,20 +58,4 @@ declare global {
/** Vite define: desktop app version injected by electron-vite renderer build */
const __MAIN_VERSION__: string;
-
- namespace React {
- namespace JSX {
- interface IntrinsicElements {
- /** Electron `<webview>` tag β€” desktop-only, hosts the in-app browser sidebar */
- webview: React.DetailedHTMLProps<
- React.HTMLAttributes<HTMLElement> & {
- allowpopups?: string;
- partition?: string;
- src?: string;
- },
- HTMLElement
- >;
- }
- }
- }
}