mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-25 13:45:03 +08:00
Feat/auto failover (#367)
* 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
This commit is contained in:
@@ -1,27 +1,22 @@
|
||||
import { useState } from "react";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Activity, Clock, TrendingUp, Server, ListOrdered } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { Settings, Activity, Clock, TrendingUp, Server } from "lucide-react";
|
||||
import { ProxySettingsDialog } from "./ProxySettingsDialog";
|
||||
import { toast } from "sonner";
|
||||
import { useProxyTargets } from "@/lib/query/failover";
|
||||
import { ProviderHealthBadge } from "@/components/providers/ProviderHealthBadge";
|
||||
import { useProviderHealth } from "@/lib/query/failover";
|
||||
import type { ProxyStatus } from "@/types/proxy";
|
||||
|
||||
export function ProxyPanel() {
|
||||
const { status, isRunning, start, stop, isPending } = useProxyStatus();
|
||||
const { status, isRunning } = useProxyStatus();
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
|
||||
const handleToggle = async () => {
|
||||
try {
|
||||
if (isRunning) {
|
||||
await stop();
|
||||
} else {
|
||||
await start();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Toggle proxy failed:", error);
|
||||
}
|
||||
};
|
||||
// 获取所有三个应用类型的代理目标列表
|
||||
const { data: claudeTargets = [] } = useProxyTargets("claude");
|
||||
const { data: codexTargets = [] } = useProxyTargets("codex");
|
||||
const { data: geminiTargets = [] } = useProxyTargets("gemini");
|
||||
|
||||
const formatUptime = (seconds: number): string => {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
@@ -39,58 +34,12 @@ export function ProxyPanel() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="space-y-6 rounded-xl border border-white/10 glass-card p-6">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 rounded-lg bg-primary/10 text-primary">
|
||||
<Server className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-foreground">
|
||||
本地代理服务
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isRunning
|
||||
? `运行中 · ${status?.address}:${status?.port}`
|
||||
: "已停止"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge
|
||||
variant={isRunning ? "default" : "secondary"}
|
||||
className="gap-1.5"
|
||||
>
|
||||
<Activity
|
||||
className={`h-3 w-3 ${isRunning ? "animate-pulse" : ""}`}
|
||||
/>
|
||||
{isRunning ? "运行中" : "已停止"}
|
||||
</Badge>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setShowSettings(true)}
|
||||
disabled={isPending}
|
||||
aria-label="打开代理设置"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
</Button>
|
||||
<Switch
|
||||
checked={isRunning}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={isPending}
|
||||
aria-label={isRunning ? "停止代理服务" : "启动代理服务"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="space-y-6">
|
||||
{isRunning && status ? (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-lg border border-white/10 bg-muted/40 p-4 space-y-4">
|
||||
<div className="rounded-lg border border-border bg-muted/40 p-4 space-y-4">
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
服务地址
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">服务地址</p>
|
||||
<div className="mt-2 flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<code className="flex-1 text-sm bg-background px-3 py-2 rounded border border-border/60">
|
||||
http://{status.address}:{status.port}
|
||||
@@ -110,16 +59,14 @@ export function ProxyPanel() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-3 border-t border-white/10 space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
当前代理
|
||||
</p>
|
||||
<div className="pt-3 border-t border-border space-y-2">
|
||||
<p className="text-xs text-muted-foreground">使用中</p>
|
||||
{status.active_targets && status.active_targets.length > 0 ? (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{status.active_targets.map((target) => (
|
||||
<div
|
||||
key={target.app_type}
|
||||
className="flex items-center justify-between rounded-md border border-white/10 bg-background/60 px-2 py-1.5 text-xs"
|
||||
className="flex items-center justify-between rounded-md border border-border bg-background/60 px-2 py-1.5 text-xs"
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
{target.app_type}
|
||||
@@ -146,6 +93,50 @@ export function ProxyPanel() {
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 供应商队列 - 按应用类型分组展示 */}
|
||||
{(claudeTargets.length > 0 ||
|
||||
codexTargets.length > 0 ||
|
||||
geminiTargets.length > 0) && (
|
||||
<div className="pt-3 border-t border-border space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<ListOrdered className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
故障转移队列
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Claude 队列 */}
|
||||
{claudeTargets.length > 0 && (
|
||||
<ProviderQueueGroup
|
||||
appType="claude"
|
||||
appLabel="Claude"
|
||||
targets={claudeTargets}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Codex 队列 */}
|
||||
{codexTargets.length > 0 && (
|
||||
<ProviderQueueGroup
|
||||
appType="codex"
|
||||
appLabel="Codex"
|
||||
targets={codexTargets}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Gemini 队列 */}
|
||||
{geminiTargets.length > 0 && (
|
||||
<ProviderQueueGroup
|
||||
appType="gemini"
|
||||
appLabel="Gemini"
|
||||
targets={geminiTargets}
|
||||
status={status}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-4">
|
||||
@@ -208,15 +199,114 @@ function StatCard({ icon, label, value, variant = "default" }: StatCardProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`rounded-lg border border-white/10 bg-white/70 p-4 text-sm text-muted-foreground dark:bg-white/5 ${variantStyles[variant]}`}
|
||||
className={`rounded-lg border border-border bg-card/60 p-4 text-sm text-muted-foreground ${variantStyles[variant]}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-2">
|
||||
{icon}
|
||||
<span className="text-xs font-medium uppercase tracking-wide">
|
||||
{label}
|
||||
</span>
|
||||
<span className="text-xs">{label}</span>
|
||||
</div>
|
||||
<p className="text-xl font-semibold text-foreground">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ProviderQueueGroupProps {
|
||||
appType: string;
|
||||
appLabel: string;
|
||||
targets: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
}>;
|
||||
status: ProxyStatus;
|
||||
}
|
||||
|
||||
function ProviderQueueGroup({
|
||||
appType,
|
||||
appLabel,
|
||||
targets,
|
||||
status,
|
||||
}: ProviderQueueGroupProps) {
|
||||
// 查找该应用类型的当前活跃目标
|
||||
const activeTarget = status.active_targets?.find(
|
||||
(t) => t.app_type === appType,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* 应用类型标题 */}
|
||||
<div className="flex items-center gap-2 px-2">
|
||||
<span className="text-xs font-semibold text-foreground/80">
|
||||
{appLabel}
|
||||
</span>
|
||||
<div className="flex-1 h-px bg-border/50" />
|
||||
</div>
|
||||
|
||||
{/* 供应商列表 */}
|
||||
<div className="space-y-1.5">
|
||||
{targets.map((target, index) => (
|
||||
<ProviderQueueItem
|
||||
key={target.id}
|
||||
provider={target}
|
||||
priority={index + 1}
|
||||
appType={appType}
|
||||
isCurrent={activeTarget?.provider_id === target.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ProviderQueueItemProps {
|
||||
provider: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
priority: number;
|
||||
appType: string;
|
||||
isCurrent: boolean;
|
||||
}
|
||||
|
||||
function ProviderQueueItem({
|
||||
provider,
|
||||
priority,
|
||||
appType,
|
||||
isCurrent,
|
||||
}: ProviderQueueItemProps) {
|
||||
const { data: health } = useProviderHealth(provider.id, appType);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center justify-between rounded-md border px-3 py-2 text-sm transition-colors ${
|
||||
isCurrent
|
||||
? "border-primary/40 bg-primary/10 text-primary font-medium"
|
||||
: "border-border bg-background/60"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={`flex-shrink-0 flex items-center justify-center w-5 h-5 rounded-full text-xs font-bold ${
|
||||
isCurrent
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{priority}
|
||||
</span>
|
||||
<span className={isCurrent ? "" : "text-foreground"}>
|
||||
{provider.name}
|
||||
</span>
|
||||
{isCurrent && (
|
||||
<span className="text-xs px-1.5 py-0.5 rounded bg-primary/20 text-primary">
|
||||
使用中
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{/* 健康徽章:队列中的代理目标始终显示,没有健康数据时默认为正常 */}
|
||||
<ProviderHealthBadge
|
||||
consecutiveFailures={health?.consecutive_failures ?? 0}
|
||||
isProxyTarget={true}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user