The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(ui): add CSV table previews to task file tabs (#15445)
Dotta083073703086
diff --git a/doc/PRODUCT.md b/doc/PRODUCT.mdindex 97560d6d9e..b47d36a50b 100644--- a/doc/PRODUCT.md+++ b/doc/PRODUCT.md@@ -232,3 +232,12 @@ to Tasks. A Views menu on the task list covers the inbox views (Mine, Unread,Blocked, Recent, Everything) and the task-status views (All, Active, Backlog,Done). Bare `/issues` opens the last-used view, defaulting to Mine; links thatcarry a task filter open All. Old `/inbox` links redirect to the matching view.++### CSV file previews++Task attachment and workspace file tabs render CSV files as tables by default.+The first record supplies column headers. Row numbers, row and column counts,+and sticky headers help operators scan exports. Rendered and raw view icons+remain next to download; raw view preserves the original source. The table+shows up to 500 data rows and 100 columns, with a notice when the preview is+limited. Download retains the complete file.diff --git a/ui/src/components/CsvPreview.tsx b/ui/src/components/CsvPreview.tsxnew file mode 100644index 0000000000..8a855aed04--- /dev/null+++ b/ui/src/components/CsvPreview.tsx@@ -0,0 +1,41 @@+import { useMemo } from "react";+import { parseCsv } from "@/lib/csv-preview";++const MAX_VISIBLE_ROWS = 500;+const MAX_VISIBLE_COLUMNS = 100;++export function CsvPreview({ text, title }: { text: string; title: string }) {+ const parsed = useMemo(() => {+ try { return { rows: parseCsv(text), error: null }; }+ catch (error) { return { rows: [], error: (error as Error).message }; }+ }, [text]);+ if (parsed.error) return <p role="alert" className="p-4 text-sm text-muted-foreground">{parsed.error}</p>;+ if (!parsed.rows.length) return <p className="p-4 text-sm text-muted-foreground">File is empty.</p>;+ const [header, ...rows] = parsed.rows;+ const columnCount = parsed.rows.reduce((count, row) => Math.max(count, row.length), 0);+ const columns = Array.from({ length: Math.min(columnCount, MAX_VISIBLE_COLUMNS) }, (_, index) => index);+ return (+ <div className="flex min-h-0 flex-1 flex-col bg-background">+ <div className="flex flex-wrap items-center gap-2 border-b border-border px-4 py-2 text-xs text-muted-foreground" role="status">+ <span className="font-medium text-foreground">CSV preview</span>+ <span>{rows.length.toLocaleString()} {rows.length === 1 ? "row" : "rows"}</span>+ <span>{columnCount.toLocaleString()} {columnCount === 1 ? "column" : "columns"}</span>+ {(rows.length > MAX_VISIBLE_ROWS || columnCount > MAX_VISIBLE_COLUMNS) && <span>Showing the first {Math.min(rows.length, MAX_VISIBLE_ROWS)} rows and {columns.length} columns. Download for the complete file.</span>}+ </div>+ <div className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset" role="region" aria-label={`${title} CSV table`} tabIndex={0}>+ <table className="w-full border-collapse text-sm">+ <caption className="sr-only">{title} — first record used as column headers</caption>+ <thead className="sticky top-0 z-10 bg-muted">+ <tr><th scope="col" className="w-10 border-b border-border px-3 py-3 text-right font-mono text-xs text-muted-foreground"><span className="sr-only">Row</span>#</th>+ {columns.map((column) => <th key={column} scope="col" className="whitespace-nowrap border-b border-border px-4 py-3 text-left font-medium">{header[column] || `Column ${column + 1}`}</th>)}+ </tr>+ </thead>+ <tbody>{rows.slice(0, MAX_VISIBLE_ROWS).map((row, index) => <tr key={index} className="even:bg-muted/30 hover:bg-accent/50">+ <th scope="row" className="border-b border-border/50 px-3 py-2 text-right font-mono text-xs font-normal text-muted-foreground">{index + 1}</th>+ {columns.map((column) => <td key={column} className="whitespace-pre-wrap border-b border-border/50 px-4 py-2 align-top">{row[column] ?? ""}</td>)}+ </tr>)}</tbody>+ </table>+ </div>+ </div>+ );+}diff --git a/ui/src/components/FileViewerSheet.copy.test.tsx b/ui/src/components/FileViewerSheet.copy.test.tsxindex 1eb5127b67..027a66d0ee 100644--- a/ui/src/components/FileViewerSheet.copy.test.tsx+++ b/ui/src/components/FileViewerSheet.copy.test.tsx@@ -4,7 +4,7 @@ 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 { FileViewerSheet } from "./FileViewerSheet";+import { FileContentViewer, FileViewerSheet } from "./FileViewerSheet";const useQueryMock = vi.fn();const viewerMock = {@@ -206,3 +206,27 @@ describe("FileViewerSheet copy actions", () => {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;+ }+ });+});diff --git a/ui/src/components/FileViewerSheet.test.tsx b/ui/src/components/FileViewerSheet.test.tsxindex 8e1ba75d02..0a1ff0692d 100644--- a/ui/src/components/FileViewerSheet.test.tsx+++ b/ui/src/components/FileViewerSheet.test.tsx@@ -168,3 +168,51 @@ describe("FileViewerMetadataRow", () => {expect(markup).toContain("Loading file details");});});+++describe("workspace CSV content", () => {+ const csv: WorkspaceFileContent = {+ resource: { kind: "file", provider: "git_worktree", title: "export.csv", displayPath: "export.csv", workspaceLabel: "Workspace", workspaceKind: "execution_workspace", workspaceId: "ws", contentType: "text/csv", byteSize: 20, previewKind: "text", capabilities: { preview: true, download: true, listChildren: false } },+ content: { encoding: "utf8", data: 'Name,Amount\n"Lee, Sam",12' },+ };+ it("defaults to a table and supports toolbar-controlled raw mode", () => {+ const rendered = renderToStaticMarkup(<FileContentViewer content={csv} highlightedLine={null} previewMode="rendered" />);+ expect(rendered).toContain("<table");+ expect(rendered).toContain("Lee, Sam");+ expect(rendered).not.toContain("CSV preview mode");+ const raw = renderToStaticMarkup(<FileContentViewer content={csv} highlightedLine={null} previewMode="raw" />);+ expect(raw).toContain("export.csv source");+ expect(raw).not.toContain("<table");+ });+});+++describe("CSV preview limits", () => {+ it.each([[500, 2], [501, 2], [1, 100], [1, 101]])(+ "bounds a file with %i rows and %i columns and preserves raw source",+ (rowCount, columnCount) => {+ const header = Array.from({ length: columnCount }, (_, i) => `Header${i}`).join(",");+ const row = Array.from({ length: columnCount }, (_, i) => `Value${i}`).join(",");+ const source = [header, ...Array.from({ length: rowCount }, () => row)].join("\n");+ const content: WorkspaceFileContent = {+ resource: { kind: "file", provider: "git_worktree", title: "limits.csv", displayPath: "limits.csv", workspaceLabel: "Workspace", workspaceKind: "execution_workspace", workspaceId: "ws", contentType: "text/csv", byteSize: source.length, previewKind: "text", capabilities: { preview: true, download: true, listChildren: false } },+ content: { encoding: "utf8", data: source },+ };+ const rendered = renderToStaticMarkup(<FileContentViewer content={content} highlightedLine={null} previewMode="rendered" />);+ expect((rendered.match(/<td /g) ?? []).length).toBe(Math.min(rowCount, 500) * Math.min(columnCount, 100));+ expect((rendered.match(/scope="col"/g) ?? []).length).toBe(Math.min(columnCount, 100) + 1);+ expect(rendered).toContain(`${rowCount} ${rowCount === 1 ? "row" : "rows"}`);+ expect(rendered).toContain(`${columnCount} columns`);+ if (rowCount > 500 || columnCount > 100) {+ expect(rendered).toContain(`Showing the first ${Math.min(rowCount, 500)} rows and ${Math.min(columnCount, 100)} columns.`);+ } else {+ expect(rendered).not.toContain("Showing the first");+ }+ const raw = renderToStaticMarkup(<FileContentViewer content={content} highlightedLine={null} previewMode="raw" />);+ expect(raw).not.toContain("<table");+ expect((raw.match(/Value0/g) ?? []).length).toBe(rowCount);+ expect(raw).toContain(row);+ expect(raw).toContain(header);+ },+ );+});diff --git a/ui/src/components/FileViewerSheet.tsx b/ui/src/components/FileViewerSheet.tsxindex fedbac839f..d92b055a69 100644--- a/ui/src/components/FileViewerSheet.tsx+++ b/ui/src/components/FileViewerSheet.tsx@@ -1,3 +1,5 @@+import { CsvPreview } from "./CsvPreview";+import { isCsvFile } from "@/lib/csv-preview";import {useCallback,useEffect,@@ -237,17 +239,20 @@ interface FileContentViewerProps {content: WorkspaceFileContent;highlightedLine: number | null;onLoaded?: (summary: string) => void;+ previewMode?: "raw" | "rendered";htmlMode?: FilePreviewMode;}type MarkdownPreviewMode = "raw" | "rendered";-export function FileContentViewer({ content, highlightedLine, onLoaded, htmlMode = "rendered" }: FileContentViewerProps) {+export function FileContentViewer({ content, highlightedLine, onLoaded, previewMode, htmlMode = "rendered" }: FileContentViewerProps) {const { resource } = content;const isMarkdown = resource.previewKind === "text" && content.content.encoding === "utf8" && isMarkdownResource(resource);- const isHtml = resource.previewKind === "text" && content.content.encoding === "utf8"- && isHtmlPreview(resource.contentType, resource.displayPath || resource.title);- const [markdownMode, setMarkdownMode] = useState<MarkdownPreviewMode>("rendered");+ const isCsv = resource.previewKind === "text" && content.content.encoding === "utf8" && isCsvFile(resource.displayPath || resource.title, resource.contentType ?? "");+ const [localMode, setMarkdownMode] = useState<MarkdownPreviewMode>("rendered");+ const markdownMode = isMarkdown || isCsv ? (previewMode ?? localMode) : "raw";+ const isHtml = resource.previewKind === "text" && content.content.encoding === "utf8" && isHtmlPreview(resource.contentType, resource.displayPath || resource.title);+ const previewLabel = isCsv ? "CSV" : "Markdown";const lines = useMemo(() => {if (resource.previewKind === "text") {return splitContentIntoLines(content.content.data);@@ -259,8 +264,8 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, htmlModeconst highlightedLineRef = useRef<HTMLDivElement>(null);useEffect(() => {- setMarkdownMode(isMarkdown ? "rendered" : "raw");- }, [isMarkdown, resource.displayPath, resource.title, resource.contentType]);+ setMarkdownMode(isMarkdown || isCsv ? "rendered" : "raw");+ }, [isMarkdown, isCsv, resource.displayPath, resource.title, resource.contentType]);useEffect(() => {if (!lines) return;@@ -271,7 +276,7 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, htmlModeif (markdownMode !== "raw") return;if (!highlightedLine || !highlightedLineRef.current) return;highlightedLineRef.current.scrollIntoView({ block: "center", behavior: "auto" });- }, [highlightedLine, markdownMode, htmlMode]);+ }, [highlightedLine, markdownMode, htmlMode, previewMode]);if (resource.previewKind === "image") {const dataUrl = content.content.encoding === "base64"@@ -380,27 +385,27 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, htmlMode);if (isHtml) {- return htmlMode === "raw" ? rawSourceView : <HtmlArtifactPreview html={content.content.data} title={resource.title} />;+ return (previewMode ?? htmlMode) === "raw" ? rawSourceView : <HtmlArtifactPreview html={content.content.data} title={resource.title} />;}- if (!isMarkdown) {+ if (!isMarkdown && !isCsv) {return rawSourceView;}return (<div className="relative flex min-h-0 flex-1 flex-col">- <div className="absolute right-3 top-3 z-20">+ {previewMode === undefined && <div className="absolute right-3 top-3 z-20"><divrole="group"- aria-label="Markdown preview mode"+ aria-label={`${previewLabel} preview mode`}className="inline-flex rounded-md border border-border bg-background/95 p-0.5 shadow-sm backdrop-blur"><Buttontype="button"variant={markdownMode === "rendered" ? "secondary" : "ghost"}size="icon-sm"- aria-label="Show rendered Markdown"- title="Rendered Markdown"+ aria-label={`Show rendered ${previewLabel}`}+ title={`Rendered ${previewLabel}`}aria-pressed={markdownMode === "rendered"}onClick={() => setMarkdownMode("rendered")}className={cn(@@ -414,8 +419,8 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, htmlModetype="button"variant={markdownMode === "raw" ? "secondary" : "ghost"}size="icon-sm"- aria-label="Show raw Markdown"- title="Raw Markdown"+ aria-label={`Show raw ${previewLabel}`}+ title={`Raw ${previewLabel}`}aria-pressed={markdownMode === "raw"}onClick={() => setMarkdownMode("raw")}className={cn(@@ -427,9 +432,10 @@ export function FileContentViewer({ content, highlightedLine, onLoaded, htmlMode</Button></div></div>+ }{markdownMode === "raw" ? (rawSourceView- ) : (+ ) : isCsv ? <CsvPreview text={content.content.data} title={resource.title} /> : (<divrole="region"aria-label={`${resource.title} rendered Markdown`}@@ -951,6 +957,7 @@ interface FileViewerBodyProps {onRetry: () => void;onSetAnnouncement: (message: string) => void;onFallbackToProject: null | (() => void);+ previewMode?: "raw" | "rendered";htmlMode?: FilePreviewMode;}@@ -963,6 +970,7 @@ export function FileViewerBody({onRetry,onSetAnnouncement,onFallbackToProject,+ previewMode,htmlMode,}: FileViewerBodyProps) {if (resolveQuery.isFetching && !resolveQuery.data) {@@ -1061,6 +1069,7 @@ export function FileViewerBody({<FileContentViewercontent={contentQuery.data}highlightedLine={highlightedLine}+ previewMode={previewMode}onLoaded={onSetAnnouncement}htmlMode={htmlMode}/>diff --git a/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsx b/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsxindex a2726b25d0..72ad95bac0 100644--- a/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsx+++ b/ui/src/components/task-side-panel/TaskAttachmentPanel.test.tsx@@ -54,6 +54,22 @@ describe("text attachment tabs", () => {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("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" />));diff --git a/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx b/ui/src/components/task-side-panel/TaskAttachmentPanel.tsxindex dea605ae63..adda17ea9c 100644--- a/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx+++ b/ui/src/components/task-side-panel/TaskAttachmentPanel.tsx@@ -1,8 +1,10 @@-import { useState } from "react";+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";@@ -37,26 +39,30 @@ export async function readTextPreview(response: Response) {}}-export function TextAttachmentPreview({ title, text, markdown, html = false, downloadUrl }: {+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 ? <FilePreviewModeToggle mode={mode} onChange={setMode} label={html ? "HTML view" : "Markdown view"} /> : null}+ {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 ? "flex min-h-0 flex-1 flex-col overflow-hidden" : "min-h-0 flex-1 overflow-auto p-4"}>+ <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>}@@ -96,5 +102,5 @@ export function TaskAttachmentPanel({ issueId, attachmentId }: { issueId: string);}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} markdown={isMarkdownAttachment(attachment)} html={isHtmlPreview(attachment.contentType, attachment.originalFilename)} downloadUrl={downloadUrl} />;+ 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} />;}diff --git a/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsx b/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsxindex 802195472b..874ffdee2c 100644--- a/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsx+++ b/ui/src/components/task-side-panel/TaskWorkspaceFilePanel.tsx@@ -1,3 +1,4 @@+import { isCsvFile } from "@/lib/csv-preview";import { useEffect, useState } from "react";import { useQuery } from "@tanstack/react-query";import { Check, Copy, Download } from "lucide-react";@@ -22,10 +23,10 @@ export function TaskWorkspaceFilePanel({payload: WorkspaceFilePayload;onFallbackToProject?: () => void;}) {+ const [previewMode, setPreviewMode] = useState<"raw" | "rendered">("rendered");+ useEffect(() => setPreviewMode("rendered"), [payload.path, payload.workspace, payload.workspaceId, payload.projectId]);const [copied, setCopied] = useState(false);const [announcement, setAnnouncement] = useState("");- const [htmlMode, setHtmlMode] = useState<FilePreviewMode>("rendered");- useEffect(() => setHtmlMode("rendered"), [payload.path, payload.workspace, payload.workspaceId, payload.projectId]);const state: FileViewerUrlState = {path: payload.path,workspace: payload.workspace,@@ -50,6 +51,8 @@ export function TaskWorkspaceFilePanel({? fileResourcesApi.downloadUrl(issueId, state): null;+ const renderedPreview = resource && (isHtmlPreview(resource.contentType, resource.displayPath || resource.title) || isCsvFile(resource.displayPath || resource.title, resource.contentType ?? "") || /\.(md|markdown|mdown|mkdn|mkd)$/i.test(resource.displayPath || resource.title) || resource.contentType?.includes("markdown"));+return (<div className="flex h-full min-h-0 flex-col bg-muted/20"><header className="flex min-w-0 items-start gap-2 border-b border-border bg-card px-3 py-2">@@ -76,10 +79,7 @@ export function TaskWorkspaceFilePanel({{copied ? <Check aria-hidden /> : <Copy aria-hidden />}</Button>) : null}- {contentQuery.data?.resource.previewKind === "text" && contentQuery.data.content.encoding === "utf8"- && isHtmlPreview(contentQuery.data.resource.contentType, contentQuery.data.resource.displayPath || contentQuery.data.resource.title) ? (- <FilePreviewModeToggle mode={htmlMode} onChange={setHtmlMode} label="HTML view" />- ) : null}+ {renderedPreview && contentQuery.data ? <FilePreviewModeToggle mode={previewMode} onChange={setPreviewMode} label="File preview mode" /> : null}{downloadUrl ? (<Button asChild variant="ghost" size="icon-sm"><a href={downloadUrl} download={resource?.title} aria-label="Download file" title="Download file">@@ -89,9 +89,10 @@ export function TaskWorkspaceFilePanel({) : null}</div></header>- <div className="min-h-0 flex-1 overflow-hidden">+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden"><div className="sr-only" aria-live="polite">{announcement}</div><FileViewerBody+ previewMode={previewMode}resolveQuery={resourceQuery}contentQuery={contentQuery}elapsedMs={0}@@ -103,7 +104,6 @@ export function TaskWorkspaceFilePanel({}}onSetAnnouncement={setAnnouncement}onFallbackToProject={onFallbackToProject ?? null}- htmlMode={htmlMode}/></div></div>diff --git a/ui/src/lib/csv-preview.test.ts b/ui/src/lib/csv-preview.test.tsnew file mode 100644index 0000000000..94e5873954--- /dev/null+++ b/ui/src/lib/csv-preview.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { isCsvFile, parseCsv } from "./csv-preview";++describe("CSV preview parsing", () => {+ it("handles BOM, CRLF, quoted commas, escaped quotes and multiline cells", () => {+ expect(parseCsv('\uFEFFName,Notes,Amount\r\n"Lee, Sam","Said ""hello""\nagain",12\r\n')).toEqual([+ ["Name", "Notes", "Amount"], ["Lee, Sam", 'Said "hello"\nagain', "12"],+ ]);+ });+ it("preserves trailing empty fields, blank records and uneven rows", () => {+ expect(parseCsv("a,b\n1,\n\n2,3,4")).toEqual([["a", "b"], ["1", ""], [""], ["2", "3", "4"]]);+ expect(parseCsv("")).toEqual([]);+ expect(parseCsv("a,b")).toEqual([["a", "b"]]);+ });+ it("reports incomplete quoted fields", () => {+ expect(() => parseCsv('a,b\n"unfinished')).toThrow("incomplete");+ });+ it("recognizes CSV filenames and media types", () => {+ expect(isCsvFile("EXPORT.CSV", "application/octet-stream")).toBe(true);+ expect(isCsvFile("download", "text/csv; charset=utf-8")).toBe(true);+ expect(isCsvFile("notes.txt", "text/plain")).toBe(false);+ });+});diff --git a/ui/src/lib/csv-preview.ts b/ui/src/lib/csv-preview.tsnew file mode 100644index 0000000000..a53b29bbd7--- /dev/null+++ b/ui/src/lib/csv-preview.ts@@ -0,0 +1,29 @@+export function isCsvFile(filename: string, contentType = "") {+ return /\.csv$/i.test(filename) || contentType.split(";")[0].trim().toLowerCase() === "text/csv";+}++/** Parse comma-separated records, preserving quoted newlines and escaped quotes. */+export function parseCsv(text: string): string[][] {+ const source = text.replace(/^\uFEFF/, "");+ if (!source) return [];+ const rows: string[][] = [];+ let row: string[] = [];+ let field = "";+ let quoted = false;+ for (let i = 0; i < source.length; i++) {+ const char = source[i];+ if (char === '"') {+ if (quoted && source[i + 1] === '"') { field += '"'; i++; }+ else if (quoted || field === "") quoted = !quoted;+ else field += char;+ } else if (!quoted && char === ",") {+ row.push(field); field = "";+ } else if (!quoted && (char === "\n" || char === "\r")) {+ row.push(field); rows.push(row); row = []; field = "";+ if (char === "\r" && source[i + 1] === "\n") i++;+ } else field += char;+ }+ if (quoted) throw new Error("A quoted field is incomplete. Switch to raw view to inspect the file.");+ if (field !== "" || row.length || !/[\r\n]$/.test(source)) { row.push(field); rows.push(row); }+ return rows;+}diff --git a/ui/storybook/stories/csv-preview.stories.tsx b/ui/storybook/stories/csv-preview.stories.tsxnew file mode 100644index 0000000000..40dc7e2b30--- /dev/null+++ b/ui/storybook/stories/csv-preview.stories.tsx@@ -0,0 +1,41 @@+import { useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { TaskWorkspaceFilePanel } from "@/components/task-side-panel/TaskWorkspaceFilePanel";+import { queryKeys } from "@/lib/queryKeys";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { TextAttachmentPreview } from "@/components/task-side-panel/TaskAttachmentPanel";++const meta: Meta<typeof TextAttachmentPreview> = {+ title: "Components/CSV File Tab",+ component: TextAttachmentPreview,+ parameters: { layout: "fullscreen" },+ decorators: [(Story) => <div className="h-screen bg-background text-foreground"><Story /></div>],+};+export default meta;+type Story = StoryObj<typeof TextAttachmentPreview>;+export const RevenueExport: Story = {+ args: {+ title: "monthly-revenue.csv",+ markdown: false,+ csv: true,+ downloadUrl: "data:text/csv,Month%2CRevenue%0AOctober%2C12800",+ text: 'Month,Customer,Plan,Revenue,Status,Notes\nOctober,"Acme, Inc.",Enterprise,12800,Active,"Expanded to 40 seats"\nOctober,Northstar Studio,Pro,2400,Active,"Annual renewal"\nOctober,Atlas Labs,Enterprise,9600,Active,"Includes onboarding"\nOctober,Juniper Design,Starter,480,Trial,"Review on Friday"\nSeptember,"Acme, Inc.",Enterprise,11200,Active,"32 seats"\nSeptember,Northstar Studio,Pro,2400,Active,"Annual renewal"\nSeptember,Atlas Labs,Pro,4800,Active,"Upgrade scheduled"\nSeptember,Juniper Design,Starter,480,Trial,"First month"',+ },+};+export const Empty: Story = { args: { ...RevenueExport.args, text: "" } };+export const Invalid: Story = { args: { ...RevenueExport.args, text: 'Name,Notes\nSam,"unfinished' } };++// Exercise the same CSV renderer through the workspace tab query boundary.+function WorkspaceCsvTab() {+ const client = useQueryClient();+ const payload = { kind: "workspace-file" as const, path: "reports/monthly-revenue.csv", workspace: "auto" as const, projectId: null, workspaceId: null, line: null, column: null };+ const { kind: _kind, ...state } = payload;+ useState(() => {+ const resource = { kind: "file", provider: "git_worktree", title: "monthly-revenue.csv", displayPath: payload.path, workspaceLabel: "Report workspace", workspaceKind: "execution_workspace", workspaceId: "csv-story-workspace", contentType: "text/csv", byteSize: 512, previewKind: "text", capabilities: { preview: true, download: true, listChildren: false } };+ client.setQueryData(queryKeys.issues.fileResource("csv-story-task", state), resource);+ client.setQueryData(queryKeys.issues.fileResourceContent("csv-story-task", state), { resource, content: { encoding: "utf8", data: RevenueExport.args!.text } });+ return true;+ });+ return <TaskWorkspaceFilePanel issueId="csv-story-task" payload={payload} />;+}+export const WorkspaceTab: Story = { render: () => <WorkspaceCsvTab /> };