feat(attachments): support local files and video attachments (#6321)
* feat(attachments): support local files and video attachments Share gateway inspection and send validation for borrowed local paths while preserving binary uploads, original-file ownership, and existing limits. Related to NAN-284. Native provider video input remains outside this change. * test: make cross-platform verification fixtures self-contained * test(webui): align typed fixtures with runtime contracts * fix(webui): preserve uploaded video playback during history sync * test(tui): preserve local attachment drafts across resizes * perf(attachments): preserve upload caches and release video previews * docs(webui): keep attachment guidance user-focused * chore: remove redundant dependency comment * test(providers): make stream idle renewal timing deterministic * fix(attachments): keep upload byte limits out of local references Validate common format/count rules separately from upload byte budgets. Keep local inspection and send-time checks metadata-only, and exclude local references from composer and pending-upload totals. Explain upload size rejections with actual size and maximum in all ten locales. Related to NAN-284. * fix(attachments): retain image references and draft order * fix(attachments): close local reference UX and authorization gaps * fix(attachments): preserve focus during asynchronous path confirmation
This commit is contained in:
1 parent
7dfeff9ddf
commit
254f94b068
65 files changed
+1816
-292
No files matched your search
@@ -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)")
|
||||
@@ -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.
|
||||
|
||||
@@ -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())
|
||||
@@ -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"]
|
||||
@@ -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),
|
||||
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user