feat(attachments): support local files and video attachments (#6321)

* feat(attachments): support local files and video attachments

Share gateway inspection and send validation for borrowed local paths while preserving binary uploads, original-file ownership, and existing limits.

Related to NAN-284. Native provider video input remains outside this change.

* test: make cross-platform verification fixtures self-contained

* test(webui): align typed fixtures with runtime contracts

* fix(webui): preserve uploaded video playback during history sync

* test(tui): preserve local attachment drafts across resizes

* perf(attachments): preserve upload caches and release video previews

* docs(webui): keep attachment guidance user-focused

* chore: remove redundant dependency comment

* test(providers): make stream idle renewal timing deterministic

* fix(attachments): keep upload byte limits out of local references

Validate common format/count rules separately from upload byte budgets. Keep local inspection and send-time checks metadata-only, and exclude local references from composer and pending-upload totals. Explain upload size rejections with actual size and maximum in all ten locales. Related to NAN-284.

* fix(attachments): retain image references and draft order

* fix(attachments): close local reference UX and authorization gaps

* fix(attachments): preserve focus during asynchronous path confirmation
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-22 18:32:18 +08:00
1 parent 7dfeff9ddf
commit 254f94b068
65 files changed
+1816 -292

No files matched your search

@@ -8,6 +8,7 @@ import {
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { ComposerDraftStore } from "@/lib/composer-draft";
import type { EncodeResponse } from "@/lib/imageEncode";
import type { WebUIIngressLimits } from "@/lib/types";
@@ -425,3 +426,180 @@ describe("ThreadComposer — attachments", () => {
expect(onSend).not.toHaveBeenCalled();
});
});
describe("local attachment paths and video ingress", () => {
const local = { path: "C:\\project\\my clip.mp4", name: "my clip.mp4", size: 12,
mime: "video/mp4", kind: "video" as const, url: "/api/media/sig/local" };
it("confirms a large pasted video path and sends only the borrowed reference", async () => {
const inspect = vi.fn().mockResolvedValue({ ...local, size: 64 * 1024 * 1024 + 1 });
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} onInspectAttachment={inspect} />);
const input = screen.getByLabelText(/message input/i);
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"));
expect(input).toHaveValue("keep this ");
expect(inspect).toHaveBeenCalledWith(local.path);
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend.mock.calls[0][1][0].media).toEqual({ path: local.path, name: local.name });
});
it.each(["append", "prepend"])("keeps %s text written while the pasted path is being checked", async (edit) => {
let complete!: (attachment: typeof local) => void;
const inspect = vi.fn(() => new Promise<typeof local>((resolve) => { complete = resolve; }));
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} onInspectAttachment={inspect} />);
const input = screen.getByLabelText(/message input/i) as HTMLTextAreaElement;
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
const typed = edit === "append" ? `${local.path} describe it` : `请看 ${local.path}`;
fireEvent.change(input, { target: { value: typed, selectionStart: typed.length } });
await act(async () => complete(local));
await screen.findByTestId("composer-chip");
expect(input).toHaveValue(edit === "append" ? " describe it" : "请看 ");
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend.mock.calls[0][0]).toBe(edit === "append" ? "describe it" : "请看");
expect(onSend.mock.calls[0][1][0].media).toEqual({ path: local.path, name: local.name });
});
it.each(["edit", "remove"])("does not attach a path after the user chooses to %s it during inspection", async (edit) => {
let complete!: (attachment: typeof local) => void;
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
const typed = edit === "edit" ? local.path.replace("clip", "other") : "keep my new text";
fireEvent.change(input, { target: { value: typed } });
await act(async () => complete(local));
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
expect(input).toHaveValue(typed);
expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled();
});
it("does not steal toolbar focus when a pending path is confirmed", async () => {
let complete!: (attachment: typeof local) => void;
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
const input = screen.getByLabelText(/message input/i);
await waitFor(() => expect(input).toHaveFocus());
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
const attach = screen.getByRole("button", { name: /attach/i });
attach.focus();
expect(attach).toHaveFocus();
await act(async () => complete(local));
await screen.findByTestId("composer-chip");
expect(attach).toHaveFocus();
});
it("lets an IME composition finish before converting its pasted path", async () => {
let complete!: (attachment: typeof local) => void;
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
fireEvent.compositionStart(input);
fireEvent.change(input, { target: { value: `${local.path}你` } });
await act(async () => complete(local));
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
fireEvent.compositionEnd(input);
await screen.findByTestId("composer-chip");
expect(input).toHaveValue("你");
});
it("ignores an inspection reply after the workspace scope changes", async () => {
let complete!: (attachment: typeof local) => void;
const inspect = () => new Promise<typeof local>((resolve) => { complete = resolve; });
const view = render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} workspaceScope={{ project_path: "C:\\project", access_mode: "full" }} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
view.rerender(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} workspaceScope={{ project_path: "C:\\project", access_mode: "restricted" }} />);
await act(async () => complete(local));
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
expect(input).toHaveValue(local.path);
expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled();
});
it("keeps mixed local and uploaded attachment order across draft remounts", async () => {
encodeImage.mockImplementation(async (file) => resolveReady(file));
const firstLocal = { ...local, path: "C:\\project\\first.png", name: "first.png", kind: "image" as const, mime: "image/png" };
const lastLocal = { ...firstLocal, path: "C:\\project\\last.png", name: "last.png" };
const inspect = vi.fn().mockResolvedValueOnce(firstLocal).mockResolvedValueOnce(lastLocal);
const store = new ComposerDraftStore();
const onSend = vi.fn();
const composer = () => <ThreadComposer draftKey="mixed-order" draftStore={store} onSend={onSend} onInspectAttachment={inspect} />;
const view = render(composer());
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => firstLocal.path } });
await screen.findByText(firstLocal.name);
fireEvent.change(input.closest("form")!.querySelector('input[type="file"]')!, { target: { files: [pngFile("middle.png")] } });
await screen.findByText("middle.png");
fireEvent.paste(input, { clipboardData: { items: [], getData: () => lastLocal.path } });
await screen.findByText(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"),
]);
view.unmount();
render(composer());
await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
fireEvent.keyDown(screen.getByLabelText(/message input/i), { key: "Enter" });
expect(onSend.mock.calls[0][1].map((item: { media: { name: string } }) => item.media.name)).toEqual([
"first.png", "middle.png", "last.png",
]);
});
it("keeps failed path text and attachment draft, and does not consume prose or URLs", async () => {
const inspect = vi.fn().mockRejectedValue(new Error("file not found"));
render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => "./missing.mp4" } });
await waitFor(() => expect(screen.getByText("file not found")).toBeInTheDocument());
expect(input).toHaveValue("./missing.mp4");
for (const text of ["look at ./missing.mp4 please", "https://host/clip.mp4", "const path = './clip.mp4'", "line one\n./clip.mp4"]) {
fireEvent.paste(input, { clipboardData: { items: [], getData: () => text } });
}
expect(inspect).toHaveBeenCalledTimes(1);
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
});
it("does not charge large local documents against a picked document's upload budget", async () => {
const onSend = vi.fn();
const document = { ...local, path: "C:\\project\\large.pdf", name: "large.pdf", mime: "application/pdf", kind: "file" as const, size: 64 * 1024 * 1024 + 1 };
render(<ThreadComposer onSend={onSend} onInspectAttachment={vi.fn().mockResolvedValue(document)} ingressLimits={ingressLimits({ maxFileBytes: 8, maxTotalBytes: 8 })} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.paste(input, { clipboardData: { items: [], getData: () => document.path } });
await screen.findByText(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());
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend).toHaveBeenCalledWith("", [
expect.objectContaining({ media: { path: document.path, name: document.name } }),
expect.objectContaining({ media: expect.objectContaining({ name: "upload.pdf", data_url: expect.any(String) }) }),
], undefined);
});
it("explains the size and limit of a rejected browser video without losing the draft", () => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} />);
const input = screen.getByLabelText(/message input/i);
fireEvent.change(input, { target: { value: "keep this text" } });
const file = new File([new Uint8Array(21 * 1024 * 1024)], "large.mp4", { type: "video/mp4" });
fireEvent.change(input.closest("form")!.querySelector('input[type="file"]')!, { target: { files: [file] } });
expect(screen.getByRole("alert")).toHaveTextContent("21.0 MiB");
expect(screen.getByRole("alert")).toHaveTextContent("20.0 MiB");
expect(input).toHaveValue("keep this text");
expect(onSend).not.toHaveBeenCalled();
});
it("uploads picked video bytes with the existing independent video size/count allowance", async () => {
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} ingressLimits={ingressLimits({ maxFileBytes: 3 })} />);
const input = screen.getByLabelText(/message input/i);
const picker = input.closest("form")!.querySelector('input[type="file"]')!;
fireEvent.change(picker, { target: { files: [new File(["movie"], "clip.mov", { type: "" })] } });
await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
fireEvent.keyDown(input, { key: "Enter" });
expect(onSend.mock.calls[0][1][0].media).toEqual({ data_url: `data:video/quicktime;base64,${btoa("movie")}`, name: "clip.mov" });
});
});