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

DiffPanel.tsx

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