"use client"; import { ChevronDown, LoaderCircle, Shrink, TriangleAlert } from "lucide-react"; import { AnimatePresence, animate, motion, type MotionValue, useMotionValue, useReducedMotion, useTransform, type Transition, type Variants, } from "motion/react"; import { type ComponentProps, useCallback, useEffect, useId, useRef, useState } from "react"; import { AnimatedNumber } from "@/components/motion/animated-number"; import { Tooltip } from "@/components/motion/tooltip"; import { EASE_OUT } from "@/lib/ease"; import { useDismiss, type DismissReason } from "@/lib/hooks/use-dismiss"; import { useMessages } from "@/lib/i18n"; import { PresenceGate } from "@/lib/presence-gate"; import { cn } from "@/lib/utils"; /** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */ export const contextMeterMessages = { trigger: "Context window: {percent}% used, {used} of {limit} tokens", collapse: "Hide context breakdown", tokens: "/ {limit} tokens", free: "Free", warning: "Nearing the limit. Compact to free up space.", danger: "Almost full. Older messages may be dropped.", compact: "Compact", compacting: "Compacting", warningReached: "Context window {percent}% full", }; export type ContextMeterMessages = typeof contextMeterMessages; export interface ContextSegment { /** Stable id for the segment, used as its React key. */ key: string; /** Name shown in the breakdown, e.g. "System prompt" or "Messages". */ label: string; /** Tokens this segment takes up. */ tokens: number; } export interface ContextMeterProps extends Omit, "children" | "onChange"> { /** What fills the context window, in display order. The meter shows their sum. */ segments: ContextSegment[]; /** Size of the context window in tokens. */ limit: number; /** Share of the window (0 to 1) where the meter turns to the warning color. Default: 0.8 */ warnAt?: number; /** Share of the window (0 to 1) where the meter turns to the danger color. Default: 0.95 */ dangerAt?: number; /** Shows a Compact button in the panel and calls this when it is pressed. Shrink the segments yourself. */ onCompact?: () => void; /** Shows the Compact button as busy and disables it while your compaction runs. Default: false */ compacting?: boolean; /** Formats a token count for display. Default: compact notation, e.g. 42.1k */ formatTokens?: (tokens: number) => string; /** Which way the pill grows into the panel. Default: "top" */ side?: "top" | "bottom"; /** The pill's edge the panel stays lined up with as it grows. Default: "start" */ align?: "start" | "end"; /** Override any built-in string, e.g. for translation. */ labels?: Partial; } type Level = "normal" | "warning" | "danger"; // The pill grows into the panel with a light overshoot that settles fast, // a touch springier than SPRING_MORPH because this panel is a small readout // rather than a menu. Local: only this morph wants it. const MORPH_OPEN = { type: "spring", duration: 0.5, bounce: 0.2 } as const; // Folding back lands on the pill with just a hint of give. Gentler than // the open: the same bounce would pinch the 32px pill. const MORPH_CLOSE = { type: "spring", duration: 0.4, bounce: 0.12 } as const; // From the keyboard, or with reduced motion: no morph at all. const INSTANT = { duration: 0 } as const; // The ring and bar spring to new values with a slight settle. The bar's // track clips at 100%, so an overshoot near full never draws past the end. const FILL = { type: "spring", duration: 0.55, bounce: 0.18 } as const; // On open the bar's segments spring out from zero one after another, // starting once the panel has mostly grown. const BAR_DELAY = 0.12; const BAR_STAGGER = 0.05; // The content fades out fast as the panel folds, so the fold reads clean. const CONTENT_OUT = { duration: 0.12, ease: EASE_OUT } as const; // The closed pill is fully round (half its h-8); the panel is rounded-2xl. const PILL_RADIUS = 16; const PANEL_RADIUS = 16; // The pill and the panel's header share this row, so the morph is seamless. const ROW = "flex h-8 items-center gap-1.5 pr-3 pl-2 text-xs font-medium"; // Ring geometry, in px: a 16px icon with a 2px stroke. const RING = 16; const STROKE = 2; const R = (RING - STROKE) / 2; // Segment shades, darkest first: one hue, so the meter matches any theme. const SHADES = ["bg-primary", "bg-primary/65", "bg-primary/40", "bg-primary/25"]; const LEVEL_TEXT: Record = { normal: "text-primary", warning: "text-warning", danger: "text-destructive", }; const LIST: Variants = { hidden: {}, show: { transition: { staggerChildren: 0.03, delayChildren: 0.06 } }, }; const ITEM: Variants = { hidden: { opacity: 0, y: 4, filter: "blur(2px)" }, show: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: 0.22, ease: EASE_OUT } }, }; const compactFormat = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1, }); function defaultFormat(tokens: number) { return compactFormat.format(tokens).toLowerCase(); } function shade(index: number) { return SHADES[Math.min(index, SHADES.length - 1)]; } function Ring({ progress, level }: { progress: MotionValue; level: Level }) { // A round cap draws a dot at 0, so the arc hides until there is something to show. const arcOpacity = useTransform(progress, (value) => (value > 0.001 ? 1 : 0)); return ( ); } interface MeterBarProps { segments: ContextSegment[]; /** Where each segment ends along the bar, 0 to 1. */ ends: number[]; fill: Transition; /** Spring each segment out from zero, one after another, as the bar mounts. */ springIn: boolean; } /** * Each segment is a full-width layer scaled to where it ends, earlier ones on * top, and the gaps between them ride on translateX, so the bar animates on * transform alone. It mounts with each open, so the staggered spring out from * zero plays once per open and later changes spring without a delay. */ function MeterBar({ segments, ends, fill, springIn }: MeterBarProps) { const [entered, setEntered] = useState(!springIn); const delay = (index: number) => (entered ? 0 : BAR_DELAY + index * BAR_STAGGER); const last = segments.length - 1; return ( ); } /** * A pill with a ring that shows how much of a model's context window a chat * uses. Pressing it grows the pill itself into a breakdown by segment with * what is left and, near the limit, a Compact action; it folds back into the * pill on close. The app owns the counting: pass the segments in and shrink * them when it compacts. */ export function ContextMeter({ segments, limit, warnAt = 0.8, dangerAt = 0.95, onCompact, compacting = false, formatTokens = defaultFormat, side = "top", align = "start", labels, className, ...props }: ContextMeterProps) { const t = useMessages("contextMeter", contextMeterMessages, labels); const reduce = useReducedMotion() ?? false; const baseId = useId(); const surfaceId = `${baseId}-surface`; const panelId = `${baseId}-panel`; const rootRef = useRef(null); const triggerRef = useRef(null); const headerRef = useRef(null); const [open, setOpenState] = useState(false); // Opened or closed from the keyboard: skip the morph and move focus. const [instant, setInstant] = useState(false); // Set when the panel closes holding focus: the pill is unmounted while // open, so focus can only go back once it has mounted again. const restoreFocus = useRef(false); const used = segments.reduce((sum, segment) => sum + Math.max(0, segment.tokens), 0); const share = limit > 0 ? Math.min(1, used / limit) : 0; const percent = Math.round(share * 100); // From the rounded percent, so the color always agrees with the number shown. const level: Level = percent >= dangerAt * 100 ? "danger" : percent >= warnAt * 100 ? "warning" : "normal"; const usedText = formatTokens(used); const limitText = formatTokens(limit); const setOpen = useCallback((next: boolean, now: boolean) => { if (!next && rootRef.current?.contains(document.activeElement)) restoreFocus.current = true; setInstant(now); setOpenState(next); }, []); const dismiss = useCallback( (reason: DismissReason) => setOpen(false, reason === "escape"), [setOpen], ); useDismiss(open, dismiss, rootRef); useEffect(() => { if (open) { if (instant) headerRef.current?.focus(); return; } if (!restoreFocus.current) return; restoreFocus.current = false; triggerRef.current?.focus(); }, [open, instant]); // The ring's arc follows the share on one tween; reduced motion jumps. const progress = useMotionValue(share); useEffect(() => { if (reduce) { progress.set(share); return; } const controls = animate(progress, share, FILL); return () => controls.stop(); }, [share, reduce, progress]); // Announce crossing into warning or danger, not every change in between. const [announcement, setAnnouncement] = useState(""); const lastLevel = useRef(level); useEffect(() => { if (level === lastLevel.current) return; const rising = level !== "normal" && (lastLevel.current === "normal" || level === "danger"); lastLevel.current = level; setAnnouncement(rising ? t("warningReached", { percent }) : ""); }, [level, percent, t]); // Where each segment ends along the bar, 0 to 1. let running = 0; const ends = segments.map((segment) => { running += Math.max(0, segment.tokens); return limit > 0 ? Math.min(1, running / limit) : 0; }); const morph = reduce || instant ? INSTANT : MORPH_OPEN; const fold = reduce || instant ? INSTANT : MORPH_CLOSE; const fill = reduce ? INSTANT : FILL; // Both surfaces sit on the same corner, so the panel grows away from it. const anchor = cn( "absolute", side === "top" ? "bottom-0" : "top-0", align === "start" ? "left-0" : "right-0", ); const pillContent = ( <> {/* Fixed width so 9% and 100% take the same room and nothing shifts. */} {percent}% ); // Points the way the panel folds back: down toward a pill below it, up otherwise. const chevron = (