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

DiffPanel.tsx

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