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] + + +@pytest.mark.parametrize("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" + + +@pytest.mark.parametrize("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"] + + +@pytest.mark.asyncio +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("*")) + + +@pytest.mark.asyncio +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() + + +@pytest.mark.asyncio +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" + + +@pytest.mark.asyncio +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)] + + +@pytest.mark.parametrize("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; + 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 { - 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 + + +@pytest.mark.asyncio +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" + + +@pytest.mark.asyncio +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 +@pytest.fixture(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 | 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 { 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>) => 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>) => 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 { + 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 + inspectAttachment(path: string): Promise 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 { 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 { + if (!this.chatId) return Promise.reject(new Error("chat is not ready")) + return this.requestMutation("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( action: string, payload: Record = {}, 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() - private readonly images = new Map() + private readonly images = new Map() 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(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 (