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

DiffPanel.tsx

910 lines36.9 KB

1import { useAtomValue } from "@effect/atom-react";
2import { useParams } from "@tanstack/react-router";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
8import type { ScopedThreadRef, RunId } from "@t3tools/contracts";
9import {
10 ArrowRightIcon,
11 CheckIcon,
12 ChevronDownIcon,
13 ChevronRightIcon,
14 Columns2Icon,
15 PilcrowIcon,
16 Rows3Icon,
17 SearchIcon,
18 TextWrapIcon,
19} from "lucide-react";
20import { useCallback, useEffect, useMemo, useRef, useState } from "react";
21import { useOpenInPreferredEditor } from "../editorPreferences";
22import { type DraftId } from "../composerDraftStore";
23import { openDiffFilePrimaryAction } from "../diffFileActions";
24import { useCheckpointDiff } from "~/lib/checkpointDiffState";
25import { cn } from "~/lib/utils";
26import { selectThreadDiffPanelSelection, useDiffPanelStore } from "../diffPanelStore";
27import { useTheme } from "../hooks/useTheme";
28import {
29 buildFileDiffRenderKey,
30 getDiffCollapseIconClassName,
31 getRenderablePatch,
32 resolveDiffThemeName,
33 resolveFileDiffPath,
34} from "../lib/diffRendering";
35import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
36import { useProject, useThreadProjection, useThreadShell } from "../state/entities";
37import { resolveThreadRouteRef } from "../threadRoutes";
38import { useClientSettings } from "../hooks/useSettings";
39import { formatShortTimestamp } from "../timestampFormat";
40import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
41import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
42import { ToggleGroup, Toggle } from "./ui/toggle-group";
43import { Switch } from "./ui/switch";
44import {
45 Combobox,
46 ComboboxEmpty,
47 ComboboxInput,
48 ComboboxItem,
49 ComboboxList,
50 ComboboxPopup,
51 ComboboxTrigger,
52} from "./ui/combobox";
53import {
54 DropdownMenu,
55 DropdownMenuContent,
56 DropdownMenuItem,
57 DropdownMenuSub,
58 DropdownMenuSubContent,
59 DropdownMenuSubTrigger,
60 DropdownMenuTrigger,
61} from "./ui/menu";
62import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
63import { useEnvironmentQuery } from "../state/query";
64import { serverEnvironment } from "../state/server";
65import { reviewEnvironment } from "../state/review";
66import { vcsEnvironment } from "../state/vcs";
67import { buildBaseRefChoices, filterBaseRefChoices } from "../lib/baseRefChoices";
68​
69type DiffRenderMode = "stacked" | "split";
70type DiffThemeType = "light" | "dark";
71const AUTOMATIC_BASE_REF = "__automatic_base_ref__";
72​
73interface CollapsedDiffFilesState {
74 readonly scopeKey: string | null;
75 readonly fileKeys: ReadonlySet<string>;
77​
78const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
79​
80const DIFF_PANEL_UNSAFE_CSS = `
81[data-diffs-header],
82[data-diff],
83[data-file],
84[data-error-wrapper],
85[data-virtualizer-buffer] {
86 --diffs-header-font-family: var(--font-sans) !important;
87 --diffs-font-family: var(--font-mono) !important;
88 --diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
89 --diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
90 --diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
91 --diffs-token-light-bg: transparent;
92 --diffs-token-dark-bg: transparent;
93​
94 --diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
95 --diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
96 --diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
97 --diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
98​
99 --diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
100 --diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
101 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
102 --diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
103​
104 --diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
105 --diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
106 --diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
107 --diffs-bg-deletion-emphasis-override: color-mix(
108 in srgb,
109 var(--background) 80%,
110 var(--destructive)
111 );
112​
113 background-color: var(--diffs-bg) !important;
115​
116[data-file-info] {
117 background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
118 border-block-color: var(--border) !important;
119 color: var(--foreground) !important;
121​
122[data-diffs-header] {
123 position: sticky !important;
124 top: 0;
125 z-index: 4;
126 background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
127 border-bottom: 1px solid var(--border) !important;
128 align-items: center !important;
129 font-family: var(--font-sans) !important;
130 font-size: 12px !important;
131 line-height: 1 !important;
132 min-height: 32px !important;
133 padding-block: 6px !important;
135​
136[data-diffs-header] [data-header-content] {
137 align-items: center !important;
138 line-height: 1 !important;
140​
141[data-diffs-header] [data-metadata] {
142 align-items: center !important;
143 line-height: 1 !important;
144 font-variant-numeric: tabular-nums;
146​
147[data-diffs-header] [data-additions-count],
148[data-diffs-header] [data-deletions-count] {
149 font-family: var(--font-mono) !important;
150 font-size: 11px !important;
151 font-variant-numeric: tabular-nums;
152 line-height: 1 !important;
154​
155[data-diffs-header] [data-change-icon],
156[data-diffs-header] [data-rename-icon] {
157 display: block;
158 flex-shrink: 0;
160​
161[data-title] {
162 cursor: pointer;
163 transition:
164 color 120ms ease,
165 text-decoration-color 120ms ease;
166 text-decoration: underline;
167 text-decoration-color: transparent;
168 text-underline-offset: 2px;
169 font-family: var(--font-sans) !important;
171​
172[data-title]:hover {
173 color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
174 text-decoration-color: currentColor;
176`;
177​
178interface DiffPanelProps {
179 mode?: DiffPanelMode;
180 composerDraftTarget: ScopedThreadRef | DraftId;
181 initialGitScope: "branch" | "unstaged";
183​
184export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
185​
186export default function DiffPanel({
187 mode = "inline",
188 composerDraftTarget,
189 initialGitScope: initialGitScopeProp,
190}: DiffPanelProps) {
191 const { resolvedTheme } = useTheme();
192 const settings = useClientSettings();
193 const [initialGitScope] = useState(initialGitScopeProp);
194 const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
195 const [wordWrap, setWordWrap] = useState(settings.wordWrap);
196 const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
197 const [baseRefQuery, setBaseRefQuery] = useState("");
198 const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
199 scopeKey: null,
200 fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS,
201 }));
202 const codeViewRef = useRef<AnnotatableCodeViewHandle>(null);
203​
204 const routeThreadRef = useParams({
205 strict: false,
206 select: (params) => resolveThreadRouteRef(params),
207 });
208 const activeThreadId = routeThreadRef?.threadId ?? null;
209 const activeThread = useThreadShell(routeThreadRef);
210 const activeThreadProjection = useThreadProjection(routeThreadRef)?.projection ?? null;
211 const activeProjectId = activeThread?.projectId ?? null;
212 const activeProject = useProject(
213 activeThread && activeProjectId
214 ? {
215 environmentId: activeThread.environmentId,
216 projectId: activeProjectId,
217 }
218 : null,
219 );
220 const activeCwd = activeThread?.worktreePath ?? activeProject?.workspaceRoot;
221 const serverConfig = useAtomValue(
222 serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),
223 );
224 const openInPreferredEditor = useOpenInPreferredEditor(
225 activeThread?.environmentId ?? null,
226 serverConfig?.availableEditors ?? [],
227 );
228 const gitStatusQuery = useEnvironmentQuery(
229 activeThread !== null && activeThread !== undefined && activeCwd != null
230 ? vcsEnvironment.status({
231 environmentId: activeThread.environmentId,
232 input: { cwd: activeCwd },
233 })
234 : null,
235 );
236 const diffSelection = useDiffPanelStore((state) =>
237 selectThreadDiffPanelSelection(
238 state.byThreadKey,
239 routeThreadRef,
240 initialGitScope === "unstaged",
241 ),
242 );
243 const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
244 const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } =
245 useTurnDiffSummaries(activeThreadProjection);
246 const orderedTurnDiffSummaries = useMemo(
247 () =>
248 [...turnDiffSummaries].toSorted((left, right) => {
249 const leftTurnCount =
250 left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0;
251 const rightTurnCount =
252 right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0;
253 if (leftTurnCount !== rightTurnCount) {
254 return rightTurnCount - leftTurnCount;
255 }
256 return right.completedAt.localeCompare(left.completedAt);
257 }),
258 [inferredCheckpointTurnCountByRunId, turnDiffSummaries],
259 );
260​
261 useEffect(() => {
262 if (!routeThreadRef || diffSelection.kind !== "turn") return;
263 useDiffPanelStore.getState().reconcileTurnSelection(
264 routeThreadRef,
265 orderedTurnDiffSummaries.map((summary) => summary.runId),
266 );
267 }, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
268​
269 const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
270 const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch";
271 const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null;
272 const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
273 const selectedFileRevealRequestId =
274 diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
275 const selectedTurn =
276 selectedRunId === null
277 ? undefined
278 : (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ??
279 orderedTurnDiffSummaries[0]);
280 const selectedCheckpointTurnCount =
281 selectedTurn &&
282 (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[selectedTurn.runId]);
283 const latestTurn = orderedTurnDiffSummaries[0];
284 const selectedScopeLabel =
285 selectedRunId === null
286 ? selectedGitScope === "unstaged"
287 ? "Working tree"
288 : "Branch changes"
289 : selectedTurn?.runId === latestTurn?.runId
290 ? "Latest turn"
291 : `Turn ${selectedCheckpointTurnCount ?? "?"}`;
292 const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope;
293 const collapseScopeKey = routeThreadRef
294 ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
295 : null;
296 const collapsedDiffFileKeys =
297 collapsedDiffFiles.scopeKey === collapseScopeKey
298 ? collapsedDiffFiles.fileKeys
299 : EMPTY_COLLAPSED_DIFF_FILE_KEYS;
300 const reviewSectionTitle = selectedTurn
301 ? `Turn ${selectedCheckpointTurnCount ?? "?"}`
302 : selectedGitScope === "unstaged"
303 ? "Working tree"
304 : "Branch changes";
305 const selectedCheckpointRange = useMemo(
306 () =>
307 typeof selectedCheckpointTurnCount === "number"
308 ? {
309 fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
310 toTurnCount: selectedCheckpointTurnCount,
311 }
312 : null,
313 [selectedCheckpointTurnCount],
314 );
315 const activeCheckpointDiff = useCheckpointDiff(
316 {
317 environmentId: activeThread?.environmentId ?? null,
318 threadId: activeThreadId,
319 fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
320 toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
321 ignoreWhitespace: diffIgnoreWhitespace,
322 cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null,
323 },
324 { enabled: isGitRepo && selectedTurn !== undefined },
325 );
326 const primaryBranchDiffPreview = useEnvironmentQuery(
327 selectedRunId === null && activeThread && activeCwd
328 ? reviewEnvironment.diffPreview({
329 environmentId: activeThread.environmentId,
330 input: {
331 cwd: activeCwd,
332 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
333 ignoreWhitespace: diffIgnoreWhitespace,
334 },
335 })
336 : null,
337 );
338 const shouldRetryBranchDiffAtEnvironmentCwd =
339 selectedRunId === null &&
340 primaryBranchDiffPreview.error?.includes("configured workspace root") === true &&
341 serverConfig?.cwd !== undefined &&
342 serverConfig.cwd !== activeCwd;
343 const fallbackBranchDiffPreview = useEnvironmentQuery(
344 shouldRetryBranchDiffAtEnvironmentCwd && activeThread && serverConfig
345 ? reviewEnvironment.diffPreview({
346 environmentId: activeThread.environmentId,
347 input: {
348 cwd: serverConfig.cwd,
349 ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}),
350 ignoreWhitespace: diffIgnoreWhitespace,
351 },
352 })
353 : null,
354 );
355 const branchDiffPreview = shouldRetryBranchDiffAtEnvironmentCwd
356 ? fallbackBranchDiffPreview
357 : primaryBranchDiffPreview;
358 const selectedGitSource = branchDiffPreview.data?.sources.find(
359 (source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
360 );
361 const localBranchRefs = useEnvironmentQuery(
362 selectedRunId === null &&
363 selectedGitScope === "branch" &&
364 activeThread &&
365 branchDiffPreview.data?.cwd
366 ? vcsEnvironment.listRefs({
367 environmentId: activeThread.environmentId,
368 input: {
369 cwd: branchDiffPreview.data.cwd,
370 includeMatchingRemoteRefs: true,
371 refKind: "local",
372 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
373 limit: 100,
374 },
375 })
376 : null,
377 );
378 const remoteBranchRefs = useEnvironmentQuery(
379 selectedRunId === null &&
380 selectedGitScope === "branch" &&
381 activeThread &&
382 branchDiffPreview.data?.cwd
383 ? vcsEnvironment.listRefs({
384 environmentId: activeThread.environmentId,
385 input: {
386 cwd: branchDiffPreview.data.cwd,
387 includeMatchingRemoteRefs: true,
388 refKind: "remote",
389 ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}),
390 limit: 100,
391 },
392 })
393 : null,
394 );
395 const baseRefChoices = buildBaseRefChoices(
396 localBranchRefs.data?.refs.filter((ref) => ref.name !== selectedGitSource?.headRef) ?? [],
397 remoteBranchRefs.data?.refs ?? [],
398 );
399 const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery);
400 const valueForBaseRefChoice = (choice: (typeof baseRefChoices)[number]) =>
401 selectedBaseRef && selectedBaseRef === choice.remote?.name
402 ? selectedBaseRef
403 : (choice.local?.name ?? choice.remote?.name ?? choice.id);
404 const baseRefItems = [AUTOMATIC_BASE_REF, ...baseRefChoices.map(valueForBaseRefChoice)];
405 const filteredBaseRefItems = [
406 ...(baseRefQuery.trim().length === 0 ? [AUTOMATIC_BASE_REF] : []),
407 ...matchingBaseRefChoices.map(valueForBaseRefChoice),
408 ];
409 const gitDiff = selectedGitSource?.diff;
410​
411 const selectedPatch = selectedTurn ? activeCheckpointDiff.data?.diff : gitDiff;
412 const isSelectedPatchTruncated = !selectedTurn && selectedGitSource?.truncated === true;
413 const isLoadingSelectedPatch = selectedTurn
414 ? activeCheckpointDiff.isPending
415 : branchDiffPreview.isPending;
416 const selectedPatchError = selectedTurn ? activeCheckpointDiff.error : branchDiffPreview.error;
417 const hasResolvedPatch = typeof selectedPatch === "string";
418 const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
419 const renderablePatch = useMemo(
420 () =>
421 getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, {
422 compactPartialHunkOffsets: selectedRunId === null,
423 }),
424 [resolvedTheme, selectedPatch, selectedRunId],
425 );
426 const renderableFiles = useMemo(() => {
427 if (!renderablePatch || renderablePatch.kind !== "files") {
428 return [];
429 }
430 return renderablePatch.files.toSorted((left, right) =>
431 resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
432 numeric: true,
433 sensitivity: "base",
434 }),
435 );
436 }, [renderablePatch]);
437 const codeViewFiles = useMemo(
438 () =>
439 renderableFiles.map((fileDiff) => {
440 const fileKey = buildFileDiffRenderKey(fileDiff);
441 return {
442 fileDiff,
443 filePath: resolveFileDiffPath(fileDiff),
444 fileKey,
445 collapsed: collapsedDiffFileKeys.has(fileKey),
446 };
447 }),
448 [collapsedDiffFileKeys, renderableFiles],
449 );
450​
451 useEffect(() => {
452 if (!selectedFilePath) return;
453 const file = codeViewFiles.find((candidate) => candidate.filePath === selectedFilePath);
454 if (!file) return;
455 codeViewRef.current?.scrollTo({ type: "item", id: file.fileKey, align: "start" });
456 }, [codeViewFiles, selectedFilePath, selectedFileRevealRequestId]);
457​
458 const openDiffFile = useCallback(
459 (filePath: string) => {
460 openDiffFilePrimaryAction({
461 threadRef: routeThreadRef,
462 filePath,
463 activeCwd,
464 openInEditor: (targetPath) => {
465 void (async () => {
466 const result = await openInPreferredEditor(targetPath);
467 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
468 console.warn("Failed to open diff file in editor.", {
469 operation: "open-diff-file",
470 ...(routeThreadRef
471 ? {
472 environmentId: routeThreadRef.environmentId,
473 threadId: routeThreadRef.threadId,
474 }
475 : {}),
476 ...safeErrorLogAttributes(squashAtomCommandFailure(result)),
477 });
478 }
479 })();
480 },
481 });
482 },
483 [activeCwd, openInPreferredEditor, routeThreadRef],
484 );
485 const toggleDiffFileCollapsed = useCallback(
486 (fileKey: string) => {
487 setCollapsedDiffFiles((current) => {
488 const next = new Set(current.scopeKey === collapseScopeKey ? current.fileKeys : []);
489 if (next.has(fileKey)) {
490 next.delete(fileKey);
491 } else {
492 next.add(fileKey);
493 }
494 return { scopeKey: collapseScopeKey, fileKeys: next };
495 });
496 },
497 [collapseScopeKey],
498 );
499​
500 const selectTurn = (runId: RunId) => {
501 if (!routeThreadRef) return;
502 useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
503 };
504 const selectGitScope = (scope: "branch" | "unstaged") => {
505 if (!routeThreadRef) return;
506 useDiffPanelStore.getState().selectGitScope(routeThreadRef, scope);
507 };
508 const selectBranchBaseRef = (baseRef: string | null) => {
509 if (!routeThreadRef) return;
510 useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef);
511 };
512​
513 const headerRow = (
514 <>
515 <div className="flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
516 <DropdownMenu>
517 <DropdownMenuTrigger
518 className="inline-flex h-6 max-w-full items-center gap-1 rounded-md bg-muted/70 px-2 text-xs font-medium text-foreground outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
519 aria-label={`Diff scope: ${selectedScopeLabel}`}
520 >
521 <span className="truncate">{selectedScopeLabel}</span>
522 <ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" />
523 </DropdownMenuTrigger>
524 <DropdownMenuContent align="start" className="w-60">
525 <DropdownMenuItem
526 className={
527 selectedRunId === null && selectedGitScope === "unstaged"
528 ? "bg-foreground/[0.08]"
529 : undefined
530 }
531 onClick={() => selectGitScope("unstaged")}
532 >
533 <span>Working tree</span>
534 {selectedRunId === null && selectedGitScope === "unstaged" && (
535 <CheckIcon className="ml-auto" />
536 )}
537 </DropdownMenuItem>
538 <DropdownMenuItem
539 className={
540 selectedRunId === null && selectedGitScope === "branch"
541 ? "bg-foreground/[0.08]"
542 : undefined
543 }
544 onClick={() => selectGitScope("branch")}
545 >
546 <span>Branch changes</span>
547 {selectedRunId === null && selectedGitScope === "branch" && (
548 <CheckIcon className="ml-auto" />
549 )}
550 </DropdownMenuItem>
551 <DropdownMenuItem
552 className={
553 selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId
554 ? "bg-foreground/[0.08]"
555 : undefined
556 }
557 onClick={() => {
558 if (latestTurn) selectTurn(latestTurn.runId);
559 }}
560 >
561 <span>Latest turn</span>
562 {selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId && (
563 <CheckIcon className="ml-auto" />
564 )}
565 </DropdownMenuItem>
566 <DropdownMenuSub>
567 <DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
568 <DropdownMenuSubContent className="w-64">
569 {orderedTurnDiffSummaries.map((summary) => {
570 const turnCount =
571 summary.checkpointTurnCount ??
572 inferredCheckpointTurnCountByRunId[summary.runId] ??
573 "?";
574 return (
575 <DropdownMenuItem
576 key={summary.runId}
577 className={
578 summary.runId === selectedTurn?.runId ? "bg-foreground/[0.08]" : undefined
579 }
580 onClick={() => selectTurn(summary.runId)}
581 >
582 <span>Turn {turnCount}</span>
583 <span className="ml-auto text-xs tabular-nums text-muted-foreground">
584 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
585 </span>
586 {summary.runId === selectedTurn?.runId && <CheckIcon className="ml-1" />}
587 </DropdownMenuItem>
588 );
589 })}
590 </DropdownMenuSubContent>
591 </DropdownMenuSub>
592 </DropdownMenuContent>
593 </DropdownMenu>
594 {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
595 <div
596 className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
597 title={`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
598 aria-label={`Comparing ${selectedGitSource.headRef ?? "HEAD"} against ${selectedGitSource.baseRef}`}
599 >
600 <span className="min-w-0 max-w-48 truncate">{selectedGitSource.headRef ?? "HEAD"}</span>
601 <ArrowRightIcon className="size-3.5 shrink-0 opacity-70" />
602 <Combobox
603 items={baseRefItems}
604 filteredItems={filteredBaseRefItems}
605 value={selectedBaseRef ?? AUTOMATIC_BASE_REF}
606 onOpenChange={(open) => {
607 if (!open) setBaseRefQuery("");
608 }}
609 onValueChange={(value) => {
610 if (!value) return;
611 selectBranchBaseRef(value === AUTOMATIC_BASE_REF ? null : value);
612 }}
613 >
614 <ComboboxTrigger
615 className="inline-flex min-w-0 max-w-48 items-center gap-1 overflow-hidden rounded-md px-1.5 py-1 outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
616 aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`}
617 >
618 <span className="min-w-0 truncate">{selectedGitSource.baseRef}</span>
619 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
620 </ComboboxTrigger>
621 <ComboboxPopup
622 align="start"
623 className="w-72 min-w-0 max-w-[calc(100vw-1rem)] overflow-hidden [&>[data-slot=combobox-popup]]:min-w-0 [&>[data-slot=combobox-popup]]:overflow-hidden"
624 >
625 <div className="min-w-0 shrink-0 px-3 pt-2.5">
626 <div className="relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring">
627 <SearchIcon
628 aria-hidden="true"
629 className="pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55"
630 />
631 <ComboboxInput
632 className="[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5"
633 inputClassName="rounded-none bg-transparent text-sm"
634 placeholder="Search refs..."
635 showTrigger={false}
636 size="sm"
637 unstyled
638 value={baseRefQuery}
639 onChange={(event) => setBaseRefQuery(event.target.value)}
640 />
641 </div>
642 </div>
643 <div className="grid shrink-0 grid-cols-[1rem_minmax(0,1fr)] items-center gap-2 border-b border-border/70 ps-3 pe-6.5 pt-2 pb-1.5 font-medium text-[10px] text-muted-foreground uppercase tracking-wide">
644 <span aria-hidden="true" />
645 <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center">
646 <span>Branch</span>
647 <span className="text-right">Remote</span>
648 </div>
649 </div>
650 <ComboboxEmpty>No matching refs.</ComboboxEmpty>
651 <ComboboxList className="max-h-64 min-w-0 overflow-x-hidden">
652 <ComboboxItem
653 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
654 contentClassName="w-full min-w-0 overflow-hidden"
655 value={AUTOMATIC_BASE_REF}
656 >
657 <span className="block min-w-0 truncate">Automatic</span>
658 </ComboboxItem>
659 {baseRefChoices.map((choice) => {
660 const item = valueForBaseRefChoice(choice);
661 const hasBoth = choice.local !== null && choice.remote !== null;
662 const useRemote = choice.remote?.name === item;
663 return (
664 <ComboboxItem
665 key={choice.id}
666 className="h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0"
667 contentClassName="w-full min-w-0 overflow-hidden"
668 value={item}
669 >
670 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden">
671 <span className="block min-w-0 truncate pe-2">{choice.label}</span>
672 {hasBoth ? (
673 <div
674 className="flex justify-end"
675 onClick={(event) => event.stopPropagation()}
676 onPointerDown={(event) => event.stopPropagation()}
677 >
678 <Switch
679 aria-label={`Use remote version of ${choice.label}`}
680 checked={useRemote}
681 className="[--thumb-size:--spacing(3)]"
682 onCheckedChange={(checked) => {
683 const nextRef = checked
684 ? choice.remote?.name
685 : choice.local?.name;
686 if (nextRef) selectBranchBaseRef(nextRef);
687 }}
688 />
689 </div>
690 ) : choice.remote ? (
691 <span
692 className="flex justify-end text-muted-foreground"
693 title="Remote only"
694 >
695 <CheckIcon aria-hidden="true" className="size-3" />
696 </span>
697 ) : null}
698 </div>
699 </ComboboxItem>
700 );
701 })}
702 </ComboboxList>
703 </ComboboxPopup>
704 </Combobox>
705 </div>
706 )}
707 </div>
708 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
709 <ToggleGroup
710 className="shrink-0"
711 variant="outline"
712 size="xs"
713 value={[diffRenderMode]}
714 onValueChange={(value) => {
715 const next = value[0];
716 if (next === "stacked" || next === "split") {
717 setDiffRenderMode(next);
718 }
719 }}
720 >
721 <Toggle aria-label="Stacked diff view" value="stacked">
722 <Rows3Icon className="size-3" />
723 </Toggle>
724 <Toggle aria-label="Split diff view" value="split">
725 <Columns2Icon className="size-3" />
726 </Toggle>
727 </ToggleGroup>
728 <Tooltip>
729 <TooltipTrigger
730 render={
731 <Toggle
732 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
733 variant="outline"
734 size="xs"
735 pressed={wordWrap}
736 onPressedChange={(pressed) => {
737 setWordWrap(Boolean(pressed));
738 }}
739 />
740 }
741 >
742 <TextWrapIcon className="size-3" />
743 </TooltipTrigger>
744 <TooltipPopup side="top">
745 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
746 </TooltipPopup>
747 </Tooltip>
748 <Tooltip>
749 <TooltipTrigger
750 render={
751 <Toggle
752 aria-label={
753 diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
754 }
755 variant="outline"
756 size="xs"
757 pressed={diffIgnoreWhitespace}
758 onPressedChange={(pressed) => {
759 setDiffIgnoreWhitespace(Boolean(pressed));
760 }}
761 />
762 }
763 >
764 <PilcrowIcon className="size-3" />
765 </TooltipTrigger>
766 <TooltipPopup side="top">
767 {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
768 </TooltipPopup>
769 </Tooltip>
770 </div>
771 </>
772 );
773​
774 return (
775 <DiffPanelShell mode={mode} header={headerRow}>
776 {!activeThread ? (
777 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
778 Select a thread to inspect turn diffs.
779 </div>
780 ) : !isGitRepo ? (
781 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
782 Turn diffs are unavailable because this project is not a git repository.
783 </div>
784 ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
785 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
786 No completed turns yet.
787 </div>
788 ) : (
789 <>
790 <div className="diff-panel-viewport flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
791 {isSelectedPatchTruncated && (
792 <p className="shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground">
793 This diff was truncated because it exceeded the preview limit. The changes shown are
794 incomplete.
795 </p>
796 )}
797 {selectedPatchError && !renderablePatch && (
798 <div className="px-3">
799 <p className="mb-2 text-[11px] text-red-500/80">{selectedPatchError}</p>
800 </div>
801 )}
802 {!renderablePatch ? (
803 isLoadingSelectedPatch ? (
804 <DiffPanelLoadingState
805 label={
806 selectedTurn
807 ? "Loading checkpoint diff..."
808 : selectedGitScope === "unstaged"
809 ? "Loading working tree diff..."
810 : "Loading branch diff..."
811 }
812 />
813 ) : (
814 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
815 <p>
816 {hasNoNetChanges
817 ? "No net changes in this selection."
818 : "No patch available for this selection."}
819 </p>
820 </div>
821 )
822 ) : renderablePatch.kind === "files" ? (
823 <div
824 className="min-h-0 flex-1"
825 onClickCapture={(event) => {
826 const composedPath = event.nativeEvent.composedPath?.() ?? [];
827 const title = composedPath.find(
828 (node): node is HTMLElement =>
829 node instanceof HTMLElement && node.hasAttribute("data-title"),
830 );
831 const filePath = title?.textContent?.trim();
832 if (filePath) openDiffFile(filePath);
833 }}
834 >
835 <AnnotatableCodeView
836 viewerRef={codeViewRef}
837 key={collapseScopeKey ?? reviewSectionId}
838 className="diff-render-surface h-full min-h-0 overflow-auto"
839 files={codeViewFiles}
840 sectionId={reviewSectionId}
841 sectionTitle={reviewSectionTitle}
842 composerDraftTarget={composerDraftTarget}
843 renderHeaderPrefix={(fileDiff, fileKey, collapsed) => {
844 const filePath = resolveFileDiffPath(fileDiff);
845 return (
846 <Tooltip>
847 <TooltipTrigger
848 render={
849 <button
850 type="button"
851 className={cn(
852 "inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
853 getDiffCollapseIconClassName(fileDiff),
854 )}
855 aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
856 aria-expanded={!collapsed}
857 onClick={(event) => {
858 event.stopPropagation();
859 toggleDiffFileCollapsed(fileKey);
860 }}
861 />
862 }
863 >
864 {collapsed ? (
865 <ChevronRightIcon className="size-4" />
866 ) : (
867 <ChevronDownIcon className="size-4" />
868 )}
869 </TooltipTrigger>
870 <TooltipPopup side="top">
871 {collapsed ? "Expand diff" : "Collapse diff"}
872 </TooltipPopup>
873 </Tooltip>
874 );
875 }}
876 options={{
877 diffStyle: diffRenderMode === "split" ? "split" : "unified",
878 lineDiffType: "none",
879 overflow: wordWrap ? "wrap" : "scroll",
880 theme: resolveDiffThemeName(resolvedTheme),
881 themeType: resolvedTheme as DiffThemeType,
882 unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
883 stickyHeaders: true,
884 layout: { paddingTop: 8, paddingBottom: 8, gap: 8 },
885 }}
886 />
887 </div>
888 ) : (
889 <div className="min-h-0 flex-1 overflow-auto p-2">
890 <div className="space-y-2">
891 <p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
892 <pre
893 className={cn(
894 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
895 wordWrap
896 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
897 : "overflow-auto",
898 )}
899 >
900 {renderablePatch.text}
901 </pre>
902 </div>
903 </div>
904 )}
905 </div>
906 </>
907 )}
908 </DiffPanelShell>
909 );