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

DiffPanel.tsx

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