fix(webui): restore session-scoped file previews

This commit is contained in:
Xubin Ren committed 2026-09-24 15:17:05 +08:00
1 parent 1457904e8d
commit af5acabb33
15 files changed
+564 -70

No files matched your search

+45 -9
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import base64
import re
from pathlib import Path
from typing import Any
@@ -12,6 +13,20 @@ from nanobot.security.workspace_access import WorkspaceScope
from nanobot.security.workspace_policy import WorkspaceBoundaryError, resolve_allowed_path
MAX_FILE_PREVIEW_BYTES = 384 * 1024
MAX_IMAGE_PREVIEW_BYTES = 8 * 1024 * 1024
def _image_mime(prefix: bytes) -> str | None:
# Only inert raster formats; SVG/HTML continue to be shown as source.
if prefix.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
if prefix.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
if prefix.startswith((b"GIF87a", b"GIF89a")):
return "image/gif"
if prefix[:4] == b"RIFF" and prefix[8:12] == b"WEBP":
return "image/webp"
return None
class WebUIFilePreviewError(ValueError):
@@ -29,16 +44,36 @@ def file_preview_payload(
scope: WorkspaceScope,
max_bytes: int = MAX_FILE_PREVIEW_BYTES,
) -> dict[str, Any]:
"""Return a text preview for a file allowed by the session workspace scope."""
"""Return a bounded source or raster preview within the session workspace scope."""
resolved = _resolve_preview_path(raw_path, scope=scope)
try:
with open(resolved, "rb") as f:
raw = f.read(max_bytes + 1)
prefix = f.read(12)
mime = _image_mime(prefix)
limit = MAX_IMAGE_PREVIEW_BYTES if mime else max_bytes
raw = prefix + f.read(max(0, limit + 1 - len(prefix)))
size = resolved.stat().st_size
except OSError as e:
raise WebUIFilePreviewError(500, "failed to read file") from e
metadata = {
"path": str(resolved),
"display_path": _display_path(resolved, scope.project_path),
"project_path": str(scope.project_path),
"size": size,
}
if mime:
if len(raw) > MAX_IMAGE_PREVIEW_BYTES:
raise WebUIFilePreviewError(413, "image is too large to preview (maximum 8 MiB)")
return {
**metadata,
"kind": "image",
"mime_type": mime,
"data_url": f"data:{mime};base64,{base64.b64encode(raw).decode('ascii')}",
}
if b"\0" in raw[:4096]:
raise WebUIFilePreviewError(415, "binary files cannot be previewed")
@@ -49,14 +84,11 @@ def file_preview_payload(
except UnicodeDecodeError:
content = preview_bytes.decode("utf-8", errors="replace")
display_path = _display_path(resolved, scope.project_path)
return {
"path": str(resolved),
"display_path": display_path,
"project_path": str(scope.project_path),
**metadata,
"kind": "text",
"language": _language_for_path(resolved),
"content": content,
"size": resolved.stat().st_size,
"truncated": truncated,
}
@@ -66,15 +98,19 @@ def file_preview_availability_payload(
*,
scope: WorkspaceScope,
) -> dict[str, bool]:
"""Confirm that a path is a readable text preview candidate without loading it fully."""
"""Probe a readable source or raster candidate without loading it fully."""
resolved = _resolve_preview_path(raw_path, scope=scope)
try:
with open(resolved, "rb") as f:
prefix = f.read(4096)
size = resolved.stat().st_size
except OSError as e:
raise WebUIFilePreviewError(500, "failed to read file") from e
if b"\0" in prefix:
if _image_mime(prefix):
if size > MAX_IMAGE_PREVIEW_BYTES:
raise WebUIFilePreviewError(413, "image is too large to preview (maximum 8 MiB)")
elif b"\0" in prefix:
raise WebUIFilePreviewError(415, "binary files cannot be previewed")
return {"available": True}
+40
View File
@@ -37,6 +37,11 @@ from nanobot.session.webui_turns import (
from nanobot.utils.helpers import safe_filename
from nanobot.utils.prompt_templates import render_template
from nanobot.webui.cli_apps_api import normalize_cli_app_mentions
from nanobot.webui.file_preview import (
WebUIFilePreviewError,
file_preview_availability_payload,
file_preview_payload,
)
from nanobot.webui.forking import handle_webui_fork_chat
from nanobot.webui.gateway_services import GatewayServices
from nanobot.webui.mcp_presets_api import normalize_mcp_preset_mentions
@@ -781,6 +786,41 @@ class WebUICommandRouter:
)
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.
preview_payload = cast(dict[str, object], payload)
chat_id = preview_payload.get("chat_id")
path = preview_payload.get("path")
probe = preview_payload.get("probe") 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",
)
return
try:
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)
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}:
await self.send_webui_response(
connection, request_id, result={"available": False},
)
else:
await self.send_webui_response(
connection, request_id, status=exc.status, message=exc.message,
)
else:
await self.send_webui_response(connection, request_id, result=result)
return
payload_digest = hashlib.sha256(
json.dumps(
payload,
+3 -3
View File
@@ -1124,10 +1124,10 @@ class GatewayHTTPHandler:
else:
payload = file_preview_payload(path, scope=scope)
except WebUIFilePreviewError as e:
if is_probe and e.status in {400, 403, 404, 415}:
return _http_json_response({"available": False})
if is_probe 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)
return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS)
def _handle_session_automations(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):