Files
PaperClipAI/ui/src/components/task-side-panel/TaskDocumentPanel.tsx
T
673742bfc6 fix(ui): keep artifact previews in agent chat (#22252)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent Chat lets people discuss work and review the plans and
documents it produces.
> - A document link in Chat promises to open the sidebar. It currently
moves the reader to Tasks.
> - Readers need to see the document and the conversation together, even
when the window is narrow.
> - This pull request opens the document in Chat, frees space for
reading, and gives readers a link to the source task.
> - Readers can review the saved revision in context and open the task
when they need its details.

## Linked Issues or Issue Description

Refs #11226 for the document sidebar that this change builds on.

**What happened?**

Opening a saved plan from Agent Chat changed the route to Tasks. The
document could show the same title twice. At narrow desktop widths, the
chat list left too little space for the conversation beside the
document. A task opened by UUID could still show a Chat header.

**Expected behavior**

The sidebar shows the saved revision beside the current conversation. It
shows a matching title once. The chat list collapses when space is
tight. The source link opens the standard task header with status, name,
and ID.

**Steps to reproduce**

1. Open an Agent Chat with a saved plan and select its sidebar link.
2. Use a narrow desktop window and inspect the conversation and plan.
3. Open the task that owns the plan and inspect the breadcrumb.

**Paperclip version or commit**

Reproduced on source commit `8285a81280`.

**Deployment mode**

Local trusted development instance with synthetic data.

## What Changed

- Open sidebar document links on the current Chat route. Keep the
requested revision and document owner, including links inside another
task’s preview. Provide an **Open source task** link.
- Show one title when the document title matches the opening Markdown
heading.
- Collapse the desktop chat list when an artifact tab would leave less
than 420 px for the conversation. Keep **Browse chats** in the header
with access to saved chat history. Restore the list when there is room.
- Use the task breadcrumb on task URLs, with the short UUID for a
conversation-backed task without a number.

## Verification

- Ran 618 focused Vitest tests across 18 UI files on the published
revision `2ff6c9e931`. All passed.
- Ran `pnpm --filter @paperclipai/ui typecheck`. It passed.
- Checked the synthetic demo in Chromium. Opened the plan in Chat,
checked the title, resized the window, and followed **Open source task**
to check its breadcrumb. Also verified a link inside a preview owned by
another task.
- Reproduced the chat navigation failure from the CI trace. The same
Playwright test passed locally after limiting collapse to artifact tabs.
- GitHub CI passed on `2ff6c9e931`, including build, typecheck, and all
browser shards. The remaining jobs passed on a retry after runner
shutdowns and a server handover test failure. The handover suite also
passed locally (19 tests). [GitHub
CI](https://github.com/paperclipai/paperclip/actions/runs/44423540581/attempts/2)
- `pnpm verify` selected broader CI coverage because `doc/PRODUCT.md`
changed. The full local suite was not run.

## Risks

The chat list changes visibility when an artifact tab is active and the
available width crosses the threshold. The list stays mounted to keep
its search text. Document tabs use the existing read API and check the
owning company. This change adds no database migration or API contract
change.

## Model Used

OpenAI Codex (GPT-6), with repository tools, shell execution, and
Chromium.

## 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 linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have used public GitHub references for linked work
- [x] My branch name describes the change and contains no internal
Paperclip ticket ID
- [x] I have run focused 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: Scott Tong <1504818+scotttong@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-18 16:19:13 -08:00

154 lines
6.4 KiB
TypeScript

import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { IssueDocument } from "@paperclipai/shared";
import { ArrowUpRight, FileQuestion, Loader2 } from "lucide-react";
import { fromMarkdown } from "mdast-util-from-markdown";
import { ApiError } from "@/api/client";
import { issuesApi } from "@/api/issues";
import { DocumentAnnotationsCountChip, IssueDocumentAnnotations } from "@/components/IssueDocumentAnnotations";
import { DocumentMarkdownBody } from "@/components/DocumentMarkdownBody";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { queryKeys } from "@/lib/queryKeys";
import { documentDisplayTitle } from "@/lib/issue-artifacts";
import { createIssueDetailPath } from "@/lib/issueDetailBreadcrumb";
import { Link, useLocation } from "@/lib/router";
type HeadingNode = { type: string; value?: string; children?: HeadingNode[] };
function headingText(node: HeadingNode): string {
if (node.type === "text" || node.type === "inlineCode") return node.value ?? "";
if (node.type === "break") return " ";
return node.children?.map(headingText).join("") ?? "";
}
function startsWithMatchingHeading(body: string, title: string): boolean {
if (!body || !title) return false;
const first = fromMarkdown(body).children.find((node) =>
node.type !== "definition" && !(node.type === "html" && /^<!--[\s\S]*-->$/.test(node.value.trim())),
);
const normalize = (value: string) => value.trim().replace(/\s+/g, " ").toLowerCase();
return first?.type === "heading" && normalize(headingText(first)) === normalize(title);
}
export function TaskDocumentSourceLink({ taskRef }: { taskRef: string }) {
return (
<Link to={createIssueDetailPath(encodeURIComponent(taskRef))} disableIssueQuicklook
className="inline-flex w-fit items-center gap-1.5 rounded-sm text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
Open source task <ArrowUpRight className="size-4" aria-hidden />
</Link>
);
}
export function TaskDocumentPanel({
companyId,
issueId,
documentKey,
initialDocument,
revisionId,
documentIssueId,
currentIssueId = issueId,
}: {
companyId?: string;
issueId: string;
documentKey: string;
initialDocument?: IssueDocument;
revisionId?: string;
documentIssueId?: string;
currentIssueId?: string;
}) {
const location = useLocation();
const [annotationPanelOpen, setAnnotationPanelOpen] = useState(false);
const query = useQuery<IssueDocument | null>({
queryKey: [...queryKeys.issues.documents(issueId), documentKey, ...(revisionId ? ["revision", revisionId] : []), ...(documentIssueId && companyId ? ["company", companyId] : [])],
queryFn: async () => {
try {
const current = await issuesApi.getDocument(issueId, documentKey);
if (companyId && current.companyId !== companyId) return null;
if (!revisionId) return current;
const revision = await issuesApi.getDocumentRevision(issueId, documentKey, revisionId);
return { ...current, title: revision.title, body: revision.body, format: revision.format,
latestRevisionId: revision.id, latestRevisionNumber: revision.revisionNumber, updatedAt: revision.createdAt };
} catch (error) {
if (error instanceof ApiError && error.status === 404) return null;
throw error;
}
},
initialData: revisionId ? undefined : initialDocument,
});
const view = useQueryView(query);
const document = query.data;
const title = document ? documentDisplayTitle(document) : "";
const body = document?.body ?? "";
const hasMatchingHeading = useMemo(() => startsWithMatchingHeading(body, title), [body, title]);
if (query.isLoading || view.kind === "reconnecting") {
return (
<div className="flex items-center gap-2 py-8 text-sm text-muted-foreground" role="status">
<Loader2 className="size-4 animate-spin" aria-hidden />
Loading document…
</div>
);
}
if (view.kind === "error") {
return (
<div className="py-6">
<QueryErrorState error={query.error} action="load the document" onRetry={view.retry} retrying={view.isFetching} />
</div>
);
}
if (!document) {
return (
<div className="flex items-start gap-3 py-8 text-sm" role="status">
<FileQuestion className="mt-0.5 size-5 shrink-0 text-muted-foreground" aria-hidden />
<div className="space-y-1">
<p className="font-medium">{revisionId ? "Reviewed revision unavailable" : "Document no longer available"}</p>
<p className="text-muted-foreground">
{revisionId ? "The exact reviewed revision could not be found. The current version has not been substituted." : "Close this tab or choose another document."}
</p>
</div>
</div>
);
}
return (
<article className="space-y-4">
<header className="space-y-1">
{!hasMatchingHeading ? <h2 className="text-lg font-semibold">{title}</h2> : null}
<div className="flex flex-wrap items-center gap-1 text-xs text-muted-foreground">
<span>{`Revision ${document.latestRevisionNumber ?? 1}`}</span>
<span aria-hidden>·</span>
<span>{`Updated ${new Date(document.updatedAt).toLocaleString()}`}</span>
{!revisionId ? <DocumentAnnotationsCountChip
issueId={issueId}
docKey={document.key}
panelOpen={annotationPanelOpen}
onToggle={() => setAnnotationPanelOpen((open) => !open)}
/> : <span>· Reviewed version</span>}
</div>
</header>
{document.body.trim() ? (
<IssueDocumentAnnotations
issueId={issueId}
doc={document}
bodyMarkdown={document.body}
draftDirty={false}
draftConflicted={false}
historicalPreview={!!revisionId}
locationHash={location.hash}
panelOpen={annotationPanelOpen}
onPanelOpenChange={setAnnotationPanelOpen}
panelPlacement="popover"
>
<DocumentMarkdownBody documentKey={document.key} revisionId={revisionId}
documentIssueId={documentIssueId} currentIssueId={currentIssueId}>
{document.body}
</DocumentMarkdownBody>
</IssueDocumentAnnotations>
) : (
<p className="text-sm text-muted-foreground">Document is empty.</p>
)}
</article>
);
}