mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-28 13:09:40 +01:00
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:
1 parent
18e8c121d9
commit
24c58e479a
19 files changed
+2479
-233
No files matched your search
@@ -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&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="\n\n"
|
||||
/>,
|
||||
);
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user