perf(ui): open a task restored from the saved read cache through the chat bootstrap (#21650)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The board UI opens a task page as a chat. A hard load of a task URL
starts one chat bootstrap request before the app's JavaScript runs.
> - A returning browser also restores a saved read cache from local
storage. This cache holds the core fields of recently opened tasks, but
no chat history.
> - The task page started the bootstrap only when the core task was not
cached. A restored core task skipped it. The early bootstrap request
ran, but nothing used its answer.
> - So every first-frame read went to its own endpoint, and the comment
input facts waited for the recent comments. A returning load was slower
than a cold load: on staging, 3.6–3.8 s against 1.9–2.4 s.
> - This pull request treats a task that only the saved cache holds as
cold for the chat. The page adopts the bootstrap, the restored task's
own revalidation shares it, and the answer replaces the restored data.
> - The benefit is that a returning load is now faster than a cold load,
not slower.

## Linked Issues or Issue Description

**Describe the bug**
A hard load of a task page is slower when the browser has a saved read
cache than when it has none. Measured on staging on 2026-11-14 (hard
load, JavaScript in the HTTP cache, 3 alternating pairs on one task):
saved cache cleared 1.9–2.4 s, saved cache present 3.6–3.8 s, until the
chat composer exists.

**Steps to reproduce**
1. Open a task page so that the saved read cache
(`paperclip:query-cache:v1:*`) holds it.
2. Close the tab and open the same task URL again.
3. Compare the time to the first chat frame with a load where the saved
read cache is cleared.

**Expected behavior**
A load with a saved read cache is at least as fast as a load without
one. The chat's first-frame reads share the one bootstrap request.

**Actual behavior**
With a saved read cache, the bootstrap request runs but its answer is
not used. About 16 more per-endpoint reads run before the frame, and the
frame waits for a second, serial wave of reads.

Related: #20355 (chat bootstrap endpoints), #20592 (cold task open from
one bootstrap), #20591 and #20594 (returning Mine inbox from the saved
read cache), #21557 (cold-load perf spec).

## What Changed

- `ui/src/lib/persisted-query-cache.ts`: records which queries a page
restored from the saved read cache. `isRestoredSavedRead(client, key)`
is true until a read or a local write in this page replaces that data.
- `ui/src/pages/IssueDetail.tsx`: starts (or adopts) the chat bootstrap
when the core task is missing or only restored. It passes the restored
task's id and identifier as aliases, so reads keyed by the id share the
request while it loads.
- `ui/src/lib/issue-chat-bootstrap.ts`: `readFromIssueChatBootstrap`
lets a key that holds only restored data share the bootstrap, like an
empty key. `startIssueChatBootstrap` accepts aliases.
- `ui/src/lib/issueChatBootstrapCache.ts` and
`ui/src/lib/issueDetailCache.ts`: the bootstrap answer replaces restored
data (core task under every ref). The restored core task's revalidation
shares the bootstrap. A core task that was read in this page keeps its
own small read.
- `ui/src/hooks/useIssuePlanDocument.ts`: the first plan read shares the
bootstrap's plan projection instead of reading `documents/plan` before
the frame.
- `tests/perf/issue-detail/cold-bootstrap.perf.spec.ts`: an always-on
request-shape test for a returning load with a saved read cache, and an
opt-in benchmark of alternating pairs (saved cache present and cleared).
The harness now clears storage after the warm-up page closes, because
closing the app saves its read cache again.
- `ui/src/lib/restored-task-chat-bootstrap.test.ts`: unit tests for the
restore-then-bootstrap path.
- `tests/perf/issue-detail/README.md`: documents the returning-load test
and benchmark.

## Verification

Local production build (`PAPERCLIP_UI_DEV_MIDDLEWARE=false`),
local_trusted instance, CDP delay of 300 ms on every API request, fresh
browser context per run, JavaScript in the HTTP cache. Time from
navigation start to the revealed history with the latest message and an
editable composer.

| Build | Saved read cache | Runs | Median | Spread | API requests
before frame | Frame released by |
| --- | --- | ---: | ---: | ---: | ---: | --- |
| master `95a6ab31e6` | cleared | 5 | 913 ms | 908–957 | 33 | company
list (shell stage 2) |
| master `95a6ab31e6` | present | 5 | 1,204 ms | 1,178–1,215 | 49 |
`activity?view=comment-inputs` (serial second wave) |
| this PR | cleared | 7 | 942 ms | 925–997 | 35 | company list (shell
stage 2) |
| this PR | present | 7 | 573 ms | 566–658 | 37 | app boot and route
mount (all task data is the bootstrap) |

- Paired delta with this PR (present − cleared): median −376 ms over 7
pairs, all negative (−267 to −400). On master it was +292 ms over 5
pairs, all positive.
- With an 800 ms API delay (this PR, 5 pairs): present 890 ms, released
by the bootstrap response; cleared 1,910 ms.
- Cold load with no app storage (existing benchmark, 7 runs): master 910
ms, this PR 939 ms. The host load average was about 20 during the PR run
(other work on the machine). Requests before the frame are 35 in both. I
make no claim of a cold change.
- Request-shape tests (`cold-bootstrap.perf.spec.ts`): the new
returning-load test fails on master (the timeline shows `?view=core`,
`recent-comments`, `activity`, `runs`, `interactions`, `attachments`,
`live-runs` before the frame) and passes with this PR. The existing cold
test passes.
- Unit tests: `restored-task-chat-bootstrap.test.ts` has 10 cases. With
the behavior changes reverted (the restore marker kept so the file
imports), 3 fail: the bootstrap refreshes the restored task and fills
the chat, id-keyed reads share the loading bootstrap, and a partial
answer. All 10 pass with this PR. The other 7 cases are guards that hold
on both: a stale refresh reads the server, a failed bootstrap falls
back, a 403 removes the restored task from memory and storage, another
company's answer is not seeded, an answer is not used after another user
signs in, and another user's saved task is not restored.
- Focused Vitest: 27 files that use the changed modules, including
`IssueDetail.test.tsx` and `TaskChatThread.test.tsx`: 1,208 passed.
- Browser layout journeys against the PR build:
`layout-stability.spec.ts` and `plan-startup.spec.ts`, 17 of 17 passed
(reveal order, reading anchor, older history, Back, comment links,
drafts during background refresh, failed and stalled reads with Retry,
plan projection with stalled plan reads).
- `pnpm verify` exit 2 (the README is a global CI input), so required CI
supplies the broad coverage.

Commands:

```sh
cd ui && npx vitest run src/lib/restored-task-chat-bootstrap.test.ts
PAPERCLIP_ISSUE_PERF_BASE_URL=http://127.0.0.1:<port> pnpm exec playwright test --config tests/perf/issue-detail/playwright.config.ts cold-bootstrap
PAPERCLIP_ISSUE_PERF_BASE_URL=http://127.0.0.1:<port> PAPERCLIP_ISSUE_PERF_COLD_RUNS=7 pnpm exec playwright test --config tests/perf/issue-detail/playwright.config.ts cold-bootstrap -g returning
```

## Risks

- Low risk. The change only affects data that the saved read cache
restored and that no read in this page has confirmed. Data read in this
page keeps the old rule: a refresh asks the server.
- The saved read cache content is unchanged. It still excludes comments
and bootstrap payloads, so the first chat frame still needs one response
(the bootstrap). It cannot appear before any task response without
saving chat history, which the documented allowlist excludes.
- If the bootstrap fails, stalls or omits the task, each read falls back
to its own request, as on a cold load. A 403 or 404 on the restored
task's fallback read removes it from memory and storage, as before.
- Account changes: a bootstrap answer is bound to the session's user, as
before. The saved cache restores data only for the same user.

## Model Used

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

## 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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-14 15:16:43 -06:00
1 parent 0ab73d4e30
commit ecdeed5e7e
9 files changed
+416 -24

No files matched your search

+20
View File
@@ -85,6 +85,26 @@ changes the delay. `PAPERCLIP_ISSUE_PERF_COLD_HTTP_CACHE=1` downloads the
JavaScript on every run. Serve a production build
(`PAPERCLIP_UI_DEV_MIDDLEWARE=false`).
### Returning direct task load (saved read cache)
A returning browser restores the saved read cache (`paperclip:query-cache:v1:*`)
before the first render, including the core fields of recently opened tasks.
Chat history is never saved, so the restored task's chat still reads the
bootstrap. Its reads, including the restored task's own revalidation and its
plan projection, share that one request instead of reading each endpoint.
The always-on request-shape test checks this with a saved cache. The opt-in
benchmark runs alternating pairs with the saved read cache present and
cleared (other app storage kept) and writes `returning-task-<label>.{json,md}`:
```sh
PAPERCLIP_ISSUE_PERF_BASE_URL=http://127.0.0.1:3287 \
PAPERCLIP_ISSUE_PERF_COLD_RUNS=5 PAPERCLIP_ISSUE_PERF_LABEL=candidate \
pnpm exec playwright test --config tests/perf/issue-detail/playwright.config.ts cold-bootstrap -g returning
```
Closing a page saves its read cache, so the harness clears storage from a
separate same-origin page after the warm-up page closes.
## Real-instance click harness
Local fixtures cannot reproduce staging's network round trips, server contention
@@ -59,21 +59,42 @@ function scrub(url: string, seedData: Seed) {
.replaceAll(seedData.companyId, ":company");
}
async function measure(browser: Browser, baseURL: string, seedData: Seed, run: number): Promise<Sample> {
/**
* What the measured load starts with:
* - `empty`: no app storage at all.
* - `no-saved-reads`: a returning browser whose saved read cache was cleared.
* - `saved-reads`: a returning browser with the saved read cache of an earlier
* visit to this task (`paperclip:query-cache:v1:*` in local storage).
*/
type StartState = "empty" | "no-saved-reads" | "saved-reads";
const SAVED_READS_PREFIX = "paperclip:query-cache:v1:";
async function measure(browser: Browser, baseURL: string, seedData: Seed, run: number, start: StartState = "empty"): Promise<Sample> {
const context = await browser.newContext({ baseURL, viewport: { width: 1440, height: 900 }, serviceWorkers: "block" });
if (WARM_HTTP_CACHE) {
if (WARM_HTTP_CACHE || start !== "empty") {
// Load the app's JavaScript into this context's HTTP cache, then clear
// every app store so the measured load starts without app data.
// the app stores the measured load must start without.
const warm = await context.newPage();
await warm.goto(`/${seedData.prefix}/issues/${seedData.identifier}`);
await warm.getByTestId("task-chat-thread").locator(':scope > [aria-busy="false"]').waitFor({ timeout: 60_000 });
await warm.evaluate(async () => {
localStorage.clear();
if (start === "saved-reads") {
// The read cache saves after a short debounce; wait until it holds this task.
await warm.waitForFunction(({ prefix, issueId }) => Object.keys(localStorage).some((key) => key.startsWith(prefix)
&& (localStorage.getItem(key) ?? "").includes(issueId)), { prefix: SAVED_READS_PREFIX, issueId: seedData.issueId }, { timeout: 30_000 });
}
// Closing the app saves its read cache, so clear storage afterwards from
// a same-origin page that does not run the app.
await warm.close();
const cleaner = await context.newPage();
await cleaner.goto("/api/health");
await cleaner.evaluate(async ({ start, prefix }) => {
if (start === "empty") localStorage.clear();
else if (start === "no-saved-reads") for (const key of Object.keys(localStorage)) if (key.startsWith(prefix)) localStorage.removeItem(key);
sessionStorage.clear();
for (const db of (await indexedDB.databases?.()) ?? []) if (db.name) indexedDB.deleteDatabase(db.name);
for (const key of (await caches?.keys?.()) ?? []) await caches.delete(key);
});
await warm.close();
}, { start, prefix: SAVED_READS_PREFIX });
await cleaner.close();
}
const page = await context.newPage();
// Delay API requests through CDP request interception. Playwright routing
@@ -176,6 +197,25 @@ test("a cold direct task load reads its first frame from one chat bootstrap", as
expect(firstFrameReads.map((record) => record.path)).toEqual([]);
});
test("a returning task load with saved reads revalidates its first frame through one chat bootstrap", async ({ browser, baseURL, request }) => {
const seedData = await seed(request);
const sample = await measure(browser, baseURL!, seedData, 1, "saved-reads");
await test.info().attach("requests.json", { body: JSON.stringify(sample, null, 2), contentType: "application/json" });
// The saved task (header, core fields) is restored, but no chat history
// is saved: its reads must share the page's bootstrap like a cold load,
// including the restored task's own revalidation and its plan projection.
const perEndpoint = (record: RequestRecord) => FIRST_FRAME_ENDPOINTS.some((pattern) => pattern.test(record.path))
|| /^\/api\/issues\/[^/]+\/documents\/plan$/.test(record.path);
const startedBefore = sample.requests.filter((record) => record.startMs <= sample.revealMs);
const catchUpFrom = sample.socketMs ?? Number.POSITIVE_INFINITY;
const firstFrameReads = startedBefore.filter((record) => perEndpoint(record) && record.startMs < catchUpFrom);
if (firstFrameReads.length > 0) {
console.log(`frame at ${Math.round(sample.revealMs)} ms, socket ${sample.socketMs === null ? "none" : Math.round(sample.socketMs)} ms\n${sample.requests.map((r) => `${Math.round(r.startMs)}-${r.endMs === null ? "pending" : Math.round(r.endMs)} ${r.method} ${r.path}`).join("\n")}`);
}
expect(startedBefore.filter((record) => record.path.startsWith("/api/issues/:ref/chat-bootstrap"))).toHaveLength(1);
expect(firstFrameReads.map((record) => record.path)).toEqual([]);
});
test("cold direct task load benchmark", async ({ browser, baseURL, request }) => {
test.skip(RUNS === 0, "Set PAPERCLIP_ISSUE_PERF_COLD_RUNS to run the benchmark.");
test.setTimeout(15 * 60_000);
@@ -208,3 +248,69 @@ test("cold direct task load benchmark", async ({ browser, baseURL, request }) =>
console.log(`\n${report}\n`);
});
function summary(samples: Sample[]) {
const reveals = samples.map((sample) => sample.revealMs);
const counts = samples.map((sample) => sample.apiRequestsBeforeReveal);
return {
median: Math.round(median(reveals)), min: Math.round(Math.min(...reveals)), max: Math.round(Math.max(...reveals)),
requestsMedian: median(counts), requestsMin: Math.min(...counts), requestsMax: Math.max(...counts),
};
}
test("returning task load benchmark: saved read cache present versus cleared", async ({ browser, baseURL, request }) => {
test.skip(RUNS === 0, "Set PAPERCLIP_ISSUE_PERF_COLD_RUNS to run the benchmark.");
test.setTimeout(20 * 60_000);
const seedData = await seed(request);
const pairs: Array<{ cleared: Sample; saved: Sample }> = [];
// Alternate the order within each pair so drift does not favour one side.
for (let run = 1; run <= RUNS; run += 1) {
if (run % 2) {
const cleared = await measure(browser, baseURL!, seedData, run, "no-saved-reads");
pairs.push({ cleared, saved: await measure(browser, baseURL!, seedData, run, "saved-reads") });
} else {
const saved = await measure(browser, baseURL!, seedData, run, "saved-reads");
pairs.push({ cleared: await measure(browser, baseURL!, seedData, run, "no-saved-reads"), saved });
}
}
const cleared = summary(pairs.map((pair) => pair.cleared));
const saved = summary(pairs.map((pair) => pair.saved));
const deltas = pairs.map((pair) => pair.saved.revealMs - pair.cleared.revealMs);
const row = (name: string, value: ReturnType<typeof summary>) =>
`| ${name} | ${value.median} | ${value.min}–${value.max} | ${value.requestsMedian} (${value.requestsMin}–${value.requestsMax}) |`;
const timeline = (sample: Sample) => sample.requests.map((record) =>
`| ${Math.round(record.startMs)} | ${record.endMs === null ? "pending" : Math.round(record.endMs)} | ${record.method} ${record.path}${record.startMs > sample.revealMs ? " (after frame)" : ""} |`);
const report = [
`# Returning task load (${LABEL})`,
"",
`API delay ${API_DELAY_MS} ms per request, ${RUNS} alternating pairs, fresh browser context each run, JavaScript in the HTTP cache.`,
"",
"| saved read cache | median ms | spread ms | requests before frame |",
"| --- | ---: | ---: | ---: |",
row("cleared", cleared),
row("present", saved),
"",
`Paired delta (present − cleared): median ${Math.round(median(deltas))} ms, ${deltas.map((delta) => Math.round(delta)).join(", ")}.`,
`Released by (pair 1): cleared ${pairs[0]!.cleared.releasedBy.join(", ")}; present ${pairs[0]!.saved.releasedBy.join(", ")}.`,
"",
"## Pair 1, saved read cache present (ms from navigation start)",
"",
"| start | end | request |",
"| ---: | ---: | --- |",
...timeline(pairs[0]!.saved),
"",
`Frame at ${Math.round(pairs[0]!.saved.revealMs)} ms.`,
"",
"## Pair 1, saved read cache cleared",
"",
"| start | end | request |",
"| ---: | ---: | --- |",
...timeline(pairs[0]!.cleared),
"",
`Frame at ${Math.round(pairs[0]!.cleared.revealMs)} ms.`,
].join("\n");
await fs.mkdir(OUTPUT_DIR, { recursive: true });
await fs.writeFile(path.join(OUTPUT_DIR, `returning-task-${LABEL}.json`), JSON.stringify({ apiDelayMs: API_DELAY_MS, pairs }, null, 2));
await fs.writeFile(path.join(OUTPUT_DIR, `returning-task-${LABEL}.md`), report);
console.log(`\n${report}\n`);
});