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): integrate HTML previews with current upstream
AR307f495d258a273
diff --cc apps/desktop/electron/main/browser-host.tsindex 58a3c0fa1,e31ba2f13..c00ae2cb0--- a/apps/desktop/electron/main/browser-host.ts+++ b/apps/desktop/electron/main/browser-host.ts@@@ -366,7 -410,7 +410,7 @@@ export class BrowserHostassertVisible();let state: BrowserState | null;try {- state = await page.pane.navigateAndWait(target, roots);- state = await page.pane.navigateAndWait(target, root);++ state = await page.pane.navigateAndWait(target, roots[0] ?? null);} catch (error) {if (!current()) return null;page.navigating = false;diff --cc apps/desktop/electron/main/services/plugin-services.tsindex 6a4eec405,95e8afbde..b1b405977--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@@ -601,16 -601,19 +601,24 @@@ export function createPluginServices(})().catch((error) => logger.app("plugin", "warn", "browser.link.open.failed", { data: String(error) }));},isPluginLoaded: (pluginId) => Boolean(plugins.getLoaded(pluginId)),- getFileRoot: async (sessionId) => {- if (sessionId) {- try {- const res = (await getHost()?.call("session.get", { id: sessionId })) as- | { session: { projectPath?: string } | null }- | undefined;- const path = res?.session?.projectPath?.trim();- if (path) return path;- } catch {- // Fall through to the visible workspace.- }+ getFileRoots: async (sessionId) => {+ if (!sessionId) return projectFolderPaths(getWorkspacePath());- const res = await getHost()?.call<{ session: { projectPath?: string } | null }>(++ const host = getHost();++ if (!host) throw new Error("Browser preview host is unavailable.");++ const res = await host.call<{ session: { projectPath?: string; worktree?: unknown } | null }>(+ "session.get", { id: sessionId },+ );+ if (!res?.session) throw new Error("Browser preview session is unavailable.");++ if (res.session.worktree) {++ const location = await host.call<{ path?: string }>("worktree.location", { sessionId });++ const path = location.path?.trim();++ if (!path) throw new Error("Browser preview worktree is unavailable.");++ return [path, join(dataDir, "scratch", sessionId)];+ }- return getWorkspacePath();+ return [+ ...projectFolderPaths(res.session.projectPath?.trim() || null),+ join(dataDir, "scratch", sessionId),+ ];},getScratchDir: (sessionId) => {if (!sessionId) return null;diff --cc apps/desktop/test/browser-host-session.test.mjsindex a4a715af3,875c28e13..e92a87309--- a/apps/desktop/test/browser-host-session.test.mjs+++ b/apps/desktop/test/browser-host-session.test.mjs@@@ -20,9 -20,9 +20,9 @@@ function harness()setVisible(value) { this.visible = value; },getState: () => state, getWebContents: () => null,invalidateNavigation: () => {},- navigateAndWait(target, fileRoots) {- navigateAndWait(target) {++ navigateAndWait(target, fileRoot) {const done = deferred();- loads.push({ target, fileRoots, pane, finish() {- loads.push({ target, pane, finish() {++ loads.push({ target, fileRoot, pane, finish() {state = { url: target, title: target, isLoading: false, canGoBack: false, canGoForward: false };onState(state); done.resolve(state);}, fail: () => done.resolve(null) });@@@ -104,21 -103,6 +104,21 @@@ test("background navigation targets thaassert.equal(h.host.getState(), null);});+test("a temporary preview uses its own scratch even while a project session is visible", async () => {+ const h = harness();+ await open(h, "project", "project-tab", "project.html");+ h.host.setChromeSession("temporary", "scratch-tab", "/scratch/temporary/animation.html");+ assert.equal(h.roots.at(-1).sessionId, "temporary");+ h.roots.at(-1).resolve(null);+ await settled();- assert.deepEqual(h.loads.at(-1).fileRoots, ["/scratch/temporary"]);++ assert.equal(h.loads.at(-1).fileRoot, "/scratch/temporary");+ h.loads.at(-1).finish();+ await settled();+ h.host.setChromeSession("project", "project-tab");+ assert.equal(h.host.getState().url, "project.html");+ h.host.dispose();+});+test("an empty tab exposes no previous address or native page", async () => {const h = harness(); await open(h, "A", "a", "A.html");h.host.setChromeSession("A", "blank");diff --cc apps/desktop/test/browser-preview-tool.test.mjsindex 86b044083,56bacc40c..4837fe68f--- a/apps/desktop/test/browser-preview-tool.test.mjs+++ b/apps/desktop/test/browser-preview-tool.test.mjs@@@ -44,7 -44,7 +44,7 @@@ test("sidecar routes main-local tools b);});--test("main serves BrowserPreview from its originating session workspace", () => {++test("main serves BrowserPreview from its originating session workspace", async () => {assert.match(mainSource, /s\.setLocalTool\("BrowserPreview"/);// The local tool receives session identity from the sidecar and resolves the// workspace from that durable session, never from the visible shell project.@@@ -53,9 -53,19 +53,15 @@@mainSource.indexOf("sidecar = s;"),);assert.match(handler, /async \(\{ args, sessionId \}\)/);- assert.match(handler, /root = await sessionFileRoot\(sessionId\)/);+ assert.match(handler, /browserHost\.getFileRoots\(sessionId\)/);assert.doesNotMatch(handler, /workspace\.get/);- // The root comes from the durable session: its project, or the worktree of an- // isolated session resolved by host-core (ADR 0329).- const resolver = mainSource.slice(- mainSource.indexOf("const sessionFileRoot = async"),- mainSource.indexOf('s.setLocalTool("BrowserPreview"'),- );- assert.match(resolver, /"session\.get", \{ id: sessionId \}/);- assert.match(resolver, /res\?\.session\?\.projectPath/);- assert.match(resolver, /"worktree\.location", \{ sessionId \}/);- assert.doesNotMatch(resolver, /workspace\.get/);- assert.match(handler, /browserHost\.previewWorkspaceFile\(sessionId, raw, root\)/);+ assert.match(handler, /browserHost\.previewFile\(\)/);++ const services = await readFile(new URL("../electron/main/services/plugin-services.ts", import.meta.url), "utf8");++ const roots = services.slice(services.indexOf("getFileRoots: async"), services.indexOf("getScratchDir:"));++ assert.match(roots, /"session\.get", \{ id: sessionId \}/);++ assert.match(roots, /res\.session\.worktree/);++ assert.match(roots, /"worktree\.location", \{ sessionId \}/);++ assert.match(roots, /return \[path, join\(dataDir, "scratch", sessionId\)\]/);assert.ok(handler.indexOf("resolveLocalFile(raw, root)") <handler.indexOf("sendToRenderer(IPC.event.browserPreview"),diff --cc docs/spec/06-delivery/04-e2e-test-plan.mdindex e06c20fbf,915181bd7..2373703ae--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@@ -4520,38 -4645,17 +4645,38 @@@ window; opening a normal panel afterwarvisible 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 files in- the session's project folders or scratch directory 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-CHAT-html-artifacts: Open generated pages from ordinary and project conversations++- **Preconditions**: Isolated Electron profile, real Host storage and loopback+ model 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+ source reference. Send a prompt that invokes BrowserPreview through the real+ sidecar in an ordinary and a project conversation. Disable Browser and click+ again. Switch conversations between cases.+- **Expected**: Valid pages render and execute in the side browser at their+ canonical path. Missing/restricted files report errors without guest loads.+ A line reference opens source, not execution. Disabled Browser remains+ disabled and reports an error. BrowserPreview uses its originating session's+ roots and delivers a valid resource tab. No visible-project fallback.+- **Automation**: `node scripts/e2e-chat-html-artifacts.mjs`, after building+ Host, runtime and Electron. Captures and synthetic profiles are retained in+ `PI_TEST_OUTPUT` (or the OS temporary directory).+- **Status**: Electron user-path covered on Windows; other OSes pending.+#### E2E-BROWSER-capture-resize: Capture preserves live placement and restores the latest viewport- **Preconditions**: Isolated Electron profile and a local responsive pagediff --cc scripts/e2e-chat-html-artifacts.mjsindex 2ed84d1a0,000000000..32008e3bcmode 100644,000000..100644--- a/scripts/e2e-chat-html-artifacts.mjs+++ b/scripts/e2e-chat-html-artifacts.mjs@@@ -1,191 -1,0 +1,191 @@@+#!/usr/bin/env node+// Real transcript clicks, Rust storage, preload IPC and native HTML guests.- // No provider requests: seed only synthetic messages in an isolated profile.++// Only the loopback model fixture receives requests; all session data is synthetic.+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 { pathToFileURL } from "node:url";+import { randomUUID } from "node:crypto";+import { createRequire } from "node:module";+import { Host, resolveHostBinary } from "./e2e/host.mjs";+import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";+import { startHtmlPreviewModel } from "./e2e/html-preview-model.mjs";++const root = repositoryRoot();+const require = createRequire(import.meta.url);+const { _electron } = require(process.env.PI_TEST_PLAYWRIGHT || "playwright");+const output = await mkdtemp(join(process.env.PI_TEST_OUTPUT || tmpdir(), "pi-html-links-"));+const data = join(output, "data"), primary = join(output, "project"), secondary = join(output, "assets");+await Promise.all([data, primary, secondary].map(path => mkdir(path, { recursive: true })));+const binary = resolveHostBinary();+const host = new Host(binary, data, { quiet: true });+const model = await startHtmlPreviewModel();+const cases = [];+let outside;+const html = '<!doctype html><meta charset="utf-8"><title>Pelican animation</title><style>body{background:#f5f5f5;color:#222;font:20px system-ui;padding:28px}svg{width:240px}circle{animation:ride 2s infinite alternate}@keyframes ride{to{transform:translateX(80px)}}</style><h1>Pelican bicycle animation</h1><svg viewBox="0 0 240 80"><circle cx="40" cy="40" r="24" fill="#222"/></svg><p id="result">Ready</p><button onclick="document.querySelector(\'#result\').textContent=\'Animation opened\'">Run animation</button>';+try {+ await host.start();+ const { provider } = await host.call("providers.create", {+ name: "HTML local fixture", vendorKey: "custom", type: "openai_compatible",+ protocol: "openai_compatible", baseUrl: model.baseUrl, authKind: "none",+ defaultModelId: "html-fixture", apiStyle: "chat_completions",+ });+ await host.call("settings.set", { language: "en", theme: "dark", developerMode: true,+ defaultProviderId: provider.id, defaultModelId: "html-fixture",+ defaultMode: "agent", defaultPermissionMode: "auto" });+ const plain = (await host.call("session.create", { title: "HTML ordinary conversation" })).session;+ 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;+ 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"],+ ]) {+ await mkdir(dir, { recursive: true });+ const name = spelling === "url" ? "鹈鹕 animation.html" : label.replaceAll(" ", "-") + ".html";+ const file = join(dir, name);+ await writeFile(file, html);+ const href = spelling === "relative" ? name : spelling === "url" ? pathToFileURL(file).href : file.replaceAll("\\", "/");+ await host.call("session.appendMessage", { sessionId: session.id, message: {+ id: randomUUID(), role: "user", content: "Create " + label,+ status: "complete", createdAt: new Date().toISOString(),+ } });+ await host.call("session.appendMessage", { sessionId: session.id, message: {+ id: randomUUID(), role: "assistant", content: "[" + label + "](<" + href + ">)",+ status: "complete", createdAt: new Date().toISOString(),+ } });+ cases.push({ sessionId: session.id, label, file });+ }+ await host.call("session.appendMessage", { sessionId: plain.id, message: {+ id: randomUUID(), role: "user", content: "Open a missing file",+ status: "complete", createdAt: new Date().toISOString(),+ } });+ await host.call("session.appendMessage", { sessionId: plain.id, message: {+ id: randomUUID(), role: "assistant", content: "[Missing HTML](missing.html)",+ status: "complete", createdAt: new Date().toISOString(),+ } });+ outside = join(output, "outside.html");+ await writeFile(outside, html);+ for (const [label, content] of [+ ["Outside HTML", "[Outside HTML](<" + outside.replaceAll("\\", "/") + ">)"],+ ["Source line", "Source: Ordinary-scratch.html:1"],+ ]) {+ for (const [role, text] of [["user", "Inspect " + label], ["assistant", content]]) {+ await host.call("session.appendMessage", { sessionId: plain.id, message: {+ id: randomUUID(), role, content: text, status: "complete", createdAt: new Date().toISOString(),+ } });+ }+ }+} finally { await host.stop(); }++const env = { ...process.env, PI_DESKTOP_DATA_DIR: data, PI_DESKTOP_HOST_BIN: binary,+ PI_DESKTOP_MCP_CONTROL: "0", ELECTRON_RENDERER_URL: "", PI_DESKTOP_START_MAXIMIZED: "0" };+delete env.ELECTRON_RUN_AS_NODE;+const { appDir, electronBinary } = resolveElectronBinary(root);+const app = await _electron.launch({ executablePath: electronBinary,+ args: [appDir, "--user-data-dir=" + join(output, "profile")], env, timeout: 60_000 });+let page;+const results = [];+try {+ const ready = Date.now() + 60_000;+ do {+ for (const candidate of app.windows()) {+ if (await candidate.locator(".app-shell").count()) { page = candidate; break; }+ }+ if (page) break;+ await new Promise(resolve => setTimeout(resolve, 100));+ } while (Date.now() < ready);+ assert.ok(page, "main application window appears");+ page.setDefaultTimeout(25_000);+ await page.locator(".app-shell:not(.app-shell-boot)").waitFor();+ await app.evaluate(({ BrowserWindow }, url) =>+ BrowserWindow.getAllWindows().find(window => window.webContents.getURL() === url)+ ?.setTitle("PI HTML Link Regression QA"), page.url());+ for (const item of cases) {+ await page.evaluate(id => window.__PI_DESKTOP__.selectSession(id), item.sessionId);+ await page.getByRole("link", { name: item.label, exact: true }).click();+ const url = pathToFileURL(item.file).href;+ let guest;+ const deadline = Date.now() + 15_000;+ do {+ guest = await app.evaluate(({ webContents }, url) => webContents.getAllWebContents().find(wc => wc.getURL() === url)?.id, url);+ if (guest) break;+ await new Promise(resolve => setTimeout(resolve, 100));+ } while (Date.now() < deadline);+ assert.ok(guest, item.label + ": transcript click must create a real HTML guest");+ assert.equal(await app.evaluate(async ({ webContents, BrowserWindow }, id) => {+ const wc = webContents.fromId(id);+ const visibleGuest = views => views.some(view => view.getVisible() &&+ (view.webContents?.id === id || visibleGuest(view.children)));+ 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");+ }, guest), "Animation opened");+ const png = await app.evaluate(async ({ webContents }, id) =>+ (await webContents.fromId(id).capturePage()).toPNG().toString("base64"), guest);+ await writeFile(join(output, item.label.replaceAll(" ", "-") + ".png"), Buffer.from(png, "base64"));+ results.push(item.label);+ console.log("PASS " + item.label);+ }+ await page.evaluate(id => window.__PI_DESKTOP__.selectSession(id), cases[0].sessionId);+ await page.getByRole("link", { name: "Missing HTML", exact: true }).click();+ await page.getByText("No file matches missing.html", { exact: true }).waitFor();+ results.push("missing file reports its failure");+ await page.getByRole("link", { name: "Outside HTML", exact: true }).click();+ await page.getByText(/is outside the locations this app can access/).waitFor();+ 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");+ await page.getByText("Ordinary-scratch.html:1", { exact: true }).click();+ await page.locator(".file-viewer").waitFor();+ results.push("positioned HTML opens source, not execution");+ // 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]]) {+ await page.evaluate(id => window.__PI_DESKTOP__.selectSession(id), item.sessionId);+ model.preview(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");+ 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");+ 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");+ if (!result.ok) throw new Error(result.error.message);+ });+ await page.getByRole("link", { name: cases[0].label, exact: true }).click();+ await page.locator(".toast-message").filter({+ hasText: "This view could not be loaded. Reload the plugin and try again.",+ }).waitFor();+ results.push("disabled browser reports a visible error without auto-enabling");+ console.log("HTML_LINKS_RESULT " + JSON.stringify({ results, output }));+} catch (error) {+ if (page) await page.screenshot({ path: join(output, "failure.png") });+ console.error("HTML_LINKS_FAILED " + output);+ throw error;+} finally {+ await app.evaluate(() => { process.env.PI_DESKTOP_BOOT_PROBE = "1"; });+ await app.close();+ await model.close();+}