Files
PaperClipAI/ui/storybook/stories/document-annotations.stories.tsx
DottaandPaperclip 87d05e194b feat(work-products): add rich cards and run artifact inventory (#12717)
## Thinking Path

> - Paperclip is the control plane for AI-agent companies.
> - Agent outputs must remain visible after a run and easy to inspect
from a task.
> - The thread and artifact inventory need one consistent rich-card
vocabulary.
> - Run uploads also need durable artifact registration and
producing-run context.
> - Reviewers need deterministic examples for each rich-card kind and
state.
> - This pull request adds the shared presentation, registration,
inventory, and Storybook review coverage.
> - The benefit is a complete output path that reviewers can inspect
without seeded data.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

This change improves work-product presentation in task threads and the
task Artifacts tab.

**Subsystem affected**

The change affects shared work-product contracts, the runner diff path,
server attachment and work-product services, GitHub metadata refresh,
the React board UI, and Storybook.

**Current behavior**

The thread used generic cards. Some files uploaded by a run existed only
as message attachments. The Artifacts tab showed a flat list without run
context or filters. Storybook showed only one resting card per kind.

**Proposed behavior**

The thread uses rich cards for supported work-product types. Each
run-produced file registers one attachment-backed artifact work product.
The Artifacts tab groups outputs by run and supports filters. Storybook
shows every kind and requested state, PR lifecycle states, stats
variants, truncation, mobile layout, and message-tail media.

**Reason and benefit**

Users can identify outputs quickly. Reviewers can inspect all card
permutations without creating task data.

**Breaking changes**

None. The metadata fields and automatic artifact registration are
additive. Existing attachments and work products keep their current
behavior.

## What Changed

- Added a shared rich work-product card with kind-specific content and a
compact inventory variant.
- Added pull-request and commit diff metadata plus bounded GitHub state
refresh.
- Added media strips and typed file chips to message-tail attachments.
- Registered each run-produced attachment as an artifact work product in
the same server transaction.
- Grouped task artifacts by run with agent and timestamp headings.
- Added type and run filters, image thumbnails, compact cards, and a
company Artifacts link.
- Added a Storybook kind-by-state matrix with stats variants for all
eight visual kinds.
- Added PR open, draft, merged, and closed examples, long-title
truncation, an exact 375-pixel viewport, and message-tail overflow
coverage.
- Closed reconciled runtime work products when the linked runtime stops
or disappears, so the card shows `Stopped` instead of `Unhealthy`.

### Screenshots

Before: one resting card per kind.

![Previous rich-card
inventory](https://pages.paperclip.ing/rich-work-product-storybook-20260902/before-inventory.png)

After: the kind and state matrix.

![Rich-card kind and state
matrix](https://pages.paperclip.ing/rich-work-product-storybook-20260902/after-kind-state-matrix.png)

After: message-tail media at 375 pixels.

![Message-tail thumbnails and typed
chips](https://pages.paperclip.ing/rich-work-product-storybook-20260902/after-message-tail.png)

[Open the Storybook evidence
viewer](https://pages.paperclip.ing/rich-work-product-storybook-20260902/).

The earlier artifact inventory comparison remains available in the
[artifact inventory
viewer](https://pages.paperclip.ing/rich-artifacts-inventory-proof-20260902/).

## Verification

- `pnpm --filter @paperclipai/ui typecheck` passed.
- `pnpm check:token-gates` passed.
- `pnpm build-storybook` passed.
- `pnpm exec vitest run
server/src/__tests__/work-product-runtime-reconciliation.test.ts` passed
with 5 tests.
- Chromium visual checks passed at desktop and 375-pixel widths.
- All 30 latest-head GitHub checks passed. One unrelated annotation test
was flaky and passed on its single retry.
- Greptile passed at 5/5 with zero unresolved threads.

## Risks

- Low risk. The Storybook change adds review fixtures only. The runtime
fix changes read-time reconciliation without database writes.
- The matrix is intentionally large so every permutation stays visible
in one review surface.

> I checked `ROADMAP.md`. This work does not duplicate planned core
work.

## Model Used

- OpenAI Codex with GPT-5 and GPT-5.6-sol across this pull request.
Reasoning, tool use, and code execution were enabled. The context-window
size is not exposed.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My public branch name describes the change and contains no
internal task id
- [x] I have run tests locally and the changed-path tests pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-09-02 15:27:54 -05:00

574 lines
20 KiB
TypeScript

import { useMemo, useRef, useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type {
Agent,
DocumentAnnotationThreadWithComments,
Issue,
IssueDocument,
} from "@paperclipai/shared";
import { DocumentAnnotationPanel } from "@/components/DocumentAnnotationPanel";
import { DocumentAnnotationLayer, type PendingAnchor } from "@/components/DocumentAnnotationLayer";
import {
DocumentAnnotationsCountChip,
IssueDocumentAnnotations,
} from "@/components/IssueDocumentAnnotations";
import { IssueDocumentsSection } from "@/components/IssueDocumentsSection";
import { MarkdownBody } from "@/components/MarkdownBody";
import { MarkdownEditor } from "@/components/MarkdownEditor";
import { queryKeys } from "@/lib/queryKeys";
import type { CompanyUserProfile } from "@/lib/company-members";
const sampleMarkdown = `# Plan: Document Highlights And Comment Threads
We should **keep** the current markdown document stack for the first version.
The existing editor is MDXEditor on top of Lexical, and the current code already uses Lexical-level customization.
## Reader And Goal
Reader: board reviewer, CTO, and implementing engineers.
## Anchor Strategy
Do not insert comment markers into markdown. The markdown document body must
remain portable and readable.
Use a sidecar anchor made from two selectors:
- Text quote selector: exact selected text plus prefix/suffix context.
- Text position selector: normalized rendered-text offsets plus markdown source offsets.
## Future Work
Phase 5 covers QA validation across desktop and mobile.`;
function makeThread(
overrides: Partial<DocumentAnnotationThreadWithComments> = {},
): DocumentAnnotationThreadWithComments {
const id = overrides.id ?? "thread-1";
return {
id,
companyId: "co-1",
issueId: "issue-1",
documentId: "doc-1",
documentKey: "plan",
status: "open",
anchorState: "active",
anchorConfidence: "exact",
originalRevisionId: "rev-4",
originalRevisionNumber: 4,
currentRevisionId: "rev-4",
currentRevisionNumber: 4,
selectedText: "keep the current markdown document stack",
prefixText: "We should ",
suffixText: " for the first version",
normalizedStart: 0,
normalizedEnd: 40,
markdownStart: 0,
markdownEnd: 40,
anchorSelector: {
quote: {
exact: "keep the current markdown document stack",
prefix: "We should ",
suffix: " for the first version",
},
position: { normalizedStart: 0, normalizedEnd: 40, markdownStart: 0, markdownEnd: 40 },
},
createdByAgentId: null,
createdByUserId: "user-1",
resolvedByAgentId: null,
resolvedByUserId: null,
resolvedAt: null,
createdAt: new Date("2026-05-12T10:00:00Z"),
updatedAt: new Date("2026-05-12T10:01:00Z"),
comments: [
{
id: "comment-1",
companyId: "co-1",
threadId: id,
issueId: "issue-1",
documentId: "doc-1",
body: "Could we benchmark the editor against a CRDT alternative before committing?",
authorType: "user",
authorAgentId: null,
authorUserId: "user-1",
createdByRunId: null,
createdAt: new Date("2026-05-12T10:00:00Z"),
updatedAt: new Date("2026-05-12T10:00:00Z"),
},
{
id: "comment-2",
companyId: "co-1",
threadId: id,
issueId: "issue-1",
documentId: "doc-1",
body: "We did a small spike — happy to share results in the plan.",
authorType: "agent",
authorAgentId: "agent-uxdesigner",
authorUserId: null,
createdByRunId: "run-1",
createdAt: new Date("2026-05-12T10:01:00Z"),
updatedAt: new Date("2026-05-12T10:01:00Z"),
},
],
...overrides,
};
}
const baseThreads: DocumentAnnotationThreadWithComments[] = [
makeThread({ id: "open-1" }),
makeThread({
id: "stale-1",
anchorState: "stale",
anchorConfidence: "fuzzy",
selectedText: "two selectors",
prefixText: "anchor made from ",
suffixText: ":",
comments: [
{
id: "comment-stale",
companyId: "co-1",
threadId: "stale-1",
issueId: "issue-1",
documentId: "doc-1",
body: "Original wording was slightly different — re-anchor when convenient.",
authorType: "user",
authorAgentId: null,
authorUserId: "user-1",
createdByRunId: null,
createdAt: new Date("2026-05-12T11:00:00Z"),
updatedAt: new Date("2026-05-12T11:00:00Z"),
},
],
}),
makeThread({
id: "resolved-1",
status: "resolved",
selectedText: "Reader: board reviewer, CTO, and implementing engineers",
comments: [
{
id: "comment-resolved",
companyId: "co-1",
threadId: "resolved-1",
issueId: "issue-1",
documentId: "doc-1",
body: "Updated reader list to add the security lead.",
authorType: "agent",
authorAgentId: "agent-uxdesigner",
authorUserId: null,
createdByRunId: "run-1",
createdAt: new Date("2026-05-12T12:00:00Z"),
updatedAt: new Date("2026-05-12T12:00:00Z"),
},
],
}),
makeThread({
id: "orphan-1",
anchorState: "orphaned",
selectedText: "an earlier paragraph that has been rewritten",
comments: [
{
id: "comment-orphan",
companyId: "co-1",
threadId: "orphan-1",
issueId: "issue-1",
documentId: "doc-1",
body: "This anchor lost its location after the rewrite. Original quote preserved.",
authorType: "user",
authorAgentId: null,
authorUserId: "user-1",
createdByRunId: null,
createdAt: new Date("2026-05-12T13:00:00Z"),
updatedAt: new Date("2026-05-12T13:00:00Z"),
},
],
}),
];
const integratedAgentMap: ReadonlyMap<string, Pick<Agent, "id" | "name">> = new Map([
["agent-uxdesigner", { id: "agent-uxdesigner", name: "UXDesigner" }],
]);
const integratedUserProfileMap: ReadonlyMap<string, CompanyUserProfile> = new Map([
["user-1", { label: "Dotta", image: null }],
]);
function makeClient() {
return new QueryClient({
defaultOptions: {
queries: { retry: false, staleTime: Number.POSITIVE_INFINITY },
mutations: { retry: false },
},
});
}
const integratedIssueId = "issue-storybook-1";
const integratedDoc: IssueDocument = {
id: "doc-storybook-1",
companyId: "co-1",
issueId: integratedIssueId,
key: "plan",
title: "Plan",
format: "markdown",
body: sampleMarkdown,
latestRevisionId: "rev-4",
latestRevisionNumber: 4,
createdByAgentId: null,
createdByUserId: "user-1",
updatedByAgentId: null,
updatedByUserId: "user-1",
lockedAt: null,
lockedByAgentId: null,
lockedByUserId: null,
createdAt: new Date("2026-05-12T09:00:00Z"),
updatedAt: new Date("2026-05-12T10:01:00Z"),
};
function makeIntegratedIssue(): Issue {
return {
id: integratedIssueId,
companyId: "co-1",
projectId: null,
projectWorkspaceId: null,
goalId: null,
parentId: null,
title: "Highlighting and comments on documents",
description: null,
status: "in_progress",
workMode: "standard",
priority: "medium",
reviewPolicy: null,
assigneeAgentId: null,
assigneeUserId: null,
responsibleUserId: null,
checkoutRunId: null,
executionRunId: null,
executionAgentNameKey: null,
executionLockedAt: null,
createdByAgentId: null,
createdByUserId: "user-1",
issueNumber: 9402,
identifier: "PAP-9402",
requestDepth: 0,
billingCode: null,
assigneeAdapterOverrides: null,
executionWorkspaceId: null,
executionWorkspacePreference: null,
executionWorkspaceSettings: null,
startedAt: null,
completedAt: null,
cancelledAt: null,
hiddenAt: null,
documentSummaries: [
{
id: integratedDoc.id,
companyId: integratedDoc.companyId,
issueId: integratedIssueId,
key: integratedDoc.key,
title: integratedDoc.title,
format: integratedDoc.format,
latestRevisionId: integratedDoc.latestRevisionId,
latestRevisionNumber: integratedDoc.latestRevisionNumber,
createdByAgentId: null,
createdByUserId: "user-1",
updatedByAgentId: null,
updatedByUserId: "user-1",
lockedAt: integratedDoc.lockedAt,
lockedByAgentId: integratedDoc.lockedByAgentId,
lockedByUserId: integratedDoc.lockedByUserId,
createdAt: integratedDoc.createdAt,
updatedAt: integratedDoc.updatedAt,
},
],
legacyPlanDocument: null,
planDocument: integratedDoc,
createdAt: new Date("2026-05-10T00:00:00Z"),
updatedAt: new Date("2026-05-12T10:01:00Z"),
};
}
/**
* Storybook fetch stub for the integrated stories. The annotation surface is
* driven by prefilled React Query data, but MarkdownEditor in edit mode can
* fire an autosave PUT on first onChange. Without this stub the cell would
* render a "Request failed: 404" string from the section's error state — which
* defeats the purpose of the integrated capture.
*/
function useIntegratedFetchStub(issueId: string, doc: IssueDocument) {
// Install once per mount; the cleanup restores the previous fetch.
// The preview's global fetch fixture is still in place — we only intercept
// the document mutation URL pattern for this issue.
useMemo(() => {
if (typeof window === "undefined") return;
const upsertUrlPath = `/api/issues/${issueId}/documents/${doc.key}`;
const original = window.fetch.bind(window);
const wrapped: typeof window.fetch = async (input, init) => {
const rawUrl = typeof input === "string"
? input
: input instanceof URL
? input.href
: input.url;
const method = (init?.method ?? (typeof input === "object" && "method" in input ? (input as Request).method : "GET")).toUpperCase();
const url = new URL(rawUrl, window.location.origin);
if (url.pathname === upsertUrlPath && (method === "PUT" || method === "GET")) {
return Response.json({ ...doc, latestRevisionNumber: doc.latestRevisionNumber + 1 });
}
return original(input, init);
};
window.fetch = wrapped;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [issueId, doc.key]);
}
function IntegratedSurface({
threads = baseThreads,
focusedThreadId = "open-1",
initialPanelOpen = true,
beginEditOnMount = false,
}: {
threads?: DocumentAnnotationThreadWithComments[];
focusedThreadId?: string | null;
initialPanelOpen?: boolean;
beginEditOnMount?: boolean;
}) {
const issue = useMemo(makeIntegratedIssue, []);
useIntegratedFetchStub(issue.id, integratedDoc);
const queryClient = useMemo(() => {
const client = makeClient();
// Prefill documents + annotations cache so React Query renders without hitting the network.
client.setQueryData(queryKeys.issues.documents(issue.id), [integratedDoc]);
client.setQueryData(
queryKeys.issues.documentAnnotations(issue.id, integratedDoc.key, "all"),
threads,
);
return client;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [issue.id]);
const panelKeys = initialPanelOpen ? [integratedDoc.key] : [];
const focusedThreadIds = focusedThreadId ? { [integratedDoc.key]: focusedThreadId } : undefined;
const editKey = beginEditOnMount ? integratedDoc.key : null;
return (
<QueryClientProvider client={queryClient}>
<div className="paperclip-doc-annotation-integrated mx-auto max-w-[1320px] p-4">
<div className="rounded-lg border border-border bg-background p-4">
<IssueDocumentsSection
issue={issue}
canDeleteDocuments={false}
agentMap={integratedAgentMap}
userProfileMap={integratedUserProfileMap}
defaultAnnotationPanelOpenKeys={panelKeys}
defaultAnnotationFocusedThreadIds={focusedThreadIds}
forceEditDocumentKey={editKey}
/>
</div>
</div>
</QueryClientProvider>
);
}
function DirtyDraftWithIntegratedHeader() {
const issue = useMemo(makeIntegratedIssue, []);
useIntegratedFetchStub(issue.id, integratedDoc);
const queryClient = useMemo(() => {
const client = makeClient();
client.setQueryData(queryKeys.issues.documents(issue.id), [integratedDoc]);
client.setQueryData(
queryKeys.issues.documentAnnotations(issue.id, integratedDoc.key, "all"),
baseThreads,
);
return client;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [issue.id]);
const [panelOpen, setPanelOpen] = useState(true);
const [draftBody, setDraftBody] = useState(`${sampleMarkdown}\n\nA work-in-progress edit that is unsaved.`);
return (
<QueryClientProvider client={queryClient}>
<div className="paperclip-doc-annotation-integrated mx-auto max-w-[1320px] p-4">
<div className="rounded-lg border border-border bg-background p-4">
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-2 min-w-0">
<h3 className="w-full text-sm font-medium text-muted-foreground shrink-0 sm:w-auto">Documents</h3>
</div>
<div className="rounded-lg border border-border p-3">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2 min-w-0">
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground">▾</span>
<span className="shrink-0 rounded-full border border-border px-2 py-0.5 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
plan
</span>
<span className="text-[11px] text-muted-foreground">rev 4 ▾</span>
<span className="truncate text-[11px] text-muted-foreground">updated 2h ago</span>
<DocumentAnnotationsCountChip
issueId={issue.id}
docKey={integratedDoc.key}
panelOpen={panelOpen}
onToggle={() => setPanelOpen((current) => !current)}
/>
</div>
</div>
</div>
<div className="mt-3 space-y-3">
<IssueDocumentAnnotations
issueId={issue.id}
doc={integratedDoc}
bodyMarkdown={draftBody}
draftDirty
draftConflicted={false}
historicalPreview={false}
locationHash=""
panelOpen={panelOpen}
onPanelOpenChange={setPanelOpen}
agentMap={integratedAgentMap}
userProfileMap={integratedUserProfileMap}
defaultFocusedThreadId="open-1"
>
<MarkdownEditor
value={draftBody}
onChange={(body) => setDraftBody(body)}
placeholder="Markdown body"
bordered={false}
className="bg-transparent"
contentClassName="paperclip-edit-in-place-content min-h-[220px] text-[15px] leading-7"
/>
</IssueDocumentAnnotations>
<div className="flex min-h-4 items-center justify-end px-1">
<span className="text-[11px] text-amber-300">Autosaving…</span>
</div>
</div>
</div>
</div>
</div>
</div>
</QueryClientProvider>
);
}
function StatesShowcase({ focusedThreadId = "open-1" }: { focusedThreadId?: string }) {
const queryClient = useMemo(() => makeClient(), []);
const bodyRef = useRef<HTMLElement | null>(null);
const [pendingAnchor, setPendingAnchor] = useState<PendingAnchor | null>(null);
const [focused, setFocused] = useState<string | null>(focusedThreadId);
return (
<QueryClientProvider client={queryClient}>
<div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_360px]">
<div className="relative rounded-lg border border-border bg-card p-4">
<section
ref={(element) => {
bodyRef.current = element;
}}
className="relative"
>
<MarkdownBody className="text-[15px] leading-7">{sampleMarkdown}</MarkdownBody>
<DocumentAnnotationLayer
containerRef={bodyRef}
markdown={sampleMarkdown}
threads={baseThreads.map((thread) => ({
id: thread.id,
selectedText: thread.selectedText,
status: thread.status,
anchorState: thread.anchorState,
}))}
focusedThreadId={focused}
onThreadFocus={(id) => setFocused(id)}
pendingAnchor={pendingAnchor}
onPendingAnchorChange={setPendingAnchor}
onRequestComment={() => {}}
hideResolved={false}
/>
</section>
</div>
<DocumentAnnotationPanel
open
onOpenChange={() => {}}
issueId="issue-1"
documentKey="plan"
documentRevisionNumber={4}
baseRevisionId="rev-4"
baseRevisionNumber={4}
threads={baseThreads}
focusedThreadId={focused}
focusedCommentId={null}
onFocusThread={(id) => setFocused(id)}
pendingAnchor={null}
onClearPendingAnchor={() => setPendingAnchor(null)}
agentMap={integratedAgentMap}
userProfileMap={integratedUserProfileMap}
/>
</div>
</QueryClientProvider>
);
}
const meta = {
title: "Product/Documents/Annotations",
component: StatesShowcase,
parameters: {
docs: {
description: {
component:
"Document annotation surface for issue documents. Stories under 'Integrated' render the real IssueDocumentsSection chrome (count chip in header, panel + body in their actual layout). Stories under 'States' isolate the panel/layer for unit-level visual debugging.",
},
},
},
} satisfies Meta<typeof StatesShowcase>;
export default meta;
type Story = StoryObj<typeof meta>;
// ---------------------------------------------------------------------------
// Integrated stories — render IssueDocumentsSection with all chrome.
// These are the captures the UX gate requires.
// ---------------------------------------------------------------------------
export const IntegratedDesktopOpen: Story = {
globals: { viewport: { value: "100pct-100pct" } },
render: () => <IntegratedSurface focusedThreadId="open-1" initialPanelOpen />,
};
export const IntegratedDesktopZeroComments: Story = {
globals: { viewport: { value: "100pct-100pct" } },
render: () => <IntegratedSurface threads={[]} initialPanelOpen={false} focusedThreadId={null} />,
};
export const IntegratedDesktopEditMode: Story = {
globals: { viewport: { value: "100pct-100pct" } },
render: () => (
<IntegratedSurface focusedThreadId="open-1" initialPanelOpen beginEditOnMount />
),
};
export const IntegratedDesktopDirtyDraft: Story = {
globals: { viewport: { value: "100pct-100pct" } },
render: () => <DirtyDraftWithIntegratedHeader />,
};
export const IntegratedMobileBottomSheet: Story = {
globals: { viewport: { value: "mobile1" } },
render: () => <IntegratedSurface focusedThreadId="open-1" initialPanelOpen />,
};
// ---------------------------------------------------------------------------
// Isolated state stories (kept for unit-level visual debugging).
// ---------------------------------------------------------------------------
export const DesktopOpenFocused: Story = {
render: () => <StatesShowcase focusedThreadId="open-1" />,
};
export const DesktopResolvedFocused: Story = {
render: () => <StatesShowcase focusedThreadId="resolved-1" />,
};
export const DesktopStaleFocused: Story = {
render: () => <StatesShowcase focusedThreadId="stale-1" />,
};
export const DesktopOrphanedFocused: Story = {
render: () => <StatesShowcase focusedThreadId="orphan-1" />,
};