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