Files
PaperClipAI/ui/src/components/DocumentMarkdownBody.test.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

143 lines
7.4 KiB
TypeScript

// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { MemoryRouter, useLocation, useNavigate } from "react-router-dom";
import { afterEach, describe, expect, it } from "vitest";
import { ThemeProvider } from "@/context/ThemeContext";
import { DocumentMarkdownBody } from "./DocumentMarkdownBody";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
let root: Root;
let container: HTMLDivElement;
afterEach(async () => {
await act(async () => root?.unmount());
container?.remove();
});
const body = "![First](/first.png)\n\n![Second][shot]\n\n![Repeated](/first.png)\n\n[shot]: https://example.com/second.png";
function LocationProbe() {
const location = useLocation();
const navigate = useNavigate();
return <><output>{location.pathname}{location.search}{location.hash}</output><button onClick={() => navigate(-1)}>Back</button></>;
}
async function render(hash = "", markdown = body, revisionId?: string, documentIssueId?: string, currentIssueId?: string) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
await act(async () => {
root.render(<MemoryRouter initialEntries={[`/PAP/issues/example?keep=1${hash}`]}>
<QueryClientProvider client={client}><ThemeProvider>
<DocumentMarkdownBody documentKey="report" revisionId={revisionId} documentIssueId={documentIssueId} currentIssueId={currentIssueId}>{markdown}</DocumentMarkdownBody>
<LocationProbe />
</ThemeProvider></QueryClientProvider>
</MemoryRouter>);
});
}
async function click(selector: string) {
const element = document.querySelector<HTMLElement>(selector)!;
expect(element).not.toBeNull();
await act(async () => element.click());
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
}
async function key(key: string) {
await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })));
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
}
function dialog() { return document.querySelector('[role="dialog"]'); }
describe("document image gallery", () => {
it("keeps fragment links scoped to the saved document's task after the URL changes", async () => {
await render("#document-local", "[Evidence](#document-evidence&thread=note)\n\n[Explicit](#document-brief&documentIssue=other)\n\n[Section](#section)", "old", "owner", "current");
expect([...container.querySelectorAll(".paperclip-markdown a")].map(link => link.getAttribute("href"))).toEqual([
"#document-evidence&thread=note&documentIssue=owner",
"#document-brief&documentIssue=other",
"#section",
]);
});
it("opens a clicked occurrence, navigates all rendered images, and updates the URL", async () => {
await render("#document-report&viewer=full&thread=thread-1");
await click('[aria-label="Open image: Repeated"]');
expect(dialog()?.textContent).toContain("3 / 3");
expect(dialog()?.querySelector("img")?.getAttribute("src")).toBe("/first.png");
expect(container.querySelector("output")?.textContent).toBe("/PAP/issues/example?keep=1#document-report&thread=thread-1&viewer=full&image=3");
await key("ArrowRight");
expect(dialog()?.textContent).toContain("1 / 3");
await click('button[title="Next"]');
expect(dialog()?.querySelector("img")?.getAttribute("src")).toBe("https://example.com/second.png");
expect(container.querySelector("output")?.textContent).toContain("image=2");
await key("ArrowLeft");
expect(dialog()?.textContent).toContain("1 / 3");
await click('button[title="Previous"]');
expect(dialog()?.textContent).toContain("3 / 3");
await key("Escape");
expect(dialog()).toBeNull();
expect(container.querySelector("output")?.textContent).not.toContain("image=");
expect(container.querySelector("output")?.textContent).toContain("viewer=full");
expect(document.activeElement?.getAttribute("aria-label")).toBe("Open image: Repeated");
});
it("loads a shared image URL for the exact revision and retains it on close", async () => {
await render("#document-report&revision=old&interaction=review&documentIssue=owner&image=2", body, "old", "owner");
expect(dialog()?.textContent).toContain("2 / 3");
expect(dialog()?.querySelector("a")?.getAttribute("href")).toBe("https://example.com/second.png");
await click('button[title="Close"]');
expect(container.querySelector("output")?.textContent).toContain("#document-report&revision=old&interaction=review&documentIssue=owner");
expect(dialog()).toBeNull();
});
it("opens a saved owner after the URL has changed to another document", async () => {
await render("#document-local&documentIssue=wrong-owner", body, "old", "owner");
await click('[aria-label="Open image: First"]');
expect(dialog()?.textContent).toContain("1 / 3");
expect(container.querySelector("output")?.textContent).toContain("#document-report&revision=old&documentIssue=owner&image=1");
await key("ArrowRight");
expect(container.querySelector("output")?.textContent).toContain("documentIssue=owner&image=2");
});
it("opens an explicit current-task link and keeps review parameters through navigation and reopening", async () => {
await render("#document-report&revision=old&interaction=review&viewer=full&documentIssue=current-task&image=2", body, "old", undefined, "current-task");
expect(dialog()?.textContent).toContain("2 / 3");
await key("ArrowRight");
expect(dialog()?.textContent).toContain("3 / 3");
await click('button[title="Close"]');
expect(dialog()).toBeNull();
await click('[aria-label="Open image: First"]');
expect(dialog()?.textContent).toContain("1 / 3");
const url = container.querySelector("output")?.textContent;
expect(url).toContain("revision=old");
expect(url).toContain("interaction=review");
expect(url).toContain("viewer=full");
expect(url).toContain("documentIssue=current-task");
});
it("does not match another task's saved tab to an implicit current-task link", async () => {
await render("#document-report&revision=old&image=2", body, "old", "other-task", "current-task");
expect(dialog()).toBeNull();
await click('[aria-label="Open image: First"]');
expect(dialog()?.textContent).toContain("1 / 3");
expect(container.querySelector("output")?.textContent).toContain("documentIssue=other-task");
});
it.each(["#document-other&image=1", "#document-report&image=100", "#document-report&image=0", "#document-report&revision=old&image=1"])("does not open an unavailable image target: %s", async (hash) => {
await render(hash);
expect(dialog()).toBeNull();
});
it("opens a single image from the keyboard without navigation controls", async () => {
await render("", "![Only](/only.png)");
const image = container.querySelector("img")!;
await act(async () => {
image.focus();
image.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
});
expect(dialog()?.textContent).toContain("1 / 1");
expect(dialog()?.querySelector('button[title="Next"]')).toBeNull();
await click('[role="dialog"]');
expect(dialog()).toBeNull();
expect(document.activeElement).toBe(image);
});
});