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

DiffPanel.tsx

1,274 lines50.9 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​
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 );
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 );
189​
190interface DiffPanelProps {
191 mode?: DiffPanelMode;
192 composerDraftTarget: ScopedThreadRef | DraftId;
193 workspaceMutationId: string | null;
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 // Find can ask again before the unfolded file reaches the viewer, so this must never fold.
699 const unfoldDiffFile = useCallback((fileKey: string) => {
700 const { collapseScopeKey, defaultCollapsedDiffFileKeys } = collapseDefaultsRef.current;
701 setCollapsedDiffFiles((current) => {
702 const fileKeys =
703 current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys;
704 if (!fileKeys.has(fileKey)) return current;
705 const next = new Set(fileKeys);
706 next.delete(fileKey);
707 return { scopeKey: collapseScopeKey, fileKeys: next };
708 });
709 }, []);
710​
711 const toggleDiffFileCollapse = useCallback(() => {
712 setCodeViewRevision((current) => current + 1);
713 setCollapsedDiffFiles((current) => {
714 const currentKeys =
715 current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys;
716​
717 return {
718 scopeKey: collapseScopeKey,
719 fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
720 };
721 });
722 }, [collapseScopeKey, defaultCollapsedDiffFileKeys, diffFileKeys]);
723​
724 const selectTurn = (runId: RunId) => {
725 if (!routeThreadRef) return;
726 useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
727 };
728 const selectGitScope = (scope: "branch" | "unstaged") => {
729 if (!routeThreadRef) return;
730 useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
731 };
732 const selectBranchBaseRef = (baseRef: string | null) => {
733 if (!routeThreadRef) return;
734 useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
735 };
736 // The scope menu has two radio groups: the top-level one treats the latest
737 // turn as "latest", while the turn sub-menu keys every turn by id so the
738 // latest turn is also marked there.
739 const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : "";
740 const selectedScopeValue =
741 selectedRunId === null
742 ? selectedGitScope
743 : selectedTurn?.runId === latestTurn?.runId
744 ? "latest"
745 : selectedTurnValue;
746 const selectScopeValue = (value: string) => {
747 if (value === "unstaged" || value === "branch") {
748 selectGitScope(value);
749 } else if (value === "latest") {
750 if (latestTurn) selectTurn(latestTurn.runId);
751 } else {
752 const turn = orderedTurnDiffSummaries.find((summary) => `turn:${summary.runId}` === value);
753 if (turn) selectTurn(turn.runId);
754 }
755 };
756​
757 const headerRow = (
758 <>
759 <div className="flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
760 <DropdownMenu>
761 <DropdownMenuTrigger
762 render={<Button size="xs" variant="secondary" />}
763 className="max-w-full"
764 aria-label={`Diff scope: ${selectedScopeLabel}`}
765 >
766 <span className="truncate">{selectedScopeLabel}</span>
767 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
768 </DropdownMenuTrigger>
769 <DropdownMenuContent align="start">
770 <DropdownMenuRadioGroup value={selectedScopeValue} onValueChange={selectScopeValue}>
771 <DropdownMenuRadioItem value="branch" closeOnClick>
772 <span>Changes</span>
773 </DropdownMenuRadioItem>
774 <DropdownMenuRadioItem value="unstaged" closeOnClick>
775 <span>Uncommitted</span>
776 </DropdownMenuRadioItem>
777 <DropdownMenuRadioItem value="latest" closeOnClick>
778 <span>Latest turn</span>
779 </DropdownMenuRadioItem>
780 </DropdownMenuRadioGroup>
781 <DropdownMenuSub>
782 <DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
783 <DropdownMenuSubContent>
784 <DropdownMenuRadioGroup value={selectedTurnValue} onValueChange={selectScopeValue}>
785 {orderedTurnDiffSummaries.map((summary) => {
786 const turnCount =
787 summary.checkpointTurnCount ??
788 inferredCheckpointTurnCountByRunId[summary.runId] ??
789 "?";
790 return (
791 <DropdownMenuRadioItem
792 key={summary.runId}
793 value={`turn:${summary.runId}`}
794 closeOnClick
795 >
796 <span className="flex items-center gap-2">
797 <span>Turn {turnCount}</span>
798 <span className="ml-auto text-xs tabular-nums text-muted-foreground">
799 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
800 </span>
801 </span>
802 </DropdownMenuRadioItem>
803 );
804 })}
805 </DropdownMenuRadioGroup>
806 </DropdownMenuSubContent>
807 </DropdownMenuSub>
808 </DropdownMenuContent>
809 </DropdownMenu>
810 {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
811 <div
812 className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
813 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
814 >
815 <Tooltip>
816 <TooltipTrigger render={<span className="flex min-w-0 items-center gap-2" />}>
817 <span className="min-w-0 max-w-48 truncate">
818 {selectedGitSource.headRef ?? "HEAD"}
819 </span>
820 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
821 </TooltipTrigger>
822 <TooltipPopup side="top">
823 {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
824 </TooltipPopup>
825 </Tooltip>
826 <Combobox
827 items={baseRefItems}
828 filteredItems={filteredBaseRefItems}
829 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
830 onOpenChange={(open) => {
831 if (!open) setBaseRefQuery("");
832 }}
833 onValueChange={(value) => {
834 if (!value) return;
835 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
836 }}
837 >
838 <ComboboxTrigger
839 render={<Button variant="ghost-muted" size="xs" />}
840 className="min-w-0 max-w-48"
841 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
842 >
843 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
844 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
845 </ComboboxTrigger>
846 <ComboboxPopup
847 align="start"
848 className="w-72 min-w-0 max-w-[calc(100vw-1rem)] overflow-hidden"
849 >
850 <ComboboxSearchInput
851 placeholder="Search refs..."
852 value={baseRefQuery}
853 onChange={(event) => setBaseRefQuery(event.target.value)}
854 />
855 <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">
856 <span aria-hidden="true" />
857 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
858 <span>Branch</span>
859 <span className="text-right">Remote</span>
860 </div>
861 </div>
862 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
863 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
864 <ComboboxItem
865 className="w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)]"
866 value={AUTOMATIC_BASE_REF}
867 >
868 <span className="block min-w-0 truncate">Automatic</span>
869 </ComboboxItem>
870 {baseRefChoices.map((choice) => {
871 const item = valueForBaseRefChoice(choice);
872 const hasBoth = choice.local !== null && choice.remote !== null;
873 const useRemote = choice.remote?.name === item;
874 return (
875 <ComboboxItem
876 key={choice.id}
877 className="w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)]"
878 value={item}
879 >
880 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden">
881 <span className="block min-w-0 truncate pe-2">{choice.label}</span>
882 {hasBoth ? (
883 <div
884 className="flex justify-end"
885 onClick={(event) => event.stopPropagation()}
886 onPointerDown={(event) => event.stopPropagation()}
887 >
888 <Switch
889 aria-label={`Use remote version of ${choice.label}`}
890 checked={useRemote}
891 className="[--thumb-size:--spacing(3)]"
892 onCheckedChange={(checked) => {
893 const nextRef = checked
894 ? choice.remote?.name
895 : choice.local?.name;
896 if (nextRef) selectBranchBaseRef(nextRef);
897 }}
898 />
899 </div>
900 ) : choice.remote ? (
901 <Tooltip>
902 <TooltipTrigger
903 render={
904 <span className="flex justify-end text-muted-foreground">
905 <CheckIcon
906 role="img"
907 aria-label="Remote only"
908 className="size-3"
909 />
910 </span>
911 }
912 />
913 <TooltipPopup side="top">Remote only</TooltipPopup>
914 </Tooltip>
915 ) : null}
916 </div>
917 </ComboboxItem>
918 );
919 })}
920 </ComboboxList>
921 </ComboboxPopup>
922 </Combobox>
923 </div>
924 )}
925 </div>
926 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
927 {codeViewFiles.length > 0 || (!selectedTurn && selectedGitSource?.files?.length) ? (
928 <DiffStatLabel
929 additions={diffLineStat.additions}
930 deletions={diffLineStat.deletions}
931 className="mr-1 text-2xs"
932 layout="inline"
933 />
934 ) : null}
935 {canRefreshGitDiff && (
936 <Tooltip>
937 <TooltipTrigger
938 render={
939 <Button
940 type="button"
941 size="icon-sm"
942 variant="ghost"
943 aria-label={isRefreshingDiff ? "Refreshing diff" : "Refresh diff"}
944 onClick={refreshDiffFromUserAction}
945 />
946 }
947 >
948 <RefreshIcon size="sm" refreshing={isRefreshingDiff} />
949 </TooltipTrigger>
950 <TooltipPopup side="top">
951 {isRefreshingDiff ? "Refreshing diff…" : "Refresh diff"}
952 </TooltipPopup>
953 </Tooltip>
954 )}
955 {diffFileKeys.length > 0 && (
956 <Tooltip>
957 <TooltipTrigger
958 render={
959 <Button
960 type="button"
961 size="icon-sm"
962 variant="ghost"
963 aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
964 onClick={toggleDiffFileCollapse}
965 />
966 }
967 >
968 <MorphIcon
969 className="size-3.5"
970 icon={allDiffFilesCollapsed ? ChevronsUpDown : ChevronsDownUp}
971 />
972 </TooltipTrigger>
973 <TooltipPopup side="top">
974 {allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
975 </TooltipPopup>
976 </Tooltip>
977 )}
978 <ToggleGroup
979 aria-label="Diff layout"
980 className="shrink-0"
981 variant="segmented"
982 value={[diffLayout]}
983 onValueChange={(value) => {
984 const next = value[0];
985 if (next === "stacked" || next === "split") {
986 updateClientSettings({ diffLayout: next });
987 }
988 }}
989 >
990 <Toggle aria-label="Stacked diff view" value="stacked">
991 <Rows3Icon className="size-3.5" />
992 </Toggle>
993 <Toggle aria-label="Split diff view" value="split">
994 <Columns2Icon className="size-3.5" />
995 </Toggle>
996 </ToggleGroup>
997 <Tooltip>
998 <TooltipTrigger
999 render={
1000 <Toggle
1001 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
1002 variant="ghost"
1003 size="sm"
1004 pressed={wordWrap}
1005 onPressedChange={(pressed) => {
1006 setWordWrap(Boolean(pressed));
1007 }}
1008 />
1011 <TextWrapIcon className="size-3.5" />
1012 </TooltipTrigger>
1013 <TooltipPopup side="top">
1014 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
1015 </TooltipPopup>
1016 </Tooltip>
1017 <Tooltip>
1018 <TooltipTrigger
1019 render={
1020 <Toggle
1021 aria-label={
1022 diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
1024 variant="ghost"
1025 size="sm"
1026 pressed={diffIgnoreWhitespace}
1027 onPressedChange={(pressed) => {
1028 setDiffIgnoreWhitespace(Boolean(pressed));
1029 }}
1030 />
1033 <PilcrowIcon className="size-3.5" />
1034 </TooltipTrigger>
1035 <TooltipPopup side="top">
1036 {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
1037 </TooltipPopup>
1038 </Tooltip>
1039 {diffFileKeys.length > 0 && (
1040 <Tooltip>
1041 <TooltipTrigger
1042 render={
1043 <Toggle
1044 aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}
1045 variant="ghost"
1046 size="sm"
1047 pressed={fileTreeOpen}
1048 onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}
1049 />
1052 <FolderTreeIcon className="size-3.5" />
1053 </TooltipTrigger>
1054 <TooltipPopup side="top">
1055 {fileTreeOpen ? "Hide file tree" : "Show file tree"}
1056 </TooltipPopup>
1057 </Tooltip>
1058 )}
1059 </div>
1060 </>
1061 );
1062​
1063 return (
1064 <DiffPanelShell mode={mode} header={headerRow}>
1065 {!activeThread ? (
1066 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1067 Select a thread to inspect turn diffs.
1068 </div>
1069 ) : !isGitRepo ? (
1070 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1071 Turn diffs are unavailable because this project is not a git repository.
1072 </div>
1073 ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
1074 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1075 No completed turns yet.
1076 </div>
1077 ) : selectedRunId === null && !canReadFiles ? (
1078 fileAccess.isPending ? (
1079 <DiffPanelLoadingState label="Checking file access..." />
1080 ) : (
1081 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1082 {fileAccess.error ?? "This connection cannot read local diffs."}
1083 </div>
1085 ) : (
1086 <>
1087 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
1088 {isSelectedPatchTruncated && !lazySource && (
1089 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
1090 This preview exceeds the size limit. Changes shown are incomplete.
1091 {selectedGitSource?.files ? " Totals include all changes." : ""}
1092 </p>
1093 )}
1094 {selectedPatchError && !renderablePatch && (
1095 <div className="px-3">
1096 <p className="mb-2 text-2xs text-error/80">{selectedPatchError}</p>
1097 </div>
1098 )}
1099 {!renderablePatch && !lazySource ? (
1100 isLoadingSelectedPatch ? (
1101 <DiffPanelLoadingState
1102 label={
1103 selectedTurn
1104 ? "Loading checkpoint diff..."
1105 : selectedGitScope === "unstaged"
1106 ? "Loading uncommitted changes..."
1107 : "Loading changes..."
1109 />
1110 ) : (
1111 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
1112 <p>
1113 {hasNoNetChanges
1114 ? "No net changes in this selection."
1115 : "No patch available for this selection."}
1116 </p>
1117 </div>
1119 ) : lazySource || renderablePatch?.kind === "files" ? (
1120 <div className="flex min-h-0 flex-1 overflow-hidden">
1121 <div
1122 className="min-h-0 min-w-0 flex-1"
1123 onClickCapture={(event) => {
1124 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1125 for (const node of composedPath) {
1126 if (!(node instanceof HTMLElement)) continue;
1127 // Header controls keep their own actions. In particular, the chevron must
1128 // not also trigger the row handler or the two toggles cancel each other.
1129 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1130 return;
1133 const title = composedPath.find(
1134 (node): node is HTMLElement =>
1135 node instanceof HTMLElement && node.hasAttribute("data-title"),
1136 );
1137 const filePath = title?.textContent;
1138 // The filename remains the explicit "open in editor" affordance.
1139 if (filePath) {
1140 openDiffFile(filePath);
1141 return;
1143 const header = composedPath.find(
1144 (node): node is HTMLElement =>
1145 node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),
1146 );
1147 const headerFilePath = header?.querySelector("[data-title]")?.textContent;
1148 if (!headerFilePath) return;
1149 const file = codeViewFiles.find(
1150 (candidate) => candidate.filePath === headerFilePath,
1151 );
1152 if (file) toggleDiffFileCollapsed(file.fileKey);
1153 }}
1154 onContextMenuCapture={(event) => {
1155 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1156 const title = composedPath.find(
1157 (node): node is HTMLElement =>
1158 node instanceof HTMLElement && node.hasAttribute("data-title"),
1159 );
1160 const filePath = title?.textContent?.trim();
1161 if (!filePath) return;
1162 event.preventDefault();
1163 onFileContextMenu(
1165 environmentId: activeThread?.environmentId ?? null,
1166 filePath,
1167 workspaceRoot: activeCwd,
1168 repositoryRoot: activeRepositoryRoot,
1169 },
1170 event,
1171 );
1172 }}
1174 <AnnotatableCodeView
1175 key={collapseScopeKey ?? reviewSectionId}
1176 viewerRef={setCodeView}
1177 codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
1178 className="h-full min-h-0 overflow-auto"
1179 files={codeViewFiles}
1180 renderCodeViewFooter={renderLoadingBoundary}
1181 sectionId={reviewSectionId}
1182 sectionTitle={reviewSectionTitle}
1183 composerDraftTarget={composerDraftTarget}
1184 renderHeaderFilenameSuffix={(fileDiff) => {
1185 const path = resolveFileDiffPath(fileDiff);
1186 const state = fileStates.get(path);
1187 return (
1188 <DiffFileHeaderSuffix
1189 filePath={path}
1190 hasStat={fileStats.has(path)}
1191 error={state?.error ?? false}
1192 truncated={state?.truncated ?? false}
1193 onRetry={retry}
1194 />
1195 );
1196 }}
1197 {...(lazySource
1198 ? {
1199 unsafeCSSExtra:
1200 "[data-additions-count], [data-deletions-count] { display: none; }",
1201 renderHeaderMetadata: (fileDiff: FileDiffMetadata) => {
1202 const stat = fileStats.get(resolveFileDiffPath(fileDiff));
1203 return stat ? (
1204 <DiffStatLabel
1205 additions={stat.additions}
1206 deletions={stat.deletions}
1207 />
1208 ) : null;
1209 },
1211 : {})}
1212 onRevealSearchMatch={unfoldDiffFile}
1213 renderHeaderPrefix={(fileDiff, fileKey) => {
1214 const unavailable = fileDiff.cacheKey?.endsWith(":pending") === true;
1215 return (
1216 <DiffFileCollapseToggle
1217 filePath={resolveFileDiffPath(fileDiff)}
1218 fileKey={fileKey}
1219 collapsed={unavailable || collapsedDiffFileKeys.has(fileKey)}
1220 unavailable={unavailable}
1221 iconClassName={getDiffCollapseIconClassName(fileDiff)}
1222 onToggle={toggleDiffFileCollapsed}
1223 />
1224 );
1225 }}
1226 options={{
1227 diffStyle: diffLayout === "split" ? "split" : "unified",
1228 lineDiffType: "none",
1229 overflow: wordWrap ? "wrap" : "scroll",
1230 theme: resolveDiffThemeName(resolvedTheme),
1231 preferredHighlighter: PREFERRED_HIGHLIGHTER,
1232 themeType: resolvedTheme as DiffThemeType,
1233 stickyHeaders: true,
1234 ...(currentLoadDiffFiles ? { loadDiffFiles } : {}),
1235 }}
1236 />
1237 </div>
1238 {fileTreeOpen ? (
1239 <aside className="flex w-[min(16rem,40%)] min-w-40 shrink-0 border-l border-border/60">
1240 <DiffFileTree
1241 ariaLabel={`${reviewSectionTitle} files`}
1242 entries={fileTreeEntries}
1243 selectedPath={selectedFilePath}
1244 revealRequestId={selectedFileRevealRequestId}
1245 onSelectFile={revealDiffFile}
1246 />
1247 </aside>
1248 ) : null}
1249 </div>
1250 ) : (
1251 <div className="min-h-0 flex-1 overflow-auto p-2">
1252 <div className="space-y-2">
1253 <p className="text-2xs text-muted-foreground/75">
1254 {renderablePatch?.kind === "raw" ? renderablePatch.reason : null}
1255 </p>
1256 <pre
1257 className={cn(
1258 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-2xs leading-relaxed text-muted-foreground/90",
1259 wordWrap
1260 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
1261 : "overflow-auto",
1262 )}
1264 {renderablePatch?.kind === "raw" ? renderablePatch.text : null}
1265 </pre>
1266 </div>
1267 </div>
1268 )}
1269 </div>
1270 </>
1271 )}
1272 </DiffPanelShell>
1273 );