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