feat(webui): show image attachments as composer thumbnails

This commit is contained in:
Xubin Ren committed 2026-10-25 00:09:24 +08:00
1 parent 127f38b7c3
commit 0bdc24a891
5 files changed
+158 -37

No files matched your search

+2
View File
@@ -181,6 +181,8 @@ In Restricted mode, ordinary file and shell work stays inside the selected proje
The composer supports text, attachments (images, documents, and videos), slash commands and `@` mentions. With voice transcription configured, the empty composer offers voice input; transcription is added to the draft before sending.
Images appear as thumbnails above the draft. Hover over a thumbnail for its filename and size; use its top-right × to remove it before sending. Documents and videos keep their file cards, and attachment errors remain visible.
Choose or drop MP4, WebM, or MOV videos into the composer (one per message, up to 20 MiB per upload). You can play them in WebUI; the Agent cannot directly analyze their contents yet.
To attach a file on the connected nanobot host, paste its path on its own. Quoted paths and spaces are supported; relative paths start from the topic's workspace. The topic's access permissions apply. Path references do not upload or copy the file and have no file-size or combined-size limit; supported formats and attachment counts still apply. If attaching fails, the text stays in your draft.
+102
View File
@@ -0,0 +1,102 @@
import { expect, test, type Page } from "@playwright/test";
async function imageFile(page: Page, name: string, background: string) {
const data = await page.evaluate((fill) => {
const canvas = document.createElement("canvas");
canvas.width = 480;
canvas.height = 320;
const context = canvas.getContext("2d")!;
context.fillStyle = fill;
context.fillRect(0, 0, 480, 320);
context.fillStyle = "#7898a5";
context.fillRect(48, 64, 260, 24);
context.fillRect(48, 112, 380, 16);
context.fillRect(48, 152, 320, 16);
return canvas.toDataURL("image/png").split(",")[1];
}, background);
return { name, mimeType: "image/png", buffer: Buffer.from(data, "base64") };
}
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
await page.route("**/api/**", route => route.fulfill({ json: {} }));
});
for (const { width, dark, variant } of [
{ width: 1440, dark: false, variant: "hero" },
{ width: 1440, dark: true, variant: "thread" },
{ width: 360, dark: false, variant: "hero" },
{ width: 314, dark: true, variant: "thread" },
]) {
test.describe(`${width}px ${dark ? "dark" : "light"} ${variant} attachments`, () => {
test.use({ viewport: { width, height: 800 }, hasTouch: width < 640 });
test("shows image-only thumbnails and keeps mixed attachments removable", async ({ page }, testInfo) => {
await page.goto(`/browser/fixture.html?case=composer-action&composerVariant=${variant}`);
await page.locator("html").evaluate((node, enabled) => node.classList.toggle("dark", enabled), dark);
const files = [
await imageFile(page, "white.png", "#fff"),
await imageFile(page, "dark.png", "#111"),
await imageFile(page, "notes.png", "#dfebe4"),
{ name: "report.pdf", mimeType: "application/pdf", buffer: Buffer.from("%PDF-1.4\npreview fixture") },
];
await page.locator('input[type="file"]').setInputFiles(files);
await expect(page.getByRole("button", { name: "Send message", exact: true })).toBeEnabled();
const chips = page.getByTestId("composer-chip");
await expect(chips).toHaveCount(4);
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);
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);
expect(await chip.innerText()).toBe("");
const remove = chip.getByRole("button", { name: "Remove attachment" });
await expect(remove).toBeVisible();
await expect(remove).toHaveAccessibleDescription(name);
const target = (await remove.boundingBox())!;
expect(target.width).toBeGreaterThanOrEqual(44);
expect(target.height).toBeGreaterThanOrEqual(44);
expect(target.x + target.width).toBeCloseTo(box.x + box.width - 1);
expect(target.y).toBeCloseTo(box.y + 1);
}
const document = chips.filter({ hasText: "report.pdf" });
await expect(document).toContainText("B");
expect((await document.boundingBox())!.height).toBeLessThan(96);
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");
if (width < 640) await whiteRemove.tap();
else await whiteRemove.click();
await expect(chips).toHaveCount(3);
const darkRemove = chips.filter({ has: page.getByRole("img", { name: "dark.png", exact: true }) }).getByRole("button");
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 expect(page.getByRole("textbox")).toBeFocused();
await expect(page.getByRole("textbox")).toHaveValue("Compare these images with the report.");
});
});
}
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 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(page.getByRole("button", { name: "Send message", exact: true })).toBeDisabled();
await chip.getByRole("button", { name: "Remove attachment" }).click();
await expect(page.getByRole("button", { name: "Voice input", exact: true })).toBeEnabled();
await expect(page.getByRole("textbox")).toBeFocused();
});
+31 -19
View File
@@ -2670,7 +2670,7 @@ export function ThreadComposer({
) : null}
{images.length > 0 ? (
<div
className="flex flex-wrap gap-2 px-3 pt-3"
className="flex flex-wrap items-start gap-2 px-3 pt-3"
aria-label={t("thread.composer.attachImage")}
>
{images.map((img) => (
@@ -3403,6 +3403,7 @@ function AttachmentChip({
image.status === "ready" && image.normalized && image.encodedBytes
? normalizedHint(image.file.size, image.encodedBytes)
: formatBytes(image.file.size);
const isThumbnail = image.kind === "image" && image.status !== "error";
const tone =
image.status === "error"
? "border-destructive/40 bg-destructive/5 text-destructive"
@@ -3411,18 +3412,22 @@ function AttachmentChip({
return (
<div
className={cn(
"group relative flex items-center gap-2 rounded-control border px-2 py-1.5",
"group relative flex max-w-full shrink-0 items-center rounded-control border",
"transition-colors motion-reduce:transition-none",
isThumbnail ? "h-24 w-24" : "gap-2 px-2 py-1.5",
tone,
)}
title={isThumbnail ? `${image.file.name}\n${sizeLabel}` : undefined}
data-testid="composer-chip"
>
<div className="relative h-10 w-10 overflow-hidden rounded-md bg-background">
<div className={cn(
"relative shrink-0 overflow-hidden bg-background",
isThumbnail ? "h-full w-full rounded-[inherit]" : "h-10 w-10 rounded-md",
)}>
{image.kind === "image" && image.previewUrl ? (
<img
src={image.previewUrl}
alt=""
aria-hidden
alt={isThumbnail ? image.file.name : ""}
loading="eager"
draggable={false}
className="h-full w-full object-cover"
@@ -3447,29 +3452,36 @@ function AttachmentChip({
</div>
) : null}
</div>
<div className="flex min-w-0 flex-col text-[11.5px] leading-4">
<span className="max-w-[min(14rem,calc(100vw-8rem))] truncate font-medium" title={image.file.name}>
{image.file.name}
</span>
<span className="truncate text-muted-foreground">
{image.status === "error" && image.error
? formatError(image.error)
: sizeLabel}
</span>
</div>
{!isThumbnail ? (
<div className="flex min-w-0 flex-col text-[11.5px] leading-4">
<span className="max-w-[min(14rem,calc(100vw-8rem))] truncate font-medium" title={image.file.name}>
{image.file.name}
</span>
<span className="truncate text-muted-foreground">
{image.status === "error" && image.error
? formatError(image.error)
: sizeLabel}
</span>
</div>
) : null}
<button
type="button"
ref={registerRef}
onClick={onRemove}
onKeyDown={onKeyDown}
aria-label={labelRemove}
aria-description={image.file.name}
title={labelRemove}
className={cn(
"ml-1 grid h-5 w-5 flex-none place-items-center rounded-full",
"text-muted-foreground/80 hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground/30",
"grid flex-none place-items-center rounded-full focus-visible:outline-none focus-visible:ring-2",
isThumbnail
? "group/remove absolute right-0 top-0 h-11 w-11 focus-visible:bg-black/50 focus-visible:ring-inset focus-visible:ring-white"
: "ml-1 h-5 w-5 text-muted-foreground/80 hover:text-foreground focus-visible:ring-foreground/30",
)}
>
<X className="h-3.5 w-3.5" aria-hidden />
<span className={cn(isThumbnail && "grid h-6 w-6 place-items-center rounded-full bg-black/65 text-white group-hover/remove:bg-black/80")}>
<X className="h-3.5 w-3.5" aria-hidden />
</span>
</button>
</div>
);
+17 -12
View File
@@ -34,7 +34,7 @@ function csvFile(name = "report.csv", type = "application/vnd.ms-excel") {
return new File(["name,value\nnanobot,1"], name, { type });
}
function resolveReady(file: File): EncodeResponse {
function resolveReady(file: File): Extract<EncodeResponse, { ok: true }> {
return {
id: "stub",
ok: true,
@@ -86,9 +86,9 @@ beforeEach(() => {
});
describe("ThreadComposer — attachments", () => {
it("attaches a picked image and includes its data url on send", async () => {
const file = pngFile("a.png");
encodeImage.mockResolvedValueOnce(resolveReady(file));
it("previews a picked image with size details on hover and includes its data url on send", async () => {
const file = pngFile("a.png", 100);
encodeImage.mockResolvedValueOnce({ ...resolveReady(file), normalized: true, bytes: 50 });
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} />);
@@ -102,9 +102,9 @@ describe("ThreadComposer — attachments", () => {
fireEvent.change(input, { target: { files: [file] } });
});
await waitFor(() =>
expect(screen.getByTestId("composer-chip")).toBeInTheDocument(),
);
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)");
expect(screen.getByRole("button", { name: "Remove attachment" })).toHaveAccessibleDescription("a.png");
const textarea = screen.getByLabelText(/message input/i);
fireEvent.change(textarea, { target: { value: "hi" } });
@@ -359,6 +359,8 @@ describe("ThreadComposer — attachments", () => {
fireEvent.change(fileInput, { target: { files: [file] } });
});
expect(screen.getByRole("img", { name: "slow.png" })).toBeInTheDocument();
expect(screen.getByLabelText("Encoding…")).toBeInTheDocument();
const textarea = screen.getByLabelText(/message input/i);
fireEvent.change(textarea, { target: { value: "hello" } });
fireEvent.keyDown(textarea, { key: "Enter" });
@@ -400,6 +402,9 @@ describe("ThreadComposer — attachments", () => {
fireEvent.change(textarea, { target: { value: "hi" } });
fireEvent.keyDown(textarea, { key: "Enter" });
expect(onSend).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Remove attachment" }));
fireEvent.keyDown(textarea, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith("hi", undefined, undefined);
});
});
@@ -505,15 +510,15 @@ describe("local attachment paths and video ingress", () => {
const view = render(composer());
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => firstLocal.path } });
await screen.findByText(firstLocal.name);
await screen.findByRole("img", { name: firstLocal.name });
fireEvent.change(input.closest("form")!.querySelector('input[type="file"]')!, { target: { files: [pngFile("middle.png")] } });
await screen.findByText("middle.png");
await screen.findByRole("img", { name: "middle.png" });
fireEvent.paste(input, { clipboardData: { items: [], getData: () => lastLocal.path } });
await screen.findByText(lastLocal.name);
await screen.findByRole("img", { name: lastLocal.name });
fireEvent.change(input, { target: { value: "compare the first, second and third images" } });
await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
expect(screen.getAllByTestId("composer-chip").map((chip) => chip.textContent)).toEqual([
expect.stringContaining("first.png"), expect.stringContaining("middle.png"), expect.stringContaining("last.png"),
expect(screen.getAllByRole("img").map((image) => image.getAttribute("alt"))).toEqual([
"first.png", "middle.png", "last.png",
]);
view.unmount();
render(composer());
+6 -6
View File
@@ -3822,7 +3822,7 @@ describe("ThreadComposer", () => {
expect(fileInput).toBeTruthy();
const file = new File(["image"], "draft.png", { type: "image/png" });
fireEvent.change(fileInput!, { target: { files: [file] } });
await screen.findByText("draft.png");
await screen.findByRole("img", { name: "draft.png" });
fireEvent.change(input, { target: { value: "look at this" } });
fireEvent.keyDown(input, { key: "Enter" });
@@ -3834,7 +3834,7 @@ describe("ThreadComposer", () => {
fireEvent.click(screen.getByRole("button", { name: "Edit message" }));
expect(input).toHaveValue("look at this");
expect(screen.getByTestId("composer-chip")).toHaveTextContent("draft.png");
expect(screen.getByRole("img", { name: "draft.png" })).toBeInTheDocument();
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
fireEvent.keyDown(input, { key: "Enter" });
@@ -4093,7 +4093,7 @@ describe("ThreadComposer", () => {
fireEvent.change(first.container.querySelector<HTMLInputElement>('input[type="file"]')!, {
target: { files: [new File(["image"], "queued.png", { type: "image/png" })] },
});
await screen.findByText("queued.png");
await screen.findByRole("img", { name: "queued.png" });
for (const text of ["queued attachment", "more guidance"]) {
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: text } });
fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" });
@@ -4263,7 +4263,7 @@ describe("session composer drafts", () => {
view.rerender(composer("other-draft"));
view.rerender(composer("unchanged-draft"));
expect(screen.getByRole("textbox")).toHaveValue("send once");
if (attachment) await screen.findByText("draft.png");
if (attachment) await screen.findByRole("img", { name: "draft.png" });
await act(async () => resolveSend(true));
view.unmount();
expect(new ComposerDraftStore().get("unchanged-draft", true)).toBeUndefined();
@@ -4299,10 +4299,10 @@ describe("session composer drafts", () => {
const file = new File(["image"], "draft.png", { type: "image/png" });
fireEvent.change(view.container.querySelector('input[type="file"]')!, { target: { files: [file] } });
view.rerender(composer("chat-b"));
expect(screen.queryByText("draft.png")).not.toBeInTheDocument();
expect(screen.queryByRole("img", { name: "draft.png" })).not.toBeInTheDocument();
expect(screen.queryByLabelText("Quoted context")).not.toBeInTheDocument();
view.rerender(composer("chat-a"));
expect(await screen.findByText("draft.png")).toBeInTheDocument();
expect(await screen.findByRole("img", { name: "draft.png" })).toBeInTheDocument();
expect(screen.getByLabelText("Quoted context")).toHaveTextContent("quoted answer");
await waitFor(() => expect(screen.getByRole("button", { name: "Send message" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Send message" }));