feat(proxy): implement local HTTP proxy server with multi-provider failover

Add a complete HTTP proxy server implementation built on Axum framework,
enabling local API request forwarding with automatic provider failover
and load balancing capabilities.

Backend Implementation (Rust):
- Add proxy server module with 7 core components:
  * server.rs: Axum HTTP server lifecycle management (start/stop/status)
  * router.rs: API routing configuration for Claude/OpenAI/Gemini endpoints
  * handlers.rs: Request/response handling and transformation
  * forwarder.rs: Upstream forwarding logic with retry mechanism (652 lines)
  * error.rs: Comprehensive error handling and HTTP status mapping
  * types.rs: Shared types (ProxyConfig, ProxyStatus, ProxyServerInfo)
  * health.rs: Provider health check infrastructure

Service Layer:
- Add ProxyService (services/proxy.rs, 157 lines):
  * Manage proxy server lifecycle
  * Handle configuration updates
  * Track runtime status and metrics

Database Layer:
- Add proxy configuration DAO (dao/proxy.rs, 242 lines):
  * Persist proxy settings (listen address, port, timeout)
  * Store provider priority and availability flags
- Update schema with proxy_config table (schema.rs):
  * Support runtime configuration persistence

Tauri Commands:
- Add 6 command endpoints (commands/proxy.rs):
  * start_proxy_server: Launch proxy server
  * stop_proxy_server: Gracefully shutdown server
  * get_proxy_status: Query runtime status
  * get_proxy_config: Retrieve current configuration
  * update_proxy_config: Modify settings without restart
  * is_proxy_running: Check server state

Frontend Implementation (React + TypeScript):
- Add ProxyPanel component (222 lines):
  * Real-time server status display
  * Start/stop controls
  * Provider availability monitoring
- Add ProxySettingsDialog component (420 lines):
  * Configuration editor (address, port, timeout)
  * Provider priority management
  * Settings validation
- Add React hooks:
  * useProxyConfig: Manage proxy configuration state
  * useProxyStatus: Poll and display server status
- Add TypeScript types (types/proxy.ts):
  * Define ProxyConfig, ProxyStatus interfaces

Provider Integration:
- Extend Provider model with availability field (providers.rs):
  * Track provider health for failover logic
- Update ProviderCard UI to display proxy status
- Integrate proxy controls in Settings page

Dependencies:
- Add Axum 0.7 (async web framework)
- Add Tower 0.4 (middleware and service abstractions)
- Add Tower-HTTP (CORS layer)
- Add Tokio sync primitives (oneshot, RwLock)

Technical Details:
- Graceful shutdown via oneshot channel
- Shared state with Arc<RwLock<T>> for thread-safe config updates
- CORS enabled for cross-origin frontend access
- Request/response streaming support
- Automatic retry with exponential backoff (forwarder)
- API key extraction from multiple config formats (Claude/Codex/Gemini)

File Statistics:
- 41 files changed
- 3491 insertions(+), 41 deletions(-)
- Core modules: 1393 lines (server + forwarder + handlers)
- Frontend UI: 642 lines (ProxyPanel + ProxySettingsDialog)
- Database/DAO: 326 lines

This implementation provides the foundation for advanced features like:
- Multi-provider load balancing
- Automatic failover on provider errors
- Request logging and analytics
- Usage tracking and cost monitoring
This commit is contained in:
YoVinchen
2025-12-01 02:41:36 +08:00
parent 04a588694b
commit 4c94e70f97
41 changed files with 3491 additions and 41 deletions
+2
View File
@@ -74,6 +74,7 @@ function App() {
switchProvider,
deleteProvider,
saveUsageScript,
setProxyTarget,
} = useProviderActions(activeApp);
// 监听来自托盘菜单的切换事件
@@ -310,6 +311,7 @@ function App() {
appId={activeApp}
isLoading={isLoading}
onSwitch={switchProvider}
onSetProxyTarget={setProxyTarget}
onEdit={setEditingProvider}
onDelete={setConfirmDelete}
onDuplicate={handleDuplicateProvider}
+39 -7
View File
@@ -11,6 +11,8 @@ import { cn } from "@/lib/utils";
import { ProviderActions } from "@/components/providers/ProviderActions";
import { ProviderIcon } from "@/components/ProviderIcon";
import UsageFooter from "@/components/UsageFooter";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
interface DragHandleProps {
attributes: DraggableAttributes;
@@ -28,6 +30,7 @@ interface ProviderCardProps {
onConfigureUsage: (provider: Provider) => void;
onOpenWebsite: (url: string) => void;
onDuplicate: (provider: Provider) => void;
onSetProxyTarget: (provider: Provider) => void;
dragHandleProps?: DragHandleProps;
}
@@ -76,6 +79,7 @@ export function ProviderCard({
onConfigureUsage,
onOpenWebsite,
onDuplicate,
onSetProxyTarget,
dragHandleProps,
}: ProviderCardProps) {
const { t } = useTranslation();
@@ -164,14 +168,42 @@ export function ProviderCard({
</span>
)}
<span
className={cn(
"rounded-full bg-green-500/10 px-2 py-0.5 text-xs font-medium text-green-500 dark:text-green-400 transition-opacity duration-200",
isCurrent ? "opacity-100" : "opacity-0 pointer-events-none",
)}
{/* 代理目标开关 */}
<div
className="flex items-center gap-2 ml-2"
onClick={(e) => e.stopPropagation()}
>
{t("provider.currentlyUsing")}
</span>
<Switch
id={`proxy-target-switch-${provider.id}`}
checked={provider.isProxyTarget || false}
onCheckedChange={(checked) => {
if (checked && !provider.isProxyTarget) {
onSetProxyTarget(provider);
}
}}
disabled={provider.isProxyTarget}
className="scale-75 data-[state=checked]:bg-purple-500"
/>
{provider.isProxyTarget && (
<Label
htmlFor={`proxy-target-switch-${provider.id}`}
className="text-xs font-medium text-purple-500 dark:text-purple-400 cursor-pointer"
>
{t("provider.proxyTarget", { defaultValue: "代理目标" })}
</Label>
)}
{!provider.isProxyTarget && (
<Label
htmlFor={`proxy-target-switch-${provider.id}`}
className="text-xs text-muted-foreground cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity"
>
{t("provider.setAsProxyTarget", {
defaultValue: "设为代理",
})}
</Label>
)}
</div>
</div>
{displayUrl && (
@@ -24,6 +24,7 @@ interface ProviderListProps {
onOpenWebsite: (url: string) => void;
onCreate?: () => void;
isLoading?: boolean;
onSetProxyTarget: (provider: Provider) => void;
}
export function ProviderList({
@@ -38,6 +39,7 @@ export function ProviderList({
onOpenWebsite,
onCreate,
isLoading = false,
onSetProxyTarget,
}: ProviderListProps) {
const { sortedProviders, sensors, handleDragEnd } = useDragSort(
providers,
@@ -87,6 +89,7 @@ export function ProviderList({
onDuplicate={onDuplicate}
onConfigureUsage={onConfigureUsage}
onOpenWebsite={onOpenWebsite}
onSetProxyTarget={onSetProxyTarget}
/>
))}
</div>
@@ -105,6 +108,7 @@ interface SortableProviderCardProps {
onDuplicate: (provider: Provider) => void;
onConfigureUsage?: (provider: Provider) => void;
onOpenWebsite: (url: string) => void;
onSetProxyTarget: (provider: Provider) => void;
}
function SortableProviderCard({
@@ -117,6 +121,7 @@ function SortableProviderCard({
onDuplicate,
onConfigureUsage,
onOpenWebsite,
onSetProxyTarget,
}: SortableProviderCardProps) {
const {
setNodeRef,
@@ -146,6 +151,7 @@ function SortableProviderCard({
onConfigureUsage ? (item) => onConfigureUsage(item) : () => undefined
}
onOpenWebsite={onOpenWebsite}
onSetProxyTarget={onSetProxyTarget}
dragHandleProps={{
attributes,
listeners,
+222
View File
@@ -0,0 +1,222 @@
import { useState } from "react";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
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";
export function ProxyPanel() {
const { status, isRunning, start, stop, isPending } = 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 formatUptime = (seconds: number): string => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
if (hours > 0) {
return `${hours}h ${minutes}m ${secs}s`;
} else if (minutes > 0) {
return `${minutes}m ${secs}s`;
} else {
return `${secs}s`;
}
};
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>
{isRunning && status ? (
<div className="space-y-6">
<div className="rounded-lg border border-white/10 bg-muted/40 p-4 space-y-4">
<div>
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
</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}
</code>
<Button
size="sm"
variant="outline"
onClick={() => {
navigator.clipboard.writeText(
`http://${status.address}:${status.port}`,
);
toast.success("地址已复制");
}}
>
</Button>
</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>
{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"
>
<span className="text-muted-foreground">
{target.app_type}
</span>
<span
className="ml-2 font-medium truncate text-foreground"
title={target.provider_name}
>
{target.provider_name}
</span>
</div>
))}
</div>
) : status.current_provider ? (
<p className="text-sm text-muted-foreground">
Provider{" "}
<span className="font-medium text-foreground">
{status.current_provider}
</span>
</p>
) : (
<p className="text-sm text-yellow-600 dark:text-yellow-400">
Provider
</p>
)}
</div>
</div>
<div className="grid gap-3 md:grid-cols-4">
<StatCard
icon={<Activity className="h-4 w-4" />}
label="活跃连接"
value={status.active_connections}
/>
<StatCard
icon={<TrendingUp className="h-4 w-4" />}
label="总请求数"
value={status.total_requests}
/>
<StatCard
icon={<Clock className="h-4 w-4" />}
label="成功率"
value={`${status.success_rate.toFixed(1)}%`}
variant={status.success_rate > 90 ? "success" : "warning"}
/>
<StatCard
icon={<Clock className="h-4 w-4" />}
label="运行时间"
value={formatUptime(status.uptime_seconds)}
/>
</div>
</div>
) : (
<div className="text-center py-10 text-muted-foreground">
<div className="mx-auto w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4">
<Server className="h-8 w-8" />
</div>
<p className="text-base font-medium text-foreground mb-1">
</p>
<p className="text-sm text-muted-foreground">
使
</p>
</div>
)}
</section>
<ProxySettingsDialog open={showSettings} onOpenChange={setShowSettings} />
</>
);
}
interface StatCardProps {
icon: React.ReactNode;
label: string;
value: string | number;
variant?: "default" | "success" | "warning";
}
function StatCard({ icon, label, value, variant = "default" }: StatCardProps) {
const variantStyles = {
default: "",
success: "border-green-500/40 bg-green-500/5",
warning: "border-yellow-500/40 bg-yellow-500/5",
};
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]}`}
>
<div className="flex items-center gap-2 text-muted-foreground mb-2">
{icon}
<span className="text-xs font-medium uppercase tracking-wide">
{label}
</span>
</div>
<p className="text-xl font-semibold text-foreground">{value}</p>
</div>
);
}
@@ -0,0 +1,420 @@
/**
* 代理服务设置对话框
*/
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormDescription,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useProxyConfig } from "@/hooks/useProxyConfig";
import { useEffect, useMemo } from "react";
import { AlertCircle } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { FullScreenPanel } from "@/components/common/FullScreenPanel";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import type { ProxyConfig } from "@/types/proxy";
type ProxyConfigForm = ProxyConfig;
const createProxyConfigSchema = (t: TFunction) => {
const requestTimeoutSchema = z
.number()
.min(
0,
t("proxy.settings.validation.timeoutNonNegative", {
defaultValue: "超时时间不能为负数",
}),
)
.max(
600,
t("proxy.settings.validation.timeoutMax", {
defaultValue: "超时时间最多600秒",
}),
)
.refine((value) => value === 0 || value >= 10, {
message: t("proxy.settings.validation.timeoutRange", {
defaultValue: "请输入 0 或 10-600 之间的数值",
}),
});
return z.object({
enabled: z.boolean(),
listen_address: z.string().regex(
/^(\d{1,3}\.){3}\d{1,3}$/,
t("proxy.settings.validation.addressInvalid", {
defaultValue: "请输入有效的IP地址",
}),
),
listen_port: z
.number()
.min(
1024,
t("proxy.settings.validation.portMin", {
defaultValue: "端口必须大于1024",
}),
)
.max(
65535,
t("proxy.settings.validation.portMax", {
defaultValue: "端口必须小于65535",
}),
),
max_retries: z
.number()
.min(
0,
t("proxy.settings.validation.retryMin", {
defaultValue: "重试次数不能为负",
}),
)
.max(
10,
t("proxy.settings.validation.retryMax", {
defaultValue: "重试次数不能超过10",
}),
),
request_timeout: requestTimeoutSchema,
enable_logging: z.boolean(),
});
};
interface ProxySettingsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function ProxySettingsDialog({
open,
onOpenChange,
}: ProxySettingsDialogProps) {
const { config, isLoading, updateConfig, isUpdating } = useProxyConfig();
const { t } = useTranslation();
const schema = useMemo(() => createProxyConfigSchema(t), [t]);
const closePanel = () => onOpenChange(false);
const form = useForm<ProxyConfigForm>({
resolver: zodResolver(schema),
defaultValues: {
enabled: false,
listen_address: "127.0.0.1",
listen_port: 5000,
max_retries: 3,
request_timeout: 300,
enable_logging: true,
},
});
// 当配置加载完成后更新表单
useEffect(() => {
if (config) {
form.reset({
...config,
});
}
}, [config, form]);
const onSubmit = async (data: ProxyConfigForm) => {
try {
await updateConfig(data);
closePanel();
} catch (error) {
console.error("Save config failed:", error);
}
};
const formId = "proxy-settings-form";
return (
<FullScreenPanel
isOpen={open}
title={t("proxy.settings.title", { defaultValue: "代理服务设置" })}
onClose={closePanel}
footer={
<>
<Button
type="button"
variant="outline"
onClick={closePanel}
disabled={isUpdating}
>
{t("common.cancel", { defaultValue: "取消" })}
</Button>
<Button
type="submit"
form={formId}
disabled={isUpdating || isLoading}
>
{isUpdating
? t("common.saving", { defaultValue: "保存中..." })
: t("proxy.settings.actions.save", { defaultValue: "保存配置" })}
</Button>
</>
}
>
<div className="space-y-6">
<p className="text-sm text-muted-foreground">
{t("proxy.settings.description", {
defaultValue:
"配置本地代理服务器的监听地址、端口和运行参数,保存后立即生效。",
})}
</p>
<Alert className="border-emerald-500/40 bg-emerald-500/10">
<AlertCircle className="h-4 w-4" />
<AlertDescription className="text-sm">
{t("proxy.settings.alert.autoApply", {
defaultValue:
"保存后将自动同步到正在运行的代理服务,无需手动重启。",
})}
</AlertDescription>
</Alert>
<Form {...form}>
<form
id={formId}
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-6"
>
<section className="space-y-4 rounded-xl border border-white/10 glass-card p-6">
<div>
<h3 className="text-base font-semibold text-foreground">
{t("proxy.settings.basic.title", {
defaultValue: "基础设置",
})}
</h3>
<p className="text-sm text-muted-foreground">
{t("proxy.settings.basic.description", {
defaultValue: "控制代理服务是否启用以及监听的地址与端口。",
})}
</p>
</div>
<FormField
control={form.control}
name="enabled"
render={({ field }) => (
<FormItem className="flex items-center justify-between rounded-lg border border-white/10 bg-background/60 p-4">
<div className="space-y-1">
<FormLabel>
{t("proxy.settings.fields.enabled.label", {
defaultValue: "启用代理服务",
})}
</FormLabel>
<FormDescription>
{t("proxy.settings.fields.enabled.description", {
defaultValue: "开启后可以从命令或 UI 启动代理服务器",
})}
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<div className="grid gap-4 md:grid-cols-2">
<FormField
control={form.control}
name="listen_address"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("proxy.settings.fields.listenAddress.label", {
defaultValue: "监听地址",
})}
</FormLabel>
<FormControl>
<Input
{...field}
placeholder={t(
"proxy.settings.fields.listenAddress.placeholder",
{ defaultValue: "127.0.0.1" },
)}
disabled={isLoading}
/>
</FormControl>
<FormDescription>
{t("proxy.settings.fields.listenAddress.description", {
defaultValue:
"代理服务器监听的 IP 地址(推荐 127.0.0.1",
})}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="listen_port"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("proxy.settings.fields.listenPort.label", {
defaultValue: "监听端口",
})}
</FormLabel>
<FormControl>
<Input
type="number"
inputMode="numeric"
{...field}
onChange={(e) =>
field.onChange(parseInt(e.target.value, 10) || 0)
}
placeholder={t(
"proxy.settings.fields.listenPort.placeholder",
{ defaultValue: "5000" },
)}
disabled={isLoading}
/>
</FormControl>
<FormDescription>
{t("proxy.settings.fields.listenPort.description", {
defaultValue:
"代理服务器监听的端口号(1024 ~ 65535",
})}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
</section>
<section className="space-y-4 rounded-xl border border-white/10 glass-card p-6">
<div>
<h3 className="text-base font-semibold text-foreground">
{t("proxy.settings.advanced.title", {
defaultValue: "高级参数",
})}
</h3>
<p className="text-sm text-muted-foreground">
{t("proxy.settings.advanced.description", {
defaultValue: "控制请求的稳定性和日志记录。",
})}
</p>
</div>
<div className="grid gap-4 md:grid-cols-2">
<FormField
control={form.control}
name="max_retries"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("proxy.settings.fields.maxRetries.label", {
defaultValue: "最大重试次数",
})}
</FormLabel>
<FormControl>
<Input
type="number"
inputMode="numeric"
{...field}
onChange={(e) =>
field.onChange(parseInt(e.target.value, 10) || 0)
}
placeholder={t(
"proxy.settings.fields.maxRetries.placeholder",
{ defaultValue: "3" },
)}
disabled={isLoading}
/>
</FormControl>
<FormDescription>
{t("proxy.settings.fields.maxRetries.description", {
defaultValue: "请求失败时的重试次数(0 ~ 10)",
})}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="request_timeout"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("proxy.settings.fields.requestTimeout.label", {
defaultValue: "请求超时(秒)",
})}
</FormLabel>
<FormControl>
<Input
type="number"
inputMode="numeric"
{...field}
onChange={(e) =>
field.onChange(parseInt(e.target.value, 10) || 0)
}
placeholder={t(
"proxy.settings.fields.requestTimeout.placeholder",
{ defaultValue: "0(不限)或 300" },
)}
disabled={isLoading}
/>
</FormControl>
<FormDescription>
{t("proxy.settings.fields.requestTimeout.description", {
defaultValue:
"单个请求的最大等待时间(0 表示不限制,或设置 10 ~ 600 秒)",
})}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="enable_logging"
render={({ field }) => (
<FormItem className="flex items-center justify-between rounded-lg border border-white/10 bg-background/60 p-4">
<div className="space-y-1">
<FormLabel>
{t("proxy.settings.fields.enableLogging.label", {
defaultValue: "启用日志记录",
})}
</FormLabel>
<FormDescription>
{t("proxy.settings.fields.enableLogging.description", {
defaultValue: "记录所有代理请求,便于排查问题",
})}
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</section>
</form>
</Form>
</div>
</FullScreenPanel>
);
}
+6
View File
@@ -0,0 +1,6 @@
/**
* 代理功能组件导出
*/
export { ProxyPanel } from "./ProxyPanel";
export { ProxySettingsDialog } from "./ProxySettingsDialog";
+5
View File
@@ -17,6 +17,7 @@ import { WindowSettings } from "@/components/settings/WindowSettings";
import { DirectorySettings } from "@/components/settings/DirectorySettings";
import { ImportExportSection } from "@/components/settings/ImportExportSection";
import { AboutSection } from "@/components/settings/AboutSection";
import { ProxyPanel } from "@/components/proxy";
import { useSettings } from "@/hooks/useSettings";
import { useImportExport } from "@/hooks/useImportExport";
import { useTranslation } from "react-i18next";
@@ -205,6 +206,10 @@ export function SettingsPage({
onBrowseDirectory={browseDirectory}
onResetDirectory={resetDirectory}
/>
{/* 代理服务面板 */}
<ProxyPanel />
<ImportExportSection
status={importStatus}
selectedFile={selectedFile}
+59
View File
@@ -0,0 +1,59 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };
+13 -1
View File
@@ -9,6 +9,7 @@ import {
useUpdateProviderMutation,
useDeleteProviderMutation,
useSwitchProviderMutation,
useSetProxyTargetMutation,
} from "@/lib/query";
import { extractErrorMessage } from "@/utils/errorUtils";
@@ -24,6 +25,7 @@ export function useProviderActions(activeApp: AppId) {
const updateProviderMutation = useUpdateProviderMutation(activeApp);
const deleteProviderMutation = useDeleteProviderMutation(activeApp);
const switchProviderMutation = useSwitchProviderMutation(activeApp);
const setProxyTargetMutation = useSetProxyTargetMutation(activeApp);
// Claude 插件同步逻辑
const syncClaudePlugin = useCallback(
@@ -91,6 +93,14 @@ export function useProviderActions(activeApp: AppId) {
[switchProviderMutation, syncClaudePlugin],
);
// 设置代理目标
const setProxyTarget = useCallback(
async (provider: Provider) => {
await setProxyTargetMutation.mutateAsync(provider.id);
},
[setProxyTargetMutation],
);
// 删除供应商
const deleteProvider = useCallback(
async (id: string) => {
@@ -136,12 +146,14 @@ export function useProviderActions(activeApp: AppId) {
addProvider,
updateProvider,
switchProvider,
setProxyTarget,
deleteProvider,
saveUsageScript,
isLoading:
addProviderMutation.isPending ||
updateProviderMutation.isPending ||
deleteProviderMutation.isPending ||
switchProviderMutation.isPending,
switchProviderMutation.isPending ||
setProxyTargetMutation.isPending,
};
}
+42
View File
@@ -0,0 +1,42 @@
/**
* 代理配置管理 Hook
*/
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { invoke } from "@tauri-apps/api/core";
import { toast } from "sonner";
import type { ProxyConfig } from "@/types/proxy";
/**
* 代理配置管理
*/
export function useProxyConfig() {
const queryClient = useQueryClient();
// 查询配置
const { data: config, isLoading } = useQuery({
queryKey: ["proxyConfig"],
queryFn: () => invoke<ProxyConfig>("get_proxy_config"),
});
// 更新配置
const updateMutation = useMutation({
mutationFn: (newConfig: ProxyConfig) =>
invoke("update_proxy_config", { config: newConfig }),
onSuccess: () => {
toast.success("代理配置已保存");
queryClient.invalidateQueries({ queryKey: ["proxyConfig"] });
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
},
onError: (error: Error) => {
toast.error(`保存失败: ${error.message}`);
},
});
return {
config,
isLoading,
updateConfig: updateMutation.mutateAsync,
isUpdating: updateMutation.isPending,
};
}
+70
View File
@@ -0,0 +1,70 @@
/**
* 代理服务状态管理 Hook
*/
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { invoke } from "@tauri-apps/api/core";
import { toast } from "sonner";
import type { ProxyStatus, ProxyServerInfo } from "@/types/proxy";
/**
* 代理服务状态管理
*/
export function useProxyStatus() {
const queryClient = useQueryClient();
// 查询状态(自动轮询)
const { data: status, isLoading } = useQuery({
queryKey: ["proxyStatus"],
queryFn: () => invoke<ProxyStatus>("get_proxy_status"),
// 仅在服务运行时轮询
refetchInterval: (query) => (query.state.data?.running ? 2000 : false),
// 保持之前的数据,避免闪烁
placeholderData: (previousData) => previousData,
});
// 启动服务器
const startMutation = useMutation({
mutationFn: () => invoke<ProxyServerInfo>("start_proxy_server"),
onSuccess: (info) => {
toast.success(`代理服务已启动 - ${info.address}:${info.port}`);
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
},
onError: (error: Error) => {
toast.error(`启动失败: ${error.message}`);
},
});
// 停止服务器
const stopMutation = useMutation({
mutationFn: () => invoke("stop_proxy_server"),
onSuccess: () => {
toast.success("代理服务已停止");
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
},
onError: (error: Error) => {
toast.error(`停止失败: ${error.message}`);
},
});
// 检查是否运行中
const checkRunning = async () => {
try {
return await invoke<boolean>("is_proxy_running");
} catch {
return false;
}
};
return {
status,
isLoading,
isRunning: status?.running || false,
start: startMutation.mutateAsync,
stop: stopMutation.mutateAsync,
checkRunning,
isStarting: startMutation.isPending,
isStopping: stopMutation.isPending,
isPending: startMutation.isPending || stopMutation.isPending,
};
}
+4
View File
@@ -38,6 +38,10 @@ export const providersApi = {
return await invoke("switch_provider", { id, app: appId });
},
async setProxyTarget(id: string, appId: AppId): Promise<boolean> {
return await invoke("set_proxy_target_provider", { id, app: appId });
},
async importDefault(appId: AppId): Promise<boolean> {
return await invoke("import_default_config", { app: appId });
},
+28
View File
@@ -167,6 +167,34 @@ export const useSwitchProviderMutation = (appId: AppId) => {
});
};
export const useSetProxyTargetMutation = (appId: AppId) => {
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: async (providerId: string) => {
return await providersApi.setProxyTarget(providerId, appId);
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["providers", appId] });
toast.success(
t("notifications.proxyTargetSet", {
defaultValue: "已设置代理目标",
}),
);
},
onError: (error: Error) => {
const detail = extractErrorMessage(error) || t("common.unknown");
toast.error(
t("notifications.setProxyTargetFailed", {
defaultValue: "设置代理目标失败: {{error}}",
error: detail,
}),
);
},
});
};
export const useSaveSettingsMutation = () => {
const queryClient = useQueryClient();
+2
View File
@@ -23,6 +23,8 @@ export interface Provider {
// 图标配置
icon?: string; // 图标名称(如 "openai", "anthropic"
iconColor?: string; // 图标颜色(Hex 格式,如 "#00A67E"
// 新增:是否为代理目标
isProxyTarget?: boolean;
}
export interface AppConfig {
+61
View File
@@ -0,0 +1,61 @@
export interface ProxyConfig {
enabled: boolean;
listen_address: string;
listen_port: number;
max_retries: number;
request_timeout: number;
enable_logging: boolean;
}
export interface ProxyStatus {
running: boolean;
address: string;
port: number;
active_connections: number;
total_requests: number;
success_requests: number;
failed_requests: number;
success_rate: number;
uptime_seconds: number;
current_provider: string | null;
current_provider_id: string | null;
last_request_at: string | null;
last_error: string | null;
failover_count: number;
active_targets?: ActiveTarget[];
}
export interface ActiveTarget {
app_type: string;
provider_name: string;
provider_id: string;
}
export interface ProxyServerInfo {
address: string;
port: number;
started_at: string;
}
export interface ProviderHealth {
provider_id: string;
app_type: string;
is_healthy: boolean;
consecutive_failures: number;
last_success_at: string | null;
last_failure_at: string | null;
last_error: string | null;
updated_at: string;
}
export interface ProxyUsageRecord {
provider_id: string;
app_type: string;
endpoint: string;
request_tokens: number | null;
response_tokens: number | null;
status_code: number;
latency_ms: number;
error: string | null;
timestamp: string;
}