Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): preview interactive HTML attachments (#1100)
Generd84079ac91c9
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.tsindex 9dc41f257..d39bcdfa0 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.test.ts@@ -362,3 +362,75 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {expect(await res.json()).toEqual({ error: "internal error", code: "internal" })})})++describe("HTML attachment preview mode", () => {+ const previewReq = (headers: Record<string, string> = {}) => new NextRequest("http://localhost/api/community/channels/c1/attachments/att_1?preview=html", { headers })+ const htmlRow = (over: Record<string, unknown> = {}) => persistedRow({ filename: "page.html", contentType: "text/html", size: 40, ...over })+ beforeEach(() => { vi.clearAllMocks() })++ it("checks readability before type validation or reading the object", async () => {+ mockGetReadableAttachmentById.mockResolvedValue(null)+ const response = await GET(previewReq(), ctx())+ expect(response.status).toBe(404)+ expect(await response.json()).toEqual({ error: "attachment not found" })+ expect(mockR2Get).not.toHaveBeenCalled()+ })+ it("returns inline executable HTML with opaque-origin CSP, no storage cache and an early bootstrap", async () => {+ allowPersistedHuman(htmlRow())+ mockR2Get.mockResolvedValue(r2Object({}, new TextEncoder().encode('<!doctype html><html><body><button onclick="this.textContent=2">1</button></body></html>')))+ const response = await GET(previewReq({ Range: "bytes=0-5" }), ctx())+ expect(response.status).toBe(200)+ expect(mockGetReadableAttachmentById).toHaveBeenCalledWith(expect.anything(), "att_1", "u1")+ expect(response.headers.get("content-type")).toBe("text/html; charset=utf-8")+ expect(response.headers.get("content-disposition")).toContain("inline")+ expect(response.headers.get("content-security-policy")).toContain("sandbox allow-scripts")+ expect(response.headers.get("content-security-policy")).not.toContain("allow-same-origin")+ expect(response.headers.get("cache-control")).toBe("private, no-store")+ expect(response.headers.get("referrer-policy")).toBe("no-referrer")+ expect(response.headers.get("x-content-type-options")).toBe("nosniff")+ expect(response.headers.get("content-length")).toBeNull()+ expect(await response.text()).toContain("alook-html-ready")+ expect(mockR2Get).toHaveBeenCalledExactlyOnceWith("channel/c_row/uuid/a.png")+ })+ it("preserves ordinary HTML download and the bot download contract", async () => {+ for (const request of [req(), previewReq({ Authorization: "Bearer crk_abc" })]) {+ allowPersistedHuman(htmlRow())+ mockR2Get.mockResolvedValue(r2Object({}, new TextEncoder().encode("<p>original</p>")))+ const response = await GET(request, ctx())+ expect(await response.text()).toBe("<p>original</p>")+ expect(response.headers.get("content-security-policy")).toContain("default-src 'none'")+ expect(response.headers.get("content-security-policy")).not.toContain("allow-scripts")+ if (request.headers.has("authorization")) expect(response.headers.get("x-alook-filename")).toBe("page.html")+ else expect(response.headers.get("content-disposition")).toContain("attachment")+ }+ })+ it("rejects incompatible type and declared oversize without an object read", async () => {+ for (const [row, status] of [[htmlRow({ contentType: "image/png" }), 415], [htmlRow({ size: 2 * 1024 * 1024 + 1 }), 422]] as const) {+ allowPersistedHuman(row)+ expect((await GET(previewReq(), ctx())).status).toBe(status)+ }+ expect(mockR2Get).not.toHaveBeenCalled()+ })+ it.each(["", "<style>body{height:100vh}</style>"])("fails invalid HTML in this one response", async (html) => {+ allowPersistedHuman(htmlRow())+ mockR2Get.mockResolvedValue(r2Object({}, new TextEncoder().encode(html)))+ const response = await GET(previewReq(), ctx())+ expect(response.status).toBe(422)+ expect(response.headers.get("cache-control")).toBe("private, no-store")+ })+ it("rejects actual overflow even when the stored size is small", async () => {+ allowPersistedHuman(htmlRow({ size: 1 }))+ const cancel = vi.fn()+ mockR2Get.mockResolvedValue(r2Object({ body: new ReadableStream({ start(c) { c.enqueue(new Uint8Array(2 * 1024 * 1024 + 1)) }, cancel }) }))+ const response = await GET(previewReq(), ctx())+ expect(response.status).toBe(422)+ expect(cancel).toHaveBeenCalledOnce()+ })+ it("separates missing storage from a failed object stream", async () => {+ allowPersistedHuman(htmlRow())+ mockR2Get.mockResolvedValue(null)+ expect((await GET(previewReq(), ctx())).status).toBe(502)+ mockR2Get.mockResolvedValue(r2Object({ body: new ReadableStream({ start(c) { c.error(new Error("read failure")) } }) }))+ expect((await GET(previewReq(), ctx())).status).toBe(500)+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.tsindex 4d129eb5a..2036d0947 100644--- a/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/attachments/[attachmentId]/route.ts@@ -8,6 +8,8 @@ import { authorizeAttachment } from "@/lib/community/attachment-authorization"import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"import { resolveAttachmentPresentation, resolveMediaContentType } from "@/lib/community/attachment-presentation"import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"+import { isHtmlPreviewFile, MAX_HTML_PREVIEW_BYTES } from "@/lib/community/html-preview-policy"+import { HTML_PREVIEW_CSP, HtmlPreviewValidationError, prepareHtmlPreview, readHtmlPreview } from "@/lib/community/html-attachment-preview"const log = createLogger({ service: "community-attachments-download" })@@ -68,6 +70,33 @@ export const GET = withPrivateMediaCache(withCommunityActor(async (req: NextRequ}const row = authz.row+ if (ctx.actor.kind === "human" && req.nextUrl.searchParams.get("preview") === "html") {+ if (!isHtmlPreviewFile(row.filename, row.contentType)) {+ return NextResponse.json({ error: "HTML preview unavailable" }, { status: 415 })+ }+ if (row.size !== null && row.size > MAX_HTML_PREVIEW_BYTES) {+ return NextResponse.json({ error: "HTML exceeds the preview limit" }, { status: 422 })+ }+ const object = await ctx.env.COMMUNITY_MEDIA.get(row.r2Key)+ if (!object) return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })+ try {+ const html = prepareHtmlPreview(await readHtmlPreview(object.body, req.signal))+ return new Response(html, { headers: {+ "Content-Type": "text/html; charset=utf-8",+ "Content-Disposition": contentDisposition("inline", row.filename),+ "Content-Security-Policy": HTML_PREVIEW_CSP,+ "Cache-Control": "private, no-store",+ "X-Content-Type-Options": "nosniff",+ "Referrer-Policy": "no-referrer",+ } })+ } catch (error) {+ if (error instanceof HtmlPreviewValidationError) {+ return NextResponse.json({ error: error.message }, { status: 422 })+ }+ throw error+ }+ }+const storedPresentation = resolveAttachmentPresentation(row.filename, row.contentType)const isStoredMedia = storedPresentation.category === "audio" || storedPresentation.category === "video"const requestedRange = ctx.actor.kind === "human" && isStoredMediadiff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex c74008a7c..01abb74a8 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -2431,6 +2431,7 @@ html.dark .blog-content [data-rehype-pretty-code-figure] span {/* ── Streamdown block actions: unified styling (matches MessageActionsToolbar) ── */[data-streamdown="code-block-actions"],[data-streamdown="mermaid-block-actions"],+[data-html-preview-actions],[data-streamdown="table-wrapper"]>div:first-child:not(:has([data-streamdown="table"])) {opacity: 0;pointer-events: none;@@ -2446,6 +2447,7 @@ html.dark .blog-content [data-rehype-pretty-code-figure] span {[data-streamdown="code-block-actions"] button,[data-streamdown="mermaid-block-actions"] button,+[data-html-preview-actions] button,[data-streamdown="table-wrapper"]>div:first-child:not(:has([data-streamdown="table"])) button {width: 1.5rem !important;height: 1.5rem !important;@@ -2460,17 +2462,36 @@ html.dark .blog-content [data-rehype-pretty-code-figure] span {[data-streamdown="code-block-actions"] button:hover,[data-streamdown="mermaid-block-actions"] button:hover,+[data-html-preview-actions] button:hover,[data-streamdown="table-wrapper"]>div:first-child:not(:has([data-streamdown="table"])) button:hover {color: #ffffff !important;}[data-streamdown="code-block-actions"] button svg,[data-streamdown="mermaid-block-actions"] button svg,+[data-html-preview-actions] button svg,[data-streamdown="table-wrapper"]>div:first-child:not(:has([data-streamdown="table"])) button svg {width: 0.875rem !important;height: 0.875rem !important;}+[data-html-preview]:is(:hover, :focus-within) [data-html-preview-actions] {+ opacity: 1;+ pointer-events: auto;+}++@media (hover: none), (pointer: coarse) {+ [data-html-preview-actions] {+ opacity: 1;+ pointer-events: auto;+ }++ [data-html-preview-actions] button {+ width: 2.75rem !important;+ height: 2.75rem !important;+ }+}+/* ── Streamdown block actions: dropdown popups ── */[data-streamdown="code-block-actions"] .absolute,[data-streamdown="mermaid-block-actions"] .absolute,diff --git a/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx b/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsxnew file mode 100644index 000000000..8406898c9--- /dev/null+++ b/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx@@ -0,0 +1,225 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import { act, fireEvent } from "@/test/react-dom-harness"+import { renderCommunity as render } from "@/test/community-owner-harness"+import { ApplicationOwnerProvider, createApplicationOwner, retireApplicationOwner } from "@/lib/application-owner"+import { Message } from "./message"+import { ThreadOpener } from "./thread-opener"+import { HtmlAttachmentPreview } from "./html-attachment-preview"+import { MessageBodyView } from "./message-body-view"+import { tid } from "@/lib/community/testids"+import { NATIVE_MOBILE_BACK_EVENT, useNativeMobileBack } from "@/hooks/community/use-native-mobile-back"++const opener = vi.hoisted(() => ({ message: {} }))+vi.mock("@/hooks/community/use-message", () => ({ useMessage: () => ({ message: opener.message, isLoading: false, isError: false }) }))+const theme = vi.hoisted(() => ({ resolvedTheme: "light" }))+vi.mock("next-themes", () => ({ useTheme: () => theme }))+const file = { id: "a1", name: "demo.html", contentType: "text/html", kind: "file" as const, url: "/api/community/channels/c1/attachments/a1", size: "100 B" }+const owners: ReturnType<typeof createApplicationOwner>[] = []+function setup(body = <HtmlAttachmentPreview attachment={file} />) {+ const owner = createApplicationOwner("viewer")+ owners.push(owner)+ const tree = (node = body) => <ApplicationOwnerProvider owner={owner}>{node}</ApplicationOwnerProvider>+ const view = render(tree())+ return { ...view, owner, tree }+}+function frameMessage(frame: HTMLIFrameElement, data: unknown, over: MessageEventInit = {}) {+ fireEvent(window, new MessageEvent("message", { data, source: frame.contentWindow, origin: "null", ...over }))+}+function BackListener({ replacePath }: { replacePath: (path: string) => void }) {+ useNativeMobileBack({ dismissShellOverlay: () => false, parentPath: "/c/me", replacePath })+ return null+}+afterEach(() => { for (const owner of owners.splice(0)) owner.queryClient.clear(); vi.restoreAllMocks(); vi.unstubAllGlobals(); theme.resolvedTheme = "light"; vi.useRealTimers() })++describe("HTML attachment frame", () => {+ it("keeps the filename out of content and groups floating preview actions", () => {+ const view = setup()+ const actions = view.getByRole("group", { name: "HTML preview actions" })+ expect(view.queryByText(file.name)).toBeNull()+ expect(actions).toContainElement(view.getByTestId(tid.htmlPreviewDownload("a1")))+ expect(actions).toContainElement(view.getByTestId(tid.htmlPreviewExpand("a1")))+ expect(view.getByTestId(tid.htmlPreview("a1"))).toHaveAccessibleName(file.name)+ })+ it("keeps one opaque-origin frame and clamps valid current-frame measurements", () => {+ const view = setup()+ const frame = view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElement+ expect(frame).toHaveAttribute("src", `${file.url}?preview=html`)+ expect(frame.getAttribute("sandbox")).toContain("allow-scripts")+ expect(frame.getAttribute("sandbox")).not.toContain("allow-same-origin")+ expect(frame).toHaveAttribute("referrerpolicy", "no-referrer")+ frameMessage(frame, { type: "alook-html-height", height: 123 }, { source: window })+ frameMessage(frame, { type: "alook-html-height", height: 123 }, { origin: "https://elsewhere.test" })+ for (const height of [NaN, Infinity, -2, "123"]) frameMessage(frame, { type: "alook-html-height", height })+ expect(frame.style.height).toBe("320px")+ frameMessage(frame, { type: "alook-html-height", height: 123.4 })+ expect(frame.style.height).toBe("124px")+ frameMessage(frame, { type: "alook-html-height", height: 999999 })+ expect(frame.style.height).toBe("2000px")+ frameMessage(frame, { type: "alook-html-height", height: 1 })+ expect(frame.style.height).toBe("80px")+ frameMessage(frame, { type: "alook-html-ready" })+ expect(view.getByTestId(tid.htmlPreview("a1"))).toHaveAttribute("data-html-preview-status", "ready")+ })+ it("posts updated Alook theme without replacing the document", () => {+ const view = setup(), frame = view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElement+ const post = vi.spyOn(frame.contentWindow!, "postMessage")+ document.documentElement.style.setProperty("--background", "#fefdfb")+ frameMessage(frame, { type: "alook-html-ready" })+ expect(post).toHaveBeenLastCalledWith(expect.objectContaining({ type: "alook-html-theme", dark: false, variables: expect.objectContaining({ "--background": "#fefdfb" }) }), "*")+ theme.resolvedTheme = "dark"+ view.rerender(view.tree(<HtmlAttachmentPreview attachment={file} />))+ expect(view.getByTestId(tid.htmlPreviewFrame("a1"))).toBe(frame)+ expect(post).toHaveBeenLastCalledWith(expect.objectContaining({ dark: true }), "*")+ document.documentElement.style.removeProperty("--background")+ })+ it("expands and returns the same frame, with Escape and focus recovery", () => {+ const view = setup(), frame = view.getByTestId(tid.htmlPreviewFrame("a1"))+ const dialog = view.getByTestId(tid.htmlPreview("a1")) as HTMLDialogElement+ Object.assign(dialog, {+ getBoundingClientRect() { return { height: 420 } },+ close() { dialog.open = false },+ show() { dialog.open = true },+ showModal() { dialog.open = true },+ })+ fireEvent.click(view.getByTestId(tid.htmlPreviewExpand("a1")))+ expect(view.getByRole("dialog")).toHaveAttribute("aria-modal", "true")+ expect(dialog.parentElement!.style.height).toBe("420px")+ expect(view.getByTestId(tid.htmlPreviewFrame("a1"))).toBe(frame)+ fireEvent(view.getByRole("dialog"), new Event("cancel", { cancelable: true }))+ expect(view.queryByRole("dialog")).toBeNull()+ expect(dialog.parentElement!.style.height).toBe("")+ expect(view.getByTestId(tid.htmlPreviewFrame("a1"))).toBe(frame)+ expect(view.getByTestId(tid.htmlPreviewExpand("a1"))).toHaveFocus()+ })+ it("returns native Back from fullscreen to the same inline document before page navigation", () => {+ const originalUrl = window.location.href+ const replacePath = vi.fn((path: string) => window.history.replaceState(null, "", path))+ window.history.replaceState(null, "", "/c/channels/server/channel")+ try {+ const view = setup(<><BackListener replacePath={replacePath} /><textarea aria-label="Host draft" defaultValue="saved draft" /><HtmlAttachmentPreview attachment={file} /></>)+ const frame = view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElement+ const frameDocument = frame.contentDocument!+ const html = frameDocument.createElement("html")+ const body = frameDocument.createElement("body")+ const input = frameDocument.createElement("input")+ input.id = "preview-state"+ input.value = "kept value"+ body.appendChild(input)+ html.appendChild(body)+ frameDocument.replaceChildren(html)+ const dialog = view.getByTestId(tid.htmlPreview("a1")) as HTMLDialogElement+ Object.assign(dialog, {+ close() { dialog.open = false },+ show() { dialog.open = true },+ showModal() { dialog.open = true },+ })+ fireEvent.click(view.getByTestId(tid.htmlPreviewExpand("a1")))+ const url = window.location.href+ const src = frame.src+ const event = new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })+ act(() => { window.dispatchEvent(event) })+ expect(event.defaultPrevented).toBe(true)+ expect(view.getByTestId(tid.htmlPreview("a1"))).not.toHaveAttribute("aria-modal", "true")+ expect(replacePath).not.toHaveBeenCalled()+ expect(window.location.href).toBe(url)+ expect(view.getByTestId(tid.htmlPreviewFrame("a1"))).toBe(frame)+ expect(frame.src).toBe(src)+ expect(frame.contentDocument).toBe(frameDocument)+ expect(frameDocument.getElementById("preview-state")).toBe(input)+ expect(input.value).toBe("kept value")+ expect(view.getByRole("textbox", { name: "Host draft" })).toHaveValue("saved draft")+ expect(view.getByTestId(tid.htmlPreviewExpand("a1"))).toHaveFocus()+ act(() => { window.dispatchEvent(new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })) })+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")+ } finally { window.history.replaceState(null, "", originalUrl) }+ })+ it("waits until near the viewport and cleans up on owner retirement", () => {+ let intersect: IntersectionObserverCallback | undefined+ const disconnect = vi.fn()+ vi.stubGlobal("IntersectionObserver", class { constructor(callback: IntersectionObserverCallback) { intersect = callback } observe() {} disconnect = disconnect })+ const view = setup()+ expect(view.queryByTestId(tid.htmlPreviewFrame("a1"))).toBeNull()+ act(() => intersect!([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver))+ const frame = view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElement+ act(() => retireApplicationOwner(view.owner))+ expect(view.queryByTestId(tid.htmlPreview("a1"))).toBeNull()+ frameMessage(frame, { type: "alook-html-ready" })+ expect(view.queryByTestId(tid.htmlPreview("a1"))).toBeNull()+ expect(disconnect).toHaveBeenCalled()+ })+ it("rejects a late message from a replaced attachment frame", () => {+ const view = setup()+ const previous = (view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElement).contentWindow+ view.rerender(view.tree(<HtmlAttachmentPreview attachment={{ ...file, id: "a2", url: "/api/community/channels/c1/attachments/a2" }} />))+ const current = view.getByTestId(tid.htmlPreviewFrame("a2")) as HTMLIFrameElement+ fireEvent(window, new MessageEvent("message", { origin: "null", source: previous, data: { type: "alook-html-ready" } }))+ fireEvent(window, new MessageEvent("message", { origin: "null", source: previous, data: { type: "alook-html-height", height: 999 } }))+ expect(current.style.height).toBe("320px")+ expect(view.getByTestId(tid.htmlPreview("a2"))).toHaveAttribute("data-html-preview-status", "loading")+ frameMessage(current, { type: "alook-html-ready" })+ expect(view.getByTestId(tid.htmlPreview("a2"))).toHaveAttribute("data-html-preview-status", "ready")+ })+ it("turns missing readiness into a single failure block", () => {+ vi.useFakeTimers()+ const view = setup()+ act(() => vi.advanceTimersByTime(15_000))+ expect(view.queryByTestId(tid.htmlPreviewFrame("a1"))).toBeNull()+ expect(view.getByRole("status")).toHaveTextContent("Preview unavailable")+ expect(view.getAllByTestId(tid.htmlPreview("a1"))).toHaveLength(1)+ expect(view.getByTestId(tid.htmlPreviewDownload("a1"))).toBeEnabled()+ expect(view.getByTestId(tid.htmlPreviewExpand("a1"))).toBeDisabled()+ })+})++describe("HTML marker rendering", () => {+ it("splits inline text around a single block and consumes repeated markers", () => {+ const view = setup(<MessageBodyView plugins={{}} text="before [alook-html-preview](a1) after\n\n[alook-html-preview](a1)" attachments={[file]} />)+ expect(view.getAllByTestId(tid.htmlPreview("a1"))).toHaveLength(1)+ expect(view.container.textContent).toContain("before")+ expect(view.container.textContent).toContain("after")+ const body = view.container.querySelector(".message-markdown-blocks")!+ expect([...body.children].map((node) => node.tagName)).toEqual(["P", "DIV", "P"])+ expect(view.container.querySelector("p dialog")).toBeNull()+ })+ it("does not execute typed HTML tags or let them duplicate a valid marker", () => {+ const literal = '<htmlpreview data-attachment-id="a1"></htmlpreview>'+ const body = (text: string) => <MessageBodyView plugins={{}} text={text} attachments={[file]} />+ const view = setup(body(literal))+ expect(view.container.querySelector("iframe")).toBeNull()+ view.rerender(view.tree(body("[alook-html-preview](a1)\n\n" + literal)))+ expect(view.getAllByTestId(tid.htmlPreview("a1"))).toHaveLength(1)+ })+ it("retains the current document when canonical attachments are republished", () => {+ const text = "[alook-html-preview](a1)"+ const body = () => <MessageBodyView plugins={{}} text={text} attachments={[{ ...file }]} />+ const view = setup(body())+ const frame = view.getByTestId(tid.htmlPreviewFrame("a1"))+ view.rerender(view.tree(body()))+ expect(view.getByTestId(tid.htmlPreviewFrame("a1"))).toBe(frame)+ })+ it("leaves an unassociated or escaped ID inert", () => {+ const view = setup(<MessageBodyView plugins={{}} text="[alook-html-preview](foreign)\n\n\\[alook-html-preview](a1)" attachments={[file]} />)+ expect(view.container.querySelector("iframe")).toBeNull()+ })+})+++describe("HTML preview full message compositions", () => {+ it.each(["row", "opener"])("deduplicates preview and attachment cards in the actual %s", (surface) => {+ const message = {+ id: "m1", type: "chat" as const, authorId: "viewer", authorName: "Viewer", createdAt: "2026-10-28T08:00:00Z", grouped: false,+ content: "before [alook-html-preview](a1) after\n\n[alook-html-preview](a1)",+ attachments: [file, { ...file, id: "ordinary", name: "ordinary.txt", contentType: "text/plain" }],+ }+ opener.message = message+ const body = surface === "row"+ ? <Message m={message} onOpenThread={() => undefined} viewerUserId="viewer" />+ : <ThreadOpener parentMessageId="m1" parentChannelId="c1" serverId="s1" viewerUserId="viewer" />+ const view = setup(body)+ expect(view.getAllByTestId(tid.htmlPreview("a1"))).toHaveLength(1)+ expect(view.queryByTestId(tid.attachmentCard("demo.html"))).toBeNull()+ expect(view.getAllByTestId(tid.attachmentCard("ordinary.txt"))).toHaveLength(1)+ expect(view.container.textContent).toContain("before")+ expect(view.container.textContent).toContain("after")+ })+})diff --git a/src/web/src/components/community/messages/html-attachment-preview.theme.dom.test.tsx b/src/web/src/components/community/messages/html-attachment-preview.theme.dom.test.tsxnew file mode 100644index 000000000..a98de3e0f--- /dev/null+++ b/src/web/src/components/community/messages/html-attachment-preview.theme.dom.test.tsx@@ -0,0 +1,56 @@+import { afterEach, expect, it, vi } from "vitest"+import { ThemeProvider, useTheme } from "next-themes"+import { act, fireEvent, waitFor } from "@/test/react-dom-harness"+import { renderCommunity as render } from "@/test/community-owner-harness"+import { ApplicationOwnerProvider, createApplicationOwner } from "@/lib/application-owner"+import { tid } from "@/lib/community/testids"+import { HtmlAttachmentPreview } from "./html-attachment-preview"++const storageKey = "html-preview-theme-regression"+const owners: ReturnType<typeof createApplicationOwner>[] = []+afterEach(() => {+ for (const owner of owners.splice(0)) owner.queryClient.clear()+ localStorage.removeItem(storageKey)+ vi.restoreAllMocks()+})++function ThemeControls() {+ const { setTheme } = useTheme()+ return <><button onClick={() => setTheme("light")}>Light</button><button onClick={() => setTheme("dark")}>Dark</button></>+}++it("syncs the loaded iframe scheme and committed CSS tokens through the real theme provider in both directions", async () => {+ const root = document.documentElement+ const originalClass = root.getAttribute("class"), originalStyle = root.getAttribute("style")+ const sheet = document.createElement("style")+ sheet.textContent = ":root{--background:#ffffff;--foreground:#102030;--card:#f1f2f3;--secondary:#e1e2e3;--primary:#112233}:root.dark{--background:#121314;--foreground:#e1e2e3;--card:#222324;--secondary:#323334;--primary:#f1f2f3}"+ document.head.appendChild(sheet)+ localStorage.setItem(storageKey, "light")+ const owner = createApplicationOwner("theme-viewer")+ owners.push(owner)+ try {+ const view = render(<ApplicationOwnerProvider owner={owner}><ThemeProvider attribute="class" defaultTheme="light" enableSystem={false} storageKey={storageKey}><ThemeControls /><HtmlAttachmentPreview attachment={{ id: "theme-html", kind: "file", name: "theme.html", url: "/api/community/channels/c1/attachments/theme-html", contentType: "text/html", size: "100 B" }} /></ThemeProvider></ApplicationOwnerProvider>)+ const frame = view.getByTestId(tid.htmlPreviewFrame("theme-html")) as HTMLIFrameElement+ expect(frame.style.colorScheme).toBe("")+ expect(frame).toHaveClass("scheme-light")+ fireEvent.load(frame)+ await waitFor(() => expect(frame.style.colorScheme).toBe("light"))+ const post = vi.spyOn(frame.contentWindow!, "postMessage")+ act(() => { window.dispatchEvent(new MessageEvent("message", { data: { type: "alook-html-ready" }, source: frame.contentWindow, origin: "null" })) })+ for (const mode of ["dark", "light"] as const) {+ fireEvent.click(view.getByRole("button", { name: mode === "dark" ? "Dark" : "Light" }))+ await waitFor(() => expect(root).toHaveClass(mode))+ await waitFor(() => expect(frame.style.colorScheme).toBe(mode))+ await waitFor(() => {+ const style = getComputedStyle(root)+ const variables = Object.fromEntries(["background", "foreground", "card", "secondary", "primary"].map((name) => [`--${name}`, style.getPropertyValue(`--${name}`).trim()]))+ expect(post).toHaveBeenLastCalledWith(expect.objectContaining({ type: "alook-html-theme", dark: mode === "dark", variables: expect.objectContaining(variables) }), "*")+ })+ expect(view.getByTestId(tid.htmlPreviewFrame("theme-html"))).toBe(frame)+ }+ } finally {+ sheet.remove()+ if (originalClass === null) root.removeAttribute("class"); else root.setAttribute("class", originalClass)+ if (originalStyle === null) root.removeAttribute("style"); else root.setAttribute("style", originalStyle)+ }+})diff --git a/src/web/src/components/community/messages/html-attachment-preview.tsx b/src/web/src/components/community/messages/html-attachment-preview.tsxnew file mode 100644index 000000000..ba3ea032d--- /dev/null+++ b/src/web/src/components/community/messages/html-attachment-preview.tsx@@ -0,0 +1,182 @@+"use client"++import { useQuery } from "@tanstack/react-query"+import { useSelector } from "@tanstack/react-store"+import { useEffect, useMemo, useRef, useState } from "react"+import { Download, Expand, LoaderCircle, X } from "lucide-react"+import { useTheme } from "next-themes"+import { collectHtmlPreviewFonts, loadHtmlPreviewFonts } from "@/lib/community/html-preview-fonts"+import { applicationKey, assertApplicationOwner, captureApplicationOwner, useApplicationOwner } from "@/lib/application-owner"+import { HTML_PREVIEW_SANDBOX, HTML_PREVIEW_THEME_VARIABLES } from "@/lib/community/html-preview-policy"+import type { FileAttachment } from "@/lib/community/models/message"+import { useAttachmentDownload, attachmentDownloadStatusText } from "@/lib/community/attachment-download"+import { tid } from "@/lib/community/testids"+import { buttonVariants } from "@/components/ui/button"+import { useNativeBackOwner } from "@/components/ui/native-back-layer"+import { cn } from "@/lib/utils"++export function HtmlAttachmentPreview({ attachment }: { attachment: FileAttachment & { id: string } }) {+ const owner = useApplicationOwner()+ const lifecycle = useSelector(owner.lifecycle)+ return lifecycle.active ? <HtmlPreviewDocument key={`${owner.userId}:${lifecycle.generation}:${attachment.id}:${attachment.url}`} attachment={attachment} /> : null+}++function HtmlPreviewDocument({ attachment }: { attachment: FileAttachment & { id: string } }) {+ const owner = useApplicationOwner()+ const { resolvedTheme } = useTheme()+ const fonts = useMemo(() => typeof document === "undefined" ? [] : collectHtmlPreviewFonts(document,+ getComputedStyle(document.documentElement).getPropertyValue("--font-dm-sans") + "," + getComputedStyle(document.documentElement).getPropertyValue("--font-dm-mono")), [])+ const [mounted, setMounted] = useState(false)+ const [loaded, setLoaded] = useState(false)+ const [status, setStatus] = useState<"loading" | "ready" | "error">("loading")+ const [height, setHeight] = useState(320)+ const [expanded, setExpanded] = useState(false)+ const [inlineHeight, setInlineHeight] = useState(0)+ const fontSheet = useQuery({+ queryKey: applicationKey(owner, "html-preview-fonts", fonts), enabled: mounted && fonts.length > 0,+ staleTime: Infinity, retry: false,+ queryFn: async ({ signal }) => {+ const token = captureApplicationOwner(owner)+ assertApplicationOwner(token, signal)+ const css = await loadHtmlPreviewFonts(fonts, signal)+ assertApplicationOwner(token, signal)+ return css+ },+ }, owner.queryClient).data+ const root = useRef<HTMLDialogElement>(null)+ const frame = useRef<HTMLIFrameElement>(null)+ const ready = useRef(false)+ const expandButton = useRef<HTMLButtonElement>(null)+ const download = useAttachmentDownload(attachment)+ const id = attachment.id+ const url = `${attachment.url}?preview=html`+ const error = status === "error"++ useEffect(() => {+ const element = root.current+ if (!element) return+ if (!window.IntersectionObserver) { setMounted(true); return }+ const observer = new IntersectionObserver((entries) => {+ if (entries.some((entry) => entry.isIntersecting)) { setMounted(true); observer.disconnect() }+ }, { rootMargin: "200px" })+ observer.observe(element)+ return () => observer.disconnect()+ }, [])++ useEffect(() => {+ if (!mounted || error) return+ function theme() {+ const style = getComputedStyle(document.documentElement)+ const variables = Object.fromEntries(HTML_PREVIEW_THEME_VARIABLES.map((key) => [`--${key}`, style.getPropertyValue(`--${key}`).trim()]))+ variables["--font-sans"] = style.getPropertyValue("--font-dm-sans").trim() || style.fontFamily+ variables["--font-mono"] = style.getPropertyValue("--font-dm-mono").trim() || "ui-monospace, monospace"+ frame.current?.contentWindow?.postMessage({ type: "alook-html-theme", dark: resolvedTheme === "dark", variables, fontSheet }, "*")+ }+ const timeout = setTimeout(() => { if (!ready.current) setStatus("error") }, 15_000)+ function message(event: MessageEvent<unknown>) {+ if (!frame.current?.contentWindow || event.source !== frame.current.contentWindow || event.origin !== "null"+ || typeof event.data !== "object" || event.data === null || !("type" in event.data)) return+ if (event.data.type === "alook-html-theme-request") theme()+ if (event.data.type === "alook-html-ready") {+ clearTimeout(timeout)+ ready.current = true+ setStatus("ready")+ theme()+ }+ if (event.data.type === "alook-html-height" && "height" in event.data+ && typeof event.data.height === "number" && Number.isFinite(event.data.height) && event.data.height > 0) {+ setHeight(Math.max(80, Math.min(2000, Math.ceil(event.data.height))))+ }+ }+ window.addEventListener("message", message)+ theme()+ const themeFrame = requestAnimationFrame(theme)+ return () => { clearTimeout(timeout); cancelAnimationFrame(themeFrame); window.removeEventListener("message", message) }+ }, [mounted, error, resolvedTheme, fontSheet])++ function close() {+ const dialog = root.current+ if (!dialog) return+ dialog.close()+ dialog.show()+ setExpanded(false)+ expandButton.current?.focus()+ }++ useNativeBackOwner(() => expanded ? root.current : null, () => {+ close()+ return "requested"+ })++ function expand() {+ const dialog = root.current+ if (!dialog) return+ setInlineHeight(dialog.getBoundingClientRect().height)+ dialog.close()+ dialog.showModal()+ setExpanded(true)+ }++ return (+ <div className="min-w-0" style={expanded ? { height: inlineHeight } : undefined}>+ <dialog+ ref={root}+ open+ role={expanded ? "dialog" : "group"}+ aria-modal={expanded || undefined}+ aria-label={attachment.name}+ data-html-preview+ data-testid={tid.htmlPreview(id)}+ data-html-preview-status={status}+ onCancel={(event) => { event.preventDefault(); close() }}+ className="relative m-0 block w-full min-w-0 max-w-full overflow-hidden rounded-none border-0 bg-transparent p-0 text-foreground backdrop:bg-background/80 [&:modal]:fixed [&:modal]:inset-0 [&:modal]:m-auto [&:modal]:flex [&:modal]:h-[calc(100dvh-2rem)] [&:modal]:max-h-none [&:modal]:w-[calc(100vw-2rem)] [&:modal]:max-w-none [&:modal]:flex-col [&:modal]:bg-background"+ >+ <div role="group" aria-label="HTML preview actions" data-html-preview-actions className="absolute top-1.5 right-1.5 z-10 flex items-center">+ <button+ type="button"+ data-testid={tid.htmlPreviewDownload(id)}+ className={buttonVariants({ variant: "ghost", size: "icon" })}+ onClick={() => download.state.status === "downloading" ? download.cancel() : void download.start()}+ aria-label={download.state.status === "downloading" ? "Cancel download" : `Download ${attachment.name}`}+ aria-busy={download.state.status === "downloading"}+ title={attachmentDownloadStatusText(download.state) ?? `Download ${attachment.name}`}+ >+ {download.state.status === "downloading" ? <LoaderCircle className="size-4 motion-safe:animate-spin" /> : <Download className="size-4" />}+ <span className="sr-only" aria-live="polite">{attachmentDownloadStatusText(download.state)}</span>+ </button>+ <button+ ref={expandButton}+ type="button"+ className={buttonVariants({ variant: "ghost", size: "icon" })}+ data-testid={expanded ? tid.htmlPreviewClose(id) : tid.htmlPreviewExpand(id)}+ aria-label={expanded ? "Close fullscreen preview" : "Expand HTML preview"}+ title={expanded ? "Close fullscreen preview" : "Expand HTML preview"}+ onClick={expanded ? close : expand}+ disabled={error && !expanded}+ >+ {expanded ? <X className="size-4" /> : <Expand className="size-4" />}+ </button>+ </div>+ {error ? (+ <div role="status" className="p-4 text-sm text-muted-foreground">Preview unavailable. You can download this file.</div>+ ) : (+ <>+ {status === "loading" && <div role="status" className="px-2 py-1 text-sm text-muted-foreground">Loading preview…</div>}+ {mounted && <iframe+ ref={frame}+ title={attachment.name}+ data-testid={tid.htmlPreviewFrame(id)}+ src={url}+ sandbox={HTML_PREVIEW_SANDBOX}+ referrerPolicy="no-referrer"+ allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'"+ onLoad={() => setLoaded(true)}+ className={cn("block w-full border-0 bg-transparent scheme-light", expanded && "min-h-0 flex-1")}+ style={{ height: expanded ? undefined : height, colorScheme: loaded ? resolvedTheme === "dark" ? "dark" : "light" : undefined }}+ />}+ </>+ )}+ </dialog>+ </div>+ )+}diff --git a/src/web/src/components/community/messages/message-body-view.tsx b/src/web/src/components/community/messages/message-body-view.tsxindex 1d9f22706..7bb654823 100644--- a/src/web/src/components/community/messages/message-body-view.tsx+++ b/src/web/src/components/community/messages/message-body-view.tsx@@ -1,4 +1,7 @@-import { useMemo, type ComponentProps } from "react"+import { createContext, useContext, useMemo, type ComponentProps } from "react"+import { HtmlAttachmentPreview } from "./html-attachment-preview"+import type { Attachment, FileAttachment } from "@/lib/community/models/message"+import { htmlPreviewPlugin, selectHtmlPreviews } from "@/lib/community/html-preview-markdown"import { Streamdown } from "streamdown"import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from "rehype-sanitize"import { harden } from "rehype-harden"@@ -16,6 +19,15 @@ import { CommunityInviteCard } from "../social/community-invite-card"import type { MessagePerspective } from "@/components/community/messages/message-presentation-types"import type { OpenProfile } from "@/components/community/social/profile-types"+const HtmlPreviewAttachments = createContext<ReadonlyMap<string, FileAttachment>>(new Map())++function HtmlPreviewMarkdown(props: Record<string, unknown>) {+ const selected = useContext(HtmlPreviewAttachments)+ const id = props["data-attachment-id"]+ const attachment = typeof id === "string" ? selected.get(id) : undefined+ return attachment && typeof id === "string" ? <HtmlAttachmentPreview attachment={{ ...attachment, id }} /> : null+}+// The sanitize schema Streamdown builds internally when `allowedTags` is// left at its default merge path (verified against Streamdown 2.5.0's// compiled source): `defaultSchema` + `protocols.href` gains `"tel"` +@@ -94,50 +106,58 @@ const REHYPE_PLUGINS: PluggableList = [// the raw link even when the card is present.export function MessageBodyView({text,+ attachments,plugins,onOpenProfile,perspective = "neutral",}: {text: string+ attachments?: readonly Attachment[]plugins: ComponentProps<typeof Streamdown>["plugins"]onOpenProfile?: OpenProfileperspective?: MessagePerspective}) {const inviteTokens = useMemo(() => extractInviteTokens(text), [text])- const components = useMemo(- () => buildMdComponents(onOpenProfile),- [onOpenProfile],- )+ const selected = useMemo(() => selectHtmlPreviews(text, attachments), [text, attachments])+ const remarkPlugins = useMemo<PluggableList>(() => selected.size+ ? [...CHAT_REMARK_PLUGINS, [htmlPreviewPlugin, { text, attachments }]]+ : CHAT_REMARK_PLUGINS, [text, attachments, selected])+ const components = useMemo(() => ({+ ...buildMdComponents(onOpenProfile),+ htmlpreview: HtmlPreviewMarkdown,+ }), [onOpenProfile])return (<divdata-community-message-bodyclassName="markdown markdown-chat flex flex-col gap-2 wrap-anywhere select-text text-[15px] leading-snug text-foreground">- <Streamdown- className="message-markdown-blocks flex flex-col gap-2 space-y-0"- mode="static"- parseIncompleteMarkdown={false}- plugins={plugins}- remarkPlugins={CHAT_REMARK_PLUGINS}- remarkRehypeOptions={{ handlers: chatSyntaxHandlers }}- rehypePlugins={REHYPE_PLUGINS}- // Deliberately skips the AI-content confirm-before-navigating modal- // — that feature exists for LLM-generated content where a model- // could be prompt-injected into emitting a malicious-looking link;- // community chat links are typed by the human sender, so a plain- // hyperlink click is the expected behavior. Protocol/XSS filtering- // is unconditional via `rehype-harden` above, unaffected by this- // flag either way.- linkSafety={{ enabled: false }}- controls={{- code: { copy: true, download: false },- table: { copy: true, download: false, fullscreen: true },- }}- literalTagContent={MD_LITERAL_TAGS}- components={components}- >- {text}- </Streamdown>+ <HtmlPreviewAttachments.Provider value={selected}>+ <Streamdown+ className="message-markdown-blocks flex flex-col gap-2 space-y-0"+ mode="static"+ parseIncompleteMarkdown={false}+ plugins={plugins}+ remarkPlugins={remarkPlugins}+ remarkRehypeOptions={{ handlers: chatSyntaxHandlers }}+ rehypePlugins={REHYPE_PLUGINS}+ // Deliberately skips the AI-content confirm-before-navigating modal+ // — that feature exists for LLM-generated content where a model+ // could be prompt-injected into emitting a malicious-looking link;+ // community chat links are typed by the human sender, so a plain+ // hyperlink click is the expected behavior. Protocol/XSS filtering+ // is unconditional via `rehype-harden` above, unaffected by this+ // flag either way.+ linkSafety={{ enabled: false }}+ controls={{+ code: { copy: true, download: false },+ table: { copy: true, download: false, fullscreen: true },+ }}+ literalTagContent={MD_LITERAL_TAGS}+ components={components}+ >+ {text}+ </Streamdown>+ </HtmlPreviewAttachments.Provider>{inviteTokens.length > 0 && (<div className="flex flex-col gap-2">{inviteTokens.map((token) => (diff --git a/src/web/src/components/community/messages/message-body.tsx b/src/web/src/components/community/messages/message-body.tsxindex 583dd670f..a0654f91a 100644--- a/src/web/src/components/community/messages/message-body.tsx+++ b/src/web/src/components/community/messages/message-body.tsx@@ -7,7 +7,10 @@ import type { OpenProfile } from "../social/profile-types"import type { MessagePerspective } from "./message-presentation-types"import { MessageBodyView } from "./message-body-view"+import type { Attachment } from "@/lib/community/models/message"+type MessageBodyProps = {+ attachments?: readonly Attachment[]text: stringonOpenProfile?: OpenProfileperspective?: MessagePerspectivediff --git a/src/web/src/components/community/messages/message-markdown.tsx b/src/web/src/components/community/messages/message-markdown.tsxindex 3467e3d7e..68886b630 100644--- a/src/web/src/components/community/messages/message-markdown.tsx+++ b/src/web/src/components/community/messages/message-markdown.tsx@@ -43,6 +43,7 @@ export function extractInviteTokens(text: string): string[] {// mention pill would lose its discriminator (same-name pills all resolve to// the first match) and @everyone loses its styling flag.export const MD_ALLOWED_TAGS = {+ htmlpreview: ["dataAttachmentId"],redacted: [],redactedcode: ["dataRedactedBlock", "dataLanguage"],spoiler: [],diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsxindex 1658e8ba0..227d5a52f 100644--- a/src/web/src/components/community/messages/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -12,6 +12,7 @@ import { ContextMenu, ContextMenuTrigger, ContextMenuContent, isSecondaryContextimport { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent } from "@/components/ui/dropdown-menu"import { Avatar } from "../avatar"import { MessageBody } from "./message-body"+import { selectHtmlPreviews } from "@/lib/community/html-preview-markdown"import { MessageAuthorLine } from "./message-author-line"import {copyMessageExternalLink,@@ -238,6 +239,7 @@ function MessageImpl({? (replyAuthorProfile?.name ?? "Deleted user"): (m.replyTo?.authorName ?? "Deleted user")const visibleContent = m.content ?? ""+ const htmlPreviews = selectHtmlPreviews(m.approval || m.botCreation ? "" : visibleContent, m.attachments)// keep the hover toolbar pinned open while its ⋯ dropdown is openconst pageSwipe = usePageSwipeStart()const [toolbarOpen, setToolbarOpen] = useAtom(useCreateAtom(false))@@ -738,6 +740,7 @@ function MessageImpl({<MessageBodykey={m.id}text={visibleContent}+ attachments={m.attachments}onOpenProfile={onOpenProfile}perspective={viewerUserId@@ -751,6 +754,7 @@ function MessageImpl({{m.attachments && m.attachments.length > 0 && (<div className="flex flex-col gap-2">{m.attachments.map((a, i) => {+ if (a.id && htmlPreviews.has(a.id)) return nullif (a.kind === "image") {const frameStyle = attachmentImageFrameStyle(a.width, a.height)return (diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsxindex c715a23ba..cc8f4ada3 100644--- a/src/web/src/components/community/messages/thread-opener.tsx+++ b/src/web/src/components/community/messages/thread-opener.tsx@@ -3,6 +3,7 @@import { MessagesSquare, ArrowUpRight } from "lucide-react"import { Avatar } from "../avatar"import { MessageBody } from "./message-body"+import { selectHtmlPreviews } from "@/lib/community/html-preview-markdown"import { MessageAuthorLine } from "./message-author-line"import { attachmentImageFrameStyle } from "./attachment-layout"import { formatMessageTime } from "@/lib/community/format-time"@@ -105,6 +106,7 @@ export function ThreadOpener({? (authorProfile?.avatar ?? avatarInitial(authorName)): (msg.authorAvatar ?? avatarInitial(authorName))const visibleContent = msg.content ?? ""+ const htmlPreviews = selectHtmlPreviews(visibleContent, msg.attachments)return (<div data-thread-opener className="group relative flex flex-col gap-2">@@ -148,6 +150,7 @@ export function ThreadOpener({<MessageBodykey={msg.id}text={visibleContent}+ attachments={msg.attachments}onOpenProfile={onOpenProfile}perspective={msg.authorId === viewerUserId ? "sender" : "recipient"}/>@@ -156,6 +159,7 @@ export function ThreadOpener({{msg.attachments && msg.attachments.length > 0 && (<div className="flex flex-col gap-2">{msg.attachments.map((a, i) => {+ if (a.id && htmlPreviews.has(a.id)) return nullif (a.kind === "image") {const frameStyle = attachmentImageFrameStyle(a.width, a.height)return (diff --git a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts b/src/web/src/hooks/community/community-ws/message-events.dom.test.tsindex 9ba8a69fb..920e9ddbd 100644--- a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts+++ b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts@@ -1308,7 +1308,7 @@ describe("canonical message refresh ownership", () => {await act(async () => { capturedOnMessage!({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION, message: incomplete }) })expect(getCommunityDbRegistry(capturedQueryClient)!.collections.messages.get(event.message.id)?.attachments).toEqual(attachments)expect(getMessageStreamState(capturedQueryClient, scope).liveIds).not.toContain(event.message.id)- expect(canonicalMessage(event.message.id)?.attachments).toEqual([{ name: "settled.txt", url: "/media/settled", contentType: "text/plain", sizeBytes: 1024, kind: "file", size: "1.0 KB" }])+ expect(canonicalMessage(event.message.id)?.attachments).toEqual([{ id: "settled", name: "settled.txt", url: "/media/settled", contentType: "text/plain", sizeBytes: 1024, kind: "file", size: "1.0 KB" }])})})diff --git a/src/web/src/hooks/community/mutations/messages.dom.test.ts b/src/web/src/hooks/community/mutations/messages.dom.test.tsindex 4585ddc4d..e7933144b 100644--- a/src/web/src/hooks/community/mutations/messages.dom.test.ts+++ b/src/web/src/hooks/community/mutations/messages.dom.test.ts@@ -198,7 +198,7 @@ describe("useSendMessage — happy path", () => {runtime.ui.actions.subscribe({ channelId: scope.id })const replyTo = { id: "reply_1", authorId: "reply-author", authorName: "Reply Author", text: "preview" }const attachment = { id: "file_1", filename: "notes.txt", contentType: "text/plain", size: 1024 }- const remoteAttachment = { kind: "file" as const, name: attachment.filename,+ const remoteAttachment = { id: attachment.id, kind: "file" as const, name: attachment.filename,url: "/api/community/channels/ch_1/attachments/file_1", contentType: attachment.contentType,sizeBytes: attachment.size, size: "1.0 KB" }const wireAttachment = { id: attachment.id, name: remoteAttachment.name, url: remoteAttachment.url, contentType: remoteAttachment.contentType, sizeBytes: remoteAttachment.sizeBytes, thumbnailUrl: null, width: null, height: null }diff --git a/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts b/src/web/src/hooks/community/use-messages.loading-state.dom.test.tsindex 121a6a71b..6e13df0de 100644--- a/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts+++ b/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts@@ -108,7 +108,7 @@ describe("useMessages — instant channel switch", () => {const { client, registry } = await createCommunityQueryOwner()const scope: MessageScope = kind === "channel" ? { kind, id: "ch_new", serverId: "s1" } : { kind, id: "dm_new" }const attachments = [{ id: "attachment", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, thumbnailUrl: null, contentType: "text/plain", width: null, height: null }]- const presentedAttachments = [{ name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, contentType: "text/plain", kind: "file", size: "1.0 KB" }]+ const presentedAttachments = [{ id: "attachment", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, contentType: "text/plain", kind: "file", size: "1.0 KB" }]const embeds = [{ title: "Existing embed" }], replyTo = { id: "reply", authorId: "peer", authorName: "Peer", text: "reply" }const message: CanonicalMessage = { id: "rich", seq: 3, type: "chat", authorId: "peer", authorName: "Peer", content: "before", clientNonce: "rich-nonce", createdAt: "2026-08-07T10:00:00.000Z" }ingestMessages(registry, scope.id, [messageResourceFixture({ ...message, channelId: scope.id, replyToId: "reply", attachments, embeds, replyTo })])diff --git a/src/web/src/lib/community/attachment-presentation.test.ts b/src/web/src/lib/community/attachment-presentation.test.tsindex bb6e38dc2..958f1195b 100644--- a/src/web/src/lib/community/attachment-presentation.test.ts+++ b/src/web/src/lib/community/attachment-presentation.test.ts@@ -181,3 +181,12 @@ describe("formatAttachmentSize", () => {expect(formatAttachmentSize(2 * 1024 * 1024)).toBe("2.0 MB")})})++describe("HTML preview attachment identity", () => {+ it("keeps a canonical attachment ID in the display projection", async () => {+ const { presentMessageAttachment } = await import("./attachment-presentation")+ expect(presentMessageAttachment({ id: "html-id", name: "page.html", url: "/attachment/html-id", contentType: "text/html", sizeBytes: 1024, thumbnailUrl: null, width: null, height: null })).toEqual({+ id: "html-id", kind: "file", name: "page.html", url: "/attachment/html-id", contentType: "text/html", sizeBytes: 1024, size: "1.0 KB",+ })+ })+})diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.tsindex 632b2662e..b3b4cd6ea 100644--- a/src/web/src/lib/community/attachment-presentation.ts+++ b/src/web/src/lib/community/attachment-presentation.ts@@ -284,6 +284,7 @@ export function presentMessageAttachment(): Attachment {const kind = isInlineAttachmentContentType(attachment.contentType) ? "image" : "file"const metadata = {+ ...("id" in attachment ? { id: attachment.id } : {}),name: attachment.name, url: attachment.url,...(attachment.contentType != null ? { contentType: attachment.contentType } : {}),...(attachment.sizeBytes != null ? { sizeBytes: attachment.sizeBytes } : {}),diff --git a/src/web/src/lib/community/html-attachment-preview.test.ts b/src/web/src/lib/community/html-attachment-preview.test.tsnew file mode 100644index 000000000..60e8e362d--- /dev/null+++ b/src/web/src/lib/community/html-attachment-preview.test.ts@@ -0,0 +1,107 @@+import { JSDOM } from "jsdom"+import { describe, expect, it, vi } from "vitest"+import { HTML_PREVIEW_CSP, HtmlPreviewValidationError, prepareHtmlPreview, readHtmlPreview } from "./html-attachment-preview"+import { MAX_HTML_PREVIEW_BYTES } from "./html-preview-policy"++const stream = (text: string) => new Response(text).body!+describe("HTML preview response preparation", () => {+ it("reads UTF-8 split across byte chunks", async () => {+ const bytes = new TextEncoder().encode("<p>你好</p>")+ const body = new ReadableStream({ start(controller) { for (const byte of bytes) controller.enqueue(new Uint8Array([byte])); controller.close() } })+ expect(await readHtmlPreview(body)).toBe("<p>你好</p>")+ })+ it.each(["", " \n", "a\0b"])("rejects empty or binary input", async (text) => {+ await expect(readHtmlPreview(stream(text))).rejects.toBeInstanceOf(HtmlPreviewValidationError)+ })+ it("rejects invalid UTF-8 and overflow based on real bytes", async () => {+ await expect(readHtmlPreview(new Response(new Uint8Array([255])).body!)).rejects.toThrow("UTF-8")+ const cancel = vi.fn()+ const body = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(MAX_HTML_PREVIEW_BYTES + 1)) }, cancel })+ await expect(readHtmlPreview(body)).rejects.toThrow("limit")+ expect(cancel).toHaveBeenCalledOnce()+ })+ it("cancels a pending read when its request aborts", async () => {+ const abort = new AbortController(), cancel = vi.fn()+ const result = readHtmlPreview(new ReadableStream({ cancel }), abort.signal)+ abort.abort()+ await expect(result).rejects.toMatchObject({ name: "AbortError" })+ expect(cancel).toHaveBeenCalledOnce()+ })+ it.each(['<style>body{height:100vh}</style>', '<p style="min-height:50dvh">x</p>', "<div style='height:80svh'>x</div>"])("rejects CSS viewport feedback loops", (html) => {+ expect(() => prepareHtmlPreview(html)).toThrow(HtmlPreviewValidationError)+ })+ it("does not reject ordinary text, comments or base64 containing vh", () => {+ expect(() => prepareHtmlPreview('<p>100vh</p><!-- style="height:100vh" --><img src="data:image/png;base64,100vhAA">')).not.toThrow()+ })+ it("runs the bootstrap before original scripts for documents and fragments", () => {+ for (const html of ['<!doctype html><html><head><script>original()</script></head><body>x</body></html>', '<script>original()</script><p>x</p>', '<!-- <head> --><p>x</p>']) {+ const result = prepareHtmlPreview(html)+ expect(result).toContain(html.replace(/^<!doctype html>/i, ""))+ expect(result.indexOf("alook-html-ready")).toBeLessThan(result.indexOf("original()") === -1 ? result.length : result.indexOf("original()"))+ }+ expect(HTML_PREVIEW_CSP).toContain("sandbox allow-scripts")+ expect(HTML_PREVIEW_CSP).not.toContain("allow-same-origin")+ expect(HTML_PREVIEW_CSP).toContain("frame-src 'none'")+ expect(HTML_PREVIEW_CSP).toContain("base-uri 'none'")+ })+})+++describe("generated HTML bootstrap", () => {+ it.each(["light dark", "only light"])("preserves the author's %s scheme and colors when styles load after the theme", async (scheme) => {+ const dom = new JSDOM(prepareHtmlPreview(`<!doctype html><html><head><style data-authored>:root{color-scheme:${scheme}}html,body{background:transparent}#authored{background:#73a3b2;color:#112233}</style></head><body><section id="authored">Original colors</section><input id="state" value="original"></body></html>`), {+ runScripts: "dangerously",+ beforeParse(window) {+ Object.defineProperty(window, "parent", { value: { postMessage: vi.fn() } })+ window.requestAnimationFrame = vi.fn(() => 0)+ },+ })+ try {+ await new Promise<void>((resolve) => dom.window.document.addEventListener("DOMContentLoaded", () => resolve(), { once: true }))+ const { document } = dom.window+ const input = document.querySelector<HTMLInputElement>("#state")!+ input.value = "retained edit"+ for (const dark of [false, true, false]) {+ dom.window.dispatchEvent(new dom.window.MessageEvent("message", { source: dom.window.parent, data: { type: "alook-html-theme", dark, variables: { "--background": dark ? "#121314" : "#ffffff", "--foreground": dark ? "#eeeeee" : "#111111" } } }))+ document.head.appendChild(document.querySelector("style[data-authored]")!)+ expect(dom.window.getComputedStyle(document.documentElement).colorScheme).toBe(scheme)+ for (const element of [document.documentElement, document.body]) expect(dom.window.getComputedStyle(element).backgroundColor).toBe("rgba(0, 0, 0, 0)")+ const authored = dom.window.getComputedStyle(document.querySelector("#authored")!)+ expect(authored.backgroundColor).toBe("rgb(115, 163, 178)")+ expect(authored.color).toBe("rgb(17, 34, 51)")+ expect(document.querySelector("#state")).toBe(input)+ expect(input.value).toBe("retained edit")+ }+ } finally { dom.window.close() }+ })++ it("requests the host theme, reports readiness and rejects a different sender", async () => {+ const post = vi.fn()+ const frames = new Map<number, FrameRequestCallback>()+ let frameId = 0+ const dom = new JSDOM(prepareHtmlPreview('<html><head><title>Fixture</title></head><body><button>Works</button><script>document.body.dataset.original="executed"</script></body></html>'), {+ runScripts: "dangerously",+ beforeParse(window) {+ Object.defineProperty(window, "parent", { value: { postMessage: post } })+ window.requestAnimationFrame = (callback) => { frames.set(++frameId, callback); return frameId }+ window.cancelAnimationFrame = (id) => { frames.delete(id) }+ },+ })+ try {+ await new Promise<void>((resolve) => dom.window.document.addEventListener("DOMContentLoaded", () => resolve(), { once: true }))+ expect(dom.window.document.title).toBe("Fixture")+ expect(dom.window.document.body.dataset.original).toBe("executed")+ expect(post).toHaveBeenCalledWith({ type: "alook-html-theme-request" }, "*")+ expect(post).toHaveBeenCalledWith({ type: "alook-html-ready" }, "*")+ const data = { type: "alook-html-theme", dark: true, variables: { "--background": "#123456", "--foreground": "#abcdef", "--bad": "red;}<script>" } }+ dom.window.dispatchEvent(new dom.window.MessageEvent("message", { source: dom.window, data }))+ expect(dom.window.document.documentElement.classList.contains("dark")).toBe(false)+ dom.window.dispatchEvent(new dom.window.MessageEvent("message", { source: dom.window.parent, data }))+ expect(dom.window.document.documentElement.classList.contains("dark")).toBe(true)+ expect(dom.window.document.getElementById("alook-preview-theme")!.textContent).toContain("--background:#123456")+ expect(dom.window.document.getElementById("alook-preview-theme")!.textContent).not.toContain("--bad")+ for (const [id, callback] of frames) { frames.delete(id); callback(0) }+ expect(post).toHaveBeenCalledWith({ type: "alook-html-height", height: 80 }, "*")+ } finally { frames.clear(); dom.window.close() }+ })+})diff --git a/src/web/src/lib/community/html-attachment-preview.ts b/src/web/src/lib/community/html-attachment-preview.tsnew file mode 100644index 000000000..f80401e71--- /dev/null+++ b/src/web/src/lib/community/html-attachment-preview.ts@@ -0,0 +1,118 @@+import { HTML_PREVIEW_SANDBOX, MAX_HTML_PREVIEW_BYTES } from "./html-preview-policy"++export const HTML_PREVIEW_CSP = [+ `sandbox ${HTML_PREVIEW_SANDBOX}`,+ "default-src 'none'",+ "script-src https: 'unsafe-inline' 'unsafe-eval'",+ "style-src https: 'unsafe-inline'",+ "img-src https: data: blob:",+ "font-src https: data:",+ "connect-src https:",+ "media-src https: data: blob:",+ "object-src 'none'",+ "frame-src 'none'",+ "base-uri 'none'",+ "form-action https:",+ "frame-ancestors 'self'",+].join("; ")++export class HtmlPreviewValidationError extends Error {}++export async function readHtmlPreview(body: ReadableStream<Uint8Array>, signal?: AbortSignal): Promise<string> {+ const reader = body.getReader()+ const decoder = new TextDecoder("utf-8", { fatal: true })+ function decode(value?: Uint8Array, stream = false) {+ try { return decoder.decode(value, { stream }) }+ catch { throw new HtmlPreviewValidationError("HTML must use UTF-8") }+ }+ let size = 0, html = "", finished = false+ const abort = () => { void reader.cancel().catch(() => undefined) }+ signal?.addEventListener("abort", abort, { once: true })+ try {+ while (true) {+ signal?.throwIfAborted()+ const { done, value } = await reader.read()+ signal?.throwIfAborted()+ if (done) { finished = true; break }+ size += value.byteLength+ if (size > MAX_HTML_PREVIEW_BYTES) throw new HtmlPreviewValidationError("HTML exceeds the preview limit")+ html += decode(value, true)+ }+ html += decode()+ if (!html.trim() || html.includes("\0")) throw new HtmlPreviewValidationError("Invalid HTML document")+ return html+ } finally {+ signal?.removeEventListener("abort", abort)+ if (!finished) await reader.cancel().catch(() => undefined)+ reader.releaseLock()+ }+}++const CSS_SOURCE = /<!--[\s\S]*?(?:-->|$)|<style\b[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))/gi+const VIEWPORT_HEIGHT = /(?<![\w.+/])(?:\d+(?:\.\d+)?|\.\d+)[sld]?vh(?![\w-])/i++const BASE_CSS = "html{background:var(--background);color:var(--foreground);font-family:var(--font-sans,system-ui);font-size:15px;line-height:1.6;color-scheme:light dark}body{margin:0}code,pre,kbd,samp{font-family:var(--font-mono,monospace)}:focus-visible{outline:2px solid var(--ring);outline-offset:-2px}"+const BOOTSTRAP = String.raw`(() => {+ const framed = window.parent !== window;+ const themeStyle = document.getElementById("alook-preview-theme");+ let lastHeight = 0;+ let pending = false;+ function send(type, fields) {+ if (framed) parent.postMessage({ type, ...fields }, "*");+ }+ function measure() {+ pending = false;+ if (!document.body) return;+ const root = document.documentElement;+ const measured = Math.ceil(root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height);+ const height = Math.max(80, Math.min(2000, measured));+ if (height !== lastHeight) {+ lastHeight = height;+ send("alook-html-height", { height });+ }+ }+ function schedule() {+ if (pending) return;+ pending = true;+ requestAnimationFrame(measure);+ }+ window.addEventListener("message", (event) => {+ const data = event.data;+ if (event.source !== parent || !data || data.type !== "alook-html-theme" || !data.variables || typeof data.variables !== "object") return;+ let css = ":root{color-scheme:" + (data.dark ? "dark" : "light") + ";";+ for (const key in data.variables) {+ const value = data.variables[key];+ if (/^--[a-z-]+$/.test(key) && typeof value === "string" && value.length < 1024 && !/[;{}<>]/.test(value)) css += key + ":" + value + ";";+ }+ themeStyle.textContent = css + "}" + (typeof data.fontSheet === "string" && data.fontSheet.length <= 1500000 ? data.fontSheet : "");+ document.documentElement.classList.toggle("dark", data.dark === true);+ schedule();+ });+ send("alook-html-theme-request");+ document.addEventListener("DOMContentLoaded", () => {+ send("alook-html-ready");+ schedule();+ if (window.ResizeObserver) {+ const observer = new ResizeObserver(schedule);+ observer.observe(document.documentElement);+ observer.observe(document.body);+ }+ if (window.MutationObserver) new MutationObserver(schedule).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true });+ });+ window.addEventListener("load", schedule);+ document.addEventListener("load", schedule, true);+})();`+++export function prepareHtmlPreview(html: string): string {+ for (const [, sheet, doubleQuoted, singleQuoted, unquoted] of html.matchAll(CSS_SOURCE)) {+ if (VIEWPORT_HEIGHT.test(sheet ?? doubleQuoted ?? singleQuoted ?? unquoted ?? "")) {+ throw new HtmlPreviewValidationError("Use content height instead of viewport height units")+ }+ }+ const prefix = `<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>${BASE_CSS}</style><style id="alook-preview-theme"></style><script>${BOOTSTRAP}</script>`+ const doctype = /^\s*<!doctype[^>]*>/i.exec(html)+ return doctype+ ? html.slice(0, doctype[0].length) + prefix + html.slice(doctype[0].length)+ : `<!doctype html>${prefix}${html}`+}diff --git a/src/web/src/lib/community/html-preview-fonts.dom.test.ts b/src/web/src/lib/community/html-preview-fonts.dom.test.tsnew file mode 100644index 000000000..f878f6949--- /dev/null+++ b/src/web/src/lib/community/html-preview-fonts.dom.test.ts@@ -0,0 +1,37 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import { createElement } from "react"+import { render } from "@/test/react-dom-harness"+import { collectHtmlPreviewFonts, loadHtmlPreviewFonts } from "./html-preview-fonts"++afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })++describe("HTML preview host fonts", () => {+ it("selects only named public Next font assets from the current host", () => {+ const view = render(createElement("style", null, '@font-face{font-family:"Host Sans";font-weight:400 900;src:url("/_next/static/media/sans.woff2")}@font-face{font-family:Other;src:url("/_next/static/media/other.woff2")}@font-face{font-family:"Host Sans";src:url("https://external.test/secret.woff2")}@font-face{font-family:"Host Sans";src:url("/api/private.woff2")}'))+ const style = view.container.querySelector("style")!+ const sources = ['url("/_next/static/media/sans.woff2")', 'url("/_next/static/media/other.woff2")', 'url("https://external.test/secret.woff2")', 'url("/api/private.woff2")']+ Array.from(style.sheet!.cssRules).forEach((rule, index) => {+ const declaration = (rule as CSSFontFaceRule).style+ const original = declaration.getPropertyValue.bind(declaration)+ vi.spyOn(declaration, "getPropertyValue").mockImplementation((name) => name === "src" ? sources[index]! : name === "font-weight" ? "400 900" : original(name))+ })+ try {+ expect(collectHtmlPreviewFonts(document, '"Host Sans", serif')).toEqual([{ family: "Host Sans", weight: "400 900", style: "normal", url: new URL("/_next/static/media/sans.woff2", location.href).href }])+ } finally { view.unmount() }+ })+ it("embeds bounded public font bytes without credentials, bypassing opaque-origin font CORS", async () => {+ const fetch = vi.fn().mockResolvedValue(new Response(new Uint8Array([1, 2, 3])))+ vi.stubGlobal("fetch", fetch)+ const font = { family: "Host Sans", weight: "400 900", style: "normal", url: "http://localhost/_next/static/media/sans.woff2" }+ const abort = new AbortController()+ const css = await loadHtmlPreviewFonts([font], abort.signal)+ expect(fetch).toHaveBeenCalledWith(font.url, { credentials: "omit", cache: "force-cache", signal: abort.signal })+ expect(css).toContain("data:font/woff2;base64,AQID")+ expect(css).toContain('font-family:"Host Sans"')+ expect(css).not.toContain(font.url)+ const cancel = vi.fn()+ fetch.mockResolvedValue(new Response(new ReadableStream({ start(c) { c.enqueue(new Uint8Array(256 * 1024 + 1)) }, cancel })))+ await expect(loadHtmlPreviewFonts([font], abort.signal)).rejects.toThrow("too large")+ expect(cancel).toHaveBeenCalledOnce()+ })+})diff --git a/src/web/src/lib/community/html-preview-fonts.ts b/src/web/src/lib/community/html-preview-fonts.tsnew file mode 100644index 000000000..5fffa933c--- /dev/null+++ b/src/web/src/lib/community/html-preview-fonts.ts@@ -0,0 +1,53 @@+export type HtmlPreviewFont = { family: string; weight: string; style: string; url: string }++export function collectHtmlPreviewFonts(document: Document, families: string): HtmlPreviewFont[] {+ const names = new Set(families.split(",").map((name) => name.trim().replace(/^["']|["']$/g, "")))+ const fonts = new Map<string, HtmlPreviewFont>()+ function visit(rules: CSSRuleList, base: string) {+ for (const rule of Array.from(rules)) {+ if (rule instanceof CSSFontFaceRule) {+ const style = rule.style+ const family = style.getPropertyValue("font-family").trim().replace(/^["']|["']$/g, "")+ const source = /url\(["']?([^\s"')]+)["']?\)/i.exec(style.getPropertyValue("src"))?.[1]+ if (!names.has(family) || !source) continue+ const url = new URL(source, base)+ if (url.origin !== document.location.origin || !/^\/_next\/static\/media\/[^/]+\.woff2?$/.test(url.pathname)) continue+ fonts.set(url.href, { family, weight: style.getPropertyValue("font-weight") || "400", style: style.getPropertyValue("font-style") || "normal", url: url.href })+ } else if ("cssRules" in rule) visit((rule as CSSGroupingRule).cssRules, base)+ }+ }+ for (const sheet of Array.from(document.styleSheets)) {+ try { visit(sheet.cssRules, sheet.href || document.location.href) } catch {}+ }+ return [...fonts.values()].slice(0, 4)+}++export async function loadHtmlPreviewFonts(fonts: readonly HtmlPreviewFont[], signal: AbortSignal): Promise<string> {+ const sheets = await Promise.all(fonts.map(async (font) => {+ const response = await fetch(font.url, { credentials: "omit", cache: "force-cache", signal })+ if (!response.ok || !response.body) throw new Error("Preview font unavailable")+ const reader = response.body.getReader(), chunks: Uint8Array[] = []+ let size = 0, done = false+ try {+ while (true) {+ signal.throwIfAborted()+ const chunk = await reader.read()+ signal.throwIfAborted()+ if (chunk.done) { done = true; break }+ size += chunk.value.byteLength+ if (size > 256 * 1024) throw new Error("Preview font too large")+ chunks.push(chunk.value)+ }+ const bytes = new Uint8Array(size)+ let offset = 0+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length }+ const base64 = btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""))+ const format = font.url.endsWith(".woff2") ? "woff2" : "woff"+ return `@font-face{font-family:${JSON.stringify(font.family)};font-weight:${font.weight};font-style:${font.style};font-display:swap;src:url(data:font/${format};base64,${base64}) format("${format}")}`+ } finally {+ if (!done) await reader.cancel().catch(() => undefined)+ reader.releaseLock()+ }+ }))+ return sheets.join("")+}diff --git a/src/web/src/lib/community/html-preview-markdown.test.ts b/src/web/src/lib/community/html-preview-markdown.test.tsnew file mode 100644index 000000000..64569cda1--- /dev/null+++ b/src/web/src/lib/community/html-preview-markdown.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from "vitest"+import { selectHtmlPreviews } from "./html-preview-markdown"+import { isHtmlPreviewFile, MAX_HTML_PREVIEW_BYTES } from "./html-preview-policy"+import type { FileAttachment } from "./models/message"++const file: FileAttachment = { id: "own-id", kind: "file", name: "page.html", contentType: "text/html", url: "/attachments/own-id", size: "1 KB" }+const marker = "[alook-html-preview](own-id)"+describe("HTML attachment selection", () => {+ it.each([marker, `before ${marker} after`, `before\n\n${marker}\n\nafter`, `> ${marker}`, `- ${marker}`])("selects one own HTML marker: %s", (text) => {+ expect([...selectHtmlPreviews(text, [file]).keys()]).toEqual(["own-id"])+ })+ it("deduplicates within a message and permits another message's own reuse", () => {+ expect(selectHtmlPreviews(`${marker}\n\n${marker}`, [file]).size).toBe(1)+ expect(selectHtmlPreviews(marker, [file]).size).toBe(1)+ })+ it.each([+ `\`${marker}\``, `\`\`\`html\n${marker}\n\`\`\``, `\\${marker}`, `prefix${marker}`, `${marker}suffix`,+ "[**alook-html-preview**](own-id)", "[alook-html-preview](https://example.com)",+ "[alook-html-preview](<own-id>)", "[alook-html-preview](own-id \"title\")",+ "[alook-html-preview][ref]\n\n[ref]: own-id", `||${marker}||`, `**${marker}**`,+ ])("keeps code, escaped, nested and nonliteral markers inert: %s", (text) => {+ expect(selectHtmlPreviews(text, [file]).size).toBe(0)+ })+ it("requires this message's canonical ID, applicable type and size", () => {+ for (const attachments of [[], [{ ...file, id: undefined }], [{ ...file, id: "foreign" }], [{ ...file, name: "file.txt", contentType: "text/plain" }], [{ ...file, sizeBytes: MAX_HTML_PREVIEW_BYTES + 1 }]]) {+ expect(selectHtmlPreviews(marker, attachments).size).toBe(0)+ }+ })+ it.each([["x.html", null, true], ["x.htm", "application/octet-stream", true], ["x", "text/html; charset=utf-8", true], ["x.html", "image/png", false], ["x.xhtml", "application/xhtml+xml", false]])("classifies HTML without accepting conflicting types", (name, type, expected) => {+ expect(isHtmlPreviewFile(name as string, type as string | null)).toBe(expected)+ })+})diff --git a/src/web/src/lib/community/html-preview-markdown.ts b/src/web/src/lib/community/html-preview-markdown.tsnew file mode 100644index 000000000..8dc203b57--- /dev/null+++ b/src/web/src/lib/community/html-preview-markdown.ts@@ -0,0 +1,78 @@+import { unified, type Plugin } from "unified"+import remarkParse from "remark-parse"+import type { Root, RootContent, Paragraph, Link } from "mdast"+import type { Attachment, FileAttachment } from "./models/message"+import { CHAT_REMARK_PLUGINS } from "./chat-markdown"++import { isHtmlPreviewFile, MAX_HTML_PREVIEW_BYTES } from "./html-preview-policy"++interface HtmlPreviewNode {+ type: "htmlPreview"+ data: { hName: "htmlpreview"; hProperties: { dataAttachmentId: string } }+}++declare module "mdast" {+ interface RootContentMap { htmlPreview: HtmlPreviewNode }+}++type Options = { text: string; attachments?: readonly Attachment[] }+const parser = unified().use(remarkParse).use(CHAT_REMARK_PLUGINS).freeze()++function replaceMarkers(tree: Root, { text, attachments }: Options): Map<string, FileAttachment> {+ const files = new Map((attachments ?? []).flatMap((attachment) => attachment.kind === "file" && attachment.id+ && isHtmlPreviewFile(attachment.name, attachment.contentType)+ && (attachment.sizeBytes === undefined || attachment.sizeBytes <= MAX_HTML_PREVIEW_BYTES)+ ? [[attachment.id, attachment] as const] : []))+ const selected = new Map<string, FileAttachment>()+ if (!files.size || !text.includes("[alook-html-preview]")) return selected++ function attachmentFor(node: Paragraph["children"][number]): FileAttachment | undefined {+ if (node.type !== "link") return+ const link: Link = node+ const start = link.position?.start.offset, end = link.position?.end.offset+ if (start === undefined || end === undefined || link.title+ || link.children.length !== 1 || link.children[0]?.type !== "text" || link.children[0].value !== "alook-html-preview"+ || text.slice(start, end) !== `[alook-html-preview](${link.url})`+ || (start > 0 && !/\s/.test(text[start - 1]!))+ || (end < text.length && !/\s/.test(text[end]!))) return+ return files.get(link.url)+ }++ function walk(parent: { children: RootContent[] }) {+ parent.children = parent.children.flatMap((node): RootContent[] => {+ if (node.type === "blockquote" || node.type === "listItem" || node.type === "list") {+ walk(node)+ return [node]+ }+ if (node.type !== "paragraph") return [node]+ const blocks: RootContent[] = []+ let children: Paragraph["children"] = []+ function flush() {+ if (children.some((child) => child.type !== "text" || child.value.trim())) blocks.push({ type: "paragraph", children })+ children = []+ }+ for (const child of node.children) {+ const attachment = attachmentFor(child)+ if (!attachment?.id) { children.push(child); continue }+ flush()+ if (!selected.has(attachment.id)) {+ selected.set(attachment.id, attachment)+ blocks.push({ type: "htmlPreview", data: { hName: "htmlpreview", hProperties: { dataAttachmentId: attachment.id } } })+ }+ }+ if (!blocks.length && children.length === node.children.length) return [node]+ flush()+ return blocks+ })+ }+ walk(tree)+ return selected+}++export function selectHtmlPreviews(text: string, attachments?: readonly Attachment[]): Map<string, FileAttachment> {+ if (!attachments?.some((attachment) => attachment.id) || !text.includes("[alook-html-preview]")) return new Map()+ const tree = parser.runSync(parser.parse(text)) as Root+ return replaceMarkers(tree, { text, attachments })+}++export const htmlPreviewPlugin: Plugin<[Options], Root> = (options) => (tree) => { replaceMarkers(tree, options) }diff --git a/src/web/src/lib/community/html-preview-policy.ts b/src/web/src/lib/community/html-preview-policy.tsnew file mode 100644index 000000000..34f3055da--- /dev/null+++ b/src/web/src/lib/community/html-preview-policy.ts@@ -0,0 +1,12 @@+export const MAX_HTML_PREVIEW_BYTES = 2 * 1024 * 1024+export const HTML_PREVIEW_SANDBOX = "allow-scripts allow-forms allow-popups allow-downloads"+export const HTML_PREVIEW_THEME_VARIABLES = [+ "background", "foreground", "card", "card-foreground", "popover", "popover-foreground",+ "primary", "primary-foreground", "secondary", "secondary-foreground", "muted", "muted-foreground",+ "accent", "accent-foreground", "border", "input", "ring", "destructive", "warning", "radius", "font-sans", "font-mono",+] as const++export function isHtmlPreviewFile(name: string, contentType?: string | null): boolean {+ const type = contentType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""+ return type === "text/html" || (["", "application/octet-stream", "binary/octet-stream"].includes(type) && /\.html?$/i.test(name))+}diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.tsindex 0c5ca99c1..56c6a70e2 100644--- a/src/web/src/lib/community/message-stream.test.ts+++ b/src/web/src/lib/community/message-stream.test.ts@@ -520,7 +520,7 @@ describe("attachment ownership effects", () => {expect(converged.liveIds).toContain("mf")expect(canonicalRows().get("mf")?.attachments).toEqual(settledResourceAttachments)expect(materializeMessageStream([currentBase], converged)[0]?.attachments).toEqual(- settledAttachments,+ settledAttachments.map((attachment) => ({ ...attachment, id: "photo" })),)})@@ -543,6 +543,7 @@ describe("attachment ownership effects", () => {it("lets explicit canonical attachments replace prior attachments", () => {const replacement: NonNullable<Msg["attachments"]> = [{+ id: "replacement",kind: "file",name: "canonical.txt",url: "/media/canonical",@@ -577,7 +578,7 @@ describe("attachment ownership effects", () => {state = apply(state, { type: "baseChanged", messages: [completeBase] }).stateexpect(materializeMessageStream([completeBase], state)).toEqual([- expect.objectContaining({ id: "base-id", attachments: settledAttachments }),+ expect.objectContaining({ id: "base-id", attachments: settledAttachments.map((attachment) => ({ ...attachment, id: "photo" })) }),])})diff --git a/src/web/src/lib/community/message-wire.test.ts b/src/web/src/lib/community/message-wire.test.tsindex 4c2df21fe..964525365 100644--- a/src/web/src/lib/community/message-wire.test.ts+++ b/src/web/src/lib/community/message-wire.test.ts@@ -106,9 +106,9 @@ describe("projectCommunityMessageCreate", () => {expect(raw.embeds).toHaveLength(3)expect(projected.embeds).toEqual([{ title: "Card", url: "https://example.com" }])expect(projected.attachments).toEqual([- { kind: "image", name: "photo.png", url: "/photo", contentType: "image/png", sizeBytes: 2048, width: 640, height: 480 },- { kind: "file", name: "doc.pdf", url: "/doc", contentType: "application/pdf", sizeBytes: 2048, size: "2.0 KB" },- { kind: "file", name: "unsafe.svg", url: "/unsafe", contentType: "image/svg+xml", sizeBytes: 1024, size: "1.0 KB" },+ { id: "a1", kind: "image", name: "photo.png", url: "/photo", contentType: "image/png", sizeBytes: 2048, width: 640, height: 480 },+ { id: "a2", kind: "file", name: "doc.pdf", url: "/doc", contentType: "application/pdf", sizeBytes: 2048, size: "2.0 KB" },+ { id: "a3", kind: "file", name: "unsafe.svg", url: "/unsafe", contentType: "image/svg+xml", sizeBytes: 1024, size: "1.0 KB" },])})})diff --git a/src/web/src/lib/community/messages.test.ts b/src/web/src/lib/community/messages.test.tsindex 83b047d7a..42b573525 100644--- a/src/web/src/lib/community/messages.test.ts+++ b/src/web/src/lib/community/messages.test.ts@@ -66,7 +66,7 @@ describe("groupAttachments", () => {it("retains file dimensions while formatting them only for the read view", () => {const raw = groupAttachments([{ id: "att1", messageId: "m1", targetId: "c1", filename: "a.pdf", r2Key: "key", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 }]).m1![0]!expect(raw).toMatchObject({ id: "att1", width: 1920, height: 1080, sizeBytes: 2048, thumbnailUrl: null })- expect(presentMessageAttachment(raw)).toEqual({ kind: "file", name: "a.pdf", url: "/api/community/channels/c1/attachments/att1", contentType: "application/pdf", sizeBytes: 2048, size: "2.0 KB" })+ expect(presentMessageAttachment(raw)).toEqual({ id: "att1", kind: "file", name: "a.pdf", url: "/api/community/channels/c1/attachments/att1", contentType: "application/pdf", sizeBytes: 2048, size: "2.0 KB" })})it.each(["image/svg+xml", "image/x-forged"])("preserves unsafe %s metadata and renders a file", (contentType) => {diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.tsindex e9869a710..73fb17a72 100644--- a/src/web/src/lib/community/models/message.ts+++ b/src/web/src/lib/community/models/message.ts@@ -5,6 +5,7 @@ import type { CommunityChannelResource, CommunityMessageResource, CommunityMessaexport type AttachmentPreview = Pick<CommunityMessageAttachment, "name" | "url"> & Partial<Omit<CommunityMessageAttachment, "name" | "url">>type AttachmentMetadata = Pick<CommunityMessageAttachment, "name" | "url"> & {+ id?: CommunityMessageAttachment["id"]contentType?: NonNullable<CommunityMessageAttachment["contentType"]>sizeBytes?: NonNullable<CommunityMessageAttachment["sizeBytes"]>}diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 9798f0ee1..6c7e9e324 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -195,6 +195,11 @@ export const tid = {message: (id: string) => `community-message-${id}`,messageImage: (id: string, index: number) => `community-message-image-${id}-${index}`,threadOpenerImage: (index: number) => `community-thread-opener-image-${index}`,+ htmlPreview: (id: string) => `community-html-preview-${id}`,+ htmlPreviewFrame: (id: string) => `community-html-preview-frame-${id}`,+ htmlPreviewExpand: (id: string) => `community-html-preview-expand-${id}`,+ htmlPreviewClose: (id: string) => `community-html-preview-close-${id}`,+ htmlPreviewDownload: (id: string) => `community-html-preview-download-${id}`,attachmentCard: (name: string) => `community-attachment-card-${name}`,attachmentPreviewSheet: "community-attachment-preview-sheet",attachmentPreviewDownload: "community-attachment-preview-download",diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.tsindex 304acfa4d..7262f1c97 100644--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts@@ -1,7 +1,10 @@+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"import type { Locator, Page, TestInfo } from "@playwright/test"+import sharp from "sharp"import { test, expect } from "./_fixtures/case-fixture"import { tid } from "./_fixtures/testids"import { composerEditable, createServer } from "./_fixtures/actions"+import { holdRoute } from "./_fixtures/held-route"import { solidPngFixture } from "../fixtures/media"const LANDSCAPE_FIXTURE = solidPngFixture(800, 450, [91, 110, 225])@@ -878,3 +881,219 @@ test("image previews keep one frame through loading, decode, failure, retry, andcontentType: "application/json",})})++test("HTML attachment markers render once with interactive isolated content across readers", async ({ caseActors, caseResources }, testInfo) => {+ test.setTimeout(120_000)+ const actors = await caseActors(["alice", "bob", "carol"])+ const serverId = await actors.seed.seedServer("alice", `HTML preview ${Date.now()}`)+ const channelId = await actors.seed.seedChannel("alice", serverId, "html-preview")+ await actors.seed.seedJoinServer("alice", "bob", serverId)+ const { page } = await actors.asUser("alice", { colorScheme: null })+ const channelPath = `/c/channels/${serverId}/${channelId}`+ await page.goto(channelPath)+ const html = '<!doctype html><html><head><style>body{padding:16px;background:var(--background);color:var(--foreground)}button{background:var(--primary);color:var(--primary-foreground)}.row{height:64px}</style></head><body><h2>Interactive HTML</h2><button onclick="document.getElementById(\'rows\').insertAdjacentHTML(\'beforeend\',\'<div class=row>Added row</div>\');document.getElementById(\'count\').textContent=Number(document.getElementById(\'count\').textContent)+1">Add row</button><output id="count">0</output><div id="rows"></div><p id="isolation"></p><script>try{parent.document.body;document.getElementById("isolation").textContent="parent accessible"}catch(e){document.getElementById("isolation").textContent="parent isolated"}</script></body></html>'+ async function upload(name: string, mimeType: string, content: string) {+ const response = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/attachments`, {+ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,+ multipart: { file: { name, mimeType, buffer: Buffer.from(content) } },+ }))+ expect(response.status()).toBe(200)+ return (await response.json() as { id: string }).id+ }+ const attachmentId = await upload("interactive.html", "text/html", html)+ const textId = await upload("ordinary.txt", "text/plain", "ordinary bytes")+ const marker = `[alook-html-preview](${attachmentId})`+ const response = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/messages`, {+ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,+ data: { content: `Before preview ${marker} After preview\n\n${marker}\n\n[alook-html-preview](${textId})\n\n\`${marker}\`\n\n\\${marker}`, attachments: [attachmentId, textId] },+ }))+ expect(response.status()).toBe(201)+ const messageId = (await response.json() as { message: { id: string } }).message.id+ const message = page.getByTestId(tid.message(messageId))+ const preview = message.getByTestId(tid.htmlPreview(attachmentId))+ await expect(preview).toHaveAttribute("data-html-preview-status", "ready")+ await expect(message.getByTestId(tid.htmlPreview(attachmentId))).toHaveCount(1)+ await expect(message.getByTestId(tid.attachmentCard("interactive.html"))).toHaveCount(0)+ await expect(message.getByTestId(tid.attachmentCard("ordinary.txt"))).toHaveCount(1)+ await expect(message).toContainText("Before preview")+ await expect(message).toContainText("After preview")+ const iframe = message.getByTestId(tid.htmlPreviewFrame(attachmentId))+ expect(await iframe.getAttribute("sandbox")).not.toContain("allow-same-origin")+ const content = iframe.contentFrame()+ await expect(content.locator("#isolation")).toHaveText("parent isolated")+ const actions = preview.getByRole("group", { name: "HTML preview actions" })+ await expect(preview).toHaveCSS("border-top-width", "0px")+ await expect(preview.getByText("interactive.html", { exact: true })).toHaveCount(0)+ await expect(actions).toHaveCSS("position", "absolute")+ async function appearance(mode: "Light" | "Dark") {+ await page.getByTestId(tid.userSettingsOpen).click()+ await page.getByTestId(tid.settingsTab("appearance")).click()+ await page.getByRole("button", { name: mode, exact: true }).click()+ await page.getByTestId(tid.settingsClose).click()+ }+ async function expectCommittedTheme(dark: boolean) {+ const names = ["background", "foreground", "card", "secondary", "primary", "primary-foreground", "border"]+ await expect.poll(async () => {+ const host = await iframe.evaluate((element, tokens) => {+ const root = getComputedStyle(document.documentElement), painted = getComputedStyle(element)+ return { dark: document.documentElement.classList.contains("dark"), variables: Object.fromEntries(tokens.map((name) => [name, root.getPropertyValue(`--${name}`).trim()])), foreground: painted.color, background: root.backgroundColor }+ }, names)+ const embedded = await content.locator("html").evaluate((element, tokens) => {+ const root = getComputedStyle(element), painted = getComputedStyle(document.body)+ return { dark: element.classList.contains("dark"), variables: Object.fromEntries(tokens.map((name) => [name, root.getPropertyValue(`--${name}`).trim()])), foreground: painted.color, background: painted.backgroundColor }+ }, names)+ return { hostDark: host.dark, frameDark: embedded.dark, tokens: JSON.stringify(embedded.variables) === JSON.stringify(host.variables), foreground: embedded.foreground === host.foreground, background: embedded.background === host.background }+ }).toEqual({ hostDark: dark, frameDark: dark, tokens: true, foreground: true, background: true })+ await expect(iframe).toHaveCount(1)+ await expect(iframe).toHaveCSS("background-color", "rgba(0, 0, 0, 0)")+ }+ await appearance("Light")+ await expectCommittedTheme(false)+ const initialFrame = await iframe.elementHandle()+ await appearance("Dark")+ await expectCommittedTheme(true)+ await appearance("Light")+ await expectCommittedTheme(false)+ expect(await iframe.evaluate((element, original) => element === original, initialFrame)).toBe(true)+ await initialFrame?.dispose()+ await page.mouse.move(0, 0)+ await expect(actions).toHaveCSS("opacity", "0")+ await preview.hover()+ await expect(actions).toHaveCSS("opacity", "1")+ await page.mouse.move(0, 0)+ await message.getByTestId(tid.htmlPreviewDownload(attachmentId)).focus()+ await expect(actions).toHaveCSS("opacity", "1")+ const beforeHeight = await iframe.evaluate((element) => element.getBoundingClientRect().height)+ await content.getByRole("button", { name: "Add row" }).click()+ await expect(content.locator("#count")).toHaveText("1")+ await expect.poll(() => iframe.evaluate((element) => element.getBoundingClientRect().height)).toBeGreaterThan(beforeHeight)+ await message.getByTestId(tid.htmlPreviewExpand(attachmentId)).click()+ await expect(preview).toHaveAttribute("aria-modal", "true")+ await expect(content.locator("#count")).toHaveText("1")+ await message.getByTestId(tid.htmlPreviewClose(attachmentId)).click()+ await expect(preview).not.toHaveAttribute("aria-modal", "true")+ await expect(content.locator("#count")).toHaveText("1")++ const previewUrl = `/api/community/channels/${channelId}/attachments/${attachmentId}?preview=html`+ const direct = await page.request.get(previewUrl)+ expect(direct.status()).toBe(200)+ expect(direct.headers()["content-security-policy"]).toContain("sandbox allow-scripts")+ expect(direct.headers()["cache-control"]).toBe("private, no-store")+ const original = await page.request.get(`/api/community/channels/${channelId}/attachments/${attachmentId}`)+ expect(original.headers()["content-disposition"]).toContain("attachment")+ expect(await original.text()).toBe(html)++ const { page: reader } = await actors.asUser("bob", { viewport: { width: 390, height: 844 }, hasTouch: true })+ await reader.goto(channelPath)+ const readerPreview = reader.getByTestId(tid.message(messageId)).getByTestId(tid.htmlPreview(attachmentId))+ await expect(readerPreview).toHaveAttribute("data-html-preview-status", "ready")+ await expect(readerPreview.getByTestId(tid.htmlPreviewFrame(attachmentId)).contentFrame().getByRole("button", { name: "Add row" })).toBeVisible()+ await expect(readerPreview.getByRole("group", { name: "HTML preview actions" })).toHaveCSS("opacity", "1")+ await expect(readerPreview.getByTestId(tid.htmlPreviewExpand(attachmentId))).toHaveCSS("width", "44px")+ await readerPreview.getByTestId(tid.htmlPreviewExpand(attachmentId)).tap()+ await expect(readerPreview).toHaveAttribute("aria-modal", "true")+ await readerPreview.getByTestId(tid.htmlPreviewClose(attachmentId)).tap()+ await expect(readerPreview).not.toHaveAttribute("aria-modal", "true")+ await expect(readerPreview.getByTestId(tid.htmlPreviewFrame(attachmentId)).contentFrame().locator("#count")).toHaveText("0")+ const { page: outsider } = await actors.asUser("carol")+ const denied = await outsider.request.get(previewUrl)+ expect(denied.status()).toBe(404)+ await testInfo.attach("html-preview-headers.json", {+ body: JSON.stringify({ serverId, channelId, messageId, attachmentId, preview: Object.fromEntries(Object.entries(direct.headers()).filter(([name]) => ["content-type", "content-disposition", "content-security-policy", "cache-control", "referrer-policy", "x-content-type-options"].includes(name))), download: Object.fromEntries(Object.entries(original.headers()).filter(([name]) => ["content-type", "content-disposition", "cache-control"].includes(name))), outsiderStatus: denied.status() }, null, 2),+ contentType: "application/json",+ })++ const transparentHtml = '<!doctype html><html><head><style>:root{color-scheme:light dark}html,body{margin:0;background:transparent}body{min-height:112px;color:var(--foreground)}#authored{position:absolute;left:0;top:48px;width:160px;height:48px;background:#73a3b2;color:#112233}input{position:absolute;left:180px;top:48px}</style></head><body><div id="authored"></div><input id="state" value="original"></body></html>'+ const transparentId = await upload("transparent.html", "text/html", transparentHtml)+ await appearance("Dark")+ const transparentPreviewUrl = new URL(`/api/community/channels/${channelId}/attachments/${transparentId}?preview=html`, page.url()).href+ const heldPreview = await holdRoute(page, transparentPreviewUrl, caseResources)+ let transparentPreview: Locator, transparentFrame: Locator+ let loading: Awaited<ReturnType<typeof captureCanvas>>+ try {+ const transparentResponse = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/messages`, {+ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,+ data: { content: `[alook-html-preview](${transparentId})`, attachments: [transparentId] },+ }))+ expect(transparentResponse.status()).toBe(201)+ const transparentMessageId = (await transparentResponse.json() as { message: { id: string } }).message.id+ transparentPreview = page.getByTestId(tid.message(transparentMessageId)).getByTestId(tid.htmlPreview(transparentId))+ transparentFrame = transparentPreview.getByTestId(tid.htmlPreviewFrame(transparentId))+ await transparentPreview.scrollIntoViewIfNeeded()+ await expect.poll(heldPreview.held).toBeGreaterThan(0)+ await expect(transparentPreview).toHaveAttribute("data-html-preview-status", "loading")+ await expect(transparentFrame).toHaveCSS("color-scheme", "light")+ loading = await captureCanvas("transparent-canvas-dark-host-loading.png")+ } finally { await heldPreview.release() }+ await expect(transparentPreview).toHaveAttribute("data-html-preview-status", "ready")+ await expect(transparentFrame).toHaveCSS("color-scheme", "dark")+ const transparentContent = transparentFrame.contentFrame()+ const originalTransparentFrame = await transparentFrame.elementHandle()+ await transparentContent.locator("#state").fill("retained edit")+ async function captureCanvas(name: string) {+ await transparentFrame.scrollIntoViewIfNeeded()+ await expect(transparentFrame).toHaveCSS("background-color", "rgba(0, 0, 0, 0)")+ const carrier = await transparentFrame.evaluate(async (element) => {+ const ancestors: Element[] = []+ for (let node = element.parentElement; node; node = node.parentElement) ancestors.push(node)+ await Promise.all(ancestors.flatMap((node) => node.getAnimations().filter((animation) => animation.effect?.getTiming().iterations !== Infinity).map((animation) => animation.finished)))+ const canvas = document.createElement("canvas")+ canvas.width = canvas.height = 1+ const context = canvas.getContext("2d")+ if (!context) throw new Error("Canvas2D is unavailable")+ const layers = ancestors.reverse().map((node) => {+ const style = getComputedStyle(node)+ if (style.backgroundImage !== "none" || style.opacity !== "1") throw new Error("Preview carrier has a background image or element opacity")+ context.fillStyle = style.backgroundColor+ context.fillRect(0, 0, 1, 1)+ return { tag: node.tagName, testId: node.getAttribute("data-testid"), background: style.backgroundColor }+ })+ const rgba = [...context.getImageData(0, 0, 1, 1).data]+ if (rgba[3] !== 255) throw new Error("Preview carrier has no opaque backing")+ return { rgb: rgba.slice(0, 3), layers }+ })+ const screenshot = await transparentFrame.screenshot({ scale: "css" })+ await testInfo.attach(name, { body: screenshot, contentType: "image/png" })+ const canvas = [...await sharp(screenshot).extract({ left: 2, top: 2, width: 1, height: 1 }).removeAlpha().raw().toBuffer()]+ expect(canvas).toEqual(carrier.rgb)+ return { screenshot, canvas, carrier }+ }+ async function transparentPixels(name: string) {+ const { screenshot, canvas, carrier } = await captureCanvas(name)+ const authored = [...await sharp(screenshot).extract({ left: 2, top: 52, width: 1, height: 1 }).removeAlpha().raw().toBuffer()]+ expect(authored).toEqual([115, 163, 178])+ return { canvas, authored, carrier }+ }+ const canvasSamples = []+ const transparentActions = transparentPreview.getByRole("group", { name: "HTML preview actions" })+ for (const mode of ["Light", "Dark"] as const) {+ await appearance(mode)+ await expect(transparentFrame).toHaveCSS("color-scheme", mode.toLowerCase())+ await expect(transparentContent.locator("html")).toHaveCSS("color-scheme", "light dark")+ await expect.poll(() => transparentContent.locator("html").evaluate(() => matchMedia("(prefers-color-scheme: dark)").matches)).toBe(mode === "Dark")+ for (const selector of ["html", "body"]) await expect(transparentContent.locator(selector)).toHaveCSS("background-color", "rgba(0, 0, 0, 0)")+ await expect(transparentContent.locator("#authored")).toHaveCSS("color", "rgb(17, 34, 51)")+ const inline = await transparentPixels(`transparent-canvas-${mode.toLowerCase()}-inline.png`)+ await transparentPreview.hover()+ await expect(transparentActions).toHaveCSS("opacity", "1")+ await expect(transparentActions).toHaveCSS("pointer-events", "auto")+ await transparentPreview.getByTestId(tid.htmlPreviewExpand(transparentId)).click()+ await expect(transparentPreview).toHaveAttribute("aria-modal", "true")+ const fullscreen = await transparentPixels(`transparent-canvas-${mode.toLowerCase()}-fullscreen.png`)+ await transparentPreview.getByTestId(tid.htmlPreviewClose(transparentId)).click()+ await expect(transparentPreview).not.toHaveAttribute("aria-modal", "true")+ await expect(transparentContent.locator("#state")).toHaveValue("retained edit")+ canvasSamples.push({ mode, inline, fullscreen })+ }+ for (const phase of ["inline", "fullscreen"] as const) {+ expect(canvasSamples[1]![phase].canvas.reduce((sum, value) => sum + value, 0)).toBeLessThan(canvasSamples[0]![phase].canvas.reduce((sum, value) => sum + value, 0))+ }+ expect(loading.canvas.reduce((sum, value) => sum + value, 0)).toBeLessThan(canvasSamples[0]!.inline.canvas.reduce((sum, value) => sum + value, 0))+ await appearance("Light")+ await expect(transparentContent.locator("html")).toHaveCSS("color-scheme", "light dark")+ await expect.poll(() => transparentContent.locator("html").evaluate(() => matchMedia("(prefers-color-scheme: dark)").matches)).toBe(false)+ await expect(transparentContent.locator("#state")).toHaveValue("retained edit")+ expect(await transparentFrame.evaluate((element, original) => element === original, originalTransparentFrame)).toBe(true)+ await originalTransparentFrame?.dispose()+ await testInfo.attach("transparent-canvas-pixels.json", { body: JSON.stringify({ loadingCanvas: loading.canvas, loadingCarrier: loading.carrier, themes: canvasSamples }, null, 2), contentType: "application/json" })+})