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