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