PAP-10440: group artifacts by task stacks (#7654)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The artifacts surface is where board users inspect files, media, and
documents produced by agents.
> - Grouped artifact stacks make that surface easier to scan by task,
but the first pass still made grouping feel secondary to media filters.
> - The follow-up request was to make grouping the default and give the
grouping control the same icon-only outline treatment used on the issues
page.
> - This pull request keeps the existing artifact grouping API/UI, then
polishes the artifacts toolbar state and Storybook review coverage.
> - The benefit is that `/artifacts` now opens in the task-stack view by
default while preserving explicit flat-mode filtering via
`groupBy=none`.

## Linked Issues or Issue Description

No public GitHub issue exists for this internal Paperclip task.

### Subsystem affected

ui/ — React + Vite board UI.

### Problem or motivation

The `/artifacts` grouping affordance was visually placed after the media
filters, rendered as a text button, and defaulted to a flat artifact
list. Internal follow-up `PAP-10465` requested the grouping icon move
left of the filters, become an icon-only outlined button like `/issues`,
and make Task grouping the default.

### Proposed solution

Default `/artifacts` to grouped Task stacks, keep explicit flat mode
available as `groupBy=none`, move the grouping control before the media
chips, and restyle it as the shared icon-only outline button pattern.

### Alternatives considered

Leaving flat mode as the implicit default was rejected because it does
not satisfy the follow-up. Keeping a text label on the grouping trigger
was rejected because `/issues` already established the icon-only outline
pattern for this class of toolbar control.

### Roadmap alignment

This aligns with the `Artifacts & Work Products` roadmap item by making
generated outputs easier to inspect and operate from the board UI.

## What Changed

- Defaulted the `/artifacts` page to `groupBy=task` when no grouping URL
param is present, while keeping explicit flat mode available with
`groupBy=none`.
- Moved the group control before the media filter chips and changed it
to an icon-only outlined button using the shared `Button` pattern.
- Updated artifact page tests to cover default Task grouping, explicit
flat mode, trigger ordering, and icon-only outline metadata.
- Updated the artifact Storybook story so its toolbar mock matches the
production ordering and grouped Task is documented as the default mode.

## Verification

- `pnpm exec vitest run ui/src/pages/Artifacts.test.tsx
ui/src/components/artifacts/ArtifactGroupCard.test.tsx` — passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `git diff --check` — passed.
- QA visual validation from internal follow-up PAP-10466 passed
desktop/mobile scenarios. Screenshot evidence attached there:
- Desktop default:
http://paperclip-dev:3100/api/attachments/bc81305d-f5de-485c-abeb-9e7c3d9d8539/content
- Desktop toolbar close-up:
http://paperclip-dev:3100/api/attachments/3375a62b-2110-48f3-bafa-ea98c00f99f7/content
- Mobile default:
http://paperclip-dev:3100/api/attachments/bfc5642e-9248-431e-9bac-36284dec1c89/content
- Mobile toolbar close-up:
http://paperclip-dev:3100/api/attachments/ca79401a-5ba8-464d-bc6e-aeffd47fe695/content
- GitHub PR checks on head `431964c8b` — passed, including Greptile 5/5.

## Risks

Low to medium risk. The main behavior shift is intentional: `/artifacts`
now queries grouped Task stacks by default. Existing flat mode remains
available through the grouping menu and explicit `groupBy=none` URLs.

## Model Used

OpenAI Codex, GPT-5.4 class coding model in this Paperclip heartbeat
environment, with shell, git, test, and GitHub CLI tool use. Context
window managed by the Codex runtime.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta
2026-06-06 10:22:47 -05:00
committed by GitHub
parent 2e74d32871
commit d8e1004551
17 changed files with 2011 additions and 114 deletions
+35
View File
@@ -59,6 +59,41 @@ describe("artifactsApi.list", () => {
);
});
it("omits groupBy when grouping is none", async () => {
await artifactsApi.list("company-1", { groupBy: "none" });
expect(mockApi.get).toHaveBeenCalledWith("/companies/company-1/artifacts");
});
it("serializes groupBy and the selected stack issue", async () => {
await artifactsApi.list("company-1", {
groupBy: "parent_task",
groupIssueId: "issue-9",
kind: "image",
});
expect(mockApi.get).toHaveBeenCalledWith(
"/companies/company-1/artifacts?kind=image&groupBy=parent_task&groupIssueId=issue-9",
);
});
it("preserves groups and selectedGroup from the envelope", async () => {
const artifact = sampleArtifact();
const group = {
id: "task:issue-1",
groupBy: "task" as const,
issue: artifact.issue,
title: "Demo reel",
count: 3,
mediaKinds: ["video" as const],
previewArtifacts: [artifact],
updatedAt: "2026-06-01T00:00:00.000Z",
href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-1",
};
mockApi.get.mockResolvedValue({ artifacts: [], groups: [group], nextCursor: "next" });
const result = await artifactsApi.list("company-1", { groupBy: "task" });
expect(result.groups).toEqual([group]);
expect(result.nextCursor).toBe("next");
});
it("returns the envelope shape from the backend", async () => {
const artifact = sampleArtifact();
mockApi.get.mockResolvedValue({ artifacts: [artifact], nextCursor: "next" });
+17 -3
View File
@@ -1,12 +1,15 @@
import { api } from "./client";
import type {
CompanyArtifact,
CompanyArtifactGroupBy,
CompanyArtifactMediaKind,
CompanyArtifactsResponse,
} from "@paperclipai/shared";
export type {
CompanyArtifact,
CompanyArtifactGroup,
CompanyArtifactGroupBy as ArtifactGroupBy,
CompanyArtifactMediaKind as ArtifactMediaKind,
CompanyArtifactsResponse,
CompanyArtifactSource as ArtifactSource,
@@ -32,6 +35,10 @@ export interface ListArtifactsParams {
kind?: ArtifactKindFilter;
projectId?: string;
q?: string;
/** Grouping mode. `none` (default) returns the flat artifact grid. */
groupBy?: CompanyArtifactGroupBy;
/** When grouping, selects a single stack to expand into its artifacts. */
groupIssueId?: string;
limit?: number;
cursor?: string;
}
@@ -41,6 +48,8 @@ function buildArtifactsQuery(params?: ListArtifactsParams): string {
if (params?.kind && params.kind !== "all") search.set("kind", params.kind);
if (params?.projectId) search.set("projectId", params.projectId);
if (params?.q) search.set("q", params.q);
if (params?.groupBy && params.groupBy !== "none") search.set("groupBy", params.groupBy);
if (params?.groupIssueId) search.set("groupIssueId", params.groupIssueId);
if (params?.limit != null) search.set("limit", String(params.limit));
if (params?.cursor) search.set("cursor", params.cursor);
const qs = search.toString();
@@ -49,8 +58,8 @@ function buildArtifactsQuery(params?: ListArtifactsParams): string {
/**
* Normalize the endpoint response. The contract is an envelope
* (`{ artifacts, nextCursor }`), but we also tolerate a bare array so the page
* keeps working if the backend ships the simpler shape.
* (`{ artifacts, groups?, selectedGroup?, nextCursor }`), but we also tolerate a
* bare array so the page keeps working if the backend ships the simpler shape.
*/
function normalizeArtifactsResponse(
raw: CompanyArtifactsResponse | CompanyArtifact[],
@@ -58,7 +67,12 @@ function normalizeArtifactsResponse(
if (Array.isArray(raw)) {
return { artifacts: raw, nextCursor: null };
}
return { artifacts: raw.artifacts ?? [], nextCursor: raw.nextCursor ?? null };
return {
artifacts: raw.artifacts ?? [],
groups: raw.groups,
selectedGroup: raw.selectedGroup,
nextCursor: raw.nextCursor ?? null,
};
}
export const artifactsApi = {
+1 -1
View File
@@ -97,7 +97,7 @@ function TextPreview({ artifact }: { artifact: CompanyArtifact }) {
);
}
function ArtifactPreview({ artifact }: { artifact: CompanyArtifact }) {
export function ArtifactPreview({ artifact }: { artifact: CompanyArtifact }) {
switch (artifact.mediaKind) {
case "image":
return <ImagePreview artifact={artifact} />;
@@ -0,0 +1,121 @@
// @vitest-environment jsdom
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ArtifactGroupCard } from "./ArtifactGroupCard";
import type { CompanyArtifact, CompanyArtifactGroup } from "@/api/artifacts";
vi.mock("@/context/CompanyContext", () => ({
useCompany: () => ({ selectedCompany: null, selectedCompanyId: "company-1" }),
}));
function sampleArtifact(overrides: Partial<CompanyArtifact> = {}): CompanyArtifact {
return {
id: "artifact-1",
source: "attachment",
mediaKind: "image",
title: "Hero shot",
previewText: null,
contentType: "image/png",
contentPath: "/files/hero.png",
openPath: "/files/hero.png",
downloadPath: "/files/hero.png?download=1",
issue: { id: "issue-1", identifier: "PAP-42", title: "Ship launch" },
project: null,
createdByAgent: null,
updatedAt: "2026-06-01T00:00:00.000Z",
href: "/PAP/issues/PAP-42#attachment-1",
...overrides,
} as CompanyArtifact;
}
function sampleGroup(overrides: Partial<CompanyArtifactGroup> = {}): CompanyArtifactGroup {
return {
id: "task:issue-1",
groupBy: "task",
issue: { id: "issue-1", identifier: "PAP-42", title: "Ship launch" },
title: "Ship launch",
count: 3,
mediaKinds: ["image"],
previewArtifacts: [sampleArtifact()],
updatedAt: "2026-06-01T00:00:00.000Z",
href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-1",
...overrides,
};
}
function render(group: CompanyArtifactGroup, to = "?groupBy=task&groupIssueId=issue-1") {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
flushSync(() => {
root.render(
<MemoryRouter>
<ArtifactGroupCard group={group} to={to} />
</MemoryRouter>,
);
});
return { container, root };
}
describe("ArtifactGroupCard", () => {
let mounted: { container: HTMLElement; root: ReturnType<typeof createRoot> } | null = null;
beforeEach(() => {
mounted = null;
});
afterEach(() => {
if (mounted) {
flushSync(() => mounted!.root.unmount());
mounted.container.remove();
mounted = null;
}
});
it("shows a stack effect and plural count when count > 1", () => {
mounted = render(sampleGroup({ count: 3 }));
const card = mounted.container.querySelector('[data-testid="artifact-group-card"]') as HTMLElement;
expect(card).not.toBeNull();
expect(card.getAttribute("data-stacked")).toBe("true");
expect(card.getAttribute("data-count")).toBe("3");
// Two decorative stack layers sit behind the card.
expect(mounted.container.querySelectorAll('[data-testid="artifact-stack-layer"]').length).toBe(2);
expect(mounted.container.textContent).toContain("3 artifacts");
});
it("omits the stack effect and uses singular count when count === 1", () => {
mounted = render(sampleGroup({ count: 1 }));
const card = mounted.container.querySelector('[data-testid="artifact-group-card"]') as HTMLElement;
expect(card.getAttribute("data-stacked")).toBe("false");
expect(card.getAttribute("data-count")).toBe("1");
expect(mounted.container.querySelectorAll('[data-testid="artifact-stack-layer"]').length).toBe(0);
expect(mounted.container.textContent).toContain("1 artifact");
expect(mounted.container.textContent).not.toContain("1 artifacts");
});
it("links to the provided stack destination and shows the task subject", () => {
mounted = render(sampleGroup());
const anchor = mounted.container.querySelector("a") as HTMLAnchorElement;
expect(anchor).not.toBeNull();
expect(anchor.getAttribute("href")).toContain("groupIssueId=issue-1");
expect(mounted.container.textContent).toContain("PAP-42");
expect(mounted.container.textContent).toContain("Ship launch");
});
it("renders the first preview artifact image", () => {
mounted = render(sampleGroup());
const img = mounted.container.querySelector("img") as HTMLImageElement;
expect(img).not.toBeNull();
expect(img.getAttribute("src")).toBe("/files/hero.png");
});
it("falls back to a placeholder when there are no preview artifacts", () => {
mounted = render(sampleGroup({ previewArtifacts: [] }));
expect(mounted.container.querySelector("img")).toBeNull();
const card = mounted.container.querySelector('[data-testid="artifact-group-card"]') as HTMLElement;
expect(card).not.toBeNull();
});
});
@@ -0,0 +1,87 @@
import { Layers } from "lucide-react";
import type { To } from "react-router-dom";
import type { CompanyArtifactGroup } from "@/api/artifacts";
import { Link } from "@/lib/router";
import { ArtifactPreview } from "@/components/artifacts/ArtifactCard";
import { formatDate } from "@/lib/utils";
interface ArtifactGroupCardProps {
group: CompanyArtifactGroup;
/** Destination for opening this stack (preserves active filters/search). */
to: To;
}
/**
* A stack card rendered in grouped mode. It mirrors the dimensions and preview
* of {@link ArtifactCard} so grouped and flat grids share the same rhythm, and
* layers a subtle "stack" effect behind the card only when it represents more
* than one artifact.
*/
export function ArtifactGroupCard({ group, to }: ArtifactGroupCardProps) {
const stacked = group.count > 1;
const preview = group.previewArtifacts[0];
const countLabel = `${group.count} artifact${group.count === 1 ? "" : "s"}`;
return (
<div className="relative">
{stacked ? (
<>
<div
aria-hidden="true"
data-testid="artifact-stack-layer"
className="pointer-events-none absolute inset-0 translate-x-[8px] translate-y-[8px] rounded-[8px] border border-border bg-muted/40 shadow-sm"
/>
<div
aria-hidden="true"
data-testid="artifact-stack-layer"
className="pointer-events-none absolute inset-0 translate-x-[4px] translate-y-[4px] rounded-[8px] border border-border bg-muted/70 shadow-sm"
/>
</>
) : null}
<Link
to={to}
title={countLabel}
data-testid="artifact-group-card"
data-group-id={group.id}
data-count={group.count}
data-stacked={stacked ? "true" : "false"}
className="group relative flex flex-col overflow-hidden rounded-[8px] border border-border bg-card transition-colors hover:border-foreground/20"
>
<div className="relative">
{preview ? (
<ArtifactPreview artifact={preview} />
) : (
<div className="flex aspect-video w-full items-center justify-center bg-accent/20 text-muted-foreground/50">
<Layers className="h-7 w-7" aria-hidden="true" />
</div>
)}
<span className="absolute right-2 top-2 inline-flex items-center gap-1 rounded-full bg-background/85 px-2 py-0.5 text-[11px] font-medium text-foreground/90 shadow-sm backdrop-blur">
<Layers className="h-3 w-3" aria-hidden="true" />
{group.count}
</span>
</div>
<div className="flex flex-1 flex-col gap-1 p-3">
<div className="flex h-7 items-center gap-2">
<span className="shrink-0 font-mono text-[11px] text-muted-foreground">
{group.issue.identifier}
</span>
<h3
className="min-w-0 flex-1 truncate text-sm font-medium leading-7 text-foreground/85"
title={group.title}
>
{group.title}
</h3>
</div>
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/65">
<span>{countLabel}</span>
<span className="text-muted-foreground/50">·</span>
<span>Updated {formatDate(group.updatedAt)}</span>
</div>
</div>
</Link>
</div>
);
}
+15 -2
View File
@@ -117,8 +117,21 @@ export const queryKeys = {
detail: (id: string) => ["goals", "detail", id] as const,
},
artifacts: {
list: (companyId: string, kind?: string, q?: string) =>
["artifacts", companyId, kind ?? "all", q ?? ""] as const,
list: (
companyId: string,
kind?: string,
q?: string,
groupBy?: string,
groupIssueId?: string,
) =>
[
"artifacts",
companyId,
kind ?? "all",
q ?? "",
groupBy ?? "none",
groupIssueId ?? "",
] as const,
},
budgets: {
overview: (companyId: string) => ["budgets", "overview", companyId] as const,
+207 -9
View File
@@ -3,9 +3,10 @@
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MemoryRouter } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Artifacts } from "./Artifacts";
import type { CompanyArtifact } from "../api/artifacts";
import type { CompanyArtifact, CompanyArtifactGroup } from "../api/artifacts";
const companyState = vi.hoisted(() => ({
selectedCompanyId: "company-1",
@@ -31,10 +32,34 @@ vi.mock("../api/artifacts", () => ({
artifactsApi: artifactsApiMock,
}));
// Render the menu inline (no radix portal / pointer-capture) so option clicks
// are deterministic in jsdom.
vi.mock("@/components/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuItem: ({
children,
onSelect,
...rest
}: {
children: React.ReactNode;
onSelect?: () => void;
}) => (
<button type="button" onClick={onSelect} {...rest}>
{children}
</button>
),
}));
vi.mock("../components/artifacts/ArtifactCard", () => ({
ArtifactCard: ({ artifact }: { artifact: CompanyArtifact }) => (
<article data-testid="artifact-card">{artifact.title}</article>
),
ArtifactPreview: ({ artifact }: { artifact: CompanyArtifact }) => (
<div data-testid="artifact-preview">{artifact.title}</div>
),
}));
type ObserverCallback = IntersectionObserverCallback;
@@ -76,6 +101,21 @@ function sampleArtifact(overrides: Partial<CompanyArtifact> = {}): CompanyArtifa
};
}
function sampleGroup(overrides: Partial<CompanyArtifactGroup> = {}): CompanyArtifactGroup {
return {
id: "task:issue-1",
groupBy: "task",
issue: { id: "issue-1", identifier: "PAP-42", title: "Ship launch" },
title: "Ship launch",
count: 3,
mediaKinds: ["document"],
previewArtifacts: [sampleArtifact()],
updatedAt: "2026-06-01T00:00:00.000Z",
href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-1",
...overrides,
};
}
async function flush() {
await Promise.resolve();
await new Promise((resolve) => setTimeout(resolve, 0));
@@ -95,7 +135,7 @@ async function waitForAssertion(assertion: () => void, attempts = 50) {
throw lastError;
}
function renderArtifacts(container: HTMLDivElement) {
function renderArtifacts(container: HTMLDivElement, initialEntries: string[] = ["/artifacts"]) {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -103,7 +143,9 @@ function renderArtifacts(container: HTMLDivElement) {
flushSync(() => {
root.render(
<QueryClientProvider client={queryClient}>
<Artifacts />
<MemoryRouter initialEntries={initialEntries}>
<Artifacts />
</MemoryRouter>
</QueryClientProvider>,
);
});
@@ -129,10 +171,8 @@ describe("Artifacts page", () => {
container.remove();
});
it("debounces artifact search into the artifacts API", async () => {
artifactsApiMock.list
.mockResolvedValueOnce({ artifacts: [sampleArtifact()], nextCursor: null })
.mockResolvedValueOnce({ artifacts: [], nextCursor: null });
it("requests task-grouped artifact stacks by default", async () => {
artifactsApiMock.list.mockResolvedValue({ artifacts: [], groups: [sampleGroup()], nextCursor: null });
const { root } = renderArtifacts(container);
@@ -140,11 +180,34 @@ describe("Artifacts page", () => {
expect(artifactsApiMock.list).toHaveBeenCalledWith("company-1", {
kind: "all",
q: undefined,
groupBy: "task",
groupIssueId: undefined,
limit: 30,
cursor: undefined,
});
const groupControl = container.querySelector('[data-testid="artifact-group-control"]') as HTMLButtonElement;
const allFilter = [...container.querySelectorAll('[role="tab"]')]
.find((element) => element.textContent === "All") as HTMLButtonElement;
expect(groupControl).not.toBeNull();
expect(groupControl.textContent).toBe("");
expect(groupControl.getAttribute("data-variant")).toBe("outline");
expect(groupControl.getAttribute("data-size")).toBe("icon");
expect(groupControl.getAttribute("data-group-by")).toBe("task");
expect(Boolean(groupControl.compareDocumentPosition(allFilter) & Node.DOCUMENT_POSITION_FOLLOWING)).toBe(true);
});
flushSync(() => {
root.unmount();
});
});
it("debounces artifact search into the artifacts API", async () => {
artifactsApiMock.list
.mockResolvedValueOnce({ artifacts: [], groups: [sampleGroup()], nextCursor: null })
.mockResolvedValueOnce({ artifacts: [], groups: [], nextCursor: null });
const { root } = renderArtifacts(container);
const input = container.querySelector('input[aria-label="Search artifacts"]') as HTMLInputElement;
expect(input).not.toBeNull();
@@ -163,6 +226,8 @@ describe("Artifacts page", () => {
expect(artifactsApiMock.list).toHaveBeenLastCalledWith("company-1", {
kind: "all",
q: "launch",
groupBy: "task",
groupIssueId: undefined,
limit: 30,
cursor: undefined,
});
@@ -176,7 +241,7 @@ describe("Artifacts page", () => {
it("keeps the artifacts grid max-width constrained and left aligned", async () => {
artifactsApiMock.list.mockResolvedValue({ artifacts: [sampleArtifact()], nextCursor: null });
const { root } = renderArtifacts(container);
const { root } = renderArtifacts(container, ["/artifacts?groupBy=none"]);
await waitForAssertion(() => {
expect(container.querySelector('[data-testid="artifact-card"]')).not.toBeNull();
@@ -202,7 +267,7 @@ describe("Artifacts page", () => {
nextCursor: null,
});
const { root } = renderArtifacts(container);
const { root } = renderArtifacts(container, ["/artifacts?groupBy=none"]);
await waitForAssertion(() => {
expect(container.textContent).toContain("First Artifact");
@@ -218,6 +283,8 @@ describe("Artifacts page", () => {
expect(artifactsApiMock.list).toHaveBeenLastCalledWith("company-1", {
kind: "all",
q: undefined,
groupBy: "none",
groupIssueId: undefined,
limit: 30,
cursor: "cursor-2",
});
@@ -228,4 +295,135 @@ describe("Artifacts page", () => {
root.unmount();
});
});
it("switches grouping via the group control and refetches stacks", async () => {
artifactsApiMock.list.mockImplementation((_companyId: string, params?: { groupBy?: string }) => {
if (params?.groupBy === "none") {
return Promise.resolve({ artifacts: [sampleArtifact()], nextCursor: null });
}
return Promise.resolve({ artifacts: [], groups: [sampleGroup()], nextCursor: null });
});
const { root } = renderArtifacts(container);
await waitForAssertion(() => {
expect(container.querySelector('[data-testid="artifact-group-card"]')).not.toBeNull();
});
const noneOption = container.querySelector(
'[data-testid="artifact-group-option-none"]',
) as HTMLButtonElement;
expect(noneOption).not.toBeNull();
flushSync(() => {
noneOption.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
});
await waitForAssertion(() => {
expect(artifactsApiMock.list).toHaveBeenLastCalledWith("company-1", {
kind: "all",
q: undefined,
groupBy: "none",
groupIssueId: undefined,
limit: 30,
cursor: undefined,
});
expect(container.querySelector('[data-testid="artifact-card"]')).not.toBeNull();
const groupControl = container.querySelector('[data-testid="artifact-group-control"]') as HTMLElement;
expect(groupControl.getAttribute("data-group-by")).toBe("none");
});
flushSync(() => {
root.unmount();
});
});
it("renders stack cards from a grouped URL with count metadata", async () => {
artifactsApiMock.list.mockResolvedValue({
artifacts: [],
groups: [sampleGroup({ count: 4 })],
nextCursor: null,
});
const { root } = renderArtifacts(container, ["/artifacts?groupBy=task"]);
await waitForAssertion(() => {
expect(artifactsApiMock.list).toHaveBeenCalledWith("company-1", {
kind: "all",
q: undefined,
groupBy: "task",
groupIssueId: undefined,
limit: 30,
cursor: undefined,
});
const card = container.querySelector('[data-testid="artifact-group-card"]') as HTMLElement;
expect(card).not.toBeNull();
expect(card.getAttribute("data-count")).toBe("4");
expect(card.getAttribute("data-stacked")).toBe("true");
expect(card.getAttribute("href")).toBe("/artifacts?groupIssueId=issue-1");
expect(card.textContent).toContain("4 artifacts");
});
flushSync(() => {
root.unmount();
});
});
it("opens a stack from the URL and shows the back affordance and artifacts", async () => {
artifactsApiMock.list.mockResolvedValue({
artifacts: [sampleArtifact({ title: "Stacked Artifact" })],
selectedGroup: sampleGroup(),
nextCursor: null,
});
const { root } = renderArtifacts(container, [
"/artifacts?groupBy=task&groupIssueId=issue-1",
]);
await waitForAssertion(() => {
expect(artifactsApiMock.list).toHaveBeenCalledWith("company-1", {
kind: "all",
q: undefined,
groupBy: "task",
groupIssueId: "issue-1",
limit: 30,
cursor: undefined,
});
expect(container.querySelector('[data-testid="artifact-stack-back"]')).not.toBeNull();
expect(
(container.querySelector('[data-testid="artifact-stack-back"]') as HTMLAnchorElement).getAttribute("href"),
).toBe("/artifacts");
expect(container.textContent).toContain("Stacked Artifact");
expect(container.querySelector('[data-testid="artifact-card"]')).not.toBeNull();
});
flushSync(() => {
root.unmount();
});
});
it("preserves the media filter when grouping", async () => {
artifactsApiMock.list.mockResolvedValue({
artifacts: [],
groups: [sampleGroup()],
nextCursor: null,
});
const { root } = renderArtifacts(container, ["/artifacts?kind=image&groupBy=task"]);
await waitForAssertion(() => {
expect(artifactsApiMock.list).toHaveBeenCalledWith("company-1", {
kind: "image",
q: undefined,
groupBy: "task",
groupIssueId: undefined,
limit: 30,
cursor: undefined,
});
});
flushSync(() => {
root.unmount();
});
});
});
+257 -45
View File
@@ -1,20 +1,35 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useInfiniteQuery } from "@tanstack/react-query";
import { Package, Search, X } from "lucide-react";
import { artifactsApi, type ArtifactKindFilter } from "../api/artifacts";
import { ArrowLeft, Check, Layers, Package, Search, X } from "lucide-react";
import type { To } from "react-router-dom";
import {
artifactsApi,
type ArtifactGroupBy,
type ArtifactKindFilter,
} from "../api/artifacts";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { EmptyState } from "../components/EmptyState";
import { PageSkeleton } from "../components/PageSkeleton";
import { ArtifactCard } from "../components/artifacts/ArtifactCard";
import { ArtifactGroupCard } from "../components/artifacts/ArtifactGroupCard";
import { useSearchParams, Link } from "@/lib/router";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
const ARTIFACTS_PAGE_SIZE = 30;
const SEARCH_DEBOUNCE_MS = 250;
const KIND_FILTERS: { value: ArtifactKindFilter; label: string }[] = [
export const ARTIFACT_KIND_FILTERS: { value: ArtifactKindFilter; label: string }[] = [
{ value: "all", label: "All" },
{ value: "image", label: "Images" },
{ value: "video", label: "Videos" },
@@ -23,22 +38,135 @@ const KIND_FILTERS: { value: ArtifactKindFilter; label: string }[] = [
{ value: "file", label: "Files" },
];
export const ARTIFACT_GROUP_OPTIONS: { value: ArtifactGroupBy; label: string }[] = [
{ value: "none", label: "None" },
{ value: "task", label: "Task" },
{ value: "parent_task", label: "Parent task" },
];
const KIND_VALUES = new Set(ARTIFACT_KIND_FILTERS.map((filter) => filter.value));
function parseGroupBy(value: string | null): ArtifactGroupBy {
if (value === "none" || value === "task" || value === "parent_task") return value;
return "task";
}
function parseKind(value: string | null): ArtifactKindFilter {
return value && KIND_VALUES.has(value as ArtifactKindFilter)
? (value as ArtifactKindFilter)
: "all";
}
export function artifactGroupByLabel(value: ArtifactGroupBy): string {
return ARTIFACT_GROUP_OPTIONS.find((option) => option.value === value)?.label ?? "None";
}
export function Artifacts() {
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const [kind, setKind] = useState<ArtifactKindFilter>("all");
const [draftQuery, setDraftQuery] = useState("");
const [query, setQuery] = useState("");
const [searchParams, setSearchParams] = useSearchParams();
const kind = parseKind(searchParams.get("kind"));
const query = searchParams.get("q") ?? "";
const groupBy = parseGroupBy(searchParams.get("groupBy"));
const groupIssueId = searchParams.get("groupIssueId") ?? undefined;
const [draftQuery, setDraftQuery] = useState(query);
const loadMoreRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
setBreadcrumbs([{ label: "Artifacts" }]);
}, [setBreadcrumbs]);
const grouping = groupBy !== "none";
const viewingStackList = grouping && !groupIssueId;
const viewingSelectedStack = grouping && !!groupIssueId;
// Keep the search box in sync when the committed query changes from outside
// (e.g. back/forward navigation or a shared URL), without clobbering in-flight
// typing (which leaves `query` unchanged until the debounce commits).
useEffect(() => {
const handle = window.setTimeout(() => setQuery(draftQuery.trim()), SEARCH_DEBOUNCE_MS);
setDraftQuery((prev) => (prev.trim() === query ? prev : query));
}, [query]);
// Debounce the search box into the `q` URL param so searches are shareable.
useEffect(() => {
const trimmed = draftQuery.trim();
if (trimmed === query) return;
const handle = window.setTimeout(() => {
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
if (trimmed) next.set("q", trimmed);
else next.delete("q");
return next;
},
{ replace: true },
);
}, SEARCH_DEBOUNCE_MS);
return () => window.clearTimeout(handle);
}, [draftQuery]);
}, [draftQuery, query, setSearchParams]);
const updateParams = useCallback(
(mutate: (next: URLSearchParams) => void) => {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
mutate(next);
return next;
});
},
[setSearchParams],
);
const selectKind = useCallback(
(value: ArtifactKindFilter) => {
updateParams((next) => {
if (value === "all") next.delete("kind");
else next.set("kind", value);
});
},
[updateParams],
);
const selectGroupBy = useCallback(
(value: ArtifactGroupBy) => {
updateParams((next) => {
// Switching the grouping mode always returns to the stack list.
next.delete("groupIssueId");
if (value === "task") next.delete("groupBy");
else next.set("groupBy", value);
});
},
[updateParams],
);
// Build a relative `To` that preserves the active filters/search while
// changing only the grouping selection. A bare query string keeps the current
// pathname (the company-prefixed /artifacts route) and stays linkable.
const buildTo = useCallback(
(mutate: (next: URLSearchParams) => void): To => {
const next = new URLSearchParams(searchParams);
mutate(next);
const serialized = next.toString();
return serialized ? `?${serialized}` : "?";
},
[searchParams],
);
const stackTo = useCallback(
(issueId: string): To =>
buildTo((next) => {
if (groupBy === "task") next.delete("groupBy");
else if (groupBy !== "none") next.set("groupBy", groupBy);
next.set("groupIssueId", issueId);
}),
[buildTo, groupBy],
);
const backToStacksTo = useMemo<To>(
() =>
buildTo((next) => {
if (groupBy === "task") next.delete("groupBy");
next.delete("groupIssueId");
}),
[buildTo, groupBy],
);
const {
data,
@@ -49,11 +177,13 @@ export function Artifacts() {
fetchNextPage,
error,
} = useInfiniteQuery({
queryKey: queryKeys.artifacts.list(selectedCompanyId!, kind, query),
queryKey: queryKeys.artifacts.list(selectedCompanyId!, kind, query, groupBy, groupIssueId),
queryFn: ({ pageParam }) =>
artifactsApi.list(selectedCompanyId!, {
kind,
q: query || undefined,
groupBy,
groupIssueId,
limit: ARTIFACTS_PAGE_SIZE,
cursor: pageParam,
}),
@@ -75,12 +205,46 @@ export function Artifacts() {
}, [fetchNextPage, hasNextPage, isFetchingNextPage]);
const artifacts = useMemo(() => data?.pages.flatMap((page) => page.artifacts) ?? [], [data]);
const groups = useMemo(
() => data?.pages.flatMap((page) => page.groups ?? []) ?? [],
[data],
);
const selectedGroup = useMemo(
() => data?.pages.map((page) => page.selectedGroup).find(Boolean) ?? null,
[data],
);
const searching = query.length > 0;
useEffect(() => {
if (viewingSelectedStack && selectedGroup) {
setBreadcrumbs([
{ label: "Artifacts", href: "/artifacts" },
{ label: `${selectedGroup.issue.identifier} · ${selectedGroup.title}` },
]);
} else {
setBreadcrumbs([{ label: "Artifacts" }]);
}
}, [setBreadcrumbs, viewingSelectedStack, selectedGroup]);
if (!selectedCompanyId) {
return <EmptyState icon={Package} message="Select a company to view artifacts." />;
}
const showGroupCards = viewingStackList;
const items = showGroupCards ? groups : artifacts;
const emptyMessage = showGroupCards
? searching
? "No artifact stacks match this search."
: "No artifact stacks yet."
: searching
? "No artifacts match this search."
: viewingSelectedStack
? "No artifacts in this stack match the current filters."
: kind === "all"
? "No artifacts yet. Outputs attached to issues will appear here."
: "No artifacts of this type yet.";
return (
<div className="w-full max-w-6xl space-y-5">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
@@ -105,48 +269,96 @@ export function Artifacts() {
) : null}
</div>
<div className="flex flex-wrap items-center gap-1.5" role="tablist" aria-label="Filter artifacts by type">
{KIND_FILTERS.map((filter) => (
<button
key={filter.value}
type="button"
role="tab"
aria-selected={kind === filter.value}
onClick={() => setKind(filter.value)}
className={cn(
"rounded-md px-2.5 py-1 text-xs font-medium transition-colors",
kind === filter.value
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
)}
>
{filter.label}
</button>
))}
<div className="flex flex-wrap items-center gap-1.5">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
size="icon"
aria-label={`Group artifacts (currently ${artifactGroupByLabel(groupBy)})`}
title="Group artifacts"
data-testid="artifact-group-control"
data-group-by={groupBy}
className={cn("h-8 w-8 shrink-0", grouping && "bg-accent")}
>
<Layers className="h-3.5 w-3.5" aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuLabel>Group by</DropdownMenuLabel>
{ARTIFACT_GROUP_OPTIONS.map((option) => (
<DropdownMenuItem
key={option.value}
data-testid={`artifact-group-option-${option.value}`}
aria-selected={groupBy === option.value}
onSelect={() => selectGroupBy(option.value)}
className="justify-between"
>
{option.label}
{groupBy === option.value ? <Check className="h-3.5 w-3.5" /> : null}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<div className="flex flex-wrap items-center gap-1.5" role="tablist" aria-label="Filter artifacts by type">
{ARTIFACT_KIND_FILTERS.map((filter) => (
<button
key={filter.value}
type="button"
role="tab"
aria-selected={kind === filter.value}
onClick={() => selectKind(filter.value)}
className={cn(
"rounded-md px-2.5 py-1 text-xs font-medium transition-colors",
kind === filter.value
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
)}
>
{filter.label}
</button>
))}
</div>
</div>
</div>
{viewingSelectedStack ? (
<div className="flex flex-wrap items-center gap-2 text-sm">
<Link
to={backToStacksTo}
data-testid="artifact-stack-back"
className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
All stacks
</Link>
{selectedGroup ? (
<span className="truncate text-muted-foreground">
<span className="text-foreground/80">{selectedGroup.issue.identifier}</span>{" "}
{selectedGroup.title}
</span>
) : null}
</div>
) : null}
{error && <p className="text-sm text-destructive">{error.message}</p>}
{isLoading ? (
<PageSkeleton variant="list" />
) : artifacts.length === 0 ? (
<EmptyState
icon={Package}
message={
searching
? "No artifacts match this search."
: kind === "all"
? "No artifacts yet. Outputs attached to issues will appear here."
: "No artifacts of this type yet."
}
/>
) : items.length === 0 ? (
<EmptyState icon={showGroupCards ? Layers : Package} message={emptyMessage} />
) : (
<>
<div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
{artifacts.map((artifact) => (
<ArtifactCard key={`${artifact.source}:${artifact.id}`} artifact={artifact} />
))}
{showGroupCards
? groups.map((group) => (
<ArtifactGroupCard key={group.id} group={group} to={stackTo(group.issue.id)} />
))
: artifacts.map((artifact) => (
<ArtifactCard key={`${artifact.source}:${artifact.id}`} artifact={artifact} />
))}
</div>
<div ref={loadMoreRef} className="flex min-h-10 items-center justify-center pb-2 text-xs text-muted-foreground">
{isFetchingNextPage