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 pdf attachments (#686)
Gener5ad9ecc86ec3
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b99319b85..8bb856dcb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -487,6 +487,9 @@ importers:next-themes:specifier: ^0.4.6+ pdfjs-dist:+ specifier: 6.3.289+ version: 6.3.289postal-mime:specifier: ^2.7.6version: 2.7.6@@ -2565,6 +2568,81 @@ packages:resolution: {integrity: sha512-VVPPgHyQ6ShqnrmDWuxjmUIsO9gWyOZFmuOfLd9LfBGQJwZfy0gvv9pbHSJuoFNIYC7ZDX9aoFwowjcdSC4E8w==}engines: {node: '>=18'}+ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-5+nkh8i3gt6lqS/d2jTZ1xAn6tdgtB4Lf1mW6T0Qm5/rXNwBuV1sAEyLEWan5o9gJPU/GuvHR3rvSeZ+FaGrbw==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-7jQ47gi+fZ7KJmfc/5rNyy1CYw/cu4kZ0KPIYbo9UUgSdW0bKQJpt+WihEor6s4Lyp7+xc3a+3HeyXmAEbbnPg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-rRjDMZs9pIRKGxgijwezplKc1RnJsqUokrA9h88bbTkqQ+7ePj0ZN4ZnZDy8Vu0tXs7KRlI2tQLaK4mx9QlxHg==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-jGcCd+8ra6Q61xKqZeiItujTpp9a9eRLcQ0jW6qYNku+WpupqOPFPY0SrsuSnXFviJwkpKYT9p7QrB4lsf3LNQ==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-od6I2Y7kU7i1SwZYG2EKW8rWz6JiedtPpko4WEe1DDsiikrfaotVBCRaUTM5/yeZKaZ92EatoAS+5xG+6uJlYA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-yYkPbJDJiWj6N0gASA3CAvRypZmVpJnxU0DQg3aBhneLDQde9TPLKADsQkobNoJUtTT/lj46aWpzT48PDb3Qcg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-PB00MSKAp4VwK/xwe6duKxRKmH8UH4GIl1pqHSbxng0jnU9Dr7FwaDypDiqwNFZ774N+8G7mJLGuLtg9NTcQsg==}+ engines: {node: '>= 10'}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-TWM2XWJoitLiIPCvgJh7SriC+L/T9qkYCVzC66AidsZy0QP1hkKzBzVwshCdcA3q6fIn3yE0ISbq4lMJSy8jFw==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-hb20MxKXXb5IB7AAwN8UHz9WRsa2HmdZfjsDCzjElwJoeV1aotVEwFU4FrFQcYQVzsJQLeaCc/2Qdt/0Q72mMg==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-WwPN08IXE4SkL+FhJyPz/iFnycMAUkbphFIT4cmKLlvbSU0Zfn1R7BGJ3Hqky1S89QUYc0Q4IOScXb/42Re9wQ==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-XkrVqKb+pxyba7kjy2LJvABFVBTE0DNpEl7MrG4OYUmaWarrXH+t54z/Czj2YxCKtizYTV4mg6phNm3x24qjhQ==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-/SaLcvlqGWdm0HSCWMgHu7cjJiQXfP8/mOY+6dUyV9flQz7sPBBZ+ed2zYtoukojPmxOaL7bm+d/G4GeWWoN7g==}+ engines: {node: '>= 10'}+'@napi-rs/[email protected]':resolution: {integrity: sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q==}engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}@@ -7867,6 +7945,10 @@ packages:resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}+ resolution: {integrity: sha512-ZHjSVpDa3D6izMq8/04lvkhkATUmL9px6ChPaXc1k6nU2Mrhlg1/7F0bdUqCwUjw3NsPTfPZsMDUU6ZIcRaeQw==}+ engines: {node: '>=22.13.0 || >=24'}+resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}@@ -11528,6 +11610,54 @@ snapshots:strict-event-emitter: 0.5.1optional: true+ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optionalDependencies:+ '@napi-rs/canvas-android-arm64': 1.0.8+ '@napi-rs/canvas-darwin-arm64': 1.0.8+ '@napi-rs/canvas-darwin-x64': 1.0.8+ '@napi-rs/canvas-linux-arm-gnueabihf': 1.0.8+ '@napi-rs/canvas-linux-arm64-gnu': 1.0.8+ '@napi-rs/canvas-linux-arm64-musl': 1.0.8+ '@napi-rs/canvas-linux-riscv64-gnu': 1.0.8+ '@napi-rs/canvas-linux-x64-gnu': 1.0.8+ '@napi-rs/canvas-linux-x64-musl': 1.0.8+ '@napi-rs/canvas-win32-arm64-msvc': 1.0.8+ '@napi-rs/canvas-win32-x64-msvc': 1.0.8+ optional: true+dependencies:'@emnapi/core': 1.10.0@@ -17424,6 +17554,10 @@ snapshots:+ optionalDependencies:+ '@napi-rs/canvas': 1.0.8+diff --git a/src/web/package.json b/src/web/package.jsonindex 7ad2d8537..4b248fb28 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -103,6 +103,7 @@"nanoid": "^5.1.16","next": "16.3.0","next-themes": "^0.4.6",+ "pdfjs-dist": "6.3.289","postal-mime": "^2.7.6","react": "19.2.8","react-dom": "19.2.8",diff --git a/src/web/src/components/community/messages/attachment-card.test.ts b/src/web/src/components/community/messages/attachment-card.test.tsindex 2d7553f93..c8f8a4a43 100644--- a/src/web/src/components/community/messages/attachment-card.test.ts+++ b/src/web/src/components/community/messages/attachment-card.test.ts@@ -48,29 +48,47 @@ describe("AttachmentCard", () => {createElement: vi.fn(() => anchor),})vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:file"), revokeObjectURL: vi.fn() })- const pdf = attachment({ name: "报告.pdf", contentType: "application/pdf" })+ const archive = attachment({ name: "报告.zip", contentType: "application/zip" })let renderer: TestRenderer.ReactTestRendereract(() => {renderer = TestRenderer.create(React.createElement(AttachmentCard, {- attachment: pdf,+ attachment: archive,onPreview,}))})const button = renderer!.root.findByType("button")- expect(button.props["data-attachment-category"]).toBe("pdf")- expect(button.props["aria-label"]).toBe("Download 报告.pdf")+ expect(button.props["data-attachment-category"]).toBe("archive")+ expect(button.props["aria-label"]).toBe("Download 报告.zip")await act(async () => {button.props.onClick()await Promise.resolve()await Promise.resolve()})expect(fetch).toHaveBeenCalledWith("/attachments/a1", { credentials: "same-origin" })- expect(anchor).toEqual(expect.objectContaining({ href: "blob:file", download: "报告.pdf" }))+ expect(anchor).toEqual(expect.objectContaining({ href: "blob:file", download: "报告.zip" }))expect(anchor.click).toHaveBeenCalledOnce()expect(onPreview).not.toHaveBeenCalled()expect(renderer!.root.findByProps({ role: "status" }).children).toEqual(["Download started"])})+ it("opens a PDF through the shared preview handler", () => {+ const onPreview = vi.fn()+ const pdf = attachment({ name: "报告.pdf", contentType: "application/pdf" })+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(AttachmentCard, {+ attachment: pdf,+ onPreview,+ }))+ })++ const button = renderer!.root.findByType("button")+ expect(button.props["data-attachment-category"]).toBe("pdf")+ expect(button.props["aria-label"]).toBe("Preview 报告.pdf")+ act(() => button.props.onClick())+ expect(onPreview).toHaveBeenCalledWith(pdf)+ })+it.each([["source.ts", "application/octet-stream", "code"],["unsafe.svg", "image/svg+xml", "code"],diff --git a/src/web/src/components/community/messages/attachment-preview-sheet.test.ts b/src/web/src/components/community/messages/attachment-preview-sheet.test.tsindex 818612ec9..3c86c64fb 100644--- a/src/web/src/components/community/messages/attachment-preview-sheet.test.ts+++ b/src/web/src/components/community/messages/attachment-preview-sheet.test.ts@@ -1,22 +1,34 @@import React from "react"import TestRenderer, { act } from "react-test-renderer"import { afterEach, describe, expect, it, vi } from "vitest"-import { AttachmentPreviewSheet, readAttachmentText } from "./attachment-preview-sheet"+import {+ AttachmentPreviewSheet,+ readAttachmentBytes,+ readAttachmentText,+} from "./attachment-preview-sheet"import type { FileAttachment } from "@/lib/community/models/message"import { resetAttachmentDownloadsForTest } from "@/lib/community/attachment-download"+import { MAX_PDF_ATTACHMENT_PREVIEW_BYTES } from "@/lib/community/attachment-presentation"const dynamicMock = vi.hoisted(() => ({- options: null as null | Record<string, unknown>,+ loaders: [] as Array<() => Promise<unknown>>,+ options: [] as Array<Record<string, unknown>>,}))vi.mock("next/dynamic", () => ({- default: (_loader: unknown, options: Record<string, unknown>) => {- dynamicMock.options = options- return ({ content, language }: { content: string; language: string | null }) => React.createElement(- "pre",- { "data-code-language": language ?? "plain" },- content,- )+ default: (loader: () => Promise<unknown>, options: Record<string, unknown>) => {+ dynamicMock.loaders.push(loader)+ const index = dynamicMock.options.push(options) - 1+ return index === 0+ ? ({ content, language }: { content: string; language: string | null }) => React.createElement(+ "pre",+ { "data-code-language": language ?? "plain" },+ content,+ )+ : ({ data }: { data: Uint8Array }) => React.createElement(+ "pdf-preview",+ { "data-testid": "community-pdf-preview", "data-byte-length": data.byteLength },+ )},}))@@ -67,6 +79,13 @@ vi.mock("./code-preview", () => ({),}))+vi.mock("./pdf-preview", () => ({+ PdfPreview: ({ data }: { data: Uint8Array }) => React.createElement(+ "pdf-preview",+ { "data-testid": "community-pdf-preview", "data-byte-length": data.byteLength },+ ),+}))+function file(overrides: Partial<FileAttachment> = {}): FileAttachment {return {kind: "file",@@ -105,10 +124,32 @@ describe("readAttachmentText", () => {})})+describe("readAttachmentBytes", () => {+ it("accepts the exact limit and rejects declared or streamed overflow", async () => {+ await expect(readAttachmentBytes(new Response(new Uint8Array([1, 2, 3])), 3))+ .resolves.toEqual(new Uint8Array([1, 2, 3]))+ await expect(readAttachmentBytes(new Response(new Uint8Array([1]), {+ headers: { "content-length": "4" },+ }), 3)).rejects.toThrow("too large")+ await expect(readAttachmentBytes(new Response(new Uint8Array([1, 2, 3, 4])), 3))+ .rejects.toThrow("too large")+ })++ it("reads a bodyless response through the bounded array-buffer fallback", async () => {+ const response = {+ ok: true,+ headers: new Headers(),+ body: null,+ arrayBuffer: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]).buffer),+ } as unknown as Response+ await expect(readAttachmentBytes(response, 3)).resolves.toEqual(new Uint8Array([1, 2, 3]))+ })+})+describe("AttachmentPreviewSheet", () => {it("keeps the syntax-preview subtree client-only with a stable loading state", async () => {- expect(dynamicMock.options?.ssr).toBe(false)- const loading = dynamicMock.options?.loading as (() => React.ReactElement) | undefined+ expect(dynamicMock.options[0]?.ssr).toBe(false)+ const loading = dynamicMock.options[0]?.loading as (() => React.ReactElement) | undefinedexpect(loading).toBeTypeOf("function")let renderer: TestRenderer.ReactTestRendererawait act(async () => {@@ -121,6 +162,21 @@ describe("AttachmentPreviewSheet", () => {expect(state.children.join("")).toContain("Loading syntax highlighter")})+ it("keeps the PDF renderer client-only with a stable loading state", async () => {+ expect(dynamicMock.options[1]?.ssr).toBe(false)+ await expect(dynamicMock.loaders[1]!()).resolves.toBeTypeOf("function")+ const loading = dynamicMock.options[1]?.loading as (() => React.ReactElement) | undefined+ let renderer: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(loading!())+ })+ const state = renderer!.root.findByProps({+ "data-testid": "community-pdf-preview-status",+ })+ expect(state.props.role).toBe("status")+ expect(state.children.join("")).toContain("Loading PDF renderer")+ })+it("fetches private Markdown, renders it safely, and exposes metadata/download", async () => {resetAttachmentDownloadsForTest()const fetchMock = vi.fn()@@ -201,6 +257,108 @@ describe("AttachmentPreviewSheet", () => {expect(renderer!.root.findAllByType("pre")[0]?.children).toEqual(["second"])})+ it("keeps the exact PDF cap eligible and hands authenticated bytes to the lazy renderer", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(new Uint8Array([37, 80, 68, 70]), {+ status: 200,+ }))+ vi.stubGlobal("fetch", fetchMock)+ let renderer: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {+ attachment: file({+ name: "report.pdf",+ contentType: "application/pdf",+ sizeBytes: MAX_PDF_ATTACHMENT_PREVIEW_BYTES,+ }),+ open: true,+ onOpenChange: vi.fn(),+ }))+ })+ await flush()++ expect(fetchMock).toHaveBeenCalledWith("/attachments/a1", expect.objectContaining({+ credentials: "same-origin",+ }))+ expect(renderer!.root.findByProps({ "data-testid": "community-pdf-preview" }).props["data-byte-length"])+ .toBe(4)+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-content" }).props.className)+ .toContain("p-0")+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-content" }).props.className)+ .toContain("overflow-hidden")+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-download" }))+ .toBeTruthy()+ })++ it("rejects a known oversized PDF before fetch while preserving Download", async () => {+ const fetchMock = vi.fn()+ vi.stubGlobal("fetch", fetchMock)+ let renderer: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {+ attachment: file({+ name: "large.pdf",+ contentType: "application/pdf",+ sizeBytes: MAX_PDF_ATTACHMENT_PREVIEW_BYTES + 1,+ }),+ open: true,+ onOpenChange: vi.fn(),+ }))+ })++ expect(fetchMock).not.toHaveBeenCalled()+ expect(renderer!.root.findAllByType("p").some((node) => node.children.join("").includes("too large")))+ .toBe(true)+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-download" }))+ .toBeTruthy()+ })++ it("aborts PDF acquisition when the sheet closes", async () => {+ let requestSignal: AbortSignal | undefined+ vi.stubGlobal("fetch", vi.fn((_url: string, init: RequestInit) => {+ requestSignal = init.signal as AbortSignal+ return new Promise<Response>(() => {})+ }))+ let renderer: TestRenderer.ReactTestRenderer+ const attachment = file({ name: "report.pdf", contentType: "application/pdf" })+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {+ attachment,+ open: true,+ onOpenChange: vi.fn(),+ }))+ })++ expect(requestSignal?.aborted).toBe(false)+ await act(async () => {+ renderer!.update(React.createElement(AttachmentPreviewSheet, {+ attachment,+ open: false,+ onOpenChange: vi.fn(),+ }))+ })+ expect(requestSignal?.aborted).toBe(true)+ expect(renderer!.root.findAllByProps({ "data-testid": "community-pdf-preview" }))+ .toHaveLength(0)+ })++ it("keeps Download available when the authenticated PDF request is denied", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("denied", { status: 403 })))+ let renderer: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {+ attachment: file({ name: "private.pdf", contentType: "application/pdf" }),+ open: true,+ onOpenChange: vi.fn(),+ }))+ })+ await flush()++ expect(renderer!.root.findAllByType("p").some((node) => node.children.join("").includes("403")))+ .toBe(true)+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-download" }))+ .toBeTruthy()+ })+it("passes the resolved source language to CodePreview", async () => {vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("const answer = 42", { status: 200 })))let renderer: TestRenderer.ReactTestRenderer@@ -236,6 +394,8 @@ describe("AttachmentPreviewSheet", () => {.not.toContain("p-0")expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-content" }).props.className).not.toContain("sm:p-0")+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-content" }).props.className)+ .not.toContain("overflow-hidden")})it("keeps the existing one MiB ceiling for code", async () => {diff --git a/src/web/src/components/community/messages/attachment-preview-sheet.tsx b/src/web/src/components/community/messages/attachment-preview-sheet.tsxindex 11402ecd7..af629d1e9 100644--- a/src/web/src/components/community/messages/attachment-preview-sheet.tsx+++ b/src/web/src/components/community/messages/attachment-preview-sheet.tsx@@ -11,6 +11,7 @@ import type { FileAttachment } from "@/lib/community/models/message"import { tid } from "@/lib/community/testids"import {formatAttachmentSize,+ MAX_PDF_ATTACHMENT_PREVIEW_BYTES,MAX_TEXT_ATTACHMENT_PREVIEW_BYTES,resolveAttachmentPresentation,} from "@/lib/community/attachment-presentation"@@ -36,9 +37,27 @@ const CodePreview = dynamic(},)+const PdfPreview = dynamic(+ () => import("./pdf-preview").then((module) => module.PdfPreview),+ {+ ssr: false,+ loading: () => (+ <div+ data-testid={tid.pdfPreviewStatus}+ role="status"+ className="flex min-h-40 items-center justify-center gap-2 text-sm text-muted-foreground"+ >+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />+ Loading PDF renderer…+ </div>+ ),+ },+)+type PreviewState =| { status: "idle" | "loading"; content: null; error: null }- | { status: "ready"; content: string; error: null }+ | { status: "ready"; kind: "text"; content: string; error: null }+ | { status: "ready"; kind: "pdf"; content: Uint8Array<ArrayBuffer>; error: null }| { status: "error"; content: null; error: string }const IDLE_STATE: PreviewState = { status: "idle", content: null, error: null }@@ -78,6 +97,14 @@ export async function readAttachmentText(maxBytes = MAX_TEXT_ATTACHMENT_PREVIEW_BYTES,signal?: AbortSignal,): Promise<string> {+ return new TextDecoder().decode(await readAttachmentBytes(response, maxBytes, signal))+}++export async function readAttachmentBytes(+ response: Response,+ maxBytes: number,+ signal?: AbortSignal,+): Promise<Uint8Array<ArrayBuffer>> {if (!response.ok) throw new Error(`Couldn’t load this attachment (${response.status})`)const declaredLength = Number(response.headers.get("content-length"))if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {@@ -86,13 +113,12 @@ export async function readAttachmentText(if (!response.body) {const bytes = new Uint8Array(await response.arrayBuffer())if (bytes.byteLength > maxBytes) throw new Error("This file is too large to preview")- return new TextDecoder().decode(bytes)+ return bytes}const reader = response.body.getReader()- const decoder = new TextDecoder()let byteLength = 0- let content = ""+ const chunks: Uint8Array[] = []try {while (true) {if (signal?.aborted) throw new DOMException("Aborted", "AbortError")@@ -103,9 +129,15 @@ export async function readAttachmentText(await reader.cancel()throw new Error("This file is too large to preview")}- content += decoder.decode(value, { stream: true })+ chunks.push(value)}- return content + decoder.decode()+ const bytes = new Uint8Array(byteLength)+ let offset = 0+ for (const chunk of chunks) {+ bytes.set(chunk, offset)+ offset += chunk.byteLength+ }+ return bytes} finally {reader.releaseLock()}@@ -136,7 +168,10 @@ export function AttachmentPreviewSheet({setPreview({ status: "error", content: null, error: "This file type can’t be previewed" })return}- if (selected.sizeBytes !== undefined && selected.sizeBytes > MAX_TEXT_ATTACHMENT_PREVIEW_BYTES) {+ const maxBytes = presentation.previewKind === "pdf"+ ? MAX_PDF_ATTACHMENT_PREVIEW_BYTES+ : MAX_TEXT_ATTACHMENT_PREVIEW_BYTES+ if (selected.sizeBytes !== undefined && selected.sizeBytes > maxBytes) {setPreview({ status: "error", content: null, error: "This file is too large to preview" })return}@@ -145,9 +180,21 @@ export function AttachmentPreviewSheet({let active = truesetPreview({ status: "loading", content: null, error: null })fetch(selected.url, { credentials: "same-origin", signal: controller.signal })- .then((response) => readAttachmentText(response, MAX_TEXT_ATTACHMENT_PREVIEW_BYTES, controller.signal))+ .then(async (response): Promise<PreviewState> => presentation.previewKind === "pdf"+ ? {+ status: "ready",+ kind: "pdf",+ content: await readAttachmentBytes(response, maxBytes, controller.signal),+ error: null,+ }+ : {+ status: "ready",+ kind: "text",+ content: await readAttachmentText(response, maxBytes, controller.signal),+ error: null,+ }).then((content) => {- if (active) setPreview({ status: "ready", content, error: null })+ if (active) setPreview(content)}).catch((error: unknown) => {if (!active || controller.signal.aborted) return@@ -185,7 +232,12 @@ export function AttachmentPreviewSheet({bodyTestId={tid.attachmentPreviewContent}bodyClassName={cn("flex min-h-0 flex-col",- (presentation?.previewKind === "code" || presentation?.previewKind === "text") && "p-0 sm:p-0",+ presentation?.previewKind === "pdf" && "overflow-hidden",+ (+ presentation?.previewKind === "code"+ || presentation?.previewKind === "text"+ || presentation?.previewKind === "pdf"+ ) && "p-0 sm:p-0",)}>{preview.status === "loading" && (@@ -200,12 +252,15 @@ export function AttachmentPreviewSheet({<p className="max-w-72 text-sm text-muted-foreground">{preview.error}</p></div>)}- {preview.status === "ready" && presentation?.previewKind === "markdown" && (+ {preview.status === "ready" && preview.kind === "text" && presentation?.previewKind === "markdown" && (<MessageBody text={preview.content} />)}- {preview.status === "ready" && presentation?.previewKind !== "markdown" && (+ {preview.status === "ready" && preview.kind === "text" && presentation?.previewKind !== "markdown" && (<CodePreview content={preview.content} language={presentation?.shikiLanguage ?? null} />)}+ {preview.status === "ready" && preview.kind === "pdf" && (+ <PdfPreview data={preview.content} />+ )}</CommunitySheet>)}diff --git a/src/web/src/components/community/messages/pdf-preview.test.ts b/src/web/src/components/community/messages/pdf-preview.test.tsnew file mode 100644index 000000000..850a67afa--- /dev/null+++ b/src/web/src/components/community/messages/pdf-preview.test.ts@@ -0,0 +1,310 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"++const pdfMock = vi.hoisted(() => ({+ getDocument: vi.fn(),+ workers: [] as Array<{ destroyed: boolean; destroy: ReturnType<typeof vi.fn> }>,+ workerOptions: { workerSrc: "" },+}))++vi.mock("pdfjs-dist/legacy/build/pdf.mjs", () => ({+ GlobalWorkerOptions: pdfMock.workerOptions,+ PDFWorker: class {+ destroyed = false+ destroy = vi.fn(() => {+ this.destroyed = true+ })++ constructor() {+ pdfMock.workers.push(this)+ }+ },+ getDocument: pdfMock.getDocument,+}))++import {+ MAX_PDF_CANVAS_PIXELS,+ PdfPreview,+ resolvePdfCanvasLayout,+} from "./pdf-preview"++function page(width = 600, height = 800) {+ const renderTask = { promise: Promise.resolve(), cancel: vi.fn() }+ return {+ getViewport: vi.fn(({ scale }: { scale: number }) => ({+ width: width * scale,+ height: height * scale,+ })),+ render: vi.fn(() => renderTask),+ cleanup: vi.fn(),+ renderTask,+ }+}++function documentWithPages(pages: ReturnType<typeof page>[]) {+ return {+ numPages: pages.length,+ getPage: vi.fn((pageNumber: number) => Promise.resolve(pages[pageNumber - 1])),+ }+}++function loadingTask(document: ReturnType<typeof documentWithPages>) {+ return {+ promise: Promise.resolve(document),+ destroy: vi.fn().mockResolvedValue(undefined),+ }+}++async function flush(): Promise<void> {+ await act(async () => {+ await Promise.resolve()+ await Promise.resolve()+ await Promise.resolve()+ await Promise.resolve()+ })+}++function nodeMock(element: React.ReactElement) {+ if (element.type === "div") return { clientWidth: 600 }+ if (element.type === "section") return {}+ if (element.type === "canvas") return { width: 0, height: 0, style: {} }+ return null+}++beforeEach(() => {+ pdfMock.getDocument.mockReset()+ pdfMock.workers.length = 0+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true)+ vi.stubGlobal("window", { devicePixelRatio: 3 })+ vi.stubGlobal("ResizeObserver", class {+ constructor(private callback: () => void) {}+ observe() { this.callback() }+ disconnect() {}+ })+ vi.stubGlobal("IntersectionObserver", class {+ constructor(private callback: (entries: Array<{ isIntersecting: boolean }>) => void) {}+ observe() { this.callback([{ isIntersecting: true }]) }+ disconnect() {}+ })+})++afterEach(() => {+ vi.unstubAllGlobals()+})++describe("resolvePdfCanvasLayout", () => {+ it("fits the page width, caps retina scale, and never exceeds the pixel budget", () => {+ const layout = resolvePdfCanvasLayout(600, 800, 1200, 4)+ expect(layout).toMatchObject({ cssWidth: 1200, cssHeight: 1600 })+ expect(layout.outputScale).toBeLessThan(2)+ expect(layout.pixelWidth * layout.pixelHeight).toBeLessThanOrEqual(MAX_PDF_CANVAS_PIXELS)+ })+})++describe("PdfPreview", () => {+ it("loads owned bytes in one worker and lazily renders every visible page", async () => {+ const pages = [page(), page(800, 600)]+ const document = documentWithPages(pages)+ const task = loadingTask(document)+ pdfMock.getDocument.mockReturnValue(task)+ const data = new Uint8Array([37, 80, 68, 70])+ let renderer: TestRenderer.ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PdfPreview, { data }), {+ createNodeMock: nodeMock,+ })+ })+ await flush()++ expect(pdfMock.workerOptions.workerSrc).toContain("legacy/build/pdf.worker.min.mjs")+ expect(pdfMock.workers).toHaveLength(1)+ expect(pdfMock.getDocument).toHaveBeenCalledOnce()+ const options = pdfMock.getDocument.mock.calls[0]![0]+ expect(options.data).toEqual(data)+ expect(options.data).not.toBe(data)+ expect(options).toMatchObject({+ useSystemFonts: true,+ useWasm: false,+ maxImageSize: MAX_PDF_CANVAS_PIXELS,+ canvasMaxAreaInBytes: MAX_PDF_CANVAS_PIXELS * 4,+ })+ expect(document.getPage).toHaveBeenCalledTimes(2)+ expect(pages.every((value) => value.render.mock.calls.length === 1)).toBe(true)+ expect(renderer!.root.findByProps({ "data-testid": "community-pdf-preview-page-1" })).toBeTruthy()+ expect(renderer!.root.findByProps({ "data-testid": "community-pdf-preview-page-2" })).toBeTruthy()++ await act(async () => renderer!.unmount())+ await flush()+ expect(pages.every((value) => value.renderTask.cancel.mock.calls.length === 1)).toBe(true)+ expect(pages.every((value) => value.cleanup.mock.calls.length === 1)).toBe(true)+ expect(task.destroy).toHaveBeenCalledOnce()+ expect(pdfMock.workers[0]!.destroy).toHaveBeenCalledOnce()+ })++ it("reports document errors without creating page canvases", async () => {+ const error = new Error("password required")+ error.name = "PasswordException"+ const task = {+ promise: Promise.reject(error),+ destroy: vi.fn().mockResolvedValue(undefined),+ }+ pdfMock.getDocument.mockReturnValue(task)+ let renderer: TestRenderer.ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PdfPreview, {+ data: new Uint8Array([1]),+ }), { createNodeMock: nodeMock })+ })+ await flush()++ const alert = renderer!.root.findByProps({ role: "alert" })+ expect(alert.children.join("")).toContain("Password-protected PDFs")+ expect(renderer!.root.findAllByType("canvas")).toHaveLength(0)+ })++ it("reports synchronous setup errors and destroys the standalone worker", async () => {+ pdfMock.getDocument.mockImplementation(() => {+ throw new Error("invalid PDF")+ })+ let renderer: TestRenderer.ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PdfPreview, {+ data: new Uint8Array([1]),+ }), { createNodeMock: nodeMock })+ })++ expect(renderer!.root.findByProps({ role: "alert" }).children.join(""))+ .toContain("Couldn’t render this PDF")+ await act(async () => renderer!.unmount())+ expect(pdfMock.workers[0]!.destroy).toHaveBeenCalledOnce()+ })++ it("renders when observer APIs are unavailable", async () => {+ vi.stubGlobal("ResizeObserver", undefined)+ vi.stubGlobal("IntersectionObserver", undefined)+ const visiblePage = page()+ const document = documentWithPages([visiblePage])+ pdfMock.getDocument.mockReturnValue(loadingTask(document))++ await act(async () => {+ TestRenderer.create(React.createElement(PdfPreview, {+ data: new Uint8Array([1]),+ }), { createNodeMock: nodeMock })+ })+ await flush()++ expect(visiblePage.render).toHaveBeenCalledOnce()+ })++ it("stays idle when layout refs are unavailable", async () => {+ const hiddenPage = page()+ const document = documentWithPages([hiddenPage])+ pdfMock.getDocument.mockReturnValue(loadingTask(document))++ await act(async () => {+ TestRenderer.create(React.createElement(PdfPreview, {+ data: new Uint8Array([1]),+ }))+ })+ await flush()++ expect(document.getPage).not.toHaveBeenCalled()+ })++ it("releases a page that resolves after its render generation closes", async () => {+ let resolvePage!: (value: ReturnType<typeof page>) => void+ const latePage = page()+ const document = {+ numPages: 1,+ getPage: vi.fn(() => new Promise<ReturnType<typeof page>>((resolve) => {+ resolvePage = resolve+ })),+ }+ pdfMock.getDocument.mockReturnValue(loadingTask(document as ReturnType<typeof documentWithPages>))+ let renderer: TestRenderer.ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PdfPreview, {+ data: new Uint8Array([1]),+ }), { createNodeMock: nodeMock })+ })+ await flush()+ await act(async () => renderer!.unmount())+ resolvePage(latePage)+ await flush()++ expect(latePage.cleanup).toHaveBeenCalledOnce()+ expect(latePage.render).not.toHaveBeenCalled()+ })++ it("reports page render failures and tolerates a missing canvas ref", async () => {+ const failedPage = page()+ let rejectRender!: (error: Error) => void+ failedPage.renderTask.promise = new Promise<void>((_resolve, reject) => {+ rejectRender = reject+ })+ const failedDocument = documentWithPages([failedPage])+ pdfMock.getDocument.mockReturnValueOnce(loadingTask(failedDocument))+ let renderer: TestRenderer.ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PdfPreview, {+ data: new Uint8Array([1]),+ }), { createNodeMock: nodeMock })+ })+ await flush()+ rejectRender(new Error("paint failed"))+ await flush()+ expect(renderer!.root.findByProps({ role: "alert" }).children.join(""))+ .toContain("Couldn’t render page 1")+ await act(async () => renderer!.unmount())++ const canvaslessPage = page()+ pdfMock.getDocument.mockReturnValueOnce(loadingTask(documentWithPages([canvaslessPage])))+ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PdfPreview, {+ data: new Uint8Array([2]),+ }), {+ createNodeMock: (element) => element.type === "canvas" ? null : nodeMock(element),+ })+ })+ await flush()+ expect(canvaslessPage.render).not.toHaveBeenCalled()+ })++ it("destroys a replaced loading generation and ignores its late result", async () => {+ let resolveFirst!: (document: ReturnType<typeof documentWithPages>) => void+ const first = {+ promise: new Promise<ReturnType<typeof documentWithPages>>((resolve) => {+ resolveFirst = resolve+ }),+ destroy: vi.fn().mockResolvedValue(undefined),+ }+ const secondPage = page()+ const secondDocument = documentWithPages([secondPage])+ const second = loadingTask(secondDocument)+ pdfMock.getDocument.mockReturnValueOnce(first).mockReturnValueOnce(second)+ let renderer: TestRenderer.ReactTestRenderer++ await act(async () => {+ renderer = TestRenderer.create(React.createElement(PdfPreview, {+ data: new Uint8Array([1]),+ }), { createNodeMock: nodeMock })+ })+ await act(async () => {+ renderer!.update(React.createElement(PdfPreview, { data: new Uint8Array([2]) }))+ })+ await flush()+ expect(first.destroy).toHaveBeenCalledOnce()+ expect(secondDocument.getPage).toHaveBeenCalledOnce()++ resolveFirst(documentWithPages([page(), page()]))+ await flush()+ expect(renderer!.root.findAll((node) => node.props["data-testid"]?.startsWith("community-pdf-preview-page-")))+ .toHaveLength(1)+ })+})diff --git a/src/web/src/components/community/messages/pdf-preview.tsx b/src/web/src/components/community/messages/pdf-preview.tsxnew file mode 100644index 000000000..47f530884--- /dev/null+++ b/src/web/src/components/community/messages/pdf-preview.tsx@@ -0,0 +1,291 @@+"use client"++import { useEffect, useRef, useState } from "react"+import { Loader2 } from "lucide-react"+import {+ getDocument,+ GlobalWorkerOptions,+ PDFWorker,+ type PDFDocumentLoadingTask,+ type PDFDocumentProxy,+ type PDFPageProxy,+ type RenderTask,+} from "pdfjs-dist/legacy/build/pdf.mjs"+import { tid } from "@/lib/community/testids"++export const MAX_PDF_CANVAS_PIXELS = 4_000_000++GlobalWorkerOptions.workerSrc = new URL(+ "pdfjs-dist/legacy/build/pdf.worker.min.mjs",+ import.meta.url,+).toString()++type CanvasLayout = {+ cssWidth: number+ cssHeight: number+ outputScale: number+ pixelWidth: number+ pixelHeight: number+}++export function resolvePdfCanvasLayout(+ pageWidth: number,+ pageHeight: number,+ availableWidth: number,+ devicePixelRatio: number,+): CanvasLayout {+ const safePageWidth = Math.max(1, pageWidth)+ const safePageHeight = Math.max(1, pageHeight)+ const cssWidth = Math.max(1, availableWidth)+ const cssHeight = cssWidth * (safePageHeight / safePageWidth)+ const requestedScale = Math.min(Math.max(devicePixelRatio, 1), 2)+ const boundedScale = Math.sqrt(MAX_PDF_CANVAS_PIXELS / (cssWidth * cssHeight))+ const outputScale = Math.max(0.1, Math.min(requestedScale, boundedScale))++ return {+ cssWidth,+ cssHeight,+ outputScale,+ pixelWidth: Math.max(1, Math.floor(cssWidth * outputScale)),+ pixelHeight: Math.max(1, Math.floor(cssHeight * outputScale)),+ }+}++type DocumentState =+ | { status: "loading"; document: null; error: null }+ | { status: "ready"; document: PDFDocumentProxy; error: null }+ | { status: "error"; document: null; error: string }++function pdfErrorMessage(error: unknown): string {+ if (error instanceof Error && error.name === "PasswordException") {+ return "Password-protected PDFs aren’t supported yet"+ }+ return "Couldn’t render this PDF"+}++function useElementWidth(ref: React.RefObject<HTMLDivElement | null>): number {+ const [width, setWidth] = useState(0)++ useEffect(() => {+ const element = ref.current+ if (!element) return+ const update = () => setWidth(Math.max(1, Math.floor(element.clientWidth)))+ update()+ if (typeof ResizeObserver === "undefined") return+ const observer = new ResizeObserver(update)+ observer.observe(element)+ return () => observer.disconnect()+ }, [ref])++ return width+}++function PdfPage({+ document,+ pageNumber,+ availableWidth,+}: {+ document: PDFDocumentProxy+ pageNumber: number+ availableWidth: number+}) {+ const containerRef = useRef<HTMLElement>(null)+ const canvasRef = useRef<HTMLCanvasElement>(null)+ const [nearby, setNearby] = useState(false)+ const [aspectRatio, setAspectRatio] = useState(8.5 / 11)+ const [status, setStatus] = useState<"idle" | "loading" | "ready" | "error">("idle")++ useEffect(() => {+ const element = containerRef.current+ if (!element) return+ if (typeof IntersectionObserver === "undefined") {+ setNearby(true)+ return+ }+ const observer = new IntersectionObserver(+ ([entry]) => setNearby(entry?.isIntersecting === true),+ { rootMargin: "800px 0px" },+ )+ observer.observe(element)+ return () => observer.disconnect()+ }, [])++ useEffect(() => {+ if (!nearby || availableWidth < 1) return+ let active = true+ let page: PDFPageProxy | null = null+ let renderTask: RenderTask | null = null+ const canvas = canvasRef.current+ setStatus("loading")++ void document.getPage(pageNumber)+ .then(async (nextPage) => {+ if (!active) {+ nextPage.cleanup()+ return+ }+ page = nextPage+ const baseViewport = page.getViewport({ scale: 1 })+ setAspectRatio(baseViewport.width / baseViewport.height)+ const layout = resolvePdfCanvasLayout(+ baseViewport.width,+ baseViewport.height,+ availableWidth,+ window.devicePixelRatio,+ )+ const viewport = page.getViewport({ scale: layout.cssWidth / baseViewport.width })+ if (!canvas) return+ canvas.width = layout.pixelWidth+ canvas.height = layout.pixelHeight+ canvas.style.width = `${layout.cssWidth}px`+ canvas.style.height = `${layout.cssHeight}px`+ renderTask = page.render({+ canvas,+ viewport,+ transform: layout.outputScale === 1+ ? undefined+ : [layout.outputScale, 0, 0, layout.outputScale, 0, 0],+ })+ await renderTask.promise+ if (active) setStatus("ready")+ })+ .catch((error: unknown) => {+ if (active && (!(error instanceof Error) || error.name !== "RenderingCancelledException")) {+ setStatus("error")+ }+ })++ return () => {+ active = false+ renderTask?.cancel()+ page?.cleanup()+ if (canvas) {+ canvas.width = 0+ canvas.height = 0+ }+ }+ }, [availableWidth, document, nearby, pageNumber])++ return (+ <section+ ref={containerRef}+ data-testid={tid.pdfPreviewPage(pageNumber)}+ aria-label={`Page ${pageNumber}`}+ className="relative w-full overflow-hidden rounded-lg bg-background shadow-(--e1)"+ style={{ aspectRatio }}+ >+ {status === "loading" && (+ <div className="absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground">+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />+ Loading page {pageNumber}…+ </div>+ )}+ {status === "error" && (+ <div role="alert" className="absolute inset-0 flex items-center justify-center text-sm text-muted-foreground">+ Couldn’t render page {pageNumber}+ </div>+ )}+ <canvas+ ref={canvasRef}+ aria-label={`Rendered page ${pageNumber}`}+ className={status === "ready" ? "block h-auto w-full" : "invisible block h-auto w-full"}+ />+ </section>+ )+}++function PdfPages({ document }: { document: PDFDocumentProxy }) {+ const pagesRef = useRef<HTMLDivElement>(null)+ const availableWidth = useElementWidth(pagesRef)++ return (+ <div className="p-4">+ <div ref={pagesRef} className="mx-auto flex w-full max-w-5xl flex-col gap-4">+ {Array.from({ length: document.numPages }, (_, index) => (+ <PdfPage+ key={index + 1}+ document={document}+ pageNumber={index + 1}+ availableWidth={availableWidth}+ />+ ))}+ </div>+ </div>+ )+}++export function PdfPreview({ data }: { data: Uint8Array<ArrayBuffer> }) {+ const [state, setState] = useState<DocumentState>({+ status: "loading",+ document: null,+ error: null,+ })++ useEffect(() => {+ let active = true+ const worker = new PDFWorker()+ let loadingTask: PDFDocumentLoadingTask | null = null+ setState({ status: "loading", document: null, error: null })++ try {+ loadingTask = getDocument({+ data: data.slice(),+ worker,+ useSystemFonts: true,+ useWasm: false,+ maxImageSize: MAX_PDF_CANVAS_PIXELS,+ canvasMaxAreaInBytes: MAX_PDF_CANVAS_PIXELS * 4,+ })+ void loadingTask.promise+ .then((document) => {+ if (active) setState({ status: "ready", document, error: null })+ })+ .catch((error: unknown) => {+ if (active) setState({ status: "error", document: null, error: pdfErrorMessage(error) })+ })+ } catch (error) {+ setState({ status: "error", document: null, error: pdfErrorMessage(error) })+ }++ return () => {+ active = false+ if (!loadingTask) {+ worker.destroy()+ return+ }+ void loadingTask.destroy().finally(() => {+ if (!worker.destroyed) worker.destroy()+ })+ }+ }, [data])++ return (+ <div+ data-testid={tid.pdfPreview}+ className="min-h-0 flex-1 overflow-y-auto bg-muted/40 thin-scrollbar"+ >+ {state.status === "loading" && (+ <div+ data-testid={tid.pdfPreviewStatus}+ role="status"+ className="flex min-h-40 items-center justify-center gap-2 text-sm text-muted-foreground"+ >+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />+ Loading PDF…+ </div>+ )}+ {state.status === "error" && (+ <div+ data-testid={tid.pdfPreviewStatus}+ role="alert"+ className="flex min-h-40 items-center justify-center text-sm text-muted-foreground"+ >+ {state.error}+ </div>+ )}+ {state.status === "ready" && (+ <PdfPages document={state.document} />+ )}+ </div>+ )+}diff --git a/src/web/src/lib/community/attachment-presentation.test.ts b/src/web/src/lib/community/attachment-presentation.test.tsindex 6de82cfcd..bb6e38dc2 100644--- a/src/web/src/lib/community/attachment-presentation.test.ts+++ b/src/web/src/lib/community/attachment-presentation.test.ts@@ -14,7 +14,7 @@ const presentation = (describe("resolveAttachmentPresentation", () => {it.each([- ["report.pdf", "application/pdf", presentation("pdf", null)],+ ["report.pdf", "application/pdf", presentation("pdf", "pdf")],["sheet.bin", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", presentation("spreadsheet", null)],["slides.bin", "application/vnd.ms-powerpoint", presentation("presentation", null)],["voice.bin", "audio/mpeg", presentation("audio", null)],@@ -35,6 +35,7 @@ describe("resolveAttachmentPresentation", () => {[".env.local", "", presentation("code", "code", "dotenv")],["Dockerfile", "binary/octet-stream", presentation("code", "code", "dockerfile")],["GNUmakefile", undefined, presentation("code", "code", "makefile")],+ ["report.pdf", "application/octet-stream", presentation("pdf", "pdf")],["deck.pptx", undefined, presentation("presentation", null)],["bundle.zip", "binary/octet-stream", presentation("archive", null)],])("falls back to the filename for generic MIME: %s", (filename, contentType, expected) => {@@ -115,9 +116,9 @@ describe("resolveAttachmentPresentation", () => {it("does not let a misleading filename override a specific MIME", () => {expect(resolveAttachmentPresentation("payload.html", "application/pdf"))- .toEqual(presentation("pdf", null))+ .toEqual(presentation("pdf", "pdf"))expect(resolveAttachmentPresentation("payload.md", "application/pdf"))- .toEqual(presentation("pdf", null))+ .toEqual(presentation("pdf", "pdf"))expect(resolveAttachmentPresentation("payload.ts", "application/x-custom")).toEqual(presentation("unknown", null))})@@ -150,7 +151,7 @@ describe("resolveAttachmentPresentation", () => {it("keeps a specific non-media MIME authoritative over media extensions", () => {expect(resolveAttachmentPresentation("report.mp4", "application/pdf"))- .toEqual(presentation("pdf", null))+ .toEqual(presentation("pdf", "pdf"))expect(resolveAttachmentPresentation("archive.mp3", "application/zip")).toEqual(presentation("archive", null))})diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.tsindex dbac83b57..bf9f9488b 100644--- a/src/web/src/lib/community/attachment-presentation.ts+++ b/src/web/src/lib/community/attachment-presentation.ts@@ -1,4 +1,5 @@export const MAX_TEXT_ATTACHMENT_PREVIEW_BYTES = 1024 * 1024+export const MAX_PDF_ATTACHMENT_PREVIEW_BYTES = 10 * 1024 * 1024export type AttachmentCategory =| "image"@@ -13,7 +14,7 @@ export type AttachmentCategory =| "archive"| "unknown"-type AttachmentPreviewKind = "markdown" | "text" | "code"+type AttachmentPreviewKind = "markdown" | "text" | "code" | "pdf"export type ShikiLanguage =| "bash"@@ -106,7 +107,7 @@ const MIME_PRESENTATIONS: ReadonlyArray<{{ matches: (type) => ["application/x-terraform", "text/x-hcl"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "hcl" } },{ matches: (type) => ["text/x-diff", "text/x-patch"].includes(type), presentation: { category: "code", previewKind: "code", shikiLanguage: "diff" } },{ matches: (type) => type === "text/x-log", presentation: { category: "code", previewKind: "code", shikiLanguage: "log" } },- { matches: (type) => type === "application/pdf", presentation: { category: "pdf", previewKind: null, shikiLanguage: null } },+ { matches: (type) => type === "application/pdf", presentation: { category: "pdf", previewKind: "pdf", shikiLanguage: null } },{ matches: (type) => type.includes("spreadsheet") || type.includes("excel") || type === "text/csv" || type === "text/tab-separated-values", presentation: { category: "spreadsheet", previewKind: null, shikiLanguage: null } },{ matches: (type) => type.includes("presentation") || type.includes("powerpoint"), presentation: { category: "presentation", previewKind: null, shikiLanguage: null } },{ matches: (type) => type.includes("wordprocessing") || type === "application/msword" || type === "application/rtf", presentation: { category: "document", previewKind: null, shikiLanguage: null } },@@ -185,7 +186,7 @@ const EXTENSION_PRESENTATIONS: Readonly<Record<string, AttachmentPresentation>>htm: code("html"),svg: code("xml"),mdx: code("mdx"),- pdf: { category: "pdf", previewKind: null, shikiLanguage: null },+ pdf: { category: "pdf", previewKind: "pdf", shikiLanguage: null },doc: { category: "document", previewKind: null, shikiLanguage: null },docx: { category: "document", previewKind: null, shikiLanguage: null },rtf: { category: "document", previewKind: null, shikiLanguage: null },diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.tsindex dc7ce21e7..e5dc29fd4 100644--- a/src/web/src/lib/community/testids.test.ts+++ b/src/web/src/lib/community/testids.test.ts@@ -88,6 +88,9 @@ describe("community QA selectors", () => {expect(tid.attachmentPreviewSheet).toBe("community-attachment-preview-sheet")expect(tid.attachmentPreviewDownload).toBe("community-attachment-preview-download")expect(tid.attachmentPreviewContent).toBe("community-attachment-preview-content")+ expect(tid.pdfPreview).toBe("community-pdf-preview")+ expect(tid.pdfPreviewStatus).toBe("community-pdf-preview-status")+ expect(tid.pdfPreviewPage(2)).toBe("community-pdf-preview-page-2")expect(tid.mediaBlock("clip.mp4")).toBe("community-media-block-clip.mp4")expect(tid.mediaPlay("clip.mp4")).toBe("community-media-play-clip.mp4")expect(tid.mediaPlayer("clip.mp4")).toBe("community-media-player-clip.mp4")diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 44dcdb633..597b53bc3 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -115,6 +115,9 @@ export const tid = {attachmentPreviewSheet: "community-attachment-preview-sheet",attachmentPreviewDownload: "community-attachment-preview-download",attachmentPreviewContent: "community-attachment-preview-content",+ pdfPreview: "community-pdf-preview",+ pdfPreviewStatus: "community-pdf-preview-status",+ pdfPreviewPage: (pageNumber: number) => `community-pdf-preview-page-${pageNumber}`,mediaBlock: (name: string) => `community-media-block-${name}`,mediaPlay: (name: string) => `community-media-play-${name}`,mediaPlayer: (name: string) => `community-media-player-${name}`,diff --git a/src/web/src/test/architecture/community-pdf-preview-boundary.test.ts b/src/web/src/test/architecture/community-pdf-preview-boundary.test.tsnew file mode 100644index 000000000..58ea11574--- /dev/null+++ b/src/web/src/test/architecture/community-pdf-preview-boundary.test.ts@@ -0,0 +1,49 @@+import { readdirSync, readFileSync } from "node:fs"+import { relative, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import { describe, expect, it } from "vitest"++const repositoryRoot = fileURLToPath(new URL("../../../../../", import.meta.url))+const webSourceRoot = resolve(repositoryRoot, "src/web/src")++function walkTypeScript(directory: string, files: string[] = []): string[] {+ for (const entry of readdirSync(directory, { withFileTypes: true })) {+ const path = resolve(directory, entry.name)+ if (entry.isDirectory()) walkTypeScript(path, files)+ else if (/\.tsx?$/.test(entry.name)) files.push(path)+ }+ return files+}++function source(path: string): string {+ return readFileSync(resolve(repositoryRoot, path), "utf8")+}++describe("community PDF preview boundary", () => {+ it("keeps PDF.js owned by one client-only lazy module", () => {+ const productionOwners = walkTypeScript(webSourceRoot)+ .filter((path) => !path.includes("/test/") && !path.endsWith(".test.ts") && !path.endsWith(".test.tsx"))+ .filter((path) => /from "pdfjs-dist(?:\/[^"\n]+)?"/.test(readFileSync(path, "utf8")))+ .map((path) => relative(repositoryRoot, path).replaceAll("\\", "/"))++ expect(productionOwners).toEqual([+ "src/web/src/components/community/messages/pdf-preview.tsx",+ ])+ const sheet = source("src/web/src/components/community/messages/attachment-preview-sheet.tsx")+ expect(sheet).toContain('import("./pdf-preview")')+ expect(sheet).toContain("ssr: false")+ expect(sheet).not.toContain('from "pdfjs-dist"')+ const preview = source("src/web/src/components/community/messages/pdf-preview.tsx")+ expect(preview).toContain('from "pdfjs-dist/legacy/build/pdf.mjs"')+ })++ it("keeps the PDF worker lazy and cleanup generation-owned", () => {+ const preview = source("src/web/src/components/community/messages/pdf-preview.tsx")+ expect(preview).toContain('"pdfjs-dist/legacy/build/pdf.worker.min.mjs"')+ expect(preview).toContain("data: data.slice()")+ expect(preview).toContain("renderTask?.cancel()")+ expect(preview).toContain("page?.cleanup()")+ expect(preview).toContain("loadingTask.destroy()")+ expect(preview).toContain("worker.destroy()")+ })+})