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