Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(browser): keep session pages available in the background
vastsac3e0bbdad717
diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex df2216395..0b5044e88 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -532,7 +532,7 @@ export async function createWindow({});let windowCloseAccepted = false;window.webContents.on("did-start-loading", () => {- browserHost.disposeGuest();+ browserHost.detachPresentation();windowState.notificationViewingSessionId = null;if (windowState.mainWindow === window) resetMenuRendererReady(window);});diff --git a/apps/desktop/electron/main/browser-backing-host.ts b/apps/desktop/electron/main/browser-backing-host.tsnew file mode 100644index 000000000..e482928cc--- /dev/null+++ b/apps/desktop/electron/main/browser-backing-host.ts@@ -0,0 +1,45 @@+import { BrowserWindow, type View } from "electron";++/** Keep background guests connected to Chromium without presenting a window. */+export class BrowserBackingHost {+ private window: BrowserWindow | null = null;+ private readonly surfaces = new Set<View>();++ attach(surface: View, size: { width: number; height: number }): BrowserWindow {+ let window = this.window;+ if (!window || window.isDestroyed()) {+ window = new BrowserWindow({+ show: false,+ skipTaskbar: true,+ width: Math.max(1024, size.width),+ height: Math.max(768, size.height),+ webPreferences: {+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ backgroundThrottling: false,+ },+ });+ this.window = window;+ }+ const [width, height] = window.getContentSize();+ if (width < size.width || height < size.height) {+ window.setContentSize(Math.max(width, size.width), Math.max(height, size.height));+ }+ if (!window.contentView.children.includes(surface)) window.contentView.addChildView(surface);+ this.surfaces.add(surface);+ return window;+ }++ detach(surface: View): void {+ const window = this.window;+ if (window && !window.isDestroyed() && window.contentView.children.includes(surface)) {+ window.contentView.removeChildView(surface);+ }+ this.surfaces.delete(surface);+ if (this.surfaces.size === 0) {+ this.window = null;+ if (window && !window.isDestroyed()) window.destroy();+ }+ }+}diff --git a/apps/desktop/electron/main/browser-cdp.ts b/apps/desktop/electron/main/browser-cdp.tsindex 267f7d827..7c9f8c9b7 100644--- a/apps/desktop/electron/main/browser-cdp.ts+++ b/apps/desktop/electron/main/browser-cdp.ts@@ -177,6 +177,10 @@ export class BrowserCdp {await wc.debugger.sendCommand("Page.enable");await wc.debugger.sendCommand("DOM.enable");await wc.debugger.sendCommand("Accessibility.enable");+ // Chromium ignores input on detached guests unless it emulates focus.+ // This does not focus or attach a native window, so background tools can+ // interact with their own page without disturbing the visible session.+ await wc.debugger.sendCommand("Emulation.setFocusEmulationEnabled", { enabled: true });}detach(wc?: WebContents): void {@@ -258,21 +262,47 @@ export class BrowserCdp {async click(wc: WebContents, uid: string): Promise<void> {const backendNodeId = this.requireUid(uid);await this.attach(wc);- await wc.debugger.sendCommand("DOM.scrollIntoViewIfNeeded", { backendNodeId });- const model = (await wc.debugger.sendCommand("DOM.getBoxModel", { backendNodeId })) as {- model?: { content?: number[] };+ await wc.debugger.sendCommand("Emulation.setFocusEmulationEnabled", { enabled: false });+ await wc.debugger.sendCommand("Emulation.setFocusEmulationEnabled", { enabled: true });+ const resolved = (await wc.debugger.sendCommand("DOM.resolveNode", { backendNodeId })) as {+ object?: { objectId?: string };};- const quad = model.model?.content;- if (!Array.isArray(quad) || quad.length < 8) {- throw Object.assign(new Error(`no box model for ${uid}`), { code: "NOT_FOUND" });+ const objectId = resolved.object?.objectId;+ if (!objectId) throw Object.assign(new Error(`could not resolve ${uid}`), { code: "NOT_FOUND" });+ // CDP box quads can include the detached native view's offscreen offset.+ // Resolve the actual element in its page viewport, then use trusted input.+ const evaluated = (await wc.debugger.sendCommand("Runtime.callFunctionOn", {+ objectId,+ functionDeclaration: `function () {+ const view = this.ownerDocument.defaultView;+ let rect = this.getBoundingClientRect();+ if (rect.left < 0 || rect.top < 0 || rect.right > view.innerWidth || rect.bottom > view.innerHeight) {+ this.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });+ }+ return new Promise(resolve => view.requestAnimationFrame(() => view.requestAnimationFrame(() => {+ rect = this.getBoundingClientRect();+ const left = Math.max(0, rect.left), right = Math.min(view.innerWidth, rect.right);+ const top = Math.max(0, rect.top), bottom = Math.min(view.innerHeight, rect.bottom);+ resolve(right > left && bottom > top ? { x: (left + right) / 2, y: (top + bottom) / 2 } : null);+ })));+ }`,+ awaitPromise: true,+ returnByValue: true,+ })) as { result?: { value?: { x?: number; y?: number } | null } };+ const point = evaluated.result?.value;+ if (typeof point?.x !== "number" || typeof point.y !== "number" || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {+ throw Object.assign(new Error(`no visible box for ${uid}`), { code: "NOT_FOUND" });}- const x = (quad[0] + quad[2] + quad[4] + quad[6]) / 4;- const y = (quad[1] + quad[3] + quad[5] + quad[7]) / 4;+ const { x, y } = point;+ await wc.debugger.sendCommand("Input.dispatchMouseEvent", {+ type: "mouseMoved", x, y, button: "none", buttons: 0,+ });await wc.debugger.sendCommand("Input.dispatchMouseEvent", {type: "mousePressed",x,y,button: "left",+ buttons: 1,clickCount: 1,});await wc.debugger.sendCommand("Input.dispatchMouseEvent", {@@ -281,6 +311,7 @@ export class BrowserCdp {y,button: "left",clickCount: 1,+ buttons: 0,});}@@ -297,7 +328,7 @@ export class BrowserCdp {await wc.debugger.sendCommand("Runtime.callFunctionOn", {objectId,functionDeclaration: `function (value) {- this.focus();+ this.focus({ preventScroll: true });if ("value" in this) {this.value = value;this.dispatchEvent(new Event("input", { bubbles: true }));diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.tsindex c00ae2cb0..5f4576c7d 100644--- a/apps/desktop/electron/main/browser-host.ts+++ b/apps/desktop/electron/main/browser-host.ts@@ -4,11 +4,13 @@ import type { BrowserPane } from "./browser-view";import { BrowserCdp } from "./browser-cdp";import { writeFileSync, mkdirSync } from "node:fs";import { join } from "node:path";+import { randomUUID } from "node:crypto";export const BROWSER_PLUGIN_ID = "pi.browser";export const BROWSER_VIEW_ID = "browser";const BROWSER_REVEAL_TIMEOUT_MS = 5_000;const BROWSER_CDP_TIMEOUT_MS = 30_000;+const DEFAULT_BROWSER_TAB_ID = "plugin:pi.browser/browser";export type BrowserRect = {x: number;@@ -63,7 +65,8 @@ export type BrowserHostDeps = {getFileRoots: (sessionId?: string) => Promise<readonly string[]>;getScratchDir?: (sessionId?: string) => string | null;onState: (state: BrowserState) => void;- onRevealView?: (sessionId: string, tabId?: string) => void;+ onPresentationState?: (state: BrowserState) => void;+ onRevealView?: (sessionId: string, tabId?: string, location?: BrowserNavigateInput) => void;};type ChromeSurface = {@@ -141,8 +144,7 @@ export class BrowserHost {private readonly pages = new Map<string, BrowserPage>();private readonly locations = new Map<string, string>();private readonly selectedTabs = new Map<string, string | null>();- private readonly pendingSessions = new Map<string, string>();- private readonly pendingTabs = new Set<string>();+ private readonly connectedTabs = new Map<string, string | null>();private readonly revealWaiters = new Set<BrowserRevealWaiter>();private active: BrowserPage | null = null;private window: BrowserWindow | null = null;@@ -274,8 +276,8 @@ export class BrowserHost {(state) => {if (this.pages.get(key) !== page) return;page.state = state;- if (state.url && !page.navigating && !this.pendingTabs.has(key)) this.locations.set(key, state.url);- if (this.active === page) this.publishCurrent();+ if (state.url && !page.navigating) this.locations.set(key, state.url);+ this.publishPage(page);},(url) => {if (this.pages.get(key) === page) this.deps.onOpenUrl?.(url, sessionId || undefined);@@ -287,12 +289,20 @@ export class BrowserHost {return page;}+ private publishPage(page: BrowserPage): void {+ const state = this.stateFor(page);+ if (!state) return;+ this.deps.onState(state);+ if (this.active === page) this.deps.onPresentationState?.(state);+ }+private publishCurrent(): void {- const state = this.getState();- this.deps.onState(state ?? {+ const state = this.getState() ?? {url: "", title: "", isLoading: false, canGoBack: false, canGoForward: false,...this.getContext(),- });+ };+ this.deps.onState(state);+ this.deps.onPresentationState?.(state);}setChromeSession(sessionId: string | undefined, tabId?: string, location?: string): boolean {@@ -304,14 +314,8 @@ export class BrowserHost {this.active?.pane.setVisible(false);this.active = page;this.selectedTabs.set(id, tab);- const pending = this.pendingSessions.get(id);- if (pending) {- this.locations.set(page.key, pending);- this.pendingTabs.add(page.key);- this.pendingSessions.delete(id);- }const target = this.locations.get(page.key) ?? location?.trim();- const navigate = this.pendingTabs.delete(page.key) || (!page.started && !page.navigating);+ const navigate = !page.started && !page.navigating;if (target && navigate) {page.started = false;page.state = null;@@ -342,72 +346,61 @@ export class BrowserHost {}}- rememberLocation(sessionId: string | undefined, location: string): void {- const id = sessionId?.trim();- const target = location.trim();- if (!id || !target) return;- const tabId = this.selectedTabs.get(id);- if (tabId != null) {- const key = this.key(id, tabId);- this.locations.set(key, target);- if (this.active?.key !== key) this.pendingTabs.add(key);- } else {- this.pendingSessions.set(id, target);- }+ /** A new preview has its own page even before the renderer mounts its tab. */+ async openTab(input: BrowserNavigateInput, sessionId: string): Promise<{ tabId: string; state: BrowserState | null }> {+ this.assertPluginAvailable();+ const id = sessionId.trim();+ if (!id) throw this.unavailableError("Browser navigation requires a session.");+ const tabId = `plugin:pi.browser/browser:${randomUUID()}`;+ const page = this.pageFor(id, tabId);+ this.selectedTabs.set(id, tabId);+ this.connectedTabs.set(id, tabId);+ const navigation = this.navigatePage(page, String(input.path ?? input.url ?? "").trim());+ this.deps.onRevealView?.(id, tabId, input);+ return { tabId, state: await navigation };}async navigate(input: BrowserNavigateInput, sessionId?: string, tabId?: string): Promise<BrowserState | null> {- this.assertBrowserViewVisible();+ this.assertPluginAvailable();const target = String(input.path ?? input.url ?? "").trim();- if (!target) return this.getState();- const id = sessionId?.trim() || this.active?.sessionId || "";- if (tabId !== undefined) {- const page = this.pages.get(this.key(id, tabId));- return page ? this.navigatePage(page, target, true) : null;- }- if (!this.active) {- this.active = this.pageFor(id, this.selectedTabs.get(id) ?? null);- this.selectedTabs.set(id, this.active.tabId);- }- if (id !== this.active.sessionId) {- this.rememberLocation(id, target);- return null;+ let page: BrowserPage;+ if (sessionId !== undefined) {+ const id = sessionId.trim();+ if (!id) throw this.unavailableError("Browser navigation requires a session.");+ const selected = tabId ?? this.connectedTabs.get(id) ?? this.selectedTabs.get(id) ?? DEFAULT_BROWSER_TAB_ID;+ const key = this.key(id, selected);+ const existing = this.pages.get(key);+ if (tabId !== undefined && !existing) throw this.unavailableError("The Browser tab is closed.");+ page = existing ?? this.pageFor(id, selected);+ if (tabId === undefined) this.connectedTabs.set(id, selected);+ if (!existing) this.selectedTabs.set(id, selected);+ const navigation = target ? this.navigatePage(page, target) : Promise.resolve(this.stateFor(page));+ if (!existing) this.deps.onRevealView?.(id, selected);+ return navigation;}- return this.navigatePage(this.active, target, true);+ page = this.operationPage();+ return target ? this.navigatePage(page, target) : this.stateFor(page);}- private async navigatePage(page: BrowserPage, target: string, requireVisible = false): Promise<BrowserState | null> {+ private async navigatePage(page: BrowserPage, target: string): Promise<BrowserState | null> {const version = ++page.navigationVersion;- const previousLocation = this.locations.get(page.key);page.navigating = true;this.locations.set(page.key, target);const current = () => this.pages.get(page.key) === page && page.navigationVersion === version;- const assertVisible = () => {- if (!requireVisible) return;- try {- this.assertBrowserViewVisible();- } catch (error) {- page.navigating = false;- if (previousLocation === undefined) this.locations.delete(page.key);- else this.locations.set(page.key, previousLocation);- throw error;- }- };let roots: readonly string[];try {roots = await this.getFileRoots(page.sessionId || undefined);} catch (error) {if (!current()) return null;- assertVisible();page.navigating = false;page.started = false;page.state = { url: target, title: "", isLoading: false, canGoBack: false,canGoForward: false, loadError: error instanceof Error ? error.message : String(error) };- if (this.active === page) { this.publishCurrent(); this.applyGuest(); }+ this.publishPage(page);+ if (this.active === page) this.applyGuest();return null;}if (!current()) return null;- assertVisible();let state: BrowserState | null;try {state = await page.pane.navigateAndWait(target, roots[0] ?? null);@@ -417,65 +410,99 @@ export class BrowserHost {page.started = false;page.state = { url: target, title: "", isLoading: false, canGoBack: false,canGoForward: false, loadError: error instanceof Error ? error.message : String(error) };- if (this.active === page) { this.publishCurrent(); this.applyGuest(); }+ this.publishPage(page);+ if (this.active === page) this.applyGuest();return null;}if (!current()) return null;page.navigating = false;page.started = state !== null;page.state = state ?? page.pane.getState();- if (!this.pendingTabs.has(page.key)) this.locations.set(page.key, state?.url || target);+ this.locations.set(page.key, state?.url || target);if (!state && !page.state?.loadError) {page.state = { url: target, title: "", isLoading: false,canGoBack: false, canGoForward: false, loadError: "INVALID_URL" };}- if (this.active === page) { this.publishCurrent(); this.applyGuest(); }+ this.publishPage(page);+ if (this.active === page) this.applyGuest();return state ? { ...state, ...this.contextFor(page) } : null;}- action(action: "back" | "forward" | "reload" | "stop", sessionId?: string, tabId?: string): void {+ private assertPluginAvailable(): void {+ if (!this.deps.isPluginLoaded(BROWSER_PLUGIN_ID)) {+ throw this.unavailableError("The Browser plugin is unavailable.");+ }+ }++ /** Trusted tool session identity never falls back to the visible page. */+ private operationPage(sessionId?: string, tabId?: string): BrowserPage {+ this.assertPluginAvailable();+ if (sessionId !== undefined) {+ const id = sessionId.trim();+ const tab = tabId ?? this.connectedTabs.get(id) ?? this.selectedTabs.get(id);+ const page = id && tab !== undefined ? this.pages.get(this.key(id, tab)) : undefined;+ if (!page) throw this.unavailableError("No Browser page is connected to this session. Navigate or open a preview first.");+ if (tabId === undefined) this.connectedTabs.set(id, page.tabId);+ return page;+ }+ // Unscoped plugin/UI calls retain their existing visible-page boundary.this.assertBrowserViewVisible();- const page = sessionId !== undefined && tabId !== undefined- ? this.pages.get(this.key(sessionId, tabId)) : this.active;- if (page?.state) page.pane.action(action);+ if (!this.active) throw this.unavailableError("browser guest is not available");+ return this.active;+ }++ private stateFor(page: BrowserPage): BrowserState | null {+ return page.state ? { ...page.state, ...this.contextFor(page) } : null;+ }++ action(action: "back" | "forward" | "reload" | "stop", sessionId?: string, tabId?: string): void {+ const page = this.operationPage(sessionId, tabId);+ if (page.state) page.pane.action(action);}getState(): BrowserState | null {- return this.active?.state ? { ...this.active.state, ...this.getContext() } : null;+ return this.active ? this.stateFor(this.active) : null;}- getStateForPlugin(): BrowserState | null {- this.assertBrowserViewVisible();- return this.getState();+ getStateForPlugin(sessionId?: string, tabId?: string): BrowserState | null {+ return this.stateFor(this.operationPage(sessionId, tabId));+ }++ /** Rehydrate side-panel tabs after a renderer reload; DOM stays in Main. */+ getPages(sessionId: string): BrowserState[] {+ if (!this.deps.isPluginLoaded(BROWSER_PLUGIN_ID)) return [];+ return [...this.pages.values()].filter((page) => page.sessionId === sessionId && page.tabId !== null)+ .map((page) => this.stateFor(page) ?? {+ url: "", title: "", isLoading: page.navigating, canGoBack: false, canGoForward: false,+ ...this.contextFor(page),+ });}openExternal(sessionId?: string, tabId?: string): void {- this.assertBrowserViewVisible();- const page = sessionId !== undefined && tabId !== undefined- ? this.pages.get(this.key(sessionId, tabId)) : this.active;- if (page?.started) page.pane.openExternal();+ const page = this.operationPage(sessionId, tabId);+ if (page.started) page.pane.openExternal();}- private currentPage(): BrowserPage {- this.assertBrowserViewVisible();- if (!this.active?.started) throw Object.assign(new Error("browser guest is not available"), { code: "UNAVAILABLE" });- return this.active;+ private currentPage(sessionId?: string, tabId?: string): BrowserPage {+ const page = this.operationPage(sessionId, tabId);+ if (!page.started) throw this.unavailableError("browser guest is not available");+ return page;}- private requireWebContents() {- const wc = this.currentPage().pane.getWebContents();- if (!wc || wc.isDestroyed()) throw Object.assign(new Error("browser guest is not available"), { code: "UNAVAILABLE" });+ private requireWebContents(page: BrowserPage): WebContents {+ const wc = page.pane.getWebContents();+ if (!wc || wc.isDestroyed()) throw this.unavailableError("browser guest is not available");return wc;}- async snapshot(): Promise<{ tree: string; url: string; title: string }> {- const page = this.currentPage();- const wc = this.requireWebContents();+ async snapshot(sessionId?: string, tabId?: string): Promise<{ tree: string; url: string; title: string }> {+ const page = this.currentPage(sessionId, tabId);+ const wc = this.requireWebContents(page);return withCdpDeadline(page, wc, () => page.cdp.snapshot(wc), "snapshot");}- async screenshot(input: { fullPage?: boolean } = {}, sessionId?: string): Promise<{ mimeType: string; data: string; path?: string }> {- const page = this.currentPage();+ async screenshot(input: { fullPage?: boolean } = {}, sessionId?: string, tabId?: string): Promise<{ mimeType: string; data: string; path?: string }> {+ const page = this.currentPage(sessionId, tabId);const shot = await captureScreenshotWithDeadline(page, (wc) => page.cdp.screenshot(wc, input));const scratch = this.deps.getScratchDir?.(sessionId ?? page.sessionId);if (!scratch) return shot;@@ -487,38 +514,39 @@ export class BrowserHost {} catch { return shot; }}- async click(uid: string): Promise<void> {- const page = this.currentPage();- const wc = this.requireWebContents();- return withCdpDeadline(page, wc, () => page.cdp.click(wc, uid), "click");+ async click(uid: string, sessionId?: string, tabId?: string): Promise<void> {+ const page = this.currentPage(sessionId, tabId);+ return page.pane.withStableViewport((wc) =>+ withCdpDeadline(page, wc, () => page.cdp.click(wc, uid), "click"),+ );}- async fill(uid: string, text: string): Promise<void> {- const page = this.currentPage();- const wc = this.requireWebContents();+ async fill(uid: string, text: string, sessionId?: string, tabId?: string): Promise<void> {+ const page = this.currentPage(sessionId, tabId);+ const wc = this.requireWebContents(page);return withCdpDeadline(page, wc, () => page.cdp.fill(wc, uid, text), "fill");}- async evaluate(expression: string): Promise<unknown> {- const page = this.currentPage();- const wc = this.requireWebContents();+ async evaluate(expression: string, sessionId?: string, tabId?: string): Promise<unknown> {+ const page = this.currentPage(sessionId, tabId);+ const wc = this.requireWebContents(page);return withCdpDeadline(page, wc, () => page.cdp.evaluate(wc, expression), "evaluate");}- console(limit?: number): { messages: ReturnType<BrowserCdp["console"]> } {- this.assertBrowserViewVisible();- if (!this.active?.started) return { messages: [] };- const wc = this.requireWebContents();- void this.active.cdp.attach(wc);- return { messages: this.active.cdp.console(limit) };- }- async cdpCommand(method: string, params?: unknown): Promise<unknown> {- const page = this.currentPage();- const wc = this.requireWebContents();+ console(limit?: number, sessionId?: string, tabId?: string): { messages: ReturnType<BrowserCdp["console"]> } {+ const page = this.operationPage(sessionId, tabId);+ if (!page.started) return { messages: [] };+ const wc = this.requireWebContents(page);+ void page.cdp.attach(wc);+ return { messages: page.cdp.console(limit) };+ }+ async cdpCommand(method: string, params?: unknown, sessionId?: string, tabId?: string): Promise<unknown> {+ const page = this.currentPage(sessionId, tabId);+ const wc = this.requireWebContents(page);if (method === "Page.captureScreenshot") {return captureScreenshotWithDeadline(page, (view) => page.cdp.send(view, method, params));}return withCdpDeadline(page, wc, () => page.cdp.send(wc, method, params), `cdp ${method}`);}- /** The renderer-created resource tab is the preview's only navigation owner. */+ /** Resolve containment roots from the owning session, not the visible UI. */getFileRoots(sessionId?: string): Promise<readonly string[]> {return this.deps.getFileRoots(sessionId);}@@ -541,7 +569,6 @@ export class BrowserHost {if (this.active === page) this.active = null;}this.locations.delete(key);- this.pendingTabs.delete(key);if (this.selectedTabs.get(sessionId) === tabId) this.selectedTabs.delete(sessionId);}@@ -550,15 +577,24 @@ export class BrowserHost {if (page.sessionId !== sessionId) continue;this.closeTab(sessionId, page.tabId);}- this.pendingSessions.delete(sessionId);this.selectedTabs.delete(sessionId);+ this.connectedTabs.delete(sessionId);for (const key of this.locations.keys()) {- if (JSON.parse(key)[0] === sessionId) { this.locations.delete(key); this.pendingTabs.delete(key); }+ if (JSON.parse(key)[0] === sessionId) this.locations.delete(key);}}dispose(): void { this.disposeGuest(); }+ /** Presentation is renderer-owned; page lifetime is not. */+ detachPresentation(): void {+ for (const page of this.pages.values()) page.pane.setVisible(false);+ this.active = null;+ this.chrome = null;+ this.hole = null;+ this.holePluginId = null;+ }+disposeGuest(): void {for (const waiter of [...this.revealWaiters]) {this.rejectRevealWaiter(@@ -572,9 +608,10 @@ export class BrowserHost {page.pane.dispose();}this.pages.clear();- this.active = null;- this.hole = null;- this.holePluginId = null;+ this.locations.clear();+ this.selectedTabs.clear();+ this.connectedTabs.clear();+ this.detachPresentation();}private guestBounds(): BrowserRect | null {diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.tsindex 53a7700c2..139a70fd6 100644--- a/apps/desktop/electron/main/browser-view.ts+++ b/apps/desktop/electron/main/browser-view.ts@@ -4,6 +4,7 @@ import { dirname, isAbsolute, resolve, sep } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import type { BrowserState } from "@pi-desktop/shared";import { isAllowedHttpUrl, parseAllowedExternalUrl } from "./safe-open-external";+import { BrowserBackingHost } from "./browser-backing-host";/*** Work panel embedded preview browser (D100, ADR 0019).@@ -120,13 +121,15 @@ function resolveBrowserLocalFile(raw: string, root: string | null): string | nul}export class BrowserPane {+ private static readonly sharedBackingHost = new BrowserBackingHost();private view: WebContentsView | null = null;private surface: View | null = null;private window: BrowserWindow | null = null;+ private attachedWindow: BrowserWindow | null = null;private visible = false;private bounds = { x: 0, y: 0, width: 0, height: 0 };- private capturing = false;- private captureTail: Promise<void> = Promise.resolve();+ private viewportPinned = false;+ private operationTail: Promise<void> = Promise.resolve();private onState: (state: BrowserState) => void;private fileRoot: string | null = null;private watcher: FSWatcher | null = null;@@ -141,10 +144,16 @@ export class BrowserPane {private cancelPending: (() => void) | null = null;private readonly onOpenUrl?: (url: string) => void;+ private readonly backingHost: BrowserBackingHost;- constructor(onState: (state: BrowserState) => void, onOpenUrl?: (url: string) => void) {+ constructor(+ onState: (state: BrowserState) => void,+ onOpenUrl?: (url: string) => void,+ backingHost = BrowserPane.sharedBackingHost,+ ) {this.onState = onState;this.onOpenUrl = onOpenUrl;+ this.backingHost = backingHost;}setWindow(window: BrowserWindow | null): void {@@ -181,26 +190,32 @@ export class BrowserPane {return wc;}- /** Serialize captures with native resizing on this page only. */+ /** Captures and pointer input share one page-local viewport owner. */captureScreenshot<T>(capture: (wc: WebContents) => Promise<T>): Promise<T> {- // Pin the guest before queueing so a closed/recreated page cannot receive- // a screenshot requested for its predecessor.+ return this.withStableViewport(capture);+ }++ withStableViewport<T>(operation: (wc: WebContents) => Promise<T>): Promise<T> {+ // Pin identity before queueing; a replacement cannot receive old work.const wc = this.getWebContents();- const task = this.captureTail.then(async () => {+ const task = this.operationTail.then(async () => {if (!wc || wc.isDestroyed() || this.getWebContents() !== wc) {throw Object.assign(new Error("browser guest is not available"), { code: "UNAVAILABLE" });}- this.capturing = true;+ const throttled = wc.getBackgroundThrottling();+ this.viewportPinned = true;+ wc.setBackgroundThrottling(false);try {- return await capture(wc);+ return await operation(wc);} finally {- this.capturing = false;+ this.viewportPinned = false;+ if (!wc.isDestroyed()) wc.setBackgroundThrottling(throttled);this.applyBounds();}});// The caller still receives capture errors; a failure must not block the// next independent capture.- this.captureTail = task.then(() => undefined, () => undefined);+ this.operationTail = task.then(() => undefined, () => undefined);return task;}@@ -343,8 +358,8 @@ export class BrowserPane {// Move and clip the presentation surface immediately, even while Chromium// pins its capture-time viewport. A pending screenshot must not leave the// guest over the conversation when the window or work panel moves.- this.surface?.setBounds(this.bounds);- if (this.view && this.visible && !this.capturing && this.getWebContents()) {+ if (this.visible) this.surface?.setBounds(this.bounds);+ if (this.view && this.visible && !this.viewportPinned && this.getWebContents()) {this.view.setBounds({ x: 0, y: 0, width: this.bounds.width, height: this.bounds.height });}}@@ -352,10 +367,8 @@ export class BrowserPane {setVisible(visible: boolean): void {this.visible = visible;if (!this.view) return;- this.surface?.setVisible(visible);- this.view.setVisible?.(visible);if (visible) this.attach();- else this.detach();+ else this.park();}openExternal(): void {@@ -390,24 +403,41 @@ export class BrowserPane {private attach(): void {if (!this.window || this.window.isDestroyed() || !this.surface) return;+ if (this.attachedWindow !== this.window) this.detach();const children = this.window.contentView.children;- // The guest hole sits on top of plugin chrome. Re-adding a plugin view- // after this pane is attached would cover the guest unless we keep it last.+ // Keep the guest above its plugin chrome, but confined to the measured hole.if (children.includes(this.surface) && children[children.length - 1] !== this.surface) {this.window.contentView.removeChildView(this.surface);}- if (!this.window.contentView.children.includes(this.surface)) {- this.window.contentView.addChildView(this.surface);- }+ if (!this.window.contentView.children.includes(this.surface)) this.window.contentView.addChildView(this.surface);+ this.attachedWindow = this.window;+ this.surface.setVisible(true);+ this.view?.setVisible(true);this.applyBounds();}+ /** A hidden native host keeps Chromium input/capture independent of the UI. */+ private park(): void {+ if (!this.surface || !this.view || !this.getWebContents()) return;+ if (this.attachedWindow && this.attachedWindow !== this.window && !this.attachedWindow.isDestroyed()) return;+ this.detach();+ const bounds = this.view.getBounds();+ const size = { width: bounds.width || 1024, height: bounds.height || 768 };+ if (!bounds.width || !bounds.height) this.view.setBounds({ x: 0, y: 0, ...size });+ this.surface.setBounds({ x: 0, y: 0, ...size });+ this.surface.setVisible(true);+ this.view.setVisible(true);+ this.attachedWindow = this.backingHost.attach(this.surface, size);+ }+private detach(): void {- if (!this.window || this.window.isDestroyed() || !this.surface) return;- const children = this.window.contentView.children;- if (children.includes(this.surface)) {- this.window.contentView.removeChildView(this.surface);+ if (!this.surface) return;+ const owner = this.attachedWindow;+ if (owner && !owner.isDestroyed() && owner.contentView.children.includes(this.surface)) {+ owner.contentView.removeChildView(this.surface);}+ this.attachedWindow = null;+ this.backingHost.detach(this.surface);}/** Watch the previewed file's directory so page + asset edits re-render. */@@ -541,6 +571,8 @@ export class BrowserPane {},);this.view = view;+ if (this.visible) this.attach();+ else this.park();return view;}diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.tsindex f704e0c02..f2a6e26cb 100644--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts@@ -769,6 +769,12 @@ export function registerWorkspaceIpc({return browserHost.getState();});+ handle(IPC.invoke.browserGetPages, async (input: { sessionId?: string } = {}) => {+ const sessionId = String(input.sessionId ?? "").trim();+ if (!sessionId) return [];+ return browserHost.getPages(sessionId);+ });+type WorkspaceRootInfo = {root: string;/** Present only for an isolated session's worktree checkout. */diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex 437d1455e..dca5d870f 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -472,18 +472,19 @@ export type PluginHostServices = {action: (action: "back" | "forward" | "reload" | "stop", sessionId?: string, tabId?: string) => void;setBounds: (pluginId: string, hole: unknown) => unknown;setVisible: (pluginId: string, visible: boolean) => void;- getState: () => unknown;+ getState: (sessionId?: string, tabId?: string) => unknown;openExternal: (sessionId?: string, tabId?: string) => void;- snapshot: () => Promise<unknown>;+ snapshot: (sessionId?: string, tabId?: string) => Promise<unknown>;screenshot: (input?: { fullPage?: boolean },sessionId?: string,+ tabId?: string,) => Promise<unknown>;- click: (uid: string) => Promise<void>;- fill: (uid: string, text: string) => Promise<void>;- evaluate: (expression: string) => Promise<unknown>;- console: (limit?: number) => unknown;- cdp: (method: string, params?: unknown) => Promise<unknown>;+ click: (uid: string, sessionId?: string, tabId?: string) => Promise<void>;+ fill: (uid: string, text: string, sessionId?: string, tabId?: string) => Promise<void>;+ evaluate: (expression: string, sessionId?: string, tabId?: string) => Promise<unknown>;+ console: (limit?: number, sessionId?: string, tabId?: string) => unknown;+ cdp: (method: string, params?: unknown, sessionId?: string, tabId?: string) => Promise<unknown>;};onPluginUnload?: (pluginId: string) => void;listModels?: () => Promise<PluginModelInfo[]>;@@ -4820,7 +4821,11 @@ export class PluginRuntime {}private browserSessionId(pluginId?: string): string | undefined {- return pluginId ? this.inFlightTool(pluginId)?.sessionId.trim() || undefined : undefined;+ const invocation = pluginId ? this.inFlightTool(pluginId) : undefined;+ if (!invocation) return undefined;+ const sessionId = invocation.sessionId.trim();+ if (!sessionId) throw apiError("INVALID_ARGUMENT", "Browser tool calls require a session.");+ return sessionId;}private async invokeBrowser(@@ -6364,7 +6369,7 @@ export class PluginRuntime {action === "reload" ||action === "stop") {- this.services.browser.action(action, browserContext?.sessionId, browserContext?.tabId);+ this.services.browser.action(action, this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);}},setBounds: (hole: unknown) => {@@ -6387,14 +6392,14 @@ export class PluginRuntime {if (!this.services.browser) {throw apiError("UNAVAILABLE", "browser host missing");}- return this.services.browser.getState();+ return this.services.browser.getState(this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);},openExternal: () => {this.assertPermission(loaded, "browser.cdp");if (!this.services.browser) {throw apiError("UNAVAILABLE", "browser host missing");}- this.services.browser.openExternal(browserContext?.sessionId, browserContext?.tabId);+ this.services.browser.openExternal(this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);this.services.audit?.({pluginId,api: "browser.openExternal",@@ -6407,7 +6412,7 @@ export class PluginRuntime {if (!this.services.browser) {throw apiError("UNAVAILABLE", "browser host missing");}- return this.services.browser.snapshot();+ return this.services.browser.snapshot(this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);},screenshot: async (input?: { fullPage?: boolean }) => {this.assertPermission(loaded, "browser.cdp");@@ -6416,7 +6421,8 @@ export class PluginRuntime {}return this.services.browser.screenshot(input,- this.browserSessionId(pluginId),+ this.browserSessionId(pluginId) ?? browserContext?.sessionId,+ browserContext?.tabId,);},click: async (input: string | { uid?: string }) => {@@ -6425,7 +6431,7 @@ export class PluginRuntime {throw apiError("UNAVAILABLE", "browser host missing");}const uid = typeof input === "string" ? input : String(input?.uid ?? "");- await this.services.browser.click(uid);+ await this.services.browser.click(uid, this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);},fill: async (input: string | { uid?: string; text?: string },@@ -6437,7 +6443,7 @@ export class PluginRuntime {}const uid = typeof input === "string" ? input : String(input?.uid ?? "");const text = typeof input === "string" ? String(textArg ?? "") : String(input?.text ?? "");- await this.services.browser.fill(uid, text);+ await this.services.browser.fill(uid, text, this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);},evaluate: async (input: string | { expression?: string }) => {this.assertPermission(loaded, "browser.cdp");@@ -6451,7 +6457,7 @@ export class PluginRuntime {ok: true,ts: Date.now(),});- return this.services.browser.evaluate(expression);+ return this.services.browser.evaluate(expression, this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);},console: (input?: number | { limit?: number }) => {this.assertPermission(loaded, "browser.cdp");@@ -6459,7 +6465,7 @@ export class PluginRuntime {throw apiError("UNAVAILABLE", "browser host missing");}const limit = typeof input === "number" ? input : input?.limit;- return this.services.browser.console(limit);+ return this.services.browser.console(limit, this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);},cdp: async (input: string | { method?: string; params?: unknown },@@ -6478,7 +6484,7 @@ export class PluginRuntime {ts: Date.now(),method,});- return this.services.browser.cdp(method, params);+ return this.services.browser.cdp(method, params, this.browserSessionId(pluginId) ?? browserContext?.sessionId, browserContext?.tabId);},},};diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.tsindex 1fee85cff..745404902 100644--- a/apps/desktop/electron/main/runtime/sidecar.ts+++ b/apps/desktop/electron/main/runtime/sidecar.ts@@ -605,13 +605,10 @@ export function createSidecarRuntime({content: preview.content,};}- sendToRenderer(IPC.event.browserPreview, {- sessionId,- path: file,- });+ await browserHost.openTab({ path: file }, sessionId);return {ok: true,- content: `Requested a new Browser tab for ${raw}. Once loaded, live reload updates the page when the file or sibling assets change.`,+ content: `Opened a new Browser tab for ${raw}. Its page stays available in the background, and live reload updates it when the file or sibling assets change.`,};});// Plugin skills (D174): the model loads a declared skill document by id.diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex dcd0e1e43..cdd62ef13 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -50,6 +50,7 @@ import { PluginPanelHost } from "../plugin-panel-host";import { PluginViewHost } from "../plugin-view-host";import { SESSION_SCOPED_EVENTS, sessionEventScopeFilter } from "../plugin-session-scope";import { BrowserPane } from "../browser-view";+import { BrowserBackingHost } from "../browser-backing-host";import { BrowserHost, BROWSER_PLUGIN_ID } from "../browser-host";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";import type { ClipboardHistory } from "../clipboard-history";@@ -566,6 +567,8 @@ export function createPluginServices({const sessionProjects = new Map<string, string | null>();const emitBrowserState = (state: BrowserState) => {sendToRenderer(IPC.event.browserState, state);+ };+ const emitBrowserPresentationState = (state: BrowserState) => {pluginPanels.broadcast("browser:state", state);pluginViews.broadcast("browser:state", state);};@@ -657,8 +660,9 @@ export function createPluginServices({});});pluginPanels.addSenderResolver((senderId) => pluginViews.pluginIdForSender(senderId));+ const browserBackingHost = new BrowserBackingHost();const browserHost = new BrowserHost({- createPane: (onState, onOpenUrl) => new BrowserPane(onState, onOpenUrl),+ createPane: (onState, onOpenUrl) => new BrowserPane(onState, onOpenUrl, browserBackingHost),onOpenUrl: (url, sessionId) => {void (async () => {const settings = await getHost()?.call<AppSettings>("settings.get");@@ -694,8 +698,9 @@ export function createPluginServices({return join(dataDir, "scratch", sessionId);},onState: emitBrowserState,- onRevealView: (sessionId, tabId) =>- sendToRenderer(IPC.event.browserPreview, { sessionId, tabId, revealOnly: true }),+ onPresentationState: emitBrowserPresentationState,+ onRevealView: (sessionId, tabId, location) =>+ sendToRenderer(IPC.event.browserPreview, { sessionId, tabId, ...(location ?? { revealOnly: true }) }),});pluginViews.onSurface = (surface) => {browserHost.setChromeSurface(surface);@@ -757,15 +762,15 @@ export function createPluginServices({action: (action, sessionId, tabId) => browserHost.action(action, sessionId, tabId),setBounds: (pluginId, hole) => browserHost.setGuestHole(pluginId, hole),setVisible: (pluginId, visible) => browserHost.setGuestVisible(pluginId, visible),- getState: () => browserHost.getStateForPlugin(),+ getState: (sessionId, tabId) => browserHost.getStateForPlugin(sessionId, tabId),openExternal: (sessionId, tabId) => browserHost.openExternal(sessionId, tabId),- snapshot: () => browserHost.snapshot(),- screenshot: (input, sessionId) => browserHost.screenshot(input, sessionId),- click: (uid) => browserHost.click(uid),- fill: (uid, text) => browserHost.fill(uid, text),- evaluate: (expression) => browserHost.evaluate(expression),- console: (limit) => browserHost.console(limit),- cdp: (method, params) => browserHost.cdpCommand(method, params),+ snapshot: (sessionId, tabId) => browserHost.snapshot(sessionId, tabId),+ screenshot: (input, sessionId, tabId) => browserHost.screenshot(input, sessionId, tabId),+ click: (uid, sessionId, tabId) => browserHost.click(uid, sessionId, tabId),+ fill: (uid, text, sessionId, tabId) => browserHost.fill(uid, text, sessionId, tabId),+ evaluate: (expression, sessionId, tabId) => browserHost.evaluate(expression, sessionId, tabId),+ console: (limit, sessionId, tabId) => browserHost.console(limit, sessionId, tabId),+ cdp: (method, params, sessionId, tabId) => browserHost.cdpCommand(method, params, sessionId, tabId),},onPluginUnload: (pluginId) => {if (pluginId === BROWSER_PLUGIN_ID) browserHost.disposeGuest();diff --git a/apps/desktop/resources/plugins/pi.browser/main.js b/apps/desktop/resources/plugins/pi.browser/main.jsindex 62da193a0..19f596334 100644--- a/apps/desktop/resources/plugins/pi.browser/main.js+++ b/apps/desktop/resources/plugins/pi.browser/main.js@@ -29,10 +29,10 @@ export async function onLoad() {description: ["Drive PI-Desktop's work-panel browser via CDP.",'Call ToolSearch for "browser" or "cdp" to load this tool.',- "Browser operations automatically reveal the work-panel view for this session and wait until it is ready.",- "Keep the panel visible while working.",- "For a workspace HTML file, call BrowserPreview first; it opens and reveals a live-reloading Browser tab.",- "Do not ask the user to open Browser manually. If this session is in the background, ask them to switch to it and retry.",+ "Browser operations use this session's connected page, including while its side panel is hidden or another session is visible.",+ "Navigate first if no page is connected. Opening the first page adds its Browser tab automatically.",+ "For a workspace HTML file, call BrowserPreview first; it opens a live-reloading Browser tab.",+ "Do not ask the user to open Browser manually or switch back to this session. Background operations never take focus.","Then snapshot the accessibility tree, click/fill by uid, take screenshots, evaluate JavaScript,","read console output, or send an allowlisted raw CDP method.",].join(" "),@@ -44,7 +44,7 @@ export async function onLoad() {action: {type: "string",enum: ACTIONS,- description: "The Browser view opens automatically for the calling session before this action runs.",+ description: "Action on the calling session's connected Browser page; the side panel need not be visible.",},url: { type: "string", description: "http(s) URL for action=navigate." },path: {@@ -84,7 +84,6 @@ export async function onLoad() {error: `unknown action "${action}"; use ${ACTIONS.join(", ")}`,};}- await pi.browser.reveal();switch (action) {case "navigate": {const state = await pi.browser.navigate({diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsxindex 08a94051e..b6f4c60e5 100644--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx@@ -86,6 +86,21 @@ export function useAppShellRuntime() {);const workPanelVisible = workPanelOpen;+ useEffect(() => {+ if (!ready || !activeSessionId || activeSessionId.startsWith("remote:")) return;+ const state = useAppStore.getState();+ const tabs = state.workPanelContexts[activeSessionId]?.tabs ?? state.workPanelTabs;+ let current = true;+ void api.browserGetPages(activeSessionId).then((pages) => {+ if (!current) return;+ const live = useAppStore.getState();+ const liveTabs = live.workPanelContexts[activeSessionId]?.tabs ?? live.workPanelTabs;+ if (live.activeSessionId !== activeSessionId || liveTabs !== tabs) return;+ live.restoreBrowserWorkPanelTabs(activeSessionId, pages);+ }).catch((error) => console.warn("Browser tab restore failed", error));+ return () => { current = false; };+ }, [ready, activeSessionId, workPanelOpen]);+const [searchOpen, setSearchOpen] = useState(false);const [sidebarCollapsed, setSidebarCollapsed] = useState(false);const [sidebarWidth, setSidebarWidth] = useState(() => loadSidebarWidth());@@ -684,6 +699,7 @@ export function useAppShellRuntime() {}state.openWorkPanelTabForSession(event.sessionId, {...browserPluginTab(event.path ?? event.url),+ ...(event.tabId ? { id: event.tabId } : {}),});});const offBrowserOpenFile = api.onBrowserOpenFile(({ path }) => {diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 6b2ac75f1..47b45ea4e 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1598,6 +1598,8 @@ export const api = {invoke(IPC.invoke.browserOpenExternal, url ? { url } : {}),browserGetState: () =>invoke<BrowserState | null>(IPC.invoke.browserGetState),+ browserGetPages: (sessionId: string) =>+ invoke<BrowserState[]>(IPC.invoke.browserGetPages, { sessionId }),fsList: (path?: string, sessionId?: string) =>invoke<{ entries: FsEntry[] }>(IPC.invoke.fsList, { path: path ?? "", ...(sessionId ? { sessionId } : {}) }),fsRead: (path: string, mimeType?: string, sessionId?: string) =>diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.tsindex a2d018447..faa36c6d2 100644--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@ -439,6 +439,7 @@ export type AppState = {) => void;openUrlInWorkPanel: (url: string) => void;updateBrowserWorkPanelTab: (state: BrowserState) => void;+ restoreBrowserWorkPanelTabs: (sessionId: string, pages: BrowserState[]) => void;};export type AppStateData = {diff --git a/apps/desktop/src/stores/slices/work-panel-slice.ts b/apps/desktop/src/stores/slices/work-panel-slice.tsindex d3c563028..c0702a4d2 100644--- a/apps/desktop/src/stores/slices/work-panel-slice.ts+++ b/apps/desktop/src/stores/slices/work-panel-slice.ts@@ -118,6 +118,7 @@ export function createWorkPanelSlice({| "openFileInWorkPanel"| "openUrlInWorkPanel"| "updateBrowserWorkPanelTab"+ | "restoreBrowserWorkPanelTabs"> {let workPanelFileRequestSeq = 0;const nextFileRequest = (tab?: WorkPanelTab): WorkPanelContext["fileRequest"] => {@@ -385,6 +386,25 @@ export function createWorkPanelSlice({workPanelContexts: { ...state.workPanelContexts, [sessionId]: { ...context, tabs } } };});},+ restoreBrowserWorkPanelTabs: (sessionId, pages) => {+ if (!sessionId || isRemoteSession(get().sessions.find((session) => session.id === sessionId)) || sessionId.startsWith("remote:")) return;+ set((state) => {+ const visible = state.activeSessionId === sessionId && !isSessionSelectionPending(sessionId);+ const context = visible ? currentWorkPanelContext(state) : state.workPanelContexts[sessionId] ?? emptyWorkPanelContext();+ const retained = pages.flatMap((page): WorkPanelTab[] => {+ const tabId = page.tabId;+ if (page.sessionId !== sessionId || !tabId || context.tabs.some((tab) => tab.id === tabId)) return [];+ return [{ ...browserPluginTab(), id: tabId, location: page.url, label: page.title || browserTabLabel(page.url) }];+ });+ const last = retained.at(-1);+ if (!last) return {};+ const next = { ...context, tabs: [...context.tabs, ...retained], activeTabId: context.activeTabId ?? last.id };+ return {+ workPanelContexts: { ...state.workPanelContexts, [sessionId]: next },+ ...(visible ? { workPanelTabs: next.tabs, activeWorkPanelTabId: next.activeTabId } : {}),+ };+ });+ },openUrlInWorkPanel: (url) => {if (isRemoteSession(get().sessions.find((session) => session.id === get().activeSessionId))) return;const hasBrowser = get().pluginViews.some(diff --git a/apps/desktop/test/browser-background-session.test.mjs b/apps/desktop/test/browser-background-session.test.mjsnew file mode 100644index 000000000..f9104043d--- /dev/null+++ b/apps/desktop/test/browser-background-session.test.mjs@@ -0,0 +1,257 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import { register } from "node:module";+import test from "node:test";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { BrowserHost } = await import("../electron/main/browser-host.ts");++const settled = () => new Promise(setImmediate);+function deferred() {+ let resolve;+ const promise = new Promise((done) => { resolve = done; });+ return { promise, resolve };+}++// Electron/WebContents is the external edge. BrowserHost and BrowserCdp use+// their production wiring, including per-page snapshot uids and deadlines.+function harness() {+ const panes = [], roots = [], loads = [], published = [], presentation = [], reveals = [];+ let enabled = true;+ const host = new BrowserHost({+ createPane(onState) {+ let state = null;+ let attached = false;+ const commands = [];+ const wc = {+ id: panes.length + 1,+ clicks: 0,+ value: "",+ isDestroyed: () => pane.disposed,+ getURL: () => state?.url ?? "",+ getTitle: () => state?.title ?? "",+ debugger: Object.assign(new EventEmitter(), {+ isAttached: () => attached,+ attach() { attached = true; },+ detach() { attached = false; },+ async sendCommand(method, input = {}) {+ commands.push({ method, input });+ if (method === "Accessibility.getFullAXTree") return {+ nodes: [{ nodeId: "1", role: { value: "button" }, name: { value: wc.getTitle() }, backendDOMNodeId: wc.id }],+ };+ if (method === "DOM.getBoxModel") return { model: { content: wc.hiddenBoxOffset ? [-140, -876, -100, -876, -100, -836, -140, -836] : [0, 0, 40, 0, 40, 40, 0, 40] } };+ if (method === "DOM.resolveNode") return { object: { objectId: `input-${wc.id}` } };+ if (method === "Input.dispatchMouseEvent" && input.type === "mouseReleased" && input.x >= 0 && input.y >= 0) wc.clicks += 1;+ if (method === "Runtime.callFunctionOn" && input.functionDeclaration.includes("getBoundingClientRect")) return { result: { value: { x: 20, y: 20 } } };+ if (method === "Runtime.callFunctionOn") wc.value = input.arguments[0].value;+ if (method === "Runtime.evaluate") return { result: { value: wc.getTitle() } };+ if (method === "Page.captureScreenshot") return { data: Buffer.from(wc.getTitle()).toString("base64") };+ return {};+ },+ }),+ };+ const pane = {+ disposed: false,+ visible: false,+ wc,+ commands,+ setWindow() {},+ setBounds() {},+ setVisible(visible) { this.visible = visible; },+ getState: () => state,+ getWebContents: () => pane.disposed ? null : wc,+ captureScreenshot: (run) => run(wc),+ withStableViewport: (run) => run(wc),+ navigateAndWait(url, root) {+ const pending = deferred();+ loads.push({ url, root, pane, finish() {+ state = { url, title: url, isLoading: false, canGoBack: false, canGoForward: false };+ onState(state);+ pending.resolve(state);+ } });+ return pending.promise;+ },+ dispose() { this.disposed = true; this.visible = false; },+ };+ panes.push(pane);+ return pane;+ },+ isPluginLoaded: () => enabled,+ getFileRoots(sessionId) {+ const pending = deferred();+ roots.push({ sessionId, ...pending });+ return pending.promise;+ },+ onState: (state) => published.push(state),+ onPresentationState: (state) => presentation.push(state),+ onRevealView: (sessionId, tabId) => reveals.push({ sessionId, tabId }),+ });+ const surface = (visible = true) => host.setChromeSurface({+ pluginId: "pi.browser", viewId: "browser", visible,+ bounds: { x: 100, y: 20, width: 400, height: 600 },+ });+ surface();+ host.setGuestHole("pi.browser", { x: 0, y: 30, width: 400, height: 570 });+ return { host, panes, roots, loads, published, presentation, reveals, surface, disable: () => { enabled = false; } };+}++async function open(h, sessionId, tabId, url) {+ h.host.setChromeSession(sessionId, tabId, url);+ h.roots.at(-1).resolve([`/projects/${sessionId}`]);+ await settled();+ h.loads.at(-1).finish();+ await settled();+ return h.panes.at(-1);+}++test("background Browser actions stay on the invoking session while another page is visible", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ const a = await open(h, "A", "a", "https://fixture.invalid/a");+ const b = await open(h, "B", "b", "https://fixture.invalid/b");+ const snapshot = await h.host.snapshot("A");+ assert.equal(snapshot.url, "https://fixture.invalid/a");+ assert.match(snapshot.tree, /fixture.invalid\/a/);+ await h.host.click("e1", "A");+ await h.host.fill("e1", "A's draft", "A");+ assert.equal(await h.host.evaluate("document.title", "A"), "https://fixture.invalid/a");+ const shot = await h.host.screenshot({}, "A");+ assert.equal(Buffer.from(shot.data, "base64").toString(), "https://fixture.invalid/a");+ await h.host.cdpCommand("Page.enable", {}, "A");+ assert.deepEqual(h.host.console(10, "A"), { messages: [] });+ assert.equal(a.wc.clicks, 1);+ assert.equal(a.wc.value, "A's draft");+ assert.equal(b.wc.clicks, 0);+ assert.equal(b.wc.value, "");+ assert.equal(h.host.getState().sessionId, "B");+ assert.equal(a.visible, false);+ assert.equal(b.visible, true);+ assert.deepEqual(h.reveals, []);+});++test("hiding or unmounting browser chrome does not interrupt an owned page", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ const a = await open(h, "A", "a", "https://fixture.invalid/a");+ h.surface(false);+ h.host.setChromeSurface(null);+ assert.equal((await h.host.snapshot("A")).url, "https://fixture.invalid/a");+ await h.host.fill("e1", "retained draft", "A");+ assert.equal(h.host.getStateForPlugin("A").tabId, "a");+ assert.equal(a.disposed, false);+ assert.equal(a.visible, false);+ h.surface();+ h.host.setChromeSession("A", "a");+ assert.equal(a.wc.value, "retained draft");+ assert.equal(h.loads.length, 1, "showing the side panel must not reload its page");+});++test("background navigation executes immediately and never rewrites the visible session", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ await open(h, "A", "a", "https://fixture.invalid/a");+ await open(h, "B", "b", "https://fixture.invalid/b");+ const navigation = h.host.navigate({ url: "https://fixture.invalid/new-a" }, "A");+ assert.equal(h.roots.at(-1).sessionId, "A");+ h.roots.at(-1).resolve(["/projects/A"]);+ await settled();+ assert.equal(h.loads.at(-1).url, "https://fixture.invalid/new-a");+ h.loads.at(-1).finish();+ assert.equal((await navigation).tabId, "a");+ assert.equal(h.host.getState().url, "https://fixture.invalid/b");+ assert.equal((await h.host.snapshot("A")).url, "https://fixture.invalid/new-a");+});++test("unknown, closed and disabled targets fail without borrowing another session's page", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ await open(h, "A", "a", "https://fixture.invalid/a");+ const b = await open(h, "B", "b", "https://fixture.invalid/b");+ await assert.rejects(h.host.snapshot("missing"), { code: "UNAVAILABLE" });+ h.host.closeSession("A");+ await assert.rejects(h.host.snapshot("A"), { code: "UNAVAILABLE" });+ await assert.rejects(h.host.click("e1", "A"), { code: "UNAVAILABLE" });+ h.disable();+ await assert.rejects(h.host.snapshot("B"), { code: "UNAVAILABLE" });+ assert.equal(b.commands.length, 0);+});++test("renderer reload detaches only presentation and keeps page identity and inputs", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ const a = await open(h, "A", "a", "https://fixture.invalid/a");+ await h.host.snapshot("A");+ await h.host.fill("e1", "unsaved input", "A");+ h.host.detachPresentation();+ assert.equal(h.host.getState(), null);+ assert.deepEqual(h.host.getPages("A").map((page) => page.tabId), ["a"]);+ assert.deepEqual(h.host.getPages("B"), []);+ assert.equal((await h.host.snapshot("A")).url, "https://fixture.invalid/a");+ h.surface();+ h.host.setGuestHole("pi.browser", { x: 0, y: 30, width: 400, height: 570 });+ h.host.setChromeSession("A", "a", "https://fixture.invalid/a");+ assert.equal(h.panes.length, 1);+ assert.equal(h.loads.length, 1);+ assert.equal(a.wc.value, "unsaved input");+ h.host.closeTab("A", "a");+ assert.deepEqual(h.host.getPages("A"), []);+});++test("a preview creates and loads its own background page before a side-panel tab mounts", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ await open(h, "B", "b", "https://fixture.invalid/b");+ const preview = h.host.openTab({ path: "/projects/A/preview.html" }, "A");+ assert.equal(h.roots.at(-1).sessionId, "A");+ h.roots.at(-1).resolve(["/projects/A"]);+ await settled();+ h.loads.at(-1).finish();+ const result = await preview;+ assert.equal(result.state.sessionId, "A");+ assert.equal(result.state.tabId, result.tabId);+ assert.equal(h.host.getState().sessionId, "B");+ assert.equal((await h.host.snapshot("A")).url, "/projects/A/preview.html");+ h.host.setChromeSession("A", result.tabId, "/projects/A/preview.html");+ assert.equal(h.loads.length, 2);+});++test("an established connection stays on its page when the user views another tab", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ const first = await open(h, "A", "first", "https://fixture.invalid/first");+ await h.host.snapshot("A");+ const second = await open(h, "A", "second", "https://fixture.invalid/second");+ await h.host.click("e1", "A");+ assert.equal(first.wc.clicks, 1);+ assert.equal(second.wc.clicks, 0);+ assert.equal(h.host.getState().tabId, "second");+ h.host.closeTab("A", "first");+ await assert.rejects(h.host.snapshot("A"), { code: "UNAVAILABLE" });+});++test("background page metadata never repaints the visible browser chrome", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ await open(h, "A", "a", "https://fixture.invalid/a");+ await open(h, "B", "b", "https://fixture.invalid/b");+ assert.equal(h.presentation.at(-1)?.sessionId, "B", "foreground state reaches browser chrome");+ h.presentation.length = 0;+ const navigation = h.host.navigate({ url: "https://fixture.invalid/new-a" }, "A");+ h.roots.at(-1).resolve(["/projects/A"]);+ await settled();+ h.loads.at(-1).finish();+ await navigation;+ assert.equal(h.published.at(-1).sessionId, "A", "renderer retains the originating tab metadata");+ assert.deepEqual(h.presentation, [], "B's chrome must not repaint or report A's bounds");+});++test("hidden native-view offsets cannot send a Browser click outside the page", async (t) => {+ const h = harness();+ t.after(() => h.host.dispose());+ const a = await open(h, "A", "a", "https://fixture.invalid/a");+ await h.host.snapshot("A");+ await open(h, "B", "b", "https://fixture.invalid/b");+ a.wc.hiddenBoxOffset = true;+ await h.host.click("e1", "A");+ assert.equal(a.wc.clicks, 1, "click must use the target element's page-relative point");+});diff --git a/apps/desktop/test/browser-capture-resize.test.mjs b/apps/desktop/test/browser-capture-resize.test.mjsindex 006bded79..39175acbd 100644--- a/apps/desktop/test/browser-capture-resize.test.mjs+++ b/apps/desktop/test/browser-capture-resize.test.mjs@@ -20,6 +20,16 @@ const electron = `data:text/javascript,${encodeURIComponent(`getBounds() { return { ...this.bounds }; }setVisible(visible) { this.visible = visible; }}+ export class BrowserWindow {+ static instances = [];+ contentView = new View();+ destroyed = false;+ constructor(options) { this.size = [options.width, options.height]; BrowserWindow.instances.push(this); }+ getContentSize() { return this.size; }+ setContentSize(width, height) { this.size = [width, height]; }+ isDestroyed() { return this.destroyed; }+ destroy() { this.destroyed = true; }+ }export class WebContentsView extends View {static instances = [];constructor() {@@ -37,6 +47,9 @@ const electron = `data:text/javascript,${encodeURIComponent(`getURL() { return this.url; },getTitle: () => "fixture", isLoading: () => false,isDestroyed() { return this.destroyed; },+ throttled: true,+ getBackgroundThrottling() { return this.throttled; },+ setBackgroundThrottling(value) { this.throttled = value; },close() {if (this.destroyed) throw new Error("guest already destroyed");this.destroyed = true;@@ -83,7 +96,7 @@ registerHooks({ resolve(specifier, context, next) {register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));const { BrowserHost } = await import("../electron/main/browser-host.ts");const { BrowserPane } = await import("../electron/main/browser-view.ts");-const { WebContentsView } = await import("electron");+const { WebContentsView, BrowserWindow } = await import("electron");async function harness(t) {const host = new BrowserHost({@@ -101,7 +114,7 @@ async function harness(t) {const resize = (width, height) => host.setGuestHole("pi.browser", { x: 0, y: 0, width, height });resize(800, 500);host.setChromeSession("session", "first");- await host.navigate({ url: "https://fixture.invalid/first" }, "session");+ await host.navigate({ url: "https://fixture.invalid/first" }, "session", "first");t.after(() => host.dispose());return { host, resize, children, view: WebContentsView.instances.at(-1), wc: WebContentsView.instances.at(-1).webContents };}@@ -239,7 +252,7 @@ test("overlapping capture APIs serialize per page, not across sibling tabs", asyconst nextStarted = once(wc, "capture-start");const next = host.cdpCommand("Page.captureScreenshot", { format: "png" });host.setChromeSession("session", "second");- await host.navigate({ url: "https://fixture.invalid/second" }, "session");+ await host.navigate({ url: "https://fixture.invalid/second" }, "session", "second");const sibling = WebContentsView.instances.at(-1).webContents;const siblingStarted = once(sibling, "capture-start");const siblingShot = host.screenshot();@@ -267,7 +280,7 @@ test("closing a tab rejects its queued capture without capturing a replacement",const queued = assert.rejects(host.screenshot(), /browser guest is not available/);host.closeTab("session", "first");host.setChromeSession("session", "replacement");- await host.navigate({ url: "https://fixture.invalid/replacement" }, "session");+ await host.navigate({ url: "https://fixture.invalid/replacement" }, "session", "replacement");wc.captures[0].resolve();await first;await queued;@@ -282,9 +295,9 @@ test("hiding and restoring a captured page keeps its presentation isolated fromconst capture = host.screenshot();await started;host.setChromeSession("session", "second");- await host.navigate({ url: "https://fixture.invalid/second" }, "session");+ await host.navigate({ url: "https://fixture.invalid/second" }, "session", "second");assert(!children.includes(surface));- assert.equal(surface.visible, false);+ assert.equal(surface.parent.visible, true, "the page stays rendered in the hidden backing host");const relocated = { x: 960, y: 70, width: 530, height: 400 };host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true, bounds: relocated });host.setGuestHole("pi.browser", { x: 0, y: 0, width: 530, height: 400 });@@ -307,7 +320,7 @@ test("a destroyed native guest can be resized, replaced and disposed safely", aswc.close();assert.equal(view.webContents, undefined, "Electron clears a destroyed guest handle");resize(930, 620);- await host.navigate({ url: "https://fixture.invalid/recreated" }, "session");+ await host.navigate({ url: "https://fixture.invalid/recreated" }, "session", "first");const replacement = WebContentsView.instances.at(-1);assert.notEqual(replacement, view);assert(!children.includes(previousSurface));@@ -330,3 +343,34 @@ test("capture completion after native guest destruction preserves the original cassert.equal((await capture).data, "fixture-image");host.dispose();});++test("background backing windows stay hidden and release with the last parked page", async (t) => {+ const { host, children, view, wc } = await harness(t);+ host.setChromeSurface(null);+ const backing = BrowserWindow.instances.at(-1);+ assert.equal(backing.destroyed, false);+ assert(backing.contentView.children.includes(view.parent));+ assert.equal(children.length, 0, "hidden pages cannot cover the main window");+ host.closeSession("session");+ assert.equal(wc.destroyed, true);+ assert.equal(backing.destroyed, true);+ assert.equal(backing.contentView.children.length, 0);+});++test("page-local viewport work restores throttling and resizing on failure", async (t) => {+ const { host, wc, resize } = await harness(t);+ const paneSurface = WebContentsView.instances.at(-1).parent;+ host.setChromeSurface(null);+ const started = once(wc, "capture-start");+ const failed = assert.rejects(host.screenshot({}, "session"), /fixture failure/);+ await started;+ assert.equal(wc.getBackgroundThrottling(), false);+ wc.captures[0].reject(new Error("fixture failure"));+ await failed;+ assert.equal(wc.getBackgroundThrottling(), true);+ assert.equal(paneSurface.parent.children.includes(paneSurface), true);+ host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true,+ bounds: { x: 0, y: 0, width: 1200, height: 900 } });+ resize(920, 610);+ assert.deepEqual(wc.viewport, { width: 920, height: 610 });+});diff --git a/apps/desktop/test/browser-cdp-deadline.test.mjs b/apps/desktop/test/browser-cdp-deadline.test.mjsindex 0a40deb2f..1fc77a7ce 100644--- a/apps/desktop/test/browser-cdp-deadline.test.mjs+++ b/apps/desktop/test/browser-cdp-deadline.test.mjs@@ -55,6 +55,7 @@ function harness() {webContents: wc,invalidateNavigation: () => {},captureScreenshot: (run) => run(wc),+ withStableViewport: (run) => run(wc),navigateAndWait(target) {const done = deferred();loads.push({ target, pane, finish() {diff --git a/apps/desktop/test/browser-host-session.test.mjs b/apps/desktop/test/browser-host-session.test.mjsindex e92a87309..27b7f0105 100644--- a/apps/desktop/test/browser-host-session.test.mjs+++ b/apps/desktop/test/browser-host-session.test.mjs@@ -69,39 +69,36 @@ test("BrowserPreview prepares a new resource tab without navigating or rewritingassert.equal(h.loads.length, 2, "switching back must reuse the page");});-test("background navigation targets that session's last selected tab", async () => {+test("background navigation runs in that session's last selected tab", async () => {const h = harness(); await open(h, "A", "a", "A.html");await open(h, "B", "b", "B.html");h.host.setChromeSession("A", "a");- await h.host.navigate({ url: "https://fixture.invalid/new-b" }, "B");- h.loads[1].finish(); // A late native state update cannot overwrite the queued URL.- assert.equal(h.host.getState().url, "A.html");- assert.equal(h.loads.length, 2);- h.host.setChromeSession("B", "b", "B.html");+ const navigation = h.host.navigate({ url: "https://fixture.invalid/new-b" }, "B");h.roots.at(-1).resolve("/projects/B"); await settled();assert.equal(h.loads.at(-1).target, "https://fixture.invalid/new-b");- h.loads.at(-1).finish(); await settled();- assert.equal(h.host.getState().url, "https://fixture.invalid/new-b");- h.host.setChromeSession("D", "d", "old-d.html");- h.roots.at(-1).resolve("/projects/D"); await settled();- const pendingLoad = h.loads.at(-1);- h.host.setChromeSession("A", "a");- await h.host.navigate({ url: "https://fixture.invalid/new-d" }, "D");- pendingLoad.finish(); await settled();- h.host.setChromeSession("D", "d");- h.roots.at(-1).resolve("/projects/D"); await settled();- assert.equal(h.loads.at(-1).target, "https://fixture.invalid/new-d");- h.loads.at(-1).finish(); await settled();- await h.host.navigate({ url: "https://fixture.invalid/queued" }, "C");- await open(h, "C", "c", "old.html");- assert.equal(h.host.getState().url, "https://fixture.invalid/queued");- h.host.setChromeSession("E"); // A session may exist without a concrete resource tab.- h.host.setChromeSession("A", "a");- await h.host.navigate({ url: "https://fixture.invalid/first-e" }, "E");- await open(h, "E", "e", "old-e.html");- assert.equal(h.host.getState().url, "https://fixture.invalid/first-e");- h.host.setChromeSession("C", "blank");- assert.equal(h.host.getState(), null);+ h.loads.at(-1).finish();+ const state = await navigation;+ assert.equal(state.sessionId, "B");+ assert.equal(state.tabId, "b");+ assert.equal(h.host.getState().url, "A.html");+ h.host.setChromeSession("B", "b");+ assert.equal(h.host.getState().url, state.url);+ assert.equal(h.loads.length, 3, "selecting an already running page must not reload it");+ h.host.dispose();+});++test("the first background navigation creates an isolated tab without UI mounting", async () => {+ const h = harness(); await open(h, "A", "a", "A.html");+ const navigation = h.host.navigate({ url: "https://fixture.invalid/first-c" }, "C");+ assert.equal(h.roots.at(-1).sessionId, "C");+ h.roots.at(-1).resolve("/projects/C"); await settled();+ h.loads.at(-1).finish();+ const state = await navigation;+ assert.equal(state.sessionId, "C");+ assert.equal(state.tabId, "plugin:pi.browser/browser");+ assert.equal(h.host.getState().url, "A.html");+ assert.equal(h.panes.at(-1).visible, false);+ h.host.dispose();});test("a temporary preview uses its own scratch even while a project session is visible", async () => {@@ -221,13 +218,9 @@ test("Browser reveal never steals focus from a different session", async () => {await assert.rejects(reveal, (error) => error?.code === "UNAVAILABLE");});-test("plugin browser operations remain unavailable until the Browser view is visible", async () => {+test("unscoped plugin browser operations still require a visible Browser view", async () => {const h = harness(); await open(h, "A", "a", "A.html");assert.equal(h.host.getStateForPlugin().url, "A.html");- const pendingNavigation = h.host.navigate({ url: "https://fixture.invalid/hidden" });- h.surface(false);- h.roots.at(-1).resolve("/projects/A");- await assert.rejects(pendingNavigation, (error) => error?.code === "UNAVAILABLE");h.surface(false);const unavailable = (error) => error?.code === "UNAVAILABLE";diff --git a/apps/desktop/test/browser-pane-navigation.test.mjs b/apps/desktop/test/browser-pane-navigation.test.mjsindex b19db76f0..f30893bb6 100644--- a/apps/desktop/test/browser-pane-navigation.test.mjs+++ b/apps/desktop/test/browser-pane-navigation.test.mjs@@ -22,9 +22,19 @@ const electron = `data:text/javascript,${encodeURIComponent(`setVisible() {}setBounds() {}}+ export class BrowserWindow {+ contentView = new View();+ destroyed = false;+ constructor(options) { this.size = [options.width, options.height]; }+ getContentSize() { return this.size; }+ setContentSize(width, height) { this.size = [width, height]; }+ isDestroyed() { return this.destroyed; }+ destroy() { this.destroyed = true; }+ }export class WebContentsView {static instances = [];constructor() {+ this.bounds = { x: 0, y: 0, width: 0, height: 0 };this.webContents = Object.assign(new EventEmitter(), {url: "https://fixture.invalid/previous",mainFrame: { processId: 7, routingId: 11 },@@ -45,6 +55,9 @@ const electron = `data:text/javascript,${encodeURIComponent(`});WebContentsView.instances.push(this);}+ getBounds() { return this.bounds; }+ setBounds(bounds) { this.bounds = bounds; }+ setVisible() {}}`)}`;registerHooks({ resolve(specifier, context, next) {diff --git a/apps/desktop/test/browser-preview-tool.test.mjs b/apps/desktop/test/browser-preview-tool.test.mjsindex 59542693a..4f196a261 100644--- a/apps/desktop/test/browser-preview-tool.test.mjs+++ b/apps/desktop/test/browser-preview-tool.test.mjs@@ -72,13 +72,10 @@ test("main serves BrowserPreview from its originating session workspace", asyncassert.match(roots, /return \[path, join\(dataDir, "scratch", sessionId\)\]/);assert.ok(handler.indexOf("resolveLocalFile(raw, root)") <- handler.indexOf("sendToRenderer(IPC.event.browserPreview"),+ handler.indexOf("browserHost.openTab"),);assert.doesNotMatch(handler, /browserPane\.navigate/);- assert.match(- handler,- /sendToRenderer\(IPC\.event\.browserPreview, \{\s*sessionId,\s*path: file,\s*\}\)/,- );+ assert.match(handler, /await browserHost\.openTab\(\{ path: file \}, sessionId\)/);assert.match(protocolSource, /browserPreview: "pi-desktop\/browser\/event\/preview"/);});@@ -139,10 +136,10 @@ test("agent runtime exposes BrowserPreview in every mode and prompts for it", ()assert.match(runtimeSource, /live-reloads/);});-test("Browser tool automatically reveals its view before browser operations", async () => {- assert.match(browserPluginSource, /Browser operations automatically reveal the work-panel view/);- assert.match(browserPluginSource, /Do not ask the user to open Browser manually/);- assert.match(browserPluginSource, /await pi\.browser\.reveal\(\)/);+test("Browser tool uses its connected page without forcing the side panel open", async () => {+ assert.match(browserPluginSource, /side panel is hidden or another session is visible/);+ assert.match(browserPluginSource, /Background operations never take focus/);+ assert.doesNotMatch(browserPluginSource, /await pi\.browser\.reveal\(\)/);let registeredTool;const calls = [];@@ -164,7 +161,7 @@ test("Browser tool automatically reveals its view before browser operations", asconst plugin = await import("../resources/plugins/pi.browser/main.js");await plugin.onLoad();const result = await registeredTool.execute({ action: "snapshot" });- assert.deepEqual(calls, ["reveal", "snapshot"]);+ assert.deepEqual(calls, ["snapshot"]);assert.deepEqual(result, {ok: true,action: "snapshot",diff --git a/apps/desktop/test/browser-tab-restore.test.mjs b/apps/desktop/test/browser-tab-restore.test.mjsnew file mode 100644index 000000000..5b01f04ab--- /dev/null+++ b/apps/desktop/test/browser-tab-restore.test.mjs@@ -0,0 +1,68 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import ts from "typescript";+import * as workPanelResize from "../src/lib/work-panel-resize.ts";+import * as workPanelTabs from "../src/lib/work-panel-tabs.ts";++const { outputText } = ts.transpileModule(readFileSync(new URL("../src/stores/slices/work-panel-slice.ts", import.meta.url), "utf8"), {+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },+});+const imports = {+ "../../lib/api": { api: { pluginViewClose: async () => {} } },+ "../../lib/remote-session-safety": { isRemoteSession: () => false },+ "../../lib/work-panel-tabs": workPanelTabs,+ "../../lib/work-panel-resize": workPanelResize,+};+const module = { exports: {} };+new Function("require", "exports", "module", outputText)((id) => {+ assert.ok(Object.hasOwn(imports, id), `Unexpected import: ${id}`);+ return imports[id];+}, module.exports, module);++function store() {+ let state = {+ activeSessionId: "A", sessions: [], workPanelOpen: false,+ workPanelTabs: [], activeWorkPanelTabId: null, workPanelFileRequest: null,+ workPanelContexts: {},+ };+ const get = () => state;+ const set = (value) => { state = { ...state, ...(typeof value === "function" ? value(state) : value) }; };+ Object.assign(state, module.exports.createWorkPanelSlice({ get, set, isSessionSelectionPending: () => false }));+ return { get, set };+}+const page = (sessionId, tabId, title) => ({ sessionId, tabId, title, url: `https://fixture.invalid/${title}`, isLoading: false, canGoBack: false, canGoForward: false });++test("renderer recovery restores owned Browser tabs without opening a collapsed panel", () => {+ const { get } = store();+ get().restoreBrowserWorkPanelTabs("A", [page("A", "a", "A"), page("B", "b", "B")]);+ assert.deepEqual(get().workPanelTabs.map((tab) => tab.id), ["a"]);+ assert.equal(get().activeWorkPanelTabId, "a");+ assert.equal(get().workPanelOpen, false);+ get().openWorkPanel();+ assert.equal(get().workPanelOpen, true);+ get().collapseWorkPanel();+ assert.equal(get().workPanelContexts.A.tabs[0].id, "a");+});++test("background restore and navigation events only update the owning context", () => {+ const { get } = store();+ get().restoreBrowserWorkPanelTabs("B", [page("B", "b", "B")]);+ assert.deepEqual(get().workPanelTabs, []);+ assert.equal(get().workPanelOpen, false);+ get().updateBrowserWorkPanelTab(page("B", "b", "Updated B"));+ assert.equal(get().workPanelContexts.B.tabs[0].label, "Updated B");+ assert.deepEqual(get().workPanelTabs, []);+});++test("renderer recovery does not duplicate tabs or replace a user-selected resource", () => {+ const { get } = store();+ get().openWorkPanelTab(workPanelTabs.toolWorkPanelTab("review"));+ get().restoreBrowserWorkPanelTabs("A", [page("A", "a", "A")]);+ get().restoreBrowserWorkPanelTabs("A", [page("A", "a", "Old A")]);+ assert.deepEqual(get().workPanelTabs.map((tab) => tab.id), ["review", "a"]);+ assert.equal(get().activeWorkPanelTabId, "review");+ assert.equal(get().workPanelTabs[1].label, "A");+ get().closeWorkPanelTab("a");+ assert.deepEqual(get().workPanelTabs.map((tab) => tab.id), ["review"]);+});diff --git a/apps/desktop/test/main-wiring-contract.test.mjs b/apps/desktop/test/main-wiring-contract.test.mjsindex 0b04a7544..ac75479f3 100644--- a/apps/desktop/test/main-wiring-contract.test.mjs+++ b/apps/desktop/test/main-wiring-contract.test.mjs@@ -185,17 +185,22 @@ test("the IPC registrar passes every required agent IPC dependency", () => {);});-test("browser state reaches every plugin surface", () => {+test("browser metadata stays separate from the selected plugin presentation", () => {const services = read("services/plugin-services.ts");- const state = braceBody(+ const metadata = braceBody(services,services.indexOf("{", services.indexOf("const emitBrowserState")),);- // The renderer plus both plugin surfaces: dropping one of them is silent,- // because each surface simply stops updating.- assert.match(state, /sendToRenderer\(IPC\.event\.browserState, state\)/);- assert.match(state, /pluginPanels\.broadcast\("browser:state", state\)/);- assert.match(state, /pluginViews\.broadcast\("browser:state", state\)/);+ const presentation = braceBody(+ services,+ services.indexOf("{", services.indexOf("const emitBrowserPresentationState")),+ );+ assert.match(metadata, /sendToRenderer\(IPC\.event\.browserState, state\)/);+ assert.doesNotMatch(metadata, /\.broadcast\("browser:state"/);+ assert.match(presentation, /pluginPanels\.broadcast\("browser:state", state\)/);+ assert.match(presentation, /pluginViews\.broadcast\("browser:state", state\)/);+ assert.match(services, /onState: emitBrowserState/);+ assert.match(services, /onPresentationState: emitBrowserPresentationState/);});test("a finished turn is announced to every plugin surface", () => {diff --git a/apps/desktop/test/plugin-tool-invocations.test.mjs b/apps/desktop/test/plugin-tool-invocations.test.mjsindex 079440dfb..4b18aac60 100644--- a/apps/desktop/test/plugin-tool-invocations.test.mjs+++ b/apps/desktop/test/plugin-tool-invocations.test.mjs@@ -53,6 +53,16 @@ const PLUGIN = `ctx.signal.addEventListener("abort", () => aborted.add(ctx.sessionId), { once: true });await pi.desktop.invoke({ operation: "session/get", args: [ctx.sessionId] });if (args.reveal) await pi.browser.reveal();+ if (args.browser) {+ await pi.browser.snapshot();+ await pi.browser.click({ uid: "e1" });+ await pi.browser.fill({ uid: "e1", text: ctx.sessionId });+ await pi.browser.evaluate({ expression: "document.title" });+ await pi.browser.screenshot();+ await pi.browser.console({ limit: 10 });+ await pi.browser.cdp({ method: "Page.enable" });+ await pi.browser.getState();+ }if (args.wait) {return new Promise((resolve) => {const finish = () => { aborted.add(ctx.sessionId); resolve({ aborted: true }); };@@ -84,6 +94,7 @@ async function fixture(t, onInvoke) {writeFileSync(join(dir, "main.js"), PLUGIN);const calls = [];const reveals = [];+ const browserCalls = [];const runtime = new PluginRuntime({hostEntry,spawnProcess({ entry }) {@@ -101,6 +112,14 @@ async function fixture(t, onInvoke) {},browser: {async reveal(sessionId) { reveals.push(sessionId); },+ async snapshot(sessionId) { browserCalls.push(["snapshot", sessionId]); return {}; },+ async click(_uid, sessionId) { browserCalls.push(["click", sessionId]); },+ async fill(_uid, _text, sessionId) { browserCalls.push(["fill", sessionId]); },+ async evaluate(_expression, sessionId) { browserCalls.push(["evaluate", sessionId]); },+ async screenshot(_input, sessionId) { browserCalls.push(["screenshot", sessionId]); return {}; },+ console(_limit, sessionId) { browserCalls.push(["console", sessionId]); return {}; },+ async cdp(_method, _params, sessionId) { browserCalls.push(["cdp", sessionId]); },+ getState(sessionId) { browserCalls.push(["getState", sessionId]); return {}; },},getSessionContext: async (sessionId) => ({ sessionId, messages: [], truncated: false }),});@@ -108,7 +127,7 @@ async function fixture(t, onInvoke) {await runtime.loadFromPath(dir, permissions);const tool = runtime.getTools().find((entry) => entry.name === "probe");assert.ok(tool);- return { id, runtime, tool, calls, reveals };+ return { id, runtime, tool, calls, reveals, browserCalls };}test("browser.reveal reaches Main with the invoking session context", { timeout: 5000 }, async (t) => {@@ -118,6 +137,19 @@ test("browser.reveal reaches Main with the invoking session context", { timeout:assert.deepEqual(reveals, ["session-b"]);});+test("every Browser API forwards trusted invocation identity across the real plugin process", { timeout: 5000 }, async (t) => {+ const { tool, browserCalls, reveals } = await fixture(t, async () => ({}));+ await Promise.all([+ tool.execute({ browser: true, sessionId: "spoofed-b" }, { sessionId: "A" }),+ tool.execute({ browser: true, sessionId: "spoofed-a" }, { sessionId: "B" }),+ ]);+ const expected = ["snapshot", "click", "fill", "evaluate", "screenshot", "console", "cdp", "getState"];+ assert.deepEqual(browserCalls.filter(([, id]) => id === "A").map(([method]) => method), expected);+ assert.deepEqual(browserCalls.filter(([, id]) => id === "B").map(([method]) => method), expected);+ assert.equal(browserCalls.length, expected.length * 2);+ assert.deepEqual(reveals, []);+});+test("real plugin calls keep sender identity through concurrent out-of-order completion", { timeout: 5000 }, async (t) => {const enteredA = deferred();const enteredB = deferred();diff --git a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md b/docs/adr/0170-work-panel-browser-as-bundled-plugin.mdindex b0dc8c84e..6aeb1a09e 100644--- a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md+++ b/docs/adr/0170-work-panel-browser-as-bundled-plugin.md@@ -37,11 +37,12 @@ guest.network-interception methods are refused. No DevTools websocket is exposed.5. **Host `BrowserPreview` remains a thin facade** (Plan/subagent namestability). It errors if `pi.browser` is disabled; otherwise it loads the- workspace file into the guest and reveals the plugin view. The bundled- Browser agent tool calls `pi.browser.reveal()` before page operations; the- host opens the originating session's existing Browser tab and waits for its- view to become visible. Background sessions never take focus. Plugin CDP- stays Agent-only (`plugin_*`).+ workspace file into a session-owned guest and requests its side-panel tab.+ [Background browser pages](browser-background-lifecycle.md) supersedes the+ visible-before-operation requirement: the bundled tool uses a trusted+ session connection without calling `reveal()` before every operation.+ Explicit `reveal()` remains a presentation API. Background work never+ takes focus; existing Plan/Goal action restrictions remain intact.6. The original singleton guest decision is superseded by[Retain a host-owned browser page per resource tab](retained-browser-pages-per-tab.md).BrowserHost now retains one page per session/tab while plugin chrome remains@@ -56,8 +57,9 @@ superseded: the panel's launchable surfaces are plugin views.- Disabling `pi.browser` removes the launcher row, agent CDP, and guest. URLchips fall back to `openExternal`. `BrowserPreview` fails closed.-- Third-party plugins with `browser.cdp` address the current browser page;- bounds remain clamped to the active browser chrome.+- Tools with `browser.cdp` address their invoking session's connected page;+ unscoped plugin UI calls still require the current visible Browser view.+ Bounds remain clamped to the active browser chrome.- Plan still sees `BrowserPreview`. The Browser plugin tool is also visible in Plan/Goal for the four `planSafeActions` (`navigate`, `snapshot`, `screenshot`, `console`); click/fill/evaluate/cdp stay Agent-only (ADR 0211).## Alternatives considereddiff --git a/docs/adr/README.md b/docs/adr/README.mdindex bae232b03..4677e3c53 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -20,6 +20,7 @@ Each ADR includes:| ID | Title | Status ||---|---|---|+| browser-background-lifecycle | [Browser page execution outlives side-panel presentation](browser-background-lifecycle.md) | Accepted || asktool-draft-survives-session-switch | [AskTool drafts survive a card remount](asktool-draft-survives-session-switch.md) | Accepted || tool-abort-abandons-host-call | [A user stop ends the turn even when the running tool cannot be cancelled](tool-abort-abandons-host-call.md) | Accepted for implementation || provider-metadata-client-certificate-retry | [Provider metadata recovery from optional client certificates](provider-metadata-client-certificate-retry.md) | Implemented candidate |diff --git a/docs/adr/browser-background-lifecycle.md b/docs/adr/browser-background-lifecycle.mdnew file mode 100644index 000000000..c853de8b9--- /dev/null+++ b/docs/adr/browser-background-lifecycle.md@@ -0,0 +1,72 @@+# ADR: Browser page execution outlives side-panel presentation++- Status: Accepted+- Date: 2026-10-17+- Amends: [ADR 0170](0170-work-panel-browser-as-bundled-plugin.md) and+ [retained resource pages](retained-browser-pages-per-tab.md)++## Context++Main already retains one BrowserPane and CDP session per conversation/resource+page. Tool execution nevertheless depended on the shared visible browser chrome,+and the bundled Browser tool called `reveal()` before every action. Switching+conversations or collapsing the side panel therefore made a retained page+unusable. Renderer reload also disposed every guest, discarding live forms.++Moving the browser elsewhere would not remove those dependencies. The requested+layout keeps it in the side panel while making execution independent of UI+mounting and visibility.++## Decision++Main owns live pages and their execution. The renderer owns only presentation:+measured bounds, visible page selection and side-panel tabs.++- Every tool API derives its session from the trusted in-flight invocation and+ resolves that session's connected page. It never falls back to another+ conversation's visible page. A first navigation or BrowserPreview establishes+ a connection; viewing another tab does not change an established connection.+- Navigation starts immediately in Main, including in background conversations.+ BrowserPreview creates a new host page before requesting its renderer tab.+ Continuing operations do not reopen a collapsed panel or steal focus.+- Background page metadata updates the originating renderer context. The shared+ plugin chrome receives only presentation-selected page state, so background+ navigation cannot repaint another page or alter its native bounds.+- Unknown/closed targets fail with `UNAVAILABLE`. A new navigation or preview can+ establish a new connection; arbitrary cross-session sharing is not introduced.+- Explicit `reveal()` remains a presentation API with its existing visible-view+ acknowledgement. Unscoped plugin UI calls keep their visible-page boundary.+- Hidden pages are parked in a lazy, invisible sandboxed BrowserWindow owned by+ BrowserBackingHost, keeping Chromium's render/input widget connected while the+ side-panel container is unmounted. Showing a page moves its same native view+ back to the measured side-panel hole; neither a new visible window nor a second+ page is created. The backing window is released when no parked pages remain.+- Host-only focus emulation and page-relative target coordinates make background+ input reliable without native focus or extending the public raw-CDP allowlist.+ Pointer/capture work shares a page-local viewport queue and restores throttling+ and pending bounds after success, failure or timeout.+- Renderer reload hides and detaches presentation, not pages. An additive,+ session-filtered `browser/getPages` IPC returns BrowserState metadata; the+ renderer restores missing tabs without reopening the panel or replacing a+ user-selected resource. Stale restore results are discarded.+- Explicit tab/session closure, plugin disable/unload, window destruction and+ app shutdown release the corresponding pages, debugger state and watchers.++The process model, browser plugin contract, URL/file-root gates, permission+checks, raw-CDP allowlist, cookie partition, tool modes and screenshot deadlines+remain unchanged. There is no database migration or restart DOM persistence.++## Alternatives++Keeping the visibility dependency forces users to babysit a background task.+Making all plugin calls globally address the current page would permit accidental+cross-session reads and actions. Moving the browser to a new window would add a+presentation lifecycle without solving either issue.++## Consequences++Users can collapse the side panel, view another conversation or Settings, and+reload the shell while the original browser remains usable. Memory stays allocated+until its explicit owner closes it; restart and guest-crash recovery do not promise+unsaved DOM preservation. Tests cover real BrowserHost/CDP wiring, plugin process+identity, renderer tab restoration and isolated Chromium input/screenshots.diff --git a/docs/adr/retained-browser-pages-per-tab.md b/docs/adr/retained-browser-pages-per-tab.mdindex 43a44485e..813af96b1 100644--- a/docs/adr/retained-browser-pages-per-tab.md+++ b/docs/adr/retained-browser-pages-per-tab.md@@ -20,20 +20,20 @@ Only the selected page is attached to the measured browser hole; hidden pagesretain their WebContents and use Chromium background throttling. The browserpartition and existing URL, permission, file-root and CDP allowlists stay intact.-BrowserPreview validates the request and asks the renderer to open a new resource-tab. Only that tab starts its navigation. Background browser.navigate records an-intent for the session's last selected tab; before a session has a tab, its first-tab consumes that intent once. Older load completion cannot overwrite an intent.+BrowserPreview validates the request and asks BrowserHost to create and load a+new resource page before its renderer tab mounts. Background browser.navigate+runs immediately in its session's connected page. Presentation selection and+the tool connection are independent; see [background lifecycle](browser-background-lifecycle.md).An empty tab has no inherited native page state. Bundled browser chrome tagsits navigation/action requests with the owning session/tab; a delayed replycannot repaint another tab. Agent-facing methods retain runtime-owned sessionidentity rather than accepting these UI routing fields.Closing a tab releases its page and CDP state. Session deletion, plugin disposal,-renderer reload, window destruction and application shutdown release the corresponding pages.-This iteration does not automatically evict pages or persist their DOM across-application restarts. Navigation/reload can still reset state as on a normal-browser, and page crashes do not promise preservation of unsaved form data.+window destruction and application shutdown release the corresponding pages.+Renderer reload now only detaches presentation; Main retains pages and exposes+their metadata for restoring side-panel tabs. Application restart does not+persist arbitrary DOM, and page crashes do not promise unsaved-form recovery.## Alternativesdiff --git a/docs/project/browser-background-trial.md b/docs/project/browser-background-trial.mdnew file mode 100644index 000000000..84029d6d4--- /dev/null+++ b/docs/project/browser-background-trial.md@@ -0,0 +1,60 @@+# Browser background lifecycle trial++## Candidate++- Branch: `feat/browser-background-lifecycle`+- Worktree: `worktrees/browser-background`+- Base main: `36e19eb59b9b4e0cab1e2d47b8bcb70304ddad60`+- The user approved landing the validated browser changes through a pull request.+- The primary checkout was not modified.++## Behavior++The Browser stays in the side work panel. Main owns its session-connected page+independently of panel visibility, conversation selection and renderer mounting.+Hidden pages use an invisible sandboxed backing host. Background tools do not+retarget the visible conversation or reopen its side panel. Shell reload restores+live page metadata without reloading its DOM. Explicit page/session closure,+plugin disable and app/window shutdown still release resources.++## Verification performed++- Desktop targeted Node tests: **185 passed** across `browser-*.test.mjs`,+ `plugin-tool-invocations.test.mjs` and `work-panel*.test.mjs`.+- Shared protocol contract tests: **15 passed** (`src/protocol.test.ts`).+- Landing preparation: the complete Desktop suite passed **4305 tests** with+ 3 environment-dependent skips; the Shared suite passed **1281 tests**.+- Documentation locale/structure checks and VitePress site build passed.+- Desktop TypeScript typecheck: passed.+- Workspace TypeScript dependencies and Electron/Vite build: passed.+- Biome lint and style-token guard: passed; no automatic fixes applied.+- `git diff --check` and PR-base ancestry check: passed on the base above.+- Isolated native Electron suites: `e2e-browser-background.mjs`,+ `e2e-browser-capture-resize.mjs` and `e2e-browser-local-file-access.mjs` passed.+- Actual Desktop user path on the refreshed candidate: Composer submission,+ ToolSearch, Browser tool, plugin child process, sidecar and Host used their+ production wiring. After A's snapshot, selection changed to B; A filled its+ form, clicked its button, captured a screenshot and completed while B remained+ visible. Returning to A showed the retained page.+- Actual recovery path: collapse the side panel, enter Settings, reload using+ native CDP `Page.reload`, select A and reopen the panel. Native page identity,+ `A: Background OK` input and button count `1` were preserved.++## Environment and limitations++Electron 43.6.0 / Chromium 150.0.7871.250, Node 24.14.0; dependencies and the+compatible Rust Host binary were reused from the primary development environment.+Build outputs stayed in the task worktree. Profiles, synthetic sessions, localhost+model fixture, logs and screenshots stayed in session scratch. No real provider,+user credentials or paid API was used.++Package-manager commands could not use the linked dependency topology, so the+installed TypeScript/Electron/Vitest tools were invoked directly. No second+installation was created. `verify:ui:*` and Rust source validation were not run;+the Rust source was unchanged. An optional+secondary review was cancelled without a final report; no review result is+claimed.++There is no restart DOM persistence or automatic cross-session page sharing.+Retained pages consume memory until explicitly closed. This record covers the+isolated candidate validation; PR integration checks are recorded in the PR.diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex da447d18c..a208cffd2 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -4,3 +4,9 @@1.1.0 to 1.3.0. Preserve Desktop compatibility patches, omit foreign-modelthinking from replay, reject malformed final tool JSON before execution, andexpose the user-run discriminator to trusted extension startup handlers.+- Keep each session's side-panel browser available while the panel is collapsed,+ another conversation or Settings is visible, or the renderer reloads. Browser+ actions stay on their connected page without stealing focus. Hidden pages use+ an invisible sandboxed backing host; explicit page/session closure and plugin+ disable still release resources. Browser page-count indicators are not part of+ this change.diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 1abc005b8..2035a0a20 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1858,8 +1858,8 @@ through `session.get`, allowing its project-group folders (or its isolatedworktree) and its own `<data_dir>/scratch/<sessionId>` directory. A temporaryconversation needs no workspace to preview its generated HTML. A missingsession fails explicitly; a background preview never inherits the visible-session's roots. BrowserPreview validates realpath containment before emitting-the absolute path to the existing resource-tab owner. Chat links to other+session's roots. BrowserPreview validates realpath containment before creating+its host-owned page and emitting the corresponding resource-tab identity.sessions' scratch files and attachments retain the read-only file surface.This does not restrict the Browser's explicit absolute-path / `file:` addressentry or local-page navigation, which follow its existing local-file policy.@@ -1889,12 +1889,15 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:tab id is supplied). The shared plugin chrome is not closed with a sibling page.- event: `browser/event/state {url, title, isLoading, canGoBack, canGoForward, loadError?, sessionId?, tabId?}`(also pushed to plugin views as `browser:state`)-- agent preview event: `browser/event/preview {sessionId, path?, url?}`.- Electron Main validates a workspace `path` inside that session's project,- asks the renderer to create a Browser resource tab before navigation, with- `location` in the matching- runtime panel context. Navigation of a background session does not steal the- visible guest.+- `browser/getPages({sessionId})` → `BrowserState[]`. Returns only that session's+ retained page metadata for shell-reload recovery, including blank/loading tabs.+ It never returns DOM, credentials, another session's pages or shared plugin state.+- agent preview event: `browser/event/preview {sessionId, tabId?, path?, url?, revealOnly?}`.+ Electron Main validates a workspace `path`, starts its own resource page and+ requests the corresponding renderer tab. Page execution does not wait for UI+ mounting. Continuing operations use a trusted session connection rather than+ visible selection. Explicit reveal remains presentation-only; background work+ never steals focus. Shell reload hides presentation without destroying pages.- plugin file action: `browser/event/openFile {path}`. Electron Main emits thisonly after the plugin's `fs.openInBrowser` request passes its declared`fs.read` scope and HTML-file checks. The renderer opens the absolute path in adiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 4b95cd6ec..4a1a103ce 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1166,8 +1166,8 @@ entirely inside the plugin's isolated page:stays hidden until its current main-frame navigation commits. Root lookup or loadcompletion from a superseded request cannot navigate, reveal, or publish theold session as current. A session without a remembered preview stays empty;- closing the panel or disposing the guest wins over pending work. Normal- navigation within the same session retains that session's visible content.+ collapsing the panel hides presentation without canceling owned page work.+ Normal navigation within the same session retains that session's visible content.The address bar immediately shows loading feedback. A current main-frame commitreveals the page without waiting for images or subframes; those continue todrive the loading/stop control. A failed switch or one exceeding the 15-second@@ -1195,9 +1195,16 @@ entirely inside the plugin's isolated page:ordinary in-page navigation stay in the current tab. Website new-window linksfollow Link open destination: another work-panel tab, or the system browser.-- BrowserPreview creates its resource tab before navigating and never rewrites- the prior tab. A background navigation is retained for its session's selected- tab (or consumed once by its first tab). A new blank tab reports empty state.+- BrowserPreview creates and loads its host-owned page before requesting its+ side-panel resource tab; it never rewrites the prior tab. Background navigation+ runs immediately in the calling session's connected page. A blank tab stays empty.+- The browser stays in the side panel. Collapsing it, switching conversations,+ navigating to Settings, unmounting chrome or reloading the shell does not stop+ a retained page or its AI operations. Main detaches presentation on shell reload+ and provides session-owned metadata to restore tabs without reopening the panel.+ AI connections do not follow presentation selection once established. Unknown+ or closed targets fail rather than borrowing the visible page. Explicit tab or+ session close, plugin disable, window destruction and app shutdown release pages.- Main-frame same-document navigation (fragment links and History API routes) updatesthe browser address, history controls, and loading state without requiring adiff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 9498d8900..027ca8fd4 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -610,6 +610,11 @@ may be retained while exactly one workspace supplies the visible shell context.switching back restores it; selecting a workspace without an activeconversation hides the panel. Session/workspace identity remains attached toevery relative resource, preventing cross-context reinterpretation.+- Browser page execution is Main-owned, independent of the side panel's+ presentation lifecycle. Hidden/background tool operations keep their trusted+ session connection and never reveal or retarget the visible page. A shell+ reload detaches presentation; selecting a session restores its live Browser+ tab metadata without changing the panel's collapsed state.- Relaunch discards every session context, including Browser resources; onlythe committed preferred panel width persists. Native window state is storedindependently from normal bounds, including when the app closes whilediff --git a/docs/spec/05-security/01-security.md b/docs/spec/05-security/01-security.mdindex 4bc397a94..2acb0ec53 100644--- a/docs/spec/05-security/01-security.md+++ b/docs/spec/05-security/01-security.md@@ -49,6 +49,15 @@ cannot use a file link to escape the workspace. This local-file browsing iscovered by the high-risk `browser.cdp` capability; `BrowserPreview` and thesidecar's workspace file resolver remain restricted to the session workspace.+Browser tool calls derive page identity from the trusted in-flight invocation,+not plugin arguments or the currently visible page. Session-owned CDP works+while hidden; unscoped plugin UI calls remain visibility-gated. Unknown or closed+targets fail closed. Hidden guests are hosted by an invisible sandboxed backing+window with no Node integration or elevated preload. Host-only focus emulation+enables input without presenting or focusing a window or extending the raw CDP+allowlist. Closing the last parked page releases the backing host. Cookie,+storage, Target and network-interception methods remain denied.+### Content Security Policy- Dev: `script-src 'self' 'unsafe-inline' 'unsafe-eval'` (required by Vitediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 54f78d31c..3026851c3 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1859,23 +1859,22 @@ identify the platform validation still needed.2) With the work panel closed, ask the agent to preview a workspace HTMLfile (`BrowserPreview`) and verify the Browser tab opens in the visible workpanel. 3) Use ToolSearch `cdp` / `Browser` to snapshot and interact while the- panel remains visible. 4) With the work panel closed, call the plugin- Browser tool for an HTTP(S) URL and verify it activates the existing Browser- tab before navigating. 5) Switch to a second session and call Browser;- verify it opens that session's own page, then switch back and verify the first- page is retained. 6) Run Browser from a background session and verify it does- not steal focus. 7) Switch to Plan and call the plugin Browser tool. 8) Disable+ panel remains visible. 4) Collapse the panel and continue Browser snapshot,+ click/fill, screenshot and navigation. 5) Switch to a second session and call+ Browser; verify it uses that session's own page. 6) Continue the first session's+ Browser actions while the second session is visible; reload the shell and+ return to the first page. 7) In Plan/Goal, exercise the read-only Browser+ actions and verify mutating actions remain denied. 8) Disable`pi.browser`. 9) Call `BrowserPreview` and click an http(s) transcript link.10) From a third-party or test caller, send`Network.getAllCookies` through `pi.browser.cdp`.- **Expected**: The launcher has no host Browser row. Preview opens the plugin- view, reveals the work panel, and live-reloads the file. Browser operations- run only after the originating session's view is visible; the agent opens it- automatically and waits for readiness. A background session does not change- the visible tab and receives `UNAVAILABLE` if it cannot be revealed. Plugin- tool `plugin_pi_browser_Browser` can snapshot- after ToolSearch. Plan denies the plugin tool- (`PLUGIN_DISABLED_IN_PLAN`) while `BrowserPreview` remains callable. Disable+ view, reveals the work panel, and live-reloads the file. Session-owned Browser+ operations run in the background without opening the panel, borrowing another+ page, or changing focus. Shell reload retains the native page and form data;+ its side-panel tabs can be restored. ToolSearch activates the Browser tool.+ Plan/Goal allow navigate/snapshot/screenshot/console; click/fill/evaluate/cdp+ remain denied. Disablehides the view and tools; `BrowserPreview` errors; http(s) chips use`openExternal`. Cookie CDP is denied. Guest bounds stay inside the pluginview.@@ -5006,10 +5005,10 @@ window; opening a normal panel afterward must still work.does not create a work-panel tab. Session switches and invalid schemes retaintheir security and visibility gates.- **Additional paths**: Invoke BrowserPreview through ToolSearch/BrowserPreview- while a tab has unsent form input: only a new tab navigates. Queue navigation- for an inactive session with an existing tab, then return and verify the queued- destination wins over an old load completion. Open a blank tab and inspect its- empty address and state. Close a background tab and verify its WebContents is+ while a tab has unsent form input: only a new host-owned page navigates, before+ its renderer tab mounts. Navigate for an inactive session and verify immediate+ execution in its connected page without changing the visible one. Open a blank+ tab and inspect its empty address and state. Close a background tab and verify its WebContents isdestroyed without affecting its sibling; deleting a session and plugin/windowdisposal release the appropriate retained pages.- **Status**: Targeted isolated Electron validation; no new repository test suite.@@ -5028,6 +5027,31 @@ window; opening a normal panel afterward must still work.isolation; native Electron click-through for actual same-document events.- **Specs linked**: `04-ux/08-component-spec.md` §5.3.+#### E2E-BROWSER-background-lifecycle: Side-panel presentation does not own page execution++- **Preconditions**: Dedicated worktree, reused Electron/toolchain, isolated+ profile and localhost A/B/C pages. No real account or paid provider requests.+- **Steps**: Snapshot A, switch to B, fill and click A through production CDP,+ then start a new hidden screenshot. Detach presentation, reload the renderer,+ repeat A's snapshot/screenshot and restore its tab. Open a first C preview+ before UI mounting. Close C and try unknown/closed targets. Exercise every+ Browser API through real concurrent plugin invocations with spoofed argument+ identities. Restore missing renderer tabs while the panel is collapsed.+- **Expected**: A's actions, pixels and screenshot path belong to A; B is+ unchanged and remains the only visible guest. No background action reveals+ a page. Renderer reload retains native identity and inputs. C executes before+ mounting. Unknown/closed targets fail without fallback. Restored tabs are+ scoped, duplicate-free and do not reopen or replace a user's selected resource.+ Hidden backing hosts remain invisible and release with the last parked page.+- **Automation**: `node scripts/e2e-browser-background.mjs`,+ `browser-background-session.test.mjs`, `browser-tab-restore.test.mjs`,+ `browser-capture-resize.test.mjs`, and `plugin-tool-invocations.test.mjs`.+ The isolated Desktop trial also uses real Composer, sidecar, plugin and Host+ wiring with a localhost SSE model; no real provider is contacted.+- **Specs**: `04-ux/08-component-spec.md`, `07-plugins/03-plugin-api.md`,+ `05-security/01-security.md`, [background lifecycle ADR](../../adr/browser-background-lifecycle.md).+- **Status**: Automated native Chromium/service paths; isolated Desktop trial passed.+#### E2E-060: Files tab browsing stays inside the workspace- **Preconditions**: Workspace with file artifacts for nested source, largediff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 041dea630..28eefe320 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -958,6 +958,10 @@ pi.browser.cdp(input: { method: string; params?: unknown }): Promise<unknown>`navigate` returns when the current main-frame navigation commits, includingredirects; it does not wait for slow images or subframes. `browser:state` reportsloading immediately and optionally includes `loadError` for failed navigation.+Renderer page metadata stays session-scoped in background `browser/event/state`+updates; the shared `browser:state` plugin chrome feed includes only the page+currently selected for presentation. Background events cannot retarget the+address bar or issue bounds/visibility updates for another page.Optional `sessionId` and `tabId` identify the host-owned work-panel destination;plugins do not select these identities through navigation arguments.With the high-risk `browser.cdp` permission, `navigate` may open an existing@@ -966,21 +970,34 @@ workspace-scoped. A local file page may navigate to other existing local files;web pages retain only the prior in-workspace file-navigation allowance.The current guest page is a host-owned `WebContentsView` (`persist:work-browser`).-Each resource tab retains its own page. A navigation for a background session is-queued for that session's last selected tab, or its first tab when none exists.-It does not navigate or return another session's visible page.+Each resource tab retains its own page. Agent navigation executes immediately+in the calling session's connected page, even when its panel is hidden or a+different session is visible. It never returns or navigates another session's page.`setBounds` is content-relative to the calling plugin view and is clamped sothe guest cannot cover chat/composer. `cdp` is deny-by-default; cookie,storage, target, and network-interception methods fail with`PERMISSION_DENIED`. Session identity for agent calls comes from the in-flight`plugins.execute` `sessionId`, not from plugin arguments (D333 / ADR 0170).-Page operations (`navigate`, `action`, `openExternal`, `getState`, snapshot,-screenshot, and CDP calls) are available only while the Browser view is-visible. `reveal()` asks the host to activate the Browser tab for the calling-session and resolves only after that session's view is visible. A background-session never takes focus; if it cannot become visible, `reveal()` fails with-`UNAVAILABLE`. The bundled Browser agent tool calls `reveal()` before each-operation. `BrowserPreview` remains the live-reloading workspace-file preview.+The host binds every agent page operation to the trusted in-flight tool session.+The first navigation or BrowserPreview connects a page; browsing another side-panel+tab does not retarget an established connection. A closed target fails with+`UNAVAILABLE` until another navigation or preview connects a page. Unscoped plugin+UI calls keep their visible-page requirement. The bundled Browser tool does not+call `reveal()` before operations; an explicit `reveal()` still waits for the+calling session's visible tab and never takes focus from a background session.+Renderer reload detaches only presentation. Main retains live pages, inputs,+history and CDP; session-scoped metadata restores the side-panel tabs without+opening a collapsed panel. Closing a tab/session, disabling the plugin, window+destruction or app shutdown releases the relevant pages. No restart DOM recovery+or cross-session page sharing is introduced.+Hidden guests are parked in a lazy, invisible sandboxed backing window, keeping+Chromium's input/capture widget connected without a visible window or native focus.+The same view moves back to the side panel on show; closing the last parked page+releases the backing window. Host-only focus emulation and page-relative target+coordinates do not expand raw-CDP permissions. Pointer/capture work pins the+viewport per page, temporarily disables throttling and restores it on completion.+`BrowserPreview` remains confined to its session's workspace/scratch roots and+loads independently of renderer mounting.Full-page `screenshot` captures are proportionally scaled to no more than1280×2048 output pixels. Viewport screenshots and raw `Page.captureScreenshot`diff --git a/package.json b/package.jsonindex 8927d08ac..b83fc31e7 100644--- a/package.json+++ b/package.json@@ -65,6 +65,7 @@"test:e2e:window-surface": "node scripts/e2e-window-surface.mjs","test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs","test:e2e:browser-local-files": "node scripts/e2e-browser-local-file-access.mjs",+ "test:e2e:browser-background": "node scripts/e2e-browser-background.mjs","test:e2e:work-panel-drag": "node scripts/e2e-work-panel-drag.mjs","test:e2e:work-panel-tab-close": "node scripts/e2e-work-panel-tab-close.mjs","test:e2e:supervision": "node scripts/e2e-supervision.mjs",diff --git a/packages/shared/src/protocol.test.ts b/packages/shared/src/protocol.test.tsindex 6c6a0cb2b..f8e4c7c79 100644--- a/packages/shared/src/protocol.test.ts+++ b/packages/shared/src/protocol.test.ts@@ -30,6 +30,13 @@ import {type ToolsOutputParams,} from "./index.js";+describe("Browser recovery IPC", () => {+ it("admits the additive session-owned page metadata channel", () => {+ expect(IPC.invoke.browserGetPages).toBe("pi-desktop/browser/getPages");+ expect(IPC_WHITELIST.has(IPC.invoke.browserGetPages)).toBe(true);+ });+});+describe("Plan protocol contracts", () => {it("uses protocol v11/schema v16 and exposes the plan, schedule, and shell channels", () => {expect(PROTOCOL_VERSION).toBe(11);diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 2aec120dd..68743b3f2 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -416,6 +416,7 @@ export const IPC = {browserSetVisible: "pi-desktop/browser/setVisible",browserOpenExternal: "pi-desktop/browser/openExternal",browserGetState: "pi-desktop/browser/getState",+ browserGetPages: "pi-desktop/browser/getPages",fsList: "pi-desktop/fs/list",fsRead: "pi-desktop/fs/read",fsReadImageDataUrl: "pi-desktop/fs/readImageDataUrl",diff --git a/scripts/e2e-browser-background.mjs b/scripts/e2e-browser-background.mjsnew file mode 100644index 000000000..2a2cf6321--- /dev/null+++ b/scripts/e2e-browser-background.mjs@@ -0,0 +1,32 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdtempSync } from "node:fs";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const dependencyRoot = process.env.E2E_DEPENDENCY_ROOT || root;+const require = createRequire(join(dependencyRoot, "packages/agent-runtime/package.json"));+const { build } = require("esbuild");+const { electronBinary } = resolveElectronBinary(dependencyRoot);+const artifacts = mkdtempSync(join(tmpdir(), "pi-browser-background-"));+const main = join(artifacts, "main.cjs");+await build({ entryPoints: [join(root, "scripts/e2e/browser-background-session.ts")],+ outfile: main, bundle: true, platform: "node", format: "cjs", external: ["electron"] });+const env = { ...process.env, BROWSER_BACKGROUND_ARTIFACT_DIR: artifacts };+delete env.ELECTRON_RUN_AS_NODE;+const child = spawn(electronBinary, [main], { env, stdio: ["ignore", "pipe", "pipe"] });+let output = "";+for (const stream of [child.stdout, child.stderr]) stream.on("data", (data) => { output += data; });+const timeout = setTimeout(() => child.kill(), 90_000);+let code;+try {+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });+} finally { clearTimeout(timeout); }+console.log(`Browser background artifacts retained at ${artifacts}`);+console.log(output.trim());+assert.equal(code, 0, "native browser background regression failed");+assert.match(output, /BROWSER_BACKGROUND {"ok":true/);diff --git a/scripts/e2e/browser-background-session.ts b/scripts/e2e/browser-background-session.tsnew file mode 100644index 000000000..eefc90433--- /dev/null+++ b/scripts/e2e/browser-background-session.ts@@ -0,0 +1,128 @@+import assert from "node:assert/strict";+import { once } from "node:events";+import { mkdirSync, writeFileSync } from "node:fs";+import { createServer } from "node:http";+import { join } from "node:path";+import { app, BrowserWindow, nativeImage, WebContentsView, type View } from "electron";+import { BrowserHost } from "../../apps/desktop/electron/main/browser-host";+import { BrowserPane } from "../../apps/desktop/electron/main/browser-view";++const output = process.env.BROWSER_BACKGROUND_ARTIFACT_DIR;+if (!output) throw new Error("BROWSER_BACKGROUND_ARTIFACT_DIR is required");+app.setPath("userData", join(output, "profile"));++async function probe(output: string) {+ const server = createServer((request, response) => {+ const name = request.url === "/b" ? "B" : request.url === "/c" ? "C" : "A";+ response.setHeader("Content-Type", "text/html; charset=utf-8");+ response.end(`<!doctype html><meta charset="utf-8"><title>Page ${name}</title>+ <style>body{margin:0;padding:32px;box-sizing:border-box;min-height:700px;background:${name === "B" ? "rgb(177,77,47)" : "rgb(45,107,199)"};color:white;font:24px sans-serif}button,input{font:20px sans-serif;margin:8px;padding:12px}</style>+ <h1>Page ${name}</h1><label for="note">Note ${name}</label><input id="note">+ <button onclick="document.querySelector('output').textContent=String(++window.count)">Increment ${name}</button><output>0</output><script>window.count=0</script>`);+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const address = server.address();+ assert(address && typeof address !== "string");+ const origin = `http://127.0.0.1:${address.port}`;+ const window = new BrowserWindow({ width: 1100, height: 750, show: true, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } });+ const panes: BrowserPane[] = [];+ const reveals: string[] = [];+ const host = new BrowserHost({+ createPane: (onState, onOpenUrl) => { const pane = new BrowserPane(onState, onOpenUrl); panes.push(pane); return pane; },+ isPluginLoaded: () => true,+ getFileRoots: async () => [],+ getScratchDir: (sessionId) => sessionId ? join(output, sessionId) : null,+ onState: () => {},+ onRevealView: (sessionId) => reveals.push(sessionId),+ });+ const visible = () => {+ const ids: number[] = [];+ const visit = (views: readonly View[]) => {+ for (const view of views) {+ if (!view.getVisible()) continue;+ if (view instanceof WebContentsView) ids.push(view.webContents.id);+ visit(view.children);+ }+ };+ visit(window.contentView.children);+ return ids;+ };+ const show = () => {+ host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true,+ bounds: { x: 570, y: 80, width: 470, height: 560 } });+ host.setGuestHole("pi.browser", { x: 0, y: 0, width: 470, height: 560 });+ };+ const passed: string[] = [];+ try {+ await window.loadURL("data:text/html,<h1>Isolated browser background validation</h1>");+ host.setWindow(window);+ show();+ host.setChromeSession("A", "a");+ await host.navigate({ url: origin + "/a" }, "A");+ const a = panes.at(-1)!;+ const aId = a.getWebContents()!.id;+ const snapshot = await host.snapshot("A");+ host.setChromeSession("B", "b");+ await host.navigate({ url: origin + "/b" }, "B");+ const bId = panes.at(-1)!.getWebContents()!.id;+ assert.equal(snapshot.title, "Page A");+ const button = snapshot.tree.match(/- (e\d+) button "Increment A"/)?.[1];+ const input = snapshot.tree.match(/- (e\d+) textbox "Note A"/)?.[1];+ assert(button && input, snapshot.tree);+ await host.fill(input, "Background draft", "A");+ await host.click(button, "A");+ assert.equal(await host.evaluate("window.count", "A"), 1);+ assert.equal(await host.evaluate("window.count", "B"), 0);+ assert.equal(await host.evaluate("document.querySelector('#note').value", "A"), "Background draft");+ assert.deepEqual(visible(), [bId]);+ passed.push("hidden A snapshot, click and fill stay isolated while B remains visible");++ const shot = await host.screenshot({ fullPage: true }, "A");+ assert(shot.path?.startsWith(join(output, "A")));+ const image = nativeImage.createFromBuffer(Buffer.from(shot.data, "base64"));+ assert(!image.isEmpty());+ const pixel = image.toBitmap();+ assert(pixel[0] > pixel[2] + 60 && pixel[0] > pixel[1] + 50,+ "background screenshot contains A's blue page, not B or a blank frame");+ assert.deepEqual(visible(), [bId]);+ passed.push("new hidden screenshot returns A's real pixels and owning scratch path without revealing it");++ host.detachPresentation();+ await window.webContents.reload();+ assert.deepEqual(visible(), []);+ assert.equal((await host.snapshot("A")).title, "Page A");+ await host.screenshot({ fullPage: true }, "A");+ assert.equal(await host.evaluate("document.querySelector('#note').value", "A"), "Background draft");+ show();+ host.setChromeSession("A", "a");+ assert.equal(a.getWebContents()!.id, aId);+ assert.deepEqual(visible(), [aId]);+ assert.equal(host.getPages("A")[0].tabId, "a");+ passed.push("renderer reload retains the native page, form data and background access");++ const created = await host.openTab({ url: origin + "/c" }, "C");+ assert(created.state);+ assert.equal((await host.snapshot("C")).title, "Page C");+ await host.screenshot({ fullPage: true }, "C");+ assert.deepEqual(visible(), [aId]);+ passed.push("first background preview is usable before any side-panel mount");+ await assert.rejects(host.snapshot("missing"), { code: "UNAVAILABLE" });+ host.closeSession("C");+ await assert.rejects(host.snapshot("C"), { code: "UNAVAILABLE" });+ assert.equal((await host.snapshot("A")).title, "Page A");+ assert.deepEqual(reveals, ["C"]);+ passed.push("unknown and closed sessions cannot fall back to another page");+ mkdirSync(output, { recursive: true });+ writeFileSync(join(output, "result.json"), JSON.stringify({ ok: true, passed }, null, 2));+ console.log("BROWSER_BACKGROUND " + JSON.stringify({ ok: true, passed }));+ } finally {+ host.dispose();+ if (!window.isDestroyed()) window.destroy();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+}+app.whenReady().then(() => probe(output)).then(() => app.exit(0), (error) => {+ console.error(error);+ app.exit(1);+});diff --git a/scripts/e2e/browser-pane-lifecycle.ts b/scripts/e2e/browser-pane-lifecycle.tsindex 92d88950d..98df9bd2c 100644--- a/scripts/e2e/browser-pane-lifecycle.ts+++ b/scripts/e2e/browser-pane-lifecycle.ts@@ -64,7 +64,7 @@ export async function checkBrowserPaneLifecycle(stage("lifecycle-queue");show();host.setChromeSession("lifecycle", "first");- await host.navigate({ url }, "lifecycle");+ await host.navigate({ url }, "lifecycle", "first");const first = panes.at(-1)!;const firstWc = first.getWebContents();assert(firstWc);@@ -73,13 +73,13 @@ export async function checkBrowserPaneLifecycle(try {const queued = host.cdpCommand("Page.captureScreenshot", { format: "png" });host.setChromeSession("lifecycle", "second");- await host.navigate({ url: url + "/second" }, "lifecycle");+ await host.navigate({ url: url + "/second" }, "lifecycle", "second");const second = panes.at(-1)!;assert.deepEqual(attached(), [second.getWebContents()!.id]);await host.screenshot();assert.equal(capture.count(), 1, "other pages do not start a queued capture");host.setChromeSession("another-session", "third");- await host.navigate({ url: url + "/third" }, "another-session");+ await host.navigate({ url: url + "/third" }, "another-session", "third");assert.deepEqual(attached(), [panes.at(-1)!.getWebContents()!.id]);host.setChromeSession("lifecycle", "first");show({ x: 680, y: 110, width: 300, height: 360 });@@ -129,7 +129,7 @@ export async function checkBrowserPaneLifecycle(assert(firstWc.isDestroyed());assert.deepEqual(attached(), []);host.setChromeSession("lifecycle", "replacement");- await host.navigate({ url: url + "/replacement" }, "lifecycle");+ await host.navigate({ url: url + "/replacement" }, "lifecycle", "replacement");closing.release();await closing.result;await rejected;@@ -146,7 +146,7 @@ export async function checkBrowserPaneLifecycle(liveWc.close();await closed;host.setChromeSession("lifecycle", "replacement");- await host.navigate({ url: url + "/recreated" }, "lifecycle");+ await host.navigate({ url: url + "/recreated" }, "lifecycle", "replacement");assert.notEqual(live.getWebContents()!.id, liveWc.id);assert.deepEqual(attached(), [live.getWebContents()!.id]);assert.equal(window.contentView.children.length, 1, "destroyed guest must not leave an orphan container");diff --git a/scripts/e2e/html-preview-model.mjs b/scripts/e2e/html-preview-model.mjsindex 5ffdca938..fb8d3e606 100644--- a/scripts/e2e/html-preview-model.mjs+++ b/scripts/e2e/html-preview-model.mjs@@ -23,7 +23,7 @@ export async function startHtmlPreviewModel() {if (pending.name === "BrowserPreview") {const content = typeof result.content === "string" ? result.content: result.content.map(part => part.text ?? "").join("");- assert.match(content, /Requested a new Browser tab/);+ assert.match(content, /Opened a new Browser tab/);completed = true;}pending = undefined;