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:
+11
-5
@@ -23,6 +23,7 @@ import {
|
||||
} from "@/lib/api";
|
||||
import { checkAllEnvConflicts, checkEnvConflicts } from "@/lib/api/env";
|
||||
import { useProviderActions } from "@/hooks/useProviderActions";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
import { AppSwitcher } from "@/components/AppSwitcher";
|
||||
import { ProviderList } from "@/components/providers/ProviderList";
|
||||
@@ -61,7 +62,13 @@ function App() {
|
||||
const addActionButtonClass =
|
||||
"bg-orange-500 hover:bg-orange-600 dark:bg-orange-500 dark:hover:bg-orange-600 text-white shadow-lg shadow-orange-500/30 dark:shadow-orange-500/40 rounded-full w-8 h-8";
|
||||
|
||||
const { data, isLoading, refetch } = useProvidersQuery(activeApp);
|
||||
// 获取代理服务状态
|
||||
const { isRunning: isProxyRunning } = useProxyStatus();
|
||||
|
||||
// 获取供应商列表,当代理服务运行时自动刷新
|
||||
const { data, isLoading, refetch } = useProvidersQuery(activeApp, {
|
||||
isProxyRunning,
|
||||
});
|
||||
const providers = useMemo(() => data?.providers ?? {}, [data]);
|
||||
const currentProviderId = data?.currentProviderId ?? "";
|
||||
// Skills 功能仅支持 Claude 和 Codex
|
||||
@@ -74,7 +81,6 @@ function App() {
|
||||
switchProvider,
|
||||
deleteProvider,
|
||||
saveUsageScript,
|
||||
setProxyTarget,
|
||||
} = useProviderActions(activeApp);
|
||||
|
||||
// 监听来自托盘菜单的切换事件
|
||||
@@ -314,8 +320,8 @@ function App() {
|
||||
currentProviderId={currentProviderId}
|
||||
appId={activeApp}
|
||||
isLoading={isLoading}
|
||||
isProxyRunning={isProxyRunning}
|
||||
onSwitch={switchProvider}
|
||||
onSetProxyTarget={setProxyTarget}
|
||||
onEdit={setEditingProvider}
|
||||
onDelete={setConfirmDelete}
|
||||
onDuplicate={handleDuplicateProvider}
|
||||
@@ -369,7 +375,7 @@ function App() {
|
||||
)}
|
||||
|
||||
<header
|
||||
className="glass-header fixed top-0 z-50 w-full py-3 transition-all duration-300"
|
||||
className="fixed top-0 z-50 w-full py-3 bg-background/80 backdrop-blur-md transition-all duration-300"
|
||||
data-tauri-drag-region
|
||||
style={{ WebkitAppRegion: "drag" } as any}
|
||||
>
|
||||
@@ -478,7 +484,7 @@ function App() {
|
||||
<>
|
||||
<AppSwitcher activeApp={activeApp} onSwitch={setActiveApp} />
|
||||
|
||||
<div className="glass p-1 rounded-xl flex items-center gap-1">
|
||||
<div className="bg-muted p-1 rounded-xl flex items-center gap-1">
|
||||
{hasSkillsSupport && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -24,14 +24,14 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="inline-flex bg-gray-100 dark:bg-gray-800 rounded-lg p-1 gap-1">
|
||||
<div className="inline-flex bg-muted rounded-lg p-1 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("claude")}
|
||||
className={`group inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
activeApp === "claude"
|
||||
? "bg-white text-gray-900 shadow-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-background/50"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
@@ -41,7 +41,7 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
className={
|
||||
activeApp === "claude"
|
||||
? "text-foreground"
|
||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.claude}</span>
|
||||
@@ -50,10 +50,10 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("codex")}
|
||||
className={`inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
className={`group inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
activeApp === "codex"
|
||||
? "bg-white text-gray-900 shadow-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-background/50"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
@@ -63,7 +63,7 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
className={
|
||||
activeApp === "codex"
|
||||
? "text-foreground"
|
||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.codex}</span>
|
||||
@@ -72,10 +72,10 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleSwitch("gemini")}
|
||||
className={`inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
className={`group inline-flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-all duration-200 ${
|
||||
activeApp === "gemini"
|
||||
? "bg-white text-gray-900 shadow-sm dark:bg-gray-900 dark:text-gray-100"
|
||||
: "text-gray-500 hover:text-gray-900 hover:bg-white/50 dark:text-gray-400 dark:hover:text-gray-100 dark:hover:bg-gray-800/60"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-background/50"
|
||||
}`}
|
||||
>
|
||||
<ProviderIcon
|
||||
@@ -85,7 +85,7 @@ export function AppSwitcher({ activeApp, onSwitch }: AppSwitcherProps) {
|
||||
className={
|
||||
activeApp === "gemini"
|
||||
? "text-foreground"
|
||||
: "text-gray-500 dark:text-gray-400 group-hover:text-foreground transition-colors"
|
||||
: "text-muted-foreground group-hover:text-foreground transition-colors"
|
||||
}
|
||||
/>
|
||||
<span>{appDisplayName.gemini}</span>
|
||||
|
||||
@@ -33,13 +33,23 @@ export function EditProviderDialog({
|
||||
unknown
|
||||
> | null>(null);
|
||||
|
||||
// 使用 ref 标记是否已经加载过,防止重复读取覆盖用户编辑
|
||||
const [hasLoadedLive, setHasLoadedLive] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const load = async () => {
|
||||
if (!open || !provider) {
|
||||
setLiveSettings(null);
|
||||
setHasLoadedLive(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 关键修复:只在首次打开时加载一次
|
||||
if (hasLoadedLive) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const currentId = await providersApi.getCurrent(appId);
|
||||
if (currentId && provider.id === currentId) {
|
||||
@@ -49,13 +59,20 @@ export function EditProviderDialog({
|
||||
)) as Record<string, unknown>;
|
||||
if (!cancelled && live && typeof live === "object") {
|
||||
setLiveSettings(live);
|
||||
setHasLoadedLive(true);
|
||||
}
|
||||
} catch {
|
||||
// 读取实时配置失败则回退到 SSOT(不打断编辑流程)
|
||||
if (!cancelled) setLiveSettings(null);
|
||||
if (!cancelled) {
|
||||
setLiveSettings(null);
|
||||
setHasLoadedLive(true);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!cancelled) setLiveSettings(null);
|
||||
if (!cancelled) {
|
||||
setLiveSettings(null);
|
||||
setHasLoadedLive(true);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// no-op
|
||||
@@ -65,14 +82,33 @@ export function EditProviderDialog({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, provider, appId]);
|
||||
}, [open, provider?.id, appId, hasLoadedLive]); // 只依赖 provider.id,不依赖整个 provider 对象
|
||||
|
||||
const initialSettingsConfig = useMemo(() => {
|
||||
return (liveSettings ?? provider?.settingsConfig ?? {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
}, [liveSettings, provider]);
|
||||
}, [liveSettings, provider?.settingsConfig]); // 只依赖 settingsConfig,不依赖整个 provider
|
||||
|
||||
// 固定 initialData,防止 provider 对象更新时重置表单
|
||||
const initialData = useMemo(() => {
|
||||
if (!provider) return null;
|
||||
return {
|
||||
name: provider.name,
|
||||
notes: provider.notes,
|
||||
websiteUrl: provider.websiteUrl,
|
||||
settingsConfig: initialSettingsConfig,
|
||||
category: provider.category,
|
||||
meta: provider.meta,
|
||||
icon: provider.icon,
|
||||
iconColor: provider.iconColor,
|
||||
};
|
||||
}, [
|
||||
provider?.id, // 只依赖 ID,provider 对象更新不会触发重新计算
|
||||
initialSettingsConfig,
|
||||
// 注意:不依赖 provider 的其他字段,防止表单重置
|
||||
]);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (values: ProviderFormValues) => {
|
||||
@@ -104,7 +140,7 @@ export function EditProviderDialog({
|
||||
[onSubmit, onOpenChange, provider],
|
||||
);
|
||||
|
||||
if (!provider) {
|
||||
if (!provider || !initialData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -130,17 +166,7 @@ export function EditProviderDialog({
|
||||
submitLabel={t("common.save")}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
initialData={{
|
||||
name: provider.name,
|
||||
notes: provider.notes,
|
||||
websiteUrl: provider.websiteUrl,
|
||||
// 若读取到实时配置则优先使用
|
||||
settingsConfig: initialSettingsConfig,
|
||||
category: provider.category,
|
||||
meta: provider.meta,
|
||||
icon: provider.icon,
|
||||
iconColor: provider.iconColor,
|
||||
}}
|
||||
initialData={initialData}
|
||||
showButtons={false}
|
||||
/>
|
||||
</FullScreenPanel>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
Play,
|
||||
TestTube2,
|
||||
Trash2,
|
||||
RotateCcw,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -21,6 +22,9 @@ interface ProviderActionsProps {
|
||||
onTest?: () => void;
|
||||
onConfigureUsage: () => void;
|
||||
onDelete: () => void;
|
||||
onResetCircuitBreaker?: () => void;
|
||||
isProxyTarget?: boolean;
|
||||
consecutiveFailures?: number;
|
||||
}
|
||||
|
||||
export function ProviderActions({
|
||||
@@ -32,6 +36,9 @@ export function ProviderActions({
|
||||
onTest,
|
||||
onConfigureUsage,
|
||||
onDelete,
|
||||
onResetCircuitBreaker,
|
||||
isProxyTarget,
|
||||
consecutiveFailures = 0,
|
||||
}: ProviderActionsProps) {
|
||||
const { t } = useTranslation();
|
||||
const iconButtonClass = "h-8 w-8 p-1";
|
||||
@@ -110,6 +117,32 @@ export function ProviderActions({
|
||||
<BarChart3 className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
{/* 重置熔断器按钮 - 代理目标启用时显示 */}
|
||||
{onResetCircuitBreaker && isProxyTarget && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
onClick={onResetCircuitBreaker}
|
||||
disabled={consecutiveFailures === 0}
|
||||
title={
|
||||
consecutiveFailures > 0
|
||||
? t("provider.resetCircuitBreaker", {
|
||||
defaultValue: "重置熔断器",
|
||||
})
|
||||
: t("provider.noFailures", {
|
||||
defaultValue: "当前无失败记录",
|
||||
})
|
||||
}
|
||||
className={cn(
|
||||
iconButtonClass,
|
||||
consecutiveFailures > 0 &&
|
||||
"hover:text-orange-500 dark:hover:text-orange-400",
|
||||
)}
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
|
||||
@@ -13,6 +13,13 @@ import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
import UsageFooter from "@/components/UsageFooter";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ProviderHealthBadge } from "@/components/providers/ProviderHealthBadge";
|
||||
import {
|
||||
useProviderHealth,
|
||||
useResetCircuitBreaker,
|
||||
useSetProxyTarget,
|
||||
} from "@/lib/query/failover";
|
||||
import { toast } from "sonner";
|
||||
|
||||
interface DragHandleProps {
|
||||
attributes: DraggableAttributes;
|
||||
@@ -32,8 +39,9 @@ interface ProviderCardProps {
|
||||
onDuplicate: (provider: Provider) => void;
|
||||
onTest?: (provider: Provider) => void;
|
||||
isTesting?: boolean;
|
||||
onSetProxyTarget: (provider: Provider) => void;
|
||||
isProxyRunning: boolean;
|
||||
proxyPriority?: number; // 代理目标的实际优先级 (1, 2, 3...)
|
||||
allProviders?: Provider[]; // 所有供应商列表,用于计算开启后的优先级
|
||||
dragHandleProps?: DragHandleProps;
|
||||
}
|
||||
|
||||
@@ -84,12 +92,109 @@ export function ProviderCard({
|
||||
onDuplicate,
|
||||
onTest,
|
||||
isTesting,
|
||||
onSetProxyTarget,
|
||||
isProxyRunning,
|
||||
proxyPriority,
|
||||
allProviders,
|
||||
dragHandleProps,
|
||||
}: ProviderCardProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 获取供应商健康状态
|
||||
const { data: health } = useProviderHealth(provider.id, appId);
|
||||
|
||||
// 设置代理目标
|
||||
const setProxyTargetMutation = useSetProxyTarget();
|
||||
|
||||
// 重置熔断器
|
||||
const resetCircuitBreaker = useResetCircuitBreaker();
|
||||
|
||||
const handleSetProxyTarget = async (enabled: boolean) => {
|
||||
try {
|
||||
await setProxyTargetMutation.mutateAsync({
|
||||
providerId: provider.id,
|
||||
appType: appId,
|
||||
enabled,
|
||||
});
|
||||
|
||||
// 计算实际优先级(开启时)
|
||||
let actualPriority: number | undefined;
|
||||
if (enabled && allProviders) {
|
||||
// 模拟开启后的状态:获取所有将要启用代理的 providers
|
||||
const futureProxyTargets = allProviders.filter((p) => {
|
||||
// 包括:已经是代理目标的 或 当前要开启的这个
|
||||
if (p.id === provider.id) return true;
|
||||
return p.isProxyTarget;
|
||||
});
|
||||
|
||||
// 按 sortIndex 排序
|
||||
const sortedTargets = futureProxyTargets.sort((a, b) => {
|
||||
const indexA = a.sortIndex ?? Number.MAX_SAFE_INTEGER;
|
||||
const indexB = b.sortIndex ?? Number.MAX_SAFE_INTEGER;
|
||||
return indexA - indexB;
|
||||
});
|
||||
|
||||
// 找到当前 provider 的位置
|
||||
const position = sortedTargets.findIndex((p) => p.id === provider.id);
|
||||
actualPriority = position >= 0 ? position + 1 : undefined;
|
||||
}
|
||||
|
||||
const message = enabled
|
||||
? actualPriority
|
||||
? t("provider.proxyTargetEnabled", {
|
||||
defaultValue: `已启用代理目标(优先级:P${actualPriority})`,
|
||||
})
|
||||
: t("provider.proxyTargetEnabled", {
|
||||
defaultValue: "已启用代理目标",
|
||||
})
|
||||
: t("provider.proxyTargetDisabled", {
|
||||
defaultValue: "已禁用代理目标",
|
||||
});
|
||||
|
||||
const description = enabled
|
||||
? t("provider.proxyTargetEnabledDesc", {
|
||||
defaultValue: "下次请求将按优先级自动选择此供应商",
|
||||
})
|
||||
: t("provider.proxyTargetDisabledDesc", {
|
||||
defaultValue: "后续请求将使用其他可用供应商",
|
||||
});
|
||||
|
||||
toast.success(message, {
|
||||
description,
|
||||
duration: 4000,
|
||||
});
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("provider.setProxyTargetFailed", {
|
||||
defaultValue: "操作失败",
|
||||
}) +
|
||||
": " +
|
||||
String(error),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetCircuitBreaker = async () => {
|
||||
try {
|
||||
await resetCircuitBreaker.mutateAsync({
|
||||
providerId: provider.id,
|
||||
appType: appId,
|
||||
});
|
||||
toast.success(
|
||||
t("provider.circuitBreakerReset", {
|
||||
defaultValue: "熔断器已重置",
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("provider.circuitBreakerResetFailed", {
|
||||
defaultValue: "重置失败",
|
||||
}) +
|
||||
": " +
|
||||
String(error),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const fallbackUrlText = t("provider.notConfigured", {
|
||||
defaultValue: "未配置接口地址",
|
||||
});
|
||||
@@ -124,9 +229,9 @@ export function ProviderCard({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"glass-card relative overflow-hidden rounded-xl p-4 transition-all duration-300",
|
||||
"group hover:bg-black/[0.02] dark:hover:bg-white/[0.02] hover:border-primary/50",
|
||||
isCurrent ? "glass-card-active" : "hover:scale-[1.01]",
|
||||
"relative overflow-hidden rounded-xl border border-border p-4 transition-all duration-300",
|
||||
"bg-card text-card-foreground group hover:border-border-active",
|
||||
isCurrent ? "border-primary/50 shadow-sm" : "hover:shadow-sm",
|
||||
dragHandleProps?.isDragging &&
|
||||
"cursor-grabbing border-primary shadow-lg scale-105 z-10",
|
||||
)}
|
||||
@@ -149,7 +254,7 @@ export function ProviderCard({
|
||||
</button>
|
||||
|
||||
{/* 供应商图标 */}
|
||||
<div className="h-8 w-8 rounded-lg bg-white/5 flex items-center justify-center border border-gray-200 dark:border-white/10 group-hover:scale-105 transition-transform duration-300">
|
||||
<div className="h-8 w-8 rounded-lg bg-muted flex items-center justify-center border border-border group-hover:scale-105 transition-transform duration-300">
|
||||
<ProviderIcon
|
||||
icon={provider.icon}
|
||||
name={provider.name}
|
||||
@@ -163,6 +268,29 @@ export function ProviderCard({
|
||||
<h3 className="text-base font-semibold leading-none">
|
||||
{provider.name}
|
||||
</h3>
|
||||
|
||||
{/* 健康状态徽章和优先级 */}
|
||||
{isProxyRunning && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{/* 健康徽章:代理目标启用时始终显示,没有健康数据时默认为正常(0失败) */}
|
||||
{(provider.isProxyTarget || health) && (
|
||||
<ProviderHealthBadge
|
||||
consecutiveFailures={health?.consecutive_failures ?? 0}
|
||||
isProxyTarget={provider.isProxyTarget ?? false}
|
||||
/>
|
||||
)}
|
||||
{/* 优先级:仅在代理目标启用时显示 */}
|
||||
{provider.isProxyTarget && proxyPriority && (
|
||||
<span
|
||||
className="text-xs text-muted-foreground"
|
||||
title={`代理队列优先级:第${proxyPriority}位`}
|
||||
>
|
||||
P{proxyPriority}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{provider.category === "third_party" &&
|
||||
provider.meta?.isPartner && (
|
||||
<span
|
||||
@@ -185,17 +313,15 @@ export function ProviderCard({
|
||||
id={`proxy-target-switch-${provider.id}`}
|
||||
checked={provider.isProxyTarget || false}
|
||||
onCheckedChange={(checked) => {
|
||||
if (checked && !provider.isProxyTarget) {
|
||||
onSetProxyTarget(provider);
|
||||
}
|
||||
handleSetProxyTarget(checked);
|
||||
}}
|
||||
disabled={provider.isProxyTarget}
|
||||
className="scale-75 data-[state=checked]:bg-purple-500"
|
||||
disabled={setProxyTargetMutation.isPending}
|
||||
className="scale-75 data-[state=checked]:bg-green-500"
|
||||
/>
|
||||
{provider.isProxyTarget && (
|
||||
<Label
|
||||
htmlFor={`proxy-target-switch-${provider.id}`}
|
||||
className="text-xs font-medium text-purple-500 dark:text-purple-400 cursor-pointer"
|
||||
className="text-xs font-medium text-green-600 dark:text-green-400 cursor-pointer"
|
||||
>
|
||||
{t("provider.proxyTarget", { defaultValue: "代理目标" })}
|
||||
</Label>
|
||||
@@ -255,6 +381,13 @@ export function ProviderCard({
|
||||
onTest={onTest ? () => onTest(provider) : undefined}
|
||||
onConfigureUsage={() => onConfigureUsage(provider)}
|
||||
onDelete={() => onDelete(provider)}
|
||||
onResetCircuitBreaker={
|
||||
isProxyRunning && provider.isProxyTarget
|
||||
? handleResetCircuitBreaker
|
||||
: undefined
|
||||
}
|
||||
isProxyTarget={provider.isProxyTarget}
|
||||
consecutiveFailures={health?.consecutive_failures ?? 0}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -10,7 +10,7 @@ export function ProviderEmptyState({ onCreate }: ProviderEmptyStateProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed border-muted-foreground/30 p-10 text-center">
|
||||
<div className="flex flex-col items-center justify-center rounded-lg border border-dashed border-border p-10 text-center">
|
||||
<div className="mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-muted">
|
||||
<Users className="h-7 w-7 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ProviderHealthStatus } from "@/types/proxy";
|
||||
|
||||
interface ProviderHealthBadgeProps {
|
||||
consecutiveFailures: number;
|
||||
isProxyTarget?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 供应商健康状态徽章
|
||||
* 根据连续失败次数显示不同颜色的状态指示器
|
||||
*/
|
||||
export function ProviderHealthBadge({
|
||||
consecutiveFailures,
|
||||
isProxyTarget,
|
||||
className,
|
||||
}: ProviderHealthBadgeProps) {
|
||||
// 如果代理目标已关闭但有失败记录,仍然显示(自动熔断场景)
|
||||
// 如果代理目标启用,始终显示
|
||||
// 如果代理目标关闭且无失败记录,隐藏
|
||||
if (!isProxyTarget && consecutiveFailures === 0) return null;
|
||||
|
||||
// 根据失败次数计算状态
|
||||
const getStatus = () => {
|
||||
if (consecutiveFailures === 0) {
|
||||
return {
|
||||
label: "正常",
|
||||
status: ProviderHealthStatus.Healthy,
|
||||
color: "bg-green-500",
|
||||
// 使用更深/柔和的背景色,去除可能的白色内容感
|
||||
bgColor: "bg-green-500/10",
|
||||
textColor: "text-green-600 dark:text-green-400",
|
||||
};
|
||||
} else if (consecutiveFailures < 5) {
|
||||
return {
|
||||
label: "降级",
|
||||
status: ProviderHealthStatus.Degraded,
|
||||
color: "bg-yellow-500",
|
||||
bgColor: "bg-yellow-500/10",
|
||||
textColor: "text-yellow-600 dark:text-yellow-400",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
label: "熔断",
|
||||
status: ProviderHealthStatus.Failed,
|
||||
color: "bg-red-500",
|
||||
bgColor: "bg-red-500/10",
|
||||
textColor: "text-red-600 dark:text-red-400",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const statusConfig = getStatus();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium",
|
||||
statusConfig.bgColor,
|
||||
statusConfig.textColor,
|
||||
className,
|
||||
)}
|
||||
title={`连续失败 ${consecutiveFailures} 次`}
|
||||
>
|
||||
<div className={cn("w-2 h-2 rounded-full", statusConfig.color)} />
|
||||
<span>{statusConfig.label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,11 +5,11 @@ import {
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable";
|
||||
import { useMemo } from "react";
|
||||
import type { CSSProperties } from "react";
|
||||
import type { Provider } from "@/types";
|
||||
import type { AppId } from "@/lib/api";
|
||||
import { useDragSort } from "@/hooks/useDragSort";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { useModelTest } from "@/hooks/useModelTest";
|
||||
import { ProviderCard } from "@/components/providers/ProviderCard";
|
||||
import { ProviderEmptyState } from "@/components/providers/ProviderEmptyState";
|
||||
@@ -26,7 +26,7 @@ interface ProviderListProps {
|
||||
onOpenWebsite: (url: string) => void;
|
||||
onCreate?: () => void;
|
||||
isLoading?: boolean;
|
||||
onSetProxyTarget: (provider: Provider) => void;
|
||||
isProxyRunning?: boolean; // 代理服务运行状态
|
||||
}
|
||||
|
||||
export function ProviderList({
|
||||
@@ -41,19 +41,37 @@ export function ProviderList({
|
||||
onOpenWebsite,
|
||||
onCreate,
|
||||
isLoading = false,
|
||||
onSetProxyTarget,
|
||||
isProxyRunning = false, // 默认值为 false
|
||||
}: ProviderListProps) {
|
||||
const { sortedProviders, sensors, handleDragEnd } = useDragSort(
|
||||
providers,
|
||||
appId,
|
||||
);
|
||||
|
||||
// 获取代理服务运行状态
|
||||
const { isRunning: isProxyRunning } = useProxyStatus();
|
||||
|
||||
// 模型测试
|
||||
const { testProvider, isTesting } = useModelTest(appId);
|
||||
|
||||
// 计算代理目标的实际优先级映射 (P1, P2, P3...)
|
||||
const proxyPriorityMap = useMemo(() => {
|
||||
// 获取所有启用代理目标的供应商
|
||||
const proxyTargets = sortedProviders.filter((p) => p.isProxyTarget);
|
||||
|
||||
// 按 sortIndex 排序
|
||||
const sortedTargets = proxyTargets.sort((a, b) => {
|
||||
const indexA = a.sortIndex ?? Number.MAX_SAFE_INTEGER;
|
||||
const indexB = b.sortIndex ?? Number.MAX_SAFE_INTEGER;
|
||||
return indexA - indexB;
|
||||
});
|
||||
|
||||
// 创建优先级映射
|
||||
const map = new Map<string, number>();
|
||||
sortedTargets.forEach((provider, index) => {
|
||||
map.set(provider.id, index + 1); // P1, P2, P3...
|
||||
});
|
||||
|
||||
return map;
|
||||
}, [sortedProviders]);
|
||||
|
||||
const handleTest = (provider: Provider) => {
|
||||
testProvider(provider.id, provider.name);
|
||||
};
|
||||
@@ -103,8 +121,9 @@ export function ProviderList({
|
||||
onOpenWebsite={onOpenWebsite}
|
||||
onTest={handleTest}
|
||||
isTesting={isTesting(provider.id)}
|
||||
onSetProxyTarget={onSetProxyTarget}
|
||||
isProxyRunning={isProxyRunning}
|
||||
proxyPriority={proxyPriorityMap.get(provider.id)}
|
||||
allProviders={sortedProviders}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -125,8 +144,9 @@ interface SortableProviderCardProps {
|
||||
onOpenWebsite: (url: string) => void;
|
||||
onTest: (provider: Provider) => void;
|
||||
isTesting: boolean;
|
||||
onSetProxyTarget: (provider: Provider) => void;
|
||||
isProxyRunning: boolean;
|
||||
proxyPriority?: number; // 代理目标的实际优先级 (1, 2, 3...)
|
||||
allProviders?: Provider[]; // 所有供应商列表
|
||||
}
|
||||
|
||||
function SortableProviderCard({
|
||||
@@ -141,8 +161,9 @@ function SortableProviderCard({
|
||||
onOpenWebsite,
|
||||
onTest,
|
||||
isTesting,
|
||||
onSetProxyTarget,
|
||||
isProxyRunning,
|
||||
proxyPriority,
|
||||
allProviders,
|
||||
}: SortableProviderCardProps) {
|
||||
const {
|
||||
setNodeRef,
|
||||
@@ -174,8 +195,9 @@ function SortableProviderCard({
|
||||
onOpenWebsite={onOpenWebsite}
|
||||
onTest={onTest}
|
||||
isTesting={isTesting}
|
||||
onSetProxyTarget={onSetProxyTarget}
|
||||
isProxyRunning={isProxyRunning}
|
||||
proxyPriority={proxyPriority}
|
||||
allProviders={allProviders}
|
||||
dragHandleProps={{
|
||||
attributes,
|
||||
listeners,
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Save, Loader2, Info } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
useCircuitBreakerConfig,
|
||||
useUpdateCircuitBreakerConfig,
|
||||
} from "@/lib/query/failover";
|
||||
|
||||
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({
|
||||
failureThreshold: 5,
|
||||
successThreshold: 2,
|
||||
timeoutSeconds: 60,
|
||||
errorRateThreshold: 0.5,
|
||||
minRequests: 10,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
setFormData({
|
||||
...config,
|
||||
});
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await updateConfig.mutateAsync({
|
||||
failureThreshold: formData.failureThreshold,
|
||||
successThreshold: formData.successThreshold,
|
||||
timeoutSeconds: formData.timeoutSeconds,
|
||||
errorRateThreshold: formData.errorRateThreshold,
|
||||
minRequests: formData.minRequests,
|
||||
});
|
||||
toast.success(
|
||||
t("proxy.autoFailover.configSaved", "自动故障转移配置已保存"),
|
||||
);
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
t("proxy.autoFailover.configSaveFailed", "保存失败") + ": " + String(e),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
if (config) {
|
||||
setFormData({
|
||||
...config,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-4">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<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>
|
||||
|
||||
{/* 熔断器高级配置 */}
|
||||
<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={!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.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>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import {
|
||||
useCircuitBreakerConfig,
|
||||
useUpdateCircuitBreakerConfig,
|
||||
} from "@/lib/query/failover";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useState, useEffect } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
/**
|
||||
* 熔断器配置面板
|
||||
* 允许用户调整熔断器参数
|
||||
*/
|
||||
export function CircuitBreakerConfigPanel() {
|
||||
const { data: config, isLoading } = useCircuitBreakerConfig();
|
||||
const updateConfig = useUpdateCircuitBreakerConfig();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
failureThreshold: 5,
|
||||
successThreshold: 2,
|
||||
timeoutSeconds: 60,
|
||||
errorRateThreshold: 0.5,
|
||||
minRequests: 10,
|
||||
});
|
||||
|
||||
// 当配置加载完成时更新表单数据
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
setFormData(config);
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await updateConfig.mutateAsync(formData);
|
||||
toast.success("熔断器配置已保存");
|
||||
} catch (error) {
|
||||
toast.error("保存失败: " + String(error));
|
||||
}
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
if (config) {
|
||||
setFormData(config);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="text-sm text-muted-foreground">加载中...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">熔断器配置</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
调整熔断器参数以控制故障检测和恢复行为
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="h-px bg-border my-4" />
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* 失败阈值 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="failureThreshold">失败阈值</Label>
|
||||
<Input
|
||||
id="failureThreshold"
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
value={formData.failureThreshold}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
failureThreshold: parseInt(e.target.value) || 5,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
连续失败多少次后打开熔断器
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 超时时间 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSeconds">超时时间(秒)</Label>
|
||||
<Input
|
||||
id="timeoutSeconds"
|
||||
type="number"
|
||||
min="10"
|
||||
max="300"
|
||||
value={formData.timeoutSeconds}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
timeoutSeconds: parseInt(e.target.value) || 60,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
熔断器打开后多久尝试恢复(半开状态)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 成功阈值 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="successThreshold">成功阈值</Label>
|
||||
<Input
|
||||
id="successThreshold"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
value={formData.successThreshold}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
successThreshold: parseInt(e.target.value) || 2,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
半开状态下成功多少次后关闭熔断器
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 错误率阈值 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="errorRateThreshold">错误率阈值 (%)</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,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
错误率超过此值时打开熔断器
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 最小请求数 */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="minRequests">最小请求数</Label>
|
||||
<Input
|
||||
id="minRequests"
|
||||
type="number"
|
||||
min="5"
|
||||
max="100"
|
||||
value={formData.minRequests}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
minRequests: parseInt(e.target.value) || 10,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
计算错误率前的最小请求数
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<Button onClick={handleSave} disabled={updateConfig.isPending}>
|
||||
{updateConfig.isPending ? "保存中..." : "保存配置"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleReset}
|
||||
disabled={updateConfig.isPending}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 说明信息 */}
|
||||
<div className="p-4 bg-muted/50 rounded-lg space-y-2 text-sm">
|
||||
<h4 className="font-medium">配置说明</h4>
|
||||
<ul className="space-y-1 text-muted-foreground">
|
||||
<li>
|
||||
• <strong>失败阈值</strong>:连续失败达到此次数时,熔断器打开
|
||||
</li>
|
||||
<li>
|
||||
• <strong>超时时间</strong>:熔断器打开后,等待此时间后尝试半开
|
||||
</li>
|
||||
<li>
|
||||
• <strong>成功阈值</strong>:半开状态下,成功达到此次数时关闭熔断器
|
||||
</li>
|
||||
<li>
|
||||
• <strong>错误率阈值</strong>:错误率超过此值时,熔断器打开
|
||||
</li>
|
||||
<li>
|
||||
• <strong>最小请求数</strong>:只有请求数达到此值后才计算错误率
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Download, ExternalLink, Info, Loader2, RefreshCw } from "lucide-react";
|
||||
import {
|
||||
Download,
|
||||
ExternalLink,
|
||||
Info,
|
||||
Loader2,
|
||||
RefreshCw,
|
||||
Terminal,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
@@ -7,16 +16,27 @@ import { getVersion } from "@tauri-apps/api/app";
|
||||
import { settingsApi } from "@/lib/api";
|
||||
import { useUpdate } from "@/contexts/UpdateContext";
|
||||
import { relaunchApp } from "@/lib/updater";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
interface AboutSectionProps {
|
||||
isPortable: boolean;
|
||||
}
|
||||
|
||||
interface ToolVersion {
|
||||
name: string;
|
||||
version: string | null;
|
||||
latest_version: string | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
// ... (use hooks as before) ...
|
||||
const { t } = useTranslation();
|
||||
const [version, setVersion] = useState<string | null>(null);
|
||||
const [isLoadingVersion, setIsLoadingVersion] = useState(true);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [toolVersions, setToolVersions] = useState<ToolVersion[]>([]);
|
||||
const [isLoadingTools, setIsLoadingTools] = useState(true);
|
||||
|
||||
const {
|
||||
hasUpdate,
|
||||
@@ -31,18 +51,24 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
let active = true;
|
||||
const load = async () => {
|
||||
try {
|
||||
const loaded = await getVersion();
|
||||
const [appVersion, tools] = await Promise.all([
|
||||
getVersion(),
|
||||
settingsApi.getToolVersions(),
|
||||
]);
|
||||
|
||||
if (active) {
|
||||
setVersion(loaded);
|
||||
setVersion(appVersion);
|
||||
setToolVersions(tools);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[AboutSection] Failed to get version", error);
|
||||
console.error("[AboutSection] Failed to load info", error);
|
||||
if (active) {
|
||||
setVersion(null);
|
||||
}
|
||||
} finally {
|
||||
if (active) {
|
||||
setIsLoadingVersion(false);
|
||||
setIsLoadingTools(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -53,6 +79,8 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ... (handlers like handleOpenReleaseNotes, handleCheckUpdate) ...
|
||||
|
||||
const handleOpenReleaseNotes = useCallback(async () => {
|
||||
try {
|
||||
const targetVersion = updateInfo?.availableVersion ?? version ?? "";
|
||||
@@ -125,7 +153,7 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
const displayVersion = version ?? t("common.unknown");
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<section className="space-y-6">
|
||||
<header className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{t("common.about")}</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
@@ -133,24 +161,28 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="space-y-4 rounded-lg border border-border-default p-4">
|
||||
<div className="rounded-xl border border-border bg-card/50 p-6 space-y-6">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-foreground">CC Switch</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("common.version")}{" "}
|
||||
{isLoadingVersion ? (
|
||||
<Loader2 className="inline h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
`v${displayVersion}`
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-lg font-semibold text-foreground">CC Switch</h4>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline" className="gap-1.5 bg-background">
|
||||
<span className="text-muted-foreground">
|
||||
{t("common.version")}
|
||||
</span>
|
||||
{isLoadingVersion ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<span className="font-medium">{`v${displayVersion}`}</span>
|
||||
)}
|
||||
</Badge>
|
||||
{isPortable && (
|
||||
<Badge variant="secondary" className="gap-1.5">
|
||||
<Info className="h-3 w-3" />
|
||||
{t("settings.portableMode")}
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
{isPortable ? (
|
||||
<p className="inline-flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Info className="h-3 w-3" />
|
||||
{t("settings.portableMode")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
@@ -159,6 +191,7 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleOpenReleaseNotes}
|
||||
className="h-9"
|
||||
>
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
{t("settings.releaseNotes")}
|
||||
@@ -168,7 +201,7 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
size="sm"
|
||||
onClick={handleCheckUpdate}
|
||||
disabled={isChecking || isDownloading}
|
||||
className="min-w-[140px]"
|
||||
className="min-w-[140px] h-9"
|
||||
>
|
||||
{isDownloading ? (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
@@ -194,18 +227,71 @@ export function AboutSection({ isPortable }: AboutSectionProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasUpdate && updateInfo ? (
|
||||
<div className="rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
|
||||
<p>
|
||||
{hasUpdate && updateInfo && (
|
||||
<div className="rounded-lg bg-primary/10 border border-primary/20 px-4 py-3 text-sm">
|
||||
<p className="font-medium text-primary mb-1">
|
||||
{t("settings.updateAvailable", {
|
||||
version: updateInfo.availableVersion,
|
||||
})}
|
||||
</p>
|
||||
{updateInfo.notes ? (
|
||||
<p className="mt-1 line-clamp-3">{updateInfo.notes}</p>
|
||||
) : null}
|
||||
{updateInfo.notes && (
|
||||
<p className="text-muted-foreground line-clamp-3 leading-relaxed">
|
||||
{updateInfo.notes}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium text-muted-foreground px-1">
|
||||
本地环境检查
|
||||
</h4>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{isLoadingTools
|
||||
? Array.from({ length: 3 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="h-20 rounded-xl border border-border bg-card/50 animate-pulse"
|
||||
/>
|
||||
))
|
||||
: toolVersions.map((tool) => (
|
||||
<div
|
||||
key={tool.name}
|
||||
className="flex flex-col gap-2 rounded-xl border border-border bg-card/50 p-4 transition-colors hover:bg-muted/50"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium capitalize">
|
||||
{tool.name}
|
||||
</span>
|
||||
</div>
|
||||
{tool.version ? (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{tool.latest_version &&
|
||||
tool.version !== tool.latest_version && (
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded-full bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border border-yellow-500/20">
|
||||
Update: {tool.latest_version}
|
||||
</span>
|
||||
)}
|
||||
<CheckCircle2 className="h-4 w-4 text-green-500" />
|
||||
</div>
|
||||
) : (
|
||||
<AlertCircle className="h-4 w-4 text-yellow-500" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<div
|
||||
className="text-xs font-mono truncate"
|
||||
title={tool.version || tool.error || "Unknown"}
|
||||
>
|
||||
{tool.version ? tool.version : tool.error || "未安装"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -50,7 +50,7 @@ export function DirectorySettings({
|
||||
<Input
|
||||
value={appConfigDir ?? resolvedDirs.appConfig ?? ""}
|
||||
placeholder={t("settings.browsePlaceholderApp")}
|
||||
className="font-mono text-xs"
|
||||
className="text-xs"
|
||||
onChange={(event) => onAppConfigChange(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
@@ -161,7 +161,7 @@ function DirectoryInput({
|
||||
<Input
|
||||
value={displayValue}
|
||||
placeholder={placeholder}
|
||||
className="font-mono text-xs"
|
||||
className="text-xs"
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Loader2, Save } from "lucide-react";
|
||||
import {
|
||||
Loader2,
|
||||
Save,
|
||||
FolderSearch,
|
||||
Activity,
|
||||
Coins,
|
||||
Database,
|
||||
Server,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -8,6 +16,12 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { settingsApi } from "@/lib/api";
|
||||
@@ -20,11 +34,15 @@ import { AboutSection } from "@/components/settings/AboutSection";
|
||||
import { ProxyPanel } from "@/components/proxy";
|
||||
import { PricingConfigPanel } from "@/components/usage/PricingConfigPanel";
|
||||
import { ModelTestConfigPanel } from "@/components/usage/ModelTestConfigPanel";
|
||||
import { AutoFailoverConfigPanel } from "@/components/proxy/AutoFailoverConfigPanel";
|
||||
import { UsageDashboard } from "@/components/usage/UsageDashboard";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
import { useImportExport } from "@/hooks/useImportExport";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { SettingsFormState } from "@/hooks/useSettings";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
|
||||
interface SettingsDialogProps {
|
||||
open: boolean;
|
||||
@@ -154,6 +172,26 @@ export function SettingsPage({
|
||||
|
||||
const isBusy = useMemo(() => isLoading && !settings, [isLoading, settings]);
|
||||
|
||||
const {
|
||||
isRunning,
|
||||
start: startProxy,
|
||||
stop: stopProxy,
|
||||
isPending: isProxyPending,
|
||||
} = useProxyStatus();
|
||||
const [failoverEnabled, setFailoverEnabled] = useState(true);
|
||||
|
||||
const handleToggleProxy = async (checked: boolean) => {
|
||||
try {
|
||||
if (!checked) {
|
||||
await stopProxy();
|
||||
} else {
|
||||
await startProxy();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Toggle proxy failed:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-[56rem] flex flex-col h-[calc(100vh-8rem)] overflow-hidden px-6">
|
||||
{isBusy ? (
|
||||
@@ -198,61 +236,225 @@ export function SettingsPage({
|
||||
|
||||
<TabsContent value="advanced" className="space-y-6 mt-0 pb-6">
|
||||
{settings ? (
|
||||
<>
|
||||
<DirectorySettings
|
||||
appConfigDir={appConfigDir}
|
||||
resolvedDirs={resolvedDirs}
|
||||
onAppConfigChange={updateAppConfigDir}
|
||||
onBrowseAppConfig={browseAppConfigDir}
|
||||
onResetAppConfig={resetAppConfigDir}
|
||||
claudeDir={settings.claudeConfigDir}
|
||||
codexDir={settings.codexConfigDir}
|
||||
geminiDir={settings.geminiConfigDir}
|
||||
onDirectoryChange={updateDirectory}
|
||||
onBrowseDirectory={browseDirectory}
|
||||
onResetDirectory={resetDirectory}
|
||||
/>
|
||||
<div className="space-y-4">
|
||||
<Accordion
|
||||
type="multiple"
|
||||
defaultValue={[]}
|
||||
className="w-full space-y-4"
|
||||
>
|
||||
<AccordionItem
|
||||
value="directory"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<FolderSearch className="h-5 w-5 text-primary" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
配置文件目录
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
管理 Claude、Codex 和 Gemini 的配置存储路径
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<DirectorySettings
|
||||
appConfigDir={appConfigDir}
|
||||
resolvedDirs={resolvedDirs}
|
||||
onAppConfigChange={updateAppConfigDir}
|
||||
onBrowseAppConfig={browseAppConfigDir}
|
||||
onResetAppConfig={resetAppConfigDir}
|
||||
claudeDir={settings.claudeConfigDir}
|
||||
codexDir={settings.codexConfigDir}
|
||||
geminiDir={settings.geminiConfigDir}
|
||||
onDirectoryChange={updateDirectory}
|
||||
onBrowseDirectory={browseDirectory}
|
||||
onResetDirectory={resetDirectory}
|
||||
/>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* 代理服务面板 */}
|
||||
<ProxyPanel />
|
||||
<AccordionItem
|
||||
value="proxy"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex flex-1 items-center justify-between pr-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Server className="h-5 w-5 text-green-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
本地代理
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
控制代理服务开关、查看状态与端口信息
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="flex items-center gap-4"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Badge
|
||||
variant={isRunning ? "default" : "secondary"}
|
||||
className="gap-1.5 h-6"
|
||||
>
|
||||
<Activity
|
||||
className={`h-3 w-3 ${isRunning ? "animate-pulse" : ""}`}
|
||||
/>
|
||||
{isRunning ? "运行中" : "已停止"}
|
||||
</Badge>
|
||||
<Switch
|
||||
checked={isRunning}
|
||||
onCheckedChange={handleToggleProxy}
|
||||
disabled={isProxyPending}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-0 border-t border-border/50">
|
||||
<ProxyPanel />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* 模型定价配置 */}
|
||||
<PricingConfigPanel />
|
||||
<AccordionItem
|
||||
value="test"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<Activity className="h-5 w-5 text-indigo-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
模型测试配置
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
配置模型测试使用的默认模型和提示词
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<ModelTestConfigPanel />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* 模型测试配置 */}
|
||||
<ModelTestConfigPanel />
|
||||
<AccordionItem
|
||||
value="failover"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex flex-1 items-center justify-between pr-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Activity className="h-5 w-5 text-orange-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
自动故障转移
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
配置自动故障转移和熔断策略
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="flex items-center gap-4"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Removed status text as requested */}
|
||||
<Switch
|
||||
checked={failoverEnabled}
|
||||
onCheckedChange={setFailoverEnabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<AutoFailoverConfigPanel
|
||||
enabled={failoverEnabled}
|
||||
onEnabledChange={setFailoverEnabled}
|
||||
/>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
<ImportExportSection
|
||||
status={importStatus}
|
||||
selectedFile={selectedFile}
|
||||
errorMessage={errorMessage}
|
||||
backupId={backupId}
|
||||
isImporting={isImporting}
|
||||
onSelectFile={selectImportFile}
|
||||
onImport={importConfig}
|
||||
onExport={exportConfig}
|
||||
onClear={clearSelection}
|
||||
/>
|
||||
<div className="pt-6 border-t border-gray-200 dark:border-white/10">
|
||||
<AccordionItem
|
||||
value="pricing"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<Coins className="h-5 w-5 text-yellow-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
成本定价
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
管理各模型 Token 计费规则
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<PricingConfigPanel />
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
<AccordionItem
|
||||
value="data"
|
||||
className="rounded-xl glass-card overflow-hidden"
|
||||
>
|
||||
<AccordionTrigger className="px-6 py-4 hover:no-underline hover:bg-muted/50 data-[state=open]:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<Database className="h-5 w-5 text-blue-500" />
|
||||
<div className="text-left">
|
||||
<h3 className="text-base font-semibold">
|
||||
数据管理
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground font-normal">
|
||||
导入导出配置与备份恢复
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-6 pb-6 pt-4 border-t border-border/50">
|
||||
<ImportExportSection
|
||||
status={importStatus}
|
||||
selectedFile={selectedFile}
|
||||
errorMessage={errorMessage}
|
||||
backupId={backupId}
|
||||
isImporting={isImporting}
|
||||
onSelectFile={selectImportFile}
|
||||
onImport={importConfig}
|
||||
onExport={exportConfig}
|
||||
onClear={clearSelection}
|
||||
/>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<div className="pt-4">
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
className="w-full"
|
||||
className="w-full h-12 text-base font-medium"
|
||||
disabled={isSaving}
|
||||
>
|
||||
{isSaving ? (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
{t("settings.saving")}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
<Save className="mr-2 h-5 w-5" />
|
||||
{t("common.save")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
) : null}
|
||||
</TabsContent>
|
||||
|
||||
@@ -271,10 +473,7 @@ export function SettingsPage({
|
||||
open={showRestartPrompt}
|
||||
onOpenChange={(open) => !open && handleRestartLater()}
|
||||
>
|
||||
<DialogContent
|
||||
zIndex="alert"
|
||||
className="max-w-md glass border-white/10"
|
||||
>
|
||||
<DialogContent zIndex="alert" className="max-w-md glass border-border">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("settings.restartRequired")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
@@ -287,7 +486,7 @@ export function SettingsPage({
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleRestartLater}
|
||||
className="hover:bg-white/5"
|
||||
className="hover:bg-muted/50"
|
||||
>
|
||||
{t("settings.restartLater")}
|
||||
</Button>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { SettingsFormState } from "@/hooks/useSettings";
|
||||
import { AppWindow, MonitorUp, Power } from "lucide-react";
|
||||
|
||||
interface WindowSettingsProps {
|
||||
settings: SettingsFormState;
|
||||
@@ -12,40 +13,46 @@ export function WindowSettings({ settings, onChange }: WindowSettingsProps) {
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<header className="space-y-1">
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-border/40">
|
||||
<AppWindow className="h-4 w-4 text-primary" />
|
||||
<h3 className="text-sm font-medium">{t("settings.windowBehavior")}</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.windowBehaviorHint")}
|
||||
</p>
|
||||
</header>
|
||||
</div>
|
||||
|
||||
<ToggleRow
|
||||
title={t("settings.launchOnStartup")}
|
||||
description={t("settings.launchOnStartupDescription")}
|
||||
checked={!!settings.launchOnStartup}
|
||||
onCheckedChange={(value) => onChange({ launchOnStartup: value })}
|
||||
/>
|
||||
<div className="space-y-3">
|
||||
<ToggleRow
|
||||
icon={<Power className="h-4 w-4 text-orange-500" />}
|
||||
title={t("settings.launchOnStartup")}
|
||||
description={t("settings.launchOnStartupDescription")}
|
||||
checked={!!settings.launchOnStartup}
|
||||
onCheckedChange={(value) => onChange({ launchOnStartup: value })}
|
||||
/>
|
||||
|
||||
<ToggleRow
|
||||
title={t("settings.minimizeToTray")}
|
||||
description={t("settings.minimizeToTrayDescription")}
|
||||
checked={settings.minimizeToTrayOnClose}
|
||||
onCheckedChange={(value) => onChange({ minimizeToTrayOnClose: value })}
|
||||
/>
|
||||
<ToggleRow
|
||||
icon={<AppWindow className="h-4 w-4 text-blue-500" />}
|
||||
title={t("settings.minimizeToTray")}
|
||||
description={t("settings.minimizeToTrayDescription")}
|
||||
checked={settings.minimizeToTrayOnClose}
|
||||
onCheckedChange={(value) =>
|
||||
onChange({ minimizeToTrayOnClose: value })
|
||||
}
|
||||
/>
|
||||
|
||||
<ToggleRow
|
||||
title={t("settings.enableClaudePluginIntegration")}
|
||||
description={t("settings.enableClaudePluginIntegrationDescription")}
|
||||
checked={!!settings.enableClaudePluginIntegration}
|
||||
onCheckedChange={(value) =>
|
||||
onChange({ enableClaudePluginIntegration: value })
|
||||
}
|
||||
/>
|
||||
<ToggleRow
|
||||
icon={<MonitorUp className="h-4 w-4 text-purple-500" />}
|
||||
title={t("settings.enableClaudePluginIntegration")}
|
||||
description={t("settings.enableClaudePluginIntegrationDescription")}
|
||||
checked={!!settings.enableClaudePluginIntegration}
|
||||
onCheckedChange={(value) =>
|
||||
onChange({ enableClaudePluginIntegration: value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleRowProps {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description?: string;
|
||||
checked: boolean;
|
||||
@@ -53,18 +60,24 @@ interface ToggleRowProps {
|
||||
}
|
||||
|
||||
function ToggleRow({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
checked,
|
||||
onCheckedChange,
|
||||
}: ToggleRowProps) {
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-4 rounded-lg border border-border-default p-4">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium leading-none">{title}</p>
|
||||
{description ? (
|
||||
<p className="text-xs text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
<div className="flex items-center justify-between gap-4 rounded-xl border border-border bg-card/50 p-4 transition-colors hover:bg-muted/50">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-background ring-1 ring-border">
|
||||
{icon}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium leading-none">{title}</p>
|
||||
{description ? (
|
||||
<p className="text-xs text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={checked}
|
||||
|
||||
@@ -19,17 +19,11 @@ import { RefreshCw, Search } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { SkillCard } from "./SkillCard";
|
||||
import { RepoManagerPanel } from "./RepoManagerPanel";
|
||||
import {
|
||||
skillsApi,
|
||||
type Skill,
|
||||
type SkillRepo,
|
||||
type AppType,
|
||||
} from "@/lib/api/skills";
|
||||
import { skillsApi, type Skill, type SkillRepo } from "@/lib/api/skills";
|
||||
import { formatSkillError } from "@/lib/errors/skillErrorParser";
|
||||
|
||||
interface SkillsPageProps {
|
||||
onClose?: () => void;
|
||||
initialApp?: AppType;
|
||||
}
|
||||
|
||||
export interface SkillsPageHandle {
|
||||
@@ -38,7 +32,7 @@ export interface SkillsPageHandle {
|
||||
}
|
||||
|
||||
export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
({ onClose: _onClose, initialApp = "claude" }, ref) => {
|
||||
({ onClose: _onClose }, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [skills, setSkills] = useState<Skill[]>([]);
|
||||
const [repos, setRepos] = useState<SkillRepo[]>([]);
|
||||
@@ -48,13 +42,11 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
const [filterStatus, setFilterStatus] = useState<
|
||||
"all" | "installed" | "uninstalled"
|
||||
>("all");
|
||||
// 使用 initialApp,不允许切换
|
||||
const selectedApp = initialApp;
|
||||
|
||||
const loadSkills = async (afterLoad?: (data: Skill[]) => void) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await skillsApi.getAll(selectedApp);
|
||||
const data = await skillsApi.getAll();
|
||||
setSkills(data);
|
||||
if (afterLoad) {
|
||||
afterLoad(data);
|
||||
@@ -92,7 +84,6 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([loadSkills(), loadRepos()]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
@@ -102,7 +93,7 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
|
||||
const handleInstall = async (directory: string) => {
|
||||
try {
|
||||
await skillsApi.install(directory, selectedApp);
|
||||
await skillsApi.install(directory);
|
||||
toast.success(t("skills.installSuccess", { name: directory }));
|
||||
await loadSkills();
|
||||
} catch (error) {
|
||||
@@ -131,7 +122,7 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
|
||||
const handleUninstall = async (directory: string) => {
|
||||
try {
|
||||
await skillsApi.uninstall(directory, selectedApp);
|
||||
await skillsApi.uninstall(directory);
|
||||
toast.success(t("skills.uninstallSuccess", { name: directory }));
|
||||
await loadSkills();
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import * as React from "react";
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Accordion = AccordionPrimitive.Root;
|
||||
|
||||
const AccordionItem = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AccordionPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn("border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AccordionItem.displayName = "AccordionItem";
|
||||
|
||||
const AccordionTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
));
|
||||
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
|
||||
|
||||
const AccordionContent = React.forwardRef<
|
||||
React.ElementRef<typeof AccordionPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<AccordionPrimitive.Content
|
||||
ref={ref}
|
||||
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
|
||||
{...props}
|
||||
>
|
||||
<div className={cn("pb-4 pt-0", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
));
|
||||
|
||||
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
|
||||
@@ -18,7 +18,7 @@ export function ModelStatsTable() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-md bg-card/60 shadow-sm">
|
||||
<div className="rounded-lg border border-border/50 bg-card/40 backdrop-blur-sm overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
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 { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { ChevronDown, ChevronRight, Save, Loader2 } from "lucide-react";
|
||||
import { Save, Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
getModelTestConfig,
|
||||
@@ -21,7 +14,6 @@ import {
|
||||
|
||||
export function ModelTestConfigPanel() {
|
||||
const { t } = useTranslation();
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -66,160 +58,120 @@ export function ModelTestConfigPanel() {
|
||||
|
||||
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("modelTest.configTitle", "模型测试配置")}
|
||||
</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>
|
||||
<CardTitle className="text-base">
|
||||
{t("modelTest.configTitle", "模型测试配置")}
|
||||
</CardTitle>
|
||||
{!isExpanded && (
|
||||
<CardDescription className="mt-1">
|
||||
{t(
|
||||
"modelTest.configDesc",
|
||||
"配置模型测试使用的默认模型和提示词",
|
||||
)}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{isExpanded && (
|
||||
<CardContent className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="claudeModel">
|
||||
{t("modelTest.claudeModel", "Claude 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="claudeModel"
|
||||
value={config.claudeModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, claudeModel: e.target.value })
|
||||
}
|
||||
placeholder="claude-haiku-4-5-20251001"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="codexModel">
|
||||
{t("modelTest.codexModel", "Codex 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="codexModel"
|
||||
value={config.codexModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, codexModel: e.target.value })
|
||||
}
|
||||
placeholder="gpt-5.1-low"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="geminiModel">
|
||||
{t("modelTest.geminiModel", "Gemini 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="geminiModel"
|
||||
value={config.geminiModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, geminiModel: e.target.value })
|
||||
}
|
||||
placeholder="gemini-3-pro-low"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="testPrompt">
|
||||
{t("modelTest.testPrompt", "测试提示词")}
|
||||
</Label>
|
||||
<Input
|
||||
id="testPrompt"
|
||||
value={config.testPrompt}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, testPrompt: e.target.value })
|
||||
}
|
||||
placeholder="ping"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"modelTest.testPromptHint",
|
||||
"发送给模型的测试消息,建议使用简短内容以减少 token 消耗",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSecs">
|
||||
{t("modelTest.timeout", "超时时间(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="timeoutSecs"
|
||||
type="number"
|
||||
min={5}
|
||||
max={60}
|
||||
value={config.timeoutSecs}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
timeoutSecs: parseInt(e.target.value) || 15,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<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>
|
||||
</CardContent>
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="claudeModel">
|
||||
{t("modelTest.claudeModel", "Claude 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="claudeModel"
|
||||
value={config.claudeModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, claudeModel: e.target.value })
|
||||
}
|
||||
placeholder="claude-haiku-4-5-20251001"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="codexModel">
|
||||
{t("modelTest.codexModel", "Codex 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="codexModel"
|
||||
value={config.codexModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, codexModel: e.target.value })
|
||||
}
|
||||
placeholder="gpt-5.1-low"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="geminiModel">
|
||||
{t("modelTest.geminiModel", "Gemini 测试模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="geminiModel"
|
||||
value={config.geminiModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, geminiModel: e.target.value })
|
||||
}
|
||||
placeholder="gemini-3-pro-low"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="testPrompt">
|
||||
{t("modelTest.testPrompt", "测试提示词")}
|
||||
</Label>
|
||||
<Input
|
||||
id="testPrompt"
|
||||
value={config.testPrompt}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, testPrompt: e.target.value })
|
||||
}
|
||||
placeholder="ping"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
"modelTest.testPromptHint",
|
||||
"发送给模型的测试消息,建议使用简短内容以减少 token 消耗",
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSecs">
|
||||
{t("modelTest.timeout", "超时时间(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="timeoutSecs"
|
||||
type="number"
|
||||
min={5}
|
||||
max={60}
|
||||
value={config.timeoutSecs}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
timeoutSecs: parseInt(e.target.value) || 15,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -110,136 +104,107 @@ export function PricingConfigPanel() {
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="border rounded-lg">
|
||||
<CardHeader
|
||||
className="cursor-pointer select-none"
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<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>
|
||||
<CardTitle className="text-base">
|
||||
{t("usage.modelPricing", "模型定价")}
|
||||
{pricing && pricing.length > 0 && (
|
||||
<span className="ml-2 text-sm font-normal text-muted-foreground">
|
||||
({pricing.length})
|
||||
</span>
|
||||
)}
|
||||
</CardTitle>
|
||||
{!isExpanded && (
|
||||
<CardDescription className="mt-1">
|
||||
{t(
|
||||
"usage.modelPricingDesc",
|
||||
"配置各模型的 Token 成本(每百万 tokens 的 USD 价格,支持 * 与 ? 通配)",
|
||||
)}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleAddNew();
|
||||
}}
|
||||
size="sm"
|
||||
>
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
{t("common.add", "新增")}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<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>
|
||||
|
||||
{isExpanded && (
|
||||
<CardContent>
|
||||
{!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>
|
||||
<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>
|
||||
</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>
|
||||
)}
|
||||
</CardContent>
|
||||
)}
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{editingModel && (
|
||||
<PricingEditModal
|
||||
@@ -284,6 +249,6 @@ export function PricingConfigPanel() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export function ProviderStatsTable() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-md bg-card/60 shadow-sm">
|
||||
<div className="rounded-lg border border-border/50 bg-card/40 backdrop-blur-sm overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
|
||||
@@ -65,123 +65,151 @@ export function RequestLogTable() {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 筛选栏 */}
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-md bg-card/60 p-3 shadow-sm">
|
||||
<Select
|
||||
value={tempFilters.appType || "all"}
|
||||
onValueChange={(v) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
appType: v === "all" ? undefined : v,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder={t("usage.endpoint", "端点")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("common.all", "全部")}</SelectItem>
|
||||
<SelectItem value="claude">Claude</SelectItem>
|
||||
<SelectItem value="codex">Codex</SelectItem>
|
||||
<SelectItem value="gemini">Gemini</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex flex-col gap-4 rounded-lg border bg-card/50 p-4 backdrop-blur-sm">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Select
|
||||
value={tempFilters.appType || "all"}
|
||||
onValueChange={(v) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
appType: v === "all" ? undefined : v,
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[130px] bg-background">
|
||||
<SelectValue placeholder={t("usage.endpoint", "端点")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("common.all", "全部端点")}</SelectItem>
|
||||
<SelectItem value="claude">Claude</SelectItem>
|
||||
<SelectItem value="codex">Codex</SelectItem>
|
||||
<SelectItem value="gemini">Gemini</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select
|
||||
value={tempFilters.statusCode?.toString() || "all"}
|
||||
onValueChange={(v) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
statusCode: v === "all" ? undefined : parseInt(v),
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue placeholder={t("usage.status", "状态码")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("common.all", "全部")}</SelectItem>
|
||||
<SelectItem value="200">200</SelectItem>
|
||||
<SelectItem value="400">400</SelectItem>
|
||||
<SelectItem value="401">401</SelectItem>
|
||||
<SelectItem value="429">429</SelectItem>
|
||||
<SelectItem value="500">500</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={tempFilters.statusCode?.toString() || "all"}
|
||||
onValueChange={(v) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
statusCode: v === "all" ? undefined : parseInt(v),
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-[130px] bg-background">
|
||||
<SelectValue placeholder={t("usage.status", "状态码")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">{t("common.all", "全部状态")}</SelectItem>
|
||||
<SelectItem value="200">200 OK</SelectItem>
|
||||
<SelectItem value="400">400 Bad Request</SelectItem>
|
||||
<SelectItem value="401">401 Unauthorized</SelectItem>
|
||||
<SelectItem value="429">429 Rate Limit</SelectItem>
|
||||
<SelectItem value="500">500 Server Error</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Input
|
||||
placeholder={t("usage.provider", "供应商名称")}
|
||||
className="w-[140px]"
|
||||
value={tempFilters.providerName || ""}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
providerName: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<div className="flex items-center gap-2 flex-1 min-w-[300px]">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t("usage.provider", "搜索供应商...")}
|
||||
className="pl-9 bg-background"
|
||||
value={tempFilters.providerName || ""}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
providerName: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
placeholder={t("usage.model", "搜索模型...")}
|
||||
className="w-[180px] bg-background"
|
||||
value={tempFilters.model || ""}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
model: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
placeholder={t("usage.model", "模型名称")}
|
||||
className="w-[140px]"
|
||||
value={tempFilters.model || ""}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
model: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="whitespace-nowrap">时间范围:</span>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
className="h-8 w-[200px] bg-background"
|
||||
value={
|
||||
tempFilters.startDate
|
||||
? new Date(tempFilters.startDate * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 16)
|
||||
: ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
startDate: e.target.value
|
||||
? Math.floor(new Date(e.target.value).getTime() / 1000)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span>-</span>
|
||||
<Input
|
||||
type="datetime-local"
|
||||
className="h-8 w-[200px] bg-background"
|
||||
value={
|
||||
tempFilters.endDate
|
||||
? new Date(tempFilters.endDate * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 16)
|
||||
: ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
endDate: e.target.value
|
||||
? Math.floor(new Date(e.target.value).getTime() / 1000)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
type="datetime-local"
|
||||
className="w-[180px]"
|
||||
value={
|
||||
tempFilters.startDate
|
||||
? new Date(tempFilters.startDate * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 16)
|
||||
: ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
startDate: e.target.value
|
||||
? Math.floor(new Date(e.target.value).getTime() / 1000)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="datetime-local"
|
||||
className="w-[180px]"
|
||||
value={
|
||||
tempFilters.endDate
|
||||
? new Date(tempFilters.endDate * 1000).toISOString().slice(0, 16)
|
||||
: ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setTempFilters({
|
||||
...tempFilters,
|
||||
endDate: e.target.value
|
||||
? Math.floor(new Date(e.target.value).getTime() / 1000)
|
||||
: undefined,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="ml-auto flex gap-2">
|
||||
<Button size="sm" onClick={handleSearch}>
|
||||
<Search className="mr-1 h-4 w-4" />
|
||||
{t("common.search", "查询")}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={handleReset}>
|
||||
<X className="mr-1 h-4 w-4" />
|
||||
{t("common.reset", "重置")}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={handleRefresh}>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex items-center gap-2 ml-auto">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={handleSearch}
|
||||
className="h-8"
|
||||
>
|
||||
<Search className="mr-2 h-3.5 w-3.5" />
|
||||
{t("common.search", "查询")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleReset}
|
||||
className="h-8"
|
||||
>
|
||||
<X className="mr-2 h-3.5 w-3.5" />
|
||||
{t("common.reset", "重置")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleRefresh}
|
||||
className="h-8 px-2"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -189,40 +217,34 @@ export function RequestLogTable() {
|
||||
<div className="h-[400px] animate-pulse rounded bg-gray-100" />
|
||||
) : (
|
||||
<>
|
||||
<div className="rounded-md bg-card/60 shadow-sm overflow-x-auto">
|
||||
<div className="rounded-lg border border-border/50 bg-card/40 backdrop-blur-sm overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="whitespace-nowrap">
|
||||
{t("usage.time", "时间")}
|
||||
</TableHead>
|
||||
<TableHead className="whitespace-nowrap">
|
||||
{t("usage.provider", "供应商")}
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[280px] whitespace-nowrap">
|
||||
<TableHead>{t("usage.time", "时间")}</TableHead>
|
||||
<TableHead>{t("usage.provider", "供应商")}</TableHead>
|
||||
<TableHead className="min-w-[280px]">
|
||||
{t("usage.billingModel", "计费模型")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right whitespace-nowrap">
|
||||
<TableHead className="text-right">
|
||||
{t("usage.inputTokens", "输入")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right whitespace-nowrap">
|
||||
<TableHead className="text-right">
|
||||
{t("usage.outputTokens", "输出")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right min-w-[90px] whitespace-nowrap">
|
||||
{t("usage.cacheReadTokens", "缓存读取")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right min-w-[90px] whitespace-nowrap">
|
||||
<TableHead className="text-right min-w-[90px]">
|
||||
{t("usage.cacheCreationTokens", "缓存写入")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right whitespace-nowrap">
|
||||
<TableHead className="text-right min-w-[90px]">
|
||||
{t("usage.cacheReadTokens", "缓存读取")}
|
||||
</TableHead>
|
||||
<TableHead className="text-right">
|
||||
{t("usage.totalCost", "成本")}
|
||||
</TableHead>
|
||||
<TableHead className="text-center min-w-[140px] whitespace-nowrap">
|
||||
<TableHead className="text-center min-w-[140px]">
|
||||
{t("usage.timingInfo", "用时/首字")}
|
||||
</TableHead>
|
||||
<TableHead className="whitespace-nowrap">
|
||||
{t("usage.status", "状态")}
|
||||
</TableHead>
|
||||
<TableHead>{t("usage.status", "状态")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -258,10 +280,10 @@ export function RequestLogTable() {
|
||||
{log.outputTokens.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{log.cacheReadTokens.toLocaleString()}
|
||||
{log.cacheCreationTokens.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{log.cacheCreationTokens.toLocaleString()}
|
||||
{log.cacheReadTokens.toLocaleString()}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
${parseFloat(log.totalCostUsd).toFixed(6)}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { UsageSummaryCards } from "./UsageSummaryCards";
|
||||
import { UsageTrendChart } from "./UsageTrendChart";
|
||||
import { RequestLogTable } from "./RequestLogTable";
|
||||
import { ProviderStatsTable } from "./ProviderStatsTable";
|
||||
import { ModelStatsTable } from "./ModelStatsTable";
|
||||
import type { TimeRange } from "@/types/usage";
|
||||
import { motion } from "framer-motion";
|
||||
import { BarChart3, ListFilter, Activity } from "lucide-react";
|
||||
|
||||
export function UsageDashboard() {
|
||||
const { t } = useTranslation();
|
||||
@@ -16,50 +17,90 @@ export function UsageDashboard() {
|
||||
const days = timeRange === "1d" ? 1 : timeRange === "7d" ? 7 : 30;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-end">
|
||||
<select
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.4 }}
|
||||
className="space-y-8 pb-8"
|
||||
>
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h2 className="text-2xl font-bold">{t("usage.title", "使用统计")}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("usage.subtitle", "查看 AI 模型的使用情况和成本统计")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs
|
||||
value={timeRange}
|
||||
onChange={(e) => setTimeRange(e.target.value as TimeRange)}
|
||||
className="rounded-md border px-3 py-1.5 text-sm"
|
||||
onValueChange={(v) => setTimeRange(v as TimeRange)}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<option value="1d">{t("usage.today", "今天")}</option>
|
||||
<option value="7d">{t("usage.last7days", "过去 7 天")}</option>
|
||||
<option value="30d">{t("usage.last30days", "过去 30 天")}</option>
|
||||
</select>
|
||||
<TabsList className="flex w-full sm:w-auto bg-card/60 border border-border/50 backdrop-blur-sm shadow-sm h-10 p-1">
|
||||
<TabsTrigger
|
||||
value="1d"
|
||||
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
|
||||
>
|
||||
{t("usage.today", "24小时")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="7d"
|
||||
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
|
||||
>
|
||||
{t("usage.last7days", "7天")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="30d"
|
||||
className="flex-1 sm:flex-none sm:px-6 data-[state=active]:bg-primary/10 data-[state=active]:text-primary hover:text-primary transition-colors"
|
||||
>
|
||||
{t("usage.last30days", "30天")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
<UsageSummaryCards days={days} />
|
||||
|
||||
<Card className="border-none bg-transparent p-0 shadow-none">
|
||||
<UsageTrendChart days={days} />
|
||||
</Card>
|
||||
<UsageTrendChart days={days} />
|
||||
|
||||
<Tabs defaultValue="logs" className="w-full">
|
||||
<TabsList>
|
||||
<TabsTrigger value="logs">
|
||||
{t("usage.requestLogs", "请求日志")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="providers">
|
||||
{t("usage.providerStats", "Provider 统计")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="models">
|
||||
{t("usage.modelStats", "模型统计")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<div className="space-y-4">
|
||||
<Tabs defaultValue="logs" className="w-full">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<TabsList className="bg-muted/50">
|
||||
<TabsTrigger value="logs" className="gap-2">
|
||||
<ListFilter className="h-4 w-4" />
|
||||
{t("usage.requestLogs", "请求日志")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="providers" className="gap-2">
|
||||
<Activity className="h-4 w-4" />
|
||||
{t("usage.providerStats", "Provider 统计")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="models" className="gap-2">
|
||||
<BarChart3 className="h-4 w-4" />
|
||||
{t("usage.modelStats", "模型统计")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<TabsContent value="logs" className="mt-4">
|
||||
<RequestLogTable />
|
||||
</TabsContent>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<TabsContent value="logs" className="mt-0">
|
||||
<RequestLogTable />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="providers" className="mt-4">
|
||||
<ProviderStatsTable />
|
||||
</TabsContent>
|
||||
<TabsContent value="providers" className="mt-0">
|
||||
<ProviderStatsTable />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="models" className="mt-4">
|
||||
<ModelStatsTable />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
<TabsContent value="models" className="mt-0">
|
||||
<ModelStatsTable />
|
||||
</TabsContent>
|
||||
</motion.div>
|
||||
</Tabs>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { useUsageSummary } from "@/lib/query/usage";
|
||||
import { Activity, DollarSign, Layers, Database, Loader2 } from "lucide-react";
|
||||
import { motion } from "framer-motion";
|
||||
|
||||
interface UsageSummaryCardsProps {
|
||||
days: number;
|
||||
@@ -8,29 +11,118 @@ interface UsageSummaryCardsProps {
|
||||
|
||||
export function UsageSummaryCards({ days }: UsageSummaryCardsProps) {
|
||||
const { t } = useTranslation();
|
||||
const endDate = Math.floor(Date.now() / 1000);
|
||||
const startDate = endDate - days * 24 * 60 * 60;
|
||||
|
||||
const { startDate, endDate } = useMemo(() => {
|
||||
const end = Math.floor(Date.now() / 1000);
|
||||
const start = end - days * 24 * 60 * 60;
|
||||
return { startDate: start, endDate: end };
|
||||
}, [days]);
|
||||
|
||||
const { data: summary, isLoading } = useUsageSummary(startDate, endDate);
|
||||
const totalRequests = summary?.totalRequests ?? 0;
|
||||
const totalCost = parseFloat(summary?.totalCost || "0").toFixed(4);
|
||||
const totalInputTokens = summary?.totalInputTokens ?? 0;
|
||||
const totalOutputTokens = summary?.totalOutputTokens ?? 0;
|
||||
const totalTokens = totalInputTokens + totalOutputTokens;
|
||||
const cacheWriteTokens = summary?.totalCacheCreationTokens ?? 0;
|
||||
const cacheReadTokens = summary?.totalCacheReadTokens ?? 0;
|
||||
const totalCacheTokens = cacheWriteTokens + cacheReadTokens;
|
||||
|
||||
const stats = useMemo(() => {
|
||||
const totalRequests = summary?.totalRequests ?? 0;
|
||||
const totalCost = parseFloat(summary?.totalCost || "0");
|
||||
|
||||
const inputTokens = summary?.totalInputTokens ?? 0;
|
||||
const outputTokens = summary?.totalOutputTokens ?? 0;
|
||||
const totalTokens = inputTokens + outputTokens;
|
||||
|
||||
const cacheWriteTokens = summary?.totalCacheCreationTokens ?? 0;
|
||||
const cacheReadTokens = summary?.totalCacheReadTokens ?? 0;
|
||||
const totalCacheTokens = cacheWriteTokens + cacheReadTokens;
|
||||
|
||||
return [
|
||||
{
|
||||
title: t("usage.totalRequests", "总请求数"),
|
||||
value: totalRequests.toLocaleString(),
|
||||
icon: Activity,
|
||||
color: "text-blue-500",
|
||||
bg: "bg-blue-500/10",
|
||||
subValue: null,
|
||||
},
|
||||
{
|
||||
title: t("usage.totalCost", "总成本"),
|
||||
value: `$${totalCost.toFixed(4)}`,
|
||||
icon: DollarSign,
|
||||
color: "text-green-500",
|
||||
bg: "bg-green-500/10",
|
||||
subValue: null,
|
||||
},
|
||||
{
|
||||
title: t("usage.totalTokens", "总 Token 数"),
|
||||
value: totalTokens.toLocaleString(),
|
||||
icon: Layers,
|
||||
color: "text-purple-500",
|
||||
bg: "bg-purple-500/10",
|
||||
subValue: (
|
||||
<div className="flex flex-col gap-1 text-xs text-muted-foreground mt-3 pt-3 border-t border-border/50">
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Input</span>
|
||||
<span className="text-foreground/80">
|
||||
{(inputTokens / 1000).toFixed(1)}k
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Output</span>
|
||||
<span className="text-foreground/80">
|
||||
{(outputTokens / 1000).toFixed(1)}k
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t("usage.cacheTokens", "缓存 Token"),
|
||||
value: totalCacheTokens.toLocaleString(),
|
||||
icon: Database,
|
||||
color: "text-orange-500",
|
||||
bg: "bg-orange-500/10",
|
||||
subValue: (
|
||||
<div className="flex flex-col gap-1 text-xs text-muted-foreground mt-3 pt-3 border-t border-border/50">
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Write</span>
|
||||
<span className="text-foreground/80">
|
||||
{(cacheWriteTokens / 1000).toFixed(1)}k
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span>Read</span>
|
||||
<span className="text-foreground/80">
|
||||
{(cacheReadTokens / 1000).toFixed(1)}k
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
}, [summary, t]);
|
||||
|
||||
const container = {
|
||||
hidden: { opacity: 0 },
|
||||
show: {
|
||||
opacity: 1,
|
||||
transition: {
|
||||
staggerChildren: 0.1,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const item = {
|
||||
hidden: { opacity: 0, y: 20 },
|
||||
show: { opacity: 1, y: 0 },
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
{[...Array(4)].map((_, i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader className="pb-2">
|
||||
<div className="h-4 w-24 animate-pulse rounded bg-gray-200" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-8 w-32 animate-pulse rounded bg-gray-200" />
|
||||
<Card
|
||||
key={i}
|
||||
className="border border-border/50 bg-card/40 backdrop-blur-sm shadow-sm"
|
||||
>
|
||||
<CardContent className="p-6 flex items-center justify-center min-h-[160px]">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground/50" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
@@ -39,75 +131,39 @@ export function UsageSummaryCards({ days }: UsageSummaryCardsProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.totalRequests", "总请求数")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{totalRequests.toLocaleString()}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<motion.div
|
||||
variants={container}
|
||||
initial="hidden"
|
||||
animate="show"
|
||||
className="grid gap-4 md:grid-cols-4"
|
||||
>
|
||||
{stats.map((stat, i) => (
|
||||
<motion.div key={i} variants={item}>
|
||||
<Card className="relative h-full overflow-hidden border border-border/50 bg-gradient-to-br from-card/50 to-background/50 backdrop-blur-xl hover:from-card/60 hover:to-background/60 transition-all shadow-sm">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<p className="text-sm font-medium text-muted-foreground">
|
||||
{stat.title}
|
||||
</p>
|
||||
<div className={`p-2 rounded-lg ${stat.bg}`}>
|
||||
<stat.icon className={`h-4 w-4 ${stat.color}`} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.totalCost", "总成本")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">${totalCost}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-2xl font-bold truncate" title={stat.value}>
|
||||
{stat.value}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.totalTokens", "总 Token 数")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{totalTokens.toLocaleString()}
|
||||
</div>
|
||||
<div className="mt-2 space-y-1 text-sm text-muted-foreground">
|
||||
<div>
|
||||
{t("usage.inputTokens", "输入")}:{" "}
|
||||
{totalInputTokens.toLocaleString()}
|
||||
</div>
|
||||
<div>
|
||||
{t("usage.outputTokens", "输出")}:{" "}
|
||||
{totalOutputTokens.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">
|
||||
{t("usage.cacheTokens", "缓存 Token")}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">
|
||||
{totalCacheTokens.toLocaleString()}
|
||||
</div>
|
||||
<div className="mt-2 space-y-1 text-sm text-muted-foreground">
|
||||
<div>
|
||||
{t("usage.cacheWrite", "写入")}:{" "}
|
||||
{cacheWriteTokens.toLocaleString()}
|
||||
</div>
|
||||
<div>
|
||||
{t("usage.cacheRead", "读取")}: {cacheReadTokens.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
{stat.subValue || (
|
||||
/* Placeholder to properly align cards if no subvalue (first 2 cards) - effectively adding empty space or using flex-1 equivalent */
|
||||
<div className="mt-3 pt-3 border-t border-transparent h-[52px]"></div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
AreaChart,
|
||||
Area,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Legend,
|
||||
} from "recharts";
|
||||
import { useUsageTrends } from "@/lib/query/usage";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
interface UsageTrendChartProps {
|
||||
days: number;
|
||||
@@ -20,7 +21,11 @@ export function UsageTrendChart({ days }: UsageTrendChartProps) {
|
||||
const { data: trends, isLoading } = useUsageTrends(days);
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="h-[320px] animate-pulse rounded bg-gray-100" />;
|
||||
return (
|
||||
<div className="flex h-[350px] items-center justify-center rounded-xl bg-card/40 border border-border/50">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground/30" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const isToday = days === 1;
|
||||
@@ -38,8 +43,6 @@ export function UsageTrendChart({ days }: UsageTrendChartProps) {
|
||||
hour: pointDate.getHours(),
|
||||
inputTokens: stat.totalInputTokens,
|
||||
outputTokens: stat.totalOutputTokens,
|
||||
cacheCreationTokens: stat.totalCacheCreationTokens,
|
||||
cacheReadTokens: stat.totalCacheReadTokens,
|
||||
cost: parseFloat(stat.totalCost),
|
||||
};
|
||||
}) || [];
|
||||
@@ -56,8 +59,6 @@ export function UsageTrendChart({ days }: UsageTrendChartProps) {
|
||||
label: `${hour.toString().padStart(2, "0")}:00`,
|
||||
inputTokens: bucket?.inputTokens ?? 0,
|
||||
outputTokens: bucket?.outputTokens ?? 0,
|
||||
cacheCreationTokens: bucket?.cacheCreationTokens ?? 0,
|
||||
cacheReadTokens: bucket?.cacheReadTokens ?? 0,
|
||||
cost: bucket?.cost ?? 0,
|
||||
};
|
||||
});
|
||||
@@ -65,96 +66,129 @@ export function UsageTrendChart({ days }: UsageTrendChartProps) {
|
||||
|
||||
const displayData = isToday ? hourlyData : chartData;
|
||||
|
||||
const rangeLabel = isToday
|
||||
? t("usage.rangeToday", "今天 (按小时)")
|
||||
: days === 7
|
||||
? t("usage.rangeLast7Days", "过去 7 天")
|
||||
: t("usage.rangeLast30Days", "过去 30 天");
|
||||
const CustomTooltip = ({ active, payload, label }: any) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div className="rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-md">
|
||||
<p className="mb-2 font-medium">{label}</p>
|
||||
{payload.map((entry: any, index: number) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-2 text-sm"
|
||||
style={{ color: entry.color }}
|
||||
>
|
||||
<div
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ backgroundColor: entry.color }}
|
||||
/>
|
||||
<span className="font-medium">{entry.name}:</span>
|
||||
<span>
|
||||
{entry.name.includes(t("usage.cost", "成本"))
|
||||
? `$${typeof entry.value === "number" ? entry.value.toFixed(6) : entry.value}`
|
||||
: entry.value.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="rounded-xl border border-border/50 bg-card/40 p-6 backdrop-blur-sm">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("usage.trends", "使用趋势")}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">{rangeLabel}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{isToday
|
||||
? t("usage.rangeToday", "今天 (按小时)")
|
||||
: days === 7
|
||||
? t("usage.rangeLast7Days", "过去 7 天")
|
||||
: t("usage.rangeLast30Days", "过去 30 天")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ResponsiveContainer width="100%" height={320}>
|
||||
<LineChart data={displayData}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="label" />
|
||||
<YAxis
|
||||
yAxisId="tokens"
|
||||
label={{
|
||||
value: t("usage.tokensAxis", "Tokens"),
|
||||
angle: -90,
|
||||
position: "insideLeft",
|
||||
}}
|
||||
/>
|
||||
<YAxis
|
||||
yAxisId="cost"
|
||||
orientation="right"
|
||||
label={{
|
||||
value: t("usage.costAxis", "成本 (USD)"),
|
||||
angle: 90,
|
||||
position: "insideRight",
|
||||
}}
|
||||
/>
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
<Line
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="inputTokens"
|
||||
name={t("usage.inputTokens", "输入 Tokens")}
|
||||
stroke="#2563eb"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
<Line
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="outputTokens"
|
||||
name={t("usage.outputTokens", "输出 Tokens")}
|
||||
stroke="#16a34a"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
<Line
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="cacheCreationTokens"
|
||||
name={t("usage.cacheCreationTokens", "缓存写入")}
|
||||
stroke="#f97316"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
<Line
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="cacheReadTokens"
|
||||
name={t("usage.cacheReadTokens", "缓存读取")}
|
||||
stroke="#a855f7"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
<Line
|
||||
yAxisId="cost"
|
||||
type="monotone"
|
||||
dataKey="cost"
|
||||
name={t("usage.cost", "成本")}
|
||||
stroke="#dc2626"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
isAnimationActive
|
||||
/>
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
<div className="h-[350px] w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart
|
||||
data={displayData}
|
||||
margin={{ top: 10, right: 10, left: 0, bottom: 0 }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="colorInput" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.2} />
|
||||
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
<linearGradient id="colorOutput" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#22c55e" stopOpacity={0.2} />
|
||||
<stop offset="95%" stopColor="#22c55e" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
vertical={false}
|
||||
stroke="hsl(var(--border))"
|
||||
opacity={0.4}
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="label"
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 12 }}
|
||||
dy={10}
|
||||
/>
|
||||
<YAxis
|
||||
yAxisId="tokens"
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 12 }}
|
||||
tickFormatter={(value) => `${(value / 1000).toFixed(0)}k`}
|
||||
/>
|
||||
<YAxis
|
||||
yAxisId="cost"
|
||||
orientation="right"
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fill: "hsl(var(--muted-foreground))", fontSize: 12 }}
|
||||
tickFormatter={(value) => `$${value}`}
|
||||
/>
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Legend />
|
||||
<Area
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="inputTokens"
|
||||
name={t("usage.inputTokens", "输入 Tokens")}
|
||||
stroke="#3b82f6"
|
||||
fillOpacity={1}
|
||||
fill="url(#colorInput)"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<Area
|
||||
yAxisId="tokens"
|
||||
type="monotone"
|
||||
dataKey="outputTokens"
|
||||
name={t("usage.outputTokens", "输出 Tokens")}
|
||||
stroke="#22c55e"
|
||||
fillOpacity={1}
|
||||
fill="url(#colorOutput)"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<Area
|
||||
yAxisId="cost"
|
||||
type="monotone"
|
||||
dataKey="cost"
|
||||
name={t("usage.cost", "成本")}
|
||||
stroke="#f43f5e"
|
||||
fill="none"
|
||||
strokeWidth={2}
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
useUpdateProviderMutation,
|
||||
useDeleteProviderMutation,
|
||||
useSwitchProviderMutation,
|
||||
useSetProxyTargetMutation,
|
||||
} from "@/lib/query";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
|
||||
@@ -25,7 +24,6 @@ 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(
|
||||
@@ -93,14 +91,6 @@ 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) => {
|
||||
@@ -146,14 +136,12 @@ export function useProviderActions(activeApp: AppId) {
|
||||
addProvider,
|
||||
updateProvider,
|
||||
switchProvider,
|
||||
setProxyTarget,
|
||||
deleteProvider,
|
||||
saveUsageScript,
|
||||
isLoading:
|
||||
addProviderMutation.isPending ||
|
||||
updateProviderMutation.isPending ||
|
||||
deleteProviderMutation.isPending ||
|
||||
switchProviderMutation.isPending ||
|
||||
setProxyTargetMutation.isPending,
|
||||
switchProviderMutation.isPending,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type {
|
||||
ProviderHealth,
|
||||
CircuitBreakerConfig,
|
||||
CircuitBreakerStats,
|
||||
} from "@/types/proxy";
|
||||
|
||||
export interface Provider {
|
||||
id: string;
|
||||
name: string;
|
||||
settingsConfig: unknown;
|
||||
websiteUrl?: string;
|
||||
category?: string;
|
||||
createdAt?: number;
|
||||
sortIndex?: number;
|
||||
notes?: string;
|
||||
meta?: unknown;
|
||||
icon?: string;
|
||||
iconColor?: string;
|
||||
isProxyTarget?: boolean;
|
||||
}
|
||||
|
||||
export const failoverApi = {
|
||||
// 获取代理目标列表
|
||||
async getProxyTargets(appType: string): Promise<Provider[]> {
|
||||
return invoke("get_proxy_targets", { appType });
|
||||
},
|
||||
|
||||
// 设置代理目标
|
||||
async setProxyTarget(
|
||||
providerId: string,
|
||||
appType: string,
|
||||
enabled: boolean,
|
||||
): Promise<void> {
|
||||
return invoke("set_proxy_target", { providerId, appType, enabled });
|
||||
},
|
||||
|
||||
// 获取供应商健康状态
|
||||
async getProviderHealth(
|
||||
providerId: string,
|
||||
appType: string,
|
||||
): Promise<ProviderHealth> {
|
||||
return invoke("get_provider_health", { providerId, appType });
|
||||
},
|
||||
|
||||
// 重置熔断器
|
||||
async resetCircuitBreaker(
|
||||
providerId: string,
|
||||
appType: string,
|
||||
): Promise<void> {
|
||||
return invoke("reset_circuit_breaker", { providerId, appType });
|
||||
},
|
||||
|
||||
// 获取熔断器配置
|
||||
async getCircuitBreakerConfig(): Promise<CircuitBreakerConfig> {
|
||||
return invoke("get_circuit_breaker_config");
|
||||
},
|
||||
|
||||
// 更新熔断器配置
|
||||
async updateCircuitBreakerConfig(
|
||||
config: CircuitBreakerConfig,
|
||||
): Promise<void> {
|
||||
return invoke("update_circuit_breaker_config", { config });
|
||||
},
|
||||
|
||||
// 获取熔断器统计信息
|
||||
async getCircuitBreakerStats(
|
||||
providerId: string,
|
||||
appType: string,
|
||||
): Promise<CircuitBreakerStats | null> {
|
||||
return invoke("get_circuit_breaker_stats", { providerId, appType });
|
||||
},
|
||||
};
|
||||
@@ -115,4 +115,15 @@ export const settingsApi = {
|
||||
async getAutoLaunchStatus(): Promise<boolean> {
|
||||
return await invoke("get_auto_launch_status");
|
||||
},
|
||||
|
||||
async getToolVersions(): Promise<
|
||||
Array<{
|
||||
name: string;
|
||||
version: string | null;
|
||||
latest_version: string | null;
|
||||
error: string | null;
|
||||
}>
|
||||
> {
|
||||
return await invoke("get_tool_versions");
|
||||
},
|
||||
};
|
||||
|
||||
+6
-20
@@ -19,31 +19,17 @@ export interface SkillRepo {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export type AppType = "claude" | "codex" | "gemini";
|
||||
|
||||
export const skillsApi = {
|
||||
async getAll(app: AppType = "claude"): Promise<Skill[]> {
|
||||
if (app === "claude") {
|
||||
return await invoke("get_skills");
|
||||
}
|
||||
return await invoke("get_skills_for_app", { app });
|
||||
async getAll(): Promise<Skill[]> {
|
||||
return await invoke("get_skills");
|
||||
},
|
||||
|
||||
async install(directory: string, app: AppType = "claude"): Promise<boolean> {
|
||||
if (app === "claude") {
|
||||
return await invoke("install_skill", { directory });
|
||||
}
|
||||
return await invoke("install_skill_for_app", { app, directory });
|
||||
async install(directory: string): Promise<boolean> {
|
||||
return await invoke("install_skill", { directory });
|
||||
},
|
||||
|
||||
async uninstall(
|
||||
directory: string,
|
||||
app: AppType = "claude",
|
||||
): Promise<boolean> {
|
||||
if (app === "claude") {
|
||||
return await invoke("uninstall_skill", { directory });
|
||||
}
|
||||
return await invoke("uninstall_skill_for_app", { app, directory });
|
||||
async uninstall(directory: string): Promise<boolean> {
|
||||
return await invoke("uninstall_skill", { directory });
|
||||
},
|
||||
|
||||
async getRepos(): Promise<SkillRepo[]> {
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { failoverApi } from "@/lib/api/failover";
|
||||
|
||||
/**
|
||||
* 获取代理目标列表
|
||||
*/
|
||||
export function useProxyTargets(appType: string) {
|
||||
return useQuery({
|
||||
queryKey: ["proxyTargets", appType],
|
||||
queryFn: () => failoverApi.getProxyTargets(appType),
|
||||
enabled: !!appType,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取供应商健康状态
|
||||
*/
|
||||
export function useProviderHealth(providerId: string, appType: string) {
|
||||
return useQuery({
|
||||
queryKey: ["providerHealth", providerId, appType],
|
||||
queryFn: () => failoverApi.getProviderHealth(providerId, appType),
|
||||
enabled: !!providerId && !!appType,
|
||||
refetchInterval: 5000, // 每 5 秒刷新一次
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置代理目标
|
||||
*/
|
||||
export function useSetProxyTarget() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
providerId,
|
||||
appType,
|
||||
enabled,
|
||||
}: {
|
||||
providerId: string;
|
||||
appType: string;
|
||||
enabled: boolean;
|
||||
}) => failoverApi.setProxyTarget(providerId, appType, enabled),
|
||||
onSuccess: (_, variables) => {
|
||||
// 刷新代理目标列表
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["proxyTargets", variables.appType],
|
||||
});
|
||||
// 刷新供应商列表
|
||||
queryClient.invalidateQueries({ queryKey: ["providers"] });
|
||||
// 刷新健康状态
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providerHealth", variables.providerId, variables.appType],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置熔断器
|
||||
*/
|
||||
export function useResetCircuitBreaker() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
providerId,
|
||||
appType,
|
||||
}: {
|
||||
providerId: string;
|
||||
appType: string;
|
||||
}) => failoverApi.resetCircuitBreaker(providerId, appType),
|
||||
onSuccess: (_, variables) => {
|
||||
// 刷新健康状态
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["providerHealth", variables.providerId, variables.appType],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取熔断器配置
|
||||
*/
|
||||
export function useCircuitBreakerConfig() {
|
||||
return useQuery({
|
||||
queryKey: ["circuitBreakerConfig"],
|
||||
queryFn: () => failoverApi.getCircuitBreakerConfig(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新熔断器配置
|
||||
*/
|
||||
export function useUpdateCircuitBreakerConfig() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: failoverApi.updateCircuitBreakerConfig,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["circuitBreakerConfig"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取熔断器统计信息
|
||||
*/
|
||||
export function useCircuitBreakerStats(providerId: string, appType: string) {
|
||||
return useQuery({
|
||||
queryKey: ["circuitBreakerStats", providerId, appType],
|
||||
queryFn: () => failoverApi.getCircuitBreakerStats(providerId, appType),
|
||||
enabled: !!providerId && !!appType,
|
||||
refetchInterval: 5000, // 每 5 秒刷新一次
|
||||
});
|
||||
}
|
||||
@@ -34,12 +34,22 @@ export interface ProvidersQueryData {
|
||||
currentProviderId: string;
|
||||
}
|
||||
|
||||
export interface UseProvidersQueryOptions {
|
||||
isProxyRunning?: boolean; // 代理服务是否运行中
|
||||
}
|
||||
|
||||
export const useProvidersQuery = (
|
||||
appId: AppId,
|
||||
options?: UseProvidersQueryOptions,
|
||||
): UseQueryResult<ProvidersQueryData> => {
|
||||
const { isProxyRunning = false } = options || {};
|
||||
|
||||
return useQuery({
|
||||
queryKey: ["providers", appId],
|
||||
placeholderData: keepPreviousData,
|
||||
// 当代理服务运行时,每 10 秒刷新一次供应商列表
|
||||
// 这样可以自动反映后端熔断器自动禁用代理目标的变更
|
||||
refetchInterval: isProxyRunning ? 10000 : false,
|
||||
queryFn: async () => {
|
||||
let providers: Record<string, Provider> = {};
|
||||
let currentProviderId = "";
|
||||
|
||||
@@ -48,6 +48,39 @@ export interface ProviderHealth {
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
// 熔断器相关类型
|
||||
export interface CircuitBreakerConfig {
|
||||
failureThreshold: number;
|
||||
successThreshold: number;
|
||||
timeoutSeconds: number;
|
||||
errorRateThreshold: number;
|
||||
minRequests: number;
|
||||
}
|
||||
|
||||
export type CircuitState = "closed" | "open" | "half_open";
|
||||
|
||||
export interface CircuitBreakerStats {
|
||||
state: CircuitState;
|
||||
consecutiveFailures: number;
|
||||
consecutiveSuccesses: number;
|
||||
totalRequests: number;
|
||||
failedRequests: number;
|
||||
}
|
||||
|
||||
// 供应商健康状态枚举
|
||||
export enum ProviderHealthStatus {
|
||||
Healthy = "healthy",
|
||||
Degraded = "degraded",
|
||||
Failed = "failed",
|
||||
Unknown = "unknown",
|
||||
}
|
||||
|
||||
// 扩展 ProviderHealth 以包含前端计算的状态
|
||||
export interface ProviderHealthWithStatus extends ProviderHealth {
|
||||
status: ProviderHealthStatus;
|
||||
circuitState?: CircuitState;
|
||||
}
|
||||
|
||||
export interface ProxyUsageRecord {
|
||||
provider_id: string;
|
||||
app_type: string;
|
||||
|
||||
Reference in New Issue
Block a user