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): open local files outside workspace
vastsa6e5c3c98abc0
diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.tsindex cc98c82d8..64e060c86 100644--- a/apps/desktop/electron/main/browser-view.ts+++ b/apps/desktop/electron/main/browser-view.ts@@ -14,9 +14,9 @@ import { isAllowedHttpUrl, parseAllowedExternalUrl } from "./safe-open-external"* the active panel surface or a blocking overlay opens (the view always* composites above renderer content).*- * Besides http(s) URLs, the pane renders HTML files inside the workspace- * (agent-generated pages) with live reload: the loaded file's directory is- * watched so edits to the page or its sibling assets refresh the preview.+ * Besides http(s) URLs, the pane renders existing local HTML files with live+ * reload: the loaded file's directory is watched so edits to the page or its+ * sibling assets refresh the preview.*/const PARTITION = "persist:work-browser";@@ -54,12 +54,29 @@ function isWithinRoot(path: string, root: string): boolean {}}+function resolveExistingFile(candidate: string): string | null {+ try {+ const real = realpathSync(resolve(candidate));+ return statSync(real).isFile() ? real : null;+ } catch {+ return null;+ }+}++function fileUrlToLocalPath(raw: string): string | null {+ try {+ const url = new URL(raw);+ if (url.protocol !== "file:" || (url.hostname && url.hostname !== "localhost")) return null;+ return fileURLToPath(url);+ } catch {+ return null;+ }+}+/**- * Resolve user input to a previewable file inside the workspace: a file://- * URL, an absolute path, or a workspace-relative path (./demo/index.html,- * index.html). Returns null unless the target exists as a file within the- * root. A missing relative file (for example, "localhost:3000/a.html")- * returns null so the caller can try HTTP URL normalization.+ * Resolve a BrowserPreview input to a previewable file inside the workspace.+ * It accepts a file:// URL, absolute path, or workspace-relative path. This+ * stays workspace-scoped for the Agent BrowserPreview tool and sidecar.*/export function resolveLocalFile(raw: string, root: string | null): string | null {const trimmed = raw.trim();@@ -77,17 +94,25 @@ export function resolveLocalFile(raw: string, root: string | null): string | nulcandidate = resolve(root, trimmed);}if (!candidate) return null;- const resolved = resolve(candidate);- if (!isWithinRoot(resolved, root)) return null;- try {- const real = realpathSync(resolved);- const realRoot = realpathSync(resolve(root));- if (real !== realRoot && !real.startsWith(realRoot + sep)) return null;- if (!statSync(real).isFile()) return null;- return real;- } catch {- return null;+ if (!isWithinRoot(candidate, root)) return null;+ const real = resolveExistingFile(candidate);+ return real && isWithinRoot(real, root) ? real : null;+}++/**+ * Resolve a file requested by the embedded browser. Explicit file URLs and+ * absolute paths may target any existing local file; relative inputs remain+ * rooted in the current workspace. BrowserPreview uses resolveLocalFile.+ */+function resolveBrowserLocalFile(raw: string, root: string | null): string | null {+ const trimmed = raw.trim();+ if (!trimmed) return null;+ if (/^file:/i.test(trimmed)) {+ const candidate = fileUrlToLocalPath(trimmed);+ return candidate ? resolveExistingFile(candidate) : null;}+ if (isAbsolute(trimmed)) return resolveExistingFile(trimmed);+ return resolveLocalFile(trimmed, root);}export class BrowserPane {@@ -202,8 +227,9 @@ export class BrowserPane {timeoutMs = 15_000,): Promise<BrowserState | null> {if (fileRoot) this.fileRoot = fileRoot;- const localPath = resolveLocalFile(raw, this.fileRoot);- const localInput = /^file:/i.test(raw.trim()) || isAbsolute(raw.trim());+ const localPath = resolveBrowserLocalFile(raw, this.fileRoot);+ const trimmed = raw.trim();+ const localInput = /^file:/i.test(trimmed) || isAbsolute(trimmed) || /^\.{1,2}\//.test(trimmed);const target = localPath? pathToFileURL(localPath).toString(): localInput ? null : normalizeUrl(raw);@@ -415,12 +441,12 @@ export class BrowserPane {}private isAllowedFileUrl(url: string): boolean {- if (!this.fileRoot) return false;- try {- return isWithinRoot(resolve(fileURLToPath(url)), this.fileRoot);- } catch {- return false;- }+ const localPath = resolveBrowserLocalFile(url, this.fileRoot);+ if (!localPath) return false;+ if (this.fileRoot && isWithinRoot(localPath, this.fileRoot)) return true;+ // Preserve workspace-file links from web pages, but only let a local+ // document navigate to files outside that workspace.+ return this.view?.webContents.getURL().startsWith("file:") === true;}private ensureView(): WebContentsView {@@ -458,8 +484,8 @@ export class BrowserPane {this.nativeNavigationPending = this.hasCurrentStateEventScope();return;}- // Relative links inside a previewed page may point at sibling files;- // anything escaping the workspace root stays blocked.+ // Keep web pages inside the existing workspace-file allowance. A local+ // file page may follow links to any other existing local file.if (/^file:/i.test(url) && this.isAllowedFileUrl(url)) {this.nativeNavigationPending = this.hasCurrentStateEventScope();return;diff --git a/apps/desktop/resources/plugins/pi.browser/views/browser.html b/apps/desktop/resources/plugins/pi.browser/views/browser.htmlindex 1fd611211..fcb7f10d4 100644--- a/apps/desktop/resources/plugins/pi.browser/views/browser.html+++ b/apps/desktop/resources/plugins/pi.browser/views/browser.html@@ -169,7 +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.",+ localFileBody: "Only existing local files can be opened.",emptyTitle: "No page open",emptyBody: "Enter an address, or preview an HTML file from the conversation.",},@@ -186,7 +186,7 @@stoppedBody: "输入网址可重新打开页面。",failedTitle: "无法打开此页面",failedBody: "请检查网址或网络连接,然后重试。",- localFileBody: "只能打开此项目工作区内已存在的文件。",+ localFileBody: "只能打开已存在的本地文件。",emptyTitle: "尚未打开页面",emptyBody: "输入地址,或从对话预览 HTML 文件。",},diff --git a/apps/desktop/test/browser-local-file-feedback.test.mjs b/apps/desktop/test/browser-local-file-feedback.test.mjsindex f77779274..8adb27a59 100644--- a/apps/desktop/test/browser-local-file-feedback.test.mjs+++ b/apps/desktop/test/browser-local-file-feedback.test.mjs@@ -40,8 +40,8 @@ function render(locale) {}for (const [locale, expected] of [- ["en", "Only existing files inside this project's workspace can be opened."],- ["zh-CN", "只能打开此项目工作区内已存在的文件。"],+ ["en", "Only existing local files can be opened."],+ ["zh-CN", "只能打开已存在的本地文件。"],]) {for (const url of ["file:///tmp/demo.html", "/tmp/demo.html"]) {test(`address bar explains ${url} in ${locale}`, async () => {diff --git a/apps/desktop/test/browser-pane-navigation.test.mjs b/apps/desktop/test/browser-pane-navigation.test.mjsindex 766e75c9a..b19db76f0 100644--- a/apps/desktop/test/browser-pane-navigation.test.mjs+++ b/apps/desktop/test/browser-pane-navigation.test.mjs@@ -10,7 +10,11 @@ import { pathToFileURL } from "node:url";// 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 const shell = {+ openedPaths: [],+ openPath(path) { this.openedPaths.push(path); return Promise.resolve(""); },+ openExternal() { return Promise.resolve(); },+ };export class View {children = [];addChildView(view) { this.children.push(view); }@@ -47,8 +51,8 @@ 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, normalizeUrl } = await import("../electron/main/browser-view.ts");-const { WebContentsView } = await import("electron");+const { BrowserPane, normalizeUrl, resolveLocalFile } = await import("../electron/main/browser-view.ts");+const { WebContentsView, shell } = await import("electron");const settled = () => new Promise(setImmediate);function harness(t) {@@ -128,7 +132,7 @@ test("an invalid target cannot mark the previous document ready", async (t) => {await settled();});-test("outside file URLs and absolute paths explain the workspace boundary without loading", async (t) => {+test("address-bar file inputs and page links can open existing files outside the workspace", 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 }); });@@ -152,35 +156,76 @@ test("outside file URLs and absolute paths explain the workspace boundary withouwc.pendingLoads.shift().resolve();await allowedAbsolute;- 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);+ const outsideUrl = pathToFileURL(outsideFile).href;+ const allowedOutsideUrl = pane.navigateAndWait(outsideUrl, root);+ assert.equal(wc.pendingLoads.at(-1).url, pathToFileURL(realpathSync(outsideFile)).href);+ wc.url = pathToFileURL(realpathSync(outsideFile)).href;+ wc.pendingLoads.shift().resolve();+ assert.equal((await allowedOutsideUrl).url, pathToFileURL(realpathSync(outsideFile)).href);++ const allowedOutsideAbsolute = pane.navigateAndWait(outsideFile, root);+ assert.equal(wc.pendingLoads.at(-1).url, pathToFileURL(realpathSync(outsideFile)).href);+ wc.pendingLoads.shift().resolve();+ assert.equal((await allowedOutsideAbsolute).url, pathToFileURL(realpathSync(outsideFile)).href);+ pane.openExternal();+ assert.equal(shell.openedPaths.at(-1), realpathSync(outsideFile));++ assert.equal(resolveLocalFile(outsideFile, root), null,+ "workspace-scoped BrowserPreview resolution must remain restricted");++ const willNavigate = wc.listeners("will-navigate")[0];+ assert.ok(willNavigate, "top-level navigation guard is installed");+ let outsidePrevented = false;+ willNavigate({ preventDefault() { outsidePrevented = true; } }, outsideUrl);+ assert.equal(outsidePrevented, false, "an existing outside file link is allowed");++ let missingPrevented = false;+ willNavigate({ preventDefault() { missingPrevented = true; } },+ pathToFileURL(join(outside, "missing.html")).href);+ assert.equal(missingPrevented, true, "a missing outside file remains blocked");- assert.equal(await pane.navigateAndWait(outsideFile, root, 10), null);- assert.equal(wc.pendingLoads.at(-1)?.url, undefined, "outside absolute path must never reach Electron");- assert.equal(published.at(-1).url, outsideFile);- assert.equal(published.at(-1).loadError, "LOCAL_FILE_NOT_ALLOWED");+ let directoryPrevented = false;+ willNavigate({ preventDefault() { directoryPrevented = true; } }, pathToFileURL(outside).href);+ assert.equal(directoryPrevented, true, "a directory is not a previewable file");++ wc.url = "https://fixture.invalid/page";+ let webPagePrevented = false;+ willNavigate({ preventDefault() { webPagePrevented = true; } }, outsideUrl);+ assert.equal(webPagePrevented, true, "a web page cannot navigate outside the workspace");++ let remoteAuthorityPrevented = false;+ willNavigate({ preventDefault() { remoteAuthorityPrevented = true; } },+ `file://fileserver${outsideFile}`);+ assert.equal(remoteAuthorityPrevented, true, "remote file authorities are not local files");++ assert.equal(await pane.navigateAndWait(`../${outside.split("/").at(-1)}/demo.html`, root), null,+ "relative address-bar paths remain inside the workspace");});-test("a denied local file on a blank tab publishes an error without creating a guest", async () => {+test("a missing local file on a blank tab publishes an error without creating a guest", async () => {+ const tempRoot = mkdtempSync(join(tmpdir(), "pi-browser-missing-"));+ const missingFile = join(tempRoot, "missing.html");+ const missingUrl = pathToFileURL(missingFile).href;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,- });- assert.equal(await pane.navigateAndWait("/tmp/demo.html", "/projects/demo"), null);- assert.equal(WebContentsView.instances.length, count);- assert.deepEqual(published.at(-1), {- url: "/tmp/demo.html", title: "", isLoading: false,- loadError: "LOCAL_FILE_NOT_ALLOWED", canGoBack: false, canGoForward: false,- });+ try {+ const count = WebContentsView.instances.length;+ assert.equal(await pane.navigateAndWait(missingUrl, "/projects/demo"), null);+ assert.equal(WebContentsView.instances.length, count);+ assert.deepEqual(published.at(-1), {+ url: missingUrl, title: "", isLoading: false,+ loadError: "LOCAL_FILE_NOT_ALLOWED", canGoBack: false, canGoForward: false,+ });+ assert.equal(await pane.navigateAndWait(missingFile, "/projects/demo"), null);+ assert.equal(WebContentsView.instances.length, count);+ assert.deepEqual(published.at(-1), {+ url: missingFile, title: "", isLoading: false,+ loadError: "LOCAL_FILE_NOT_ALLOWED", canGoBack: false, canGoForward: false,+ });+ } finally {+ pane.dispose();+ rmSync(tempRoot, { recursive: true, force: true });+ }});test("late native navigation events cannot publish after the session is invalidated", async () => {diff --git a/docs/adr/0328-browser-arbitrary-local-files.md b/docs/adr/0328-browser-arbitrary-local-files.mdnew file mode 100644index 000000000..b0c35d8db--- /dev/null+++ b/docs/adr/0328-browser-arbitrary-local-files.md@@ -0,0 +1,59 @@+# ADR 0328: Open arbitrary local files in the embedded Browser++- Status: Accepted+- Date: 2026-10-13+- Deciders: PI-Desktop core+- Related: issue #1627 · [ADR 0170](0170-work-panel-browser-as-bundled-plugin.md) ·+ [ADR 0028](0028-session-scoped-work-panel-contexts.md)++## Context++The embedded Browser accepted only files below the active session workspace.+That restriction also blocked a user from opening an existing local HTML file+by absolute path or `file:` URL, and prevented local pages from following links+to files elsewhere on the machine. `BrowserPreview` and the runtime sidecar+also use workspace-rooted path validation, but those agent-facing file tools+must keep their current scope.++## Decision++1. The embedded Browser accepts an absolute path or `file:` URL for any existing+ regular local file. Relative address-bar paths remain rooted in the current+ session workspace.+2. A local-file page may navigate to other existing local files. HTTP(S) pages+ keep the prior in-workspace file-link allowance and cannot navigate to files+ outside that workspace.+3. File URLs with a remote authority, missing paths, directories, and other+ unsupported schemes remain blocked. Popups still open externally only for+ the existing `http:`, `https:`, and `mailto:` allowlist.+4. The public `pi.browser.navigate` API receives the same local-file behavior+ under the high-risk `browser.cdp` permission. `BrowserPreview` and the+ sidecar continue to use `resolveLocalFile()` and remain workspace-scoped.++## Consequences++- Users can preview local HTML and related files outside the project from the+ Browser address bar.+- A plugin granted `browser.cdp` can navigate the visible Browser to an+ explicitly supplied local path and inspect its page through the existing+ browser API. The Browser remains a sandboxed `WebContentsView` with Node+ integration disabled, context isolation enabled, and permission requests+ denied; access to local content is still a high-risk capability.+- A remote web page cannot use a top-level file link to escape the session+ workspace. Workspace-relative paths, BrowserPreview validation, and the+ runtime sidecar file boundary are unchanged.+- No IPC schema, persisted state, or user setting changes.++## Alternatives considered++### Allow address-bar entry but keep local-page links workspace-scoped++Rejected because a local HTML page can reference or link to sibling files+outside the project, which is the same preview workflow the Browser already+supports within a workspace.++### Add a separate opt-in toggle++Rejected because issue #1627 explicitly asks the Browser to stop imposing the+workspace boundary. Address-bar navigation remains an explicit user action;+programmatic navigation remains guarded by the existing high-risk permission.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 9f7da18d9..63d92b95e 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -373,6 +373,7 @@ Each ADR includes:| 0325 | [Smooth Windows main-window corner compositing](0325-windows-window-corner-compositing.md) | Proposed (implementation candidate; Windows E2E pending) || 0326 | [Verified SSH Host installation and daily startup](0326-verified-ssh-host-installation.md) | Accepted for experimental implementation (amends ADR 0292; Linux SSH qualification and publication pending) || 0327 | [Automatic remote Host version realignment](0327-remote-host-version-realignment.md) | Accepted for experimental implementation (amends ADR 0326 item 6; Linux SSH qualification pending) |+| 0328 | [Open arbitrary local files in the embedded Browser](0328-browser-arbitrary-local-files.md) | Accepted (D657; amends ADR 0170; issue #1627) || plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) || local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex d7c52d90a..66e46e854 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1080,17 +1080,19 @@ entirely inside the plugin's isolated page:reveals the page without waiting for images or subframes; those continue todrive the loading/stop control. A failed switch or one exceeding the 15-secondmain-frame wait shows a retryable error, with the old guest hidden. Superseded- 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.- Existing files inside the workspace remain previewable by absolute path.+ and cancelled requests cannot publish over the new navigation. The address+ bar accepts `file:` URLs and absolute paths to existing local files anywhere+ on the machine; a local file page may also navigate to other existing local+ files. Missing files, directories, remote file authorities, and unsupported+ schemes are rejected before loading. Relative paths remain rooted in the+ session workspace. BrowserPreview remains workspace-scoped.- Browser address input accepts HTTP(S) URLs and scheme-less web hosts. A`localhost` or dotted hostname followed by a numeric port (for example,`localhost:3000/index.html` or `example.com:8080`) is treated as an HTTPaddress rather than a custom URL scheme. Unsupported schemes remain blocked;- workspace file previews continue to use the in-root file path gate.+ explicit local-file navigation is not limited to the workspace. BrowserPreview+ continues to use the in-root file path gate.- Opening an HTTP(S) link in the work panel creates an additional Browserresource tab instead of replacing the previous URL. Each tab owns a host-retained WebContents, address, title and navigationdiff --git a/docs/spec/05-security/01-security.md b/docs/spec/05-security/01-security.mdindex bdfab3c3a..9b404585c 100644--- a/docs/spec/05-security/01-security.md+++ b/docs/spec/05-security/01-security.md@@ -24,7 +24,9 @@ Required (all **implemented**):forwards only parsed `http:` / `https:` / `mailto:` URLs to the OS browser(`parseAllowedExternalUrl`, D330 / ADR 0168). `file:`, `javascript:`,`data:`, and custom URI schemes never reach `shell.openExternal`.- `will-navigate` blocks all non-dev-server navigations+ `will-navigate` is enforced by each owning surface; the embedded Browser+ permits HTTP(S), workspace file links, and local-file navigation initiated+ from an already loaded local file, while other schemes remain blocked.- Every web contents Electron creates starts with a deny-all window-openhandler and a blocked `<webview>` attach (`app.on("web-contents-created")`);the owning surface replaces the handler with its own policy, so a window@@ -38,6 +40,15 @@ Required (all **implemented**):reply can therefore reveal the user's IP to the host it names. Links nevernavigate in-app and always route through the external-open path.+### Embedded Browser local files++The embedded Browser can open any existing local file explicitly entered as an+absolute path or `file:` URL. A loaded local file can navigate to other existing+local files. A web page can still navigate to workspace files as before, but+cannot use a file link to escape the workspace. This local-file browsing is+covered by the high-risk `browser.cdp` capability; `BrowserPreview` and the+sidecar's workspace file resolver remain restricted to the session workspace.+### Content Security Policy- Dev: `script-src 'self' 'unsafe-inline' 'unsafe-eval'` (required by Vitediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 22a6af49f..5937efc35 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4512,7 +4512,7 @@ window; opening a normal panel afterward must still work.#### E2E-059: Embedded browser preview isolation and overlays-- **Preconditions**: A local dev server is running; a URL or BrowserPreview artifact exists.+- **Preconditions**: A local dev server is running; a URL or BrowserPreview artifact exists; HTML fixtures exist both inside and outside the workspace.- **Steps**: 1) Activate the artifact, enter `localhost:<port>` and`localhost:<port>/index.html` without a scheme, and submit each. Enter adotted host with a port (for example, `example.com:8080`), then verify an@@ -4524,30 +4524,38 @@ window; opening a normal panel afterward must still work.and trigger an inline tool permission card. 5) Switch to another panel taband back; close the panel. 6) Use open-external. 7) From both an existing pageand a blank Browser tab, enter an existing HTML file inside the workspace by- `file:` URL and absolute path. Then enter both `file:///tmp/demo.html` and- `/tmp/demo.html`, pointing to an existing file outside the workspace.+ platform-appropriate `file:` URL and absolute path. Then enter an existing+ file outside the workspace by its platform-appropriate URL and absolute path+ (for example, `file:///tmp/demo.html` and `/tmp/demo.html` on Unix, or+ `file:///D:/demo.html` and `D:\demo.html` on Windows). From the loaded+ local HTML, follow a link to another existing file outside the workspace.+ From an HTTP page, try the same outside file link and enter a missing local+ file path.- **Expected**: Scheme-less input normalizes to http; nav state (URL bar,back/forward enablement, load spinner) mirrors the page. Popups open inthe default browser (never in-app) only when the URL parses as http(s) or- mailto; `file:`, `javascript:`, and custom schemes are denied. Permission- requests are denied; non-http(s) navigation is blocked except in-root- `file:` siblings. The preview hides for the whole lifetime of the rename+ mailto; popups using `file:`, `javascript:`, and custom schemes are denied.+ Permission requests are denied; top-level navigation allows HTTP(S),+ in-workspace file links, and existing local file links from a local file+ page. HTTP pages cannot navigate to files outside the workspace. Missing+ files, directories, remote file authorities, and other schemes are blocked.+ The preview hides for the whole lifetime of the renamedialog and every other blocking overlay, and whileunmounted, reappearing with correct bounds afterwards. An inline permissioncard does not hide or remount the preview; resize/drag keeps the native viewvisible and aligned with the placeholder rect without a black flash. Openingthe work-panel context dropdown moves beside the native view; the view keepsits 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). Both in-root forms open; neither- outside form reaches the guest load, 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+ Open-external launches an http(s) page in the default browser and any loaded+ local file via `openPath`. The view uses an isolated persist partition+ (no session bleed from the app shell). Both inside and outside forms load;+ the HTTP page's outside link and missing path do not reach the guest load.+ The submitted address remains visible on failure, with localized copy that+ only existing local files can open.+- **Specs linked**: `03-runtime/01-ipc-protocol.md` §13a, `04-ux/08-component-spec.md`, `05-security/01-security.md`, ADR 0019, ADR 0168, ADR 0328- **Acceptance**: Quality, Security- **Milestone**: M5-- **Status**: Draft (manual)+- **Status**: Partial automation: `scripts/e2e-browser-local-file-access.mjs` covers native local-file navigation; the address-bar and overlay workflow remains manual.#### E2E-BROWSER-capture-resize: Capture preserves live placement and restores the latest viewportdiff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 5418b3c63..12a3dff4d 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -824,6 +824,10 @@ redirects; it does not wait for slow images or subframes. `browser:state` reportloading 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.+With the high-risk `browser.cdp` permission, `navigate` may open an existing+local file through an absolute path or `file:` URL. Relative paths remain+workspace-scoped. A local file page may navigate to other existing local files;+web pages retain only the prior in-workspace file-navigation allowance.The current guest page is a host-owned `WebContentsView` (`persist:work-browser`).Each resource tab retains its own page. A navigation for a background session isdiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex e50c58dfe..f8aa947e5 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -50,6 +50,7 @@ This log freezes previously open questions into concrete decisions.| D654 | Keep the deterministic first-prompt session title in the core | **Amend D652 / ADR 0323: a session whose stored title is still a recognized placeholder derives a whitespace-collapsed 48-character fallback from the first prompt, written through the host RPC and IPC `session/deriveTitle`. Host-core applies it only while the title is still a placeholder with the `default` source, and the derived text keeps that source, so an installed title plugin may still replace it and only a manual rename opts out. No model call, no new permission, no schema or protocol version change; `updated_at`, transcript content, and message count stay unchanged. See `03-runtime/01-ipc-protocol.md`, `03-runtime/02-agent-runtime.md`, `03-runtime/06-host-rpc-protocol.md`, `03-runtime/04-data-storage.md`, `04-ux/08-component-spec.md`, and E2E-021a.** | Removing every automatic write left an untouched session showing a placeholder until a plugin ran, so offline readability depended on installing optional software. || D655 | Cloud sync opens in packaged builds as Experimental | **Amend D649: remove the packaged-build visibility gate from Settings `sync` and restore its `Experimental` badge on the rail row and page title. Cloud sync and Remote Hosts are both available in packaged and development builds with Experimental badges. The S3 sync behavior, protocol, Host schema, and persisted data are unchanged. See `04-ux/06-settings-ia.md`, `03-runtime/22-config-sync.md`, and E2E-CONFIG-SYNC-s3-portable-configuration.** | The existing encrypted backup is useful to packaged-build users; the Experimental badge communicates its current maturity without keeping the feature hidden. || D656 | Quarantine appends the host keeps refusing instead of stalling the outbox | **Amend ADR 0041 / D318 / D444 / D597: an append whose `session.appendMessage` or `session.recordUsage` call fails with an error the outbox cannot classify as a duplicate message id, a `PERMISSION_DENIED:` poison row, or a foreign-key orphan is retried on a bounded backoff (5s, doubling to a 60s cap) instead of ending the flush. The fifth consecutive failure on that head moves it into an application-owned dead-letter file, `session-message-outbox.dead-letter.json`, with its payload, session id, quarantine timestamp, and host error; only the newest 256 quarantined appends are kept, and the oldest is discarded with a warn. The flush then continues with the next entry, so one refused append can no longer hold the FIFO head, fill the 1024-entry cap, or fail every session's writes. Quarantined appends are never replayed automatically, and `session.delete` drops that session's quarantined appends too. No protocol version, storage schema, or queued-outbox format change.** | A `stream did not contain valid UTF-8` append stayed at the FIFO head for 14.8 hours while `session.persistence.outbox.is.full` fired 5990 times, so every session's appends failed until restart. Only three error classes had a drain, and every other error was treated as transient forever (#1560). |+| D657 | Let the embedded Browser open local files outside the workspace | **Amend ADR 0170: an explicit absolute path or `file:` URL may load any existing regular local file, and a local-file page may navigate to other existing local files. Relative inputs remain workspace-rooted; HTTP(S) pages retain only the prior in-workspace file-link allowance. Missing files, directories, and remote file authorities remain blocked. `BrowserPreview` and the sidecar keep their workspace-rooted resolver. The public `pi.browser.navigate` API follows this policy under the high-risk `browser.cdp` permission. See ADR 0328, E2E-059, `04-ux/08-component-spec.md`, and `05-security/01-security.md`.** | Users need to inspect local HTML outside a project, while workspace-scoped agent file tools and remote-page navigation must retain their existing boundary (#1627). |## B. Secondary implementation defaults@@ -7641,3 +7642,17 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.restart, dead-letter cap, session delete) andE2E-SESSION-outbox-unclassifiable-failure-does-not-stall-the-queue. See ADR0041, `03-runtime/04-data-storage.md`, and `03-runtime/06-host-rpc-protocol.md`.++## 2026-10-13 — Open local files in the embedded Browser (D657)++- D657 amends ADR 0170: explicit absolute paths and `file:` URLs can open any+ existing regular local file, and local-file pages can follow links to other+ local files. Relative paths remain workspace-rooted. HTTP(S) pages cannot+ navigate outside the workspace through a file link.+- The public `pi.browser.navigate` API follows the same policy under its+ existing high-risk `browser.cdp` permission. `BrowserPreview` and the sidecar+ retain workspace-rooted validation.+- Covered by `apps/desktop/test/browser-pane-navigation.test.mjs`,+ `apps/desktop/test/browser-local-file-feedback.test.mjs`, and E2E-059. See+ ADR 0328, `04-ux/08-component-spec.md`, `07-plugins/03-plugin-api.md`, and+ `05-security/01-security.md`.diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 61678f2f2..a2498e2dd 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -772,14 +772,15 @@ vendor 进来的 `pi.file-manager` 视图在插件自己的隔离页面内完成当前主框架导航提交后即可显示页面,不再等待图片或子框架完成加载。导航失败或主框架等待超过 15 秒时显示可重试的错误,并隐藏旧页面;被替代或取消的请求不得覆盖新导航。- `file:` 地址或绝对路径若不能解析为当前会话工作区内已存在的文件,- 必须在加载前拒绝,并在浏览器栏显示明确的工作区范围提示;空白标签页也一样。- 工作区内已存在文件的绝对路径仍可预览。+ 地址栏可通过 `file:` URL 或绝对路径打开机器上任意已存在的本地文件;+ 本地文件页面也可导航到其他已存在的本地文件。缺失文件、目录、远程文件 authority+ 和不支持的 scheme 必须在加载前拒绝。相对路径仍以当前会话工作区为根。+ BrowserPreview 仍受工作区范围限制。- 浏览器地址栏接受 HTTP(S) URL 和省略协议的网页主机。`localhost` 或点分主机名后接数字端口时(如 `localhost:3000/index.html`、`example.com:8080`),按 HTTP 地址处理,而不是误认为自定义 scheme。不支持的 scheme 仍会被拒绝;- 工作区文件预览继续使用根目录范围校验。+ 显式本地文件导航不再限制于工作区,BrowserPreview 仍使用根目录范围校验。- 在工作面板中打开 HTTP(S) 链接会新增浏览器资源标签,不覆盖原网址。每个标签保留自己的 WebContents、地址、标题及浏览历史。切换只隐藏/显示页面,diff --git a/docs/zh-CN/spec/05-security/01-security.md b/docs/zh-CN/spec/05-security/01-security.mdindex d776ef9a9..2f311d244 100644--- a/docs/zh-CN/spec/05-security/01-security.md+++ b/docs/zh-CN/spec/05-security/01-security.md@@ -27,7 +27,8 @@`http:` / `https:` / `mailto:` URL 转给系统浏览器(`parseAllowedExternalUrl`,D330 / ADR 0168)。`file:`、`javascript:`、`data:` 和自定义 URI scheme 不会到达 `shell.openExternal`。- `will-navigate` 阻止所有非开发服务器导航+ `will-navigate` 由各自的界面实施策略;内置浏览器允许 HTTP(S)、工作区内文件链接,+ 以及从已加载本地文件发起的本地文件导航,其他 scheme 仍会被阻止。- 预加载仅公开经过白名单检查的 ADR/../03-runtime/09-logging-and-observability.md 桥(`IPC_WHITELIST` 在 preload 和主侧均强制执行)@@ -60,6 +61,13 @@[远程 Agent Control 架构](/zh-CN/spec/02-architecture/05-remote-agent-control)。本地安全基线不会因为远程目标规格而开放新的监听器或权限通道。+### 内置浏览器访问本地文件++内置浏览器可通过绝对路径或 `file:` URL 打开机器上任意已存在的本地文件,+本地文件页面也可导航到其他已存在的本地文件。网页仍只能打开工作区内的文件,+不能借助文件链接越出工作区。该浏览能力属于高风险 `browser.cdp` 权限;+`BrowserPreview` 与 sidecar 的工作区文件解析仍受会话工作区限制。+## 3. 秘密- 通过 Electron `safeStorage` 加密存储的密钥,由 host-core 管理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 ecb1e49d6..4c17cbb59 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@@ -2433,7 +2433,7 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的#### E2E-059:嵌入式浏览器预览隔离和覆盖-- **前提条件**:本地开发服务器正在运行;存在 URL 或 BrowserPreview 工件。+- **前提条件**:本地开发服务器正在运行;存在 URL 或 BrowserPreview 工件;工作区内外均有 HTML 测试文件。- **步骤**: 1) 激活工件,依次输入不带协议的 `localhost:<port>` 和`localhost:<port>/index.html` 并提交;再输入带端口的点分主机名(如 `example.com:8080`),验证显式 HTTP(S) 地址及被拒绝的 `javascript:` 地址。@@ -2441,26 +2441,30 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的`window.open` 弹出窗口和权限请求页面(例如通知提示)。 4) 打开全局搜索,然后打开设置。返回聊天并触发内联工具权限卡。 5) 切换到另一个面板选项卡- 然后回来;关闭面板。 6) 使用开放式外部。7) 分别从已有页面和空白浏览器标签页,- 使用 `file:` 地址和绝对路径打开工作区内已存在的 HTML 文件;再输入指向工作区外- 已存在文件的 `file:///tmp/demo.html` 和 `/tmp/demo.html`。+ 然后回来;关闭面板。 6) 使用“在外部打开”。7) 分别从已有页面和空白浏览器标签页,+ 使用平台对应的 `file:` 地址和绝对路径打开工作区内已存在的 HTML 文件;再使用平台对应的+ URL 和绝对路径打开工作区外已存在文件(Unix 如 `file:///tmp/demo.html` 和+ `/tmp/demo.html`;Windows 如 `file:///D:/demo.html` 和 `D:\demo.html`)。接着从已加载的+ 本地 HTML 页面点击链接,打开另一个工作区外文件;从 HTTP 页面尝试同一链接,并输入缺失的本地文件路径。- **预期**:无方案输入标准化为 http;导航状态(URL 栏,back/forward 启用、加载微调器)镜像页面。弹出窗口仅在 URL 解析为http(s) 或 mailto 时打开默认浏览器(绝不在应用程序内);- `file:`、`javascript:` 和自定义 scheme 被拒绝。许可请求被拒绝;- 非 http(s) 导航被阻止,根内 `file:` 同级文件除外。预览隐藏在每个遮挡下+ 弹出的 `file:`、`javascript:` 和自定义 scheme 被拒绝。许可请求被拒绝;+ 顶层导航允许 HTTP(S)、工作区内文件链接,以及从本地文件页面发起的已有本地文件链接。+ HTTP 页面不能导航到工作区外文件;缺失文件、目录、远程文件 authority 和其他 scheme 均被阻止。+ 预览隐藏在每个遮挡下覆盖并卸载时,随后以正确的边界重新出现。内嵌权限卡不会隐藏或重新挂载预览;resize/drag 期间原生视图保持可见,并与占位符矩形对齐,不再闪出黑色面板底色。打开工作面板上下文下拉框时,原生视图在不透明菜单边界下方保持可见,菜单关闭后恢复完整表面矩形。- Open-external 对 http(s) 页走系统浏览器,对根内文件预览走 `openPath`。- 视图使用隔离的持久分区(应用程序外壳中没有会话流失)。工作区内的两种地址- 都能打开;工作区外的两种地址都不会进入 guest 加载,地址栏保留提交的地址,- 浏览器用当前语言说明只能打开工作区内已存在的文件。-- **链接规格**:`03-runtime/01-ipc-protocol.md` §13a、ADR 0019、ADR 0168+ Open-external 对 http(s) 页走系统浏览器,对任意已加载本地文件走 `openPath`。+ 视图使用隔离的持久分区(应用程序外壳中没有会话流失)。工作区内外的地址都能加载;+ HTTP 页面发起的工作区外链接与缺失路径不会进入 guest。失败时地址栏保留输入,+ 浏览器用当前语言说明只能打开已存在的本地文件。+- **链接规格**:`03-runtime/01-ipc-protocol.md` §13a、`04-ux/08-component-spec.md`、`05-security/01-security.md`、ADR 0019、ADR 0168、ADR 0328- **验收**:质量、安全- **里程碑**:M5-- **状态**:草案(手动)+- **状态**:部分自动化:`scripts/e2e-browser-local-file-access.mjs` 覆盖原生本地文件导航;地址栏与遮挡层交互仍需手动验证。#### E2E-BROWSER-capture-resize:截图期间保持预览位置并恢复最新视口diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex 17d07559f..5cbba3618 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -675,6 +675,8 @@ pi.browser.cdp(input: { method: string; params?: unknown }): Promise<unknown>`navigate` 在当前主框架导航提交(含重定向)时返回,不等待慢图片或子框架。`browser:state` 立即报告加载状态,导航失败时可带 `loadError`。可选的 `sessionId`、`tabId` 标识宿主管理的工作面板目标;插件不能通过导航参数指定这些身份。+拥有高风险 `browser.cdp` 权限后,`navigate` 可以通过绝对路径或 `file:` URL 打开任意已存在的本地文件。+相对路径仍以工作区为根。本地文件页面可导航到其他已存在的本地文件;网页仍只能通过文件链接访问工作区内文件。### 服务(需要 `background.service`)```tsdiff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex c656e779c..526300583 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -52,6 +52,7 @@| D654 | 核心保留确定性的首条提示标题 | **修订 D652 / ADR 0323:当会话存储标题仍是可识别占位标题时,用首条提示派生一个折叠空白、截断为 48 字符的兜底标题,通过主机 RPC 与 IPC `session/deriveTitle` 写入。host-core 只在标题仍是占位标题且来源为 `default` 时接受,派生文本也保留该来源,因此已安装的标题插件仍可替换它,只有手动重命名会退出自动替换。不调用模型、不新增权限、不改架构或协议版本;`updated_at`、转录内容与消息数都不变。见 `03-runtime/01-ipc-protocol.md`、`03-runtime/02-agent-runtime.md`、`03-runtime/06-host-rpc-protocol.md`、`03-runtime/04-data-storage.md`、`04-ux/08-component-spec.md` 与 E2E-021a。** | 移除全部自动写入会让未触碰的会话一直显示占位标题,直到插件运行,从而让离线可读性依赖安装可选软件。 || D655 | 云同步在打包版开放并标记为实验性 | **修订 D649:移除设置中 `sync` 目的地的打包构建门控,并在导轨行与页面标题恢复实验性徽章。云同步和远程主机在开发版与打包版中均可使用,并带有实验性标签。S3 同步行为、协议、Host schema 与持久化数据不变。见 `04-ux/06-settings-ia.md`、`03-runtime/22-config-sync.md` 与 E2E-CONFIG-SYNC-s3-portable-configuration。** | 已实现的加密云备份对打包版用户同样有用;实验性标签可以说明其成熟度,而无需继续隐藏功能。 || D656 | 隔离宿主持续拒绝的 outbox 追加,避免整队停摆 | **修订 ADR 0041 / D318 / D444 / D597:当 `session.appendMessage` 或 `session.recordUsage` 返回的错误无法归类为重复消息 ID、`PERMISSION_DENIED:` 毒行或外键孤立行时,不再结束本次 flush,而是在同一 Host 代内按有界退避重试(5 秒起、翻倍、上限 60 秒)。同一队头连续第五次失败后,该追加被移入应用自有的死信文件 `session-message-outbox.dead-letter.json`(保留载荷、sessionId、隔离时间与宿主错误;只保留最新 256 条,超出丢弃最旧并记 warn),随后继续排空后续条目,因此单条被拒追加不再长期占用 FIFO 队头、填满 1024 条上限或导致所有会话写入失败。Host 重启属于新代,会立即重试该队头。隔离条目永不自动重放,`session.delete` 会连同该会话的隔离条目一起删除。协议版本、存储架构与队列文件格式均不变。** | 一条 `stream did not contain valid UTF-8` 追加在队头滞留 14.8 小时,期间 `session.persistence.outbox.is.full` 触发 5990 次,导致所有会话的写入直到重启前全部失败;此前只有三类错误有排空出口,其余错误被永久当作瞬时错误(#1560)。 |+| D657 | 让内置浏览器打开工作区外的本地文件 | **修订 ADR 0170:通过绝对路径或 `file:` URL 可打开任意已存在的本地普通文件,本地文件页面也可导航到其他已存在的本地文件。相对输入仍以工作区为根;HTTP(S) 页面只保留此前工作区内文件链接的权限。缺失文件、目录与远程文件 authority 仍被阻止。`BrowserPreview` 与 sidecar 继续使用工作区根解析。公开的 `pi.browser.navigate` API 在高风险 `browser.cdp` 权限下采用相同策略。见 ADR 0328、E2E-059、`04-ux/08-component-spec.md` 与 `05-security/01-security.md`。** | 用户需要检查项目外的本地 HTML,而工作区范围内的 Agent 文件工具和远程页面导航仍须保留原有边界(#1627)。 |## B. 辅助实现默认值@@ -5388,3 +5389,13 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编跨重启保留死信、死信上限、会话删除)与E2E-SESSION-outbox-unclassifiable-failure-does-not-stall-the-queue 覆盖。见 ADR 0041、`03-runtime/04-data-storage.md` 与 `03-runtime/06-host-rpc-protocol.md`。++## 2026-10-13 —— 内置浏览器打开工作区外本地文件(D657)++- D657 修订 ADR 0170:绝对路径与 `file:` URL 可打开任意已存在的本地普通文件,本地文件页面也可+ 跟随链接访问其他本地文件。相对路径仍以工作区为根;HTTP(S) 页面不能通过 file 链接越出工作区。+- 公开的 `pi.browser.navigate` API 在现有高风险 `browser.cdp` 权限下采用相同策略。+ `BrowserPreview` 与 sidecar 仍保留工作区范围校验。+- 由 `apps/desktop/test/browser-pane-navigation.test.mjs`、+ `apps/desktop/test/browser-local-file-feedback.test.mjs` 与 E2E-059 覆盖。见 ADR 0328、+ `04-ux/08-component-spec.md`、`07-plugins/03-plugin-api.md` 与 `05-security/01-security.md`。diff --git a/package.json b/package.jsonindex 74d89b4bd..684058061 100644--- a/package.json+++ b/package.json@@ -60,6 +60,7 @@"test:e2e:window-resize-native": "node scripts/e2e-window-controls.mjs --native-edge-drag","test:e2e:window-surface": "node scripts/e2e-window-surface.mjs","test:e2e:work-panel-reorder": "node scripts/e2e-work-panel-reorder.mjs",+ "test:e2e:browser-local-files": "node scripts/e2e-browser-local-file-access.mjs","test:e2e:work-panel-drag": "node scripts/e2e-work-panel-drag.mjs","test:e2e:supervision": "node scripts/e2e-supervision.mjs","test:e2e:subagents": "node scripts/e2e-subagents.mjs",diff --git a/scripts/e2e-browser-local-file-access.mjs b/scripts/e2e-browser-local-file-access.mjsnew file mode 100644index 000000000..65c0c60ba--- /dev/null+++ b/scripts/e2e-browser-local-file-access.mjs@@ -0,0 +1,45 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdtempSync } from "node:fs";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const dependencyRoot = process.env.E2E_DEPENDENCY_ROOT || root;+const require = createRequire(join(dependencyRoot, "packages/agent-runtime/package.json"));+const { build } = require("esbuild");+const { electronBinary } = resolveElectronBinary(dependencyRoot);+const artifacts = mkdtempSync(join(tmpdir(), "pi-browser-local-files-"));+const main = join(artifacts, "main.cjs");+await build({+ entryPoints: [join(root, "scripts/e2e/browser-local-file-access.ts")],+ outfile: main,+ bundle: true,+ platform: "node",+ format: "cjs",+ external: ["electron"],+});+const env = { ...process.env, BROWSER_LOCAL_FILE_ARTIFACT_DIR: artifacts };+delete env.ELECTRON_RUN_AS_NODE;+const child = spawn(electronBinary, [main], { env, stdio: ["ignore", "pipe", "pipe"] });+let output = "";+for (const stream of [child.stdout, child.stderr]) {+ stream.on("data", (data) => { output += data; });+}+const timeout = setTimeout(() => child.kill(), 30_000);+let code;+try {+ code = await new Promise((resolve, reject) => {+ child.once("error", reject);+ child.once("close", resolve);+ });+} finally {+ clearTimeout(timeout);+}+console.log(`Browser local-file artifacts retained at ${artifacts}`);+console.log(output.trim());+assert.equal(code, 0, "native browser local-file access regression failed");+assert.match(output, /"ok":true/);diff --git a/scripts/e2e/browser-local-file-access.ts b/scripts/e2e/browser-local-file-access.tsnew file mode 100644index 000000000..d2a1eb751--- /dev/null+++ b/scripts/e2e/browser-local-file-access.ts@@ -0,0 +1,100 @@+import assert from "node:assert/strict";+import { once } from "node:events";+import { mkdtempSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";+import { createServer } from "node:http";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import { app, BrowserWindow } from "electron";+import { BrowserPane } from "../../apps/desktop/electron/main/browser-view";++const artifactDir = process.env.BROWSER_LOCAL_FILE_ARTIFACT_DIR;+if (!artifactDir) throw new Error("BROWSER_LOCAL_FILE_ARTIFACT_DIR is required");+const artifactRoot = artifactDir;+app.setPath("userData", join(artifactRoot, "profile"));++async function run(): Promise<void> {+ const workspace = mkdtempSync(join(artifactRoot, "workspace-"));+ const outside = mkdtempSync(join(artifactRoot, "outside-"));+ const outsideStart = join(outside, "start.html");+ const outsideNext = join(outside, "next.html");+ const outsideMissing = join(outside, "missing.html");+ mkdirSync(workspace, { recursive: true });+ mkdirSync(outside, { recursive: true });+ writeFileSync(outsideNext, "<!doctype html><title>Outside next</title><p>Outside sibling</p>");+ const outsideNextUrl = pathToFileURL(realpathSync(outsideNext)).href;+ writeFileSync(outsideStart, `<!doctype html><title>Outside start</title>+ <a id="next" href="${outsideNextUrl}">Next local file</a>`);+ const outsideStartUrl = pathToFileURL(realpathSync(outsideStart)).href;++ const server = createServer((_request, response) => {+ response.setHeader("Content-Type", "text/html; charset=utf-8");+ response.end("<!doctype html><title>HTTP page</title><p>HTTP fixture</p>");+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ const address = server.address();+ assert(address && typeof address !== "string");+ const httpUrl = `http://127.0.0.1:${address.port}/`;+ const window = new BrowserWindow({ width: 800, height: 600, show: false });+ const pane = new BrowserPane(() => {});++ try {+ pane.setWindow(window);+ pane.setBounds({ x: 0, y: 0, width: 700, height: 500 });+ pane.setVisible(true);++ const fileUrlState = await pane.navigateAndWait(outsideStartUrl, workspace, 5_000);+ assert.equal(fileUrlState?.url, outsideStartUrl, "file URL outside the workspace loads");+ const wc = pane.getWebContents();+ assert(wc, "browser guest exists after file navigation");+ assert.equal(await wc.executeJavaScript("document.title"), "Outside start");++ const absoluteState = await pane.navigateAndWait(outsideNext, workspace, 5_000);+ assert.equal(absoluteState?.url, outsideNextUrl, "absolute path outside the workspace loads");+ assert.equal(await wc.executeJavaScript("document.title"), "Outside next");++ await pane.navigateAndWait(outsideStart, workspace, 5_000);+ const localWillNavigate = once(wc, "will-navigate").then(([event, url]) => ({+ prevented: event.defaultPrevented,+ url: url as string,+ }));+ const localLinkNavigation = once(wc, "did-navigate").then(([event, url]) => url as string);+ const localPageLoaded = once(wc, "did-finish-load");+ await wc.executeJavaScript("document.querySelector('#next').click()").catch(() => undefined);+ const localAttempt = await localWillNavigate;+ assert.equal(localAttempt.prevented, false, "local pages may navigate outside the workspace");+ assert.equal(await localLinkNavigation, outsideNextUrl, "a local page follows an outside file link");+ await localPageLoaded;+ assert.equal(await wc.executeJavaScript("document.title"), "Outside next");++ await pane.navigateAndWait(httpUrl, workspace, 5_000);+ assert.equal(wc.getURL(), httpUrl, "HTTP fixture loads");++ const missingState = await pane.navigateAndWait(outsideMissing, workspace, 5_000);+ assert.equal(missingState, null, "missing local files are rejected");+ assert.equal(wc.getURL(), httpUrl, "missing files never reach Electron navigation");+ assert.equal(pane.getState()?.loadError, "LOCAL_FILE_NOT_ALLOWED");++ console.log(JSON.stringify({+ ok: true,+ electron: process.versions.electron,+ chrome: process.versions.chrome,+ fileUrl: true,+ absolutePath: true,+ localFileLink: true,+ httpPageLoads: true,+ missingFileBlocked: true,+ }));+ } finally {+ pane.dispose();+ if (!window.isDestroyed()) window.destroy();+ await new Promise<void>((resolve, reject) => {+ server.close((error) => error ? reject(error) : resolve());+ });+ }+}++app.whenReady().then(run).then(+ () => app.exit(0),+ (error: unknown) => { console.error(error); app.exit(1); },+);