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

DiffPanel.tsx

740 lines28.9 KB

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