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