Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): share attachment download state (#679)

Gener87c024ae28b5
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index a32bd0c32..050574de8 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -407,12 +407,6 @@ function DmView() {
onPreviewAttachment: (attachment: FileAttachment) => {
uiHandlers.previewAttachment?.(attachment)
},
- onDownloadFile: (url: string, name: string) => {
- const a = document.createElement("a")
- a.href = url
- a.download = name
- a.click()
- },
}), [toggleReaction, toggleMark, dmId, currentUser.id, messages, retryDmMessage, uiHandlers, advanceOnboardingAfterSend])
// DM endpoint ignores mentionType. Replies are supported — the backend
@@ -494,7 +488,6 @@ function DmView() {
onDismiss={dmBlocked ? undefined : messageActions.onDismiss}
onPreviewImage={messageActions.onPreviewImage}
onPreviewAttachment={messageActions.onPreviewAttachment}
- onDownloadFile={messageActions.onDownloadFile}
onOpenProfile={openProfile}
resolveUserName={resolveUserName}
onScrollRoot={setScrollRootEl}
diff --git a/src/web/src/components/community/channels/thread-channel-surface.test.ts b/src/web/src/components/community/channels/thread-channel-surface.test.ts
index beb7a4ae4..796e8b52a 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.test.ts
@@ -109,7 +109,6 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
onEdit: vi.fn(),
onRetry: vi.fn(),
onPreviewImage: vi.fn(),
- onDownloadFile: vi.fn(),
},
threadActions: {
onToggleReaction: vi.fn(),
@@ -122,7 +121,6 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
onEdit: vi.fn(),
onRetry: vi.fn(),
onPreviewImage: vi.fn(),
- onDownloadFile: vi.fn(),
},
acceptMessage: mocks.acceptMessage,
handleTyping: mocks.handleTyping,
@@ -287,15 +285,6 @@ describe("ThreadChannelSurface ownership", () => {
expect(mocks.router.push).toHaveBeenCalledWith("/c/channels/server_1/parent_1?msg=opener_1")
act(() => opener.props.onPreviewImage?.("https://example.test/image.png"))
expect(props.uiHandlers.previewImage).toHaveBeenCalledWith("https://example.test/image.png")
- const anchor = { href: "", download: "", click: vi.fn() }
- vi.stubGlobal("document", { createElement: vi.fn(() => anchor) })
- act(() => opener.props.onDownloadFile?.("https://example.test/report.pdf", "report.pdf"))
- expect(anchor).toEqual(expect.objectContaining({
- href: "https://example.test/report.pdf",
- download: "report.pdf",
- }))
- expect(anchor.click).toHaveBeenCalledTimes(1)
-
expect(mockedMessageList).toHaveBeenCalledWith(expect.objectContaining({
channel: "Thread name",
messages: expect.arrayContaining([expect.objectContaining({ id: "message_1" })]),
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 81169a50f..fed9ddfbd 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -188,12 +188,6 @@ export function ThreadChannelSurface({
onInsertMentionText={mentionInsertion.insertMentionText}
onPreviewImage={(image) => uiHandlers.previewImage?.(image)}
onPreviewAttachment={(attachment) => uiHandlers.previewAttachment?.(attachment)}
- onDownloadFile={(url, name) => {
- const link = document.createElement("a")
- link.href = url
- link.download = name
- link.click()
- }}
onJump={parentChannelId
? () => router.push(`/c/channels/${serverParam}/${parentChannelId}?msg=${parentMessageId}`)
: undefined}
diff --git a/src/web/src/components/community/messages/attachment-card.test.ts b/src/web/src/components/community/messages/attachment-card.test.ts
index 4fe4b9984..2d7553f93 100644
--- a/src/web/src/components/community/messages/attachment-card.test.ts
+++ b/src/web/src/components/community/messages/attachment-card.test.ts
@@ -1,8 +1,9 @@
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
-import { describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { AttachmentCard } from "./attachment-card"
import type { FileAttachment } from "@/lib/community/models/message"
+import { resetAttachmentDownloadsForTest } from "@/lib/community/attachment-download"
function attachment(overrides: Partial<FileAttachment> = {}): FileAttachment {
return {
@@ -17,15 +18,19 @@ function attachment(overrides: Partial<FileAttachment> = {}): FileAttachment {
}
describe("AttachmentCard", () => {
+ beforeEach(() => resetAttachmentDownloadsForTest())
+ afterEach(() => {
+ resetAttachmentDownloadsForTest()
+ vi.unstubAllGlobals()
+ })
+
it("opens previewable text through the shared preview handler", () => {
const onPreview = vi.fn()
- const onDownload = vi.fn()
let renderer: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(React.createElement(AttachmentCard, {
attachment: attachment(),
onPreview,
- onDownload,
}))
})
const button = renderer!.root.findByType("button")
@@ -33,27 +38,37 @@ describe("AttachmentCard", () => {
expect(button.props["aria-label"]).toBe("Preview notes.md")
act(() => button.props.onClick())
expect(onPreview).toHaveBeenCalledWith(attachment())
- expect(onDownload).not.toHaveBeenCalled()
})
- it("downloads unsupported files and preserves the original filename", () => {
+ it("downloads unsupported files through the shared owner and preserves the original filename", async () => {
const onPreview = vi.fn()
- const onDownload = vi.fn()
+ const anchor = { href: "", download: "", hidden: false, click: vi.fn(), remove: vi.fn() }
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("bytes")))
+ vi.stubGlobal("document", {
+ createElement: vi.fn(() => anchor),
+ })
+ vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:file"), revokeObjectURL: vi.fn() })
const pdf = attachment({ name: "报告.pdf", contentType: "application/pdf" })
let renderer: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(React.createElement(AttachmentCard, {
attachment: pdf,
onPreview,
- onDownload,
}))
})
const button = renderer!.root.findByType("button")
expect(button.props["data-attachment-category"]).toBe("pdf")
expect(button.props["aria-label"]).toBe("Download 报告.pdf")
- act(() => button.props.onClick())
- expect(onDownload).toHaveBeenCalledWith("/attachments/a1", "报告.pdf")
+ 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.click).toHaveBeenCalledOnce()
expect(onPreview).not.toHaveBeenCalled()
+ expect(renderer!.root.findByProps({ role: "status" }).children).toEqual(["Download started"])
})
it.each([
@@ -61,14 +76,12 @@ describe("AttachmentCard", () => {
["unsafe.svg", "image/svg+xml", "code"],
])("opens %s through the source preview instead of download", (name, contentType, category) => {
const onPreview = vi.fn()
- const onDownload = vi.fn()
const source = attachment({ name, contentType })
let renderer: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(React.createElement(AttachmentCard, {
attachment: source,
onPreview,
- onDownload,
}))
})
const button = renderer!.root.findByType("button")
@@ -76,7 +89,6 @@ describe("AttachmentCard", () => {
expect(button.props["aria-label"]).toBe(`Preview ${name}`)
act(() => button.props.onClick())
expect(onPreview).toHaveBeenCalledWith(source)
- expect(onDownload).not.toHaveBeenCalled()
})
it.each([
@@ -88,7 +100,6 @@ describe("AttachmentCard", () => {
act(() => {
renderer = TestRenderer.create(React.createElement(AttachmentCard, {
attachment: file,
- onDownload: vi.fn(),
}))
})
@@ -104,7 +115,6 @@ describe("AttachmentCard", () => {
act(() => {
renderer = TestRenderer.create(React.createElement(AttachmentCard, {
attachment: pdf,
- onDownload: vi.fn(),
}))
})
@@ -113,4 +123,45 @@ describe("AttachmentCard", () => {
expect(renderer!.root.findAllByProps({ "data-testid": "community-media-block-document.mp4" }))
.toHaveLength(0)
})
+
+ it("shares one in-flight state and operation across two rendered surfaces", async () => {
+ let resolveBlob!: (blob: Blob) => void
+ const blob = vi.fn(() => new Promise<Blob>((resolve) => { resolveBlob = resolve }))
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, blob })
+ const anchor = { href: "", download: "", hidden: false, click: vi.fn(), remove: vi.fn() }
+ vi.stubGlobal("fetch", fetchMock)
+ vi.stubGlobal("document", {
+ createElement: vi.fn(() => anchor),
+ })
+ vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:file"), revokeObjectURL: vi.fn() })
+ const pdf = attachment({ name: "report.pdf", contentType: "application/pdf" })
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(React.Fragment, null,
+ React.createElement(AttachmentCard, { attachment: pdf }),
+ React.createElement(AttachmentCard, { attachment: pdf }),
+ ))
+ })
+
+ const buttons = renderer!.root.findAllByType("button")
+ act(() => {
+ buttons[0]!.props.onClick()
+ buttons[1]!.props.onClick()
+ })
+ expect(renderer!.root.findAllByProps({ role: "status" }).map((node) => node.children.join("")))
+ .toEqual(["Downloading…", "Downloading…"])
+ expect(renderer!.root.findAllByType("button").every((button) => button.props.disabled)).toBe(true)
+ await Promise.resolve()
+ expect(fetchMock).toHaveBeenCalledOnce()
+
+ await vi.waitFor(() => expect(blob).toHaveBeenCalledOnce())
+ resolveBlob(new Blob(["complete"]))
+ await act(async () => {
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ expect(anchor.click).toHaveBeenCalledOnce()
+ expect(renderer!.root.findAllByProps({ role: "status" }).map((node) => node.children.join("")))
+ .toEqual(["Download started", "Download started"])
+ })
})
diff --git a/src/web/src/components/community/messages/attachment-card.tsx b/src/web/src/components/community/messages/attachment-card.tsx
index cb1030d08..cee241d55 100644
--- a/src/web/src/components/community/messages/attachment-card.tsx
+++ b/src/web/src/components/community/messages/attachment-card.tsx
@@ -3,6 +3,7 @@
import type { LucideIcon } from "lucide-react"
import {
Archive,
+ CircleCheck,
Download,
Eye,
File,
@@ -12,7 +13,9 @@ import {
FileSpreadsheet,
FileText,
FileVideo,
+ LoaderCircle,
Presentation,
+ RefreshCw,
} from "lucide-react"
import type { FileAttachment } from "@/lib/community/models/message"
import { MediaAttachmentBlock } from "./media-attachment-block"
@@ -21,6 +24,10 @@ import {
resolveAttachmentPresentation,
type AttachmentCategory,
} from "@/lib/community/attachment-presentation"
+import {
+ attachmentDownloadStatusText,
+ useAttachmentDownload,
+} from "@/lib/community/attachment-download"
const CATEGORY_ICONS: Record<AttachmentCategory, LucideIcon> = {
image: FileImage,
@@ -39,11 +46,9 @@ const CATEGORY_ICONS: Record<AttachmentCategory, LucideIcon> = {
export function AttachmentCard({
attachment,
onPreview,
- onDownload,
}: {
attachment: FileAttachment
onPreview?: (attachment: FileAttachment) => void
- onDownload?: (url: string, name: string) => void
}) {
const presentation = resolveAttachmentPresentation(attachment.name, attachment.contentType)
if (presentation.category === "audio" || presentation.category === "video") {
@@ -51,14 +56,40 @@ export function AttachmentCard({
<MediaAttachmentBlock
attachment={attachment}
mediaKind={presentation.category}
- onDownload={onDownload}
/>
)
}
+ return <FileAttachmentCard attachment={attachment} onPreview={onPreview} />
+}
+
+function FileAttachmentCard({
+ attachment,
+ onPreview,
+}: {
+ attachment: FileAttachment
+ onPreview?: (attachment: FileAttachment) => void
+}) {
+ const presentation = resolveAttachmentPresentation(attachment.name, attachment.contentType)
+ const download = useAttachmentDownload(attachment)
const Icon = CATEGORY_ICONS[presentation.category]
const canPreview = presentation.previewKind !== null && !!onPreview
- const ActionIcon = canPreview ? Eye : Download
- const action = canPreview ? "Preview" : "Download"
+ const statusText = canPreview ? null : attachmentDownloadStatusText(download.state)
+ const ActionIcon = canPreview
+ ? Eye
+ : download.state.status === "downloading"
+ ? LoaderCircle
+ : download.state.status === "success"
+ ? CircleCheck
+ : download.state.status === "error"
+ ? RefreshCw
+ : Download
+ const action = canPreview
+ ? "Preview"
+ : download.state.status === "downloading"
+ ? "Downloading"
+ : download.state.status === "error"
+ ? "Retry download"
+ : "Download"
return (
<button
@@ -67,18 +98,29 @@ export function AttachmentCard({
data-attachment-category={presentation.category}
onClick={() => canPreview
? onPreview(attachment)
- : onDownload?.(attachment.url, attachment.name)}
- className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ : void download.start()}
+ className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground"
aria-label={`${action} ${attachment.name}`}
+ aria-busy={!canPreview && download.state.status === "downloading"}
+ disabled={!canPreview && download.state.status === "downloading"}
>
<Icon className="size-7 shrink-0 text-muted-foreground" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-primary">{attachment.name}</div>
- {attachment.size && (
+ {statusText ? (
+ <div
+ role={download.state.status === "error" ? "alert" : "status"}
+ className="text-xs text-muted-foreground"
+ >
+ {statusText}
+ </div>
+ ) : attachment.size && (
<div className="text-xs text-muted-foreground">{attachment.size}</div>
)}
</div>
- <ActionIcon className="size-4 shrink-0 text-muted-foreground" />
+ <ActionIcon
+ className={`size-4 shrink-0 text-muted-foreground ${download.state.status === "downloading" ? "animate-spin motion-reduce:animate-none" : ""}`}
+ />
</button>
)
}
diff --git a/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts b/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts
new file mode 100644
index 000000000..e2325c7e7
--- /dev/null
+++ b/src/web/src/components/community/messages/attachment-download-surfaces.contract.test.ts
@@ -0,0 +1,47 @@
+import { readFileSync } from "node:fs"
+import { dirname, resolve } from "node:path"
+import { fileURLToPath } from "node:url"
+import { describe, expect, it } from "vitest"
+
+const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")
+const source = (path: string) => readFileSync(resolve(webRoot, path), "utf8")
+
+describe("Community attachment download surface contract", () => {
+ it("keeps every ordinary attachment action on the shared owner", () => {
+ for (const path of [
+ "src/components/community/messages/attachment-card.tsx",
+ "src/components/community/messages/media-attachment-block.tsx",
+ "src/components/community/messages/attachment-preview-sheet.tsx",
+ ]) {
+ expect(source(path), path).toContain("useAttachmentDownload")
+ }
+ })
+
+ it("does not restore a direct anchor fallback in DM, channel, thread, context, or preview", () => {
+ for (const path of [
+ "src/app/c/me/[dmId]/page.tsx",
+ "src/components/community/channels/thread-channel-surface.tsx",
+ "src/components/community/messages/message-channel-controller-actions.ts",
+ "src/components/community/messages/message-context-sheet.tsx",
+ "src/components/community/messages/attachment-card.tsx",
+ "src/components/community/messages/media-attachment-block.tsx",
+ "src/components/community/messages/attachment-preview-sheet.tsx",
+ ]) {
+ const text = source(path)
+ expect(text, path).not.toContain("onDownloadFile")
+ expect(text, path).not.toMatch(/createElement\(["']a["']\)/)
+ expect(text, path).not.toMatch(/<a\b[^>]*\bdownload=/)
+ }
+ })
+
+ it("renders representative message and thread attachments without a surface callback", () => {
+ for (const path of [
+ "src/components/community/messages/message.tsx",
+ "src/components/community/messages/thread-opener.tsx",
+ ]) {
+ const text = source(path)
+ expect(text, path).toContain("<AttachmentCard")
+ expect(text, path).not.toContain("onDownload=")
+ }
+ })
+})
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.ts
index 185c03c7a..818612ec9 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
@@ -3,6 +3,7 @@ import TestRenderer, { act } from "react-test-renderer"
import { afterEach, describe, expect, it, vi } from "vitest"
import { AttachmentPreviewSheet, readAttachmentText } from "./attachment-preview-sheet"
import type { FileAttachment } from "@/lib/community/models/message"
+import { resetAttachmentDownloadsForTest } from "@/lib/community/attachment-download"
const dynamicMock = vi.hoisted(() => ({
options: null as null | Record<string, unknown>,
@@ -86,6 +87,7 @@ async function flush(): Promise<void> {
}
afterEach(() => {
+ resetAttachmentDownloadsForTest()
vi.unstubAllGlobals()
})
@@ -120,8 +122,16 @@ describe("AttachmentPreviewSheet", () => {
})
it("fetches private Markdown, renders it safely, and exposes metadata/download", async () => {
- const fetchMock = vi.fn().mockResolvedValue(new Response("# Hello", { status: 200 }))
+ resetAttachmentDownloadsForTest()
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response("# Hello", { status: 200 }))
+ .mockResolvedValueOnce(new Response("download bytes", { status: 200 }))
+ const anchor = { href: "", download: "", hidden: false, click: vi.fn(), remove: vi.fn() }
vi.stubGlobal("fetch", fetchMock)
+ vi.stubGlobal("document", {
+ createElement: vi.fn(() => anchor),
+ })
+ vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:preview"), revokeObjectURL: vi.fn() })
let renderer: TestRenderer.ReactTestRenderer
await act(async () => {
renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {
@@ -134,12 +144,24 @@ describe("AttachmentPreviewSheet", () => {
expect(fetchMock).toHaveBeenCalledWith("/attachments/a1", expect.objectContaining({ credentials: "same-origin" }))
expect(renderer!.root.findByProps({ "data-markdown": true }).children).toEqual(["# Hello"])
const download = renderer!.root.findByProps({ "data-testid": "community-attachment-preview-download" })
- expect(download.props.href).toBe("/attachments/a1")
- expect(download.props.download).toBe("notes.md")
+ expect(download.type).toBe("button")
+ expect(download.children.join("")).toContain("Download")
expect(download.props.className).toContain("h-11")
expect(download.props.className).toContain("sm:h-7")
- expect(download.parent?.type).toBe("footer")
+ expect(renderer!.root.findByType("footer").findByProps({
+ "data-testid": "community-attachment-preview-download",
+ })).toBe(download)
expect(renderer!.root.findByType("p").children.join("")).toContain("text/markdown · 128 B")
+ await act(async () => {
+ download.props.onClick()
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ expect(fetchMock).toHaveBeenNthCalledWith(2, "/attachments/a1", { credentials: "same-origin" })
+ expect(anchor).toEqual(expect.objectContaining({ href: "blob:preview", download: "notes.md" }))
+ expect(anchor.click).toHaveBeenCalledOnce()
+ expect(renderer!.root.findByProps({ "data-testid": "community-attachment-preview-download" }).children.join(""))
+ .toContain("Download started")
})
it("aborts the old request on switch and never paints its stale result", async () => {
diff --git a/src/web/src/components/community/messages/attachment-preview-sheet.tsx b/src/web/src/components/community/messages/attachment-preview-sheet.tsx
index f1b9544aa..11402ecd7 100644
--- a/src/web/src/components/community/messages/attachment-preview-sheet.tsx
+++ b/src/web/src/components/community/messages/attachment-preview-sheet.tsx
@@ -2,7 +2,7 @@
import { useEffect, useState } from "react"
import dynamic from "next/dynamic"
-import { Download, Loader2 } from "lucide-react"
+import { CircleCheck, Download, Loader2, RefreshCw } from "lucide-react"
import { buttonVariants } from "@/components/ui/button"
import { CommunitySheet } from "@/components/community/shell/community-sheet"
import { cn } from "@/lib/utils"
@@ -14,6 +14,10 @@ import {
MAX_TEXT_ATTACHMENT_PREVIEW_BYTES,
resolveAttachmentPresentation,
} from "@/lib/community/attachment-presentation"
+import {
+ attachmentDownloadStatusText,
+ useAttachmentDownload,
+} from "@/lib/community/attachment-download"
const CodePreview = dynamic(
() => import("./code-preview").then((module) => module.CodePreview),
@@ -39,6 +43,36 @@ type PreviewState =
const IDLE_STATE: PreviewState = { status: "idle", content: null, error: null }
+function AttachmentPreviewDownload({ attachment }: { attachment: FileAttachment }) {
+ const download = useAttachmentDownload(attachment)
+ const statusText = attachmentDownloadStatusText(download.state)
+ const Icon = download.state.status === "downloading"
+ ? Loader2
+ : download.state.status === "success"
+ ? CircleCheck
+ : download.state.status === "error"
+ ? RefreshCw
+ : Download
+
+ return (
+ <button
+ type="button"
+ data-testid={tid.attachmentPreviewDownload}
+ onClick={() => void download.start()}
+ disabled={download.state.status === "downloading"}
+ aria-busy={download.state.status === "downloading"}
+ className={buttonVariants({
+ variant: "outline",
+ size: "sm",
+ className: "h-11 disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground sm:h-7",
+ })}
+ >
+ <Icon className={`size-3.5 ${download.state.status === "downloading" ? "animate-spin motion-reduce:animate-none" : ""}`} />
+ {statusText ?? "Download"}
+ </button>
+ )
+}
+
export async function readAttachmentText(
response: Response,
maxBytes = MAX_TEXT_ATTACHMENT_PREVIEW_BYTES,
@@ -143,15 +177,7 @@ export function AttachmentPreviewSheet({
title={selected?.name ?? "Attachment"}
description={[selected?.contentType || presentation?.category, size].filter(Boolean).join(" · ")}
footer={selected && (
- <a
- data-testid={tid.attachmentPreviewDownload}
- href={selected.url}
- download={selected.name}
- className={buttonVariants({ variant: "outline", size: "sm", className: "h-11 sm:h-7" })}
- >
- <Download className="size-3.5" />
- Download
- </a>
+ <AttachmentPreviewDownload attachment={selected} />
)}
resizable
closeLabel="Close attachment preview"
diff --git a/src/web/src/components/community/messages/media-attachment-block.test.ts b/src/web/src/components/community/messages/media-attachment-block.test.ts
index e51879fe0..ac12e6ceb 100644
--- a/src/web/src/components/community/messages/media-attachment-block.test.ts
+++ b/src/web/src/components/community/messages/media-attachment-block.test.ts
@@ -1,9 +1,10 @@
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
-import { describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { tid } from "@/lib/community/testids"
import type { FileAttachment } from "@/lib/community/models/message"
import { MediaAttachmentBlock } from "./media-attachment-block"
+import { resetAttachmentDownloadsForTest } from "@/lib/community/attachment-download"
vi.mock("@/components/ui/button", () => ({
Button: ({ children, ...props }: React.ComponentProps<"button">) => React.createElement("button", props, children),
@@ -24,13 +25,11 @@ function attachment(overrides: Partial<FileAttachment> = {}): FileAttachment {
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
} = {}) {
@@ -46,7 +45,7 @@ function renderMedia({
let renderer: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(
- React.createElement(MediaAttachmentBlock, { attachment: item, mediaKind, onDownload }),
+ React.createElement(MediaAttachmentBlock, { attachment: item, mediaKind }),
{
createNodeMock: (element) => {
if (element.type !== "audio" && element.type !== "video") return null
@@ -59,6 +58,12 @@ function renderMedia({
}
describe("MediaAttachmentBlock", () => {
+ beforeEach(() => resetAttachmentDownloadsForTest())
+ afterEach(() => {
+ resetAttachmentDownloadsForTest()
+ vi.unstubAllGlobals()
+ })
+
it("keeps video idle without mounting media and exposes a stable play surface", () => {
const { renderer, mediaNode } = renderMedia()
@@ -317,14 +322,26 @@ describe("MediaAttachmentBlock", () => {
expect(mediaNode.play).toHaveBeenCalledTimes(2)
})
- it("downloads the original file without activating playback", () => {
- const onDownload = vi.fn()
+ it("downloads the original file through the shared owner without activating playback", async () => {
const stopPropagation = vi.fn()
- const { renderer, mediaNode } = renderMedia({ onDownload })
+ const anchor = { href: "", download: "", hidden: false, click: vi.fn(), remove: vi.fn() }
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("media bytes")))
+ vi.stubGlobal("document", {
+ createElement: vi.fn(() => anchor),
+ })
+ vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:media"), revokeObjectURL: vi.fn() })
+ const { renderer, mediaNode } = renderMedia()
- act(() => renderer.root.findByProps({ "data-testid": tid.mediaDownload("clip.mp4") }).props.onClick({ stopPropagation }))
+ await act(async () => {
+ renderer.root.findByProps({ "data-testid": tid.mediaDownload("clip.mp4") }).props.onClick({ stopPropagation })
+ await Promise.resolve()
+ await Promise.resolve()
+ })
expect(stopPropagation).toHaveBeenCalledOnce()
- expect(onDownload).toHaveBeenCalledWith("/attachments/video-1", "clip.mp4")
+ expect(fetch).toHaveBeenCalledWith("/attachments/video-1", { credentials: "same-origin" })
+ expect(anchor).toEqual(expect.objectContaining({ href: "blob:media", download: "clip.mp4" }))
+ expect(anchor.click).toHaveBeenCalledOnce()
+ expect(renderer.root.findByProps({ role: "status" }).children).toEqual(["Download started"])
expect(mediaNode.play).not.toHaveBeenCalled()
expect(renderer.root.findAllByType("video")).toHaveLength(0)
})
diff --git a/src/web/src/components/community/messages/media-attachment-block.tsx b/src/web/src/components/community/messages/media-attachment-block.tsx
index 0bcf63aa4..e44b10ea2 100644
--- a/src/web/src/components/community/messages/media-attachment-block.tsx
+++ b/src/web/src/components/community/messages/media-attachment-block.tsx
@@ -2,10 +2,14 @@
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 { CircleCheck, 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 "@/lib/community/models/message"
+import {
+ attachmentDownloadStatusText,
+ useAttachmentDownload,
+} from "@/lib/community/attachment-download"
type MediaKind = "audio" | "video"
type MediaStatus = "idle" | "loading" | "ready" | "blocked" | "error"
@@ -13,11 +17,9 @@ 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")
@@ -28,6 +30,15 @@ export function MediaAttachmentBlock({
const playbackAttemptRef = useRef(0)
const playbackActiveRef = useRef(false)
const MediaIcon = mediaKind === "video" ? FileVideo : FileAudio
+ const attachmentDownload = useAttachmentDownload(attachment)
+ const downloadStatusText = attachmentDownloadStatusText(attachmentDownload.state)
+ const DownloadIcon = attachmentDownload.state.status === "downloading"
+ ? LoaderCircle
+ : attachmentDownload.state.status === "success"
+ ? CircleCheck
+ : attachmentDownload.state.status === "error"
+ ? RefreshCw
+ : Download
function playPlayer(player: HTMLMediaElement): void {
const attempt = playbackAttemptRef.current + 1
@@ -98,9 +109,9 @@ export function MediaAttachmentBlock({
})
}
- function download(event: MouseEvent<HTMLButtonElement>): void {
+ function handleDownload(event: MouseEvent<HTMLButtonElement>): void {
event.stopPropagation()
- onDownload?.(attachment.url, attachment.name)
+ void attachmentDownload.start()
}
const playerProps = {
@@ -197,6 +208,14 @@ export function MediaAttachmentBlock({
<div className="text-xs text-muted-foreground">
{[mediaKind === "video" ? "Video" : "Audio", attachment.size].filter(Boolean).join(" · ")}
</div>
+ {downloadStatusText && (
+ <p
+ role={attachmentDownload.state.status === "error" ? "alert" : "status"}
+ className="text-xs text-muted-foreground"
+ >
+ {downloadStatusText}
+ </p>
+ )}
{status === "error" && (
<p data-testid={tid.mediaStatus(attachment.name)} role="alert" className="text-xs text-muted-foreground">
Couldn’t play this file
@@ -269,10 +288,16 @@ export function MediaAttachmentBlock({
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}`}
+ onClick={handleDownload}
+ aria-label={`${attachmentDownload.state.status === "downloading"
+ ? "Downloading"
+ : attachmentDownload.state.status === "error"
+ ? "Retry download"
+ : "Download"} ${attachment.name}`}
+ aria-busy={attachmentDownload.state.status === "downloading"}
+ disabled={attachmentDownload.state.status === "downloading"}
>
- <Download className="size-4" />
+ <DownloadIcon className={`size-4 ${attachmentDownload.state.status === "downloading" ? "animate-spin motion-reduce:animate-none" : ""}`} />
</Button>
</div>
diff --git a/src/web/src/components/community/messages/message-channel-controller-actions.test.ts b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
index 24f67b00d..900bb5eae 100644
--- a/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
@@ -85,10 +85,8 @@ describe("createMessageActions", () => {
})
afterEach(() => vi.unstubAllGlobals())
- it("routes reply, reactions, marks, previews, retry, dismiss, and download exactly", async () => {
+ it("routes reply, reactions, marks, previews, retry, and dismiss exactly", async () => {
const harness = setup()
- const link = { href: "", download: "", click: vi.fn() }
- vi.stubGlobal("document", { createElement: vi.fn(() => link) })
harness.actions.onReply("m1")
expect(harness.setReplyTo).toHaveBeenCalledWith({ id: "m1", authorName: "Viewer", text: "hello" })
harness.actions.onToggleReaction("m1", "👍")
@@ -127,9 +125,6 @@ describe("createMessageActions", () => {
harness.actions.onDismiss("m1")
expect(mocks.dispatch).toHaveBeenCalledTimes(dispatchCount)
expect(harness.runAcceptedIntent).toHaveBeenCalledOnce()
- harness.actions.onDownloadFile("/file", "report.txt")
- expect(link).toEqual(expect.objectContaining({ href: "/file", download: "report.txt" }))
- expect(link.click).toHaveBeenCalledOnce()
})
it("preserves pin/unpin, thread, copy, and edit guards and callbacks", async () => {
diff --git a/src/web/src/components/community/messages/message-channel-controller-actions.ts b/src/web/src/components/community/messages/message-channel-controller-actions.ts
index 5ff2d0ac7..4ade77b18 100644
--- a/src/web/src/components/community/messages/message-channel-controller-actions.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-actions.ts
@@ -163,11 +163,5 @@ export function createMessageActions({
onPreviewImage: (image: ImagePreview) => actionContext.current.uiHandlers.previewImage?.(image),
onPreviewAttachment: (attachment: FileAttachment) =>
actionContext.current.uiHandlers.previewAttachment?.(attachment),
- onDownloadFile: (url, name) => {
- const link = document.createElement("a")
- link.href = url
- link.download = name
- link.click()
- },
}
}
diff --git a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
index de9e1034b..4292ca252 100644
--- a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
@@ -34,7 +34,6 @@ type ExpectedMessageActions = {
onDismiss: (id: string) => void
onPreviewImage: (image: ImagePreview) => void
onPreviewAttachment: (attachment: FileAttachment) => void
- onDownloadFile: (url: string, name: string) => void
}
type ExpectedControllerValue = {
feed: ReturnType<typeof useChannelMessageFeed>
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.test.ts
index db7d3569e..a23bfbd1d 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.test.ts
@@ -20,7 +20,7 @@ const mocks = vi.hoisted(() => {
onToggleReaction: vi.fn(), onReact: vi.fn(), onReply: vi.fn(), onPin: vi.fn(),
onMark: vi.fn(), onCreateThread: vi.fn(async () => {}), onCopy: vi.fn(), onEdit: vi.fn(),
onRetry: vi.fn(), onDismiss: vi.fn(), onPreviewImage: vi.fn(),
- onPreviewAttachment: vi.fn(), onDownloadFile: vi.fn(),
+ onPreviewAttachment: vi.fn(),
}
return {
order,
@@ -518,7 +518,7 @@ describe("useMessageChannelController", () => {
const actionKeys = [
"onToggleReaction", "onReact", "onReply", "onPin", "onMark", "onCreateThread",
"onCopy", "onEdit", "onRetry", "onDismiss", "onPreviewImage",
- "onPreviewAttachment", "onDownloadFile",
+ "onPreviewAttachment",
]
expect(Object.keys(latest.messageActions)).toEqual(actionKeys)
expect(Object.keys(latest.threadActions)).toEqual(actionKeys)
diff --git a/src/web/src/components/community/messages/message-channel-controller-types.ts b/src/web/src/components/community/messages/message-channel-controller-types.ts
index eb7c87cbe..31de245bb 100644
--- a/src/web/src/components/community/messages/message-channel-controller-types.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-types.ts
@@ -44,7 +44,6 @@ export type MessageActions = {
onDismiss: (id: string) => void
onPreviewImage: (image: ImagePreview) => void
onPreviewAttachment: (attachment: FileAttachment) => void
- onDownloadFile: (url: string, name: string) => void
}
export type MessageChannelControllerValue = {
diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsx
index a42aa972c..9169dc859 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -117,8 +117,8 @@ function toggleSheetReaction(
* of `<MessageRow>` rows (no MessageList, no virtualization), centers the
* target row on open.
*
- * **Self-contained by design** — reactions, pin, copy, thread, image preview,
- * file download all live INSIDE the sheet and operate on the sheet's own
+ * **Self-contained by design** — reactions, pin, copy, thread, and image
+ * preview all live INSIDE the sheet and operate on the sheet's own
* TanStack cache (a separate query key from the main channel). The main
* channel's cache is deliberately untouched to avoid re-render storms in the
* underlying `<MessageList>` and to avoid injecting mid-history rows into the
@@ -350,13 +350,6 @@ export function MessageContextSheet({
uiHandlers.previewAttachment?.(attachment)
}, [uiHandlers])
- const onDownloadFile = useCallback((url: string, name: string) => {
- const a = document.createElement("a")
- a.href = url
- a.download = name
- a.click()
- }, [])
-
// The sheet's scrollable body — we scroll INSIDE this container, not via
// `element.scrollIntoView({block:'center'})`. `scrollIntoView` walks up to
// the nearest scrollable ancestor and, on a first-open where the sheet is
@@ -447,7 +440,6 @@ export function MessageContextSheet({
onCreateThread={type === "channel" ? onCreateThreadId : undefined}
onPreviewImage={onPreviewImage}
onPreviewAttachment={onPreviewAttachment}
- onDownloadFile={onDownloadFile}
/>
)}
</CommunitySheet>
@@ -471,7 +463,6 @@ function ContextRows({
onCreateThread,
onPreviewImage,
onPreviewAttachment,
- onDownloadFile,
}: {
rows: RenderMsg[]
viewerUserId: string
@@ -489,7 +480,6 @@ function ContextRows({
onCreateThread?: (id: string) => void
onPreviewImage: (image: ImagePreview) => void
onPreviewAttachment: (attachment: FileAttachment) => void
- onDownloadFile: (url: string, name: string) => void
}) {
const hoverCapable = useHoverCapable()
// Single-message share from the peek sheet. The sheet has no select-mode
@@ -535,7 +525,6 @@ function ContextRows({
onCopyId={onCopy}
onPreviewImage={onPreviewImage}
onPreviewAttachment={onPreviewAttachment}
- onDownloadFile={onDownloadFile}
resolveUserName={resolveUserName}
onShareSingleId={onShareSingleId}
/>
diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
index d3d7a6b65..c452320c3 100644
--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
@@ -30,7 +30,6 @@ type ExpectedMessageListProps = {
onDismiss?: (id: string) => void
onPreviewImage?: (image: ImagePreview) => void
onPreviewAttachment?: (attachment: FileAttachment) => void
- onDownloadFile?: (url: string, name: string) => void
resolveUserName?: (userId: string) => string
scrollToMessageId?: string | null
hero?: ReactNode
diff --git a/src/web/src/components/community/messages/message-list-row.test.ts b/src/web/src/components/community/messages/message-list-row.test.ts
index 135079f48..3e6da08a4 100644
--- a/src/web/src/components/community/messages/message-list-row.test.ts
+++ b/src/web/src/components/community/messages/message-list-row.test.ts
@@ -32,7 +32,6 @@ const callbacks = {
onDismiss: vi.fn(),
onPreviewImage: vi.fn(),
onPreviewAttachment: vi.fn(),
- onDownloadFile: vi.fn(),
resolveUserName: vi.fn(),
}
@@ -121,7 +120,6 @@ describe("renderMessageListRow", () => {
onJumpToId: controller.jumpTo,
onPreviewImage: callbacks.onPreviewImage,
onPreviewAttachment: callbacks.onPreviewAttachment,
- onDownloadFile: callbacks.onDownloadFile,
resolveUserName: callbacks.resolveUserName,
onImageLoad: controller.onImageLoad,
selectMode: true,
diff --git a/src/web/src/components/community/messages/message-list-row.tsx b/src/web/src/components/community/messages/message-list-row.tsx
index 028a5952a..227e8189f 100644
--- a/src/web/src/components/community/messages/message-list-row.tsx
+++ b/src/web/src/components/community/messages/message-list-row.tsx
@@ -41,7 +41,6 @@ export function renderMessageListRow(
onJumpToId={controller.jumpTo}
onPreviewImage={props.onPreviewImage}
onPreviewAttachment={props.onPreviewAttachment}
- onDownloadFile={props.onDownloadFile}
resolveUserName={props.resolveUserName}
onImageLoad={controller.onImageLoad}
selectMode={controller.selectMode}
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index c4bcde5bc..e274b77da 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -25,7 +25,6 @@ export type MessageListProps = {
onDismiss?: (id: string) => void
onPreviewImage?: (image: ImagePreview) => void
onPreviewAttachment?: (attachment: FileAttachment) => void
- onDownloadFile?: (url: string, name: string) => void
resolveUserName?: (userId: string) => string
scrollToMessageId?: string | null
hero?: ReactNode
diff --git a/src/web/src/components/community/messages/message-row.tsx b/src/web/src/components/community/messages/message-row.tsx
index a4d3d9fd7..013f0f885 100644
--- a/src/web/src/components/community/messages/message-row.tsx
+++ b/src/web/src/components/community/messages/message-row.tsx
@@ -39,7 +39,6 @@ export interface MessageRowProps {
onJumpToId?: (id: string) => void
onPreviewImage?: (image: ImagePreview) => void
onPreviewAttachment?: (attachment: FileAttachment) => void
- onDownloadFile?: (url: string, name: string) => void
resolveUserName?: (userId: string) => string
onImageLoad?: () => void
// Multi-select share. `selectMode`/`selected` are plain booleans (pass-through);
@@ -58,7 +57,7 @@ function MessageRowImpl(props: MessageRowProps) {
const {
m, viewerUserId, hoverCapable, pinned, highlighted, onOpenThread, onOpenProfile,
onToggleReactionId, onReactId, onReplyId, mentionText, onInsertMentionText, onPinId, onMarkId, onCreateThreadId,
- onCopyId, onEditId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onPreviewAttachment, onDownloadFile,
+ onCopyId, onEditId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onPreviewAttachment,
resolveUserName, onImageLoad,
selectMode, selected, onToggleSelectId, onEnterSelectId, onShareSingleId,
} = props
@@ -117,7 +116,6 @@ function MessageRowImpl(props: MessageRowProps) {
onDismiss={onDismissId ? onDismiss : undefined}
onPreviewImage={onPreviewImage}
onPreviewAttachment={onPreviewAttachment}
- onDownloadFile={onDownloadFile}
resolveUserName={resolveUserName}
onImageLoad={onImageLoad}
selectMode={selectMode}
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index a26e9f0f0..be0f75dc7 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -110,7 +110,7 @@ export function createMessageMenuPointAnchor(clientX: number, clientY: number) {
function MessageImpl({
m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,
onToggleReaction, onReact, onReply, onMentionAuthor, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss,
- onPreviewImage, onPreviewAttachment, onDownloadFile, highlighted, resolveUserName, onImageLoad,
+ onPreviewImage, onPreviewAttachment, highlighted, resolveUserName, onImageLoad,
selectMode, selected, onToggleSelect, onEnterSelect, onShareSingle,
viewerUserId, hoverCapable = true,
}: {
@@ -136,7 +136,6 @@ function MessageImpl({
onDismiss?: () => void
onPreviewImage?: (image: ImagePreview) => void
onPreviewAttachment?: (attachment: FileAttachment) => void
- onDownloadFile?: (url: string, name: string) => void
highlighted?: boolean
resolveUserName?: (userId: string) => string
onImageLoad?: () => void
@@ -530,7 +529,7 @@ function MessageImpl({
/>
</button>
)
- return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} onDownload={onDownloadFile} />
+ return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} />
})}
</div>
)}
@@ -778,7 +777,6 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {
prev.onDismiss === next.onDismiss &&
prev.onPreviewImage === next.onPreviewImage &&
prev.onPreviewAttachment === next.onPreviewAttachment &&
- prev.onDownloadFile === next.onDownloadFile &&
prev.resolveUserName === next.resolveUserName &&
prev.onImageLoad === next.onImageLoad &&
// Multi-select: `selected` flips per-row on toggle, `selectMode` flips for
diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsx
index e5dc59192..dab6152d9 100644
--- a/src/web/src/components/community/messages/thread-opener.tsx
+++ b/src/web/src/components/community/messages/thread-opener.tsx
@@ -38,7 +38,6 @@ export function ThreadOpener({
onOpenProfile,
onPreviewImage,
onPreviewAttachment,
- onDownloadFile,
onJump,
onToggleReaction,
resolveUserName,
@@ -50,7 +49,6 @@ export function ThreadOpener({
onOpenProfile?: OpenProfile
onPreviewImage?: (image: ImagePreview) => void
onPreviewAttachment?: (attachment: FileAttachment) => void
- onDownloadFile?: (url: string, name: string) => void
onToggleReaction?: (emoji: string) => void
resolveUserName?: (userId: string) => string
resolveAuthorMentionText?: (authorId: string) => string | null
@@ -180,7 +178,7 @@ export function ThreadOpener({
/>
</button>
)
- return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} onDownload={onDownloadFile} />
+ return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} />
})}
</div>
)}
diff --git a/src/web/src/lib/community/attachment-download.test.ts b/src/web/src/lib/community/attachment-download.test.ts
new file mode 100644
index 000000000..856b90558
--- /dev/null
+++ b/src/web/src/lib/community/attachment-download.test.ts
@@ -0,0 +1,141 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ attachmentDownloadKey,
+ readAttachmentDownloadState,
+ resetAttachmentDownloadsForTest,
+ startAttachmentDownload,
+} from "./attachment-download"
+
+type AnchorMock = {
+ href: string
+ download: string
+ hidden: boolean
+ click: ReturnType<typeof vi.fn>
+ remove: ReturnType<typeof vi.fn>
+}
+
+function installBrowserMocks() {
+ const order: string[] = []
+ const anchor: AnchorMock = {
+ href: "",
+ download: "",
+ hidden: false,
+ click: vi.fn(() => order.push("click")),
+ remove: vi.fn(() => order.push("remove")),
+ }
+ const createObjectURL = vi.fn(() => {
+ order.push("create-url")
+ return "blob:attachment"
+ })
+ const revokeObjectURL = vi.fn(() => order.push("revoke-url"))
+ vi.stubGlobal("document", {
+ createElement: vi.fn(() => anchor),
+ })
+ vi.stubGlobal("URL", { createObjectURL, revokeObjectURL })
+ return { anchor, createObjectURL, revokeObjectURL, order }
+}
+
+describe("attachment download owner", () => {
+ beforeEach(() => resetAttachmentDownloadsForTest())
+ afterEach(() => {
+ resetAttachmentDownloadsForTest()
+ vi.unstubAllGlobals()
+ })
+
+ it("deduplicates one in-flight attachment until Blob completion and one save trigger", async () => {
+ const browser = installBrowserMocks()
+ const bytes = new Blob(["complete"])
+ let resolveBlob!: (blob: Blob) => void
+ const blob = vi.fn(() => new Promise<Blob>((resolve) => { resolveBlob = resolve }))
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, blob })
+ vi.stubGlobal("fetch", fetchMock)
+ const target = {
+ name: "报告.pdf",
+ url: "/api/community/channels/channel-1/attachments/attachment-1",
+ }
+
+ const first = startAttachmentDownload(target)
+ const second = startAttachmentDownload(target)
+ expect(second).toBe(first)
+ expect(readAttachmentDownloadState(attachmentDownloadKey(target))).toEqual({ status: "downloading" })
+ await Promise.resolve()
+ expect(fetchMock).toHaveBeenCalledOnce()
+ expect(fetchMock).toHaveBeenCalledWith(target.url, { credentials: "same-origin" })
+ expect(browser.anchor.click).not.toHaveBeenCalled()
+ expect(readAttachmentDownloadState(target.url)).toEqual({ status: "downloading" })
+
+ await vi.waitFor(() => expect(blob).toHaveBeenCalledOnce())
+ resolveBlob(bytes)
+ await first
+ expect(browser.createObjectURL).toHaveBeenCalledWith(bytes)
+ expect(browser.anchor).toEqual(expect.objectContaining({
+ href: "blob:attachment",
+ download: "报告.pdf",
+ hidden: true,
+ }))
+ expect(browser.anchor.click).toHaveBeenCalledOnce()
+ expect(browser.anchor.remove).toHaveBeenCalledOnce()
+ expect(browser.revokeObjectURL).toHaveBeenCalledOnce()
+ expect(browser.order).toEqual(["create-url", "click", "remove", "revoke-url"])
+ expect(readAttachmentDownloadState(target.url)).toEqual({ status: "success" })
+ })
+
+ it("does not key same-named attachments from different channel routes together", async () => {
+ installBrowserMocks()
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ blob: vi.fn().mockResolvedValue(new Blob(["bytes"])),
+ })
+ vi.stubGlobal("fetch", fetchMock)
+ const first = { name: "report.pdf", url: "/api/community/channels/channel-1/attachments/a1" }
+ const second = { name: "report.pdf", url: "/api/community/channels/channel-2/attachments/a1" }
+
+ await Promise.all([startAttachmentDownload(first), startAttachmentDownload(second)])
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(attachmentDownloadKey(first)).not.toBe(attachmentDownloadKey(second))
+ })
+
+ it.each([
+ ["network", () => Promise.reject(new TypeError("network failed"))],
+ ["abort", () => Promise.reject(new DOMException("Aborted", "AbortError"))],
+ ["non-2xx", () => Promise.resolve({ ok: false, status: 403, blob: vi.fn() })],
+ ["Blob", () => Promise.resolve({ ok: true, status: 200, blob: vi.fn().mockRejectedValue(new Error("Blob failed")) })],
+ ])("makes %s failure visible and allows a later retry", async (_kind, failedFetch) => {
+ const browser = installBrowserMocks()
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(failedFetch)
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ blob: vi.fn().mockResolvedValue(new Blob(["retry"])),
+ })
+ vi.stubGlobal("fetch", fetchMock)
+ const target = { name: "report.pdf", url: "/api/community/channels/c1/attachments/a1" }
+
+ await startAttachmentDownload(target)
+ expect(readAttachmentDownloadState(target.url).status).toBe("error")
+ expect(browser.anchor.click).not.toHaveBeenCalled()
+
+ await startAttachmentDownload(target)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(browser.anchor.click).toHaveBeenCalledOnce()
+ expect(readAttachmentDownloadState(target.url)).toEqual({ status: "success" })
+ })
+
+ it("cleans up a created anchor and object URL when the save trigger throws", async () => {
+ const browser = installBrowserMocks()
+ browser.anchor.click.mockImplementationOnce(() => { throw new Error("save blocked") })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ blob: vi.fn().mockResolvedValue(new Blob(["bytes"])),
+ }))
+ const target = { name: "report.pdf", url: "/api/community/channels/c1/attachments/a1" }
+
+ await startAttachmentDownload(target)
+ expect(readAttachmentDownloadState(target.url).status).toBe("error")
+ expect(browser.anchor.remove).toHaveBeenCalledOnce()
+ expect(browser.revokeObjectURL).toHaveBeenCalledWith("blob:attachment")
+ })
+})
diff --git a/src/web/src/lib/community/attachment-download.ts b/src/web/src/lib/community/attachment-download.ts
new file mode 100644
index 000000000..8f29af1c7
--- /dev/null
+++ b/src/web/src/lib/community/attachment-download.ts
@@ -0,0 +1,116 @@
+"use client"
+
+import { useCallback, useSyncExternalStore } from "react"
+
+export type AttachmentDownloadTarget = {
+ name: string
+ url: string
+}
+
+export type AttachmentDownloadState =
+ | { status: "idle" }
+ | { status: "downloading" }
+ | { status: "success" }
+ | { status: "error"; message: string }
+
+const IDLE_STATE: AttachmentDownloadState = { status: "idle" }
+const states = new Map<string, AttachmentDownloadState>()
+const listeners = new Map<string, Set<() => void>>()
+const inFlight = new Map<string, Promise<void>>()
+
+export function attachmentDownloadKey(attachment: AttachmentDownloadTarget): string {
+ return attachment.url
+}
+
+export function readAttachmentDownloadState(key: string): AttachmentDownloadState {
+ return states.get(key) ?? IDLE_STATE
+}
+
+export function attachmentDownloadStatusText(state: AttachmentDownloadState): string | null {
+ if (state.status === "downloading") return "Downloading…"
+ if (state.status === "success") return "Download started"
+ if (state.status === "error") return "Couldn’t download — retry"
+ return null
+}
+
+function publish(key: string, state: AttachmentDownloadState): void {
+ states.set(key, state)
+ for (const listener of listeners.get(key) ?? []) listener()
+}
+
+function subscribe(key: string, listener: () => void): () => void {
+ const keyListeners = listeners.get(key) ?? new Set<() => void>()
+ keyListeners.add(listener)
+ listeners.set(key, keyListeners)
+ return () => {
+ keyListeners.delete(listener)
+ if (keyListeners.size === 0) listeners.delete(key)
+ }
+}
+
+async function acquireAndSave(attachment: AttachmentDownloadTarget): Promise<void> {
+ let objectUrl: string | null = null
+ let anchor: HTMLAnchorElement | null = null
+ try {
+ const response = await fetch(attachment.url, { credentials: "same-origin" })
+ if (!response.ok) throw new Error(`Couldn’t download this attachment (${response.status})`)
+ const blob = await response.blob()
+ objectUrl = URL.createObjectURL(blob)
+ anchor = document.createElement("a")
+ anchor.href = objectUrl
+ anchor.download = attachment.name
+ anchor.hidden = true
+ anchor.click()
+ } finally {
+ anchor?.remove()
+ if (objectUrl) URL.revokeObjectURL(objectUrl)
+ }
+}
+
+export function startAttachmentDownload(attachment: AttachmentDownloadTarget): Promise<void> {
+ const key = attachmentDownloadKey(attachment)
+ const active = inFlight.get(key)
+ if (active) return active
+
+ const target = { name: attachment.name, url: attachment.url }
+ const task = Promise.resolve()
+ .then(() => acquireAndSave(target))
+ .then(() => publish(key, { status: "success" }))
+ .catch((error: unknown) => {
+ publish(key, {
+ status: "error",
+ message: error instanceof Error ? error.message : "Couldn’t download this attachment",
+ })
+ })
+ .finally(() => {
+ if (inFlight.get(key) === task) inFlight.delete(key)
+ })
+
+ inFlight.set(key, task)
+ publish(key, { status: "downloading" })
+ return task
+}
+
+export function useAttachmentDownload(attachment: AttachmentDownloadTarget): {
+ state: AttachmentDownloadState
+ start: () => Promise<void>
+} {
+ const key = attachmentDownloadKey(attachment)
+ const subscribeToKey = useCallback(
+ (listener: () => void) => subscribe(key, listener),
+ [key],
+ )
+ const getSnapshot = useCallback(() => readAttachmentDownloadState(key), [key])
+ const state = useSyncExternalStore(subscribeToKey, getSnapshot, getSnapshot)
+ const start = useCallback(
+ () => startAttachmentDownload({ name: attachment.name, url: attachment.url }),
+ [attachment.name, attachment.url],
+ )
+ return { state, start }
+}
+
+export function resetAttachmentDownloadsForTest(): void {
+ states.clear()
+ listeners.clear()
+ inFlight.clear()
+}
diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
index edb3df1a2..05bf70535 100644
--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
@@ -97,10 +97,7 @@ async function expectFooterGeometry(
const sheet = page.getByRole("dialog", { name: title, exact: true })
await settleSheet(sheet)
const footer = sheet.locator("[data-slot='sheet-footer']")
- const actions = actionNames.map((name) => footer.getByRole(
- name === "Download" ? "link" : "button",
- { name, exact: true },
- ))
+ const actions = actionNames.map((name) => footer.getByRole("button", { name, exact: true }))
const footerRect = await rect(footer)
const actionRects = await Promise.all(actions.map(rect))
const style = await footer.evaluate((element) => {