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