Files
PaperClipAI/ui/src/components/PipelineItemBodyDocument.tsx
T
1ef3b08714 feat(ui): integrate agent personas across the app (#13171)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A stable agent persona is useful only when the same identity appears
across the app.
> - Lists, task messages, selectors, and activity feeds need inexpensive
static avatars.
> - Onboarding and agent headers need a larger character with
expressions and pointer tracking.
> - This pull request connects the persona foundation to those existing
views and preserves onboarding draft assignments.
> - Full-page stories and Linux checks make the placements and
performance contract reviewable.

## Linked Issues or Issue Description

**Problem or motivation**

Agents need a stable visual identity in lists, tasks, onboarding, and
configuration. External tools also need an image URL for that identity.

**Proposed solution**

Assign each agent a permanent palette from a fixed ClipLab character
library. Store the assignment on the agent. Render and cache preset PNG
URLs on demand. Use static images in dense views and one animated
character in larger placements.

**Alternatives considered**

A generated image bundle requires a separate asset build. A live
renderer in every avatar adds unnecessary work in large lists. Arbitrary
uploaded images do not provide the requested shared character system.

**Roadmap alignment**

This improves agent identity across existing control-plane views. It
preserves agent permissions, company boundaries, and status labels.
ROADMAP.md has no separate ClipLab persona milestone.

Related approaches: #2422 adds configurable image URLs and DiceBear
generation; #5578 adds optional uploaded avatars. This work uses a
fixed, versioned character library and preset URLs.

## What Changed

- Replace agent icons with static persona images across lists, the
sidebar, org charts, tasks, comments, selectors, activity, and dashboard
views.
- Put one animated character in the agent header. Let it follow the
pointer across the page, with reduced-motion and touch fallbacks.
- Add larger padded characters to agent creation. Keep the palette
stable across draft refreshes and connection retries, then reveal it
after success.
- Pass appearance through shared projections rather than fetching each
agent separately.
- Add real full-page Storybook examples for the agent list, overview,
task, dashboard, new-agent dialog, and connection page.
- Add Linux screenshot, clipping, density, and 500-avatar performance
checks.

## Verification

- `pnpm -r typecheck`, `pnpm build`, and token gates pass on the rebased
tree. Persona lifecycle tests pass.
- The rebased feature passes 38 Linux screenshot/performance checks,
including both display densities, corner pointer positions, and the
no-WebGL/no-live-download contract for 500 avatars.
- The final Linux persona suite passes all 38 visual, lifecycle,
density, and full-page checks using the standard Storybook configuration
and real on-demand avatar endpoint.
- Final local focused verification: 45 avatar/native-recovery tests
pass; UI identity/routine tests, typecheck/build, token gates, and
Storybook build pass.
- Current-head CI passes: full workspace/server tests, all serialized
server groups, typecheck/release checks, build, canary validation, and
end-to-end shards. The build passed after retrying a native-runner
concurrency-test failure; its three targeted cases also pass locally.
- Manual inspection covered stable identities in the app, header
placement, full-page mouse tracking, onboarding size, and task/dashboard
placements.


### Screenshots

Linux captures use synthetic Storybook fixtures. Full-page captures use
reduced motion. The live character, mouse tracking, and disposal are
checked separately.

<details>
<summary>Agent overview with the character in its header</summary>

<img
src="https://raw.githubusercontent.com/paperclipai/paperclip/8c68f42b268ada22b67d79d0fe1bb0a2f84ec25c/screenshots/full-page-agent-overview.png"
width="900" alt="Agent overview with the character in its header" />

</details>
<details>
<summary>Task messages and assignee identity</summary>

<img
src="https://raw.githubusercontent.com/paperclipai/paperclip/8c68f42b268ada22b67d79d0fe1bb0a2f84ec25c/screenshots/full-page-task.png"
width="900" alt="Task messages and assignee identity" />

</details>
<details>
<summary>Larger onboarding character with room for expressions</summary>

<img
src="https://raw.githubusercontent.com/paperclipai/paperclip/8c68f42b268ada22b67d79d0fe1bb0a2f84ec25c/screenshots/full-page-meet-your-next-agent.png"
width="900" alt="Larger onboarding character with room for expressions"
/>

</details>
<details>
<summary>Dashboard agent activity</summary>

<img
src="https://raw.githubusercontent.com/paperclipai/paperclip/8c68f42b268ada22b67d79d0fe1bb0a2f84ec25c/screenshots/full-page-company-dashboard.png"
width="900" alt="Dashboard agent activity" />

</details>

## Risks

- This PR depends on #13170, the persona foundation. Merge the
foundation first, then retarget this PR to master.
- Many placements change from icons to character silhouettes. Human
avatars and authoritative agent status labels retain their existing
behavior.
- Only one character can render live per view. Reduced motion,
hidden/offscreen content, touch input, and renderer failures use the
defined fallbacks.
- The full-page stories use fixture data. They do not contact a real
company or complete real provider sign-in.

## Model Used

OpenAI Codex, GPT-6 family. The exact model identifier and context
window are not exposed in this session. Used code editing, shell
execution, browser inspection, and Linux visual testing.

## 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 branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they 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 any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Tonio <tonework@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-19 07:57:53 -05:00

460 lines
18 KiB
TypeScript

import { useCallback, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
PIPELINE_CASE_BODY_DOCUMENT_KEY,
type Agent,
type Issue,
type PipelineCaseDocumentPayload,
} from "@paperclipai/shared";
import { FilePenLine, FileText, Loader2 } from "lucide-react";
import { ApiError } from "../api/client";
import { issuesApi } from "../api/issues";
import { pipelinesApi } from "../api/pipelines";
import type { CompanyUserProfile } from "../lib/company-members";
import { queryKeys } from "../lib/queryKeys";
import { useToastActions } from "../context/ToastContext";
import { DocumentAnnotationLayer, type PendingAnchor } from "./DocumentAnnotationLayer";
import { DocumentFrameHeader, type DocumentFrameHeaderRevisionActor } from "./DocumentFrameHeader";
import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "./IssueDocumentAnnotations";
import { EmptyState } from "./EmptyState";
import { FoldCurtain } from "./FoldCurtain";
import { MarkdownBody } from "./MarkdownBody";
import { MarkdownEditor, type MentionOption } from "./MarkdownEditor";
import { Button } from "@/components/ui/button";
/** Case-level body document key (PUT /cases/:id/documents/body). */
const BODY_DOCUMENT_KEY = "body";
/** Local view of the shared case document payload `document` field. */
type CaseBodyDocument = PipelineCaseDocumentPayload["document"] & {
latestBody?: string | null;
updatedAt?: string | Date | null;
updatedByAgentId?: string | null;
updatedByUserId?: string | null;
createdByAgentId?: string | null;
createdByUserId?: string | null;
};
function getPipelineRevisionActor(
revision: { createdByAgentId?: string | null; createdByUserId?: string | null },
maps: {
agentMap?: ReadonlyMap<string, Pick<Agent, "id" | "name"> & Partial<Pick<Agent, "icon" | "appearance">>>;
userProfileMap?: ReadonlyMap<string, CompanyUserProfile>;
},
): DocumentFrameHeaderRevisionActor {
if (revision.createdByAgentId) {
const agent = maps.agentMap?.get(revision.createdByAgentId);
return {
kind: "agent",
name: agent?.name ?? revision.createdByAgentId.slice(0, 8),
agentIcon: agent?.icon ?? null,
agent: agent ?? { id: revision.createdByAgentId },
};
}
if (revision.createdByUserId) {
const profile = maps.userProfileMap?.get(revision.createdByUserId);
return {
kind: "user",
name: profile?.label ?? (revision.createdByUserId === "local-board" ? "Board" : revision.createdByUserId.slice(0, 8)),
imageUrl: profile?.image ?? null,
};
}
return { kind: "system", name: "System" };
}
function isNotFound(error: unknown) {
return error instanceof ApiError && error.status === 404;
}
export interface PipelineItemBodyDocumentProps {
caseId: string;
/** Legacy `case.summary` shown read-only until the first edit migrates it. */
legacySummary: string | null;
/** True when the item still has legacy long fields rendered elsewhere. */
hasLegacyLongFields: boolean;
/** Active conversation issue the body document is/should be anchored to. */
conversationIssueId: string | null;
conversationIssue: Issue | null;
agentMap?: ReadonlyMap<string, Pick<Agent, "id" | "name"> & Partial<Pick<Agent, "icon" | "appearance">>>;
userProfileMap?: ReadonlyMap<string, CompanyUserProfile>;
mentions?: MentionOption[];
imageUploadHandler?: (file: File) => Promise<string>;
locationHash: string;
/** Create (or reuse) the conversation issue. Returns the issue so we can link the body. */
onStartConversation: () => Promise<Issue | null>;
/** Invalidate parent-owned queries (case detail, events, conversation) after a change. */
onAfterChange?: () => void | Promise<void>;
}
export function PipelineItemBodyDocument({
caseId,
legacySummary,
hasLegacyLongFields,
conversationIssueId,
conversationIssue,
agentMap,
userProfileMap,
mentions,
imageUploadHandler,
locationHash,
onStartConversation,
onAfterChange,
}: PipelineItemBodyDocumentProps) {
const queryClient = useQueryClient();
const { pushToast } = useToastActions();
const [folded, setFolded] = useState(false);
const [editing, setEditing] = useState(false);
const [draftBody, setDraftBody] = useState("");
const [selectedRevisionId, setSelectedRevisionId] = useState<string | null>(null);
const [revisionMenuOpen, setRevisionMenuOpen] = useState(false);
const [panelOpen, setPanelOpen] = useState(false);
const [selectionAnchor, setSelectionAnchor] = useState<PendingAnchor | null>(null);
const [pendingStartAnchor, setPendingStartAnchor] = useState<PendingAnchor | null>(null);
const containerRef = useRef<HTMLElement | null>(null);
const caseDocumentQuery = useQuery({
queryKey: queryKeys.pipelines.caseDocument(caseId, BODY_DOCUMENT_KEY),
queryFn: async () => {
try {
return await pipelinesApi.getCaseDocument(caseId, BODY_DOCUMENT_KEY);
} catch (error) {
if (isNotFound(error)) return null;
throw error;
}
},
staleTime: 15_000,
});
const payload = caseDocumentQuery.data ?? null;
const doc = (payload?.document ?? null) as CaseBodyDocument | null;
const hasDocument = Boolean(doc && doc.latestRevisionId);
const latestBody = doc?.latestBody ?? payload?.revision?.body ?? "";
// The body document is mirrored onto the conversation issue under the system key once
// it is saved while a conversation is active. Annotations bind to that issue document.
const conversationDocumentsQuery = useQuery({
queryKey: conversationIssueId
? queryKeys.issues.documents(conversationIssueId)
: ["pipeline-item-body", caseId, "no-conversation-documents"],
queryFn: () => issuesApi.listDocuments(conversationIssueId!, { includeSystem: true }),
enabled: Boolean(conversationIssueId),
staleTime: 15_000,
});
const bodyIssueDocument = useMemo(
() => conversationDocumentsQuery.data?.find((document) => document.key === PIPELINE_CASE_BODY_DOCUMENT_KEY) ?? null,
[conversationDocumentsQuery.data],
);
const annotationsLinked = Boolean(conversationIssueId && bodyIssueDocument?.latestRevisionId);
const revisionsQuery = useQuery({
queryKey: queryKeys.pipelines.caseDocumentRevisions(caseId, BODY_DOCUMENT_KEY),
queryFn: () => pipelinesApi.listCaseDocumentRevisions(caseId, BODY_DOCUMENT_KEY),
enabled: revisionMenuOpen && hasDocument,
staleTime: 10_000,
});
const revisions = revisionsQuery.data ?? [];
const selectedHistoricalRevision = selectedRevisionId
? revisions.find((revision) => revision.id === selectedRevisionId) ?? null
: null;
const isHistoricalPreview = Boolean(selectedHistoricalRevision);
const displayedBody = isHistoricalPreview
? selectedHistoricalRevision!.body
: editing
? draftBody
: latestBody;
const displayedRevisionNumber = selectedHistoricalRevision?.revisionNumber ?? doc?.latestRevisionNumber ?? 1;
const invalidateAll = useCallback(async () => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: queryKeys.pipelines.caseDocument(caseId, BODY_DOCUMENT_KEY) }),
queryClient.invalidateQueries({ queryKey: queryKeys.pipelines.caseDocumentRevisions(caseId, BODY_DOCUMENT_KEY) }),
conversationIssueId
? queryClient.invalidateQueries({ queryKey: queryKeys.issues.documents(conversationIssueId) })
: Promise.resolve(),
conversationIssueId
? queryClient.invalidateQueries({
queryKey: queryKeys.issues.documentAnnotations(conversationIssueId, PIPELINE_CASE_BODY_DOCUMENT_KEY, "all"),
})
: Promise.resolve(),
]);
await onAfterChange?.();
}, [caseId, conversationIssueId, onAfterChange, queryClient]);
const saveMutation = useMutation({
mutationFn: (input: { body: string; baseRevisionId: string | null; changeSummary?: string | null }) =>
pipelinesApi.upsertCaseDocument(caseId, BODY_DOCUMENT_KEY, {
body: input.body,
baseRevisionId: input.baseRevisionId,
changeSummary: input.changeSummary ?? null,
}),
onSuccess: async () => {
await invalidateAll();
},
});
const restoreMutation = useMutation({
mutationFn: (revisionId: string) => pipelinesApi.restoreCaseDocumentRevision(caseId, BODY_DOCUMENT_KEY, revisionId),
onSuccess: async () => {
setSelectedRevisionId(null);
await invalidateAll();
pushToast({ title: "Revision restored", tone: "success" });
},
onError: () => pushToast({ title: "Could not restore the revision", tone: "error" }),
});
const beginEdit = useCallback(() => {
setSelectedRevisionId(null);
setDraftBody(latestBody || legacySummary || "");
setEditing(true);
}, [latestBody, legacySummary]);
const cancelEdit = useCallback(() => {
setEditing(false);
setDraftBody("");
}, []);
const handleSave = useCallback(async () => {
try {
await saveMutation.mutateAsync({
body: draftBody,
baseRevisionId: doc?.latestRevisionId ?? null,
});
setEditing(false);
setDraftBody("");
} catch (error) {
if (error instanceof ApiError && error.status === 409) {
await caseDocumentQuery.refetch();
pushToast({
title: "Body changed elsewhere",
body: "This item body was updated by someone else. Reloaded the latest — re-apply your edit.",
tone: "error",
});
return;
}
pushToast({ title: "Could not save the body", tone: "error" });
}
}, [caseDocumentQuery, doc?.latestRevisionId, draftBody, pushToast, saveMutation]);
// Selection → comment when the body is not yet anchored to a conversation. Snapshot the
// anchor, ensure a conversation exists, mirror the body onto it, then hand the anchor to
// IssueDocumentAnnotations which re-opens the composer once the link lands.
const handleStartConversationFromAnchor = useCallback(
async (anchor: PendingAnchor) => {
setPendingStartAnchor(anchor);
setSelectionAnchor(null);
try {
if (!conversationIssueId) {
const issue = await onStartConversation();
if (!issue) {
setPendingStartAnchor(null);
return;
}
}
// Re-save the unchanged body so the server links it onto the conversation issue.
if (doc?.latestRevisionId) {
await saveMutation.mutateAsync({
body: latestBody,
baseRevisionId: doc.latestRevisionId,
changeSummary: "Linked body to conversation for comments",
});
}
setPanelOpen(true);
} catch {
setPendingStartAnchor(null);
pushToast({ title: "Could not start the conversation", tone: "error" });
}
},
[conversationIssueId, doc?.latestRevisionId, latestBody, onStartConversation, pushToast, saveMutation],
);
const bodyContentClassName = "paperclip-edit-in-place-content min-h-(--sz-220px) text-sm leading-7";
const renderReadOnlyBody = (body: string) => (
<FoldCurtain className="max-w-3xl">
<MarkdownBody className={bodyContentClassName} softBreaks={false}>{body}</MarkdownBody>
</FoldCurtain>
);
// ── Body content (edit / preview / read) ──────────────────────────────────────────────
let bodyContent: React.ReactNode;
if (editing) {
bodyContent = (
<div
onKeyDown={(event) => {
if (event.key === "Escape") {
event.preventDefault();
cancelEdit();
}
}}
>
<div className="rounded-md border border-border bg-background">
<MarkdownEditor
value={draftBody}
onChange={setDraftBody}
placeholder="Write the item body in Markdown…"
bordered={false}
className="min-h-(--sz-220px) bg-transparent"
contentClassName={bodyContentClassName}
mentions={mentions}
imageUploadHandler={imageUploadHandler}
onSubmit={() => void handleSave()}
/>
</div>
<div className="mt-2 flex flex-wrap items-center justify-between gap-2">
<span className="text-(length:--text-micro) text-muted-foreground">
Saving creates rev {(doc?.latestRevisionNumber ?? 0) + 1} · ⌘↵ to save · Esc to cancel
</span>
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" onClick={cancelEdit} disabled={saveMutation.isPending}>
Cancel
</Button>
<Button size="sm" onClick={() => void handleSave()} disabled={saveMutation.isPending}>
{saveMutation.isPending ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : null}
{saveMutation.isPending ? "Saving…" : "Save"}
</Button>
</div>
</div>
</div>
);
} else if (isHistoricalPreview && selectedHistoricalRevision) {
bodyContent = (
<div className="space-y-3">
<div className="rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-3">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="space-y-1">
<p className="text-sm font-medium text-amber-800 dark:text-amber-200">
Viewing revision {selectedHistoricalRevision.revisionNumber}
</p>
<p className="text-xs text-muted-foreground">
Historical preview. New comments are disabled while previewing a historical revision. Restoring it
creates a new latest revision and keeps history append-only.
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" size="sm" onClick={() => setSelectedRevisionId(null)}>
Return to latest
</Button>
<Button
size="sm"
onClick={() => restoreMutation.mutate(selectedHistoricalRevision.id)}
disabled={restoreMutation.isPending}
>
{restoreMutation.isPending ? "Restoring…" : "Restore this revision"}
</Button>
</div>
</div>
</div>
{renderReadOnlyBody(displayedBody)}
</div>
);
} else if (!hasDocument && legacySummary) {
// Legacy fallback (B): read-only summary; first Edit→Save migrates it to a document.
bodyContent = renderReadOnlyBody(legacySummary);
} else if (!hasDocument) {
// Truly empty (A).
bodyContent = (
<EmptyState icon={FileText} message="No body yet. Capture the item's details here." action="Add the item body" onAction={beginEdit} />
);
} else if (annotationsLinked && bodyIssueDocument) {
bodyContent = (
<IssueDocumentAnnotations
issueId={conversationIssueId!}
doc={bodyIssueDocument}
bodyMarkdown={displayedBody}
draftDirty={false}
draftConflicted={false}
historicalPreview={false}
locationHash={locationHash}
panelOpen={panelOpen}
onPanelOpenChange={setPanelOpen}
agentMap={agentMap}
userProfileMap={userProfileMap}
initialComposerAnchor={pendingStartAnchor}
onInitialComposerAnchorConsumed={() => setPendingStartAnchor(null)}
>
{renderReadOnlyBody(displayedBody)}
</IssueDocumentAnnotations>
);
} else {
// Has a saved body but no conversation/link yet: allow selecting text to start one.
bodyContent = (
<section
ref={(element) => {
containerRef.current = element;
}}
className="relative min-w-0"
data-testid="pipeline-item-body-unlinked"
>
<div className="relative z-(--z-1)">{renderReadOnlyBody(displayedBody)}</div>
<DocumentAnnotationLayer
containerRef={containerRef}
markdown={displayedBody}
threads={[]}
focusedThreadId={null}
onThreadFocus={() => {}}
pendingAnchor={selectionAnchor}
onPendingAnchorChange={setSelectionAnchor}
onRequestComment={(anchor) => void handleStartConversationFromAnchor(anchor)}
hideResolved
/>
</section>
);
}
return (
<section
aria-label="Item body"
id="pipeline-item-body-document"
data-testid="pipeline-item-body-document"
className="rounded-lg border border-border p-3"
>
<DocumentFrameHeader
documentKey={BODY_DOCUMENT_KEY}
documentLabel="Item body document"
folded={folded}
onToggleFolded={() => setFolded((value) => !value)}
revisionMenu={hasDocument ? {
open: revisionMenuOpen,
onOpenChange: setRevisionMenuOpen,
loading: revisionsQuery.isFetching,
revisions: revisions.map((revision) => ({
id: revision.id,
revisionNumber: revision.revisionNumber,
createdAt: revision.createdAt,
actor: getPipelineRevisionActor(revision, { agentMap, userProfileMap }),
})),
selectedRevisionId,
currentRevisionId: doc?.latestRevisionId ?? null,
displayedRevisionNumber,
historicalPreview: isHistoricalPreview,
onSelectRevision: (revisionId: string, isCurrent: boolean) => setSelectedRevisionId(isCurrent ? null : revisionId),
} : undefined}
updatedAt={hasDocument ? doc?.updatedAt : null}
updatedHref="#pipeline-item-body-document"
annotationSlot={annotationsLinked && conversationIssueId ? (
<DocumentAnnotationsCountChip
issueId={conversationIssueId}
docKey={PIPELINE_CASE_BODY_DOCUMENT_KEY}
panelOpen={panelOpen}
onToggle={() => setPanelOpen((value) => !value)}
/>
) : null}
actionsSlot={editing ? (
<span className="text-(length:--text-micro) font-medium text-amber-700 dark:text-amber-300">● Editing · unsaved</span>
) : (
<Button variant="ghost" size="sm" className="h-auto gap-1.5 px-2 py-1 text-xs" onClick={beginEdit}>
<FilePenLine className="h-3.5 w-3.5" />
Edit
</Button>
)}
/>
{!folded ? <div className="mt-3 space-y-3">{bodyContent}</div> : null}
</section>
);
}