Improve task artifacts with rich cards and editable stories (#14469)

Render eight artifact card types from real task records and share them with editable Storybook stories. Preserve document review and media/file actions, and load bounded CSV previews on request.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-28 15:38:06 -05:00
1 parent 18e8c121d9
commit 24c58e479a
19 files changed
+2479 -233

No files matched your search

+1 -1
View File
@@ -50,7 +50,7 @@ for (const mobile of [false, true]) {
await expect(artifacts).toBeVisible();
await expect(artifacts).toHaveAttribute("aria-selected", "false");
await artifacts.click();
await expect(panel.getByText("Arriving report", { exact: true })).toBeVisible();
await expect(panel.getByRole("heading", { name: "Arriving report", level: 2, exact: true })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("artifact-opened-by-user.png"), fullPage: true });
});
}
@@ -0,0 +1,275 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import type { IssueWorkProduct } from "@paperclipai/shared";
import {
IssueArtifactFile,
IssueWorkProductArtifactCard,
} from "./IssueArtifactCard";
import { DocumentCard } from "./RichArtifactCards";
function product(overrides: Partial<IssueWorkProduct> = {}): IssueWorkProduct {
return {
id: "wp-1",
companyId: "company-1",
projectId: null,
issueId: "issue-1",
executionWorkspaceId: null,
runtimeServiceId: null,
type: "pull_request",
provider: "github",
externalId: null,
title: "Actual artifact title",
url: "https://github.com/org/repo/pull/42",
status: "active",
reviewState: "none",
isPrimary: false,
healthStatus: "unknown",
summary: "Actual artifact summary",
metadata: null,
createdByRunId: null,
createdAt: new Date("2026-09-28"),
updatedAt: new Date("2026-09-28"),
...overrides,
};
}
function render(wp: IssueWorkProduct) {
return renderToStaticMarkup(
<QueryClientProvider client={new QueryClient()}>
<IssueWorkProductArtifactCard workProduct={wp} author="Actual agent" />
</QueryClientProvider>,
);
}
describe("production artifact cards", () => {
it("renders supplied PR metadata without synthesizing missing counts, checks or branch names", () => {
const sparse = render(product());
expect(sparse).toContain("Actual artifact title");
expect(sparse).toContain("Actual artifact summary");
expect(sparse).toContain("Actual agent");
expect(sparse).toContain("Checks not available");
expect(sparse).not.toContain("Checks passed");
expect(sparse).not.toContain("+0");
expect(sparse).not.toContain("#0");
expect(sparse).not.toContain("master");
const full = render(
product({
metadata: {
number: 42,
repo: "org/repo",
state: "draft",
additions: 0,
deletions: 8,
changedFiles: 2,
headRef: "feature",
baseRef: "main",
},
}),
);
for (const value of [
"#42",
"org/repo",
"Draft",
"+0",
"−8",
"feature",
"main",
])
expect(full).toContain(value);
});
it("preserves review and unhealthy states", () => {
expect(
render(product({ reviewState: "changes_requested", status: "merged" })),
).toContain("Changes requested");
expect(
render(product({ type: "preview_url", healthStatus: "unhealthy" })),
).toContain("Unhealthy");
expect(
render(product({ type: "preview_url", healthStatus: "unknown" })),
).not.toContain("Healthy");
});
it.each([
["ready_for_review", "Review"],
["changes_requested", "Changes requested"],
])(
"preserves PR status %s without a separate reviewState",
(status, label) => {
expect(render(product({ status, reviewState: "none" }))).toContain(label);
},
);
it("preserves browser-open actions for attachments and signed external file URLs", () => {
const signedUrl =
"https://files.example/report.pdf?signature=abc&expires=123";
const external = render(
product({
type: "artifact",
url: signedUrl,
metadata: { contentType: "application/pdf" },
}),
);
expect(external).toContain(
'href="https://files.example/report.pdf?signature=abc&amp;expires=123"',
);
expect(external).not.toContain("?download=1");
expect(external).toContain("Open file");
expect(external).toContain("Download file");
const local = renderToStaticMarkup(
<QueryClientProvider client={new QueryClient()}>
<IssueArtifactFile
id="pdf-1"
title="Report"
summary=""
author=""
updatedAt="Today"
filename="report.pdf"
contentType="application/pdf"
contentPath="/api/attachments/pdf-1/content"
openPath="/api/attachments/pdf-1/content"
downloadPath="/api/attachments/pdf-1/content?download=1"
byteSize={100}
/>
</QueryClientProvider>,
);
expect(local).toContain(
'href="/api/attachments/pdf-1/content" target="_blank"',
);
expect(local).toContain(
'href="/api/attachments/pdf-1/content?download=1" download="report.pdf"',
);
});
it("selects commit, link, image, video and file renderers from real records", () => {
expect(
render(
product({
type: "commit",
metadata: { sha: "123456789abcdef", repo: "org/repo" },
}),
),
).toContain("12345678");
expect(render(product({ type: "preview_url" }))).toContain("Open link");
const attachment = {
contentPath: "/api/attachments/file-1/content",
byteSize: 25,
};
expect(
render(
product({
type: "artifact",
metadata: {
...attachment,
contentType: "image/png",
originalFilename: "actual.png",
},
}),
),
).toContain("View image");
const video = render(
product({
type: "artifact",
metadata: {
...attachment,
contentType: "video/mp4",
originalFilename: "actual.mp4",
},
}),
);
expect(video).toContain("<video");
expect(video).toContain("controls");
expect(video).not.toContain("autoplay");
const file = render(
product({
type: "artifact",
metadata: {
...attachment,
contentType: "application/pdf",
originalFilename: "actual.pdf",
},
}),
);
expect(file).toContain("Download file");
expect(file).toContain("25 B");
expect(file).toContain("?download=1");
});
it("shows parsed attachment rows and downloads the original CSV", () => {
const client = new QueryClient();
client.setQueryData(
["artifact-csv", "csv-1", "/api/attachments/csv-1/content", "Today"],
{ columns: ["Region"], rows: [["Actual region"]], truncated: false },
);
const html = renderToStaticMarkup(
<QueryClientProvider client={client}>
<IssueArtifactFile
id="csv-1"
title="Report"
summary=""
author=""
updatedAt="Today"
filename="actual.csv"
contentType="text/csv"
contentPath="/api/attachments/csv-1/content"
downloadPath="/api/attachments/csv-1/content?download=1"
byteSize={100}
/>
</QueryClientProvider>,
);
expect(html).toContain("Actual region");
expect(html).toContain("View data");
});
it("does not fetch remote Markdown images just to render a document preview", () => {
const html = renderToStaticMarkup(
<DocumentCard
title="Report"
summary=""
author=""
updatedAt=""
filename="report.md"
revision={1}
body="![External image](https://tracker.example/image.png)\n\n![Uploaded image](/api/attachments/image-1/content)"
/>,
);
expect(html).not.toContain('src="https://tracker.example');
expect(html).toContain('href="https://tracker.example/image.png"');
expect(html).toContain('src="/api/attachments/image-1/content"');
});
it("does not automatically load remote thumbnail or poster metadata", () => {
const link = render(
product({
type: "preview_url",
metadata: { imageUrl: "https://tracker.example/pixel.png" },
}),
);
expect(link).not.toContain("<img");
expect(link).not.toContain("tracker.example");
const video = render(
product({
type: "artifact",
metadata: {
contentType: "video/mp4",
contentPath: "/api/attachments/file-1/content",
posterUrl: "https://tracker.example/poster.png",
},
}),
);
expect(video).not.toContain("poster=");
const local = render(
product({
type: "preview_url",
metadata: { imageUrl: "/api/attachments/thumbnail-1/content" },
}),
);
expect(local).toContain('src="/api/attachments/thumbnail-1/content"');
});
it("keeps branch and runtime actions and blocks unsafe artifact URLs", () => {
expect(render(product({ type: "branch" }))).toContain("Open on GitHub");
expect(
render(product({ type: "runtime_service", healthStatus: "unhealthy" })),
).toContain("Unhealthy");
expect(
render(product({ type: "preview_url", url: "javascript:alert(1)" })),
).not.toContain("javascript:");
});
});
@@ -0,0 +1,277 @@
import { useContext, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
getAttachmentArtifactWorkProductMetadata,
type IssueWorkProduct,
} from "@paperclipai/shared";
import { IssueGalleryContext } from "@/context/IssueGalleryContext";
import { ImageGalleryModal } from "@/components/ImageGalleryModal";
import {
RichWorkProductCard,
stateChipFor,
} from "@/components/task-chat/RichWorkProductCard";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { isImageLikeOutput, isVideoLikeOutput } from "@/lib/issue-output";
import { attachmentDownloadPath } from "@/lib/issue-attachments";
import { workProductHref } from "@/lib/issue-artifacts";
import { formatDateTime } from "@/lib/utils";
import {
artifactText as text,
artifactNumber as number,
artifactUrl,
artifactPreviewUrl,
artifactFileSize,
CSV_PREVIEW_MAX_BYTES,
loadArtifactCsv,
} from "@/lib/artifact-card-data";
import {
CommitCard,
DataCard,
FileCard,
ImageCard,
LinkPreviewCard,
PullRequestCard,
VideoCard,
type ArtifactIdentity,
} from "./RichArtifactCards";
export interface IssueArtifactFileProps extends ArtifactIdentity {
id: string;
filename: string;
contentType: string;
contentPath: string;
downloadPath: string;
openPath?: string;
byteSize: number | null;
metadata?: Record<string, unknown> | null;
}
/** Shared by uploads and promoted uploads; both use the issue's existing gallery. */
export function IssueArtifactFile(props: IssueArtifactFileProps) {
const { metadata = null } = props;
const openGallery = useContext(IssueGalleryContext);
const [galleryOpen, setGalleryOpen] = useState(false);
const [csvRequested, setCsvRequested] = useState(false);
const image = isImageLikeOutput(props.contentType, props.filename);
const video = isVideoLikeOutput(props.contentType, props.filename);
const csv =
props.contentType.split(";")[0] === "text/csv" ||
/\.csv$/i.test(props.filename);
const tooLarge =
props.byteSize !== null && props.byteSize > CSV_PREVIEW_MAX_BYTES;
const localCsv =
csv &&
/^\/api\/attachments\/[a-zA-Z0-9-]+\/content$/.test(props.contentPath);
const data = useQuery({
queryKey: ["artifact-csv", props.id, props.contentPath, props.updatedAt],
queryFn: ({ signal }) => loadArtifactCsv(props.contentPath, signal),
enabled: localCsv && !tooLarge && csvRequested,
retry: false,
staleTime: Infinity,
});
const contentPath = artifactUrl(props.contentPath);
const downloadPath = artifactUrl(props.downloadPath);
const onOpen = () => {
if (!openGallery?.(contentPath)) setGalleryOpen(true);
};
if ((image || video) && contentPath) {
return (
<>
{video ? (
<VideoCard
{...props}
videoUrl={contentPath}
posterUrl={artifactPreviewUrl(text(metadata, "posterUrl"))}
duration={text(metadata, "durationLabel")}
onOpen={onOpen}
/>
) : (
<ImageCard
{...props}
imageUrl={contentPath}
alt={text(metadata, "alt") || props.title}
width={number(metadata, "width")}
height={number(metadata, "height")}
onOpen={onOpen}
/>
)}
{galleryOpen && (
<ImageGalleryModal
items={[
{
id: props.id,
contentPath,
contentType: props.contentType,
originalFilename: props.filename,
downloadPath,
},
]}
initialIndex={0}
open
onOpenChange={setGalleryOpen}
/>
)}
</>
);
}
if (localCsv && !tooLarge && data.data)
return <DataCard {...props} {...data.data} downloadUrl={downloadPath} />;
return (
<div className="flex flex-col gap-2">
<FileCard
{...props}
fileSize={artifactFileSize(props.byteSize)}
entries={[]}
downloadUrl={downloadPath}
openUrl={artifactUrl(props.openPath) || contentPath}
actions={
localCsv && !tooLarge && !data.isError ? (
<Button
variant="outline"
size="sm"
disabled={data.isFetching}
onClick={() => setCsvRequested(true)}
>
{data.isFetching ? "Loading preview…" : "Preview data"}
</Button>
) : undefined
}
/>
{csv && (tooLarge || data.isError || !localCsv) && (
<div className="px-2 text-xs text-muted-foreground" role="status">
{tooLarge
? "CSV is too large to preview. Download the file to view it."
: data.isError
? data.error.message
: "CSV preview is unavailable. Download the file to view it."}
{data.isError && (
<Button
variant="ghost"
size="sm"
onClick={() => void data.refetch()}
>
Retry preview
</Button>
)}
</div>
)}
</div>
);
}
export function IssueWorkProductArtifactCard({
workProduct: wp,
author,
}: {
workProduct: IssueWorkProduct;
author: string;
}) {
const m = wp.metadata;
const href = artifactUrl(workProductHref(wp));
const chip = stateChipFor(wp.type, wp.status, wp.reviewState);
const identity: ArtifactIdentity = {
title: wp.title,
summary: wp.summary ?? "",
author,
updatedAt: formatDateTime(wp.updatedAt),
statusBadge:
wp.healthStatus === "unhealthy" ? (
<Badge variant="destructive">Unhealthy</Badge>
) : chip ? (
<Badge variant="outline">{chip.label}</Badge>
) : undefined,
};
const diff = {
additions: number(m, "additions"),
deletions: number(m, "deletions"),
filesChanged: number(m, "changedFiles", "files"),
};
if (wp.type === "pull_request") {
const state =
text(m, "state") || (wp.status === "active" ? "open" : wp.status);
const checks = text(m, "checks");
return (
<PullRequestCard
{...identity}
{...diff}
number={number(m, "number", "pullRequestNumber")}
repository={text(m, "repo", "repository", "repositoryName")}
sourceBranch={text(m, "headRef", "head", "headBranch", "branch")}
targetBranch={text(m, "baseRef", "base", "baseBranch")}
state={
state === "open" ||
state === "draft" ||
state === "merged" ||
state === "closed"
? state
: "unknown"
}
checks={
checks === "passed" || checks === "failed" || checks === "pending"
? checks
: "unknown"
}
evidenceSource={text(m, "evidenceSource")}
reviewSummary={text(m, "reviewSummary")}
url={href}
statusBadge={
wp.reviewState === "changes_requested" ||
wp.reviewState === "needs_board_review" ||
wp.status === "ready_for_review" ||
wp.status === "changes_requested" ||
wp.status === "failed" ||
wp.healthStatus === "unhealthy"
? identity.statusBadge
: undefined
}
/>
);
}
if (wp.type === "commit")
return (
<CommitCard
{...identity}
{...diff}
sha={text(m, "sha", "shortSha") || wp.externalId || ""}
repository={text(m, "repo", "repository", "repositoryName")}
branch={text(m, "branch", "branchName")}
url={href}
/>
);
if (wp.type === "preview_url")
return (
<LinkPreviewCard
{...identity}
url={href}
imageUrl={artifactPreviewUrl(text(m, "imageUrl"))}
imageAlt={text(m, "imageAlt") || wp.title}
/>
);
if (wp.type === "artifact") {
const attachment = getAttachmentArtifactWorkProductMetadata(wp);
const contentPath = artifactUrl(
attachment?.contentPath || text(m, "contentPath") || href,
);
return (
<IssueArtifactFile
{...identity}
id={wp.id}
filename={text(m, "originalFilename") || wp.title}
contentType={text(m, "contentType")}
contentPath={contentPath}
openPath={artifactUrl(text(m, "openPath")) || href || contentPath}
downloadPath={
artifactUrl(text(m, "downloadPath")) ||
(artifactPreviewUrl(contentPath)
? attachmentDownloadPath({ contentPath })
: href || contentPath)
}
byteSize={number(m, "byteSize", "size")}
metadata={m}
/>
);
}
// Branches, external documents, and runtime services keep their existing actions and health semantics.
return <RichWorkProductCard workProduct={wp} href={href || null} />;
}
@@ -0,0 +1,73 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi } from "vitest";
import { IssueArtifactFile } from "./IssueArtifactCard";
import { loadArtifactCsv } from "@/lib/artifact-card-data";
vi.mock("@/lib/artifact-card-data", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/artifact-card-data")>()),
loadArtifactCsv: vi.fn(),
}));
describe("CSV preview consent", () => {
it("does not fetch any CSV until its preview is requested", async () => {
const load = vi
.mocked(loadArtifactCsv)
.mockResolvedValue({
columns: ["Name"],
rows: [["Actual row"]],
truncated: false,
});
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
try {
await act(async () =>
root.render(
<QueryClientProvider client={client}>
{Array.from({ length: 20 }, (_, i) => (
<IssueArtifactFile
key={i}
id={`csv-${i}`}
title={`Data ${i}`}
summary=""
author=""
updatedAt="Today"
filename={`report-${i}.csv`}
contentType="text/csv"
contentPath={`/api/attachments/csv-${i}/content`}
downloadPath={`/api/attachments/csv-${i}/content?download=1`}
byteSize={100}
/>
))}
</QueryClientProvider>,
),
);
expect(load).not.toHaveBeenCalled();
const preview = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent === "Preview data",
);
expect(preview).toBeDefined();
await act(async () => preview!.click());
await vi.waitFor(() =>
expect(container.textContent).toContain("Actual row"),
);
expect(load).toHaveBeenCalledTimes(1);
expect(load).toHaveBeenCalledWith(
"/api/attachments/csv-0/content",
expect.any(AbortSignal),
);
expect(container.textContent).toContain("View data");
} finally {
await act(async () => root.unmount());
client.clear();
container.remove();
vi.clearAllMocks();
}
});
});
@@ -0,0 +1,733 @@
import { useState, type ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import {
ArrowRight,
CircleCheck,
CircleHelp,
Clock,
ExternalLink,
File,
FileText,
Film,
GitBranch,
GitCommitHorizontal,
GitMerge,
GitPullRequest,
Globe,
Image as ImageIcon,
Table2,
TriangleAlert,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { artifactPreviewUrl, artifactUrl } from "@/lib/artifact-card-data";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
// Renderers contain UI labels only. All artifact-specific content is passed in.
// Example values live exclusively in the individual stories' args.
export interface ArtifactIdentity {
title: string;
summary: string;
author: string;
updatedAt: string;
statusBadge?: ReactNode;
}
function Identity({
title,
summary,
}: Pick<ArtifactIdentity, "title" | "summary">) {
return (
<div className="flex flex-col gap-2">
<h2 className="break-words text-lg font-semibold leading-snug">
{title}
</h2>
{summary && (
<p className="whitespace-pre-wrap text-sm leading-relaxed text-muted-foreground">
{summary}
</p>
)}
</div>
);
}
function Footer({
author,
updatedAt,
action,
statusBadge,
}: Pick<ArtifactIdentity, "author" | "updatedAt" | "statusBadge"> & {
action: ReactNode;
}) {
return (
<footer className="flex flex-wrap items-center justify-between gap-3 border-t border-border px-5 py-3">
<span className="text-xs text-muted-foreground">
{[author, updatedAt].filter(Boolean).join(" · ")}
</span>
{statusBadge}
{action}
</footer>
);
}
function Card({ children }: { children: ReactNode }) {
return (
<article className="w-full overflow-hidden rounded-lg border border-border bg-card text-card-foreground">
{children}
</article>
);
}
function SourceLink({ url, children }: { url: string; children: ReactNode }) {
return url ? (
<Button variant="outline" size="sm" asChild>
<a href={url} target="_blank" rel="noreferrer">
{children}
<ExternalLink className="size-3" />
</a>
</Button>
) : (
<Button variant="outline" size="sm" disabled>
{children}
</Button>
);
}
function Viewer({
title,
description,
action,
children,
}: {
title: string;
description: string;
action: string;
children: ReactNode;
}) {
return (
<Dialog>
<DialogTrigger asChild>
<Button size="sm" variant="outline">
{action}
</Button>
</DialogTrigger>
<DialogContent className="max-h-dvh overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle className="pr-6">{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
{children}
</DialogContent>
</Dialog>
);
}
interface DiffProps {
additions?: number | null;
deletions?: number | null;
filesChanged?: number | null;
}
function Diff({ additions, deletions, filesChanged }: DiffProps) {
return (
<div className="flex flex-wrap gap-2 font-mono text-xs">
{additions != null && (
<span className="text-(--status-task-icon-done)">
+{additions.toLocaleString("en-US")}
</span>
)}
{deletions != null && (
<span className="text-(--status-task-icon-blocked)">
−{deletions.toLocaleString("en-US")}
</span>
)}
{filesChanged != null && (
<span className="text-muted-foreground">
{filesChanged} {filesChanged === 1 ? "file" : "files"}
</span>
)}
</div>
);
}
export interface PullRequestCardProps extends ArtifactIdentity, DiffProps {
number?: number | null;
repository: string;
sourceBranch: string;
targetBranch: string;
state: "open" | "draft" | "merged" | "closed" | "unknown";
checks: "passed" | "pending" | "failed" | "unknown";
evidenceSource: string;
reviewSummary: string;
url: string;
}
const checksLabel = {
passed: "Checks passed",
pending: "Checks pending",
failed: "Checks failed",
unknown: "Checks not available",
};
const stateLabel = {
open: "Open",
draft: "Draft",
merged: "Merged",
closed: "Closed",
unknown: "State unknown",
};
export function PullRequestCard(props: PullRequestCardProps) {
const {
number,
repository,
sourceBranch,
targetBranch,
state,
checks,
evidenceSource,
reviewSummary,
url,
} = props;
const CheckIcon = {
passed: CircleCheck,
pending: Clock,
failed: TriangleAlert,
unknown: CircleHelp,
}[checks];
const checkTone = {
passed: "text-(--status-task-icon-done)",
pending: "text-muted-foreground",
failed: "text-(--status-task-icon-blocked)",
unknown: "text-muted-foreground",
}[checks];
return (
<Card>
<div className="flex flex-col gap-4 p-5">
<div className="flex items-center justify-between gap-2">
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<GitPullRequest className="size-4" /> Pull request{" "}
{number != null && <span className="font-mono">#{number}</span>}
</span>
<Badge
variant="outline"
className={
state === "merged"
? "text-(--status-task-icon-done)"
: "text-muted-foreground"
}
>
{state === "merged" && <GitMerge className="size-3" />}
{stateLabel[state]}
</Badge>
</div>
<Identity {...props} />
<div className="flex flex-col gap-2 text-xs text-muted-foreground">
<span>{repository}</span>
{(sourceBranch || targetBranch) && (
<div className="flex min-w-0 items-center gap-2">
<GitBranch className="size-3.5 shrink-0" />
<code className="min-w-0 truncate" title={sourceBranch}>
{sourceBranch}
</code>
{sourceBranch && targetBranch && (
<ArrowRight className="size-3.5 shrink-0" />
)}
<code className="min-w-0 truncate" title={targetBranch}>
{targetBranch}
</code>
</div>
)}
</div>
<Diff {...props} />
</div>
<div className="flex flex-col gap-2 border-t border-border px-5 py-4">
<span className="flex items-center gap-2 text-xs">
<CheckIcon className={`size-4 ${checkTone}`} />
{checksLabel[checks]}
</span>
{reviewSummary && (
<p className="text-xs leading-relaxed">{reviewSummary}</p>
)}
{evidenceSource && (
<p className="text-xs text-muted-foreground">
Source: {evidenceSource}
</p>
)}
</div>
<Footer
{...props}
action={<SourceLink url={url}>Open pull request</SourceLink>}
/>
</Card>
);
}
export interface CommitCardProps extends ArtifactIdentity, DiffProps {
sha: string;
repository: string;
branch: string;
url: string;
}
export function CommitCard(props: CommitCardProps) {
return (
<Card>
<div className="flex flex-col gap-4 p-5">
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<GitCommitHorizontal className="size-4" /> Commit{" "}
<code title={props.sha}>{props.sha.slice(0, 8)}</code>
</span>
<Identity {...props} />
<span className="break-words text-xs text-muted-foreground">
{props.repository}
</span>
{props.branch && (
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<GitBranch className="size-3.5" />
<code className="min-w-0 truncate">{props.branch}</code>
</span>
)}
<Diff {...props} />
</div>
<Footer
{...props}
action={<SourceLink url={props.url}>View commit</SourceLink>}
/>
</Card>
);
}
function Markdown({ body }: { body: string }) {
return (
<div className="flex flex-col gap-3 text-sm leading-relaxed">
<ReactMarkdown
components={{
h1: ({ children }) => (
<h3 className="text-lg font-semibold">{children}</h3>
),
h2: ({ children }) => (
<h3 className="text-base font-semibold">{children}</h3>
),
h3: ({ children }) => (
<h4 className="text-sm font-semibold">{children}</h4>
),
ul: ({ children }) => (
<ul className="list-disc space-y-1 pl-5">{children}</ul>
),
ol: ({ children }) => (
<ol className="list-decimal space-y-1 pl-5">{children}</ol>
),
img: ({ src, alt }) => {
const localPreview = artifactPreviewUrl(
typeof src === "string" ? src : "",
);
if (localPreview)
return (
<img
src={localPreview}
alt={alt ?? ""}
loading="lazy"
className="h-auto max-w-full"
/>
);
const href = artifactUrl(typeof src === "string" ? src : "");
return href ? (
<a
href={href}
target="_blank"
rel="noreferrer"
className="underline underline-offset-4"
>
{alt || "Open image"}
</a>
) : (
<span>{alt}</span>
);
},
a: ({ children, href }) => (
<a
href={href}
target="_blank"
rel="noreferrer"
className="underline underline-offset-4"
>
{children}
</a>
),
}}
>
{body}
</ReactMarkdown>
</div>
);
}
export interface DocumentCardProps extends ArtifactIdentity {
filename: string;
revision?: number | null;
body: string;
onOpen?: () => void;
expanded?: boolean;
actions?: ReactNode;
}
export function DocumentCard(props: DocumentCardProps) {
return (
<Card>
{props.body && (
<div
className="max-h-52 overflow-hidden border-b border-border bg-muted/20 p-5"
inert
>
<Markdown body={props.body.slice(0, 4000)} />
</div>
)}
<div className="flex flex-col gap-3 p-5">
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<FileText className="size-4" /> Markdown
{props.revision != null && ` · revision ${props.revision}`}
</span>
<Identity {...props} />
<span className="break-all font-mono text-xs text-muted-foreground">
{props.filename}
</span>
</div>
<Footer
{...props}
action={
<div className="flex flex-wrap items-center gap-2">
{props.actions}
{props.onOpen ? (
<Button
size="sm"
variant="outline"
aria-expanded={props.expanded}
onClick={props.onOpen}
>
{props.expanded ? "Close document" : "Read document"}
</Button>
) : (
<Viewer
title={props.title}
description={props.filename}
action="Read document"
>
<Markdown body={props.body} />
</Viewer>
)}
</div>
}
/>
</Card>
);
}
export interface DataCardProps extends ArtifactIdentity {
filename: string;
columns: string[];
rows: (string | number)[][];
truncated?: boolean;
downloadUrl?: string;
}
function DataTable({ columns, rows }: Pick<DataCardProps, "columns" | "rows">) {
return (
<div className="overflow-x-auto">
<table className="w-full text-left text-xs">
<thead>
<tr>
{columns.map((column, i) => (
<th
key={i}
className="border-b border-border px-3 py-3 font-medium text-muted-foreground"
>
{column}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, i) => (
<tr key={i}>
{columns.map((_, j) => (
<td key={j} className="border-b border-border/50 px-3 py-3">
{row[j] ?? ""}
</td>
))}
</tr>
))}
</tbody>
</table>
{rows.length === 0 && (
<p className="p-4 text-xs text-muted-foreground">No rows</p>
)}
</div>
);
}
export function DataCard(props: DataCardProps) {
const csv = [props.columns, ...props.rows]
.map((row) =>
row.map((cell) => `"${String(cell).replaceAll('"', '""')}"`).join(","),
)
.join("\n");
return (
<Card>
<div className="border-b border-border bg-muted/20 px-2">
<DataTable columns={props.columns} rows={props.rows.slice(0, 3)} />
</div>
<div className="flex flex-col gap-3 p-5">
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<Table2 className="size-4" /> CSV · {props.truncated ? "First " : ""}
{props.rows.length} {props.rows.length === 1 ? "row" : "rows"} ·{" "}
{props.columns.length}{" "}
{props.columns.length === 1 ? "column" : "columns"}
</span>
<Identity {...props} />
<span className="break-all font-mono text-xs text-muted-foreground">
{props.filename}
</span>
</div>
<Footer
{...props}
action={
<Viewer
title={props.title}
description={props.filename}
action="View data"
>
<DataTable {...props} />
<Button asChild variant="outline" size="sm" className="w-fit">
<a
download={props.filename}
href={
props.downloadUrl ||
`data:text/csv;charset=utf-8,${encodeURIComponent(csv)}`
}
>
Download CSV
</a>
</Button>
</Viewer>
}
/>
</Card>
);
}
function ImageContent({ src, alt }: { src: string; alt: string }) {
const [failedUrl, setFailedUrl] = useState<string | null>(null);
return src && failedUrl !== src ? (
<img
src={src}
alt={alt}
onError={() => setFailedUrl(src)}
loading="lazy"
className="aspect-video w-full object-contain"
/>
) : (
<div className="flex aspect-video flex-col items-center justify-center gap-3 text-muted-foreground">
<ImageIcon className="size-8" />
<span className="text-xs">No preview available</span>
</div>
);
}
export interface ImageCardProps extends ArtifactIdentity {
filename: string;
imageUrl: string;
alt: string;
width?: number | null;
height?: number | null;
onOpen?: () => void;
}
export function ImageCard(props: ImageCardProps) {
return (
<Card>
<div className="border-b border-border bg-muted/20">
<ImageContent src={props.imageUrl} alt={props.alt} />
</div>
<div className="flex flex-col gap-3 p-5">
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<ImageIcon className="size-4" /> Image
{props.width && props.height
? ` · ${props.width} × ${props.height}`
: ""}
</span>
<Identity {...props} />
<span className="break-all font-mono text-xs text-muted-foreground">
{props.filename}
</span>
</div>
<Footer
{...props}
action={
props.onOpen ? (
<Button
size="sm"
variant="outline"
aria-label={`View image: ${props.title}`}
onClick={props.onOpen}
>
View image
</Button>
) : (
<Viewer
title={props.title}
description={props.filename}
action="View image"
>
<ImageContent src={props.imageUrl} alt={props.alt} />
</Viewer>
)
}
/>
</Card>
);
}
export interface VideoCardProps extends ArtifactIdentity {
filename: string;
videoUrl: string;
posterUrl: string;
duration: string;
onOpen?: () => void;
}
export function VideoCard(props: VideoCardProps) {
return (
<Card>
<video
key={props.videoUrl}
src={props.videoUrl || undefined}
poster={props.posterUrl || undefined}
controls
preload="metadata"
aria-label={props.title}
className="aspect-video w-full border-b border-border bg-muted"
/>
<div className="flex flex-col gap-3 p-5">
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<Film className="size-4" /> Video
{props.duration && ` · ${props.duration}`}
</span>
<Identity {...props} />
<span className="break-all font-mono text-xs text-muted-foreground">
{props.filename}
</span>
</div>
<Footer
{...props}
action={
props.onOpen ? (
<Button
size="sm"
variant="outline"
aria-label={`Open video: ${props.title}`}
onClick={props.onOpen}
>
Open video
</Button>
) : (
<SourceLink url={props.videoUrl}>Open video</SourceLink>
)
}
/>
</Card>
);
}
export interface LinkPreviewCardProps extends ArtifactIdentity {
url: string;
imageUrl: string;
imageAlt: string;
}
export function LinkPreviewCard(props: LinkPreviewCardProps) {
return (
<Card>
{props.imageUrl && (
<div className="border-b border-border bg-muted/20">
<ImageContent src={props.imageUrl} alt={props.imageAlt} />
</div>
)}
<div className="flex flex-col gap-4 p-5">
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<Globe className="size-4" /> Link preview
</span>
<Identity {...props} />
<span className="break-all font-mono text-xs text-muted-foreground">
{props.url}
</span>
</div>
<Footer
{...props}
action={<SourceLink url={props.url}>Open link</SourceLink>}
/>
</Card>
);
}
export interface FileCardProps extends ArtifactIdentity {
filename: string;
contentType: string;
fileSize: string;
entries: string[];
downloadUrl: string;
openUrl?: string;
actions?: ReactNode;
}
export function FileCard(props: FileCardProps) {
return (
<Card>
<div className="flex flex-col gap-4 p-5">
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<File className="size-4" /> File
{props.fileSize && ` · ${props.fileSize}`}
</span>
<Identity {...props} />
<div className="flex flex-col gap-1">
<span className="break-all font-mono text-xs">{props.filename}</span>
<span className="break-all text-xs text-muted-foreground">
{props.contentType}
</span>
</div>
{props.entries.length > 0 && (
<ul className="flex flex-col gap-2 border-t border-border pt-4">
{props.entries.map((entry, i) => (
<li
key={i}
className="flex items-center gap-2 font-mono text-xs text-muted-foreground"
>
<FileText className="size-3.5 shrink-0" />
{entry}
</li>
))}
</ul>
)}
</div>
<Footer
{...props}
action={
<div className="flex flex-wrap items-center gap-2">
{props.actions}
{props.openUrl && (
<SourceLink url={props.openUrl}>Open file</SourceLink>
)}
{props.downloadUrl ? (
<Button asChild size="sm" variant="outline">
<a href={props.downloadUrl} download={props.filename}>
Download file
</a>
</Button>
) : (
<Button size="sm" variant="outline" disabled>
Download unavailable
</Button>
)}
</div>
}
/>
</Card>
);
}
@@ -1,5 +1,4 @@
import { useEffect, useMemo, useRef, useState } from "react";
import type { CSSProperties } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type {
AttachmentArtifactWorkProductMetadata,
@@ -13,14 +12,7 @@ import {
getMarkdownWorkProductAttachmentMetadata,
isArtifactReviewDocumentKey,
} from "@paperclipai/shared";
import {
ChevronDown,
ChevronRight,
Download,
ExternalLink,
FileText,
Paperclip,
} from "lucide-react";
import { Download, ExternalLink } from "lucide-react";
import { ApiError } from "@/api/client";
import { issuesApi } from "@/api/issues";
import { activityApi } from "@/api/activity";
@@ -30,15 +22,22 @@ import { useIssueDocuments } from "@/hooks/useIssueDocuments";
import {
documentDisplayTitle,
selectAgentArtifactAttachments,
workProductHref,
} from "@/lib/issue-artifacts";
import { MediaArtifactCard } from "@/components/artifacts/MediaArtifactCard";
import { isImageLikeOutput, isVideoLikeOutput } from "@/lib/issue-output";
import { attachmentDownloadPath, attachmentOpenPath } from "@/lib/issue-attachments";
import { DocumentCard } from "@/components/artifacts/RichArtifactCards";
import {
IssueArtifactFile,
IssueWorkProductArtifactCard,
} from "@/components/artifacts/IssueArtifactCard";
import {
attachmentDownloadPath,
attachmentOpenPath,
} from "@/lib/issue-attachments";
import { MarkdownBody } from "@/components/MarkdownBody";
import { RichWorkProductCard } from "@/components/task-chat/RichWorkProductCard";
import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "@/components/IssueDocumentAnnotations";
import { cn, formatDateTime } from "@/lib/utils";
import {
DocumentAnnotationsCountChip,
IssueDocumentAnnotations,
} from "@/components/IssueDocumentAnnotations";
import { formatDateTime } from "@/lib/utils";
import { useLocation } from "@/lib/router";
interface IssuePropertiesArtifactsTabProps {
@@ -50,14 +49,10 @@ interface IssuePropertiesArtifactsTabProps {
} | null;
}
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
}
/** Work-product status → label + `--status-task-*` base-hue var for `.status-chip`. */
function workProductStatusBadge(status: string): { label: string; cssVar: string } | null {
function workProductStatusBadge(
status: string,
): { label: string; cssVar: string } | null {
switch (status) {
case "active":
case "draft":
@@ -76,9 +71,6 @@ function workProductStatusBadge(status: string): { label: string; cssVar: string
}
}
const ROW_CLASS =
"flex items-center gap-2 rounded-md border border-border bg-card/50 px-2.5 py-1.5 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
/**
* Work-product row for an eligible Markdown artifact (LOOA-1533 gap): expands
* in place into the shipped document review surface backed by the
@@ -91,12 +83,14 @@ function MarkdownWorkProductRow({
workProduct,
metadata,
reviewDoc,
author,
openRequestId,
}: {
issueId: string;
workProduct: IssueWorkProduct;
metadata: AttachmentArtifactWorkProductMetadata;
reviewDoc: IssueDocument | undefined;
author: string;
openRequestId?: number;
}) {
const [expanded, setExpanded] = useState(false);
@@ -105,13 +99,15 @@ function MarkdownWorkProductRow({
const location = useLocation();
const queryClient = useQueryClient();
const badge = workProductStatusBadge(workProduct.status);
const Chevron = expanded ? ChevronDown : ChevronRight;
const tooLarge = metadata.byteSize > MARKDOWN_REVIEW_DOCUMENT_MAX_BYTES;
const ensure = useMutation({
mutationFn: () => issuesApi.ensureWorkProductReviewDocument(issueId, workProduct.id),
mutationFn: () =>
issuesApi.ensureWorkProductReviewDocument(issueId, workProduct.id),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: queryKeys.issues.documents(issueId) });
await queryClient.invalidateQueries({
queryKey: queryKeys.issues.documents(issueId),
});
},
});
@@ -145,7 +141,8 @@ function MarkdownWorkProductRow({
}, [openRequestId, reviewDoc]);
const unsupportedError =
ensure.error instanceof ApiError && [413, 415, 422].includes(ensure.error.status);
ensure.error instanceof ApiError &&
[413, 415, 422].includes(ensure.error.status);
let expandedBody: React.ReactNode;
if (tooLarge) {
@@ -155,24 +152,25 @@ function MarkdownWorkProductRow({
</p>
);
} else if (reviewDoc) {
expandedBody = reviewDoc.body.trim().length > 0 ? (
<IssueDocumentAnnotations
issueId={issueId}
doc={reviewDoc}
bodyMarkdown={reviewDoc.body}
draftDirty={false}
draftConflicted={false}
historicalPreview={false}
locationHash={location.hash}
panelOpen={annotationPanelOpen}
onPanelOpenChange={setAnnotationPanelOpen}
panelPlacement="popover"
>
<MarkdownBody>{reviewDoc.body}</MarkdownBody>
</IssueDocumentAnnotations>
) : (
<p className="text-sm text-muted-foreground">Document is empty.</p>
);
expandedBody =
reviewDoc.body.trim().length > 0 ? (
<IssueDocumentAnnotations
issueId={issueId}
doc={reviewDoc}
bodyMarkdown={reviewDoc.body}
draftDirty={false}
draftConflicted={false}
historicalPreview={false}
locationHash={location.hash}
panelOpen={annotationPanelOpen}
onPanelOpenChange={setAnnotationPanelOpen}
panelPlacement="popover"
>
<MarkdownBody>{reviewDoc.body}</MarkdownBody>
</IssueDocumentAnnotations>
) : (
<p className="text-sm text-muted-foreground">Document is empty.</p>
);
} else if (ensure.isError) {
expandedBody = (
<div className="flex flex-col items-start gap-1.5">
@@ -196,61 +194,65 @@ function MarkdownWorkProductRow({
</div>
);
} else {
expandedBody = <p className="text-sm text-muted-foreground">Preparing preview…</p>;
expandedBody = (
<p className="text-sm text-muted-foreground">Preparing preview…</p>
);
}
return (
<div className="rounded-md border border-border bg-card/50">
<div ref={headerRef} className="flex items-center hover:bg-accent/50">
<button
type="button"
onClick={handleToggle}
className="flex min-w-0 flex-1 items-center gap-2 px-2.5 py-1.5 text-left text-sm"
aria-expanded={expanded}
>
<FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{workProduct.title}</span>
{badge ? (
<span
className="status-chip inline-flex shrink-0 items-center rounded-full border px-1.5 py-0.5 text-(length:--text-nano) leading-none whitespace-nowrap"
style={{ "--sc": `var(${badge.cssVar})` } as CSSProperties}
>
{badge.label}
</span>
) : null}
{reviewDoc ? (
<span className="shrink-0 text-(length:--text-micro) text-muted-foreground">
{`Rev ${reviewDoc.latestRevisionNumber ?? 1}`}
</span>
) : null}
<Chevron className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</button>
{reviewDoc ? (
<DocumentAnnotationsCountChip
issueId={issueId}
docKey={reviewDoc.key}
panelOpen={annotationPanelOpen}
onToggle={() => setAnnotationPanelOpen((open) => !open)}
/>
) : null}
<a
href={metadata.openPath}
target="_blank"
rel="noreferrer"
aria-label={`Open raw ${workProduct.title}`}
title="Open raw"
className="shrink-0 px-1.5 py-1.5 text-muted-foreground hover:text-foreground"
>
<ExternalLink className="h-3 w-3" />
</a>
<a
href={metadata.downloadPath}
aria-label={`Download ${workProduct.title}`}
title="Download"
className="shrink-0 py-1.5 pr-2 pl-0.5 text-muted-foreground hover:text-foreground"
>
<Download className="h-3 w-3" />
</a>
<div className="flex flex-col gap-2">
<div ref={headerRef}>
<DocumentCard
title={workProduct.title}
summary={workProduct.summary ?? ""}
author={author}
updatedAt={formatDateTime(workProduct.updatedAt)}
filename={metadata.originalFilename ?? workProduct.title}
revision={reviewDoc?.latestRevisionNumber}
body={reviewDoc?.body ?? ""}
onOpen={handleToggle}
expanded={expanded}
statusBadge={
badge ? (
<span className="text-xs text-muted-foreground">
{badge.label}
</span>
) : undefined
}
actions={
<>
{reviewDoc ? (
<DocumentAnnotationsCountChip
issueId={issueId}
docKey={reviewDoc.key}
panelOpen={annotationPanelOpen}
onToggle={() => {
setExpanded(true);
setAnnotationPanelOpen((open) => !open);
}}
/>
) : null}
<a
href={metadata.openPath}
target="_blank"
rel="noreferrer"
aria-label={`Open raw ${workProduct.title}`}
title="Open raw"
className="shrink-0 px-1.5 py-1.5 text-muted-foreground hover:text-foreground"
>
<ExternalLink className="h-3 w-3" />
</a>
<a
href={metadata.downloadPath}
aria-label={`Download ${workProduct.title}`}
title="Download"
className="shrink-0 py-1.5 pr-2 pl-0.5 text-muted-foreground hover:text-foreground"
>
<Download className="h-3 w-3" />
</a>
</>
}
/>
</div>
{expanded ? (
<div className="border-t border-border px-2.5 py-2">{expandedBody}</div>
@@ -262,11 +264,13 @@ function MarkdownWorkProductRow({
function DocumentRow({
issueId,
doc,
author,
openRequestId,
onOpen,
}: {
issueId: string;
doc: IssueDocument;
author: string;
openRequestId?: number;
onOpen?: () => void;
}) {
@@ -274,7 +278,6 @@ function DocumentRow({
const [annotationPanelOpen, setAnnotationPanelOpen] = useState(false);
const headerRef = useRef<HTMLDivElement | null>(null);
const location = useLocation();
const Chevron = expanded ? ChevronDown : ChevronRight;
useEffect(() => {
if (onOpen || openRequestId === undefined) return;
setExpanded(true);
@@ -283,45 +286,32 @@ function DocumentRow({
if (onOpen || openRequestId === undefined || !expanded) return;
headerRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
}, [expanded, onOpen, openRequestId]);
if (onOpen) {
return (
<button
type="button"
onClick={onOpen}
className={cn(ROW_CLASS, "w-full text-left hover:bg-accent/50")}
>
<FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{documentDisplayTitle(doc)}</span>
<span className="shrink-0 text-(length:--text-micro) text-muted-foreground">
{`Rev ${doc.latestRevisionNumber ?? 1}`}
</span>
<ChevronRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</button>
);
}
return (
<div className="rounded-md border border-border bg-card/50">
<div ref={headerRef} className="flex items-center hover:bg-accent/50">
<button
type="button"
onClick={() => setExpanded((open) => !open)}
className="flex min-w-0 flex-1 items-center gap-2 px-2.5 py-1.5 text-left text-sm"
aria-expanded={expanded}
>
<FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{documentDisplayTitle(doc)}</span>
<span className="shrink-0 text-(length:--text-micro) text-muted-foreground">
{`Rev ${doc.latestRevisionNumber ?? 1}`}
</span>
<Chevron className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</button>
<DocumentAnnotationsCountChip
issueId={issueId}
docKey={doc.key}
panelOpen={annotationPanelOpen}
onToggle={() => setAnnotationPanelOpen((open) => !open)}
/>
</div>
<div ref={headerRef}>
<DocumentCard
title={documentDisplayTitle(doc)}
summary=""
author={author}
updatedAt={formatDateTime(doc.updatedAt)}
filename={`${doc.key}.md`}
revision={doc.latestRevisionNumber}
body={doc.body}
onOpen={onOpen ?? (() => setExpanded((open) => !open))}
expanded={onOpen ? undefined : expanded}
actions={
!onOpen ? (
<DocumentAnnotationsCountChip
issueId={issueId}
docKey={doc.key}
panelOpen={annotationPanelOpen}
onToggle={() => {
setExpanded(true);
setAnnotationPanelOpen((open) => !open);
}}
/>
) : undefined
}
/>
{expanded ? (
<div className="border-t border-border px-2.5 py-2">
{doc.body.trim().length > 0 ? (
@@ -358,16 +348,35 @@ function DocumentRow({
* user uploads are excluded — those stay first-class in the conversation
* thread.
*/
export function IssuePropertiesArtifactsTab({ issue, documentDeepLink, onOpenDocument }: IssuePropertiesArtifactsTabProps) {
const { data: attachments } = useQuery({
export function IssuePropertiesArtifactsTab({
issue,
documentDeepLink,
onOpenDocument,
}: IssuePropertiesArtifactsTabProps) {
const {
data: attachments,
isPending: attachmentsPending,
isError: attachmentsError,
refetch: refetchAttachments,
} = useQuery({
queryKey: queryKeys.issues.attachments(issue.id),
queryFn: () => issuesApi.listAttachments(issue.id),
});
const { data: workProducts } = useQuery({
const {
data: workProducts,
isPending: productsPending,
isError: productsError,
refetch: refetchProducts,
} = useQuery({
queryKey: queryKeys.issues.workProducts(issue.id),
queryFn: () => issuesApi.listWorkProducts(issue.id),
});
const { data: documents } = useIssueDocuments(issue.id);
const {
data: documents,
isPending: documentsPending,
isError: documentsError,
refetch: refetchDocuments,
} = useIssueDocuments(issue.id);
const { data: runs } = useQuery({
queryKey: queryKeys.issues.runs(issue.id),
queryFn: () => activityApi.runsForIssue(issue.id),
@@ -380,67 +389,136 @@ export function IssuePropertiesArtifactsTab({ issue, documentDeepLink, onOpenDoc
const workProductRows = workProducts ?? [];
// Proxy review documents (`artifact-review-*`) present only through their
// originating Work product row, never as standalone Documents rows.
const documentRows = (documents ?? []).filter((doc) => !isArtifactReviewDocumentKey(doc.key));
const reviewDocsByKey = new Map((documents ?? []).map((doc) => [doc.key, doc]));
const documentRows = (documents ?? []).filter(
(doc) => !isArtifactReviewDocumentKey(doc.key),
);
const reviewDocsByKey = new Map(
(documents ?? []).map((doc) => [doc.key, doc]),
);
const fileRows = selectAgentArtifactAttachments(attachments, workProducts);
const runsById = useMemo(() => new Map((runs ?? []).map((run) => [run.runId, run])), [runs]);
const agentsById = useMemo(() => new Map((agents ?? []).map((agent) => [agent.id, agent])), [agents]);
const runsById = useMemo(
() => new Map((runs ?? []).map((run) => [run.runId, run])),
[runs],
);
const agentsById = useMemo(
() => new Map((agents ?? []).map((agent) => [agent.id, agent])),
[agents],
);
type ArtifactRow =
| { kind: "work_product"; id: string; runId: string | null; date: Date; value: IssueWorkProduct }
| { kind: "document"; id: string; runId: null; date: Date; value: IssueDocument }
| { kind: "attachment"; id: string; runId: null; date: Date; value: NonNullable<typeof fileRows>[number] };
| {
kind: "work_product";
id: string;
runId: string | null;
date: Date;
value: IssueWorkProduct;
}
| {
kind: "document";
id: string;
runId: null;
date: Date;
value: IssueDocument;
}
| {
kind: "attachment";
id: string;
runId: null;
date: Date;
value: NonNullable<typeof fileRows>[number];
};
const allRows = useMemo<ArtifactRow[]>(() => [
...workProductRows.map((value): ArtifactRow => ({
kind: "work_product",
id: value.id,
runId: value.createdByRunId,
date: new Date(value.createdAt),
value,
})),
...documentRows.map((value): ArtifactRow => ({
kind: "document",
id: value.id,
runId: null,
date: new Date(value.createdAt),
value,
})),
...fileRows.map((value): ArtifactRow => ({
kind: "attachment",
id: value.id,
runId: null,
date: new Date(value.createdAt),
value,
})),
], [documentRows, fileRows, workProductRows]);
const allRows = useMemo<ArtifactRow[]>(
() => [
...workProductRows.map(
(value): ArtifactRow => ({
kind: "work_product",
id: value.id,
runId: value.createdByRunId,
date: new Date(value.createdAt),
value,
}),
),
...documentRows.map(
(value): ArtifactRow => ({
kind: "document",
id: value.id,
runId: null,
date: new Date(value.createdAt),
value,
}),
),
...fileRows.map(
(value): ArtifactRow => ({
kind: "attachment",
id: value.id,
runId: null,
date: new Date(value.createdAt),
value,
}),
),
],
[documentRows, fileRows, workProductRows],
);
const groupedRows = [...allRows.reduce((groups, row) => {
const key = row.runId ?? "other";
const group = groups.get(key) ?? [];
group.push(row);
groups.set(key, group);
return groups;
}, new Map<string, ArtifactRow[]>())]
const groupedRows = [
...allRows.reduce((groups, row) => {
const key = row.runId ?? "other";
const group = groups.get(key) ?? [];
group.push(row);
groups.set(key, group);
return groups;
}, new Map<string, ArtifactRow[]>()),
]
.map(([runId, rows]) => ({
runId,
rows: rows.sort((a, b) => b.date.getTime() - a.date.getTime()),
date: runId === "other"
? rows[0]?.date ?? new Date(0)
: new Date(runsById.get(runId)?.startedAt ?? rows[0]?.date ?? 0),
date:
runId === "other"
? (rows[0]?.date ?? new Date(0))
: new Date(runsById.get(runId)?.startedAt ?? rows[0]?.date ?? 0),
}))
.sort((a, b) => b.date.getTime() - a.date.getTime());
if (workProductRows.length === 0 && documentRows.length === 0 && fileRows.length === 0) {
const loadError = attachmentsError || productsError || documentsError;
const loading = attachmentsPending || productsPending || documentsPending;
const feedback = loadError ? (
<div role="alert" className="px-1 py-3 text-sm text-muted-foreground">
Some artifacts could not be loaded.
<button
className="ml-2 underline"
onClick={() => {
void refetchAttachments();
void refetchProducts();
void refetchDocuments();
}}
>
Retry
</button>
</div>
) : loading ? (
<p role="status" className="px-1 py-3 text-sm text-muted-foreground">
Loading artifacts…
</p>
) : null;
if (
workProductRows.length === 0 &&
documentRows.length === 0 &&
fileRows.length === 0
) {
if (feedback) return feedback;
return (
<div className="px-1 py-6 text-sm text-muted-foreground">
No artifacts yet. Work products, documents, and agent-produced files will appear here.
No artifacts yet. Work products, documents, and agent-produced files
will appear here.
</div>
);
}
return (
<div className="@container flex flex-col gap-3 py-2">
{feedback}
{groupedRows.map((group) => {
const run = group.runId === "other" ? null : runsById.get(group.runId);
const agent = run ? agentsById.get(run.agentId) : null;
@@ -451,16 +529,20 @@ export function IssuePropertiesArtifactsTab({ issue, documentDeepLink, onOpenDoc
<h3 className="truncate text-xs font-medium text-foreground">
{agent?.name ?? `Run ${group.runId.slice(0, 8)}`}
</h3>
<time className="shrink-0 text-(length:--text-micro) text-muted-foreground" dateTime={group.date.toISOString()}>
<time
className="shrink-0 text-(length:--text-micro) text-muted-foreground"
dateTime={group.date.toISOString()}
>
{formatDateTime(group.date)}
</time>
</header>
) : null}
<ul className="grid grid-cols-1 gap-2 @xs:grid-cols-2 @2xl:grid-cols-3">
<ul className="grid grid-cols-1 gap-3">
{group.rows.map((row) => {
if (row.kind === "work_product") {
const wp = row.value;
const markdownMetadata = getMarkdownWorkProductAttachmentMetadata(wp);
const markdownMetadata =
getMarkdownWorkProductAttachmentMetadata(wp);
if (markdownMetadata) {
const reviewKey = artifactReviewDocumentKey(wp.id);
return (
@@ -468,20 +550,24 @@ export function IssuePropertiesArtifactsTab({ issue, documentDeepLink, onOpenDoc
<MarkdownWorkProductRow
issueId={issue.id}
workProduct={wp}
author={agent?.name ?? ""}
metadata={markdownMetadata}
reviewDoc={reviewDocsByKey.get(reviewKey)}
openRequestId={documentDeepLink?.documentKey === reviewKey ? documentDeepLink.requestId : undefined}
openRequestId={
documentDeepLink?.documentKey === reviewKey
? documentDeepLink.requestId
: undefined
}
/>
</li>
);
}
const contentType = typeof wp.metadata?.contentType === "string" ? wp.metadata.contentType : "";
const filename = typeof wp.metadata?.originalFilename === "string" ? wp.metadata.originalFilename : wp.title;
const hasMediaPath = Boolean(wp.metadata?.contentPath || wp.metadata?.openPath || workProductHref(wp));
const media = hasMediaPath && wp.type === "artifact" && (isImageLikeOutput(contentType, filename) || isVideoLikeOutput(contentType, filename));
return (
<li key={row.id} className={cn("min-w-0", !media && "col-span-full")}>
<RichWorkProductCard workProduct={wp} href={workProductHref(wp)} variant={media ? "gallery" : "compact"} />
<li key={row.id} className="col-span-full min-w-0">
<IssueWorkProductArtifactCard
workProduct={wp}
author={agent?.name ?? ""}
/>
</li>
);
}
@@ -492,36 +578,44 @@ export function IssuePropertiesArtifactsTab({ issue, documentDeepLink, onOpenDoc
<DocumentRow
issueId={issue.id}
doc={doc}
onOpen={onOpenDocument ? () => onOpenDocument(doc) : undefined}
openRequestId={documentDeepLink?.documentKey === doc.key ? documentDeepLink.requestId : undefined}
author={
agentsById.get(
doc.updatedByAgentId ?? doc.createdByAgentId ?? "",
)?.name ?? ""
}
onOpen={
onOpenDocument ? () => onOpenDocument(doc) : undefined
}
openRequestId={
documentDeepLink?.documentKey === doc.key
? documentDeepLink.requestId
: undefined
}
/>
</li>
);
}
const attachment = row.value;
const filename = attachment.originalFilename ?? attachment.objectKey;
if (isImageLikeOutput(attachment.contentType, filename) || isVideoLikeOutput(attachment.contentType, filename)) {
return (
<li key={row.id} className="min-w-0">
<MediaArtifactCard
id={attachment.id}
title={filename}
contentPath={attachment.contentPath}
contentType={attachment.contentType}
originalFilename={filename}
downloadPath={attachmentDownloadPath(attachment)}
detail={formatBytes(attachment.byteSize)}
/>
</li>
);
}
const filename =
attachment.originalFilename ?? attachment.objectKey;
return (
<li key={row.id} className="col-span-full min-w-0">
<a href={attachmentOpenPath(attachment)} target="_blank" rel="noreferrer" className={cn(ROW_CLASS, "hover:bg-accent/50")}>
<Paperclip className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 truncate">{attachment.originalFilename ?? attachment.objectKey}</span>
<span className="shrink-0 text-(length:--text-micro) text-muted-foreground">{formatBytes(attachment.byteSize)}</span>
</a>
<IssueArtifactFile
id={attachment.id}
title={filename}
summary=""
author={
agentsById.get(attachment.createdByAgentId ?? "")
?.name ?? ""
}
updatedAt={formatDateTime(attachment.updatedAt)}
filename={filename}
contentType={attachment.contentType}
contentPath={attachment.contentPath}
openPath={attachmentOpenPath(attachment)}
downloadPath={attachmentDownloadPath(attachment)}
byteSize={attachment.byteSize}
/>
</li>
);
})}
@@ -209,7 +209,8 @@ describe("markdown work product review row", () => {
it("renders an expandable row with explicit raw and download actions", async () => {
await renderTab();
expect(expandButton().textContent).toContain("Verification report");
expect(container.querySelector("h2")?.textContent).toBe("Verification report");
expect(expandButton().textContent).toBe("Read document");
const raw = container.querySelector('a[title="Open raw"]') as HTMLAnchorElement;
const download = container.querySelector('a[title="Download"]') as HTMLAnchorElement;
expect(raw?.getAttribute("href")).toBe(`/api/attachments/${ATTACHMENT_ID}/content`);
@@ -320,11 +321,11 @@ describe("markdown work product review row", () => {
await waitForAssertion(() => {
expect(container.textContent).toContain("loose-notes.md");
});
expect(container.textContent).not.toContain("report.md");
expect(container.querySelectorAll("article")).toHaveLength(2);
const looseLink = Array.from(container.querySelectorAll("a")).find(
(anchor) => anchor.textContent?.includes("loose-notes.md"),
(anchor) => anchor.getAttribute("download") === "loose-notes.md",
);
expect(looseLink?.getAttribute("href")).toBe("/api/attachments/22222222-2222-4222-8222-222222222222/content");
expect(looseLink?.getAttribute("href")).toBe("/api/attachments/22222222-2222-4222-8222-222222222222/content?download=1");
});
it("keeps non-markdown work products on the download row", async () => {
@@ -345,10 +346,10 @@ describe("markdown work product review row", () => {
await renderTab();
await waitForAssertion(() => {
const row = container.querySelector('[data-testid="task-chat-rich-work-product-artifact"]');
const link = row?.querySelector("a");
const row = container.querySelector("article");
const link = row?.querySelector("a[download]");
expect(row?.textContent).toContain("Verification report");
expect(link?.getAttribute("aria-label")).toBe("Download: Verification report");
expect(link?.textContent).toBe("Download file");
expect(link?.getAttribute("href")).toBe(`${contentPath}?download=1`);
});
expect(container.querySelector("button[aria-expanded]")).toBeNull();
@@ -365,16 +366,16 @@ describe("markdown work product review row", () => {
})]);
await renderTab({}, "Cover artwork");
await waitForAssertion(() => {
const buttons = container.querySelectorAll('button[aria-label^="Open gallery:"]');
const buttons = container.querySelectorAll('button[aria-label^="View image:"], button[aria-label^="Open video:"]');
expect(buttons).toHaveLength(3);
expect(container.querySelectorAll("img")).toHaveLength(2);
expect(buttons[0].querySelector("img")).not.toBeNull();
expect(buttons[1].querySelector("video")?.getAttribute("src")).toBe(video.contentPath);
expect(container.querySelectorAll("article")).toHaveLength(3);
expect(container.querySelector("video")?.getAttribute("src")).toBe(video.contentPath);
expect(container.querySelectorAll("video")).toHaveLength(1);
});
});
it("groups compact rows by producing run", async () => {
it("groups rich cards by producing run", async () => {
const runOne = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const runTwo = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const imagePath = `/api/attachments/${ATTACHMENT_ID}/content`;
@@ -416,10 +417,10 @@ describe("markdown work product review row", () => {
await waitForAssertion(() => {
expect(container.textContent).toContain("CodexCoder");
expect(container.textContent).toContain("DesignCoder");
expect(container.querySelector('article[data-variant="compact"]')).not.toBeNull();
expect(container.querySelectorAll("article")).toHaveLength(2);
expect(container.querySelector(`img[src="${imagePath}"]`)).not.toBeNull();
expect(container.querySelector('a[aria-label="Open on GitHub: Artifact grouping PR"]')).not.toBeNull();
expect(container.querySelector('button[aria-label="Open gallery: Artifacts screenshot"]')).not.toBeNull();
expect(container.querySelector('a[href="https://github.com/paperclipai/paperclip/pull/1"]')?.textContent).toContain("Open pull request");
expect(container.querySelector('button[aria-label="View image: Artifacts screenshot"]')).not.toBeNull();
});
});
});
+127
View File
@@ -0,0 +1,127 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
artifactNumber,
artifactPreviewUrl,
artifactUrl,
CSV_PREVIEW_MAX_BYTES,
loadArtifactCsv,
parseArtifactCsv,
} from "./artifact-card-data";
afterEach(() => vi.unstubAllGlobals());
describe("artifact metadata", () => {
it("does not turn absent or invalid counts into zero", () => {
for (const value of [undefined, null, "12", -1, Infinity, NaN])
expect(artifactNumber({ additions: value }, "additions")).toBeNull();
expect(artifactNumber({ additions: 0 }, "additions")).toBe(0);
});
it("loads optional thumbnails only through local authenticated attachment routes", () => {
for (const value of [
"https://example.com/tracker.png",
"http://127.0.0.1/private",
"//evil.test/track",
"/api/companies",
"/api/attachments/a/content?redirect=1",
])
expect(artifactPreviewUrl(value)).toBe("");
expect(artifactPreviewUrl("/api/attachments/file-1/content")).toBe(
"/api/attachments/file-1/content",
);
});
it("permits web and root-relative URLs only", () => {
for (const url of [
"javascript:alert(1)",
"//evil.test",
"/\\evil.test",
"data:text/html,hello",
"https:\n//evil.test",
])
expect(artifactUrl(url)).toBe("");
expect(artifactUrl("/api/attachments/a/content")).toBe(
"/api/attachments/a/content",
);
expect(artifactUrl("https://example.com/path?q=1")).toBe(
"https://example.com/path?q=1",
);
});
});
describe("CSV artifact preview", () => {
it("reads quoted commas, escaped quotes, embedded newlines, CRLF, BOM and empty cells", () => {
expect(
parseArtifactCsv(
'\uFEFFName,Notes,Count\r\n"Smith, Jo","a ""quote""\nand line",0\r\nOther,,2\r\n',
),
).toEqual({
columns: ["Name", "Notes", "Count"],
rows: [
["Smith, Jo", 'a "quote"\nand line', "0"],
["Other", "", "2"],
],
truncated: false,
});
});
it("bounds rows, columns and bytes and rejects malformed quoting", () => {
const preview = parseArtifactCsv(
"Name\n" + Array.from({ length: 202 }, (_, i) => `${i}`).join("\n"),
);
expect(preview.rows).toHaveLength(200);
expect(preview.truncated).toBe(true);
expect(() => parseArtifactCsv(Array(51).fill("x").join(","))).toThrow(
"too many columns",
);
expect(() =>
parseArtifactCsv("x".repeat(CSV_PREVIEW_MAX_BYTES + 1)),
).toThrow("too large");
expect(() => parseArtifactCsv('Name\n"unfinished')).toThrow(
"could not be previewed",
);
expect(() => parseArtifactCsv('Name\n"closed"extra')).toThrow(
"could not be previewed",
);
expect(parseArtifactCsv("")).toEqual({
columns: [],
rows: [],
truncated: false,
});
});
it("never fetches remote or arbitrary local URLs", async () => {
const fetcher = vi.fn();
vi.stubGlobal("fetch", fetcher);
for (const path of [
"https://example.com/data.csv",
"/api/companies",
"/api/attachments/a/content?redirect=yes",
])
await expect(loadArtifactCsv(path)).rejects.toThrow("unavailable");
expect(fetcher).not.toHaveBeenCalled();
});
it("uses authenticated attachment content with no redirects", async () => {
const fetcher = vi.fn().mockResolvedValue(new Response("A,B\n1,2"));
vi.stubGlobal("fetch", fetcher);
const signal = new AbortController().signal;
expect(
(await loadArtifactCsv("/api/attachments/file-1/content", signal)).rows,
).toEqual([["1", "2"]]);
expect(fetcher).toHaveBeenCalledWith("/api/attachments/file-1/content", {
credentials: "same-origin",
redirect: "error",
signal,
});
});
it("stops oversized streamed files even when the server sends no content length", async () => {
const cancel = vi.fn();
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(CSV_PREVIEW_MAX_BYTES + 1));
},
cancel,
});
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(stream)));
await expect(
loadArtifactCsv("/api/attachments/file-1/content"),
).rejects.toThrow("too large");
expect(cancel).toHaveBeenCalled();
});
});
+164
View File
@@ -0,0 +1,164 @@
/** Optional producer metadata must never become invented facts in an artifact card. */
export function artifactText(
metadata: Record<string, unknown> | null,
...keys: string[]
): string {
for (const key of keys) {
const value = metadata?.[key];
if (typeof value === "string" && value.trim()) return value.trim();
}
return "";
}
export function artifactNumber(
metadata: Record<string, unknown> | null,
...keys: string[]
): number | null {
for (const key of keys) {
const value = metadata?.[key];
if (typeof value === "number" && Number.isFinite(value) && value >= 0)
return value;
}
return null;
}
export function artifactUrl(value: string | null | undefined): string {
if (!value || /[\u0000-\u0020\\]/.test(value)) return "";
if (value.startsWith("/") && !value.startsWith("//")) return value;
try {
const url = new URL(value);
return ["https:", "http:"].includes(url.protocol) ? value : "";
} catch {
return "";
}
}
/** Optional link thumbnails and video posters must not contact producer-chosen hosts. */
export function artifactPreviewUrl(value: string): string {
return /^\/api\/attachments\/[a-zA-Z0-9-]+\/content$/.test(value)
? value
: "";
}
export function artifactFileSize(bytes: number | null): string {
if (bytes === null) return "";
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export const CSV_PREVIEW_MAX_BYTES = 1024 * 1024;
const CSV_PREVIEW_MAX_ROWS = 200;
const CSV_PREVIEW_MAX_COLUMNS = 50;
/** RFC 4180 quoting, CRLF, embedded newlines, and a UTF-8 BOM; bounded for the UI. */
export function parseArtifactCsv(text: string) {
if (new TextEncoder().encode(text).length > CSV_PREVIEW_MAX_BYTES)
throw new Error(
"CSV is too large to preview. Download the file to view it.",
);
const records: string[][] = [];
let row: string[] = [],
field = "",
quoted = false,
closedQuote = false;
const endField = () => {
row.push(field);
if (row.length > CSV_PREVIEW_MAX_COLUMNS)
throw new Error(
"CSV has too many columns to preview. Download the file to view it.",
);
field = "";
closedQuote = false;
};
const input = text.replace(/^\uFEFF/, "");
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (quoted) {
if (char === '"' && input[i + 1] === '"') {
field += '"';
i++;
} else if (char === '"') {
quoted = false;
closedQuote = true;
} else field += char;
} else if (char === ",") {
endField();
} else if (char === "\n" || char === "\r") {
endField();
records.push(row);
row = [];
if (char === "\r" && input[i + 1] === "\n") i++;
if (records.length > CSV_PREVIEW_MAX_ROWS + 1) break;
} else if (char === '"' && !field && !closedQuote) {
quoted = true;
} else {
if (closedQuote || char === '"')
throw new Error(
"CSV could not be previewed. Download the file to view it.",
);
field += char;
}
}
if (quoted)
throw new Error(
"CSV could not be previewed. Download the file to view it.",
);
if (field || row.length || closedQuote) {
endField();
records.push(row);
}
return {
columns: records[0] ?? [],
rows: records.slice(1, CSV_PREVIEW_MAX_ROWS + 1),
truncated: records.length > CSV_PREVIEW_MAX_ROWS + 1,
};
}
/** Only fetch authenticated attachment bytes, never a producer-supplied remote URL. */
export async function loadArtifactCsv(
contentPath: string,
signal?: AbortSignal,
) {
if (!/^\/api\/attachments\/[a-zA-Z0-9-]+\/content$/.test(contentPath))
throw new Error(
"CSV preview is unavailable. Download the file to view it.",
);
const response = await fetch(contentPath, {
credentials: "same-origin",
redirect: "error",
signal,
});
if (!response.ok)
throw new Error("CSV could not be loaded. Try again or download the file.");
if (Number(response.headers.get("content-length")) > CSV_PREVIEW_MAX_BYTES) {
await response.body?.cancel();
throw new Error(
"CSV is too large to preview. Download the file to view it.",
);
}
const reader = response.body?.getReader();
if (!reader)
throw new Error("CSV could not be loaded. Try again or download the file.");
const decoder = new TextDecoder();
let text = "",
size = 0;
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > CSV_PREVIEW_MAX_BYTES) {
await reader.cancel();
throw new Error(
"CSV is too large to preview. Download the file to view it.",
);
}
text += decoder.decode(value, { stream: true });
}
text += decoder.decode();
} finally {
reader.releaseLock();
}
return parseArtifactCsv(text);
}
@@ -0,0 +1,70 @@
# Artifact cards
Storybook: **Explorations → Artifact cards**. Each story renders one production
card from `ui/src/components/artifacts/RichArtifactCards.tsx`. All example titles,
authors, content, filenames, repository names, and URLs live in story args.
Use **Controls** to edit values, including Markdown bodies and JSON table data.
Theme and viewport use Storybook's toolbar.
Fixed component text consists of type, action, metadata, and state labels, such
as “Pull request,” “Read document,” “Source,” and “Checks not available.” The
contents of documents, column names, and descriptions are data.
## Production data
`IssuePropertiesArtifactsTab` renders these cards through `IssueArtifactCard`.
It keeps run grouping, agent attribution, upload deduplication, document deep
links, the document editor/annotation surface, and the shared issue gallery.
Chat work-product rows and branch/runtime cards keep their existing rendering.
| Card | Source |
| --- | --- |
| Pull request | Work-product title, summary, status, and GitHub metadata (`repo`, `number`, `baseRef`, `headRef`, `additions`, `deletions`, `changedFiles`, `state`) |
| Commit | Work-product title, summary, `repo`, `sha`, `branch`, and diff counts |
| Document | Issue document body/revision, or the existing materialized Markdown attachment review document |
| Data | User-requested authenticated attachment CSV content, parsed locally with a 1 MiB limit, at most 200 preview rows and 50 columns; downloads retain the original file |
| Image | Attachment content path, filename, optional `alt`, `width`, and `height` metadata |
| Video | Attachment content path, filename, optional `posterUrl` and `durationLabel` metadata; native playback controls |
| Link preview | Preview work-product URL, title, summary, optional `imageUrl` and `imageAlt` metadata |
| File | Filename, MIME type, recorded byte size, original browser-open and download paths |
External file URLs (including signed query strings) are preserved unchanged.
File cards retain a separate browser-open action for inline formats such as PDF.
Missing summaries and counts stay absent. Unknown PR state/checks stay unknown.
Optional producer metadata `checks` (`passed`, `pending`, `failed`),
`reviewSummary`, and `evidenceSource` appears only when supplied. These are
recorded values, not a new live GitHub check or review integration. Runtime health
is never inferred from a URL. No remote page is scraped to manufacture a preview. Optional link images and
video posters must use local authenticated attachment content URLs; remote
metadata cannot silently trigger requests from the operator’s browser. Markdown
card previews follow the same rule; remote images appear as explicit links.
CSV previews load only after the operator clicks **Preview data**. Opening a task
does not fetch its CSV contents. Previews only fetch local attachment content endpoints. Malformed, oversized,
or unavailable files retain the download action and explain the preview failure.
The existing company-scoped APIs continue to authorize all content access.
Markdown attachments retain the existing server materialization and annotation
workflow. Their body preview appears after that document has been created.
## Examples
PR and commit args use captured facts from public PR #14141. The explanatory
summaries and agent-reported review details are editable examples, not live
provider data. Other stories use illustrative data. Image and video stories use
existing local Paper Trail fixtures. File downloads a small sample text file.
The File story's optional entries demonstrate supplied archive contents; the
app does not inspect arbitrary archive bytes.
## Run and verify
```sh
pnpm storybook
pnpm build-storybook
pnpm --filter @paperclipai/ui typecheck
pnpm check:token-gates
```
Start at `/?path=/story/explorations-artifact-cards-pull-request--pull-request`.
Tests cover metadata validation, bounded CSV parsing/fetching, card selection,
Markdown review/annotations, deep links, agent filtering, and deduplication.
@@ -0,0 +1,45 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { CommitCard } from "@/components/artifacts/RichArtifactCards";
import {
decorators,
parameters,
identityControls,
textData,
diffControls,
} from "./storyConfig";
const meta = {
title: "Explorations/Artifact cards/Commit",
component: CommitCard,
decorators,
parameters,
argTypes: {
...identityControls,
...diffControls,
sha: textData("Commit SHA; the card displays the first eight characters."),
repository: textData("Repository owner/name."),
branch: textData("Branch name. Clear to hide."),
url: textData("Destination for the fixed View commit action."),
},
} satisfies Meta<typeof CommitCard>;
export default meta;
type Story = StoryObj<typeof meta>;
// Every artifact-specific example value is editable through Storybook Controls.
export const Commit: Story = {
name: "Commit",
args: {
title: "Historical-schema worktree fixture fix",
summary:
"Insert historical user columns explicitly so worktree seeding tests work against the older schema.",
author: "Codie",
updatedAt: "Sep 26, 2026",
sha: "1c3c9ddfddc755a4c45b3644d3d4b21abcdde43c",
repository: "paperclipai/paperclip",
branch: "fix/personal-keyboard-shortcut-preference",
additions: 12,
deletions: 8,
filesChanged: 1,
url: "https://github.com/paperclipai/paperclip/commit/1c3c9ddfddc755a4c45b3644d3d4b21abcdde43c",
},
};
@@ -0,0 +1,47 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { DataCard } from "@/components/artifacts/RichArtifactCards";
import {
decorators,
parameters,
identityControls,
textData,
objectData,
} from "./storyConfig";
const meta = {
title: "Explorations/Artifact cards/Data",
component: DataCard,
decorators,
parameters,
argTypes: {
...identityControls,
filename: textData("Filename used when downloading the data."),
columns: objectData(
"Editable JSON array of column names. No column names are hardcoded in the renderer.",
),
rows: objectData(
"Editable JSON array of rows. The card previews three; View data shows all. Counts and CSV download follow this data.",
),
},
} satisfies Meta<typeof DataCard>;
export default meta;
type Story = StoryObj<typeof meta>;
// Every artifact-specific example value is editable through Storybook Controls.
export const Data: Story = {
name: "Data",
args: {
title: "Signup report",
summary: "",
author: "Codie",
updatedAt: "Sep 26, 2026",
filename: "signups.csv",
columns: ["Region", "Signups", "Conversion"],
rows: [
["North America", 1240, "8.2%"],
["Europe", 980, "7.6%"],
["Asia Pacific", 720, "6.9%"],
["Latin America", 410, "7.1%"],
],
},
};
@@ -0,0 +1,43 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { DocumentCard } from "@/components/artifacts/RichArtifactCards";
import {
decorators,
parameters,
identityControls,
textData,
numberData,
} from "./storyConfig";
const meta = {
title: "Explorations/Artifact cards/Document",
component: DocumentCard,
decorators,
parameters,
argTypes: {
...identityControls,
filename: textData("Actual document filename."),
revision: numberData("Document revision number."),
body: {
...textData(
"The document’s actual Markdown body. Every word in the preview comes from this control.",
),
table: { category: "Artifact content" },
},
},
} satisfies Meta<typeof DocumentCard>;
export default meta;
type Story = StoryObj<typeof meta>;
// Every artifact-specific example value is editable through Storybook Controls.
export const Document: Story = {
name: "Document",
args: {
title: "Rollout brief",
summary: "",
author: "Codie",
updatedAt: "Sep 26, 2026",
filename: "rollout-brief.md",
revision: 3,
body: "## Ready for rollout\n\nKeyboard shortcuts are now a personal preference.\n\n- Available to every user.\n- Off by default after upgrade.\n- Changes apply only to the signed-in account.",
},
};
@@ -0,0 +1,51 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { FileCard } from "@/components/artifacts/RichArtifactCards";
import {
decorators,
parameters,
identityControls,
textData,
objectData,
} from "./storyConfig";
const meta = {
title: "Explorations/Artifact cards/File",
component: FileCard,
decorators,
parameters,
argTypes: {
...identityControls,
filename: textData("Original file name, also used for download."),
contentType: textData("MIME type from file metadata."),
fileSize: textData("Formatted file size."),
entries: objectData(
"Optional archive entries as a JSON array of file paths. Empty hides the list.",
),
openUrl: textData(
"Optional URL for opening the original file in a browser tab.",
),
downloadUrl: textData(
"Stored file URL. Empty disables download. This example supplies a tiny text file.",
),
},
} satisfies Meta<typeof FileCard>;
export default meta;
type Story = StoryObj<typeof meta>;
// Every artifact-specific example value is editable through Storybook Controls.
export const File: Story = {
name: "File",
args: {
title: "Release notes",
summary: "",
author: "Codie",
updatedAt: "Sep 26, 2026",
filename: "release-notes.txt",
contentType: "text/plain",
fileSize: "42 B",
entries: [],
openUrl: "",
downloadUrl:
"data:text/plain;charset=utf-8,Personal%20keyboard%20shortcuts%20are%20available.%0A",
},
};
@@ -0,0 +1,45 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { ImageCard } from "@/components/artifacts/RichArtifactCards";
import {
decorators,
parameters,
identityControls,
textData,
numberData,
} from "./storyConfig";
import posterUrl from "../../fixtures/artifact-media/paper-trail.png?url";
const meta = {
title: "Explorations/Artifact cards/Image",
component: ImageCard,
decorators,
parameters,
argTypes: {
...identityControls,
filename: textData("Original image filename."),
imageUrl: textData(
"The image source URL. The preview is an actual image, not a hardcoded Settings component.",
),
alt: textData("Description of the image for assistive technology."),
width: numberData("Image width from file metadata."),
height: numberData("Image height from file metadata."),
},
} satisfies Meta<typeof ImageCard>;
export default meta;
type Story = StoryObj<typeof meta>;
// Every artifact-specific example value is editable through Storybook Controls.
export const Image: Story = {
name: "Image",
args: {
title: "Paper Trail concept",
summary: "",
author: "Codie",
updatedAt: "Sep 26, 2026",
filename: "paper-trail.png",
imageUrl: posterUrl,
alt: "Paper Trail visual concept",
width: 400,
height: 400,
},
};
@@ -0,0 +1,41 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { LinkPreviewCard } from "@/components/artifacts/RichArtifactCards";
import {
decorators,
parameters,
identityControls,
textData,
} from "./storyConfig";
const meta = {
title: "Explorations/Artifact cards/Link preview",
component: LinkPreviewCard,
decorators,
parameters,
argTypes: {
...identityControls,
url: textData(
"Saved destination URL. There is no embedded app or simulated workspace.",
),
imageUrl: textData(
"Optional saved screenshot or link image URL. Empty means no thumbnail.",
),
imageAlt: textData("Description of the optional image."),
},
} satisfies Meta<typeof LinkPreviewCard>;
export default meta;
type Story = StoryObj<typeof meta>;
// Every artifact-specific example value is editable through Storybook Controls.
export const LinkPreview: Story = {
name: "Link preview",
args: {
title: "Project website",
summary: "A link saved by the agent.",
author: "Codie",
updatedAt: "Sep 26, 2026",
url: "https://example.com",
imageUrl: "",
imageAlt: "",
},
};
@@ -0,0 +1,68 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { PullRequestCard } from "@/components/artifacts/RichArtifactCards";
import {
decorators,
parameters,
identityControls,
textData,
numberData,
diffControls,
} from "./storyConfig";
const meta = {
title: "Explorations/Artifact cards/Pull request",
component: PullRequestCard,
decorators,
parameters,
argTypes: {
...identityControls,
...diffControls,
number: numberData("Pull request number."),
repository: textData("Repository owner/name."),
sourceBranch: textData("Source branch."),
targetBranch: textData("Target branch."),
state: {
control: "select",
options: ["open", "draft", "merged", "closed", "unknown"],
description: "Saved PR state. The component formats its label.",
table: { category: "Artifact data" },
},
checks: {
control: "select",
options: ["passed", "pending", "failed", "unknown"],
description: "Reported check state, not a live query.",
table: { category: "Artifact data" },
},
evidenceSource: textData(
"Where the displayed check/review information came from. Clear to hide.",
),
reviewSummary: textData("Optional reported review result. Clear to hide."),
url: textData("Destination for the fixed Open pull request action."),
},
} satisfies Meta<typeof PullRequestCard>;
export default meta;
type Story = StoryObj<typeof meta>;
// Every artifact-specific example value is editable through Storybook Controls.
export const PullRequest: Story = {
name: "Pull request",
args: {
title: "Per-user keyboard shortcut preference",
summary:
"Each user can enable keyboard shortcuts in Profile without administrator access.",
author: "Codie",
updatedAt: "Sep 26, 2026",
number: 14141,
repository: "paperclipai/paperclip",
sourceBranch: "fix/personal-keyboard-shortcut-preference",
targetBranch: "master",
state: "merged",
checks: "passed",
evidenceSource: "Codie’s Sep 26, 11:50 AM handoff",
reviewSummary: "Greptile 5/5 · 6 review threads resolved",
additions: 1159,
deletions: 68,
filesChanged: 30,
url: "https://github.com/paperclipai/paperclip/pull/14141",
},
};
@@ -0,0 +1,51 @@
import type { Decorator } from "@storybook/react-vite";
// Layout only; no demo heading or text is rendered around the card.
export const decorators: Decorator[] = [
(Story) => (
<div className="w-full max-w-lg">
<Story />
</div>
),
];
export const parameters = {
layout: "padded",
controls: {
expanded: false,
exclude: ["onOpen", "actions", "statusBadge", "expanded"],
},
docs: {
description: {
component:
"One card. Every artifact-specific value is editable in Controls. Labels and actions are fixed component copy. No live API requests.",
},
},
};
export const textData = (description: string) => ({
control: { type: "text" as const },
description,
table: { category: "Artifact data" },
});
export const numberData = (description: string) => ({
control: { type: "number" as const, min: 0 },
description,
table: { category: "Artifact data" },
});
export const objectData = (description: string) => ({
control: { type: "object" as const },
description,
table: { category: "Artifact content" },
});
export const identityControls = {
title: textData("Artifact title. This is example data, not fixed UI copy."),
summary: textData(
"Optional artifact summary. Clear it to remove the paragraph.",
),
author: textData("Author name supplied by the artifact."),
updatedAt: textData("Display date supplied by the artifact."),
};
export const diffControls = {
additions: numberData("Added lines from the change metadata."),
deletions: numberData("Deleted lines from the change metadata."),
filesChanged: numberData("Number of changed files."),
};
@@ -0,0 +1,41 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { VideoCard } from "@/components/artifacts/RichArtifactCards";
import {
decorators,
parameters,
identityControls,
textData,
} from "./storyConfig";
import posterUrl from "../../fixtures/artifact-media/paper-trail.png?url";
import videoUrl from "../../fixtures/artifact-media/paper-trail.mp4?url";
const meta = {
title: "Explorations/Artifact cards/Video",
component: VideoCard,
decorators,
parameters,
argTypes: {
...identityControls,
filename: textData("Original video filename."),
videoUrl: textData("Playable video source URL."),
posterUrl: textData("Poster image source URL."),
duration: textData("Duration from media metadata."),
},
} satisfies Meta<typeof VideoCard>;
export default meta;
type Story = StoryObj<typeof meta>;
// Every artifact-specific example value is editable through Storybook Controls.
export const Video: Story = {
name: "Video",
args: {
title: "Paper Trail motion study",
summary: "",
author: "Codie",
updatedAt: "Sep 26, 2026",
filename: "paper-trail.mp4",
videoUrl: videoUrl,
posterUrl: posterUrl,
duration: "0:03",
},
};