Skip to content

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

fix(browser): keep preview navigation scoped to the current session

xjxa7a52d43c36c
diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.ts
index 95e9e90f9..c1850f99e 100644
--- a/apps/desktop/electron/main/browser-host.ts
+++ b/apps/desktop/electron/main/browser-host.ts
@@ -82,6 +82,7 @@ export class BrowserHost {
private readonly locations = new Map<string, string>();
private chromeSessionId: string | null = null;
private started = false;
+ private navigationEpoch = 0;
constructor(deps: BrowserHostDeps) {
this.deps = deps;
@@ -97,7 +98,14 @@ export class BrowserHost {
const next = sessionId?.trim() || null;
if (this.chromeSessionId === next) return;
this.chromeSessionId = next;
- if (next) void this.rebindSession(next);
+ this.navigationEpoch += 1;
+ this.started = false;
+ this.pane.setVisible(false);
+ if (next) {
+ void this.rebindSession(next).catch((error) => {
+ console.warn("Browser preview session restore failed", error);
+ });
+ }
}
/**
@@ -145,10 +153,10 @@ export class BrowserHost {
Boolean(this.chromeSessionId) &&
sessionId !== this.chromeSessionId;
if (background) return this.pane.getState();
- const root = await this.deps.getFileRoot(sessionId ?? this.chromeSessionId ?? undefined);
- this.started = true;
- const state = await this.pane.navigateAndWait(target, root);
- this.applyGuest();
+ const state = await this.navigateGuest(
+ target,
+ this.deps.getFileRoot(sessionId ?? this.chromeSessionId ?? undefined),
+ );
if (state) this.deps.onState(state);
return state;
}
@@ -229,14 +237,13 @@ export class BrowserHost {
const background =
Boolean(this.chromeSessionId) && this.chromeSessionId !== sessionId;
if (!background) {
- this.started = true;
- await this.pane.navigateAndWait(path, root);
- this.applyGuest();
+ await this.navigateGuest(path, root);
}
return { ok: true };
}
disposeGuest(): void {
+ this.navigationEpoch += 1;
this.cdp.detach(this.pane.getWebContents() ?? undefined);
this.pane.dispose();
this.started = false;
@@ -252,8 +259,7 @@ export class BrowserHost {
private applyGuest(): void {
const bounds = this.guestBounds();
- const url = this.pane.getState()?.url;
- if (!bounds || (!this.started && !url)) {
+ if (!bounds || !this.started) {
this.pane.setVisible(false);
return;
}
@@ -264,10 +270,23 @@ export class BrowserHost {
private async rebindSession(sessionId: string): Promise<void> {
const location = this.locations.get(sessionId);
if (!location) return;
- const root = await this.deps.getFileRoot(sessionId);
- this.started = true;
- await this.pane.navigateAndWait(location, root);
+ 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;
+ // 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;
this.applyGuest();
+ return state;
}
private requireWebContents() {
diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.ts
index 22dca5b57..f32cc3473 100644
--- a/apps/desktop/electron/main/browser-view.ts
+++ b/apps/desktop/electron/main/browser-view.ts
@@ -147,22 +147,27 @@ export class BrowserPane {
const target = localPath
? pathToFileURL(localPath).toString()
: normalizeUrl(raw);
- if (!target) return this.getState();
+ if (!target) return null;
if (localPath) this.watchDirForReload(dirname(localPath));
else this.clearLiveReload();
const view = this.ensureView();
if (this.visible) this.attach();
+ let timer: ReturnType<typeof setTimeout> | undefined;
try {
- await Promise.race([
- view.webContents.loadURL(target),
- new Promise<void>((resolve) => {
- setTimeout(resolve, Math.max(1, timeoutMs));
+ const completed = await Promise.race([
+ view.webContents.loadURL(target).then(() => true),
+ new Promise<false>((resolve) => {
+ timer = setTimeout(() => resolve(false), Math.max(1, timeoutMs));
}),
]);
+ return completed ? this.getState() : null;
} catch {
- // Load failures surface through did-fail-load → state push.
+ // 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 this.getState();
}
action(action: "back" | "forward" | "reload" | "stop"): void {
diff --git a/apps/desktop/test/browser-host-session.test.mjs b/apps/desktop/test/browser-host-session.test.mjs
new file mode 100644
index 000000000..319808019
--- /dev/null
+++ b/apps/desktop/test/browser-host-session.test.mjs
@@ -0,0 +1,212 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { BrowserHost } = await import("../electron/main/browser-host.ts");
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+}
+
+// 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 = [];
+ const pane = {
+ getState: () => state,
+ getWebContents: () => null,
+ 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 host = new BrowserHost({
+ pane,
+ isPluginLoaded: () => true,
+ getFileRoot(sessionId) {
+ const root = deferred();
+ roots.push({ sessionId, ...root });
+ return root.promise;
+ },
+ onState: (value) => published.push(value),
+ });
+ const surface = (show = true) => host.setChromeSurface({
+ pluginId: "pi.browser", viewId: "browser", visible: show,
+ 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; } };
+}
+
+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;
+}
+
+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("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("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");
+ 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("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("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("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("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("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);
+});
diff --git a/apps/desktop/test/browser-pane-navigation.test.mjs b/apps/desktop/test/browser-pane-navigation.test.mjs
new file mode 100644
index 000000000..cc56b95c5
--- /dev/null
+++ b/apps/desktop/test/browser-pane-navigation.test.mjs
@@ -0,0 +1,74 @@
+import assert from "node:assert/strict";
+import { register, registerHooks } from "node:module";
+import test from "node:test";
+
+// Electron is the external boundary; all navigation and timeout logic below
+// runs in the production BrowserPane, without opening a native window.
+const electron = `data:text/javascript,${encodeURIComponent(`
+ import { EventEmitter } from "node:events";
+ export const shell = {};
+ export class WebContentsView {
+ static instances = [];
+ constructor() {
+ this.webContents = Object.assign(new EventEmitter(), {
+ url: "https://fixture.invalid/previous",
+ loadURL: () => new Promise(() => {}),
+ getURL() { return this.url; },
+ getTitle: () => "fixture",
+ isLoading: () => false,
+ isDestroyed: () => false,
+ navigationHistory: { canGoBack: () => false, canGoForward: () => false },
+ setWindowOpenHandler: () => {},
+ session: { setPermissionRequestHandler: () => {} },
+ });
+ WebContentsView.instances.push(this);
+ }
+ }
+`)}`;
+registerHooks({ resolve(specifier, context, next) {
+ return specifier === "electron" ? { url: electron, shortCircuit: true } : next(specifier, context);
+} });
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { BrowserPane } = await import("../electron/main/browser-view.ts");
+const { WebContentsView } = await import("electron");
+const settled = () => new Promise(setImmediate);
+
+function harness(t) {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const pane = new BrowserPane(() => {});
+ // The production class creates its native guest lazily at the first request.
+ const request = pane.navigateAndWait("https://fixture.invalid/new", null, 100);
+ const wc = WebContentsView.instances.at(-1).webContents;
+ return { pane, wc, request };
+}
+
+test("timing out a new preview does not return the previous document as ready", async (t) => {
+ const { request } = harness(t);
+ t.mock.timers.tick(100);
+ assert.equal(await request, null);
+});
+
+test("a rejected navigation does not return the previous document as ready", async (t) => {
+ const { pane, wc, request } = harness(t);
+ t.mock.timers.tick(100);
+ await request;
+ wc.loadURL = async () => { throw new Error("fixture load failure"); };
+ assert.equal(await pane.navigateAndWait("https://fixture.invalid/failed"), null);
+});
+
+test("a completed navigation returns its actual page, including redirects", async (t) => {
+ const { pane, wc, request } = harness(t);
+ t.mock.timers.tick(100);
+ await request;
+ wc.loadURL = async () => { wc.url = "https://fixture.invalid/redirected"; };
+ const state = await pane.navigateAndWait("https://fixture.invalid/new");
+ assert.equal(state.url, "https://fixture.invalid/redirected");
+});
+
+test("an invalid target cannot mark the previous document ready", async (t) => {
+ const { pane, request } = harness(t);
+ t.mock.timers.tick(100);
+ await request;
+ assert.equal(await pane.navigateAndWait("javascript:alert(1)"), null);
+ await settled();
+});
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 7b928813f..6824d7457 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1031,6 +1031,15 @@ entirely inside the plugin's isolated page:
folder the view is browsing — never the whole group — refuses credential
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
+ completion from a superseded request cannot navigate, reveal, or publish the
+ old session as current. A session without a remembered preview stays empty;
+ closing the panel or disposing the guest wins over pending work. Normal
+ navigation within the same session retains that session's visible content.
+ 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.
+
### 5.3 States
| State | Behavior |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index f9de15ea1..3829eb82b 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -3446,6 +3446,30 @@ identify the platform validation still needed.
- **Milestone**: M5
- **Status**: Draft (manual)
+#### E2E-BROWSER-session-preview-race: Session switching does not expose a stale preview
+
+- **Preconditions**: Two sessions have distinct HTML previews; their Browser
+ panel contexts are retained independently. Directory lookups and document
+ loads can be delayed independently by the fixture.
+- **Steps**: Preview A; produce B's preview in the background; collapse A's
+ panel and open B; delay B's directory lookup and load, then return to A.
+ Switch rapidly B → C and finish the older B lookup last. Repeat with an
+ already-started old load, an empty session, a failed load, and disposal.
+- **Expected**: Background B does not navigate A. On switching, no A document
+ appears in B's panel, even after bounds/visibility updates. Only the latest
+ navigation can reveal the guest; the late B lookup cannot replace C.
+ Returning to A restores A, while an empty session remains empty. Closing or
+ disposing cannot be undone by a delayed completion. Same-session navigation
+ keeps its current page visible. Invalid, failed, or timed-out loads do not
+ report 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.
+- **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. Native
+ Electron compositing and the reporter's live sessions are not covered.
+
#### E2E-060: Files tab browsing stays inside the workspace
- **Preconditions**: Workspace with file artifacts for nested source, large
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 1c2120fba..3b296af1a 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -762,6 +762,12 @@ vendor 进来的 `pi.file-manager` 视图在插件自己的隔离页面内完成
自身的读写走自己的宿主进程,由该进程维持它正在浏览的那一个文件夹的牢笼(绝不是整个项目组)、
拒绝凭据类路径,并把写入记进自己的审计日志(ADR 0241、ADR 0263)。
+- 切换浏览器所属会话时,Main 立即隐藏共享 guest,直到目标会话的当前导航完成。
+ 已被替代请求的目录查询或加载完成不能再导航、显示或发布旧会话为当前内容。
+ 没有预览记录的会话保持空白;关闭面板或销毁 guest 的结果不能被未完成请求撤销。
+ 同一会话内的正常导航仍保留本会话当前显示的内容。切换导航失败或超过既有 15 秒等待
+ 上限时保持隐藏,需重试;迟到的网络加载完成不会自动显示。
+
### 5.3 状态
| 状态 | 行为 |
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.md
index 189b60af5..5a642745f 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
@@ -2147,6 +2147,23 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的
- **里程碑**:M5
- **状态**:草案(手动)
+#### E2E-BROWSER-session-preview-race:切换会话不显示过期预览
+
+- **前置条件**:两个会话具有不同 HTML 预览,浏览器面板上下文分别保留。夹具可以独立
+ 延迟目录查询和文档加载。
+- **步骤**:预览 A,在后台生成 B 的预览;折叠 A 的面板后打开 B,延迟 B 的目录查询和
+ 加载,然后切回 A。快速切换 B → C,最后才完成旧 B 的目录查询。再分别验证已经开始的
+ 旧加载、空会话、加载失败和 guest 销毁。
+- **预期**:后台 B 不导航 A。切换后,B 的面板不显示 A 的文档,后续尺寸与可见性更新
+ 也不能显示它。只有最新导航可以显示 guest,旧 B 查询迟到不能覆盖 C。切回 A 恢复 A,
+ 空会话保持空白。迟到完成不能撤销关闭或销毁。同会话正常导航保留当前页面。
+ 非法目标、失败或超时不能把上一个文档报告为目标会话已经就绪。切换导航超过既有
+ 15 秒等待上限后保持隐藏,需重试,不承诺迟到完成自动显示。
+- **关联规范**:`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-060:文件选项卡浏览停留在工作区中
- **先决条件**:具有嵌套源文件工件的工作区,大型