From 05bee21b1068cb4e68561ef965e15f3bca1151a7 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:03:37 +0800 Subject: [PATCH] feat(webui): unify file preview actions --- docs/webui.md | 9 ++ .../websocket/tests/test_websocket_channel.py | 35 ++++- nanobot/webui/file_preview.py | 10 ++ nanobot/webui/inbound_commands.py | 12 +- nanobot/webui/ws_http.py | 8 +- tests/webui/test_file_preview.py | 42 ++++++ webui/src/components/FileActions.tsx | 129 ++++++++++++++++++ webui/src/components/FilePreviewPanel.tsx | 14 +- webui/src/components/FileReferenceChip.tsx | 3 + webui/src/components/thread/ThreadShell.tsx | 20 +++ webui/src/i18n/locales/en/common.json | 13 ++ webui/src/i18n/locales/es/common.json | 13 ++ webui/src/i18n/locales/fr/common.json | 13 ++ webui/src/i18n/locales/id/common.json | 13 ++ webui/src/i18n/locales/ja/common.json | 13 ++ webui/src/i18n/locales/ko/common.json | 13 ++ webui/src/i18n/locales/pt-BR/common.json | 13 ++ webui/src/i18n/locales/vi/common.json | 13 ++ webui/src/i18n/locales/zh-CN/common.json | 13 ++ webui/src/i18n/locales/zh-TW/common.json | 13 ++ webui/src/lib/api.ts | 15 ++ webui/src/lib/types.ts | 5 + webui/src/tests/file-actions.test.tsx | 103 ++++++++++++++ .../tests/temporary-chat-navigation.test.tsx | 17 ++- 24 files changed, 542 insertions(+), 10 deletions(-) create mode 100644 webui/src/components/FileActions.tsx create mode 100644 webui/src/tests/file-actions.test.tsx diff --git a/docs/webui.md b/docs/webui.md index fd6a1a7c7..da558f17e 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -136,6 +136,15 @@ them with **View diff**. Large diffs may hide unchanged lines or truncate the inline preview. Select the filename in the activity row to open the read-only file preview panel. +Use the **…** menu beside a file reference (or right-click it) to preview the file +and copy its absolute or project-relative path. The same menu is available in +the preview header. Keyboard users can focus a reference and press **Shift+F10**. +Paths are resolved on the gateway machine, which may not be the computer running +your browser. Files outside the project do not have a project-relative path. +If a reference cannot be resolved, you can still copy the original reference; +the menu does not invent an absolute path. Finder, external editor and terminal +launching are not available from this browser menu. + File previews follow the active topic's access mode. Restricted workspace access previews only files under the selected workspace. Full Access can preview files outside the workspace when that access mode is allowed by the gateway. diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index d16b03eed..b497063d2 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -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 diff --git a/nanobot/webui/file_preview.py b/nanobot/webui/file_preview.py index fb1bc7edb..192084fd4 100644 --- a/nanobot/webui/file_preview.py +++ b/nanobot/webui/file_preview.py @@ -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, *, diff --git a/nanobot/webui/inbound_commands.py b/nanobot/webui/inbound_commands.py index 330b37555..16f471d8b 100644 --- a/nanobot/webui/inbound_commands.py +++ b/nanobot/webui/inbound_commands.py @@ -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}, ) diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index f9e724545..c0d0f1f61 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -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) diff --git a/tests/webui/test_file_preview.py b/tests/webui/test_file_preview.py index 72ac718ad..e5ca00729 100644 --- a/tests/webui/test_file_preview.py +++ b/tests/webui/test_file_preview.py @@ -8,6 +8,7 @@ from nanobot.webui.file_preview import ( WebUIFilePreviewError, file_preview_availability_payload, file_preview_payload, + file_reference_payload, ) PNG = base64.b64decode( @@ -15,6 +16,47 @@ PNG = base64.b64decode( ) +def test_file_reference_metadata_does_not_read_contents(tmp_path, monkeypatch) -> None: + source = tmp_path / "notes with space.bin" + source.write_bytes(b"\0binary") + scope = default_workspace_scope(tmp_path, restrict_to_workspace=True) + monkeypatch.setattr("builtins.open", lambda *args, **kwargs: pytest.fail("read contents")) + assert file_reference_payload("notes%20with%20space.bin:12", scope=scope) == { + "path": str(source.resolve()), "relative_path": "notes with space.bin", + } + + +def test_file_reference_outside_project_has_no_relative_path(tmp_path) -> None: + workspace = tmp_path / "workspace" + workspace.mkdir() + outside = tmp_path / "elsewhere.txt" + outside.write_text("example") + scope = default_workspace_scope(workspace, restrict_to_workspace=False) + assert file_reference_payload(str(outside), scope=scope) == { + "path": str(outside.resolve()), "relative_path": None, + } + + +@pytest.mark.parametrize("target", ["../elsewhere.txt", "linked.txt"]) +def test_file_reference_rejects_traversal_and_symlink_escape(tmp_path, target) -> None: + workspace = tmp_path / "workspace" + workspace.mkdir() + outside = tmp_path / "elsewhere.txt" + outside.write_text("example") + (workspace / "linked.txt").symlink_to(outside) + scope = default_workspace_scope(workspace, restrict_to_workspace=True) + with pytest.raises(WebUIFilePreviewError) as error: + file_reference_payload(target, scope=scope) + assert error.value.status == 403 + + +@pytest.mark.parametrize("target", ["missing.txt", "."]) +def test_file_reference_rejects_missing_files_and_directories(tmp_path, target) -> None: + with pytest.raises(WebUIFilePreviewError) as error: + file_reference_payload(target, scope=default_workspace_scope(tmp_path, True)) + assert error.value.status == 404 + + @pytest.mark.parametrize(("data", "mime"), [ (PNG, "image/png"), (b"\xff\xd8\xff\xe0\0example", "image/jpeg"), diff --git a/webui/src/components/FileActions.tsx b/webui/src/components/FileActions.tsx new file mode 100644 index 000000000..2432597f3 --- /dev/null +++ b/webui/src/components/FileActions.tsx @@ -0,0 +1,129 @@ +import { createContext, useContext, useEffect, useState, type ReactNode } from "react"; +import { Copy, Ellipsis, PanelRight } from "lucide-react"; +import { useTranslation } from "react-i18next"; + +import { + DropdownMenu, DropdownMenuContent, DropdownMenuItem, + DropdownMenuSeparator, DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { copyTextToClipboard } from "@/lib/clipboard"; +import type { FileReferenceMetadata } from "@/lib/types"; + +interface FileActionsContextValue { + resolveMetadata: (path: string) => Promise; + openPreview: (path: string) => void; +} + +const FileActionsContext = createContext(undefined); + +export const FileActionsProvider = FileActionsContext.Provider; + +/** Shared by reply references, activity rows, and the preview header. */ +export function FileActions({ + path, children, onPreview, metadata, +}: { + path: string; + children?: ReactNode; + onPreview?: (path: string) => void; + metadata?: FileReferenceMetadata; +}) { + const context = useContext(FileActionsContext); + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const [resolved, setResolved] = useState(null); + const [loadFailed, setLoadFailed] = useState(false); + const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null); + const resolveMetadata = context?.resolveMetadata; + + useEffect(() => { + let cancelled = false; + setResolved(metadata ?? null); + setLoadFailed(false); + setCopyStatus(null); + if (open && !metadata && resolveMetadata) { + void resolveMetadata(path).then((value) => { + if (typeof value.path !== "string" || !(value.relative_path === null || typeof value.relative_path === "string")) { + throw new Error("File metadata is unavailable on this gateway"); + } + if (!cancelled) setResolved(value); + }).catch(() => { if (!cancelled) setLoadFailed(true); }); + } + return () => { cancelled = true; }; + }, [open, path, metadata, resolveMetadata]); + + const enabled = Boolean(context || onPreview || metadata); + + const copy = async (value: string) => { + const success = await copyTextToClipboard(value); + setCopyStatus(success ? "copied" : "failed"); + }; + const preview = onPreview ? context?.openPreview ?? onPreview : undefined; + + return ( + + { + if (!enabled) return; + event.preventDefault(); + event.stopPropagation(); + setOpen(true); + }} + onKeyDown={(event) => { + if (!enabled) return; + if (event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey)) { + event.preventDefault(); + event.stopPropagation(); + setOpen(true); + } + }} + > + {children} + {enabled ? + + : null} + {enabled ? event.stopPropagation()}> + {preview ? <> + preview(path)}> + + {t("fileActions.preview")} + + + : null} + { + event.preventDefault(); + if (resolved) void copy(resolved.path); + }}> + + {t("fileActions.copyAbsolute")} + + { + event.preventDefault(); + if (resolved?.relative_path) void copy(resolved.relative_path); + }}> + + {t("fileActions.copyRelative")} + + {!resolved ? { + event.preventDefault(); + void copy(path); + }}>{t("fileActions.copyReference")} : null} +
+ {copyStatus ? t(`fileActions.${copyStatus}`) + : loadFailed ? t("fileActions.unavailable") + : !resolved && resolveMetadata ? t("fileActions.loading") + : t("fileActions.gatewayPath")} +
+
: null} +
+
+ ); +} diff --git a/webui/src/components/FilePreviewPanel.tsx b/webui/src/components/FilePreviewPanel.tsx index 01434897f..412403327 100644 --- a/webui/src/components/FilePreviewPanel.tsx +++ b/webui/src/components/FilePreviewPanel.tsx @@ -4,9 +4,10 @@ import { AlertCircle, ChevronRight, Loader2, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { CodeBlock } from "@/components/CodeBlock"; +import { FileActions } from "@/components/FileActions"; import { splitFilePath } from "@/components/FileReferenceChip"; import { ApiError, fetchFilePreview } from "@/lib/api"; -import type { FilePreviewPayload } from "@/lib/types"; +import type { FilePreviewPayload, FileReferenceMetadata } from "@/lib/types"; import { cn } from "@/lib/utils"; interface FilePreviewPanelProps { @@ -64,6 +65,16 @@ export function FilePreviewPanel({ }, [path, sessionKey]); const displayPath = state.status === "ready" ? state.payload.display_path : path; + const metadata = useMemo(() => { + if (state.status !== "ready") return undefined; + const { path: absolute, project_path: root, display_path: relative } = state.payload; + // display_path is absolute for files outside the session project (e.g. media). + const normalizedRoot = root?.replace(/\\/g, "/").replace(/\/+$/, ""); + return { + path: absolute, + relative_path: normalizedRoot != null && absolute.replace(/\\/g, "/").startsWith(`${normalizedRoot}/`) ? relative : null, + }; + }, [state]); const previewPath = state.status === "ready" ? state.payload.path : displayPath; const normalizedPreviewPath = previewPath.replace(/\\/g, "/"); const hasRootPrefix = normalizedPreviewPath.startsWith("/"); @@ -201,6 +212,7 @@ export function FilePreviewPanel({ ); })} + {metadata ? : null}