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

DiffPanel.tsx

1,202 lines48.3 KB

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