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

DiffPanel.tsx

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