Files
PaperClipAI/ui/src/components/task-side-panel/TaskAttachmentPanel.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

107 lines
5.7 KiB
TypeScript

import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Download } from "lucide-react";
import { issuesApi } from "@/api/issues";
import { Button } from "@/components/ui/button";
import { CsvPreview } from "@/components/CsvPreview";
import { isCsvFile } from "@/lib/csv-preview";
import { MarkdownBody } from "@/components/MarkdownBody";
import { HtmlArtifactPreview } from "@/components/HtmlArtifactPreview";
import { FilePreviewModeToggle, type FilePreviewMode } from "@/components/FilePreviewModeToggle";
import { isHtmlPreview } from "@/lib/html-preview";
import { attachmentDownloadPath, isMarkdownAttachment, isTextAttachment } from "@/lib/issue-attachments";
import { queryKeys } from "@/lib/queryKeys";
export const TEXT_PREVIEW_MAX_BYTES = 512 * 1024;
/** Bound the actual response, not just producer-supplied attachment metadata. */
export async function readTextPreview(response: Response) {
if (!response.ok) throw new Error(`Could not load file (${response.status}).`);
if (!response.body) throw new Error("The file response is empty.");
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8", { fatal: true });
let bytes = 0;
let text = "";
try {
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
bytes += chunk.value.byteLength;
if (bytes > TEXT_PREVIEW_MAX_BYTES) throw new Error("This file is too large to preview. Download it instead.");
text += decoder.decode(chunk.value, { stream: true });
}
text += decoder.decode();
if (text.includes("\0")) throw new Error("This file contains binary data. Download it instead.");
return text;
} finally {
await reader.cancel();
reader.releaseLock();
}
}
export function TextAttachmentPreview({ title, text, markdown, html = false, csv = false, downloadUrl }: {
title: string;
text: string;
markdown: boolean;
html?: boolean;
csv?: boolean;
downloadUrl: string;
}) {
const [mode, setMode] = useState<FilePreviewMode>("rendered");
useEffect(() => setMode("rendered"), [title]);
const renderCsv = csv && mode === "rendered" && text.length > 0;
const renderHtml = html && mode === "rendered" && text.length > 0;
return (
<div className="flex h-full min-h-0 flex-col">
<header className="flex items-center gap-2 border-b border-border px-3 py-2">
<h2 className="min-w-0 flex-1 truncate text-sm font-medium" title={title}>{title}</h2>
{markdown || html || csv ? <FilePreviewModeToggle mode={mode} onChange={setMode} label={html ? "HTML view" : csv ? "CSV view" : "Markdown view"} /> : null}
<Button asChild variant="ghost" size="icon-sm">
<a href={downloadUrl} download aria-label={`Download ${title}`} title={`Download ${title}`}><Download aria-hidden /></a>
</Button>
</header>
<div className={renderHtml || renderCsv ? "flex min-h-0 flex-1 flex-col overflow-hidden" : "min-h-0 flex-1 overflow-auto p-4"}>
{text.length === 0 ? <p className="text-sm text-muted-foreground">File is empty.</p>
: renderCsv ? <CsvPreview text={text} title={title} />
: renderHtml ? <HtmlArtifactPreview html={text} title={title} />
: markdown && mode === "rendered" ? <MarkdownBody mediaMode="reference">{text}</MarkdownBody>
: <pre className="whitespace-pre-wrap break-words font-mono text-sm" aria-label={`${title} raw text`}>{text}</pre>}
</div>
</div>
);
}
export function TaskAttachmentPanel({ issueId, attachmentId }: { issueId: string; attachmentId: string }) {
const attachments = useQuery({
queryKey: queryKeys.issues.attachments(issueId),
queryFn: () => issuesApi.listAttachments(issueId),
});
// Re-resolve against this task's authorized attachment list; never trust persisted URLs.
const attachment = attachments.data?.find((item) => item.id === attachmentId);
const eligible = attachment && isTextAttachment(attachment) && attachment.byteSize <= TEXT_PREVIEW_MAX_BYTES;
const content = useQuery({
queryKey: ["task-text-attachment", issueId, attachmentId],
queryFn: async ({ signal }) => readTextPreview(await fetch(
`/api/attachments/${encodeURIComponent(attachmentId)}/content`,
{ signal, credentials: "same-origin" },
)),
enabled: Boolean(eligible),
retry: false,
});
if (attachments.isLoading) return <p className="p-4 text-sm" role="status">Loading file…</p>;
if (attachments.isError) return <div className="p-4" role="alert">Could not load attachment details. <Button onClick={() => void attachments.refetch()}>Retry</Button></div>;
if (!attachment) return <p className="p-4 text-sm" role="status">File no longer available. Close this tab or choose another file.</p>;
const downloadUrl = attachmentDownloadPath(attachment);
if (!eligible || content.isError) {
return (
<div className="space-y-3 p-4" role="alert">
<p className="text-sm">{content.isError ? "Could not preview this file. Retry or download it." : "This file is too large or is not supported for text preview. Download it instead."}</p>
{eligible ? <Button onClick={() => void content.refetch()}>Retry</Button> : null}
<Button asChild variant="outline"><a href={downloadUrl} download>Download file</a></Button>
</div>
);
}
if (content.data === undefined) return <p className="p-4 text-sm" role="status">Loading file…</p>;
return <TextAttachmentPreview key={attachment.id} title={attachment.originalFilename ?? attachment.id} text={content.data} csv={isCsvFile(attachment.originalFilename ?? "", attachment.contentType)} markdown={isMarkdownAttachment(attachment)} html={isHtmlPreview(attachment.contentType, attachment.originalFilename)} downloadUrl={downloadUrl} />;
}