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

+129
View File
@@ -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>
);
}
+13 -1
View File
@@ -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<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 normalizedPreviewPath = previewPath.replace(/\\/g, "/");
const hasRootPrefix = normalizedPreviewPath.startsWith("/");
@@ -201,6 +212,7 @@ export function FilePreviewPanel({
);
})}
</nav>
{metadata ? <FileActions path={previewPath} metadata={metadata} /> : null}
<button
type="button"
onClick={onClose}
@@ -1,4 +1,5 @@
import type { KeyboardEvent, MouseEvent } from "react";
import { FileActions } from "@/components/FileActions";
import {
Tooltip,
@@ -60,6 +61,7 @@ export function FileReferenceChip({
openPreview(event);
};
return (
<FileActions path={targetPath} onPreview={onOpen}>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
@@ -120,6 +122,7 @@ export function FileReferenceChip({
</TooltipContent>
</Tooltip>
</TooltipProvider>
</FileActions>
);
}
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { FileActionsProvider } from "@/components/FileActions";
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
@@ -28,6 +29,7 @@ import { useFilePreviewState, type FilePreviewStore } from "@/hooks/useFilePrevi
import {
ApiError,
fetchFilePreviewAvailability,
fetchFileReferenceMetadata,
fetchInstalledCliApps,
fetchMcpPresets,
fetchSettings,
@@ -48,6 +50,7 @@ import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
import type {
ChatSummary,
FilePreviewPayload,
FileReferenceMetadata,
RoundUsage,
SettingsPayload,
SlashCommand,
@@ -1525,6 +1528,21 @@ export function ThreadShell({
const openFilePreviewRef = useRef(handleOpenFilePreview);
openFilePreviewRef.current = handleOpenFilePreview;
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(() => {
if (!filePreviewPath || !headerActive) return;
@@ -1814,6 +1832,7 @@ export function ThreadShell({
<FilePreviewAvailabilityProvider
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
>
<FileActionsProvider value={previewSessionKey ? fileActions : undefined}>
<ThreadViewport
ref={viewportRef}
messages={displayMessages}
@@ -1842,6 +1861,7 @@ export function ThreadShell({
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
onQuoteSelection={session ? handleQuoteSelection : undefined}
/>
</FileActionsProvider>
</FilePreviewAvailabilityProvider>
</div>
{headerPortalTarget && headerActive
+13
View File
@@ -1881,6 +1881,19 @@
"next": "Next image",
"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": {
"aria": "File preview",
"breadcrumb": "File path",
+13
View File
@@ -1682,6 +1682,19 @@
"next": "Imagen siguiente",
"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": {
"aria": "Vista previa de archivo",
"breadcrumb": "Ruta del archivo",
+13
View File
@@ -1681,6 +1681,19 @@
"next": "Image suivante",
"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": {
"aria": "Aperçu du fichier",
"breadcrumb": "Chemin du fichier",
+13
View File
@@ -1681,6 +1681,19 @@
"next": "Gambar berikutnya",
"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": {
"aria": "Pratinjau file",
"breadcrumb": "Jalur file",
+13
View File
@@ -1681,6 +1681,19 @@
"next": "次の画像",
"close": "プレビューを閉じる"
},
"fileActions": {
"menu": "{{name}} のファイル操作",
"title": "ファイル操作",
"preview": "プレビュー",
"copyAbsolute": "絶対パスをコピー",
"copyRelative": "相対パスをコピー",
"copyReference": "元の参照をコピー",
"copied": "コピーしました",
"failed": "コピーできませんでした。再試行してください。",
"unavailable": "ファイルを解決できません。元の参照をコピーできます。",
"loading": "ファイルを確認中…",
"gatewayPath": "パスはゲートウェイのマシンを指します。"
},
"filePreview": {
"aria": "ファイルプレビュー",
"breadcrumb": "ファイルパス",
+13
View File
@@ -1681,6 +1681,19 @@
"next": "다음 이미지",
"close": "미리보기 닫기"
},
"fileActions": {
"menu": "{{name}} 파일 작업",
"title": "파일 작업",
"preview": "미리보기",
"copyAbsolute": "절대 경로 복사",
"copyRelative": "상대 경로 복사",
"copyReference": "원본 참조 복사",
"copied": "복사됨",
"failed": "복사하지 못했습니다. 다시 시도하세요.",
"unavailable": "파일을 확인할 수 없습니다. 원본 참조를 복사할 수 있습니다.",
"loading": "파일 확인 중…",
"gatewayPath": "경로는 게이트웨이 컴퓨터를 가리킵니다."
},
"filePreview": {
"aria": "파일 미리보기",
"breadcrumb": "파일 경로",
+13
View File
@@ -1695,6 +1695,19 @@
"next": "Próxima imagem",
"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": {
"aria": "Pré-visualização de arquivo",
"breadcrumb": "Caminho do arquivo",
+13
View File
@@ -1681,6 +1681,19 @@
"next": "Ảnh tiếp theo",
"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": {
"aria": "Xem trước tệp",
"breadcrumb": "Đường dẫn tệp",
+13
View File
@@ -1881,6 +1881,19 @@
"next": "下一张",
"close": "关闭预览"
},
"fileActions": {
"menu": "{{name}} 的文件操作",
"title": "文件操作",
"preview": "预览",
"copyAbsolute": "复制绝对路径",
"copyRelative": "复制相对路径",
"copyReference": "复制原始引用",
"copied": "已复制",
"failed": "复制失败,请重试。",
"unavailable": "无法解析此文件,可复制原始引用。",
"loading": "正在解析文件…",
"gatewayPath": "路径指向网关所在的机器。"
},
"filePreview": {
"aria": "文件预览",
"breadcrumb": "文件路径",
+13
View File
@@ -1681,6 +1681,19 @@
"next": "下一張",
"close": "關閉預覽"
},
"fileActions": {
"menu": "{{name}} 的檔案操作",
"title": "檔案操作",
"preview": "預覽",
"copyAbsolute": "複製絕對路徑",
"copyRelative": "複製相對路徑",
"copyReference": "複製原始參照",
"copied": "已複製",
"failed": "複製失敗,請重試。",
"unavailable": "無法解析此檔案,可複製原始參照。",
"loading": "正在解析檔案…",
"gatewayPath": "路徑指向閘道所在的電腦。"
},
"filePreview": {
"aria": "檔案預覽",
"breadcrumb": "檔案路徑",
+15
View File
@@ -8,6 +8,7 @@ import type {
ChatSummary,
CliAppsPayload,
FilePreviewPayload,
FileReferenceMetadata,
ImageGenerationSettingsUpdate,
McpPresetsPayload,
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(
token: string,
key: string,
+5
View File
@@ -1607,6 +1607,11 @@ export interface WebuiThreadTraceDetailPayload {
events: ThreadProjectionEvent[];
}
export interface FileReferenceMetadata {
path: string;
relative_path: string | null;
}
interface FilePreviewMetadata {
path: string;
display_path: string;
+103
View File
@@ -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") {
queueMicrotask(() => this.receive({
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?")) {
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")!));
}
if (withFiles && path.includes("/webui-thread")) {
@@ -161,7 +164,17 @@ describe("temporary chat navigation", () => {
} else {
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 selectTopic("Second pane");
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();