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

DiffPanel.tsx

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