mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-28 00:35:32 +08:00
1586451862
* feat(failover): add auto-failover master switch with proxy integration
- Add persistent auto_failover_enabled setting in database
- Add get/set_auto_failover_enabled commands
- Provider router respects master switch state
- Proxy shutdown automatically disables failover
- Enabling failover auto-starts proxy server
- Optimistic updates for failover queue toggle
* feat(proxy): persist proxy takeover state across app restarts
- Add proxy_takeover_{app_type} settings for per-app state tracking
- Restore proxy takeover state automatically on app startup
- Preserve state on normal exit, clear on manual stop
- Add stop_with_restore_keep_state method for graceful shutdown
* fix(proxy): set takeover state for all apps in start_with_takeover
* fix(windows): hide console window when checking CLI versions
Add CREATE_NO_WINDOW flag to prevent command prompt from flashing
when detecting claude/codex/gemini CLI versions on Windows.
* refactor(failover): make auto-failover toggle per-app independent
- Change setting key from 'auto_failover_enabled' to 'auto_failover_enabled_{app_type}'
- Update provider_router to check per-app failover setting
- When failover disabled, use current provider only; when enabled, use queue order
- Add unit tests for failover enabled/disabled behavior
* feat(failover): auto-switch to higher priority provider on recovery
- After circuit breaker reset, check if recovered provider has higher priority
- Automatically switch back if queue_order is lower (higher priority)
- Stream health check now resets circuit breaker on success/degraded
* chore: remove unused start_proxy_with_takeover command
- Remove command registration from lib.rs
- Add comment clarifying failover queue is preserved on proxy stop
* feat(ui): integrate failover controls into provider cards
- Add failover toggle button to provider card actions
- Show priority badge (P1, P2, ...) for queued providers
- Highlight active provider with green border in failover mode
- Sync drag-drop order with failover queue
- Move per-app failover toggle to FailoverQueueManager
- Simplify SettingsPage failover section
* test(providers): add mocks for failover hooks in ProviderList tests
* refactor(failover): merge failover_queue table into providers
- Add in_failover_queue field to providers table
- Remove standalone failover_queue table and related indexes
- Simplify queue ordering by reusing sort_index field
- Remove reorder_failover_queue and set_failover_item_enabled commands
- Update frontend to use simplified FailoverQueueItem type
* fix(database): ensure in_failover_queue column exists for v2 databases
Add column check in create_tables to handle existing v2 databases
that were created before the failover queue refactor.
* fix(ui): differentiate active provider border color by proxy mode
- Use green border/gradient when proxy takeover is active
- Use blue border/gradient in normal mode (no proxy)
- Improves visual distinction between proxy and non-proxy states
* fix(database): clear provider health record when removing from failover queue
When a provider is removed from the failover queue, its health monitoring
is no longer needed. This change ensures the health record is also deleted
from the database to prevent stale data.
* fix(failover): improve cache cleanup for provider health and circuit breaker
- Use removeQueries instead of invalidateQueries when stopping proxy to
completely clear health and circuit breaker caches
- Clear provider health and circuit breaker caches when removing from
failover queue
- Refresh failover queue after drag-sort since queue order depends on
sort_index
- Only show health badge when provider is in failover queue
* style: apply prettier formatting to App.tsx and ProviderList.tsx
* fix(proxy): handle missing health records and clear health on proxy stop
- Return default healthy state when provider health record not found
- Add clear_provider_health_for_app to clear health for specific app
- Clear app health records when stopping proxy takeover
* fix(proxy): track actual provider used in forwarding for accurate logging
Introduce ForwardResult and ForwardError structs to return the actual
provider that handled the request. This ensures usage statistics and
error logs reflect the correct provider after failover.
209 lines
6.3 KiB
TypeScript
209 lines
6.3 KiB
TypeScript
/**
|
|
* 代理服务状态管理 Hook
|
|
*/
|
|
|
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import { invoke } from "@tauri-apps/api/core";
|
|
import { toast } from "sonner";
|
|
import { useTranslation } from "react-i18next";
|
|
import type {
|
|
ProxyStatus,
|
|
ProxyServerInfo,
|
|
ProxyTakeoverStatus,
|
|
} from "@/types/proxy";
|
|
import { extractErrorMessage } from "@/utils/errorUtils";
|
|
|
|
/**
|
|
* 代理服务状态管理
|
|
*/
|
|
export function useProxyStatus() {
|
|
const queryClient = useQueryClient();
|
|
const { t } = useTranslation();
|
|
|
|
// 查询状态(自动轮询)
|
|
const { data: status, isLoading } = useQuery({
|
|
queryKey: ["proxyStatus"],
|
|
queryFn: () => invoke<ProxyStatus>("get_proxy_status"),
|
|
// 仅在服务运行时轮询
|
|
refetchInterval: (query) => (query.state.data?.running ? 2000 : false),
|
|
// 保持之前的数据,避免闪烁
|
|
placeholderData: (previousData) => previousData,
|
|
});
|
|
|
|
// 查询各应用接管状态
|
|
const { data: takeoverStatus } = useQuery({
|
|
queryKey: ["proxyTakeoverStatus"],
|
|
queryFn: () => invoke<ProxyTakeoverStatus>("get_proxy_takeover_status"),
|
|
placeholderData: (previousData) => previousData,
|
|
});
|
|
|
|
// 启动服务器(总开关:仅启动服务,不接管)
|
|
const startProxyServerMutation = useMutation({
|
|
mutationFn: () => invoke<ProxyServerInfo>("start_proxy_server"),
|
|
onSuccess: (info) => {
|
|
toast.success(
|
|
t("proxy.server.started", {
|
|
defaultValue: `代理服务已启动 - ${info.address}:${info.port}`,
|
|
}),
|
|
{ closeButton: true },
|
|
);
|
|
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
|
},
|
|
onError: (error: Error) => {
|
|
const detail =
|
|
extractErrorMessage(error) ||
|
|
t("common.unknown", { defaultValue: "未知错误" });
|
|
toast.error(
|
|
t("proxy.server.startFailed", {
|
|
defaultValue: `启动代理服务失败: ${detail}`,
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
|
|
// 停止服务器(总开关关闭:强制恢复所有已接管的 Live 配置)
|
|
const stopWithRestoreMutation = useMutation({
|
|
mutationFn: () => invoke("stop_proxy_with_restore"),
|
|
onSuccess: () => {
|
|
toast.success(
|
|
t("proxy.stoppedWithRestore", {
|
|
defaultValue: "代理服务已关闭,已恢复所有接管配置",
|
|
}),
|
|
{ closeButton: true },
|
|
);
|
|
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
|
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverStatus"] });
|
|
// 彻底删除所有供应商健康状态缓存(后端已清空数据库记录)
|
|
queryClient.removeQueries({ queryKey: ["providerHealth"] });
|
|
// 彻底删除所有熔断器统计缓存(代理停止后熔断器状态已重置)
|
|
queryClient.removeQueries({ queryKey: ["circuitBreakerStats"] });
|
|
// 注意:故障转移队列和开关状态会保留,不需要刷新
|
|
},
|
|
onError: (error: Error) => {
|
|
const detail =
|
|
extractErrorMessage(error) ||
|
|
t("common.unknown", { defaultValue: "未知错误" });
|
|
toast.error(
|
|
t("proxy.stopWithRestoreFailed", {
|
|
defaultValue: `停止失败: ${detail}`,
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
|
|
// 按应用开启/关闭接管
|
|
const setTakeoverForAppMutation = useMutation({
|
|
mutationFn: ({ appType, enabled }: { appType: string; enabled: boolean }) =>
|
|
invoke("set_proxy_takeover_for_app", { appType, enabled }),
|
|
onSuccess: (_data, variables) => {
|
|
const appLabel =
|
|
variables.appType === "claude"
|
|
? "Claude"
|
|
: variables.appType === "codex"
|
|
? "Codex"
|
|
: "Gemini";
|
|
|
|
toast.success(
|
|
variables.enabled
|
|
? t("proxy.takeover.enabled", {
|
|
defaultValue: `已接管 ${appLabel} 配置(请求将走本地代理)`,
|
|
})
|
|
: t("proxy.takeover.disabled", {
|
|
defaultValue: `已恢复 ${appLabel} 配置`,
|
|
}),
|
|
{ closeButton: true },
|
|
);
|
|
|
|
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
|
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverStatus"] });
|
|
},
|
|
onError: (error: Error) => {
|
|
const detail =
|
|
extractErrorMessage(error) ||
|
|
t("common.unknown", { defaultValue: "未知错误" });
|
|
toast.error(
|
|
t("proxy.takeover.failed", {
|
|
defaultValue: `操作失败: ${detail}`,
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
|
|
// 代理模式切换供应商(热切换)
|
|
const switchProxyProviderMutation = useMutation({
|
|
mutationFn: ({
|
|
appType,
|
|
providerId,
|
|
}: {
|
|
appType: string;
|
|
providerId: string;
|
|
}) => invoke("switch_proxy_provider", { appType, providerId }),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
|
},
|
|
onError: (error: Error) => {
|
|
const detail =
|
|
extractErrorMessage(error) ||
|
|
t("common.unknown", { defaultValue: "未知错误" });
|
|
toast.error(
|
|
t("proxy.switchFailed", {
|
|
error: detail,
|
|
defaultValue: `切换失败: ${detail}`,
|
|
}),
|
|
);
|
|
},
|
|
});
|
|
|
|
// 检查是否运行中
|
|
const checkRunning = async () => {
|
|
try {
|
|
return await invoke<boolean>("is_proxy_running");
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
// 检查接管状态
|
|
const checkTakeoverActive = async () => {
|
|
try {
|
|
return await invoke<boolean>("is_live_takeover_active");
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
return {
|
|
status,
|
|
isLoading,
|
|
isRunning: status?.running || false,
|
|
takeoverStatus,
|
|
isTakeoverActive:
|
|
takeoverStatus?.claude ||
|
|
takeoverStatus?.codex ||
|
|
takeoverStatus?.gemini ||
|
|
false,
|
|
|
|
// 启动/停止(总开关)
|
|
startProxyServer: startProxyServerMutation.mutateAsync,
|
|
stopWithRestore: stopWithRestoreMutation.mutateAsync,
|
|
|
|
// 按应用接管开关
|
|
setTakeoverForApp: setTakeoverForAppMutation.mutateAsync,
|
|
|
|
// 代理模式下切换供应商
|
|
switchProxyProvider: switchProxyProviderMutation.mutateAsync,
|
|
|
|
// 状态检查
|
|
checkRunning,
|
|
checkTakeoverActive,
|
|
|
|
// 加载状态
|
|
isStarting: startProxyServerMutation.isPending,
|
|
isStopping: stopWithRestoreMutation.isPending,
|
|
isPending:
|
|
startProxyServerMutation.isPending ||
|
|
stopWithRestoreMutation.isPending ||
|
|
setTakeoverForAppMutation.isPending,
|
|
};
|
|
}
|