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

DiffPanel.tsx

1,184 lines47.4 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 // 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 pendingFiles = renderableFiles.filter((file) => file.cacheKey?.endsWith(":pending"));
546 const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
547 const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
548 const fileTreeEntries = diffFileTreeEntries(renderableFiles);
549 const treeRevealScope = { collapseScopeKey, diffSelection };
550 const requestTreeReveal = useCodeViewFileReveal(codeView, treeRevealScope, codeViewFileKeys);
551 const revealDiffFile = (filePath: string) => {
552 const index = renderableFileEntries.findIndex(
553 (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
554 );
555 const file = renderableFileEntries[index];
556 if (!file) return false;
557 updateCollapsedDiffFiles((current) => {
558 const next = new Set(current);
559 next.delete(file.fileKey);
560 return next;
561 });
562 if (lazySource && index >= settledFileCount) {
563 requestFile(index);
564 }
565 requestTreeReveal(file.fileKey);
566 return true;
567 };
568​
569 const externalRevealRef = useRef<string | null>(null);
570 useEffect(() => {
571 if (!selectedFilePath) {
572 externalRevealRef.current = null;
573 return;
574 }
575 const key = JSON.stringify([collapseScopeKey, selectedFilePath, selectedFileRevealRequestId]);
576 if (externalRevealRef.current === key) return;
577 if (revealDiffFile(selectedFilePath)) {
578 externalRevealRef.current = key;
579 }
580 }, [collapseScopeKey, selectedFilePath, selectedFileRevealRequestId, revealDiffFile]);
581​
582 const openDiffFile = (filePath: string) => {
583 openDiffFilePrimaryAction({
584 threadRef: routeThreadRef,
585 filePath,
586 activeCwd,
587 repositoryRoot: activeRepositoryRoot,
588 openInEditor: (targetPath) => {
589 void (async () => {
590 const result = await openInPreferredEditor(targetPath);
591 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
592 console.warn("Failed to open diff file in editor.", {
593 operation: "open-diff-file",
594 ...(routeThreadRef
595 ? {
596 environmentId: routeThreadRef.environmentId,
597 threadId: routeThreadRef.threadId,
598 }
599 : {}),
600 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
601 });
602 }
603 })();
604 },
605 });
606 };
607 // Every file header holds these; a new identity per collapse change would redraw them all.
608 const toggleDiffFileCollapsed = useStableCallback((fileKey: string) => {
609 updateCollapsedDiffFiles((current) => {
610 const next = new Set(current);
611 if (next.has(fileKey)) {
612 next.delete(fileKey);
613 } else {
614 next.add(fileKey);
615 }
616 return next;
617 });
618 });
619 // Find can ask again before the unfolded file reaches the viewer, so this must never fold.
620 const unfoldDiffFile = useStableCallback((fileKey: string) => {
621 updateCollapsedDiffFiles((current) => {
622 if (!current.has(fileKey)) return current;
623 const next = new Set(current);
624 next.delete(fileKey);
625 return next;
626 });
627 });
628​
629 const toggleDiffFileCollapse = () => {
630 setCodeViewRevision((current) => current + 1);
631 updateCollapsedDiffFiles((current) => toggleAllDiffFiles(diffFileKeys, current));
632 };
633​
634 const selectTurn = (runId: RunId) => {
635 if (!routeThreadRef) return;
636 useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
637 };
638 const selectGitScope = (scope: "branch" | "unstaged") => {
639 if (!routeThreadRef) return;
640 useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
641 };
642 const selectBranchBaseRef = (baseRef: string | null) => {
643 if (!routeThreadRef) return;
644 useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
645 };
646 const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : "";
647 const selectedScopeValue =
648 selectedRunId === null
649 ? selectedGitScope
650 : selectedTurn?.runId === latestTurn?.runId
651 ? "latest"
652 : selectedTurnValue;
653 const selectScopeValue = (value: string) => {
654 if (value === "unstaged" || value === "branch") {
655 selectGitScope(value);
656 } else if (value === "latest") {
657 if (latestTurn) selectTurn(latestTurn.runId);
658 } else {
659 const turn = orderedTurnDiffSummaries.find((summary) => `turn:${summary.runId}` === value);
660 if (turn) selectTurn(turn.runId);
661 }
662 };
663​
664 const headerRow = (
665 <>
666 <div className="flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
667 <DropdownMenu>
668 <DropdownMenuTrigger
669 render={<Button size="xs" variant="secondary" />}
670 className="max-w-full"
671 aria-label={`Diff scope: ${selectedScopeLabel}`}
672 >
673 <span className="truncate">{selectedScopeLabel}</span>
674 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
675 </DropdownMenuTrigger>
676 <DropdownMenuContent align="start">
677 <DropdownMenuRadioGroup value={selectedScopeValue} onValueChange={selectScopeValue}>
678 <DropdownMenuRadioItem value="branch" closeOnClick>
679 <span>Changes</span>
680 </DropdownMenuRadioItem>
681 <DropdownMenuRadioItem value="unstaged" closeOnClick>
682 <span>Uncommitted</span>
683 </DropdownMenuRadioItem>
684 <DropdownMenuRadioItem value="latest" closeOnClick>
685 <span>Latest turn</span>
686 </DropdownMenuRadioItem>
687 </DropdownMenuRadioGroup>
688 <DropdownMenuSub>
689 <DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
690 <DropdownMenuSubContent>
691 <DropdownMenuRadioGroup value={selectedTurnValue} onValueChange={selectScopeValue}>
692 {orderedTurnDiffSummaries.map((summary) => {
693 const turnCount = summary.checkpointTurnCount;
694 return (
695 <DropdownMenuRadioItem
696 key={summary.runId}
697 value={`turn:${summary.runId}`}
698 closeOnClick
699 >
700 <span className="flex items-center gap-2">
701 <span>Turn {turnCount}</span>
702 <span className="ml-auto text-xs tabular-nums text-muted-foreground">
703 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
704 </span>
705 </span>
706 </DropdownMenuRadioItem>
707 );
708 })}
709 </DropdownMenuRadioGroup>
710 </DropdownMenuSubContent>
711 </DropdownMenuSub>
712 </DropdownMenuContent>
713 </DropdownMenu>
714 {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
715 <div
716 className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
717 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
718 >
719 {/* The head ref keeps 3rem while the row has room; below that the
720 base-ref button keeps 2.25rem so its menu stays reachable. */}
721 <Tooltip>
722 <TooltipTrigger
723 render={
724 <span className="flex min-w-[min(3rem,calc(100%-2.75rem))] items-center gap-2 overflow-hidden" />
725 }
726 >
727 <span className="min-w-0 max-w-48 truncate">
728 {selectedGitSource.headRef ?? "HEAD"}
729 </span>
730 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
731 </TooltipTrigger>
732 <TooltipPopup side="top">
733 {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
734 </TooltipPopup>
735 </Tooltip>
736 <Combobox
737 items={baseRefItems}
738 filteredItems={filteredBaseRefItems}
739 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
740 onOpenChange={(open) => {
741 if (!open) setBaseRefQuery("");
742 }}
743 onValueChange={(value) => {
744 if (!value) return;
745 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
746 }}
747 >
748 <ComboboxTrigger
749 render={<Button variant="ghost-muted" size="xs" />}
750 className="min-w-9 max-w-48 shrink"
751 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
752 >
753 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
754 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
755 </ComboboxTrigger>
756 <ComboboxPopup
757 align="start"
758 className="w-72 min-w-0 max-w-[calc(100vw-1rem)] overflow-hidden"
759 >
760 <ComboboxSearchInput
761 placeholder="Search refs..."
762 value={baseRefQuery}
763 onChange={(event) => setBaseRefQuery(event.target.value)}
764 />
765 <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">
766 <span aria-hidden="true" />
767 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
768 <span>Branch</span>
769 <span className="text-right">Remote</span>
770 </div>
771 </div>
772 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
773 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
774 <ComboboxItem
775 className="w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)]"
776 value={AUTOMATIC_BASE_REF}
777 >
778 <span className="block min-w-0 truncate">Automatic</span>
779 </ComboboxItem>
780 {baseRefChoices.map((choice) => {
781 const item = valueForBaseRefChoice(choice);
782 const hasBoth = choice.local !== null && choice.remote !== null;
783 const useRemote = choice.remote?.name === item;
784 return (
785 <ComboboxItem
786 key={choice.id}
787 className="w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)]"
788 value={item}
789 >
790 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden">
791 <span className="block min-w-0 truncate pe-2">{choice.label}</span>
792 {hasBoth ? (
793 <div
794 className="flex justify-end"
795 onClick={(event) => event.stopPropagation()}
796 onPointerDown={(event) => event.stopPropagation()}
797 >
798 <Switch
799 aria-label={`Use remote version of ${choice.label}`}
800 checked={useRemote}
801 className="[--thumb-size:--spacing(3)]"
802 onCheckedChange={(checked) => {
803 const nextRef = checked
804 ? choice.remote?.name
805 : choice.local?.name;
806 if (nextRef) selectBranchBaseRef(nextRef);
807 }}
808 />
809 </div>
810 ) : choice.remote ? (
811 <Tooltip>
812 <TooltipTrigger
813 render={
814 <span className="flex justify-end text-muted-foreground">
815 <CheckIcon
816 role="img"
817 aria-label="Remote only"
818 className="size-3"
819 />
820 </span>
821 }
822 />
823 <TooltipPopup side="top">Remote only</TooltipPopup>
824 </Tooltip>
825 ) : null}
826 </div>
827 </ComboboxItem>
828 );
829 })}
830 </ComboboxList>
831 </ComboboxPopup>
832 </Combobox>
833 </div>
834 )}
835 </div>
836 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
837 {codeViewFiles.length > 0 || (!selectedTurn && selectedGitSource?.files?.length) ? (
838 <DiffStatLabel
839 additions={diffLineStat.additions}
840 deletions={diffLineStat.deletions}
841 className="mr-1 text-2xs"
842 layout="inline"
843 />
844 ) : null}
845 {canRefreshGitDiff && (
846 <Tooltip>
847 <TooltipTrigger
848 render={
849 <Button
850 type="button"
851 size="icon-sm"
852 variant="ghost"
853 aria-label={isRefreshingDiff ? "Refreshing diff" : "Refresh diff"}
854 onClick={refreshDiffFromUserAction}
855 />
856 }
857 >
858 <RefreshIcon size="sm" refreshing={isRefreshingDiff} />
859 </TooltipTrigger>
860 <TooltipPopup side="top">
861 {isRefreshingDiff ? "Refreshing diff…" : "Refresh diff"}
862 </TooltipPopup>
863 </Tooltip>
864 )}
865 {diffFileKeys.length > 0 && (
866 <Tooltip>
867 <TooltipTrigger
868 render={
869 <Button
870 type="button"
871 size="icon-sm"
872 variant="ghost"
873 aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
874 onClick={toggleDiffFileCollapse}
875 />
876 }
877 >
878 <MorphIcon
879 className="size-3.5"
880 icon={allDiffFilesCollapsed ? ChevronsUpDown : ChevronsDownUp}
881 />
882 </TooltipTrigger>
883 <TooltipPopup side="top">
884 {allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
885 </TooltipPopup>
886 </Tooltip>
887 )}
888 <ToggleGroup
889 aria-label="Diff layout"
890 className="shrink-0"
891 variant="segmented"
892 value={[diffLayout]}
893 onValueChange={(value) => {
894 const next = value[0];
895 if (next === "stacked" || next === "split") {
896 updateClientSettings({ diffLayout: next });
897 }
898 }}
899 >
900 <Toggle aria-label="Stacked diff view" value="stacked">
901 <Rows3Icon className="size-3.5" />
902 </Toggle>
903 <Toggle aria-label="Split diff view" value="split">
904 <Columns2Icon className="size-3.5" />
905 </Toggle>
906 </ToggleGroup>
907 <Tooltip>
908 <TooltipTrigger
909 render={
910 <Toggle
911 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
912 variant="ghost"
913 size="sm"
914 pressed={wordWrap}
915 onPressedChange={(pressed) => {
916 setWordWrap(Boolean(pressed));
917 }}
918 />
919 }
920 >
921 <TextWrapIcon className="size-3.5" />
922 </TooltipTrigger>
923 <TooltipPopup side="top">
924 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
925 </TooltipPopup>
926 </Tooltip>
927 <Tooltip>
928 <TooltipTrigger
929 render={
930 <Toggle
931 aria-label={
932 diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
933 }
934 variant="ghost"
935 size="sm"
936 pressed={diffIgnoreWhitespace}
937 onPressedChange={(pressed) => {
938 setDiffIgnoreWhitespace(Boolean(pressed));
939 }}
940 />
941 }
942 >
943 <PilcrowIcon className="size-3.5" />
944 </TooltipTrigger>
945 <TooltipPopup side="top">
946 {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
947 </TooltipPopup>
948 </Tooltip>
949 {diffFileKeys.length > 0 && (
950 <Tooltip>
951 <TooltipTrigger
952 render={
953 <Toggle
954 aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}
955 variant="ghost"
956 size="sm"
957 pressed={fileTreeOpen}
958 onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}
959 />
960 }
961 >
962 <FolderTreeIcon className="size-3.5" />
963 </TooltipTrigger>
964 <TooltipPopup side="top">
965 {fileTreeOpen ? "Hide file tree" : "Show file tree"}
966 </TooltipPopup>
967 </Tooltip>
968 )}
969 </div>
970 </>
971 );
972​
973 return (
974 <DiffPanelShell mode={mode} header={headerRow}>
975 {!activeThread ? (
976 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
977 Select a thread to inspect turn diffs.
978 </div>
979 ) : !isGitRepo ? (
980 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
981 Turn diffs are unavailable because this project is not a git repository.
982 </div>
983 ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
984 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
985 No completed turns yet.
986 </div>
987 ) : selectedRunId === null && !canReadFiles ? (
988 fileAccess.isPending ? (
989 <DiffPanelLoadingState label="Checking file access..." />
990 ) : (
991 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
992 {fileAccess.error ?? "This connection cannot read local diffs."}
993 </div>
994 )
995 ) : (
996 <>
997 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
998 {isSelectedPatchTruncated && !lazySource && (
999 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
1000 This preview exceeds the size limit. Changes shown are incomplete.
1001 {selectedGitSource?.files ? " Totals include all changes." : ""}
1002 </p>
1003 )}
1004 {selectedPatchError && !renderablePatch && (
1005 <div className="px-3">
1006 <p className="mb-2 text-2xs text-error/80">{selectedPatchError}</p>
1007 </div>
1008 )}
1009 {!renderablePatch && !lazySource ? (
1010 isLoadingSelectedPatch ? (
1011 <DiffPanelLoadingState
1012 label={
1013 selectedTurn
1014 ? "Loading checkpoint diff..."
1015 : selectedGitScope === "unstaged"
1016 ? "Loading uncommitted changes..."
1017 : "Loading changes..."
1019 />
1020 ) : (
1021 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
1022 <p>
1023 {hasNoNetChanges
1024 ? "No net changes in this selection."
1025 : "No patch available for this selection."}
1026 </p>
1027 </div>
1029 ) : lazySource || renderablePatch?.kind === "files" ? (
1030 <div className="flex min-h-0 flex-1 overflow-hidden">
1031 <div
1032 className="min-h-0 min-w-0 flex-1"
1033 onClickCapture={(event) => {
1034 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1035 for (const node of composedPath) {
1036 if (!(node instanceof HTMLElement)) continue;
1037 // Header controls keep their own actions. In particular, the chevron must
1038 // not also trigger the row handler or the two toggles cancel each other.
1039 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1040 return;
1043 const title = composedPath.find(
1044 (node): node is HTMLElement =>
1045 node instanceof HTMLElement && node.hasAttribute("data-title"),
1046 );
1047 const filePath = title?.textContent;
1048 if (filePath) {
1049 openDiffFile(filePath);
1050 return;
1052 const header = composedPath.find(
1053 (node): node is HTMLElement =>
1054 node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),
1055 );
1056 const headerFilePath = header?.querySelector("[data-title]")?.textContent;
1057 if (!headerFilePath) return;
1058 const file = codeViewFiles.find(
1059 (candidate) => candidate.filePath === headerFilePath,
1060 );
1061 if (file) toggleDiffFileCollapsed(file.fileKey);
1062 }}
1063 onContextMenuCapture={(event) => {
1064 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1065 const title = composedPath.find(
1066 (node): node is HTMLElement =>
1067 node instanceof HTMLElement && node.hasAttribute("data-title"),
1068 );
1069 const filePath = title?.textContent?.trim();
1070 if (!filePath) return;
1071 event.preventDefault();
1072 onFileContextMenu(
1074 environmentId: activeThread?.environmentId ?? null,
1075 filePath,
1076 workspaceRoot: activeCwd,
1077 repositoryRoot: activeRepositoryRoot,
1078 },
1079 event,
1080 );
1081 }}
1083 <AnnotatableCodeView
1084 key={collapseScopeKey ?? reviewSectionId}
1085 viewerRef={setCodeView}
1086 codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
1087 className="h-full min-h-0 overflow-auto"
1088 files={codeViewFiles}
1089 pendingFiles={pendingFiles}
1090 renderCodeViewFooter={renderLoadingBoundary}
1091 sectionId={reviewSectionId}
1092 sectionTitle={reviewSectionTitle}
1093 composerDraftTarget={composerDraftTarget}
1094 renderHeaderFilenameSuffix={(fileDiff) => {
1095 const path = resolveFileDiffPath(fileDiff);
1096 const state = fileStates.get(path);
1097 return (
1098 <DiffFileHeaderSuffix
1099 filePath={path}
1100 hasStat={fileStats.has(path)}
1101 error={state?.error ?? false}
1102 truncated={state?.truncated ?? false}
1103 onRetry={retry}
1104 />
1105 );
1106 }}
1107 {...(lazySource
1108 ? {
1109 unsafeCSSExtra:
1110 "[data-additions-count], [data-deletions-count] { display: none; }",
1111 renderHeaderMetadata: (fileDiff: FileDiffMetadata) => {
1112 const stat = fileStats.get(resolveFileDiffPath(fileDiff));
1113 return stat ? (
1114 <DiffStatLabel
1115 additions={stat.additions}
1116 deletions={stat.deletions}
1117 />
1118 ) : null;
1119 },
1121 : {})}
1122 onRevealSearchMatch={unfoldDiffFile}
1123 renderHeaderPrefix={(fileDiff, fileKey) => {
1124 const unavailable = fileDiff.cacheKey?.endsWith(":pending") === true;
1125 return (
1126 <DiffFileCollapseToggle
1127 filePath={resolveFileDiffPath(fileDiff)}
1128 fileKey={fileKey}
1129 collapsed={unavailable || collapsedDiffFileKeys.has(fileKey)}
1130 unavailable={unavailable}
1131 iconClassName={getDiffCollapseIconClassName(fileDiff)}
1132 onToggle={toggleDiffFileCollapsed}
1133 />
1134 );
1135 }}
1136 options={{
1137 diffStyle: diffLayout === "split" ? "split" : "unified",
1138 lineDiffType: "none",
1139 overflow: wordWrap ? "wrap" : "scroll",
1140 theme: resolveDiffThemeName(resolvedTheme),
1141 preferredHighlighter: PREFERRED_HIGHLIGHTER,
1142 themeType: resolvedTheme as DiffThemeType,
1143 stickyHeaders: true,
1144 ...(currentLoadDiffFiles ? { loadDiffFiles } : {}),
1145 }}
1146 />
1147 </div>
1148 {fileTreeOpen ? (
1149 <aside className="flex w-[min(16rem,40%)] min-w-40 shrink-0 border-l border-border/60">
1150 <DiffFileTree
1151 ariaLabel={`${reviewSectionTitle} files`}
1152 entries={fileTreeEntries}
1153 selectedPath={selectedFilePath}
1154 revealRequestId={selectedFileRevealRequestId}
1155 onSelectFile={revealDiffFile}
1156 />
1157 </aside>
1158 ) : null}
1159 </div>
1160 ) : (
1161 <div className="min-h-0 flex-1 overflow-auto p-2">
1162 <div className="space-y-2">
1163 <p className="text-2xs text-muted-foreground/75">
1164 {renderablePatch?.kind === "raw" ? renderablePatch.reason : null}
1165 </p>
1166 <pre
1167 className={cn(
1168 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-2xs leading-relaxed text-muted-foreground/90",
1169 wordWrap
1170 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
1171 : "overflow-auto",
1172 )}
1174 {renderablePatch?.kind === "raw" ? renderablePatch.text : null}
1175 </pre>
1176 </div>
1177 </div>
1178 )}
1179 </div>
1180 </>
1181 )}
1182 </DiffPanelShell>
1183 );