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
This commit is contained in:
YoVinchen
2025-12-08 17:03:07 +08:00
parent 4c884a1256
commit cfbbc9485f
2 changed files with 274 additions and 412 deletions
+261 -328
View File
@@ -1,37 +1,30 @@
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { ChevronDown, ChevronRight, Save, Loader2, Info } from "lucide-react";
import { Save, Loader2, Info } from "lucide-react";
import { toast } from "sonner";
import {
useCircuitBreakerConfig,
useUpdateCircuitBreakerConfig,
} from "@/lib/query/failover";
/**
* 自动故障转移配置面板
* 放置在高级设置页面,模型测试配置下方
*/
export function AutoFailoverConfigPanel() {
const { t } = useTranslation();
const [isExpanded, setIsExpanded] = useState(false);
export interface AutoFailoverConfigPanelProps {
enabled: boolean;
onEnabledChange: (enabled: boolean) => void;
}
export function AutoFailoverConfigPanel({
enabled,
onEnabledChange,
}: AutoFailoverConfigPanelProps) {
const { t } = useTranslation();
const { data: config, isLoading, error } = useCircuitBreakerConfig();
const updateConfig = useUpdateCircuitBreakerConfig();
const [formData, setFormData] = useState({
enabled: true, // 自动故障转移总开关
failureThreshold: 5,
successThreshold: 2,
timeoutSeconds: 60,
@@ -42,7 +35,6 @@ export function AutoFailoverConfigPanel() {
useEffect(() => {
if (config) {
setFormData({
enabled: true, // 默认开启,后续可以从数据库读取
...config,
});
}
@@ -70,7 +62,6 @@ export function AutoFailoverConfigPanel() {
const handleReset = () => {
if (config) {
setFormData({
enabled: formData.enabled,
...config,
});
}
@@ -78,326 +69,268 @@ export function AutoFailoverConfigPanel() {
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("proxy.autoFailover.title", "自动故障转移配置")}
</CardTitle>
</div>
</CardHeader>
</Card>
<div className="flex items-center justify-center p-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
);
}
return (
<Card className="border rounded-lg">
<CardHeader
className="cursor-pointer select-none"
onClick={() => setIsExpanded(!isExpanded)}
>
<div className="flex items-center gap-2">
{isExpanded ? (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
)}
<div className="flex-1">
<div className="flex items-center gap-3">
<CardTitle className="text-base">
{t("proxy.autoFailover.title", "自动故障转移配置")}
</CardTitle>
{/* 总开关 - 点击时阻止折叠/展开 */}
<div
onClick={(e) => e.stopPropagation()}
className="flex items-center gap-2"
>
<Switch
id="autoFailoverEnabled"
checked={formData.enabled}
onCheckedChange={(checked) =>
setFormData({ ...formData, enabled: checked })
}
className="scale-90"
/>
<Label
htmlFor="autoFailoverEnabled"
className="text-xs font-medium cursor-pointer"
>
{formData.enabled
? t("proxy.autoFailover.enabled", "已启用")
: t("proxy.autoFailover.disabled", "已禁用")}
</Label>
</div>
</div>
{!isExpanded && (
<CardDescription className="mt-1">
{t(
"proxy.autoFailover.description",
"配置多个代理目标之间的自动切换规则和熔断策略",
)}
</CardDescription>
<div className="border-0 rounded-none shadow-none bg-transparent">
{/* Header Switch moved to parent accordion logic or kept here absolutely positioned if styling permits.
Since we need it in the accordion header, and this component is inside the content, we can use a portal or
absolute positioning trick similar to ProxyPanel, OR cleaner, just duplicate the switch logic in SettingsPage
and pass it down. But for now, let's use the absolute positioning trick to "lift" it visually.
Better yet, let's just render the content directly without the wrapping Card header/collapse logic
since the user requested "click to expand is detailed info, no need to fold again" (implying the accordion handles folding).
*/}
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{String(error)}</AlertDescription>
</Alert>
)}
<Alert className="border-blue-500/40 bg-blue-500/10">
<Info className="h-4 w-4" />
<AlertDescription className="text-sm">
{t(
"proxy.autoFailover.info",
"当启用多个代理目标时,系统会按优先级顺序依次尝试。当某个供应商连续失败达到阈值时,熔断器会自动打开,跳过该供应商。",
)}
</AlertDescription>
</Alert>
{/* 重试与超时配置 */}
<div className="space-y-4 rounded-lg border border-white/10 bg-muted/30 p-4">
<h4 className="text-sm font-semibold">
{t("proxy.autoFailover.retrySettings", "重试与超时设置")}
</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="failureThreshold">
{t("proxy.autoFailover.failureThreshold", "失败阈值")}
</Label>
<Input
id="failureThreshold"
type="number"
min="1"
max="20"
value={formData.failureThreshold}
onChange={(e) =>
setFormData({
...formData,
failureThreshold: parseInt(e.target.value) || 5,
})
}
disabled={!enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.failureThresholdHint",
"连续失败多少次后打开熔断器(建议: 3-10)",
)}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="timeoutSeconds">
{t("proxy.autoFailover.timeout", "恢复等待时间(秒)")}
</Label>
<Input
id="timeoutSeconds"
type="number"
min="10"
max="300"
value={formData.timeoutSeconds}
onChange={(e) =>
setFormData({
...formData,
timeoutSeconds: parseInt(e.target.value) || 60,
})
}
disabled={!enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.timeoutHint",
"熔断器打开后,等待多久后尝试恢复(建议: 30-120)",
)}
</p>
</div>
</div>
</div>
</CardHeader>
{isExpanded && (
<CardContent className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{String(error)}</AlertDescription>
</Alert>
)}
{/* 熔断器高级配置 */}
<div className="space-y-4 rounded-lg border border-white/10 bg-muted/30 p-4">
<h4 className="text-sm font-semibold">
{t("proxy.autoFailover.circuitBreakerSettings", "熔断器高级设置")}
</h4>
<Alert className="border-blue-500/40 bg-blue-500/10">
<Info className="h-4 w-4" />
<AlertDescription className="text-sm">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="successThreshold">
{t("proxy.autoFailover.successThreshold", "恢复成功阈值")}
</Label>
<Input
id="successThreshold"
type="number"
min="1"
max="10"
value={formData.successThreshold}
onChange={(e) =>
setFormData({
...formData,
successThreshold: parseInt(e.target.value) || 2,
})
}
disabled={!enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.successThresholdHint",
"半开状态下成功多少次后关闭熔断器",
)}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="errorRateThreshold">
{t("proxy.autoFailover.errorRate", "错误率阈值 (%)")}
</Label>
<Input
id="errorRateThreshold"
type="number"
min="0"
max="100"
step="5"
value={Math.round(formData.errorRateThreshold * 100)}
onChange={(e) =>
setFormData({
...formData,
errorRateThreshold: (parseInt(e.target.value) || 50) / 100,
})
}
disabled={!enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.errorRateHint",
"错误率超过此值时打开熔断器",
)}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="minRequests">
{t("proxy.autoFailover.minRequests", "最小请求数")}
</Label>
<Input
id="minRequests"
type="number"
min="5"
max="100"
value={formData.minRequests}
onChange={(e) =>
setFormData({
...formData,
minRequests: parseInt(e.target.value) || 10,
})
}
disabled={!enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.minRequestsHint",
"计算错误率前的最小请求数",
)}
</p>
</div>
</div>
</div>
{/* 操作按钮 */}
<div className="flex justify-end gap-3 pt-2">
<Button
variant="outline"
onClick={handleReset}
disabled={updateConfig.isPending || !enabled}
>
{t("common.reset", "重置")}
</Button>
<Button
onClick={handleSave}
disabled={updateConfig.isPending || !formData.enabled}
>
{updateConfig.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("common.saving", "保存中...")}
</>
) : (
<>
<Save className="mr-2 h-4 w-4" />
{t("common.save", "保存")}
</>
)}
</Button>
</div>
{/* 说明信息 */}
<div className="p-4 bg-muted/50 rounded-lg space-y-2 text-sm">
<h4 className="font-medium">
{t("proxy.autoFailover.explanationTitle", "工作原理")}
</h4>
<ul className="space-y-1 text-muted-foreground">
<li>
{" "}
<strong>
{t("proxy.autoFailover.failureThresholdLabel", "失败阈值")}
</strong>
{t(
"proxy.autoFailover.info",
"当启用多个代理目标时,系统会按优先级顺序依次尝试。当某个供应商连续失败达到阈值时,熔断器会自动打开,跳过该供应商",
"proxy.autoFailover.failureThresholdExplain",
"连续失败达到此次数时,熔断器打开,该供应商暂时不可用",
)}
</AlertDescription>
</Alert>
{/* 重试与超时配置 */}
<div className="space-y-4 rounded-lg border border-white/10 bg-muted/30 p-4">
<h4 className="text-sm font-semibold">
{t("proxy.autoFailover.retrySettings", "重试与超时设置")}
</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="failureThreshold">
{t("proxy.autoFailover.failureThreshold", "失败阈值")}
</Label>
<Input
id="failureThreshold"
type="number"
min="1"
max="20"
value={formData.failureThreshold}
onChange={(e) =>
setFormData({
...formData,
failureThreshold: parseInt(e.target.value) || 5,
})
}
disabled={!formData.enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.failureThresholdHint",
"连续失败多少次后打开熔断器(建议: 3-10)",
)}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="timeoutSeconds">
{t("proxy.autoFailover.timeout", "恢复等待时间(秒)")}
</Label>
<Input
id="timeoutSeconds"
type="number"
min="10"
max="300"
value={formData.timeoutSeconds}
onChange={(e) =>
setFormData({
...formData,
timeoutSeconds: parseInt(e.target.value) || 60,
})
}
disabled={!formData.enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.timeoutHint",
"熔断器打开后,等待多久后尝试恢复(建议: 30-120)",
)}
</p>
</div>
</div>
</div>
{/* 熔断器高级配置 */}
<div className="space-y-4 rounded-lg border border-white/10 bg-muted/30 p-4">
<h4 className="text-sm font-semibold">
{t("proxy.autoFailover.circuitBreakerSettings", "熔断器高级设置")}
</h4>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="successThreshold">
{t("proxy.autoFailover.successThreshold", "恢复成功阈值")}
</Label>
<Input
id="successThreshold"
type="number"
min="1"
max="10"
value={formData.successThreshold}
onChange={(e) =>
setFormData({
...formData,
successThreshold: parseInt(e.target.value) || 2,
})
}
disabled={!formData.enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.successThresholdHint",
"半开状态下成功多少次后关闭熔断器",
)}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="errorRateThreshold">
{t("proxy.autoFailover.errorRate", "错误率阈值 (%)")}
</Label>
<Input
id="errorRateThreshold"
type="number"
min="0"
max="100"
step="5"
value={Math.round(formData.errorRateThreshold * 100)}
onChange={(e) =>
setFormData({
...formData,
errorRateThreshold:
(parseInt(e.target.value) || 50) / 100,
})
}
disabled={!formData.enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.errorRateHint",
"错误率超过此值时打开熔断器",
)}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="minRequests">
{t("proxy.autoFailover.minRequests", "最小请求数")}
</Label>
<Input
id="minRequests"
type="number"
min="5"
max="100"
value={formData.minRequests}
onChange={(e) =>
setFormData({
...formData,
minRequests: parseInt(e.target.value) || 10,
})
}
disabled={!formData.enabled}
/>
<p className="text-xs text-muted-foreground">
{t(
"proxy.autoFailover.minRequestsHint",
"计算错误率前的最小请求数",
)}
</p>
</div>
</div>
</div>
{/* 操作按钮 */}
<div className="flex justify-end gap-3 pt-2">
<Button
variant="outline"
onClick={handleReset}
disabled={updateConfig.isPending || !formData.enabled}
>
{t("common.reset", "重置")}
</Button>
<Button
onClick={handleSave}
disabled={updateConfig.isPending || !formData.enabled}
>
{updateConfig.isPending ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("common.saving", "保存中...")}
</>
) : (
<>
<Save className="mr-2 h-4 w-4" />
{t("common.save", "保存")}
</>
</li>
<li>
{" "}
<strong>
{t("proxy.autoFailover.timeoutLabel", "恢复等待时间")}
</strong>
{t(
"proxy.autoFailover.timeoutExplain",
"熔断器打开后,等待此时间后尝试半开状态",
)}
</Button>
</div>
{/* 说明信息 */}
<div className="p-4 bg-muted/50 rounded-lg space-y-2 text-sm">
<h4 className="font-medium">
{t("proxy.autoFailover.explanationTitle", "工作原理")}
</h4>
<ul className="space-y-1 text-muted-foreground">
<li>
{" "}
<strong>
{t("proxy.autoFailover.failureThresholdLabel", "失败阈值")}
</strong>
{t(
"proxy.autoFailover.failureThresholdExplain",
"连续失败达到此次数时,熔断器打开,该供应商暂时不可用",
)}
</li>
<li>
{" "}
<strong>
{t("proxy.autoFailover.timeoutLabel", "恢复等待时间")}
</strong>
{t(
"proxy.autoFailover.timeoutExplain",
"熔断器打开后,等待此时间后尝试半开状态",
)}
</li>
<li>
{" "}
<strong>
{t(
"proxy.autoFailover.successThresholdLabel",
"恢复成功阈值",
)}
</strong>
{t(
"proxy.autoFailover.successThresholdExplain",
"半开状态下,成功达到此次数时关闭熔断器,供应商恢复可用",
)}
</li>
<li>
{" "}
<strong>
{t("proxy.autoFailover.errorRateLabel", "错误率阈值")}
</strong>
{t(
"proxy.autoFailover.errorRateExplain",
"错误率超过此值时,即使未达到失败阈值也会打开熔断器",
)}
</li>
</ul>
</div>
</CardContent>
)}
</Card>
</li>
<li>
{" "}
<strong>
{t("proxy.autoFailover.successThresholdLabel", "恢复成功阈值")}
</strong>
{t(
"proxy.autoFailover.successThresholdExplain",
"半开状态下,成功达到此次数时关闭熔断器,供应商恢复可用",
)}
</li>
<li>
{" "}
<strong>
{t("proxy.autoFailover.errorRateLabel", "错误率阈值")}
</strong>
{t(
"proxy.autoFailover.errorRateExplain",
"错误率超过此值时,即使未达到失败阈值也会打开熔断器",
)}
</li>
</ul>
</div>
</div>
</div>
);
}
+13 -84
View File
@@ -1,16 +1,7 @@
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,
ListOrdered,
} from "lucide-react";
import { ProxySettingsDialog } from "./ProxySettingsDialog";
import { toast } from "sonner";
import { useProxyTargets } from "@/lib/query/failover";
@@ -19,7 +10,7 @@ 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);
// 获取所有三个应用类型的代理目标列表
@@ -27,18 +18,6 @@ export function ProxyPanel() {
const { data: codexTargets = [] } = useProxyTargets("codex");
const { data: geminiTargets = [] } = useProxyTargets("gemini");
const handleToggle = async () => {
try {
if (isRunning) {
await stop();
} else {
await start();
}
} catch (error) {
console.error("Toggle proxy failed:", error);
}
};
const formatUptime = (seconds: number): string => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
@@ -55,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}
@@ -126,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}
@@ -167,10 +98,10 @@ export function ProxyPanel() {
{(claudeTargets.length > 0 ||
codexTargets.length > 0 ||
geminiTargets.length > 0) && (
<div className="pt-3 border-t border-white/10 space-y-3">
<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 font-medium text-muted-foreground uppercase tracking-wide">
<p className="text-xs text-muted-foreground">
</p>
</div>
@@ -268,13 +199,11 @@ 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>
@@ -351,7 +280,7 @@ function ProviderQueueItem({
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-white/10 bg-background/60"
: "border-border bg-background/60"
}`}
>
<div className="flex items-center gap-2">