-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathDiffPanel.tsx
More file actions
754 lines (722 loc) · 27.3 KB
/
DiffPanel.tsx
File metadata and controls
754 lines (722 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
import { parsePatchFiles } from "@pierre/diffs";
import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@okcode/contracts";
import { CheckIcon, ChevronDownIcon, Columns2Icon, Rows3Icon, TextWrapIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { RawPatchViewer } from "~/components/pr-review/RawPatchViewer";
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { useFileViewNavigation } from "~/hooks/useFileViewNavigation";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useTheme } from "../hooks/useTheme";
import { buildPatchCacheKey } from "../lib/diffRendering";
import {
acceptAllDiffFiles,
expandDiffFile,
reconcileDiffFileReviewState,
toggleDiffFileAccepted,
toggleDiffFileCollapsed,
type DiffFileReviewStateByPath,
} from "../lib/diffFileReviewState";
import { resolveDiffThemeName } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { useI18n } from "../i18n/useI18n";
import { useStore } from "../store";
import { useAppSettings } from "../appSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { DiffStatLabel, hasNonZeroStat } from "./chat/DiffStatLabel";
import { Button } from "./ui/button";
import { Select, SelectButton, SelectItem, SelectPopup } from "./ui/select";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
type DiffRenderMode = "stacked" | "split";
type DiffThemeType = "light" | "dark";
const DIFF_PANEL_UNSAFE_CSS = `
[data-diffs-header],
[data-diff],
[data-file],
[data-error-wrapper],
[data-virtualizer-buffer] {
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
--diffs-token-light-bg: transparent;
--diffs-token-dark-bg: transparent;
--diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
--diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
--diffs-bg-deletion-emphasis-override: color-mix(
in srgb,
var(--background) 80%,
var(--destructive)
);
background-color: var(--diffs-bg) !important;
}
[data-file-info] {
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
border-block-color: var(--border) !important;
color: var(--foreground) !important;
}
[data-diffs-header] {
position: sticky !important;
top: 0;
z-index: 4;
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
border-bottom: 1px solid var(--border) !important;
}
[data-title] {
cursor: pointer;
transition:
color 120ms ease,
text-decoration-color 120ms ease;
text-decoration: underline;
text-decoration-color: transparent;
text-underline-offset: 2px;
}
[data-title]:hover {
color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
text-decoration-color: currentColor;
}
`;
type RenderablePatch =
| {
kind: "files";
files: FileDiffMetadata[];
}
| {
kind: "raw";
text: string;
reason: string;
};
function getRenderablePatch(
patch: string | undefined,
cacheScope = "diff-panel",
): RenderablePatch | null {
if (!patch) return null;
const normalizedPatch = patch.trim();
if (normalizedPatch.length === 0) return null;
try {
const parsedPatches = parsePatchFiles(
normalizedPatch,
buildPatchCacheKey(normalizedPatch, cacheScope),
);
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
if (files.length > 0) {
return { kind: "files", files };
}
return {
kind: "raw",
text: normalizedPatch,
reason: "Unsupported diff format. Showing raw patch.",
};
} catch {
return {
kind: "raw",
text: normalizedPatch,
reason: "Failed to parse patch. Showing raw patch.",
};
}
}
function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
const raw = fileDiff.name ?? fileDiff.prevName ?? "";
if (raw.startsWith("a/") || raw.startsWith("b/")) {
return raw.slice(2);
}
return raw;
}
function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
}
function summarizeFileDiffStats(fileDiff: FileDiffMetadata): {
additions: number;
deletions: number;
} {
return fileDiff.hunks.reduce(
(summary, hunk) => ({
additions: summary.additions + hunk.additionLines,
deletions: summary.deletions + hunk.deletionLines,
}),
{ additions: 0, deletions: 0 },
);
}
function DiffFileSection(props: {
fileDiff: FileDiffMetadata;
filePath: string;
fileKey: string;
diffRenderMode: DiffRenderMode;
diffWordWrap: boolean;
resolvedTheme: "light" | "dark";
collapsed: boolean;
accepted: boolean;
onOpenInEditor: (filePath: string) => void;
onToggleCollapsed: (filePath: string) => void;
onToggleAccepted: (filePath: string) => void;
}) {
const {
accepted,
collapsed,
diffRenderMode,
diffWordWrap,
fileDiff,
fileKey,
filePath,
onOpenInEditor,
onToggleAccepted,
onToggleCollapsed,
resolvedTheme,
} = props;
const stats = summarizeFileDiffStats(fileDiff);
return (
<section
data-diff-file-path={filePath}
className={cn(
"diff-render-file mb-2 overflow-hidden rounded-md border border-border/70 bg-card/30 first:mt-2 last:mb-0",
accepted && "border-success/40",
)}
>
<div className="flex items-center gap-2 border-b border-border/60 bg-card/70 px-2 py-1.5">
<Button
size="icon-xs"
variant="ghost"
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
aria-expanded={!collapsed}
onClick={() => onToggleCollapsed(filePath)}
className="text-muted-foreground/80"
>
<ChevronDownIcon
className={cn("size-3.5 transition-transform", collapsed && "-rotate-90")}
/>
</Button>
<button
type="button"
className="min-w-0 flex-1 truncate text-left font-mono text-[11px] text-foreground/90 underline-offset-2 hover:underline"
onClick={() => onOpenInEditor(filePath)}
title={`Open ${filePath}`}
>
{filePath}
</button>
{hasNonZeroStat(stats) && (
<span className="hidden shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/80 sm:inline">
<DiffStatLabel additions={stats.additions} deletions={stats.deletions} />
</span>
)}
<Button
size="xs"
variant={accepted ? "secondary" : "outline"}
onClick={() => onToggleAccepted(filePath)}
className={cn(
"gap-1.5",
accepted && "border-success/30 bg-success/12 text-success hover:bg-success/18",
)}
>
<CheckIcon className={cn("size-3.5", accepted ? "opacity-100" : "opacity-35")} />
{accepted ? "Accepted" : "Accept"}
</Button>
</div>
{!collapsed && (
<div key={fileKey}>
<FileDiff
fileDiff={fileDiff}
options={{
diffStyle: diffRenderMode === "split" ? "split" : "unified",
lineDiffType: "none",
overflow: diffWordWrap ? "wrap" : "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme as DiffThemeType,
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
}}
/>
</div>
)}
</section>
);
}
interface DiffPanelProps {
mode?: DiffPanelMode;
}
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { resolvedLocale } = useI18n();
const { settings } = useAppSettings();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
const patchViewportRef = useRef<HTMLDivElement>(null);
const previousDiffOpenRef = useRef(false);
const [reviewStateBySelectionKey, setReviewStateBySelectionKey] = useState<
Record<string, DiffFileReviewStateByPath>
>({});
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const diffOpen = diffSearch.diff === "1";
const activeThreadId = routeThreadId;
const activeThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
);
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useStore((store) =>
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
const isGitRepo = gitBranchesQuery.data?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
() =>
[...turnDiffSummaries].toSorted((left, right) => {
const leftTurnCount =
left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
const rightTurnCount =
right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
if (leftTurnCount !== rightTurnCount) {
return rightTurnCount - leftTurnCount;
}
return right.completedAt.localeCompare(left.completedAt);
}),
[inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
);
const selectedTurnId = diffSearch.diffTurnId ?? null;
const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
const selectedTurn =
selectedTurnId === null
? undefined
: (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
orderedTurnDiffSummaries[0]);
const selectedCheckpointTurnCount =
selectedTurn &&
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
const selectedCheckpointRange = useMemo(
() =>
typeof selectedCheckpointTurnCount === "number"
? {
fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
toTurnCount: selectedCheckpointTurnCount,
}
: null,
[selectedCheckpointTurnCount],
);
const conversationCheckpointTurnCount = useMemo(() => {
const turnCounts = orderedTurnDiffSummaries
.map(
(summary) =>
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
)
.filter((value): value is number => typeof value === "number");
if (turnCounts.length === 0) {
return undefined;
}
const latest = Math.max(...turnCounts);
return latest > 0 ? latest : undefined;
}, [inferredCheckpointTurnCountByTurnId, orderedTurnDiffSummaries]);
const conversationCheckpointRange = useMemo(
() =>
!selectedTurn && typeof conversationCheckpointTurnCount === "number"
? {
fromTurnCount: 0,
toTurnCount: conversationCheckpointTurnCount,
}
: null,
[conversationCheckpointTurnCount, selectedTurn],
);
const activeCheckpointRange = selectedTurn
? selectedCheckpointRange
: conversationCheckpointRange;
const conversationCacheScope = useMemo(() => {
if (selectedTurn || orderedTurnDiffSummaries.length === 0) {
return null;
}
return `conversation:${orderedTurnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
}, [orderedTurnDiffSummaries, selectedTurn]);
const activeCheckpointDiffQuery = useQuery(
checkpointDiffQueryOptions({
threadId: activeThreadId,
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
enabled: isGitRepo,
}),
);
const selectedTurnCheckpointDiff = selectedTurn
? activeCheckpointDiffQuery.data?.diff
: undefined;
const conversationCheckpointDiff = selectedTurn
? undefined
: activeCheckpointDiffQuery.data?.diff;
const isLoadingCheckpointDiff = activeCheckpointDiffQuery.isLoading;
const checkpointDiffError =
activeCheckpointDiffQuery.error instanceof Error
? activeCheckpointDiffQuery.error.message
: activeCheckpointDiffQuery.error
? "Failed to load checkpoint diff."
: null;
const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
const hasResolvedPatch = typeof selectedPatch === "string";
const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
const renderablePatch = useMemo(
() => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`),
[resolvedTheme, selectedPatch],
);
const renderableFiles = useMemo(() => {
if (!renderablePatch || renderablePatch.kind !== "files") {
return [];
}
return renderablePatch.files.toSorted((left, right) =>
resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
numeric: true,
sensitivity: "base",
}),
);
}, [renderablePatch]);
const patchReviewSelectionKey = useMemo(() => {
if (!activeThreadId || !selectedPatch) {
return null;
}
const scope = selectedTurn ? `turn:${selectedTurn.turnId}` : "conversation";
return `${activeThreadId}:${scope}:${buildPatchCacheKey(selectedPatch, "diff-review")}`;
}, [activeThreadId, selectedPatch, selectedTurn]);
const renderableFilePaths = useMemo(
() => renderableFiles.map((fileDiff) => resolveFileDiffPath(fileDiff)),
[renderableFiles],
);
const activeReviewState = useMemo(() => {
return patchReviewSelectionKey
? (reviewStateBySelectionKey[patchReviewSelectionKey] ?? {})
: {};
}, [patchReviewSelectionKey, reviewStateBySelectionKey]);
const acceptedFileCount = useMemo(
() =>
renderableFilePaths.reduce(
(count, filePath) => count + (activeReviewState[filePath]?.accepted ? 1 : 0),
0,
),
[activeReviewState, renderableFilePaths],
);
const hasUnacceptedFiles =
renderableFilePaths.length > 0 && acceptedFileCount < renderableFilePaths.length;
useEffect(() => {
if (diffOpen && !previousDiffOpenRef.current) {
setDiffWordWrap(settings.diffWordWrap);
}
previousDiffOpenRef.current = diffOpen;
}, [diffOpen, settings.diffWordWrap]);
useEffect(() => {
if (!patchReviewSelectionKey) {
return;
}
setReviewStateBySelectionKey((current) => {
const nextSelectionState = reconcileDiffFileReviewState(
renderableFilePaths,
current[patchReviewSelectionKey],
);
if (current[patchReviewSelectionKey] === nextSelectionState) {
return current;
}
return {
...current,
[patchReviewSelectionKey]: nextSelectionState,
};
});
}, [patchReviewSelectionKey, renderableFilePaths]);
useEffect(() => {
if (!patchReviewSelectionKey || !selectedFilePath) {
return;
}
setReviewStateBySelectionKey((current) => {
const selectionState = current[patchReviewSelectionKey];
if (!selectionState) {
return current;
}
const nextSelectionState = expandDiffFile(selectionState, selectedFilePath);
if (nextSelectionState === selectionState) {
return current;
}
return {
...current,
[patchReviewSelectionKey]: nextSelectionState,
};
});
}, [patchReviewSelectionKey, selectedFilePath]);
useEffect(() => {
if (!selectedFilePath || !patchViewportRef.current) {
return;
}
const target = Array.from(
patchViewportRef.current.querySelectorAll<HTMLElement>("[data-diff-file-path]"),
).find((element) => element.dataset.diffFilePath === selectedFilePath);
target?.scrollIntoView({ block: "nearest" });
}, [selectedFilePath, renderableFiles]);
const openFileInCodeViewer = useFileViewNavigation();
const openDiffFileInCodeViewer = useCallback(
(filePath: string) => {
if (!activeCwd) return;
openFileInCodeViewer(activeCwd, filePath);
},
[activeCwd, openFileInCodeViewer],
);
const updateActiveReviewState = useCallback(
(updater: (current: DiffFileReviewStateByPath) => DiffFileReviewStateByPath) => {
if (!patchReviewSelectionKey) {
return;
}
setReviewStateBySelectionKey((current) => ({
...current,
[patchReviewSelectionKey]: updater(current[patchReviewSelectionKey] ?? {}),
}));
},
[patchReviewSelectionKey],
);
const onToggleFileAccepted = useCallback(
(filePath: string) => {
updateActiveReviewState((current) => toggleDiffFileAccepted(current, filePath));
},
[updateActiveReviewState],
);
const onAcceptAllFiles = useCallback(() => {
if (renderableFilePaths.length === 0) {
return;
}
updateActiveReviewState((current) => acceptAllDiffFiles(current, renderableFilePaths));
}, [renderableFilePaths, updateActiveReviewState]);
const onToggleFileCollapsed = useCallback(
(filePath: string) => {
updateActiveReviewState((current) => toggleDiffFileCollapsed(current, filePath));
},
[updateActiveReviewState],
);
const latestSelectedTurnId = orderedTurnDiffSummaries[0]?.turnId ?? null;
const selectTurn = useCallback(
(turnId: TurnId) => {
if (!activeThread) return;
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, diff: "1", diffTurnId: turnId };
},
});
},
[activeThread, navigate],
);
const selectWholeConversation = useCallback(() => {
if (!activeThread) return;
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, diff: "1" };
},
});
}, [activeThread, navigate]);
const turnSelectValue = selectedTurnId ?? "all";
const handleTurnSelectChange = useCallback(
(value: string | null) => {
if (value === "all" || value === null) {
selectWholeConversation();
} else {
selectTurn(value as TurnId);
}
},
[selectTurn, selectWholeConversation],
);
const headerRow = (
<>
<div className="min-w-0 flex-1 [-webkit-app-region:no-drag]">
<Select value={turnSelectValue} onValueChange={handleTurnSelectChange}>
<SelectButton size="xs" variant="ghost">
{selectedTurnId === null
? "All changes"
: selectedTurn?.turnId === latestSelectedTurnId
? `Latest • ${formatShortTimestamp(
selectedTurn.completedAt,
settings.timestampFormat,
resolvedLocale,
)}`
: `Change ${
selectedTurn?.checkpointTurnCount ??
(selectedTurn
? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]
: null) ??
"?"
} • ${
selectedTurn
? formatShortTimestamp(
selectedTurn.completedAt,
settings.timestampFormat,
resolvedLocale,
)
: ""
}`}
</SelectButton>
<SelectPopup>
<SelectItem value="all">All changes</SelectItem>
{orderedTurnDiffSummaries.map((summary) => (
<SelectItem key={summary.turnId} value={summary.turnId}>
<span className="flex items-center justify-between gap-3">
<span>
{summary.turnId === latestSelectedTurnId
? "Latest"
: `Change ${
summary.checkpointTurnCount ??
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
"?"
}`}
</span>
<span className="text-muted-foreground text-xs">
{formatShortTimestamp(
summary.completedAt,
settings.timestampFormat,
resolvedLocale,
)}
</span>
</span>
</SelectItem>
))}
</SelectPopup>
</Select>
</div>
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
{renderablePatch?.kind === "files" ? (
<Button
size="xs"
variant="outline"
onClick={onAcceptAllFiles}
disabled={!hasUnacceptedFiles}
className="gap-1.5"
>
<CheckIcon className="size-3.5" />
{hasUnacceptedFiles ? "Accept All" : "All Accepted"}
</Button>
) : null}
<ToggleGroup
className="shrink-0"
variant="outline"
size="xs"
value={[diffRenderMode]}
onValueChange={(value) => {
const next = value[0];
if (next === "stacked" || next === "split") {
setDiffRenderMode(next);
}
}}
>
<Toggle aria-label="Stacked diff view" value="stacked">
<Rows3Icon className="size-3" />
</Toggle>
<Toggle aria-label="Split diff view" value="split">
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
<Toggle
aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
variant="outline"
size="xs"
pressed={diffWordWrap}
onPressedChange={(pressed) => {
setDiffWordWrap(Boolean(pressed));
}}
>
<TextWrapIcon className="size-3" />
</Toggle>
</div>
</>
);
return (
<DiffPanelShell mode={mode} header={headerRow}>
{!activeThread ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
Select a thread to inspect changes.
</div>
) : !isGitRepo ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
Changes are unavailable because this project is not a git repository.
</div>
) : orderedTurnDiffSummaries.length === 0 ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
No captured changes yet.
</div>
) : (
<>
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
{checkpointDiffError && !renderablePatch && (
<div className="px-3">
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
</div>
)}
{!renderablePatch ? (
isLoadingCheckpointDiff ? (
<DiffPanelLoadingState label="Loading changes..." />
) : (
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
<p>
{hasNoNetChanges
? "No net changes in this selection."
: "No patch available for this selection."}
</p>
</div>
)
) : renderablePatch.kind === "files" ? (
<Virtualizer
// `@pierre/diffs` virtualizes file bodies against its own scroll root.
// Nesting that root inside another scrolling viewport leaves the diff
// rows stuck in placeholder mode, which matches the blank panels here.
className="diff-panel-viewport diff-render-surface h-full min-h-0 min-w-0 overflow-x-hidden overflow-y-auto"
contentClassName="px-2 pb-2"
config={{
overscrollSize: 600,
intersectionObserverMargin: 1200,
}}
>
{renderableFiles.map((fileDiff) => {
const filePath = resolveFileDiffPath(fileDiff);
const fileKey = buildFileDiffRenderKey(fileDiff);
const themedFileKey = `${fileKey}:${resolvedTheme}`;
const fileReviewState = activeReviewState[filePath] ?? {
accepted: false,
collapsed: true,
};
return (
<DiffFileSection
key={themedFileKey}
accepted={fileReviewState.accepted}
collapsed={fileReviewState.collapsed}
diffRenderMode={diffRenderMode}
diffWordWrap={diffWordWrap}
fileDiff={fileDiff}
fileKey={themedFileKey}
filePath={filePath}
onOpenInEditor={openDiffFileInCodeViewer}
onToggleAccepted={onToggleFileAccepted}
onToggleCollapsed={onToggleFileCollapsed}
resolvedTheme={resolvedTheme}
/>
);
})}
</Virtualizer>
) : (
<RawPatchViewer text={renderablePatch.text} reason={renderablePatch.reason} />
)}
</div>
</>
)}
</DiffPanelShell>
);
}