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

+18 -2
View File
@@ -176,6 +176,7 @@ export class NanobotTui {
private ready = false
private shimmerFrame = 0
private shimmerTimer: ReturnType<typeof setInterval> | null = null
private attachmentSendPending = false
private submitPending = false
private submitGeneration = 0
private unsentSubmit = false
@@ -584,10 +585,25 @@ export class NanobotTui {
this.sendPrompt(prompt)
}
private sendPrompt(prompt: QueuedPrompt, steering = false): boolean {
private sendPrompt(prompt: QueuedPrompt, steering = false, acceptedTurnId?: string): boolean {
if (!acceptedTurnId && prompt.options.media?.length) {
if (this.attachmentSendPending) return false
this.attachmentSendPending = true
const originalText = this.composer.plainText
const chatId = this.client.activeChatId
this.status.content = "Uploading attachments…"
void this.client.sendAttachments(prompt.content, prompt.options).then((turnId) => {
if (this.client.activeChatId !== chatId || this.composer.plainText !== originalText) return
this.sendPrompt(prompt, steering, turnId)
}).catch((error: unknown) => {
this.unsentSubmit = true
this.status.content = error instanceof Error ? error.message : "Attachment send failed · draft retained"
}).finally(() => { this.attachmentSendPending = false })
return true
}
let turnId: string
try {
turnId = this.client.send(prompt.content, prompt.options)
turnId = acceptedTurnId ?? this.client.send(prompt.content, prompt.options)
} catch {
this.markSubmitUnsent(true)
return false
+32
View File
@@ -127,6 +127,38 @@ describe("NanobotTui composer", () => {
expect(ui.composer.plainText).toBe("")
})
test("retains the image and text until acceptance and after upload failure", async () => {
setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })
const transport = client()
let rejectSend: (error: Error) => void = () => {}
let resolveSend: (turnId: string) => void = () => {}
let attempts = 0
transport.sendAttachments = () => {
attempts++
return new Promise<string>((resolve, reject) => { resolveSend = resolve; rejectSend = reject })
}
const app = NanobotTui.mount(setup.renderer, options, transport,
new MockTreeSitterClient({ autoResolveTimeout: 0 }), undefined,
{ read: async () => ({ mimeType: "image/png", dataUrl: "data:image/png;base64,eA==" }), dispose: async () => {} })
app.accept({ event: "attached", chat_id: "chat" })
const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; draft: { imageCount: number }; status: { plainText: string } }
await waitUntil(() => ui.ready)
setup.mockInput.pressKey("v", { ctrl: true })
await waitUntil(() => ui.draft.imageCount === 1)
ui.composer.submit()
await waitUntil(() => attempts === 1)
expect(ui.composer.plainText).toContain("[Image #1]")
rejectSend(new Error("Upload failed (401)"))
await waitUntil(() => ui.status.plainText.includes("401"))
expect(ui.draft.imageCount).toBe(1)
expect(ui.composer.plainText).toContain("[Image #1]")
ui.composer.submit()
await waitUntil(() => attempts === 2)
resolveSend("accepted-image")
await waitUntil(() => ui.composer.plainText === "")
expect(ui.draft.imageCount).toBe(0)
})
test("pastes clipboard images into removable placeholders and sends their data", async () => {
const sent: string[] = []
const sentOptions: MessageOptions[] = []
+3
View File
@@ -66,6 +66,9 @@ export function client(
sentOptions.push(messageOptions)
return "turn"
},
async sendAttachments(content: string, messageOptions: MessageOptions) {
return this.send(content, messageOptions)
},
attach(chatId: string) {
attached.push(chatId)
},
+1
View File
@@ -32,6 +32,7 @@ export interface ChatClient {
connect(): void
close(): void
send(content: string, options?: MessageOptions): string
sendAttachments(content: string, options: MessageOptions): Promise<string>
attach(chatId: string): void
newChat(scope?: WorkspaceScopePayload): void
forkChat?(sourceChatId: string, beforeUserIndex: number, title?: string): void
+1
View File
@@ -46,6 +46,7 @@ describe("TUI /usage", () => {
const client = {
activeChatId: "chat", connect() {}, close() {},
send(content: string) { sent.push(content); return "turn" },
async sendAttachments(content: string) { return this.send(content) },
attach(chatId: string) { this.activeChatId = chatId },
newChat() { this.activeChatId = "new-chat" },
setWorkspaceScope() {},
+43 -4
View File
@@ -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 })
}
})
+34 -4
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 { 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
+1 -1
View File
@@ -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[]