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