Skip to content

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

fix(desktop): open chat HTML artifacts in the owning session

AR307fa03ae1ecb81
diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.ts
index 1644dcd05..58a3c0fa1 100644
--- a/apps/desktop/electron/main/browser-host.ts
+++ b/apps/desktop/electron/main/browser-host.ts
@@ -59,7 +59,7 @@ export type BrowserHostDeps = {
createPane: (onState: (state: BrowserState) => void, onOpenUrl: (url: string) => void) => BrowserPane;
onOpenUrl?: (url: string, sessionId?: string) => void;
isPluginLoaded: (pluginId: string) => boolean;
- getFileRoot: (sessionId?: string) => Promise<string | null>;
+ getFileRoots: (sessionId?: string) => Promise<readonly string[]>;
getScratchDir?: (sessionId?: string) => string | null;
onState: (state: BrowserState) => void;
onRevealView?: (sessionId: string, tabId?: string) => void;
@@ -349,9 +349,9 @@ export class BrowserHost {
throw error;
}
};
- let root: string | null;
+ let roots: readonly string[];
try {
- root = await this.deps.getFileRoot(page.sessionId || undefined);
+ roots = await this.getFileRoots(page.sessionId || undefined);
} catch (error) {
if (!current()) return null;
assertVisible();
@@ -366,7 +366,7 @@ export class BrowserHost {
assertVisible();
let state: BrowserState | null;
try {
- state = await page.pane.navigateAndWait(target, root);
+ state = await page.pane.navigateAndWait(target, roots);
} catch (error) {
if (!current()) return null;
page.navigating = false;
@@ -460,7 +460,11 @@ export class BrowserHost {
}
/** The renderer-created resource tab is the preview's only navigation owner. */
- async previewWorkspaceFile(_sessionId: string, _path: string, _root: string): Promise<{ ok: true } | { ok: false; content: string }> {
+ getFileRoots(sessionId?: string): Promise<readonly string[]> {
+ return this.deps.getFileRoots(sessionId);
+ }
+
+ async previewFile(): Promise<{ ok: true } | { ok: false; content: string }> {
if (!this.deps.isPluginLoaded(BROWSER_PLUGIN_ID)) return {
ok: false, content: "BrowserPreview: the Browser plugin is disabled. Enable pi.browser in Plugins to preview HTML.",
};
diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.ts
index cc98c82d8..71652e383 100644
--- a/apps/desktop/electron/main/browser-view.ts
+++ b/apps/desktop/electron/main/browser-view.ts
@@ -14,7 +14,7 @@ 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
+ * Besides http(s) URLs, the pane renders HTML files inside session-owned roots
* (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.
*/
@@ -99,7 +99,7 @@ export class BrowserPane {
private capturing = false;
private captureTail: Promise<void> = Promise.resolve();
private onState: (state: BrowserState) => void;
- private fileRoot: string | null = null;
+ private fileRoots: readonly string[] = [];
private watcher: FSWatcher | null = null;
private watchedDir: string | null = null;
private reloadTimer: NodeJS.Timeout | null = null;
@@ -191,18 +191,19 @@ export class BrowserPane {
this.nativeNavigationPending = false;
}
- navigate(raw: string, fileRoot: string | null = null): BrowserState | null {
- void this.navigateAndWait(raw, fileRoot);
+ navigate(raw: string, fileRoots: string | readonly string[] | null = null): BrowserState | null {
+ void this.navigateAndWait(raw, fileRoots);
return this.getState();
}
async navigateAndWait(
raw: string,
- fileRoot: string | null = null,
+ fileRoots: string | readonly string[] | null = null,
timeoutMs = 15_000,
): Promise<BrowserState | null> {
- if (fileRoot) this.fileRoot = fileRoot;
- const localPath = resolveLocalFile(raw, this.fileRoot);
+ this.fileRoots = typeof fileRoots === "string" ? [fileRoots] : fileRoots ?? [];
+ const localPath = this.fileRoots.map((root) => resolveLocalFile(raw, root))
+ .find((path) => path !== null);
const localInput = /^file:/i.test(raw.trim()) || isAbsolute(raw.trim());
const target = localPath
? pathToFileURL(localPath).toString()
@@ -415,12 +416,7 @@ export class BrowserPane {
}
private isAllowedFileUrl(url: string): boolean {
- if (!this.fileRoot) return false;
- try {
- return isWithinRoot(resolve(fileURLToPath(url)), this.fileRoot);
- } catch {
- return false;
- }
+ return this.fileRoots.some((root) => resolveLocalFile(url, root) !== null);
}
private ensureView(): WebContentsView {
@@ -459,7 +455,7 @@ export class BrowserPane {
return;
}
// Relative links inside a previewed page may point at sibling files;
- // anything escaping the workspace root stays blocked.
+ // anything escaping the session's project/scratch roots stays blocked.
if (/^file:/i.test(url) && this.isAllowedFileUrl(url)) {
this.nativeNavigationPending = this.hasCurrentStateEventScope();
return;
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index 9edc060ae..e6b95f939 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -560,30 +560,25 @@ export function createSidecarRuntime({
content: "BrowserPreview: `path` is required.",
};
}
- let root: string | null = null;
+ let roots: readonly string[];
try {
- const res = (await runtimeState.host?.call("session.get", { id: sessionId })) as
- | { session: { projectPath?: string } | null }
- | undefined;
- root = res?.session?.projectPath?.trim() || null;
- } catch {
- root = null;
- }
- if (!root) {
+ roots = await browserHost.getFileRoots(sessionId);
+ } catch (error) {
return {
ok: false,
isError: true,
- content: "BrowserPreview: no workspace is open.",
+ content: `BrowserPreview: ${error instanceof Error ? error.message : String(error)}`,
};
}
- if (!resolveLocalFile(raw, root)) {
+ const file = roots.map((root) => resolveLocalFile(raw, root)).find((path) => path !== null);
+ if (!file) {
return {
ok: false,
isError: true,
- content: `BrowserPreview: "${raw}" does not resolve to an existing file inside the workspace.`,
+ content: `BrowserPreview: "${raw}" does not resolve to an existing file inside this session's project or scratch directory.`,
};
}
- const preview = await browserHost.previewWorkspaceFile(sessionId, raw, root);
+ const preview = await browserHost.previewFile();
if (!preview.ok) {
return {
ok: false,
@@ -593,7 +588,7 @@ export function createSidecarRuntime({
}
sendToRenderer(IPC.event.browserPreview, {
sessionId,
- path: raw,
+ path: file,
});
return {
ok: true,
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 95e8afbde..6a4eec405 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -31,7 +31,7 @@ import {
type RuntimeProviderConfig,
} from "@pi-desktop/agent-runtime";
import { createFsConsentService } from "../plugin-fs-consent";
-import { pluginWorkspaceInfo } from "../workspace-roots";
+import { pluginWorkspaceInfo, projectFolderPaths } from "../workspace-roots";
import { createDesktopConsentService } from "../plugin-desktop-consent";
import { PluginRuntime } from "../plugin-runtime";
import { createSpeechService } from "./speech-service";
@@ -601,19 +601,16 @@ 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.
- }
- }
- return getWorkspacePath();
+ getFileRoots: async (sessionId) => {
+ if (!sessionId) return projectFolderPaths(getWorkspacePath());
+ const res = await getHost()?.call<{ session: { projectPath?: string } | null }>(
+ "session.get", { id: sessionId },
+ );
+ if (!res?.session) throw new Error("Browser preview session is unavailable.");
+ return [
+ ...projectFolderPaths(res.session.projectPath?.trim() || null),
+ join(dataDir, "scratch", sessionId),
+ ];
},
getScratchDir: (sessionId) => {
if (!sessionId) 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 1fd611211..23c0b3443 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 files inside this session's project folders or scratch directory 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/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsx
index f97b6949f..e34ca6550 100644
--- a/apps/desktop/src/components/Markdown.tsx
+++ b/apps/desktop/src/components/Markdown.tsx
@@ -547,7 +547,9 @@ function InlineCode({
onClick={() => {
if (!localToolsAllowed) return;
if (target.kind === "file") {
- openFileRef(text ?? target.path, baseDir);
+ openFileRef(target.path, baseDir, undefined, {
+ line: target.line, column: target.column,
+ });
return;
}
if (target.kind === "session") {
diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.ts
index b1131e461..00b955486 100644
--- a/apps/desktop/src/hooks/use-preview-target.ts
+++ b/apps/desktop/src/hooks/use-preview-target.ts
@@ -9,6 +9,7 @@ import { api } from "../lib/api";
import { isHtmlFilePath, toWorkspaceRel, type ChatPreviewTarget } from "../lib/chat-links";
import { openHttpUrl } from "../lib/open-http-url";
import {
+ BROWSER_PLUGIN_TAB,
FILE_MANAGER_PLUGIN_TAB,
fileManagerPluginTab,
hasPluginView,
@@ -83,6 +84,8 @@ export type ResolvedChatFileRef = {
inProject: boolean;
/** True when that folder is the project's primary one. */
primary: boolean;
+ /** Session-owned generated artifacts, rather than imported attachments. */
+ scratch: boolean;
};
/**
@@ -191,6 +194,7 @@ function useResolveChatFileRef() {
relativePath: null,
inProject: false,
primary: false,
+ scratch: match.sessionScratch === true,
};
}
// A project group can hold several folders, and a relative path always
@@ -203,6 +207,7 @@ function useResolveChatFileRef() {
relativePath: match.relativePath,
inProject: true,
primary,
+ scratch: false,
};
},
[paneSessionId, sessionId, showToast, t, workspacePath],
@@ -212,14 +217,14 @@ function useResolveChatFileRef() {
/**
* Open a file reference the conversation mentioned.
*
- * A workspace `.html` page in the primary folder stays with the side browser
+ * A project or session-scratch `.html` page stays with the side browser
* (ADR 0163): it is a page to run, not a file to read. A direct click on a
* plain project file starts or retries the bundled file view; a positioned
* `path:line` reference uses the host file tab, which can scroll to the line.
* The plugin view accepts opaque path locations and has no line-navigation
* contract, so positioned references keep their path unchanged and use the
- * host viewer's existing scroll support. Scratch and attachment files also use
- * the host file tab.
+ * host viewer's existing scroll support. Other scratch and attachment files
+ * also use the host file tab.
*/
export function useOpenChatFileRef() {
const { t } = useTranslation();
@@ -246,7 +251,7 @@ export function useOpenChatFileRef() {
if (!resolved) return;
const current = useAppStore.getState();
if (
- current.workspace?.path !== workspacePath ||
+ (current.workspace?.path ?? null) !== workspacePath ||
current.activeSessionId !== sessionId
) {
return;
@@ -255,19 +260,21 @@ export function useOpenChatFileRef() {
if (
!current.workspace?.remote &&
!hasPosition &&
- resolved.inProject &&
- resolved.primary &&
- resolved.relativePath &&
- isHtmlFilePath(resolved.relativePath)
+ (resolved.inProject || resolved.scratch) &&
+ isHtmlFilePath(resolved.absolutePath)
) {
- openUrl(resolved.relativePath);
+ if (!hasPluginView(current.pluginViews, BROWSER_PLUGIN_TAB)) {
+ showToast(t("panel.pluginView.failed"), { variant: "error" });
+ return;
+ }
+ openUrl(resolved.absolutePath);
return;
}
if (!current.workspace?.remote && resolved.inProject && !hasPosition) {
if (await ensureFileManagerView(workspacePath)) {
const latest = useAppStore.getState();
if (
- latest.workspace?.path !== workspacePath ||
+ (latest.workspace?.path ?? null) !== workspacePath ||
latest.activeSessionId !== sessionId
) {
return;
@@ -277,7 +284,7 @@ export function useOpenChatFileRef() {
}
const latest = useAppStore.getState();
if (
- latest.workspace?.path !== workspacePath ||
+ (latest.workspace?.path ?? null) !== workspacePath ||
latest.activeSessionId !== sessionId
) {
return;
diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.ts
index 26f31ac38..7e89f4f5c 100644
--- a/apps/desktop/src/lib/chat-links.ts
+++ b/apps/desktop/src/lib/chat-links.ts
@@ -101,14 +101,30 @@ function encodeWindowsPathForHref(path: string): string {
: path;
}
-function normalizeMarkdownWindowsPath(url: string): string {
+function normalizeMarkdownFilePath(url: string): string {
+ // Convert file URLs to references before sanitization, never native links.
+ // Main still verifies the resulting path against its allowed roots.
+ if (/^file:/i.test(url)) {
+ try {
+ const file = new URL(url);
+ if (file.hostname && file.hostname !== "localhost") return url;
+ if (file.search || file.hash) return url;
+ const pathname = decodeURIComponent(file.pathname);
+ const path = /^\/[A-Za-z]:\//.test(pathname) ? pathname.slice(1) : pathname;
+ const filePath = parseFileRefPosition(path) ? stripLineRef(path) : path;
+ if (!isAbsoluteFilePath(filePath) || !isLikelyFilePath(filePath)) return url;
+ return encodeURIComponent(path);
+ } catch {
+ return url;
+ }
+ }
// Keep a drive letter from being interpreted as a URI scheme by the
// renderer and sanitizer; the anchor decodes this back before file lookup.
const decoded = safeDecodeUri(url);
+ if (parseFileRef(decoded) && parseFileRefPosition(decoded)) return encodeURIComponent(decoded);
if (!/^[A-Za-z]:[\\/]/.test(decoded)) return url;
- const path = parseFileRef(decoded);
- if (path !== decoded) return url;
- return encodeWindowsPathForHref(path);
+ if (!parseFileRef(decoded)) return url;
+ return encodeWindowsPathForHref(decoded);
}
/**
@@ -227,6 +243,12 @@ export type ChatPreviewTarget =
| { kind: "url"; url: string }
| { kind: "session"; sessionId: string };
+function fileTargetHref(target: Extract<ChatPreviewTarget, { kind: "file" }>): string {
+ const position = target.line === undefined ? ""
+ : ":" + target.line + (target.column === undefined ? "" : ":" + target.column);
+ return position ? encodeURIComponent(target.path + position) : encodeWindowsPathForHref(target.path);
+}
+
/** Resolve one raw chat token into a previewable target, or null. */
export function resolvePreviewTarget(
text: string,
@@ -263,14 +285,19 @@ export function handleMarkdownFileLinkClick(
href: string,
root: string | null | undefined,
baseDir: string | undefined,
- openFileRef: (path: string, baseDir?: string) => void,
+ openFileRef: (path: string, baseDir?: string, mimeType?: string,
+ position?: { line?: number; column?: number }) => void,
): boolean {
const decoded = safeDecodeUri(href);
const target = resolvePreviewTarget(decoded, root, baseDir);
const ref = target?.kind === "file" ? target.path : toWorkspaceRel(decoded, root, baseDir);
if (!ref) return false;
event.preventDefault();
- openFileRef(ref, baseDir);
+ if (target?.kind === "file" && target.line !== undefined) {
+ openFileRef(ref, baseDir, undefined, { line: target.line, column: target.column });
+ } else {
+ openFileRef(ref, baseDir);
+ }
return true;
}
@@ -416,7 +443,7 @@ const SKIP_MDAST = new Set([
function normalizeMarkdownLinkDestination(node: MdastNode): void {
if ((node.type === "link" || node.type === "definition") && typeof node.url === "string") {
- node.url = normalizeMarkdownWindowsPath(node.url);
+ node.url = normalizeMarkdownFilePath(node.url);
}
}
@@ -489,7 +516,7 @@ export function linkifyMdastTree(
? target.url
: target.kind === "session"
? formatSessionLink(target.sessionId)
- : encodeWindowsPathForHref(target.path);
+ : fileTargetHref(target);
next.push({
type: "link",
url,
@@ -514,7 +541,7 @@ export function linkifyMdastTree(
? segment.target.url
: segment.target.kind === "session"
? formatSessionLink(segment.target.sessionId)
- : encodeWindowsPathForHref(segment.target.path);
+ : fileTargetHref(segment.target);
next.push({
type: "link",
url,
diff --git a/apps/desktop/test/browser-capture-resize.test.mjs b/apps/desktop/test/browser-capture-resize.test.mjs
index d0fd1e44d..fc0df01af 100644
--- a/apps/desktop/test/browser-capture-resize.test.mjs
+++ b/apps/desktop/test/browser-capture-resize.test.mjs
@@ -87,7 +87,7 @@ const { WebContentsView } = await import("electron");
async function harness(t) {
const host = new BrowserHost({
createPane: (onState, onOpenUrl) => new BrowserPane(onState, onOpenUrl),
- isPluginLoaded: () => true, getFileRoot: async () => null, onState: () => {},
+ isPluginLoaded: () => true, getFileRoots: async () => [], onState: () => {},
});
const children = [];
host.setWindow({ isDestroyed: () => false, contentView: {
diff --git a/apps/desktop/test/browser-host-session.test.mjs b/apps/desktop/test/browser-host-session.test.mjs
index 875c28e13..a4a715af3 100644
--- a/apps/desktop/test/browser-host-session.test.mjs
+++ b/apps/desktop/test/browser-host-session.test.mjs
@@ -20,9 +20,9 @@ function harness() {
setVisible(value) { this.visible = value; },
getState: () => state, getWebContents: () => null,
invalidateNavigation: () => {},
- navigateAndWait(target) {
+ navigateAndWait(target, fileRoots) {
const done = deferred();
- loads.push({ target, pane, finish() {
+ loads.push({ target, fileRoots, pane, finish() {
state = { url: target, title: target, isLoading: false, canGoBack: false, canGoForward: false };
onState(state); done.resolve(state);
}, fail: () => done.resolve(null) });
@@ -35,8 +35,9 @@ function harness() {
};
const host = new BrowserHost({
createPane, isPluginLoaded: () => true,
- getFileRoot(sessionId) {
- const done = deferred(); roots.push({ sessionId, ...done }); return done.promise;
+ getFileRoots(sessionId) {
+ const done = deferred(); roots.push({ sessionId, ...done });
+ return done.promise.then(root => root ? [root, "/scratch/" + sessionId] : ["/scratch/" + sessionId]);
},
onState: (state) => published.push(state),
onRevealView: (sessionId, tabId) => reveals.push({ sessionId, tabId }),
@@ -57,7 +58,7 @@ async function open(h, sessionId, tabId, url) {
test("BrowserPreview prepares a new resource tab without navigating or rewriting the current tab", async () => {
const h = harness(); await open(h, "A", "one", "A.html");
- const preview = h.host.previewWorkspaceFile("A", "preview.html", "/projects/A");
+ const preview = h.host.previewFile();
await settled();
assert.equal(h.loads.length, 1, "preview must wait for the resource-tab owner");
assert.equal(h.host.getState().url, "A.html");
@@ -103,6 +104,21 @@ test("background navigation targets that session's last selected tab", async ()
assert.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"]);
+ 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 --git a/apps/desktop/test/browser-local-file-feedback.test.mjs b/apps/desktop/test/browser-local-file-feedback.test.mjs
index f77779274..3513c395a 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 files inside this session's project folders or scratch directory 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.mjs
index 766e75c9a..51c121661 100644
--- a/apps/desktop/test/browser-pane-navigation.test.mjs
+++ b/apps/desktop/test/browser-pane-navigation.test.mjs
@@ -183,6 +183,31 @@ test("a denied local file on a blank tab publishes an error without creating a g
});
});
+test("temporary and secondary-root HTML previews use the supplied roots without retaining old scope", async (t) => {
+ const temp = mkdtempSync(join(tmpdir(), "pi-browser-artifacts-"));
+ const primary = join(temp, "primary"), secondary = join(temp, "secondary"), scratch = join(temp, "scratch");
+ for (const root of [primary, secondary, scratch]) {
+ mkdirSync(root);
+ writeFileSync(join(root, "animation.html"), "<button>Run animation</button>");
+ }
+ const pane = new BrowserPane(() => {});
+ t.after(() => { pane.dispose(); rmSync(temp, { recursive: true }); });
+ for (const [file, roots] of [
+ [join(scratch, "animation.html"), [scratch]],
+ [join(secondary, "animation.html"), [primary, secondary, scratch]],
+ ]) {
+ const loading = pane.navigateAndWait(file, roots);
+ const wc = pane.getWebContents();
+ assert.ok(wc, "an allowed HTML artifact creates the native preview");
+ wc.url = pathToFileURL(realpathSync(file)).href;
+ assert.equal(wc.pendingLoads.at(-1).url, wc.url);
+ wc.pendingLoads.shift().resolve();
+ assert.equal((await loading).url, wc.url);
+ }
+ assert.equal(await pane.navigateAndWait(join(scratch, "animation.html"), []), null);
+ assert.equal(pane.getState().loadError, "LOCAL_FILE_NOT_ALLOWED");
+});
+
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/apps/desktop/test/browser-preview-tool.test.mjs b/apps/desktop/test/browser-preview-tool.test.mjs
index 18584b58f..86b044083 100644
--- a/apps/desktop/test/browser-preview-tool.test.mjs
+++ b/apps/desktop/test/browser-preview-tool.test.mjs
@@ -53,10 +53,9 @@ test("main serves BrowserPreview from its originating session workspace", () =>
mainSource.indexOf("sidecar = s;"),
);
assert.match(handler, /async \(\{ args, sessionId \}\)/);
- assert.match(handler, /host\?\.call\("session\.get", \{ id: sessionId \}\)/);
- assert.match(handler, /res\?\.session\?\.projectPath/);
+ assert.match(handler, /browserHost\.getFileRoots\(sessionId\)/);
assert.doesNotMatch(handler, /workspace\.get/);
- assert.match(handler, /browserHost\.previewWorkspaceFile\(sessionId, raw, root\)/);
+ assert.match(handler, /browserHost\.previewFile\(\)/);
assert.ok(
handler.indexOf("resolveLocalFile(raw, root)") <
handler.indexOf("sendToRenderer(IPC.event.browserPreview"),
@@ -64,7 +63,7 @@ test("main serves BrowserPreview from its originating session workspace", () =>
assert.doesNotMatch(handler, /browserPane\.navigate/);
assert.match(
handler,
- /sendToRenderer\(IPC\.event\.browserPreview, \{\s*sessionId,\s*path: raw,\s*\}\)/,
+ /sendToRenderer\(IPC\.event\.browserPreview, \{\s*sessionId,\s*path: file,\s*\}\)/,
);
assert.match(protocolSource, /browserPreview: "pi-desktop\/browser\/event\/preview"/);
});
diff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjs
index de23dea29..3f6ab9dbb 100644
--- a/apps/desktop/test/chat-links.test.mjs
+++ b/apps/desktop/test/chat-links.test.mjs
@@ -97,6 +97,36 @@ test("Windows Markdown file links survive parsing and sanitization without chang
assertMarkdownLinkClick(encodedSlashMarkup, "D:/person/dir name/报告.js");
});
+test("positioned HTML references preserve source navigation through Markdown sanitization", () => {
+ for (const source of [
+ "Source: animation.html:12:3",
+ "`animation.html:12:3`",
+ "[Source](animation.html:12:3)",
+ "[Source](<D:/person/animation.html:12:3>)",
+ ]) {
+ const markup = renderSanitizedMarkdown(source);
+ const href = markup.match(/<a href="([^"]+)"/)?.[1];
+ assert.ok(href, source);
+ const calls = [];
+ handleMarkdownFileLinkClick({ preventDefault() {} }, href, "D:/person", undefined,
+ (...args) => calls.push(args));
+ assert.deepEqual(calls, [[source.includes("D:/person") ? "D:/person/animation.html" : "animation.html",
+ undefined, undefined, { line: 12, column: 3 }]], source);
+ }
+});
+
+test("file URL links survive sanitization only as references for main-process resolution", () => {
+ for (const [url, path] of [
+ ["file:///C:/scratch/animation.html", "C:/scratch/animation.html"],
+ ["file:///tmp/my%20animation.html", "/tmp/my animation.html"],
+ ["file:///C:/scratch/%E9%B9%88%E9%B9%95.html", "C:/scratch/鹈鹕.html"],
+ ]) {
+ const markup = renderSanitizedMarkdown("[Open animation](<" + url + ">)");
+ assertMarkdownLinkClick(markup, path);
+ assert.doesNotMatch(markup, /href="file:/i);
+ }
+});
+
test("Markdown link normalization leaves web, relative, automatic, and unsafe links alone", () => {
const httpMarkup = renderSanitizedMarkdown("[web](https://example.com/a%20b)");
assert.match(httpMarkup, /href="https:\/\/example\.com\/a%20b"/);
@@ -111,7 +141,8 @@ test("Markdown link normalization leaves web, relative, automatic, and unsafe li
for (const destination of [
"javascript:alert%281%29",
"data:text/html,unsafe",
- "file:///C:/secret.txt",
+ "file://other-host/secret.txt",
+ "file:///tmp/page.html?redirect=1",
"ms-msdt:/diagnostics",
"custom:payload",
]) {
diff --git a/apps/desktop/test/chat-ref-resolve.test.mjs b/apps/desktop/test/chat-ref-resolve.test.mjs
index 9847657ad..9fe164405 100644
--- a/apps/desktop/test/chat-ref-resolve.test.mjs
+++ b/apps/desktop/test/chat-ref-resolve.test.mjs
@@ -397,6 +397,11 @@ test("an absolute path in the wider store opens though another session wrote it"
assert.equal(match?.root, "scratch");
assert.equal(match?.matchedBy, "exact-absolute");
assert.equal(match?.absolutePath, image);
+ assert.notEqual(match?.sessionScratch, true, "a readable foreign artifact is not executable session scratch");
+ const own = join(scratch, "animation.html");
+ writeFileSync(own, "<h1>Own artifact</h1>");
+ assert.equal((await resolve(own, { scratch, containment }))?.sessionScratch, true);
+ assert.equal((await resolve("animation.html", { scratch, containment }))?.sessionScratch, true);
});
test("a shorthand still searches the session's own store and not the wider one", async () => {
diff --git a/apps/desktop/test/transcript-file-chips.test.mjs b/apps/desktop/test/transcript-file-chips.test.mjs
index 223c72992..c9e551f50 100644
--- a/apps/desktop/test/transcript-file-chips.test.mjs
+++ b/apps/desktop/test/transcript-file-chips.test.mjs
@@ -50,11 +50,10 @@ test("a file chip is routed by where the reference resolved, never optimisticall
// for its siblings, and the file view switches to the folder it is given.
assert.match(hook, /match\.projectRoot \? match\.projectRoot\.primary : true/);
assert.match(hook, /path: primary \? match\.relativePath : match\.absolutePath/);
- // A workspace HTML page is a page to run, not a file to read (ADR 0163), and
- // only the primary folder has a workspace-relative address for the browser.
- assert.match(hook, /resolved\.primary &&/);
- assert.match(hook, /isHtmlFilePath\(resolved\.relativePath\)/);
- assert.match(hook, /openUrl\(resolved\.relativePath\)/);
+ // Project and scratch HTML run at the exact path resolved by main.
+ assert.match(hook, /resolved\.inProject \|\| resolved\.scratch/);
+ assert.match(hook, /isHtmlFilePath\(resolved\.absolutePath\)/);
+ assert.match(hook, /openUrl\(resolved\.absolutePath\)/);
// Plain project files prefer the bundled file view. A path:line reference
// uses the host file tab because the bundled view has no line-navigation API.
assert.match(hook, /FILE_MANAGER_PLUGIN_TAB/);
diff --git a/docs/adr/0262-chat-file-refs-open-in-the-file-view.md b/docs/adr/0262-chat-file-refs-open-in-the-file-view.md
index f94bae795..3369e5893 100644
--- a/docs/adr/0262-chat-file-refs-open-in-the-file-view.md
+++ b/docs/adr/0262-chat-file-refs-open-in-the-file-view.md
@@ -55,9 +55,15 @@ work-panel tab already carries was honoured by main for `pi.browser` only.
host viewer's existing scroll support. A file in the session scratch or
attachment store opens in the
host `file:` tab, because it lives outside that view's project root — see
- point 4. A workspace `.html` / `.htm` file still opens in the side browser
+ point 4. An unpositioned `.html` / `.htm` file in any folder of the
+ session's project group or its own scratch directory opens in the side browser
(ADR 0163), for an agent reply and a user chip alike: it is a page to run,
- not a file to read. A direct user click on a project file actively ensures
+ not a file to read. Main resolves browser roots from the owning session,
+ never a different visible project's root. The resolved absolute path is
+ carried through navigation, and realpath containment still applies.
+ Positioned HTML references retain the source viewer. A disabled browser
+ reports an error instead of silently dropping a click or enabling itself.
+ A direct user click on a project file actively ensures
the bundled file view is running: an off plugin is enabled, and an enabled
plugin with no contributed view is reloaded before the tab opens. This click
is explicit intent to use the bundled view. The host does not restore a
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index ee14880fc..0cfa1a772 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1809,9 +1809,15 @@ Command sources:
Work panel channels are Electron-main implementations. User-driven workspace
operations resolve the visible root from `workspace.get` and fail closed
-without one. Agent-driven BrowserPreview routing resolves the originating
-conversation through `session.get`, so a background preview never inherits the
-visible session's workspace.
+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.
### workspace
@@ -1873,6 +1879,8 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:
- `fs/resolveRef({ref, sessionId?})` → `FsChatRefResolveResult`
(`{ match: FsChatRefMatch | null, reason?: "outside-allowed-roots" }`, the match naming the answering `root`
(`workspace` / `scratch` / `attachments`), the `relativePath` relative to that
+ root, 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` /
`exact-absolute` / `path-suffix` / `basename`), and — for a `workspace` match
— `projectRoot` (`{ path, name, primary }`), which names the project folder
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 9b65c6f23..218d815c6 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -1336,8 +1336,16 @@ Project drag/drop follows these patterns:
(ADR 0263) — and then opens where it resolved: a project file in the bundled
`pi.file-manager` work-panel view (the host `file:` tab when that view is not
available), a session-scratch or attachment file in the host `file:` tab, and
- a `.html`/`.htm` page of the project's primary folder in the side browser,
- because the side browser is rooted at that folder. The address handed to
+ an unpositioned `.html`/`.htm` page from any project folder or the current
+ session's scratch directory in the side browser. HTML navigation uses the
+ resolved absolute path; the browser validates the owning session's roots.
+ No project is required to open a scratch artifact. Missing workspace state
+ is normalized consistently across asynchronous session-change guards.
+ Local `file:` Markdown URLs are converted to file references before
+ sanitization, not admitted as native links. `path:line[:column]` retains
+ source navigation in plain text, inline code and Markdown links, including
+ HTML; unavailable browser views report an error without auto-enabling.
+ The address handed to
the work panel follows the folder that answered: a file of the primary folder
travels as a project-relative path, a file of a sibling folder of the same
project as an absolute one, exactly as a scratch or attachment file does. A
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index e9d68a16e..e06c20fbf 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -4524,13 +4524,34 @@ window; opening a normal panel afterward must still work.
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.
+ 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
- **Acceptance**: Quality, Security
- **Milestone**: M5
- **Status**: Draft (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 page
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 8d5311fa5..f7b6d08b2 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -3156,7 +3156,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
if (scheduledToolDescriptions[toolName]) return scheduledToolDescriptions[toolName];
switch (toolName) {
case "BrowserPreview":
- return "Open a workspace HTML file in PI-Desktop's built-in browser panel. `path` is workspace-relative (e.g. \"demo/index.html\"). The preview live-reloads on later edits to the file or its sibling assets, so call once per page.";
+ return "Open an HTML file in PI-Desktop's built-in browser panel. `path` may be relative to a project folder or this session's scratch directory, or an absolute path inside those roots. No project is required for scratch previews. The preview live-reloads on later edits to the file or its sibling assets, so call once per page.";
case "Read":
return (
"Read a bounded window from an existing regular text file, never a directory. " +
@@ -3222,7 +3222,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
),
},
BrowserPreview: {
- path: pathParam("File to preview; workspace-relative."),
+ path: pathParam("File to preview inside the session's project folders or scratch directory."),
file_path: aliasParam("path"),
},
Glob: {
diff --git a/packages/host-runtime/src/chat-ref-resolve.ts b/packages/host-runtime/src/chat-ref-resolve.ts
index eb069c7c6..9803053eb 100644
--- a/packages/host-runtime/src/chat-ref-resolve.ts
+++ b/packages/host-runtime/src/chat-ref-resolve.ts
@@ -61,6 +61,7 @@ export type ChatRefContainmentRoot = { kind: FsChatRefRoot; path: string };
type ChatRefRootEntry = {
kind: FsChatRefRoot;
path: string;
+ sessionScratch?: boolean;
projectRoot?: FsChatRefProjectRoot;
};
@@ -158,7 +159,7 @@ function orderedRoots(roots: ChatRefRoots): ChatRefRootEntry[] {
for (const kind of ["scratch", "attachments"] as const) {
const value = roots[kind];
if (typeof value !== "string" || !value.trim()) continue;
- list.push({ kind, path: resolve(value) });
+ list.push({ kind, path: resolve(value), ...(kind === "scratch" ? { sessionScratch: true } : {}) });
}
return list;
}
@@ -408,6 +409,7 @@ export async function resolveChatFileRef(
relativePath,
absolutePath,
matchedBy: "exact-absolute",
+ ...(root.sessionScratch ? { sessionScratch: true } : {}),
...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
};
}
@@ -456,6 +458,7 @@ export async function resolveChatFileRef(
relativePath: parsed.segments.join("/"),
absolutePath,
matchedBy: "exact-relative",
+ ...(root.sessionScratch ? { sessionScratch: true } : {}),
...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
};
}
@@ -471,6 +474,7 @@ export async function resolveChatFileRef(
relativePath: candidate.relativePath,
absolutePath: join(root.path, ...segmentsOf(candidate.relativePath)),
matchedBy: candidate.matchedBy,
+ ...(root.sessionScratch ? { sessionScratch: true } : {}),
...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
};
}
diff --git a/packages/shared/src/types/filesystem.ts b/packages/shared/src/types/filesystem.ts
index 6bbf03e8a..4d66474a4 100644
--- a/packages/shared/src/types/filesystem.ts
+++ b/packages/shared/src/types/filesystem.ts
@@ -113,6 +113,8 @@ export type FsChatRefMatchKind =
export type FsChatRefMatch = {
root: FsChatRefRoot;
+ /** The match belongs to this session's scratch, not the wider read-only store. */
+ sessionScratch?: boolean;
/** POSIX path relative to the matched root. */
relativePath: string;
/** Native absolute path of the matched regular file. */
diff --git a/scripts/e2e-chat-html-artifacts.mjs b/scripts/e2e-chat-html-artifacts.mjs
new file mode 100644
index 000000000..2ed84d1a0
--- /dev/null
+++ b/scripts/e2e-chat-html-artifacts.mjs
@@ -0,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.
+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();
+}
diff --git a/scripts/e2e/browser-capture-resize.ts b/scripts/e2e/browser-capture-resize.ts
index 3b2bd18bc..583093f9b 100644
--- a/scripts/e2e/browser-capture-resize.ts
+++ b/scripts/e2e/browser-capture-resize.ts
@@ -39,7 +39,7 @@ async function probe(artifactDir: string) {
panes.push(pane);
return pane;
},
- isPluginLoaded: () => true, getFileRoot: async () => null, onState: () => {},
+ isPluginLoaded: () => true, getFileRoots: async () => [], onState: () => {},
});
try {
await window.loadURL(`data:text/html,${encodeURIComponent(`<!doctype html>
diff --git a/scripts/e2e/html-preview-model.mjs b/scripts/e2e/html-preview-model.mjs
new file mode 100644
index 000000000..5ffdca938
--- /dev/null
+++ b/scripts/e2e/html-preview-model.mjs
@@ -0,0 +1,67 @@
+// Only the provider boundary is synthetic; the app executes the real tool.
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import { once } from "node:events";
+
+export async function startHtmlPreviewModel() {
+ let path, pending, completed = false, calls = 0;
+ const failures = [];
+ const server = createServer(async (req, res) => {
+ try {
+ if (req.method === "GET" && req.url.endsWith("/models")) {
+ res.setHeader("content-type", "application/json");
+ res.end(JSON.stringify({ data: [{ id: "html-fixture", object: "model" }] }));
+ return;
+ }
+ const chunks = [];
+ for await (const chunk of req) chunks.push(chunk);
+ const request = JSON.parse(Buffer.concat(chunks).toString());
+ if (pending) {
+ const result = request.messages.find(message =>
+ message.role === "tool" && message.tool_call_id === pending.id);
+ assert.ok(result, "the real tool returns its result to the provider");
+ if (pending.name === "BrowserPreview") {
+ const content = typeof result.content === "string" ? result.content
+ : result.content.map(part => part.text ?? "").join("");
+ assert.match(content, /Requested a new Browser tab/);
+ completed = true;
+ }
+ pending = undefined;
+ }
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const base = { id: "html-" + ++calls, object: "chat.completion.chunk", created: 1, model: request.model };
+ const emit = (delta, finish_reason = null) => res.write("data: " + JSON.stringify({
+ ...base, choices: [{ index: 0, delta, finish_reason }],
+ }) + "\n\n");
+ if (completed) {
+ emit({ role: "assistant", content: "HTML preview tool completed." });
+ emit({}, "stop");
+ } else {
+ const available = request.tools?.some(tool => tool.function?.name === "BrowserPreview");
+ const name = available ? "BrowserPreview" : "ToolSearch";
+ assert.ok(request.tools?.some(tool => tool.function?.name === name), name + " is available");
+ pending = { id: "html-tool-" + calls, name };
+ emit({ role: "assistant", tool_calls: [{ index: 0, id: pending.id, type: "function",
+ function: { name, arguments: JSON.stringify(available ? { path } : { query: "BrowserPreview" }) },
+ }] });
+ emit({}, "tool_calls");
+ }
+ res.end("data: [DONE]\n\n");
+ } catch (error) {
+ failures.push(String(error));
+ if (!res.headersSent) res.writeHead(400);
+ res.end("HTML fixture failed");
+ }
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ return {
+ baseUrl: "http://127.0.0.1:" + server.address().port + "/v1",
+ failures,
+ preview(file) { path = file; pending = undefined; completed = false; },
+ close: () => new Promise((resolve, reject) => {
+ server.close(error => error ? reject(error) : resolve());
+ server.closeAllConnections();
+ }),
+ };
+}