diff --git a/server/src/__tests__/task-cold-open.test.ts b/server/src/__tests__/task-cold-open.test.ts index f256fc2119b..fdd40bbf255 100644 --- a/server/src/__tests__/task-cold-open.test.ts +++ b/server/src/__tests__/task-cold-open.test.ts @@ -134,6 +134,26 @@ const support = externalDatabase ? { supported: true } : await getEmbeddedPostgr expect(response.body.comments.map((c: { body: string }) => c.body)).toEqual([ "Human direction", "Newest direction", "New reply 5", "New reply 4", "New reply 3", "New reply 2", ]); + expect(response.body.hasMore).toBe(true); + }); + it.each([ + { replies: 4, pinned: 2, hasMore: false }, + { replies: 4, pinned: 3, hasMore: true }, + { replies: 4, pinned: 6, hasMore: true }, + ])("reports more comments only when one stays hidden ($replies replies after $pinned older)", async ({ replies, pinned, hasMore }) => { + const bareIssueId = randomUUID(); + await db.insert(issues).values({ id: bareIssueId, companyId, title: "No description" }); + await db.insert(issueComments).values([ + ...Array.from({ length: pinned }, (_, i) => ({ + companyId, issueId: bareIssueId, body: `Older ${i}`, createdAt: new Date(i), + ...(i === 0 || i === pinned - 1 ? { authorType: "user" as const, authorUserId: "local-board" } : { authorType: "agent" as const, authorAgentId: agentId }), + })), + ...Array.from({ length: replies }, (_, i) => ({ companyId, issueId: bareIssueId, body: `Reply ${i}`, authorType: "agent" as const, authorAgentId: agentId, createdAt: new Date(1000 + i) })), + ]); + const response = await request(app()).get(`/api/issues/${bareIssueId}/recent-comments`); + expect(response.status).toBe(200); + expect(response.body.comments).toHaveLength(replies + 2); + expect(response.body.hasMore).toBe(hasMore); }); it("loads the original input receipts outside the recent activity window and ignores replay receipts", async () => { const commentId = randomUUID(); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 312b58b0d67..55be61b9e94 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -17357,17 +17357,18 @@ export function issueRoutes( }); } const [recent, human, firstInstruction] = await Promise.all([ - svc.listComments(issue.id, { companyId: issue.companyId, order: "desc", limit: 5 }), + svc.listComments(issue.id, { companyId: issue.companyId, order: "desc", limit: 7 }), svc.listComments(issue.id, { companyId: issue.companyId, order: "desc", limit: 1, humanOnly: true }), issue.description?.trim() ? Promise.resolve([]) : svc.listComments(issue.id, { companyId: issue.companyId, order: "asc", limit: 1, humanOnly: true }), ]); const comments = [...new Map([...firstInstruction, ...human, ...recent.slice(0, 4)].map((comment) => [comment.id, comment])).values()]; + const included = new Set(comments.map((comment) => comment.id)); return runRedactions.redactForIssue(issue.companyId, issue.id, { comments, latestCommentId: recent[0]?.id ?? null, - hasMore: recent.length > 4, + hasMore: recent.slice(4).some((comment) => !included.has(comment.id)), }); } diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx index 24736265263..b28cde32a13 100644 --- a/ui/src/components/TaskChatThread.tsx +++ b/ui/src/components/TaskChatThread.tsx @@ -1,3 +1,9 @@ +import { + hasVisibleRunAnswer, + LEGACY_WITHHELD_RUN_COMMENT, + presentationDecisionCommentId, + semanticProgressCommentIds, +} from "@/lib/run-answer-visibility"; import { imagePreparationReceiptIds } from "./task-chat/image-resources"; import type { ScrollingHistory } from "@/components/task-chat/TaskMessageScroller"; import { TaskChatShimmerScope } from "@/components/task-chat/TaskChatShimmer"; @@ -306,8 +312,6 @@ function isNativePaperclipRunnerRun( run?.runtimeMode === "native" && run.adapterType === "paperclip_runner" ); } -const LEGACY_WITHHELD_RUN_COMMENT = - "Run completed. Agent did not post a summary comment this run (transcript withheld — see run log)."; function acceptedSemanticResult( value: unknown, @@ -348,42 +352,6 @@ function acceptedSemanticResultDisposition(value: unknown): string | null { : null; } -function presentationDecisionCommentId( - value: unknown, -): string | null | undefined { - if (!value || typeof value !== "object" || Array.isArray(value)) - return undefined; - const decision = (value as Record).presentationDecision; - if (!decision || typeof decision !== "object" || Array.isArray(decision)) - return undefined; - const record = decision as Record; - if (record.schema !== "paperclip.run_presentation_decision.v1") - return undefined; - return typeof record.commentId === "string" && record.commentId.trim() - ? record.commentId - : null; -} - -function semanticProgressCommentIds(value: unknown): Set { - if (!value || typeof value !== "object" || Array.isArray(value)) - return new Set(); - const receipts = (value as Record).semanticToolReceipts; - if (!receipts || typeof receipts !== "object" || Array.isArray(receipts)) - return new Set(); - const ids = new Set(); - for (const receipt of Object.values(receipts)) { - if (!receipt || typeof receipt !== "object" || Array.isArray(receipt)) - continue; - const record = receipt as Record; - if (record.operationId !== "report_progress") continue; - const result = record.result; - if (!result || typeof result !== "object" || Array.isArray(result)) - continue; - const commentId = (result as Record).commentId; - if (typeof commentId === "string" && commentId) ids.add(commentId); - } - return ids; -} function acceptedSemanticResultVerificationCaveats(value: unknown) { const runResult = @@ -1046,14 +1014,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { const meta = linkedRunMetaById.get(run.id); if (acceptedSemanticResultDisposition(meta?.resultJson) === "yielded" || interactions?.some(interaction => interaction.sourceRunId === run.id && interaction.status === "pending")) continue; - const presentationCommentId = presentationDecisionCommentId(meta?.resultJson); - const progressCommentIds = semanticProgressCommentIds(meta?.resultJson); - if (projectedComments.some(comment => - comment.authorType === "agent" && !comment.deletedAt && comment.body.trim() && - comment.body !== LEGACY_WITHHELD_RUN_COMMENT && !progressCommentIds.has(comment.id) && - (comment.runId ?? comment.createdByRunId ?? comment.derivedCreatedByRunId) === run.id && - (presentationCommentId === undefined || presentationCommentId === comment.id), - )) deferred.add(run.id); + if (hasVisibleRunAnswer(projectedComments, run.id, meta?.resultJson)) deferred.add(run.id); } return deferred; }, [issueId, runs, projectedComments, linkedRunMetaById, interactions, compactTranscriptDeferral, slowSettledTranscriptRunIds, openedAt]); diff --git a/ui/src/lib/issue-chat-history-queries.ts b/ui/src/lib/issue-chat-history-queries.ts index 4d188d78459..50f353fcc0f 100644 --- a/ui/src/lib/issue-chat-history-queries.ts +++ b/ui/src/lib/issue-chat-history-queries.ts @@ -15,6 +15,7 @@ import { queryKeys } from "@/lib/queryKeys"; export interface RecentIssueRunWindow { runs: RunForIssue[]; hasEarlierRuns: boolean; + earlierRun?: Pick | null; } export function recentIssueActivityQueryKey(issueRef: string) { @@ -92,7 +93,7 @@ export async function fetchRecentIssueRunWindow( const existingRunIds = new Set(recent.map((run) => run.runId)); previous = previous.filter((run) => existingRunIds.has(run.runId)); } - return buildRecentIssueRunWindow(recent, previous, !reconciledFullHistory && previousWindow?.hasEarlierRuns === true); + return buildRecentIssueRunWindow(recent, previous, reconciledFullHistory ? false : previousWindow?.hasEarlierRuns === true, reconciledFullHistory ? null : previousWindow?.earlierRun); } /** @@ -103,17 +104,22 @@ 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)]); - return { + 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: recent.some((run) => !visible.has(run.runId)) - || (recent.length >= 2 && previouslyHadEarlierRuns), + 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. */ diff --git a/ui/src/lib/issueChatBootstrapCache.test.ts b/ui/src/lib/issueChatBootstrapCache.test.ts index bffae918095..fb2fc5435d1 100644 --- a/ui/src/lib/issueChatBootstrapCache.test.ts +++ b/ui/src/lib/issueChatBootstrapCache.test.ts @@ -66,7 +66,7 @@ describe("seedIssueChatBootstrap", () => { // 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 }); + 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([]); diff --git a/ui/src/lib/issueDetailCache.test.ts b/ui/src/lib/issueDetailCache.test.ts index 060eb7370c5..e34b09d4713 100644 --- a/ui/src/lib/issueDetailCache.test.ts +++ b/ui/src/lib/issueDetailCache.test.ts @@ -229,7 +229,7 @@ describe("task navigation prefetch", () => { await prefetchIssueDetailForNavigation(client, ref, { issue, history: true }); expect(issuesApi.chatBootstrap).toHaveBeenCalledWith(issue.companyId, [ref]); expect(client.getQueryData(recentIssueActivityQueryKey(ref))).toEqual([{ id: "event-1" }]); - expect(client.getQueryData(recentIssueRunWindowQueryKey(ref))).toEqual({ runs: [run("run-2", "failed")], hasEarlierRuns: true }); + expect(client.getQueryData(recentIssueRunWindowQueryKey(ref))).toEqual({ runs: [run("run-2", "failed")], hasEarlierRuns: true, earlierRun: { runId: "run-1", status: "succeeded" } }); expect(client.getQueryData(queryKeys.issues.liveRuns(ref))).toEqual([]); expect(client.getQueryData([...queryKeys.issues.comments(ref), "recent"])).toEqual(recentComments); // The recent-comments read shares the bootstrap; the header keeps its own read. @@ -263,7 +263,7 @@ describe("task navigation prefetch", () => { await prefetchIssueDetailForNavigation(client, ref, { issue, history: true }); expect(client.getQueryData(recentIssueActivityQueryKey(ref))).toEqual([{ id: "event-1" }]); // Same window shape the page builds: the latest run, plus evidence of earlier runs. - expect(client.getQueryData(recentIssueRunWindowQueryKey(ref))).toEqual({ runs: [run("run-2", "failed")], hasEarlierRuns: true }); + expect(client.getQueryData(recentIssueRunWindowQueryKey(ref))).toEqual({ runs: [run("run-2", "failed")], hasEarlierRuns: true, earlierRun: { runId: "run-1", status: "succeeded" } }); expect(client.getQueryData(queryKeys.issues.interactions(ref))).toEqual([]); expect(client.getQueryData(queryKeys.issues.attachments(ref))).toEqual([]); expect(client.getQueryData(queryKeys.issues.liveRuns(ref))).toEqual([]); diff --git a/ui/src/lib/run-answer-visibility.ts b/ui/src/lib/run-answer-visibility.ts new file mode 100644 index 00000000000..06b41578277 --- /dev/null +++ b/ui/src/lib/run-answer-visibility.ts @@ -0,0 +1,62 @@ +export const LEGACY_WITHHELD_RUN_COMMENT = + "Run completed. Agent did not post a summary comment this run (transcript withheld — see run log)."; + +export function presentationDecisionCommentId( + value: unknown, +): string | null | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) + return undefined; + const decision = (value as Record).presentationDecision; + if (!decision || typeof decision !== "object" || Array.isArray(decision)) + return undefined; + const record = decision as Record; + if (record.schema !== "paperclip.run_presentation_decision.v1") + return undefined; + return typeof record.commentId === "string" && record.commentId.trim() + ? record.commentId + : null; +} + +export function semanticProgressCommentIds(value: unknown): Set { + if (!value || typeof value !== "object" || Array.isArray(value)) + return new Set(); + const receipts = (value as Record).semanticToolReceipts; + if (!receipts || typeof receipts !== "object" || Array.isArray(receipts)) + return new Set(); + const ids = new Set(); + for (const receipt of Object.values(receipts)) { + if (!receipt || typeof receipt !== "object" || Array.isArray(receipt)) + continue; + const record = receipt as Record; + if (record.operationId !== "report_progress") continue; + const result = record.result; + if (!result || typeof result !== "object" || Array.isArray(result)) + continue; + const commentId = (result as Record).commentId; + if (typeof commentId === "string" && commentId) ids.add(commentId); + } + return ids; +} + +export function hasVisibleRunAnswer( + comments: ReadonlyArray<{ + id: string; + authorType: string; + body: string; + deletedAt?: Date | string | null; + runId?: string | null; + createdByRunId?: string | null; + derivedCreatedByRunId?: string | null; + }>, + runId: string, + resultJson: unknown, +): boolean { + const presentationCommentId = presentationDecisionCommentId(resultJson); + const progressCommentIds = semanticProgressCommentIds(resultJson); + return comments.some(comment => + comment.authorType === "agent" && !comment.deletedAt && comment.body.trim() && + comment.body !== LEGACY_WITHHELD_RUN_COMMENT && !progressCommentIds.has(comment.id) && + (comment.runId ?? comment.createdByRunId ?? comment.derivedCreatedByRunId) === runId && + (presentationCommentId === undefined || presentationCommentId === comment.id), + ); +} diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx index 95b100cbfce..1c145d8d3de 100644 --- a/ui/src/pages/IssueDetail.test.tsx +++ b/ui/src/pages/IssueDetail.test.tsx @@ -1,6 +1,7 @@ import { TaskChatPausedTakeover, type TaskComposerPause } from "../components/task-chat/TaskChatPausedTakeover"; // @vitest-environment jsdom +import { LEGACY_WITHHELD_RUN_COMMENT } from "@/lib/run-answer-visibility"; import type { Breadcrumb } from "../context/BreadcrumbContext"; import { DispositionRecoveryNotice, type DispositionRecoverySnapshot } from "../components/DispositionRecoveryNotice"; @@ -2455,6 +2456,29 @@ describe("IssueDetail", () => { }); }); + it.each([ + { status: "succeeded", answered: true, disclosed: false }, + { status: "succeeded", answered: false, disclosed: true }, + { status: "failed", answered: true, disclosed: true }, + { status: "succeeded", answered: true, disclosed: true, body: LEGACY_WITHHELD_RUN_COMMENT }, + ])("discloses an omitted $status run only when its answer is not visible (answered: $answered)", async ({ status, answered, disclosed, body = "Earlier answer" }) => { + queryClient.setQueryData(["issues", "history-expanded", "PAP-1"], false); + mockIssuesApi.get.mockResolvedValue(createIssue()); + const latest = { runId: "latest", status: "succeeded", agentId: "agent-1", createdAt: new Date().toISOString() }; + const older = { ...latest, runId: "older", status }; + const answer = createIssueComment({ id: "answer", authorType: "agent", authorAgentId: "agent-1", authorUserId: null, + body, createdByRunId: answered ? "older" : "unrelated" }); + mockIssuesApi.recentComments.mockResolvedValue({ comments: [answer], latestCommentId: answer.id, hasMore: false }); + mockActivityApi.recentRunsForIssue.mockResolvedValue([latest, older]); + await act(async () => renderIssueView()); + await waitForAssertion(() => { + const props = mockIssueChatThreadRender.mock.calls.at(-1)?.[0]; + expect(props?.linkedRuns).toMatchObject([latest]); + expect(props?.comments).toMatchObject([{ id: "answer" }]); + expect(Boolean(props?.historyControl)).toBe(disclosed); + }); + }); + it.each([false, true])("refreshes admission with latest comments (compact chat: %s)", async compact => { const interruption: NonNullable = { intentId: "retry", responsibility: "system", state: "failed", nextRetryAt: null, canRetry: true, userAction: null, sourceRunIds: ["failed-run"], observedRunId: "failed-run", diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index ecfbed973e7..06c5cb47a22 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -233,6 +233,7 @@ import { type IssueChatRunFinalizationAction, } from "../components/IssueChatThread"; import { TaskChatThread } from "../components/TaskChatThread"; +import { hasVisibleRunAnswer } from "@/lib/run-answer-visibility"; import type { TaskChatIssueBrief } from "../components/task-chat/TaskChatDescriptionBubble"; import { useClassicTaskInterfaceEnabled } from "../hooks/useClassicTaskInterfaceEnabled"; import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled"; @@ -1672,7 +1673,10 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ ...(Array.isArray(linkedRunHistory) ? linkedRunHistory : linkedRunHistory?.runs ?? []), ...(conversationMode && !historyExpanded ? commentRuns.data ?? [] : []), ].map(run => [run.runId, run])).values()], [linkedRunHistory, conversationMode, historyExpanded, commentRuns.data]); - const hasEarlierRuns = !Array.isArray(linkedRunHistory) && linkedRunHistory?.hasEarlierRuns === true; + const earlierRun = Array.isArray(linkedRunHistory) ? undefined : linkedRunHistory?.earlierRun; + const hasEarlierRuns = !Array.isArray(linkedRunHistory) && linkedRunHistory?.hasEarlierRuns === true && !( + earlierRun?.status === "succeeded" && hasVisibleRunAnswer(comments, earlierRun.runId, earlierRun.resultJson) + ); const resolvedActivity = useMemo( () => [...new Map([...(activity ?? []), ...(inputFacts.data ?? [])].map((event) => [event.id, event])).values()], [activity, inputFacts.data],