mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 18:26:40 +01:00
perf(ui): show a returning task's saved chat before any server response (#21671)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board UI opens a task as a chat. A returning browser restores a saved read cache from local storage before the first render. > - #21650 made a returning hard load share the one chat bootstrap. But the saved cache held no chat, so the first chat frame still waited for that response. > - The owner approved saving recent comments in the browser on 2026-11-14, so that cached tasks show their chat at once. > - This pull request saves the first chat frame of the 20 most recently opened tasks, with size, age, revocation and isolation guardrails. The restored chat shows at once and revalidates through the bootstrap. > - It also adopts the hard-load bootstrap at app start and sends the other live-run readers through it, so readers that start before the task page mounts do not send their own requests. > - The benefit is that a hard load of a task the user opened before shows its conversation before any server response. ## Linked Issues or Issue Description **Describe the enhancement** A hard load of a task that the user opened before still waits for one server round trip before its chat appears. The saved read cache did not include comments. **Current behavior** With every API response delayed by 800 ms, a returning load shows the chat at 892 ms (median). The frame waits for the chat bootstrap response. **Proposed behavior** The saved read cache also keeps the first chat frame of recently opened tasks. A returning load shows that frame before any response, then revalidates through the bootstrap. **Why** The owner approved saving recent comments in the browser for this on 2026-11-14. Cold and cached loads must both be as fast as possible. Related: #21650 (returning load shares the chat bootstrap), #20594 and #20591 (returning inbox from the saved cache), #20592 and #21557 (cold task load from one bootstrap). ## What Changed - `ui/src/lib/persisted-query-cache.ts`: saves the reads the first chat frame waits for (`taskChatFirstFrameRef`): recent comments, their input facts, recent activity, the recent run window, interactions, attachment metadata, live and active runs, work products and the plan document. - Only for the 20 saved recent tasks, in the record of the task's own user and company. - At most 50 comments per task (the newest; `hasMore` is set), 192 KiB per task, 1 MiB in total, newest tasks first. - If storage refuses a record, the record is saved again without chat, so chat never displaces the rest of the cache. - All other field exclusions (tokens, credentials, environment values, embedded documents) still apply. Only `comments` is allowed, and only for these keys. - Expiry is the same as every other entry: 24 hours after the read. - A 401, 403 or 404 on the task or on any of its chat reads removes the task and its saved chat from memory and storage at once. - `ui/src/lib/issue-chat-bootstrap.ts` and `ui/src/main.tsx`: `adoptHardLoadChatBootstrap` adopts the bootstrap that the HTML started, at app start, under the task's restored id and identifier. Readers that start before the task page mounts share it. - `IssueDetail.tsx`, `LiveRunWidget.tsx`, `IssueRunLedger.tsx`, `useTaskPluginPanels.ts`: their `live-runs` reads share the loading bootstrap. Before, whichever observer mounted first could send its own request. - `doc/DEVELOPING.md`: the read-cache rules now state what is saved, the bounds, why, and the owner's approval on 2026-11-14. - Tests: `ui/src/lib/saved-task-chat.test.ts` (guardrails), a new case in `restored-task-chat-bootstrap.test.ts`, and an always-on perf test: "a returning task load shows its saved chat before any API response, then revalidates". ## Verification Local production build, local_trusted instance, CDP delay on every API request, fresh browser context per run, JavaScript in the HTTP cache. Time to the revealed history with the latest message and an editable composer. Saved read cache present against cleared (other storage kept), 5 alternating pairs each. | API delay | Build | Cleared | Present | Requests before frame (present) | | ---: | --- | ---: | ---: | ---: | | 800 ms | master `36101ebcb9` | 1,911 ms (1,895–1,920) | 892 ms (887–898), released by the bootstrap | 33 | | 800 ms | this PR | 1,922 ms (1,912–1,936) | 571 ms (556–588), before any response | 36 | | 300 ms | master | 916 ms (907–920) | 570 ms (564–576) | 37 | | 300 ms | this PR | 928 ms (910–998) | 586 ms (568–622) | 37 | - At 300 ms the bootstrap answers before the page mounts on both builds, so they are the same. At 800 ms the saved chat removes the wait for the bootstrap: −321 ms against master. - The new perf test holds every response for 2.5 s. It fails on master (frame at 2,595 ms, first response at 2,524 ms) and passes with this PR. - Guardrail tests, red/green: I disabled each guardrail in turn in `persisted-query-cache.ts` and ran `saved-task-chat.test.ts`. Each mutant made its test fail, and all 19 tests pass with the code. Mutants: no chat saved, no 50-comment cap, no 20-task cap, no per-task budget, no total budget, no retry without chat when storage refuses, no 24-hour expiry, no revocation on a chat read, chat stored in the wrong company record, and no field exclusions. - Sign-out and other-user isolation use the existing per-user records and their clearing (no new code). The tests cover them for saved chat. - "Never overwrites newer data" is the query cache's hydrate rule; the test covers it. "The bootstrap replaces saved data" uses the restored-entry rule from #21650; the test covers it. - App-start adoption test: it fails when the adoption call is removed, and passes with it. - Focused Vitest: 25 files that use the changed modules, including `IssueDetail.test.tsx` and `TaskChatThread.test.tsx`: 1,156 passed. `pnpm --filter @paperclipai/ui typecheck` passes. - Browser journeys against this build: `layout-stability.spec.ts`, `plan-startup.spec.ts`, `cold-bootstrap.perf.spec.ts`: 20 passed (2 opt-in benchmarks skipped). Leftover early reads on staging (one run after #21650 started `issues/:ref?view=core` and `issues/:ref/live-runs` before the frame): I could not reproduce them locally. That included sidebar Recents and a bootstrap delayed to 1.2 s with CDP initiator stacks. Both reads would go to the server only if no bootstrap was being tracked for the task, or if an observer used a direct read. This PR removes both openings: the bootstrap is adopted at app start, and every `live-runs` observer shares it. I will check the request timeline on staging after deploy. ## Risks - Privacy: recent comments of up to 20 recent tasks now stay in local storage for up to 24 hours, or until sign-out. The owner approved this on 2026-11-14. The bounds, the revocation and the field exclusions are tested. Saved data is per user and company, and sign-out clears it in every tab. - Storage: saved chat is limited to 1 MiB in total. A record that storage refuses is saved again without chat. - A saved chat can be up to 24 hours old when it shows. It is marked for revalidation, and the bootstrap answer replaces it within one round trip. A refused revalidation removes it. ## 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 and Chrome). ## 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
36101ebcb9
commit
fc9e4cbbb3
14 files changed
+559
-38
No files matched your search
@@ -36,6 +36,7 @@ import {
|
||||
ProviderTraceStatusBadge,
|
||||
runRequestedProviderTrace,
|
||||
} from "./ProviderTraceStatusBadge";
|
||||
import { readFromIssueChatBootstrap } from "@/lib/issue-chat-bootstrap";
|
||||
|
||||
type IssueRunLedgerProps = {
|
||||
issueId: string;
|
||||
@@ -465,7 +466,7 @@ export function IssueRunLedger({
|
||||
});
|
||||
const { data: liveRuns } = useQuery({
|
||||
queryKey: queryKeys.issues.liveRuns(issueId),
|
||||
queryFn: () => heartbeatsApi.liveRunsForIssue(issueId),
|
||||
queryFn: () => readFromIssueChatBootstrap(queryClient, queryKeys.issues.liveRuns(issueId), issueId, (item) => item.liveRuns, () => heartbeatsApi.liveRunsForIssue(issueId)),
|
||||
enabled: hasLiveRuns,
|
||||
refetchInterval: 3000,
|
||||
placeholderData:
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Identity } from "./Identity";
|
||||
import { RunChatSurface } from "./RunChatSurface";
|
||||
import { StatusBadge } from "./StatusBadge";
|
||||
import { useLiveRunTranscripts } from "./transcript/useLiveRunTranscripts";
|
||||
import { readFromIssueChatBootstrap } from "@/lib/issue-chat-bootstrap";
|
||||
|
||||
interface LiveRunWidgetProps {
|
||||
issueId: string;
|
||||
@@ -36,7 +37,7 @@ export function LiveRunWidget({ issueId, companyId }: LiveRunWidgetProps) {
|
||||
|
||||
const { data: liveRuns } = useQuery({
|
||||
queryKey: queryKeys.issues.liveRuns(issueId),
|
||||
queryFn: () => heartbeatsApi.liveRunsForIssue(issueId),
|
||||
queryFn: () => readFromIssueChatBootstrap(queryClient, queryKeys.issues.liveRuns(issueId), issueId, (item) => item.liveRuns, () => heartbeatsApi.liveRunsForIssue(issueId)),
|
||||
enabled: !!issueId,
|
||||
refetchInterval: liveRunRefetchInterval,
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { QueryNotReadyError } from "@/lib/query-client";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { useAgentEnvironmentSlots } from "@/plugins/useAgentEnvironmentSlots";
|
||||
import { usePluginSlots, type ResolvedPluginSlot } from "@/plugins/slots";
|
||||
import { readFromIssueChatBootstrap } from "@/lib/issue-chat-bootstrap";
|
||||
|
||||
export interface TaskPluginPanel {
|
||||
entityId: string;
|
||||
@@ -43,7 +44,7 @@ export function useTaskPluginPanels(issue: Issue | null | undefined, enabled = t
|
||||
});
|
||||
const { data: runs, isError: runsError, isPending: runsPending } = useQuery({
|
||||
queryKey: queryKeys.issues.liveRuns(issue?.id ?? "pending"),
|
||||
queryFn: () => heartbeatsApi.liveRunsForIssue(issue!.id),
|
||||
queryFn: () => readFromIssueChatBootstrap(queryClient, queryKeys.issues.liveRuns(issue!.id), issue!.id, (item) => item.liveRuns, () => heartbeatsApi.liveRunsForIssue(issue!.id)),
|
||||
enabled: savedTask && declaredPanels.length > 0 && !errorMessage,
|
||||
refetchInterval: connected ? false : 3000,
|
||||
retry: (failures: number, error: Error) => failures < 2 && !(error instanceof ApiError && error.status >= 400 && error.status < 500),
|
||||
|
||||
@@ -257,6 +257,25 @@ function adoptEarlyChatBootstrap(queryClient: QueryClient, companyId: string | n
|
||||
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.
|
||||
|
||||
@@ -5,6 +5,7 @@ import { heartbeatsApi } from "@/api/heartbeats";
|
||||
import { issuesApi } from "@/api/issues";
|
||||
import { prefetchIssueIdBatches } from "@/hooks/useIssueIdBatches";
|
||||
import { readFromIssueChatBootstrap } from "@/lib/issue-chat-bootstrap";
|
||||
import { isRestoredSavedRead } from "@/lib/persisted-query-cache";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
|
||||
// The compact task chat reveals its first frame only after these reads settle
|
||||
@@ -54,7 +55,9 @@ export function prefetchIssueCommentInputFacts(queryClient: QueryClient, issueRe
|
||||
|
||||
/** Recent activity, merged with events already observed while the task is open. */
|
||||
export async function fetchRecentIssueActivity(queryClient: QueryClient, issueRef: string) {
|
||||
const cached = queryClient.getQueryData<ActivityEvent[]>(recentIssueActivityQueryKey(issueRef));
|
||||
const key = recentIssueActivityQueryKey(issueRef);
|
||||
// Restored (saved) events are replaced by the first read, never merged.
|
||||
const cached = isRestoredSavedRead(queryClient, key) ? undefined : queryClient.getQueryData<ActivityEvent[]>(key);
|
||||
// A cold open may already have this in a loading bootstrap; a refresh asks the server.
|
||||
const recent = cached
|
||||
? await activityApi.recentForIssue(issueRef)
|
||||
@@ -70,7 +73,8 @@ export async function fetchRecentIssueRunWindow(
|
||||
options: { conversationMode?: boolean } = {},
|
||||
): Promise<RecentIssueRunWindow> {
|
||||
const key = recentIssueRunWindowQueryKey(issueRef);
|
||||
const previousWindow = queryClient.getQueryData<RecentIssueRunWindow>(key);
|
||||
// A restored (saved) window is replaced by the first read, never merged.
|
||||
const previousWindow = isRestoredSavedRead(queryClient, key) ? undefined : queryClient.getQueryData<RecentIssueRunWindow>(key);
|
||||
let recent = previousWindow
|
||||
? await activityApi.recentRunsForIssue(issueRef)
|
||||
: await readFromIssueChatBootstrap(queryClient, key, issueRef, (item) => item.recentRuns, () => activityApi.recentRunsForIssue(issueRef));
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { QueryClient } from "@tanstack/react-query";
|
||||
import type { IssueComment, IssueRecentComments } from "@paperclipai/shared";
|
||||
import { issuesApi } from "@/api/issues";
|
||||
import { readFromIssueChatBootstrap } from "./issue-chat-bootstrap";
|
||||
import { isRestoredSavedRead } from "./persisted-query-cache";
|
||||
import { queryKeys } from "./queryKeys";
|
||||
|
||||
export function mergeWindowComments(...windows: readonly IssueComment[][]): IssueComment[] {
|
||||
@@ -14,7 +15,10 @@ export function getIssueRecentCommentsQueryOptions(queryClient: QueryClient, iss
|
||||
return {
|
||||
queryKey: recentKey,
|
||||
queryFn: async ({ signal }: { signal: AbortSignal }): Promise<IssueRecentComments> => {
|
||||
const previous = queryClient.getQueryData<IssueRecentComments>(recentKey);
|
||||
// A window restored from the saved read cache was never confirmed in this
|
||||
// page (a comment may have been deleted since): read it like a cold open
|
||||
// and replace it, never merge it.
|
||||
const previous = isRestoredSavedRead(queryClient, recentKey) ? undefined : queryClient.getQueryData<IssueRecentComments>(recentKey);
|
||||
// A cold open may already have this window in a loading bootstrap.
|
||||
if (!previous) {
|
||||
return readFromIssueChatBootstrap(queryClient, recentKey, issueRef, (item) => item.recentComments, () => issuesApi.recentComments(issueRef, { signal }));
|
||||
|
||||
@@ -28,12 +28,15 @@ const issueIdentity = (query: { queryKey: readonly unknown[]; state: { data: unk
|
||||
const issueRefs = (query: { queryKey: readonly unknown[]; state: { data: unknown } }) => [query.queryKey[2], object(query.state.data)?.id, object(query.state.data)?.identifier]
|
||||
.filter((id): id is string => typeof id === "string").map(id => id.toLowerCase());
|
||||
const excludedFields = new Set(["planDocument", "legacyPlanDocument", "documentSummaries", "documents", "comments", "workProducts", "browsers", "pairingCode", "viewerUrl", "accessToken", "refreshToken", "sessionToken", "token", "password", "apiKey", "privateKey", "authorization", "access_token", "refresh_token", "id_token", "clientSecret", "client_secret", "api_key", "private_key", "credentials", "env"].map(key => key.toLowerCase()));
|
||||
function displayData(value: unknown, denied: ReadonlySet<string>): unknown {
|
||||
if (Array.isArray(value)) return value.map(item => displayData(item, denied)).filter(item => item !== undefined);
|
||||
// A saved task's chat keeps its comments (the owner approved saving recent
|
||||
// comments on 2026-11-14); every other exclusion still applies.
|
||||
const chatExcludedFields = new Set([...excludedFields].filter(key => key !== "comments"));
|
||||
function displayData(value: unknown, denied: ReadonlySet<string>, excluded: ReadonlySet<string> = excludedFields): unknown {
|
||||
if (Array.isArray(value)) return value.map(item => displayData(item, denied, excluded)).filter(item => item !== undefined);
|
||||
if (!value || typeof value !== "object" || value instanceof Date) return value;
|
||||
const row = value as Record<string, unknown>;
|
||||
if (typeof row.id === "string" && denied.has(row.id.toLowerCase())) return undefined;
|
||||
return Object.fromEntries(Object.entries(row).filter(([key]) => !excludedFields.has(key.toLowerCase()))
|
||||
return Object.fromEntries(Object.entries(row).filter(([key]) => !excluded.has(key.toLowerCase()))
|
||||
.map(([key, item]) => {
|
||||
if (key === "runtimeConfig") return [key, {}];
|
||||
if (key === "adapterConfig") {
|
||||
@@ -41,7 +44,7 @@ function displayData(value: unknown, denied: ReadonlySet<string>): unknown {
|
||||
return [key, Object.fromEntries(["provider", "model", "agent", "acpxAgent", "effort", "modelReasoningEffort", "reasoningEffort", "thinking", "variant"]
|
||||
.filter(field => typeof config?.[field] === "string").map(field => [field, config![field]]).concat(typeof config?.fastMode === "boolean" ? [["fastMode", config.fastMode]] : []))];
|
||||
}
|
||||
return [key, displayData(item, denied)];
|
||||
return [key, displayData(item, denied, excluded)];
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -52,9 +55,58 @@ function isLegacyInboxQuery(key: readonly unknown[]): boolean {
|
||||
}
|
||||
|
||||
function queryDisplayData(key: readonly unknown[], data: unknown, denied: ReadonlySet<string>): unknown {
|
||||
if (taskChatFirstFrameRef(key) !== null) return displayData(boundedChatData(key, data), denied, chatExcludedFields);
|
||||
return displayData(isLegacyInboxQuery(key) && Array.isArray(data) ? data.slice(0, 100) : data, denied);
|
||||
}
|
||||
|
||||
/** Saved recent comments per task: the latest ones, enough for the first frame. */
|
||||
export const SAVED_TASK_CHAT_MAX_COMMENTS = 50;
|
||||
/** Saved chat bytes per task; a larger task opens through the bootstrap as before. */
|
||||
export const SAVED_TASK_CHAT_MAX_TASK_BYTES = 192 * 1024;
|
||||
/** Saved chat bytes per user across companies, newest tasks first. Keeps room for the rest of the cache. */
|
||||
export const SAVED_TASK_CHAT_MAX_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The task ref of a read that the first chat frame of a task waits for, or
|
||||
* null for any other key. These reads are saved only for recently opened tasks.
|
||||
*/
|
||||
export function taskChatFirstFrameRef(key: readonly unknown[]): string | null {
|
||||
const [root, kind, ref] = key;
|
||||
if (root !== "issues" || typeof ref !== "string" || !ref) return null;
|
||||
const rest = key.slice(3);
|
||||
const tail = (...values: string[]) => rest.length === values.length && values.every((value, index) => rest[index] === value);
|
||||
switch (kind) {
|
||||
case "comments": return tail("recent") ? ref : null;
|
||||
case "activity":
|
||||
if (tail("recent") || tail("comment-inputs", "batch-ids")) return ref;
|
||||
return rest.length === 3 && rest[0] === "comment-inputs" && rest[1] === "batch" && Array.isArray(rest[2]) ? ref : null;
|
||||
case "runs": return tail("recent-window") ? ref : null;
|
||||
case "documents": return tail("plan") ? ref : null;
|
||||
case "interactions": case "attachments": case "live-runs": case "active-run": case "work-products": return rest.length === 0 ? ref : null;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
function boundedChatData(key: readonly unknown[], data: unknown): unknown {
|
||||
const recent = object(data);
|
||||
if (key[1] !== "comments" || !Array.isArray(recent?.comments) || recent.comments.length <= SAVED_TASK_CHAT_MAX_COMMENTS) return data;
|
||||
// The window is chronological; keep its newest comments and say more exist.
|
||||
const comments = recent.comments.slice(-SAVED_TASK_CHAT_MAX_COMMENTS);
|
||||
return { ...recent, comments, hasMore: true, oldestCommentId: object(comments[0])?.id ?? null };
|
||||
}
|
||||
|
||||
/** Task ref (lowercase) → company, from saved or cached task records. */
|
||||
function taskCompaniesOf(queries: Iterable<{ queryKey: readonly unknown[]; state: { data: unknown } }>, keep?: (query: { queryKey: readonly unknown[]; state: { data: unknown } }) => boolean) {
|
||||
const companies = new Map<string, string>();
|
||||
for (const query of queries) {
|
||||
if (!Array.isArray(query?.queryKey) || query.queryKey[0] !== "issues" || query.queryKey[1] !== "detail") continue;
|
||||
const companyId = object(query.state?.data)?.companyId;
|
||||
if (typeof companyId !== "string" || (keep && !keep(query))) continue;
|
||||
for (const ref of issueRefs(query)) companies.set(ref, companyId);
|
||||
}
|
||||
return companies;
|
||||
}
|
||||
|
||||
function browserStorage(): CacheStorage | null {
|
||||
try { return typeof window === "undefined" ? null : window.localStorage; } catch { return null; }
|
||||
}
|
||||
@@ -102,8 +154,14 @@ function companyIdsFor(client: QueryClient, userId: string): string[] {
|
||||
return (result?.companies ?? []).map(company => company.id).filter(id => typeof id === "string" && id.length > 0);
|
||||
}
|
||||
|
||||
export function persistedQueryScope(key: readonly unknown[], data: unknown, userId: string, companyIds: readonly string[]): string | null | undefined {
|
||||
export function persistedQueryScope(key: readonly unknown[], data: unknown, userId: string, companyIds: readonly string[], taskCompanies?: ReadonlyMap<string, string>): string | null | undefined {
|
||||
const [root, second, third] = key;
|
||||
const chatRef = taskChatFirstFrameRef(key);
|
||||
if (chatRef !== null) {
|
||||
// A chat read belongs to the company of a saved (recent) task record.
|
||||
const companyId = taskCompanies?.get(chatRef.toLowerCase());
|
||||
return companyId && companyIds.includes(companyId) ? companyId : undefined;
|
||||
}
|
||||
if (hashKey(key) === hashKey(queryKeys.auth.session)) return userIdOf(data) === userId ? null : undefined;
|
||||
if (key.length === 1 && root === "health") return null;
|
||||
if (root === "companies" && second === "list" && third === userId && key.length === 3) return null;
|
||||
@@ -263,9 +321,12 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
||||
} catch { return null; }
|
||||
};
|
||||
const fresh = (updatedAt: number) => Number.isFinite(updatedAt) && now() - updatedAt >= 0 && now() - updatedAt <= QUERY_CACHE_MAX_AGE;
|
||||
const savedQueries = (entry: Envelope, companyIds: string[]) => entry.state.queries.filter(query => query?.state?.data !== undefined && query.state.status === "success"
|
||||
&& fresh(query.state.dataUpdatedAt) && Array.isArray(query.queryKey) && !blockedQueries.has(hashKey(query.queryKey))
|
||||
&& persistedQueryScope(query.queryKey, query.state.data, entry.userId, companyIds) === entry.companyId);
|
||||
const savedQueries = (entry: Envelope, companyIds: string[]) => {
|
||||
const taskCompanies = taskCompaniesOf(entry.state.queries);
|
||||
return entry.state.queries.filter(query => query?.state?.data !== undefined && query.state.status === "success"
|
||||
&& fresh(query.state.dataUpdatedAt) && Array.isArray(query.queryKey) && !blockedQueries.has(hashKey(query.queryKey))
|
||||
&& persistedQueryScope(query.queryKey, query.state.data, entry.userId, companyIds, taskCompanies) === entry.companyId);
|
||||
};
|
||||
const readSaved = (userId: string): Envelope[] => {
|
||||
if (!storage) return [];
|
||||
const prefix = `${QUERY_CACHE_PREFIX}${encodeURIComponent(userId)}:`;
|
||||
@@ -305,8 +366,11 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
||||
}
|
||||
return { queryKey: query.queryKey, queryHash: hashKey(query.queryKey), state: { ...query.state, data, error: null, status: "success", fetchStatus: "idle", fetchFailureReason: null, fetchMeta: null } };
|
||||
};
|
||||
const allowedIssue = (query: { queryKey: readonly unknown[]; state: { data: unknown } }) => !(query.queryKey[0] === "issues" && query.queryKey[1] === "detail"
|
||||
&& issueRefs(query).some(id => deniedIssues.has(id)));
|
||||
const allowedIssue = (query: { queryKey: readonly unknown[]; state: { data: unknown } }) => {
|
||||
const chatRef = taskChatFirstFrameRef(query.queryKey);
|
||||
if (chatRef !== null) return !deniedIssues.has(chatRef.toLowerCase());
|
||||
return !(query.queryKey[0] === "issues" && query.queryKey[1] === "detail" && issueRefs(query).some(id => deniedIssues.has(id)));
|
||||
};
|
||||
const scrubSaved = (userId: string, entries: Envelope[]) => {
|
||||
if (!storage || ownerRevision !== revisionFor(userId)) return;
|
||||
const companies = approvedCompanies(userId, entries);
|
||||
@@ -319,7 +383,7 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
||||
}
|
||||
};
|
||||
const restoreState = (entry: Envelope, companyIds: string[]) => {
|
||||
const queries = savedQueries(entry, companyIds)
|
||||
const queries = savedQueries(entry, companyIds).filter(allowedIssue)
|
||||
.map(query => ({ queryKey: query.queryKey, queryHash: hashKey(query.queryKey), state: {
|
||||
data: queryDisplayData(query.queryKey, query.state.data, deniedIssues), dataUpdatedAt: query.state.dataUpdatedAt, dataUpdateCount: 1,
|
||||
error: null, errorUpdateCount: 0, errorUpdatedAt: 0, fetchFailureCount: 0, fetchFailureReason: null,
|
||||
@@ -364,11 +428,12 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
||||
if (ownerRevision !== revisionFor(userId)) { suspendAccount(); return; }
|
||||
const entries = readSaved(userId);
|
||||
const companies = approvedCompanies(userId, entries);
|
||||
const knownTasks = taskCompaniesOf([...client.getQueryCache().getAll(), ...entries.flatMap(entry => entry.state.queries)]);
|
||||
const eligible = (query: Query) => query.state.data !== undefined
|
||||
&& (query.state.status === "success" || isTransientError(query.state.error))
|
||||
&& !blockedQueries.has(hashKey(query.queryKey))
|
||||
&& fresh(query.state.dataUpdatedAt)
|
||||
&& persistedQueryScope(query.queryKey, query.state.data, userId, companies) !== undefined;
|
||||
&& persistedQueryScope(query.queryKey, query.state.data, userId, companies, knownTasks) !== undefined;
|
||||
// Memory GC is independent of the on-disk lifetime. Retain valid saved
|
||||
// reads, prefer newer data, and apply the same limits to the merged set.
|
||||
const merged = new Map<string, SavedQuery>();
|
||||
@@ -387,20 +452,51 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
||||
for (const query of recent) if (issueIds.size < QUERY_CACHE_MAX_ISSUES) issueIds.add(issueIdentity(query));
|
||||
const previews = new Set([...merged.values()].filter(query => query.queryKey[0] === "link-preview")
|
||||
.sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt).slice(0, MAX_LINK_PREVIEWS).map(query => hashKey(query.queryKey)));
|
||||
const queries = [...merged.values()].filter(query => allowedIssue(query)
|
||||
// Saved chat reads follow their task: only the recent tasks kept above,
|
||||
// newest first, within the per-task and total byte budgets.
|
||||
const keptTasks = recent.filter(query => issueIds.has(issueIdentity(query)));
|
||||
const taskCompanies = taskCompaniesOf(keptTasks);
|
||||
const taskIdentity = new Map<string, string>();
|
||||
for (const query of keptTasks) for (const ref of issueRefs(query)) taskIdentity.set(ref, issueIdentity(query));
|
||||
const projected = [...merged.values()].filter(query => allowedIssue(query)
|
||||
&& (query.queryKey[0] !== "link-preview" || previews.has(hashKey(query.queryKey)))
|
||||
&& !(query.queryKey[0] === "issues" && query.queryKey[1] === "detail" && !issueIds.has(issueIdentity(query))))
|
||||
.map(query => projectQuery(query, userId)).filter(query => query.state.data !== undefined);
|
||||
const chatTaskOf = (query: SavedQuery) => {
|
||||
const ref = taskChatFirstFrameRef(query.queryKey);
|
||||
return ref === null ? null : taskIdentity.get(ref.toLowerCase()) ?? "";
|
||||
};
|
||||
const chatBytes = new Map<string, number>();
|
||||
for (const query of projected) {
|
||||
const task = chatTaskOf(query);
|
||||
if (task) chatBytes.set(task, (chatBytes.get(task) ?? 0) + JSON.stringify(query).length);
|
||||
}
|
||||
const savedChatTasks = new Set<string>();
|
||||
let chatTotal = 0;
|
||||
for (const task of issueIds) {
|
||||
const bytes = chatBytes.get(task);
|
||||
if (bytes === undefined || bytes > SAVED_TASK_CHAT_MAX_TASK_BYTES || chatTotal + bytes > SAVED_TASK_CHAT_MAX_BYTES) continue;
|
||||
chatTotal += bytes;
|
||||
savedChatTasks.add(task);
|
||||
}
|
||||
const queries = projected.filter(query => {
|
||||
const task = chatTaskOf(query);
|
||||
return task === null || savedChatTasks.has(task);
|
||||
});
|
||||
try {
|
||||
const expected = new Set([QUERY_CACHE_ACTIVE]);
|
||||
for (const companyId of [null, ...companies]) {
|
||||
const key = recordKey(userId, companyId);
|
||||
expected.add(key);
|
||||
const envelope: Envelope = { version: 1, userId, companyId, buildId, revision: ownerRevision, savedAt: now(),
|
||||
state: { mutations: [], queries: queries.filter(query => persistedQueryScope(query.queryKey, query.state.data, userId, companies) === companyId) } };
|
||||
const serialized = JSON.stringify(envelope);
|
||||
if (serialized.length <= MAX_RECORD_BYTES) storage.setItem(key, serialized);
|
||||
else storage.removeItem(key);
|
||||
const scoped = queries.filter(query => persistedQueryScope(query.queryKey, query.state.data, userId, companies, taskCompanies) === companyId);
|
||||
const write = (records: SavedQuery[]) => {
|
||||
const serialized = JSON.stringify({ version: 1, userId, companyId, buildId, revision: ownerRevision, savedAt: now(),
|
||||
state: { mutations: [], queries: records } } satisfies Envelope);
|
||||
if (serialized.length > MAX_RECORD_BYTES) return false;
|
||||
try { storage.setItem(key, serialized); return true; } catch { return false; }
|
||||
};
|
||||
// Saved chat is optional: when it does not fit, keep the rest of the record.
|
||||
if (!write(scoped) && !write(scoped.filter(query => taskChatFirstFrameRef(query.queryKey) === null))) storage.removeItem(key);
|
||||
}
|
||||
const userPrefix = `${QUERY_CACHE_PREFIX}${encodeURIComponent(userId)}:`;
|
||||
for (const key of storageKeys(storage)) {
|
||||
@@ -459,6 +555,7 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
||||
}
|
||||
if (event.type === "observerAdded" && event.query.queryKey[0] === "issues" && event.query.queryKey[1] === "detail") visits.set(event.query.queryHash, now());
|
||||
const issueDetail = event.query.queryKey[0] === "issues" && event.query.queryKey[1] === "detail";
|
||||
const chatRef = taskChatFirstFrameRef(event.query.queryKey);
|
||||
if (event.type === "updated" && event.action.type === "success" && !event.action.manual) {
|
||||
blockedQueries.delete(hashKey(event.query.queryKey));
|
||||
if (issueDetail) for (const id of issueRefs(event.query)) deniedIssues.delete(id);
|
||||
@@ -467,14 +564,24 @@ export function startPersistedQueryCache(client: QueryClient, options: {
|
||||
blockedQueries.add(hashKey(event.query.queryKey));
|
||||
const userId = owner ?? userIdOf(client.getQueryData(queryKeys.auth.session));
|
||||
const saved = userId ? readSaved(userId) : [];
|
||||
if (issueDetail && ["auth", "forbidden", "not_found"].includes(classifyError(event.action.error))) {
|
||||
const ids = new Set(issueRefs(event.query));
|
||||
const matches = (query: Query) => query.queryKey[0] === "issues" && query.queryKey[1] === "detail"
|
||||
&& issueRefs(query).some(id => ids.has(id));
|
||||
if ((issueDetail || chatRef !== null) && ["auth", "forbidden", "not_found"].includes(classifyError(event.action.error))) {
|
||||
// A refused task read, or a refused read of its saved chat, removes the
|
||||
// task and its saved chat at once, from memory and from storage.
|
||||
const ids = new Set(issueDetail ? issueRefs(event.query) : [chatRef!.toLowerCase()]);
|
||||
const matches = (query: Query) => {
|
||||
const ref = taskChatFirstFrameRef(query.queryKey);
|
||||
if (ref !== null) return ids.has(ref.toLowerCase());
|
||||
return query.queryKey[0] === "issues" && query.queryKey[1] === "detail" && issueRefs(query).some(id => ids.has(id));
|
||||
};
|
||||
for (const query of [...client.getQueryCache().getAll(), ...saved.flatMap(entry => entry.state.queries)].filter(query => Array.isArray(query?.queryKey) && query.queryKey[0] === "issues" && query.queryKey[1] === "detail" && issueRefs(query).some(id => ids.has(id)))) {
|
||||
for (const id of issueRefs(query)) ids.add(id);
|
||||
}
|
||||
for (const id of ids) deniedIssues.add(id);
|
||||
// Chat keys of the task's other refs (an id when it was read by identifier).
|
||||
for (const query of client.getQueryCache().getAll()) {
|
||||
const ref = taskChatFirstFrameRef(query.queryKey);
|
||||
if (ref !== null && ids.has(ref.toLowerCase())) deniedIssues.add(ref.toLowerCase());
|
||||
}
|
||||
void client.cancelQueries({ predicate: matches }, { revert: false, silent: true });
|
||||
for (const query of client.getQueryCache().getAll().filter(matches)) query.setState({ data: undefined, dataUpdatedAt: 0,
|
||||
error: event.action.error, status: "error", fetchStatus: "idle" });
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 {
|
||||
adoptHardLoadChatBootstrap,
|
||||
readFromIssueChatBootstrap,
|
||||
resetIssueChatBootstrapsForTest,
|
||||
startIssueChatBootstrap,
|
||||
@@ -138,6 +139,24 @@ describe("a task restored from the saved read cache", () => {
|
||||
expect(ownRead).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("is shared with readers that start before the task page mounts, by any ref the task is known by", async () => {
|
||||
const { client } = restoredPage();
|
||||
let respond!: (item: ChatBootstrapItem) => void;
|
||||
earlyBootstrap(new Promise((resolve) => { respond = resolve; }));
|
||||
// App start, before any route renders.
|
||||
adoptHardLoadChatBootstrap(client);
|
||||
const ownRead = vi.fn(async () => []);
|
||||
const byId = readFromIssueChatBootstrap(client, queryKeys.issues.liveRuns(TASK_ID), TASK_ID, (item) => item.liveRuns, ownRead);
|
||||
const byRef = readFromIssueChatBootstrap(client, queryKeys.issues.liveRuns(REF), REF, (item) => item.liveRuns, ownRead);
|
||||
respond(answer({ liveRuns: [{ id: "run-1" }] as never }));
|
||||
await expect(byId).resolves.toEqual([{ id: "run-1" }]);
|
||||
await expect(byRef).resolves.toEqual([{ id: "run-1" }]);
|
||||
expect(ownRead).not.toHaveBeenCalled();
|
||||
// The task page's own start reuses the adopted request.
|
||||
await startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
||||
expect(api.chatBootstrap).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" });
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import type { Issue, 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 { resetIssueChatBootstrapsForTest, startIssueChatBootstrap, type ChatBootstrapItem } from "./issue-chat-bootstrap";
|
||||
import { fetchRecentIssueActivity, issueCommentInputFactsQueryKey, recentIssueActivityQueryKey, recentIssueRunWindowQueryKey } from "./issue-chat-history-queries";
|
||||
import { getIssueRecentCommentsQueryOptions } from "./issue-comment-window-query";
|
||||
import {
|
||||
clearPersistedQueryCache,
|
||||
isRestoredSavedRead,
|
||||
QUERY_CACHE_MAX_AGE,
|
||||
QUERY_CACHE_PREFIX,
|
||||
SAVED_TASK_CHAT_MAX_BYTES,
|
||||
SAVED_TASK_CHAT_MAX_COMMENTS,
|
||||
SAVED_TASK_CHAT_MAX_TASK_BYTES,
|
||||
startPersistedQueryCache,
|
||||
taskChatFirstFrameRef,
|
||||
} from "./persisted-query-cache";
|
||||
import { queryKeys } from "./queryKeys";
|
||||
|
||||
// The first chat frame of a recently opened task is saved with the rest of
|
||||
// the read cache, so a hard load shows it before any response. The owner
|
||||
// approved saving recent comments on 2026-11-14, within these guardrails.
|
||||
|
||||
const api = vi.hoisted(() => ({ chatBootstrap: vi.fn(), getSession: vi.fn(), recentComments: vi.fn(), listComments: vi.fn(), recentForIssue: vi.fn() }));
|
||||
vi.mock("@/api/issues", () => ({ issuesApi: { chatBootstrap: api.chatBootstrap, recentComments: api.recentComments, listComments: api.listComments } }));
|
||||
vi.mock("@/api/activity", () => ({ activityApi: { recentForIssue: api.recentForIssue } }));
|
||||
vi.mock("@/api/auth", () => ({ authApi: { getSession: api.getSession } }));
|
||||
|
||||
class MemoryStorage {
|
||||
values = new Map<string, string>();
|
||||
quota = Number.POSITIVE_INFINITY;
|
||||
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) {
|
||||
if (value.length > this.quota) throw new DOMException("Quota exceeded", "QuotaExceededError");
|
||||
this.values.set(key, value);
|
||||
}
|
||||
removeItem(key: string) { this.values.delete(key); }
|
||||
text() { return [...this.values.values()].join(" "); }
|
||||
}
|
||||
|
||||
const COMPANY = "company-one";
|
||||
const session = (id: string) => ({ session: { id: `session-${id}`, userId: id }, user: { id, name: id, email: `${id}@example.test`, image: null } });
|
||||
const coreKey = (ref: string) => [...queryKeys.issues.detail(ref), "core"];
|
||||
const commentsKey = (ref: string) => [...queryKeys.issues.comments(ref), "recent"];
|
||||
const task = (n: number, companyId = COMPANY) => ({ id: `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`, identifier: `ABC-${n}`, companyId, title: `Task ${n}`, status: "todo" });
|
||||
|
||||
function recentComments(n: number, count = 3, body = "Saved reply"): IssueRecentComments {
|
||||
const comments = Array.from({ length: count }, (_, index) => ({ id: `comment-${n}-${index}`, body: `${body} ${index}`, createdAt: "2026-11-14T00:00:00Z" }));
|
||||
return { comments, latestCommentId: comments.at(-1)?.id ?? null, oldestCommentId: comments[0]?.id ?? null, hasMore: false } as unknown as IssueRecentComments;
|
||||
}
|
||||
|
||||
const handles: Array<() => void> = [];
|
||||
function page(storage: MemoryStorage, options: { now?: () => number; user?: string | null; companies?: string[] } = {}) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
if (options.user) client.setQueryData(queryKeys.auth.session, session(options.user));
|
||||
const handle = startPersistedQueryCache(client, { storage, now: options.now, buildId: "build-one", eventTarget: null, debounceMs: 100_000 });
|
||||
handles.push(() => { handle.dispose(); client.clear(); });
|
||||
return { client, handle };
|
||||
}
|
||||
|
||||
function signIn(client: QueryClient, user = "alice", companies = [COMPANY]) {
|
||||
client.setQueryData(queryKeys.auth.session, session(user));
|
||||
client.setQueryData(queryKeys.companies.list(user), { companies: companies.map((id) => ({ id, name: id })), unauthorized: false });
|
||||
}
|
||||
|
||||
/** A task the user opened: its record and its first chat frame. */
|
||||
function openTask(client: QueryClient, n: number, options: { companyId?: string; comments?: IssueRecentComments; updatedAt?: number } = {}) {
|
||||
const issue = task(n, options.companyId);
|
||||
const at = { updatedAt: options.updatedAt ?? Date.now() };
|
||||
client.setQueryData(coreKey(issue.identifier), issue, at);
|
||||
client.setQueryData(coreKey(issue.id), issue, at);
|
||||
client.setQueryData(commentsKey(issue.identifier), options.comments ?? recentComments(n), at);
|
||||
client.setQueryData(recentIssueActivityQueryKey(issue.identifier), [{ id: `event-${n}` }], at);
|
||||
client.setQueryData(recentIssueRunWindowQueryKey(issue.identifier), { runs: [] }, at);
|
||||
client.setQueryData([...issueCommentInputFactsQueryKey(issue.identifier), "batch-ids"], [[`comment-${n}-0`]], at);
|
||||
client.setQueryData([...issueCommentInputFactsQueryKey(issue.identifier), "batch", [`comment-${n}-0`]], [], at);
|
||||
client.setQueryData(queryKeys.issues.interactions(issue.identifier), [], at);
|
||||
client.setQueryData(queryKeys.issues.attachments(issue.identifier), [{ id: `attachment-${n}`, originalFilename: "notes.txt", contentPath: "/api/attachments/x/content" }], at);
|
||||
client.setQueryData(queryKeys.issues.liveRuns(issue.identifier), [], at);
|
||||
client.setQueryData(queryKeys.issues.workProducts(issue.identifier), [], at);
|
||||
client.setQueryData([...queryKeys.issues.documents(issue.id), "plan"], { key: "plan", body: "# Plan" }, at);
|
||||
return issue;
|
||||
}
|
||||
|
||||
function savedPage(setup: (client: QueryClient) => void, storage = new MemoryStorage()) {
|
||||
const first = page(storage);
|
||||
signIn(first.client);
|
||||
setup(first.client);
|
||||
first.handle.flush();
|
||||
return storage;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetIssueChatBootstrapsForTest();
|
||||
api.chatBootstrap.mockReset();
|
||||
});
|
||||
afterEach(() => {
|
||||
for (const dispose of handles.splice(0)) dispose();
|
||||
delete (window as unknown as Record<string, unknown>)[EARLY_CHAT_BOOTSTRAP_GLOBAL];
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("saved first chat frame of a recently opened task", () => {
|
||||
it("is restored on the next hard load, shown at once and marked for revalidation", () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1); });
|
||||
const { client } = page(storage);
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toMatchObject({ latestCommentId: "comment-1-2" });
|
||||
for (const key of [commentsKey("ABC-1"), recentIssueActivityQueryKey("ABC-1"), queryKeys.issues.liveRuns("ABC-1"), [...queryKeys.issues.documents(task(1).id), "plan"]]) {
|
||||
expect(isRestoredSavedRead(client, key)).toBe(true);
|
||||
expect(client.getQueryState(key)?.isInvalidated).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("recognises exactly the first-frame reads", () => {
|
||||
expect(taskChatFirstFrameRef(commentsKey("ABC-1"))).toBe("ABC-1");
|
||||
expect(taskChatFirstFrameRef([...issueCommentInputFactsQueryKey("ABC-1"), "batch", ["c"]])).toBe("ABC-1");
|
||||
expect(taskChatFirstFrameRef(queryKeys.issues.comments("ABC-1"))).toBeNull();
|
||||
expect(taskChatFirstFrameRef([...queryKeys.issues.comments("ABC-1"), "earlier"])).toBeNull();
|
||||
expect(taskChatFirstFrameRef(queryKeys.issues.activity("ABC-1"))).toBeNull();
|
||||
expect(taskChatFirstFrameRef(queryKeys.issues.queuedComments("ABC-1"))).toBeNull();
|
||||
expect(taskChatFirstFrameRef([...queryKeys.issues.documents("ABC-1")])).toBeNull();
|
||||
});
|
||||
|
||||
describe("bounds", () => {
|
||||
it("keeps only the newest comments of a long window and says more exist", () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1, { comments: recentComments(1, SAVED_TASK_CHAT_MAX_COMMENTS + 10) }); });
|
||||
const restored = page(storage).client.getQueryData<IssueRecentComments>(commentsKey("ABC-1"))!;
|
||||
expect(restored.comments).toHaveLength(SAVED_TASK_CHAT_MAX_COMMENTS);
|
||||
expect(restored.comments.at(-1)).toMatchObject({ id: `comment-1-${SAVED_TASK_CHAT_MAX_COMMENTS + 9}` });
|
||||
expect(restored).toMatchObject({ hasMore: true, oldestCommentId: "comment-1-10" });
|
||||
});
|
||||
|
||||
it("saves chat only for the twenty most recently opened tasks", () => {
|
||||
const start = Date.now() - 60_000;
|
||||
const storage = savedPage((client) => { for (let n = 1; n <= 21; n += 1) openTask(client, n, { updatedAt: start + n * 1_000 }); });
|
||||
const { client } = page(storage);
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
expect(client.getQueryData(coreKey("ABC-1"))).toBeUndefined();
|
||||
// Nothing of the older task's chat is left on disk either.
|
||||
expect(storage.text()).not.toContain("comment-1-0");
|
||||
for (const n of [2, 21]) expect(client.getQueryData(commentsKey(`ABC-${n}`))).toBeDefined();
|
||||
});
|
||||
|
||||
it("skips a task whose chat exceeds the per-task budget and keeps its record", () => {
|
||||
const huge = recentComments(1, 3, "x".repeat(SAVED_TASK_CHAT_MAX_TASK_BYTES));
|
||||
const storage = savedPage((client) => { openTask(client, 1, { comments: huge }); openTask(client, 2); });
|
||||
const { client } = page(storage);
|
||||
expect(client.getQueryData(coreKey("ABC-1"))).toBeDefined();
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
expect(client.getQueryData(commentsKey("ABC-2"))).toBeDefined();
|
||||
});
|
||||
|
||||
it("stops at the total budget, newest tasks first", () => {
|
||||
const body = "y".repeat(Math.floor(SAVED_TASK_CHAT_MAX_TASK_BYTES * 0.8));
|
||||
const count = Math.ceil(SAVED_TASK_CHAT_MAX_BYTES / (SAVED_TASK_CHAT_MAX_TASK_BYTES * 0.8)) + 2;
|
||||
const start = Date.now() - 60_000;
|
||||
const storage = savedPage((client) => {
|
||||
for (let n = 1; n <= count; n += 1) openTask(client, n, { comments: recentComments(n, 1, body), updatedAt: start + n * 1_000 });
|
||||
});
|
||||
const { client } = page(storage);
|
||||
expect(client.getQueryData(commentsKey(`ABC-${count}`))).toBeDefined();
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
const savedChars = [...storage.values.values()].reduce((sum, value) => sum + value.length, 0);
|
||||
expect(savedChars).toBeLessThan(SAVED_TASK_CHAT_MAX_BYTES + 256 * 1024);
|
||||
});
|
||||
|
||||
it("keeps the rest of the record when storage refuses the saved chat", () => {
|
||||
const storage = new MemoryStorage();
|
||||
const withoutChat = savedPage((client) => { openTask(client, 1); }, new MemoryStorage());
|
||||
const plainRecord = [...withoutChat.values.entries()].find(([key]) => key.endsWith(`:${COMPANY}`))![1];
|
||||
// Room for the record, not for its saved chat.
|
||||
storage.quota = plainRecord.length - 200;
|
||||
savedPage((client) => { openTask(client, 1); }, storage);
|
||||
const { client } = page(storage);
|
||||
expect(client.getQueryData(coreKey("ABC-1"))).toMatchObject({ title: "Task 1" });
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it("expires a fixed time after it was read, even while the rest of the cache stays current", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
const start = Date.now();
|
||||
let now = start;
|
||||
const storage = new MemoryStorage();
|
||||
const first = page(storage, { now: () => now });
|
||||
signIn(first.client);
|
||||
openTask(first.client, 1, { updatedAt: now });
|
||||
first.handle.flush();
|
||||
// A later visit reads the session and companies again and saves, but not the task's chat.
|
||||
now = start + QUERY_CACHE_MAX_AGE / 2;
|
||||
vi.setSystemTime(now);
|
||||
const second = page(storage, { now: () => now });
|
||||
// The session read verifies the restored account, so this visit saves again.
|
||||
await second.client.fetchQuery({ queryKey: queryKeys.auth.session, queryFn: async () => session("alice") });
|
||||
signIn(second.client);
|
||||
expect(second.client.getQueryData(commentsKey("ABC-1"))).toBeDefined();
|
||||
second.handle.flush();
|
||||
now = start + QUERY_CACHE_MAX_AGE + 1;
|
||||
vi.setSystemTime(now);
|
||||
const { client } = page(storage, { now: () => now });
|
||||
expect(client.getQueryData(queryKeys.companies.list("alice"))).toBeDefined();
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
});
|
||||
|
||||
describe("revocation", () => {
|
||||
it.each([403, 404, 401])("removes the task's saved chat at once after a %s on its revalidation", async (status) => {
|
||||
const storage = savedPage((client) => { openTask(client, 1); openTask(client, 2); });
|
||||
const { client } = page(storage);
|
||||
await client.fetchQuery({ queryKey: commentsKey("ABC-1"), queryFn: async () => { throw new ApiError("Refused", status, null); } }).catch(() => {});
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
expect(client.getQueryData(coreKey("ABC-1"))).toBeUndefined();
|
||||
expect(storage.text()).not.toContain("comment-1-0");
|
||||
expect(storage.text()).toContain("comment-2-0");
|
||||
const reloaded = page(storage).client;
|
||||
expect(reloaded.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
expect(reloaded.getQueryData(commentsKey("ABC-2"))).toBeDefined();
|
||||
});
|
||||
|
||||
it("removes the saved chat when the task record itself is refused", async () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1); });
|
||||
const { client } = page(storage);
|
||||
await client.fetchQuery({ queryKey: coreKey("ABC-1"), queryFn: async () => { throw new ApiError("Forbidden", 403, null); } }).catch(() => {});
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
expect(storage.text()).not.toContain("comment-1-0");
|
||||
expect(page(storage).client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isolation", () => {
|
||||
it("is cleared on sign-out", () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1); });
|
||||
const { client } = page(storage);
|
||||
clearPersistedQueryCache(client);
|
||||
expect(storage.text()).not.toContain("comment-1-0");
|
||||
expect(page(storage).client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
});
|
||||
|
||||
it("is never restored for another user", () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1); });
|
||||
const { client } = page(storage, { user: "bob" });
|
||||
expect(client.getQueryData(commentsKey("ABC-1"))).toBeUndefined();
|
||||
});
|
||||
|
||||
it("is saved in its task's company record and never in another company's", () => {
|
||||
const storage = new MemoryStorage();
|
||||
const first = page(storage);
|
||||
signIn(first.client, "alice", [COMPANY, "company-two"]);
|
||||
openTask(first.client, 1);
|
||||
openTask(first.client, 2, { companyId: "company-two" });
|
||||
first.handle.flush();
|
||||
const record = (companyId: string) => storage.getItem(`${QUERY_CACHE_PREFIX}alice:${companyId}`) ?? "";
|
||||
expect(record(COMPANY)).toContain("comment-1-0");
|
||||
expect(record(COMPANY)).not.toContain("comment-2-0");
|
||||
expect(record("company-two")).toContain("comment-2-0");
|
||||
expect(record("company-two")).not.toContain("comment-1-0");
|
||||
});
|
||||
|
||||
it("is not saved for a task whose company the user no longer has", () => {
|
||||
const storage = savedPage((client) => { openTask(client, 3, { companyId: "company-gone" }); });
|
||||
expect(storage.text()).not.toContain("comment-3-0");
|
||||
});
|
||||
});
|
||||
|
||||
it("saves only what the first frame shows: no secrets or excluded fields", () => {
|
||||
const storage = savedPage((client) => {
|
||||
openTask(client, 1, { comments: { ...recentComments(1), comments: [{ id: "c", body: "Visible", token: "secret-token", apiKey: "secret-key", documents: [{ body: "doc" }] }] } as unknown as IssueRecentComments });
|
||||
client.setQueryData(recentIssueRunWindowQueryKey("ABC-1"), { runs: [{ id: "r", env: { SECRET: "secret-env" }, credentials: "secret-creds" }] });
|
||||
});
|
||||
expect(storage.text()).toContain("Visible");
|
||||
for (const secret of ["secret-token", "secret-key", "secret-env", "secret-creds", "\"documents\":"]) expect(storage.text()).not.toContain(secret);
|
||||
});
|
||||
|
||||
describe("freshness", () => {
|
||||
it("never replaces newer data already in the page", () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1, { updatedAt: Date.now() - 10_000 }); });
|
||||
const client = new QueryClient();
|
||||
client.setQueryData(commentsKey("ABC-1"), recentComments(1, 1, "Newer from the server"));
|
||||
const handle = startPersistedQueryCache(client, { storage, buildId: "build-one", eventTarget: null, debounceMs: 100_000 });
|
||||
handles.push(() => { handle.dispose(); client.clear(); });
|
||||
expect(client.getQueryData<IssueRecentComments>(commentsKey("ABC-1"))!.comments[0]).toMatchObject({ body: "Newer from the server 0" });
|
||||
});
|
||||
|
||||
it("is replaced, not merged, by its first refresh: a comment deleted on the server disappears", async () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1); });
|
||||
const { client } = page(storage);
|
||||
// comment-1-1 was deleted while the browser was closed.
|
||||
const current = { ...recentComments(1), comments: recentComments(1).comments.filter((comment) => comment.id !== "comment-1-1") };
|
||||
api.recentComments.mockResolvedValue(current);
|
||||
api.listComments.mockResolvedValue([]);
|
||||
const refreshed = await client.fetchQuery({ ...getIssueRecentCommentsQueryOptions(client, "ABC-1"), queryFn: ({ signal }) => getIssueRecentCommentsQueryOptions(client, "ABC-1").queryFn({ signal }) });
|
||||
expect(refreshed.comments.map((comment) => comment.id)).toEqual(["comment-1-0", "comment-1-2"]);
|
||||
});
|
||||
|
||||
it("replaces restored activity with its first refresh", async () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1); });
|
||||
const { client } = page(storage);
|
||||
api.recentForIssue.mockResolvedValue([{ id: "event-current" }]);
|
||||
await expect(fetchRecentIssueActivity(client, "ABC-1")).resolves.toEqual([{ id: "event-current" }]);
|
||||
});
|
||||
|
||||
it("is replaced by the bootstrap when it arrives", async () => {
|
||||
const storage = savedPage((client) => { openTask(client, 1); });
|
||||
const { client } = page(storage);
|
||||
const fresh = recentComments(1, 1, "From the bootstrap");
|
||||
const item = {
|
||||
ref: "ABC-1", issue: { ...task(1), title: "Current" } as unknown as Issue, recentComments: fresh, commentInputFacts: [],
|
||||
recentActivity: [{ id: "event-new" }], recentRuns: [], interactions: [], attachments: [], liveRuns: [], activeRun: null,
|
||||
} as unknown as ChatBootstrapItem;
|
||||
(window as unknown as Record<string, unknown>)[EARLY_CHAT_BOOTSTRAP_GLOBAL] = { ref: "ABC-1", startedAt: Date.now(), promise: Promise.resolve(item) };
|
||||
await startIssueChatBootstrap(client, COMPANY, "ABC-1", [task(1).id]);
|
||||
expect(client.getQueryData<IssueRecentComments>(commentsKey("ABC-1"))!.comments[0]).toMatchObject({ body: "From the bootstrap 0" });
|
||||
expect(client.getQueryData(recentIssueActivityQueryKey("ABC-1"))).toEqual([{ id: "event-new" }]);
|
||||
expect(isRestoredSavedRead(client, commentsKey("ABC-1"))).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,7 @@ import { connectivity } from "./lib/connectivity";
|
||||
import { bindConnectivity, createAppQueryClient } from "./lib/query-client";
|
||||
import { captureQueryException } from "./lib/sentry";
|
||||
import { startPersistedQueryCache } from "./lib/persisted-query-cache";
|
||||
import { adoptHardLoadChatBootstrap } from "./lib/issue-chat-bootstrap";
|
||||
import { hasPendingWrites, subscribePendingWrites } from "./lib/reload-safety";
|
||||
import "@mdxeditor/editor/style.css";
|
||||
import "./index.css";
|
||||
@@ -89,6 +90,8 @@ bindConnectivity(queryClient, connectivity);
|
||||
startPersistedQueryCache(queryClient, {
|
||||
buildId: typeof __PAPERCLIP_BUILD_COMMIT__ === "string" ? __PAPERCLIP_BUILD_COMMIT__ : null,
|
||||
});
|
||||
// Readers that start before the task page mounts share a hard load's bootstrap.
|
||||
adoptHardLoadChatBootstrap(queryClient);
|
||||
window.addEventListener("load", () => {
|
||||
startServiceWorkerUpdates({
|
||||
canReload: () => connectivity.getSnapshot().status === "online"
|
||||
|
||||
@@ -3650,7 +3650,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
const { data: liveRunSummary = EMPTY_LIVE_RUN_SUMMARY } = useQuery<LiveRunForIssue[], Error, LiveRunSummary>(
|
||||
{
|
||||
queryKey: queryKeys.issues.liveRuns(issueId!),
|
||||
queryFn: () => heartbeatsApi.liveRunsForIssue(issueId!),
|
||||
// Shares the chat's read: whichever observer mounts first must not send
|
||||
// its own request while the page's bootstrap is loading.
|
||||
queryFn: () => readFromIssueChatBootstrap(queryClient, queryKeys.issues.liveRuns(issueId!), issueId!, (item) => item.liveRuns, () => heartbeatsApi.liveRunsForIssue(issueId!)),
|
||||
enabled: !!issueId,
|
||||
refetchInterval: (query) => liveRunRefetchInterval(hasLiveConnection, query.state, 3000),
|
||||
select: summarizeLiveRuns,
|
||||
|
||||
Reference in new issue
Block a user