mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A person opens a task from the sidebar's Recent Tasks, the Inbox or the Tasks list, and the task chat shows its first frame from a `chat-bootstrap` read > - On staging, a task opened from Recent Tasks soon after a page load took 15.3 s to show its chat. The same task from the Inbox took 0.19 s > - Two defects cause this. Every task's bootstrap paid a fixed ~1.8 s for its latest runs. Recent Tasks preloaded ten tasks in one request (17.7 s), and an open waited for that whole request > - Recent Tasks also warmed its tasks only once per page load. Unread cache entries are dropped after five minutes, so its tasks were cold for the rest of the session > - This pull request makes the runs read use indexes, lets an open read its own task instead of waiting for a ten-task preload, and re-warms Recent Tasks on navigation > - The benefit is that a task from Recent Tasks opens as fast as from a task list ## Linked Issues or Issue Description Refs #19818, Refs #16713 (earlier proposals of the same `runsForIssue` rewrite; this PR adds a query-plan regression test and the client fixes). **What happened?** On staging, a click on a Recent Tasks link about 6 s after a page load took 15.3 s until the chat thread showed. The Inbox opened the same task in 0.19 s. **Steps to reproduce** 1. Load a page with a populated Recent Tasks sidebar. 2. Within a few seconds, click a recent task. 3. The chat stays on its loading state for many seconds. **Expected behavior** The task opens about as fast as from the Inbox or the Tasks list. **Root cause (measured on staging)** - `GET /issues/:id/runs?view=recent` took 1.7–1.9 s of server time for tasks with 1 to 24 runs. Every other first-frame read took 80–350 ms. The query filtered with `issue_id = $1 OR EXISTS (activity_log … run_id = heartbeat_runs.id)`, so Postgres walked every run of the company. - The bootstrap reads two tasks at a time, so the Recents preload of ten tasks took 17.7 s. Each task in a batch settles only with the whole request, and the page's reads wait for it (up to the 5 s share deadline, then read again under load). - `useRecentTaskOpenWarmup` remembered preloaded task ids for the life of the page and never preloaded them again. ## What Changed - `activityService.runsForIssue`: select the task's runs by `id IN (runs with issue_id = task UNION run ids from the task's activity)`. Each half uses its own index. The results are the same. - `startIssueChatBootstrap`: when the only request for a task is a background batch that is still loading, send a request for that task alone. All refs of the task point to the new request. The later batch answer only fills keys that are still empty or older. - `loadIssueChatBootstraps` (background): a task whose answer did not arrive is not held back for five minutes, so the next preload can retry it. - `useRecentTaskOpenWarmup`: use the background preload (five-minute repeat, the same as the cache GC time) and run again after each navigation (`navigationKey`). It no longer keeps a per-page-load set. `SidebarRecentTasks` and `CoordinatorSidebar` pass the pathname. ## Verification - `server/src/__tests__/issue-runs-read-cost.test.ts` (new): a company with 20,003 runs, and a task with 3 runs. EXPLAIN ANALYZE of the runs reads examined **40,011** run rows before the fix and **15** after (red/green). The test also checks the run order and the run that is linked only through activity. - `ui/src/lib/issue-chat-bootstrap.test.ts`: a new test opens a task while a ten-task preload is still loading. Before the fix it timed out waiting on the batch. After the fix it reads its own request. A second new test checks that a single-task request is still shared. - `ui/src/hooks/useRecentTaskOpenWarmup.test.tsx`: a new test re-warms Recents on a navigation after five minutes (red on the old hook). Another new test sends nothing for navigations inside five minutes. - Existing suites pass: activity service/routes, task cold open, agent conversations (197 tests); sidebar, Recents, navigation prefetch, issue detail cache, IssueDetail (341 tests). - `tsc --noEmit` is clean for `server` and `ui` (apart from the pre-existing Storybook index errors). - `pnpm verify` exits 2 (an opaque server setup dependency), so CI supplies the broad coverage. - After deploy: on staging, time a Recent Tasks click a few seconds after a cold load, and time `runs?view=recent`. ## Risks - Low risk. The SQL change keeps the same filter. It changes only how Postgres finds the candidate runs. The existing activity tests cover retry, credential and conversation cases. - An open during a background preload now sends one more bootstrap request for that task. This happens only on an open or a resting hover, never for each row. - Recents now sends at most one preload per five minutes while the person navigates. It sends nothing while the tab is idle or hidden. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, browser measurement on staging, code execution). ## 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>
427 lines
19 KiB
TypeScript
427 lines
19 KiB
TypeScript
import type { QueryClient, QueryKey } from "@tanstack/react-query";
|
|
import { ISSUE_CHAT_BOOTSTRAP_MAX_IDS } from "@paperclipai/shared";
|
|
import { api } from "@/api/client";
|
|
import { issuesApi } from "@/api/issues";
|
|
import { EARLY_CHAT_BOOTSTRAP_GLOBAL } from "@/lib/issue-detail-preload-events";
|
|
import { isRestoredSavedRead } from "@/lib/persisted-query-cache";
|
|
import { queryKeys } from "@/lib/queryKeys";
|
|
import {
|
|
hasFreshIssueChatFirstFrame,
|
|
ISSUE_CHAT_BOOTSTRAP_FRESH_MS,
|
|
seedIssueChatBootstrap,
|
|
type IssueChatBootstrapEntry,
|
|
} from "@/lib/issueChatBootstrapCache";
|
|
|
|
// A task opens instantly when everything its chat reads before the first frame
|
|
// is already cached. One bootstrap request returns those reads for up to ten
|
|
// tasks, in the shapes of the per-task endpoints, and `issueChatBootstrapCache`
|
|
// writes them under the exact keys the task page reads. This module decides
|
|
// when to send that request and lets the page's reads share it:
|
|
//
|
|
// - Task lists and the sidebar's Recents preload their top rows in the background.
|
|
// - A cold open (direct link, or a task that was not preloaded) starts one
|
|
// bootstrap for that task, and the page's gating reads wait for it instead of
|
|
// sending about ten requests of their own.
|
|
// - A hard load of a task URL adopts the fetch the HTML started (see
|
|
// `vite-issue-detail-preload`).
|
|
|
|
export type ChatBootstrapItem = IssueChatBootstrapEntry;
|
|
|
|
/**
|
|
* How many top rows of a task list are preloaded: one request. Each task
|
|
* costs the server about fifty queries, and a resting hover warms any other
|
|
* row before it is clicked.
|
|
*/
|
|
export const CHAT_BOOTSTRAP_PRELOAD_LIMIT = ISSUE_CHAT_BOOTSTRAP_MAX_IDS;
|
|
/** How long after it arrives a bootstrap answer may stand in for a page read. */
|
|
const SHARE_WINDOW_MS = 2_000;
|
|
/**
|
|
* How long a page read waits for a loading bootstrap before it reads the
|
|
* server itself. A stalled bootstrap must not keep the chat (or its Retry)
|
|
* from loading.
|
|
*/
|
|
export const CHAT_BOOTSTRAP_SHARE_DEADLINE_MS = 5_000;
|
|
|
|
/**
|
|
* The account a request was sent for: a user id, `null` when the session has
|
|
* no user, or `undefined` while this document has not read its session yet.
|
|
* `revoked` marks a request whose answer must never be used.
|
|
*/
|
|
type Owner = { account: string | null | undefined; revoked: boolean };
|
|
|
|
/**
|
|
* One task's part of a bootstrap request. It is never used by another account.
|
|
* `batched` marks a part of a request for several tasks: it settles only when
|
|
* the slowest of them has been read.
|
|
*/
|
|
type Entry = { promise: Promise<ChatBootstrapItem | undefined>; owner: Owner; startedAt: number; settledAt?: number; batched: boolean };
|
|
const entries = new Map<string, Entry>();
|
|
|
|
function refKey(ref: string) {
|
|
return /^[0-9a-f-]{36}$/i.test(ref) ? ref.toLowerCase() : ref.toUpperCase();
|
|
}
|
|
|
|
/** The session's user id, `null` without a user, `undefined` before the first session read. */
|
|
function sessionAccount(queryClient: QueryClient): string | null | undefined {
|
|
const session = queryClient.getQueryState<{ user?: { id?: unknown } | null } | null>(queryKeys.auth.session)?.data;
|
|
if (session === undefined) return undefined;
|
|
return typeof session?.user?.id === "string" ? session.user.id : null;
|
|
}
|
|
|
|
/**
|
|
* Whether `owner`'s answer may be used now. A request sent before the first
|
|
* session read (a hard load's early fetch) can only have used this
|
|
* document's original sign-in, so it belongs to the first account the
|
|
* session reports; a session without a user revokes it.
|
|
*/
|
|
function ownerMatches(owner: Owner, current: string | null | undefined) {
|
|
if (owner.revoked) return false;
|
|
if (owner.account !== undefined) return owner.account === current;
|
|
if (current === undefined) return true;
|
|
if (current === null) {
|
|
owner.revoked = true;
|
|
return false;
|
|
}
|
|
owner.account = current;
|
|
return true;
|
|
}
|
|
|
|
/** Owners sent before the first session read, bound as soon as the session is known. */
|
|
const pendingOwners = new Set<Owner>();
|
|
let stopWatchingSession: (() => void) | null = null;
|
|
|
|
function newOwner(queryClient: QueryClient): Owner {
|
|
const owner: Owner = { account: sessionAccount(queryClient), revoked: false };
|
|
if (owner.account !== undefined) return owner;
|
|
pendingOwners.add(owner);
|
|
stopWatchingSession ??= queryClient.getQueryCache().subscribe(() => {
|
|
const current = sessionAccount(queryClient);
|
|
if (current === undefined) return;
|
|
// Bind (or, for a session without a user, revoke) before anything else
|
|
// can sign in, so a later account never inherits these answers.
|
|
for (const pending of pendingOwners) ownerMatches(pending, current);
|
|
pendingOwners.clear();
|
|
stopWatchingSession?.();
|
|
stopWatchingSession = null;
|
|
});
|
|
return owner;
|
|
}
|
|
|
|
function isExpired(entry: Entry, now: number) {
|
|
return entry.settledAt !== undefined && now - entry.settledAt >= ISSUE_CHAT_BOOTSTRAP_FRESH_MS;
|
|
}
|
|
|
|
/** This account's entry for `ref` that is loading or loaded recently. */
|
|
function currentEntry(queryClient: QueryClient, ref: string, now = Date.now()) {
|
|
const entry = entries.get(refKey(ref));
|
|
if (!entry || isExpired(entry, now)) return undefined;
|
|
return ownerMatches(entry.owner, sessionAccount(queryClient)) ? entry : undefined;
|
|
}
|
|
|
|
/** Remove `entry` from every ref that still points at it. */
|
|
function forget(entry: Entry) {
|
|
for (const [key, value] of entries) if (value === entry) entries.delete(key);
|
|
}
|
|
|
|
/**
|
|
* Track one task's part of a request under every ref it is known by: the
|
|
* refs the caller gave at once, and the task's id and identifier when the
|
|
* answer arrives. A list (identifiers) and Recents (ids) then never load the
|
|
* same task twice, even while a request is in flight. Expired entries are
|
|
* dropped, so answers do not stay in memory.
|
|
*/
|
|
function track(queryClient: QueryClient, refs: readonly string[], owner: Owner, startedAt: number, promise: Promise<ChatBootstrapItem | undefined>, batched = false) {
|
|
const now = Date.now();
|
|
for (const [key, entry] of entries) if (isExpired(entry, now)) entries.delete(key);
|
|
const entry: Entry = { startedAt, owner, promise, batched };
|
|
for (const ref of refs) entries.set(refKey(ref), entry);
|
|
void promise.then((item) => {
|
|
entry.settledAt = Date.now();
|
|
if (!item) {
|
|
// A failed or empty answer must not suppress later reads or preloads.
|
|
forget(entry);
|
|
return;
|
|
}
|
|
for (const alias of [item.issue.id, item.issue.identifier]) {
|
|
if (alias && !currentEntry(queryClient, alias)) entries.set(refKey(alias), entry);
|
|
}
|
|
});
|
|
}
|
|
|
|
/** One task to request: the ref sent to the server, plus every ref it is known by. */
|
|
type Wanted = { ref: string; refs: string[] };
|
|
|
|
function startChunk(queryClient: QueryClient, companyId: string, wanted: readonly Wanted[]) {
|
|
const refs = wanted.map((target) => target.ref);
|
|
const requestedAt = Date.now();
|
|
const owner = newOwner(queryClient);
|
|
// A synchronous throw (bad input) is only a missed preload as well.
|
|
const request = Promise.resolve().then(() => issuesApi.chatBootstrap(companyId, refs)).then((response) => {
|
|
const byRef = new Map<string, ChatBootstrapItem>();
|
|
// Never seed or share an answer read with the previous account's cookie.
|
|
if (!ownerMatches(owner, sessionAccount(queryClient))) return byRef;
|
|
for (const item of response.items) {
|
|
if (!seedIssueChatBootstrap(queryClient, item, { companyId, requestedAt })) continue;
|
|
byRef.set(refKey(item.ref), item);
|
|
}
|
|
return byRef;
|
|
});
|
|
for (const target of wanted) {
|
|
track(queryClient, target.refs, owner, requestedAt, request.then((byRef) => byRef.get(refKey(target.ref)), () => undefined), wanted.length > 1);
|
|
}
|
|
return request.then(() => undefined, () => undefined);
|
|
}
|
|
|
|
/**
|
|
* How long a background preload (a task list) skips a task it already
|
|
* preloaded. A list that stays open re-renders as live events reorder it;
|
|
* events keep a preloaded task's cache current or mark it stale, so the list
|
|
* does not need to preload the same task again every 30 seconds.
|
|
*/
|
|
export const CHAT_BOOTSTRAP_BACKGROUND_REPEAT_MS = 5 * 60_000;
|
|
/**
|
|
* When each task was last preloaded in the background, per cache and per
|
|
* account: another account (after a sign-out) starts with an empty cache and
|
|
* must preload its own tasks.
|
|
*/
|
|
let backgroundPreloadedAt = new WeakMap<QueryClient, Map<string, number>>();
|
|
|
|
function backgroundKey(queryClient: QueryClient, ref: string) {
|
|
return `${sessionAccount(queryClient) ?? ""}:${refKey(ref)}`;
|
|
}
|
|
|
|
function backgroundPreloads(queryClient: QueryClient) {
|
|
let preloads = backgroundPreloadedAt.get(queryClient);
|
|
if (!preloads) backgroundPreloadedAt.set(queryClient, preloads = new Map());
|
|
return preloads;
|
|
}
|
|
|
|
function preloadedInBackgroundRecently(queryClient: QueryClient, refs: readonly string[], now: number) {
|
|
const preloads = backgroundPreloads(queryClient);
|
|
return refs.some((ref) => {
|
|
const at = preloads.get(backgroundKey(queryClient, ref));
|
|
return at !== undefined && now - at < CHAT_BOOTSTRAP_BACKGROUND_REPEAT_MS;
|
|
});
|
|
}
|
|
|
|
function rememberBackgroundPreload(queryClient: QueryClient, refs: readonly string[], now: number) {
|
|
const preloads = backgroundPreloads(queryClient);
|
|
for (const [key, at] of preloads) if (now - at >= CHAT_BOOTSTRAP_BACKGROUND_REPEAT_MS) preloads.delete(key);
|
|
for (const ref of refs) preloads.set(backgroundKey(queryClient, ref), now);
|
|
}
|
|
|
|
function forgetBackgroundPreload(queryClient: QueryClient, refs: readonly string[]) {
|
|
const preloads = backgroundPreloads(queryClient);
|
|
for (const ref of refs) preloads.delete(backgroundKey(queryClient, ref));
|
|
}
|
|
|
|
/** A task to preload: a ref, or its id with the identifier it may also be cached under. */
|
|
export type ChatBootstrapTarget = string | { id: string; identifier: string | null };
|
|
|
|
/**
|
|
* Load the bootstrap for these tasks in requests of at most ten, one request
|
|
* at a time, and seed the cache as each one arrives. Tasks loading, loaded
|
|
* within `ISSUE_CHAT_BOOTSTRAP_FRESH_MS`, or whose first frame is already cached
|
|
* and fresh are skipped.
|
|
*
|
|
* `signal` stops later requests, never one in flight: a click that unmounts
|
|
* the list must still be able to use the answer for the task it opens.
|
|
* `background` (a list's preload) also skips tasks it preloaded within
|
|
* `CHAT_BOOTSTRAP_BACKGROUND_REPEAT_MS`.
|
|
*/
|
|
export async function loadIssueChatBootstraps(
|
|
queryClient: QueryClient,
|
|
companyId: string,
|
|
targets: readonly ChatBootstrapTarget[],
|
|
options: { signal?: AbortSignal; background?: boolean } = {},
|
|
) {
|
|
const now = Date.now();
|
|
// Keyed by the normalized ref; the request keeps the caller's spelling.
|
|
const wanted = new Map<string, Wanted>();
|
|
for (const target of targets) {
|
|
const refs = typeof target === "string" ? [target] : [target.id, target.identifier].filter((ref): ref is string => !!ref);
|
|
if (!refs.length || wanted.has(refKey(refs[0]!))) continue;
|
|
if (refs.some((ref) => currentEntry(queryClient, ref, now))) continue;
|
|
if (hasFreshIssueChatFirstFrame(queryClient, refs, now)) continue;
|
|
if (options.background && preloadedInBackgroundRecently(queryClient, refs, now)) continue;
|
|
wanted.set(refKey(refs[0]!), { ref: refs[0]!, refs });
|
|
}
|
|
const ordered = [...wanted.values()];
|
|
for (let start = 0; start < ordered.length; start += ISSUE_CHAT_BOOTSTRAP_MAX_IDS) {
|
|
if (options.signal?.aborted) return;
|
|
const chunk = ordered.slice(start, start + ISSUE_CHAT_BOOTSTRAP_MAX_IDS);
|
|
if (options.background) rememberBackgroundPreload(queryClient, chunk.flatMap((target) => target.refs), Date.now());
|
|
await startChunk(queryClient, companyId, chunk);
|
|
// A failed or partial answer leaves those tasks cold: the next preload may retry them.
|
|
if (options.background) {
|
|
for (const target of chunk) {
|
|
if (!hasFreshIssueChatFirstFrame(queryClient, target.refs)) forgetBackgroundPreload(queryClient, target.refs);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Set by the inline script; `startedAt` is the request's `Date.now()`. */
|
|
type EarlyChatBootstrap = { ref: string; startedAt?: number; promise: Promise<ChatBootstrapItem | null> };
|
|
|
|
/**
|
|
* Adopt the fetch the page's inline script started on a hard load of this task
|
|
* (see `vite-issue-detail-preload`), so the first answer needs no new request.
|
|
*/
|
|
function adoptEarlyChatBootstrap(queryClient: QueryClient, companyId: string | null | undefined, ref: string) {
|
|
if (typeof window === "undefined") return false;
|
|
const holder = window as unknown as Record<string, EarlyChatBootstrap | undefined>;
|
|
const early = holder[EARLY_CHAT_BOOTSTRAP_GLOBAL];
|
|
if (!early || refKey(early.ref) !== refKey(ref)) return false;
|
|
delete holder[EARLY_CHAT_BOOTSTRAP_GLOBAL];
|
|
// Staleness counts from when the server could last have read the task.
|
|
const startedAt = typeof early.startedAt === "number" ? early.startedAt : Date.now();
|
|
// A page that took this long to start reads the task itself.
|
|
if (Date.now() - startedAt >= ISSUE_CHAT_BOOTSTRAP_FRESH_MS) return false;
|
|
const owner = newOwner(queryClient);
|
|
track(queryClient, [ref], owner, startedAt, early.promise.then((item) => {
|
|
// The answer belongs to the account that loaded the page.
|
|
if (!item?.issue || !ownerMatches(owner, sessionAccount(queryClient))) return undefined;
|
|
// The route's task is the one the page opens; a known company must match it.
|
|
const ownerCompanyId = companyId ?? item.issue.companyId;
|
|
return seedIssueChatBootstrap(queryClient, item, { companyId: ownerCompanyId, requestedAt: startedAt }) ? item : undefined;
|
|
}, () => undefined));
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* At app start, adopt the bootstrap a hard load of a task URL started, so
|
|
* every reader of that task's chat shares it, including ones that start before
|
|
* the task page mounts. A task the saved read cache restored is also known by
|
|
* its id and identifier. Starts no request of its own.
|
|
*/
|
|
export function adoptHardLoadChatBootstrap(queryClient: QueryClient) {
|
|
if (typeof window === "undefined") return;
|
|
const early = (window as unknown as Record<string, EarlyChatBootstrap | undefined>)[EARLY_CHAT_BOOTSTRAP_GLOBAL];
|
|
if (!early?.ref || currentEntry(queryClient, early.ref)) return;
|
|
const restored = queryClient.getQueryData<{ id?: unknown; identifier?: unknown; companyId?: unknown }>([...queryKeys.issues.detail(early.ref), "core"]);
|
|
const companyId = typeof restored?.companyId === "string" ? restored.companyId : null;
|
|
if (!adoptEarlyChatBootstrap(queryClient, companyId, early.ref)) return;
|
|
const entry = currentEntry(queryClient, early.ref);
|
|
for (const alias of [restored?.id, restored?.identifier]) {
|
|
if (entry && typeof alias === "string" && alias && !currentEntry(queryClient, alias)) entries.set(refKey(alias), entry);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The single-task route, for a task whose company the caller does not know
|
|
* (a link's open intent). The task's own company owns the answer.
|
|
*/
|
|
function startSingle(queryClient: QueryClient, ref: string) {
|
|
const requestedAt = Date.now();
|
|
const owner = newOwner(queryClient);
|
|
const path = `/issues/${encodeURIComponent(ref)}/chat-bootstrap`;
|
|
track(queryClient, [ref], owner, requestedAt, Promise.resolve().then(() => api.get<ChatBootstrapItem>(path, { cache: "no-store" })).then((item) => {
|
|
if (!item?.issue || !ownerMatches(owner, sessionAccount(queryClient))) return undefined;
|
|
return seedIssueChatBootstrap(queryClient, item, { companyId: item.issue.companyId, requestedAt }) ? item : undefined;
|
|
}, () => undefined));
|
|
}
|
|
|
|
/**
|
|
* Start a single-task bootstrap for a cold open or an open intent, unless one
|
|
* is loading, loaded recently, or the task's first frame is cached and fresh.
|
|
* A task whose only request is a background preload of several tasks, still
|
|
* loading, gets its own request. Without a company it uses the single-task route. Resolves when the task's
|
|
* 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(
|
|
queryClient: QueryClient,
|
|
companyId: string | null | undefined,
|
|
ref: string | null | undefined,
|
|
aliases: readonly (string | null | undefined)[] = [],
|
|
): Promise<unknown> {
|
|
if (!ref) return 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;
|
|
};
|
|
const existing = currentEntry(queryClient, ref);
|
|
// A task being opened must not wait for the rest of a background preload
|
|
// (Recents or a list reads ten tasks in one request): it is read on its own,
|
|
// and its reads share that answer instead. The preload's later answer only
|
|
// fills what is still empty.
|
|
if (existing?.batched && existing.settledAt === undefined) {
|
|
if (companyId) void startChunk(queryClient, companyId, [{ ref, refs: [ref] }]);
|
|
else startSingle(queryClient, ref);
|
|
const single = currentEntry(queryClient, ref);
|
|
if (single && single !== existing) {
|
|
for (const [key, value] of entries) if (value === existing) entries.set(key, single);
|
|
}
|
|
return settled();
|
|
}
|
|
if (existing) return settled();
|
|
if (adoptEarlyChatBootstrap(queryClient, companyId, ref)) return settled();
|
|
if (companyId) {
|
|
void loadIssueChatBootstraps(queryClient, companyId, [ref]);
|
|
return settled();
|
|
}
|
|
if (hasFreshIssueChatFirstFrame(queryClient, [ref])) return Promise.resolve();
|
|
startSingle(queryClient, ref);
|
|
return settled();
|
|
}
|
|
|
|
/**
|
|
* 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
|
|
* sending another request. A key that already holds data read in this
|
|
* 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.
|
|
*/
|
|
export async function readFromIssueChatBootstrap<T>(
|
|
queryClient: QueryClient,
|
|
key: QueryKey,
|
|
ref: string,
|
|
pick: (item: ChatBootstrapItem) => T | undefined,
|
|
read: () => Promise<T>,
|
|
): Promise<T> {
|
|
if (queryClient.getQueryData(key) !== undefined && !isRestoredSavedRead(queryClient, key)) return read();
|
|
const entry = currentEntry(queryClient, ref);
|
|
// Only share an answer that is still loading or a moment old.
|
|
if (entry && (entry.settledAt === undefined || Date.now() - entry.settledAt < SHARE_WINDOW_MS)) {
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
const stalled = new Promise<"stalled">((resolve) => { timer = setTimeout(() => resolve("stalled"), CHAT_BOOTSTRAP_SHARE_DEADLINE_MS); });
|
|
const answer = await Promise.race([entry.promise, stalled]);
|
|
clearTimeout(timer);
|
|
if (answer === "stalled") {
|
|
// Later reads (and Retry) go to the server instead of the stuck request.
|
|
forget(entry);
|
|
return read();
|
|
}
|
|
const item = answer;
|
|
const value = item ? pick(item) : undefined;
|
|
if (value !== undefined) return value;
|
|
}
|
|
return read();
|
|
}
|
|
|
|
/** Whether two sorted id lists are the same set. */
|
|
export function sameIds(a: readonly string[], b: readonly string[]) {
|
|
return a.length === b.length && a.every((id, index) => id === b[index]);
|
|
}
|
|
|
|
/** Test seam. */
|
|
export function resetIssueChatBootstrapsForTest() {
|
|
entries.clear();
|
|
backgroundPreloadedAt = new WeakMap();
|
|
pendingOwners.clear();
|
|
stopWatchingSession?.();
|
|
stopWatchingSession = null;
|
|
}
|
|
|
|
/** Test seam: how many refs hold an entry. */
|
|
export function issueChatBootstrapEntryCountForTest() {
|
|
return entries.size;
|
|
}
|