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

DiffPanel.tsx

1,179 lines47.0 KB

1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import { useAtomValue } from "@effect/atom-react";
3import type { FileDiffContentsLoader, FileDiffMetadata } from "@pierre/diffs";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
9import type { ScopedThreadRef, RunId } from "@t3tools/contracts";
10import {
11 ArrowRightIcon,
12 CheckIcon,
13 ChevronDownIcon,
14 Columns2Icon,
15 FolderTreeIcon,
16 PilcrowIcon,
17 Rows3Icon,
18 TextWrapIcon,
19} from "lucide-react";
20import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
21import * as Schema from "effect/Schema";
22import * 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;
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 );
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 );
185​
186interface DiffPanelProps {
187 mode?: DiffPanelMode;
188 composerDraftTarget: ScopedThreadRef | DraftId;
189 workspaceMutationId: string | null;
190 visible: boolean;
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 const loadDiffFiles: FileDiffContentsLoader = useStableCallback(async (fileDiff) => {
389 if (!currentLoadDiffFiles) {
390 throw new Error("Diff file contents are unavailable for this selection.");
391 }
392 return currentLoadDiffFiles(fileDiff);
393 });
394 const localBranchRefs = useEnvironmentQuery(
395 selectedRunId === null &&
396 selectedGitScope === "branch" &&
397 activeThread &&
398 branchDiffPreview.data?.cwd
399 ? vcsEnvironment.listRefs({
400 environmentId: activeThread.environmentId,
401 input: {
402 cwd: branchDiffPreview.data.cwd,
403 includeMatchingRemoteRefs: true,
404 refKind: "local",
405 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
406 limit: 100,
407 },
408 })
409 : null,
410 );
411 const remoteBranchRefs = useEnvironmentQuery(
412 selectedRunId === null &&
413 selectedGitScope === "branch" &&
414 activeThread &&
415 branchDiffPreview.data?.cwd
416 ? vcsEnvironment.listRefs({
417 environmentId: activeThread.environmentId,
418 input: {
419 cwd: branchDiffPreview.data.cwd,
420 includeMatchingRemoteRefs: true,
421 refKind: "remote",
422 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
423 limit: 100,
424 },
425 })
426 : null,
427 );
428 const baseRefChoices = buildBaseRefChoices(
429 localBranchRefs.data?.refs.filter((ref) => ref.name !== selectedGitSource?.headRef) ?? [],
430 remoteBranchRefs.data?.refs ?? [],
431 );
432 const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery);
433 const valueForBaseRefChoice = (choice: (typeof baseRefChoices)[number]) =>
434 selectedBaseRef && selectedBaseRef === choice.remote?.name
435 ? selectedBaseRef
436 : (choice.local?.name ?? choice.remote?.name ?? choice.id);
437 const baseRefItems = [AUTOMATIC_BASE_REF, ...baseRefChoices.map(valueForBaseRefChoice)];
438 const filteredBaseRefItems = [
439 ...(baseRefQuery.trim().length === 0 ? [AUTOMATIC_BASE_REF] : []),
440 ...matchingBaseRefChoices.map(valueForBaseRefChoice),
441 ];
442 const {
443 scope: filePatchScope,
444 isPending: areFilePatchesPending,
445 fileStates,
446 retry,
447 requestFile,
448 readyFilePaths,
449 renderableFiles,
450 settledFileCount,
451 loadNextFiles,
452 } = useReviewFilePatches({
453 environmentId: activeThread?.environmentId,
454 cwd: branchDiffPreview.data?.cwd,
455 source: lazySource,
456 baseRef: lazySource?.baseRef ?? selectedBaseRef,
457 ignoreWhitespace: diffIgnoreWhitespace,
458 theme: resolvedTheme,
459 revision: branchDiffPreview.data
460 ? DateTime.formatIso(branchDiffPreview.data.generatedAt)
461 : undefined,
462 preview: renderablePatch,
463 });
464 const refreshBranchDiffPreview = refreshPreviewQuery;
465 const previewOpenHandledRef = useRef(false);
466 const refreshDiffForWorkspaceMutation = useStableCallback(() => {
467 previewOpenHandledRef.current = true;
468 refreshBranchDiffPreview();
469 });
470​
471 // A mutation refresh also satisfies revalidation for the current opening.
472 useWorkspaceMutationRefresh({
473 enabled: canRefreshGitDiff,
474 mutationId: workspaceMutationId,
475 refresh: refreshDiffForWorkspaceMutation,
476 resourceKey: `diff:${activeThreadRefreshKey ?? ""}`,
477 });
478​
479 useEffect(() => {
480 if (!visible || !canReadFiles || !canRefreshGitDiff) {
481 previewOpenHandledRef.current = false;
482 return;
483 }
484 if (previewOpenHandledRef.current) return;
485 previewOpenHandledRef.current = true;
486 if (branchDiffPreview.data !== null && !branchDiffPreview.isPending) {
487 refreshBranchDiffPreview();
488 }
489 }, [
490 branchDiffPreview.data,
491 branchDiffPreview.isPending,
492 canReadFiles,
493 canRefreshGitDiff,
494 refreshBranchDiffPreview,
495 visible,
496 ]);
497​
498 useEffect(() => {
499 if (!canRefreshGitDiff) return;
500 const refreshOnFocus = () => refreshBranchDiffPreview();
501 window.addEventListener("focus", refreshOnFocus);
502 return () => window.removeEventListener("focus", refreshOnFocus);
503 }, [canRefreshGitDiff, refreshBranchDiffPreview]);
504​
505 const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;
506 const renderableFileEntries = renderableFiles.map(getCachedFileEntry);
507 const diffFileKeys = renderableFileEntries.map((file) => file.fileKey);
508 const defaultCollapsedDiffFileKeys = settings.diffFilesCollapsed
509 ? new Set(diffFileKeys)
510 : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
511 const storedCollapsedDiffFileKeys = useDiffPanelSessionStore((state) =>
512 collapseScopeKey ? state.collapsedFileKeysByScopeKey[collapseScopeKey] : undefined,
513 );
514 const collapsedDiffFileKeys = storedCollapsedDiffFileKeys ?? defaultCollapsedDiffFileKeys;
515 const updateCollapsedDiffFiles = (
516 update: (current: ReadonlySet<string>) => ReadonlySet<string>,
517 ) => {
518 if (!collapseScopeKey) return;
519 useDiffPanelSessionStore
520 .getState()
521 .updateCollapsedFileKeys(collapseScopeKey, defaultCollapsedDiffFileKeys, update);
522 };
523 const renderLoadingBoundary = () =>
524 settledFileCount < renderableFiles.length ? (
525 <DiffFileLoadingBoundary
526 load={loadNextFiles}
527 count={renderableFiles.length - settledFileCount}
528 />
529 ) : null;
530 const codeViewFiles = renderableFileEntries
531 .filter(
532 ({ fileDiff }) =>
533 !lazySource || !readyFilePaths || readyFilePaths.has(resolveFileDiffPath(fileDiff)),
534 )
535 .map(({ fileDiff, fileKey, fileVersion }) => ({
536 fileDiff,
537 filePath: resolveFileDiffPath(fileDiff),
538 fileKey,
539 fileVersion,
540 collapsed:
541 collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
542 }));
543 const codeViewFileKeys = codeViewFiles.map((file) => file.fileKey);
544 const pendingFiles = renderableFiles.filter((file) => file.cacheKey?.endsWith(":pending"));
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 const toggleDiffFileCollapsed = useStableCallback((fileKey: string) => {
607 updateCollapsedDiffFiles((current) => {
608 const next = new Set(current);
609 if (next.has(fileKey)) {
610 next.delete(fileKey);
611 } else {
612 next.add(fileKey);
613 }
614 return next;
615 });
616 });
617 // Find can ask again before the unfolded file reaches the viewer, so this must never fold.
618 const unfoldDiffFile = useStableCallback((fileKey: string) => {
619 updateCollapsedDiffFiles((current) => {
620 if (!current.has(fileKey)) return current;
621 const next = new Set(current);
622 next.delete(fileKey);
623 return next;
624 });
625 });
626​
627 const toggleDiffFileCollapse = () => {
628 setCodeViewRevision((current) => current + 1);
629 updateCollapsedDiffFiles((current) => toggleAllDiffFiles(diffFileKeys, current));
630 };
631​
632 const selectTurn = (runId: RunId) => {
633 if (!routeThreadRef) return;
634 useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
635 };
636 const selectGitScope = (scope: "branch" | "unstaged") => {
637 if (!routeThreadRef) return;
638 useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
639 };
640 const selectBranchBaseRef = (baseRef: string | null) => {
641 if (!routeThreadRef) return;
642 useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
643 };
644 const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : "";
645 const selectedScopeValue =
646 selectedRunId === null
647 ? selectedGitScope
648 : selectedTurn?.runId === latestTurn?.runId
649 ? "latest"
650 : selectedTurnValue;
651 const selectScopeValue = (value: string) => {
652 if (value === "unstaged" || value === "branch") {
653 selectGitScope(value);
654 } else if (value === "latest") {
655 if (latestTurn) selectTurn(latestTurn.runId);
656 } else {
657 const turn = orderedTurnDiffSummaries.find((summary) => `turn:${summary.runId}` === value);
658 if (turn) selectTurn(turn.runId);
659 }
660 };
661​
662 const headerRow = (
663 <>
664 <div className="flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
665 <DropdownMenu>
666 <DropdownMenuTrigger
667 render={<Button size="xs" variant="secondary" />}
668 className="max-w-full"
669 aria-label={`Diff scope: ${selectedScopeLabel}`}
670 >
671 <span className="truncate">{selectedScopeLabel}</span>
672 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
673 </DropdownMenuTrigger>
674 <DropdownMenuContent align="start">
675 <DropdownMenuRadioGroup value={selectedScopeValue} onValueChange={selectScopeValue}>
676 <DropdownMenuRadioItem value="branch" closeOnClick>
677 <span>Changes</span>
678 </DropdownMenuRadioItem>
679 <DropdownMenuRadioItem value="unstaged" closeOnClick>
680 <span>Uncommitted</span>
681 </DropdownMenuRadioItem>
682 <DropdownMenuRadioItem value="latest" closeOnClick>
683 <span>Latest turn</span>
684 </DropdownMenuRadioItem>
685 </DropdownMenuRadioGroup>
686 <DropdownMenuSub>
687 <DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
688 <DropdownMenuSubContent>
689 <DropdownMenuRadioGroup value={selectedTurnValue} onValueChange={selectScopeValue}>
690 {orderedTurnDiffSummaries.map((summary) => {
691 const turnCount = summary.checkpointTurnCount;
692 return (
693 <DropdownMenuRadioItem
694 key={summary.runId}
695 value={`turn:${summary.runId}`}
696 closeOnClick
697 >
698 <span className="flex items-center gap-2">
699 <span>Turn {turnCount}</span>
700 <span className="ml-auto text-xs tabular-nums text-muted-foreground">
701 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
702 </span>
703 </span>
704 </DropdownMenuRadioItem>
705 );
706 })}
707 </DropdownMenuRadioGroup>
708 </DropdownMenuSubContent>
709 </DropdownMenuSub>
710 </DropdownMenuContent>
711 </DropdownMenu>
712 {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
713 <div
714 className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
715 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
716 >
717 <Tooltip>
718 <TooltipTrigger
719 render={
720 <span className="flex min-w-[min(3rem,calc(100%-2.75rem))] items-center gap-2 overflow-hidden" />
721 }
722 >
723 <span className="min-w-0 max-w-48 truncate">
724 {selectedGitSource.headRef ?? "HEAD"}
725 </span>
726 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
727 </TooltipTrigger>
728 <TooltipPopup side="top">
729 {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
730 </TooltipPopup>
731 </Tooltip>
732 <Combobox
733 items={baseRefItems}
734 filteredItems={filteredBaseRefItems}
735 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
736 onOpenChange={(open) => {
737 if (!open) setBaseRefQuery("");
738 }}
739 onValueChange={(value) => {
740 if (!value) return;
741 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
742 }}
743 >
744 <ComboboxTrigger
745 render={<Button variant="ghost-muted" size="xs" />}
746 className="min-w-9 max-w-48 shrink"
747 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
748 >
749 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
750 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
751 </ComboboxTrigger>
752 <ComboboxPopup
753 align="start"
754 className="w-72 min-w-0 max-w-[calc(100vw-1rem)] overflow-hidden"
755 >
756 <ComboboxSearchInput
757 placeholder="Search refs..."
758 value={baseRefQuery}
759 onChange={(event) => setBaseRefQuery(event.target.value)}
760 />
761 <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">
762 <span aria-hidden="true" />
763 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
764 <span>Branch</span>
765 <span className="text-right">Remote</span>
766 </div>
767 </div>
768 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
769 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
770 <ComboboxItem
771 className="w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)]"
772 value={AUTOMATIC_BASE_REF}
773 >
774 <span className="block min-w-0 truncate">Automatic</span>
775 </ComboboxItem>
776 {baseRefChoices.map((choice) => {
777 const item = valueForBaseRefChoice(choice);
778 const hasBoth = choice.local !== null && choice.remote !== null;
779 const useRemote = choice.remote?.name === item;
780 return (
781 <ComboboxItem
782 key={choice.id}
783 className="w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)]"
784 value={item}
785 >
786 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden">
787 <span className="block min-w-0 truncate pe-2">{choice.label}</span>
788 {hasBoth ? (
789 <div
790 className="flex justify-end"
791 onClick={(event) => event.stopPropagation()}
792 onPointerDown={(event) => event.stopPropagation()}
793 >
794 <Switch
795 aria-label={`Use remote version of ${choice.label}`}
796 checked={useRemote}
797 className="[--thumb-size:--spacing(3)]"
798 onCheckedChange={(checked) => {
799 const nextRef = checked
800 ? choice.remote?.name
801 : choice.local?.name;
802 if (nextRef) selectBranchBaseRef(nextRef);
803 }}
804 />
805 </div>
806 ) : choice.remote ? (
807 <Tooltip>
808 <TooltipTrigger
809 render={
810 <span className="flex justify-end text-muted-foreground">
811 <CheckIcon
812 role="img"
813 aria-label="Remote only"
814 className="size-3"
815 />
816 </span>
817 }
818 />
819 <TooltipPopup side="top">Remote only</TooltipPopup>
820 </Tooltip>
821 ) : null}
822 </div>
823 </ComboboxItem>
824 );
825 })}
826 </ComboboxList>
827 </ComboboxPopup>
828 </Combobox>
829 </div>
830 )}
831 </div>
832 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
833 {codeViewFiles.length > 0 || (!selectedTurn && selectedGitSource?.files?.length) ? (
834 <DiffStatLabel
835 additions={diffLineStat.additions}
836 deletions={diffLineStat.deletions}
837 className="mr-1 text-2xs"
838 layout="inline"
839 />
840 ) : null}
841 {canRefreshGitDiff && (
842 <Tooltip>
843 <TooltipTrigger
844 render={
845 <Button
846 type="button"
847 size="icon-sm"
848 variant="ghost"
849 aria-label={isRefreshingDiff ? "Refreshing diff" : "Refresh diff"}
850 onClick={refreshDiffFromUserAction}
851 />
852 }
853 >
854 <RefreshIcon size="sm" refreshing={isRefreshingDiff} />
855 </TooltipTrigger>
856 <TooltipPopup side="top">
857 {isRefreshingDiff ? "Refreshing diff…" : "Refresh diff"}
858 </TooltipPopup>
859 </Tooltip>
860 )}
861 {diffFileKeys.length > 0 && (
862 <Tooltip>
863 <TooltipTrigger
864 render={
865 <Button
866 type="button"
867 size="icon-sm"
868 variant="ghost"
869 aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
870 onClick={toggleDiffFileCollapse}
871 />
872 }
873 >
874 <MorphIcon
875 className="size-3.5"
876 icon={allDiffFilesCollapsed ? ChevronsUpDown : ChevronsDownUp}
877 />
878 </TooltipTrigger>
879 <TooltipPopup side="top">
880 {allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
881 </TooltipPopup>
882 </Tooltip>
883 )}
884 <ToggleGroup
885 aria-label="Diff layout"
886 className="shrink-0"
887 variant="segmented"
888 value={[diffLayout]}
889 onValueChange={(value) => {
890 const next = value[0];
891 if (next === "stacked" || next === "split") {
892 updateClientSettings({ diffLayout: next });
893 }
894 }}
895 >
896 <Toggle aria-label="Stacked diff view" value="stacked">
897 <Rows3Icon className="size-3.5" />
898 </Toggle>
899 <Toggle aria-label="Split diff view" value="split">
900 <Columns2Icon className="size-3.5" />
901 </Toggle>
902 </ToggleGroup>
903 <Tooltip>
904 <TooltipTrigger
905 render={
906 <Toggle
907 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
908 variant="ghost"
909 size="sm"
910 pressed={wordWrap}
911 onPressedChange={(pressed) => {
912 setWordWrap(Boolean(pressed));
913 }}
914 />
915 }
916 >
917 <TextWrapIcon className="size-3.5" />
918 </TooltipTrigger>
919 <TooltipPopup side="top">
920 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
921 </TooltipPopup>
922 </Tooltip>
923 <Tooltip>
924 <TooltipTrigger
925 render={
926 <Toggle
927 aria-label={
928 diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
929 }
930 variant="ghost"
931 size="sm"
932 pressed={diffIgnoreWhitespace}
933 onPressedChange={(pressed) => {
934 setDiffIgnoreWhitespace(Boolean(pressed));
935 }}
936 />
937 }
938 >
939 <PilcrowIcon className="size-3.5" />
940 </TooltipTrigger>
941 <TooltipPopup side="top">
942 {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
943 </TooltipPopup>
944 </Tooltip>
945 {diffFileKeys.length > 0 && (
946 <Tooltip>
947 <TooltipTrigger
948 render={
949 <Toggle
950 aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}
951 variant="ghost"
952 size="sm"
953 pressed={fileTreeOpen}
954 onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}
955 />
956 }
957 >
958 <FolderTreeIcon className="size-3.5" />
959 </TooltipTrigger>
960 <TooltipPopup side="top">
961 {fileTreeOpen ? "Hide file tree" : "Show file tree"}
962 </TooltipPopup>
963 </Tooltip>
964 )}
965 </div>
966 </>
967 );
968​
969 return (
970 <DiffPanelShell mode={mode} header={headerRow}>
971 {!activeThread ? (
972 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
973 Select a thread to inspect turn diffs.
974 </div>
975 ) : !isGitRepo ? (
976 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
977 Turn diffs are unavailable because this project is not a git repository.
978 </div>
979 ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
980 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
981 No completed turns yet.
982 </div>
983 ) : selectedRunId === null && !canReadFiles ? (
984 fileAccess.isPending ? (
985 <DiffPanelLoadingState label="Checking file access..." />
986 ) : (
987 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
988 {fileAccess.error ?? "This connection cannot read local diffs."}
989 </div>
990 )
991 ) : (
992 <>
993 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
994 {isSelectedPatchTruncated && !lazySource && (
995 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
996 This preview exceeds the size limit. Changes shown are incomplete.
997 {selectedGitSource?.files ? " Totals include all changes." : ""}
998 </p>
999 )}
1000 {selectedPatchError && !renderablePatch && (
1001 <div className="px-3">
1002 <p className="mb-2 text-2xs text-error/80">{selectedPatchError}</p>
1003 </div>
1004 )}
1005 {!renderablePatch && !lazySource ? (
1006 isLoadingSelectedPatch ? (
1007 <DiffPanelLoadingState
1008 label={
1009 selectedTurn
1010 ? "Loading checkpoint diff..."
1011 : selectedGitScope === "unstaged"
1012 ? "Loading uncommitted changes..."
1013 : "Loading changes..."
1015 />
1016 ) : (
1017 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
1018 <p>
1019 {hasNoNetChanges
1020 ? "No net changes in this selection."
1021 : "No patch available for this selection."}
1022 </p>
1023 </div>
1025 ) : lazySource || renderablePatch?.kind === "files" ? (
1026 <div className="flex min-h-0 flex-1 overflow-hidden">
1027 <div
1028 className="min-h-0 min-w-0 flex-1"
1029 onClickCapture={(event) => {
1030 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1031 for (const node of composedPath) {
1032 if (!(node instanceof HTMLElement)) continue;
1033 // Header buttons own their clicks; bubbling a chevron click would toggle twice.
1034 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1035 return;
1038 const title = composedPath.find(
1039 (node): node is HTMLElement =>
1040 node instanceof HTMLElement && node.hasAttribute("data-title"),
1041 );
1042 const filePath = title?.textContent;
1043 if (filePath) {
1044 openDiffFile(filePath);
1045 return;
1047 const header = composedPath.find(
1048 (node): node is HTMLElement =>
1049 node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),
1050 );
1051 const headerFilePath = header?.querySelector("[data-title]")?.textContent;
1052 if (!headerFilePath) return;
1053 const file = codeViewFiles.find(
1054 (candidate) => candidate.filePath === headerFilePath,
1055 );
1056 if (file) toggleDiffFileCollapsed(file.fileKey);
1057 }}
1058 onContextMenuCapture={(event) => {
1059 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1060 const title = composedPath.find(
1061 (node): node is HTMLElement =>
1062 node instanceof HTMLElement && node.hasAttribute("data-title"),
1063 );
1064 const filePath = title?.textContent?.trim();
1065 if (!filePath) return;
1066 event.preventDefault();
1067 onFileContextMenu(
1069 environmentId: activeThread?.environmentId ?? null,
1070 filePath,
1071 workspaceRoot: activeCwd,
1072 repositoryRoot: activeRepositoryRoot,
1073 },
1074 event,
1075 );
1076 }}
1078 <AnnotatableCodeView
1079 key={collapseScopeKey ?? reviewSectionId}
1080 viewerRef={setCodeView}
1081 codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
1082 className="h-full min-h-0 overflow-auto"
1083 files={codeViewFiles}
1084 pendingFiles={pendingFiles}
1085 renderCodeViewFooter={renderLoadingBoundary}
1086 sectionId={reviewSectionId}
1087 sectionTitle={reviewSectionTitle}
1088 composerDraftTarget={composerDraftTarget}
1089 renderHeaderFilenameSuffix={(fileDiff) => {
1090 const path = resolveFileDiffPath(fileDiff);
1091 const state = fileStates.get(path);
1092 return (
1093 <DiffFileHeaderSuffix
1094 filePath={path}
1095 hasStat={fileStats.has(path)}
1096 error={state?.error ?? false}
1097 truncated={state?.truncated ?? false}
1098 onRetry={retry}
1099 />
1100 );
1101 }}
1102 {...(lazySource
1103 ? {
1104 unsafeCSSExtra:
1105 "[data-additions-count], [data-deletions-count] { display: none; }",
1106 renderHeaderMetadata: (fileDiff: FileDiffMetadata) => {
1107 const stat = fileStats.get(resolveFileDiffPath(fileDiff));
1108 return stat ? (
1109 <DiffStatLabel
1110 additions={stat.additions}
1111 deletions={stat.deletions}
1112 />
1113 ) : null;
1114 },
1116 : {})}
1117 onRevealSearchMatch={unfoldDiffFile}
1118 renderHeaderPrefix={(fileDiff, fileKey) => {
1119 const unavailable = fileDiff.cacheKey?.endsWith(":pending") === true;
1120 return (
1121 <DiffFileCollapseToggle
1122 filePath={resolveFileDiffPath(fileDiff)}
1123 fileKey={fileKey}
1124 collapsed={unavailable || collapsedDiffFileKeys.has(fileKey)}
1125 unavailable={unavailable}
1126 iconClassName={getDiffCollapseIconClassName(fileDiff)}
1127 onToggle={toggleDiffFileCollapsed}
1128 />
1129 );
1130 }}
1131 options={{
1132 diffStyle: diffLayout === "split" ? "split" : "unified",
1133 lineDiffType: "none",
1134 overflow: wordWrap ? "wrap" : "scroll",
1135 theme: resolveDiffThemeName(resolvedTheme),
1136 preferredHighlighter: PREFERRED_HIGHLIGHTER,
1137 themeType: resolvedTheme as DiffThemeType,
1138 stickyHeaders: true,
1139 ...(currentLoadDiffFiles ? { loadDiffFiles } : {}),
1140 }}
1141 />
1142 </div>
1143 {fileTreeOpen ? (
1144 <aside className="flex w-[min(16rem,40%)] min-w-40 shrink-0 border-l border-border/60">
1145 <DiffFileTree
1146 ariaLabel={`${reviewSectionTitle} files`}
1147 entries={fileTreeEntries}
1148 selectedPath={selectedFilePath}
1149 revealRequestId={selectedFileRevealRequestId}
1150 onSelectFile={revealDiffFile}
1151 />
1152 </aside>
1153 ) : null}
1154 </div>
1155 ) : (
1156 <div className="min-h-0 flex-1 overflow-auto p-2">
1157 <div className="space-y-2">
1158 <p className="text-2xs text-muted-foreground/75">
1159 {renderablePatch?.kind === "raw" ? renderablePatch.reason : null}
1160 </p>
1161 <pre
1162 className={cn(
1163 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-2xs leading-relaxed text-muted-foreground/90",
1164 wordWrap
1165 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
1166 : "overflow-auto",
1167 )}
1169 {renderablePatch?.kind === "raw" ? renderablePatch.text : null}
1170 </pre>
1171 </div>
1172 </div>
1173 )}
1174 </div>
1175 </>
1176 )}
1177 </DiffPanelShell>
1178 );