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

+27 -6
View File
@@ -8,7 +8,7 @@ const draft: ComposerDraft = {
text: " Keep this draft\n继续编辑",
quotedContext: "Quoted answer",
sessionMentions: [{ name: "other", title: "Other topic", session_key: "websocket:other" }],
files: [new File(["attachment"], "draft.txt", { type: "text/plain" })],
attachments: [new File(["attachment"], "draft.txt", { type: "text/plain" })],
};
afterEach(() => {
@@ -21,15 +21,15 @@ describe("composer draft storage", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
expect(store.get(key)).toBe(draft);
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, files: [] });
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, attachments: [] });
expect(new ComposerDraftStore().get("websocket:other", true)).toBeUndefined();
expect(localStorage.getItem(storageKey)).not.toContain("files");
expect(JSON.parse(localStorage.getItem(storageKey)!).attachments).toEqual([]);
});
it("keeps the identity of an unchanged restored draft but advances it for edits", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
store.set(key, { ...draft, files: [...draft.files], sessionMentions: [...draft.sessionMentions] }, true);
store.set(key, { ...draft, attachments: [...draft.attachments], sessionMentions: [...draft.sessionMentions] }, true);
expect(store.get(key)).toBe(draft);
const edited = { ...draft, text: "edited draft" };
store.set(key, edited, true);
@@ -39,6 +39,27 @@ describe("composer draft storage", () => {
expect(store.get(key)).toBe(reverted);
});
it("keeps mixed attachment order in memory and the local subsequence after reload", () => {
const first = { path: "/project/first.png", name: "first.png", size: 8, mime: "image/png", kind: "image" as const, url: "" };
const last = { ...first, path: "/project/last.png", name: "last.png" };
const mixed = { ...draft, attachments: [first, draft.attachments[0], last] };
const store = new ComposerDraftStore();
store.set(key, mixed, true);
store.set(key, { ...mixed, attachments: [...mixed.attachments] }, true);
expect(store.get(key)).toBe(mixed);
expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([first, last]);
const reordered = { ...mixed, attachments: [last, draft.attachments[0], first] };
store.set(key, reordered, true);
expect(store.get(key)).toBe(reordered);
expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([last, first]);
});
it("reads local references already saved in v1 drafts", () => {
const local = { path: "/project/previous.png", name: "previous.png", size: 8, mime: "image/png", kind: "image", url: "" };
localStorage.setItem(storageKey, JSON.stringify({ text: "previous draft", quotedContext: null, sessionMentions: [], localAttachments: [local] }));
expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([local]);
});
it("requires explicit opt-in for both saving and restoring", () => {
const store = new ComposerDraftStore();
store.set(key, draft);
@@ -52,7 +73,7 @@ describe("composer draft storage", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
store.set(key, { ...draft, text: "", quotedContext: null, sessionMentions: [] }, true);
expect(store.get(key)?.files).toEqual(draft.files);
expect(store.get(key)?.attachments).toEqual(draft.attachments);
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
});
@@ -82,7 +103,7 @@ describe("composer draft storage", () => {
localStorage.setItem(storageKey, JSON.stringify({
...draft, sessionMentions: [null, { name: 42 }, ...draft.sessionMentions],
}));
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, files: [] });
expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, attachments: [] });
});
it("keeps editing usable when storage is unavailable and removes stale saved text", () => {
+40
View File
@@ -1049,6 +1049,23 @@ describe("MessageBubble", () => {
expect(content.querySelectorAll("li")).toHaveLength(1000);
});
it("retries a failed video locally without replacing a healthy player on history updates", () => {
const message: UIMessage = { id: "retry-video", role: "user", content: "watch", createdAt: 0,
media: [{ kind: "video", name: "clip.webm", url: "/api/media/sig/clip" }] };
const { container, rerender } = render(<MessageBubble message={message} />);
const original = container.querySelector("video")!;
fireEvent.error(original);
expect(container.querySelector("video")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
const retried = container.querySelector("video")!;
expect(retried).toHaveAttribute("src", "/api/media/sig/clip");
expect(retried).not.toBe(original);
rerender(<MessageBubble message={{ ...message, media: [...message.media!] }} />);
expect(container.querySelector("video")).toBe(retried);
fireEvent.error(retried);
expect(screen.getByRole("button", { name: "Retry" })).toBeVisible();
});
it("renders video media as an inline player", () => {
const message: UIMessage = {
id: "a1",
@@ -1076,6 +1093,29 @@ describe("MessageBubble", () => {
expect(screen.queryByText("Code")).not.toBeInTheDocument();
});
it("starts an uploaded player from its accepted URL and preserves it through hydration", () => {
const message: UIMessage = {
id: "optimistic-user", role: "user", content: "Watch this", createdAt: 1,
turnId: "video-turn", turnPhase: "user", deliveryStatus: "sending",
media: [{ kind: "video", name: "clip.webm" }],
};
const accepted: UIMessage = {
...message, deliveryStatus: "accepted",
media: [{ kind: "video", name: "clip.webm", url: "/api/media/sig/clip" }],
};
const { rerender, unmount } = render(<ThreadMessages messages={[message]} />);
expect(screen.queryByLabelText(/video attachment/i)?.tagName).not.toBe("VIDEO");
expect(screen.queryByText(/attachment unavailable/i)).not.toBeInTheDocument();
rerender(<ThreadMessages messages={[accepted]} />);
const video = screen.getByLabelText(/video attachment/i);
rerender(<ThreadMessages messages={[{ ...accepted, id: "history-user" }]} />);
expect(screen.getByLabelText(/video attachment/i)).toBe(video);
expect(video).toHaveAttribute("src", "/api/media/sig/clip");
unmount();
render(<ThreadMessages messages={[accepted]} />);
expect(screen.getByLabelText(/video attachment/i)).toHaveAttribute("src", "/api/media/sig/clip");
});
it("renders streaming reasoning as one compact activity line", () => {
const message: UIMessage = {
id: "a-reasoning-streaming",
+15 -1
View File
@@ -67,6 +67,20 @@ describe("merged waiting messages", () => {
});
});
it.each(["video", "file"] as const)("sends a restored large local %s and a browser upload without spending local bytes", (kind) => {
const local = { path: `C:\\project\\large.${kind === "video" ? "mp4" : "pdf"}`, name: "large reference", kind, size: 64 * 1024 * 1024 + 1, mime: kind === "video" ? "video/mp4" : "application/pdf", url: "/api/media/sig/local" };
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
{ id: "first", text: "read references", images: [{ local, kind }, DOCUMENT] },
]));
const onSend = vi.fn();
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" ingressLimits={limits({ max_file_bytes: 5, max_total_bytes: 5 })} />);
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
expect(onSend).toHaveBeenCalledWith("read references", [
expect.objectContaining({ media: { path: local.path, name: local.name } }),
expect.objectContaining({ media: { data_url: DOCUMENT.dataUrl, name: DOCUMENT.name } }),
]);
});
it("preserves merged text longer than the former per-entry storage truncation across remounts", () => {
const onSend = vi.fn();
const first = render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming />);
@@ -155,7 +169,7 @@ describe("merged waiting messages", () => {
render(<ThreadComposer {...props} />);
await waitFor(() => expect(screen.queryByLabelText("Encoding…")).not.toBeInTheDocument());
expect(screen.getAllByTestId("composer-chip")).toHaveLength(2);
expect(draftStore.get("chat-a")?.files.map((file) => file.name)).toEqual(["first.png", "second.txt"]);
expect(draftStore.get("chat-a")?.attachments.map((file) => file.name)).toEqual(["first.png", "second.txt"]);
});
it("retains a merged rejected send after leaving the topic during upload", async () => {
+2 -2
View File
@@ -288,7 +288,7 @@ describe("SettingsView Apps catalog", () => {
"Fix connection",
);
await act(() => i18n.changeLanguage("zh-CN"));
await act(async () => { await i18n.changeLanguage("zh-CN"); });
expect(within(row as HTMLElement).getByText("连接失败。")).toBeInTheDocument();
const manage = within(row as HTMLElement).getByRole("button", { name: "管理 Xmind" });
expect(manage).toHaveTextContent("修复连接");
@@ -306,7 +306,7 @@ describe("SettingsView Apps catalog", () => {
{ name: "xmind", reset: true, use_proxy: "false" },
30_000,
));
await act(() => i18n.changeLanguage("en"));
await act(async () => { await i18n.changeLanguage("en"); });
});
it("keeps an OAuth runtime failure visible after credentials are cleared", async () => {
@@ -42,7 +42,7 @@ describe("automation channel identity", () => {
["ja", "メール"],
["es", "Correo electrónico"],
]) {
await act(() => i18n.changeLanguage(locale));
await act(async () => { await i18n.changeLanguage(locale); });
expect(detail.getByText(name)).toBeVisible();
expect(detail.queryByText("Email")).not.toBeInTheDocument();
}
@@ -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" });
});
});
+30 -3
View File
@@ -665,6 +665,33 @@ describe("ThreadShell", () => {
expect(client.sendMessage).not.toHaveBeenCalled();
});
it("restores the landing attachment draft in its created topic after a gateway rejection", async () => {
const client = { ...makeClient(), sendAttachments: vi.fn().mockRejectedValue(new Error("file not found")) };
const store = new ComposerDraftStore();
store.set("new:chat", {
text: "keep the first draft", sessionMentions: [], quotedContext: null,
attachments: [{ path: "/project/video.mp4", name: "video.mp4", size: 8, mime: "video/mp4", kind: "video", url: "" }],
});
const onCreateChat = vi.fn().mockResolvedValue("created");
const shell = (id: string | null) => wrap(client, <ThreadShell session={id ? session(id) : null}
title="First attachment" draftStore={store} onToggleSidebar={() => {}} onCreateChat={onCreateChat} />);
const view = render(shell(null));
await screen.findByTestId("composer-chip");
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
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(screen.getByRole("alert")).toHaveTextContent("file not found");
expect(store.get("websocket:created")?.attachments).toHaveLength(1);
expect(store.has("new:chat")).toBe(false);
client.sendAttachments.mockResolvedValue(undefined);
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
await waitFor(() => expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument());
expect(screen.getByRole("textbox")).toHaveValue("");
expect(client.sendAttachments).toHaveBeenCalledTimes(2);
});
it("clears the welcome draft after a delayed new-chat send and an unchanged round-trip", async () => {
const client = makeClient();
const store = new ComposerDraftStore();
@@ -694,7 +721,7 @@ describe("ThreadShell", () => {
const client = makeClient();
let draftStore = new ComposerDraftStore();
draftStore.set("websocket:reload-draft", {
text: "original", files: [], sessionMentions: [], quotedContext: "quoted answer",
text: "original", attachments: [], sessionMentions: [], quotedContext: "quoted answer",
});
const shell = () => wrap(client, (
<ThreadShell session={session("reload-draft")} title="Reload test" temporary={temporary}
@@ -740,8 +767,8 @@ describe("ThreadShell", () => {
it.each([false, true])("keeps text and quote drafts scoped to the session (temporary=%s)", async (temporary) => {
const client = makeClient();
const draftStore: ComposerDraftStore = new Map([
["websocket:draft-a", { text: "draft A", files: [], sessionMentions: [], quotedContext: "quote A" }],
["websocket:draft-b", { text: "draft B", files: [], sessionMentions: [], quotedContext: "quote B" }],
["websocket:draft-a", { text: "draft A", attachments: [], sessionMentions: [], quotedContext: "quote A" }],
["websocket:draft-b", { text: "draft B", attachments: [], sessionMentions: [], quotedContext: "quote B" }],
]);
const shell = (chatId: string) => wrap(client, (
<ThreadShell session={session(chatId)} title="Draft test" temporary={temporary}
+43
View File
@@ -2899,6 +2899,49 @@ describe("useNanobotStream", () => {
);
});
it("uses the accepted upload URL instead of retaining an encoded video in message state", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("uploaded-video", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => {
result.current.send("watch", [{
media: { data_url: "data:video/webm;base64,AAAA", name: "clip.webm" },
preview: { kind: "video", url: "data:video/webm;base64,AAAA", name: "clip.webm" },
}]);
});
const optimistic = result.current.messages[0];
expect(optimistic.media).toEqual([{ kind: "video", name: "clip.webm" }]);
const media = [{ kind: "video" as const, url: "/api/media/sig/upload", name: "clip.webm" }];
act(() => fake.emit("uploaded-video", {
event: "message_accepted", chat_id: "uploaded-video",
turn_id: optimistic.turnId!, starts_turn: true, media_urls: media,
}));
expect(result.current.messages).toHaveLength(1);
expect(result.current.messages[0]).toMatchObject({ id: optimistic.id, media, deliveryStatus: "accepted" });
});
it("replaces a local reference's optimistic preview with the gateway's session URL", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("local-video", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => {
result.current.send("watch", [{
media: { path: "/project/video.mp4", name: "video.mp4" },
preview: { kind: "video", url: "", name: "video.mp4" },
}]);
});
const optimistic = result.current.messages[0];
const media = [{ kind: "video" as const, url: "/api/media/sig/local-video", name: "video.mp4" }];
act(() => fake.emit("local-video", {
event: "user_message", chat_id: "local-video", text: "watch",
turn_id: optimistic.turnId!, starts_turn: true, media_urls: media,
}));
expect(result.current.messages).toHaveLength(1);
expect(result.current.messages[0]).toMatchObject({ id: optimistic.id, media, deliveryStatus: "accepted" });
});
it("inlines quoted context into the optimistic and outbound user message", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-quote", EMPTY_MESSAGES), {
+2 -2
View File
@@ -345,7 +345,7 @@ describe("durable run recovery", () => {
it.each(["failed read", "missing activity state"])("leaves %s unresolved", async (failure) => {
const body = completedThread();
delete body.has_pending_tool_calls;
Reflect.deleteProperty(body, "has_pending_tool_calls");
body.events = body.events.slice(0, 2);
const fetchMock = failure === "failed read"
? vi.fn().mockRejectedValue(new Error("offline"))
@@ -390,7 +390,7 @@ describe("durable run recovery", () => {
it("accepts an explicit completed turn when an older host omits activity metadata", async () => {
const body = completedThread();
delete body.has_pending_tool_calls;
Reflect.deleteProperty(body, "has_pending_tool_calls");
body.completed_turn_ids = ["turn-old"];
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body)));
const { client, running, reopen, close } = setup();