feat(webui): unify file preview actions
This commit is contained in:
1 parent
af5acabb33
commit
05bee21b10
24 files changed
+542
-10
No files matched your search
@@ -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
|
inline preview. Select the filename in the activity row to open the read-only
|
||||||
file preview panel.
|
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
|
File previews follow the active topic's access mode. Restricted workspace access
|
||||||
previews only files under the selected workspace. Full Access can preview files
|
previews only files under the selected workspace. Full Access can preview files
|
||||||
outside the workspace when that access mode is allowed by the gateway.
|
outside the workspace when that access mode is allowed by the gateway.
|
||||||
|
|||||||
@@ -339,11 +339,11 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm
|
|||||||
channel._webui_connections.add(other)
|
channel._webui_connections.add(other)
|
||||||
disk_before = {path for path in tmp_path.rglob("*") if path.is_file()}
|
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", {
|
await channel._dispatch_envelope(connection, "webui-client", {
|
||||||
"type": "webui_request", "request_id": "private-preview",
|
"type": "webui_request", "request_id": "private-preview",
|
||||||
"action": "temporary_chat.file_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])
|
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["ok"] is True
|
||||||
assert result["result"]["content"] == "synthetic preview"
|
assert result["result"]["content"] == "synthetic preview"
|
||||||
assert (await preview(owner, probe=True))["result"] == {"available": True}
|
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(other))["error"]["status"] == 404
|
||||||
assert (await preview(owner, str(outside)))["error"]["status"] == 403
|
assert (await preview(owner, str(outside)))["error"]["status"] == 403
|
||||||
assert (await preview(owner, str(outside), probe=True))["result"] == {"available": False}
|
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,
|
"type": "discard_temporary_chat", "chat_id": chat_id,
|
||||||
})
|
})
|
||||||
assert (await preview(owner))["error"]["status"] == 404
|
assert (await preview(owner))["error"]["status"] == 404
|
||||||
|
assert (await preview(owner, metadata=True))["error"]["status"] == 404
|
||||||
assert not channel._webui_request_operations
|
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
|
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:
|
def test_handle_file_preview_returns_workspace_file(tmp_path) -> None:
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,16 @@ class WebUIFilePreviewError(ValueError):
|
|||||||
self.message = message
|
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(
|
def file_preview_payload(
|
||||||
raw_path: str | None,
|
raw_path: str | None,
|
||||||
*,
|
*,
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ from nanobot.webui.file_preview import (
|
|||||||
WebUIFilePreviewError,
|
WebUIFilePreviewError,
|
||||||
file_preview_availability_payload,
|
file_preview_availability_payload,
|
||||||
file_preview_payload,
|
file_preview_payload,
|
||||||
|
file_reference_payload,
|
||||||
)
|
)
|
||||||
from nanobot.webui.forking import handle_webui_fork_chat
|
from nanobot.webui.forking import handle_webui_fork_chat
|
||||||
from nanobot.webui.gateway_services import GatewayServices
|
from nanobot.webui.gateway_services import GatewayServices
|
||||||
@@ -793,6 +794,7 @@ class WebUICommandRouter:
|
|||||||
chat_id = preview_payload.get("chat_id")
|
chat_id = preview_payload.get("chat_id")
|
||||||
path = preview_payload.get("path")
|
path = preview_payload.get("path")
|
||||||
probe = preview_payload.get("probe") is True
|
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):
|
if not isinstance(chat_id, str) or not isinstance(path, str):
|
||||||
await self.send_webui_response(
|
await self.send_webui_response(
|
||||||
connection, request_id, status=400, message="invalid preview request",
|
connection, request_id, status=400, message="invalid preview request",
|
||||||
@@ -802,14 +804,18 @@ class WebUICommandRouter:
|
|||||||
policy = self._temporary_chats.message_policy(connection, chat_id, "")
|
policy = self._temporary_chats.message_policy(connection, chat_id, "")
|
||||||
if policy is None:
|
if policy is None:
|
||||||
raise TemporaryChatError("temporary_chat_unavailable")
|
raise TemporaryChatError("temporary_chat_unavailable")
|
||||||
preview = file_preview_availability_payload if probe else file_preview_payload
|
if metadata_only:
|
||||||
result = preview(path, scope=policy.workspace_scope)
|
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:
|
except TemporaryChatError as exc:
|
||||||
await self.send_webui_response(
|
await self.send_webui_response(
|
||||||
connection, request_id, status=404, message=exc.detail,
|
connection, request_id, status=404, message=exc.detail,
|
||||||
)
|
)
|
||||||
except WebUIFilePreviewError as exc:
|
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(
|
await self.send_webui_response(
|
||||||
connection, request_id, result={"available": False},
|
connection, request_id, result={"available": False},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ from nanobot.webui.file_preview import (
|
|||||||
WebUIFilePreviewError,
|
WebUIFilePreviewError,
|
||||||
file_preview_availability_payload,
|
file_preview_availability_payload,
|
||||||
file_preview_payload,
|
file_preview_payload,
|
||||||
|
file_reference_payload,
|
||||||
)
|
)
|
||||||
from nanobot.webui.gateway_tokens import GatewayTokenStore, token_response_payload
|
from nanobot.webui.gateway_tokens import GatewayTokenStore, token_response_payload
|
||||||
from nanobot.webui.http_utils import JSONResponseMetrics
|
from nanobot.webui.http_utils import JSONResponseMetrics
|
||||||
@@ -1117,14 +1118,17 @@ class GatewayHTTPHandler:
|
|||||||
query = _parse_query(request.path)
|
query = _parse_query(request.path)
|
||||||
path = _query_first(query, "path")
|
path = _query_first(query, "path")
|
||||||
is_probe = _query_first(query, "probe") == "1"
|
is_probe = _query_first(query, "probe") == "1"
|
||||||
|
metadata_only = _query_first(query, "metadata") == "1"
|
||||||
try:
|
try:
|
||||||
scope = self.workspaces.scope_for_session_key(decoded_key)
|
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)
|
payload = file_preview_availability_payload(path, scope=scope)
|
||||||
else:
|
else:
|
||||||
payload = file_preview_payload(path, scope=scope)
|
payload = file_preview_payload(path, scope=scope)
|
||||||
except WebUIFilePreviewError as e:
|
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_json_response({"available": False}, extra_headers=_NO_STORE_HEADERS)
|
||||||
return _http_error(e.status, e.message)
|
return _http_error(e.status, e.message)
|
||||||
return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS)
|
return _http_json_response(payload, extra_headers=_NO_STORE_HEADERS)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from nanobot.webui.file_preview import (
|
|||||||
WebUIFilePreviewError,
|
WebUIFilePreviewError,
|
||||||
file_preview_availability_payload,
|
file_preview_availability_payload,
|
||||||
file_preview_payload,
|
file_preview_payload,
|
||||||
|
file_reference_payload,
|
||||||
)
|
)
|
||||||
|
|
||||||
PNG = base64.b64decode(
|
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"), [
|
@pytest.mark.parametrize(("data", "mime"), [
|
||||||
(PNG, "image/png"),
|
(PNG, "image/png"),
|
||||||
(b"\xff\xd8\xff\xe0\0example", "image/jpeg"),
|
(b"\xff\xd8\xff\xe0\0example", "image/jpeg"),
|
||||||
|
|||||||
@@ -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<FileReferenceMetadata>;
|
||||||
|
openPreview: (path: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FileActionsContext = createContext<FileActionsContextValue | undefined>(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<FileReferenceMetadata | null>(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 (
|
||||||
|
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||||
|
<span
|
||||||
|
className="not-prose inline-flex max-w-full items-baseline gap-0.5 align-baseline"
|
||||||
|
onContextMenu={(event) => {
|
||||||
|
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 ? <DropdownMenuTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })}
|
||||||
|
title={t("fileActions.title")}
|
||||||
|
onClick={(event) => event.stopPropagation()}
|
||||||
|
className="inline-flex h-6 w-6 shrink-0 items-center justify-center self-center rounded-md text-muted-foreground/65 transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
<Ellipsis className="h-3.5 w-3.5" aria-hidden />
|
||||||
|
</button>
|
||||||
|
</DropdownMenuTrigger> : null}
|
||||||
|
{enabled ? <DropdownMenuContent align="end" collisionPadding={12} onClick={(event) => event.stopPropagation()}>
|
||||||
|
{preview ? <>
|
||||||
|
<DropdownMenuItem onSelect={() => preview(path)}>
|
||||||
|
<PanelRight className="mr-2 h-4 w-4" aria-hidden />
|
||||||
|
{t("fileActions.preview")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
</> : null}
|
||||||
|
<DropdownMenuItem disabled={!resolved} onSelect={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (resolved) void copy(resolved.path);
|
||||||
|
}}>
|
||||||
|
<Copy className="mr-2 h-4 w-4" aria-hidden />
|
||||||
|
{t("fileActions.copyAbsolute")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem disabled={!resolved?.relative_path} onSelect={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (resolved?.relative_path) void copy(resolved.relative_path);
|
||||||
|
}}>
|
||||||
|
<Copy className="mr-2 h-4 w-4" aria-hidden />
|
||||||
|
{t("fileActions.copyRelative")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
{!resolved ? <DropdownMenuItem onSelect={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
void copy(path);
|
||||||
|
}}>{t("fileActions.copyReference")}</DropdownMenuItem> : null}
|
||||||
|
<div role="status" className="max-w-64 px-2.5 py-1.5 text-xs text-muted-foreground">
|
||||||
|
{copyStatus ? t(`fileActions.${copyStatus}`)
|
||||||
|
: loadFailed ? t("fileActions.unavailable")
|
||||||
|
: !resolved && resolveMetadata ? t("fileActions.loading")
|
||||||
|
: t("fileActions.gatewayPath")}
|
||||||
|
</div>
|
||||||
|
</DropdownMenuContent> : null}
|
||||||
|
</span>
|
||||||
|
</DropdownMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,9 +4,10 @@ import { AlertCircle, ChevronRight, Loader2, X } from "lucide-react";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { CodeBlock } from "@/components/CodeBlock";
|
import { CodeBlock } from "@/components/CodeBlock";
|
||||||
|
import { FileActions } from "@/components/FileActions";
|
||||||
import { splitFilePath } from "@/components/FileReferenceChip";
|
import { splitFilePath } from "@/components/FileReferenceChip";
|
||||||
import { ApiError, fetchFilePreview } from "@/lib/api";
|
import { ApiError, fetchFilePreview } from "@/lib/api";
|
||||||
import type { FilePreviewPayload } from "@/lib/types";
|
import type { FilePreviewPayload, FileReferenceMetadata } from "@/lib/types";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
interface FilePreviewPanelProps {
|
interface FilePreviewPanelProps {
|
||||||
@@ -64,6 +65,16 @@ export function FilePreviewPanel({
|
|||||||
}, [path, sessionKey]);
|
}, [path, sessionKey]);
|
||||||
|
|
||||||
const displayPath = state.status === "ready" ? state.payload.display_path : path;
|
const displayPath = state.status === "ready" ? state.payload.display_path : path;
|
||||||
|
const metadata = useMemo<FileReferenceMetadata | undefined>(() => {
|
||||||
|
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 previewPath = state.status === "ready" ? state.payload.path : displayPath;
|
||||||
const normalizedPreviewPath = previewPath.replace(/\\/g, "/");
|
const normalizedPreviewPath = previewPath.replace(/\\/g, "/");
|
||||||
const hasRootPrefix = normalizedPreviewPath.startsWith("/");
|
const hasRootPrefix = normalizedPreviewPath.startsWith("/");
|
||||||
@@ -201,6 +212,7 @@ export function FilePreviewPanel({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
|
{metadata ? <FileActions path={previewPath} metadata={metadata} /> : null}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { KeyboardEvent, MouseEvent } from "react";
|
import type { KeyboardEvent, MouseEvent } from "react";
|
||||||
|
import { FileActions } from "@/components/FileActions";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Tooltip,
|
Tooltip,
|
||||||
@@ -60,6 +61,7 @@ export function FileReferenceChip({
|
|||||||
openPreview(event);
|
openPreview(event);
|
||||||
};
|
};
|
||||||
return (
|
return (
|
||||||
|
<FileActions path={targetPath} onPreview={onOpen}>
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
@@ -120,6 +122,7 @@ export function FileReferenceChip({
|
|||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
|
</FileActions>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
|
|
||||||
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
|
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
|
||||||
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
|
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
|
||||||
|
import { FileActionsProvider } from "@/components/FileActions";
|
||||||
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
|
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
|
||||||
import { PromptNavigator } from "@/components/thread/PromptNavigator";
|
import { PromptNavigator } from "@/components/thread/PromptNavigator";
|
||||||
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
|
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
|
||||||
@@ -28,6 +29,7 @@ import { useFilePreviewState, type FilePreviewStore } from "@/hooks/useFilePrevi
|
|||||||
import {
|
import {
|
||||||
ApiError,
|
ApiError,
|
||||||
fetchFilePreviewAvailability,
|
fetchFilePreviewAvailability,
|
||||||
|
fetchFileReferenceMetadata,
|
||||||
fetchInstalledCliApps,
|
fetchInstalledCliApps,
|
||||||
fetchMcpPresets,
|
fetchMcpPresets,
|
||||||
fetchSettings,
|
fetchSettings,
|
||||||
@@ -48,6 +50,7 @@ import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
|
|||||||
import type {
|
import type {
|
||||||
ChatSummary,
|
ChatSummary,
|
||||||
FilePreviewPayload,
|
FilePreviewPayload,
|
||||||
|
FileReferenceMetadata,
|
||||||
RoundUsage,
|
RoundUsage,
|
||||||
SettingsPayload,
|
SettingsPayload,
|
||||||
SlashCommand,
|
SlashCommand,
|
||||||
@@ -1525,6 +1528,21 @@ export function ThreadShell({
|
|||||||
const openFilePreviewRef = useRef(handleOpenFilePreview);
|
const openFilePreviewRef = useRef(handleOpenFilePreview);
|
||||||
openFilePreviewRef.current = handleOpenFilePreview;
|
openFilePreviewRef.current = handleOpenFilePreview;
|
||||||
const openFilePreview = useCallback((path: string) => openFilePreviewRef.current(path), []);
|
const openFilePreview = useCallback((path: string) => openFilePreviewRef.current(path), []);
|
||||||
|
const resolveFileMetadata = useCallback((path: string) => {
|
||||||
|
if (!previewSessionKey) return Promise.reject(new Error("No active session"));
|
||||||
|
return temporary
|
||||||
|
? client.requestMutation<FileReferenceMetadata>("temporary_chat.file_preview", {
|
||||||
|
chat_id: chatId, path, metadata: true,
|
||||||
|
})
|
||||||
|
: fetchFileReferenceMetadata(getToken(), previewSessionKey, path);
|
||||||
|
}, [chatId, client, getToken, previewSessionKey, temporary]);
|
||||||
|
const fileActions = useMemo(() => ({
|
||||||
|
resolveMetadata: resolveFileMetadata,
|
||||||
|
// A menu's explicit Preview action should not toggle an already-open file closed.
|
||||||
|
openPreview: (path: string) => {
|
||||||
|
if (path !== filePreviewPath || filePreviewClosing) openFilePreview(path);
|
||||||
|
},
|
||||||
|
}), [filePreviewClosing, filePreviewPath, openFilePreview, resolveFileMetadata]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!filePreviewPath || !headerActive) return;
|
if (!filePreviewPath || !headerActive) return;
|
||||||
@@ -1814,6 +1832,7 @@ export function ThreadShell({
|
|||||||
<FilePreviewAvailabilityProvider
|
<FilePreviewAvailabilityProvider
|
||||||
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
|
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
|
||||||
>
|
>
|
||||||
|
<FileActionsProvider value={previewSessionKey ? fileActions : undefined}>
|
||||||
<ThreadViewport
|
<ThreadViewport
|
||||||
ref={viewportRef}
|
ref={viewportRef}
|
||||||
messages={displayMessages}
|
messages={displayMessages}
|
||||||
@@ -1842,6 +1861,7 @@ export function ThreadShell({
|
|||||||
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
|
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
|
||||||
onQuoteSelection={session ? handleQuoteSelection : undefined}
|
onQuoteSelection={session ? handleQuoteSelection : undefined}
|
||||||
/>
|
/>
|
||||||
|
</FileActionsProvider>
|
||||||
</FilePreviewAvailabilityProvider>
|
</FilePreviewAvailabilityProvider>
|
||||||
</div>
|
</div>
|
||||||
{headerPortalTarget && headerActive
|
{headerPortalTarget && headerActive
|
||||||
|
|||||||
@@ -1881,6 +1881,19 @@
|
|||||||
"next": "Next image",
|
"next": "Next image",
|
||||||
"close": "Close image preview"
|
"close": "Close image preview"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "File actions for {{name}}",
|
||||||
|
"title": "File actions",
|
||||||
|
"preview": "Preview",
|
||||||
|
"copyAbsolute": "Copy absolute path",
|
||||||
|
"copyRelative": "Copy relative path",
|
||||||
|
"copyReference": "Copy reference",
|
||||||
|
"copied": "Copied",
|
||||||
|
"failed": "Could not copy. Please try again.",
|
||||||
|
"unavailable": "Could not resolve this file. You can copy the original reference.",
|
||||||
|
"loading": "Resolving file…",
|
||||||
|
"gatewayPath": "Paths refer to the gateway machine."
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "File preview",
|
"aria": "File preview",
|
||||||
"breadcrumb": "File path",
|
"breadcrumb": "File path",
|
||||||
|
|||||||
@@ -1682,6 +1682,19 @@
|
|||||||
"next": "Imagen siguiente",
|
"next": "Imagen siguiente",
|
||||||
"close": "Cerrar vista previa"
|
"close": "Cerrar vista previa"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "Acciones de archivo para {{name}}",
|
||||||
|
"title": "Acciones de archivo",
|
||||||
|
"preview": "Vista previa",
|
||||||
|
"copyAbsolute": "Copiar ruta absoluta",
|
||||||
|
"copyRelative": "Copiar ruta relativa",
|
||||||
|
"copyReference": "Copiar referencia",
|
||||||
|
"copied": "Copiado",
|
||||||
|
"failed": "No se pudo copiar. Inténtalo de nuevo.",
|
||||||
|
"unavailable": "No se pudo resolver el archivo. Puedes copiar la referencia original.",
|
||||||
|
"loading": "Resolviendo archivo…",
|
||||||
|
"gatewayPath": "Las rutas pertenecen al equipo del gateway."
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "Vista previa de archivo",
|
"aria": "Vista previa de archivo",
|
||||||
"breadcrumb": "Ruta del archivo",
|
"breadcrumb": "Ruta del archivo",
|
||||||
|
|||||||
@@ -1681,6 +1681,19 @@
|
|||||||
"next": "Image suivante",
|
"next": "Image suivante",
|
||||||
"close": "Fermer l’aperçu"
|
"close": "Fermer l’aperçu"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "Actions du fichier {{name}}",
|
||||||
|
"title": "Actions du fichier",
|
||||||
|
"preview": "Aperçu",
|
||||||
|
"copyAbsolute": "Copier le chemin absolu",
|
||||||
|
"copyRelative": "Copier le chemin relatif",
|
||||||
|
"copyReference": "Copier la référence",
|
||||||
|
"copied": "Copié",
|
||||||
|
"failed": "Impossible de copier. Réessayez.",
|
||||||
|
"unavailable": "Impossible de résoudre ce fichier. Vous pouvez copier la référence d’origine.",
|
||||||
|
"loading": "Résolution du fichier…",
|
||||||
|
"gatewayPath": "Les chemins désignent la machine de la passerelle."
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "Aperçu du fichier",
|
"aria": "Aperçu du fichier",
|
||||||
"breadcrumb": "Chemin du fichier",
|
"breadcrumb": "Chemin du fichier",
|
||||||
|
|||||||
@@ -1681,6 +1681,19 @@
|
|||||||
"next": "Gambar berikutnya",
|
"next": "Gambar berikutnya",
|
||||||
"close": "Tutup pratinjau"
|
"close": "Tutup pratinjau"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "Tindakan file untuk {{name}}",
|
||||||
|
"title": "Tindakan file",
|
||||||
|
"preview": "Pratinjau",
|
||||||
|
"copyAbsolute": "Salin jalur absolut",
|
||||||
|
"copyRelative": "Salin jalur relatif",
|
||||||
|
"copyReference": "Salin referensi",
|
||||||
|
"copied": "Disalin",
|
||||||
|
"failed": "Tidak dapat menyalin. Coba lagi.",
|
||||||
|
"unavailable": "File tidak dapat ditemukan. Anda dapat menyalin referensi aslinya.",
|
||||||
|
"loading": "Memeriksa file…",
|
||||||
|
"gatewayPath": "Jalur merujuk ke komputer gateway."
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "Pratinjau file",
|
"aria": "Pratinjau file",
|
||||||
"breadcrumb": "Jalur file",
|
"breadcrumb": "Jalur file",
|
||||||
|
|||||||
@@ -1681,6 +1681,19 @@
|
|||||||
"next": "次の画像",
|
"next": "次の画像",
|
||||||
"close": "プレビューを閉じる"
|
"close": "プレビューを閉じる"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "{{name}} のファイル操作",
|
||||||
|
"title": "ファイル操作",
|
||||||
|
"preview": "プレビュー",
|
||||||
|
"copyAbsolute": "絶対パスをコピー",
|
||||||
|
"copyRelative": "相対パスをコピー",
|
||||||
|
"copyReference": "元の参照をコピー",
|
||||||
|
"copied": "コピーしました",
|
||||||
|
"failed": "コピーできませんでした。再試行してください。",
|
||||||
|
"unavailable": "ファイルを解決できません。元の参照をコピーできます。",
|
||||||
|
"loading": "ファイルを確認中…",
|
||||||
|
"gatewayPath": "パスはゲートウェイのマシンを指します。"
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "ファイルプレビュー",
|
"aria": "ファイルプレビュー",
|
||||||
"breadcrumb": "ファイルパス",
|
"breadcrumb": "ファイルパス",
|
||||||
|
|||||||
@@ -1681,6 +1681,19 @@
|
|||||||
"next": "다음 이미지",
|
"next": "다음 이미지",
|
||||||
"close": "미리보기 닫기"
|
"close": "미리보기 닫기"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "{{name}} 파일 작업",
|
||||||
|
"title": "파일 작업",
|
||||||
|
"preview": "미리보기",
|
||||||
|
"copyAbsolute": "절대 경로 복사",
|
||||||
|
"copyRelative": "상대 경로 복사",
|
||||||
|
"copyReference": "원본 참조 복사",
|
||||||
|
"copied": "복사됨",
|
||||||
|
"failed": "복사하지 못했습니다. 다시 시도하세요.",
|
||||||
|
"unavailable": "파일을 확인할 수 없습니다. 원본 참조를 복사할 수 있습니다.",
|
||||||
|
"loading": "파일 확인 중…",
|
||||||
|
"gatewayPath": "경로는 게이트웨이 컴퓨터를 가리킵니다."
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "파일 미리보기",
|
"aria": "파일 미리보기",
|
||||||
"breadcrumb": "파일 경로",
|
"breadcrumb": "파일 경로",
|
||||||
|
|||||||
@@ -1695,6 +1695,19 @@
|
|||||||
"next": "Próxima imagem",
|
"next": "Próxima imagem",
|
||||||
"close": "Fechar pré-visualização"
|
"close": "Fechar pré-visualização"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "Ações do arquivo {{name}}",
|
||||||
|
"title": "Ações do arquivo",
|
||||||
|
"preview": "Pré-visualizar",
|
||||||
|
"copyAbsolute": "Copiar caminho absoluto",
|
||||||
|
"copyRelative": "Copiar caminho relativo",
|
||||||
|
"copyReference": "Copiar referência",
|
||||||
|
"copied": "Copiado",
|
||||||
|
"failed": "Não foi possível copiar. Tente novamente.",
|
||||||
|
"unavailable": "Não foi possível localizar o arquivo. Você pode copiar a referência original.",
|
||||||
|
"loading": "Localizando arquivo…",
|
||||||
|
"gatewayPath": "Os caminhos se referem à máquina do gateway."
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "Pré-visualização de arquivo",
|
"aria": "Pré-visualização de arquivo",
|
||||||
"breadcrumb": "Caminho do arquivo",
|
"breadcrumb": "Caminho do arquivo",
|
||||||
|
|||||||
@@ -1681,6 +1681,19 @@
|
|||||||
"next": "Ảnh tiếp theo",
|
"next": "Ảnh tiếp theo",
|
||||||
"close": "Đóng xem trước"
|
"close": "Đóng xem trước"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "Thao tác tệp {{name}}",
|
||||||
|
"title": "Thao tác tệp",
|
||||||
|
"preview": "Xem trước",
|
||||||
|
"copyAbsolute": "Sao chép đường dẫn tuyệt đối",
|
||||||
|
"copyRelative": "Sao chép đường dẫn tương đối",
|
||||||
|
"copyReference": "Sao chép tham chiếu",
|
||||||
|
"copied": "Đã sao chép",
|
||||||
|
"failed": "Không thể sao chép. Vui lòng thử lại.",
|
||||||
|
"unavailable": "Không thể xác định tệp. Bạn có thể sao chép tham chiếu gốc.",
|
||||||
|
"loading": "Đang xác định tệp…",
|
||||||
|
"gatewayPath": "Đường dẫn thuộc máy chạy gateway."
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "Xem trước tệp",
|
"aria": "Xem trước tệp",
|
||||||
"breadcrumb": "Đường dẫn tệp",
|
"breadcrumb": "Đường dẫn tệp",
|
||||||
|
|||||||
@@ -1881,6 +1881,19 @@
|
|||||||
"next": "下一张",
|
"next": "下一张",
|
||||||
"close": "关闭预览"
|
"close": "关闭预览"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "{{name}} 的文件操作",
|
||||||
|
"title": "文件操作",
|
||||||
|
"preview": "预览",
|
||||||
|
"copyAbsolute": "复制绝对路径",
|
||||||
|
"copyRelative": "复制相对路径",
|
||||||
|
"copyReference": "复制原始引用",
|
||||||
|
"copied": "已复制",
|
||||||
|
"failed": "复制失败,请重试。",
|
||||||
|
"unavailable": "无法解析此文件,可复制原始引用。",
|
||||||
|
"loading": "正在解析文件…",
|
||||||
|
"gatewayPath": "路径指向网关所在的机器。"
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "文件预览",
|
"aria": "文件预览",
|
||||||
"breadcrumb": "文件路径",
|
"breadcrumb": "文件路径",
|
||||||
|
|||||||
@@ -1681,6 +1681,19 @@
|
|||||||
"next": "下一張",
|
"next": "下一張",
|
||||||
"close": "關閉預覽"
|
"close": "關閉預覽"
|
||||||
},
|
},
|
||||||
|
"fileActions": {
|
||||||
|
"menu": "{{name}} 的檔案操作",
|
||||||
|
"title": "檔案操作",
|
||||||
|
"preview": "預覽",
|
||||||
|
"copyAbsolute": "複製絕對路徑",
|
||||||
|
"copyRelative": "複製相對路徑",
|
||||||
|
"copyReference": "複製原始參照",
|
||||||
|
"copied": "已複製",
|
||||||
|
"failed": "複製失敗,請重試。",
|
||||||
|
"unavailable": "無法解析此檔案,可複製原始參照。",
|
||||||
|
"loading": "正在解析檔案…",
|
||||||
|
"gatewayPath": "路徑指向閘道所在的電腦。"
|
||||||
|
},
|
||||||
"filePreview": {
|
"filePreview": {
|
||||||
"aria": "檔案預覽",
|
"aria": "檔案預覽",
|
||||||
"breadcrumb": "檔案路徑",
|
"breadcrumb": "檔案路徑",
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import type {
|
|||||||
ChatSummary,
|
ChatSummary,
|
||||||
CliAppsPayload,
|
CliAppsPayload,
|
||||||
FilePreviewPayload,
|
FilePreviewPayload,
|
||||||
|
FileReferenceMetadata,
|
||||||
ImageGenerationSettingsUpdate,
|
ImageGenerationSettingsUpdate,
|
||||||
McpPresetsPayload,
|
McpPresetsPayload,
|
||||||
McpOAuthFlowPayload,
|
McpOAuthFlowPayload,
|
||||||
@@ -460,6 +461,20 @@ export async function fetchFilePreview(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function fetchFileReferenceMetadata(
|
||||||
|
token: string,
|
||||||
|
key: string,
|
||||||
|
path: string,
|
||||||
|
): Promise<FileReferenceMetadata> {
|
||||||
|
const query = new URLSearchParams({ path, metadata: "1" });
|
||||||
|
return request<FileReferenceMetadata>(
|
||||||
|
`/api/sessions/${encodeURIComponent(key)}/file-preview?${query}`,
|
||||||
|
token,
|
||||||
|
{ cache: "no-store" },
|
||||||
|
API_READ_TIMEOUT_MS,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export async function fetchFilePreviewAvailability(
|
export async function fetchFilePreviewAvailability(
|
||||||
token: string,
|
token: string,
|
||||||
key: string,
|
key: string,
|
||||||
|
|||||||
@@ -1607,6 +1607,11 @@ export interface WebuiThreadTraceDetailPayload {
|
|||||||
events: ThreadProjectionEvent[];
|
events: ThreadProjectionEvent[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface FileReferenceMetadata {
|
||||||
|
path: string;
|
||||||
|
relative_path: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
interface FilePreviewMetadata {
|
interface FilePreviewMetadata {
|
||||||
path: string;
|
path: string;
|
||||||
display_path: string;
|
display_path: string;
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { FileActions, FileActionsProvider } from "@/components/FileActions";
|
||||||
|
import { FileReferenceChip } from "@/components/FileReferenceChip";
|
||||||
|
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||||
|
import type { FileReferenceMetadata } from "@/lib/types";
|
||||||
|
|
||||||
|
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: vi.fn() }));
|
||||||
|
const details = { path: "/workspace/notes.md", relative_path: "notes.md" };
|
||||||
|
|
||||||
|
describe("File actions", () => {
|
||||||
|
beforeEach(() => vi.mocked(copyTextToClipboard).mockReset().mockResolvedValue(true));
|
||||||
|
|
||||||
|
it("resolves paths only when opened and uses the same menu for both copies", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const resolveMetadata = vi.fn().mockResolvedValue(details);
|
||||||
|
const openPreview = vi.fn();
|
||||||
|
render(<FileActionsProvider value={{ resolveMetadata, openPreview }}>
|
||||||
|
<FileReferenceChip path="notes.md:12" onOpen={vi.fn()} />
|
||||||
|
</FileActionsProvider>);
|
||||||
|
expect(resolveMetadata).not.toHaveBeenCalled();
|
||||||
|
await user.click(screen.getByRole("button", { name: "File actions for notes.md:12" }));
|
||||||
|
await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).not.toHaveAttribute("data-disabled"));
|
||||||
|
expect(resolveMetadata).toHaveBeenCalledWith("notes.md:12");
|
||||||
|
await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" }));
|
||||||
|
expect(copyTextToClipboard).toHaveBeenLastCalledWith(details.path);
|
||||||
|
expect(await screen.findByText("Copied")).toBeVisible();
|
||||||
|
await user.click(screen.getByRole("menuitem", { name: "Copy relative path" }));
|
||||||
|
expect(copyTextToClipboard).toHaveBeenLastCalledWith("notes.md");
|
||||||
|
await user.click(screen.getByRole("menuitem", { name: "Preview" }));
|
||||||
|
expect(openPreview).toHaveBeenCalledWith("notes.md:12");
|
||||||
|
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps primary click working and supports context menu and Shift+F10", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const onOpen = vi.fn();
|
||||||
|
render(<FileReferenceChip path="src/app.ts" onOpen={onOpen} />);
|
||||||
|
const reference = screen.getByRole("button", { name: "src/app.ts" });
|
||||||
|
await user.click(reference);
|
||||||
|
expect(onOpen).toHaveBeenCalledTimes(1);
|
||||||
|
expect(onOpen).toHaveBeenCalledWith("src/app.ts");
|
||||||
|
fireEvent.contextMenu(reference);
|
||||||
|
expect(await screen.findByRole("menuitem", { name: "Preview" })).toBeVisible();
|
||||||
|
await user.keyboard("{Escape}");
|
||||||
|
fireEvent.keyDown(reference, { key: "F10", shiftKey: true });
|
||||||
|
expect(await screen.findByRole("menuitem", { name: "Copy reference" })).toBeVisible();
|
||||||
|
expect(onOpen).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not invent a relative path for files outside the project", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<FileActions path="/media/image.png" metadata={{ path: "/media/image.png", relative_path: null }} />);
|
||||||
|
await user.click(screen.getByRole("button", { name: "File actions for image.png" }));
|
||||||
|
expect(screen.getByRole("menuitem", { name: "Copy relative path" })).toHaveAttribute("data-disabled");
|
||||||
|
expect(screen.queryByRole("menuitem", { name: "Preview" })).not.toBeInTheDocument();
|
||||||
|
await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" }));
|
||||||
|
expect(copyTextToClipboard).toHaveBeenCalledWith("/media/image.png");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retains the original reference if resolution fails and reports clipboard errors", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
vi.mocked(copyTextToClipboard).mockResolvedValue(false);
|
||||||
|
render(<FileActionsProvider value={{ resolveMetadata: vi.fn().mockRejectedValue(new Error("404")), openPreview: vi.fn() }}>
|
||||||
|
<FileReferenceChip path="missing.txt" onOpen={vi.fn()} />
|
||||||
|
</FileActionsProvider>);
|
||||||
|
await user.click(screen.getByRole("button", { name: "File actions for missing.txt" }));
|
||||||
|
expect(await screen.findByText(/Could not resolve this file/)).toBeVisible();
|
||||||
|
expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).toHaveAttribute("data-disabled");
|
||||||
|
await user.click(screen.getByRole("menuitem", { name: "Copy reference" }));
|
||||||
|
expect(copyTextToClipboard).toHaveBeenCalledWith("missing.txt");
|
||||||
|
expect(await screen.findByText("Could not copy. Please try again.")).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores late metadata from a previous session", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
let resolveOld!: (value: FileReferenceMetadata) => void;
|
||||||
|
const previous = { resolveMetadata: () => new Promise<FileReferenceMetadata>((resolve) => { resolveOld = resolve; }), openPreview: vi.fn() };
|
||||||
|
const current = { resolveMetadata: vi.fn().mockResolvedValue({ path: "/new/notes.md", relative_path: "notes.md" }), openPreview: vi.fn() };
|
||||||
|
const view = (value: typeof current | typeof previous) => <FileActionsProvider value={value}><FileReferenceChip path="notes.md" onOpen={vi.fn()} /></FileActionsProvider>;
|
||||||
|
const { rerender } = render(view(previous));
|
||||||
|
await user.click(screen.getByRole("button", { name: "File actions for notes.md" }));
|
||||||
|
rerender(view(current));
|
||||||
|
await waitFor(() => expect(current.resolveMetadata).toHaveBeenCalled());
|
||||||
|
await act(async () => resolveOld(details));
|
||||||
|
await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" }));
|
||||||
|
expect(copyTextToClipboard).toHaveBeenCalledWith("/new/notes.md");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("degrades to the original reference on an older gateway response", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<FileActionsProvider value={{ resolveMetadata: vi.fn().mockResolvedValue({ path: "/workspace/notes.md", content: "old preview response" }), openPreview: vi.fn() }}>
|
||||||
|
<FileReferenceChip path="notes.md" onOpen={vi.fn()} />
|
||||||
|
</FileActionsProvider>);
|
||||||
|
await user.click(screen.getByRole("button", { name: "File actions for notes.md" }));
|
||||||
|
expect(await screen.findByText(/Could not resolve this file/)).toBeVisible();
|
||||||
|
expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).toHaveAttribute("data-disabled");
|
||||||
|
await user.click(screen.getByRole("menuitem", { name: "Copy reference" }));
|
||||||
|
expect(copyTextToClipboard).toHaveBeenCalledWith("notes.md");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -59,7 +59,9 @@ class TestSocket {
|
|||||||
} else if (frame.type === "webui_request" && frame.action === "temporary_chat.file_preview") {
|
} else if (frame.type === "webui_request" && frame.action === "temporary_chat.file_preview") {
|
||||||
queueMicrotask(() => this.receive({
|
queueMicrotask(() => this.receive({
|
||||||
event: "webui_response", request_id: frame.request_id, ok: true,
|
event: "webui_response", request_id: frame.request_id, ok: true,
|
||||||
result: frame.payload.probe ? { available: true } : previewFile(String(frame.payload.path)),
|
result: frame.payload.metadata
|
||||||
|
? { path: `/workspace/${String(frame.payload.path)}`, relative_path: frame.payload.path }
|
||||||
|
: frame.payload.probe ? { available: true } : previewFile(String(frame.payload.path)),
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -119,6 +121,7 @@ describe("temporary chat navigation", () => {
|
|||||||
}
|
}
|
||||||
if (path.includes("/file-preview?")) {
|
if (path.includes("/file-preview?")) {
|
||||||
const query = new URL(path, "http://test").searchParams;
|
const query = new URL(path, "http://test").searchParams;
|
||||||
|
if (query.has("metadata")) return Response.json({ path: `/workspace/${query.get("path")}`, relative_path: query.get("path") });
|
||||||
return Response.json(query.has("probe") ? { available: true } : previewFile(query.get("path")!));
|
return Response.json(query.has("probe") ? { available: true } : previewFile(query.get("path")!));
|
||||||
}
|
}
|
||||||
if (withFiles && path.includes("/webui-thread")) {
|
if (withFiles && path.includes("/webui-thread")) {
|
||||||
@@ -161,7 +164,17 @@ describe("temporary chat navigation", () => {
|
|||||||
} else {
|
} else {
|
||||||
await selectTopic("Regular topic");
|
await selectTopic("Regular topic");
|
||||||
}
|
}
|
||||||
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
|
fireEvent.contextMenu(await screen.findByRole("button", { name: "notes.txt" }));
|
||||||
|
await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).not.toHaveAttribute("data-disabled"));
|
||||||
|
if (temporary) {
|
||||||
|
expect(TestSocket.current.sent).toContainEqual(expect.objectContaining({
|
||||||
|
type: "webui_request", action: "temporary_chat.file_preview",
|
||||||
|
payload: expect.objectContaining({ path: "notes.txt", metadata: true }),
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("path=notes.txt&metadata=1"))).toBe(true);
|
||||||
|
}
|
||||||
|
fireEvent.click(screen.getByRole("menuitem", { name: "Preview" }));
|
||||||
await screen.findByText("Preview of notes.txt");
|
await screen.findByText("Preview of notes.txt");
|
||||||
await selectTopic("Second pane");
|
await selectTopic("Second pane");
|
||||||
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
|
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
|
||||||
|
|||||||
Reference in new issue
Block a user