Files
PaperClipAI/ui/src/lib/issue-chat-history-queries.ts
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

181 lines
8.3 KiB
TypeScript

import type { QueryClient } from "@tanstack/react-query";
import type { ActivityEvent, Issue, IssueComment, IssueRecentComments } from "@paperclipai/shared";
import { activityApi, type RunForIssue } from "@/api/activity";
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
// (see `initialHistoryPending` in IssueDetail). The page and navigation prefetch
// both build them here, so a prefetch fills exactly the keys the page reads.
export interface RecentIssueRunWindow {
runs: RunForIssue[];
hasEarlierRuns: boolean;
earlierRun?: Pick<RunForIssue, "runId" | "status" | "resultJson"> | null;
}
export function recentIssueActivityQueryKey(issueRef: string) {
return [...queryKeys.issues.activity(issueRef), "recent"] as const;
}
export function recentIssueRunWindowQueryKey(issueRef: string) {
return [...queryKeys.issues.runs(issueRef), "recent-window"] as const;
}
/** Base key of the batched input facts for the comments in the chat window. */
export function issueCommentInputFactsQueryKey(issueRef: string) {
return [...queryKeys.issues.activity(issueRef), "comment-inputs"] as const;
}
/** The saved (not optimistic) comment ids whose input facts the chat reads, sorted. */
export function issueInputCommentIds(comments: readonly IssueComment[]) {
return comments
.filter((comment) => !("clientStatus" in comment) || !comment.clientStatus)
.map((comment) => comment.id)
.sort();
}
/**
* Warm the input facts of the recent comments already in cache, under the
* batch keys that `useIssueIdBatches` reads in the chat.
*/
export function prefetchIssueCommentInputFacts(queryClient: QueryClient, issueRef: string, staleTime: number) {
const recent = queryClient.getQueryData<IssueRecentComments>([...queryKeys.issues.comments(issueRef), "recent"]);
return prefetchIssueIdBatches(
queryClient,
issueCommentInputFactsQueryKey(issueRef),
issueInputCommentIds(recent?.comments ?? []),
(ids) => activityApi.inputFactsForIssue(issueRef, ids),
staleTime,
);
}
/** Recent activity, merged with events already observed while the task is open. */
export async function fetchRecentIssueActivity(queryClient: QueryClient, issueRef: string) {
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)
: await readFromIssueChatBootstrap(queryClient, recentIssueActivityQueryKey(issueRef), issueRef, (item) => item.recentActivity, () => activityApi.recentForIssue(issueRef));
const previous = cached ?? [];
return [...new Map([...previous, ...recent].map((event) => [event.id, event])).values()];
}
/** The latest run, plus every run observed while the task is open. */
export async function fetchRecentIssueRunWindow(
queryClient: QueryClient,
issueRef: string,
options: { conversationMode?: boolean } = {},
): Promise<RecentIssueRunWindow> {
const key = recentIssueRunWindowQueryKey(issueRef);
// 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));
let previous = previousWindow?.runs ?? [];
let reconciledFullHistory = false;
if (previous.some((run) =>
(run.status === "running" || run.status === "queued") && !recent.some((next) => next.runId === run.runId),
)) {
// After a reconnect, several turns may have completed beyond the small
// window. Reconcile watched runs once against authoritative summaries.
recent = options.conversationMode
? await activityApi.runsByIdsForIssue(issueRef, [...new Set([...previous.map(run => run.runId), ...recent.map(run => run.runId)])])
: await activityApi.runsForIssue(issueRef);
reconciledFullHistory = true;
const existingRunIds = new Set(recent.map((run) => run.runId));
previous = previous.filter((run) => existingRunIds.has(run.runId));
}
return buildRecentIssueRunWindow(recent, previous, reconciledFullHistory ? false : previousWindow?.hasEarlierRuns === true, reconciledFullHistory ? null : previousWindow?.earlierRun);
}
/**
* The run window for a `/runs?view=recent` answer. `previous` holds runs
* already observed while the task is open; a cold open passes none.
*/
export function buildRecentIssueRunWindow(
recent: RunForIssue[],
previous: RunForIssue[] = [],
previouslyHadEarlierRuns = false,
previousEarlierRun?: RecentIssueRunWindow["earlierRun"],
): RecentIssueRunWindow {
// The second row refreshes a just-finished predecessor. Start with only
// the latest run, then keep every run observed while this task is open.
const visible = new Set([...previous.map((run) => run.runId), ...recent.slice(0, 1).map((run) => run.runId)]);
const omitted = recent.find((run) => !visible.has(run.runId));
const retained = recent.length >= 2 && previouslyHadEarlierRuns;
const window: RecentIssueRunWindow = {
runs: [...new Map([...previous, ...recent].filter((run) => visible.has(run.runId)).map((run) => [run.runId, run])).values()],
// A first run is already visible. The disclosure needs evidence of an
// omitted run, and must retain that evidence as later turns arrive.
hasEarlierRuns: !!omitted || retained,
};
const earlierRun = omitted ? { runId: omitted.runId, status: omitted.status, resultJson: omitted.resultJson } : retained ? previousEarlierRun : undefined;
if (earlierRun) window.earlierRun = earlierRun;
return window;
}
/** Prefetched answers for live state stay usable only briefly. */
const LIVE_STATE_PREFETCH_STALE_TIME_MS = 5_000;
/**
* Warm the reads that gate the compact chat's first frame, so a task the person
* is about to open renders from cache. Comments and the core issue are warmed by
* `prefetchIssueDetailForNavigation`; this adds the rest of the gate.
*/
export function prefetchIssueChatHistory(
queryClient: QueryClient,
issueRef: string,
options: {
issue?: Pick<Issue, "status" | "executionRunId" | "conversationAgentId"> | null;
staleTime: number;
},
) {
const { staleTime } = options;
// Same mode as the page, so a reconnect reconciles only the watched runs.
const conversationMode = !!options.issue?.conversationAgentId;
const reads: Promise<unknown>[] = [
queryClient.prefetchQuery({
queryKey: recentIssueActivityQueryKey(issueRef),
queryFn: () => fetchRecentIssueActivity(queryClient, issueRef),
staleTime,
}),
queryClient.prefetchQuery({
queryKey: recentIssueRunWindowQueryKey(issueRef),
queryFn: () => fetchRecentIssueRunWindow(queryClient, issueRef, { conversationMode }),
staleTime,
}),
queryClient.prefetchQuery({
queryKey: queryKeys.issues.interactions(issueRef),
queryFn: () => issuesApi.listInteractions(issueRef),
staleTime,
}),
queryClient.prefetchQuery({
queryKey: queryKeys.issues.attachments(issueRef),
queryFn: () => issuesApi.listAttachments(issueRef),
staleTime,
}),
queryClient.prefetchQuery({
queryKey: queryKeys.issues.liveRuns(issueRef),
queryFn: () => heartbeatsApi.liveRunsForIssue(issueRef),
staleTime: LIVE_STATE_PREFETCH_STALE_TIME_MS,
}),
];
// The page reads the active run only for work that is running.
if (options.issue && (options.issue.executionRunId || options.issue.status === "in_progress")) {
reads.push(queryClient.prefetchQuery({
queryKey: queryKeys.issues.activeRun(issueRef),
queryFn: () => heartbeatsApi.activeRunForIssue(issueRef),
staleTime: LIVE_STATE_PREFETCH_STALE_TIME_MS,
}));
}
return Promise.all(reads);
}