fix(webui): separate file cards from media previews

This commit is contained in:
Xubin Ren committed 2026-10-24 23:55:10 +08:00
1 parent d6cc08f335
commit 0b22c1875a
21 files changed
+432 -44

No files matched your search

+1 -1
View File
@@ -121,7 +121,7 @@ Selecting a Markdown file opens **Preview**; **Source** shows the original text.
Text previews are limited to 384 KiB and indicate truncation. Very large or minified source may remain plain text. Image previews support PNG, JPEG, GIF and WebP up to 8 MiB. HTML and SVG files display as read-only source. Text previews are limited to 384 KiB and indicate truncation. Very large or minified source may remain plain text. Image previews support PNG, JPEG, GIF and WebP up to 8 MiB. HTML and SVG files display as read-only source.
Explicit Markdown images appear inline; image attachments use a gallery. Ordinary image file links open the preview instead. Explicit Markdown images appear inline; image attachments use a gallery. Other files appear as compact download cards below the image and video previews, with a file-type icon, filename and download action. File-type icons do not indicate preview support. Ordinary image file links open the preview instead.
Mermaid diagrams render after the reply finishes. The source remains available if rendering fails. Links, external images and executable HTML inside diagrams are disabled. Mermaid diagrams render after the reply finishes. The source remains available if rendering fails. Links, external images and executable HTML inside diagrams are disabled.
@@ -0,0 +1,68 @@
import { MessageBubble } from "@/components/MessageBubble";
import type { UIMediaAttachment, UIMessage } from "@/lib/types";
import sampleVideo from "@/dev/gallery/fixtures/sample.webm";
function image(name: string, color: string): UIMediaAttachment {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="200"><rect width="320" height="200" fill="${color}"/><circle cx="160" cy="100" r="55" fill="white" fill-opacity=".55"/></svg>`;
return { kind: "image", name, url: `data:image/svg+xml,${encodeURIComponent(svg)}` };
}
// A valid 22-byte empty ZIP keeps the native browser download deterministic.
const archive: UIMediaAttachment = { kind: "file", name: "archive.zip", url: "data:application/zip;base64,UEsFBgAAAAAAAAAAAAAAAAAAAAAAAA==" };
const files: UIMediaAttachment[] = [
{ ...archive, name: "release-deliverables-with-a-very-long-English-filename-for-layout-regression.zip" },
{ kind: "file", name: "项目交付资料与详细验收记录包含中英文的超长文件名称-final-review.pdf", url: "/fixture/report.pdf" },
{ kind: "file", url: "/fixture/unnamed" },
];
const samples: { label: string; message: UIMessage }[] = [
{
label: "Assistant mixed attachments",
message: {
id: "assistant-mixed", role: "assistant", content: "Three image studies and the source archive.", createdAt: 1,
media: [image("Coral study.svg", "#e88b7b"), archive, image("Blue study.svg", "#83a9d8"), image("Green study.svg", "#83ba9c")],
},
},
{
label: "User mixed attachments",
message: {
id: "user-mixed", role: "user", content: "Please review this image and archive.", createdAt: 2,
media: [archive, image("User study.svg", "#c9a2d7")],
},
},
{
label: "Multiple files and long names",
message: {
id: "multiple-files", role: "assistant", content: "Download the full deliverables.", createdAt: 3,
media: files,
},
},
{
label: "User multiple files",
message: { id: "user-files", role: "user", content: "Review these files together.", createdAt: 4, media: files },
},
{
label: "Playable video",
message: { id: "video", role: "assistant", content: "A small playable clip.", createdAt: 4, media: [{ kind: "video", name: "sample.webm", url: sampleVideo }] },
},
{
label: "Retry video",
message: { id: "retry-video", role: "assistant", content: "Retry when the clip becomes available.", createdAt: 5, media: [{ kind: "video", name: "retry.webm", url: "/fixture/retry.webm" }] },
},
{
label: "Pending attachment",
message: { id: "pending", role: "user", content: "Uploading the archive.", createdAt: 6, deliveryStatus: "sending", media: [{ kind: "file", name: "pending.zip" }] },
},
{
label: "Unavailable attachment",
message: { id: "unavailable", role: "assistant", content: "This file is no longer available.", createdAt: 7, media: [{ kind: "file", name: "unavailable.pdf" }] },
},
];
export function AttachmentLayoutFixture() {
return <main className="space-y-8 px-4 py-6">
{samples.map(({ label, message }) => <section key={message.id} aria-label={label}>
<h2 className="mb-3 text-xs font-medium text-muted-foreground">{label}</h2>
<MessageBubble message={message} />
</section>)}
</main>;
}
+192
View File
@@ -0,0 +1,192 @@
import { readFile } from "node:fs/promises";
import { expect, test, type Locator, type Page } from "@playwright/test";
const archiveBytes = Buffer.from("504b0506000000000000000000000000000000000000", "hex");
async function openAttachments(page: Page, width = 1024, theme = "light", locale = "en") {
await page.setViewportSize({ width, height: 900 });
await page.emulateMedia({ reducedMotion: "reduce", colorScheme: theme === "dark" ? "dark" : "light" });
await page.addInitScript((language) => localStorage.setItem("nanobot.locale", language), locale);
await page.goto("/browser/fixture.html?case=attachments");
await expect(page.getByRole("region", { name: "Assistant mixed attachments" }).locator("img")).toHaveCount(3);
// The root element does not necessarily exist during addInitScript.
await page.evaluate((dark) => document.documentElement.classList.toggle("dark", dark), theme === "dark");
expect(await page.locator("html").evaluate((element) => element.classList.contains("dark"))).toBe(theme === "dark");
const brightness = await page.locator("body").evaluate((element) => {
const channels = getComputedStyle(element).backgroundColor.match(/[\d.]+/g)!.slice(0, 3).map(Number);
return channels.reduce((sum, channel) => sum + channel, 0) / 3;
});
if (theme === "dark") expect(brightness, "dark theme must render a dark background").toBeLessThan(100);
else expect(brightness, "light theme must render a light background").toBeGreaterThan(200);
}
async function bounds(locator: Locator) {
const box = await locator.boundingBox();
expect(box).not.toBeNull();
return box!;
}
for (const width of [1024, 360]) {
for (const theme of ["light", "dark"]) {
test(`mixed attachments stay compact, aligned and readable at ${width}px in ${theme}`, async ({ page }, testInfo) => {
// The two widths also cover both localized download names, without a second matrix.
const chinese = width === 360;
await page.route("**/fixture/retry.webm", (route) => route.fulfill({ status: 503, body: "Temporarily unavailable" }));
await openAttachments(page, width, theme, chinese ? "zh-CN" : "en");
await expect(page.getByRole("button", { name: chinese ? "重试" : "Retry", exact: true })).toBeVisible();
await expect.poll(() => page.locator("img").evaluateAll((images) => images.every((image) => image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0))).toBe(true);
const video = page.getByRole("region", { name: "Playable video", exact: true }).locator("video");
await expect.poll(() => video.evaluate((element: HTMLVideoElement) => element.readyState)).toBeGreaterThanOrEqual(1);
await page.screenshot({ path: testInfo.outputPath("layout.png"), fullPage: true });
await testInfo.attach("attachment layout", { path: testInfo.outputPath("layout.png"), contentType: "image/png" });
await page.getByRole("region", { name: "Assistant mixed attachments" }).screenshot({ path: testInfo.outputPath("assistant-three-images-archive.png") });
await testInfo.attach("three images and ZIP", { path: testInfo.outputPath("assistant-three-images-archive.png"), contentType: "image/png" });
for (const role of ["Assistant", "User"]) {
const region = page.getByRole("region", { name: `${role} mixed attachments`, exact: true });
const card = region.locator("a[download]");
await expect(card).toHaveCount(1);
const file = await bounds(card);
const regionBox = await bounds(region);
const imageBoxes = await region.locator("img").evaluateAll((images) => images.map((image) => {
const rect = image.getBoundingClientRect();
return { bottom: rect.bottom, left: rect.left, right: rect.right };
}));
await testInfo.attach(`${role} geometry`, { body: JSON.stringify({ file, region: regionBox, images: imageBoxes }, null, 2), contentType: "application/json" });
expect(file.height, `${role} file must not stretch to the image row height`).toBeLessThanOrEqual(80);
expect(file.y, `${role} file belongs below all images`).toBeGreaterThanOrEqual(Math.max(...imageBoxes.map((image) => image.bottom)));
if (role === "Assistant") {
expect(Math.abs(file.x - regionBox.x)).toBeLessThanOrEqual(1);
expect(Math.abs(Math.min(...imageBoxes.map((image) => image.left)) - regionBox.x)).toBeLessThanOrEqual(2);
} else {
const right = regionBox.x + regionBox.width;
expect(Math.abs(file.x + file.width - right)).toBeLessThanOrEqual(1);
expect(Math.abs(Math.max(...imageBoxes.map((image) => image.right)) - right)).toBeLessThanOrEqual(2);
}
await expect(card).toHaveAccessibleName(`${chinese ? "下载" : "Download"} archive.zip`);
await expect(card.getByText("ZIP", { exact: true })).toBeVisible();
}
const files = page.getByRole("region", { name: "Multiple files and long names" }).locator("a[download]");
await expect(files).toHaveCount(3);
const userFiles = page.getByRole("region", { name: "User multiple files", exact: true });
const userBubble = await bounds(userFiles.locator(":scope > div"));
const userCards = userFiles.locator("a[download]");
await expect(userCards).toHaveCount(3);
const userCardBoxes = await Promise.all((await userCards.all()).map(bounds));
await testInfo.attach("User multiple files geometry", { body: JSON.stringify({ bubble: userBubble, files: userCardBoxes }, null, 2), contentType: "application/json" });
for (const box of userCardBoxes) {
expect(box.x, "user file stays inside its message bubble").toBeGreaterThanOrEqual(userBubble.x);
expect(box.x + box.width, "user file stays inside its message bubble").toBeLessThanOrEqual(userBubble.x + userBubble.width + 1);
}
for (const card of await page.locator("a[download]").all()) {
const box = await bounds(card);
expect(box.height).toBeLessThanOrEqual(80);
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(width);
const icon = card.locator("svg.lucide-download");
await expect(icon).toBeVisible();
const iconBox = await bounds(icon);
expect(iconBox.width).toBeGreaterThanOrEqual(12);
expect(iconBox.x).toBeGreaterThanOrEqual(box.x);
expect(iconBox.x + iconBox.width).toBeLessThanOrEqual(box.x + box.width);
expect(iconBox.y).toBeGreaterThanOrEqual(box.y);
expect(iconBox.y + iconBox.height).toBeLessThanOrEqual(box.y + box.height);
}
for (const card of [files.nth(0), files.nth(1)]) {
const name = card.getByText(/release-deliverables|项目交付资料/);
await expect(name).toHaveCSS("text-overflow", "ellipsis");
expect(await name.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(true);
const nameBox = await bounds(name);
expect(nameBox.x + nameBox.width).toBeLessThanOrEqual((await bounds(card.locator("svg.lucide-download"))).x);
}
await expect(files.nth(1).getByText("PDF", { exact: true })).toBeVisible();
await expect(files.nth(2)).toHaveAccessibleName(chinese ? "下载 文件附件" : "Download File attachment");
for (const [label, filename, status] of [
["Pending attachment", "pending.zip", chinese ? "发送中…" : "Sending…"],
["Unavailable attachment", "unavailable.pdf", chinese ? "附件不可用" : "Attachment unavailable"],
]) {
const region = page.getByRole("region", { name: label, exact: true });
await expect(region.getByText(filename, { exact: true })).toBeVisible();
await expect(region.getByText(status, { exact: true }).first()).toBeVisible();
// A replay placeholder has no download capability until it has a URL.
await expect(region.getByRole("link")).toHaveCount(0);
}
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width);
});
}
}
test("image lightbox and file download remain keyboard accessible", async ({ page }, testInfo) => {
await page.route("**/fixture/retry.webm", (route) => route.fulfill({ status: 503, body: "Temporarily unavailable" }));
await openAttachments(page);
const region = page.getByRole("region", { name: "Assistant mixed attachments" });
const firstImage = region.getByRole("button", { name: "View image: Coral study.svg", exact: true });
await page.keyboard.press("Tab");
await expect(firstImage).toBeFocused();
await page.keyboard.press("Enter");
await expect(page.getByRole("dialog", { name: "Coral study.svg" })).toBeVisible();
await page.keyboard.press("ArrowRight");
await expect(page.getByRole("dialog", { name: "Blue study.svg" })).toBeVisible();
await page.keyboard.press("End");
await expect(page.getByRole("dialog", { name: "Green study.svg" })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("lightbox.png") });
await testInfo.attach("image lightbox", { path: testInfo.outputPath("lightbox.png"), contentType: "image/png" });
await page.keyboard.press("Escape");
await expect(page.getByRole("dialog")).toHaveCount(0);
await expect(firstImage).toBeFocused();
for (let step = 0; step < 3; step++) await page.keyboard.press("Tab");
const downloadLink = region.getByRole("link", { name: "Download archive.zip", exact: true });
await expect(downloadLink).toBeFocused();
expect(await downloadLink.evaluate((element) => element.matches(":focus-visible"))).toBe(true);
expect(await downloadLink.evaluate((element) => getComputedStyle(element).boxShadow)).not.toBe("none");
await page.screenshot({ path: testInfo.outputPath("keyboard-focus.png") });
await testInfo.attach("keyboard download focus", { path: testInfo.outputPath("keyboard-focus.png"), contentType: "image/png" });
const downloadEvent = page.waitForEvent("download");
await page.keyboard.press("Enter");
const download = await downloadEvent;
expect(download.suggestedFilename()).toBe("archive.zip");
expect(await download.failure()).toBeNull();
expect((await readFile((await download.path())!)).toString("hex")).toBe(archiveBytes.toString("hex"));
await download.saveAs(testInfo.outputPath("archive.zip"));
await expect(page).toHaveURL(/case=attachments$/);
});
test("native video controls play the clip and retry recovers a failed media request", async ({ page }, testInfo) => {
const clip = await readFile("src/dev/gallery/fixtures/sample.webm");
let available = false;
let attempts = 0;
await page.route("**/fixture/retry.webm", (route) => {
attempts++;
return available
? route.fulfill({ contentType: "video/webm", body: clip })
: route.fulfill({ status: 503, body: "Temporarily unavailable" });
});
await openAttachments(page, 360);
const ready = page.getByRole("region", { name: "Playable video", exact: true }).getByLabel("Video attachment: sample.webm", { exact: true });
await expect(ready).toHaveJSProperty("controls", true);
await expect.poll(() => ready.evaluate((element: HTMLVideoElement) => element.readyState)).toBeGreaterThanOrEqual(2);
await ready.focus();
await page.keyboard.press("Space");
await expect.poll(() => ready.evaluate((element: HTMLVideoElement) => element.currentTime)).toBeGreaterThan(0);
await ready.evaluate((element: HTMLVideoElement) => element.pause());
const retryRegion = page.getByRole("region", { name: "Retry video", exact: true });
await expect(retryRegion.getByText("Attachment unavailable", { exact: true })).toBeVisible();
await expect(retryRegion.getByRole("link")).toHaveCount(0);
const failedAttempts = attempts;
expect(failedAttempts).toBeGreaterThan(0);
available = true;
await retryRegion.getByRole("button", { name: "Retry", exact: true }).click();
const recovered = retryRegion.getByLabel("Video attachment: retry.webm", { exact: true });
await expect(recovered).toHaveJSProperty("controls", true);
await expect.poll(() => recovered.evaluate((element: HTMLVideoElement) => element.readyState)).toBeGreaterThanOrEqual(2);
expect(attempts).toBeGreaterThan(failedAttempts);
await recovered.focus();
await page.keyboard.press("Space");
await expect.poll(() => recovered.evaluate((element: HTMLVideoElement) => element.currentTime)).toBeGreaterThan(0);
await expect(retryRegion.getByRole("button", { name: "Retry", exact: true })).toHaveCount(0);
await recovered.evaluate((element: HTMLVideoElement) => element.pause());
await page.screenshot({ path: testInfo.outputPath("video-recovered.png"), fullPage: true });
await testInfo.attach("video retry recovered", { path: testInfo.outputPath("video-recovered.png"), contentType: "image/png" });
});
+4 -1
View File
@@ -37,6 +37,7 @@ import { WorkspaceAlignmentFixture } from "./workspace-alignment-fixture";
import { ComposerActionFixture } from "./composer-action-fixture"; import { ComposerActionFixture } from "./composer-action-fixture";
import { MobileChatLayoutFixture } from "./mobile-chat-layout-fixture"; import { MobileChatLayoutFixture } from "./mobile-chat-layout-fixture";
import { DisplayMathFixture } from "./display-math-fixture"; import { DisplayMathFixture } from "./display-math-fixture";
import { AttachmentLayoutFixture } from "./attachment-layout-fixture";
const history: UIMessage[] = [ const history: UIMessage[] = [
{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 }, { id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },
@@ -210,7 +211,9 @@ if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi()
if (parameters.get("case") === "idle-compaction") installIdleCompactionApi(); if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();
await initializeI18n(); await initializeI18n();
createRoot(document.getElementById("root")!).render(<TooltipProvider> createRoot(document.getElementById("root")!).render(<TooltipProvider>
{parameters.get("case") === "mobile-chat-layout" {parameters.get("case") === "attachments"
? <AttachmentLayoutFixture />
: parameters.get("case") === "mobile-chat-layout"
? <ClientProvider client={railClient} token="fixture"><MobileChatLayoutFixture parameters={parameters} /></ClientProvider> ? <ClientProvider client={railClient} token="fixture"><MobileChatLayoutFixture parameters={parameters} /></ClientProvider>
: parameters.get("case") === "composer-action" : parameters.get("case") === "composer-action"
? <ComposerActionFixture parameters={parameters} /> ? <ComposerActionFixture parameters={parameters} />
+31 -27
View File
@@ -1,5 +1,6 @@
import { useState, type ReactNode } from "react"; import { useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Download } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { UIMediaAttachment } from "@/lib/types"; import type { UIMediaAttachment } from "@/lib/types";
@@ -61,58 +62,61 @@ export function AttachmentTile({ attachment, className, inline = false, variant
); );
} }
const fileKind = attachment.kind === "file" const filePath = attachment.name || attachment.url?.split(/[?#]/, 1)[0] || "";
? fileKindForPath(attachment.name || attachment.url || "") const fileKind = attachment.kind === "file" ? fileKindForPath(filePath) : attachment.kind;
: attachment.kind; const name = attachment.name || label;
const available = hasUrl && !failed;
const extension = attachment.name?.match(/\.(tar\.(?:gz|bz2|xz)|[a-z0-9]{1,12})$/i)?.[1];
const details = available ? extension?.toUpperCase() || label
: pending ? t("message.delivery.sending") : t("message.attachmentUnavailable", { defaultValue: "Attachment unavailable" });
const cardClassName = cn(
"not-prose flex w-72 min-w-0 max-w-full items-center gap-3 rounded-control",
"border border-border/60 bg-muted/40 px-3 py-2.5 text-sm text-muted-foreground",
variant === "compact" && "w-56 gap-2 px-2.5 py-2 text-xs",
className,
);
const body = ( const body = (
<> <>
<FileReferenceIcon kind={fileKind} className="size-4" /> <span className={cn("flex size-9 shrink-0 items-center justify-center rounded-compact bg-background/70", variant === "compact" && "size-8")}>
<span className="min-w-0 truncate">{attachment.name ?? label}</span> <FileReferenceIcon kind={fileKind} className={variant === "compact" ? "size-4" : "size-5"} />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-foreground">{name}</span>
<span className="block break-words text-xs leading-4">{details}</span>
</span>
</> </>
); );
if (hasUrl && !failed) { if (available) {
return ( return (
<a <a
href={attachment.url} href={attachment.url}
download={attachment.name ?? label} download={name}
title={attachment.name ?? undefined} title={name}
aria-label={label} aria-label={t("message.downloadAttachment", { name })}
className={cn( className={cn(
"flex max-w-[18rem] items-center gap-2 rounded-control", cardClassName,
"border border-border/60 bg-muted/40 px-3 py-2 text-xs text-muted-foreground",
"transition-colors hover:bg-muted/55 hover:text-foreground", "transition-colors hover:bg-muted/55 hover:text-foreground",
variant === "compact" && "max-w-[14rem] rounded-xl px-2.5 py-1.5 text-[11.5px]", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
className,
)} )}
> >
{body} {body}
<Download aria-hidden strokeWidth={1.75} className="size-4 shrink-0" />
</a> </a>
); );
} }
const Frame = inline ? "span" : "div";
return ( return (
<div <Frame className={cardClassName} title={name} aria-label={attachment.name ? `${label}: ${name}` : label}>
className={cn(
"flex max-w-[18rem] items-center gap-2 rounded-control",
"border border-border/60 bg-muted/35 px-3 py-2 text-xs text-muted-foreground",
variant === "compact" && "max-w-[14rem] rounded-xl px-2.5 py-1.5 text-[11.5px]",
className,
)}
title={attachment.name ?? undefined}
aria-label={label}
>
{body} {body}
<span className="text-xs text-muted-foreground">
{pending ? t("message.delivery.sending") : t("message.attachmentUnavailable", { defaultValue: "Attachment unavailable" })}
</span>
{attachment.kind === "video" && failed && !pending ? ( {attachment.kind === "video" && failed && !pending ? (
<button type="button" onClick={() => setFailedUrl(undefined)} <button type="button" onClick={() => setFailedUrl(undefined)}
className="shrink-0 rounded-sm px-1 text-foreground underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2"> className="shrink-0 rounded-sm px-1 text-foreground underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2">
{t("common.retry")} {t("common.retry")}
</button> </button>
) : null} ) : null}
</div> </Frame>
); );
} }
+43 -1
View File
@@ -1,5 +1,5 @@
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type MouseEvent, type HTMLAttributes } from "react"; import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type MouseEvent, type HTMLAttributes } from "react";
import { File, FileCode2, FileImage, FileJson2, FileText, FileVideo2, type LucideIcon } from "lucide-react"; import { File, FileArchive, FileAudio, FileChartColumn, FileCode2, FileImage, FileJson2, FileSpreadsheet, FileText, FileVideo2, type LucideIcon } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { FileActions, useFilePreviewLoader } from "@/components/FileActions"; import { FileActions, useFilePreviewLoader } from "@/components/FileActions";
import { inferMediaKind } from "@/lib/media"; import { inferMediaKind } from "@/lib/media";
@@ -14,15 +14,20 @@ import { cn } from "@/lib/utils";
export type FileReferenceKind = export type FileReferenceKind =
| "default" | "default"
| "archive"
| "audio"
| "css" | "css"
| "document"
| "html" | "html"
| "image" | "image"
| "javascript" | "javascript"
| "json" | "json"
| "markdown" | "markdown"
| "notebook" | "notebook"
| "presentation"
| "python" | "python"
| "react" | "react"
| "spreadsheet"
| "text" | "text"
| "typescript" | "typescript"
| "video"; | "video";
@@ -232,6 +237,38 @@ export function fileKindForPath(path: string): FileReferenceKind {
return "default"; return "default";
} }
switch (ext) { switch (ext) {
case "zip":
case "7z":
case "rar":
case "tar":
case "gz":
case "bz2":
case "xz":
case "tgz":
return "archive";
case "mp3":
case "wav":
case "ogg":
case "m4a":
case "flac":
case "aac":
return "audio";
case "pdf":
case "doc":
case "docx":
case "odt":
case "rtf":
return "document";
case "xls":
case "xlsx":
case "csv":
case "tsv":
case "ods":
return "spreadsheet";
case "ppt":
case "pptx":
case "odp":
return "presentation";
case "avif": case "avif":
return "image"; return "image";
case "py": case "py":
@@ -273,15 +310,20 @@ export function fileKindForPath(path: string): FileReferenceKind {
const FILE_ICONS = { const FILE_ICONS = {
default: File, default: File,
archive: FileArchive,
audio: FileAudio,
css: FileCode2, css: FileCode2,
document: FileText,
html: FileCode2, html: FileCode2,
image: FileImage, image: FileImage,
javascript: FileCode2, javascript: FileCode2,
json: FileJson2, json: FileJson2,
markdown: FileText, markdown: FileText,
notebook: FileCode2, notebook: FileCode2,
presentation: FileChartColumn,
python: FileCode2, python: FileCode2,
react: FileCode2, react: FileCode2,
spreadsheet: FileSpreadsheet,
text: FileText, text: FileText,
typescript: FileCode2, typescript: FileCode2,
video: FileVideo2, video: FileVideo2,
+17 -7
View File
@@ -651,32 +651,42 @@ function MessageMedia({
if (media.length === 0) return null; if (media.length === 0) return null;
const images: UIImage[] = []; const images: UIImage[] = [];
const seen = new Set<string>(); const seen = new Set<string>();
const nonImages: UIMediaAttachment[] = []; const videos: UIMediaAttachment[] = [];
const files: UIMediaAttachment[] = [];
for (const item of media) { for (const item of media) {
const normalized = toMediaAttachment(item); const normalized = toMediaAttachment(item);
if (normalized.kind === "image") { if (normalized.kind === "image") {
if (normalized.url && (inlineImages.has(normalized.url) || seen.has(normalized.url))) continue; if (normalized.url && (inlineImages.has(normalized.url) || seen.has(normalized.url))) continue;
if (normalized.url) seen.add(normalized.url); if (normalized.url) seen.add(normalized.url);
images.push({ url: normalized.url, name: normalized.name }); images.push({ url: normalized.url, name: normalized.name });
} else if (normalized.kind === "video") {
videos.push(normalized);
} else { } else {
nonImages.push(normalized); files.push(normalized);
} }
} }
if (images.length === 0 && nonImages.length === 0) return null; if (images.length === 0 && videos.length === 0 && files.length === 0) return null;
return ( return (
<div <div
className={cn( className={cn(
"mt-2 flex flex-wrap gap-2", "mt-2 flex min-w-0 max-w-full flex-col gap-2",
align === "right" ? "justify-end" : "justify-start", align === "right" ? "items-end" : "items-start",
)} )}
> >
{images.length > 0 ? ( {images.length > 0 ? (
<ImageGallery images={images} align={align} size={align === "left" ? "large" : "compact"} /> <ImageGallery images={images} align={align} size={align === "left" ? "large" : "compact"} />
) : null} ) : null}
{nonImages.map((item, i) => ( {videos.map((item, i) => (
<AttachmentTile key={`${item.kind}-${i}`} attachment={item} pending={pending} /> <AttachmentTile key={`video-${i}`} attachment={item} pending={pending} className="my-0" />
))} ))}
{files.length > 0 ? (
<div className={cn("flex w-full min-w-0 flex-wrap items-start gap-2", align === "right" && "justify-end")}>
{files.map((item, i) => (
<AttachmentTile key={`file-${i}`} attachment={item} pending={pending} />
))}
</div>
) : null}
</div> </div>
); );
} }
+1
View File
@@ -2539,6 +2539,7 @@
"imageAttachment": "Image attachment", "imageAttachment": "Image attachment",
"videoAttachment": "Video attachment", "videoAttachment": "Video attachment",
"fileAttachment": "File attachment", "fileAttachment": "File attachment",
"downloadAttachment": "Download {{name}}",
"attachmentUnavailable": "Attachment unavailable", "attachmentUnavailable": "Attachment unavailable",
"dataTable": "Data table", "dataTable": "Data table",
"fileEditPreparing": "Preparing file edit…", "fileEditPreparing": "Preparing file edit…",
+1
View File
@@ -2157,6 +2157,7 @@
"imageAttachment": "Imagen adjunta", "imageAttachment": "Imagen adjunta",
"videoAttachment": "Archivo de vídeo", "videoAttachment": "Archivo de vídeo",
"fileAttachment": "Archivo adjunto", "fileAttachment": "Archivo adjunto",
"downloadAttachment": "Descargar {{name}}",
"attachmentUnavailable": "Adjunto no disponible", "attachmentUnavailable": "Adjunto no disponible",
"dataTable": "Tabla de datos", "dataTable": "Tabla de datos",
"fileEditPreparing": "Preparando la edición del archivo…", "fileEditPreparing": "Preparando la edición del archivo…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "Pièce jointe image", "imageAttachment": "Pièce jointe image",
"videoAttachment": "Pièce jointe vidéo", "videoAttachment": "Pièce jointe vidéo",
"fileAttachment": "Pièce jointe", "fileAttachment": "Pièce jointe",
"downloadAttachment": "Télécharger {{name}}",
"attachmentUnavailable": "Pièce jointe indisponible", "attachmentUnavailable": "Pièce jointe indisponible",
"dataTable": "Tableau de données", "dataTable": "Tableau de données",
"fileEditPreparing": "Préparation de la modification du fichier…", "fileEditPreparing": "Préparation de la modification du fichier…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "Lampiran gambar", "imageAttachment": "Lampiran gambar",
"videoAttachment": "Lampiran video", "videoAttachment": "Lampiran video",
"fileAttachment": "Lampiran file", "fileAttachment": "Lampiran file",
"downloadAttachment": "Unduh {{name}}",
"attachmentUnavailable": "Lampiran tidak tersedia", "attachmentUnavailable": "Lampiran tidak tersedia",
"dataTable": "Tabel data", "dataTable": "Tabel data",
"fileEditPreparing": "Menyiapkan perubahan file…", "fileEditPreparing": "Menyiapkan perubahan file…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "画像の添付", "imageAttachment": "画像の添付",
"videoAttachment": "動画の添付", "videoAttachment": "動画の添付",
"fileAttachment": "ファイルの添付", "fileAttachment": "ファイルの添付",
"downloadAttachment": "{{name}} をダウンロード",
"attachmentUnavailable": "添付ファイルを利用できません", "attachmentUnavailable": "添付ファイルを利用できません",
"dataTable": "データテーブル", "dataTable": "データテーブル",
"fileEditPreparing": "ファイル編集を準備中…", "fileEditPreparing": "ファイル編集を準備中…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "이미지 첨부", "imageAttachment": "이미지 첨부",
"videoAttachment": "동영상 첨부", "videoAttachment": "동영상 첨부",
"fileAttachment": "파일 첨부", "fileAttachment": "파일 첨부",
"downloadAttachment": "{{name}} 다운로드",
"attachmentUnavailable": "첨부 파일을 사용할 수 없음", "attachmentUnavailable": "첨부 파일을 사용할 수 없음",
"dataTable": "데이터 표", "dataTable": "데이터 표",
"fileEditPreparing": "파일 편집 준비 중…", "fileEditPreparing": "파일 편집 준비 중…",
+1
View File
@@ -2347,6 +2347,7 @@
"imageAttachment": "Anexo de imagem", "imageAttachment": "Anexo de imagem",
"videoAttachment": "Anexo de vídeo", "videoAttachment": "Anexo de vídeo",
"fileAttachment": "Anexo de arquivo", "fileAttachment": "Anexo de arquivo",
"downloadAttachment": "Baixar {{name}}",
"attachmentUnavailable": "Anexo indisponível", "attachmentUnavailable": "Anexo indisponível",
"dataTable": "Tabela de dados", "dataTable": "Tabela de dados",
"fileEditPreparing": "Preparando a edição do arquivo…", "fileEditPreparing": "Preparando a edição do arquivo…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "Tệp hình ảnh đính kèm", "imageAttachment": "Tệp hình ảnh đính kèm",
"videoAttachment": "Tệp video đính kèm", "videoAttachment": "Tệp video đính kèm",
"fileAttachment": "Tệp đính kèm", "fileAttachment": "Tệp đính kèm",
"downloadAttachment": "Tải xuống {{name}}",
"attachmentUnavailable": "Tệp đính kèm không khả dụng", "attachmentUnavailable": "Tệp đính kèm không khả dụng",
"dataTable": "Bảng dữ liệu", "dataTable": "Bảng dữ liệu",
"fileEditPreparing": "Đang chuẩn bị sửa tệp…", "fileEditPreparing": "Đang chuẩn bị sửa tệp…",
+1
View File
@@ -2539,6 +2539,7 @@
"imageAttachment": "图片附件", "imageAttachment": "图片附件",
"videoAttachment": "视频附件", "videoAttachment": "视频附件",
"fileAttachment": "文件附件", "fileAttachment": "文件附件",
"downloadAttachment": "下载 {{name}}",
"attachmentUnavailable": "附件不可用", "attachmentUnavailable": "附件不可用",
"dataTable": "数据表", "dataTable": "数据表",
"fileEditPreparing": "准备编辑文件…", "fileEditPreparing": "准备编辑文件…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "圖片附件", "imageAttachment": "圖片附件",
"videoAttachment": "影片附件", "videoAttachment": "影片附件",
"fileAttachment": "檔案附件", "fileAttachment": "檔案附件",
"downloadAttachment": "下載 {{name}}",
"attachmentUnavailable": "附件無法使用", "attachmentUnavailable": "附件無法使用",
"dataTable": "資料表", "dataTable": "資料表",
"fileEditPreparing": "準備編輯檔案…", "fileEditPreparing": "準備編輯檔案…",
+47
View File
@@ -0,0 +1,47 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { AttachmentTile } from "@/components/AttachmentTile";
describe("attachment download cards", () => {
it("keeps named download actions distinct and shows the file extension", () => {
render(<>
<AttachmentTile attachment={{ kind: "file", name: "猫咪图鉴完整包.zip", url: "/api/media/signed/archive" }} />
<AttachmentTile attachment={{ kind: "file", name: "source.tar.gz", url: "/api/media/signed/source" }} />
</>);
const archive = screen.getByRole("link", { name: "Download 猫咪图鉴完整包.zip" });
expect(archive).toHaveAttribute("download", "猫咪图鉴完整包.zip");
expect(archive).toHaveAttribute("href", "/api/media/signed/archive");
expect(archive).toHaveAttribute("title", "猫咪图鉴完整包.zip");
expect(archive).toHaveTextContent("ZIP");
expect(archive.querySelector(".lucide-download")).toHaveAttribute("aria-hidden", "true");
expect(screen.getByRole("link", { name: "Download source.tar.gz" })).toHaveTextContent("TAR.GZ");
});
it("changes a pending file to a download only after its URL arrives", () => {
const attachment = { kind: "file" as const, name: "report.pdf" };
const { rerender } = render(<AttachmentTile attachment={attachment} pending />);
expect(screen.getByText("Sending…")).toBeVisible();
expect(screen.queryByRole("link")).not.toBeInTheDocument();
rerender(<AttachmentTile attachment={{ ...attachment, url: "/api/media/signed/report" }} />);
expect(screen.getByRole("link", { name: "Download report.pdf" })).toHaveTextContent("PDF");
rerender(<AttachmentTile attachment={attachment} />);
expect(screen.getByText("Attachment unavailable")).toBeVisible();
expect(screen.queryByRole("link")).not.toBeInTheDocument();
});
it("keeps unnamed and extensionless attachments identifiable", () => {
render(<>
<AttachmentTile attachment={{ kind: "file", url: "/api/media/signed/archive.zip?signature=example#payload.txt" }} />
<AttachmentTile attachment={{ kind: "file", name: "LICENSE", url: "/api/media/signed/license" }} />
</>);
const unnamed = screen.getByRole("link", { name: "Download File attachment" });
expect(unnamed).toHaveAttribute("download", "File attachment");
expect(unnamed).toHaveTextContent("File attachment");
expect(unnamed.querySelector(".lucide-file-archive")).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Download LICENSE" })).toHaveTextContent("File attachment");
});
});
+16 -4
View File
@@ -14,6 +14,7 @@ describe("shared file icons", () => {
["styles.css", "file-code2"], ["styles.css", "file-code2"],
["app.js", "file-code2"], ["app.js", "file-code2"],
["app.ts", "file-code2"], ["app.ts", "file-code2"],
["app#draft.ts", "file-code2"],
["app.tsx", "file-code2"], ["app.tsx", "file-code2"],
["script.py", "file-code2"], ["script.py", "file-code2"],
["analysis.ipynb", "file-code2"], ["analysis.ipynb", "file-code2"],
@@ -22,7 +23,18 @@ describe("shared file icons", () => {
["notes.txt", "file-text"], ["notes.txt", "file-text"],
["build.log", "file-text"], ["build.log", "file-text"],
["demo.mp4", "file-video2"], ["demo.mp4", "file-video2"],
["archive.zip", "file"], ["https://files.example.com/demo.mp4?signature=abc#download.zip", "file-video2"],
["archive.zip", "file-archive"],
["backup.tar.gz", "file-archive"],
["voice.mp3", "file-audio"],
["recording.flac", "file-audio"],
["REPORT#2.PDF", "file-text"],
["proposal.docx", "file-text"],
["budget.xlsx", "file-spreadsheet"],
["results.csv", "file-spreadsheet"],
["slides.pptx", "file-chart-column"],
["slides.odp", "file-chart-column"],
["payload.bin", "file"],
])("uses a consistent monochrome file-family icon for %s", (path, icon) => { ])("uses a consistent monochrome file-family icon for %s", (path, icon) => {
const { container } = render(<FileReferenceIcon kind={fileKindForPath(path)} />); const { container } = render(<FileReferenceIcon kind={fileKindForPath(path)} />);
const svg = container.querySelector("svg")!; const svg = container.querySelector("svg")!;
@@ -36,7 +48,7 @@ describe("shared file icons", () => {
expect(svg.querySelector("text, [fill], [stroke]")).toBeNull(); expect(svg.querySelector("text, [fill], [stroke]")).toBeNull();
}); });
it.each(["chart.png", "index.html", "data.json", "script.py", "notes.md"])( it.each(["chart.png", "index.html", "data.json", "script.py", "notes.md", "archive.zip", "report.pdf", "budget.xlsx", "slides.pptx", "song.mp3"])(
"reuses the same glyph for %s in replies, tabs and attachments without changing actions", (path) => { "reuses the same glyph for %s in replies, tabs and attachments without changing actions", (path) => {
const open = vi.fn(); const open = vi.fn();
render(<> render(<>
@@ -48,12 +60,12 @@ describe("shared file icons", () => {
</>); </>);
const reference = screen.getByRole("button", { name: path }); const reference = screen.getByRole("button", { name: path });
const tab = screen.getByRole("tab", { name: path }); const tab = screen.getByRole("tab", { name: path });
const attachment = screen.getByRole("link", { name: "File attachment" }); const attachment = screen.getByRole("link", { name: `Download ${path}` });
const glyph = reference.querySelector("svg")!.innerHTML; const glyph = reference.querySelector("svg")!.innerHTML;
expect(tab.querySelector("svg")!.innerHTML).toBe(glyph); expect(tab.querySelector("svg")!.innerHTML).toBe(glyph);
expect(attachment.querySelector("svg")!.innerHTML).toBe(glyph); expect(attachment.querySelector("svg")!.innerHTML).toBe(glyph);
expect(tab.querySelector("svg")).toHaveClass("size-3.5"); expect(tab.querySelector("svg")).toHaveClass("size-3.5");
expect(attachment.querySelector("svg")).toHaveClass("size-4"); expect(attachment.querySelector("svg")).toHaveClass("size-5");
expect(tab.querySelector("svg")).not.toHaveClass("translate-y-[0.12em]"); expect(tab.querySelector("svg")).not.toHaveClass("translate-y-[0.12em]");
expect(attachment.querySelector("svg")).not.toHaveClass("translate-y-[0.12em]"); expect(attachment.querySelector("svg")).not.toHaveClass("translate-y-[0.12em]");
expect(attachment).toHaveAttribute("href", `/download/${path}`); expect(attachment).toHaveAttribute("href", `/download/${path}`);
@@ -291,7 +291,7 @@ describe("MarkdownTextRenderer", () => {
it("renders markdown links with file-looking names as file attachments", () => { it("renders markdown links with file-looking names as file attachments", () => {
render(<MarkdownTextRenderer>![index.html](/api/media/sig/html)</MarkdownTextRenderer>); render(<MarkdownTextRenderer>![index.html](/api/media/sig/html)</MarkdownTextRenderer>);
expect(screen.getByLabelText("File attachment")).toHaveTextContent("index.html"); expect(screen.getByRole("link", { name: "Download index.html" })).toHaveTextContent("index.html");
expect(screen.queryByRole("img", { name: "index.html" })).not.toBeInTheDocument(); expect(screen.queryByRole("img", { name: "index.html" })).not.toBeInTheDocument();
}); });
+2 -2
View File
@@ -1268,7 +1268,7 @@ describe("MessageBubble", () => {
const { container } = render(<MessageBubble message={message} />); const { container } = render(<MessageBubble message={message} />);
expect(screen.getByLabelText("File attachment")).toHaveTextContent("index.html"); expect(screen.getByRole("link", { name: "Download index.html" })).toHaveTextContent("index.html");
expect(container.querySelector("img")).not.toBeInTheDocument(); expect(container.querySelector("img")).not.toBeInTheDocument();
}); });
@@ -1291,7 +1291,7 @@ describe("MessageBubble", () => {
expect(screen.getByRole("button", { name: /view image: growth.svg/i })).toBeInTheDocument(); expect(screen.getByRole("button", { name: /view image: growth.svg/i })).toBeInTheDocument();
expect(container.querySelector('img[src="/api/media/sig/svg"]')).toBeInTheDocument(); expect(container.querySelector('img[src="/api/media/sig/svg"]')).toBeInTheDocument();
expect(screen.queryByLabelText("File attachment")).not.toBeInTheDocument(); expect(screen.queryByRole("link", { name: "Download growth.svg" })).not.toBeInTheDocument();
}); });
}); });