feat: add priority/usage APIs, WebUI dashboard, config options

- PATCH /v0/management/auth/:id/priority endpoint
- GET /v0/management/auth/:id/usage endpoint
- AccountUsage.tsx dashboard component
- AutoRefreshBuffer, DailyResetHour config fields
- Conductor wiring for refresh config
This commit is contained in:
Finessse
2026-01-05 12:59:29 +07:00
parent 4dd917ff31
commit 093e77c8c0
11 changed files with 671 additions and 99 deletions
File diff suppressed because one or more lines are too long
+5
View File
@@ -115,6 +115,11 @@ ws-auth: false
# summarization-timeout-seconds: 30 # Default: 30. Timeout for LLM summarization calls.
# fallback-to-regex: true # Default: true. Use regex-based summary when LLM fails.
# Token refresh and usage tracking configuration.
# auto-refresh-buffer: 5m # Default: 5m. Refresh tokens this long before expiry.
# # Supports Go duration format: "5m", "10m", "1h", etc.
# daily-reset-hour: 0 # Default: 0 (midnight UTC). Hour (0-23, UTC) to reset daily usage stats.
# Token-aware compression (proactive trimming based on model context window).
# Prevents "prompt too long" errors by trimming before hitting model limits.
# Environment variables:
@@ -0,0 +1,50 @@
package management
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
type setAuthPriorityRequest struct {
Priority *int `json:"priority"`
}
// SetAuthPriority updates the priority field for an auth entry.
func (h *Handler) SetAuthPriority(c *gin.Context) {
authID := strings.TrimSpace(c.Param("id"))
if authID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing auth id"})
return
}
var req setAuthPriorityRequest
if err := c.ShouldBindJSON(&req); err != nil || req.Priority == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth manager unavailable"})
return
}
auth, ok := h.authManager.GetByID(authID)
if !ok || auth == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "auth not found"})
return
}
auth.Priority = *req.Priority
auth.UpdatedAt = time.Now()
updated, err := h.authManager.Update(c.Request.Context(), auth)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, h.buildAuthFileEntry(updated))
}
@@ -0,0 +1,34 @@
package management
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// GetAuthUsage returns usage statistics for a specific auth entry.
func (h *Handler) GetAuthUsage(c *gin.Context) {
authID := strings.TrimSpace(c.Param("id"))
if authID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing auth id"})
return
}
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth manager unavailable"})
return
}
auth, ok := h.authManager.GetByID(authID)
if !ok || auth == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "auth not found"})
return
}
c.JSON(http.StatusOK, gin.H{
"total_input_tokens": auth.Usage.TotalInputTokens,
"total_output_tokens": auth.Usage.TotalOutputTokens,
"request_count": auth.Usage.RequestCount,
"daily_input_tokens": auth.Usage.DailyInputTokens,
"daily_output_tokens": auth.Usage.DailyOutputTokens,
"daily_request_count": auth.Usage.DailyRequestCount,
})
}
+2
View File
@@ -627,6 +627,8 @@ func (s *Server) registerManagementRoutes() {
mgmt.GET("/auth-files/download", s.mgmt.DownloadAuthFile)
mgmt.POST("/auth-files", s.mgmt.UploadAuthFile)
mgmt.DELETE("/auth-files", s.mgmt.DeleteAuthFile)
mgmt.PATCH("/auth/:id/priority", s.mgmt.SetAuthPriority)
mgmt.GET("/auth/:id/usage", s.mgmt.GetAuthUsage)
mgmt.POST("/vertex/import", s.mgmt.ImportVertexCredential)
mgmt.GET("/anthropic-auth-url", s.mgmt.RequestAnthropicToken)
+42
View File
@@ -4,6 +4,8 @@
// debug settings, proxy configuration, and API keys.
package config
import "time"
// GlobalModelMapperFunc is a function type for looking up global model mappings.
// It takes a model name and provider hint, and returns the mapped model name (or empty string if no mapping).
type GlobalModelMapperFunc func(model string, provider string) string
@@ -33,6 +35,14 @@ type SDKConfig struct {
// Compression configures context compression behavior for long conversations.
Compression CompressionConfig `yaml:"compression,omitempty" json:"compression,omitempty"`
// AutoRefreshBuffer is the duration before token expiry at which automatic refresh is triggered.
// Default is 5 minutes. Example: "5m", "10m", "1h".
AutoRefreshBuffer string `yaml:"auto-refresh-buffer,omitempty" json:"auto-refresh-buffer,omitempty"`
// DailyResetHour is the hour (0-23, UTC) at which daily usage statistics are reset.
// Default is 0 (midnight UTC).
DailyResetHour *int `yaml:"daily-reset-hour,omitempty" json:"daily-reset-hour,omitempty"`
// GlobalModelMapper is an optional hook for looking up global model mappings.
// This is set by the parent Config to enable cross-provider model aliasing.
GlobalModelMapper GlobalModelMapperFunc `yaml:"-" json:"-"`
@@ -108,6 +118,12 @@ const (
// DefaultAccessProviderName is applied when no provider name is supplied.
DefaultAccessProviderName = "config-inline"
// DefaultAutoRefreshBuffer is the default duration before token expiry for auto-refresh.
DefaultAutoRefreshBuffer = 5 * time.Minute
// DefaultDailyResetHour is the default hour (UTC) for daily usage reset.
DefaultDailyResetHour = 0
)
// ConfigAPIKeyProvider returns the first inline API key provider if present.
@@ -190,3 +206,29 @@ func (cfg *SDKConfig) LookupGlobalModelMapping(model string, provider string) st
return cfg.GlobalModelMapper(model, provider)
}
// GetAutoRefreshBuffer parses and returns the auto-refresh buffer duration.
// Returns DefaultAutoRefreshBuffer if not set or invalid.
func (cfg *SDKConfig) GetAutoRefreshBuffer() time.Duration {
if cfg == nil || cfg.AutoRefreshBuffer == "" {
return DefaultAutoRefreshBuffer
}
d, err := time.ParseDuration(cfg.AutoRefreshBuffer)
if err != nil || d <= 0 {
return DefaultAutoRefreshBuffer
}
return d
}
// GetDailyResetHour returns the daily reset hour (0-23, UTC).
// Returns DefaultDailyResetHour if not set or out of range.
func (cfg *SDKConfig) GetDailyResetHour() int {
if cfg == nil || cfg.DailyResetHour == nil {
return DefaultDailyResetHour
}
h := *cfg.DailyResetHour
if h < 0 || h > 23 {
return DefaultDailyResetHour
}
return h
}
+70 -5
View File
@@ -115,6 +115,10 @@ type Manager struct {
requestRetry atomic.Int32
maxRetryInterval atomic.Int64
// Auto refresh configuration
autoRefreshBuffer atomic.Int64 // nanoseconds
dailyResetHour atomic.Int32
// Optional HTTP RoundTripper provider injected by host.
rtProvider RoundTripperProvider
@@ -181,6 +185,21 @@ func (m *Manager) SetRetryConfig(retry int, maxRetryInterval time.Duration) {
m.maxRetryInterval.Store(maxRetryInterval.Nanoseconds())
}
// SetRefreshConfig updates auto-refresh buffer and daily reset hour settings.
func (m *Manager) SetRefreshConfig(autoRefreshBuffer time.Duration, dailyResetHour int) {
if m == nil {
return
}
if autoRefreshBuffer <= 0 {
autoRefreshBuffer = 5 * time.Minute // default
}
if dailyResetHour < 0 || dailyResetHour > 23 {
dailyResetHour = 0 // default to midnight UTC
}
m.autoRefreshBuffer.Store(autoRefreshBuffer.Nanoseconds())
m.dailyResetHour.Store(int32(dailyResetHour))
}
// RegisterExecutor registers a provider executor with the manager.
func (m *Manager) RegisterExecutor(executor ProviderExecutor) {
if executor == nil {
@@ -941,12 +960,12 @@ func (m *Manager) MarkResult(ctx context.Context, result Result) {
auth.Usage.RequestCount++
auth.Usage.LastRequestAt = now
// Reset daily if new day
if time.Since(auth.Usage.DayStartedAt) > 24*time.Hour {
// Reset daily if past configured reset hour (default: midnight UTC)
if m.shouldResetDailyUsage(auth.Usage.DayStartedAt, now) {
auth.Usage.DailyInputTokens = 0
auth.Usage.DailyOutputTokens = 0
auth.Usage.DailyRequestCount = 0
auth.Usage.DayStartedAt = now.Truncate(24 * time.Hour)
auth.Usage.DayStartedAt = m.getDayStartTime(now)
}
auth.Usage.DailyInputTokens += result.Usage.InputTokens
auth.Usage.DailyOutputTokens += result.Usage.OutputTokens
@@ -1531,8 +1550,8 @@ func (m *Manager) shouldRefresh(a *Auth, now time.Time) bool {
return evaluator.ShouldRefresh(now, a)
}
// Check if token expires within buffer (5 minutes)
const refreshBuffer = 5 * time.Minute
// Check if token expires within buffer (configurable, default 5 minutes)
refreshBuffer := m.getAutoRefreshBuffer()
if !a.TokenExpiresAt.IsZero() && a.TokenExpiresAt.Sub(now) < refreshBuffer {
return true
}
@@ -1581,6 +1600,52 @@ func (m *Manager) shouldRefresh(a *Auth, now time.Time) bool {
return true
}
func (m *Manager) getAutoRefreshBuffer() time.Duration {
if m == nil {
return 5 * time.Minute
}
d := time.Duration(m.autoRefreshBuffer.Load())
if d <= 0 {
return 5 * time.Minute // default
}
return d
}
func (m *Manager) getDailyResetHour() int {
if m == nil {
return 0
}
h := int(m.dailyResetHour.Load())
if h < 0 || h > 23 {
return 0
}
return h
}
// shouldResetDailyUsage checks if daily usage stats should be reset based on configured reset hour.
func (m *Manager) shouldResetDailyUsage(dayStartedAt, now time.Time) bool {
if dayStartedAt.IsZero() {
return true
}
resetHour := m.getDailyResetHour()
// Calculate next reset time from dayStartedAt
nextReset := time.Date(dayStartedAt.Year(), dayStartedAt.Month(), dayStartedAt.Day(), resetHour, 0, 0, 0, time.UTC)
if !nextReset.After(dayStartedAt) {
nextReset = nextReset.Add(24 * time.Hour)
}
return now.After(nextReset) || now.Equal(nextReset)
}
// getDayStartTime returns the start time for the current usage day based on configured reset hour.
func (m *Manager) getDayStartTime(now time.Time) time.Time {
resetHour := m.getDailyResetHour()
dayStart := time.Date(now.Year(), now.Month(), now.Day(), resetHour, 0, 0, 0, time.UTC)
if dayStart.After(now) {
dayStart = dayStart.Add(-24 * time.Hour)
}
return dayStart
}
func authPreferredInterval(a *Auth) time.Duration {
if a == nil {
return 0
+62 -60
View File
@@ -1,60 +1,62 @@
// Package config provides the public SDK configuration API.
//
// It re-exports the server configuration types and helpers so external projects can
// embed CLIProxyAPI without importing internal packages.
package config
import internalconfig "github.com/router-for-me/CLIProxyAPI/v6/internal/config"
type SDKConfig = internalconfig.SDKConfig
type AccessConfig = internalconfig.AccessConfig
type AccessProvider = internalconfig.AccessProvider
type Config = internalconfig.Config
type StreamingConfig = internalconfig.StreamingConfig
type TLSConfig = internalconfig.TLSConfig
type RemoteManagement = internalconfig.RemoteManagement
type PayloadConfig = internalconfig.PayloadConfig
type PayloadRule = internalconfig.PayloadRule
type PayloadModelRule = internalconfig.PayloadModelRule
type GeminiKey = internalconfig.GeminiKey
type CodexKey = internalconfig.CodexKey
type ClaudeKey = internalconfig.ClaudeKey
type VertexCompatKey = internalconfig.VertexCompatKey
type VertexCompatModel = internalconfig.VertexCompatModel
type OpenAICompatibility = internalconfig.OpenAICompatibility
type OpenAICompatibilityAPIKey = internalconfig.OpenAICompatibilityAPIKey
type OpenAICompatibilityModel = internalconfig.OpenAICompatibilityModel
type GlobalModelMapping = internalconfig.GlobalModelMapping
type TLS = internalconfig.TLSConfig
const (
AccessProviderTypeConfigAPIKey = internalconfig.AccessProviderTypeConfigAPIKey
DefaultAccessProviderName = internalconfig.DefaultAccessProviderName
DefaultPanelGitHubRepository = internalconfig.DefaultPanelGitHubRepository
)
func MakeInlineAPIKeyProvider(keys []string) *AccessProvider {
return internalconfig.MakeInlineAPIKeyProvider(keys)
}
func LoadConfig(configFile string) (*Config, error) { return internalconfig.LoadConfig(configFile) }
func LoadConfigOptional(configFile string, optional bool) (*Config, error) {
return internalconfig.LoadConfigOptional(configFile, optional)
}
func SaveConfigPreserveComments(configFile string, cfg *Config) error {
return internalconfig.SaveConfigPreserveComments(configFile, cfg)
}
func SaveConfigPreserveCommentsUpdateNestedScalar(configFile string, path []string, value string) error {
return internalconfig.SaveConfigPreserveCommentsUpdateNestedScalar(configFile, path, value)
}
func NormalizeCommentIndentation(data []byte) []byte {
return internalconfig.NormalizeCommentIndentation(data)
}
// Package config provides the public SDK configuration API.
//
// It re-exports the server configuration types and helpers so external projects can
// embed CLIProxyAPI without importing internal packages.
package config
import internalconfig "github.com/router-for-me/CLIProxyAPI/v6/internal/config"
type SDKConfig = internalconfig.SDKConfig
type AccessConfig = internalconfig.AccessConfig
type AccessProvider = internalconfig.AccessProvider
type Config = internalconfig.Config
type StreamingConfig = internalconfig.StreamingConfig
type TLSConfig = internalconfig.TLSConfig
type RemoteManagement = internalconfig.RemoteManagement
type PayloadConfig = internalconfig.PayloadConfig
type PayloadRule = internalconfig.PayloadRule
type PayloadModelRule = internalconfig.PayloadModelRule
type GeminiKey = internalconfig.GeminiKey
type CodexKey = internalconfig.CodexKey
type ClaudeKey = internalconfig.ClaudeKey
type VertexCompatKey = internalconfig.VertexCompatKey
type VertexCompatModel = internalconfig.VertexCompatModel
type OpenAICompatibility = internalconfig.OpenAICompatibility
type OpenAICompatibilityAPIKey = internalconfig.OpenAICompatibilityAPIKey
type OpenAICompatibilityModel = internalconfig.OpenAICompatibilityModel
type GlobalModelMapping = internalconfig.GlobalModelMapping
type TLS = internalconfig.TLSConfig
const (
AccessProviderTypeConfigAPIKey = internalconfig.AccessProviderTypeConfigAPIKey
DefaultAccessProviderName = internalconfig.DefaultAccessProviderName
DefaultPanelGitHubRepository = internalconfig.DefaultPanelGitHubRepository
DefaultAutoRefreshBuffer = internalconfig.DefaultAutoRefreshBuffer
DefaultDailyResetHour = internalconfig.DefaultDailyResetHour
)
func MakeInlineAPIKeyProvider(keys []string) *AccessProvider {
return internalconfig.MakeInlineAPIKeyProvider(keys)
}
func LoadConfig(configFile string) (*Config, error) { return internalconfig.LoadConfig(configFile) }
func LoadConfigOptional(configFile string, optional bool) (*Config, error) {
return internalconfig.LoadConfigOptional(configFile, optional)
}
func SaveConfigPreserveComments(configFile string, cfg *Config) error {
return internalconfig.SaveConfigPreserveComments(configFile, cfg)
}
func SaveConfigPreserveCommentsUpdateNestedScalar(configFile string, path []string, value string) error {
return internalconfig.SaveConfigPreserveCommentsUpdateNestedScalar(configFile, path, value)
}
func NormalizeCommentIndentation(data []byte) []byte {
return internalconfig.NormalizeCommentIndentation(data)
}
+5 -1
View File
@@ -13,6 +13,7 @@ import {
ConfigEditor,
RequestMonitor,
UsageStats,
AccountUsage,
ThinkingBudgetSettings,
} from '@/components/dashboard'
import { Header } from '@/components/layout/Header'
@@ -133,7 +134,10 @@ function DashboardContent() {
return (
<div className="space-y-6">
{mgmtKey ? (
<UsageStats />
<>
<UsageStats />
<AccountUsage />
</>
) : (
<div className="rounded-xl border border-amber-500/30 bg-amber-500/10 p-4 text-sm text-amber-300">
Management key required to access analytics.
@@ -0,0 +1,367 @@
import { useEffect, useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useProxyContext } from '@/hooks/useProxyContext'
import { Loader2, Users, Zap, Activity, RefreshCw, Clock } from 'lucide-react'
import { cn } from '@/lib/utils'
interface AccountUsageData {
total_input_tokens: number
total_output_tokens: number
request_count: number
daily_input_tokens: number
daily_output_tokens: number
daily_request_count: number
day_started_at?: string
}
interface AuthFileInfo {
id: string
name: string
provider?: string
type?: string
email?: string
label?: string
status?: string
usage?: AccountUsageData
}
// Provider color mapping
const providerColors: Record<string, string> = {
claude: 'oklch(0.60 0.15 35)',
anthropic: 'oklch(0.60 0.15 35)',
gemini: 'oklch(0.55 0.18 250)',
'gemini-cli': 'oklch(0.58 0.16 240)',
codex: 'oklch(0.60 0.16 145)',
qwen: 'oklch(0.60 0.14 280)',
antigravity: 'oklch(0.65 0.20 320)',
kiro: 'oklch(0.58 0.17 200)',
amazonq: 'oklch(0.55 0.16 30)',
minimax: 'oklch(0.60 0.18 60)',
zhipu: 'oklch(0.55 0.15 180)',
}
function getProviderColor(provider: string): string {
const p = provider?.toLowerCase() || ''
for (const [key, color] of Object.entries(providerColors)) {
if (p.includes(key)) return color
}
return 'oklch(0.55 0.15 220)' // default blue
}
function formatTokens(n: number): string {
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`
return n.toString()
}
function formatTimeAgo(dateStr?: string): string {
if (!dateStr) return 'N/A'
const date = new Date(dateStr)
const now = new Date()
const diffMs = now.getTime() - date.getTime()
const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
const diffMins = Math.floor(diffMs / (1000 * 60))
if (diffHours >= 24) {
const days = Math.floor(diffHours / 24)
return `${days}d ago`
}
if (diffHours > 0) return `${diffHours}h ago`
if (diffMins > 0) return `${diffMins}m ago`
return 'just now'
}
interface AccountCardProps {
account: AuthFileInfo
maxTotalTokens: number
}
function AccountCard({ account, maxTotalTokens }: AccountCardProps) {
const usage = account.usage
const totalTokens = (usage?.total_input_tokens || 0) + (usage?.total_output_tokens || 0)
const dailyTokens = (usage?.daily_input_tokens || 0) + (usage?.daily_output_tokens || 0)
const color = getProviderColor(account.provider || account.type || '')
const barWidth = maxTotalTokens > 0 ? (totalTokens / maxTotalTokens) * 100 : 0
const displayName = account.email || account.label || account.name || account.id
const providerName = account.provider || account.type || 'unknown'
return (
<div
className={cn(
'relative p-4 rounded-lg border border-[var(--border-subtle)]',
'bg-[var(--bg-panel)] hover:border-transparent transition-all duration-200',
'group'
)}
style={{ ['--provider-color' as string]: color }}
>
{/* Hover glow */}
<div
className="absolute inset-0 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"
style={{
boxShadow: `0 0 20px color-mix(in oklch, ${color} 20%, transparent), inset 0 0 15px color-mix(in oklch, ${color} 5%, transparent)`,
}}
/>
{/* Hover border */}
<div
className="absolute inset-0 rounded-lg border-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none"
style={{ borderColor: color }}
/>
{/* Header */}
<div className="relative flex items-start justify-between mb-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span
className="inline-flex px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wider"
style={{
background: `color-mix(in oklch, ${color} 20%, transparent)`,
color: color,
}}
>
{providerName}
</span>
{account.status && (
<span
className={cn(
'inline-flex px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wider',
account.status === 'active' || account.status === 'ok'
? 'bg-[var(--status-online)]/15 text-[var(--status-online)]'
: 'bg-[var(--text-muted)]/15 text-[var(--text-muted)]'
)}
>
{account.status}
</span>
)}
</div>
<p className="text-sm font-medium text-[var(--text-primary)] truncate" title={displayName}>
{displayName}
</p>
</div>
</div>
{/* Stats Grid */}
<div className="relative grid grid-cols-2 gap-3 mb-3">
<div className="space-y-1">
<div className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--text-muted)]">
<Activity className="h-3 w-3" />
Requests
</div>
<div className="text-lg font-bold text-[var(--text-primary)]">
{usage?.request_count?.toLocaleString() || 0}
</div>
</div>
<div className="space-y-1">
<div className="flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--text-muted)]">
<Zap className="h-3 w-3" />
Total Tokens
</div>
<div className="text-lg font-bold text-[var(--text-primary)]">
{formatTokens(totalTokens)}
</div>
</div>
</div>
{/* Token Bar */}
<div className="relative mb-3">
<div className="flex justify-between text-[10px] text-[var(--text-muted)] mb-1">
<span>In: {formatTokens(usage?.total_input_tokens || 0)}</span>
<span>Out: {formatTokens(usage?.total_output_tokens || 0)}</span>
</div>
<div className="h-2 w-full rounded-full bg-[var(--bg-elevated)] overflow-hidden">
<div
className="h-full rounded-full transition-all duration-500"
style={{
width: `${Math.max(barWidth, 2)}%`,
background: `linear-gradient(90deg, ${color}, color-mix(in oklch, ${color} 70%, white))`,
boxShadow: `0 0 8px ${color}`,
}}
/>
</div>
</div>
{/* Daily Stats */}
<div className="relative border-t border-[var(--border-subtle)] pt-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1 text-[10px] text-[var(--text-muted)]">
<Clock className="h-3 w-3" />
Daily: {usage?.daily_request_count || 0} reqs, {formatTokens(dailyTokens)} tokens
</div>
<div className="text-[10px] text-[var(--text-muted)]">
Reset {formatTimeAgo(usage?.day_started_at)}
</div>
</div>
</div>
</div>
)
}
export function AccountUsage() {
const { mgmtFetch, status } = useProxyContext()
const [accounts, setAccounts] = useState<AuthFileInfo[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const isRunning = status?.running ?? false
const fetchData = async () => {
if (!isRunning) {
setAccounts([])
setLoading(false)
return
}
try {
const res = await mgmtFetch('/v0/management/auth-files')
const files = res.files || []
setAccounts(files)
setError(null)
} catch (e) {
console.error('Failed to fetch auth files:', e)
setError(e instanceof Error ? e.message : String(e))
} finally {
setLoading(false)
}
}
useEffect(() => {
fetchData()
const interval = setInterval(fetchData, 30000)
return () => clearInterval(interval)
}, [isRunning])
// Calculate max tokens for relative bar sizing
const maxTotalTokens = Math.max(
...accounts.map(a => (a.usage?.total_input_tokens || 0) + (a.usage?.total_output_tokens || 0)),
1
)
// Aggregate totals
const totals = accounts.reduce(
(acc, a) => ({
requests: acc.requests + (a.usage?.request_count || 0),
inputTokens: acc.inputTokens + (a.usage?.total_input_tokens || 0),
outputTokens: acc.outputTokens + (a.usage?.total_output_tokens || 0),
dailyRequests: acc.dailyRequests + (a.usage?.daily_request_count || 0),
}),
{ requests: 0, inputTokens: 0, outputTokens: 0, dailyRequests: 0 }
)
if (loading && accounts.length === 0) {
return (
<div className="flex h-64 items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
if (!isRunning) {
return (
<Card className="backdrop-blur-sm bg-card/60 border-border/50 shadow-xl">
<CardHeader>
<div className="flex items-center gap-2">
<Users className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-lg">Account Usage</CardTitle>
</div>
<CardDescription>Per-account usage statistics</CardDescription>
</CardHeader>
<CardContent>
<div className="p-4 rounded-lg border border-yellow-500/30 bg-yellow-500/5 text-yellow-500 text-xs text-center uppercase tracking-widest font-mono">
Start the proxy engine to view account usage
</div>
</CardContent>
</Card>
)
}
if (error && accounts.length === 0) {
return (
<div className="rounded-xl border border-red-500/30 bg-red-500/10 p-6 text-center">
<p className="text-red-300">Failed to load account usage</p>
<p className="mt-2 text-xs text-red-400/70">{error}</p>
</div>
)
}
if (accounts.length === 0) {
return (
<Card className="backdrop-blur-sm bg-card/60 border-border/50 shadow-xl">
<CardHeader>
<div className="flex items-center gap-2">
<Users className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-lg">Account Usage</CardTitle>
</div>
<CardDescription>Per-account usage statistics</CardDescription>
</CardHeader>
<CardContent>
<div className="py-8 text-center text-sm text-muted-foreground">
No accounts configured. Add providers in the Providers tab.
</div>
</CardContent>
</Card>
)
}
return (
<div className="space-y-6">
{/* Summary Card */}
<Card className="backdrop-blur-sm bg-card/60 border-border/50 shadow-xl">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Users className="h-4 w-4 text-muted-foreground" />
<CardTitle className="text-lg">Account Usage</CardTitle>
</div>
<button
onClick={() => { setLoading(true); fetchData() }}
className="p-1.5 rounded-md hover:bg-[var(--bg-elevated)] transition-colors"
title="Refresh"
>
<RefreshCw className={cn('h-4 w-4 text-[var(--text-muted)]', loading && 'animate-spin')} />
</button>
</div>
<CardDescription>
{accounts.length} account{accounts.length !== 1 ? 's' : ''} across all providers
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-4 md:grid-cols-4">
<div className="space-y-1">
<p className="text-xs text-[var(--text-muted)] uppercase tracking-wider">Total Requests</p>
<p className="text-2xl font-bold text-[var(--text-primary)]">
{totals.requests.toLocaleString()}
</p>
</div>
<div className="space-y-1">
<p className="text-xs text-[var(--text-muted)] uppercase tracking-wider">Input Tokens</p>
<p className="text-2xl font-bold text-[var(--text-primary)]">
{formatTokens(totals.inputTokens)}
</p>
</div>
<div className="space-y-1">
<p className="text-xs text-[var(--text-muted)] uppercase tracking-wider">Output Tokens</p>
<p className="text-2xl font-bold text-[var(--text-primary)]">
{formatTokens(totals.outputTokens)}
</p>
</div>
<div className="space-y-1">
<p className="text-xs text-[var(--text-muted)] uppercase tracking-wider">Today's Requests</p>
<p className="text-2xl font-bold text-[var(--text-primary)]">
{totals.dailyRequests.toLocaleString()}
</p>
</div>
</div>
</CardContent>
</Card>
{/* Account Grid */}
<div
className="grid gap-4"
style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))' }}
>
{accounts.map((account) => (
<AccountCard key={account.id} account={account} maxTotalTokens={maxTotalTokens} />
))}
</div>
</div>
)
}
+1
View File
@@ -8,6 +8,7 @@ export { SemanticMemory } from './SemanticMemory'
export { ConfigEditor } from './ConfigEditor'
export { RequestMonitor } from './RequestMonitor'
export { UsageStats } from './UsageStats'
export { AccountUsage } from './AccountUsage'
export { ThinkingBudgetSettings } from './ThinkingBudgetSettings'
export * from './Integrations'
export * from './AgentSetup'