Files
PaperClipAI/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsx
T
DottaandPaperclip 752cb8d3da fix(ui): contain patch previews and highlight diff source (#19478)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Tasks show documents and file attachments in cards and file views.
> - Patch source needs clear added and removed lines in each view.
> - Long patch lines can exceed the width of an inline preview.
> - This pull request keeps the preview inside the card and adds patch
colors.
> - Users can read a compact patch preview and open the full source.

## Linked Issues or Issue Description

**What happened?**
Patch text can exceed the inline document box. Patch files and patch
code blocks show plain text in the document view.

**Expected behavior**
Keep source inside its preview. Show added lines in green and removed
lines in red. Keep headers, source markers, copy controls, line numbers,
and downloads.

**Steps to reproduce**
1. Open a document card with a diff code block that has long unbroken
lines.
2. Open a `.patch` or `.diff` attachment in a task tab.
3. Open the same patch in the workspace file view.

**Paperclip version or commit**
Source checkout based on `e82210386f1e`.

**Deployment mode**
Built from source. The browser checks use Storybook fixtures.

Related work: #19269 adds inline diffs for file edits. This change uses
its line classifier for document and file source views.

## What Changed

- Share the unified diff line classifier with file and document views.
Track hunk lengths so later file headers keep their metadata style.
- Add safe patch source rendering for patch files and `diff` or `patch`
code blocks.
- Clip long lines with an ellipsis in compact cards. Wrap the full
source in file views.
- Add a Preview patch action for small `.patch` and `.diff` attachments,
including generic binary MIME types. Opening a large artifact list does
not fetch patch source. Bound the actual response bytes. Reject remote
preview URLs and redirects. Keep download and retry fallbacks.
- Add patch text colors with sufficient contrast in both themes. Keep
source-line selection visible over patch row colors. Copy the original
patch text without layout line breaks.
- Add five production component stories and browser checks at two widths
in both themes.
- Document the focused Storybook browser command.

## Verification

- Final base qualification at
`a120e0ada3f1eee9746f47a10384b5aa95f79824`: normally integrated the
already-merged #19610 model-fixture repair
(`8621bcf53ee2e4bbefb7d193add42dd544ca06e8`), preserving the reviewed
patch preview changes. Official preflight passes (1.8s); all 129 focused
tests pass again (23.67s), with UI typecheck and token gates passing.
Current revision CI and reviews are pending; prior-head review receipts
below are not current-head approval.

- Conflict qualification at `befc954a6116f7292506200b96623b673f9385b5`:
normally merged current master
`c66b4a55efdc5675b5a5146197078b94de6407da`, resolving the append-only
`ui/src/index.css` conflict by retaining both the patch rules and all
current agent identity rules. No feature behavior was changed during
resolution. Official isolated preflight passes. The seven focused
component/parser suites pass 129 tests; UI typecheck and token gates
pass. Fresh head CI and reviews are pending.
- Qualification setup limits: the first focused command used the
repository root instead of the UI working directory, so setup failed
before any test ran. It was corrected to the UI directory and actual
attachment-test path. The first UI typecheck found the unbuilt local
plugin SDK; building that checkout’s SDK and repeating typecheck passes.
These setup attempts are not test/typecheck passes.

- Focused Vitest run: 139 tests passed in eight files. This includes
source preservation, HTML escaping, large patches, tabs, Markdown
wrapping, line numbers, and transcript diff parsing. A 200-card check
confirms no patch fetch occurs before a preview request. CRLF
regressions cover no-newline markers and added lines that start with
`+++`.
- `pnpm --filter @paperclipai/ui typecheck`: passed after the plugin SDK
build prerequisite.
- `pnpm check:token-gates`: passed.
- Storybook catalog check and 30 map/catalog tests: passed.
- `STORYBOOK_TEST_BASE_URL=http://localhost:6006 pnpm exec playwright
test patch-preview.spec.ts
--config=tests/storybook-visual/playwright.config.ts --project=stories
--workers=2 --retries=0`: 20 passed on Linux Chromium. The checks
include accessibility, theme colors, overflow, opening a document,
wrapping source, exact clipboard contents, and the selected source line.
Screenshots were inspected and saved to the task.
- The first browser runs found contrast failures in diff text and source
gutters. Patch text tokens and patch gutter opacity now fix those
failures. The final run passes without retries.
- `pnpm verify`: exit 2. The new browser spec is a global CI input.
Required CI must supply broad coverage.
- The local full Storybook build was killed with exit 137. This is not a
build pass. External screenshot baselines are not published, so no
baseline comparison was run.
- Reviews found selected-row background precedence, file headers in
unified patches without git separators, eager patch loading across a
collection, and CRLF no-newline markers. Each finding has a focused fix
and regression checks. The Storybook hunk count now matches its source
lines.
- Prior feature commit `b3cb9d6d3c0423315540514b1ad68325a64c1cc2`: [CI
typecheck, build, tests, runner checks, and E2E
passed](https://github.com/paperclipai/paperclip/actions/runs/42247974154).
[Security scan
passed](https://github.com/paperclipai/paperclip/runs/127995160859).
[Greptile is
5/5](https://github.com/paperclipai/paperclip/pull/19478#issuecomment-6688482753),
and [Paperclip Review is
5/5](https://github.com/paperclipai/paperclip/runs/127998788846). All
six inline review threads are resolved.

## Risks

- Compact previews omit the end of long lines. The full document and
downloads keep the source.
- Patch colors apply to unified diff syntax. Other patch formats keep
literal text and do not have full format parsing.
- The shared classifier keeps the existing task chat behavior.
Regression tests cover that consumer.
- No database, API, or access rules change.

## Model Used

- OpenAI Codex, GPT-6, with reasoning, tool use, and code execution. The
runtime did not expose a more specific model ID or context window size.

## 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
- [ ] All Paperclip CI gates are green
- [ ] 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-11-07 00:06:50 +00:00

135 lines
10 KiB
TypeScript

// @vitest-environment jsdom
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { queryKeys } from "@/lib/queryKeys";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import { TaskAttachmentPanel, TextAttachmentPreview, readTextPreview, TEXT_PREVIEW_MAX_BYTES } from "./TaskAttachmentPanel";
import { isTextAttachment } from "@/lib/issue-attachments";
import { readTaskSidePanelState, taskPanelAttachmentTab, writeTaskSidePanelState } from "@/lib/task-side-panel-state";
vi.mock("@/components/MarkdownBody", () => ({ MarkdownBody: ({ children }: { children: string }) => <article data-rendered>{children}</article> }));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
afterEach(() => { window.localStorage.clear(); vi.unstubAllGlobals(); });
describe("text attachment tabs", () => {
it("does not fetch missing or oversized attachments and offers download for oversized files", async () => {
const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
client.setQueryData(queryKeys.issues.attachments("task"), [{ id: "large", originalFilename: "large.txt", contentType: "text/plain", byteSize: TEXT_PREVIEW_MAX_BYTES + 1, contentPath: "/api/attachments/large/content" }]);
const host = document.createElement("div"); const root = createRoot(host);
await act(async () => root.render(<QueryClientProvider client={client}><TaskAttachmentPanel issueId="task" attachmentId="missing" /></QueryClientProvider>));
expect(host.textContent).toContain("File no longer available");
await act(async () => root.render(<QueryClientProvider client={client}><TaskAttachmentPanel issueId="task" attachmentId="large" /></QueryClientProvider>));
expect(host.textContent).toContain("too large");
expect(host.querySelector("a")?.textContent).toBe("Download file");
expect(fetch).not.toHaveBeenCalled();
await act(async () => root.unmount()); client.clear();
});
it("classifies text without treating PDF or images as text", () => {
for (const [contentType, originalFilename] of [["application/octet-stream", "fix.patch"], ["application/octet-stream", "fix.diff"], ["text/x-patch", "download"], ["text/plain", "notes.txt"], ["application/octet-stream", "AGENTS.md"], ["application/json", "report.json"]]) expect(isTextAttachment({ contentType, originalFilename })).toBe(true);
expect(isTextAttachment({ contentType: "application/pdf", originalFilename: "report.pdf" })).toBe(false);
expect(isTextAttachment({ contentType: "image/png", originalFilename: "fake.txt" })).toBe(false);
});
it("retains attachment tabs when workspace browsing is disabled", () => {
const tab = taskPanelAttachmentTab("file-1", "AGENTS.md");
writeTaskSidePanelState("user", "company", "task", { state: { tabs: [tab], activeTabId: tab.id }, launcherOpen: false, userInteracted: true, autoPlanHandled: false, updatedAt: 1 });
expect(readTaskSidePanelState("user", "company", "task", false)?.state.tabs).toEqual([tab]);
expect(taskPanelAttachmentTab("file-1", "Renamed.md").id).toBe(tab.id);
});
it("switches rendered/raw Markdown and keeps a download action", async () => {
const host = document.createElement("div"); document.body.append(host);
const root = createRoot(host);
await act(async () => root.render(<TextAttachmentPreview title="AGENTS.md" markdown text="# Charter" downloadUrl="/api/attachments/file-1/content?download=1" />));
expect(host.querySelector("[data-rendered]")).not.toBeNull();
const raw = host.querySelector<HTMLButtonElement>('button[aria-label="Raw"]');
const rendered = host.querySelector<HTMLButtonElement>('button[aria-label="Rendered"]');
expect(raw?.querySelector("svg")).not.toBeNull();
expect(rendered?.querySelector("svg")).not.toBeNull();
expect(raw?.textContent).toBe("");
await act(async () => raw!.click());
expect(host.querySelector("pre")?.textContent).toBe("# Charter");
expect(host.querySelector("a")?.getAttribute("href")).toContain("download=1");
await act(async () => rendered!.click());
expect(host.querySelector("[data-rendered]")).not.toBeNull();
await act(async () => root.unmount()); host.remove();
});
it("renders CSV cells safely and switches to the exact raw source beside download", async () => {
const host = document.createElement("div"); const root = createRoot(host);
const text = 'Name,Notes,Amount\n"Lee, Sam","<script>hello</script>",12\nJo,"line 1\nline 2",';
await act(async () => root.render(<TextAttachmentPreview title="export.csv" markdown={false} csv text={text} downloadUrl="/download" />));
expect(host.querySelector("table")).not.toBeNull();
expect(host.textContent).toContain("2 rows");
expect(host.querySelector("td")?.textContent).toBe("Lee, Sam");
expect(host.querySelector("script")).toBeNull();
expect(host.querySelector("header")?.lastElementChild?.getAttribute("href")).toBe("/download");
await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Raw"]')!.click());
expect(host.querySelector("pre")?.textContent).toBe(text);
expect(host.querySelector("table")).toBeNull();
await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Rendered"]')!.click());
expect(host.querySelector("table")).not.toBeNull();
await act(async () => root.unmount());
});
it.each(["fix.patch", "fix.diff"])("highlights %s while preserving literal source and download", async (title) => {
const host = document.createElement("div"); const root = createRoot(host);
const text = "--- a/file\n+++ b/file\n@@ -1 +1 @@\n-old\n+<script>new</script>\n";
await act(async () => root.render(<TextAttachmentPreview title={title} markdown={false} text={text} downloadUrl="/download" />));
expect(host.querySelector("pre")?.textContent).toBe(text);
expect(host.querySelector('[data-patch-line="add"]')?.textContent).toBe("+<script>new</script>\n");
expect(host.querySelector('[data-patch-line="remove"]')?.textContent).toBe("-old\n");
expect(host.querySelector("script")).toBeNull();
expect(host.querySelector("a")?.getAttribute("href")).toBe("/download");
await act(async () => root.unmount());
});
it("shows plain text literally without Markdown controls", async () => {
const host = document.createElement("div"); const root = createRoot(host);
await act(async () => root.render(<TextAttachmentPreview title="notes.txt" markdown={false} text="<script>alert(1)</script>" downloadUrl="/download" />));
expect(host.querySelector("script")).toBeNull();
expect(host.querySelector("pre")?.textContent).toContain("<script>");
expect(host.querySelector('[aria-label="Markdown view"]')).toBeNull();
expect(host.querySelector('a[aria-label="Download notes.txt"] svg')).not.toBeNull();
await act(async () => root.unmount());
});
it("renders HTML in an opaque sandbox, switches to literal source, and keeps download beside the controls", async () => {
const html = '<h1>Report</h1><script>parent.document.cookie</script>';
const host = document.createElement("div"); const root = createRoot(host);
await act(async () => root.render(<TextAttachmentPreview title="report.html" markdown={false} html text={html} downloadUrl="/download" />));
const frame = host.querySelector("iframe");
expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");
expect(frame?.getAttribute("referrerpolicy")).toBe("no-referrer");
expect(frame?.getAttribute("srcdoc")).toContain("Content-Security-Policy");
expect(host.querySelector("script")).toBeNull();
const toggle = host.querySelector('[aria-label="HTML view"]');
expect(toggle?.nextElementSibling?.getAttribute("href")).toBe("/download");
await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Raw"]')!.click());
expect(host.querySelector("iframe")).toBeNull();
expect(host.querySelector("pre")?.textContent).toBe(html);
expect(host.querySelector('[aria-label="Raw"]')?.getAttribute("aria-pressed")).toBe("true");
await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Rendered"]')!.click());
expect(host.querySelector("iframe")).not.toBeNull();
await act(async () => root.unmount());
});
it("opens HTML from an authorized attachment and resets the view for the next file", async () => {
const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
client.setQueryData(queryKeys.issues.attachments("task"), ["one", "two"].map(id => ({ id, originalFilename: `${id}.html`, contentType: "text/html", byteSize: 20, contentPath: `/api/attachments/${id}/content` })));
for (const id of ["one", "two"]) client.setQueryData(["task-text-attachment", "task", id], `<h1>${id}</h1>`);
const host = document.createElement("div"); const root = createRoot(host);
const panel = (id: string) => <QueryClientProvider client={client}><TaskAttachmentPanel issueId="task" attachmentId={id} /></QueryClientProvider>;
await act(async () => root.render(panel("one")));
expect(host.querySelector("iframe")?.getAttribute("title")).toBe("one.html rendered HTML");
await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Raw"]')!.click());
await act(async () => root.render(panel("two")));
expect(host.querySelector("iframe")?.getAttribute("title")).toBe("two.html rendered HTML");
expect(fetch).not.toHaveBeenCalled();
await act(async () => root.unmount()); client.clear();
});
it("rejects HTTP errors, oversized responses and binary data", async () => {
await expect(readTextPreview(new Response("denied", { status: 403 }))).rejects.toThrow("403");
await expect(readTextPreview(new Response("x".repeat(TEXT_PREVIEW_MAX_BYTES + 1)))).rejects.toThrow("too large");
await expect(readTextPreview(new Response("binary\0data"))).rejects.toThrow("binary");
expect(await readTextPreview(new Response(""))).toBe("");
expect(await readTextPreview(new Response("héllo"))).toBe("héllo");
});
});