feat(webui): polish tabbed previews and image presentation

This commit is contained in:
Xubin Ren committed 2026-09-24 15:17:05 +08:00
1 parent fccf415283
commit b555164a17
41 files changed
+1459 -621

No files matched your search

+27 -17
View File
@@ -16,22 +16,28 @@ describe("File actions", () => {
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 }}>
render(<FileActionsProvider value={{ resolveMetadata }}>
<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" }));
expect(screen.queryByRole("button", { name: /File actions/ })).not.toBeInTheDocument();
fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md:12" }), { clientX: 100, clientY: 200 });
await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy absolute path" })).not.toHaveAttribute("data-disabled"));
expect(resolveMetadata).toHaveBeenCalledWith("notes.md:12");
expect(screen.queryByRole("menuitem", { name: "Preview" })).not.toBeInTheDocument();
expect(screen.queryByText("Paths refer to the gateway machine.")).not.toBeInTheDocument();
expect(screen.getAllByRole("menuitem")).toHaveLength(2);
await user.click(screen.getByRole("menuitem", { name: "Copy absolute path" }));
expect(copyTextToClipboard).toHaveBeenLastCalledWith(details.path);
expect(await screen.findByText("Copied")).toBeVisible();
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "notes.md:12" })).toHaveFocus();
fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md:12" }));
await waitFor(() => expect(screen.getByRole("menuitem", { name: "Copy relative path" })).not.toHaveAttribute("data-disabled"));
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();
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "notes.md:12" })).toHaveFocus();
});
it("keeps primary click working and supports context menu and Shift+F10", async () => {
@@ -43,17 +49,21 @@ describe("File actions", () => {
expect(onOpen).toHaveBeenCalledTimes(1);
expect(onOpen).toHaveBeenCalledWith("src/app.ts");
fireEvent.contextMenu(reference);
expect(await screen.findByRole("menuitem", { name: "Preview" })).toBeVisible();
expect(await screen.findByRole("menuitem", { name: "Copy reference" })).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);
await user.keyboard("{Escape}");
fireEvent.keyDown(reference, { key: "ContextMenu" });
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" }));
render(<FileActions path="/media/image.png" metadata={{ path: "/media/image.png", relative_path: null }}><button>image.png</button></FileActions>);
fireEvent.contextMenu(screen.getByRole("button", { name: "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" }));
@@ -63,10 +73,10 @@ describe("File actions", () => {
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() }}>
render(<FileActionsProvider value={{ resolveMetadata: vi.fn().mockRejectedValue(new Error("404")) }}>
<FileReferenceChip path="missing.txt" onOpen={vi.fn()} />
</FileActionsProvider>);
await user.click(screen.getByRole("button", { name: "File actions for missing.txt" }));
fireEvent.contextMenu(screen.getByRole("button", { name: "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" }));
@@ -77,11 +87,11 @@ describe("File actions", () => {
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 previous = { resolveMetadata: () => new Promise<FileReferenceMetadata>((resolve) => { resolveOld = resolve; }) };
const current = { resolveMetadata: vi.fn().mockResolvedValue({ path: "/new/notes.md", relative_path: "notes.md" }) };
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" }));
fireEvent.contextMenu(screen.getByRole("button", { name: "notes.md" }));
rerender(view(current));
await waitFor(() => expect(current.resolveMetadata).toHaveBeenCalled());
await act(async () => resolveOld(details));
@@ -91,10 +101,10 @@ describe("File actions", () => {
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() }}>
render(<FileActionsProvider value={{ resolveMetadata: vi.fn().mockResolvedValue({ path: "/workspace/notes.md", content: "old preview response" }) }}>
<FileReferenceChip path="notes.md" onOpen={vi.fn()} />
</FileActionsProvider>);
await user.click(screen.getByRole("button", { name: "File actions for notes.md" }));
fireEvent.contextMenu(screen.getByRole("button", { name: "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" }));
+49 -17
View File
@@ -1,5 +1,4 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
@@ -46,7 +45,7 @@ describe("FilePreviewPanel", () => {
kind: "image", path: "/workspace/chart.png", display_path: "chart.png",
project_path: "/workspace", size: 42, mime_type: "image/png", data_url: dataUrl,
});
render(<FilePreviewPanel sessionKey="websocket:a" path="chart.png" token="test" onClose={() => {}} />);
render(<FilePreviewPanel sessionKey="websocket:a" path="chart.png" token="test" />);
const img = await screen.findByRole("img", { name: "chart.png" });
expect(img).toHaveAttribute("src", dataUrl);
expect(screen.queryByTestId("mock-code-block")).not.toBeInTheDocument();
@@ -62,7 +61,7 @@ describe("FilePreviewPanel", () => {
language: "text", content: "session B", truncated: false, size: 9,
};
vi.mocked(fetchFilePreview).mockResolvedValueOnce(payload);
const view = (key: string) => <FilePreviewPanel key={key} sessionKey={key} path="notes.txt" token="test" onClose={() => {}} />;
const view = (key: string) => <FilePreviewPanel key={key} sessionKey={key} path="notes.txt" token="test" />;
const { rerender } = render(view("a"));
rerender(view("b"));
await screen.findByText("session B");
@@ -70,9 +69,27 @@ describe("FilePreviewPanel", () => {
expect(screen.queryByText("session A")).not.toBeInTheDocument();
});
it("shows a compact breadcrumb with one file name and a visible close action", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
it("opens the sidebar image in the shared zoomable viewer and returns to the preview", async () => {
vi.mocked(fetchFilePreview).mockResolvedValue({
kind: "image", path: "/workspace/chart.png", display_path: "chart.png",
size: 42, mime_type: "image/png", data_url: "data:image/png;base64,example",
});
render(<FilePreviewPanel sessionKey="websocket:a" path="chart.png" token="test" />);
const trigger = await screen.findByRole("button", { name: "View image: chart.png" });
trigger.focus();
fireEvent.click(trigger);
const dialog = screen.getByRole("dialog");
expect(within(dialog).getByRole("img", { name: "chart.png" })).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole("button", { name: "Zoom in" }));
expect(within(dialog).getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
fireEvent.keyDown(dialog, { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
await waitFor(() => expect(trigger).toHaveFocus());
expect(screen.getByTestId("file-preview-panel")).toBeInTheDocument();
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
});
it("renders file content without a second filename or breadcrumb below the tabs", async () => {
vi.mocked(fetchFilePreview).mockResolvedValue({
path: "/Users/hr/workspace/quicksort.py",
display_path: "quicksort.py",
@@ -86,7 +103,6 @@ describe("FilePreviewPanel", () => {
sessionKey="websocket:chat-1"
path="quicksort.py"
token="tok"
onClose={onClose}
/>,
);
@@ -94,16 +110,33 @@ describe("FilePreviewPanel", () => {
expect(codeBlock).toHaveTextContent("print('ok')");
expect(codeBlock).toHaveAttribute("data-language", "python");
expect(codeBlock).toHaveAttribute("data-highlight", "true");
expect(screen.getByTestId("file-preview-breadcrumb")).toHaveTextContent("...");
expect(screen.getByTestId("file-preview-breadcrumb")).toHaveTextContent("workspace");
expect(screen.getByTestId("file-preview-title")).toHaveTextContent("quicksort.py");
expect(screen.getAllByText("quicksort.py")).toHaveLength(1);
expect(screen.queryByTestId("file-preview-breadcrumb")).not.toBeInTheDocument();
expect(screen.queryByText("quicksort.py")).not.toBeInTheDocument();
const closeButton = screen.getByRole("button", { name: "Close file preview" });
expect(closeButton).toBeVisible();
});
await user.click(closeButton);
expect(onClose).toHaveBeenCalledTimes(1);
it("paints cached content immediately, revalidates it, and does not restart when the cache ages", async () => {
const cached = { path: "notes.txt", display_path: "notes.txt", language: "text", content: "Cached", truncated: false };
let resolve!: (payload: typeof cached) => void;
const loadPreview = vi.fn(() => new Promise<typeof cached>(r => { resolve = r; }));
const view = (initialPreview?: typeof cached) => <FilePreviewPanel sessionKey="a" path="notes.txt"
token="test" loadPreview={loadPreview} initialPreview={initialPreview} />;
const { rerender } = render(view(cached));
expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Cached");
expect(screen.queryByRole("status")).not.toBeInTheDocument();
await act(async () => resolve({ ...cached, content: "Updated" }));
expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Updated");
rerender(view());
expect(screen.getByTestId("mock-code-block")).toHaveTextContent("Updated");
expect(loadPreview).toHaveBeenCalledTimes(1);
});
it("reports a failed revalidation rather than leaving stale cached content looking current", async () => {
const cached = { path: "notes.txt", display_path: "notes.txt", language: "text", content: "Cached", truncated: false };
render(<FilePreviewPanel sessionKey="a" path="notes.txt" token="test" initialPreview={cached}
loadPreview={vi.fn().mockRejectedValue(new Error("Forbidden"))} />);
await screen.findByText("Could not preview this file.");
expect(screen.queryByText("Cached")).not.toBeInTheDocument();
});
it("updates translated chrome without refetching the open file", async () => {
@@ -120,7 +153,6 @@ describe("FilePreviewPanel", () => {
sessionKey="websocket:chat-1"
path="notes.md"
token="tok"
onClose={() => {}}
/>,
);
@@ -0,0 +1,71 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createFilePreviewResource } from "@/lib/file-preview-resource";
import type { FilePreviewPayload } from "@/lib/types";
const payload: FilePreviewPayload = { path: "notes.txt", display_path: "notes.txt", content: "One", language: "text", truncated: false };
afterEach(() => vi.useRealTimers());
describe("session-scoped file previews", () => {
it("shares hover and click requests, then immediately reuses a recently viewed file", async () => {
const fetchPreview = vi.fn().mockResolvedValue(payload);
const resource = createFilePreviewResource(fetchPreview);
const hover = resource.load("notes.txt");
expect(resource.load("notes.txt")).toBe(hover);
await hover;
expect(resource.peek("notes.txt")).toBe(payload);
expect(await resource.load("notes.txt")).toBe(payload);
expect(fetchPreview).toHaveBeenCalledTimes(1);
});
it("revalidates older content without losing the snapshot, but does not retain it forever", async () => {
vi.useFakeTimers();
const updated = { ...payload, content: "Two" };
const fetchPreview = vi.fn().mockResolvedValueOnce(payload).mockResolvedValueOnce(updated);
const resource = createFilePreviewResource(fetchPreview);
await resource.load("notes.txt");
vi.advanceTimersByTime(5_001);
expect(resource.peek("notes.txt")).toBe(payload);
expect(await resource.load("notes.txt")).toBe(updated);
expect(fetchPreview).toHaveBeenCalledTimes(2);
vi.advanceTimersByTime(60_001);
expect(resource.peek("notes.txt")).toBeUndefined();
});
it("does not hide authorization failures behind cached data and allows a retry", async () => {
vi.useFakeTimers();
const fetchPreview = vi.fn().mockResolvedValueOnce(payload).mockRejectedValueOnce(new Error("401")).mockResolvedValueOnce(payload);
const resource = createFilePreviewResource(fetchPreview);
await resource.load("notes.txt");
vi.advanceTimersByTime(5_001);
await expect(resource.load("notes.txt")).rejects.toThrow("401");
expect(resource.peek("notes.txt")).toBeUndefined();
expect(await resource.load("notes.txt")).toBe(payload);
});
it("bounds entries and payload bytes; late evicted requests cannot refill the cache", async () => {
let resolve!: (value: FilePreviewPayload) => void;
const fetchPreview = vi.fn().mockImplementationOnce(() => new Promise<FilePreviewPayload>(r => { resolve = r; })).mockResolvedValue(payload);
const resource = createFilePreviewResource(fetchPreview);
const late = resource.load("old.txt");
for (let index = 0; index < 4; index++) await resource.load(`${index}.txt`);
resolve(payload);
await late;
expect(resource.peek("old.txt")).toBeUndefined();
fetchPreview.mockResolvedValueOnce({ ...payload, content: "x".repeat(4 * 1024 * 1024 + 1) });
await resource.load("huge.txt");
expect(resource.peek("huge.txt")).toBeUndefined();
});
it("never shares data between session resources or writes browser storage", async () => {
const writes = vi.spyOn(Storage.prototype, "setItem");
const first = createFilePreviewResource(vi.fn().mockResolvedValue(payload));
const second = createFilePreviewResource(vi.fn().mockResolvedValue({ ...payload, content: "Second session" }));
await first.load("notes.txt");
expect(second.peek("notes.txt")).toBeUndefined();
expect((await second.load("notes.txt"))).toMatchObject({ content: "Second session" });
expect(first.peek("notes.txt")).toBe(payload);
expect(writes).not.toHaveBeenCalled();
writes.mockRestore();
});
});
+165
View File
@@ -0,0 +1,165 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { ImageGallery } from "@/components/ImageGallery";
import { MessageBubble } from "@/components/MessageBubble";
import { FileActionsProvider } from "@/components/FileActions";
import { FileReferenceChip } from "@/components/FileReferenceChip";
import type { FilePreviewPayload, UIMessage } from "@/lib/types";
const images = Array.from({ length: 8 }, (_, index) => ({ url: `/api/media/sign/image-${index}`, name: `${index}.png` }));
const message: UIMessage = { id: "images", role: "assistant", content: "", createdAt: 1,
media: [{ kind: "image", url: "/api/media/sign/chart", name: "chart.png" }] };
describe("image presentation", () => {
it("bounds a large collection to four thumbnails and keeps every image in the viewer", async () => {
const user = userEvent.setup();
const { container } = render(<ImageGallery images={images} />);
expect(container.querySelectorAll("img")).toHaveLength(4);
expect(screen.getByText("+4")).toBeVisible();
await user.click(screen.getByRole("button", { name: "View all 8 images" }));
expect(screen.getByText("4 / 8")).toBeVisible();
await user.keyboard("{End}");
expect(screen.getByText("8 / 8")).toBeVisible();
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "7.png" })).toBeVisible();
await user.keyboard("{Escape}");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "View all 8 images" })).toHaveFocus();
});
it("preserves an inline image's position, deduplicates its attachment, and opens the shared viewer", async () => {
const user = userEvent.setup();
const { container, rerender } = render(<MessageBubble message={{ ...message,
content: "Before\n\n![Trend](/api/media/sign/chart)\n\nAfter", media: [...message.media!, ...message.media!] }} />);
await screen.findByRole("img", { name: "Trend" });
await waitFor(() => expect(container.querySelectorAll("img")).toHaveLength(1));
expect(container.textContent).toMatch(/Before.*After/s);
await user.click(screen.getByRole("button", { name: "View image: Trend" }));
expect(await screen.findByRole("button", { name: "Zoom in" })).toBeVisible();
await user.keyboard("{Escape}");
// Removing inline content must restore the attachment; no global remembered suppression.
rerender(<MessageBubble message={{ ...message, content: "File ready" }} />);
expect(await screen.findByRole("button", { name: "View image: chart.png" })).toBeVisible();
});
it("does not suppress files referenced in code or links, or different images sharing a name", async () => {
const { container } = render(<MessageBubble message={{ ...message,
content: "```md\n![example](/api/media/sign/chart)\n```\n\n[chart.png](/api/media/sign/chart)",
media: [...message.media!, { kind: "image", url: "/api/media/other/chart", name: "chart.png" }] }} />);
await waitFor(() => expect(container.querySelector("pre")).toBeInTheDocument());
expect(container.querySelectorAll("img")).toHaveLength(2);
});
it("keeps the attachment if an image reference is not actually rendered by the streaming renderer", async () => {
const { container } = render(<MessageBubble message={{ ...message,
content: "![Trend][chart]\n\n[chart]: /api/media/sign/chart" }} />);
await screen.findByText("![Trend][chart]");
expect(screen.getByRole("button", { name: "View image: chart.png" })).toBeVisible();
await waitFor(() => expect(container.querySelectorAll("img")).toHaveLength(1));
});
it("keeps unavailable images readable, and never hides a valid image behind missing placeholders", async () => {
const user = userEvent.setup();
render(<ImageGallery images={[...Array.from({ length: 4 }, () => ({ name: "old.png" })), images[0]]} />);
await user.click(screen.getByRole("button", { name: "View all 5 images" }));
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "0.png" })).toBeVisible();
});
it("replaces a broken thumbnail with a quiet named placeholder", () => {
render(<ImageGallery images={[images[0]]} />);
fireEvent.error(screen.getByRole("img"));
expect(screen.queryByRole("img")).not.toBeInTheDocument();
expect(screen.getByText("0.png")).toBeVisible();
expect(screen.queryByRole("button")).not.toBeInTheDocument();
});
});
describe("file quick look", () => {
const preview: FilePreviewPayload = { kind: "image", path: "chart.png", display_path: "chart.png",
project_path: "/workspace", size: 100, mime_type: "image/png", data_url: "data:image/png;base64,dGVzdA==" };
it("loads only on deliberate hover/focus, keeps click as preview, and releases content on dismissal", async () => {
const user = userEvent.setup();
const loadPreview = vi.fn().mockResolvedValue(preview);
const onOpen = vi.fn();
const { container } = render(<FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
<FileReferenceChip path="chart.png" onOpen={onOpen} />
</FileActionsProvider>);
expect(loadPreview).not.toHaveBeenCalled();
await user.hover(screen.getByRole("button", { name: "chart.png" }));
expect(loadPreview).not.toHaveBeenCalled();
await screen.findByRole("tooltip");
await waitFor(() => expect(loadPreview).toHaveBeenCalledWith("chart.png"));
const quickLook = screen.getByTestId("file-image-quick-look");
expect(quickLook.textContent).toBe("");
expect(quickLook).toHaveClass("w-max");
expect(quickLook).not.toHaveClass("h-36", "w-full");
expect(quickLook.querySelector("img")).toHaveClass("rounded-mark", "object-contain");
expect(quickLook.querySelector("img")).toHaveClass("h-auto", "w-auto", "max-h-36");
expect(screen.getByRole("tooltip")).toHaveTextContent("File preview");
await user.click(screen.getByRole("button", { name: "chart.png" }));
expect(onOpen).toHaveBeenCalledWith("chart.png");
await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument());
expect(container.querySelector("img")).not.toBeInTheDocument();
});
it("does not show a late image from a previous session, and shows a quiet failure instead of an empty popup", async () => {
let resolveOld!: (payload: FilePreviewPayload) => void;
const oldLoader = vi.fn(() => new Promise<FilePreviewPayload>((resolve) => { resolveOld = resolve; }));
const newLoader = vi.fn().mockRejectedValue(new Error("404"));
const view = (loadPreview: typeof oldLoader) => <FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
<FileReferenceChip path="chart.png" onOpen={vi.fn()} />
</FileActionsProvider>;
const { rerender } = render(view(oldLoader));
fireEvent.focus(screen.getByRole("button", { name: "chart.png" }));
await waitFor(() => expect(oldLoader).toHaveBeenCalled());
rerender(view(newLoader));
await act(async () => resolveOld(preview));
expect(document.querySelector('img[src^="data:image"]')).not.toBeInTheDocument();
expect(screen.getByText("Could not preview this file.")).toBeVisible();
expect(screen.getByRole("button", { name: "chart.png" })).toBeVisible();
});
it("keeps long image paths out of the quick look while preserving the real preview target", async () => {
const user = userEvent.setup();
const filename = "a-long-descriptive-filename-for-a-generated-project-overview.png";
const path = `/workspace/projects/weekly-reports/exported-charts/${filename}`;
const loadPreview = vi.fn().mockResolvedValue(preview);
const onOpen = vi.fn();
render(<FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
<FileReferenceChip path="Project overview" tooltipPath={path} previewPath={path} onOpen={onOpen} />
</FileActionsProvider>);
fireEvent.focus(screen.getByRole("button", { name: path }));
const tooltip = await screen.findByRole("tooltip");
expect(tooltip).not.toHaveTextContent(filename);
expect(tooltip).not.toHaveTextContent("/workspace/");
await waitFor(() => expect(loadPreview).toHaveBeenCalledWith(path));
expect(screen.getByTestId("file-image-quick-look").textContent).toBe("");
await user.click(screen.getByRole("button", { name: path }));
expect(onOpen).toHaveBeenCalledWith(path);
});
it("replaces a broken preview image with a readable failure without repeating the filename", async () => {
const loadPreview = vi.fn().mockResolvedValue(preview);
render(<FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
<FileReferenceChip path="chart.png" onOpen={vi.fn()} />
</FileActionsProvider>);
fireEvent.focus(screen.getByRole("button", { name: "chart.png" }));
await waitFor(() => expect(document.querySelector('img[src^="data:image"]')).toBeInTheDocument());
fireEvent.error(screen.getByTestId("file-image-quick-look").querySelector("img")!);
expect(screen.queryByTestId("file-image-quick-look")).not.toBeInTheDocument();
expect(screen.getByText("Could not preview this file.")).toBeVisible();
expect(screen.getAllByText("chart.png")).toHaveLength(1);
});
it("retains the full path tooltip for non-image file references without fetching an image", async () => {
const path = "/workspace/projects/reports/data.json";
const loadPreview = vi.fn();
render(<FileActionsProvider value={{ resolveMetadata: vi.fn(), loadPreview }}>
<FileReferenceChip path="data.json" tooltipPath={path} onOpen={vi.fn()} />
</FileActionsProvider>);
fireEvent.focus(screen.getByRole("button", { name: path }));
expect(await screen.findByRole("tooltip")).toHaveTextContent(path);
expect(loadPreview).not.toHaveBeenCalled();
});
});
+88
View File
@@ -0,0 +1,88 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { ImageLightbox } from "@/components/ImageLightbox";
import { ZoomableImage } from "@/components/ZoomableImage";
function renderImage() {
const result = render(<ZoomableImage src="data:image/png;base64,test" alt="Test chart" />);
const viewport = screen.getByTestId("image-zoom-viewport");
const image = screen.getByRole("img", { name: "Test chart" });
Object.defineProperties(viewport, { clientWidth: { value: 800 }, clientHeight: { value: 600 } });
Object.defineProperties(image, { offsetWidth: { value: 800 }, offsetHeight: { value: 600 } });
viewport.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600);
return { ...result, viewport, image };
}
function wheel(target: Element, deltaY: number, ctrlKey = true) {
const event = new WheelEvent("wheel", { deltaY, bubbles: true, cancelable: true });
// happy-dom 16's WheelEvent extends UIEvent instead of MouseEvent and drops these fields.
Object.defineProperties(event, { ctrlKey: { value: ctrlKey }, clientX: { value: 400 }, clientY: { value: 300 } });
return fireEvent(target, event);
}
describe("image zoom", () => {
it("pinches around the two-finger midpoint, then drags with the remaining finger", () => {
const { viewport, image } = renderImage();
fireEvent.pointerDown(viewport, { pointerId: 1, pointerType: "touch", button: 0, clientX: 300, clientY: 300 });
fireEvent.pointerDown(viewport, { pointerId: 2, pointerType: "touch", button: 0, clientX: 500, clientY: 300 });
fireEvent.pointerMove(viewport, { pointerId: 2, pointerType: "touch", clientX: 700, clientY: 300 });
expect(image.style.transform).toBe("translate3d(100px, 0px, 0) scale(2)");
fireEvent.pointerUp(viewport, { pointerId: 2, pointerType: "touch" });
fireEvent.pointerMove(viewport, { pointerId: 1, pointerType: "touch", clientX: 400, clientY: 300 });
expect(image.style.transform).toBe("translate3d(200px, 0px, 0) scale(2)");
fireEvent.pointerMove(viewport, { pointerId: 1, pointerType: "touch", clientX: 9000, clientY: 9000 });
expect(image.style.transform).toBe("translate3d(400px, 300px, 0) scale(2)");
fireEvent.pointerCancel(viewport, { pointerId: 1 });
fireEvent.pointerMove(viewport, { pointerId: 1, clientX: 300, clientY: 300 });
expect(image.style.transform).toBe("translate3d(400px, 300px, 0) scale(2)");
expect(viewport.className).not.toContain("cursor-grabbing");
fireEvent.click(screen.getByRole("button", { name: "Fit image" }));
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1)");
});
it("supports trackpad pinch without hijacking browser zoom outside the image", () => {
const { viewport, image } = renderImage();
expect(wheel(viewport, 20, false)).toBe(true);
expect(wheel(viewport, -50)).toBe(false);
expect(image.style.transform).toContain(`scale(${Math.exp(0.5)})`);
expect(wheel(document.body, -50)).toBe(true);
expect(wheel(viewport, 20, false)).toBe(false);
expect(image.style.transform).toContain("-20px");
for (let i = 0; i < 10; i++) wheel(viewport, -50);
expect(image.style.transform).toContain("scale(8)");
expect(screen.getByRole("button", { name: "Zoom in" })).toBeDisabled();
for (let i = 0; i < 10; i++) wheel(viewport, 50);
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1)");
expect(screen.getByRole("button", { name: "Zoom out" })).toBeDisabled();
});
it("supports double-click, keyboard and visible controls", () => {
const { viewport, image } = renderImage();
fireEvent.doubleClick(viewport, { clientX: 400, clientY: 300 });
expect(image.style.transform).toContain("scale(2)");
fireEvent.doubleClick(viewport, { clientX: 400, clientY: 300 });
expect(image.style.transform).toContain("scale(1)");
fireEvent.keyDown(viewport, { key: "+" });
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
fireEvent.keyDown(viewport, { key: "0" });
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
fireEvent.click(screen.getByRole("button", { name: "Zoom out" }));
expect(image.style.transform).toContain("scale(1)");
});
it("resets zoom when switching images and reopening the lightbox", () => {
const images = [{ url: "data:image/png;base64,a", name: "A" }, { url: "data:image/png;base64,b", name: "B" }];
const view = (index: number | null) => <ImageLightbox images={images} index={index} onIndexChange={() => {}} onOpenChange={() => {}} />;
const { rerender } = render(view(0));
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
rerender(view(1));
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "B" }).style.transform).toContain("scale(1)");
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
rerender(view(null));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
rerender(view(1));
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("100%");
});
});
@@ -265,10 +265,7 @@ describe("MarkdownTextRenderer", () => {
const image = screen.getByRole("img", { name: "Diagram" });
expect(image).toHaveAttribute("src", "/api/media/sig/payload");
expect(screen.getByRole("link", { name: "Open Diagram" })).toHaveAttribute(
"href",
"/api/media/sig/payload",
);
expect(screen.getByRole("button", { name: "View image: Diagram" })).toBeInTheDocument();
});
it("renders markdown videos as inline players", () => {
@@ -378,10 +375,7 @@ describe("MarkdownTextRenderer", () => {
"src",
"/api/media/sig/payload",
);
expect(screen.getByRole("link", { name: "Open Diagram" })).toHaveAttribute(
"href",
"/api/media/sig/payload",
);
expect(screen.getByRole("button", { name: "View image: Diagram" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Code" })).not.toBeInTheDocument();
});
+1 -1
View File
@@ -1158,7 +1158,7 @@ describe("MessageBubble", () => {
const { container } = render(<MessageBubble message={message} />);
const imageButton = screen.getByRole("button", { name: /view image/i });
expect(imageButton).toHaveClass("w-[min(100%,34rem)]", "rounded-panel");
expect(imageButton).toHaveClass("w-[min(100%,28rem)]", "rounded-control");
expect(imageButton).toHaveClass(
"border",
"border-border/60",
+12
View File
@@ -108,6 +108,18 @@ function BspWorkbenchHarness() {
}
describe("PaneWorkbench", () => {
it("keeps a single conversation's header inside that pane instead of above its previews", () => {
render(<PaneWorkbench panes={[{ key: "alpha", title: "Alpha" }]} activePaneKey="alpha"
layout="columns" chrome showLayoutControl={false} onActivatePane={vi.fn()} onAddPane={vi.fn()}
onLayoutChange={vi.fn()} onPaneOrderChange={vi.fn()}
renderPane={(_pane, context) => {
expect(context.headerPortalTarget).toBeUndefined();
return <div data-testid="local-toolbar">{context.headerActions}</div>;
}} />);
expect(screen.getByTestId("workbench-header-host")).toBeEmptyDOMElement();
expect(within(screen.getByTestId("local-toolbar")).getByRole("button", { name: "Add pane" })).toBeVisible();
});
const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
const originalAnimate = HTMLElement.prototype.animate;
const animate = vi.fn(() => ({
+108
View File
@@ -0,0 +1,108 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { PreviewPane } from "@/components/PreviewPane";
import { FilePreviewStore, useFilePreviewState } from "@/hooks/useFilePreviewState";
describe("preview tabs", () => {
it("deduplicates targets, keeps selection and width per session, and closes neighboring tabs", () => {
const store = new FilePreviewStore();
const storage = vi.spyOn(Storage.prototype, "setItem");
store.open("a", "file", "chart.png");
store.open("a", "file", "index.html");
store.open("a", "file", "data.json");
store.update("a", { width: 620 });
store.open("a", "file", "index.html");
expect(store.get("a").tabs).toHaveLength(3);
expect(store.get("a").activeId).toBe("file:index.html");
store.closeTab("a", "file:chart.png");
expect(store.get("a").activeId).toBe("file:index.html");
store.closeTab("a", "file:index.html");
expect(store.get("a").activeId).toBe("file:data.json");
store.select("a", "missing");
store.closeTab("a", "missing");
expect(store.get("a").activeId).toBe("file:data.json");
store.open("b", "web", "https://example.com");
expect(store.get("a").width).toBe(620);
store.closeTab("a", "file:data.json");
expect(store.get("a")).toMatchObject({ tabs: [], activeId: null, width: 620 });
expect(store.get("b").tabs).toHaveLength(1);
store.open("a", "file", "chart.png");
store.close("a");
expect(store.get("a")).toMatchObject({ tabs: [], activeId: null, width: 620 });
store.delete("b");
store.clear();
expect(store.get("a").tabs).toEqual([]);
expect(store.get("b").tabs).toEqual([]);
expect(storage).not.toHaveBeenCalled();
storage.mockRestore();
});
it("keeps one shell, supports keyboard tabs and close buttons, and never reloads the same tab", async () => {
const store = new FilePreviewStore();
store.open("a", "file", "chart.png");
store.open("a", "file", "index.html");
store.open("a", "file", "data.json");
function View() {
const { state, selectTab, closeTab, close } = useFilePreviewState("a", store);
return state.activeId ? <PreviewPane tabs={state.tabs} activeId={state.activeId} width={544}
isClosing={false} onSelect={selectTab} onCloseTab={closeTab} onClose={close} onResizeStart={() => {}}>
<p>{state.activeId}</p>
</PreviewPane> : null;
}
render(<View />);
const shell = screen.getByTestId("preview-pane");
const highlight = screen.getByTestId("preview-tabs-selection-highlight");
expect(highlight).toHaveAttribute("data-active-id", "file:data.json");
expect(highlight.className).toContain("bg-sidebar-foreground/[0.055]");
expect(highlight.className).toContain("motion-reduce:transition-none");
await waitFor(() => expect(shell.style.getPropertyValue("--file-preview-slot-width")).toBe("544px"));
fireEvent.click(screen.getByRole("tab", { name: "chart.png" }));
expect(screen.getByTestId("preview-pane")).toBe(shell);
expect(screen.getByTestId("preview-tabs-selection-highlight")).toBe(highlight);
expect(highlight).toHaveAttribute("data-active-id", "file:chart.png");
expect(shell.style.getPropertyValue("--file-preview-slot-width")).toBe("544px");
expect(screen.getByRole("tabpanel")).toHaveTextContent("file:chart.png");
fireEvent.keyDown(screen.getByRole("tab", { name: "chart.png" }), { key: "ArrowRight" });
expect(screen.getByRole("tab", { name: "index.html" })).toHaveFocus();
expect(screen.getByRole("tab", { name: "index.html" })).toHaveAttribute("aria-selected", "true");
act(() => store.open("a", "file", "index.html"));
expect(screen.getAllByRole("tab")).toHaveLength(3);
fireEvent.keyDown(screen.getByRole("tab", { name: "index.html" }), { key: "Delete" });
expect(screen.queryByRole("tab", { name: "index.html" })).not.toBeInTheDocument();
expect(screen.getByRole("tab", { name: "data.json" })).toHaveFocus();
fireEvent.click(screen.getByRole("button", { name: "Close chart.png" }));
expect(screen.getByRole("tab", { name: "data.json" })).toHaveAttribute("aria-selected", "true");
expect(screen.queryByRole("button", { name: "Close preview pane" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close data.json" }));
expect(screen.queryByTestId("preview-pane")).not.toBeInTheDocument();
});
it("reveals the whole active tab including its close button after the tab strip resizes", () => {
let resize: (() => void) | undefined;
const observe = vi.fn();
const disconnect = vi.fn();
vi.stubGlobal("ResizeObserver", class {
constructor(callback: () => void) { resize = callback; }
observe = observe;
disconnect = disconnect;
});
try {
const tab = { id: "file:chart.png", kind: "file" as const, value: "chart.png" };
const view = render(<PreviewPane tabs={[tab]} activeId={tab.id} width={544} isClosing={false}
onSelect={() => {}} onCloseTab={() => {}} onClose={() => {}} onResizeStart={() => {}}>
<p>Preview</p>
</PreviewPane>);
const wholeTab = screen.getByRole("tab", { name: "chart.png" }).parentElement!;
const reveal = vi.fn();
wholeTab.scrollIntoView = reveal;
expect(wholeTab).toContainElement(screen.getByRole("button", { name: "Close chart.png" }));
expect(observe).toHaveBeenCalledWith(screen.getByRole("tablist"));
act(() => resize?.());
expect(reveal).toHaveBeenCalledWith({ block: "nearest", inline: "nearest" });
view.unmount();
expect(disconnect).toHaveBeenCalled();
} finally {
vi.unstubAllGlobals();
}
});
});
@@ -174,18 +174,50 @@ describe("temporary chat navigation", () => {
} 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" }));
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
await screen.findByText("Preview of notes.txt");
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
await screen.findByText("Preview of second.txt");
const pane = screen.getByTestId("preview-pane");
expect(within(pane).getAllByText("second.txt")).toHaveLength(1);
expect(within(pane).queryByRole("navigation", { name: "File path" })).not.toBeInTheDocument();
expect(within(pane).queryByRole("button", { name: /File actions/ })).not.toBeInTheDocument();
fireEvent.contextMenu(within(pane).getByRole("tab", { name: "second.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: "second.txt", metadata: true }),
}));
} else {
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("path=second.txt&metadata=1"))).toBe(true);
}
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
expect(screen.getByTestId("preview-pane")).toBe(pane);
const previewRequestCount = () => temporary
? TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action === "temporary_chat.file_preview"
&& frame.payload?.path === "notes.txt" && !frame.payload?.metadata && !frame.payload?.probe).length
: vi.mocked(fetch).mock.calls.filter(([url]) => String(url).includes("/file-preview?path=notes.txt")
&& !String(url).includes("metadata=") && !String(url).includes("probe=")).length;
const beforeReturn = previewRequestCount();
fireEvent.click(screen.getByRole("tab", { name: "notes.txt" }));
expect(screen.getByText("Preview of notes.txt")).toBeInTheDocument();
expect(previewRequestCount()).toBe(beforeReturn);
await selectTopic("Second pane");
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: "second.txt" }));
await screen.findByText("Preview of second.txt");
await selectTopic(temporary ? "Show example files" : "Regular topic");
await screen.findByText("Preview of notes.txt");
expect(screen.getAllByRole("tab")).toHaveLength(2);
expect(screen.getByRole("tab", { name: "notes.txt" })).toHaveAttribute("aria-selected", "true");
expect(screen.queryByText("Preview of second.txt")).not.toBeInTheDocument();
// Explicit close must stick even if switching interrupts the close animation.
fireEvent.click(screen.getByRole("button", { name: "Close file preview" }));
fireEvent.click(screen.getByRole("button", { name: "Close preview pane" }));
await selectTopic("Second pane");
await selectTopic(temporary ? "Show example files" : "Regular topic");
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
@@ -212,7 +244,7 @@ describe("temporary chat navigation", () => {
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
await screen.findByTestId("web-preview-panel");
await selectTopic("Synthetic separate session");
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
await selectTopic("Regular topic");
await screen.findByTestId("web-preview-panel");
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
@@ -221,24 +253,24 @@ describe("temporary chat navigation", () => {
expect(screen.getByTestId("web-preview-panel")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
fireEvent.keyDown(window, { key: "Escape" });
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
await screen.findByText("Preview of notes.txt");
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close website preview" }));
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close preview pane" }));
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
for (const storage of [localStorage, sessionStorage]) {
const values = Array.from({ length: storage.length }, (_, i) => storage.getItem(storage.key(i)!));
expect(JSON.stringify(values)).not.toContain("https://example.com/demo");
}
});
it("toggles the current file, switches files, and only handles Escape below dialogs", async () => {
it("keeps the sidebar mounted across tabs, deduplicates repeated opens, and handles Escape below dialogs", async () => {
withFiles = true;
render(<App />);
await screen.findByRole("button", { name: "Temporary chat" });
@@ -248,8 +280,15 @@ describe("temporary chat navigation", () => {
await screen.findByText("Preview of notes.txt");
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
await screen.findByText("Preview of second.txt");
const pane = screen.getByTestId("preview-pane");
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
await waitFor(() => expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument());
expect(screen.getByTestId("preview-pane")).toBe(pane);
expect(screen.getAllByRole("tab")).toHaveLength(2);
expect(screen.getByRole("tab", { name: "second.txt" })).toHaveAttribute("aria-selected", "true");
fireEvent.click(screen.getByRole("button", { name: "Close second.txt" }));
await screen.findByText("Preview of notes.txt");
expect(screen.getByTestId("preview-pane")).toBe(pane);
expect(screen.getAllByRole("tab")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
await screen.findByText("Preview of notes.txt");
const dialog = document.createElement("div");
@@ -263,7 +302,7 @@ describe("temporary chat navigation", () => {
});
it("forgets preview paths on temporary close and disconnect", async () => {
const update = vi.spyOn(FilePreviewStore.prototype, "update");
const update = vi.spyOn(FilePreviewStore.prototype, "open");
render(<App />);
await screen.findByRole("button", { name: "Temporary chat" });
act(() => TestSocket.current.open());
@@ -273,14 +312,14 @@ describe("temporary chat navigation", () => {
}));
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
await screen.findByText("Preview of notes.txt");
const store = update.mock.contexts.find((value) => value.get(`websocket:${chatId}`).path)!;
expect(store.get(`websocket:${chatId}`).path).toBe("notes.txt");
const store = update.mock.contexts.find((value) => value.get(`websocket:${chatId}`).tabs.length)!;
expect(store.get(`websocket:${chatId}`).activeId).toBe("file:notes.txt");
await selectTopic("Close temporary chat: Show example files");
expect(store.get(`websocket:${chatId}`).path).toBeNull();
act(() => store.update("websocket:regular", { path: "notes.txt" }));
expect(store.get(`websocket:${chatId}`).tabs).toEqual([]);
act(() => store.open("websocket:regular", "file", "notes.txt"));
vi.useFakeTimers();
act(() => TestSocket.current.close());
expect(store.get("websocket:regular").path).toBeNull();
expect(store.get("websocket:regular").tabs).toEqual([]);
});
it("keeps messages when navigating to a regular workbench and back", async () => {
+19 -16
View File
@@ -40,8 +40,7 @@ describe("web preview boundaries", () => {
expect(webPreviewRestriction(external, page, false, true)).toBeNull();
});
it("embeds only on mount, without credentials/referrer/host permissions, and refreshes with a new frame", async () => {
const close = vi.fn();
const { container } = render(<WebPreviewPanel url="https://example.com/demo" onClose={close} />);
const { container } = render(<WebPreviewPanel url="https://example.com/demo" />);
const frame = container.querySelector("iframe")!;
expect(frame).toHaveAttribute("src", "https://example.com/demo");
expect(frame).toHaveAttribute("sandbox", "allow-scripts");
@@ -50,27 +49,29 @@ describe("web preview boundaries", () => {
expect(frame.getAttribute("allow")).toContain("clipboard-read 'none'");
// A frame load event is not evidence that CSP/X-Frame-Options allowed embedding.
fireEvent.load(frame);
expect(screen.getByText(/Some sites block embedding/)).toBeInTheDocument();
expect(screen.queryByText(/Some sites block embedding/)).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "About website previews" }));
expect(await screen.findByText(/Some sites block embedding/)).toBeInTheDocument();
await userEvent.setup().keyboard("{Escape}");
fireEvent.click(screen.getByRole("button", { name: "Refresh website" }));
expect(container.querySelector("iframe")).not.toBe(frame);
expect(screen.getByRole("link", { name: "Open in browser" })).toHaveAttribute("rel", "noreferrer noopener");
fireEvent.click(screen.getByRole("button", { name: "Close website preview" }));
expect(close).toHaveBeenCalledOnce();
});
it("does not load an iframe in native or unsupported browsers", () => {
vi.mocked(isNativeRuntime).mockReturnValue(true);
const { container, rerender } = render(<WebPreviewPanel url="https://example.com" onClose={() => {}} />);
const { container, rerender } = render(<WebPreviewPanel url="https://example.com" />);
expect(container.querySelector("iframe")).toBeNull();
expect(screen.getByRole("status")).toHaveTextContent(/native host/);
vi.mocked(isNativeRuntime).mockReturnValue(false);
Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
rerender(<WebPreviewPanel url="https://example.com" onClose={() => {}} />);
rerender(<WebPreviewPanel url="https://example.com" />);
expect(container.querySelector("iframe")).toBeNull();
expect(screen.getByRole("status")).toHaveTextContent(/does not support/);
});
it("explains that loopback belongs to the browsing device", () => {
render(<WebPreviewPanel url="http://127.0.0.1:4173" onClose={() => {}} />);
expect(screen.getByText(/not a remote gateway/)).toBeInTheDocument();
it("explains that loopback belongs to the browsing device on request", async () => {
render(<WebPreviewPanel url="http://127.0.0.1:4173" />);
fireEvent.click(screen.getByRole("button", { name: "About website previews" }));
expect(await screen.findByText(/not a remote gateway/)).toBeInTheDocument();
});
});
@@ -105,12 +106,12 @@ describe("web link actions", () => {
});
});
it("keeps mutually exclusive preview targets per session, clears them on deletion, and never persists URLs", () => {
it("keeps file and website tabs per session, clears them on deletion, and never persists URLs", () => {
const store = new FilePreviewStore();
const local = vi.spyOn(Storage.prototype, "setItem");
function View({ session }: { session: string }) {
const { state, setWebUrl, setPath } = useFilePreviewState(session, store);
return <><output>{state.webUrl ?? state.path ?? "closed"}</output><button onClick={() => setWebUrl("https://example.com/preview")}>Web</button><button onClick={() => setPath("notes.txt")}>File</button></>;
const { state, openWeb, openFile } = useFilePreviewState(session, store);
return <><output>{state.tabs.find((tab) => tab.id === state.activeId)?.value ?? "closed"}</output><button onClick={() => openWeb("https://example.com/preview")}>Web</button><button onClick={() => openFile("notes.txt")}>File</button></>;
}
const { rerender } = render(<View session="a" />);
fireEvent.click(screen.getByText("Web"));
@@ -120,12 +121,14 @@ it("keeps mutually exclusive preview targets per session, clears them on deletio
rerender(<View session="a" />);
expect(screen.getByRole("status")).toHaveTextContent("https://example.com/preview");
fireEvent.click(screen.getByText("File"));
expect(store.get("a")).toMatchObject({ path: "notes.txt", webUrl: null });
expect(store.get("a").activeId).toBe("file:notes.txt");
expect(store.get("a").tabs).toHaveLength(2);
fireEvent.click(screen.getByText("Web"));
expect(store.get("a").path).toBeNull();
expect(store.get("a").activeId).toBe("web:https://example.com/preview");
expect(store.get("a").tabs).toHaveLength(2);
act(() => store.delete("a"));
expect(screen.getByRole("status")).toHaveTextContent("closed");
act(() => store.clear());
expect(store.get("b").path).toBeNull();
expect(store.get("b").tabs).toEqual([]);
expect(local).not.toHaveBeenCalled();
});