Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions frontend/src/components/Chat/ChatWindow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2031,6 +2031,8 @@ export default function ChatWindow({
</MessageBar>
)}
{editDraft === null && <MessageList
key={viewedConversationId ?? 'no-conversation'}
conversationId={viewedConversationId}
messages={isEvidenceUnavailable ? [] : messages}
showGenerationInfo={activeTarget?.capabilities?.supports_temperature !== false}
onCopyToInput={handleCopyToInput}
Expand Down
135 changes: 133 additions & 2 deletions frontend/src/components/Chat/MessageList.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render, screen, fireEvent, within } from "@testing-library/react";
import { render, screen, fireEvent, within, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import MessageList from "./MessageList";
Expand Down Expand Up @@ -2296,13 +2296,144 @@ describe("MessageList", () => {
});

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<Response>((_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(<TestWrapper><MessageList messages={messages} /></TestWrapper>);
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(<TestWrapper><MessageList messages={messages} /></TestWrapper>);
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(<TestWrapper><MessageList conversationId="conversation-a" messages={firstMessages} /></TestWrapper>);
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(<TestWrapper><MessageList conversationId="conversation-b" messages={secondMessages} /></TestWrapper>);
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();

Expand Down
71 changes: 55 additions & 16 deletions frontend/src/components/Chat/MessageList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -421,12 +423,27 @@ export default function MessageList({
const followLatestRef = useRef(true)
const copyMenuId = useId()
const isCopyConversationDisabled = copyConversationDisabled || Boolean(copyConversationDisabledReason)
const [downloadErrors, setDownloadErrors] = useState<Record<string, string>>({})
const activeDownloads = useRef(new Set<string>())
const [pendingDownloads, setPendingDownloads] = useState<Set<string>>(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')
Expand All @@ -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))
}
}

Expand Down Expand Up @@ -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) => (
<Tooltip key={ai} content={`Download ${att.name}`} relationship="label">
<Button
appearance="subtle"
size="small"
icon={<ArrowDownloadRegular />}
onClick={() => handleDownload(att)}
data-testid={`download-btn-${index}-${ai}`}
className={styles.messageActionButton}
/>
</Tooltip>
))}
{!isUser && message.attachments && message.attachments.filter(a => a.type !== 'file' && a.url).map((att, ai) => {
// Key download state to the message and attachment, not their array positions.
// MessageList can remain mounted while the user switches conversations.
const downloadKey = JSON.stringify([
conversationId ?? null,
message.timestamp,
message.role,
message.content,
att.url,
att.name,
])
return (
<div key={downloadKey}>
<Tooltip content={`Download ${att.name}`} relationship="label">
<Button
appearance="subtle"
size="small"
icon={<ArrowDownloadRegular />}
disabled={pendingDownloads.has(downloadKey)}
aria-busy={pendingDownloads.has(downloadKey)}
onClick={() => handleDownload(att, downloadKey)}
data-testid={`download-btn-${index}-${ai}`}
className={styles.messageActionButton}
>
{downloadErrors[downloadKey] && 'Retry download'}
</Button>
</Tooltip>
{downloadErrors[downloadKey] && <div role="alert">{downloadErrors[downloadKey]}</div>}
</div>
)
})}

</div>
)}
Expand Down
Loading