import { FileDiff, Virtualizer } from "@pierre/diffs/react"; import { useNavigate, useParams, useSearch } from "@tanstack/react-router"; import { scopeThreadRef } from "@t3tools/client-runtime"; import type { TurnId } from "@t3tools/contracts"; import { ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, Columns2Icon, PilcrowIcon, Rows3Icon, TextWrapIcon, } from "lucide-react"; import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState, } from "react"; import { openInPreferredEditor } from "../editorPreferences"; import { useCheckpointDiff } from "~/lib/checkpointDiffState"; import { useVcsStatus } from "~/lib/vcsStatusState"; import { cn } from "~/lib/utils"; import { readLocalApi } from "../localApi"; import { resolvePathLinkTarget } from "../terminal-links"; import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"; import { useTheme } from "../hooks/useTheme"; import { buildFileDiffRenderKey, getDiffCollapseIconClassName, getRenderablePatch, resolveDiffThemeName, resolveFileDiffPath, } from "../lib/diffRendering"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; import { selectProjectByRef, useStore } from "../store"; import { createThreadSelectorByRef } from "../storeSelectors"; import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes"; import { useSettings } from "../hooks/useSettings"; import { formatShortTimestamp } from "../timestampFormat"; import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; import { ToggleGroup, Toggle } from "./ui/toggle-group"; type DiffRenderMode = "stacked" | "split"; type DiffThemeType = "light" | "dark"; const DIFF_PANEL_UNSAFE_CSS = ` [data-diffs-header], [data-diff], [data-file], [data-error-wrapper], [data-virtualizer-buffer] { --diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; --diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; --diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; --diffs-token-light-bg: transparent; --diffs-token-dark-bg: transparent; --diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground)); --diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground)); --diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground)); --diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground)); --diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success)); --diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success)); --diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success)); --diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success)); --diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive)); --diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive)); --diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive)); --diffs-bg-deletion-emphasis-override: color-mix( in srgb, var(--background) 80%, var(--destructive) ); background-color: var(--diffs-bg) !important; } [data-file-info] { background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important; border-block-color: var(--border) !important; color: var(--foreground) !important; } [data-diffs-header] { position: sticky !important; top: 0; z-index: 4; background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important; border-bottom: 1px solid var(--border) !important; } [data-title] { cursor: pointer; transition: color 120ms ease, text-decoration-color 120ms ease; text-decoration: underline; text-decoration-color: transparent; text-underline-offset: 2px; } [data-title]:hover { color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important; text-decoration-color: currentColor; } `; interface DiffPanelProps { mode?: DiffPanelMode; } export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider"; export default function DiffPanel({ mode = "inline" }: DiffPanelProps) { const navigate = useNavigate(); const { resolvedTheme } = useTheme(); const settings = useSettings(); const [diffRenderMode, setDiffRenderMode] = useState("stacked"); const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap); const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace); const [collapsedDiffFileKeys, setCollapsedDiffFileKeys] = useState>( () => new Set(), ); const patchViewportRef = useRef(null); const turnStripRef = useRef(null); const previousDiffOpenRef = useRef(false); const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false); const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false); const routeThreadRef = useParams({ strict: false, select: (params) => resolveThreadRouteRef(params), }); const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) }); const diffOpen = diffSearch.diff === "1"; const activeThreadId = routeThreadRef?.threadId ?? null; const activeThread = useStore( useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]), ); const activeProjectId = activeThread?.projectId ?? null; const activeProject = useStore((store) => activeThread && activeProjectId ? selectProjectByRef(store, { environmentId: activeThread.environmentId, projectId: activeProjectId, }) : undefined, ); const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd; const gitStatusQuery = useVcsStatus({ environmentId: activeThread?.environmentId ?? null, cwd: activeCwd ?? null, }); const isGitRepo = gitStatusQuery.data?.isRepo ?? true; const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } = useTurnDiffSummaries(activeThread); const orderedTurnDiffSummaries = useMemo( () => [...turnDiffSummaries].toSorted((left, right) => { const leftTurnCount = left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0; const rightTurnCount = right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0; if (leftTurnCount !== rightTurnCount) { return rightTurnCount - leftTurnCount; } return right.completedAt.localeCompare(left.completedAt); }), [inferredCheckpointTurnCountByTurnId, turnDiffSummaries], ); const selectedTurnId = diffSearch.diffTurnId ?? null; const selectedFilePath = selectedTurnId !== null ? (diffSearch.diffFilePath ?? null) : null; const selectedTurn = selectedTurnId === null ? undefined : (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ?? orderedTurnDiffSummaries[0]); const selectedCheckpointTurnCount = selectedTurn && (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]); const selectedCheckpointRange = useMemo( () => typeof selectedCheckpointTurnCount === "number" ? { fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1), toTurnCount: selectedCheckpointTurnCount, } : null, [selectedCheckpointTurnCount], ); const conversationCheckpointTurnCount = useMemo(() => { const turnCounts: Array = []; for (const summary of orderedTurnDiffSummaries) { const value = summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId]; if (typeof value === "number") { turnCounts.push(value); } } if (turnCounts.length === 0) { return undefined; } const latest = Math.max(...turnCounts); return latest > 0 ? latest : undefined; }, [inferredCheckpointTurnCountByTurnId, orderedTurnDiffSummaries]); const conversationCheckpointRange = useMemo( () => !selectedTurn && typeof conversationCheckpointTurnCount === "number" ? { fromTurnCount: 0, toTurnCount: conversationCheckpointTurnCount, } : null, [conversationCheckpointTurnCount, selectedTurn], ); const activeCheckpointRange = selectedTurn ? selectedCheckpointRange : conversationCheckpointRange; const conversationCacheScope = useMemo(() => { if (selectedTurn || orderedTurnDiffSummaries.length === 0) { return null; } return `conversation:${orderedTurnDiffSummaries.map((summary) => summary.turnId).join(",")}`; }, [orderedTurnDiffSummaries, selectedTurn]); const activeCheckpointDiff = useCheckpointDiff( { environmentId: activeThread?.environmentId ?? null, threadId: activeThreadId, fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null, toTurnCount: activeCheckpointRange?.toTurnCount ?? null, ignoreWhitespace: diffIgnoreWhitespace, cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope, }, { enabled: isGitRepo }, ); const selectedTurnCheckpointDiff = selectedTurn ? activeCheckpointDiff.data?.diff : undefined; const conversationCheckpointDiff = selectedTurn ? undefined : activeCheckpointDiff.data?.diff; const isLoadingCheckpointDiff = activeCheckpointDiff.isPending; const checkpointDiffError = activeCheckpointDiff.error; const selectedPatch = selectedTurn ? selectedTurnCheckpointDiff : conversationCheckpointDiff; const hasResolvedPatch = typeof selectedPatch === "string"; const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0; const renderablePatch = useMemo( () => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`), [resolvedTheme, selectedPatch], ); const renderableFiles = useMemo(() => { if (!renderablePatch || renderablePatch.kind !== "files") { return []; } return renderablePatch.files.toSorted((left, right) => resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, { numeric: true, sensitivity: "base", }), ); }, [renderablePatch]); useEffect(() => { if (renderableFiles.length === 0) { setCollapsedDiffFileKeys((current) => (current.size === 0 ? current : new Set())); return; } const visibleFileKeys = new Set(renderableFiles.map(buildFileDiffRenderKey)); setCollapsedDiffFileKeys((current) => { const next = new Set([...current].filter((fileKey) => visibleFileKeys.has(fileKey))); return next.size === current.size ? current : next; }); }, [renderableFiles]); useEffect(() => { if (diffOpen && !previousDiffOpenRef.current) { setDiffWordWrap(settings.diffWordWrap); setDiffIgnoreWhitespace(settings.diffIgnoreWhitespace); } previousDiffOpenRef.current = diffOpen; }, [diffOpen, settings.diffIgnoreWhitespace, settings.diffWordWrap]); useEffect(() => { if (!selectedFilePath || !patchViewportRef.current) { return; } const target = Array.from( patchViewportRef.current.querySelectorAll("[data-diff-file-path]"), ).find((element) => element.dataset.diffFilePath === selectedFilePath); target?.scrollIntoView({ block: "nearest" }); }, [selectedFilePath, renderableFiles]); const openDiffFileInEditor = useCallback( (filePath: string) => { const api = readLocalApi(); if (!api) return; const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath; void openInPreferredEditor(api, targetPath).catch((error) => { console.warn("Failed to open diff file in editor.", error); }); }, [activeCwd], ); const toggleDiffFileCollapsed = useCallback((fileKey: string) => { setCollapsedDiffFileKeys((current) => { const next = new Set(current); if (next.has(fileKey)) { next.delete(fileKey); } else { next.add(fileKey); } return next; }); }, []); const selectTurn = (turnId: TurnId) => { if (!activeThread) return; void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)), search: (previous) => { const rest = stripDiffSearchParams(previous); return { ...rest, diff: "1", diffTurnId: turnId }; }, }); }; const selectWholeConversation = () => { if (!activeThread) return; void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(scopeThreadRef(activeThread.environmentId, activeThread.id)), search: (previous) => { const rest = stripDiffSearchParams(previous); return { ...rest, diff: "1" }; }, }); }; const updateTurnStripScrollState = useCallback(() => { const element = turnStripRef.current; if (!element) { setCanScrollTurnStripLeft(false); setCanScrollTurnStripRight(false); return; } const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth); setCanScrollTurnStripLeft(element.scrollLeft > 4); setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4); }, []); const scrollTurnStripBy = useCallback((offset: number) => { const element = turnStripRef.current; if (!element) return; element.scrollBy({ left: offset, behavior: "smooth" }); }, []); const onTurnStripWheel = useCallback((event: ReactWheelEvent) => { const element = turnStripRef.current; if (!element) return; if (element.scrollWidth <= element.clientWidth + 1) return; if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return; event.preventDefault(); element.scrollBy({ left: event.deltaY, behavior: "auto" }); }, []); useEffect(() => { const element = turnStripRef.current; if (!element) return; const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState()); const onScroll = () => updateTurnStripScrollState(); element.addEventListener("scroll", onScroll, { passive: true }); const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState()); resizeObserver.observe(element); return () => { window.cancelAnimationFrame(frameId); element.removeEventListener("scroll", onScroll); resizeObserver.disconnect(); }; }, [updateTurnStripScrollState]); useEffect(() => { const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState()); return () => { window.cancelAnimationFrame(frameId); }; }, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]); useEffect(() => { const element = turnStripRef.current; if (!element) return; const selectedChip = element.querySelector("[data-turn-chip-selected='true']"); selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" }); }, [selectedTurn?.turnId, selectedTurnId]); const headerRow = ( <>
{orderedTurnDiffSummaries.map((summary) => ( ))}
{ const next = value[0]; if (next === "stacked" || next === "split") { setDiffRenderMode(next); } }} > { setDiffWordWrap(Boolean(pressed)); }} > { setDiffIgnoreWhitespace(Boolean(pressed)); }} >
); return ( {!activeThread ? (
Select a thread to inspect turn diffs.
) : !isGitRepo ? (
Turn diffs are unavailable because this project is not a git repository.
) : orderedTurnDiffSummaries.length === 0 ? (
No completed turns yet.
) : ( <>
{checkpointDiffError && !renderablePatch && (

{checkpointDiffError}

)} {!renderablePatch ? ( isLoadingCheckpointDiff ? ( ) : (

{hasNoNetChanges ? "No net changes in this selection." : "No patch available for this selection."}

) ) : renderablePatch.kind === "files" ? ( {renderableFiles.map((fileDiff) => { const filePath = resolveFileDiffPath(fileDiff); const fileKey = buildFileDiffRenderKey(fileDiff); const themedFileKey = `${fileKey}:${resolvedTheme}`; const collapsed = collapsedDiffFileKeys.has(fileKey); return (
{ const nativeEvent = event.nativeEvent as MouseEvent; const composedPath = nativeEvent.composedPath?.() ?? []; const clickedHeader = composedPath.some((node) => { if (!(node instanceof Element)) return false; return node.hasAttribute("data-title"); }); if (!clickedHeader) return; openDiffFileInEditor(filePath); }} > ( )} options={{ collapsed, diffStyle: diffRenderMode === "split" ? "split" : "unified", lineDiffType: "none", overflow: diffWordWrap ? "wrap" : "scroll", theme: resolveDiffThemeName(resolvedTheme), themeType: resolvedTheme as DiffThemeType, unsafeCSS: DIFF_PANEL_UNSAFE_CSS, }} />
); })}
) : (

{renderablePatch.reason}

                    {renderablePatch.text}
                  
)}
)}
); }