The best way to control Claude Code, Codex and more from any computer or phone

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