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