fix(webui): upload TUI and WebUI attachments over binary HTTP (#5980)

* feat(webui): add bounded binary attachment staging

* feat(webui): bridge binary HTTP bodies alongside websocket listener

* fix(webui): deliver attachments over authenticated binary HTTP

* fix(webui): bound incomplete upload headers and preserve staging markers

* test: reflect aiohttp runtime dependency for binary uploads

* fix(webui): relay binary uploads and retain rejected drafts

* refactor(webui): remove obsolete attachment transport errors

* refactor(websocket): own binary attachment transport

* fix(websocket): allow bounded uploads over slow connections

* test(webui): restore upload timeout before retry

* docs(websocket): focus attachment guide on client usage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-08 11:55:13 +08:00
1 parent 5be1e589f2
commit 6646f5fbee
53 files changed
+1972 -847

No files matched your search

+24 -17
View File
@@ -1099,11 +1099,9 @@ export function ThreadComposer({
? "Empty files cannot be attached"
: reason === "total_too_large"
? "Attachments are too large together — remove some or use smaller files"
: reason === "transport_too_large"
? "This attachment would exceed the gateway transport limit"
: reason === "too_large"
? "File is too large"
: "Unsupported file type";
: reason === "too_large"
? "File is too large"
: "Unsupported file type";
return t(key, { max: maxAttachments, defaultValue: fallback });
},
[maxAttachments, t],
@@ -1965,6 +1963,16 @@ export function ThreadComposer({
});
}, []);
const observeQueuedSend = useCallback((prompt: QueuedPrompt, result: void | boolean | Promise<void | boolean>) => {
const restore = (error?: unknown) => {
skipNextQueuedFlushRef.current = true;
setQueuedPrompts((items) => items.some((item) => item.id === prompt.id) ? items : [prompt, ...items]);
setInlineError(error instanceof Error ? error.message : "Message not sent; queued draft retained");
};
if (result instanceof Promise) void result.then((accepted) => { if (accepted === false) restore(); }).catch(restore);
else if (result === false) restore();
}, []);
const sendQueuedPrompt = useCallback(
(prompt: QueuedPrompt) => {
secondEnterPromptIdRef.current = null;
@@ -1985,11 +1993,11 @@ export function ThreadComposer({
...(isStreaming ? { continueActiveTurn: true } : {}),
}
: undefined;
onSend(text, queuedImages, options);
observeQueuedSend(prompt, onSend(text, queuedImages, options));
}
requestAnimationFrame(() => textareaRef.current?.focus());
},
[isStreaming, onSend],
[isStreaming, onSend, observeQueuedSend],
);
const sendNextQueuedPrompt = useCallback(() => {
@@ -2011,12 +2019,13 @@ export function ThreadComposer({
: {}),
}
: undefined;
if (queuedImages?.length && options) onSend(nextPrompt.text.trim(), queuedImages, options);
else if (queuedImages?.length) onSend(nextPrompt.text.trim(), queuedImages);
else if (options) onSend(nextPrompt.text.trim(), undefined, options);
else onSend(nextPrompt.text.trim());
const result = queuedImages?.length && options ? onSend(nextPrompt.text.trim(), queuedImages, options)
: queuedImages?.length ? onSend(nextPrompt.text.trim(), queuedImages)
: options ? onSend(nextPrompt.text.trim(), undefined, options)
: onSend(nextPrompt.text.trim());
observeQueuedSend(nextPrompt, result);
requestAnimationFrame(() => textareaRef.current?.focus());
}, [onSend, queuedPrompts]);
}, [onSend, queuedPrompts, observeQueuedSend]);
useEffect(() => {
const previous = previousQueueRunRef.current;
@@ -2057,10 +2066,8 @@ export function ThreadComposer({
setInlineError(textTooLargeMessage());
return;
}
// Share the same ``data:`` URL with both the wire payload and the
// optimistic bubble preview: data URLs are self-contained (no blob
// lifetime, safe under React StrictMode double-mount) and keep the bubble
// in sync with whatever the backend actually sees.
// Keep self-contained local previews across drafts and optimistic bubbles.
// The client decodes these to HTTP binary; WS messages contain only refs.
const payload: SendAttachment[] | undefined =
readyImages.length > 0
? readyImages.map((img) => ({
@@ -2142,7 +2149,7 @@ export function ThreadComposer({
if (accepted !== false) finishSend();
})
.catch((error: unknown) => {
console.error("Failed to send message", error);
setInlineError(error instanceof Error ? error.message : "Failed to send message");
})
.finally(() => setSendPending(false));
return;
+9 -3
View File
@@ -538,6 +538,7 @@ function randomHeroGreetingKey(): (typeof HERO_GREETING_KEYS)[number] {
}
interface PendingFirstMessage {
finish?: (accepted: boolean) => void;
content: string;
images?: SendAttachment[];
options?: SendOptions;
@@ -1442,6 +1443,9 @@ export function ThreadShell({
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
setSubmittedViewportTurnId(submitted.turnId);
}
if (submitted?.delivery) {
void submitted.delivery.then(() => pending.finish?.(true), () => pending.finish?.(false));
} else pending.finish?.(submitted !== null);
setBooting(false);
}, [chatId, pendingFirstTargetChatId, send]);
@@ -1489,7 +1493,9 @@ export function ThreadShell({
async (content: string, images?: SendAttachment[], options?: SendOptions) => {
if (booting) return false;
setBooting(true);
pendingFirstRef.current = { content, images, options: withWorkspaceScope(options) };
let finish!: (accepted: boolean) => void;
const delivery = new Promise<boolean>((resolve) => { finish = resolve; });
pendingFirstRef.current = { content, images, options: withWorkspaceScope(options), finish };
setPendingFirstTargetChatId(null);
const newId = await onCreateChat?.(workspaceScope, content, localModelPreset);
if (!newId) {
@@ -1502,7 +1508,7 @@ export function ThreadShell({
await client.sendSystemCommand(newId, `/model ${localModelPreset}`).catch(() => {});
}
setPendingFirstTargetChatId(newId);
return true;
return delivery;
},
[booting, client, localModelPreset, onCreateChat, withWorkspaceScope, workspaceScope],
);
@@ -1519,7 +1525,7 @@ export function ThreadShell({
activeViewportTurnByChatIdRef.current.set(chatId, submitted.turnId);
setSubmittedViewportTurnId(submitted.turnId);
}
return submitted !== null;
return submitted?.delivery ? submitted.delivery.then(() => true) : submitted !== null;
},
[chatId, send, withWorkspaceScope],
);
+2 -40
View File
@@ -45,10 +45,9 @@ export type RestoredReadyImage = RestoredReadyAttachment;
* Callers localize these via the ``composer.imageRejected.*`` i18n table. */
export type AttachmentError =
| "unsupported_type" // server whitelist excludes this MIME
| "empty_file" // backend data-URL decoder rejects empty payloads
| "empty_file" // attachments must contain bytes
| "too_many_attachments" // per-message cap (4) reached before enqueue
| "total_too_large" // decoded attachments exceed the business-policy total
| "transport_too_large" // projected JSON frame exceeds the transport guard
| "magic_mismatch" // extension lies about the real content
| "decode_failed" // Worker couldn't decode / re-encode
| "too_large" // even after normalization we exceed the budget
@@ -108,35 +107,12 @@ function mimeForFile(file: File): string {
return file.type;
}
function projectedDataUrlBytes(
file: File,
kind: AttachmentKind,
maxFileBytes: number,
): number {
const prefixBytes = `data:${mimeForFile(file)};base64,`.length;
const decodedBytes = kind === "image" ? Math.min(file.size, maxFileBytes) : file.size;
return prefixBytes + 4 * Math.ceil(decodedBytes / 3);
}
function positiveLimit(value: number | null | undefined, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0
? Math.floor(value)
: fallback;
}
function attachmentPayloadBudget(limits: WebUIIngressLimits | null | undefined): number | null {
const maxFrameBytes = limits?.transport.max_frame_bytes;
if (typeof maxFrameBytes !== "number" || !Number.isFinite(maxFrameBytes)) {
return null;
}
return Math.max(
0,
Math.floor(maxFrameBytes)
- positiveLimit(limits?.message.max_text_bytes, 0)
- positiveLimit(limits?.transport.envelope_reserve_bytes, 0),
);
}
export function acceptedAttachmentKind(file: File): AttachmentKind | null {
if (DOCUMENT_MIME_BY_EXTENSION.has(extensionOf(file.name))) return "file";
if (ACCEPTED_IMAGE_MIMES.has(file.type)) return "image";
@@ -297,14 +273,6 @@ export function useAttachedImages({
const rejected: Array<{ file: File; reason: AttachmentError }> = [];
const toAdd: AttachedAttachment[] = [];
let slot = maxAttachments - imagesRef.current.length;
const payloadBudget = attachmentPayloadBudget(ingressLimits);
let projectedWireBytes = imagesRef.current.reduce(
(total, image) => total + (
image.dataUrl?.length
?? projectedDataUrlBytes(image.file, image.kind, maxFileBytes)
),
0,
);
let projectedDecodedBytes = imagesRef.current.reduce(
(total, image) => total + (
image.encodedBytes
@@ -336,14 +304,8 @@ export function useAttachedImages({
rejected.push({ file, reason: "total_too_large" });
continue;
}
const nextWireBytes = projectedDataUrlBytes(file, kind, maxFileBytes);
if (payloadBudget !== null && projectedWireBytes + nextWireBytes > payloadBudget) {
rejected.push({ file, reason: "transport_too_large" });
continue;
}
slot -= 1;
projectedDecodedBytes += nextDecodedBytes;
projectedWireBytes += nextWireBytes;
toAdd.push({
id: uuid(),
kind,
@@ -393,7 +355,7 @@ export function useAttachedImages({
}
return { rejected };
},
[ingressLimits, maxAttachments, maxFileBytes, maxTotalBytes, setEntry],
[maxAttachments, maxFileBytes, maxTotalBytes, setEntry],
);
const remove = useCallback((id: string) => {
+9 -2
View File
@@ -78,6 +78,7 @@ export interface SendOptions {
}
export interface SubmittedTurn {
delivery?: Promise<void>;
turnId: string;
userMessageId: string;
sideChannel: boolean;
@@ -993,8 +994,14 @@ export function useNanobotStream(
delete clientOptions.sideChannel;
delete clientOptions.finalizeActiveTurn;
delete clientOptions.continueActiveTurn;
client.sendMessage(chatId, outboundContent, wireMedia, clientOptions);
return { turnId, userMessageId, sideChannel };
const delivery = wireMedia?.length
? client.sendAttachments(chatId, outboundContent, wireMedia, clientOptions)
: undefined;
if (!delivery) client.sendMessage(chatId, outboundContent, undefined, clientOptions);
// Every caller may keep this promise to retain its draft until accepted.
// Also observe it here for queued/landing sends without an active composer.
void delivery?.catch(() => {});
return { turnId, userMessageId, sideChannel, delivery };
},
[chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages],
);
-1
View File
@@ -2110,7 +2110,6 @@
"decode_failed": "Couldn't decode this image",
"too_large": "File is too large — try a smaller one",
"total_too_large": "Attachments are too large together — remove some or use smaller files",
"transport_too_large": "This attachment would exceed the gateway transport limit",
"io": "Couldn't read this file"
},
"workspace": {
-1
View File
@@ -1896,7 +1896,6 @@
"decode_failed": "No se pudo decodificar esta imagen",
"too_large": "Archivo demasiado grande — prueba uno más pequeño",
"total_too_large": "Los archivos adjuntos son demasiado grandes en conjunto; elimina algunos o usa archivos más pequeños",
"transport_too_large": "Este archivo adjunto superaría el límite de transporte de la puerta de enlace",
"io": "No se pudo leer este archivo"
},
"mentions": {
-1
View File
@@ -1895,7 +1895,6 @@
"decode_failed": "Impossible de décoder cette image",
"too_large": "Fichier trop volumineux — essayez-en un plus petit",
"total_too_large": "Les pièces jointes sont trop volumineuses ensemble — supprimez-en ou utilisez des fichiers plus petits",
"transport_too_large": "Cette pièce jointe dépasserait la limite de transport de la passerelle",
"io": "Impossible de lire ce fichier"
},
"mentions": {
-1
View File
@@ -1895,7 +1895,6 @@
"decode_failed": "Tidak dapat mendekode gambar ini",
"too_large": "File terlalu besar — coba yang lebih kecil",
"total_too_large": "Total lampiran terlalu besar — hapus beberapa atau gunakan file yang lebih kecil",
"transport_too_large": "Lampiran ini akan melebihi batas transport gateway",
"io": "Tidak dapat membaca file ini"
},
"mentions": {
-1
View File
@@ -1895,7 +1895,6 @@
"decode_failed": "この画像をデコードできません",
"too_large": "ファイルが大きすぎます。小さいものを選んでください",
"total_too_large": "添付ファイルの合計サイズが大きすぎます。いくつか削除するか、より小さいファイルを使用してください",
"transport_too_large": "この添付ファイルはゲートウェイの転送上限を超えます",
"io": "このファイルを読み込めません"
},
"mentions": {
-1
View File
@@ -1895,7 +1895,6 @@
"decode_failed": "이 이미지를 디코딩할 수 없습니다",
"too_large": "파일이 너무 큽니다. 더 작은 파일을 선택해 주세요",
"total_too_large": "첨부 파일의 전체 크기가 너무 큽니다. 일부를 제거하거나 더 작은 파일을 사용해 주세요",
"transport_too_large": "이 첨부 파일은 게이트웨이 전송 한도를 초과합니다",
"io": "이 파일을 읽을 수 없습니다"
},
"mentions": {
-1
View File
@@ -1924,7 +1924,6 @@
"decode_failed": "Não foi possível decodificar esta imagem",
"too_large": "A imagem é grande demais — tente uma menor",
"total_too_large": "Os anexos são grandes demais em conjunto — remova alguns ou use arquivos menores",
"transport_too_large": "Este anexo excederia o limite de transporte do gateway",
"io": "Não foi possível ler este arquivo"
},
"workspace": {
-1
View File
@@ -1895,7 +1895,6 @@
"decode_failed": "Không thể giải mã ảnh này",
"too_large": "Tệp quá lớn — hãy thử tệp nhỏ hơn",
"total_too_large": "Tổng dung lượng tệp đính kèm quá lớn — hãy xóa bớt hoặc dùng tệp nhỏ hơn",
"transport_too_large": "Tệp đính kèm này sẽ vượt quá giới hạn truyền tải của gateway",
"io": "Không thể đọc tệp này"
},
"mentions": {
-1
View File
@@ -2109,7 +2109,6 @@
"decode_failed": "无法解码这张图片",
"too_large": "文件太大,请换一个小一点的",
"total_too_large": "附件总大小过大,请移除部分文件或使用更小的文件",
"transport_too_large": "该附件会超过网关的传输上限",
"io": "无法读取该文件"
},
"goalStateCloseAria": "关闭目标",
-1
View File
@@ -1895,7 +1895,6 @@
"decode_failed": "無法解碼這張圖片",
"too_large": "檔案太大,請改用較小的檔案",
"total_too_large": "附件總大小過大,請移除部分檔案或改用較小的檔案",
"transport_too_large": "此附件會超過閘道的傳輸上限",
"io": "無法讀取這個檔案"
},
"mentions": {
+41 -3
View File
@@ -1,3 +1,5 @@
import { uploadAttachments, uploadCapability, type AttachmentReference, type UploadCapability } from "../../../packages/client-events/attachments";
import { DeliveryReceipts } from "../../../packages/client-events/delivery";
import { decodeNotification } from "../../../packages/client-events/notifications";
import type {
ConnectionStatus,
@@ -54,6 +56,7 @@ function wsInboundDebugEnabled(): boolean {
/** Shorten streaming text fields so logging stays usable for huge deltas. */
function summarizeInboundWsPayload(ev: InboundEvent): unknown {
const kind = (ev as { event?: string }).event;
if (kind === "ready") return { ...ev, upload: "[redacted]" };
if (kind !== "delta" && kind !== "reasoning_delta") return ev;
const row = { ...(ev as object) } as Record<string, unknown>;
const text = typeof row.text === "string" ? row.text : "";
@@ -188,6 +191,8 @@ interface PendingMessageSend {
*/
export class NanobotClient {
private socket: WebSocket | null = null;
private upload: UploadCapability | null = null;
private receipts = new DeliveryReceipts();
private statusHandlers = new Set<StatusHandler>();
private runtimeModelHandlers = new Set<RuntimeModelHandler>();
private sessionUpdateHandlers = new Set<SessionUpdateHandler>();
@@ -837,6 +842,8 @@ export class NanobotClient {
}
close(): void {
this.upload = null;
this.receipts.close();
this.intentionallyClosed = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
@@ -1010,10 +1017,36 @@ export class NanobotClient {
}
}
async sendAttachments(
chatId: string, content: string, media: OutboundMedia[],
options?: Parameters<NanobotClient["sendMessage"]>[3],
): Promise<void> {
const socket = this.socket;
const capability = this.upload;
const turnId = options?.turnId ?? crypto.randomUUID();
const stillConnected = () => this.socket === socket
&& socket?.readyState === WS_OPEN && this.upload === capability;
try {
const references = await uploadAttachments(media, capability,
typeof window !== "undefined" ? window.location.href : this.currentUrl,
stillConnected);
if (!stillConnected()) throw new Error("Connection changed during attachment send");
await this.receipts.wait(turnId, () => {
if (!this.sendMessage(chatId, content, references, { ...options, turnId })) {
throw new Error("Message exceeds the gateway's WebSocket frame limit; draft retained");
}
});
} catch (error) {
this.emitError({ kind: "turn_rejected", chatId, turnId, detail: "attachment_rejected",
reason: error instanceof Error ? error.message : "Attachment send failed" });
throw error;
}
}
sendMessage(
chatId: string,
content: string,
media?: OutboundMedia[],
media?: AttachmentReference[],
options?: {
cliApps?: OutboundCliAppMention[];
mcpPresets?: OutboundMcpPresetMention[];
@@ -1025,7 +1058,7 @@ export class NanobotClient {
/** False for side-channel or injected messages that do not own a lifecycle. */
startsNewRun?: boolean;
},
): void {
): boolean {
const temporary = this.temporaryChatIds.has(chatId);
if (!temporary) this.knownChats.add(chatId);
const frame: Outbound = {
@@ -1053,7 +1086,7 @@ export class NanobotClient {
chatId,
...(options?.turnId ? { turnId: options.turnId } : {}),
});
return;
return false;
}
if (options?.turnId && !isSystemCommandTurnId(options.turnId)) {
const startsNewRun = options.startsNewRun !== false;
@@ -1061,6 +1094,7 @@ export class NanobotClient {
this.trackPendingMessageSend(chatId, options.turnId, startsNewRun);
}
this.queueSend(frame);
return true;
}
sendSystemCommand(chatId: string, command: string, timeoutMs = 5_000): Promise<void> {
@@ -1176,6 +1210,7 @@ export class NanobotClient {
if (fallbackTurnId) parsed = { ...parsed, turn_id: fallbackTurnId };
}
this.receipts.event(parsed);
const turnId = "turn_id" in parsed && typeof parsed.turn_id === "string"
? parsed.turn_id
: null;
@@ -1228,6 +1263,7 @@ export class NanobotClient {
}
if (parsed.event === "ready") {
this.upload = uploadCapability(parsed.upload);
this.readyChatId = parsed.chat_id;
this.knownChats.add(parsed.chat_id);
return;
@@ -1361,6 +1397,8 @@ export class NanobotClient {
}
private handleClose(event?: { code?: number }): void {
this.upload = null;
this.receipts.close();
this.socket = null;
this.clearTemporaryChats();
const willReconnect = !this.intentionallyClosed && this.shouldReconnect;
+3 -3
View File
@@ -1401,7 +1401,7 @@ interface InboundTurnMetadata {
export type InboundEvent =
| { event: "subagent_task"; chat_id: string; task: SubagentTaskSnapshot }
| { event: "ready"; chat_id: string; client_id: string }
| { event: "ready"; chat_id: string; client_id: string; upload?: unknown }
| {
event: "attached";
chat_id: string;
@@ -1592,7 +1592,7 @@ export type ThreadProjectionEvent = Extract<
created_at_ms?: number;
};
/** Base64-encoded file attached to an outbound ``message`` envelope.
/** Local draft/preview data, converted to HTTP binary before sending a message.
*
* ``data_url`` must use a server-whitelisted image, video, or document MIME
* type. SVG remains rejected on ingress to avoid an embedded-script XSS
@@ -1692,7 +1692,7 @@ export type Outbound =
type: "message";
chat_id: string;
content: string;
media?: OutboundMedia[];
media?: import("../../../packages/client-events/attachments").AttachmentReference[];
cli_apps?: OutboundCliAppMention[];
mcp_presets?: OutboundMcpPresetMention[];
session_mentions?: SessionMention[];
+103
View File
@@ -2378,3 +2378,106 @@ describe("NanobotClient", () => {
expect(FakeSocket.instances.length).toBeGreaterThan(1);
});
});
describe("binary attachment transport", () => {
it("keeps a progressing HTTP upload alive beyond the old 65-second limit", async () => {
const timeout = vi.spyOn(AbortSignal, "timeout").mockImplementation((milliseconds) => {
const controller = new AbortController();
setTimeout(() => controller.abort(), milliseconds);
return controller.signal;
});
vi.stubGlobal("fetch", vi.fn().mockImplementation((_url, request: RequestInit) => new Promise((resolve, reject) => {
request.signal?.addEventListener("abort", () => reject(new Error("Upload timed out")));
setTimeout(() => resolve(Response.json({ reference: "slow-ref" }, { status: 201 })), 80_000);
})));
const client = new NanobotClient({ url: "ws://test", reconnect: false,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
try {
client.connect();
const socket = lastSocket(); socket.fakeOpen();
socket.fakeMessage({ event: "ready", chat_id: "chat", client_id: "test",
upload: { path: "/api/attachments", token: "cap" } });
const delivery = client.sendAttachments("chat", "look", [
{ data_url: "data:text/plain;base64,eA==", name: "note.txt" },
], { turnId: "slow-upload" });
await vi.advanceTimersByTimeAsync(80_000);
expect(socket.sent.some((frame) => frame.includes("slow-ref"))).toBe(true);
socket.fakeMessage({ event: "message_accepted", chat_id: "chat", turn_id: "slow-upload" });
await delivery;
} finally {
client.close(); vi.unstubAllGlobals(); timeout.mockRestore();
}
});
it("rejects an oversized message envelope without waiting for an ACK and retains the draft", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ reference: "ref" }, { status: 201 })));
const client = new NanobotClient({ url: "ws://test", reconnect: false, maxFrameBytes: 256,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
try {
client.connect();
const socket = lastSocket(); socket.fakeOpen();
socket.fakeMessage({ event: "ready", chat_id: "chat", client_id: "test",
upload: { path: "/api/attachments", token: "cap" } });
const draft = [{ data_url: "data:text/plain;base64,eA==", name: "note.txt" }];
await expect(client.sendAttachments("chat", "x".repeat(400), draft)).rejects.toThrow("frame limit");
expect(socket.sent.filter((value) => JSON.parse(value).type === "message")).toHaveLength(0);
expect(draft[0].data_url).toBe("data:text/plain;base64,eA==");
} finally { client.close(); vi.unstubAllGlobals(); }
});
it("uploads >1 MiB as HTTP bytes and waits for a small WS reference ACK", async () => {
const fetchMock = vi.fn().mockResolvedValue(Response.json({ reference: "opaque-ref" }, { status: 201 }));
vi.stubGlobal("fetch", fetchMock);
const client = new NanobotClient({ url: "ws://test", reconnect: false, maxFrameBytes: 1024 * 1024,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
try {
client.connect();
const socket = lastSocket();
socket.fakeOpen();
socket.fakeMessage({ event: "ready", chat_id: "chat", client_id: "test",
upload: { path: "/api/attachments", token: "upload-capability" } });
const raw = "x".repeat(1_089_490);
let accepted = false;
const delivery = client.sendAttachments("chat", "look", [
{ data_url: `data:image/png;base64,${btoa(raw)}`, name: "paste.png" },
], { turnId: "large-image" }).then(() => { accepted = true; });
await vi.waitFor(() => expect(socket.sent.some((frame) => frame.includes("opaque-ref"))).toBe(true));
expect(accepted).toBe(false);
const [, request] = fetchMock.mock.calls[0];
expect(request.method).toBe("POST");
expect(request.headers.Authorization).toBe("Bearer upload-capability");
expect(request.redirect).toBe("error");
expect(await request.body.text()).toBe(raw);
const frame = socket.sent.find((value) => value.includes("opaque-ref"))!;
expect(frame.length).toBeLessThan(1024);
expect(frame).not.toContain("data_url");
socket.fakeMessage({ event: "message_accepted", chat_id: "chat", turn_id: "large-image" });
await delivery;
expect(accepted).toBe(true);
} finally { client.close(); vi.unstubAllGlobals(); }
});
it("does not send a message after HTTP rejection or a connection change", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response("denied", { status: 401 }));
vi.stubGlobal("fetch", fetchMock);
const client = new NanobotClient({ url: "ws://test", reconnect: false,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket });
try {
client.connect();
const socket = lastSocket(); socket.fakeOpen();
socket.fakeMessage({ event: "ready", chat_id: "chat", client_id: "test",
upload: { path: "/api/attachments", token: "cap" } });
const draft = [{ data_url: "data:text/plain;base64,eA==", name: "note.txt" }];
await expect(client.sendAttachments("chat", "look", draft)).rejects.toThrow("401");
expect(socket.sent.filter((frame) => JSON.parse(frame).type === "message")).toHaveLength(0);
expect(draft[0].data_url).toBe("data:text/plain;base64,eA==");
fetchMock.mockImplementation(async () => {
socket.fakeCloseWithCode(1009);
return Response.json({ reference: "old-connection-ref" });
});
await expect(client.sendAttachments("chat", "look", draft)).rejects.toThrow("Connection changed");
expect(socket.sent.filter((frame) => JSON.parse(frame).type === "message")).toHaveLength(0);
} finally { client.close(); vi.unstubAllGlobals(); }
});
});
@@ -219,7 +219,7 @@ describe("ThreadComposer — attachments", () => {
expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
});
it("reports a transport limit separately from attachment policy", async () => {
it("does not count binary attachments against the WebSocket frame limit", async () => {
const first = pdfFile("first.pdf", 400 * 1024);
const second = pdfFile("second.pdf", 400 * 1024);
@@ -239,12 +239,10 @@ describe("ThreadComposer — attachments", () => {
fireEvent.change(input, { target: { files: [first, second] } });
});
expect(screen.getByRole("alert")).toHaveTextContent(
"gateway transport limit",
);
expect(screen.getAllByTestId("composer-chip")).toHaveLength(1);
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.getAllByTestId("composer-chip")).toHaveLength(2);
expect(screen.getByText("first.pdf")).toBeInTheDocument();
expect(screen.queryByText("second.pdf")).not.toBeInTheDocument();
expect(screen.getByText("second.pdf")).toBeInTheDocument();
});
it("enforces the decoded attachment-total policy independently", async () => {
+2 -1
View File
@@ -146,6 +146,7 @@ function fakeClient() {
return () => set!.delete(h);
},
sendMessage: vi.fn(),
sendAttachments: vi.fn().mockResolvedValue(undefined),
requestMutation,
finishRunLocally: vi.fn(),
newChat: vi.fn(),
@@ -2721,7 +2722,7 @@ describe("useNanobotStream", () => {
expect(result.current.messages[0].media).toEqual([attachment.preview]);
expect(result.current.messages[0].images).toBeUndefined();
expect(fake.client.sendMessage).toHaveBeenCalledWith(
expect(fake.client.sendAttachments).toHaveBeenCalledWith(
"chat-file-send",
"summarize",
[attachment.media],