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:
1 parent
5be1e589f2
commit
6646f5fbee
53 files changed
+1972
-847
No files matched your search
@@ -539,7 +539,6 @@ describe("gateway protocol", () => {
|
||||
}),
|
||||
})
|
||||
client.send("hello", {
|
||||
media: [{ data_url: "data:image/png;base64,AAAA", name: "clipboard-image-1.png" }],
|
||||
cliApps: [{ name: "github" }],
|
||||
sessionMentions: [{ name: "plan", session_key: "websocket:plan" }],
|
||||
userShell: true,
|
||||
@@ -558,9 +557,7 @@ describe("gateway protocol", () => {
|
||||
expect(outbound[1]?.chat_id).toBe("terminal")
|
||||
expect(outbound[1]?.content).toBe("hello")
|
||||
expect(outbound[1]?.user_shell).toBe(true)
|
||||
expect(outbound[1]?.media).toEqual([
|
||||
{ data_url: "data:image/png;base64,AAAA", name: "clipboard-image-1.png" },
|
||||
])
|
||||
expect(outbound[1]?.media).toBeUndefined()
|
||||
expect(outbound[1]?.cli_apps).toEqual([{ name: "github" }])
|
||||
expect(outbound[1]?.session_mentions).toEqual([
|
||||
{ name: "plan", session_key: "websocket:plan" },
|
||||
@@ -1382,3 +1379,45 @@ describe("gateway protocol", () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
test("uploads clipboard bytes over HTTP, sends only a reference, and awaits acceptance", async () => {
|
||||
const originalSocket = globalThis.WebSocket
|
||||
const originalFetch = globalThis.fetch
|
||||
let socket: FakeSocket | undefined
|
||||
const raw = "x".repeat(1_089_490)
|
||||
Object.defineProperty(globalThis, "WebSocket", { configurable: true,
|
||||
value: class extends FakeSocket { constructor() { super(); socket = this } } })
|
||||
globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
expect(String(url)).toBe("http://127.0.0.1:1234/api/attachments")
|
||||
expect(init?.method).toBe("POST")
|
||||
expect((init?.headers as Record<string, string>).Authorization).toBe("Bearer capability")
|
||||
expect(await (init?.body as Blob).text()).toBe(raw)
|
||||
return Response.json({ reference: "binary-ref" }, { status: 201 })
|
||||
}) as typeof fetch
|
||||
const client = new NanobotClient({ url: "ws://127.0.0.1:1234/ws?token=one-shot", chatId: "chat",
|
||||
reconnect: false, onStatus() {}, onEvent() {} })
|
||||
try {
|
||||
client.connect()
|
||||
if (!socket) throw new Error("no socket")
|
||||
socket.emit("message", { data: JSON.stringify({ event: "ready", chat_id: "chat", client_id: "test",
|
||||
upload: { path: "/api/attachments", token: "capability" } }) })
|
||||
let accepted = false
|
||||
const delivery = client.sendAttachments("look", { media: [
|
||||
{ data_url: `data:image/png;base64,${btoa(raw)}`, name: "clipboard.png" },
|
||||
] }).then(() => { accepted = true })
|
||||
await waitUntil(() => socket!.sent.some((frame) => frame.includes("binary-ref")))
|
||||
expect(accepted).toBe(false)
|
||||
const frame = socket.sent.find((value) => value.includes("binary-ref"))!
|
||||
expect(frame.length).toBeLessThan(1024)
|
||||
expect(frame).not.toContain("data_url")
|
||||
const payload = JSON.parse(frame)
|
||||
socket.emit("message", { data: JSON.stringify({ event: "message_accepted", chat_id: "chat", turn_id: payload.turn_id }) })
|
||||
await delivery
|
||||
expect(accepted).toBe(true)
|
||||
} finally {
|
||||
client.close()
|
||||
globalThis.fetch = originalFetch
|
||||
Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: originalSocket })
|
||||
}
|
||||
})
|
||||
@@ -1,3 +1,5 @@
|
||||
import { uploadAttachments, uploadCapability, type AttachmentReference, type UploadCapability } from "../../../packages/client-events/attachments"
|
||||
import { DeliveryReceipts } from "../../../packages/client-events/delivery"
|
||||
import { isRecoveryState } from "../../../packages/client-events/notifications"
|
||||
|
||||
import {
|
||||
@@ -17,6 +19,9 @@ import type {
|
||||
import { decodeInboundEvent, decodeWebUIResponse, isRecord } from "./validation"
|
||||
|
||||
export class NanobotClient {
|
||||
private upload: UploadCapability | null = null
|
||||
private uploadBase = ""
|
||||
private receipts = new DeliveryReceipts()
|
||||
private identityVerified = false
|
||||
private handshakeTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private socket: WebSocket | null = null
|
||||
@@ -94,6 +99,8 @@ export class NanobotClient {
|
||||
}
|
||||
let socket: WebSocket
|
||||
try {
|
||||
this.uploadBase = url
|
||||
this.upload = null
|
||||
socket = new WebSocket(url)
|
||||
} catch (error) {
|
||||
this.lastFailure = sanitizeConnectionFailure(error)
|
||||
@@ -127,9 +134,14 @@ export class NanobotClient {
|
||||
this.lastFailure = "connection failed"
|
||||
this.reportRetryState()
|
||||
})
|
||||
socket.addEventListener("close", () => {
|
||||
socket.addEventListener("close", (event) => {
|
||||
if (this.socket !== socket) return
|
||||
this.socket = null
|
||||
this.upload = null
|
||||
this.receipts.close()
|
||||
this.lastFailure = event.code
|
||||
? `connection closed (${event.code}${event.reason ? `: ${event.reason}` : ""})`
|
||||
: "connection closed"
|
||||
this.rejectPendingMutations("gateway connection closed")
|
||||
if (this.closedByClient) {
|
||||
this.options.onStatus("closed")
|
||||
@@ -148,6 +160,8 @@ export class NanobotClient {
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.upload = null
|
||||
this.receipts.close()
|
||||
if (this.handshakeTimer) clearTimeout(this.handshakeTimer)
|
||||
this.handshakeTimer = null
|
||||
this.closedByClient = true
|
||||
@@ -160,9 +174,23 @@ export class NanobotClient {
|
||||
this.rejectPendingMutations("gateway connection closed")
|
||||
}
|
||||
|
||||
send(content: string, options: MessageOptions = {}): string {
|
||||
if (!this.chatId) throw new Error("chat is not ready")
|
||||
async sendAttachments(content: string, options: MessageOptions): Promise<string> {
|
||||
const socket = this.socket
|
||||
const chatId = this.chatId
|
||||
const upload = this.upload
|
||||
const stillConnected = () => this.socket === socket
|
||||
&& socket?.readyState === WebSocket.OPEN && this.upload === upload && this.chatId === chatId
|
||||
const references = await uploadAttachments(options.media ?? [], upload, this.uploadBase,
|
||||
stillConnected)
|
||||
if (!stillConnected()) throw new Error("Connection changed during attachment send")
|
||||
const turnId = crypto.randomUUID()
|
||||
await this.receipts.wait(turnId, () => this.send(content, options, references, turnId))
|
||||
return turnId
|
||||
}
|
||||
|
||||
send(content: string, options: MessageOptions = {}, references?: AttachmentReference[], turnId = crypto.randomUUID()): string {
|
||||
if (!this.chatId) throw new Error("chat is not ready")
|
||||
if (options.media?.length && !references) throw new Error("Attachments require HTTP upload")
|
||||
this.write({
|
||||
type: "message",
|
||||
chat_id: this.chatId,
|
||||
@@ -171,7 +199,7 @@ export class NanobotClient {
|
||||
webui: true,
|
||||
...(this.workspaceScope ? { workspace_scope: this.workspaceScope } : {}),
|
||||
...(options.userShell ? { user_shell: true } : {}),
|
||||
...(options.media?.length ? { media: options.media } : {}),
|
||||
...(references?.length ? { media: references } : {}),
|
||||
...(options.cliApps?.length ? { cli_apps: options.cliApps } : {}),
|
||||
...(options.mcpPresets?.length ? { mcp_presets: options.mcpPresets } : {}),
|
||||
...(options.sessionMentions?.length
|
||||
@@ -309,7 +337,9 @@ export class NanobotClient {
|
||||
return
|
||||
}
|
||||
|
||||
this.receipts.event(event)
|
||||
if (event.event === "ready") {
|
||||
this.upload = uploadCapability(isRecord(value) ? value.upload : null)
|
||||
const requestedChatId = this.chatId || this.options.chatId
|
||||
if (requestedChatId) {
|
||||
this.chatId = requestedChatId
|
||||
|
||||
@@ -193,7 +193,7 @@ export type OutboundEvent =
|
||||
turn_id: string
|
||||
webui: true
|
||||
workspace_scope?: WorkspaceScopePayload
|
||||
media?: OutboundMedia[]
|
||||
media?: import("../../../packages/client-events/attachments").AttachmentReference[]
|
||||
cli_apps?: Array<{ name: string }>
|
||||
mcp_presets?: Array<{ name: string }>
|
||||
session_mentions?: SessionMention[]
|
||||
|
||||
Reference in new issue
Block a user