feat: Implement provider groupings with account calculator and compre… (#113)

* feat: Implement provider groupings with account calculator and comprehensive fixes

- Add provider detection utilities (detectProvider, PROVIDER_REGISTRY) for Claude/Gemini/Others categorization
- Implement grouping logic (groupModelsByProvider, calculateProviderStats, calculateAccountStats) with health status calculation
- Create useProviderGrouping hook for collapsible state management and persistence
- Add ProviderGroup component with health indicators, progress bars, and model visibility integration
- Enhance CloudAccountList with account-level calculator showing overall percentage and earliest reset time
- Implement grid layout selector (auto/2-col/3-col/list) with config persistence and tooltips
- Add global quota aggregate bar across all accounts in top statistics
- Fix model visibility settings regression by accessing account.quota.models instead of account.quota
- Show 'Rate Limited' instead of '0%' for exhausted quotas with consistent getQuotaLabel function
- Add comprehensive i18n translations for layout selector and rate limited labels (en, zh-CN, ru)
- Disable batch operations when provider groupings are enabled to prevent conflicts
- Include unit tests for provider detection logic and grouping functionality

Addresses critical issues: model list regression, rate limited display, layout control, global quota visibility, and consistent quota labeling across all components.

* fix: resolve ESLint no-ex-assign violations in proxy service

- Fix exception parameter reassignment in catch blocks
- Rename catch parameters to avoid no-ex-assign rule violations
- Maintain same error handling logic while complying with linting rules

* fix: add missing Models tab to settings page

- Add Models tab between General and Proxy tabs
- Import and integrate ModelVisibilitySettings component
- Fix critical regression where model visibility settings were inaccessible

* fix: add missing React hook imports in settings route

* test: remove obsolete tests for removed controller APIs

---------

Co-authored-by: Draculabo <[email protected]>
This commit is contained in:
ArtemisAIandDraculabo authored and GitHub committed 2026-02-18 16:38:15 +08:00
1 parent 118fad567e
commit 1e59a1c901
12 files changed
+1237 -97

No files matched your search

+84 -10
View File
@@ -22,6 +22,9 @@ import { MoreVertical, Trash, RefreshCw, Box, Power, Fingerprint } from 'lucide-
import { formatDistanceToNow, differenceInMinutes, differenceInHours, isBefore } from 'date-fns';
import { Badge } from '@/components/ui/badge';
import { useTranslation } from 'react-i18next';
import { useAppConfig } from '@/hooks/useAppConfig';
import { useProviderGrouping } from '@/hooks/useProviderGrouping';
import { ProviderGroup } from '@/components/ProviderGroup';
interface CloudAccountCardProps {
account: CloudAccount;
@@ -49,6 +52,13 @@ export function CloudAccountCard({
isSwitching,
}: CloudAccountCardProps) {
const { t } = useTranslation();
const { config } = useAppConfig();
const {
enabled: providerGroupingsEnabled,
getAccountStats,
isProviderCollapsed,
toggleProviderCollapse,
} = useProviderGrouping();
// Helpers to get quota color
const getQuotaColor = (percentage: number) => {
@@ -71,6 +81,13 @@ export function CloudAccountCard({
return 'bg-rose-500';
};
const getQuotaLabel = (percentage: number) => {
if (percentage === 0) {
return t('cloud.card.rateLimitedQuota');
}
return `${percentage}%`;
};
const formatTimeRemaining = (dateStr: string) => {
const targetDate = new Date(dateStr);
if (Number.isNaN(targetDate.getTime())) {
@@ -120,17 +137,19 @@ export function CloudAccountCard({
return `${t('cloud.card.resetTime')}: ${resetDate.toLocaleString()}`;
};
const modelQuotas = Object.entries(account.quota?.models || {});
const modelQuotas = Object.entries(account.quota?.models || {}).filter(
([modelName]) => config?.model_visibility?.[modelName] !== false,
);
return (
<Card
className={`group flex h-full flex-col overflow-hidden border bg-card transition-all duration-200 hover:border-primary/40 hover:shadow-sm ${isSelected ? 'ring-primary border-primary/50 ring-2' : ''}`}
className={`group bg-card hover:border-primary/40 flex h-full flex-col overflow-hidden border transition-all duration-200 hover:shadow-sm ${isSelected ? 'ring-primary border-primary/50 ring-2' : ''}`}
>
<CardHeader className="relative flex flex-row items-center gap-4 space-y-0 pb-2">
{/* Selection Checkbox - Visible on hover or selected */}
{onToggleSelection && (
<div
className={`absolute top-2 left-2 z-10 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} rounded-full bg-background/90 p-2 transition-opacity`}
className={`absolute top-2 left-2 z-10 ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} bg-background/90 rounded-full p-2 transition-opacity`}
>
<Checkbox
checked={isSelected}
@@ -238,11 +257,64 @@ export function CloudAccountCard({
</div>
<div className="space-y-2">
{modelQuotas.length > 0 ? (
{providerGroupingsEnabled ? (
// Grouped view with provider sections
(() => {
const accountStats = getAccountStats(account);
if (accountStats.visibleModels === 0) {
return (
<div className="text-muted-foreground flex flex-col items-center justify-center py-4">
<Box className="mb-2 h-8 w-8 opacity-20" />
<span className="text-xs">{t('cloud.card.noQuota')}</span>
</div>
);
}
return (
<>
{/* Account-level overall stats */}
<div className="bg-muted/40 flex items-center justify-between rounded-lg px-3 py-1.5 text-xs">
<span className="font-medium">{t('settings.providerGroupings.overall')}</span>
<div className="flex items-center gap-2">
<span
className={`font-mono font-bold ${getQuotaColor(accountStats.overallPercentage)}`}
>
{getQuotaLabel(accountStats.overallPercentage)}
</span>
<div className="bg-muted h-1.5 w-16 overflow-hidden rounded-full">
<div
className={`h-full rounded-full transition-all duration-300 ${getQuotaBarColor(accountStats.overallPercentage)}`}
style={{
width: `${Math.max(0, Math.min(100, accountStats.overallPercentage))}%`,
}}
/>
</div>
</div>
</div>
{/* Provider groups */}
{accountStats.providers.map((providerStats) => (
<ProviderGroup
key={providerStats.providerKey}
stats={providerStats}
isCollapsed={isProviderCollapsed(account.id, providerStats.providerKey)}
onToggleCollapse={() =>
toggleProviderCollapse(account.id, providerStats.providerKey)
}
getQuotaColor={getQuotaColor}
getQuotaBarColor={getQuotaBarColor}
getQuotaLabel={getQuotaLabel}
getResetTimeLabel={getResetTimeLabel}
getResetTimeTitle={getResetTimeTitle}
leftLabel={t('cloud.card.left')}
/>
))}
</>
);
})()
) : modelQuotas.length > 0 ? (
modelQuotas.map(([modelName, info]) => (
<div
key={modelName}
className="hover:bg-muted/60 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3 rounded-lg border border-transparent px-2 py-2 text-sm transition-colors hover:border-border/60"
className="hover:bg-muted/60 hover:border-border/60 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3 rounded-lg border border-transparent px-2 py-2 text-sm transition-colors"
>
<span className="text-muted-foreground min-w-0 truncate" title={modelName}>
{modelName.replace('models/', '')}
@@ -254,15 +326,17 @@ export function CloudAccountCard({
>
{getResetTimeLabel(info.resetTime)}
</span>
<div className="flex items-baseline gap-1.5">
<div className="flex items-baseline gap-1.5">
<span
className={`font-mono leading-none font-bold ${getQuotaColor(info.percentage)}`}
>
{info.percentage}%
</span>
<span className="text-muted-foreground text-[10px]">
{t('cloud.card.left')}
{getQuotaLabel(info.percentage)}
</span>
{info.percentage > 0 && (
<span className="text-muted-foreground text-[10px]">
{t('cloud.card.left')}
</span>
)}
</div>
<div className="bg-muted h-1.5 w-24 overflow-hidden rounded-full">
<div
+175 -20
View File
@@ -27,6 +27,10 @@ import {
Trash2,
X,
RefreshCw,
LayoutGrid,
List,
Columns2,
Columns3,
} from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import {
@@ -40,15 +44,27 @@ import {
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useState, useEffect, useRef } from 'react';
import { useState, useEffect, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { getLocalizedErrorMessage } from '@/utils/errorMessages';
import { useAppConfig } from '@/hooks/useAppConfig';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
// ... (existing code: imports and comments)
export type GridLayout = 'auto' | '2-col' | '3-col' | 'list';
const GRID_LAYOUT_CLASSES: Record<GridLayout, string> = {
auto: 'grid gap-4 md:grid-cols-2 xl:grid-cols-3',
'2-col': 'grid gap-4 grid-cols-2',
'3-col': 'grid gap-4 grid-cols-3',
list: 'grid gap-4 grid-cols-1',
};
export function CloudAccountList() {
const { t } = useTranslation();
const { data: accounts, isLoading, isError, error, errorUpdatedAt, refetch } = useCloudAccounts();
const { config, saveConfig } = useAppConfig();
const refreshMutation = useRefreshQuota();
const deleteMutation = useDeleteCloudAccount();
const addMutation = useAddGoogleAccount();
@@ -62,6 +78,63 @@ export function CloudAccountList() {
const { toast } = useToast();
const lastCloudLoadErrorToastAt = useRef<number>(0);
const gridLayout: GridLayout = (config?.grid_layout as GridLayout) || 'auto';
const setGridLayout = async (layout: GridLayout) => {
if (config) {
await saveConfig({ ...config, grid_layout: layout });
}
};
// Calculate global quota across all accounts
const globalQuota = useMemo(() => {
if (!accounts || accounts.length === 0) {
return null;
}
const visibilitySettings = config?.model_visibility ?? {};
let totalPercentage = 0;
let modelCount = 0;
accounts.forEach((account) => {
if (!account.quota?.models) {
return;
}
Object.entries(account.quota.models).forEach(([modelName, info]) => {
if (visibilitySettings[modelName] !== false) {
totalPercentage += info.percentage;
modelCount++;
}
});
});
if (modelCount === 0) {
return null;
}
return Math.round((totalPercentage / modelCount) * 10) / 10;
}, [accounts, config?.model_visibility]);
const getGlobalQuotaColor = (percentage: number) => {
if (percentage > 80) {
return 'bg-emerald-500';
}
if (percentage > 20) {
return 'bg-amber-500';
}
return 'bg-rose-500';
};
const getGlobalQuotaTextColor = (percentage: number) => {
if (percentage > 80) {
return 'text-emerald-600 dark:text-emerald-400';
}
if (percentage > 20) {
return 'text-amber-600 dark:text-amber-400';
}
return 'text-rose-600 dark:text-rose-400';
};
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
const [authCode, setAuthCode] = useState('');
const [identityAccount, setIdentityAccount] = useState<CloudAccount | null>(null);
@@ -328,7 +401,7 @@ export function CloudAccountList() {
return (
<div className="space-y-5 pb-20">
<div className="rounded-lg border bg-card p-5">
<div className="bg-card rounded-lg border p-5">
<div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex shrink-0 flex-col gap-1">
<h2 className="text-2xl font-bold tracking-tight">{t('cloud.title')}</h2>
@@ -336,22 +409,49 @@ export function CloudAccountList() {
</div>
<div className="flex flex-wrap gap-2">
<div className="bg-muted/50 rounded-md border px-3 py-2">
<div className="text-muted-foreground text-[11px] uppercase">{t('cloud.card.actions')}</div>
<div className="text-muted-foreground text-[11px] uppercase">
{t('cloud.card.actions')}
</div>
<div className="text-base font-semibold">{totalAccounts}</div>
</div>
<div className="bg-muted/50 rounded-md border px-3 py-2">
<div className="text-muted-foreground text-[11px] uppercase">{t('cloud.card.active')}</div>
<div className="text-muted-foreground text-[11px] uppercase">
{t('cloud.card.active')}
</div>
<div className="text-base font-semibold text-emerald-600">{activeAccounts}</div>
</div>
<div className="bg-muted/50 rounded-md border px-3 py-2">
<div className="text-muted-foreground text-[11px] uppercase">{t('cloud.card.rateLimited')}</div>
<div className="text-muted-foreground text-[11px] uppercase">
{t('cloud.card.rateLimited')}
</div>
<div className="text-base font-semibold text-rose-600">{rateLimitedAccounts}</div>
</div>
{/* Global Quota */}
{globalQuota !== null && (
<div className="bg-muted/50 rounded-md border px-3 py-2">
<div className="text-muted-foreground text-[11px] uppercase">
{t('cloud.globalQuota')}
</div>
<div className="flex items-center gap-2">
<span
className={`text-base font-semibold ${getGlobalQuotaTextColor(globalQuota)}`}
>
{globalQuota}%
</span>
<div className="bg-muted h-2 w-20 overflow-hidden rounded-full">
<div
className={`h-full rounded-full transition-all duration-300 ${getGlobalQuotaColor(globalQuota)}`}
style={{ width: `${Math.max(0, Math.min(100, globalQuota))}%` }}
/>
</div>
</div>
</div>
)}
</div>
</div>
</div>
<div className="flex flex-wrap items-center gap-2 rounded-lg border bg-card p-3">
<div className="bg-card flex flex-wrap items-center gap-2 rounded-lg border p-3">
<div className="bg-muted/50 flex items-center gap-2 rounded-md border px-3 py-2">
<div className="flex items-center gap-2">
<Zap
@@ -369,7 +469,12 @@ export function CloudAccountList() {
/>
</div>
<Button variant="ghost" onClick={toggleSelectAll} title={t('cloud.batch.selectAll')} className="cursor-pointer">
<Button
variant="ghost"
onClick={toggleSelectAll}
title={t('cloud.batch.selectAll')}
className="cursor-pointer"
>
<CheckSquare
className={`mr-2 h-4 w-4 ${selectedIds.size > 0 && selectedIds.size === accounts?.length ? 'text-primary fill-primary/20' : ''}`}
/>
@@ -384,9 +489,7 @@ export function CloudAccountList() {
disabled={forcePollMutation.isPending}
className="cursor-pointer"
>
<RefreshCcw
className={`h-4 w-4 ${forcePollMutation.isPending ? 'animate-spin' : ''}`}
/>
<RefreshCcw className={`h-4 w-4 ${forcePollMutation.isPending ? 'animate-spin' : ''}`} />
</Button>
<Button
@@ -396,9 +499,7 @@ export function CloudAccountList() {
title={t('cloud.syncFromIDE')}
className="cursor-pointer"
>
<Download
className={`mr-2 h-4 w-4 ${syncMutation.isPending ? 'animate-bounce' : ''}`}
/>
<Download className={`mr-2 h-4 w-4 ${syncMutation.isPending ? 'animate-bounce' : ''}`} />
{t('cloud.syncFromIDE')}
</Button>
@@ -427,13 +528,9 @@ export function CloudAccountList() {
id="code"
placeholder={t('cloud.authDialog.placeholder')}
value={authCode}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setAuthCode(e.target.value)
}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setAuthCode(e.target.value)}
/>
<p className="text-muted-foreground text-xs">
{t('cloud.authDialog.instruction')}
</p>
<p className="text-muted-foreground text-xs">{t('cloud.authDialog.instruction')}</p>
</div>
</div>
<DialogFooter>
@@ -447,9 +544,67 @@ export function CloudAccountList() {
</DialogFooter>
</DialogContent>
</Dialog>
{/* Layout Selector */}
<div className="ml-auto flex items-center gap-1 rounded-md border p-1">
<TooltipProvider delayDuration={0}>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant={gridLayout === 'auto' ? 'secondary' : 'ghost'}
size="icon"
className="h-7 w-7 cursor-pointer"
onClick={() => setGridLayout('auto')}
>
<LayoutGrid className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('cloud.layout.auto')}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant={gridLayout === '2-col' ? 'secondary' : 'ghost'}
size="icon"
className="h-7 w-7 cursor-pointer"
onClick={() => setGridLayout('2-col')}
>
<Columns2 className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('cloud.layout.twoCol')}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant={gridLayout === '3-col' ? 'secondary' : 'ghost'}
size="icon"
className="h-7 w-7 cursor-pointer"
onClick={() => setGridLayout('3-col')}
>
<Columns3 className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('cloud.layout.threeCol')}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant={gridLayout === 'list' ? 'secondary' : 'ghost'}
size="icon"
className="h-7 w-7 cursor-pointer"
onClick={() => setGridLayout('list')}
>
<List className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('cloud.layout.list')}</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<div className={GRID_LAYOUT_CLASSES[gridLayout]}>
{accounts?.map((account) => (
<CloudAccountCard
key={account.id}
+211
View File
@@ -0,0 +1,211 @@
import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useAppConfig } from '@/hooks/useAppConfig';
import { useCloudAccounts } from '@/hooks/useCloudAccounts';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Loader2, Search, RotateCcw, Save } from 'lucide-react';
interface ModelVisibilitySettingsProps {}
export const ModelVisibilitySettings: React.FC<ModelVisibilitySettingsProps> = () => {
const { t } = useTranslation();
const { config, saveConfig } = useAppConfig();
const { data: accounts, isLoading: accountsLoading } = useCloudAccounts();
const [searchTerm, setSearchTerm] = useState('');
const [modelVisibility, setModelVisibility] = useState<Record<string, boolean>>({});
const [providerGroupingsEnabled, setProviderGroupingsEnabled] = useState(false);
const [isSaving, setIsSaving] = useState(false);
// Initialize model visibility and provider groupings from config
React.useEffect(() => {
if (config?.model_visibility) {
setModelVisibility(config.model_visibility);
}
if (config?.provider_groupings_enabled !== undefined) {
setProviderGroupingsEnabled(config.provider_groupings_enabled);
}
}, [config?.model_visibility, config?.provider_groupings_enabled]);
// Get all unique models from all accounts
const allModels = useMemo(() => {
if (!accounts) return [];
const modelSet = new Set<string>();
accounts.forEach((account) => {
if (account.quota?.models) {
Object.keys(account.quota.models).forEach((model) => {
modelSet.add(model);
});
}
});
return Array.from(modelSet).sort();
}, [accounts]);
// Filter models based on search term
const filteredModels = useMemo(() => {
return allModels.filter((model) => model.toLowerCase().includes(searchTerm.toLowerCase()));
}, [allModels, searchTerm]);
// Handle model visibility toggle
const handleModelToggle = (modelName: string, checked: boolean) => {
setModelVisibility((prev) => ({
...prev,
[modelName]: checked,
}));
};
// Reset to defaults (all models visible)
const handleReset = () => {
setModelVisibility({});
};
// Save configuration
const handleSave = async () => {
if (!config) return;
setIsSaving(true);
try {
await saveConfig({
...config,
model_visibility: modelVisibility,
provider_groupings_enabled: providerGroupingsEnabled,
});
} catch (error) {
console.error('Failed to save model visibility settings:', error);
} finally {
setIsSaving(false);
}
};
if (accountsLoading) {
return (
<Card>
<CardContent className="flex items-center justify-center p-6">
<Loader2 className="h-6 w-6 animate-spin" />
<span className="ml-2">{t('common.loading')}</span>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<span>{t('settings.modelVisibility.title')}</span>
<Badge variant="secondary">{filteredModels.length} models</Badge>
</CardTitle>
<CardDescription>{t('settings.modelVisibility.description')}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Search */}
<div className="relative">
<Search className="text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 transform" />
<Input
placeholder={t('settings.modelVisibility.searchPlaceholder')}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
{/* Provider Groupings Toggle */}
<div className="flex items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<Label htmlFor="provider-groupings" className="text-sm font-medium">
{t('settings.providerGroupings.enabled')}
</Label>
<p className="text-muted-foreground text-xs">
{t('settings.providerGroupings.description')}
</p>
</div>
<Switch
id="provider-groupings"
checked={providerGroupingsEnabled}
onCheckedChange={setProviderGroupingsEnabled}
/>
</div>
{/* Model List */}
<div className="max-h-96 space-y-2 overflow-y-auto rounded-lg border p-4">
{filteredModels.length === 0 ? (
<div className="text-muted-foreground py-8 text-center">
{searchTerm
? t('settings.modelVisibility.noModelsFound')
: t('settings.modelVisibility.noModels')}
</div>
) : (
filteredModels.map((modelName) => {
const isVisible = modelVisibility[modelName] !== false; // Default to true
return (
<div
key={modelName}
className="hover:bg-muted/50 flex items-center space-x-3 rounded p-2"
>
<Checkbox
id={`model-${modelName}`}
checked={isVisible}
onCheckedChange={(checked) => handleModelToggle(modelName, checked as boolean)}
/>
<label
htmlFor={`model-${modelName}`}
className="flex-1 cursor-pointer text-sm font-medium"
>
{modelName}
</label>
{!isVisible && (
<Badge variant="secondary" className="text-xs">
{t('settings.modelVisibility.hidden')}
</Badge>
)}
</div>
);
})
)}
</div>
{/* Action Buttons */}
<div className="flex gap-2 pt-4">
<Button
variant="outline"
onClick={handleReset}
disabled={Object.keys(modelVisibility).length === 0}
className="flex items-center gap-2"
>
<RotateCcw className="h-4 w-4" />
{t('settings.modelVisibility.reset')}
</Button>
<Button onClick={handleSave} disabled={isSaving} className="flex items-center gap-2">
{isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
{isSaving ? t('settings.modelVisibility.saving') : t('settings.modelVisibility.save')}
</Button>
</div>
{/* Statistics */}
<div className="text-muted-foreground border-t pt-2 text-sm">
<div className="flex justify-between">
<span>
{t('settings.modelVisibility.totalModels')}: {allModels.length}
</span>
<span>
{t('settings.modelVisibility.visibleModels')}:{' '}
{allModels.length - Object.values(modelVisibility).filter((v) => !v).length}
</span>
<span>
{t('settings.modelVisibility.hiddenModels')}:{' '}
{Object.values(modelVisibility).filter((v) => !v).length}
</span>
</div>
</div>
</CardContent>
</Card>
);
};
+139
View File
@@ -0,0 +1,139 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronRight } from 'lucide-react';
import type { ProviderStats } from '@/utils/provider-grouping';
interface ProviderGroupProps {
stats: ProviderStats;
isCollapsed: boolean;
onToggleCollapse: () => void;
getQuotaColor: (percentage: number) => string;
getQuotaBarColor: (percentage: number) => string;
getQuotaLabel: (percentage: number) => string;
getResetTimeLabel: (resetTime?: string) => string;
getResetTimeTitle: (resetTime?: string) => string | undefined;
leftLabel: string;
}
export const ProviderGroup: React.FC<ProviderGroupProps> = ({
stats,
isCollapsed,
onToggleCollapse,
getQuotaColor,
getQuotaBarColor,
getQuotaLabel,
getResetTimeLabel,
getResetTimeTitle,
leftLabel,
}) => {
const { t } = useTranslation();
const { providerInfo, visibleModels, avgPercentage, earliestReset } = stats;
if (visibleModels.length === 0) {
return null;
}
return (
<div className="border-border/60 overflow-hidden rounded-lg border">
{/* Provider Header */}
<button
type="button"
onClick={onToggleCollapse}
className="hover:bg-muted/60 flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-sm transition-colors"
>
{isCollapsed ? (
<ChevronRight className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
) : (
<ChevronDown className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
)}
{/* Provider color dot */}
<span
className="inline-block h-2.5 w-2.5 shrink-0 rounded-full"
style={{ backgroundColor: providerInfo.color }}
/>
<span className="font-medium">{providerInfo.name}</span>
<span className="text-muted-foreground text-xs">
{t('settings.providerGroupings.models', { count: visibleModels.length })}
</span>
{/* Spacer */}
<div className="flex-1" />
{/* Averaged metrics */}
<div className="flex items-center gap-2">
{earliestReset && (
<span
className="text-muted-foreground text-[10px]"
title={getResetTimeTitle(earliestReset)}
>
{getResetTimeLabel(earliestReset)}
</span>
)}
<div className="flex items-baseline gap-1">
<span className={`font-mono text-xs font-bold ${getQuotaColor(avgPercentage)}`}>
{getQuotaLabel(avgPercentage)}
</span>
{avgPercentage > 0 && (
<span className="text-muted-foreground text-[10px]">
{t('settings.providerGroupings.avgLabel')}
</span>
)}
</div>
<div className="bg-muted h-1.5 w-16 overflow-hidden rounded-full">
<div
className={`h-full rounded-full transition-all duration-300 ${getQuotaBarColor(avgPercentage)}`}
style={{ width: `${Math.max(0, Math.min(100, avgPercentage))}%` }}
/>
</div>
</div>
</button>
{/* Individual model rows (shown when expanded) */}
{!isCollapsed && (
<div className="border-border/40 border-t">
{visibleModels.map((model, index) => (
<div
key={model.id}
className={`hover:bg-muted/60 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3 px-3 py-2 pl-9 text-sm transition-colors ${
index < visibleModels.length - 1 ? 'border-border/20 border-b' : ''
}`}
>
<span className="text-muted-foreground min-w-0 truncate" title={model.id}>
{model.id.replace('models/', '')}
</span>
<div className="flex flex-col items-end gap-1">
<span
className="text-muted-foreground text-[10px] leading-none"
title={getResetTimeTitle(model.resetTime)}
>
{getResetTimeLabel(model.resetTime)}
</span>
<div className="flex items-baseline gap-1.5">
<span
className={`font-mono leading-none font-bold ${getQuotaColor(model.percentage)}`}
>
{getQuotaLabel(model.percentage)}
</span>
{model.percentage > 0 && (
<span className="text-muted-foreground text-[10px]">{leftLabel}</span>
)}
</div>
<div className="bg-muted h-1.5 w-24 overflow-hidden rounded-full">
<div
className={`h-full rounded-full transition-all duration-300 ${getQuotaBarColor(model.percentage)}`}
style={{ width: `${Math.max(0, Math.min(100, model.percentage))}%` }}
/>
</div>
</div>
</div>
))}
</div>
)}
</div>
);
};