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

DiffPanel.tsx

1,255 lines50.7 KB

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