Repository navigation
Expand file tree
/
Copy pathDiffPanel.tsx
More file actions
1542 lines (1520 loc) · 63.2 KB
/
Copy pathDiffPanel.tsx
File metadata and controls
1542 lines (1520 loc) · 63.2 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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { RefreshIcon } from "~/components/ui/refresh-icon";
import { useAtomValue } from "@effect/atom-react";
import type { FileDiffContentsLoader, FileDiffMetadata } from "@pierre/diffs";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import type { ReviewBranchCommitsResult, ScopedThreadRef, RunId } from "@t3tools/contracts";
import {
ArrowRightIcon,
CheckIcon,
ChevronDownIcon,
Columns2Icon,
FlaskConicalOffIcon,
FolderTreeIcon,
PilcrowIcon,
Rows3Icon,
TextWrapIcon,
ChevronRightIcon,
ChevronsDownUpIcon,
ChevronsUpDownIcon,
} from "lucide-react";
import * as Schema from "effect/Schema";
import { type MouseEvent, useEffect, useRef, useState } from "react";
import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
import { useFilesystemReadAccess } from "~/state/filesystem";
import { useOpenInPreferredEditor } from "../editorPreferences";
import { useFileContextMenuHandler } from "../fileContextMenu";
import { type DraftId } from "../composerDraftStore";
import { openDiffFilePrimaryAction } from "../diffFileActions";
import { toolCallDiff } from "../lib/toolCallDiff";
import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries";
import { revisionedQuery } from "~/state/revisionedQuery";
import { cn } from "~/lib/utils";
import {
resolveToolCallDiffTarget,
selectThreadBranchBaseRef,
selectThreadDiffPanelSelection,
useDiffPanelSessionStore,
useDiffPanelStore,
} from "../diffPanelStore";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { isTestChangedFile } from "@t3tools/shared/changedFileKind";
import { useHideTestFiles } from "./diffs/useHideTestFiles";
import { useRenderedAppearance } from "../hooks/useTheme";
import { useStableCallback } from "../hooks/useStableCallback";
import {
buildFileDiffContentVersion,
buildFileDiffIdentityKey,
getDiffLineStat,
getRenderablePatch,
resolveDiffThemeName,
resolveFileDiffPath,
} from "../lib/diffRendering";
import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "../hooks/useLiveRefresh";
import {
useProject,
useThreadCheckpointSummaries,
useQuietThreadShell,
useQuietThreadVisibleTurnItems,
} from "../state/entities";
import { useClientSettings, updateClientSettings } from "../hooks/useSettings";
import { formatRelativeTimeLabel, formatShortTimestamp } from "../timestampFormat";
import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { DiffStatLabel } from "./chat/DiffStatLabel";
import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView";
import { DiffFileTree } from "./diffs/DiffFileTree";
import { FileExplorerPane } from "./files/FileExplorerPane";
import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";
import { Button } from "./ui/button";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
import { Switch } from "./ui/switch";
import {
Combobox,
ComboboxEmpty,
ComboboxSearchInput,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxTrigger,
} from "./ui/combobox";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "./ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { useEnvironmentQuery } from "../state/query";
import { useAtomCommand } from "../state/use-atom-command";
import { serverEnvironment } from "../state/server";
import { reviewEnvironment } from "../state/review";
import { vcsEnvironment } from "../state/vcs";
import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
import { createGitDiffFileContentsLoader } from "../lib/diffFileContents";
import { observeIntersection } from "~/lib/observeIntersection";
import { useReviewFilePatches } from "./diffs/useReviewFilePatches";
import { DiffFileLoadingBoundary } from "./diffs/DiffFileLoadingBoundary";
import { DiffFileStatus } from "./diffs/DiffFileStatus";
import { useThreadRouteRef } from "../hooks/useThreadRouteTarget";
import { projectCommitUrl } from "@t3tools/client-runtime/change-request-links";
import { useOpenLink } from "../browser/useOpenLink";
type DiffThemeType = "light" | "dark";
const AUTOMATIC_BASE_REF = "__automatic_base_ref__";
const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen";
const fileEntryCache = new WeakMap<
FileDiffMetadata,
{ fileDiff: FileDiffMetadata; fileKey: string; fileVersion: number }
>();
function getCachedFileEntry(fileDiff: FileDiffMetadata) {
const cached = fileEntryCache.get(fileDiff);
if (cached) return cached;
const entry = {
fileDiff,
fileKey: buildFileDiffIdentityKey(fileDiff),
fileVersion: buildFileDiffContentVersion(fileDiff),
};
fileEntryCache.set(fileDiff, entry);
return entry;
}
const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
function DiffFileCollapseToggle({
filePath,
fileKey,
collapsed,
onToggle,
load,
}: {
filePath: string;
fileKey: string;
collapsed: boolean;
load?: () => void;
onToggle: (fileKey: string) => void;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost"
className="-ms-0.5"
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
aria-expanded={!collapsed}
ref={(node) => {
if (!node || !load) return;
return observeIntersection(
node,
(entry) => {
if (entry.isIntersecting) load();
},
{ rootMargin: "600px" },
);
}}
onClick={(event) => {
event.stopPropagation();
onToggle(fileKey);
}}
/>
}
>
{collapsed ? (
<ChevronRightIcon className="size-4 text-muted-foreground/80" />
) : (
<ChevronDownIcon className="size-4 text-muted-foreground/80" />
)}
</TooltipTrigger>
<TooltipPopup side="top">{collapsed ? "Expand diff" : "Collapse diff"}</TooltipPopup>
</Tooltip>
);
}
function DiffFileHeaderSuffix({
filePath,
hasStat,
error,
truncated,
onRetry,
}: {
filePath: string;
hasStat: boolean;
error: boolean;
truncated: boolean;
onRetry: (path: string) => void;
}) {
return (
<>
<span data-diff-copy-path className="inline-flex">
<DiffFilePathCopyButton filePath={filePath} />
</span>
{hasStat ? (
<DiffFileStatus error={error} truncated={truncated} retry={() => onRetry(filePath)} />
) : null}
</>
);
}
interface DiffPanelProps {
mode?: DiffPanelMode;
composerDraftTarget: ScopedThreadRef | DraftId;
workspaceMutationId: string | null;
visible: boolean;
}
export default function DiffPanel({
mode = "inline",
composerDraftTarget,
workspaceMutationId,
visible,
}: DiffPanelProps) {
const resolvedTheme = useRenderedAppearance();
const settings = useClientSettings((settings) => ({
diffFilesCollapsed: settings.diffFilesCollapsed,
diffIgnoreWhitespace: settings.diffIgnoreWhitespace,
diffLayout: settings.diffLayout,
timestampFormat: settings.timestampFormat,
wordWrap: settings.wordWrap,
}));
const diffLayout = settings.diffLayout;
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
const diffIgnoreWhitespace =
useDiffPanelSessionStore((state) => state.ignoreWhitespace) ?? settings.diffIgnoreWhitespace;
const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(
DIFF_FILE_TREE_STORAGE_KEY,
false,
Schema.Boolean,
);
const [hideTestFiles, setHideTestFiles] = useHideTestFiles();
const [baseRefQuery, setBaseRefQuery] = useState("");
// The open commit menu keeps the list it opened with, so rows do not move under the pointer.
const [openCommitMenu, setOpenCommitMenu] = useState<ReviewBranchCommitsResult | null>(null);
const [codeViewRevision, setCodeViewRevision] = useState(0);
const routeThreadRef = useThreadRouteRef();
const activeThreadId = routeThreadRef?.threadId ?? null;
const activeThread = useQuietThreadShell(routeThreadRef);
const fileAccess = useFilesystemReadAccess(activeThread?.environmentId ?? null);
const { canReadFiles } = fileAccess;
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useProject(
activeThread && activeProjectId
? {
environmentId: activeThread.environmentId,
projectId: activeProjectId,
}
: null,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot;
const activeRepositoryRoot = activeThread?.worktreePath
? undefined
: activeProject?.repositoryIdentity?.rootPath;
const serverConfig = useAtomValue(
serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),
);
const onFileContextMenu = useFileContextMenuHandler(activeThread?.environmentId ?? null);
const openInPreferredEditor = useOpenInPreferredEditor(
activeThread?.environmentId ?? null,
serverConfig?.availableEditors ?? [],
);
const getDiffFileContents = useAtomCommand(reviewEnvironment.diffFileContents);
const gitStatusQuery = useEnvironmentQuery(
activeThread !== null && activeThread !== undefined && activeCwd != null
? vcsEnvironment.status({
environmentId: activeThread.environmentId,
input: { cwd: activeCwd },
})
: null,
);
const diffSelection = useDiffPanelStore((state) =>
selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef),
);
const rememberedBaseRef = useDiffPanelStore((state) =>
selectThreadBranchBaseRef(state, routeThreadRef),
);
const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null;
const isGitSelection =
diffSelection.kind === "branch" ||
diffSelection.kind === "unstaged" ||
diffSelection.kind === "commit";
const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null);
const toolCallDetail = useTurnItemDetail(
toolCallSelection && routeThreadRef
? {
...resolveToolCallDiffTarget(toolCallSelection, toolCallItems),
environmentId: routeThreadRef.environmentId,
}
: null,
);
const toolCallItem = toolCallDetail.data?.item;
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef);
const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => {
if (left.checkpointTurnCount !== right.checkpointTurnCount) {
return right.checkpointTurnCount - left.checkpointTurnCount;
}
return right.completedAt.localeCompare(left.completedAt);
});
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rewrites the persisted diff store selection to the latest turn when the selected turn disappears
useEffect(() => {
if (!routeThreadRef || diffSelection.kind !== "turn") return;
useDiffPanelStore.getState().reconcileTurnSelection(
routeThreadRef,
orderedTurnDiffSummaries.map((summary) => summary.runId),
);
}, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
const selectedGitScope =
diffSelection.kind === "unstaged" || diffSelection.kind === "commit"
? diffSelection.kind
: "branch";
const selectedCommitSha = diffSelection.kind === "commit" ? diffSelection.sha : null;
const selectedBaseRef =
diffSelection.kind === "branch" || diffSelection.kind === "commit"
? diffSelection.baseRef
: null;
const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
const selectedFileRevealRequestId =
diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
const selectedTurn =
selectedRunId === null
? undefined
: (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ??
orderedTurnDiffSummaries[0]);
const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount;
const latestTurn = orderedTurnDiffSummaries[0];
const reviewSectionId = toolCallSelection
? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}`
: selectedTurn
? `turn:${selectedTurn.runId}`
: selectedCommitSha !== null
? `commit:${selectedCommitSha}`
: selectedGitScope;
const collapseScopeKey = routeThreadRef
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
: null;
const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
const selectedCheckpointRange =
typeof selectedCheckpointTurnCount === "number"
? {
fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
toTurnCount: selectedCheckpointTurnCount,
}
: null;
const activeCheckpointDiff = useCheckpointDiff(
{
environmentId: activeThread?.environmentId ?? null,
threadId: activeThreadId,
fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
ignoreWhitespace: diffIgnoreWhitespace,
cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null,
},
{ enabled: isGitRepo && selectedTurn !== undefined },
);
const branchDiffPreviewInput =
canReadFiles && isGitSelection && activeThread && activeCwd
? {
cwd: activeCwd,
...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
...(selectedCommitSha !== null ? { commitSha: selectedCommitSha } : {}),
ignoreWhitespace: diffIgnoreWhitespace,
metadataOnly: true,
...(selectedCommitSha === null
? {
sourceKind:
selectedGitScope === "unstaged"
? ("working-tree" as const)
: ("branch-range" as const),
}
: {}),
}
: undefined;
const canRefreshGitDiff =
isGitRepo && isGitSelection && activeThread != null && activeCwd != null;
// Read under the workspace mutation id, so each mutation refetches the diff; the panel stays
// mounted while hidden, so a mutation made then is already reflected when it shows.
const branchDiffPreview = useEnvironmentQuery(
branchDiffPreviewInput && activeThread
? revisionedQuery(
reviewEnvironment.diffPreview({
environmentId: activeThread.environmentId,
input: branchDiffPreviewInput,
}),
canRefreshGitDiff ? workspaceMutationId : undefined,
)
: null,
);
const branchCommitsQuery = useEnvironmentQuery(
visible && isGitRepo && canReadFiles && activeThread && activeCwd
? reviewEnvironment.branchCommits({
environmentId: activeThread.environmentId,
input: {
cwd: activeCwd,
...(rememberedBaseRef ? { baseRef: rememberedBaseRef } : {}),
},
})
: null,
);
const branchCommits = openCommitMenu ?? branchCommitsQuery.data;
const activeThreadRefreshKey = routeThreadRef
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
: null;
const selectedGitSource = branchDiffPreview.data?.sources.find(
(source) =>
source.kind ===
(selectedGitScope === "unstaged"
? "working-tree"
: selectedGitScope === "commit"
? "commit"
: "branch-range"),
);
const comparisonHeadRef = selectedGitSource?.headRef ?? gitStatusQuery.data?.refName ?? "HEAD";
const comparisonBaseRef = selectedGitSource?.baseRef ?? selectedBaseRef ?? "Automatic";
const selectedCommitSubject =
selectedCommitSha !== null && selectedGitSource?.headRef === selectedCommitSha
? selectedGitSource.commitSubject
: undefined;
const selectedGitScopeLabel =
selectedCommitSha !== null
? (selectedCommitSubject ?? `Commit ${selectedCommitSha.slice(0, 7)}`)
: selectedGitScope === "unstaged"
? "Uncommitted"
: "Changes";
const selectedScopeLabel = toolCallSelection
? "Tool call"
: selectedRunId === null
? selectedCommitSha !== null
? (selectedCommitSubject ?? "Commit")
: selectedGitScopeLabel
: selectedTurn?.runId === latestTurn?.runId
? "Latest turn"
: `Turn ${selectedCheckpointTurnCount ?? "?"}`;
const reviewSectionTitle = toolCallSelection
? "Tool call"
: selectedTurn
? `Turn ${selectedCheckpointTurnCount ?? "?"}`
: selectedGitScopeLabel;
const headerCommitSha = selectedRunId === null ? selectedCommitSha : null;
const selectedCommitUrl =
headerCommitSha !== null
? projectCommitUrl(activeProject?.repositoryIdentity, headerCommitSha)
: null;
const openLink = useOpenLink(routeThreadRef);
// A SHA link goes to the code host; it must not route back into this pane's commit selection.
const openCommitUrl = (event: MouseEvent<HTMLElement>, url: string) => {
event.stopPropagation();
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button === 1)
return;
event.preventDefault();
void openLink(url, { event });
};
const refreshPreviewQuery = branchDiffPreview.refresh;
const refreshDiffFromUserAction = refreshPreviewQuery;
const preview = branchDiffPreview.data;
const gitDiff = selectedGitSource?.diff;
const toolCallPreview =
toolCallSelection && toolCallItem?.type === "file_change" ? toolCallDiff(toolCallItem) : null;
const selectedPatch = toolCallSelection
? toolCallPreview?.patch
: selectedTurn
? activeCheckpointDiff.data?.diff
: gitDiff;
const isSelectedPatchTruncated =
toolCallPreview?.truncated === true ||
(isGitSelection && selectedGitSource?.truncated === true);
const selectedPatchQuery = toolCallSelection
? toolCallDetail
: selectedTurn
? activeCheckpointDiff
: branchDiffPreview;
const isLoadingSelectedPatch =
selectedPatchQuery.isPending &&
(selectedPatchQuery.data === null ||
(isGitSelection && preview?.incomplete === true && selectedGitSource?.files?.length === 0));
const selectedPatchError = toolCallSelection
? toolCallDetail.error
: selectedTurn
? activeCheckpointDiff.error
: branchDiffPreview.error;
const hasResolvedPatch = typeof selectedPatch === "string";
const hasNoNetChanges =
hasResolvedPatch &&
selectedPatch.trim().length === 0 &&
!preview?.incomplete &&
(!selectedGitSource?.patchesDeferred || selectedGitSource.files?.length === 0);
const lazySource =
isGitSelection &&
(selectedGitSource?.truncated || selectedGitSource?.patchesDeferred) &&
selectedGitSource.files?.length
? selectedGitSource
: null;
const renderablePatch = getRenderablePatch(
lazySource ? undefined : selectedPatch,
`diff-panel:${resolvedTheme}`,
{
compactPartialHunkOffsets: isGitSelection,
...(toolCallSelection ? { ignoreWhitespace: diffIgnoreWhitespace } : {}),
},
);
const recordedToolCallFileCount =
toolCallSelection && toolCallItem?.type === "file_change"
? (toolCallItem.changes?.length ?? 0)
: 0;
const omittedToolCallFiles =
renderablePatch?.kind === "files"
? Math.max(0, recordedToolCallFileCount - renderablePatch.files.length)
: 0;
const fileStats = new Map(lazySource?.files?.map((file) => [file.path, file]));
const sourceLineStat =
isGitSelection && selectedGitSource?.files
? selectedGitSource.files.reduce(
(total, file) => ({
additions: total.additions + file.additions,
deletions: total.deletions + file.deletions,
}),
{ additions: 0, deletions: 0 },
)
: null;
const currentLoadDiffFiles =
isGitSelection && activeThread && preview && selectedGitSource && canReadFiles
? createGitDiffFileContentsLoader(getDiffFileContents, {
environmentId: activeThread.environmentId,
cwd: preview.cwd,
sourceKind: selectedGitSource.kind,
baseRef: selectedGitSource.baseRef,
headRef: selectedGitSource.headRef,
cacheKey: selectedGitSource.diffHash,
})
: undefined;
const loadDiffFiles: FileDiffContentsLoader = useStableCallback(async (fileDiff) => {
if (!currentLoadDiffFiles) {
throw new Error("Diff file contents are unavailable for this selection.");
}
return currentLoadDiffFiles(fileDiff);
});
const canSelectBranchBase = canReadFiles && canRefreshGitDiff && selectedGitScope === "branch";
const branchRefsCwd = branchDiffPreview.data?.cwd ?? activeCwd;
const localBranchRefs = useEnvironmentQuery(
canSelectBranchBase && activeThread && branchRefsCwd
? vcsEnvironment.listRefs({
environmentId: activeThread.environmentId,
input: {
cwd: branchRefsCwd,
includeMatchingRemoteRefs: true,
refKind: "local",
...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
limit: 100,
},
})
: null,
);
const remoteBranchRefs = useEnvironmentQuery(
canSelectBranchBase && activeThread && branchRefsCwd
? vcsEnvironment.listRefs({
environmentId: activeThread.environmentId,
input: {
cwd: branchRefsCwd,
includeMatchingRemoteRefs: true,
refKind: "remote",
...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
limit: 100,
},
})
: null,
);
const baseRefChoices = buildBaseRefChoices(
localBranchRefs.data?.refs.filter((ref) => ref.name !== comparisonHeadRef) ?? [],
remoteBranchRefs.data?.refs ?? [],
);
const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery);
const valueForBaseRefChoice = (choice: (typeof baseRefChoices)[number]) =>
selectedBaseRef && selectedBaseRef === choice.remote?.name
? selectedBaseRef
: (choice.local?.name ?? choice.remote?.name ?? choice.id);
const baseRefItems = [AUTOMATIC_BASE_REF, ...baseRefChoices.map(valueForBaseRefChoice)];
const filteredBaseRefItems = [
...(baseRefQuery.trim().length === 0 ? [AUTOMATIC_BASE_REF] : []),
...matchingBaseRefChoices.map(valueForBaseRefChoice),
];
const {
isPending: areFilePatchesPending,
fileStates,
retry,
requestFile,
renderableFiles,
remainingFileCount,
loadNextFiles,
} = useReviewFilePatches({
environmentId: activeThread?.environmentId,
cwd: branchDiffPreview.data?.cwd,
source: lazySource,
baseRef:
selectedCommitSha !== null ? selectedBaseRef : (lazySource?.baseRef ?? selectedBaseRef),
ignoreWhitespace: diffIgnoreWhitespace,
theme: resolvedTheme,
previewInput: branchDiffPreviewInput,
preview: renderablePatch,
});
const refreshBranchDiffPreview = refreshPreviewQuery;
const diffRefreshKey = `diff:${activeThreadRefreshKey ?? ""}`;
// The panel stays mounted while hidden, and edits made outside T3 Code bump no mutation id, so
// showing it revalidates the diff; that also stands in for focus events missed while hidden.
// A git diff is too costly to repeat on a timer nobody asked for. A diff read within the floor,
// such as a mutation's refetch while hidden, already counts as that revalidation.
useLiveRefresh(
branchDiffPreview.data !== null && !branchDiffPreview.isPending
? () => {
if (Date.now() - branchDiffPreview.dataUpdatedAt < LIVE_REFRESH_MIN_INTERVAL_MS) return;
refreshBranchDiffPreview();
}
: null,
{
enabled: visible && canReadFiles && canRefreshGitDiff,
key: diffRefreshKey,
intervalMs: null,
refreshOnShow: true,
},
);
const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;
const pathOccurrences = new Map<string, number>();
const renderableFileEntries = renderableFiles.map((fileDiff) => {
const entry = getCachedFileEntry(fileDiff);
if (!isGitSelection) return entry;
// Metadata has no change type; keep each path's identity when its patch arrives.
const pathKey = JSON.stringify([fileDiff.prevName ?? fileDiff.name, fileDiff.name]);
const occurrence = pathOccurrences.get(pathKey) ?? 0;
pathOccurrences.set(pathKey, occurrence + 1);
return { ...entry, fileKey: `${pathKey}:${occurrence}` };
});
const diffFileKeys = renderableFileEntries.map((file) => file.fileKey);
const testFileCount = renderableFiles.filter((file) =>
isTestChangedFile(resolveFileDiffPath(file)),
).length;
// Hiding is display-only: lazy loading indexes into the full list. A requested file stays visible.
const isFileShown = (file: FileDiffMetadata) => {
const path = resolveFileDiffPath(file);
return !hideTestFiles || path === selectedFilePath || !isTestChangedFile(path);
};
const shownFileEntries = renderableFileEntries.filter(({ fileDiff }) => isFileShown(fileDiff));
const shownFileKeys = shownFileEntries.map((file) => file.fileKey);
const defaultCollapsedDiffFileKeys = settings.diffFilesCollapsed
? new Set(diffFileKeys)
: EMPTY_COLLAPSED_DIFF_FILE_KEYS;
const storedCollapsedDiffFileKeys = useDiffPanelSessionStore((state) =>
collapseScopeKey ? state.collapsedFileKeysByScopeKey[collapseScopeKey] : undefined,
);
const collapsedDiffFileKeys = storedCollapsedDiffFileKeys ?? defaultCollapsedDiffFileKeys;
const updateCollapsedDiffFiles = (
update: (current: ReadonlySet<string>) => ReadonlySet<string>,
) => {
if (!collapseScopeKey) return;
useDiffPanelSessionStore
.getState()
.updateCollapsedFileKeys(collapseScopeKey, defaultCollapsedDiffFileKeys, update);
};
const renderLoadingBoundary = () =>
remainingFileCount > 0 ? (
<DiffFileLoadingBoundary load={loadNextFiles} count={remainingFileCount} />
) : null;
const codeViewFiles = shownFileEntries.map(({ fileDiff, fileKey, fileVersion }) => ({
fileDiff,
filePath: resolveFileDiffPath(fileDiff),
fileKey,
fileVersion,
collapsed:
collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
}));
const pendingFiles = renderableFiles.filter(
(file) => file.cacheKey?.endsWith(":pending") && isFileShown(file),
);
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(shownFileKeys, collapsedDiffFileKeys);
const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
const fileTreeEntries = diffFileTreeEntries(renderableFiles.filter(isFileShown));
const codeViewReveal = useCodeViewFileReveal();
const revealDiffFile = (filePath: string) => {
const index = renderableFileEntries.findIndex(
(candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
);
const file = renderableFileEntries[index];
if (!file) return false;
updateCollapsedDiffFiles((current) => {
const next = new Set(current);
next.delete(file.fileKey);
return next;
});
if (lazySource) requestFile(filePath);
codeViewReveal.request(file.fileKey);
return true;
};
// A file another view asked to reveal (a chat diff link): retried as the diff loads until it
// holds the file, then not again until a new request, so it does not undo what the user did since.
const externalRevealRef = useRef<string | null>(null);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals an externally requested file in the diff viewer, retrying as the diff DOM loads
useEffect(() => {
if (!selectedFilePath) {
externalRevealRef.current = null;
return;
}
const key = JSON.stringify([collapseScopeKey, selectedFilePath, selectedFileRevealRequestId]);
if (externalRevealRef.current === key) return;
if (revealDiffFile(selectedFilePath)) {
externalRevealRef.current = key;
}
}, [collapseScopeKey, selectedFilePath, selectedFileRevealRequestId, revealDiffFile]);
const openDiffFile = (filePath: string) => {
openDiffFilePrimaryAction({
threadRef: routeThreadRef,
filePath,
activeCwd,
repositoryRoot: activeRepositoryRoot,
openInEditor: (targetPath) => {
void (async () => {
const result = await openInPreferredEditor(targetPath);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
console.warn("Failed to open diff file in editor.", {
operation: "open-diff-file",
...(routeThreadRef
? {
environmentId: routeThreadRef.environmentId,
threadId: routeThreadRef.threadId,
}
: {}),
...safeErrorLogAttributes(squashAtomCommandFailure(result)),
});
}
})();
},
});
};
const toggleDiffFileCollapsed = useStableCallback((fileKey: string) => {
const file = renderableFileEntries.find((file) => file.fileKey === fileKey);
if (lazySource && file) requestFile(resolveFileDiffPath(file.fileDiff));
const pending = file?.fileDiff.cacheKey?.endsWith(":pending") === true;
updateCollapsedDiffFiles((current) => {
const next = new Set(current);
if (pending || next.has(fileKey)) {
next.delete(fileKey);
} else {
next.add(fileKey);
}
return next;
});
});
// Find can ask again before the unfolded file reaches the viewer, so this must never fold.
const unfoldDiffFile = useStableCallback((fileKey: string) => {
updateCollapsedDiffFiles((current) => {
if (!current.has(fileKey)) return current;
const next = new Set(current);
next.delete(fileKey);
return next;
});
});
const toggleDiffFileCollapse = () => {
setCodeViewRevision((current) => current + 1);
updateCollapsedDiffFiles((current) => toggleAllDiffFiles(shownFileKeys, current));
};
const selectTurn = (runId: RunId) => {
if (!routeThreadRef) return;
useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
};
const selectGitScope = (scope: "branch" | "unstaged") => {
if (!routeThreadRef) return;
useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
};
const selectBranchBaseRef = (baseRef: string | null) => {
if (!routeThreadRef) return;
useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
};
const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : "";
const selectedCommitValue = selectedCommitSha !== null ? `commit:${selectedCommitSha}` : "";
const selectedScopeValue = toolCallSelection
? ""
: selectedRunId === null
? selectedCommitValue || selectedGitScope
: selectedTurn?.runId === latestTurn?.runId
? "latest"
: selectedTurnValue;
const selectScopeValue = (value: string) => {
if (value === "unstaged" || value === "branch") {
selectGitScope(value);
} else if (value === selectedCommitValue) {
selectGitScope("branch");
} else if (value.startsWith("commit:")) {
if (routeThreadRef) {
useDiffPanelStore.getState().selectCommit(routeThreadRef, value.slice("commit:".length));
}
} else if (value === "latest") {
if (latestTurn) selectTurn(latestTurn.runId);
} else {
const turn = orderedTurnDiffSummaries.find((summary) => `turn:${summary.runId}` === value);
if (turn) selectTurn(turn.runId);
}
};
const headerRow = (
<>
<div className="@container/diff-refs flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
<DropdownMenu>
<DropdownMenuTrigger
render={<Button size="xs" variant="secondary" />}
className={cn("max-w-full", headerCommitSha !== null && "min-w-0 shrink")}
aria-label={`Diff scope: ${selectedScopeLabel}`}
data-workspace-focus-default
>
<span className="truncate">{selectedScopeLabel}</span>
<ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
</DropdownMenuTrigger>
{headerCommitSha !== null ? (
selectedCommitUrl ? (
<Tooltip>
<TooltipTrigger
render={
<a
href={selectedCommitUrl}
target="_blank"
rel="noopener noreferrer"
className="shrink-0 font-mono text-xs text-muted-foreground underline underline-offset-4"
onClick={(event) => openCommitUrl(event, selectedCommitUrl)}
/>
}
>
{headerCommitSha.slice(0, 7)}
</TooltipTrigger>
<TooltipPopup side="top">{selectedCommitUrl}</TooltipPopup>
</Tooltip>
) : (
<span className="shrink-0 font-mono text-xs text-muted-foreground">
{headerCommitSha.slice(0, 7)}
</span>
)
) : null}
<DropdownMenuContent align="start">
<DropdownMenuRadioGroup value={selectedScopeValue} onValueChange={selectScopeValue}>
<DropdownMenuRadioItem value="branch" closeOnClick>
<span>Changes</span>
</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="unstaged" closeOnClick>
<span>Uncommitted</span>
</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="latest" closeOnClick>
<span>Latest turn</span>
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuRadioGroup value={selectedTurnValue} onValueChange={selectScopeValue}>
{orderedTurnDiffSummaries.map((summary) => {
const turnCount = summary.checkpointTurnCount;
return (
<DropdownMenuRadioItem
key={summary.runId}
value={`turn:${summary.runId}`}
closeOnClick
>
<span className="flex items-center gap-2">
<span>Turn {turnCount}</span>
<span className="ml-auto text-xs tabular-nums text-muted-foreground">
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
</span>
</span>
</DropdownMenuRadioItem>
);
})}
</DropdownMenuRadioGroup>
</DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSub
onOpenChange={(open) => {
setOpenCommitMenu(open ? (branchCommitsQuery.data ?? null) : null);
if (!open) return;
// The menu keeps the list it opened with; the refreshed one shows next time.
branchCommitsQuery.refresh();
}}
>
<DropdownMenuSubTrigger>Commits</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="max-h-80 max-w-96">
<DropdownMenuRadioGroup
value={selectedCommitValue}
onValueChange={selectScopeValue}
>
{branchCommits?.commits.map((commit) => {
const commitUrl = projectCommitUrl(
activeProject?.repositoryIdentity,
commit.sha,
);
return (
<div
key={commit.sha}
className={cn(
"flex items-center rounded-sm hover:bg-accent has-data-highlighted:bg-accent has-focus-visible:bg-accent [&_[data-checked]]:bg-transparent [&_[data-highlighted]]:bg-transparent",
selectedCommitSha === commit.sha && "bg-foreground/[0.08]",
)}
>
<Tooltip>
<TooltipTrigger
render={
<DropdownMenuRadioItem
className="min-w-0 flex-1"
value={`commit:${commit.sha}`}
closeOnClick
/>
}
>
<span className="flex items-center gap-3">
<span className="min-w-0 flex-1 truncate">{commit.subject}</span>
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">
{formatRelativeTimeLabel(commit.committedAt)}
</span>
</span>
</TooltipTrigger>
<TooltipPopup side="right" className="max-w-80">
{commit.subject}
</TooltipPopup>
</Tooltip>
{commitUrl ? (
<DropdownMenuItem
className="shrink-0"
render={
<a
href={commitUrl}
target="_blank"
rel="noopener noreferrer"
aria-label={`Open commit ${commit.sha.slice(0, 7)}`}
/>
}
onClick={(event) => openCommitUrl(event, commitUrl)}
>
<span className="font-mono text-xs text-muted-foreground underline underline-offset-4">
{commit.sha.slice(0, 7)}
</span>
</DropdownMenuItem>
) : (
<span className="shrink-0 px-2 font-mono text-xs text-muted-foreground">
{commit.sha.slice(0, 7)}
</span>
)}
</div>
);
})}
</DropdownMenuRadioGroup>
{branchCommitsQuery.error ? (
<DropdownMenuItem disabled>{branchCommitsQuery.error}</DropdownMenuItem>
) : !canReadFiles ? (
<DropdownMenuItem disabled>
{fileAccess.isPending
? "Checking file access..."
: (fileAccess.error ?? "This connection cannot read local diffs.")}
</DropdownMenuItem>
) : branchCommits === null ? (
<DropdownMenuItem disabled>Loading commits...</DropdownMenuItem>
) : branchCommits.commits.length === 0 ? (
<DropdownMenuItem disabled>No commits on this branch.</DropdownMenuItem>
) : branchCommits.truncated ? (
<DropdownMenuItem disabled>
{`Showing latest ${branchCommits.commits.length} commits`}
</DropdownMenuItem>
) : null}
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuContent>
</DropdownMenu>
{canSelectBranchBase && (
<div
className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
aria-label={`Comparing ${comparisonHeadRef} against ${comparisonBaseRef}`}
>
<Tooltip>
<TooltipTrigger
render={
// Too narrow for both refs, keep the target readable and drop the head, which
// is the thread's own branch.
<span className="flex min-w-[min(3rem,calc(100%-2.75rem))] items-center gap-2 overflow-hidden @max-[20rem]/diff-refs:hidden" />
}
>