Skip to content

Your lightweight open-source personal agent.

feat(attachments): support local files and video attachments (#6321)

chengyongru254f94b068bd
diff --git a/docs/webui.md b/docs/webui.md
index f8afdb3f9..b012a570d 100644
--- a/docs/webui.md
+++ b/docs/webui.md
@@ -175,7 +175,13 @@ In Restricted mode, ordinary file and shell work stays inside the selected proje
## Composer
-The composer supports text, image attachments, slash commands and `@` mentions. With voice transcription configured, the empty composer offers voice input; transcription is added to the draft before sending.
+The composer supports text, attachments (images, documents, and videos), slash commands and `@` mentions. With voice transcription configured, the empty composer offers voice input; transcription is added to the draft before sending.
+
+Choose or drop MP4, WebM, or MOV videos into the composer (one per message, up to 20 MiB per upload). You can play them in WebUI; the Agent cannot directly analyze their contents yet.
+
+To attach a file on the connected nanobot host, paste its path on its own. Quoted paths and spaces are supported; relative paths start from the topic's workspace. The topic's access permissions apply. Path references do not upload or copy the file and have no file-size or combined-size limit; supported formats and attachment counts still apply. If attaching fails, the text stays in your draft.
+
+Files attached by path reflect changes to the original file and become unavailable if it is moved or deleted. Removing an attachment or deleting a topic does not delete the original.
To reference another topic, type or paste its complete handle (such as `@luma`), choose it from the `@` menu, or drag it from the sidebar into the composer. Recognized handles are highlighted; unknown handles remain plain text. You can reference up to eight different topics in one message.
diff --git a/nanobot/agent/context.py b/nanobot/agent/context.py
index 825999fd8..3576f0e6d 100644
--- a/nanobot/agent/context.py
+++ b/nanobot/agent/context.py
@@ -21,7 +21,7 @@ from nanobot.security.workspace_access import WorkspaceScopeResolver
from nanobot.session.keys import last_channel_from_metadata
from nanobot.session.manager import Session
from nanobot.session.summary import SessionSummary
-from nanobot.utils.helpers import detect_image_mime, load_bundled_template
+from nanobot.utils.helpers import detect_image_mime, image_placeholder_text, load_bundled_template
from nanobot.utils.prompt_templates import render_template
@@ -328,7 +328,7 @@ class ContextBuilder:
if not image_paths:
return text
- image_blocks: list[dict[str, Any]] = []
+ media_blocks: list[dict[str, Any]] = []
for path in image_paths:
p = Path(path)
if not p.is_file():
@@ -340,12 +340,13 @@ class ContextBuilder:
if not mime or not mime.startswith("image/"):
continue
b64 = base64.b64encode(raw).decode()
- image_blocks.append({
+ media_blocks.append({"type": "text", "text": image_placeholder_text(str(p))})
+ media_blocks.append({
"type": "image_url",
"image_url": {"url": f"data:{mime};base64,{b64}"},
"_meta": {"path": str(p)},
})
- if not image_blocks:
+ if not media_blocks:
return text
- return image_blocks + [{"type": "text", "text": text}]
+ return media_blocks + [{"type": "text", "text": text}]
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index 98c6a3be2..0355ffe42 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -46,6 +46,7 @@ from nanobot.agent.turn_delivery import (
from nanobot.agent.turn_delivery import TurnRoute as TurnRoute
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
from nanobot.bus.events import (
+ INBOUND_META_LOCAL_MEDIA,
INBOUND_META_RUNTIME_CONTROL,
INBOUND_META_TURN_ID,
INBOUND_META_USER_SHELL,
@@ -712,6 +713,9 @@ class AgentLoop:
turn_id = msg.metadata.get(INBOUND_META_TURN_ID)
if isinstance(turn_id, str) and turn_id:
extra[INBOUND_META_TURN_ID] = turn_id
+ local_media = msg.metadata.get(INBOUND_META_LOCAL_MEDIA)
+ if isinstance(local_media, list) and local_media:
+ extra[INBOUND_META_LOCAL_MEDIA] = [path for path in cast(list[object], local_media) if isinstance(path, str)]
return extra
async def _persist_user_message_early(
@@ -2447,9 +2451,9 @@ class AgentLoop:
).startswith("data:image/"):
internal_meta = cast(dict[str, Any], block_data.get("_meta") or {})
path = cast(str, internal_meta.get("path", ""))
- filtered.append(
- {"type": "text", "text": image_placeholder_text(path)}
- )
+ reference = {"type": "text", "text": image_placeholder_text(path)}
+ if not filtered or filtered[-1] != reference:
+ filtered.append(reference)
continue
filtered.append(block_data)
diff --git a/nanobot/bus/events.py b/nanobot/bus/events.py
index a2b2325a8..11879a001 100644
--- a/nanobot/bus/events.py
+++ b/nanobot/bus/events.py
@@ -22,6 +22,7 @@ RUNTIME_CONTROL_SESSION_DISCARD = "session_discard"
# Transport-provided turn correlation; the persisted spelling is retained for clients.
INBOUND_META_TURN_ID = "webui_turn_id"
+INBOUND_META_LOCAL_MEDIA = "local_media_paths"
@dataclass
diff --git a/nanobot/channels/websocket/attachment_policy.py b/nanobot/channels/websocket/attachment_policy.py
index 030a8cc3c..f02e0ba24 100644
--- a/nanobot/channels/websocket/attachment_policy.py
+++ b/nanobot/channels/websocket/attachment_policy.py
@@ -1,4 +1,4 @@
-"""File, MIME and batch policy for WebSocket channel binary uploads."""
+"""Shared MIME and batch limits for WebSocket attachment ingress."""
from dataclasses import dataclass
@@ -39,3 +39,35 @@ DOCUMENT_MIME_ALLOWED: frozenset[str] = frozenset({
"text/csv", "text/html", "text/markdown", "text/plain", "text/xml", "text/yaml",
})
UPLOAD_MIME_ALLOWED = IMAGE_MIME_ALLOWED | VIDEO_MIME_ALLOWED | DOCUMENT_MIME_ALLOWED
+
+
+def validate_attachment_batch(
+ mimes: list[str], *, limits: AttachmentIngressLimits,
+) -> None:
+ """Apply shared format and count limits without imposing an upload budget."""
+ videos = sum(mime in VIDEO_MIME_ALLOWED for mime in mimes)
+ if videos > MAX_VIDEOS_PER_MESSAGE or len(mimes) - videos > limits.max_count:
+ raise ValueError("Too many attachments")
+ if any(mime not in UPLOAD_MIME_ALLOWED for mime in mimes):
+ raise ValueError("Unsupported attachment MIME")
+
+
+def validate_upload_size(mime: str, size: int, *, limits: AttachmentIngressLimits) -> None:
+ if isinstance(size, bool) or size <= 0:
+ raise ValueError("Empty files cannot be uploaded")
+ limit = MAX_VIDEO_BYTES if mime in VIDEO_MIME_ALLOWED else limits.max_file_bytes
+ if size > limit:
+ maximum = f"{limit / (1024 * 1024):g} MiB" if limit >= 1024 * 1024 else f"{limit:,} bytes"
+ raise ValueError(f"Attachment exceeds the {maximum} upload limit ({size:,} bytes)")
+
+
+def validate_upload_batch(
+ items: list[tuple[str, int]], *, limits: AttachmentIngressLimits,
+) -> None:
+ """Upload ownership alone incurs per-file and cumulative byte limits."""
+ validate_attachment_batch([mime for mime, _ in items], limits=limits)
+ for mime, size in items:
+ validate_upload_size(mime, size, limits=limits)
+ total = sum(size for mime, size in items if mime not in VIDEO_MIME_ALLOWED)
+ if total > limits.max_total_bytes:
+ raise ValueError(f"Uploaded attachments exceed the total upload limit ({total:,} bytes; maximum {limits.max_total_bytes:,} bytes)")
diff --git a/nanobot/channels/websocket/attachment_store.py b/nanobot/channels/websocket/attachment_store.py
index a4cad232e..4b4ec3aa0 100644
--- a/nanobot/channels/websocket/attachment_store.py
+++ b/nanobot/channels/websocket/attachment_store.py
@@ -16,13 +16,13 @@ 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,
+ validate_upload_batch,
+ validate_upload_size,
)
from nanobot.utils.media_decode import media_destination
@@ -32,7 +32,7 @@ class AttachmentUploadError(ValueError):
@dataclass(frozen=True)
-class _Attachment:
+class StagedAttachment:
owner: str
path: Path
mime: str
@@ -69,7 +69,7 @@ class AttachmentStore:
self.ttl_seconds = ttl_seconds
self.upload_timeout = upload_timeout
self.upload_idle_timeout = upload_idle_timeout
- self._entries: dict[str, _Attachment] = {}
+ self._entries: dict[str, StagedAttachment] = {}
self._reserved_bytes = 0
self._active = 0
self._journal = media_dir / ".pending-attachments"
@@ -94,9 +94,10 @@ class AttachmentStore:
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")
+ try:
+ validate_upload_size(mime, size, limits=self.limits)
+ except ValueError as exc:
+ raise AttachmentUploadError(str(exc)) from exc
if self._active + len(self._entries) >= self.max_pending:
raise AttachmentUploadError("Too many pending attachments")
if self._reserved_bytes + size > self.max_pending_bytes:
@@ -135,7 +136,7 @@ class AttachmentStore:
if received != size:
raise AttachmentUploadError("Incomplete attachment body")
reference = secrets.token_urlsafe(32)
- self._entries[reference] = _Attachment(
+ self._entries[reference] = StagedAttachment(
owner, path, mime, size, time.monotonic() + self.ttl_seconds,
)
stored = True
@@ -150,27 +151,27 @@ class AttachmentStore:
if marker_created:
(self._journal / path.name).unlink(missing_ok=True)
- def resolve(self, references: list[str], *, owner: str) -> list[str]:
+ def inspect(self, references: list[str], *, owner: str) -> list[StagedAttachment]:
"""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] = []
+ entries: list[StagedAttachment] = []
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]
+ try:
+ validate_upload_batch([(e.mime, e.size) for e in entries], limits=self.limits)
+ except ValueError as exc:
+ raise AttachmentUploadError(str(exc)) from exc
+ return entries
+
+ def resolve(self, references: list[str], *, owner: str) -> list[str]:
+ return [str(entry.path) for entry in self.inspect(references, owner=owner)]
def commit(self, references: list[str], *, owner: str) -> list[str]:
"""Transfer validated files to session ownership after message acceptance.
diff --git a/nanobot/channels/websocket/tests/test_attachment_store.py b/nanobot/channels/websocket/tests/test_attachment_store.py
index 2ff2dfc27..2959de043 100644
--- a/nanobot/channels/websocket/tests/test_attachment_store.py
+++ b/nanobot/channels/websocket/tests/test_attachment_store.py
@@ -255,3 +255,19 @@ async def test_filename_collision_preserves_another_uploads_crash_marker(tmp_pat
assert (tmp_path / ".pending-attachments" / path.name).exists()
assert path.read_bytes() == b"attachment"
store.clear()
+
+
+async def test_video_upload_limit_explains_size_before_reading_body(tmp_path):
+ from nanobot.channels.websocket.attachment_policy import MAX_VIDEO_BYTES
+
+ async def unread():
+ pytest.fail("oversized upload body must not be consumed")
+ yield b""
+
+ with pytest.raises(AttachmentUploadError) as error:
+ await AttachmentStore(tmp_path).upload(
+ unread(), owner="owner", mime="video/mp4", size=MAX_VIDEO_BYTES + 1,
+ )
+ assert "20 MiB" in str(error.value)
+ assert "20,971,521" in str(error.value)
+ assert not list(tmp_path.iterdir())
diff --git a/nanobot/channels/websocket/tests/test_local_attachments.py b/nanobot/channels/websocket/tests/test_local_attachments.py
new file mode 100644
index 000000000..861a383bb
--- /dev/null
+++ b/nanobot/channels/websocket/tests/test_local_attachments.py
@@ -0,0 +1,151 @@
+"""Borrowed local attachments share ingress policy without taking file ownership."""
+
+from unittest.mock import Mock
+
+import pytest
+from websockets.datastructures import Headers
+from websockets.http11 import Request
+
+from nanobot.channels.websocket.attachment_policy import AttachmentIngressLimits
+from nanobot.security.workspace_access import default_workspace_scope
+from nanobot.webui.attachments import inspect_local_attachment
+from nanobot.webui.file_preview import WebUIFilePreviewError
+from nanobot.webui.media_gateway import WebUIMediaGateway
+
+
+def test_inspect_literal_relative_path_without_reading_or_copying(tmp_path, monkeypatch):
+ source = tmp_path / "clip #100%.mp4"
+ source.write_bytes(b"\0video")
+ monkeypatch.setattr(type(source), "read_bytes", lambda *_: pytest.fail("inspection read file body"))
+ scope = default_workspace_scope(tmp_path, True)
+ result = inspect_local_attachment(source.name, scope=scope, limits=AttachmentIngressLimits())
+ assert result == {"path": str(source), "name": source.name, "size": 6, "mime": "video/mp4", "kind": "video"}
+ assert [path for path in tmp_path.rglob("*") if path.is_file()] == [source]
+
+
[email protected]("name", ["image.png", "notes.md", "document.pdf", "video.mov", "video.webm"])
+def test_local_supported_formats_do_not_consume_upload_byte_limits(tmp_path, name):
+ source = tmp_path / name
+ size = 64 * 1024 * 1024 + 1
+ with source.open("wb") as output:
+ output.truncate(size)
+ limits = AttachmentIngressLimits(max_file_bytes=3, max_total_bytes=3)
+ assert inspect_local_attachment(name, scope=default_workspace_scope(tmp_path, True), limits=limits)["size"] == size
+
+
+def test_reject_missing_directory_outside_empty_and_unreadable(tmp_path, monkeypatch):
+ workspace = tmp_path / "project"
+ workspace.mkdir()
+ source = tmp_path / "outside.mp4"
+ source.write_bytes(b"x")
+ scope = default_workspace_scope(workspace, True)
+ for path, status in [("missing.mp4", 404), (str(workspace), 404), (str(source), 403)]:
+ with pytest.raises(WebUIFilePreviewError) as error:
+ inspect_local_attachment(path, scope=scope, limits=AttachmentIngressLimits())
+ assert error.value.status == status
+ video = workspace / "large.mp4"
+ video.touch()
+ with pytest.raises(WebUIFilePreviewError, match="[Ee]mpty"):
+ inspect_local_attachment(str(video), scope=scope, limits=AttachmentIngressLimits())
+ monkeypatch.setattr("nanobot.webui.attachments.os.open", Mock(side_effect=PermissionError))
+ with pytest.raises(WebUIFilePreviewError, match="readable"):
+ inspect_local_attachment(str(video), scope=scope, limits=AttachmentIngressLimits())
+
+
+def test_local_media_ranges_latest_contents_and_current_scope_without_staging(tmp_path):
+ project = tmp_path / "project"
+ project.mkdir()
+ source = tmp_path / "original.mp4"
+ source.write_bytes(b"first video")
+ media = tmp_path / "media"
+ gateway = WebUIMediaGateway(workspace_path=project, logger=Mock(), media_dir=lambda _: media)
+ attachments = gateway.augment_transcript_user_media([str(source)], [str(source)], session_key="websocket:local")
+ sig, payload = attachments[0]["url"].split("/")[-2:]
+ scope = default_workspace_scope(project, False)
+
+ def fetch(range_header=None):
+ return gateway.serve_signed_media(
+ sig, payload, scope_for_session=lambda _: scope,
+ request=Request("/", Headers({"Range": range_header} if range_header else {})),
+ )
+
+ assert bytes(fetch().body) == b"first video"
+ source.write_bytes(b"latest video")
+ response = fetch("bytes=0-5")
+ assert response.status_code == 206
+ assert bytes(response.body) == b"latest"
+ assert response.headers["Cache-Control"] == "no-store"
+ assert not media.exists()
+ scope = default_workspace_scope(project, True)
+ assert fetch().status_code == 403
+ scope = default_workspace_scope(project, False)
+ source.unlink()
+ assert fetch().status_code == 404
+ assert gateway.augment_transcript_user_media([str(source)], [str(source)], session_key="websocket:local")[0]["url"] == ""
+
+
+def test_referenced_file_in_media_storage_is_not_treated_as_immutable_upload(tmp_path):
+ media = tmp_path / "media"
+ media.mkdir()
+ source = media / "original.mp4"
+ source.write_bytes(b"before")
+ gateway = WebUIMediaGateway(workspace_path=tmp_path, logger=Mock(), media_dir=lambda _: media)
+ attachment = gateway.augment_transcript_user_media([str(source)], [str(source)], session_key="websocket:local")[0]
+ sig, payload = attachment["url"].split("/")[-2:]
+ source.write_bytes(b"updated")
+ response = gateway.serve_signed_media(
+ sig, payload, scope_for_session=lambda _: default_workspace_scope(tmp_path, True),
+ )
+ assert bytes(response.body) == b"updated"
+ assert response.headers["Cache-Control"] == "no-store"
+ assert list(media.iterdir()) == [source]
+
+
+def test_legacy_media_filename_starting_with_bracket_keeps_working(tmp_path):
+ source = tmp_path / "[recording].mp4"
+ source.write_bytes(b"uploaded video")
+ gateway = WebUIMediaGateway(workspace_path=tmp_path, logger=Mock(), media_dir=lambda _: tmp_path)
+ attachment = gateway.sign_or_stage_media_path(source)
+ sig, payload = attachment["url"].split("/")[-2:]
+ response = gateway.serve_signed_media(sig, payload)
+ assert bytes(response.body) == b"uploaded video"
+
+
[email protected]("canonical", [False, True])
+async def test_mixed_media_replay_keeps_uploaded_cache_and_borrowed_freshness(tmp_path, history, canonical):
+ from nanobot.session.manager import Session
+ from nanobot.webui.transcript import (
+ WebUITranscriptRecorder,
+ build_session_thread_response,
+ )
+ media = tmp_path / "media"
+ media.mkdir()
+ uploaded = media / "upload.png"
+ borrowed = media / "borrowed.png"
+ uploaded.write_bytes(b"upload")
+ borrowed.write_bytes(b"original")
+ paths = [str(uploaded), str(borrowed)]
+ metadata = {"local_media_paths": [str(borrowed)]}
+ gateway = WebUIMediaGateway(workspace_path=tmp_path, logger=Mock(), media_dir=lambda _: media)
+
+ def augment(paths, local):
+ return gateway.augment_transcript_user_media(paths, local, session_key="websocket:cache")
+
+ if canonical:
+ session = Session(key="websocket:cache")
+ session.add_message("user", "look", media=paths, **metadata)
+ response = build_session_thread_response(session, augment_user_media=augment)
+ else:
+ assert await WebUITranscriptRecorder(history.sessions).append_user_message(
+ "cache", "look", media_paths=paths, metadata=await history.metadata("cache", metadata),
+ )
+ response = history.build("websocket:cache", session_messages=[], augment_user_media=augment)
+ urls = response["events"][0]["media_urls"]
+ scope = default_workspace_scope(tmp_path, True)
+ borrowed.write_bytes(b"updated")
+ for attachment, expected, cache in zip(urls, [b"upload", b"updated"], ["private, max-age=31536000, immutable", "no-store"], strict=True):
+ sig, payload = attachment["url"].split("/")[-2:]
+ served = gateway.serve_signed_media(sig, payload, scope_for_session=lambda _: scope)
+ assert bytes(served.body) == expected
+ assert served.headers["Cache-Control"] == cache
+ assert sorted(path.name for path in media.iterdir()) == ["borrowed.png", "upload.png"]
diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py
index 745c91fb0..283e904fb 100644
--- a/nanobot/channels/websocket/tests/test_websocket_channel.py
+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py
@@ -481,8 +481,16 @@ async def test_temporary_chat_is_transient_and_discarded(history, bus, tmp_path)
chat_id = await _new_temporary_chat(channel, connection)
upload = tmp_path / "temporary-upload.txt"
upload.write_text("private attachment", encoding="utf-8")
- channel.gateway.uploads.store.resolve = MagicMock(return_value=[str(upload)])
- channel.gateway.uploads.store.commit = MagicMock(return_value=[str(upload)])
+ async def upload_chunks():
+ yield upload.read_bytes()
+
+ owner = channel.gateway.uploads.issue(connection)["token"]
+ reference = await channel.gateway.uploads.store.upload(
+ upload_chunks(), owner=owner, mime="text/plain", size=upload.stat().st_size,
+ filename=upload.name,
+ )
+ upload.unlink()
+ upload = channel.gateway.uploads.store.inspect([reference], owner=owner)[0].path
await channel._dispatch_envelope(
connection,
@@ -491,7 +499,7 @@ async def test_temporary_chat_is_transient_and_discarded(history, bus, tmp_path)
"type": "message",
"chat_id": chat_id,
"content": "read this",
- "media": [{"reference": "temporary-upload"}],
+ "media": [{"reference": reference}],
"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.py
index a18a4d62e..e8d5a2312 100644
--- a/nanobot/channels/websocket/tests/test_websocket_envelope_media.py
+++ b/nanobot/channels/websocket/tests/test_websocket_envelope_media.py
@@ -19,7 +19,9 @@ from nanobot.session.session_handles import SessionHandleResolver
from nanobot.webui.gateway_services import build_gateway_services
-def _make_channel(session_manager: SessionManager | None = None) -> WebSocketChannel:
+def _make_channel(
+ session_manager: SessionManager | None = None, *, workspace: Path | None = None, restricted: bool = False,
+) -> WebSocketChannel:
bus = MagicMock()
bus.publish_inbound = AsyncMock()
cfg = {"enabled": True, "allowFrom": ["*"], "websocketRequiresToken": False}
@@ -29,8 +31,8 @@ def _make_channel(session_manager: SessionManager | None = None) -> WebSocketCha
bus=bus,
session_manager=session_manager,
static_dist_path=None,
- workspace_path=Path.cwd(),
- default_restrict_to_workspace=False,
+ workspace_path=workspace or Path.cwd(),
+ default_restrict_to_workspace=restricted,
runtime_model_name=None,
runtime_surface="browser",
runtime_capabilities_overrides=None,
@@ -66,11 +68,12 @@ def test_max_message_bytes_keeps_existing_transport_guard() -> None:
@pytest.mark.asyncio
-async def test_message_without_media_backward_compatible() -> None:
+async def test_message_without_media_backward_compatible(monkeypatch) -> None:
"""Existing clients that don't send ``media`` keep working unchanged."""
channel = _make_channel()
mock_conn = AsyncMock()
envelope = {"type": "message", "chat_id": "abc123", "content": "hello"}
+ monkeypatch.setattr(channel.gateway.uploads.store, "prune", lambda: pytest.fail("text send scanned upload staging"))
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
@@ -311,3 +314,165 @@ async def test_reference_attachments_are_projected_to_other_clients(tmp_path, mo
assert payload["media_urls"][0]["name"] == "shot.png"
assert payload["media_urls"][0]["url"].startswith("/api/media/")
assert reference not in str(payload)
+ accepted = json.loads(origin.send.await_args.args[0])
+ assert accepted["event"] == "message_accepted"
+ assert accepted["media_urls"] == payload["media_urls"]
+
+
+async def test_local_reference_inspection_send_recheck_and_no_staging(tmp_path, monkeypatch):
+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data")
+ workspace = tmp_path / "project"
+ workspace.mkdir()
+ source = workspace / "clip #100%.mp4"
+ source.write_bytes(b"\0video")
+ channel = _make_channel(workspace=workspace, restricted=True)
+ conn = AsyncMock()
+ channel._webui_connections.add(conn)
+
+ async def inspect(path):
+ conn.send.reset_mock()
+ await channel._dispatch_envelope(conn, "client", {
+ "type": "webui_request", "request_id": "inspect", "action": "attachment.inspect",
+ "payload": {"chat_id": "local-chat", "path": path},
+ })
+ return json.loads(conn.send.await_args.args[0])
+
+ result = await inspect(source.name)
+ assert result["ok"] is True
+ local = result["result"]
+ assert local["path"] == str(source)
+ assert local["size"] == 6
+ assert local["kind"] == "video"
+ assert channel.gateway.uploads.store._entries == {}
+ assert not list(channel.gateway.uploads.store.media_dir.glob("*"))
+ assert channel._webui_request_operations == {}
+
+ for invalid in ("missing.mp4", str(workspace), str(tmp_path / "outside.mp4")):
+ failure = await inspect(invalid)
+ assert failure["ok"] is False
+
+ message = {
+ "type": "message", "chat_id": "local-chat", "content": "keep my text",
+ "webui": True, "turn_id": "local-turn", "media": [{"path": local["path"]}],
+ }
+ source.unlink()
+ await channel._dispatch_envelope(conn, "client", message)
+ assert json.loads(conn.send.await_args.args[0])["detail"] == "attachment_rejected"
+ channel._handle_message.assert_not_awaited()
+ source.write_bytes(b"latest video")
+ await channel._dispatch_envelope(conn, "client", message)
+ channel._handle_message.assert_awaited_once()
+ assert channel._handle_message.await_args.kwargs["media"] == [str(source)]
+ assert channel._handle_message.await_args.kwargs["metadata"]["local_media_paths"] == [str(source)]
+ assert source.read_bytes() == b"latest video"
+ assert not list(channel.gateway.uploads.store.media_dir.glob("*"))
+
+
+async def test_mixed_local_and_uploaded_video_limit_keeps_upload_for_retry(tmp_path, monkeypatch):
+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data")
+ source = tmp_path / "local.webm"
+ source.write_bytes(b"video")
+ channel = _make_channel(workspace=tmp_path, restricted=True)
+ conn = AsyncMock()
+ owner = channel.gateway.uploads.issue(conn)["token"]
+
+ async def body():
+ yield b"upload"
+
+ ref = await channel.gateway.uploads.store.upload(body(), owner=owner, mime="video/mp4", size=6)
+ await channel._dispatch_envelope(conn, "client", {
+ "type": "message", "chat_id": "mixed-local", "content": "retained",
+ "media": [{"path": str(source)}, {"reference": ref}],
+ })
+ assert json.loads(conn.send.await_args.args[0])["detail"] == "attachment_rejected"
+ assert channel.gateway.uploads.store.resolve([ref], owner=owner)
+ assert source.exists()
+ channel._handle_message.assert_not_awaited()
+
+
+async def test_temporary_chat_disposal_never_deletes_borrowed_source(tmp_path, monkeypatch):
+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data")
+ source = tmp_path / "original.txt"
+ source.write_text("borrowed", encoding="utf-8")
+ manager = SessionManager(tmp_path)
+ channel = _make_channel(manager, workspace=tmp_path, restricted=True)
+ conn = AsyncMock()
+ channel._webui_connections.add(conn)
+ chat_id = await channel.gateway.temporary_chats.create(conn, trusted_webui=True)
+ await channel._dispatch_envelope(conn, "client", {
+ "type": "message", "chat_id": chat_id, "content": "", "webui": True,
+ "media": [{"path": str(source)}],
+ })
+ channel._handle_message.assert_awaited_once()
+ url = channel.gateway.media.local_attachment_url(str(source), session_key=f"websocket:{chat_id}")
+ sig, payload = url.split("/")[-2:]
+ assert channel.gateway.http._handle_media_fetch(sig, payload).status_code == 200
+ channel.gateway.uploads.store.discard_owner(channel.gateway.uploads.owner(conn))
+ channel.gateway.uploads.store.prune()
+ await channel.gateway.temporary_chats.discard(conn, chat_id)
+ assert channel.gateway.http._handle_media_fetch(sig, payload).status_code == 404
+ assert source.read_text(encoding="utf-8") == "borrowed"
+
+
+async def test_large_local_files_and_upload_share_count_but_not_byte_budget(tmp_path, monkeypatch):
+ from nanobot.channels.websocket.attachment_policy import AttachmentIngressLimits
+
+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data")
+ sources = [tmp_path / "large.mp4", tmp_path / "large.pdf"]
+ for source in sources:
+ with source.open("wb") as output:
+ output.truncate(64 * 1024 * 1024 + 1)
+ channel = _make_channel(workspace=tmp_path, restricted=True)
+ channel.gateway.uploads.store.limits = AttachmentIngressLimits(max_file_bytes=8, max_total_bytes=8)
+ conn = AsyncMock()
+ owner = channel.gateway.uploads.issue(conn)["token"]
+
+ async def body():
+ yield b"uploaded"
+
+ ref = await channel.gateway.uploads.store.upload(body(), owner=owner, mime="image/png", size=8)
+ uploaded = channel.gateway.uploads.store.resolve([ref], owner=owner)[0]
+ await channel._dispatch_envelope(conn, "client", {
+ "type": "message", "chat_id": "large-local", "content": "read references",
+ "media": [{"path": str(sources[0])}, {"reference": ref}, {"path": str(sources[1])}],
+ })
+ channel._handle_message.assert_awaited_once()
+ assert channel._handle_message.await_args.kwargs["media"] == [str(sources[0]), uploaded, str(sources[1])]
+ assert channel._handle_message.await_args.kwargs["metadata"]["local_media_paths"] == [str(source) for source in sources]
+ assert all(source.stat().st_size == 64 * 1024 * 1024 + 1 for source in sources)
+ assert [path for path in channel.gateway.uploads.store.media_dir.iterdir() if path.is_file()] == [Path(uploaded)]
+
+
[email protected]("persisted", [False, True])
+async def test_deleted_local_attachment_scope_never_reverts_to_default(tmp_path, monkeypatch, persisted):
+ from nanobot.security.workspace_access import default_workspace_scope
+
+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path / "data")
+ project = tmp_path / "nested"
+ project.mkdir()
+ source = tmp_path / "original.txt"
+ source.write_text("borrowed", encoding="utf-8")
+ manager = SessionManager(tmp_path)
+ channel = _make_channel(manager, workspace=tmp_path, restricted=True)
+ workspaces = channel.gateway.workspaces
+ key = "websocket:scoped-media"
+ await workspaces.stage_scope("scoped-media", default_workspace_scope(project, False))
+ if persisted:
+ await workspaces.persist_scope("scoped-media", default_workspace_scope(project, False))
+ url = channel.gateway.media.local_attachment_url(str(source), session_key=key)
+ sig, payload = url.split("/")[-2:]
+
+ def fetch():
+ return channel.gateway.http._handle_media_fetch(sig, payload)
+
+ assert bytes(fetch().body) == b"borrowed"
+ await workspaces.stage_scope("scoped-media", default_workspace_scope(project, True))
+ assert fetch().status_code == 403
+ workspaces.discard_draft_scope(key)
+ await manager.state.delete(key)
+ assert fetch().status_code == 404
+ assert source.read_text(encoding="utf-8") == "borrowed"
diff --git a/nanobot/webui/attachments.py b/nanobot/webui/attachments.py
new file mode 100644
index 000000000..c4c87fb4d
--- /dev/null
+++ b/nanobot/webui/attachments.py
@@ -0,0 +1,60 @@
+"""Read-only local attachment checks shared by WebUI and native TUI ingress."""
+
+from __future__ import annotations
+
+import mimetypes
+import os
+import stat
+from typing import Literal, TypedDict
+
+from nanobot.channels.websocket.attachment_policy import (
+ AttachmentIngressLimits,
+ validate_attachment_batch,
+)
+from nanobot.security.workspace_access import WorkspaceScope
+from nanobot.webui.file_preview import WebUIFilePreviewError, resolve_file_path
+
+
+class LocalAttachment(TypedDict):
+ path: str
+ name: str
+ size: int
+ mime: str
+ kind: Literal["image", "video", "file"]
+
+
+# Match the upload ingress formats even on hosts with different MIME registries.
+_MIME_BY_SUFFIX = {
+ ".md": "text/markdown", ".log": "text/plain", ".txt": "text/plain",
+ ".ini": "text/plain", ".cfg": "text/plain", ".csv": "text/csv",
+ ".yaml": "application/yaml", ".yml": "application/yaml", ".toml": "application/toml",
+ ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime",
+}
+
+
+def inspect_local_attachment(
+ path: str, *, scope: WorkspaceScope, limits: AttachmentIngressLimits,
+) -> LocalAttachment:
+ """Check accessibility and metadata without reading or copying the file body."""
+ resolved = resolve_file_path(path, scope=scope, literal=True)
+ try:
+ fd = os.open(resolved, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0))
+ try:
+ info = os.fstat(fd)
+ if not stat.S_ISREG(info.st_mode):
+ raise WebUIFilePreviewError(400, "attachment must be a regular file")
+ finally:
+ os.close(fd)
+ except PermissionError as exc:
+ raise WebUIFilePreviewError(403, "file is not readable") from exc
+ except OSError as exc:
+ raise WebUIFilePreviewError(404, "file is unavailable") from exc
+ if info.st_size == 0:
+ raise WebUIFilePreviewError(400, "Empty files cannot be attached")
+ mime = _MIME_BY_SUFFIX.get(resolved.suffix.lower()) or mimetypes.guess_type(resolved.name)[0] or "application/octet-stream"
+ try:
+ validate_attachment_batch([mime], limits=limits)
+ except ValueError as exc:
+ raise WebUIFilePreviewError(400, str(exc)) from exc
+ kind = "video" if mime.startswith("video/") else "image" if mime.startswith("image/") else "file"
+ return {"path": str(resolved), "name": resolved.name, "size": info.st_size, "mime": mime, "kind": kind}
diff --git a/nanobot/webui/file_preview.py b/nanobot/webui/file_preview.py
index 192084fd4..5d085939a 100644
--- a/nanobot/webui/file_preview.py
+++ b/nanobot/webui/file_preview.py
@@ -40,7 +40,7 @@ class WebUIFilePreviewError(ValueError):
def file_reference_payload(raw_path: str | None, *, scope: WorkspaceScope) -> dict[str, str | None]:
"""Resolve copyable paths through the preview policy without reading file contents."""
- resolved = _resolve_preview_path(raw_path, scope=scope)
+ resolved = resolve_file_path(raw_path, scope=scope)
try:
relative = resolved.relative_to(scope.project_path).as_posix()
except ValueError:
@@ -56,7 +56,7 @@ def file_preview_payload(
) -> dict[str, Any]:
"""Return a bounded source or raster preview within the session workspace scope."""
- resolved = _resolve_preview_path(raw_path, scope=scope)
+ resolved = resolve_file_path(raw_path, scope=scope)
try:
with open(resolved, "rb") as f:
@@ -110,7 +110,7 @@ def file_preview_availability_payload(
) -> dict[str, bool]:
"""Probe a readable source or raster candidate without loading it fully."""
- resolved = _resolve_preview_path(raw_path, scope=scope)
+ resolved = resolve_file_path(raw_path, scope=scope)
try:
with open(resolved, "rb") as f:
prefix = f.read(4096)
@@ -125,8 +125,10 @@ def file_preview_availability_payload(
return {"available": True}
-def _resolve_preview_path(raw_path: str | None, *, scope: WorkspaceScope) -> Path:
- path = _clean_preview_path(raw_path)
+def resolve_file_path(
+ raw_path: str | None, *, scope: WorkspaceScope, literal: bool = False,
+) -> Path:
+ path = (raw_path or "").strip() if literal else _clean_preview_path(raw_path)
if not path:
raise WebUIFilePreviewError(400, "missing path")
if len(path) > 4096:
@@ -145,6 +147,8 @@ def _resolve_preview_path(raw_path: str | None, *, scope: WorkspaceScope) -> Pat
raise WebUIFilePreviewError(404, "file not found") from e
except WorkspaceBoundaryError as e:
raise WebUIFilePreviewError(403, "file is outside the current workspace") from e
+ except PermissionError as e:
+ raise WebUIFilePreviewError(403, "file is not readable") from e
except OSError as e:
raise WebUIFilePreviewError(400, "invalid path") from e
diff --git a/nanobot/webui/history.py b/nanobot/webui/history.py
index 071d6fd75..406d67c56 100644
--- a/nanobot/webui/history.py
+++ b/nanobot/webui/history.py
@@ -10,6 +10,7 @@ from contextlib import closing
from pathlib import Path
from typing import Any, cast
+from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA
from nanobot.config.paths import get_webui_dir
from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind, HistoryReader
from nanobot.session.manager import SessionInfo, SessionManager
@@ -36,7 +37,7 @@ _MESSAGE_KINDS = {
}
_CONTENT_FIELDS = frozenset({
"text", "media_paths", "media", "media_urls", "reply_to", "agent_ui", "cli_apps", "mcp_presets", "session_mentions",
- "session_message", "tool_events", "edits", "source", "response_sources", "resuming",
+ "session_message", INBOUND_META_LOCAL_MEDIA, "tool_events", "edits", "source", "response_sources", "resuming",
"merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state",
"outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message",
"transcript_incomplete", "stream_id", "compaction_id", "phase", "reason",
diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py
index aad66c1f6..81941f641 100644
--- a/nanobot/webui/inbound_commands.py
+++ b/nanobot/webui/inbound_commands.py
@@ -15,7 +15,8 @@ from typing import Any, Protocol, cast
from loguru import logger
from websockets.asyncio.server import ServerConnection
-from nanobot.bus.events import INBOUND_META_USER_SHELL
+from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA, INBOUND_META_USER_SHELL
+from nanobot.channels.websocket.attachment_policy import validate_attachment_batch
from nanobot.channels.websocket.attachment_store import AttachmentUploadError
from nanobot.command.builtin import USER_SHELL_COMMAND, builtin_command_starts_agent_turn
from nanobot.runtime_context import (
@@ -39,6 +40,7 @@ from nanobot.session.webui_turns import (
)
from nanobot.utils.helpers import safe_filename
from nanobot.utils.prompt_templates import render_template
+from nanobot.webui.attachments import inspect_local_attachment
from nanobot.webui.cli_apps_api import normalize_cli_app_mentions
from nanobot.webui.file_preview import (
WebUIFilePreviewError,
@@ -238,8 +240,7 @@ class WebUICommandRouter:
*,
turn_id: str | None,
starts_turn: bool,
- media_paths: list[str],
- media_names: list[str | None],
+ media: list[dict[str, Any]],
cli_apps: list[dict[str, Any]],
mcp_presets: list[dict[str, Any]],
session_mentions: list[SessionMention],
@@ -252,10 +253,6 @@ class WebUICommandRouter:
}
if turn_id is not None:
body["turn_id"] = turn_id
- media = self._media.augment_transcript_user_media(media_paths)
- for attachment, name in zip(media, media_names, strict=False):
- if name:
- attachment["name"] = name
if media:
body["media_urls"] = media
if cli_apps:
@@ -584,6 +581,8 @@ class WebUICommandRouter:
media_paths: list[str] = []
media_names: list[str | None] = []
references: list[str] = []
+ local_paths: list[str] = []
+ attachment_order: list[tuple[bool, int]] = []
upload_owner = self._uploads.owner(connection) if raw_media else ""
try:
if not isinstance(raw_media, list):
@@ -596,13 +595,21 @@ class WebUICommandRouter:
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)
+ path = attachment.get("path")
+ if "data_url" in attachment or (reference is None) == (path is None):
+ raise AttachmentUploadError("Expected an upload reference or local path")
+ if path is not None:
+ if not isinstance(path, str) or not path or len(path) > 4096:
+ raise AttachmentUploadError("Invalid local attachment path")
+ attachment_order.append((True, len(local_paths)))
+ local_paths.append(path)
+ else:
+ if not isinstance(reference, str) or len(reference) > 64:
+ raise AttachmentUploadError("Invalid upload reference")
+ attachment_order.append((False, len(references)))
+ references.append(reference)
name = attachment.get("name")
media_names.append((safe_filename(name) or None) if isinstance(name, str) else None)
- 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),
@@ -610,7 +617,7 @@ class WebUICommandRouter:
)
return
- if not content.strip() and not media_paths:
+ if not content.strip() and not attachment_order:
await self._transport.webui_send_event(
connection,
"error",
@@ -661,7 +668,7 @@ class WebUICommandRouter:
and turn_id is not None
and turn_id.startswith(WEBUI_SYSTEM_COMMAND_TURN_PREFIX)
and content.strip().lower() == "/restart"
- and not media_paths
+ and not attachment_order
)
if restart_control:
metadata[WEBUI_RESTART_CONTROL_METADATA_KEY] = True
@@ -697,16 +704,35 @@ class WebUICommandRouter:
# persisting paths, with no intervening await, so expiry cannot remove
# files referenced by the canonical transcript.
try:
+ local = [
+ await asyncio.to_thread(
+ inspect_local_attachment, path, scope=scope, limits=self._uploads.store.limits,
+ )
+ for path in local_paths
+ ]
+ uploaded = self._uploads.store.inspect(references, owner=upload_owner) if references else []
+ validate_attachment_batch(
+ [item["mime"] for item in local] + [item.mime for item in uploaded],
+ limits=self._uploads.store.limits,
+ )
+ media_paths = [
+ local[index]["path"] if is_local else str(uploaded[index].path)
+ for is_local, index in attachment_order
+ ]
+ if len(set(media_paths)) != len(media_paths):
+ raise AttachmentUploadError("Duplicate attachment reference")
if references:
- media_paths = self._uploads.store.commit(references, owner=upload_owner)
- except AttachmentUploadError as exc:
+ self._uploads.store.commit(references, owner=upload_owner)
+ except (ValueError, WebUIFilePreviewError) as exc:
await self._transport.webui_send_event(
connection, "error", detail="attachment_rejected", reason=str(exc),
**rejection_fields,
)
return
+ if local:
+ metadata[INBOUND_META_LOCAL_MEDIA] = [item["path"] for item in local]
if temporary_policy is not None:
- self._temporary_chats.register_media(connection, chat_id, media_paths)
+ self._temporary_chats.register_media(connection, chat_id, [str(item.path) for item in uploaded])
is_webui = metadata.get("webui") is True
queued_owner = None
if is_webui and not is_user_shell and builtin_command_starts_agent_turn(content):
@@ -825,6 +851,13 @@ class WebUICommandRouter:
if not accepted and queued_owner is not None:
clear_websocket_turn_if_current(chat_id, queued_owner)
+ media = self._media.augment_transcript_user_media(
+ media_paths, local_paths=[item["path"] for item in local],
+ session_key=webui_session_key(chat_id),
+ ) if is_webui else []
+ for attachment, name in zip(media, media_names, strict=False):
+ if name:
+ attachment["name"] = name
if is_webui and not restart_control:
await self.broadcast_user_message(
connection,
@@ -832,8 +865,7 @@ class WebUICommandRouter:
content,
turn_id=turn_id,
starts_turn=queued_owner is not None,
- media_paths=media_paths,
- media_names=media_names,
+ media=media,
cli_apps=cli_apps,
mcp_presets=mcp_presets,
session_mentions=session_mentions,
@@ -847,6 +879,7 @@ class WebUICommandRouter:
chat_id=chat_id,
turn_id=turn_id,
starts_turn=queued_owner is not None,
+ **({"media_urls": media} if media else {}),
**(
{"active_turn_id": active_turn_id}
if active_turn_id is not None
@@ -906,6 +939,46 @@ class WebUICommandRouter:
)
return
+ payload = cast(dict[str, Any], payload)
+ if action == "attachment.inspect":
+ # Read-only and connection-scoped: never retain filesystem results in
+ # the mutation replay cache. Send admission always checks again.
+ chat_id, path = payload.get("chat_id"), payload.get("path")
+ if (chat_id is not None and not is_valid_webui_chat_id(chat_id)) or not isinstance(path, str):
+ await self.send_webui_response(
+ connection, request_id, status=400, message="invalid attachment request",
+ )
+ return
+ try:
+ if chat_id is None:
+ scope = await self._workspaces.scope_for_new_chat(
+ payload, can_change_project=self.workspace_project_selection_available(connection),
+ )
+ else:
+ policy = self._temporary_chats.message_policy(connection, chat_id, "")
+ scope = policy.workspace_scope if policy is not None else (
+ await self._workspaces.scope_for_message(
+ payload, chat_id=chat_id,
+ chat_running=websocket_turn_wall_started_at(chat_id) is not None,
+ can_change_project=self.workspace_project_selection_available(connection),
+ )
+ )
+ result = await asyncio.to_thread(
+ inspect_local_attachment, path, scope=scope, limits=self._uploads.store.limits,
+ )
+ except (TemporaryChatError, WorkspaceScopeError, WebUIFilePreviewError) as exc:
+ await self.send_webui_response(
+ connection, request_id, status=getattr(exc, "status", 404), message=str(exc),
+ )
+ else:
+ await self.send_webui_response(
+ connection, request_id,
+ result={**result, "url": self._media.local_attachment_url(
+ result["path"], session_key=webui_session_key(chat_id),
+ ) if chat_id is not None else ""},
+ )
+ return
+
if action == "temporary_chat.file_preview":
# Connection-owned, read-only, and deliberately outside the mutation
# replay cache: private paths/content must not outlive this request.
@@ -972,7 +1045,7 @@ class WebUICommandRouter:
self.execute_webui_request(
connection,
action,
- cast(dict[str, Any], payload),
+ payload,
)
)
new_operation = WebUIRequestOperation(
diff --git a/nanobot/webui/media_api.py b/nanobot/webui/media_api.py
index 14e3c949b..f1fc48081 100644
--- a/nanobot/webui/media_api.py
+++ b/nanobot/webui/media_api.py
@@ -6,6 +6,7 @@ import base64
import binascii
import hashlib
import hmac
+import json
import mimetypes
import os
import re
@@ -13,13 +14,15 @@ import shutil
import uuid
from collections.abc import Callable
from pathlib import Path
-from typing import Any
+from typing import Any, cast
from websockets.http11 import Request as WsRequest
from websockets.http11 import Response
from nanobot.config.paths import get_media_dir
+from nanobot.security.workspace_access import WorkspaceScope
from nanobot.utils.helpers import safe_filename
+from nanobot.webui.file_preview import WebUIFilePreviewError, resolve_file_path
from nanobot.webui.http_utils import (
case_insensitive_header as _case_insensitive_header,
)
@@ -115,6 +118,13 @@ def sign_media_path(
return f"/api/media/{b64url_encode(mac)}/{payload}"
+def sign_local_attachment(path: str, *, session_key: str, secret: bytes) -> str:
+ """Bind a borrowed path to its session; serving rechecks the current scope."""
+ payload = b64url_encode(b"\0" + json.dumps([session_key, path], ensure_ascii=False).encode("utf-8"))
+ mac = hmac.new(secret, payload.encode("ascii"), hashlib.sha256).digest()[:16]
+ return f"/api/media/{b64url_encode(mac)}/{payload}"
+
+
def sign_or_stage_media_path(
path: Path,
*,
@@ -196,6 +206,7 @@ def serve_signed_media(
secret: bytes,
request: WsRequest | None = None,
media_dir: MediaDirProvider = _default_media_dir,
+ scope_for_session: Callable[[str], WorkspaceScope | None] | None = None,
) -> Response:
"""Serve a signed media URL, including browser-friendly byte ranges."""
try:
@@ -210,21 +221,45 @@ def serve_signed_media(
rel_str = rel_bytes.decode("utf-8")
except (ValueError, binascii.Error, UnicodeDecodeError):
return _http_error(400, "invalid payload")
- try:
- media_root = media_dir(None).resolve()
- candidate = (media_root / rel_str).resolve()
- candidate.relative_to(media_root)
- except (OSError, ValueError):
- return _http_error(404, "not found")
- if not candidate.is_file():
- return _http_error(404, "not found")
+ # NUL cannot start a legacy filesystem-relative path.
+ borrowed = rel_str.startswith("\0")
+ if borrowed:
+ try:
+ raw_reference: object = json.loads(rel_str[1:])
+ if not isinstance(raw_reference, list) or scope_for_session is None:
+ return _http_error(400, "invalid local attachment")
+ reference = cast(list[object], raw_reference)
+ if len(reference) != 2:
+ return _http_error(400, "invalid local attachment")
+ session_key, path = reference
+ if not isinstance(session_key, str) or not isinstance(path, str):
+ return _http_error(400, "invalid local attachment")
+ scope = scope_for_session(session_key)
+ if scope is None:
+ return _http_error(404, "attachment unavailable")
+ candidate = resolve_file_path(path, scope=scope, literal=True)
+ except (ValueError, WebUIFilePreviewError) as exc:
+ return _http_error(getattr(exc, "status", 404), "attachment unavailable")
+ else:
+ try:
+ media_root = media_dir(None).resolve()
+ candidate = (media_root / rel_str).resolve()
+ candidate.relative_to(media_root)
+ except (OSError, ValueError):
+ return _http_error(404, "not found")
+ if not candidate.is_file():
+ return _http_error(404, "not found")
+
+ return _serve_media_file(candidate, request=request, borrowed=borrowed)
+
+def _serve_media_file(candidate: Path, *, request: WsRequest | None, borrowed: bool) -> Response:
mime, _ = mimetypes.guess_type(candidate.name)
if mime not in _MEDIA_ALLOWED_MIMES:
mime = "application/octet-stream"
common_headers = [
("Accept-Ranges", "bytes"),
- ("Cache-Control", "private, max-age=31536000, immutable"),
+ ("Cache-Control", "no-store" if borrowed else "private, max-age=31536000, immutable"),
("X-Content-Type-Options", "nosniff"),
]
if mime == "image/svg+xml":
diff --git a/nanobot/webui/media_gateway.py b/nanobot/webui/media_gateway.py
index be7b260cc..07bf8e8ad 100644
--- a/nanobot/webui/media_gateway.py
+++ b/nanobot/webui/media_gateway.py
@@ -11,8 +11,12 @@ from websockets.http11 import Request as WsRequest
from websockets.http11 import Response
from nanobot.config.paths import get_media_dir
+from nanobot.security.workspace_access import WorkspaceScope
from nanobot.webui.media_api import (
+ media_attachment_kind,
serve_signed_media,
+ sign_local_attachment,
+ sign_media_path,
sign_or_stage_media_path,
signed_media_attachments,
)
@@ -45,6 +49,7 @@ class WebUIMediaGateway:
payload: str,
*,
request: WsRequest | None = None,
+ scope_for_session: Callable[[str], WorkspaceScope | None] | None = None,
) -> Response:
return serve_signed_media(
sig,
@@ -52,6 +57,7 @@ class WebUIMediaGateway:
secret=self.secret,
request=request,
media_dir=self._media_dir,
+ scope_for_session=scope_for_session,
)
def sign_or_stage_media_path(self, path: Path) -> dict[str, str] | None:
@@ -80,5 +86,19 @@ class WebUIMediaGateway:
sign_path=self.sign_or_stage_media_path,
)
- def augment_transcript_user_media(self, paths: list[str]) -> list[dict[str, Any]]:
- return self.augment_transcript_media(paths)
+ def local_attachment_url(self, path: str, *, session_key: str) -> str:
+ return sign_local_attachment(path, session_key=session_key, secret=self.secret)
+
+ def augment_transcript_user_media(
+ self, paths: list[str], local_paths: list[str], *, session_key: str,
+ ) -> list[dict[str, Any]]:
+ local = set(local_paths)
+ media: list[dict[str, Any]] = []
+ for raw in paths:
+ path = Path(raw)
+ if raw in local:
+ url = self.local_attachment_url(raw, session_key=session_key) if path.is_file() else ""
+ else:
+ url = sign_media_path(path, secret=self.secret, media_dir=self._media_dir) or ""
+ media.append({"kind": media_attachment_kind(path.name), "name": path.name, "url": url})
+ return media
diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py
index 88c49e052..0d72abc73 100644
--- a/nanobot/webui/transcript.py
+++ b/nanobot/webui/transcript.py
@@ -21,7 +21,7 @@ from urllib.parse import unquote, urlparse
from loguru import logger
-from nanobot.bus.events import INBOUND_META_TURN_ID
+from nanobot.bus.events import INBOUND_META_LOCAL_MEDIA, INBOUND_META_TURN_ID
from nanobot.runtime_context import public_history_message
from nanobot.session.automation_turns import is_automation_kind
from nanobot.session.display_history import (
@@ -577,8 +577,15 @@ class WebUITranscriptRecorder:
) -> bool:
if text.strip() == "/stop" and not media_paths:
return False
- event = build_user_transcript_event(chat_id, text, media_paths=media_paths,
- cli_apps=cli_apps, mcp_presets=mcp_presets, session_mentions=session_mentions)
+ event = build_user_transcript_event(
+ chat_id,
+ text,
+ media_paths=media_paths,
+ local_media_paths=_local_media_paths(metadata),
+ cli_apps=cli_apps,
+ mcp_presets=mcp_presets,
+ session_mentions=session_mentions,
+ )
if event is None:
return False
return await self.prepare_and_append(chat_id, event, metadata=metadata, phase="user")
@@ -689,11 +696,17 @@ def normalize_session_message_ui_metadata(raw: object) -> dict[str, Any] | None:
}
+def _local_media_paths(record: Mapping[str, Any]) -> list[str]:
+ raw = record.get(INBOUND_META_LOCAL_MEDIA)
+ return [path for path in cast(list[object], raw) if isinstance(path, str)] if isinstance(raw, list) else []
+
+
def build_user_transcript_event(
chat_id: str,
text: str,
*,
media_paths: list[Any] | None = None,
+ local_media_paths: list[str] | None = None,
cli_apps: list[Any] | None = None,
mcp_presets: list[Any] | None = None,
session_mentions: Sequence[Any] | None = None,
@@ -708,6 +721,9 @@ def build_user_transcript_event(
}
if paths:
event["media_paths"] = paths
+ local = [path for path in (local_media_paths or []) if path in paths]
+ if local:
+ event[INBOUND_META_LOCAL_MEDIA] = local
apps = [
dict(cast(Mapping[str, Any], app))
for app in (cli_apps or [])
@@ -765,6 +781,7 @@ def _session_user_event(
chat_id,
text,
media_paths=cast(list[Any], media) if isinstance(media, list) else None,
+ local_media_paths=_local_media_paths(message),
cli_apps=cast(list[Any], cli_apps) if isinstance(cli_apps, list) else None,
mcp_presets=cast(list[Any], mcp_presets) if isinstance(mcp_presets, list) else None,
session_mentions=(
@@ -983,7 +1000,7 @@ def _transcript_turn_signature(records: list[dict[str, Any]]) -> tuple[str, ...]
def _user_recovery_signature(event: dict[str, Any]) -> str:
fields = {
key: event[key]
- for key in ("text", "media_paths", "cli_apps", "mcp_presets", "session_mentions", "session_message")
+ for key in ("text", "media_paths", INBOUND_META_LOCAL_MEDIA, "cli_apps", "mcp_presets", "session_mentions", "session_message")
if key in event
}
return json.dumps(fields, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
@@ -1367,7 +1384,7 @@ def _client_projection_source(record: dict[str, Any]) -> dict[str, Any] | None:
def _client_projection_event(
record: dict[str, Any],
*,
- augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None,
+ augment_user_media: Callable[[list[str], list[str]], list[dict[str, Any]]] | None,
augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None,
augment_assistant_text: Callable[[str], str] | None,
) -> dict[str, Any] | None:
@@ -1389,7 +1406,7 @@ def _client_projection_event(
if path
] if isinstance(raw_paths, list) else []
if paths and augment_user_media is not None:
- media = augment_user_media(paths)
+ media = augment_user_media(paths, _local_media_paths(record))
if media:
projected["media_urls"] = media
for source_key, target_key in (
@@ -1603,7 +1620,7 @@ def _client_projection_page_event_count(turn: list[dict[str, Any]]) -> int:
def _client_projection_events(
lines: list[dict[str, Any]],
*,
- augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None,
+ augment_user_media: Callable[[list[str], list[str]], list[dict[str, Any]]] | None,
augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None,
augment_assistant_text: Callable[[str], str] | None,
) -> tuple[list[dict[str, Any]], int | None]:
@@ -1658,7 +1675,7 @@ def build_session_thread_response(
*,
active: bool = False,
latency_ms: int | None = None,
- augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
+ augment_user_media: Callable[[list[str], list[str]], list[dict[str, Any]]] | None = None,
augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
augment_assistant_text: Callable[[str], str] | None = None,
) -> dict[str, Any]:
@@ -1727,7 +1744,7 @@ def build_webui_thread_response(
session_key: str,
*,
history: HistoryReader,
- augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
+ augment_user_media: Callable[[list[str], list[str]], list[dict[str, Any]]] | None = None,
augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
augment_assistant_text: Callable[[str], str] | None = None,
session_messages: list[dict[str, Any]] | None = None,
diff --git a/nanobot/webui/workspaces.py b/nanobot/webui/workspaces.py
index c169d7c51..a38e2d589 100644
--- a/nanobot/webui/workspaces.py
+++ b/nanobot/webui/workspaces.py
@@ -279,14 +279,21 @@ class WebUIWorkspaceController:
return self._scope_from_metadata_value(raw_scope, default_scope=default_scope)
def scope_for_session_key(self, session_key: str) -> WorkspaceScope:
+ return self.existing_scope_for_session_key(session_key) or self.default_scope()
+
+ def existing_scope_for_session_key(self, session_key: str) -> WorkspaceScope | None:
+ """Resolve live authority without turning a deleted session into a default scope."""
draft = self._draft_scopes.get(session_key)
if draft is not None:
self._draft_scopes.move_to_end(session_key)
return draft
if self._sessions is None:
- return self.default_scope()
+ return None
+ identity = self._sessions.state.peek_identity(session_key)
+ if identity is not None and not identity.policy.persist:
+ return self.restricted_default_scope()
data = self._sessions.read_session_metadata(session_key)
- return self._scope_from_snapshot(data)
+ return self._scope_from_snapshot(data) if data is not None else None
async def async_scope_for_session_key(self, session_key: str) -> WorkspaceScope:
draft = self._draft_scopes.get(session_key)
diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py
index 3f7311ea3..3656c60cc 100644
--- a/nanobot/webui/ws_http.py
+++ b/nanobot/webui/ws_http.py
@@ -949,7 +949,7 @@ class GatewayHTTPHandler:
active=status.state in {"queued", "running", "stopping"},
latency_ms=(int(max(0.0, status.finished_at - status.started_at) * 1000)
if status.finished_at is not None else None),
- augment_user_media=self.media.augment_transcript_media,
+ augment_user_media=lambda paths, local: self.media.augment_transcript_user_media(paths, local, session_key=session_key),
augment_assistant_media=self.media.augment_transcript_media,
augment_assistant_text=lambda text: self.media.rewrite_local_markdown_images(
text, workspace_path=scope.project_path,
@@ -1262,7 +1262,7 @@ class GatewayHTTPHandler:
replay_stats = diagnostics.transcript if diagnostics is not None else TranscriptReplayStats()
data = build_webui_thread_response(
decoded_key, history=history,
- augment_user_media=self.media.augment_transcript_media,
+ augment_user_media=lambda paths, local: self.media.augment_transcript_user_media(paths, local, session_key=decoded_key),
augment_assistant_media=self.media.augment_transcript_media,
augment_assistant_text=lambda text: self.media.rewrite_local_markdown_images(
text,
@@ -1682,6 +1682,7 @@ class GatewayHTTPHandler:
sig,
payload,
request=request,
+ scope_for_session=self.workspaces.existing_scope_for_session_key,
)
# -- Misc routes --------------------------------------------------------
diff --git a/packages/client-events/attachments.ts b/packages/client-events/attachments.ts
index 0cef843ca..b0c3a074a 100644
--- a/packages/client-events/attachments.ts
+++ b/packages/client-events/attachments.ts
@@ -1,6 +1,79 @@
-/** 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 }
+/** Preview bodies upload over HTTP; borrowed paths never upload file bytes. */
+export interface LocalAttachment {
+ path: string;
+ name: string;
+ size: number;
+ mime: string;
+ kind: "image" | "video" | "file";
+ url: string;
+}
+export function isLocalAttachment(value: unknown): value is LocalAttachment {
+ if (!value || typeof value !== "object") return false;
+ const row = value as Record<string, unknown>;
+ return typeof row.path === "string" && row.path.length > 0 && row.path.length <= 4096
+ && typeof row.name === "string" && typeof row.mime === "string"
+ && typeof row.size === "number" && Number.isSafeInteger(row.size) && row.size > 0
+ && typeof row.kind === "string" && ["image", "video", "file"].includes(row.kind)
+ && typeof row.url === "string" && (row.url === "" || row.url.startsWith("/api/media/"));
+}
+export type DraftAttachment =
+ | { data_url: string; name?: string; path?: never }
+ | { path: string; name?: string; data_url?: never };
+export type AttachmentReference =
+ | { reference: string; name?: string; path?: never }
+ | { path: string; name?: string; reference?: never };
+
+/** Recognize only a standalone pasted path, never search prose/code for one. */
+export function pastedFilePath(text: string): string | null {
+ let value = text.trim();
+ if (!value || /[\r\n\0]/.test(value)) return null;
+ const quoted = (value.startsWith('"') && value.endsWith('"'))
+ || (value.startsWith("'") && value.endsWith("'"));
+ if (quoted) value = value.slice(1, -1);
+ if (!value || /["`<>|]/.test(value) || /^[a-z][a-z\d+.-]*:\/\//i.test(value)
+ || /^[a-z]:[\\/]fakepath[\\/]/i.test(value)) return null;
+ if (/^(?:[a-z]:[\\/]|\/|\\\\|\.{1,2}[\\/]|~[\\/])/i.test(value)) return value;
+ // Bare relative names and relative directory paths; whitespace needs quotes.
+ return (quoted || !/\s/.test(value)) && /(?:[\\/]|\.[\w-]+$)/u.test(value)
+ ? value : null;
+}
+/** One in-flight paste owns only its original text range, not the whole composer. */
+export class PastedPathRange {
+ private valid = true;
+
+ constructor(private value: string, private start: number, private end: number) {}
+
+ update(next: string): boolean {
+ if (!this.valid || next === this.value) return this.valid;
+ let start = 0;
+ while (start < this.value.length && start < next.length && this.value[start] === next[start]) start += 1;
+ let oldEnd = this.value.length;
+ let newEnd = next.length;
+ while (oldEnd > start && newEnd > start && this.value[oldEnd - 1] === next[newEnd - 1]) {
+ oldEnd -= 1;
+ newEnd -= 1;
+ }
+ if (oldEnd <= this.start) {
+ const shift = newEnd - oldEnd;
+ this.start += shift;
+ this.end += shift;
+ } else if (start < this.end) {
+ this.valid = false;
+ }
+ this.value = next;
+ return this.valid;
+ }
+
+ replace(text: string, cursor: number): { value: string; cursor: number } | null {
+ if (!this.valid) return null;
+ const shift = text.length - (this.end - this.start);
+ return {
+ value: this.value.slice(0, this.start) + text + this.value.slice(this.end),
+ cursor: cursor <= this.start ? cursor : cursor >= this.end ? cursor + shift : this.start + text.length,
+ };
+ }
+}
+
export interface UploadCapability { path: string; token: string }
// Allow the gateway's five-minute body budget plus request/response overhead.
@@ -17,16 +90,20 @@ 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");
- // Send same-origin edge-auth cookies without following redirects with 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");
+ if (draft.path !== undefined) {
+ references.push({ path: draft.path, ...(draft.name ? { name: draft.name } : {}) });
+ continue;
+ }
+ if (!capability) 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");
+ // Never send capabilities across redirects or forward URL credentials.
+ url.search = "";
+ url.username = "";
+ url.password = "";
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]);
diff --git a/pyproject.toml b/pyproject.toml
index 1a61e67e7..9ea93b9b8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -105,6 +105,7 @@ dev = [
"pytest-xdist>=3.8.0,<4.0.0",
"ruff>=0.1.0",
"basedpyright>=1.39.0,<2.0.0",
+ "setproctitle>=1.3.7,<2.0.0",
"pymupdf>=1.25.0",
"pypdf>=5.0.0,<6.0.0",
"python-docx>=1.1.0,<2.0.0",
diff --git a/tests/agent/test_attachment_references.py b/tests/agent/test_attachment_references.py
index d2c5fdca3..83f13bf15 100644
--- a/tests/agent/test_attachment_references.py
+++ b/tests/agent/test_attachment_references.py
@@ -213,3 +213,52 @@ def test_attachment_references_canonicalize_existing_relative_paths(
assert media == [str(image_path.resolve())]
assert f"[Attachment: {doc_path.resolve()}]" in content
+
+
+async def test_borrowed_image_origin_survives_canonical_reload(tmp_path: Path) -> None:
+ from nanobot.webui.transcript import build_session_thread_response
+
+ source = tmp_path / "borrowed.png"
+ source.write_bytes(base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+yF9kAAAAASUVORK5CYII="
+ ))
+ loop = _make_loop(tmp_path)
+ loop._run_agent_loop = AsyncMock(side_effect=RuntimeError("interrupt"))
+ message = InboundMessage(
+ channel="websocket", sender_id="u", chat_id="borrowed-origin", content="look",
+ media=[str(source)], metadata={"local_media_paths": [str(source)]},
+ )
+ with pytest.raises(RuntimeError, match="interrupt"):
+ await loop._process_message(message)
+ loop.sessions.invalidate(message.session_key)
+ persisted = loop.sessions.get_or_create(message.session_key)
+ assert persisted.messages[0]["local_media_paths"] == [str(source)]
+ augment = MagicMock(return_value=[{"kind": "image", "url": "/borrowed"}])
+ response = build_session_thread_response(persisted, augment_user_media=augment)
+ augment.assert_called_once_with([str(source)], [str(source)])
+ assert response["events"][0]["media_urls"][0]["url"] == "/borrowed"
+
+
+async def test_image_path_remains_visible_once_after_session_reload(tmp_path: Path) -> None:
+ image = tmp_path / "original.png"
+ image.write_bytes(base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+yF9kAAAAASUVORK5CYII="
+ ))
+ loop = _make_loop(tmp_path)
+ loop.provider.aclose = AsyncMock()
+ try:
+ await loop.process_direct("edit this image", session_key="websocket:image-reference", channel="websocket", chat_id="image-reference", media=[str(image)])
+ initial = loop.provider.chat_stream_with_retry.call_args.kwargs["messages"]
+ current = initial[-1]["content"]
+ assert any(block.get("type") == "image_url" for block in current)
+ assert sum(block.get("text", "").count(str(image)) for block in current) == 1
+ loop.sessions.invalidate("websocket:image-reference")
+ await loop.process_direct("which file was that?", session_key="websocket:image-reference", channel="websocket", chat_id="image-reference")
+ following = loop.provider.chat_stream_with_retry.call_args.kwargs["messages"]
+ previous = next(message["content"] for message in following if message["role"] == "user")
+ previous_text = previous if isinstance(previous, str) else "\n".join(block.get("text", "") for block in previous)
+ assert previous_text.count(str(image)) == 1
+ finally:
+ await loop.aclose()
diff --git a/tests/agent/test_context_builder.py b/tests/agent/test_context_builder.py
index 725cfbd70..de125a1a0 100644
--- a/tests/agent/test_context_builder.py
+++ b/tests/agent/test_context_builder.py
@@ -260,19 +260,36 @@ class TestBuildUserContent:
builder = _builder(tmp_path)
result = builder.build_user_content("hello", [str(png)])
assert isinstance(result, list)
- assert len(result) == 2
- assert result[0]["type"] == "image_url"
- assert result[0]["image_url"]["url"].startswith("data:image/png;base64,")
- assert result[1]["type"] == "text"
- assert result[1]["text"] == "hello"
+ assert len(result) == 3
+ assert result[0] == {"type": "text", "text": f"[image: {png}]"}
+ assert result[1]["type"] == "image_url"
+ assert result[1]["image_url"]["url"].startswith("data:image/png;base64,")
+ assert result[2]["type"] == "text"
+ assert result[2]["text"] == "hello"
+
+ def test_images_keep_paired_paths_in_provider_visible_content(self, tmp_path):
+ from nanobot.providers.base import LLMProvider
+ from nanobot.providers.openai_responses.converters import convert_user_message
+
+ paths = [tmp_path / "original.png", tmp_path / "uploaded.png"]
+ for index, path in enumerate(paths):
+ path.write_bytes(b"\x89PNG\r\n\x1a\n" + bytes([index]) * 16)
+ content = _builder(tmp_path).build_user_content("compare these", [str(path) for path in paths])
+ clean = LLMProvider._sanitize_empty_content([{"role": "user", "content": content}])[0]
+ converted = convert_user_message(clean["content"])["content"]
+ image_indexes = [index for index, block in enumerate(converted) if block["type"] == "input_image"]
+ assert len(image_indexes) == 2
+ for index, path in zip(image_indexes, paths, strict=True):
+ assert index > 0
+ assert converted[index - 1] == {"type": "input_text", "text": f"[image: {path}]"}
+ assert converted[-1] == {"type": "input_text", "text": "compare these"}
def test_image_meta_includes_path(self, tmp_path):
png = tmp_path / "test.png"
png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 16)
builder = _builder(tmp_path)
result = builder.build_user_content("hello", [str(png)])
- assert "_meta" in result[0]
- assert "path" in result[0]["_meta"]
+ assert result[1]["_meta"]["path"] == str(png)
# ---------------------------------------------------------------------------
diff --git a/tests/channels/test_scheduled_delivery.py b/tests/channels/test_scheduled_delivery.py
index 813775b99..262574bc7 100644
--- a/tests/channels/test_scheduled_delivery.py
+++ b/tests/channels/test_scheduled_delivery.py
@@ -4,6 +4,7 @@ import asyncio
import json
import os
import sqlite3
+import subprocess
from functools import partial
from unittest.mock import AsyncMock, MagicMock
@@ -359,7 +360,9 @@ async def test_recovery_rechecks_attachment_workspace_boundary(tmp_path):
manager = make_manager(tmp_path, sessions)
manager.config.agents.defaults.workspace = str(workspace)
manager.config.tools.restrict_to_workspace = True
- attachment = workspace / "report.txt"
+ reports = workspace / "reports"
+ reports.mkdir()
+ attachment = reports / "report.txt"
attachment.write_text("report")
msg = message(generation=session.generation)
msg.media = [str(attachment)]
@@ -367,9 +370,19 @@ async def test_recovery_rechecks_attachment_workspace_boundary(tmp_path):
try:
await manager.bus.publish_outbound(msg)
attachment.unlink()
- private = tmp_path / "private.txt"
- private.write_text("not authorized")
- attachment.symlink_to(private)
+ reports.rmdir()
+ private = tmp_path / "private"
+ private.mkdir()
+ (private / "report.txt").write_text("not authorized")
+ if os.name == "nt":
+ # Directory junctions resolve across the same workspace boundary
+ # without requiring Windows' privileged symlink capability.
+ subprocess.run(
+ ["cmd", "/c", "mklink", "/J", str(reports), str(private)],
+ check=True, capture_output=True,
+ )
+ else:
+ reports.symlink_to(private, target_is_directory=True)
await manager._send_scheduled(channel, msg)
channel.send.assert_not_called()
assert rows(manager._outbox)[0]["error"] == "attachment_access_denied"
diff --git a/tests/providers/test_internal_streaming.py b/tests/providers/test_internal_streaming.py
index ae8339417..606a7193f 100644
--- a/tests/providers/test_internal_streaming.py
+++ b/tests/providers/test_internal_streaming.py
@@ -2,7 +2,7 @@
import asyncio
import json
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Awaitable, Callable
import httpx
import pytest
@@ -27,6 +27,7 @@ class _EventStream(httpx.AsyncByteStream):
self.events = events
self.stall_at = stall_at
self.event_delay = event_delay
+ self.sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
self.closed = False
async def __aiter__(self) -> AsyncIterator[bytes]:
@@ -34,7 +35,7 @@ class _EventStream(httpx.AsyncByteStream):
if index == self.stall_at:
await asyncio.Event().wait()
if self.event_delay:
- await asyncio.sleep(self.event_delay)
+ await self.sleep(self.event_delay)
yield f"data: {json.dumps(event)}\n\n".encode()
async def aclose(self) -> None:
@@ -117,9 +118,22 @@ async def make_provider(monkeypatch):
@pytest.mark.parametrize("api", ["chat", "responses", "azure"])
@pytest.mark.parametrize("kind", ["content", "reasoning", "tool", "metadata"])
-async def test_silent_stream_renews_idle_timeout_on_every_event(make_provider, api, kind):
+async def test_silent_stream_renews_idle_timeout_on_every_event(
+ make_provider, monkeypatch, api, kind,
+):
provider, stream = await make_provider(api, kind, event_delay=0.05, idle_timeout=0.3)
+ loop = asyncio.get_running_loop()
+ started_at = now = loop.time()
+ monkeypatch.setattr(loop, "time", lambda: now)
+
+ async def advance_time(delay: float) -> None:
+ nonlocal now
+ now += delay
+ await asyncio.sleep(0)
+
+ stream.sleep = advance_time
response = await provider.chat_stream_with_retry([{"role": "user", "content": "work"}])
+ assert now - started_at > 0.3
assert response.finish_reason == "stop"
assert response.content is not None and response.content.strip().endswith("done")
assert stream.closed
diff --git a/tests/providers/test_openai_codex_websocket.py b/tests/providers/test_openai_codex_websocket.py
index f9cc6b7ad..d9e322c6d 100644
--- a/tests/providers/test_openai_codex_websocket.py
+++ b/tests/providers/test_openai_codex_websocket.py
@@ -266,6 +266,10 @@ async def test_gateway_continues_image_then_pdf_attachment_turn(codex_peer, tmp_
assert len(server.requests) == 2
initial, continued = [body for _, body in server.requests]
assert "input_image" in json.dumps(initial["input"])
+ assert any(
+ block.get("type") == "input_text" and str(image) in block["text"]
+ for item in initial["input"] for block in item.get("content", [])
+ )
assert continued["previous_response_id"] == "resp_1"
assert "input_image" not in json.dumps(continued["input"])
assert f"[Attachment: {pdf}]" in continued["input"][0]["content"][0]["text"]
diff --git a/tests/tools/test_rg_tool.py b/tests/tools/test_rg_tool.py
index b1794414c..2f54f2845 100644
--- a/tests/tools/test_rg_tool.py
+++ b/tests/tools/test_rg_tool.py
@@ -213,11 +213,10 @@ async def test_direct_process_cancellation_reaps_child(tmp_path, monkeypatch):
async def test_direct_search_uses_configured_path(tmp_path, monkeypatch):
installed = shutil.which("rg")
assert installed
- bin_dir = tmp_path / "custom bin"
- bin_dir.mkdir()
- shutil.copy2(installed, bin_dir / ("rg.exe" if sys.platform == "win32" else "rg"))
+ # Keep installed launchers with their adjacent files (e.g. Scoop's .shim).
+ bin_dir = os.path.dirname(installed)
monkeypatch.setenv("PATH", "")
- result = await RgTool(working_dir=str(tmp_path), path_prepend=str(bin_dir)).execute(
+ result = await RgTool(working_dir=str(tmp_path), path_prepend=bin_dir).execute(
args=["--version"],
)
assert "ripgrep" in result
diff --git a/tests/webui/test_remote_discovery.py b/tests/webui/test_remote_discovery.py
index 253008aa3..9e2b18894 100644
--- a/tests/webui/test_remote_discovery.py
+++ b/tests/webui/test_remote_discovery.py
@@ -1,6 +1,7 @@
"""Remote setup discovers metadata, not secrets, and never invents sudo access."""
import asyncio
+import getpass
import json
import os
import subprocess
@@ -19,6 +20,13 @@ if sys.platform != "win32":
import pwd
[email protected](autouse=True)
+def local_probe_user(monkeypatch):
+ # The probe runs over SSH on Unix in production; its local Windows harness
+ # must not depend on the test runner's optional username environment.
+ monkeypatch.setattr(getpass, "getuser", lambda: "probe-user")
+
+
def locate(monkeypatch, capsys, path, units="", properties=""):
calls = []
diff --git a/tui/src/app/app.ts b/tui/src/app/app.ts
index 093eacfd2..848510650 100644
--- a/tui/src/app/app.ts
+++ b/tui/src/app/app.ts
@@ -1,3 +1,4 @@
+import { pastedFilePath, PastedPathRange } from "../../../packages/client-events/attachments"
import {
BoxRenderable,
CliRenderEvents,
@@ -221,6 +222,8 @@ export class NanobotTui {
private apiRefreshPromise: Promise<GatewayApiConnection> | null = null
private skillLoadId = 0
private clipboardImagePending = false
+ private pathInspection: PastedPathRange | null = null
+ private get pathInspectionPending(): boolean { return this.pathInspection !== null }
private clipboardPasteGeneration = 0
private composerValue = ""
private composerCursor = 0
@@ -508,6 +511,10 @@ export class NanobotTui {
private submit(): void {
if (this.quitting || this.composer.isDestroyed) return
const visibleContent = this.composer.plainText.trim()
+ if (this.pathInspectionPending) {
+ this.status.content = "Checking local attachment…"
+ return
+ }
if (this.sessionLoading) {
this.status.content = "Loading sessions…"
return
@@ -564,7 +571,7 @@ export class NanobotTui {
}
const command = this.commandMenu.resolve(visibleContent)
if ((command || visibleContent.startsWith("!")) && this.draft.media(visibleContent).length) {
- this.status.content = "Remove the image before running a command."
+ this.status.content = "Remove attachments before running a command."
return
}
if (command?.source === "tui") {
@@ -607,7 +614,7 @@ export class NanobotTui {
this.attachmentSendPending = true
const originalText = this.composer.plainText
const chatId = this.client.activeChatId
- this.status.content = "Uploading attachments…"
+ this.status.content = "Sending 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)
@@ -1246,10 +1253,7 @@ export class NanobotTui {
this.status.content = "Duplicate image placeholder. Rename or remove it before sending."
return false
}
- if (!this.hasPrompt(prompt)) return false
- if ((prompt.options.media?.length || 0) <= MAX_DRAFT_IMAGES) return true
- this.status.content = `Remove images until ${MAX_DRAFT_IMAGES} or fewer remain`
- return false
+ return this.hasPrompt(prompt)
}
private restoreQueuedPrompts(): void {
@@ -1264,7 +1268,7 @@ export class NanobotTui {
if (!this.activeTurn || !this.ready) return
const visibleContent = this.composer.plainText.trim()
if (this.draft.media(visibleContent).length) {
- this.status.content = "Images cannot be queued. Press Enter to send now."
+ this.status.content = "Attachments cannot be queued. Press Enter to send now."
return
}
if (this.commandMenu.resolve(visibleContent)?.source === "tui") {
@@ -1874,6 +1878,11 @@ export class NanobotTui {
value = edit.value
cursor = edit.cursor
}
+ if (this.pathInspection && !this.pathInspection.update(value)) {
+ this.pathInspection = null
+ if (this.activeTurn) this.renderActiveStatus()
+ else this.status.content = this.ready ? this.readyStatus() : this.connectionMessage
+ }
this.composerValue = value
this.composerCursor = cursor
this.draft.prune(value)
@@ -1933,6 +1942,7 @@ export class NanobotTui {
private setComposer(content: string): void {
this.clipboardPasteGeneration += 1
+ this.pathInspection = null
this.draft.clear()
this.composer.setText(content)
this.composer.cursorOffset = content.length
@@ -1945,10 +1955,6 @@ export class NanobotTui {
private async pasteClipboardImage(): Promise<void> {
if (this.clipboardImagePending) return
- if (this.draft.imageCount >= MAX_DRAFT_IMAGES) {
- this.status.content = `A message can include up to ${MAX_DRAFT_IMAGES} images`
- return
- }
const generation = this.clipboardPasteGeneration
this.clipboardImagePending = true
this.status.content = "Reading clipboard image…"
@@ -1957,7 +1963,7 @@ export class NanobotTui {
if (this.quitting || generation !== this.clipboardPasteGeneration) return
const insertion = this.draft.image(image, this.composer.plainText)
if (!insertion) {
- this.status.content = `A message can include up to ${MAX_DRAFT_IMAGES} images`
+ this.status.content = `A message can include up to ${MAX_DRAFT_IMAGES} images or files`
return
}
this.composer.insertText(insertion.text)
@@ -1981,6 +1987,41 @@ export class NanobotTui {
private handlePaste(event: PasteEvent): void {
event.preventDefault()
const value = stripAnsiSequences(decodePasteBytes(event.bytes))
+ const path = pastedFilePath(value)
+ if (path && !this.pathInspectionPending) {
+ this.composer.insertText(value)
+ const pasted = this.composer.plainText
+ const cursor = this.composerStringCursor()
+ const generation = this.clipboardPasteGeneration
+ const chatId = this.client.activeChatId
+ const range = new PastedPathRange(pasted, cursor - value.length, cursor)
+ this.pathInspection = range
+ this.status.content = "Checking local attachment…"
+ void this.client.inspectAttachment(path).then((file) => {
+ if (this.quitting || this.composer.isDestroyed || generation !== this.clipboardPasteGeneration
+ || chatId !== this.client.activeChatId || this.pathInspection !== range) return
+ if (!range.update(this.composer.plainText)) return
+ const insertion = this.draft.localFile(file, this.composer.plainText)
+ if (!insertion) throw new Error("Too many attachments; remove one and paste the path again")
+ const edited = range.replace(insertion.text, this.composerStringCursor())!
+ this.pathInspection = null
+ this.composer.setText(edited.value)
+ this.setComposerStringCursor(edited.value, edited.cursor)
+ this.status.content = `Attached ${file.name}. Review before sending.`
+ }).catch((error: unknown) => {
+ if (generation !== this.clipboardPasteGeneration || this.quitting || this.pathInspection !== range) return
+ this.pathInspection = null
+ this.status.content = error instanceof Error ? error.message : "Attachment unavailable; path retained"
+ }).finally(() => {
+ if (this.pathInspection !== range) return
+ this.pathInspection = null
+ if (!this.quitting && !this.composer.isDestroyed) {
+ if (this.activeTurn) this.renderActiveStatus()
+ else this.status.content = this.ready ? this.readyStatus() : this.connectionMessage
+ }
+ })
+ return
+ }
const insertion = this.draft.paste(value)
if (!insertion.text) return
this.composer.insertText(insertion.text)
diff --git a/tui/src/app/composer.test.ts b/tui/src/app/composer.test.ts
index 22eef2232..033f90e5e 100644
--- a/tui/src/app/composer.test.ts
+++ b/tui/src/app/composer.test.ts
@@ -104,6 +104,119 @@ describe("NanobotTui composer", () => {
expect(setup.captureCharFrame()).toContain("Ask nanobot anything")
})
+ test("turns a confirmed pasted video path into a removable reference and retains failed sends", async () => {
+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })
+ const transport = client()
+ transport.inspectAttachment = async (path) => {
+ if (path.includes("missing")) throw new Error("file not found")
+ return { path, name: "my clip.mp4", size: 6, kind: "video", mime: "video/mp4", url: "/api/media/sig/path" }
+ }
+ const sentOptions: MessageOptions[] = []
+ transport.sendAttachments = async (_content, options) => {
+ sentOptions.push(options)
+ if (sentOptions.length === 1) throw new Error("source unavailable")
+ return "accepted"
+ }
+ const app = NanobotTui.mount(setup.renderer, options, transport, new MockTreeSitterClient({ autoResolveTimeout: 0 }))
+ app.accept({ event: "attached", chat_id: "chat" })
+ const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; status: { plainText: string } }
+ await waitUntil(() => ui.ready)
+ await setup.mockInput.pasteBracketedText('"/project/my clip.mp4"')
+ await waitUntil(() => ui.composer.plainText.includes("[Video #1: my clip.mp4]"))
+ ui.composer.submit()
+ await waitUntil(() => ui.status.plainText.includes("source unavailable"))
+ expect(ui.composer.plainText).toContain("[Video #1: my clip.mp4]")
+ expect(sentOptions[0]?.media).toEqual([{ path: "/project/my clip.mp4", name: "my clip.mp4" }])
+ ui.composer.submit()
+ await waitUntil(() => ui.composer.plainText === "")
+ await setup.mockInput.pasteBracketedText("./missing.mp4")
+ await waitUntil(() => ui.status.plainText.includes("file not found"))
+ expect(ui.composer.plainText).toBe("./missing.mp4")
+ })
+
+ test.each([false, true])("preserves text %s while a native pasted path is checked", async (prepend) => {
+ setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })
+ const transport = client()
+ let complete!: (file: Awaited<ReturnType<typeof transport.inspectAttachment>>) => void
+ transport.inspectAttachment = () => new Promise((resolve) => { complete = resolve })
+ const sent: Array<{ content: string; options: MessageOptions }> = []
+ transport.sendAttachments = async (content, options) => { sent.push({ content, options }); return "accepted" }
+ const app = NanobotTui.mount(setup.renderer, options, transport, new MockTreeSitterClient({ autoResolveTimeout: 0 }))
+ app.accept({ event: "attached", chat_id: "chat" })
+ const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; pathInspectionPending: boolean }
+ await waitUntil(() => ui.ready)
+ const path = "/project/image.png"
+ await setup.mockInput.pasteBracketedText(path)
+ if (prepend) ui.composer.cursorOffset = 0
+ await setup.mockInput.typeText(prepend ? "请看 " : " describe it")
+ complete({ path, name: "image.png", size: 6, kind: "image", mime: "image/png", url: "/api/media/sig/path" })
+ await waitUntil(() => !ui.pathInspectionPending)
+ expect(ui.composer.plainText).toContain("[Image #1: image.png]")
+ ui.composer.submit()
+ await waitUntil(() => sent.length === 1)
+ expect(sent[0]?.content).toBe(prepend ? "请看" : "describe it")
+ expect(sent[0]?.options.media).toEqual([{ path, name: "image.png" }])
+ })
+
+ test("cancels an edited native path and clears checking status without losing the text", async () => {
+ setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })
+ const transport = client()
+ let complete!: (file: Awaited<ReturnType<typeof transport.inspectAttachment>>) => void
+ transport.inspectAttachment = () => new Promise((resolve) => { complete = resolve })
+ const app = NanobotTui.mount(setup.renderer, options, transport, new MockTreeSitterClient({ autoResolveTimeout: 0 }))
+ app.accept({ event: "attached", chat_id: "chat" })
+ const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; pathInspectionPending: boolean; status: { plainText: string }; draft: { imageCount: number } }
+ await waitUntil(() => ui.ready)
+ await setup.mockInput.pasteBracketedText("/project/image.png")
+ ui.composer.setText("/project/other.png")
+ complete({ path: "/project/image.png", name: "image.png", size: 6, kind: "image", mime: "image/png", url: "/api/media/sig/path" })
+ await waitUntil(() => !ui.pathInspectionPending)
+ expect(ui.draft.imageCount).toBe(0)
+ expect(ui.composer.plainText).toBe("/project/other.png")
+ expect(ui.status.plainText).not.toContain("Checking local attachment")
+ })
+
+ test("allows one referenced video plus four non-video attachments including a clipboard image", async () => {
+ setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })
+ const transport = client()
+ transport.inspectAttachment = async (path) => ({
+ path, name: path.split("/").at(-1)!, size: 6, url: "/api/media/sig/path",
+ kind: path.endsWith("mp4") ? "video" : "file",
+ mime: path.endsWith("mp4") ? "video/mp4" : "text/plain",
+ })
+ const sentOptions: MessageOptions[] = []
+ transport.sendAttachments = async (_content, options) => { sentOptions.push(options); return "accepted" }
+ 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; pathInspectionPending: boolean; composer: TextareaRenderable; draft: { imageCount: number }; status: { plainText: string } }
+ await waitUntil(() => ui.ready)
+ for (const [index, name] of ["clip.mp4", "one.txt", "two.txt", "three.txt"].entries()) {
+ await setup.mockInput.pasteBracketedText(`/project/${name}`)
+ await waitUntil(() => !ui.pathInspectionPending)
+ expect(ui.draft.imageCount, `${name}: ${ui.composer.plainText}; ${ui.status.plainText}`).toBe(index + 1)
+ }
+ const beforeResize = ui.composer.plainText
+ for (const width of [140, 40, 100]) {
+ setup.resize(width, 30)
+ await setup.flush()
+ expect(ui.composer.plainText).toBe(beforeResize)
+ expect(ui.draft.imageCount).toBe(4)
+ }
+ setup.mockInput.pressKey("v", { ctrl: true })
+ await waitUntil(() => ui.draft.imageCount === 5)
+ setup.mockInput.pressKey("v", { ctrl: true })
+ await waitUntil(() => ui.status.plainText.includes("4 images or files"))
+ expect(ui.draft.imageCount).toBe(5)
+ ui.composer.submit()
+ await waitUntil(() => sentOptions.length === 1)
+ expect(sentOptions[0]?.media).toHaveLength(5)
+ expect(sentOptions[0]?.media?.filter((item) => item.path)).toHaveLength(4)
+ expect(sentOptions[0]?.media?.at(-1)?.data_url).toBe("data:image/png;base64,eA==")
+ await waitUntil(() => ui.composer.plainText === "")
+ })
+
test("compacts large pastes in the composer without changing the sent text", async () => {
const sent: string[] = []
setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })
@@ -248,7 +361,7 @@ describe("NanobotTui composer", () => {
setup.mockInput.pressKey("v", { ctrl: true })
await waitUntil(() => ui.composer.plainText === "这是什么? [Image #1] ")
setup.mockInput.pressTab()
- expect(ui.status.plainText).toContain("Images cannot be queued")
+ expect(ui.status.plainText).toContain("Attachments cannot be queued")
expect(ui.composer.plainText).toBe("这是什么? [Image #1] ")
ui.composer.submit()
await waitUntil(() => sent.length === 2)
@@ -405,7 +518,7 @@ describe("NanobotTui composer", () => {
setup.mockInput.pressKey("v", { ctrl: true })
await waitUntil(() => ui.composer.plainText === "/model [Image #1] ")
ui.composer.submit()
- await waitUntil(() => ui.status.plainText.includes("Remove the image before running a command."))
+ await waitUntil(() => ui.status.plainText.includes("Remove attachments before running a command."))
expect(sent).toEqual([])
expect(ui.composer.plainText).toBe("/model [Image #1] ")
diff --git a/tui/src/app/test-support.ts b/tui/src/app/test-support.ts
index 0d3bed4ab..aa88c59d5 100644
--- a/tui/src/app/test-support.ts
+++ b/tui/src/app/test-support.ts
@@ -69,6 +69,9 @@ export function client(
async sendAttachments(content: string, messageOptions: MessageOptions) {
return this.send(content, messageOptions)
},
+ async inspectAttachment(_path: string): Promise<import("../../../packages/client-events/attachments").LocalAttachment> {
+ throw new Error("file not found")
+ },
attach(chatId: string) {
attached.push(chatId)
},
diff --git a/tui/src/app/types.ts b/tui/src/app/types.ts
index f34e2858b..58fb65e30 100644
--- a/tui/src/app/types.ts
+++ b/tui/src/app/types.ts
@@ -1,4 +1,5 @@
import type { ThemeMode } from "@opentui/core"
+import type { LocalAttachment } from "../../../packages/client-events/attachments"
import type {
GatewayConnection,
@@ -33,6 +34,7 @@ export interface ChatClient {
close(): void
send(content: string, options?: MessageOptions): string
sendAttachments(content: string, options: MessageOptions): Promise<string>
+ inspectAttachment(path: string): Promise<LocalAttachment>
attach(chatId: string): void
newChat(scope?: WorkspaceScopePayload): void
forkChat?(sourceChatId: string, beforeUserIndex: number, title?: string): void
diff --git a/tui/src/app/usage-app.test.ts b/tui/src/app/usage-app.test.ts
index 8a0aea770..91e6d1575 100644
--- a/tui/src/app/usage-app.test.ts
+++ b/tui/src/app/usage-app.test.ts
@@ -47,6 +47,7 @@ describe("TUI /usage", () => {
activeChatId: "chat", connect() {}, close() {},
send(content: string) { sent.push(content); return "turn" },
async sendAttachments(content: string) { return this.send(content) },
+ async inspectAttachment(): Promise<never> { throw new Error("file not found") },
attach(chatId: string) { this.activeChatId = chatId },
newChat() { this.activeChatId = "new-chat" },
setWorkspaceScope() {},
diff --git a/tui/src/client/attachments.test.ts b/tui/src/client/attachments.test.ts
new file mode 100644
index 000000000..7c4d1d1d3
--- /dev/null
+++ b/tui/src/client/attachments.test.ts
@@ -0,0 +1,36 @@
+import { afterEach, expect, test } from "bun:test"
+import { pastedFilePath, uploadAttachments } from "../../../packages/client-events/attachments"
+
+const originalFetch = globalThis.fetch
+afterEach(() => { globalThis.fetch = originalFetch })
+
+test("recognizes whole paths across native platforms without consuming prose, code, URLs or fakepath", () => {
+ for (const [text, path] of [
+ ['"C:\\project\\my clip.mp4"', "C:\\project\\my clip.mp4"],
+ ["'./clips/my clip.webm'", "./clips/my clip.webm"],
+ ["/tmp/my clip.mov", "/tmp/my clip.mov"], ["clips/clip.mp4", "clips/clip.mp4"],
+ ["clip.mp4", "clip.mp4"],
+ ['"C:\\project\\O\'Reilly.png"', "C:\\project\\O'Reilly.png"],
+ ["/tmp/O'Reilly.png", "/tmp/O'Reilly.png"],
+ ['"O\'Reilly notes.pdf"', "O'Reilly notes.pdf"],
+ ]) expect(pastedFilePath(text!)).toBe(path!)
+ for (const text of ["please read ./file.txt", "const p = './file.txt'", "https://host/clip.mp4",
+ "C:\\fakepath\\clip.mp4", "line\n./clip.mp4", "`./clip.mp4`"]) expect(pastedFilePath(text)).toBeNull()
+})
+
+test("local paths send zero HTTP bodies; mixed batches upload only the required bytes", async () => {
+ const requests: { url: string; body: Blob }[] = []
+ globalThis.fetch = (async (url, init) => {
+ requests.push({ url: String(url), body: init?.body as Blob })
+ return Response.json({ reference: "upload-token" })
+ }) as typeof fetch
+ const local = { path: "/workspace/original.mp4", name: "original.mp4" }
+ expect(await uploadAttachments([local], null, "ws://unused", () => true)).toEqual([local])
+ expect(requests).toHaveLength(0)
+ expect(await uploadAttachments([local, { data_url: "data:video/webm;base64,eA==", name: "upload.webm" }],
+ { path: "/api/attachments", token: "private-capability" }, "ws://localhost:1234", () => true))
+ .toEqual([local, { reference: "upload-token", name: "upload.webm" }])
+ expect(requests).toHaveLength(1)
+ expect(requests[0]?.url).toBe("http://localhost:1234/api/attachments")
+ expect(await requests[0]?.body.text()).toBe("x")
+})
diff --git a/tui/src/client/nanobot-client.ts b/tui/src/client/nanobot-client.ts
index f13745454..6f589b7f7 100644
--- a/tui/src/client/nanobot-client.ts
+++ b/tui/src/client/nanobot-client.ts
@@ -1,4 +1,4 @@
-import { uploadAttachments, uploadCapability, type AttachmentReference, type UploadCapability } from "../../../packages/client-events/attachments"
+import { uploadAttachments, uploadCapability, isLocalAttachment, type AttachmentReference, type UploadCapability } from "../../../packages/client-events/attachments"
import { DeliveryReceipts } from "../../../packages/client-events/delivery"
import { isRecoveryState } from "../../../packages/client-events/notifications"
@@ -249,6 +249,17 @@ export class NanobotClient {
})
}
+ inspectAttachment(path: string): Promise<import("../../../packages/client-events/attachments").LocalAttachment> {
+ if (!this.chatId) return Promise.reject(new Error("chat is not ready"))
+ return this.requestMutation<unknown>("attachment.inspect", {
+ chat_id: this.chatId, path,
+ ...(this.workspaceScope ? { workspace_scope: this.workspaceScope } : {}),
+ }).then((result) => {
+ if (!isLocalAttachment(result)) throw new Error("Invalid attachment metadata")
+ return result
+ })
+ }
+
private requestMutation<T>(
action: string,
payload: Record<string, unknown> = {},
diff --git a/tui/src/client/types.ts b/tui/src/client/types.ts
index 3f23a39af..b40c592bd 100644
--- a/tui/src/client/types.ts
+++ b/tui/src/client/types.ts
@@ -71,10 +71,7 @@ export interface MediaAttachment {
name?: string
}
-export interface OutboundMedia {
- data_url: string
- name?: string
-}
+export type OutboundMedia = import("../../../packages/client-events/attachments").DraftAttachment
export interface WorkspaceScopePayload {
project_path: string
diff --git a/tui/src/composer/composer-draft.ts b/tui/src/composer/composer-draft.ts
index 0e69a42af..cafba70db 100644
--- a/tui/src/composer/composer-draft.ts
+++ b/tui/src/composer/composer-draft.ts
@@ -1,4 +1,5 @@
import type { OutboundMedia } from "../client"
+import type { LocalAttachment } from "../../../packages/client-events/attachments"
const LARGE_PASTE_CHARS = 1_000
const LARGE_PASTE_LINES = 10
@@ -31,7 +32,7 @@ interface DraftImage {
/** Keeps large pasted text and image payloads out of the editable composer surface. */
export class ComposerDraft {
private readonly pastes = new Map<string, string>()
- private readonly images = new Map<string, OutboundMedia>()
+ private readonly images = new Map<string, OutboundMedia & { kind: LocalAttachment["kind"] }>()
get imageCount(): number {
return this.images.size
@@ -67,16 +68,30 @@ export class ComposerDraft {
}
image(image: DraftImage, visible = ""): PasteInsertion | null {
- if (this.images.size >= MAX_DRAFT_IMAGES) return null
+ if ([...this.images.values()].filter((item) => item.kind !== "video").length >= MAX_DRAFT_IMAGES) return null
const index = this.nextImageIndex(visible)
const label = `[Image #${index}]`
this.images.set(label, {
+ kind: "image",
data_url: image.dataUrl,
name: `clipboard-image-${index}.${IMAGE_EXTENSIONS[image.mimeType]}`,
})
return { text: `${label} `, compacted: true, description: label.slice(1, -1) }
}
+ localFile(file: LocalAttachment, visible = ""): PasteInsertion | null {
+ const current = [...this.images.values()]
+ if (file.kind === "video"
+ ? current.some((item) => item.kind === "video")
+ : current.filter((item) => item.kind !== "video").length >= MAX_DRAFT_IMAGES) return null
+ const prefix = file.kind === "video" ? "Video" : file.kind === "image" ? "Image" : "File"
+ let index = 1
+ let label = `[${prefix} #${index}: ${file.name}]`
+ while (this.imageLabelInUse(label, visible)) label = `[${prefix} #${++index}: ${file.name}]`
+ this.images.set(label, { kind: file.kind, path: file.path, name: file.name })
+ return { text: `${label} `, compacted: true, description: label.slice(1, -1) }
+ }
+
private expandPastes(visible: string): string {
let expanded = visible
for (const [label, content] of this.pastes) expanded = expanded.split(label).join(content)
@@ -180,7 +195,7 @@ export class ComposerDraft {
return [...this.images]
.filter(([label]) => visible.includes(label))
.sort(([left], [right]) => visible.indexOf(left) - visible.indexOf(right))
- .map(([, media]) => media)
+ .map(([, { kind: _kind, ...media }]) => media)
}
prune(visible: string): void {
diff --git a/webui/src/components/AttachmentTile.tsx b/webui/src/components/AttachmentTile.tsx
index 9e285d8bd..f549cfeda 100644
--- a/webui/src/components/AttachmentTile.tsx
+++ b/webui/src/components/AttachmentTile.tsx
@@ -13,12 +13,14 @@ interface AttachmentTileProps {
className?: string;
inline?: boolean;
variant?: "default" | "compact";
+ pending?: boolean;
}
-export function AttachmentTile({ attachment, className, inline = false, variant = "default" }: AttachmentTileProps) {
+export function AttachmentTile({ attachment, className, inline = false, variant = "default", pending = false }: AttachmentTileProps) {
const { t } = useTranslation();
+ const videoUrl = attachment.url;
const [failedUrl, setFailedUrl] = useState<string | undefined>(undefined);
- const failed = !!attachment.url && failedUrl === attachment.url;
+ const failed = !!videoUrl && failedUrl === videoUrl;
const [imageOpen, setImageOpen] = useState(false);
const hasUrl = typeof attachment.url === "string" && attachment.url.length > 0;
const label = attachmentLabel(attachment, t);
@@ -36,7 +38,7 @@ export function AttachmentTile({ attachment, className, inline = false, variant
);
}
- if (attachment.kind === "video" && hasUrl) {
+ if (attachment.kind === "video" && hasUrl && !failed) {
return (
<AttachmentFrame
attachment={attachment}
@@ -45,9 +47,10 @@ export function AttachmentTile({ attachment, className, inline = false, variant
variant={variant}
>
<video
- src={attachment.url}
+ src={videoUrl}
controls
preload="metadata"
+ onError={() => setFailedUrl(videoUrl)}
className={cn(
"block w-full bg-black",
variant === "compact" ? "max-h-40" : "max-h-[26rem]",
@@ -100,9 +103,15 @@ export function AttachmentTile({ attachment, className, inline = false, variant
aria-label={label}
>
{body}
- <span className="sr-only">
- {t("message.attachmentUnavailable", { defaultValue: "Attachment unavailable" })}
+ <span className="text-xs text-muted-foreground">
+ {pending ? t("message.delivery.sending") : t("message.attachmentUnavailable", { defaultValue: "Attachment unavailable" })}
</span>
+ {attachment.kind === "video" && failed && !pending ? (
+ <button type="button" onClick={() => setFailedUrl(undefined)}
+ className="shrink-0 rounded-sm px-1 text-foreground underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2">
+ {t("common.retry")}
+ </button>
+ ) : null}
</div>
);
}
diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx
index bfb768578..5a08d2504 100644
--- a/webui/src/components/MessageBubble.tsx
+++ b/webui/src/components/MessageBubble.tsx
@@ -477,7 +477,7 @@ export function MessageBubble({
{!hasText ? contextMenu : null}
{hasImages ? <ImageGallery images={images} align="right" size="compact" /> : null}
{!hasImages && hasMedia ? (
- <MessageMedia media={media} align="right" />
+ <MessageMedia media={media} align="right" pending={message.deliveryStatus === "sending"} />
) : null}
{quotedContext ? (
<UserQuotedContext
@@ -641,9 +641,11 @@ function mergeCliMentionApps(
function MessageMedia({
media,
align,
+ pending = false,
}: {
media: UIMediaAttachment[];
align: "left" | "right";
+ pending?: boolean;
}) {
const inlineImages = useInlineImages();
if (media.length === 0) return null;
@@ -673,7 +675,7 @@ function MessageMedia({
<ImageGallery images={images} align={align} size={align === "left" ? "large" : "compact"} />
) : null}
{nonImages.map((item, i) => (
- <AttachmentTile key={`${item.url ?? item.name ?? item.kind}-${i}`} attachment={item} />
+ <AttachmentTile key={`${item.kind}-${i}`} attachment={item} pending={pending} />
))}
</div>
);
diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsx
index 90b79f72f..1914ecc45 100644
--- a/webui/src/components/thread/ThreadComposer.tsx
+++ b/webui/src/components/thread/ThreadComposer.tsx
@@ -1,3 +1,4 @@
+import { pastedFilePath, PastedPathRange, isLocalAttachment, type LocalAttachment } from "../../../../packages/client-events/attachments";
import {
NewChatIcon,
CompactIcon,
@@ -57,6 +58,7 @@ import {
ChevronUp,
CornerDownRight,
FileText,
+ Video,
ImageIcon,
Loader2,
Quote,
@@ -94,13 +96,15 @@ import {
} from "@/components/thread/ComposerUsagePopover";
import {
ACCEPT_ATTR,
+ acceptedAttachmentKind,
MAX_ATTACHMENTS_PER_MESSAGE,
MAX_ATTACHMENT_BYTES,
MAX_TOTAL_ATTACHMENT_BYTES,
+ MAX_VIDEO_BYTES,
+ MAX_VIDEOS_PER_MESSAGE,
useAttachedImages,
type AttachedImage,
type AttachmentError,
- type AttachmentKind,
type RestoredReadyImage,
} from "@/hooks/useAttachedImages";
import { useClipboardAndDrop } from "@/hooks/useClipboardAndDrop";
@@ -142,7 +146,7 @@ import {
} from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import { cn } from "@/lib/utils";
-import type { ComposerDraftStore } from "@/lib/composer-draft";
+import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
const VOICE_SHORTCUT_CODE = "KeyD";
@@ -153,8 +157,8 @@ type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
- if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
- return `${(n / (1024 * 1024)).toFixed(1)} MB`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
+ return `${(n / (1024 * 1024)).toFixed(1)} MiB`;
}
function utf8Bytes(value: string): number {
@@ -244,6 +248,7 @@ interface ThreadComposerProps {
onStop?: () => void;
surfaceRef?: Ref<HTMLDivElement>;
onTranscribeAudio?: (dataUrl: string, options?: { durationMs?: number }) => Promise<string>;
+ onInspectAttachment?: (path: string) => Promise<LocalAttachment>;
/** Sustained objective for this chat (WebSocket ``goal_state``). */
goalState?: GoalStateWsPayload;
workspaceScope?: WorkspaceScopePayload | null;
@@ -398,17 +403,15 @@ function mergeQueuedPrompt(first: QueuedPrompt, next: QueuedPrompt): QueuedPromp
};
}
-function queuedAttachmentBytes(image: QueuedPromptImage): number {
- const base64 = image.dataUrl.slice(image.dataUrl.indexOf(",") + 1);
+function queuedUploadBytes(image: QueuedPromptImage): number {
+ if (image.local) return 0;
+ const dataUrl = image.dataUrl ?? "";
+ const base64 = dataUrl.slice(dataUrl.indexOf(",") + 1);
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
return Math.floor(base64.length * 3 / 4) - padding;
}
-interface QueuedPromptImage {
- dataUrl: string;
- name?: string;
- kind?: AttachmentKind;
-}
+type QueuedPromptImage = RestoredReadyImage;
interface CliAppMentionQuery {
query: string;
@@ -555,13 +558,16 @@ function normalizeQueuedPrompt(item: unknown, index: number): QueuedPrompt | nul
if (typeof record.text !== "string") return null;
const text = record.text.trim();
const images = Array.isArray(record.images)
- ? record.images.flatMap((image) => {
+ ? record.images.flatMap((image): QueuedPromptImage[] => {
if (!image || typeof image !== "object") return [];
const candidate = image as Partial<QueuedPromptImage>;
+ if (isLocalAttachment(candidate.local)) {
+ return [{ local: candidate.local, kind: candidate.local.kind, name: candidate.local.name }];
+ }
if (typeof candidate.dataUrl !== "string" || !candidate.dataUrl.startsWith("data:")) {
return [];
}
- const kind = candidate.kind === "file" || candidate.kind === "image"
+ const kind = candidate.kind === "file" || candidate.kind === "image" || candidate.kind === "video"
? candidate.kind
: candidate.dataUrl.startsWith("data:image/")
? "image"
@@ -721,10 +727,11 @@ if (typeof window !== "undefined") {
}
function readyImagesToQueuedImages(
- images: Array<AttachedImage & { dataUrl: string }>,
+ images: AttachedImage[],
): QueuedPromptImage[] {
return images.map((img) => ({
dataUrl: img.dataUrl,
+ local: img.local,
kind: img.kind,
name: img.file.name,
}));
@@ -732,17 +739,20 @@ function readyImagesToQueuedImages(
function queuedImagesToSendImages(images?: QueuedPromptImage[]): SendAttachment[] | undefined {
if (!images?.length) return undefined;
- return images.map((img) => ({
- media: {
- data_url: img.dataUrl,
- ...(img.name ? { name: img.name } : {}),
- },
- preview: {
- kind: img.kind ?? (img.dataUrl.startsWith("data:image/") ? "image" : "file"),
- url: img.dataUrl,
- ...(img.name ? { name: img.name } : {}),
- },
- }));
+ return images.flatMap((img): SendAttachment[] => {
+ if (img.local) return [{
+ media: { path: img.local.path, name: img.local.name },
+ preview: { kind: img.local.kind, url: img.local.url, name: img.local.name },
+ }];
+ if (!img.dataUrl) return [];
+ return [{
+ media: { data_url: img.dataUrl, ...(img.name ? { name: img.name } : {}) },
+ preview: {
+ kind: img.kind ?? (img.dataUrl.startsWith("data:image/") ? "image" : img.dataUrl.startsWith("data:video/") ? "video" : "file"),
+ url: img.dataUrl, ...(img.name ? { name: img.name } : {}),
+ },
+ }];
+ });
}
function queuedPromptLabel(prompt: QueuedPrompt): string {
@@ -1096,6 +1106,7 @@ export function ThreadComposer({
onStop,
surfaceRef,
onTranscribeAudio,
+ onInspectAttachment,
goalState,
workspaceScope = null,
workspaceControlsHidden = false,
@@ -1134,6 +1145,14 @@ export function ThreadComposer({
} | null>(null);
const [inlineError, setInlineError] = useState<string | null>(null);
const [sendPending, setSendPending] = useState(false);
+ const [pathInspection, setPathInspection] = useState<{
+ generation: number; scope: string; range: PastedPathRange; attachment?: LocalAttachment;
+ } | null>(null);
+ const pathCheckGeneration = useRef(0);
+ const pathCheckScope = useRef("");
+ const scopeIdentity = `${workspaceScope?.project_path ?? ""}:${workspaceScope?.access_mode ?? ""}`;
+ pathCheckScope.current = scopeIdentity;
+ useEffect(() => () => { pathCheckGeneration.current += 1; }, []);
const [modelSetupAttentionRequest, setModelSetupAttentionRequest] = useState(0);
const queuedPromptStorageKey = queuedPromptsStorageKey(pendingQueueKey);
const queuedPromptStore = useMemo(() => queuedPromptStoreFor(queuedPromptStorageKey), [queuedPromptStorageKey]);
@@ -1223,35 +1242,47 @@ export function ThreadComposer({
const maxAttachments = ingressLimits?.attachments.max_count
?? MAX_ATTACHMENTS_PER_MESSAGE;
+ const maxFileBytes = ingressLimits?.attachments.max_file_bytes ?? MAX_ATTACHMENT_BYTES;
const maxTextBytes = ingressLimits?.message.max_text_bytes ?? 64 * 1024;
- const { images, enqueue, remove, clear, restoreReadyImages, encoding, full } =
+ const { images, enqueue, addLocal, remove, clear, restoreReadyImages, encoding: encodingFiles, full } =
useAttachedImages({ ingressLimits });
+ const encoding = encodingFiles || pathInspection !== null;
const restoredDraftAttachments = useRef(false);
- const [draftAttachmentsReady, setDraftAttachmentsReady] = useState(!initialDraft?.files.length);
+ const [draftAttachmentsReady, setDraftAttachmentsReady] = useState(!initialDraft?.attachments.length);
useLayoutEffect(() => {
if (restoredDraftAttachments.current) return;
restoredDraftAttachments.current = true;
- if (initialDraft?.files.length) enqueue(initialDraft.files, { restoringDraft: true });
+ for (const attachment of initialDraft?.attachments ?? []) {
+ if (attachment instanceof File) enqueue([attachment], { restoringDraft: true });
+ else addLocal(attachment, { restoringDraft: true });
+ }
setDraftAttachmentsReady(true);
- }, [enqueue, initialDraft]);
+ }, [enqueue, addLocal, initialDraft]);
const formatRejection = useCallback(
- (reason: AttachmentError): string => {
+ (reason: Exclude<AttachmentError, "too_large">): string => {
const key = `thread.composer.imageRejected.${reason}`;
- const fallback = reason === "too_many_attachments"
+ const fallback = reason === "too_many_videos"
+ ? "Max 1 video per message"
+ : reason === "too_many_attachments"
? `Max ${maxAttachments} attachments per message`
: reason === "empty_file"
? "Empty files cannot be attached"
: reason === "total_too_large"
? "Attachments are too large together — remove some or use smaller files"
- : reason === "too_large"
- ? "File is too large"
- : "Unsupported file type";
+ : "Unsupported file type";
return t(key, { max: maxAttachments, defaultValue: fallback });
},
[maxAttachments, t],
);
+ const formatUploadTooLarge = useCallback(
+ (size: number, maximum: number) => t("thread.composer.imageRejected.too_large", {
+ size: formatBytes(size), max: formatBytes(maximum),
+ }),
+ [t],
+ );
+
const textTooLargeMessage = useCallback(
() => t("thread.composer.textTooLarge", {
max: formatBytes(maxTextBytes),
@@ -1266,17 +1297,20 @@ export function ThreadComposer({
secondEnterPromptIdRef.current = null;
const { rejected } = enqueue(files);
if (rejected.length > 0) {
- setInlineError(formatRejection(rejected[0].reason));
+ const { reason, file } = rejected[0];
+ setInlineError(reason === "too_large"
+ ? formatUploadTooLarge(file.size, acceptedAttachmentKind(file) === "video" ? MAX_VIDEO_BYTES : maxFileBytes)
+ : formatRejection(reason));
} else {
setInlineError(null);
}
},
- [enqueue, formatRejection, interactionDisabled],
+ [enqueue, formatRejection, formatUploadTooLarge, interactionDisabled, maxFileBytes],
);
const {
isDragging,
- onPaste,
+ onPaste: onAttachmentPaste,
onDragEnter,
onDragOver,
onDragLeave,
@@ -1306,8 +1340,8 @@ export function ThreadComposer({
const normalizedQuotedContext = quotedContext?.trim() || null;
const readyImages = useMemo(
- () => images.filter((img): img is AttachedImage & { dataUrl: string } =>
- img.status === "ready" && typeof img.dataUrl === "string",
+ () => images.filter((img) =>
+ img.status === "ready" && (typeof img.dataUrl === "string" || !!img.local),
),
[images],
);
@@ -1531,6 +1565,49 @@ export function ThreadComposer({
resetKey: pendingQueueKey,
});
const { rawSelection, replace: replaceMentionInput } = mentionInput;
+ const onPaste = useCallback((event: React.ClipboardEvent<HTMLTextAreaElement>) => {
+ onAttachmentPaste(event);
+ if (event.defaultPrevented || interactionDisabled || !onInspectAttachment) return;
+ const raw = event.clipboardData.getData("text/plain");
+ const path = pastedFilePath(raw);
+ if (!path) return;
+ event.preventDefault();
+ const { start, end } = rawSelection();
+ const pasted = value.slice(0, start) + raw + value.slice(end);
+ const generation = ++pathCheckGeneration.current;
+ replaceMentionInput(pasted, start + raw.length);
+ setPathInspection({ generation, scope: scopeIdentity, range: new PastedPathRange(pasted, start, start + raw.length) });
+ void onInspectAttachment(path).then((attachment) => {
+ if (generation !== pathCheckGeneration.current) return;
+ setPathInspection((current) => current?.generation === generation ? { ...current, attachment } : current);
+ }).catch((error: unknown) => {
+ if (generation !== pathCheckGeneration.current || pathCheckScope.current !== scopeIdentity) return;
+ setInlineError(error instanceof Error ? error.message : t("message.attachmentUnavailable"));
+ setPathInspection(null);
+ });
+ }, [interactionDisabled, onAttachmentPaste, onInspectAttachment, rawSelection, replaceMentionInput, scopeIdentity, t, value]);
+
+ useLayoutEffect(() => {
+ if (!pathInspection) return;
+ if (pathInspection.scope !== scopeIdentity || !pathInspection.range.update(value)) {
+ pathCheckGeneration.current += 1;
+ setPathInspection(null);
+ return;
+ }
+ // Let the native IME commit before removing the confirmed path from its text.
+ if (!pathInspection.attachment || mentionInput.isComposing) return;
+ const edited = pathInspection.range.replace("", rawSelection().start);
+ if (edited) {
+ const rejection = addLocal(pathInspection.attachment);
+ if (rejection) setInlineError(formatRejection(rejection));
+ else {
+ replaceMentionInput(edited.value, edited.cursor, { preserveFocus: true });
+ setInlineError(null);
+ }
+ }
+ setPathInspection(null);
+ }, [addLocal, formatRejection, mentionInput.isComposing, pathInspection, rawSelection, replaceMentionInput, scopeIdentity, value]);
+
const draftText = composerMentionText(mentionInput.segments).raw;
const sessionDragInsertion = sessionDragPreview
? mentionInsertion(
@@ -1571,7 +1648,9 @@ export function ThreadComposer({
}
draftStore.set(draftKey, {
text: draftText,
- files: images.map((image) => image.file),
+ attachments: images.flatMap((image): ComposerDraft["attachments"] => (
+ image.local ? [image.local] : image.file instanceof File ? [image.file] : []
+ )),
sessionMentions: activeSessionMentions,
quotedContext,
}, persistDraft);
@@ -2017,19 +2096,22 @@ export function ThreadComposer({
return textTooLargeMessage();
}
const attachments = prompt.images ?? [];
- if (attachments.length > maxAttachments) return formatRejection("too_many_attachments");
- const sizes = attachments.map(queuedAttachmentBytes);
- if (sizes.some((size) => size > (ingressLimits?.attachments.max_file_bytes ?? MAX_ATTACHMENT_BYTES))) {
- return formatRejection("too_large");
+ const videos = attachments.filter((item) => item.kind === "video").length;
+ if (videos > MAX_VIDEOS_PER_MESSAGE) return formatRejection("too_many_videos");
+ if (attachments.length - videos > maxAttachments) return formatRejection("too_many_attachments");
+ const oversized = attachments.find((item) => queuedUploadBytes(item) > (item.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes));
+ if (oversized) {
+ return formatUploadTooLarge(queuedUploadBytes(oversized), oversized.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes);
}
- if (sizes.reduce((sum, size) => sum + size, 0) > (ingressLimits?.attachments.max_total_bytes ?? MAX_TOTAL_ATTACHMENT_BYTES)) {
+ const total = attachments.reduce((sum, item) => sum + (item.kind === "video" ? 0 : queuedUploadBytes(item)), 0);
+ if (total > (ingressLimits?.attachments.max_total_bytes ?? MAX_TOTAL_ATTACHMENT_BYTES)) {
return formatRejection("total_too_large");
}
if ((prompt.sessionMentions?.length ?? 0) > SESSION_MENTIONS_LIMIT) {
return t("thread.composer.queued.tooManyMentions", { max: SESSION_MENTIONS_LIMIT });
}
return null;
- }, [formatRejection, ingressLimits, maxAttachments, maxTextBytes, t, textTooLargeMessage]);
+ }, [formatRejection, formatUploadTooLarge, ingressLimits, maxAttachments, maxFileBytes, maxTextBytes, t, textTooLargeMessage]);
const collectGuidancePrompt = useCallback((): QueuedPrompt => {
queuedPromptCounterRef.current += 1;
@@ -2146,16 +2228,7 @@ export function ThreadComposer({
}
// 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) => ({
- media: {
- data_url: img.dataUrl,
- name: img.file.name,
- },
- preview: { kind: img.kind, url: img.dataUrl, name: img.file.name },
- }))
- : undefined;
+ const payload = queuedImagesToSendImages(readyImagesToQueuedImages(readyImages));
const attachedCliApps = activeCliMentionApps.map(cliAppMentionPayload);
const attachedMcpPresets = activeMcpPresetMentions.map(mcpPresetMentionPayload);
const options: SendOptions | undefined =
@@ -2627,7 +2700,9 @@ export function ThreadComposer({
current: formatBytes(current),
})
}
- formatError={formatRejection}
+ formatError={(reason) => reason === "too_large"
+ ? formatUploadTooLarge(img.file.size, img.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes)
+ : formatRejection(reason)}
onRemove={() => removeChip(img.id)}
onKeyDown={onChipKey(img.id)}
registerRef={(el) => {
@@ -3393,6 +3468,8 @@ function AttachmentChip({
<div className="flex h-full w-full items-center justify-center">
{image.kind === "image" ? (
<ImageIcon className="h-4 w-4 text-muted-foreground" aria-hidden />
+ ) : image.kind === "video" ? (
+ <Video className="h-4 w-4 text-muted-foreground" aria-hidden />
) : (
<FileText className="h-4 w-4 text-muted-foreground" aria-hidden />
)}
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index 19bc934a5..eea2187b4 100644
--- a/webui/src/components/thread/ThreadShell.tsx
+++ b/webui/src/components/thread/ThreadShell.tsx
@@ -15,7 +15,7 @@ import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover";
-import type { ComposerDraftStore } from "@/lib/composer-draft";
+import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import type {
ComposerContextUsage,
@@ -54,6 +54,7 @@ import {
isMcpPresetsPayload,
} from "@/lib/mcp-preset-events";
import type { StreamError } from "@/lib/nanobot-client";
+import { isLocalAttachment } from "../../../../packages/client-events/attachments";
import type {
ChatSummary,
FilePreviewPayload,
@@ -560,7 +561,8 @@ export function ThreadShell({
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
const filePreviewCloseTimerRef = useRef<number | null>(null);
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
- const pendingFirstRef = useRef<PendingFirstMessage | null>(null);
+ const pendingFirstRef = useRef<(PendingFirstMessage & { draft?: ComposerDraft; draftKey: string }) | null>(null);
+ const [restoredFirstDraft, setRestoredFirstDraft] = useState<{ chatId: string; revision: number; error: string } | null>(null);
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
const consumedPendingFirstMessageIdRef = useRef<string | null>(null);
const viewportRef = useRef<ThreadViewportHandle | null>(null);
@@ -971,10 +973,27 @@ export function ThreadShell({
setSubmittedViewportTurnId(submitted.turnId);
}
if (submitted?.delivery) {
- void submitted.delivery.then(() => pending.finish?.(true), () => pending.finish?.(false));
+ void submitted.delivery.then(() => pending.finish?.(true), (error: unknown) => {
+ // Topic creation already unmounted the landing composer. A rejected
+ // local reference must hand its draft to that topic, not strand it on /new.
+ if (pending.draft && pending.images?.some((image) => image.media.path !== undefined)) {
+ const targetKey = `websocket:${chatId}`;
+ const current = draftStore?.get(targetKey, !temporary);
+ if (!current?.text && !current?.attachments.length
+ && !current?.sessionMentions.length && !current?.quotedContext) {
+ draftStore?.set(targetKey, pending.draft, !temporary);
+ if (draftStore?.get(pending.draftKey) === pending.draft) draftStore.delete(pending.draftKey);
+ setRestoredFirstDraft((previous) => ({
+ chatId, revision: (previous?.revision ?? 0) + 1,
+ error: error instanceof Error ? error.message : String(error),
+ }));
+ }
+ }
+ pending.finish?.(false);
+ });
} else pending.finish?.(submitted !== null);
setBooting(false);
- }, [chatId, pendingFirstTargetChatId, send]);
+ }, [chatId, draftStore, pendingFirstTargetChatId, send, temporary]);
useEffect(() => {
if (
@@ -1022,7 +1041,10 @@ export function ThreadShell({
setBooting(true);
let finish!: (accepted: boolean) => void;
const delivery = new Promise<boolean>((resolve) => { finish = resolve; });
- pendingFirstRef.current = { content, images, options: withWorkspaceScope(options), finish };
+ pendingFirstRef.current = {
+ content, images, options: withWorkspaceScope(options), finish,
+ draftKey, draft: draftStore?.get(draftKey, persistDraft),
+ };
setPendingFirstTargetChatId(null);
const newId = await onCreateChat?.(workspaceScope, content, localModelPreset);
if (!newId) {
@@ -1037,11 +1059,20 @@ export function ThreadShell({
setPendingFirstTargetChatId(newId);
return delivery;
},
- [booting, client, localModelPreset, onCreateChat, withWorkspaceScope, workspaceScope],
+ [booting, client, draftKey, draftStore, localModelPreset, onCreateChat, persistDraft, withWorkspaceScope, workspaceScope],
);
+ const inspectAttachment = useCallback(async (path: string) => {
+ const result = await client.requestMutation("attachment.inspect", {
+ chat_id: chatId, path, ...(workspaceScope ? { workspace_scope: workspaceScope } : {}),
+ });
+ if (!isLocalAttachment(result)) throw new Error("Invalid attachment metadata");
+ return result;
+ }, [chatId, client, workspaceScope]);
+
const handleThreadSend = useCallback(
(content: string, images?: SendAttachment[], options?: SendOptions) => {
+ setRestoredFirstDraft((current) => current?.chatId === chatId ? { ...current, error: "" } : current);
const submitted = send(content, images, withWorkspaceScope(options));
if (
chatId
@@ -1253,9 +1284,12 @@ export function ThreadShell({
onOpenSettings={onOpenModelSettings}
/>
) : null}
+ {restoredFirstDraft?.chatId === chatId && restoredFirstDraft.error ? (
+ <p role="alert" className="px-3 text-sm text-destructive">{restoredFirstDraft.error}</p>
+ ) : null}
{session ? (
<ThreadComposer
- key={draftKey}
+ key={`${draftKey}:${restoredFirstDraft?.chatId === chatId ? restoredFirstDraft.revision : 0}`}
draftKey={draftKey}
draftStore={draftStore}
persistDraft={persistDraft}
@@ -1291,6 +1325,7 @@ export function ThreadShell({
sessions={mentionSessions}
skills={skills}
onStop={stop}
+ onInspectAttachment={inspectAttachment}
onTranscribeAudio={transcribeAudio}
goalState={currentGoalState}
onFavoriteWorkspaceProject={favoriteWorkspaceProject}
@@ -1347,6 +1382,7 @@ export function ThreadShell({
sessions={mentionSessions}
skills={skills}
surfaceRef={composerSurfaceRef}
+ onInspectAttachment={inspectAttachment}
onTranscribeAudio={transcribeAudio}
goalState={currentGoalState}
onFavoriteWorkspaceProject={favoriteWorkspaceProject}
diff --git a/webui/src/hooks/useAttachedImages.ts b/webui/src/hooks/useAttachedImages.ts
index 8081c3a2b..e4ab2447c 100644
--- a/webui/src/hooks/useAttachedImages.ts
+++ b/webui/src/hooks/useAttachedImages.ts
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
+import type { LocalAttachment } from "../../../packages/client-events/attachments";
import { encodeImage, type EncodeFailure } from "@/lib/imageEncode";
import type { WebUIIngressLimits } from "@/lib/types";
@@ -10,12 +11,13 @@ import type { WebUIIngressLimits } from "@/lib/types";
* - ``error`` — validation / decode failure; chip shows inline error
*/
type AttachmentStatus = "encoding" | "ready" | "error";
-export type AttachmentKind = "image" | "file";
+export type AttachmentKind = "image" | "video" | "file";
interface AttachedAttachment {
id: string;
kind: AttachmentKind;
- file: File;
+ file: Pick<File, "name" | "size" | "type">;
+ local?: LocalAttachment;
/** Optimistic ``blob:`` preview URL; revoked on ``remove`` / ``clear`` /
* unmount. */
previewUrl?: string;
@@ -32,8 +34,9 @@ interface AttachedAttachment {
export type AttachedImage = AttachedAttachment;
-interface RestoredReadyAttachment {
- dataUrl: string;
+export interface RestoredReadyAttachment {
+ dataUrl?: string;
+ local?: LocalAttachment;
name?: string;
kind?: AttachmentKind;
}
@@ -46,16 +49,24 @@ export type RestoredReadyImage = RestoredReadyAttachment;
export type AttachmentError =
| "unsupported_type" // server whitelist excludes this MIME
| "empty_file" // attachments must contain bytes
- | "too_many_attachments" // per-message cap (4) reached before enqueue
+ | "too_many_attachments" // non-video per-message cap reached before enqueue
+ | "too_many_videos" // video slot is already occupied
| "total_too_large" // decoded attachments exceed the business-policy total
| "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
| "io"; // file read failed at the browser layer
+type AttachmentCountError = Extract<AttachmentError, "too_many_attachments" | "too_many_videos">;
+
export const MAX_ATTACHMENTS_PER_MESSAGE = 4;
export const MAX_ATTACHMENT_BYTES = 6 * 1024 * 1024;
export const MAX_TOTAL_ATTACHMENT_BYTES = 24 * 1024 * 1024;
+export const MAX_VIDEO_BYTES = 20 * 1024 * 1024;
+export const MAX_VIDEOS_PER_MESSAGE = 1;
+const VIDEO_MIME_BY_EXTENSION = new Map([
+ [".mp4", "video/mp4"], [".webm", "video/webm"], [".mov", "video/quicktime"],
+]);
/** MIME whitelist — mirrors the server's and the ``<input accept>`` attr. */
const ACCEPTED_IMAGE_MIMES: ReadonlySet<string> = new Set([
@@ -91,6 +102,8 @@ export const ACCEPT_ATTR = [
...ACCEPTED_IMAGE_MIMES,
...ACCEPTED_DOCUMENT_MIMES,
...DOCUMENT_MIME_BY_EXTENSION.keys(),
+ ...VIDEO_MIME_BY_EXTENSION.values(),
+ ...VIDEO_MIME_BY_EXTENSION.keys(),
].join(",");
function extensionOf(name: string): string {
@@ -99,7 +112,8 @@ function extensionOf(name: string): string {
}
function mimeForFile(file: File): string {
- const byName = DOCUMENT_MIME_BY_EXTENSION.get(extensionOf(file.name));
+ const byName = DOCUMENT_MIME_BY_EXTENSION.get(extensionOf(file.name))
+ ?? VIDEO_MIME_BY_EXTENSION.get(extensionOf(file.name));
if (byName) return byName;
if (!file.type || file.type === "application/octet-stream") {
return "application/octet-stream";
@@ -114,6 +128,8 @@ function positiveLimit(value: number | null | undefined, fallback: number): numb
}
export function acceptedAttachmentKind(file: File): AttachmentKind | null {
+ if (VIDEO_MIME_BY_EXTENSION.has(extensionOf(file.name))
+ || [...VIDEO_MIME_BY_EXTENSION.values()].includes(file.type)) return "video";
if (DOCUMENT_MIME_BY_EXTENSION.has(extensionOf(file.name))) return "file";
if (ACCEPTED_IMAGE_MIMES.has(file.type)) return "image";
const mime = mimeForFile(file);
@@ -127,7 +143,8 @@ function dataUrlMime(dataUrl: string): string {
}
function kindFromDataUrl(dataUrl: string): AttachmentKind {
- return dataUrlMime(dataUrl).startsWith("image/") ? "image" : "file";
+ const mime = dataUrlMime(dataUrl);
+ return mime.startsWith("image/") ? "image" : mime.startsWith("video/") ? "video" : "file";
}
function dataUrlToFile(dataUrl: string, name?: string): File {
@@ -212,6 +229,7 @@ export interface UseAttachedImagesApi {
enqueue: (files: Iterable<File>, options?: { restoringDraft: boolean }) => {
rejected: Array<{ file: File; reason: AttachmentError }>;
};
+ addLocal: (attachment: LocalAttachment, options?: { restoringDraft: boolean }) => AttachmentCountError | null;
remove: (id: string) => { nextFocusId: string | null };
/** Revoke every staged blob URL and drop all attachments. Called after a
* successful submit — the optimistic bubble holds onto an independent
@@ -272,13 +290,14 @@ export function useAttachedImages({
const enqueue = useCallback(
(files: Iterable<File>, { restoringDraft = false } = {}) => {
const rejected: Array<{ file: File; reason: AttachmentError }> = [];
- const toAdd: AttachedAttachment[] = [];
- let slot = maxAttachments - imagesRef.current.length;
+ const toAdd: Array<AttachedAttachment & { file: File }> = [];
+ let slot = maxAttachments - imagesRef.current.filter((item) => item.kind !== "video").length;
+ let videoSlot = MAX_VIDEOS_PER_MESSAGE - imagesRef.current.filter((item) => item.kind === "video").length;
let projectedDecodedBytes = imagesRef.current.reduce(
- (total, image) => total + (
+ (total, image) => total + (image.local || image.kind === "video" ? 0 : (
image.encodedBytes
?? (image.kind === "image" ? Math.min(image.file.size, maxFileBytes) : image.file.size)
- ),
+ )),
0,
);
@@ -292,20 +311,21 @@ export function useAttachedImages({
rejected.push({ file, reason: "empty_file" });
continue;
}
- if (!restoringDraft && kind === "file" && file.size > maxFileBytes) {
+ if (!restoringDraft && kind !== "image" && file.size > (kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes)) {
rejected.push({ file, reason: "too_large" });
continue;
}
- if (!restoringDraft && slot <= 0) {
- rejected.push({ file, reason: "too_many_attachments" });
+ if (!restoringDraft && (kind === "video" ? videoSlot : slot) <= 0) {
+ rejected.push({ file, reason: kind === "video" ? "too_many_videos" : "too_many_attachments" });
continue;
}
- const nextDecodedBytes = kind === "image" ? Math.min(file.size, maxFileBytes) : file.size;
+ const nextDecodedBytes = kind === "video" ? 0 : kind === "image" ? Math.min(file.size, maxFileBytes) : file.size;
if (!restoringDraft && projectedDecodedBytes + nextDecodedBytes > maxTotalBytes) {
rejected.push({ file, reason: "total_too_large" });
continue;
}
- slot -= 1;
+ if (kind === "video") videoSlot -= 1;
+ else slot -= 1;
projectedDecodedBytes += nextDecodedBytes;
toAdd.push({
id: uuid(),
@@ -325,7 +345,7 @@ export function useAttachedImages({
queueMicrotask(() => {
const work = entry.kind === "image"
? encodeImage(entry.file)
- : encodeFile(entry.file, maxFileBytes);
+ : encodeFile(entry.file, entry.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes);
work.then(
(result) => {
if (result.ok) {
@@ -359,6 +379,22 @@ export function useAttachedImages({
[maxAttachments, maxFileBytes, maxTotalBytes, setEntry],
);
+ const addLocal = useCallback((local: LocalAttachment, { restoringDraft = false } = {}): AttachmentCountError | null => {
+ const current = imagesRef.current;
+ const videos = current.filter((item) => item.kind === "video").length;
+ if (!restoringDraft && (local.kind === "video" ? videos >= MAX_VIDEOS_PER_MESSAGE : current.length - videos >= maxAttachments)) {
+ return local.kind === "video" ? "too_many_videos" : "too_many_attachments";
+ }
+ const next: AttachedAttachment[] = [...current, {
+ id: uuid(), kind: local.kind, local, status: "ready", encodedBytes: local.size,
+ file: { name: local.name, size: local.size, type: local.mime },
+ ...(local.kind === "image" ? { previewUrl: local.url } : {}),
+ }];
+ imagesRef.current = next;
+ setImages(next);
+ return null;
+ }, [maxAttachments]);
+
const remove = useCallback((id: string) => {
let nextFocusId: string | null = null;
setImages((prev) => {
@@ -399,21 +435,24 @@ export function useAttachedImages({
}, []);
const restoreReadyImages = useCallback((restored: RestoredReadyAttachment[]) => {
- const toRestore = restored
- .filter((img) => acceptedAttachmentKind(dataUrlToFile(img.dataUrl, img.name)))
- .map((img): AttachedAttachment => {
- const file = dataUrlToFile(img.dataUrl, img.name);
- const kind = img.kind ?? kindFromDataUrl(img.dataUrl);
- return {
- id: uuid(),
- kind,
- file,
- ...(kind === "image" ? { previewUrl: img.dataUrl } : {}),
- status: "ready",
- dataUrl: img.dataUrl,
- encodedBytes: file.size,
- };
- });
+ const toRestore = restored.flatMap((img): AttachedAttachment[] => {
+ if (img.local) {
+ const local = img.local;
+ return [{
+ id: uuid(), kind: local.kind, local, status: "ready", encodedBytes: local.size,
+ file: { name: local.name, size: local.size, type: local.mime },
+ ...(local.kind === "image" ? { previewUrl: local.url } : {}),
+ }];
+ }
+ if (!img.dataUrl) return [];
+ const file = dataUrlToFile(img.dataUrl, img.name);
+ if (!acceptedAttachmentKind(file)) return [];
+ const kind = img.kind ?? kindFromDataUrl(img.dataUrl);
+ return [{
+ id: uuid(), kind, file, status: "ready", dataUrl: img.dataUrl, encodedBytes: file.size,
+ ...(kind === "image" ? { previewUrl: img.dataUrl } : {}),
+ }];
+ });
setImages((prev) => {
for (const img of prev) {
if (img.previewUrl) {
@@ -447,7 +486,8 @@ export function useAttachedImages({
}, []);
const encoding = images.some((img) => img.status === "encoding");
- const full = images.length >= maxAttachments;
+ const videos = images.filter((image) => image.kind === "video").length;
+ const full = images.length - videos >= maxAttachments && videos >= MAX_VIDEOS_PER_MESSAGE;
- return { images, enqueue, remove, clear, restoreReadyImages, encoding, full };
+ return { images, enqueue, addLocal, remove, clear, restoreReadyImages, encoding, full };
}
diff --git a/webui/src/hooks/useComposerMentionInput.ts b/webui/src/hooks/useComposerMentionInput.ts
index 26b52cacd..559ea1328 100644
--- a/webui/src/hooks/useComposerMentionInput.ts
+++ b/webui/src/hooks/useComposerMentionInput.ts
@@ -19,7 +19,7 @@ export function useComposerMentionInput({
}) {
const text = useMemo(() => composerMentionText(segments), [segments]);
const textRef = useRef(text);
- const pendingSelection = useRef<{ start: number; end: number } | null>(null);
+ const pendingSelection = useRef<{ start: number; end: number; preserveFocus?: boolean } | null>(null);
const history = useRef<{ undo: Snapshot[]; redo: Snapshot[] }>({ undo: [], redo: [] });
const lastEdit = useRef({ type: "", at: 0, cursor: -1 });
const composing = useRef(false);
@@ -42,10 +42,10 @@ export function useComposerMentionInput({
return selection;
}, [inputRef]);
- const selectRaw = useCallback((start: number, end = start) => {
+ const selectRaw = useCallback((start: number, end = start, preserveFocus = false) => {
const el = inputRef.current;
- // Focus first: removing a queued prompt's edit button can reset a blurred selection.
- el?.focus();
+ // Focus first for user actions; passive attachment confirmation keeps the active control.
+ if (!preserveFocus) el?.focus();
el?.setSelectionRange(
mentionTextOffset(textRef.current, start, "toDisplay", "start"),
mentionTextOffset(textRef.current, end, "toDisplay", "end"),
@@ -74,13 +74,13 @@ export function useComposerMentionInput({
}
textRef.current = text;
if (!composing.current && pendingSelection.current) {
- const { start, end } = pendingSelection.current;
- selectRaw(start, end);
+ const { start, end, preserveFocus } = pendingSelection.current;
+ selectRaw(start, end, preserveFocus);
pendingSelection.current = null;
}
});
- const apply = useCallback((value: string, cursor: number, type = "", selection = rawSelection()) => {
+ const apply = useCallback((value: string, cursor: number, type = "", selection = rawSelection(), preserveFocus = false) => {
const previous = textRef.current;
if (value !== previous.raw) {
const now = Date.now();
@@ -93,10 +93,14 @@ export function useComposerMentionInput({
history.current.redo = [];
lastEdit.current = { type, at: now, cursor };
}
- pendingSelection.current = value === previous.raw ? null : { start: cursor, end: cursor };
+ pendingSelection.current = value === previous.raw ? null : { start: cursor, end: cursor, preserveFocus };
onEdit(value, cursor);
}, [onEdit, rawSelection]);
+ const replace = useCallback((value: string, cursor: number, { preserveFocus = false } = {}) => {
+ apply(value, cursor, "", undefined, preserveFocus);
+ }, [apply]);
+
const beforeSelection = useRef<{ start: number; end: number; raw: { start: number; end: number } } | null>(null);
const captureSelection = useCallback(() => {
const el = inputRef.current;
@@ -170,7 +174,7 @@ export function useComposerMentionInput({
),
isComposing: compositionValue !== null,
rawSelection,
- replace: apply,
+ replace,
onChange,
onKeyDown,
onCopy: (event: ClipboardEvent<HTMLTextAreaElement>) => copy(event, false),
diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts
index 142223c01..0f43d4c01 100644
--- a/webui/src/hooks/useNanobotStream.ts
+++ b/webui/src/hooks/useNanobotStream.ts
@@ -688,7 +688,16 @@ export function useNanobotStream(
if (turnId) {
setMessages((prev) => transitionTurnDelivery(prev, turnId, "accepted"));
}
- if (ev.event === "message_accepted") return;
+ if (ev.event === "message_accepted") {
+ if (ev.media_urls?.length) {
+ setMessages((prev) => prev.map((message) => (
+ message.role === "user" && message.turnId === ev.turn_id
+ ? { ...message, media: ev.media_urls }
+ : message
+ )));
+ }
+ return;
+ }
if (ev.event === "user_message") {
if (ev.provenance?.session_message) {
flushPendingStreamEvents();
@@ -705,7 +714,11 @@ export function useNanobotStream(
setMessages((prev) => {
if (ev.turn_id && prev.some((message) => (
message.role === "user" && message.turnId === ev.turn_id
- ))) return prev;
+ ))) return ev.media_urls?.length ? prev.map((message) => (
+ message.role === "user" && message.turnId === ev.turn_id
+ ? { ...message, media: ev.media_urls }
+ : message
+ )) : prev;
const row: UIMessage = {
id: crypto.randomUUID(),
role: "user",
@@ -1021,7 +1034,11 @@ export function useNanobotStream(
const turnId = crypto.randomUUID();
const userMessageId = crypto.randomUUID();
if (sideChannel) transcriptRef.current.sideChannelTurnIds.add(turnId);
- const previews = hasAttachments ? images!.map((i) => i.preview) : undefined;
+ const previews = hasAttachments ? images!.map(({ preview }) => (
+ preview.kind === "video" && preview.url?.startsWith("data:")
+ ? { kind: preview.kind, name: preview.name }
+ : preview
+ )) : undefined;
setMessages((prev) => {
let projection = { ...transcriptRef.current.projection, messages: prev };
if ((!sideChannel && !continueActiveTurn) || finalizeActiveTurn) {
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 828fa749e..f792a6651 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -2307,10 +2307,11 @@
"unsupported_type": "Unsupported file type",
"empty_file": "Empty files cannot be attached",
"too_many_attachments": "Max {{max}} attachments per message",
+ "too_many_videos": "Max 1 video per message",
"too_many_images": "Max {{max}} images per message",
"magic_mismatch": "File doesn't look like a real image",
"decode_failed": "Couldn't decode this image",
- "too_large": "File is too large — try a smaller one",
+ "too_large": "File is too large to upload ({{size}}; maximum {{max}})",
"total_too_large": "Attachments are too large together — remove some or use smaller files",
"io": "Couldn't read this file"
},
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index 48441ba8e..046c71759 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -2087,10 +2087,11 @@
"unsupported_type": "Tipo de archivo no compatible",
"empty_file": "No se pueden adjuntar archivos vacíos",
"too_many_attachments": "Máximo {{max}} adjuntos por mensaje",
+ "too_many_videos": "Máximo 1 vídeo por mensaje",
"too_many_images": "Máximo {{max}} imágenes por mensaje",
"magic_mismatch": "El archivo no parece una imagen real",
"decode_failed": "No se pudo decodificar esta imagen",
- "too_large": "Archivo demasiado grande — prueba uno más pequeño",
+ "too_large": "El archivo ({{size}}) supera el límite de carga de {{max}}",
"total_too_large": "Los archivos adjuntos son demasiado grandes en conjunto; elimina algunos o usa archivos más pequeños",
"io": "No se pudo leer este archivo"
},
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index 7f227fd40..41ff91475 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -2086,10 +2086,11 @@
"unsupported_type": "Type de fichier non pris en charge",
"empty_file": "Impossible de joindre des fichiers vides",
"too_many_attachments": "Maximum {{max}} pièces jointes par message",
+ "too_many_videos": "Une seule vidéo par message",
"too_many_images": "Maximum {{max}} images par message",
"magic_mismatch": "Ce fichier n'est pas une image",
"decode_failed": "Impossible de décoder cette image",
- "too_large": "Fichier trop volumineux — essayez-en un plus petit",
+ "too_large": "Le fichier ({{size}}) dépasse la limite d’envoi de {{max}}",
"total_too_large": "Les pièces jointes sont trop volumineuses ensemble — supprimez-en ou utilisez des fichiers plus petits",
"io": "Impossible de lire ce fichier"
},
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index 8a31e8ded..dc3fa6ec9 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -2086,10 +2086,11 @@
"unsupported_type": "Tipe file tidak didukung",
"empty_file": "File kosong tidak dapat dilampirkan",
"too_many_attachments": "Maksimal {{max}} lampiran per pesan",
+ "too_many_videos": "Maksimal 1 video per pesan",
"too_many_images": "Maksimal {{max}} gambar per pesan",
"magic_mismatch": "File ini tampaknya bukan gambar asli",
"decode_failed": "Tidak dapat mendekode gambar ini",
- "too_large": "File terlalu besar — coba yang lebih kecil",
+ "too_large": "Ukuran file {{size}} melebihi batas unggahan {{max}}",
"total_too_large": "Total lampiran terlalu besar — hapus beberapa atau gunakan file yang lebih kecil",
"io": "Tidak dapat membaca file ini"
},
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 5a08308f7..a9973b61b 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -2086,10 +2086,11 @@
"unsupported_type": "対応していないファイル形式です",
"empty_file": "空のファイルは添付できません",
"too_many_attachments": "1 メッセージにつき最大 {{max}} 件までです",
+ "too_many_videos": "1 メッセージにつき動画は 1 件までです",
"too_many_images": "1 メッセージにつき最大 {{max}} 枚です",
"magic_mismatch": "画像ファイルではないようです",
"decode_failed": "この画像をデコードできません",
- "too_large": "ファイルが大きすぎます。小さいものを選んでください",
+ "too_large": "ファイルサイズ {{size}} はアップロード上限 {{max}} を超えています",
"total_too_large": "添付ファイルの合計サイズが大きすぎます。いくつか削除するか、より小さいファイルを使用してください",
"io": "このファイルを読み込めません"
},
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index ec5959d03..308e666a7 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -2086,10 +2086,11 @@
"unsupported_type": "지원하지 않는 파일 형식입니다",
"empty_file": "빈 파일은 첨부할 수 없습니다",
"too_many_attachments": "메시지당 최대 {{max}}개까지 가능합니다",
+ "too_many_videos": "메시지당 동영상은 최대 1개까지 가능합니다",
"too_many_images": "메시지당 최대 {{max}}장까지 가능합니다",
"magic_mismatch": "이미지 파일이 아닌 것 같습니다",
"decode_failed": "이 이미지를 디코딩할 수 없습니다",
- "too_large": "파일이 너무 큽니다. 더 작은 파일을 선택해 주세요",
+ "too_large": "파일 크기 {{size}}가 업로드 한도 {{max}}를 초과합니다",
"total_too_large": "첨부 파일의 전체 크기가 너무 큽니다. 일부를 제거하거나 더 작은 파일을 사용해 주세요",
"io": "이 파일을 읽을 수 없습니다"
},
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index 0ee9d5817..df640c2f9 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -2115,10 +2115,11 @@
"unsupported_type": "Tipo de arquivo não compatível",
"empty_file": "Arquivos vazios não podem ser anexados",
"too_many_attachments": "Máx. de {{max}} anexos por mensagem",
+ "too_many_videos": "Máx. de 1 vídeo por mensagem",
"too_many_images": "Máx. de {{max}} imagens por mensagem",
"magic_mismatch": "O arquivo não parece uma imagem real",
"decode_failed": "Não foi possível decodificar esta imagem",
- "too_large": "A imagem é grande demais — tente uma menor",
+ "too_large": "O arquivo ({{size}}) excede o limite de upload de {{max}}",
"total_too_large": "Os anexos são grandes demais em conjunto — remova alguns ou use arquivos menores",
"io": "Não foi possível ler este arquivo"
},
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index 64ac5520f..db6650602 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -2086,10 +2086,11 @@
"unsupported_type": "Loại tệp không được hỗ trợ",
"empty_file": "Không thể đính kèm tệp trống",
"too_many_attachments": "Tối đa {{max}} tệp đính kèm mỗi tin nhắn",
+ "too_many_videos": "Tối đa 1 video mỗi tin nhắn",
"too_many_images": "Tối đa {{max}} ảnh mỗi tin nhắn",
"magic_mismatch": "Tệp này không phải là một ảnh thực",
"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",
+ "too_large": "Tệp có dung lượng {{size}}, vượt giới hạn tải lên {{max}}",
"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",
"io": "Không thể đọc tệp này"
},
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index db4e03c39..8014fa584 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -2306,10 +2306,11 @@
"unsupported_type": "不支持的文件类型",
"empty_file": "不能附加空文件",
"too_many_attachments": "每条消息最多 {{max}} 个附件",
+ "too_many_videos": "每条消息最多 1 个视频",
"too_many_images": "每条消息最多 {{max}} 张图片",
"magic_mismatch": "文件看起来不像真实的图片",
"decode_failed": "无法解码这张图片",
- "too_large": "文件太大,请换一个小一点的",
+ "too_large": "文件为 {{size}},超过上传上限 {{max}}",
"total_too_large": "附件总大小过大,请移除部分文件或使用更小的文件",
"io": "无法读取该文件"
},
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index 1688e642f..7a64d265f 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -2086,10 +2086,11 @@
"unsupported_type": "不支援的檔案類型",
"empty_file": "無法附加空白檔案",
"too_many_attachments": "每則訊息最多 {{max}} 個附件",
+ "too_many_videos": "每則訊息最多 1 部影片",
"too_many_images": "每則訊息最多 {{max}} 張圖片",
"magic_mismatch": "檔案內容似乎不是有效的圖片",
"decode_failed": "無法解碼這張圖片",
- "too_large": "檔案太大,請改用較小的檔案",
+ "too_large": "檔案為 {{size}},超過上傳上限 {{max}}",
"total_too_large": "附件總大小過大,請移除部分檔案或改用較小的檔案",
"io": "無法讀取這個檔案"
},
diff --git a/webui/src/lib/composer-draft.ts b/webui/src/lib/composer-draft.ts
index 80c3795aa..33d2e848a 100644
--- a/webui/src/lib/composer-draft.ts
+++ b/webui/src/lib/composer-draft.ts
@@ -1,9 +1,10 @@
import type { SessionMention } from "./types";
+import { isLocalAttachment, type LocalAttachment } from "../../../packages/client-events/attachments";
-/** Files stay in memory, including unfinished attachments. */
+/** Ordered attachments retain browser Files in memory and persist local references. */
export interface ComposerDraft {
text: string;
- files: File[];
+ attachments: Array<File | LocalAttachment>;
sessionMentions: SessionMention[];
quotedContext: string | null;
}
@@ -34,7 +35,9 @@ function readDraft(raw: string): ComposerDraft | undefined {
? { id: item.id } : {}),
}];
});
- return { text: value.text, quotedContext: value.quotedContext, sessionMentions, files: [] };
+ const rawAttachments = Array.isArray(value.attachments) ? value.attachments : value.localAttachments;
+ const attachments = Array.isArray(rawAttachments) ? rawAttachments.filter(isLocalAttachment) : [];
+ return { text: value.text, quotedContext: value.quotedContext, sessionMentions, attachments };
}
function removeStoredDraft(key: string): void {
@@ -69,14 +72,14 @@ export class ComposerDraftStore extends Map<string, ComposerDraft> {
const unchanged = previous
&& previous.text === draft.text
&& previous.quotedContext === draft.quotedContext
- && previous.files.length === draft.files.length
- && previous.files.every((file, index) => file === draft.files[index])
+ && previous.attachments.length === draft.attachments.length
+ && previous.attachments.every((attachment, index) => attachment === draft.attachments[index])
&& previous.sessionMentions.length === draft.sessionMentions.length
&& previous.sessionMentions.every((mention, index) => mention === draft.sessionMentions[index]);
// Restoring a composer is not an edit. Pending sends retain this identity across mounts.
super.set(key, unchanged ? previous : draft);
if (!persist) return this;
- if (!draft.text && !draft.quotedContext) {
+ if (!draft.text && !draft.quotedContext && !draft.attachments.some(isLocalAttachment)) {
removeStoredDraft(key);
return this;
}
@@ -85,6 +88,7 @@ export class ComposerDraftStore extends Map<string, ComposerDraft> {
text: draft.text,
quotedContext: draft.quotedContext,
sessionMentions: draft.sessionMentions,
+ attachments: draft.attachments.filter(isLocalAttachment),
});
if (raw.length <= MAX_STORED_CHARS) localStorage.setItem(STORAGE_PREFIX + key, raw);
else removeStoredDraft(key);
diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts
index 2f7099218..a06544090 100644
--- a/webui/src/lib/types.ts
+++ b/webui/src/lib/types.ts
@@ -1488,11 +1488,12 @@ export type InboundEvent =
event: "message_accepted";
chat_id: string;
turn_id: string;
+ media_urls?: UIMediaAttachment[];
starts_turn?: boolean;
active_turn_id?: string;
started_at?: number;
}
- | {
+ | ({
event: "user_message";
chat_id: string;
text: string;
@@ -1506,14 +1507,14 @@ export type InboundEvent =
mcp_presets?: UIMcpPresetAttachment[];
session_mentions?: SessionMention[];
provenance?: { session_message?: UISessionMessage };
- }
+ } & InboundTurnMetadata)
| ({
event: "message";
chat_id: string;
text: string;
reply_to?: string;
media?: string[];
- media_urls?: Array<{ url: string; name?: string }>;
+ media_urls?: Array<{ url: string; name?: string; kind?: UIMediaKind }>;
tool_events?: ToolProgressEvent[];
/** Oversized persisted activity detail, fetched only when the trace is expanded. */
trace_detail?: UITraceDetail;
@@ -1677,10 +1678,7 @@ export type ThreadProjectionEvent = Extract<
* surface. ``name`` is advisory and is surfaced as the placeholder label when
* the session is replayed.
*/
-export interface OutboundMedia {
- data_url: string;
- name?: string;
-}
+export type OutboundMedia = import("../../../packages/client-events/attachments").DraftAttachment;
export interface OutboundCliAppMention {
name: string;
diff --git a/webui/src/tests/composer-draft.test.ts b/webui/src/tests/composer-draft.test.ts
index 39c07cd50..d23bfcec8 100644
--- a/webui/src/tests/composer-draft.test.ts
+++ b/webui/src/tests/composer-draft.test.ts
@@ -8,7 +8,7 @@ const draft: ComposerDraft = {
text: " Keep this draft\n继续编辑",
quotedContext: "Quoted answer",
sessionMentions: [{ name: "other", title: "Other topic", session_key: "websocket:other" }],
- files: [new File(["attachment"], "draft.txt", { type: "text/plain" })],
+ attachments: [new File(["attachment"], "draft.txt", { type: "text/plain" })],
};
afterEach(() => {
@@ -21,15 +21,15 @@ describe("composer draft storage", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
expect(store.get(key)).toBe(draft);
- expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, files: [] });
+ expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, attachments: [] });
expect(new ComposerDraftStore().get("websocket:other", true)).toBeUndefined();
- expect(localStorage.getItem(storageKey)).not.toContain("files");
+ expect(JSON.parse(localStorage.getItem(storageKey)!).attachments).toEqual([]);
});
it("keeps the identity of an unchanged restored draft but advances it for edits", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
- store.set(key, { ...draft, files: [...draft.files], sessionMentions: [...draft.sessionMentions] }, true);
+ store.set(key, { ...draft, attachments: [...draft.attachments], sessionMentions: [...draft.sessionMentions] }, true);
expect(store.get(key)).toBe(draft);
const edited = { ...draft, text: "edited draft" };
store.set(key, edited, true);
@@ -39,6 +39,27 @@ describe("composer draft storage", () => {
expect(store.get(key)).toBe(reverted);
});
+ it("keeps mixed attachment order in memory and the local subsequence after reload", () => {
+ const first = { path: "/project/first.png", name: "first.png", size: 8, mime: "image/png", kind: "image" as const, url: "" };
+ const last = { ...first, path: "/project/last.png", name: "last.png" };
+ const mixed = { ...draft, attachments: [first, draft.attachments[0], last] };
+ const store = new ComposerDraftStore();
+ store.set(key, mixed, true);
+ store.set(key, { ...mixed, attachments: [...mixed.attachments] }, true);
+ expect(store.get(key)).toBe(mixed);
+ expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([first, last]);
+ const reordered = { ...mixed, attachments: [last, draft.attachments[0], first] };
+ store.set(key, reordered, true);
+ expect(store.get(key)).toBe(reordered);
+ expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([last, first]);
+ });
+
+ it("reads local references already saved in v1 drafts", () => {
+ const local = { path: "/project/previous.png", name: "previous.png", size: 8, mime: "image/png", kind: "image", url: "" };
+ localStorage.setItem(storageKey, JSON.stringify({ text: "previous draft", quotedContext: null, sessionMentions: [], localAttachments: [local] }));
+ expect(new ComposerDraftStore().get(key, true)?.attachments).toEqual([local]);
+ });
+
it("requires explicit opt-in for both saving and restoring", () => {
const store = new ComposerDraftStore();
store.set(key, draft);
@@ -52,7 +73,7 @@ describe("composer draft storage", () => {
const store = new ComposerDraftStore();
store.set(key, draft, true);
store.set(key, { ...draft, text: "", quotedContext: null, sessionMentions: [] }, true);
- expect(store.get(key)?.files).toEqual(draft.files);
+ expect(store.get(key)?.attachments).toEqual(draft.attachments);
expect(new ComposerDraftStore().get(key, true)).toBeUndefined();
});
@@ -82,7 +103,7 @@ describe("composer draft storage", () => {
localStorage.setItem(storageKey, JSON.stringify({
...draft, sessionMentions: [null, { name: 42 }, ...draft.sessionMentions],
}));
- expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, files: [] });
+ expect(new ComposerDraftStore().get(key, true)).toEqual({ ...draft, attachments: [] });
});
it("keeps editing usable when storage is unavailable and removes stale saved text", () => {
diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx
index 2c3b4c31c..f2f867025 100644
--- a/webui/src/tests/message-bubble.test.tsx
+++ b/webui/src/tests/message-bubble.test.tsx
@@ -1049,6 +1049,23 @@ describe("MessageBubble", () => {
expect(content.querySelectorAll("li")).toHaveLength(1000);
});
+ it("retries a failed video locally without replacing a healthy player on history updates", () => {
+ const message: UIMessage = { id: "retry-video", role: "user", content: "watch", createdAt: 0,
+ media: [{ kind: "video", name: "clip.webm", url: "/api/media/sig/clip" }] };
+ const { container, rerender } = render(<MessageBubble message={message} />);
+ const original = container.querySelector("video")!;
+ fireEvent.error(original);
+ expect(container.querySelector("video")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ const retried = container.querySelector("video")!;
+ expect(retried).toHaveAttribute("src", "/api/media/sig/clip");
+ expect(retried).not.toBe(original);
+ rerender(<MessageBubble message={{ ...message, media: [...message.media!] }} />);
+ expect(container.querySelector("video")).toBe(retried);
+ fireEvent.error(retried);
+ expect(screen.getByRole("button", { name: "Retry" })).toBeVisible();
+ });
+
it("renders video media as an inline player", () => {
const message: UIMessage = {
id: "a1",
@@ -1076,6 +1093,29 @@ describe("MessageBubble", () => {
expect(screen.queryByText("Code")).not.toBeInTheDocument();
});
+ it("starts an uploaded player from its accepted URL and preserves it through hydration", () => {
+ const message: UIMessage = {
+ id: "optimistic-user", role: "user", content: "Watch this", createdAt: 1,
+ turnId: "video-turn", turnPhase: "user", deliveryStatus: "sending",
+ media: [{ kind: "video", name: "clip.webm" }],
+ };
+ const accepted: UIMessage = {
+ ...message, deliveryStatus: "accepted",
+ media: [{ kind: "video", name: "clip.webm", url: "/api/media/sig/clip" }],
+ };
+ const { rerender, unmount } = render(<ThreadMessages messages={[message]} />);
+ expect(screen.queryByLabelText(/video attachment/i)?.tagName).not.toBe("VIDEO");
+ expect(screen.queryByText(/attachment unavailable/i)).not.toBeInTheDocument();
+ rerender(<ThreadMessages messages={[accepted]} />);
+ const video = screen.getByLabelText(/video attachment/i);
+ rerender(<ThreadMessages messages={[{ ...accepted, id: "history-user" }]} />);
+ expect(screen.getByLabelText(/video attachment/i)).toBe(video);
+ expect(video).toHaveAttribute("src", "/api/media/sig/clip");
+ unmount();
+ render(<ThreadMessages messages={[accepted]} />);
+ expect(screen.getByLabelText(/video attachment/i)).toHaveAttribute("src", "/api/media/sig/clip");
+ });
+
it("renders streaming reasoning as one compact activity line", () => {
const message: UIMessage = {
id: "a-reasoning-streaming",
diff --git a/webui/src/tests/queued-guidance.test.tsx b/webui/src/tests/queued-guidance.test.tsx
index 592a68907..5b50e739b 100644
--- a/webui/src/tests/queued-guidance.test.tsx
+++ b/webui/src/tests/queued-guidance.test.tsx
@@ -67,6 +67,20 @@ describe("merged waiting messages", () => {
});
});
+ it.each(["video", "file"] as const)("sends a restored large local %s and a browser upload without spending local bytes", (kind) => {
+ const local = { path: `C:\\project\\large.${kind === "video" ? "mp4" : "pdf"}`, name: "large reference", kind, size: 64 * 1024 * 1024 + 1, mime: kind === "video" ? "video/mp4" : "application/pdf", url: "/api/media/sig/local" };
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
+ { id: "first", text: "read references", images: [{ local, kind }, DOCUMENT] },
+ ]));
+ const onSend = vi.fn();
+ render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" ingressLimits={limits({ max_file_bytes: 5, max_total_bytes: 5 })} />);
+ fireEvent.click(screen.getByRole("button", { name: "Send now" }));
+ expect(onSend).toHaveBeenCalledWith("read references", [
+ expect.objectContaining({ media: { path: local.path, name: local.name } }),
+ expect.objectContaining({ media: { data_url: DOCUMENT.dataUrl, name: DOCUMENT.name } }),
+ ]);
+ });
+
it("preserves merged text longer than the former per-entry storage truncation across remounts", () => {
const onSend = vi.fn();
const first = render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming />);
@@ -155,7 +169,7 @@ describe("merged waiting messages", () => {
render(<ThreadComposer {...props} />);
await waitFor(() => expect(screen.queryByLabelText("Encoding…")).not.toBeInTheDocument());
expect(screen.getAllByTestId("composer-chip")).toHaveLength(2);
- expect(draftStore.get("chat-a")?.files.map((file) => file.name)).toEqual(["first.png", "second.txt"]);
+ expect(draftStore.get("chat-a")?.attachments.map((file) => file.name)).toEqual(["first.png", "second.txt"]);
});
it("retains a merged rejected send after leaving the topic during upload", async () => {
diff --git a/webui/src/tests/settings-apps-oauth.test.tsx b/webui/src/tests/settings-apps-oauth.test.tsx
index 2c9eb9caa..efb4e0047 100644
--- a/webui/src/tests/settings-apps-oauth.test.tsx
+++ b/webui/src/tests/settings-apps-oauth.test.tsx
@@ -288,7 +288,7 @@ describe("SettingsView Apps catalog", () => {
"Fix connection",
);
- await act(() => i18n.changeLanguage("zh-CN"));
+ await act(async () => { await i18n.changeLanguage("zh-CN"); });
expect(within(row as HTMLElement).getByText("连接失败。")).toBeInTheDocument();
const manage = within(row as HTMLElement).getByRole("button", { name: "管理 Xmind" });
expect(manage).toHaveTextContent("修复连接");
@@ -306,7 +306,7 @@ describe("SettingsView Apps catalog", () => {
{ name: "xmind", reset: true, use_proxy: "false" },
30_000,
));
- await act(() => i18n.changeLanguage("en"));
+ await act(async () => { await i18n.changeLanguage("en"); });
});
it("keeps an OAuth runtime failure visible after credentials are cleared", async () => {
diff --git a/webui/src/tests/settings-automations.test.tsx b/webui/src/tests/settings-automations.test.tsx
index 713b1c4d4..1fab1abcf 100644
--- a/webui/src/tests/settings-automations.test.tsx
+++ b/webui/src/tests/settings-automations.test.tsx
@@ -42,7 +42,7 @@ describe("automation channel identity", () => {
["ja", "メール"],
["es", "Correo electrónico"],
]) {
- await act(() => i18n.changeLanguage(locale));
+ await act(async () => { await i18n.changeLanguage(locale); });
expect(detail.getByText(name)).toBeVisible();
expect(detail.queryByText("Email")).not.toBeInTheDocument();
}
diff --git a/webui/src/tests/thread-composer-attach.test.tsx b/webui/src/tests/thread-composer-attach.test.tsx
index bd1a5bb04..f4e9de1c3 100644
--- a/webui/src/tests/thread-composer-attach.test.tsx
+++ b/webui/src/tests/thread-composer-attach.test.tsx
@@ -8,6 +8,7 @@ import {
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
+import { ComposerDraftStore } from "@/lib/composer-draft";
import type { EncodeResponse } from "@/lib/imageEncode";
import type { WebUIIngressLimits } from "@/lib/types";
@@ -425,3 +426,180 @@ describe("ThreadComposer — attachments", () => {
expect(onSend).not.toHaveBeenCalled();
});
});
+
+
+describe("local attachment paths and video ingress", () => {
+ const local = { path: "C:\\project\\my clip.mp4", name: "my clip.mp4", size: 12,
+ mime: "video/mp4", kind: "video" as const, url: "/api/media/sig/local" };
+
+ it("confirms a large pasted video path and sends only the borrowed reference", async () => {
+ const inspect = vi.fn().mockResolvedValue({ ...local, size: 64 * 1024 * 1024 + 1 });
+ const onSend = vi.fn();
+ render(<ThreadComposer onSend={onSend} onInspectAttachment={inspect} />);
+ const input = screen.getByLabelText(/message input/i);
+ fireEvent.change(input, { target: { value: "keep this " } });
+ (input as HTMLTextAreaElement).setSelectionRange(10, 10);
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => '"C:\\project\\my clip.mp4"' } });
+ await waitFor(() => expect(screen.getByTestId("composer-chip")).toHaveTextContent("my clip.mp4"));
+ expect(input).toHaveValue("keep this ");
+ expect(inspect).toHaveBeenCalledWith(local.path);
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(onSend.mock.calls[0][1][0].media).toEqual({ path: local.path, name: local.name });
+ });
+
+ it.each(["append", "prepend"])("keeps %s text written while the pasted path is being checked", async (edit) => {
+ let complete!: (attachment: typeof local) => void;
+ const inspect = vi.fn(() => new Promise<typeof local>((resolve) => { complete = resolve; }));
+ const onSend = vi.fn();
+ render(<ThreadComposer onSend={onSend} onInspectAttachment={inspect} />);
+ const input = screen.getByLabelText(/message input/i) as HTMLTextAreaElement;
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
+ const typed = edit === "append" ? `${local.path} describe it` : `请看 ${local.path}`;
+ fireEvent.change(input, { target: { value: typed, selectionStart: typed.length } });
+ await act(async () => complete(local));
+ await screen.findByTestId("composer-chip");
+ expect(input).toHaveValue(edit === "append" ? " describe it" : "请看 ");
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(onSend.mock.calls[0][0]).toBe(edit === "append" ? "describe it" : "请看");
+ expect(onSend.mock.calls[0][1][0].media).toEqual({ path: local.path, name: local.name });
+ });
+
+ it.each(["edit", "remove"])("does not attach a path after the user chooses to %s it during inspection", async (edit) => {
+ let complete!: (attachment: typeof local) => void;
+ render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
+ const input = screen.getByLabelText(/message input/i);
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
+ const typed = edit === "edit" ? local.path.replace("clip", "other") : "keep my new text";
+ fireEvent.change(input, { target: { value: typed } });
+ await act(async () => complete(local));
+ expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
+ expect(input).toHaveValue(typed);
+ expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled();
+ });
+
+ it("does not steal toolbar focus when a pending path is confirmed", async () => {
+ let complete!: (attachment: typeof local) => void;
+ render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
+ const input = screen.getByLabelText(/message input/i);
+ await waitFor(() => expect(input).toHaveFocus());
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
+ const attach = screen.getByRole("button", { name: /attach/i });
+ attach.focus();
+ expect(attach).toHaveFocus();
+ await act(async () => complete(local));
+ await screen.findByTestId("composer-chip");
+ expect(attach).toHaveFocus();
+ });
+
+ it("lets an IME composition finish before converting its pasted path", async () => {
+ let complete!: (attachment: typeof local) => void;
+ render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={() => new Promise((resolve) => { complete = resolve; })} />);
+ const input = screen.getByLabelText(/message input/i);
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
+ fireEvent.compositionStart(input);
+ fireEvent.change(input, { target: { value: `${local.path}你` } });
+ await act(async () => complete(local));
+ expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
+ fireEvent.compositionEnd(input);
+ await screen.findByTestId("composer-chip");
+ expect(input).toHaveValue("你");
+ });
+
+ it("ignores an inspection reply after the workspace scope changes", async () => {
+ let complete!: (attachment: typeof local) => void;
+ const inspect = () => new Promise<typeof local>((resolve) => { complete = resolve; });
+ const view = render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} workspaceScope={{ project_path: "C:\\project", access_mode: "full" }} />);
+ const input = screen.getByLabelText(/message input/i);
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => local.path } });
+ view.rerender(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} workspaceScope={{ project_path: "C:\\project", access_mode: "restricted" }} />);
+ await act(async () => complete(local));
+ expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
+ expect(input).toHaveValue(local.path);
+ expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled();
+ });
+
+ it("keeps mixed local and uploaded attachment order across draft remounts", async () => {
+ encodeImage.mockImplementation(async (file) => resolveReady(file));
+ const firstLocal = { ...local, path: "C:\\project\\first.png", name: "first.png", kind: "image" as const, mime: "image/png" };
+ const lastLocal = { ...firstLocal, path: "C:\\project\\last.png", name: "last.png" };
+ const inspect = vi.fn().mockResolvedValueOnce(firstLocal).mockResolvedValueOnce(lastLocal);
+ const store = new ComposerDraftStore();
+ const onSend = vi.fn();
+ const composer = () => <ThreadComposer draftKey="mixed-order" draftStore={store} onSend={onSend} onInspectAttachment={inspect} />;
+ const view = render(composer());
+ const input = screen.getByLabelText(/message input/i);
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => firstLocal.path } });
+ await screen.findByText(firstLocal.name);
+ fireEvent.change(input.closest("form")!.querySelector('input[type="file"]')!, { target: { files: [pngFile("middle.png")] } });
+ await screen.findByText("middle.png");
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => lastLocal.path } });
+ await screen.findByText(lastLocal.name);
+ fireEvent.change(input, { target: { value: "compare the first, second and third images" } });
+ await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
+ expect(screen.getAllByTestId("composer-chip").map((chip) => chip.textContent)).toEqual([
+ expect.stringContaining("first.png"), expect.stringContaining("middle.png"), expect.stringContaining("last.png"),
+ ]);
+ view.unmount();
+ render(composer());
+ await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
+ fireEvent.keyDown(screen.getByLabelText(/message input/i), { key: "Enter" });
+ expect(onSend.mock.calls[0][1].map((item: { media: { name: string } }) => item.media.name)).toEqual([
+ "first.png", "middle.png", "last.png",
+ ]);
+ });
+
+ it("keeps failed path text and attachment draft, and does not consume prose or URLs", async () => {
+ const inspect = vi.fn().mockRejectedValue(new Error("file not found"));
+ render(<ThreadComposer onSend={vi.fn()} onInspectAttachment={inspect} />);
+ const input = screen.getByLabelText(/message input/i);
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => "./missing.mp4" } });
+ await waitFor(() => expect(screen.getByText("file not found")).toBeInTheDocument());
+ expect(input).toHaveValue("./missing.mp4");
+ for (const text of ["look at ./missing.mp4 please", "https://host/clip.mp4", "const path = './clip.mp4'", "line one\n./clip.mp4"]) {
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => text } });
+ }
+ expect(inspect).toHaveBeenCalledTimes(1);
+ expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument();
+ });
+
+ it("does not charge large local documents against a picked document's upload budget", async () => {
+ const onSend = vi.fn();
+ const document = { ...local, path: "C:\\project\\large.pdf", name: "large.pdf", mime: "application/pdf", kind: "file" as const, size: 64 * 1024 * 1024 + 1 };
+ render(<ThreadComposer onSend={onSend} onInspectAttachment={vi.fn().mockResolvedValue(document)} ingressLimits={ingressLimits({ maxFileBytes: 8, maxTotalBytes: 8 })} />);
+ const input = screen.getByLabelText(/message input/i);
+ fireEvent.paste(input, { clipboardData: { items: [], getData: () => document.path } });
+ await screen.findByText(document.name);
+ const picker = input.closest("form")!.querySelector('input[type="file"]')!;
+ fireEvent.change(picker, { target: { files: [pdfFile("upload.pdf", 8)] } });
+ await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(onSend).toHaveBeenCalledWith("", [
+ expect.objectContaining({ media: { path: document.path, name: document.name } }),
+ expect.objectContaining({ media: expect.objectContaining({ name: "upload.pdf", data_url: expect.any(String) }) }),
+ ], undefined);
+ });
+
+ it("explains the size and limit of a rejected browser video without losing the draft", () => {
+ const onSend = vi.fn();
+ render(<ThreadComposer onSend={onSend} />);
+ const input = screen.getByLabelText(/message input/i);
+ fireEvent.change(input, { target: { value: "keep this text" } });
+ const file = new File([new Uint8Array(21 * 1024 * 1024)], "large.mp4", { type: "video/mp4" });
+ fireEvent.change(input.closest("form")!.querySelector('input[type="file"]')!, { target: { files: [file] } });
+ expect(screen.getByRole("alert")).toHaveTextContent("21.0 MiB");
+ expect(screen.getByRole("alert")).toHaveTextContent("20.0 MiB");
+ expect(input).toHaveValue("keep this text");
+ expect(onSend).not.toHaveBeenCalled();
+ });
+
+ it("uploads picked video bytes with the existing independent video size/count allowance", async () => {
+ const onSend = vi.fn();
+ render(<ThreadComposer onSend={onSend} ingressLimits={ingressLimits({ maxFileBytes: 3 })} />);
+ const input = screen.getByLabelText(/message input/i);
+ const picker = input.closest("form")!.querySelector('input[type="file"]')!;
+ fireEvent.change(picker, { target: { files: [new File(["movie"], "clip.mov", { type: "" })] } });
+ await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(onSend.mock.calls[0][1][0].media).toEqual({ data_url: `data:video/quicktime;base64,${btoa("movie")}`, name: "clip.mov" });
+ });
+});
diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx
index bb1de416e..faf667045 100644
--- a/webui/src/tests/thread-shell.test.tsx
+++ b/webui/src/tests/thread-shell.test.tsx
@@ -665,6 +665,33 @@ describe("ThreadShell", () => {
expect(client.sendMessage).not.toHaveBeenCalled();
});
+ it("restores the landing attachment draft in its created topic after a gateway rejection", async () => {
+ const client = { ...makeClient(), sendAttachments: vi.fn().mockRejectedValue(new Error("file not found")) };
+ const store = new ComposerDraftStore();
+ store.set("new:chat", {
+ text: "keep the first draft", sessionMentions: [], quotedContext: null,
+ attachments: [{ path: "/project/video.mp4", name: "video.mp4", size: 8, mime: "video/mp4", kind: "video", url: "" }],
+ });
+ const onCreateChat = vi.fn().mockResolvedValue("created");
+ const shell = (id: string | null) => wrap(client, <ThreadShell session={id ? session(id) : null}
+ title="First attachment" draftStore={store} onToggleSidebar={() => {}} onCreateChat={onCreateChat} />);
+ const view = render(shell(null));
+ await screen.findByTestId("composer-chip");
+ fireEvent.click(screen.getByRole("button", { name: "Send message" }));
+ await waitFor(() => expect(onCreateChat).toHaveBeenCalledTimes(1));
+ view.rerender(shell("created"));
+ await waitFor(() => expect(screen.getByRole("textbox")).toHaveValue("keep the first draft"));
+ expect(await screen.findByTestId("composer-chip")).toHaveTextContent("video.mp4");
+ expect(screen.getByRole("alert")).toHaveTextContent("file not found");
+ expect(store.get("websocket:created")?.attachments).toHaveLength(1);
+ expect(store.has("new:chat")).toBe(false);
+ client.sendAttachments.mockResolvedValue(undefined);
+ fireEvent.click(screen.getByRole("button", { name: "Send message" }));
+ await waitFor(() => expect(screen.queryByTestId("composer-chip")).not.toBeInTheDocument());
+ expect(screen.getByRole("textbox")).toHaveValue("");
+ expect(client.sendAttachments).toHaveBeenCalledTimes(2);
+ });
+
it("clears the welcome draft after a delayed new-chat send and an unchanged round-trip", async () => {
const client = makeClient();
const store = new ComposerDraftStore();
@@ -694,7 +721,7 @@ describe("ThreadShell", () => {
const client = makeClient();
let draftStore = new ComposerDraftStore();
draftStore.set("websocket:reload-draft", {
- text: "original", files: [], sessionMentions: [], quotedContext: "quoted answer",
+ text: "original", attachments: [], sessionMentions: [], quotedContext: "quoted answer",
});
const shell = () => wrap(client, (
<ThreadShell session={session("reload-draft")} title="Reload test" temporary={temporary}
@@ -740,8 +767,8 @@ describe("ThreadShell", () => {
it.each([false, true])("keeps text and quote drafts scoped to the session (temporary=%s)", async (temporary) => {
const client = makeClient();
const draftStore: ComposerDraftStore = new Map([
- ["websocket:draft-a", { text: "draft A", files: [], sessionMentions: [], quotedContext: "quote A" }],
- ["websocket:draft-b", { text: "draft B", files: [], sessionMentions: [], quotedContext: "quote B" }],
+ ["websocket:draft-a", { text: "draft A", attachments: [], sessionMentions: [], quotedContext: "quote A" }],
+ ["websocket:draft-b", { text: "draft B", attachments: [], sessionMentions: [], quotedContext: "quote B" }],
]);
const shell = (chatId: string) => wrap(client, (
<ThreadShell session={session(chatId)} title="Draft test" temporary={temporary}
diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx
index dc8980b6d..d907ba21d 100644
--- a/webui/src/tests/useNanobotStream.test.tsx
+++ b/webui/src/tests/useNanobotStream.test.tsx
@@ -2899,6 +2899,49 @@ describe("useNanobotStream", () => {
);
});
+ it("uses the accepted upload URL instead of retaining an encoded video in message state", () => {
+ const fake = fakeClient();
+ const { result } = renderHook(() => useNanobotStream("uploaded-video", EMPTY_MESSAGES), {
+ wrapper: wrap(fake.client),
+ });
+ act(() => {
+ result.current.send("watch", [{
+ media: { data_url: "data:video/webm;base64,AAAA", name: "clip.webm" },
+ preview: { kind: "video", url: "data:video/webm;base64,AAAA", name: "clip.webm" },
+ }]);
+ });
+ const optimistic = result.current.messages[0];
+ expect(optimistic.media).toEqual([{ kind: "video", name: "clip.webm" }]);
+ const media = [{ kind: "video" as const, url: "/api/media/sig/upload", name: "clip.webm" }];
+ act(() => fake.emit("uploaded-video", {
+ event: "message_accepted", chat_id: "uploaded-video",
+ turn_id: optimistic.turnId!, starts_turn: true, media_urls: media,
+ }));
+ expect(result.current.messages).toHaveLength(1);
+ expect(result.current.messages[0]).toMatchObject({ id: optimistic.id, media, deliveryStatus: "accepted" });
+ });
+
+ it("replaces a local reference's optimistic preview with the gateway's session URL", () => {
+ const fake = fakeClient();
+ const { result } = renderHook(() => useNanobotStream("local-video", EMPTY_MESSAGES), {
+ wrapper: wrap(fake.client),
+ });
+ act(() => {
+ result.current.send("watch", [{
+ media: { path: "/project/video.mp4", name: "video.mp4" },
+ preview: { kind: "video", url: "", name: "video.mp4" },
+ }]);
+ });
+ const optimistic = result.current.messages[0];
+ const media = [{ kind: "video" as const, url: "/api/media/sig/local-video", name: "video.mp4" }];
+ act(() => fake.emit("local-video", {
+ event: "user_message", chat_id: "local-video", text: "watch",
+ turn_id: optimistic.turnId!, starts_turn: true, media_urls: media,
+ }));
+ expect(result.current.messages).toHaveLength(1);
+ expect(result.current.messages[0]).toMatchObject({ id: optimistic.id, media, deliveryStatus: "accepted" });
+ });
+
it("inlines quoted context into the optimistic and outbound user message", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-quote", EMPTY_MESSAGES), {
diff --git a/webui/src/tests/useReconnectRuns.test.tsx b/webui/src/tests/useReconnectRuns.test.tsx
index c96980718..c005feab4 100644
--- a/webui/src/tests/useReconnectRuns.test.tsx
+++ b/webui/src/tests/useReconnectRuns.test.tsx
@@ -345,7 +345,7 @@ describe("durable run recovery", () => {
it.each(["failed read", "missing activity state"])("leaves %s unresolved", async (failure) => {
const body = completedThread();
- delete body.has_pending_tool_calls;
+ Reflect.deleteProperty(body, "has_pending_tool_calls");
body.events = body.events.slice(0, 2);
const fetchMock = failure === "failed read"
? vi.fn().mockRejectedValue(new Error("offline"))
@@ -390,7 +390,7 @@ describe("durable run recovery", () => {
it("accepts an explicit completed turn when an older host omits activity metadata", async () => {
const body = completedThread();
- delete body.has_pending_tool_calls;
+ Reflect.deleteProperty(body, "has_pending_tool_calls");
body.completed_turn_ids = ["turn-old"];
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body)));
const { client, running, reopen, close } = setup();