Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(browser): auto-reveal Browser per session

vastsa06f2b8849369
diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.ts
index 0d6a5124a..1644dcd05 100644
--- a/apps/desktop/electron/main/browser-host.ts
+++ b/apps/desktop/electron/main/browser-host.ts
@@ -7,6 +7,7 @@ import { join } from "node:path";
export const BROWSER_PLUGIN_ID = "pi.browser";
export const BROWSER_VIEW_ID = "browser";
+const BROWSER_REVEAL_TIMEOUT_MS = 5_000;
export type BrowserRect = {
x: number;
@@ -61,6 +62,7 @@ export type BrowserHostDeps = {
getFileRoot: (sessionId?: string) => Promise<string | null>;
getScratchDir?: (sessionId?: string) => string | null;
onState: (state: BrowserState) => void;
+ onRevealView?: (sessionId: string, tabId?: string) => void;
};
type ChromeSurface = {
@@ -70,6 +72,13 @@ type ChromeSurface = {
bounds: BrowserRect;
};
+type BrowserRevealWaiter = {
+ sessionId: string;
+ resolve: () => void;
+ reject: (error: Error) => void;
+ timeout: ReturnType<typeof setTimeout>;
+};
+
type BrowserPage = {
key: string;
sessionId: string;
@@ -90,6 +99,7 @@ export class BrowserHost {
private readonly selectedTabs = new Map<string, string | null>();
private readonly pendingSessions = new Map<string, string>();
private readonly pendingTabs = new Set<string>();
+ private readonly revealWaiters = new Set<BrowserRevealWaiter>();
private active: BrowserPage | null = null;
private window: BrowserWindow | null = null;
private chrome: ChromeSurface | null = null;
@@ -108,6 +118,52 @@ export class BrowserHost {
setChromeSurface(surface: ChromeSurface | null): void {
this.chrome = surface;
this.applyGuest();
+ this.resolveVisibleRevealWaiters();
+ }
+
+ async reveal(sessionId?: string): Promise<void> {
+ const id = sessionId?.trim();
+ if (!id) throw this.unavailableError("Browser reveal requires an active session.");
+ if (!this.deps.isPluginLoaded(BROWSER_PLUGIN_ID)) {
+ throw this.unavailableError("The Browser plugin is unavailable.");
+ }
+ if (this.isBrowserVisibleForSession(id)) return;
+ const revealView = this.deps.onRevealView;
+ if (!revealView) throw this.unavailableError("Browser view cannot be opened by this host.");
+
+ let waiter: BrowserRevealWaiter | undefined;
+ const visible = new Promise<void>((resolve, reject) => {
+ const entry: BrowserRevealWaiter = {
+ sessionId: id,
+ resolve,
+ reject: (error) => reject(error),
+ timeout: setTimeout(() => {
+ this.rejectRevealWaiter(
+ entry,
+ this.unavailableError(
+ "Browser view did not become visible for the calling session. Switch to that session and retry.",
+ ),
+ );
+ }, BROWSER_REVEAL_TIMEOUT_MS),
+ };
+ waiter = entry;
+ this.revealWaiters.add(entry);
+ });
+
+ try {
+ const tabId = this.active?.sessionId === id
+ ? this.active.tabId ?? undefined
+ : this.selectedTabs.get(id) ?? undefined;
+ revealView(id, tabId);
+ } catch (error) {
+ if (waiter) {
+ this.rejectRevealWaiter(
+ waiter,
+ error instanceof Error ? error : new Error(String(error)),
+ );
+ }
+ }
+ return visible;
}
getContext(): { sessionId?: string; tabId?: string } {
@@ -121,6 +177,32 @@ export class BrowserHost {
};
}
+ private isBrowserVisibleForSession(sessionId: string): boolean {
+ return this.chrome?.visible === true &&
+ this.chrome.pluginId === BROWSER_PLUGIN_ID &&
+ this.chrome.viewId === BROWSER_VIEW_ID &&
+ this.active?.sessionId === sessionId;
+ }
+
+ private resolveVisibleRevealWaiters(): void {
+ for (const waiter of [...this.revealWaiters]) {
+ if (!this.isBrowserVisibleForSession(waiter.sessionId)) continue;
+ this.revealWaiters.delete(waiter);
+ clearTimeout(waiter.timeout);
+ waiter.resolve();
+ }
+ }
+
+ private rejectRevealWaiter(waiter: BrowserRevealWaiter, error: Error): void {
+ if (!this.revealWaiters.delete(waiter)) return;
+ clearTimeout(waiter.timeout);
+ waiter.reject(error);
+ }
+
+ private unavailableError(message: string): Error & { code: string } {
+ return Object.assign(new Error(message), { code: "UNAVAILABLE" });
+ }
+
private assertBrowserViewVisible(): void {
if (
this.chrome?.visible === true &&
@@ -415,6 +497,12 @@ export class BrowserHost {
dispose(): void { this.disposeGuest(); }
disposeGuest(): void {
+ for (const waiter of [...this.revealWaiters]) {
+ this.rejectRevealWaiter(
+ waiter,
+ this.unavailableError("Browser view was closed before it became visible."),
+ );
+ }
for (const page of this.pages.values()) {
page.navigationVersion += 1;
page.cdp.detach(page.pane.getWebContents() ?? undefined);
diff --git a/apps/desktop/electron/main/plugin-host-process.mjs b/apps/desktop/electron/main/plugin-host-process.mjs
index 8a6937066..77c84e0e4 100644
--- a/apps/desktop/electron/main/plugin-host-process.mjs
+++ b/apps/desktop/electron/main/plugin-host-process.mjs
@@ -387,6 +387,7 @@ function buildApi() {
openExternal: (url) => call("shell.openExternal", [url]),
},
browser: {
+ reveal: () => call("browser.reveal"),
navigate: (input) => call("browser.navigate", [input ?? {}]),
action: (input) => call("browser.action", [input]),
setBounds: (hole) => call("browser.setBounds", [hole]),
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index 602a478a0..26e5344da 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -448,6 +448,7 @@ export type PluginHostServices = {
}) => Promise<void> | void;
/** Work-panel guest + CDP, gated by `browser.cdp` in the runtime. */
browser?: {
+ reveal: (sessionId?: string) => Promise<void>;
navigate: (
input: { url?: string; path?: string },
sessionId?: string,
@@ -550,6 +551,7 @@ const HOST_API_ALLOWLIST = new Set([
"bus.publish",
"bus.subscribe",
"bus.unsubscribe",
+ "browser.reveal",
"browser.navigate",
"browser.action",
"browser.setBounds",
@@ -5978,6 +5980,19 @@ export class PluginRuntime {
this.busUnsubscribe(loaded, subscriptionId),
},
browser: {
+ reveal: async () => {
+ this.assertPermission(loaded, "browser.cdp");
+ if (!this.services.browser) {
+ throw apiError("UNAVAILABLE", "browser host missing");
+ }
+ await this.services.browser.reveal(this.browserSessionId(pluginId));
+ this.services.audit?.({
+ pluginId,
+ api: "browser.reveal",
+ ok: true,
+ ts: Date.now(),
+ });
+ },
navigate: async (input: { url?: string; path?: string } = {}) => {
this.assertPermission(loaded, "browser.cdp");
if (!this.services.browser) {
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 550ccfb5d..95e8afbde 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -620,6 +620,8 @@ export function createPluginServices({
return join(dataDir, "scratch", sessionId);
},
onState: emitBrowserState,
+ onRevealView: (sessionId, tabId) =>
+ sendToRenderer(IPC.event.browserPreview, { sessionId, tabId, revealOnly: true }),
});
pluginViews.onSurface = (surface) => {
browserHost.setChromeSurface(surface);
@@ -641,6 +643,7 @@ export function createPluginServices({
agentExtensionsChanged: () =>
sendToRenderer(IPC.event.pluginChanged, { reason: "agentExtensions" }),
browser: {
+ reveal: (sessionId) => browserHost.reveal(sessionId),
navigate: (input, sessionId, tabId) => browserHost.navigate(input, sessionId, tabId),
action: (action, sessionId, tabId) => browserHost.action(action, sessionId, tabId),
setBounds: (pluginId, hole) => browserHost.setGuestHole(pluginId, hole),
diff --git a/apps/desktop/resources/plugins/pi.browser/main.js b/apps/desktop/resources/plugins/pi.browser/main.js
index 3dee902b3..62da193a0 100644
--- a/apps/desktop/resources/plugins/pi.browser/main.js
+++ b/apps/desktop/resources/plugins/pi.browser/main.js
@@ -29,11 +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.',
- "Before any browser operation, ensure the Browser view is open and visible in the work panel.",
+ "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 Browser tab.",
- "For other URLs, open or activate Browser from the work-panel launcher before navigating.",
- "If you cannot make the view visible, ask the user to open it and wait before continuing.",
+ "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.",
"Then snapshot the accessibility tree, click/fill by uid, take screenshots, evaluate JavaScript,",
"read console output, or send an allowlisted raw CDP method.",
].join(" "),
@@ -45,7 +44,7 @@ export async function onLoad() {
action: {
type: "string",
enum: ACTIONS,
- description: "Run only after confirming the Browser view is open and visible in the work panel.",
+ description: "The Browser view opens automatically for the calling session before this action runs.",
},
url: { type: "string", description: "http(s) URL for action=navigate." },
path: {
@@ -79,6 +78,13 @@ export async function onLoad() {
},
execute: async (args) => {
const action = String(args?.action ?? "").trim();
+ if (!ACTIONS.includes(action)) {
+ return {
+ ok: false,
+ 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.tsx
index 8b16e8b52..18967e05f 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -27,7 +27,7 @@ import {
MAIN_PANE_MIN_WIDTH,
workPanelWidthForSidebarReopen,
} from "../../lib/work-panel-resize";
-import { browserPluginTab } from "../../lib/work-panel-tabs";
+import { browserPluginTab, browserPluginTabForReveal } from "../../lib/work-panel-tabs";
import { useAppStore } from "../../stores/app-store";
import { useSidebarTransition } from "./useSidebarTransition";
import { useStartupWatchdog } from "./useStartupWatchdog";
@@ -608,11 +608,20 @@ export function useAppShellRuntime() {
// opens a workspace file in the embedded browser (BrowserPreview tool).
const offBrowserState = api.onBrowserState((event) => useAppStore.getState().updateBrowserWorkPanelTab(event));
const offBrowserPreview = api.onBrowserPreview((event) => {
- useAppStore
- .getState()
- .openWorkPanelTabForSession(event.sessionId, {
- ...browserPluginTab(event.path ?? event.url),
- });
+ const state = useAppStore.getState();
+ if (event.revealOnly) {
+ const context = state.activeSessionId === event.sessionId
+ ? { tabs: state.workPanelTabs, activeTabId: state.activeWorkPanelTabId }
+ : state.workPanelContexts[event.sessionId];
+ state.openWorkPanelTabForSession(
+ event.sessionId,
+ browserPluginTabForReveal(context?.tabs ?? [], context?.activeTabId ?? null, event.tabId),
+ );
+ return;
+ }
+ state.openWorkPanelTabForSession(event.sessionId, {
+ ...browserPluginTab(event.path ?? event.url),
+ });
});
const offHostStatus = api.onHostStatus((status) => {
if (status.archMismatch) setArchMismatch(status.archMismatch);
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 8b68cad3f..12a22c89d 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -1523,11 +1523,23 @@ export const api = {
);
},
onBrowserPreview: (
- listener: (event: { sessionId: string; path?: string; url?: string }) => void,
+ listener: (event: {
+ sessionId: string;
+ path?: string;
+ url?: string;
+ tabId?: string;
+ revealOnly?: boolean;
+ }) => void,
) => {
if (!window.piDesktop?.on) return () => undefined;
return window.piDesktop.on(IPC.event.browserPreview, (payload) =>
- listener(payload as { sessionId: string; path?: string; url?: string }),
+ listener(payload as {
+ sessionId: string;
+ path?: string;
+ url?: string;
+ tabId?: string;
+ revealOnly?: boolean;
+ }),
);
},
onAgentEvent: (listener: (event: AgentEventEnvelope) => void) => {
diff --git a/apps/desktop/src/lib/work-panel-tabs.ts b/apps/desktop/src/lib/work-panel-tabs.ts
index dfa6b65b1..dac6dfc60 100644
--- a/apps/desktop/src/lib/work-panel-tabs.ts
+++ b/apps/desktop/src/lib/work-panel-tabs.ts
@@ -151,6 +151,21 @@ export function browserPluginTab(location?: string): WorkPanelTab {
return { ...base, id: `${base.id}:${Date.now().toString(36)}-${++newWorkPanelTabSequence}`, location: target, label: browserTabLabel(target) };
}
+export function browserPluginTabForReveal(
+ tabs: WorkPanelTab[],
+ activeTabId: string | null,
+ preferredTabId?: string,
+): WorkPanelTab {
+ const isBrowserTab = (tab: WorkPanelTab) =>
+ tab.kind === "plugin" && tab.resource === `${BROWSER_PLUGIN_TAB.pluginId}/${BROWSER_PLUGIN_TAB.viewId}`;
+ const preferred = preferredTabId
+ ? tabs.find((tab) => tab.id === preferredTabId && isBrowserTab(tab))
+ : undefined;
+ const active = tabs.find((tab) => tab.id === activeTabId && isBrowserTab(tab));
+ const latest = [...tabs].reverse().find(isBrowserTab);
+ return preferred ?? active ?? latest ?? browserPluginTab();
+}
+
export function browserTabLabel(location: string): string {
try { return new URL(location).host || location; } catch { return location.split(/[\\/]/).at(-1) || location; }
}
diff --git a/apps/desktop/test/browser-cdp.test.mjs b/apps/desktop/test/browser-cdp.test.mjs
index 5eff5549e..b31103d08 100644
--- a/apps/desktop/test/browser-cdp.test.mjs
+++ b/apps/desktop/test/browser-cdp.test.mjs
@@ -113,8 +113,15 @@ const runtimeSource = readFileSync(
);
const mainSource = readMainSourceSync();
+test("browser.reveal is admitted by the plugin host API allowlist", () => {
+ const allowlist = runtimeSource.match(/const HOST_API_ALLOWLIST = new Set\(\[([\s\S]*?)\]\);/)?.[1] ?? "";
+ assert.match(allowlist, /"browser\.reveal"/);
+ assert.match(runtimeSource, /this\.services\.browser\.reveal\(this\.browserSessionId\(pluginId\)\)/);
+});
+
test("in-flight tool.execute session survives the child host-api round trip", () => {
assert.match(runtimeSource, /private readonly toolInvocations = new PluginToolInvocations/);
+ assert.match(runtimeSource, /reveal: async \(\) => \{[\s\S]*browserSessionId\(pluginId\)/);
assert.match(runtimeSource, /toolInvocations\.begin\(target/);
assert.match(runtimeSource, /invocationId: invocation\.id/);
assert.match(runtimeSource, /this\.browserSessionId\(pluginId\)/);
diff --git a/apps/desktop/test/browser-host-session.test.mjs b/apps/desktop/test/browser-host-session.test.mjs
index 3bdd79ae5..875c28e13 100644
--- a/apps/desktop/test/browser-host-session.test.mjs
+++ b/apps/desktop/test/browser-host-session.test.mjs
@@ -11,7 +11,7 @@ function deferred() {
return { promise, resolve };
}
function harness() {
- const roots = [], loads = [], panes = [], published = [];
+ const roots = [], loads = [], panes = [], published = [], reveals = [];
const createPane = (onState) => {
let state = null;
const pane = {
@@ -39,6 +39,7 @@ function harness() {
const done = deferred(); roots.push({ sessionId, ...done }); return done.promise;
},
onState: (state) => published.push(state),
+ onRevealView: (sessionId, tabId) => reveals.push({ sessionId, tabId }),
});
const surface = (visible = true) => host.setChromeSurface({
pluginId: "pi.browser", viewId: "browser", visible,
@@ -46,7 +47,7 @@ function harness() {
});
surface();
host.setGuestHole("pi.browser", { x: 0, y: 30, width: 400, height: 570 });
- return { host, roots, loads, panes, published, surface };
+ return { host, roots, loads, panes, published, reveals, surface };
}
async function open(h, sessionId, tabId, url) {
h.host.setChromeSession(sessionId, tabId, url);
@@ -147,7 +148,64 @@ test("closing the panel keeps a pending page hidden until the panel returns", as
h.surface(); assert.equal(h.panes[0].visible, true);
});
-test("plugin browser operations are unavailable while the Browser view is hidden", async () => {
+test("Browser reveal opens the calling session and waits for its visible view", async () => {
+ const h = harness();
+ await open(h, "A", "a", "https://fixture.invalid/current");
+ h.surface(false);
+
+ let resolved = false;
+ const reveal = h.host.reveal("A").then(() => { resolved = true; });
+ assert.deepEqual(h.reveals, [{ sessionId: "A", tabId: "a" }]);
+ h.surface(false);
+ assert.equal(resolved, false, "a hidden view must not release the operation");
+ h.surface(true);
+ await reveal;
+ assert.equal(resolved, true);
+});
+
+test("switching sessions reveals an isolated Browser page and preserves the previous session", async () => {
+ const h = harness();
+ await open(h, "A", "a", "https://fixture.invalid/a");
+ h.surface(false);
+
+ const reveal = h.host.reveal("B");
+ assert.deepEqual(h.reveals, [{ sessionId: "B", tabId: undefined }]);
+ h.host.setChromeSession("B", "plugin:pi.browser/browser");
+ h.surface(true);
+ await reveal;
+ assert.equal(h.host.getContext().sessionId, "B");
+
+ const navigation = h.host.navigate({ url: "https://fixture.invalid/b" }, "B");
+ h.roots.at(-1).resolve("/projects/B");
+ await settled();
+ h.loads.at(-1).finish();
+ assert.equal((await navigation).url, "https://fixture.invalid/b");
+
+ h.host.setChromeSession("A", "a");
+ assert.equal(h.host.getState().url, "https://fixture.invalid/a");
+});
+
+test("Browser reveal returns UNAVAILABLE when the session view never appears", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const h = harness();
+ const timedOut = assert.rejects(h.host.reveal("B"), { code: "UNAVAILABLE" });
+ t.mock.timers.tick(5_000);
+ await timedOut;
+ assert.deepEqual(h.reveals, [{ sessionId: "B", tabId: undefined }]);
+});
+
+test("Browser reveal never steals focus from a different session", async () => {
+ const h = harness();
+ await open(h, "A", "a", "https://fixture.invalid/current");
+ h.surface(false);
+ const reveal = h.host.reveal("B");
+ assert.deepEqual(h.reveals, [{ sessionId: "B", tabId: undefined }]);
+ assert.equal(h.host.getContext().sessionId, "A");
+ h.host.disposeGuest();
+ await assert.rejects(reveal, (error) => error?.code === "UNAVAILABLE");
+});
+
+test("plugin browser operations remain unavailable until the Browser view is visible", 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" });
diff --git a/apps/desktop/test/browser-preview-tool.test.mjs b/apps/desktop/test/browser-preview-tool.test.mjs
index 10aeb27ff..18584b58f 100644
--- a/apps/desktop/test/browser-preview-tool.test.mjs
+++ b/apps/desktop/test/browser-preview-tool.test.mjs
@@ -72,19 +72,20 @@ test("main serves BrowserPreview from its originating session workspace", () =>
test("renderer routes browser preview events to the originating session", () => {
assert.match(
apiSource,
- /onBrowserPreview:[\s\S]*event: \{ sessionId: string; path\?: string; url\?: string \}/,
+ /onBrowserPreview:[\s\S]*event: \{[\s\S]*sessionId: string;[\s\S]*tabId\?: string;[\s\S]*revealOnly\?: boolean/,
);
const previewHandler =
appSource.match(/api\.onBrowserPreview\([\s\S]*?\n\s*\}\);/)?.[0] ?? "";
assert.ok(previewHandler, "browser preview renderer handler exists");
assert.match(
previewHandler,
- /openWorkPanelTabForSession\((?:event\.)?sessionId,[\s\S]*browserPluginTab/,
+ /openWorkPanelTabForSession\(\s*event\.sessionId,[\s\S]*browserPluginTabForReveal/,
);
assert.doesNotMatch(
appSource,
/api\.onBrowserPreview\(\(\) => \{\s*useAppStore\.getState\(\)\.openWorkPanelTab/,
);
+ assert.match(appSource, /event\.revealOnly/);
assert.match(appSource, /offBrowserPreview\(\);/);
});
@@ -108,25 +109,42 @@ test("agent runtime exposes BrowserPreview in every mode and prompts for it", ()
assert.match(runtimeSource, /live-reloads/);
});
-test("Browser tool prompt requires the work-panel view to stay visible", () => {
- assert.match(
- browserPluginSource,
- /Before any browser operation, ensure the Browser view is open and visible in the work panel/,
- );
- assert.match(
- browserPluginSource,
- /For a workspace HTML file, call BrowserPreview first; it opens and reveals a Browser tab/,
- );
- assert.match(
- browserPluginSource,
- /For other URLs, open or activate Browser from the work-panel launcher before navigating/,
- );
- assert.match(
- browserPluginSource,
- /If you cannot make the view visible, ask the user to open it and wait before continuing/,
- );
- assert.match(
- browserPluginSource,
- /Run only after confirming the Browser view is open and visible in the work panel/,
- );
+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\(\)/);
+
+ let registeredTool;
+ const calls = [];
+ const previousPi = globalThis.pi;
+ globalThis.pi = {
+ agent: {
+ registerTool: async (tool) => { registeredTool = tool; },
+ unregisterTool: async () => {},
+ },
+ browser: {
+ reveal: async () => { calls.push("reveal"); },
+ snapshot: async () => {
+ calls.push("snapshot");
+ return { tree: "- e1 WebArea", url: "https://fixture.invalid", title: "Fixture" };
+ },
+ },
+ };
+ try {
+ const 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(result, {
+ ok: true,
+ action: "snapshot",
+ tree: "- e1 WebArea",
+ url: "https://fixture.invalid",
+ title: "Fixture",
+ });
+ await plugin.onUnload();
+ } finally {
+ if (previousPi === undefined) delete globalThis.pi;
+ else globalThis.pi = previousPi;
+ }
});
diff --git a/apps/desktop/test/plugin-tool-invocations.test.mjs b/apps/desktop/test/plugin-tool-invocations.test.mjs
index d77178641..079440dfb 100644
--- a/apps/desktop/test/plugin-tool-invocations.test.mjs
+++ b/apps/desktop/test/plugin-tool-invocations.test.mjs
@@ -52,6 +52,7 @@ const PLUGIN = `
execute: async (args, ctx) => {
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.wait) {
return new Promise((resolve) => {
const finish = () => { aborted.add(ctx.sessionId); resolve({ aborted: true }); };
@@ -76,12 +77,13 @@ const PLUGIN = `
async function fixture(t, onInvoke) {
const dir = mkdtempSync(join(tmpdir(), "pi-tool-invocations-"));
const id = "demo.invocations";
- const permissions = ["agent.tool.register", "desktop.control", "session.read"];
+ const permissions = ["agent.tool.register", "browser.cdp", "desktop.control", "session.read"];
writeFileSync(join(dir, "manifest.json"), JSON.stringify({
schemaVersion: 1, id, name: id, version: "0.0.1", main: "main.js", permissions,
}));
writeFileSync(join(dir, "main.js"), PLUGIN);
const calls = [];
+ const reveals = [];
const runtime = new PluginRuntime({
hostEntry,
spawnProcess({ entry }) {
@@ -97,15 +99,25 @@ async function fixture(t, onInvoke) {
operations: [{ id: "session/get", risk: "read" }, { id: "session/create", risk: "write" }],
async invoke(input) { calls.push(input); return onInvoke(input); },
},
+ browser: {
+ async reveal(sessionId) { reveals.push(sessionId); },
+ },
getSessionContext: async (sessionId) => ({ sessionId, messages: [], truncated: false }),
});
t.after(async () => { await runtime.unload(id); rmSync(dir, { recursive: true, force: true }); });
await runtime.loadFromPath(dir, permissions);
const tool = runtime.getTools().find((entry) => entry.name === "probe");
assert.ok(tool);
- return { id, runtime, tool, calls };
+ return { id, runtime, tool, calls, reveals };
}
+test("browser.reveal reaches Main with the invoking session context", { timeout: 5000 }, async (t) => {
+ const { tool, reveals } = await fixture(t, async () => ({}));
+ const result = await tool.execute({ reveal: true }, { sessionId: "session-b", turnId: "turn-b" });
+ assert.equal(result.sessionId, "session-b");
+ assert.deepEqual(reveals, ["session-b"]);
+});
+
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/apps/desktop/test/work-panel-tabs.test.mjs b/apps/desktop/test/work-panel-tabs.test.mjs
index 96fe3a9f9..9683aef2a 100644
--- a/apps/desktop/test/work-panel-tabs.test.mjs
+++ b/apps/desktop/test/work-panel-tabs.test.mjs
@@ -5,6 +5,7 @@ const {
FILE_MANAGER_PLUGIN_TAB,
activateWorkPanelTabState,
browserPluginTab,
+ browserPluginTabForReveal,
closeWorkPanelTabState,
createWorkPanelFileRequest,
emptyWorkPanelContext,
@@ -73,6 +74,16 @@ test("selecting an already-open tool removes only the source launcher tab", () =
assert.equal(replaced.activeTabId, browser.id);
});
+test("Browser reveal reuses the originating session's browser tab", () => {
+ const first = browserPluginTab("https://example.com/first");
+ const latest = browserPluginTab("https://example.com/latest");
+ const tabs = [first, toolWorkPanelTab("review"), latest];
+
+ assert.equal(browserPluginTabForReveal(tabs, "review", first.id), first);
+ assert.equal(browserPluginTabForReveal(tabs, latest.id), latest);
+ assert.equal(browserPluginTabForReveal([], null).id, browserPluginTab().id);
+});
+
test("file tabs normalize lexical paths and remain distinct by resource", () => {
const first = fileWorkPanelTab("src\\App.tsx");
const equivalent = fileWorkPanelTab("./src//components/../App.tsx");
diff --git a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md b/docs/adr/0170-work-panel-browser-as-bundled-plugin.md
index 5f8b07b69..b0dc8c84e 100644
--- a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md
+++ b/docs/adr/0170-work-panel-browser-as-bundled-plugin.md
@@ -37,8 +37,11 @@ guest.
network-interception methods are refused. No DevTools websocket is exposed.
5. **Host `BrowserPreview` remains a thin facade** (Plan/subagent name
stability). It errors if `pi.browser` is disabled; otherwise it loads the
- workspace file into the guest when that session's chrome is visible and
- reveals the plugin view. Plugin CDP stays Agent-only (`plugin_*`).
+ 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_*`).
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
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d2a46698c..9f41e610b 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -1601,16 +1601,21 @@ identify the platform validation still needed.
2) With the work panel closed, ask the agent to preview a workspace HTML
file (`BrowserPreview`) and verify the Browser tab opens in the visible work
panel. 3) Use ToolSearch `cdp` / `Browser` to snapshot and interact while the
- panel remains visible. 4) For an HTTP(S) URL, verify the agent opens or
- activates Browser before navigating; if it cannot reveal the view, it asks
- the user to open it before continuing. 5) Switch to Plan and call the plugin
- Browser tool. 6) Disable `pi.browser`. 7) Call `BrowserPreview` and click an
- http(s) transcript link. 8) From a third-party or test caller, send
+ 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
+ `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
- are made only while the view is visible; the agent waits for the user to
- reveal it if necessary. Plugin tool `plugin_pi_browser_Browser` can snapshot
+ 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
hides the view and tools; `BrowserPreview` errors; http(s) chips use
diff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.md
index a4c1f987b..0be6b6dbf 100644
--- a/docs/spec/07-plugins/03-plugin-api.md
+++ b/docs/spec/07-plugins/03-plugin-api.md
@@ -803,6 +803,7 @@ hrefs (D330 / ADR 0168). Other schemes fail with `INVALID_ARGUMENT`.
### browser (requires `browser.cdp`)
```ts
+pi.browser.reveal(): Promise<void>
pi.browser.navigate(input: { url?: string; path?: string }): Promise<BrowserState | null>
pi.browser.action(input: { action: "back" | "forward" | "reload" | "stop" }): Promise<void>
pi.browser.setBounds(hole: { x: number; y: number; width: number; height: number }): Promise<unknown>
@@ -835,8 +836,11 @@ storage, target, and network-interception methods fail with
`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. Calls made while it is hidden fail with `UNAVAILABLE`; use
-`BrowserPreview` to ask the host to reveal the Browser view before continuing.
+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.
`getHistory` returns newest-first entries explicitly recorded by the host, with
text and images interleaved in capture order. Content written through
diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts
index 809d5e130..c3ba33f7d 100644
--- a/packages/plugin-sdk/src/index.ts
+++ b/packages/plugin-sdk/src/index.ts
@@ -1334,6 +1334,8 @@ export type PluginHostApi = {
openExternal: (url: string) => Promise<void>;
};
browser: {
+ /** Reveal the Browser view for the calling session and wait until it is ready. */
+ reveal: () => Promise<void>;
navigate: (input: { url?: string; path?: string }) => Promise<unknown>;
action: (input: { action: "back" | "forward" | "reload" | "stop" }) => Promise<void>;
setBounds: (hole: { x: number; y: number; width: number; height: number }) => Promise<unknown>;