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

DiffPanel.tsx

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