mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-24 21:30:17 +08:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 344a4f1a5c | |||
| 038b74b844 | |||
| f1e5afdae2 | |||
| c9ea13a7ce | |||
| 404ab5a1ae | |||
| 9a8f12a490 | |||
| 6a7c2df2d2 | |||
| 735b3b7d39 | |||
| cbc23764c0 | |||
| 2a541cfda4 | |||
| 5cc864c6aa | |||
| 87ca36fc6d | |||
| 86ebb524f7 | |||
| ed5ad7ad3d | |||
| 454c3ed111 | |||
| 08647ac3ba | |||
| 6acd6e5090 |
@@ -3,7 +3,6 @@
|
||||
# All-in-One Assistant for Claude Code, Codex & Gemini CLI
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/trending/typescript)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -12,21 +11,13 @@
|
||||
|
||||
English | [中文](README_ZH.md) | [日本語](README_JA.md) | [Changelog](CHANGELOG.md)
|
||||
|
||||
**From Provider Switcher to All-in-One AI CLI Management Platform**
|
||||
|
||||
Unified management for Claude Code, Codex & Gemini CLI provider configurations, MCP servers, Skills extensions, and system prompts.
|
||||
|
||||
</div>
|
||||
|
||||
## ❤️Sponsor
|
||||
|
||||

|
||||
|
||||
This project is sponsored by Z.ai, supporting us with their GLM CODING PLAN.
|
||||
|
||||
GLM CODING PLAN is a subscription service designed for AI coding, starting at just $3/month. It provides access to their flagship GLM-4.6 model across 10+ popular AI coding tools (Claude Code, Cline, Roo Code, etc.), offering developers top-tier, fast, and stable coding experiences.
|
||||
|
||||
Get 10% OFF the GLM CODING PLAN with [this link](https://z.ai/subscribe?ic=8JVLJQFSKB)!
|
||||
This project is sponsored by Z.ai, supporting us with their GLM CODING PLAN.GLM CODING PLAN is a subscription service designed for AI coding, starting at just $3/month. It provides access to their flagship GLM-4.6 model across 10+ popular AI coding tools (Claude Code, Cline, Roo Code, etc.), offering developers top-tier, fast, and stable coding experiences.Get 10% OFF the GLM CODING PLAN with [this link](https://z.ai/subscribe?ic=8JVLJQFSKB)!
|
||||
|
||||
---
|
||||
|
||||
@@ -41,6 +32,12 @@ Get 10% OFF the GLM CODING PLAN with [this link](https://z.ai/subscribe?ic=8JVLJ
|
||||
<td>Thanks to ShanDianShuo for sponsoring this project! ShanDianShuo is a local-first AI voice input: Millisecond latency, data stays on device, 4x faster than typing, AI-powered correction, Privacy-first, completely free. Doubles your coding efficiency with Claude Code! <a href="https://www.shandianshuo.cn">Free download</a> for Mac/Win</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></td>
|
||||
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses.AIGoCode has prepared a special benefit for CC Switch users: if you register via <a href="https://aigocode.com/invite/CC-SWITCH">this link</a>, you’ll receive an extra 10% bonus credit on your first top-up!
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
## Screenshots
|
||||
|
||||
+8
-10
@@ -3,7 +3,6 @@
|
||||
# Claude Code / Codex / Gemini CLI オールインワン・アシスタント
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/trending/typescript)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -12,21 +11,13 @@
|
||||
|
||||
[English](README.md) | [中文](README_ZH.md) | 日本語 | [Changelog](CHANGELOG.md) | [v3.8.0 リリースノート](docs/release-note-v3.8.0-en.md)
|
||||
|
||||
**プロバイダスイッチャーから AI CLI 一体型管理プラットフォームへ**
|
||||
|
||||
Claude Code・Codex・Gemini CLI のプロバイダ設定、MCP サーバー、Skills 拡張、システムプロンプトを統合管理。
|
||||
|
||||
</div>
|
||||
|
||||
## ❤️スポンサー
|
||||
|
||||

|
||||
|
||||
本プロジェクトは Z.ai の GLM CODING PLAN による支援を受けています。
|
||||
|
||||
GLM CODING PLAN は AI コーディング向けのサブスクリプションで、月額わずか 3 ドルから。Claude Code、Cline、Roo Code など 10 以上の人気 AI コーディングツールでフラッグシップモデル GLM-4.6 を利用でき、速く安定した開発体験を提供します。
|
||||
|
||||
[このリンク](https://z.ai/subscribe?ic=8JVLJQFSKB) から申し込むと 10% オフになります!
|
||||
本プロジェクトは Z.ai の GLM CODING PLAN による支援を受けています。GLM CODING PLAN は AI コーディング向けのサブスクリプションで、月額わずか 3 ドルから。Claude Code、Cline、Roo Code など 10 以上の人気 AI コーディングツールでフラッグシップモデル GLM-4.6 を利用でき、速く安定した開発体験を提供します。[このリンク](https://z.ai/subscribe?ic=8JVLJQFSKB) から申し込むと 10% オフになります!
|
||||
|
||||
---
|
||||
|
||||
@@ -41,6 +32,13 @@ GLM CODING PLAN は AI コーディング向けのサブスクリプションで
|
||||
<td>ShanDianShuo のご支援に感謝します!ShanDianShuo はローカルファーストの音声入力ツールで、ミリ秒遅延・データは端末から外に出ず・キーボード入力の 4 倍の速度・AI 自動補正・プライバシー優先で完全無料。Claude Code と組み合わせればコーディング効率が倍増します。<a href="https://www.shandianshuo.cn">Mac/Win 版を無料ダウンロード</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></td>
|
||||
<td>本プロジェクトは AIGoCode のスポンサー提供でお届けしています。AIGoCode は、Claude Code・Codex・最新の Gemini モデルを統合したオールインワンのAIコーディングプラットフォームで、安定性・高速性・コストパフォーマンスに優れた開発サービスを提供します。柔軟なサブスクリプションプランを備え、レスポンスも非常に高速です。さらに、CC Switch ユーザー向けの特典として、<a href="https://aigocode.com/invite/CC-SWITCH">このリンク</a>から登録すると、初回チャージ時に10%分のボーナスクレジットが付与されます!
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
## スクリーンショット
|
||||
|
||||
+6
-10
@@ -3,7 +3,6 @@
|
||||
# Claude Code / Codex / Gemini CLI 全方位辅助工具
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/trending/typescript)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -12,21 +11,13 @@
|
||||
|
||||
[English](README.md) | 中文 | [日本語](README_JA.md) | [更新日志](CHANGELOG.md) | [v3.8.0 发布说明](docs/release-note-v3.8.0-zh.md)
|
||||
|
||||
**从供应商切换器到 AI CLI 一体化管理平台**
|
||||
|
||||
统一管理 Claude Code、Codex 与 Gemini CLI 的供应商配置、MCP 服务器、Skills 扩展和系统提示词。
|
||||
|
||||
</div>
|
||||
|
||||
## ❤️赞助商
|
||||
|
||||

|
||||
|
||||
感谢智谱AI的 GLM CODING PLAN 赞助了本项目!
|
||||
|
||||
GLM CODING PLAN 是专为AI编码打造的订阅套餐,每月最低仅需20元,即可在十余款主流AI编码工具如 Claude Code、Cline 中畅享智谱旗舰模型 GLM-4.6,为开发者提供顶尖、高速、稳定的编码体验。
|
||||
|
||||
CC Switch 已经预设了智谱GLM,只需要填写 key 即可一键导入编程工具。智谱AI为本软件的用户提供了特别优惠,使用[此链接](https://www.bigmodel.cn/claude-code?ic=RRVJPB5SII)购买可以享受九折优惠。
|
||||
感谢智谱AI的 GLM CODING PLAN 赞助了本项目!GLM CODING PLAN 是专为AI编码打造的订阅套餐,每月最低仅需20元,即可在十余款主流AI编码工具如 Claude Code、Cline 中畅享智谱旗舰模型 GLM-4.6,为开发者提供顶尖、高速、稳定的编码体验。CC Switch 已经预设了智谱GLM,只需要填写 key 即可一键导入编程工具。智谱AI为本软件的用户提供了特别优惠,使用[此链接](https://www.bigmodel.cn/claude-code?ic=RRVJPB5SII)购买可以享受九折优惠。
|
||||
|
||||
---
|
||||
|
||||
@@ -41,6 +32,11 @@ CC Switch 已经预设了智谱GLM,只需要填写 key 即可一键导入编
|
||||
<td>感谢闪电说赞助了本项目!闪电说是本地优先的 AI 语音输入法:毫秒级响应,数据不离设备;打字速度提升 4 倍,AI 智能纠错;绝对隐私安全,完全免费,配合 Claude Code 写代码效率翻倍!支持 Mac/Win 双平台,<a href="https://www.shandianshuo.cn">免费下载</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></td>
|
||||
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一个集成了 Claude Code、Codex 以及 Gemini 最新模型的一站式平台,为你提供稳定、高效且高性价比的AI编程服务。本站提供灵活的订阅计划,零封号风险,国内直连,无需魔法,极速响应。AIGoCode 为 CC Switch 的用户提供了特别福利,通过<a href="https://aigocode.com/invite/CC-SWITCH">此链接</a>注册的用户首次充值可以获得额外10%奖励额度!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
## 界面预览
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
@@ -6,13 +6,13 @@ mod env;
|
||||
mod import_export;
|
||||
mod mcp;
|
||||
mod misc;
|
||||
mod model_test;
|
||||
mod plugin;
|
||||
mod prompt;
|
||||
mod provider;
|
||||
mod proxy;
|
||||
mod settings;
|
||||
pub mod skill;
|
||||
mod stream_check;
|
||||
mod usage;
|
||||
|
||||
pub use config::*;
|
||||
@@ -21,11 +21,11 @@ pub use env::*;
|
||||
pub use import_export::*;
|
||||
pub use mcp::*;
|
||||
pub use misc::*;
|
||||
pub use model_test::*;
|
||||
pub use plugin::*;
|
||||
pub use prompt::*;
|
||||
pub use provider::*;
|
||||
pub use proxy::*;
|
||||
pub use settings::*;
|
||||
pub use skill::*;
|
||||
pub use stream_check::*;
|
||||
pub use usage::*;
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
//! 模型测试相关命令
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::services::model_test::{
|
||||
ModelTestConfig, ModelTestLog, ModelTestResult, ModelTestService,
|
||||
};
|
||||
use crate::store::AppState;
|
||||
use tauri::State;
|
||||
|
||||
/// 测试单个供应商的模型可用性
|
||||
#[tauri::command]
|
||||
pub async fn test_provider_model(
|
||||
state: State<'_, AppState>,
|
||||
app_type: AppType,
|
||||
provider_id: String,
|
||||
) -> Result<ModelTestResult, AppError> {
|
||||
// 获取测试配置
|
||||
let config = state.db.get_model_test_config()?;
|
||||
|
||||
// 获取供应商
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
let provider = providers
|
||||
.get(&provider_id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {provider_id} 不存在")))?;
|
||||
|
||||
// 执行测试
|
||||
let result = ModelTestService::test_provider(&app_type, provider, &config).await?;
|
||||
|
||||
// 记录日志
|
||||
let _ = state.db.save_model_test_log(
|
||||
&provider_id,
|
||||
&provider.name,
|
||||
app_type.as_str(),
|
||||
&result.model_used,
|
||||
&config.test_prompt,
|
||||
&result,
|
||||
);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 批量测试所有供应商
|
||||
#[tauri::command]
|
||||
pub async fn test_all_providers_model(
|
||||
state: State<'_, AppState>,
|
||||
app_type: AppType,
|
||||
proxy_targets_only: bool,
|
||||
) -> Result<Vec<(String, ModelTestResult)>, AppError> {
|
||||
let config = state.db.get_model_test_config()?;
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
|
||||
let mut results = Vec::new();
|
||||
|
||||
for (id, provider) in providers {
|
||||
// 如果只测试代理目标,跳过非代理目标
|
||||
if proxy_targets_only && !provider.is_proxy_target.unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match ModelTestService::test_provider(&app_type, &provider, &config).await {
|
||||
Ok(result) => {
|
||||
// 记录日志
|
||||
let _ = state.db.save_model_test_log(
|
||||
&id,
|
||||
&provider.name,
|
||||
app_type.as_str(),
|
||||
&result.model_used,
|
||||
&config.test_prompt,
|
||||
&result,
|
||||
);
|
||||
results.push((id, result));
|
||||
}
|
||||
Err(e) => {
|
||||
let error_result = ModelTestResult {
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: None,
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
};
|
||||
results.push((id, error_result));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// 获取模型测试配置
|
||||
#[tauri::command]
|
||||
pub fn get_model_test_config(state: State<'_, AppState>) -> Result<ModelTestConfig, AppError> {
|
||||
state.db.get_model_test_config()
|
||||
}
|
||||
|
||||
/// 保存模型测试配置
|
||||
#[tauri::command]
|
||||
pub fn save_model_test_config(
|
||||
state: State<'_, AppState>,
|
||||
config: ModelTestConfig,
|
||||
) -> Result<(), AppError> {
|
||||
state.db.save_model_test_config(&config)
|
||||
}
|
||||
|
||||
/// 获取模型测试日志
|
||||
#[tauri::command]
|
||||
pub fn get_model_test_logs(
|
||||
state: State<'_, AppState>,
|
||||
app_type: Option<String>,
|
||||
provider_id: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> Result<Vec<ModelTestLog>, AppError> {
|
||||
state.db.get_model_test_logs(
|
||||
app_type.as_deref(),
|
||||
provider_id.as_deref(),
|
||||
limit.unwrap_or(50),
|
||||
)
|
||||
}
|
||||
|
||||
/// 清理旧的测试日志
|
||||
#[tauri::command]
|
||||
pub fn cleanup_model_test_logs(
|
||||
state: State<'_, AppState>,
|
||||
keep_count: Option<u32>,
|
||||
) -> Result<u64, AppError> {
|
||||
state.db.cleanup_model_test_logs(keep_count.unwrap_or(100))
|
||||
}
|
||||
@@ -7,18 +7,18 @@ use crate::proxy::types::*;
|
||||
use crate::proxy::{CircuitBreakerConfig, CircuitBreakerStats};
|
||||
use crate::store::AppState;
|
||||
|
||||
/// 启动代理服务器
|
||||
/// 启动代理服务器(带 Live 配置接管)
|
||||
#[tauri::command]
|
||||
pub async fn start_proxy_server(
|
||||
pub async fn start_proxy_with_takeover(
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<ProxyServerInfo, String> {
|
||||
state.proxy_service.start().await
|
||||
state.proxy_service.start_with_takeover().await
|
||||
}
|
||||
|
||||
/// 停止代理服务器
|
||||
/// 停止代理服务器(恢复 Live 配置)
|
||||
#[tauri::command]
|
||||
pub async fn stop_proxy_server(state: tauri::State<'_, AppState>) -> Result<(), String> {
|
||||
state.proxy_service.stop().await
|
||||
pub async fn stop_proxy_with_restore(state: tauri::State<'_, AppState>) -> Result<(), String> {
|
||||
state.proxy_service.stop_with_restore().await
|
||||
}
|
||||
|
||||
/// 获取代理服务器状态
|
||||
@@ -48,6 +48,25 @@ pub async fn is_proxy_running(state: tauri::State<'_, AppState>) -> Result<bool,
|
||||
Ok(state.proxy_service.is_running().await)
|
||||
}
|
||||
|
||||
/// 检查是否处于 Live 接管模式
|
||||
#[tauri::command]
|
||||
pub async fn is_live_takeover_active(state: tauri::State<'_, AppState>) -> Result<bool, String> {
|
||||
state.proxy_service.is_takeover_active().await
|
||||
}
|
||||
|
||||
/// 代理模式下切换供应商(热切换)
|
||||
#[tauri::command]
|
||||
pub async fn switch_proxy_provider(
|
||||
state: tauri::State<'_, AppState>,
|
||||
app_type: String,
|
||||
provider_id: String,
|
||||
) -> Result<(), String> {
|
||||
state
|
||||
.proxy_service
|
||||
.switch_proxy_target(&app_type, &provider_id)
|
||||
.await
|
||||
}
|
||||
|
||||
// ==================== 故障转移相关命令 ====================
|
||||
|
||||
/// 获取代理目标列表
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! 流式健康检查命令
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::services::stream_check::{
|
||||
HealthStatus, StreamCheckConfig, StreamCheckResult, StreamCheckService,
|
||||
};
|
||||
use crate::store::AppState;
|
||||
use tauri::State;
|
||||
|
||||
/// 流式健康检查(单个供应商)
|
||||
#[tauri::command]
|
||||
pub async fn stream_check_provider(
|
||||
state: State<'_, AppState>,
|
||||
app_type: AppType,
|
||||
provider_id: String,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
let config = state.db.get_stream_check_config()?;
|
||||
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
let provider = providers
|
||||
.get(&provider_id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {provider_id} 不存在")))?;
|
||||
|
||||
let result = StreamCheckService::check_with_retry(&app_type, provider, &config).await?;
|
||||
|
||||
// 记录日志
|
||||
let _ =
|
||||
state
|
||||
.db
|
||||
.save_stream_check_log(&provider_id, &provider.name, app_type.as_str(), &result);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 批量流式健康检查
|
||||
#[tauri::command]
|
||||
pub async fn stream_check_all_providers(
|
||||
state: State<'_, AppState>,
|
||||
app_type: AppType,
|
||||
proxy_targets_only: bool,
|
||||
) -> Result<Vec<(String, StreamCheckResult)>, AppError> {
|
||||
let config = state.db.get_stream_check_config()?;
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
|
||||
let mut results = Vec::new();
|
||||
|
||||
for (id, provider) in providers {
|
||||
if proxy_targets_only && !provider.is_proxy_target.unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let result = StreamCheckService::check_with_retry(&app_type, &provider, &config)
|
||||
.await
|
||||
.unwrap_or_else(|e| StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: None,
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: 0,
|
||||
});
|
||||
|
||||
let _ = state
|
||||
.db
|
||||
.save_stream_check_log(&id, &provider.name, app_type.as_str(), &result);
|
||||
|
||||
results.push((id, result));
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// 获取流式检查配置
|
||||
#[tauri::command]
|
||||
pub fn get_stream_check_config(state: State<'_, AppState>) -> Result<StreamCheckConfig, AppError> {
|
||||
state.db.get_stream_check_config()
|
||||
}
|
||||
|
||||
/// 保存流式检查配置
|
||||
#[tauri::command]
|
||||
pub fn save_stream_check_config(
|
||||
state: State<'_, AppState>,
|
||||
config: StreamCheckConfig,
|
||||
) -> Result<(), AppError> {
|
||||
state.db.save_stream_check_config(&config)
|
||||
}
|
||||
@@ -8,5 +8,6 @@ pub mod providers;
|
||||
pub mod proxy;
|
||||
pub mod settings;
|
||||
pub mod skills;
|
||||
pub mod stream_check;
|
||||
|
||||
// 所有 DAO 方法都通过 Database impl 提供,无需单独导出
|
||||
|
||||
@@ -483,6 +483,26 @@ impl Database {
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
/// 更新供应商的 settings_config(仅更新配置,不改变其他字段)
|
||||
pub fn update_provider_settings_config(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
settings_config: &serde_json::Value,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"UPDATE providers SET settings_config = ?1 WHERE id = ?2 AND app_type = ?3",
|
||||
params![
|
||||
serde_json::to_string(settings_config).unwrap(),
|
||||
provider_id,
|
||||
app_type
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 添加自定义端点
|
||||
pub fn add_custom_endpoint(
|
||||
&self,
|
||||
|
||||
@@ -17,7 +17,7 @@ impl Database {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.query_row(
|
||||
"SELECT enabled, listen_address, listen_port, max_retries,
|
||||
request_timeout, enable_logging
|
||||
request_timeout, enable_logging, live_takeover_active
|
||||
FROM proxy_config WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
@@ -28,6 +28,7 @@ impl Database {
|
||||
max_retries: row.get::<_, i32>(3)? as u8,
|
||||
request_timeout: row.get::<_, i32>(4)? as u64,
|
||||
enable_logging: row.get::<_, i32>(5)? != 0,
|
||||
live_takeover_active: row.get::<_, i32>(6).unwrap_or(0) != 0,
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -51,8 +52,8 @@ impl Database {
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO proxy_config
|
||||
(id, enabled, listen_address, listen_port, max_retries, request_timeout, enable_logging, target_app, created_at, updated_at)
|
||||
VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7,
|
||||
(id, enabled, listen_address, listen_port, max_retries, request_timeout, enable_logging, live_takeover_active, target_app, created_at, updated_at)
|
||||
VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8,
|
||||
COALESCE((SELECT created_at FROM proxy_config WHERE id = 1), datetime('now')),
|
||||
datetime('now'))",
|
||||
rusqlite::params![
|
||||
@@ -62,6 +63,7 @@ impl Database {
|
||||
config.max_retries as i32,
|
||||
config.request_timeout as i32,
|
||||
if config.enable_logging { 1 } else { 0 },
|
||||
if config.live_takeover_active { 1 } else { 0 },
|
||||
"claude", // 兼容旧字段,写入默认值
|
||||
],
|
||||
)
|
||||
@@ -70,6 +72,30 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 设置 Live 接管状态
|
||||
pub async fn set_live_takeover_active(&self, active: bool) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"UPDATE proxy_config SET live_takeover_active = ?1, updated_at = datetime('now') WHERE id = 1",
|
||||
rusqlite::params![if active { 1 } else { 0 }],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检查是否处于 Live 接管模式
|
||||
pub async fn is_live_takeover_active(&self) -> Result<bool, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let active: i32 = conn
|
||||
.query_row(
|
||||
"SELECT COALESCE(live_takeover_active, 0) FROM proxy_config WHERE id = 1",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap_or(0);
|
||||
Ok(active != 0)
|
||||
}
|
||||
|
||||
// ==================== Provider Health ====================
|
||||
|
||||
/// 获取Provider健康状态
|
||||
@@ -184,83 +210,6 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Proxy Usage (可选) ====================
|
||||
|
||||
/// 记录代理使用统计
|
||||
#[allow(dead_code)]
|
||||
pub async fn record_proxy_usage(&self, record: &ProxyUsageRecord) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO proxy_usage
|
||||
(provider_id, app_type, endpoint, request_tokens, response_tokens,
|
||||
status_code, latency_ms, error, timestamp)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
&record.provider_id,
|
||||
&record.app_type,
|
||||
&record.endpoint,
|
||||
record.request_tokens,
|
||||
record.response_tokens,
|
||||
record.status_code as i64,
|
||||
record.latency_ms as i64,
|
||||
&record.error,
|
||||
&record.timestamp,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 查询最近的使用统计
|
||||
#[allow(dead_code)]
|
||||
pub async fn get_recent_usage(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
limit: usize,
|
||||
) -> Result<Vec<ProxyUsageRecord>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT provider_id, app_type, endpoint, request_tokens, response_tokens,
|
||||
status_code, latency_ms, error, timestamp
|
||||
FROM proxy_usage
|
||||
WHERE provider_id = ?1 AND app_type = ?2
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT ?3",
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let rows = stmt
|
||||
.query_map(
|
||||
rusqlite::params![provider_id, app_type, limit as i64],
|
||||
|row| {
|
||||
Ok(ProxyUsageRecord {
|
||||
provider_id: row.get(0)?,
|
||||
app_type: row.get(1)?,
|
||||
endpoint: row.get(2)?,
|
||||
request_tokens: row.get(3)?,
|
||||
response_tokens: row.get(4)?,
|
||||
status_code: row.get::<_, i64>(5)? as u16,
|
||||
latency_ms: row.get::<_, i64>(6)? as u64,
|
||||
error: row.get(7)?,
|
||||
timestamp: row.get(8)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let mut records = Vec::new();
|
||||
for row in rows {
|
||||
records.push(row.map_err(|e| AppError::Database(e.to_string()))?);
|
||||
}
|
||||
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
// ==================== Circuit Breaker Config ====================
|
||||
|
||||
/// 获取熔断器配置
|
||||
@@ -318,4 +267,74 @@ impl Database {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Live Backup ====================
|
||||
|
||||
/// 保存 Live 配置备份
|
||||
pub async fn save_live_backup(
|
||||
&self,
|
||||
app_type: &str,
|
||||
config_json: &str,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO proxy_live_backup (app_type, original_config, backed_up_at)
|
||||
VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![app_type, config_json, now],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
log::info!("已备份 {app_type} Live 配置");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 获取 Live 配置备份
|
||||
pub async fn get_live_backup(&self, app_type: &str) -> Result<Option<LiveBackup>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
let result = conn.query_row(
|
||||
"SELECT app_type, original_config, backed_up_at FROM proxy_live_backup WHERE app_type = ?1",
|
||||
rusqlite::params![app_type],
|
||||
|row| {
|
||||
Ok(LiveBackup {
|
||||
app_type: row.get(0)?,
|
||||
original_config: row.get(1)?,
|
||||
backed_up_at: row.get(2)?,
|
||||
})
|
||||
},
|
||||
);
|
||||
|
||||
match result {
|
||||
Ok(backup) => Ok(Some(backup)),
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
|
||||
Err(e) => Err(AppError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 删除 Live 配置备份
|
||||
pub async fn delete_live_backup(&self, app_type: &str) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute(
|
||||
"DELETE FROM proxy_live_backup WHERE app_type = ?1",
|
||||
rusqlite::params![app_type],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
log::info!("已删除 {app_type} Live 配置备份");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 删除所有 Live 配置备份
|
||||
pub async fn delete_all_live_backups(&self) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute("DELETE FROM proxy_live_backup", [])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
log::info!("已删除所有 Live 配置备份");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! 流式健康检查日志 DAO
|
||||
|
||||
use crate::database::{lock_conn, Database};
|
||||
use crate::error::AppError;
|
||||
use crate::services::stream_check::{StreamCheckConfig, StreamCheckResult};
|
||||
|
||||
impl Database {
|
||||
/// 保存流式检查日志
|
||||
pub fn save_stream_check_log(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
provider_name: &str,
|
||||
app_type: &str,
|
||||
result: &StreamCheckResult,
|
||||
) -> Result<i64, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO stream_check_logs
|
||||
(provider_id, provider_name, app_type, status, success, message,
|
||||
response_time_ms, http_status, model_used, retry_count, tested_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
|
||||
rusqlite::params![
|
||||
provider_id,
|
||||
provider_name,
|
||||
app_type,
|
||||
format!("{:?}", result.status).to_lowercase(),
|
||||
result.success,
|
||||
result.message,
|
||||
result.response_time_ms.map(|t| t as i64),
|
||||
result.http_status.map(|s| s as i64),
|
||||
result.model_used,
|
||||
result.retry_count as i64,
|
||||
result.tested_at,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// 获取流式检查配置
|
||||
pub fn get_stream_check_config(&self) -> Result<StreamCheckConfig, AppError> {
|
||||
match self.get_setting("stream_check_config")? {
|
||||
Some(json) => serde_json::from_str(&json)
|
||||
.map_err(|e| AppError::Message(format!("解析配置失败: {e}"))),
|
||||
None => Ok(StreamCheckConfig::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存流式检查配置
|
||||
pub fn save_stream_check_config(&self, config: &StreamCheckConfig) -> Result<(), AppError> {
|
||||
let json = serde_json::to_string(config)
|
||||
.map_err(|e| AppError::Message(format!("序列化配置失败: {e}")))?;
|
||||
self.set_setting("stream_check_config", &json)
|
||||
}
|
||||
}
|
||||
@@ -173,40 +173,7 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 10. Proxy Usage 表 (代理使用统计,可选)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_usage (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
endpoint TEXT NOT NULL,
|
||||
request_tokens INTEGER,
|
||||
response_tokens INTEGER,
|
||||
status_code INTEGER NOT NULL,
|
||||
latency_ms INTEGER NOT NULL,
|
||||
error TEXT,
|
||||
timestamp TEXT NOT NULL
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 为 proxy_usage 创建索引
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_proxy_usage_timestamp
|
||||
ON proxy_usage(timestamp)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_proxy_usage_provider
|
||||
ON proxy_usage(provider_id, app_type)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 11. Proxy Request Logs 表 (详细请求日志)
|
||||
// 10. Proxy Request Logs 表 (详细请求日志)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_request_logs (
|
||||
request_id TEXT PRIMARY KEY,
|
||||
@@ -272,7 +239,7 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 12. Model Pricing 表 (模型定价)
|
||||
// 11. Model Pricing 表 (模型定价)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS model_pricing (
|
||||
model_id TEXT PRIMARY KEY,
|
||||
@@ -286,38 +253,20 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 13. Usage Daily Stats 表 (每日聚合统计)
|
||||
// 12. Stream Check Logs 表 (流式健康检查日志)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS usage_daily_stats (
|
||||
date TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
request_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_input_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
success_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_count INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (date, provider_id, app_type, model)
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 14. Model Test Logs 表 (模型测试日志,独立于代理使用统计)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS model_test_logs (
|
||||
"CREATE TABLE IF NOT EXISTS stream_check_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
provider_id TEXT NOT NULL,
|
||||
provider_name TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
success INTEGER NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
response_time_ms INTEGER,
|
||||
http_status INTEGER,
|
||||
model_used TEXT,
|
||||
retry_count INTEGER DEFAULT 0,
|
||||
tested_at INTEGER NOT NULL
|
||||
)",
|
||||
[],
|
||||
@@ -325,20 +274,13 @@ impl Database {
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_test_logs_provider
|
||||
ON model_test_logs(provider_id, app_type)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_stream_check_logs_provider
|
||||
ON stream_check_logs(app_type, provider_id, tested_at DESC)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_test_logs_tested_at
|
||||
ON model_test_logs(tested_at DESC)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 15. Circuit Breaker Config 表 (熔断器配置)
|
||||
// 13. Circuit Breaker Config 表 (熔断器配置)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS circuit_breaker_config (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
@@ -360,6 +302,23 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 16. Proxy Live Backup 表 (Live 配置备份)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS proxy_live_backup (
|
||||
app_type TEXT PRIMARY KEY,
|
||||
original_config TEXT NOT NULL,
|
||||
backed_up_at TEXT NOT NULL
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 尝试添加 live_takeover_active 列到 proxy_config 表
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN live_takeover_active INTEGER NOT NULL DEFAULT 0",
|
||||
[],
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -557,24 +516,6 @@ impl Database {
|
||||
[],
|
||||
)?;
|
||||
|
||||
// usage_daily_stats 表
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS usage_daily_stats (
|
||||
date TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
request_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_input_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
success_count INTEGER NOT NULL DEFAULT 0,
|
||||
error_count INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (date, provider_id, app_type, model)
|
||||
)",
|
||||
[],
|
||||
)?;
|
||||
|
||||
// 清空并重新插入模型定价
|
||||
conn.execute("DELETE FROM model_pricing", [])
|
||||
.map_err(|e| AppError::Database(format!("清空模型定价失败: {e}")))?;
|
||||
|
||||
+64
-10
@@ -530,7 +530,7 @@ pub fn run() {
|
||||
Ok(config) => {
|
||||
if config.enabled {
|
||||
log::info!("代理服务配置为启用,正在启动...");
|
||||
match state.proxy_service.start().await {
|
||||
match state.proxy_service.start_with_takeover().await {
|
||||
Ok(info) => log::info!(
|
||||
"代理服务器自动启动成功: {}:{}",
|
||||
info.address,
|
||||
@@ -647,12 +647,14 @@ pub fn run() {
|
||||
commands::set_auto_launch,
|
||||
commands::get_auto_launch_status,
|
||||
// Proxy server management
|
||||
commands::start_proxy_server,
|
||||
commands::stop_proxy_server,
|
||||
commands::start_proxy_with_takeover,
|
||||
commands::stop_proxy_with_restore,
|
||||
commands::get_proxy_status,
|
||||
commands::get_proxy_config,
|
||||
commands::update_proxy_config,
|
||||
commands::is_proxy_running,
|
||||
commands::is_live_takeover_active,
|
||||
commands::switch_proxy_provider,
|
||||
// Proxy failover commands
|
||||
commands::get_proxy_targets,
|
||||
commands::set_proxy_target,
|
||||
@@ -672,13 +674,11 @@ pub fn run() {
|
||||
commands::update_model_pricing,
|
||||
commands::delete_model_pricing,
|
||||
commands::check_provider_limits,
|
||||
// Model testing
|
||||
commands::test_provider_model,
|
||||
commands::test_all_providers_model,
|
||||
commands::get_model_test_config,
|
||||
commands::save_model_test_config,
|
||||
commands::get_model_test_logs,
|
||||
commands::cleanup_model_test_logs,
|
||||
// Stream health check
|
||||
commands::stream_check_provider,
|
||||
commands::stream_check_all_providers,
|
||||
commands::get_stream_check_config,
|
||||
commands::save_stream_check_config,
|
||||
commands::get_tool_versions,
|
||||
]);
|
||||
|
||||
@@ -687,6 +687,22 @@ pub fn run() {
|
||||
.expect("error while running tauri application");
|
||||
|
||||
app.run(|app_handle, event| {
|
||||
// 处理退出请求(所有平台)
|
||||
if let RunEvent::ExitRequested { api, .. } = &event {
|
||||
log::info!("收到退出请求,开始清理...");
|
||||
// 阻止立即退出,执行清理
|
||||
api.prevent_exit();
|
||||
|
||||
let app_handle = app_handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
cleanup_before_exit(&app_handle).await;
|
||||
log::info!("清理完成,退出应用");
|
||||
// 使用 std::process::exit 避免再次触发 ExitRequested
|
||||
std::process::exit(0);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
match event {
|
||||
@@ -766,6 +782,44 @@ pub fn run() {
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 应用退出清理
|
||||
// ============================================================
|
||||
|
||||
/// 应用退出前的清理工作
|
||||
///
|
||||
/// 在应用退出前检查代理服务器状态,如果正在运行则停止代理并恢复 Live 配置。
|
||||
/// 确保 Claude Code/Codex/Gemini 的配置不会处于损坏状态。
|
||||
pub async fn cleanup_before_exit(app_handle: &tauri::AppHandle) {
|
||||
if let Some(state) = app_handle.try_state::<store::AppState>() {
|
||||
let proxy_service = &state.proxy_service;
|
||||
|
||||
// 检查代理是否在运行
|
||||
if proxy_service.is_running().await {
|
||||
log::info!("检测到代理服务器正在运行,开始清理...");
|
||||
|
||||
// 检查是否处于 Live 接管模式
|
||||
if let Ok(is_takeover) = state.db.is_live_takeover_active().await {
|
||||
if is_takeover {
|
||||
// 接管模式:停止并恢复配置
|
||||
if let Err(e) = proxy_service.stop_with_restore().await {
|
||||
log::error!("退出时恢复 Live 配置失败: {e}");
|
||||
} else {
|
||||
log::info!("已恢复 Live 配置");
|
||||
}
|
||||
} else {
|
||||
// 非接管模式:仅停止代理
|
||||
if let Err(e) = proxy_service.stop().await {
|
||||
log::error!("退出时停止代理失败: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("代理服务器清理完成");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 迁移错误对话框辅助函数
|
||||
// ============================================================
|
||||
|
||||
@@ -30,58 +30,42 @@ impl ProviderRouter {
|
||||
/// 选择可用的供应商(支持故障转移)
|
||||
/// 返回按优先级排序的可用供应商列表
|
||||
pub async fn select_providers(&self, app_type: &str) -> Result<Vec<Provider>, AppError> {
|
||||
// 1. 获取所有启用代理的供应商
|
||||
let providers = self.db.get_proxy_targets(app_type).await?;
|
||||
// 直接获取当前选中的供应商(基于 is_current 字段)
|
||||
let current_id = self
|
||||
.db
|
||||
.get_current_provider(app_type)?
|
||||
.ok_or_else(|| AppError::Config(format!("No current provider for {}", app_type)))?;
|
||||
|
||||
if providers.is_empty() {
|
||||
return Err(AppError::Config(
|
||||
"No proxy target providers configured".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
log::debug!(
|
||||
"Found {} proxy target providers for app_type: {}",
|
||||
providers.len(),
|
||||
app_type
|
||||
);
|
||||
|
||||
// 2. 按 sort_index 排序(已经在数据库查询中排序了)
|
||||
let sorted_providers: Vec<_> = providers.into_values().collect();
|
||||
|
||||
// 3. 过滤可用的供应商(检查熔断器状态)
|
||||
let mut available_providers = Vec::new();
|
||||
|
||||
for provider in sorted_providers {
|
||||
let circuit_key = format!("{}:{}", app_type, provider.id);
|
||||
let breaker = self.get_or_create_circuit_breaker(&circuit_key).await;
|
||||
|
||||
if breaker.allow_request().await {
|
||||
log::debug!(
|
||||
"Provider {} is available (circuit state: {:?})",
|
||||
provider.id,
|
||||
breaker.get_state().await
|
||||
);
|
||||
available_providers.push(provider);
|
||||
} else {
|
||||
log::warn!(
|
||||
"Provider {} is unavailable (circuit breaker open)",
|
||||
provider.id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if available_providers.is_empty() {
|
||||
return Err(AppError::Config(
|
||||
"All proxy target providers are unavailable (circuit breakers open)".to_string(),
|
||||
));
|
||||
}
|
||||
let providers = self.db.get_all_providers(app_type)?;
|
||||
let provider = providers
|
||||
.get(¤t_id)
|
||||
.ok_or_else(|| AppError::Config(format!("Current provider {} not found", current_id)))?
|
||||
.clone();
|
||||
|
||||
log::info!(
|
||||
"Selected {} available providers for failover chain",
|
||||
available_providers.len()
|
||||
"[{}] Selected current provider: {} ({})",
|
||||
app_type,
|
||||
provider.name,
|
||||
provider.id
|
||||
);
|
||||
|
||||
Ok(available_providers)
|
||||
// 检查熔断器状态
|
||||
let circuit_key = format!("{}:{}", app_type, provider.id);
|
||||
let breaker = self.get_or_create_circuit_breaker(&circuit_key).await;
|
||||
|
||||
if !breaker.allow_request().await {
|
||||
log::warn!(
|
||||
"Provider {} is unavailable (circuit breaker open)",
|
||||
provider.id
|
||||
);
|
||||
return Err(AppError::Config(format!(
|
||||
"Current provider {} is unavailable (circuit breaker open)",
|
||||
provider.name
|
||||
)));
|
||||
}
|
||||
|
||||
// 返回单个供应商(保留 Vec 接口以兼容现有代码)
|
||||
Ok(vec![provider])
|
||||
}
|
||||
|
||||
/// 记录供应商请求结果
|
||||
|
||||
@@ -148,17 +148,24 @@ impl ProxyServer {
|
||||
// 健康检查
|
||||
.route("/health", get(handlers::health_check))
|
||||
.route("/status", get(handlers::get_status))
|
||||
// Claude API
|
||||
// Claude API (支持带前缀和不带前缀两种格式)
|
||||
.route("/v1/messages", post(handlers::handle_messages))
|
||||
// OpenAI Chat Completions API (Codex CLI)
|
||||
.route("/claude/v1/messages", post(handlers::handle_messages))
|
||||
// OpenAI Chat Completions API (Codex CLI,支持带前缀和不带前缀)
|
||||
.route(
|
||||
"/v1/chat/completions",
|
||||
post(handlers::handle_chat_completions),
|
||||
)
|
||||
// OpenAI Responses API (Codex CLI)
|
||||
.route(
|
||||
"/codex/v1/chat/completions",
|
||||
post(handlers::handle_chat_completions),
|
||||
)
|
||||
// OpenAI Responses API (Codex CLI,支持带前缀和不带前缀)
|
||||
.route("/v1/responses", post(handlers::handle_responses))
|
||||
// Gemini API
|
||||
.route("/codex/v1/responses", post(handlers::handle_responses))
|
||||
// Gemini API (支持带前缀和不带前缀)
|
||||
.route("/v1beta/*path", post(handlers::handle_gemini))
|
||||
.route("/gemini/v1beta/*path", post(handlers::handle_gemini))
|
||||
.layer(cors)
|
||||
.with_state(self.state.clone())
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ pub struct ProxyConfig {
|
||||
pub request_timeout: u64,
|
||||
/// 是否启用日志
|
||||
pub enable_logging: bool,
|
||||
/// 是否正在接管 Live 配置
|
||||
#[serde(default)]
|
||||
pub live_takeover_active: bool,
|
||||
}
|
||||
|
||||
impl Default for ProxyConfig {
|
||||
@@ -26,6 +29,7 @@ impl Default for ProxyConfig {
|
||||
max_retries: 3,
|
||||
request_timeout: 300,
|
||||
enable_logging: true,
|
||||
live_takeover_active: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,16 +108,13 @@ pub struct ProviderHealth {
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
/// 使用统计记录
|
||||
/// Live 配置备份记录
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ProxyUsageRecord {
|
||||
pub provider_id: String,
|
||||
pub struct LiveBackup {
|
||||
/// 应用类型 (claude/codex/gemini)
|
||||
pub app_type: String,
|
||||
pub endpoint: String,
|
||||
pub request_tokens: Option<i32>,
|
||||
pub response_tokens: Option<i32>,
|
||||
pub status_code: u16,
|
||||
pub latency_ms: u64,
|
||||
pub error: Option<String>,
|
||||
pub timestamp: String,
|
||||
/// 原始配置 JSON
|
||||
pub original_config: String,
|
||||
/// 备份时间
|
||||
pub backed_up_at: String,
|
||||
}
|
||||
|
||||
@@ -2,18 +2,16 @@ pub mod config;
|
||||
pub mod env_checker;
|
||||
pub mod env_manager;
|
||||
pub mod mcp;
|
||||
pub mod model_test;
|
||||
pub mod prompt;
|
||||
pub mod provider;
|
||||
pub mod proxy;
|
||||
pub mod skill;
|
||||
pub mod speedtest;
|
||||
pub mod stream_check;
|
||||
pub mod usage_stats;
|
||||
|
||||
pub use config::ConfigService;
|
||||
pub use mcp::McpService;
|
||||
#[allow(unused_imports)]
|
||||
pub use model_test::{ModelTestConfig, ModelTestLog, ModelTestResult, ModelTestService};
|
||||
pub use prompt::PromptService;
|
||||
pub use provider::{ProviderService, ProviderSortUpdate};
|
||||
pub use proxy::ProxyService;
|
||||
|
||||
@@ -1,510 +0,0 @@
|
||||
//! 模型测试服务
|
||||
//!
|
||||
//! 提供独立的模型可用性测试功能,复用现有 Provider 适配器逻辑,
|
||||
//! 但不影响正常代理数据流程。测试结果记录到独立的日志表。
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::database::Database;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::providers::{get_adapter, AuthInfo, ProviderAdapter};
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// 模型测试配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelTestConfig {
|
||||
/// 默认测试模型(Claude)
|
||||
pub claude_model: String,
|
||||
/// 默认测试模型(Codex/OpenAI)
|
||||
pub codex_model: String,
|
||||
/// 默认测试模型(Gemini)
|
||||
pub gemini_model: String,
|
||||
/// 测试提示词
|
||||
pub test_prompt: String,
|
||||
/// 超时时间(秒)
|
||||
pub timeout_secs: u64,
|
||||
}
|
||||
|
||||
impl Default for ModelTestConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
claude_model: "claude-haiku-4-5-20251001".to_string(),
|
||||
codex_model: "gpt-5.1-low".to_string(),
|
||||
gemini_model: "gemini-3-pro-low".to_string(),
|
||||
test_prompt: "ping".to_string(),
|
||||
timeout_secs: 15,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 模型测试结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelTestResult {
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub response_time_ms: Option<u64>,
|
||||
pub http_status: Option<u16>,
|
||||
pub model_used: String,
|
||||
pub tested_at: i64,
|
||||
}
|
||||
|
||||
/// 模型测试日志记录
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelTestLog {
|
||||
pub id: i64,
|
||||
pub provider_id: String,
|
||||
pub provider_name: String,
|
||||
pub app_type: String,
|
||||
pub model: String,
|
||||
pub prompt: String,
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub response_time_ms: Option<i64>,
|
||||
pub http_status: Option<i64>,
|
||||
pub tested_at: i64,
|
||||
}
|
||||
|
||||
/// 模型测试服务
|
||||
pub struct ModelTestService;
|
||||
|
||||
impl ModelTestService {
|
||||
/// 测试单个供应商的模型可用性
|
||||
pub async fn test_provider(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &ModelTestConfig,
|
||||
) -> Result<ModelTestResult, AppError> {
|
||||
let start = Instant::now();
|
||||
let adapter = get_adapter(app_type);
|
||||
|
||||
// 构建 HTTP 客户端(独立于代理服务)
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(config.timeout_secs))
|
||||
.build()
|
||||
.map_err(|e| AppError::Message(format!("创建 HTTP 客户端失败: {e}")))?;
|
||||
|
||||
// 根据 AppType 选择测试模型
|
||||
let model = match app_type {
|
||||
AppType::Claude => &config.claude_model,
|
||||
AppType::Codex => &config.codex_model,
|
||||
AppType::Gemini => &config.gemini_model,
|
||||
};
|
||||
|
||||
let result = match app_type {
|
||||
AppType::Claude => {
|
||||
Self::test_claude(
|
||||
&client,
|
||||
provider,
|
||||
adapter.as_ref(),
|
||||
model,
|
||||
&config.test_prompt,
|
||||
)
|
||||
.await
|
||||
}
|
||||
AppType::Codex => {
|
||||
Self::test_codex(
|
||||
&client,
|
||||
provider,
|
||||
adapter.as_ref(),
|
||||
model,
|
||||
&config.test_prompt,
|
||||
)
|
||||
.await
|
||||
}
|
||||
AppType::Gemini => {
|
||||
Self::test_gemini(
|
||||
&client,
|
||||
provider,
|
||||
adapter.as_ref(),
|
||||
model,
|
||||
&config.test_prompt,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
|
||||
let response_time = start.elapsed().as_millis() as u64;
|
||||
let tested_at = chrono::Utc::now().timestamp();
|
||||
|
||||
match result {
|
||||
Ok((status, msg)) => Ok(ModelTestResult {
|
||||
success: true,
|
||||
message: msg,
|
||||
response_time_ms: Some(response_time),
|
||||
http_status: Some(status),
|
||||
model_used: model.clone(),
|
||||
tested_at,
|
||||
}),
|
||||
Err(e) => Ok(ModelTestResult {
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: Some(response_time),
|
||||
http_status: None,
|
||||
model_used: model.clone(),
|
||||
tested_at,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// 测试 Claude (Anthropic Messages API)
|
||||
async fn test_claude(
|
||||
client: &Client,
|
||||
provider: &Provider,
|
||||
adapter: &dyn ProviderAdapter,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base_url = adapter
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("提取 base_url 失败: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("未找到 API Key".to_string()))?;
|
||||
|
||||
// 智能拼接 URL,避免重复 /v1
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = if base.ends_with("/v1") {
|
||||
format!("{base}/messages")
|
||||
} else {
|
||||
format!("{base}/v1/messages")
|
||||
};
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"max_tokens": 1,
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
}]
|
||||
});
|
||||
|
||||
let mut request = client.post(&url).json(&body);
|
||||
request = Self::add_claude_auth(request, &auth);
|
||||
|
||||
let response = request.send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
AppError::Message("请求超时".to_string())
|
||||
} else if e.is_connect() {
|
||||
AppError::Message(format!("连接失败: {e}"))
|
||||
} else {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
})?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if response.status().is_success() {
|
||||
// 先获取文本,再尝试解析 JSON(兼容流式响应)
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
|
||||
// 尝试解析 JSON
|
||||
if let Ok(data) = serde_json::from_str::<Value>(&text) {
|
||||
if data.get("type").is_some()
|
||||
|| data.get("content").is_some()
|
||||
|| data.get("id").is_some()
|
||||
{
|
||||
return Ok((status, "模型测试成功".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// 即使无法解析 JSON,只要状态码是 200 就认为成功
|
||||
Ok((status, "模型测试成功".to_string()))
|
||||
} else {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
Err(AppError::Message(format!("HTTP {status}: {error_text}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// 测试 Codex (OpenAI Chat Completions API)
|
||||
async fn test_codex(
|
||||
client: &Client,
|
||||
provider: &Provider,
|
||||
adapter: &dyn ProviderAdapter,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base_url = adapter
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("提取 base_url 失败: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("未找到 API Key".to_string()))?;
|
||||
|
||||
// 智能拼接 URL,避免重复 /v1
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = if base.ends_with("/v1") {
|
||||
format!("{base}/chat/completions")
|
||||
} else {
|
||||
format!("{base}/v1/chat/completions")
|
||||
};
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
}],
|
||||
"max_tokens": 1,
|
||||
"stream": false
|
||||
});
|
||||
|
||||
let request = client
|
||||
.post(&url)
|
||||
.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body);
|
||||
|
||||
let response = request.send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
AppError::Message("请求超时".to_string())
|
||||
} else if e.is_connect() {
|
||||
AppError::Message(format!("连接失败: {e}"))
|
||||
} else {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
})?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if response.status().is_success() {
|
||||
// 先获取文本,再尝试解析 JSON
|
||||
let text = response.text().await.unwrap_or_default();
|
||||
|
||||
if let Ok(data) = serde_json::from_str::<Value>(&text) {
|
||||
if data.get("choices").is_some() || data.get("id").is_some() {
|
||||
return Ok((status, "模型测试成功".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// 即使无法解析 JSON,只要状态码是 200 就认为成功
|
||||
Ok((status, "模型测试成功".to_string()))
|
||||
} else {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
Err(AppError::Message(format!("HTTP {status}: {error_text}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// 测试 Gemini (Google Generative AI API)
|
||||
async fn test_gemini(
|
||||
client: &Client,
|
||||
provider: &Provider,
|
||||
adapter: &dyn ProviderAdapter,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base_url = adapter
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("提取 base_url 失败: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("未找到 API Key".to_string()))?;
|
||||
|
||||
let url = format!(
|
||||
"{}/v1beta/models/{}:generateContent?key={}",
|
||||
base_url.trim_end_matches('/'),
|
||||
model,
|
||||
auth.api_key
|
||||
);
|
||||
|
||||
let body = json!({
|
||||
"contents": [{
|
||||
"parts": [{
|
||||
"text": prompt
|
||||
}]
|
||||
}],
|
||||
"generationConfig": {
|
||||
"maxOutputTokens": 1
|
||||
}
|
||||
});
|
||||
|
||||
let request = client
|
||||
.post(&url)
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body);
|
||||
|
||||
let response = request.send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
AppError::Message("请求超时".to_string())
|
||||
} else if e.is_connect() {
|
||||
AppError::Message(format!("连接失败: {e}"))
|
||||
} else {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
})?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if response.status().is_success() {
|
||||
let data: Value = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| AppError::Message(format!("解析响应失败: {e}")))?;
|
||||
|
||||
if data.get("candidates").is_some() {
|
||||
Ok((status, "模型测试成功".to_string()))
|
||||
} else {
|
||||
Err(AppError::Message("响应格式异常".to_string()))
|
||||
}
|
||||
} else {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
Err(AppError::Message(format!("HTTP {status}: {error_text}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// 添加 Claude 认证头
|
||||
fn add_claude_auth(
|
||||
request: reqwest::RequestBuilder,
|
||||
auth: &AuthInfo,
|
||||
) -> reqwest::RequestBuilder {
|
||||
request
|
||||
.header("x-api-key", &auth.api_key)
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.header("Content-Type", "application/json")
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 数据库操作 =====
|
||||
|
||||
impl Database {
|
||||
/// 保存模型测试日志
|
||||
pub fn save_model_test_log(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
provider_name: &str,
|
||||
app_type: &str,
|
||||
model: &str,
|
||||
prompt: &str,
|
||||
result: &ModelTestResult,
|
||||
) -> Result<i64, AppError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|e| AppError::Database(format!("获取数据库连接失败: {e}")))?;
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO model_test_logs
|
||||
(provider_id, provider_name, app_type, model, prompt, success, message, response_time_ms, http_status, tested_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
rusqlite::params![
|
||||
provider_id,
|
||||
provider_name,
|
||||
app_type,
|
||||
model,
|
||||
prompt,
|
||||
result.success,
|
||||
result.message,
|
||||
result.response_time_ms.map(|t| t as i64),
|
||||
result.http_status.map(|s| s as i64),
|
||||
result.tested_at,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// 获取模型测试日志
|
||||
pub fn get_model_test_logs(
|
||||
&self,
|
||||
app_type: Option<&str>,
|
||||
provider_id: Option<&str>,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ModelTestLog>, AppError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|e| AppError::Database(format!("获取数据库连接失败: {e}")))?;
|
||||
|
||||
let mut sql = String::from(
|
||||
"SELECT id, provider_id, provider_name, app_type, model, prompt, success, message, response_time_ms, http_status, tested_at
|
||||
FROM model_test_logs WHERE 1=1"
|
||||
);
|
||||
|
||||
let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
|
||||
|
||||
if let Some(at) = app_type {
|
||||
sql.push_str(" AND app_type = ?");
|
||||
params.push(Box::new(at.to_string()));
|
||||
}
|
||||
|
||||
if let Some(pid) = provider_id {
|
||||
sql.push_str(" AND provider_id = ?");
|
||||
params.push(Box::new(pid.to_string()));
|
||||
}
|
||||
|
||||
sql.push_str(" ORDER BY tested_at DESC LIMIT ?");
|
||||
params.push(Box::new(limit as i64));
|
||||
|
||||
let params_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(&sql)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let logs = stmt
|
||||
.query_map(params_refs.as_slice(), |row| {
|
||||
Ok(ModelTestLog {
|
||||
id: row.get(0)?,
|
||||
provider_id: row.get(1)?,
|
||||
provider_name: row.get(2)?,
|
||||
app_type: row.get(3)?,
|
||||
model: row.get(4)?,
|
||||
prompt: row.get(5)?,
|
||||
success: row.get(6)?,
|
||||
message: row.get(7)?,
|
||||
response_time_ms: row.get(8)?,
|
||||
http_status: row.get(9)?,
|
||||
tested_at: row.get(10)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(logs)
|
||||
}
|
||||
|
||||
/// 获取模型测试配置
|
||||
pub fn get_model_test_config(&self) -> Result<ModelTestConfig, AppError> {
|
||||
match self.get_setting("model_test_config")? {
|
||||
Some(json) => serde_json::from_str(&json)
|
||||
.map_err(|e| AppError::Message(format!("解析模型测试配置失败: {e}"))),
|
||||
None => Ok(ModelTestConfig::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存模型测试配置
|
||||
pub fn save_model_test_config(&self, config: &ModelTestConfig) -> Result<(), AppError> {
|
||||
let json = serde_json::to_string(config)
|
||||
.map_err(|e| AppError::Message(format!("序列化模型测试配置失败: {e}")))?;
|
||||
self.set_setting("model_test_config", &json)
|
||||
}
|
||||
|
||||
/// 清理旧的测试日志(保留最近 N 条)
|
||||
pub fn cleanup_model_test_logs(&self, keep_count: u32) -> Result<u64, AppError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|e| AppError::Database(format!("获取数据库连接失败: {e}")))?;
|
||||
|
||||
let deleted = conn
|
||||
.execute(
|
||||
"DELETE FROM model_test_logs WHERE id NOT IN (
|
||||
SELECT id FROM model_test_logs ORDER BY tested_at DESC LIMIT ?
|
||||
)",
|
||||
rusqlite::params![keep_count as i64],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
Ok(deleted as u64)
|
||||
}
|
||||
}
|
||||
@@ -173,14 +173,71 @@ impl ProviderService {
|
||||
///
|
||||
/// Switch flow:
|
||||
/// 1. Validate target provider exists
|
||||
/// 2. **Backfill mechanism**: Backfill current live config to current provider, protect user manual modifications
|
||||
/// 3. Update local settings current_provider_xxx (device-level)
|
||||
/// 4. Update database is_current (as default for new devices)
|
||||
/// 5. Write target provider config to live files
|
||||
/// 6. Sync MCP configuration
|
||||
/// 2. Check if proxy takeover mode is active AND proxy server is running
|
||||
/// 3. If takeover mode active: hot-switch proxy target only (no Live config write)
|
||||
/// 4. If normal mode:
|
||||
/// a. **Backfill mechanism**: Backfill current live config to current provider
|
||||
/// b. Update local settings current_provider_xxx (device-level)
|
||||
/// c. Update database is_current (as default for new devices)
|
||||
/// d. Write target provider config to live files
|
||||
/// e. Sync MCP configuration
|
||||
pub fn switch(state: &AppState, app_type: AppType, id: &str) -> Result<(), AppError> {
|
||||
// Check if provider exists
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
let _provider = providers
|
||||
.get(id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {id} 不存在")))?;
|
||||
|
||||
// Check if proxy takeover mode is active AND proxy server is actually running
|
||||
// Both conditions must be true to use hot-switch mode
|
||||
// Use blocking wait since this is a sync function
|
||||
let is_takeover_flag =
|
||||
futures::executor::block_on(state.db.is_live_takeover_active()).unwrap_or(false);
|
||||
let is_proxy_running = futures::executor::block_on(state.proxy_service.is_running());
|
||||
|
||||
// Hot-switch only when BOTH: takeover flag is set AND proxy server is actually running
|
||||
let should_hot_switch = is_takeover_flag && is_proxy_running;
|
||||
|
||||
if should_hot_switch {
|
||||
// Proxy takeover mode: hot-switch only, don't write Live config
|
||||
log::info!(
|
||||
"代理接管模式:热切换 {} 的目标供应商为 {}",
|
||||
app_type.as_str(),
|
||||
id
|
||||
);
|
||||
|
||||
// Update database is_current
|
||||
state.db.set_current_provider(app_type.as_str(), id)?;
|
||||
|
||||
// 同时更新 is_proxy_target(代理路由器使用此字段选择供应商)
|
||||
state.db.set_proxy_target_provider(app_type.as_str(), id)?;
|
||||
|
||||
// Update local settings for consistency
|
||||
crate::settings::set_current_provider(&app_type, Some(id))?;
|
||||
|
||||
// Note: No Live config write, no MCP sync
|
||||
// The proxy server will route requests to the new provider via is_proxy_target
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Normal mode: full switch with Live config write
|
||||
// Also clear stale takeover flag if proxy is not running but flag was set
|
||||
if is_takeover_flag && !is_proxy_running {
|
||||
log::warn!("检测到代理接管标志残留(代理已停止),清除标志并执行正常切换");
|
||||
// Clear stale takeover flag
|
||||
let _ = futures::executor::block_on(state.db.set_live_takeover_active(false));
|
||||
}
|
||||
|
||||
Self::switch_normal(state, app_type, id, &providers)
|
||||
}
|
||||
|
||||
/// Normal switch flow (non-proxy mode)
|
||||
fn switch_normal(
|
||||
state: &AppState,
|
||||
app_type: AppType,
|
||||
id: &str,
|
||||
providers: &indexmap::IndexMap<String, Provider>,
|
||||
) -> Result<(), AppError> {
|
||||
let provider = providers
|
||||
.get(id)
|
||||
.ok_or_else(|| AppError::Message(format!("供应商 {id} 不存在")))?;
|
||||
|
||||
@@ -2,9 +2,13 @@
|
||||
//!
|
||||
//! 提供代理服务器的启动、停止和配置管理
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::config::{get_claude_settings_path, read_json_file, write_json_file};
|
||||
use crate::database::Database;
|
||||
use crate::proxy::server::ProxyServer;
|
||||
use crate::proxy::types::*;
|
||||
use serde_json::{json, Value};
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
@@ -59,6 +63,196 @@ impl ProxyService {
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// 启动代理服务器(带 Live 配置接管)
|
||||
pub async fn start_with_takeover(&self) -> Result<ProxyServerInfo, String> {
|
||||
// 1. 自动将各应用当前选中的供应商设置为代理目标
|
||||
self.setup_proxy_targets().await?;
|
||||
|
||||
// 2. 备份各应用的 Live 配置
|
||||
self.backup_live_configs().await?;
|
||||
|
||||
// 3. 同步 Live 配置中的 Token 到数据库(确保代理能读到最新的 Token)
|
||||
self.sync_live_to_providers().await?;
|
||||
|
||||
// 4. 接管各应用的 Live 配置(写入代理地址,清空 Token)
|
||||
self.takeover_live_configs().await?;
|
||||
|
||||
// 5. 设置接管状态
|
||||
self.db
|
||||
.set_live_takeover_active(true)
|
||||
.await
|
||||
.map_err(|e| format!("设置接管状态失败: {e}"))?;
|
||||
|
||||
// 6. 启动代理服务器
|
||||
match self.start().await {
|
||||
Ok(info) => Ok(info),
|
||||
Err(e) => {
|
||||
// 启动失败,恢复原始配置
|
||||
log::error!("代理启动失败,尝试恢复原始配置: {e}");
|
||||
let _ = self.restore_live_configs().await;
|
||||
let _ = self.db.set_live_takeover_active(false).await;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 自动设置代理目标:将各应用当前选中的供应商设置为代理目标
|
||||
async fn setup_proxy_targets(&self) -> Result<(), String> {
|
||||
let app_types = ["claude", "codex", "gemini"];
|
||||
|
||||
for app_type in app_types {
|
||||
// 获取当前选中的供应商
|
||||
if let Ok(Some(provider_id)) = self.db.get_current_provider(app_type) {
|
||||
// 设置为代理目标
|
||||
if let Err(e) = self.db.set_proxy_target(&provider_id, app_type, true).await {
|
||||
log::warn!("设置 {} 的代理目标 {} 失败: {}", app_type, provider_id, e);
|
||||
} else {
|
||||
log::info!(
|
||||
"已将 {} 的当前供应商 {} 设置为代理目标",
|
||||
app_type,
|
||||
provider_id
|
||||
);
|
||||
}
|
||||
} else {
|
||||
log::debug!("{} 没有当前供应商,跳过代理目标设置", app_type);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 同步 Live 配置中的 Token 到数据库
|
||||
///
|
||||
/// 在清空 Live Token 之前调用,确保数据库中的 Provider 配置有最新的 Token。
|
||||
/// 这样代理才能从数据库读取到正确的认证信息。
|
||||
async fn sync_live_to_providers(&self) -> Result<(), String> {
|
||||
// Claude: 同步 ANTHROPIC_AUTH_TOKEN
|
||||
if let Ok(live_config) = self.read_claude_live() {
|
||||
if let Some(provider_id) = self.db.get_current_provider("claude").ok().flatten() {
|
||||
if let Ok(Some(mut provider)) = self.db.get_provider_by_id(&provider_id, "claude") {
|
||||
// 从 live 配置提取 token
|
||||
if let Some(env) = live_config.get("env") {
|
||||
if let Some(token) =
|
||||
env.get("ANTHROPIC_AUTH_TOKEN").and_then(|v| v.as_str())
|
||||
{
|
||||
if !token.is_empty() {
|
||||
// 更新 provider 的 settings_config
|
||||
if let Some(env_obj) = provider
|
||||
.settings_config
|
||||
.get_mut("env")
|
||||
.and_then(|v| v.as_object_mut())
|
||||
{
|
||||
env_obj
|
||||
.insert("ANTHROPIC_AUTH_TOKEN".to_string(), json!(token));
|
||||
} else {
|
||||
provider.settings_config["env"] = json!({
|
||||
"ANTHROPIC_AUTH_TOKEN": token
|
||||
});
|
||||
}
|
||||
// 保存到数据库
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"claude",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
log::warn!("同步 Claude Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!(
|
||||
"已同步 Claude Token 到数据库 (provider: {})",
|
||||
provider_id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Codex: 同步 OPENAI_API_KEY
|
||||
if let Ok(live_config) = self.read_codex_live() {
|
||||
if let Some(provider_id) = self.db.get_current_provider("codex").ok().flatten() {
|
||||
if let Ok(Some(mut provider)) = self.db.get_provider_by_id(&provider_id, "codex") {
|
||||
// 从 live 配置提取 token
|
||||
if let Some(auth) = live_config.get("auth") {
|
||||
if let Some(token) = auth.get("OPENAI_API_KEY").and_then(|v| v.as_str()) {
|
||||
if !token.is_empty() {
|
||||
// 更新 provider 的 settings_config
|
||||
if let Some(auth_obj) = provider
|
||||
.settings_config
|
||||
.get_mut("auth")
|
||||
.and_then(|v| v.as_object_mut())
|
||||
{
|
||||
auth_obj.insert("OPENAI_API_KEY".to_string(), json!(token));
|
||||
} else {
|
||||
provider.settings_config["auth"] = json!({
|
||||
"OPENAI_API_KEY": token
|
||||
});
|
||||
}
|
||||
// 保存到数据库
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"codex",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
log::warn!("同步 Codex Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!(
|
||||
"已同步 Codex Token 到数据库 (provider: {})",
|
||||
provider_id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Gemini: 同步 GOOGLE_API_KEY
|
||||
if let Ok(live_config) = self.read_gemini_live() {
|
||||
if let Some(provider_id) = self.db.get_current_provider("gemini").ok().flatten() {
|
||||
if let Ok(Some(mut provider)) = self.db.get_provider_by_id(&provider_id, "gemini") {
|
||||
// 从 live 配置提取 token
|
||||
if let Some(env) = live_config.get("env") {
|
||||
if let Some(token) = env.get("GOOGLE_API_KEY").and_then(|v| v.as_str()) {
|
||||
if !token.is_empty() {
|
||||
// 更新 provider 的 settings_config
|
||||
if let Some(env_obj) = provider
|
||||
.settings_config
|
||||
.get_mut("env")
|
||||
.and_then(|v| v.as_object_mut())
|
||||
{
|
||||
env_obj.insert("GOOGLE_API_KEY".to_string(), json!(token));
|
||||
} else {
|
||||
provider.settings_config["env"] = json!({
|
||||
"GOOGLE_API_KEY": token
|
||||
});
|
||||
}
|
||||
// 保存到数据库
|
||||
if let Err(e) = self.db.update_provider_settings_config(
|
||||
"gemini",
|
||||
&provider_id,
|
||||
&provider.settings_config,
|
||||
) {
|
||||
log::warn!("同步 Gemini Token 到数据库失败: {e}");
|
||||
} else {
|
||||
log::info!(
|
||||
"已同步 Gemini Token 到数据库 (provider: {})",
|
||||
provider_id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("Live 配置 Token 同步完成");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 停止代理服务器
|
||||
pub async fn stop(&self) -> Result<(), String> {
|
||||
if let Some(server) = self.server.write().await.take() {
|
||||
@@ -66,6 +260,13 @@ impl ProxyService {
|
||||
.stop()
|
||||
.await
|
||||
.map_err(|e| format!("停止代理服务器失败: {e}"))?;
|
||||
|
||||
// 将 enabled 设为 false,避免下次启动时自动开启
|
||||
if let Ok(mut config) = self.db.get_proxy_config().await {
|
||||
config.enabled = false;
|
||||
let _ = self.db.update_proxy_config(config).await;
|
||||
}
|
||||
|
||||
log::info!("代理服务器已停止");
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -73,6 +274,267 @@ impl ProxyService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 停止代理服务器(恢复 Live 配置)
|
||||
pub async fn stop_with_restore(&self) -> Result<(), String> {
|
||||
// 1. 停止代理服务器
|
||||
self.stop().await?;
|
||||
|
||||
// 2. 恢复原始 Live 配置
|
||||
self.restore_live_configs().await?;
|
||||
|
||||
// 3. 清除接管状态
|
||||
self.db
|
||||
.set_live_takeover_active(false)
|
||||
.await
|
||||
.map_err(|e| format!("清除接管状态失败: {e}"))?;
|
||||
|
||||
// 4. 删除备份
|
||||
self.db
|
||||
.delete_all_live_backups()
|
||||
.await
|
||||
.map_err(|e| format!("删除备份失败: {e}"))?;
|
||||
|
||||
log::info!("代理已停止,Live 配置已恢复");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 备份各应用的 Live 配置
|
||||
async fn backup_live_configs(&self) -> Result<(), String> {
|
||||
// Claude
|
||||
if let Ok(config) = self.read_claude_live() {
|
||||
let json_str = serde_json::to_string(&config)
|
||||
.map_err(|e| format!("序列化 Claude 配置失败: {e}"))?;
|
||||
self.db
|
||||
.save_live_backup("claude", &json_str)
|
||||
.await
|
||||
.map_err(|e| format!("备份 Claude 配置失败: {e}"))?;
|
||||
}
|
||||
|
||||
// Codex
|
||||
if let Ok(config) = self.read_codex_live() {
|
||||
let json_str = serde_json::to_string(&config)
|
||||
.map_err(|e| format!("序列化 Codex 配置失败: {e}"))?;
|
||||
self.db
|
||||
.save_live_backup("codex", &json_str)
|
||||
.await
|
||||
.map_err(|e| format!("备份 Codex 配置失败: {e}"))?;
|
||||
}
|
||||
|
||||
// Gemini
|
||||
if let Ok(config) = self.read_gemini_live() {
|
||||
let json_str = serde_json::to_string(&config)
|
||||
.map_err(|e| format!("序列化 Gemini 配置失败: {e}"))?;
|
||||
self.db
|
||||
.save_live_backup("gemini", &json_str)
|
||||
.await
|
||||
.map_err(|e| format!("备份 Gemini 配置失败: {e}"))?;
|
||||
}
|
||||
|
||||
log::info!("已备份所有应用的 Live 配置");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 接管各应用的 Live 配置(写入代理地址)
|
||||
///
|
||||
/// 代理服务器的路由已经根据 API 端点自动区分应用类型:
|
||||
/// - `/v1/messages` → Claude
|
||||
/// - `/v1/chat/completions`, `/v1/responses` → Codex
|
||||
/// - `/v1beta/*` → Gemini
|
||||
///
|
||||
/// 因此不需要在 URL 中添加应用前缀。
|
||||
async fn takeover_live_configs(&self) -> Result<(), String> {
|
||||
let config = self
|
||||
.db
|
||||
.get_proxy_config()
|
||||
.await
|
||||
.map_err(|e| format!("获取代理配置失败: {e}"))?;
|
||||
|
||||
let proxy_url = format!("http://{}:{}", config.listen_address, config.listen_port);
|
||||
|
||||
// Claude: 修改 ANTHROPIC_BASE_URL,使用占位符替代真实 Token(代理会注入真实 Token)
|
||||
if let Ok(mut live_config) = self.read_claude_live() {
|
||||
if let Some(env) = live_config.get_mut("env").and_then(|v| v.as_object_mut()) {
|
||||
env.insert("ANTHROPIC_BASE_URL".to_string(), json!(&proxy_url));
|
||||
// 使用占位符,避免 Claude Code 显示缺少 key 的警告
|
||||
env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), json!("PROXY_MANAGED"));
|
||||
} else {
|
||||
live_config["env"] = json!({
|
||||
"ANTHROPIC_BASE_URL": &proxy_url,
|
||||
"ANTHROPIC_AUTH_TOKEN": "PROXY_MANAGED"
|
||||
});
|
||||
}
|
||||
self.write_claude_live(&live_config)?;
|
||||
log::info!("Claude Live 配置已接管,代理地址: {}", proxy_url);
|
||||
}
|
||||
|
||||
// Codex: 修改 OPENAI_BASE_URL,使用占位符替代真实 Token(代理会注入真实 Token)
|
||||
if let Ok(mut live_config) = self.read_codex_live() {
|
||||
if let Some(auth) = live_config.get_mut("auth").and_then(|v| v.as_object_mut()) {
|
||||
auth.insert("OPENAI_BASE_URL".to_string(), json!(&proxy_url));
|
||||
// 使用占位符,避免显示缺少 key 的警告
|
||||
auth.insert("OPENAI_API_KEY".to_string(), json!("PROXY_MANAGED"));
|
||||
}
|
||||
self.write_codex_live(&live_config)?;
|
||||
log::info!("Codex Live 配置已接管,代理地址: {}", proxy_url);
|
||||
}
|
||||
|
||||
// Gemini: 修改 GEMINI_API_BASE,使用占位符替代真实 Token(代理会注入真实 Token)
|
||||
if let Ok(mut live_config) = self.read_gemini_live() {
|
||||
if let Some(env) = live_config.get_mut("env").and_then(|v| v.as_object_mut()) {
|
||||
env.insert("GEMINI_API_BASE".to_string(), json!(&proxy_url));
|
||||
// 使用占位符,避免显示缺少 key 的警告
|
||||
env.insert("GOOGLE_API_KEY".to_string(), json!("PROXY_MANAGED"));
|
||||
} else {
|
||||
live_config["env"] = json!({
|
||||
"GEMINI_API_BASE": &proxy_url,
|
||||
"GOOGLE_API_KEY": "PROXY_MANAGED"
|
||||
});
|
||||
}
|
||||
self.write_gemini_live(&live_config)?;
|
||||
log::info!("Gemini Live 配置已接管,代理地址: {}", proxy_url);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 恢复原始 Live 配置
|
||||
async fn restore_live_configs(&self) -> Result<(), String> {
|
||||
// Claude
|
||||
if let Ok(Some(backup)) = self.db.get_live_backup("claude").await {
|
||||
let config: Value = serde_json::from_str(&backup.original_config)
|
||||
.map_err(|e| format!("解析 Claude 备份失败: {e}"))?;
|
||||
self.write_claude_live(&config)?;
|
||||
log::info!("Claude Live 配置已恢复");
|
||||
}
|
||||
|
||||
// Codex
|
||||
if let Ok(Some(backup)) = self.db.get_live_backup("codex").await {
|
||||
let config: Value = serde_json::from_str(&backup.original_config)
|
||||
.map_err(|e| format!("解析 Codex 备份失败: {e}"))?;
|
||||
self.write_codex_live(&config)?;
|
||||
log::info!("Codex Live 配置已恢复");
|
||||
}
|
||||
|
||||
// Gemini
|
||||
if let Ok(Some(backup)) = self.db.get_live_backup("gemini").await {
|
||||
let config: Value = serde_json::from_str(&backup.original_config)
|
||||
.map_err(|e| format!("解析 Gemini 备份失败: {e}"))?;
|
||||
self.write_gemini_live(&config)?;
|
||||
log::info!("Gemini Live 配置已恢复");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检查是否处于 Live 接管模式
|
||||
pub async fn is_takeover_active(&self) -> Result<bool, String> {
|
||||
self.db
|
||||
.is_live_takeover_active()
|
||||
.await
|
||||
.map_err(|e| format!("检查接管状态失败: {e}"))
|
||||
}
|
||||
|
||||
/// 代理模式下切换供应商(热切换,不写 Live)
|
||||
pub async fn switch_proxy_target(
|
||||
&self,
|
||||
app_type: &str,
|
||||
provider_id: &str,
|
||||
) -> Result<(), String> {
|
||||
// 更新数据库中的 is_current 标记
|
||||
let app_type_enum =
|
||||
AppType::from_str(app_type).map_err(|_| format!("无效的应用类型: {app_type}"))?;
|
||||
|
||||
self.db
|
||||
.set_current_provider(app_type_enum.as_str(), provider_id)
|
||||
.map_err(|e| format!("更新当前供应商失败: {e}"))?;
|
||||
|
||||
log::info!(
|
||||
"代理模式:已切换 {} 的目标供应商为 {}",
|
||||
app_type,
|
||||
provider_id
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== Live 配置读写辅助方法 ====================
|
||||
|
||||
fn read_claude_live(&self) -> Result<Value, String> {
|
||||
let path = get_claude_settings_path();
|
||||
if !path.exists() {
|
||||
return Err("Claude 配置文件不存在".to_string());
|
||||
}
|
||||
read_json_file(&path).map_err(|e| format!("读取 Claude 配置失败: {e}"))
|
||||
}
|
||||
|
||||
fn write_claude_live(&self, config: &Value) -> Result<(), String> {
|
||||
let path = get_claude_settings_path();
|
||||
write_json_file(&path, config).map_err(|e| format!("写入 Claude 配置失败: {e}"))
|
||||
}
|
||||
|
||||
fn read_codex_live(&self) -> Result<Value, String> {
|
||||
use crate::codex_config::{get_codex_auth_path, get_codex_config_path};
|
||||
|
||||
let auth_path = get_codex_auth_path();
|
||||
if !auth_path.exists() {
|
||||
return Err("Codex auth.json 不存在".to_string());
|
||||
}
|
||||
|
||||
let auth: Value =
|
||||
read_json_file(&auth_path).map_err(|e| format!("读取 Codex auth 失败: {e}"))?;
|
||||
|
||||
let config_path = get_codex_config_path();
|
||||
let config_str = if config_path.exists() {
|
||||
std::fs::read_to_string(&config_path)
|
||||
.map_err(|e| format!("读取 Codex config 失败: {e}"))?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
Ok(json!({
|
||||
"auth": auth,
|
||||
"config": config_str
|
||||
}))
|
||||
}
|
||||
|
||||
fn write_codex_live(&self, config: &Value) -> Result<(), String> {
|
||||
use crate::codex_config::{get_codex_auth_path, get_codex_config_path};
|
||||
|
||||
if let Some(auth) = config.get("auth") {
|
||||
let auth_path = get_codex_auth_path();
|
||||
write_json_file(&auth_path, auth).map_err(|e| format!("写入 Codex auth 失败: {e}"))?;
|
||||
}
|
||||
|
||||
if let Some(config_str) = config.get("config").and_then(|v| v.as_str()) {
|
||||
let config_path = get_codex_config_path();
|
||||
std::fs::write(&config_path, config_str)
|
||||
.map_err(|e| format!("写入 Codex config 失败: {e}"))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_gemini_live(&self) -> Result<Value, String> {
|
||||
use crate::gemini_config::{env_to_json, get_gemini_env_path, read_gemini_env};
|
||||
|
||||
let env_path = get_gemini_env_path();
|
||||
if !env_path.exists() {
|
||||
return Err("Gemini .env 文件不存在".to_string());
|
||||
}
|
||||
|
||||
let env_map = read_gemini_env().map_err(|e| format!("读取 Gemini env 失败: {e}"))?;
|
||||
Ok(env_to_json(&env_map))
|
||||
}
|
||||
|
||||
fn write_gemini_live(&self, config: &Value) -> Result<(), String> {
|
||||
use crate::gemini_config::{json_to_env, write_gemini_env_atomic};
|
||||
|
||||
let env_map = json_to_env(config).map_err(|e| format!("转换 Gemini 配置失败: {e}"))?;
|
||||
write_gemini_env_atomic(&env_map).map_err(|e| format!("写入 Gemini env 失败: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ==================== 原有方法 ====================
|
||||
|
||||
/// 获取服务器状态
|
||||
pub async fn get_status(&self) -> Result<ProxyStatus, String> {
|
||||
if let Some(server) = self.server.read().await.as_ref() {
|
||||
@@ -103,9 +565,10 @@ impl ProxyService {
|
||||
.await
|
||||
.map_err(|e| format!("获取代理配置失败: {e}"))?;
|
||||
|
||||
// 保存到数据库(保持 enabled 状态不变)
|
||||
// 保存到数据库(保持 enabled 和 live_takeover_active 状态不变)
|
||||
let mut new_config = config.clone();
|
||||
new_config.enabled = previous.enabled;
|
||||
new_config.live_takeover_active = previous.live_takeover_active;
|
||||
|
||||
self.db
|
||||
.update_proxy_config(new_config.clone())
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
//! 流式健康检查服务
|
||||
//!
|
||||
//! 使用流式 API 进行快速健康检查,只需接收首个 chunk 即判定成功。
|
||||
|
||||
use futures::StreamExt;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::providers::{get_adapter, AuthInfo};
|
||||
|
||||
/// 健康状态枚举
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum HealthStatus {
|
||||
Operational,
|
||||
Degraded,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// 流式检查配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StreamCheckConfig {
|
||||
pub timeout_secs: u64,
|
||||
pub max_retries: u32,
|
||||
pub degraded_threshold_ms: u64,
|
||||
/// Claude 测试模型
|
||||
pub claude_model: String,
|
||||
/// Codex 测试模型
|
||||
pub codex_model: String,
|
||||
/// Gemini 测试模型
|
||||
pub gemini_model: String,
|
||||
}
|
||||
|
||||
impl Default for StreamCheckConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
timeout_secs: 45,
|
||||
max_retries: 2,
|
||||
degraded_threshold_ms: 6000,
|
||||
claude_model: "claude-haiku-4-5-20251001".to_string(),
|
||||
codex_model: "gpt-5.1-codex@low".to_string(),
|
||||
gemini_model: "gemini-3-pro-preview".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 流式检查结果
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StreamCheckResult {
|
||||
pub status: HealthStatus,
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub response_time_ms: Option<u64>,
|
||||
pub http_status: Option<u16>,
|
||||
pub model_used: String,
|
||||
pub tested_at: i64,
|
||||
pub retry_count: u32,
|
||||
}
|
||||
|
||||
/// 流式健康检查服务
|
||||
pub struct StreamCheckService;
|
||||
|
||||
impl StreamCheckService {
|
||||
/// 执行流式健康检查(带重试)
|
||||
pub async fn check_with_retry(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
let mut last_result = None;
|
||||
|
||||
for attempt in 0..=config.max_retries {
|
||||
let result = Self::check_once(app_type, provider, config).await;
|
||||
|
||||
match &result {
|
||||
Ok(r) if r.success => {
|
||||
return Ok(StreamCheckResult {
|
||||
retry_count: attempt,
|
||||
..r.clone()
|
||||
});
|
||||
}
|
||||
Ok(r) => {
|
||||
// 失败但非异常,判断是否重试
|
||||
if Self::should_retry(&r.message) && attempt < config.max_retries {
|
||||
last_result = Some(r.clone());
|
||||
continue;
|
||||
}
|
||||
return Ok(StreamCheckResult {
|
||||
retry_count: attempt,
|
||||
..r.clone()
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
if Self::should_retry(&e.to_string()) && attempt < config.max_retries {
|
||||
continue;
|
||||
}
|
||||
return Err(AppError::Message(e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(last_result.unwrap_or_else(|| StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
success: false,
|
||||
message: "检查失败".to_string(),
|
||||
response_time_ms: None,
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: config.max_retries,
|
||||
}))
|
||||
}
|
||||
|
||||
/// 单次流式检查
|
||||
async fn check_once(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
config: &StreamCheckConfig,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
let start = Instant::now();
|
||||
let adapter = get_adapter(app_type);
|
||||
|
||||
let base_url = adapter
|
||||
.extract_base_url(provider)
|
||||
.map_err(|e| AppError::Message(format!("提取 base_url 失败: {e}")))?;
|
||||
|
||||
let auth = adapter
|
||||
.extract_auth(provider)
|
||||
.ok_or_else(|| AppError::Message("未找到 API Key".to_string()))?;
|
||||
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(config.timeout_secs))
|
||||
.user_agent("cc-switch/1.0")
|
||||
.build()
|
||||
.map_err(|e| AppError::Message(format!("创建客户端失败: {e}")))?;
|
||||
|
||||
let result = match app_type {
|
||||
AppType::Claude => {
|
||||
Self::check_claude_stream(&client, &base_url, &auth, &config.claude_model).await
|
||||
}
|
||||
AppType::Codex => {
|
||||
Self::check_codex_stream(&client, &base_url, &auth, &config.codex_model).await
|
||||
}
|
||||
AppType::Gemini => {
|
||||
Self::check_gemini_stream(&client, &base_url, &auth, &config.gemini_model).await
|
||||
}
|
||||
};
|
||||
|
||||
let response_time = start.elapsed().as_millis() as u64;
|
||||
let tested_at = chrono::Utc::now().timestamp();
|
||||
|
||||
match result {
|
||||
Ok((status_code, model)) => {
|
||||
let health_status =
|
||||
Self::determine_status(response_time, config.degraded_threshold_ms);
|
||||
Ok(StreamCheckResult {
|
||||
status: health_status,
|
||||
success: true,
|
||||
message: "检查成功".to_string(),
|
||||
response_time_ms: Some(response_time),
|
||||
http_status: Some(status_code),
|
||||
model_used: model,
|
||||
tested_at,
|
||||
retry_count: 0,
|
||||
})
|
||||
}
|
||||
Err(e) => Ok(StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
success: false,
|
||||
message: e.to_string(),
|
||||
response_time_ms: Some(response_time),
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at,
|
||||
retry_count: 0,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Claude 流式检查
|
||||
async fn check_claude_stream(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
auth: &AuthInfo,
|
||||
model: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = if base.ends_with("/v1") {
|
||||
format!("{base}/messages")
|
||||
} else {
|
||||
format!("{base}/v1/messages")
|
||||
};
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"max_tokens": 1,
|
||||
"messages": [{ "role": "user", "content": "hi" }],
|
||||
"stream": true
|
||||
});
|
||||
|
||||
let response = client
|
||||
.post(&url)
|
||||
.header("x-api-key", &auth.api_key)
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(Self::map_request_error)?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if !response.status().is_success() {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
|
||||
}
|
||||
|
||||
// 流式读取:只需首个 chunk
|
||||
let mut stream = response.bytes_stream();
|
||||
if let Some(chunk) = stream.next().await {
|
||||
match chunk {
|
||||
Ok(_) => Ok((status, model.to_string())),
|
||||
Err(e) => Err(AppError::Message(format!("读取流失败: {e}"))),
|
||||
}
|
||||
} else {
|
||||
Err(AppError::Message("未收到响应数据".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Codex 流式检查
|
||||
async fn check_codex_stream(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
auth: &AuthInfo,
|
||||
model: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = if base.ends_with("/v1") {
|
||||
format!("{base}/chat/completions")
|
||||
} else {
|
||||
format!("{base}/v1/chat/completions")
|
||||
};
|
||||
|
||||
// 解析模型名和推理等级 (支持 model@level 或 model#level 格式)
|
||||
let (actual_model, reasoning_effort) = Self::parse_model_with_effort(model);
|
||||
|
||||
let mut body = json!({
|
||||
"model": actual_model,
|
||||
"messages": [
|
||||
{ "role": "system", "content": "" },
|
||||
{ "role": "assistant", "content": "" },
|
||||
{ "role": "user", "content": "hi" }
|
||||
],
|
||||
"max_tokens": 1,
|
||||
"temperature": 0,
|
||||
"stream": true
|
||||
});
|
||||
|
||||
// 如果是推理模型,添加 reasoning_effort
|
||||
if let Some(effort) = reasoning_effort {
|
||||
body["reasoning_effort"] = json!(effort);
|
||||
}
|
||||
|
||||
let response = client
|
||||
.post(&url)
|
||||
.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(Self::map_request_error)?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if !response.status().is_success() {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
|
||||
}
|
||||
|
||||
let mut stream = response.bytes_stream();
|
||||
if let Some(chunk) = stream.next().await {
|
||||
match chunk {
|
||||
Ok(_) => Ok((status, model.to_string())),
|
||||
Err(e) => Err(AppError::Message(format!("读取流失败: {e}"))),
|
||||
}
|
||||
} else {
|
||||
Err(AppError::Message("未收到响应数据".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Gemini 流式检查
|
||||
async fn check_gemini_stream(
|
||||
client: &Client,
|
||||
base_url: &str,
|
||||
auth: &AuthInfo,
|
||||
model: &str,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
let url = format!("{base}/v1/chat/completions");
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"messages": [{ "role": "user", "content": "hi" }],
|
||||
"max_tokens": 1,
|
||||
"temperature": 0,
|
||||
"stream": true
|
||||
});
|
||||
|
||||
let response = client
|
||||
.post(&url)
|
||||
.header("Authorization", format!("Bearer {}", auth.api_key))
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(Self::map_request_error)?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
if !response.status().is_success() {
|
||||
let error_text = response.text().await.unwrap_or_default();
|
||||
return Err(AppError::Message(format!("HTTP {status}: {error_text}")));
|
||||
}
|
||||
|
||||
let mut stream = response.bytes_stream();
|
||||
if let Some(chunk) = stream.next().await {
|
||||
match chunk {
|
||||
Ok(_) => Ok((status, model.to_string())),
|
||||
Err(e) => Err(AppError::Message(format!("读取流失败: {e}"))),
|
||||
}
|
||||
} else {
|
||||
Err(AppError::Message("未收到响应数据".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn determine_status(latency_ms: u64, threshold: u64) -> HealthStatus {
|
||||
if latency_ms <= threshold {
|
||||
HealthStatus::Operational
|
||||
} else {
|
||||
HealthStatus::Degraded
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析模型名和推理等级 (支持 model@level 或 model#level 格式)
|
||||
/// 返回 (实际模型名, Option<推理等级>)
|
||||
fn parse_model_with_effort(model: &str) -> (String, Option<String>) {
|
||||
// 查找 @ 或 # 分隔符
|
||||
if let Some(pos) = model.find('@').or_else(|| model.find('#')) {
|
||||
let actual_model = model[..pos].to_string();
|
||||
let effort = model[pos + 1..].to_string();
|
||||
if !effort.is_empty() {
|
||||
return (actual_model, Some(effort));
|
||||
}
|
||||
}
|
||||
(model.to_string(), None)
|
||||
}
|
||||
|
||||
fn should_retry(msg: &str) -> bool {
|
||||
let lower = msg.to_lowercase();
|
||||
lower.contains("timeout")
|
||||
|| lower.contains("abort")
|
||||
|| lower.contains("中断")
|
||||
|| lower.contains("超时")
|
||||
}
|
||||
|
||||
fn map_request_error(e: reqwest::Error) -> AppError {
|
||||
if e.is_timeout() {
|
||||
AppError::Message("请求超时".to_string())
|
||||
} else if e.is_connect() {
|
||||
AppError::Message(format!("连接失败: {e}"))
|
||||
} else {
|
||||
AppError::Message(e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_determine_status() {
|
||||
assert_eq!(
|
||||
StreamCheckService::determine_status(3000, 6000),
|
||||
HealthStatus::Operational
|
||||
);
|
||||
assert_eq!(
|
||||
StreamCheckService::determine_status(6000, 6000),
|
||||
HealthStatus::Operational
|
||||
);
|
||||
assert_eq!(
|
||||
StreamCheckService::determine_status(6001, 6000),
|
||||
HealthStatus::Degraded
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_retry() {
|
||||
assert!(StreamCheckService::should_retry("请求超时"));
|
||||
assert!(StreamCheckService::should_retry("request timeout"));
|
||||
assert!(!StreamCheckService::should_retry("API Key 无效"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_config() {
|
||||
let config = StreamCheckConfig::default();
|
||||
assert_eq!(config.timeout_secs, 45);
|
||||
assert_eq!(config.max_retries, 2);
|
||||
assert_eq!(config.degraded_threshold_ms, 6000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_model_with_effort() {
|
||||
// 带 @ 分隔符
|
||||
let (model, effort) = StreamCheckService::parse_model_with_effort("gpt-5.1-codex@low");
|
||||
assert_eq!(model, "gpt-5.1-codex");
|
||||
assert_eq!(effort, Some("low".to_string()));
|
||||
|
||||
// 带 # 分隔符
|
||||
let (model, effort) = StreamCheckService::parse_model_with_effort("o1-preview#high");
|
||||
assert_eq!(model, "o1-preview");
|
||||
assert_eq!(effort, Some("high".to_string()));
|
||||
|
||||
// 无分隔符
|
||||
let (model, effort) = StreamCheckService::parse_model_with_effort("gpt-4o-mini");
|
||||
assert_eq!(model, "gpt-4o-mini");
|
||||
assert_eq!(effort, None);
|
||||
}
|
||||
}
|
||||
@@ -652,56 +652,6 @@ impl Database {
|
||||
monthly_exceeded,
|
||||
})
|
||||
}
|
||||
|
||||
/// 更新每日统计聚合
|
||||
///
|
||||
/// 在请求完成后调用,更新 usage_daily_stats 表
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn update_daily_stats(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
app_type: &str,
|
||||
model: &str,
|
||||
input_tokens: u32,
|
||||
output_tokens: u32,
|
||||
total_cost: &str,
|
||||
is_success: bool,
|
||||
) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let date = Utc::now().format("%Y-%m-%d").to_string();
|
||||
|
||||
// 使用 UPSERT 更新或插入统计
|
||||
conn.execute(
|
||||
"INSERT INTO usage_daily_stats (
|
||||
date, provider_id, app_type, model,
|
||||
request_count, total_input_tokens, total_output_tokens,
|
||||
total_cost_usd, success_count, error_count
|
||||
) VALUES (?1, ?2, ?3, ?4, 1, ?5, ?6, ?7, ?8, ?9)
|
||||
ON CONFLICT(date, provider_id, app_type, model) DO UPDATE SET
|
||||
request_count = request_count + 1,
|
||||
total_input_tokens = total_input_tokens + ?5,
|
||||
total_output_tokens = total_output_tokens + ?6,
|
||||
total_cost_usd = CAST(
|
||||
CAST(total_cost_usd AS REAL) + CAST(?7 AS REAL) AS TEXT
|
||||
),
|
||||
success_count = success_count + ?8,
|
||||
error_count = error_count + ?9",
|
||||
params![
|
||||
date,
|
||||
provider_id,
|
||||
app_type,
|
||||
model,
|
||||
input_tokens,
|
||||
output_tokens,
|
||||
total_cost,
|
||||
if is_success { 1 } else { 0 },
|
||||
if is_success { 0 } else { 1 },
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(format!("更新每日统计失败: {e}")))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Provider 限额状态
|
||||
|
||||
@@ -525,23 +525,18 @@ fn validate_request_url(request_url: &str, base_url: &str) -> Result<(), AppErro
|
||||
|
||||
// 检查端口是否匹配(考虑默认端口)
|
||||
// 使用 port_or_known_default() 会自动处理默认端口(http->80, https->443)
|
||||
match (parsed_request.port_or_known_default(), parsed_base.port_or_known_default()) {
|
||||
match (
|
||||
parsed_request.port_or_known_default(),
|
||||
parsed_base.port_or_known_default(),
|
||||
) {
|
||||
(Some(request_port), Some(base_port)) if request_port == base_port => {
|
||||
// 端口匹配,继续执行
|
||||
}
|
||||
(Some(request_port), Some(base_port)) => {
|
||||
return Err(AppError::localized(
|
||||
"usage_script.request_port_mismatch",
|
||||
format!(
|
||||
"请求端口 {} 必须与 base_url 端口 {} 匹配",
|
||||
request_port,
|
||||
base_port
|
||||
),
|
||||
format!(
|
||||
"Request port {} must match base_url port {}",
|
||||
request_port,
|
||||
base_port
|
||||
),
|
||||
format!("请求端口 {request_port} 必须与 base_url 端口 {base_port} 匹配"),
|
||||
format!("Request port {request_port} must match base_url port {base_port}"),
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
@@ -774,22 +769,25 @@ mod tests {
|
||||
fn test_https_bypass_prevention() {
|
||||
// 非本地域名的 HTTP 应该被拒绝
|
||||
let result = validate_base_url("http://127.0.0.1.evil.com/api");
|
||||
assert!(result.is_err(), "Should reject HTTP for non-localhost domains");
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"Should reject HTTP for non-localhost domains"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_edge_cases() {
|
||||
// 边界情况测试
|
||||
assert!(is_private_ip("172.16.0.0")); // RFC1918起始
|
||||
assert!(is_private_ip("172.16.0.0")); // RFC1918起始
|
||||
assert!(is_private_ip("172.31.255.255")); // RFC1918结束
|
||||
assert!(is_private_ip("10.0.0.0")); // 10.0.0.0/8起始
|
||||
assert!(is_private_ip("10.0.0.0")); // 10.0.0.0/8起始
|
||||
assert!(is_private_ip("10.255.255.255")); // 10.0.0.0/8结束
|
||||
assert!(is_private_ip("192.168.0.0")); // 192.168.0.0/16起始
|
||||
assert!(is_private_ip("192.168.0.0")); // 192.168.0.0/16起始
|
||||
assert!(is_private_ip("192.168.255.255")); // 192.168.0.0/16结束
|
||||
|
||||
// 紧邻RFC1918的公网地址 - 应该返回false
|
||||
assert!(!is_private_ip("172.15.255.255")); // 172.16.0.0的前一个
|
||||
assert!(!is_private_ip("172.32.0.0")); // 172.31.255.255的后一个
|
||||
assert!(!is_private_ip("172.32.0.0")); // 172.31.255.255的后一个
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -815,27 +813,57 @@ mod tests {
|
||||
// 测试用例:(base_url, request_url, should_match)
|
||||
let test_cases = vec![
|
||||
// HTTPS默认端口测试
|
||||
("https://api.example.com", "https://api.example.com/v1/test", true),
|
||||
("https://api.example.com", "https://api.example.com:443/v1/test", true),
|
||||
("https://api.example.com:443", "https://api.example.com/v1/test", true),
|
||||
("https://api.example.com:443", "https://api.example.com:443/v1/test", true),
|
||||
|
||||
(
|
||||
"https://api.example.com",
|
||||
"https://api.example.com/v1/test",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"https://api.example.com",
|
||||
"https://api.example.com:443/v1/test",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"https://api.example.com:443",
|
||||
"https://api.example.com/v1/test",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"https://api.example.com:443",
|
||||
"https://api.example.com:443/v1/test",
|
||||
true,
|
||||
),
|
||||
// 端口不匹配测试
|
||||
("https://api.example.com", "https://api.example.com:8443/v1/test", false),
|
||||
("https://api.example.com:443", "https://api.example.com:8443/v1/test", false),
|
||||
(
|
||||
"https://api.example.com",
|
||||
"https://api.example.com:8443/v1/test",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"https://api.example.com:443",
|
||||
"https://api.example.com:8443/v1/test",
|
||||
false,
|
||||
),
|
||||
];
|
||||
|
||||
for (base_url, request_url, should_match) in test_cases {
|
||||
let result = validate_request_url(request_url, base_url);
|
||||
|
||||
if should_match {
|
||||
assert!(result.is_ok(),
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"应该匹配的URL被拒绝: base_url={}, request_url={}, error={}",
|
||||
base_url, request_url, result.unwrap_err());
|
||||
base_url,
|
||||
request_url,
|
||||
result.unwrap_err()
|
||||
);
|
||||
} else {
|
||||
assert!(result.is_err(),
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"应该不匹配的URL被允许: base_url={}, request_url={}",
|
||||
base_url, request_url);
|
||||
base_url,
|
||||
request_url
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+12
-2
@@ -25,6 +25,7 @@ import { checkAllEnvConflicts, checkEnvConflicts } from "@/lib/api/env";
|
||||
import { useProviderActions } from "@/hooks/useProviderActions";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { AppSwitcher } from "@/components/AppSwitcher";
|
||||
import { ProviderList } from "@/components/providers/ProviderList";
|
||||
import { AddProviderDialog } from "@/components/providers/AddProviderDialog";
|
||||
@@ -33,6 +34,7 @@ import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||
import { SettingsPage } from "@/components/settings/SettingsPage";
|
||||
import { UpdateBadge } from "@/components/UpdateBadge";
|
||||
import { EnvWarningBanner } from "@/components/env/EnvWarningBanner";
|
||||
import { ProxyToggle } from "@/components/proxy/ProxyToggle";
|
||||
import UsageScriptModal from "@/components/UsageScriptModal";
|
||||
import UnifiedMcpPanel from "@/components/mcp/UnifiedMcpPanel";
|
||||
import PromptPanel from "@/components/prompts/PromptPanel";
|
||||
@@ -63,7 +65,7 @@ function App() {
|
||||
"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 { isRunning: isProxyRunning } = useProxyStatus();
|
||||
const { isRunning: isProxyRunning, isTakeoverActive } = useProxyStatus();
|
||||
|
||||
// 获取供应商列表,当代理服务运行时自动刷新
|
||||
const { data, isLoading, refetch } = useProvidersQuery(activeApp, {
|
||||
@@ -321,6 +323,7 @@ function App() {
|
||||
appId={activeApp}
|
||||
isLoading={isLoading}
|
||||
isProxyRunning={isProxyRunning}
|
||||
isProxyTakeover={isProxyRunning && isTakeoverActive}
|
||||
onSwitch={switchProvider}
|
||||
onEdit={setEditingProvider}
|
||||
onDelete={setConfirmDelete}
|
||||
@@ -415,7 +418,12 @@ function App() {
|
||||
href="https://github.com/farion1231/cc-switch"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-xl font-semibold text-blue-500 transition-colors hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
className={cn(
|
||||
"text-xl font-semibold transition-colors",
|
||||
isProxyRunning && isTakeoverActive
|
||||
? "text-emerald-500 hover:text-emerald-600 dark:text-emerald-400 dark:hover:text-emerald-300"
|
||||
: "text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
)}
|
||||
>
|
||||
CC Switch
|
||||
</a>
|
||||
@@ -482,6 +490,8 @@ function App() {
|
||||
)}
|
||||
{currentView === "providers" && (
|
||||
<>
|
||||
<ProxyToggle />
|
||||
|
||||
<AppSwitcher activeApp={activeApp} onSwitch={setActiveApp} />
|
||||
|
||||
<div className="bg-muted p-1 rounded-xl flex items-center gap-1">
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { HealthStatus } from "@/lib/api/model-test";
|
||||
|
||||
interface HealthStatusIndicatorProps {
|
||||
status: HealthStatus;
|
||||
responseTimeMs?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const statusConfig = {
|
||||
operational: {
|
||||
color: "bg-emerald-500",
|
||||
label: "正常",
|
||||
textColor: "text-emerald-600 dark:text-emerald-400",
|
||||
},
|
||||
degraded: {
|
||||
color: "bg-yellow-500",
|
||||
label: "降级",
|
||||
textColor: "text-yellow-600 dark:text-yellow-400",
|
||||
},
|
||||
failed: {
|
||||
color: "bg-red-500",
|
||||
label: "失败",
|
||||
textColor: "text-red-600 dark:text-red-400",
|
||||
},
|
||||
};
|
||||
|
||||
export const HealthStatusIndicator: React.FC<HealthStatusIndicatorProps> = ({
|
||||
status,
|
||||
responseTimeMs,
|
||||
className,
|
||||
}) => {
|
||||
const config = statusConfig[status];
|
||||
|
||||
return (
|
||||
<div className={cn("flex items-center gap-2", className)}>
|
||||
<div className={cn("w-2 h-2 rounded-full", config.color)} />
|
||||
<span className={cn("text-xs font-medium", config.textColor)}>
|
||||
{config.label}
|
||||
{responseTimeMs !== undefined && ` (${responseTimeMs}ms)`}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -16,6 +16,7 @@ import { cn } from "@/lib/utils";
|
||||
interface ProviderActionsProps {
|
||||
isCurrent: boolean;
|
||||
isTesting?: boolean;
|
||||
isProxyTakeover?: boolean;
|
||||
onSwitch: () => void;
|
||||
onEdit: () => void;
|
||||
onDuplicate: () => void;
|
||||
@@ -30,6 +31,7 @@ interface ProviderActionsProps {
|
||||
export function ProviderActions({
|
||||
isCurrent,
|
||||
isTesting,
|
||||
isProxyTakeover = false,
|
||||
onSwitch,
|
||||
onEdit,
|
||||
onDuplicate,
|
||||
@@ -54,6 +56,10 @@ export function ProviderActions({
|
||||
"w-[4.5rem] px-2.5",
|
||||
isCurrent &&
|
||||
"bg-gray-200 text-muted-foreground hover:bg-gray-200 hover:text-muted-foreground dark:bg-gray-700 dark:hover:bg-gray-700",
|
||||
// 代理接管模式下启用按钮使用绿色
|
||||
!isCurrent &&
|
||||
isProxyTakeover &&
|
||||
"bg-emerald-500 hover:bg-emerald-600 dark:bg-emerald-600 dark:hover:bg-emerald-700"
|
||||
)}
|
||||
>
|
||||
{isCurrent ? (
|
||||
@@ -118,7 +124,8 @@ export function ProviderActions({
|
||||
</Button>
|
||||
|
||||
{/* 重置熔断器按钮 - 代理目标启用时显示 */}
|
||||
{onResetCircuitBreaker && isProxyTarget && (
|
||||
{/* TODO: 暂时隐藏,后续根据故障转移功能启用 */}
|
||||
{/* {onResetCircuitBreaker && isProxyTarget && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
@@ -141,7 +148,7 @@ export function ProviderActions({
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
)} */}
|
||||
|
||||
<Button
|
||||
size="icon"
|
||||
@@ -151,7 +158,7 @@ export function ProviderActions({
|
||||
className={cn(
|
||||
iconButtonClass,
|
||||
!isCurrent && "hover:text-red-500 dark:hover:text-red-400",
|
||||
isCurrent && "opacity-40 cursor-not-allowed text-muted-foreground",
|
||||
isCurrent && "opacity-40 cursor-not-allowed text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
|
||||
@@ -11,13 +11,10 @@ import { cn } from "@/lib/utils";
|
||||
import { ProviderActions } from "@/components/providers/ProviderActions";
|
||||
import { ProviderIcon } from "@/components/ProviderIcon";
|
||||
import UsageFooter from "@/components/UsageFooter";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ProviderHealthBadge } from "@/components/providers/ProviderHealthBadge";
|
||||
import {
|
||||
useProviderHealth,
|
||||
useResetCircuitBreaker,
|
||||
useSetProxyTarget,
|
||||
} from "@/lib/query/failover";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -40,8 +37,7 @@ interface ProviderCardProps {
|
||||
onTest?: (provider: Provider) => void;
|
||||
isTesting?: boolean;
|
||||
isProxyRunning: boolean;
|
||||
proxyPriority?: number; // 代理目标的实际优先级 (1, 2, 3...)
|
||||
allProviders?: Provider[]; // 所有供应商列表,用于计算开启后的优先级
|
||||
isProxyTakeover?: boolean; // 代理接管模式(Live配置已被接管,切换为热切换)
|
||||
dragHandleProps?: DragHandleProps;
|
||||
}
|
||||
|
||||
@@ -93,8 +89,7 @@ export function ProviderCard({
|
||||
onTest,
|
||||
isTesting,
|
||||
isProxyRunning,
|
||||
proxyPriority,
|
||||
allProviders,
|
||||
isProxyTakeover = false,
|
||||
dragHandleProps,
|
||||
}: ProviderCardProps) {
|
||||
const { t } = useTranslation();
|
||||
@@ -102,77 +97,9 @@ export function ProviderCard({
|
||||
// 获取供应商健康状态
|
||||
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({
|
||||
@@ -230,13 +157,25 @@ export function ProviderCard({
|
||||
<div
|
||||
className={cn(
|
||||
"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",
|
||||
"bg-card text-card-foreground group",
|
||||
// 代理接管模式下 hover 使用绿色边框,否则使用蓝色
|
||||
isProxyTakeover ? "hover:border-emerald-500/50" : "hover:border-border-active",
|
||||
// 代理接管模式下当前供应商使用绿色边框
|
||||
isProxyTakeover && isCurrent
|
||||
? "border-emerald-500/60 shadow-sm shadow-emerald-500/10"
|
||||
: isCurrent
|
||||
? "border-primary/50 shadow-sm"
|
||||
: "hover:shadow-sm",
|
||||
dragHandleProps?.isDragging &&
|
||||
"cursor-grabbing border-primary shadow-lg scale-105 z-10",
|
||||
)}
|
||||
>
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-primary/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none" />
|
||||
<div className={cn(
|
||||
"absolute inset-0 bg-gradient-to-r to-transparent transition-opacity duration-500 pointer-events-none",
|
||||
// 代理接管模式下使用绿色渐变,否则使用蓝色主色调
|
||||
isProxyTakeover && isCurrent ? "from-emerald-500/10" : "from-primary/10",
|
||||
isCurrent ? "opacity-100" : "opacity-0"
|
||||
)} />
|
||||
<div className="relative flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-1 items-center gap-2">
|
||||
<button
|
||||
@@ -270,25 +209,10 @@ export function ProviderCard({
|
||||
</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>
|
||||
{isProxyRunning && health && (
|
||||
<ProviderHealthBadge
|
||||
consecutiveFailures={health.consecutive_failures}
|
||||
/>
|
||||
)}
|
||||
|
||||
{provider.category === "third_party" &&
|
||||
@@ -302,42 +226,6 @@ export function ProviderCard({
|
||||
⭐
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* 代理目标开关 - 仅在代理服务运行时显示 */}
|
||||
{isProxyRunning && (
|
||||
<div
|
||||
className="flex items-center gap-2 ml-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Switch
|
||||
id={`proxy-target-switch-${provider.id}`}
|
||||
checked={provider.isProxyTarget || false}
|
||||
onCheckedChange={(checked) => {
|
||||
handleSetProxyTarget(checked);
|
||||
}}
|
||||
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-green-600 dark:text-green-400 cursor-pointer"
|
||||
>
|
||||
{t("provider.proxyTarget", { defaultValue: "代理目标" })}
|
||||
</Label>
|
||||
)}
|
||||
{!provider.isProxyTarget && (
|
||||
<Label
|
||||
htmlFor={`proxy-target-switch-${provider.id}`}
|
||||
className="text-xs text-muted-foreground cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
{t("provider.setAsProxyTarget", {
|
||||
defaultValue: "设为代理",
|
||||
})}
|
||||
</Label>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{displayUrl && (
|
||||
@@ -360,7 +248,7 @@ export function ProviderCard({
|
||||
</div>
|
||||
|
||||
<div className="relative flex items-center ml-auto">
|
||||
<div className="ml-auto transition-transform duration-200 group-hover:-translate-x-[12.25rem] group-focus-within:-translate-x-[12.25rem] sm:group-hover:-translate-x-[14.25rem] sm:group-focus-within:-translate-x-[14.25rem]">
|
||||
<div className="ml-auto transition-transform duration-300 ease-out group-hover:-translate-x-[14.5rem] group-focus-within:-translate-x-[14.5rem] sm:group-hover:-translate-x-[16.5rem] sm:group-focus-within:-translate-x-[16.5rem]">
|
||||
<UsageFooter
|
||||
provider={provider}
|
||||
providerId={provider.id}
|
||||
@@ -371,10 +259,11 @@ export function ProviderCard({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="absolute right-0 top-1/2 -translate-y-1/2 flex items-center gap-1.5 opacity-0 pointer-events-none group-hover:opacity-100 group-focus-within:opacity-100 group-hover:pointer-events-auto group-focus-within:pointer-events-auto transition-all duration-200 translate-x-2 group-hover:translate-x-0 group-focus-within:translate-x-0">
|
||||
<div className="absolute right-0 top-1/2 -translate-y-1/2 flex items-center gap-1.5 opacity-0 pointer-events-none group-hover:opacity-100 group-focus-within:opacity-100 group-hover:pointer-events-auto group-focus-within:pointer-events-auto transition-all duration-300 ease-out translate-x-2 group-hover:translate-x-0 group-focus-within:translate-x-0">
|
||||
<ProviderActions
|
||||
isCurrent={isCurrent}
|
||||
isTesting={isTesting}
|
||||
isProxyTakeover={isProxyTakeover}
|
||||
onSwitch={() => onSwitch(provider)}
|
||||
onEdit={() => onEdit(provider)}
|
||||
onDuplicate={() => onDuplicate(provider)}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { ProviderHealthStatus } from "@/types/proxy";
|
||||
|
||||
interface ProviderHealthBadgeProps {
|
||||
consecutiveFailures: number;
|
||||
isProxyTarget?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
@@ -13,14 +12,8 @@ interface ProviderHealthBadgeProps {
|
||||
*/
|
||||
export function ProviderHealthBadge({
|
||||
consecutiveFailures,
|
||||
isProxyTarget,
|
||||
className,
|
||||
}: ProviderHealthBadgeProps) {
|
||||
// 如果代理目标已关闭但有失败记录,仍然显示(自动熔断场景)
|
||||
// 如果代理目标启用,始终显示
|
||||
// 如果代理目标关闭且无失败记录,隐藏
|
||||
if (!isProxyTarget && consecutiveFailures === 0) return null;
|
||||
|
||||
// 根据失败次数计算状态
|
||||
const getStatus = () => {
|
||||
if (consecutiveFailures === 0) {
|
||||
|
||||
@@ -5,12 +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 { useModelTest } from "@/hooks/useModelTest";
|
||||
import { useStreamCheck } from "@/hooks/useStreamCheck";
|
||||
import { ProviderCard } from "@/components/providers/ProviderCard";
|
||||
import { ProviderEmptyState } from "@/components/providers/ProviderEmptyState";
|
||||
|
||||
@@ -27,6 +26,7 @@ interface ProviderListProps {
|
||||
onCreate?: () => void;
|
||||
isLoading?: boolean;
|
||||
isProxyRunning?: boolean; // 代理服务运行状态
|
||||
isProxyTakeover?: boolean; // 代理接管模式(Live配置已被接管)
|
||||
}
|
||||
|
||||
export function ProviderList({
|
||||
@@ -42,38 +42,18 @@ export function ProviderList({
|
||||
onCreate,
|
||||
isLoading = false,
|
||||
isProxyRunning = false, // 默认值为 false
|
||||
isProxyTakeover = false, // 默认值为 false
|
||||
}: ProviderListProps) {
|
||||
const { sortedProviders, sensors, handleDragEnd } = useDragSort(
|
||||
providers,
|
||||
appId,
|
||||
);
|
||||
|
||||
// 模型测试
|
||||
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 { checkProvider, isChecking } = useStreamCheck(appId);
|
||||
|
||||
const handleTest = (provider: Provider) => {
|
||||
testProvider(provider.id, provider.name);
|
||||
checkProvider(provider.id, provider.name);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
@@ -120,10 +100,9 @@ export function ProviderList({
|
||||
onConfigureUsage={onConfigureUsage}
|
||||
onOpenWebsite={onOpenWebsite}
|
||||
onTest={handleTest}
|
||||
isTesting={isTesting(provider.id)}
|
||||
isTesting={isChecking(provider.id)}
|
||||
isProxyRunning={isProxyRunning}
|
||||
proxyPriority={proxyPriorityMap.get(provider.id)}
|
||||
allProviders={sortedProviders}
|
||||
isProxyTakeover={isProxyTakeover}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -145,8 +124,7 @@ interface SortableProviderCardProps {
|
||||
onTest: (provider: Provider) => void;
|
||||
isTesting: boolean;
|
||||
isProxyRunning: boolean;
|
||||
proxyPriority?: number; // 代理目标的实际优先级 (1, 2, 3...)
|
||||
allProviders?: Provider[]; // 所有供应商列表
|
||||
isProxyTakeover: boolean;
|
||||
}
|
||||
|
||||
function SortableProviderCard({
|
||||
@@ -162,8 +140,7 @@ function SortableProviderCard({
|
||||
onTest,
|
||||
isTesting,
|
||||
isProxyRunning,
|
||||
proxyPriority,
|
||||
allProviders,
|
||||
isProxyTakeover,
|
||||
}: SortableProviderCardProps) {
|
||||
const {
|
||||
setNodeRef,
|
||||
@@ -196,8 +173,7 @@ function SortableProviderCard({
|
||||
onTest={onTest}
|
||||
isTesting={isTesting}
|
||||
isProxyRunning={isProxyRunning}
|
||||
proxyPriority={proxyPriority}
|
||||
allProviders={allProviders}
|
||||
isProxyTakeover={isProxyTakeover}
|
||||
dragHandleProps={{
|
||||
attributes,
|
||||
listeners,
|
||||
|
||||
@@ -18,8 +18,11 @@ export interface AutoFailoverConfigPanelProps {
|
||||
|
||||
export function AutoFailoverConfigPanel({
|
||||
enabled,
|
||||
onEnabledChange,
|
||||
onEnabledChange: _onEnabledChange,
|
||||
}: AutoFailoverConfigPanelProps) {
|
||||
// Note: onEnabledChange is currently unused but kept in the interface
|
||||
// for potential future use by parent components
|
||||
void _onEnabledChange;
|
||||
const { t } = useTranslation();
|
||||
const { data: config, isLoading, error } = useCircuitBreakerConfig();
|
||||
const updateConfig = useUpdateCircuitBreakerConfig();
|
||||
@@ -77,11 +80,11 @@ export function AutoFailoverConfigPanel({
|
||||
|
||||
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
|
||||
{/* 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).
|
||||
*/}
|
||||
|
||||
@@ -262,7 +265,7 @@ export function AutoFailoverConfigPanel({
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={updateConfig.isPending || !formData.enabled}
|
||||
disabled={updateConfig.isPending || !enabled}
|
||||
>
|
||||
{updateConfig.isPending ? (
|
||||
<>
|
||||
|
||||
@@ -302,10 +302,9 @@ function ProviderQueueItem({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{/* 健康徽章:队列中的代理目标始终显示,没有健康数据时默认为正常 */}
|
||||
{/* 健康徽章 */}
|
||||
<ProviderHealthBadge
|
||||
consecutiveFailures={health?.consecutive_failures ?? 0}
|
||||
isProxyTarget={true}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* 代理模式切换开关组件
|
||||
*
|
||||
* 放置在主界面头部,用于一键启用/关闭代理模式
|
||||
* 启用时自动接管 Live 配置,关闭时恢复原始配置
|
||||
*/
|
||||
|
||||
import { Radio, Loader2 } from "lucide-react";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ProxyToggleProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ProxyToggle({ className }: ProxyToggleProps) {
|
||||
const {
|
||||
isRunning,
|
||||
isTakeoverActive,
|
||||
startWithTakeover,
|
||||
stopWithRestore,
|
||||
isPending,
|
||||
status,
|
||||
} = useProxyStatus();
|
||||
|
||||
const handleToggle = async (checked: boolean) => {
|
||||
if (checked) {
|
||||
await startWithTakeover();
|
||||
} else {
|
||||
await stopWithRestore();
|
||||
}
|
||||
};
|
||||
|
||||
const isActive = isRunning && isTakeoverActive;
|
||||
|
||||
const tooltipText = isActive
|
||||
? `代理模式运行中 - ${status?.address}:${status?.port}\n切换供应商为热切换`
|
||||
: "开启代理模式\n启用后自动接管 Live 配置";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 px-3 py-1.5 rounded-lg transition-all cursor-default",
|
||||
isActive
|
||||
? "bg-emerald-500/10 border border-emerald-500/30"
|
||||
: "bg-muted/50 hover:bg-muted",
|
||||
className,
|
||||
)}
|
||||
title={tooltipText}
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<Radio
|
||||
className={cn(
|
||||
"h-4 w-4 transition-colors",
|
||||
isActive
|
||||
? "text-emerald-500 animate-pulse"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm font-medium transition-colors select-none",
|
||||
isActive
|
||||
? "text-emerald-600 dark:text-emerald-400"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
Proxy
|
||||
</span>
|
||||
<Switch
|
||||
checked={isActive}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={isPending}
|
||||
className="ml-1"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -174,8 +174,8 @@ export function SettingsPage({
|
||||
|
||||
const {
|
||||
isRunning,
|
||||
start: startProxy,
|
||||
stop: stopProxy,
|
||||
startWithTakeover: startProxy,
|
||||
stopWithRestore: stopProxy,
|
||||
isPending: isProxyPending,
|
||||
} = useProxyStatus();
|
||||
const [failoverEnabled, setFailoverEnabled] = useState(true);
|
||||
|
||||
@@ -7,9 +7,9 @@ import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Save, Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
getModelTestConfig,
|
||||
saveModelTestConfig,
|
||||
type ModelTestConfig,
|
||||
getStreamCheckConfig,
|
||||
saveStreamCheckConfig,
|
||||
type StreamCheckConfig,
|
||||
} from "@/lib/api/model-test";
|
||||
|
||||
export function ModelTestConfigPanel() {
|
||||
@@ -17,12 +17,13 @@ export function ModelTestConfigPanel() {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [config, setConfig] = useState<ModelTestConfig>({
|
||||
const [config, setConfig] = useState<StreamCheckConfig>({
|
||||
timeoutSecs: 45,
|
||||
maxRetries: 2,
|
||||
degradedThresholdMs: 6000,
|
||||
claudeModel: "claude-haiku-4-5-20251001",
|
||||
codexModel: "gpt-5.1-low",
|
||||
geminiModel: "gemini-3-pro-low",
|
||||
testPrompt: "ping",
|
||||
timeoutSecs: 15,
|
||||
codexModel: "gpt-5.1-codex@low",
|
||||
geminiModel: "gemini-3-pro-preview",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -33,7 +34,7 @@ export function ModelTestConfigPanel() {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const data = await getModelTestConfig();
|
||||
const data = await getStreamCheckConfig();
|
||||
setConfig(data);
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
@@ -45,11 +46,11 @@ export function ModelTestConfigPanel() {
|
||||
async function handleSave() {
|
||||
try {
|
||||
setIsSaving(true);
|
||||
await saveModelTestConfig(config);
|
||||
toast.success(t("modelTest.configSaved", "模型测试配置已保存"));
|
||||
await saveStreamCheckConfig(config);
|
||||
toast.success(t("streamCheck.configSaved", "健康检查配置已保存"));
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
t("modelTest.configSaveFailed", "保存失败") + ": " + String(e),
|
||||
t("streamCheck.configSaveFailed", "保存失败") + ": " + String(e),
|
||||
);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
@@ -65,95 +66,126 @@ export function ModelTestConfigPanel() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-6">
|
||||
{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-4">
|
||||
<h4 className="text-sm font-medium text-muted-foreground">
|
||||
{t("streamCheck.testModels", "测试模型")}
|
||||
</h4>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="claudeModel">
|
||||
{t("streamCheck.claudeModel", "Claude 模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="claudeModel"
|
||||
value={config.claudeModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, claudeModel: e.target.value })
|
||||
}
|
||||
placeholder="claude-3-5-haiku-latest"
|
||||
/>
|
||||
</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="codexModel">
|
||||
{t("streamCheck.codexModel", "Codex 模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="codexModel"
|
||||
value={config.codexModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, codexModel: e.target.value })
|
||||
}
|
||||
placeholder="gpt-4o-mini"
|
||||
/>
|
||||
</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 className="space-y-2">
|
||||
<Label htmlFor="geminiModel">
|
||||
{t("streamCheck.geminiModel", "Gemini 模型")}
|
||||
</Label>
|
||||
<Input
|
||||
id="geminiModel"
|
||||
value={config.geminiModel}
|
||||
onChange={(e) =>
|
||||
setConfig({ ...config, geminiModel: e.target.value })
|
||||
}
|
||||
placeholder="gemini-1.5-flash"
|
||||
/>
|
||||
</div>
|
||||
</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-4">
|
||||
<h4 className="text-sm font-medium text-muted-foreground">
|
||||
{t("streamCheck.checkParams", "检查参数")}
|
||||
</h4>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="timeoutSecs">
|
||||
{t("streamCheck.timeout", "超时时间(秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="timeoutSecs"
|
||||
type="number"
|
||||
min={10}
|
||||
max={120}
|
||||
value={config.timeoutSecs}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
timeoutSecs: parseInt(e.target.value) || 45,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</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 className="space-y-2">
|
||||
<Label htmlFor="maxRetries">
|
||||
{t("streamCheck.maxRetries", "最大重试次数")}
|
||||
</Label>
|
||||
<Input
|
||||
id="maxRetries"
|
||||
type="number"
|
||||
min={0}
|
||||
max={5}
|
||||
value={config.maxRetries}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
maxRetries: parseInt(e.target.value) || 2,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="degradedThresholdMs">
|
||||
{t("streamCheck.degradedThreshold", "降级阈值(毫秒)")}
|
||||
</Label>
|
||||
<Input
|
||||
id="degradedThresholdMs"
|
||||
type="number"
|
||||
min={1000}
|
||||
max={30000}
|
||||
step={1000}
|
||||
value={config.degradedThresholdMs}
|
||||
onChange={(e) =>
|
||||
setConfig({
|
||||
...config,
|
||||
degradedThresholdMs: parseInt(e.target.value) || 6000,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { testProviderModel, type ModelTestResult } from "@/lib/api/model-test";
|
||||
import type { AppId } from "@/lib/api";
|
||||
|
||||
export function useModelTest(appId: AppId) {
|
||||
const { t } = useTranslation();
|
||||
const [testingIds, setTestingIds] = useState<Set<string>>(new Set());
|
||||
|
||||
const testProvider = useCallback(
|
||||
async (
|
||||
providerId: string,
|
||||
providerName: string,
|
||||
): Promise<ModelTestResult | null> => {
|
||||
setTestingIds((prev) => new Set(prev).add(providerId));
|
||||
|
||||
try {
|
||||
const result = await testProviderModel(appId, providerId);
|
||||
|
||||
if (result.success) {
|
||||
toast.success(
|
||||
t("modelTest.success", {
|
||||
name: providerName,
|
||||
time: result.responseTimeMs,
|
||||
defaultValue: `${providerName} 测试成功 (${result.responseTimeMs}ms)`,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
toast.error(
|
||||
t("modelTest.failed", {
|
||||
name: providerName,
|
||||
error: result.message,
|
||||
defaultValue: `${providerName} 测试失败: ${result.message}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
t("modelTest.error", {
|
||||
name: providerName,
|
||||
error: String(e),
|
||||
defaultValue: `${providerName} 测试出错: ${String(e)}`,
|
||||
}),
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setTestingIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(providerId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
[appId, t],
|
||||
);
|
||||
|
||||
const isTesting = useCallback(
|
||||
(providerId: string) => testingIds.has(providerId),
|
||||
[testingIds],
|
||||
);
|
||||
|
||||
return { testProvider, isTesting };
|
||||
}
|
||||
+83
-15
@@ -5,13 +5,16 @@
|
||||
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 } from "@/types/proxy";
|
||||
import { extractErrorMessage } from "@/utils/errorUtils";
|
||||
|
||||
/**
|
||||
* 代理服务状态管理
|
||||
*/
|
||||
export function useProxyStatus() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 查询状态(自动轮询)
|
||||
const { data: status, isLoading } = useQuery({
|
||||
@@ -23,27 +26,71 @@ export function useProxyStatus() {
|
||||
placeholderData: (previousData) => previousData,
|
||||
});
|
||||
|
||||
// 启动服务器
|
||||
const startMutation = useMutation({
|
||||
mutationFn: () => invoke<ProxyServerInfo>("start_proxy_server"),
|
||||
// 查询接管状态
|
||||
const { data: isTakeoverActive } = useQuery({
|
||||
queryKey: ["proxyTakeoverActive"],
|
||||
queryFn: () => invoke<boolean>("is_live_takeover_active"),
|
||||
});
|
||||
|
||||
// 启动服务器(带 Live 配置接管)
|
||||
const startWithTakeoverMutation = useMutation({
|
||||
mutationFn: () => invoke<ProxyServerInfo>("start_proxy_with_takeover"),
|
||||
onSuccess: (info) => {
|
||||
toast.success(`代理服务已启动 - ${info.address}:${info.port}`);
|
||||
toast.success(
|
||||
t("proxy.startedWithTakeover", {
|
||||
defaultValue: `代理模式已启用 - ${info.address}:${info.port}`,
|
||||
}),
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverActive"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`启动失败: ${error.message}`);
|
||||
const detail = extractErrorMessage(error) || "未知错误";
|
||||
toast.error(
|
||||
t("proxy.startWithTakeoverFailed", {
|
||||
defaultValue: `启动失败: ${detail}`,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// 停止服务器
|
||||
const stopMutation = useMutation({
|
||||
mutationFn: () => invoke("stop_proxy_server"),
|
||||
// 停止服务器(恢复 Live 配置)
|
||||
const stopWithRestoreMutation = useMutation({
|
||||
mutationFn: () => invoke("stop_proxy_with_restore"),
|
||||
onSuccess: () => {
|
||||
toast.success(
|
||||
t("proxy.stoppedWithRestore", {
|
||||
defaultValue: "代理模式已关闭,配置已恢复",
|
||||
}),
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyTakeoverActive"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const detail = extractErrorMessage(error) || "未知错误";
|
||||
toast.error(
|
||||
t("proxy.stopWithRestoreFailed", {
|
||||
defaultValue: `停止失败: ${detail}`,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
// 代理模式切换供应商(热切换)
|
||||
const switchProxyProviderMutation = useMutation({
|
||||
mutationFn: ({
|
||||
appType,
|
||||
providerId,
|
||||
}: {
|
||||
appType: string;
|
||||
providerId: string;
|
||||
}) => invoke("switch_proxy_provider", { appType, providerId }),
|
||||
onSuccess: () => {
|
||||
toast.success("代理服务已停止");
|
||||
queryClient.invalidateQueries({ queryKey: ["proxyStatus"] });
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(`停止失败: ${error.message}`);
|
||||
const detail = extractErrorMessage(error) || "未知错误";
|
||||
toast.error(`切换失败: ${detail}`);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -56,15 +103,36 @@ export function useProxyStatus() {
|
||||
}
|
||||
};
|
||||
|
||||
// 检查接管状态
|
||||
const checkTakeoverActive = async () => {
|
||||
try {
|
||||
return await invoke<boolean>("is_live_takeover_active");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
status,
|
||||
isLoading,
|
||||
isRunning: status?.running || false,
|
||||
start: startMutation.mutateAsync,
|
||||
stop: stopMutation.mutateAsync,
|
||||
isTakeoverActive: isTakeoverActive || false,
|
||||
|
||||
// 启动/停止(接管模式)
|
||||
startWithTakeover: startWithTakeoverMutation.mutateAsync,
|
||||
stopWithRestore: stopWithRestoreMutation.mutateAsync,
|
||||
|
||||
// 代理模式下切换供应商
|
||||
switchProxyProvider: switchProxyProviderMutation.mutateAsync,
|
||||
|
||||
// 状态检查
|
||||
checkRunning,
|
||||
isStarting: startMutation.isPending,
|
||||
isStopping: stopMutation.isPending,
|
||||
isPending: startMutation.isPending || stopMutation.isPending,
|
||||
checkTakeoverActive,
|
||||
|
||||
// 加载状态
|
||||
isStarting: startWithTakeoverMutation.isPending,
|
||||
isStopping: stopWithRestoreMutation.isPending,
|
||||
isPending:
|
||||
startWithTakeoverMutation.isPending || stopWithRestoreMutation.isPending,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
streamCheckProvider,
|
||||
type StreamCheckResult,
|
||||
} from "@/lib/api/model-test";
|
||||
import type { AppId } from "@/lib/api";
|
||||
|
||||
export function useStreamCheck(appId: AppId) {
|
||||
const { t } = useTranslation();
|
||||
const [checkingIds, setCheckingIds] = useState<Set<string>>(new Set());
|
||||
|
||||
const checkProvider = useCallback(
|
||||
async (
|
||||
providerId: string,
|
||||
providerName: string,
|
||||
): Promise<StreamCheckResult | null> => {
|
||||
setCheckingIds((prev) => new Set(prev).add(providerId));
|
||||
|
||||
try {
|
||||
const result = await streamCheckProvider(appId, providerId);
|
||||
|
||||
if (result.status === "operational") {
|
||||
toast.success(
|
||||
t("streamCheck.operational", {
|
||||
name: providerName,
|
||||
time: result.responseTimeMs,
|
||||
defaultValue: `${providerName} 运行正常 (${result.responseTimeMs}ms)`,
|
||||
}),
|
||||
);
|
||||
} else if (result.status === "degraded") {
|
||||
toast.warning(
|
||||
t("streamCheck.degraded", {
|
||||
name: providerName,
|
||||
time: result.responseTimeMs,
|
||||
defaultValue: `${providerName} 响应较慢 (${result.responseTimeMs}ms)`,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
toast.error(
|
||||
t("streamCheck.failed", {
|
||||
name: providerName,
|
||||
error: result.message,
|
||||
defaultValue: `${providerName} 检查失败: ${result.message}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (e) {
|
||||
toast.error(
|
||||
t("streamCheck.error", {
|
||||
name: providerName,
|
||||
error: String(e),
|
||||
defaultValue: `${providerName} 检查出错: ${String(e)}`,
|
||||
}),
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setCheckingIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(providerId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
[appId, t],
|
||||
);
|
||||
|
||||
const isChecking = useCallback(
|
||||
(providerId: string) => checkingIds.has(providerId),
|
||||
[checkingIds],
|
||||
);
|
||||
|
||||
return { checkProvider, isChecking };
|
||||
}
|
||||
+27
-52
@@ -1,89 +1,64 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { AppId } from "./types";
|
||||
|
||||
export interface ModelTestConfig {
|
||||
// ===== 流式健康检查类型 =====
|
||||
|
||||
export type HealthStatus = "operational" | "degraded" | "failed";
|
||||
|
||||
export interface StreamCheckConfig {
|
||||
timeoutSecs: number;
|
||||
maxRetries: number;
|
||||
degradedThresholdMs: number;
|
||||
claudeModel: string;
|
||||
codexModel: string;
|
||||
geminiModel: string;
|
||||
testPrompt: string;
|
||||
timeoutSecs: number;
|
||||
}
|
||||
|
||||
export interface ModelTestResult {
|
||||
export interface StreamCheckResult {
|
||||
status: HealthStatus;
|
||||
success: boolean;
|
||||
message: string;
|
||||
responseTimeMs?: number;
|
||||
httpStatus?: number;
|
||||
modelUsed: string;
|
||||
testedAt: number;
|
||||
retryCount: number;
|
||||
}
|
||||
|
||||
export interface ModelTestLog {
|
||||
id: number;
|
||||
providerId: string;
|
||||
providerName: string;
|
||||
appType: string;
|
||||
model: string;
|
||||
prompt: string;
|
||||
success: boolean;
|
||||
message: string;
|
||||
responseTimeMs?: number;
|
||||
httpStatus?: number;
|
||||
testedAt: number;
|
||||
}
|
||||
// ===== 流式健康检查 API =====
|
||||
|
||||
/**
|
||||
* 测试单个供应商的模型可用性
|
||||
* 流式健康检查(单个供应商)
|
||||
*/
|
||||
export async function testProviderModel(
|
||||
export async function streamCheckProvider(
|
||||
appType: AppId,
|
||||
providerId: string,
|
||||
): Promise<ModelTestResult> {
|
||||
return invoke("test_provider_model", { appType, providerId });
|
||||
): Promise<StreamCheckResult> {
|
||||
return invoke("stream_check_provider", { appType, providerId });
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量测试所有供应商
|
||||
* 批量流式健康检查
|
||||
*/
|
||||
export async function testAllProvidersModel(
|
||||
export async function streamCheckAllProviders(
|
||||
appType: AppId,
|
||||
proxyTargetsOnly: boolean = false,
|
||||
): Promise<Array<[string, ModelTestResult]>> {
|
||||
return invoke("test_all_providers_model", { appType, proxyTargetsOnly });
|
||||
): Promise<Array<[string, StreamCheckResult]>> {
|
||||
return invoke("stream_check_all_providers", { appType, proxyTargetsOnly });
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取模型测试配置
|
||||
* 获取流式检查配置
|
||||
*/
|
||||
export async function getModelTestConfig(): Promise<ModelTestConfig> {
|
||||
return invoke("get_model_test_config");
|
||||
export async function getStreamCheckConfig(): Promise<StreamCheckConfig> {
|
||||
return invoke("get_stream_check_config");
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存模型测试配置
|
||||
* 保存流式检查配置
|
||||
*/
|
||||
export async function saveModelTestConfig(
|
||||
config: ModelTestConfig,
|
||||
export async function saveStreamCheckConfig(
|
||||
config: StreamCheckConfig,
|
||||
): Promise<void> {
|
||||
return invoke("save_model_test_config", { config });
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取模型测试日志
|
||||
*/
|
||||
export async function getModelTestLogs(
|
||||
appType?: string,
|
||||
providerId?: string,
|
||||
limit?: number,
|
||||
): Promise<ModelTestLog[]> {
|
||||
return invoke("get_model_test_logs", { appType, providerId, limit });
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理旧的测试日志
|
||||
*/
|
||||
export async function cleanupModelTestLogs(
|
||||
keepCount?: number,
|
||||
): Promise<number> {
|
||||
return invoke("cleanup_model_test_logs", { keepCount });
|
||||
return invoke("save_stream_check_config", { config });
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface ProxyConfig {
|
||||
max_retries: number;
|
||||
request_timeout: number;
|
||||
enable_logging: boolean;
|
||||
live_takeover_active?: boolean;
|
||||
}
|
||||
|
||||
export interface ProxyStatus {
|
||||
|
||||
Reference in New Issue
Block a user