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

+49
View File
@@ -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()
+24 -7
View File
@@ -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)
# ---------------------------------------------------------------------------
+17 -4
View File
@@ -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"
+17 -3
View File
@@ -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
@@ -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"]
+3 -4
View File
@@ -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
+8
View File
@@ -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 = []