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

DiffPanel.tsx

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