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(desktop): resolve HTML artifacts in isolated session worktrees
AR3072ad7048d00dc
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.tsindex 32a511205..57d7b5979 100644--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts@@ -771,9 +771,19 @@ export function registerWorkspaceIpc({const requireWorkspaceRoot = async (sessionId?: string) => {const owner = getHost();if (!owner) throw new Error("host unavailable");- const root = sessionId- ? (await owner.call<{ session?: { projectPath?: string } }>("session.get", { id: sessionId, messageLimit: 1 })).session?.projectPath- : (await owner.call<{ workspace?: { path: string } }>("workspace.get")).workspace?.path;+ let root: string | undefined;+ if (sessionId) {+ const { session } = await owner.call<{ session?: { projectPath?: string; worktree?: unknown } }>(+ "session.get", { id: sessionId, messageLimit: 1 },+ );+ // Chat references and source reads must see the same files as the+ // session's tools, not a same-named file in the parent checkout.+ root = session?.worktree+ ? (await owner.call<{ path?: string }>("worktree.location", { sessionId })).path+ : session?.projectPath;+ } else {+ root = (await owner.call<{ workspace?: { path: string } }>("workspace.get")).workspace?.path;+ }if (getHost() !== owner) throw Object.assign(new Error("host replaced"), { errorCode: ErrorCodes.HOST_UNAVAILABLE });if (!root) throw Object.assign(new Error("workspace required"), { errorCode: ErrorCodes.INVALID_ARGUMENT });return root;diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 0ac3f7fe0..4d4a72303 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1851,15 +1851,16 @@ Command sources:Work panel channels are Electron-main implementations. User-driven workspaceoperations resolve the visible root from `workspace.get` and fail closed-without one. Browser navigation and Agent-driven BrowserPreview resolve the-owning conversation through `session.get`, allowing its project-group folders-and its own `<data_dir>/scratch/<sessionId>` directory. A temporary conversation-needs no workspace to preview its generated HTML. A missing session fails-explicitly; a background preview never inherits the visible session's roots.-BrowserPreview emits the validated absolute path to the existing resource-tab-owner. Realpath containment applies to initial and in-page local navigation.-Other sessions' scratch files and attachments do not gain execution permission-from their separate read-only file-reference access.+without one. Agent-driven BrowserPreview resolves the owning conversation+through `session.get`, allowing its project-group folders (or its isolated+worktree) and its own `<data_dir>/scratch/<sessionId>` directory. A temporary+conversation needs no workspace to preview its generated HTML. A missing+session fails explicitly; a background preview never inherits the visible+session's roots. BrowserPreview validates realpath containment before emitting+the absolute path to the existing resource-tab owner. Chat links to other+sessions' scratch files and attachments retain the read-only file surface.+This does not restrict the Browser's explicit absolute-path / `file:` address+entry or local-page navigation, which follow its existing local-file policy.### workspace@@ -1919,11 +1920,13 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:`.mp4` symlink inside its private app-data directory before the OS handoff,so the extensionless blob has a media association without copying its bytes.- `fs/resolveRef({ref, sessionId?})` → `FsChatRefResolveResult`+ (for isolated sessions, lookup and file reads use `worktree.location` rather+ than the parent project checkout)(`{ match: FsChatRefMatch | null, reason?: "outside-allowed-roots" }`, the match naming the answering `root`(`workspace` / `scratch` / `attachments`), the `relativePath` relative to thatroot, optional `sessionScratch: true` for the current session's own scratch- (not the wider read-only scratch containment store), the- root, the absolute `absolutePath`, `matchedBy` (`exact-relative` /+ (not the wider read-only scratch containment store), the absolute+ `absolutePath`, `matchedBy` (`exact-relative` /`exact-absolute` / `path-suffix` / `basename`), and — for a `workspace` match— `projectRoot` (`{ path, name, primary }`), which names the project folderthat answered); `sessionId` selects thediff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 49d67c36c..c61d1c03d 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -1352,7 +1352,7 @@ Project drag/drop follows these patterns:available), a session-scratch or attachment file in the host `file:` tab, andan unpositioned `.html`/`.htm` page from any project folder or the currentsession's scratch directory in the side browser. HTML navigation uses the- resolved absolute path; the browser validates the owning session's roots.+ resolved absolute path after file-reference resolution checks its roots.No project is required to open a scratch artifact. Missing workspace stateis normalized consistently across asynchronous session-change guards.Local `file:` Markdown URLs are converted to file references beforediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 2373703ae..bf1e75f6e 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4661,11 +4661,12 @@ window; opening a normal panel afterward must still work.- **Preconditions**: Isolated Electron profile, real Host storage and loopbackmodel fixture; no credentials or paid provider requests.- **Steps**: Open assistant Markdown links to ordinary-session scratch HTML,- primary project HTML, secondary project-folder HTML and project scratch HTML.- Repeat with a `file:` URL containing Unicode/spaces. Interact with the- rendered page. Try a missing file, an outside file and a positioned HTML+ primary project HTML, secondary project-folder HTML, project scratch HTML+ and an isolated session's worktree HTML. Repeat with a `file:` URL containing+ Unicode/spaces. Interact with each rendered page using native pointer input.+ Try a missing file, an outside file and a positioned HTMLsource reference. Send a prompt that invokes BrowserPreview through the real- sidecar in an ordinary and a project conversation. Disable Browser and click+ sidecar in ordinary, project and isolated conversations. Disable Browser and clickagain. Switch conversations between cases.- **Expected**: Valid pages render and execute in the side browser at theircanonical path. Missing/restricted files report errors without guest loads.diff --git a/scripts/e2e-chat-html-artifacts.mjs b/scripts/e2e-chat-html-artifacts.mjsindex 32008e3bc..d9d836621 100644--- a/scripts/e2e-chat-html-artifacts.mjs+++ b/scripts/e2e-chat-html-artifacts.mjs@@ -4,10 +4,11 @@import assert from "node:assert/strict";import { mkdir, mkdtemp, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";-import { join } from "node:path";+import { basename, join } from "node:path";import { pathToFileURL } from "node:url";import { randomUUID } from "node:crypto";import { createRequire } from "node:module";+import { execFileSync } from "node:child_process";import { Host, resolveHostBinary } from "./e2e/host.mjs";import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";import { startHtmlPreviewModel } from "./e2e/html-preview-model.mjs";@@ -38,12 +39,23 @@ try {await host.call("project.group.create", { name: "HTML project", folders: [primary, secondary] });await host.call("workspace.set", { path: primary });const project = (await host.call("session.create", { title: "HTML project conversation", projectPath: primary })).session;+ // A real isolated session must preview its worktree, not the parent checkout.+ const git = (...args) => execFileSync("git", args, { cwd: primary, stdio: "pipe" });+ git("init", "-q");+ git("-c", "user.name=HTML fixture", "-c", "[email protected]",+ "commit", "--allow-empty", "-qm", "Initialize HTML fixture");+ const isolated = (await host.call("session.create", {+ title: "HTML isolated conversation", projectPath: primary, isolated: true,+ }, 120_000)).session;+ const worktree = (await host.call("worktree.location", { sessionId: isolated.id })).path;+ assert.ok(worktree && worktree !== primary, "isolated session has its own checkout");for (const [session, dir, label, spelling] of [[plain, join(data, "scratch", plain.id), "Ordinary scratch", "relative"],[project, primary, "Project primary", "relative"],[project, secondary, "Project secondary", "absolute"],[project, join(data, "scratch", project.id), "Project scratch", "absolute"],[plain, join(data, "scratch", plain.id), "File URL Unicode", "url"],+ [isolated, worktree, "Isolated worktree", "relative"],]) {await mkdir(dir, { recursive: true });const name = spelling === "url" ? "鹈鹕 animation.html" : label.replaceAll(" ", "-") + ".html";@@ -80,6 +92,12 @@ try {} });}}+ for (const [role, content] of [["user", "Inspect isolated HTML source"],+ ["assistant", "Source: Isolated-worktree.html:1"]]) {+ await host.call("session.appendMessage", { sessionId: isolated.id, message: {+ id: randomUUID(), role, content, status: "complete", createdAt: new Date().toISOString(),+ } });+ }} finally { await host.stop(); }const env = { ...process.env, PI_DESKTOP_DATA_DIR: data, PI_DESKTOP_HOST_BIN: binary,@@ -124,11 +142,21 @@ try {if (!BrowserWindow.getAllWindows().some(window => visibleGuest(window.contentView.children))) {throw new Error("The loaded guest is not attached to a visible native surface");}- // WebContentsView is a native child outside Playwright's DOM. The guest- // interaction is executed in that same real page after its visible- // attachment is verified above; the screenshot below proves the rendered- // page, rather than a mocked link, is the surface under test.- return wc.executeJavaScript("document.querySelector('button').click();document.querySelector('#result').textContent");+ // WebContentsView is outside the renderer DOM: send native pointer+ // input to the rendered guest instead of invoking a DOM click handler.+ const point = await wc.executeJavaScript("(() => { const r = document.querySelector('button').getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()");+ wc.focus();+ wc.sendInputEvent({ type: "mouseMove", ...point });+ wc.sendInputEvent({ type: "mouseDown", ...point, button: "left", clickCount: 1 });+ wc.sendInputEvent({ type: "mouseUp", ...point, button: "left", clickCount: 1 });+ const until = Date.now() + 5_000;+ let text;+ do {+ text = await wc.executeJavaScript("document.querySelector('#result').textContent");+ if (text === "Animation opened") return text;+ await new Promise(resolve => setTimeout(resolve, 50));+ } while (Date.now() < until);+ return text;}, guest), "Animation opened");const png = await app.evaluate(async ({ webContents }, id) =>(await webContents.fromId(id).capturePage()).toPNG().toString("base64"), guest);@@ -145,30 +173,59 @@ try {assert.equal(await app.evaluate(({ webContents }, url) =>webContents.getAllWebContents().some(wc => wc.getURL() === url), pathToFileURL(outside).href), false);results.push("outside HTML is rejected without guest navigation");+ for (const dismiss of await page.locator(".toast-dismiss").all()) await dismiss.click();+ await page.locator(".toast").first().waitFor({ state: "hidden" });await page.getByText("Ordinary-scratch.html:1", { exact: true }).click();await page.locator(".file-viewer").waitFor();results.push("positioned HTML opens source, not execution");+ await page.evaluate(id => window.__PI_DESKTOP__.selectSession(id), cases[5].sessionId);+ await page.getByText("Isolated-worktree.html:1", { exact: true }).click();+ await page.locator(".file-viewer").waitFor();+ await page.locator(".file-viewer").getByText(/Pelican bicycle animation/).waitFor();+ results.push("isolated HTML source reads the session worktree");// Exercise BrowserPreview through a user send, ToolSearch, sidecar and main.// The only fake is the loopback provider, which requests a deterministic tool.- for (const item of [cases[0], cases[2]]) {+ for (const item of [cases[0], cases[2], cases[5]]) {await page.evaluate(id => window.__PI_DESKTOP__.selectSession(id), item.sessionId);- model.preview(item.file);+ model.preview(item === cases[2] ? item.file : basename(item.file));const composer = page.locator('.composer-input[contenteditable="true"]');await composer.fill("Open the generated HTML with BrowserPreview.");await composer.press("Enter");await page.getByText("HTML preview tool completed.", { exact: true }).filter({ visible: true }).waitFor({ timeout: 45_000 });- assert.equal(await app.evaluate(({ webContents, BrowserWindow }, url) => {- const guest = webContents.getAllWebContents().find(item => item.getURL() === url);- const visible = views => views.some(view => view.getVisible() &&- (view.webContents?.id === guest?.id || visible(view.children)));- return Boolean(guest && BrowserWindow.getAllWindows().some(window => visible(window.contentView.children)));- }, pathToFileURL(item.file).href), true, "BrowserPreview opens its HTML in the visible native panel");+ // BrowserPreview creates a new resource tab even if an older, hidden tab+ // already holds the same URL. Wait for that new native page to appear.+ const deadline = Date.now() + 15_000;+ let visible = false;+ do {+ visible = await app.evaluate(({ webContents, BrowserWindow }, url) => {+ const ids = new Set(webContents.getAllWebContents()+ .filter(item => item.getURL() === url).map(item => item.id));+ const attached = views => views.some(view => view.getVisible() &&+ (ids.has(view.webContents?.id) || attached(view.children)));+ return BrowserWindow.getAllWindows().some(window => attached(window.contentView.children));+ }, pathToFileURL(item.file).href);+ if (visible) break;+ await new Promise(resolve => setTimeout(resolve, 100));+ } while (Date.now() < deadline);+ assert.equal(visible, true, "BrowserPreview opens its HTML in the visible native panel");assert.deepEqual(model.failures, []);results.push("BrowserPreview through actual send: " + item.label);}await page.screenshot({ path: join(output, "browser-preview-visible.png") });- results.push("full Electron window captured with BrowserPreview visible");+ results.push("renderer shell captured; native HTML guests captured separately");+ if (process.platform === "win32") {+ const native = await app.evaluate(async ({ desktopCapturer }) => {+ const sources = await desktopCapturer.getSources({+ types: ["window"], thumbnailSize: { width: 1600, height: 1200 },+ });+ const source = sources.find(item => item.name === "PI HTML Link Regression QA");+ if (!source || source.thumbnail.isEmpty()) throw new Error("Test-window native capture unavailable");+ return source.thumbnail.toPNG().toString("base64");+ });+ await writeFile(join(output, "native-window.png"), Buffer.from(native, "base64"));+ results.push("native Windows window captured with browser guest");+ }await page.evaluate(id => window.__PI_DESKTOP__.selectSession(id), cases[0].sessionId);await page.evaluate(async () => {const result = await window.piDesktop.invoke("pi-desktop/plugin/disable", "pi.browser");