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