Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): run HTML artifact scripts in isolated webviews (#79009)

Shy Alter97817becb0ed
diff --git a/products/desktop/apps/code/src/main/artifact-preview-link.test.ts b/products/desktop/apps/code/src/main/artifact-preview-link.test.ts
new file mode 100644
index 000000000000..c82087d0649a
--- /dev/null
+++ b/products/desktop/apps/code/src/main/artifact-preview-link.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import { trustedArtifactLink } from "./artifact-preview-link";
+
+describe("trustedArtifactLink", () => {
+ it("accepts real HTTP link clicks and rejects script-generated clicks", () => {
+ const link = document.createElement("a");
+ link.href = "https://example.com/report";
+ const child = document.createElement("span");
+ link.appendChild(child);
+
+ expect(trustedArtifactLink({ isTrusted: true, target: child })).toBe(
+ "https://example.com/report",
+ );
+ expect(trustedArtifactLink({ isTrusted: false, target: child })).toBeNull();
+ });
+
+ it.each(["javascript:alert(1)", "file:///etc/passwd", "#section-2"])(
+ "rejects non-external link %s",
+ (href) => {
+ const link = document.createElement("a");
+ link.href = href;
+
+ expect(trustedArtifactLink({ isTrusted: true, target: link })).toBeNull();
+ },
+ );
+});
diff --git a/products/desktop/apps/code/src/main/artifact-preview-link.ts b/products/desktop/apps/code/src/main/artifact-preview-link.ts
new file mode 100644
index 000000000000..57eb4cad432f
--- /dev/null
+++ b/products/desktop/apps/code/src/main/artifact-preview-link.ts
@@ -0,0 +1,14 @@
+export function trustedArtifactLink({
+ isTrusted,
+ target,
+}: Pick<MouseEvent, "isTrusted" | "target">): string | null {
+ if (!isTrusted || !(target instanceof Element)) return null;
+ const href = target
+ .closest<HTMLAnchorElement>("a[href]")
+ ?.getAttribute("href");
+ if (!href) return null;
+ const url = URL.parse(href);
+ return url?.protocol === "http:" || url?.protocol === "https:"
+ ? url.href
+ : null;
+}
diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-artifact-preview.test.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-artifact-preview.test.ts
new file mode 100644
index 000000000000..0d866225ef82
--- /dev/null
+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-artifact-preview.test.ts
@@ -0,0 +1,202 @@
+import type { BrowserWindow, WebContents, WebPreferences } from "electron";
+import { describe, expect, it, vi } from "vitest";
+import {
+ ARTIFACT_PREVIEW_ARG,
+ ARTIFACT_PREVIEW_DATA_URL_PREFIX,
+} from "../../shared/constants";
+import {
+ hardenArtifactPreviewPreferences,
+ isAllowedArtifactPreview,
+ lockDownArtifactPreview,
+ setupArtifactPreviewWebviews,
+} from "./electron-artifact-preview";
+
+describe("artifact preview webviews", () => {
+ it.each([
+ ["https://example.com/report.html", "artifact-preview-one"],
+ [`${ARTIFACT_PREVIEW_DATA_URL_PREFIX}<h1>report</h1>`, "persist:main"],
+ ["file:///tmp/report.html", "artifact-preview-one"],
+ ])("rejects unsupported source and partition pairs", (src, partition) => {
+ expect(isAllowedArtifactPreview(src, partition)).toBe(false);
+ });
+
+ it("allows an HTML data document in an ephemeral artifact partition", () => {
+ expect(
+ isAllowedArtifactPreview(
+ `${ARTIFACT_PREVIEW_DATA_URL_PREFIX}<script>render()</script>`,
+ "artifact-preview-123",
+ ),
+ ).toBe(true);
+ });
+
+ it("overrides privileged guest preferences", () => {
+ const preferences = {
+ preload: "/tmp/untrusted.js",
+ nodeIntegration: true,
+ contextIsolation: false,
+ sandbox: false,
+ webSecurity: false,
+ allowRunningInsecureContent: true,
+ webviewTag: true,
+ disableDialogs: false,
+ } as WebPreferences;
+
+ hardenArtifactPreviewPreferences(preferences, "/app/artifact-preload.js");
+
+ expect(preferences).toMatchObject({
+ preload: "/app/artifact-preload.js",
+ additionalArguments: [ARTIFACT_PREVIEW_ARG],
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ contextIsolation: true,
+ sandbox: true,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ webviewTag: false,
+ disableDialogs: true,
+ experimentalFeatures: false,
+ enableBlinkFeatures: "",
+ plugins: false,
+ });
+ });
+
+ it("blocks guest network, navigation, permissions, popups, and downloads", () => {
+ const handlers = new Map<string, (...args: never[]) => void>();
+ const permissionRequest = vi.fn();
+ const permissionCheck = vi.fn();
+ const beforeRequest = vi.fn();
+ const download = vi.fn();
+ const guest = {
+ setWindowOpenHandler: vi.fn(),
+ setWebRTCIPHandlingPolicy: vi.fn(),
+ on: vi.fn((event: string, handler: (...args: never[]) => void) => {
+ handlers.set(event, handler);
+ }),
+ session: {
+ enableNetworkEmulation: vi.fn(),
+ setProxy: vi.fn().mockResolvedValue(undefined),
+ setPermissionCheckHandler: permissionCheck,
+ setPermissionRequestHandler: permissionRequest,
+ on: vi.fn((event: string, handler: (...args: never[]) => void) => {
+ if (event === "will-download") download.mockImplementation(handler);
+ }),
+ webRequest: { onBeforeRequest: beforeRequest },
+ },
+ } as unknown as WebContents;
+
+ lockDownArtifactPreview(guest);
+
+ expect(guest.setWindowOpenHandler).toHaveBeenCalledOnce();
+ expect(guest.setWebRTCIPHandlingPolicy).toHaveBeenCalledWith(
+ "disable_non_proxied_udp",
+ );
+ expect(guest.session.enableNetworkEmulation).toHaveBeenCalledWith({
+ offline: true,
+ });
+ expect(guest.session.setProxy).toHaveBeenCalledWith(
+ expect.objectContaining({ mode: "fixed_servers" }),
+ );
+ expect(permissionCheck).toHaveBeenCalledOnce();
+ expect(permissionRequest).toHaveBeenCalledOnce();
+ expect(beforeRequest).toHaveBeenCalledWith(
+ expect.objectContaining({
+ urls: expect.arrayContaining(["http://*/*", "https://*/*"]),
+ }),
+ expect.any(Function),
+ );
+
+ const preventNavigation = vi.fn();
+ handlers.get("will-navigate")?.(
+ { preventDefault: preventNavigation } as never,
+ "https://example.com" as never,
+ );
+ expect(preventNavigation).toHaveBeenCalledOnce();
+
+ const allowNavigation = vi.fn();
+ handlers.get("will-navigate")?.(
+ { preventDefault: allowNavigation } as never,
+ `${ARTIFACT_PREVIEW_DATA_URL_PREFIX}PGgxPlJlcG9ydDwvaDE+` as never,
+ );
+ handlers.get("will-navigate")?.(
+ { preventDefault: allowNavigation } as never,
+ "about:blank" as never,
+ );
+ expect(allowNavigation).not.toHaveBeenCalled();
+
+ const preventSubframeNavigation = vi.fn();
+ handlers.get("will-frame-navigate")?.({
+ isMainFrame: false,
+ preventDefault: preventSubframeNavigation,
+ } as never);
+ expect(preventSubframeNavigation).toHaveBeenCalledOnce();
+
+ const allowMainFrameNavigation = vi.fn();
+ handlers.get("will-frame-navigate")?.({
+ isMainFrame: true,
+ preventDefault: allowMainFrameNavigation,
+ } as never);
+ expect(allowMainFrameNavigation).not.toHaveBeenCalled();
+
+ const preventDownload = vi.fn();
+ download({ preventDefault: preventDownload });
+ expect(preventDownload).toHaveBeenCalledOnce();
+ });
+
+ it("wires the attachment allowlist before locking down an allowed guest", () => {
+ const handlers = new Map<string, (...args: never[]) => void>();
+ const window = {
+ webContents: {
+ on: vi.fn((event: string, handler: (...args: never[]) => void) => {
+ handlers.set(event, handler);
+ }),
+ },
+ } as unknown as BrowserWindow;
+ setupArtifactPreviewWebviews(window);
+
+ const blockedPreferences = {} as WebPreferences;
+ const preventBlocked = vi.fn();
+ handlers.get("will-attach-webview")?.(
+ { preventDefault: preventBlocked } as never,
+ blockedPreferences as never,
+ {
+ src: "https://example.com",
+ partition: "artifact-preview-one",
+ } as never,
+ );
+ expect(preventBlocked).toHaveBeenCalledOnce();
+ expect(blockedPreferences.preload).toBeUndefined();
+
+ const allowedPreferences = {} as WebPreferences;
+ const preventAllowed = vi.fn();
+ handlers.get("will-attach-webview")?.(
+ { preventDefault: preventAllowed } as never,
+ allowedPreferences as never,
+ {
+ src: `${ARTIFACT_PREVIEW_DATA_URL_PREFIX}PGgxPlJlcG9ydDwvaDE+`,
+ partition: "artifact-preview-one",
+ } as never,
+ );
+ expect(preventAllowed).not.toHaveBeenCalled();
+ expect(allowedPreferences).toMatchObject({
+ preload: expect.stringMatching(/preload\.js$/),
+ additionalArguments: [ARTIFACT_PREVIEW_ARG],
+ sandbox: true,
+ });
+
+ const guest = {
+ setWindowOpenHandler: vi.fn(),
+ setWebRTCIPHandlingPolicy: vi.fn(),
+ on: vi.fn(),
+ session: {
+ enableNetworkEmulation: vi.fn(),
+ setProxy: vi.fn().mockResolvedValue(undefined),
+ setPermissionCheckHandler: vi.fn(),
+ setPermissionRequestHandler: vi.fn(),
+ on: vi.fn(),
+ webRequest: { onBeforeRequest: vi.fn() },
+ },
+ } as unknown as WebContents;
+ handlers.get("did-attach-webview")?.({} as never, guest as never);
+ expect(guest.setWindowOpenHandler).toHaveBeenCalledOnce();
+ });
+});
diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-artifact-preview.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-artifact-preview.ts
new file mode 100644
index 000000000000..265aa2c9a5d3
--- /dev/null
+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-artifact-preview.ts
@@ -0,0 +1,101 @@
+import path from "node:path";
+import type { BrowserWindow, WebContents, WebPreferences } from "electron";
+import {
+ ARTIFACT_PREVIEW_ARG,
+ ARTIFACT_PREVIEW_DATA_URL_PREFIX,
+ ARTIFACT_PREVIEW_PARTITION_PREFIX,
+} from "../../shared/constants";
+import { logger } from "../utils/logger";
+
+const log = logger.scope("artifact-preview-webview");
+
+export function isAllowedArtifactPreview(
+ src: string,
+ partition: string | undefined,
+): boolean {
+ return (
+ src.startsWith(ARTIFACT_PREVIEW_DATA_URL_PREFIX) &&
+ partition?.startsWith(ARTIFACT_PREVIEW_PARTITION_PREFIX) === true
+ );
+}
+
+export function hardenArtifactPreviewPreferences(
+ preferences: WebPreferences,
+ preloadPath: string,
+): void {
+ preferences.preload = preloadPath;
+ preferences.additionalArguments = [ARTIFACT_PREVIEW_ARG];
+ preferences.nodeIntegration = false;
+ preferences.nodeIntegrationInSubFrames = false;
+ preferences.contextIsolation = true;
+ preferences.sandbox = true;
+ preferences.webSecurity = true;
+ preferences.allowRunningInsecureContent = false;
+ preferences.webviewTag = false;
+ preferences.disableDialogs = true;
+ preferences.experimentalFeatures = false;
+ preferences.enableBlinkFeatures = "";
+ preferences.plugins = false;
+}
+
+export function lockDownArtifactPreview(guest: WebContents): void {
+ guest.setWindowOpenHandler(() => ({ action: "deny" }));
+ guest.setWebRTCIPHandlingPolicy("disable_non_proxied_udp");
+ guest.on("will-navigate", (event, url) => {
+ if (
+ url.startsWith(ARTIFACT_PREVIEW_DATA_URL_PREFIX) ||
+ url === "about:blank"
+ ) {
+ return;
+ }
+ event.preventDefault();
+ });
+ guest.on("will-frame-navigate", (event) => {
+ if (!event.isMainFrame) event.preventDefault();
+ });
+
+ const guestSession = guest.session;
+ guestSession.enableNetworkEmulation({ offline: true });
+ void guestSession
+ .setProxy({
+ mode: "fixed_servers",
+ proxyRules: "http=127.0.0.1:9;https=127.0.0.1:9;socks=127.0.0.1:9",
+ })
+ .catch((error) =>
+ log.warn("Failed to isolate artifact preview proxy", { error }),
+ );
+ guestSession.setPermissionCheckHandler(() => false);
+ guestSession.setPermissionRequestHandler((_contents, _permission, callback) =>
+ callback(false),
+ );
+ guestSession.on("will-download", (event) => event.preventDefault());
+ guestSession.webRequest.onBeforeRequest(
+ {
+ urls: [
+ "http://*/*",
+ "https://*/*",
+ "file://*/*",
+ "ws://*/*",
+ "wss://*/*",
+ ],
+ },
+ (_details, callback) => callback({ cancel: true }),
+ );
+}
+
+export function setupArtifactPreviewWebviews(window: BrowserWindow): void {
+ const preloadPath = path.join(__dirname, "preload.js");
+
+ window.webContents.on("will-attach-webview", (event, preferences, params) => {
+ if (!isAllowedArtifactPreview(params.src, params.partition)) {
+ event.preventDefault();
+ log.warn("Blocked an unsupported webview attachment");
+ return;
+ }
+ hardenArtifactPreviewPreferences(preferences, preloadPath);
+ });
+
+ window.webContents.on("did-attach-webview", (_event, guest) => {
+ lockDownArtifactPreview(guest);
+ });
+}
diff --git a/products/desktop/apps/code/src/main/preload.test.ts b/products/desktop/apps/code/src/main/preload.test.ts
new file mode 100644
index 000000000000..126b0488c731
--- /dev/null
+++ b/products/desktop/apps/code/src/main/preload.test.ts
@@ -0,0 +1,43 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { APP_WINDOW_ARG } from "../shared/constants";
+
+const { contextBridge, ipcRenderer } = vi.hoisted(() => ({
+ contextBridge: { exposeInMainWorld: vi.fn() },
+ ipcRenderer: {
+ on: vi.fn(),
+ sendToHost: vi.fn(),
+ },
+}));
+
+vi.mock("electron", () => ({
+ contextBridge,
+ ipcRenderer,
+ webUtils: { getPathForFile: vi.fn() },
+}));
+vi.mock("electron-log/preload", () => ({}));
+vi.mock("@posthog/electron-trpc/main", () => ({
+ exposeElectronTRPC: vi.fn(),
+}));
+
+import { setupPreload } from "./preload";
+
+describe("preload mode selection", () => {
+ beforeEach(() => {
+ contextBridge.exposeInMainWorld.mockClear();
+ });
+
+ it("defaults an untagged process to the restricted artifact preload", () => {
+ setupPreload([]);
+
+ expect(contextBridge.exposeInMainWorld).not.toHaveBeenCalled();
+ });
+
+ it("exposes application APIs only to an explicitly tagged app window", () => {
+ setupPreload([APP_WINDOW_ARG]);
+
+ expect(contextBridge.exposeInMainWorld).toHaveBeenCalledWith(
+ "electronUtils",
+ expect.any(Object),
+ );
+ });
+});
diff --git a/products/desktop/apps/code/src/main/preload.ts b/products/desktop/apps/code/src/main/preload.ts
index 67bd5bbc7d3f..f97abd4862b9 100644
--- a/products/desktop/apps/code/src/main/preload.ts
+++ b/products/desktop/apps/code/src/main/preload.ts
@@ -1,12 +1,49 @@
import { exposeElectronTRPC } from "@posthog/electron-trpc/main";
-import { contextBridge, webUtils } from "electron";
-import "electron-log/preload";
+import { contextBridge, ipcRenderer, webUtils } from "electron";
+import { sanitizeArtifactBridgeMessage } from "../shared/artifact-preview-message";
+import {
+ APP_WINDOW_ARG,
+ ARTIFACT_HOST_TO_PREVIEW_CHANNEL,
+ ARTIFACT_OPEN_EXTERNAL_CHANNEL,
+ ARTIFACT_PREVIEW_TO_HOST_CHANNEL,
+} from "../shared/constants";
+import { trustedArtifactLink } from "./artifact-preview-link";
import { parseSessionIdArg } from "./posthog-session-arg";
const DEV_FLAGS_CLI_PREFIX = "--posthog-code-flags=";
-function readDevFlags(): { devMode: boolean } {
- const arg = process.argv.find((a) => a.startsWith(DEV_FLAGS_CLI_PREFIX));
+function setupArtifactPreviewPreload(): void {
+ document.addEventListener(
+ "click",
+ (event) => {
+ const href = trustedArtifactLink(event);
+ if (!href) return;
+ event.preventDefault();
+ event.stopPropagation();
+ ipcRenderer.sendToHost(ARTIFACT_OPEN_EXTERNAL_CHANNEL, href);
+ },
+ true,
+ );
+
+ window.addEventListener("message", (event) => {
+ const message = sanitizeArtifactBridgeMessage(event.data);
+ if (
+ !message ||
+ (message.type === "selection" &&
+ navigator.userActivation?.isActive !== true)
+ ) {
+ return;
+ }
+ ipcRenderer.sendToHost(ARTIFACT_PREVIEW_TO_HOST_CHANNEL, message);
+ });
+
+ ipcRenderer.on(ARTIFACT_HOST_TO_PREVIEW_CHANNEL, (_event, data: unknown) => {
+ window.postMessage(data, "*");
+ });
+}
+
+function readDevFlags(argv: string[]): { devMode: boolean } {
+ const arg = argv.find((a) => a.startsWith(DEV_FLAGS_CLI_PREFIX));
if (!arg) return { devMode: false };
try {
const payload = decodeURIComponent(arg.slice(DEV_FLAGS_CLI_PREFIX.length));
@@ -17,29 +54,42 @@ function readDevFlags(): { devMode: boolean } {
}
}
-const devFlags = readDevFlags();
+function setupApplicationPreload(argv: string[]): void {
+ void import("electron-log/preload");
+ const devFlags = readDevFlags(argv);
+
+ contextBridge.exposeInMainWorld("electronUtils", {
+ getPathForFile: (file: File) => webUtils.getPathForFile(file),
+ });
-contextBridge.exposeInMainWorld("electronUtils", {
- getPathForFile: (file: File) => webUtils.getPathForFile(file),
-});
+ contextBridge.exposeInMainWorld("__posthogBootstrap", {
+ sessionId: parseSessionIdArg(argv),
+ });
-contextBridge.exposeInMainWorld("__posthogBootstrap", {
- sessionId: parseSessionIdArg(process.argv),
-});
+ contextBridge.exposeInMainWorld("__posthogDevFlags", devFlags);
-contextBridge.exposeInMainWorld("__posthogDevFlags", devFlags);
+ if (argv.includes("--posthog-code-dev")) {
+ contextBridge.exposeInMainWorld("__posthogTest", {
+ crash: () => {
+ process.crash();
+ },
+ abort: () => {
+ process.abort();
+ },
+ });
+ }
-if (process.argv.includes("--posthog-code-dev")) {
- contextBridge.exposeInMainWorld("__posthogTest", {
- crash: () => {
- process.crash();
- },
- abort: () => {
- process.abort();
- },
+ process.once("loaded", async () => {
+ exposeElectronTRPC();
});
}
-process.once("loaded", async () => {
- exposeElectronTRPC();
-});
+export function setupPreload(argv: string[]): void {
+ if (argv.includes(APP_WINDOW_ARG)) {
+ setupApplicationPreload(argv);
+ } else {
+ setupArtifactPreviewPreload();
+ }
+}
+
+setupPreload(process.argv);
diff --git a/products/desktop/apps/code/src/main/window.ts b/products/desktop/apps/code/src/main/window.ts
index 48367c7c93b9..ecc8ef0e4a17 100644
--- a/products/desktop/apps/code/src/main/window.ts
+++ b/products/desktop/apps/code/src/main/window.ts
@@ -10,9 +10,11 @@ import {
type MenuItemConstructorOptions,
screen,
} from "electron";
+import { APP_WINDOW_ARG } from "../shared/constants";
import { container } from "./di/container";
import { setupExternalLinkHandlers } from "./external-links";
import { buildApplicationMenu } from "./menu";
+import { setupArtifactPreviewWebviews } from "./platform-adapters/electron-artifact-preview";
import type { ElectronMainWindow } from "./platform-adapters/electron-main-window";
import { posthogNodeAnalytics } from "./platform-adapters/posthog-analytics";
import { POSTHOG_SESSION_ID_ARG } from "./posthog-session-arg";
@@ -255,9 +257,11 @@ export function createWindow(): void {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, "preload.js"),
+ webviewTag: true,
enableBlinkFeatures: "GetDisplayMedia",
partition: "persist:main",
additionalArguments: [
+ APP_WINDOW_ARG,
...(isDev ? ["--posthog-code-dev"] : []),
`${POSTHOG_SESSION_ID_ARG}${posthogNodeAnalytics.getOrCreateSessionId()}`,
encodeDevFlagsForArg(readDevFlagsSync()),
@@ -341,6 +345,7 @@ export function createWindow(): void {
: pathToFileURL(rendererFilePath);
setupExternalLinkHandlers(mainWindow, appHome);
+ setupArtifactPreviewWebviews(mainWindow);
setupEditableContextMenu(mainWindow);
setupCrashLogging(mainWindow);
buildApplicationMenu();
diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.ts
index 0e8ed789dc37..274673ea76cb 100644
--- a/products/desktop/apps/code/src/renderer/di/bindings.ts
+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts
@@ -229,6 +229,10 @@ import {
AGENT_PROMPT_SENDER,
type AgentPromptSender,
} from "@posthog/ui/features/sessions/agentPromptSender";
+import {
+ ARTIFACT_HTML_FRAME_COMPONENT,
+ type ArtifactHtmlFrameComponent,
+} from "@posthog/ui/features/sessions/components/artifactHtmlFrameHost";
import {
MCP_TOOL_BLOCK_COMPONENT,
type McpToolBlockComponent,
@@ -296,6 +300,7 @@ export interface RendererBindings {
[FOCUS_CONTROLLER_DEPS]: FocusControllerDeps;
[DIFF_WORKER_FACTORY]: DiffWorkerFactory;
[REVIEW_HOST]: ReviewHost;
+ [ARTIFACT_HTML_FRAME_COMPONENT]: ArtifactHtmlFrameComponent;
[MCP_TOOL_BLOCK_COMPONENT]: McpToolBlockComponent;
[MCP_APP_HOST_COMPONENT]: McpAppHostComponent;
[MCP_SANDBOX_PROXY_URL]: McpSandboxProxyUrlProvider;
diff --git a/products/desktop/apps/code/src/renderer/di/container.ts b/products/desktop/apps/code/src/renderer/di/container.ts
index 4af115d4c59a..a479a48e68d9 100644
--- a/products/desktop/apps/code/src/renderer/di/container.ts
+++ b/products/desktop/apps/code/src/renderer/di/container.ts
@@ -127,6 +127,7 @@ import {
MCP_APP_HOST_COMPONENT,
MCP_SANDBOX_PROXY_URL,
} from "@posthog/ui/features/mcp-apps/identifiers";
+import { ARTIFACT_HTML_FRAME_COMPONENT } from "@posthog/ui/features/sessions/components/artifactHtmlFrameHost";
import { MCP_TOOL_BLOCK_COMPONENT } from "@posthog/ui/features/sessions/components/session-update/identifiers";
import {
localHandoffDialog,
@@ -156,6 +157,7 @@ import {
diffWorkerFactory,
reviewHost,
} from "@renderer/features/code-review/reviewHost";
+import { ElectronArtifactHtmlFrame } from "@renderer/platform-adapters/electron-artifact-html-frame";
import {
taskDeletionHost,
taskDeletionWorkspaceClient,
@@ -280,6 +282,10 @@ container.bind(FOCUS_CONTROLLER_DEPS).toConstantValue(focusDeps);
container.bind(DIFF_WORKER_FACTORY).toConstantValue(diffWorkerFactory);
container.bind<ReviewHost>(REVIEW_HOST).toConstantValue(reviewHost);
+container
+ .bind(ARTIFACT_HTML_FRAME_COMPONENT)
+ .toConstantValue(ElectronArtifactHtmlFrame);
+
// sessions MCP tool renderer slot
container.bind(MCP_TOOL_BLOCK_COMPONENT).toConstantValue(McpToolBlock);
diff --git a/products/desktop/apps/code/src/renderer/platform-adapters/electron-artifact-html-frame.test.tsx b/products/desktop/apps/code/src/renderer/platform-adapters/electron-artifact-html-frame.test.tsx
new file mode 100644
index 000000000000..7d8a09a39bb4
--- /dev/null
+++ b/products/desktop/apps/code/src/renderer/platform-adapters/electron-artifact-html-frame.test.tsx
@@ -0,0 +1,169 @@
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import type { ButtonHTMLAttributes, ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { ARTIFACT_PREVIEW_DATA_URL_PREFIX } from "../../shared/constants";
+import {
+ artifactPreviewDataUrl,
+ ElectronArtifactHtmlFrame,
+} from "./electron-artifact-html-frame";
+
+vi.mock("@posthog/quill", () => ({
+ Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props}>{children}</button>
+ ),
+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+}));
+
+describe("ElectronArtifactHtmlFrame", () => {
+ it("encodes Unicode HTML with bounded base64 expansion", () => {
+ const html = "<h1>Résumé 📈</h1>";
+ const url = artifactPreviewDataUrl(html);
+ const binary = atob(url.slice(ARTIFACT_PREVIEW_DATA_URL_PREFIX.length));
+ const decoded = new TextDecoder().decode(
+ Uint8Array.from(binary, (character) => character.charCodeAt(0)),
+ );
+
+ expect(decoded).toBe(html);
+ expect(url.length - ARTIFACT_PREVIEW_DATA_URL_PREFIX.length).toBeLessThan(
+ new TextEncoder().encode(html).length * 2,
+ );
+ });
+
+ it("destroys and recreates the guest from trusted preview controls", async () => {
+ const send = vi.fn();
+ const message = { marker: "bridge", type: "comments" };
+ const { container } = render(
+ <ElectronArtifactHtmlFrame
+ document="<script>while (false) {}</script>"
+ fallbackDocument="<h1>Static fallback</h1>"
+ name="report.html"
+ messages={[message]}
+ onMessage={vi.fn()}
+ onOpenExternal={vi.fn()}
+ />,
+ );
+
+ const webview = await waitFor(() => {
+ const element = container.querySelector("webview");
+ if (!element) throw new Error("Expected the artifact webview to mount");
+ return element;
+ });
+ Object.assign(webview, { send });
+ act(() => webview.dispatchEvent(new Event("dom-ready")));
+ expect(send).toHaveBeenCalledWith("posthog-artifact-host-message", message);
+
+ fireEvent.click(screen.getByText("Stop preview"));
+ expect(container.querySelector("webview")).toBeNull();
+
+ fireEvent.click(screen.getByText("Restart preview"));
+ await waitFor(() =>
+ expect(container.querySelector("webview")).toBeTruthy(),
+ );
+ });
+
+ it("keeps a working preview mounted when a subresource is blocked", async () => {
+ const { container } = render(
+ <ElectronArtifactHtmlFrame
+ document="<img src='https://example.com/report.png'>"
+ fallbackDocument=""
+ name="report.html"
+ messages={[]}
+ onMessage={vi.fn()}
+ onOpenExternal={vi.fn()}
+ />,
+ );
+ const webview = await waitFor(() => {
+ const element = container.querySelector("webview");
+ if (!element) throw new Error("Expected the artifact webview to mount");
+ return element;
+ });
+
+ const blockedSubresource = new Event("did-fail-load");
+ Object.assign(blockedSubresource, {
+ errorCode: -20,
+ isMainFrame: false,
+ });
+ act(() => webview.dispatchEvent(blockedSubresource));
+ expect(container.querySelector("webview")).toBe(webview);
+
+ const abortedNavigation = new Event("did-fail-load");
+ Object.assign(abortedNavigation, { errorCode: -3, isMainFrame: true });
+ act(() => webview.dispatchEvent(abortedNavigation));
+ expect(container.querySelector("webview")).toBe(webview);
+
+ const failedMainDocument = new Event("did-fail-load");
+ Object.assign(failedMainDocument, {
+ errorCode: -105,
+ isMainFrame: true,
+ });
+ act(() => webview.dispatchEvent(failedMainDocument));
+ expect(container.querySelector("webview")).toBeNull();
+ expect(screen.getByText("Restart preview")).toBeInTheDocument();
+ });
+
+ it("updates the preview label without recreating the guest", async () => {
+ const props = {
+ document: "<h1>Report</h1>",
+ fallbackDocument: "",
+ messages: [],
+ onMessage: vi.fn(),
+ onOpenExternal: vi.fn(),
+ };
+ const { container, rerender } = render(
+ <ElectronArtifactHtmlFrame {...props} name="report.html" />,
+ );
+ const webview = await waitFor(() => {
+ const element = container.querySelector("webview");
+ if (!element) throw new Error("Expected the artifact webview to mount");
+ return element;
+ });
+
+ rerender(<ElectronArtifactHtmlFrame {...props} name="summary.html" />);
+
+ expect(container.querySelector("webview")).toBe(webview);
+ expect(webview).toHaveAttribute("aria-label", "Preview of summary.html");
+ });
+
+ it("opens links only through the trusted preload channel", async () => {
+ const onMessage = vi.fn();
+ const onOpenExternal = vi.fn();
+ const { container } = render(
+ <ElectronArtifactHtmlFrame
+ document="<a href='https://example.com'>Report</a>"
+ fallbackDocument=""
+ name="report.html"
+ messages={[]}
+ onMessage={onMessage}
+ onOpenExternal={onOpenExternal}
+ />,
+ );
+ const webview = await waitFor(() => {
+ const element = container.querySelector("webview");
+ if (!element) throw new Error("Expected the artifact webview to mount");
+ return element;
+ });
+
+ const spoofed = new Event("ipc-message");
+ Object.assign(spoofed, {
+ channel: "posthog-artifact-message",
+ args: [{ type: "open-external", href: "https://example.com/spoof" }],
+ });
+ act(() => webview.dispatchEvent(spoofed));
+ expect(onOpenExternal).not.toHaveBeenCalled();
+ expect(onMessage).not.toHaveBeenCalled();
+
+ const trusted = new Event("ipc-message");
+ Object.assign(trusted, {
+ channel: "posthog-artifact-open-external",
+ args: ["https://example.com/report"],
+ });
+ act(() => webview.dispatchEvent(trusted));
+ expect(onOpenExternal).toHaveBeenCalledWith("https://example.com/report");
+ });
+});
diff --git a/products/desktop/apps/code/src/renderer/platform-adapters/electron-artifact-html-frame.tsx b/products/desktop/apps/code/src/renderer/platform-adapters/electron-artifact-html-frame.tsx
new file mode 100644
index 000000000000..db6df3b6913c
--- /dev/null
+++ b/products/desktop/apps/code/src/renderer/platform-adapters/electron-artifact-html-frame.tsx
@@ -0,0 +1,194 @@
+import { Button, Text } from "@posthog/quill";
+import {
+ ARTIFACT_HTML_BRIDGE_MARKER,
+ type ArtifactHtmlFrameProps,
+} from "@posthog/ui/features/sessions/components/artifactHtmlFrameHost";
+import {
+ useCallback,
+ useEffect,
+ useEffectEvent,
+ useRef,
+ useState,
+} from "react";
+import {
+ ARTIFACT_HOST_TO_PREVIEW_CHANNEL,
+ ARTIFACT_OPEN_EXTERNAL_CHANNEL,
+ ARTIFACT_PREVIEW_DATA_URL_PREFIX,
+ ARTIFACT_PREVIEW_PARTITION_PREFIX,
+ ARTIFACT_PREVIEW_TO_HOST_CHANNEL,
+} from "../../shared/constants";
+
+type ArtifactWebviewElement = HTMLElement & {
+ send: (channel: string, ...args: unknown[]) => void;
+};
+
+type WebviewIpcMessageEvent = Event & {
+ channel: string;
+ args: unknown[];
+};
+
+type WebviewLoadFailureEvent = Event & {
+ errorCode?: number;
+ isMainFrame?: boolean;
+};
+
+type PreviewState = "running" | "stopped" | "failed" | "unresponsive";
+
+export function artifactPreviewDataUrl(htmlDocument: string): string {
+ const bytes = new TextEncoder().encode(htmlDocument);
+ let binary = "";
+ for (let offset = 0; offset < bytes.length; offset += 32_768) {
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 32_768));
+ }
+ return `${ARTIFACT_PREVIEW_DATA_URL_PREFIX}${btoa(binary)}`;
+}
+
+type RunningArtifactWebviewProps = ArtifactHtmlFrameProps & {
+ onStateChange: (state: PreviewState) => void;
+};
+
+function RunningArtifactWebview({
+ document: htmlDocument,
+ name,
+ messages,
+ onMessage,
+ onOpenExternal,
+ onStateChange,
+}: RunningArtifactWebviewProps) {
+ const mountRef = useRef<HTMLDivElement>(null);
+ const webviewRef = useRef<ArtifactWebviewElement | null>(null);
+ const readyRef = useRef(false);
+ const messagesRef = useRef(messages);
+
+ const sendMessages = useCallback(() => {
+ if (!readyRef.current) return;
+ for (const message of messagesRef.current) {
+ webviewRef.current?.send(ARTIFACT_HOST_TO_PREVIEW_CHANNEL, message);
+ }
+ }, []);
+ const reportState = useEffectEvent(onStateChange);
+ const openExternal = useEffectEvent(onOpenExternal);
+ const receiveMessage = useEffectEvent(onMessage);
+
+ useEffect(() => {
+ messagesRef.current = messages;
+ sendMessages();
+ }, [messages, sendMessages]);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reportState is an Effect Event and must not be a dependency.
+ useEffect(() => {
+ const mount = mountRef.current;
+ if (!mount) {
+ reportState("failed");
+ return;
+ }
+
+ const webview = document.createElement("webview") as ArtifactWebviewElement;
+ const partition = `${ARTIFACT_PREVIEW_PARTITION_PREFIX}${crypto.randomUUID()}`;
+ webview.className = "size-full";
+ webview.setAttribute("partition", partition);
+ webview.setAttribute("src", artifactPreviewDataUrl(htmlDocument));
+
+ const onReady = () => {
+ readyRef.current = true;
+ reportState("running");
+ sendMessages();
+ };
+ const onIpcMessage = (event: Event) => {
+ const ipcEvent = event as WebviewIpcMessageEvent;
+ if (ipcEvent.channel === ARTIFACT_OPEN_EXTERNAL_CHANNEL) {
+ const href = ipcEvent.args[0];
+ if (typeof href === "string") openExternal(href);
+ return;
+ }
+ if (ipcEvent.channel !== ARTIFACT_PREVIEW_TO_HOST_CHANNEL) return;
+ const data = ipcEvent.args[0] as Record<string, unknown> | null;
+ if (data?.type === "open-external") return;
+ if (
+ data?.marker === ARTIFACT_HTML_BRIDGE_MARKER &&
+ data.type === "ready"
+ ) {
+ sendMessages();
+ }
+ receiveMessage(data, webview.getBoundingClientRect());
+ };
+ const onFailed = (event: Event) => {
+ const failure = event as WebviewLoadFailureEvent;
+ if (failure.isMainFrame === false || failure.errorCode === -3) return;
+ reportState("failed");
+ };
+ const onGone = () => reportState("failed");
+ const onUnresponsive = () => reportState("unresponsive");
+ const onResponsive = () => reportState("running");
+
+ webview.addEventListener("dom-ready", onReady);
+ webview.addEventListener("ipc-message", onIpcMessage);
+ webview.addEventListener("did-fail-load", onFailed);
+ webview.addEventListener("render-process-gone", onGone);
+ webview.addEventListener("unresponsive", onUnresponsive);
+ webview.addEventListener("responsive", onResponsive);
+ mount.appendChild(webview);
+ webviewRef.current = webview;
+
+ return () => {
+ webview.removeEventListener("dom-ready", onReady);
+ webview.removeEventListener("ipc-message", onIpcMessage);
+ webview.removeEventListener("did-fail-load", onFailed);
+ webview.removeEventListener("render-process-gone", onGone);
+ webview.removeEventListener("unresponsive", onUnresponsive);
+ webview.removeEventListener("responsive", onResponsive);
+ readyRef.current = false;
+ webviewRef.current = null;
+ webview.remove();
+ };
+ }, [htmlDocument, sendMessages]);
+
+ useEffect(() => {
+ webviewRef.current?.setAttribute("aria-label", `Preview of ${name}`);
+ }, [name]);
+
+ return <div ref={mountRef} className="size-full" />;
+}
+
+export function ElectronArtifactHtmlFrame(props: ArtifactHtmlFrameProps) {
+ const [state, setState] = useState<PreviewState>("running");
+ const active = state === "running" || state === "unresponsive";
+ const message =
+ state === "failed"
+ ? "The preview stopped. Restart it to run the HTML again."
+ : state === "unresponsive"
+ ? "The preview isn't responding. Stop it or restart it."
+ : null;
+
+ return (
+ <div className="relative size-full bg-white">
+ {active ? (
+ <RunningArtifactWebview {...props} onStateChange={setState} />
+ ) : null}
+ <div className="absolute top-2 right-2 z-50 flex items-center gap-2">
+ {message ? (
+ <div className="rounded bg-background px-2 py-1 shadow">
+ <Text size="xs">{message}</Text>
+ </div>
+ ) : null}
+ {active ? (
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => setState("stopped")}
+ >
+ Stop preview
+ </Button>
+ ) : (
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => setState("running")}
+ >
+ Restart preview
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/products/desktop/apps/code/src/shared/artifact-preview-message.test.ts b/products/desktop/apps/code/src/shared/artifact-preview-message.test.ts
new file mode 100644
index 000000000000..44351f3eb6a9
--- /dev/null
+++ b/products/desktop/apps/code/src/shared/artifact-preview-message.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+import { sanitizeArtifactBridgeMessage } from "./artifact-preview-message";
+
+const marker = "__POSTHOG_ARTIFACT_COMMENT_BRIDGE__";
+
+function selectionMessage(): Record<string, unknown> {
+ return {
+ marker,
+ channel: "artifact-comments-1",
+ type: "selection",
+ anchor: {
+ kind: "text",
+ quote: "Report",
+ prefix: "",
+ suffix: " total",
+ start: 0,
+ end: 6,
+ },
+ rect: { top: 1, left: 2, right: 3, bottom: 4, width: 1, height: 3 },
+ triggerRect: {
+ top: 5,
+ left: 6,
+ right: 7,
+ bottom: 8,
+ width: 1,
+ height: 3,
+ },
+ };
+}
+
+describe("sanitizeArtifactBridgeMessage", () => {
+ it("copies only bounded selection fields to guest IPC", () => {
+ const value = selectionMessage();
+ value.untrustedPayload = "x".repeat(1_000_000);
+
+ const sanitized = sanitizeArtifactBridgeMessage(value);
+
+ expect(sanitized).toEqual(selectionMessage());
+ expect(sanitized).not.toHaveProperty("untrustedPayload");
+ });
+
+ it.each([
+ ["an oversized quote", { anchor: { quote: "x".repeat(10_001) } }],
+ [
+ "too many resolutions",
+ {
+ type: "resolutions",
+ items: Array.from({ length: 501 }, (_, index) => ({
+ id: `comment-${index}`,
+ status: "exact",
+ })),
+ },
+ ],
+ ["an unsupported message", { type: "open-external" }],
+ ])("rejects %s", (_name, override) => {
+ const value = selectionMessage();
+ Object.assign(value, override);
+ if ("anchor" in override) {
+ value.anchor = {
+ ...(selectionMessage().anchor as Record<string, unknown>),
+ ...override.anchor,
+ };
+ }
+
+ expect(sanitizeArtifactBridgeMessage(value)).toBeNull();
+ });
+});
diff --git a/products/desktop/apps/code/src/shared/artifact-preview-message.ts b/products/desktop/apps/code/src/shared/artifact-preview-message.ts
new file mode 100644
index 000000000000..b9aa47530bd7
--- /dev/null
+++ b/products/desktop/apps/code/src/shared/artifact-preview-message.ts
@@ -0,0 +1,97 @@
+const ARTIFACT_BRIDGE_MARKER = "__POSTHOG_ARTIFACT_COMMENT_BRIDGE__";
+const MAX_ITEMS = 500;
+const MAX_ID_LENGTH = 128;
+const MAX_CHANNEL_LENGTH = 256;
+const MAX_QUOTE_LENGTH = 10_000;
+const CONTEXT_LENGTH = 32;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function boundedString(value: unknown, maxLength: number): value is string {
+ return typeof value === "string" && value.length <= maxLength;
+}
+
+function finiteRect(value: unknown): Record<string, number> | null {
+ if (!isRecord(value)) return null;
+ const rect: Record<string, number> = {};
+ for (const key of ["top", "left", "right", "bottom", "width", "height"]) {
+ const field = value[key];
+ if (typeof field !== "number" || !Number.isFinite(field)) return null;
+ rect[key] = field;
+ }
+ return rect;
+}
+
+export function sanitizeArtifactBridgeMessage(
+ value: unknown,
+): Record<string, unknown> | null {
+ if (
+ !isRecord(value) ||
+ value.marker !== ARTIFACT_BRIDGE_MARKER ||
+ !boundedString(value.channel, MAX_CHANNEL_LENGTH)
+ ) {
+ return null;
+ }
+ const base = {
+ marker: ARTIFACT_BRIDGE_MARKER,
+ channel: value.channel,
+ };
+ if (value.type === "ready") return { ...base, type: "ready" };
+ if (
+ value.type === "activate" &&
+ boundedString(value.id, MAX_ID_LENGTH) &&
+ value.id.length > 0
+ ) {
+ return { ...base, type: "activate", id: value.id };
+ }
+ if (value.type === "resolutions" && Array.isArray(value.items)) {
+ if (value.items.length > MAX_ITEMS) return null;
+ const items: { id: string; status: string }[] = [];
+ for (const item of value.items) {
+ if (
+ !isRecord(item) ||
+ !boundedString(item.id, MAX_ID_LENGTH) ||
+ item.id.length === 0 ||
+ !["exact", "reanchored", "orphaned"].includes(String(item.status))
+ ) {
+ return null;
+ }
+ items.push({ id: item.id, status: String(item.status) });
+ }
+ return { ...base, type: "resolutions", items };
+ }
+ if (value.type !== "selection" || !isRecord(value.anchor)) return null;
+ const anchor = value.anchor;
+ if (
+ anchor.kind !== "text" ||
+ !boundedString(anchor.quote, MAX_QUOTE_LENGTH) ||
+ anchor.quote.length === 0 ||
+ !boundedString(anchor.prefix, CONTEXT_LENGTH) ||
+ !boundedString(anchor.suffix, CONTEXT_LENGTH) ||
+ !Number.isInteger(anchor.start) ||
+ !Number.isInteger(anchor.end) ||
+ Number(anchor.start) < 0 ||
+ Number(anchor.end) <= Number(anchor.start)
+ ) {
+ return null;
+ }
+ const rect = finiteRect(value.rect);
+ const triggerRect = finiteRect(value.triggerRect);
+ if (!rect || !triggerRect) return null;
+ return {
+ ...base,
+ type: "selection",
+ anchor: {
+ kind: "text",
+ quote: anchor.quote,
+ prefix: anchor.prefix,
+ suffix: anchor.suffix,
+ start: anchor.start,
+ end: anchor.end,
+ },
+ rect,
+ triggerRect,
+ };
+}
diff --git a/products/desktop/apps/code/src/shared/constants.ts b/products/desktop/apps/code/src/shared/constants.ts
index 0f969745c2ab..e675a9e70575 100644
--- a/products/desktop/apps/code/src/shared/constants.ts
+++ b/products/desktop/apps/code/src/shared/constants.ts
@@ -6,6 +6,14 @@ export const SELF_DRIVING_SETUP_TASK_FLAG =
export const SYNC_CLOUD_TASKS_FLAG = "posthog-code-sync-cloud-tasks";
export const DISCOVERY_RUN_FLAG = "posthog-code-discovery-run";
export const BRANCH_PREFIX = "posthog-code/";
+export const APP_WINDOW_ARG = "--posthog-app-window";
+export const ARTIFACT_PREVIEW_ARG = "--posthog-artifact-preview";
+export const ARTIFACT_OPEN_EXTERNAL_CHANNEL = "posthog-artifact-open-external";
+export const ARTIFACT_HOST_TO_PREVIEW_CHANNEL = "posthog-artifact-host-message";
+export const ARTIFACT_PREVIEW_TO_HOST_CHANNEL = "posthog-artifact-message";
+export const ARTIFACT_PREVIEW_DATA_URL_PREFIX =
+ "data:text/html;charset=utf-8;base64,";
+export const ARTIFACT_PREVIEW_PARTITION_PREFIX = "artifact-preview-";
export const DATA_DIR = ".posthog-code";
export const WORKTREES_DIR = ".posthog-code/worktrees";
export const LEGACY_DATA_DIRS = [
diff --git a/products/desktop/apps/code/src/shared/electron-log-preload.d.ts b/products/desktop/apps/code/src/shared/electron-log-preload.d.ts
new file mode 100644
index 000000000000..a1c2703fb477
--- /dev/null
+++ b/products/desktop/apps/code/src/shared/electron-log-preload.d.ts
@@ -0,0 +1 @@
+declare module "electron-log/preload";
diff --git a/products/desktop/docs/cloud-task-artifacts.md b/products/desktop/docs/cloud-task-artifacts.md
index 9f103b1cd0a5..20f9eb125e99 100644
--- a/products/desktop/docs/cloud-task-artifacts.md
+++ b/products/desktop/docs/cloud-task-artifacts.md
@@ -7,3 +7,5 @@ Files left in the sandbox filesystem are temporary and cannot be downloaded afte
On success the tool returns a presigned download URL for the uploaded file (minted by the finalize-upload endpoint), so an agent can link to the artifact directly in its final response. The URL is time-limited and not persisted on the run manifest; re-fetch the artifact through the download endpoint for a durable link.
Repository changes should continue to be delivered through git rather than duplicated as task artifacts. A single uploaded artifact is limited to 30 MB.
+
+The desktop app runs scripts embedded in HTML artifacts inside an isolated preview process. The preview cannot access Node.js, Electron, PostHog credentials, remote resources, downloads, or device permissions. Use **Stop preview** if a script becomes unresponsive, then use **Restart preview** to load it in a fresh process.
diff --git a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
index 4b62468d5a4f..302ae6ff7a40 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/AnnotatedArtifactHtml.tsx
@@ -8,26 +8,23 @@ import type { EditorSelection } from "@posthog/ui/features/code-editor/component
import { SelectionCommentOverlay } from "@posthog/ui/features/code-editor/components/SelectionCommentOverlay";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { parseHttpsUrl } from "@posthog/ui/utils/posthogLinks";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { artifactHtmlDocument } from "./artifactPreviewDocument";
+import { useCallback, useMemo, useRef, useState } from "react";
+import { ArtifactHtmlFrame } from "./artifactHtmlFrame";
+import {
+ ARTIFACT_HTML_BRIDGE_MARKER,
+ type ArtifactHtmlFrameRect,
+} from "./artifactHtmlFrameHost";
+import {
+ artifactHtmlDocument,
+ scriptedArtifactHtmlDocument,
+} from "./artifactPreviewDocument";
import {
type CommentLocateRequest,
type HighlightResolution,
readCommentContext,
} from "./commentViewTypes";
-const BRIDGE_MARKER = "__POSTHOG_ARTIFACT_COMMENT_BRIDGE__";
-
-type FrameRect = {
- top: number;
- left: number;
- right: number;
- bottom: number;
- width: number;
- height: number;
-};
-
-function isFrameRect(value: unknown): value is FrameRect {
+function isFrameRect(value: unknown): value is ArtifactHtmlFrameRect {
if (!value || typeof value !== "object") return false;
return ["top", "left", "right", "bottom", "width", "height"].every((key) => {
const field = (value as Record<string, unknown>)[key];
@@ -62,25 +59,27 @@ export function AnnotatedArtifactHtml({
) => void | Promise<void>;
onResolutionsChange: (resolutions: Map<string, HighlightResolution>) => void;
}) {
- const iframeRef = useRef<HTMLIFrameElement>(null);
const channelRef = useRef(`artifact-comments-${crypto.randomUUID()}`);
const [pendingAnchor, setPendingAnchor] = useState<TextCommentAnchor | null>(
null,
);
const [selection, setSelection] = useState<EditorSelection | null>(null);
- const [documentUrl, setDocumentUrl] = useState<string | null>(null);
-
- useEffect(() => {
- const document = artifactHtmlDocument(
- html,
- commentsEnabled ? channelRef.current : undefined,
- );
- const nextDocumentUrl = URL.createObjectURL(
- new Blob([document], { type: "text/html" }),
- );
- setDocumentUrl(nextDocumentUrl);
- return () => URL.revokeObjectURL(nextDocumentUrl);
- }, [commentsEnabled, html]);
+ const previewDocument = useMemo(
+ () =>
+ scriptedArtifactHtmlDocument(
+ html,
+ commentsEnabled ? channelRef.current : undefined,
+ ),
+ [commentsEnabled, html],
+ );
+ const fallbackDocument = useMemo(
+ () =>
+ artifactHtmlDocument(
+ html,
+ commentsEnabled ? channelRef.current : undefined,
+ ),
+ [commentsEnabled, html],
+ );
const bridgeItems = useMemo(
() =>
@@ -100,74 +99,39 @@ export function AnnotatedArtifactHtml({
[activeThreadId, comments],
);
- const sendComments = useCallback(() => {
- iframeRef.current?.contentWindow?.postMessage(
+ const messages = useMemo(() => {
+ if (!commentsEnabled) return [];
+ const next: Record<string, unknown>[] = [
{
- marker: BRIDGE_MARKER,
+ marker: ARTIFACT_HTML_BRIDGE_MARKER,
channel: channelRef.current,
type: "comments",
items: bridgeItems,
},
- "*",
- );
- }, [bridgeItems]);
-
- useEffect(() => {
- sendComments();
- }, [sendComments]);
-
- const sendLocate = useCallback(() => {
- if (!locateRequest) return;
- iframeRef.current?.contentWindow?.postMessage(
- {
- marker: BRIDGE_MARKER,
+ ];
+ if (locateRequest) {
+ next.push({
+ marker: ARTIFACT_HTML_BRIDGE_MARKER,
channel: channelRef.current,
type: "locate",
id: locateRequest.id,
- },
- "*",
- );
- }, [locateRequest]);
-
- useEffect(() => {
- sendLocate();
- }, [sendLocate]);
-
- const activateThreadRef = useRef(onActivateThread);
- const resolutionsChangeRef = useRef(onResolutionsChange);
- const sendCommentsRef = useRef(sendComments);
- const sendLocateRef = useRef(sendLocate);
-
- useEffect(() => {
- activateThreadRef.current = onActivateThread;
- resolutionsChangeRef.current = onResolutionsChange;
- sendCommentsRef.current = sendComments;
- sendLocateRef.current = sendLocate;
- }, [onActivateThread, onResolutionsChange, sendComments, sendLocate]);
+ });
+ }
+ return next;
+ }, [bridgeItems, commentsEnabled, locateRequest]);
- useEffect(() => {
- const receive = (event: MessageEvent) => {
- if (event.source !== iframeRef.current?.contentWindow) return;
- const data = event.data as Record<string, unknown> | null;
+ const receive = useCallback(
+ (value: unknown, frameBox: ArtifactHtmlFrameRect) => {
+ const data = value as Record<string, unknown> | null;
if (
!data ||
- data.marker !== BRIDGE_MARKER ||
+ data.marker !== ARTIFACT_HTML_BRIDGE_MARKER ||
data.channel !== channelRef.current
) {
return;
}
- if (data.type === "ready") {
- sendCommentsRef.current();
- sendLocateRef.current();
- return;
- }
- if (data.type === "open-external" && typeof data.href === "string") {
- const url = parseHttpsUrl(data.href);
- if (url) openExternalUrl(url.href);
- return;
- }
if (data.type === "activate" && typeof data.id === "string") {
- activateThreadRef.current(data.id);
+ onActivateThread(data.id);
return;
}
if (data.type === "resolutions" && Array.isArray(data.items)) {
@@ -184,14 +148,12 @@ export function AnnotatedArtifactHtml({
resolutions.set(id, status);
}
}
- resolutionsChangeRef.current(resolutions);
+ onResolutionsChange(resolutions);
return;
}
if (data.type !== "selection" || !isFrameRect(data.triggerRect)) return;
const parsed = commentAnchorSchema.safeParse(data.anchor);
if (!parsed.success || parsed.data.kind !== "text") return;
- const frameBox = iframeRef.current?.getBoundingClientRect();
- if (!frameBox) return;
setPendingAnchor(parsed.data);
setSelection({
text: parsed.data.quote,
@@ -205,9 +167,13 @@ export function AnnotatedArtifactHtml({
),
},
});
- };
- window.addEventListener("message", receive);
- return () => window.removeEventListener("message", receive);
+ },
+ [onActivateThread, onResolutionsChange],
+ );
+
+ const openExternal = useCallback((href: string) => {
+ const url = parseHttpsUrl(href);
+ if (url) openExternalUrl(url.href);
}, []);
const dismiss = () => {
@@ -217,14 +183,13 @@ export function AnnotatedArtifactHtml({
return (
<div className="relative size-full">
- <iframe
- ref={iframeRef}
- className="size-full border-0 bg-white"
- sandbox="allow-scripts"
- referrerPolicy="no-referrer"
- src={documentUrl ?? "about:blank"}
- title={`Preview of ${name}`}
- onLoad={sendComments}
+ <ArtifactHtmlFrame
+ document={previewDocument}
+ fallbackDocument={fallbackDocument}
+ name={name}
+ messages={messages}
+ onMessage={receive}
+ onOpenExternal={openExternal}
/>
<SelectionCommentOverlay
selection={selection}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
index f358aee97585..250773ad3ec9 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
@@ -22,6 +22,7 @@ import { ArtifactPreview } from "./ArtifactPreview";
import {
artifactHtmlDocument,
artifactPreviewBlob,
+ scriptedArtifactHtmlDocument,
} from "./artifactPreviewDocument";
const previewBlob = new Blob(["<h1>Artifact content</h1>"], {
@@ -47,6 +48,7 @@ vi.mock("@posthog/core/sessions/sessionService", () => ({
vi.mock("@posthog/di/react", () => ({
useService: () => ({}),
+ useServiceOptional: () => null,
}));
vi.mock("@posthog/ui/features/auth/store", () => ({
@@ -812,16 +814,25 @@ describe("ArtifactPreview", () => {
expect(document).toContain("scrollIntoView");
expect(document).toContain("new MutationObserver");
expect(document).toContain("state.renderTimer");
- const nonce = document.match(
- /<script nonce="([^"]+)" data-posthog-artifact-comments>/,
- )?.[1];
- expect(nonce).toBeTruthy();
- expect(document).toContain(`script-src &#39;nonce-${nonce}&#39;`);
+ expect(document).toMatch(/script-src &#39;nonce-[^&]+&#39;/);
expect(document).not.toContain(
"script-src &#39;self&#39; &#39;unsafe-inline&#39;",
);
});
+ it("allows embedded scripts without allowing network access", () => {
+ const document = scriptedArtifactHtmlDocument(
+ '<script>document.body.dataset.rendered="yes"</script>',
+ "test-channel",
+ );
+
+ expect(document).toContain('document.body.dataset.rendered="yes"');
+ expect(document).toContain(
+ "script-src &#39;self&#39; &#39;unsafe-inline&#39;",
+ );
+ expect(document).toContain("connect-src &#39;none&#39;");
+ });
+
it("does not parse HTML without a possible refresh directive", () => {
const parse = vi.spyOn(DOMParser.prototype, "parseFromString");
@@ -847,9 +858,6 @@ describe("ArtifactPreview", () => {
expect(document).toContain("form-action &#39;none&#39;");
expect(document).toContain("img-src &#39;self&#39; data:");
expect(document).toContain("script-src &#39;none&#39;");
- expect(document).not.toContain(
- "script-src &#39;self&#39; &#39;unsafe-inline&#39;",
- );
});
it.each([
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
index 46d8e7be547b..59c162f5a373 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlCommentBridge.ts
@@ -3,13 +3,13 @@ import { resolveTextCommentAnchor } from "@posthog/core/comments/anchors";
const BRIDGE_MARKER = "__POSTHOG_ARTIFACT_COMMENT_BRIDGE__";
/**
- * Runs inside an opaque-origin sandboxed artifact iframe. It never receives
- * credentials or writes to the API: selection and highlight traffic goes
- * through the trusted parent with a per-view channel.
+ * Runs inside the isolated artifact document. It never receives credentials
+ * or writes to the API; selection traffic uses a per-view host channel.
*/
-function artifactHtmlCommentBridge(channel: string, nonce: string): string {
+function artifactHtmlCommentBridge(channel: string, nonce?: string): string {
const safeChannel = JSON.stringify(channel);
- return `<script nonce="${nonce}" data-posthog-artifact-comments>(function(){
+ const nonceAttribute = nonce ? ` nonce="${nonce}"` : "";
+ return `<script${nonceAttribute} data-posthog-artifact-comments>(function(){
"use strict";
var CHANNEL=${safeChannel};
var MARKER=${JSON.stringify(BRIDGE_MARKER)};
@@ -42,7 +42,7 @@ style();send("ready");
export function injectArtifactHtmlCommentBridge(
html: string,
channel: string,
- nonce: string,
+ nonce?: string,
): string {
const bridge = artifactHtmlCommentBridge(channel, nonce);
const bodyEnd = html.toLowerCase().lastIndexOf("</body>");
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlFrame.tsx b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlFrame.tsx
new file mode 100644
index 000000000000..43242fba1e10
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlFrame.tsx
@@ -0,0 +1,91 @@
+import { useServiceOptional } from "@posthog/di/react";
+import {
+ type SyntheticEvent,
+ useEffect,
+ useEffectEvent,
+ useRef,
+ useState,
+} from "react";
+import {
+ ARTIFACT_HTML_BRIDGE_MARKER,
+ ARTIFACT_HTML_FRAME_COMPONENT,
+ type ArtifactHtmlFrameComponent,
+ type ArtifactHtmlFrameProps,
+} from "./artifactHtmlFrameHost";
+
+function IframeArtifactHtmlFrame({
+ document: htmlDocument,
+ name,
+ messages,
+ onMessage,
+ onOpenExternal,
+}: ArtifactHtmlFrameProps) {
+ const iframeRef = useRef<HTMLIFrameElement>(null);
+ const [documentUrl, setDocumentUrl] = useState<string | null>(null);
+ const sendMessages = useEffectEvent(() => {
+ for (const message of messages) {
+ iframeRef.current?.contentWindow?.postMessage(message, "*");
+ }
+ });
+ const receiveMessage = useEffectEvent(onMessage);
+ const openExternal = useEffectEvent(onOpenExternal);
+
+ useEffect(() => {
+ const nextDocumentUrl = URL.createObjectURL(
+ new Blob([htmlDocument], { type: "text/html" }),
+ );
+ setDocumentUrl(nextDocumentUrl);
+ return () => URL.revokeObjectURL(nextDocumentUrl);
+ }, [htmlDocument]);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: sendMessages is an Effect Event and must not be a dependency.
+ useEffect(() => {
+ void messages;
+ sendMessages();
+ }, [messages]);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: callbacks are Effect Events and must not be dependencies.
+ useEffect(() => {
+ const receive = (event: MessageEvent) => {
+ if (event.source !== iframeRef.current?.contentWindow) return;
+ const data = event.data as Record<string, unknown> | null;
+ if (data?.marker !== ARTIFACT_HTML_BRIDGE_MARKER) return;
+ if (data.type === "ready") sendMessages();
+ if (data.type === "open-external" && typeof data.href === "string") {
+ openExternal(data.href);
+ return;
+ }
+ const frameRect = iframeRef.current?.getBoundingClientRect();
+ if (!frameRect) return;
+ receiveMessage(data, frameRect);
+ };
+ window.addEventListener("message", receive);
+ return () => window.removeEventListener("message", receive);
+ }, []);
+
+ const handleLoad = (_event: SyntheticEvent<HTMLIFrameElement>) =>
+ sendMessages();
+
+ return (
+ <iframe
+ ref={iframeRef}
+ className="size-full border-0 bg-white"
+ sandbox="allow-scripts"
+ referrerPolicy="no-referrer"
+ src={documentUrl ?? "about:blank"}
+ title={`Preview of ${name}`}
+ onLoad={handleLoad}
+ />
+ );
+}
+
+export function ArtifactHtmlFrame(props: ArtifactHtmlFrameProps) {
+ const HostFrame = useServiceOptional<ArtifactHtmlFrameComponent>(
+ ARTIFACT_HTML_FRAME_COMPONENT,
+ );
+ return HostFrame ? (
+ <HostFrame {...props} />
+ ) : (
+ <IframeArtifactHtmlFrame {...props} document={props.fallbackDocument} />
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlFrameHost.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlFrameHost.ts
new file mode 100644
index 000000000000..be76cff7edad
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactHtmlFrameHost.ts
@@ -0,0 +1,28 @@
+import type { ComponentType } from "react";
+
+export const ARTIFACT_HTML_BRIDGE_MARKER =
+ "__POSTHOG_ARTIFACT_COMMENT_BRIDGE__";
+
+export type ArtifactHtmlFrameRect = {
+ top: number;
+ left: number;
+ right: number;
+ bottom: number;
+ width: number;
+ height: number;
+};
+
+export type ArtifactHtmlFrameProps = {
+ document: string;
+ fallbackDocument: string;
+ name: string;
+ messages: readonly Record<string, unknown>[];
+ onMessage: (data: unknown, frameRect: ArtifactHtmlFrameRect) => void;
+ onOpenExternal: (href: string) => void;
+};
+
+export type ArtifactHtmlFrameComponent = ComponentType<ArtifactHtmlFrameProps>;
+
+export const ARTIFACT_HTML_FRAME_COMPONENT = Symbol.for(
+ "posthog.ui.ArtifactHtmlFrameComponent",
+);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts b/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
index 53ead2a2dc2d..ffe20b2f36d2 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/artifactPreviewDocument.ts
@@ -32,6 +32,17 @@ export function artifactHtmlDocument(
nonce,
);
}
+
+export function scriptedArtifactHtmlDocument(
+ html: string,
+ commentBridgeChannel?: string,
+): string {
+ const safeHtml = removeAutomaticRedirects(html);
+ if (!commentBridgeChannel) return applyCspToHtml(safeHtml);
+ return applyCspToHtml(
+ injectArtifactHtmlCommentBridge(safeHtml, commentBridgeChannel),
+ );
+}
export async function artifactPreviewBlob(
blob: Blob,
filename: string,