mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-18 14:35:55 +01:00
## 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>
232 lines
12 KiB
TypeScript
232 lines
12 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { QueryClient } from "@tanstack/react-query";
|
|
import type { Issue, IssueDocument, IssueRecentComments } from "@paperclipai/shared";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { ApiError } from "@/api/client";
|
|
import { EARLY_CHAT_BOOTSTRAP_GLOBAL } from "./issue-detail-preload-events";
|
|
import {
|
|
adoptHardLoadChatBootstrap,
|
|
readFromIssueChatBootstrap,
|
|
resetIssueChatBootstrapsForTest,
|
|
startIssueChatBootstrap,
|
|
type ChatBootstrapItem,
|
|
} from "./issue-chat-bootstrap";
|
|
import { recentIssueActivityQueryKey } from "./issue-chat-history-queries";
|
|
import { getIssueCoreQueryOptions } from "./issueDetailCache";
|
|
import { isRestoredSavedRead, startPersistedQueryCache } from "./persisted-query-cache";
|
|
import { queryKeys } from "./queryKeys";
|
|
|
|
// A hard load of a task that the saved read cache remembers: the task's core
|
|
// fields are restored (and shown at once), its chat history is not saved, and
|
|
// the page's chat bootstrap revalidates both.
|
|
|
|
const api = vi.hoisted(() => ({ chatBootstrap: vi.fn(), getCore: vi.fn(), getSession: vi.fn() }));
|
|
vi.mock("@/api/issues", () => ({ issuesApi: { chatBootstrap: api.chatBootstrap, getCore: api.getCore } }));
|
|
vi.mock("@/api/auth", () => ({ authApi: { getSession: api.getSession } }));
|
|
|
|
class MemoryStorage {
|
|
values = new Map<string, string>();
|
|
get length() { return this.values.size; }
|
|
key(index: number) { return [...this.values.keys()][index] ?? null; }
|
|
getItem(key: string) { return this.values.get(key) ?? null; }
|
|
setItem(key: string, value: string) { this.values.set(key, value); }
|
|
removeItem(key: string) { this.values.delete(key); }
|
|
}
|
|
|
|
const TASK_ID = "00000000-0000-4000-8000-000000000007";
|
|
const REF = "ABC-7";
|
|
const coreKey = (ref: string) => [...queryKeys.issues.detail(ref), "core"];
|
|
const savedTask = { id: TASK_ID, identifier: REF, companyId: "company-one", title: "Saved title", status: "todo" };
|
|
const session = (id: string) => ({ session: { id: `session-${id}`, userId: id }, user: { id, name: id, email: `${id}@example.test`, image: null } });
|
|
|
|
function answer(overrides: Partial<ChatBootstrapItem> = {}): ChatBootstrapItem {
|
|
const comment = { id: "comment-1", body: "Latest reply", createdAt: "2026-11-14T00:00:00Z" };
|
|
return {
|
|
ref: REF,
|
|
issue: { ...savedTask, title: "Current title" } as unknown as Issue,
|
|
recentComments: { comments: [comment], latestCommentId: comment.id, hasMore: false } as unknown as IssueRecentComments,
|
|
commentInputFacts: [],
|
|
recentActivity: [{ id: "event-1" }] as never,
|
|
recentRuns: [],
|
|
interactions: [],
|
|
attachments: [],
|
|
liveRuns: [],
|
|
activeRun: null,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
const disposers: Array<() => void> = [];
|
|
/** A new page whose saved read cache remembers `savedTask` for alice. */
|
|
function restoredPage(storage = savedStorage()) {
|
|
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
const handle = startPersistedQueryCache(client, { storage, buildId: "build-one", eventTarget: null, debounceMs: 100_000 });
|
|
disposers.push(() => { handle.dispose(); client.clear(); });
|
|
return { client, handle, storage };
|
|
}
|
|
|
|
function savedStorage() {
|
|
const storage = new MemoryStorage();
|
|
const client = new QueryClient();
|
|
const handle = startPersistedQueryCache(client, { storage, buildId: "build-one", eventTarget: null, debounceMs: 100_000 });
|
|
client.setQueryData(queryKeys.auth.session, session("alice"));
|
|
client.setQueryData(queryKeys.companies.list("alice"), { companies: [{ id: "company-one", name: "Example" }], unauthorized: false });
|
|
for (const ref of [REF, TASK_ID]) client.setQueryData(coreKey(ref), savedTask);
|
|
handle.flush();
|
|
handle.dispose();
|
|
client.clear();
|
|
return storage;
|
|
}
|
|
|
|
/** The fetch a hard load's inline script starts before the app runs. */
|
|
function earlyBootstrap(promise: Promise<ChatBootstrapItem | null>) {
|
|
(window as unknown as Record<string, unknown>)[EARLY_CHAT_BOOTSTRAP_GLOBAL] = { ref: REF, startedAt: Date.now(), promise };
|
|
}
|
|
|
|
/** The page's own revalidation of the restored core task, as `useQuery` runs it. */
|
|
function revalidateCore(client: QueryClient, ref = REF) {
|
|
return client.fetchQuery({ ...getIssueCoreQueryOptions(client, ref), queryFn: ({ signal }) => getIssueCoreQueryOptions(client, ref).queryFn({ signal }) });
|
|
}
|
|
|
|
beforeEach(() => {
|
|
resetIssueChatBootstrapsForTest();
|
|
api.chatBootstrap.mockReset();
|
|
api.getCore.mockReset();
|
|
api.getCore.mockImplementation(async () => ({ ...savedTask, title: "Read on its own" }));
|
|
});
|
|
afterEach(() => {
|
|
for (const dispose of disposers.splice(0)) dispose();
|
|
delete (window as unknown as Record<string, unknown>)[EARLY_CHAT_BOOTSTRAP_GLOBAL];
|
|
});
|
|
|
|
describe("a task restored from the saved read cache", () => {
|
|
it("is shown at once and marked as not yet read in this page", () => {
|
|
const { client } = restoredPage();
|
|
expect(client.getQueryData(coreKey(REF))).toMatchObject({ title: "Saved title" });
|
|
expect(isRestoredSavedRead(client, coreKey(REF))).toBe(true);
|
|
// Chat history is never saved, so the chat opens like a cold one.
|
|
expect(client.getQueryData([...queryKeys.issues.comments(REF), "recent"])).toBeUndefined();
|
|
});
|
|
|
|
it("revalidates through the page's bootstrap: one request refreshes the restored task and fills the chat", async () => {
|
|
const { client } = restoredPage();
|
|
let respond!: (item: ChatBootstrapItem) => void;
|
|
earlyBootstrap(new Promise((resolve) => { respond = resolve; }));
|
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID, REF]);
|
|
const core = revalidateCore(client);
|
|
respond(answer());
|
|
await expect(core).resolves.toMatchObject({ title: "Current title" });
|
|
expect(api.getCore).not.toHaveBeenCalled();
|
|
// Every ref the task is known by now holds the current answer, read in this page.
|
|
for (const ref of [REF, TASK_ID]) {
|
|
expect(client.getQueryData(coreKey(ref))).toMatchObject({ title: "Current title" });
|
|
expect(isRestoredSavedRead(client, coreKey(ref))).toBe(false);
|
|
expect(client.getQueryState(coreKey(ref))?.isInvalidated).toBe(false);
|
|
}
|
|
expect(client.getQueryData([...queryKeys.issues.comments(REF), "recent"])).toMatchObject({ latestCommentId: "comment-1" });
|
|
});
|
|
|
|
it("lets reads keyed by the restored task's id share the bootstrap while it is loading", async () => {
|
|
const { client } = restoredPage();
|
|
let respond!: (item: ChatBootstrapItem) => void;
|
|
earlyBootstrap(new Promise((resolve) => { respond = resolve; }));
|
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
|
const ownRead = vi.fn(async () => null);
|
|
const plan = readFromIssueChatBootstrap<IssueDocument | null | undefined>(client, [...queryKeys.issues.documents(TASK_ID), "plan"], TASK_ID, (item) => item.issue.planDocument, ownRead);
|
|
respond(answer({ issue: { ...answer().issue, planDocument: { key: "plan", body: "# Plan" } } as unknown as Issue }));
|
|
await expect(plan).resolves.toMatchObject({ key: "plan" });
|
|
expect(ownRead).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("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" });
|
|
expect(api.getCore).toHaveBeenCalledOnce();
|
|
expect(isRestoredSavedRead(client, coreKey(REF))).toBe(false);
|
|
});
|
|
|
|
it("falls back to its own reads when the bootstrap fails, replacing the restored task", async () => {
|
|
const { client } = restoredPage();
|
|
earlyBootstrap(Promise.resolve(null));
|
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
|
await expect(revalidateCore(client)).resolves.toMatchObject({ title: "Read on its own" });
|
|
expect(api.getCore).toHaveBeenCalledOnce();
|
|
expect(client.getQueryData(coreKey(REF))).toMatchObject({ title: "Read on its own" });
|
|
});
|
|
|
|
it("uses the fields a partial answer has and reads the missing ones itself", async () => {
|
|
const { client } = restoredPage();
|
|
earlyBootstrap(Promise.resolve(answer({ recentActivity: undefined as never })));
|
|
await startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
|
expect(client.getQueryData(coreKey(REF))).toMatchObject({ title: "Current title" });
|
|
expect(client.getQueryData(recentIssueActivityQueryKey(REF))).toBeUndefined();
|
|
const ownRead = vi.fn(async () => [{ id: "own-event" }]);
|
|
await expect(readFromIssueChatBootstrap(client, recentIssueActivityQueryKey(REF), REF, (item) => item.recentActivity, ownRead))
|
|
.resolves.toEqual([{ id: "own-event" }]);
|
|
expect(ownRead).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("removes the restored task when the user can no longer read it", async () => {
|
|
const { client, storage } = restoredPage();
|
|
// An unreadable task is omitted from (or fails) the bootstrap.
|
|
earlyBootstrap(Promise.resolve(null));
|
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
|
api.getCore.mockImplementation(async () => { throw new ApiError("Forbidden", 403, null); });
|
|
await expect(revalidateCore(client)).rejects.toThrow("Forbidden");
|
|
for (const ref of [REF, TASK_ID]) expect(client.getQueryData(coreKey(ref))).toBeUndefined();
|
|
expect([...storage.values.values()].join(" ")).not.toContain("Saved title");
|
|
});
|
|
|
|
it("never fills another company's task from the bootstrap", async () => {
|
|
const { client } = restoredPage();
|
|
earlyBootstrap(Promise.resolve(answer({ issue: { ...answer().issue, companyId: "company-two" } as unknown as Issue })));
|
|
await startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
|
expect(client.getQueryData(coreKey(REF))).toMatchObject({ title: "Saved title" });
|
|
expect(client.getQueryData([...queryKeys.issues.comments(REF), "recent"])).toBeUndefined();
|
|
await expect(revalidateCore(client)).resolves.toMatchObject({ title: "Read on its own" });
|
|
});
|
|
|
|
it("never uses an answer once another user signs in", async () => {
|
|
const { client } = restoredPage();
|
|
let respond!: (item: ChatBootstrapItem) => void;
|
|
earlyBootstrap(new Promise((resolve) => { respond = resolve; }));
|
|
// The restored session is alice's; the early fetch belongs to her.
|
|
void startIssueChatBootstrap(client, "company-one", REF, [TASK_ID]);
|
|
client.setQueryData(queryKeys.auth.session, session("bob"));
|
|
respond(answer());
|
|
await Promise.resolve();
|
|
await Promise.resolve();
|
|
expect(client.getQueryData([...queryKeys.issues.comments(REF), "recent"])).toBeUndefined();
|
|
expect(client.getQueryData(coreKey(REF))).not.toMatchObject({ title: "Current title" });
|
|
});
|
|
|
|
it("is not restored for another user", () => {
|
|
const storage = savedStorage();
|
|
const client = new QueryClient();
|
|
client.setQueryData(queryKeys.auth.session, session("bob"));
|
|
const handle = startPersistedQueryCache(client, { storage, buildId: "build-one", eventTarget: null, debounceMs: 100_000 });
|
|
disposers.push(() => { handle.dispose(); client.clear(); });
|
|
expect(client.getQueryData(coreKey(REF))).toBeUndefined();
|
|
expect(isRestoredSavedRead(client, coreKey(REF))).toBe(false);
|
|
});
|
|
});
|