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