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