Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8653: fix(editor): show pending state on attachment download buttons (#9993)
AstralSolipsism9c087798a7de
diff --git a/packages/views/editor/attachment-card.test.tsx b/packages/views/editor/attachment-card.test.tsxindex 662b1a5b3c..974d275d7b 100644--- a/packages/views/editor/attachment-card.test.tsx+++ b/packages/views/editor/attachment-card.test.tsx@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen } from "@testing-library/react";+import { act, fireEvent, render, screen } from "@testing-library/react";vi.mock("../i18n", () => ({useT: () => ({@@ -216,3 +216,91 @@ describe("AttachmentFileCard — a file in a grid of cards (MUL-7649)", () => {expect(onDelete).toHaveBeenCalledTimes(1);});});++describe.each([+ {+ layout: "row",+ activate: fireEvent.mouseDown,+ attachment: (onDownload: () => void | Promise<unknown>) => (+ <AttachmentCard+ filename="bundle.zip"+ href="https://example.test/bundle.zip"+ onPreview={vi.fn()}+ onDownload={onDownload}+ />+ ),+ },+ {+ layout: "card",+ activate: fireEvent.click,+ attachment: (onDownload: () => void | Promise<unknown>) => (+ <AttachmentFileCard+ filename="bundle.zip"+ canPreview={false}+ canDownload+ onPreview={vi.fn()}+ onDownload={onDownload}+ />+ ),+ },+])("$layout download feedback", ({ attachment, activate }) => {+ it("shows pending feedback and blocks repeat activation until completion", async () => {+ const pending = Promise.withResolvers<void>();+ const onDownload = vi.fn(() => pending.promise);+ render(attachment(onDownload));+ const button = screen.getByRole("button", { name: "Download" });++ activate(button);++ expect(button).toBeDisabled();+ expect(button).toHaveAttribute("aria-busy", "true");+ expect(button.querySelector(".animate-spin")).toBeInTheDocument();+ activate(button);+ expect(onDownload).toHaveBeenCalledOnce();++ await act(async () => pending.resolve());++ expect(button).toBeEnabled();+ expect(button).toHaveAttribute("aria-busy", "false");+ expect(button.querySelector(".animate-spin")).toBeNull();+ });++ it("keeps sibling attachments available while preparing a download", async () => {+ const pending = Promise.withResolvers<void>();+ const onOtherDownload = vi.fn();+ render(<>{attachment(() => pending.promise)}{attachment(onOtherDownload)}</>);+ const [button, other] = screen.getAllByRole("button", { name: "Download" });++ activate(button!);+ activate(other!);++ expect(onOtherDownload).toHaveBeenCalledOnce();+ await act(async () => pending.resolve());+ });+});++describe("AttachmentFileCard — whole-card download", () => {+ it("shares the download button's pending guard with the whole-card action", async () => {+ const pending = Promise.withResolvers<void>();+ const onDownload = vi.fn(() => pending.promise);+ render(+ <AttachmentFileCard+ filename="bundle.zip"+ canPreview={false}+ canDownload+ onPreview={vi.fn()}+ onDownload={onDownload}+ />,+ );+ const card = screen.getByRole("button", { name: "bundle.zip" });+ const button = screen.getByRole("button", { name: "Download" });++ fireEvent.click(card);++ expect(card).toBeDisabled();+ expect(button).toBeDisabled();+ fireEvent.click(button);+ expect(onDownload).toHaveBeenCalledOnce();+ await act(async () => pending.resolve());+ });+});diff --git a/packages/views/editor/attachment-card.tsx b/packages/views/editor/attachment-card.tsxindex 4339efb484..402bf395bb 100644--- a/packages/views/editor/attachment-card.tsx+++ b/packages/views/editor/attachment-card.tsx@@ -12,12 +12,14 @@*/import type { ReactNode } from "react";+import { cn } from "@multica/ui/lib/utils";import { Download, Eye, FileText, Loader2, Trash2 } from "@multica/ui/icons";import { useT } from "../i18n";import { DeferredTooltip } from "../common/deferred-tooltip";import { formatBytes } from "../common/format-bytes";import { fileIcon } from "./utils/file-icon";import { canOpenPreview, fileTypeLabel, getPreviewKind } from "./utils/preview";+import { useAttachmentDownloadState } from "./hooks/use-attachment-download-state";interface AttachmentCardChromeProps {filename: string;@@ -26,7 +28,7 @@ interface AttachmentCardChromeProps {canDownload: boolean;canDelete?: boolean;onPreview: () => void;- onDownload: () => void;+ onDownload: () => void | Promise<unknown>;onDelete?: () => void;}@@ -41,6 +43,7 @@ function AttachmentCardChrome({onDelete,}: AttachmentCardChromeProps) {const { t } = useT("editor");+ const { downloading, handleDownload } = useAttachmentDownloadState(onDownload);return (<divclassName="flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted"@@ -85,13 +88,19 @@ function AttachmentCardChrome({type="button"className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"aria-label={t(($) => $.image.download)}+ disabled={downloading}+ aria-busy={downloading}onMouseDown={(e) => {e.preventDefault();e.stopPropagation();- onDownload();+ handleDownload();}}>- <Download className="size-3.5" />+ {downloading ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Download className="size-3.5" />+ )}</button>}/>@@ -137,7 +146,7 @@ export interface AttachmentCardProps {/** Pressed when the Eye button is clicked. */onPreview: () => void;/** Pressed when the Download button is clicked. */- onDownload: () => void;+ onDownload: () => void | Promise<unknown>;/** Optional remove button, used by editable comment/file-card surfaces. */onDelete?: () => void;}@@ -184,7 +193,7 @@ export interface AttachmentFileCardProps {/** Rendered after the filename, e.g. a version badge. */badge?: ReactNode;onPreview: () => void;- onDownload: () => void;+ onDownload: () => void | Promise<unknown>;onDelete?: () => void;}@@ -206,11 +215,12 @@ export function AttachmentFileCard({onDelete,}: AttachmentFileCardProps) {const { t } = useT("editor");+ const { downloading, handleDownload } = useAttachmentDownloadState(onDownload);const Icon = fileIcon(contentType, filename);const meta = [fileTypeLabel(filename), sizeBytes > 0 ? formatBytes(sizeBytes) : ""].filter(Boolean).join(" · ");- const open = canPreview ? onPreview : canDownload ? onDownload : undefined;+ const open = canPreview ? onPreview : canDownload ? handleDownload : undefined;return (<div className="group/file-card relative flex min-w-0 items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors hover:bg-muted/50">@@ -224,6 +234,7 @@ export function AttachmentFileCard({title={filename}aria-label={filename}onClick={open}+ disabled={!canPreview && downloading}/>)}<span className="pointer-events-none flex size-10 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">@@ -247,7 +258,10 @@ export function AttachmentFileCard({)}</span>{!uploading && (canDownload || onDelete) && (- <span className="relative flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover/file-card:opacity-100 group-focus-within/file-card:opacity-100 [@media(hover:none)]:opacity-100">+ <span className={cn(+ "relative flex shrink-0 items-center gap-0.5 transition-opacity group-hover/file-card:opacity-100 group-focus-within/file-card:opacity-100 [@media(hover:none)]:opacity-100",+ downloading ? "opacity-100" : "opacity-0",+ )}>{canDownload && (<DeferredTooltipcontent={t(($) => $.image.download)}@@ -256,9 +270,15 @@ export function AttachmentFileCard({type="button"className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"aria-label={t(($) => $.image.download)}- onClick={onDownload}+ disabled={downloading}+ aria-busy={downloading}+ onClick={handleDownload}>- <Download className="size-4" />+ {downloading ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <Download className="size-4" />+ )}</button>}/>diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsxindex 2e8cf0541b..2511522970 100644--- a/packages/views/editor/attachment-preview-modal.test.tsx+++ b/packages/views/editor/attachment-preview-modal.test.tsx@@ -173,6 +173,7 @@ vi.mock("../i18n", () => ({import {AttachmentPreviewModal,+ AttachmentPreviewStandalone,useAttachmentPreview,} from "./attachment-preview-modal";import { withFragmentNavShim } from "./utils/iframe-fragment-nav";@@ -222,6 +223,7 @@ function ClosablePreview({ attachment }: { attachment: Attachment }) {beforeEach(() => {vi.clearAllMocks();+ downloadMock.mockReset();// Drops any body a test queued but never consumed (a media kind skips the// text fetch), so it cannot answer the next test's request.getAttachmentTextContentMock.mockReset();@@ -800,6 +802,112 @@ describe("AttachmentPreviewModal — URL-only source", () => {});});+describe("attachment preview download feedback", () => {+ it("shows pending feedback in the viewer header and restores the button on completion", async () => {+ const pending = Promise.withResolvers<void>();+ downloadMock.mockReturnValueOnce(pending.promise);+ const attachment = makeAttachment({ filename: "manual.pdf", content_type: "application/pdf" });+ render(<AttachmentPreviewModal source={{ kind: "full", attachment }} open onClose={() => {}} />);+ const button = screen.getByRole("button", { name: "Download" });++ fireEvent.click(button);++ expect(button).toBeDisabled();+ expect(button).toHaveAttribute("aria-busy", "true");+ expect(button.querySelector(".animate-spin")).toBeInTheDocument();+ fireEvent.click(button);+ expect(downloadMock).toHaveBeenCalledExactlyOnceWith(attachment.id);++ await act(async () => pending.resolve());++ expect(button).toBeEnabled();+ expect(button).toHaveAttribute("aria-busy", "false");+ expect(button.querySelector(".animate-spin")).toBeNull();+ });++ it("shares pending state between the unsupported-file action and the header", async () => {+ const pending = Promise.withResolvers<void>();+ downloadMock.mockReturnValueOnce(pending.promise);+ const attachment = makeAttachment();+ render(<AttachmentPreviewModal source={{ kind: "full", attachment }} open onClose={() => {}} />);+ const [header, fallback] = screen.getAllByRole("button", { name: "Download" });++ fireEvent.click(fallback!);++ for (const button of [header!, fallback!]) {+ expect(button).toBeDisabled();+ expect(button).toHaveAttribute("aria-busy", "true");+ expect(button.querySelector(".animate-spin")).toBeInTheDocument();+ fireEvent.click(button);+ }+ expect(downloadMock).toHaveBeenCalledExactlyOnceWith(attachment.id);+ await act(async () => pending.resolve());+ });++ it("shows pending feedback on the download action after a text preview fails", async () => {+ getAttachmentTextContentMock.mockRejectedValueOnce(new FakePreviewTooLargeError());+ const pending = Promise.withResolvers<void>();+ downloadMock.mockReturnValueOnce(pending.promise);+ const attachment = makeAttachment({ filename: "large.md", content_type: "text/markdown" });+ render(<AttachmentPreviewModal source={{ kind: "full", attachment }} open onClose={() => {}} />);+ await screen.findByText("File is too large to preview. Please download.");+ const [, fallback] = screen.getAllByRole("button", { name: "Download" });++ fireEvent.click(fallback!);++ expect(fallback).toBeDisabled();+ expect(fallback).toHaveAttribute("aria-busy", "true");+ await act(async () => pending.resolve());+ });++ it("shows the same pending feedback on the standalone preview page", async () => {+ const pending = Promise.withResolvers<void>();+ downloadMock.mockReturnValueOnce(pending.promise);+ const attachment = makeAttachment({ filename: "manual.pdf", content_type: "application/pdf" });+ render(<AttachmentPreviewStandalone attachment={attachment} />);+ const button = screen.getByRole("button", { name: "Download" });++ fireEvent.click(button);++ expect(button).toBeDisabled();+ expect(button).toHaveAttribute("aria-busy", "true");+ expect(button.querySelector(".animate-spin")).toBeInTheDocument();+ await act(async () => pending.resolve());+ });++ it("allows downloading another file while the previous preview's download is pending", async () => {+ const first = makeAttachment({ filename: "first.pdf", content_type: "application/pdf" });+ const second = makeAttachment({ id: "att-2", filename: "second.pdf", content_type: "application/pdf" });+ const firstDownload = Promise.withResolvers<void>();+ const secondDownload = Promise.withResolvers<void>();+ downloadMock.mockReturnValueOnce(firstDownload.promise).mockReturnValueOnce(secondDownload.promise);+ function PreviewSequence() {+ const [index, setIndex] = useState(0);+ return (+ <AttachmentPreviewModal+ source={{ kind: "full", attachment: index === 0 ? first : second }}+ open+ onClose={() => {}}+ sequence={{ index, total: 2, onNext: () => setIndex(1), onPrev: () => setIndex(0) }}+ />+ );+ }+ render(<PreviewSequence />);+ fireEvent.click(screen.getByRole("button", { name: "Download" }));++ fireEvent.keyDown(document, { key: "ArrowRight" });+ const button = screen.getByRole("button", { name: "Download" });+ expect(button).toBeEnabled();+ fireEvent.click(button);++ expect(downloadMock.mock.calls).toEqual([[first.id], [second.id]]);+ await act(async () => firstDownload.resolve());+ expect(button).toBeDisabled();+ await act(async () => secondDownload.resolve());+ expect(button).toBeEnabled();+ });+});+describe("AttachmentPreviewModal — open-in-new-tab", () => {it("renders the open-in-new-tab button in the header for HTML attachments", async () => {getAttachmentTextContentMock.mockResolvedValueOnce({diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex b9e1a5218c..f6c00f5249 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -87,6 +87,7 @@ import { parseStructured } from "./utils/parse-structured";import { formatBytes } from "../common/format-bytes";import { ShortcutKeycaps } from "../common/shortcut-keycaps";import { useDownloadAttachment } from "./use-download-attachment";+import { useAttachmentDownloadState } from "./hooks/use-attachment-download-state";import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";import { useResignedInlineMedia } from "./hooks/use-inline-media-url";import { useZoomCanvas, type ZoomCanvasApi } from "./hooks/use-zoom-canvas";@@ -500,10 +501,9 @@ export function AttachmentPreviewModal({const attachmentId =state.attachmentId ?? attachmentIdFromStorageURL(state.mediaUrl, cdnDomain);if (attachmentId) {- download(attachmentId);- } else {- openExternal(state.mediaUrl);+ return download(attachmentId);}+ return openExternal(state.mediaUrl);};// Open-in-new-tab: the full-page route (/attachments/{id}/preview) shows@@ -691,7 +691,7 @@ function PreviewPanel({source: PreviewSource;state: PreviewState;onClose?: () => void;- onDownload: () => void;+ onDownload: () => void | Promise<unknown>;onOpenInNewTab?: () => void;sequence?: PreviewSequence;onImageError?: () => void;@@ -708,6 +708,11 @@ function PreviewPanel({}) {const { t } = useT("editor");+ const { downloading, handleDownload } = useAttachmentDownloadState(+ onDownload,+ state.attachmentId ?? state.mediaUrl,+ );+// How the file is shown. Held here rather than in the stage so a choice// carries over as the reader pages through the sequence: the next HTML// file opens at the same width, the next log wraps the same way. Wrapping@@ -973,8 +978,17 @@ function PreviewPanel({<Copy className="size-4" /></ChromeButton>)}- <ChromeButton label={t(($) => $.image.download)} onClick={onDownload}>- <Download className="size-4" />+ <ChromeButton+ label={t(($) => $.image.download)}+ onClick={handleDownload}+ disabled={downloading}+ busy={downloading}+ >+ {downloading ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <Download className="size-4" />+ )}</ChromeButton>{(onOpenOverview || info) && <ChromeDivider />}{onOpenOverview && (@@ -1035,7 +1049,8 @@ function PreviewPanel({source={source}state={state}view={view}- onDownload={onDownload}+ onDownload={handleDownload}+ downloading={downloading}onBackdropClick={closeOnBackdrop}/>)}@@ -1066,6 +1081,7 @@ function ChromeButton({shortcut,pressed,disabled,+ busy,onClick,children,}: {@@ -1075,6 +1091,7 @@ function ChromeButton({/** Toggle buttons pass their state; plain actions leave it unset. */pressed?: boolean;disabled?: boolean;+ busy?: boolean;onClick: () => void;children: ReactNode;}) {@@ -1097,6 +1114,7 @@ function ChromeButton({aria-label={label}aria-keyshortcuts={shortcut}aria-pressed={pressed}+ aria-busy={busy}disabled={disabled}onClick={onClick}>@@ -1337,6 +1355,7 @@ function PreviewContent({state,view,onDownload,+ downloading,onBackdropClick,}: {kind: Exclude<PreviewKind, "image"> | null;@@ -1344,6 +1363,7 @@ function PreviewContent({state: PreviewState;view: StageView;onDownload: () => void;+ downloading: boolean;onBackdropClick: (e: React.MouseEvent) => void;}) {const { t } = useT("editor");@@ -1353,6 +1373,7 @@ function PreviewContent({<UnsupportedFallbackmessage={t(($) => $.attachment.preview_unsupported)}onDownload={onDownload}+ downloading={downloading}/>);}@@ -1367,6 +1388,7 @@ function PreviewContent({<UnsupportedFallbackmessage={t(($) => $.attachment.preview_unsupported)}onDownload={onDownload}+ downloading={downloading}/>);}@@ -1415,6 +1437,7 @@ function PreviewContent({<TextBackedPreviewattachmentId={state.attachmentId!}onDownload={onDownload}+ downloading={downloading}render={(text) => (<DocumentSheet width="prose" onBackdropClick={onBackdropClick}><ReadonlyContent@@ -1431,6 +1454,7 @@ function PreviewContent({<TextBackedPreviewattachmentId={state.attachmentId!}onDownload={onDownload}+ downloading={downloading}render={(text) =>view.htmlSource ? (code(text, "xml")@@ -1451,6 +1475,7 @@ function PreviewContent({<TextBackedPreviewattachmentId={state.attachmentId!}onDownload={onDownload}+ downloading={downloading}render={(text) => (// Keyed on the file: sort order and column widths belong to it.<TablePreview@@ -1466,6 +1491,7 @@ function PreviewContent({<TextBackedPreviewattachmentId={state.attachmentId!}onDownload={onDownload}+ downloading={downloading}render={(text) => {const parse = view.structuredParse;if (parse?.ok && view.structuredView === "tree") {@@ -1501,6 +1527,7 @@ function PreviewContent({<TextBackedPreviewattachmentId={state.attachmentId!}onDownload={onDownload}+ downloading={downloading}render={(text) => code(text, extensionToLanguage(state.filename))}/>);@@ -1543,10 +1570,12 @@ function DocumentSheet({function TextBackedPreview({attachmentId,onDownload,+ downloading,render,}: {attachmentId: string;onDownload: () => void;+ downloading: boolean;render: (text: string) => ReactNode;}) {const { t } = useT("editor");@@ -1566,6 +1595,7 @@ function TextBackedPreview({<UnsupportedFallbackmessage={t(($) => $.attachment.preview_too_large)}onDownload={onDownload}+ downloading={downloading}/>);}@@ -1574,6 +1604,7 @@ function TextBackedPreview({<UnsupportedFallbackmessage={t(($) => $.attachment.preview_unsupported)}onDownload={onDownload}+ downloading={downloading}/>);}@@ -1581,6 +1612,7 @@ function TextBackedPreview({<UnsupportedFallbackmessage={t(($) => $.attachment.preview_failed)}onDownload={onDownload}+ downloading={downloading}/>);}@@ -1593,9 +1625,11 @@ function TextBackedPreview({function UnsupportedFallback({message,onDownload,+ downloading,}: {message: string;onDownload: () => void;+ downloading: boolean;}) {const { t } = useT("editor");return (@@ -1606,8 +1640,14 @@ function UnsupportedFallback({type="button"className="inline-flex items-center gap-2 rounded-md border border-input bg-secondary px-3 py-1.5 text-body text-foreground transition-colors hover:bg-muted"onClick={onDownload}+ disabled={downloading}+ aria-busy={downloading}>- <Download className="size-4" />+ {downloading ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <Download className="size-4" />+ )}{t(($) => $.image.download)}</button></div>diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsxindex 216836405f..a7643a5584 100644--- a/packages/views/editor/attachment.test.tsx+++ b/packages/views/editor/attachment.test.tsx@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { render, screen, fireEvent, waitFor, act } from "@testing-library/react";import type { ReactElement, ReactNode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { Attachment as AttachmentRecord } from "@multica/core/types";@@ -1256,3 +1256,43 @@ describe("Attachment — blob URL GC (MUL-7741)", () => {expect(revokeObjectURLMock).not.toHaveBeenCalled();});});++describe("image download feedback", () => {+ it("shows pending feedback and blocks repeat clicks until completion", async () => {+ const pending = Promise.withResolvers<void>();+ downloadMock.mockReturnValueOnce(pending.promise);+ renderWithQuery(<Attachment attachment={{ kind: "record", attachment: makeRecord() }} />);+ const button = screen.getByRole("button", { name: "Download" });++ fireEvent.click(button);++ expect(button).toBeDisabled();+ expect(button).toHaveAttribute("aria-busy", "true");+ expect(button.querySelector(".animate-spin")).toBeInTheDocument();+ expect(button.closest(".image-toolbar")).toHaveStyle({ opacity: "1" });+ fireEvent.click(button);+ expect(downloadMock).toHaveBeenCalledExactlyOnceWith("att-1");++ await act(async () => pending.resolve());++ expect(button).toBeEnabled();+ expect(button).toHaveAttribute("aria-busy", "false");+ expect(button.querySelector(".animate-spin")).toBeNull();+ });++ it("keeps sibling images available while preparing a download", async () => {+ const pending = Promise.withResolvers<void>();+ downloadMock.mockReturnValueOnce(pending.promise);+ renderWithQuery(<>+ <Attachment attachment={{ kind: "record", attachment: makeRecord() }} />+ <Attachment attachment={{ kind: "record", attachment: makeRecord({ id: "att-2" }) }} />+ </>);+ const [first, second] = screen.getAllByRole("button", { name: "Download" });++ fireEvent.click(first!);+ fireEvent.click(second!);++ expect(downloadMock.mock.calls).toEqual([["att-1"], ["att-2"]]);+ await act(async () => pending.resolve());+ });+});diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsxindex d15eac53af..a46beb2e24 100644--- a/packages/views/editor/attachment.tsx+++ b/packages/views/editor/attachment.tsx@@ -29,6 +29,7 @@import {Download,+ Loader2,Link as LinkIcon,Maximize2,Trash2,@@ -52,6 +53,7 @@ import {} from "./hooks/use-inline-media-url";import { useDownloadAttachment } from "./use-download-attachment";import { AttachmentCard, AttachmentFileCard } from "./attachment-card";+import { useAttachmentDownloadState } from "./hooks/use-attachment-download-state";import { canOpenPreview, getPreviewKind, type PreviewKind } from "./utils/preview";import { imageDimensions } from "./utils/image-metadata";import "./styles/attachment.css";@@ -371,10 +373,9 @@ export function Attachment({const attachmentId =state.attachmentId ?? attachmentIdFromStorageURL(shareUrl, cdnDomain);if (attachmentId) {- download(attachmentId);- return;+ return download(attachmentId);}- if (shareUrl) openByUrl(shareUrl);+ if (shareUrl) return openByUrl(shareUrl);};if (kind === "image") {@@ -460,7 +461,7 @@ interface ImageAttachmentViewProps {editable?: boolean;selected?: boolean;onView: () => void;- onDownload: () => void;+ onDownload: () => void | Promise<unknown>;onDelete?: () => void;className?: string;}@@ -480,6 +481,7 @@ function ImageAttachmentView({className,}: ImageAttachmentViewProps) {const { t } = useT("editor");+ const { downloading, handleDownload } = useAttachmentDownloadState(onDownload);const handleCopyLink = async () => {if (await copyText(linkUrl)) {@@ -550,6 +552,7 @@ function ImageAttachmentView({{!uploading && src && (<spanclassName="image-toolbar"+ style={downloading ? { opacity: 1 } : undefined}onMouseDown={(e) => e.stopPropagation()}onClick={(e) => e.stopPropagation()}>@@ -564,8 +567,18 @@ function ImageAttachmentView({<DeferredTooltipcontent={t(($) => $.image.download)}trigger={- <button type="button" onClick={onDownload} aria-label={t(($) => $.image.download)}>- <Download className="size-3.5" />+ <button+ type="button"+ onClick={handleDownload}+ disabled={downloading}+ aria-busy={downloading}+ aria-label={t(($) => $.image.download)}+ >+ {downloading ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Download className="size-3.5" />+ )}</button>}/>diff --git a/packages/views/editor/hooks/use-attachment-download-state.test.tsx b/packages/views/editor/hooks/use-attachment-download-state.test.tsxnew file mode 100644index 0000000000..8acd2b0f78--- /dev/null+++ b/packages/views/editor/hooks/use-attachment-download-state.test.tsx@@ -0,0 +1,86 @@+import { describe, expect, it, vi } from "vitest";+import { act, renderHook } from "@testing-library/react";+import { useAttachmentDownloadState } from "./use-attachment-download-state";++describe("useAttachmentDownloadState", () => {+ it("blocks synchronous reentry before React renders the pending state", async () => {+ const pending = Promise.withResolvers<void>();+ const download = vi.fn(() => pending.promise);+ const { result } = renderHook(() => useAttachmentDownloadState(download));++ act(() => {+ result.current.handleDownload();+ result.current.handleDownload();+ });++ expect(download).toHaveBeenCalledOnce();+ expect(result.current.downloading).toBe(true);+ await act(async () => pending.resolve());+ expect(result.current.downloading).toBe(false);+ });++ it("allows retry after rejection", async () => {+ const pending = Promise.withResolvers<void>();+ const download = vi.fn<() => void | Promise<void>>().mockReturnValueOnce(pending.promise);+ const { result } = renderHook(() => useAttachmentDownloadState(download));+ act(() => result.current.handleDownload());++ await act(async () => pending.reject(new Error("download failed")));++ expect(result.current.downloading).toBe(false);+ act(() => result.current.handleDownload());+ expect(download).toHaveBeenCalledTimes(2);+ });++ it("keeps synchronous callbacks immediately available", () => {+ const download = vi.fn();+ const { result } = renderHook(() => useAttachmentDownloadState(download));++ act(() => result.current.handleDownload());+ act(() => result.current.handleDownload());++ expect(result.current.downloading).toBe(false);+ expect(download).toHaveBeenCalledTimes(2);+ });++ it("releases the guard if a synchronous callback throws", () => {+ const error = new Error("download failed");+ const download = vi.fn().mockImplementationOnce(() => {+ throw error;+ });+ const { result } = renderHook(() => useAttachmentDownloadState(download));++ act(() => expect(result.current.handleDownload).toThrow(error));++ expect(result.current.downloading).toBe(false);+ act(() => result.current.handleDownload());+ expect(download).toHaveBeenCalledTimes(2);+ });++ it("retains each file's pending state when the viewer switches files", async () => {+ const first = Promise.withResolvers<void>();+ const second = Promise.withResolvers<void>();+ const download = vi.fn().mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ const { result, rerender } = renderHook(+ ({ key }) => useAttachmentDownloadState(download, key),+ { initialProps: { key: "first" } },+ );+ act(() => result.current.handleDownload());++ rerender({ key: "second" });+ expect(result.current.downloading).toBe(false);+ act(() => result.current.handleDownload());++ rerender({ key: "first" });+ expect(result.current.downloading).toBe(true);+ act(() => result.current.handleDownload());+ expect(download).toHaveBeenCalledTimes(2);++ await act(async () => first.resolve());+ expect(result.current.downloading).toBe(false);+ rerender({ key: "second" });+ expect(result.current.downloading).toBe(true);+ await act(async () => second.resolve());+ expect(result.current.downloading).toBe(false);+ });+});diff --git a/packages/views/editor/hooks/use-attachment-download-state.ts b/packages/views/editor/hooks/use-attachment-download-state.tsnew file mode 100644index 0000000000..9d5a0e5a8d--- /dev/null+++ b/packages/views/editor/hooks/use-attachment-download-state.ts@@ -0,0 +1,36 @@+"use client";++import { useRef, useState } from "react";++export function useAttachmentDownloadState(+ onDownload: () => void | Promise<unknown>,+ attachmentKey = "",+) {+ const active = useRef(new Set<string>());+ const [pending, setPending] = useState<ReadonlySet<string>>(() => new Set());+ const handleDownload = () => {+ if (active.current.has(attachmentKey)) return;+ active.current.add(attachmentKey);+ const reset = () => {+ active.current.delete(attachmentKey);+ setPending((current) => {+ const next = new Set(current);+ next.delete(attachmentKey);+ return next;+ });+ };+ try {+ const result = onDownload();+ if (result && typeof result.then === "function") {+ setPending((current) => new Set(current).add(attachmentKey));+ void result.then(reset, reset);+ } else {+ active.current.delete(attachmentKey);+ }+ } catch (error) {+ reset();+ throw error;+ }+ };+ return { downloading: pending.has(attachmentKey), handleDownload };+}