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

DiffPanel.tsx

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