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

DiffPanel.tsx

975 lines39.6 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 title={`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
587 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
588 >
589 <span className="min-w-0 max-w-48 truncate">{selectedGitSource.headRef ?? "HEAD"}</span>
590 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
591 <Combobox
592 items={baseRefItems}
593 filteredItems={filteredBaseRefItems}
594 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
595 onOpenChange={(open) => {
596 if (!open) setBaseRefQuery("");
597 }}
598 onValueChange={(value) => {
599 if (!value) return;
600 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
601 }}
602 >
603 <ComboboxTrigger
604 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"
605 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
606 >
607 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
608 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
609 </ComboboxTrigger>
610 <ComboboxPopup
611 align="start"
612 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"
613 >
614 <div className="min-w-0 shrink-0 px-3 pt-2.5">
615 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
616 <SearchIcon
617 aria-hidden="true"
618 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
619 />
620 <ComboboxInput
621 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
622 inputClassName="rounded-none bg-transparent text-sm"
623 placeholder="Search refs..."
624 showTrigger={false}
625 size="sm"
626 unstyled
627 value={baseRefQuery}
628 onChange={(event) => setBaseRefQuery(event.target.value)}
629 />
630 </div>
631 </div>
632 <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">
633 <span aria-hidden="true" />
634 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
635 <span>Branch</span>
636 <span className="text-right">Remote</span>
637 </div>
638 </div>
639 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
640 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
641 <ComboboxItem
642 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
643 contentClassName="w-full min-w-0 overflow-hidden"
644 value={AUTOMATIC_BASE_REF}
645 >
646 <span className="block min-w-0 truncate">Automatic</span>
647 </ComboboxItem>
648 {baseRefChoices.map((choice) => {
649 const item = valueForBaseRefChoice(choice);
650 const hasBoth = choice.local !== null && choice.remote !== null;
651 const useRemote = choice.remote?.name === item;
652 return (
653 <ComboboxItem
654 key={choice.id}
655 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
656 contentClassName="w-full min-w-0 overflow-hidden"
657 value={item}
658 >
659 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden">
660 <span className="block min-w-0 truncate pe-2">{choice.label}</span>
661 {hasBoth ? (
662 <div
663 className="flex justify-end"
664 onClick={(event) => event.stopPropagation()}
665 onPointerDown={(event) => event.stopPropagation()}
666 >
667 <Switch
668 aria-label={`Use remote version of ${choice.label}`}
669 checked={useRemote}
670 className="[--thumb-size:--spacing(3)]"
671 onCheckedChange={(checked) => {
672 const nextRef = checked
673 ? choice.remote?.name
674 : choice.local?.name;
675 if (nextRef) selectBranchBaseRef(nextRef);
676 }}
677 />
678 </div>
679 ) : choice.remote ? (
680 <span
681 className="flex justify-end text-muted-foreground"
682 title="Remote only"
683 >
684 <CheckIcon aria-hidden="true" className="size-3" />
685 </span>
686 ) : null}
687 </div>
688 </ComboboxItem>
689 );
690 })}
691 </ComboboxList>
692 </ComboboxPopup>
693 </Combobox>
694 </div>
695 )}
696 </div>
697 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
698 {codeViewFiles.length > 0 && (
699 <DiffStatLabel
700 additions={diffLineStat.additions}
701 deletions={diffLineStat.deletions}
702 className="mr-1 text-[11px]"
703 layout="inline"
704 />
705 )}
706 {canRefreshGitDiff && (
707 <Tooltip>
708 <TooltipTrigger
709 render={
710 <Button
711 type="button"
712 size="icon-sm"
713 variant="ghost"
714 aria-label={branchDiffPreview.isPending ? "Refreshing diff" : "Refresh diff"}
715 onClick={refreshBranchDiffPreview}
716 />
717 }
718 >
719 <RefreshCwIcon
720 className={cn("size-3.5", branchDiffPreview.isPending && "animate-spin")}
721 />
722 </TooltipTrigger>
723 <TooltipPopup side="top">
724 {branchDiffPreview.isPending ? "Refreshing diff…" : "Refresh diff"}
725 </TooltipPopup>
726 </Tooltip>
727 )}
728 {codeViewFiles.length > 0 && (
729 <Tooltip>
730 <TooltipTrigger
731 render={
732 <Button
733 type="button"
734 size="icon-sm"
735 variant="ghost"
736 aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
737 onClick={toggleDiffFileCollapse}
738 />
739 }
740 >
741 {allDiffFilesCollapsed ? (
742 <ChevronsUpDownIcon className="size-3.5" />
743 ) : (
744 <ChevronsDownUpIcon className="size-3.5" />
745 )}
746 </TooltipTrigger>
747 <TooltipPopup side="top">
748 {allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
749 </TooltipPopup>
750 </Tooltip>
751 )}
752 <ToggleGroup
753 className="shrink-0 gap-1"
754 size="sm"
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" variant="ghost">
764 <Rows3Icon className="size-3.5" />
765 </Toggle>
766 <Toggle aria-label="Split diff view" value="split" variant="ghost">
767 <Columns2Icon className="size-3.5" />
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="ghost"
776 size="sm"
777 pressed={wordWrap}
778 onPressedChange={(pressed) => {
779 setWordWrap(Boolean(pressed));
780 }}
781 />
782 }
783 >
784 <TextWrapIcon className="size-3.5" />
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="ghost"
798 size="sm"
799 pressed={diffIgnoreWhitespace}
800 onPressedChange={(pressed) => {
801 setDiffIgnoreWhitespace(Boolean(pressed));
802 }}
803 />
804 }
805 >
806 <PilcrowIcon className="size-3.5" />
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="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
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-error/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 for (const node of composedPath) {
870 if (!(node instanceof HTMLElement)) continue;
871 // Header controls keep their own actions. In particular, the chevron must
872 // not also trigger the row handler or the two toggles cancel each other.
873 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
874 return;
875 }
876 }
877 const title = composedPath.find(
878 (node): node is HTMLElement =>
879 node instanceof HTMLElement && node.hasAttribute("data-title"),
880 );
881 const filePath = title?.textContent?.trim();
882 // The filename remains the explicit "open in editor" affordance.
883 if (filePath) {
884 openDiffFile(filePath);
885 return;
886 }
887 const header = composedPath.find(
888 (node): node is HTMLElement =>
889 node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),
890 );
891 const headerFilePath = header?.querySelector("[data-title]")?.textContent?.trim();
892 if (!headerFilePath) return;
893 const file = codeViewFiles.find(
894 (candidate) => candidate.filePath === headerFilePath,
895 );
896 if (file) toggleDiffFileCollapsed(file.fileKey);
897 }}
898 >
899 <AnnotatableCodeView
900 key={collapseScopeKey ?? reviewSectionId}
901 viewerRef={codeViewRef}
902 codeViewKey={codeViewMountKey}
903 className="h-full min-h-0 overflow-auto"
904 files={codeViewFiles}
905 sectionId={reviewSectionId}
906 sectionTitle={reviewSectionTitle}
907 composerDraftTarget={composerDraftTarget}
908 renderHeaderPrefix={(fileDiff, fileKey, collapsed) => {
909 const filePath = resolveFileDiffPath(fileDiff);
910 return (
911 <Tooltip>
912 <TooltipTrigger
913 render={
914 <Button
915 size="icon-micro"
916 variant="ghost"
917 className={cn(
918 "-ms-0.5 [--control-icon-color:currentColor] bg-transparent hover:bg-foreground/10",
919 getDiffCollapseIconClassName(fileDiff),
920 )}
921 aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
922 aria-expanded={!collapsed}
923 onClick={(event) => {
924 event.stopPropagation();
925 toggleDiffFileCollapsed(fileKey);
926 }}
927 />
928 }
929 >
930 {collapsed ? (
931 <ChevronRightIcon className="size-4" />
932 ) : (
933 <ChevronDownIcon className="size-4" />
934 )}
935 </TooltipTrigger>
936 <TooltipPopup side="top">
937 {collapsed ? "Expand diff" : "Collapse diff"}
938 </TooltipPopup>
939 </Tooltip>
940 );
941 }}
942 options={{
943 diffStyle: diffRenderMode === "split" ? "split" : "unified",
944 lineDiffType: "none",
945 overflow: wordWrap ? "wrap" : "scroll",
946 theme: resolveDiffThemeName(resolvedTheme),
947 themeType: resolvedTheme as DiffThemeType,
948 stickyHeaders: true,
949 ...(loadDiffFiles ? { loadDiffFiles } : {}),
950 }}
951 />
952 </div>
953 ) : (
954 <div className="min-h-0 flex-1 overflow-auto p-2">
955 <div className="space-y-2">
956 <p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
957 <pre
958 className={cn(
959 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
960 wordWrap
961 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
962 : "overflow-auto",
963 )}
964 >
965 {renderablePatch.text}
966 </pre>
967 </div>
968 </div>
969 )}
970 </div>
971 </>
972 )}
973 </DiffPanelShell>
974 );