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