Files
PaperClipAI/ui/src/lib/issueChatBootstrapCache.test.ts
T
621c5577cd fix(tasks): hide More messages when no hidden history exists (#22099)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The task page shows the instruction and the recent exchange first,
and shows a **More messages** button for older history
> - The button is visible on almost every task. A click often shows no
new message, and the button then goes away
> - The compact chat shows only the latest run, so the page treats any
task with two or more runs as a task with hidden history
> - The recent comments read also reports more comments when the omitted
comment is already pinned into the window
> - This pull request shows the button only when a message is really
hidden
> - The benefit is a clean task page and a button that always reveals
something

## Linked Issues or Issue Description

Refs #17751

**What happened?**

The task page shows **More messages** on almost every task. A click
often adds no message, and the button then goes away.

**Expected behavior**

The page shows **More messages** only when it hides an older comment or
an older run that has no visible answer.

**Steps to reproduce**

1. Create a task and let an agent answer it in two runs.
2. Open the task with a fresh application cache.
3. See **More messages** above the conversation. Click it. No new
message appears.

## What Changed

- The recent run window keeps the newest omitted run (`earlierRun`), and
it keeps that run as later turns arrive.
- The task page ignores the omitted run when the run succeeded and its
agent answer is already visible. A failed run, or a run with no visible
answer, still shows the button. The answer check is the same one the
chat thread uses (moved to `ui/src/lib/run-answer-visibility.ts`), so a
legacy withheld-run placeholder or a progress comment does not count as
an answer.
- `GET /issues/:id/recent-comments` reads seven rows instead of five. It
sets `hasMore` only when the window leaves out a comment. Older comments
that are pinned into the window (the latest human message and the first
instruction) do not count.
- Added regression tests for the page (including the placeholder case),
the run window cache and the server route.

## Verification

- `pnpm exec vitest run src/pages/IssueDetail.test.tsx
src/components/TaskChatThread.test.tsx src/lib` in `ui`: 3,637 passed, 1
skipped. The new page test fails without the fix.
- After the review fixes: `pnpm exec vitest run
src/pages/IssueDetail.test.tsx src/components/TaskChatThread.test.tsx
src/lib/issueChatBootstrapCache.test.ts
src/lib/issueDetailCache.test.ts` in `ui`: 738 passed, 1 skipped.
- `pnpm exec vitest run src/__tests__/task-cold-open.test.ts
src/__tests__/issue-chat-bootstrap-routes.test.ts` in `server`: 33
passed.
- `tsc --noEmit` in `ui` and `server`: no errors in the changed files.
- I did not do a check in the browser.

## Risks

Low risk. No schema change. The API response shape does not change. The
run window cache gets one optional field, and older saved caches without
the field keep the old behavior.

Limitation: the recent runs read returns only the two latest runs, so
the page sees one omitted run. If that run has a visible answer but an
older run failed, the page does not show the button. **More task actions
→ Show task activity** still shows that run.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with tool use
and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 17:41:17 -08:00

158 lines
8.6 KiB
TypeScript

import { QueryClient } from "@tanstack/react-query";
import type { ActivityEvent, Issue, IssueComment } from "@paperclipai/shared";
import { afterEach, describe, expect, it } from "vitest";
import type { RunForIssue } from "@/api/activity";
import { hasFreshIssueChatFirstFrame, seedIssueChatBootstrap, type IssueChatBootstrapEntry } from "./issueChatBootstrapCache";
import {
issueCommentInputFactsQueryKey,
recentIssueActivityQueryKey,
recentIssueRunWindowQueryKey,
} from "./issue-chat-history-queries";
import { getCachedIssueDetail } from "./issueDetailCache";
import { queryKeys } from "./queryKeys";
const ID = "11111111-1111-4111-8111-111111111111";
const IDENTIFIER = "PAP-7";
const REQUESTED_AT = 1_000_000;
function issue(overrides: Partial<Issue> = {}) {
return {
id: ID, identifier: IDENTIFIER, companyId: "company-1", title: "Recent task", status: "todo", priority: "medium",
workMode: "standard", projectId: null, parentId: null, description: null, assigneeAgentId: null,
assigneeUserId: null, executionRunId: null, issueNumber: 7, requestDepth: 0,
createdAt: new Date(0), updatedAt: new Date(0),
...overrides,
} as Issue;
}
const comment = (id: string) => ({ id, issueId: ID, body: id, createdAt: new Date(0) }) as unknown as IssueComment;
const event = (id: string) => ({ id, action: "comment.created" }) as unknown as ActivityEvent;
const run = (runId: string) => ({ runId, status: "succeeded" }) as unknown as RunForIssue;
function item(overrides: Partial<IssueChatBootstrapEntry> = {}): IssueChatBootstrapEntry {
return {
ref: ID,
issue: issue(),
recentComments: { comments: [comment("c2"), comment("c1")], hasMore: true, oldestCommentId: "c1", latestCommentId: "c2" },
commentInputFacts: [event("fact-1")],
recentActivity: [event("a1"), event("a2"), event("a1")],
recentRuns: [run("r2"), run("r1")],
interactions: [],
attachments: [],
liveRuns: [],
activeRun: null,
...overrides,
};
}
const coreKey = (ref: string) => [...queryKeys.issues.detail(ref), "core"];
const commentsKey = (ref: string) => [...queryKeys.issues.comments(ref), "recent"];
let queryClient: QueryClient;
function client() {
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return queryClient;
}
afterEach(() => queryClient?.clear());
describe("seedIssueChatBootstrap", () => {
it("fills every first-frame key in the shape of its single endpoint, under id and identifier", () => {
const qc = client();
const entry = item();
expect(seedIssueChatBootstrap(qc, entry, { companyId: "company-1", requestedAt: REQUESTED_AT })).toBe(true);
for (const ref of [ID, IDENTIFIER]) {
expect(qc.getQueryData(coreKey(ref))).toBe(entry.issue);
expect(qc.getQueryData(commentsKey(ref))).toBe(entry.recentComments);
// The activity key holds the de-duplicated recent answer.
expect(qc.getQueryData(recentIssueActivityQueryKey(ref))).toEqual([event("a1"), event("a2")]);
// A cold open shows the latest run and discloses the earlier one.
expect(qc.getQueryData(recentIssueRunWindowQueryKey(ref))).toEqual({ runs: [run("r2")], hasEarlierRuns: true, earlierRun: { runId: "r1", status: "succeeded" } });
expect(qc.getQueryData(queryKeys.issues.interactions(ref))).toEqual([]);
expect(qc.getQueryData(queryKeys.issues.attachments(ref))).toEqual([]);
expect(qc.getQueryData(queryKeys.issues.liveRuns(ref))).toEqual([]);
// The input facts are stored as the single batch the chat requests: the sorted saved comment ids.
const factsKey = issueCommentInputFactsQueryKey(ref);
expect(qc.getQueryData([...factsKey, "batch-ids"])).toEqual([["c1", "c2"]]);
expect(qc.getQueryData([...factsKey, "batch", ["c1", "c2"]])).toEqual([event("fact-1")]);
expect(qc.getQueryState(coreKey(ref))?.dataUpdatedAt).toBe(REQUESTED_AT);
}
// Core cannot stand in for the full detail read and its related data.
expect(qc.getQueryData(queryKeys.issues.detail(ID))).toBeUndefined();
expect(getCachedIssueDetail(qc, IDENTIFIER)).toBeUndefined();
});
it("stores an explicit null active run but leaves missing fields unset", () => {
const qc = client();
const entry = item({ activeRun: null });
delete (entry as Partial<IssueChatBootstrapEntry>).liveRuns;
delete (entry as Partial<IssueChatBootstrapEntry>).commentInputFacts;
seedIssueChatBootstrap(qc, entry, { companyId: "company-1", requestedAt: REQUESTED_AT });
expect(qc.getQueryState(queryKeys.issues.activeRun(ID))?.data).toBeNull();
expect(qc.getQueryState(queryKeys.issues.activeRun(ID))?.status).toBe("success");
expect(qc.getQueryState(queryKeys.issues.liveRuns(ID))).toBeUndefined();
expect(qc.getQueryState([...issueCommentInputFactsQueryKey(ID), "batch-ids"])).toBeUndefined();
});
it("ignores an item for another company", () => {
const qc = client();
expect(seedIssueChatBootstrap(qc, item({ issue: issue({ companyId: "company-2" }) }), { companyId: "company-1", requestedAt: REQUESTED_AT })).toBe(false);
expect(qc.getQueryCache().getAll()).toHaveLength(0);
});
it("never replaces cached data that is as new or newer, or a key with a read in flight or pending invalidation", () => {
const qc = client();
const newer = issue({ title: "Newer title" });
qc.setQueryData(coreKey(ID), newer, { updatedAt: REQUESTED_AT + 1 });
qc.setQueryData(queryKeys.issues.interactions(ID), ["stale"], { updatedAt: REQUESTED_AT - 1 });
qc.invalidateQueries({ queryKey: queryKeys.issues.interactions(ID) });
qc.setQueryData(queryKeys.issues.attachments(ID), ["older"], { updatedAt: REQUESTED_AT - 1 });
seedIssueChatBootstrap(qc, item(), { companyId: "company-1", requestedAt: REQUESTED_AT });
expect(qc.getQueryData(coreKey(ID))).toBe(newer);
expect(qc.getQueryData(queryKeys.issues.interactions(ID))).toEqual(["stale"]);
// A whole-answer endpoint with older, valid data takes the newer answer.
expect(qc.getQueryData(queryKeys.issues.attachments(ID))).toEqual([]);
});
it("only fills empty keys whose page merges observed history", () => {
const qc = client();
const observed = { comments: [comment("c3")], hasMore: false, oldestCommentId: "c3", latestCommentId: "c3" };
qc.setQueryData(commentsKey(ID), observed, { updatedAt: REQUESTED_AT - 10_000 });
qc.setQueryData(recentIssueActivityQueryKey(ID), [event("seen")], { updatedAt: REQUESTED_AT - 10_000 });
qc.setQueryData(recentIssueRunWindowQueryKey(ID), { runs: [run("r9")], hasEarlierRuns: false }, { updatedAt: REQUESTED_AT - 10_000 });
qc.setQueryData([...issueCommentInputFactsQueryKey(ID), "batch-ids"], [["c3"]]);
seedIssueChatBootstrap(qc, item(), { companyId: "company-1", requestedAt: REQUESTED_AT });
expect(qc.getQueryData(commentsKey(ID))).toBe(observed);
expect(qc.getQueryData(recentIssueActivityQueryKey(ID))).toEqual([event("seen")]);
expect(qc.getQueryData(recentIssueRunWindowQueryKey(ID))).toEqual({ runs: [run("r9")], hasEarlierRuns: false });
expect(qc.getQueryData([...issueCommentInputFactsQueryKey(ID), "batch-ids"])).toEqual([["c3"]]);
});
});
describe("hasFreshIssueChatFirstFrame", () => {
it("is true only while every first-frame read is cached, valid and fresh", () => {
const qc = client();
expect(hasFreshIssueChatFirstFrame(qc, [ID], REQUESTED_AT)).toBe(false);
seedIssueChatBootstrap(qc, item(), { companyId: "company-1", requestedAt: REQUESTED_AT });
expect(hasFreshIssueChatFirstFrame(qc, [IDENTIFIER], REQUESTED_AT + 29_999)).toBe(true);
expect(hasFreshIssueChatFirstFrame(qc, [IDENTIFIER], REQUESTED_AT + 30_000)).toBe(false);
qc.invalidateQueries({ queryKey: commentsKey(IDENTIFIER) });
expect(hasFreshIssueChatFirstFrame(qc, [IDENTIFIER], REQUESTED_AT + 1)).toBe(false);
});
it("is false after a light warm that cached only the core issue and recent comments", () => {
const qc = client();
const entry = item();
qc.setQueryData(coreKey(IDENTIFIER), entry.issue, { updatedAt: REQUESTED_AT });
qc.setQueryData(commentsKey(IDENTIFIER), entry.recentComments, { updatedAt: REQUESTED_AT });
expect(hasFreshIssueChatFirstFrame(qc, [ID, IDENTIFIER], REQUESTED_AT + 1)).toBe(false);
});
it("is false while a recent comment's input facts are missing", () => {
const qc = client();
seedIssueChatBootstrap(qc, item(), { companyId: "company-1", requestedAt: REQUESTED_AT });
const factsKey = issueCommentInputFactsQueryKey(IDENTIFIER);
qc.removeQueries({ queryKey: [...factsKey, "batch", ["c1", "c2"]], exact: true });
expect(hasFreshIssueChatFirstFrame(qc, [IDENTIFIER], REQUESTED_AT + 1)).toBe(false);
});
});