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

DiffPanel.tsx

1,068 lines44.2 KB

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