import { Fragment, useCallback, useMemo, useRef, useState, type PointerEvent, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet"; import { FloatingPortalContext } from "@/components/ui/floating-portal"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { formatCompactTokenCount, formatTurnLatency } from "@/lib/format"; import { cn } from "@/lib/utils"; export interface ComposerContextUsage { contextTokens: number; contextWindowTokens?: number; } export interface ComposerRoundUsage { id: string; timestamp: number; inputTokens: number; outputTokens?: number; cachedTokens?: number; estimatedTokens?: number; generationMs?: number; } interface NormalizedRoundUsage extends ComposerRoundUsage { cachedTokens?: number; outputTokens: number; } function normalizeRounds( rounds: readonly ComposerRoundUsage[], ): NormalizedRoundUsage[] { return rounds .filter((round) => Number.isFinite(round.inputTokens) && round.inputTokens > 0) .map((round) => ({ ...round, inputTokens: Math.max(0, round.inputTokens), outputTokens: Number.isFinite(round.outputTokens) ? Math.max(0, round.outputTokens ?? 0) : 0, ...(Number.isFinite(round.cachedTokens) ? { cachedTokens: Math.min(round.inputTokens, Math.max(0, round.cachedTokens ?? 0)) } : {}), })); } export function ComposerUsagePopover({ context, rounds, showLabel = false, bottomSheet = false, }: { context: ComposerContextUsage | null; rounds: readonly ComposerRoundUsage[]; showLabel?: boolean; bottomSheet?: boolean; }) { const { t, i18n } = useTranslation(); const [open, setOpen] = useState(false); const normalizedRounds = useMemo(() => normalizeRounds(rounds), [rounds]); const hasContext = !!context && Number.isFinite(context.contextTokens) && context.contextTokens >= 0 && Number.isFinite(context.contextWindowTokens) && (context.contextWindowTokens ?? 0) > 0; if (!hasContext && normalizedRounds.length === 0) { return null; } const contextPercentage = hasContext ? Math.min( 100, Math.round(context!.contextTokens / context!.contextWindowTokens! * 100), ) : null; const meterPercentage = contextPercentage ?? 0; const status = meterPercentage >= 90 ? "critical" : meterPercentage >= 75 ? "caution" : "normal"; const detailsLabel = t("thread.composer.context.detailsLabel", { defaultValue: "Open context usage", }); const contextDescription = contextPercentage === null ? detailsLabel : t("thread.composer.context.tooltip", { defaultValue: "Context {{percent}}%", percent: contextPercentage, }); const triggerLabel = contextPercentage === null ? detailsLabel : `${contextDescription}. ${detailsLabel}`; const ringCircumference = 2 * Math.PI * 6; const ringLength = ringCircumference * meterPercentage / 100; const maxInputTokens = Math.max(0, ...normalizedRounds.map((round) => round.inputTokens)); const numberFormatter = new Intl.NumberFormat(i18n.language); const percentageFormatter = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 0, }); const roundDateFormatter = new Intl.DateTimeFormat(i18n.language, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); const Root = bottomSheet ? Sheet : Popover; const Trigger = bottomSheet ? SheetTrigger : PopoverTrigger; const RoundRoot = bottomSheet ? Popover : Tooltip; const RoundTrigger = bottomSheet ? PopoverTrigger : TooltipTrigger; const RoundContent = bottomSheet ? PopoverContent : TooltipContent; const RoundBar = bottomSheet ? "button" : "span"; const trigger = ( ); return ( {bottomSheet ? trigger : ( {trigger} {contextDescription} )} setOpen(false)}>
{contextPercentage !== null ? ( <>
{t("thread.composer.context.contextTitle", { defaultValue: "Context", })} {formatCompactTokenCount(context!.contextTokens)} / {formatCompactTokenCount( context!.contextWindowTokens!, )}
{contextPercentage}%
) : null} {normalizedRounds.length > 0 ? ( <>
{t("thread.composer.context.recentRounds", { defaultValue: "Recent rounds", })} {t("thread.composer.context.inputTrend", { defaultValue: "Input tokens", })}
{normalizedRounds.map((round, index) => { const cachedKnown = typeof round.cachedTokens === "number"; const cachedTokens = round.cachedTokens ?? 0; const notReusedTokens = Math.max(0, round.inputTokens - cachedTokens); const cacheHitRate = cachedKnown ? percentageFormatter.format(cachedTokens / round.inputTokens) : null; const cachedHeight = cachedKnown ? cachedTokens / round.inputTokens * 100 : 0; const barHeight = round.inputTokens / maxInputTokens * 108; const timestampLabel = roundDateFormatter.format(round.timestamp); const detailRows = [ { key: "input", label: t("thread.composer.context.input", { defaultValue: "Input tokens", }), value: numberFormatter.format(round.inputTokens), }, cachedKnown ? { key: "cache-hit-rate", label: t("thread.composer.context.cacheHitRate", { defaultValue: "KV cache hit rate", }), value: cacheHitRate!, } : null, { key: "output", label: t("thread.composer.context.output", { defaultValue: "Output tokens", }), value: numberFormatter.format(round.outputTokens), }, typeof round.generationMs === "number" ? { key: "duration", label: t("thread.composer.context.duration", { defaultValue: "Generation time", }), value: formatTurnLatency(round.generationMs, i18n.language), } : null, ].filter((row): row is NonNullable => !!row); const detailNote = (round.estimatedTokens ?? 0) > 0 ? t("message.usage.estimated", { defaultValue: "Includes estimated usage", }) : null; const detailLabel = [ timestampLabel, ...detailRows.map((row) => `${row.label} ${row.value}`), detailNote, ].filter((part): part is string => !!part).join(". "); return ( 1 && index === normalizedRounds.length - 1 && "justify-end", index === normalizedRounds.length - 1 && "opacity-100", )} > {cachedKnown ? ( <> {notReusedTokens > 0 ? ( ) : null} {cachedTokens > 0 ? ( ) : null} ) : ( )} event.preventDefault(), } : {})} > {timestampLabel} {detailRows.map((row) => ( {row.label} {row.value} ))} {detailNote ? ( {detailNote} ) : null} ); })}
) : null}
); } function UsagePanel({ bottomSheet, onDismiss, children }: { bottomSheet: boolean; onDismiss: () => void; children: ReactNode; }) { const { t } = useTranslation(); const panelRef = useRef(null); const [panelNode, setPanelNode] = useState(null); const sheetRef = useCallback((node: HTMLDivElement | null) => { panelRef.current = node; setPanelNode(node); }, []); const gesture = useRef<{ pointerId: number; x: number; y: number; time: number } | null>(null); const suppressClick = useRef(false); const [offset, setOffset] = useState(0); const [dragging, setDragging] = useState(false); const title = t("thread.composer.context.panelTitle", { defaultValue: "Context usage" }); const focusPanel = (event: Event) => { event.preventDefault(); gesture.current = null; suppressClick.current = false; setOffset(0); setDragging(false); panelRef.current?.focus({ preventScroll: true }); }; const cancelDrag = (event: PointerEvent) => { if (gesture.current?.pointerId !== event.pointerId) return; gesture.current = null; suppressClick.current = true; setDragging(false); setOffset(0); }; if (bottomSheet) { return (
{title}
{children}
); } return ( {children} ); }