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

DiffPanel.tsx

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