Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(analytics): add subscription utilization analytics (#847)
Owen9227964cb699
diff --git a/src/app/(dashboard)/dashboard/analytics/ComboHealthTab.tsx b/src/app/(dashboard)/dashboard/analytics/ComboHealthTab.tsxnew file mode 100644index 0000000000..6096b6c8f9--- /dev/null+++ b/src/app/(dashboard)/dashboard/analytics/ComboHealthTab.tsx@@ -0,0 +1,477 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import Card from "@/shared/components/Card";+import Badge from "@/shared/components/Badge";+import { Skeleton, Spinner } from "@/shared/components/Loading";+import TimeRangeSelector from "@/shared/components/analytics/TimeRangeSelector";+import type {+ ComboHealthMetrics,+ ComboHealthResponse,+ UtilizationTimeRange,+} from "@/shared/types/utilization";+import { cn } from "@/shared/utils/cn";++function formatPercent(value: number, digits = 0) {+ return `${value.toFixed(digits)}%`;+}++function formatShare(value: number) {+ return formatPercent(value * 100, 1);+}++function formatLatency(value: number) {+ return `${Math.round(value).toLocaleString()}ms`;+}++function getTrendMeta(trend: ComboHealthMetrics["quotaHealth"]["providers"][number]["trend"]) {+ if (trend === "improving") {+ return {+ icon: "trending_up",+ label: "Improving",+ variant: "success" as const,+ };+ }++ if (trend === "declining") {+ return {+ icon: "trending_down",+ label: "Declining",+ variant: "warning" as const,+ };+ }++ return {+ icon: "trending_flat",+ label: "Stable",+ variant: "default" as const,+ };+}++function MetricBlock({+ icon,+ label,+ value,+ subValue,+}: {+ icon: string;+ label: string;+ value: string;+ subValue?: string;+}) {+ return (+ <div className="rounded-lg border border-black/5 bg-black/[0.02] p-4 dark:border-white/5 dark:bg-white/[0.02]">+ <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-text-muted">+ <span className="material-symbols-outlined text-[16px]">{icon}</span>+ {label}+ </div>+ <div className="mt-2 text-2xl font-semibold text-text-main">{value}</div>+ {subValue ? <div className="mt-1 text-xs text-text-muted">{subValue}</div> : null}+ </div>+ );+}++function DistributionBar({ label, value, meta }: { label: string; value: number; meta: string }) {+ const width = `${Math.max(value * 100, value > 0 ? 6 : 0)}%`;++ return (+ <div className="flex flex-col gap-2 rounded-lg border border-black/5 bg-black/[0.02] p-3 dark:border-white/5 dark:bg-white/[0.02]">+ <div className="flex items-center justify-between gap-3 text-sm">+ <span className="truncate font-medium text-text-main">{label}</span>+ <span className="shrink-0 text-xs text-text-muted">{meta}</span>+ </div>+ <div className="h-2 overflow-hidden rounded-full bg-black/5 dark:bg-white/5">+ <div className="h-full rounded-full bg-primary transition-all" style={{ width }} />+ </div>+ </div>+ );+}++function ComboHealthCard({ combo }: { combo: ComboHealthMetrics }) {+ const sortedDistribution = useMemo(+ () =>+ [...combo.usageSkew.modelDistribution].sort(+ (left, right) => right.requestShare - left.requestShare+ ),+ [combo.usageSkew.modelDistribution]+ );++ return (+ <Card className="overflow-hidden p-0">+ <div className="border-b border-black/5 px-6 py-5 dark:border-white/5">+ <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <h3 className="text-lg font-semibold text-text-main">{combo.comboName}</h3>+ <Badge variant="primary" size="sm">+ {combo.strategy}+ </Badge>+ </div>+ <p className="mt-2 text-sm text-text-muted">+ {combo.models.length} models across {combo.quotaHealth.providers.length} providers+ </p>+ </div>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3 lg:min-w-[420px]">+ <MetricBlock+ icon="battery_status_good"+ label="Worst quota left"+ value={formatPercent(combo.quotaHealth.worstRemainingPct)}+ />+ <MetricBlock+ icon="balance"+ label="Usage skew"+ value={combo.usageSkew.giniCoefficient.toFixed(2)}+ subValue="Gini coefficient"+ />+ <MetricBlock+ icon="bolt"+ label="Success rate"+ value={formatPercent(combo.performance.successRate * 100, 1)}+ subValue={`${combo.performance.totalRequests.toLocaleString()} requests`}+ />+ </div>+ </div>+ </div>++ <div className="grid gap-6 px-6 py-5 xl:grid-cols-[1.1fr_1fr_0.95fr]">+ <section className="flex flex-col gap-4">+ <div>+ <div className="text-sm font-semibold text-text-main">Quota health</div>+ <div className="mt-1 text-xs text-text-muted">+ Lowest remaining quota across providers with short trend signals.+ </div>+ </div>++ <div className="flex flex-col gap-3">+ {combo.quotaHealth.providers.map((provider) => {+ const trendMeta = getTrendMeta(provider.trend);+ const width = `${Math.max(provider.remainingPct, provider.remainingPct > 0 ? 6 : 0)}%`;++ return (+ <div+ key={provider.provider}+ className="rounded-lg border border-black/5 bg-black/[0.02] p-4 dark:border-white/5 dark:bg-white/[0.02]"+ >+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div>+ <div className="text-sm font-medium text-text-main">{provider.provider}</div>+ <div className="mt-1 text-xs text-text-muted">+ Remaining quota {formatPercent(provider.remainingPct, 1)}+ </div>+ </div>+ <div className="flex items-center gap-2">+ <Badge variant={trendMeta.variant} size="sm" icon={trendMeta.icon}>+ {trendMeta.label}+ </Badge>+ {provider.isExhausted ? (+ <Badge variant="error" size="sm">+ Exhausted+ </Badge>+ ) : null}+ </div>+ </div>+ <div className="mt-3 h-2 overflow-hidden rounded-full bg-black/5 dark:bg-white/5">+ <div+ className="h-full rounded-full bg-primary transition-all"+ style={{ width }}+ />+ </div>+ </div>+ );+ })}+ </div>+ </section>++ <section className="flex flex-col gap-4">+ <div>+ <div className="text-sm font-semibold text-text-main">Usage skew</div>+ <div className="mt-1 text-xs text-text-muted">+ Model request share and token share within this combo.+ </div>+ </div>++ <div className="flex flex-col gap-3">+ {sortedDistribution.map((entry) => (+ <div+ key={entry.model}+ className="rounded-lg border border-black/5 bg-black/[0.02] p-4 dark:border-white/5 dark:bg-white/[0.02]"+ >+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="truncate text-sm font-medium text-text-main">{entry.model}</div>+ <div className="mt-1 text-xs text-text-muted">+ Request share {formatShare(entry.requestShare)} · Token share{" "}+ {formatShare(entry.tokenShare)}+ </div>+ </div>+ <Badge size="sm">{formatShare(entry.requestShare)}</Badge>+ </div>++ <div className="mt-3 grid gap-2">+ <DistributionBar+ label="Requests"+ value={entry.requestShare}+ meta={formatShare(entry.requestShare)}+ />+ <DistributionBar+ label="Tokens"+ value={entry.tokenShare}+ meta={formatShare(entry.tokenShare)}+ />+ </div>+ </div>+ ))}+ </div>+ </section>++ <section className="flex flex-col gap-4">+ <div>+ <div className="text-sm font-semibold text-text-main">Performance</div>+ <div className="mt-1 text-xs text-text-muted">+ Reliability and throughput for routed combo traffic.+ </div>+ </div>++ <div className="grid gap-3 sm:grid-cols-3 xl:grid-cols-1">+ <MetricBlock+ icon="timer"+ label="Avg latency"+ value={formatLatency(combo.performance.avgLatencyMs)}+ />+ <MetricBlock+ icon="task_alt"+ label="Success rate"+ value={formatPercent(combo.performance.successRate * 100, 1)}+ />+ <MetricBlock+ icon="stacked_line_chart"+ label="Total requests"+ value={combo.performance.totalRequests.toLocaleString()}+ />+ </div>+ </section>+ </div>+ </Card>+ );+}++function ComboHealthSkeleton() {+ return (+ <div className="flex flex-col gap-4">+ {[0, 1].map((index) => (+ <Card key={index} className="p-6">+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between">+ <div className="space-y-2">+ <Skeleton className="h-6 w-40" />+ <Skeleton className="h-4 w-52" />+ </div>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3 xl:min-w-[420px]">+ {[0, 1, 2].map((item) => (+ <Skeleton key={item} className="h-24 rounded-lg" />+ ))}+ </div>+ </div>+ <div className="grid gap-4 xl:grid-cols-3">+ {[0, 1, 2].map((item) => (+ <div key={item} className="space-y-3">+ <Skeleton className="h-5 w-28" />+ <Skeleton className="h-24 rounded-lg" />+ <Skeleton className="h-24 rounded-lg" />+ </div>+ ))}+ </div>+ </div>+ </Card>+ ))}+ </div>+ );+}++export default function ComboHealthTab() {+ const [range, setRange] = useState<UtilizationTimeRange>("24h");+ const [data, setData] = useState<ComboHealthResponse | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [retrying, setRetrying] = useState(false);++ useEffect(() => {+ const controller = new AbortController();++ async function fetchComboHealth() {+ setLoading(true);+ setError(null);++ try {+ const response = await fetch(`/api/usage/combo-health?range=${range}`, {+ signal: controller.signal,+ });++ if (!response.ok) {+ throw new Error("Failed to fetch combo health data");+ }++ const result = (await response.json()) as ComboHealthResponse;+ setData(result);+ } catch (fetchError) {+ if ((fetchError as Error).name === "AbortError") {+ return;+ }++ setError(fetchError instanceof Error ? fetchError.message : "Unknown error");+ setData(null);+ } finally {+ if (!controller.signal.aborted) {+ setLoading(false);+ }+ }+ }++ fetchComboHealth();++ return () => controller.abort();+ }, [range]);++ const combos = data?.combos ?? [];++ const handleRetry = useCallback(() => {+ setRetrying(true);+ setError(null);+ const controller = new AbortController();++ async function retryFetch() {+ try {+ const response = await fetch(`/api/usage/combo-health?range=${range}`, {+ signal: controller.signal,+ });++ if (!response.ok) {+ throw new Error("Failed to fetch combo health data");+ }++ const result = (await response.json()) as ComboHealthResponse;+ setData(result);+ setError(null);+ } catch (fetchError) {+ if ((fetchError as Error).name === "AbortError") {+ return;+ }+ setError(fetchError instanceof Error ? fetchError.message : "Unknown error");+ } finally {+ if (!controller.signal.aborted) {+ setLoading(false);+ setRetrying(false);+ }+ }+ }++ retryFetch();++ return () => controller.abort();+ }, [range]);++ return (+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-4 rounded-xl border border-black/5 bg-surface p-5 shadow-sm dark:border-white/5 md:flex-row md:items-center md:justify-between">+ <div>+ <h2 className="text-lg font-semibold text-text-main">Combo health</h2>+ <p className="mt-1 text-sm text-text-muted">+ Monitor quota pressure, skewed model usage, and delivery performance by combo.+ </p>+ </div>+ <TimeRangeSelector value={range} onChange={setRange} />+ </div>++ {loading ? <ComboHealthSkeleton /> : null}++ {!loading && error ? (+ <Card className="p-8">+ <div className="flex flex-col items-center justify-center gap-4 text-center">+ <span className="material-symbols-outlined text-[40px] text-error">sync_problem</span>+ <div className="flex flex-col gap-1">+ <div className="font-medium text-text-main">Unable to load combo health</div>+ <div className="text-sm text-text-muted">{error}</div>+ </div>+ <button+ type="button"+ onClick={handleRetry}+ disabled={retrying}+ className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-primary-hover disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {retrying ? (+ <>+ <span className="material-symbols-outlined animate-spin text-[18px]">+ progress_activity+ </span>+ Retrying…+ </>+ ) : (+ <>+ <span className="material-symbols-outlined text-[18px]">refresh</span>+ Retry+ </>+ )}+ </button>+ </div>+ </Card>+ ) : null}++ {!loading && !error && combos.length === 0 ? (+ <Card className="p-10">+ <div className="flex flex-col items-center justify-center gap-4 text-center">+ <span className="material-symbols-outlined text-[40px] text-text-muted/70">+ monitor_heart+ </span>+ <div className="text-base font-medium text-text-main">+ No combo health data available+ </div>+ <div className="max-w-md text-sm text-text-muted">+ Combo quota snapshots and routed requests will appear here after traffic starts+ flowing.+ </div>+ <div className="rounded-lg border border-black/5 bg-black/[0.02] p-4 dark:border-white/5 dark:bg-white/[0.02]">+ <p className="text-xs font-medium text-text-main">Getting started</p>+ <ul className="mt-2 text-left text-xs text-text-muted">+ <li className="flex items-start gap-2">+ <span className="material-symbols-outlined text-[14px] text-primary">+ check_circle+ </span>+ <span>+ Create combos in <strong>Combos</strong> with multiple providers+ </span>+ </li>+ <li className="mt-1 flex items-start gap-2">+ <span className="material-symbols-outlined text-[14px] text-primary">+ check_circle+ </span>+ <span>Send requests to combo endpoints to generate traffic data</span>+ </li>+ <li className="mt-1 flex items-start gap-2">+ <span className="material-symbols-outlined text-[14px] text-primary">+ check_circle+ </span>+ <span>Health metrics will appear automatically as requests are routed</span>+ </li>+ </ul>+ </div>+ </div>+ </Card>+ ) : null}++ {!loading && !error && combos.length > 0 ? (+ <div className="flex flex-col gap-4">+ <div className="flex items-center gap-2 text-sm text-text-muted">+ <Spinner+ size="sm"+ className={cn("text-primary", "[&_.material-symbols-outlined]:text-[16px]")}+ />+ Tracking {combos.length} combos for {range}+ </div>+ {combos.map((combo) => (+ <ComboHealthCard key={combo.comboId} combo={combo} />+ ))}+ </div>+ ) : null}+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/analytics/ProviderUtilizationTab.tsx b/src/app/(dashboard)/dashboard/analytics/ProviderUtilizationTab.tsxnew file mode 100644index 0000000000..8d48e93436--- /dev/null+++ b/src/app/(dashboard)/dashboard/analytics/ProviderUtilizationTab.tsx@@ -0,0 +1,389 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import {+ CartesianGrid,+ Legend,+ Line,+ LineChart,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from "recharts";+import Card from "@/shared/components/Card";+import ProviderIcon from "@/shared/components/ProviderIcon";+import TimeRangeSelector from "@/shared/components/analytics/TimeRangeSelector";+import type {+ ProviderUtilizationPoint,+ ProviderUtilizationResponse,+ UtilizationTimeRange,+} from "@/shared/types/utilization";++const RANGE_LABELS: Record<UtilizationTimeRange, string> = {+ "1h": "Last hour",+ "24h": "Last 24 hours",+ "7d": "Last 7 days",+ "30d": "Last 30 days",+};++const PROVIDER_COLORS = [+ "var(--color-primary)",+ "var(--color-accent)",+ "var(--color-success)",+ "var(--color-warning)",+ "var(--color-error)",+ "var(--color-text-muted)",+];++function formatTimestamp(value: string, range: UtilizationTimeRange) {+ const date = new Date(value);++ if (Number.isNaN(date.getTime())) {+ return value;+ }++ if (range === "1h" || range === "24h") {+ return new Intl.DateTimeFormat(undefined, {+ hour: "2-digit",+ minute: "2-digit",+ }).format(date);+ }++ return new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ }).format(date);+}++function formatTooltipTimestamp(value: string, range: UtilizationTimeRange) {+ const date = new Date(value);++ if (Number.isNaN(date.getTime())) {+ return value;+ }++ return new Intl.DateTimeFormat(undefined, {+ month: "short",+ day: "numeric",+ hour: range === "1h" || range === "24h" ? "2-digit" : undefined,+ minute: range === "1h" || range === "24h" ? "2-digit" : undefined,+ }).format(date);+}++function formatPercent(value: number) {+ return `${Math.round(value)}%`;+}++function getLatestPoints(points: ProviderUtilizationPoint[]) {+ const latestByProvider = new Map<string, ProviderUtilizationPoint>();++ for (const point of points) {+ const current = latestByProvider.get(point.provider);+ if (!current || new Date(point.timestamp).getTime() > new Date(current.timestamp).getTime()) {+ latestByProvider.set(point.provider, point);+ }+ }++ return Array.from(latestByProvider.values()).sort((a, b) => b.remainingPct - a.remainingPct);+}++export default function ProviderUtilizationTab() {+ const [range, setRange] = useState<UtilizationTimeRange>("24h");+ const [data, setData] = useState<ProviderUtilizationResponse | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ const fetchUtilization = useCallback(+ async (selectedRange: UtilizationTimeRange, signal?: AbortSignal) => {+ setLoading(true);++ try {+ const response = await fetch(`/api/usage/utilization?range=${selectedRange}`, {+ signal,+ cache: "no-store",+ });++ if (!response.ok) {+ throw new Error("Failed to fetch utilization data");+ }++ const json = (await response.json()) as ProviderUtilizationResponse;+ setData(json);+ setError(null);+ } catch (fetchError) {+ if (fetchError instanceof DOMException && fetchError.name === "AbortError") {+ return;+ }++ setError(+ fetchError instanceof Error ? fetchError.message : "Failed to fetch utilization data"+ );+ setData(null);+ } finally {+ if (!signal?.aborted) {+ setLoading(false);+ }+ }+ },+ []+ );++ useEffect(() => {+ const controller = new AbortController();++ fetchUtilization(range, controller.signal);++ return () => controller.abort();+ }, [fetchUtilization, range]);++ const providerColors = useMemo(() => {+ const colors = new Map<string, string>();++ for (const [index, provider] of (data?.providers ?? []).entries()) {+ colors.set(provider, PROVIDER_COLORS[index % PROVIDER_COLORS.length]);+ }++ return colors;+ }, [data?.providers]);++ const chartData = useMemo(() => {+ if (!data?.data.length) {+ return [];+ }++ const byTimestamp = new Map<string, Record<string, number | string>>();++ for (const point of data.data) {+ const entry = byTimestamp.get(point.timestamp) ?? {+ timestamp: point.timestamp,+ label: formatTimestamp(point.timestamp, data.timeRange),+ };++ entry[point.provider] = Number(point.remainingPct.toFixed(2));+ byTimestamp.set(point.timestamp, entry);+ }++ return Array.from(byTimestamp.entries())+ .sort(([left], [right]) => new Date(left).getTime() - new Date(right).getTime())+ .map(([, value]) => value);+ }, [data]);++ const latestPoints = useMemo(() => getLatestPoints(data?.data ?? []), [data?.data]);++ const hasData = Boolean(data?.data.length);+ const [retrying, setRetrying] = useState(false);++ const handleRetry = useCallback(() => {+ setRetrying(true);+ setError(null);+ fetchUtilization(range).finally(() => setRetrying(false));+ }, [range, fetchUtilization]);++ return (+ <div className="flex flex-col gap-6">+ <Card+ title="Provider utilization"+ subtitle={RANGE_LABELS[range]}+ icon="monitoring"+ action={<TimeRangeSelector value={range} onChange={setRange} />}+ className="overflow-hidden"+ >+ {loading && !hasData ? (+ <div className="flex min-h-80 items-center justify-center text-sm text-text-muted">+ <span className="material-symbols-outlined mr-2 animate-spin text-[18px]">+ progress_activity+ </span>+ Loading utilization data…+ </div>+ ) : error ? (+ <div className="flex min-h-80 flex-col items-center justify-center gap-4 text-center">+ <span className="material-symbols-outlined text-[32px] text-error">error</span>+ <div className="flex flex-col gap-1">+ <p className="text-sm font-medium text-text-main">Failed to load utilization data</p>+ <p className="text-sm text-text-muted">{error}</p>+ </div>+ <button+ type="button"+ onClick={handleRetry}+ disabled={retrying}+ className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-primary-hover disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {retrying ? (+ <>+ <span className="material-symbols-outlined animate-spin text-[18px]">+ progress_activity+ </span>+ Retrying…+ </>+ ) : (+ <>+ <span className="material-symbols-outlined text-[18px]">refresh</span>+ Retry+ </>+ )}+ </button>+ </div>+ ) : !hasData ? (+ <div className="flex min-h-80 flex-col items-center justify-center gap-4 text-center">+ <span className="material-symbols-outlined text-[40px] text-text-muted/70">+ timeline+ </span>+ <div className="flex flex-col gap-2">+ <p className="text-sm font-medium text-text-main">No utilization data available</p>+ <p className="max-w-md text-sm text-text-muted">+ Provider quota snapshots will appear here after utilization data is collected.+ </p>+ </div>+ <div className="rounded-lg border border-black/5 bg-black/[0.02] p-4 dark:border-white/5 dark:bg-white/[0.02]">+ <p className="text-xs font-medium text-text-main">Getting started</p>+ <ul className="mt-2 text-left text-xs text-text-muted">+ <li className="flex items-start gap-2">+ <span className="material-symbols-outlined text-[14px] text-primary">+ check_circle+ </span>+ <span>+ Connect providers via OAuth or API keys in <strong>Providers</strong>+ </span>+ </li>+ <li className="mt-1 flex items-start gap-2">+ <span className="material-symbols-outlined text-[14px] text-primary">+ check_circle+ </span>+ <span>+ Enable quota tracking by using the provider in a combo or direct request+ </span>+ </li>+ <li className="mt-1 flex items-start gap-2">+ <span className="material-symbols-outlined text-[14px] text-primary">+ check_circle+ </span>+ <span>Data will appear automatically as quota snapshots are collected</span>+ </li>+ </ul>+ </div>+ </div>+ ) : (+ <div className="flex flex-col gap-5">+ <div className="h-80 w-full rounded-xl border border-black/5 bg-black/[0.02] px-3 py-4 dark:border-white/5 dark:bg-white/[0.02]">+ <ResponsiveContainer width="100%" height="100%">+ <LineChart data={chartData} margin={{ top: 8, right: 16, bottom: 0, left: 0 }}>+ <CartesianGrid+ stroke="var(--color-border)"+ strokeDasharray="3 3"+ vertical={false}+ />+ <XAxis+ dataKey="timestamp"+ tickFormatter={(value) => formatTimestamp(String(value), range)}+ tick={{ fill: "var(--color-text-muted)", fontSize: 12 }}+ axisLine={{ stroke: "var(--color-border)" }}+ tickLine={{ stroke: "var(--color-border)" }}+ minTickGap={24}+ />+ <YAxis+ domain={[0, 100]}+ tickFormatter={formatPercent}+ tick={{ fill: "var(--color-text-muted)", fontSize: 12 }}+ axisLine={{ stroke: "var(--color-border)" }}+ tickLine={{ stroke: "var(--color-border)" }}+ width={44}+ />+ <Tooltip+ labelFormatter={(value) => formatTooltipTimestamp(String(value), range)}+ formatter={(value: number, name: string) => [formatPercent(value), name]}+ contentStyle={{+ backgroundColor: "var(--color-surface)",+ borderColor: "var(--color-border)",+ borderRadius: 12,+ color: "var(--color-text-main)",+ boxShadow: "var(--shadow-soft)",+ }}+ itemStyle={{ color: "var(--color-text-main)" }}+ labelStyle={{ color: "var(--color-text-main)", fontWeight: 600 }}+ />+ <Legend />+ {data?.providers.map((provider) => (+ <Line+ key={provider}+ type="monotone"+ dataKey={provider}+ name={provider}+ stroke={providerColors.get(provider) ?? "var(--color-primary)"}+ strokeWidth={2.5}+ dot={false}+ activeDot={{ r: 4, strokeWidth: 0 }}+ connectNulls+ />+ ))}+ </LineChart>+ </ResponsiveContainer>+ </div>++ <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">+ {latestPoints.map((point) => {+ const isLow = point.remainingPct <= 20;++ return (+ <Card.Section key={point.provider} className="flex h-full flex-col gap-4">+ <div className="flex items-start justify-between gap-3">+ <div className="flex items-center gap-3">+ <div className="flex h-11 w-11 items-center justify-center rounded-xl border border-black/5 bg-surface text-text-main dark:border-white/5">+ <ProviderIcon providerId={point.provider} size={22} />+ </div>+ <div>+ <p className="text-sm font-semibold text-text-main">{point.provider}</p>+ <p className="text-xs text-text-muted">Latest quota snapshot</p>+ </div>+ </div>+ <span+ className={`inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium ${+ point.isExhausted+ ? "bg-error/10 text-error"+ : isLow+ ? "bg-warning/10 text-warning"+ : "bg-success/10 text-success"+ }`}+ >+ {point.isExhausted ? "Exhausted" : isLow ? "Low" : "Healthy"}+ </span>+ </div>++ <div className="flex items-end justify-between gap-3">+ <div>+ <p className="text-3xl font-bold text-text-main">+ {point.remainingPct.toFixed(point.remainingPct < 10 ? 1 : 0)}%+ </p>+ <p className="mt-1 text-xs text-text-muted">Remaining capacity</p>+ </div>+ <div className="text-right text-xs text-text-muted">+ <p>{formatTooltipTimestamp(point.timestamp, range)}</p>+ <p className="mt-1 uppercase tracking-[0.14em]">{point.windowKey}</p>+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <div className="h-2 overflow-hidden rounded-full bg-black/5 dark:bg-white/5">+ <div+ className={`h-full rounded-full transition-all ${+ point.isExhausted ? "bg-error" : isLow ? "bg-warning" : "bg-primary"+ }`}+ style={{ width: `${Math.max(point.remainingPct, 0)}%` }}+ />+ </div>+ <div className="flex items-center justify-between text-xs text-text-muted">+ <span>0%</span>+ <span>Remaining quota</span>+ <span>100%</span>+ </div>+ </div>+ </Card.Section>+ );+ })}+ </div>+ </div>+ )}+ </Card>+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/analytics/page.tsx b/src/app/(dashboard)/dashboard/analytics/page.tsxindex 87aa0f69e6..dbea904551 100644--- a/src/app/(dashboard)/dashboard/analytics/page.tsx+++ b/src/app/(dashboard)/dashboard/analytics/page.tsx@@ -5,6 +5,8 @@ import { UsageAnalytics, CardSkeleton, SegmentedControl } from "@/shared/componeimport EvalsTab from "../usage/components/EvalsTab";import SearchAnalyticsTab from "./SearchAnalyticsTab";import DiversityScoreCard from "./components/DiversityScoreCard";+import ProviderUtilizationTab from "./ProviderUtilizationTab";+import ComboHealthTab from "./ComboHealthTab";import { useTranslations } from "next-intl";export default function AnalyticsPage() {@@ -15,6 +17,8 @@ export default function AnalyticsPage() {overview: t("overviewDescription"),evals: t("evalsDescription"),search: "Search request analytics — provider breakdown, cache hit rate, and cost tracking.",+ utilization: t("utilizationDescription"),+ comboHealth: t("comboHealthDescription"),};return (@@ -33,6 +37,8 @@ export default function AnalyticsPage() {{ value: "overview", label: t("overview") },{ value: "evals", label: t("evals") },{ value: "search", label: "Search" },+ { value: "utilization", label: t("utilization") },+ { value: "comboHealth", label: t("comboHealth") },]}value={activeTab}onChange={setActiveTab}@@ -50,6 +56,8 @@ export default function AnalyticsPage() {)}{activeTab === "evals" && <EvalsTab />}{activeTab === "search" && <SearchAnalyticsTab />}+ {activeTab === "utilization" && <ProviderUtilizationTab />}+ {activeTab === "comboHealth" && <ComboHealthTab />}</div>);}diff --git a/src/app/api/usage/combo-health/route.ts b/src/app/api/usage/combo-health/route.tsnew file mode 100644index 0000000000..9fdbd5f517--- /dev/null+++ b/src/app/api/usage/combo-health/route.ts@@ -0,0 +1,366 @@+import { NextResponse } from "next/server";+import { z } from "zod";+import { getDbInstance } from "@/lib/db/core";+import { getComboById, getCombos } from "@/lib/db/combos";+import { getQuotaSnapshots } from "@/lib/db/quotaSnapshots";+import type {+ ComboHealthMetrics,+ ComboHealthResponse,+ QuotaSnapshotRow,+ UtilizationTimeRange,+} from "@/shared/types/utilization";++type ComboModelNode = string | { model?: string | null };++type ComboRecord = {+ id?: string;+ name?: string;+ strategy?: string;+ models?: ComboModelNode[];+};++type ModelUsageRow = {+ model: string | null;+ requests: number | null;+ totalTokens: number | null;+};++type PerformanceRow = {+ totalRequests: number | null;+ successCount: number | null;+ avgLatencyMs: number | null;+};++type QuotaSnapshotView = {+ connectionId?: string;+ remainingPercentage?: number | null;+ isExhausted?: number;+ createdAt?: string;+};++type ProviderHealth = {+ provider: string;+ remainingPct: number;+ isExhausted: boolean;+ trend: "improving" | "stable" | "declining";+};++const querySchema = z.object({+ range: z.enum(["1h", "24h", "7d", "30d"]),+ comboId: z+ .string()+ .regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)+ .optional(),+});++function getRangeStartIso(range: UtilizationTimeRange): string {+ const end = new Date();+ const start = new Date(end);++ switch (range) {+ case "1h":+ start.setHours(start.getHours() - 1);+ break;+ case "24h":+ start.setDate(start.getDate() - 1);+ break;+ case "7d":+ start.setDate(start.getDate() - 7);+ break;+ case "30d":+ start.setDate(start.getDate() - 30);+ break;+ }++ return start.toISOString();+}++function roundNumber(value: number, digits = 2): number {+ if (!Number.isFinite(value)) return 0;+ return Number(value.toFixed(digits));+}++function toSafeNumber(value: number | null | undefined): number {+ return typeof value === "number" && Number.isFinite(value) ? value : 0;+}++function normalizeComboModels(models: ComboModelNode[] | undefined): string[] {+ if (!Array.isArray(models)) return [];++ return models+ .map((entry) => {+ if (typeof entry === "string") return entry;+ if (entry && typeof entry === "object" && typeof entry.model === "string") {+ return entry.model;+ }+ return "";+ })+ .filter((entry): entry is string => entry.trim().length > 0);+}++function extractProvider(model: string): string {+ const [provider] = model.split("/");+ return provider?.trim() || "unknown";+}++function calculateGini(values: number[]): number {+ if (values.length === 0) return 0;+ const sorted = [...values].sort((a, b) => a - b);+ const count = sorted.length;+ const sum = sorted.reduce((accumulator, value) => accumulator + value, 0);+ if (sum === 0) return 0;++ let weightedSum = 0;+ for (let index = 0; index < count; index += 1) {+ weightedSum += (index + 1) * sorted[index];+ }++ return (2 * weightedSum) / (count * sum) - (count + 1) / count;+}++function buildProviderHealth(provider: string, snapshots: QuotaSnapshotRow[]): ProviderHealth {+ if (snapshots.length === 0) {+ return {+ provider,+ remainingPct: 0,+ isExhausted: false,+ trend: "stable",+ };+ }++ const histories = new Map<string, QuotaSnapshotRow[]>();+ for (const snapshot of snapshots) {+ const snapshotView = snapshot as unknown as QuotaSnapshotView;+ const connectionId = snapshotView.connectionId || "unknown";+ const existing = histories.get(connectionId) ?? [];+ existing.push(snapshot);+ histories.set(connectionId, existing);+ }++ const firstValues: number[] = [];+ const lastValues: number[] = [];+ let isExhausted = false;++ for (const history of histories.values()) {+ const ordered = [...history].sort((left, right) => {+ const leftView = left as unknown as QuotaSnapshotView;+ const rightView = right as unknown as QuotaSnapshotView;+ return (leftView.createdAt || "").localeCompare(rightView.createdAt || "");+ });+ const firstSnapshot = ordered.find((entry) => {+ const entryView = entry as unknown as QuotaSnapshotView;+ return entryView.remainingPercentage !== null && entryView.remainingPercentage !== undefined;+ });+ const lastSnapshot = [...ordered].reverse().find((entry) => {+ const entryView = entry as unknown as QuotaSnapshotView;+ return entryView.remainingPercentage !== null && entryView.remainingPercentage !== undefined;+ });+ const firstSnapshotView = firstSnapshot as unknown as QuotaSnapshotView | undefined;+ const lastSnapshotView = lastSnapshot as unknown as QuotaSnapshotView | undefined;++ if (+ firstSnapshotView?.remainingPercentage !== null &&+ firstSnapshotView?.remainingPercentage !== undefined+ ) {+ firstValues.push(firstSnapshotView.remainingPercentage);+ }++ if (+ lastSnapshotView?.remainingPercentage !== null &&+ lastSnapshotView?.remainingPercentage !== undefined+ ) {+ lastValues.push(lastSnapshotView.remainingPercentage);+ }++ const latestEntry = ordered[ordered.length - 1] as unknown as QuotaSnapshotView | undefined;+ isExhausted = isExhausted || latestEntry?.isExhausted === 1;+ }++ const firstAverage =+ firstValues.length > 0+ ? firstValues.reduce((accumulator, value) => accumulator + value, 0) / firstValues.length+ : 0;+ const lastAverage =+ lastValues.length > 0+ ? lastValues.reduce((accumulator, value) => accumulator + value, 0) / lastValues.length+ : 0;+ const delta = lastAverage - firstAverage;++ let trend: ProviderHealth["trend"] = "stable";+ if (delta >= 5) trend = "improving";+ if (delta <= -5) trend = "declining";++ return {+ provider,+ remainingPct: roundNumber(lastAverage),+ isExhausted,+ trend,+ };+}++function buildUsageSkew(+ comboName: string,+ comboModels: string[],+ since: string+): ComboHealthMetrics["usageSkew"] {+ const db = getDbInstance();+ const rows = db+ .prepare(+ `SELECT+ model,+ COUNT(*) as requests,+ SUM(COALESCE(tokens_in, 0) + COALESCE(tokens_out, 0)) as totalTokens+ FROM call_logs+ WHERE combo_name = ?+ AND timestamp >= ?+ GROUP BY model`+ )+ .all(comboName, since) as ModelUsageRow[];++ const usageByModel = new Map<string, { requests: number; tokens: number }>();+ for (const model of comboModels) {+ usageByModel.set(model, { requests: 0, tokens: 0 });+ }++ for (const row of rows) {+ const model =+ typeof row.model === "string" && row.model.trim().length > 0 ? row.model : "unknown";+ usageByModel.set(model, {+ requests: toSafeNumber(row.requests),+ tokens: toSafeNumber(row.totalTokens),+ });+ }++ const modelDistributionEntries = Array.from(usageByModel.entries());+ const totalRequests = modelDistributionEntries.reduce(+ (accumulator, [, usage]) => accumulator + usage.requests,+ 0+ );+ const totalTokens = modelDistributionEntries.reduce(+ (accumulator, [, usage]) => accumulator + usage.tokens,+ 0+ );++ return {+ modelDistribution: modelDistributionEntries.map(([model, usage]) => ({+ model,+ requestShare: totalRequests > 0 ? roundNumber(usage.requests / totalRequests, 4) : 0,+ tokenShare: totalTokens > 0 ? roundNumber(usage.tokens / totalTokens, 4) : 0,+ })),+ giniCoefficient: roundNumber(+ calculateGini(modelDistributionEntries.map(([, usage]) => usage.requests)),+ 4+ ),+ };+}++function buildPerformance(comboName: string, since: string): ComboHealthMetrics["performance"] {+ const db = getDbInstance();+ const row = db+ .prepare(+ `SELECT+ COUNT(*) as totalRequests,+ SUM(CASE WHEN status >= 200 AND status < 400 THEN 1 ELSE 0 END) as successCount,+ AVG(duration) as avgLatencyMs+ FROM call_logs+ WHERE combo_name = ?+ AND timestamp >= ?`+ )+ .get(comboName, since) as PerformanceRow | undefined;++ const totalRequests = toSafeNumber(row?.totalRequests);+ const successCount = toSafeNumber(row?.successCount);+ const avgLatencyMs = toSafeNumber(row?.avgLatencyMs);++ return {+ avgLatencyMs: roundNumber(avgLatencyMs),+ successRate: totalRequests > 0 ? roundNumber(successCount / totalRequests, 4) : 0,+ totalRequests,+ };+}++function buildQuotaHealth(providers: string[], since: string): ComboHealthMetrics["quotaHealth"] {+ const providerHealth = providers.map((provider) =>+ buildProviderHealth(provider, getQuotaSnapshots({ provider, since }))+ );++ const worstRemainingPct =+ providerHealth.length > 0+ ? providerHealth.reduce(+ (lowest, entry) => Math.min(lowest, entry.remainingPct),+ providerHealth[0].remainingPct+ )+ : 0;++ return {+ providers: providerHealth,+ worstRemainingPct: roundNumber(worstRemainingPct),+ };+}++function buildComboHealth(combo: ComboRecord, since: string): ComboHealthMetrics | null {+ const comboId = typeof combo.id === "string" ? combo.id : "";+ const comboName = typeof combo.name === "string" ? combo.name : "";+ if (!comboId || !comboName) return null;++ const models = normalizeComboModels(combo.models);+ const providers = Array.from(new Set(models.map(extractProvider)));++ return {+ comboId,+ comboName,+ strategy:+ typeof combo.strategy === "string" && combo.strategy.trim().length > 0+ ? combo.strategy+ : "priority",+ models,+ quotaHealth: buildQuotaHealth(providers, since),+ usageSkew: buildUsageSkew(comboName, models, since),+ performance: buildPerformance(comboName, since),+ };+}++export async function GET(request: Request) {+ try {+ const { searchParams } = new URL(request.url);+ const parsedQuery = querySchema.safeParse({+ range: searchParams.get("range"),+ comboId: searchParams.get("comboId") || undefined,+ });++ if (!parsedQuery.success) {+ return NextResponse.json(+ {+ error: parsedQuery.error.issues[0]?.message ?? "Invalid query parameters",+ },+ { status: 400 }+ );+ }++ const { range, comboId } = parsedQuery.data;+ const since = getRangeStartIso(range);++ let combos: ComboRecord[] = [];+ if (comboId) {+ const combo = (await getComboById(comboId)) as ComboRecord | null;+ if (!combo) {+ return NextResponse.json({ error: "Combo not found" }, { status: 404 });+ }+ combos = [combo];+ } else {+ combos = (await getCombos()) as ComboRecord[];+ }++ const response: ComboHealthResponse = {+ timeRange: range,+ combos: combos+ .map((combo) => buildComboHealth(combo, since))+ .filter((combo): combo is ComboHealthMetrics => combo !== null),+ };++ return NextResponse.json(response);+ } catch (error) {+ console.error("Error fetching combo health:", error);+ return NextResponse.json({ error: "Failed to fetch combo health" }, { status: 500 });+ }+}diff --git a/src/app/api/usage/utilization/route.ts b/src/app/api/usage/utilization/route.tsnew file mode 100644index 0000000000..df18fa455f--- /dev/null+++ b/src/app/api/usage/utilization/route.ts@@ -0,0 +1,67 @@+import { NextResponse } from "next/server";+import { getAggregatedSnapshots } from "@/lib/db/quotaSnapshots";+import type { ProviderUtilizationResponse, UtilizationTimeRange } from "@/shared/types/utilization";+import { BUCKET_SIZES } from "@/shared/types/utilization";++const VALID_RANGES: UtilizationTimeRange[] = ["1h", "24h", "7d", "30d"];++function getRangeStartIso(range: UtilizationTimeRange): string {+ const end = new Date();+ const start = new Date(end);++ switch (range) {+ case "1h":+ start.setHours(start.getHours() - 1);+ break;+ case "24h":+ start.setDate(start.getDate() - 1);+ break;+ case "7d":+ start.setDate(start.getDate() - 7);+ break;+ case "30d":+ start.setDate(start.getDate() - 30);+ break;+ }++ return start.toISOString();+}++export async function GET(request: Request) {+ try {+ const { searchParams } = new URL(request.url);+ const rangeParam = searchParams.get("range");+ const providerParam = searchParams.get("provider");++ if (!rangeParam || !VALID_RANGES.includes(rangeParam as UtilizationTimeRange)) {+ return NextResponse.json(+ { error: "Invalid range. Must be one of: 1h, 24h, 7d, 30d" },+ { status: 400 }+ );+ }++ const range = rangeParam as UtilizationTimeRange;+ const since = getRangeStartIso(range);+ const bucketMinutes = BUCKET_SIZES[range];++ const data = getAggregatedSnapshots({+ provider: providerParam || undefined,+ since,+ bucketMinutes,+ });++ const providers = Array.from(new Set(data.map((d) => d.provider)));++ const response: ProviderUtilizationResponse = {+ timeRange: range,+ bucketSizeMinutes: bucketMinutes,+ providers,+ data,+ };++ return NextResponse.json(response);+ } catch (error) {+ console.error("Error fetching utilization data:", error);+ return NextResponse.json({ error: "Failed to fetch utilization data" }, { status: 500 });+ }+}diff --git a/src/domain/quotaCache.ts b/src/domain/quotaCache.tsindex 616859da23..759335228c 100644--- a/src/domain/quotaCache.ts+++ b/src/domain/quotaCache.ts@@ -17,6 +17,7 @@ import { getUsageForProvider } from "@omniroute/open-sse/services/usage.ts";import { getProviderConnectionById, resolveProxyForConnection } from "@/lib/localDb";import { runWithProxyContext } from "@omniroute/open-sse/utils/proxyFetch.ts";import { safePercentage } from "@/shared/utils/formatting";+import { saveQuotaSnapshot, cleanupOldSnapshots } from "@/lib/db/quotaSnapshots";// ─── Types ──────────────────────────────────────────────────────────────────@@ -181,14 +182,40 @@ export function setQuotaCache() {const quotas = normalizeQuotas(rawQuotas);const exhausted = isExhausted(quotas);- cache.set(connectionId, {+ const entry: QuotaCacheEntry = {connectionId,provider,quotas,fetchedAt: Date.now(),exhausted,nextResetAt: exhausted ? earliestResetAt(quotas) : null,- });+ };+ cache.set(connectionId, entry);++ if (entry && rawQuotas) {+ for (const [windowKey, quotaInfo] of Object.entries(rawQuotas)) {+ if (!quotaInfo || typeof quotaInfo !== "object") continue;+ const remainingPercentage =+ safePercentage(quotaInfo.remainingPercentage) ??+ (quotaInfo.total > 0+ ? Math.round(((quotaInfo.total - (quotaInfo.used || 0)) / quotaInfo.total) * 100)+ : 0);+ try {+ saveQuotaSnapshot({+ provider,+ connection_id: connectionId,+ window_key: windowKey,+ remaining_percentage: remainingPercentage,+ is_exhausted: entry.exhausted ? 1 : 0,+ next_reset_at: quotaInfo.resetAt ?? null,+ window_duration_ms: entry.windowDurationMs ?? null,+ raw_data: null,+ });+ } catch (error) {+ console.error("[quotaCache] Failed to save snapshot:", error);+ }+ }+ }}/**@@ -330,6 +357,7 @@ async function backgroundRefreshTick() {tickRunning = true;try {+ cleanupOldSnapshots();const now = Date.now();const pending = [...cache.values()].filter((e) => needsRefresh(e, now));diff --git a/src/i18n/messages/ar.json b/src/i18n/messages/ar.jsonindex 265696e51a..91867f3f23 100644--- a/src/i18n/messages/ar.json+++ b/src/i18n/messages/ar.json@@ -270,7 +270,11 @@"overviewDescription": "راقب أنماط استخدام واجهة برمجة التطبيقات (API) واستهلاك الرمز المميز والتكاليف واتجاهات النشاط عبر جميع مقدمي الخدمات والنماذج.","evalsDescription": "قم بتشغيل مجموعات التقييم لاختبار نقاط نهاية LLM الخاصة بك والتحقق من صحتها. مقارنة جودة النموذج، واكتشاف الانحدارات، وقياس وقت الاستجابة.","overview": "نظرة عامة",- "evals": "التقييمات"+ "evals": "التقييمات",+ "utilization": "الاستخدام",+ "utilizationDescription": "اتجاهات استخدام حصة المزود وتتبع حدود المعدل",+ "comboHealth": "صحة المجموعة",+ "comboHealthDescription": "الحصة على مستوى المجموعة وتوزيع الاستخدام ومقاييس الأداء"},"apiManager": {"title": "مفاتيح واجهة برمجة التطبيقات",diff --git a/src/i18n/messages/bg.json b/src/i18n/messages/bg.jsonindex 7d6586b9fb..b52dcd79bd 100644--- a/src/i18n/messages/bg.json+++ b/src/i18n/messages/bg.json@@ -268,9 +268,13 @@"analytics": {"title": "Анализ","overviewDescription": "Наблюдавайте своите модели на използване на API, потреблението на токени, разходите и тенденциите в дейността при всички доставчици и модели.",- "evalsDescription": "Изпълнете пакети за оценка, за да тествате и валидирате вашите крайни точки на LLM. Сравнете качеството на модела, открийте регресии и сравните латентността.",+ "evalsDescription": "Изпълнете пакети за оценка, за да тествате и валидирате вашите крайни точки на LLM. Сравнете качеството на модела, открийте регресии и сравнете латентността.","overview": "Преглед",- "evals": "Оценки"+ "evals": "Оценки",+ "utilization": "Използване",+ "utilizationDescription": "Тенденции в използването на квотата на доставчика и проследяване на ограниченията на скоростта",+ "comboHealth": "Здраве на комбинацията",+ "comboHealthDescription": "Квота на ниво комбинация, разпределение на използването и метрики на производителността"},"apiManager": {"title": "API ключове",diff --git a/src/i18n/messages/cs.json b/src/i18n/messages/cs.jsonindex f4df7fadfc..55223bfb46 100644--- a/src/i18n/messages/cs.json+++ b/src/i18n/messages/cs.json@@ -270,7 +270,11 @@"overviewDescription": "Sledujte vzorce používání API, spotřebu tokenů, náklady a trendy aktivity napříč všemi poskytovateli a modely.","evalsDescription": "Spusťte sady vyhodnocovacích programů pro test a ověření LLM koncových bodů. Porovnejte kvalitu modelů, detekujte zhoršení a porovnejte latenci.","overview": "Přehled",- "evals": "Hodnocení"+ "evals": "Hodnocení",+ "utilization": "Využití",+ "utilizationDescription": "Trendy využití kvót poskytovatele a sledování limitů rychlosti",+ "comboHealth": "Zdraví Combo",+ "comboHealthDescription": "Kvóta na úrovni kombinace, distribuce využití a metriky výkonu"},"apiManager": {"title": "API Klíče",diff --git a/src/i18n/messages/da.json b/src/i18n/messages/da.jsonindex 2227bd39eb..7da35e10b4 100644--- a/src/i18n/messages/da.json+++ b/src/i18n/messages/da.json@@ -270,7 +270,11 @@"overviewDescription": "Overvåg dine API-brugsmønstre, tokenforbrug, omkostninger og aktivitetstendenser på tværs af alle udbydere og modeller.","evalsDescription": "Kør evalueringspakker for at teste og validere dine LLM-endepunkter. Sammenlign modelkvalitet, detekter regressioner og benchmark-forsinkelse.","overview": "Oversigt",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Udnyttelse",+ "utilizationDescription": "Leverandørkvoteforbrugstendenser og hastighedsgrænseovervågning",+ "comboHealth": "Kombosundhed",+ "comboHealthDescription": "Komboniveaudkvote, fordeling af brug og ydeevnemålinger"},"apiManager": {"title": "API nøgler",diff --git a/src/i18n/messages/de.json b/src/i18n/messages/de.jsonindex aa9c3a4efa..8cc86960c2 100644--- a/src/i18n/messages/de.json+++ b/src/i18n/messages/de.json@@ -270,7 +270,11 @@"overviewDescription": "Überwachen Sie Ihre API-Nutzungsmuster, Token-Verbrauch, Kosten und Aktivitätstrends bei allen Anbietern und Modellen.","evalsDescription": "Führen Sie Evaluierungssuiten aus, um Ihre LLM-Endpunkte zu testen und zu validieren. Vergleichen Sie die Modellqualität, erkennen Sie Regressionen und messen Sie die Latenz.","overview": "Übersicht",- "evals": "Bewertungen"+ "evals": "Bewertungen",+ "utilization": "Auslastung",+ "utilizationDescription": "Anbieter-Kontingent-Nutzungstrends und Ratenlimit-Verfolgung",+ "comboHealth": "Combo-Gesundheit",+ "comboHealthDescription": "Combo-level Kontingent, Nutzungsverteilung und Leistungsmetriken"},"apiManager": {"title": "API-Schlüssel",diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.jsonindex 1e2b324ce0..522fa600b6 100644--- a/src/i18n/messages/en.json+++ b/src/i18n/messages/en.json@@ -275,7 +275,11 @@"overviewDescription": "Monitor your API usage patterns, token consumption, costs, and activity trends across all providers and models.","evalsDescription": "Run evaluation suites to test and validate your LLM endpoints. Compare model quality, detect regressions, and benchmark latency.","overview": "Overview",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Utilization",+ "utilizationDescription": "Provider quota usage trends and rate limit tracking",+ "comboHealth": "Combo Health",+ "comboHealthDescription": "Combo-level quota, usage distribution, and performance metrics"},"apiManager": {"title": "API Keys",diff --git a/src/i18n/messages/es.json b/src/i18n/messages/es.jsonindex 8bf5d692a9..7ae9518201 100644--- a/src/i18n/messages/es.json+++ b/src/i18n/messages/es.json@@ -270,7 +270,11 @@"overviewDescription": "Supervise sus patrones de uso de API, consumo de tokens, costos y tendencias de actividad en todos los proveedores y modelos.","evalsDescription": "Ejecute conjuntos de evaluación para probar y validar sus puntos finales de LLM. Compare la calidad del modelo, detecte regresiones y compare la latencia.","overview": "Descripción general",- "evals": "evaluaciones"+ "evals": "evaluaciones",+ "utilization": "Utilización",+ "utilizationDescription": "Tendencias de uso de cuota del proveedor y seguimiento de límites de tasa",+ "comboHealth": "Salud del combo",+ "comboHealthDescription": "Cuota a nivel de combo, distribución de uso y métricas de rendimiento"},"apiManager": {"title": "Claves API",diff --git a/src/i18n/messages/fi.json b/src/i18n/messages/fi.jsonindex eeaf8759de..a7512dc581 100644--- a/src/i18n/messages/fi.json+++ b/src/i18n/messages/fi.json@@ -270,7 +270,11 @@"overviewDescription": "Tarkkaile sovellusliittymän käyttötapoja, tunnuksen kulutusta, kustannuksia ja toimintatrendejä kaikilla palveluntarjoajilla ja malleilla.","evalsDescription": "Testaa ja vahvista LLM-päätepisteesi suorittamalla arviointipaketteja. Vertaile mallin laatua, havaitse regressiot ja vertaile viivettä.","overview": "Yleiskatsaus",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Käyttöaste",+ "utilizationDescription": "Palveluntarjoajan kiintiön käyttötrendit ja nopeusrajoitusten seuranta",+ "comboHealth": "Yhdistelmän kunto",+ "comboHealthDescription": "Yhdistelmätason kiintiö, käytön jakautuminen ja suorituskykymittarit"},"apiManager": {"title": "API-avaimet",diff --git a/src/i18n/messages/fr.json b/src/i18n/messages/fr.jsonindex dac4207068..cd3e9e7790 100644--- a/src/i18n/messages/fr.json+++ b/src/i18n/messages/fr.json@@ -270,7 +270,11 @@"overviewDescription": "Surveillez vos modèles d'utilisation des API, la consommation de jetons, les coûts et les tendances d'activité sur tous les fournisseurs et modèles.","evalsDescription": "Exécutez des suites d'évaluation pour tester et valider vos points de terminaison LLM. Comparez la qualité des modèles, détectez les régressions et évaluez la latence.","overview": "Aperçu",- "evals": "Évaluations"+ "evals": "Évaluations",+ "utilization": "Utilisation",+ "utilizationDescription": "Tendances d'utilisation du quota fournisseur et suivi des limites de débit",+ "comboHealth": "Santé du combo",+ "comboHealthDescription": "Quota au niveau combo, distribution de l'utilisation et métriques de performance"},"apiManager": {"title": "Clés API",diff --git a/src/i18n/messages/he.json b/src/i18n/messages/he.jsonindex 1d3f02b1aa..bccc1fe1bc 100644--- a/src/i18n/messages/he.json+++ b/src/i18n/messages/he.json@@ -270,7 +270,11 @@"overviewDescription": "עקוב אחר דפוסי השימוש שלך ב-API, צריכת אסימונים, עלויות ומגמות פעילות בכל הספקים והדגמים.","evalsDescription": "הפעל חבילות הערכה כדי לבדוק ולאמת את נקודות הקצה שלך ב-LLM. השווה את איכות המודל, זיהוי רגרסיות והשהייה בהשוואה.","overview": "סקירה כללית",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "ניצול",+ "utilizationDescription": "מגמות שימוש במכסת הספק ומעקב אחר מגבלות קצב",+ "comboHealth": "בריאות הקומבו",+ "comboHealthDescription": "מכסה ברמת הקומבו, הפצת שימוש ומדדי ביצוע"},"apiManager": {"title": "מפתחות API",diff --git a/src/i18n/messages/hi.json b/src/i18n/messages/hi.jsonindex ab8a067997..3ab8412c18 100644--- a/src/i18n/messages/hi.json+++ b/src/i18n/messages/hi.json@@ -188,7 +188,11 @@"overviewDescription": "सभी प्रदाताओं और मॉडलों में अपने एपीआई उपयोग पैटर्न, टोकन खपत, लागत और गतिविधि रुझान की निगरानी करें।","evalsDescription": "अपने एलएलएम समापन बिंदुओं का परीक्षण और सत्यापन करने के लिए मूल्यांकन सुइट चलाएँ। मॉडल गुणवत्ता की तुलना करें, प्रतिगमन और बेंचमार्क विलंबता का पता लगाएं।","overview": "सिंहावलोकन",- "evals": "एवल्स"+ "evals": "एवल्स",+ "utilization": "उपयोग",+ "utilizationDescription": "प्रदाता कोटा उपयोग रुझान और दर सीमा ट्रैकिंग",+ "comboHealth": "कॉम्बो स्वास्थ्य",+ "comboHealthDescription": "कॉम्बो-स्तरीय कोटा, उपयोग वितरण और प्रदर्शन मेट्रिक्स"},"apiManager": {"title": "एपीआई कुंजी",diff --git a/src/i18n/messages/hu.json b/src/i18n/messages/hu.jsonindex 6c882646bc..4aadf0bba3 100644--- a/src/i18n/messages/hu.json+++ b/src/i18n/messages/hu.json@@ -270,7 +270,11 @@"overviewDescription": "Kövesse nyomon API-használati mintáit, tokenfelhasználását, költségeit és tevékenységi trendjeit az összes szolgáltatónál és modellnél.","evalsDescription": "Futtasson kiértékelő csomagokat az LLM-végpontok teszteléséhez és érvényesítéséhez. Hasonlítsa össze a modell minőségét, észlelje a regressziókat és mérje fel a késleltetést.","overview": "Áttekintés",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Kihasználtság",+ "utilizationDescription": "Szolgáltatói kvótahasználati trendek és sebességkorlát-követés",+ "comboHealth": "Kombo egészsége",+ "comboHealthDescription": "Kombó szintű kvóta, használateloszlás és teljesítménymutatók"},"apiManager": {"title": "API kulcsok",diff --git a/src/i18n/messages/id.json b/src/i18n/messages/id.jsonindex 78194c0090..31d254e7e2 100644--- a/src/i18n/messages/id.json+++ b/src/i18n/messages/id.json@@ -270,7 +270,11 @@"overviewDescription": "Pantau pola penggunaan API Anda, konsumsi token, biaya, dan tren aktivitas di semua penyedia dan model.","evalsDescription": "Jalankan rangkaian evaluasi untuk menguji dan memvalidasi titik akhir LLM Anda. Bandingkan kualitas model, deteksi regresi, dan latensi tolok ukur.","overview": "Ikhtisar",- "evals": "Evaluasi"+ "evals": "Evaluasi",+ "utilization": "Pemanfaatan",+ "utilizationDescription": "Tren penggunaan kuota penyedia dan pelacakan batas tarif",+ "comboHealth": "Kesehatan Kombinasi",+ "comboHealthDescription": "Kuota tingkat kombinasi, distribusi penggunaan, dan metrik kinerja"},"apiManager": {"title": "Kunci API",diff --git a/src/i18n/messages/in.json b/src/i18n/messages/in.jsonindex 702f047895..10398ff425 100644--- a/src/i18n/messages/in.json+++ b/src/i18n/messages/in.json@@ -270,7 +270,11 @@"overviewDescription": "सभी प्रदाताओं और मॉडलों में अपने एपीआई उपयोग पैटर्न, टोकन खपत, लागत और गतिविधि रुझान की निगरानी करें।","evalsDescription": "अपने एलएलएम समापन बिंदुओं का परीक्षण और सत्यापन करने के लिए मूल्यांकन सुइट चलाएँ। मॉडल गुणवत्ता की तुलना करें, प्रतिगमन और बेंचमार्क विलंबता का पता लगाएं।","overview": "सिंहावलोकन",- "evals": "एवल्स"+ "evals": "एवल्स",+ "utilization": "उपयोग",+ "utilizationDescription": "प्रदाता कोटा उपयोग रुझान और दर सीमा ट्रैकिंग",+ "comboHealth": "कॉम्बो स्वास्थ्य",+ "comboHealthDescription": "कॉम्बो-स्तरीय कोटा, उपयोग वितरण और प्रदर्शन मेट्रिक्स"},"apiManager": {"title": "एपीआई कुंजी",diff --git a/src/i18n/messages/it.json b/src/i18n/messages/it.jsonindex 6f6565f227..ed0dd3c965 100644--- a/src/i18n/messages/it.json+++ b/src/i18n/messages/it.json@@ -270,7 +270,11 @@"overviewDescription": "Monitora i modelli di utilizzo delle API, il consumo di token, i costi e le tendenze delle attività su tutti i provider e modelli.","evalsDescription": "Esegui suite di valutazione per testare e convalidare i tuoi endpoint LLM. Confronta la qualità del modello, rileva le regressioni e confronta la latenza.","overview": "Panoramica",- "evals": "Valutazioni"+ "evals": "Valutazioni",+ "utilization": "Utilizzo",+ "utilizationDescription": "Tendenze di utilizzo della quota del provider e monitoraggio dei limiti di frequenza",+ "comboHealth": "Salute Combo",+ "comboHealthDescription": "Quota a livello combo, distribuzione dell'utilizzo e metriche delle prestazioni"},"apiManager": {"title": "Chiavi API",diff --git a/src/i18n/messages/ja.json b/src/i18n/messages/ja.jsonindex 79e3b6812b..7751671651 100644--- a/src/i18n/messages/ja.json+++ b/src/i18n/messages/ja.json@@ -270,7 +270,11 @@"overviewDescription": "すべてのプロバイダーとモデルにわたる API 使用パターン、トークン消費量、コスト、アクティビティの傾向を監視します。","evalsDescription": "評価スイートを実行して、LLM エンドポイントをテストおよび検証します。モデルの品質を比較し、回帰を検出し、待ち時間をベンチマークします。","overview": "概要",- "evals": "エヴァルス"+ "evals": "エヴァルス",+ "utilization": "活用率",+ "utilizationDescription": "プロバイダーのクォータ使用傾向とレート制限の追跡",+ "comboHealth": "コンボ健全性",+ "comboHealthDescription": "コンボレベルのクォータ、使用分布、パフォーマンスメトリクス"},"apiManager": {"title": "APIキー",diff --git a/src/i18n/messages/ko.json b/src/i18n/messages/ko.jsonindex db5170a86d..9a04b59aca 100644--- a/src/i18n/messages/ko.json+++ b/src/i18n/messages/ko.json@@ -270,7 +270,11 @@"overviewDescription": "모든 공급자와 모델 전반에 걸쳐 API 사용 패턴, 토큰 소비, 비용, 활동 추세를 모니터링하세요.","evalsDescription": "평가 모음을 실행하여 LLM 엔드포인트를 테스트하고 검증하세요. 모델 품질을 비교하고, 회귀를 감지하고, 벤치마크 대기 시간을 측정합니다.","overview": "개요",- "evals": "평가"+ "evals": "평가",+ "utilization": "활용률",+ "utilizationDescription": "공급자 할당량 사용 추세 및 속도 제한 추적",+ "comboHealth": "콤보 건강 상태",+ "comboHealthDescription": "콤보 수준 할당량, 사용 분포 및 성능 메트릭"},"apiManager": {"title": "API 키",diff --git a/src/i18n/messages/ms.json b/src/i18n/messages/ms.jsonindex 24f287bc42..cd51b5b03d 100644--- a/src/i18n/messages/ms.json+++ b/src/i18n/messages/ms.json@@ -270,7 +270,11 @@"overviewDescription": "Pantau corak penggunaan API anda, penggunaan token, kos dan aliran aktiviti merentas semua pembekal dan model.","evalsDescription": "Jalankan suite penilaian untuk menguji dan mengesahkan titik akhir LLM anda. Bandingkan kualiti model, mengesan regresi dan kependaman penanda aras.","overview": "Gambaran keseluruhan",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Pemanfaatan",+ "utilizationDescription": "Tren penggunaan kuota pembekal dan penjejakan had kadar",+ "comboHealth": "Kesihatan Combo",+ "comboHealthDescription": "Kuota peringkat combo, pengagihan penggunaan dan metrik prestasi"},"apiManager": {"title": "Kunci API",diff --git a/src/i18n/messages/nl.json b/src/i18n/messages/nl.jsonindex c06a00dbae..7b01bd55ab 100644--- a/src/i18n/messages/nl.json+++ b/src/i18n/messages/nl.json@@ -270,7 +270,11 @@"overviewDescription": "Houd toezicht op uw API-gebruikspatronen, tokenverbruik, kosten en activiteitstrends voor alle providers en modellen.","evalsDescription": "Voer evaluatiesuites uit om uw LLM-eindpunten te testen en te valideren. Vergelijk de modelkwaliteit, detecteer regressies en benchmark de latentie.","overview": "Overzicht",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Benutting",+ "utilizationDescription": "Trends in quotagebruik van de provider en bijhouden van snelheidslimieten",+ "comboHealth": "Combo-gezondheid",+ "comboHealthDescription": "Quota op combo-niveau, gebruiksdistributie en prestatiegegevens"},"apiManager": {"title": "API-sleutels",diff --git a/src/i18n/messages/no.json b/src/i18n/messages/no.jsonindex 272e394b6f..43e8c069c0 100644--- a/src/i18n/messages/no.json+++ b/src/i18n/messages/no.json@@ -270,7 +270,11 @@"overviewDescription": "Overvåk API-bruksmønstre, tokenforbruk, kostnader og aktivitetstrender på tvers av alle leverandører og modeller.","evalsDescription": "Kjør evalueringspakker for å teste og validere LLM-endepunktene dine. Sammenlign modellkvalitet, registrer regresjoner og benchmark latens.","overview": "Oversikt",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Utnyttelse",+ "utilizationDescription": "Leverandørkvotebrukstrender og hastighetsgrensesporing",+ "comboHealth": "Kombohelse",+ "comboHealthDescription": "Kombonivåkvote, bruksfordeling og ytelsesmålinger"},"apiManager": {"title": "API-nøkler",diff --git a/src/i18n/messages/phi.json b/src/i18n/messages/phi.jsonindex 65584d77a5..6afdda102b 100644--- a/src/i18n/messages/phi.json+++ b/src/i18n/messages/phi.json@@ -270,7 +270,11 @@"overviewDescription": "Subaybayan ang iyong mga pattern ng paggamit ng API, pagkonsumo ng token, gastos, at mga trend ng aktibidad sa lahat ng provider at modelo.","evalsDescription": "Magpatakbo ng mga evaluation suite para subukan at patunayan ang iyong mga LLM endpoint. Ihambing ang kalidad ng modelo, tuklasin ang mga regression, at benchmark na latency.","overview": "Pangkalahatang-ideya",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Paggamit",+ "utilizationDescription": "Mga trend sa paggamit ng quota ng provider at pagsubaybay sa rate limit",+ "comboHealth": "Kalusugan ng Combo",+ "comboHealthDescription": "Quota sa antas ng combo, pamamahagi ng paggamit, at mga metrics ng pagganap"},"apiManager": {"title": "Mga API Key",diff --git a/src/i18n/messages/pl.json b/src/i18n/messages/pl.jsonindex 0e0fede8f6..98772c2229 100644--- a/src/i18n/messages/pl.json+++ b/src/i18n/messages/pl.json@@ -270,7 +270,11 @@"overviewDescription": "Monitoruj wzorce wykorzystania interfejsu API, zużycie tokenów, koszty i trendy aktywności u wszystkich dostawców i modeli.","evalsDescription": "Uruchom pakiety ewaluacyjne, aby przetestować i zweryfikować punkty końcowe LLM. Porównaj jakość modelu, wykryj regresje i porównaj opóźnienia.","overview": "Przegląd",- "evals": "Ewaluacje"+ "evals": "Ewaluacje",+ "utilization": "Wykorzystanie",+ "utilizationDescription": "Trendy wykorzystania kwoty dostawcy i śledzenie limitów szybkości",+ "comboHealth": "Zdrowie Kombinacji",+ "comboHealthDescription": "Kwota na poziomie kombinacji, dystrybucja użycia i metryki wydajności"},"apiManager": {"title": "Klucze API",diff --git a/src/i18n/messages/pt-BR.json b/src/i18n/messages/pt-BR.jsonindex 5781280b71..3e507b645b 100644--- a/src/i18n/messages/pt-BR.json+++ b/src/i18n/messages/pt-BR.json@@ -270,7 +270,11 @@"overviewDescription": "Monitore padrões de uso da API, consumo de tokens, custos e tendências de atividade em todos os provedores e modelos.","evalsDescription": "Execute suítes de avaliação para testar e validar seus endpoints LLM. Compare qualidade de modelos, detecte regressões e faça benchmarks de latência.","overview": "Visão Geral",- "evals": "Avaliações"+ "evals": "Avaliações",+ "utilization": "Utilização",+ "utilizationDescription": "Tendências de uso de cota do provedor e rastreamento de limites de taxa",+ "comboHealth": "Saúde do Combo",+ "comboHealthDescription": "Cota em nível de combo, distribuição de uso e métricas de desempenho"},"apiManager": {"title": "Chaves de API",diff --git a/src/i18n/messages/pt.json b/src/i18n/messages/pt.jsonindex efc9de39c9..f66b0a9f1f 100644--- a/src/i18n/messages/pt.json+++ b/src/i18n/messages/pt.json@@ -270,7 +270,11 @@"overviewDescription": "Monitore seus padrões de uso de API, consumo de tokens, custos e tendências de atividades em todos os provedores e modelos.","evalsDescription": "Execute conjuntos de avaliação para testar e validar seus endpoints LLM. Compare a qualidade do modelo, detecte regressões e compare a latência.","overview": "Visão geral",- "evals": "Avaliações"+ "evals": "Avaliações",+ "utilization": "Utilização",+ "utilizationDescription": "Tendências de uso de quota do provedor e rastreamento de limites de taxa",+ "comboHealth": "Saúde do Combo",+ "comboHealthDescription": "Quota ao nível do combo, distribuição de uso e métricas de desempenho"},"apiManager": {"title": "Chaves de API",diff --git a/src/i18n/messages/ro.json b/src/i18n/messages/ro.jsonindex 766f6caa7a..bddd243b9d 100644--- a/src/i18n/messages/ro.json+++ b/src/i18n/messages/ro.json@@ -270,7 +270,11 @@"overviewDescription": "Monitorizați-vă modelele de utilizare a API-ului, consumul de simboluri, costurile și tendințele activității la toți furnizorii și modelele.","evalsDescription": "Rulați suite de evaluare pentru a testa și valida punctele finale LLM. Comparați calitatea modelului, detectați regresiile și evaluați latența.","overview": "Prezentare generală",- "evals": "Evaluări"+ "evals": "Evaluări",+ "utilization": "Utilizare",+ "utilizationDescription": "Tendințe de utilizare a cotelor furnizorului și urmărirea limitelor de rată",+ "comboHealth": "Sănătatea Combo-ului",+ "comboHealthDescription": "Cotă la nivel de combo, distribuția utilizării și metricile de performanță"},"apiManager": {"title": "Chei API",diff --git a/src/i18n/messages/ru.json b/src/i18n/messages/ru.jsonindex 98f99b3895..8384ec32ef 100644--- a/src/i18n/messages/ru.json+++ b/src/i18n/messages/ru.json@@ -270,7 +270,11 @@"overviewDescription": "Отслеживайте шаблоны использования API, потребление токенов, затраты и тенденции активности среди всех поставщиков и моделей.","evalsDescription": "Запустите оценочные пакеты для тестирования и проверки конечных точек LLM. Сравнивайте качество модели, обнаруживайте регрессии и измеряйте задержку тестирования.","overview": "Обзор",- "evals": "Оценки"+ "evals": "Оценки",+ "utilization": "Использование",+ "utilizationDescription": "Тенденции использования квоты поставщика и отслеживание ограничений скорости",+ "comboHealth": "Здоровье комбо",+ "comboHealthDescription": "Квота на уровне комбо, распределение использования и метрики производительности"},"apiManager": {"title": "API-ключи",diff --git a/src/i18n/messages/sk.json b/src/i18n/messages/sk.jsonindex 13eb240603..6fbc23249c 100644--- a/src/i18n/messages/sk.json+++ b/src/i18n/messages/sk.json@@ -270,7 +270,11 @@"overviewDescription": "Monitorujte svoje vzorce používania API, spotrebu tokenov, náklady a trendy aktivity u všetkých poskytovateľov a modelov.","evalsDescription": "Spustite vyhodnocovacie súpravy na testovanie a overovanie vašich koncových bodov LLM. Porovnajte kvalitu modelu, zistite regresie a benchmarkovú latenciu.","overview": "Prehľad",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Využitie",+ "utilizationDescription": "Trendy využitia kvót poskytovateľa a sledovanie limitov rýchlosti",+ "comboHealth": "Zdravie Combo",+ "comboHealthDescription": "Kvóta na úrovni combo, distribúcia používania a metríky výkonu"},"apiManager": {"title": "API kľúče",diff --git a/src/i18n/messages/sv.json b/src/i18n/messages/sv.jsonindex 6f314ff2a8..080d13384e 100644--- a/src/i18n/messages/sv.json+++ b/src/i18n/messages/sv.json@@ -270,7 +270,11 @@"overviewDescription": "Övervaka dina API-användningsmönster, tokenförbrukning, kostnader och aktivitetstrender för alla leverantörer och modeller.","evalsDescription": "Kör utvärderingssviter för att testa och validera dina LLM-slutpunkter. Jämför modellkvalitet, upptäck regressioner och benchmark latens.","overview": "Översikt",- "evals": "Evals"+ "evals": "Evals",+ "utilization": "Användning",+ "utilizationDescription": "Leverantörskvotanvändningstrender och hastighetsgränsuppföljning",+ "comboHealth": "Kombohälsa",+ "comboHealthDescription": "Kombonivåkvot, användningsfördelning och prestandamått"},"apiManager": {"title": "API-nycklar",diff --git a/src/i18n/messages/th.json b/src/i18n/messages/th.jsonindex 0248bfd746..a089c3a992 100644--- a/src/i18n/messages/th.json+++ b/src/i18n/messages/th.json@@ -270,7 +270,11 @@"overviewDescription": "ตรวจสอบรูปแบบการใช้งาน API การใช้โทเค็น ต้นทุน และแนวโน้มกิจกรรมของผู้ให้บริการและโมเดลทั้งหมด","evalsDescription": "เรียกใช้ชุดการประเมินผลเพื่อทดสอบและตรวจสอบความถูกต้องของตำแหน่งข้อมูล LLM ของคุณ เปรียบเทียบคุณภาพของโมเดล ตรวจจับการถดถอย และเวลาแฝงของเกณฑ์มาตรฐาน","overview": "ภาพรวม",- "evals": "เอวาลส์"+ "evals": "เอวาลส์",+ "utilization": "การใช้งาน",+ "utilizationDescription": "แนวโน้มการใช้โควต้าของผู้ให้บริการและการติดตามขีดจำกัดอัตรา",+ "comboHealth": "สุขภาพคอมโบ",+ "comboHealthDescription": "โควต้าระดับคอมโบ การกระจายการใช้งาน และตัวชั่งวัดประสิทธิภาพ"},"apiManager": {"title": "คีย์ API",diff --git a/src/i18n/messages/tr.json b/src/i18n/messages/tr.jsonindex 2c0d250334..129333f07a 100644--- a/src/i18n/messages/tr.json+++ b/src/i18n/messages/tr.json@@ -268,7 +268,11 @@"overviewDescription": "Tüm sağlayıcılar ve modeller genelinde API kullanım kalıplarınızı, jeton tüketiminizi, maliyetlerinizi ve etkinlik eğilimlerinizi izleyin.","evalsDescription": "LLM uç noktalarınızı test etmek ve doğrulamak için değerlendirme paketlerini çalıştırın. Model kalitesini karşılaştırın, regresyonları tespit edin ve gecikmeyi kıyaslayın.","overview": "Genel Bakış",- "evals": "Değerlendirmeler"+ "evals": "Değerlendirmeler",+ "utilization": "Kullanım",+ "utilizationDescription": "Sağlayıcı kota kullanım trendleri ve hız limiti takibi",+ "comboHealth": "Kombo Sağlığı",+ "comboHealthDescription": "Kombo düzeyinde kota, kullanım dağılımı ve performans metrikleri"},"apiManager": {"title": "API Anahtarları",diff --git a/src/i18n/messages/uk-UA.json b/src/i18n/messages/uk-UA.jsonindex a46c408b1d..80b0471122 100644--- a/src/i18n/messages/uk-UA.json+++ b/src/i18n/messages/uk-UA.json@@ -270,7 +270,11 @@"overviewDescription": "Відстежуйте шаблони використання API, споживання маркерів, витрати та тенденції активності в усіх постачальників і моделей.","evalsDescription": "Запустіть пакети оцінювання, щоб протестувати та перевірити кінцеві точки LLM. Порівняйте якість моделі, виявіть регресії та порівняйте затримку.","overview": "Огляд",- "evals": "Оцінки"+ "evals": "Оцінки",+ "utilization": "Використання",+ "utilizationDescription": "Тренди використання квоти постачальника та відстеження обмежень швидкості",+ "comboHealth": "Здоров'я комбінації",+ "comboHealthDescription": "Квота на рівні комбінації, розподіл використання та метрики продуктивності"},"apiManager": {"title": "Ключі API",diff --git a/src/i18n/messages/vi.json b/src/i18n/messages/vi.jsonindex a431e430f2..3ff2824bb5 100644--- a/src/i18n/messages/vi.json+++ b/src/i18n/messages/vi.json@@ -270,7 +270,11 @@"overviewDescription": "Giám sát mô hình sử dụng API, mức tiêu thụ mã thông báo, chi phí và xu hướng hoạt động của bạn trên tất cả các nhà cung cấp và mô hình.","evalsDescription": "Chạy bộ đánh giá để kiểm tra và xác thực điểm cuối LLM của bạn. So sánh chất lượng mô hình, phát hiện hồi quy và độ trễ điểm chuẩn.","overview": "Tổng quan",- "evals": "Đánh giá"+ "evals": "Đánh giá",+ "utilization": "Tỷ lệ sử dụng",+ "utilizationDescription": "Xu hướng sử dụng hạn ngạch nhà cung cấp và theo dõi giới hạn tốc độ",+ "comboHealth": "Sức khỏe Combo",+ "comboHealthDescription": "Hạn ngạch cấp combo, phân phối sử dụng và số liệu hiệu suất"},"apiManager": {"title": "Khóa API",diff --git a/src/i18n/messages/zh-CN.json b/src/i18n/messages/zh-CN.jsonindex 581bc9cabd..b1a0ea54ff 100644--- a/src/i18n/messages/zh-CN.json+++ b/src/i18n/messages/zh-CN.json@@ -275,7 +275,11 @@"overviewDescription": "监控所有提供商和模型的 API 使用模式、令牌消耗、成本和活动趋势。","evalsDescription": "运行评估套件来测试和验证您的 LLM 端点。比较模型质量、检测回归和基准延迟。","overview": "概述",- "evals": "评测"+ "evals": "评测",+ "utilization": "利用率",+ "utilizationDescription": "提供商配额使用趋势和速率限制跟踪",+ "comboHealth": "组合健康状况",+ "comboHealthDescription": "组合级别配额、使用分布和性能指标"},"apiManager": {"title": "API 密钥",diff --git a/src/lib/db/__tests__/quotaSnapshots.test.ts b/src/lib/db/__tests__/quotaSnapshots.test.tsnew file mode 100644index 0000000000..4da6140432--- /dev/null+++ b/src/lib/db/__tests__/quotaSnapshots.test.ts@@ -0,0 +1,590 @@+import { describe, it, expect, beforeEach, afterEach } from "vitest";+import Database from "better-sqlite3";+import { rowToCamel } from "../core";+import type { QuotaSnapshotRow } from "@/shared/types/utilization";++const MIGRATION_SQL = `+ CREATE TABLE IF NOT EXISTS quota_snapshots (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ provider TEXT NOT NULL,+ connection_id TEXT NOT NULL,+ window_key TEXT NOT NULL,+ remaining_percentage REAL,+ is_exhausted INTEGER DEFAULT 0,+ next_reset_at TEXT,+ window_duration_ms INTEGER,+ raw_data TEXT,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+ );+ CREATE INDEX IF NOT EXISTS idx_quota_snapshots_provider_time ON quota_snapshots(provider, created_at);+ CREATE INDEX IF NOT EXISTS idx_quota_snapshots_connection_time ON quota_snapshots(connection_id, created_at);+ CREATE INDEX IF NOT EXISTS idx_quota_snapshots_created_at ON quota_snapshots(created_at);+`;++interface StatementLike<TRow = unknown> {+ all: (...params: unknown[]) => TRow[];+ get: (...params: unknown[]) => TRow | undefined;+ run: (...params: unknown[]) => { changes: number };+}++interface DbLike {+ prepare: <TRow = unknown>(sql: string) => StatementLike<TRow>;+}++let lastCleanupAt = 0;++function saveQuotaSnapshotForTest(+ db: Database.Database,+ snapshot: Omit<QuotaSnapshotRow, "id" | "created_at">+): void {+ const now = new Date().toISOString();++ (db as unknown as DbLike)+ .prepare(+ `INSERT INTO quota_snapshots+ (provider, connection_id, window_key, remaining_percentage, is_exhausted,+ next_reset_at, window_duration_ms, raw_data, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`+ )+ .run(+ snapshot.provider,+ snapshot.connection_id,+ snapshot.window_key,+ snapshot.remaining_percentage,+ snapshot.is_exhausted,+ snapshot.next_reset_at,+ snapshot.window_duration_ms,+ snapshot.raw_data,+ now+ );+}++function getQuotaSnapshotsForTest(+ db: Database.Database,+ opts: {+ provider?: string;+ connectionId?: string;+ since: string;+ until?: string;+ }+): Array<{+ id: number;+ provider: string;+ connectionId: string;+ windowKey: string;+ remainingPercentage: number | null;+ isExhausted: number;+ nextResetAt: string | null;+ windowDurationMs: number | null;+ rawData: string | null;+ createdAt: string;+}> {+ const conditions: string[] = ["created_at >= ?"];+ const params: unknown[] = [opts.since];++ if (opts.provider) {+ conditions.push("provider = ?");+ params.push(opts.provider);+ }++ if (opts.connectionId) {+ conditions.push("connection_id = ?");+ params.push(opts.connectionId);+ }++ if (opts.until) {+ conditions.push("created_at <= ?");+ params.push(opts.until);+ }++ const sql = `SELECT * FROM quota_snapshots WHERE ${conditions.join(" AND ")} ORDER BY created_at ASC`;+ const rows = (db as unknown as DbLike).prepare(sql).all(...params);+ return rows.map(+ (r) =>+ rowToCamel(r) as unknown as {+ id: number;+ provider: string;+ connectionId: string;+ windowKey: string;+ remainingPercentage: number | null;+ isExhausted: number;+ nextResetAt: string | null;+ windowDurationMs: number | null;+ rawData: string | null;+ createdAt: string;+ }+ );+}++function getAggregatedSnapshotsForTest(+ db: Database.Database,+ opts: {+ provider?: string;+ since: string;+ until?: string;+ bucketMinutes: number;+ }+): Array<{+ timestamp: string;+ provider: string;+ remainingPct: number;+ isExhausted: boolean;+ windowKey: string;+}> {+ const conditions: string[] = ["created_at >= ?"];+ const params: unknown[] = [opts.since];++ if (opts.provider) {+ conditions.push("provider = ?");+ params.push(opts.provider);+ }++ if (opts.until) {+ conditions.push("created_at <= ?");+ params.push(opts.until);+ }++ const bucketSeconds = opts.bucketMinutes * 60;+ const sql = `+ SELECT+ datetime((strftime('%s', created_at) / ${bucketSeconds}) * ${bucketSeconds}, 'unixepoch') as bucket,+ provider,+ AVG(remaining_percentage) as remainingPct,+ MAX(is_exhausted) as isExhausted,+ window_key+ FROM quota_snapshots+ WHERE ${conditions.join(" AND ")}+ GROUP BY bucket, provider, window_key+ ORDER BY bucket ASC+ `;++ const rows = (db as unknown as DbLike).prepare(sql).all(...params) as Array<{+ bucket: string;+ provider: string;+ remainingPct: number | null;+ isExhausted: number;+ windowKey: string;+ }>;++ return rows.map((r) => ({+ timestamp: r.bucket,+ provider: r.provider,+ remainingPct: r.remainingPct ?? 0,+ isExhausted: r.isExhausted === 1,+ windowKey: r.windowKey,+ }));+}++function cleanupOldSnapshotsForTest(db: Database.Database, retentionDays = 90): number {+ const now = Date.now();+ const cleanupThresholdMs = 6 * 60 * 60 * 1000;++ if (now - lastCleanupAt < cleanupThresholdMs) {+ return 0;+ }++ const cutoffDate = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000).toISOString();+ const result = (db as unknown as DbLike)+ .prepare("DELETE FROM quota_snapshots WHERE created_at < ?")+ .run(cutoffDate);+ lastCleanupAt = now;++ return result.changes;+}++describe("quotaSnapshots DB module", () => {+ let testDb: Database.Database;++ beforeEach(() => {+ testDb = new Database(":memory:");+ testDb.pragma("journal_mode = WAL");+ testDb.exec(MIGRATION_SQL);+ lastCleanupAt = 0;+ });++ afterEach(() => {+ if (testDb) {+ testDb.close();+ }+ });++ describe("saveQuotaSnapshot", () => {+ it("should save a quota snapshot with all fields", () => {+ const snapshot = {+ provider: "codex",+ connection_id: "conn-123",+ window_key: "5h",+ remaining_percentage: 75.5,+ is_exhausted: 0,+ next_reset_at: "2024-01-15T10:00:00Z",+ window_duration_ms: 18000000,+ raw_data: null,+ };++ saveQuotaSnapshotForTest(testDb, snapshot);++ const rows = testDb+ .prepare("SELECT * FROM quota_snapshots ORDER BY id DESC LIMIT 1")+ .all() as QuotaSnapshotRow[];++ expect(rows).toHaveLength(1);+ expect(rows[0].provider).toBe("codex");+ expect(rows[0].connection_id).toBe("conn-123");+ expect(rows[0].window_key).toBe("5h");+ expect(rows[0].remaining_percentage).toBe(75.5);+ expect(rows[0].is_exhausted).toBe(0);+ });++ it("should save snapshot with null remaining_percentage", () => {+ const snapshot = {+ provider: "claude",+ connection_id: "conn-456",+ window_key: "weekly",+ remaining_percentage: null,+ is_exhausted: 1,+ next_reset_at: null,+ window_duration_ms: null,+ raw_data: null,+ };++ saveQuotaSnapshotForTest(testDb, snapshot);++ const rows = testDb+ .prepare("SELECT * FROM quota_snapshots WHERE provider = ?")+ .all("claude") as QuotaSnapshotRow[];++ expect(rows).toHaveLength(1);+ expect(rows[0].remaining_percentage).toBeNull();+ expect(rows[0].is_exhausted).toBe(1);+ });++ it("should save multiple snapshots for same provider", () => {+ const baseSnapshot = {+ provider: "test-provider",+ connection_id: "conn-789",+ window_key: "5h",+ remaining_percentage: 80,+ is_exhausted: 0,+ next_reset_at: null,+ window_duration_ms: null,+ raw_data: null,+ };++ saveQuotaSnapshotForTest(testDb, baseSnapshot);+ saveQuotaSnapshotForTest(testDb, { ...baseSnapshot, remaining_percentage: 60 });+ saveQuotaSnapshotForTest(testDb, { ...baseSnapshot, remaining_percentage: 40 });++ const rows = testDb+ .prepare("SELECT * FROM quota_snapshots WHERE provider = ?")+ .all("test-provider") as QuotaSnapshotRow[];++ expect(rows).toHaveLength(3);+ });+ });++ describe("getQuotaSnapshots", () => {+ beforeEach(() => {+ const now = new Date();+ const snapshots = [+ {+ provider: "codex",+ connection_id: "conn-1",+ window_key: "5h",+ remaining_percentage: 80,+ is_exhausted: 0,+ created_at: new Date(now.getTime() - 1000 * 60 * 30).toISOString(),+ },+ {+ provider: "codex",+ connection_id: "conn-1",+ window_key: "5h",+ remaining_percentage: 60,+ is_exhausted: 0,+ created_at: new Date(now.getTime() - 1000 * 60 * 10).toISOString(),+ },+ {+ provider: "claude",+ connection_id: "conn-2",+ window_key: "weekly",+ remaining_percentage: 90,+ is_exhausted: 0,+ created_at: new Date(now.getTime() - 1000 * 60 * 20).toISOString(),+ },+ {+ provider: "codex",+ connection_id: "conn-3",+ window_key: "5h",+ remaining_percentage: 30,+ is_exhausted: 1,+ created_at: new Date(now.getTime() - 1000 * 60 * 60 * 2).toISOString(),+ },+ ];++ for (const s of snapshots) {+ testDb+ .prepare(+ `INSERT INTO quota_snapshots+ (provider, connection_id, window_key, remaining_percentage, is_exhausted,+ next_reset_at, window_duration_ms, raw_data, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`+ )+ .run(+ s.provider,+ s.connection_id,+ s.window_key,+ s.remaining_percentage,+ s.is_exhausted,+ null,+ null,+ null,+ s.created_at+ );+ }+ });++ it("should get all snapshots since given time", () => {+ const since = new Date(Date.now() - 1000 * 60 * 60).toISOString();+ const results = getQuotaSnapshotsForTest(testDb, { since });++ expect(results.length).toBeGreaterThanOrEqual(3);+ });++ it("should filter by provider", () => {+ const since = new Date(Date.now() - 1000 * 60 * 60).toISOString();+ const results = getQuotaSnapshotsForTest(testDb, { provider: "codex", since });++ expect(results.length).toBeGreaterThanOrEqual(2);+ expect(results.every((r) => r.provider === "codex")).toBe(true);+ });++ it("should filter by connection_id", () => {+ const since = new Date(Date.now() - 1000 * 60 * 60 * 3).toISOString();+ const results = getQuotaSnapshotsForTest(testDb, { connectionId: "conn-2", since });++ expect(results).toHaveLength(1);+ expect(results[0].connectionId).toBe("conn-2");+ });++ it("should filter by time range with until", () => {+ const since = new Date(Date.now() - 1000 * 60 * 60 * 3).toISOString();+ const until = new Date(Date.now() - 1000 * 60 * 15).toISOString();+ const results = getQuotaSnapshotsForTest(testDb, { since, until });++ expect(results.length).toBeGreaterThanOrEqual(1);+ });++ it("should return empty array when no matches", () => {+ const since = new Date().toISOString();+ const results = getQuotaSnapshotsForTest(testDb, { since });++ expect(results).toHaveLength(0);+ });++ it("should return results ordered by created_at ASC", () => {+ const since = new Date(Date.now() - 1000 * 60 * 60 * 3).toISOString();+ const results = getQuotaSnapshotsForTest(testDb, { since });++ for (let i = 1; i < results.length; i++) {+ expect(new Date(results[i].createdAt) >= new Date(results[i - 1].createdAt)).toBe(true);+ }+ });+ });++ describe("getAggregatedSnapshots", () => {+ beforeEach(() => {+ const now = new Date();+ const snapshots = [+ {+ provider: "codex",+ connection_id: "conn-1",+ window_key: "5h",+ remaining_percentage: 80,+ is_exhausted: 0,+ created_at: new Date(now.getTime() - 1000 * 60 * 5).toISOString(),+ },+ {+ provider: "codex",+ connection_id: "conn-1",+ window_key: "5h",+ remaining_percentage: 70,+ is_exhausted: 0,+ created_at: new Date(now.getTime() - 1000 * 60 * 3).toISOString(),+ },+ {+ provider: "codex",+ connection_id: "conn-2",+ window_key: "5h",+ remaining_percentage: 60,+ is_exhausted: 0,+ created_at: new Date(now.getTime() - 1000 * 60 * 4).toISOString(),+ },+ {+ provider: "claude",+ connection_id: "conn-3",+ window_key: "weekly",+ remaining_percentage: 90,+ is_exhausted: 0,+ created_at: new Date(now.getTime() - 1000 * 60 * 2).toISOString(),+ },+ {+ provider: "codex",+ connection_id: "conn-1",+ window_key: "5h",+ remaining_percentage: 50,+ is_exhausted: 0,+ created_at: new Date(now.getTime() - 1000 * 60 * 15).toISOString(),+ },+ ];++ for (const s of snapshots) {+ testDb+ .prepare(+ `INSERT INTO quota_snapshots+ (provider, connection_id, window_key, remaining_percentage, is_exhausted,+ next_reset_at, window_duration_ms, raw_data, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`+ )+ .run(+ s.provider,+ s.connection_id,+ s.window_key,+ s.remaining_percentage,+ s.is_exhausted,+ null,+ null,+ null,+ s.created_at+ );+ }+ });++ it("should aggregate by time bucket", () => {+ const since = new Date(Date.now() - 1000 * 60 * 30).toISOString();+ const results = getAggregatedSnapshotsForTest(testDb, { since, bucketMinutes: 10 });++ expect(results.length).toBeGreaterThanOrEqual(1);+ });++ it("should calculate average remainingPct per bucket", () => {+ const since = new Date(Date.now() - 1000 * 60 * 30).toISOString();+ const results = getAggregatedSnapshotsForTest(testDb, { since, bucketMinutes: 10 });++ const codexResults = results.filter((r) => r.provider === "codex");+ expect(codexResults.length).toBeGreaterThanOrEqual(1);+ });++ it("should track isExhausted as boolean", () => {+ const since = new Date(Date.now() - 1000 * 60 * 30).toISOString();+ const results = getAggregatedSnapshotsForTest(testDb, { since, bucketMinutes: 10 });++ expect(results.every((r) => typeof r.isExhausted === "boolean")).toBe(true);+ });++ it("should filter by provider", () => {+ const since = new Date(Date.now() - 1000 * 60 * 30).toISOString();+ const results = getAggregatedSnapshotsForTest(testDb, {+ provider: "claude",+ since,+ bucketMinutes: 10,+ });++ expect(results.length).toBeGreaterThanOrEqual(1);+ expect(results.every((r) => r.provider === "claude")).toBe(true);+ });++ it("should respect until parameter", () => {+ const since = new Date(Date.now() - 1000 * 60 * 30).toISOString();+ const until = new Date(Date.now() - 1000 * 60 * 5).toISOString();+ const results = getAggregatedSnapshotsForTest(testDb, { since, until, bucketMinutes: 10 });++ expect(results.length).toBeGreaterThanOrEqual(1);+ });++ it("should return empty array when no data in range", () => {+ const since = new Date().toISOString();+ const results = getAggregatedSnapshotsForTest(testDb, { since, bucketMinutes: 10 });++ expect(results).toHaveLength(0);+ });+ });++ describe("cleanupOldSnapshots", () => {+ beforeEach(() => {+ const now = new Date();+ const oldDate = new Date(now.getTime() - 100 * 24 * 60 * 60 * 1000);+ const recentDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);++ const snapshots = [+ {+ provider: "codex",+ connection_id: "conn-1",+ window_key: "5h",+ remaining_percentage: 80,+ is_exhausted: 0,+ created_at: oldDate.toISOString(),+ },+ {+ provider: "codex",+ connection_id: "conn-1",+ window_key: "5h",+ remaining_percentage: 70,+ is_exhausted: 0,+ created_at: oldDate.toISOString(),+ },+ {+ provider: "claude",+ connection_id: "conn-2",+ window_key: "weekly",+ remaining_percentage: 90,+ is_exhausted: 0,+ created_at: recentDate.toISOString(),+ },+ ];++ for (const s of snapshots) {+ testDb+ .prepare(+ `INSERT INTO quota_snapshots+ (provider, connection_id, window_key, remaining_percentage, is_exhausted,+ next_reset_at, window_duration_ms, raw_data, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`+ )+ .run(+ s.provider,+ s.connection_id,+ s.window_key,+ s.remaining_percentage,+ s.is_exhausted,+ null,+ null,+ null,+ s.created_at+ );+ }+ lastCleanupAt = 0;+ });++ it("should delete snapshots older than retention days", () => {+ const deleted = cleanupOldSnapshotsForTest(testDb, 90);++ expect(deleted).toBe(2);++ const remaining = testDb.prepare("SELECT COUNT(*) as count FROM quota_snapshots").get() as {+ count: number;+ };+ expect(remaining.count).toBe(1);+ });++ it("should return 0 if no old snapshots to delete", () => {+ cleanupOldSnapshotsForTest(testDb, 90);+ const deleted = cleanupOldSnapshotsForTest(testDb, 90);++ expect(deleted).toBe(0);+ });++ it("should use default retention of 90 days", () => {+ const deleted = cleanupOldSnapshotsForTest(testDb);+ expect(deleted).toBe(2);+ });+ });+});diff --git a/src/lib/db/migrations/012_quota_snapshots.sql b/src/lib/db/migrations/012_quota_snapshots.sqlnew file mode 100644index 0000000000..d655405e26--- /dev/null+++ b/src/lib/db/migrations/012_quota_snapshots.sql@@ -0,0 +1,19 @@+-- 012_quota_snapshots.sql+-- Quota snapshots for subscription utilization tracking.+-- Stores periodic snapshots of quota state for historical analysis and time-series queries.++CREATE TABLE IF NOT EXISTS quota_snapshots (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ provider TEXT NOT NULL,+ connection_id TEXT NOT NULL,+ window_key TEXT NOT NULL,+ remaining_percentage REAL,+ is_exhausted INTEGER DEFAULT 0,+ next_reset_at TEXT,+ window_duration_ms INTEGER,+ raw_data TEXT,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+);+CREATE INDEX IF NOT EXISTS idx_quota_snapshots_provider_time ON quota_snapshots(provider, created_at);+CREATE INDEX IF NOT EXISTS idx_quota_snapshots_connection_time ON quota_snapshots(connection_id, created_at);+CREATE INDEX IF NOT EXISTS idx_quota_snapshots_created_at ON quota_snapshots(created_at);diff --git a/src/lib/db/quotaSnapshots.ts b/src/lib/db/quotaSnapshots.tsnew file mode 100644index 0000000000..09d0203e13--- /dev/null+++ b/src/lib/db/quotaSnapshots.ts@@ -0,0 +1,136 @@+import { getDbInstance, rowToCamel } from "./core";+import type { QuotaSnapshotRow, ProviderUtilizationPoint } from "@/shared/types/utilization";++type JsonRecord = Record<string, unknown>;++interface StatementLike<TRow = unknown> {+ all: (...params: unknown[]) => TRow[];+ get: (...params: unknown[]) => TRow | undefined;+ run: (...params: unknown[]) => { changes: number };+}++interface DbLike {+ prepare: <TRow = unknown>(sql: string) => StatementLike<TRow>;+}++let lastCleanupAt = 0;++export function saveQuotaSnapshot(snapshot: Omit<QuotaSnapshotRow, "id" | "created_at">): void {+ const db = getDbInstance() as unknown as DbLike;+ const now = new Date().toISOString();++ db.prepare(+ `INSERT INTO quota_snapshots+ (provider, connection_id, window_key, remaining_percentage, is_exhausted,+ next_reset_at, window_duration_ms, raw_data, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`+ ).run(+ snapshot.provider,+ snapshot.connection_id,+ snapshot.window_key,+ snapshot.remaining_percentage,+ snapshot.is_exhausted,+ snapshot.next_reset_at,+ snapshot.window_duration_ms,+ snapshot.raw_data,+ now+ );+}++export function getQuotaSnapshots(opts: {+ provider?: string;+ connectionId?: string;+ since: string;+ until?: string;+}): QuotaSnapshotRow[] {+ const db = getDbInstance() as unknown as DbLike;+ const conditions: string[] = ["created_at >= ?"];+ const params: unknown[] = [opts.since];++ if (opts.provider) {+ conditions.push("provider = ?");+ params.push(opts.provider);+ }++ if (opts.connectionId) {+ conditions.push("connection_id = ?");+ params.push(opts.connectionId);+ }++ if (opts.until) {+ conditions.push("created_at <= ?");+ params.push(opts.until);+ }++ const sql = `SELECT * FROM quota_snapshots WHERE ${conditions.join(" AND ")} ORDER BY created_at ASC`;+ const rows = db.prepare(sql).all(...params);+ return rows.map((r) => rowToCamel(r) as unknown as QuotaSnapshotRow);+}++export function getAggregatedSnapshots(opts: {+ provider?: string;+ since: string;+ until?: string;+ bucketMinutes: number;+}): ProviderUtilizationPoint[] {+ const db = getDbInstance() as unknown as DbLike;+ const conditions: string[] = ["created_at >= ?"];+ const params: unknown[] = [opts.since];++ if (opts.provider) {+ conditions.push("provider = ?");+ params.push(opts.provider);+ }++ if (opts.until) {+ conditions.push("created_at <= ?");+ params.push(opts.until);+ }++ const bucketSeconds = opts.bucketMinutes * 60;+ const sql = `+ SELECT+ datetime((strftime('%s', created_at) / ${bucketSeconds}) * ${bucketSeconds}, 'unixepoch') as bucket,+ provider,+ AVG(remaining_percentage) as remainingPct,+ MAX(is_exhausted) as isExhausted,+ window_key+ FROM quota_snapshots+ WHERE ${conditions.join(" AND ")}+ GROUP BY bucket, provider, window_key+ ORDER BY bucket ASC+ `;++ const rows = db.prepare(sql).all(...params) as Array<{+ bucket: string;+ provider: string;+ remainingPct: number | null;+ isExhausted: number;+ windowKey: string;+ }>;++ return rows.map((r) => ({+ timestamp: r.bucket,+ provider: r.provider,+ remainingPct: r.remainingPct ?? 0,+ isExhausted: r.isExhausted === 1,+ windowKey: r.windowKey,+ }));+}++export function cleanupOldSnapshots(retentionDays = 90): number {+ const now = Date.now();+ const cleanupThresholdMs = 6 * 60 * 60 * 1000;++ if (now - lastCleanupAt < cleanupThresholdMs) {+ return 0;+ }++ const db = getDbInstance() as unknown as DbLike;+ const cutoffDate = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000).toISOString();++ const result = db.prepare("DELETE FROM quota_snapshots WHERE created_at < ?").run(cutoffDate);+ lastCleanupAt = now;++ return result.changes;+}diff --git a/src/lib/localDb.ts b/src/lib/localDb.tsindex 17d89a776c..08abcd9155 100644--- a/src/lib/localDb.ts+++ b/src/lib/localDb.ts@@ -200,3 +200,12 @@ export {} from "./db/webhooks";export type { Webhook } from "./db/webhooks";++export {+ saveQuotaSnapshot,+ getQuotaSnapshots,+ getAggregatedSnapshots,+ cleanupOldSnapshots,+} from "./db/quotaSnapshots";++export type { QuotaSnapshotRow, ProviderUtilizationPoint } from "@/shared/types/utilization";diff --git a/src/shared/components/analytics/TimeRangeSelector.tsx b/src/shared/components/analytics/TimeRangeSelector.tsxnew file mode 100644index 0000000000..49588b3238--- /dev/null+++ b/src/shared/components/analytics/TimeRangeSelector.tsx@@ -0,0 +1,49 @@+"use client";++import { cn } from "@/shared/utils/cn";+import type { UtilizationTimeRange } from "@/shared/types/utilization";++interface TimeRangeSelectorProps {+ value: UtilizationTimeRange;+ onChange: (range: UtilizationTimeRange) => void;+}++const OPTIONS: Array<{ value: UtilizationTimeRange; label: string }> = [+ { value: "1h", label: "1h" },+ { value: "24h", label: "24h" },+ { value: "7d", label: "7d" },+ { value: "30d", label: "30d" },+];++export default function TimeRangeSelector({ value, onChange }: TimeRangeSelectorProps) {+ return (+ <div+ role="tablist"+ aria-label="시간 범위 선택"+ className="inline-flex items-center gap-1 rounded-lg bg-black/5 p-1 dark:bg-white/5"+ >+ {OPTIONS.map((option) => {+ const isActive = value === option.value;++ return (+ <button+ key={option.value}+ type="button"+ role="tab"+ aria-selected={isActive}+ tabIndex={isActive ? 0 : -1}+ onClick={() => onChange(option.value)}+ className={cn(+ "focus-ring h-9 rounded-md px-4 text-sm font-medium transition-all",+ isActive+ ? "bg-primary text-white shadow-sm hover:bg-primary-hover"+ : "text-text-muted hover:bg-black/5 hover:text-text-main dark:hover:bg-white/5"+ )}+ >+ {option.label}+ </button>+ );+ })}+ </div>+ );+}diff --git a/src/shared/types/utilization.ts b/src/shared/types/utilization.tsnew file mode 100644index 0000000000..60f37a0bea--- /dev/null+++ b/src/shared/types/utilization.ts@@ -0,0 +1,70 @@+export interface QuotaSnapshotRow {+ id: number;+ provider: string;+ connection_id: string;+ window_key: string;+ remaining_percentage: number | null;+ is_exhausted: number;+ next_reset_at: string | null;+ window_duration_ms: number | null;+ raw_data: string | null;+ created_at: string;+}++export interface ProviderUtilizationPoint {+ timestamp: string;+ provider: string;+ remainingPct: number;+ isExhausted: boolean;+ windowKey: string;+}++export interface ProviderUtilizationResponse {+ timeRange: "1h" | "24h" | "7d" | "30d";+ bucketSizeMinutes: number;+ providers: string[];+ data: ProviderUtilizationPoint[];+}++export interface ComboHealthMetrics {+ comboId: string;+ comboName: string;+ strategy: string;+ models: string[];+ quotaHealth: {+ providers: Array<{+ provider: string;+ remainingPct: number;+ isExhausted: boolean;+ trend: "improving" | "stable" | "declining";+ }>;+ worstRemainingPct: number;+ };+ usageSkew: {+ modelDistribution: Array<{+ model: string;+ requestShare: number;+ tokenShare: number;+ }>;+ giniCoefficient: number;+ };+ performance: {+ avgLatencyMs: number;+ successRate: number;+ totalRequests: number;+ };+}++export interface ComboHealthResponse {+ timeRange: "1h" | "24h" | "7d" | "30d";+ combos: ComboHealthMetrics[];+}++export type UtilizationTimeRange = "1h" | "24h" | "7d" | "30d";++export const BUCKET_SIZES: Record<UtilizationTimeRange, number> = {+ "1h": 1,+ "24h": 10,+ "7d": 60,+ "30d": 360,+};diff --git a/tests/e2e/analytics-tabs.spec.ts b/tests/e2e/analytics-tabs.spec.tsnew file mode 100644index 0000000000..dcd0fd4e6d--- /dev/null+++ b/tests/e2e/analytics-tabs.spec.ts@@ -0,0 +1,300 @@+import { test, expect } from "@playwright/test";++test.describe("Analytics Tabs UI", () => {+ test.beforeEach(async ({ page }) => {+ await page.route("**/api/usage/analytics", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ stats: {+ totalRequests: 1234,+ totalTokens: 567890,+ estimatedCost: 12.34,+ },+ charts: {},+ }),+ });+ });++ await page.route("**/api/usage/utilization**", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ timeRange: "24h",+ bucketSizeMinutes: 10,+ providers: ["codex", "claude", "gemini"],+ data: [+ {+ timestamp: new Date(Date.now() - 3600000).toISOString(),+ provider: "codex",+ remainingPct: 75.5,+ isExhausted: false,+ windowKey: "5h",+ },+ {+ timestamp: new Date().toISOString(),+ provider: "codex",+ remainingPct: 72.0,+ isExhausted: false,+ windowKey: "5h",+ },+ ],+ }),+ });+ });++ await page.route("**/api/usage/combo-health**", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ timeRange: "24h",+ combo: {+ id: "test-combo",+ name: "Test Combo",+ models: ["openai/gpt-4", "anthropic/claude-3"],+ },+ quotaHealth: {+ overall: {+ remainingAvg: 68.5,+ trend: "stable",+ },+ providers: [+ {+ provider: "openai",+ remaining: 75.0,+ trend: "stable",+ },+ ],+ },+ usageSkew: {+ modelDistribution: [+ { model: "openai/gpt-4", count: 45, share: 0.6 },+ { model: "anthropic/claude-3", count: 30, share: 0.4 },+ ],+ gini: 0.2,+ },+ performance: {+ successRate: 0.98,+ avgLatency: 1200,+ totalCalls: 75,+ },+ }),+ });+ });++ await page.route("**/api/combos", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ combos: [+ {+ id: "test-combo",+ name: "Test Combo",+ models: ["openai/gpt-4", "anthropic/claude-3"],+ strategy: "priority",+ isActive: true,+ },+ ],+ }),+ });+ });+ });++ test("displays all 5 analytics tabs", async ({ page }) => {+ await page.goto("/dashboard/analytics");+ await page.waitForLoadState("networkidle");++ const redirectedToLogin = page.url().includes("/login");+ test.skip(redirectedToLogin, "Authentication enabled without a login fixture.");++ const mainTabList = page.locator('[role="tablist"]').first();+ await expect(mainTabList).toBeVisible();++ const tabButtons = page.locator(+ 'button[class*="segmented"], [role="tablist"] > button, [role="tablist"] div > button'+ );+ const count = await tabButtons.count();+ expect(count).toBeGreaterThanOrEqual(4);++ const tabLabels = ["overview", "evals", "search", "utilization", "combo health"];+ for (const label of tabLabels) {+ const tabButton = page+ .locator("button")+ .filter({+ hasText: new RegExp(label, "i"),+ })+ .first();+ await expect(tabButton).toBeVisible();+ }+ });++ test("Provider Utilization tab shows TimeRangeSelector and chart", async ({ page }) => {+ await page.goto("/dashboard/analytics");+ await page.waitForLoadState("networkidle");++ const redirectedToLogin = page.url().includes("/login");+ test.skip(redirectedToLogin, "Authentication enabled without a login fixture.");++ const utilizationTab = page+ .locator("button")+ .filter({+ hasText: /utilization/i,+ })+ .first();+ await utilizationTab.click();++ await page.waitForTimeout(500);++ const timeRangeSelector = page+ .locator('[role="tablist"][aria-label]')+ .filter({ hasText: /1h/ })+ .first();+ await expect(timeRangeSelector).toBeVisible();++ const timeRangeButtons = timeRangeSelector.locator('button[role="tab"]');+ await expect(timeRangeButtons.first()).toBeVisible();++ const chart = page+ .locator('svg.recharts-surface, .recharts-wrapper, div[class*="recharts"]')+ .first();+ await expect(chart).toBeVisible();+ });++ test("Combo Health tab displays health cards and metrics", async ({ page }) => {+ await page.goto("/dashboard/analytics");+ await page.waitForLoadState("networkidle");++ const redirectedToLogin = page.url().includes("/login");+ test.skip(redirectedToLogin, "Authentication enabled without a login fixture.");++ const comboHealthTab = page+ .locator("button")+ .filter({+ hasText: /combo.*health/i,+ })+ .first();+ await comboHealthTab.click();++ await page.waitForTimeout(500);++ const mainContent = page.locator('main, [class*="dashboard"], div[class*="container"]').first();+ await expect(mainContent).toBeVisible();++ const timeRangeSelector = page.locator('[aria-label="시간 범위 선택"]');+ await expect(timeRangeSelector).toBeVisible();++ const metricElements = page+ .locator('[class*="rounded-lg"], [class*="border"], [class*="bg-black/"]')+ .first();+ await expect(metricElements).toBeVisible();+ });++ test("time range change triggers network request", async ({ page }) => {+ await page.goto("/dashboard/analytics");+ await page.waitForLoadState("networkidle");++ const redirectedToLogin = page.url().includes("/login");+ test.skip(redirectedToLogin, "Authentication enabled without a login fixture.");++ const utilizationTab = page+ .locator("button")+ .filter({+ hasText: /utilization/i,+ })+ .first();+ await utilizationTab.click();++ await page.waitForTimeout(500);++ let networkRequestMade = false;+ page.on("request", (request) => {+ if (request.url().includes("/api/usage/utilization")) {+ const url = new URL(request.url());+ if (url.searchParams.get("range") === "7d") {+ networkRequestMade = true;+ }+ }+ });++ const timeRangeSelector = page.locator('[aria-label="시간 범위 선택"]');+ const sevenDayButton = timeRangeSelector+ .locator('button[role="tab"]')+ .filter({ hasText: "7d" })+ .first();++ if (await sevenDayButton.isVisible()) {+ await sevenDayButton.click();+ } else {+ const buttons = timeRangeSelector.locator('button[role="tab"]');+ const count = await buttons.count();+ for (let i = 0; i < count; i++) {+ const button = buttons.nth(i);+ const text = await button.textContent();+ if (text?.includes("7")) {+ await button.click();+ break;+ }+ }+ }++ await page.waitForTimeout(1000);++ await expect+ .poll(() => networkRequestMade, {+ message: "Expected time range change to trigger network request",+ })+ .toBe(true);+ });++ test("tab switching persists state correctly", async ({ page }) => {+ await page.goto("/dashboard/analytics");+ await page.waitForLoadState("networkidle");++ const redirectedToLogin = page.url().includes("/login");+ test.skip(redirectedToLogin, "Authentication enabled without a login fixture.");++ const overviewTab = page+ .locator("button")+ .filter({+ hasText: /overview/i,+ })+ .first();+ await overviewTab.click();+ await page.waitForTimeout(300);++ const utilizationTab = page+ .locator("button")+ .filter({+ hasText: /utilization/i,+ })+ .first();+ await utilizationTab.click();+ await page.waitForTimeout(300);++ const chart = page+ .locator('svg.recharts-surface, .recharts-wrapper, div[class*="recharts"]')+ .first();+ await expect(chart).toBeVisible();++ const comboHealthTab = page+ .locator("button")+ .filter({+ hasText: /combo.*health/i,+ })+ .first();+ await comboHealthTab.click();+ await page.waitForTimeout(300);++ const timeRangeSelector = page.locator('[aria-label="시간 범위 선택"]');+ await expect(timeRangeSelector).toBeVisible();++ await utilizationTab.click();+ await page.waitForTimeout(300);++ await expect(chart).toBeVisible();+ });+});