fix(webui): restore session-scoped file previews
This commit is contained in:
1 parent
1457904e8d
commit
af5acabb33
15 files changed
+564
-70
No files matched your search
@@ -319,6 +319,53 @@ async def _new_temporary_chat(
|
||||
return payload["chat_id"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tmp_path) -> None:
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
(workspace / "notes.txt").write_text("synthetic preview")
|
||||
outside = tmp_path / "outside.txt"
|
||||
outside.write_text("outside")
|
||||
sessions = SessionManager(workspace)
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]}, bus,
|
||||
gateway=_basic_handler(
|
||||
bus, session_manager=sessions, workspace_path=workspace,
|
||||
default_restrict_to_workspace=False,
|
||||
),
|
||||
)
|
||||
owner, other = AsyncMock(), AsyncMock()
|
||||
chat_id = await _new_temporary_chat(channel, owner)
|
||||
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):
|
||||
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},
|
||||
})
|
||||
return json.loads(connection.send.await_args.args[0])
|
||||
|
||||
result = await preview(owner)
|
||||
assert result["ok"] is True
|
||||
assert result["result"]["content"] == "synthetic preview"
|
||||
assert (await preview(owner, probe=True))["result"] == {"available": True}
|
||||
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}
|
||||
assert (await preview(AsyncMock()))["error"]["status"] == 403
|
||||
assert not channel._webui_request_operations
|
||||
assert {path for path in tmp_path.rglob("*") if path.is_file()} == disk_before
|
||||
assert sessions.list_sessions() == []
|
||||
|
||||
await channel._dispatch_envelope(owner, "webui-client", {
|
||||
"type": "discard_temporary_chat", "chat_id": chat_id,
|
||||
})
|
||||
assert (await preview(owner))["error"]["status"] == 404
|
||||
assert not channel._webui_request_operations
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_attach_exposes_the_session_canonical_model_preset(bus, tmp_path) -> None:
|
||||
sessions = SessionManager(tmp_path)
|
||||
@@ -6171,6 +6218,7 @@ def test_handle_file_preview_returns_workspace_file(tmp_path) -> None:
|
||||
assert body["language"] == "python"
|
||||
assert body["content"].splitlines() == ["print('hello')"]
|
||||
assert body["truncated"] is False
|
||||
assert resp.headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
def test_handle_file_preview_probe_checks_availability_without_content(tmp_path) -> None:
|
||||
@@ -6198,6 +6246,7 @@ def test_handle_file_preview_probe_checks_availability_without_content(tmp_path)
|
||||
|
||||
assert resp.status_code == 200
|
||||
assert json.loads(resp.body.decode()) == {"available": True}
|
||||
assert resp.headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
def test_handle_file_preview_probe_reports_missing_file_as_unavailable(tmp_path) -> None:
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user