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

DiffPanel.tsx

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