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)
# ---------------------------------------------------------------------------