Use checkpoint diffs for turn files and ignore late summary rederives

- Load per-turn checkpoint diffs in `ChatView` and show loading/error states in the timeline
- Drive changed-file chips/stats from checkpoint diff results instead of cached turn summary files
- Prevent reducer from rederiving completed turn summaries on late `turn/diff/updated` events; add regression test
This commit is contained in:
Julius Marminge committed 2026-02-18 23:41:46 -08:00
1 parent b484e75dc2
commit 34e30dfb78
3 files changed
+171 -9

No files matched your search

+120 -8
View File
@@ -27,9 +27,10 @@ import {
useRef,
useState,
} from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
@@ -51,6 +52,7 @@ import {
import {
derivePendingApprovals,
derivePhase,
deriveTurnDiffFilesFromUnifiedDiff,
deriveTimelineEntries,
type TurnDiffSummary,
type PendingApproval,
@@ -65,6 +67,7 @@ import {
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
type ChatImageAttachment,
type TurnDiffFileChange,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
@@ -179,6 +182,33 @@ interface ExpandedImagePreview {
name: string;
}
type TurnCheckpointFilesState =
| {
status: "pending" | "loading";
files: TurnDiffFileChange[];
errorMessage?: undefined;
}
| {
status: "error";
files: TurnDiffFileChange[];
errorMessage: string;
}
| {
status: "ready";
files: TurnDiffFileChange[];
errorMessage?: undefined;
};
function checkpointErrorMessage(error: unknown): string {
if (error instanceof Error && error.message.trim().length > 0) {
return error.message;
}
if (typeof error === "string" && error.trim().length > 0) {
return error;
}
return "Checkpoint diff is unavailable.";
}
type ComposerCommandItem =
| {
id: string;
@@ -422,6 +452,69 @@ export default function ChatView() {
}
return byMessageId;
}, [turnDiffSummaries]);
const checkpointDiffInputsByTurn = useMemo(
() =>
turnDiffSummaries
.filter((summary) => summary.assistantMessageId)
.map((summary) => {
const checkpointTurnCount =
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
return {
turnId: summary.turnId,
checkpointTurnCount:
typeof checkpointTurnCount === "number" ? checkpointTurnCount : null,
};
}),
[inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
);
const checkpointDiffQueriesByTurn = useQueries({
queries: checkpointDiffInputsByTurn.map((input) =>
checkpointDiffQueryOptions(api, {
sessionId: activeSessionId,
threadRuntimeId: activeThreadRuntimeId,
fromTurnCount:
typeof input.checkpointTurnCount === "number"
? Math.max(0, input.checkpointTurnCount - 1)
: null,
toTurnCount: input.checkpointTurnCount,
cacheScope: `turn:${input.turnId}`,
}),
),
});
const turnCheckpointFilesByTurnId = useMemo(() => {
const byTurnId = new Map<string, TurnCheckpointFilesState>();
for (let index = 0; index < checkpointDiffInputsByTurn.length; index += 1) {
const input = checkpointDiffInputsByTurn[index];
const query = checkpointDiffQueriesByTurn[index];
if (!input || !query) continue;
if (!activeSessionId || typeof input.checkpointTurnCount !== "number") {
byTurnId.set(input.turnId, { status: "pending", files: [] });
continue;
}
const diff = query.data?.diff;
if (typeof diff === "string") {
byTurnId.set(input.turnId, {
status: "ready",
files: deriveTurnDiffFilesFromUnifiedDiff(diff),
});
continue;
}
if (query.isError) {
byTurnId.set(input.turnId, {
status: "error",
files: [],
errorMessage: checkpointErrorMessage(query.error),
});
continue;
}
byTurnId.set(input.turnId, { status: "loading", files: [] });
}
return byTurnId;
}, [activeSessionId, checkpointDiffInputsByTurn, checkpointDiffQueriesByTurn]);
const revertTurnCountByUserMessageId = useMemo(() => {
const byUserMessageId = new Map<string, number>();
for (let index = 0; index < timelineEntries.length; index += 1) {
@@ -1958,6 +2051,7 @@ export default function ChatView() {
completionSummary={completionSummary}
assistantCompletionByItemId={assistantCompletionByItemId}
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
turnCheckpointFilesByTurnId={turnCheckpointFilesByTurnId}
nowIso={nowIso}
expandedWorkGroups={expandedWorkGroups}
onToggleWorkGroup={onToggleWorkGroup}
@@ -2416,6 +2510,7 @@ interface MessagesTimelineProps {
completionSummary: string | null;
assistantCompletionByItemId: Map<string, string>;
turnDiffSummaryByAssistantMessageId: Map<string, TurnDiffSummary>;
turnCheckpointFilesByTurnId: Map<string, TurnCheckpointFilesState>;
nowIso: string;
expandedWorkGroups: Record<string, boolean>;
onToggleWorkGroup: (groupId: string) => void;
@@ -2435,6 +2530,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
completionSummary,
assistantCompletionByItemId,
turnDiffSummaryByAssistantMessageId,
turnCheckpointFilesByTurnId,
nowIso,
expandedWorkGroups,
onToggleWorkGroup,
@@ -2622,7 +2718,9 @@ const MessagesTimeline = memo(function MessagesTimeline({
timelineEntry.message.id,
);
if (!turnSummary) return null;
const summaryStat = turnSummary.files.reduce(
const checkpointFilesState = turnCheckpointFilesByTurnId.get(turnSummary.turnId);
const checkpointFiles = checkpointFilesState?.files ?? [];
const summaryStat = checkpointFiles.reduce(
(acc, file) => {
if (typeof file.additions !== "number" || typeof file.deletions !== "number") {
return acc;
@@ -2634,7 +2732,8 @@ const MessagesTimeline = memo(function MessagesTimeline({
},
{ additions: 0, deletions: 0 },
);
const changedFileCountLabel = String(turnSummary.files.length);
const changedFileCountLabel =
checkpointFilesState?.status === "ready" ? String(checkpointFiles.length) : "...";
return (
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="mb-1.5 flex items-center justify-between gap-2">
@@ -2653,16 +2752,29 @@ const MessagesTimeline = memo(function MessagesTimeline({
type="button"
size="xs"
variant="outline"
onClick={() =>
onOpenTurnDiff(turnSummary.turnId, turnSummary.files[0]?.path)
}
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
>
View diff
</Button>
</div>
{turnSummary.files.length > 0 ? (
{!checkpointFilesState || checkpointFilesState.status === "pending" ? (
<p className="text-[11px] text-muted-foreground/70">
Waiting for checkpoint metadata...
</p>
) : checkpointFilesState?.status === "loading" ? (
<p className="text-[11px] text-muted-foreground/70">
Loading checkpoint diff...
</p>
) : checkpointFilesState?.status === "error" ? (
<p
className="truncate text-[11px] text-muted-foreground/70"
title={checkpointFilesState.errorMessage}
>
{checkpointFilesState.errorMessage}
</p>
) : checkpointFiles.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
{turnSummary.files.map((file) => (
{checkpointFiles.map((file) => (
<button
key={`${turnSummary.turnId}:${file.path}`}
type="button"
+39
View File
@@ -970,4 +970,43 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointTurnCount).toBe(2);
expect(next.threads[0]?.turnDiffSummaries[1]?.checkpointTurnCount).toBe(3);
});
it("does not rederive completed turn summaries from late turn diff events", () => {
const completed = reducer(makeState(makeThread()), {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/completed",
turnId: "turn-1",
createdAt: "2026-02-09T00:00:03.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
activeAssistantItemRef: { current: null },
});
expect(completed.threads[0]?.turnDiffSummaries[0]?.files).toEqual([]);
const withLateDiff = reducer(completed, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/diff/updated",
turnId: "turn-1",
createdAt: "2026-02-09T00:00:04.000Z",
payload: {
diff: [
"diff --git a/src/a.ts b/src/a.ts",
"@@ -1 +1 @@",
"-old",
"+new",
"diff --git a/src/b.ts b/src/b.ts",
"@@ -1 +1 @@",
"-old",
"+new",
].join("\n"),
},
}),
activeAssistantItemRef: { current: null },
});
expect(withLateDiff.threads[0]?.turnDiffSummaries[0]?.files).toEqual([]);
});
});
+12 -1
View File
@@ -904,7 +904,18 @@ export function reducer(state: AppState, action: Action): AppState {
...state,
threads: updateThread(state.threads, target.id, (t) => {
const nextEvents = [event, ...t.events];
const shouldRederiveDiffs = event.method === "turn/completed";
const eventTurnId = getEventTurnId(event);
const hasCompletedSummaryForTurn = Boolean(
eventTurnId && t.turnDiffSummaries.some((summary) => summary.turnId === eventTurnId),
);
const itemType = asString(asObject(asObject(event.payload)?.item)?.type);
const normalizedItemType = itemType?.replace(/[_-]/g, "").toLowerCase();
const isMetadataItemCompleted =
event.method === "item/completed" &&
(normalizedItemType === "agentmessage" || normalizedItemType === "filechange");
const shouldRederiveDiffs =
event.method === "turn/completed" ||
(hasCompletedSummaryForTurn && isMetadataItemCompleted);
const turnDiffSummaries = shouldRederiveDiffs
? mergeTurnDiffSummaries(t.turnDiffSummaries, deriveTurnDiffSummaries(nextEvents))
: t.turnDiffSummaries;