mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
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:
1 parent
0ab73d4e30
commit
ecdeed5e7e
9 files changed
+416
-24
No files matched your search
@@ -85,6 +85,26 @@ changes the delay. `PAPERCLIP_ISSUE_PERF_COLD_HTTP_CACHE=1` downloads the
|
|||||||
JavaScript on every run. Serve a production build
|
JavaScript on every run. Serve a production build
|
||||||
(`PAPERCLIP_UI_DEV_MIDDLEWARE=false`).
|
(`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
|
## Real-instance click harness
|
||||||
|
|
||||||
Local fixtures cannot reproduce staging's network round trips, server contention
|
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");
|
.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" });
|
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
|
// 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();
|
const warm = await context.newPage();
|
||||||
await warm.goto(`/${seedData.prefix}/issues/${seedData.identifier}`);
|
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.getByTestId("task-chat-thread").locator(':scope > [aria-busy="false"]').waitFor({ timeout: 60_000 });
|
||||||
await warm.evaluate(async () => {
|
if (start === "saved-reads") {
|
||||||
localStorage.clear();
|
// 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();
|
sessionStorage.clear();
|
||||||
for (const db of (await indexedDB.databases?.()) ?? []) if (db.name) indexedDB.deleteDatabase(db.name);
|
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);
|
for (const key of (await caches?.keys?.()) ?? []) await caches.delete(key);
|
||||||
});
|
}, { start, prefix: SAVED_READS_PREFIX });
|
||||||
await warm.close();
|
await cleaner.close();
|
||||||
}
|
}
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
// Delay API requests through CDP request interception. Playwright routing
|
// 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([]);
|
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("cold direct task load benchmark", async ({ browser, baseURL, request }) => {
|
||||||
test.skip(RUNS === 0, "Set PAPERCLIP_ISSUE_PERF_COLD_RUNS to run the benchmark.");
|
test.skip(RUNS === 0, "Set PAPERCLIP_ISSUE_PERF_COLD_RUNS to run the benchmark.");
|
||||||
test.setTimeout(15 * 60_000);
|
test.setTimeout(15 * 60_000);
|
||||||
@@ -208,3 +248,69 @@ test("cold direct task load benchmark", async ({ browser, baseURL, request }) =>
|
|||||||
console.log(`\n${report}\n`);
|
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`);
|
||||||
|
});
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import type { IssueDocument } from "@paperclipai/shared";
|
import type { IssueDocument } from "@paperclipai/shared";
|
||||||
import { ApiError } from "@/api/client";
|
import { ApiError } from "@/api/client";
|
||||||
import { issuesApi } from "@/api/issues";
|
import { issuesApi } from "@/api/issues";
|
||||||
|
import { readFromIssueChatBootstrap } from "@/lib/issue-chat-bootstrap";
|
||||||
import { queryKeys } from "@/lib/queryKeys";
|
import { queryKeys } from "@/lib/queryKeys";
|
||||||
|
|
||||||
const PLAN_DOCUMENT_STALE_TIME_MS = 30_000;
|
const PLAN_DOCUMENT_STALE_TIME_MS = 30_000;
|
||||||
@@ -11,20 +12,23 @@ const PLAN_DOCUMENT_STALE_TIME_MS = 30_000;
|
|||||||
* "no plan yet" answer, not an error). Shared by the redesigned thread (its
|
* "no plan yet" answer, not an error). Shared by the redesigned thread (its
|
||||||
* "Plan updated" marker) and the properties pane's Plan tab, so both consume
|
* "Plan updated" marker) and the properties pane's Plan tab, so both consume
|
||||||
* one cached fetch. Keyed under queryKeys.issues.documents so document-scope
|
* one cached fetch. Keyed under queryKeys.issues.documents so document-scope
|
||||||
* invalidations refresh it.
|
* invalidations refresh it. A first read while the task's chat bootstrap is
|
||||||
|
* loading uses the plan projection of its task instead of another request.
|
||||||
*/
|
*/
|
||||||
export function useIssuePlanDocument(issueId: string | null | undefined) {
|
export function useIssuePlanDocument(issueId: string | null | undefined) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const queryKey = [...queryKeys.issues.documents(issueId ?? ""), "plan"];
|
||||||
return useQuery<IssueDocument | null>({
|
return useQuery<IssueDocument | null>({
|
||||||
queryKey: [...queryKeys.issues.documents(issueId ?? ""), "plan"],
|
queryKey,
|
||||||
enabled: Boolean(issueId) && !issueId?.startsWith("chat:"),
|
enabled: Boolean(issueId) && !issueId?.startsWith("chat:"),
|
||||||
staleTime: PLAN_DOCUMENT_STALE_TIME_MS,
|
staleTime: PLAN_DOCUMENT_STALE_TIME_MS,
|
||||||
queryFn: async () => {
|
queryFn: () => readFromIssueChatBootstrap(queryClient, queryKey, issueId!, (item) => item.issue.planDocument, async () => {
|
||||||
try {
|
try {
|
||||||
return await issuesApi.getDocument(issueId!, "plan");
|
return await issuesApi.getDocument(issueId!, "plan");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ApiError && error.status === 404) return null;
|
if (error instanceof ApiError && error.status === 404) return null;
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
},
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ import { ISSUE_CHAT_BOOTSTRAP_MAX_IDS } from "@paperclipai/shared";
|
|||||||
import { api } from "@/api/client";
|
import { api } from "@/api/client";
|
||||||
import { issuesApi } from "@/api/issues";
|
import { issuesApi } from "@/api/issues";
|
||||||
import { EARLY_CHAT_BOOTSTRAP_GLOBAL } from "@/lib/issue-detail-preload-events";
|
import { EARLY_CHAT_BOOTSTRAP_GLOBAL } from "@/lib/issue-detail-preload-events";
|
||||||
|
import { isRestoredSavedRead } from "@/lib/persisted-query-cache";
|
||||||
import { queryKeys } from "@/lib/queryKeys";
|
import { queryKeys } from "@/lib/queryKeys";
|
||||||
import {
|
import {
|
||||||
hasFreshIssueChatFirstFrame,
|
hasFreshIssueChatFirstFrame,
|
||||||
@@ -275,14 +276,23 @@ function startSingle(queryClient: QueryClient, ref: string) {
|
|||||||
* is loading, loaded recently, or the task's first frame is cached and fresh.
|
* is loading, loaded recently, or the task's first frame is cached and fresh.
|
||||||
* Without a company it uses the single-task route. Resolves when the task's
|
* Without a company it uses the single-task route. Resolves when the task's
|
||||||
* bootstrap (new or already loading) settles; it never rejects.
|
* bootstrap (new or already loading) settles; it never rejects.
|
||||||
|
*
|
||||||
|
* `aliases` are other refs the caller already knows the task by (a restored
|
||||||
|
* task's id): reads keyed by them share the request while it is loading.
|
||||||
*/
|
*/
|
||||||
export function startIssueChatBootstrap(
|
export function startIssueChatBootstrap(
|
||||||
queryClient: QueryClient,
|
queryClient: QueryClient,
|
||||||
companyId: string | null | undefined,
|
companyId: string | null | undefined,
|
||||||
ref: string | null | undefined,
|
ref: string | null | undefined,
|
||||||
|
aliases: readonly (string | null | undefined)[] = [],
|
||||||
): Promise<unknown> {
|
): Promise<unknown> {
|
||||||
if (!ref) return Promise.resolve();
|
if (!ref) return Promise.resolve();
|
||||||
const settled = () => currentEntry(queryClient, ref)?.promise ?? Promise.resolve();
|
const settled = () => {
|
||||||
|
const entry = currentEntry(queryClient, ref);
|
||||||
|
if (!entry) return Promise.resolve();
|
||||||
|
for (const alias of aliases) if (alias && !currentEntry(queryClient, alias)) entries.set(refKey(alias), entry);
|
||||||
|
return entry.promise;
|
||||||
|
};
|
||||||
if (currentEntry(queryClient, ref)) return settled();
|
if (currentEntry(queryClient, ref)) return settled();
|
||||||
if (adoptEarlyChatBootstrap(queryClient, companyId, ref)) return settled();
|
if (adoptEarlyChatBootstrap(queryClient, companyId, ref)) return settled();
|
||||||
if (companyId) {
|
if (companyId) {
|
||||||
@@ -297,8 +307,10 @@ export function startIssueChatBootstrap(
|
|||||||
/**
|
/**
|
||||||
* For a task page's first read of `key`: when this account's bootstrap for
|
* For a task page's first read of `key`: when this account's bootstrap for
|
||||||
* the task is loading or just arrived, use its part of the answer instead of
|
* the task is loading or just arrived, use its part of the answer instead of
|
||||||
* sending another request. A key that already holds data is being refreshed
|
* sending another request. A key that already holds data read in this
|
||||||
* (after a write, an invalidation or a poll), so it always asks the server.
|
* document is being refreshed (after a write, an invalidation or a poll), so
|
||||||
|
* it always asks the server. Data restored from the saved read cache has not
|
||||||
|
* been read yet: its first revalidation shares the bootstrap like an empty key.
|
||||||
* Falls back to the normal read when there is no bootstrap, or it lacks the task.
|
* Falls back to the normal read when there is no bootstrap, or it lacks the task.
|
||||||
*/
|
*/
|
||||||
export async function readFromIssueChatBootstrap<T>(
|
export async function readFromIssueChatBootstrap<T>(
|
||||||
@@ -308,7 +320,7 @@ export async function readFromIssueChatBootstrap<T>(
|
|||||||
pick: (item: ChatBootstrapItem) => T | undefined,
|
pick: (item: ChatBootstrapItem) => T | undefined,
|
||||||
read: () => Promise<T>,
|
read: () => Promise<T>,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
if (queryClient.getQueryData(key) !== undefined) return read();
|
if (queryClient.getQueryData(key) !== undefined && !isRestoredSavedRead(queryClient, key)) return read();
|
||||||
const entry = currentEntry(queryClient, ref);
|
const entry = currentEntry(queryClient, ref);
|
||||||
// Only share an answer that is still loading or a moment old.
|
// Only share an answer that is still loading or a moment old.
|
||||||
if (entry && (entry.settledAt === undefined || Date.now() - entry.settledAt < SHARE_WINDOW_MS)) {
|
if (entry && (entry.settledAt === undefined || Date.now() - entry.settledAt < SHARE_WINDOW_MS)) {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import type { RunForIssue } from "@/api/activity";
|
|||||||
import type { ActiveRunForIssue, LiveRunForIssue } from "@/api/heartbeats";
|
import type { ActiveRunForIssue, LiveRunForIssue } from "@/api/heartbeats";
|
||||||
import { seedIssueIdBatch } from "@/hooks/useIssueIdBatches";
|
import { seedIssueIdBatch } from "@/hooks/useIssueIdBatches";
|
||||||
import { seedIssueDetailProjections } from "./issueDetailCache";
|
import { seedIssueDetailProjections } from "./issueDetailCache";
|
||||||
|
import { isRestoredSavedRead } from "./persisted-query-cache";
|
||||||
import {
|
import {
|
||||||
buildRecentIssueRunWindow,
|
buildRecentIssueRunWindow,
|
||||||
issueCommentInputFactsQueryKey,
|
issueCommentInputFactsQueryKey,
|
||||||
@@ -71,13 +72,17 @@ export function hasFreshIssueChatFirstFrame(queryClient: QueryClient, refs: read
|
|||||||
* A key with a read in flight or a pending invalidation is left to that read.
|
* A key with a read in flight or a pending invalidation is left to that read.
|
||||||
* `replace` endpoints return the whole answer, so older cached data may be
|
* `replace` endpoints return the whole answer, so older cached data may be
|
||||||
* replaced. The others merge what the open page observed (comments, activity,
|
* replaced. The others merge what the open page observed (comments, activity,
|
||||||
* runs), so only an empty key is filled.
|
* runs), so only an empty key is filled. Data restored from the saved read
|
||||||
|
* cache is a stand-in no read has confirmed, so the answer replaces it.
|
||||||
*/
|
*/
|
||||||
function seedKey(queryClient: QueryClient, key: QueryKey, data: unknown, requestedAt: number, replace: boolean) {
|
function seedKey(queryClient: QueryClient, key: QueryKey, data: unknown, requestedAt: number, replace: boolean) {
|
||||||
// A missing field (an older server, or a partial answer) is not an empty answer.
|
// A missing field (an older server, or a partial answer) is not an empty answer.
|
||||||
if (data === undefined) return false;
|
if (data === undefined) return false;
|
||||||
const state = queryClient.getQueryState(key);
|
const state = queryClient.getQueryState(key);
|
||||||
if (state) {
|
if (state && isRestoredSavedRead(queryClient, key)) {
|
||||||
|
// A revalidation already running shares this answer, or asks the server.
|
||||||
|
if (state.fetchStatus === "fetching") return false;
|
||||||
|
} else if (state) {
|
||||||
if (state.fetchStatus === "fetching" || state.isInvalidated) return false;
|
if (state.fetchStatus === "fetching" || state.isInvalidated) return false;
|
||||||
if (state.data !== undefined && (!replace || state.dataUpdatedAt >= requestedAt)) return false;
|
if (state.data !== undefined && (!replace || state.dataUpdatedAt >= requestedAt)) return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ import {
|
|||||||
recentIssueActivityQueryKey,
|
recentIssueActivityQueryKey,
|
||||||
recentIssueRunWindowQueryKey,
|
recentIssueRunWindowQueryKey,
|
||||||
} from "./issue-chat-history-queries";
|
} from "./issue-chat-history-queries";
|
||||||
import { startIssueChatBootstrap } from "./issue-chat-bootstrap";
|
import { readFromIssueChatBootstrap, startIssueChatBootstrap } from "./issue-chat-bootstrap";
|
||||||
|
import { isRestoredSavedRead } from "./persisted-query-cache";
|
||||||
import { queryKeys } from "@/lib/queryKeys";
|
import { queryKeys } from "@/lib/queryKeys";
|
||||||
import { getNextIssueCommentPageParam, ISSUE_COMMENT_PAGE_SIZE } from "@/lib/optimistic-issue-comments";
|
import { getNextIssueCommentPageParam, ISSUE_COMMENT_PAGE_SIZE } from "@/lib/optimistic-issue-comments";
|
||||||
|
|
||||||
@@ -135,7 +136,7 @@ export function seedIssueDetailProjections(
|
|||||||
// Only the response's own refs are aliases; an arbitrary requested ref is not.
|
// Only the response's own refs are aliases; an arbitrary requested ref is not.
|
||||||
for (const ref of getIssueDetailCacheRefs(issue)) {
|
for (const ref of getIssueDetailCacheRefs(issue)) {
|
||||||
const key = [...queryKeys.issues.detail(ref), "core"];
|
const key = [...queryKeys.issues.detail(ref), "core"];
|
||||||
if (queryClient.getQueryData(key) === undefined) {
|
if (queryClient.getQueryData(key) === undefined || isRestoredSavedRead(queryClient, key)) {
|
||||||
queryClient.setQueryData(key, issue);
|
queryClient.setQueryData(key, issue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -159,7 +160,14 @@ export function getIssueCoreQueryOptions(queryClient: QueryClient, issueRef: str
|
|||||||
return {
|
return {
|
||||||
queryKey: [...queryKeys.issues.detail(issueRef), "core"] as const,
|
queryKey: [...queryKeys.issues.detail(issueRef), "core"] as const,
|
||||||
queryFn: async ({ signal }: { signal: AbortSignal }) => {
|
queryFn: async ({ signal }: { signal: AbortSignal }) => {
|
||||||
const issue = await issuesApi.getCore(issueRef, { signal });
|
const key = [...queryKeys.issues.detail(issueRef), "core"];
|
||||||
|
const read = () => issuesApi.getCore(issueRef, { signal });
|
||||||
|
// The header shows a restored task at once, so its revalidation can
|
||||||
|
// wait for the page's chat bootstrap. Otherwise this small read keeps
|
||||||
|
// the header from waiting on the larger bootstrap.
|
||||||
|
const issue = isRestoredSavedRead(queryClient, key)
|
||||||
|
? await readFromIssueChatBootstrap(queryClient, key, issueRef, (item) => item.issue, read)
|
||||||
|
: await read();
|
||||||
seedIssueDetailProjections(queryClient, issue, issueRef);
|
seedIssueDetailProjections(queryClient, issue, issueRef);
|
||||||
return issue;
|
return issue;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ const MAX_LINK_PREVIEWS = 100;
|
|||||||
const MAX_RECORD_BYTES = 2 * 1024 * 1024;
|
const MAX_RECORD_BYTES = 2 * 1024 * 1024;
|
||||||
const REVISION_PREFIX = "paperclip:query-cache-revision:";
|
const REVISION_PREFIX = "paperclip:query-cache-revision:";
|
||||||
const controllers = new WeakMap<QueryClient, { clear: () => void }>();
|
const controllers = new WeakMap<QueryClient, { clear: () => void }>();
|
||||||
|
/** Per client: each restored query's hash and the read time it was restored with. */
|
||||||
|
const restoredReads = new WeakMap<QueryClient, Map<string, number>>();
|
||||||
type CacheStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
|
type CacheStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
|
||||||
type Envelope = { version: 1; userId: string; companyId: string | null; buildId: string; revision: string | null; savedAt: number; state: DehydratedState };
|
type Envelope = { version: 1; userId: string; companyId: string | null; buildId: string; revision: string | null; savedAt: number; state: DehydratedState };
|
||||||
const object = (value: unknown): Record<string, unknown> | null => value != null && typeof value === "object" ? value as Record<string, unknown> : null;
|
const object = (value: unknown): Record<string, unknown> | null => value != null && typeof value === "object" ? value as Record<string, unknown> : null;
|
||||||
@@ -79,6 +81,18 @@ function removeUserRecords(storage: CacheStorage, userId: string, keepRevision?:
|
|||||||
if (storage.getItem(QUERY_CACHE_ACTIVE) === userId && !storage.getItem(recordKey(userId, null))) storage.removeItem(QUERY_CACHE_ACTIVE);
|
if (storage.getItem(QUERY_CACHE_ACTIVE) === userId && !storage.getItem(recordKey(userId, null))) storage.removeItem(QUERY_CACHE_ACTIVE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True while `key` holds only what this document restored from the saved read
|
||||||
|
* cache: no read in this document has answered it yet. Such data is shown at
|
||||||
|
* once, but its next read is a revalidation that may share a page bootstrap
|
||||||
|
* instead of always asking the server.
|
||||||
|
*/
|
||||||
|
export function isRestoredSavedRead(client: QueryClient, key: readonly unknown[]) {
|
||||||
|
const state = client.getQueryState(key);
|
||||||
|
if (state?.data === undefined) return false;
|
||||||
|
return restoredReads.get(client)?.get(hashKey(key)) === state.dataUpdatedAt;
|
||||||
|
}
|
||||||
|
|
||||||
export function clearPersistedQueryCache(client: QueryClient) {
|
export function clearPersistedQueryCache(client: QueryClient) {
|
||||||
controllers.get(client)?.clear();
|
controllers.get(client)?.clear();
|
||||||
}
|
}
|
||||||
@@ -314,6 +328,9 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
|||||||
fetchMeta: null, isInvalidated: query.queryKey[0] !== "link-preview", status: "success" as const, fetchStatus: "idle" as const,
|
fetchMeta: null, isInvalidated: query.queryKey[0] !== "link-preview", status: "success" as const, fetchStatus: "idle" as const,
|
||||||
} }));
|
} }));
|
||||||
hydrate(client, { mutations: [], queries });
|
hydrate(client, { mutations: [], queries });
|
||||||
|
let restored = restoredReads.get(client);
|
||||||
|
if (!restored) restoredReads.set(client, restored = new Map());
|
||||||
|
for (const query of queries) restored.set(query.queryHash, query.state.dataUpdatedAt);
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
const current = client.getQueryState(queryKeys.auth.session);
|
const current = client.getQueryState(queryKeys.auth.session);
|
||||||
@@ -396,6 +413,8 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
|||||||
};
|
};
|
||||||
const unsubscribe = client.getQueryCache().subscribe(event => {
|
const unsubscribe = client.getQueryCache().subscribe(event => {
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
|
// Any answer or local write replaces what was restored.
|
||||||
|
if (event.type === "updated" && event.action.type === "success") restoredReads.get(client)?.delete(event.query.queryHash);
|
||||||
const sessionEvent = hashKey(event.query.queryKey) === hashKey(queryKeys.auth.session);
|
const sessionEvent = hashKey(event.query.queryKey) === hashKey(queryKeys.auth.session);
|
||||||
const completedRead = sessionEvent && event.type === "updated" && event.action.type === "success" && !event.action.manual
|
const completedRead = sessionEvent && event.type === "updated" && event.action.type === "success" && !event.action.manual
|
||||||
? sessionReads.get(event.query) : undefined;
|
? sessionReads.get(event.query) : undefined;
|
||||||
|
|||||||
@@ -0,0 +1,212 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { QueryClient } from "@tanstack/react-query";
|
||||||
|
import type { Issue, IssueDocument, IssueRecentComments } from "@paperclipai/shared";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { ApiError } from "@/api/client";
|
||||||
|
import { EARLY_CHAT_BOOTSTRAP_GLOBAL } from "./issue-detail-preload-events";
|
||||||
|
import {
|
||||||
|
readFromIssueChatBootstrap,
|
||||||
|
resetIssueChatBootstrapsForTest,
|
||||||
|
startIssueChatBootstrap,
|
||||||
|
type ChatBootstrapItem,
|
||||||
|
} from "./issue-chat-bootstrap";
|
||||||
|
import { recentIssueActivityQueryKey } from "./issue-chat-history-queries";
|
||||||
|
import { getIssueCoreQueryOptions } from "./issueDetailCache";
|
||||||
|
import { isRestoredSavedRead, startPersistedQueryCache } from "./persisted-query-cache";
|
||||||
|
import { queryKeys } from "./queryKeys";
|
||||||
|
|
||||||
|
// A hard load of a task that the saved read cache remembers: the task's core
|
||||||
|
// fields are restored (and shown at once), its chat history is not saved, and
|
||||||
|
// the page's chat bootstrap revalidates both.
|
||||||
|
|
||||||
|
const api = vi.hoisted(() => ({ chatBootstrap: vi.fn(), getCore: vi.fn(), getSession: vi.fn() }));
|
||||||
|
vi.mock("@/api/issues", () => ({ issuesApi: { chatBootstrap: api.chatBootstrap, getCore: api.getCore } }));
|
||||||
|
vi.mock("@/api/auth", () => ({ authApi: { getSession: api.getSession } }));
|
||||||
|
|
||||||
|
class MemoryStorage {
|
||||||
|
values = new Map<string, string>();
|
||||||
|
get length() { return this.values.size; }
|
||||||
|
key(index: number) { return [...this.values.keys()][index] ?? null; }
|
||||||
|
getItem(key: string) { return this.values.get(key) ?? null; }
|
||||||
|
setItem(key: string, value: string) { this.values.set(key, value); }
|
||||||
|
removeItem(key: string) { this.values.delete(key); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const TASK_ID = "00000000-0000-4000-8000-000000000007";
|
||||||
|
const REF = "ABC-7";
|
||||||
|
const coreKey = (ref: string) => [...queryKeys.issues.detail(ref), "core"];
|
||||||
|
const savedTask = { id: TASK_ID, identifier: REF, companyId: "company-one", title: "Saved title", status: "todo" };
|
||||||
|
const session = (id: string) => ({ session: { id: `session-${id}`, userId: id }, user: { id, name: id, email: `${id}@example.test`, image: null } });
|
||||||
|
|
||||||
|
function answer(overrides: Partial<ChatBootstrapItem> = {}): ChatBootstrapItem {
|
||||||
|
const comment = { id: "comment-1", body: "Latest reply", createdAt: "2026-11-14T00:00:00Z" };
|
||||||
|
return {
|
||||||
|
ref: REF,
|
||||||
|
issue: { ...savedTask, title: "Current title" } as unknown as Issue,
|
||||||
|
recentComments: { comments: [comment], latestCommentId: comment.id, hasMore: false } as unknown as IssueRecentComments,
|
||||||
|
commentInputFacts: [],
|
||||||
|
recentActivity: [{ id: "event-1" }] as never,
|
||||||
|
recentRuns: [],
|
||||||
|
interactions: [],
|
||||||
|
attachments: [],
|
||||||
|
liveRuns: [],
|
||||||
|
activeRun: null,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const disposers: Array<() => void> = [];
|
||||||
|
/** A new page whose saved read cache remembers `savedTask` for alice. */
|
||||||
|
function restoredPage(storage = savedStorage()) {
|
||||||
|
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||||
|
const handle = startPersistedQueryCache(client, { storage, buildId: "build-one", eventTarget: null, debounceMs: 100_000 });
|
||||||
|
disposers.push(() => { handle.dispose(); client.clear(); });
|
||||||
|
return { client, handle, storage };
|
||||||
|
}
|
||||||
|
|
||||||
|
function savedStorage() {
|
||||||
|
const storage = new MemoryStorage();
|
||||||
|
const client = new QueryClient();
|
||||||
|
const handle = startPersistedQueryCache(client, { storage, buildId: "build-one", eventTarget: null, debounceMs: 100_000 });
|
||||||
|
client.setQueryData(queryKeys.auth.session, session("alice"));
|
||||||
|
client.setQueryData(queryKeys.companies.list("alice"), { companies: [{ id: "company-one", name: "Example" }], unauthorized: false });
|
||||||
|
for (const ref of [REF, TASK_ID]) client.setQueryData(coreKey(ref), savedTask);
|
||||||
|
handle.flush();
|
||||||
|
handle.dispose();
|
||||||
|
client.clear();
|
||||||
|
return storage;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The fetch a hard load's inline script starts before the app runs. */
|
||||||
|
function earlyBootstrap(promise: Promise<ChatBootstrapItem | null>) {
|
||||||
|
(window as unknown as Record<string, unknown>)[EARLY_CHAT_BOOTSTRAP_GLOBAL] = { ref: REF, startedAt: Date.now(), promise };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The page's own revalidation of the restored core task, as `useQuery` runs it. */
|
||||||
|
function revalidateCore(client: QueryClient, ref = REF) {
|
||||||
|
return client.fetchQuery({ ...getIssueCoreQueryOptions(client, ref), queryFn: ({ signal }) => getIssueCoreQueryOptions(client, ref).queryFn({ signal }) });
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetIssueChatBootstrapsForTest();
|
||||||
|
api.chatBootstrap.mockReset();
|
||||||
|
api.getCore.mockReset();
|
||||||
|
api.getCore.mockImplementation(async () => ({ ...savedTask, title: "Read on its own" }));
|
||||||
|
});
|
||||||
|
afterEach(() => {
|
||||||
|
for (const dispose of disposers.splice(0)) dispose();
|
||||||
|
delete (window as unknown as Record<string, unknown>)[EARLY_CHAT_BOOTSTRAP_GLOBAL];
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("a task restored from the saved read cache", () => {
|
||||||
|
it("is shown at once and marked as not yet read in this page", () => {
|
||||||
|
const { client } = restoredPage();
|
||||||
|
expect(client.getQueryData(coreKey(REF))).toMatchObject({ title: "Saved title" });
|
||||||
|
expect(isRestoredSavedRead(client, coreKey(REF))).toBe(true);
|
||||||
|
// Chat history is never saved, so the chat opens like a cold one.
|
||||||
|
expect(client.getQueryData([...queryKeys.issues.comments(REF), "recent"])).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("revalidates through the page's bootstrap: one request refreshes the restored task and fills the chat", async () => {
|
||||||
|
const { client } = restoredPage();
|
||||||
|
let respond!: (item: ChatBootstrapItem) => void;
|
||||||
|
earlyBootstrap(new Promise((resolve) => { respond = resolve; }));
|
||||||
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID, REF]);
|
||||||
|
const core = revalidateCore(client);
|
||||||
|
respond(answer());
|
||||||
|
await expect(core).resolves.toMatchObject({ title: "Current title" });
|
||||||
|
expect(api.getCore).not.toHaveBeenCalled();
|
||||||
|
// Every ref the task is known by now holds the current answer, read in this page.
|
||||||
|
for (const ref of [REF, TASK_ID]) {
|
||||||
|
expect(client.getQueryData(coreKey(ref))).toMatchObject({ title: "Current title" });
|
||||||
|
expect(isRestoredSavedRead(client, coreKey(ref))).toBe(false);
|
||||||
|
expect(client.getQueryState(coreKey(ref))?.isInvalidated).toBe(false);
|
||||||
|
}
|
||||||
|
expect(client.getQueryData([...queryKeys.issues.comments(REF), "recent"])).toMatchObject({ latestCommentId: "comment-1" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets reads keyed by the restored task's id share the bootstrap while it is loading", async () => {
|
||||||
|
const { client } = restoredPage();
|
||||||
|
let respond!: (item: ChatBootstrapItem) => void;
|
||||||
|
earlyBootstrap(new Promise((resolve) => { respond = resolve; }));
|
||||||
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
||||||
|
const ownRead = vi.fn(async () => null);
|
||||||
|
const plan = readFromIssueChatBootstrap<IssueDocument | null | undefined>(client, [...queryKeys.issues.documents(TASK_ID), "plan"], TASK_ID, (item) => item.issue.planDocument, ownRead);
|
||||||
|
respond(answer({ issue: { ...answer().issue, planDocument: { key: "plan", body: "# Plan" } } as unknown as Issue }));
|
||||||
|
await expect(plan).resolves.toMatchObject({ key: "plan" });
|
||||||
|
expect(ownRead).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads the task itself when no bootstrap is loading (a stale page refresh)", async () => {
|
||||||
|
const { client } = restoredPage();
|
||||||
|
await expect(revalidateCore(client)).resolves.toMatchObject({ title: "Read on its own" });
|
||||||
|
expect(api.getCore).toHaveBeenCalledOnce();
|
||||||
|
expect(isRestoredSavedRead(client, coreKey(REF))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to its own reads when the bootstrap fails, replacing the restored task", async () => {
|
||||||
|
const { client } = restoredPage();
|
||||||
|
earlyBootstrap(Promise.resolve(null));
|
||||||
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
||||||
|
await expect(revalidateCore(client)).resolves.toMatchObject({ title: "Read on its own" });
|
||||||
|
expect(api.getCore).toHaveBeenCalledOnce();
|
||||||
|
expect(client.getQueryData(coreKey(REF))).toMatchObject({ title: "Read on its own" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses the fields a partial answer has and reads the missing ones itself", async () => {
|
||||||
|
const { client } = restoredPage();
|
||||||
|
earlyBootstrap(Promise.resolve(answer({ recentActivity: undefined as never })));
|
||||||
|
await startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
||||||
|
expect(client.getQueryData(coreKey(REF))).toMatchObject({ title: "Current title" });
|
||||||
|
expect(client.getQueryData(recentIssueActivityQueryKey(REF))).toBeUndefined();
|
||||||
|
const ownRead = vi.fn(async () => [{ id: "own-event" }]);
|
||||||
|
await expect(readFromIssueChatBootstrap(client, recentIssueActivityQueryKey(REF), REF, (item) => item.recentActivity, ownRead))
|
||||||
|
.resolves.toEqual([{ id: "own-event" }]);
|
||||||
|
expect(ownRead).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes the restored task when the user can no longer read it", async () => {
|
||||||
|
const { client, storage } = restoredPage();
|
||||||
|
// An unreadable task is omitted from (or fails) the bootstrap.
|
||||||
|
earlyBootstrap(Promise.resolve(null));
|
||||||
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
||||||
|
api.getCore.mockImplementation(async () => { throw new ApiError("Forbidden", 403, null); });
|
||||||
|
await expect(revalidateCore(client)).rejects.toThrow("Forbidden");
|
||||||
|
for (const ref of [REF, TASK_ID]) expect(client.getQueryData(coreKey(ref))).toBeUndefined();
|
||||||
|
expect([...storage.values.values()].join(" ")).not.toContain("Saved title");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never fills another company's task from the bootstrap", async () => {
|
||||||
|
const { client } = restoredPage();
|
||||||
|
earlyBootstrap(Promise.resolve(answer({ issue: { ...answer().issue, companyId: "company-two" } as unknown as Issue })));
|
||||||
|
await startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
||||||
|
expect(client.getQueryData(coreKey(REF))).toMatchObject({ title: "Saved title" });
|
||||||
|
expect(client.getQueryData([...queryKeys.issues.comments(REF), "recent"])).toBeUndefined();
|
||||||
|
await expect(revalidateCore(client)).resolves.toMatchObject({ title: "Read on its own" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never uses an answer once another user signs in", async () => {
|
||||||
|
const { client } = restoredPage();
|
||||||
|
let respond!: (item: ChatBootstrapItem) => void;
|
||||||
|
earlyBootstrap(new Promise((resolve) => { respond = resolve; }));
|
||||||
|
// The restored session is alice's; the early fetch belongs to her.
|
||||||
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
||||||
|
client.setQueryData(queryKeys.auth.session, session("bob"));
|
||||||
|
respond(answer());
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(client.getQueryData([...queryKeys.issues.comments(REF), "recent"])).toBeUndefined();
|
||||||
|
expect(client.getQueryData(coreKey(REF))).not.toMatchObject({ title: "Current title" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is not restored for another user", () => {
|
||||||
|
const storage = savedStorage();
|
||||||
|
const client = new QueryClient();
|
||||||
|
client.setQueryData(queryKeys.auth.session, session("bob"));
|
||||||
|
const handle = startPersistedQueryCache(client, { storage, buildId: "build-one", eventTarget: null, debounceMs: 100_000 });
|
||||||
|
disposers.push(() => { handle.dispose(); client.clear(); });
|
||||||
|
expect(client.getQueryData(coreKey(REF))).toBeUndefined();
|
||||||
|
expect(isRestoredSavedRead(client, coreKey(REF))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -90,6 +90,7 @@ import {
|
|||||||
type RecentIssueRunWindow,
|
type RecentIssueRunWindow,
|
||||||
} from "../lib/issue-chat-history-queries";
|
} from "../lib/issue-chat-history-queries";
|
||||||
import { readFromIssueChatBootstrap, sameIds, startIssueChatBootstrap } from "../lib/issue-chat-bootstrap";
|
import { readFromIssueChatBootstrap, sameIds, startIssueChatBootstrap } from "../lib/issue-chat-bootstrap";
|
||||||
|
import { isRestoredSavedRead } from "../lib/persisted-query-cache";
|
||||||
import {
|
import {
|
||||||
heartbeatsApi,
|
heartbeatsApi,
|
||||||
type ActiveRunForIssue,
|
type ActiveRunForIssue,
|
||||||
@@ -3387,10 +3388,15 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
|||||||
|
|
||||||
// A cold open sends one bootstrap request for everything the chat's first
|
// A cold open sends one bootstrap request for everything the chat's first
|
||||||
// frame needs; the reads below wait for its answer instead of fanning out.
|
// frame needs; the reads below wait for its answer instead of fanning out.
|
||||||
// A task preloaded by the list is already cached, so this is a no-op.
|
// A task preloaded by the list is already cached, so this is a no-op. A task
|
||||||
|
// restored from the saved read cache shows its header at once but has no
|
||||||
|
// chat history saved, so it opens like a cold one.
|
||||||
const bootstrapCompanyId = companies.find((company) => company.issuePrefix === companyPrefix?.toUpperCase())?.id ?? selectedCompanyId;
|
const bootstrapCompanyId = companies.find((company) => company.issuePrefix === companyPrefix?.toUpperCase())?.id ?? selectedCompanyId;
|
||||||
if (issueId && !conversation && queryClient.getQueryData([...queryKeys.issues.detail(issueId), "core"]) === undefined) {
|
const coreIssueKey = issueId ? [...queryKeys.issues.detail(issueId), "core"] : null;
|
||||||
startIssueChatBootstrap(queryClient, bootstrapCompanyId, issueId);
|
if (issueId && coreIssueKey && !conversation
|
||||||
|
&& (queryClient.getQueryData(coreIssueKey) === undefined || isRestoredSavedRead(queryClient, coreIssueKey))) {
|
||||||
|
const restoredIssue = queryClient.getQueryData<Issue>(coreIssueKey);
|
||||||
|
startIssueChatBootstrap(queryClient, bootstrapCompanyId, issueId, [restoredIssue?.id, restoredIssue?.identifier]);
|
||||||
}
|
}
|
||||||
// The core issue keeps its own small, fast read so the header never waits
|
// The core issue keeps its own small, fast read so the header never waits
|
||||||
// for the larger chat bootstrap; a preloaded task already has it cached.
|
// for the larger chat bootstrap; a preloaded task already has it cached.
|
||||||
|
|||||||
Reference in new issue
Block a user