Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): upload TUI and WebUI attachments over binary HTTP (#5980)
chengyongru6646f5fbee5a
diff --git a/docs/websocket.md b/docs/websocket.mdindex 7dbc6d23c..5319b36fe 100644--- a/docs/websocket.md+++ b/docs/websocket.md@@ -204,9 +204,56 @@ Recognized fields: `content`, `text`, `message` (checked in that order). InvalidSee [Multi-chat multiplexing](#multi-chat-multiplexing) for the full flow.+### Binary attachments (WebUI and TUI)++The gateway advertises `webui.attachments.binary.v1`. WebUI protocol 1 and the+terminal protocol are unchanged. Bundled clients and their gateway use HTTP on+the same listener for attachment uploads. After an authorized handshake, `ready`+includes an `upload` object with `path: "/api/attachments"` and an opaque `token`.+This token is a short-lived capability tied to that live connection, not the+one-time handshake token, API token, or client-selected `client_id`.++1. `POST` the raw file bytes to the advertised path with `Authorization: Bearer+ <upload token>`, the file's `Content-Type`, and an exact `Content-Length`.+ `X-Attachment-Name` may contain a percent-encoded display filename.+ Compressed request bodies and chunked transfer encoding are rejected.+2. The response is `201 {"reference": "<opaque reference>"}`. Use it in a small+ WebSocket envelope, for example:++ ```json+ {"type":"message","chat_id":"chat-id","content":"Inspect this","webui":true,"turn_id":"unique-turn-id","media":[{"reference":"opaque-reference","name":"report.pdf"}]}+ ```++3. Retain the draft and local preview until `message_accepted` confirms the turn.+ A connection close before confirmation means delivery is uncertain, not that+ the draft should be discarded. Reconnect obtains a new upload capability;+ old uncommitted references cannot be used by the new connection. A repeated+ accepted `(chat_id, turn_id)` is acknowledged without another dispatch within+ the gateway's bounded ten-minute in-memory retry window.++The upload path accepts the existing image, document, and video MIME whitelist.+Existing file/count/total limits still apply independently of `maxMessageBytes`.+Uploads time out after five minutes, or after 30 seconds without receiving more+data. Uploads are not resumable, so a retry sends the whole file.++Update WebUI and TUI together with the gateway. Existing messages and attachments+remain available without a history migration. Clients must use HTTP uploads;+`media.data_url` message uploads are no longer accepted. Local previews and the+separate audio transcription protocol are unchanged.++Reverse proxies must forward `POST /api/attachments` (including its authorization+header) to the gateway and permit the configured file sizes. Do not enable public+CORS for this capability endpoint.++For a remote host opened through the local WebUI, update the local installation+and the remote gateway together to use binary attachments. An older host's text+chats and HTTP reads remain available.+## Configuration ReferenceAll fields go under `channels.websocket` in `config.json`.+Unrecognized options retain the existing behavior: they are ignored without+preventing startup. Active options below remain validated.### Connection@@ -217,7 +264,7 @@ All fields go under `channels.websocket` in `config.json`.| `port` | int | `8765` | Listen port. || `path` | string | `"/"` | WebSocket upgrade path. Trailing slashes are normalized (root `/` is preserved). || `publicWsUrl` | string | `""` | Exact public `ws://` or `wss://` endpoint returned by `/webui/bootstrap`. Set this when a reverse proxy forwards requests with an origin `Host` header (for example, `wss://claw.example.com/`); its path must match `path`. |-| `maxMessageBytes` | int | `37748736` | Maximum inbound message size in bytes (1 KB – 40 MB). Default (36 MB) is sized to accept up to 4 base64-encoded image attachments at 8 MB each; lower it if the channel only carries text. |+| `maxMessageBytes` | int | `37748736` | Maximum inbound WebSocket frame size in bytes (1 KB – 40 MB). The existing 36 MB default is retained. HTTP binary attachments do not count toward this limit; a legacy 1 MB setting no longer prevents larger attachments from being sent. |### Authenticationdiff --git a/nanobot/channels/__init__.py b/nanobot/channels/__init__.pyindex 1ef3cb967..475a60514 100644--- a/nanobot/channels/__init__.py+++ b/nanobot/channels/__init__.py@@ -1,5 +1,20 @@"""Shared contracts for chat channels."""-from nanobot.channels.base import BaseChannel+from __future__ import annotations++from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from nanobot.channels.base import BaseChannel+++def __getattr__(name: str) -> type[BaseChannel]:+ if name != "BaseChannel":+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ from nanobot.channels.base import BaseChannel++ globals()[name] = BaseChannel+ return BaseChannel+__all__ = ["BaseChannel"]diff --git a/nanobot/channels/websocket/attachment_http.py b/nanobot/channels/websocket/attachment_http.pynew file mode 100644index 000000000..a907adf87--- /dev/null+++ b/nanobot/channels/websocket/attachment_http.py@@ -0,0 +1,79 @@+"""Connection-scoped upload capabilities, issued only after the WS handshake."""+from __future__ import annotations++import secrets+from urllib.parse import unquote+from weakref import WeakKeyDictionary++from aiohttp import web+from websockets.asyncio.server import ServerConnection++from nanobot.channels.websocket.attachment_store import AttachmentStore, AttachmentUploadError++UPLOAD_PATH = "/api/attachments"+++class AttachmentHTTP:+ def __init__(self, store: AttachmentStore) -> None:+ self.store = store+ self._owners: WeakKeyDictionary[ServerConnection, str] = WeakKeyDictionary()+ self._tokens: set[str] = set()++ def issue(self, connection: ServerConnection) -> dict[str, str]:+ self.revoke(connection)+ token = secrets.token_urlsafe(32)+ self._owners[connection] = token+ self._tokens.add(token)+ return {"path": UPLOAD_PATH, "token": token}++ def owner(self, connection: ServerConnection) -> str:+ return self._owners.get(connection, "")++ def revoke(self, connection: ServerConnection) -> None:+ owner = self._owners.pop(connection, "")+ self._tokens.discard(owner)+ if owner:+ self.store.discard_owner(owner)++ async def handle(self, request: web.BaseRequest) -> web.StreamResponse:+ # Never reflect credentials, enable CORS, accept cookies, or reuse the+ # one-shot WS handshake token. The capability is valid on one live WS.+ if request.path != UPLOAD_PATH or request.method != "POST":+ response = web.json_response({"error": "not_found"}, status=404)+ else:+ authorization = request.headers.get("Authorization", "")+ owner = authorization.removeprefix("Bearer ")+ if not authorization.startswith("Bearer ") or owner not in self._tokens:+ response = web.json_response({"error": "unauthorized"}, status=401)+ elif request.headers.get("Content-Encoding") or request.headers.get("Transfer-Encoding"):+ response = web.json_response({"error": "unsupported_framing"}, status=400)+ elif request.headers.get("Expect", "").lower() not in {"", "100-continue"}:+ response = web.json_response({"error": "unsupported_expectation"}, status=417)+ else:+ async def body():+ # Iteration starts only after metadata and quota validation.+ if request.headers.get("Expect", "").lower() == "100-continue":+ await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n")+ async for chunk in request.content.iter_chunked(64 * 1024):+ yield chunk++ try:+ reference = await self.store.upload(+ body(), owner=owner,+ mime=request.headers.get("Content-Type", ""),+ size=request.content_length or 0,+ filename=unquote(request.headers.get("X-Attachment-Name", "")),+ )+ if owner not in self._tokens:+ self.store.discard([reference], owner=owner)+ raise AttachmentUploadError("Connection closed during upload")+ response = web.json_response({"reference": reference}, status=201)+ except TimeoutError:+ response = web.json_response({"error": "Attachment upload timed out"}, status=400)+ except (AttachmentUploadError, OSError) as exc:+ response = web.json_response({"error": str(exc)}, status=400)+ response.headers["Cache-Control"] = "no-store"+ # A POST connection cannot later switch to the GET/WS parser. Closing+ # also avoids draining an unauthenticated or rejected large body.+ response.force_close()+ return responsediff --git a/nanobot/channels/websocket/attachment_policy.py b/nanobot/channels/websocket/attachment_policy.pynew file mode 100644index 000000000..030a8cc3c--- /dev/null+++ b/nanobot/channels/websocket/attachment_policy.py@@ -0,0 +1,41 @@+"""File, MIME and batch policy for WebSocket channel binary uploads."""++from dataclasses import dataclass+++@dataclass(frozen=True)+class AttachmentIngressLimits:+ max_count: int = 4+ max_file_bytes: int = 6 * 1024 * 1024+ max_total_bytes: int = 24 * 1024 * 1024+++MAX_VIDEOS_PER_MESSAGE = 1+MAX_VIDEO_BYTES = 20 * 1024 * 1024++# A 20 MiB upload takes about 168 seconds at 1 Mbps. Keep a finite total+# budget with room for contention, but release stalled uploads promptly.+UPLOAD_TIMEOUT_SECONDS = 300.0+UPLOAD_IDLE_TIMEOUT_SECONDS = 30.0+UPLOAD_REQUEST_TIMEOUT_SECONDS = 315.0++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 = IMAGE_MIME_ALLOWED | VIDEO_MIME_ALLOWED | DOCUMENT_MIME_ALLOWEDdiff --git a/nanobot/channels/websocket/attachment_store.py b/nanobot/channels/websocket/attachment_store.pynew file mode 100644index 000000000..a4cad232e--- /dev/null+++ b/nanobot/channels/websocket/attachment_store.py@@ -0,0 +1,224 @@+"""Bounded staging for binary uploads, independent of WebSocket frame limits.++The HTTP adapter must authenticate before calling ``upload``. ``owner`` must be+server-authenticated identity, never a client-selected ID. References are only+transport state; callers persist the paths returned by ``resolve`` as before.+"""++from __future__ import annotations++import asyncio+import secrets+import time+from collections.abc import AsyncIterable+from dataclasses import dataclass+from pathlib import Path++from nanobot.channels.websocket.attachment_policy import (+ DOCUMENT_MIME_ALLOWED,+ MAX_VIDEO_BYTES,+ MAX_VIDEOS_PER_MESSAGE,+ UPLOAD_IDLE_TIMEOUT_SECONDS,+ UPLOAD_MIME_ALLOWED,+ UPLOAD_TIMEOUT_SECONDS,+ VIDEO_MIME_ALLOWED,+ AttachmentIngressLimits,+)+from nanobot.utils.media_decode import media_destination+++class AttachmentUploadError(ValueError):+ """An upload or reference failed validation without consuming the draft."""+++@dataclass(frozen=True)+class _Attachment:+ owner: str+ path: Path+ mime: str+ size: int+ expires: float+++class AttachmentStore:+ """Single-event-loop staging store with disk, count, and lifetime bounds.++ A whole file's declared size is reserved before awaiting its first chunk,+ so concurrent slow uploads cannot bypass the global disk quota. ``prune``+ should also be called periodically by the owning gateway. Committed files+ leave this store and are managed by the existing session media lifecycle.+ """++ def __init__(+ self,+ media_dir: Path,+ *,+ limits: AttachmentIngressLimits | None = None,+ max_pending: int = 128,+ max_pending_bytes: int = 128 * 1024 * 1024,+ ttl_seconds: float = 600,+ upload_timeout: float = UPLOAD_TIMEOUT_SECONDS,+ upload_idle_timeout: float = UPLOAD_IDLE_TIMEOUT_SECONDS,+ ) -> None:+ if min(max_pending, max_pending_bytes, ttl_seconds, upload_timeout, upload_idle_timeout) <= 0:+ raise ValueError("Attachment store bounds must be positive")+ self.media_dir = media_dir+ self.limits = limits or AttachmentIngressLimits()+ self.max_pending = max_pending+ self.max_pending_bytes = max_pending_bytes+ self.ttl_seconds = ttl_seconds+ self.upload_timeout = upload_timeout+ self.upload_idle_timeout = upload_idle_timeout+ self._entries: dict[str, _Attachment] = {}+ self._reserved_bytes = 0+ self._active = 0+ self._journal = media_dir / ".pending-attachments"++ async def upload(+ self,+ chunks: AsyncIterable[bytes],+ *,+ owner: str,+ mime: str,+ size: int,+ filename: str | None = None,+ ) -> str:+ """Stream a declared-length binary body and return an opaque reference.++ No body bytes are requested until metadata and capacity are validated.+ The adapter must disable automatic request decompression and reject+ ambiguous framing, and must not buffer the complete body beforehand.+ """+ self.prune()+ if not owner:+ raise AttachmentUploadError("Missing authenticated owner")+ if mime not in UPLOAD_MIME_ALLOWED:+ raise AttachmentUploadError("Unsupported attachment MIME")+ limit = MAX_VIDEO_BYTES if mime in VIDEO_MIME_ALLOWED else self.limits.max_file_bytes+ if isinstance(size, bool) or not 0 < size <= limit:+ raise AttachmentUploadError("Invalid attachment size")+ if self._active + len(self._entries) >= self.max_pending:+ raise AttachmentUploadError("Too many pending attachments")+ if self._reserved_bytes + size > self.max_pending_bytes:+ raise AttachmentUploadError("Pending attachment storage is full")+ self._active += 1+ self._reserved_bytes += size+ path: Path | None = None+ stored = False+ created = False+ marker_created = False+ try:+ self.media_dir.mkdir(parents=True, exist_ok=True)+ path = media_destination(+ self.media_dir, mime,+ filename=filename if mime in DOCUMENT_MIME_ALLOWED else None,+ )+ self._journal.mkdir(parents=True, exist_ok=True)+ (self._journal / path.name).touch(exist_ok=False)+ marker_created = True+ received = 0+ # Exclusive creation prevents accidental overwrite or symlink following.+ with path.open("xb") as output:+ created = True+ async with asyncio.timeout(self.upload_timeout):+ iterator = aiter(chunks)+ while True:+ async with asyncio.timeout(self.upload_idle_timeout):+ try:+ chunk = await anext(iterator)+ except StopAsyncIteration:+ break+ received += len(chunk)+ if received > size:+ raise AttachmentUploadError("Attachment exceeds declared size")+ output.write(chunk)+ if received != size:+ raise AttachmentUploadError("Incomplete attachment body")+ reference = secrets.token_urlsafe(32)+ self._entries[reference] = _Attachment(+ owner, path, mime, size, time.monotonic() + self.ttl_seconds,+ )+ stored = True+ return reference+ finally:+ self._active -= 1+ if not stored:+ self._reserved_bytes -= size+ if path is not None:+ if created:+ path.unlink(missing_ok=True)+ if marker_created:+ (self._journal / path.name).unlink(missing_ok=True)++ def resolve(self, references: list[str], *, owner: str) -> list[str]:+ """Validate a complete batch without consuming it, allowing send retries."""+ self.prune()+ if len(references) > self.limits.max_count + MAX_VIDEOS_PER_MESSAGE:+ raise AttachmentUploadError("Too many attachments")+ if len(set(references)) != len(references):+ raise AttachmentUploadError("Duplicate attachment reference")+ entries: list[_Attachment] = []+ for reference in references:+ entry = self._entries.get(reference)+ if entry is None or not owner or entry.owner != owner:+ raise AttachmentUploadError("Invalid attachment reference")+ entries.append(entry)+ videos = sum(entry.mime in VIDEO_MIME_ALLOWED for entry in entries)+ if videos > MAX_VIDEOS_PER_MESSAGE:+ raise AttachmentUploadError("Too many attachments")+ if len(entries) - videos > self.limits.max_count:+ raise AttachmentUploadError("Too many attachments")+ if sum(e.size for e in entries if e.mime not in VIDEO_MIME_ALLOWED) > self.limits.max_total_bytes:+ raise AttachmentUploadError("Attachment total exceeds limit")+ return [str(entry.path) for entry in entries]++ def commit(self, references: list[str], *, owner: str) -> list[str]:+ """Transfer validated files to session ownership after message acceptance.++ The caller must not await between resolve, synchronous acceptance, and+ commit. A rejected message must leave references staged for retry.+ """+ paths = self.resolve(references, owner=owner)+ for reference in references:+ entry = self._entries[reference]+ (self._journal / entry.path.name).unlink(missing_ok=True)+ self._reserved_bytes -= self._entries.pop(reference).size+ return paths++ def discard_owner(self, owner: str) -> None:+ self.discard([ref for ref, entry in self._entries.items() if entry.owner == owner], owner=owner)++ def discard(self, references: list[str], *, owner: str) -> None:+ for reference in references:+ entry = self._entries.get(reference)+ if entry is not None and entry.owner == owner:+ entry.path.unlink(missing_ok=True)+ (self._journal / entry.path.name).unlink(missing_ok=True)+ self._reserved_bytes -= entry.size+ del self._entries[reference]++ def prune(self) -> None:+ """Remove abandoned uploads; never delete committed session media."""+ now = time.monotonic()+ # Crash remnants retain a marker; committed historical files never do.+ cutoff = time.time() - self.ttl_seconds - self.upload_timeout+ for marker in self._journal.glob("*"):+ if marker.is_file() and marker.stat().st_mtime < cutoff:+ (self.media_dir / marker.name).unlink(missing_ok=True)+ marker.unlink(missing_ok=True)+ for reference, entry in list(self._entries.items()):+ if entry.expires <= now:+ entry.path.unlink(missing_ok=True)+ (self._journal / entry.path.name).unlink(missing_ok=True)+ self._reserved_bytes -= entry.size+ del self._entries[reference]++ def clear(self) -> None:+ """Clean staging after the gateway has stopped accepting uploads."""+ if self._active:+ raise RuntimeError("Stop active uploads before clearing attachment storage")+ for reference, entry in list(self._entries.items()):+ entry.path.unlink(missing_ok=True)+ (self._journal / entry.path.name).unlink(missing_ok=True)+ self._reserved_bytes -= entry.size+ del self._entries[reference]diff --git a/nanobot/channels/websocket/binary_http.py b/nanobot/channels/websocket/binary_http.pynew file mode 100644index 000000000..263d93d6d--- /dev/null+++ b/nanobot/channels/websocket/binary_http.py@@ -0,0 +1,135 @@+"""Body-capable HTTP bridge for the WebSocket channel listener.++GET (including WebSocket upgrades) remains on websockets' existing parser and+handshake path. Other methods go directly to aiohttp's bounded streaming HTTP+parser on the same socket, without proxying or changing the authenticated peer.+"""++from __future__ import annotations++import asyncio+from collections.abc import Awaitable, Callable+from typing import Any, cast++from aiohttp import web+from aiohttp.web_protocol import RequestHandler+from websockets.asyncio.server import ServerConnection++from nanobot.channels.websocket.attachment_policy import UPLOAD_REQUEST_TIMEOUT_SECONDS++_HTTP_HEADER_TIMEOUT_S = 75.0+_HTTP_CONNECTION_TIMEOUT_S = UPLOAD_REQUEST_TIMEOUT_SECONDS+++class BinaryHTTPBridge:+ """Own HTTP connections alongside a websockets ``serve`` instance.++ Pass ``connection_factory`` as ``create_connection`` to serve/unix_serve.+ After closing the listening server, await ``shutdown`` before disposing the+ upload store. Request decompression is deliberately disabled: declared body+ lengths must measure the exact bytes the upload store writes.+ """++ def __init__(self, handler: Callable[[web.BaseRequest], Awaitable[web.StreamResponse]]) -> None:+ async def request_started(request: web.BaseRequest) -> web.StreamResponse:+ if request.transport is not None:+ # This bridge remains the transport protocol while delegating+ # HTTP parsing to RequestHandler on the same transport.+ connection = cast(_BridgeConnection, request.transport.get_protocol())+ connection.request_started()+ return await handler(request)++ self.http_server = web.Server(request_started, auto_decompress=False, keepalive_timeout=5)+ self.pending_connections: set[_BridgeConnection] = set()++ bridge = self++ class Connection(_BridgeConnection):+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, bridge=bridge, **kwargs)++ self.connection_factory: type[ServerConnection] = Connection++ async def shutdown(self) -> None:+ for connection in tuple(self.pending_connections):+ connection.transport.close()+ await self.http_server.shutdown(timeout=1)+++class _BridgeConnection(ServerConnection):+ def __init__(self, *args: Any, bridge: BinaryHTTPBridge, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ self._bridge = bridge+ self._prefix = bytearray()+ self._http_protocol: RequestHandler | None = None+ self._selected = False+ self._prefix_timeout: asyncio.TimerHandle | None = None++ def connection_made(self, transport: asyncio.BaseTransport) -> None:+ # Delay websockets' handshake task until we know which parser owns this+ # connection. In particular, never feed a POST to Request.parse().+ self.transport = cast(asyncio.Transport, transport)+ self._bridge.pending_connections.add(self)+ self._prefix_timeout = asyncio.get_running_loop().call_later(10, self.transport.close)++ def data_received(self, data: bytes) -> None:+ if not self._selected:+ needed = 4 - len(self._prefix)+ self._prefix.extend(data[:needed])+ if len(self._prefix) < 4:+ return+ data = bytes(self._prefix) + data[needed:]+ self._prefix.clear()+ self._selected = True+ self._bridge.pending_connections.discard(self)+ if self._prefix_timeout is not None:+ self._prefix_timeout.cancel()+ if data.startswith(b"GET "):+ super().connection_made(self.transport)+ else:+ # Incomplete headers retain their own short deadline. A parsed+ # request receives the longer bounded upload budget below.+ self._prefix_timeout = asyncio.get_running_loop().call_later(+ _HTTP_HEADER_TIMEOUT_S, self.transport.close,+ )+ self._http_protocol = self._bridge.http_server()+ self._http_protocol.connection_made(self.transport)+ if self._http_protocol is not None:+ self._http_protocol.data_received(data)+ else:+ super().data_received(data)++ def request_started(self) -> None:+ if self._prefix_timeout is not None:+ self._prefix_timeout.cancel()+ self._prefix_timeout = asyncio.get_running_loop().call_later(+ _HTTP_CONNECTION_TIMEOUT_S, self.transport.close,+ )++ def eof_received(self) -> None:+ if self._http_protocol is not None:+ return self._http_protocol.eof_received()+ if self._selected:+ return super().eof_received()+ return None++ def connection_lost(self, exc: Exception | None) -> None:+ self._bridge.pending_connections.discard(self)+ if self._prefix_timeout is not None:+ self._prefix_timeout.cancel()+ if self._http_protocol is not None:+ self._http_protocol.connection_lost(exc)+ elif self._selected:+ super().connection_lost(exc)++ def pause_writing(self) -> None:+ if self._http_protocol is not None:+ self._http_protocol.pause_writing()+ elif self._selected:+ super().pause_writing()++ def resume_writing(self) -> None:+ if self._http_protocol is not None:+ self._http_protocol.resume_writing()+ elif self._selected:+ super().resume_writing()diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.pyindex e9207b911..e70069b21 100644--- a/nanobot/channels/websocket/runtime.py+++ b/nanobot/channels/websocket/runtime.py@@ -27,6 +27,7 @@ from nanobot.bus.events import ()from nanobot.bus.queue import MessageBusfrom nanobot.channels.base import BaseChannel+from nanobot.channels.websocket.binary_http import BinaryHTTPBridgefrom nanobot.config.schema import Basefrom nanobot.session.webui_turns import (clear_websocket_turn_if_current,@@ -207,10 +208,8 @@ class WebSocketConfig(Base):websocket_requires_token: bool = Trueallow_from: list[str] = Field(default_factory=lambda: ["*"])streaming: bool = True- # Default 36 MB, upper 40 MB: supports up to 4 images at ~6 MB each after- # client-side Worker normalization (see webui Composer). 4 × 6 MB × 1.37- # (base64 overhead) + envelope framing stays under 36 MB; the 40 MB ceiling- # leaves a small margin for sender slop without opening a DoS avenue.+ # Keep the existing configurable guard (also used for non-attachment+ # frames and older clients). HTTP attachments are outside this limit.max_message_bytes: int = Field(default=37_748_736, ge=1024, le=41_943_040)ping_interval_s: float = Field(default=20.0, ge=5.0, le=300.0)ping_timeout_s: float = Field(default=20.0, ge=5.0, le=300.0)@@ -394,6 +393,7 @@ class WebSocketChannel(BaseChannel):self.gateway = gatewayself._media = gateway.media+ self._uploads = gateway.uploadsself._transcripts = gateway.transcriptsself._temporary_chats = gateway.temporary_chatsself._session_projection = gateway.session_projection@@ -509,6 +509,7 @@ class WebSocketChannel(BaseChannel):async def _cleanup_connection(self, connection: ServerConnection) -> None:"""Remove *connection* from every subscription set; safe to call multiple times."""self._retired_connections.add(connection)+ self._uploads.revoke(connection)state = self._connection_outbound.get(connection)if state is not None:state.closing = True@@ -697,6 +698,18 @@ class WebSocketChannel(BaseChannel):async def handler(connection: ServerConnection) -> None:await self._connection_loop(connection)+ bridge = BinaryHTTPBridge(self._uploads.handle)++ async def prune_uploads() -> None:+ while not stop_event.is_set():+ self._uploads.store.prune()+ try:+ await asyncio.wait_for(stop_event.wait(), timeout=30)+ except TimeoutError:+ pass++ prune_task = asyncio.create_task(prune_uploads())+async def runner() -> None:socket_path = self.config.unix_socket_pathfailures = 0@@ -714,6 +727,7 @@ class WebSocketChannel(BaseChannel):handler,socket_path,process_request=process_request,+ create_connection=bridge.connection_factory,open_timeout=_WEBUI_HTTP_OPEN_TIMEOUT_S,max_size=self.config.max_message_bytes,ping_interval=self.config.ping_interval_s,@@ -728,6 +742,7 @@ class WebSocketChannel(BaseChannel):self.config.host,self.config.port,process_request=process_request,+ create_connection=bridge.connection_factory,open_timeout=_WEBUI_HTTP_OPEN_TIMEOUT_S,max_size=self.config.max_message_bytes,ping_interval=self.config.ping_interval_s,@@ -788,6 +803,10 @@ class WebSocketChannel(BaseChannel):try:await taskfinally:+ prune_task.cancel()+ await asyncio.gather(prune_task, return_exceptions=True)+ await bridge.shutdown()+ self._uploads.store.clear()self._running = Falseif self._server_task is task:self._server_task = None@@ -815,6 +834,8 @@ class WebSocketChannel(BaseChannel):"event": "ready","chat_id": default_chat_id,"client_id": client_id,+ **({"upload": self._uploads.issue(connection)}+ if self.is_allowed(client_id) else {}),**({"terminal": gateway_identity(self.gateway.tokens.instance_id)}if _query_first(query, "terminal_protocol") == "1" else {}),},diff --git a/nanobot/channels/websocket/tests/test_attachment_ingress.py b/nanobot/channels/websocket/tests/test_attachment_ingress.pynew file mode 100644index 000000000..3658999e3--- /dev/null+++ b/nanobot/channels/websocket/tests/test_attachment_ingress.py@@ -0,0 +1,178 @@+"""Production listener regressions for HTTP upload + small WS references."""+import asyncio+import json+from pathlib import Path++import aiohttp+import pytest+from websockets.asyncio.client import connect++from nanobot.bus.queue import MessageBus+from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig+from nanobot.session.manager import SessionManager+from nanobot.webui.gateway_services import build_gateway_services+++async def gateway(tmp_path, monkeypatch):+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ bus = MessageBus()+ config = WebSocketConfig(port=0, path="/ws", token="test-secret", max_message_bytes=1048576)+ services = build_gateway_services(+ config=config, bus=bus, session_manager=SessionManager(tmp_path),+ static_dist_path=None, workspace_path=tmp_path,+ default_restrict_to_workspace=True, runtime_model_name=None,+ runtime_surface="browser", runtime_capabilities_overrides=None,+ config_path=tmp_path / "config.json",+ )+ channel = WebSocketChannel(config, bus, gateway=services)+ task = asyncio.create_task(channel.start())+ try:+ async with asyncio.timeout(10):+ while channel._server is None:+ if task.done():+ await task+ await asyncio.sleep(.01)+ port = channel._server.sockets[0].getsockname()[1]+ yield channel, bus, f"http://127.0.0.1:{port}", f"ws://127.0.0.1:{port}/ws?token=test-secret"+ finally:+ await channel.stop()+ await task+++async def event(ws, name):+ async with asyncio.timeout(5):+ while True:+ payload = json.loads(await ws.recv())+ if payload["event"] == name:+ return payload++[email protected]("mime,name", [+ ("image/png", "image.png"), ("text/csv", "report.csv"), ("video/webm", "clip.webm"),+])+async def test_real_listener_large_binary_and_reference_delivery(gateway, mime, name):+ channel, bus, http_url, ws_url = gateway+ raw = b"x" * 1_453_245+ async with connect(ws_url) as ws, aiohttp.ClientSession() as http:+ ready = await event(ws, "ready")+ capability = ready["upload"]+ headers = {"Authorization": f"Bearer {capability['token']}", "Content-Type": mime,+ "X-Attachment-Name": name}+ async with http.post(http_url + capability["path"], data=raw, headers=headers, expect100=True) as response:+ assert response.status == 201, await response.text()+ reference = (await response.json())["reference"]+ frame = {"type": "message", "chat_id": ready["chat_id"], "content": "look",+ "webui": True, "turn_id": "binary-turn",+ "media": [{"reference": reference, "name": name}]}+ assert len(json.dumps(frame)) < 1024+ await ws.send(json.dumps(frame))+ assert (await event(ws, "message_accepted"))["turn_id"] == "binary-turn"+ inbound = await asyncio.wait_for(bus.consume_inbound(), 2)+ path = Path(inbound.media[0])+ assert path.read_bytes() == raw+ assert path.parent == channel.gateway.uploads.store.media_dir+ # Lost ACK retry must not resolve a consumed reference or dispatch twice.+ await ws.send(json.dumps(frame))+ await event(ws, "message_accepted")+ with pytest.raises(TimeoutError):+ await asyncio.wait_for(bus.consume_inbound(), .03)+ channel.gateway.uploads.store.clear()+ assert path.exists()+++async def test_capability_is_required_owner_scoped_and_revoked(gateway):+ channel, _, http_url, ws_url = gateway+ async with aiohttp.ClientSession() as http:+ for token in ("", "test-secret", "client-selected-id"):+ async with http.post(http_url + "/api/attachments", data=b"secret",+ headers={"Authorization": f"Bearer {token}", "Content-Type": "text/plain"}) as response:+ assert response.status == 401+ async with connect(ws_url) as owner, connect(ws_url) as other:+ capability = (await event(owner, "ready"))["upload"]+ other_ready = await event(other, "ready")+ headers = {"Authorization": f"Bearer {capability['token']}", "Content-Type": "image/png"}+ async with http.post(http_url + capability["path"], data=b"image", headers=headers) as response:+ reference = (await response.json())["reference"]+ await other.send(json.dumps({"type": "message", "chat_id": other_ready["chat_id"],+ "content": "steal", "media": [{"reference": reference}], "turn_id": "foreign"}))+ assert (await event(other, "error"))["detail"] == "attachment_rejected"+ async with asyncio.timeout(5):+ while capability["token"] in channel.gateway.uploads._tokens:+ await asyncio.sleep(.01)+ async with http.post(http_url + capability["path"], data=b"image", headers=headers) as response:+ assert response.status == 401+++async def test_inline_payload_rejected_and_failed_validation_keeps_upload(gateway):+ channel, bus, http_url, ws_url = gateway+ async with connect(ws_url) as ws, aiohttp.ClientSession() as http:+ ready = await event(ws, "ready")+ capability = ready["upload"]+ frame = {"type": "message", "chat_id": ready["chat_id"], "content": "look",+ "webui": True, "turn_id": "retry-turn", "media": [{"data_url": "data:image/png;base64,eA=="}]}+ await ws.send(json.dumps(frame))+ assert (await event(ws, "error"))["detail"] == "attachment_rejected"+ headers = {"Authorization": f"Bearer {capability['token']}", "Content-Type": "image/png"}+ async with http.post(http_url + capability["path"], data=b"image", headers=headers) as response:+ reference = (await response.json())["reference"]+ frame["media"] = [{"reference": reference}, {"reference": "invalid"}]+ await ws.send(json.dumps(frame))+ await event(ws, "error")+ frame["media"] = [{"reference": reference}]+ await ws.send(json.dumps(frame))+ await event(ws, "message_accepted")+ assert (await bus.consume_inbound()).media+++[email protected]("mime,body", [+ ("image/svg+xml", b"<svg/>"), ("text/javascript", b"alert(1)"),+ ("image/png", b""), ("image/png", b"x" * (6 * 1024 * 1024 + 1)),+], ids=["svg", "javascript", "empty", "oversized"])+async def test_http_policy_rejection_does_not_leave_files(gateway, mime, body):+ channel, _, http_url, ws_url = gateway+ async with connect(ws_url) as ws, aiohttp.ClientSession() as http:+ capability = (await event(ws, "ready"))["upload"]+ async with http.post(http_url + capability["path"], data=body,+ headers={"Authorization": f"Bearer {capability['token']}", "Content-Type": mime},+ expect100=True,+ ) as response:+ assert response.status == 400+ assert not [p for p in channel.gateway.uploads.store.media_dir.rglob("*") if p.is_file()]+++async def test_one_shot_handshake_token_is_not_an_upload_credential(gateway):+ channel, _, http_url, _ = gateway+ # Use the same one-shot token registry as the bootstrap endpoint.+ issued = channel.gateway.tokens.issue_token(60, audience="webui")+ ws_url = http_url.replace("http://", "ws://") + "/ws?token=" + issued+ async with connect(ws_url) as ws, aiohttp.ClientSession() as http:+ capability = (await event(ws, "ready"))["upload"]+ assert issued not in channel.gateway.tokens.issued_tokens+ for token, expected in [(issued, 401), (capability["token"], 201)]:+ async with http.post(http_url + capability["path"], data=b"binary",+ headers={"Authorization": f"Bearer {token}", "Content-Type": "image/png"},+ ) as response:+ assert response.status == expected+++async def test_stalled_upload_reports_timeout_and_keeps_connection_retryable(gateway):+ channel, _, http_url, ws_url = gateway+ channel.gateway.uploads.store.upload_idle_timeout = .05++ async def stalled():+ yield b"x"+ await asyncio.sleep(.15)+ yield b"y"++ async with connect(ws_url) as ws, aiohttp.ClientSession() as http:+ capability = (await event(ws, "ready"))["upload"]+ headers = {"Authorization": f"Bearer {capability['token']}",+ "Content-Type": "image/png", "Content-Length": "2"}+ async with http.post(http_url + capability["path"], data=stalled(), headers=headers) as response:+ assert response.status == 400+ assert (await response.json())["error"] == "Attachment upload timed out"+ assert not [p for p in channel.gateway.uploads.store.media_dir.rglob("*") if p.is_file()]+ async with http.post(http_url + capability["path"], data=b"xy", headers=headers) as response:+ assert response.status == 201diff --git a/nanobot/channels/websocket/tests/test_attachment_store.py b/nanobot/channels/websocket/tests/test_attachment_store.pynew file mode 100644index 000000000..2ff2dfc27--- /dev/null+++ b/nanobot/channels/websocket/tests/test_attachment_store.py@@ -0,0 +1,257 @@+"""Binary staging regressions; these do not exercise the gateway HTTP listener."""++import asyncio+import re+from pathlib import Path++import pytest++from nanobot.channels.websocket.attachment_policy import AttachmentIngressLimits+from nanobot.channels.websocket.attachment_store import AttachmentStore, AttachmentUploadError+from nanobot.utils.media_decode import save_base64_data_url+++async def chunks(raw: bytes):+ for offset in range(0, len(raw), 65536):+ yield raw[offset:offset + 65536]+++async def upload(store, raw=b"attachment", owner="owner", mime="image/png", **kwargs):+ return await store.upload(chunks(raw), owner=owner, mime=mime, size=len(raw), **kwargs)+++async def test_binary_larger_than_websocket_limit_preserves_layout(tmp_path):+ raw = b"x" * (1024 * 1024 + 1)+ store = AttachmentStore(tmp_path)+ ref = await upload(store, raw)+ assert len(ref) < 100+ paths = store.resolve([ref], owner="owner")+ assert re.fullmatch(r"[0-9a-f]{12}\.png", Path(paths[0]).name)+ assert Path(paths[0]).read_bytes() == raw+ assert store.resolve([ref], owner="owner") == paths # a failed send is retryable+ assert store.commit([ref], owner="owner") == paths+ store.clear()+ assert Path(paths[0]).read_bytes() == raw # cleanup must not delete session media+ with pytest.raises(AttachmentUploadError):+ store.resolve([ref], owner="owner")++[email protected]("mime,filename,pattern", [+ ("application/pdf", "../../report.pdf", r"[0-9a-f]{12}_.+\.pdf"),+ ("video/webm", "ignored.webm", r"[0-9a-f]{12}\.webm"),+ ("text/markdown", "notes.md", r"[0-9a-f]{12}_notes\.md"),+])+async def test_document_and_video_layout_matches_legacy(tmp_path, mime, filename, pattern):+ store = AttachmentStore(tmp_path)+ ref = await upload(store, mime=mime, filename=filename)+ path = Path(store.resolve([ref], owner="owner")[0])+ assert path.parent == tmp_path+ assert re.fullmatch(pattern, path.name)+ import base64+ legacy = save_base64_data_url(+ f"data:{mime};base64," + base64.b64encode(b"attachment").decode(), tmp_path,+ filename=filename if mime != "video/webm" else None,+ )+ assert legacy is not None+ assert path.name[12:] == Path(legacy).name[12:]+++async def test_ownership_invalid_and_duplicate_refs_are_atomic(tmp_path):+ store = AttachmentStore(tmp_path)+ ref = await upload(store)+ for references, owner in [([ref], "other"), ([ref, "unknown"], "owner"),+ ([ref, ref], "owner"), (["../../file"], "owner")]:+ with pytest.raises(AttachmentUploadError):+ store.commit(references, owner=owner)+ assert len(store.resolve([ref], owner="owner")) == 1++[email protected]("size,raw", [(4, b"12345"), (6, b"12345")])+async def test_body_length_failure_cleans_file_and_capacity(tmp_path, size, raw):+ store = AttachmentStore(tmp_path, max_pending=1, max_pending_bytes=6)+ with pytest.raises(AttachmentUploadError):+ await store.upload(chunks(raw), owner="owner", mime="image/png", size=size)+ assert not [path for path in tmp_path.rglob("*") if path.is_file()]+ assert await upload(store, b"123456")+++async def test_reject_metadata_before_reading_body(tmp_path):+ store = AttachmentStore(tmp_path)++ async def unread():+ pytest.fail("Rejected request body was read")+ yield b""++ for owner, mime, size in [("", "image/png", 1), ("owner", "text/javascript", 1),+ ("owner", "image/png", 7 * 1024 * 1024),+ ("owner", "image/png", 0)]:+ with pytest.raises(AttachmentUploadError):+ await store.upload(unread(), owner=owner, mime=mime, size=size)+ assert not [path for path in tmp_path.rglob("*") if path.is_file()]+++async def test_inflight_capacity_and_cancellation(tmp_path):+ store = AttachmentStore(tmp_path, max_pending_bytes=10)+ entered = asyncio.Event()++ async def slow():+ entered.set()+ await asyncio.Event().wait()+ yield b"123456"++ task = asyncio.create_task(store.upload(slow(), owner="owner", mime="image/png", size=6))+ await entered.wait()+ with pytest.raises(AttachmentUploadError, match="storage is full"):+ await upload(store, b"12345")+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert not [path for path in tmp_path.rglob("*") if path.is_file()]+ assert await upload(store, b"1234567890")+++async def test_timeout_cleans_partial_upload(tmp_path):+ store = AttachmentStore(tmp_path, upload_timeout=0.01)++ async def slow():+ yield b"1"+ await asyncio.Event().wait()++ with pytest.raises(TimeoutError):+ await store.upload(slow(), owner="owner", mime="image/png", size=2)+ assert not [path for path in tmp_path.rglob("*") if path.is_file()]+++async def test_progressing_upload_can_outlast_idle_timeout(tmp_path):+ store = AttachmentStore(tmp_path, upload_timeout=1, upload_idle_timeout=.1)++ async def slow():+ for _ in range(3):+ await asyncio.sleep(.05)+ yield b"x"++ ref = await store.upload(slow(), owner="owner", mime="image/png", size=3)+ assert Path(store.commit([ref], owner="owner")[0]).read_bytes() == b"xxx"+++async def test_stalled_upload_releases_file_and_capacity(tmp_path):+ store = AttachmentStore(+ tmp_path, upload_timeout=1, upload_idle_timeout=.01,+ max_pending=1, max_pending_bytes=2,+ )++ async def stalled():+ yield b"x"+ await asyncio.Event().wait()++ with pytest.raises(TimeoutError):+ await store.upload(stalled(), owner="owner", mime="image/png", size=2)+ assert not [path for path in tmp_path.rglob("*") if path.is_file()]+ assert await upload(store, b"xx")+++async def test_expiry_cleans_only_staged_files(tmp_path, monkeypatch):+ import nanobot.channels.websocket.attachment_store as module+ monkeypatch.setattr(module.time, "monotonic", lambda: 100)+ store = AttachmentStore(tmp_path, ttl_seconds=10)+ committed = await upload(store)+ staged = await upload(store)+ keep = Path(store.commit([committed], owner="owner")[0])+ remove = Path(store.resolve([staged], owner="owner")[0])+ monkeypatch.setattr(module.time, "monotonic", lambda: 111)+ store.prune()+ assert keep.exists()+ assert not remove.exists()+ with pytest.raises(AttachmentUploadError):+ store.resolve([staged], owner="owner")+++async def test_batch_limits_leave_all_references_retryable(tmp_path):+ store = AttachmentStore(tmp_path, limits=AttachmentIngressLimits(+ max_count=2, max_file_bytes=10, max_total_bytes=10,+ ))+ refs = [await upload(store, b"123456") for _ in range(2)]+ with pytest.raises(AttachmentUploadError, match="total"):+ store.commit(refs, owner="owner")+ for ref in refs:+ assert store.resolve([ref], owner="owner")+ videos = [await upload(store, mime="video/mp4") for _ in range(2)]+ with pytest.raises(AttachmentUploadError, match="Too many"):+ store.resolve(videos, owner="owner")+ store.clear()+ assert not [path for path in tmp_path.rglob("*") if path.is_file()]+++async def test_filename_collision_never_unlinks_existing_file(tmp_path, monkeypatch):+ import nanobot.channels.websocket.attachment_store as module+ existing = tmp_path / "existing.png"+ existing.write_bytes(b"keep")+ monkeypatch.setattr(module, "media_destination", lambda *args, **kwargs: existing)+ with pytest.raises(FileExistsError):+ await upload(AttachmentStore(tmp_path))+ assert existing.read_bytes() == b"keep"+++async def test_committed_paths_persist_and_replay_without_reference_format(tmp_path):+ from nanobot.session.manager import SessionManager++ store = AttachmentStore(tmp_path / "media")+ reference = await upload(store)+ paths = store.commit([reference], owner="owner")+ manager = SessionManager(tmp_path / "workspace")+ session = manager.get_or_create("websocket:binary-upload")+ session.add_message("user", "look", media=paths)+ manager.save(session)++ replay_manager = SessionManager(tmp_path / "workspace")+ replay = replay_manager.get_or_create("websocket:binary-upload")+ assert replay.messages[0]["media"] == paths+ assert reference not in str(replay.messages)+ assert replay.get_history()[0] == {+ "role": "user", "content": f"look\n[image: {paths[0]}]",+ }+ store.clear()+ assert Path(paths[0]).exists()+++async def test_restart_prunes_crash_remnants_but_not_committed_media(tmp_path, monkeypatch):+ import os+ import time++ first = AttachmentStore(tmp_path)+ committed = await upload(first)+ keep = Path(first.commit([committed], owner="owner")[0])+ abandoned = await upload(first)+ remove = Path(first.resolve([abandoned], owner="owner")[0])+ marker = tmp_path / ".pending-attachments" / remove.name+ old = time.time() - first.ttl_seconds - first.upload_timeout - 1+ os.utime(marker, (old, old))+ restarted = AttachmentStore(tmp_path)+ restarted.prune()+ assert not remove.exists()+ assert not marker.exists()+ assert keep.read_bytes() == b"attachment"+++async def test_disconnect_releases_staged_capacity_but_preserves_commits(tmp_path):+ store = AttachmentStore(tmp_path, max_pending=1)+ ref = await upload(store)+ keep = Path(store.commit([ref], owner="owner")[0])+ ref = await upload(store)+ remove = Path(store.resolve([ref], owner="owner")[0])+ store.discard_owner("owner")+ assert not remove.exists()+ assert keep.exists()+ assert await upload(store)+++async def test_filename_collision_preserves_another_uploads_crash_marker(tmp_path, monkeypatch):+ store = AttachmentStore(tmp_path)+ ref = await upload(store)+ path = Path(store.resolve([ref], owner="owner")[0])+ monkeypatch.setattr("nanobot.channels.websocket.attachment_store.media_destination", lambda *args, **kwargs: path)+ with pytest.raises(FileExistsError):+ await upload(store)+ assert (tmp_path / ".pending-attachments" / path.name).exists()+ assert path.read_bytes() == b"attachment"+ store.clear()diff --git a/nanobot/channels/websocket/tests/test_binary_http.py b/nanobot/channels/websocket/tests/test_binary_http.pynew file mode 100644index 000000000..2dfccf3d4--- /dev/null+++ b/nanobot/channels/websocket/tests/test_binary_http.py@@ -0,0 +1,238 @@+"""Real socket regressions for body-capable HTTP beside bounded WebSockets."""++import asyncio++import aiohttp+import pytest+from aiohttp import web+from websockets.asyncio.client import connect+from websockets.asyncio.server import serve++from nanobot.channels.websocket.attachment_store import AttachmentStore+from nanobot.channels.websocket.binary_http import BinaryHTTPBridge+++async def test_binary_body_exceeds_ws_frame_limit_without_changing_ws(tmp_path):+ store = AttachmentStore(tmp_path)++ async def upload(request):+ if request.headers.get("Authorization") != "Bearer isolated-test":+ return web.json_response({"error": "Unauthorized"}, status=401)+ if request.method != "POST" or request.path != "/api/attachments":+ return web.Response(status=404)+ if request.content_length is None or request.headers.get("Content-Encoding"):+ return web.Response(status=400)+ ref = await store.upload(+ request.content.iter_chunked(65536), owner="authenticated-owner",+ mime=request.content_type, size=request.content_length,+ )+ return web.json_response({"ref": ref})++ async def echo(connection):+ async for message in connection:+ await connection.send(message)++ bridge = BinaryHTTPBridge(upload)+ server = await serve(echo, "127.0.0.1", 0, max_size=1024 * 1024,+ create_connection=bridge.connection_factory)+ port = server.sockets[0].getsockname()[1]+ body = b"x" * 1_453_245+ try:+ async with aiohttp.ClientSession() as client:+ async with client.post(f"http://127.0.0.1:{port}/api/attachments", data=body,+ headers={"Content-Type": "image/png"}) as response:+ assert response.status == 401+ assert not list(tmp_path.iterdir())+ async with client.post(f"http://127.0.0.1:{port}/api/attachments", data=body,+ headers={"Content-Type": "image/png",+ "Authorization": "Bearer isolated-test"}) as response:+ assert response.status == 200+ ref = (await response.json())["ref"]+ paths = store.resolve([ref], owner="authenticated-owner")+ assert len(paths) == 1+ assert (tmp_path / paths[0]).read_bytes() == body+ async with connect(f"ws://127.0.0.1:{port}/") as ws:+ await ws.send(ref)+ assert await ws.recv() == ref+ await ws.send(body)+ await ws.wait_closed()+ assert ws.close_code == 1009+ finally:+ server.close()+ await server.wait_closed()+ await bridge.shutdown()+ store.clear()+++async def test_fragmented_method_and_shutdown_of_undecided_connection():+ async def upload(request):+ return web.Response(body=await request.read())++ async def echo(connection):+ async for message in connection:+ await connection.send(message)++ bridge = BinaryHTTPBridge(upload)+ server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)+ port = server.sockets[0].getsockname()[1]+ reader, writer = await asyncio.open_connection("127.0.0.1", port)+ try:+ for fragment in (b"P", b"O", b"S", b"T / HTTP/1.1\r\nHost: localhost\r\n",+ b"Content-Length: 4\r\nConnection: close\r\n\r\ntest"):+ writer.write(fragment)+ await writer.drain()+ await asyncio.sleep(0)+ response = await asyncio.wait_for(reader.read(), 2)+ assert b"200 OK" in response+ assert response.endswith(b"test")+ idle_reader, idle_writer = await asyncio.open_connection("127.0.0.1", port)+ idle_writer.write(b"P")+ await idle_writer.drain()+ await asyncio.sleep(0.01)+ server.close()+ await server.wait_closed()+ await bridge.shutdown()+ assert await asyncio.wait_for(idle_reader.read(), 2) == b""+ idle_writer.close()+ await idle_writer.wait_closed()+ finally:+ writer.close()+ await writer.wait_closed()+ server.close()+ await server.wait_closed()+ await bridge.shutdown()++[email protected]("headers", [+ b"Content-Length: 4\r\nTransfer-Encoding: chunked\r\n",+ b"Content-Length: 4\r\nContent-Length: 5\r\n",+ b"Content-Length: -1\r\n",+])+async def test_ambiguous_http_framing_is_rejected_before_handler(headers):+ calls = []++ async def upload(request):+ calls.append(request)+ return web.Response(status=200)++ async def echo(connection):+ await connection.wait_closed()++ bridge = BinaryHTTPBridge(upload)+ server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)+ port = server.sockets[0].getsockname()[1]+ reader, writer = await asyncio.open_connection("127.0.0.1", port)+ try:+ writer.write(b"POST / HTTP/1.1\r\nHost: localhost\r\n" + headers+ + b"Connection: close\r\n\r\ntest")+ await writer.drain()+ response = await asyncio.wait_for(reader.read(), 2)+ assert b"400 Bad Request" in response+ assert calls == []+ finally:+ writer.close()+ await writer.wait_closed()+ server.close()+ await server.wait_closed()+ await bridge.shutdown()+++async def test_request_body_is_not_automatically_decompressed():+ import gzip++ body = gzip.compress(b"x" * 2_000_000)+ received = []++ async def upload(request):+ received.append(await request.read())+ return web.Response(status=204)++ async def echo(connection):+ await connection.wait_closed()++ bridge = BinaryHTTPBridge(upload)+ server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)+ port = server.sockets[0].getsockname()[1]+ try:+ async with aiohttp.ClientSession() as client:+ async with client.post(f"http://127.0.0.1:{port}/", data=body,+ headers={"Content-Encoding": "gzip"}) as response:+ assert response.status == 204+ assert received == [body]+ finally:+ server.close()+ await server.wait_closed()+ await bridge.shutdown()+++async def test_incomplete_http_headers_have_a_deadline(monkeypatch):+ monkeypatch.setattr("nanobot.channels.websocket.binary_http._HTTP_HEADER_TIMEOUT_S", .05)++ async def upload(request):+ pytest.fail("Incomplete headers must not invoke the upload handler")++ async def echo(connection):+ await connection.wait_closed()++ bridge = BinaryHTTPBridge(upload)+ server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)+ port = server.sockets[0].getsockname()[1]+ reader, writer = await asyncio.open_connection("127.0.0.1", port)+ try:+ writer.write(b"POST /api/attachments HTTP/1.1\r\nHost: localhost\r\n")+ await writer.drain()+ assert await asyncio.wait_for(reader.read(), 2) == b""+ finally:+ writer.close()+ await writer.wait_closed()+ server.close()+ await server.wait_closed()+ await bridge.shutdown()+++async def test_parsed_request_outlasts_header_deadline(tmp_path, monkeypatch):+ monkeypatch.setattr("nanobot.channels.websocket.binary_http._HTTP_HEADER_TIMEOUT_S", .1)+ monkeypatch.setattr("nanobot.channels.websocket.binary_http._HTTP_CONNECTION_TIMEOUT_S", 1)+ store = AttachmentStore(tmp_path, upload_timeout=1, upload_idle_timeout=.1)+ started = asyncio.Event()++ async def upload(request):+ started.set()+ ref = await store.upload(+ request.content.iter_chunked(65536), owner="owner", mime="image/png", size=3,+ )+ response = web.json_response({"ref": ref})+ response.force_close()+ return response++ async def echo(connection):+ await connection.wait_closed()++ bridge = BinaryHTTPBridge(upload)+ server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)+ port = server.sockets[0].getsockname()[1]+ reader, writer = await asyncio.open_connection("127.0.0.1", port)+ try:+ writer.write(b"POST /api/attachments HTTP/1.1\r\nHost: localhost\r\nContent-Length: 3\r\n\r\n")+ await writer.drain()+ await asyncio.wait_for(started.wait(), 1)+ for _ in range(3):+ await asyncio.sleep(.05)+ writer.write(b"x")+ await writer.drain()+ response = await asyncio.wait_for(reader.read(), 1)+ assert b"200 OK" in response+ assert [p.read_bytes() for p in tmp_path.glob("*.png")] == [b"xxx"]+ finally:+ writer.close()+ await writer.wait_closed()+ server.close()+ await server.wait_closed()+ await bridge.shutdown()+ store.clear()diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.pyindex c1f6da937..0a2e38c6f 100644--- a/nanobot/channels/websocket/tests/test_websocket_channel.py+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py@@ -418,9 +418,8 @@ async def test_temporary_chat_is_transient_and_discarded(bus, tmp_path) -> None:chat_id = await _new_temporary_chat(channel, connection)upload = tmp_path / "temporary-upload.txt"upload.write_text("private attachment", encoding="utf-8")- channel.gateway.media.store_inbound_attachments = MagicMock(- return_value=([str(upload)], None),- )+ channel.gateway.uploads.store.resolve = MagicMock(return_value=[str(upload)])+ channel.gateway.uploads.store.commit = MagicMock(return_value=[str(upload)])await channel._dispatch_envelope(connection,@@ -429,7 +428,7 @@ async def test_temporary_chat_is_transient_and_discarded(bus, tmp_path) -> None:"type": "message","chat_id": chat_id,"content": "read this",- "media": [{"data_url": "data:text/plain;base64,cHJpdmF0ZQ=="}],+ "media": [{"reference": "temporary-upload"}],"cli_apps": [{"name": "drawio"}],"workspace_scope": {"project_path": str(selected_project),diff --git a/nanobot/channels/websocket/tests/test_websocket_envelope_media.py b/nanobot/channels/websocket/tests/test_websocket_envelope_media.pyindex 44a15b91a..157b92413 100644--- a/nanobot/channels/websocket/tests/test_websocket_envelope_media.py+++ b/nanobot/channels/websocket/tests/test_websocket_envelope_media.py@@ -1,14 +1,7 @@-"""Tests for WS envelope media handling (client attachment upload path).--Exercises ``WebSocketChannel._dispatch_envelope`` for the ``message`` branch:-decoding base64 data URLs, rejecting malformed / oversized / non-whitelisted-payloads, preserving backward compatibility with media-less frames, and-forwarding saved paths to ``_handle_message``.-"""+"""WS envelope regressions; binary ingress is tested through the HTTP listener."""from __future__ import annotations-import base64import jsonfrom pathlib import Pathfrom unittest.mock import AsyncMock, MagicMock, patch@@ -26,22 +19,6 @@ from nanobot.session.session_handles import SessionHandleResolverfrom nanobot.webui.gateway_services import build_gateway_services-def _tiny_png_data_url() -> str:- """A 1-pixel PNG prefixed as a data URL — just enough for magic-bytes sniffing."""- # 1x1 transparent PNG- png = (- b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00"- b"\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx"- b"\x9cc\xf8\xcf\xc0\x00\x00\x00\x03\x00\x01\x00\x18\xdd\x8d\xb4\x00"- b"\x00\x00\x00IEND\xaeB`\x82"- )- return f"data:image/png;base64,{base64.b64encode(png).decode()}"---def _data_url(mime: str, payload: bytes) -> str:- return f"data:{mime};base64,{base64.b64encode(payload).decode()}"--def _make_channel(session_manager: SessionManager | None = None) -> WebSocketChannel:bus = MagicMock()bus.publish_inbound = AsyncMock()@@ -76,24 +53,18 @@ def isolate_websocket_turn_state() -> None:wth._WEBSOCKET_TURN_OWNERS.clear()-# -- max_message_bytes bump -------------------------------------------------------def test_max_message_bytes_default_supports_multi_image_frame() -> None:- """Default 36 MB must comfortably hold 4 × 6 MB base64-encoded images."""+def test_max_message_bytes_keeps_existing_transport_guard() -> None:+ """Moving attachments to HTTP does not disable the configurable WS guard."""from nanobot.channels.websocket.runtime import WebSocketConfigdefault = WebSocketConfig().max_message_bytes- # 4 images × 6 MB × 1.37 base64 overhead ≈ 33 MB- assert default >= 33 * 1024 * 1024- # Upper bound 40 MB matches plan+ assert default == 36 * 1024 * 1024+ assert WebSocketConfig(max_message_bytes=1048576).max_message_bytes == 1048576+ # The existing upper bound remains 40 MB.with pytest.raises(Exception):WebSocketConfig(max_message_bytes=41_943_040 + 1)-# -- _dispatch_envelope message branch + media ----------------------------------@pytest.mark.asyncioasync def test_message_without_media_backward_compatible() -> None:"""Existing clients that don't send ``media`` keep working unchanged."""@@ -136,41 +107,6 @@ async def test_webui_message_acceptance_echoes_turn_id() -> None:}-async def test_webui_message_projects_attachments_to_other_clients(tmp_path: Path) -> None:- channel = _make_channel()- origin = AsyncMock()- peer = AsyncMock()- channel._attach(origin, "abc123")- channel._attach(peer, "abc123")- channel._webui_connections.add(origin)- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "please inspect @drawio",- "webui": True,- "turn_id": "turn-shared",- "media": [{"data_url": _tiny_png_data_url(), "name": "shot.png"}],- "cli_apps": [{"name": "DrawIO", "entry_point": "cli-anything-drawio"}],- }-- with patch("nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path):- await channel._dispatch_envelope(origin, "client-1", envelope)-- event = json.loads(peer.send.await_args.args[0])- assert event["event"] == "user_message"- assert event["turn_id"] == "turn-shared"- assert event["text"] == "please inspect @drawio"- assert event["cli_apps"] == [{- "name": "drawio",- "entry_point": "cli-anything-drawio",- }]- assert event["media_urls"][0]["kind"] == "image"- assert event["media_urls"][0]["name"] == "shot.png"- assert event["media_urls"][0]["url"].startswith("/api/media/")- assert json.loads(origin.send.await_args.args[0])["event"] == "message_accepted"--@pytest.mark.asyncioasync def test_message_text_policy_is_independent_from_transport_limit() -> None:channel = _make_channel()@@ -270,281 +206,6 @@ async def test_webui_message_forwards_verified_session_mentions(tmp_path) -> Nonassert "websocket:pricing" in block.content-async def test_message_with_single_image_forwards_saved_path(tmp_path) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "look at this",- "media": [{"data_url": _tiny_png_data_url(), "name": "shot.png"}],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_awaited_once()- paths = channel._handle_message.call_args.kwargs["media"]- assert isinstance(paths, list) and len(paths) == 1- saved = Path(paths[0])- assert saved.exists()- assert saved.suffix == ".png"- assert saved.is_relative_to(tmp_path)---async def test_message_with_multiple_images(tmp_path) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "a couple",- "media": [- {"data_url": _tiny_png_data_url()},- {"data_url": _tiny_png_data_url()},- {"data_url": _tiny_png_data_url()},- ],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- paths = channel._handle_message.call_args.kwargs["media"]- assert len(paths) == 3- # Saved filenames must be unique.- assert len({Path(p).name for p in paths}) == 3---async def test_image_only_message_allows_empty_text(tmp_path) -> None:- """When media is attached, empty text is acceptable."""- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "",- "media": [{"data_url": _tiny_png_data_url()}],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_awaited_once()- # Error event NOT sent.- mock_conn.send.assert_not_awaited()---async def test_message_rejected_when_more_than_four_images(tmp_path) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "hi",- "media": [{"data_url": _tiny_png_data_url()}] * 5,- "turn_id": "turn-attachments",- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_not_awaited()- mock_conn.send.assert_awaited_once()- err = json.loads(mock_conn.send.call_args[0][0])- assert err["event"] == "error"- assert err["chat_id"] == "abc123"- assert err["detail"] == "attachment_rejected"- assert err["reason"] == "too_many_images"- assert err["turn_id"] == "turn-attachments"---async def test_message_rejected_when_too_many_total_attachments(tmp_path) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "mixed",- "media": [- {"data_url": _tiny_png_data_url()},- {"data_url": _tiny_png_data_url()},- {"data_url": _tiny_png_data_url()},- {"data_url": _tiny_png_data_url()},- {"data_url": _data_url("application/pdf", b"%PDF-1.4"), "name": "report.pdf"},- ],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_not_awaited()- err = json.loads(mock_conn.send.call_args[0][0])- assert err["detail"] == "attachment_rejected"- assert err["reason"] == "too_many_attachments"---async def test_message_rejected_on_oversize_payload(tmp_path) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- oversized = b"x" * (9 * 1024 * 1024) # > 8 MB WS limit- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "big",- "media": [{"data_url": _data_url("image/png", oversized)}],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_not_awaited()- err = json.loads(mock_conn.send.call_args[0][0])- assert err["detail"] == "attachment_rejected"- assert err["reason"] == "size"---async def test_message_with_pdf_forwards_saved_path(tmp_path) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "pdf?",- "media": [{"data_url": _data_url("application/pdf", b"%PDF-1.4"), "name": "report.pdf"}],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_awaited_once()- paths = channel._handle_message.call_args.kwargs["media"]- assert isinstance(paths, list) and len(paths) == 1- saved = Path(paths[0])- assert saved.exists()- assert saved.suffix == ".pdf"- assert saved.name.endswith("_report.pdf")- assert saved.read_bytes() == b"%PDF-1.4"---async def test_message_with_csv_forwards_saved_path(tmp_path) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "summarize",- "media": [- {"data_url": _data_url("text/csv", b"name,value\nnanobot,1"), "name": "report.csv"}- ],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_awaited_once()- paths = channel._handle_message.call_args.kwargs["media"]- saved = Path(paths[0])- assert saved.suffix == ".csv"- assert saved.name.endswith("_report.csv")- assert saved.read_bytes() == b"name,value\nnanobot,1"---async def test_message_rejected_on_unsupported_file_mime(tmp_path) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "zip?",- "media": [{"data_url": _data_url("application/zip", b"PK")}],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_not_awaited()- err = json.loads(mock_conn.send.call_args[0][0])- assert err["detail"] == "attachment_rejected"- assert err["reason"] == "mime"---async def test_message_rejected_on_svg_mime(tmp_path) -> None:- """SVG is explicitly rejected — XSS surface inside embedded scripts."""- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "svg",- "media": [{"data_url": _data_url("image/svg+xml", b"<svg/>")}],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_not_awaited()- err = json.loads(mock_conn.send.call_args[0][0])- assert err["reason"] == "mime"--- "data_url",- [- pytest.param("http://evil.example/image.png", id="malformed_data_url"),- pytest.param("data:image/png;base64,not-valid-base64!!!", id="broken_base64"),- ],-)-async def test_message_rejects_invalid_media_data_url(tmp_path, data_url) -> None:- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "nope",- "media": [{"data_url": data_url}],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_not_awaited()- err = json.loads(mock_conn.send.call_args[0][0])- assert err["reason"] == "decode"--@pytest.mark.asyncioasync def test_message_rejected_when_media_item_shape_wrong(tmp_path) -> None:channel = _make_channel()@@ -586,38 +247,6 @@ async def test_message_rejected_when_media_field_is_not_list() -> None:assert err["reason"] == "malformed"-async def test_failed_media_does_not_partially_persist(tmp_path) -> None:- """If the second attachment is invalid, the first must not be forwarded.-- Also: files already written in this call are cleaned up on failure, so- a mixed-valid/invalid batch never leaves orphan files in the media dir.- """- channel = _make_channel()- mock_conn = AsyncMock()- envelope = {- "type": "message",- "chat_id": "abc123",- "content": "mixed",- "media": [- {"data_url": _tiny_png_data_url()},- {"data_url": _data_url("image/svg+xml", b"<svg/>")},- ],- }-- with patch(- "nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path- ):- await channel._dispatch_envelope(mock_conn, "client-1", envelope)-- channel._handle_message.assert_not_awaited()- err = json.loads(mock_conn.send.call_args[0][0])- assert err["reason"] == "mime"- # Partial-batch failures must not leak files to disk.- leftover = [p for p in tmp_path.iterdir() if p.is_file()]- assert leftover == [], f"orphan media after rejected batch: {leftover}"--@pytest.mark.asyncioasync def test_rejects_empty_text_without_media() -> None:"""When no media is attached, whitespace-only content is still rejected@@ -652,3 +281,33 @@ async def test_non_string_content_still_rejected() -> None:channel._handle_message.assert_not_awaited()err = json.loads(mock_conn.send.call_args[0][0])assert err["detail"] == "missing content"+++async def test_reference_attachments_are_projected_to_other_clients(tmp_path, monkeypatch):+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ channel = _make_channel()+ origin, peer = AsyncMock(), AsyncMock()+ owner = channel.gateway.uploads.issue(origin)["token"]+ channel._attach(origin, "reference-chat")+ channel._attach(peer, "reference-chat")+ channel._webui_connections.add(origin)++ async def body():+ yield b"image"++ reference = await channel.gateway.uploads.store.upload(+ body(), owner=owner, mime="image/png", size=5,+ )+ await channel._dispatch_envelope(origin, "client", {+ "type": "message", "chat_id": "reference-chat", "content": "",+ "webui": True, "turn_id": "reference-turn",+ "media": [{"reference": reference, "name": "shot.png"}],+ })+ channel._handle_message.assert_awaited_once()+ assert Path(channel._handle_message.call_args.kwargs["media"][0]).read_bytes() == b"image"+ payload = json.loads(peer.send.await_args.args[0])+ assert payload["event"] == "user_message"+ assert payload["media_urls"][0]["name"] == "shot.png"+ assert payload["media_urls"][0]["url"].startswith("/api/media/")+ assert reference not in str(payload)diff --git a/nanobot/channels/websocket/tests/test_websocket_media_route.py b/nanobot/channels/websocket/tests/test_websocket_media_route.pyindex ad3bb7892..ba92493f8 100644--- a/nanobot/channels/websocket/tests/test_websocket_media_route.py+++ b/nanobot/channels/websocket/tests/test_websocket_media_route.py@@ -224,7 +224,7 @@ def test_local_markdown_image_rejects_workspace_escape(with patch("nanobot.webui.media_gateway.get_media_dir", side_effect=_fake_media_dir(media)):assert channel.gateway.media.rewrite_local_markdown_images(text) == text- assert not (media / "websocket").exists()+ assert list((media / "websocket").iterdir()) == []# ---------------------------------------------------------------------------diff --git a/nanobot/utils/media_decode.py b/nanobot/utils/media_decode.pyindex 4e4ac50b1..cc8494bbe 100644--- a/nanobot/utils/media_decode.py+++ b/nanobot/utils/media_decode.py@@ -1,8 +1,6 @@-"""Shared helpers for decoding ``data:...;base64,...`` URLs to disk.+"""Data-URL persistence for API uploads and audio transcription.-Historically lived in ``nanobot.api.server``; now shared by the WebSocket-channel so the ``api`` + ``websocket`` ingress paths apply the same parsing,-size guard, and filesystem layout.+Binary WebUI uploads share the media filename layout through ``media_destination``."""from __future__ import annotations@@ -84,10 +82,15 @@ def save_base64_data_url(limit = DEFAULT_MAX_BYTES if max_bytes is None else max_bytesif len(raw) > limit:raise FileSizeExceeded(f"File exceeds {limit // (1024 * 1024)}MB limit")+ dest = media_destination(media_dir, mime_type, filename=filename)+ dest.write_bytes(raw)+ return str(dest)+++def media_destination(media_dir: Path, mime_type: str, *, filename: str | None = None) -> Path:+ """Choose the shared media layout for binary and data-URL ingress."""ext = _MIME_EXTENSION_OVERRIDES.get(mime_type) or mimetypes.guess_extension(mime_type) or ".bin"base = safe_filename(filename or "")stem = Path(base).stem[:80] if base else ""saved_name = f"{uuid.uuid4().hex[:12]}_{stem}{ext}" if stem else f"{uuid.uuid4().hex[:12]}{ext}"- dest = media_dir / safe_filename(saved_name)- dest.write_bytes(raw)- return str(dest)+ return media_dir / safe_filename(saved_name)diff --git a/nanobot/webui/attachment_ingress.py b/nanobot/webui/attachment_ingress.pydeleted file mode 100644index 8e4eeb5f9..000000000--- a/nanobot/webui/attachment_ingress.py+++ /dev/null@@ -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, Nonediff --git a/nanobot/webui/client_contract.py b/nanobot/webui/client_contract.pyindex 14b915a91..76326ce59 100644--- a/nanobot/webui/client_contract.py+++ b/nanobot/webui/client_contract.py@@ -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,],}diff --git a/nanobot/webui/gateway_services.py b/nanobot/webui/gateway_services.pyindex f8850ae07..a067c3863 100644--- a/nanobot/webui/gateway_services.py+++ b/nanobot/webui/gateway_services.py@@ -9,7 +9,10 @@ from typing import TYPE_CHECKING, Any, Callablefrom loguru import logger as default_logger+from nanobot.channels.websocket.attachment_http import AttachmentHTTP+from nanobot.channels.websocket.attachment_store import AttachmentStorefrom nanobot.config.loader import get_config_path+from nanobot.config.paths import get_media_dirfrom nanobot.webui.gateway_endpoint import WebUIGatewayEndpointfrom nanobot.webui.gateway_tokens import GatewayTokenStorefrom nanobot.webui.ingress_policy import DEFAULT_WEBUI_INGRESS_POLICY, WebUIIngressPolicy@@ -39,6 +42,7 @@ class GatewayServices:settings: WebUISettingsServicestokens: GatewayTokenStoremedia: WebUIMediaGateway+ uploads: AttachmentHTTPingress: WebUIIngressPolicytranscripts: WebUITranscriptRecorderworkspaces: 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,diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.pyindex 16f471d8b..a38ad2389 100644--- a/nanobot/webui/inbound_commands.py+++ b/nanobot/webui/inbound_commands.py@@ -16,6 +16,7 @@ from loguru import loggerfrom websockets.asyncio.server import ServerConnectionfrom nanobot.bus.events import INBOUND_META_USER_SHELL+from nanobot.channels.websocket.attachment_store import AttachmentUploadErrorfrom nanobot.command.builtin import USER_SHELL_COMMAND, builtin_command_starts_agent_turnfrom nanobot.runtime_context import (RUNTIME_CONTEXT_INPUT_META,@@ -139,6 +140,7 @@ class WebUICommandRouter:self.gateway = gatewayself._http_router = gateway.httpself._media = gateway.media+ self._uploads = gateway.uploadsself._ingress = gateway.ingressself._transcripts = gateway.transcriptsself._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,+ )+ returnif 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_mentionsmetadata[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 Truequeued_owner = Noneif 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)diff --git a/nanobot/webui/ingress_policy.py b/nanobot/webui/ingress_policy.pyindex 80ca40599..ef9dbb9b7 100644--- a/nanobot/webui/ingress_policy.py+++ b/nanobot/webui/ingress_policy.py@@ -7,10 +7,11 @@ for a text or attachment policy.from __future__ import annotations-import mathfrom dataclasses import dataclass, fieldfrom 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_bytesDEFAULT_WEBUI_INGRESS_POLICY = WebUIIngressPolicy()diff --git a/nanobot/webui/media_gateway.py b/nanobot/webui/media_gateway.pyindex 6e3f4d424..be7b260cc 100644--- a/nanobot/webui/media_gateway.py+++ b/nanobot/webui/media_gateway.py@@ -11,11 +11,6 @@ from websockets.http11 import Request as WsRequestfrom websockets.http11 import Responsefrom nanobot.config.paths import get_media_dir-from nanobot.webui.attachment_ingress import (- AttachmentIngressResult,- store_inbound_attachments,-)-from nanobot.webui.ingress_policy import AttachmentIngressLimitsfrom 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_pathself.logger = loggerself._media_dir: Callable[[str | None], Path] = media_dir or _default_media_dirself.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,diff --git a/nanobot/webui/remote_proxy.py b/nanobot/webui/remote_proxy.pyindex 79b27d6df..aa36ab5fa 100644--- a/nanobot/webui/remote_proxy.py+++ b/nanobot/webui/remote_proxy.py@@ -27,6 +27,11 @@ from websockets.exceptions import WebSocketExceptionfrom websockets.typing import Originfrom 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_errorfrom nanobot.webui.local_client_assets import LocalClientAssetsfrom 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_tokentry: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())diff --git a/packages/client-events/attachments.ts b/packages/client-events/attachments.tsnew file mode 100644index 000000000..d072d7027--- /dev/null+++ b/packages/client-events/attachments.ts@@ -0,0 +1,52 @@+/** Local preview data is never included in a WebSocket message. */+export interface DraftAttachment { data_url: string; name?: string }+export interface AttachmentReference { reference: string; name?: string }+export interface UploadCapability { path: string; token: string }++// Allow the gateway's five-minute body budget plus request/response overhead.+const UPLOAD_REQUEST_TIMEOUT_MS = 315_000;++export function uploadCapability(value: unknown): UploadCapability | null {+ if (!value || typeof value !== "object") return null;+ const row = value as Record<string, unknown>;+ return row.path === "/api/attachments" && typeof row.token === "string" && row.token.length > 0+ ? { path: row.path, token: row.token } : null;+}++export async function uploadAttachments(+ drafts: readonly DraftAttachment[], capability: UploadCapability | null,+ baseUrl: string, stillConnected: () => boolean,+): Promise<AttachmentReference[]> {+ if (!capability || !stillConnected()) throw new Error("Attachment upload connection is not ready");+ const url = new URL(capability.path, baseUrl.replace(/^ws:/, "http:").replace(/^wss:/, "https:"));+ if (!["http:", "https:"].includes(url.protocol)) throw new Error("HTTP upload is unavailable");+ // No handshake credentials in the URL, no redirects leaking the capability.+ url.search = "";+ url.username = "";+ url.password = "";+ const references: AttachmentReference[] = [];+ for (const draft of drafts) {+ if (!stillConnected()) throw new Error("Connection changed during attachment upload");+ const match = /^data:([^;,]+);base64,([\s\S]*)$/.exec(draft.data_url);+ if (!match?.[1] || !match[2]) throw new Error("Invalid attachment preview");+ const raw = atob(match[2]);+ const bytes = Uint8Array.from(raw, (character) => character.charCodeAt(0));+ const response = await fetch(url, {+ method: "POST", redirect: "error", credentials: "omit",+ headers: {+ Authorization: `Bearer ${capability.token}`,+ "Content-Type": match[1],+ ...(draft.name ? { "X-Attachment-Name": encodeURIComponent(draft.name) } : {}),+ },+ body: new Blob([bytes], { type: match[1] }),+ signal: AbortSignal.timeout(UPLOAD_REQUEST_TIMEOUT_MS),+ });+ if (!response.ok) throw new Error(`Attachment upload failed (${response.status})`);+ const result: unknown = await response.json();+ if (!result || typeof result !== "object" || !("reference" in result)+ || typeof result.reference !== "string") throw new Error("Invalid upload response");+ references.push({ reference: result.reference, ...(draft.name ? { name: draft.name } : {}) });+ }+ if (!stillConnected()) throw new Error("Connection changed during attachment upload");+ return references;+}diff --git a/packages/client-events/delivery.ts b/packages/client-events/delivery.tsnew file mode 100644index 000000000..8985abf08--- /dev/null+++ b/packages/client-events/delivery.ts@@ -0,0 +1,28 @@+/** Bounded receipt wait: a socket write is not message acceptance. */+export class DeliveryReceipts {+ private pending = new Map<string, { resolve: () => void; reject: (error: Error) => void }>();++ wait(turnId: string, send: () => void): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ const finish = (error?: Error) => {+ clearTimeout(timer);+ this.pending.delete(turnId);+ if (error) reject(error); else resolve();+ };+ const timer = setTimeout(() => finish(new Error("Message acceptance not confirmed; draft retained")), 30_000);+ this.pending.set(turnId, { resolve: () => finish(), reject: finish });+ try { send(); } catch (error) { finish(error instanceof Error ? error : new Error(String(error))); }+ });+ }++ event(event: { event: string; turn_id?: string; detail?: string; reason?: string }): void {+ if (!event.turn_id) return;+ const pending = this.pending.get(event.turn_id);+ if (event.event === "message_accepted" || event.event === "user_message") pending?.resolve();+ else if (event.event === "error") pending?.reject(new Error(event.reason || event.detail || "Message rejected"));+ }++ close(): void {+ for (const pending of this.pending.values()) pending.reject(new Error("Connection closed before message acceptance; draft retained"));+ }+}diff --git a/tests/webui/test_attachment_ingress.py b/tests/webui/test_attachment_ingress.pydeleted file mode 100644index b7b78d43c..000000000--- a/tests/webui/test_attachment_ingress.py+++ /dev/null@@ -1,117 +0,0 @@-from __future__ import annotations--import base64-from pathlib import Path-from typing import Any-from unittest.mock import MagicMock--import pytest--from nanobot.webui.attachment_ingress import (- extract_data_url_mime,- store_inbound_attachments,-)-from nanobot.webui.ingress_policy import AttachmentIngressLimits---def _data_url(mime: str, payload: bytes) -> str:- encoded = base64.b64encode(payload).decode()- return f"data:{mime};base64,{encoded}"--- ("url", "expected"),- [- ("data:image/png;base64,AAAA", "image/png"),- ("data:IMAGE/JPEG;charset=utf-8;base64,AAAA", "image/jpeg"),- ("data:video/webm;codecs=vp9;base64,AAAA", "video/webm"),- ("data:text/plain;base64,AAAA", "text/plain"),- ("data:image/svg+xml;base64,AAAA", "image/svg+xml"),- ("data:image/png,AAAA", None),- ("data:;base64,AAAA", None),- ("https://example.invalid/image.png", None),- ("", None),- (None, None),- ],-)-def test_extract_data_url_mime_normalizes_only_base64_data_urls(- url: Any,- expected: str | None,-) -> None:- assert extract_data_url_mime(url) == expected---def test_store_inbound_document_preserves_safe_name(tmp_path: Path) -> None:- paths, rejection = store_inbound_attachments(- [- {- "data_url": _data_url("text/csv", b"name,value\nnanobot,1"),- "name": "report.csv",- },- ],- media_dir=tmp_path,- logger=MagicMock(),- )-- assert rejection is None- assert len(paths) == 1- saved = Path(paths[0])- assert saved.parent == tmp_path- assert saved.name.endswith("_report.csv")- assert saved.read_bytes() == b"name,value\nnanobot,1"---def test_invalid_batch_removes_files_already_persisted(tmp_path: Path) -> None:- paths, rejection = store_inbound_attachments(- [- {"data_url": _data_url("image/png", b"valid-first-item")},- {"data_url": _data_url("image/svg+xml", b"<svg/>")},- ],- media_dir=tmp_path,- logger=MagicMock(),- )-- assert paths == []- assert rejection == "mime"- assert list(tmp_path.iterdir()) == []---def test_invalid_base64_cannot_create_an_empty_attachment(tmp_path: Path) -> None:- paths, rejection = store_inbound_attachments(- [{"data_url": "data:text/plain;base64,@@@@", "name": "empty.txt"}],- media_dir=tmp_path,- logger=MagicMock(),- )-- assert paths == []- assert rejection == "decode"- assert list(tmp_path.iterdir()) == []---def test_single_file_limit_is_attachment_policy_not_transport(tmp_path: Path) -> None:- paths, rejection = store_inbound_attachments(- [{"data_url": _data_url("text/plain", b"12345"), "name": "large.txt"}],- media_dir=tmp_path,- logger=MagicMock(),- limits=AttachmentIngressLimits(max_file_bytes=4, max_total_bytes=20),- )-- assert paths == []- assert rejection == "size"- assert list(tmp_path.iterdir()) == []---def test_total_attachment_policy_rolls_back_the_batch(tmp_path: Path) -> None:- paths, rejection = store_inbound_attachments(- [- {"data_url": _data_url("text/plain", b"1234"), "name": "one.txt"},- {"data_url": _data_url("text/plain", b"5678"), "name": "two.txt"},- ],- media_dir=tmp_path,- logger=MagicMock(),- limits=AttachmentIngressLimits(max_file_bytes=4, max_total_bytes=6),- )-- assert paths == []- assert rejection == "total_size"- assert list(tmp_path.iterdir()) == []diff --git a/tests/webui/test_client_contract.py b/tests/webui/test_client_contract.pyindex 9b3cd21e3..b51fb57cf 100644--- a/tests/webui/test_client_contract.py+++ b/tests/webui/test_client_contract.py@@ -21,6 +21,7 @@ def test_current_producer_remains_acceptable_to_initial_client():contract = webui_contract()assert contract["min_protocol"] <= 1 <= contract["max_protocol"]assert "webui.core.v1" in contract["capabilities"]+ assert "webui.attachments.binary.v1" in contract["capabilities"]@pytest.mark.parametrize("version", ["0.0.1", "9.99.0", "0.3.5.dev17", "custom-build"])diff --git a/tests/webui/test_remote_proxy.py b/tests/webui/test_remote_proxy.pyindex 835f7a6d9..7298ac4ee 100644--- a/tests/webui/test_remote_proxy.py+++ b/tests/webui/test_remote_proxy.py@@ -7,6 +7,7 @@ import socketimport sysimport timefrom dataclasses import replace+from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import MagicMockfrom urllib.parse import parse_qs, urlsplit@@ -19,6 +20,7 @@ from websockets.datastructures import Headersfrom websockets.exceptions import InvalidStatusfrom websockets.http11 import Request+from nanobot.channels.websocket.binary_http import BinaryHTTPBridgefrom nanobot.channels.websocket.runtime import WebSocketConfigfrom nanobot.webui import remote_sshfrom nanobot.webui.client_contract import webui_contract@@ -33,6 +35,7 @@ MEDIA = "/api/media/AAAAAAAAAAAAAAAAAAAAAA/remoteFilePayload"@pytest.fixtureasync def remote(tmp_path, monkeypatch):+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)assets = tmp_path / "local-dist"assets.mkdir()(assets / "index.html").write_text("<!doctype html><title>Local nanobot</title>", encoding="utf-8")@@ -50,6 +53,7 @@ async def remote(tmp_path, monkeypatch):seen, children = [], []# Frozen initial wire declaration: current client vs an independently defined host.state = SimpleNamespace(block=asyncio.Event(), entered=asyncio.Event(), ws_redirect=False,+ binary_upload=False,contract={"version": "0.3.5", "min_protocol": 1, "max_protocol": 1,"capabilities": ["webui.core.v1"]})@@ -98,14 +102,21 @@ async def remote(tmp_path, monkeypatch):async def messages(ws):assert ws in services.endpoint.webui_connectionsassert ws.request.headers.get("X-Nanobot-Auth") is None- await ws.send(json.dumps({"ready": True, "media": MEDIA,- "query": parse_qs(urlsplit(ws.request.path).query).get("client_id")}))- async for message in ws:- await ws.send(message)+ try:+ await ws.send(json.dumps({"ready": True, "media": MEDIA,+ "query": parse_qs(urlsplit(ws.request.path).query).get("client_id"),+ **({"event": "ready", "upload": services.uploads.issue(ws)}+ if state.binary_upload else {})}))+ async for message in ws:+ await ws.send(message)+ finally:+ services.uploads.revoke(ws)real_spawn = asyncio.create_subprocess_execmonkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")- async with serve(messages, "127.0.0.1", 0, process_request=process, max_size=64 * 1024 * 1024) as server:+ bridge = BinaryHTTPBridge(services.uploads.handle)+ async with serve(messages, "127.0.0.1", 0, process_request=process,+ create_connection=bridge.connection_factory, max_size=64 * 1024 * 1024) as server:port = server.sockets[0].getsockname()[1]pipe = f"""import os, socket, threading@@ -135,6 +146,8 @@ while data := upstream.recv(65536):finally:state.block.set()await proxy.close()+ await bridge.shutdown()+ services.uploads.store.clear()assert all(child.returncode is not None for child in children)@@ -280,6 +293,82 @@ async def test_custom_ws_path_multiple_tabs_and_binary_upload(remote):assert json.loads(await other.recv())["ready"] is True+async def test_binary_http_upload_uses_a_live_local_capability(remote):+ remote.state.binary_upload = True+ issued = await bootstrap(remote)+ raw = b"x" * 1_453_245+ url = issued["ws_url"] + "?token=" + issued["token"]+ async with connect(url, proxy=None, origin=remote.proxy.origin) as ws:+ capability = json.loads(await ws.recv())["upload"]+ headers = {"Authorization": "Bearer " + capability["token"],+ "Content-Type": "image/png", "X-Attachment-Name": "clipboard.png"}+ response = await remote.client.post(remote.proxy.origin + capability["path"],+ content=raw, headers=headers)+ assert response.status_code == 201, response.text+ assert response.headers["cache-control"] == "no-store"+ assert capability["token"] not in remote.services.uploads._tokens+ owner = next(iter(remote.services.uploads._tokens))+ paths = remote.services.uploads.store.resolve([response.json()["reference"]], owner=owner)+ assert Path(paths[0]).read_bytes() == raw+ assert (await remote.client.post(remote.proxy.origin + "/api/attachments", content=raw,+ headers={**headers, "Authorization": "Bearer " + issued["api_token"]})).status_code == 401+ assert (await remote.client.post(remote.proxy.origin + "/api/fixture", content=b"write",+ headers={"Authorization": "Bearer " + issued["api_token"]})).status_code == 405+ assert (await remote.client.post(remote.proxy.origin + capability["path"], content=raw,+ headers={**headers, "Origin": "https://foreign.test"})).status_code == 403+ async with asyncio.timeout(5):+ while remote.services.uploads._tokens:+ await asyncio.sleep(.01)+ assert (await remote.client.post(remote.proxy.origin + capability["path"],+ content=raw, headers=headers)).status_code == 401+ assert not remote.services.uploads.store._entries++[email protected]("encoded", [False, True], ids=["chunked", "compressed"])+async def test_binary_upload_rejects_changed_body_framing(remote, encoded):+ remote.state.binary_upload = True+ issued = await bootstrap(remote)++ async def chunks():+ yield b"bytes"++ async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None) as ws:+ capability = json.loads(await ws.recv())["upload"]+ response = await remote.client.post(remote.proxy.origin + capability["path"],+ content=b"bytes" if encoded else chunks(), headers={+ "Authorization": "Bearer " + capability["token"], "Content-Type": "image/png",+ **({"Content-Encoding": "gzip"} if encoded else {}),+ })+ assert response.status_code == 400+ assert not remote.services.uploads.store._entries+++async def test_stalled_binary_upload_is_bounded_and_retryable(remote, monkeypatch):+ remote.state.binary_upload = True+ issued = await bootstrap(remote)+ async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None) as ws:+ capability = json.loads(await ws.recv())["upload"]+ with monkeypatch.context() as stalled_timeout:+ stalled_timeout.setattr("nanobot.webui.remote_proxy.UPLOAD_IDLE_TIMEOUT_SECONDS", .1)+ reader, writer = await asyncio.open_connection("127.0.0.1", remote.proxy.port)+ try:+ writer.write((+ f"POST /api/attachments HTTP/1.1\r\nHost: 127.0.0.1:{remote.proxy.port}\r\n"+ f"Authorization: Bearer {capability['token']}\r\nContent-Type: image/png\r\n"+ "Content-Length: 2\r\nConnection: close\r\n\r\nx"+ ).encode())+ await writer.drain()+ response = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 2)+ assert b"502 Bad Gateway" in response+ finally:+ writer.close()+ await writer.wait_closed()+ response = await remote.client.post(remote.proxy.origin + capability["path"],+ content=b"xx", headers={"Authorization": "Bearer " + capability["token"],+ "Content-Type": "image/png"})+ assert response.status_code == 201, response.text++async def test_signed_media_wrapped_over_http_and_websocket_and_range_preserved(remote):issued = await bootstrap(remote)response = await remote.client.get(remote.proxy.origin + "/api/fixture", headers={diff --git a/tui/src/app/app.ts b/tui/src/app/app.tsindex 13238d311..056a1b338 100644--- a/tui/src/app/app.ts+++ b/tui/src/app/app.ts@@ -176,6 +176,7 @@ export class NanobotTui {private ready = falseprivate shimmerFrame = 0private shimmerTimer: ReturnType<typeof setInterval> | null = null+ private attachmentSendPending = falseprivate submitPending = falseprivate submitGeneration = 0private 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: stringtry {- turnId = this.client.send(prompt.content, prompt.options)+ turnId = acceptedTurnId ?? this.client.send(prompt.content, prompt.options)} catch {this.markSubmitUnsent(true)return falsediff --git a/tui/src/app/composer.test.ts b/tui/src/app/composer.test.tsindex 6e494112a..848ededac 100644--- a/tui/src/app/composer.test.ts+++ b/tui/src/app/composer.test.ts@@ -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[] = []diff --git a/tui/src/app/test-support.ts b/tui/src/app/test-support.tsindex dfc434b8e..0d3bed4ab 100644--- a/tui/src/app/test-support.ts+++ b/tui/src/app/test-support.ts@@ -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)},diff --git a/tui/src/app/types.ts b/tui/src/app/types.tsindex 11cd9f57c..f34e2858b 100644--- a/tui/src/app/types.ts+++ b/tui/src/app/types.ts@@ -32,6 +32,7 @@ export interface ChatClient {connect(): voidclose(): voidsend(content: string, options?: MessageOptions): string+ sendAttachments(content: string, options: MessageOptions): Promise<string>attach(chatId: string): voidnewChat(scope?: WorkspaceScopePayload): voidforkChat?(sourceChatId: string, beforeUserIndex: number, title?: string): voiddiff --git a/tui/src/app/usage-app.test.ts b/tui/src/app/usage-app.test.tsindex b291af6d8..8a0aea770 100644--- a/tui/src/app/usage-app.test.ts+++ b/tui/src/app/usage-app.test.ts@@ -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() {},diff --git a/tui/src/client/client.test.ts b/tui/src/client/client.test.tsindex 222d0d1d4..2f5da1f6b 100644--- a/tui/src/client/client.test.ts+++ b/tui/src/client/client.test.ts@@ -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 })+ }+})diff --git a/tui/src/client/nanobot-client.ts b/tui/src/client/nanobot-client.tsindex 137cd3285..f13745454 100644--- a/tui/src/client/nanobot-client.ts+++ b/tui/src/client/nanobot-client.ts@@ -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 = falseprivate handshakeTimer: ReturnType<typeof setTimeout> | null = nullprivate socket: WebSocket | null = null@@ -94,6 +99,8 @@ export class NanobotClient {}let socket: WebSockettry {+ this.uploadBase = url+ this.upload = nullsocket = 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) returnthis.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 = nullthis.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.chatIdif (requestedChatId) {this.chatId = requestedChatIddiff --git a/tui/src/client/types.ts b/tui/src/client/types.tsindex d6b8c8963..3f23a39af 100644--- a/tui/src/client/types.ts+++ b/tui/src/client/types.ts@@ -193,7 +193,7 @@ export type OutboundEvent =turn_id: stringwebui: trueworkspace_scope?: WorkspaceScopePayload- media?: OutboundMedia[]+ media?: import("../../../packages/client-events/attachments").AttachmentReference[]cli_apps?: Array<{ name: string }>mcp_presets?: Array<{ name: string }>session_mentions?: SessionMention[]diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsxindex cb0c6fc28..f0d34dab9 100644--- a/webui/src/components/thread/ThreadComposer.tsx+++ b/webui/src/components/thread/ThreadComposer.tsx@@ -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;diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsxindex ae0a4dc8e..8ef7e0fd0 100644--- a/webui/src/components/thread/ThreadShell.tsx+++ b/webui/src/components/thread/ThreadShell.tsx@@ -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],);diff --git a/webui/src/hooks/useAttachedImages.ts b/webui/src/hooks/useAttachedImages.tsindex f75cb7427..0e752f9ad 100644--- a/webui/src/hooks/useAttachedImages.ts+++ b/webui/src/hooks/useAttachedImages.ts@@ -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) => {diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.tsindex e83f27d26..016842c1d 100644--- a/webui/src/hooks/useNanobotStream.ts+++ b/webui/src/hooks/useNanobotStream.ts@@ -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],);diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex bd686becc..b1b0cd18f 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -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": {diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 426f87c88..b66a85b50 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -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": {diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex 10536ec46..adb51cebf 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -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": {diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 1ec787d36..7ec25d688 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -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": {diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex ff45b8d5d..8083f70ae 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -1895,7 +1895,6 @@"decode_failed": "この画像をデコードできません","too_large": "ファイルが大きすぎます。小さいものを選んでください","total_too_large": "添付ファイルの合計サイズが大きすぎます。いくつか削除するか、より小さいファイルを使用してください",- "transport_too_large": "この添付ファイルはゲートウェイの転送上限を超えます","io": "このファイルを読み込めません"},"mentions": {diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 4647449ae..fa5e6db45 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -1895,7 +1895,6 @@"decode_failed": "이 이미지를 디코딩할 수 없습니다","too_large": "파일이 너무 큽니다. 더 작은 파일을 선택해 주세요","total_too_large": "첨부 파일의 전체 크기가 너무 큽니다. 일부를 제거하거나 더 작은 파일을 사용해 주세요",- "transport_too_large": "이 첨부 파일은 게이트웨이 전송 한도를 초과합니다","io": "이 파일을 읽을 수 없습니다"},"mentions": {diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 60e72db57..6069229b2 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -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": {diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex d40e3f5b9..42df0b60a 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -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": {diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 1031c8e22..ffd8ca3dc 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -2109,7 +2109,6 @@"decode_failed": "无法解码这张图片","too_large": "文件太大,请换一个小一点的","total_too_large": "附件总大小过大,请移除部分文件或使用更小的文件",- "transport_too_large": "该附件会超过网关的传输上限","io": "无法读取该文件"},"goalStateCloseAria": "关闭目标",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex ddbc47bf6..7ae78e22d 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -1895,7 +1895,6 @@"decode_failed": "無法解碼這張圖片","too_large": "檔案太大,請改用較小的檔案","total_too_large": "附件總大小過大,請移除部分檔案或改用較小的檔案",- "transport_too_large": "此附件會超過閘道的傳輸上限","io": "無法讀取這個檔案"},"mentions": {diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.tsindex 71a9c3a1f..9a1759fdb 100644--- a/webui/src/lib/nanobot-client.ts+++ b/webui/src/lib/nanobot-client.ts@@ -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;diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex 74f0e6d9a..b610ae561 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -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[];diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.tsindex e8817b889..5883fa5c5 100644--- a/webui/src/tests/nanobot-client.test.ts+++ b/webui/src/tests/nanobot-client.test.ts@@ -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(); }+ });+});diff --git a/webui/src/tests/thread-composer-attach.test.tsx b/webui/src/tests/thread-composer-attach.test.tsxindex a20f41bbf..bd1a5bb04 100644--- a/webui/src/tests/thread-composer-attach.test.tsx+++ b/webui/src/tests/thread-composer-attach.test.tsx@@ -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 () => {diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsxindex 976b7c557..f269c7a84 100644--- a/webui/src/tests/useNanobotStream.test.tsx+++ b/webui/src/tests/useNanobotStream.test.tsx@@ -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],