mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-27 16:26:16 +08:00
41267135f5
* feat(db): add circuit breaker config table and provider proxy target APIs Add database support for auto-failover feature: - Add circuit_breaker_config table for storing failover thresholds - Add get/update_circuit_breaker_config methods in proxy DAO - Add reset_provider_health method for manual recovery - Add set_proxy_target and get_proxy_targets methods in providers DAO for managing multi-provider failover configuration * feat(proxy): implement circuit breaker and provider router for auto-failover Add core failover logic: - CircuitBreaker: Tracks provider health with three states: - Closed: Normal operation, requests pass through - Open: Circuit broken after consecutive failures, skip provider - HalfOpen: Testing recovery with limited requests - ProviderRouter: Routes requests across multiple providers with: - Health tracking and automatic failover - Configurable failure/success thresholds - Auto-disable proxy target after reaching failure threshold - Support for manual circuit breaker reset - Export new types in proxy module * feat(proxy): add failover Tauri commands and integrate with forwarder Expose failover functionality to frontend: - Add Tauri commands: get_proxy_targets, set_proxy_target, get_provider_health, reset_circuit_breaker, get/update_circuit_breaker_config, get_circuit_breaker_stats - Register all new commands in lib.rs invoke handler - Update forwarder with improved error handling and logging - Integrate ProviderRouter with proxy server startup - Add provider health tracking in request handlers * feat(frontend): add failover API layer and TanStack Query hooks Add frontend data layer for failover management: - Add failover.ts API: Tauri invoke wrappers for all failover commands - Add failover.ts query hooks: TanStack Query mutations and queries - useProxyTargets, useProviderHealth queries - useSetProxyTarget, useResetCircuitBreaker mutations - useCircuitBreakerConfig query and mutation - Update queries.ts with provider health query key - Update mutations.ts to invalidate health on provider changes - Add CircuitBreakerConfig and ProviderHealth types * feat(ui): add auto-failover configuration UI and provider health display Add comprehensive UI for failover management: Components: - ProviderHealthBadge: Display provider health status with color coding - CircuitBreakerConfigPanel: Configure failure/success thresholds, timeout duration, and error rate limits - AutoFailoverConfigPanel: Manage proxy targets with drag-and-drop priority ordering and individual enable/disable controls - ProxyPanel: Integrate failover tabs for unified proxy management Provider enhancements: - ProviderCard: Show health badge and proxy target indicator - ProviderActions: Add "Set as Proxy Target" action - EditProviderDialog: Add is_proxy_target toggle - ProviderList: Support proxy target filtering mode Other: - Update App.tsx routing for settings integration - Update useProviderActions hook with proxy target mutation - Fix ProviderList tests for updated component API * fix(usage): stabilize date range to prevent infinite re-renders * feat(backend): add tool version check command Add get_tool_versions command to check local and latest versions of Claude, Codex, and Gemini CLI tools: - Detect local installed versions via command line execution - Fetch latest versions from npm registry (Claude, Gemini) and GitHub releases API (Codex) - Return comprehensive version info including error details for uninstalled tools - Register command in Tauri invoke handler * style(ui): format accordion component code style Apply consistent code formatting to accordion component: - Convert double quotes to semicolons at line endings - Adjust indentation to 2-space standard - Align with project code style conventions * refactor(providers): update provider card styling to use theme tokens Replace hardcoded color classes with semantic design tokens: - Use bg-card, border-border, text-card-foreground instead of glass-card - Replace gray/white color literals with muted/foreground tokens - Change proxy target indicator color from purple to green - Improve hover states with border-border-active - Ensure consistent dark mode support via CSS variables * refactor(proxy): simplify auto-failover config panel structure Restructure AutoFailoverConfigPanel for better integration: - Remove internal Card wrapper and expansion toggle (now handled by parent) - Extract enabled state to props for external control - Simplify loading state display - Clean up redundant CardHeader/CardContent wrappers - ProxyPanel: reduce complexity by delegating to parent components * feat(settings): enhance settings page with accordion layout and tool versions Major settings page improvements: AboutSection: - Add local tool version detection (Claude, Codex, Gemini) - Display installed vs latest version comparison with visual indicators - Show update availability badges and environment check cards SettingsPage: - Reorganize advanced settings into collapsible accordion sections - Add proxy control panel with inline status toggle - Integrate auto-failover configuration with accordion UI - Add database and cost calculation config sections DirectorySettings & WindowSettings: - Minor styling adjustments for consistency settings.ts API: - Add getToolVersions() wrapper for new backend command * refactor(usage): restructure usage dashboard components Comprehensive usage statistics panel refactoring: UsageDashboard: - Reorganize layout with improved section headers - Add better loading states and empty state handling ModelStatsTable & ProviderStatsTable: - Minor styling updates for consistency ModelTestConfigPanel & PricingConfigPanel: - Simplify component structure - Remove redundant Card wrappers - Improve form field organization RequestLogTable: - Enhance table layout with better column sizing - Improve pagination controls UsageSummaryCards: - Update card styling with semantic tokens - Better responsive grid layout UsageTrendChart: - Refine chart container styling - Improve legend and tooltip display * chore(deps): add accordion and animation dependencies Package updates: - Add @radix-ui/react-accordion for collapsible sections - Add cmdk for command palette support - Add framer-motion for enhanced animations Tailwind config: - Add accordion-up/accordion-down animations - Update darkMode config to support both selector and class - Reorganize color and keyframe definitions for clarity * style(app): update header and app switcher styling App.tsx: - Replace glass-header with explicit bg-background/80 backdrop-blur - Update navigation button container to use bg-muted AppSwitcher: - Replace hardcoded gray colors with semantic muted/foreground tokens - Ensure consistent dark mode support via CSS variables - Add group class for better hover state transitions
255 lines
8.4 KiB
TypeScript
255 lines
8.4 KiB
TypeScript
import { useState } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
|
import {
|
|
Table,
|
|
TableBody,
|
|
TableCell,
|
|
TableHead,
|
|
TableHeader,
|
|
TableRow,
|
|
} from "@/components/ui/table";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Alert, AlertDescription } from "@/components/ui/alert";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog";
|
|
import { useModelPricing, useDeleteModelPricing } from "@/lib/query/usage";
|
|
import { PricingEditModal } from "./PricingEditModal";
|
|
import type { ModelPricing } from "@/types/usage";
|
|
import { Plus, Pencil, Trash2, ChevronDown, ChevronRight } from "lucide-react";
|
|
|
|
export function PricingConfigPanel() {
|
|
const { t } = useTranslation();
|
|
const { data: pricing, isLoading, error } = useModelPricing();
|
|
const deleteMutation = useDeleteModelPricing();
|
|
const [editingModel, setEditingModel] = useState<ModelPricing | null>(null);
|
|
const [isAddingNew, setIsAddingNew] = useState(false);
|
|
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
|
|
const [isExpanded, setIsExpanded] = useState(false);
|
|
|
|
const handleDelete = (modelId: string) => {
|
|
deleteMutation.mutate(modelId, {
|
|
onSuccess: () => {
|
|
setDeleteConfirm(null);
|
|
},
|
|
});
|
|
};
|
|
|
|
const handleAddNew = () => {
|
|
setIsAddingNew(true);
|
|
setEditingModel({
|
|
modelId: "",
|
|
displayName: "",
|
|
inputCostPerMillion: "0",
|
|
outputCostPerMillion: "0",
|
|
cacheReadCostPerMillion: "0",
|
|
cacheCreationCostPerMillion: "0",
|
|
});
|
|
};
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<Card className="border rounded-lg">
|
|
<CardHeader
|
|
className="cursor-pointer"
|
|
onClick={() => setIsExpanded(!isExpanded)}
|
|
>
|
|
<div className="flex items-center gap-2">
|
|
<ChevronRight className="h-4 w-4" />
|
|
<CardTitle className="text-base">
|
|
{t("usage.modelPricing", "模型定价")}
|
|
</CardTitle>
|
|
</div>
|
|
</CardHeader>
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
if (error) {
|
|
return (
|
|
<Card className="border rounded-lg">
|
|
<CardHeader
|
|
className="cursor-pointer"
|
|
onClick={() => setIsExpanded(!isExpanded)}
|
|
>
|
|
<div className="flex items-center gap-2">
|
|
{isExpanded ? (
|
|
<ChevronDown className="h-4 w-4" />
|
|
) : (
|
|
<ChevronRight className="h-4 w-4" />
|
|
)}
|
|
<CardTitle className="text-base">
|
|
{t("usage.modelPricing", "模型定价")}
|
|
</CardTitle>
|
|
</div>
|
|
</CardHeader>
|
|
{isExpanded && (
|
|
<CardContent>
|
|
<Alert variant="destructive">
|
|
<AlertDescription>
|
|
{t("usage.loadPricingError", "加载定价数据失败")}:{" "}
|
|
{String(error)}
|
|
</AlertDescription>
|
|
</Alert>
|
|
</CardContent>
|
|
)}
|
|
</Card>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="space-y-4">
|
|
<div className="flex items-center justify-between mb-4">
|
|
<h4 className="text-sm font-medium text-muted-foreground">
|
|
{t("usage.modelPricingDesc", "配置各模型的 Token 成本")} (每百万)
|
|
</h4>
|
|
<Button
|
|
onClick={(e) => {
|
|
e.stopPropagation();
|
|
handleAddNew();
|
|
}}
|
|
size="sm"
|
|
>
|
|
<Plus className="mr-1 h-4 w-4" />
|
|
{t("common.add", "新增")}
|
|
</Button>
|
|
</div>
|
|
|
|
<div className="space-y-4">
|
|
{!pricing || pricing.length === 0 ? (
|
|
<Alert>
|
|
<AlertDescription>
|
|
{t(
|
|
"usage.noPricingData",
|
|
'暂无定价数据。点击"新增"添加模型定价配置。',
|
|
)}
|
|
</AlertDescription>
|
|
</Alert>
|
|
) : (
|
|
<div className="rounded-md bg-card/60 shadow-sm">
|
|
<Table>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<TableHead>{t("usage.model", "模型")}</TableHead>
|
|
<TableHead>{t("usage.displayName", "显示名称")}</TableHead>
|
|
<TableHead className="text-right">
|
|
{t("usage.inputCost", "输入成本")}
|
|
</TableHead>
|
|
<TableHead className="text-right">
|
|
{t("usage.outputCost", "输出成本")}
|
|
</TableHead>
|
|
<TableHead className="text-right">
|
|
{t("usage.cacheReadCost", "缓存读取")}
|
|
</TableHead>
|
|
<TableHead className="text-right">
|
|
{t("usage.cacheWriteCost", "缓存写入")}
|
|
</TableHead>
|
|
<TableHead className="text-right">
|
|
{t("common.actions", "操作")}
|
|
</TableHead>
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{pricing.map((model) => (
|
|
<TableRow key={model.modelId}>
|
|
<TableCell className="font-mono text-sm">
|
|
{model.modelId}
|
|
</TableCell>
|
|
<TableCell>{model.displayName}</TableCell>
|
|
<TableCell className="text-right font-mono text-sm">
|
|
${model.inputCostPerMillion}
|
|
</TableCell>
|
|
<TableCell className="text-right font-mono text-sm">
|
|
${model.outputCostPerMillion}
|
|
</TableCell>
|
|
<TableCell className="text-right font-mono text-sm">
|
|
${model.cacheReadCostPerMillion}
|
|
</TableCell>
|
|
<TableCell className="text-right font-mono text-sm">
|
|
${model.cacheCreationCostPerMillion}
|
|
</TableCell>
|
|
<TableCell className="text-right">
|
|
<div className="flex justify-end gap-1">
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
onClick={() => {
|
|
setIsAddingNew(false);
|
|
setEditingModel(model);
|
|
}}
|
|
title={t("common.edit", "编辑")}
|
|
>
|
|
<Pencil className="h-4 w-4" />
|
|
</Button>
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
onClick={() => setDeleteConfirm(model.modelId)}
|
|
title={t("common.delete", "删除")}
|
|
className="text-destructive hover:text-destructive"
|
|
>
|
|
<Trash2 className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</TableCell>
|
|
</TableRow>
|
|
))}
|
|
</TableBody>
|
|
</Table>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{editingModel && (
|
|
<PricingEditModal
|
|
model={editingModel}
|
|
isNew={isAddingNew}
|
|
onClose={() => {
|
|
setEditingModel(null);
|
|
setIsAddingNew(false);
|
|
}}
|
|
/>
|
|
)}
|
|
|
|
<Dialog
|
|
open={!!deleteConfirm}
|
|
onOpenChange={() => setDeleteConfirm(null)}
|
|
>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>
|
|
{t("usage.deleteConfirmTitle", "确认删除")}
|
|
</DialogTitle>
|
|
<DialogDescription>
|
|
{t(
|
|
"usage.deleteConfirmDesc",
|
|
"确定要删除此模型定价配置吗?此操作无法撤销。",
|
|
)}
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
<DialogFooter>
|
|
<Button variant="outline" onClick={() => setDeleteConfirm(null)}>
|
|
{t("common.cancel", "取消")}
|
|
</Button>
|
|
<Button
|
|
variant="destructive"
|
|
onClick={() => deleteConfirm && handleDelete(deleteConfirm)}
|
|
disabled={deleteMutation.isPending}
|
|
>
|
|
{deleteMutation.isPending
|
|
? t("common.deleting", "删除中...")
|
|
: t("common.delete", "删除")}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
</div>
|
|
);
|
|
}
|