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:
chengyongru authored and GitHub committed 2026-10-22 18:32:18 +08:00
1 parent 7dfeff9ddf
commit 254f94b068
65 files changed
+1816 -292

No files matched your search

+6 -5
View File
@@ -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}]
+7 -3
View File
@@ -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)
+1
View File
@@ -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
@@ -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)")
+19 -18
View File
@@ -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"
+60
View File
@@ -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}
+9 -5
View File
@@ -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
+2 -1
View File
@@ -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",
+93 -20
View File
@@ -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(
+45 -10
View File
@@ -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":
+22 -2
View File
@@ -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
+26 -9
View File
@@ -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,
+9 -2
View File
@@ -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)
+3 -2
View File
@@ -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 --------------------------------------------------------