Skip to content

The open-source app everyone uses to manage agents at work

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

Dottad8e1004551f1
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index a3bfcdadd8..559e5ddd8c 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -453,6 +453,8 @@ export type {
IssueWorkProductReviewState,
CompanyArtifact,
CompanyArtifactAgentSummary,
+ CompanyArtifactGroup,
+ CompanyArtifactGroupBy,
CompanyArtifactIssueSummary,
CompanyArtifactMediaKind,
CompanyArtifactProjectSummary,
@@ -1004,6 +1006,8 @@ export {
COMPANY_ARTIFACTS_DEFAULT_LIMIT,
COMPANY_ARTIFACTS_MAX_LIMIT,
COMPANY_ARTIFACTS_MAX_QUERY_LENGTH,
+ companyArtifactGroupBySchema,
+ companyArtifactGroupSchema,
companyArtifactMediaKindSchema,
companyArtifactSchema,
companyArtifactSourceSchema,
diff --git a/packages/shared/src/types/artifact.ts b/packages/shared/src/types/artifact.ts
index 413ed68f43..6d022d34a7 100644
--- a/packages/shared/src/types/artifact.ts
+++ b/packages/shared/src/types/artifact.ts
@@ -2,6 +2,8 @@ export type CompanyArtifactSource = "document" | "attachment" | "work_product";
export type CompanyArtifactMediaKind = "image" | "video" | "text" | "document" | "file" | "empty";
+export type CompanyArtifactGroupBy = "none" | "task" | "parent_task";
+
export interface CompanyArtifactIssueSummary {
id: string;
identifier: string;
@@ -35,7 +37,21 @@ export interface CompanyArtifact {
href: string;
}
+export interface CompanyArtifactGroup {
+ id: string;
+ groupBy: Exclude<CompanyArtifactGroupBy, "none">;
+ issue: CompanyArtifactIssueSummary;
+ title: string;
+ count: number;
+ mediaKinds: CompanyArtifactMediaKind[];
+ previewArtifacts: CompanyArtifact[];
+ updatedAt: string;
+ href: string;
+}
+
export interface CompanyArtifactsResponse {
artifacts: CompanyArtifact[];
+ groups?: CompanyArtifactGroup[];
+ selectedGroup?: CompanyArtifactGroup | null;
nextCursor: string | null;
}
diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts
index f97f801aad..6b72c75264 100644
--- a/packages/shared/src/types/index.ts
+++ b/packages/shared/src/types/index.ts
@@ -217,6 +217,8 @@ export type {
export type {
CompanyArtifact,
CompanyArtifactAgentSummary,
+ CompanyArtifactGroup,
+ CompanyArtifactGroupBy,
CompanyArtifactIssueSummary,
CompanyArtifactMediaKind,
CompanyArtifactProjectSummary,
diff --git a/packages/shared/src/validators/artifact.test.ts b/packages/shared/src/validators/artifact.test.ts
new file mode 100644
index 0000000000..2f0c138a6f
--- /dev/null
+++ b/packages/shared/src/validators/artifact.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest";
+import { companyArtifactsQuerySchema, companyArtifactsResponseSchema } from "./artifact.js";
+
+const issue = {
+ id: "11111111-1111-4111-8111-111111111111",
+ identifier: "PAP-1",
+ title: "Build artifacts",
+};
+
+const artifact = {
+ id: "document:22222222-2222-4222-8222-222222222222",
+ source: "document",
+ mediaKind: "document",
+ title: "Plan",
+ previewText: "Artifact preview",
+ contentType: "text/markdown",
+ contentPath: null,
+ openPath: null,
+ downloadPath: null,
+ issue,
+ project: null,
+ createdByAgent: null,
+ updatedAt: "2026-06-06T12:00:00.000Z",
+ href: "/PAP/issues/PAP-1#document-plan",
+};
+
+describe("companyArtifactsQuerySchema", () => {
+ it("defaults to the existing flat artifact query", () => {
+ expect(companyArtifactsQuerySchema.parse({})).toMatchObject({
+ kind: "all",
+ groupBy: "none",
+ limit: 30,
+ });
+ });
+
+ it("accepts grouped artifact query parameters", () => {
+ expect(
+ companyArtifactsQuerySchema.parse({
+ groupBy: "parent_task",
+ groupIssueId: issue.id,
+ kind: "video",
+ q: "render",
+ }),
+ ).toMatchObject({
+ groupBy: "parent_task",
+ groupIssueId: issue.id,
+ kind: "video",
+ q: "render",
+ });
+ });
+
+ it("rejects invalid grouped artifact query parameters", () => {
+ expect(() => companyArtifactsQuerySchema.parse({ groupBy: "agent" })).toThrow();
+ expect(() => companyArtifactsQuerySchema.parse({ groupIssueId: "PAP-1" })).toThrow();
+ });
+});
+
+describe("companyArtifactsResponseSchema", () => {
+ it("accepts grouped artifact responses with selected group metadata", () => {
+ const group = {
+ id: `task:${issue.id}`,
+ groupBy: "task",
+ issue,
+ title: issue.title,
+ count: 1,
+ mediaKinds: ["document"],
+ previewArtifacts: [artifact],
+ updatedAt: "2026-06-06T12:00:00.000Z",
+ href: `/PAP/artifacts?groupBy=task&groupIssueId=${issue.id}`,
+ };
+
+ expect(
+ companyArtifactsResponseSchema.parse({
+ artifacts: [artifact],
+ groups: [group],
+ selectedGroup: group,
+ nextCursor: null,
+ }),
+ ).toMatchObject({
+ artifacts: [artifact],
+ groups: [group],
+ selectedGroup: group,
+ nextCursor: null,
+ });
+ });
+});
diff --git a/packages/shared/src/validators/artifact.ts b/packages/shared/src/validators/artifact.ts
index 72251d413d..4d9f32b2c3 100644
--- a/packages/shared/src/validators/artifact.ts
+++ b/packages/shared/src/validators/artifact.ts
@@ -8,10 +8,14 @@ export const companyArtifactSourceSchema = z.enum(["document", "attachment", "wo
export const companyArtifactMediaKindSchema = z.enum(["image", "video", "text", "document", "file", "empty"]);
+export const companyArtifactGroupBySchema = z.enum(["none", "task", "parent_task"]);
+
export const companyArtifactsQuerySchema = z.object({
kind: z.enum(["image", "video", "text", "document", "file", "all"]).optional().default("all"),
projectId: z.string().uuid().optional(),
q: z.string().trim().max(COMPANY_ARTIFACTS_MAX_QUERY_LENGTH).optional(),
+ groupBy: companyArtifactGroupBySchema.optional().default("none"),
+ groupIssueId: z.string().uuid().optional(),
limit: z.coerce
.number()
.int()
@@ -49,8 +53,26 @@ export const companyArtifactSchema = z.object({
href: z.string().min(1),
});
+export const companyArtifactGroupSchema = z.object({
+ id: z.string().min(1),
+ groupBy: companyArtifactGroupBySchema.exclude(["none"]),
+ issue: z.object({
+ id: z.string().uuid(),
+ identifier: z.string(),
+ title: z.string(),
+ }),
+ title: z.string(),
+ count: z.number().int().min(0),
+ mediaKinds: z.array(companyArtifactMediaKindSchema),
+ previewArtifacts: z.array(companyArtifactSchema),
+ updatedAt: z.string().datetime(),
+ href: z.string().min(1),
+});
+
export const companyArtifactsResponseSchema = z.object({
artifacts: z.array(companyArtifactSchema),
+ groups: z.array(companyArtifactGroupSchema).optional(),
+ selectedGroup: companyArtifactGroupSchema.nullable().optional(),
nextCursor: z.string().nullable(),
});
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index 751c757bbd..1595a680e0 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -333,6 +333,8 @@ export {
COMPANY_ARTIFACTS_DEFAULT_LIMIT,
COMPANY_ARTIFACTS_MAX_LIMIT,
COMPANY_ARTIFACTS_MAX_QUERY_LENGTH,
+ companyArtifactGroupBySchema,
+ companyArtifactGroupSchema,
companyArtifactMediaKindSchema,
companyArtifactSchema,
companyArtifactSourceSchema,
diff --git a/server/src/__tests__/company-artifacts-service.test.ts b/server/src/__tests__/company-artifacts-service.test.ts
index 429c724b6f..174c3306d0 100644
--- a/server/src/__tests__/company-artifacts-service.test.ts
+++ b/server/src/__tests__/company-artifacts-service.test.ts
@@ -1,5 +1,6 @@
import { Readable } from "node:stream";
import express from "express";
+import { eq } from "drizzle-orm";
import request from "supertest";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
@@ -329,7 +330,7 @@ describeEmbeddedPostgres("companyArtifactsService", () => {
updatedAt: new Date("2026-01-02T12:00:00.000Z"),
});
- return { companyId, projectId, issueId, otherRunId };
+ return { companyId, otherCompanyId, projectId, issueId, secondIssueId, otherIssueId, otherRunId };
}
it("projects agent-created documents, direct attachments, and work products while excluding noisy sources", async () => {
@@ -495,6 +496,279 @@ describeEmbeddedPostgres("companyArtifactsService", () => {
expect(forged?.createdByAgent).toBeNull();
expect(result.artifacts.some((artifact) => artifact.createdByAgent?.name === "Other")).toBe(false);
});
+
+ it("does not leak foreign issue or project metadata through malformed artifact link rows", async () => {
+ const { companyId, otherCompanyId, otherIssueId } = await seedArtifacts();
+ const foreignProjectId = "1b1b1b1b-1b1b-4b1b-8b1b-1b1b1b1b1b1b";
+ const malformedAttachmentId = "1c1c1c1c-1c1c-4c1c-8c1c-1c1c1c1c1c1c";
+
+ await db.insert(projects).values({
+ id: foreignProjectId,
+ companyId: otherCompanyId,
+ name: "Foreign Project",
+ status: "in_progress",
+ });
+ await db.update(issues).set({ projectId: foreignProjectId }).where(eq(issues.id, otherIssueId));
+ await db.insert(documents).values({
+ id: "1d1d1d1d-1d1d-4d1d-8d1d-1d1d1d1d1d1d",
+ companyId,
+ title: "Forged Link Document",
+ latestBody: "This row is company-owned but points at a foreign issue.",
+ createdByAgentId: "33333333-3333-4333-8333-333333333333",
+ updatedAt: new Date("2026-01-30T00:00:00.000Z"),
+ });
+ await db.insert(issueDocuments).values({
+ companyId,
+ issueId: otherIssueId,
+ documentId: "1d1d1d1d-1d1d-4d1d-8d1d-1d1d1d1d1d1d",
+ key: "forged-link-document",
+ });
+ await db.insert(assets).values({
+ id: "1e1e1e1e-1e1e-4e1e-8e1e-1e1e1e1e1e1e",
+ companyId,
+ provider: "local_disk",
+ objectKey: "forged-link.txt",
+ contentType: "text/plain",
+ byteSize: 42,
+ sha256: "sha256-forged-link",
+ originalFilename: "forged-link.txt",
+ createdByAgentId: "33333333-3333-4333-8333-333333333333",
+ });
+ await db.insert(issueAttachments).values({
+ id: malformedAttachmentId,
+ companyId,
+ issueId: otherIssueId,
+ assetId: "1e1e1e1e-1e1e-4e1e-8e1e-1e1e1e1e1e1e",
+ updatedAt: new Date("2026-01-29T00:00:00.000Z"),
+ });
+ await db.insert(issueWorkProducts).values({
+ id: "1f1f1f1f-1f1f-4f1f-8f1f-1f1f1f1f1f1f",
+ companyId,
+ issueId: otherIssueId,
+ type: "artifact",
+ provider: "paperclip",
+ title: "Forged Link Work Product",
+ status: "ready_for_review",
+ summary: "This row is company-owned but points at a foreign issue.",
+ metadata: { contentType: "text/plain" },
+ createdByRunId: "99999999-9999-4999-8999-999999999999",
+ updatedAt: new Date("2026-01-28T00:00:00.000Z"),
+ });
+
+ const flat = await companyArtifactsService(db, createStorageService()).list(companyId, { limit: 20 });
+ expect(flat.artifacts.map((artifact) => artifact.title)).not.toEqual(expect.arrayContaining([
+ "Forged Link Document",
+ "forged-link.txt",
+ "Forged Link Work Product",
+ ]));
+ expect(flat.artifacts.some((artifact) => artifact.issue.identifier === "OTH-1")).toBe(false);
+ expect(flat.artifacts.some((artifact) => artifact.issue.title === "Other output")).toBe(false);
+ expect(flat.artifacts.some((artifact) => artifact.project?.name === "Foreign Project")).toBe(false);
+
+ const grouped = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "task",
+ limit: 20,
+ });
+ expect(grouped.groups?.some((group) => group.issue.identifier === "OTH-1")).toBe(false);
+ expect(grouped.groups?.some((group) => group.issue.title === "Other output")).toBe(false);
+ expect(grouped.groups?.some((group) =>
+ group.previewArtifacts.some((artifact) => artifact.project?.name === "Foreign Project")
+ )).toBe(false);
+
+ const selectedForeignGroup = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "task",
+ groupIssueId: otherIssueId,
+ limit: 20,
+ });
+ expect(selectedForeignGroup).toEqual({
+ artifacts: [],
+ selectedGroup: null,
+ nextCursor: null,
+ });
+ });
+
+ it("groups artifacts by task after applying media, project, and search filters", async () => {
+ const { companyId, projectId, issueId } = await seedArtifacts();
+ const storage = createStorageService({ "notes.txt": Buffer.from("Searchable notes preview") });
+
+ const grouped = await companyArtifactsService(db, storage).list(companyId, {
+ groupBy: "task",
+ limit: 10,
+ });
+ expect(grouped.artifacts).toEqual([]);
+ expect(grouped.nextCursor).toBeNull();
+ expect(grouped.groups?.map((group) => ({
+ issue: group.issue.identifier,
+ count: group.count,
+ mediaKinds: group.mediaKinds,
+ href: group.href,
+ }))).toEqual([
+ {
+ issue: "PAP-2",
+ count: 1,
+ mediaKinds: ["document"],
+ href: "/PAP/artifacts?groupBy=task&groupIssueId=77777777-7777-4777-8777-777777777777",
+ },
+ {
+ issue: "PAP-1",
+ count: 3,
+ mediaKinds: ["video", "text"],
+ href: "/PAP/artifacts?groupBy=task&groupIssueId=66666666-6666-4666-8666-666666666666",
+ },
+ ]);
+ expect(grouped.groups?.find((group) => group.issue.id === issueId)?.previewArtifacts.map((artifact) => artifact.title))
+ .toEqual(["direct-video.mp4", "Primary Cut", "notes.txt"]);
+
+ const projectVideos = await companyArtifactsService(db, storage).list(companyId, {
+ groupBy: "task",
+ projectId,
+ kind: "video",
+ limit: 10,
+ });
+ expect(projectVideos.groups?.map((group) => ({
+ issue: group.issue.identifier,
+ count: group.count,
+ href: group.href,
+ }))).toEqual([
+ {
+ issue: "PAP-1",
+ count: 2,
+ href:
+ "/PAP/artifacts?groupBy=task&groupIssueId=66666666-6666-4666-8666-666666666666&kind=video&projectId=55555555-5555-4555-8555-555555555555",
+ },
+ ]);
+
+ const search = await companyArtifactsService(db, storage).list(companyId, {
+ groupBy: "task",
+ q: "review document",
+ limit: 10,
+ });
+ expect(search.groups?.map((group) => ({ issue: group.issue.identifier, count: group.count }))).toEqual([
+ { issue: "PAP-2", count: 1 },
+ ]);
+ });
+
+ it("paginates grouped task lists with the active group cursor", async () => {
+ const { companyId } = await seedArtifacts();
+
+ const firstPage = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "task",
+ limit: 1,
+ });
+ expect(firstPage.groups?.map((group) => group.issue.identifier)).toEqual(["PAP-2"]);
+ expect(firstPage.nextCursor).toEqual(expect.any(String));
+
+ const secondPage = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "task",
+ limit: 10,
+ cursor: firstPage.nextCursor ?? undefined,
+ });
+ expect(secondPage.groups?.map((group) => group.issue.identifier)).toEqual(["PAP-1"]);
+ expect(secondPage.nextCursor).toBeNull();
+ });
+
+ it("groups parent-task artifacts under the topmost same-company ancestor", async () => {
+ const { companyId, issueId, secondIssueId } = await seedArtifacts();
+ const grandchildIssueId = "21212121-2121-4212-8121-212121212121";
+ const grandchildAttachmentId = "23232323-2323-4232-8232-232323232323";
+
+ await db.update(issues).set({ parentId: issueId }).where(eq(issues.id, secondIssueId));
+ await db.insert(issues).values({
+ id: grandchildIssueId,
+ companyId,
+ parentId: secondIssueId,
+ identifier: "PAP-3",
+ title: "Grandchild render",
+ status: "done",
+ priority: "medium",
+ });
+ await db.insert(assets).values({
+ id: "24242424-2424-4242-8242-242424242424",
+ companyId,
+ provider: "local_disk",
+ objectKey: "grandchild.txt",
+ contentType: "text/plain",
+ byteSize: 48,
+ sha256: "sha256-grandchild",
+ originalFilename: "grandchild.txt",
+ createdByAgentId: "33333333-3333-4333-8333-333333333333",
+ });
+ await db.insert(issueAttachments).values({
+ id: grandchildAttachmentId,
+ companyId,
+ issueId: grandchildIssueId,
+ assetId: "24242424-2424-4242-8242-242424242424",
+ updatedAt: new Date("2026-01-05T00:00:00.000Z"),
+ });
+
+ const grouped = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "parent_task",
+ limit: 10,
+ });
+
+ expect(grouped.artifacts).toEqual([]);
+ expect(grouped.groups?.map((group) => ({
+ issue: group.issue.identifier,
+ count: group.count,
+ previewTitles: group.previewArtifacts.map((artifact) => artifact.title),
+ }))).toEqual([
+ {
+ issue: "PAP-1",
+ count: 5,
+ previewTitles: ["grandchild.txt", "Review Notes", "direct-video.mp4"],
+ },
+ ]);
+ });
+
+ it("returns selected group artifact pages and metadata without leaking foreign group issues", async () => {
+ const { companyId, issueId, otherIssueId } = await seedArtifacts();
+
+ const selected = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "task",
+ groupIssueId: issueId,
+ limit: 2,
+ });
+ expect(selected.groups).toBeUndefined();
+ expect(selected.selectedGroup).toMatchObject({
+ id: `task:${issueId}`,
+ groupBy: "task",
+ issue: { identifier: "PAP-1" },
+ count: 3,
+ });
+ expect(selected.artifacts.map((artifact) => artifact.title)).toEqual(["direct-video.mp4", "Primary Cut"]);
+ expect(selected.nextCursor).toEqual(expect.any(String));
+
+ const selectedSecondPage = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "task",
+ groupIssueId: issueId,
+ limit: 10,
+ cursor: selected.nextCursor ?? undefined,
+ });
+ expect(selectedSecondPage.artifacts.map((artifact) => artifact.title)).toEqual(["notes.txt"]);
+
+ const selectedEmptyByFilter = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "task",
+ groupIssueId: issueId,
+ q: "does-not-match-this-stack",
+ limit: 10,
+ });
+ expect(selectedEmptyByFilter.selectedGroup).toMatchObject({
+ id: `task:${issueId}`,
+ count: 0,
+ });
+ expect(selectedEmptyByFilter.artifacts).toEqual([]);
+
+ const foreignSelected = await companyArtifactsService(db, createStorageService()).list(companyId, {
+ groupBy: "task",
+ groupIssueId: otherIssueId,
+ limit: 10,
+ });
+ expect(foreignSelected).toEqual({
+ artifacts: [],
+ selectedGroup: null,
+ nextCursor: null,
+ });
+ });
});
describe("company artifacts route authorization", () => {
diff --git a/server/src/services/company-artifacts.ts b/server/src/services/company-artifacts.ts
index 3e787dce54..aa06d102ae 100644
--- a/server/src/services/company-artifacts.ts
+++ b/server/src/services/company-artifacts.ts
@@ -1,5 +1,5 @@
import { buffer } from "node:stream/consumers";
-import { and, desc, eq, isNotNull, isNull, notInArray, or, sql, type SQL } from "drizzle-orm";
+import { and, desc, eq, inArray, isNotNull, isNull, notInArray, or, sql, type SQL } from "drizzle-orm";
import { alias } from "drizzle-orm/pg-core";
import type { Db } from "@paperclipai/db";
import {
@@ -20,6 +20,8 @@ import {
companyArtifactsQuerySchema,
SYSTEM_ISSUE_DOCUMENT_KEYS,
type CompanyArtifact,
+ type CompanyArtifactGroup,
+ type CompanyArtifactGroupBy,
type CompanyArtifactMediaKind,
type CompanyArtifactsQuery,
type CompanyArtifactsResponse,
@@ -29,12 +31,24 @@ import type { StorageService } from "../storage/types.js";
const TEXT_PREVIEW_BYTES = 4096;
const PREVIEW_TEXT_MAX_LENGTH = 280;
+const GROUP_PREVIEW_ARTIFACT_LIMIT = 3;
+const GROUPED_ARTIFACT_FETCH_LIMIT = COMPANY_ARTIFACTS_MAX_LIMIT * 10;
type ArtifactCursor = {
updatedAt: string;
id: string;
};
+type ArtifactGroupBy = Exclude<CompanyArtifactGroupBy, "none">;
+
+type IssueGroupingRow = {
+ id: string;
+ parentId: string | null;
+ identifier: string | null;
+ title: string;
+ updatedAt: Date;
+};
+
function encodeCursor(cursor: ArtifactCursor) {
return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
}
@@ -61,6 +75,12 @@ function cursorCondition(updatedAt: SQL<Date>, artifactId: SQL<string>, cursor:
return sql`(${updatedAt} < ${cursor.updatedAt}::timestamptz OR (${updatedAt} = ${cursor.updatedAt}::timestamptz AND ${artifactId} < ${cursor.id}))`;
}
+function isAfterCursor(item: { updatedAt: string; id: string }, cursor: ArtifactCursor | null) {
+ if (!cursor) return true;
+ const dateDiff = Date.parse(item.updatedAt) - Date.parse(cursor.updatedAt);
+ return dateDiff < 0 || (dateDiff === 0 && item.id < cursor.id);
+}
+
function escapeLikePattern(value: string) {
return value.replace(/[\\%_]/g, (match) => `\\${match}`);
}
@@ -116,6 +136,21 @@ function buildIssueHref(companyPrefix: string, identifier: string, anchor: strin
return `/${encodeURIComponent(companyPrefix)}/issues/${encodeURIComponent(identifier)}#${anchor}`;
}
+function buildArtifactsGroupHref(
+ companyPrefix: string,
+ query: CompanyArtifactsQuery,
+ groupBy: ArtifactGroupBy,
+ groupIssueId: string,
+) {
+ const params = new URLSearchParams();
+ params.set("groupBy", groupBy);
+ params.set("groupIssueId", groupIssueId);
+ if (query.kind !== "all") params.set("kind", query.kind);
+ if (query.projectId) params.set("projectId", query.projectId);
+ if (query.q) params.set("q", query.q);
+ return `/${encodeURIComponent(companyPrefix)}/artifacts?${params.toString()}`;
+}
+
function attachmentContentPath(attachmentId: string) {
return `/api/attachments/${attachmentId}/content`;
}
@@ -136,11 +171,154 @@ async function readTextAttachmentPreview(
}
}
+function sortArtifacts(artifacts: CompanyArtifact[]) {
+ return artifacts.sort((a, b) => {
+ const dateDiff = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
+ if (dateDiff !== 0) return dateDiff;
+ return b.id.localeCompare(a.id);
+ });
+}
+
+function pageByCursor<T extends { id: string; updatedAt: string }>(
+ items: T[],
+ limit: number,
+ cursor: ArtifactCursor | null,
+) {
+ const filtered = items.filter((item) => isAfterCursor(item, cursor));
+ const page = filtered.slice(0, limit);
+ const nextCursor = filtered.length > limit
+ ? encodeCursor({ id: page[page.length - 1]?.id ?? "", updatedAt: page[page.length - 1]?.updatedAt ?? new Date(0).toISOString() })
+ : null;
+ return { page, nextCursor };
+}
+
+async function loadIssueGroupingRows(db: Db, companyId: string, seedIssueIds: Iterable<string>) {
+ const rowsById = new Map<string, IssueGroupingRow>();
+ let pending = [...new Set(seedIssueIds)];
+
+ while (pending.length > 0) {
+ const rows = await db
+ .select({
+ id: issues.id,
+ parentId: issues.parentId,
+ identifier: issues.identifier,
+ title: issues.title,
+ updatedAt: issues.updatedAt,
+ })
+ .from(issues)
+ .where(and(eq(issues.companyId, companyId), inArray(issues.id, pending)));
+
+ const nextPending = new Set<string>();
+ for (const row of rows) {
+ rowsById.set(row.id, row);
+ if (row.parentId && !rowsById.has(row.parentId)) {
+ nextPending.add(row.parentId);
+ }
+ }
+ pending = [...nextPending];
+ }
+
+ return rowsById;
+}
+
+function getIssueSummary(issue: IssueGroupingRow) {
+ return {
+ id: issue.id,
+ identifier: issue.identifier ?? issue.id,
+ title: issue.title,
+ };
+}
+
+function resolveRootIssueId(issueId: string, issueRows: Map<string, IssueGroupingRow>) {
+ let current = issueRows.get(issueId);
+ if (!current) return issueId;
+ const seen = new Set<string>();
+ while (current.parentId && !seen.has(current.id)) {
+ seen.add(current.id);
+ const parent = issueRows.get(current.parentId);
+ if (!parent) break;
+ current = parent;
+ }
+ return current.id;
+}
+
+function resolveGroupIssueId(groupBy: ArtifactGroupBy, issueId: string, issueRows: Map<string, IssueGroupingRow>) {
+ return groupBy === "task" ? issueId : resolveRootIssueId(issueId, issueRows);
+}
+
+function emptyGroup(input: {
+ companyPrefix: string;
+ query: CompanyArtifactsQuery;
+ groupBy: ArtifactGroupBy;
+ issue: IssueGroupingRow;
+}): CompanyArtifactGroup {
+ const summary = getIssueSummary(input.issue);
+ return {
+ id: `${input.groupBy}:${input.issue.id}`,
+ groupBy: input.groupBy,
+ issue: summary,
+ title: summary.title,
+ count: 0,
+ mediaKinds: [],
+ previewArtifacts: [],
+ updatedAt: input.issue.updatedAt.toISOString(),
+ href: buildArtifactsGroupHref(input.companyPrefix, input.query, input.groupBy, input.issue.id),
+ };
+}
+
+function buildArtifactGroups(input: {
+ artifacts: CompanyArtifact[];
+ companyPrefix: string;
+ query: CompanyArtifactsQuery;
+ groupBy: ArtifactGroupBy;
+ issueRows: Map<string, IssueGroupingRow>;
+}) {
+ const groups = new Map<string, CompanyArtifactGroup>();
+
+ for (const artifact of input.artifacts) {
+ const groupIssueId = resolveGroupIssueId(input.groupBy, artifact.issue.id, input.issueRows);
+ const groupIssue = input.issueRows.get(groupIssueId) ?? {
+ id: artifact.issue.id,
+ parentId: null,
+ identifier: artifact.issue.identifier,
+ title: artifact.issue.title,
+ updatedAt: new Date(artifact.updatedAt),
+ };
+ const groupId = `${input.groupBy}:${groupIssueId}`;
+ const existing = groups.get(groupId);
+ const group = existing ?? emptyGroup({
+ companyPrefix: input.companyPrefix,
+ query: input.query,
+ groupBy: input.groupBy,
+ issue: groupIssue,
+ });
+ if (!existing) groups.set(groupId, group);
+
+ group.count += 1;
+ if (!group.mediaKinds.includes(artifact.mediaKind)) {
+ group.mediaKinds.push(artifact.mediaKind);
+ }
+ if (group.previewArtifacts.length < GROUP_PREVIEW_ARTIFACT_LIMIT) {
+ group.previewArtifacts.push(artifact);
+ }
+ if (Date.parse(artifact.updatedAt) > Date.parse(group.updatedAt)) {
+ group.updatedAt = artifact.updatedAt;
+ }
+ }
+
+ return [...groups.values()].sort((a, b) => {
+ const dateDiff = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
+ if (dateDiff !== 0) return dateDiff;
+ return b.id.localeCompare(a.id);
+ });
+}
+
export function companyArtifactsService(db: Db, storage?: StorageService) {
return {
list: async (companyId: string, rawQuery: Partial<CompanyArtifactsQuery> = {}): Promise<CompanyArtifactsResponse> => {
const query = companyArtifactsQuerySchema.parse(rawQuery);
const cursor = decodeCursor(query.cursor);
+ const groupBy = query.groupBy === "none" ? null : query.groupBy;
const company = await db
.select({ id: companies.id, issuePrefix: companies.issuePrefix })
.from(companies)
@@ -149,6 +327,7 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
if (!company) throw notFound("Company not found");
const fetchLimit = Math.min(query.limit + 1, COMPANY_ARTIFACTS_MAX_LIMIT + 1);
+ const sourceFetchLimit = groupBy ? GROUPED_ARTIFACT_FETCH_LIMIT : fetchLimit;
const q = query.q ? `%${escapeLikePattern(query.q)}%` : null;
const artifacts: CompanyArtifact[] = [];
const workProductAttachmentIds = new Set<string>();
@@ -158,12 +337,14 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
const updatedAgent = alias(agents, "document_updated_agent");
const documentArtifactId = sql<string>`concat('document:', ${documents.id})`;
const documentConditions: SQL[] = [
+ eq(issueDocuments.companyId, companyId),
eq(documents.companyId, companyId),
or(isNotNull(documents.createdByAgentId), isNotNull(documents.updatedByAgentId))!,
notInArray(issueDocuments.key, [...SYSTEM_ISSUE_DOCUMENT_KEYS]),
];
- const documentCursor = cursorCondition(sql<Date>`${documents.updatedAt}`, documentArtifactId, cursor);
+ const documentCursor = groupBy ? undefined : cursorCondition(sql<Date>`${documents.updatedAt}`, documentArtifactId, cursor);
if (documentCursor) documentConditions.push(documentCursor);
+ if (groupBy === "task" && query.groupIssueId) documentConditions.push(eq(issues.id, query.groupIssueId));
if (query.projectId) documentConditions.push(eq(issues.projectId, query.projectId));
if (q) {
documentConditions.push(sql`(
@@ -174,7 +355,7 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
)`);
}
- const documentRows = await db
+ const documentRowsQuery = db
.select({
artifactId: documentArtifactId,
documentId: documents.id,
@@ -191,14 +372,44 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
updatedAt: documents.updatedAt,
})
.from(issueDocuments)
- .innerJoin(documents, eq(issueDocuments.documentId, documents.id))
- .innerJoin(issues, eq(issueDocuments.issueId, issues.id))
- .leftJoin(projects, eq(issues.projectId, projects.id))
- .leftJoin(createdAgent, eq(documents.createdByAgentId, createdAgent.id))
- .leftJoin(updatedAgent, eq(documents.updatedByAgentId, updatedAgent.id))
+ .innerJoin(
+ documents,
+ and(
+ eq(issueDocuments.documentId, documents.id),
+ eq(documents.companyId, issueDocuments.companyId),
+ ),
+ )
+ .innerJoin(
+ issues,
+ and(
+ eq(issueDocuments.issueId, issues.id),
+ eq(issues.companyId, issueDocuments.companyId),
+ ),
+ )
+ .leftJoin(
+ projects,
+ and(
+ eq(issues.projectId, projects.id),
+ eq(projects.companyId, issues.companyId),
+ ),
+ )
+ .leftJoin(
+ createdAgent,
+ and(
+ eq(documents.createdByAgentId, createdAgent.id),
+ eq(createdAgent.companyId, documents.companyId),
+ ),
+ )
+ .leftJoin(
+ updatedAgent,
+ and(
+ eq(documents.updatedByAgentId, updatedAgent.id),
+ eq(updatedAgent.companyId, documents.companyId),
+ ),
+ )
.where(and(...documentConditions))
- .orderBy(desc(documents.updatedAt), desc(documentArtifactId))
- .limit(fetchLimit);
+ .orderBy(desc(documents.updatedAt), desc(documentArtifactId));
+ const documentRows = await documentRowsQuery.limit(sourceFetchLimit);
for (const row of documentRows) {
const identifier = row.issueIdentifier ?? row.issueId;
@@ -233,9 +444,16 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
eq(issueWorkProducts.provider, "paperclip"),
];
const workProductConditions: SQL[] = [...workProductBaseConditions];
- const workProductCursor = cursorCondition(sql<Date>`${issueWorkProducts.updatedAt}`, workProductArtifactId, cursor);
+ const workProductCursor = groupBy
+ ? undefined
+ : cursorCondition(sql<Date>`${issueWorkProducts.updatedAt}`, workProductArtifactId, cursor);
const workProductKind = contentTypeKindCondition(workProductContentType, query.kind);
if (workProductCursor) workProductConditions.push(workProductCursor);
+ if (groupBy === "task" && query.groupIssueId) {
+ const selectedIssueCondition = eq(issues.id, query.groupIssueId);
+ workProductBaseConditions.push(selectedIssueCondition);
+ workProductConditions.push(selectedIssueCondition);
+ }
if (workProductKind) {
workProductBaseConditions.push(workProductKind);
workProductConditions.push(workProductKind);
@@ -256,7 +474,7 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
workProductConditions.push(searchCondition);
}
- const workProductRows = await db
+ const workProductRowsQuery = db
.select({
artifactId: workProductArtifactId,
workProductId: issueWorkProducts.id,
@@ -273,8 +491,20 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
updatedAt: issueWorkProducts.updatedAt,
})
.from(issueWorkProducts)
- .innerJoin(issues, eq(issueWorkProducts.issueId, issues.id))
- .leftJoin(projects, eq(issues.projectId, projects.id))
+ .innerJoin(
+ issues,
+ and(
+ eq(issueWorkProducts.issueId, issues.id),
+ eq(issues.companyId, issueWorkProducts.companyId),
+ ),
+ )
+ .leftJoin(
+ projects,
+ and(
+ eq(issues.projectId, projects.id),
+ eq(projects.companyId, issueWorkProducts.companyId),
+ ),
+ )
.leftJoin(
heartbeatRuns,
and(
@@ -290,16 +520,23 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
),
)
.where(and(...workProductConditions))
- .orderBy(desc(issueWorkProducts.updatedAt), desc(workProductArtifactId))
- .limit(fetchLimit);
+ .orderBy(desc(issueWorkProducts.updatedAt), desc(workProductArtifactId));
+ const workProductRows = await workProductRowsQuery.limit(sourceFetchLimit);
const workProductAttachmentRows = await db
.select({
attachmentId: sql<string | null>`${issueWorkProducts.metadata}->>'attachmentId'`,
})
.from(issueWorkProducts)
- .innerJoin(issues, eq(issueWorkProducts.issueId, issues.id))
- .where(and(...workProductBaseConditions, sql`${issueWorkProducts.metadata}->>'attachmentId' IS NOT NULL`));
+ .innerJoin(
+ issues,
+ and(
+ eq(issueWorkProducts.issueId, issues.id),
+ eq(issues.companyId, issueWorkProducts.companyId),
+ ),
+ )
+ .where(and(...workProductBaseConditions, sql`${issueWorkProducts.metadata}->>'attachmentId' IS NOT NULL`))
+ .limit(sourceFetchLimit);
for (const row of workProductAttachmentRows) {
if (row.attachmentId) {
@@ -342,9 +579,12 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
isNull(issueAttachments.issueCommentId),
isNotNull(assets.createdByAgentId),
];
- const attachmentCursor = cursorCondition(sql<Date>`${issueAttachments.updatedAt}`, attachmentArtifactId, cursor);
+ const attachmentCursor = groupBy
+ ? undefined
+ : cursorCondition(sql<Date>`${issueAttachments.updatedAt}`, attachmentArtifactId, cursor);
const attachmentKind = contentTypeKindCondition(sql<string>`${assets.contentType}`, query.kind);
if (attachmentCursor) attachmentConditions.push(attachmentCursor);
+ if (groupBy === "task" && query.groupIssueId) attachmentConditions.push(eq(issues.id, query.groupIssueId));
if (attachmentKind) attachmentConditions.push(attachmentKind);
if (query.projectId) attachmentConditions.push(eq(issues.projectId, query.projectId));
if (q) {
@@ -355,7 +595,7 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
)`);
}
- const attachmentRows = await db
+ const attachmentRowsQuery = db
.select({
artifactId: attachmentArtifactId,
attachmentId: issueAttachments.id,
@@ -374,13 +614,37 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
updatedAt: issueAttachments.updatedAt,
})
.from(issueAttachments)
- .innerJoin(assets, eq(issueAttachments.assetId, assets.id))
- .innerJoin(issues, eq(issueAttachments.issueId, issues.id))
- .leftJoin(projects, eq(issues.projectId, projects.id))
- .leftJoin(attachmentAgent, eq(assets.createdByAgentId, attachmentAgent.id))
+ .innerJoin(
+ assets,
+ and(
+ eq(issueAttachments.assetId, assets.id),
+ eq(assets.companyId, issueAttachments.companyId),
+ ),
+ )
+ .innerJoin(
+ issues,
+ and(
+ eq(issueAttachments.issueId, issues.id),
+ eq(issues.companyId, issueAttachments.companyId),
+ ),
+ )
+ .leftJoin(
+ projects,
+ and(
+ eq(issues.projectId, projects.id),
+ eq(projects.companyId, issues.companyId),
+ ),
+ )
+ .leftJoin(
+ attachmentAgent,
+ and(
+ eq(assets.createdByAgentId, attachmentAgent.id),
+ eq(attachmentAgent.companyId, assets.companyId),
+ ),
+ )
.where(and(...attachmentConditions))
- .orderBy(desc(issueAttachments.updatedAt), desc(attachmentArtifactId))
- .limit(fetchLimit);
+ .orderBy(desc(issueAttachments.updatedAt), desc(attachmentArtifactId));
+ const attachmentRows = await attachmentRowsQuery.limit(sourceFetchLimit);
const attachmentArtifacts = await Promise.all(attachmentRows.map(async (row): Promise<CompanyArtifact | null> => {
if (workProductAttachmentIds.has(row.attachmentId)) return null;
@@ -416,18 +680,50 @@ export function companyArtifactsService(db: Db, storage?: StorageService) {
artifacts.push(...attachmentArtifacts.filter((artifact): artifact is CompanyArtifact => artifact !== null));
}
- const sorted = artifacts
- .sort((a, b) => {
- const dateDiff = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
- if (dateDiff !== 0) return dateDiff;
- return b.id.localeCompare(a.id);
- });
- const page = sorted.slice(0, query.limit);
- const nextCursor = sorted.length > query.limit
- ? encodeCursor({ id: page[page.length - 1]?.id ?? "", updatedAt: page[page.length - 1]?.updatedAt ?? new Date(0).toISOString() })
- : null;
-
- return { artifacts: page, nextCursor };
+ const sorted = sortArtifacts(artifacts);
+ if (!groupBy) {
+ const page = sorted.slice(0, query.limit);
+ const nextCursor = sorted.length > query.limit
+ ? encodeCursor({ id: page[page.length - 1]?.id ?? "", updatedAt: page[page.length - 1]?.updatedAt ?? new Date(0).toISOString() })
+ : null;
+
+ return { artifacts: page, nextCursor };
+ }
+
+ const issueSeedIds = new Set(artifacts.map((artifact) => artifact.issue.id));
+ if (query.groupIssueId) issueSeedIds.add(query.groupIssueId);
+ const issueRows = await loadIssueGroupingRows(db, companyId, issueSeedIds);
+ const groups = buildArtifactGroups({
+ artifacts: sorted,
+ companyPrefix: company.issuePrefix,
+ query,
+ groupBy,
+ issueRows,
+ });
+
+ if (query.groupIssueId) {
+ const selectedIssue = issueRows.get(query.groupIssueId);
+ if (!selectedIssue) {
+ return { artifacts: [], selectedGroup: null, nextCursor: null };
+ }
+
+ const selectedGroupIssueId = resolveGroupIssueId(groupBy, selectedIssue.id, issueRows);
+ const selectedGroup = groups.find((group) => group.issue.id === selectedGroupIssueId)
+ ?? emptyGroup({
+ companyPrefix: company.issuePrefix,
+ query,
+ groupBy,
+ issue: issueRows.get(selectedGroupIssueId) ?? selectedIssue,
+ });
+ const selectedArtifacts = sorted.filter((artifact) =>
+ resolveGroupIssueId(groupBy, artifact.issue.id, issueRows) === selectedGroupIssueId
+ );
+ const { page, nextCursor } = pageByCursor(selectedArtifacts, query.limit, cursor);
+ return { artifacts: page, selectedGroup, nextCursor };
+ }
+
+ const { page, nextCursor } = pageByCursor(groups, query.limit, cursor);
+ return { artifacts: [], groups: page, nextCursor };
},
};
}
diff --git a/ui/src/api/artifacts.test.ts b/ui/src/api/artifacts.test.ts
index fffb68b96a..89a41bb41c 100644
--- a/ui/src/api/artifacts.test.ts
+++ b/ui/src/api/artifacts.test.ts
@@ -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" });
diff --git a/ui/src/api/artifacts.ts b/ui/src/api/artifacts.ts
index 78508305a9..e0653245d3 100644
--- a/ui/src/api/artifacts.ts
+++ b/ui/src/api/artifacts.ts
@@ -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 = {
diff --git a/ui/src/components/artifacts/ArtifactCard.tsx b/ui/src/components/artifacts/ArtifactCard.tsx
index 842c0ee665..f5f6d0e70e 100644
--- a/ui/src/components/artifacts/ArtifactCard.tsx
+++ b/ui/src/components/artifacts/ArtifactCard.tsx
@@ -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} />;
diff --git a/ui/src/components/artifacts/ArtifactGroupCard.test.tsx b/ui/src/components/artifacts/ArtifactGroupCard.test.tsx
new file mode 100644
index 0000000000..fbff819316
--- /dev/null
+++ b/ui/src/components/artifacts/ArtifactGroupCard.test.tsx
@@ -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();
+ });
+});
diff --git a/ui/src/components/artifacts/ArtifactGroupCard.tsx b/ui/src/components/artifacts/ArtifactGroupCard.tsx
new file mode 100644
index 0000000000..68544f402c
--- /dev/null
+++ b/ui/src/components/artifacts/ArtifactGroupCard.tsx
@@ -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>
+ );
+}
diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts
index 91206b1f12..e98ba814b4 100644
--- a/ui/src/lib/queryKeys.ts
+++ b/ui/src/lib/queryKeys.ts
@@ -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,
diff --git a/ui/src/pages/Artifacts.test.tsx b/ui/src/pages/Artifacts.test.tsx
index eabc37bf8c..b01d66ca32 100644
--- a/ui/src/pages/Artifacts.test.tsx
+++ b/ui/src/pages/Artifacts.test.tsx
@@ -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();
+ });
+ });
});
diff --git a/ui/src/pages/Artifacts.tsx b/ui/src/pages/Artifacts.tsx
index 50e7e94425..8d09e459dc 100644
--- a/ui/src/pages/Artifacts.tsx
+++ b/ui/src/pages/Artifacts.tsx
@@ -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);
+ 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(() => {
- setBreadcrumbs([{ label: "Artifacts" }]);
- }, [setBreadcrumbs]);
+ setDraftQuery((prev) => (prev.trim() === query ? prev : query));
+ }, [query]);
+ // Debounce the search box into the `q` URL param so searches are shareable.
useEffect(() => {
- const handle = window.setTimeout(() => setQuery(draftQuery.trim()), SEARCH_DEBOUNCE_MS);
+ 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
diff --git a/ui/storybook/stories/artifacts.stories.tsx b/ui/storybook/stories/artifacts.stories.tsx
index 1336b36fbe..185781c924 100644
--- a/ui/storybook/stories/artifacts.stories.tsx
+++ b/ui/storybook/stories/artifacts.stories.tsx
@@ -1,22 +1,55 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
-import { Package } from "lucide-react";
+import { useState } from "react";
+import { ArrowLeft, Check, Layers, Package, Search, X } from "lucide-react";
import { ArtifactCard } from "@/components/artifacts/ArtifactCard";
import { EmptyState } from "@/components/EmptyState";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import { cn, formatDate } from "@/lib/utils";
import type { CompanyArtifact } from "@/api/artifacts";
+import {
+ ARTIFACT_GROUP_OPTIONS,
+ ARTIFACT_KIND_FILTERS,
+ artifactGroupByLabel,
+} from "@/pages/Artifacts";
/**
- * Storybook coverage for the company Artifacts page (PAP-10359). Renders the
- * responsive three-column grid and every preview card variant with mock data so
- * UX/QA can review the layout and capture desktop/mobile screenshots without a
- * live backend.
+ * Storybook coverage for the company Artifacts page. Covers:
+ * - the flat grid (PAP-10359)
+ * - the new group-by control, stack cards, and selected stack view (PAP-10440 / PAP-10442)
+ *
+ * Each story is renderable standalone so UX/QA can capture desktop and mobile
+ * screenshots without booting a live backend.
*/
+type StoryArtifactKindFilter = (typeof ARTIFACT_KIND_FILTERS)[number]["value"];
+type StoryArtifactGroupBy = (typeof ARTIFACT_GROUP_OPTIONS)[number]["value"];
+
const SAMPLE_IMAGE =
"data:image/svg+xml;utf8," +
encodeURIComponent(
`<svg xmlns='http://www.w3.org/2000/svg' width='480' height='270'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='#6366f1'/><stop offset='1' stop-color='#22d3ee'/></linearGradient></defs><rect width='480' height='270' fill='url(#g)'/><text x='50%' y='52%' font-family='sans-serif' font-size='28' fill='white' text-anchor='middle'>Hero render.png</text></svg>`,
);
+const SAMPLE_IMAGE_TEAL =
+ "data:image/svg+xml;utf8," +
+ encodeURIComponent(
+ `<svg xmlns='http://www.w3.org/2000/svg' width='480' height='270'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='#0ea5e9'/><stop offset='1' stop-color='#14b8a6'/></linearGradient></defs><rect width='480' height='270' fill='url(#g)'/><text x='50%' y='52%' font-family='sans-serif' font-size='24' fill='white' text-anchor='middle'>nav-revised.png</text></svg>`,
+ );
+
+const SAMPLE_IMAGE_AMBER =
+ "data:image/svg+xml;utf8," +
+ encodeURIComponent(
+ `<svg xmlns='http://www.w3.org/2000/svg' width='480' height='270'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='#f59e0b'/><stop offset='1' stop-color='#ef4444'/></linearGradient></defs><rect width='480' height='270' fill='url(#g)'/><text x='50%' y='52%' font-family='sans-serif' font-size='22' fill='white' text-anchor='middle'>hero-warm.png</text></svg>`,
+ );
+
function makeArtifact(overrides: Partial<CompanyArtifact>): CompanyArtifact {
return {
id: "art",
@@ -44,7 +77,7 @@ const ARTIFACTS: CompanyArtifact[] = [
mediaKind: "video",
title: "Product demo — primary cut.mp4",
contentType: "video/mp4",
- contentPath: null, // exercises the calm video placeholder + play glyph
+ contentPath: null,
openPath: "/files/demo.mp4",
downloadPath: "/files/demo.mp4?download=1",
issue: { id: "issue-2", identifier: "PAP-10205", title: "Record the launch walkthrough" },
@@ -96,7 +129,7 @@ const ARTIFACTS: CompanyArtifact[] = [
mediaKind: "image",
title: "missing-preview.png (broken source)",
contentType: "image/png",
- contentPath: "/files/does-not-exist.png", // exercises the onError image fallback
+ contentPath: "/files/does-not-exist.png",
openPath: "/files/does-not-exist.png",
downloadPath: "/files/does-not-exist.png?download=1",
}),
@@ -104,7 +137,7 @@ const ARTIFACTS: CompanyArtifact[] = [
function ArtifactsGrid({ artifacts }: { artifacts: CompanyArtifact[] }) {
return (
- <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
+ <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} />
))}
@@ -112,6 +145,335 @@ function ArtifactsGrid({ artifacts }: { artifacts: CompanyArtifact[] }) {
);
}
+// ---------------------------------------------------------------------------
+// Grouping mock components (PAP-10442). These mirror the production artifact
+// grouping controls so Storybook stays useful for visual review.
+// ---------------------------------------------------------------------------
+
+/**
+ * Toolbar replica matching the existing Artifacts page (search + kind filters)
+ * with the group-by icon control placed before the filter chips.
+ */
+function ArtifactsToolbar({
+ query,
+ onQueryChange,
+ kind,
+ onKindChange,
+ groupBy,
+ onGroupByChange,
+}: {
+ query: string;
+ onQueryChange: (value: string) => void;
+ kind: StoryArtifactKindFilter;
+ onKindChange: (value: StoryArtifactKindFilter) => void;
+ groupBy: StoryArtifactGroupBy;
+ onGroupByChange: (value: StoryArtifactGroupBy) => void;
+}) {
+ return (
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="relative w-full sm:max-w-sm">
+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={query}
+ onChange={(event) => onQueryChange(event.currentTarget.value)}
+ placeholder="Search artifacts..."
+ aria-label="Search artifacts"
+ className="h-9 pl-9 pr-9 text-sm"
+ />
+ {query.length > 0 ? (
+ <button
+ type="button"
+ onClick={() => onQueryChange("")}
+ aria-label="Clear artifact search"
+ className="absolute right-2 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ ) : null}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-1.5">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className={cn("h-8 w-8 shrink-0", groupBy !== "none" && "bg-accent")}
+ title="Group artifacts"
+ aria-label={`Group artifacts (currently ${artifactGroupByLabel(groupBy)})`}
+ >
+ <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(({ value, label }) => (
+ <DropdownMenuItem
+ key={value}
+ aria-selected={groupBy === value}
+ onSelect={() => onGroupByChange(value)}
+ className="justify-between"
+ >
+ {label}
+ {groupBy === 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={() => onKindChange(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>
+ );
+}
+
+interface MockGroup {
+ id: string;
+ groupBy: Exclude<StoryArtifactGroupBy, "none">;
+ issueIdentifier: string;
+ issueTitle: string;
+ count: number;
+ preview: CompanyArtifact;
+ updatedAt: string;
+ href: string;
+}
+
+/**
+ * Stack card mock for grouped views.
+ *
+ * Visual rules (matching ArtifactCard footprint):
+ * - Same border, radius (rounded-[8px]), border + bg-card surface, hover treatment.
+ * - Preview frame is the same `aspect-video` PreviewFrame as ArtifactCard.
+ * - Footer block has the same vertical rhythm.
+ * - When `count > 1`, render two stacked sibling layers behind the main card,
+ * offset by 4px / 8px on both axes, with reduced opacity. This produces a
+ * subtle "stack" without competing with the preview content.
+ * - Stack count badge sits in the top-right of the preview as a small pill.
+ * - The body line replaces the artifact title with the issue identifier and
+ * title; metadata line shows the artifact count and most-recent-edit time.
+ */
+function ArtifactStackCard({ group }: { group: MockGroup }) {
+ const isStacked = group.count > 1;
+
+ return (
+ <div className="relative">
+ {isStacked ? (
+ <>
+ <div
+ aria-hidden="true"
+ 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"
+ className="pointer-events-none absolute inset-0 translate-x-[4px] translate-y-[4px] rounded-[8px] border border-border bg-muted/70 shadow-sm"
+ />
+ </>
+ ) : null}
+
+ <a
+ href={group.href}
+ data-testid="artifact-stack-card"
+ data-stack-count={group.count}
+ className="group relative flex flex-col overflow-hidden rounded-[8px] border border-border bg-card transition-colors hover:border-foreground/20"
+ >
+ <div className="relative aspect-video w-full overflow-hidden bg-accent/20">
+ {group.preview.contentPath ? (
+ <img
+ src={group.preview.contentPath}
+ alt=""
+ className="h-full w-full object-cover"
+ />
+ ) : (
+ <div className="flex h-full w-full items-center justify-center bg-accent/15 text-muted-foreground/40">
+ <Layers className="h-8 w-8" aria-hidden="true" />
+ </div>
+ )}
+ <div 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}
+ </div>
+ </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.issueIdentifier}
+ </span>
+ <h3
+ className="min-w-0 flex-1 truncate text-sm font-medium leading-7 text-foreground/85"
+ title={group.issueTitle}
+ >
+ {group.issueTitle}
+ </h3>
+ </div>
+
+ <div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/65">
+ <span>{group.count} artifacts</span>
+ <span className="text-muted-foreground/50">·</span>
+ <span>Updated {formatDate(group.updatedAt)}</span>
+ </div>
+ </div>
+ </a>
+ </div>
+ );
+}
+
+const TASK_GROUPS: MockGroup[] = [
+ {
+ id: "task:issue-1",
+ groupBy: "task",
+ issueIdentifier: "PAP-10306",
+ issueTitle: "Landing visuals refresh",
+ count: 5,
+ preview: makeArtifact({ mediaKind: "image", contentPath: SAMPLE_IMAGE }),
+ updatedAt: new Date("2026-06-04T12:00:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-1",
+ },
+ {
+ id: "task:issue-2",
+ groupBy: "task",
+ issueIdentifier: "PAP-10205",
+ issueTitle: "Record the launch walkthrough",
+ count: 3,
+ preview: makeArtifact({ mediaKind: "video", contentPath: null }),
+ updatedAt: new Date("2026-06-03T09:30:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-2",
+ },
+ {
+ id: "task:issue-3",
+ groupBy: "task",
+ issueIdentifier: "PAP-10341",
+ issueTitle: "Draft the rollout plan",
+ count: 2,
+ preview: makeArtifact({ mediaKind: "document", contentPath: null }),
+ updatedAt: new Date("2026-06-02T18:15:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-3",
+ },
+ {
+ id: "task:issue-4",
+ groupBy: "task",
+ issueIdentifier: "PAP-10412",
+ issueTitle: "Investigate paywall regression",
+ count: 1,
+ preview: makeArtifact({ mediaKind: "image", contentPath: SAMPLE_IMAGE_AMBER }),
+ updatedAt: new Date("2026-06-02T11:00:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-4",
+ },
+ {
+ id: "task:issue-5",
+ groupBy: "task",
+ issueIdentifier: "PAP-10391",
+ issueTitle: "Iterate on nav",
+ count: 4,
+ preview: makeArtifact({ mediaKind: "image", contentPath: SAMPLE_IMAGE_TEAL }),
+ updatedAt: new Date("2026-06-01T16:42:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-5",
+ },
+ {
+ id: "task:issue-6",
+ groupBy: "task",
+ issueIdentifier: "PAP-10377",
+ issueTitle: "QA: empty states",
+ count: 1,
+ preview: makeArtifact({ mediaKind: "text", previewText: "All empty states green except onboarding-step-3." }),
+ updatedAt: new Date("2026-05-31T10:00:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=task&groupIssueId=issue-6",
+ },
+];
+
+const PARENT_TASK_GROUPS: MockGroup[] = [
+ {
+ id: "parent_task:root-1",
+ groupBy: "parent_task",
+ issueIdentifier: "PAP-10300",
+ issueTitle: "Launch readiness epic",
+ count: 14,
+ preview: makeArtifact({ mediaKind: "image", contentPath: SAMPLE_IMAGE }),
+ updatedAt: new Date("2026-06-04T12:00:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=parent_task&groupIssueId=root-1",
+ },
+ {
+ id: "parent_task:root-2",
+ groupBy: "parent_task",
+ issueIdentifier: "PAP-10200",
+ issueTitle: "Marketing site rebuild",
+ count: 9,
+ preview: makeArtifact({ mediaKind: "image", contentPath: SAMPLE_IMAGE_TEAL }),
+ updatedAt: new Date("2026-06-03T14:25:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=parent_task&groupIssueId=root-2",
+ },
+ {
+ id: "parent_task:root-3",
+ groupBy: "parent_task",
+ issueIdentifier: "PAP-10180",
+ issueTitle: "Pricing experiment",
+ count: 1,
+ preview: makeArtifact({ mediaKind: "document", previewText: "Decision log" }),
+ updatedAt: new Date("2026-05-30T08:11:00Z").toISOString(),
+ href: "/PAP/artifacts?groupBy=parent_task&groupIssueId=root-3",
+ },
+];
+
+const SELECTED_GROUP_ARTIFACTS: CompanyArtifact[] = [
+ makeArtifact({
+ id: "img-hero",
+ mediaKind: "image",
+ title: "Hero render.png",
+ contentType: "image/png",
+ contentPath: SAMPLE_IMAGE,
+ openPath: SAMPLE_IMAGE,
+ downloadPath: SAMPLE_IMAGE,
+ }),
+ makeArtifact({
+ id: "img-teal",
+ mediaKind: "image",
+ title: "nav-revised.png",
+ contentType: "image/png",
+ contentPath: SAMPLE_IMAGE_TEAL,
+ }),
+ makeArtifact({
+ id: "img-amber",
+ mediaKind: "image",
+ title: "hero-warm.png",
+ contentType: "image/png",
+ contentPath: SAMPLE_IMAGE_AMBER,
+ }),
+ makeArtifact({
+ id: "file-zip",
+ mediaKind: "file",
+ title: "design-assets.zip",
+ contentType: "application/zip",
+ openPath: "/files/design-assets.zip",
+ downloadPath: "/files/design-assets.zip?download=1",
+ }),
+ makeArtifact({
+ id: "txt-spec",
+ mediaKind: "text",
+ title: "design-spec.txt",
+ previewText:
+ "Hero retains pearl gradient. Nav collapses to icon-rail under 640px. Card radius is 8px throughout. Keep accent button consistent with /design-guide.",
+ }),
+];
+
const meta: Meta = {
title: "Pages/Artifacts",
};
@@ -120,15 +482,168 @@ export default meta;
type Story = StoryObj;
+/**
+ * Flat grid (existing behaviour) — group control is set to `None` so the
+ * toolbar shows the new icon in its inert state.
+ */
export const Grid: Story = {
- render: () => (
- <div className="mx-auto max-w-6xl space-y-4 p-6">
- <p className="text-sm text-muted-foreground">
- Work your agents have produced — documents, media, and files — across this company's issues.
- </p>
- <ArtifactsGrid artifacts={ARTIFACTS} />
- </div>
- ),
+ render: () => {
+ const [query, setQuery] = useState("");
+ const [kind, setKind] = useState<StoryArtifactKindFilter>("all");
+ const [groupBy, setGroupBy] = useState<StoryArtifactGroupBy>("none");
+ return (
+ <div className="mx-auto w-full max-w-6xl space-y-5 p-6">
+ <ArtifactsToolbar
+ query={query}
+ onQueryChange={setQuery}
+ kind={kind}
+ onKindChange={setKind}
+ groupBy={groupBy}
+ onGroupByChange={setGroupBy}
+ />
+ <ArtifactsGrid artifacts={ARTIFACTS} />
+ </div>
+ );
+ },
+};
+
+/**
+ * Grouped by Task — the production default. Every stack is one issue's
+ * artifacts. Counts > 1 show the subtle stack effect; the lone `count = 1`
+ * stacks render flat to keep the grid honest about depth.
+ */
+export const GroupedByTask: Story = {
+ render: () => {
+ const [query, setQuery] = useState("");
+ const [kind, setKind] = useState<StoryArtifactKindFilter>("all");
+ const [groupBy, setGroupBy] = useState<StoryArtifactGroupBy>("task");
+ return (
+ <div className="mx-auto w-full max-w-6xl space-y-5 p-6">
+ <ArtifactsToolbar
+ query={query}
+ onQueryChange={setQuery}
+ kind={kind}
+ onKindChange={setKind}
+ groupBy={groupBy}
+ onGroupByChange={setGroupBy}
+ />
+ <div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
+ {TASK_GROUPS.map((group) => (
+ <ArtifactStackCard key={group.id} group={group} />
+ ))}
+ </div>
+ </div>
+ );
+ },
+};
+
+/**
+ * Grouped by Parent task — stacks cluster all descendants under the root
+ * issue identifier. Same visual contract as task grouping.
+ */
+export const GroupedByParentTask: Story = {
+ render: () => {
+ const [query, setQuery] = useState("");
+ const [kind, setKind] = useState<StoryArtifactKindFilter>("all");
+ const [groupBy, setGroupBy] = useState<StoryArtifactGroupBy>("parent_task");
+ return (
+ <div className="mx-auto w-full max-w-6xl space-y-5 p-6">
+ <ArtifactsToolbar
+ query={query}
+ onQueryChange={setQuery}
+ kind={kind}
+ onKindChange={setKind}
+ groupBy={groupBy}
+ onGroupByChange={setGroupBy}
+ />
+ <div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
+ {PARENT_TASK_GROUPS.map((group) => (
+ <ArtifactStackCard key={group.id} group={group} />
+ ))}
+ </div>
+ </div>
+ );
+ },
+};
+
+/**
+ * Selected stack — drilled into a single issue's artifacts. The header row
+ * is the back affordance plus the selected-group label; media filter and
+ * search remain available and still apply within the stack.
+ */
+export const SelectedStack: Story = {
+ render: () => {
+ const [query, setQuery] = useState("");
+ const [kind, setKind] = useState<StoryArtifactKindFilter>("all");
+ const [groupBy, setGroupBy] = useState<StoryArtifactGroupBy>("task");
+ return (
+ <div className="mx-auto w-full max-w-6xl space-y-5 p-6">
+ <ArtifactsToolbar
+ query={query}
+ onQueryChange={setQuery}
+ kind={kind}
+ onKindChange={setKind}
+ groupBy={groupBy}
+ onGroupByChange={setGroupBy}
+ />
+
+ <div className="flex flex-col gap-2 border-b border-border pb-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex items-center gap-2 min-w-0">
+ <a
+ href="/PAP/artifacts?groupBy=task"
+ className="inline-flex h-7 items-center gap-1 rounded-md px-2 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
+ </a>
+ <span className="text-muted-foreground/40" aria-hidden="true">
+ /
+ </span>
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">PAP-10306</span>
+ <span className="min-w-0 truncate text-sm font-medium text-foreground/90">
+ Landing visuals refresh
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground/70">
+ <Layers className="h-3 w-3" aria-hidden="true" />
+ <span>{SELECTED_GROUP_ARTIFACTS.length} artifacts in this stack</span>
+ </div>
+ </div>
+
+ <ArtifactsGrid artifacts={SELECTED_GROUP_ARTIFACTS} />
+ </div>
+ );
+ },
+};
+
+/**
+ * Mobile — confirms the toolbar wrap (search above, group icon + kind chips
+ * below) and that stack cards keep their stack effect at single-column width.
+ */
+export const MobileGrouping: Story = {
+ parameters: { viewport: { defaultViewport: "mobile" } },
+ render: () => {
+ const [query, setQuery] = useState("");
+ const [kind, setKind] = useState<StoryArtifactKindFilter>("all");
+ const [groupBy, setGroupBy] = useState<StoryArtifactGroupBy>("task");
+ return (
+ <div className="mx-auto w-full max-w-md space-y-5 p-4">
+ <ArtifactsToolbar
+ query={query}
+ onQueryChange={setQuery}
+ kind={kind}
+ onKindChange={setKind}
+ groupBy={groupBy}
+ onGroupByChange={setGroupBy}
+ />
+ <div className="grid grid-cols-1 gap-6">
+ {TASK_GROUPS.slice(0, 3).map((group) => (
+ <ArtifactStackCard key={group.id} group={group} />
+ ))}
+ </div>
+ </div>
+ );
+ },
};
export const Empty: Story = {