Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DiffPanel.tsx

952 lines38.3 KB

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