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

DiffPanel.tsx

1,155 lines47.5 KB

1import { useAtomValue } from "@effect/atom-react";
2import type { FileDiffContentsLoader } from "@pierre/diffs";
3import { useParams } from "@tanstack/react-router";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
9import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
10import {
11 ArrowRightIcon,
12 CheckIcon,
13 ChevronDownIcon,
14 ChevronRightIcon,
15 ChevronsDownUpIcon,
16 ChevronsUpDownIcon,
17 Columns2Icon,
18 FolderTreeIcon,
19 PilcrowIcon,
20 RefreshCwIcon,
21 Rows3Icon,
22 SearchIcon,
23 TextWrapIcon,
24} from "lucide-react";
25import * as Schema from "effect/Schema";
26import { useCallback, useEffect, useMemo, useRef, useState } from "react";
27import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
28import { useOpenInPreferredEditor } from "../editorPreferences";
29import { type DraftId } from "../composerDraftStore";
30import { openDiffFilePrimaryAction } from "../diffFileActions";
31import { useCheckpointDiff } from "~/lib/checkpointDiffState";
32import { cn } from "~/lib/utils";
33import {
34 type DiffBaseline,
35 getCheckpointDiffRange,
36 THREAD_START_DIFF_BASELINE,
37 selectThreadDiffPanelSelection,
38 useDiffPanelStore,
39} from "../diffPanelStore";
40import { useLocalStorage } from "../hooks/useLocalStorage";
41import { useTheme } from "../hooks/useTheme";
42import {
43 buildFileDiffContentVersion,
44 buildFileDiffIdentityKey,
45 getDiffCollapseIconClassName,
46 getDiffLineStat,
47 getRenderablePatch,
48 resolveDiffThemeName,
49 resolveFileDiffPath,
50} from "../lib/diffRendering";
51import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
52import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
53import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
54import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
55import { useProject, useThread } from "../state/entities";
56import { resolveThreadRouteRef } from "../threadRoutes";
57import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings";
58import { formatShortTimestamp } from "../timestampFormat";
59import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
60import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
61import { DiffStatLabel } from "./chat/DiffStatLabel";
62import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
63import { DiffFileTree } from "./diffs/DiffFileTree";
64import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";
65import { Button } from "./ui/button";
66import { ToggleGroup, Toggle } from "./ui/toggle-group";
67import { Switch } from "./ui/switch";
68import {
69 Combobox,
70 ComboboxEmpty,
71 ComboboxInput,
72 ComboboxItem,
73 ComboboxList,
74 ComboboxPopup,
75 ComboboxTrigger,
76} from "./ui/combobox";
77import {
78 DropdownMenu,
79 DropdownMenuContent,
80 DropdownMenuItem,
81 DropdownMenuSub,
82 DropdownMenuSubContent,
83 DropdownMenuSubTrigger,
84 DropdownMenuTrigger,
85} from "./ui/menu";
86import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
87import { useEnvironmentQuery } from "../state/query";
88import { useAtomCommand } from "../state/use-atom-command";
89import { serverEnvironment } from "../state/server";
90import { reviewEnvironment } from "../state/review";
91import { vcsEnvironment } from "../state/vcs";
92import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
93import { createGitDiffFileContentsLoader } from "../lib/diffFileContents";
94​
95type DiffThemeType = "light" | "dark";
96const AUTOMATIC_BASE_REF = "__automatic_base_ref__";
97const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen";
98​
99interface CollapsedDiffFilesState {
100 readonly scopeKey: string | null;
101 readonly fileKeys: ReadonlySet<string>;
103​
104const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
105​
106interface DiffPanelProps {
107 mode?: DiffPanelMode;
108 composerDraftTarget: ScopedThreadRef | DraftId;
109 initialGitScope: "branch" | "unstaged";
110 workspaceMutationId: string | null;
112​
113export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
114​
115export default function DiffPanel({
116 mode = "inline",
117 composerDraftTarget,
118 initialGitScope: initialGitScopeProp,
119 workspaceMutationId,
120}: DiffPanelProps) {
121 const { resolvedTheme } = useTheme();
122 const settings = useClientSettings();
123 const [initialGitScope] = useState(initialGitScopeProp);
124 const diffLayout = settings.diffLayout;
125 const updateClientSettings = useUpdateClientSettings();
126 const [wordWrap, setWordWrap] = useState(settings.wordWrap);
127 const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
128 const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(
129 DIFF_FILE_TREE_STORAGE_KEY,
130 false,
131 Schema.Boolean,
132 );
133 const [baseRefQuery, setBaseRefQuery] = useState("");
134 const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
135 scopeKey: null,
136 fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS,
137 }));
138 const [codeViewRevision, setCodeViewRevision] = useState(0);
139 const [codeView, setCodeView] = useState<AnnotatableCodeViewHandle | null>(null);
140​
141 const routeThreadRef = useParams({
142 strict: false,
143 select: (params) => resolveThreadRouteRef(params),
144 });
145 const activeThreadId = routeThreadRef?.threadId ?? null;
146 const activeThread = useThread(routeThreadRef);
147 const activeProjectId = activeThread?.projectId ?? null;
148 const activeProject = useProject(
149 activeThread && activeProjectId
150 ? {
151 environmentId: activeThread.environmentId,
152 projectId: activeProjectId,
153 }
154 : null,
155 );
156 const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot;
157 const activeRepositoryRoot = activeThread?.worktreePath
158 ? undefined
159 : activeProject?.repositoryIdentity?.rootPath;
160 const serverConfig = useAtomValue(
161 serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),
162 );
163 const openInPreferredEditor = useOpenInPreferredEditor(
164 activeThread?.environmentId ?? null,
165 serverConfig?.availableEditors ?? [],
166 );
167 const getDiffFileContents = useAtomCommand(reviewEnvironment.diffFileContents);
168 const gitStatusQuery = useEnvironmentQuery(
169 activeThread !== null && activeThread !== undefined && activeCwd != null
170 ? vcsEnvironment.status({
171 environmentId: activeThread.environmentId,
172 input: { cwd: activeCwd },
173 })
174 : null,
175 );
176 const diffSelection = useDiffPanelStore((state) =>
177 selectThreadDiffPanelSelection(
178 state.byThreadKey,
179 routeThreadRef,
180 initialGitScope === "unstaged",
181 ),
182 );
183 const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
184 const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
185 useTurnDiffSummaries(activeThread);
186 const orderedTurnDiffSummaries = useMemo(
187 () =>
188 [...turnDiffSummaries].toSorted((left, right) => {
189 const leftTurnCount =
190 left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
191 const rightTurnCount =
192 right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
193 if (leftTurnCount !== rightTurnCount) {
194 return rightTurnCount - leftTurnCount;
195 }
196 return right.completedAt.localeCompare(left.completedAt);
197 }),
198 [inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
199 );
200​
201 useEffect(() => {
202 if (!routeThreadRef || !activeThread || diffSelection.kind !== "turn") return;
203 useDiffPanelStore.getState().reconcileTurnSelection(
204 routeThreadRef,
205 orderedTurnDiffSummaries.map((summary) => summary.turnId),
206 );
207 }, [activeThread, diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
208​
209 const selectedTurnId =
210 diffSelection.kind === "turn"
211 ? diffSelection.followLatest
212 ? (orderedTurnDiffSummaries[0]?.turnId ?? diffSelection.turnId)
213 : diffSelection.turnId
214 : null;
215 const baselineTurnId = diffSelection.kind === "turn" ? diffSelection.baselineTurnId : undefined;
216 const baselineTurn = orderedTurnDiffSummaries.find(
217 (summary) => summary.turnId === baselineTurnId,
218 );
219 const baselineTurnCount =
220 baselineTurnId === THREAD_START_DIFF_BASELINE ? 0 : baselineTurn?.checkpointTurnCount;
221 const followsLatest = diffSelection.kind === "turn" && diffSelection.followLatest === true;
222 const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch";
223 const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null;
224 const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
225 const selectedFileRevealRequestId =
226 diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
227 const selectedTurn =
228 selectedTurnId === null
229 ? undefined
230 : (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
231 orderedTurnDiffSummaries[0]);
232 const selectedCheckpointTurnCount =
233 selectedTurn &&
234 (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
235 const latestTurn = orderedTurnDiffSummaries[0];
236 const [baselineMenuOpen, setBaselineMenuOpen] = useState(false);
237 const firstCheckpoint = orderedTurnDiffSummaries.findLast(
238 (summary) => summary.status === "ready" && summary.checkpointTurnCount > 0,
239 );
240 // A completion checkpoint can exist without Turn 0 when Git was initialized mid-turn.
241 // Check the earliest available range only when the baseline menu is opened.
242 const initialCheckpointDiff = useCheckpointDiff(
243 {
244 environmentId: activeThread?.environmentId ?? null,
245 threadId: activeThread?.id ?? null,
246 fromTurnCount: 0,
247 toTurnCount: firstCheckpoint?.checkpointTurnCount ?? null,
248 ignoreWhitespace: true,
249 },
250 { enabled: baselineMenuOpen && isGitRepo },
251 );
252 const isLatestTurnSelection =
253 baselineTurnCount === undefined ? selectedTurn?.turnId === latestTurn?.turnId : followsLatest;
254 const selectedScopeLabel =
255 selectedTurnId === null
256 ? selectedGitScope === "unstaged"
257 ? "Working tree"
258 : "Branch changes"
259 : isLatestTurnSelection
260 ? "Latest turn"
261 : `Turn ${selectedCheckpointTurnCount ?? "?"}`;
262 const comparisonLabel =
263 baselineTurnCount !== undefined
264 ? `Turn ${baselineTurnCount} → ${selectedScopeLabel}`
265 : selectedScopeLabel;
266 const reviewSectionId = selectedTurn
267 ? baselineTurnCount !== undefined
268 ? `turn:${baselineTurnId}:${selectedTurn.turnId}`
269 : `turn:${selectedTurn.turnId}`
270 : selectedGitScope;
271 const collapseScopeKey = routeThreadRef
272 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
273 : null;
274 const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
275 const collapsedDiffFileKeys =
276 collapsedDiffFiles.scopeKey === collapseScopeKey
277 ? collapsedDiffFiles.fileKeys
278 : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
279 const reviewSectionTitle = selectedTurn
280 ? baselineTurnCount !== undefined
281 ? comparisonLabel
282 : `Turn ${selectedCheckpointTurnCount ?? "?"}`
283 : selectedGitScope === "unstaged"
284 ? "Working tree"
285 : "Branch changes";
286 const selectedCheckpointRange = getCheckpointDiffRange(
287 selectedCheckpointTurnCount,
288 baselineTurnCount,
289 );
290 const activeCheckpointDiff = useCheckpointDiff(
291 {
292 environmentId: activeThread?.environmentId ?? null,
293 threadId: activeThreadId,
294 fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
295 toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
296 ignoreWhitespace: diffIgnoreWhitespace,
297 cacheScope: selectedTurn ? reviewSectionId : null,
298 },
299 { enabled: isGitRepo && selectedTurn !== undefined },
300 );
301 const primaryBranchDiffPreview = useEnvironmentQuery(
302 selectedTurnId === null && activeThread && activeCwd
303 ? reviewEnvironment.diffPreview({
304 environmentId: activeThread.environmentId,
305 input: {
306 cwd: activeCwd,
307 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
308 ignoreWhitespace: diffIgnoreWhitespace,
309 },
310 })
311 : null,
312 );
313 const shouldRetryBranchDiffAtEnvironmentCwd =
314 selectedTurnId === null &&
315 primaryBranchDiffPreview.error?.includes("configured workspace root") === true &&
316 serverConfig?.cwd !== undefined &&
317 serverConfig.cwd !== activeCwd;
318 const fallbackBranchDiffPreview = useEnvironmentQuery(
319 shouldRetryBranchDiffAtEnvironmentCwd && activeThread && serverConfig
320 ? reviewEnvironment.diffPreview({
321 environmentId: activeThread.environmentId,
322 input: {
323 cwd: serverConfig.cwd,
324 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
325 ignoreWhitespace: diffIgnoreWhitespace,
326 },
327 })
328 : null,
329 );
330 const branchDiffPreview = shouldRetryBranchDiffAtEnvironmentCwd
331 ? fallbackBranchDiffPreview
332 : primaryBranchDiffPreview;
333 const refreshBranchDiffPreview = branchDiffPreview.refresh;
334 const canRefreshGitDiff =
335 isGitRepo && selectedTurnId === null && activeThread != null && activeCwd != null;
336 const activeThreadRefreshKey = routeThreadRef
337 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
338 : null;
339​
340 useEffect(() => {
341 if (!canRefreshGitDiff) return;
342 const refreshOnFocus = () => refreshBranchDiffPreview();
343 window.addEventListener("focus", refreshOnFocus);
344 return () => window.removeEventListener("focus", refreshOnFocus);
345 }, [canRefreshGitDiff, refreshBranchDiffPreview]);
346​
347 useWorkspaceMutationRefresh({
348 enabled: canRefreshGitDiff,
349 mutationId: workspaceMutationId,
350 refresh: refreshBranchDiffPreview,
351 resourceKey: `diff:${activeThreadRefreshKey ?? ""}`,
352 });
353​
354 const selectedGitSource = branchDiffPreview.data?.sources.find(
355 (source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
356 );
357 const currentLoadDiffFiles = useMemo<FileDiffContentsLoader | undefined>(() => {
358 const preview = branchDiffPreview.data;
359 if (selectedTurnId !== null || !activeThread || !preview || !selectedGitSource) {
360 return undefined;
361 }
362​
363 return createGitDiffFileContentsLoader(getDiffFileContents, {
364 environmentId: activeThread.environmentId,
365 cwd: preview.cwd,
366 sourceKind: selectedGitSource.kind,
367 baseRef: selectedGitSource.baseRef,
368 headRef: selectedGitSource.headRef,
369 cacheKey: selectedGitSource.diffHash,
370 });
371 }, [
372 activeThread,
373 branchDiffPreview.data,
374 getDiffFileContents,
375 selectedGitSource,
376 selectedTurnId,
377 ]);
378 const loadDiffFilesRef = useRef(currentLoadDiffFiles);
379 loadDiffFilesRef.current = currentLoadDiffFiles;
380 const loadDiffFiles = useCallback<FileDiffContentsLoader>(async (fileDiff) => {
381 const loader = loadDiffFilesRef.current;
382 if (!loader) throw new Error("Diff file contents are unavailable for this selection.");
383 return loader(fileDiff);
384 }, []);
385 const localBranchRefs = useEnvironmentQuery(
386 selectedTurnId === null &&
387 selectedGitScope === "branch" &&
388 activeThread &&
389 branchDiffPreview.data?.cwd
390 ? vcsEnvironment.listRefs({
391 environmentId: activeThread.environmentId,
392 input: {
393 cwd: branchDiffPreview.data.cwd,
394 includeMatchingRemoteRefs: true,
395 refKind: "local",
396 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
397 limit: 100,
398 },
399 })
400 : null,
401 );
402 const remoteBranchRefs = useEnvironmentQuery(
403 selectedTurnId === 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: "remote",
413 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
414 limit: 100,
415 },
416 })
417 : null,
418 );
419 const baseRefChoices = buildBaseRefChoices(
420 localBranchRefs.data?.refs.filter((ref) => ref.name !== selectedGitSource?.headRef) ?? [],
421 remoteBranchRefs.data?.refs ?? [],
422 );
423 const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery);
424 const valueForBaseRefChoice = (choice: (typeof baseRefChoices)[number]) =>
425 selectedBaseRef && selectedBaseRef === choice.remote?.name
426 ? selectedBaseRef
427 : (choice.local?.name ?? choice.remote?.name ?? choice.id);
428 const baseRefItems = [AUTOMATIC_BASE_REF, ...baseRefChoices.map(valueForBaseRefChoice)];
429 const filteredBaseRefItems = [
430 ...(baseRefQuery.trim().length === 0 ? [AUTOMATIC_BASE_REF] : []),
431 ...matchingBaseRefChoices.map(valueForBaseRefChoice),
432 ];
433 const gitDiff = selectedGitSource?.diff;
434​
435 const selectedPatch = selectedTurn ? activeCheckpointDiff.data?.diff : gitDiff;
436 const isSelectedPatchTruncated = !selectedTurn && selectedGitSource?.truncated === true;
437 const isLoadingSelectedPatch = selectedTurn
438 ? activeCheckpointDiff.isPending
439 : branchDiffPreview.isPending;
440 const selectedPatchError = selectedTurn ? activeCheckpointDiff.error : branchDiffPreview.error;
441 const hasResolvedPatch = typeof selectedPatch === "string";
442 const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
443 const renderablePatch = useMemo(
444 () =>
445 getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, {
446 compactPartialHunkOffsets: selectedTurnId === null,
447 }),
448 [resolvedTheme, selectedPatch, selectedTurnId],
449 );
450 const renderableFiles = useMemo(() => {
451 if (!renderablePatch || renderablePatch.kind !== "files") {
452 return [];
453 }
454 return renderablePatch.files.toSorted((left, right) =>
455 resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
456 numeric: true,
457 sensitivity: "base",
458 }),
459 );
460 }, [renderablePatch]);
461 const renderableFileEntries = useMemo(
462 () =>
463 renderableFiles.map((fileDiff) => ({
464 fileDiff,
465 fileKey: buildFileDiffIdentityKey(fileDiff),
466 fileVersion: buildFileDiffContentVersion(fileDiff),
467 })),
468 [renderableFiles],
469 );
470 const codeViewFiles = useMemo(
471 () =>
472 renderableFileEntries.map(({ fileDiff, fileKey, fileVersion }) => {
473 return {
474 fileDiff,
475 filePath: resolveFileDiffPath(fileDiff),
476 fileKey,
477 fileVersion,
478 collapsed: collapsedDiffFileKeys.has(fileKey),
479 };
480 }),
481 [collapsedDiffFileKeys, renderableFileEntries],
482 );
483 const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
484 const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
485 const diffLineStat = useMemo(() => getDiffLineStat(renderableFiles), [renderableFiles]);
486 const fileTreeEntries = useMemo(() => diffFileTreeEntries(renderableFiles), [renderableFiles]);
487 const selectedDiffFileKey = selectedFilePath
488 ? (codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath)?.fileKey ?? null)
489 : null;
490​
491 useEffect(() => {
492 if (!selectedDiffFileKey || !codeView?.getInstance()) return;
493 codeView.scrollTo({ type: "item", id: selectedDiffFileKey, align: "start" });
494 }, [codeView, codeViewMountKey, selectedDiffFileKey, selectedFileRevealRequestId]);
495​
496 const treeRevealScope = useMemo(
497 () => ({ collapseScopeKey, diffSelection }),
498 [collapseScopeKey, diffSelection],
499 );
500 const requestTreeReveal = useCodeViewFileReveal(codeView, treeRevealScope);
501 const revealDiffFile = useCallback(
502 (filePath: string) => {
503 const file = codeViewFiles.find((candidate) => candidate.filePath === filePath);
504 if (!file) return;
505 if (file.collapsed) {
506 setCollapsedDiffFiles((current) => {
507 const next = new Set(current.scopeKey === collapseScopeKey ? current.fileKeys : []);
508 next.delete(file.fileKey);
509 return { scopeKey: collapseScopeKey, fileKeys: next };
510 });
511 }
512 requestTreeReveal(file.fileKey);
513 },
514 [codeViewFiles, collapseScopeKey, requestTreeReveal],
515 );
516​
517 const openDiffFile = useCallback(
518 (filePath: string) => {
519 openDiffFilePrimaryAction({
520 threadRef: routeThreadRef,
521 filePath,
522 activeCwd,
523 repositoryRoot: activeRepositoryRoot,
524 openInEditor: (targetPath) => {
525 void (async () => {
526 const result = await openInPreferredEditor(targetPath);
527 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
528 console.warn("Failed to open diff file in editor.", {
529 operation: "open-diff-file",
530 ...(routeThreadRef
531 ? {
532 environmentId: routeThreadRef.environmentId,
533 threadId: routeThreadRef.threadId,
534 }
535 : {}),
536 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
537 });
538 }
539 })();
540 },
541 });
542 },
543 [activeCwd, activeRepositoryRoot, openInPreferredEditor, routeThreadRef],
544 );
545 const toggleDiffFileCollapsed = useCallback(
546 (fileKey: string) => {
547 setCollapsedDiffFiles((current) => {
548 const next = new Set(current.scopeKey === collapseScopeKey ? current.fileKeys : []);
549 if (next.has(fileKey)) {
550 next.delete(fileKey);
551 } else {
552 next.add(fileKey);
553 }
554 return { scopeKey: collapseScopeKey, fileKeys: next };
555 });
556 },
557 [collapseScopeKey],
558 );
559​
560 const toggleDiffFileCollapse = useCallback(() => {
561 setCodeViewRevision((current) => current + 1);
562 setCollapsedDiffFiles((current) => {
563 const currentKeys =
564 current.scopeKey === collapseScopeKey ? current.fileKeys : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
565​
566 return {
567 scopeKey: collapseScopeKey,
568 fileKeys: toggleAllDiffFiles(diffFileKeys, currentKeys),
569 };
570 });
571 }, [collapseScopeKey, diffFileKeys]);
572​
573 const selectTurn = (turnId: TurnId) => {
574 if (!routeThreadRef) return;
575 useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId, undefined, { baselineTurnId });
576 };
577 const pinBaseline = (baseline: DiffBaseline | null) => {
578 if (routeThreadRef && latestTurn)
579 useDiffPanelStore.getState().pinBaseline(routeThreadRef, baseline, latestTurn.turnId);
580 };
581 const selectGitScope = (scope: "branch" | "unstaged") => {
582 if (!routeThreadRef) return;
583 useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
584 };
585 const selectBranchBaseRef = (baseRef: string | null) => {
586 if (!routeThreadRef) return;
587 useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
588 };
589​
590 const headerRow = (
591 <>
592 <div className="flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
593 <DropdownMenu>
594 <DropdownMenuTrigger
595 className="inline-flex h-6 max-w-full items-center gap-1 rounded-md bg-accent px-2 text-xs font-medium text-accent-foreground outline-none transition-colors hover:bg-accent/80 focus-visible:ring-2 focus-visible:ring-ring"
596 aria-label={`Diff scope: ${comparisonLabel}`}
597 >
598 <span className="truncate">{comparisonLabel}</span>
599 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
600 </DropdownMenuTrigger>
601 <DropdownMenuContent align="start" className="w-60">
602 <DropdownMenuItem
603 className={
604 selectedTurnId === null && selectedGitScope === "unstaged"
605 ? "bg-foreground/[0.08]"
606 : undefined
607 }
608 onClick={() => selectGitScope("unstaged")}
609 >
610 <span>Working tree</span>
611 </DropdownMenuItem>
612 <DropdownMenuItem
613 className={
614 selectedTurnId === null && selectedGitScope === "branch"
615 ? "bg-foreground/[0.08]"
616 : undefined
617 }
618 onClick={() => selectGitScope("branch")}
619 >
620 <span>Branch changes</span>
621 </DropdownMenuItem>
622 <DropdownMenuItem
623 className={
624 selectedTurnId !== null && isLatestTurnSelection
625 ? "bg-foreground/[0.08]"
626 : undefined
627 }
628 onClick={() => {
629 if (latestTurn && routeThreadRef)
630 useDiffPanelStore.getState().selectLatestTurn(routeThreadRef, latestTurn.turnId);
631 }}
632 >
633 <span>Latest turn</span>
634 </DropdownMenuItem>
635 <DropdownMenuSub>
636 <DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
637 <DropdownMenuSubContent className="w-64">
638 {orderedTurnDiffSummaries.map((summary) => {
639 const turnCount =
640 summary.checkpointTurnCount ??
641 inferredCheckpointTurnCountByTurnId[summary.turnId] ??
642 "?";
643 return (
644 <DropdownMenuItem
645 key={summary.turnId}
646 className={cn(
647 summary.turnId === selectedTurn?.turnId &&
648 !followsLatest &&
649 "bg-foreground/[0.08]",
650 summary.status === "ready" &&
651 summary.files.length === 0 &&
652 "text-muted-foreground",
653 )}
654 disabled={
655 baselineTurnCount !== undefined &&
656 summary.checkpointTurnCount < baselineTurnCount
657 }
658 onClick={() => selectTurn(summary.turnId)}
659 >
660 <span>
661 Turn {turnCount}
662 {summary.status === "ready" && summary.files.length === 0
663 ? " · No changes"
664 : ""}
665 </span>
666 <span className="ml-auto text-xs tabular-nums text-muted-foreground">
667 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
668 </span>
669 </DropdownMenuItem>
670 );
671 })}
672 </DropdownMenuSubContent>
673 </DropdownMenuSub>
674 <DropdownMenuSub onOpenChange={setBaselineMenuOpen}>
675 <DropdownMenuSubTrigger>Pin baseline</DropdownMenuSubTrigger>
676 <DropdownMenuSubContent className="w-64">
677 <DropdownMenuItem
678 disabled={
679 initialCheckpointDiff.data === null || initialCheckpointDiff.error !== null
680 }
681 onClick={() => pinBaseline(THREAD_START_DIFF_BASELINE)}
682 >
683 Start of thread (Turn 0){baselineTurnCount === 0 ? " (pinned)" : ""}
684 {initialCheckpointDiff.error ? " (unavailable)" : ""}
685 </DropdownMenuItem>
686 {orderedTurnDiffSummaries.map((summary) => (
687 <DropdownMenuItem
688 key={summary.turnId}
689 disabled={summary.status !== "ready"}
690 onClick={() => pinBaseline(summary.turnId)}
691 >
692 Turn {summary.checkpointTurnCount}
693 {summary.turnId === baselineTurnId ? " (pinned)" : ""}
694 </DropdownMenuItem>
695 ))}
696 </DropdownMenuSubContent>
697 </DropdownMenuSub>
698 {baselineTurnCount !== undefined && (
699 <DropdownMenuItem onClick={() => pinBaseline(null)}>
700 Unpin baseline (Turn {baselineTurnCount})
701 </DropdownMenuItem>
702 )}
703 </DropdownMenuContent>
704 </DropdownMenu>
705 {selectedTurnId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
706 <div
707 className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
708 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
709 >
710 <Tooltip>
711 <TooltipTrigger render={<span className="flex min-w-0 items-center gap-2" />}>
712 <span className="min-w-0 max-w-48 truncate">
713 {selectedGitSource.headRef ?? "HEAD"}
714 </span>
715 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
716 </TooltipTrigger>
717 <TooltipPopup side="top">
718 {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
719 </TooltipPopup>
720 </Tooltip>
721 <Combobox
722 items={baseRefItems}
723 filteredItems={filteredBaseRefItems}
724 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
725 onOpenChange={(open) => {
726 if (!open) setBaseRefQuery("");
727 }}
728 onValueChange={(value) => {
729 if (!value) return;
730 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
731 }}
732 >
733 <ComboboxTrigger
734 className="inline-flex min-w-0 max-w-48 items-center gap-1 overflow-hidden rounded-md px-1.5 py-1 outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
735 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
736 >
737 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
738 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
739 </ComboboxTrigger>
740 <ComboboxPopup
741 align="start"
742 className="w-72 min-w-0 max-w-[calc(100vw-1rem)] overflow-hidden"
743 >
744 <div className="min-w-0 shrink-0 px-3 pt-2.5">
745 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
746 <SearchIcon
747 aria-hidden="true"
748 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
749 />
750 <ComboboxInput
751 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
752 inputClassName="rounded-none bg-transparent text-sm"
753 placeholder="Search refs..."
754 showTrigger={false}
755 size="sm"
756 unstyled
757 value={baseRefQuery}
758 onChange={(event) => setBaseRefQuery(event.target.value)}
759 />
760 </div>
761 </div>
762 <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-[10px] text-muted-foreground uppercase tracking-wide">
763 <span aria-hidden="true" />
764 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
765 <span>Branch</span>
766 <span className="text-right">Remote</span>
767 </div>
768 </div>
769 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
770 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
771 <ComboboxItem
772 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
773 contentClassName="w-full min-w-0 overflow-hidden"
774 value={AUTOMATIC_BASE_REF}
775 >
776 <span className="block min-w-0 truncate">Automatic</span>
777 </ComboboxItem>
778 {baseRefChoices.map((choice) => {
779 const item = valueForBaseRefChoice(choice);
780 const hasBoth = choice.local !== null && choice.remote !== null;
781 const useRemote = choice.remote?.name === item;
782 return (
783 <ComboboxItem
784 key={choice.id}
785 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
786 contentClassName="w-full min-w-0 overflow-hidden"
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 && (
837 <DiffStatLabel
838 additions={diffLineStat.additions}
839 deletions={diffLineStat.deletions}
840 className="mr-1 text-[11px]"
841 layout="inline"
842 />
843 )}
844 {canRefreshGitDiff && (
845 <Tooltip>
846 <TooltipTrigger
847 render={
848 <Button
849 type="button"
850 size="icon-sm"
851 variant="ghost"
852 aria-label={branchDiffPreview.isPending ? "Refreshing diff" : "Refresh diff"}
853 onClick={refreshBranchDiffPreview}
854 />
855 }
856 >
857 <RefreshCwIcon
858 className={cn("size-3.5", branchDiffPreview.isPending && "animate-spin")}
859 />
860 </TooltipTrigger>
861 <TooltipPopup side="top">
862 {branchDiffPreview.isPending ? "Refreshing diff…" : "Refresh diff"}
863 </TooltipPopup>
864 </Tooltip>
865 )}
866 {codeViewFiles.length > 0 && (
867 <Tooltip>
868 <TooltipTrigger
869 render={
870 <Button
871 type="button"
872 size="icon-sm"
873 variant="ghost"
874 aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
875 onClick={toggleDiffFileCollapse}
876 />
877 }
878 >
879 {allDiffFilesCollapsed ? (
880 <ChevronsUpDownIcon className="size-3.5" />
881 ) : (
882 <ChevronsDownUpIcon className="size-3.5" />
883 )}
884 </TooltipTrigger>
885 <TooltipPopup side="top">
886 {allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
887 </TooltipPopup>
888 </Tooltip>
889 )}
890 <ToggleGroup
891 aria-label="Diff layout"
892 className="shrink-0"
893 variant="segmented"
894 value={[diffLayout]}
895 onValueChange={(value) => {
896 const next = value[0];
897 if (next === "stacked" || next === "split") {
898 updateClientSettings({ diffLayout: next });
899 }
900 }}
901 >
902 <Toggle aria-label="Stacked diff view" value="stacked">
903 <Rows3Icon className="size-3.5" />
904 </Toggle>
905 <Toggle aria-label="Split diff view" value="split">
906 <Columns2Icon className="size-3.5" />
907 </Toggle>
908 </ToggleGroup>
909 <Tooltip>
910 <TooltipTrigger
911 render={
912 <Toggle
913 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
914 variant="ghost"
915 size="sm"
916 pressed={wordWrap}
917 onPressedChange={(pressed) => {
918 setWordWrap(Boolean(pressed));
919 }}
920 />
921 }
922 >
923 <TextWrapIcon className="size-3.5" />
924 </TooltipTrigger>
925 <TooltipPopup side="top">
926 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
927 </TooltipPopup>
928 </Tooltip>
929 <Tooltip>
930 <TooltipTrigger
931 render={
932 <Toggle
933 aria-label={
934 diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
935 }
936 variant="ghost"
937 size="sm"
938 pressed={diffIgnoreWhitespace}
939 onPressedChange={(pressed) => {
940 setDiffIgnoreWhitespace(Boolean(pressed));
941 }}
942 />
943 }
944 >
945 <PilcrowIcon className="size-3.5" />
946 </TooltipTrigger>
947 <TooltipPopup side="top">
948 {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
949 </TooltipPopup>
950 </Tooltip>
951 {codeViewFiles.length > 0 && (
952 <Tooltip>
953 <TooltipTrigger
954 render={
955 <Toggle
956 aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}
957 variant="ghost"
958 size="sm"
959 pressed={fileTreeOpen}
960 onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}
961 />
962 }
963 >
964 <FolderTreeIcon className="size-3.5" />
965 </TooltipTrigger>
966 <TooltipPopup side="top">
967 {fileTreeOpen ? "Hide file tree" : "Show file tree"}
968 </TooltipPopup>
969 </Tooltip>
970 )}
971 </div>
972 </>
973 );
974​
975 return (
976 <DiffPanelShell mode={mode} header={headerRow}>
977 {!activeThread ? (
978 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
979 Select a thread to inspect turn diffs.
980 </div>
981 ) : !isGitRepo ? (
982 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
983 Turn diffs are unavailable because this project is not a git repository.
984 </div>
985 ) : selectedTurnId !== null && orderedTurnDiffSummaries.length === 0 ? (
986 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
987 No completed turns yet.
988 </div>
989 ) : (
990 <>
991 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
992 {isSelectedPatchTruncated && (
993 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground">
994 This diff was truncated because it exceeded the preview limit. The changes shown are
995 incomplete.
996 </p>
997 )}
998 {selectedPatchError && !renderablePatch && (
999 <div className="px-3">
1000 <p className="mb-2 text-[11px] text-error/80">{selectedPatchError}</p>
1001 </div>
1002 )}
1003 {!renderablePatch ? (
1004 isLoadingSelectedPatch ? (
1005 <DiffPanelLoadingState
1006 label={
1007 selectedTurn
1008 ? "Loading checkpoint diff..."
1009 : selectedGitScope === "unstaged"
1010 ? "Loading working tree diff..."
1011 : "Loading branch diff..."
1013 />
1014 ) : (
1015 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
1016 <p>
1017 {hasNoNetChanges
1018 ? "No net changes in this selection."
1019 : "No patch available for this selection."}
1020 </p>
1021 </div>
1023 ) : renderablePatch.kind === "files" ? (
1024 <div className="flex min-h-0 flex-1 overflow-hidden">
1025 <div
1026 className="min-h-0 min-w-0 flex-1"
1027 onClickCapture={(event) => {
1028 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1029 for (const node of composedPath) {
1030 if (!(node instanceof HTMLElement)) continue;
1031 // Header controls keep their own actions. In particular, the chevron must
1032 // not also trigger the row handler or the two toggles cancel each other.
1033 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1034 return;
1037 const title = composedPath.find(
1038 (node): node is HTMLElement =>
1039 node instanceof HTMLElement && node.hasAttribute("data-title"),
1040 );
1041 const filePath = title?.textContent?.trim();
1042 // The filename remains the explicit "open in editor" affordance.
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
1052 ?.querySelector("[data-title]")
1053 ?.textContent?.trim();
1054 if (!headerFilePath) return;
1055 const file = codeViewFiles.find(
1056 (candidate) => candidate.filePath === headerFilePath,
1057 );
1058 if (file) toggleDiffFileCollapsed(file.fileKey);
1059 }}
1061 <AnnotatableCodeView
1062 key={collapseScopeKey ?? reviewSectionId}
1063 viewerRef={setCodeView}
1064 codeViewKey={codeViewMountKey}
1065 className="h-full min-h-0 overflow-auto"
1066 files={codeViewFiles}
1067 sectionId={reviewSectionId}
1068 sectionTitle={reviewSectionTitle}
1069 composerDraftTarget={composerDraftTarget}
1070 renderHeaderFilenameSuffix={(fileDiff) => (
1071 <DiffFilePathCopyButton filePath={resolveFileDiffPath(fileDiff)} />
1072 )}
1073 renderHeaderPrefix={(fileDiff, fileKey, collapsed) => {
1074 const filePath = resolveFileDiffPath(fileDiff);
1075 return (
1076 <Tooltip>
1077 <TooltipTrigger
1078 render={
1079 <Button
1080 size="icon-micro"
1081 variant="ghost"
1082 className={cn(
1083 "-ms-0.5 [--control-icon-color:currentColor] bg-transparent hover:bg-foreground/10",
1084 getDiffCollapseIconClassName(fileDiff),
1085 )}
1086 aria-label={
1087 collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`
1089 aria-expanded={!collapsed}
1090 onClick={(event) => {
1091 event.stopPropagation();
1092 toggleDiffFileCollapsed(fileKey);
1093 }}
1094 />
1097 {collapsed ? (
1098 <ChevronRightIcon className="size-4" />
1099 ) : (
1100 <ChevronDownIcon className="size-4" />
1101 )}
1102 </TooltipTrigger>
1103 <TooltipPopup side="top">
1104 {collapsed ? "Expand diff" : "Collapse diff"}
1105 </TooltipPopup>
1106 </Tooltip>
1107 );
1108 }}
1109 options={{
1110 diffStyle: diffLayout === "split" ? "split" : "unified",
1111 lineDiffType: "none",
1112 overflow: wordWrap ? "wrap" : "scroll",
1113 theme: resolveDiffThemeName(resolvedTheme),
1114 preferredHighlighter: PREFERRED_HIGHLIGHTER,
1115 themeType: resolvedTheme as DiffThemeType,
1116 stickyHeaders: true,
1117 ...(currentLoadDiffFiles ? { loadDiffFiles } : {}),
1118 }}
1119 />
1120 </div>
1121 {fileTreeOpen ? (
1122 <aside className="flex w-[min(16rem,40%)] min-w-40 shrink-0 border-l border-border/60">
1123 <DiffFileTree
1124 ariaLabel={`${reviewSectionTitle} files`}
1125 entries={fileTreeEntries}
1126 selectedPath={selectedFilePath}
1127 revealRequestId={selectedFileRevealRequestId}
1128 onSelectFile={revealDiffFile}
1129 />
1130 </aside>
1131 ) : null}
1132 </div>
1133 ) : (
1134 <div className="min-h-0 flex-1 overflow-auto p-2">
1135 <div className="space-y-2">
1136 <p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
1137 <pre
1138 className={cn(
1139 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
1140 wordWrap
1141 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
1142 : "overflow-auto",
1143 )}
1145 {renderablePatch.text}
1146 </pre>
1147 </div>
1148 </div>
1149 )}
1150 </div>
1151 </>
1152 )}
1153 </DiffPanelShell>
1154 );