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): retain pages with explicit session and tab ownership
zszz34843d30838f9
diff --git a/apps/desktop/electron/main/bootstrap/app-lifecycle.ts b/apps/desktop/electron/main/bootstrap/app-lifecycle.tsindex 63648ce02..e23e6659e 100644--- a/apps/desktop/electron/main/bootstrap/app-lifecycle.ts+++ b/apps/desktop/electron/main/bootstrap/app-lifecycle.ts@@ -22,7 +22,7 @@ import { createTraySessions } from "../tray-sessions";import { createTaskbarUnreadBadge } from "../taskbar-unread-badge";import { createWindow, type WindowLifecycleState } from "./window";import { windowToggleAction } from "./window-visibility";-import type { BrowserPane } from "../browser-view";+import type { BrowserHost } from "../browser-host";import type { Logger } from "../logger";import type { PluginRuntime } from "../plugin-runtime";import type { PluginViewHost } from "../plugin-view-host";@@ -66,7 +66,7 @@ export type ApplicationLifecycleDependencies = {showPluginLauncher: () => Promise<void>;askCloseBehavior: (window: BrowserWindow) => Promise<CloseBehavior | null>;applyCloseBehavior: (behavior: CloseBehavior) => void;- browserPane: BrowserPane;+ browserHost: BrowserHost;pluginViews: PluginViewHost;plugins: PluginRuntime;logger: Pick<Logger, "app">;@@ -99,7 +99,7 @@ export function createApplicationLifecycle({showPluginLauncher,askCloseBehavior,applyCloseBehavior,- browserPane,+ browserHost,pluginViews,plugins,logger,@@ -347,7 +347,7 @@ export function createApplicationLifecycle({askCloseBehavior,applyCloseBehavior,createTray,- browserPane,+ browserHost,pluginViews,plugins,logger,diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.tsindex d0eab3a17..fb908837e 100644--- a/apps/desktop/electron/main/bootstrap/shutdown.ts+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts@@ -1,7 +1,7 @@import { app, globalShortcut, type Tray } from "electron";import type { CloseBehavior } from "@pi-desktop/shared";import type { AgentSidecar } from "../agent-sidecar";-import type { BrowserPane } from "../browser-view";+import type { BrowserHost } from "../browser-host";import type { HostProcess } from "../host-process";import type { InflightCheckpointer } from "@pi-desktop/host-runtime";import type { Logger } from "../logger";@@ -41,7 +41,7 @@ export type ShutdownDependencies = {plugins: Pick<PluginRuntime, "disposeAll">;userMcp: Pick<UserMcpRuntime, "disposeAll">;mcpOAuth?: Pick<McpOAuthManager, "disposeAll">;- browserPane: Pick<BrowserPane, "dispose">;+ browserHost: Pick<BrowserHost, "dispose">;pluginViews: Pick<PluginViewHost, "dispose">;updater: Pick<AppUpdaterController, "dispose" | "isInstallingUpdate">;logger: Pick<Logger, "app">;@@ -63,7 +63,7 @@ export function registerShutdownHandlers({plugins,userMcp,mcpOAuth,- browserPane,+ browserHost,pluginViews,updater,logger,@@ -169,7 +169,7 @@ export function registerShutdownHandlers({const pluginShutdown = plugins.disposeAll();userMcp.disposeAll();mcpOAuth?.disposeAll();- browserPane.dispose();+ browserHost.dispose();inflightCheckpointer.dispose();const sidecarShutdown = getSidecar()?.dispose();diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex a3063ac36..642573522 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -9,7 +9,7 @@ import {MAC_TRAFFIC_LIGHT_POSITION,type CloseBehavior,} from "@pi-desktop/shared";-import type { BrowserPane } from "../browser-view";+import type { BrowserHost } from "../browser-host";import type { HostProcess } from "../host-process";import type { Logger } from "../logger";import type { PluginRuntime } from "../plugin-runtime";@@ -101,7 +101,7 @@ export type WindowLifecycleDependencies = {askCloseBehavior: (window: BrowserWindow) => Promise<CloseBehavior | null>;applyCloseBehavior: (behavior: CloseBehavior) => void;createTray: () => void;- browserPane: BrowserPane;+ browserHost: BrowserHost;pluginViews: PluginViewHost;plugins: PluginRuntime;logger: Pick<Logger, "app">;@@ -128,7 +128,7 @@ export async function createWindow({askCloseBehavior,applyCloseBehavior,createTray,- browserPane,+ browserHost,pluginViews,plugins,logger,@@ -471,6 +471,7 @@ export async function createWindow({});let windowCloseAccepted = false;window.webContents.on("did-start-loading", () => {+ browserHost.disposeGuest();windowState.notificationViewingSessionId = null;if (windowState.mainWindow === window) resetMenuRendererReady(window);});@@ -658,7 +659,7 @@ export async function createWindow({screen.on("display-added", reconcileDisplayTopology);screen.on("display-removed", reconcileDisplayTopology);- browserPane.setWindow(window);+ browserHost.setWindow(window);pluginViews.setWindow(window);window.on("closed", () => {screen.removeListener("display-metrics-changed", reconcileDisplayTopology);@@ -683,7 +684,7 @@ export async function createWindow({}if (windowState.mainWindow !== window) return;windowState.mainWindow = null;- browserPane.setWindow(null);+ browserHost.setWindow(null);pluginViews.setWindow(null);if (process.platform !== "darwin" &&diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.tsindex 240810175..b641fbd19 100644--- a/apps/desktop/electron/main/browser-host.ts+++ b/apps/desktop/electron/main/browser-host.ts@@ -1,3 +1,4 @@+import type { BrowserWindow } from "electron";import type { BrowserState } from "@pi-desktop/shared";import type { BrowserPane } from "./browser-view";import { BrowserCdp } from "./browser-cdp";@@ -54,7 +55,8 @@ function asRect(value: unknown): BrowserRect | null {}export type BrowserHostDeps = {- pane: BrowserPane;+ createPane: (onState: (state: BrowserState) => void, onOpenUrl: (url: string) => void) => BrowserPane;+ onOpenUrl?: (url: string, sessionId?: string) => void;isPluginLoaded: (pluginId: string) => boolean;getFileRoot: (sessionId?: string) => Promise<string | null>;getScratchDir?: (sessionId?: string) => string | null;@@ -68,26 +70,39 @@ type ChromeSurface = {bounds: BrowserRect;};-/**- * Public `pi.browser.*` implementation: one host-owned guest WebContentsView,- * driven by plugin chrome through a clamped hole, plus CDP for the agent.- */+type BrowserPage = {+ key: string;+ sessionId: string;+ tabId: string | null;+ pane: BrowserPane;+ cdp: BrowserCdp;+ state: BrowserState | null;+ started: boolean;+ navigationVersion: number;+ navigating: boolean;+};++/** Host-owned pages, keyed by conversation and resource tab. */export class BrowserHost {- private readonly pane: BrowserPane;- private readonly cdp = new BrowserCdp();private readonly deps: BrowserHostDeps;+ 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 active: BrowserPage | null = null;+ private window: BrowserWindow | null = null;private chrome: ChromeSurface | null = null;private hole: BrowserRect | null = null;private holePluginId: string | null = null;- private readonly locations = new Map<string, string>();- private chromeSessionId: string | null = null;- private chromeTabId: string | null = null;- private started = false;- private navigationEpoch = 0;-- constructor(deps: BrowserHostDeps) {- this.deps = deps;- this.pane = deps.pane;++ constructor(deps: BrowserHostDeps) { this.deps = deps; }++ setWindow(window: BrowserWindow | null): void {+ this.window = window;+ if (!window) { this.disposeGuest(); return; }+ for (const page of this.pages.values()) page.pane.setWindow(window);+ this.applyGuest();}setChromeSurface(surface: ChromeSurface | null): void {@@ -96,51 +111,86 @@ export class BrowserHost {}getContext(): { sessionId?: string; tabId?: string } {- return { ...(this.chromeSessionId ? { sessionId: this.chromeSessionId } : {}),- ...(this.chromeTabId ? { tabId: this.chromeTabId } : {}) };+ return this.active ? this.contextFor(this.active) : {};}- publishState(state: BrowserState): void {- if (this.chromeSessionId && state.url) this.rememberLocation(this.chromeSessionId, state.url);- this.deps.onState({ ...state, ...this.getContext() });+ private contextFor(page: BrowserPage): { sessionId?: string; tabId?: string } {+ return {+ ...(page.sessionId ? { sessionId: page.sessionId } : {}),+ ...(page.tabId ? { tabId: page.tabId } : {}),+ };}- private locationKey(sessionId: string, tabId = this.chromeTabId): string {+ private key(sessionId: string, tabId: string | null): string {return JSON.stringify([sessionId, tabId]);}+ private pageFor(sessionId: string, tabId: string | null): BrowserPage {+ const key = this.key(sessionId, tabId);+ const existing = this.pages.get(key);+ if (existing) return existing;+ const page: BrowserPage = {+ key, sessionId, tabId, cdp: new BrowserCdp(), state: null,+ started: false, navigationVersion: 0, navigating: false,+ pane: this.deps.createPane(+ (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();+ },+ (url) => {+ if (this.pages.get(key) === page) this.deps.onOpenUrl?.(url, sessionId || undefined);+ },+ ),+ };+ page.pane.setWindow(this.window);+ this.pages.set(key, page);+ return page;+ }++ private publishCurrent(): void {+ const state = this.getState();+ this.deps.onState(state ?? {+ url: "", title: "", isLoading: false, canGoBack: false, canGoForward: false,+ ...this.getContext(),+ });+ }+setChromeSession(sessionId: string | undefined, tabId?: string, location?: string): boolean {- const next = sessionId?.trim() || null;- const nextTab = tabId ?? (next === this.chromeSessionId ? this.chromeTabId : null);- if (this.chromeSessionId === next && this.chromeTabId === nextTab) return false;- this.chromeSessionId = next;- this.chromeTabId = nextTab;- this.navigationEpoch += 1;- this.pane.invalidateNavigation();- this.started = false;- this.pane.setVisible(false);- if (next) {- if (location && !this.locations.has(this.locationKey(next))) this.rememberLocation(next, location);- void this.rebindSession(next).catch((error) => {- console.warn("Browser preview session restore failed", error);+ const id = sessionId?.trim() || "";+ const tab = tabId ?? (this.active?.sessionId === id+ ? this.active.tabId : this.selectedTabs.get(id) ?? null);+ const page = this.pageFor(id, tab);+ if (this.active === page) return false;+ 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);+ if (target && navigate) {+ page.started = false;+ page.state = null;+ this.publishCurrent();+ this.applyGuest();+ void this.navigatePage(page, target).catch((error) => {+ console.warn("Browser tab restore failed", error);});+ } else {+ this.publishCurrent();+ this.applyGuest();}return true;}- /**- * Content-relative hole inside the calling plugin view. Last writer wins- * (v1 is a singleton guest).- */setGuestHole(pluginId: string, hole: unknown): BrowserRect | null {- const rect = asRect(hole);- if (!rect) {- this.hole = null;- this.holePluginId = pluginId;- this.applyGuest();- return null;- }- this.hole = rect;+ this.hole = asRect(hole);this.holePluginId = pluginId;this.applyGuest();return this.guestBounds();@@ -148,184 +198,182 @@ export class BrowserHost {setGuestVisible(pluginId: string, visible: boolean): void {if (!visible && this.holePluginId === pluginId) {- this.pane.setVisible(false);- return;+ this.active?.pane.setVisible(false);+ } else if (visible) {+ this.applyGuest();}- if (visible) this.applyGuest();}rememberLocation(sessionId: string | undefined, location: string): void {const id = sessionId?.trim();- const value = location.trim();- if (!id || !value) return;- this.locations.set(this.locationKey(id, id === this.chromeSessionId ? this.chromeTabId : null), value);+ const target = location.trim();+ if (!id || !target) return;+ if (this.selectedTabs.has(id)) {+ const key = this.key(id, this.selectedTabs.get(id) ?? null);+ this.locations.set(key, target);+ if (this.active?.key !== key) this.pendingTabs.add(key);+ } else {+ this.pendingSessions.set(id, target);+ }}- async navigate(- input: BrowserNavigateInput,- sessionId?: string,- ): Promise<BrowserState | null> {+ async navigate(input: BrowserNavigateInput, sessionId?: string): Promise<BrowserState | null> {const target = String(input.path ?? input.url ?? "").trim();- if (!target) return this.pane.getState();- this.rememberLocation(sessionId ?? this.chromeSessionId ?? undefined, target);- const background =- Boolean(sessionId) &&- Boolean(this.chromeSessionId) &&- sessionId !== this.chromeSessionId;- if (background) return this.pane.getState();- const state = await this.navigateGuest(- target,- this.deps.getFileRoot(sessionId ?? this.chromeSessionId ?? undefined),- );- if (state) this.publishState(state);- return state;+ if (!target) return this.getState();+ const id = sessionId?.trim() || this.active?.sessionId || "";+ 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;+ }+ return this.navigatePage(this.active, target);+ }++ private async navigatePage(page: BrowserPage, target: string): Promise<BrowserState | null> {+ const version = ++page.navigationVersion;+ page.navigating = true;+ this.locations.set(page.key, target);+ const current = () => this.pages.get(page.key) === page && page.navigationVersion === version;+ let state: BrowserState | null;+ try {+ const root = await this.deps.getFileRoot(page.sessionId || undefined);+ if (!current()) return null;+ state = await page.pane.navigateAndWait(target, root);+ } catch (error) {+ if (!current()) return null;+ 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(); }+ 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);+ 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(); }+ return state ? { ...state, ...this.contextFor(page) } : null;}action(action: "back" | "forward" | "reload" | "stop"): void {- this.pane.action(action);+ if (this.active?.state) this.active.pane.action(action);}getState(): BrowserState | null {- const state = this.pane.getState();- return state ? { ...state, ...this.getContext() } : null;+ return this.active?.state ? { ...this.active.state, ...this.getContext() } : null;}openExternal(): void {- this.pane.openExternal();+ if (this.active?.started) this.active.pane.openExternal();+ }++ private currentPage(): BrowserPage {+ if (!this.active?.started) throw Object.assign(new Error("browser guest is not available"), { code: "UNAVAILABLE" });+ return this.active;+ }++ private requireWebContents() {+ const wc = this.currentPage().pane.getWebContents();+ if (!wc || wc.isDestroyed()) throw Object.assign(new Error("browser guest is not available"), { code: "UNAVAILABLE" });+ return wc;}async snapshot(): Promise<{ tree: string; url: string; title: string }> {- const wc = this.requireWebContents();- return this.cdp.snapshot(wc);+ return this.currentPage().cdp.snapshot(this.requireWebContents());}- async screenshot(- input: { fullPage?: boolean } = {},- sessionId?: string,- ): Promise<{ mimeType: string; data: string; path?: string }> {- const wc = this.requireWebContents();- const shot = await this.cdp.screenshot(wc, input);- const scratch = this.deps.getScratchDir?.(sessionId ?? this.chromeSessionId ?? undefined);+ async screenshot(input: { fullPage?: boolean } = {}, sessionId?: string): Promise<{ mimeType: string; data: string; path?: string }> {+ const page = this.currentPage();+ const shot = await page.cdp.screenshot(this.requireWebContents(), input);+ const scratch = this.deps.getScratchDir?.(sessionId ?? page.sessionId);if (!scratch) return shot;try {mkdirSync(scratch, { recursive: true });const path = join(scratch, `browser-screenshot-${Date.now()}.jpg`);writeFileSync(path, Buffer.from(shot.data, "base64"));return { ...shot, path };- } catch {- return shot;- }- }-- async click(uid: string): Promise<void> {- await this.cdp.click(this.requireWebContents(), uid);+ } catch { return shot; }}- async fill(uid: string, text: string): Promise<void> {- await this.cdp.fill(this.requireWebContents(), uid, text);- }-- async evaluate(expression: string): Promise<unknown> {- return this.cdp.evaluate(this.requireWebContents(), expression);+ async click(uid: string): Promise<void> { await this.currentPage().cdp.click(this.requireWebContents(), uid); }+ async fill(uid: string, text: string): Promise<void> { await this.currentPage().cdp.fill(this.requireWebContents(), uid, text); }+ async evaluate(expression: string): Promise<unknown> { return this.currentPage().cdp.evaluate(this.requireWebContents(), expression); }+ console(limit?: number): { messages: ReturnType<BrowserCdp["console"]> } {+ 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> { return this.currentPage().cdp.send(this.requireWebContents(), method, params); }- console(limit?: number): { messages: ReturnType<BrowserCdp["console"]> } {- this.ensureCdp();- return { messages: this.cdp.console(limit) };+ /** The renderer-created resource tab is the preview's only navigation owner. */+ async previewWorkspaceFile(_sessionId: string, _path: string, _root: string): Promise<{ ok: true } | { ok: false; content: string }> {+ if (!this.deps.isPluginLoaded(BROWSER_PLUGIN_ID)) return {+ ok: false, content: "BrowserPreview: the Browser plugin is disabled. Enable pi.browser in Plugins to preview HTML.",+ };+ return { ok: true };}- async cdpCommand(method: string, params?: unknown): Promise<unknown> {- return this.cdp.send(this.requireWebContents(), method, params);+ closeTab(sessionId: string, tabId: string | null): void {+ const key = this.key(sessionId, tabId);+ const page = this.pages.get(key);+ if (page) {+ this.pages.delete(key);+ page.navigationVersion += 1;+ page.cdp.detach(page.pane.getWebContents() ?? undefined);+ page.pane.dispose();+ 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);}- /**- * Host `BrowserPreview` facade: plugin must be enabled; the guest loads the- * workspace file only when that session's chrome is visible (D142).- */- async previewWorkspaceFile(- sessionId: string,- path: string,- root: string,- ): Promise<{ ok: true } | { ok: false; content: string }> {- if (!this.deps.isPluginLoaded(BROWSER_PLUGIN_ID)) {- return {- ok: false,- content:- "BrowserPreview: the Browser plugin is disabled. Enable pi.browser in Plugins to preview HTML.",- };+ closeSession(sessionId: string): void {+ for (const page of [...this.pages.values()]) {+ if (page.sessionId !== sessionId) continue;+ this.closeTab(sessionId, page.tabId);}- this.rememberLocation(sessionId, path);- const background =- Boolean(this.chromeSessionId) && this.chromeSessionId !== sessionId;- if (!background) {- await this.navigateGuest(path, root);+ this.pendingSessions.delete(sessionId);+ this.selectedTabs.delete(sessionId);+ for (const key of this.locations.keys()) {+ if (JSON.parse(key)[0] === sessionId) { this.locations.delete(key); this.pendingTabs.delete(key); }}- return { ok: true };}+ dispose(): void { this.disposeGuest(); }+disposeGuest(): void {- this.navigationEpoch += 1;- this.cdp.detach(this.pane.getWebContents() ?? undefined);- this.pane.dispose();- this.started = false;+ for (const page of this.pages.values()) {+ page.navigationVersion += 1;+ page.cdp.detach(page.pane.getWebContents() ?? undefined);+ page.pane.dispose();+ }+ this.pages.clear();+ this.active = null;this.hole = null;this.holePluginId = null;}private guestBounds(): BrowserRect | null {- if (!this.chrome?.visible || !this.hole) return null;- if (this.holePluginId !== this.chrome.pluginId) return null;+ if (!this.chrome?.visible || !this.hole || this.holePluginId !== this.chrome.pluginId) return null;return clampGuestBounds(this.chrome.bounds, this.hole);}private applyGuest(): void {+ if (!this.active) return;const bounds = this.guestBounds();- if (!bounds || !this.started) {- this.pane.setVisible(false);- return;- }- this.pane.setBounds(bounds);- this.pane.setVisible(true);- }-- private async rebindSession(sessionId: string): Promise<void> {- const location = this.locations.get(this.locationKey(sessionId));- if (!location) return;- await this.navigateGuest(location, this.deps.getFileRoot(sessionId));- }-- private async navigateGuest(- target: string,- root: string | null | Promise<string | null>,- ): Promise<BrowserState | null> {- const epoch = ++this.navigationEpoch;- const fileRoot = await root;- if (epoch !== this.navigationEpoch) return null;- const state = await this.pane.navigateAndWait(target, fileRoot);- if (epoch !== this.navigationEpoch) return null;- // Only a committed current document may become visible. Invalid input has- // no native load event, so it needs an explicit failure state as well.- this.started = state !== null;- if (!state && !this.pane.getState()?.loadError) {- this.publishState({ url: target, title: "", isLoading: false,- canGoBack: false, canGoForward: false, loadError: "INVALID_URL" });- }- this.applyGuest();- return state;- }-- private requireWebContents() {- const wc = this.pane.getWebContents();- if (!wc || wc.isDestroyed()) {- throw Object.assign(new Error("browser guest is not available"), {- code: "UNAVAILABLE",- });- }- return wc;- }-- private ensureCdp(): void {- const wc = this.pane.getWebContents();- if (wc && !wc.isDestroyed()) void this.cdp.attach(wc);+ if (!bounds || !this.active.started) { this.active.pane.setVisible(false); return; }+ this.active.pane.setBounds(bounds);+ this.active.pane.setVisible(true);}}diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.tsindex e89d2d395..d99917daf 100644--- a/apps/desktop/electron/main/browser-view.ts+++ b/apps/desktop/electron/main/browser-view.ts@@ -176,12 +176,15 @@ export class BrowserPane {return new Promise<BrowserState | null>((resolve) => {let settled = false;let started = false;+ const destinations = new Set([target]);const finish = (committed: boolean, error?: string) => {if (settled) return;settled = true;clearTimeout(timer);wc.removeListener("did-start-navigation", onStart);wc.removeListener("did-navigate", onCommit);+ wc.removeListener("did-redirect-navigation", onRedirect);+ wc.removeListener("did-fail-load", onFailure);if (epoch !== this.navigationEpoch) { resolve(null); return; }this.cancelPending = null;this.pendingTarget = null;@@ -194,17 +197,25 @@ export class BrowserPane {const onStart = (_event: unknown, url: string, inPlace: boolean, mainFrame: boolean) => {if (mainFrame && !inPlace && url === target) started = true;};+ const onRedirect = (_event: unknown, url: string, inPlace: boolean, mainFrame: boolean) => {+ if (started && mainFrame && !inPlace && epoch === this.navigationEpoch) destinations.add(url);+ };+ const onFailure = (_event: unknown, code: number, description: string, url: string, mainFrame: boolean) => {+ if (mainFrame !== false && code !== -3 && destinations.has(url)) finish(false, description);+ };const onCommit = (_event: unknown, url: string) => {// A current main-frame commit is ready to display even if images or// subframes are still loading. Old-session events cannot satisfy it.- if (started && epoch === this.navigationEpoch && url === wc.getURL()) finish(true);+ if (started && epoch === this.navigationEpoch && destinations.has(url) && url === wc.getURL()) finish(true);};const timer = setTimeout(() => finish(false, "ERR_TIMED_OUT"), Math.max(1, timeoutMs));this.cancelPending = () => finish(false);wc.on("did-start-navigation", onStart);wc.on("did-navigate", onCommit);+ wc.on("did-redirect-navigation", onRedirect);+ wc.on("did-fail-load", onFailure);void wc.loadURL(target).then(- () => finish(true),+ () => { if (destinations.has(wc.getURL())) finish(true); },(error: unknown) => finish(false, error instanceof Error ? error.message : String(error)),);});@@ -250,6 +261,7 @@ export class BrowserPane {setVisible(visible: boolean): void {this.visible = visible;if (!this.view) return;+ this.view.setVisible?.(visible);if (visible) this.attach();else this.detach();}@@ -353,6 +365,7 @@ export class BrowserPane {sandbox: true,contextIsolation: true,nodeIntegration: false,+ backgroundThrottling: true,partition: PARTITION,},});diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 1e0680554..ca9b08bf4 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -669,7 +669,6 @@ const {pluginPanels,pluginViews,browserHost,- browserPane,announceTurnEnded,speech,} = pluginServices;@@ -900,7 +899,7 @@ applicationLifecycle = createApplicationLifecycle({showPluginLauncher: showPluginLauncherForLifecycle,askCloseBehavior: askCloseBehaviorForLifecycle,applyCloseBehavior: applyCloseBehaviorForLifecycle,- browserPane,+ browserHost,pluginViews,plugins,logger,@@ -1475,7 +1474,7 @@ registerShutdownHandlers({plugins,userMcp,mcpOAuth,- browserPane,+ browserHost,pluginViews,updater,logger,diff --git a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ui-ipc.tsindex 6d8e30dfb..d4d5ba959 100644--- a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts+++ b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts@@ -201,8 +201,9 @@ export function registerPluginUiIpc({if (!view) throw new Error("plugin has no such view");const htmlPath = join(loaded.path, view.entry);if (!existsSync(htmlPath)) throw new Error("view entry missing");- const switched = isBrowserView && sessionId- ? browserHost.setChromeSession(sessionId, typeof payload.tabId === "string" ? payload.tabId : undefined, location) : false;+ if (isBrowserView && sessionId) {+ browserHost.setChromeSession(sessionId, typeof payload.tabId === "string" ? payload.tabId : undefined, location);+ }pluginViews.open({pluginId,viewId,@@ -215,19 +216,18 @@ export function registerPluginUiIpc({// view receives the opener's subject untouched (D320 follow-up)....(isBrowserView || !location ? {} : { location }),});- if (isBrowserView && location && !switched && browserHost.getState()?.url !== location) {- void browserHost.navigate(- { path: location, url: location },- sessionId || undefined,- );- }return { ok: true };},);handle(IPC.invoke.pluginViewClose,- async (payload: { pluginId?: string; viewId?: string }) => {+ async (payload: { pluginId?: string; viewId?: string; sessionId?: string; tabId?: string }) => {+ if (payload.pluginId === BROWSER_PLUGIN_ID && payload.viewId === BROWSER_VIEW_ID && typeof payload.sessionId === "string") {+ if (typeof payload.tabId === "string") browserHost.closeTab(payload.sessionId, payload.tabId);+ else browserHost.closeSession(payload.sessionId);+ return { ok: true };+ }pluginViews.close(String(payload?.pluginId ?? ""), String(payload?.viewId ?? ""));return { ok: true };},diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.tsindex d12348d66..32fff9d6b 100644--- a/apps/desktop/electron/main/runtime/sidecar.ts+++ b/apps/desktop/electron/main/runtime/sidecar.ts@@ -524,7 +524,7 @@ export function createSidecarRuntime({});return {ok: true,- content: `Previewing ${raw} in the work-panel Browser plugin. Live reload is active — subsequent edits to the file or sibling assets re-render automatically.`,+ content: `Requested a new Browser tab for ${raw}. Once loaded, live reload updates the page 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 1cbfb9b8d..f866a732f 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -549,17 +549,6 @@ export function createPluginServices({});}};- const browserPane = new BrowserPane((state) => browserHost.publishState(state), (url) => {- const { sessionId } = browserHost.getContext();- void (async () => {- const settings = await getHost()?.call<AppSettings>("settings.get");- if (!sessionId || settings?.linkOpenTarget === "external" || !/^https?:/i.test(url)) {- await shell.openExternal(url);- } else {- sendToRenderer(IPC.event.browserPreview, { sessionId, url });- }- })().catch((error) => logger.app("plugin", "warn", "browser.link.open.failed", { data: String(error) }));- });const pluginViews = new PluginViewHost(({ pluginId, url }) => {logger.app("plugin", "warn", "plugin.api", {pluginId,@@ -569,7 +558,17 @@ export function createPluginServices({});pluginPanels.addSenderResolver((senderId) => pluginViews.pluginIdForSender(senderId));const browserHost = new BrowserHost({- pane: browserPane,+ createPane: (onState, onOpenUrl) => new BrowserPane(onState, onOpenUrl),+ onOpenUrl: (url, sessionId) => {+ void (async () => {+ const settings = await getHost()?.call<AppSettings>("settings.get");+ if (!sessionId || settings?.linkOpenTarget === "external" || !/^https?:/i.test(url)) {+ await shell.openExternal(url);+ } else {+ sendToRenderer(IPC.event.browserPreview, { sessionId, url });+ }+ })().catch((error) => logger.app("plugin", "warn", "browser.link.open.failed", { data: String(error) }));+ },isPluginLoaded: (pluginId) => Boolean(plugins.getLoaded(pluginId)),getFileRoot: async (sessionId) => {if (sessionId) {@@ -646,7 +645,6 @@ export function createPluginServices({pluginPanels,pluginViews,browserHost,- browserPane,speech,};}diff --git a/apps/desktop/resources/plugins/pi.browser/views/browser.html b/apps/desktop/resources/plugins/pi.browser/views/browser.htmlindex a5ac92b9c..9de4e9a31 100644--- a/apps/desktop/resources/plugins/pi.browser/views/browser.html+++ b/apps/desktop/resources/plugins/pi.browser/views/browser.html@@ -191,6 +191,7 @@};let navigationRequest = 0;+ let displayedContext = "";const t = (key) => copy[locale]?.[key] ?? copy.en[key] ?? key;const applyCopy = () => {@@ -218,6 +219,10 @@};const paint = (state) => {+ const context = state?.sessionId && state?.tabId+ ? JSON.stringify([state.sessionId, state.tabId]) : displayedContext;+ const contextChanged = context !== displayedContext;+ displayedContext = context;started = Boolean(state?.url) && !state?.loadError;empty.hidden = started && !state?.isLoading;const phase = state?.loadError === "ERR_ABORTED" ? "stopped" : state?.loadError ? "failed" : state?.isLoading ? "loading" : "empty";@@ -229,7 +234,7 @@external.disabled = !state?.url;reload.title = state?.isLoading ? t("stop") : t("reload");reload.setAttribute("aria-label", reload.title);- if (!inputFocused && state?.url) input.value = state.url;+ if (contextChanged || !inputFocused) input.value = state?.url ?? "";reportHole();};diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex b71ef7509..914582d22 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1212,8 +1212,8 @@ export const api = {viewId: string,extra?: { sessionId?: string; location?: string; tabId?: string },) => invoke(IPC.invoke.pluginViewOpen, { pluginId, viewId, ...extra }),- pluginViewClose: (pluginId: string, viewId: string) =>- invoke(IPC.invoke.pluginViewClose, { pluginId, viewId }),+ pluginViewClose: (pluginId: string, viewId: string, extra?: { sessionId: string; tabId?: string }) =>+ invoke(IPC.invoke.pluginViewClose, { pluginId, viewId, ...extra }),pluginViewSetBounds: (bounds: {x: number;y: number;diff --git a/apps/desktop/src/lib/work-panel-tabs.ts b/apps/desktop/src/lib/work-panel-tabs.tsindex 24af3221d..2e57d28de 100644--- a/apps/desktop/src/lib/work-panel-tabs.ts+++ b/apps/desktop/src/lib/work-panel-tabs.ts@@ -124,7 +124,7 @@ export function browserPluginTab(location?: string): WorkPanelTab {const base = pluginWorkPanelTab(BROWSER_PLUGIN_TAB.pluginId, BROWSER_PLUGIN_TAB.viewId);if (!location) return base;const target = location.trim();- return { ...base, id: `${base.id}:${++newWorkPanelTabSequence}`, location: target, label: browserTabLabel(target) };+ return { ...base, id: `${base.id}:${Date.now().toString(36)}-${++newWorkPanelTabSequence}`, location: target, label: browserTabLabel(target) };}export function browserTabLabel(location: string): string {diff --git a/apps/desktop/src/stores/slices/project-slice.ts b/apps/desktop/src/stores/slices/project-slice.tsindex dc48e8247..820713609 100644--- a/apps/desktop/src/stores/slices/project-slice.ts+++ b/apps/desktop/src/stores/slices/project-slice.ts@@ -559,6 +559,8 @@ export function createProjectSlice({deleteSession: async (id) => {if (!id) return;await api.deleteSession(id);+ void api.pluginViewClose("pi.browser", "browser", { sessionId: id })+ .catch((error) => get().showToast(String(error), { variant: "error" }));clearLocalSessionState({ get, set, runtime, manualSessionTitles, withoutRecordKey },id,diff --git a/apps/desktop/src/stores/slices/work-panel-slice.ts b/apps/desktop/src/stores/slices/work-panel-slice.tsindex 1197391ad..338f09a43 100644--- a/apps/desktop/src/stores/slices/work-panel-slice.ts+++ b/apps/desktop/src/stores/slices/work-panel-slice.ts@@ -310,6 +310,11 @@ export function createWorkPanelSlice({});},closeWorkPanelTab: (tabId) => {+ const current = get();+ if (current.activeSessionId && current.workPanelTabs.some((tab) => tab.id === tabId && tab.resource === "pi.browser/browser")) {+ void api.pluginViewClose("pi.browser", "browser", { sessionId: current.activeSessionId, tabId })+ .catch((error) => get().showToast(String(error), { variant: "error" }));+ }set((state) => {const sessionId = state.activeSessionId;if (!sessionId) return {};diff --git a/apps/desktop/test/browser-host-session.test.mjs b/apps/desktop/test/browser-host-session.test.mjsindex 20c588bab..4a0e24b2e 100644--- a/apps/desktop/test/browser-host-session.test.mjs+++ b/apps/desktop/test/browser-host-session.test.mjs@@ -4,216 +4,152 @@ 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;- let reject;- const promise = new Promise((yes, no) => { resolve = yes; reject = no; });- return { promise, resolve, reject };+ const promise = new Promise((done) => { resolve = done; });+ return { promise, resolve };}--// Drain promises and their continuations, without timing-dependent sleeps.-const settled = () => new Promise(setImmediate);-function harness() {- let state = null;- let visible = false;- const roots = [];- const loads = [];- const shown = [];- const published = [];- let invalidations = 0;- const pane = {- getState: () => state,- getWebContents: () => null,- invalidateNavigation: () => { invalidations += 1; },- setBounds: () => {},- setVisible(value) {- visible = value;- if (value) shown.push(state?.url);- },- navigateAndWait(target, root) {- const done = deferred();- const load = { target, root, fail: () => done.resolve(null), finish() {- state = { url: target, title: target, isLoading: false };- done.resolve(state);- } };- loads.push(load);- return done.promise;- },- dispose: () => { state = null; visible = false; },+ const roots = [], loads = [], panes = [], published = [];+ const createPane = (onState) => {+ let state = null;+ const pane = {+ visible: false, disposed: false,+ setWindow: () => {}, setBounds: () => {},+ setVisible(value) { this.visible = value; },+ getState: () => state, getWebContents: () => null,+ invalidateNavigation: () => {},+ navigateAndWait(target) {+ const done = deferred();+ loads.push({ target, pane, finish() {+ state = { url: target, title: target, isLoading: false, canGoBack: false, canGoForward: false };+ onState(state); done.resolve(state);+ }, fail: () => done.resolve(null) });+ return done.promise;+ },+ dispose() { this.visible = false; this.disposed = true; },+ };+ panes.push(pane);+ return pane;};const host = new BrowserHost({- pane,- isPluginLoaded: () => true,+ createPane, isPluginLoaded: () => true,getFileRoot(sessionId) {- const root = deferred();- roots.push({ sessionId, ...root });- return root.promise;+ const done = deferred(); roots.push({ sessionId, ...done }); return done.promise;},- onState: (value) => published.push(value),+ onState: (state) => published.push(state),});- const surface = (show = true) => host.setChromeSurface({- pluginId: "pi.browser", viewId: "browser", visible: show,+ const surface = (visible = true) => host.setChromeSurface({+ pluginId: "pi.browser", viewId: "browser", visible,bounds: { x: 100, y: 20, width: 400, height: 600 },});- const hole = () => host.setGuestHole("pi.browser", { x: 0, y: 30, width: 400, height: 570 });surface();- hole();- return {- host, roots, loads, shown, published, surface, hole,- get visible() { return visible; },- get invalidations() { return invalidations; },- };+ host.setGuestHole("pi.browser", { x: 0, y: 30, width: 400, height: 570 });+ return { host, roots, loads, panes, published, surface };}--async function openPreview(h, sessionId, path) {- h.host.setChromeSession(sessionId);- const request = h.host.previewWorkspaceFile(sessionId, path, `/projects/${sessionId}`);- await settled();- h.loads.at(-1).finish();- await request;+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();}-test("opening two session previews and switching back never reveals the previous session while loading", async () => {- const h = harness();- await openPreview(h, "A", "A.html");- assert.equal(h.visible, true);- // A background tool prepares B's page without stealing A's preview.- await h.host.previewWorkspaceFile("B", "B.html", "/projects/B");- assert.equal(h.loads.length, 1);- h.surface(false);- h.host.setChromeSession("B");- h.surface();- h.hole();- h.host.setGuestVisible("pi.browser", true);- assert.equal(h.visible, false, "A must stay hidden during B's root lookup");- const before = h.shown.length;- h.roots.at(-1).resolve("/projects/B");- await settled();- assert.equal(h.visible, false, "A must stay hidden during B's document load");- assert.equal(h.loads.at(-1).target, "B.html");- h.loads.at(-1).finish();- await settled();- assert.equal(h.visible, true);- assert.deepEqual(h.shown.slice(before), ["B.html"]);-- h.host.setChromeSession("A");- assert.equal(h.visible, false);- h.roots.at(-1).resolve("/projects/A");- await settled();- h.loads.at(-1).finish();- await settled();- assert.equal(h.shown.at(-1), "A.html");- assert.equal(h.visible, true);+test("BrowserPreview prepares a new resource tab without navigating or rewriting the current tab", async () => {+ const h = harness(); await open(h, "A", "one", "A.html");+ const preview = h.host.previewWorkspaceFile("A", "preview.html", "/projects/A");+ await settled();+ assert.equal(h.loads.length, 1, "preview must wait for the resource-tab owner");+ assert.equal(h.host.getState().url, "A.html");+ await preview;+ await open(h, "A", "preview", "preview.html");+ h.host.setChromeSession("A", "one", "A.html");+ assert.equal(h.host.getState().url, "A.html");+ assert.equal(h.loads.length, 2, "switching back must reuse the page");});-test("an older root lookup cannot navigate over a newer session", async () => {- const h = harness();- h.host.rememberLocation("B", "B.html");- h.host.rememberLocation("C", "C.html");- h.host.setChromeSession("B");- const old = h.roots.at(-1);- h.host.setChromeSession("C");- h.roots.at(-1).resolve("/projects/C");- await settled();- h.loads.at(-1).finish();- await settled();- old.resolve("/projects/B");- await settled();- assert.deepEqual(h.loads.map((load) => load.target), ["C.html"]);- assert.equal(h.shown.at(-1), "C.html");+test("background navigation targets 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");+ 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("C", "blank");+ assert.equal(h.host.getState(), null);});-test("a previous session's load completion cannot reveal its guest while the new root is pending", async () => {- const h = harness();- h.host.setChromeSession("A");- const pending = h.host.navigate({ path: "A.html" }, "A");- h.roots.at(-1).resolve("/projects/A");- await settled();- h.host.rememberLocation("B", "B.html");- h.host.setChromeSession("B");- assert.equal(h.invalidations, 2, "each session binding invalidates native events");- h.loads[0].finish();- await pending;- assert.equal(h.visible, false);- assert.deepEqual(h.published, [], "stale navigation must not publish A as current");- h.roots.at(-1).resolve("/projects/B");- await settled();- h.loads.at(-1).finish();- await settled();- assert.equal(h.shown.at(-1), "B.html");+test("an empty tab exposes no previous address or native page", async () => {+ const h = harness(); await open(h, "A", "a", "A.html");+ h.host.setChromeSession("A", "blank");+ h.host.setGuestVisible("pi.browser", true);+ assert.equal(h.host.getState(), null);+ assert.equal(h.panes.some((pane) => pane.visible), false);+ assert.equal(h.published.at(-1).url, "");});-test("a session without a remembered preview cannot expose the previous guest", async () => {- const h = harness();- await openPreview(h, "A", "A.html");- h.host.setChromeSession("empty");- h.surface();- h.hole();- h.host.setGuestVisible("pi.browser", true);- assert.equal(h.visible, false);- assert.equal(h.roots.length, 0);+test("a delayed root lookup can finish in its own background tab without taking over the active page", async () => {+ const h = harness(); h.host.setChromeSession("A", "a", "A.html");+ const older = h.roots.at(-1);+ await open(h, "B", "b", "B.html");+ older.resolve("/projects/A"); await settled(); h.loads.at(-1).finish(); await settled();+ assert.equal(h.host.getState().url, "B.html");+ assert.equal(h.loads.at(-1).pane.visible, false);+ h.host.setChromeSession("A", "a");+ assert.equal(h.host.getState().url, "A.html");});-test("same-session navigation supersedes a pending restore and keeps existing content during normal navigation", async () => {- const h = harness();- await openPreview(h, "A", "A.html");- const next = h.host.navigate({ url: "https://fixture.invalid/new" }, "A");- assert.equal(h.visible, true, "normal navigation within A does not blank A's loaded page");- h.roots.at(-1).resolve("/projects/A");- await settled();- h.loads.at(-1).finish();- await next;- assert.equal(h.shown.at(-1), "https://fixture.invalid/new");- h.host.setChromeSession("B");- h.host.setChromeSession("A");- const restore = h.roots.at(-1);- const newest = h.host.navigate({ path: "newest.html" }, "A");- h.roots.at(-1).resolve("/projects/A");- await settled();- h.loads.at(-1).finish();- await newest;- const count = h.loads.length;- restore.resolve("/projects/A");- await settled();- assert.equal(h.loads.length, count);- assert.equal(h.shown.at(-1), "newest.html");+test("same-tab navigation supersedes an older request and retains sibling pages", async () => {+ const h = harness(); await open(h, "A", "a", "A.html");+ const older = h.host.navigate({ url: "https://fixture.invalid/older" }, "A");+ const oldRoot = h.roots.at(-1);+ const newer = h.host.navigate({ url: "https://fixture.invalid/newer" }, "A");+ h.roots.at(-1).resolve("/projects/A"); await settled(); h.loads.at(-1).finish(); await newer;+ oldRoot.resolve("/projects/A"); await older;+ assert.equal(h.loads.length, 2);+ assert.equal(h.host.getState().url, "https://fixture.invalid/newer");});-test("closing the panel during a load keeps it hidden when the load completes", async () => {- const h = harness();- h.host.setChromeSession("A");- const pending = h.host.previewWorkspaceFile("A", "A.html", "/projects/A");- await settled();- h.surface(false);- h.loads.at(-1).finish();- await pending;- assert.equal(h.visible, false);- h.surface();- assert.equal(h.visible, true);+test("closing the panel keeps a pending page hidden until the panel returns", async () => {+ const h = harness(); h.host.setChromeSession("A", "a", "A.html");+ h.roots.at(-1).resolve("/projects/A"); await settled(); h.surface(false);+ h.loads.at(-1).finish(); await settled();+ assert.equal(h.panes[0].visible, false);+ h.surface(); assert.equal(h.panes[0].visible, true);});-test("disposing the guest invalidates pending roots and prevents its recreation", async () => {- const h = harness();- h.host.rememberLocation("A", "A.html");- h.host.setChromeSession("A");- h.host.disposeGuest();- h.roots.at(-1).resolve("/projects/A");- await settled();- assert.deepEqual(h.loads, []);- assert.equal(h.visible, false);+test("closing a tab and disposing the host cancel pending ownership and release pages", async () => {+ const h = harness(); await open(h, "A", "a", "A.html");+ h.host.setChromeSession("A", "pending", "pending.html"); const root = h.roots.at(-1);+ h.host.closeTab("A", "pending"); root.resolve("/projects/A"); await settled();+ assert.equal(h.loads.length, 1);+ h.host.setChromeSession("A", "a"); assert.equal(h.host.getState().url, "A.html");+ h.host.disposeGuest(); assert.equal(h.panes.every((pane) => pane.disposed), true);+ assert.equal(h.host.getState(), null);});-test("a failed replacement load leaves the previous session hidden", async () => {- const h = harness();- await openPreview(h, "A", "A.html");- h.host.rememberLocation("B", "B.html");- h.host.setChromeSession("B");- h.roots.at(-1).resolve("/projects/B");- await settled();- h.loads.at(-1).fail();- await settled();- h.hole();- assert.equal(h.visible, false);+test("a failed tab never exposes a sibling page", async () => {+ const h = harness(); await open(h, "A", "a", "A.html");+ h.host.setChromeSession("B", "b", "B.html"); h.roots.at(-1).resolve("/projects/B"); await settled();+ h.loads.at(-1).fail(); await settled();+ assert.equal(h.panes.some((pane) => pane.visible), false);+ assert.notEqual(h.host.getState()?.url, "A.html");});diff --git a/apps/desktop/test/browser-pane-navigation.test.mjs b/apps/desktop/test/browser-pane-navigation.test.mjsindex 9411f1c4e..e8a57d6d1 100644--- a/apps/desktop/test/browser-pane-navigation.test.mjs+++ b/apps/desktop/test/browser-pane-navigation.test.mjs@@ -49,7 +49,9 @@ function harness(t) {}test("timing out a new preview does not return the previous document as ready", async (t) => {- const { request } = harness(t);+ const { request, wc } = harness(t);+ wc.pendingLoads[0].resolve(); // An old document finishing cannot satisfy this load.+ await settled();t.mock.timers.tick(100);assert.equal(await request, null);});@@ -58,7 +60,11 @@ test("a rejected navigation does not return the previous document as ready", asyconst { pane, wc, request } = harness(t);t.mock.timers.tick(100);await request;- wc.loadURL = async () => { throw new Error("fixture load failure"); };+ wc.loadURL = async (url) => {+ wc.emit("did-start-navigation", {}, url, false, true);+ wc.emit("did-navigate", {}, wc.url); // Late commit of the preceding document.+ throw new Error("fixture load failure");+ };assert.equal(await pane.navigateAndWait("https://fixture.invalid/failed"), null);});@@ -66,7 +72,11 @@ test("a completed navigation returns its actual page, including redirects", asynconst { pane, wc, request } = harness(t);t.mock.timers.tick(100);await request;- wc.loadURL = async () => { wc.url = "https://fixture.invalid/redirected"; };+ wc.loadURL = async (url) => {+ wc.emit("did-start-navigation", {}, url, false, true);+ wc.url = "https://fixture.invalid/redirected";+ wc.emit("did-redirect-navigation", {}, wc.url, false, true);+ };const state = await pane.navigateAndWait("https://fixture.invalid/new");assert.equal(state.url, "https://fixture.invalid/redirected");});diff --git a/apps/desktop/test/plugin-view-location.test.mjs b/apps/desktop/test/plugin-view-location.test.mjsindex 9b9d1f4ec..042979f05 100644--- a/apps/desktop/test/plugin-view-location.test.mjs+++ b/apps/desktop/test/plugin-view-location.test.mjs@@ -200,5 +200,5 @@ test("pi.browser keeps its own location channel", () => {/\.\.\.\(isBrowserView \|\| !location \? \{\} : \{ location \}\),/,);assert.match(body, /browserHost\.setChromeSession\(sessionId,.*location\)/);- assert.match(body, /void browserHost\.navigate\(/);+ assert.doesNotMatch(body, /browserHost\.navigate\(/);});diff --git a/apps/desktop/test/plugin-work-panel-views.test.mjs b/apps/desktop/test/plugin-work-panel-views.test.mjsindex 09e1dc84c..70beab856 100644--- a/apps/desktop/test/plugin-work-panel-views.test.mjs+++ b/apps/desktop/test/plugin-work-panel-views.test.mjs@@ -257,7 +257,7 @@ test("the view list is filtered by permission, scope, and entry existence", () =/isBrowserView = pluginId === BROWSER_PLUGIN_ID && viewId === BROWSER_VIEW_ID/,);assert.match(openBody, /isBrowserView && sessionId/);- assert.match(openBody, /isBrowserView && location/);+ assert.match(openBody, /browserHost\.setChromeSession\(sessionId,.*location\)/);});test("opening a different project refreshes the scope-filtered view list", () => {diff --git a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md b/docs/adr/0170-work-panel-browser-as-bundled-plugin.mdindex 9b6450b8f..5f8b07b69 100644--- a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md+++ b/docs/adr/0170-work-panel-browser-as-bundled-plugin.md@@ -39,11 +39,10 @@ guest.stability). It errors if `pi.browser` is disabled; otherwise it loads theworkspace file into the guest when that session's chrome is visible andreveals the plugin view. Plugin CDP stays Agent-only (`plugin_*`).-6. **v1 is a singleton guest.** Session locations are remembered and rebound- when the originating conversation's plugin tab is shown (D142). Browser- resource tabs additionally retain their individual current locations; they- reuse the guest and reload on selection rather than retaining separate DOM- state/history. Background sessions do not steal the visible guest.+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+ a shared, host-controlled surface.This supersedes ADR 0105 clause 4 (Browser remains a host-built launcher) andthe host-launcher clause of ADR 0019. Guest ownership and navigation policy@@ -54,8 +53,8 @@ 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` share the same guest; last chrome- `setBounds` wins.+- Third-party plugins with `browser.cdp` address the current browser page;+ 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 a197d17a6..a43d3804f 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -342,3 +342,4 @@ Each ADR includes:| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](registry-header-variable-spelling.md) | Proposed || provider-system-certificates | [Desktop sidecar uses OS-trusted certificates](provider-system-certificates.md) | Accepted || image-generation-capability | [Image generation as a configured Agent capability](image-generation-capability.md) | Accepted |+| retained-browser-pages-per-tab | [Retain a host-owned browser page per resource tab](retained-browser-pages-per-tab.md) | Accepted |diff --git a/docs/adr/retained-browser-pages-per-tab.md b/docs/adr/retained-browser-pages-per-tab.mdnew file mode 100644index 000000000..6b7cf9605--- /dev/null+++ b/docs/adr/retained-browser-pages-per-tab.md@@ -0,0 +1,47 @@+# ADR: Retain a host-owned browser page per resource tab++- Status: Accepted+- Date: 2026-09-26+- Supersedes: ADR 0170 clause 6 (singleton guest)++## Context++Browser resource tabs initially retained addresses but shared one guest. Switching+reloaded pages and discarded form/scroll/JavaScript state. Mixing session-only+navigation with tab addresses also allowed BrowserPreview to overwrite the active+tab, background navigation to lose its destination, and empty tabs to expose old+state. The requested behavior is to keep each open tab's live page.++## Decision++Electron Main's BrowserHost owns pages keyed by session id and tab id. Each page+owns its BrowserPane, CDP state, navigation generation, and current browser state.+Only the selected page is attached to the measured browser hole; hidden pages+retain their WebContents and use Chromium background throttling. The browser+partition 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.+An empty tab has no inherited native page state.++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.++## Alternatives++Keeping one guest and saving only URLs cannot preserve live page state. Saving+and restoring arbitrary DOM/JavaScript state is not a reliable substitute for a+retained WebContents. Automatic suspension with serialized navigation state is+possible later, but needs explicit recovery and unsaved-input handling.++## Consequences++Normal tab switching preserves forms, scroll position and per-tab navigation+history without issuing another load. Memory usage grows with open pages; users+release that memory by closing tabs. No database schema or plugin permission is+added. Independent page ownership prevents stale work from changing another tab.diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 5c52fdf7f..a93949c33 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1742,12 +1742,16 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:- `browser/openExternal({url?})` — allowlisted http(s)/mailto, or the currentguest URL when omitted+- Renderer plugin-view open/close requests may carry `sessionId` and `tabId`.+ Open binds the resource tab after checking the plugin contribution and scope;+ close releases only that tab's retained page (or the session's pages when no+ 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,- loads the guest when that conversation's plugin view is visible, and the- renderer opens a Browser resource tab with `location` in the matching+ asks the renderer to create a Browser resource tab before navigation, with+ `location` in the matchingruntime panel context. Navigation of a background session does not steal thevisible guest.diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex f9c220e4f..db30d3344 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1045,8 +1045,9 @@ entirely inside the plugin's isolated page:folder the view is browsing — never the whole group — refuses credentialpaths, and records writes to its own audit log (ADR 0241, ADR 0263).-- During a Browser session switch, Main hides the shared guest immediately- until the destination's current main-frame navigation commits. Root lookup or load+- During a Browser session switch, Main hides the previous page immediately.+ A retained destination page is shown without reloading; a new destination+ 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@@ -1058,13 +1059,18 @@ entirely inside the plugin's isolated page:and cancelled requests cannot publish over the new navigation.- Opening an HTTP(S) link in the work panel creates an additional Browser- resource tab instead of replacing the previous URL. Each tab retains its- current address and title; selecting it restores that address in the shared- guest. Tabs are not independent live browser processes: switching reloads the- destination, and DOM state/history are not retained per tab. Address-bar and+ resource tab instead of replacing the previous URL. Each tab owns a host-retained WebContents, address, title and navigation+ history. Switching hides/shows pages without reloading, preserving live form,+ scroll and JavaScript state. Hidden pages use background throttling. Closing+ tabs releases their page/CDP resources; no automatic suspension or restart DOM+ recovery is promised. Address-bar andordinary 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.+- Main-frame same-document navigation (fragment links and History API routes) updatesthe browser address, history controls, and loading state without requiring afull document load. Subframe events and events from an invalidated session ordiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex fd3d37cbd..2b4f6cdae 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3796,10 +3796,18 @@ identify the platform validation still needed.Set Link open destination to External and repeat the new-window link.- **Expected**: The current document displays after main-frame commit; slowassets do not strand the empty state. New links preserve earlier resource- tabs. Each tab restores its last address; same-tab navigation updates only its+ tabs. Tab switching retains forms, scroll positions, JS state and independent history+ without another page request. Each tab keeps its last address; same-tab navigation updates only itsoriginating tab. Failure/stop leave usable address controls. External modedoes 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+ destroyed without affecting its sibling; deleting a session and plugin/window+ disposal release the appropriate retained pages.- **Status**: Targeted isolated Electron validation; no new repository test suite.#### E2E-BROWSER-in-page-navigation: Browser chrome follows same-document navigationdiff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 2410096bf..f5ace650a 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -649,7 +649,10 @@ loading immediately and optionally includes `loadError` for failed navigation.Optional `sessionId` and `tabId` identify the host-owned work-panel destination;plugins do not select these identities through navigation arguments.-The guest page is a host-owned `WebContentsView` (`persist:work-browser`).+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.`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 withdiff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex 92e5d54bf..8aa9e0f16 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -1376,6 +1376,8 @@ Chrome 和代理 CDP 位于随应用打包的 `pi.browser` 插件中,通过 `p渲染器 IPC 仅保留给 Plan 安全的预览门面和 URL 回退:- `browser/openExternal({url?})` — 白名单内的 http(s)/mailto,或省略时使用当前访客页 URL+- 渲染器打开/关闭插件视图时可携带 `sessionId`、`tabId`。打开前检查插件贡献和作用域;+ 关闭仅释放对应标签的页面,不关闭其他标签共享的工具栏。只提供会话 id 时释放该会话的页面。- 事件:`browser/event/state {url, title, isLoading, canGoBack, canGoForward, loadError?, sessionId?, tabId?}`(同时以 `browser:state` 推送给插件视图)- 代理预览事件:`browser/event/preview {sessionId, path?, url?}`。diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex ed49177e2..c70ad4e8d 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -763,7 +763,8 @@ vendor 进来的 `pi.file-manager` 视图在插件自己的隔离页面内完成自身的读写走自己的宿主进程,由该进程维持它正在浏览的那一个文件夹的牢笼(绝不是整个项目组)、拒绝凭据类路径,并把写入记进自己的审计日志(ADR 0241、ADR 0263)。-- 切换浏览器所属会话时,Main 立即隐藏共享 guest,直到目标会话的当前主框架导航提交。+- 切换浏览器所属会话时,Main 立即隐藏旧页面;已有目标页面直接显示而不重新加载,+ 新目标页面等待当前主框架导航提交后显示。已被替代请求的目录查询或加载完成不能再导航、显示或发布旧会话为当前内容。没有预览记录的会话保持空白;关闭面板或销毁 guest 的结果不能被未完成请求撤销。同一会话内的正常导航仍保留本会话当前显示的内容。地址栏立即反馈加载状态,@@ -772,11 +773,15 @@ vendor 进来的 `pi.file-manager` 视图在插件自己的隔离页面内完成被替代或取消的请求不得覆盖新导航。- 在工作面板中打开 HTTP(S) 链接会新增浏览器资源标签,不覆盖原网址。- 每个标签保存当前地址和标题,切换时在共享 guest 中重新加载对应地址。- 标签不是独立的常驻浏览器进程,不保留各自的 DOM 状态和浏览历史。+ 每个标签保留自己的 WebContents、地址、标题及浏览历史。切换只隐藏/显示页面,+ 保留当前表单、滚动位置和 JavaScript 状态;后台页面启用节流。关闭标签释放页面和 CDP 资源,+ 不承诺自动休眠或应用重启后的 DOM 恢复。地址栏和普通页内导航留在当前标签。网页请求打开新窗口时,遵循链接打开位置设置,新增工作面板标签或打开系统浏览器。+- BrowserPreview 先创建目标资源标签,再开始导航,不改写原标签。后台导航保存到该会话+ 上次选择的标签;尚无标签时,由第一个标签消费一次。新空白标签返回空状态。+- 主框架的同文档导航(锚点链接和 History API 路由)无需完整加载文档,也必须更新浏览器地址、历史导航按钮及加载状态。子框架、失效会话或已被替换主框架的事件不得发布浏览器状态。diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 35f9ede42..5e4335e7a 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -2289,9 +2289,12 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的- **前提**:浏览器已启用;隔离配置;本地页面包含延迟 17 秒的图片、延迟主响应及普通/新窗口链接。- **步骤**:输入慢图片页面地址,检查加载反馈及图片完成前的显示;打开两个聊天链接和网页新窗口链接,切换标签,在其中一个标签内导航后再切走、切回;检查慢主响应、停止、失败、重试及外部打开设置。-- **预期**:主框架导航提交后显示页面;新链接保留原标签,各标签恢复最新地址;+- **预期**:主框架导航提交后显示页面;新链接保留原标签,各标签保留表单、滚动位置、JS 状态和独立历史,切换不重新请求页面;普通导航只更新原标签。失败/停止后地址栏仍可用;外部模式不新建工作面板标签。会话切换、非法协议的隔离和可见性规则继续生效。+- **补充路径**:通过 ToolSearch/BrowserPreview 预览文件,原标签的未提交表单和地址不被改写;+ 后台导航恢复到对应会话的标签,旧加载完成不能覆盖新意图;新空白标签地址和状态为空;+ 关闭后台标签销毁对应 WebContents,不影响其他标签,删除会话或销毁插件/窗口释放所属页面。- **状态**:隔离 Electron 定向验证;不新增仓库测试套件。#### E2E-BROWSER-in-page-navigation:浏览器工具栏跟随同文档导航diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex 651d0c131..160355ff9 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -520,7 +520,8 @@ pi.browser.console(input?: { limit?: number }): Promise<{ messages: unknown[] }>pi.browser.cdp(input: { method: string; params?: unknown }): Promise<unknown>```-访客页是宿主拥有的 `WebContentsView`(`persist:work-browser`)。+当前访客页是宿主拥有的 `WebContentsView`(`persist:work-browser`),各资源标签保留自己的页面。+后台会话导航保留给该会话上次选中的标签;尚无标签时由首个标签消费,不导航或返回其他会话的页面。`setBounds` 相对调用插件视图的内容区,并被夹紧,因此访客页不能盖住聊天/输入框。`cdp` 默认拒绝;cookie、storage、target 和网络拦截方法以 `PERMISSION_DENIED` 失败。代理调用的会话身份来自进行中的 `plugins.execute` `sessionId`,而不是插件参数(D333 / ADR 0170)。