Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DiffPanel.tsx

875 lines35.8 KB

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