Open History to see the last commit
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 { ThreadId, type TurnId } from "@t3tools/contracts";
6import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
7import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
9import { cn } from "~/lib/utils";
10import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
11import { isElectron } from "../env";
12import { useTheme } from "../hooks/useTheme";
13import { buildPatchCacheKey } from "../lib/diffRendering";
14import { resolveDiffThemeName } from "../lib/diffRendering";
15import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
16import { useStore } from "../store";
17import { ToggleGroup, Toggle } from "./ui/toggle-group";
18
19type DiffRenderMode = "stacked" | "split";
20type DiffThemeType = "light" | "dark";
21
22const DIFF_PANEL_UNSAFE_CSS = `
23[data-diffs-header],
24[data-diff],
25[data-file],
26[data-error-wrapper],
27[data-virtualizer-buffer] {
28 --diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
29 --diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
30 --diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
31 --diffs-token-light-bg: transparent;
32 --diffs-token-dark-bg: transparent;
33
34 --diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
35 --diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
36 --diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
37 --diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
38
39 --diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
40 --diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
41 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
42 --diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
43
44 --diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
45 --diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
46 --diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
47 --diffs-bg-deletion-emphasis-override: color-mix(
48 in srgb,
49 var(--background) 80%,
50 var(--destructive)
51 );
52
53 background-color: var(--diffs-bg) !important;
54}
55
56[data-file-info] {
57 background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
58 border-block-color: var(--border) !important;
59 color: var(--foreground) !important;
60}
61`;
62
63type RenderablePatch =
64 | {
65 kind: "files";
66 files: FileDiffMetadata[];
67 }
68 | {
69 kind: "raw";
70 text: string;
71 reason: string;
72 };
73
74function getRenderablePatch(
75 patch: string | undefined,
76 cacheScope = "diff-panel",
77): RenderablePatch | null {
78 if (!patch) return null;
79 const normalizedPatch = patch.trim();
80 if (normalizedPatch.length === 0) return null;
81
82 try {
83 const parsedPatches = parsePatchFiles(
84 normalizedPatch,
85 buildPatchCacheKey(normalizedPatch, cacheScope),
86 );
87 const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
88 if (files.length > 0) {
89 return { kind: "files", files };
90 }
91
92 return {
93 kind: "raw",
94 text: normalizedPatch,
95 reason: "Unsupported diff format. Showing raw patch.",
96 };
97 } catch {
98 return {
99 kind: "raw",
100 text: normalizedPatch,
101 reason: "Failed to parse patch. Showing raw patch.",
102 };
103 }
104}
105
106function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
107 const raw = fileDiff.name ?? fileDiff.prevName ?? "";
108 if (raw.startsWith("a/") || raw.startsWith("b/")) {
109 return raw.slice(2);
110 }
111 return raw;
112}
113
114function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
115 return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
116}
117
118function formatTurnChipTimestamp(isoDate: string): string {
119 return new Intl.DateTimeFormat(undefined, {
120 hour: "numeric",
121 minute: "2-digit",
122 }).format(new Date(isoDate));
123}
124
125interface DiffPanelProps {
126 mode?: "inline" | "sheet" | "sidebar";
127}
128
129export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
130
131export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
132 const navigate = useNavigate();
133 const { resolvedTheme } = useTheme();
134 const { state } = useStore();
135 const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
136 const patchViewportRef = useRef<HTMLDivElement>(null);
137 const turnStripRef = useRef<HTMLDivElement>(null);
138 const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
139 const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
140 const routeThreadId = useParams({
141 strict: false,
142 select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
143 });
144 const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
145 const activeThreadId = routeThreadId;
146 const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
147 const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
148 useTurnDiffSummaries(activeThread);
149 const orderedTurnDiffSummaries = useMemo(
150 () =>
151 [...turnDiffSummaries].toSorted((left, right) => {
152 const leftTurnCount =
153 left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
154 const rightTurnCount =
155 right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
156 if (leftTurnCount !== rightTurnCount) {
157 return rightTurnCount - leftTurnCount;
158 }
159 return right.completedAt.localeCompare(left.completedAt);
160 }),
161 [inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
162 );
163
164 const selectedTurnId = diffSearch.diffTurnId ?? null;
165 const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null;
166 const selectedTurn =
167 selectedTurnId === null
168 ? undefined
169 : (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
170 orderedTurnDiffSummaries[0]);
171 const selectedCheckpointTurnCount =
172 selectedTurn &&
173 (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
174 const selectedCheckpointRange = useMemo(
175 () =>
176 typeof selectedCheckpointTurnCount === "number"
177 ? {
178 fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
179 toTurnCount: selectedCheckpointTurnCount,
180 }
181 : null,
182 [selectedCheckpointTurnCount],
183 );
184 const conversationCheckpointTurnCount = useMemo(() => {
185 const turnCounts = orderedTurnDiffSummaries
186 .map(
187 (summary) =>
188 summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
189 )
190 .filter((value): value is number => typeof value === "number");
191 if (turnCounts.length === 0) {
192 return undefined;
193 }
194 const latest = Math.max(...turnCounts);
195 return latest > 0 ? latest : undefined;
196 }, [inferredCheckpointTurnCountByTurnId, orderedTurnDiffSummaries]);
197 const conversationCheckpointRange = useMemo(
198 () =>
199 !selectedTurn && typeof conversationCheckpointTurnCount === "number"
200 ? {
201 fromTurnCount: 0,
202 toTurnCount: conversationCheckpointTurnCount,
203 }
204 : null,
205 [conversationCheckpointTurnCount, selectedTurn],
206 );
207 const activeCheckpointRange = selectedTurn
208 ? selectedCheckpointRange
209 : conversationCheckpointRange;
210 const conversationCacheScope = useMemo(() => {
211 if (selectedTurn || orderedTurnDiffSummaries.length === 0) {
212 return null;
213 }
214 return `conversation:${orderedTurnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
215 }, [orderedTurnDiffSummaries, selectedTurn]);
216 const activeCheckpointDiffQuery = useQuery(
217 checkpointDiffQueryOptions({
218 threadId: activeThreadId,
219 fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
220 toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
221 cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
222 }),
223 );
224 const selectedTurnCheckpointDiff = selectedTurn
225 ? activeCheckpointDiffQuery.data?.diff
226 : undefined;
227 const conversationCheckpointDiff = selectedTurn
228 ? undefined
229 : activeCheckpointDiffQuery.data?.diff;
230 const isLoadingCheckpointDiff = activeCheckpointDiffQuery.isLoading;
231 const checkpointDiffError =
232 activeCheckpointDiffQuery.error instanceof Error
233 ? activeCheckpointDiffQuery.error.message
234 : activeCheckpointDiffQuery.error
235 ? "Failed to load checkpoint diff."
236 : null;
237
238 const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff;
239 const hasResolvedPatch = typeof selectedPatch === "string";
240 const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0;
241 const renderablePatch = useMemo(
242 () => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`),
243 [resolvedTheme, selectedPatch],
244 );
245 const renderableFiles = useMemo(() => {
246 if (!renderablePatch || renderablePatch.kind !== "files") {
247 return [];
248 }
249 return renderablePatch.files.toSorted((left, right) =>
250 resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
251 numeric: true,
252 sensitivity: "base",
253 }),
254 );
255 }, [renderablePatch]);
256
257 useEffect(() => {
258 if (!selectedFilePath || !patchViewportRef.current) {
259 return;
260 }
261 const target = Array.from(
262 patchViewportRef.current.querySelectorAll<HTMLElement>("[data-diff-file-path]"),
263 ).find((element) => element.dataset.diffFilePath === selectedFilePath);
264 target?.scrollIntoView({ block: "nearest" });
265 }, [selectedFilePath, renderableFiles]);
266
267 const selectTurn = (turnId: TurnId) => {
268 if (!activeThread) return;
269 void navigate({
270 to: "/$threadId",
271 params: { threadId: activeThread.id },
272 search: (previous) => {
273 const rest = stripDiffSearchParams(previous);
274 return { ...rest, diff: "1", diffTurnId: turnId };
275 },
276 });
277 };
278 const selectWholeConversation = () => {
279 if (!activeThread) return;
280 void navigate({
281 to: "/$threadId",
282 params: { threadId: activeThread.id },
283 search: (previous) => {
284 const rest = stripDiffSearchParams(previous);
285 return { ...rest, diff: "1" };
286 },
287 });
288 };
289 const updateTurnStripScrollState = useCallback(() => {
290 const element = turnStripRef.current;
291 if (!element) {
292 setCanScrollTurnStripLeft(false);
293 setCanScrollTurnStripRight(false);
294 return;
295 }
296
297 const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
298 setCanScrollTurnStripLeft(element.scrollLeft > 4);
299 setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
300 }, []);
301 const scrollTurnStripBy = useCallback((offset: number) => {
302 const element = turnStripRef.current;
303 if (!element) return;
304 element.scrollBy({ left: offset, behavior: "smooth" });
305 }, []);
306 const onTurnStripWheel = useCallback((event: WheelEvent) => {
307 const element = turnStripRef.current;
308 if (!element) return;
309 if (element.scrollWidth <= element.clientWidth + 1) return;
310 if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
311
312 event.preventDefault();
313 element.scrollBy({ left: event.deltaY, behavior: "auto" });
314 }, []);
315
316 useEffect(() => {
317 const element = turnStripRef.current;
318 if (!element) return;
319
320 updateTurnStripScrollState();
321 const onScroll = () => updateTurnStripScrollState();
322
323 element.addEventListener("scroll", onScroll, { passive: true });
324 element.addEventListener("wheel", onTurnStripWheel, { passive: false });
325
326 const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
327 resizeObserver.observe(element);
328
329 return () => {
330 element.removeEventListener("scroll", onScroll);
331 element.removeEventListener("wheel", onTurnStripWheel);
332 resizeObserver.disconnect();
333 };
334 }, [updateTurnStripScrollState, onTurnStripWheel]);
335
336 useEffect(() => {
337 updateTurnStripScrollState();
338 }, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
339
340 useEffect(() => {
341 const element = turnStripRef.current;
342 if (!element) return;
343
344 const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
345 selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
346 }, [selectedTurn?.turnId, selectedTurnId]);
347
348 const shouldUseDragRegion = isElectron && mode !== "sheet";
349 const headerRow = (
350 <>
351 <div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
352 {canScrollTurnStripLeft && (
353 <div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-linear-to-r from-card to-transparent" />
354 )}
355 {canScrollTurnStripRight && (
356 <div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-linear-to-l from-card to-transparent" />
357 )}
358 <button
359 type="button"
360 className={cn(
361 "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",
362 canScrollTurnStripLeft
363 ? "border-border/70 hover:border-border hover:text-foreground"
364 : "cursor-not-allowed border-border/40 text-muted-foreground/40",
365 )}
366 onClick={() => scrollTurnStripBy(-180)}
367 disabled={!canScrollTurnStripLeft}
368 aria-label="Scroll turn list left"
369 >
370 <ChevronLeftIcon className="size-3.5" />
371 </button>
372 <button
373 type="button"
374 className={cn(
375 "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",
376 canScrollTurnStripRight
377 ? "border-border/70 hover:border-border hover:text-foreground"
378 : "cursor-not-allowed border-border/40 text-muted-foreground/40",
379 )}
380 onClick={() => scrollTurnStripBy(180)}
381 disabled={!canScrollTurnStripRight}
382 aria-label="Scroll turn list right"
383 >
384 <ChevronRightIcon className="size-3.5" />
385 </button>
386 <div ref={turnStripRef} className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5">
387 <button
388 type="button"
389 className="shrink-0 rounded-md"
390 onClick={selectWholeConversation}
391 data-turn-chip-selected={selectedTurnId === null}
392 >
393 <div
394 className={cn(
395 "rounded-md border px-2 py-1 text-left transition-colors",
396 selectedTurnId === null
397 ? "border-border bg-accent text-accent-foreground"
398 : "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
399 )}
400 >
401 <div className="text-[10px] leading-tight font-medium">All turns</div>
402 </div>
403 </button>
404 {orderedTurnDiffSummaries.map((summary) => (
405 <button
406 key={summary.turnId}
407 type="button"
408 className="shrink-0 rounded-md"
409 onClick={() => selectTurn(summary.turnId)}
410 title={summary.turnId}
411 data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
412 >
413 <div
414 className={cn(
415 "rounded-md border px-2 py-1 text-left transition-colors",
416 summary.turnId === selectedTurn?.turnId
417 ? "border-border bg-accent text-accent-foreground"
418 : "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
419 )}
420 >
421 <div className="flex items-center gap-1">
422 <span className="text-[10px] leading-tight font-medium">
423 Turn{" "}
424 {summary.checkpointTurnCount ??
425 inferredCheckpointTurnCountByTurnId[summary.turnId] ??
426 "?"}
427 </span>
428 <span className="text-[9px] leading-tight opacity-70">
429 {formatTurnChipTimestamp(summary.completedAt)}
430 </span>
431 </div>
432 </div>
433 </button>
434 ))}
435 </div>
436 </div>
437 <ToggleGroup
438 className="shrink-0 [-webkit-app-region:no-drag]"
439 variant="outline"
440 size="xs"
441 value={[diffRenderMode]}
442 onValueChange={(value) => {
443 const next = value[0];
444 if (next === "stacked" || next === "split") {
445 setDiffRenderMode(next);
446 }
447 }}
448 >
449 <Toggle aria-label="Stacked diff view" value="stacked">
450 <Rows3Icon className="size-3" />
451 </Toggle>
452 <Toggle aria-label="Split diff view" value="split">
453 <Columns2Icon className="size-3" />
454 </Toggle>
455 </ToggleGroup>
456 </>
457 );
458 const headerRowClassName = cn(
459 "flex items-center justify-between gap-2 px-4",
460 shouldUseDragRegion ? "drag-region h-[52px] border-b border-border" : "h-12",
461 );
462
463 return (
464 <div
465 className={cn(
466 "flex h-full min-w-0 flex-col bg-background",
467 mode === "inline"
468 ? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
469 : "w-full",
470 )}
471 >
472 {shouldUseDragRegion ? (
473 <div className={headerRowClassName}>{headerRow}</div>
474 ) : (
475 <div className="border-b border-border">
476 <div className={headerRowClassName}>{headerRow}</div>
477 </div>
478 )}
479
480 {!activeThread ? (
481 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
482 Select a thread to inspect turn diffs.
483 </div>
484 ) : orderedTurnDiffSummaries.length === 0 ? (
485 <div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
486 No completed turns yet.
487 </div>
488 ) : (
489 <>
490 <div
491 ref={patchViewportRef}
492 className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
493 >
494 {checkpointDiffError && !renderablePatch && (
495 <div className="px-3">
496 <p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
497 </div>
498 )}
499 {!renderablePatch ? (
500 <div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
501 <p>
502 {isLoadingCheckpointDiff
503 ? "Loading checkpoint diff..."
504 : hasNoNetChanges
505 ? "No net changes in this selection."
506 : "No patch available for this selection."}
507 </p>
508 </div>
509 ) : renderablePatch.kind === "files" ? (
510 <Virtualizer
511 className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
512 config={{
513 overscrollSize: 600,
514 intersectionObserverMargin: 1200,
515 }}
516 >
517 {renderableFiles.map((fileDiff) => {
518 const filePath = resolveFileDiffPath(fileDiff);
519 const fileKey = buildFileDiffRenderKey(fileDiff);
520 const themedFileKey = `${fileKey}:${resolvedTheme}`;
521 return (
522 <div
523 key={themedFileKey}
524 data-diff-file-path={filePath}
525 className="diff-render-file rounded-md"
526 >
527 <FileDiff
528 fileDiff={fileDiff}
529 options={{
530 diffStyle: diffRenderMode === "split" ? "split" : "unified",
531 lineDiffType: "none",
532 theme: resolveDiffThemeName(resolvedTheme),
533 themeType: resolvedTheme as DiffThemeType,
534 unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
535 }}
536 />
537 </div>
538 );
539 })}
540 </Virtualizer>
541 ) : (
542 <div className="h-full overflow-auto px-3 py-2">
543 <div className="space-y-2">
544 <p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
545 <pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
546 {renderablePatch.text}
547 </pre>
548 </div>
549 </div>
550 )}
551 </div>
552 </>
553 )}
554 </div>
555 );
556}