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