diff --git a/frontend/src/components/Chat/ChatWindow.tsx b/frontend/src/components/Chat/ChatWindow.tsx index ff0d90bf8f..3ae8979c0d 100644 --- a/frontend/src/components/Chat/ChatWindow.tsx +++ b/frontend/src/components/Chat/ChatWindow.tsx @@ -2031,6 +2031,8 @@ export default function ChatWindow({ )} {editDraft === null && { }); describe("download handler", () => { + it("prevents overlapping downloads and enables retry after completion", async () => { + const user = userEvent.setup(); + let failDownload: (reason: Error) => void = () => { throw new Error("Download was not started"); }; + const pendingResponse = new Promise((_resolve, reject) => { + failDownload = reject; + }); + global.fetch = jest.fn().mockReturnValue(pendingResponse); + const messages: Message[] = [{ + role: "assistant", + content: "Here is the image", + timestamp: "2026-11-04T10:00:00.000Z", + attachments: [{ + type: "image", + name: "result.png", + url: "http://localhost/media/result.png", + mimeType: "image/png", + size: 1024, + }], + }]; + + render(); + const downloadButton = screen.getByTestId("download-btn-0-0"); + await user.click(downloadButton); + expect(downloadButton).toBeDisabled(); + expect(downloadButton).toHaveAttribute("aria-busy", "true"); + await user.click(downloadButton); + expect(global.fetch).toHaveBeenCalledTimes(1); + + failDownload(new Error("Network unavailable")); + expect(await screen.findByRole("alert")).toHaveTextContent("Download failed. Please try again."); + expect(downloadButton).toBeEnabled(); + expect(downloadButton).toHaveAttribute("aria-busy", "false"); + }); + + it("does not download HTTP error bodies and lets the user retry", async () => { + const user = userEvent.setup(); + const mockBlob = new Blob(["image"], { type: "image/png" }); + const mockObjectUrl = "blob:http://localhost/retry"; + const failedResponseBlob = new Blob([JSON.stringify({ detail: "Not found" })], { type: "application/json" }); + const failedBlob = jest.fn().mockResolvedValue(failedResponseBlob); + global.fetch = jest.fn() + .mockResolvedValueOnce({ ok: false, status: 404, blob: failedBlob }) + .mockResolvedValueOnce({ ok: true, status: 200, blob: () => Promise.resolve(mockBlob) }); + global.URL.createObjectURL = jest.fn().mockReturnValue(mockObjectUrl); + global.URL.revokeObjectURL = jest.fn(); + const clickSpy = jest.fn(); + const origCreateElement = document.createElement.bind(document); + jest.spyOn(document, "createElement").mockImplementation((tag: string) => { + const element = origCreateElement(tag); + if (tag === "a") jest.spyOn(element, "click").mockImplementation(clickSpy); + return element; + }); + + const messages: Message[] = [{ + role: "assistant", + content: "Here is the image", + timestamp: new Date().toISOString(), + attachments: [{ + type: "image", + name: "result.png", + url: "http://localhost/media/result.png", + mimeType: "image/png", + size: 1024, + }], + }]; + + render(); + const downloadButton = screen.getByTestId("download-btn-0-0"); + + await user.click(downloadButton); + expect(await screen.findByRole("alert")).toHaveTextContent("Download failed. Please try again."); + expect(downloadButton).toHaveTextContent("Retry download"); + expect(failedBlob).not.toHaveBeenCalled(); + expect(global.URL.createObjectURL).not.toHaveBeenCalled(); + expect(clickSpy).not.toHaveBeenCalled(); + + await user.click(downloadButton); + await waitFor(() => expect(clickSpy).toHaveBeenCalledTimes(1)); + expect(downloadButton).not.toHaveTextContent("Retry download"); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + expect(global.URL.revokeObjectURL).toHaveBeenCalledWith(mockObjectUrl); + + jest.restoreAllMocks(); + }); + + it("does not carry a failed download error into a different conversation", async () => { + const user = userEvent.setup(); + const failedBlob = jest.fn().mockResolvedValue( + new Blob([JSON.stringify({ detail: "Not found" })], { type: "application/json" }), + ); + global.fetch = jest.fn().mockResolvedValue({ + ok: false, + status: 404, + blob: failedBlob, + }); + const firstMessages: Message[] = [{ + role: "assistant", + content: "First conversation", + timestamp: "2026-11-04T10:00:00.000Z", + attachments: [{ + type: "image", + name: "same.png", + url: "http://localhost/media/same.png", + mimeType: "image/png", + size: 1024, + }], + }]; + const secondMessages: Message[] = [{ + role: "assistant", + content: "Second conversation", + timestamp: "2026-11-04T10:00:00.000Z", + attachments: [{ + type: "image", + name: "same.png", + url: "http://localhost/media/same.png", + mimeType: "image/png", + size: 1024, + }], + }]; + + const { rerender } = render(); + await user.click(screen.getByTestId("download-btn-0-0")); + expect(await screen.findByRole("alert")).toHaveTextContent("Download failed. Please try again."); + expect(failedBlob).not.toHaveBeenCalled(); + + rerender(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + + jest.restoreAllMocks(); + }); + it("should trigger download on click", async () => { const user = userEvent.setup(); // Mock fetch + blob const mockBlob = new Blob(["test"], { type: "image/png" }); const mockObjectUrl = "blob:http://localhost/mock-uuid"; - global.fetch = jest.fn().mockResolvedValue({ blob: () => Promise.resolve(mockBlob) }); + global.fetch = jest.fn().mockResolvedValue({ ok: true, status: 200, blob: () => Promise.resolve(mockBlob) }); global.URL.createObjectURL = jest.fn().mockReturnValue(mockObjectUrl); global.URL.revokeObjectURL = jest.fn(); diff --git a/frontend/src/components/Chat/MessageList.tsx b/frontend/src/components/Chat/MessageList.tsx index 08e4814a8d..eefe9b10a2 100644 --- a/frontend/src/components/Chat/MessageList.tsx +++ b/frontend/src/components/Chat/MessageList.tsx @@ -39,6 +39,8 @@ import ScoreDetails from './ScoreDetails' interface MessageListProps { onEditConversation?: () => void + /** Stable identity for the conversation; isolates transient download errors across switches. */ + conversationId?: string | null messages: Message[] /** Copy this message to the input box of the current conversation */ onCopyToInput?: (messageIndex: number) => void @@ -410,7 +412,7 @@ function MessageScores({ scores, groupId }: { scores: DisplayScore[]; groupId: s * line of compact text. */ export default function MessageList({ - messages, onCopyToInput, onCopyToNewConversation, onCopyToNewAttack, onUseInTechnique, copyConversationDisabled = false, + conversationId, messages, onCopyToInput, onCopyToNewConversation, onCopyToNewAttack, onUseInTechnique, copyConversationDisabled = false, copyConversationDisabledReason, newConversationDisabledReason, getBranchConversationDisabledReason, getBranchConversationDescription, copyToInputDisabledReason, isLoading, savedEvidence = false, announceUpdates = !savedEvidence, showGenerationInfo = false, globalMarkdown = false, onEditConversation, @@ -421,12 +423,27 @@ export default function MessageList({ const followLatestRef = useRef(true) const copyMenuId = useId() const isCopyConversationDisabled = copyConversationDisabled || Boolean(copyConversationDisabledReason) + const [downloadErrors, setDownloadErrors] = useState>({}) + const activeDownloads = useRef(new Set()) + const [pendingDownloads, setPendingDownloads] = useState>(new Set()) + + const handleDownload = async (att: MessageAttachment, downloadKey: string) => { + if (activeDownloads.current.has(downloadKey)) return + activeDownloads.current.add(downloadKey) + setPendingDownloads(new Set(activeDownloads.current)) + setDownloadErrors((current) => { + const next = { ...current } + delete next[downloadKey] + return next + }) - const handleDownload = async (att: MessageAttachment) => { try { // Convert the URL (data URI or same-origin) to a Blob, then create // an object URL so the browser reliably triggers a file download. const resp = await fetch(att.url) + if (!resp.ok) { + throw new Error(`Media download failed with HTTP ${resp.status}`) + } const blob = await resp.blob() const objectUrl = URL.createObjectURL(blob) const link = document.createElement('a') @@ -437,8 +454,11 @@ export default function MessageList({ document.body.removeChild(link) URL.revokeObjectURL(objectUrl) } catch { - // Fallback: open in a new tab rather than navigating away - window.open(att.url, '_blank') + // Keep the download action available so the user can retry. + setDownloadErrors((current) => ({ ...current, [downloadKey]: 'Download failed. Please try again.' })) + } finally { + activeDownloads.current.delete(downloadKey) + setPendingDownloads(new Set(activeDownloads.current)) } } @@ -699,18 +719,37 @@ export default function MessageList({ )} {/* Download: non-text media only */} - {!isUser && message.attachments && message.attachments.filter(a => a.type !== 'file' && a.url).map((att, ai) => ( - - + + {downloadErrors[downloadKey] &&
{downloadErrors[downloadKey]}
} + + ) + })} )}