Files
PaperClipAI/ui/src/lib/saved-task-chat.test.ts
T
DottaandClaude Opus 5.5 fad8f051ca fix(ui): keep a saved task when its plan, run or work-product read answers 404 (#21684)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - #21671 saves the first chat frame of recently opened tasks in the
browser's read cache, so a hard load shows the chat before any response.
> - It also removes a task's saved data at once when a read of the task
or its chat is refused (401, 403 or 404).
> - A task without a plan answers 404 on `GET
/issues/:id/documents/plan`. That is a normal answer, but a reader that
does not catch it records a query error.
> - The cache treated that 404 as "the task is gone" and removed the
task and its saved chat. On staging, a task without a plan was therefore
never saved, so it never opened from the saved chat.
> - This pull request revokes on a 404 only for the task record and its
comments. 401 and 403 still revoke on every chat read.
> - The benefit is that tasks without a plan (most tasks) open from the
saved chat as intended.

## Linked Issues or Issue Description

**Describe the bug**
After #21671, a task without a plan is not kept in the saved read cache.
The first chat frame is not shown from the saved cache for that task.

**Steps to reproduce**
1. Open a task that has no plan document (for example PAP-4463 on
staging).
2. Look at the saved read cache (`paperclip:query-cache:v1:*` in local
storage) after the page settles.
3. The task's record and chat are missing. The page shows `GET
/api/issues/:id/documents/plan` answering 404.

**Expected behavior**
A 404 for a missing plan, active run or work products keeps the task.
Only a refusal of the task itself (its record or comments, or any
401/403) removes it.

**Actual behavior**
Any 404 on a saved chat read removes the task and its saved chat from
memory and storage.

Refs #21671.

## What Changed

- `ui/src/lib/persisted-query-cache.ts`: a chat read revokes the task on
401 or 403, or on 404 only for the recent comments. The task record
keeps revoking on 401, 403 and 404.
- `ui/src/lib/saved-task-chat.test.ts`: a 404 for a missing plan, active
run or work products keeps the task and its saved chat.
- `doc/ui-internals.md`: the read-cache rules state which 404s revoke.

## Verification

- `cd ui && npx vitest run src/lib/saved-task-chat.test.ts`: 24 passed.
With the change in `persisted-query-cache.ts` reverted, the 3 new cases
fail. The existing 401/403/404 revocation cases on recent comments still
pass.
- `src/lib/persisted-query-cache.test.ts` and
`src/lib/restored-task-chat-bootstrap.test.ts` pass (90 tests across the
three files). `pnpm --filter @paperclipai/ui typecheck` passes.
- Staging evidence (build `fc9e4cbbb`, PAP-4463): the only 4xx during
the load was `GET /api/issues/:id/documents/plan` 404, and the saved
record did not hold the task.

## Risks

- Low risk. A 404 on a plan, run or work-product read no longer revokes
the task. A task that was deleted or made unreadable still answers 404
or 403 on its record and comments, and that removes it. Any 401 or 403
still 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).

## 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>
2026-11-14 18:43:18 -06:00

336 lines
19 KiB
TypeScript

// @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.each([
["a missing plan", [...queryKeys.issues.documents(task(1).id), "plan"]],
["a missing active run", queryKeys.issues.activeRun("ABC-1")],
["missing work products", queryKeys.issues.workProducts("ABC-1")],
])("keeps the task after a 404 for %s, which does not mean the task is gone", async (_name, key) => {
const storage = savedPage((client) => { openTask(client, 1); });
const { client } = page(storage);
await client.fetchQuery({ queryKey: key as readonly unknown[], queryFn: async () => { throw new ApiError("Not found", 404, null); } }).catch(() => {});
expect(client.getQueryData(coreKey("ABC-1"))).toBeDefined();
expect(client.getQueryData(commentsKey("ABC-1"))).toBeDefined();
expect(storage.text()).toContain("comment-1-0");
});
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);
});
});
});