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

DiffPanel.tsx

991 lines40.3 KB

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