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(gen-ui): harden contained roots and native fragment serving
vastsa4970dfa9073e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 57e59157b..d48eb8d76 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -109,12 +109,18 @@ jobs:- name: Test transcript module on Windowsrun: "cargo test -p host-core --locked transcripts::"+ - name: Test visualization paths and lifecycle on Windows+ run: cargo test -p host-core --locked visualization+- name: Build host-corerun: cargo build -p host-core --locked- name: Build Host RPC helper dependencyrun: pnpm --filter @pi-desktop/shared build+ - name: Test GenUI document file boundaries on Windows+ run: node --test apps/desktop/test/gen-ui-file-safety.test.mjs+- name: Run transcript cache Host RPC E2Erun: node scripts/e2e-transcript-cache.mjs@@ -159,6 +165,12 @@ jobs:- name: Build Desktop bundlerun: pnpm --filter @pi-desktop/desktop build+ - name: Build host-core+ run: cargo build -p host-core --locked++ - name: Run inline GenUI interaction and isolation E2E+ run: xvfb-run --auto-servernum pnpm test:e2e:gen-ui+- name: Run provider optional client certificate E2Erun: xvfb-run --auto-servernum pnpm test:e2e:provider-client-certificate@@ -168,9 +180,6 @@ jobs:- name: Run transcript rendering and disclosure E2Erun: xvfb-run --auto-servernum sh -c 'node scripts/e2e-transcript-render.mjs && node scripts/e2e-transcript-disclosure-anchor.mjs'- - name: Build host-core- run: cargo build -p host-core --locked-- name: Run trusted extensions E2Eenv:DEBUG_E2E: "1"diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.tsindex 5a9ce24bf..5049da9b4 100644--- a/apps/desktop/electron/main/bootstrap/startup.ts+++ b/apps/desktop/electron/main/bootstrap/startup.ts@@ -200,7 +200,7 @@ export function registerApplicationStartup(deps: StartupDependencies): void {installPluginRendererProtocol((pluginId, generation, requestPath) =>plugins.resolveRendererSource(pluginId, generation, requestPath),);- installGenUiProtocol({ getDataDir: () => dataDir });+ installGenUiProtocol({ getHost });// Load the close-behavior preference before the first window exists: the// close handler reads `closeBehavior` synchronously, and a window created// while it still held the "ask" default would prompt a user who alreadydiff --git a/apps/desktop/electron/main/gen-ui-document.ts b/apps/desktop/electron/main/gen-ui-document.tsindex c5374104c..934084bd7 100644--- a/apps/desktop/electron/main/gen-ui-document.ts+++ b/apps/desktop/electron/main/gen-ui-document.ts@@ -67,7 +67,10 @@ export const GEN_UI_PERMISSIONS_POLICY = [export function genUiResponseHeaders(): Record<string, string> {return {"content-type": "text/html; charset=utf-8",- "content-security-policy": GEN_UI_CONTENT_SECURITY_POLICY,+ // Response-level sandbox also protects callers that omit iframe sandbox.+ // Unlike the fetch restrictions, this forces a distinct opaque origin.+ // CSP sandbox is not supported in meta elements, so keep it header-only.+ "content-security-policy": `${GEN_UI_CONTENT_SECURITY_POLICY}; sandbox allow-scripts`,"permissions-policy": GEN_UI_PERMISSIONS_POLICY,"x-content-type-options": "nosniff","cache-control": "no-store",diff --git a/apps/desktop/electron/main/gen-ui-files.ts b/apps/desktop/electron/main/gen-ui-files.tsnew file mode 100644index 000000000..3767493f8--- /dev/null+++ b/apps/desktop/electron/main/gen-ui-files.ts@@ -0,0 +1,53 @@+import {+ GEN_UI_MAX_FRAGMENT_BYTES,+ isGenUiFileName,+ isGenUiFragmentReadResult,+ isGenUiSessionId,+ type GenUiLocation,+} from "@pi-desktop/shared";++export type GenUiFragmentResult =+ | { ok: true; fragment: string }+ | { ok: false; status: 404 | 413 | 500; code: "not-found" | "too-large" | "runtime-unavailable" };+export type GenUiFragmentReader = (location: GenUiLocation) => Promise<GenUiFragmentResult>;+export type GenUiFragmentHost = {+ call(method: "visualizations.readFragment", params: GenUiLocation, timeoutMs?: number): Promise<unknown>;+};++const NOT_FOUND = { ok: false, status: 404, code: "not-found" } as const;+const TOO_LARGE = { ok: false, status: 413, code: "too-large" } as const;+const UNAVAILABLE = { ok: false, status: 500, code: "runtime-unavailable" } as const;++/**+ * Main never resolves or opens model-written paths. Host Core pins native+ * directory handles and returns only bounded bytes for a validated identity.+ * Resolve the active Host per request so restart and profile relocation do not+ * retain a stale process. This RPC is not exposed through renderer IPC.+ */+export function createGenUiFragmentReader(getHost: () => GenUiFragmentHost | null): GenUiFragmentReader {+ return async (location) => {+ if (!isGenUiSessionId(location.sessionId) || !isGenUiFileName(location.fileName)) return NOT_FOUND;+ const host = getHost();+ if (!host) return UNAVAILABLE;+ try {+ const result = await host.call("visualizations.readFragment", location, 5_000);+ if (!isGenUiFragmentReadResult(result)) {+ console.warn("[gen-ui] invalid native fragment response");+ return UNAVAILABLE;+ }+ if (!result.ok) return result.code === "too-large" ? TOO_LARGE : NOT_FOUND;+ const bytes = Buffer.from(result.base64, "base64");+ if (bytes.length > GEN_UI_MAX_FRAGMENT_BYTES) return TOO_LARGE;+ if (bytes.toString("base64") !== result.base64) {+ console.warn("[gen-ui] non-canonical native fragment encoding");+ return UNAVAILABLE;+ }+ return { ok: true, fragment: bytes.toString("utf8") };+ } catch {+ // Preserve a diagnosable fixed failure without logging filesystem paths+ // or fragment bytes from a transport exception.+ console.warn("[gen-ui] native fragment read failed");+ return UNAVAILABLE;+ }+ };+}diff --git a/apps/desktop/electron/main/gen-ui-protocol.ts b/apps/desktop/electron/main/gen-ui-protocol.tsindex 70158aed3..8d15734d1 100644--- a/apps/desktop/electron/main/gen-ui-protocol.ts+++ b/apps/desktop/electron/main/gen-ui-protocol.ts@@ -1,10 +1,6 @@import { protocol, type CustomScheme } from "electron";-import { constants as fsConstants } from "node:fs";-import { lstat, open, readFile, realpath } from "node:fs/promises";-import { join, relative, isAbsolute } from "node:path";+import { readFile } from "node:fs/promises";import {- GEN_UI_DIRECTORY_NAME,- GEN_UI_MAX_FRAGMENT_BYTES,GEN_UI_SCHEME,genUiLocationFromUrl,type GenUiErrorCode,@@ -16,6 +12,7 @@ import {genUiResponseHeaders,isFullHtmlDocument,} from "./gen-ui-document";+import { createGenUiFragmentReader, type GenUiFragmentHost, type GenUiFragmentReader } from "./gen-ui-files";/*** Serve model-written visualization fragments to transcript cards@@ -51,20 +48,15 @@ export type GenUiResolveResult =const NOT_FOUND = { ok: false, status: 404, code: "not-found" } as const;-function isInside(root: string, candidate: string): boolean {- const rel = relative(root, candidate);- return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));-}-/**- * Resolve one request to a shell document or a safe error. Pure apart from- * filesystem reads, so it is tested without Electron. Errors carry a fixed+ * Resolve one request through the native reader and build its shell. The+ * dependency boundary is tested without Electron. Errors carry a fixed* code the card localizes; they never echo a path.*/export async function resolveGenUiRequest(input: {method: string;url: string;- dataDir: string;+ readFragment: GenUiFragmentReader;loadKit: () => Promise<GenUiKit>;}): Promise<GenUiResolveResult> {if (input.method !== "GET") {@@ -73,61 +65,11 @@ export async function resolveGenUiRequest(input: {const location = genUiLocationFromUrl(input.url);if (!location) return NOT_FOUND;- const visualizationsRoot = join(input.dataDir, GEN_UI_DIRECTORY_NAME);- const sessionDir = join(visualizationsRoot, location.sessionId);-- let fragment: string;- try {- // The session directory must really live under the visualizations root:- // a symlinked session directory would otherwise serve any `.html` file on- // disk with a matching name.- const [realRoot, realSessionDir] = await Promise.all([- realpath(visualizationsRoot),- realpath(sessionDir),- ]);- if (!isInside(realRoot, realSessionDir) || realSessionDir === realRoot) return NOT_FOUND;-- // Open the file inside the resolved directory without following a final- // symlink, then check the opened handle, so a swap between the checks and- // the read cannot redirect it.- const filePath = join(realSessionDir, location.fileName);- // O_NOFOLLOW is unavailable on Windows; keep the lstat check there.- if ((await lstat(filePath)).isSymbolicLink()) return NOT_FOUND;- const handle = await open(- filePath,- fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW,- );- try {- const stats = await handle.stat();- if (!stats.isFile()) return NOT_FOUND;- if (stats.size > GEN_UI_MAX_FRAGMENT_BYTES) {- return { ok: false, status: 413, code: "too-large" };- }- // Bounded read: a file that grows after stat still cannot exceed the cap.- const buffer = Buffer.alloc(Math.min(stats.size, GEN_UI_MAX_FRAGMENT_BYTES) + 1);- let bytesRead = 0;- while (bytesRead < buffer.length) {- const chunk = await handle.read(buffer, bytesRead, buffer.length - bytesRead, bytesRead);- if (chunk.bytesRead === 0) break;- bytesRead += chunk.bytesRead;- }- if (bytesRead > GEN_UI_MAX_FRAGMENT_BYTES) {- return { ok: false, status: 413, code: "too-large" };- }- fragment = buffer.subarray(0, bytesRead).toString("utf8");- } finally {- await handle.close();- }-- if (isFullHtmlDocument(fragment)) {- return {- ok: false,- status: 422,- code: "not-fragment",- };- }- } catch {- return NOT_FOUND;+ const result = await input.readFragment(location);+ if (!result.ok) return result;+ const { fragment } = result;+ if (isFullHtmlDocument(fragment)) {+ return { ok: false, status: 422, code: "not-fragment" };}let kit: GenUiKit;@@ -214,10 +156,11 @@ function loadInstalledKit(): Promise<GenUiKit> {}/**- * Install the request handler. Call once, after the app is ready. `getDataDir`- * is read per request so the handler follows the data directory in use.+ * Install once after ready. Resolve the current local Host per request so+ * profile relocation and runtime restarts never reuse a stale reader.*/-export function installGenUiProtocol(input: { getDataDir: () => string }): void {+export function installGenUiProtocol(input: { getHost: () => GenUiFragmentHost | null }): void {+ const readFragment = createGenUiFragmentReader(input.getHost);protocol.handle(GEN_UI_SCHEME, async (request) => {if (isGenUiAssetRequest(request.url)) {return genUiAssetResponse(@@ -228,7 +171,7 @@ export function installGenUiProtocol(input: { getDataDir: () => string }): voidawait resolveGenUiRequest({method: request.method,url: request.url,- dataDir: input.getDataDir(),+ readFragment,loadKit: loadInstalledKit,}),);diff --git a/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx b/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsxindex 9828af295..d33bd71aa 100644--- a/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx+++ b/apps/desktop/src/features/chat/gen-ui/GenUiCard.tsx@@ -113,7 +113,7 @@ function PooledGenUiCard({</div>)}</div>- {expanded ? <GenUiDialog url={url} title={title} onClose={closeDialog} /> : null}+ {expanded ? <GenUiDialog url={url} inlineSlot={slot.current} title={title} onClose={closeDialog} /> : null}</div>);}diff --git a/apps/desktop/src/features/chat/gen-ui/GenUiDialog.tsx b/apps/desktop/src/features/chat/gen-ui/GenUiDialog.tsxindex 210cd37d8..de9a93d2d 100644--- a/apps/desktop/src/features/chat/gen-ui/GenUiDialog.tsx+++ b/apps/desktop/src/features/chat/gen-ui/GenUiDialog.tsx@@ -1,8 +1,9 @@-import { useEffect, useRef } from "react";+import { useEffect, useLayoutEffect, useRef } from "react";import { useTranslation } from "react-i18next";import { OverlayBackdrop, portalOverlay, TooltipButton } from "../../../components/ui";import { IconClose } from "../../../components/icons";import { GenUiFrame } from "./GenUiFrame";+import { genUiFramePool } from "./gen-ui-frames";/*** Where Tab should move focus inside the dialog, or null to let the browser@@ -27,16 +28,25 @@ const FOCUSABLE = "button:not([disabled]), iframe";*/export function GenUiDialog({url,+ inlineSlot,title,onClose,}: {url: string;+ inlineSlot: symbol;title: string;onClose: () => void;}) {const { t } = useTranslation();const closeRef = useRef<HTMLButtonElement | null>(null);const dialogRef = useRef<HTMLDivElement | null>(null);+ const slot = useRef(Symbol(url));++ useLayoutEffect(() => {+ const id = slot.current;+ genUiFramePool.acquireExpanded(id, inlineSlot, onClose);+ return () => genUiFramePool.release(id);+ }, [inlineSlot, onClose]);useEffect(() => {const previouslyFocused = document.activeElement as HTMLElement | null;diff --git a/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts b/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.tsindex 8950013c5..f9e9393a9 100644--- a/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts+++ b/apps/desktop/src/features/chat/gen-ui/gen-ui-frames.ts@@ -98,34 +98,44 @@ export function isGenUiReadyMessage(event: FrameMessageEvent, frameWindow: unkno/** Upper bound on simultaneously mounted guest frames across all panes. */export const GEN_UI_MAX_LIVE_FRAMES = 8;-type LiveFrame = { onEvict: () => void; visible: boolean };+type LiveFrame = { onEvict: () => void; visible: boolean; inlineSlot?: symbol };/*** Bounded set of live frames. Cards hold a slot only while near the viewport* and release it when they scroll away, so the pool overflows only when many* cards are near at once (tall windows, split panes). Acquiring beyond the- * limit evicts the longest-live frame that is off-screen, and only when every- * other frame is on screen the longest-live one overall. An off-screen- * newcomer never displaces a frame the reader is looking at: it is evicted- * itself and loads once it scrolls into view.+ * limit evicts an off-screen inline frame first, then the oldest inline frame.+ * Expanded frames share the quota and protect their source inline state while+ * open. An off-screen newcomer never displaces a visible frame.*/export function createGenUiFramePool(limit = GEN_UI_MAX_LIVE_FRAMES) {const live = new Map<symbol, LiveFrame>();const victim = (newcomer: symbol): symbol => {- for (const [id, frame] of live) if (!frame.visible) return id;- for (const id of live.keys()) if (id !== newcomer) return id;+ const protectedSlots = new Set([...live.values()].flatMap((frame) => frame.inlineSlot ? [frame.inlineSlot] : []));+ const inline = [...live].filter(([id, frame]) => !frame.inlineSlot && !protectedSlots.has(id));+ for (const [id, frame] of inline) if (!frame.visible) return id;+ for (const [id] of inline) if (id !== newcomer) return id;+ if (inline.some(([id]) => id === newcomer)) return newcomer;+ // Multiple panes may hold expanded views; the global bound still wins.+ for (const [id, frame] of live) if (frame.inlineSlot && id !== newcomer) return id;return newcomer;};+ const acquire = (id: symbol, frame: LiveFrame): void => {+ live.delete(id);+ live.set(id, frame);+ while (live.size > limit) {+ const evicted = victim(id);+ const entry = live.get(evicted);+ live.delete(evicted);+ entry?.onEvict();+ }+ };return {acquire(id: symbol, onEvict: () => void, visible = true): void {- live.delete(id);- live.set(id, { onEvict, visible });- while (live.size > limit) {- const evicted = victim(id);- const frame = live.get(evicted);- live.delete(evicted);- frame?.onEvict();- }+ acquire(id, { onEvict, visible });+ },+ acquireExpanded(id: symbol, inlineSlot: symbol, onEvict: () => void): void {+ acquire(id, { onEvict, visible: true, inlineSlot });},setVisible(id: symbol, visible: boolean): void {const frame = live.get(id);diff --git a/apps/desktop/test/gen-ui-card.test.mjs b/apps/desktop/test/gen-ui-card.test.mjsindex d61c2e122..c460ae883 100644--- a/apps/desktop/test/gen-ui-card.test.mjs+++ b/apps/desktop/test/gen-ui-card.test.mjs@@ -211,3 +211,25 @@ test("every locale defines the gen-ui strings", () => {}assert.equal(Object.keys(catalogs).length, 9);});++test("expanded frames share the quota without evicting their inline state", async (t) => {+ const ssr = await slotSsr(t);+ const { createGenUiFramePool } = await ssr.load("/src/features/chat/gen-ui/gen-ui-frames.ts");+ const pool = createGenUiFramePool(3);+ const [source, other, dialog, incoming] = [Symbol("source"), Symbol("other"), Symbol("dialog"), Symbol("incoming")];+ const evicted = [];+ pool.acquire(source, () => evicted.push("source"));+ pool.acquire(other, () => evicted.push("other"));+ pool.acquireExpanded(dialog, source, () => evicted.push("dialog"));+ pool.acquire(incoming, () => evicted.push("incoming"));+ assert.equal(pool.size, 3);+ assert.deepEqual(evicted, ["other"]);+ pool.release(dialog);+ pool.acquire(other, () => evicted.push("other"));+ const next = Symbol("next");+ pool.acquire(next, () => evicted.push("next"));+ assert.equal(pool.size, 3);+ assert.deepEqual(evicted, ["other", "source"], "closing releases the inline protection");+ for (const id of [source, other, incoming, next]) pool.release(id);+ assert.equal(pool.size, 0);+});diff --git a/apps/desktop/test/gen-ui-file-safety.test.mjs b/apps/desktop/test/gen-ui-file-safety.test.mjsnew file mode 100644index 000000000..6eb368c15--- /dev/null+++ b/apps/desktop/test/gen-ui-file-safety.test.mjs@@ -0,0 +1,108 @@+import assert from "node:assert/strict";+import test from "node:test";+import { register } from "node:module";+import fs from "node:fs/promises";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+register(`data:text/javascript,${encodeURIComponent(`+ export async function resolve(specifier, context, next) {+ if (specifier === "electron") return { url: "data:text/javascript,export const protocol = {};", shortCircuit: true };+ return next(specifier, context);+ }+`)}`);+const { createGenUiFragmentReader } = await import("../electron/main/gen-ui-files.ts");+const { resolveGenUiRequest, genUiResponse } = await import("../electron/main/gen-ui-protocol.ts");+const { GEN_UI_MAX_FRAGMENT_BYTES } = await import("@pi-desktop/shared");+const location = { sessionId: "session", fileName: "chart.html" };+const wire = (text) => ({ ok: true, base64: Buffer.from(text).toString("base64") });+const unavailable = { ok: false, status: 500, code: "runtime-unavailable" };++// Filesystem regressions live with the real native directory-capability reader.+// This suite mocks only that external Host boundary, never a second file policy.+test("the protocol asks the native Host for identity only and enforces response sandbox", async () => {+ const calls = [];+ const readFragment = createGenUiFragmentReader(() => ({+ async call(method, args, timeout) {+ calls.push({ method, args, timeout });+ return wire("<p>chart</p>");+ },+ }));+ const result = await resolveGenUiRequest({+ method: "GET", url: "pi-genui://session/session/chart.html", readFragment,+ loadKit: async () => ({ css: "", runtime: "", vendorUrls: new Map(), vendorFiles: new Map() }),+ });+ assert.equal(result.ok, true);+ assert.match(result.document, /<p>chart<\/p>/);+ assert.deepEqual(calls, [{ method: "visualizations.readFragment", args: location, timeout: 5_000 }]);+ for (const value of [result, { ok: false, status: 404, code: "not-found" }]) {+ const response = genUiResponse(value);+ assert.match(response.headers.get("content-security-policy"), /(?:^|; )sandbox allow-scripts(?:;|$)/);+ assert.doesNotMatch(await response.text(), /<meta[^>]+content="[^"]*sandbox /);+ }+});++test("invalid identities cannot reach a native Host or name an absolute file", async () => {+ let calls = 0;+ const read = createGenUiFragmentReader(() => ({ async call() { calls += 1; return wire("bad"); } }));+ for (const input of [+ { sessionId: "../other", fileName: "chart.html" }, { sessionId: "session", fileName: "/private/chart.html" },+ { sessionId: "session", fileName: "..\\chart.html" }, { sessionId: "session", fileName: "chart.txt" },+ ]) assert.deepEqual(await read(input), { ok: false, status: 404, code: "not-found" });+ assert.equal(calls, 0);+});++test("fixed native errors map to the existing public card failures", async () => {+ for (const [code, status] of [["not-found", 404], ["too-large", 413]]) {+ const read = createGenUiFragmentReader(() => ({ async call() { return { ok: false, code }; } }));+ assert.deepEqual(await read(location), { ok: false, status, code });+ }+});++test("malformed native replies fail closed and never log bytes or filesystem paths", async (t) => {+ const diagnostics = [];+ t.mock.method(console, "warn", (...args) => diagnostics.push(args));+ for (const result of [+ null, [], { ok: true }, { ok: true, base64: "!!!!" }, { ok: true, base64: "AB==" },+ { ok: false, code: "not-found", path: "/private/DO_NOT_PRINT" },+ { ok: true, base64: "A".repeat(Math.ceil(GEN_UI_MAX_FRAGMENT_BYTES / 3) * 4 + 4) },+ ]) {+ const read = createGenUiFragmentReader(() => ({ async call() { return result; } }));+ assert.deepEqual(await read(location), unavailable);+ }+ assert.ok(diagnostics.length > 0, "unexpected boundary failures remain observable");+ assert.doesNotMatch(JSON.stringify(diagnostics), /DO_NOT_PRINT|!!!!|AB==/);+});++test("byte limits apply after base64 decode and do not depend on JSON expansion", async () => {+ for (const size of [0, GEN_UI_MAX_FRAGMENT_BYTES, GEN_UI_MAX_FRAGMENT_BYTES + 1]) {+ const read = createGenUiFragmentReader(() => ({ async call() { return wire(Buffer.alloc(size)); } }));+ const result = await read(location);+ if (size <= GEN_UI_MAX_FRAGMENT_BYTES) {+ assert.equal(result.ok, true);+ assert.equal(result.fragment.length, size);+ } else assert.deepEqual(result, { ok: false, status: 413, code: "too-large" });+ }+});++test("restart and relocation switch the Host without retaining a stale reader", async (t) => {+ t.mock.method(console, "warn", () => undefined);+ let current = { async call() { return wire("old profile"); } };+ const read = createGenUiFragmentReader(() => current);+ assert.deepEqual(await read(location), { ok: true, fragment: "old profile" });+ current = null;+ assert.deepEqual(await read(location), unavailable);+ current = { async call() { return wire("new profile"); } };+ assert.deepEqual(await read(location), { ok: true, fragment: "new profile" });+ current = { async call() { throw new Error("/private/transport-failure"); } };+ assert.deepEqual(await read(location), unavailable);+});++test("Main has no local filesystem fallback when reading a native fragment", async (t) => {+ let fileOperations = 0;+ for (const name of ["lstat", "realpath", "open", "readFile"]) {+ t.mock.method(fs, name, () => { fileOperations += 1; throw new Error("Main must not reopen fragment paths"); });+ }+ const read = createGenUiFragmentReader(() => ({ async call() { return wire("native bytes"); } }));+ assert.deepEqual(await read(location), { ok: true, fragment: "native bytes" });+ assert.equal(fileOperations, 0);+});diff --git a/apps/desktop/test/gen-ui-protocol.test.mjs b/apps/desktop/test/gen-ui-protocol.test.mjsindex a2889a2cc..fc0ade160 100644--- a/apps/desktop/test/gen-ui-protocol.test.mjs+++ b/apps/desktop/test/gen-ui-protocol.test.mjs@@ -1,8 +1,7 @@import assert from "node:assert/strict";import test from "node:test";import { register } from "node:module";-import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";+import { readFileSync } from "node:fs";import { join } from "node:path";import { readMainModule, readMainSource } from "./helpers/source-contracts.mjs";@@ -16,7 +15,6 @@ const {isFullHtmlDocument,sanitizeGenUiThemeVars,} = await import("../electron/main/gen-ui-document.ts");-const { GEN_UI_MAX_FRAGMENT_BYTES } = await import("@pi-desktop/shared");// gen-ui-protocol.ts imports `electron` for `protocol`; load it through a tiny// stub so the resolver and privileges can be exercised without Electron.@@ -46,16 +44,10 @@ const D3_CDN = "https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js";const EXPECTED_CSP ="default-src 'none'; script-src 'unsafe-inline' pi-genui://assets; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'; webrtc 'block'";+const EXPECTED_HEADER_CSP = `${EXPECTED_CSP}; sandbox allow-scripts`;-function fixture(t) {- const dataDir = mkdtempSync(join(tmpdir(), "pi-genui-"));- t.after(() => rmSync(dataDir, { recursive: true, force: true }));- const sessionDir = join(dataDir, "visualizations", "sess_1");- mkdirSync(sessionDir, { recursive: true });- return { dataDir, sessionDir };-}--const get = (dataDir, url, method = "GET") => resolveGenUiRequest({ method, url, dataDir, loadKit });+const missingFragment = async () => ({ ok: false, status: 404, code: "not-found" });+const get = (readFragment, url, method = "GET") => resolveGenUiRequest({ method, url, readFragment, loadKit });test("guest CSP and permissions policy are exact and network-free", () => {assert.equal(GEN_UI_CONTENT_SECURITY_POLICY, EXPECTED_CSP);@@ -65,7 +57,7 @@ test("guest CSP and permissions policy are exact and network-free", () => {const headers = genUiResponseHeaders();assert.deepEqual(headers, {"content-type": "text/html; charset=utf-8",- "content-security-policy": EXPECTED_CSP,+ "content-security-policy": EXPECTED_HEADER_CSP,"permissions-policy": GEN_UI_PERMISSIONS_POLICY,"x-content-type-options": "nosniff","cache-control": "no-store",@@ -160,12 +152,10 @@ test("assets: only manifest files are served, as cacheable JavaScript", async ()});test("a missing kit yields the unavailable page, never a half-built document", async (t) => {- const { dataDir, sessionDir } = fixture(t);- writeFileSync(join(sessionDir, "chart.html"), "<p>x</p>");const result = await resolveGenUiRequest({method: "GET",url: "pi-genui://session/sess_1/chart.html",- dataDir,+ readFragment: async () => ({ ok: true, fragment: "<p>x</p>" }),loadKit: async () => {throw new Error("missing");},@@ -218,32 +208,24 @@ test("full HTML documents are detected past whitespace, BOM, and comments", () =});test("a valid fragment is served inside the shell with security headers", async (t) => {- const { dataDir, sessionDir } = fixture(t);- writeFileSync(join(sessionDir, "chart.html"), "<svg id=chart></svg>");- const result = await get(dataDir, "pi-genui://session/sess_1/chart.html");+ const result = await get(async () => ({ ok: true, fragment: "<svg id=chart></svg>" }), "pi-genui://session/sess_1/chart.html");assert.equal(result.ok, true);assert.match(result.document, /<svg id=chart><\/svg>/);const response = genUiResponse(result);assert.equal(response.status, 200);- assert.equal(response.headers.get("content-security-policy"), EXPECTED_CSP);+ assert.equal(response.headers.get("content-security-policy"), EXPECTED_HEADER_CSP);assert.equal(response.headers.get("access-control-allow-origin"), null);assert.match(await response.text(), /<svg id=chart>/);});-test("rejections: method, URL shape, traversal, symlinks, non-files, size, documents", async (t) => {- const { dataDir, sessionDir } = fixture(t);- writeFileSync(join(sessionDir, "ok.html"), "<p>ok</p>");- const outside = join(dataDir, "secret.html");- writeFileSync(outside, "<p>secret</p>");- symlinkSync(outside, join(sessionDir, "link.html"));- mkdirSync(join(sessionDir, "dir.html"));- writeFileSync(join(sessionDir, "big.html"), Buffer.alloc(GEN_UI_MAX_FRAGMENT_BYTES + 1, 0x61));- writeFileSync(join(sessionDir, "doc.html"), "<!-- hi -->\n<!doctype html><html></html>");- // A symlinked session directory must not reach outside the root either.- mkdirSync(join(dataDir, "elsewhere"));- writeFileSync(join(dataDir, "elsewhere", "ok.html"), "<p>elsewhere</p>");- symlinkSync(join(dataDir, "elsewhere"), join(dataDir, "visualizations", "linked"));-+test("rejections: method, URL shape, traversal, native file errors, documents", async () => {+ // Native filesystem checks are covered by Host tests; this boundary maps+ // their fixed failures without reimplementing path containment in Main.+ const readFragment = async (location) => {+ if (location.fileName === "big.html") return { ok: false, status: 413, code: "too-large" };+ if (location.fileName === "doc.html") return { ok: true, fragment: "<!-- hi -->\n<!doctype html><html></html>" };+ return missingFragment();+ };const cases = [["POST", "pi-genui://session/sess_1/ok.html", 405],["GET", "pi-genui://session/bad%20id/ok.html", 404],@@ -261,35 +243,29 @@ test("rejections: method, URL shape, traversal, symlinks, non-files, size, docum["GET", "pi-genui://session/sess_1/doc.html", 422],];for (const [method, url, status] of cases) {- const result = await get(dataDir, url, method);+ const result = await get(readFragment, url, method);assert.equal(result.ok, false, url);assert.equal(result.status, status, `${method} ${url}`);const response = genUiResponse(result);assert.equal(response.status, status);- assert.equal(response.headers.get("content-security-policy"), EXPECTED_CSP);+ assert.equal(response.headers.get("content-security-policy"), EXPECTED_HEADER_CSP);const body = await response.text();- assert.ok(!body.includes(dataDir), `error body leaks the data dir for ${url}`);assert.ok(!body.includes("secret"), url);assert.ok(!body.includes("elsewhere"), url);}- assert.equal(genUiResponse(await get(dataDir, "pi-genui://session/sess_1/ok.html", "POST")).headers.get("allow"), "GET");- // Missing visualizations root entirely.- const empty = mkdtempSync(join(tmpdir(), "pi-genui-empty-"));- t.after(() => rmSync(empty, { recursive: true, force: true }));- assert.equal((await get(empty, "pi-genui://session/sess_1/ok.html")).status, 404);+ assert.equal(genUiResponse(await get(readFragment, "pi-genui://session/sess_1/ok.html", "POST")).headers.get("allow"), "GET");+ assert.equal((await get(missingFragment, "pi-genui://session/sess_1/ok.html")).status, 404);});-test("the data directory is read per request, so references follow relocation", async (t) => {- const first = fixture(t);- const second = fixture(t);- writeFileSync(join(second.sessionDir, "moved.html"), "<p>moved</p>");- let current = first.dataDir;- const resolveNow = (url) => get(current, url);+test("the native reader dependency is used per request so references follow relocation", async () => {+ let current = { ok: false, status: 404, code: "not-found" };+ const readFragment = async () => current;+ const resolveNow = (url) => get(readFragment, url);assert.equal((await resolveNow("pi-genui://session/sess_1/moved.html")).ok, false);- current = second.dataDir;+ current = { ok: true, fragment: "<p>moved</p>" };assert.equal((await resolveNow("pi-genui://session/sess_1/moved.html")).ok, true);const source = await readMainModule("gen-ui-protocol.ts");- assert.match(source, /dataDir: input\.getDataDir\(\)/);+ assert.match(source, /createGenUiFragmentReader\(input\.getHost\)/);});test("scheme privileges: standard + secure only, registered in the single privileged call", async () => {@@ -305,7 +281,7 @@ test("scheme privileges: standard + secure only, registered in the single privil/registerSchemesAsPrivileged\(\[\s*PLUGIN_ASSET_SCHEME_PRIVILEGES,\s*PLUGIN_RENDERER_SCHEME_PRIVILEGES,\s*GEN_UI_SCHEME_PRIVILEGES,\s*\]\)/,);const startup = await readMainModule("bootstrap/startup.ts");- const install = startup.indexOf("installGenUiProtocol({ getDataDir: () => dataDir });");+ const install = startup.indexOf("installGenUiProtocol({ getHost });");assert.ok(install > startup.indexOf("app.whenReady()"), "protocol handler installs after ready");});diff --git a/crates/host-core/src/rpc/gen_ui.rs b/crates/host-core/src/rpc/gen_ui.rsnew file mode 100644index 000000000..7699c42ab--- /dev/null+++ b/crates/host-core/src/rpc/gen_ui.rs@@ -0,0 +1,122 @@+//! Private Host-to-Main bridge for sandboxed visualization documents.++use std::sync::Arc;++use base64::{engine::general_purpose::STANDARD, Engine as _};+use serde::Deserialize;+use serde_json::{json, Value};+use tokio::sync::Mutex;++use super::{rpc_err, JsonRpcError};+use crate::state::AppState;+use crate::visualizations::files::{self, FragmentReadError};++#[derive(Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+struct ReadFragmentParams {+ session_id: String,+ file_name: String,+}++pub(super) async fn read_fragment(+ state: Arc<Mutex<AppState>>,+ params: Value,+) -> Result<Value, JsonRpcError> {+ let params: ReadFragmentParams = serde_json::from_value(params).map_err(|_| {+ rpc_err(+ 1002,+ "invalid visualization read parameters",+ "INVALID_PARAMS",+ )+ })?;+ let data_dir = { state.lock().await.data_dir.clone() };+ // Filesystem work never holds the authoritative state/database lock.+ let result = tokio::task::spawn_blocking(move || {+ files::read_fragment(&data_dir, ¶ms.session_id, ¶ms.file_name)+ })+ .await+ .map_err(|_| rpc_err(1000, "visualization read worker failed", "INTERNAL"))?;+ Ok(match result {+ Ok(bytes) => json!({ "ok": true, "base64": STANDARD.encode(bytes) }),+ Err(FragmentReadError::NotFound) => json!({ "ok": false, "code": "not-found" }),+ Err(FragmentReadError::TooLarge) => json!({ "ok": false, "code": "too-large" }),+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::rpc::handle_request;+ use std::fs;+ use tokio::sync::mpsc;++ fn fixture() -> (tempfile::TempDir, Arc<Mutex<AppState>>) {+ let directory = tempfile::tempdir().unwrap();+ let mut state = AppState::open(directory.path()).unwrap();+ state.handshook = true;+ (directory, Arc::new(Mutex::new(state)))+ }++ async fn call(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value, JsonRpcError> {+ handle_request(+ state,+ "visualizations.readFragment",+ params,+ mpsc::unbounded_channel().0,+ )+ .await+ }++ #[tokio::test]+ async fn visualization_native_rpc_returns_bounded_bytes_without_a_workspace() {+ let (directory, state) = fixture();+ let session = directory.path().join("visualizations").join("s1");+ fs::create_dir_all(&session).unwrap();+ let file = session.join("chart.html");+ let params = json!({ "sessionId": "s1", "fileName": "chart.html" });+ fs::write(&file, "<p>native chart</p>").unwrap();+ let result = call(state.clone(), params.clone()).await.unwrap();+ assert_eq!(result["ok"], true);+ assert_eq!(+ STANDARD.decode(result["base64"].as_str().unwrap()).unwrap(),+ b"<p>native chart</p>"+ );+ fs::write(&file, vec![0; files::MAX_FRAGMENT_BYTES]).unwrap();+ let result = call(state.clone(), params.clone()).await.unwrap();+ assert_eq!(+ STANDARD+ .decode(result["base64"].as_str().unwrap())+ .unwrap()+ .len(),+ files::MAX_FRAGMENT_BYTES+ );+ fs::write(&file, vec![0; files::MAX_FRAGMENT_BYTES + 1]).unwrap();+ assert_eq!(+ call(state.clone(), params).await.unwrap(),+ json!({ "ok": false, "code": "too-large" })+ );+ assert_eq!(+ call(+ state,+ json!({ "sessionId": "s1", "fileName": "../outside.html" })+ )+ .await+ .unwrap(),+ json!({ "ok": false, "code": "not-found" })+ );+ }++ #[tokio::test]+ async fn visualization_native_rpc_rejects_caller_roots_and_malformed_parameters() {+ let (_directory, state) = fixture();+ for params in [+ json!({ "sessionId": "s1", "fileName": "chart.html", "dataDir": "/private" }),+ json!({ "sessionId": "s1", "fileName": 1 }),+ json!({ "fileName": "chart.html" }),+ ] {+ let error = call(state.clone(), params).await.unwrap_err();+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");+ assert!(!error.message.contains("/private"));+ }+ }+}diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex e61b4a4fa..8e58a366f 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -1,4 +1,5 @@mod config_sync_rpc;+mod gen_ui;mod plugin_reviews_rpc;mod remote_tools;mod scheduled_rpc;@@ -1421,8 +1422,8 @@ fn requires_external_path_permission(let Some(path) = args.get("path").and_then(Value::as_str) else {return false;};- if roots.lexical_root(path).is_some() {- return false;+ if let Some(root) = roots.lexical_root(path) {+ return !root.allows_implicit_access();}let Some(workspace_path) = workspace_path else {return false;@@ -1461,7 +1462,8 @@ fn contained_write_auto_allowed(&& args.get("path").and_then(Value::as_str)- .is_some_and(|path| roots.lexical_root(path).is_some())+ .and_then(|path| roots.lexical_root(path))+ .is_some_and(|root| root.allows_implicit_access())&& edit_move_stays_contained(roots, args)}@@ -1475,7 +1477,11 @@ fn edit_move_stays_contained(roots: &ContainedRoots, args: &Value) -> bool {let Ok(parsed) = crate::tools::hashline::parse_ops(ops) else {return true;};- crate::tools::hashline::mv_dest(&parsed).is_none_or(|dest| roots.lexical_root(dest).is_some())+ crate::tools::hashline::mv_dest(&parsed).is_none_or(|dest| {+ roots+ .lexical_root(dest)+ .is_some_and(|root| root.allows_implicit_access())+ })}/// Plans are owned by the session's persisted project. Unlike the legacy@@ -1908,6 +1914,7 @@ async fn handle_request(}match method {+ "visualizations.readFragment" => gen_ui::read_fragment(state, params).await,"tools.remoteComplete" | "tools.workspaceExecute" | "tools.workspaceAbort" => {remote_tools::handle(state, method, params, tx).await}@@ -4140,10 +4147,10 @@ async fn handle_request();// Write/Edit targeting the session scratch dir (D114) or// visualization dir (D671) never touch the user's project —- // skip the prompt. The lexical pre-check only decides- // prompting; execution still goes through the symlink-aware- // resolver, so it cannot be used to escape containment. A- // contract mode's hard deny is never bypassed.+ // skip the prompt only while those roots remain valid.+ // Execution revalidates visualization roots and runs the+ // symlink-aware path resolver; root identity is not cached.+ // A contract mode's hard deny is never bypassed.if auto.is_none()&& contained_write_auto_allowed(remote_workspace.is_some(),diff --git a/crates/host-core/src/rpc/visualization_tests.rs b/crates/host-core/src/rpc/visualization_tests.rsindex ba1adcdb0..dd4827136 100644--- a/crates/host-core/src/rpc/visualization_tests.rs+++ b/crates/host-core/src/rpc/visualization_tests.rs@@ -4,6 +4,7 @@use super::*;use std::fs;+mod fork;fn options(visualization_root: Option<&Path>) -> tools::ToolExecutionOptions<'_> {tools::ToolExecutionOptions {timeout_ms: None,@@ -26,7 +27,7 @@ fn fixture() -> Fixture {let data = tempfile::tempdir().unwrap();// Canonical paths keep the symlink-aware resolver's comparisons simple on// macOS, where the temp dir lives behind /var -> /private/var.- let data_dir = fs::canonicalize(data.path()).unwrap();+ let data_dir = workspace::simple_canonicalize(data.path()).unwrap();let workspace = data_dir.join("project");fs::create_dir_all(&workspace).unwrap();let scratch = scratch::session_dir(&data_dir, "s1").unwrap();@@ -40,6 +41,258 @@ fn fixture() -> Fixture {}}+#[test]+fn redirected_visualization_roots_never_skip_authorization() {+ for redirect_base in [false, true] {+ let f = fixture();+ // Keep the root list across replacement: it is not a cached grant.+ let roots = local_contained_roots(&f.data_dir, "s1", false);+ let link = if redirect_base {+ visualizations::base_dir(&f.data_dir)+ } else {+ fs::create_dir_all(visualizations::base_dir(&f.data_dir)).unwrap();+ f.visualization.clone()+ };+ crate::session_worktrees::test_support::link_dir(&f.workspace, &link);+ let args = json!({ "path": f.visualization.join("index.html"), "content": "overwrite" });+ for ws in [&f.workspace, &f.data_dir] {+ assert!(!contained_write_auto_allowed(+ false, "agent", &roots, "Write", &args+ ));+ assert!(requires_external_path_permission(+ Some(&ws.to_string_lossy()),+ &roots,+ "Read",+ &args+ ));+ assert!(requires_external_path_permission(+ Some(&ws.to_string_lossy()),+ &roots,+ "Write",+ &args+ ));+ }+ let scratch_args = json!({+ "path": f.scratch.join("notes.txt"),+ "ops": format!("MV {}", f.visualization.join("index.html").display()),+ });+ assert!(!contained_write_auto_allowed(+ false,+ "agent",+ &roots,+ "Edit",+ &scratch_args+ ));+ }+}++#[tokio::test]+async fn execution_rejects_redirected_roots_and_does_not_create_external_directories() {+ for redirect_base in [false, true] {+ for contains_data in [false, true] {+ let f = fixture();+ let roots = local_contained_roots(&f.data_dir, "s1", false);+ fs::create_dir_all(&f.visualization).unwrap();+ let link = if redirect_base {+ visualizations::base_dir(&f.data_dir)+ } else {+ f.visualization.clone()+ };+ fs::rename(&link, f.data_dir.join("previous-root")).unwrap();+ crate::session_worktrees::test_support::link_dir(&f.workspace, &link);+ let ws = if contains_data {+ &f.data_dir+ } else {+ &f.workspace+ };+ let path = f.visualization.join("index.html");+ assert!(workspace::resolve_tool_path(ws, &roots, &path.to_string_lossy()).is_err());+ let written = tools::execute_tool_with_path_access(+ Some(ws),+ Some(&f.scratch),+ "Write",+ &json!({ "path": path, "content": "overwrite" }),+ options(Some(&f.visualization)),+ )+ .await;+ assert!(!written.ok, "redirected root must not execute: {written:?}");+ assert!(!f.workspace.join("index.html").exists());+ assert!(+ !f.workspace.join("s1").exists(),+ "lazy creation followed the base link"+ );+ }+ }+}++async fn rpc_session(+ f: &Fixture,+ contains_data: bool,+ permission_mode: &str,+) -> (Arc<Mutex<AppState>>, String) {+ let mut app = AppState::open(&f.data_dir).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));+ let project = if contains_data {+ &f.data_dir+ } else {+ &f.workspace+ };+ let created = handle_request(+ state.clone(),+ "session.create",+ json!({ "projectPath": project }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ let id = created["session"]["id"].as_str().unwrap().to_string();+ handle_request(+ state.clone(),+ "session.configure",+ json!({ "id": id, "mode": "agent", "permissionMode": permission_mode }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ (state, id)+}++#[tokio::test]+async fn rpc_redirected_visualization_write_prompts_and_denial_preserves_project() {+ for redirect_base in [false, true] {+ for contains_data in [false, true] {+ let f = fixture();+ let (state, id) = rpc_session(&f, contains_data, "ask").await;+ let root = visualizations::session_dir(&f.data_dir, &id).unwrap();+ let target = if redirect_base {+ f.workspace.join(&id)+ } else {+ f.workspace.clone()+ };+ fs::create_dir_all(&target).unwrap();+ fs::write(target.join("index.html"), "important project file").unwrap();+ let link = if redirect_base {+ visualizations::base_dir(&f.data_dir)+ } else {+ fs::create_dir_all(visualizations::base_dir(&f.data_dir)).unwrap();+ root.clone()+ };+ crate::session_worktrees::test_support::link_dir(&f.workspace, &link);+ let (tx, mut rx) = mpsc::unbounded_channel();+ let pending_state = state.clone();+ let params = json!({ "sessionId": id, "toolCallId": "redirected-write", "toolName": "Write",+ "args": { "path": root.join("index.html"), "content": "overwrite" }, "mode": "agent" });+ let mut pending = tokio::spawn(handle_request(+ pending_state,+ "tools.execute",+ params,+ tx.clone(),+ ));+ let permission: Value = tokio::time::timeout(Duration::from_secs(5), async {+ tokio::select! {+ note = rx.recv() => serde_json::from_str(¬e.unwrap()).unwrap(),+ result = &mut pending => panic!("redirected Write completed without approval: {result:?}"),+ }+ }).await.unwrap();+ assert_eq!(permission["method"], "permissions.request");+ assert_eq!(+ fs::read_to_string(target.join("index.html")).unwrap(),+ "important project file"+ );+ handle_request(+ state.clone(),+ "permissions.resolve",+ json!({ "requestId": permission["params"]["requestId"], "decision": "deny" }),+ tx,+ )+ .await+ .unwrap();+ assert_eq!(pending.await.unwrap().unwrap()["errorCode"], "TOOL_DENIED");+ assert_eq!(+ fs::read_to_string(target.join("index.html")).unwrap(),+ "important project file"+ );+ }+ }+}++// Runs without platform gating, including Windows where std canonicalize+// returns a drive prefix that the tool resolver deliberately strips.+#[tokio::test]+async fn rpc_direct_html_write_read_edit_user_path_uses_one_canonical_spelling() {+ let f = fixture();+ let (state, id) = rpc_session(&f, false, "ask").await;+ let root = visualizations::session_dir(&f.data_dir, &id).unwrap();+ let path = root.join("chart.html");+ let (tx, mut rx) = mpsc::unbounded_channel();+ let write = handle_request(+ state.clone(),+ "tools.execute",+ json!({ "sessionId": id, "toolCallId": "write", "toolName": "Write",+ "args": { "path": path, "content": "<p>before</p>" }, "mode": "agent" }),+ tx.clone(),+ )+ .await+ .unwrap();+ assert_eq!(write["ok"], true, "{write}");+ assert_eq!(write["content"]["root"], "visualization");+ assert!(write["content"].get("review").is_none());+ let read = handle_request(+ state.clone(),+ "tools.execute",+ json!({ "sessionId": id, "toolCallId": "read", "toolName": "Read",+ "args": { "path": path }, "mode": "agent" }),+ tx.clone(),+ )+ .await+ .unwrap();+ assert_eq!(read["ok"], true, "{read}");+ let resolved = PathBuf::from(read["content"]["path"].as_str().unwrap());+ assert_eq!(+ resolved.parent(),+ Some(workspace::simple_canonicalize(&root).unwrap().as_path())+ );+ let edited = handle_request(state.clone(), "tools.execute",+ json!({ "sessionId": id, "toolCallId": "edit", "toolName": "Edit",+ "args": { "path": path, "tag": read["content"]["tag"], "ops": "PUT 1.=1:\n+<p>after</p>" },+ "mode": "agent" }), tx,+ ).await.unwrap();+ assert_eq!(edited["ok"], true, "{edited}");+ assert_eq!(edited["content"]["root"], "visualization");+ assert!(edited["content"].get("review").is_none());+ assert_eq!(fs::read_to_string(&path).unwrap(), "<p>after</p>");+ while let Ok(note) = rx.try_recv() {+ let note: Value = serde_json::from_str(¬e).unwrap();+ assert_ne!(note["method"], "permissions.request");+ }+}++#[tokio::test]+async fn rpc_session_delete_and_project_removal_do_not_follow_a_redirected_base() {+ for remove_project in [false, true] {+ let f = fixture();+ let (state, id) = rpc_session(&f, false, "ask").await;+ let external = f.workspace.join("important");+ let keep = external.join(&id).join("keep.html");+ fs::create_dir_all(keep.parent().unwrap()).unwrap();+ fs::write(&keep, "irreplaceable").unwrap();+ crate::session_worktrees::test_support::link_dir(+ &external,+ &visualizations::base_dir(&f.data_dir),+ );+ let (method, params) = if remove_project {+ ("projects.remove", json!({ "path": f.workspace }))+ } else {+ ("session.delete", json!({ "id": id }))+ };+ handle_request(state, method, params, mpsc::unbounded_channel().0)+ .await+ .unwrap();+ assert_eq!(fs::read_to_string(keep).unwrap(), "irreplaceable");+ }+}+async fn run(f: &Fixture, tool: &str, args: Value) -> tools::ToolsExecuteResult {tools::execute_tool_with_path_access(Some(&f.workspace),@@ -291,3 +544,87 @@ async fn visualization_rules_apply_when_the_workspace_contains_the_data_dir() {assert!(!result.ok, "non-html write must be rejected: {result:?}");assert!(!f.visualization.join("notes.txt").exists());}++#[tokio::test]+async fn visualization_redirection_can_only_execute_as_explicitly_approved_external_access() {+ for mode in ["ask", "accept-edits"] {+ let f = fixture();+ let (state, id) = rpc_session(&f, false, mode).await;+ let root = visualizations::session_dir(&f.data_dir, &id).unwrap();+ fs::create_dir_all(root.parent().unwrap()).unwrap();+ fs::write(f.workspace.join("index.html"), "before approval").unwrap();+ crate::session_worktrees::test_support::link_dir(&f.workspace, &root);+ let (tx, mut rx) = mpsc::unbounded_channel();+ let pending = tokio::spawn(handle_request(+ state.clone(),+ "tools.execute",+ json!({"sessionId": id, "toolCallId": "external-write", "toolName": "Write", "mode": "agent",+ "args": {"path": root.join("index.html"), "content": "approved external write"}}),+ tx.clone(),+ ));+ let permission: Value = serde_json::from_str(+ &tokio::time::timeout(Duration::from_secs(5), rx.recv())+ .await+ .unwrap()+ .unwrap(),+ )+ .unwrap();+ assert_eq!(permission["method"], "permissions.request");+ assert_eq!(+ fs::read_to_string(f.workspace.join("index.html")).unwrap(),+ "before approval"+ );+ handle_request(+ state,+ "permissions.resolve",+ json!({"requestId": permission["params"]["requestId"], "decision": "allow-once"}),+ tx,+ )+ .await+ .unwrap();+ let written = pending.await.unwrap().unwrap();+ assert_eq!(written["ok"], true, "{written}");+ assert_eq!(written["content"]["root"], "external");+ assert_eq!(+ fs::read_to_string(f.workspace.join("index.html")).unwrap(),+ "approved external write"+ );+ }+}++#[tokio::test]+async fn visualization_alias_spelling_preserves_root_identity_even_inside_the_workspace() {+ let f = fixture();+ let alias = f.workspace.join("profile-alias");+ crate::session_worktrees::test_support::link_dir(&f.data_dir, &alias);+ let root = visualizations::session_dir(&alias, "s1").unwrap();+ let roots = local_contained_roots(&alias, "s1", false);+ let path = f.visualization.join("chart.html");+ let written = tools::execute_tool_with_path_access(+ Some(&f.data_dir),+ Some(&f.scratch),+ "Write",+ &json!({"path": path, "content": "<p>chart</p>"}),+ options(Some(&root)),+ )+ .await;+ assert!(written.ok, "{written:?}");+ assert_eq!(written.content["root"], "visualization");+ fs::rename(&f.visualization, f.data_dir.join("old-root")).unwrap();+ crate::session_worktrees::test_support::link_dir(&f.workspace, &f.visualization);+ for path in [root.join("chart.html"), f.visualization.join("chart.html")] {+ let args = json!({"path": path});+ assert!(!contained_write_auto_allowed(+ false, "agent", &roots, "Write", &args+ ));+ assert!(requires_external_path_permission(+ Some(&f.data_dir.to_string_lossy()),+ &roots,+ "Read",+ &args+ ));+ assert!(+ workspace::resolve_tool_path(&f.data_dir, &roots, &path.to_string_lossy()).is_err()+ );+ }+}diff --git a/crates/host-core/src/rpc/visualization_tests/fork.rs b/crates/host-core/src/rpc/visualization_tests/fork.rsnew file mode 100644index 000000000..b0df84c92--- /dev/null+++ b/crates/host-core/src/rpc/visualization_tests/fork.rs@@ -0,0 +1,175 @@+//! Real RPC path: Bash creates a chart, a completed reply references it,+//! the profile moves, then a bounded fork keeps its own chart after deletion.++use super::*;++#[tokio::test]+async fn rpc_bash_created_visualization_survives_relocation_fork_and_source_deletion() {+ let data = tempfile::tempdir().unwrap();+ let parent = workspace::simple_canonicalize(data.path()).unwrap();+ let data_dir = parent.join("old-profile");+ let workspace = parent.join("project");+ fs::create_dir_all(&data_dir).unwrap();+ fs::create_dir_all(&workspace).unwrap();+ let f = Fixture {+ _data: data,+ scratch: scratch::session_dir(&data_dir, "s1").unwrap(),+ visualization: visualizations::session_dir(&data_dir, "s1").unwrap(),+ data_dir,+ workspace,+ };+ let (state, id) = rpc_session(&f, false, "auto").await;+ let root = visualizations::session_dir(&f.data_dir, &id).unwrap();+ let chart = root.join("chart.html");+ let shell = tools::shell::catalog(None).effective.unwrap();+ let quote = |path: &Path| path.to_string_lossy().replace('\'', "'\\''");+ let command = match shell.dialect.as_str() {+ "powershell" => format!(+ "[void][System.IO.Directory]::CreateDirectory('{}'); [System.IO.File]::WriteAllText('{}', '<p>chart</p>')",+ root.to_string_lossy().replace('\'', "''"), chart.to_string_lossy().replace('\'', "''"),+ ),+ "cmd" => format!(+ "if not exist \"{}\" mkdir \"{}\" & > \"{}\" echo ^<p^>chart^</p^>",+ root.display(), root.display(), chart.display(),+ ),+ _ => format!("mkdir -p '{}'; printf '%s' '<p>chart</p>' > '{}'", quote(&root), quote(&chart)),+ };+ let result = tokio::time::timeout(+ Duration::from_secs(10),+ handle_request(+ state.clone(),+ "tools.execute",+ json!({ "sessionId": id, "toolCallId": "bash-chart", "toolName": "Bash",+ "args": { "command": command }, "mode": "agent",+ "expectedCommandShellId": shell.id, "expectedCommandShellDialect": shell.dialect }),+ mpsc::unbounded_channel().0,+ ),+ )+ .await+ .expect("the fixture approves Bash and it finishes within its execution budget")+ .unwrap();+ assert_eq!(result["ok"], true, "{result}");+ assert_eq!(fs::read_to_string(&chart).unwrap().trim(), "<p>chart</p>");+ fs::write(root.join("unreferenced.html"), "unused").unwrap();+ let reference = format!("::visualize{}", json!({"path": chart, "title": "Chart"}));+ handle_request(+ state.clone(),+ "session.appendMessage",+ json!({ "sessionId": id, "message": { "id": "chart-reply", "role": "assistant",+ "content": reference, "createdAt": "2026-10-08T00:00:00Z" } }),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ let later = root.join("later.html");+ fs::write(&later, "later").unwrap();+ handle_request(+ state.clone(), "session.appendMessage",+ json!({ "sessionId": id, "message": { "id": "later-reply", "role": "assistant",+ "content": format!("::visualize{}", json!({"path": later})), "createdAt": "2026-10-08T00:00:01Z" } }),+ mpsc::unbounded_channel().0,+ ).await.unwrap();+ drop(state);++ let moved_data = parent.join("moved-profile");+ fs::rename(&f.data_dir, &moved_data).unwrap();+ let mut moved = AppState::open(&moved_data).unwrap();+ moved.handshook = true;+ let state = Arc::new(Mutex::new(moved));+ let source = handle_request(+ state.clone(),+ "session.get",+ json!({"id": id}),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ assert_eq!(source["session"]["messages"][0]["content"], reference);+ assert!(!chart.exists());+ let fork = handle_request(+ state.clone(),+ "session.fork",+ json!({"sessionId": id, "throughMessageId": "chart-reply"}),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ let child_id = fork["session"]["id"].as_str().unwrap();+ let child_root = visualizations::session_dir(&moved_data, child_id).unwrap();+ let child_chart = child_root.join("chart.html");+ assert_eq!(+ fs::read_to_string(&child_chart).unwrap().trim(),+ "<p>chart</p>"+ );+ assert_eq!(fork["session"]["messages"].as_array().unwrap().len(), 1);+ assert_eq!(+ fork["session"]["messages"][0]["content"],+ format!(+ "::visualize{}",+ json!({"path": child_chart, "title": "Chart"})+ )+ );+ assert!(!child_root.join("unreferenced.html").exists());+ assert!(!child_root.join("later.html").exists());+ handle_request(+ state.clone(),+ "session.delete",+ json!({"id": id}),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ assert_eq!(+ fs::read_to_string(&child_chart).unwrap().trim(),+ "<p>chart</p>"+ );+ let child = handle_request(+ state,+ "session.get",+ json!({"id": child_id}),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ assert_eq!(+ child["session"]["messages"][0]["content"],+ fork["session"]["messages"][0]["content"]+ );+}++#[tokio::test]+async fn rpc_visualization_fork_index_failure_rolls_back_child_files() {+ let f = fixture();+ let (state, id) = rpc_session(&f, false, "ask").await;+ let source = visualizations::session_dir(&f.data_dir, &id).unwrap();+ fs::create_dir_all(&source).unwrap();+ let chart = source.join("chart.html");+ fs::write(&chart, "source bytes").unwrap();+ handle_request(+ state.clone(), "session.appendMessage",+ json!({ "sessionId": id, "message": {"id": "chart", "role": "assistant",+ "content": format!("::visualize{}", json!({"path": chart})), "createdAt": "2026-10-08T00:00:00Z"} }),+ mpsc::unbounded_channel().0,+ ).await.unwrap();+ let transcripts_before = fs::read_dir(f.data_dir.join("sessions")).unwrap().count();+ state.lock().await.db.conn().execute_batch("CREATE TRIGGER fail_fork BEFORE INSERT ON sessions BEGIN SELECT RAISE(ABORT, 'injected index failure'); END;").unwrap();+ let result = handle_request(+ state,+ "session.fork",+ json!({"sessionId": id}),+ mpsc::unbounded_channel().0,+ )+ .await;+ assert!(result.is_err());+ assert_eq!(+ fs::read_dir(f.data_dir.join("sessions")).unwrap().count(),+ transcripts_before+ );+ assert_eq!(+ fs::read_dir(visualizations::base_dir(&f.data_dir))+ .unwrap()+ .count(),+ 1+ );+ assert_eq!(fs::read_to_string(chart).unwrap(), "source bytes");+}diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 4e3f7fb75..1fe85b381 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -6329,11 +6329,14 @@ mod tests {let chart = dir.join("chart.html");std::fs::write(&chart, "<p>chart</p>").unwrap();std::fs::write(dir.join("unused.html"), "<p>unused</p>").unwrap();- let text = format!("::visualize{{\"path\":\"{}\"}}", chart.display());+ let text = format!("::visualize{}", json!({"path": chart}));append_message(&db,&source.id,- &user_msg("viz-1", &text, "2025-05-01T00:00:00Z"),+ &UiMessage {+ role: "assistant".into(),+ ..user_msg("viz-1", &text, "2025-05-01T00:00:00Z")+ },None,).unwrap();@@ -6347,7 +6350,7 @@ mod tests {let child_chart = child_dir.join("chart.html");assert_eq!(child.messages[0].content,- format!("::visualize{{\"path\":\"{}\"}}", child_chart.display())+ format!("::visualize{}", json!({"path": child_chart})));assert!(!child_dir.join("unused.html").exists());delete_session(&db, &source.id).unwrap();diff --git a/crates/host-core/src/sessions/fork_files.rs b/crates/host-core/src/sessions/fork_files.rsindex 0177e5d05..eae13a390 100644--- a/crates/host-core/src/sessions/fork_files.rs+++ b/crates/host-core/src/sessions/fork_files.rs@@ -9,9 +9,16 @@ use serde_json::Value;use crate::transcripts::{CompactionRecord, MessageRecord};use crate::{scratch, visualizations};+#[derive(Clone, Copy)]+enum ForkDirectory {+ Scratch,+ Visualization,+}+/// Roll back copied inputs if transcript/index publication fails.pub(super) struct ForkFiles {destination: PathBuf,+ kind: ForkDirectory,committed: bool,}@@ -23,10 +30,17 @@ impl ForkFiles {impl Drop for ForkFiles {fn drop(&mut self) {- if !self.committed && self.destination.exists() {- if let Err(error) = fs::remove_dir_all(&self.destination) {- tracing::warn!(%error, "fork attachment rollback failed");+ if self.committed {+ return;+ }+ match self.kind {+ ForkDirectory::Visualization => visualizations::remove_session_root(&self.destination),+ ForkDirectory::Scratch if self.destination.exists() => {+ if let Err(error) = fs::remove_dir_all(&self.destination) {+ tracing::warn!(%error, "fork attachment rollback failed");+ }}+ ForkDirectory::Scratch => {}}}}@@ -127,6 +141,7 @@ pub(super) fn preserve(}let guard = ForkFiles {destination,+ kind: ForkDirectory::Scratch,committed: false,};let pasted = source.join("pasted");@@ -206,6 +221,82 @@ fn copy_regular_file(path: &Path, target: &Path) -> Result<()> {Ok(())}+// Only completed assistant text and model-context text can hold cards. Do+// not rewrite raw shell commands, tool results, thinking, or code examples.+fn rewrite_visualization_value(+ value: &mut Value,+ source_id: &str,+ file: &str,+ target: &str,+) -> bool {+ match value {+ Value::String(text) => visualizations::references::rewrite(text, source_id, file, target),+ Value::Array(values) => {+ let mut changed = false;+ for value in values {+ changed |= rewrite_visualization_value(value, source_id, file, target);+ }+ changed+ }+ Value::Object(values) => {+ if values+ .get("role")+ .and_then(Value::as_str)+ .is_some_and(|role| role != "assistant")+ || values+ .get("type")+ .and_then(Value::as_str)+ .is_some_and(|kind| kind != "text")+ {+ return false;+ }+ let mut changed = false;+ for key in [+ "text",+ "content",+ "blocks",+ "summary",+ "messages",+ "retainedTail",+ "details",+ ] {+ if let Some(value) = values.get_mut(key) {+ changed |= rewrite_visualization_value(value, source_id, file, target);+ }+ }+ changed+ }+ _ => false,+ }+}++fn rewrite_visualizations(+ records: &mut [MessageRecord],+ compactions: &mut [CompactionRecord],+ source_id: &str,+ file: &str,+ target: &str,+) -> bool {+ let mut changed = false;+ for record in records+ .iter_mut()+ .filter(|record| record.role == "assistant" && record.tool_name.is_none())+ {+ changed |= rewrite_visualization_value(&mut record.blocks, source_id, file, target);+ }+ for record in compactions {+ changed |=+ visualizations::references::rewrite(&mut record.summary, source_id, file, target);+ for value in [&mut record.retained_tail, &mut record.details]+ .into_iter()+ .flatten()+ {+ changed |= rewrite_visualization_value(value, source_id, file, target);+ }+ }+ changed+}+/// Give a fork its own copies of the visualization fragments its transcript/// references (D671), so deleting the source session cannot break the/// child's cards. Unreferenced fragments stay behind.@@ -220,47 +311,65 @@ pub(super) fn preserve_visualizations(.ok_or_else(|| anyhow!("invalid source session id"))?;let destination = visualizations::session_dir(data_dir, child_id).ok_or_else(|| anyhow!("invalid child session id"))?;- if destination.try_exists()? {+ // A missing or redirected source remains unavailable, like an expired+ // scratch input. An empty guard owns nothing and must not clean up paths.+ let source = match visualizations::validate_session_root(&source) {+ Ok(source) => source,+ Err(error)+ if matches!(+ error.kind(),+ std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied+ ) =>+ {+ tracing::warn!(%error, "fork visualization source unavailable");+ return Ok(ForkFiles {+ destination,+ kind: ForkDirectory::Visualization,+ committed: true,+ });+ }+ Err(error) => return Err(error.into()),+ };+ let canonical_destination = visualizations::validate_session_root(&destination)?;+ if canonical_destination.try_exists()? {return Err(anyhow!("fork visualization directory already exists"));}let guard = ForkFiles {- destination,+ destination: canonical_destination,+ kind: ForkDirectory::Visualization,committed: false,};- // Visualizations are disposable like scratch: a missing directory does- // not prevent branching, and a symlinked one is never followed.- for directory in [visualizations::base_dir(data_dir), source.clone()] {- match fs::symlink_metadata(&directory) {- Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {}- Ok(_) => return Ok(guard),- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(guard),- Err(error) => return Err(error.into()),- }- }- for entry in fs::read_dir(&source)? {+ visualizations::validate_session_root(&source)?;+ let entries = match fs::read_dir(&source) {+ Ok(entries) => entries,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(guard),+ Err(error) => return Err(error.into()),+ };+ for entry in entries {let entry = entry?;let path = entry.path();- if !entry.file_type()?.is_file() || !visualizations::is_fragment_path(&path) {+ if !visualizations::is_regular_fragment_file(&path)? {continue;}- let target = guard.destination.join(entry.file_name());- let source_path = path.to_string_lossy();- let target_path = target.to_string_lossy();- let referenced = rewrite(records, compactions, &source_path, &target_path);- // Renderer path references may use forward slashes on Windows.- #[cfg(windows)]- let referenced = referenced- | rewrite(- records,- compactions,- &source_path.replace('\\', "/"),- &target_path.replace('\\', "/"),- );- if !referenced {+ let name = entry.file_name();+ let Some(file_name) = name.to_str() else {+ continue;+ };+ let target_reference = destination.join(&name);+ if !rewrite_visualizations(+ records,+ compactions,+ source_id,+ file_name,+ &target_reference.to_string_lossy(),+ ) {continue;}- fs::create_dir_all(&guard.destination)?;- copy_regular_file(&path, &target)?;+ // Use the canonical data-parent spelling chosen at the start, but+ // advertise the child's original data-directory spelling.+ visualizations::ensure_session_root(&guard.destination)?;+ visualizations::validate_session_root(&source)?;+ copy_regular_file(&path, &guard.destination.join(&name))?;}Ok(guard)}@@ -390,4 +499,235 @@ mod tests {"/scratch/source/pasted/note.txt.bak");}++ fn visualization_text(path: &str) -> String {+ format!("::visualize{}", json!({"path": path, "title": "Chart"}))+ }++ fn assistant(text: &str) -> MessageRecord {+ let mut record = message(json!([{"type": "text", "text": text}]));+ record.role = "assistant".into();+ record+ }++ #[test]+ fn visualization_fork_correlates_relocated_paths_and_compaction_json() {+ let data = tempfile::tempdir().unwrap();+ let source = visualizations::session_dir(data.path(), "source").unwrap();+ fs::create_dir_all(&source).unwrap();+ fs::write(source.join("chart.html"), "chart bytes").unwrap();+ fs::write(source.join("checkpoint.html"), "checkpoint bytes").unwrap();+ fs::write(source.join("unused.html"), "unused").unwrap();+ let old = "/retired profile/visualizations/source/chart.html";+ let windows = r"C:\retired profile\visualizations\source\checkpoint.html";+ let mut records = vec![assistant(&visualization_text(old))];+ let mut compactions: Vec<CompactionRecord> = vec![serde_json::from_value(json!({+ "id": "checkpoint", "summary": visualization_text(windows),+ "throughMessageId": "message", "tokensBefore": 10, "createdAt": "now",+ "retainedTail": [{"role": "assistant", "content": visualization_text(old)}],+ "details": {"summary": visualization_text(windows)}+ }))+ .unwrap()];+ let guard = preserve_visualizations(+ data.path(),+ "source",+ "child",+ &mut records,+ &mut compactions,+ )+ .unwrap();+ let child = visualizations::session_dir(data.path(), "child").unwrap();+ assert_eq!(+ fs::read_to_string(child.join("chart.html")).unwrap(),+ "chart bytes"+ );+ assert_eq!(+ fs::read_to_string(child.join("checkpoint.html")).unwrap(),+ "checkpoint bytes"+ );+ assert!(!child.join("unused.html").exists());+ assert_eq!(+ records[0].blocks[0]["text"],+ visualization_text(&child.join("chart.html").to_string_lossy())+ );+ assert_eq!(+ compactions[0].summary,+ visualization_text(&child.join("checkpoint.html").to_string_lossy())+ );+ assert_eq!(+ compactions[0].retained_tail.as_ref().unwrap()[0]["content"],+ records[0].blocks[0]["text"]+ );+ assert_eq!(+ compactions[0].details.as_ref().unwrap()["summary"],+ compactions[0].summary+ );+ drop(guard);+ assert!(!child.exists());+ assert!(source.join("chart.html").exists());+ }++ #[test]+ fn visualization_fork_accepts_canonical_references_with_a_data_directory_alias() {+ let data = tempfile::tempdir().unwrap();+ let alias_parent = tempfile::tempdir().unwrap();+ let alias = alias_parent.path().join("profile");+ crate::session_worktrees::test_support::link_dir(data.path(), &alias);+ let source = visualizations::session_dir(&alias, "source").unwrap();+ fs::create_dir_all(&source).unwrap();+ let file = source.join("chart.html");+ fs::write(&file, "chart bytes").unwrap();+ let canonical = crate::workspace::simple_canonicalize(&file).unwrap();+ let mut records = vec![assistant(&visualization_text(&canonical.to_string_lossy()))];+ preserve_visualizations(&alias, "source", "child", &mut records, &mut [])+ .unwrap()+ .commit();+ let child = visualizations::session_dir(&alias, "child").unwrap();+ assert_eq!(+ fs::read_to_string(child.join("chart.html")).unwrap(),+ "chart bytes"+ );+ assert_eq!(+ records[0].blocks[0]["text"],+ visualization_text(&child.join("chart.html").to_string_lossy())+ );+ }++ #[test]+ fn visualization_fork_leaves_code_examples_tool_strings_and_foreign_references_untouched() {+ let data = tempfile::tempdir().unwrap();+ let source = visualizations::session_dir(data.path(), "source").unwrap();+ fs::create_dir_all(&source).unwrap();+ for name in ["code.html", "raw.html", "chart.html"] {+ fs::write(source.join(name), name).unwrap();+ }+ let code = visualization_text(&source.join("code.html").to_string_lossy());+ let raw = visualization_text(&source.join("raw.html").to_string_lossy());+ let foreign = visualization_text("/old/visualizations/other/chart.html");+ let text = format!("Example:\n```json\n{code}\n```\nNot a card.\n {code}\n{foreign}");+ let mut tool = message(json!([{"type": "text", "text": raw}]));+ tool.role = "tool".into();+ let mut caller = assistant("");+ caller.blocks = json!([+ {"type": "tool_call", "name": "Bash", "args": {"command": raw, "content": raw}},+ {"type": "thinking", "text": raw}+ ]);+ let mut records = vec![assistant(&text), tool, caller];+ let before = records+ .iter()+ .map(|record| record.blocks.clone())+ .collect::<Vec<_>>();+ let mut compactions: Vec<CompactionRecord> = vec![serde_json::from_value(json!({+ "id": "checkpoint", "summary": "No cards", "throughMessageId": "message", "tokensBefore": 10, "createdAt": "now",+ "retainedTail": [{"role": "tool", "content": raw}, {"role": "assistant", "blocks": records[2].blocks}],+ "details": {"raw": raw, "summary": text}+ })).unwrap()];+ let compactions_before = serde_json::to_value(&compactions).unwrap();+ preserve_visualizations(+ data.path(),+ "source",+ "child",+ &mut records,+ &mut compactions,+ )+ .unwrap()+ .commit();+ assert_eq!(+ records+ .iter()+ .map(|record| record.blocks.clone())+ .collect::<Vec<_>>(),+ before+ );+ assert_eq!(+ serde_json::to_value(&compactions).unwrap(),+ compactions_before+ );+ assert!(!visualizations::session_dir(data.path(), "child")+ .unwrap()+ .exists());+ }++ #[test]+ fn visualization_rollback_does_not_follow_a_replaced_base() {+ let data = tempfile::tempdir().unwrap();+ let source = visualizations::session_dir(data.path(), "source").unwrap();+ fs::create_dir_all(&source).unwrap();+ fs::write(source.join("chart.html"), "chart bytes").unwrap();+ let mut records = vec![assistant(&visualization_text(+ &source.join("chart.html").to_string_lossy(),+ ))];+ let guard =+ preserve_visualizations(data.path(), "source", "child", &mut records, &mut []).unwrap();+ let external = tempfile::tempdir().unwrap();+ let keep = external.path().join("child/keep.html");+ fs::create_dir_all(keep.parent().unwrap()).unwrap();+ fs::write(&keep, "irreplaceable").unwrap();+ fs::rename(+ visualizations::base_dir(data.path()),+ data.path().join("old-visualizations"),+ )+ .unwrap();+ crate::session_worktrees::test_support::link_dir(+ external.path(),+ &visualizations::base_dir(data.path()),+ );+ drop(guard);+ assert_eq!(fs::read_to_string(keep).unwrap(), "irreplaceable");+ }++ #[test]+ fn visualization_fork_copies_only_referenced_regular_safe_html_files() {+ let data = tempfile::tempdir().unwrap();+ let source = visualizations::session_dir(data.path(), "source").unwrap();+ fs::create_dir_all(&source).unwrap();+ fs::write(source.join("chart.html"), "chart bytes").unwrap();+ for name in ["unused.html", "a..b.html", ".hidden.html", "code.js"] {+ fs::write(source.join(name), "not a card").unwrap();+ }+ let external = tempfile::tempdir().unwrap();+ let important = external.path().join("important.html");+ fs::write(&important, "irreplaceable").unwrap();+ crate::session_worktrees::test_support::link_dir(+ external.path(),+ &source.join("directory.html"),+ );+ crate::session_worktrees::test_support::try_link_file(+ &important,+ &source.join("linked.html"),+ );+ let rejected = [+ "directory.html",+ "linked.html",+ "a..b.html",+ ".hidden.html",+ "code.js",+ "missing.html",+ ]+ .map(|name| visualization_text(&source.join(name).to_string_lossy()));+ let text = format!(+ "{}\n{}",+ visualization_text(&source.join("chart.html").to_string_lossy()),+ rejected.join("\n")+ );+ let mut records = vec![assistant(&text)];+ preserve_visualizations(data.path(), "source", "child", &mut records, &mut [])+ .unwrap()+ .commit();+ let child = visualizations::session_dir(data.path(), "child").unwrap();+ assert_eq!(fs::read_dir(&child).unwrap().count(), 1);+ assert_eq!(+ fs::read_to_string(child.join("chart.html")).unwrap(),+ "chart bytes"+ );+ assert_eq!(+ records[0].blocks[0]["text"],+ format!(+ "{}\n{}",+ visualization_text(&child.join("chart.html").to_string_lossy()),+ rejected.join("\n")+ )+ );+ assert_eq!(fs::read_to_string(important).unwrap(), "irreplaceable");+ }}diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex 6d3f1b88d..44e59a27d 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -1203,8 +1203,8 @@ pub async fn execute_tool_with_path_access(if let (Some(dir), Some(path)) =(visualization_root, args.get("path").and_then(Value::as_str)){- if crate::workspace::lexically_inside(dir, path) {- if let Err(error) = std::fs::create_dir_all(dir) {+ if crate::visualizations::contains_session_path(dir, path) {+ if let Err(error) = crate::visualizations::ensure_session_root(dir) {tracing::warn!(%error, "failed to create visualization directory");}}@@ -1343,7 +1343,8 @@ fn ensure_visualization_fragment(let direct_child = roots.iter().find(|root| root.kind == ToolRoot::Visualization)- .and_then(|root| std::fs::canonicalize(&root.path).ok())+ .filter(|root| root.allows_implicit_access())+ .and_then(|root| crate::workspace::simple_canonicalize(&root.path).ok()).is_some_and(|root| resolved.parent() == Some(root.as_path()));if !direct_child || !crate::visualizations::is_fragment_path(resolved) {return Err((@@ -1615,9 +1616,11 @@ fn tool_write(return Err(ignore_rules::denied_error(path));}ensure_visualization_fragment(roots, root_kind, &resolved)?;- if let Some(parent) = resolved.parent() {- std::fs::create_dir_all(parent)- .map_err(|e| ("TOOL_FAILED".into(), format!("mkdir failed: {e}")))?;+ if root_kind != ToolRoot::Visualization {+ if let Some(parent) = resolved.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|e| ("TOOL_FAILED".into(), format!("mkdir failed: {e}")))?;+ }}std::fs::write(&resolved, &content).map_err(|e| {if e.kind() == std::io::ErrorKind::NotFound {@@ -1779,6 +1782,8 @@ fn tool_edit()?;if success.delete_file {+ ensure_visualization_fragment(roots, root_kind, &resolved)+ .map_err(|(code, message)| hashline::ToolError::new(code, message))?;std::fs::remove_file(&resolved).map_err(|e| hashline::ToolError::new("TOOL_FAILED", format!("delete failed: {e}")))?;hashline::invalidate_path(hashline, &canonical);@@ -1810,11 +1815,15 @@ fn tool_edit("MV destination resolves to the source file; choose a different destination",));}- if let Some(parent) = dest_resolved.parent() {- std::fs::create_dir_all(parent).map_err(|e| {- hashline::ToolError::new("TOOL_FAILED", format!("mkdir failed: {e}"))- })?;+ if dest_root != ToolRoot::Visualization {+ if let Some(parent) = dest_resolved.parent() {+ std::fs::create_dir_all(parent).map_err(|e| {+ hashline::ToolError::new("TOOL_FAILED", format!("mkdir failed: {e}"))+ })?;+ }}+ ensure_visualization_fragment(roots, root_kind, &resolved)+ .map_err(|(code, message)| hashline::ToolError::new(code, message))?;std::fs::write(&dest_resolved, &bytes).map_err(|e| hashline::ToolError::new("TOOL_FAILED", format!("write failed: {e}")))?;std::fs::remove_file(&resolved)@@ -1839,6 +1848,8 @@ fn tool_edit(}));}+ ensure_visualization_fragment(roots, root_kind, &resolved)+ .map_err(|(code, message)| hashline::ToolError::new(code, message))?;std::fs::write(&resolved, &bytes).map_err(|e| hashline::ToolError::new("TOOL_FAILED", format!("write failed: {e}")))?;hashline::record_write(hashline, &canonical, &file, &success.tag);diff --git a/crates/host-core/src/visualizations.rs b/crates/host-core/src/visualizations.rsindex ae7d2fb81..4992884f5 100644--- a/crates/host-core/src/visualizations.rs+++ b/crates/host-core/src/visualizations.rs@@ -9,6 +9,10 @@use std::collections::HashSet;use std::path::{Path, PathBuf};+use std::{fs, io};++pub(crate) mod files;+pub(crate) mod references;/// Session ids come from our own DB (UUIDs), but stay defensive: an id that/// could traverse out of the base directory gets no directory at all.@@ -31,6 +35,125 @@ pub fn session_dir(data_dir: &Path, session_id: &str) -> Option<PathBuf> {Some(base_dir(data_dir).join(session_id))}+/// Validate the owned base and session entries on every use, including before+/// their lazy creation. The data directory itself may legitimately be an alias+/// (for example /var on macOS); neither owned entry may redirect elsewhere.+pub(crate) fn validate_session_root(root: &Path) -> io::Result<PathBuf> {+ let (data, id) = session_root_parts(root)?;+ let canonical_base = validated_base(data)?;+ let canonical_root = canonical_base.join(id);+ validate_directory(root, &canonical_root)?;+ Ok(canonical_root)+}++fn session_root_parts(root: &Path) -> io::Result<(&Path, &str)> {+ let id = root+ .file_name()+ .and_then(|name| name.to_str())+ .filter(|id| safe_session_id(id))+ .ok_or_else(|| {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ "invalid visualization session root",+ )+ })?;+ let base = root+ .parent()+ .filter(|base| {+ base.file_name()+ .is_some_and(|name| name == "visualizations")+ })+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid visualization base"))?;+ let data = base.parent().ok_or_else(|| {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ "invalid visualization data directory",+ )+ })?;+ Ok((data, id))+}++/// Recognize the advertised spelling or a canonical data-directory alias.+/// Canonicalize only the data parent, never a possibly redirected owned root.+/// This identifies a claimed visualization path; validation still decides+/// whether it is safe, including when it also lies inside the workspace.+pub(crate) fn contains_session_path(root: &Path, input: &str) -> bool {+ if crate::workspace::lexically_inside(root, input) {+ return true;+ }+ let Ok((data, id)) = session_root_parts(root) else {+ return false;+ };+ crate::workspace::simple_canonicalize(data).is_ok_and(|data| {+ crate::workspace::lexically_inside(&data.join("visualizations").join(id), input)+ })+}++fn validated_base(data_dir: &Path) -> io::Result<PathBuf> {+ let canonical = crate::workspace::simple_canonicalize(data_dir)?.join("visualizations");+ validate_directory(&base_dir(data_dir), &canonical)?;+ Ok(canonical)+}++fn validate_directory(path: &Path, expected: &Path) -> io::Result<()> {+ let metadata = match fs::symlink_metadata(path) {+ Ok(metadata) => metadata,+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error),+ };+ if !metadata.is_dir() || is_redirected(&metadata) {+ return Err(io::Error::new(+ io::ErrorKind::PermissionDenied,+ "visualization directory is redirected or not a regular directory",+ ));+ }+ let canonical = crate::workspace::simple_canonicalize(path)?;+ // Use the resolver's platform-aware comparisons (Windows is case-insensitive).+ if !crate::workspace::lexically_inside(expected, &canonical.to_string_lossy())+ || !crate::workspace::lexically_inside(&canonical, &expected.to_string_lossy())+ {+ return Err(io::Error::new(+ io::ErrorKind::PermissionDenied,+ "visualization directory is redirected",+ ));+ }+ Ok(())+}++fn is_redirected(metadata: &fs::Metadata) -> bool {+ #[cfg(windows)]+ {+ use std::os::windows::fs::MetadataExt;+ if metadata.file_attributes()+ & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT+ != 0+ {+ return true;+ }+ }+ metadata.file_type().is_symlink()+}++/// Create one owned directory at a time, checking both before and after each+/// step. Never let create_dir_all follow a replaced base/session entry.+pub(crate) fn ensure_session_root(root: &Path) -> io::Result<PathBuf> {+ let canonical = validate_session_root(root)?;+ let base = canonical+ .parent()+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid visualization base"))?;+ for directory in [base, canonical.as_path()] {+ // Revalidate the chain, not just the leaf, after a previous operation.+ validate_session_root(root)?;+ match fs::create_dir(directory) {+ Ok(()) => {}+ Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}+ Err(error) => return Err(error),+ }+ validate_session_root(root)?;+ }+ Ok(canonical)+}+/// True when `path` names an `.html` file (lowercase `.html` only).pub fn is_fragment_path(path: &Path) -> bool {// Mirrors `isGenUiFileName` in packages/shared/src/gen-ui.ts.@@ -47,14 +170,38 @@ pub fn is_fragment_path(path: &Path) -> bool {&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))}+/// Fork only real regular fragments; file links and Windows reparse points+/// cannot turn a transcript reference into an external read.+pub(crate) fn is_regular_fragment_file(path: &Path) -> io::Result<bool> {+ if !is_fragment_path(path) {+ return Ok(false);+ }+ match fs::symlink_metadata(path) {+ Ok(metadata) => Ok(metadata.is_file() && !is_redirected(&metadata)),+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),+ Err(error) => Err(error),+ }+}+/// Remove a session's visualization directory (idempotent, best-effort).pub fn remove_session_dir(data_dir: &Path, session_id: &str) {if let Some(dir) = session_dir(data_dir, session_id) {- if dir.exists() {- if let Err(error) = std::fs::remove_dir_all(&dir) {- tracing::warn!(path = %dir.display(), %error, "visualization cleanup failed");- }+ remove_session_root(&dir);+ }+}++/// Also used by fork rollback. Recheck the base at deletion time: a root+/// validated during creation is not authority after directory replacement.+pub(crate) fn remove_session_root(root: &Path) {+ let result = (|| -> io::Result<()> {+ let dir = validate_session_root(root)?;+ match fs::remove_dir_all(&dir) {+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),+ result => result,}+ })();+ if let Err(error) = result {+ tracing::warn!(path = %root.display(), %error, "visualization cleanup failed");}}@@ -62,24 +209,31 @@ pub fn remove_session_dir(data_dir: &Path, session_id: &str) {/// sessions keep their cards regardless of age — the transcript still/// references them.pub fn sweep(data_dir: &Path, live_session_ids: &HashSet<String>) {- let base = base_dir(data_dir);- let Ok(entries) = std::fs::read_dir(&base) else {- return;- };- for entry in entries.flatten() {- let path = entry.path();- // Do not follow symlinks out of the base directory.- let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);- if !is_dir {- continue;- }- let name = entry.file_name().to_string_lossy().to_string();- if live_session_ids.contains(&name) {- continue;- }- if let Err(error) = std::fs::remove_dir_all(&path) {- tracing::warn!(path = %path.display(), %error, "visualization sweep failed");+ let result = (|| -> io::Result<()> {+ let base = validated_base(data_dir)?;+ let entries = match fs::read_dir(&base) {+ Ok(entries) => entries,+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error),+ };+ for entry in entries {+ let entry = entry?;+ let name = entry.file_name();+ let Some(id) = name.to_str().filter(|id| safe_session_id(id)) else {+ continue;+ };+ if live_session_ids.contains(id) || !entry.file_type()?.is_dir() {+ continue;+ }+ // An iterator survives renaming its directory. Revalidate the+ // owned base before using any entry path for deletion.+ validated_base(data_dir)?;+ remove_session_root(&base.join(id));}+ Ok(())+ })();+ if let Err(error) = result {+ tracing::warn!(%error, "visualization sweep failed");}}@@ -140,14 +294,90 @@ mod tests {.unwrap().set_modified(ancient).unwrap();- std::fs::File::open(&live)+ let mut directory = std::fs::File::options();+ directory.read(true);+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ use windows_sys::Win32::Storage::FileSystem::{+ FILE_FLAG_BACKUP_SEMANTICS, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES,+ };+ directory+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)+ .access_mode(FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES);+ }+ directory+ .open(&live).unwrap().set_modified(ancient)- .ok();+ .unwrap();let mut ids = HashSet::new();ids.insert("live".to_string());sweep(dir.path(), &ids);assert!(card.exists());assert!(!orphan.exists());}++ #[test]+ fn sweep_rejects_a_redirected_base_without_deleting_external_data() {+ let data = tempdir().unwrap();+ let external = tempdir().unwrap();+ let important = external.path().join("important").join("keep.html");+ std::fs::create_dir_all(important.parent().unwrap()).unwrap();+ std::fs::write(&important, "irreplaceable").unwrap();+ crate::session_worktrees::test_support::link_dir(external.path(), &base_dir(data.path()));+ sweep(data.path(), &HashSet::new());+ assert_eq!(std::fs::read_to_string(important).unwrap(), "irreplaceable");+ }++ #[test]+ fn session_cleanup_rejects_a_redirected_base() {+ let data = tempdir().unwrap();+ let external = tempdir().unwrap();+ let important = external.path().join("source").join("keep.html");+ std::fs::create_dir_all(important.parent().unwrap()).unwrap();+ std::fs::write(&important, "irreplaceable").unwrap();+ crate::session_worktrees::test_support::link_dir(external.path(), &base_dir(data.path()));+ remove_session_dir(data.path(), "source");+ assert_eq!(std::fs::read_to_string(important).unwrap(), "irreplaceable");+ }++ #[test]+ fn sweep_preserves_directories_that_cannot_be_session_ids() {+ let data = tempdir().unwrap();+ let important = base_dir(data.path())+ .join("important documents")+ .join("keep.html");+ std::fs::create_dir_all(important.parent().unwrap()).unwrap();+ std::fs::write(&important, "irreplaceable").unwrap();+ sweep(data.path(), &HashSet::new());+ assert_eq!(std::fs::read_to_string(important).unwrap(), "irreplaceable");+ }++ #[test]+ fn cleanup_allows_a_data_directory_alias_but_not_a_session_link() {+ let data = tempdir().unwrap();+ let alias_parent = tempdir().unwrap();+ let alias = alias_parent.path().join("profile");+ crate::session_worktrees::test_support::link_dir(data.path(), &alias);+ let live = session_dir(&alias, "live").unwrap();+ let orphan = session_dir(&alias, "orphan").unwrap();+ std::fs::create_dir_all(&live).unwrap();+ std::fs::create_dir_all(&orphan).unwrap();+ std::fs::write(live.join("keep.html"), "live").unwrap();+ let external = tempdir().unwrap();+ std::fs::write(external.path().join("keep.html"), "external").unwrap();+ let link = session_dir(&alias, "linked").unwrap();+ crate::session_worktrees::test_support::link_dir(external.path(), &link);+ sweep(&alias, &HashSet::from(["live".into()]));+ remove_session_dir(&alias, "linked");+ assert_eq!(+ std::fs::read_to_string(external.path().join("keep.html")).unwrap(),+ "external"+ );+ assert!(live.join("keep.html").exists());+ assert!(!orphan.exists());+ remove_session_dir(&alias, "live");+ assert!(!live.exists());+ }}diff --git a/crates/host-core/src/visualizations/files.rs b/crates/host-core/src/visualizations/files.rsnew file mode 100644index 000000000..2e8306a8e--- /dev/null+++ b/crates/host-core/src/visualizations/files.rs@@ -0,0 +1,99 @@+//! Bounded native reads for the private GenUI protocol bridge.+//!+//! Only the data directory is trusted. Owned directories and the leaf are+//! opened without following redirects, and stay bound to native handles.++use std::fs::File;+use std::io::Read;+use std::path::Path;++#[cfg(unix)]+#[path = "files/unix.rs"]+mod unix;+#[cfg(windows)]+#[path = "files/windows.rs"]+mod windows;++pub(crate) const MAX_FRAGMENT_BYTES: usize = 2_097_152;++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum FragmentReadError {+ NotFound,+ TooLarge,+}++impl std::fmt::Display for FragmentReadError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(match self {+ Self::NotFound => "not-found",+ Self::TooLarge => "too-large",+ })+ }+}++impl std::error::Error for FragmentReadError {}++/// Read one direct HTML fragment, preserving its bytes without decoding.+/// Missing, redirected, non-regular, invalid, and inaccessible entries all+/// fail closed without exposing paths through the private RPC error contract.+pub fn read_fragment(+ data_dir: &Path,+ session_id: &str,+ file_name: &str,+) -> Result<Vec<u8>, FragmentReadError> {+ if !valid_names(session_id, file_name) {+ return Err(FragmentReadError::NotFound);+ }+ #[cfg(unix)]+ {+ unix::read_fragment(data_dir, session_id, file_name)+ }+ #[cfg(windows)]+ {+ windows::read_fragment(data_dir, session_id, file_name)+ }+ #[cfg(not(any(unix, windows)))]+ {+ let _ = data_dir;+ Err(FragmentReadError::NotFound)+ }+}++fn valid_names(session_id: &str, file_name: &str) -> bool {+ let path = Path::new(file_name);+ !session_id.is_empty()+ && session_id.len() <= 128+ && session_id+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))+ && !file_name.contains(['/', '\\'])+ && path.file_name().is_some_and(|name| name == file_name)+ && super::is_fragment_path(path)+}++fn read_open_file(file: File) -> Result<Vec<u8>, FragmentReadError> {+ let metadata = file.metadata().map_err(|_| FragmentReadError::NotFound)?;+ if !metadata.is_file() {+ return Err(FragmentReadError::NotFound);+ }+ read_bounded(file, metadata.len())+}++fn read_bounded(reader: impl Read, size: u64) -> Result<Vec<u8>, FragmentReadError> {+ if size > MAX_FRAGMENT_BYTES as u64 {+ return Err(FragmentReadError::TooLarge);+ }+ let mut bytes = Vec::with_capacity(size as usize);+ reader+ .take((MAX_FRAGMENT_BYTES + 1) as u64)+ .read_to_end(&mut bytes)+ .map_err(|_| FragmentReadError::NotFound)?;+ if bytes.len() > MAX_FRAGMENT_BYTES {+ return Err(FragmentReadError::TooLarge);+ }+ Ok(bytes)+}++#[cfg(test)]+#[path = "files/tests.rs"]+mod tests;diff --git a/crates/host-core/src/visualizations/files/tests.rs b/crates/host-core/src/visualizations/files/tests.rsnew file mode 100644index 000000000..404c32137--- /dev/null+++ b/crates/host-core/src/visualizations/files/tests.rs@@ -0,0 +1,223 @@+use super::*;+use std::fs;+use std::io::{self, Cursor};+use std::path::PathBuf;+use tempfile::{tempdir, TempDir};++pub(super) const SESSION: &str = "session-A";+pub(super) const FILE_NAME: &str = "chart.html";+pub(super) const ORIGINAL: &[u8] = "<p>Original \u{1f4ca}</p>\n".as_bytes();+pub(super) const VICTIM: &[u8] = b"private-marker";++pub(super) struct Fixture {+ pub temp: TempDir,+ pub data: PathBuf,+ pub session: PathBuf,+}++pub(super) fn fixture() -> Fixture {+ let temp = tempdir().expect("test directory");+ let data = temp.path().join("data");+ let session = data.join("visualizations").join(SESSION);+ fs::create_dir_all(&session).expect("test session");+ fs::write(session.join(FILE_NAME), ORIGINAL).expect("test fragment");+ Fixture {+ temp,+ data,+ session,+ }+}++#[test]+fn reads_regular_fragment_without_decoding_bytes() {+ let fixture = fixture();+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Ok(ORIGINAL.to_vec())+ );+ let bytes = b"<p>raw</p>\0\xff";+ fs::write(fixture.session.join(FILE_NAME), bytes).expect("raw fragment");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Ok(bytes.to_vec())+ );+}++#[test]+fn accepts_empty_and_exactly_two_mib_fragments() {+ let fixture = fixture();+ let path = fixture.session.join(FILE_NAME);+ fs::write(&path, []).expect("empty fragment");+ assert_eq!(read_fragment(&fixture.data, SESSION, FILE_NAME), Ok(vec![]));+ let bytes = vec![b'x'; MAX_FRAGMENT_BYTES];+ fs::write(&path, &bytes).expect("maximum fragment");+ assert_eq!(read_fragment(&fixture.data, SESSION, FILE_NAME), Ok(bytes));+}++#[test]+fn reports_too_large_above_two_mib() {+ let fixture = fixture();+ fs::write(+ fixture.session.join(FILE_NAME),+ vec![b'x'; MAX_FRAGMENT_BYTES + 1],+ )+ .expect("oversized fragment");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::TooLarge)+ );+}++#[test]+fn bounded_read_detects_growth_after_metadata_and_never_reads_past_cap_plus_one() {+ let mut reader = Cursor::new(vec![b'x'; MAX_FRAGMENT_BYTES + 100]);+ assert_eq!(+ read_bounded(&mut reader, 1),+ Err(FragmentReadError::TooLarge)+ );+ assert_eq!(reader.position(), (MAX_FRAGMENT_BYTES + 1) as u64);+ assert_eq!(+ read_bounded(Cursor::new([]), u64::MAX),+ Err(FragmentReadError::TooLarge)+ );+}++#[test]+fn rejects_invalid_sessions_and_direct_file_names() {+ let fixture = fixture();+ for session in [+ "",+ ".",+ "..",+ "../victim",+ "a/b",+ "a\\b",+ "a b",+ "\u{e9}",+ "a\0b",+ ] {+ assert!(+ !valid_names(session, FILE_NAME),+ "session validation {session:?}"+ );+ assert_eq!(+ read_fragment(&fixture.data, session, FILE_NAME),+ Err(FragmentReadError::NotFound),+ "session {session:?}"+ );+ }+ assert!(!valid_names(&"a".repeat(129), FILE_NAME));+ assert_eq!(+ read_fragment(&fixture.data, &"a".repeat(129), FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ for name in [+ "",+ ".html",+ "..",+ "../chart.html",+ "a/chart.html",+ "a\\chart.html",+ "/chart.html",+ "C:chart.html",+ "\\\\?\\C:\\chart.html",+ "chart.html/",+ "chart.html\\",+ ".hidden.html",+ "a..b.html",+ "chart.HTML",+ "chart.htm",+ "chart.html:stream",+ "*.html",+ "%2e%2e.html",+ "a\0.html",+ ] {+ assert!(!valid_names(SESSION, name), "filename validation {name:?}");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, name),+ Err(FragmentReadError::NotFound),+ "filename {name:?}"+ );+ }+ let name = format!("{}.html", "a".repeat(129));+ assert!(!valid_names(SESSION, &name));+ assert_eq!(+ read_fragment(&fixture.data, SESSION, &name),+ Err(FragmentReadError::NotFound)+ );+}++#[test]+fn valid_direct_names_and_session_length_match_contract() {+ let fixture = fixture();+ for name in ["chart.html", "a-v2_final.html", "a.b.html", "1.html"] {+ assert!(super::super::is_fragment_path(Path::new(name)));+ fs::write(fixture.session.join(name), ORIGINAL).expect("valid fragment");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, name),+ Ok(ORIGINAL.to_vec())+ );+ }+ let session = "a".repeat(128);+ let name = format!("{}.html", "a".repeat(128));+ let path = fixture.data.join("visualizations").join(&session);+ fs::create_dir(&path).expect("maximum session id");+ fs::write(path.join(&name), ORIGINAL).expect("maximum filename");+ assert_eq!(+ read_fragment(&fixture.data, &session, &name),+ Ok(ORIGINAL.to_vec())+ );+}++#[test]+fn missing_entries_and_nonregular_roots_or_leaf_fail_closed() {+ let fixture = fixture();+ assert_eq!(+ read_fragment(&fixture.data, SESSION, "missing.html"),+ Err(FragmentReadError::NotFound)+ );+ fs::create_dir(fixture.session.join("directory.html")).expect("directory leaf");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, "directory.html"),+ Err(FragmentReadError::NotFound)+ );+ assert_eq!(+ read_fragment(&fixture.data, "missing", FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ let plain = fixture.temp.path().join("plain");+ fs::write(&plain, []).expect("non-directory data");+ assert_eq!(+ read_fragment(&plain, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ let base = plain.with_file_name("other-data");+ fs::create_dir(&base).expect("other data");+ fs::write(base.join("visualizations"), []).expect("non-directory base");+ assert_eq!(+ read_fragment(&base, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ let bad_session = fixture.data.join("visualizations").join("plain-session");+ fs::write(&bad_session, []).expect("non-directory session");+ assert_eq!(+ read_fragment(&fixture.data, "plain-session", FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+}++#[test]+fn read_failures_have_only_fixed_error_codes() {+ struct BrokenReader;+ impl Read for BrokenReader {+ fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {+ Err(io::Error::other("private path must not escape"))+ }+ }+ assert_eq!(+ read_bounded(BrokenReader, 0),+ Err(FragmentReadError::NotFound)+ );+ assert_eq!(FragmentReadError::NotFound.to_string(), "not-found");+ assert_eq!(FragmentReadError::TooLarge.to_string(), "too-large");+}diff --git a/crates/host-core/src/visualizations/files/unix.rs b/crates/host-core/src/visualizations/files/unix.rsnew file mode 100644index 000000000..ab7fba4f2--- /dev/null+++ b/crates/host-core/src/visualizations/files/unix.rs@@ -0,0 +1,81 @@+use super::{read_open_file, FragmentReadError};+use std::ffi::CString;+use std::fs::{self, File, OpenOptions};+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};+use std::os::unix::fs::OpenOptionsExt;+use std::path::Path;++pub(super) fn read_fragment(+ data_dir: &Path,+ session_id: &str,+ file_name: &str,+) -> Result<Vec<u8>, FragmentReadError> {+ read_fragment_impl(data_dir, session_id, file_name, || {})+}++// Private seam for deterministic filesystem races. Production supplies no hook.+fn read_fragment_impl(+ data_dir: &Path,+ session_id: &str,+ file_name: &str,+ after_directory_pin: impl FnOnce(),+) -> Result<Vec<u8>, FragmentReadError> {+ // Canonical aliases are allowed only for the trusted data directory.+ let canonical = fs::canonicalize(data_dir).map_err(|_| FragmentReadError::NotFound)?;+ let data = OpenOptions::new()+ .read(true)+ .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)+ .open(canonical)+ .map_err(|_| FragmentReadError::NotFound)?;+ require_directory(&data)?;+ let base = open_relative(&data, "visualizations", true)?;+ let session = open_relative(&base, session_id, true)?;+ after_directory_pin();++ // Never resolve the leaf through an absolute path again. Renaming any+ // opened ancestor cannot redirect this directory capability to a victim.+ let leaf = open_relative(&session, file_name, false)?;+ read_open_file(leaf)+}++fn open_relative(parent: &File, name: &str, directory: bool) -> Result<File, FragmentReadError> {+ let name = CString::new(name).map_err(|_| FragmentReadError::NotFound)?;+ let flags = libc::O_RDONLY+ | libc::O_CLOEXEC+ | libc::O_NOFOLLOW+ | if directory {+ libc::O_DIRECTORY+ } else {+ // A FIFO with no writer must not block the filesystem worker.+ libc::O_NONBLOCK+ };+ // SAFETY: parent owns a live descriptor, name is NUL-terminated, and no+ // creation flag is set, so openat requires no variadic mode argument.+ let descriptor = unsafe { libc::openat(parent.as_raw_fd(), name.as_ptr(), flags) };+ if descriptor < 0 {+ return Err(FragmentReadError::NotFound);+ }+ // SAFETY: openat returned a new, exclusively owned descriptor. OwnedFd+ // closes it on every return path, including failed metadata checks.+ let file = File::from(unsafe { OwnedFd::from_raw_fd(descriptor) });+ if directory {+ require_directory(&file)?;+ }+ Ok(file)+}++fn require_directory(file: &File) -> Result<(), FragmentReadError> {+ if file+ .metadata()+ .map_err(|_| FragmentReadError::NotFound)?+ .is_dir()+ {+ Ok(())+ } else {+ Err(FragmentReadError::NotFound)+ }+}++#[cfg(test)]+#[path = "unix_tests.rs"]+mod tests;diff --git a/crates/host-core/src/visualizations/files/unix_tests.rs b/crates/host-core/src/visualizations/files/unix_tests.rsnew file mode 100644index 000000000..e9cb7ccfa--- /dev/null+++ b/crates/host-core/src/visualizations/files/unix_tests.rs@@ -0,0 +1,166 @@+use super::super::tests::{fixture, FILE_NAME, ORIGINAL, SESSION, VICTIM};+use super::super::{read_fragment, FragmentReadError};+use super::read_fragment_impl;+use std::ffi::CString;+use std::fs;+use std::os::unix::ffi::OsStrExt;+use std::os::unix::fs::symlink;+use std::sync::mpsc;+use std::time::Duration;++#[test]+fn allows_canonical_alias_for_trusted_data_directory() {+ let fixture = fixture();+ let alias = fixture.temp.path().join("data-alias");+ symlink(&fixture.data, &alias).expect("data alias");+ assert_eq!(+ read_fragment(&alias, SESSION, FILE_NAME),+ Ok(ORIGINAL.to_vec())+ );+}++#[test]+fn rejects_symlinked_visualization_base() {+ let fixture = fixture();+ let base = fixture.data.join("visualizations");+ let original_base = fixture.data.join("held-visualizations");+ fs::rename(&base, &original_base).expect("move original base");+ symlink(&original_base, &base).expect("base alias");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+}++#[test]+fn rejects_session_symlinks_including_same_root_session_alias() {+ let fixture = fixture();+ let victim = fixture.data.join("visualizations").join("session-B");+ fs::create_dir(&victim).expect("victim session");+ fs::write(victim.join(FILE_NAME), VICTIM).expect("victim fragment");+ let held = fixture.session.with_file_name("held-session");+ fs::rename(&fixture.session, &held).expect("move original session");+ symlink(&victim, &fixture.session).expect("same-root session alias");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ fs::remove_file(&fixture.session).expect("unlink alias");+ symlink(&held, &fixture.session).expect("alias to original session");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+}++#[test]+fn rejects_symlinked_leaf_even_when_target_is_owned() {+ let fixture = fixture();+ let leaf = fixture.session.join(FILE_NAME);+ let target = fixture.session.join("original.html");+ fs::rename(&leaf, &target).expect("move fragment");+ symlink(&target, &leaf).expect("leaf alias");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+}++#[test]+fn fifo_with_no_writer_is_rejected_without_blocking() {+ let fixture = fixture();+ let path = fixture.session.join("fifo.html");+ let name = CString::new(path.as_os_str().as_bytes()).expect("FIFO name");+ // SAFETY: the name is NUL-terminated and lives through mkfifo.+ assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0);+ let (sender, receiver) = mpsc::channel();+ let data = fixture.data.clone();+ let worker = std::thread::spawn(move || {+ sender+ .send(read_fragment(&data, SESSION, "fifo.html"))+ .expect("FIFO result");+ });+ assert_eq!(+ receiver+ .recv_timeout(Duration::from_secs(2))+ .expect("FIFO read must finish without a writer"),+ Err(FragmentReadError::NotFound)+ );+ worker.join().expect("FIFO worker");+}++#[test]+fn pinned_session_cannot_be_redirected_by_rename_and_symlink() {+ let fixture = fixture();+ let victim = fixture.data.join("visualizations").join("session-B");+ fs::create_dir(&victim).expect("victim session");+ fs::write(victim.join(FILE_NAME), VICTIM).expect("victim fragment");+ let held = fixture.session.with_file_name("held-session");+ let result = read_fragment_impl(&fixture.data, SESSION, FILE_NAME, || {+ fs::rename(&fixture.session, &held).expect("rename pinned session");+ symlink(&victim, &fixture.session).expect("replace visible session with victim alias");+ assert_eq!(+ fs::read(fixture.session.join(FILE_NAME)).expect("path-based attack control"),+ VICTIM+ );+ });+ // Leave the victim alias active during the actual leaf open/read: a+ // path-based leaf open, even O_NOFOLLOW, would return the victim here.+ fs::remove_file(&fixture.session).expect("unlink victim alias");+ fs::rename(&held, &fixture.session).expect("restore session");+ assert_eq!(result, Ok(ORIGINAL.to_vec()));+}++#[test]+fn pinned_session_survives_aba_restore_before_leaf_open() {+ let fixture = fixture();+ let victim = fixture.data.join("visualizations").join("session-B");+ fs::create_dir(&victim).expect("victim session");+ fs::write(victim.join(FILE_NAME), VICTIM).expect("victim fragment");+ let held = fixture.session.with_file_name("held-session");+ let result = read_fragment_impl(&fixture.data, SESSION, FILE_NAME, || {+ fs::rename(&fixture.session, &held).expect("rename pinned session");+ symlink(&victim, &fixture.session).expect("ABA victim alias");+ assert_eq!(+ fs::read(fixture.session.join(FILE_NAME)).expect("ABA attack control"),+ VICTIM+ );+ fs::remove_file(&fixture.session).expect("unlink ABA alias");+ fs::rename(&held, &fixture.session).expect("restore before leaf open");+ });+ assert_eq!(result, Ok(ORIGINAL.to_vec()));+}++#[test]+fn pinned_session_survives_visualization_base_replacement() {+ let fixture = fixture();+ let victim = fixture.temp.path().join("victim-base");+ fs::create_dir_all(victim.join(SESSION)).expect("victim base");+ fs::write(victim.join(SESSION).join(FILE_NAME), VICTIM).expect("victim fragment");+ let base = fixture.data.join("visualizations");+ let held = fixture.data.join("held-base");+ let result = read_fragment_impl(&fixture.data, SESSION, FILE_NAME, || {+ fs::rename(&base, &held).expect("rename pinned base");+ symlink(&victim, &base).expect("redirect visible base");+ assert_eq!(+ fs::read(base.join(SESSION).join(FILE_NAME)).expect("path-based attack control"),+ VICTIM+ );+ });+ fs::remove_file(&base).expect("unlink base alias");+ fs::rename(&held, &base).expect("restore base");+ assert_eq!(result, Ok(ORIGINAL.to_vec()));+}++#[test]+fn leaf_replaced_with_symlink_after_directory_pin_is_rejected() {+ let fixture = fixture();+ let victim = fixture.temp.path().join("victim.html");+ fs::write(&victim, VICTIM).expect("victim fragment");+ let leaf = fixture.session.join(FILE_NAME);+ let result = read_fragment_impl(&fixture.data, SESSION, FILE_NAME, || {+ fs::remove_file(&leaf).expect("remove original leaf");+ symlink(&victim, &leaf).expect("replace leaf with victim alias");+ });+ assert_eq!(result, Err(FragmentReadError::NotFound));+}diff --git a/crates/host-core/src/visualizations/files/windows.rs b/crates/host-core/src/visualizations/files/windows.rsnew file mode 100644index 000000000..113e66c5f--- /dev/null+++ b/crates/host-core/src/visualizations/files/windows.rs@@ -0,0 +1,118 @@+use super::{read_open_file, FragmentReadError};+use std::fs::{self, File, OpenOptions};+use std::os::windows::fs::{MetadataExt, OpenOptionsExt};+use std::os::windows::io::AsRawHandle;+use std::path::{Component, Path, PathBuf, Prefix};+use windows_sys::Win32::Storage::FileSystem::{+ GetFileType, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,+ FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_TYPE_DISK,+};++pub(super) fn read_fragment(+ data_dir: &Path,+ session_id: &str,+ file_name: &str,+) -> Result<Vec<u8>, FragmentReadError> {+ read_fragment_impl(data_dir, session_id, file_name, || {})+}++// Private seam for share/rename tests; it cannot be supplied through the RPC.+fn read_fragment_impl(+ data_dir: &Path,+ session_id: &str,+ file_name: &str,+ after_directory_pin: impl FnOnce(),+) -> Result<Vec<u8>, FragmentReadError> {+ // std canonicalize uses the native final handle path and retains the+ // extended drive/UNC prefix. Only this trusted root may resolve aliases.+ let canonical = fs::canonicalize(data_dir).map_err(|_| FragmentReadError::NotFound)?;+ let mut pins = Vec::new();+ // Pin from the volume/share root downwards, BEFORE resolving each next+ // component. Keeping just data/base/session handles would leave their+ // earlier ancestors free to be renamed or converted to junctions.+ for ancestor in directory_chain(&canonical)? {+ pins.push(open_directory(&ancestor)?);+ }+ let base = canonical.join("visualizations");+ pins.push(open_directory(&base)?);+ let session = base.join(session_id);+ pins.push(open_directory(&session)?);+ after_directory_pin();++ // All ancestors now deny write/delete sharing. Absolute resolution cannot+ // be redirected while they are held. The leaf denies those shares too,+ // including when a writable/deletable attacker handle already exists.+ let leaf = OpenOptions::new()+ .read(true)+ .share_mode(FILE_SHARE_READ)+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)+ .open(session.join(file_name))+ .map_err(|_| FragmentReadError::NotFound)?;+ let metadata = leaf.metadata().map_err(|_| FragmentReadError::NotFound)?;+ if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0+ || !metadata.is_file()+ || !is_disk(&leaf)+ {+ return Err(FragmentReadError::NotFound);+ }+ let result = read_open_file(leaf);+ // Explicitly keep every directory capability alive THROUGH the read.+ drop(pins);+ result+}++fn open_directory(path: &Path) -> Result<File, FragmentReadError> {+ let file = OpenOptions::new()+ .read(true)+ .access_mode(FILE_READ_ATTRIBUTES)+ .share_mode(FILE_SHARE_READ)+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)+ .open(path)+ .map_err(|_| FragmentReadError::NotFound)?;+ let metadata = file.metadata().map_err(|_| FragmentReadError::NotFound)?;+ if !metadata.is_dir()+ || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0+ || !is_disk(&file)+ {+ return Err(FragmentReadError::NotFound);+ }+ Ok(file)+}++fn is_disk(file: &File) -> bool {+ // SAFETY: File owns a live Windows handle for the duration of this call.+ unsafe { GetFileType(file.as_raw_handle()) == FILE_TYPE_DISK }+}++fn directory_chain(canonical: &Path) -> Result<Vec<PathBuf>, FragmentReadError> {+ let mut components = canonical.components();+ let prefix = match components.next() {+ Some(Component::Prefix(prefix))+ if matches!(+ prefix.kind(),+ Prefix::VerbatimDisk(_) | Prefix::VerbatimUNC(..)+ ) =>+ {+ prefix+ }+ _ => return Err(FragmentReadError::NotFound),+ };+ if components.next() != Some(Component::RootDir) {+ return Err(FragmentReadError::NotFound);+ }+ let mut current = PathBuf::from(prefix.as_os_str());+ current.push(Component::RootDir.as_os_str());+ let mut chain = vec![current.clone()];+ for component in components {+ if !matches!(component, Component::Normal(_)) {+ return Err(FragmentReadError::NotFound);+ }+ current.push(component.as_os_str());+ chain.push(current.clone());+ }+ Ok(chain)+}++#[cfg(test)]+#[path = "windows_tests.rs"]+mod tests;diff --git a/crates/host-core/src/visualizations/files/windows_tests.rs b/crates/host-core/src/visualizations/files/windows_tests.rsnew file mode 100644index 000000000..271fd6756--- /dev/null+++ b/crates/host-core/src/visualizations/files/windows_tests.rs@@ -0,0 +1,228 @@+use super::super::tests::{fixture, FILE_NAME, ORIGINAL, SESSION, VICTIM};+use super::super::{read_fragment, FragmentReadError};+use super::{directory_chain, read_fragment_impl};+use std::fs::{self, File, OpenOptions};+use std::os::windows::fs::{symlink_file, OpenOptionsExt};+use std::path::{Component, Path, PathBuf, Prefix};+use std::process::Command;+use windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION;+use windows_sys::Win32::Storage::FileSystem::{+ FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ,+ FILE_SHARE_WRITE, FILE_WRITE_DATA,+};++fn junction(link: &Path, target: &Path) {+ // Junctions need no symlink privilege. Both paths are controlled fixtures;+ // quoting protects spaces in the Windows temporary directory.+ let command = format!("mklink /J \"{}\" \"{}\"", link.display(), target.display());+ let output = Command::new("cmd")+ .args(["/D", "/C", &command])+ .output()+ .expect("create test junction");+ assert!(+ output.status.success(),+ "junction creation failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+}++fn open_writable_directory(path: &Path) -> std::io::Result<File> {+ OpenOptions::new()+ .write(true)+ .access_mode(FILE_WRITE_DATA)+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)+ .open(path)+}++#[test]+fn extended_drive_and_unc_paths_keep_their_root_components() {+ assert_eq!(+ directory_chain(Path::new(r"\\?\C:\Users\example\data")).expect("drive chain"),+ [+ PathBuf::from(r"\\?\C:\"),+ PathBuf::from(r"\\?\C:\Users"),+ PathBuf::from(r"\\?\C:\Users\example"),+ PathBuf::from(r"\\?\C:\Users\example\data"),+ ]+ );+ assert_eq!(+ directory_chain(Path::new(r"\\?\UNC\server\share\data")).expect("UNC chain"),+ [+ PathBuf::from(r"\\?\UNC\server\share\"),+ PathBuf::from(r"\\?\UNC\server\share\data"),+ ]+ );+ for path in [+ r"C:\data",+ r"C:data",+ r"\\.\pipe\data",+ r"\\?\C:\data\..\other",+ ] {+ assert_eq!(+ directory_chain(Path::new(path)),+ Err(FragmentReadError::NotFound)+ );+ }+}++#[test]+fn reads_canonical_drive_path_and_allows_trusted_data_junction_alias() {+ let fixture = fixture();+ let canonical = fs::canonicalize(&fixture.data).expect("canonical data");+ assert!(matches!(+ canonical.components().next(),+ Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::VerbatimDisk(_) | Prefix::VerbatimUNC(..))+ ));+ assert_eq!(+ read_fragment(&canonical, SESSION, FILE_NAME),+ Ok(ORIGINAL.to_vec())+ );+ let alias = fixture.temp.path().join("data-alias");+ junction(&alias, &fixture.data);+ assert_eq!(+ read_fragment(&alias, SESSION, FILE_NAME),+ Ok(ORIGINAL.to_vec())+ );+ fs::remove_dir(alias).expect("remove data junction");+}++#[test]+fn rejects_visualization_base_junction_even_to_original_base() {+ let fixture = fixture();+ let base = fixture.data.join("visualizations");+ let held = fixture.data.join("held-base");+ fs::rename(&base, &held).expect("move base");+ junction(&base, &held);+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ fs::remove_dir(base).expect("remove base junction");+}++#[test]+fn rejects_same_root_session_junction_alias() {+ let fixture = fixture();+ let victim = fixture.data.join("visualizations").join("session-B");+ fs::create_dir(&victim).expect("victim session");+ fs::write(victim.join(FILE_NAME), VICTIM).expect("victim fragment");+ let held = fixture.session.with_file_name("held-session");+ fs::rename(&fixture.session, &held).expect("move session");+ junction(&fixture.session, &victim);+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ fs::remove_dir(&fixture.session).expect("remove session junction");+}++#[test]+fn rejects_reparse_leaf_and_file_symlink_when_privilege_is_available() {+ let fixture = fixture();+ let leaf = fixture.session.join(FILE_NAME);+ fs::remove_file(&leaf).expect("remove original leaf");+ junction(&leaf, fixture.temp.path());+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ fs::remove_dir(&leaf).expect("remove leaf junction");+ let victim = fixture.temp.path().join("victim.html");+ fs::write(&victim, VICTIM).expect("victim fragment");+ match symlink_file(&victim, &leaf) {+ Ok(()) => assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ ),+ Err(error) if error.raw_os_error() == Some(1314) => {+ eprintln!("file symlink assertion skipped: Windows symlink privilege is unavailable");+ }+ Err(error) => panic!("create leaf symlink: {error}"),+ }+}++#[test]+fn pins_data_ancestors_base_and_session_until_read_completes() {+ let fixture = fixture();+ let base = fixture.data.join("visualizations");+ let paths = [+ fixture.temp.path(),+ fixture.data.as_path(),+ base.as_path(),+ fixture.session.as_path(),+ ];+ // Establish that write access is allowed without our share pins.+ for path in paths {+ drop(open_writable_directory(path).expect("unpinned writable directory"));+ }+ let result = read_fragment_impl(&fixture.data, SESSION, FILE_NAME, || {+ for path in paths {+ let replacement = path.with_file_name("rename-attempt");+ assert!(+ fs::rename(path, &replacement).is_err(),+ "pinned ancestor cannot be renamed"+ );+ let error =+ open_writable_directory(path).expect_err("pinned ancestor cannot be modified");+ assert_eq!(error.raw_os_error(), Some(ERROR_SHARING_VIOLATION as i32));+ }+ });+ assert_eq!(result, Ok(ORIGINAL.to_vec()));+ for path in paths {+ drop(open_writable_directory(path).expect("directory pin released"));+ }+ let held = fixture.session.with_file_name("renamed-after-read");+ fs::rename(&fixture.session, &held).expect("session pin released");+ fs::rename(&held, &fixture.session).expect("restore session");+}++#[test]+fn refuses_preexisting_write_or_delete_directory_handles() {+ let fixture = fixture();+ let writable =+ open_writable_directory(&fixture.session).expect("existing writable session handle");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ drop(writable);+ let deletion = OpenOptions::new()+ .read(true)+ .access_mode(windows_sys::Win32::Storage::FileSystem::DELETE)+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)+ .open(&fixture.data)+ .expect("existing deletable data handle");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ drop(deletion);+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Ok(ORIGINAL.to_vec())+ );+}++#[test]+fn refuses_preexisting_writable_leaf_and_releases_handles_on_error() {+ let fixture = fixture();+ let writable = OpenOptions::new()+ .write(true)+ .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)+ .open(fixture.session.join(FILE_NAME))+ .expect("existing writable leaf");+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Err(FragmentReadError::NotFound)+ );+ drop(writable);+ assert_eq!(+ read_fragment(&fixture.data, SESSION, FILE_NAME),+ Ok(ORIGINAL.to_vec())+ );+ let held = fixture.data.with_file_name("data-after-error");+ fs::rename(&fixture.data, &held).expect("all ancestor pins released");+ fs::rename(&held, &fixture.data).expect("restore data");+}diff --git a/crates/host-core/src/visualizations/references.rs b/crates/host-core/src/visualizations/references.rsnew file mode 100644index 000000000..18d2c1822--- /dev/null+++ b/crates/host-core/src/visualizations/references.rs@@ -0,0 +1,235 @@+//! Visualization reference identities and Markdown boundaries. Forks resolve+//! the trailing session/file identity, never the historical data-dir prefix.+//! Keep the syntax aligned with packages/shared/src/gen-ui.ts.++use std::collections::HashSet;+use std::path::Path;++use serde_json::Value;++/// Locate exactly one safe direct-child fragment, independently of Unix,+/// Windows, relocated, or aliased data-directory spelling.+fn location(path: &str) -> Option<(String, String)> {+ let normalized = path.replace('\\', "/");+ let mut parts = normalized.split('/').filter(|part| !part.is_empty()).rev();+ let file = parts.next()?;+ let session = parts.next()?;+ if parts.next()? != "visualizations"+ || session.len() > 128+ || !super::safe_session_id(session)+ || !super::is_fragment_path(Path::new(file))+ {+ return None;+ }+ Some((session.to_owned(), file.to_owned()))+}++fn parse_json(json: &str) -> Option<Value> {+ if let Ok(value) = serde_json::from_str(json) {+ return Some(value);+ }+ // Match the renderer's retry for models emitting unescaped Windows paths.+ // Preserve existing escaped quotes, slashes, and backslash pairs.+ let mut escaped = String::with_capacity(json.len());+ let mut chars = json.chars().peekable();+ while let Some(ch) = chars.next() {+ escaped.push(ch);+ if ch != '\\' {+ continue;+ }+ match chars.peek() {+ Some('"' | '\\' | '/') => escaped.push(chars.next()?),+ _ => escaped.push('\\'),+ }+ }+ serde_json::from_str(&escaped).ok()+}++fn rewrite_line(line: &str, source_id: &str, file_name: &str, target: &str) -> Option<String> {+ let trimmed = line.trim();+ let json = trimmed.strip_prefix("::visualize")?;+ if !json.starts_with('{') || !json.ends_with('}') {+ return None;+ }+ let mut value = parse_json(json)?;+ let path = value.as_object_mut()?.get_mut("path")?;+ let (session, file) = location(path.as_str()?)?;+ if session != source_id || file != file_name {+ return None;+ }+ *path = Value::String(target.to_owned());+ let encoded = serde_json::to_string(&value).ok()?;+ let prefix_len = line.len() - line.trim_start().len();+ let suffix_start = line.trim_end().len();+ Some(format!(+ "{}::visualize{encoded}{}",+ &line[..prefix_len],+ &line[suffix_start..]+ ))+}++fn fence_marker(line: &str) -> Option<(char, usize, &str)> {+ let spaces = line.bytes().take_while(|byte| *byte == b' ').count();+ if spaces > 3 {+ return None;+ }+ let line = &line[spaces..];+ let marker = line.chars().next()?;+ if !matches!(marker, '`' | '~') {+ return None;+ }+ let length = line.chars().take_while(|ch| *ch == marker).count();+ (length >= 3).then_some((marker, length, &line[length..]))+}++/// Rewrite only real standalone directives, not prose paths, indented code,+/// or arbitrary fenced examples. The renderer also accepts a final fenced+/// block consisting of exactly one reference; preserve that compatibility.+/// JSON encoding of the child path is identical on every platform.+pub(crate) fn rewrite(text: &mut String, source_id: &str, file_name: &str, target: &str) -> bool {+ if !text.contains("::visualize") {+ return false;+ }+ let lines: Vec<_> = text.split_inclusive('\n').collect();+ let mut eligible = HashSet::new();+ let mut fence: Option<(char, usize, usize)> = None;+ let mut last_block = None;+ for (index, line) in lines.iter().enumerate() {+ let marker = fence_marker(line);+ if let Some((open_marker, open_length, open_index)) = fence {+ if marker.is_some_and(|(marker, length, rest)| {+ marker == open_marker && length >= open_length && rest.trim().is_empty()+ }) {+ last_block = Some((open_index, index));+ fence = None;+ }+ continue;+ }+ if let Some((marker, length, rest)) = marker {+ if marker != '`' || !rest.contains('`') {+ fence = Some((marker, length, index));+ continue;+ }+ }+ if !line.starts_with(" ") && !line.starts_with('\t') {+ eligible.insert(index);+ }+ }+ if fence.is_none() {+ if let Some((open, close)) = last_block {+ if close == open + 2 && lines[close + 1..].iter().all(|line| line.trim().is_empty()) {+ eligible.insert(open + 1);+ }+ }+ }+ let mut output = String::with_capacity(text.len());+ let mut changed = false;+ for (index, line) in lines.iter().enumerate() {+ if eligible.contains(&index) {+ if let Some(rewritten) = rewrite_line(line, source_id, file_name, target) {+ output.push_str(&rewritten);+ changed = true;+ continue;+ }+ }+ output.push_str(line);+ }+ if changed {+ *text = output;+ }+ changed+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn reference_identity_ignores_prefix_and_requires_a_safe_session_and_file() {+ for path in [+ "/retired/visualizations/source/chart.html",+ r"C:\profile\visualizations\source\chart.html",+ ] {+ assert_eq!(location(path), Some(("source".into(), "chart.html".into())));+ }+ for path in [+ "/x/visualizations/source/sub/chart.html",+ "/x/visualizations/source/../chart.html",+ "/x/visualizations/source/a..b.html",+ "/x/visualizations/source/.hidden.html",+ "/x/visualizations/source/chart.HTML",+ ] {+ assert!(location(path).is_none(), "{path}");+ }+ }++ #[test]+ fn json_paths_are_escaped_consistently_for_windows_and_unix() {+ for source in [+ "/old/visualizations/source/chart.html",+ r"C:\old\visualizations\source\chart.html",+ ] {+ for target in [+ "/new/visualizations/child/chart.html",+ r"C:\new\visualizations\child\chart.html",+ ] {+ let mut text = format!(+ " ::visualize{} \r\n",+ json!({"path": source, "title": "Chart"})+ );+ assert!(rewrite(&mut text, "source", "chart.html", target));+ let value: Value =+ serde_json::from_str(text.trim().strip_prefix("::visualize").unwrap()).unwrap();+ assert_eq!(value["path"], target);+ assert_eq!(value["title"], "Chart");+ assert!(text.starts_with(" ::visualize"));+ assert!(text.ends_with(" \r\n"));+ }+ }+ let mut unescaped =+ r#"::visualize{"path":"C:\old\visualizations\source\chart.html"}"#.to_string();+ assert!(rewrite(+ &mut unescaped,+ "source",+ "chart.html",+ "/new/visualizations/child/chart.html"+ ));+ assert_eq!(+ unescaped,+ r#"::visualize{"path":"/new/visualizations/child/chart.html"}"#+ );+ }++ #[test]+ fn markdown_boundaries_and_foreign_sessions_are_preserved() {+ let reference = r#"::visualize{"path":"/old/visualizations/source/chart.html"}"#;+ for original in [+ format!("```json\n{reference}\n```\nExample only."),+ format!("~~~\n{reference}\n~~~\nExample only."),+ format!(" {reference}"),+ format!("\t{reference}"),+ format!("`{reference}`"),+ reference.replace("source/", "foreign/"),+ reference.replace("chart.html", "chart.html.bak"),+ ] {+ let mut text = original.clone();+ assert!(!rewrite(+ &mut text,+ "source",+ "chart.html",+ "/child/chart.html"+ ));+ assert_eq!(text, original);+ }+ let mut final_fence = format!("Chart:\n````json\n{reference}\n````\n");+ assert!(rewrite(+ &mut final_fence,+ "source",+ "chart.html",+ "/new/visualizations/child/chart.html"+ ));+ assert!(final_fence.starts_with("Chart:\n````json\n::visualize"));+ assert!(final_fence.ends_with("\n````\n"));+ }+}diff --git a/crates/host-core/src/workspace.rs b/crates/host-core/src/workspace.rsindex 02720b8ad..69ed1f273 100644--- a/crates/host-core/src/workspace.rs+++ b/crates/host-core/src/workspace.rs@@ -108,8 +108,25 @@ pub struct ContainedRoot {pub kind: ToolRoot,}-/// Ordered list of contained roots tried after the workspace. The first root-/// that contains a path wins.+impl ContainedRoot {+ /// Root identity is rechecked at authorization and execution, not cached+ /// when the session starts. Scratch retains its existing D114 semantics.+ pub fn allows_implicit_access(&self) -> bool {+ self.kind != ToolRoot::Visualization+ || crate::visualizations::validate_session_root(&self.path).is_ok()+ }++ fn lexically_contains(&self, input: &str) -> bool {+ if self.kind == ToolRoot::Visualization {+ crate::visualizations::contains_session_path(&self.path, input)+ } else {+ lexically_inside(&self.path, input)+ }+ }+}++/// Ordered contained roots checked before workspace fallback. The first root+/// that claims a path must validate its current identity before granting access.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct ContainedRoots {roots: Vec<ContainedRoot>,@@ -137,12 +154,12 @@ impl ContainedRoots {self.roots.iter()}- /// The first root that lexically contains `input` (absolute paths only).- /// Decides prompting only; execution runs the symlink-aware resolver.+ /// First claimed root (absolute paths only), including visualization data+ /// aliases. Claiming a root does not grant access: check its current validity.pub fn lexical_root(&self, input: &str) -> Option<&ContainedRoot> {self.roots.iter()- .find(|root| lexically_inside(&root.path, input))+ .find(|root| root.lexically_contains(input))}}@@ -325,6 +342,9 @@ pub fn resolve_tool_path(}fn resolve_in_contained_root(root: &ContainedRoot, input: &str) -> Option<PathBuf> {+ if !root.allows_implicit_access() {+ return None;+ }if let Ok(path) = resolve_in_workspace(&root.path, input) {return Some(path);}diff --git a/docs/adr/README.md b/docs/adr/README.mdindex ba1e13e74..de317b59d 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -385,4 +385,4 @@ Each ADR includes:| local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation || 0332 | [macOS keeps its translucent window surface with an opaque opt-out](0332-macos-opaque-window-surface.md) | Accepted (D665, amended by D666 and D667; supersedes the macOS vibrancy window backing from D348; issue #1064) |-| gen-ui-inline-visualization | [Inline generative UI visualizations](gen-ui-inline-visualization.md) | Proposed (D671) |+| gen-ui-inline-visualization | [Inline generative UI visualizations](gen-ui-inline-visualization.md) | Accepted (D671) |diff --git a/docs/adr/gen-ui-inline-visualization.md b/docs/adr/gen-ui-inline-visualization.mdindex b2978d4fe..f437e6303 100644--- a/docs/adr/gen-ui-inline-visualization.md+++ b/docs/adr/gen-ui-inline-visualization.md@@ -1,6 +1,6 @@# ADR: Inline generative UI visualizations-- Status: Proposed+- Status: Accepted- Related: D671, D114 (session scratch root), ADR 0092 (plugin-owned panel surface)## Context@@ -35,11 +35,11 @@ The model ends its reply with one standalone line per visualization:::visualize{"path":"/abs/path/to/chart.html","title":"Optional title"}```-The renderer parses references only in completed (non-streaming) assistant-messages and ignores lines inside fenced or indented code blocks. A malformed-line stays plain text. The model-facing contract lives in a first-party-built-in skill, `pi-desktop/visualize`, adapted from ZCode's visualize skill-with the host API, tweaks, calendar, export, and CDN guidance removed.+The renderer parses only completed assistant messages. Fenced and indented code+stays code, except a closing fence containing only one reference is accepted as+the model's reference. Malformed lines stay text. The first-party builtin+`pi-desktop/visualize` skill teaches this contract; host APIs, tweaks, calendar,+export, and CDN guidance are removed from the adapted ZCode skill.### Storage root (Rust host-core)@@ -47,25 +47,33 @@ with the host API, tweaks, calendar, export, and CDN guidance removed.additional containment root for `Read`, `Write`, and `Edit`, addressed byabsolute path only, with the same lexical and symlink defenses as the D114scratch root.+ The visualization base and session directories must not be redirected by+ symlinks or junctions, including when the data directory is in a workspace.2. Before adding the root, the single optional `scratch_root` parameter thatthreads through path resolution is generalized into an ordered list ofcontained roots. That step is behavior-preserving and lands first, so thenew root does not become a second parallel path.3. `Write` and `Edit` into the visualization root accept only `.html` files.`Read` is unrestricted inside the root so the model can revise a fragment.-4. Writes there auto-allow without a permission card under the same conditions- as scratch (local workspace only; contract and Plan modes still deny), and- the root is never treated as an external path. Files there are not recorded- as artifacts and not snapshotted for review.+4. Valid contained writes auto-allow under scratch's conditions (local workspace+ only; contract and Plan modes still deny), without artifacts or review+ snapshots. Redirected roots never grant containment; an explicitly approved+ external path continues through ordinary external permission semantics.5. The directory is created lazily and removed with its session (sessiondelete and project removal). The startup sweep removes only directories ofsessions that no longer exist; unlike scratch it never expires livesessions by age, because transcripts keep pointing at these files.+ Cleanup refuses a redirected base instead of traversing or deleting its+ target. The selected data directory itself may use a canonical alias.6. Forks copy only the fragments their transcript references into`visualizations/<childId>/` and rewrite those paths, like referenced pastedfiles in scratch. Cards always resolve against the owning session, so atranscript cannot load another session's files, and deleting the parentleaves the child's cards intact.+ References are matched by source-session/file identity rather than the+ current absolute prefix, so relocation and canonical aliases preserve forks.+ Only assistant/checkpoint visualization references are remapped; raw tool+ strings, thinking, code examples, and foreign-session references stay intact.### Model guidance (agent runtime and Electron Main)@@ -82,19 +90,29 @@ fallback for older messages.1. Main registers a `pi-genui:` scheme through the single`registerSchemesAsPrivileged` call site as `standard` and `secure` only —- no Fetch API support, no CORS, no `Access-Control-Allow-Origin` header — so- no other renderer context, including renderer plugins, can read another- session's visualization.+ no Fetch API support, no CORS, no `Access-Control-Allow-Origin` header.+ Every document response also enforces `sandbox allow-scripts` in its CSP+ header. This forces an opaque origin even when a renderer plugin or other+ caller omits the iframe sandbox; blocking Fetch alone cannot isolate DOMs.2. The card URL is `pi-genui://session/<sessionId>/<file>.html`. The renderer derivesit from the trailing `visualizations/<sessionId>/<file>.html` segment of the- referenced path and never loads the absolute path. Main resolves the file- against the *current* data directory, so references survive data-directory- relocation, which does not rewrite message text.+ referenced path and never loads the absolute path. Main asks the current+ local Host to resolve its own data directory, so references survive+ relocation without rewriting the historical message prefix.3. The handler accepts `GET` only, validates the session ID against`[A-Za-z0-9_-]` and the file name as a single path component ending in`.html`, and rejects symlinks, non-regular files, files over 2 MB, andcomplete HTML documents (a leading `<!doctype`, `<html`, `<head`, or`<body`).+ Main does not open model-written paths. The private+ `visualizations.readFragment` RPC returns bounded base64 bytes for a session+ and filename only. Unix Host Core opens base/session/leaf relative to pinned+ directory descriptors with no-follow flags and a nonblocking leaf. Windows+ pins the full canonical directory chain without write/delete sharing and+ rejects reparse points. Ancestor rename or ABA replacement cannot redirect+ the leaf to another session. No renderer IPC or Plugin SDK surface is added.+ This replaces path snapshots, which cannot establish an atomic directory+ capability. Main validates the private reply before constructing the shell.4. Main wraps the fragment in a host shell: the kit stylesheet(`resources/gen-ui/visualize.css`, which defines the agent-facing tokenssuch as `--foreground` and `--viz-series-1` from MCP Apps-style@@ -146,14 +164,15 @@ visualization cannot replace itself with a remote page outside its own CSP.renderer posts `{ type: "pi-genui:theme", vars, colorScheme }` (hostdesign tokens mapped to `--color-*` names) when the resolved themechanges and `{ type: "pi-genui:view", view }` on load.-4. Expanding opens a modal with a fresh frame for the same URL. Moving an- iframe in the DOM reloads it anyway, and this version has no guest state to- lose. The `expanded` view centers the fragment in the dialog.+4. Expanding opens a modal with a fresh frame for the same URL. The inline+ frame remains mounted with its existing interactive state. The `expanded`+ view centers the fragment in the dialog; Esc closes the copy.5. A missing, invalid, or remote file renders an "unavailable" card with alocalized reason; the rest of the message renders normally. Serving errorsreach the card as a fixed code (`pi-genui:error`), never as text or paths.-6. The number of simultaneously live frames is bounded so hidden session panes- do not accumulate pages.+6. A shared pool bounds inline and expanded frames to eight across all panes.+ Expanded views protect their source inline frame from quota eviction while+ open; off-screen inline frames are evicted before visible ones.## Consequencesdiff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 7a9422e55..241f03f86 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -8,4 +8,6 @@get a builtin `visualize` skill; the model writes an HTML fragment to thesession's visualization directory and references it with a `::visualize`line, which the transcript shows as a sandboxed, theme-aware card with an- expanded view.+ expanded view. Visualization writes and cleanup reject redirected roots;+ document responses enforce an opaque sandbox, inline and expanded frames+ share a bounded pool, and forks retain their cards after data relocation.diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex e85f1a6ee..d0c105252 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -302,8 +302,10 @@ visualization lives as long as its session:directory, no prompt line, and no `pi-desktop/visualize` skill.- **Addressing.** Absolute paths only; the path is advertised in the systemprompt next to the scratch directory. Relative paths never resolve here.-- **Containment.** `resolve_tool_path` checks the workspace, scratch, and- visualization roots in that order with the same lexical + symlink defense.+- **Containment.** Scratch and visualization roots are checked before the+ workspace, so a data directory inside a workspace remains controlled.+ The visualization base and session must be real directories, never+ symlink/junction redirects; canonical data-directory aliases are supported.- **Content.** `Write`/`Edit` accept only a single-component file name ending in`.html`; anything else in this root fails with a tool error. `Read` isallowed.@@ -312,15 +314,23 @@ visualization lives as long as its session:contract modes cannot write here. Results carry `root: "visualization"`, arenot recorded as artifacts, and are not review-snapshotted.- **Lifecycle.** Created lazily on the first write. Deleted with- `session.delete`. The startup sweep removes only directories whose session- no longer exists; it never removes by age.+ `session.delete`. The startup sweep removes only safe session directories+ whose session no longer exists; it never expires live cards by age or+ traverses a redirected visualization base.- **Rendering.** A standalone `::visualize{"path":"<absolute path>","title":"…"}`line outside code blocks renders as an inline card after the turn completes.The renderer derives `pi-genui://session/<sessionId>/<file>` from the path- suffix and never sends the absolute path to Main. Main serves only regular,- non-symlink fragments up to 2 MB below the current data directory, rejects- full documents, and wraps the fragment in a host shell with a strict CSP- (no network, frames, or forms); the frame is `sandbox="allow-scripts"`.+ suffix and never sends the absolute path to Main. Host Core reads only regular+ non-symlink fragments up to 2 MB using pinned native directory capabilities.+ Main validates the private byte response, rejects full documents, and wraps+ the fragment in a host shell with a strict CSP.+ Both the iframe and the response CSP header enforce `sandbox allow-scripts`,+ so omitting the caller's sandbox cannot enable cross-session DOM reads.+ Unix uses relative `openat` and a nonblocking leaf; Windows holds the ancestor+ chain without write/delete sharing and rejects reparse points. Directory+ replacement/restoration cannot redirect serving to a different session.+ Fetches, frames, forms, and remote assets are blocked. WebRTC ICE remains+ the explicitly documented v1 residual channel (see the ADR).## 4c. Message-owned review snapshots and rollbackdiff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex eed60a812..30aea15a3 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -714,6 +714,10 @@ CREATE INDEX idx_session_import_origins_plugin`::visualize` paths; unreferenced fragments stay behind. Cards always loadfrom the owning session's directory, so deleting the source session does notaffect the fork (D671).+ Reference identity is the source session and file name, independent of the+ old absolute data prefix, JSON escaping, or canonical alias spelling.+ Relocating the data directory before forking must retain those child copies.+ Cleanup and copying refuse redirected visualization base/session directories.### 4.6 turns — one row per agent rundiff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex dcc37ad96..a2fc6f024 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -337,6 +337,18 @@ to later refresh and inference; the vendor picker does not collect them.branch (discarding unmerged work)- `session.getScratchPath` — the session's scratch directory (D114), createdon demand+- `visualizations.readFragment({ sessionId, fileName })` — private Main-to-Host+ reader for `pi-genui:` documents (D671). No renderer IPC or Plugin SDK method+ is added. Parameters contain only a validated session ID and direct `.html`+ basename; caller-supplied roots and extra fields are rejected. Host resolves+ against its current data directory and pins native directory capabilities:+ Unix uses relative `openat` with no-follow/nonblocking flags; Windows pins the+ complete ancestor chain without write/delete sharing and refuses reparse+ points. Returns `{ ok: true, base64 }` for at most 2 MiB of file bytes, or+ `{ ok: false, code: "not-found" | "too-large" }`. Main validates this payload,+ decodes bytes, rejects full HTML documents, and supplies the response sandbox.+ Filesystem work does not hold the state/database lock. Additive to v11; no+ storage schema change.- `session.rename({ id, title })` trims and validates the title at the hostboundary. It accepts 1–80 Unicode code points and returns `{ ok: boolean }`;blank or overlong titles are `INVALID_PARAMS`. A successful rename changesdiff --git a/docs/spec/05-security/01-security.md b/docs/spec/05-security/01-security.mdindex 4bc397a94..d3d872995 100644--- a/docs/spec/05-security/01-security.md+++ b/docs/spec/05-security/01-security.md@@ -67,6 +67,14 @@ sidecar's workspace file resolver remain restricted to the session workspace.links, URL attributes, `foreignObject`, script, embedded media, and externalimage elements are removed before the SVG reaches the DOM. Invalid oroversized input fails closed to escaped source text.+- Inline GenUI admits only `frame-src pi-genui:` in the parent. Its document+ responses enforce `sandbox allow-scripts` in the CSP header, in addition to+ the caller's opaque-origin iframe sandbox. Documents allow only bundled+ scripts and inline styles; fetches, frames, forms, and remote assets are+ blocked. The private Host reader pins native directory capabilities and+ returns bounded bytes; Main never reopens model paths. See+ [the GenUI ADR](../../adr/gen-ui-inline-visualization.md) for the explicit+ WebRTC ICE residual channel and the remaining v1 limits.### Future hardening (tracked, post-MVP)diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 4174bb753..ede8a0f95 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -18616,7 +18616,11 @@ host-created files. The full app's file-preview viewer is covered separately.card's expand button, then Esc. 5) Ask the model to write a non-`.html` fileinto the visualization directory, and to write a fragment that calls`fetch("https://example.com")`. 6) Fork the session, then delete the source- session. 7) Repeat step 1 in the remote session.+ session. 7) Repeat step 1 in the remote session. 8) Relocate the data directory,+ then fork a transcript that still names its old visualization path. 9) Try+ redirected visualization roots and a `.html` FIFO, and open two document+ URLs from callers that omit the iframe sandbox. 10) Expand a card while+ eight inline cards are live.- **Expected**:- No permission card appears for the fragment write. While streaming, thereply shows plain text; after completion the `::visualize` line is@@ -18624,9 +18628,23 @@ host-created files. The full app's file-preview viewer is covered separately.- The slider works; theme changes recolor the card without a reload.- Expand opens a large modal copy; Esc closes it and the inline card keepsits state.- - The non-`.html` write fails with a tool error; the network call fails and- nothing leaves the machine; the frame cannot open popups or navigate.- - The fork shows the same card until the source session is deleted, then an- "unavailable" card. The source's `visualizations/<sessionId>/` directory is- removed with it.+ - The non-`.html` write fails with a tool error; fetch requests are blocked,+ and the frame cannot open popups or navigate remotely. The ADR's WebRTC+ ICE limitation remains explicit rather than a blanket no-network claim.+ - The fork retains its own card after the source session is deleted, including+ a fork made after data relocation. The source's directory is removed.+ - Redirected roots cannot bypass Ask write confirmation or let cleanup delete+ unrelated data. FIFO requests fail without blocking other filesystem work.+ - Every document response enforces an opaque sandbox; a caller that omits+ iframe sandbox cannot read another session's DOM.+ - Expanded and inline frames share the eight-frame quota, and the expanded+ card's original inline control state remains unchanged.- The remote session gets no visualization directory or skill.+- **Coverage**: `pnpm test:e2e:gen-ui` runs the offline Electron card journey,+ including real protocol responses, bundled assets, focus/guest Escape,+ viewport release, and unsandboxed callers through a real isolated Host.+ Native directory, FIFO, and ABA regressions run in `visualizations/files`;+ `gen-ui-file-safety.test.mjs` validates the private Host-to-Main boundary.+ Rust visualization RPC/lifecycle/fork tests+ cover authorization, deletion safety, Windows path spelling, and relocation.+- **Status**: Automated without a paid provider or a user's running instance.diff --git a/package.json b/package.jsonindex 8927d08ac..3eda61640 100644--- a/package.json+++ b/package.json@@ -41,6 +41,7 @@"test:e2e:composer-model-selection": "node scripts/e2e-composer-model-selection.mjs","test:e2e:composer-paste": "node scripts/e2e-composer-paste.mjs","test:e2e:transcript": "node scripts/e2e-transcript-render.mjs",+ "test:e2e:gen-ui": "node scripts/e2e-gen-ui.mjs","test:e2e:renderer-responsiveness": "node scripts/e2e-renderer-responsiveness.mjs","test:e2e:transcript-minimap-jump": "node scripts/e2e-transcript-minimap-jump.mjs","test:e2e:copy-tex": "node scripts/e2e-copy-tex.mjs",diff --git a/packages/shared/src/gen-ui.test.ts b/packages/shared/src/gen-ui.test.tsindex 14a36c7f2..d288736a6 100644--- a/packages/shared/src/gen-ui.test.ts+++ b/packages/shared/src/gen-ui.test.ts@@ -3,6 +3,8 @@ import {genUiLocationFromPath,genUiLocationFromUrl,genUiUrl,+ GEN_UI_MAX_FRAGMENT_BYTES,+ isGenUiFragmentReadResult,parseGenUiReferenceLine,splitGenUiReferences,} from "./gen-ui.js";@@ -116,3 +118,18 @@ describe("gen-ui references", () => {expect(splitGenUiReferences(markdown)).toEqual({ content: markdown, references: [] });});});++describe("native visualization read contract", () => {+ it("accepts bounded bytes and fixed failures only", () => {+ for (const value of [{ ok: true, base64: "PHA+eDwvcD4=" }, { ok: true, base64: "" },+ { ok: false, code: "not-found" }, { ok: false, code: "too-large" }]) {+ expect(isGenUiFragmentReadResult(value)).toBe(true);+ }+ for (const value of [null, [], "bytes", { ok: true }, { ok: true, base64: "AA" },+ { ok: true, base64: "!!!!" }, { ok: true, base64: "====" },+ { ok: false, code: "private-path" }, { ok: false, code: "not-found", path: "/private" },+ { ok: true, base64: "A".repeat(Math.ceil(GEN_UI_MAX_FRAGMENT_BYTES / 3) * 4 + 4) }]) {+ expect(isGenUiFragmentReadResult(value)).toBe(false);+ }+ });+});diff --git a/packages/shared/src/gen-ui.ts b/packages/shared/src/gen-ui.tsindex 1bd8d7cd2..f35b92cec 100644--- a/packages/shared/src/gen-ui.ts+++ b/packages/shared/src/gen-ui.ts@@ -20,6 +20,25 @@ export const GEN_UI_SKILL_ID = "pi-desktop/visualize";/** Largest fragment Electron Main will serve. */export const GEN_UI_MAX_FRAGMENT_BYTES = 2 * 1024 * 1024;+/** Private Host → Main payload; base64 bounds JSON expansion of fragment bytes. */+export type GenUiFragmentReadResult =+ | { ok: true; base64: string }+ | { ok: false; code: "not-found" | "too-large" };++const MAX_BASE64_LENGTH = Math.ceil(GEN_UI_MAX_FRAGMENT_BYTES / 3) * 4;+const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;++/** Validate the private native-reader boundary before Main decodes any bytes. */+export function isGenUiFragmentReadResult(value: unknown): value is GenUiFragmentReadResult {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const record = value as Record<string, unknown>;+ if (Object.keys(record).length !== 2) return false;+ if (record.ok === false) return record.code === "not-found" || record.code === "too-large";+ return record.ok === true && typeof record.base64 === "string"+ && record.base64.length <= MAX_BASE64_LENGTH && record.base64.length % 4 === 0+ && BASE64_PATTERN.test(record.base64);+}+/** Guest → host: the guest document's content height in CSS pixels. */export const GEN_UI_SIZE_MESSAGE = "pi-genui:size";/** Host → guest: resolved theme variables to apply on the guest root. */diff --git a/scripts/README.md b/scripts/README.mdindex e2dba3b88..bcbdf1e35 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -62,6 +62,7 @@ The scenarios are specified in| `e2e-provider-recovery.mjs` | `node scripts/e2e-provider-recovery.mjs` | Isolated desktop with a localhost fault-injection provider: socket failures, interrupted streams, Responses recovery, exhausted retries, Continue, and recovery across eleven real Read calls. Requires a built desktop/runtime and host binary (`PI_DESKTOP_HOST_BIN` when outside the checkout); retains screenshots and JSON under `.artifacts/issue-699/` || `e2e-settings-scroll.mjs` | `pnpm test:e2e:settings-scroll` | Production Settings component navigation, search anchoring, focus-on-mount, and scroll behavior || `e2e-transcript-render.mjs` | `pnpm test:e2e:transcript` | Production transcript render boundaries, runtime status geometry, and deterministic smooth-text cadence |+| `e2e-gen-ui.mjs` | `pnpm test:e2e:gen-ui` | Offline production GenUI card/protocol journey: slider, theme, expand/Escape, viewport cleanup, global frame quota, and response-level cross-session sandbox || `e2e-renderer-responsiveness.mjs` | `pnpm test:e2e:renderer-responsiveness` | Native Electron click, typing, session switching, disclosure, and scroll while an isolated child process streams large transcript deltas || `e2e-config-sync-multidevice.mjs` | `pnpm test:e2e:config-sync` | Four isolated host-core processes against a SigV4-validating local S3 fixture; covers credential opt-out, approvals, concurrent edits/conflict resolution, mapped skill resources, deletion, sync/backup restore, restart, password rewrap, encrypted storage and cleanup || `e2e-supervision.mjs` | `pnpm test:e2e:supervision` | Process supervision and restart behavior |diff --git a/scripts/e2e-gen-ui.mjs b/scripts/e2e-gen-ui.mjsnew file mode 100644index 000000000..2922d0f9d--- /dev/null+++ b/scripts/e2e-gen-ui.mjs@@ -0,0 +1,77 @@+#!/usr/bin/env node+/** Offline Electron regression for inline GenUI interaction and isolation. */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const require = createRequire(join(root, "packages/agent-runtime/package.json"));+const { build } = require("esbuild");+const { electronBinary } = resolveElectronBinary(root);+const directory = await mkdtemp(join(tmpdir(), "pi-genui-e2e-"));+let child;+let timeout;+try {+ await build({+ entryPoints: [join(root, "scripts/e2e/gen-ui-renderer.tsx")],+ outfile: join(directory, "renderer.js"),+ bundle: true, platform: "browser", format: "iife", jsx: "automatic",+ loader: { ".css": "empty" },+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env": '{"DEV":false,"MODE":"production"}' },+ alias: {+ "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),+ react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ await build({+ entryPoints: [join(root, "scripts/e2e/gen-ui-main.mjs")],+ outfile: join(directory, "main.cjs"),+ bundle: true, platform: "node", format: "cjs", external: ["electron"], logLevel: "error",+ alias: { "@pi-desktop/shared": join(root, "packages/shared/src/index.ts") },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ const renderer = join(root, "apps/desktop/out/renderer");+ const assets = join(renderer, "assets");+ const sheets = (await readdir(assets)).filter((name) => name.endsWith(".css"));+ assert.ok(sheets.length, "Build the desktop renderer before running GenUI E2E");+ await writeFile(join(directory, "stylesheet.css"),+ (await Promise.all(sheets.map((name) => readFile(join(assets, name), "utf8")))).join("\n"));+ const html = await readFile(join(root, "apps/desktop/index.html"), "utf8");+ const csp = html.match(/http-equiv="Content-Security-Policy"\s+content="([^"]+)"/)?.[1];+ assert.ok(csp, "Production parent CSP not found");+ // The app scrolls its transcript, not the document. This standalone fixture+ // uses document scrolling to exercise the same IntersectionObserver lifecycle.+ await writeFile(join(directory, "index.html"), `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${csp}"><link rel="stylesheet" href="stylesheet.css"><style>html,body{height:auto!important;overflow:auto!important}body{margin:0;padding:20px}#root{max-width:600px;height:auto!important;min-height:0!important;overflow:visible!important}#footer{height:5000px}</style><div id="root"></div><div id="footer"></div><script src="renderer.js"></script>`);+ const home = join(directory, "home");+ await mkdir(home);+ const env = { ...process.env, HOME: home, PI_GEN_UI_E2E_ROOT: root, PI_GEN_UI_E2E_DIR: directory };+ delete env.ELECTRON_RUN_AS_NODE;+ child = spawn(electronBinary, [join(directory, "main.cjs")], { cwd: directory, env, stdio: ["ignore", "pipe", "pipe"] });+ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (chunk) => { stdout += chunk; });+ child.stderr.on("data", (chunk) => { stderr += chunk; });+ timeout = setTimeout(() => child.kill("SIGKILL"), 120_000);+ const { code, signal } = await new Promise((resolve, reject) => {+ child.once("error", reject);+ child.once("close", (code, signal) => resolve({ code, signal }));+ });+ assert.equal(signal, null, `GenUI Electron process hung: ${stderr.slice(-4000)}`);+ assert.equal(code, 0, `GenUI Electron process failed: ${stderr.slice(-4000)}`);+ const result = stdout.split("\n").find((line) => line.startsWith("GENUI_E2E "));+ assert.ok(result, `No GenUI result: ${stdout}\n${stderr.slice(-4000)}`);+ assert.equal(JSON.parse(result.slice("GENUI_E2E ".length)).ok, true);+ console.log(result);+} finally {+ clearTimeout(timeout);+ if (child && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");+ await rm(directory, { recursive: true, force: true });+}diff --git a/scripts/e2e/gen-ui-main.mjs b/scripts/e2e/gen-ui-main.mjsnew file mode 100644index 000000000..8735d7f04--- /dev/null+++ b/scripts/e2e/gen-ui-main.mjs@@ -0,0 +1,156 @@+import assert from "node:assert/strict";+import { mkdir, writeFile } from "node:fs/promises";+import { createServer } from "node:http";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import { GEN_UI_MAX_FRAGMENT_BYTES } from "@pi-desktop/shared";+import { app, BrowserWindow, protocol, session } from "electron";+import {+ GEN_UI_SCHEME_PRIVILEGES, resolveGenUiRequest, genUiResponse,+ resolveGenUiAssetRequest, genUiAssetResponse,+} from "../../apps/desktop/electron/main/gen-ui-protocol.ts";+import { genUiAssetFileFromUrl, loadGenUiKit } from "../../apps/desktop/electron/main/gen-ui-kit.ts";+import { installLiveMicrophonePermissionHandlers } from "../../apps/desktop/electron/main/live-voice/microphone-permissions.ts";+import { createGenUiFragmentReader } from "../../apps/desktop/electron/main/gen-ui-files.ts";++const root = process.env.PI_GEN_UI_E2E_ROOT;+const directory = process.env.PI_GEN_UI_E2E_DIR;+if (!root || !directory) throw new Error("GenUI E2E fixture paths are required");+const dataDir = join(directory, "data");+app.setPath("userData", join(directory, "profile"));+app.commandLine.appendSwitch("disable-background-networking");+protocol.registerSchemesAsPrivileged([GEN_UI_SCHEME_PRIVILEGES]);+let nativeHost;+process.once("exit", () => nativeHost?.child?.kill());++async function run() {+ const { Host, resolveHostBinary } = await import(pathToFileURL(join(root, "scripts/e2e/host.mjs")).href);+ nativeHost = new Host(resolveHostBinary(), dataDir, { quiet: true });+ await nativeHost.start();+ const readFragment = createGenUiFragmentReader(() => nativeHost);+ const networkRequests = [];+ const server = createServer((request, response) => {+ networkRequests.push(request.url);+ response.end("unexpected network access");+ });+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ const address = server.address();+ assert.ok(address && typeof address === "object");+ const localUrl = `http://127.0.0.1:${address.port}/blocked`;+ const fragment = `<div><input id="slider" type="range" min="0" max="20" value="5"><output id="value"></output></div>+<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js"></script>+<script>const slider=document.getElementById('slider');const update=()=>d3.select('#value').text(slider.value);slider.addEventListener('input',update);update();window.fixtureValue=()=>document.getElementById('value').textContent;fetch(${JSON.stringify(localUrl)}).then(()=>{window.fixtureNetworkBlocked=false},()=>{window.fixtureNetworkBlocked=true});parent.postMessage({type:'fixture:loaded'},'*');</script>`;+ const sessionDir = join(dataDir, "visualizations", "probe_session");+ await mkdir(sessionDir, { recursive: true });+ for (let index = 0; index < 8; index += 1) await writeFile(join(sessionDir, `chart${index}.html`), fragment);+ await mkdir(join(dataDir, "visualizations", "victim"), { recursive: true });+ await writeFile(join(dataDir, "visualizations", "victim", "secret.html"),+ "<p>CROSS_SESSION_PRIVATE_MARKER</p><script>parent.postMessage({type:'fixture:loaded'},'*')</script>");+ await writeFile(join(sessionDir, "attacker.html"), `<p>attacker</p><script>addEventListener('message',event=>{if(event.data!=='attack')return;try{parent.postMessage({type:'cross-read',stolen:parent.frames[1].document.querySelector('p').textContent},'*')}catch(error){parent.postMessage({type:'cross-read',error:error.name},'*')}});parent.postMessage({type:'fixture:loaded'},'*')</script>`);+ await writeFile(join(sessionDir, "limit.html"), Buffer.alloc(GEN_UI_MAX_FRAGMENT_BYTES, 0x20));+ const limit = await readFragment({ sessionId: "probe_session", fileName: "limit.html" });+ assert.equal(limit.ok, true);+ assert.equal(limit.fragment.length, GEN_UI_MAX_FRAGMENT_BYTES);+ await writeFile(join(sessionDir, "limit.html"), Buffer.alloc(GEN_UI_MAX_FRAGMENT_BYTES + 1, 0x20));+ assert.deepEqual(await readFragment({ sessionId: "probe_session", fileName: "limit.html" }), { ok: false, status: 413, code: "too-large" });++ await app.whenReady();+ const kit = await loadGenUiKit(join(root, "apps/desktop/resources/gen-ui"));+ const loadKit = async () => kit;+ protocol.handle("pi-genui", async (request) => genUiAssetFileFromUrl(request.url)+ ? genUiAssetResponse(await resolveGenUiAssetRequest({ method: request.method, url: request.url, loadKit }))+ : genUiResponse(await resolveGenUiRequest({ method: request.method, url: request.url, readFragment, loadKit })));+ const window = new BrowserWindow({+ show: false, width: 900, height: 700,+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false },+ });+ installLiveMicrophonePermissionHandlers({ targetSession: session.defaultSession, getMainWindow: () => window, hasReservation: () => false });+ const host = async (expression) => {+ try { return await window.webContents.executeJavaScript(expression); }+ catch (error) { throw new Error(`Host probe ${expression}: ${error.message}`, { cause: error }); }+ };+ const guests = () => window.webContents.mainFrame.framesInSubtree.filter((frame) => frame.url.startsWith("pi-genui://session/"));+ const message = (index) => `Chart\n::visualize${JSON.stringify({ path: join(sessionDir, `chart${index}.html`), title: `Chart ${index}` })}`;+ const checks = [];+ checks.push("real native Host reads bounded two-megabyte fragments");+ const timeout = setTimeout(() => { console.error("GenUI E2E timed out"); app.exit(1); }, 90_000);+ try {+ await window.loadFile(join(directory, "index.html"));+ await host("window.genUiProbe.ready");+ await host(`window.genUiProbe.mount(${JSON.stringify(message(0))},true)`);+ assert.equal(await host('document.querySelectorAll("iframe").length'), 0);+ assert.equal(await host('document.getElementById("prose").textContent'), "Chart");+ checks.push("streaming reference hidden");++ await host(`window.genUiProbe.mount(${JSON.stringify(message(0))});window.genUiProbe.waitLoaded(1)`);+ const inline = guests()[0];+ assert.equal(await inline.executeJavaScript("d3.version"), "7.9.0");+ assert.equal(await host('document.querySelector("iframe").getAttribute("sandbox")'), "allow-scripts");+ await inline.executeJavaScript('document.getElementById("slider").value="17";document.getElementById("slider").dispatchEvent(new Event("input",{bubbles:true}));');+ assert.equal(await inline.executeJavaScript("window.fixtureValue()"), "17");+ assert.equal(await inline.executeJavaScript("window.fixtureNetworkBlocked"), true);+ checks.push("bundled D3 and slider work; network fetch denied");++ await host('document.documentElement.dataset.theme="dark";document.documentElement.style.setProperty("--ds-text-primary","rgb(9, 8, 7)");');+ await inline.executeJavaScript('new Promise((resolve,reject)=>{const deadline=performance.now()+10000;const check=()=>{if(document.documentElement.style.getPropertyValue("--color-text-primary")==="rgb(9, 8, 7)")return resolve(true);if(performance.now()>deadline)return reject(new Error("theme timeout"));requestAnimationFrame(check);};check();})');+ checks.push("theme updates without guest reload");++ await host('document.querySelector(".gen-ui-card .gen-ui-action").click();window.genUiProbe.waitLoaded(2)');+ assert.equal(await host('document.querySelectorAll("[role=dialog]").length'), 1);+ const expanded = guests().at(-1);+ await expanded.executeJavaScript('document.body.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:true}));');+ await host('window.genUiProbe.wait(()=>!document.querySelector("[role=dialog]"),"guest Escape closes dialog")');+ assert.equal(await inline.executeJavaScript("window.fixtureValue()"), "17");+ checks.push("expand and guest Escape preserve inline state");++ await host('window.scrollTo(0,4000);window.genUiProbe.wait(()=>document.querySelectorAll("iframe").length===0,"release offscreen")');+ await host("window.scrollTo(0,0);window.genUiProbe.waitLoaded(1)");+ checks.push("offscreen release and automatic reload");+ await host(`window.genUiProbe.mount(${JSON.stringify(message(0))},false,true)`);+ assert.equal(await host('document.querySelectorAll("iframe").length'), 0);+ assert.equal(await host('!!document.querySelector(".is-unavailable")'), true);+ const missing = message(0).replace("chart0.html", "missing.html");+ await host(`window.genUiProbe.mount(${JSON.stringify(missing)});window.genUiProbe.wait(()=>!!document.querySelector(".is-unavailable"),"missing error shell")`);+ checks.push("remote and missing files show unavailable cards");++ window.setContentSize(900, 2600);+ const all = Array.from({ length: 8 }, (_, index) => message(index)).join("\n");+ await host(`window.genUiProbe.mount(${JSON.stringify(all)});window.genUiProbe.waitLoaded(8)`);+ const retained = guests()[0];+ await retained.executeJavaScript('document.getElementById("slider").value="19";document.getElementById("slider").dispatchEvent(new Event("input",{bubbles:true}));');+ await host('document.querySelector(".gen-ui-card .gen-ui-action").click();window.genUiProbe.wait(()=>!!document.querySelector("[role=dialog] iframe"),"expanded frame mounts").then(()=>window.genUiProbe.waitLoaded(8))');+ assert.equal(await host('document.querySelectorAll("iframe").length'), 8, "expanded frame must share the global quota");+ assert.equal(await host("window.genUiProbe.poolSize()"), 8);+ assert.equal(await retained.executeJavaScript("window.fixtureValue()"), "19", "quota eviction must retain the source inline frame");+ assert.equal(await host('document.querySelectorAll("[role=dialog]").length'), 1);+ checks.push("expanded frame shares eight-frame quota and retains source state");++ await host("window.genUiProbe.unmount()");+ assert.equal(await host("window.genUiProbe.poolSize()"), 0);+ assert.equal(await host('document.querySelectorAll("iframe").length'), 0);+ checks.push("unmount releases all frame slots");++ // Use intentionally unsandboxed callers, as a renderer plugin can. The+ // response itself must force distinct opaque origins between sessions.+ await host('for(const [id,url] of [["attacker","pi-genui://session/probe_session/attacker.html"],["victim","pi-genui://session/victim/secret.html"]]){const frame=document.createElement("iframe");frame.id=id;frame.src=url;document.body.appendChild(frame)};window.genUiProbe.waitLoaded(2)');+ await host('document.getElementById("attacker").contentWindow.postMessage("attack","*");window.genUiProbe.wait(()=>window.genUiProbe.messages.some(message=>message?.type==="cross-read"),"cross-frame sandbox result")');+ const crossRead = await host('window.genUiProbe.messages.find(message=>message?.type==="cross-read")');+ assert.equal(crossRead.error, "SecurityError");+ assert.equal(crossRead.stolen, undefined);+ checks.push("response sandbox rejects cross-session DOM read without caller sandbox");+ assert.deepEqual(networkRequests, []);+ window.destroy();+ clearTimeout(timeout);+ server.close();+ await nativeHost.stop();+ process.stdout.write(`GENUI_E2E ${JSON.stringify({ ok: true, checks })}\n`, () => app.exit(0));+ } catch (error) {+ clearTimeout(timeout);+ server.close();+ window.destroy();+ await nativeHost.stop();+ throw error;+ }+}++run().catch(async (error) => { await nativeHost?.stop(); console.error(error.stack || error); app.exit(1); });diff --git a/scripts/e2e/gen-ui-renderer.tsx b/scripts/e2e/gen-ui-renderer.tsxnew file mode 100644index 000000000..d67a0daf8--- /dev/null+++ b/scripts/e2e/gen-ui-renderer.tsx@@ -0,0 +1,55 @@+import { createElement } from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { GenUiCards } from "../../apps/desktop/src/features/chat/gen-ui/GenUiCard";+import { genUiSplitFor } from "../../apps/desktop/src/features/chat/gen-ui/gen-ui-split";+import { genUiFramePool } from "../../apps/desktop/src/features/chat/gen-ui/gen-ui-frames";++const container = document.getElementById("root");+if (!container) throw new Error("GenUI fixture root is missing");+const root = createRoot(container);+const i18n = createInstance();+const loaded = new WeakSet<object>();+const messages: unknown[] = [];+window.addEventListener("message", (event) => {+ messages.push(event.data);+ if (event.data?.type === "fixture:loaded" && event.source) loaded.add(event.source);+});++async function wait(predicate: () => boolean, label: string): Promise<void> {+ const deadline = performance.now() + 15_000;+ while (!predicate()) {+ if (performance.now() > deadline) throw new Error(`Timed out: ${label}`);+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ }+}++// The test enters through the production card interface and real React wiring;+// only the externally generated HTML and its owning session are fixture data.+Object.assign(window, {+ genUiProbe: {+ ready: i18n.init({ lng: "en", resources: { en: { translation: catalogs.en } } }).then(() => true),+ mount(content: string, streaming = false, remote = false) {+ const split = genUiSplitFor(content, streaming);+ flushSync(() => root.render(+ createElement(I18nextProvider, { i18n },+ createElement("p", { id: "prose" }, split.content),+ createElement(GenUiCards, { references: split.references, sessionId: "probe_session", remote }),+ ),+ ));+ },+ wait,+ waitLoaded(count: number) {+ return wait(() => {+ const frames = [...document.querySelectorAll("iframe")];+ return frames.length === count && frames.every((frame) => frame.contentWindow && loaded.has(frame.contentWindow));+ }, `guest loads ${count}`);+ },+ messages,+ poolSize: () => genUiFramePool.size,+ unmount() { flushSync(() => root.unmount()); },+ },+});