Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DiffPanel.tsx

1,205 lines48.8 KB

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