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

DiffPanel.tsx

1,487 lines60.9 KB

1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import { useAtomValue } from "@effect/atom-react";
3import type { FileDiffContentsLoader, FileDiffMetadata } from "@pierre/diffs";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
9import type { ReviewBranchCommitsResult, ScopedThreadRef, RunId } from "@t3tools/contracts";
10import {
11 ArrowRightIcon,
12 CheckIcon,
13 ChevronDownIcon,
14 Columns2Icon,
15 FlaskConicalOffIcon,
16 FolderTreeIcon,
17 PilcrowIcon,
18 Rows3Icon,
19 TextWrapIcon,
20} from "lucide-react";
21import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
22import * as Schema from "effect/Schema";
23import { type MouseEvent, useEffect, useRef, useState } from "react";
24import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";
25import { useFilesystemReadAccess } from "~/state/filesystem";
26import { useOpenInPreferredEditor } from "../editorPreferences";
27import { useFileContextMenuHandler } from "../fileContextMenu";
28import { type DraftId } from "../composerDraftStore";
29import { openDiffFilePrimaryAction } from "../diffFileActions";
30import { toolCallDiff } from "../lib/toolCallDiff";
31import { useCheckpointDiff, useTurnItemDetail } from "~/state/queries";
32import { revisionedQuery } from "~/state/revisionedQuery";
33import { cn } from "~/lib/utils";
34import {
35 resolveToolCallDiffTarget,
36 selectThreadBranchBaseRef,
37 selectThreadDiffPanelSelection,
38 useDiffPanelSessionStore,
39 useDiffPanelStore,
40} from "../diffPanelStore";
41import { useLocalStorage } from "../hooks/useLocalStorage";
42import { isTestChangedFile } from "@t3tools/shared/changedFileKind";
43import { useHideTestFiles } from "./diffs/useHideTestFiles";
44import { useRenderedAppearance } from "../hooks/useTheme";
45import { useStableCallback } from "../hooks/useStableCallback";
46import {
47 buildFileDiffContentVersion,
48 buildFileDiffIdentityKey,
49 getDiffLineStat,
50 getRenderablePatch,
51 resolveDiffThemeName,
52 resolveFileDiffPath,
53} from "../lib/diffRendering";
54import { PREFERRED_HIGHLIGHTER } from "../lib/syntaxHighlighting";
55import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
56import { LIVE_REFRESH_MIN_INTERVAL_MS, useLiveRefresh } from "../hooks/useLiveRefresh";
57import {
58 useProject,
59 useThreadCheckpointSummaries,
60 useQuietThreadShell,
61 useQuietThreadVisibleTurnItems,
62} from "../state/entities";
63import { useClientSettings, updateClientSettings } from "../hooks/useSettings";
64import { formatRelativeTimeLabel, formatShortTimestamp } from "../timestampFormat";
65import { DiffFilePathCopyButton } from "./DiffFilePathCopyButton";
66import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
67import { DiffStatLabel } from "./chat/DiffStatLabel";
68import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView";
69import { DiffFileTree } from "./diffs/DiffFileTree";
70import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";
71import { Button } from "./ui/button";
72import { MorphIcon } from "~/components/MorphIcon";
73import { ToggleGroup, Toggle } from "./ui/toggle-group";
74import { Switch } from "./ui/switch";
75import {
76 Combobox,
77 ComboboxEmpty,
78 ComboboxSearchInput,
79 ComboboxItem,
80 ComboboxList,
81 ComboboxPopup,
82 ComboboxTrigger,
83} from "./ui/combobox";
84import {
85 DropdownMenu,
86 DropdownMenuContent,
87 DropdownMenuItem,
88 DropdownMenuRadioGroup,
89 DropdownMenuRadioItem,
90 DropdownMenuSub,
91 DropdownMenuSubContent,
92 DropdownMenuSubTrigger,
93 DropdownMenuTrigger,
94} from "./ui/menu";
95import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
96import { useEnvironmentQuery } from "../state/query";
97import { useAtomCommand } from "../state/use-atom-command";
98import { serverEnvironment } from "../state/server";
99import { reviewEnvironment } from "../state/review";
100import { vcsEnvironment } from "../state/vcs";
101import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
102import { createGitDiffFileContentsLoader } from "../lib/diffFileContents";
103​
104import { useReviewFilePatches } from "./diffs/useReviewFilePatches";
105import { DiffFileLoadingBoundary } from "./diffs/DiffFileLoadingBoundary";
106import { DiffFileStatus } from "./diffs/DiffFileStatus";
107import { useThreadRouteRef } from "../hooks/useThreadRouteTarget";
108import { projectCommitUrl } from "@t3tools/client-runtime/change-request-links";
109import { useOpenLink } from "../browser/useOpenLink";
110​
111type DiffThemeType = "light" | "dark";
112const AUTOMATIC_BASE_REF = "__automatic_base_ref__";
113const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen";
114const fileEntryCache = new WeakMap<
115 FileDiffMetadata,
116 { fileDiff: FileDiffMetadata; fileKey: string; fileVersion: number }
117>();
118​
119function getCachedFileEntry(fileDiff: FileDiffMetadata) {
120 const cached = fileEntryCache.get(fileDiff);
121 if (cached) return cached;
122 const entry = {
123 fileDiff,
124 fileKey: buildFileDiffIdentityKey(fileDiff),
125 fileVersion: buildFileDiffContentVersion(fileDiff),
126 };
127 fileEntryCache.set(fileDiff, entry);
128 return entry;
130​
131const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
132​
133function DiffFileCollapseToggle({
134 filePath,
135 fileKey,
136 collapsed,
137 unavailable,
138 onToggle,
139}: {
140 filePath: string;
141 fileKey: string;
142 collapsed: boolean;
143 unavailable: boolean;
144 onToggle: (fileKey: string) => void;
145}) {
146 return (
147 <Tooltip>
148 <TooltipTrigger
149 render={
150 <Button
151 size="icon-micro"
152 variant="ghost"
153 className="-ms-0.5"
154 aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
155 aria-expanded={!collapsed}
156 disabled={unavailable}
157 onClick={(event) => {
158 event.stopPropagation();
159 onToggle(fileKey);
160 }}
161 />
162 }
163 >
164 <MorphIcon
165 className="size-4 text-muted-foreground/80"
166 icon={collapsed ? ChevronRight : ChevronDown}
167 />
168 </TooltipTrigger>
169 <TooltipPopup side="top">{collapsed ? "Expand diff" : "Collapse diff"}</TooltipPopup>
170 </Tooltip>
171 );
173​
174function DiffFileHeaderSuffix({
175 filePath,
176 hasStat,
177 error,
178 truncated,
179 onRetry,
180}: {
181 filePath: string;
182 hasStat: boolean;
183 error: boolean;
184 truncated: boolean;
185 onRetry: (path: string) => void;
186}) {
187 return (
188 <>
189 <span data-diff-copy-path className="inline-flex">
190 <DiffFilePathCopyButton filePath={filePath} />
191 </span>
192 {hasStat ? (
193 <DiffFileStatus error={error} truncated={truncated} retry={() => onRetry(filePath)} />
194 ) : null}
195 </>
196 );
198​
199interface DiffPanelProps {
200 mode?: DiffPanelMode;
201 composerDraftTarget: ScopedThreadRef | DraftId;
202 workspaceMutationId: string | null;
203 visible: boolean;
205​
206export default function DiffPanel({
207 mode = "inline",
208 composerDraftTarget,
209 workspaceMutationId,
210 visible,
211}: DiffPanelProps) {
212 const resolvedTheme = useRenderedAppearance();
213 const settings = useClientSettings((settings) => ({
214 diffFilesCollapsed: settings.diffFilesCollapsed,
215 diffIgnoreWhitespace: settings.diffIgnoreWhitespace,
216 diffLayout: settings.diffLayout,
217 timestampFormat: settings.timestampFormat,
218 wordWrap: settings.wordWrap,
219 }));
220 const diffLayout = settings.diffLayout;
221 const [wordWrap, setWordWrap] = useState(settings.wordWrap);
222 const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
223 const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(
224 DIFF_FILE_TREE_STORAGE_KEY,
225 false,
226 Schema.Boolean,
227 );
228 const [hideTestFiles, setHideTestFiles] = useHideTestFiles();
229 const [baseRefQuery, setBaseRefQuery] = useState("");
230 // The open commit menu keeps the list it opened with, so rows do not move under the pointer.
231 const [openCommitMenu, setOpenCommitMenu] = useState<ReviewBranchCommitsResult | null>(null);
232 const [codeViewRevision, setCodeViewRevision] = useState(0);
233​
234 const routeThreadRef = useThreadRouteRef();
235 const activeThreadId = routeThreadRef?.threadId ?? null;
236 const activeThread = useQuietThreadShell(routeThreadRef);
237 const fileAccess = useFilesystemReadAccess(activeThread?.environmentId ?? null);
238 const { canReadFiles } = fileAccess;
239 const activeProjectId = activeThread?.projectId ?? null;
240 const activeProject = useProject(
241 activeThread && activeProjectId
242 ? {
243 environmentId: activeThread.environmentId,
244 projectId: activeProjectId,
245 }
246 : null,
247 );
248 const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot;
249 const activeRepositoryRoot = activeThread?.worktreePath
250 ? undefined
251 : activeProject?.repositoryIdentity?.rootPath;
252 const serverConfig = useAtomValue(
253 serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),
254 );
255 const onFileContextMenu = useFileContextMenuHandler(activeThread?.environmentId ?? null);
256 const openInPreferredEditor = useOpenInPreferredEditor(
257 activeThread?.environmentId ?? null,
258 serverConfig?.availableEditors ?? [],
259 );
260 const getDiffFileContents = useAtomCommand(reviewEnvironment.diffFileContents);
261 const gitStatusQuery = useEnvironmentQuery(
262 activeThread !== null && activeThread !== undefined && activeCwd != null
263 ? vcsEnvironment.status({
264 environmentId: activeThread.environmentId,
265 input: { cwd: activeCwd },
266 })
267 : null,
268 );
269 const diffSelection = useDiffPanelStore((state) =>
270 selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef),
271 );
272 const rememberedBaseRef = useDiffPanelStore((state) =>
273 selectThreadBranchBaseRef(state, routeThreadRef),
274 );
275 const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null;
276 const isGitSelection =
277 diffSelection.kind === "branch" ||
278 diffSelection.kind === "unstaged" ||
279 diffSelection.kind === "commit";
280 const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null);
281 const toolCallDetail = useTurnItemDetail(
282 toolCallSelection && routeThreadRef
283 ? {
284 ...resolveToolCallDiffTarget(toolCallSelection, toolCallItems),
285 environmentId: routeThreadRef.environmentId,
286 }
287 : null,
288 );
289 const toolCallItem = toolCallDetail.data?.item;
290 const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
291 const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef);
292 const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => {
293 if (left.checkpointTurnCount !== right.checkpointTurnCount) {
294 return right.checkpointTurnCount - left.checkpointTurnCount;
295 }
296 return right.completedAt.localeCompare(left.completedAt);
297 });
298​
299 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- rewrites the persisted diff store selection to the latest turn when the selected turn disappears
300 useEffect(() => {
301 if (!routeThreadRef || diffSelection.kind !== "turn") return;
302 useDiffPanelStore.getState().reconcileTurnSelection(
303 routeThreadRef,
304 orderedTurnDiffSummaries.map((summary) => summary.runId),
305 );
306 }, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
307​
308 const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
309 const selectedGitScope =
310 diffSelection.kind === "unstaged" || diffSelection.kind === "commit"
311 ? diffSelection.kind
312 : "branch";
313 const selectedCommitSha = diffSelection.kind === "commit" ? diffSelection.sha : null;
314 const selectedBaseRef =
315 diffSelection.kind === "branch" || diffSelection.kind === "commit"
316 ? diffSelection.baseRef
317 : null;
318 const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
319 const selectedFileRevealRequestId =
320 diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
321 const selectedTurn =
322 selectedRunId === null
323 ? undefined
324 : (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ??
325 orderedTurnDiffSummaries[0]);
326 const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount;
327 const latestTurn = orderedTurnDiffSummaries[0];
328 const reviewSectionId = toolCallSelection
329 ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}`
330 : selectedTurn
331 ? `turn:${selectedTurn.runId}`
332 : selectedCommitSha !== null
333 ? `commit:${selectedCommitSha}`
334 : selectedGitScope;
335 const collapseScopeKey = routeThreadRef
336 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
337 : null;
338 const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`;
339 const selectedCheckpointRange =
340 typeof selectedCheckpointTurnCount === "number"
341 ? {
342 fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
343 toTurnCount: selectedCheckpointTurnCount,
344 }
345 : null;
346 const activeCheckpointDiff = useCheckpointDiff(
347 {
348 environmentId: activeThread?.environmentId ?? null,
349 threadId: activeThreadId,
350 fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
351 toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
352 ignoreWhitespace: diffIgnoreWhitespace,
353 cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null,
354 },
355 { enabled: isGitRepo && selectedTurn !== undefined },
356 );
357 const branchDiffPreviewInput =
358 canReadFiles && isGitSelection && activeThread && activeCwd
359 ? {
360 cwd: activeCwd,
361 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
362 ...(selectedCommitSha !== null ? { commitSha: selectedCommitSha } : {}),
363 ignoreWhitespace: diffIgnoreWhitespace,
364 }
365 : undefined;
366 const canRefreshGitDiff =
367 isGitRepo && isGitSelection && activeThread != null && activeCwd != null;
368 // Read under the workspace mutation id, so each mutation refetches the diff; the panel stays
369 // mounted while hidden, so a mutation made then is already reflected when it shows.
370 const branchDiffPreview = useEnvironmentQuery(
371 branchDiffPreviewInput && activeThread
372 ? revisionedQuery(
373 reviewEnvironment.diffPreview({
374 environmentId: activeThread.environmentId,
375 input: branchDiffPreviewInput,
376 }),
377 canRefreshGitDiff ? workspaceMutationId : undefined,
378 )
379 : null,
380 );
381 const branchCommitsQuery = useEnvironmentQuery(
382 visible && isGitRepo && canReadFiles && activeThread && activeCwd
383 ? reviewEnvironment.branchCommits({
384 environmentId: activeThread.environmentId,
385 input: {
386 cwd: activeCwd,
387 ...(rememberedBaseRef ? { baseRef: rememberedBaseRef } : {}),
388 },
389 })
390 : null,
391 );
392 const branchCommits = openCommitMenu ?? branchCommitsQuery.data;
393 const activeThreadRefreshKey = routeThreadRef
394 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}`
395 : null;
396​
397 const selectedGitSource = branchDiffPreview.data?.sources.find(
398 (source) =>
399 source.kind ===
400 (selectedGitScope === "unstaged"
401 ? "working-tree"
402 : selectedGitScope === "commit"
403 ? "commit"
404 : "branch-range"),
405 );
406 const selectedCommitSubject =
407 selectedCommitSha !== null && selectedGitSource?.headRef === selectedCommitSha
408 ? selectedGitSource.commitSubject
409 : undefined;
410 const selectedGitScopeLabel =
411 selectedCommitSha !== null
412 ? (selectedCommitSubject ?? `Commit ${selectedCommitSha.slice(0, 7)}`)
413 : selectedGitScope === "unstaged"
414 ? "Uncommitted"
415 : "Changes";
416 const selectedScopeLabel = toolCallSelection
417 ? "Tool call"
418 : selectedRunId === null
419 ? selectedCommitSha !== null
420 ? (selectedCommitSubject ?? "Commit")
421 : selectedGitScopeLabel
422 : selectedTurn?.runId === latestTurn?.runId
423 ? "Latest turn"
424 : `Turn ${selectedCheckpointTurnCount ?? "?"}`;
425 const reviewSectionTitle = toolCallSelection
426 ? "Tool call"
427 : selectedTurn
428 ? `Turn ${selectedCheckpointTurnCount ?? "?"}`
429 : selectedGitScopeLabel;
430 const headerCommitSha = selectedRunId === null ? selectedCommitSha : null;
431 const selectedCommitUrl =
432 headerCommitSha !== null
433 ? projectCommitUrl(activeProject?.repositoryIdentity, headerCommitSha)
434 : null;
435 const openLink = useOpenLink(routeThreadRef);
436 // A SHA link goes to the code host; it must not route back into this pane's commit selection.
437 const openCommitUrl = (event: MouseEvent<HTMLElement>, url: string) => {
438 event.stopPropagation();
439 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button === 1)
440 return;
441 event.preventDefault();
442 void openLink(url, { event });
443 };
444 const refreshPreviewQuery = branchDiffPreview.refresh;
445 const refreshDiffFromUserAction = refreshPreviewQuery;
446​
447 const preview = branchDiffPreview.data;
448 const gitDiff = selectedGitSource?.diff;
449​
450 const toolCallPreview =
451 toolCallSelection && toolCallItem?.type === "file_change" ? toolCallDiff(toolCallItem) : null;
452 const selectedPatch = toolCallSelection
453 ? toolCallPreview?.patch
454 : selectedTurn
455 ? activeCheckpointDiff.data?.diff
456 : gitDiff;
457 const isSelectedPatchTruncated =
458 toolCallPreview?.truncated === true ||
459 (isGitSelection && selectedGitSource?.truncated === true);
460 const selectedPatchQuery = toolCallSelection
461 ? toolCallDetail
462 : selectedTurn
463 ? activeCheckpointDiff
464 : branchDiffPreview;
465 const isLoadingSelectedPatch = selectedPatchQuery.isPending && selectedPatchQuery.data === null;
466 const selectedPatchError = toolCallSelection
467 ? toolCallDetail.error
468 : selectedTurn
469 ? activeCheckpointDiff.error
470 : branchDiffPreview.error;
471 const hasResolvedPatch = typeof selectedPatch === "string";
472 const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
473 const lazySource =
474 isGitSelection && selectedGitSource?.truncated && selectedGitSource.files
475 ? selectedGitSource
476 : null;
477 const renderablePatch = getRenderablePatch(
478 lazySource ? undefined : selectedPatch,
479 `diff-panel:${resolvedTheme}`,
480 {
481 compactPartialHunkOffsets: isGitSelection,
482 ...(toolCallSelection ? { ignoreWhitespace: diffIgnoreWhitespace } : {}),
483 },
484 );
485 const recordedToolCallFileCount =
486 toolCallSelection && toolCallItem?.type === "file_change"
487 ? (toolCallItem.changes?.length ?? 0)
488 : 0;
489 const omittedToolCallFiles =
490 renderablePatch?.kind === "files"
491 ? Math.max(0, recordedToolCallFileCount - renderablePatch.files.length)
492 : 0;
493 const fileStats = new Map(lazySource?.files?.map((file) => [file.path, file]));
494 const sourceLineStat =
495 isGitSelection && selectedGitSource?.files
496 ? selectedGitSource.files.reduce(
497 (total, file) => ({
498 additions: total.additions + file.additions,
499 deletions: total.deletions + file.deletions,
500 }),
501 { additions: 0, deletions: 0 },
502 )
503 : null;
504 const currentLoadDiffFiles =
505 isGitSelection && activeThread && preview && selectedGitSource && canReadFiles
506 ? createGitDiffFileContentsLoader(getDiffFileContents, {
507 environmentId: activeThread.environmentId,
508 cwd: preview.cwd,
509 sourceKind: selectedGitSource.kind,
510 baseRef: selectedGitSource.baseRef,
511 headRef: selectedGitSource.headRef,
512 cacheKey: selectedGitSource.diffHash,
513 })
514 : undefined;
515 const loadDiffFiles: FileDiffContentsLoader = useStableCallback(async (fileDiff) => {
516 if (!currentLoadDiffFiles) {
517 throw new Error("Diff file contents are unavailable for this selection.");
518 }
519 return currentLoadDiffFiles(fileDiff);
520 });
521 const localBranchRefs = useEnvironmentQuery(
522 isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd
523 ? vcsEnvironment.listRefs({
524 environmentId: activeThread.environmentId,
525 input: {
526 cwd: branchDiffPreview.data.cwd,
527 includeMatchingRemoteRefs: true,
528 refKind: "local",
529 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
530 limit: 100,
531 },
532 })
533 : null,
534 );
535 const remoteBranchRefs = useEnvironmentQuery(
536 isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd
537 ? vcsEnvironment.listRefs({
538 environmentId: activeThread.environmentId,
539 input: {
540 cwd: branchDiffPreview.data.cwd,
541 includeMatchingRemoteRefs: true,
542 refKind: "remote",
543 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
544 limit: 100,
545 },
546 })
547 : null,
548 );
549 const baseRefChoices = buildBaseRefChoices(
550 localBranchRefs.data?.refs.filter((ref) => ref.name !== selectedGitSource?.headRef) ?? [],
551 remoteBranchRefs.data?.refs ?? [],
552 );
553 const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery);
554 const valueForBaseRefChoice = (choice: (typeof baseRefChoices)[number]) =>
555 selectedBaseRef && selectedBaseRef === choice.remote?.name
556 ? selectedBaseRef
557 : (choice.local?.name ?? choice.remote?.name ?? choice.id);
558 const baseRefItems = [AUTOMATIC_BASE_REF, ...baseRefChoices.map(valueForBaseRefChoice)];
559 const filteredBaseRefItems = [
560 ...(baseRefQuery.trim().length === 0 ? [AUTOMATIC_BASE_REF] : []),
561 ...matchingBaseRefChoices.map(valueForBaseRefChoice),
562 ];
563 const {
564 scope: filePatchScope,
565 isPending: areFilePatchesPending,
566 fileStates,
567 retry,
568 requestFile,
569 readyFilePaths,
570 renderableFiles,
571 settledFileCount,
572 loadNextFiles,
573 } = useReviewFilePatches({
574 environmentId: activeThread?.environmentId,
575 cwd: branchDiffPreview.data?.cwd,
576 source: lazySource,
577 baseRef:
578 selectedCommitSha !== null ? selectedBaseRef : (lazySource?.baseRef ?? selectedBaseRef),
579 ignoreWhitespace: diffIgnoreWhitespace,
580 theme: resolvedTheme,
581 previewInput: branchDiffPreviewInput,
582 preview: renderablePatch,
583 });
584 const refreshBranchDiffPreview = refreshPreviewQuery;
585 const diffRefreshKey = `diff:${activeThreadRefreshKey ?? ""}`;
586​
587 // The panel stays mounted while hidden, and edits made outside T3 Code bump no mutation id, so
588 // showing it revalidates the diff; that also stands in for focus events missed while hidden.
589 // A git diff is too costly to repeat on a timer nobody asked for. A diff read within the floor,
590 // such as a mutation's refetch while hidden, already counts as that revalidation.
591 useLiveRefresh(
592 branchDiffPreview.data !== null && !branchDiffPreview.isPending
593 ? () => {
594 if (Date.now() - branchDiffPreview.dataUpdatedAt < LIVE_REFRESH_MIN_INTERVAL_MS) return;
595 refreshBranchDiffPreview();
596 }
597 : null,
598 {
599 enabled: visible && canReadFiles && canRefreshGitDiff,
600 key: diffRefreshKey,
601 intervalMs: null,
602 refreshOnShow: true,
603 },
604 );
605​
606 const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;
607 const renderableFileEntries = renderableFiles.map(getCachedFileEntry);
608 const diffFileKeys = renderableFileEntries.map((file) => file.fileKey);
609 const testFileCount = renderableFiles.filter((file) =>
610 isTestChangedFile(resolveFileDiffPath(file)),
611 ).length;
612 // Hiding is display-only: lazy loading indexes into the full list. A requested file stays visible.
613 const isFileShown = (file: FileDiffMetadata) => {
614 const path = resolveFileDiffPath(file);
615 return !hideTestFiles || path === selectedFilePath || !isTestChangedFile(path);
616 };
617 const shownFileEntries = renderableFileEntries.filter(({ fileDiff }) => isFileShown(fileDiff));
618 const shownFileKeys = shownFileEntries.map((file) => file.fileKey);
619 const defaultCollapsedDiffFileKeys = settings.diffFilesCollapsed
620 ? new Set(diffFileKeys)
621 : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
622 const storedCollapsedDiffFileKeys = useDiffPanelSessionStore((state) =>
623 collapseScopeKey ? state.collapsedFileKeysByScopeKey[collapseScopeKey] : undefined,
624 );
625 const collapsedDiffFileKeys = storedCollapsedDiffFileKeys ?? defaultCollapsedDiffFileKeys;
626 const updateCollapsedDiffFiles = (
627 update: (current: ReadonlySet<string>) => ReadonlySet<string>,
628 ) => {
629 if (!collapseScopeKey) return;
630 useDiffPanelSessionStore
631 .getState()
632 .updateCollapsedFileKeys(collapseScopeKey, defaultCollapsedDiffFileKeys, update);
633 };
634 const renderLoadingBoundary = () =>
635 settledFileCount < renderableFiles.length ? (
636 <DiffFileLoadingBoundary
637 load={loadNextFiles}
638 count={renderableFiles.length - settledFileCount}
639 />
640 ) : null;
641 const codeViewFiles = shownFileEntries
642 .filter(
643 ({ fileDiff }) =>
644 !lazySource || !readyFilePaths || readyFilePaths.has(resolveFileDiffPath(fileDiff)),
645 )
646 .map(({ fileDiff, fileKey, fileVersion }) => ({
647 fileDiff,
648 filePath: resolveFileDiffPath(fileDiff),
649 fileKey,
650 fileVersion,
651 collapsed:
652 collapsedDiffFileKeys.has(fileKey) || fileDiff.cacheKey?.endsWith(":pending") === true,
653 }));
654 const pendingFiles = renderableFiles.filter(
655 (file) => file.cacheKey?.endsWith(":pending") && isFileShown(file),
656 );
657 const allDiffFilesCollapsed = areAllDiffFilesCollapsed(shownFileKeys, collapsedDiffFileKeys);
658 const diffLineStat = sourceLineStat ?? getDiffLineStat(renderableFiles);
659 const fileTreeEntries = diffFileTreeEntries(renderableFiles.filter(isFileShown));
660 const codeViewReveal = useCodeViewFileReveal();
661 const revealDiffFile = (filePath: string) => {
662 const index = renderableFileEntries.findIndex(
663 (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
664 );
665 const file = renderableFileEntries[index];
666 if (!file) return false;
667 updateCollapsedDiffFiles((current) => {
668 const next = new Set(current);
669 next.delete(file.fileKey);
670 return next;
671 });
672 if (lazySource && index >= settledFileCount) {
673 requestFile(index);
674 }
675 codeViewReveal.request(file.fileKey);
676 return true;
677 };
678​
679 // A file another view asked to reveal (a chat diff link): retried as the diff loads until it
680 // holds the file, then not again until a new request, so it does not undo what the user did since.
681 const externalRevealRef = useRef<string | null>(null);
682 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reveals an externally requested file in the diff viewer, retrying as the diff DOM loads
683 useEffect(() => {
684 if (!selectedFilePath) {
685 externalRevealRef.current = null;
686 return;
687 }
688 const key = JSON.stringify([collapseScopeKey, selectedFilePath, selectedFileRevealRequestId]);
689 if (externalRevealRef.current === key) return;
690 if (revealDiffFile(selectedFilePath)) {
691 externalRevealRef.current = key;
692 }
693 }, [collapseScopeKey, selectedFilePath, selectedFileRevealRequestId, revealDiffFile]);
694​
695 const openDiffFile = (filePath: string) => {
696 openDiffFilePrimaryAction({
697 threadRef: routeThreadRef,
698 filePath,
699 activeCwd,
700 repositoryRoot: activeRepositoryRoot,
701 openInEditor: (targetPath) => {
702 void (async () => {
703 const result = await openInPreferredEditor(targetPath);
704 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
705 console.warn("Failed to open diff file in editor.", {
706 operation: "open-diff-file",
707 ...(routeThreadRef
708 ? {
709 environmentId: routeThreadRef.environmentId,
710 threadId: routeThreadRef.threadId,
711 }
712 : {}),
713 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
714 });
715 }
716 })();
717 },
718 });
719 };
720 const toggleDiffFileCollapsed = useStableCallback((fileKey: string) => {
721 updateCollapsedDiffFiles((current) => {
722 const next = new Set(current);
723 if (next.has(fileKey)) {
724 next.delete(fileKey);
725 } else {
726 next.add(fileKey);
727 }
728 return next;
729 });
730 });
731 // Find can ask again before the unfolded file reaches the viewer, so this must never fold.
732 const unfoldDiffFile = useStableCallback((fileKey: string) => {
733 updateCollapsedDiffFiles((current) => {
734 if (!current.has(fileKey)) return current;
735 const next = new Set(current);
736 next.delete(fileKey);
737 return next;
738 });
739 });
740​
741 const toggleDiffFileCollapse = () => {
742 setCodeViewRevision((current) => current + 1);
743 updateCollapsedDiffFiles((current) => toggleAllDiffFiles(shownFileKeys, current));
744 };
745​
746 const selectTurn = (runId: RunId) => {
747 if (!routeThreadRef) return;
748 useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
749 };
750 const selectGitScope = (scope: "branch" | "unstaged") => {
751 if (!routeThreadRef) return;
752 useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
753 };
754 const selectBranchBaseRef = (baseRef: string | null) => {
755 if (!routeThreadRef) return;
756 useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
757 };
758 const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : "";
759 const selectedCommitValue = selectedCommitSha !== null ? `commit:${selectedCommitSha}` : "";
760 const selectedScopeValue = toolCallSelection
761 ? ""
762 : selectedRunId === null
763 ? selectedCommitValue || selectedGitScope
764 : selectedTurn?.runId === latestTurn?.runId
765 ? "latest"
766 : selectedTurnValue;
767 const selectScopeValue = (value: string) => {
768 if (value === "unstaged" || value === "branch") {
769 selectGitScope(value);
770 } else if (value === selectedCommitValue) {
771 selectGitScope("branch");
772 } else if (value.startsWith("commit:")) {
773 if (routeThreadRef) {
774 useDiffPanelStore.getState().selectCommit(routeThreadRef, value.slice("commit:".length));
775 }
776 } else if (value === "latest") {
777 if (latestTurn) selectTurn(latestTurn.runId);
778 } else {
779 const turn = orderedTurnDiffSummaries.find((summary) => `turn:${summary.runId}` === value);
780 if (turn) selectTurn(turn.runId);
781 }
782 };
783​
784 const headerRow = (
785 <>
786 <div className="@container/diff-refs flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
787 <DropdownMenu>
788 <DropdownMenuTrigger
789 render={<Button size="xs" variant="secondary" />}
790 className={cn("max-w-full", headerCommitSha !== null && "min-w-0 shrink")}
791 aria-label={`Diff scope: ${selectedScopeLabel}`}
792 data-workspace-focus-default
793 >
794 <span className="truncate">{selectedScopeLabel}</span>
795 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
796 </DropdownMenuTrigger>
797 {headerCommitSha !== null ? (
798 selectedCommitUrl ? (
799 <Tooltip>
800 <TooltipTrigger
801 render={
802 <a
803 href={selectedCommitUrl}
804 target="_blank"
805 rel="noopener noreferrer"
806 className="shrink-0 font-mono text-xs text-muted-foreground underline underline-offset-4"
807 onClick={(event) => openCommitUrl(event, selectedCommitUrl)}
808 />
809 }
810 >
811 {headerCommitSha.slice(0, 7)}
812 </TooltipTrigger>
813 <TooltipPopup side="top">{selectedCommitUrl}</TooltipPopup>
814 </Tooltip>
815 ) : (
816 <span className="shrink-0 font-mono text-xs text-muted-foreground">
817 {headerCommitSha.slice(0, 7)}
818 </span>
819 )
820 ) : null}
821 <DropdownMenuContent align="start">
822 <DropdownMenuRadioGroup value={selectedScopeValue} onValueChange={selectScopeValue}>
823 <DropdownMenuRadioItem value="branch" closeOnClick>
824 <span>Changes</span>
825 </DropdownMenuRadioItem>
826 <DropdownMenuRadioItem value="unstaged" closeOnClick>
827 <span>Uncommitted</span>
828 </DropdownMenuRadioItem>
829 <DropdownMenuRadioItem value="latest" closeOnClick>
830 <span>Latest turn</span>
831 </DropdownMenuRadioItem>
832 </DropdownMenuRadioGroup>
833 <DropdownMenuSub>
834 <DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
835 <DropdownMenuSubContent>
836 <DropdownMenuRadioGroup value={selectedTurnValue} onValueChange={selectScopeValue}>
837 {orderedTurnDiffSummaries.map((summary) => {
838 const turnCount = summary.checkpointTurnCount;
839 return (
840 <DropdownMenuRadioItem
841 key={summary.runId}
842 value={`turn:${summary.runId}`}
843 closeOnClick
844 >
845 <span className="flex items-center gap-2">
846 <span>Turn {turnCount}</span>
847 <span className="ml-auto text-xs tabular-nums text-muted-foreground">
848 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
849 </span>
850 </span>
851 </DropdownMenuRadioItem>
852 );
853 })}
854 </DropdownMenuRadioGroup>
855 </DropdownMenuSubContent>
856 </DropdownMenuSub>
857 <DropdownMenuSub
858 onOpenChange={(open) => {
859 setOpenCommitMenu(open ? (branchCommitsQuery.data ?? null) : null);
860 if (!open) return;
861 // The menu keeps the list it opened with; the refreshed one shows next time.
862 branchCommitsQuery.refresh();
863 }}
864 >
865 <DropdownMenuSubTrigger>Commits</DropdownMenuSubTrigger>
866 <DropdownMenuSubContent className="max-h-80 max-w-96">
867 <DropdownMenuRadioGroup
868 value={selectedCommitValue}
869 onValueChange={selectScopeValue}
870 >
871 {branchCommits?.commits.map((commit) => {
872 const commitUrl = projectCommitUrl(
873 activeProject?.repositoryIdentity,
874 commit.sha,
875 );
876 return (
877 <div
878 key={commit.sha}
879 className={cn(
880 "flex items-center rounded-sm hover:bg-accent has-data-highlighted:bg-accent has-focus-visible:bg-accent [&_[data-checked]]:bg-transparent [&_[data-highlighted]]:bg-transparent",
881 selectedCommitSha === commit.sha && "bg-foreground/[0.08]",
882 )}
883 >
884 <Tooltip>
885 <TooltipTrigger
886 render={
887 <DropdownMenuRadioItem
888 className="min-w-0 flex-1"
889 value={`commit:${commit.sha}`}
890 closeOnClick
891 />
892 }
893 >
894 <span className="flex items-center gap-3">
895 <span className="min-w-0 flex-1 truncate">{commit.subject}</span>
896 <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
897 {formatRelativeTimeLabel(commit.committedAt)}
898 </span>
899 </span>
900 </TooltipTrigger>
901 <TooltipPopup side="right" className="max-w-80">
902 {commit.subject}
903 </TooltipPopup>
904 </Tooltip>
905 {commitUrl ? (
906 <DropdownMenuItem
907 className="shrink-0"
908 render={
909 <a
910 href={commitUrl}
911 target="_blank"
912 rel="noopener noreferrer"
913 aria-label={`Open commit ${commit.sha.slice(0, 7)}`}
914 />
915 }
916 onClick={(event) => openCommitUrl(event, commitUrl)}
917 >
918 <span className="font-mono text-xs text-muted-foreground underline underline-offset-4">
919 {commit.sha.slice(0, 7)}
920 </span>
921 </DropdownMenuItem>
922 ) : (
923 <span className="shrink-0 px-2 font-mono text-xs text-muted-foreground">
924 {commit.sha.slice(0, 7)}
925 </span>
926 )}
927 </div>
928 );
929 })}
930 </DropdownMenuRadioGroup>
931 {branchCommitsQuery.error ? (
932 <DropdownMenuItem disabled>{branchCommitsQuery.error}</DropdownMenuItem>
933 ) : !canReadFiles ? (
934 <DropdownMenuItem disabled>
935 {fileAccess.isPending
936 ? "Checking file access..."
937 : (fileAccess.error ?? "This connection cannot read local diffs.")}
938 </DropdownMenuItem>
939 ) : branchCommits === null ? (
940 <DropdownMenuItem disabled>Loading commits...</DropdownMenuItem>
941 ) : branchCommits.commits.length === 0 ? (
942 <DropdownMenuItem disabled>No commits on this branch.</DropdownMenuItem>
943 ) : branchCommits.truncated ? (
944 <DropdownMenuItem disabled>
945 {`Showing latest ${branchCommits.commits.length} commits`}
946 </DropdownMenuItem>
947 ) : null}
948 </DropdownMenuSubContent>
949 </DropdownMenuSub>
950 </DropdownMenuContent>
951 </DropdownMenu>
952 {isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
953 <div
954 className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
955 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
956 >
957 <Tooltip>
958 <TooltipTrigger
959 render={
960 // Too narrow for both refs, keep the target readable and drop the head, which
961 // is the thread's own branch.
962 <span className="flex min-w-[min(3rem,calc(100%-2.75rem))] items-center gap-2 overflow-hidden @max-[20rem]/diff-refs:hidden" />
963 }
964 >
965 <span className="min-w-0 max-w-48 truncate">
966 {selectedGitSource.headRef ?? "HEAD"}
967 </span>
968 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
969 </TooltipTrigger>
970 <TooltipPopup side="top">
971 {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
972 </TooltipPopup>
973 </Tooltip>
974 <Tooltip>
975 <TooltipTrigger
976 render={<span aria-hidden className="hidden @max-[20rem]/diff-refs:inline" />}
977 >
978 vs
979 </TooltipTrigger>
980 <TooltipPopup side="top">
981 {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
982 </TooltipPopup>
983 </Tooltip>
984 <Combobox
985 items={baseRefItems}
986 filteredItems={filteredBaseRefItems}
987 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
988 onOpenChange={(open) => {
989 if (!open) setBaseRefQuery("");
990 }}
991 onValueChange={(value) => {
992 if (!value) return;
993 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
994 }}
995 >
996 <ComboboxTrigger
997 render={<Button variant="ghost-muted" size="xs" />}
998 className="min-w-9 max-w-48 shrink-0"
999 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
1001 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
1002 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
1003 </ComboboxTrigger>
1004 <ComboboxPopup
1005 align="start"
1006 className="w-72 min-w-0 max-w-[calc(100vw-1rem)] overflow-hidden"
1008 <ComboboxSearchInput
1009 placeholder="Search refs..."
1010 value={baseRefQuery}
1011 onChange={(event) => setBaseRefQuery(event.target.value)}
1012 />
1013 <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-3xs text-muted-foreground uppercase tracking-wide">
1014 <span aria-hidden="true" />
1015 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
1016 <span>Branch</span>
1017 <span className="text-right">Remote</span>
1018 </div>
1019 </div>
1020 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
1021 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
1022 <ComboboxItem
1023 className="w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)]"
1024 value={AUTOMATIC_BASE_REF}
1026 <span className="block min-w-0 truncate">Automatic</span>
1027 </ComboboxItem>
1028 {baseRefChoices.map((choice) => {
1029 const item = valueForBaseRefChoice(choice);
1030 const hasBoth = choice.local !== null && choice.remote !== null;
1031 const useRemote = choice.remote?.name === item;
1032 return (
1033 <ComboboxItem
1034 key={choice.id}
1035 className="w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)]"
1036 value={item}
1038 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden">
1039 <span className="block min-w-0 truncate pe-2">{choice.label}</span>
1040 {hasBoth ? (
1041 <div
1042 className="flex justify-end"
1043 onClick={(event) => event.stopPropagation()}
1044 onPointerDown={(event) => event.stopPropagation()}
1046 <Switch
1047 aria-label={`Use remote version of ${choice.label}`}
1048 checked={useRemote}
1049 className="[--thumb-size:--spacing(3)]"
1050 onCheckedChange={(checked) => {
1051 const nextRef = checked
1052 ? choice.remote?.name
1053 : choice.local?.name;
1054 if (nextRef) selectBranchBaseRef(nextRef);
1055 }}
1056 />
1057 </div>
1058 ) : choice.remote ? (
1059 <Tooltip>
1060 <TooltipTrigger
1061 render={
1062 <span className="flex justify-end text-muted-foreground">
1063 <CheckIcon
1064 role="img"
1065 aria-label="Remote only"
1066 className="size-3"
1067 />
1068 </span>
1070 />
1071 <TooltipPopup side="top">Remote only</TooltipPopup>
1072 </Tooltip>
1073 ) : null}
1074 </div>
1075 </ComboboxItem>
1076 );
1077 })}
1078 </ComboboxList>
1079 </ComboboxPopup>
1080 </Combobox>
1081 </div>
1082 )}
1083 </div>
1084 <div
1085 className={cn(
1086 "flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]",
1087 headerCommitSha !== null && "gap-0",
1088 )}
1090 {codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? (
1091 <DiffStatLabel
1092 additions={diffLineStat.additions}
1093 deletions={diffLineStat.deletions}
1094 className="mr-1 text-2xs"
1095 layout="inline"
1096 />
1097 ) : null}
1098 {canRefreshGitDiff && (
1099 <Tooltip>
1100 <TooltipTrigger
1101 render={
1102 <Button
1103 type="button"
1104 size="icon-sm"
1105 variant="ghost"
1106 aria-label={isRefreshingDiff ? "Refreshing diff" : "Refresh diff"}
1107 onClick={refreshDiffFromUserAction}
1108 />
1111 <RefreshIcon size="sm" refreshing={isRefreshingDiff} />
1112 </TooltipTrigger>
1113 <TooltipPopup side="top">
1114 {isRefreshingDiff ? "Refreshing diff…" : "Refresh diff"}
1115 </TooltipPopup>
1116 </Tooltip>
1117 )}
1118 {diffFileKeys.length > 0 && (
1119 <Tooltip>
1120 <TooltipTrigger
1121 render={
1122 <Button
1123 type="button"
1124 size="icon-sm"
1125 variant="ghost"
1126 aria-label={allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
1127 onClick={toggleDiffFileCollapse}
1128 />
1131 <MorphIcon
1132 className="size-3.5"
1133 icon={allDiffFilesCollapsed ? ChevronsUpDown : ChevronsDownUp}
1134 />
1135 </TooltipTrigger>
1136 <TooltipPopup side="top">
1137 {allDiffFilesCollapsed ? "Expand all files" : "Collapse all files"}
1138 </TooltipPopup>
1139 </Tooltip>
1140 )}
1141 <ToggleGroup
1142 aria-label="Diff layout"
1143 className="shrink-0"
1144 variant="segmented"
1145 value={[diffLayout]}
1146 onValueChange={(value) => {
1147 const next = value[0];
1148 if (next === "stacked" || next === "split") {
1149 updateClientSettings({ diffLayout: next });
1151 }}
1153 <Toggle aria-label="Stacked diff view" value="stacked">
1154 <Rows3Icon className="size-3.5" />
1155 </Toggle>
1156 <Toggle aria-label="Split diff view" value="split">
1157 <Columns2Icon className="size-3.5" />
1158 </Toggle>
1159 </ToggleGroup>
1160 <Tooltip>
1161 <TooltipTrigger
1162 render={
1163 <Toggle
1164 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
1165 variant="ghost"
1166 size="sm"
1167 pressed={wordWrap}
1168 onPressedChange={(pressed) => {
1169 setWordWrap(Boolean(pressed));
1170 }}
1171 />
1174 <TextWrapIcon className="size-3.5" />
1175 </TooltipTrigger>
1176 <TooltipPopup side="top">
1177 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
1178 </TooltipPopup>
1179 </Tooltip>
1180 <Tooltip>
1181 <TooltipTrigger
1182 render={
1183 <Toggle
1184 aria-label={
1185 diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
1187 variant="ghost"
1188 size="sm"
1189 pressed={diffIgnoreWhitespace}
1190 onPressedChange={(pressed) => {
1191 setDiffIgnoreWhitespace(Boolean(pressed));
1192 }}
1193 />
1196 <PilcrowIcon className="size-3.5" />
1197 </TooltipTrigger>
1198 <TooltipPopup side="top">
1199 {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
1200 </TooltipPopup>
1201 </Tooltip>
1202 {testFileCount > 0 && (
1203 <Tooltip>
1204 <TooltipTrigger
1205 render={
1206 <Toggle
1207 aria-label="Hide test files"
1208 variant="ghost"
1209 size="sm"
1210 pressed={hideTestFiles}
1211 onPressedChange={(pressed) => setHideTestFiles(Boolean(pressed))}
1212 />
1215 <FlaskConicalOffIcon className="size-3.5" />
1216 </TooltipTrigger>
1217 <TooltipPopup side="top">
1218 {hideTestFiles
1219 ? `Show ${testFileCount} hidden test ${testFileCount === 1 ? "file" : "files"}`
1220 : "Hide test files"}
1221 </TooltipPopup>
1222 </Tooltip>
1223 )}
1224 {diffFileKeys.length > 0 && (
1225 <Tooltip>
1226 <TooltipTrigger
1227 render={
1228 <Toggle
1229 aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}
1230 variant="ghost"
1231 size="sm"
1232 pressed={fileTreeOpen}
1233 onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}
1234 />
1237 <FolderTreeIcon className="size-3.5" />
1238 </TooltipTrigger>
1239 <TooltipPopup side="top">
1240 {fileTreeOpen ? "Hide file tree" : "Show file tree"}
1241 </TooltipPopup>
1242 </Tooltip>
1243 )}
1244 </div>
1245 </>
1246 );
1247​
1248 return (
1249 <DiffPanelShell mode={mode} header={headerRow}>
1250 {!activeThread ? (
1251 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1252 Select a thread to inspect turn diffs.
1253 </div>
1254 ) : !isGitRepo && !toolCallSelection ? (
1255 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1256 Turn diffs are unavailable because this project is not a git repository.
1257 </div>
1258 ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
1259 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1260 No completed turns yet.
1261 </div>
1262 ) : isGitSelection && !canReadFiles ? (
1263 fileAccess.isPending ? (
1264 <DiffPanelLoadingState label="Checking file access..." />
1265 ) : (
1266 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
1267 {fileAccess.error ?? "This connection cannot read local diffs."}
1268 </div>
1270 ) : (
1271 <>
1272 <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background">
1273 {isSelectedPatchTruncated && !lazySource && (
1274 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
1275 This preview exceeds the size limit. Changes shown are incomplete.
1276 {isGitSelection && selectedGitSource?.files ? " Totals include all changes." : ""}
1277 </p>
1278 )}
1279 {omittedToolCallFiles > 0 && (
1280 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-2xs text-muted-foreground">
1281 This tool call changed {recordedToolCallFileCount} files. The recorded patch omits{" "}
1282 {omittedToolCallFiles} of them.
1283 </p>
1284 )}
1285 {selectedPatchError && !renderablePatch && (
1286 <div className="px-3">
1287 <p className="mb-2 text-2xs text-error/80">{selectedPatchError}</p>
1288 </div>
1289 )}
1290 {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? (
1291 <div className="min-h-0 flex-1 space-y-3 overflow-auto p-3 text-xs">
1292 <p className="text-muted-foreground">
1293 The provider recorded file content without a diff.
1294 </p>
1295 {toolCallPreview.content.map(({ label, text }) => (
1296 <div key={label} className="space-y-1">
1297 <p className="text-muted-foreground">{label}</p>
1298 <pre
1299 className={cn(
1300 "overflow-auto font-mono text-2xs",
1301 wordWrap && "whitespace-pre-wrap wrap-break-word",
1302 )}
1304 {text === "" ? "Empty content." : text}
1305 </pre>
1306 </div>
1307 ))}
1308 </div>
1309 ) : !renderablePatch && !lazySource ? (
1310 isLoadingSelectedPatch ? (
1311 <DiffPanelLoadingState
1312 label={
1313 toolCallSelection
1314 ? "Loading tool call diff..."
1315 : selectedTurn
1316 ? "Loading checkpoint diff..."
1317 : selectedGitScope === "unstaged"
1318 ? "Loading uncommitted changes..."
1319 : selectedGitScope === "commit"
1320 ? "Loading commit..."
1321 : "Loading changes..."
1323 />
1324 ) : (
1325 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
1326 <p>
1327 {hasNoNetChanges
1328 ? "No net changes in this selection."
1329 : "No patch available for this selection."}
1330 </p>
1331 </div>
1333 ) : lazySource || renderablePatch?.kind === "files" ? (
1334 <div className="flex min-h-0 flex-1 overflow-hidden">
1335 <div
1336 className="min-h-0 min-w-0 flex-1"
1337 onClickCapture={(event) => {
1338 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1339 for (const node of composedPath) {
1340 if (!(node instanceof HTMLElement)) continue;
1341 // Header buttons own their clicks; bubbling a chevron click would toggle twice.
1342 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1343 return;
1346 const title = composedPath.find(
1347 (node): node is HTMLElement =>
1348 node instanceof HTMLElement && node.hasAttribute("data-title"),
1349 );
1350 const filePath = title?.textContent;
1351 if (filePath) {
1352 openDiffFile(filePath);
1353 return;
1355 const header = composedPath.find(
1356 (node): node is HTMLElement =>
1357 node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),
1358 );
1359 const headerFilePath = header?.querySelector("[data-title]")?.textContent;
1360 if (!headerFilePath) return;
1361 const file = codeViewFiles.find(
1362 (candidate) => candidate.filePath === headerFilePath,
1363 );
1364 if (file) toggleDiffFileCollapsed(file.fileKey);
1365 }}
1366 onContextMenuCapture={(event) => {
1367 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1368 const title = composedPath.find(
1369 (node): node is HTMLElement =>
1370 node instanceof HTMLElement && node.hasAttribute("data-title"),
1371 );
1372 const filePath = title?.textContent?.trim();
1373 if (!filePath) return;
1374 event.preventDefault();
1375 onFileContextMenu(
1377 environmentId: activeThread?.environmentId ?? null,
1378 filePath,
1379 workspaceRoot: activeCwd,
1380 repositoryRoot: activeRepositoryRoot,
1381 },
1382 event,
1383 );
1384 }}
1386 <AnnotatableCodeView
1387 key={collapseScopeKey ?? reviewSectionId}
1388 viewerRef={codeViewReveal.attach}
1389 codeViewKey={`${codeViewMountKey}:${lazySource ? filePatchScope : "preview"}`}
1390 className="h-full min-h-0 overflow-auto"
1391 files={codeViewFiles}
1392 pendingFiles={pendingFiles}
1393 renderCodeViewFooter={renderLoadingBoundary}
1394 sectionId={reviewSectionId}
1395 sectionTitle={reviewSectionTitle}
1396 composerDraftTarget={composerDraftTarget}
1397 renderHeaderFilenameSuffix={(fileDiff) => {
1398 const path = resolveFileDiffPath(fileDiff);
1399 const state = fileStates.get(path);
1400 return (
1401 <DiffFileHeaderSuffix
1402 filePath={path}
1403 hasStat={fileStats.has(path)}
1404 error={state?.error ?? false}
1405 truncated={state?.truncated ?? false}
1406 onRetry={retry}
1407 />
1408 );
1409 }}
1410 {...(lazySource
1411 ? {
1412 unsafeCSSExtra:
1413 "[data-additions-count], [data-deletions-count] { display: none; }",
1414 renderHeaderMetadata: (fileDiff: FileDiffMetadata) => {
1415 const stat = fileStats.get(resolveFileDiffPath(fileDiff));
1416 return stat ? (
1417 <DiffStatLabel
1418 additions={stat.additions}
1419 deletions={stat.deletions}
1420 />
1421 ) : null;
1422 },
1424 : {})}
1425 onRevealSearchMatch={unfoldDiffFile}
1426 renderHeaderPrefix={(fileDiff, fileKey) => {
1427 const unavailable = fileDiff.cacheKey?.endsWith(":pending") === true;
1428 return (
1429 <DiffFileCollapseToggle
1430 filePath={resolveFileDiffPath(fileDiff)}
1431 fileKey={fileKey}
1432 collapsed={unavailable || collapsedDiffFileKeys.has(fileKey)}
1433 unavailable={unavailable}
1434 onToggle={toggleDiffFileCollapsed}
1435 />
1436 );
1437 }}
1438 options={{
1439 diffStyle: diffLayout === "split" ? "split" : "unified",
1440 lineDiffType: "none",
1441 overflow: wordWrap ? "wrap" : "scroll",
1442 theme: resolveDiffThemeName(resolvedTheme),
1443 preferredHighlighter: PREFERRED_HIGHLIGHTER,
1444 themeType: resolvedTheme as DiffThemeType,
1445 stickyHeaders: true,
1446 onPostRender: codeViewReveal.flush,
1447 ...(currentLoadDiffFiles ? { loadDiffFiles } : {}),
1448 }}
1449 />
1450 </div>
1451 {fileTreeOpen ? (
1452 <aside className="flex w-[min(16rem,40%)] min-w-40 shrink-0 border-l border-border/60">
1453 <DiffFileTree
1454 ariaLabel={`${reviewSectionTitle} files`}
1455 entries={fileTreeEntries}
1456 selectedPath={selectedFilePath}
1457 revealRequestId={selectedFileRevealRequestId}
1458 onSelectFile={revealDiffFile}
1459 />
1460 </aside>
1461 ) : null}
1462 </div>
1463 ) : (
1464 <div className="min-h-0 flex-1 overflow-auto p-2">
1465 <div className="space-y-2">
1466 <p className="text-2xs text-muted-foreground/75">
1467 {renderablePatch?.kind === "raw" ? renderablePatch.reason : null}
1468 </p>
1469 <pre
1470 className={cn(
1471 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-2xs leading-relaxed text-muted-foreground/90",
1472 wordWrap
1473 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
1474 : "overflow-auto",
1475 )}
1477 {renderablePatch?.kind === "raw" ? renderablePatch.text : null}
1478 </pre>
1479 </div>
1480 </div>
1481 )}
1482 </div>
1483 </>
1484 )}
1485 </DiffPanelShell>
1486 );