Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import type { FileDiffContentsLoader } from "@pierre/diffs";
3import { useParams } from "@tanstack/react-router";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
9import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
10import {
11 ArrowRightIcon,
12 CheckIcon,
13 ChevronDownIcon,
14 ChevronRightIcon,
15 ChevronsDownUpIcon,
16 ChevronsUpDownIcon,
17 Columns2Icon,
18 PilcrowIcon,
19 RefreshCwIcon,
20 Rows3Icon,
21 SearchIcon,
22 TextWrapIcon,
23} from "lucide-react";
24import { useCallback, useEffect, useMemo, useRef, useState } from "react";
25import { useOpenInPreferredEditor } from "../editorPreferences";
26import { type DraftId } from "../composerDraftStore";
27import { openDiffFilePrimaryAction } from "../diffFileActions";
28import { useCheckpointDiff } from "~/lib/checkpointDiffState";
29import { cn } from "~/lib/utils";
30import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../diffPanelStore";
31import { useTheme } from "../hooks/useTheme";
32import {
33 buildFileDiffRenderKey,
34 getDiffCollapseIconClassName,
35 getDiffLineStat,
36 getRenderablePatch,
37 resolveDiffThemeName,
38 resolveFileDiffPath,
39 DIFF_SURFACE_THEME_UNSAFE_CSS,
40} from "../lib/diffRendering";
41import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
42import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
43import { useProject, useThread } from "../state/entities";
44import { resolveThreadRouteRef } from "../threadRoutes";
45import { useClientSettings } from "../hooks/useSettings";
46import { formatShortTimestamp } from "../timestampFormat";
47import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
48import { DiffStatLabel } from "./chat/DiffStatLabel";
49import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
50import { Button } from "./ui/button";
51import { ToggleGroup, Toggle } from "./ui/toggle-group";
52import { Switch } from "./ui/switch";
53import {
54 Combobox,
55 ComboboxEmpty,
56 ComboboxInput,
57 ComboboxItem,
58 ComboboxList,
59 ComboboxPopup,
60 ComboboxTrigger,
61} from "./ui/combobox";
62import {
63 DropdownMenu,
64 DropdownMenuContent,
65 DropdownMenuItem,
66 DropdownMenuSub,
67 DropdownMenuSubContent,
68 DropdownMenuSubTrigger,
69 DropdownMenuTrigger,
70} from "./ui/menu";
71import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
72import { useEnvironmentQuery } from "../state/query";
73import { useAtomCommand } from "../state/use-atom-command";
74import { serverEnvironment } from "../state/server";
75import { reviewEnvironment } from "../state/review";
76import { vcsEnvironment } from "../state/vcs";
77import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
78
79type DiffRenderMode = "stacked" | "split";
80type DiffThemeType = "light" | "dark";
81const AUTOMATIC_BASE_REF = "__automatic_base_ref__";
82
83interface CollapsedDiffFilesState {
84 readonly scopeKey: string | null;
85 readonly fileKeys: ReadonlySet<string>;
86}
87
88const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
89
90const DIFF_PANEL_UNSAFE_CSS = `${DIFF_SURFACE_THEME_UNSAFE_CSS}
91:is(
92 [data-line],
93 [data-line-annotation],
94 [data-merge-conflict],
95 [data-merge-conflict-actions],
96 [data-no-newline]
97)[data-selected-line] {
98 --diffs-line-bg: light-dark(
99 color-mix(
100 in lab,
101 var(--code-background) 88%,
102 color-mix(in srgb, var(--code-background) 50%, var(--diffs-modified-base))
103 ),
104 color-mix(
105 in lab,
106 var(--code-background) 80%,
107 color-mix(in srgb, var(--code-background) 70%, var(--diffs-modified-base))
108 )
109 ) !important;
110}
111
112:is([data-gutter-buffer], [data-column-number])[data-selected-line] {
113 --diffs-line-bg: light-dark(
114 color-mix(
115 in lab,
116 var(--code-background) 91%,
117 color-mix(in srgb, var(--code-background) 35%, var(--diffs-modified-base))
118 ),
119 color-mix(
120 in lab,
121 var(--code-background) 85%,
122 color-mix(in srgb, var(--code-background) 60%, var(--diffs-modified-base))
123 )
124 ) !important;
125}
126
127[data-indicators="bars"]
128 :is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line] {
129 position: relative;
130}
131
132[data-indicators="bars"]
133 :is([data-column-number], [data-gutter-buffer="annotation"])[data-selected-line]::before {
134 position: absolute !important;
135 inset-block: 0 !important;
136 inset-inline-start: 0 !important;
137 display: block !important;
138 width: 4px !important;
139 min-width: 4px !important;
140 max-width: 4px !important;
141 height: auto !important;
142 padding: 0 !important;
143 content: "" !important;
144 background-color: var(--diffs-modified-base) !important;
145 background-image: none !important;
146}
147
148[data-file-info] {
149 background-color: var(--code-background) !important;
150 border-block-color: transparent !important;
151 color: var(--code-foreground) !important;
152}
153
154[data-diffs-header] {
155 position: sticky !important;
156 top: 0;
157 z-index: 4;
158 background-color: var(--code-background) !important;
159 border-bottom-color: transparent !important;
160 align-items: center !important;
161 font-family: var(--font-sans) !important;
162 font-size: 12px !important;
163 line-height: 1 !important;
164 min-height: 32px !important;
165 padding-block: 6px !important;
166 padding-inline: 8px 12px !important;
167}
168
169[data-diffs-header]:hover {
170 background-color: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground)) !important;
171}
172
173:is([data-separator="line-info"], [data-separator="line-info-basic"]) {
174 height: 24px !important;
175 margin-block: 0 !important;
176 background-color: var(--code-background) !important;
177}
178
179:is([data-separator="line-info"], [data-separator="line-info-basic"])
180 [data-separator-wrapper] {
181 padding-inline: 8px 12px !important;
182 background-color: transparent !important;
183}
184
185:is([data-separator="line-info"], [data-separator="line-info-basic"])
186 [data-separator-content] {
187 gap: 8px;
188 padding-inline: 0 !important;
189 background-color: transparent !important;
190 color: color-mix(in srgb, var(--code-foreground) 52%, var(--code-background)) !important;
191 font-family: var(--font-sans) !important;
192 font-size: 11px !important;
193 text-decoration: none !important;
194}
195
196:is([data-separator="line-info"], [data-separator="line-info-basic"])
197 [data-unmodified-lines] {
198 display: flex !important;
199 min-width: 0;
200 flex: 1 1 auto;
201 align-items: center;
202 gap: 8px;
203 cursor: pointer;
204}
205
206:is([data-separator="line-info"], [data-separator="line-info-basic"])
207 [data-unmodified-lines]::before,
208:is([data-separator="line-info"], [data-separator="line-info-basic"])
209 [data-unmodified-lines]::after {
210 width: auto;
211 height: 1px;
212 flex: 1 1 auto;
213 content: "";
214 background-color: color-mix(in srgb, var(--code-background) 92%, var(--code-foreground));
215}
216
217:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
218 [data-separator-wrapper] {
219 grid-template-columns: 0 minmax(0, 1fr) !important;
220}
221
222:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
223 [data-separator-content] {
224 grid-column: 2 !important;
225}
226
227:is([data-separator="line-info"], [data-separator="line-info-basic"])
228 [data-expand-button] {
229 display: none !important;
230}
231
232:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
233 [data-expand-button]
234 )
235 [data-separator-content] {
236 cursor: pointer;
237}
238
239:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
240 [data-expand-button]
241 ):hover
242 [data-separator-content] {
243 color: color-mix(in srgb, var(--code-foreground) 76%, var(--code-background)) !important;
244}
245
246:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
247 [data-expand-button]
248 ):hover
249 [data-unmodified-lines]::before,
250:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
251 [data-expand-button]
252 ):hover
253 [data-unmodified-lines]::after {
254 background-color: color-mix(in srgb, var(--code-background) 84%, var(--code-foreground));
255}
256
257[data-diffs-header] [data-header-content] {
258 align-items: center !important;
259 line-height: 1 !important;
260}
261
262[data-diffs-header] [data-metadata] {
263 align-items: center !important;
264 line-height: 1 !important;
265 font-variant-numeric: tabular-nums;
266}
267
268[data-diffs-header] [data-additions-count],
269[data-diffs-header] [data-deletions-count] {
270 font-family: var(--font-mono) !important;
271 font-size: 11px !important;
272 font-variant-numeric: tabular-nums;
273 line-height: 1 !important;
274}
275
276[data-diffs-header] [data-change-icon],
277[data-diffs-header] [data-rename-icon] {
278 display: block;
279 flex-shrink: 0;
280}
281
282[data-title] {
283 cursor: pointer;
284 transition:
285 color 120ms ease,
286 text-decoration-color 120ms ease;
287 text-decoration: underline;
288 text-decoration-color: transparent;
289 text-underline-offset: 2px;
290 font-family: var(--font-sans) !important;
291}
292
293[data-title]:hover {
294 color: color-mix(in srgb, var(--code-foreground) 84%, var(--primary)) !important;
295 text-decoration-color: currentColor;
296}
297`;
298
299interface DiffPanelProps {
300 mode?: DiffPanelMode;
301 composerDraftTarget: ScopedThreadRef | DraftId;
302 initialGitScope: "branch" | "unstaged";
303}
304
305export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
306
307export default function DiffPanel({
308 mode = "inline",
309 composerDraftTarget,
310 initialGitScope: initialGitScopeProp,
311}: DiffPanelProps) {
312 const { resolvedTheme } = useTheme();
313 const settings = useClientSettings();
314 const [initialGitScope] = useState(initialGitScopeProp);
315 const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
316 const [wordWrap, setWordWrap] = useState(settings.wordWrap);
317 const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
318 const [baseRefQuery, setBaseRefQuery] = useState("");
319 const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
320 scopeKey: null,
321 fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS,
322 }));
323 const [codeViewRevision, setCodeViewRevision] = useState(0);
324 const codeViewRef = useRef<AnnotatableCodeViewHandle>(null);
325 const lastCompletedTurnRefreshRef = useRef<{
326 readonly threadKey: string | null;
327 readonly turnId: TurnId | null;
328 } | null>(null);
329
330 const routeThreadRef = useParams({
331 strict: false,
332 select: (params) => resolveThreadRouteRef(params),
333 });
334 const activeThreadId = routeThreadRef?.threadId ?? null;
335 const activeThread = useThread(routeThreadRef);
336 const activeProjectId = activeThread?.projectId ?? null;
337 const activeProject = useProject(
338 activeThread && activeProjectId
339 ? {
340 environmentId: activeThread.environmentId,
341 projectId: activeProjectId,
342 }
343 : null,
344 );
345 const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot;
346 const serverConfig = useAtomValue(
347 serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),
348 );
349 const openInPreferredEditor = useOpenInPreferredEditor(
350 activeThread?.environmentId ?? null,
351 serverConfig?.availableEditors ?? [],
352 );
353 const getDiffFileContents = useAtomCommand(reviewEnvironment.diffFileContents);
354 const gitStatusQuery = useEnvironmentQuery(
355 activeThread !== null && activeThread !== undefined && activeCwd != null
356 ? vcsEnvironment.status({
357 environmentId: activeThread.environmentId,
358 input: { cwd: activeCwd },
359 })
360 : null,
361 );
362 const diffSelection = useDiffPanelStore((state) =>
363 selectThreadDiffPanelSelection(
364 state.byThreadKey,
365 routeThreadRef,
366 initialGitScope === "unstaged",
367 ),
368 );
369 const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
370 const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
371 useTurnDiffSummaries(activeThread);
372 const orderedTurnDiffSummaries = useMemo(
373 () =>
374 [...turnDiffSummaries].toSorted((left, right) => {
375 const leftTurnCount =
376 left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
377 const rightTurnCount =
378 right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
379 if (leftTurnCount !== rightTurnCount) {
380 return rightTurnCount - leftTurnCount;
381 }
382 return right.completedAt.localeCompare(left.completedAt);
383 }),
384 [inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
385 );
386
387 useEffect(() => {
388 if (!routeThreadRef || diffSelection.kind !== "turn") return;
389 useDiffPanelStore.getState().reconcileTurnSelection(
390 routeThreadRef,
391 orderedTurnDiffSummaries.map((summary) => summary.turnId),
392 );
393 }, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
394
395 const selectedTurnId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
396 const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch";
397 const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null;
398 const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
399 const selectedFileRevealRequestId =
400 diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
401 const selectedTurn =
402 selectedTurnId === null
403 ? undefined
404 : (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
405 orderedTurnDiffSummaries[0]);
406 const selectedCheckpointTurnCount =
407 selectedTurn &&
408 (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
409 const latestTurn = orderedTurnDiffSummaries[0];
410 const selectedScopeLabel =
411 selectedTurnId === null
412 ? selectedGitScope === "unstaged"
413 ? "Working tree"
414 : "Branch changes"
415 : selectedTurn?.turnId === latestTurn?.turnId
416 ? "Latest turn"
417 : `Turn ${selectedCheckpointTurnCount ?? "?"}`;
418 const reviewSectionId = selectedTurn ? `turn:${selectedTurn.turnId}` : selectedGitScope;
419 const collapseScopeKey = routeThreadRef
420 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
421 : null;
422 const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
423 const collapsedDiffFileKeys =
424 collapsedDiffFiles.scopeKey === collapseScopeKey
425 ? collapsedDiffFiles.fileKeys
426 : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
427 const reviewSectionTitle = selectedTurn
428 ? `Turn ${selectedCheckpointTurnCount ?? "?"}`
429 : selectedGitScope === "unstaged"
430 ? "Working tree"
431 : "Branch changes";
432 const selectedCheckpointRange = useMemo(
433 () =>
434 typeof selectedCheckpointTurnCount === "number"
435 ? {
436 fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
437 toTurnCount: selectedCheckpointTurnCount,
438 }
439 : null,
440 [selectedCheckpointTurnCount],
441 );
442 const activeCheckpointDiff = useCheckpointDiff(
443 {
444 environmentId: activeThread?.environmentId ?? null,
445 threadId: activeThreadId,
446 fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
447 toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
448 ignoreWhitespace: diffIgnoreWhitespace,
449 cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null,
450 },
451 { enabled: isGitRepo && selectedTurn !== undefined },
452 );
453 const primaryBranchDiffPreview = useEnvironmentQuery(
454 selectedTurnId === null && activeThread && activeCwd
455 ? reviewEnvironment.diffPreview({
456 environmentId: activeThread.environmentId,
457 input: {
458 cwd: activeCwd,
459 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
460 ignoreWhitespace: diffIgnoreWhitespace,
461 },
462 })
463 : null,
464 );
465 const shouldRetryBranchDiffAtEnvironmentCwd =
466 selectedTurnId === null &&
467 primaryBranchDiffPreview.error?.includes("configured workspace root") === true &&
468 serverConfig?.cwd !== undefined &&
469 serverConfig.cwd !== activeCwd;
470 const fallbackBranchDiffPreview = useEnvironmentQuery(
471 shouldRetryBranchDiffAtEnvironmentCwd && activeThread && serverConfig
472 ? reviewEnvironment.diffPreview({
473 environmentId: activeThread.environmentId,
474 input: {
475 cwd: serverConfig.cwd,
476 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
477 ignoreWhitespace: diffIgnoreWhitespace,
478 },
479 })
480 : null,
481 );
482 const branchDiffPreview = shouldRetryBranchDiffAtEnvironmentCwd
483 ? fallbackBranchDiffPreview
484 : primaryBranchDiffPreview;
485 const refreshBranchDiffPreview = branchDiffPreview.refresh;
486 const canRefreshGitDiff =
487 isGitRepo && selectedTurnId === null && activeThread != null && activeCwd != null;
488 const activeThreadRefreshKey = routeThreadRef
489 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
490 : null;
491
492 useEffect(() => {
493 if (!canRefreshGitDiff) return;
494 const refreshOnFocus = () => refreshBranchDiffPreview();
495 window.addEventListener("focus", refreshOnFocus);
496 return () => window.removeEventListener("focus", refreshOnFocus);
497 }, [canRefreshGitDiff, refreshBranchDiffPreview]);
498
499 useEffect(() => {
500 const current = {
501 threadKey: activeThreadRefreshKey,
502 turnId: latestTurn?.turnId ?? null,
503 };
504 const previous = lastCompletedTurnRefreshRef.current;
505 if (!canRefreshGitDiff) {
506 return;
507 }
508 if (previous === null || previous.threadKey !== current.threadKey) {
509 lastCompletedTurnRefreshRef.current = current;
510 return;
511 }
512 if (previous.turnId === current.turnId) return;
513 refreshBranchDiffPreview();
514 lastCompletedTurnRefreshRef.current = current;
515 }, [activeThreadRefreshKey, canRefreshGitDiff, latestTurn?.turnId, refreshBranchDiffPreview]);
516
517 const selectedGitSource = branchDiffPreview.data?.sources.find(
518 (source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
519 );
520 const loadDiffFiles = useMemo<FileDiffContentsLoader | undefined>(() => {
521 const preview = branchDiffPreview.data;
522 if (selectedTurnId !== null || !activeThread || !preview || !selectedGitSource) {
523 return undefined;
524 }
525
526 const source = selectedGitSource;
527 return async (fileDiff) => {
528 const newPath = resolveFileDiffPath(fileDiff);
529 const oldPath = fileDiff.prevName
530 ? resolveFileDiffPath({ ...fileDiff, name: fileDiff.prevName })
531 : newPath;
532 const result = await getDiffFileContents({
533 environmentId: activeThread.environmentId,
534 input: {
535 cwd: preview.cwd,
536 sourceKind: source.kind,
537 changeType: fileDiff.type,
538 baseRef: source.baseRef,
539 headRef: source.headRef,
540 oldPath,
541 newPath,
542 },
543 });
544 if (result._tag !== "Success") {
545 throw squashAtomCommandFailure(result);
546 }
547
548 const newFile = {
549 name: newPath,
550 contents: result.value.newContents,
551 cacheKey: `${source.diffHash}:new:${newPath}`,
552 };
553 if (fileDiff.type === "rename-pure") {
554 return { oldFile: null, newFile };
555 }
556 return {
557 oldFile: {
558 name: oldPath,
559 contents: result.value.oldContents,
560 cacheKey: `${source.diffHash}:old:${oldPath}`,
561 },
562 newFile,
563 };
564 };
565 }, [
566 activeThread,
567 branchDiffPreview.data,
568 getDiffFileContents,
569 selectedGitSource,
570 selectedTurnId,
571 ]);
572 const localBranchRefs = useEnvironmentQuery(
573 selectedTurnId === null &&
574 selectedGitScope === "branch" &&
575 activeThread &&
576 branchDiffPreview.data?.cwd
577 ? vcsEnvironment.listRefs({
578 environmentId: activeThread.environmentId,
579 input: {
580 cwd: branchDiffPreview.data.cwd,
581 includeMatchingRemoteRefs: true,
582 refKind: "local",
583 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
584 limit: 100,
585 },
586 })
587 : null,
588 );
589 const remoteBranchRefs = useEnvironmentQuery(
590 selectedTurnId === null &&
591 selectedGitScope === "branch" &&
592 activeThread &&
593 branchDiffPreview.data?.cwd
594 ? vcsEnvironment.listRefs({
595 environmentId: activeThread.environmentId,
596 input: {
597 cwd: branchDiffPreview.data.cwd,
598 includeMatchingRemoteRefs: true,
599 refKind: "remote",
600 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
601 limit: 100,
602 },
603 })
604 : null,
605 );
606 const baseRefChoices = buildBaseRefChoices(
607 localBranchRefs.data?.refs.filter((ref) => ref.name !== selectedGitSource?.headRef) ?? [],
608 remoteBranchRefs.data?.refs ?? [],
609 );
610 const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery);
611 const valueForBaseRefChoice = (choice: (typeof baseRefChoices)[number]) =>
612 selectedBaseRef && selectedBaseRef === choice.remote?.name
613 ? selectedBaseRef
614 : (choice.local?.name ?? choice.remote?.name ?? choice.id);
615 const baseRefItems = [AUTOMATIC_BASE_REF, ...baseRefChoices.map(valueForBaseRefChoice)];
616 const filteredBaseRefItems = [
617 ...(baseRefQuery.trim().length === 0 ? [AUTOMATIC_BASE_REF] : []),
618 ...matchingBaseRefChoices.map(valueForBaseRefChoice),
619 ];
620 const gitDiff = selectedGitSource?.diff;
621
622 const selectedPatch = selectedTurn ? activeCheckpointDiff.data?.diff : gitDiff;
623 const isSelectedPatchTruncated = !selectedTurn && selectedGitSource?.truncated === true;
624 const isLoadingSelectedPatch = selectedTurn
625 ? activeCheckpointDiff.isPending
626 : branchDiffPreview.isPending;
627 const selectedPatchError = selectedTurn ? activeCheckpointDiff.error : branchDiffPreview.error;
628 const hasResolvedPatch = typeof selectedPatch === "string";
629 const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
630 const renderablePatch = useMemo(
631 () =>
632 getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, {
633 compactPartialHunkOffsets: selectedTurnId === null,
634 }),
635 [resolvedTheme, selectedPatch, selectedTurnId],
636 );
637 const renderableFiles = useMemo(() => {
638 if (!renderablePatch || renderablePatch.kind !== "files") {
639 return [];
640 }
641 return renderablePatch.files.toSorted((left, right) =>
642 resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
643 numeric: true,
644 sensitivity: "base",
645 }),
646 );
647 }, [renderablePatch]);
648 const renderableFileEntries = useMemo(
649 () =>
650 renderableFiles.map((fileDiff) => ({
651 fileDiff,
652 fileKey: buildFileDiffRenderKey(fileDiff),
653 })),
654 [renderableFiles],
655 );
656 const codeViewFiles = useMemo(
657 () =>
658 renderableFileEntries.map(({ fileDiff, fileKey }) => {
659 return {
660 fileDiff,
661 filePath: resolveFileDiffPath(fileDiff),
662 fileKey,
663 collapsed: collapsedDiffFileKeys.has(fileKey),
664 };
665 }),
666 [collapsedDiffFileKeys, renderableFileEntries],
667 );
668 const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
669 const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
670 const diffLineStat = useMemo(() => getDiffLineStat(renderableFiles), [renderableFiles]);
671 const selectedDiffFileKey = selectedFilePath
672 ? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null)
673 : null;
674
675 useEffect(() => {
676 if (!selectedDiffFileKey) return;
677 codeViewRef.current?.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
678 }, [codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
679
680 const openDiffFile = useCallback(
681 (filePath: string) => {
682 openDiffFilePrimaryAction({
683 threadRef: routeThreadRef,
684 filePath,
685 activeCwd,
686 openInEditor: (targetPath) => {
687 void (async () => {
688 const result = await openInPreferredEditor(targetPath);
689 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
690 console.warn("Failed to open diff file in editor.", {
691 operation: "open-diff-file",
692 ...(routeThreadRef
693 ? {
694 environmentId: routeThreadRef.environmentId,
695 threadId: routeThreadRef.threadId,
696 }
697 : {}),
698 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
699 });
700 }
701 })();
702 },
703 });
704 },
705 [activeCwd, openInPreferredEditor, routeThreadRef],
706 );
707 const toggleDiffFileCollapsed = useCallback(
708 (fileKey: string) => {
709 setCollapsedDiffFiles((current) => {
710 const next = new Set(current.scopeKey === collapseScopeKey ? current.fileKeys : []);
711 if (next.has(fileKey)) {
712 next.delete(fileKey);
713 } else {
714 next.add(fileKey);
715 }
716 return { scopeKey: collapseScopeKey, fileKeys: next };
717 });
718 },
719 [collapseScopeKey],
720 );
721
722 const toggleDiffFileCollapse = useCallback(() => {
723 setCodeViewRevision((current) => current + 1);
724 setCollapsedDiffFiles((current) => {
725 const currentKeys =
726 current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
727
728 return {
729 scopeKey: collapseScopeKey,
730 fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
731 };
732 });
733 }, [collapseScopeKey, diffFileKeys]);
734
735 const selectTurn = (turnId: TurnId) => {
736 if (!routeThreadRef) return;
737 useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
738 };
739 const selectGitScope = (scope: "branch" | "unstaged") => {
740 if (!routeThreadRef) return;
741 useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
742 };
743 const selectBranchBaseRef = (baseRef: string | null) => {
744 if (!routeThreadRef) return;
745 useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
746 };
747
748 const headerRow = (
749 <>
750 <div className="flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
751 <DropdownMenu>
752 <DropdownMenuTrigger
753 className="inline-flex h-6 max-w-full items-center gap-1 rounded-md bg-accent px-2 text-xs font-medium text-accent-foreground outline-none transition-colors hover:bg-accent/80 focus-visible:ring-2 focus-visible:ring-ring"
754 aria-label={`Diff scope: ${selectedScopeLabel}`}
755 >
756 <span className="truncate">{selectedScopeLabel}</span>
757 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
758 </DropdownMenuTrigger>
759 <DropdownMenuContent align="start" className="w-60">
760 <DropdownMenuItem
761 className={
762 selectedTurnId === null && selectedGitScope === "unstaged"
763 ? "bg-foreground/[0.08]"
764 : undefined
765 }
766 onClick={() => selectGitScope("unstaged")}
767 >
768 <span>Working tree</span>
769 </DropdownMenuItem>
770 <DropdownMenuItem
771 className={
772 selectedTurnId === null && selectedGitScope === "branch"
773 ? "bg-foreground/[0.08]"
774 : undefined
775 }
776 onClick={() => selectGitScope("branch")}
777 >
778 <span>Branch changes</span>
779 </DropdownMenuItem>
780 <DropdownMenuItem
781 className={
782 selectedTurnId !== null && selectedTurn?.turnId === latestTurn?.turnId
783 ? "bg-foreground/[0.08]"
784 : undefined
785 }
786 onClick={() => {
787 if (latestTurn) selectTurn(latestTurn.turnId);
788 }}
789 >
790 <span>Latest turn</span>
791 </DropdownMenuItem>
792 <DropdownMenuSub>
793 <DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
794 <DropdownMenuSubContent className="w-64">
795 {orderedTurnDiffSummaries.map((summary) => {
796 const turnCount =
797 summary.checkpointTurnCount ??
798 inferredCheckpointTurnCountByTurnId[summary.turnId] ??
799 "?";
800 return (
801 <DropdownMenuItem
802 key={summary.turnId}
803 className={
804 summary.turnId === selectedTurn?.turnId ? "bg-foreground/[0.08]" : undefined
805 }
806 onClick={() => selectTurn(summary.turnId)}
807 >
808 <span>Turn {turnCount}</span>
809 <span className="ml-auto text-xs tabular-nums text-muted-foreground">
810 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
811 </span>
812 </DropdownMenuItem>
813 );
814 })}
815 </DropdownMenuSubContent>
816 </DropdownMenuSub>
817 </DropdownMenuContent>
818 </DropdownMenu>
819 {selectedTurnId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
820 <div
821 className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
822 title={`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
823 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
824 >
825 <span className="min-w-0 max-w-48 truncate">{selectedGitSource.headRef ?? "HEAD"}</span>
826 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
827 <Combobox
828 items={baseRefItems}
829 filteredItems={filteredBaseRefItems}
830 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
831 onOpenChange={(open) => {
832 if (!open) setBaseRefQuery("");
833 }}
834 onValueChange={(value) => {
835 if (!value) return;
836 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
837 }}
838 >
839 <ComboboxTrigger
840 className="inline-flex min-w-0 max-w-48 items-center gap-1 overflow-hidden rounded-md px-1.5 py-1 outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
841 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
842 >
843 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
844 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
845 </ComboboxTrigger>
846 <ComboboxPopup
847 align="start"
848 className="w-72 min-w-0 max-w-[calc(100vw-1rem)] overflow-hidden [&>[data-slot=combobox-popup]]:min-w-0 [&>[data-slot=combobox-popup]]:overflow-hidden"
849 >
850 <div className="min-w-0 shrink-0 px-3 pt-2.5">
851 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
852 <SearchIcon
853 aria-hidden="true"
854 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
855 />
856 <ComboboxInput
857 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
858 inputClassName="rounded-none bg-transparent text-sm"
859 placeholder="Search refs..."
860 showTrigger={false}
861 size="sm"
862 unstyled
863 value={baseRefQuery}
864 onChange={(event) => setBaseRefQuery(event.target.value)}
865 />
866 </div>
867 </div>
868 <div className="grid shrink-0 grid-cols-[1rem_minmax(0,1fr)] items-center gap-2 border-b border-border/70 ps-3 pe-6.5 pt-2 pb-1.5 font-medium text-[10px] text-muted-foreground uppercase tracking-wide">
869 <span aria-hidden="true" />
870 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
871 <span>Branch</span>
872 <span className="text-right">Remote</span>
873 </div>
874 </div>
875 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
876 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
877 <ComboboxItem
878 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
879 contentClassName="w-full min-w-0 overflow-hidden"
880 value={AUTOMATIC_BASE_REF}
881 >
882 <span className="block min-w-0 truncate">Automatic</span>
883 </ComboboxItem>
884 {baseRefChoices.map((choice) => {
885 const item = valueForBaseRefChoice(choice);
886 const hasBoth = choice.local !== null && choice.remote !== null;
887 const useRemote = choice.remote?.name === item;
888 return (
889 <ComboboxItem
890 key={choice.id}
891 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
892 contentClassName="w-full min-w-0 overflow-hidden"
893 value={item}
894 >
895 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden">
896 <span className="block min-w-0 truncate pe-2">{choice.label}</span>
897 {hasBoth ? (
898 <div
899 className="flex justify-end"
900 onClick={(event) => event.stopPropagation()}
901 onPointerDown={(event) => event.stopPropagation()}
902 >
903 <Switch
904 aria-label={`Use remote version of ${choice.label}`}
905 checked={useRemote}
906 className="[--thumb-size:--spacing(3)]"
907 onCheckedChange={(checked) => {
908 const nextRef = checked
909 ? choice.remote?.name
910 : choice.local?.name;
911 if (nextRef) selectBranchBaseRef(nextRef);
912 }}
913 />
914 </div>
915 ) : choice.remote ? (
916 <span
917 className="flex justify-end text-muted-foreground"
918 title="Remote only"
919 >
920 <CheckIcon aria-hidden="true" className="size-3" />
921 </span>
922 ) : null}
923 </div>
924 </ComboboxItem>
925 );
926 })}
927 </ComboboxList>
928 </ComboboxPopup>
929 </Combobox>
930 </div>
931 )}
932 </div>
933 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
934 {codeViewFiles.length > 0 && (
935 <DiffStatLabel
936 additions={diffLineStat.additions}
937 deletions={diffLineStat.deletions}
938 className="mr-1 text-[11px]"
939 layout="inline"
940 />
941 )}
942 {canRefreshGitDiff && (
943 <Tooltip>
944 <TooltipTrigger
945 render={
946 <Button
947 type="button"
948 size="icon-sm"
949 variant="ghost"
950 aria-label={branchDiffPreview.isPending ? "Refreshing diff" : "Refresh diff"}
951 onClick={refreshBranchDiffPreview}
952 />
953 }
954 >
955 <RefreshCwIcon
956 className={cn("size-3.5", branchDiffPreview.isPending && "animate-spin")}
957 />
958 </TooltipTrigger>
959 <TooltipPopup side="top">
960 {branchDiffPreview.isPending ? "Refreshing diff…" : "Refresh diff"}
961 </TooltipPopup>
962 </Tooltip>
963 )}
964 {codeViewFiles.length > 0 && (
965 <Tooltip>
966 <TooltipTrigger
967 render={
968 <Button
969 type="button"
970 size="icon-sm"
971 variant="ghost"
972 aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
973 onClick={toggleDiffFileCollapse}
974 />
975 }
976 >
977 {allDiffFilesCollapsed ? (
978 <ChevronsUpDownIcon className="size-3.5" />
979 ) : (
980 <ChevronsDownUpIcon className="size-3.5" />
981 )}
982 </TooltipTrigger>
983 <TooltipPopup side="top">
984 {allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
985 </TooltipPopup>
986 </Tooltip>
987 )}
988 <ToggleGroup
989 className="shrink-0 gap-1"
990 size="sm"
991 value={[diffRenderMode]}
992 onValueChange={(value) => {
993 const next = value[0];
994 if (next === "stacked" || next === "split") {
995 setDiffRenderMode(next);
996 }
997 }}
998 >
999 <Toggle aria-label="Stacked diff view" value="stacked" variant="ghost">
1000 <Rows3Icon className="size-3.5" />
1001 </Toggle>
1002 <Toggle aria-label="Split diff view" value="split" variant="ghost">
1003 <Columns2Icon className="size-3.5" />
1004 </Toggle>
1005 </ToggleGroup>
1006 <Tooltip>
1007 <TooltipTrigger
1008 render={
1009 <Toggle
1010 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
1011 variant="ghost"
1012 size="sm"
1013 pressed={wordWrap}
1014 onPressedChange={(pressed) => {
1015 setWordWrap(Boolean(pressed));
1016 }}
1017 />
1018 }
1019 >
1020 <TextWrapIcon className="size-3.5" />
1021 </TooltipTrigger>
1022 <TooltipPopup side="top">
1023 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
1024 </TooltipPopup>
1025 </Tooltip>
1026 <Tooltip>
1027 <TooltipTrigger
1028 render={
1029 <Toggle
1030 aria-label={
1031 diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
1032 }
1033 variant="ghost"
1034 size="sm"
1035 pressed={diffIgnoreWhitespace}
1036 onPressedChange={(pressed) => {
1037 setDiffIgnoreWhitespace(Boolean(pressed));
1038 }}
1039 />
1040 }
1041 >
1042 <PilcrowIcon className="size-3.5" />
1043 </TooltipTrigger>
1044 <TooltipPopup side="top">
1045 {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
1046 </TooltipPopup>
1047 </Tooltip>
1048 </div>
1049 </>
1050 );
1051
1052 return (
1053 <DiffPanelShell mode={mode} header={headerRow}>
1054 {!activeThread ? (
1055 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1056 Select a thread to inspect turn diffs.
1057 </div>
1058 ) : !isGitRepo ? (
1059 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1060 Turn diffs are unavailable because this project is not a git repository.
1061 </div>
1062 ) : selectedTurnId !== null && orderedTurnDiffSummaries.length === 0 ? (
1063 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1064 No completed turns yet.
1065 </div>
1066 ) : (
1067 <>
1068 <div className="diff-panel-viewport flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
1069 {isSelectedPatchTruncated && (
1070 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground">
1071 This diff was truncated because it exceeded the preview limit. The changes shown are
1072 incomplete.
1073 </p>
1074 )}
1075 {selectedPatchError && !renderablePatch && (
1076 <div className="px-3">
1077 <p className="mb-2 text-[11px] text-error/80">{selectedPatchError}</p>
1078 </div>
1079 )}
1080 {!renderablePatch ? (
1081 isLoadingSelectedPatch ? (
1082 <DiffPanelLoadingState
1083 label={
1084 selectedTurn
1085 ? "Loading checkpoint diff..."
1086 : selectedGitScope === "unstaged"
1087 ? "Loading working tree diff..."
1088 : "Loading branch diff..."
1089 }
1090 />
1091 ) : (
1092 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
1093 <p>
1094 {hasNoNetChanges
1095 ? "No net changes in this selection."
1096 : "No patch available for this selection."}
1097 </p>
1098 </div>
1099 )
1100 ) : renderablePatch.kind === "files" ? (
1101 <div
1102 className="min-h-0 flex-1"
1103 onClickCapture={(event) => {
1104 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1105 const title = composedPath.find(
1106 (node): node is HTMLElement =>
1107 node instanceof HTMLElement && node.hasAttribute("data-title"),
1108 );
1109 const filePath = title?.textContent?.trim();
1110 if (filePath) openDiffFile(filePath);
1111 }}
1112 >
1113 <AnnotatableCodeView
1114 key={collapseScopeKey ?? reviewSectionId}
1115 viewerRef={codeViewRef}
1116 codeViewKey={codeViewMountKey}
1117 className="diff-render-surface h-full min-h-0 overflow-auto"
1118 files={codeViewFiles}
1119 sectionId={reviewSectionId}
1120 sectionTitle={reviewSectionTitle}
1121 composerDraftTarget={composerDraftTarget}
1122 renderHeaderPrefix={(fileDiff, fileKey, collapsed) => {
1123 const filePath = resolveFileDiffPath(fileDiff);
1124 return (
1125 <Tooltip>
1126 <TooltipTrigger
1127 render={
1128 <button
1129 type="button"
1130 className={cn(
1131 "-ms-0.5 inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
1132 getDiffCollapseIconClassName(fileDiff),
1133 )}
1134 aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
1135 aria-expanded={!collapsed}
1136 onClick={(event) => {
1137 event.stopPropagation();
1138 toggleDiffFileCollapsed(fileKey);
1139 }}
1140 />
1141 }
1142 >
1143 {collapsed ? (
1144 <ChevronRightIcon className="size-4" />
1145 ) : (
1146 <ChevronDownIcon className="size-4" />
1147 )}
1148 </TooltipTrigger>
1149 <TooltipPopup side="top">
1150 {collapsed ? "Expand diff" : "Collapse diff"}
1151 </TooltipPopup>
1152 </Tooltip>
1153 );
1154 }}
1155 options={{
1156 diffStyle: diffRenderMode === "split" ? "split" : "unified",
1157 lineDiffType: "none",
1158 overflow: wordWrap ? "wrap" : "scroll",
1159 theme: resolveDiffThemeName(resolvedTheme),
1160 themeType: resolvedTheme as DiffThemeType,
1161 unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
1162 stickyHeaders: true,
1163 ...(loadDiffFiles ? { loadDiffFiles } : {}),
1164 itemMetrics: {
1165 diffHeaderHeight: 32,
1166 hunkSeparatorHeight: 24,
1167 paddingTop: 0,
1168 paddingBottom: 0,
1169 },
1170 layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
1171 }}
1172 />
1173 </div>
1174 ) : (
1175 <div className="min-h-0 flex-1 overflow-auto p-2">
1176 <div className="space-y-2">
1177 <p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
1178 <pre
1179 className={cn(
1180 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
1181 wordWrap
1182 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
1183 : "overflow-auto",
1184 )}
1185 >
1186 {renderablePatch.text}
1187 </pre>
1188 </div>
1189 </div>
1190 )}
1191 </div>
1192 </>
1193 )}
1194 </DiffPanelShell>
1195 );
1196}