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

DiffPanel.tsx

676 lines25.9 KB

1import { parsePatchFiles } from "@pierre/diffs";
2import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/react";
3import { useQuery } from "@tanstack/react-query";
4import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
5import { scopeThreadRef } from "@t3tools/client-runtime";
6import type { TurnId } from "@t3tools/contracts";
7import {
8 ChevronLeftIcon,
9 ChevronRightIcon,
10 Columns2Icon,
11 PilcrowIcon,
12 Rows3Icon,
13 TextWrapIcon,
14} from "lucide-react";
15import {
16 type WheelEvent as ReactWheelEvent,
17 useCallback,
18 useEffect,
19 useMemo,
20 useRef,
21 useState,
22} from "react";
23import { openInPreferredEditor } from "../editorPreferences";
24import { useGitStatus } from "~/lib/gitStatusState";
25import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
26import { cn } from "~/lib/utils";
27import { readLocalApi } from "../localApi";
28import { resolvePathLinkTarget } from "../terminal-links";
29import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
30import { useTheme } from "../hooks/useTheme";
31import { buildPatchCacheKey } from "../lib/diffRendering";
32import { resolveDiffThemeName } from "../lib/diffRendering";
33import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
34import { selectProjectByRef, useStore } from "../store";
35import { createThreadSelectorByRef } from "../storeSelectors";
36import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
37import { useSettings } from "../hooks/useSettings";
38import { formatShortTimestamp } from "../timestampFormat";
39import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
40import { ToggleGroup, Toggle } from "./ui/toggle-group";
41​
42type DiffRenderMode = "stacked" | "split";
43type DiffThemeType = "light" | "dark";
44​
45const DIFF_PANEL_UNSAFE_CSS = `
46[data-diffs-header],
47[data-diff],
48[data-file],
49[data-error-wrapper],
50[data-virtualizer-buffer] {
51 --diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
52 --diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
53 --diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
54 --diffs-token-light-bg: transparent;
55 --diffs-token-dark-bg: transparent;
56​
57 --diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
58 --diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
59 --diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
60 --diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
61​
62 --diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
63 --diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
64 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
65 --diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
66​
67 --diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
68 --diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
69 --diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
70 --diffs-bg-deletion-emphasis-override: color-mix(
71 in srgb,
72 var(--background) 80%,
73 var(--destructive)
74 );
75​
76 background-color: var(--diffs-bg) !important;
78​
79[data-file-info] {
80 background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
81 border-block-color: var(--border) !important;
82 color: var(--foreground) !important;
84​
85[data-diffs-header] {
86 position: sticky !important;
87 top: 0;
88 z-index: 4;
89 background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
90 border-bottom: 1px solid var(--border) !important;
92​
93[data-title] {
94 cursor: pointer;
95 transition:
96 color 120ms ease,
97 text-decoration-color 120ms ease;
98 text-decoration: underline;
99 text-decoration-color: transparent;
100 text-underline-offset: 2px;
102​
103[data-title]:hover {
104 color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
105 text-decoration-color: currentColor;
107`;
108​
109type RenderablePatch =
110 | {
111 kind: "files";
112 files: FileDiffMetadata[];
113 }
114 | {
115 kind: "raw";
116 text: string;
117 reason: string;
118 };
119​
120function getRenderablePatch(
121 patch: string | undefined,
122 cacheScope = "diff-panel",
123): RenderablePatch | null {
124 if (!patch) return null;
125 const normalizedPatch = patch.trim();
126 if (normalizedPatch.length === 0) return null;
127​
128 try {
129 const parsedPatches = parsePatchFiles(
130 normalizedPatch,
131 buildPatchCacheKey(normalizedPatch, cacheScope),
132 );
133 const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
134 if (files.length > 0) {
135 return { kind: "files", files };
136 }
137​
138 return {
139 kind: "raw",
140 text: normalizedPatch,
141 reason: "Unsupported diff format. Showing raw patch.",
142 };
143 } catch {
144 return {
145 kind: "raw",
146 text: normalizedPatch,
147 reason: "Failed to parse patch. Showing raw patch.",
148 };
149 }
151​
152function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
153 const raw = fileDiff.name ?? fileDiff.prevName ?? "";
154 if (raw.startsWith("a/") || raw.startsWith("b/")) {
155 return raw.slice(2);
156 }
157 return raw;
159​
160function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
161 return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
163​
164interface DiffPanelProps {
165 mode?: DiffPanelMode;
167​
168export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
169​
170export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
171 const navigate = useNavigate();
172 const { resolvedTheme } = useTheme();
173 const settings = useSettings();
174 const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
175 const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
176 const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
177 const patchViewportRef = useRef<HTMLDivElement>(null);
178 const turnStripRef = useRef<HTMLDivElement>(null);
179 const previousDiffOpenRef = useRef(false);
180 const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
181 const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
182 const routeThreadRef = useParams({
183 strict: false,
184 select: (params) => resolveThreadRouteRef(params),
185 });
186 const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
187 const diffOpen = diffSearch.diff === "1";
188 const activeThreadId = routeThreadRef?.threadId ?? null;
189 const activeThread = useStore(
190 useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
191 );
192 const activeProjectId = activeThread?.projectId ?? null;
193 const activeProject = useStore((store) =>
194 activeThread && activeProjectId
195 ? selectProjectByRef(store, {
196 environmentId: activeThread.environmentId,
197 projectId: activeProjectId,
198 })
199 : undefined,
200 );
201 const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
202 const gitStatusQuery = useGitStatus({
203 environmentId: activeThread?.environmentId ?? null,
204 cwd: activeCwd ?? null,
205 });
206 const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
207 const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
208 useTurnDiffSummaries(activeThread);
209 const orderedTurnDiffSummaries = useMemo(
210 () =>
211 [...turnDiffSummaries].toSorted((left, right) => {
212 const leftTurnCount =
213 left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
214 const rightTurnCount =
215 right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
216 if (leftTurnCount !== rightTurnCount) {
217 return rightTurnCount - leftTurnCount;
218 }
219 return right.completedAt.localeCompare(left.completedAt);
220 }),
221 [inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
222 );
223​
224 const selectedTurnId = diffSearch.diffTurnId ?? null;
225 const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
226 const selectedTurn =
227 selectedTurnId === null
228 ? undefined
229 : (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
230 orderedTurnDiffSummaries[0]);
231 const selectedCheckpointTurnCount =
232 selectedTurn &&
233 (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
234 const selectedCheckpointRange = useMemo(
235 () =>
236 typeof selectedCheckpointTurnCount === "number"
237 ? {
238 fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
239 toTurnCount: selectedCheckpointTurnCount,
240 }
241 : null,
242 [selectedCheckpointTurnCount],
243 );
244 const conversationCheckpointTurnCount = useMemo(() => {
245 const turnCounts = orderedTurnDiffSummaries
246 .map(
247 (summary) =>
248 summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
249 )
250 .filter((value): value is number => typeof value === "number");
251 if (turnCounts.length === 0) {
252 return undefined;
253 }
254 const latest = Math.max(...turnCounts);
255 return latest > 0 ? latest : undefined;
256 }, [inferredCheckpointTurnCountByTurnId, orderedTurnDiffSummaries]);
257 const conversationCheckpointRange = useMemo(
258 () =>
259 !selectedTurn && typeof conversationCheckpointTurnCount === "number"
260 ? {
261 fromTurnCount: 0,
262 toTurnCount: conversationCheckpointTurnCount,
263 }
264 : null,
265 [conversationCheckpointTurnCount, selectedTurn],
266 );
267 const activeCheckpointRange = selectedTurn
268 ? selectedCheckpointRange
269 : conversationCheckpointRange;
270 const conversationCacheScope = useMemo(() => {
271 if (selectedTurn || orderedTurnDiffSummaries.length === 0) {
272 return null;
273 }
274 return `conversation:${orderedTurnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
275 }, [orderedTurnDiffSummaries, selectedTurn]);
276 const activeCheckpointDiffQuery = useQuery(
277 checkpointDiffQueryOptions({
278 environmentId: activeThread?.environmentId ?? null,
279 threadId: activeThreadId,
280 fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
281 toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
282 ignoreWhitespace: diffIgnoreWhitespace,
283 cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
284 enabled: isGitRepo,
285 }),
286 );
287 const selectedTurnCheckpointDiff = selectedTurn
288 ? activeCheckpointDiffQuery.data?.diff
289 : undefined;
290 const conversationCheckpointDiff = selectedTurn
291 ? undefined
292 : activeCheckpointDiffQuery.data?.diff;
293 const isLoadingCheckpointDiff = activeCheckpointDiffQuery.isLoading;
294 const checkpointDiffError =
295 activeCheckpointDiffQuery.error instanceof Error
296 ? activeCheckpointDiffQuery.error.message
297 : activeCheckpointDiffQuery.error
298 ? "Failed to load checkpoint diff."
299 : null;
300​
301 const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
302 const hasResolvedPatch = typeof selectedPatch === "string";
303 const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
304 const renderablePatch = useMemo(
305 () => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`),
306 [resolvedTheme, selectedPatch],
307 );
308 const renderableFiles = useMemo(() => {
309 if (!renderablePatch || renderablePatch.kind !== "files") {
310 return [];
311 }
312 return renderablePatch.files.toSorted((left, right) =>
313 resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
314 numeric: true,
315 sensitivity: "base",
316 }),
317 );
318 }, [renderablePatch]);
319​
320 useEffect(() => {
321 if (diffOpen && !previousDiffOpenRef.current) {
322 setDiffWordWrap(settings.diffWordWrap);
323 setDiffIgnoreWhitespace(settings.diffIgnoreWhitespace);
324 }
325 previousDiffOpenRef.current = diffOpen;
326 }, [diffOpen, settings.diffIgnoreWhitespace, settings.diffWordWrap]);
327​
328 useEffect(() => {
329 if (!selectedFilePath || !patchViewportRef.current) {
330 return;
331 }
332 const target = Array.from(
333 patchViewportRef.current.querySelectorAll<HTMLElement>("[data-diff-file-path]"),
334 ).find((element) => element.dataset.diffFilePath === selectedFilePath);
335 target?.scrollIntoView({ block: "nearest" });
336 }, [selectedFilePath, renderableFiles]);
337​
338 const openDiffFileInEditor = useCallback(
339 (filePath: string) => {
340 const api = readLocalApi();
341 if (!api) return;
342 const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
343 void openInPreferredEditor(api, targetPath).catch((error) => {
344 console.warn("Failed to open diff file in editor.", error);
345 });
346 },
347 [activeCwd],
348 );
349​
350 const selectTurn = (turnId: TurnId) => {
351 if (!activeThread) return;
352 void navigate({
353 to: "/$environmentId/$threadId",
354 params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)),
355 search: (previous) => {
356 const rest = stripDiffSearchParams(previous);
357 return { ...rest, diff: "1", diffTurnId: turnId };
358 },
359 });
360 };
361 const selectWholeConversation = () => {
362 if (!activeThread) return;
363 void navigate({
364 to: "/$environmentId/$threadId",
365 params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)),
366 search: (previous) => {
367 const rest = stripDiffSearchParams(previous);
368 return { ...rest, diff: "1" };
369 },
370 });
371 };
372 const updateTurnStripScrollState = useCallback(() => {
373 const element = turnStripRef.current;
374 if (!element) {
375 setCanScrollTurnStripLeft(false);
376 setCanScrollTurnStripRight(false);
377 return;
378 }
379​
380 const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
381 setCanScrollTurnStripLeft(element.scrollLeft > 4);
382 setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
383 }, []);
384 const scrollTurnStripBy = useCallback((offset: number) => {
385 const element = turnStripRef.current;
386 if (!element) return;
387 element.scrollBy({ left: offset, behavior: "smooth" });
388 }, []);
389 const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
390 const element = turnStripRef.current;
391 if (!element) return;
392 if (element.scrollWidth <= element.clientWidth + 1) return;
393 if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
394​
395 event.preventDefault();
396 element.scrollBy({ left: event.deltaY, behavior: "auto" });
397 }, []);
398​
399 useEffect(() => {
400 const element = turnStripRef.current;
401 if (!element) return;
402​
403 const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
404 const onScroll = () => updateTurnStripScrollState();
405​
406 element.addEventListener("scroll", onScroll, { passive: true });
407​
408 const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
409 resizeObserver.observe(element);
410​
411 return () => {
412 window.cancelAnimationFrame(frameId);
413 element.removeEventListener("scroll", onScroll);
414 resizeObserver.disconnect();
415 };
416 }, [updateTurnStripScrollState]);
417​
418 useEffect(() => {
419 const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
420 return () => {
421 window.cancelAnimationFrame(frameId);
422 };
423 }, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
424​
425 useEffect(() => {
426 const element = turnStripRef.current;
427 if (!element) return;
428​
429 const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
430 selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
431 }, [selectedTurn?.turnId, selectedTurnId]);
432​
433 const headerRow = (
434 <>
435 <div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
436 <button
437 type="button"
438 className={cn(
439 "absolute left-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
440 canScrollTurnStripLeft
441 ? "border-border/70 hover:border-border hover:text-foreground"
442 : "cursor-not-allowed border-border/40 text-muted-foreground/40",
443 )}
444 onClick={() => scrollTurnStripBy(-180)}
445 disabled={!canScrollTurnStripLeft}
446 aria-label="Scroll turn list left"
447 >
448 <ChevronLeftIcon className="size-3.5" />
449 </button>
450 <button
451 type="button"
452 className={cn(
453 "absolute right-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
454 canScrollTurnStripRight
455 ? "border-border/70 hover:border-border hover:text-foreground"
456 : "cursor-not-allowed border-border/40 text-muted-foreground/40",
457 )}
458 onClick={() => scrollTurnStripBy(180)}
459 disabled={!canScrollTurnStripRight}
460 aria-label="Scroll turn list right"
461 >
462 <ChevronRightIcon className="size-3.5" />
463 </button>
464 <div
465 ref={turnStripRef}
466 className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
467 style={
468 canScrollTurnStripLeft || canScrollTurnStripRight
469 ? {
470 maskImage: `linear-gradient(to right, ${canScrollTurnStripLeft ? "transparent 24px, black 72px" : "black"}, ${canScrollTurnStripRight ? "black calc(100% - 72px), transparent calc(100% - 24px)" : "black"})`,
471 }
472 : undefined
473 }
474 onWheel={onTurnStripWheel}
475 >
476 <button
477 type="button"
478 className="shrink-0 rounded-md"
479 onClick={selectWholeConversation}
480 data-turn-chip-selected={selectedTurnId === null}
481 >
482 <div
483 className={cn(
484 "rounded-md border px-2 py-1 text-left transition-colors",
485 selectedTurnId === null
486 ? "border-border bg-accent text-accent-foreground"
487 : "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
488 )}
489 >
490 <div className="text-[10px] leading-tight font-medium">All turns</div>
491 </div>
492 </button>
493 {orderedTurnDiffSummaries.map((summary) => (
494 <button
495 key={summary.turnId}
496 type="button"
497 className="shrink-0 rounded-md"
498 onClick={() => selectTurn(summary.turnId)}
499 title={summary.turnId}
500 data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
501 >
502 <div
503 className={cn(
504 "rounded-md border px-2 py-1 text-left transition-colors",
505 summary.turnId === selectedTurn?.turnId
506 ? "border-border bg-accent text-accent-foreground"
507 : "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
508 )}
509 >
510 <div className="flex items-center gap-1">
511 <span className="text-[10px] leading-tight font-medium">
512 Turn{" "}
513 {summary.checkpointTurnCount ??
514 inferredCheckpointTurnCountByTurnId[summary.turnId] ??
515 "?"}
516 </span>
517 <span className="text-[9px] leading-tight opacity-70">
518 {formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
519 </span>
520 </div>
521 </div>
522 </button>
523 ))}
524 </div>
525 </div>
526 <div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
527 <ToggleGroup
528 className="shrink-0"
529 variant="outline"
530 size="xs"
531 value={[diffRenderMode]}
532 onValueChange={(value) => {
533 const next = value[0];
534 if (next === "stacked" || next === "split") {
535 setDiffRenderMode(next);
536 }
537 }}
538 >
539 <Toggle aria-label="Stacked diff view" value="stacked">
540 <Rows3Icon className="size-3" />
541 </Toggle>
542 <Toggle aria-label="Split diff view" value="split">
543 <Columns2Icon className="size-3" />
544 </Toggle>
545 </ToggleGroup>
546 <Toggle
547 aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
548 title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
549 variant="outline"
550 size="xs"
551 pressed={diffWordWrap}
552 onPressedChange={(pressed) => {
553 setDiffWordWrap(Boolean(pressed));
554 }}
555 >
556 <TextWrapIcon className="size-3" />
557 </Toggle>
558 <Toggle
559 aria-label={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
560 title={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
561 variant="outline"
562 size="xs"
563 pressed={diffIgnoreWhitespace}
564 onPressedChange={(pressed) => {
565 setDiffIgnoreWhitespace(Boolean(pressed));
566 }}
567 >
568 <PilcrowIcon className="size-3" />
569 </Toggle>
570 </div>
571 </>
572 );
573​
574 return (
575 <DiffPanelShell mode={mode} header={headerRow}>
576 {!activeThread ? (
577 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
578 Select a thread to inspect turn diffs.
579 </div>
580 ) : !isGitRepo ? (
581 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
582 Turn diffs are unavailable because this project is not a git repository.
583 </div>
584 ) : orderedTurnDiffSummaries.length === 0 ? (
585 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
586 No completed turns yet.
587 </div>
588 ) : (
589 <>
590 <div
591 ref={patchViewportRef}
592 className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
593 >
594 {checkpointDiffError && !renderablePatch && (
595 <div className="px-3">
596 <p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
597 </div>
598 )}
599 {!renderablePatch ? (
600 isLoadingCheckpointDiff ? (
601 <DiffPanelLoadingState label="Loading checkpoint diff..." />
602 ) : (
603 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
604 <p>
605 {hasNoNetChanges
606 ? "No net changes in this selection."
607 : "No patch available for this selection."}
608 </p>
609 </div>
610 )
611 ) : renderablePatch.kind === "files" ? (
612 <Virtualizer
613 className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
614 config={{
615 overscrollSize: 600,
616 intersectionObserverMargin: 1200,
617 }}
618 >
619 {renderableFiles.map((fileDiff) => {
620 const filePath = resolveFileDiffPath(fileDiff);
621 const fileKey = buildFileDiffRenderKey(fileDiff);
622 const themedFileKey = `${fileKey}:${resolvedTheme}`;
623 return (
624 <div
625 key={themedFileKey}
626 data-diff-file-path={filePath}
627 className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
628 onClickCapture={(event) => {
629 const nativeEvent = event.nativeEvent as MouseEvent;
630 const composedPath = nativeEvent.composedPath?.() ?? [];
631 const clickedHeader = composedPath.some((node) => {
632 if (!(node instanceof Element)) return false;
633 return node.hasAttribute("data-title");
634 });
635 if (!clickedHeader) return;
636 openDiffFileInEditor(filePath);
637 }}
638 >
639 <FileDiff
640 fileDiff={fileDiff}
641 options={{
642 diffStyle: diffRenderMode === "split" ? "split" : "unified",
643 lineDiffType: "none",
644 overflow: diffWordWrap ? "wrap" : "scroll",
645 theme: resolveDiffThemeName(resolvedTheme),
646 themeType: resolvedTheme as DiffThemeType,
647 unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
648 }}
649 />
650 </div>
651 );
652 })}
653 </Virtualizer>
654 ) : (
655 <div className="h-full overflow-auto p-2">
656 <div className="space-y-2">
657 <p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
658 <pre
659 className={cn(
660 "max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
661 diffWordWrap
662 ? "overflow-auto whitespace-pre-wrap wrap-break-word"
663 : "overflow-auto",
664 )}
665 >
666 {renderablePatch.text}
667 </pre>
668 </div>
669 </div>
670 )}
671 </div>
672 </>
673 )}
674 </DiffPanelShell>
675 );