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): scope native events to active preview
xjx5e59484c1528
diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.tsindex c1850f99e..e763f1822 100644--- a/apps/desktop/electron/main/browser-host.ts+++ b/apps/desktop/electron/main/browser-host.ts@@ -99,6 +99,7 @@ export class BrowserHost {if (this.chromeSessionId === next) return;this.chromeSessionId = next;this.navigationEpoch += 1;+ this.pane.invalidateNavigation();this.started = false;this.pane.setVisible(false);if (next) {diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.tsindex f32cc3473..930c9125a 100644--- a/apps/desktop/electron/main/browser-view.ts+++ b/apps/desktop/electron/main/browser-view.ts@@ -85,6 +85,10 @@ export class BrowserPane {private watcher: FSWatcher | null = null;private watchedDir: string | null = null;private reloadTimer: NodeJS.Timeout | null = null;+ private navigationEpoch = 0;+ private stateEventsEpoch: number | null = null;+ private stateUrl: string | null = null;+ private nativeNavigationPending = false;constructor(onState: (state: BrowserState) => void) {this.onState = onState;@@ -114,25 +118,45 @@ export class BrowserPane {return wc;}+ /**+ * Stop native WebContents events from publishing state for the document+ * that belonged to the previous session. The next completed managed+ * navigation establishes a new event scope.+ */+ invalidateNavigation(): void {+ this.navigationEpoch += 1;+ this.stateEventsEpoch = null;+ this.stateUrl = null;+ this.nativeNavigationPending = false;+ }+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()).catch(() => {- // Navigation failures surface through did-fail-load → state push.- });+ 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).catch(() => {- // Navigation failures surface through did-fail-load → state push.- });+ void view.webContents+ .loadURL(url)+ .then(() => this.completeManagedNavigation(epoch))+ .catch(() => {+ // A failed replacement must not publish the previous document.+ });if (this.visible) this.attach();return this.getState();}@@ -148,6 +172,7 @@ export class BrowserPane {? pathToFileURL(localPath).toString(): normalizeUrl(raw);if (!target) return null;+ const epoch = this.beginManagedNavigation();if (localPath) this.watchDirForReload(dirname(localPath));else this.clearLiveReload();const view = this.ensureView();@@ -160,7 +185,10 @@ export class BrowserPane {timer = setTimeout(() => resolve(false), Math.max(1, timeoutMs));}),]);- return completed ? this.getState() : null;+ 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.@@ -174,10 +202,13 @@ export class BrowserPane {const wc = this.view?.webContents;if (!wc || wc.isDestroyed()) return;if (action === "back" && wc.navigationHistory.canGoBack()) {+ this.nativeNavigationPending = this.hasCurrentStateEventScope();wc.navigationHistory.goBack();} else if (action === "forward" && wc.navigationHistory.canGoForward()) {+ this.nativeNavigationPending = this.hasCurrentStateEventScope();wc.navigationHistory.goForward();} else if (action === "reload") {+ this.nativeNavigationPending = this.hasCurrentStateEventScope();wc.reload();} else if (action === "stop") {wc.stop();@@ -220,6 +251,7 @@ export class BrowserPane {}dispose(): void {+ this.invalidateNavigation();this.clearLiveReload();this.detach();if (this.view) {@@ -313,13 +345,20 @@ export class BrowserPane {callback(false);});wc.on("will-navigate", (event, url) => {- if (isAllowedHttpUrl(url)) return;+ if (isAllowedHttpUrl(url)) {+ this.nativeNavigationPending = this.hasCurrentStateEventScope();+ return;+ }// Relative links inside a previewed page may point at sibling files;// anything escaping the workspace root stays blocked.- if (/^file:/i.test(url) && this.isAllowedFileUrl(url)) return;+ if (/^file:/i.test(url) && this.isAllowedFileUrl(url)) {+ this.nativeNavigationPending = this.hasCurrentStateEventScope();+ return;+ }event.preventDefault();});wc.on("did-navigate", (_event, url) => {+ if (!this.acceptNativeNavigation(url)) return;if (!/^file:/i.test(url)) return;try {this.watchDirForReload(dirname(fileURLToPath(url)));@@ -328,16 +367,68 @@ export class BrowserPane {}});const push = () => {+ if (!this.hasCurrentStateEventScope()) return;+ const url = wc.getURL();+ if (this.stateUrl !== url) return;const state = this.getState();if (state) this.onState(state);};wc.on("did-start-loading", push);wc.on("did-stop-loading", push);- wc.on("did-navigate", push);- wc.on("did-navigate-in-page", push);+ wc.on("did-navigate", (_event, url) => {+ if (this.acceptNativeNavigation(url)) push();+ });+ wc.on("did-navigate-in-page", (_event, url) => {+ if (this.acceptNativeNavigation(url)) push();+ });wc.on("page-title-updated", push);- wc.on("did-fail-load", push);+ wc.on(+ "did-fail-load",+ (_event, _errorCode, _errorDescription, validatedUrl, isMainFrame) => {+ if (isMainFrame === false) return;+ if (this.acceptNativeNavigation(validatedUrl)) push();+ },+ );this.view = view;return view;}++ private beginManagedNavigation(): number {+ const epoch = ++this.navigationEpoch;+ this.stateEventsEpoch = null;+ this.stateUrl = null;+ this.nativeNavigationPending = false;+ return epoch;+ }++ private enableStateEvents(epoch: number, url: string): void {+ if (epoch !== this.navigationEpoch) return;+ this.stateEventsEpoch = epoch;+ this.stateUrl = url;+ 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;+ }++ private acceptNativeNavigation(url: string): boolean {+ if (!this.hasCurrentStateEventScope()) return false;+ if (url === this.stateUrl) {+ this.nativeNavigationPending = false;+ return true;+ }+ if (!this.nativeNavigationPending) return false;+ this.stateUrl = url;+ this.nativeNavigationPending = false;+ return true;+ }}diff --git a/apps/desktop/test/browser-host-session.test.mjs b/apps/desktop/test/browser-host-session.test.mjsindex 319808019..20c588bab 100644--- a/apps/desktop/test/browser-host-session.test.mjs+++ b/apps/desktop/test/browser-host-session.test.mjs@@ -22,9 +22,11 @@ function harness() {const loads = [];const shown = [];const published = [];+ let invalidations = 0;const pane = {getState: () => state,getWebContents: () => null,+ invalidateNavigation: () => { invalidations += 1; },setBounds: () => {},setVisible(value) {visible = value;@@ -58,7 +60,11 @@ function harness() {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; } };+ return {+ host, roots, loads, shown, published, surface, hole,+ get visible() { return visible; },+ get invalidations() { return invalidations; },+ };}async function openPreview(h, sessionId, path) {@@ -127,6 +133,7 @@ test("a previous session's load completion cannot reveal its guest while the newawait 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);diff --git a/apps/desktop/test/browser-pane-navigation.test.mjs b/apps/desktop/test/browser-pane-navigation.test.mjsindex cc56b95c5..ab286b112 100644--- a/apps/desktop/test/browser-pane-navigation.test.mjs+++ b/apps/desktop/test/browser-pane-navigation.test.mjs@@ -12,7 +12,12 @@ const electron = `data:text/javascript,${encodeURIComponent(`constructor() {this.webContents = Object.assign(new EventEmitter(), {url: "https://fixture.invalid/previous",- loadURL: () => new Promise(() => {}),+ pendingLoads: [],+ loadURL(url) {+ return new Promise((resolve, reject) => {+ this.pendingLoads.push({ url, resolve, reject });+ });+ },getURL() { return this.url; },getTitle: () => "fixture",isLoading: () => false,@@ -72,3 +77,26 @@ test("an invalid target cannot mark the previous document ready", async (t) => {assert.equal(await pane.navigateAndWait("javascript:alert(1)"), null);await settled();});++test("late native navigation events cannot publish after the session is invalidated", async () => {+ const published = [];+ const pane = new BrowserPane((state) => published.push(state));+ const first = pane.navigateAndWait("https://fixture.invalid/first");+ const wc = WebContentsView.instances.at(-1).webContents;+ wc.url = "https://fixture.invalid/first";+ wc.pendingLoads.shift().resolve();+ await first;+ pane.invalidateNavigation();+ const second = pane.navigateAndWait("https://fixture.invalid/second");+ wc.url = "https://fixture.invalid/second";+ wc.pendingLoads.shift().resolve();+ await second;++ wc.emit("did-navigate", {}, "https://fixture.invalid/first");+ wc.emit("did-fail-load", {}, -3, "aborted", "https://fixture.invalid/first", true);+ assert.deepEqual(published, []);++ wc.emit("did-navigate", {}, "https://fixture.invalid/second");+ assert.equal(published.length, 1);+ assert.equal(published[0].url, "https://fixture.invalid/second");+});