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