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

DiffPanel.tsx

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