import type { ProviderInstanceId, ServerProvider, ServerProviderUsageWindow, UsageLimitSourceSnapshots, } from "@t3tools/contracts"; import { collectProviderUsageLimits, type LimitPace, paceOf, paceRemainingPercent, remainingPercent, } from "@t3tools/shared/usageLimits"; import { formatDuration, limitsNotice } from "@t3tools/shared/usageLimitsCopy"; import { Link } from "@tanstack/react-router"; import { msg, useGT, useLocale, useMessages } from "gt-react"; import { CalendarRangeIcon, GaugeIcon, Minimize2Icon, TimerIcon } from "lucide-react"; import type { ReactNode } from "react"; import { usePrimarySettings } from "../../hooks/useSettings"; import { useNowMinute } from "../../hooks/useNowMinute"; import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window"; import { formatContextWindowTokens } from "../../lib/contextWindow"; import { cn } from "../../lib/utils"; import { formatUpcomingTimestamp } from "../../timestampFormat"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { ThreadDetailsControl } from "./ThreadDetailsControl"; import { formatContextWindowCompactionMessage } from "./compaction.logic"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; const PACE_LABEL: Record = { ahead: msg("Ahead of pace"), on: msg("On pace"), under: msg("Under pace"), }; export interface ThreadDetailsUsageInput { readonly providerInstanceId: ProviderInstanceId | null; readonly providers: readonly ServerProvider[]; readonly sources: UsageLimitSourceSnapshots; readonly contextWindow: ContextWindowSnapshot | null; } type UsageTone = "error" | "warning" | null; /** Provider limits share the canvas's icon, label, meter, percentage and reset columns; each row opens the usage page. */ export function ThreadDetailsUsage({ providerInstanceId, providers, sources, }: Omit) { const gt = useGT(); const m = useMessages(); const nowMinute = useNowMinute(); const now = Date.parse(`${nowMinute}:00Z`); const report = providerInstanceId !== null ? collectProviderUsageLimits(providerInstanceId, providers, sources, now) : null; const limits = report?.accounts.find((entry) => entry.instanceId === providerInstanceId)?.limits ?? providers.find((provider) => provider.instanceId === providerInstanceId)?.usageLimits; const notice = limits ? limitsNotice(limits, m) : gt("This provider has not reported usage limits."); return ( {notice || !limits?.windows.length ? ( } fill={null} tone={null} value={gt("Unavailable")} tooltip={notice ?? gt("No usage windows reported.")} opensUsage /> ) : ( limits.windows.map((window) => ) )} ); } /** Context fills as tokens are used. Compact follows the composer's real provider command. */ export function ThreadDetailsContext({ usage, onCompact, compactDisabled, compactDisabledReason, }: { readonly usage: ContextWindowSnapshot | null; readonly onCompact?: (() => void) | undefined; readonly compactDisabled?: boolean | undefined; readonly compactDisabledReason?: string | null | undefined; }) { const gt = useGT(); const m = useMessages(); const locale = useLocale(); const maxTokens = usage?.maxTokens != null && usage.maxTokens > 0 ? usage.maxTokens : null; const used = maxTokens !== null && usage?.usedPercentage != null ? Math.round(Math.max(0, Math.min(100, usage.usedPercentage))) : null; const threshold = usage?.autoCompactThreshold ?? null; const tick = maxTokens !== null && threshold !== null && threshold > 0 && threshold < maxTokens ? (threshold / maxTokens) * 100 : null; const usedTokens = usage ? formatContextWindowTokens(usage.usedTokens) : null; return ( } fill={used} tick={tick} tone={used === null ? null : used >= 90 ? "error" : used >= 80 ? "warning" : null} value={ used !== null ? `${used}%` : (usedTokens ?? gt("N/A", { $context: "context usage not reported" })) } ariaValue={ used !== null ? gt("{used}% used", { used }) : usedTokens ? gt("{usedTokens} tokens used", { usedTokens }) : gt("Not reported", { $context: "context usage" }) } trailing={ onCompact && usage ? ( ) : undefined } tooltip={ <> {used !== null ? gt("Context: {used}% used", { used }) : usedTokens ? gt("Context: {usedTokens} tokens used", { usedTokens }) : gt("The provider has not reported context usage.")} {usage && maxTokens !== null ? ( {gt("{used} of {max} tokens", { used: usage.usedTokens.toLocaleString(locale), max: maxTokens.toLocaleString(locale), })} ) : null} {threshold !== null && threshold > 0 ? ( {formatContextWindowCompactionMessage(threshold, m)} ) : null} {compactDisabled && compactDisabledReason ? {compactDisabledReason} : null} } /> ); } function LimitRow({ window, now, }: { readonly window: ServerProviderUsageWindow; readonly now: number; }) { const gt = useGT(); const m = useMessages(); const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); const left = remainingPercent(window); const pace = paceOf(window, now); const timeLeft = paceRemainingPercent(window, now); const resetsAt = window.resetsAt ? Date.parse(window.resetsAt) : Number.NaN; const remainingMs = resetsAt - now; const weekly = (window.windowDurationMins ?? 0) >= 24 * 60 || /week/i.test(window.label); const reset = remainingMs > 0 ? weekly ? new Intl.DateTimeFormat(undefined, { weekday: "short" }).format(resetsAt) : formatDuration(remainingMs, m) : null; return ( : } fill={left} tick={timeLeft} tone={left <= 10 ? "error" : left <= 20 ? "warning" : null} value={`${left}%`} ariaValue={gt("{left}% left", { left })} opensUsage trailing={ reset ? ( {reset} ) : undefined } tooltip={ <> {gt("{label}: {left}% left", { label: window.label, left })} {pace && timeLeft !== null ? ( {m(PACE_LABEL[pace])} {gt("{timeLeft}% of the window left", { timeLeft })} ) : null} {window.resetsAt && remainingMs > 0 ? ( {gt("Resets in {duration}", { duration: formatDuration(remainingMs, m) })} {formatUpcomingTimestamp(window.resetsAt, timestampFormat, now, undefined, m)} ) : null} } /> ); } /** With `opensUsage` the row links to the usage page. */ function UsageRow({ label, icon, fill, tone, tick = null, value, ariaValue = value, tooltip, trailing, opensUsage = false, }: { readonly label: string; readonly icon: ReactNode; readonly fill: number | null; readonly tone: UsageTone; readonly tick?: number | null; readonly value: string; readonly ariaValue?: string; readonly tooltip: ReactNode; readonly trailing?: ReactNode; readonly opensUsage?: boolean; }) { const gt = useGT(); const rowProps = { "aria-label": gt("{label}: {value}", { label, value: ariaValue }), className: cn( "flex min-w-0 flex-1 items-center gap-2 rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring", opensUsage ? "cursor-pointer" : "cursor-default", ), }; return (
:
} > {icon} {label} {fill !== null ? ( {fill > 0 ? ( ) : null} {tick !== null ? ( ) : null} ) : ( )} {value} {trailing}
{tooltip} {opensUsage ? {gt("Open usage")} : null}
); }