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