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