perf(ui): load the @task mention pool after the task page settles; add a cold-load perf spec (#21557)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People often open a task by its URL, for example from a link in a
message or after a reload
> - #20592 made a hard load of a task URL read the chat's first frame
from one `chat-bootstrap` request
> - The task page still sends a large read as it mounts: 100 full
recently updated tasks for the `@task` mention picker. On staging this
read returned 395 KB and took 3.9 s of server time
> - The hosted database is CPU-bound, so reads that do not affect the
first frame must not compete with the reads that do
> - Also, no test measured a cold direct load under realistic latency or
guarded the one-bootstrap request shape
> - This pull request starts the mention pool after the task page
settles. It also adds a cold-load perf spec with a delay on each API
request and an always-on request-shape test
> - The benefit is less concurrent server work during a cold task open,
and a regression guard for the one-round-trip first frame

## Linked Issues or Issue Description

Refs #20592 (hard-load chat bootstrap that this pull request measures
and guards). Refs #20355 (the `chat-bootstrap` endpoints).

**What existing behavior does this improve?**
The task page loads the `@task` mention pool when it mounts.

**Subsystem affected**
Board UI task page (`ui/src/pages/IssueDetail.tsx`) and the issue-detail
perf harness (`tests/perf/issue-detail`).

**Current behavior**
`GET /api/companies/:id/issues?limit=100&sortField=updated&sortDir=desc`
starts with the chat's first-frame reads. It starts before the first
chat frame in 14 of 14 local cold loads. The picker needs it only after
the person types `@`.

**Proposed behavior**
The read starts after the page has painted and its own reads have
finished. On a page that keeps reading, it starts after at most 5 s.

**Reason and benefit**
The read never affects the first frame. Deferring it removes a large
concurrent read from the busiest part of a cold open.

**Breaking changes**
None. If the person types `@task` in the first moments after a cold
load, the task suggestions can appear about half a second later.

## What Changed

- `ui/src/hooks/usePageSettled.ts`: new hook. It returns `true` once
`whenPageSettles` runs (the page has painted, the tab is visible, no
query is fetching, and the browser is idle), or after
`PAGE_SETTLED_MAX_WAIT_MS` (5 s). The cap keeps a long-running read from
keeping the picker empty.
- `ui/src/pages/IssueDetail.tsx`: the mention-pool query is enabled only
when `usePageSettled()` is true.
- `ui/src/hooks/usePageSettled.test.tsx`: tests that the hook waits for
in-flight reads and that the cap applies.
- `ui/src/pages/IssueDetail.test.tsx`: mocks the hook to `true`, so
existing tests keep their behavior.
- `tests/perf/issue-detail/cold-bootstrap.perf.spec.ts`: new spec. It
delays every API response (300 ms by default) and opens the task URL in
a new browser context, with the JavaScript in the HTTP cache and no app
storage. The finish event is the first readable frame: the history is
revealed, the latest saved message is visible and the composer is
editable.
- The request-shape test always runs. It requires one `chat-bootstrap`
request and no per-endpoint first-frame read before the frame. Reads
that start after the live socket is created are excluded, because they
are its catch-up refresh.
- The benchmark runs only when `PAPERCLIP_ISSUE_PERF_COLD_RUNS` is set.
It writes the median, the spread, the request count before the frame,
the last requests before the frame, the JavaScript bytes transferred and
a request timeline.
- The delay uses CDP `Fetch` interception instead of Playwright routing,
because routing disables the HTTP cache.
- `tests/perf/issue-detail/README.md`: documents the spec.
- My earlier draft also added a deadline for a stalled bootstrap. Master
already has one (`CHAT_BOOTSTRAP_SHARE_DEADLINE_MS`, 5 s), so this pull
request does not include it.

## Verification

Measurement setup:
- Production UI builds of master `4a78124a3e` and of this branch, served
by one local server (`PAPERCLIP_UI_DEV_MIDDLEWARE=false`, embedded
PostgreSQL).
- A delay of 300 ms on each API request.
- Cold direct task URL with 24 saved comments and a plan.
- Master and the branch alternated: 2 rounds of 7 runs each.
- The host was shared with other agent sessions.

| Build | Runs | First readable frame, median | p25–p75 | Min–max | API
requests before frame (median) | Mention pool started before frame |
|---|---:|---:|---:|---:|---:|---:|
| master | 14 | 1,422 ms | 1,336–1,525 | 1,284–7,398 | 50 | 14 / 14 |
| this branch | 14 | 1,390 ms | 1,338–1,457 | 1,272–2,207 | 49 | 0 / 14
|

- The spec adds the API delay through CDP request interception, so the
HTTP cache stays on. The measured loads downloaded 0 KiB of JavaScript
in every run. The spec records this as `jsTransferBytes`. Each build has
one outlier (7,398 ms on master, 2,207 ms on this branch), from host
contention.
- With this branch, the mention pool starts after the frame in every run
(350–400 ms after it in an earlier set).
- The first-frame timing is neutral locally. The local database answers
the pool read in milliseconds, so it does not compete with other reads.
The intended benefit is lower concurrent server load on a busy database.
This pull request does not show it as a local latency gain.
- On master and on this branch, the hard load adopts the bootstrap and
the frame is no longer held by task reads. The frame now comes right
after the shell reads return: `auth/get-session` and
`instance/settings/experimental`, then `companies` and
`workspace-preferences/me`. Profiling marks confirm this: the chat
thread mounts after `workspace-preferences/me` returns, and all
readiness gates are ready within 30 ms.
- The request-shape test passed 5 of 5 on master and 5 of 5 on this
branch.
- `layout-stability.spec.ts`, `plan-startup.spec.ts` and
`cold-bootstrap.perf.spec.ts` against this branch's build: 18 passed.
- `ui` Vitest for `usePageSettled.test.tsx` and `IssueDetail.test.tsx`:
278 passed. The `ui` typecheck passed. `pnpm check:token-gates` passed.
- `pnpm verify` exits 2 because `tests/perf/issue-detail/README.md` is a
global CI input. Required CI supplies the broad coverage.

To reproduce the measurement:

```sh
PAPERCLIP_ISSUE_PERF_BASE_URL=http://127.0.0.1:3287 PAPERCLIP_ISSUE_PERF_COLD_RUNS=7 PAPERCLIP_ISSUE_PERF_LABEL=branch \
  pnpm exec playwright test --config tests/perf/issue-detail/playwright.config.ts cold-bootstrap -g benchmark
```

## Risks

- Low risk. The only product change is when one read starts.
- If the page keeps a query in flight, the pool waits up to 5 s. During
that time, `@task` suggestions list only agents, projects and members.
- The request-shape test treats reads that start after the live socket
is created as catch-up refreshes. If the socket connects before the task
page mounts, such a test would not see a first-frame read that started
later. The test still requires exactly one bootstrap request before the
frame.
- The perf spec is not in the default CI browser suites. It runs when
the issue-detail harness runs.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use (shell, file editing, Playwright browser runs). It wrote
the change, the tests and the measurements.

## 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
- [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-13 22:30:03 -06:00
1 parent 54c3616ad9
commit 8c0c7c6abb
6 files changed
+327 -2

No files matched your search

+29
View File
@@ -56,6 +56,35 @@ harness validates the task identity before measuring. Network spans in the trace
use recorded request start/end timestamps relative to task navigation; they
include completed requests observed during the sample, even after content paint.
## Cold direct task load (chat bootstrap)
A hard load of a task URL starts `GET /api/issues/:ref/chat-bootstrap` from the
inline preload script, before the app's JavaScript loads. The chat's
first-frame reads share that answer (`ui/src/lib/issue-chat-bootstrap.ts`) and
fall back to their own requests when it fails, lacks a field, or stalls.
`cold-bootstrap.perf.spec.ts` delays every API response (300 ms by default)
so serial request stages show up as wall-clock time. It opens the task by URL
in a fresh browser context with the app's JavaScript in the HTTP cache and no
app storage. The finish event is the revealed history with the latest saved
message and an editable composer. Its request-shape test always runs: one
bootstrap request, no per-endpoint first-frame read before the frame, and no
such read completing before it. Reads that start after the live socket
connects are its catch-up refresh and are excluded. The benchmark is opt-in:
```sh
PAPERCLIP_ISSUE_PERF_BASE_URL=http://127.0.0.1:3287 \
PAPERCLIP_ISSUE_PERF_COLD_RUNS=7 PAPERCLIP_ISSUE_PERF_LABEL=candidate \
pnpm exec playwright test --config tests/perf/issue-detail/playwright.config.ts cold-bootstrap -g benchmark
```
It writes `cold-bootstrap-<label>.{json,md}` with the median, spread, the
request count before the frame, the requests that finished last before it,
and the first run's request timeline. `PAPERCLIP_ISSUE_PERF_API_DELAY_MS`
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`).
## Real-instance click harness
Local fixtures cannot reproduce staging's network round trips, server contention
@@ -0,0 +1,210 @@
import fs from "node:fs/promises";
import path from "node:path";
import { expect, test, type APIRequestContext, type Browser } from "@playwright/test";
/**
* Cold direct load of a task URL with every API response delayed, so serial
* request stages show up as wall-clock time. The finish event is the first
* readable chat frame: the history is revealed (`aria-busy="false"`), the saved
* messages are visible and the composer is editable.
*
* `PAPERCLIP_ISSUE_PERF_COLD_RUNS` (>= 5) enables the benchmark and writes
* `test-results/issue-detail-perf/cold-bootstrap-<label>.{json,md}`. The request-shape
* test always runs.
*/
const API_DELAY_MS = Number(process.env.PAPERCLIP_ISSUE_PERF_API_DELAY_MS ?? 300);
const requestedRuns = Number(process.env.PAPERCLIP_ISSUE_PERF_COLD_RUNS ?? 0);
const RUNS = Number.isFinite(requestedRuns) && requestedRuns > 0 ? Math.max(5, Math.floor(requestedRuns)) : 0;
const OUTPUT_DIR = path.resolve(process.cwd(), "test-results/issue-detail-perf");
const LABEL = process.env.PAPERCLIP_ISSUE_PERF_LABEL ?? "candidate";
const COMMENT_COUNT = 24;
// The staging measurement had the app's JavaScript in the HTTP cache. Set
// PAPERCLIP_ISSUE_PERF_COLD_HTTP_CACHE=1 to download it on every run instead.
const WARM_HTTP_CACHE = process.env.PAPERCLIP_ISSUE_PERF_COLD_HTTP_CACHE !== "1";
const LAST_COMMENT = `Cold bootstrap comment ${COMMENT_COUNT}: the latest saved message.`;
type Seed = { companyId: string; prefix: string; issueId: string; identifier: string };
type RequestRecord = { path: string; method: string; startMs: number; endMs: number | null };
type Sample = { run: number; revealMs: number; jsTransferBytes: number; socketMs: number | null; apiRequestsBeforeReveal: number; requests: RequestRecord[]; releasedBy: string[] };
test.use({ serviceWorkers: "block", viewport: { width: 1440, height: 900 } });
async function seed(request: APIRequestContext): Promise<Seed> {
const companyResponse = await request.post("/api/companies", { data: { name: `Cold bootstrap ${Date.now()}` } });
expect(companyResponse.ok(), await companyResponse.text()).toBe(true);
const company = await companyResponse.json();
const issueResponse = await request.post(`/api/companies/${company.id}/issues`, {
data: { title: `Cold bootstrap task ${Date.now()}`, description: "A task opened by a direct URL.", status: "todo" },
});
expect(issueResponse.ok(), await issueResponse.text()).toBe(true);
const issue = await issueResponse.json();
for (let index = 1; index <= COMMENT_COUNT; index += 1) {
const body = index === COMMENT_COUNT ? LAST_COMMENT : `Cold bootstrap comment ${index}: ${"saved conversation text ".repeat(12)}`;
const response = await request.post(`/api/issues/${issue.id}/comments`, { data: { body } });
expect(response.ok(), await response.text()).toBe(true);
}
const planResponse = await request.put(`/api/issues/${issue.id}/documents/plan`, {
data: { format: "markdown", title: "Plan", body: "# Plan\n\nOpen the task in one round trip." },
});
expect(planResponse.ok(), await planResponse.text()).toBe(true);
return { companyId: company.id, prefix: company.issuePrefix, issueId: issue.id, identifier: issue.identifier };
}
function scrub(url: string, seedData: Seed) {
const parsed = new URL(url);
return `${parsed.pathname}${parsed.search}`
.replaceAll(seedData.issueId, ":id")
.replaceAll(seedData.identifier, ":ref")
.replaceAll(seedData.companyId, ":company");
}
async function measure(browser: Browser, baseURL: string, seedData: Seed, run: number): Promise<Sample> {
const context = await browser.newContext({ baseURL, viewport: { width: 1440, height: 900 }, serviceWorkers: "block" });
if (WARM_HTTP_CACHE) {
// Load the app's JavaScript into this context's HTTP cache, then clear
// every app store so the measured load starts without app data.
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();
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();
}
const page = await context.newPage();
// Delay API requests through CDP request interception. Playwright routing
// would disable the HTTP cache and download the warmed JavaScript again.
const cdp = await context.newCDPSession(page);
cdp.on("Fetch.requestPaused", (event: { requestId: string }) => {
setTimeout(() => { void cdp.send("Fetch.continueRequest", { requestId: event.requestId }).catch(() => {}); }, API_DELAY_MS);
});
await cdp.send("Fetch.enable", { patterns: [{ urlPattern: "*/api/*", requestStage: "Request" }] });
const records = new Map<object, RequestRecord>();
let origin = 0;
page.on("request", (req) => {
if (!new URL(req.url()).pathname.startsWith("/api/")) return;
records.set(req, { path: scrub(req.url(), seedData), method: req.method(), startMs: Date.now() - origin, endMs: null });
});
const finish = (req: object) => {
const record = records.get(req);
if (record) record.endMs = Date.now() - origin;
};
let socketMs: number | null = null;
// When the live-update socket is created. It refreshes every open query on
// open, which follows creation, so later reads may be that catch-up.
page.on("websocket", (socket) => {
if (new URL(socket.url()).pathname.startsWith("/api/")) socketMs ??= Date.now() - origin;
});
page.on("requestfinished", finish);
page.on("requestfailed", finish);
// Record the first frame in the page so polling does not add latency.
await page.addInitScript((lastComment) => {
const check = () => {
if ((window as Window & { __coldReveal?: number }).__coldReveal) return;
const ready = document.querySelector('[data-testid="task-chat-thread"] > [aria-busy="false"]');
const composer = document.querySelector('[data-testid="task-chat-composer-stack"] [contenteditable="true"]');
const message = ready && [...ready.querySelectorAll("p, div")].some((el) => el.textContent === lastComment);
if (ready && composer && message) (window as Window & { __coldReveal?: number }).__coldReveal = performance.now();
else requestAnimationFrame(check);
};
requestAnimationFrame(check);
}, LAST_COMMENT);
origin = Date.now();
await page.goto(`/${seedData.prefix}/issues/${seedData.identifier}`);
await page.waitForFunction(() => (window as Window & { __coldReveal?: number }).__coldReveal, null, { timeout: 60_000, polling: 50 });
const { revealMs, navStartEpoch, jsTransferBytes } = await page.evaluate(() => ({
// Bytes of JavaScript fetched over the network; near zero when the HTTP cache served it.
jsTransferBytes: (performance.getEntriesByType("resource") as PerformanceResourceTiming[])
.filter((entry) => entry.initiatorType === "script" || /\.m?js(\?|$)/.test(entry.name))
.reduce((sum, entry) => sum + entry.transferSize, 0),
revealMs: (window as Window & { __coldReveal?: number }).__coldReveal!,
navStartEpoch: performance.timeOrigin,
}));
await page.waitForTimeout(1_500);
await context.close();
// Re-base node-side timestamps on the navigation start.
const shift = navStartEpoch - origin;
const requests = [...records.values()]
.map((record) => ({ ...record, startMs: record.startMs - shift, endMs: record.endMs === null ? null : record.endMs - shift }))
.sort((left, right) => left.startMs - right.startMs);
const before = requests.filter((record) => record.startMs <= revealMs);
const finishedBefore = before.filter((record) => record.endMs !== null && record.endMs <= revealMs);
const lastEnd = Math.max(...finishedBefore.map((record) => record.endMs!));
const releasedBy = finishedBefore.filter((record) => record.endMs! >= lastEnd - 50).map((record) => record.path);
return { run, revealMs, jsTransferBytes, socketMs: socketMs === null ? null : socketMs - shift, apiRequestsBeforeReveal: before.length, requests, releasedBy };
}
function median(values: number[]) {
const sorted = [...values].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
}
// The per-endpoint reads the chat bootstrap answers. The full task read
// (`/api/issues/:ref`) is not among them: it adds related data and never
// gates the first frame.
const FIRST_FRAME_ENDPOINTS = [
/^\/api\/issues\/[^/]+\?view=core$/,
/^\/api\/issues\/[^/]+\/(recent-)?comments(\?|$)/,
/^\/api\/issues\/[^/]+\/activity(\?|$)/,
/^\/api\/issues\/[^/]+\/runs(\?|$)/,
/^\/api\/issues\/[^/]+\/interactions(\?|$)/,
/^\/api\/issues\/[^/]+\/attachments(\?|$)/,
/^\/api\/issues\/[^/]+\/live-runs(\?|$)/,
/^\/api\/issues\/[^/]+\/active-run(\?|$)/,
];
test("a cold direct task load reads its first frame from one chat bootstrap", async ({ browser, baseURL, request }) => {
const seedData = await seed(request);
const sample = await measure(browser, baseURL!, seedData, 1);
await test.info().attach("requests.json", { body: JSON.stringify(sample, null, 2), contentType: "application/json" });
const perEndpoint = (record: RequestRecord) => FIRST_FRAME_ENDPOINTS.some((pattern) => pattern.test(record.path));
const startedBefore = sample.requests.filter((record) => record.startMs <= sample.revealMs);
// Once the live-update socket opens, it refreshes every open query
// to cover events between the initial reads and the subscription. Those
// refreshes are not first-frame reads.
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);
const seedData = await seed(request);
const samples: Sample[] = [];
for (let run = 1; run <= RUNS; run += 1) samples.push(await measure(browser, baseURL!, seedData, run));
const reveals = samples.map((sample) => sample.revealMs);
const counts = samples.map((sample) => sample.apiRequestsBeforeReveal);
const report = [
`# Cold direct task load (${LABEL})`,
"",
`API delay ${API_DELAY_MS} ms per request, ${RUNS} runs, fresh browser context each run, JavaScript ${WARM_HTTP_CACHE ? "in the HTTP cache" : "downloaded"}, no app storage.`,
"",
`- First readable frame: median ${Math.round(median(reveals))} ms, min ${Math.round(Math.min(...reveals))}, max ${Math.round(Math.max(...reveals))}`,
`- API requests started before the frame: median ${median(counts)}, min ${Math.min(...counts)}, max ${Math.max(...counts)}`,
`- JavaScript transferred over the network: median ${Math.round(median(samples.map((sample) => sample.jsTransferBytes)) / 1024)} KiB`,
`- Released by (run 1): ${samples[0]!.releasedBy.join(", ")}`,
"",
"## Run 1 requests (ms from navigation start)",
"",
"| start | end | request |",
"| ---: | ---: | --- |",
...samples[0]!.requests.map((record) => `| ${Math.round(record.startMs)} | ${record.endMs === null ? "pending" : Math.round(record.endMs)} | ${record.method} ${record.path}${record.startMs > samples[0]!.revealMs ? " (after frame)" : ""} |`),
"",
`Frame at ${Math.round(samples[0]!.revealMs)} ms.`,
].join("\n");
await fs.mkdir(OUTPUT_DIR, { recursive: true });
await fs.writeFile(path.join(OUTPUT_DIR, `cold-bootstrap-${LABEL}.json`), JSON.stringify({ apiDelayMs: API_DELAY_MS, samples }, null, 2));
await fs.writeFile(path.join(OUTPUT_DIR, `cold-bootstrap-${LABEL}.md`), report);
console.log(`\n${report}\n`);
});
+52
View File
@@ -0,0 +1,52 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { PAGE_SETTLED_MAX_WAIT_MS, usePageSettled } from "./usePageSettled";
let root: Root, container: HTMLDivElement, client: QueryClient;
let settled: boolean[] = [];
function Probe() {
settled.push(usePageSettled());
return null;
}
async function render() {
await act(async () => root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>));
}
beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.useFakeTimers();
// Frames and idle callbacks run on the fake clock.
vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => setTimeout(() => cb(0), 16) as unknown as number);
vi.stubGlobal("cancelAnimationFrame", (id: number) => clearTimeout(id));
vi.stubGlobal("requestIdleCallback", (cb: () => void) => setTimeout(cb, 50) as unknown as number);
vi.stubGlobal("cancelIdleCallback", (id: number) => clearTimeout(id));
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
settled = [];
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
});
afterEach(async () => {
await act(async () => root.unmount());
container.remove(); client.clear(); vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllGlobals();
});
it("turns true after the page paints and its reads finish", async () => {
let finish!: (value: string) => void;
void client.fetchQuery({ queryKey: ["first-frame"], queryFn: () => new Promise<string>((resolve) => { finish = resolve; }) }).catch(() => {});
await render();
await act(async () => { await vi.advanceTimersByTimeAsync(500); });
expect(settled.at(-1)).toBe(false);
await act(async () => { finish("done"); await vi.advanceTimersByTimeAsync(100); });
expect(settled.at(-1)).toBe(true);
});
it("turns true after the maximum wait on a page that keeps reading", async () => {
void client.fetchQuery({ queryKey: ["never"], queryFn: () => new Promise<string>(() => {}) }).catch(() => {});
await render();
await act(async () => { await vi.advanceTimersByTimeAsync(PAGE_SETTLED_MAX_WAIT_MS - 10); });
expect(settled.at(-1)).toBe(false);
await act(async () => { await vi.advanceTimersByTimeAsync(20); });
expect(settled.at(-1)).toBe(true);
});
+28
View File
@@ -0,0 +1,28 @@
import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { whenPageSettles } from "@/lib/when-page-settles";
/** The longest a settle wait may last on a page that keeps reading. */
export const PAGE_SETTLED_MAX_WAIT_MS = 5_000;
/**
* False on mount, true once the page has painted and its reads have finished
* (see `whenPageSettles`), or after `maxWaitMs` on a page that never settles.
* Use it to start reads that never affect the first frame, so they do not
* compete with the reads that do.
*/
export function usePageSettled(maxWaitMs = PAGE_SETTLED_MAX_WAIT_MS) {
const queryClient = useQueryClient();
const [settled, setSettled] = useState(false);
useEffect(() => {
if (settled) return;
const done = () => setSettled(true);
const cancel = whenPageSettles(queryClient, done);
const timer = window.setTimeout(done, maxWaitMs);
return () => {
cancel();
window.clearTimeout(timer);
};
}, [queryClient, settled, maxWaitMs]);
return settled;
}
+2
View File
@@ -60,6 +60,8 @@ import type { issuesApi } from "../api/issues";
// persistence have their own hook tests; keep their readiness explicit here.
const coordinatorPreference = vi.hoisted(() => ({ enabled: false, loaded: true }));
const inlineEditorFixture = vi.hoisted(() => ({ real: false }));
// Reads deferred until the page settles start at once in these tests.
vi.mock("@/hooks/usePageSettled", () => ({ usePageSettled: () => true, PAGE_SETTLED_MAX_WAIT_MS: 0 }));
vi.mock("../hooks/useCoordinatorWorkspaceEnabled", () => ({
useCoordinatorWorkspaceEnabled: () => coordinatorPreference,
}));
+6 -2
View File
@@ -307,6 +307,7 @@ import {
PopoverContent,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { usePageSettled } from "@/hooks/usePageSettled";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { describeError, isTransientError } from "@/api/errors";
import {
@@ -3784,7 +3785,10 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
enabled: !!selectedCompanyId,
});
// Bounded pool of recently-updated issues to back the `@task` reference picker.
// The picker filters this list client-side by identifier/title.
// The picker filters this list client-side by identifier/title. It is a large
// read (full rows) that never affects the first chat frame, so it starts once
// the page's own reads have finished.
const mentionPoolReady = usePageSettled();
const { data: mentionIssues = EMPTY_ISSUES } = useQuery({
queryKey: resolvedCompanyId
? queryKeys.issues.mentionPool(resolvedCompanyId)
@@ -3795,7 +3799,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
sortField: "updated",
sortDir: "desc",
}),
enabled: !!resolvedCompanyId,
enabled: !!resolvedCompanyId && mentionPoolReady,
staleTime: 60_000,
placeholderData: keepPreviousDataForSameQueryTail<Issue[]>(
resolvedCompanyId ?? "pending",