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

DiffPanel.tsx

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