From eed7b47753a82e11398dfb58225bdf4f38e9e13f Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:39:44 +0800 Subject: [PATCH] feat(webui): refine attachment galleries and file cards (#6457) * feat(webui): refine attachment galleries and file cards * fix(webui): align attachment tests and Escape handling --- .../websocket/tests/test_local_attachments.py | 32 ++++++ nanobot/webui/media_api.py | 15 ++- nanobot/webui/media_gateway.py | 13 ++- webui/browser/attachment-layout.spec.ts | 97 ++++++++++++++----- webui/browser/composer-attachments.spec.ts | 64 +++++++++--- webui/src/components/AttachmentCard.tsx | 73 ++++++++++++++ webui/src/components/AttachmentTile.tsx | 72 ++++---------- webui/src/components/ImageGallery.tsx | 91 +++++++++++++---- .../src/components/thread/ThreadComposer.tsx | 96 ++++-------------- webui/src/lib/image-gallery-layout.ts | 53 ++++++++++ webui/src/tests/attachment-tile.test.tsx | 54 +++++++++-- webui/src/tests/file-reference-icon.test.tsx | 54 +++++++---- webui/src/tests/image-gallery-layout.test.ts | 57 +++++++++++ webui/src/tests/image-gallery.test.tsx | 53 +++++++++- .../src/tests/markdown-text-renderer.test.tsx | 3 +- webui/src/tests/message-bubble.test.tsx | 20 ++-- .../src/tests/thread-composer-attach.test.tsx | 50 ++++++++-- webui/src/tests/thread-messages.test.tsx | 11 ++- webui/src/tests/thread-shell.test.tsx | 7 +- 19 files changed, 660 insertions(+), 255 deletions(-) create mode 100644 webui/src/components/AttachmentCard.tsx create mode 100644 webui/src/lib/image-gallery-layout.ts create mode 100644 webui/src/tests/image-gallery-layout.test.ts diff --git a/nanobot/channels/websocket/tests/test_local_attachments.py b/nanobot/channels/websocket/tests/test_local_attachments.py index 861a383bb..d448e0046 100644 --- a/nanobot/channels/websocket/tests/test_local_attachments.py +++ b/nanobot/channels/websocket/tests/test_local_attachments.py @@ -149,3 +149,35 @@ async def test_mixed_media_replay_keeps_uploaded_cache_and_borrowed_freshness(tm assert bytes(served.body) == expected assert served.headers["Cache-Control"] == cache assert sorted(path.name for path in media.iterdir()) == ["borrowed.png", "upload.png"] + + +@pytest.mark.parametrize("role", ["assistant", "user"]) +def test_replayed_media_keeps_missing_files_in_order_without_download_urls(tmp_path, monkeypatch, role): + media = tmp_path / "media" + media.mkdir() + first = media / "first.json" + missing = media / "missing.txt" + last = media / "last.pdf" + first.write_bytes(b'{"synthetic":true}') + last.write_bytes(b"synthetic pdf") + paths = [str(path) for path in (first, missing, last)] + gateway = WebUIMediaGateway(workspace_path=tmp_path, logger=Mock(), media_dir=lambda _: media) + + def project(): + if role == "assistant": + return gateway.augment_transcript_media(paths) + return gateway.augment_transcript_user_media(paths, [], session_key="websocket:files") + + with monkeypatch.context() as patch: + patch.setattr(type(first), "read_bytes", lambda *_: pytest.fail("projection read file contents")) + attachments = project() + assert [item["name"] for item in attachments] == ["first.json", "missing.txt", "last.pdf"] + assert attachments[1] == {"kind": "file", "name": "missing.txt", "url": ""} + sig, payload = attachments[0]["url"].split("/")[-2:] + assert bytes(gateway.serve_signed_media(sig, payload).body) == b'{"synthetic":true}' + assert attachments[2]["url"] + + last.unlink() + refreshed = project() + assert [item["name"] for item in refreshed] == [item["name"] for item in attachments] + assert refreshed[2]["url"] == "" diff --git a/nanobot/webui/media_api.py b/nanobot/webui/media_api.py index f1fc48081..576fe2441 100644 --- a/nanobot/webui/media_api.py +++ b/nanobot/webui/media_api.py @@ -184,17 +184,16 @@ def signed_media_attachments( *, sign_path: SignedMediaPath, ) -> list[dict[str, Any]]: - """Map persisted media paths to WebUI attachment dicts with fresh signed URLs.""" + """Keep every attachment in order, signing only files available at projection time.""" out: list[dict[str, Any]] = [] for pstr in paths: path = Path(pstr) - att = sign_path(path) - if att is None: - continue - url = att.get("url") - if not url: - continue - name = att.get("name") or path.name + try: + att = sign_path(path) if path.is_file() else None + except OSError: + att = None + name = (att.get("name") if att else None) or path.name + url = (att.get("url") if att else None) or "" out.append({"kind": media_attachment_kind(name), "url": url, "name": name}) return out diff --git a/nanobot/webui/media_gateway.py b/nanobot/webui/media_gateway.py index 07bf8e8ad..3d60f880c 100644 --- a/nanobot/webui/media_gateway.py +++ b/nanobot/webui/media_gateway.py @@ -96,9 +96,14 @@ class WebUIMediaGateway: media: list[dict[str, Any]] = [] for raw in paths: path = Path(raw) - if raw in local: - url = self.local_attachment_url(raw, session_key=session_key) if path.is_file() else "" - else: - url = sign_media_path(path, secret=self.secret, media_dir=self._media_dir) or "" + try: + if not path.is_file(): + url = "" + elif raw in local: + url = self.local_attachment_url(raw, session_key=session_key) + else: + url = sign_media_path(path, secret=self.secret, media_dir=self._media_dir) or "" + except OSError: + url = "" media.append({"kind": media_attachment_kind(path.name), "name": path.name, "url": url}) return media diff --git a/webui/browser/attachment-layout.spec.ts b/webui/browser/attachment-layout.spec.ts index 3484314cc..c08826d48 100644 --- a/webui/browser/attachment-layout.spec.ts +++ b/webui/browser/attachment-layout.spec.ts @@ -26,6 +26,26 @@ async function bounds(locator: Locator) { return box!; } +async function expectFileDetails(page: Page, card: Locator, filename: string, width: number, description?: string) { + const info = card.getByRole("button", { name: filename, exact: true }); + await info.hover(); + await expect(page.getByRole("tooltip")).toContainText(filename); + await info.click(); + const details = page.getByRole("dialog", { name: filename, exact: true }); + const name = details.getByText(filename, { exact: true }); + await expect(name).toBeVisible(); + if (description) await expect(details.getByText(description, { exact: true })).toBeVisible(); + const box = await bounds(details); + expect(box.x).toBeGreaterThanOrEqual(0); + expect(box.x + box.width).toBeLessThanOrEqual(width); + expect(await name.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true); + expect(await details.evaluate((element) => element.scrollHeight <= element.clientHeight)).toBe(true); + await page.keyboard.press("Escape"); + await expect(details).toHaveCount(0); + await expect(info).toBeFocused(); + await page.mouse.move(0, 0); +} + 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) => { @@ -44,16 +64,19 @@ for (const width of [1024, 360]) { for (const role of ["Assistant", "User"]) { const region = page.getByRole("region", { name: `${role} mixed attachments`, exact: true }); - const card = region.locator("a[download]"); + const card = region.locator("[data-file-attachment]"); 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 }; + const { naturalWidth, naturalHeight } = image as HTMLImageElement; + return { bottom: rect.bottom, left: rect.left, right: rect.right, naturalWidth, naturalHeight }; })); 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.width, `${role} file card keeps its compact width`).toBe(96); + expect(file.height, `${role} file card must not stretch to the image row height`).toBe(96); + for (const image of imageBoxes) expect(image).toMatchObject({ naturalWidth: 320, naturalHeight: 200 }); 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); @@ -63,15 +86,15 @@ for (const width of [1024, 360]) { 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.getByRole("link")).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]"); + const files = page.getByRole("region", { name: "Multiple files and long names" }).locator("[data-file-attachment]"); 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]"); + const userCards = userFiles.locator("[data-file-attachment]"); 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" }); @@ -79,36 +102,47 @@ for (const width of [1024, 360]) { 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 availableCards = page.locator("[data-file-attachment]").filter({ has: page.locator("a[download]") }); + for (const card of await availableCards.all()) { const box = await bounds(card); - expect(box.height).toBeLessThanOrEqual(80); + expect(box.width).toBe(96); + expect(box.height).toBe(96); expect(box.x).toBeGreaterThanOrEqual(0); expect(box.x + box.width).toBeLessThanOrEqual(width); - const icon = card.locator("svg.lucide-download"); + const download = card.locator("a[download]"); + const target = await bounds(download); + expect(target.width).toBe(44); + expect(target.height).toBe(44); + expect(target.x).toBeGreaterThanOrEqual(box.x); + expect(target.x + target.width).toBeLessThanOrEqual(box.x + box.width); + expect(target.y).toBeGreaterThanOrEqual(box.y); + expect(target.y + target.height).toBeLessThanOrEqual(box.y + box.height); + const icon = download.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); + expect(iconBox.x).toBeGreaterThanOrEqual(target.x); + expect(iconBox.x + iconBox.width).toBeLessThanOrEqual(target.x + target.width); + expect(iconBox.y).toBeGreaterThanOrEqual(target.y); + expect(iconBox.y + iconBox.height).toBeLessThanOrEqual(target.y + target.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); + for (const [index, filename, type] of [ + [0, "release-deliverables-with-a-very-long-English-filename-for-layout-regression.zip", "ZIP"], + [1, "项目交付资料与详细验收记录包含中英文的超长文件名称-final-review.pdf", "PDF"], + ] as const) { + const card = files.nth(index); + await expect(card.getByRole("button", { name: filename, exact: true })).toHaveText(type); + await expectFileDetails(page, card, filename, width); } - await expect(files.nth(1).getByText("PDF", { exact: true })).toBeVisible(); - await expect(files.nth(2)).toHaveAccessibleName(chinese ? "下载 文件附件" : "Download File attachment"); + await expect(files.nth(2).getByRole("link")).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(); + const card = region.locator("[data-file-attachment]"); + await expect(card.getByText(status, { exact: true })).toBeVisible(); + await expectFileDetails(page, card, filename, width, status); // A replay placeholder has no download capability until it has a URL. await expect(region.getByRole("link")).toHaveCount(0); } @@ -135,7 +169,22 @@ test("image lightbox and file download remain keyboard accessible", async ({ pag 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"); + for (const name of ["Blue study.svg", "Green study.svg"]) { + await page.keyboard.press("Tab"); + await expect(region.getByRole("button", { name: `View image: ${name}`, exact: true })).toBeFocused(); + } + await page.keyboard.press("Tab"); + const fileInfo = region.getByRole("button", { name: "archive.zip", exact: true }); + await expect(fileInfo).toBeFocused(); + expect(await fileInfo.evaluate((element) => element.matches(":focus-visible"))).toBe(true); + await expect(page.getByRole("tooltip")).toContainText("archive.zip"); + await page.keyboard.press("Enter"); + const details = page.getByRole("dialog", { name: "archive.zip", exact: true }); + await expect(details.getByText("archive.zip", { exact: true })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(details).toHaveCount(0); + await expect(fileInfo).toBeFocused(); + 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); diff --git a/webui/browser/composer-attachments.spec.ts b/webui/browser/composer-attachments.spec.ts index b3ac37250..81eeb1f09 100644 --- a/webui/browser/composer-attachments.spec.ts +++ b/webui/browser/composer-attachments.spec.ts @@ -1,4 +1,4 @@ -import { expect, test, type Page } from "@playwright/test"; +import { expect, test, type Locator, type Page } from "@playwright/test"; async function imageFile(page: Page, name: string, background: string) { const data = await page.evaluate((fill) => { @@ -17,6 +17,26 @@ async function imageFile(page: Page, name: string, background: string) { return { name, mimeType: "image/png", buffer: Buffer.from(data, "base64") }; } +async function expectAttachmentDetails(page: Page, chip: Locator, name: string, touch = false) { + const info = chip.getByRole("button", { name, exact: true }); + const size = await info.getAttribute("aria-description"); + expect(size).toMatch(/^\d+(?:\.\d+)? (?:B|KiB|MiB)$/); + if (touch) await info.tap(); + else { + await info.hover(); + await expect(page.getByRole("tooltip")).toContainText(name); + await expect(page.getByRole("tooltip")).toContainText(size!); + await info.click(); + } + const details = page.getByRole("dialog", { name, exact: true }); + await expect(details.getByText(name, { exact: true })).toBeVisible(); + await expect(details.getByText(size!, { exact: true })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(details).toHaveCount(0); + await expect(info).toBeFocused(); + await page.mouse.move(0, 0); +} + test.beforeEach(async ({ page }) => { await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en")); await page.route("**/api/**", route => route.fulfill({ json: {} })); @@ -46,9 +66,8 @@ for (const { width, dark, variant } of [ for (const name of ["white.png", "dark.png", "notes.png"]) { const image = page.getByRole("img", { name, exact: true }); await expect(image).toBeVisible(); - expect(await image.evaluate(node => (node as HTMLImageElement).naturalWidth)).toBe(480); + expect(await image.evaluate(node => ({ width: (node as HTMLImageElement).naturalWidth, height: (node as HTMLImageElement).naturalHeight }))).toEqual({ width: 480, height: 320 }); const chip = chips.filter({ has: image }); - await expect(chip).toHaveAttribute("title", new RegExp(`^${name}\\n`)); const box = (await chip.boundingBox())!; expect(box.width).toBe(96); expect(box.height).toBe(96); @@ -61,28 +80,33 @@ for (const { width, dark, variant } of [ expect(target.height).toBeGreaterThanOrEqual(44); expect(target.x + target.width).toBeCloseTo(box.x + box.width - 1); expect(target.y).toBeCloseTo(box.y + 1); + await expectAttachmentDetails(page, chip, name, width < 640); } - const document = chips.filter({ hasText: "report.pdf" }); - await expect(document).toContainText("B"); - expect((await document.boundingBox())!.height).toBeLessThan(96); + const document = chips.filter({ has: page.getByRole("button", { name: "report.pdf", exact: true }) }); + await expect(document).toHaveText("PDF"); + await expect(document.getByRole("button", { name: "report.pdf", exact: true })).toHaveAccessibleDescription(`${files[3].buffer.byteLength} B`); + const documentBox = (await document.boundingBox())!; + expect(documentBox.width).toBe(96); + expect(documentBox.height).toBe(96); + await expectAttachmentDetails(page, document, "report.pdf", width < 640); expect(await page.evaluate(() => window.document.documentElement.scrollWidth)).toBe(width); await page.getByRole("textbox").fill("Compare these images with the report."); const screenshot = testInfo.outputPath("composer-attachments.png"); await page.locator("main").screenshot({ path: screenshot }); await testInfo.attach("composer-attachments", { path: screenshot, contentType: "image/png" }); - const whiteRemove = chips.filter({ has: page.getByRole("img", { name: "white.png", exact: true }) }).getByRole("button"); + const whiteRemove = chips.filter({ has: page.getByRole("img", { name: "white.png", exact: true }) }).getByRole("button", { name: "Remove attachment", exact: true }); // Tap outside the visible circle, but inside the larger touch target. if (width < 640) await whiteRemove.tap({ position: { x: 6, y: 22 } }); else await whiteRemove.click(); await expect(chips).toHaveCount(3); - const darkRemove = chips.filter({ has: page.getByRole("img", { name: "dark.png", exact: true }) }).getByRole("button"); + const darkRemove = chips.filter({ has: page.getByRole("img", { name: "dark.png", exact: true }) }).getByRole("button", { name: "Remove attachment", exact: true }); await darkRemove.focus(); await expect(darkRemove).toBeFocused(); await page.keyboard.press("Delete"); await expect(chips).toHaveCount(2); - await chips.filter({ has: page.getByRole("img", { name: "notes.png", exact: true }) }).getByRole("button").click(); - await document.getByRole("button").click(); + await chips.filter({ has: page.getByRole("img", { name: "notes.png", exact: true }) }).getByRole("button", { name: "Remove attachment", exact: true }).click(); + await document.getByRole("button", { name: "Remove attachment", exact: true }).click(); await expect(page.getByRole("textbox")).toBeFocused(); await expect(page.getByRole("textbox")).toHaveValue("Compare these images with the report."); }); @@ -91,13 +115,25 @@ for (const { width, dark, variant } of [ test("shows a readable error card and allows removal of a corrupt image", async ({ page }) => { await page.goto("/browser/fixture.html?case=composer-action"); + const input = page.getByRole("textbox"); + const draft = "Keep this draft while checking the attachment."; + await input.fill(draft); const broken = Buffer.from("not a PNG image"); await page.locator('input[type="file"]').setInputFiles({ name: "broken.png", mimeType: "image/png", buffer: broken }); const chip = page.getByTestId("composer-chip"); - await expect(chip).toContainText("broken.png"); - await expect(chip).toContainText("File doesn't look like a real image"); + await expect(chip.getByRole("button", { name: "broken.png", exact: true })).toHaveText("PNG"); + await expect(chip.getByText("File doesn't look like a real image", { exact: true })).toBeVisible(); + await expectAttachmentDetails(page, chip, "broken.png"); await expect(page.getByRole("button", { name: "Send message", exact: true })).toBeDisabled(); - await chip.getByRole("button", { name: "Remove attachment" }).click(); + await input.press("Enter"); + await expect(page.getByRole("status", { name: "Execution status", exact: true })).toHaveText("Idle"); + await expect(input).toHaveValue(draft); + await expect(chip).toHaveCount(1); + await chip.getByRole("button", { name: "Remove attachment", exact: true }).click(); + await expect(chip).toHaveCount(0); + await expect(input).toBeFocused(); + await expect(input).toHaveValue(draft); + await expect(page.getByRole("button", { name: "Send message", exact: true })).toBeEnabled(); + await input.fill(""); await expect(page.getByRole("button", { name: "Voice input", exact: true })).toBeEnabled(); - await expect(page.getByRole("textbox")).toBeFocused(); }); diff --git a/webui/src/components/AttachmentCard.tsx b/webui/src/components/AttachmentCard.tsx new file mode 100644 index 000000000..7c0c1c656 --- /dev/null +++ b/webui/src/components/AttachmentCard.tsx @@ -0,0 +1,73 @@ +import { useState, type ReactNode } from "react"; +import { FileText, ImageIcon, Video } from "lucide-react"; +import { useTranslation } from "react-i18next"; + +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; +import type { UIMediaKind } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +export const attachmentCardActionClassName = "absolute right-0 top-0 grid h-11 w-11 place-items-center rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"; + +/** The card owns only its information surface; callers own removal, download, and status. */ +export function AttachmentCard({ name, description, children, action, invalid = false }: { + name: string; + description?: string; + children: ReactNode; + action?: ReactNode; + invalid?: boolean; +}) { + const [detailsOpen, setDetailsOpen] = useState(false); + const [hintOpen, setHintOpen] = useState(false); + const changeDetailsOpen = (open: boolean) => { setDetailsOpen(open); setHintOpen(false); }; + const details = <> + {name} + {description ? {description} : null} + ; + + return + + + + + + + + + event.preventDefault()} + className="w-max max-w-[min(20rem,calc(100vw-2rem))] break-words px-3 py-1.5 text-caption"> + {details} + + + {details} + + + {action} + ; +} + +export function AttachmentTypeFace({ name, kind = "file" }: { name: string; kind?: UIMediaKind }) { + const { t } = useTranslation(); + const type = name.match(/\.(tar\.(?:gz|bz2|xz)|[a-z0-9]{1,12})$/i)?.[1].toUpperCase() + || t(kind === "image" ? "message.imageAttachment" : kind === "video" ? "message.videoAttachment" : "message.fileAttachment"); + const Icon = kind === "image" ? ImageIcon : kind === "video" ? Video : FileText; + return + + {type} + ; +} diff --git a/webui/src/components/AttachmentTile.tsx b/webui/src/components/AttachmentTile.tsx index b5c6a5df2..0294f55c5 100644 --- a/webui/src/components/AttachmentTile.tsx +++ b/webui/src/components/AttachmentTile.tsx @@ -7,7 +7,7 @@ import type { UIMediaAttachment } from "@/lib/types"; import { ImageThumbnail } from "@/components/ImageGallery"; import { ImageLightbox } from "@/components/ImageLightbox"; import { useRegisterInlineImage } from "@/components/InlineImageContext"; -import { FileReferenceIcon, fileKindForPath } from "@/components/FileReferenceChip"; +import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard"; interface AttachmentTileProps { attachment: UIMediaAttachment; @@ -63,61 +63,27 @@ export function AttachmentTile({ attachment, className, inline = false, variant } const filePath = attachment.name || attachment.url?.split(/[?#]/, 1)[0] || ""; - const fileKind = attachment.kind === "file" ? fileKindForPath(filePath) : 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 = ( - <> - - - - - {name} - {details} - - - ); + const status = available ? undefined : pending ? t("message.delivery.sending") : t("message.attachmentUnavailable"); + const download = available ? + + : undefined; - if (available) { - return ( - - {body} - - - ); - } - - const Frame = inline ? "span" : "div"; - return ( - - {body} - {attachment.kind === "video" && failed && !pending ? ( - - ) : null} - - ); + return + + + + {status ? {status} : null} + {attachment.kind === "video" && failed && !pending ? ( + + ) : null} + ; } function AttachmentFrame({ diff --git a/webui/src/components/ImageGallery.tsx b/webui/src/components/ImageGallery.tsx index 297dcaad3..57f240b71 100644 --- a/webui/src/components/ImageGallery.tsx +++ b/webui/src/components/ImageGallery.tsx @@ -1,8 +1,9 @@ -import { useState } from "react"; +import { useLayoutEffect, useRef, useState, type CSSProperties } from "react"; import { ImageIcon } from "lucide-react"; import { useTranslation } from "react-i18next"; import { ImageLightbox } from "@/components/ImageLightbox"; +import { IMAGE_GAP, imageFrameRatio, layoutImageRows, type ImageDimensions } from "@/lib/image-gallery-layout"; import type { UIImage } from "@/lib/types"; import { cn } from "@/lib/utils"; @@ -14,20 +15,64 @@ export function ImageGallery({ images, align = "left", size = "large" }: { }) { const { t } = useTranslation(); const [index, setIndex] = useState(null); + const [dimensions, setDimensions] = useState>({}); + const [width, setWidth] = useState(0); + const container = useRef(null); const viewable = images.filter((image) => image.url); - const multiple = images.length > 1; const visible = images.slice(0, 4); + const measured = visible.map((image) => image.url ? dimensions[image.url] : null); + const ready = measured.every((image) => image !== undefined); + const maxWidth = size === "large" ? 448 : 360; + const maxHeight = visible.length === 1 ? (size === "large" ? 352 : 320) : (size === "large" ? 256 : 224); + const single = visible.length === 1 ? measured[0] : null; + const preferredWidth = single ? Math.min(maxWidth, single.width, maxHeight * imageFrameRatio(single)) : maxWidth; + + useLayoutEffect(() => { + const element = container.current; + if (!element) return; + const measure = () => setWidth(element.getBoundingClientRect().width); + measure(); + const observer = new ResizeObserver(measure); + observer.observe(element); + return () => observer.disconnect(); + }, [preferredWidth]); + + const layoutWidth = Math.min(width || preferredWidth, preferredWidth); + const rows = layoutImageRows( + ready ? measured : visible.map(() => null), layoutWidth, + size === "large" ? 176 : 144, maxHeight, + ); + let top = 0; + const tiles = rows.flatMap((row) => { + const rowWidth = row.widths.reduce((sum, item) => sum + item, IMAGE_GAP * (row.widths.length - 1)); + let left = align === "right" ? layoutWidth - rowWidth : 0; + const items = row.widths.map((tileWidth, offset) => { + const tile = { position: row.start + offset, frame: { width: tileWidth, height: row.height, left, top } }; + left += tileWidth + IMAGE_GAP; + return tile; + }); + top += row.height + IMAGE_GAP; + return items; + }); + const remember = (url: string, value: ImageDimensions | null) => setDimensions((current) => { + const previous = current[url]; + if (previous === value || (previous && value && previous.width === value.width && previous.height === value.height)) return current; + return { ...current, [url]: value }; + }); + return <> - - {visible.map((image, position) => { + + {tiles.map(({ position, frame }) => { + const image = visible[position]; const remaining = images.length - visible.length; const overflow = position === visible.length - 1 && remaining > 0; return { if (image.url) remember(image.url, value); }} + onError={() => { if (image.url) remember(image.url, null); }} label={overflow ? t("lightbox.viewAll", { count: images.length }) : undefined} onOpen={image.url || (overflow && viewable.length) ? () => setIndex(Math.max(0, viewable.indexOf(image))) : undefined} overlay={overflow ? `+${remaining}` : undefined} />; @@ -38,31 +83,39 @@ export function ImageGallery({ images, align = "left", size = "large" }: { ; } -export function ImageThumbnail({ image, size = "large", onOpen, label, overlay, onError }: { +export function ImageThumbnail({ image, size = "large", frame, onOpen, label, overlay, onLoad, onError }: { image: UIImage; - size?: "compact" | "large" | "grid"; + size?: "compact" | "large"; + frame?: ImageDimensions & { left: number; top: number }; onOpen?: () => void; label?: string; overlay?: string; + onLoad?: (dimensions: ImageDimensions) => void; onError?: () => void; }) { const { t } = useTranslation(); const [failed, setFailed] = useState(false); const classes = cn( - "relative block max-w-full overflow-hidden rounded-control border border-border/60 bg-muted/25", - size === "large" ? "w-[min(100%,28rem)]" : size === "grid" ? "aspect-[8/5] w-full" : "h-24 w-24", + "relative block max-w-full shrink-0 overflow-hidden rounded-control bg-muted/25 ring-1 ring-inset ring-border/60", + !frame && (size === "large" ? "w-[min(100%,28rem)]" : "w-48"), ); + const style: CSSProperties | undefined = frame ? { ...frame, position: "absolute" } : undefined; + const unavailable = t("message.attachmentUnavailable"); const content = image.url && !failed ? {image.name { + const { naturalWidth, naturalHeight } = event.currentTarget; + onLoad?.({ width: naturalWidth, height: naturalHeight }); + }} onError={() => { setFailed(true); onError?.(); }} - className={cn("block w-full object-contain", size === "large" ? "h-auto max-h-[22rem]" : "h-full")} /> - : + className={cn("block w-full object-contain text-transparent", frame ? "h-full" : "h-auto max-h-[22rem]")} /> + : - {image.name || t("message.imageAttachment")} + {unavailable} ; - if (!onOpen || ((!image.url || failed) && !overlay)) return {content}; - return + }> + {isThumbnail && image.previewUrl ? {image.file.name} : } + {image.status === "encoding" ? + + : null} + + {error ? {error} : null} ); } diff --git a/webui/src/lib/image-gallery-layout.ts b/webui/src/lib/image-gallery-layout.ts new file mode 100644 index 000000000..fbbaff602 --- /dev/null +++ b/webui/src/lib/image-gallery-layout.ts @@ -0,0 +1,53 @@ +export interface ImageDimensions { + width: number; + height: number; +} + +export interface ImageRow { + start: number; + widths: number[]; + height: number; +} + +export const IMAGE_GAP = 8; + +// Extreme screenshots keep their full content inside a bounded portrait/landscape frame. +export function imageFrameRatio(image: ImageDimensions | null): number { + return image ? Math.max(0.5, Math.min(3, image.width / image.height)) : 1.5; +} + +/** Choose ordered, equal-height rows for the gallery's at most four previews. */ +export function layoutImageRows( + images: (ImageDimensions | null)[], + width: number, + targetHeight: number, + maxHeight: number, +): ImageRow[] { + let best: ImageRow[] = []; + let bestScore = Infinity; + const ratios = images.map(imageFrameRatio); + + function visit(start: number, rows: ImageRow[], score: number) { + if (start === images.length) { + if (score < bestScore) { best = rows; bestScore = score; } + return; + } + if (rows.length === 2) return; + for (let end = start + 1; end <= images.length; end += 1) { + const count = end - start; + const rowRatios = ratios.slice(start, end); + const ratioSum = rowRatios.reduce((sum, ratio) => sum + ratio, 0); + const naturalHeight = Math.min(...images.slice(start, end).map((image, i) => + image ? Math.min(image.height, image.width / rowRatios[i]) : maxHeight)); + const height = Math.min((width - IMAGE_GAP * (count - 1)) / ratioSum, maxHeight, naturalHeight); + const widths = rowRatios.map((ratio) => ratio * height); + const unusedWidth = (width - ratioSum * height - IMAGE_GAP * (count - 1)) / width; + const rowScore = count * (Math.log(height / targetHeight) ** 2 + unusedWidth ** 2) + 0.55; + const lonelyLast = end === images.length && count === 1 && images.length > 2 ? 0.25 : 0; + visit(end, [...rows, { start, widths, height }], score + rowScore + lonelyLast); + } + } + + visit(0, [], 0); + return best; +} diff --git a/webui/src/tests/attachment-tile.test.tsx b/webui/src/tests/attachment-tile.test.tsx index 5c06a4b02..75be4b7b8 100644 --- a/webui/src/tests/attachment-tile.test.tsx +++ b/webui/src/tests/attachment-tile.test.tsx @@ -1,7 +1,12 @@ -import { render, screen } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; +import { render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { beforeAll, describe, expect, it } from "vitest"; import { AttachmentTile } from "@/components/AttachmentTile"; +import { MessageBubble } from "@/components/MessageBubble"; +import { preloadMarkdownText } from "@/components/MarkdownText"; + +beforeAll(preloadMarkdownText); describe("attachment download cards", () => { it("keeps named download actions distinct and shows the file extension", () => { @@ -14,9 +19,9 @@ describe("attachment download cards", () => { expect(archive).toHaveAttribute("download", "猫咪图鉴完整包.zip"); expect(archive).toHaveAttribute("href", "/api/media/signed/archive"); expect(archive).toHaveAttribute("title", "猫咪图鉴完整包.zip"); - expect(archive).toHaveTextContent("ZIP"); + expect(archive.closest("[data-file-attachment]")).toHaveTextContent("ZIP"); expect(archive.querySelector(".lucide-download")).toHaveAttribute("aria-hidden", "true"); - expect(screen.getByRole("link", { name: "Download source.tar.gz" })).toHaveTextContent("TAR.GZ"); + expect(screen.getByRole("link", { name: "Download source.tar.gz" }).closest("[data-file-attachment]")).toHaveTextContent("TAR.GZ"); }); it("changes a pending file to a download only after its URL arrives", () => { @@ -26,7 +31,8 @@ describe("attachment download cards", () => { expect(screen.queryByRole("link")).not.toBeInTheDocument(); rerender(); - expect(screen.getByRole("link", { name: "Download report.pdf" })).toHaveTextContent("PDF"); + expect(screen.getByRole("link", { name: "Download report.pdf" })).toHaveAttribute("href", "/api/media/signed/report"); + expect(screen.getByText("PDF")).toBeVisible(); rerender(); expect(screen.getByText("Attachment unavailable")).toBeVisible(); @@ -40,8 +46,40 @@ describe("attachment download cards", () => { ); 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"); + expect(unnamed.closest("[data-file-attachment]")).toHaveTextContent("ZIP"); + expect(screen.getByRole("link", { name: "Download LICENSE" }).closest("[data-file-attachment]")).toHaveTextContent("File attachment"); + }); +}); + +describe("delivered file type cards", () => { + it.each(["user", "assistant"] as const)("keeps %s file information and named downloads separate", async (role) => { + const user = userEvent.setup(); + const { container } = render(); + const cards = container.querySelectorAll("[data-file-attachment]"); + expect(Array.from(cards).map((card) => card.textContent)).toEqual(["JSON", "JSON"]); + const first = within(cards[0] as HTMLElement); + const download = first.getByRole("link", { name: "Download render-config.json" }); + expect(download).toHaveAttribute("href", "/api/media/signed/first"); + expect(download).toHaveAttribute("download", "render-config.json"); + await user.click(first.getByRole("button", { name: "render-config.json" })); + expect(await screen.findByRole("dialog", { name: "render-config.json" })).toHaveTextContent("render-config.json"); + await user.keyboard("{Escape}"); + expect(first.getByRole("button", { name: "render-config.json" })).toHaveFocus(); + expect(within(cards[1] as HTMLElement).getByRole("link", { name: "Download another-config.json" })).toHaveAttribute("href", "/api/media/signed/second"); + }); + + it("keeps a file link inside its paragraph instead of extracting it into an attachment card", async () => { + const { container } = render(); + const link = await screen.findByRole("link", { name: "notes.txt" }); + expect(link.closest("p")).toHaveTextContent("Before notes.txt after."); + expect(link).toHaveAttribute("href", "https://example.com/notes.txt"); + expect(container.querySelectorAll("[data-file-attachment]")).toHaveLength(1); + expect(screen.getByRole("link", { name: "Download report.pdf" })).toHaveAttribute("download", "report.pdf"); }); }); diff --git a/webui/src/tests/file-reference-icon.test.tsx b/webui/src/tests/file-reference-icon.test.tsx index de7dff209..4f0dcb252 100644 --- a/webui/src/tests/file-reference-icon.test.tsx +++ b/webui/src/tests/file-reference-icon.test.tsx @@ -1,4 +1,4 @@ -import { fireEvent, render, screen } from "@testing-library/react"; +import { fireEvent, render, screen, within } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; import { AttachmentTile } from "@/components/AttachmentTile"; @@ -48,30 +48,45 @@ describe("shared file icons", () => { expect(svg.querySelector("text, [fill], [stroke]")).toBeNull(); }); - 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) => { + it.each([ + ["chart.png", "PNG"], + ["index.html", "HTML"], + ["data.json", "JSON"], + ["script.py", "PY"], + ["notes.md", "MD"], + ["archive.zip", "ZIP"], + ["report.pdf", "PDF"], + ["budget.xlsx", "XLSX"], + ["slides.pptx", "PPTX"], + ["song.mp3", "MP3"], + ])( + "shares reply and tab glyphs for %s while keeping attachment type cards and actions distinct", (path, type) => { const open = vi.fn(); - render(<> + const references = render(<> {}} onCloseTab={() => {}} onClose={() => {}} onResizeStart={() => {}}>

Preview

- ); - const reference = screen.getByRole("button", { name: path }); - const tab = screen.getByRole("tab", { name: path }); - const attachment = screen.getByRole("link", { name: `Download ${path}` }); + const attachments = render(); + const reference = within(references.container).getByRole("button", { name: path }); + const tab = within(references.container).getByRole("tab", { name: path }); + const information = within(attachments.container).getByRole("button", { name: path }); + const download = within(attachments.container).getByRole("link", { name: `Download ${path}` }); const glyph = reference.querySelector("svg")!.innerHTML; expect(tab.querySelector("svg")!.innerHTML).toBe(glyph); - expect(attachment.querySelector("svg")!.innerHTML).toBe(glyph); expect(tab.querySelector("svg")).toHaveClass("size-3.5"); - expect(attachment.querySelector("svg")).toHaveClass("size-5"); expect(tab.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("download", path); + expect(within(information).getByText(type)).toBeVisible(); + expect(information.querySelector("svg")).toHaveClass("lucide-file-text"); + expect(download.querySelector("svg")).toHaveClass("lucide-download", "size-4"); + expect(download).toHaveAttribute("href", `/download/${path}`); + expect(download).toHaveAttribute("download", path); fireEvent.click(reference); expect(open).toHaveBeenCalledWith(path); + fireEvent.click(information); + expect(screen.getByRole("dialog", { name: path })).toHaveTextContent(path); + expect(open).toHaveBeenCalledTimes(1); }, ); @@ -88,10 +103,15 @@ describe("shared file icons", () => { expect(open).toHaveBeenCalledWith("/repo/src/app.tsx"); }); - it.each(["image", "video"] as const)("retains %s identity when its attachment is unavailable", (kind) => { - const { container } = render(); - expect(container.querySelector("svg")).toHaveClass(kind === "image" ? "lucide-file-image" : "lucide-file-video2"); + it.each([ + ["image", "Image attachment"], + ["video", "Video attachment"], + ] as const)("retains %s identity when its attachment is unavailable", (kind, label) => { + render(); + const information = screen.getByRole("button", { name: "Unavailable" }); + expect(within(information).getByText(label)).toBeVisible(); + expect(information).toHaveAccessibleDescription("Attachment unavailable"); expect(screen.queryByRole("link")).not.toBeInTheDocument(); - expect(screen.getByText("Attachment unavailable")).toBeInTheDocument(); + expect(screen.getByText("Attachment unavailable")).toBeVisible(); }); }); diff --git a/webui/src/tests/image-gallery-layout.test.ts b/webui/src/tests/image-gallery-layout.test.ts new file mode 100644 index 000000000..31d8f7f8e --- /dev/null +++ b/webui/src/tests/image-gallery-layout.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "vitest"; + +import { IMAGE_GAP, layoutImageRows } from "@/lib/image-gallery-layout"; + +const square = { width: 800, height: 800 }; + +describe("ordered image layout", () => { + it("chooses two balanced rows for four square images, rather than a tiny single strip", () => { + const rows = layoutImageRows([square, square, square, square], 360, 144, 224); + expect(rows.map((row) => row.widths.length)).toEqual([2, 2]); + for (const row of rows) { + expect(row.height).toBe(176); + expect(row.widths).toEqual([176, 176]); + } + }); + + it.each([360, 240])("preserves the order and native proportions of mixed images at %ipx", (width) => { + const images = [ + { width: 1200, height: 800 }, + { width: 600, height: 900 }, + square, + { width: 1600, height: 900 }, + ]; + const rows = layoutImageRows(images, width, 144, 224); + let position = 0; + for (const row of rows) { + expect(row.start).toBe(position); + expect(row.height).toBeGreaterThan(0); + expect(row.height).toBeLessThanOrEqual(224); + expect(row.widths.reduce((sum, item) => sum + item, IMAGE_GAP * (row.widths.length - 1))).toBeLessThanOrEqual(width + 0.001); + for (const tileWidth of row.widths) { + expect(tileWidth / row.height).toBeCloseTo(images[position].width / images[position].height); + position += 1; + } + } + expect(position).toBe(images.length); + expect(rows.length).toBeLessThanOrEqual(2); + }); + + it("fits a single portrait without stretching it into a square or exceeding the height limit", () => { + const [row] = layoutImageRows([{ width: 600, height: 900 }], 360, 144, 320); + expect(row.height).toBe(320); + expect(row.widths[0]).toBeCloseTo(320 * 2 / 3); + }); + + it("does not enlarge a small image beyond its original resolution", () => { + const [row] = layoutImageRows([{ width: 48, height: 32 }], 360, 144, 320); + expect(row).toEqual({ start: 0, widths: [48], height: 32 }); + }); + + it("gives extreme screenshots a bounded frame instead of a nearly invisible sliver", () => { + const [long] = layoutImageRows([{ width: 600, height: 4800 }], 360, 144, 320); + const [wide] = layoutImageRows([{ width: 4800, height: 600 }], 360, 144, 320); + expect(long).toEqual({ start: 0, widths: [160], height: 320 }); + expect(wide).toEqual({ start: 0, widths: [360], height: 120 }); + }); +}); diff --git a/webui/src/tests/image-gallery.test.tsx b/webui/src/tests/image-gallery.test.tsx index 151f6058b..c77733359 100644 --- a/webui/src/tests/image-gallery.test.tsx +++ b/webui/src/tests/image-gallery.test.tsx @@ -70,13 +70,60 @@ describe("image presentation", () => { expect(within(screen.getByRole("dialog")).getByRole("img", { name: "0.png" })).toBeVisible(); }); - it("replaces a broken thumbnail with a quiet named placeholder", () => { + it("shows an explicit failure without painting a filename across the thumbnail", () => { render(); fireEvent.error(screen.getByRole("img")); - expect(screen.queryByRole("img")).not.toBeInTheDocument(); - expect(screen.getByText("0.png")).toBeVisible(); + expect(screen.getByText("Attachment unavailable")).toBeVisible(); + expect(screen.getByLabelText("Attachment unavailable: 0.png")).toHaveAttribute("title", "0.png"); + expect(screen.queryByText("0.png")).not.toBeInTheDocument(); expect(screen.queryByRole("button")).not.toBeInTheDocument(); }); + + it("uses the loaded picture's shape for a sent user image and retains its accessible viewer action", async () => { + const user = userEvent.setup(); + render(); + const image = screen.getByRole("img", { name: "portrait.png" }); + Object.defineProperties(image, { naturalWidth: { value: 600 }, naturalHeight: { value: 900 } }); + fireEvent.load(image); + const open = screen.getByRole("button", { name: "View image: portrait.png" }); + expect(Number.parseFloat(open.style.width)).toBeCloseTo(320 * 2 / 3); + expect(open.style.height).toBe("320px"); + expect(screen.queryByText("portrait.png")).not.toBeInTheDocument(); + await user.click(open); + expect(within(screen.getByRole("dialog")).getByRole("img", { name: "portrait.png" })).toBeVisible(); + }); + + it("settles a mixed gallery together after loading and preserves click order through regrouping", async () => { + const user = userEvent.setup(); + const { container } = render(); + for (const image of screen.getAllByRole("img")) { + Object.defineProperties(image, { naturalWidth: { value: 800 }, naturalHeight: { value: 800 } }); + fireEvent.load(image); + } + const tiles = Array.from(container.querySelectorAll("[data-image-gallery] > button")); + expect(tiles.map((tile) => Number.parseFloat(tile.style.top))).toEqual([0, 0, 184, 184]); + expect(screen.getAllByRole("button").map((button) => button.getAttribute("aria-label"))).toEqual( + [0, 1, 2, 3].map((index) => `View image: ${index}.png`)); + await user.click(screen.getByRole("button", { name: "View image: 2.png" })); + expect(screen.getByText("3 / 4")).toBeVisible(); + expect(within(screen.getByRole("dialog")).getByRole("img", { name: "2.png" })).toBeVisible(); + }); + + it("returns focus to the same thumbnail when late image loads change the row grouping", async () => { + const user = userEvent.setup(); + const { container } = render(); + const thumbnails = container.querySelectorAll("[data-image-gallery] img"); + const opener = screen.getByRole("button", { name: "View image: 2.png" }); + await user.click(opener); + for (const image of thumbnails) { + Object.defineProperties(image, { naturalWidth: { value: 600 }, naturalHeight: { value: 900 } }); + fireEvent.load(image); + } + await user.keyboard("{Escape}"); + expect(screen.getByRole("button", { name: "View image: 2.png" })).toBe(opener); + expect(opener).toHaveFocus(); + }); }); describe("file quick look", () => { diff --git a/webui/src/tests/markdown-text-renderer.test.tsx b/webui/src/tests/markdown-text-renderer.test.tsx index 529f69e20..89dad6bfe 100644 --- a/webui/src/tests/markdown-text-renderer.test.tsx +++ b/webui/src/tests/markdown-text-renderer.test.tsx @@ -294,7 +294,8 @@ describe("MarkdownTextRenderer", () => { it("renders markdown links with file-looking names as file attachments", () => { render(![index.html](/api/media/sig/html)); - expect(screen.getByRole("link", { name: "Download index.html" })).toHaveTextContent("index.html"); + expect(screen.getByRole("link", { name: "Download index.html" })).toHaveAttribute("download", "index.html"); + expect(screen.getByRole("button", { name: "index.html" })).toBeVisible(); expect(screen.queryByRole("img", { name: "index.html" })).not.toBeInTheDocument(); }); diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx index 1521d4bd6..3b4a26398 100644 --- a/webui/src/tests/message-bubble.test.tsx +++ b/webui/src/tests/message-bubble.test.tsx @@ -1238,18 +1238,15 @@ describe("MessageBubble", () => { const { container } = render(); + const image = container.querySelector("img")!; + Object.defineProperties(image, { naturalWidth: { value: 1600 }, naturalHeight: { value: 900 } }); + fireEvent.load(image); const imageButton = screen.getByRole("button", { name: /view image/i }); - expect(imageButton).toHaveClass("w-[min(100%,28rem)]", "rounded-control"); - expect(imageButton).toHaveClass( - "border", - "border-border/60", - "focus-visible:ring-2", - ); - expect(imageButton).not.toHaveClass("hover:scale-[1.01]"); - expect(imageButton).not.toHaveClass("hover:ring-2"); - expect(imageButton).not.toHaveClass("hover:ring-primary/25"); + expect(imageButton).toHaveClass("rounded-control", "focus-visible:ring-2"); + expect(imageButton.style.width).toBe("448px"); + expect(imageButton.style.height).toBe("252px"); expect(imageButton).not.toHaveAttribute("title"); - expect(container.querySelector("img")).toHaveClass("h-auto", "w-full", "object-contain"); + expect(image).toHaveClass("object-contain"); }); it("renders mislabeled html assistant media as a file attachment", () => { @@ -1269,7 +1266,8 @@ describe("MessageBubble", () => { const { container } = render(); - expect(screen.getByRole("link", { name: "Download index.html" })).toHaveTextContent("index.html"); + expect(screen.getByRole("link", { name: "Download index.html" })).toHaveAttribute("download", "index.html"); + expect(screen.getByRole("button", { name: "index.html" })).toBeVisible(); expect(container.querySelector("img")).not.toBeInTheDocument(); }); diff --git a/webui/src/tests/thread-composer-attach.test.tsx b/webui/src/tests/thread-composer-attach.test.tsx index 3d57f9529..5127ef263 100644 --- a/webui/src/tests/thread-composer-attach.test.tsx +++ b/webui/src/tests/thread-composer-attach.test.tsx @@ -4,7 +4,9 @@ import { render, screen, waitFor, + within, } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { ThreadComposer } from "@/components/thread/ThreadComposer"; @@ -87,6 +89,7 @@ beforeEach(() => { describe("ThreadComposer — attachments", () => { it("previews a picked image with size details on hover and includes its data url on send", async () => { + const user = userEvent.setup(); const file = pngFile("a.png", 100); encodeImage.mockResolvedValueOnce({ ...resolveReady(file), normalized: true, bytes: 50 }); const onSend = vi.fn(); @@ -103,7 +106,10 @@ describe("ThreadComposer — attachments", () => { }); expect(screen.getByRole("img", { name: "a.png" })).toHaveAttribute("src", expect.stringContaining("blob:")); - expect(screen.getByTestId("composer-chip")).toHaveAttribute("title", "a.png\n100 B → 50 B (auto)"); + await user.hover(screen.getByRole("button", { name: "a.png" })); + const details = await screen.findByRole("tooltip"); + expect(details).toHaveTextContent("a.png"); + expect(details).toHaveTextContent("100 B → 50 B (auto)"); expect(screen.getByRole("button", { name: "Remove attachment" })).toHaveAccessibleDescription("a.png"); const textarea = screen.getByLabelText(/message input/i); @@ -118,6 +124,32 @@ describe("ThreadComposer — attachments", () => { expect(images[0].media.name).toBe("a.png"); }); + it("identifies same-type files through focus/tap details and removes only the chosen attachment", async () => { + const user = userEvent.setup(); + const first = new File(['{"theme":"light"}'], "render-config.json", { type: "application/json" }); + const second = new File(['{"theme":"dark"}'], "another-config.json", { type: "application/json" }); + const onSend = vi.fn(); + render(); + const textarea = screen.getByLabelText(/message input/i); + const input = textarea.closest("form")!.querySelector('input[type="file"]')!; + await act(async () => fireEvent.change(input, { target: { files: [first, second] } })); + const cards = screen.getAllByTestId("composer-chip"); + expect(cards.map((card) => card.textContent)).toEqual(["JSON", "JSON"]); + const firstInfo = within(cards[0]).getByRole("button", { name: first.name }); + act(() => firstInfo.focus()); + expect(await screen.findByRole("tooltip")).toHaveTextContent(first.name); + expect(screen.getByRole("tooltip")).toHaveTextContent(`${first.size} B`); + await user.keyboard("{Escape}"); + await user.click(within(cards[1]).getByRole("button", { name: second.name })); + expect(await screen.findByRole("dialog", { name: second.name })).toHaveTextContent(second.name); + await user.keyboard("{Escape}"); + await user.click(within(cards[1]).getByRole("button", { name: "Remove attachment" })); + expect(screen.getAllByTestId("composer-chip")).toHaveLength(1); + expect(screen.getByRole("button", { name: first.name })).toBeVisible(); + fireEvent.keyDown(textarea, { key: "Enter" }); + expect(onSend.mock.calls[0][1].map((attachment: { media: { name: string } }) => attachment.media.name)).toEqual([first.name]); + }); + it("attaches a picked PDF and includes its data url on send", async () => { const file = pdfFile(); const onSend = vi.fn(); @@ -134,7 +166,7 @@ describe("ThreadComposer — attachments", () => { }); await waitFor(() => - expect(screen.getByTestId("composer-chip")).toHaveTextContent("report.pdf"), + expect(screen.getByTestId("composer-chip")).toHaveTextContent("PDF"), ); const textarea = screen.getByLabelText(/message input/i); @@ -168,7 +200,7 @@ describe("ThreadComposer — attachments", () => { }); await waitFor(() => - expect(screen.getByTestId("composer-chip")).toHaveTextContent("report.csv"), + expect(screen.getByRole("button", { name: "report.csv" })).toHaveAccessibleDescription(expect.stringContaining("B")), ); const textarea = screen.getByLabelText(/message input/i); @@ -242,8 +274,8 @@ describe("ThreadComposer — attachments", () => { expect(screen.queryByRole("alert")).not.toBeInTheDocument(); expect(screen.getAllByTestId("composer-chip")).toHaveLength(2); - expect(screen.getByText("first.pdf")).toBeInTheDocument(); - expect(screen.getByText("second.pdf")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "first.pdf" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "second.pdf" })).toBeInTheDocument(); }); it("enforces the decoded attachment-total policy independently", async () => { @@ -317,7 +349,7 @@ describe("ThreadComposer — attachments", () => { }); await waitFor(() => - expect(screen.getByText("pasted.pdf")).toBeInTheDocument(), + expect(screen.getByRole("button", { name: "pasted.pdf" })).toBeInTheDocument(), ); await act(async () => { @@ -332,7 +364,7 @@ describe("ThreadComposer — attachments", () => { }); await waitFor(() => - expect(screen.getByText("dropped.pdf")).toBeInTheDocument(), + expect(screen.getByRole("button", { name: "dropped.pdf" })).toBeInTheDocument(), ); expect(screen.getAllByTestId("composer-chip")).toHaveLength(2); expect(encodeImage).not.toHaveBeenCalled(); @@ -421,7 +453,7 @@ describe("local attachment paths and video ingress", () => { fireEvent.change(input, { target: { value: "keep this " } }); (input as HTMLTextAreaElement).setSelectionRange(10, 10); fireEvent.paste(input, { clipboardData: { items: [], getData: () => '"C:\\project\\my clip.mp4"' } }); - await waitFor(() => expect(screen.getByTestId("composer-chip")).toHaveTextContent("my clip.mp4")); + await waitFor(() => expect(screen.getByRole("button", { name: "my clip.mp4" })).toBeInTheDocument()); expect(input).toHaveValue("keep this "); expect(inspect).toHaveBeenCalledWith(local.path); fireEvent.keyDown(input, { key: "Enter" }); @@ -568,7 +600,7 @@ describe("local attachment paths and video ingress", () => { render(); const input = screen.getByLabelText(/message input/i); fireEvent.paste(input, { clipboardData: { items: [], getData: () => document.path } }); - await screen.findByText(document.name); + await screen.findByRole("button", { name: document.name }); const picker = input.closest("form")!.querySelector('input[type="file"]')!; fireEvent.change(picker, { target: { files: [pdfFile("upload.pdf", 8)] } }); await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled()); diff --git a/webui/src/tests/thread-messages.test.tsx b/webui/src/tests/thread-messages.test.tsx index 18c817dda..dc5990228 100644 --- a/webui/src/tests/thread-messages.test.tsx +++ b/webui/src/tests/thread-messages.test.tsx @@ -2022,9 +2022,14 @@ describe("ThreadMessages", () => { }); render(); - expect(screen.getByText("result.csv")).toBeInTheDocument(); - const ownerRow = screen.getByText("result.csv") - .closest("[data-thread-display-unit]")!; + const information = screen.getByRole("button", { name: "result.csv" }); + const download = screen.getByRole("link", { name: "Download result.csv" }); + expect(information).toBeVisible(); + expect(download).toHaveAttribute("href", "/api/media/result.csv"); + expect(download).toHaveAttribute("download", "result.csv"); + expect(download.closest("[data-testid='activity-model-message'], [data-testid='agent-activity-content']")).toBeNull(); + const ownerRow = information.closest("[data-thread-display-unit]")!; + expect(ownerRow).toContainElement(download); openAssistantBlockMenu(ownerRow); expect(screen.getByRole("button", { name: "Worked" })).toBeInTheDocument(); }); diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index b8c7997ad..947b6725e 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -593,9 +593,12 @@ describe("ThreadShell", () => { await waitFor(() => expect(onCreateChat).toHaveBeenCalledTimes(1)); view.rerender(shell("created")); await waitFor(() => expect(screen.getByRole("textbox")).toHaveValue("keep the first draft")); - expect(await screen.findByTestId("composer-chip")).toHaveTextContent("video.mp4"); + expect(within(await screen.findByTestId("composer-chip")).getByRole("button", { name: "video.mp4" })).toBeVisible(); expect(screen.getByRole("alert")).toHaveTextContent("file not found"); - expect(store.get("websocket:created")?.attachments).toHaveLength(1); + expect(store.get("websocket:created")).toMatchObject({ + text: "keep the first draft", + attachments: [{ path: "/project/video.mp4", name: "video.mp4", kind: "video" }], + }); expect(store.has("new:chat")).toBe(false); client.sendAttachments.mockResolvedValue(undefined); fireEvent.click(screen.getByRole("button", { name: "Send message" }));