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): add progressive media attachment playback (#464)
Gener7f5c8a64f94f
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 ce72878c3..39accdd57 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@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"import { NextRequest } from "next/server"const mockR2Get = vi.fn()+const mockR2Head = vi.fn()vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))const mockGetAttachmentById = vi.fn()@@ -53,7 +54,16 @@ vi.mock("@/lib/middleware/community-actor", async () => {(authz.startsWith("Bearer crk_")? { kind: "bot", userId: "bot_1", ownerUserId: "o_1", machineId: "m_1" }: { kind: "human", userId: "u1", email: "[email protected]", isBot: false })- return handler(req, { env: { COMMUNITY_MEDIA: { get: (...a: unknown[]) => mockR2Get(...a) } }, actor, params })+ return handler(req, {+ env: {+ COMMUNITY_MEDIA: {+ get: (...a: unknown[]) => mockR2Get(...a),+ head: (...a: unknown[]) => mockR2Head(...a),+ },+ },+ actor,+ params,+ })},}})@@ -86,14 +96,21 @@ const persistedRow = (over: Record<string, unknown> = {}) => ({...over,})-const r2Object = (over: Record<string, unknown> = {}) => ({- body: new ReadableStream(),+const r2Object = (over: Record<string, unknown> = {}, bytes = new Uint8Array(10)) => ({+ body: new Response(bytes).body,size: 10,httpMetadata: {},- arrayBuffer: async () => new ArrayBuffer(10),+ arrayBuffer: async () => bytes.slice().buffer,...over,})+function allowPersistedHuman(row = persistedRow()): void {+ mockGetAttachmentById.mockResolvedValue(row)+ mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "c_real" })+ mockGetChannelType.mockResolvedValue("text")+ mockRequireChannelMember.mockResolvedValue({ ok: true, value: {} })+}+describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {beforeEach(() => {vi.clearAllMocks()@@ -152,6 +169,25 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {expect(res.headers.get("Cache-Control")).toBeNull()})+ it("bot: ignores Range and preserves the full-download protocol", async () => {+ const bytes = Uint8Array.from({ length: 10 }, (_, index) => index)+ mockGetAttachmentById.mockResolvedValue(persistedRow({+ messageId: null,+ uploaderId: "bot_1",+ filename: "clip.mp4",+ contentType: "video/mp4",+ }))+ mockR2Get.mockResolvedValue(r2Object({}, bytes))++ const res = await GET(req({ Authorization: "Bearer crk_abc", Range: "bytes=2-4" }), ctx())++ expect(res.status).toBe(200)+ expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png")+ expect(res.headers.get("X-Alook-Filename")).toBe(encodeURIComponent("clip.mp4"))+ expect(res.headers.get("Content-Range")).toBeNull()+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes)+ })+it("bot: percent-encodes non-ASCII filenames per RFC 5987", async () => {mockGetAttachmentById.mockResolvedValue(persistedRow({ messageId: null, uploaderId: "bot_1", filename: "图表.png" }))mockR2Get.mockResolvedValue(r2Object())@@ -187,6 +223,122 @@ describe("GET /api/community/channels/[id]/attachments/[attachmentId]", () => {expect(res.headers.get("Content-Disposition")).toBe('attachment; filename="doc.pdf"')})+ it("human: full media GET is inline, byte-exact, and range-capable", async () => {+ const bytes = Uint8Array.from({ length: 10 }, (_, index) => index)+ allowPersistedHuman(persistedRow({+ filename: "clip.mp4",+ contentType: "video/mp4",+ size: bytes.byteLength,+ }))+ mockR2Get.mockResolvedValue(r2Object({}, bytes))++ const res = await GET(req(), ctx())++ expect(res.status).toBe(200)+ expect(res.headers.get("Content-Type")).toBe("video/mp4")+ expect(res.headers.get("Content-Disposition")).toBe("inline")+ expect(res.headers.get("Accept-Ranges")).toBe("bytes")+ expect(res.headers.get("Content-Length")).toBe("10")+ expect(res.headers.get("Content-Range")).toBeNull()+ expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable")+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes)+ })++ it("human: generic-MIME media fallback emits a browser-playable Content-Type", async () => {+ allowPersistedHuman(persistedRow({+ filename: "voice.m4a",+ contentType: "application/octet-stream",+ }))+ mockR2Get.mockResolvedValue(r2Object())++ const res = await GET(req(), ctx())++ expect(res.status).toBe(200)+ expect(res.headers.get("Content-Type")).toBe("audio/mp4")+ expect(res.headers.get("Content-Disposition")).toBe("inline")+ expect(res.headers.get("Accept-Ranges")).toBe("bytes")+ })++ it.each([+ ["bytes=2-5", 2, 4, "bytes 2-5/10"],+ ["bytes=6-", 6, 4, "bytes 6-9/10"],+ ["bytes=-3", 7, 3, "bytes 7-9/10"],+ ["bytes=8-99", 8, 2, "bytes 8-9/10"],+ ])("human: %s returns an exact 206 R2 slice", async (range, offset, length, contentRange) => {+ const bytes = Uint8Array.from({ length: 10 }, (_, index) => index)+ allowPersistedHuman(persistedRow({ filename: "clip.webm", contentType: "video/webm", size: 10 }))+ mockR2Get.mockImplementation(async (_key: string, options?: R2GetOptions) => {+ const requested = options?.range as { offset: number; length: number }+ return r2Object({}, bytes.slice(requested.offset, requested.offset + requested.length))+ })++ const res = await GET(req({ Range: range }), ctx())++ expect(res.status).toBe(206)+ expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png", { range: { offset, length } })+ expect(res.headers.get("Content-Range")).toBe(contentRange)+ expect(res.headers.get("Content-Length")).toBe(String(length))+ expect(res.headers.get("Accept-Ranges")).toBe("bytes")+ expect(res.headers.get("Content-Disposition")).toBe("inline")+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes.slice(offset, offset + length))+ })++ it.each([+ "bytes=",+ "bytes=-0",+ "bytes=5-4",+ "bytes=10-",+ "bytes=0-1,3-4",+ "items=0-1",+ "bytes=one-two",+ ])("human: malformed or unsatisfiable media range %s returns 416 without an object read", async (range) => {+ allowPersistedHuman(persistedRow({ filename: "clip.mp4", contentType: "video/mp4", size: 10 }))++ const res = await GET(req({ Range: range }), ctx())++ expect(res.status).toBe(416)+ expect(res.headers.get("Content-Range")).toBe("bytes */10")+ expect(res.headers.get("Accept-Ranges")).toBe("bytes")+ expect(mockR2Get).not.toHaveBeenCalled()+ })++ it("human: falls back to R2 HEAD for a legacy media row without size", async () => {+ const bytes = Uint8Array.from({ length: 10 }, (_, index) => index)+ allowPersistedHuman(persistedRow({ filename: "clip.mov", contentType: "video/quicktime", size: null }))+ mockR2Head.mockResolvedValue({ size: 10 })+ mockR2Get.mockResolvedValue(r2Object({}, bytes.slice(4, 7)))++ const res = await GET(req({ Range: "bytes=4-6" }), ctx())++ expect(mockR2Head).toHaveBeenCalledWith("channel/c_row/uuid/a.png")+ expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png", { range: { offset: 4, length: 3 } })+ expect(res.status).toBe(206)+ expect(res.headers.get("Content-Range")).toBe("bytes 4-6/10")+ })++ it("human: ranged media returns 502 when the authorized R2 object is missing", async () => {+ allowPersistedHuman(persistedRow({ filename: "clip.mp4", contentType: "video/mp4", size: 10 }))+ mockR2Get.mockResolvedValue(null)++ const res = await GET(req({ Range: "bytes=0-2" }), ctx())++ expect(res.status).toBe(502)+ expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png", { range: { offset: 0, length: 3 } })+ })++ it("human: Range on non-media keeps the existing full attachment response", async () => {+ allowPersistedHuman(persistedRow({ filename: "doc.pdf", contentType: "application/pdf" }))+ mockR2Get.mockResolvedValue(r2Object({ httpMetadata: { contentType: "application/pdf" } }))++ const res = await GET(req({ Range: "bytes=2-4" }), ctx())++ expect(res.status).toBe(200)+ expect(res.headers.get("Content-Disposition")).toBe('attachment; filename="doc.pdf"')+ expect(res.headers.get("Accept-Ranges")).toBeNull()+ expect(res.headers.get("Content-Range")).toBeNull()+ expect(mockR2Get).toHaveBeenCalledWith("channel/c_row/uuid/a.png")+ })+it("routes a DM-scoped row through requireDMAccess (block gate), not requireChannelMember", async () => {mockGetAttachmentById.mockResolvedValue(persistedRow())mockGetMessage.mockResolvedValue({ id: "m_1", channelId: "dm_1" })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 3e72ce2d0..3a9264ef4 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@@ -4,9 +4,33 @@ import { getDb } from "@/lib/db"import { withCommunityActor } from "@/lib/middleware/community-actor"import { authorizeAttachment } from "@/lib/community/attachment-authorization"import { ATTACHMENT_PRIVATE_IMMUTABLE_CACHE } from "@/lib/community/storage"+import { resolveAttachmentPresentation, resolveMediaContentType } from "@/lib/community/attachment-presentation"const log = createLogger({ service: "community-attachments-download" })+type ParsedByteRange = { offset: number; length: number; end: number }++function parseByteRange(value: string, size: number): ParsedByteRange | null {+ if (!Number.isSafeInteger(size) || size <= 0) return null+ const match = /^bytes=(\d*)-(\d*)$/.exec(value)+ if (!match || (!match[1] && !match[2])) return null++ if (!match[1]) {+ const suffix = Number(match[2])+ if (!Number.isSafeInteger(suffix) || suffix <= 0) return null+ const length = Math.min(suffix, size)+ const offset = size - length+ return { offset, length, end: size - 1 }+ }++ const offset = Number(match[1])+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= size) return null+ const requestedEnd = match[2] ? Number(match[2]) : size - 1+ if (!Number.isSafeInteger(requestedEnd) || requestedEnd < offset) return null+ const end = Math.min(requestedEnd, size - 1)+ return { offset, length: end - offset + 1, end }+}+/*** RFC 5987 filename encoding for `X-Alook-Filename`. Percent-encodes* everything outside the RFC 5987 attr-char set. The daemon-side client@@ -24,8 +48,9 @@ function encodeRfc5987(value: string): string {* attachment-download door. Dual-actor (route/disc trunk — folds the bot* `attachmentDownload` verb + the human `media/[...key]` GET's attachment* part):- * - human/web (`<img src>` / link) → cookie session → bytes + inline/attach- * `Content-Disposition` + immutable cache (the media route's serve shape).+ * - human/web (`<img>`, native media, or link) → cookie session → bytes ++ * inline/attach `Content-Disposition` + immutable cache. Audio/video also+ * accept one byte range for native playback and seeking.* - bot/CLI (crk_ bearer) → raw body + `X-Alook-Filename` (RFC 5987), the* shape the daemon `callDownload` buffers and writes to disk.*@@ -59,15 +84,46 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {}const row = authz.row- const obj = await ctx.env.COMMUNITY_MEDIA.get(row.r2Key)+ const storedPresentation = resolveAttachmentPresentation(row.filename, row.contentType)+ const isStoredMedia = storedPresentation.category === "audio" || storedPresentation.category === "video"+ const requestedRange = ctx.actor.kind === "human" && isStoredMedia+ ? req.headers.get("range")+ : null+ let knownSize = row.size+ if (requestedRange && (!Number.isSafeInteger(knownSize) || (knownSize ?? -1) < 0)) {+ const metadata = await ctx.env.COMMUNITY_MEDIA.head(row.r2Key)+ if (!metadata) {+ return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })+ }+ knownSize = metadata.size+ }++ const parsedRange = requestedRange && knownSize !== null+ ? parseByteRange(requestedRange, knownSize)+ : null+ if (requestedRange && !parsedRange) {+ return new Response(null, {+ status: 416,+ headers: {+ "Accept-Ranges": "bytes",+ "Content-Range": `bytes */${knownSize ?? 0}`,+ },+ })+ }++ const obj = parsedRange+ ? await ctx.env.COMMUNITY_MEDIA.get(row.r2Key, {+ range: { offset: parsedRange.offset, length: parsedRange.length },+ })+ : await ctx.env.COMMUNITY_MEDIA.get(row.r2Key)if (!obj) {// Row exists but R2 has no object — infra fault, distinct from the// enumeration-safe 404 above.return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })}- const contentType =- row.contentType || obj.httpMetadata?.contentType || "application/octet-stream"+ const storedContentType = row.contentType || obj.httpMetadata?.contentType || "application/octet-stream"+ const contentType = resolveMediaContentType(row.filename, storedContentType) ?? storedContentTypeif (ctx.actor.kind === "bot") {// Bot arm — raw body + X-Alook-Filename. Buffer inside the try/catch so an@@ -85,17 +141,24 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {return new Response(buffer, { headers })}- // Human arm — inline for images, attachment download otherwise, immutable- // cache (the media route's serve shape). Stream the body directly.const isImage = contentType.startsWith("image/")+ const isMedia = contentType.startsWith("audio/") || contentType.startsWith("video/")+ const size = knownSize ?? row.size ?? obj.size+ const headers: Record<string, string> = {+ "Content-Type": contentType,+ "Content-Disposition": isImage || isMedia+ ? "inline"+ : `attachment; filename="${row.filename}"`,+ "Cache-Control": ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,+ "Content-Length": String(parsedRange?.length ?? size),+ }+ if (isMedia) headers["Accept-Ranges"] = "bytes"+ if (parsedRange) {+ headers["Content-Range"] = `bytes ${parsedRange.offset}-${parsedRange.end}/${size}`+ }return new Response(obj.body, {- headers: {- "Content-Type": contentType,- "Content-Disposition": isImage- ? "inline"- : `attachment; filename="${row.filename}"`,- "Cache-Control": ATTACHMENT_PRIVATE_IMMUTABLE_CACHE,- },+ status: parsedRange ? 206 : 200,+ headers,})} catch (err) {log.error("attachment_route_failure", {diff --git a/src/web/src/components/community/attachment-card.test.ts b/src/web/src/components/community/attachment-card.test.tsindex 32e3fbe6d..ed41d8595 100644--- a/src/web/src/components/community/attachment-card.test.ts+++ b/src/web/src/components/community/attachment-card.test.ts@@ -78,4 +78,39 @@ describe("AttachmentCard", () => {expect(onPreview).toHaveBeenCalledWith(source)expect(onDownload).not.toHaveBeenCalled()})++ it.each([+ ["voice.mp3", "audio/mpeg", "audio"],+ ["clip.webm", "application/octet-stream", "video"],+ ])("delegates %s to the shared %s media block", (name, contentType, mediaKind) => {+ const file = attachment({ name, contentType })+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(AttachmentCard, {+ attachment: file,+ onDownload: vi.fn(),+ }))+ })++ expect(renderer!.root.findByProps({ "data-testid": `community-media-block-${name}` }).props["data-media-kind"])+ .toBe(mediaKind)+ expect(renderer!.root.findAllByProps({ "data-testid": `community-attachment-card-${name}` }))+ .toHaveLength(0)+ })++ it("does not let a media-looking filename override a specific non-media MIME", () => {+ const pdf = attachment({ name: "document.mp4", contentType: "application/pdf" })+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(AttachmentCard, {+ attachment: pdf,+ onDownload: vi.fn(),+ }))+ })++ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-card-document.mp4" }).props["data-attachment-category"])+ .toBe("pdf")+ expect(renderer!.root.findAllByProps({ "data-testid": "community-media-block-document.mp4" }))+ .toHaveLength(0)+ })})diff --git a/src/web/src/components/community/attachment-card.tsx b/src/web/src/components/community/attachment-card.tsxindex f69d58315..83ff68ae2 100644--- a/src/web/src/components/community/attachment-card.tsx+++ b/src/web/src/components/community/attachment-card.tsx@@ -15,6 +15,7 @@ import {Presentation,} from "lucide-react"import type { FileAttachment } from "./_types"+import { MediaAttachmentBlock } from "./media-attachment-block"import { tid } from "@/lib/community/testids"import {resolveAttachmentPresentation,@@ -45,6 +46,15 @@ export function AttachmentCard({onDownload?: (url: string, name: string) => void}) {const presentation = resolveAttachmentPresentation(attachment.name, attachment.contentType)+ if (presentation.category === "audio" || presentation.category === "video") {+ return (+ <MediaAttachmentBlock+ attachment={attachment}+ mediaKind={presentation.category}+ onDownload={onDownload}+ />+ )+ }const Icon = CATEGORY_ICONS[presentation.category]const canPreview = presentation.previewKind !== null && !!onPreviewconst ActionIcon = canPreview ? Eye : Downloaddiff --git a/src/web/src/components/community/media-attachment-block.test.ts b/src/web/src/components/community/media-attachment-block.test.tsnew file mode 100644index 000000000..3e8d625d1--- /dev/null+++ b/src/web/src/components/community/media-attachment-block.test.ts@@ -0,0 +1,331 @@+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { describe, expect, it, vi } from "vitest"+import { tid } from "@/lib/community/testids"+import type { FileAttachment } from "./_types"+import { MediaAttachmentBlock } from "./media-attachment-block"++vi.mock("@/components/ui/button", () => ({+ Button: ({ children, ...props }: React.ComponentProps<"button">) => React.createElement("button", props, children),+}))++function attachment(overrides: Partial<FileAttachment> = {}): FileAttachment {+ return {+ kind: "file",+ name: "clip.mp4",+ url: "/attachments/video-1",+ contentType: "video/mp4",+ sizeBytes: 256,+ size: "256 B",+ ...overrides,+ }+}++function renderMedia({+ item = attachment(),+ mediaKind = "video",+ onDownload,+ play = vi.fn().mockResolvedValue(undefined),+ readyState = 4,+}: {+ item?: FileAttachment+ mediaKind?: "audio" | "video"+ onDownload?: (url: string, name: string) => void+ play?: ReturnType<typeof vi.fn>+ readyState?: number+} = {}) {+ let currentTime = readyState === 0 ? 0 : 12+ const seek = vi.fn((value: number) => { currentTime = value })+ const mediaNode = {+ play,+ pause: vi.fn(),+ readyState,+ get currentTime() { return currentTime },+ set currentTime(value: number) { seek(value) },+ }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(MediaAttachmentBlock, { attachment: item, mediaKind, onDownload }),+ {+ createNodeMock: (element) => {+ if (element.type !== "audio" && element.type !== "video") return null+ return mediaNode+ },+ },+ )+ })+ return { renderer: renderer!, mediaNode, seek }+}++describe("MediaAttachmentBlock", () => {+ it("keeps video idle without mounting media and exposes a stable play surface", () => {+ const { renderer, mediaNode } = renderMedia()++ expect(renderer.root.findAllByType("video")).toHaveLength(0)+ expect(renderer.root.findAllByType("audio")).toHaveLength(0)+ const play = renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") })+ expect(play.props["aria-label"]).toBe("Play clip.mp4")+ expect(play.parent?.props.className).toContain("aspect-video")+ expect(mediaNode.play).not.toHaveBeenCalled()+ })++ it("plays video on first activation and uses the same custom button for pause and resume", async () => {+ const { renderer, mediaNode } = renderMedia()++ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })++ expect(mediaNode.play).toHaveBeenCalledOnce()+ const player = renderer.root.findByProps({ "data-testid": tid.mediaPlayer("clip.mp4") })+ expect(player.type).toBe("video")+ expect(player.props).toMatchObject({+ src: "/attachments/video-1",+ controls: false,+ playsInline: true,+ preload: "metadata",+ autoPlay: false,+ })++ const pause = renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") })+ expect(pause.props["aria-label"]).toBe("Pause clip.mp4")+ act(() => pause.props.onClick())+ expect(mediaNode.pause).toHaveBeenCalledOnce()+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props["aria-label"])+ .toBe("Play clip.mp4")++ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })+ expect(mediaNode.play).toHaveBeenCalledTimes(2)+ })++ it("keeps the custom button synchronized with native play and pause events", async () => {+ const { renderer } = renderMedia()+ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })+ const player = renderer.root.findByType("video")++ act(() => player.props.onPause())+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props["aria-label"])+ .toBe("Play clip.mp4")+ act(() => player.props.onPlay())+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props["aria-label"])+ .toBe("Pause clip.mp4")+ })++ it("resets on natural completion and replays the retained media element", async () => {+ const { renderer, mediaNode } = renderMedia()+ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })+ const retainedPlayer = renderer.root.findByType("video")++ act(() => renderer.root.findByType("video").props.onEnded())+ expect(mediaNode.pause).not.toHaveBeenCalled()+ expect(mediaNode.currentTime).toBe(0)+ expect(renderer.root.findByType("video")).toBe(retainedPlayer)+ expect(renderer.root.findAllByProps({ "data-testid": tid.mediaCollapse("clip.mp4") })).toHaveLength(0)+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props["aria-label"])+ .toBe("Play clip.mp4")++ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })+ expect(renderer.root.findAllByType("video")).toHaveLength(1)+ expect(renderer.root.findByType("video")).toBe(retainedPlayer)+ expect(mediaNode.play).toHaveBeenCalledTimes(2)+ })++ it("plays audio without exposing native UI and keeps every mobile action at least 44px", async () => {+ const audio = attachment({+ name: "voice.ogg",+ url: "/attachments/audio-1",+ contentType: "audio/ogg",+ })+ const { renderer, mediaNode } = renderMedia({ item: audio, mediaKind: "audio" })++ const play = renderer.root.findByProps({ "data-testid": tid.mediaPlay("voice.ogg") })+ expect(play.props.className).toContain("size-11")+ expect(play.props.className).toContain("text-muted-foreground")+ expect(play.props.className).toContain("hover:text-foreground")+ expect(play.props.className).toContain("focus-visible:text-foreground")+ await act(async () => {+ play.props.onClick()+ await Promise.resolve()+ })++ expect(mediaNode.play).toHaveBeenCalledOnce()+ const player = renderer.root.findByProps({ "data-testid": tid.mediaPlayer("voice.ogg") })+ expect(player.type).toBe("audio")+ expect(player.props).toMatchObject({ controls: false, preload: "metadata", autoPlay: false, className: "hidden" })+ expect(player.props.playsInline).toBeUndefined()+ expect(renderer.root.findByProps({ "data-testid": tid.mediaCollapse("voice.ogg") }).props.className)+ .toContain("size-11")+ expect(renderer.root.findByProps({ "data-testid": tid.mediaCollapse("voice.ogg") }).props["aria-label"])+ .toBe("Stop playback voice.ogg")+ expect(renderer.root.findByProps({ "data-testid": tid.mediaDownload("voice.ogg") }).props.className)+ .toContain("size-11")+ })++ it("keeps audio loading feedback inside the existing play button without adding row height", () => {+ const pendingPlay = new Promise<void>(() => {})+ const audio = attachment({ name: "voice.ogg", contentType: "audio/ogg" })+ const { renderer } = renderMedia({ item: audio, mediaKind: "audio", play: vi.fn(() => pendingPlay) })++ const idleStopSlot = renderer.root.findByProps({ "data-media-stop-slot": true })+ expect(idleStopSlot.props.className).toContain("size-11")+ expect(idleStopSlot.props.className).toContain("sm:size-8")+ act(() => renderer.root.findByProps({ "data-testid": tid.mediaPlay("voice.ogg") }).props.onClick())+ const loadingButton = renderer.root.findByProps({ "data-testid": tid.mediaPlay("voice.ogg") })+ expect(loadingButton.props["aria-label"]).toBe("Loading voice.ogg")+ expect(loadingButton.props["aria-busy"]).toBe(true)+ expect(loadingButton.props.disabled).toBe(true)+ const status = renderer.root.findByProps({ "data-testid": tid.mediaStatus("voice.ogg") })+ expect(status.props.className).toBe("sr-only")+ expect(status.parent?.type).toBe("button")+ expect(status.parent?.props["data-testid"]).toBe(tid.mediaPlay("voice.ogg"))+ expect(renderer.root.findAll((node) => node.type === "p" && node.props.role === "status")).toHaveLength(0)+ expect(renderer.root.findAllByProps({ "data-media-stop-slot": true })).toHaveLength(0)+ expect(renderer.root.findByProps({ "data-testid": tid.mediaCollapse("voice.ogg") }).props.className)+ .toContain("size-11")+ })++ it("stops at the beginning and retains the loaded media element", async () => {+ const { renderer, mediaNode, seek } = renderMedia()+ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })++ const retainedPlayer = renderer.root.findByType("video")+ const stop = renderer.root.findByProps({ "data-testid": tid.mediaCollapse("clip.mp4") })+ expect(stop.props["aria-label"]).toBe("Stop playback clip.mp4")+ expect(stop.props.className).toContain("size-11")+ expect(stop.props.className).toContain("sm:size-8")+ expect(stop.parent?.props.className).toContain("bottom-2 left-2 flex gap-2")+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).parent).toBe(stop.parent)+ act(() => stop.props.onClick())+ expect(mediaNode.pause).toHaveBeenCalledOnce()+ expect(mediaNode.currentTime).toBe(0)+ expect(seek).toHaveBeenCalledWith(0)+ expect(renderer.root.findByType("video")).toBe(retainedPlayer)+ expect(renderer.root.findAllByProps({ "data-testid": tid.mediaCollapse("clip.mp4") })).toHaveLength(0)+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props["aria-label"])+ .toBe("Play clip.mp4")++ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })+ expect(renderer.root.findByType("video")).toBe(retainedPlayer)+ expect(mediaNode.play).toHaveBeenCalledTimes(2)+ })++ it("stops safely before metadata exists without attempting an invalid seek", async () => {+ let rejectPlay!: (error: unknown) => void+ const pendingPlay = new Promise<void>((_resolve, reject) => { rejectPlay = reject })+ const play = vi.fn(() => pendingPlay)+ const { renderer, mediaNode, seek } = renderMedia({ readyState: 0, play })+ act(() => renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick())++ act(() => renderer.root.findByProps({ "data-testid": tid.mediaCollapse("clip.mp4") }).props.onClick())+ expect(mediaNode.pause).toHaveBeenCalledOnce()+ expect(seek).not.toHaveBeenCalled()+ expect(mediaNode.currentTime).toBe(0)+ expect(renderer.root.findByType("video")).toBeDefined()+ expect(renderer.root.findAllByProps({ "data-testid": tid.mediaRetry("clip.mp4") })).toHaveLength(0)+ expect(renderer.root.findAllByProps({ "data-testid": tid.mediaCollapse("clip.mp4") })).toHaveLength(0)+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props["aria-label"])+ .toBe("Play clip.mp4")++ await act(async () => {+ rejectPlay(Object.assign(new Error("play interrupted"), { name: "AbortError" }))+ await Promise.resolve()+ })+ expect(renderer.root.findAllByProps({ "data-testid": tid.mediaRetry("clip.mp4") })).toHaveLength(0)+ expect(renderer.root.findByType("video")).toBeDefined()+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props["aria-label"])+ .toBe("Play clip.mp4")+ })++ it("shows blocked-play feedback and lets the custom button try again", async () => {+ const blocked = Object.assign(new Error("blocked"), { name: "NotAllowedError" })+ const play = vi.fn().mockRejectedValueOnce(blocked).mockResolvedValueOnce(undefined)+ const { renderer } = renderMedia({ play })++ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })+ expect(renderer.root.findByProps({ "data-testid": tid.mediaStatus("clip.mp4") }).children)+ .toEqual(["Playback was blocked — try again"])+ expect(renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props["aria-label"])+ .toBe("Try playing clip.mp4")++ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })+ expect(play).toHaveBeenCalledTimes(2)+ expect(renderer.root.findAllByProps({ "data-testid": tid.mediaStatus("clip.mp4") })).toHaveLength(0)+ })++ it("shows codec errors and retry remounts and immediately plays", async () => {+ const { renderer, mediaNode } = renderMedia()+ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("clip.mp4") }).props.onClick()+ await Promise.resolve()+ })+ act(() => renderer.root.findByType("video").props.onError())++ expect(renderer.root.findAllByType("video")).toHaveLength(0)+ expect(renderer.root.findByProps({ "data-testid": tid.mediaStatus("clip.mp4") }).children)+ .toEqual(["Couldn’t play this file"])+ const retry = renderer.root.findByProps({ "data-testid": tid.mediaRetry("clip.mp4") })+ expect(retry.props["aria-label"]).toBe("Retry clip.mp4")+ await act(async () => {+ retry.props.onClick()+ await Promise.resolve()+ })+ expect(renderer.root.findAllByType("video")).toHaveLength(1)+ expect(mediaNode.play).toHaveBeenCalledTimes(2)+ })++ it("keeps audio retry reachable after a playback error", async () => {+ const audio = attachment({ name: "voice.mp3", contentType: "audio/mpeg" })+ const { renderer, mediaNode } = renderMedia({ item: audio, mediaKind: "audio" })+ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaPlay("voice.mp3") }).props.onClick()+ await Promise.resolve()+ })+ act(() => renderer.root.findByType("audio").props.onError())+ expect(renderer.root.findAllByType("audio")).toHaveLength(0)++ await act(async () => {+ renderer.root.findByProps({ "data-testid": tid.mediaRetry("voice.mp3") }).props.onClick()+ await Promise.resolve()+ })+ expect(renderer.root.findAllByType("audio")).toHaveLength(1)+ expect(mediaNode.play).toHaveBeenCalledTimes(2)+ })++ it("downloads the original file without activating playback", () => {+ const onDownload = vi.fn()+ const stopPropagation = vi.fn()+ const { renderer, mediaNode } = renderMedia({ onDownload })++ act(() => renderer.root.findByProps({ "data-testid": tid.mediaDownload("clip.mp4") }).props.onClick({ stopPropagation }))+ expect(stopPropagation).toHaveBeenCalledOnce()+ expect(onDownload).toHaveBeenCalledWith("/attachments/video-1", "clip.mp4")+ expect(mediaNode.play).not.toHaveBeenCalled()+ expect(renderer.root.findAllByType("video")).toHaveLength(0)+ })+})diff --git a/src/web/src/components/community/media-attachment-block.tsx b/src/web/src/components/community/media-attachment-block.tsxnew file mode 100644index 000000000..68036c187--- /dev/null+++ b/src/web/src/components/community/media-attachment-block.tsx@@ -0,0 +1,284 @@+"use client"++import { useRef, useState, type MouseEvent } from "react"+import { flushSync } from "react-dom"+import { Download, FileAudio, FileVideo, LoaderCircle, Pause, Play, RefreshCw, Square } from "lucide-react"+import { Button } from "@/components/ui/button"+import { tid } from "@/lib/community/testids"+import type { FileAttachment } from "./_types"++type MediaKind = "audio" | "video"+type MediaStatus = "idle" | "loading" | "ready" | "blocked" | "error"++export function MediaAttachmentBlock({+ attachment,+ mediaKind,+ onDownload,+}: {+ attachment: FileAttachment+ mediaKind: MediaKind+ onDownload?: (url: string, name: string) => void+}) {+ const [mounted, setMounted] = useState(false)+ const [status, setStatus] = useState<MediaStatus>("idle")+ const [isPlaying, setIsPlaying] = useState(false)+ const [playerKey, setPlayerKey] = useState(0)+ const playerRef = useRef<HTMLMediaElement>(null)+ const playOnMountRef = useRef(false)+ const playbackAttemptRef = useRef(0)+ const playbackActiveRef = useRef(false)+ const MediaIcon = mediaKind === "video" ? FileVideo : FileAudio++ function playPlayer(player: HTMLMediaElement): void {+ const attempt = playbackAttemptRef.current + 1+ playbackAttemptRef.current = attempt+ playbackActiveRef.current = true+ setIsPlaying(true)+ setStatus((value) => value === "ready" ? value : "loading")+ void player.play().then(() => {+ if (playerRef.current === player && playbackAttemptRef.current === attempt) setStatus("ready")+ }).catch((error: unknown) => {+ if (playerRef.current !== player || playbackAttemptRef.current !== attempt) return+ playbackActiveRef.current = false+ setIsPlaying(false)+ setStatus(+ typeof error === "object" && error !== null && "name" in error && error.name === "NotAllowedError"+ ? "blocked"+ : "error",+ )+ })+ }++ function togglePlayback(): void {+ const player = playerRef.current+ if (!player) {+ playOnMountRef.current = true+ flushSync(() => {+ setStatus("loading")+ setMounted(true)+ })+ return+ }+ if (isPlaying) {+ player.pause()+ setIsPlaying(false)+ return+ }+ playPlayer(player)+ }++ function stopPlayer(): void {+ playOnMountRef.current = false+ playbackAttemptRef.current += 1+ playbackActiveRef.current = false+ const player = playerRef.current+ if (player) {+ player.pause()+ if (player.readyState > 0) player.currentTime = 0+ }+ setStatus("idle")+ setIsPlaying(false)+ }++ function finishPlayer(): void {+ playbackAttemptRef.current += 1+ playbackActiveRef.current = false+ const player = playerRef.current+ if (player && player.readyState > 0) player.currentTime = 0+ setStatus("idle")+ setIsPlaying(false)+ }++ function retryPlayer(): void {+ playOnMountRef.current = true+ flushSync(() => {+ setPlayerKey((value) => value + 1)+ setStatus("loading")+ setMounted(true)+ })+ }++ function download(event: MouseEvent<HTMLButtonElement>): void {+ event.stopPropagation()+ onDownload?.(attachment.url, attachment.name)+ }++ const playerProps = {+ "data-testid": tid.mediaPlayer(attachment.name),+ src: attachment.url,+ controls: false,+ preload: "metadata" as const,+ autoPlay: false,+ ref: (player: HTMLMediaElement | null) => {+ playerRef.current = player+ if (!player || !playOnMountRef.current) return+ playOnMountRef.current = false+ playPlayer(player)+ },+ onPlay: () => setIsPlaying(true),+ onPause: () => setIsPlaying(false),+ onEnded: finishPlayer,+ onError: () => {+ if (!playbackActiveRef.current) return+ playbackActiveRef.current = false+ setIsPlaying(false)+ setStatus("error")+ },+ }++ const playbackLabel = `${isPlaying ? "Pause" : status === "blocked" ? "Try playing" : "Play"} ${attachment.name}`++ return (+ <article+ data-testid={tid.mediaBlock(attachment.name)}+ data-media-kind={mediaKind}+ className="w-full max-w-100 overflow-hidden rounded-lg border border-border bg-card text-card-foreground"+ >+ {mediaKind === "video" && (+ <div className="relative aspect-video bg-muted/40">+ {mounted && status !== "error" ? (+ <video key={playerKey} {...playerProps} playsInline className="size-full object-contain" />+ ) : (+ <button+ data-testid={status === "error" ? tid.mediaRetry(attachment.name) : tid.mediaPlay(attachment.name)}+ type="button"+ onClick={status === "error" ? retryPlayer : togglePlayback}+ className="flex size-full flex-col items-center justify-center gap-2 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:outline-none"+ aria-label={`${status === "error" ? "Retry" : "Play"} ${attachment.name}`}+ >+ {status === "error" ? <RefreshCw className="size-7" /> : <Play className="size-8" />}+ <span className="text-xs font-medium">{status === "error" ? "Retry playback" : "Play video"}</span>+ </button>+ )}+ {mounted && status !== "error" && (+ <div className="absolute bottom-2 left-2 flex gap-2">+ <Button+ data-testid={tid.mediaPlay(attachment.name)}+ type="button"+ variant="secondary"+ size="icon-sm"+ className="size-11 sm:size-8"+ onClick={togglePlayback}+ aria-label={playbackLabel}+ >+ {isPlaying ? <Pause className="size-4" /> : <Play className="size-4" />}+ </Button>+ {status !== "idle" && (+ <Button+ data-testid={tid.mediaCollapse(attachment.name)}+ type="button"+ variant="secondary"+ size="icon-sm"+ className="size-11 sm:size-8"+ onClick={stopPlayer}+ aria-label={`Stop playback ${attachment.name}`}+ >+ <Square className="size-4" />+ </Button>+ )}+ </div>+ )}+ {mounted && status === "loading" && (+ <span+ data-testid={tid.mediaStatus(attachment.name)}+ role="status"+ className="absolute top-2 left-2 rounded-md bg-background/90 px-2 py-1 text-xs text-muted-foreground"+ >+ Loading media…+ </span>+ )}+ </div>+ )}++ <div className="flex min-h-14 items-center gap-3 px-3 py-2">+ <MediaIcon className="size-6 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium text-foreground">{attachment.name}</div>+ <div className="text-xs text-muted-foreground">+ {[mediaKind === "video" ? "Video" : "Audio", attachment.size].filter(Boolean).join(" · ")}+ </div>+ {status === "error" && (+ <p data-testid={tid.mediaStatus(attachment.name)} role="alert" className="text-xs text-muted-foreground">+ Couldn’t play this file+ </p>+ )}+ {status === "blocked" && (+ <p data-testid={tid.mediaStatus(attachment.name)} role="alert" className="text-xs text-muted-foreground">+ Playback was blocked — try again+ </p>+ )}+ </div>+ {mediaKind === "audio" && status !== "error" && (+ <Button+ data-testid={tid.mediaPlay(attachment.name)}+ type="button"+ variant="ghost"+ size="icon-sm"+ className="size-11 text-muted-foreground hover:text-foreground focus-visible:text-foreground sm:size-8"+ onClick={togglePlayback}+ aria-label={status === "loading" ? `Loading ${attachment.name}` : playbackLabel}+ aria-busy={status === "loading"}+ disabled={status === "loading"}+ >+ {status === "loading" ? (+ <>+ <LoaderCircle className="size-4 animate-spin motion-reduce:animate-none" />+ <span data-testid={tid.mediaStatus(attachment.name)} role="status" className="sr-only">+ Loading media…+ </span>+ </>+ ) : isPlaying ? <Pause className="size-4" /> : <Play className="size-4" />}+ </Button>+ )}+ {mediaKind === "audio" && status === "error" && (+ <Button+ data-testid={tid.mediaRetry(attachment.name)}+ type="button"+ variant="ghost"+ size="icon-sm"+ className="size-11 text-muted-foreground hover:text-foreground focus-visible:text-foreground sm:size-8"+ onClick={retryPlayer}+ aria-label={`Retry ${attachment.name}`}+ >+ <RefreshCw className="size-4" />+ </Button>+ )}+ {mediaKind === "audio" && status === "idle" && (+ <span+ data-media-stop-slot+ aria-hidden="true"+ className="size-11 shrink-0 sm:size-8"+ />+ )}+ {mediaKind === "audio" && mounted && status !== "idle" && status !== "error" && (+ <Button+ data-testid={tid.mediaCollapse(attachment.name)}+ type="button"+ variant="ghost"+ size="icon-sm"+ className="size-11 text-muted-foreground hover:text-foreground focus-visible:text-foreground sm:size-8"+ onClick={stopPlayer}+ aria-label={`Stop playback ${attachment.name}`}+ >+ <Square className="size-4" />+ </Button>+ )}+ <Button+ data-testid={tid.mediaDownload(attachment.name)}+ type="button"+ variant="ghost"+ size="icon-sm"+ className="size-11 text-muted-foreground hover:text-foreground focus-visible:text-foreground sm:size-8"+ onClick={download}+ aria-label={`Download ${attachment.name}`}+ >+ <Download className="size-4" />+ </Button>+ </div>++ {mediaKind === "audio" && mounted && status !== "error" && (+ <audio key={playerKey} {...playerProps} className="hidden" />+ )}+ </article>+ )+}diff --git a/src/web/src/components/community/message-body.test.ts b/src/web/src/components/community/message-body.test.tsindex d540c581a..fd1df2567 100644--- a/src/web/src/components/community/message-body.test.ts+++ b/src/web/src/components/community/message-body.test.ts@@ -3,6 +3,23 @@ import React from "react"import TestRenderer, { act } from "react-test-renderer"import { MessageBody } from "./message-body"+describe("MessageBody — theme contrast", () => {+ it("pins body copy to the semantic foreground token", () => {+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(MessageBody, { text: "Readable in both themes" }),+ )+ })++ const body = renderer!.root.find(+ (node) => node.type === "div" && typeof node.props.className === "string"+ && node.props.className.includes("markdown-chat"),+ )+ expect(body.props.className).toContain("text-foreground")+ })+})+// Regression test for the bug MD_LITERAL_TAGS included "spoiler" fixed:// Streamdown's `literalTagContent` flattens every descendant of a listed// tag into one text node. `mention`/`channelref` are leaf nodes so that'sdiff --git a/src/web/src/components/community/message-body.tsx b/src/web/src/components/community/message-body.tsxindex 5d38d0cca..1c4431583 100644--- a/src/web/src/components/community/message-body.tsx+++ b/src/web/src/components/community/message-body.tsx@@ -106,7 +106,7 @@ function MessageBodyImpl({[onOpenProfile],)return (- <div className="markdown markdown-chat wrap-anywhere text-[15px] leading-snug">+ <div className="markdown markdown-chat wrap-anywhere text-[15px] leading-snug text-foreground"><StreamdownparseIncompleteMarkdown={false}plugins={{ mermaid, cjk, math }}diff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/message.render.test.tsindex 0995644b1..e64585a4e 100644--- a/src/web/src/components/community/message.render.test.ts+++ b/src/web/src/components/community/message.render.test.ts@@ -200,6 +200,28 @@ describe("Message file attachment", () => {act(() => card.props.onClick())expect(onPreviewAttachment).toHaveBeenCalledWith(file)})++ it("renders media through the shared progressive-disclosure block", () => {+ const media = {+ kind: "file" as const,+ name: "voice.ogg",+ url: "/voice",+ contentType: "audio/ogg",+ sizeBytes: 256,+ size: "256 B",+ }+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(makeTree({+ m: baseMsg({ attachments: [media] }),+ onOpenThread: vi.fn(),+ }), { createNodeMock: () => genericMock })+ })++ expect(renderer!.root.findByProps({ "data-testid": "community-media-block-voice.ogg" }).props["data-media-kind"])+ .toBe("audio")+ expect(renderer!.root.findAllByType("audio")).toHaveLength(0)+ })})describe("Message lazy overlays", () => {diff --git a/src/web/src/components/community/thread-opener.test.ts b/src/web/src/components/community/thread-opener.test.tsindex b980dafef..cf8cd33fb 100644--- a/src/web/src/components/community/thread-opener.test.ts+++ b/src/web/src/components/community/thread-opener.test.ts@@ -115,4 +115,35 @@ describe("ThreadOpener image attachment layout", () => {act(() => card.props.onClick())expect(onPreviewAttachment).toHaveBeenCalledWith(file)})++ it("renders opener media through the shared progressive-disclosure block", () => {+ const media = {+ kind: "file" as const,+ name: "clip.webm",+ url: "/clip",+ contentType: "video/webm",+ sizeBytes: 512,+ size: "512 B",+ }+ useMessageMock.mockReturnValue({+ isLoading: false,+ isError: false,+ message: {+ id: "opener_1", type: "chat", authorId: "u1", authorName: "Alice",+ content: "Clip", createdAt: "2026-08-08T00:00:00.000Z",+ attachments: [media],+ },+ })+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(ThreadOpener, { parentMessageId: "opener_1" }),+ { createNodeMock: () => genericMock },+ )+ })++ expect(renderer!.root.findByProps({ "data-testid": "community-media-block-clip.webm" }).props["data-media-kind"])+ .toBe("video")+ expect(renderer!.root.findAllByType("video")).toHaveLength(0)+ })})diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.tsindex eb021a3fd..7b8fd5700 100644--- a/src/web/src/hooks/community/mutations/forum.test.ts+++ b/src/web/src/hooks/community/mutations/forum.test.ts@@ -120,6 +120,9 @@ describe("useCreateForumThread", () => {const body = JSON.parse((init as { body: string }).body)expect(body.attachments).toEqual(["att_1"])expect(body.mentionType).toBe("everyone")+ const [, replyInit] = apiFetchMock.mock.calls[1]+ const replyBody = JSON.parse((replyInit as { body: string }).body)+ expect(replyBody.attachments).toEqual(["att_1"])})it("invalidates the composed forum list on success", async () => {diff --git a/src/web/src/lib/community/attachment-presentation.test.ts b/src/web/src/lib/community/attachment-presentation.test.tsindex e3c426ef6..b92391a0b 100644--- a/src/web/src/lib/community/attachment-presentation.test.ts+++ b/src/web/src/lib/community/attachment-presentation.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"import {formatAttachmentSize,resolveAttachmentPresentation,+ resolveMediaContentType,type AttachmentPresentation,} from "./attachment-presentation"@@ -100,6 +101,56 @@ describe("resolveAttachmentPresentation", () => {expect(resolveAttachmentPresentation("payload.ts", "application/x-custom")).toEqual(presentation("unknown", null))})++ it.each([+ ["voice.mp3", "audio/mpeg", "audio"],+ ["voice.wav", "audio/wav", "audio"],+ ["voice.m4a", "audio/mp4", "audio"],+ ["voice.ogg", "audio/ogg", "audio"],+ ["clip.mp4", "video/mp4", "video"],+ ["clip.webm", "video/webm", "video"],+ ["clip.mov", "video/quicktime", "video"],+ ])("classifies media MIME for %s", (filename, contentType, category) => {+ expect(resolveAttachmentPresentation(filename, contentType))+ .toEqual(presentation(category as AttachmentPresentation["category"], null))+ })++ it.each([+ ["voice.mp3", "audio"],+ ["voice.wav", "audio"],+ ["voice.m4a", "audio"],+ ["voice.ogg", "audio"],+ ["clip.mp4", "video"],+ ["clip.webm", "video"],+ ["clip.mov", "video"],+ ])("uses generic-MIME media fallback for %s", (filename, category) => {+ expect(resolveAttachmentPresentation(filename, "application/octet-stream"))+ .toEqual(presentation(category as AttachmentPresentation["category"], null))+ })++ it("keeps a specific non-media MIME authoritative over media extensions", () => {+ expect(resolveAttachmentPresentation("report.mp4", "application/pdf"))+ .toEqual(presentation("pdf", null))+ expect(resolveAttachmentPresentation("archive.mp3", "application/zip"))+ .toEqual(presentation("archive", null))+ })++ it.each([+ ["voice.mp3", "application/octet-stream", "audio/mpeg"],+ ["voice.wav", "", "audio/wav"],+ ["voice.m4a", undefined, "audio/mp4"],+ ["voice.ogg", "binary/octet-stream", "audio/ogg"],+ ["clip.mp4", "application/octet-stream", "video/mp4"],+ ["clip.webm", undefined, "video/webm"],+ ["clip.mov", "", "video/quicktime"],+ ["anything.bin", "video/mp4; codecs=avc1", "video/mp4"],+ ])("resolves a browser media type for %s", (filename, contentType, expected) => {+ expect(resolveMediaContentType(filename, contentType)).toBe(expected)+ })++ it("does not derive a media response type from a misleading specific MIME", () => {+ expect(resolveMediaContentType("report.mp4", "application/pdf")).toBeNull()+ })})describe("formatAttachmentSize", () => {diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.tsindex 7f1d37795..2f1b30802 100644--- a/src/web/src/lib/community/attachment-presentation.ts+++ b/src/web/src/lib/community/attachment-presentation.ts@@ -62,6 +62,16 @@ export type AttachmentPresentation = {const GENERIC_CONTENT_TYPES = new Set(["", "application/octet-stream", "binary/octet-stream"])+const MEDIA_EXTENSION_CONTENT_TYPES: Readonly<Record<string, string>> = {+ mp3: "audio/mpeg",+ wav: "audio/wav",+ m4a: "audio/mp4",+ ogg: "audio/ogg",+ mp4: "video/mp4",+ webm: "video/webm",+ mov: "video/quicktime",+}+const MIME_PRESENTATIONS: ReadonlyArray<{matches: (contentType: string) => booleanpresentation: AttachmentPresentation@@ -232,6 +242,18 @@ export function resolveAttachmentPresentation(?? { category: "unknown", previewKind: null, shikiLanguage: null }}+export function resolveMediaContentType(+ filename: string,+ contentType?: string | null,+): string | null {+ const normalizedType = contentType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""+ if (normalizedType.startsWith("audio/") || normalizedType.startsWith("video/")) {+ return normalizedType+ }+ if (!GENERIC_CONTENT_TYPES.has(normalizedType)) return null+ return MEDIA_EXTENSION_CONTENT_TYPES[filenameParts(filename).extension] ?? null+}+export function formatAttachmentSize(bytes?: number): string {if (bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return ""if (bytes < 1024) return `${bytes} B`diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.tsindex 9263a7019..792f34315 100644--- a/src/web/src/lib/community/testids.test.ts+++ b/src/web/src/lib/community/testids.test.ts@@ -24,6 +24,13 @@ 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.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")+ expect(tid.mediaCollapse("clip.mp4")).toBe("community-media-collapse-clip.mp4")+ expect(tid.mediaDownload("clip.mp4")).toBe("community-media-download-clip.mp4")+ expect(tid.mediaRetry("clip.mp4")).toBe("community-media-retry-clip.mp4")+ expect(tid.mediaStatus("clip.mp4")).toBe("community-media-status-clip.mp4")})it("exposes only the four stable My Bots bug-report flow selectors", () => {diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex a38bc2ad5..6502abf97 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -44,6 +44,13 @@ export const tid = {attachmentPreviewSheet: "community-attachment-preview-sheet",attachmentPreviewDownload: "community-attachment-preview-download",attachmentPreviewContent: "community-attachment-preview-content",+ mediaBlock: (name: string) => `community-media-block-${name}`,+ mediaPlay: (name: string) => `community-media-play-${name}`,+ mediaPlayer: (name: string) => `community-media-player-${name}`,+ mediaCollapse: (name: string) => `community-media-collapse-${name}`,+ mediaDownload: (name: string) => `community-media-download-${name}`,+ mediaRetry: (name: string) => `community-media-retry-${name}`,+ mediaStatus: (name: string) => `community-media-status-${name}`,codePreview: "community-code-preview",codePreviewLanguage: "community-code-preview-language",codePreviewCopy: "community-code-preview-copy",