import { lazy, Suspense, useCallback, useEffect, useId, useRef, useState } from "react"; import { LayoutGroup, motion, useReducedMotion } from "motion/react"; import { useTranslation } from "react-i18next"; import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; import { cn } from "@/lib/utils"; import { formatTurnLatency } from "@/lib/format-time"; import type { ContextGraph, ContextSnapshot } from "@/lib/types"; import type { ComposerContextUsage, ComposerRoundUsage } from "./ComposerUsagePopover"; import { ContextReplayButton } from "./ContextReplayButton"; const ContextGraphScene = lazy(() => import("./ContextGraphScene").then(module => ({ default: module.ContextGraphScene }))); const EMPTY_GRAPH: ContextGraph = { nodes: [], edges: [] }; const surface = "context-inspector-surface select-none rounded-[20px] bg-card"; export function ContextInspector({ context, rounds, snapshots, onOpenFile, sidebar = false, expandable = true }: { context: ComposerContextUsage | null; rounds: readonly ComposerRoundUsage[]; snapshots: readonly ContextSnapshot[]; onOpenFile?: (path: string) => void; sidebar?: boolean; expandable?: boolean; }) { const { t, i18n } = useTranslation(); const layoutId = useId(); const reducedMotion = useReducedMotion(); const [expanded, setExpanded] = useState(false); const [replay, setReplay] = useState<{ frames: readonly ContextSnapshot[]; index: number; startedAt: number; interval: number } | null>(null); const [readyGraph, setReadyGraph] = useState(null); const [meterHover, setMeterHover] = useState(false); const epoch = snapshots[0]?.id; useEffect(() => { setReplay(null); }, [epoch]); useEffect(() => { if (!replay || readyGraph !== replay.frames[replay.index].graph) return; // Keep a shared timeline instead of adding rendering time to every step. // Advance only after painting each snapshot, even when catching up. const remaining = replay.startedAt + (replay.index + 1) * replay.interval - performance.now(); const timer = window.setTimeout(() => setReplay((current) => current && current.index + 1 < current.frames.length ? { ...current, index: current.index + 1 } : null), Math.max(0, remaining)); return () => window.clearTimeout(timer); }, [replay, readyGraph]); const snapshot = replay ? replay.frames[replay.index] : snapshots.at(-1); const latestRound = rounds.at(-1); const tokens = snapshot ? snapshot.estimatedTokens ?? snapshot.usage?.context_tokens ?? snapshot.usage?.prompt_tokens : context?.contextTokens; const estimated = snapshot?.estimatedTokens !== undefined || (!snapshot?.usage && context?.estimated); const windowTokens = snapshot?.contextWindowTokens ?? context?.contextWindowTokens; const tokenNumbers = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 1 }); const hasTokenUsage = tokens !== undefined || !!windowTokens; const used = tokens !== undefined && windowTokens ? Math.min(100, tokens / windowTokens * 100) : null; const cached = snapshot ? snapshot.usage?.cached_tokens : latestRound?.cachedTokens; const input = snapshot ? snapshot.usage?.prompt_tokens : latestRound?.inputTokens; const cachedWidth = cached !== undefined && windowTokens ? Math.min(used ?? 0, cached / windowTokens * 100) : 0; const duration = snapshot ? snapshot.usage?.generation_ms : latestRound?.generationMs; const toggleExpanded = useCallback(() => setExpanded((value) => !value), []); const openFileCallback = useRef(onOpenFile); openFileCallback.current = onOpenFile; const openFile = useCallback((path: string) => { setExpanded(false); openFileCallback.current?.(path); }, []); const content = (large: boolean) => }>
setMeterHover(true)} onPointerLeave={() => setMeterHover(false)} className={cn(surface, "relative flex h-14 min-w-0 flex-1 items-center gap-4 px-4 transition-transform duration-150 ease-out motion-reduce:transition-none", meterHover && "scale-[1.015]")}>
{used === null ? "—" : `${estimated ? "≈" : ""}${Math.round(used)}%`} {meterHover && (hasTokenUsage || cached !== undefined || duration !== undefined || replay !== null) &&
{hasTokenUsage && <>
{t("thread.composer.context.panelTitle")}
{t("thread.composer.context.tokenUsage", { used: tokens === undefined ? "—" : `${estimated ? "≈" : ""}${tokenNumbers.format(tokens / 1000)}k`, limit: windowTokens ? `${tokenNumbers.format(windowTokens / 1000)}k` : "—", })}
} {cached !== undefined && !!input && <>
{t("thread.composer.context.cacheHitRate")}
{Math.round(cached / input * 100)}%
} {duration !== undefined && <>
{t("thread.composer.context.duration")}
{formatTurnLatency(duration)}
} {replay && <>
{t("thread.composer.context.history")}
{replay.index + 1}/{replay.frames.length}
}
}
{ setMeterHover(false); // Scale by request count: our replay unit is a snapshot, not a graph edge. const stepsPerSecond = Math.min(20, Math.max(5, 0.5 * Math.sqrt(snapshots.length))); setReplay({ frames: [...snapshots], index: 0, startedAt: performance.now(), interval: 1000 / stepsPerSecond }); }} />
; return {!expanded && content(false)} {t("thread.composer.context.panelTitle")} {content(true)} ; }