feat(webui): unify file preview actions

This commit is contained in:
Xubin Ren committed 2026-09-24 15:17:05 +08:00
1 parent af5acabb33
commit 05bee21b10
24 files changed
+542 -10

No files matched your search

@@ -339,11 +339,11 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm
channel._webui_connections.add(other)
disk_before = {path for path in tmp_path.rglob("*") if path.is_file()}
async def preview(connection, path="notes.txt", probe=False):
async def preview(connection, path="notes.txt", probe=False, metadata=False):
await channel._dispatch_envelope(connection, "webui-client", {
"type": "webui_request", "request_id": "private-preview",
"action": "temporary_chat.file_preview",
"payload": {"chat_id": chat_id, "path": path, "probe": probe},
"payload": {"chat_id": chat_id, "path": path, "probe": probe, "metadata": metadata},
})
return json.loads(connection.send.await_args.args[0])
@@ -351,6 +351,11 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm
assert result["ok"] is True
assert result["result"]["content"] == "synthetic preview"
assert (await preview(owner, probe=True))["result"] == {"available": True}
assert (await preview(owner, metadata=True))["result"] == {
"path": str((workspace / "notes.txt").resolve()), "relative_path": "notes.txt",
}
assert (await preview(other, metadata=True))["error"]["status"] == 404
assert (await preview(owner, str(outside), metadata=True))["error"]["status"] == 403
assert (await preview(other))["error"]["status"] == 404
assert (await preview(owner, str(outside)))["error"]["status"] == 403
assert (await preview(owner, str(outside), probe=True))["result"] == {"available": False}
@@ -363,6 +368,7 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm
"type": "discard_temporary_chat", "chat_id": chat_id,
})
assert (await preview(owner))["error"]["status"] == 404
assert (await preview(owner, metadata=True))["error"]["status"] == 404
assert not channel._webui_request_operations
@@ -6189,6 +6195,31 @@ def test_handle_webui_thread_get_returns_canonical_events_by_default(
assert answer["response_sources"] == sources
@pytest.mark.parametrize("authorized", [True, False])
def test_handle_file_reference_metadata_is_authenticated_and_no_store(tmp_path, authorized) -> None:
from urllib.parse import quote
from websockets.datastructures import Headers
from websockets.http11 import Request
source = tmp_path / "notes.bin"
source.write_bytes(b"\0binary")
gateway = _basic_handler(MagicMock(), workspace_path=tmp_path)
gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0
enc = quote("websocket:file-actions", safe="")
req = Request(
f"/api/sessions/{enc}/file-preview?path=notes.bin&metadata=1",
Headers([("Authorization", "Bearer tok")]) if authorized else Headers(),
)
resp = gateway.http._handle_file_preview(req, enc)
assert resp.status_code == (200 if authorized else 401)
if authorized:
assert json.loads(resp.body.decode()) == {
"path": str(source.resolve()), "relative_path": "notes.bin",
}
assert resp.headers["Cache-Control"] == "no-store"
def test_handle_file_preview_returns_workspace_file(tmp_path) -> None:
from urllib.parse import quote
+10
View File
@@ -38,6 +38,16 @@ class WebUIFilePreviewError(ValueError):
self.message = message
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)
try:
relative = resolved.relative_to(scope.project_path).as_posix()
except ValueError:
relative = None
return {"path": str(resolved), "relative_path": relative}
def file_preview_payload(
raw_path: str | None,
*,
+9 -3
View File
@@ -41,6 +41,7 @@ from nanobot.webui.file_preview import (
WebUIFilePreviewError,
file_preview_availability_payload,
file_preview_payload,
file_reference_payload,
)
from nanobot.webui.forking import handle_webui_fork_chat
from nanobot.webui.gateway_services import GatewayServices
@@ -793,6 +794,7 @@ class WebUICommandRouter:
chat_id = preview_payload.get("chat_id")
path = preview_payload.get("path")
probe = preview_payload.get("probe") is True
metadata_only = preview_payload.get("metadata") is True
if not isinstance(chat_id, str) or not isinstance(path, str):
await self.send_webui_response(
connection, request_id, status=400, message="invalid preview request",
@@ -802,14 +804,18 @@ class WebUICommandRouter:
policy = self._temporary_chats.message_policy(connection, chat_id, "")
if policy is None:
raise TemporaryChatError("temporary_chat_unavailable")
preview = file_preview_availability_payload if probe else file_preview_payload
result = preview(path, scope=policy.workspace_scope)
if metadata_only:
result = file_reference_payload(path, scope=policy.workspace_scope)
elif probe:
result = file_preview_availability_payload(path, scope=policy.workspace_scope)
else:
result = file_preview_payload(path, scope=policy.workspace_scope)
except TemporaryChatError as exc:
await self.send_webui_response(
connection, request_id, status=404, message=exc.detail,
)
except WebUIFilePreviewError as exc:
if probe and exc.status in {400, 403, 404, 413, 415}:
if probe and not metadata_only and exc.status in {400, 403, 404, 413, 415}:
await self.send_webui_response(
connection, request_id, result={"available": False},
)
+6 -2
View File
@@ -41,6 +41,7 @@ from nanobot.webui.file_preview import (
WebUIFilePreviewError,
file_preview_availability_payload,
file_preview_payload,
file_reference_payload,
)
from nanobot.webui.gateway_tokens import GatewayTokenStore, token_response_payload
from nanobot.webui.http_utils import JSONResponseMetrics
@@ -1117,14 +1118,17 @@ class GatewayHTTPHandler:
query = _parse_query(request.path)
path = _query_first(query, "path")
is_probe = _query_first(query, "probe") == "1"
metadata_only = _query_first(query, "metadata") == "1"
try:
scope = self.workspaces.scope_for_session_key(decoded_key)
if is_probe:
if metadata_only:
payload = file_reference_payload(path, scope=scope)
elif is_probe:
payload = file_preview_availability_payload(path, scope=scope)
else:
payload = file_preview_payload(path, scope=scope)
except WebUIFilePreviewError as e:
if is_probe and e.status in {400, 403, 404, 413, 415}:
if is_probe and not metadata_only and e.status in {400, 403, 404, 413, 415}:
return _http_json_response({"available": False}, extra_headers=_NO_STORE_HEADERS)
return _http_error(e.status, e.message)
return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS)