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