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): reveal committed pages and retain link tabs
zszz3e8684dd5a384
diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.tsindex e763f1822..240810175 100644--- a/apps/desktop/electron/main/browser-host.ts+++ b/apps/desktop/electron/main/browser-host.ts@@ -81,6 +81,7 @@ export class BrowserHost {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;@@ -94,19 +95,37 @@ export class BrowserHost {this.applyGuest();}- setChromeSession(sessionId: string | undefined): void {+ getContext(): { sessionId?: string; tabId?: string } {+ return { ...(this.chromeSessionId ? { sessionId: this.chromeSessionId } : {}),+ ...(this.chromeTabId ? { tabId: this.chromeTabId } : {}) };+ }++ publishState(state: BrowserState): void {+ if (this.chromeSessionId && state.url) this.rememberLocation(this.chromeSessionId, state.url);+ this.deps.onState({ ...state, ...this.getContext() });+ }++ private locationKey(sessionId: string, tabId = this.chromeTabId): string {+ return JSON.stringify([sessionId, tabId]);+ }++ setChromeSession(sessionId: string | undefined, tabId?: string, location?: string): boolean {const next = sessionId?.trim() || null;- if (this.chromeSessionId === next) return;+ 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);});}+ return true;}/**@@ -139,7 +158,7 @@ export class BrowserHost {const id = sessionId?.trim();const value = location.trim();if (!id || !value) return;- this.locations.set(id, value);+ this.locations.set(this.locationKey(id, id === this.chromeSessionId ? this.chromeTabId : null), value);}async navigate(@@ -158,7 +177,7 @@ export class BrowserHost {target,this.deps.getFileRoot(sessionId ?? this.chromeSessionId ?? undefined),);- if (state) this.deps.onState(state);+ if (state) this.publishState(state);return state;}@@ -167,7 +186,8 @@ export class BrowserHost {}getState(): BrowserState | null {- return this.pane.getState();+ const state = this.pane.getState();+ return state ? { ...state, ...this.getContext() } : null;}openExternal(): void {@@ -269,7 +289,7 @@ export class BrowserHost {}private async rebindSession(sessionId: string): Promise<void> {- const location = this.locations.get(sessionId);+ const location = this.locations.get(this.locationKey(sessionId));if (!location) return;await this.navigateGuest(location, this.deps.getFileRoot(sessionId));}@@ -283,9 +303,13 @@ export class BrowserHost {if (epoch !== this.navigationEpoch) return null;const state = await this.pane.navigateAndWait(target, fileRoot);if (epoch !== this.navigationEpoch) return null;- // A failed or timed-out load is not evidence that the previous session's- // document has been replaced. Only a completed navigation makes it ready.- if (state) this.started = true;+ // 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;}diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.tsindex 50174ac01..e89d2d395 100644--- a/apps/desktop/electron/main/browser-view.ts+++ b/apps/desktop/electron/main/browser-view.ts@@ -89,9 +89,15 @@ export class BrowserPane {private stateEventsEpoch: number | null = null;private stateUrl: string | null = null;private nativeNavigationPending = false;+ private pendingTarget: string | null = null;+ private loadError: { url: string; message: string } | null = null;+ private cancelPending: (() => void) | null = null;- constructor(onState: (state: BrowserState) => void) {+ private readonly onOpenUrl?: (url: string) => void;++ constructor(onState: (state: BrowserState) => void, onOpenUrl?: (url: string) => void) {this.onState = onState;+ this.onOpenUrl = onOpenUrl;}setWindow(window: BrowserWindow | null): void {@@ -104,9 +110,10 @@ export class BrowserPane {const wc = this.view?.webContents;if (!wc || wc.isDestroyed()) return null;return {- url: wc.getURL(),+ url: this.loadError?.url ?? this.pendingTarget ?? wc.getURL(),title: wc.getTitle(),- isLoading: wc.isLoading(),+ isLoading: !this.loadError && (this.pendingTarget !== null || wc.isLoading()),+ ...(this.loadError ? { loadError: this.loadError.message } : {}),canGoBack: wc.navigationHistory.canGoBack(),canGoForward: wc.navigationHistory.canGoForward(),};@@ -124,6 +131,10 @@ export class BrowserPane {* navigation establishes a new event scope.*/invalidateNavigation(): void {+ this.cancelPending?.();+ this.cancelPending = null;+ this.pendingTarget = null;+ this.loadError = null;this.navigationEpoch += 1;this.stateEventsEpoch = null;this.stateUrl = null;@@ -131,33 +142,7 @@ export class BrowserPane {}navigate(raw: string, fileRoot: string | null = null): BrowserState | null {- if (fileRoot) this.fileRoot = fileRoot;- const localPath = resolveLocalFile(raw, this.fileRoot);- if (localPath) {- const epoch = this.beginManagedNavigation();- const view = this.ensureView();- this.watchDirForReload(dirname(localPath));- void view.webContents- .loadURL(pathToFileURL(localPath).toString())- .then(() => this.completeManagedNavigation(epoch))- .catch(() => {- // A failed replacement must not publish the previous document.- });- if (this.visible) this.attach();- return this.getState();- }- const url = normalizeUrl(raw);- if (!url) return this.getState();- const epoch = this.beginManagedNavigation();- this.clearLiveReload();- const view = this.ensureView();- void view.webContents- .loadURL(url)- .then(() => this.completeManagedNavigation(epoch))- .catch(() => {- // A failed replacement must not publish the previous document.- });- if (this.visible) this.attach();+ void this.navigateAndWait(raw, fileRoot);return this.getState();}@@ -171,36 +156,72 @@ export class BrowserPane {const target = localPath? pathToFileURL(localPath).toString(): normalizeUrl(raw);- if (!target) return null;+ if (!target) {+ this.beginManagedNavigation();+ this.loadError = { url: raw, message: "INVALID_URL" };+ const state = this.getState();+ if (state) this.onState(state);+ return null;+ }const epoch = this.beginManagedNavigation();+ this.pendingTarget = target;+ this.loadError = null;if (localPath) this.watchDirForReload(dirname(localPath));else this.clearLiveReload();const view = this.ensureView();+ const wc = view.webContents;+ const loading = this.getState();+ if (loading) this.onState(loading);if (this.visible) this.attach();- let timer: ReturnType<typeof setTimeout> | undefined;- try {- const completed = await Promise.race([- view.webContents.loadURL(target).then(() => true),- new Promise<false>((resolve) => {- timer = setTimeout(() => resolve(false), Math.max(1, timeoutMs));- }),- ]);- if (!completed || epoch !== this.navigationEpoch) return null;- const state = this.getState();- if (state) this.enableStateEvents(epoch, state.url);- return state;- } catch {- // Load failures still surface through did-fail-load → state push, but- // must not make a previous session's document eligible for display.- return null;- } finally {- if (timer) clearTimeout(timer);- }+ return new Promise<BrowserState | null>((resolve) => {+ let settled = false;+ let started = false;+ const finish = (committed: boolean, error?: string) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ wc.removeListener("did-start-navigation", onStart);+ wc.removeListener("did-navigate", onCommit);+ if (epoch !== this.navigationEpoch) { resolve(null); return; }+ this.cancelPending = null;+ this.pendingTarget = null;+ if (error) this.loadError = { url: target, message: error };+ const state = this.getState();+ if (committed && state) this.enableStateEvents(epoch, state.url);+ if (error && state) this.onState(state);+ resolve(committed ? state : null);+ };+ const onStart = (_event: unknown, url: string, inPlace: boolean, mainFrame: boolean) => {+ if (mainFrame && !inPlace && url === target) started = true;+ };+ 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);+ };+ 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);+ void wc.loadURL(target).then(+ () => finish(true),+ (error: unknown) => finish(false, error instanceof Error ? error.message : String(error)),+ );+ });}action(action: "back" | "forward" | "reload" | "stop"): void {const wc = this.view?.webContents;if (!wc || wc.isDestroyed()) return;+ if (action === "stop" && this.pendingTarget) {+ const url = this.pendingTarget;+ this.cancelPending?.();+ this.loadError = { url, message: "ERR_ABORTED" };+ wc.stop();+ const state = this.getState();+ if (state) this.onState(state);+ return;+ }if (action === "back" && wc.navigationHistory.canGoBack()) {this.nativeNavigationPending = this.hasCurrentStateEventScope();wc.navigationHistory.goBack();@@ -338,7 +359,10 @@ export class BrowserPane {const wc = view.webContents;wc.setWindowOpenHandler(({ url }) => {const allowed = parseAllowedExternalUrl(url);- if (allowed) void shell.openExternal(allowed);+ if (allowed) {+ if (this.onOpenUrl) this.onOpenUrl(allowed);+ else void shell.openExternal(allowed);+ }return { action: "deny" };});wc.session.setPermissionRequestHandler((_wc, _permission, callback) => {@@ -395,7 +419,9 @@ export class BrowserPane {wc.on("did-fail-load",(_event, _errorCode, _errorDescription, validatedUrl, isMainFrame) => {- if (isMainFrame === false) return;+ // Replacing a still-loading document aborts its old request. That+ // event must not consume the pending navigation to the new document.+ if (isMainFrame === false || _errorCode === -3) return;if (this.acceptNativeNavigation(validatedUrl)) push();},);@@ -404,6 +430,10 @@ export class BrowserPane {}private beginManagedNavigation(): number {+ this.cancelPending?.();+ this.cancelPending = null;+ this.pendingTarget = null;+ this.loadError = null;const epoch = ++this.navigationEpoch;this.stateEventsEpoch = null;this.stateUrl = null;@@ -418,14 +448,6 @@ export class BrowserPane {this.nativeNavigationPending = false;}- private completeManagedNavigation(epoch: number): void {- if (epoch !== this.navigationEpoch) return;- const state = this.getState();- if (!state) return;- this.enableStateEvents(epoch, state.url);- this.onState(state);- }-private hasCurrentStateEventScope(): boolean {return this.stateEventsEpoch === this.navigationEpoch && this.stateUrl !== null;}diff --git a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts b/apps/desktop/electron/main/ipc/plugin-ui-ipc.tsindex 80ddbfc8b..6d8e30dfb 100644--- a/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts+++ b/apps/desktop/electron/main/ipc/plugin-ui-ipc.ts@@ -180,16 +180,13 @@ export function registerPluginUiIpc({viewId?: string;sessionId?: string;location?: string;+ tabId?: string;}) => {const pluginId = String(payload?.pluginId ?? "");const viewId = String(payload?.viewId ?? "");const sessionId = String(payload?.sessionId ?? "").trim();const location = String(payload?.location ?? "").trim();const isBrowserView = pluginId === BROWSER_PLUGIN_ID && viewId === BROWSER_VIEW_ID;- if (isBrowserView && sessionId) browserHost.setChromeSession(sessionId);- if (isBrowserView && sessionId && location) {- browserHost.rememberLocation(sessionId, location);- }const loaded = plugins.getLoaded(pluginId);if (!loaded) throw new Error("plugin not loaded");if (!loaded.permissions.has("ui.view")) {@@ -204,6 +201,8 @@ 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;pluginViews.open({pluginId,viewId,@@ -216,7 +215,7 @@ export function registerPluginUiIpc({// view receives the opener's subject untouched (D320 follow-up)....(isBrowserView || !location ? {} : { location }),});- if (isBrowserView && location) {+ if (isBrowserView && location && !switched && browserHost.getState()?.url !== location) {void browserHost.navigate({ path: location, url: location },sessionId || undefined,diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex 98bf9259d..1cbfb9b8d 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -549,7 +549,17 @@ export function createPluginServices({});}};- const browserPane = new BrowserPane(emitBrowserState);+ 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,diff --git a/apps/desktop/resources/plugins/pi.browser/views/browser.html b/apps/desktop/resources/plugins/pi.browser/views/browser.htmlindex 0bb6439ca..a5ac92b9c 100644--- a/apps/desktop/resources/plugins/pi.browser/views/browser.html+++ b/apps/desktop/resources/plugins/pi.browser/views/browser.html@@ -163,6 +163,12 @@stop: "Stop",external: "Open externally",placeholder: "Search or enter a URL",+ loadingTitle: "Loading page…",+ loadingBody: "Waiting for the website to respond. You can stop or enter another address.",+ stoppedTitle: "Loading stopped",+ stoppedBody: "Enter an address to try again.",+ failedTitle: "Could not open this page",+ failedBody: "Check the address or connection, then try again.",emptyTitle: "No page open",emptyBody: "Enter an address, or preview an HTML file from the conversation.",},@@ -173,11 +179,18 @@stop: "停止",external: "在外部打开",placeholder: "搜索或输入网址",+ loadingTitle: "正在加载网页…",+ loadingBody: "正在等待网站响应,可以停止加载或输入其他地址。",+ stoppedTitle: "已停止加载",+ stoppedBody: "输入网址可重新打开页面。",+ failedTitle: "无法打开此页面",+ failedBody: "请检查网址或网络连接,然后重试。",emptyTitle: "尚未打开页面",emptyBody: "输入地址,或从对话预览 HTML 文件。",},};+ let navigationRequest = 0;const t = (key) => copy[locale]?.[key] ?? copy.en[key] ?? key;const applyCopy = () => {@@ -205,8 +218,11 @@};const paint = (state) => {- started = Boolean(state?.url);- empty.hidden = started;+ 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";+ emptyTitle.textContent = t(`${phase}Title`);+ emptyBody.textContent = t(`${phase}Body`);back.disabled = !state?.canGoBack;forward.disabled = !state?.canGoForward;reload.disabled = !started;@@ -214,6 +230,7 @@reload.title = state?.isLoading ? t("stop") : t("reload");reload.setAttribute("aria-label", reload.title);if (!inputFocused && state?.url) input.value = state.url;+ reportHole();};const reportHole = () => {@@ -232,10 +249,13 @@event.preventDefault();const value = input.value.trim();if (!value) return;- started = true;- empty.hidden = true;- void bridge.invoke("browser.navigate", { url: value }).then(paint);- reportHole();+ const request = ++navigationRequest;+ paint({ url: value, isLoading: true });+ void bridge.invoke("browser.navigate", { url: value }).then((state) => {+ if (request === navigationRequest && state) paint(state);+ }).catch(() => {+ if (request === navigationRequest) paint({ url: value, loadError: "navigation failed" });+ });});back.addEventListener("click", () => void bridge.invoke("browser.action", { action: "back" }));forward.addEventListener("click", () => void bridge.invoke("browser.action", { action: "forward" }));@@ -258,7 +278,9 @@bridge.on("browser:state", paint);bridge.on("appearance:changed", setBaseTheme);bridge.invoke("app.getAppearance").then(setBaseTheme).catch(() => setBaseTheme(null));+ const initialRequest = navigationRequest;void bridge.invoke("browser.getState").then((state) => {+ if (navigationRequest !== initialRequest) return;paint(state);reportHole();});diff --git a/apps/desktop/src/components/workpanel/PluginViewTab.tsx b/apps/desktop/src/components/workpanel/PluginViewTab.tsxindex 669521a37..17c1e431e 100644--- a/apps/desktop/src/components/workpanel/PluginViewTab.tsx+++ b/apps/desktop/src/components/workpanel/PluginViewTab.tsx@@ -24,6 +24,7 @@ export function PluginViewTab({blocked = false,sessionId,location,+ tabId,}: {pluginId: string;viewId: string;@@ -32,9 +33,13 @@ export function PluginViewTab({blocked?: boolean;sessionId?: string;location?: string;+ tabId?: string;}) {const { t } = useTranslation();const surfaceRef = useRef<HTMLDivElement | null>(null);+ const locationRef = useRef(location);+ locationRef.current = location;+ const viewLocation = pluginId === "pi.browser" && viewId === "browser" ? undefined : location;const [failed, setFailed] = useState(false);// Create the view, and re-create it whenever the plugin's lifecycle changed@@ -43,7 +48,7 @@ export function PluginViewTab({useEffect(() => {let current = true;const open = () => {- void api.pluginViewOpen(pluginId, viewId, { sessionId, location }).then(+ void api.pluginViewOpen(pluginId, viewId, { sessionId, location: locationRef.current, tabId }).then(() => {if (current) setFailed(false);},@@ -61,7 +66,7 @@ export function PluginViewTab({current = false;off();};- }, [pluginId, viewId, sessionId, location]);+ }, [pluginId, viewId, sessionId, viewLocation, tabId]);useEffect(() => {const surface = surfaceRef.current;diff --git a/apps/desktop/src/components/workpanel/WorkPanel.tsx b/apps/desktop/src/components/workpanel/WorkPanel.tsxindex f12ca92bb..ac7144ca7 100644--- a/apps/desktop/src/components/workpanel/WorkPanel.tsx+++ b/apps/desktop/src/components/workpanel/WorkPanel.tsx@@ -105,6 +105,7 @@ function tabLabel(pluginViews: PluginViewMeta[],) {if (tab.kind === "plugin") {+ if (tab.resource === "pi.browser/browser" && tab.label) return tab.label;const view = pluginViews.find((candidate) => candidate.ref === tab.resource);// A view whose plugin was disabled mid-session no longer resolves; fall// back to its id rather than leaving the tab blank until it closes.@@ -953,6 +954,7 @@ export function WorkPanel({icon={activePluginView?.icon}sessionId={activeSessionId ?? undefined}location={activeTab.location}+ tabId={activeTab.id}// Native WebContentsViews composite above renderer content.blocked={exiting || panelBlocked || blockingOverlayActive}/>diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsxindex 248969144..1df208ddf 100644--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx@@ -596,6 +596,7 @@ export function useAppShellRuntime() {});// Agent-driven HTML preview: surface the browser tab when the agent// 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()@@ -797,6 +798,7 @@ export function useAppShellRuntime() {offToast();offInsecureEndpoint();offBrowserPreview();+ offBrowserState();offHostStatus();offNotificationChanged();offSessionsChanged();diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 3cfd32863..b71ef7509 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1210,7 +1210,7 @@ export const api = {pluginViewOpen: (pluginId: string,viewId: string,- extra?: { sessionId?: string; location?: 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 }),diff --git a/apps/desktop/src/lib/work-panel-tabs.ts b/apps/desktop/src/lib/work-panel-tabs.tsindex b9a2f6c14..24af3221d 100644--- a/apps/desktop/src/lib/work-panel-tabs.ts+++ b/apps/desktop/src/lib/work-panel-tabs.ts@@ -121,10 +121,14 @@ export const BROWSER_PLUGIN_TAB = {} as const;export function browserPluginTab(location?: string): WorkPanelTab {- return {- ...pluginWorkPanelTab(BROWSER_PLUGIN_TAB.pluginId, BROWSER_PLUGIN_TAB.viewId),- ...(location ? { location } : {}),- };+ 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) };+}++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/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.tsindex 33807d7a9..bc238da1c 100644--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@ -1,5 +1,6 @@import type {AgentEventEnvelope,+ BrowserState,AgentQueueChangedEvent,AgentStatus,AppNotification,@@ -382,6 +383,7 @@ export type AppState = {setWorkPanelWidth: (width: number) => void;openFileInWorkPanel: (path: string, mimeType?: string) => void;openUrlInWorkPanel: (url: string) => void;+ updateBrowserWorkPanelTab: (state: BrowserState) => void;};export type AppStateData = {diff --git a/apps/desktop/src/stores/slices/work-panel-slice.ts b/apps/desktop/src/stores/slices/work-panel-slice.tsindex 1e2df303a..1197391ad 100644--- a/apps/desktop/src/stores/slices/work-panel-slice.ts+++ b/apps/desktop/src/stores/slices/work-panel-slice.ts@@ -2,6 +2,7 @@ import { api } from "../../lib/api";import {activateWorkPanelTabState,browserPluginTab,+ browserTabLabel,closeWorkPanelTabState,emptyWorkPanelContext,fileWorkPanelTab,@@ -113,6 +114,7 @@ export function createWorkPanelSlice({| "setWorkPanelWidth"| "openFileInWorkPanel"| "openUrlInWorkPanel"+ | "updateBrowserWorkPanelTab"> {let workPanelFileRequestSeq = 0;@@ -376,6 +378,20 @@ export function createWorkPanelSlice({openFileInWorkPanel: (path, mimeType) => {get().openWorkPanelTab(fileWorkPanelTab(path, mimeType));},+ updateBrowserWorkPanelTab: (event) => {+ const sessionId = event.sessionId;+ if (!sessionId || !event.tabId || !event.url) return;+ set((state) => {+ const visible = state.activeSessionId === sessionId && !isSessionSelectionPending(sessionId);+ const context = visible ? currentWorkPanelContext(state) : state.workPanelContexts[sessionId];+ if (!context || !context.tabs.some((tab) => tab.id === event.tabId && tab.resource === "pi.browser/browser")) return {};+ const tabs = context.tabs.map((tab) => tab.id === event.tabId+ ? { ...tab, location: event.url, label: !event.isLoading && !event.loadError && event.title ? event.title : browserTabLabel(event.url) }+ : tab);+ return { ...(visible ? { workPanelTabs: tabs } : {}),+ workPanelContexts: { ...state.workPanelContexts, [sessionId]: { ...context, tabs } } };+ });+ },openUrlInWorkPanel: (url) => {const hasBrowser = get().pluginViews.some((view) => view.pluginId === "pi.browser" && view.viewId === "browser",diff --git a/apps/desktop/test/browser-pane-navigation.test.mjs b/apps/desktop/test/browser-pane-navigation.test.mjsindex 2554ff5ce..9411f1c4e 100644--- a/apps/desktop/test/browser-pane-navigation.test.mjs+++ b/apps/desktop/test/browser-pane-navigation.test.mjs@@ -92,6 +92,8 @@ test("late native navigation events cannot publish after the session is invalidawc.url = "https://fixture.invalid/second";wc.pendingLoads.shift().resolve();await second;+ assert.equal(published.at(-1).url, "https://fixture.invalid/second");+ published.length = 0;wc.emit("did-navigate", {}, "https://fixture.invalid/first");wc.emit("did-fail-load", {}, -3, "aborted", "https://fixture.invalid/first", true);@@ -111,6 +113,8 @@ async function loadedPage() {wc.url = "https://fixture.invalid/page";wc.pendingLoads.shift().resolve();await request;+ assert.equal(published[0].isLoading, true);+ published.length = 0;return { pane, wc, published };}diff --git a/apps/desktop/test/plugin-view-location.test.mjs b/apps/desktop/test/plugin-view-location.test.mjsindex 8cf4e591f..9b9d1f4ec 100644--- a/apps/desktop/test/plugin-view-location.test.mjs+++ b/apps/desktop/test/plugin-view-location.test.mjs@@ -199,6 +199,6 @@ test("pi.browser keeps its own location channel", () => {body,/\.\.\.\(isBrowserView \|\| !location \? \{\} : \{ location \}\),/,);- assert.match(body, /browserHost\.rememberLocation\(sessionId, location\)/);+ assert.match(body, /browserHost\.setChromeSession\(sessionId,.*location\)/);assert.match(body, /void browserHost\.navigate\(/);});diff --git a/apps/desktop/test/work-panel-tabs.test.mjs b/apps/desktop/test/work-panel-tabs.test.mjsindex 1c6bbe56e..98e1015e9 100644--- a/apps/desktop/test/work-panel-tabs.test.mjs+++ b/apps/desktop/test/work-panel-tabs.test.mjs@@ -47,14 +47,15 @@ test("new tabs are unique launcher pages and replace themselves with a tool", ()openWorkPanelTabState({ tabs: [], activeTabId: null }, first),second,);+ const browser = browserPluginTab("https://example.com");const replaced = replaceWorkPanelTabState(state,second.id,- browserPluginTab("https://example.com"),+ browser,);- assert.deepEqual(replaced.tabs.map((tab) => tab.id), [first.id, "plugin:pi.browser/browser"]);- assert.equal(replaced.activeTabId, "plugin:pi.browser/browser");+ assert.deepEqual(replaced.tabs.map((tab) => tab.id), [first.id, browser.id]);+ assert.equal(replaced.activeTabId, browser.id);assert.equal(replaced.tabs.find((tab) => tab.id === first.id)?.kind, "new");});diff --git a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md b/docs/adr/0170-work-panel-browser-as-bundled-plugin.mdindex d0de94c02..9b6450b8f 100644--- a/docs/adr/0170-work-panel-browser-as-bundled-plugin.md+++ b/docs/adr/0170-work-panel-browser-as-bundled-plugin.md@@ -40,8 +40,10 @@ guest.workspace 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). Background- sessions do not steal the visible guest.+ 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.This supersedes ADR 0105 clause 4 (Browser remains a host-built launcher) andthe host-launcher clause of ADR 0019. Guest ownership and navigation policydiff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 8ac585d15..5c52fdf7f 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1742,12 +1742,12 @@ 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-- event: `browser/event/state {url, title, isLoading, canGoBack, canGoForward}`+- 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 `plugin:pi.browser/browser` with `location` in the matching+ renderer opens a Browser resource tab 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 9e52c8678..f9c220e4f 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1046,13 +1046,24 @@ entirely inside the plugin's isolated page:paths, 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 navigation completes. Root lookup or load+ until the destination's 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. Normalnavigation within the same session retains that session's visible content.- A failed switch or one exceeding the existing 15-second load wait remains- hidden until retried; a late network completion does not automatically reveal it.+ The address bar immediately shows loading feedback. A current main-frame commit+ reveals the page without waiting for images or subframes; those continue to+ drive the loading/stop control. A failed switch or one exceeding the 15-second+ main-frame wait shows a retryable error, with the old guest hidden. Superseded+ 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+ ordinary in-page navigation stay in the current tab. Website new-window links+ follow Link open destination: another work-panel tab, or the system browser.- Main-frame same-document navigation (fragment links and History API routes) updatesthe browser address, history controls, and loading state without requiring adiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 87f50bd4f..fd3d37cbd 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3775,14 +3775,33 @@ identify the platform validation still needed.disposing cannot be undone by a delayed completion. Same-session navigationkeeps its current page visible. Invalid, failed, or timed-out loads do notreport the previous document as the destination being ready. A switch that- exceeds the existing 15-second load wait stays hidden until retried; automatic- late reveal is not promised.+ exceeds the 15-second main-frame wait stays hidden with an error until retried.+ Slow images/subframes do not delay revealing a committed current document.+ Start navigation during an unfinished page load: the old ERR_ABORTED event+ must not prevent the new address, title, and loading state from updating.- **Specs linked**: `04-ux/08-component-spec.md` §5.3; ADR 0028, ADR 0170.- **Status**: Automated service-path coverage in `browser-host-session.test.mjs`and `browser-pane-navigation.test.mjs`: production BrowserHost/BrowserPane,controlled native-browser/Host boundaries, and deterministic timers. NativeElectron compositing and the reporter's live sessions are not covered.+#### E2E-BROWSER-responsive-resource-tabs++- **Preconditions**: Browser enabled; isolated profile; local HTML with a+ 17-second image, a delayed main response, and ordinary/new-window links.+- **Steps**: Submit the slow-image URL once; observe loading feedback and page+ display before the image finishes. Open two chat links and a website+ new-window link; switch tabs, navigate within one, then switch away and back.+ Repeat with a delayed main response, Stop, failed navigation, and a retry.+ Set Link open destination to External and repeat the new-window link.+- **Expected**: The current document displays after main-frame commit; slow+ assets do not strand the empty state. New links preserve earlier resource+ tabs. Each tab restores its last address; same-tab navigation updates only its+ originating tab. Failure/stop leave usable address controls. External mode+ does not create a work-panel tab. Session switches and invalid schemes retain+ their security and visibility gates.+- **Status**: Targeted isolated Electron validation; no new repository test suite.+#### E2E-BROWSER-in-page-navigation: Browser chrome follows same-document navigation- **Preconditions**: Browser plugin enabled; a local page has a fragment linkdiff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 5e44abb35..2410096bf 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -643,6 +643,12 @@ pi.browser.console(input?: { limit?: number }): Promise<{ messages: unknown[] }>pi.browser.cdp(input: { method: string; params?: unknown }): Promise<unknown>```+`navigate` returns when the current main-frame navigation commits, including+redirects; it does not wait for slow images or subframes. `browser:state` reports+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`).`setBounds` is content-relative to the calling plugin view and is clamped sothe guest cannot cover chat/composer. `cdp` is deny-by-default; cookie,diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex 87d891a6a..92e5d54bf 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -1376,7 +1376,7 @@ Chrome 和代理 CDP 位于随应用打包的 `pi.browser` 插件中,通过 `p渲染器 IPC 仅保留给 Plan 安全的预览门面和 URL 回退:- `browser/openExternal({url?})` — 白名单内的 http(s)/mailto,或省略时使用当前访客页 URL-- 事件:`browser/event/state {url, title, isLoading, canGoBack, canGoForward}`+- 事件:`browser/event/state {url, title, isLoading, canGoBack, canGoForward, loadError?, sessionId?, tabId?}`(同时以 `browser:state` 推送给插件视图)- 代理预览事件:`browser/event/preview {sessionId, path?, url?}`。Electron Main 会校验工作区 `path` 位于该会话项目内,在该对话的插件视图可见时diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 0c6a61a5b..ed49177e2 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -763,11 +763,19 @@ vendor 进来的 `pi.file-manager` 视图在插件自己的隔离页面内完成自身的读写走自己的宿主进程,由该进程维持它正在浏览的那一个文件夹的牢笼(绝不是整个项目组)、拒绝凭据类路径,并把写入记进自己的审计日志(ADR 0241、ADR 0263)。-- 切换浏览器所属会话时,Main 立即隐藏共享 guest,直到目标会话的当前导航完成。+- 切换浏览器所属会话时,Main 立即隐藏共享 guest,直到目标会话的当前主框架导航提交。已被替代请求的目录查询或加载完成不能再导航、显示或发布旧会话为当前内容。没有预览记录的会话保持空白;关闭面板或销毁 guest 的结果不能被未完成请求撤销。- 同一会话内的正常导航仍保留本会话当前显示的内容。切换导航失败或超过既有 15 秒等待- 上限时保持隐藏,需重试;迟到的网络加载完成不会自动显示。+ 同一会话内的正常导航仍保留本会话当前显示的内容。地址栏立即反馈加载状态,+ 当前主框架导航提交后即可显示页面,不再等待图片或子框架完成加载。+ 导航失败或主框架等待超过 15 秒时显示可重试的错误,并隐藏旧页面;+ 被替代或取消的请求不得覆盖新导航。++- 在工作面板中打开 HTTP(S) 链接会新增浏览器资源标签,不覆盖原网址。+ 每个标签保存当前地址和标题,切换时在共享 guest 中重新加载对应地址。+ 标签不是独立的常驻浏览器进程,不保留各自的 DOM 状态和浏览历史。+ 地址栏和普通页内导航留在当前标签。网页请求打开新窗口时,遵循链接打开位置设置,+ 新增工作面板标签或打开系统浏览器。- 主框架的同文档导航(锚点链接和 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 31fe676c5..35f9ede42 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@@ -2277,12 +2277,23 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的也不能显示它。只有最新导航可以显示 guest,旧 B 查询迟到不能覆盖 C。切回 A 恢复 A,空会话保持空白。迟到完成不能撤销关闭或销毁。同会话正常导航保留当前页面。非法目标、失败或超时不能把上一个文档报告为目标会话已经就绪。切换导航超过既有- 15 秒等待上限后保持隐藏,需重试,不承诺迟到完成自动显示。+ 15 秒主框架等待上限后保持隐藏并显示错误,需重试。慢图片或子框架不阻塞已提交页面的显示;+ 页面尚未加载完成就导航时,旧请求的 ERR_ABORTED 不得阻止新地址、标题和加载状态更新。- **关联规范**:`04-ux/08-component-spec.md` §5.3;ADR 0028、ADR 0170。- **状态**:`browser-host-session.test.mjs` 与 `browser-pane-navigation.test.mjs`覆盖生产 BrowserHost/BrowserPane 服务路径,控制原生浏览器与 Host 边界,采用确定性时钟。尚不覆盖原生 Electron 合成显示或报告者的真实会话。+#### E2E-BROWSER-responsive-resource-tabs++- **前提**:浏览器已启用;隔离配置;本地页面包含延迟 17 秒的图片、延迟主响应及普通/新窗口链接。+- **步骤**:输入慢图片页面地址,检查加载反馈及图片完成前的显示;打开两个聊天链接和网页新窗口链接,+ 切换标签,在其中一个标签内导航后再切走、切回;检查慢主响应、停止、失败、重试及外部打开设置。+- **预期**:主框架导航提交后显示页面;新链接保留原标签,各标签恢复最新地址;+ 普通导航只更新原标签。失败/停止后地址栏仍可用;外部模式不新建工作面板标签。+ 会话切换、非法协议的隔离和可见性规则继续生效。+- **状态**:隔离 Electron 定向验证;不新增仓库测试套件。+#### E2E-BROWSER-in-page-navigation:浏览器工具栏跟随同文档导航- **前置条件**:启用 Browser 插件;本地网页包含锚点链接及 History API 路由控件。diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex f89167432..651d0c131 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -531,6 +531,10 @@ pi.browser.cdp(input: { method: string; params?: unknown }): Promise<unknown>内存中,最多保留 30 天、500 条和 256 MiB;单条文本最多 100 KiB UTF-8 字节,图片最多 50 MiB。图片统一返回 PNG 字节及像素尺寸。没有粘贴过的复制内容不会被记录。+`navigate` 在当前主框架导航提交(含重定向)时返回,不等待慢图片或子框架。+`browser:state` 立即报告加载状态,导航失败时可带 `loadError`。+可选的 `sessionId`、`tabId` 标识宿主管理的工作面板目标;插件不能通过导航参数指定这些身份。+### 服务(需要 `background.service`)```tspi.services.register(service: {diff --git a/packages/shared/src/types/workpanel.ts b/packages/shared/src/types/workpanel.tsindex 61428ed21..ac5eb44f0 100644--- a/packages/shared/src/types/workpanel.ts+++ b/packages/shared/src/types/workpanel.ts@@ -83,6 +83,11 @@ export type WorkspaceDiff = {export type BrowserAction = "back" | "forward" | "reload" | "stop";export type BrowserState = {+ /** Main-owned origin for retained browser resource tabs. */+ sessionId?: string;+ tabId?: string;+ /** Navigation failure; the previous document must not be presented as ready. */+ loadError?: string;url: string;title: string;isLoading: boolean;