Files
PaperClipAI/ui/src/lib/issueDetailCache.test.ts
T
DottaandClaude Opus 5.5 189fefb991 perf(task-chat): warm the whole first frame before a task opens (#20286)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People open tasks from the issues list and the inbox to continue a
conversation with an agent
> - The compact task chat shows its first frame only after about ten
reads settle. These include recent comments, activity, recent runs,
interactions, attachments and live runs
> - Navigation prefetch warmed only the issue and its recent comments.
The other reads started on the click, and the slowest one decided when
the chat appeared. On staging that took 1.1–2.0 s
> - This pull request warms the whole first-frame set when an open is
likely, under the exact keys the page reads
> - The benefit is that a task the person is about to open can render
from cache. A pointer that only passes over rows does not add load

## Linked Issues or Issue Description

**Problem or motivation**
On a busy instance, the composer and the latest messages appear 1.1–2.0
s after a click on a task row. The page waits for about ten reads.
Before the click, only two of them are warmed.

**Proposed solution**
Warm the rest of the first-frame reads when an open is likely: a mouse
or pen press, a click, keyboard Enter, or a hover or focus that rests on
the link for 120 ms. The page and the prefetch use the same fetchers and
query keys.

**Alternatives considered**
- Warm everything on every hover. This sends about 7 requests for each
row that a pointer crosses, so it was rejected.
- Warm only on press. The time from press to click is short, so most of
the wait would remain.
- A single bootstrap endpoint. This is planned separately, because it
changes the API contract.

**Roadmap alignment**
This is part of the task-loading performance plan in #20276. It follows
#20277 and #20284.

## What Changed

- New `ui/src/lib/issue-chat-history-queries.ts`:
- The recent activity and recent run window fetchers moved here from
`IssueDetail.tsx`, together with their query keys. The logic is
unchanged.
- `prefetchIssueChatHistory` warms activity, the run window,
interactions, attachments and live runs. It warms the active run only
for running work, as the page does.
- Live state uses a 5 s stale time. The other reads use the existing 30
s navigation stale time.
- The run-window prefetch uses the same conversation mode as the page.
Thus a reconnect in an agent conversation reads only the watched runs by
id.
- `prefetchIssueCommentInputFacts` warms the input facts of the recent
comments after those comments arrive.
- `ui/src/hooks/useIssueIdBatches.ts`: new `prefetchIssueIdBatches`
fills the same batch keys that the hook reads. The hook and the prefetch
share one batching function.
- `prefetchIssueDetailForNavigation` accepts `history: true` and then
also warms that set, plus the comment input facts.
- `IssueLinkQuicklook`:
- A hover still warms the light set at once. The quicklook trigger does
not start a history prefetch.
- A hover that rests on the link for 120 ms warms the full set. Leaving
the link before 120 ms cancels it.
- Keyboard focus uses the same 120 ms dwell as a hover. Blur cancels it.
  - A primary mouse or pen press and a click warm the full set at once.
- A touch can start a scroll, so it warms only the light set. The full
set waits for the click.
- The keyboard Enter handlers in `IssuesList`, `LegacyIssuesList`,
`Inbox` and `LegacyInbox` pass `history: true`.
- `IssueDetail.tsx` uses the shared fetchers and keys.

## Verification

- `cd ui && npx vitest run src/lib/issueDetailCache.test.ts
src/components/IssueLinkQuicklook.test.tsx
src/hooks/useIssueIdBatches.test.tsx` passes 29 tests. These are the new
ones:
- A `history` prefetch fills every key that the compact chat waits on,
with the same run-window shape that the page builds.
- A `history` prefetch fills the comment input-fact batch keys that the
chat reads.
- In an agent conversation, a reconnect reads the watched runs by id,
not every run.
- Prefetched id batches render with no loading state on the first
render.
  - The active run is read only for work that is running.
  - A light prefetch makes no history requests.
- A pointer that passes over a link in less than 120 ms warms only the
light set, with the quicklook on and off.
  - A hover that rests on a link warms the full set.
  - A mouse press warms the full set at once.
  - A touch warms only the light set until the click.
  - Keyboard focus warms the full set only after it rests on the link.
- The tests for the review fixes (quicklook hover, input facts,
conversation mode, touch and focus) fail without the fix.
- The `IssueDetail`, `Inbox`, `IssuesList` and `LegacyInbox` suites
pass: 4 files, 412 tests.
- `pnpm typecheck` in `ui` shows no new errors. The only errors are
existing ones from an unbuilt `plugin-sdk` package in this worktree.
- The staging harness from #20276 will measure the gain after deploy,
for a hover, a click, and a revisit.

## Risks

- More requests when an open is likely: up to 7 extra reads for each
task that is pressed with a mouse or pen, or hovered or focused for 120
ms. These are the same reads that the page would send on open, so a
completed open costs nothing extra. A hover that does not lead to an
open costs those reads.
- Freshness: a prefetched result can stay fresh for up to 30 s (5 s for
live state). Websocket invalidation still refreshes these keys, as on a
revisit today.
- No API or schema change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use (shell, browser automation, file editing).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 10:26:42 -06:00

292 lines
13 KiB
TypeScript

import { QueryClient } from "@tanstack/react-query";
import type { Issue } from "@paperclipai/shared";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { issuesApi } from "@/api/issues";
import { activityApi } from "@/api/activity";
import { heartbeatsApi } from "@/api/heartbeats";
import {
issueCommentInputFactsQueryKey,
recentIssueActivityQueryKey,
recentIssueRunWindowQueryKey,
} from "./issue-chat-history-queries";
import {
fetchIssueDetail,
getCachedIssueDetail,
prefetchIssueDetail,
prefetchIssueDetailForNavigation,
seedIssueDetailCache,
} from "./issueDetailCache";
import { queryKeys } from "./queryKeys";
vi.mock("@/api/issues", () => ({
issuesApi: {
get: vi.fn(),
getCore: vi.fn(),
recentComments: vi.fn(),
listComments: vi.fn(),
listInteractions: vi.fn(),
listAttachments: vi.fn(),
},
}));
vi.mock("@/api/activity", () => ({
activityApi: { recentForIssue: vi.fn(), recentRunsForIssue: vi.fn(), runsForIssue: vi.fn(), runsByIdsForIssue: vi.fn(), inputFactsForIssue: vi.fn() },
}));
vi.mock("@/api/heartbeats", () => ({
heartbeatsApi: { liveRunsForIssue: vi.fn(), activeRunForIssue: vi.fn() },
}));
function createIssue(overrides: Partial<Issue> = {}): Issue {
return {
id: "issue-1",
identifier: "PAP-1",
companyId: "company-1",
projectId: null,
projectWorkspaceId: null,
goalId: null,
parentId: null,
title: "Fast link target",
description: null,
status: "todo",
priority: "medium",
reviewPolicy: null,
assigneeAgentId: null,
assigneeUserId: null,
responsibleUserId: null,
createdByAgentId: null,
createdByUserId: null,
issueNumber: 1,
requestDepth: 0,
billingCode: null,
assigneeAdapterOverrides: null,
executionWorkspaceId: null,
executionWorkspacePreference: null,
executionWorkspaceSettings: null,
checkoutRunId: null,
executionRunId: null,
executionAgentNameKey: null,
executionLockedAt: null,
startedAt: null,
completedAt: null,
cancelledAt: null,
hiddenAt: null,
createdAt: new Date("2026-04-11T00:00:00.000Z"),
updatedAt: new Date("2026-04-11T00:00:00.000Z"),
labels: [],
labelIds: [],
myLastTouchAt: null,
lastExternalCommentAt: null,
isUnreadForMe: false,
...overrides,
workMode: overrides.workMode ?? "standard",
};
}
describe("issueDetailCache", () => {
let queryClient: QueryClient;
beforeEach(() => {
queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
vi.clearAllMocks();
});
it("seeds and resolves issue detail by both identifier and id", () => {
const issue = createIssue();
seedIssueDetailCache(queryClient, issue, { issueRef: issue.identifier });
expect(getCachedIssueDetail(queryClient, issue.identifier)).toEqual(issue);
expect(getCachedIssueDetail(queryClient, issue.id)).toEqual(issue);
expect(queryClient.getQueryData(queryKeys.issues.detail(issue.identifier!))).toEqual(issue);
expect(queryClient.getQueryData(queryKeys.issues.detail(issue.id))).toEqual(issue);
});
it("prefetches with the provided issue snapshot without forcing a fresh fetch", async () => {
const issue = createIssue();
await prefetchIssueDetail(queryClient, issue.identifier!, { issue });
expect(getCachedIssueDetail(queryClient, issue.identifier)).toEqual(issue);
expect(getCachedIssueDetail(queryClient, issue.id)).toEqual(issue);
expect(issuesApi.get).not.toHaveBeenCalled();
});
it("does not seed partial issue snapshots during prefetch", async () => {
const issue = createIssue();
const partialIssue = {
id: issue.id,
identifier: issue.identifier,
title: issue.title,
status: issue.status,
priority: issue.priority,
} as Issue;
vi.mocked(issuesApi.get).mockResolvedValue(issue);
await prefetchIssueDetail(queryClient, issue.identifier!, { issue: partialIssue });
expect(issuesApi.get).toHaveBeenCalledWith(issue.identifier);
expect(getCachedIssueDetail(queryClient, issue.identifier)).toEqual(issue);
});
it("does not write partial issue snapshots into the detail cache", () => {
const issue = createIssue();
const partialIssue = {
id: issue.id,
identifier: issue.identifier,
title: issue.title,
status: issue.status,
priority: issue.priority,
} as Issue;
seedIssueDetailCache(queryClient, partialIssue, { issueRef: issue.identifier });
expect(queryClient.getQueryData(queryKeys.issues.detail(issue.identifier!))).toBeUndefined();
expect(getCachedIssueDetail(queryClient, issue.identifier)).toBeUndefined();
});
it("hydrates both cache aliases from a fetched issue detail response", async () => {
const issue = createIssue();
vi.mocked(issuesApi.get).mockResolvedValue(issue);
const result = await fetchIssueDetail(queryClient, issue.identifier!);
expect(result).toEqual(issue);
expect(queryClient.getQueryData(queryKeys.issues.detail(issue.identifier!))).toEqual(issue);
expect(queryClient.getQueryData(queryKeys.issues.detail(issue.id))).toEqual(issue);
});
});
describe("task navigation prefetch", () => {
it("warms the compact task and recent exchange used by the default surface", async () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const issue = createIssue();
const recent = { comments: [], latestCommentId: null, oldestCommentId: null, hasMore: false };
vi.mocked(issuesApi.getCore).mockResolvedValue(issue);
vi.mocked(issuesApi.recentComments).mockResolvedValue(recent);
vi.mocked(issuesApi.get).mockResolvedValue(issue);
vi.mocked(issuesApi.listComments).mockResolvedValue([]);
vi.clearAllMocks();
try {
await prefetchIssueDetailForNavigation(client, issue.identifier!);
expect(client.getQueryData([...queryKeys.issues.detail(issue.identifier!), "core"])).toEqual(issue);
expect(client.getQueryData([...queryKeys.issues.comments(issue.identifier!), "recent"])).toEqual(recent);
expect(issuesApi.get).not.toHaveBeenCalled();
expect(issuesApi.listComments).not.toHaveBeenCalled();
} finally { client.clear(); }
});
it("retains full-history prefetch for an already expanded task", async () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const issue = createIssue();
client.setQueryData(["issues", "history-expanded", issue.identifier!], true);
vi.mocked(issuesApi.get).mockResolvedValue(issue);
vi.mocked(issuesApi.listComments).mockResolvedValue([]);
try {
await prefetchIssueDetailForNavigation(client, issue.identifier!);
expect(client.getQueryData(queryKeys.issues.detail(issue.identifier!))).toEqual(issue);
expect(client.getQueryData(queryKeys.issues.comments(issue.identifier!))).toMatchObject({ pages: [[]] });
} finally { client.clear(); }
});
describe("chat history for a likely open", () => {
const run = (runId: string, status: string) => ({ runId, status, agentId: "agent-1", adapterType: "codex_local", createdAt: "2026-11-09T00:00:00Z" });
function mockHistoryReads() {
const issue = createIssue();
vi.mocked(issuesApi.getCore).mockResolvedValue(issue);
vi.mocked(issuesApi.recentComments).mockResolvedValue({ comments: [], latestCommentId: null, oldestCommentId: null, hasMore: false });
vi.mocked(activityApi.recentForIssue).mockResolvedValue([{ id: "event-1" }] as never);
vi.mocked(activityApi.recentRunsForIssue).mockResolvedValue([run("run-2", "failed"), run("run-1", "succeeded")] as never);
vi.mocked(issuesApi.listInteractions).mockResolvedValue([]);
vi.mocked(issuesApi.listAttachments).mockResolvedValue([]);
vi.mocked(heartbeatsApi.liveRunsForIssue).mockResolvedValue([]);
vi.mocked(heartbeatsApi.activeRunForIssue).mockResolvedValue(null);
return issue;
}
it("fills every key the compact chat waits on before its first reveal", async () => {
vi.clearAllMocks();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const issue = mockHistoryReads();
const ref = issue.identifier!;
try {
await prefetchIssueDetailForNavigation(client, ref, { issue, history: true });
expect(client.getQueryData(recentIssueActivityQueryKey(ref))).toEqual([{ id: "event-1" }]);
// Same window shape the page builds: the latest run, plus evidence of earlier runs.
expect(client.getQueryData(recentIssueRunWindowQueryKey(ref))).toEqual({ runs: [run("run-2", "failed")], hasEarlierRuns: true });
expect(client.getQueryData(queryKeys.issues.interactions(ref))).toEqual([]);
expect(client.getQueryData(queryKeys.issues.attachments(ref))).toEqual([]);
expect(client.getQueryData(queryKeys.issues.liveRuns(ref))).toEqual([]);
// A task that is not running has no active run for the page to read.
expect(heartbeatsApi.activeRunForIssue).not.toHaveBeenCalled();
} finally { client.clear(); }
});
it("reads the active run only for running work", async () => {
vi.clearAllMocks();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const issue = { ...mockHistoryReads(), status: "in_progress" as const };
try {
await prefetchIssueDetailForNavigation(client, issue.identifier!, { issue, history: true });
expect(heartbeatsApi.activeRunForIssue).toHaveBeenCalledWith(issue.identifier);
expect(client.getQueryData(queryKeys.issues.activeRun(issue.identifier!))).toBeNull();
} finally { client.clear(); }
});
it("warms the input facts of the recent comments under the chat's batch keys", async () => {
vi.clearAllMocks();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const issue = mockHistoryReads();
const ref = issue.identifier!;
const comment = (id: string) => ({ id, body: id, createdAt: "2026-11-09T00:00:00Z" });
vi.mocked(issuesApi.recentComments).mockResolvedValue({
comments: [comment("comment-b"), comment("comment-a")],
latestCommentId: "comment-b", oldestCommentId: "comment-a", hasMore: false,
} as never);
vi.mocked(activityApi.inputFactsForIssue).mockResolvedValue([{ id: "input-1" }] as never);
try {
await prefetchIssueDetailForNavigation(client, ref, { issue, history: true });
// The same ids, order and keys that the chat's useIssueIdBatches reads.
expect(activityApi.inputFactsForIssue).toHaveBeenCalledWith(ref, ["comment-a", "comment-b"]);
const key = issueCommentInputFactsQueryKey(ref);
expect(client.getQueryData([...key, "batch-ids"])).toEqual([["comment-a", "comment-b"]]);
expect(client.getQueryData([...key, "batch", ["comment-a", "comment-b"]])).toEqual([{ id: "input-1" }]);
} finally { client.clear(); }
});
it("reconciles a watched agent conversation's runs by id, not by reading every run", async () => {
vi.clearAllMocks();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const issue = { ...mockHistoryReads(), conversationAgentId: "agent-1" };
const ref = issue.identifier!;
// A run watched earlier is still running, but has left the recent window.
client.setQueryData(recentIssueRunWindowQueryKey(ref), { runs: [run("run-0", "running")], hasEarlierRuns: false });
client.getQueryCache().find({ queryKey: recentIssueRunWindowQueryKey(ref) })!.invalidate();
vi.mocked(activityApi.runsByIdsForIssue).mockResolvedValue([run("run-2", "failed"), run("run-0", "succeeded")] as never);
try {
await prefetchIssueDetailForNavigation(client, ref, { issue, history: true });
expect(activityApi.runsByIdsForIssue).toHaveBeenCalledWith(ref, ["run-0", "run-2", "run-1"]);
expect(activityApi.runsForIssue).not.toHaveBeenCalled();
} finally { client.clear(); }
});
it("keeps a pointer passing over a row to the issue and recent comments", async () => {
vi.clearAllMocks();
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const issue = mockHistoryReads();
try {
await prefetchIssueDetailForNavigation(client, issue.identifier!, { issue });
expect(activityApi.recentForIssue).not.toHaveBeenCalled();
expect(activityApi.recentRunsForIssue).not.toHaveBeenCalled();
expect(issuesApi.listInteractions).not.toHaveBeenCalled();
expect(heartbeatsApi.liveRunsForIssue).not.toHaveBeenCalled();
} finally { client.clear(); }
});
});
});