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

DiffPanel.tsx

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