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, RunId } 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, useThreadProjection, useThreadShell } 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 runId: RunId | 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 = useThreadShell(routeThreadRef);
336 const activeThreadProjection = useThreadProjection(routeThreadRef)?.projection ?? null;
337 const activeProjectId = activeThread?.projectId ?? null;
338 const activeProject = useProject(
339 activeThread && activeProjectId
340 ? {
341 environmentId: activeThread.environmentId,
342 projectId: activeProjectId,
343 }
344 : null,
345 );
346 const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot;
347 const serverConfig = useAtomValue(
348 serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),
349 );
350 const openInPreferredEditor = useOpenInPreferredEditor(
351 activeThread?.environmentId ?? null,
352 serverConfig?.availableEditors ?? [],
353 );
354 const getDiffFileContents = useAtomCommand(reviewEnvironment.diffFileContents);
355 const gitStatusQuery = useEnvironmentQuery(
356 activeThread !== null && activeThread !== undefined && activeCwd != null
357 ? vcsEnvironment.status({
358 environmentId: activeThread.environmentId,
359 input: { cwd: activeCwd },
360 })
361 : null,
362 );
363 const diffSelection = useDiffPanelStore((state) =>
364 selectThreadDiffPanelSelection(
365 state.byThreadKey,
366 routeThreadRef,
367 initialGitScope === "unstaged",
368 ),
369 );
370 const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
371 const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } =
372 useTurnDiffSummaries(activeThreadProjection);
373 const orderedTurnDiffSummaries = useMemo(
374 () =>
375 [...turnDiffSummaries].toSorted((left, right) => {
376 const leftTurnCount =
377 left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0;
378 const rightTurnCount =
379 right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0;
380 if (leftTurnCount !== rightTurnCount) {
381 return rightTurnCount - leftTurnCount;
382 }
383 return right.completedAt.localeCompare(left.completedAt);
384 }),
385 [inferredCheckpointTurnCountByRunId, turnDiffSummaries],
386 );
387
388 useEffect(() => {
389 if (!routeThreadRef || diffSelection.kind !== "turn") return;
390 useDiffPanelStore.getState().reconcileTurnSelection(
391 routeThreadRef,
392 orderedTurnDiffSummaries.map((summary) => summary.runId),
393 );
394 }, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
395
396 const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
397 const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch";
398 const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null;
399 const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
400 const selectedFileRevealRequestId =
401 diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
402 const selectedTurn =
403 selectedRunId === null
404 ? undefined
405 : (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ??
406 orderedTurnDiffSummaries[0]);
407 const selectedCheckpointTurnCount =
408 selectedTurn &&
409 (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[selectedTurn.runId]);
410 const latestTurn = orderedTurnDiffSummaries[0];
411 const selectedScopeLabel =
412 selectedRunId === null
413 ? selectedGitScope === "unstaged"
414 ? "Working tree"
415 : "Branch changes"
416 : selectedTurn?.runId === latestTurn?.runId
417 ? "Latest turn"
418 : `Turn ${selectedCheckpointTurnCount ?? "?"}`;
419 const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope;
420 const collapseScopeKey = routeThreadRef
421 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
422 : null;
423 const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
424 const collapsedDiffFileKeys =
425 collapsedDiffFiles.scopeKey === collapseScopeKey
426 ? collapsedDiffFiles.fileKeys
427 : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
428 const reviewSectionTitle = selectedTurn
429 ? `Turn ${selectedCheckpointTurnCount ?? "?"}`
430 : selectedGitScope === "unstaged"
431 ? "Working tree"
432 : "Branch changes";
433 const selectedCheckpointRange = useMemo(
434 () =>
435 typeof selectedCheckpointTurnCount === "number"
436 ? {
437 fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
438 toTurnCount: selectedCheckpointTurnCount,
439 }
440 : null,
441 [selectedCheckpointTurnCount],
442 );
443 const activeCheckpointDiff = useCheckpointDiff(
444 {
445 environmentId: activeThread?.environmentId ?? null,
446 threadId: activeThreadId,
447 fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
448 toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
449 ignoreWhitespace: diffIgnoreWhitespace,
450 cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null,
451 },
452 { enabled: isGitRepo && selectedTurn !== undefined },
453 );
454 const primaryBranchDiffPreview = useEnvironmentQuery(
455 selectedRunId === null && activeThread && activeCwd
456 ? reviewEnvironment.diffPreview({
457 environmentId: activeThread.environmentId,
458 input: {
459 cwd: activeCwd,
460 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
461 ignoreWhitespace: diffIgnoreWhitespace,
462 },
463 })
464 : null,
465 );
466 const shouldRetryBranchDiffAtEnvironmentCwd =
467 selectedRunId === null &&
468 primaryBranchDiffPreview.error?.includes("configured workspace root") === true &&
469 serverConfig?.cwd !== undefined &&
470 serverConfig.cwd !== activeCwd;
471 const fallbackBranchDiffPreview = useEnvironmentQuery(
472 shouldRetryBranchDiffAtEnvironmentCwd && activeThread && serverConfig
473 ? reviewEnvironment.diffPreview({
474 environmentId: activeThread.environmentId,
475 input: {
476 cwd: serverConfig.cwd,
477 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
478 ignoreWhitespace: diffIgnoreWhitespace,
479 },
480 })
481 : null,
482 );
483 const branchDiffPreview = shouldRetryBranchDiffAtEnvironmentCwd
484 ? fallbackBranchDiffPreview
485 : primaryBranchDiffPreview;
486 const refreshBranchDiffPreview = branchDiffPreview.refresh;
487 const canRefreshGitDiff =
488 isGitRepo && selectedRunId === null && activeThread != null && activeCwd != null;
489 const activeThreadRefreshKey = routeThreadRef
490 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
491 : null;
492
493 useEffect(() => {
494 if (!canRefreshGitDiff) return;
495 const refreshOnFocus = () => refreshBranchDiffPreview();
496 window.addEventListener("focus", refreshOnFocus);
497 return () => window.removeEventListener("focus", refreshOnFocus);
498 }, [canRefreshGitDiff, refreshBranchDiffPreview]);
499
500 useEffect(() => {
501 const current = {
502 threadKey: activeThreadRefreshKey,
503 runId: latestTurn?.runId ?? null,
504 };
505 const previous = lastCompletedTurnRefreshRef.current;
506 if (!canRefreshGitDiff) {
507 return;
508 }
509 if (previous === null || previous.threadKey !== current.threadKey) {
510 lastCompletedTurnRefreshRef.current = current;
511 return;
512 }
513 if (previous.runId === current.runId) return;
514 refreshBranchDiffPreview();
515 lastCompletedTurnRefreshRef.current = current;
516 }, [activeThreadRefreshKey, canRefreshGitDiff, latestTurn?.runId, refreshBranchDiffPreview]);
517
518 const selectedGitSource = branchDiffPreview.data?.sources.find(
519 (source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
520 );
521 const loadDiffFiles = useMemo<FileDiffContentsLoader | undefined>(() => {
522 const preview = branchDiffPreview.data;
523 if (selectedRunId !== null || !activeThread || !preview || !selectedGitSource) {
524 return undefined;
525 }
526
527 const source = selectedGitSource;
528 return async (fileDiff) => {
529 const newPath = resolveFileDiffPath(fileDiff);
530 const oldPath = fileDiff.prevName
531 ? resolveFileDiffPath({ ...fileDiff, name: fileDiff.prevName })
532 : newPath;
533 const result = await getDiffFileContents({
534 environmentId: activeThread.environmentId,
535 input: {
536 cwd: preview.cwd,
537 sourceKind: source.kind,
538 changeType: fileDiff.type,
539 baseRef: source.baseRef,
540 headRef: source.headRef,
541 oldPath,
542 newPath,
543 },
544 });
545 if (result._tag !== "Success") {
546 throw squashAtomCommandFailure(result);
547 }
548
549 const newFile = {
550 name: newPath,
551 contents: result.value.newContents,
552 cacheKey: `${source.diffHash}:new:${newPath}`,
553 };
554 if (fileDiff.type === "rename-pure") {
555 return { oldFile: null, newFile };
556 }
557 return {
558 oldFile: {
559 name: oldPath,
560 contents: result.value.oldContents,
561 cacheKey: `${source.diffHash}:old:${oldPath}`,
562 },
563 newFile,
564 };
565 };
566 }, [activeThread, branchDiffPreview.data, getDiffFileContents, selectedGitSource, selectedRunId]);
567 const localBranchRefs = useEnvironmentQuery(
568 selectedRunId === null &&
569 selectedGitScope === "branch" &&
570 activeThread &&
571 branchDiffPreview.data?.cwd
572 ? vcsEnvironment.listRefs({
573 environmentId: activeThread.environmentId,
574 input: {
575 cwd: branchDiffPreview.data.cwd,
576 includeMatchingRemoteRefs: true,
577 refKind: "local",
578 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
579 limit: 100,
580 },
581 })
582 : null,
583 );
584 const remoteBranchRefs = useEnvironmentQuery(
585 selectedRunId === null &&
586 selectedGitScope === "branch" &&
587 activeThread &&
588 branchDiffPreview.data?.cwd
589 ? vcsEnvironment.listRefs({
590 environmentId: activeThread.environmentId,
591 input: {
592 cwd: branchDiffPreview.data.cwd,
593 includeMatchingRemoteRefs: true,
594 refKind: "remote",
595 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
596 limit: 100,
597 },
598 })
599 : null,
600 );
601 const baseRefChoices = buildBaseRefChoices(
602 localBranchRefs.data?.refs.filter((ref) => ref.name !== selectedGitSource?.headRef) ?? [],
603 remoteBranchRefs.data?.refs ?? [],
604 );
605 const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery);
606 const valueForBaseRefChoice = (choice: (typeof baseRefChoices)[number]) =>
607 selectedBaseRef && selectedBaseRef === choice.remote?.name
608 ? selectedBaseRef
609 : (choice.local?.name ?? choice.remote?.name ?? choice.id);
610 const baseRefItems = [AUTOMATIC_BASE_REF, ...baseRefChoices.map(valueForBaseRefChoice)];
611 const filteredBaseRefItems = [
612 ...(baseRefQuery.trim().length === 0 ? [AUTOMATIC_BASE_REF] : []),
613 ...matchingBaseRefChoices.map(valueForBaseRefChoice),
614 ];
615 const gitDiff = selectedGitSource?.diff;
616
617 const selectedPatch = selectedTurn ? activeCheckpointDiff.data?.diff : gitDiff;
618 const isSelectedPatchTruncated = !selectedTurn && selectedGitSource?.truncated === true;
619 const isLoadingSelectedPatch = selectedTurn
620 ? activeCheckpointDiff.isPending
621 : branchDiffPreview.isPending;
622 const selectedPatchError = selectedTurn ? activeCheckpointDiff.error : branchDiffPreview.error;
623 const hasResolvedPatch = typeof selectedPatch === "string";
624 const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
625 const renderablePatch = useMemo(
626 () =>
627 getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, {
628 compactPartialHunkOffsets: selectedRunId === null,
629 }),
630 [resolvedTheme, selectedPatch, selectedRunId],
631 );
632 const renderableFiles = useMemo(() => {
633 if (!renderablePatch || renderablePatch.kind !== "files") {
634 return [];
635 }
636 return renderablePatch.files.toSorted((left, right) =>
637 resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
638 numeric: true,
639 sensitivity: "base",
640 }),
641 );
642 }, [renderablePatch]);
643 const renderableFileEntries = useMemo(
644 () =>
645 renderableFiles.map((fileDiff) => ({
646 fileDiff,
647 fileKey: buildFileDiffRenderKey(fileDiff),
648 })),
649 [renderableFiles],
650 );
651 const codeViewFiles = useMemo(
652 () =>
653 renderableFileEntries.map(({ fileDiff, fileKey }) => {
654 return {
655 fileDiff,
656 filePath: resolveFileDiffPath(fileDiff),
657 fileKey,
658 collapsed: collapsedDiffFileKeys.has(fileKey),
659 };
660 }),
661 [collapsedDiffFileKeys, renderableFileEntries],
662 );
663 const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
664 const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
665 const diffLineStat = useMemo(() => getDiffLineStat(renderableFiles), [renderableFiles]);
666 const selectedDiffFileKey = selectedFilePath
667 ? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null)
668 : null;
669
670 useEffect(() => {
671 if (!selectedDiffFileKey) return;
672 codeViewRef.current?.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
673 }, [codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
674
675 const openDiffFile = useCallback(
676 (filePath: string) => {
677 openDiffFilePrimaryAction({
678 threadRef: routeThreadRef,
679 filePath,
680 activeCwd,
681 openInEditor: (targetPath) => {
682 void (async () => {
683 const result = await openInPreferredEditor(targetPath);
684 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
685 console.warn("Failed to open diff file in editor.", {
686 operation: "open-diff-file",
687 ...(routeThreadRef
688 ? {
689 environmentId: routeThreadRef.environmentId,
690 threadId: routeThreadRef.threadId,
691 }
692 : {}),
693 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
694 });
695 }
696 })();
697 },
698 });
699 },
700 [activeCwd, openInPreferredEditor, routeThreadRef],
701 );
702 const toggleDiffFileCollapsed = useCallback(
703 (fileKey: string) => {
704 setCollapsedDiffFiles((current) => {
705 const next = new Set(current.scopeKey === collapseScopeKey ? current.fileKeys : []);
706 if (next.has(fileKey)) {
707 next.delete(fileKey);
708 } else {
709 next.add(fileKey);
710 }
711 return { scopeKey: collapseScopeKey, fileKeys: next };
712 });
713 },
714 [collapseScopeKey],
715 );
716
717 const toggleDiffFileCollapse = useCallback(() => {
718 setCodeViewRevision((current) => current + 1);
719 setCollapsedDiffFiles((current) => {
720 const currentKeys =
721 current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
722
723 return {
724 scopeKey: collapseScopeKey,
725 fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
726 };
727 });
728 }, [collapseScopeKey, diffFileKeys]);
729
730 const selectTurn = (runId: RunId) => {
731 if (!routeThreadRef) return;
732 useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
733 };
734 const selectGitScope = (scope: "branch" | "unstaged") => {
735 if (!routeThreadRef) return;
736 useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
737 };
738 const selectBranchBaseRef = (baseRef: string | null) => {
739 if (!routeThreadRef) return;
740 useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
741 };
742
743 const headerRow = (
744 <>
745 <div className="flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
746 <DropdownMenu>
747 <DropdownMenuTrigger
748 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"
749 aria-label={`Diff scope: ${selectedScopeLabel}`}
750 >
751 <span className="truncate">{selectedScopeLabel}</span>
752 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
753 </DropdownMenuTrigger>
754 <DropdownMenuContent align="start" className="w-60">
755 <DropdownMenuItem
756 className={
757 selectedRunId === null && selectedGitScope === "unstaged"
758 ? "bg-foreground/[0.08]"
759 : undefined
760 }
761 onClick={() => selectGitScope("unstaged")}
762 >
763 <span>Working tree</span>
764 {selectedRunId === null && selectedGitScope === "unstaged" && (
765 <CheckIcon className="ml-auto" />
766 )}
767 </DropdownMenuItem>
768 <DropdownMenuItem
769 className={
770 selectedRunId === null && selectedGitScope === "branch"
771 ? "bg-foreground/[0.08]"
772 : undefined
773 }
774 onClick={() => selectGitScope("branch")}
775 >
776 <span>Branch changes</span>
777 {selectedRunId === null && selectedGitScope === "branch" && (
778 <CheckIcon className="ml-auto" />
779 )}
780 </DropdownMenuItem>
781 <DropdownMenuItem
782 className={
783 selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId
784 ? "bg-foreground/[0.08]"
785 : undefined
786 }
787 onClick={() => {
788 if (latestTurn) selectTurn(latestTurn.runId);
789 }}
790 >
791 <span>Latest turn</span>
792 {selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId && (
793 <CheckIcon className="ml-auto" />
794 )}
795 </DropdownMenuItem>
796 <DropdownMenuSub>
797 <DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
798 <DropdownMenuSubContent className="w-64">
799 {orderedTurnDiffSummaries.map((summary) => {
800 const turnCount =
801 summary.checkpointTurnCount ??
802 inferredCheckpointTurnCountByRunId[summary.runId] ??
803 "?";
804 return (
805 <DropdownMenuItem
806 key={summary.runId}
807 className={
808 summary.runId === selectedTurn?.runId ? "bg-foreground/[0.08]" : undefined
809 }
810 onClick={() => selectTurn(summary.runId)}
811 >
812 <span>Turn {turnCount}</span>
813 <span className="ml-auto text-xs tabular-nums text-muted-foreground">
814 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
815 </span>
816 {summary.runId === selectedTurn?.runId && <CheckIcon className="ml-1" />}
817 </DropdownMenuItem>
818 );
819 })}
820 </DropdownMenuSubContent>
821 </DropdownMenuSub>
822 </DropdownMenuContent>
823 </DropdownMenu>
824 {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
825 <div
826 className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
827 title={`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
828 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
829 >
830 <span className="min-w-0 max-w-48 truncate">{selectedGitSource.headRef ?? "HEAD"}</span>
831 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
832 <Combobox
833 items={baseRefItems}
834 filteredItems={filteredBaseRefItems}
835 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
836 onOpenChange={(open) => {
837 if (!open) setBaseRefQuery("");
838 }}
839 onValueChange={(value) => {
840 if (!value) return;
841 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
842 }}
843 >
844 <ComboboxTrigger
845 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"
846 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
847 >
848 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
849 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
850 </ComboboxTrigger>
851 <ComboboxPopup
852 align="start"
853 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"
854 >
855 <div className="min-w-0 shrink-0 px-3 pt-2.5">
856 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
857 <SearchIcon
858 aria-hidden="true"
859 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
860 />
861 <ComboboxInput
862 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
863 inputClassName="rounded-none bg-transparent text-sm"
864 placeholder="Search refs..."
865 showTrigger={false}
866 size="sm"
867 unstyled
868 value={baseRefQuery}
869 onChange={(event) => setBaseRefQuery(event.target.value)}
870 />
871 </div>
872 </div>
873 <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">
874 <span aria-hidden="true" />
875 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
876 <span>Branch</span>
877 <span className="text-right">Remote</span>
878 </div>
879 </div>
880 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
881 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
882 <ComboboxItem
883 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
884 contentClassName="w-full min-w-0 overflow-hidden"
885 value={AUTOMATIC_BASE_REF}
886 >
887 <span className="block min-w-0 truncate">Automatic</span>
888 </ComboboxItem>
889 {baseRefChoices.map((choice) => {
890 const item = valueForBaseRefChoice(choice);
891 const hasBoth = choice.local !== null && choice.remote !== null;
892 const useRemote = choice.remote?.name === item;
893 return (
894 <ComboboxItem
895 key={choice.id}
896 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
897 contentClassName="w-full min-w-0 overflow-hidden"
898 value={item}
899 >
900 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden">
901 <span className="block min-w-0 truncate pe-2">{choice.label}</span>
902 {hasBoth ? (
903 <div
904 className="flex justify-end"
905 onClick={(event) => event.stopPropagation()}
906 onPointerDown={(event) => event.stopPropagation()}
907 >
908 <Switch
909 aria-label={`Use remote version of ${choice.label}`}
910 checked={useRemote}
911 className="[--thumb-size:--spacing(3)]"
912 onCheckedChange={(checked) => {
913 const nextRef = checked
914 ? choice.remote?.name
915 : choice.local?.name;
916 if (nextRef) selectBranchBaseRef(nextRef);
917 }}
918 />
919 </div>
920 ) : choice.remote ? (
921 <span
922 className="flex justify-end text-muted-foreground"
923 title="Remote only"
924 >
925 <CheckIcon aria-hidden="true" className="size-3" />
926 </span>
927 ) : null}
928 </div>
929 </ComboboxItem>
930 );
931 })}
932 </ComboboxList>
933 </ComboboxPopup>
934 </Combobox>
935 </div>
936 )}
937 </div>
938 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
939 {codeViewFiles.length > 0 && (
940 <DiffStatLabel
941 additions={diffLineStat.additions}
942 deletions={diffLineStat.deletions}
943 className="mr-1 text-[11px]"
944 layout="inline"
945 />
946 )}
947 {canRefreshGitDiff && (
948 <Tooltip>
949 <TooltipTrigger
950 render={
951 <Button
952 type="button"
953 size="icon-sm"
954 variant="ghost"
955 aria-label={branchDiffPreview.isPending ? "Refreshing diff" : "Refresh diff"}
956 onClick={refreshBranchDiffPreview}
957 />
958 }
959 >
960 <RefreshCwIcon
961 className={cn("size-3.5", branchDiffPreview.isPending && "animate-spin")}
962 />
963 </TooltipTrigger>
964 <TooltipPopup side="top">
965 {branchDiffPreview.isPending ? "Refreshing diff…" : "Refresh diff"}
966 </TooltipPopup>
967 </Tooltip>
968 )}
969 {codeViewFiles.length > 0 && (
970 <Tooltip>
971 <TooltipTrigger
972 render={
973 <Button
974 type="button"
975 size="icon-sm"
976 variant="ghost"
977 aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
978 onClick={toggleDiffFileCollapse}
979 />
980 }
981 >
982 {allDiffFilesCollapsed ? (
983 <ChevronsUpDownIcon className="size-3.5" />
984 ) : (
985 <ChevronsDownUpIcon className="size-3.5" />
986 )}
987 </TooltipTrigger>
988 <TooltipPopup side="top">
989 {allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
990 </TooltipPopup>
991 </Tooltip>
992 )}
993 <ToggleGroup
994 className="shrink-0 gap-1"
995 size="sm"
996 value={[diffRenderMode]}
997 onValueChange={(value) => {
998 const next = value[0];
999 if (next === "stacked" || next === "split") {
1000 setDiffRenderMode(next);
1001 }
1002 }}
1003 >
1004 <Toggle aria-label="Stacked diff view" value="stacked" variant="ghost">
1005 <Rows3Icon className="size-3.5" />
1006 </Toggle>
1007 <Toggle aria-label="Split diff view" value="split" variant="ghost">
1008 <Columns2Icon className="size-3.5" />
1009 </Toggle>
1010 </ToggleGroup>
1011 <Tooltip>
1012 <TooltipTrigger
1013 render={
1014 <Toggle
1015 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
1016 variant="ghost"
1017 size="sm"
1018 pressed={wordWrap}
1019 onPressedChange={(pressed) => {
1020 setWordWrap(Boolean(pressed));
1021 }}
1022 />
1023 }
1024 >
1025 <TextWrapIcon className="size-3.5" />
1026 </TooltipTrigger>
1027 <TooltipPopup side="top">
1028 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
1029 </TooltipPopup>
1030 </Tooltip>
1031 <Tooltip>
1032 <TooltipTrigger
1033 render={
1034 <Toggle
1035 aria-label={
1036 diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
1037 }
1038 variant="ghost"
1039 size="sm"
1040 pressed={diffIgnoreWhitespace}
1041 onPressedChange={(pressed) => {
1042 setDiffIgnoreWhitespace(Boolean(pressed));
1043 }}
1044 />
1045 }
1046 >
1047 <PilcrowIcon className="size-3.5" />
1048 </TooltipTrigger>
1049 <TooltipPopup side="top">
1050 {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
1051 </TooltipPopup>
1052 </Tooltip>
1053 </div>
1054 </>
1055 );
1056
1057 return (
1058 <DiffPanelShell mode={mode} header={headerRow}>
1059 {!activeThread ? (
1060 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1061 Select a thread to inspect turn diffs.
1062 </div>
1063 ) : !isGitRepo ? (
1064 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1065 Turn diffs are unavailable because this project is not a git repository.
1066 </div>
1067 ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
1068 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1069 No completed turns yet.
1070 </div>
1071 ) : (
1072 <>
1073 <div className="diff-panel-viewport flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
1074 {isSelectedPatchTruncated && (
1075 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground">
1076 This diff was truncated because it exceeded the preview limit. The changes shown are
1077 incomplete.
1078 </p>
1079 )}
1080 {selectedPatchError && !renderablePatch && (
1081 <div className="px-3">
1082 <p className="mb-2 text-[11px] text-error/80">{selectedPatchError}</p>
1083 </div>
1084 )}
1085 {!renderablePatch ? (
1086 isLoadingSelectedPatch ? (
1087 <DiffPanelLoadingState
1088 label={
1089 selectedTurn
1090 ? "Loading checkpoint diff..."
1091 : selectedGitScope === "unstaged"
1092 ? "Loading working tree diff..."
1093 : "Loading branch diff..."
1094 }
1095 />
1096 ) : (
1097 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
1098 <p>
1099 {hasNoNetChanges
1100 ? "No net changes in this selection."
1101 : "No patch available for this selection."}
1102 </p>
1103 </div>
1104 )
1105 ) : renderablePatch.kind === "files" ? (
1106 <div
1107 className="min-h-0 flex-1"
1108 onClickCapture={(event) => {
1109 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1110 const title = composedPath.find(
1111 (node): node is HTMLElement =>
1112 node instanceof HTMLElement && node.hasAttribute("data-title"),
1113 );
1114 const filePath = title?.textContent?.trim();
1115 if (filePath) openDiffFile(filePath);
1116 }}
1117 >
1118 <AnnotatableCodeView
1119 key={collapseScopeKey ?? reviewSectionId}
1120 viewerRef={codeViewRef}
1121 codeViewKey={codeViewMountKey}
1122 className="diff-render-surface h-full min-h-0 overflow-auto"
1123 files={codeViewFiles}
1124 sectionId={reviewSectionId}
1125 sectionTitle={reviewSectionTitle}
1126 composerDraftTarget={composerDraftTarget}
1127 renderHeaderPrefix={(fileDiff, fileKey, collapsed) => {
1128 const filePath = resolveFileDiffPath(fileDiff);
1129 return (
1130 <Tooltip>
1131 <TooltipTrigger
1132 render={
1133 <button
1134 type="button"
1135 className={cn(
1136 "-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",
1137 getDiffCollapseIconClassName(fileDiff),
1138 )}
1139 aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
1140 aria-expanded={!collapsed}
1141 onClick={(event) => {
1142 event.stopPropagation();
1143 toggleDiffFileCollapsed(fileKey);
1144 }}
1145 />
1146 }
1147 >
1148 {collapsed ? (
1149 <ChevronRightIcon className="size-4" />
1150 ) : (
1151 <ChevronDownIcon className="size-4" />
1152 )}
1153 </TooltipTrigger>
1154 <TooltipPopup side="top">
1155 {collapsed ? "Expand diff" : "Collapse diff"}
1156 </TooltipPopup>
1157 </Tooltip>
1158 );
1159 }}
1160 options={{
1161 diffStyle: diffRenderMode === "split" ? "split" : "unified",
1162 lineDiffType: "none",
1163 overflow: wordWrap ? "wrap" : "scroll",
1164 theme: resolveDiffThemeName(resolvedTheme),
1165 themeType: resolvedTheme as DiffThemeType,
1166 unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
1167 stickyHeaders: true,
1168 ...(loadDiffFiles ? { loadDiffFiles } : {}),
1169 itemMetrics: {
1170 diffHeaderHeight: 32,
1171 hunkSeparatorHeight: 24,
1172 paddingTop: 0,
1173 paddingBottom: 0,
1174 },
1175 layout: { paddingTop: 0, paddingBottom: 0, gap: 0 },
1176 }}
1177 />
1178 </div>
1179 ) : (
1180 <div className="min-h-0 flex-1 overflow-auto p-2">
1181 <div className="space-y-2">
1182 <p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
1183 <pre
1184 className={cn(
1185 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
1186 wordWrap
1187 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
1188 : "overflow-auto",
1189 )}
1190 >
1191 {renderablePatch.text}
1192 </pre>
1193 </div>
1194 </div>
1195 )}
1196 </div>
1197 </>
1198 )}
1199 </DiffPanelShell>
1200 );
1201}