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>
);
};
+86
View File
@@ -0,0 +1,86 @@
import { useState, useMemo, useCallback } from 'react';
import { useAppConfig } from '@/hooks/useAppConfig';
import { CloudAccount } from '@/types/cloudAccount';
import { groupModelsByProvider, type AccountStats } from '@/utils/provider-grouping';
export interface UseProviderGroupingResult {
enabled: boolean;
getAccountStats: (account: CloudAccount) => AccountStats;
isProviderCollapsed: (accountId: string, providerKey: string) => boolean;
toggleProviderCollapse: (accountId: string, providerKey: string) => void;
isAccountCollapsed: (accountId: string) => boolean;
toggleAccountCollapse: (accountId: string) => void;
}
export function useProviderGrouping(): UseProviderGroupingResult {
const { config } = useAppConfig();
// Collapse state is managed locally per session for responsive toggling.
// Provider groups default to expanded on each page load.
const [collapsedProviders, setCollapsedProviders] = useState<Record<string, string[]>>({});
const [collapsedAccounts, setCollapsedAccounts] = useState<string[]>([]);
const enabled = config?.provider_groupings_enabled ?? false;
const visibilitySettings = config?.model_visibility ?? {};
const getAccountStats = useCallback(
(account: CloudAccount): AccountStats => {
const models = account.quota?.models ?? {};
return groupModelsByProvider(models, visibilitySettings);
},
[visibilitySettings],
);
const isProviderCollapsed = useCallback(
(accountId: string, providerKey: string): boolean => {
return collapsedProviders[accountId]?.includes(providerKey) ?? false;
},
[collapsedProviders],
);
const toggleProviderCollapse = useCallback((accountId: string, providerKey: string): void => {
setCollapsedProviders((prev) => {
const accountCollapsed = prev[accountId] ?? [];
const isCollapsed = accountCollapsed.includes(providerKey);
return {
...prev,
[accountId]: isCollapsed
? accountCollapsed.filter((k) => k !== providerKey)
: [...accountCollapsed, providerKey],
};
});
}, []);
const isAccountCollapsed = useCallback(
(accountId: string): boolean => {
return collapsedAccounts.includes(accountId);
},
[collapsedAccounts],
);
const toggleAccountCollapse = useCallback((accountId: string): void => {
setCollapsedAccounts((prev) =>
prev.includes(accountId) ? prev.filter((id) => id !== accountId) : [...prev, accountId],
);
}, []);
return useMemo(
() => ({
enabled,
getAccountStats,
isProviderCollapsed,
toggleProviderCollapse,
isAccountCollapsed,
toggleAccountCollapse,
}),
[
enabled,
getAccountStats,
isProviderCollapsed,
toggleProviderCollapse,
isAccountCollapsed,
toggleAccountCollapse,
],
);
}
+122
View File
@@ -138,6 +138,38 @@ i18n
default: 'Default',
restoreDefaults: 'Restore Defaults',
},
modelVisibility: {
title: 'Model Visibility',
description:
"Control which models are visible in account cards. Hidden models won't appear in the quota display.",
searchPlaceholder: 'Search models...',
showAll: 'Show All',
hideAll: 'Hide All',
reset: 'Reset to Defaults',
save: 'Save Changes',
noModels: 'No models found',
modelsShown: '{{visible}} of {{total}} models visible',
quotaManagement: 'Quota Management',
hidden: 'Hidden',
noModelsFound: 'No models found',
totalModels: 'Total',
visibleModels: 'Visible',
hiddenModels: 'Hidden',
saving: 'Saving...',
},
providerGroupings: {
title: 'Provider Groupings',
description: 'Group models by provider for better organization',
enabled: 'Enable Provider Groupings',
models: '{{count}} models',
avgLabel: 'avg',
resetLabel: 'reset',
overall: 'Overall',
healthy: 'Healthy',
degraded: 'Degraded',
limited: 'Limited',
critical: 'Critical',
},
examples: {
title: 'Usage Examples',
@@ -215,10 +247,18 @@ i18n
title: 'Accounts',
description: 'Manage your Google Gemini account pool.',
autoSwitch: 'Auto-Switch',
providerGroupings: 'Provider Groupings',
addAccount: 'Add Account',
syncFromIDE: 'Sync from IDE',
checkQuota: 'Check Quota Now',
polling: 'Polling triggered',
globalQuota: 'Global Quota',
layout: {
auto: 'Auto',
twoCol: '2 Columns',
threeCol: '3 Columns',
list: 'List',
},
authDialog: {
title: 'Add Google Account',
description: 'To add an account, you need to authorize the application.',
@@ -242,6 +282,7 @@ i18n
refresh: 'Refresh Quota',
delete: 'Delete Account',
noQuota: 'No quota data',
rateLimitedQuota: 'Rate Limited',
resetPrefix: 'reset',
resetTime: 'Reset time',
resetUnknown: 'Unknown',
@@ -480,6 +521,37 @@ i18n
default: '默认',
restoreDefaults: '恢复默认配置',
},
modelVisibility: {
title: '模型可见性',
description: '控制哪些模型在账号卡片中可见。隐藏的模型不会在配额显示中出现。',
searchPlaceholder: '搜索模型...',
showAll: '显示全部',
hideAll: '隐藏全部',
reset: '重置为默认',
save: '保存更改',
noModels: '未找到模型',
modelsShown: '{{visible}} / {{total}} 个模型可见',
quotaManagement: '配额管理',
hidden: '已隐藏',
noModelsFound: '未找到模型',
totalModels: '总数',
visibleModels: '可见',
hiddenModels: '隐藏',
saving: '保存中...',
},
providerGroupings: {
title: '模型分组',
description: '按供应商分组模型以便更好地管理',
enabled: '启用供应商分组',
models: '{{count}} 个模型',
avgLabel: '平均',
resetLabel: '重置',
overall: '总览',
healthy: '正常',
degraded: '降级',
limited: '受限',
critical: '严重',
},
examples: {
title: '使用示例',
@@ -556,10 +628,18 @@ i18n
title: '账号列表',
description: '管理您的 Google Gemini 账号池。',
autoSwitch: '自动切换',
providerGroupings: '提供商分组',
addAccount: '添加账号',
syncFromIDE: '从 IDE 同步',
checkQuota: '立即检查配额',
polling: '已触发轮询',
globalQuota: '全局配额',
layout: {
auto: '自动',
twoCol: '2 列',
threeCol: '3 列',
list: '列表',
},
authDialog: {
title: '添加 Google 账号',
description: '添加账号需要进行应用授权。',
@@ -582,6 +662,7 @@ i18n
refresh: '刷新配额',
delete: '删除账号',
noQuota: '无配额数据',
rateLimitedQuota: '已达限额',
resetPrefix: '重置',
resetTime: '重置时间',
resetUnknown: '未知',
@@ -822,6 +903,38 @@ i18n
default: 'По умолчанию',
restoreDefaults: 'Сбросить по умолчанию',
},
modelVisibility: {
title: 'Видимость моделей',
description:
'Управляйте тем, какие модели отображаются в карточках аккаунтов. Скрытые модели не будут показаны в отображении квот.',
searchPlaceholder: 'Поиск моделей...',
showAll: 'Показать все',
hideAll: 'Скрыть все',
reset: 'Сбросить по умолчанию',
save: 'Сохранить изменения',
noModels: 'Модели не найдены',
modelsShown: '{{visible}} из {{total}} моделей видно',
quotaManagement: 'Управление квотами',
hidden: 'Скрыто',
noModelsFound: 'Модели не найдены',
totalModels: 'Всего',
visibleModels: 'Видно',
hiddenModels: 'Скрыто',
saving: 'Сохранение...',
},
providerGroupings: {
title: 'Группировка провайдеров',
description: 'Группировка моделей по провайдерам для лучшей организации',
enabled: 'Включить группировку провайдеров',
models: '{{count}} моделей',
avgLabel: 'сред.',
resetLabel: 'сброс',
overall: 'Общее',
healthy: 'Исправно',
degraded: 'Снижено',
limited: 'Ограничено',
critical: 'Критично',
},
examples: {
title: 'Примеры использования',
description: 'Примеры команд для вызова локального API прокси.',
@@ -898,10 +1011,18 @@ i18n
title: 'Аккаунты',
description: 'Управление пулом аккаунтов Google Gemini.',
autoSwitch: 'Авто-переключение',
providerGroupings: 'Группировка по провайдерам',
addAccount: 'Добавить аккаунт',
syncFromIDE: 'Синхр. из IDE',
checkQuota: 'Проверить квоту',
polling: 'Опрос запущен',
globalQuota: 'Глобальная квота',
layout: {
auto: 'Авто',
twoCol: '2 колонки',
threeCol: '3 колонки',
list: 'Список',
},
authDialog: {
title: 'Добавить Google Аккаунт',
description: 'Для добавления аккаунта необходимо авторизовать приложение.',
@@ -925,6 +1046,7 @@ i18n
refresh: 'Обновить квоту',
delete: 'Удалить аккаунт',
noQuota: 'Нет данных',
rateLimitedQuota: 'Лимит исчерпан',
resetPrefix: 'Сброс',
resetTime: 'Время сброса',
resetUnknown: 'Неизвестно',
+9 -2
View File
@@ -18,7 +18,8 @@ import { useTranslation } from 'react-i18next';
import { setAppLanguage } from '@/actions/language';
import { useAppConfig } from '@/hooks/useAppConfig';
import { Loader2, FolderOpen } from 'lucide-react';
import { useState, useEffect } from 'react';
import { ModelVisibilitySettings } from '@/components/ModelVisibilitySettings';
import { useEffect, useState } from 'react';
import { ProxyConfig } from '@/types/config';
import { openLogDirectory } from '@/actions/system';
@@ -80,8 +81,9 @@ function SettingsPage() {
</div>
<Tabs defaultValue="general" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="general">{t('settings.general', 'General')}</TabsTrigger>
<TabsTrigger value="models">{t('settings.models', 'Models')}</TabsTrigger>
<TabsTrigger value="proxy">{t('settings.proxy_tab', 'Proxy')}</TabsTrigger>
</TabsList>
@@ -297,6 +299,11 @@ function SettingsPage() {
</Card>
</TabsContent>
{/* --- MODELS TAB --- */}
<TabsContent value="models" className="space-y-5">
<ModelVisibilitySettings />
</TabsContent>
{/* --- PROXY TAB (Upstream Proxy Config Only) --- */}
<TabsContent value="proxy" className="space-y-5">
<Card>
+34 -31
View File
@@ -119,8 +119,8 @@ export class ProxyService {
);
return this.toAnthropicChatResponse(transformResponse(response));
}
} catch (fallbackError) {
error = fallbackError;
} catch (fallbackErr) {
lastError = fallbackErr;
}
}
@@ -158,8 +158,8 @@ export class ProxyService {
model: request.model,
};
}
} catch (downgradeError) {
error = downgradeError;
} catch (downgradeErr) {
lastError = downgradeErr;
}
}
@@ -313,10 +313,10 @@ export class ProxyService {
);
return this.normalizeGeminiGenerateResponse(response);
} catch (error) {
if (error instanceof Error && this.isProjectContextError(error.message)) {
} catch (err) {
if (err instanceof Error && this.isProjectContextError(err.message)) {
this.logger.warn(
`Gemini request hit project context issue, retrying without project: ${error.message}`,
`Gemini request hit project context issue, retrying without project: ${err.message}`,
);
try {
const fallbackBody = this.createGeminiInternalRequest(
@@ -332,15 +332,16 @@ export class ProxyService {
extraHeaders,
);
return this.normalizeGeminiGenerateResponse(response);
} catch (fallbackError) {
error = fallbackError;
} catch (fallbackErr) {
lastError = fallbackErr;
}
} else {
lastError = err;
}
lastError = error;
if (error instanceof Error) {
this.logger.warn(`Gemini request failed with account ${token.email}: ${error.message}`);
const decision = this.classifyUpstreamError(error.message);
if (lastError instanceof Error) {
this.logger.warn(`Gemini request failed with account ${token.email}: ${lastError.message}`);
const decision = this.classifyUpstreamError(lastError.message);
if (decision.retry) {
if (decision.markAsForbidden) {
this.tokenManager.markAsForbidden(token.id);
@@ -400,10 +401,10 @@ export class ProxyService {
extraHeaders,
);
return this.passthroughSseStream(stream);
} catch (error) {
if (error instanceof Error && this.isProjectContextError(error.message)) {
} catch (err) {
if (err instanceof Error && this.isProjectContextError(err.message)) {
this.logger.warn(
`Gemini stream request hit project context issue, retrying without project: ${error.message}`,
`Gemini stream request hit project context issue, retrying without project: ${err.message}`,
);
try {
const fallbackBody = this.createGeminiInternalRequest(
@@ -419,17 +420,18 @@ export class ProxyService {
extraHeaders,
);
return this.passthroughSseStream(stream);
} catch (fallbackError) {
error = fallbackError;
} catch (fallbackErr) {
lastError = fallbackErr;
}
} else {
lastError = err;
}
lastError = error;
if (error instanceof Error) {
if (lastError instanceof Error) {
this.logger.warn(
`Gemini stream request failed with account ${token.email}: ${error.message}`,
`Gemini stream request failed with account ${token.email}: ${lastError.message}`,
);
const decision = this.classifyUpstreamError(error.message);
const decision = this.classifyUpstreamError(lastError.message);
if (decision.retry) {
if (decision.markAsForbidden) {
this.tokenManager.markAsForbidden(token.id);
@@ -627,10 +629,10 @@ export class ProxyService {
this.logger.log(`Claude Response: ${JSON.stringify(claudeResponse).substring(0, 500)}`);
return this.convertClaudeToOpenAIResponse(claudeResponse, request.model);
}
} catch (error) {
if (error instanceof Error && this.isProjectContextError(error.message)) {
} catch (err) {
if (err instanceof Error && this.isProjectContextError(err.message)) {
this.logger.warn(
`OpenAI compatibility request hit project context issue, retrying without project: ${error.message}`,
`OpenAI compatibility request hit project context issue, retrying without project: ${err.message}`,
);
try {
const claudeRequest = this.convertOpenAIToClaude(request);
@@ -653,16 +655,17 @@ export class ProxyService {
);
const claudeResponse = transformResponse(response);
return this.convertClaudeToOpenAIResponse(claudeResponse, request.model);
} catch (fallbackError) {
error = fallbackError;
} catch (fallbackErr) {
lastError = fallbackErr;
}
} else {
lastError = err;
}
lastError = error;
if (error instanceof Error) {
this.logger.warn(`Request failed with account ${token.email}: ${error.message}`);
if (lastError instanceof Error) {
this.logger.warn(`Request failed with account ${token.email}: ${lastError.message}`);
const decision = this.classifyUpstreamError(error.message);
const decision = this.classifyUpstreamError(lastError.message);
if (decision.retry) {
if (decision.markAsForbidden) {
this.tokenManager.markAsForbidden(token.id);
+197
View File
@@ -0,0 +1,197 @@
import { describe, it, expect } from 'vitest';
import {
detectProvider,
getProviderInfo,
calculateProviderStats,
groupModelsByProvider,
} from '@/utils/provider-grouping';
describe('detectProvider', () => {
it('should categorize Claude models correctly', () => {
expect(detectProvider('claude-3-7-sonnet')).toBe('claude-');
expect(detectProvider('claude-2.1')).toBe('claude-');
expect(detectProvider('claude-3-5-sonnet')).toBe('claude-');
expect(detectProvider('claude-3-opus')).toBe('claude-');
expect(detectProvider('claude-3-haiku')).toBe('claude-');
});
it('should categorize Gemini models correctly', () => {
expect(detectProvider('gemini-2.0-flash')).toBe('gemini-');
expect(detectProvider('gemini-1.5-pro')).toBe('gemini-');
expect(detectProvider('gemini-2.5-flash')).toBe('gemini-');
});
it('should fallback to others for unknown models', () => {
expect(detectProvider('gpt-4-turbo')).toBe('others');
expect(detectProvider('llama-2-7b')).toBe('others');
expect(detectProvider('unknown-model')).toBe('others');
});
it('should handle empty string', () => {
expect(detectProvider('')).toBe('others');
});
});
describe('getProviderInfo', () => {
it('should return Claude info for Claude models', () => {
const info = getProviderInfo('claude-3-7-sonnet');
expect(info.name).toBe('Claude');
expect(info.company).toBe('Anthropic');
});
it('should return Gemini info for Gemini models', () => {
const info = getProviderInfo('gemini-2.0-flash');
expect(info.name).toBe('Gemini');
expect(info.company).toBe('Google');
});
it('should return Other info for unknown models', () => {
const info = getProviderInfo('gpt-4');
expect(info.name).toBe('Other');
expect(info.company).toBe('Various');
});
});
describe('calculateProviderStats', () => {
it('should calculate correct averages for visible models', () => {
const models = [
{ id: 'claude-3-7-sonnet', percentage: 80, resetTime: '2026-02-16T10:00:00Z' },
{ id: 'claude-3-5-sonnet', percentage: 70, resetTime: '2026-02-16T08:00:00Z' },
];
const stats = calculateProviderStats('claude-', models, {});
expect(stats.avgPercentage).toBe(75);
expect(stats.visibleModels).toHaveLength(2);
expect(stats.providerInfo.name).toBe('Claude');
});
it('should exclude hidden models from calculations', () => {
const models = [
{ id: 'claude-3-7-sonnet', percentage: 80, resetTime: '2026-02-16T10:00:00Z' },
{ id: 'claude-3-5-sonnet', percentage: 40, resetTime: '2026-02-16T08:00:00Z' },
];
const visibility = { 'claude-3-5-sonnet': false };
const stats = calculateProviderStats('claude-', models, visibility);
expect(stats.avgPercentage).toBe(80);
expect(stats.visibleModels).toHaveLength(1);
expect(stats.models).toHaveLength(2);
});
it('should find the earliest reset time', () => {
const models = [
{ id: 'claude-3-7-sonnet', percentage: 80, resetTime: '2026-02-16T10:00:00Z' },
{ id: 'claude-3-5-sonnet', percentage: 70, resetTime: '2026-02-16T08:00:00Z' },
];
const stats = calculateProviderStats('claude-', models, {});
expect(stats.earliestReset).toBe('2026-02-16T08:00:00.000Z');
});
it('should handle empty models', () => {
const stats = calculateProviderStats('claude-', [], {});
expect(stats.avgPercentage).toBe(0);
expect(stats.visibleModels).toHaveLength(0);
expect(stats.earliestReset).toBeNull();
});
it('should handle all models hidden', () => {
const models = [{ id: 'claude-3-7-sonnet', percentage: 80, resetTime: '2026-02-16T10:00:00Z' }];
const visibility = { 'claude-3-7-sonnet': false };
const stats = calculateProviderStats('claude-', models, visibility);
expect(stats.avgPercentage).toBe(0);
expect(stats.visibleModels).toHaveLength(0);
});
});
describe('groupModelsByProvider', () => {
it('should group models by provider', () => {
const models = {
'claude-3-7-sonnet': { percentage: 80, resetTime: '2026-02-16T10:00:00Z' },
'claude-3-5-sonnet': { percentage: 70, resetTime: '2026-02-16T08:00:00Z' },
'gemini-2.0-flash': { percentage: 50, resetTime: '2026-02-16T06:00:00Z' },
'gemini-1.5-pro': { percentage: 30, resetTime: '2026-02-16T07:00:00Z' },
};
const stats = groupModelsByProvider(models, {});
expect(stats.providers).toHaveLength(2);
expect(stats.providers[0].providerKey).toBe('claude-');
expect(stats.providers[0].visibleModels).toHaveLength(2);
expect(stats.providers[1].providerKey).toBe('gemini-');
expect(stats.providers[1].visibleModels).toHaveLength(2);
});
it('should include others group for unknown models', () => {
const models = {
'claude-3-7-sonnet': { percentage: 80, resetTime: '2026-02-16T10:00:00Z' },
'gpt-4-turbo': { percentage: 60, resetTime: '2026-02-16T09:00:00Z' },
};
const stats = groupModelsByProvider(models, {});
expect(stats.providers).toHaveLength(2);
expect(stats.providers[1].providerKey).toBe('others');
});
it('should calculate overall percentage as average of all visible models', () => {
const models = {
'claude-3-7-sonnet': { percentage: 80, resetTime: '' },
'gemini-2.0-flash': { percentage: 40, resetTime: '' },
};
const stats = groupModelsByProvider(models, {});
expect(stats.overallPercentage).toBe(60);
expect(stats.visibleModels).toBe(2);
expect(stats.totalModels).toBe(2);
});
it('should determine health status based on overall percentage', () => {
// healthy (>=50%)
const healthyModels = {
'claude-3-7-sonnet': { percentage: 80, resetTime: '' },
};
expect(groupModelsByProvider(healthyModels, {}).healthStatus).toBe('healthy');
// degraded (25-50%)
const degradedModels = {
'claude-3-7-sonnet': { percentage: 40, resetTime: '' },
};
expect(groupModelsByProvider(degradedModels, {}).healthStatus).toBe('degraded');
// limited (10-25%)
const limitedModels = {
'claude-3-7-sonnet': { percentage: 20, resetTime: '' },
};
expect(groupModelsByProvider(limitedModels, {}).healthStatus).toBe('limited');
// critical (<10%)
const criticalModels = {
'claude-3-7-sonnet': { percentage: 5, resetTime: '' },
};
expect(groupModelsByProvider(criticalModels, {}).healthStatus).toBe('critical');
});
it('should handle empty models object', () => {
const stats = groupModelsByProvider({}, {});
expect(stats.providers).toHaveLength(0);
expect(stats.overallPercentage).toBe(0);
expect(stats.totalModels).toBe(0);
expect(stats.visibleModels).toBe(0);
});
it('should respect model visibility settings', () => {
const models = {
'claude-3-7-sonnet': { percentage: 80, resetTime: '' },
'claude-3-5-sonnet': { percentage: 40, resetTime: '' },
};
const visibility = { 'claude-3-5-sonnet': false };
const stats = groupModelsByProvider(models, visibility);
expect(stats.visibleModels).toBe(1);
expect(stats.overallPercentage).toBe(80);
});
it('should sort providers: claude first, gemini second, others last', () => {
const models = {
'gpt-4': { percentage: 50, resetTime: '' },
'gemini-2.0-flash': { percentage: 60, resetTime: '' },
'claude-3-7-sonnet': { percentage: 70, resetTime: '' },
};
const stats = groupModelsByProvider(models, {});
expect(stats.providers[0].providerKey).toBe('claude-');
expect(stats.providers[1].providerKey).toBe('gemini-');
expect(stats.providers[2].providerKey).toBe('others');
});
});
@@ -12,22 +12,6 @@ function createReplyMock() {
}
describe('ProxyController Integration', () => {
it('supports models listing endpoints', () => {
const proxyService = {};
const controller = new ProxyController(proxyService as any);
const allModels = controller.getModels();
const claudeModels = controller.getClaudeModels();
expect(allModels.object).toBe('list');
expect(Array.isArray(allModels.data)).toBe(true);
expect(allModels.data.length).toBeGreaterThan(0);
expect(allModels.data.every((model) => model.owned_by === 'antigravity')).toBe(true);
expect(allModels.data.every((model) => model.created === 1770652800)).toBe(true);
expect(claudeModels).toEqual(allModels);
});
it('routes Claude OpenAI requests to protocol parity path', async () => {
const proxyService = {
handleChatCompletions: vi.fn().mockResolvedValue({ ok: true }),
@@ -439,24 +423,6 @@ describe('ProxyController Integration', () => {
expect(reply.send).toHaveBeenCalledWith('Invalid `boundary` for `multipart/form-data` request');
});
it('supports model detect endpoint', () => {
const proxyService = {
detectModelCapabilities: vi.fn().mockReturnValue({
model: 'claude-sonnet-4-5',
mapped_model: 'gemini-3-pro-preview',
type: 'generate-content',
features: { has_web_search: false, is_image_gen: false },
}),
};
const controller = new ProxyController(proxyService as any);
const reply = createReplyMock();
controller.detectModel({ model: 'claude-sonnet-4-5' }, reply as any);
expect(proxyService.detectModelCapabilities).toHaveBeenCalledWith('claude-sonnet-4-5');
expect(reply.status).toHaveBeenCalledWith(200);
});
it('supports Anthropic messages endpoint', async () => {
const proxyService = {
handleAnthropicMessages: vi.fn().mockResolvedValue({
+6
View File
@@ -28,6 +28,9 @@ export const AppConfigSchema = z.object({
error_reporting_enabled: z.boolean(),
privacy_consent_asked: z.boolean().optional().default(false), // Optional for backward compatibility
default_export_path: z.string().nullable().optional(), // 导出路径
model_visibility: z.record(z.string(), z.boolean()).default({}), // Model visibility preferences
provider_groupings_enabled: z.boolean().default(false), // Enable provider groupings UI
grid_layout: z.enum(['auto', '2-col', '3-col', 'list']).default('auto'), // Account card grid layout
proxy: ProxyConfigSchema,
});
@@ -46,6 +49,9 @@ export const DEFAULT_APP_CONFIG: AppConfig = {
error_reporting_enabled: true, // Default to disabled for privacy
privacy_consent_asked: false, // Whether the user has been asked for consent
default_export_path: null,
model_visibility: {}, // Model visibility preferences
provider_groupings_enabled: false, // Enable provider groupings UI
grid_layout: 'auto' as const, // Account card grid layout
proxy: {
enabled: false,
port: 8045,
+174
View File
@@ -0,0 +1,174 @@
/**
* Provider grouping utilities for categorizing AI models by provider
* and calculating aggregated statistics.
*/
export interface ProviderInfo {
name: string;
company: string;
color: string;
}
export const PROVIDER_REGISTRY: Record<string, ProviderInfo> = {
'claude-': {
name: 'Claude',
company: 'Anthropic',
color: '#D97757',
},
'gemini-': {
name: 'Gemini',
company: 'Google',
color: '#4285F4',
},
others: {
name: 'Other',
company: 'Various',
color: '#6B7280',
},
};
export type ProviderKey = keyof typeof PROVIDER_REGISTRY;
/**
* Detect the provider key for a given model name based on prefix matching.
*/
export function detectProvider(modelName: string): ProviderKey {
for (const prefix of Object.keys(PROVIDER_REGISTRY)) {
if (prefix !== 'others' && modelName.startsWith(prefix)) {
return prefix;
}
}
return 'others';
}
/**
* Get the provider display info for a given model name.
*/
export function getProviderInfo(modelName: string): ProviderInfo {
const key = detectProvider(modelName);
return PROVIDER_REGISTRY[key];
}
export interface ModelQuota {
id: string;
percentage: number;
resetTime: string;
}
export interface ProviderStats {
providerKey: ProviderKey;
providerInfo: ProviderInfo;
models: ModelQuota[];
visibleModels: ModelQuota[];
avgPercentage: number;
earliestReset: string | null;
}
/**
* Calculate aggregated stats for a group of models belonging to one provider.
*/
export function calculateProviderStats(
providerKey: ProviderKey,
models: ModelQuota[],
visibilitySettings: Record<string, boolean>,
): ProviderStats {
const visibleModels = models.filter((m) => visibilitySettings[m.id] !== false);
if (visibleModels.length === 0) {
return {
providerKey,
providerInfo: PROVIDER_REGISTRY[providerKey],
models,
visibleModels: [],
avgPercentage: 0,
earliestReset: null,
};
}
const avgPercentage =
visibleModels.reduce((sum, m) => sum + m.percentage, 0) / visibleModels.length;
const resetTimes = visibleModels
.map((m) => m.resetTime)
.filter(Boolean)
.map((time) => new Date(time).getTime())
.filter((t) => !Number.isNaN(t));
const earliestReset =
resetTimes.length > 0 ? new Date(Math.min(...resetTimes)).toISOString() : null;
return {
providerKey,
providerInfo: PROVIDER_REGISTRY[providerKey],
models,
visibleModels,
avgPercentage: Math.round(avgPercentage * 10) / 10,
earliestReset,
};
}
export interface AccountStats {
providers: ProviderStats[];
totalModels: number;
visibleModels: number;
overallPercentage: number;
healthStatus: 'healthy' | 'degraded' | 'limited' | 'critical';
}
/**
* Group models by provider and calculate per-provider and overall account stats.
*/
export function groupModelsByProvider(
models: Record<string, { percentage: number; resetTime: string }>,
visibilitySettings: Record<string, boolean>,
): AccountStats {
const grouped: Record<ProviderKey, ModelQuota[]> = {};
for (const [modelName, info] of Object.entries(models)) {
const key = detectProvider(modelName);
if (!grouped[key]) {
grouped[key] = [];
}
grouped[key].push({
id: modelName,
percentage: info.percentage,
resetTime: info.resetTime,
});
}
const providers: ProviderStats[] = [];
for (const [key, groupModels] of Object.entries(grouped)) {
providers.push(calculateProviderStats(key, groupModels, visibilitySettings));
}
// Sort: known providers first (claude-, gemini-), then others
const providerOrder = Object.keys(PROVIDER_REGISTRY);
providers.sort(
(a, b) => providerOrder.indexOf(a.providerKey) - providerOrder.indexOf(b.providerKey),
);
const allVisibleModels = providers.flatMap((p) => p.visibleModels);
const totalModels = providers.reduce((sum, p) => sum + p.models.length, 0);
const overallPercentage =
allVisibleModels.length > 0
? allVisibleModels.reduce((sum, m) => sum + m.percentage, 0) / allVisibleModels.length
: 0;
let healthStatus: AccountStats['healthStatus'] = 'healthy';
if (overallPercentage < 10) {
healthStatus = 'critical';
} else if (overallPercentage < 25) {
healthStatus = 'limited';
} else if (overallPercentage < 50) {
healthStatus = 'degraded';
}
return {
providers,
totalModels,
visibleModels: allVisibleModels.length,
overallPercentage: Math.round(overallPercentage * 10) / 10,
healthStatus,
};
}