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