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