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