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

-172
View File
@@ -1,172 +0,0 @@
"""Validation and persistence for inbound WebUI message attachments."""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any, Literal, cast
from nanobot.utils.media_decode import FileSizeExceeded, save_base64_data_url
from nanobot.webui.ingress_policy import (
DEFAULT_WEBUI_INGRESS_POLICY,
AttachmentIngressLimits,
)
AttachmentRejection = Literal[
"malformed",
"too_many_images",
"too_many_videos",
"too_many_attachments",
"total_size",
"mime",
"size",
"decode",
]
AttachmentIngressResult = tuple[list[str], AttachmentRejection | None]
_MAX_VIDEOS_PER_MESSAGE = 1
_MAX_VIDEO_BYTES = 20 * 1024 * 1024
_IMAGE_MIME_ALLOWED: frozenset[str] = frozenset({
"image/png",
"image/jpeg",
"image/webp",
"image/gif",
})
_VIDEO_MIME_ALLOWED: frozenset[str] = frozenset({
"video/mp4",
"video/webm",
"video/quicktime",
})
_DOCUMENT_MIME_ALLOWED: frozenset[str] = frozenset({
"application/json",
"application/pdf",
"application/toml",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/x-yaml",
"application/xhtml+xml",
"application/xml",
"application/yaml",
"text/csv",
"text/html",
"text/markdown",
"text/plain",
"text/xml",
"text/yaml",
})
_UPLOAD_MIME_ALLOWED: frozenset[str] = (
_IMAGE_MIME_ALLOWED | _VIDEO_MIME_ALLOWED | _DOCUMENT_MIME_ALLOWED
)
_DATA_URL_MIME_RE = re.compile(r"^data:([^;,]+)(?:;[^,]*)*;base64,", re.DOTALL)
def extract_data_url_mime(url: Any) -> str | None:
"""Return the normalized MIME from a base64 data URL, else ``None``."""
if not isinstance(url, str):
return None
match = _DATA_URL_MIME_RE.match(url)
if match is None:
return None
return match.group(1).strip().lower() or None
def store_inbound_attachments(
media: list[Any],
*,
media_dir: Path,
logger: Any,
limits: AttachmentIngressLimits = DEFAULT_WEBUI_INGRESS_POLICY.attachments,
) -> AttachmentIngressResult:
"""Validate and atomically persist one WebUI message's attachments.
The caller owns transport-level error mapping. This function owns the
WebUI upload policy and removes files already written when a later item
makes the batch invalid.
"""
image_count = 0
video_count = 0
document_count = 0
for item in media:
attachment = cast(dict[str, Any], item) if isinstance(item, dict) else None
mime = (
extract_data_url_mime(attachment.get("data_url", ""))
if attachment is not None
else None
)
if mime in _VIDEO_MIME_ALLOWED:
video_count += 1
elif mime in _IMAGE_MIME_ALLOWED:
image_count += 1
elif mime in _DOCUMENT_MIME_ALLOWED:
document_count += 1
if image_count > limits.max_count:
return [], "too_many_images"
if video_count > _MAX_VIDEOS_PER_MESSAGE:
return [], "too_many_videos"
if image_count + document_count > limits.max_count:
return [], "too_many_attachments"
paths: list[str] = []
total_attachment_bytes = 0
def abort(reason: AttachmentRejection) -> AttachmentIngressResult:
for path in paths:
try:
Path(path).unlink(missing_ok=True)
except OSError as exc:
logger.warning("failed to unlink partial media {}: {}", path, exc)
return [], reason
for item in media:
if not isinstance(item, dict):
return abort("malformed")
attachment = cast(dict[str, Any], item)
data_url = attachment.get("data_url")
if not isinstance(data_url, str) or not data_url:
return abort("malformed")
mime = extract_data_url_mime(data_url)
if mime is None:
return abort("decode")
if mime not in _UPLOAD_MIME_ALLOWED:
return abort("mime")
is_video = mime in _VIDEO_MIME_ALLOWED
is_document = mime in _DOCUMENT_MIME_ALLOWED
max_bytes = (
_MAX_VIDEO_BYTES if is_video
else limits.max_file_bytes
)
name = (
attachment.get("name")
if is_document and isinstance(attachment.get("name"), str)
else None
)
try:
saved = save_base64_data_url(
data_url,
media_dir,
max_bytes=max_bytes,
filename=name,
)
except FileSizeExceeded:
return abort("size")
except Exception as exc:
logger.warning("media decode failed: {}", exc)
return abort("decode")
if saved is None:
return abort("decode")
paths.append(saved)
if not is_video:
try:
total_attachment_bytes += Path(saved).stat().st_size
except OSError as exc:
logger.warning("failed to stat inbound attachment {}: {}", saved, exc)
return abort("decode")
if total_attachment_bytes > limits.max_total_bytes:
return abort("total_size")
return paths, None
+2
View File
@@ -17,6 +17,7 @@ SUBAGENT_CAPABILITY = "webui.subagents.v1"
SUBAGENT_EVENTS_CAPABILITY = "webui.subagents.events.v1"
SUBAGENT_HISTORY_CAPABILITY = "webui.subagents.history.v1"
AUTOMATION_CHAT_CAPABILITY = "webui.automation-chat.v1"
BINARY_ATTACHMENTS_CAPABILITY = "webui.attachments.binary.v1"
class Compatibility(TypedDict):
@@ -33,6 +34,7 @@ def webui_contract() -> dict[str, object]:
"capabilities": [
CORE_CAPABILITY, SUBAGENT_CAPABILITY, SUBAGENT_EVENTS_CAPABILITY,
SUBAGENT_HISTORY_CAPABILITY, AUTOMATION_CHAT_CAPABILITY,
BINARY_ATTACHMENTS_CAPABILITY,
],
}
+8 -1
View File
@@ -9,7 +9,10 @@ from typing import TYPE_CHECKING, Any, Callable
from loguru import logger as default_logger
from nanobot.channels.websocket.attachment_http import AttachmentHTTP
from nanobot.channels.websocket.attachment_store import AttachmentStore
from nanobot.config.loader import get_config_path
from nanobot.config.paths import get_media_dir
from nanobot.webui.gateway_endpoint import WebUIGatewayEndpoint
from nanobot.webui.gateway_tokens import GatewayTokenStore
from nanobot.webui.ingress_policy import DEFAULT_WEBUI_INGRESS_POLICY, WebUIIngressPolicy
@@ -39,6 +42,7 @@ class GatewayServices:
settings: WebUISettingsServices
tokens: GatewayTokenStore
media: WebUIMediaGateway
uploads: AttachmentHTTP
ingress: WebUIIngressPolicy
transcripts: WebUITranscriptRecorder
workspaces: WebUIWorkspaceController
@@ -101,8 +105,10 @@ def build_gateway_services(
media = WebUIMediaGateway(
workspace_path=workspace_path,
logger=logger,
attachment_limits=ingress.attachments,
)
uploads = AttachmentHTTP(AttachmentStore(
get_media_dir("websocket"), limits=ingress.attachments,
))
transcripts = WebUITranscriptRecorder(log=logger)
workspaces = WebUIWorkspaceController(
session_manager=session_manager,
@@ -152,6 +158,7 @@ def build_gateway_services(
settings=settings,
tokens=tokens,
media=media,
uploads=uploads,
ingress=ingress,
transcripts=transcripts,
workspaces=workspaces,
+82 -26
View File
@@ -16,6 +16,7 @@ from loguru import logger
from websockets.asyncio.server import ServerConnection
from nanobot.bus.events import INBOUND_META_USER_SHELL
from nanobot.channels.websocket.attachment_store import AttachmentUploadError
from nanobot.command.builtin import USER_SHELL_COMMAND, builtin_command_starts_agent_turn
from nanobot.runtime_context import (
RUNTIME_CONTEXT_INPUT_META,
@@ -139,6 +140,7 @@ class WebUICommandRouter:
self.gateway = gateway
self._http_router = gateway.http
self._media = gateway.media
self._uploads = gateway.uploads
self._ingress = gateway.ingress
self._transcripts = gateway.transcripts
self._workspaces = gateway.workspaces
@@ -156,6 +158,8 @@ class WebUICommandRouter:
] = {}
self.request_operations: dict[str, WebUIRequestOperation] = {}
self.request_locks: dict[ServerConnection, asyncio.Lock] = {}
self._accepted_messages: dict[tuple[str, str], float] = {}
self._message_locks: dict[tuple[str, str], tuple[asyncio.Lock, int]] = {}
def workspace_project_selection_available(self, connection: ServerConnection) -> bool:
return self._http_router.workspace_project_selection_available(connection)
@@ -484,6 +488,29 @@ class WebUICommandRouter:
connection: ServerConnection,
client_id: str,
envelope: dict[str, Any],
) -> None:
chat_id, turn_id = envelope.get("chat_id"), envelope.get("turn_id")
if not isinstance(chat_id, str) or not isinstance(turn_id, str) or not turn_id:
await self._dispatch_message_once(connection, client_id, envelope)
return
key = (chat_id, turn_id)
lock, users = self._message_locks.get(key, (asyncio.Lock(), 0))
self._message_locks[key] = (lock, users + 1)
try:
async with lock:
await self._dispatch_message_once(connection, client_id, envelope)
finally:
_, users = self._message_locks[key]
if users == 1:
del self._message_locks[key]
else:
self._message_locks[key] = (lock, users - 1)
async def _dispatch_message_once(
self,
connection: ServerConnection,
client_id: str,
envelope: dict[str, Any],
) -> None:
chat_id = envelope.get("chat_id")
content = envelope.get("content")
@@ -523,6 +550,19 @@ class WebUICommandRouter:
)
return
# A client may retry the same turn after an ACK was lost. Check before
# resolving already-committed refs; never dispatch that turn twice.
now = time.monotonic()
self._accepted_messages = {
key: expires for key, expires in self._accepted_messages.items() if expires > now
}
if turn_id and (chat_id, turn_id) in self._accepted_messages:
await self._transport.webui_send_event(
connection, "message_accepted", chat_id=chat_id, turn_id=turn_id,
starts_turn=False,
)
return
try:
temporary_policy = self._temporary_chats.message_policy(
connection,
@@ -538,37 +578,35 @@ class WebUICommandRouter:
)
return
raw_media = envelope.get("media")
raw_media = envelope.get("media", [])
media_paths: list[str] = []
media_names: list[str | None] = []
if raw_media is not None:
references: list[str] = []
upload_owner = self._uploads.owner(connection) if raw_media else ""
try:
if not isinstance(raw_media, list):
await self._transport.webui_send_event(
connection,
"error",
detail="attachment_rejected",
reason="malformed",
**rejection_fields,
)
return
media_paths, reason = self._media.store_inbound_attachments(
cast(list[Any], raw_media)
)
if reason is not None:
await self._transport.webui_send_event(
connection,
"error",
detail="attachment_rejected",
reason=reason,
**rejection_fields,
)
return
for item in cast(list[Any], raw_media):
attachment = cast(dict[str, Any], item) if isinstance(item, dict) else {}
raise AttachmentUploadError("malformed")
attachments = cast(list[Any], raw_media)
if len(attachments) > self._uploads.store.limits.max_count + 1:
raise AttachmentUploadError("Too many attachments")
for item in attachments:
if not isinstance(item, dict):
raise AttachmentUploadError("malformed")
attachment = cast(dict[str, Any], item)
reference = attachment.get("reference")
if not isinstance(reference, str) or len(reference) > 64 or "data_url" in attachment:
raise AttachmentUploadError("Expected an HTTP attachment reference")
references.append(reference)
name = attachment.get("name")
media_names.append((safe_filename(name) or None) if isinstance(name, str) else None)
if temporary_policy is not None:
self._temporary_chats.register_media(connection, chat_id, media_paths)
if references:
media_paths = self._uploads.store.resolve(references, owner=upload_owner)
except AttachmentUploadError as exc:
await self._transport.webui_send_event(
connection, "error", detail="attachment_rejected", reason=str(exc),
**rejection_fields,
)
return
if not content.strip() and not media_paths:
await self._transport.webui_send_event(
@@ -646,6 +684,20 @@ class WebUICommandRouter:
if session_mentions:
metadata["session_mentions"] = session_mentions
metadata[WORKSPACE_SCOPE_METADATA_KEY] = scope.metadata()
# Revalidate after all asynchronous scope/hydration work. Commit before
# persisting paths, with no intervening await, so expiry cannot remove
# files referenced by the canonical transcript.
try:
if references:
media_paths = self._uploads.store.commit(references, owner=upload_owner)
except AttachmentUploadError as exc:
await self._transport.webui_send_event(
connection, "error", detail="attachment_rejected", reason=str(exc),
**rejection_fields,
)
return
if temporary_policy is not None:
self._temporary_chats.register_media(connection, chat_id, media_paths)
is_webui = metadata.get("webui") is True
queued_owner = None
if is_webui and not is_user_shell and builtin_command_starts_agent_turn(content):
@@ -702,6 +754,10 @@ class WebUICommandRouter:
)
self._workspaces.persist_scope(chat_id, scope)
accepted = True
if turn_id:
self._accepted_messages[(chat_id, turn_id)] = time.monotonic() + 600
if len(self._accepted_messages) > 1024:
del self._accepted_messages[next(iter(self._accepted_messages))]
finally:
if not accepted and queued_owner is not None:
clear_websocket_turn_if_current(chat_id, queued_owner)
+4 -17
View File
@@ -7,10 +7,11 @@ for a text or attachment policy.
from __future__ import annotations
import math
from dataclasses import dataclass, field
from typing import Literal
from nanobot.channels.websocket.attachment_policy import AttachmentIngressLimits
MessageRejection = Literal["text_too_large"]
@@ -19,13 +20,6 @@ class MessageIngressLimits:
max_text_bytes: int = 64 * 1024
@dataclass(frozen=True)
class AttachmentIngressLimits:
max_count: int = 4
max_file_bytes: int = 6 * 1024 * 1024
max_total_bytes: int = 24 * 1024 * 1024
@dataclass(frozen=True)
class WebUIIngressPolicy:
"""Limits applied after the channel has decoded the transport envelope."""
@@ -56,15 +50,8 @@ class WebUIIngressPolicy:
}
def minimum_full_policy_frame_bytes(self) -> int:
"""Conservative frame size needed for every policy-valid message."""
encoded_attachments = 4 * math.ceil(self.attachments.max_total_bytes / 3)
data_url_allowance = self.attachments.max_count * 128
return (
encoded_attachments
+ data_url_allowance
+ self.message.max_text_bytes
+ self.envelope_reserve_bytes
)
"""Conservative frame capacity for messages using HTTP attachments."""
return self.message.max_text_bytes + self.envelope_reserve_bytes
DEFAULT_WEBUI_INGRESS_POLICY = WebUIIngressPolicy()
-16
View File
@@ -11,11 +11,6 @@ from websockets.http11 import Request as WsRequest
from websockets.http11 import Response
from nanobot.config.paths import get_media_dir
from nanobot.webui.attachment_ingress import (
AttachmentIngressResult,
store_inbound_attachments,
)
from nanobot.webui.ingress_policy import AttachmentIngressLimits
from nanobot.webui.media_api import (
serve_signed_media,
sign_or_stage_media_path,
@@ -38,22 +33,11 @@ class WebUIMediaGateway:
logger: Any,
media_dir: Callable[[str | None], Path] | None = None,
secret: bytes | None = None,
attachment_limits: AttachmentIngressLimits | None = None,
) -> None:
self.workspace_path = workspace_path
self.logger = logger
self._media_dir: Callable[[str | None], Path] = media_dir or _default_media_dir
self.secret = secret or secrets.token_bytes(32)
self.attachment_limits = attachment_limits or AttachmentIngressLimits()
def store_inbound_attachments(self, media: list[Any]) -> AttachmentIngressResult:
"""Validate and persist attachments from an inbound WebUI message."""
return store_inbound_attachments(
media,
media_dir=self._media_dir("websocket"),
logger=self.logger,
limits=self.attachment_limits,
)
def serve_signed_media(
self,
+80 -2
View File
@@ -27,6 +27,11 @@ from websockets.exceptions import WebSocketException
from websockets.typing import Origin
from yarl import URL
from nanobot.channels.websocket.attachment_http import UPLOAD_PATH
from nanobot.channels.websocket.attachment_policy import (
UPLOAD_IDLE_TIMEOUT_SECONDS,
UPLOAD_REQUEST_TIMEOUT_SECONDS,
)
from nanobot.webui.client_contract import assess_webui_contract, compatibility_error
from nanobot.webui.local_client_assets import LocalClientAssets
from nanobot.webui.remote_ssh import (
@@ -71,6 +76,7 @@ class RemoteProxy:
self._ws_path = "/remote-session/" + secrets.token_urlsafe(18)
self._api: dict[str, _Grant] = {}
self._ws: dict[str, _Grant] = {}
self._uploads: dict[str, _Grant] = {}
self._media_cipher = Fernet(Fernet.generate_key())
self._media_cache: OrderedDict[str, str] = OrderedDict()
self._tasks: set[asyncio.Task[Any]] = set()
@@ -91,7 +97,9 @@ class RemoteProxy:
self.port = int(listener.getsockname()[1])
app = web.Application(client_max_size=_MAX_BYTES)
app.router.add_route("*", "/{path:.*}", self._handle)
self._runner = web.AppRunner(app, access_log=None, handler_cancellation=True)
self._runner = web.AppRunner(
app, access_log=None, handler_cancellation=True, auto_decompress=False,
)
try:
await self._runner.setup()
await web.SockSite(self._runner, listener).start()
@@ -114,6 +122,7 @@ class RemoteProxy:
self._ws_path = "/remote-session/" + secrets.token_urlsafe(18)
self._api.clear()
self._ws.clear()
self._uploads.clear()
self._media_cipher = Fernet(Fernet.generate_key())
self._media_cache.clear()
self._remote_secret = secret
@@ -129,6 +138,7 @@ class RemoteProxy:
await asyncio.gather(*tasks, return_exceptions=True)
self._api.clear()
self._ws.clear()
self._uploads.clear()
await self.tunnel.pause()
async def close(self) -> None:
@@ -196,6 +206,8 @@ class RemoteProxy:
return await self._bootstrap()
if path == "/webui/terminal":
raise web.HTTPForbidden()
if path == UPLOAD_PATH:
return await self._upload(request)
if not path.startswith("/api/"):
return self.assets.response(request)
return await self._http(request, path)
@@ -348,6 +360,52 @@ class RemoteProxy:
await result.write_eof()
return result
async def _upload(self, request: web.Request) -> web.Response:
if request.method != "POST":
raise web.HTTPMethodNotAllowed(request.method, ["POST"])
if not request.headers.getall("Authorization", []):
raise web.HTTPUnauthorized()
grant = self._grant(self._credential(request), self._uploads)
if request.headers.get("Content-Encoding") or request.headers.get("Transfer-Encoding"):
raise web.HTTPBadRequest(text="Unsupported attachment framing")
size = request.content_length
if size is None or not 0 < size <= _MAX_BYTES:
raise web.HTTPBadRequest(text="Invalid attachment size")
headers = self._headers(request)
headers["Authorization"] = "Bearer " + grant.remote
headers["Content-Length"] = str(size)
if "X-Attachment-Name" in request.headers:
headers["X-Attachment-Name"] = request.headers["X-Attachment-Name"]
# Only this connection-scoped upload route accepts HTTP writes. Stream
# the declared bytes without decoding or buffering the browser's file.
async def upload_body():
iterator = aiter(request.content.iter_chunked(64 * 1024))
while True:
async with asyncio.timeout(UPLOAD_IDLE_TIMEOUT_SECONDS):
try:
chunk = await anext(iterator)
except StopAsyncIteration:
return
yield chunk
async with asyncio.timeout(UPLOAD_REQUEST_TIMEOUT_SECONDS), httpx.AsyncClient(
trust_env=False, timeout=httpx.Timeout(UPLOAD_IDLE_TIMEOUT_SECONDS, connect=20),
) as client:
async with client.stream("POST", self._upstream(UPLOAD_PATH), headers=headers,
content=upload_body()) as upstream:
if upstream.is_redirect:
raise web.HTTPBadGateway(text="Unexpected remote redirect")
body = bytearray()
async for chunk in upstream.aiter_bytes():
body.extend(chunk)
if len(body) > _MAX_BYTES:
raise ValueError("response too large")
return web.Response(body=bytes(body), status=upstream.status_code, headers={
"Content-Type": upstream.headers.get("Content-Type", "application/json"),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
})
async def _websocket(self, request: web.Request, grant: _Grant) -> web.WebSocketResponse:
# An already-connected socket fixes the upstream and disables all WS
# redirects. Its HTTP authority still matches the browser's origin.
@@ -364,15 +422,35 @@ class RemoteProxy:
max_size=_MAX_BYTES, open_timeout=20, close_timeout=2) as upstream:
browser = web.WebSocketResponse(max_msg_size=_MAX_BYTES, heartbeat=30)
await browser.prepare(request)
upload_token = ""
async def receive() -> None:
nonlocal upload_token
try:
async for message in upstream:
if isinstance(message, bytes):
await browser.send_bytes(message)
else:
await browser.send_str(json.dumps(self._rewrite(json.loads(message))))
payload: object = json.loads(message)
if isinstance(payload, dict):
data = cast(dict[str, Any], payload)
if data.get("event") == "ready":
self._uploads.pop(upload_token, None)
upload_token = ""
upload = data.pop("upload", None)
if isinstance(upload, dict):
upload = cast(dict[str, Any], upload)
if (upload.get("path") == UPLOAD_PATH
and isinstance(upload.get("token"), str)
and upload["token"]):
if len(self._uploads) >= _MAX_CAPABILITIES:
raise ValueError("too many upload capabilities")
upload_token = secrets.token_urlsafe(32)
self._uploads[upload_token] = _Grant(upload["token"], math.inf)
data["upload"] = {"path": UPLOAD_PATH, "token": upload_token}
await browser.send_str(json.dumps(self._rewrite(payload)))
finally:
self._uploads.pop(upload_token, None)
await browser.close()
reader = asyncio.create_task(receive())