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