forked from Emanuele-web04/synara
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiffPanel.tsx
More file actions
1178 lines (1128 loc) · 47.9 KB
/
Copy pathDiffPanel.tsx
File metadata and controls
1178 lines (1128 loc) · 47.9 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 { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import { FaPlusMinus } from "react-icons/fa6";
import { LuWrapText } from "react-icons/lu";
import {
CheckIcon,
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
Columns2Icon,
CopyIcon,
DiffIcon,
Rows3Icon,
TextWrapIcon,
XIcon,
} from "~/lib/icons";
import {
type WheelEvent as ReactWheelEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
gitBranchesQueryOptions,
gitQueryKeys,
gitStatusQueryOptions,
gitSummarizeDiffQueryOptions,
gitWorkingTreeDiffQueryOptions,
} from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useTheme } from "../hooks/useTheme";
import {
buildPatchCacheKey,
getRenderablePatch,
resolveDiffCopyText,
resolveDiffThemeName,
serializeRenderablePatchText,
summarizePatchStats,
} from "../lib/diffRendering";
import { resolveDiffEnvironmentState } from "../lib/threadEnvironment";
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import {
isRepoDiffScope,
REPO_DIFF_SCOPE_LABELS,
useRepoDiffScopeStore,
} from "../repoDiffScopeStore";
import { useStore } from "../store";
import { createProjectSelector, createThreadSelector } from "../storeSelectors";
import { getProviderStartOptions, useAppSettings } from "../appSettings";
import { useComposerDraftStore } from "../composerDraftStore";
import { formatShortTimestamp } from "../timestampFormat";
import ChatMarkdown from "./ChatMarkdown";
import { resolveDiffPanelThread, resolveDiffSelectAllArmed } from "./DiffPanel.logic";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { Button } from "./ui/button";
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
import { FileEntryIcon } from "./chat/FileEntryIcon";
import { DiffStatLabel, hasNonZeroStat } from "./chat/DiffStatLabel";
import { type SplitViewPanePanelState } from "../splitViewStore";
type DiffRenderMode = "stacked" | "split";
type DiffSurfaceMode = "review" | "summary" | "total";
type DiffThemeType = "light" | "dark";
function buildDiffPanelUnsafeCSS(theme: "light" | "dark"): string {
const titleColor = theme === "dark" ? "#6073CC" : "#526FFF";
return `
:host {
/* Route the entire diff viewer through the chat code font so custom code fonts reach line numbers too. */
--diffs-font-family: var(--font-chat-code-family);
--diffs-header-font-family: var(--font-chat-code-family);
/* Honor the user-chosen chat code font size from settings instead of the library default (13px). */
--diffs-font-size: var(--app-font-size-chat-code, 11px);
font-family: var(--font-chat-code-family) !important;
font-size: var(--app-font-size-chat-code, 11px) !important;
}
[data-diffs-header],
[data-diff],
[data-file],
[data-error-wrapper],
[data-virtualizer-buffer] {
/* Re-assert the code font inside the library chrome because these nodes live in shadow-rooted markup. */
--diffs-font-family: var(--font-chat-code-family) !important;
--diffs-header-font-family: var(--font-chat-code-family) !important;
--diffs-font-size: var(--app-font-size-chat-code, 11px) !important;
font-family: var(--font-chat-code-family) !important;
font-size: var(--app-font-size-chat-code, 11px) !important;
--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] {
font-family: var(--font-chat-code-family) !important;
font-size: var(--app-font-size-chat-code, 11px) !important;
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;
cursor: pointer;
}
/* Hide the default change-type icon (blue circle) — replaced by chevron + file-type icon. */
[data-change-icon] {
display: none;
}
[data-title] {
font-family: var(--font-chat-code-family) !important;
font-size: var(--app-font-size-chat-code, 11px) !important;
cursor: pointer;
color: ${titleColor} !important;
}
`;
}
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}`;
}
interface DiffPanelProps {
mode?: DiffPanelMode;
threadId?: ThreadId | null;
panelState?: Pick<SplitViewPanePanelState, "panel" | "diffTurnId" | "diffFilePath">;
onUpdatePanelState?: (
patch: Partial<Pick<SplitViewPanePanelState, "panel" | "diffTurnId" | "diffFilePath">>,
) => void;
onClosePanel?: () => void;
}
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({
mode = "inline",
threadId: controlledThreadId,
panelState,
onUpdatePanelState,
onClosePanel,
}: DiffPanelProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { resolvedTheme } = useTheme();
const { settings } = useAppSettings();
const providerOptions = useMemo(() => getProviderStartOptions(settings), [settings]);
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
const [surfaceMode, setSurfaceMode] = useState<DiffSurfaceMode>("review");
const repoDiffScope = useRepoDiffScopeStore((store) => store.scope);
const setRepoDiffScope = useRepoDiffScopeStore((store) => store.setScope);
const [collapsedFiles, setCollapsedFiles] = useState<Set<string>>(() => new Set());
const patchViewportRef = useRef<HTMLDivElement>(null);
// Tracks an in-flight "select all then copy" gesture inside the virtualized diff surface.
const diffSelectAllArmedRef = useRef(false);
const turnStripRef = useRef<HTMLDivElement>(null);
const previousDiffOpenRef = useRef(false);
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
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 = panelState ? panelState.panel === "diff" : diffSearch.diff === "1";
const activeThreadId = controlledThreadId ?? routeThreadId;
const serverThread = useStore(
useMemo(() => createThreadSelector(activeThreadId), [activeThreadId]),
);
const draftThread = useComposerDraftStore((store) =>
activeThreadId ? (store.draftThreadsByThreadId[activeThreadId] ?? null) : null,
);
const fallbackDraftProjectId = draftThread?.projectId ?? null;
const fallbackDraftProject = useStore(
useMemo(() => createProjectSelector(fallbackDraftProjectId), [fallbackDraftProjectId]),
);
// Keep diff summary access available for draft chats before the first turn promotes them into the server store.
const activeThread = useMemo(
() =>
resolveDiffPanelThread({
threadId: activeThreadId,
serverThread,
draftThread,
fallbackModelSelection: fallbackDraftProject?.defaultModelSelection ?? null,
}),
[activeThreadId, draftThread, fallbackDraftProject?.defaultModelSelection, serverThread],
);
const activeProjectId = activeThread?.projectId ?? draftThread?.projectId ?? null;
const activeProject = useStore(
useMemo(() => createProjectSelector(activeProjectId), [activeProjectId]),
);
const resolvedThreadEnvMode =
serverThread?.envMode ?? draftThread?.envMode ?? activeThread?.envMode;
const resolvedThreadWorktreePath =
serverThread?.worktreePath ?? draftThread?.worktreePath ?? activeThread?.worktreePath ?? null;
const diffEnvironmentState = resolveDiffEnvironmentState({
projectCwd: activeProject?.cwd ?? null,
envMode: resolvedThreadEnvMode,
worktreePath: resolvedThreadWorktreePath,
});
const diffEnvironmentPending = diffEnvironmentState.pending;
const activeCwd = diffEnvironmentState.cwd;
const gitBranchesQuery = useQuery(gitBranchesQueryOptions(activeCwd ?? null));
const gitStatusQuery = useQuery(gitStatusQueryOptions(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 = panelState
? (panelState.diffTurnId ?? null)
: (diffSearch.diffTurnId ?? null);
const selectedFilePath =
selectedTurnId !== null
? panelState
? (panelState.diffFilePath ?? 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 && !diffEnvironmentPending,
}),
);
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 normalizedSelectedPatch = hasResolvedPatch ? selectedPatch.trim() : null;
const repoDiffQuery = useQuery(
gitWorkingTreeDiffQueryOptions({
cwd: activeCwd ?? null,
scope: repoDiffScope,
enabled: diffOpen && !diffEnvironmentPending,
}),
);
const repoPatch = repoDiffQuery.data?.patch;
const hasResolvedRepoPatch = typeof repoPatch === "string";
const hasNoRepoChanges = hasResolvedRepoPatch && repoPatch.trim().length === 0;
const normalizedRepoPatch = hasResolvedRepoPatch ? repoPatch.trim() : null;
const repoDiffError =
repoDiffQuery.error instanceof Error
? repoDiffQuery.error.message
: repoDiffQuery.error
? "Failed to load repo diff."
: null;
const branchHasCommittedChanges = (gitStatusQuery.data?.aheadCount ?? 0) > 0;
useEffect(() => {
if (!hasResolvedRepoPatch || !activeCwd) {
return;
}
void queryClient.invalidateQueries({ queryKey: gitQueryKeys.status(activeCwd) });
void queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(activeCwd) });
}, [activeCwd, hasResolvedRepoPatch, queryClient, repoPatch]);
useEffect(() => {
if (
diffOpen &&
repoDiffScope === "workingTree" &&
hasResolvedRepoPatch &&
hasNoRepoChanges &&
branchHasCommittedChanges
) {
setRepoDiffScope("branch");
setSurfaceMode("total");
}
}, [
branchHasCommittedChanges,
diffOpen,
hasNoRepoChanges,
hasResolvedRepoPatch,
repoDiffScope,
setRepoDiffScope,
]);
const activeReviewPatch = surfaceMode === "total" ? repoPatch : selectedPatch;
const activeReviewError = surfaceMode === "total" ? repoDiffError : checkpointDiffError;
const activeReviewIsLoading =
surfaceMode === "total" ? repoDiffQuery.isLoading : isLoadingCheckpointDiff;
const activeReviewHasNoChanges = surfaceMode === "total" ? hasNoRepoChanges : hasNoNetChanges;
const isSidebarMode = mode === "sidebar";
const { copyToClipboard, isCopied: isSummaryCopied } = useCopyToClipboard();
const { copyToClipboard: copyDiffToClipboard, isCopied: isDiffCopied } = useCopyToClipboard();
const renderablePatch = useMemo(
() => getRenderablePatch(activeReviewPatch, `diff-panel:${resolvedTheme}`),
[activeReviewPatch, resolvedTheme],
);
// Serialize the full diff straight from the parsed model so copy paths never depend on
// which virtualized rows happen to be mounted in the DOM.
const diffCopyText = useMemo(
() => serializeRenderablePatchText(renderablePatch) ?? resolveDiffCopyText(activeReviewPatch),
[renderablePatch, activeReviewPatch],
);
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 totalPatchStat = useMemo(() => summarizePatchStats(repoPatch), [repoPatch]);
useEffect(() => {
if (diffOpen && !previousDiffOpenRef.current) {
setDiffWordWrap(settings.diffWordWrap);
setSurfaceMode("review");
}
previousDiffOpenRef.current = diffOpen;
}, [diffOpen, settings.diffWordWrap]);
const selectedPatchIdentity = useMemo(
() =>
normalizedSelectedPatch && normalizedSelectedPatch.length > 0
? buildPatchCacheKey(normalizedSelectedPatch, "diff-panel:surface")
: null,
[normalizedSelectedPatch],
);
const diffSummaryCacheScope = useMemo(() => {
if (!activeProjectId) {
return activeCwd ?? null;
}
// Share summaries across chats in the same project, while isolating worktrees.
return activeThread?.worktreePath
? `project:${activeProjectId}:worktree:${activeThread.worktreePath}`
: `project:${activeProjectId}:local`;
}, [activeCwd, activeProjectId, activeThread?.worktreePath]);
useEffect(() => {
if (surfaceMode === "summary" && hasResolvedRepoPatch && hasNoRepoChanges) {
setSurfaceMode("review");
}
}, [hasNoRepoChanges, hasResolvedRepoPatch, surfaceMode]);
useEffect(() => {
setSurfaceMode("review");
}, [activeThreadId, diffOpen, selectedPatchIdentity, selectedTurnId]);
const diffSummaryPrefetchOptions = useMemo(
() =>
gitSummarizeDiffQueryOptions({
cwd: activeCwd ?? null,
cacheScope: diffSummaryCacheScope,
patch: normalizedRepoPatch,
codexHomePath: settings.codexHomePath || null,
model: settings.textGenerationModel ?? null,
...(providerOptions ? { providerOptions } : {}),
enabled: true,
}),
[
activeCwd,
diffSummaryCacheScope,
normalizedRepoPatch,
settings.codexHomePath,
settings.textGenerationModel,
providerOptions,
],
);
const diffSummaryQueryOptions = useMemo(
() =>
gitSummarizeDiffQueryOptions({
cwd: activeCwd ?? null,
cacheScope: diffSummaryCacheScope,
patch: normalizedRepoPatch,
codexHomePath: settings.codexHomePath || null,
model: settings.textGenerationModel ?? null,
...(providerOptions ? { providerOptions } : {}),
enabled: surfaceMode === "summary",
}),
[
activeCwd,
diffSummaryCacheScope,
normalizedRepoPatch,
settings.codexHomePath,
settings.textGenerationModel,
providerOptions,
surfaceMode,
],
);
const diffSummaryQuery = useQuery(diffSummaryQueryOptions);
const diffSummaryText = diffSummaryQuery.data?.summary ?? null;
const diffSummaryError =
diffSummaryQuery.error instanceof Error
? diffSummaryQuery.error.message
: diffSummaryQuery.error
? "Failed to generate diff summary."
: null;
const canShowSummary = Boolean(
!diffEnvironmentPending && activeCwd && (!hasResolvedRepoPatch || !hasNoRepoChanges),
);
const canPrefetchSummary = Boolean(
diffOpen && !diffEnvironmentPending && activeCwd && normalizedRepoPatch && !hasNoRepoChanges,
);
const canShowTotal = Boolean(!diffEnvironmentPending && activeCwd);
useEffect(() => {
if (!canPrefetchSummary) {
return;
}
const cachedSummaryState = queryClient.getQueryState(diffSummaryPrefetchOptions.queryKey);
if (
cachedSummaryState?.status === "success" ||
cachedSummaryState?.fetchStatus === "fetching"
) {
return;
}
const timerId = window.setTimeout(() => {
const nextSummaryState = queryClient.getQueryState(diffSummaryPrefetchOptions.queryKey);
if (nextSummaryState?.status === "success" || nextSummaryState?.fetchStatus === "fetching") {
return;
}
void queryClient.prefetchQuery(diffSummaryPrefetchOptions);
}, 900);
return () => {
window.clearTimeout(timerId);
};
}, [canPrefetchSummary, diffSummaryPrefetchOptions, queryClient]);
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 toggleFileCollapsed = useCallback((fileKey: string) => {
setCollapsedFiles((prev) => {
const next = new Set(prev);
if (next.has(fileKey)) next.delete(fileKey);
else next.add(fileKey);
return next;
});
}, []);
// The diff surface is virtualized and renders into shadow DOM, so a native
// "select all + copy" only captures the handful of mounted rows. We watch the
// document: a Cmd/Ctrl+A keydown still passes through the viewport element (so we can
// tell the gesture started in the diff), and the matching `copy` event — which does
// *not* travel through the viewport — is then hijacked to write the fully serialized
// diff so every line reaches the clipboard.
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const viewport = patchViewportRef.current;
const isWithinDiffViewport = viewport ? event.composedPath().includes(viewport) : false;
diffSelectAllArmedRef.current = resolveDiffSelectAllArmed(
diffSelectAllArmedRef.current,
event,
isWithinDiffViewport,
);
};
const handlePointerDown = () => {
// Any fresh pointer interaction ends the select-all gesture.
diffSelectAllArmedRef.current = false;
};
const handleCopy = (event: ClipboardEvent) => {
if (!diffSelectAllArmedRef.current) {
return;
}
// One-shot: the next deliberate select-all must re-arm it.
diffSelectAllArmedRef.current = false;
if (!diffCopyText || !event.clipboardData) {
return;
}
event.preventDefault();
event.clipboardData.setData("text/plain", diffCopyText);
};
document.addEventListener("keydown", handleKeyDown, true);
document.addEventListener("pointerdown", handlePointerDown, true);
document.addEventListener("copy", handleCopy, true);
return () => {
document.removeEventListener("keydown", handleKeyDown, true);
document.removeEventListener("pointerdown", handlePointerDown, true);
document.removeEventListener("copy", handleCopy, true);
};
}, [diffCopyText]);
const selectTurn = (turnId: TurnId) => {
if (!activeThread) return;
if (onUpdatePanelState) {
onUpdatePanelState({
panel: "diff",
diffTurnId: turnId,
diffFilePath: null,
});
return;
}
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, panel: "diff", diff: "1", diffTurnId: turnId };
},
});
};
const selectWholeConversation = () => {
if (!activeThread) return;
if (onUpdatePanelState) {
onUpdatePanelState({
panel: "diff",
diffTurnId: null,
diffFilePath: null,
});
return;
}
void navigate({
to: "/$threadId",
params: { threadId: activeThread.id },
search: (previous) => {
const rest = stripDiffSearchParams(previous);
return { ...rest, panel: "diff", diff: "1" };
},
});
};
const updateTurnStripScrollState = useCallback(() => {
const element = turnStripRef.current;
if (!element) {
setCanScrollTurnStripLeft(false);
setCanScrollTurnStripRight(false);
return;
}
const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
setCanScrollTurnStripLeft(element.scrollLeft > 4);
setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
}, []);
const scrollTurnStripBy = useCallback((offset: number) => {
const element = turnStripRef.current;
if (!element) return;
element.scrollBy({ left: offset, behavior: "smooth" });
}, []);
const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
const element = turnStripRef.current;
if (!element) return;
if (element.scrollWidth <= element.clientWidth + 1) return;
if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
event.preventDefault();
element.scrollBy({ left: event.deltaY, behavior: "auto" });
}, []);
useEffect(() => {
const element = turnStripRef.current;
if (!element) return;
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
const onScroll = () => updateTurnStripScrollState();
element.addEventListener("scroll", onScroll, { passive: true });
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
resizeObserver.observe(element);
return () => {
window.cancelAnimationFrame(frameId);
element.removeEventListener("scroll", onScroll);
resizeObserver.disconnect();
};
}, [updateTurnStripScrollState]);
useEffect(() => {
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
return () => {
window.cancelAnimationFrame(frameId);
};
}, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
useEffect(() => {
const element = turnStripRef.current;
if (!element) return;
const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
}, [selectedTurn?.turnId, selectedTurnId]);
const headerRow = (
<>
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
{canScrollTurnStripLeft && (
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-linear-to-r from-card to-transparent" />
)}
{canScrollTurnStripRight && (
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-linear-to-l from-card to-transparent" />
)}
<button
type="button"
className={cn(
"absolute left-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
canScrollTurnStripLeft
? "border-border/70 hover:border-border hover:text-foreground"
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
)}
onClick={() => scrollTurnStripBy(-180)}
disabled={!canScrollTurnStripLeft}
aria-label="Scroll turn list left"
>
<ChevronLeftIcon className="size-3.5" />
</button>
<button
type="button"
className={cn(
"absolute right-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
canScrollTurnStripRight
? "border-border/70 hover:border-border hover:text-foreground"
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
)}
onClick={() => scrollTurnStripBy(180)}
disabled={!canScrollTurnStripRight}
aria-label="Scroll turn list right"
>
<ChevronRightIcon className="size-3.5" />
</button>
<div
ref={turnStripRef}
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
onWheel={onTurnStripWheel}
>
<button
type="button"
className="shrink-0 rounded-md"
onClick={selectWholeConversation}
data-turn-chip-selected={selectedTurnId === null}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
selectedTurnId === null
? "border-[color:var(--color-border)] bg-[var(--color-text-foreground)] text-[var(--color-background-surface)]"
: "border-[color:var(--color-border-light)] bg-transparent text-[var(--color-text-foreground-secondary)] hover:border-[color:var(--color-border)] hover:bg-[var(--sidebar-accent)] hover:text-[var(--color-text-foreground)]",
)}
>
<div className="text-[10px] leading-tight font-medium">All turns</div>
</div>
</button>
{orderedTurnDiffSummaries.map((summary) => (
<button
key={summary.turnId}
type="button"
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
title={summary.turnId}
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
summary.turnId === selectedTurn?.turnId
? "border-[color:var(--color-border)] bg-[var(--color-text-foreground)] text-[var(--color-background-surface)]"
: "border-[color:var(--color-border-light)] bg-transparent text-[var(--color-text-foreground-secondary)] hover:border-[color:var(--color-border)] hover:bg-[var(--sidebar-accent)] hover:text-[var(--color-text-foreground)]",
)}
>
<div className="flex items-center gap-1">
<span className="text-[10px] leading-tight font-medium">
Turn{" "}
{summary.checkpointTurnCount ??
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
"?"}
</span>
<span className="text-[9px] leading-tight opacity-70">
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
</span>
</div>
</div>
</button>
))}
</div>
</div>
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
{!isSidebarMode ? (
<>
<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>
</>
) : null}
{onClosePanel ? (
<button
type="button"
className="inline-flex size-7 shrink-0 items-center justify-center rounded-md border border-transparent text-[var(--color-text-foreground)] transition-colors hover:bg-[var(--sidebar-accent)] [-webkit-app-region:no-drag]"
onClick={(event) => {
event.stopPropagation();
onClosePanel();
}}
>
<XIcon className="size-3.5" />
<span className="sr-only">Close file view</span>
</button>
) : null}
</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 turn diffs.
</div>
) : !isGitRepo ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
Turn diffs are unavailable because this project is not a git repository.
</div>
) : diffEnvironmentPending ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
This chat environment is still being prepared. Diff and summary will be available once the
worktree is ready.
</div>
) : (
<>
<div className="border-b border-border/70 px-3">
<div className="flex items-end gap-1">
<button
type="button"
className={cn(
"relative -mb-px inline-flex h-10 items-center gap-1.5 border-b-2 px-2.5 text-[13px] font-medium tracking-[-0.01em] transition-colors",
surfaceMode === "summary"
? "border-foreground text-foreground"
: "border-transparent text-muted-foreground hover:text-foreground",
!canShowSummary && "cursor-not-allowed opacity-45 hover:text-muted-foreground",
)}
disabled={!canShowSummary}
onClick={() => {
setSurfaceMode("summary");
}}
aria-pressed={surfaceMode === "summary"}
>
<LuWrapText className="size-3.5 opacity-80" />
<span>Summary</span>
</button>
<button
type="button"
className={cn(
"relative -mb-px inline-flex h-10 items-center gap-1.5 border-b-2 px-2.5 text-[13px] font-medium tracking-[-0.01em] transition-colors",
surfaceMode === "review"
? "border-foreground text-foreground"
: "border-transparent text-muted-foreground hover:text-foreground",
)}
onClick={() => {
setSurfaceMode("review");
}}
aria-pressed={surfaceMode === "review"}
>
<span className="inline-flex size-4 items-center justify-center rounded-[4px]">
<FaPlusMinus className="size-2.25 text-[var(--color-text-foreground)]" />
</span>
<span>Review</span>
</button>
<Menu>
<MenuTrigger
render={
<button
type="button"
className={cn(
"relative -mb-px inline-flex h-10 items-center gap-1.5 border-b-2 px-2.5 text-[13px] font-medium tracking-[-0.01em] transition-colors",
surfaceMode === "total"
? "border-foreground text-foreground"
: "border-transparent text-muted-foreground hover:text-foreground",
!canShowTotal &&
"cursor-not-allowed opacity-45 hover:text-muted-foreground",
)}
disabled={!canShowTotal}
onClick={() => {
setSurfaceMode("total");
}}
aria-pressed={surfaceMode === "total"}
aria-label="Choose repo diff source"
/>
}
>
<DiffIcon className="size-3.5 opacity-80" />
<span>{REPO_DIFF_SCOPE_LABELS[repoDiffScope]}</span>
{totalPatchStat && hasNonZeroStat(totalPatchStat) ? (
<span className="ml-0.5 inline-flex items-center font-mono text-[11px] font-medium">
<DiffStatLabel
additions={totalPatchStat.additions}
deletions={totalPatchStat.deletions}
/>
</span>
) : null}
<ChevronDownIcon className="size-3 opacity-70" />
</MenuTrigger>
<MenuPopup align="start">
<MenuRadioGroup
value={repoDiffScope}
onValueChange={(value) => {
if (isRepoDiffScope(value)) {
setRepoDiffScope(value);
setSurfaceMode("total");
}
}}
>
<MenuRadioItem value="branch">Branch</MenuRadioItem>
<MenuRadioItem value="workingTree">Working tree</MenuRadioItem>
<MenuRadioItem value="unstaged">Unstaged</MenuRadioItem>
<MenuRadioItem value="staged">Staged</MenuRadioItem>
</MenuRadioGroup>
</MenuPopup>
</Menu>
{surfaceMode !== "summary" && diffCopyText ? (
<Button
variant="ghost"
size="xs"
className="ml-auto shrink-0 gap-1.5 self-center"
onClick={() => {
copyDiffToClipboard(diffCopyText, undefined);
}}
aria-label={isDiffCopied ? "Copied full diff" : "Copy full diff"}
title={isDiffCopied ? "Copied full diff" : "Copy full diff"}
>
{isDiffCopied ? (
<CheckIcon className="size-3 text-success" />
) : (
<CopyIcon className="size-3" />
)}
<span>{isDiffCopied ? "Copied" : "Copy"}</span>
</Button>
) : null}
</div>
</div>
{surfaceMode === "summary" ? (
<div className="min-h-0 flex-1 overflow-auto px-4 py-4">
<div className="mb-4 flex items-center justify-between gap-3 border-b border-border/60 pb-3">
<div className="min-w-0">
<p className="text-sm font-medium text-foreground">Repo summary</p>
<p className="text-[11px] text-muted-foreground">
Generated from the current {REPO_DIFF_SCOPE_LABELS[repoDiffScope].toLowerCase()}{" "}
diff.
</p>
</div>
{diffSummaryText ? (
<Button
variant="ghost"
size="xs"
className="shrink-0 gap-1.5"
onClick={() => {