Files
PaperClipAI/ui/src/components/FileViewerSheet.copy.test.tsx
T
DottaandPaperclip 0830737030 feat(ui): add CSV table previews to task file tabs (#15445)
## Thinking Path

> - Paperclip helps people manage AI agents and inspect their work.
> - Task file tabs show the files that agents produce.
> - Markdown has a readable view, but CSV files show only source text.
> - People need to scan CSV reports without a separate app.
> - This pull request adds a table view to attachment and workspace file
tabs.
> - View buttons let people inspect the original source beside download.

## Linked Issues or Issue Description

**Subsystem affected**

ui/ — task file tabs.

**Problem or motivation**

CSV exports are difficult to scan as source text. Related work:
https://github.com/paperclipai/paperclip/pull/14297 added text
attachment tabs.

**Proposed solution**

Render CSV as a table by default. Add row numbers, sticky headers, and
record counts. Keep rendered and raw icons beside download in task tabs.

**Roadmap alignment**

This is a small improvement to existing task file previews. It does not
add a new core subsystem.

## What Changed

- Add a shared CSV parser and table preview.
- Handle quoted commas, escaped quotes, UTF-8 BOM, CRLF, and multiline
cells.
- Show at most 500 data rows and 100 columns. Show a notice for larger
files. Keep the complete download.
- Add CSV attachment and workspace previews. Put workspace tab view
controls in the header.
- Add parser and interaction tests, Storybook examples, and product
documentation.

## Verification

- 28 focused tests pass across the parser, attachment tabs, and file
viewer.
- UI typecheck, UI build, and token gates pass.
- Playwright checked desktop and mobile rendered → raw → rendered flows
using the real attachment preview component in Storybook. Screenshots
are recorded on the driving task.
- Repository-wide typecheck and build were attempted. Both require
cargo, which is absent in this environment.
- The earlier repository-wide local test run stopped after a server test
race failure. The prior commit passed all GitHub CI jobs.
- Review fixes add source-line navigation coverage and CSV boundary
tests. All 22 file-viewer tests pass. UI typecheck and token gates pass.
- All 54 active GitHub checks pass on the final commit. Two Storybook
checks are skipped. Greptile gives 5/5 with no actionable findings.
- The final version preserves HTML previews from master and uses the
shared toolbar control. All 35 focused tests, UI typecheck, UI build,
and token gates pass.

## Risks

- The first CSV record supplies column headers. Files without headers
use that same rule.
- The table preview is bounded. Download and raw view retain the
complete file.
- No API, database, or dependency changes.

## Model Used

- OpenAI Codex, GPT-6. The runtime does not expose a more precise model
ID or context window. Used code editing, shell tools, and browser
checks.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-07 09:17:18 -05:00

233 lines
7.8 KiB
TypeScript

// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ResolvedWorkspaceResource, WorkspaceFileContent } from "@paperclipai/shared";
import { FileContentViewer, FileViewerSheet } from "./FileViewerSheet";
const useQueryMock = vi.fn();
const viewerMock = {
state: null,
browse: false,
query: null,
folderPath: null,
browseProjectId: null,
browseWorkspaceId: null,
open: vi.fn(),
updateBrowseState: vi.fn(),
close: vi.fn(),
backToFiles: vi.fn(),
};
vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
return {
...actual,
useQuery: (options: unknown) => useQueryMock(options),
};
});
vi.mock("@/context/FileViewerContext", () => ({
useRequiredFileViewer: () => viewerMock,
}));
vi.mock("@/components/WorkspaceFileBrowser", () => ({
WorkspaceFileBrowser: () => null,
}));
vi.mock("@/components/WorkspaceFileMarkdownBody", () => ({
WorkspaceFileMarkdownBody: ({ children }: { children: string }) => (
<div data-testid="mock-rendered-markdown">Rendered Markdown: {children}</div>
),
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
function ok<T>(data: T) {
return { data, isFetching: false, isError: false, error: null, refetch: vi.fn(async () => ({ data })) };
}
const resolvedResource: ResolvedWorkspaceResource = {
kind: "file",
provider: "git_worktree",
title: "tweet.md",
displayPath: "videos/90-days-paperclip/tweet.md",
workspaceLabel: "Isolated workspace",
workspaceKind: "execution_workspace",
workspaceId: "ws-1",
contentType: "text/markdown; charset=utf-8",
byteSize: 42,
previewKind: "text",
capabilities: { preview: true, download: true, listChildren: false },
};
const content: WorkspaceFileContent = {
resource: resolvedResource,
content: {
encoding: "utf8",
data: "hello from the file",
},
};
describe("FileViewerSheet copy actions", () => {
let container: HTMLDivElement;
let root: Root;
let writeText: ReturnType<typeof vi.fn>;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
useQueryMock.mockImplementation((options: { queryKey?: readonly unknown[] }) => {
const key = JSON.stringify(options.queryKey ?? []);
if (key.includes('"content"')) return ok(content);
return ok(resolvedResource);
});
writeText = vi.fn(async () => undefined);
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText },
});
Object.defineProperty(window, "isSecureContext", {
configurable: true,
value: true,
});
window.history.pushState({}, "", "/PAP/issues/PAP-10629?file=videos%2F90-days-paperclip%2Ftweet.md");
});
afterEach(() => {
flushSync(() => root.unmount());
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
});
function renderSheet() {
flushSync(() => {
root.render(
<FileViewerSheet
issueId="issue-1"
state={{
path: "videos/90-days-paperclip/tweet.md",
workspace: "auto",
line: null,
column: null,
projectId: null,
workspaceId: null,
}}
open
/>,
);
});
}
async function click(label: string) {
const button = document.body.querySelector(`button[aria-label="${label}"]`) as HTMLButtonElement | null;
expect(button).not.toBeNull();
flushSync(() => {
button!.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
});
await Promise.resolve();
await new Promise((resolve) => setTimeout(resolve, 0));
}
it("copies file contents and shows confirmation", async () => {
renderSheet();
await click("Copy file contents");
expect(writeText).toHaveBeenCalledWith("hello from the file");
expect(document.body.textContent).toContain("Copied contents");
});
it("copies the current file view link and shows confirmation", async () => {
renderSheet();
await click("Copy link to this file view");
expect(writeText).toHaveBeenCalledWith(window.location.href);
expect(document.body.textContent).toContain("Copied link");
});
it("renders a keyboard-addressable file tree resize separator", () => {
renderSheet();
const separator = document.body.querySelector('[role="separator"][aria-label="Resize file tree"]');
expect(separator).not.toBeNull();
expect(separator?.getAttribute("aria-valuenow")).toBe("288");
});
it("keeps split panes unframed so file selection does not shift the browser", () => {
renderSheet();
const separator = document.body.querySelector('[role="separator"][aria-label="Resize file tree"]');
const browserPane = separator?.previousElementSibling;
const previewPane = separator?.nextElementSibling;
expect(browserPane?.className).not.toContain("border");
expect(browserPane?.className).not.toContain("rounded");
expect(previewPane?.className).not.toContain("border");
expect(previewPane?.className).not.toContain("rounded");
});
it("defaults Markdown files to rendered mode and switches back to raw source", async () => {
useQueryMock.mockImplementation((options: { queryKey?: readonly unknown[] }) => {
const key = JSON.stringify(options.queryKey ?? []);
if (key.includes('"content"')) {
return ok({
...content,
resource: {
...resolvedResource,
title: "launch.md",
displayPath: "docs/launch.md",
contentType: "text/markdown; charset=utf-8",
},
content: { encoding: "utf8", data: "# Launch note\n\nRendered body" },
});
}
return ok({
...resolvedResource,
title: "launch.md",
displayPath: "docs/launch.md",
contentType: "text/markdown; charset=utf-8",
});
});
renderSheet();
expect(document.body.querySelector('[aria-label="launch.md rendered Markdown"]')).not.toBeNull();
expect(document.body.querySelector('[aria-label="launch.md source"]')).toBeNull();
expect(document.body.querySelector('button[aria-label="Show rendered Markdown"]')).not.toBeNull();
expect(document.body.querySelector('button[aria-label="Show raw Markdown"]')).not.toBeNull();
expect(document.body.textContent).toContain("Rendered Markdown: # Launch note");
await click("Show raw Markdown");
expect(document.body.querySelector('[aria-label="launch.md source"]')).not.toBeNull();
expect(document.body.querySelector('[aria-label="launch.md rendered Markdown"]')).toBeNull();
});
});
describe("source line navigation", () => {
it("scrolls plain source to its selected line when the toolbar requests rendered mode", () => {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
const scrollIntoView = vi.fn();
const original = HTMLElement.prototype.scrollIntoView;
HTMLElement.prototype.scrollIntoView = scrollIntoView;
try {
flushSync(() => root.render(<FileContentViewer content={{
resource: { ...resolvedResource, title: "util.ts", displayPath: "src/util.ts", contentType: "text/plain" },
content: { encoding: "utf8", data: "first\nsecond\nthird" },
}} highlightedLine={2} previewMode="rendered" />));
expect(scrollIntoView).toHaveBeenCalledWith({ block: "center", behavior: "auto" });
expect(container.textContent).toContain("second");
} finally {
flushSync(() => root.unmount());
container.remove();
HTMLElement.prototype.scrollIntoView = original;
}
});
});