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