Skip to content

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

fix(browser): explain local file preview restrictions

yuxinoa0093b639228
diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.ts
index 48c2af1d6..4b5e109d3 100644
--- a/apps/desktop/electron/main/browser-view.ts
+++ b/apps/desktop/electron/main/browser-view.ts
@@ -118,7 +118,16 @@ export class BrowserPane {
getState(): BrowserState | null {
const wc = this.view?.webContents;
- if (!wc || wc.isDestroyed()) return null;
+ if (!wc || wc.isDestroyed()) {
+ return this.loadError ? {
+ url: this.loadError.url,
+ title: "",
+ isLoading: false,
+ loadError: this.loadError.message,
+ canGoBack: false,
+ canGoForward: false,
+ } : null;
+ }
return {
url: this.loadError?.url ?? this.pendingTarget ?? wc.getURL(),
title: wc.getTitle(),
@@ -168,7 +177,8 @@ export class BrowserPane {
: normalizeUrl(raw);
if (!target) {
this.beginManagedNavigation();
- this.loadError = { url: raw, message: "INVALID_URL" };
+ const localInput = /^file:/i.test(raw.trim()) || isAbsolute(raw.trim());
+ this.loadError = { url: raw, message: localInput ? "LOCAL_FILE_NOT_ALLOWED" : "INVALID_URL" };
const state = this.getState();
if (state) this.onState(state);
return null;
diff --git a/apps/desktop/resources/plugins/pi.browser/views/browser.html b/apps/desktop/resources/plugins/pi.browser/views/browser.html
index 8fbc76edf..1fd611211 100644
--- a/apps/desktop/resources/plugins/pi.browser/views/browser.html
+++ b/apps/desktop/resources/plugins/pi.browser/views/browser.html
@@ -169,6 +169,7 @@
stoppedBody: "Enter an address to try again.",
failedTitle: "Could not open this page",
failedBody: "Check the address or connection, then try again.",
+ localFileBody: "Only existing files inside this project's workspace can be opened.",
emptyTitle: "No page open",
emptyBody: "Enter an address, or preview an HTML file from the conversation.",
},
@@ -185,6 +186,7 @@
stoppedBody: "输入网址可重新打开页面。",
failedTitle: "无法打开此页面",
failedBody: "请检查网址或网络连接,然后重试。",
+ localFileBody: "只能打开此项目工作区内已存在的文件。",
emptyTitle: "尚未打开页面",
emptyBody: "输入地址,或从对话预览 HTML 文件。",
},
@@ -232,7 +234,8 @@
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`);
+ emptyBody.textContent = state?.loadError === "LOCAL_FILE_NOT_ALLOWED"
+ ? t("localFileBody") : t(`${phase}Body`);
back.disabled = !state?.canGoBack;
forward.disabled = !state?.canGoForward;
reload.disabled = !started;
diff --git a/apps/desktop/test/browser-local-file-feedback.test.mjs b/apps/desktop/test/browser-local-file-feedback.test.mjs
new file mode 100644
index 000000000..286e9a60c
--- /dev/null
+++ b/apps/desktop/test/browser-local-file-feedback.test.mjs
@@ -0,0 +1,59 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { runInNewContext } from "node:vm";
+import test from "node:test";
+
+const html = readFileSync(new URL("../resources/plugins/pi.browser/views/browser.html", import.meta.url), "utf8");
+const script = html.match(/<script>([\s\S]*?)<\/script>/)?.[1];
+assert.ok(script, "browser chrome script exists");
+
+function render(locale) {
+ const elements = new Map();
+ const callbacks = new Map();
+ const calls = [];
+ const element = (id) => {
+ if (!elements.has(id)) elements.set(id, {
+ id, disabled: false, hidden: false, value: "", textContent: "", title: "",
+ handlers: new Map(),
+ addEventListener(name, fn) { this.handlers.set(name, fn); },
+ setAttribute(name, value) { this[name] = value; },
+ getBoundingClientRect: () => ({ x: 0, y: 36, width: 400, height: 300 }),
+ });
+ return elements.get(id);
+ };
+ const bridge = {
+ on(name, fn) { callbacks.set(name, fn); },
+ invoke(name, payload) {
+ calls.push({ name, payload });
+ if (name === "app.getAppearance") return Promise.resolve({ locale, base: "light" });
+ if (name === "browser.getState" || name === "browser.navigate") return Promise.resolve(null);
+ return Promise.resolve();
+ },
+ };
+ runInNewContext(script, {
+ document: { getElementById: element, documentElement: { dataset: {}, lang: "" } },
+ window: { pluginBridge: bridge, matchMedia: () => ({ matches: true }), addEventListener() {} },
+ navigator: { language: locale },
+ ResizeObserver: class { observe() {} },
+ });
+ return { element, callbacks, calls };
+}
+
+for (const [locale, expected] of [
+ ["en", "Only existing files inside this project's workspace can be opened."],
+ ["zh-CN", "只能打开此项目工作区内已存在的文件。"],
+]) {
+ test(`address bar explains denied local files in ${locale}`, async () => {
+ const view = render(locale);
+ await new Promise(setImmediate);
+ const url = "file:///tmp/demo.html";
+ view.element("url").value = url;
+ view.element("form").handlers.get("submit")({ preventDefault() {} });
+ assert.equal(view.calls.findLast((call) => call.name === "browser.navigate")?.payload.url, url);
+ view.callbacks.get("browser:state")({ url, loadError: "LOCAL_FILE_NOT_ALLOWED" });
+ assert.equal(view.element("empty").hidden, false);
+ assert.equal(view.element("empty-body").textContent, expected);
+ assert.equal(view.element("url").value, url);
+ assert.equal(view.calls.at(-1).payload.visible, false);
+ });
+}
diff --git a/apps/desktop/test/browser-pane-navigation.test.mjs b/apps/desktop/test/browser-pane-navigation.test.mjs
index e8a57d6d1..41faf9a3b 100644
--- a/apps/desktop/test/browser-pane-navigation.test.mjs
+++ b/apps/desktop/test/browser-pane-navigation.test.mjs
@@ -1,6 +1,10 @@
import assert from "node:assert/strict";
+import { mkdtempSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { register, registerHooks } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import test from "node:test";
+import { pathToFileURL } from "node:url";
// Electron is the external boundary; all navigation and timeout logic below
// runs in the production BrowserPane, without opening a native window.
@@ -23,6 +27,7 @@ const electron = `data:text/javascript,${encodeURIComponent(`
getTitle: () => "fixture",
isLoading: () => false,
isDestroyed: () => false,
+ close: () => {},
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: () => {},
session: { setPermissionRequestHandler: () => {} },
@@ -89,6 +94,45 @@ test("an invalid target cannot mark the previous document ready", async (t) => {
await settled();
});
+test("an outside file URL explains the workspace boundary without loading it", async (t) => {
+ const root = mkdtempSync(join(tmpdir(), "pi-browser-root-"));
+ const outside = mkdtempSync(join(tmpdir(), "pi-browser-outside-"));
+ t.after(() => { pane.dispose(); rmSync(root, { recursive: true }); rmSync(outside, { recursive: true }); });
+ mkdirSync(join(root, "pages"));
+ const insideFile = join(root, "pages", "demo.html");
+ const outsideFile = join(outside, "demo.html");
+ writeFileSync(insideFile, "<h1>Inside</h1>");
+ writeFileSync(outsideFile, "<h1>Outside</h1>");
+ const published = [];
+ const pane = new BrowserPane((state) => published.push(state));
+
+ const allowed = pane.navigateAndWait(pathToFileURL(insideFile).href, root);
+ const wc = WebContentsView.instances.at(-1).webContents;
+ assert.equal(wc.pendingLoads.at(-1).url, pathToFileURL(realpathSync(insideFile)).href);
+ wc.url = pathToFileURL(realpathSync(insideFile)).href;
+ wc.pendingLoads.shift().resolve();
+ await allowed;
+
+ const deniedUrl = pathToFileURL(outsideFile).href;
+ assert.equal(await pane.navigateAndWait(deniedUrl, root), null);
+ assert.equal(wc.pendingLoads.length, 0, "outside file must never reach Electron");
+ assert.equal(published.at(-1).url, deniedUrl);
+ assert.equal(published.at(-1).loadError, "LOCAL_FILE_NOT_ALLOWED");
+ assert.equal(published.at(-1).isLoading, false);
+});
+
+test("a denied local file on a blank tab publishes an error without creating a guest", async () => {
+ const published = [];
+ const pane = new BrowserPane((state) => published.push(state));
+ const count = WebContentsView.instances.length;
+ assert.equal(await pane.navigateAndWait("file:///tmp/demo.html", "/projects/demo"), null);
+ assert.equal(WebContentsView.instances.length, count);
+ assert.deepEqual(published.at(-1), {
+ url: "file:///tmp/demo.html", title: "", isLoading: false,
+ loadError: "LOCAL_FILE_NOT_ALLOWED", canGoBack: false, canGoForward: false,
+ });
+});
+
test("late native navigation events cannot publish after the session is invalidated", async () => {
const published = [];
const pane = new BrowserPane((state) => published.push(state));
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 63ec1467f..6313fc1f3 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1061,7 +1061,10 @@ entirely inside the plugin's isolated page:
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.
+ and cancelled requests cannot publish over the new navigation. A local file
+ address or absolute path that does not resolve to an existing file inside
+ the session workspace is rejected before loading and shows a specific
+ workspace-boundary message in the browser chrome, including on a blank tab.
- Opening an HTTP(S) link in the work panel creates an additional Browser
resource tab instead of replacing the previous URL. Each tab owns a host-retained WebContents, address, title and navigation
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 2cbcbec72..253d9b649 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -3743,7 +3743,9 @@ identify the platform validation still needed.
prompt). 4) Open global search, then rename a session from the left sidebar;
close it and open Settings. Return to chat
and trigger an inline tool permission card. 5) Switch to another panel tab
- and back; close the panel. 6) Use open-external.
+ and back; close the panel. 6) Use open-external. 7) From both an existing page
+ and a blank Browser tab, enter an existing HTML file inside the workspace,
+ then `file:///tmp/demo.html` pointing to an existing file outside it.
- **Expected**: Scheme-less input normalizes to http; nav state (URL bar,
back/forward enablement, load spinner) mirrors the page. Popups open in
the default browser (never in-app) only when the URL parses as http(s) or
@@ -3758,7 +3760,9 @@ identify the platform validation still needed.
its full surface rect and the plugin body does not shift down.
Open-external launches an http(s) page in the default browser and an in-root
file preview via `openPath`. The view uses an isolated persist partition
- (no session bleed from the app shell).
+ (no session bleed from the app shell). The in-root file opens; the outside
+ file never loads, the submitted address remains visible, and the browser
+ explains in the active locale that only existing workspace files can open.
- **Specs linked**: `03-runtime/01-ipc-protocol.md` §13a, ADR 0019, ADR 0168
- **Acceptance**: Quality, Security
- **Milestone**: M5